Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.ui/src/org')
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/Corext.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties24
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/SourceRange.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/ValidateEditException.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/ClasspathModifier.java1067
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/IBuildpathModifierListener.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchy.java229
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties13
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyVisitor.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallLocation.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallSearchResultCollector.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java313
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeMethodWrapper.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallerMethodWrapper.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/Implementors.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodCall.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodReferencesSearchRequestor.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodWrapper.java320
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java259
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java244
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddGetterSetterOperation.java357
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddImportsOperation.java406
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java197
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java285
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java244
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationSettings.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ContextSensitiveImportRewriteContext.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/GetterSetterUtil.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/IRequestQuery.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ImportReferencesCollector.java395
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/OrganizeImportsOperation.java546
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/SortMembersOperation.java258
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility.java1474
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility2.java696
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTFlattener.java1407
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodeFactory.java200
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodes.java805
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Bindings.java1014
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/BodyDeclarationRewrite.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/CodeScopeBuilder.java241
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/GenericVisitor.java659
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/HierarchicalASTVisitor.java789
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/JdtASTMatcher.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LinkedNodeFinder.java280
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LocalVariableIndex.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ModifierRewrite.java139
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/NodeFinder.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ReplaceRewrite.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ScopeAnalyzer.java787
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Selection.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/SelectionAnalyzer.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/StatementRewrite.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TokenScanner.java450
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeBindingVisitor.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeRules.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/VariableDeclarationRewrite.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragment.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragmentFactory.java192
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTMatchingFragmentFinder.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/AssociativeInfixExpressionFragment.java437
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IASTFragment.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IExpressionFragment.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleExpressionFragment.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleFragment.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/Util.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/AbstractFix.java140
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java1246
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPostSaveListener.java379
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPreferenceUtil.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpRefactoring.java1057
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CodeStyleFix.java705
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ControlStatementsFix.java485
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertForLoopOperation.java639
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertIterableLoopOperation.java562
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopFix.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopOperation.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ExpressionsFix.java377
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFix.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFixRewriteOperation.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ILinkedFixRewriteOperation.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ImportsFix.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedFix.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalModel.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalPositionGroup.java184
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/SortMembersFix.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/StringFix.java229
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/UnusedCodeFix.java637
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/VariableDeclarationFix.java535
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocLocations.java582
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/AbstractJavaElementRenameChange.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/Checks.java829
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CollectingSearchRequestor.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CuCollectingSearchRequestor.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ExceptionInfo.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringContribution.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptor.java338
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptorComment.java300
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ParameterInfo.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringAvailabilityTester.java1124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringCoreMessages.java2350
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringElementFilter.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringExecutionStarter.java467
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringScopeFactory.java272
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine.java229
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine2.java726
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ReturnTypeInfo.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/SearchResultGroup.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/StubTypeContext.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypeContextChecker.java753
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypedSource.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JDTChange.java260
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStatusContext.java272
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStringStatusContext.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/RefactoringStatusCodes.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/AbstractCodeCreationOperation.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreator.java255
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AbstractDeleteChange.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AddToClasspathChange.java128
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitChange.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitReorgChange.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyCompilationUnitChange.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageChange.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageFragmentRootChange.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyResourceChange.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreateCompilationUnitChange.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreatePackageChange.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFileChange.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFolderChange.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFromClasspathChange.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeletePackageFragmentRootChange.java170
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteSourceManipulationChange.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationRefactoringChange.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationStateChange.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveCompilationUnitChange.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageChange.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageFragmentRootChange.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveResourceChange.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MultiStateCompilationUnitChange.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageReorgChange.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameCompilationUnitChange.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameJavaProjectChange.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenamePackageChange.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameResourceChange.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/ResourceReorgChange.java153
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/TextChangeCompatibility.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoDeleteResourceChange.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoablePackageDeleteChange.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/Utils.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/WorkspaceTracker.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/AstMatchingNodeFinder.java594
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallContext.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallInliner.java833
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CodeRefactoringUtil.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConstantChecks.java194
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java1032
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExceptionAnalyzer.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java831
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java719
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java993
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java1007
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineConstantRefactoring.java970
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineMethodRefactoring.java566
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineTempRefactoring.java437
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java1238
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java1275
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java575
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/Invocations.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/NameCollector.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/OperatorPrecedence.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ParameterData.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java929
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ReplaceInvocationsRefactoring.java554
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ScriptableRefactoring.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SnippetFinder.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceAnalyzer.java465
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceProvider.java637
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TargetProvider.java431
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TempAssignmentFinder.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BlockFlowInfo.java19
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BranchFlowInfo.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ConditionalFlowInfo.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/DoWhileFlowInfo.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/EnhancedForFlowInfo.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java889
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowContext.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowInfo.java515
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ForFlowInfo.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericConditionalFlowInfo.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericSequentialFlowInfo.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/IfFlowInfo.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InOutFlowAnalyzer.java126
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java299
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/MessageSendFlowInfo.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/SwitchFlowInfo.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ThrowFlowInfo.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TryFlowInfo.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TypeVariableFlowInfo.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WhileFlowInfo.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WithFlowInfo.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateCreator.java460
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateFieldCreator.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateMethodCreator.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassCreator.java331
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassModifier.java281
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassReference.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/KeyValuePair.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHint.java304
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHintHelper.java454
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSLine.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSPropertyFileModifier.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSRefactoring.java527
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSScanner.java166
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSourceModifier.java333
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java331
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSUtil.java209
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/PropertyFileDocumentModel.java327
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/SimpleLineReader.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateFileChange.java218
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateTextFileChange.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/DeleteFileChange.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties16
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/JavaProcessors.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/RefactoringProcessors.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java352
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceProcessors.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties1354
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/GenericRefactoringHandleTransplanter.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameProcessor.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodChecks.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java230
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringScanner.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java453
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameCompilationUnitProcessor.java464
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameFieldProcessor.java907
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameJavaProjectProcessor.java227
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java440
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java883
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameModifications.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameNonVirtualMethodProcessor.java235
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamePackageProcessor.java1073
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameResourceProcessor.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameSourceFolderProcessor.java203
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameTypeProcessor.java1702
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameVirtualMethodProcessor.java217
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamingNameSuggestor.java570
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RippleMethodFinder2.java358
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempDeclarationFinder.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempOccurrenceAnalyzer.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TextMatchUpdater.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TypeOccurrenceCollector.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/todo.txt3
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ASTNodeDeleteUtil.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ArrayTypeConverter.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CopyModifications.java159
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateCopyOfCompilationUnitChange.java208
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteChangeCreator.java229
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteModifications.java240
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IConfirmQuery.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQueries.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQuery.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQueries.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQuery.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IPackageFragmentRootManipulationQuery.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgDestinationValidator.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgPolicy.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgQueries.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyProcessor.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteProcessor.java884
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaElementTransfer.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaMoveProcessor.java312
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetChange.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetQueries.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedNewNameQueries.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringNewNameQueries.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java420
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveModifications.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/OverwriteHelper.java228
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ParentChecker.java192
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReadOnlyResourceFinder.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/RefactoringModifications.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java3474
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgUtils.java603
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/SourceReferenceUtil.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractConstantRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractTempRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineMethodRefactoringContribution.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameCompilationUnitRefactoringContribution.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameFieldRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameJavaProjectRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameLocalVariableRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameMethodRefactoringContribution.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenamePackageRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameResourceRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameSourceFolderRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameTypeRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/AccessAnalyzer.java316
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java823
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ASTNodeSearchUtil.java237
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/BodyUpdater.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java2623
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java1419
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/CompilationUnitRewrite.java323
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ConstructorReferenceFinder.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractInterfaceConstraintsSolver.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeProcessor.java1110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/HierarchyProcessor.java634
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IDefaultValueAdvisor.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IMemberActionInfo.java14
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRemover.java232
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRewriteUtil.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberCheckUtil.java161
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberVisibilityAdjustor.java1331
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java1488
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodProcessor.java2980
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodRefactoring.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMemberAnalyzer.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java1035
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MovedMemberAnalyzer.java189
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoring.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java1862
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoring.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java993
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceAnalyzer.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/TypeVariableMaplet.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeProcessor.java460
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeRefactoring.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/ConditionalTypeConstraint.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/CovariantTypeConstraint.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java758
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsModel.java564
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsSolver.java279
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java1250
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeSet.java287
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ISurroundWithTryCatchQuery.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/LocalDeclarationAnalyzer.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithAnalyzer.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java361
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/INameUpdating.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IQualifiedNameUpdating.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IReferenceUpdating.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ITextUpdating.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ASTCreator.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompilationUnitRange.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompositeOrTypeConstraint.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCollector.java622
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCreator.java533
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintOperator.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariable.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariableFactory.java258
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/DeclaringTypeVariable.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ExpressionVariable.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/FullConstraintCreator.java675
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IConstraintVariableFactory.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IContext.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraint.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraintFactory.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/NullContext.java16
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ParameterTypeVariable.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/RawBindingVariable.java21
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ReturnTypeVariable.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/SimpleTypeConstraint.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeConstraintFactory.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeVariable.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/AbstractTypeVariable.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/ArrayType.java159
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/CaptureType.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/GenericType.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/HierarchyType.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/NullType.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/PrimitiveType.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/RawType.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/StandardType.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TType.java574
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeEnvironment.java367
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeTuple.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/UnboundWildcardType.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/VoidType.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/WildcardType.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArraySuperTypeSet.java197
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArrayTypeSet.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EmptyTypeSet.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EnumeratedTypeSet.java488
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SingletonTypeSet.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesOfSingleton.java265
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesSet.java300
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesOfSingleton.java253
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesSet.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSet.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetEnvironment.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetIntersection.java321
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetUnion.java152
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeUniverseSet.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayElementVariable2.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayTypeVariable2.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CastVariable2.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CollectionElementVariable2.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ConstraintVariable2.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ISourceConstraintVariable.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraint2.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraintVariable.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeSet.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ImmutableTypeVariable2.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/IndependentTypeVariable2.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterTypeVariable2.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterizedTypeVariable2.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ReturnTypeVariable2.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/SubTypeConstraint2.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TTypes.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeEquivalenceSet.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/VariableVariable2.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/Changes.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CodeAnalyzer.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CommentAnalyzer.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavaElementUtil.java240
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavadocUtil.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/NoCommentSourceRangeComputer.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameFinder.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameSearchResult.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringASTParser.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringFileBuffers.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/ResourceUtil.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/SelectionAwareSourceRangeComputer.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/StatementAnalyzer.java272
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextChangeManager.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextEditBasedChangeManager.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TightSourceRangeComputer.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContext.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java353
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplates.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java700
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContext.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContextType.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java603
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContextType.java350
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContext.java218
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContextType.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaFormatter.java354
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/SignatureUtil.java150
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java376
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/Templates.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java383
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java311
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java398
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java947
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java228
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java373
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java419
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java433
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java259
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/CompatibilityTemplateStore.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/EditorInputAdapterFactory.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaHelpContextIds.java440
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaThemeConstants.java152
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJsGlobalScopeContainerInitializerExtension.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IProductConstants.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IResourceLocator.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IUIConstants.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/InitializeAfterLoadJob.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementAdapterFactory.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementContainmentAdapter.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementProperties.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java595
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaProjectAdapterFactory.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java927
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIException.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIPreferenceInitializer.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIStatus.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaWorkbenchAdapter.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java156
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/LogicalPackageAdapterFactory.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/MarkerAdapterFactory.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/PersistableJavaElementFactory.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceAdapterFactory.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceLocator.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SetupProjectsWizzard.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SharedImages.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.java376
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties412
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionUtil.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddBlockCommentAction.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddTaskAction.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AllCleanUpsAction.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java327
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CategoryFilterActionGroup.java530
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CleanUpAction.java287
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CompositeActionGroup.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CopyQualifiedNameAction.java269
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ExtractSuperClassAction.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FindBrokenNLSKeysAction.java358
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingActionGroup.java246
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsContentProvider.java201
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsSelectionDialog.java352
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsValidator.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateJavadocAction.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/IndentAction.java570
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/JDTQuickMenuAction.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/LexicalSortingAction.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiActionGroup.java126
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiOrganizeImportAction.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiSortMembersAction.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/NewWizardsActionGroup.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OccurrencesSearchMenuAction.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenBrowserUtil.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeAction.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeInHierarchyAction.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java300
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/RemoveBlockCommentAction.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectAllAction.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java310
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithActionGroup.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithTemplateMenuAction.java412
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/WorkbenchRunnableAdapter.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingContentProvider.java537
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties24
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPart.java1315
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java180
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaElementTypeComparator.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackage.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackagesProvider.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/MembersView.java336
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackageViewerWrapper.java343
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesView.java653
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewFlatContentProvider.java300
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewHierarchicalContentProvider.java646
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewLabelProvider.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTableViewer.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTreeViewer.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PatchedOpenInNewWindowAction.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectAndSourceFolderContentProvider.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectsView.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TypesView.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyContentProvider.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyFiltersActionGroup.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyImageDescriptor.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelDecorator.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelProvider.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyTransferDropAdapter.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyUI.java276
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewPart.java948
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewer.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CancelSearchAction.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CopyCallHierarchyAction.java128
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/DeferredMethodWrapper.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FiltersDialog.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FocusOnSelectionAction.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryAction.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryDropDownAction.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryListAction.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ICallHierarchyViewPart.java19
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationCopyAction.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationLabelProvider.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationViewer.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/MethodWrapperWorkbenchAdapter.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenCallHierarchyAction.java239
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenDeclarationAction.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenLocationAction.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/RefreshAction.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeAction.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeActionGroup.java355
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeHierarchyAction.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeProjectAction.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkingSetAction.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkspaceAction.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchUtil.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SelectWorkingSetAction.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleCallModeAction.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleOrientationAction.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeRoot.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeTermination.java17
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/JavaElementReferenceConverter.java233
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/OpenElementInEditorHandler.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInPackageViewHandler.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInTypeHierarchyViewHandler.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareDialog.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java317
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistory.java22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistoryImpl.java304
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareAction.java183
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareUtilities.java454
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionAction.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionActionImpl.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaContentViewerCreator.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaElementHistoryPageSource.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryAction.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryActionImpl.java334
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaMergeViewer.java423
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaNode.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaParseTreeBuilder.java205
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionAction.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionActionImpl.java212
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithPreviousEditionAction.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureCreator.java501
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewer.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewerCreator.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextBufferNode.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewer.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewerCreator.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java225
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/LocalHistoryActionGroup.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ResizableDialog.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/TextMergeViewerCreator.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java1650
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/ListDialog.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/MultiElementListSelectionDialog.java323
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog2.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OptionalMessageDialog.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java391
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/PackageSelectionDialog.java321
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SortMembersMessageDialog.java186
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SourceActionDialog.java655
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusInfo.java196
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusUtil.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TableTextCellEditor.java437
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TextFieldNavigationHandler.java505
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java1583
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionComponent.java437
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java332
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDragAdapter.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDropAdapter.java268
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDragAdapter.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDropAdapter.java295
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/ResourceTransferDragAdapter.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClassFilter.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClosedProjectFilter.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ContainedLibraryFilter.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java417
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyInnerPackageFilter.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyPackageFilter.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterDescriptor.java277
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties23
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ImportDeclarationFilter.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/JavaFileFilter.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LocalTypesFilter.java24
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NamePatternFilter.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NoPackageContainingFoldersFilter.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonJavaElementFilter.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicTypeFilter.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonSharedProjectFilter.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/AbstractCleanUp.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpRefactoringWizard.java494
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantConfigurationModifyDialog.java285
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantPreferenceConfiguration.java345
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatCleanUp.java118
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatFix.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeStyleCleanUp.java237
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatCleanUp.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatFix.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ControlStatementsCleanUp.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ConvertLoopCleanUp.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ExpressionsCleanUp.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ICleanUp.java175
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ImportsCleanUp.java145
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SortMembersCleanUp.java175
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/StringCleanUp.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnnecessaryCodeCleanUp.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/VariableDeclarationCleanUp.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java572
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/CopyToClipboardAction.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/GotoInputAction.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java703
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/SourceView.java518
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/TextSelectionConverter.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CheckboxTreeAndListGroup.java804
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CreateJavadocActionDelegate.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocConsoleLineTracker.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties119
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkDialogLabelProvider.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkRef.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocMemberContentProvider.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocOptionsManager.java1158
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocProjectContentProvider.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocReader.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java302
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocStandardWizardPage.java573
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocTreeWizardPage.java706
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizard.java456
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizardPage.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWriter.java310
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/RecentSettingsStore.java277
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java672
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddClassFileMarkerAction.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddImportOnSelectionAction.java245
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicJavaEditorActionContributor.java230
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileDocumentProvider.java388
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditor.java871
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorActionContributor.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorInputFactory.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerAnnotationModel.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerRulerAction.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClipboardOperationAction.java507
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitAnnotationModelEvent.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java1566
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java1739
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditorActionContributor.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompoundEditExitStrategy.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties218
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/DocumentAdapter.java524
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java633
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ExternalClassFileEditorInput.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/GotoMatchingBracketAction.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IClassFileEditorInput.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompilationUnitDocumentProvider.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaAnnotation.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaEditorActionConstants.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ISavePolicy.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IndentUtil.java476
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java129
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JarEntryEditorInput.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java165
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaDocumentSetupParticipant.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java3630
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorErrorTickUpdater.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMarkerAnnotation.java159
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMoveLinesAction.java481
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java1401
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectAnnotationRulerAction.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectMarkerRulerAction2.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectRulerAction.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSourceViewer.java630
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaTextSelection.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlink.java184
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlinkDetector.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorManager.java248
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlighting.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingManager.java627
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingPresenter.java772
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java469
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightings.java1665
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticToken.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistAction.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/StorageMarkerAnnotationModel.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleCommentAction.java318
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleMarkOccurrencesAction.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/TogglePresentationAction.java149
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleTextHoverAction.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/WorkingCopyManager.java129
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/AbstractSaveParticipantPreferenceConfiguration.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/IPostSaveListener.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties12
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantRegistry.java160
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/GoToNextPreviousMemberAction.java241
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionHistory.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectEnclosingAction.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectHistoryAction.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectNextAction.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectPreviousAction.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectionAction.java170
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelContentProvider.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelLabelProvider.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelMerger.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelProvider.java80
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationCompareAdapter.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationContentProvider.java808
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationLabelProvider.java173
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties12
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/ContainerFolder.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/IExtensionStateConstants.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaDropAdapterAssistant.java252
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaFileLinkHelper.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorActionProvider.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java343
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorRefactorActionProvider.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorViewActionProvider.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialElementsFilter.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyInnerPackageFilter.java21
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyPackageFilter.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/OpenAndExpand.java264
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CollapseAllAction.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CustomHashtable.java403
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/DefaultElementComparer.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDragAdapter.java240
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDropAdapter.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoPackageAction.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoResourceAction.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoTypeAction.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/HierarchicalDecorationContext.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/IMultiElementTreeContentProvider.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/JsGlobalScopeContainer.java188
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java112
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/NamespaceGroup.java314
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerActionGroup.java393
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java1533
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java166
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java1604
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerProblemsDecorator.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageFragmentRootContainer.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesFrameSource.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDragAdapter.java21
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDropAdapter.java244
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java246
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareJavaElementSorter.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetDropAdapter.java262
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java469
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferenceAndPropertyPage.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java235
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java269
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BulletListBlock.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CleanUpPreferencePage.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedConfigurationBlock.java768
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedPreferencePage.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistConfigurationBlock.java420
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java464
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreviewCode.txt44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeStylePreferencePage.java126
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateBlock.java580
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplatePreferencePage.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateSourceViewerConfiguration.java159
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ComplianceConfigurationBlock.java617
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CompliancePreferencePage.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/EditTemplateDialog.java608
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingConfigurationBlock.java377
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingPreferencePage.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java508
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeInputDialog.java240
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizePreferencePage.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBasePreferencePage.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java310
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildPreferencePage.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaCategoryPropertyPage.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java433
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java960
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringPreferencePage.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java580
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverPreferencePage.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPreferencePage.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPropertyPage.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaElementInfoPage.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaPreferencesSettings.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaScriptMainPage.java60
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaTemplatePreferencePage.java164
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java920
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java254
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java266
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsPreferencePage.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java267
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferenceCache.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferencePage.java409
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java273
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NameConventionConfigurationBlock.java513
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NewJavaProjectPreferencePage.java519
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OccurrencesPreferencePage.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OptionsConfigurationBlock.java881
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java486
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesAccess.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.java780
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties911
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesConfigurationBlock.java606
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesPreferencePage.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProfilePreferencePage.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProjectSelectionDialog.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertiesFileEditorColorSettingPreviewCode.txt5
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertyAndPreferencePage.java339
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantConfigurationBlock.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantPreferencePage.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ScrolledPageContent.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingConfigurationBlock.java263
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingPreferencePage.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SourceAttachmentPropertyPage.java212
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskConfigurationBlock.java369
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskInputDialog.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskPreferencePage.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterInputDialog.java150
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterPreferencePage.java280
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/UserLibraryPreferencePage.java1311
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/WorkInProgressPreferencePage.java165
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpConfigurationBlock.java269
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpModifyDialog.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpPreview.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileManager.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileVersioner.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpTabPage.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeFormatingTabPage.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/UnnecessaryCodeTabPage.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/AlreadyExistsDialog.java208
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BlankLinesTabPage.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CodeFormatterConfigurationBlock.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CommentsTabPage.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CompilationUnitPreview.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ControlStatementsTabPage.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CreateProfileDialog.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.java498
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties561
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterModifyDialog.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileManager.java128
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileStore.java144
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterTabPage.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IProfileVersioner.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IndentationTabPage.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/JavaPreview.java216
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/LineWrappingTabPage.java893
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialog.java389
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialogTabPage.java817
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/NewLinesTabPage.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileConfigurationBlock.java452
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileManager.java795
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileStore.java342
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileVersioner.java687
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/SnippetPreview.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java1261
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceTabPage.java475
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionHandler.java160
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionsControl.java317
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeParametersControl.java732
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeSignatureWizard.java396
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeContentProvider.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeWizard.java371
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ComboSelectionDialog.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CompilationUnitChangeNode.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ConvertAnonymousToNestedWizard.java152
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CreateTextFileChangePreviewViewer.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/DelegateUIHelper.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractConstantWizard.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMemberPage.java563
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMethodPage.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractTempWizard.java172
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IExceptionListChangeListener.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IParameterListChangeListener.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IScheduledRefactoring.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IVisibilityChangeListener.java15
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineConstantWizard.java143
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineTempWizard.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryInputPage.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryWizard.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionInputPage.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceParameterWizard.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/JavaStatusContextViewer.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MessageWizardPage.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInnerToTopWizard.java184
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInstanceMethodWizard.java339
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveMembersWizard.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ParameterEditDialog.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PromoteTempWizard.java234
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullPushCheckboxTableViewer.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMemberPage.java972
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMethodPage.java562
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpWizard.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PushDownWizard.java599
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/QualifiedNameComponent.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringAdapterFactory.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringExecutionHelper.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringMessages.java968
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSaveHelper.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSavePreferences.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/TextInputWizardPage.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UseSupertypeWizard.java320
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceManager.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceStarter.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/VisibilityControlUtil.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ApplyRefactoringScriptAction.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/CreateRefactoringScriptAction.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineConstantAction.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineMethodAction.java149
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ListDialog.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveInstanceMethodAction.java144
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveStaticMembersAction.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringActions.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringStarter.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameJavaElementAction.java215
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameResourceAction.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ShowRefactoringHistoryAction.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/binary/BinaryRefactoringHistoryWizard.java731
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodInputPage.java407
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodWizard.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodInputPage.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodWizard.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsInputPage.java152
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java260
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CompletionContextRequestor.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/ControlContentAssistHelper.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/FieldNameProcessor.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageCompletionProcessor.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageFragmentRootCompletionProcessor.java150
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaSourcePackageFragmentRootCompletionProcessor.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java194
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/VariableNamesProcessor.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/AccessorDescription.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizard.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java1332
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/MultiStateCellEditor.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSAccessorConfigurationDialog.java442
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageBrowseAdapter.java144
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageFragmentSelection.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionDialogButtonField.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionStringButtonAdapter.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/RenameKeysDialog.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceChangeListener.java18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceContainerDialog.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFirstPackageSelectionDialogField.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFolderSelectionDialogButtonField.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/CompilationUnitEntry.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/FileEntry.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/LineReader.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchEditorOpener.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchQuery.java185
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResult.java234
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultLabelProvider2.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultPage.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java377
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/Properties.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/SearchBrokenNLSKeysUtil.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties618
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CopyToClipboardAction.java357
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CreateTargetQueries.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CutAction.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteAction.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteUserInterfaceManager.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteWizard.java287
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DestinationContentProvider.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/NewNameQueries.java213
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/PasteAction.java1141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameCuWizard.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameFieldWizard.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInformationPopup.java822
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInputWizardPage.java313
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameJavaProjectWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java610
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLocalVariableWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodUserInterfaceStarter.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenamePackageWizard.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameRefactoringWizard.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameResourceWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSelectionState.java140
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSourceFolderWizard.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeParameterWizard.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizard.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java192
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java165
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsPage.java778
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceManager.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceStarter.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyAction.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyStarter.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyWizard.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties176
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveAction.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveStarter.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveWizard.java262
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgQueries.java418
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgUserInputPage.java146
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/TypedSourceTransfer.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldInputPage.java330
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldWizard.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/BreakContinueTargetFinder.java281
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesFinder.java252
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesGroupKey.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/FindOccurrencesEngine.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/GroupAction.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/IOccurrencesFinder.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ImplementOccurrencesFinder.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementLine.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementMatch.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaMatchFilter.java507
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchContentProvider.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchEditorOpener.java151
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPage.java976
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPageScoreComputer.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java261
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResult.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResultPage.java547
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchScopeFactory.java436
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchTableContentProvider.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LRUWorkingSetsList.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LevelTreeContentProvider.java251
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/MethodExitsFinder.java254
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchResultCollector.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchViewActionGroup.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesFinder.java295
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesGroupKey.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchLabelProvider.java47
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchQuery.java108
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResult.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResultPage.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OpenJavaSearchPageAction.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PatternStrings.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PostfixLabelProvider.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchLabelProvider.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.java250
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties312
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantDescriptor.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantRecord.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantsExtensionPoint.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchResultUpdater.java159
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchUtil.java236
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortAction.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortingLabelProvider.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchLabelProvider.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchTableContentProvider.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetComparator.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetsComparator.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractInformationControl.java775
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java356
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/BufferedDocumentScanner.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ChangeHoverInformationControl.java222
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java371
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ContentAssistPreference.java233
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java222
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java560
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ISourceVersionDependent.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java420
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCodeReader.java239
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCommentScanner.java294
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCompositeReconcilingStrategy.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaElementProvider.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaHeuristicScanner.java950
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaIndenter.java1649
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java755
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPairMatcher.java155
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPartitionScanner.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaReconciler.java416
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWhitespaceDetector.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordDetector.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordFinder.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/LineBreakingReader.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/PreferencesAdapter.java330
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SimpleJavaSourceViewerConfiguration.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SingleTokenJavaScanner.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java275
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java469
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingStrategy.java373
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTResolving.java930
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTRewriteCorrectionProposal.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AbstractMethodCompletionProposal.java200
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddArgumentCorrectionProposal.java127
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddImportCorrectionProposal.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java2172
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssignToVariableAssistProposal.java342
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssistContext.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CUCorrectionProposal.java584
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeCorrectionProposal.java280
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeMethodSignatureProposal.java481
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java230
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ContributedProcessorDescriptor.java137
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectMainTypeNameProposal.java81
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandHandler.java156
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandInstaller.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java590
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties353
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/FixCorrectionProposal.java201
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ICommandAccess.java26
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/IStatusLineProposal.java30
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionAssistant.java329
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java513
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavadocTagsSubProcessor.java517
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedCorrectionProposal.java95
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedNamesAssistProposal.java288
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java896
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MarkerResolutionProposal.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java1073
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NameMatcher.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java395
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewDefiningMethodProposal.java119
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewMethodCompletionProposal.java239
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewVariableCompletionProposal.java483
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ProblemLocation.java174
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.java281
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistProcessor.java1366
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickFixProcessor.java449
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickTemplateProcessor.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RemoveDeclarationCorrectionProposal.java237
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RenameNodeCompletionProposal.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java512
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReplaceCorrectionProposal.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReturnTypeSubProcessor.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElement.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElementsRequestor.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SurroundWith.java563
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TaskMarkerProposal.java152
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeChangeCompletionProposal.java161
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeMismatchSubProcessor.java294
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java1464
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java153
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties22
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java139
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java591
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTML2TextReader.java330
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties16
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java306
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java315
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SingleCharReader.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SubstitutionTextReader.java162
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java1035
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java261
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeProposalInfo.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalCategory.java327
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java547
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java388
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistHistory.java481
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistProcessor.java559
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java68
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FilledArgumentNamesMethodProposal.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/GetterSetterCompletionProposal.java144
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IJavaReconcilingListener.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IReconcilingParticipant.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ImportCompletionProposal.java206
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaAutoIndentStrategy.java1362
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCodeScanner.java561
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProcessor.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposalComputer.java245
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaDoubleClickSelector.java340
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaFormattingStrategy.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java222
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaNoTypeCompletionProposalComputer.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaParameterListValidator.java318
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaReconcilingStrategy.java191
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringAutoIndentStrategy.java199
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringDoubleClickSelector.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java190
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java249
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyGenericTypeProposal.java455
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java428
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java372
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodDeclarationCompletionProposal.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java217
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/OverrideCompletionProposal.java174
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuesser.java654
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuessingProposal.java318
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalContextInformation.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterHandle.java280
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterRegistry.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java1012
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TemplateCompletionProposalComputer.java208
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TypeProposalInfo.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractAnnotationHover.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpandHover.java308
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpansionControl.java844
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java130
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java293
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java205
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties23
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaInformationProvider.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaSourceHover.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaTypeHover.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java233
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/NLSStringHover.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/SourceViewerInformationControl.java458
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/HTMLTagCompletionProposalComputer.java250
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDoc2HTMLTextReader.java371
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java435
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties18
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocScanner.java214
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProcessor.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProposalComputer.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocInlineTagCompletionProposal.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocLinkTypeCompletionProposal.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/LegacyJavadocCompletionProposalComputer.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/OAADocReader.java121
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/JavaSpellingReconcileStrategy.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/SpellingQuickFixProcessor.java228
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java615
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java683
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java375
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java126
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java29
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java59
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java102
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java283
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java197
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/SurroundWithTemplateProposal.java267
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java32
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties17
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateEngine.java164
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateProposal.java537
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/VariablePosition.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateContentProvider.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties12
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProposal.java114
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/AbstractHierarchyViewerSorter.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/EnableMemberFilterAction.java51
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnSelectionAction.java70
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnTypeAction.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyInformationControl.java369
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyLabelProvider.java182
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyViewerSorter.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryAction.java58
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryDropDownAction.java105
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryListAction.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ITypeHierarchyLifeCycleListener.java27
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsContentProvider.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsLabelProvider.java147
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java313
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowInheritedMembersAction.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowQualifiedTypeNamesAction.java50
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SortByDefiningTypeAction.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SubTypeHierarchyViewer.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SuperTypeHierarchyViewer.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleOrientationAction.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleViewAction.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java151
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java353
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java274
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties109
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyTransferDropAdapter.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java1646
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewer.java194
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/BusyIndicatorRunnableContext.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java262
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java196
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ElementValidator.java203
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ExceptionHandler.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JSDScopeUiUtil.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavaUIHelp.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavadocHelpContext.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/OpenTypeHierarchyUtil.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PatternConstructor.java129
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PixelConverter.java28
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/RowLayouter.java184
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SWTUtil.java109
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SelectionUtil.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/StringMatcher.java384
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java186
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TypeNameMatchLabelProvider.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ViewerPane.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/BindingLabelProvider.java424
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredJavaElementLabels.java895
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredString.java173
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredViewersManager.java218
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/FilterUpdater.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryDropDownAction.java153
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryListAction.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IProblemChangedListener.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IRichLabelProvider.java19
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ISelectionListenerWithAST.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IViewPartInputProvider.java25
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDescriptorRegistry.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDisposer.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageImageDescriptor.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java399
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaUILabelProvider.java278
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaViewerFilter.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LabelProviderDisposer.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LibraryFilter.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilter.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilterAction.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/OwnerDrawSupport.java163
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemMarkerManager.java180
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTableViewer.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTreeViewer.java328
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProjectTemplateStore.java172
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ResourceToItemsMapper.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java211
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionProviderMediator.java206
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SourcePositionComparator.java113
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StatusBarUpdater.java106
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StorageLabelProvider.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/TreeHierarchyLayoutProblemsDecorator.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ViewHistory.java103
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/ClassPathDetector.java238
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/IStatusChangeListener.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizard.java188
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java725
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardSecondPage.java462
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewClassCreationWizard.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewElementWizard.java168
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java274
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewSourceFolderWizardPage.java510
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.java683
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties901
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedElementSelectionValidator.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java64
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRuleEntryDialog.java173
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesDialog.java361
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesLabelProvider.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizardPage.java732
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ArchiveFileFilter.java110
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathBasePage.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathSupport.java303
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java104
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java1016
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java828
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementAttribute.java148
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java360
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java165
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathAttributeConfigurationDescriptors.java122
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathOrderingWorkbookPage.java233
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java298
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java62
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionDialog.java314
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionEntryDialog.java285
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/FolderSelectionDialog.java115
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JARFileSelectionDialog.java186
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocAttributeConfiguration.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocLocationDialog.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDefaultPage.java142
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDescriptor.java131
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerWizard.java198
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java863
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/MultipleFolderSelectionDialog.java312
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewContainerDialog.java158
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewSourceFolderDialog.java194
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java473
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SetFilterWizardPage.java333
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java583
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentDialog.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java918
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryMarkerResolutionGenerator.java254
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java326
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java226
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java189
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierDropDownAction.java178
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java342
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java117
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction2.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java120
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction2.java36
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java451
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java292
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ExcludeFromBuildpathAction.java175
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HelpAction.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java318
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/IncludeToBuildpathAction.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/LinkFolderDialog.java515
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java334
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveFromBuildpathAction.java263
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveLinkedFolderDialog.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java284
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ComboDialogField.java252
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/DialogField.java239
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IListAdapter.java33
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java20
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java46
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/LayoutUtil.java132
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java942
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ObjectStringStatusButtonDialogField.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java209
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java274
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/Separator.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java180
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringDialogField.java190
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/TreeListDialogField.java909
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAction.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAssignementAction.java573
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditWorkingSetAction.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditorTracker.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/IWorkingSetActionGroup.java23
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetElementAdapter.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPage.java480
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPageContentProvider.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetUpdater.java242
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/Mementos.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OpenPropertiesWorkingSetAction.java55
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OthersWorkingSetUpdater.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/RemoveWorkingSetElementAction.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SelectWorkingSetAction.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SimpleWorkingSetSelectionDialog.java335
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewAction.java35
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewActionGroup.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationBlock.java403
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationDialog.java609
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilter.java222
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java355
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java101
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.java87
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties79
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetModel.java456
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetShowActionGroup.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/rino.gifbin637 -> 0 bytes
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeGeneration.java336
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeStyleConfiguration.java96
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IContextMenuConstants.java149
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IDocumentationReader.java40
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java93
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IPackagesViewPart.java56
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java317
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ITypeHierarchyViewPart.java204
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManager.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManagerExtension.java48
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyProvider.java38
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java357
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaElementSorter.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java358
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementImageDescriptor.java297
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabelProvider.java268
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java1191
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptLibrariesAction.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSourceFoldersAction.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSuperTypeAction.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java753
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/Messages.java42
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/OverrideIndicatorLabelDecorator.java237
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/PreferenceConstants.java3772
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java398
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java181
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java509
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AbstractOpenWizardAction.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddDelegateMethodsAction.java596
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddGetterSetterAction.java1083
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddJavaDocStubAction.java223
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddToClasspathAction.java166
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddUnimplementedConstructorsAction.java597
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/BuildActionGroup.java133
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java176
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ChangeTypeAction.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertAnonymousToNestedAction.java161
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertLocalToFieldAction.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertNestedToTopAction.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertingSelectionProvider.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CustomFiltersActionGroup.java757
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java207
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExternalizeStringsAction.java541
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractConstantAction.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractTempAction.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindAction.java323
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsAction.java78
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInHierarchyAction.java88
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInProjectAction.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInWorkingSetAction.java112
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindExceptionOccurrencesAction.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementOccurrencesAction.java124
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsAction.java82
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInProjectAction.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInWorkingSetAction.java112
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindOccurrencesInFileAction.java219
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesAction.java75
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInHierarchyAction.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInProjectAction.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInWorkingSetAction.java99
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesAction.java98
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInHierarchyAction.java89
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInProjectAction.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInWorkingSetAction.java111
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesAction.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInHierarchyAction.java76
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInProjectAction.java85
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInWorkingSetAction.java100
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FormatAllAction.java430
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java535
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateNewConstructorUsingFieldsAction.java387
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java635
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImportActionGroup.java74
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineAction.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineTempAction.java125
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceFactoryAction.java136
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceIndirectionAction.java154
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceParameterAction.java83
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java183
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java565
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MemberFilterActionGroup.java346
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ModifyParametersAction.java167
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MoveAction.java256
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/NavigateActionGroup.java107
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java192
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenAction.java225
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenExternalJavadocAction.java202
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenJavaPerspectiveAction.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java84
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewJavaProjectWizardAction.java66
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenProjectAction.java227
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenSuperImplementationAction.java195
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenTypeHierarchyAction.java259
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java314
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OrganizeImportsAction.java397
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OverrideMethodsAction.java276
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ProjectActionGroup.java218
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PullUpAction.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PushDownAction.java179
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java205
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefactorActionGroup.java670
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java217
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefreshAction.java221
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RemoveFromClasspathAction.java138
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RenameAction.java116
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReplaceInvocationsAction.java141
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java254
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelfEncapsulateFieldAction.java165
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java134
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInNavigatorViewAction.java171
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInPackageViewAction.java135
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SortMembersAction.java257
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SurroundWithTryCatchAction.java145
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/UseSupertypeAction.java157
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WorkingSetFindAction.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java205
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoFilterExtension.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoImageProvider.java45
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoRequestor.java61
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeSelectionComponent.java31
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/TypeSelectionExtension.java97
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties11
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/project/JsNature.java273
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/IRefactoringProcessorIds.java274
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/RenameSupport.java471
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ElementQuerySpecification.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IMatchPresentation.java65
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IQueryParticipant.java63
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java34
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/PatternQuerySpecification.java86
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/QuerySpecification.java72
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManager.java54
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManagerExtension.java44
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptColorConstants.java177
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptPartitions.java52
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java849
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptTextTools.java306
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java1456
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java69
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProviderExtension.java53
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/AbstractProposalSorter.java92
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java769
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java94
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java722
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/ContentAssistInvocationContext.java196
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IInvocationContext.java67
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposal.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavadocCompletionProcessor.java77
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IProblemLocation.java91
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickAssistProcessor.java49
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickFixProcessor.java57
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaContentAssistInvocationContext.java308
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java37
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties13
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/hover/IJavaEditorTextHover.java43
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java73
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java601
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/ClasspathAttributeConfiguration.java123
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java71
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension.java41
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension2.java39
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java264
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewClassWizardPage.java286
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewContainerWizardPage.java519
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java90
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewJavaProjectWizardPage.java333
-rw-r--r--bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java2407
1879 files changed, 0 insertions, 427824 deletions
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/Corext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/Corext.java
deleted file mode 100644
index ccd12239..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/Corext.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext;
-
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class Corext {
-
- public static String getPluginId() {
- return JavaScriptPlugin.getPluginId();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.java
deleted file mode 100644
index 13fa5571..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext;
-
-import org.eclipse.osgi.util.NLS;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class CorextMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.CorextMessages";//$NON-NLS-1$
-
- private CorextMessages() {
- // Do not instantiate
- }
-
- public static String Resources_outOfSyncResources;
- public static String Resources_outOfSync;
- public static String Resources_modifiedResources;
- public static String Resources_fileModified;
-
- public static String JavaDocLocations_migrate_operation;
- public static String JavaDocLocations_error_readXML;
- public static String JavaDocLocations_migratejob_name;
-
-
- public static String History_error_serialize;
- public static String History_error_read;
- public static String TypeInfoHistory_consistency_check;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CorextMessages.class);
- }
-
- public static String JavaModelUtil_applyedit_operation;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties
deleted file mode 100644
index c6b037b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties
+++ /dev/null
@@ -1,24 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-Resources_outOfSyncResources= Some resources are out of sync
-Resources_outOfSync= Resource ''{0}'' is out of sync with file system.
-Resources_modifiedResources= There are modified resources
-Resources_fileModified= File ''{0}'' has been modified since the beginning of the operation
-
-JavaDocLocations_migrate_operation=Migrate JSDoc locations to include path attributes...
-JavaDocLocations_error_readXML=Problems while reading the JSDoc locations from XML
-JavaDocLocations_migratejob_name=Migrate JSDoc locations to include path attributes
-JavaModelUtil_applyedit_operation=Applying changes
-
-
-History_error_serialize= Problems serializing information to XML ''{0}''
-TypeInfoHistory_consistency_check=Checking consistency of type history...
-History_error_read=Problems reading information from XML ''{0}''
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/SourceRange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/SourceRange.java
deleted file mode 100644
index 0efd81c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/SourceRange.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext;
-
-import java.util.Arrays;
-import java.util.Comparator;
-
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class SourceRange implements ISourceRange{
-
- private final int fOffset;
- private final int fLength;
-
- public SourceRange(int offset, int length){
- fLength= length;
- fOffset= offset;
- }
-
- public SourceRange(ASTNode node) {
- this(node.getStartPosition(), node.getLength());
- }
-
- public SourceRange(IProblem problem) {
- this(problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1);
- }
-
- /*
- * @see ISourceRange#getLength()
- */
- public int getLength() {
- return fLength;
- }
-
- /*
- * @see ISourceRange#getOffset()
- */
- public int getOffset() {
- return fOffset;
- }
-
- public int getEndExclusive() {
- return getOffset() + getLength();
- }
-
- public int getEndInclusive() {
- return getEndExclusive() - 1;
- }
-
- /*non java doc
- * for debugging only
- */
- public String toString(){
- return "<offset: " + fOffset +" length: " + fLength + "/>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /**
- * Sorts the given ranges by offset (backwards).
- * Note: modifies the parameter.
- * @param ranges the ranges to sort
- * @return the sorted ranges, which are identical to the parameter ranges
- */
- public static ISourceRange[] reverseSortByOffset(ISourceRange[] ranges){
- Comparator comparator= new Comparator(){
- public int compare(Object o1, Object o2){
- return ((ISourceRange)o2).getOffset() - ((ISourceRange)o1).getOffset();
- }
- };
- Arrays.sort(ranges, comparator);
- return ranges;
- }
-
- /*
- * @see Object#equals(Object)
- */
- public boolean equals(Object obj) {
- if (! (obj instanceof ISourceRange))
- return false;
- return ((ISourceRange)obj).getOffset() == fOffset && ((ISourceRange)obj).getLength() == fLength;
- }
-
- /*
- * @see Object#hashCode()
- */
- public int hashCode() {
- return fLength ^ fOffset;
- }
-
- public boolean covers(ASTNode node) {
- return covers(new SourceRange(node));
- }
-
- public boolean covers(SourceRange range) {
- return getOffset() <= range.getOffset()
- && getEndInclusive() >= range.getEndInclusive();
- }
-
- /**
- * Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=130161
- * (Java Model returns ISourceRanges [-1, 0] if source not available).
- *
- * @param range a source range, can be <code>null</code>
- * @return <code>true</code> iff range is not null and range.getOffset() is not -1
- */
- public static boolean isAvailable(ISourceRange range) {
- return range != null && range.getOffset() != -1;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/ValidateEditException.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/ValidateEditException.java
deleted file mode 100644
index 51bad17c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/ValidateEditException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ValidateEditException extends CoreException {
-
- private static final long serialVersionUID= 1L;
-
- public ValidateEditException(IStatus status) {
- super(status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java
deleted file mode 100644
index 2ec2c96a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.buildpath;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class BuildpathDelta {
-
- private final String fOperationDescription;
- private CPListElement[] fNewEntries;
- private final List fCreatedResources;
- private final List fDeletedResources;
- private final List fAddedEntries;
- private final ArrayList fRemovedEntries;
-
- public BuildpathDelta(String operationDescription) {
- fOperationDescription= operationDescription;
-
- fCreatedResources= new ArrayList();
- fDeletedResources= new ArrayList();
- fAddedEntries= new ArrayList();
- fRemovedEntries= new ArrayList();
- }
-
- public String getOperationDescription() {
- return fOperationDescription;
- }
-
- public CPListElement[] getNewEntries() {
- return fNewEntries;
- }
-
- public IResource[] getCreatedResources() {
- return (IResource[])fCreatedResources.toArray(new IResource[fCreatedResources.size()]);
- }
-
- public IResource[] getDeletedResources() {
- return (IResource[])fDeletedResources.toArray(new IResource[fDeletedResources.size()]);
- }
-
- public void setNewEntries(CPListElement[] newEntries) {
- fNewEntries= newEntries;
- }
-
- public void addCreatedResource(IResource resource) {
- fCreatedResources.add(resource);
- }
-
- public void addDeletedResource(IResource resource) {
- fDeletedResources.add(resource);
- }
-
- public List getAddedEntries() {
- return fAddedEntries;
- }
-
- public void addEntry(CPListElement entry) {
- fAddedEntries.add(entry);
- }
-
- public List getRemovedEntries() {
- return fRemovedEntries;
- }
-
- public void removeEntry(CPListElement entry) {
- fRemovedEntries.add(entry);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java
deleted file mode 100644
index 2a1af9a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.buildpath;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CPJavaProject {
-
- public static CPJavaProject createFromExisting(IJavaScriptProject javaProject) throws CoreException {
- List classpathEntries= ClasspathModifier.getExistingEntries(javaProject);
- return new CPJavaProject(classpathEntries);
- }
-
- private final List fCPListElements;
-
- public CPJavaProject(List cpListElements) {
- fCPListElements= cpListElements;
- }
-
- public CPJavaProject createWorkingCopy() {
- List newList= new ArrayList(fCPListElements.size());
- for (Iterator iterator= fCPListElements.iterator(); iterator.hasNext();) {
- CPListElement element= (CPListElement)iterator.next();
- newList.add(element.copy());
- }
- return new CPJavaProject(newList);
- }
-
- public CPListElement get(int index) {
- return (CPListElement)fCPListElements.get(index);
- }
-
- public IIncludePathEntry[] getIncludePathEntries() {
- IIncludePathEntry[] result= new IIncludePathEntry[fCPListElements.size()];
- int i= 0;
- for (Iterator iterator= fCPListElements.iterator(); iterator.hasNext();) {
- CPListElement element= (CPListElement)iterator.next();
- result[i]= element.getClasspathEntry();
- i++;
- }
- return result;
- }
-
- public CPListElement getCPElement(CPListElement element) {
- return ClasspathModifier.getClasspathEntry(fCPListElements, element);
- }
-
- public List getCPListElements() {
- return fCPListElements;
- }
-
- public IJavaScriptProject getJavaProject() {
- return ((CPListElement)fCPListElements.get(0)).getJavaProject();
- }
-
- public int indexOf(CPListElement element) {
- return fCPListElements.indexOf(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/ClasspathModifier.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/ClasspathModifier.java
deleted file mode 100644
index 69ba6fff..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/ClasspathModifier.java
+++ /dev/null
@@ -1,1067 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.buildpath;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ClasspathModifier {
-
- private ClasspathModifier() {}
-
- public static BuildpathDelta removeFromBuildpath(CPListElement[] toRemove, CPJavaProject cpProject) {
-
- IJavaScriptProject javaScriptProject= cpProject.getJavaProject();
- IPath projectPath= javaScriptProject.getPath();
- IWorkspaceRoot workspaceRoot= javaScriptProject.getProject().getWorkspace().getRoot();
-
- List existingEntries= cpProject.getCPListElements();
- BuildpathDelta result= new BuildpathDelta(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip);
-
- for (int i= 0; i < toRemove.length; i++) {
- CPListElement element= toRemove[i];
- existingEntries.remove(element);
- result.removeEntry(element);
- IPath path= element.getPath();
- removeFilters(path, javaScriptProject, existingEntries);
- if (!path.equals(projectPath)) {
- IResource member= workspaceRoot.findMember(path);
- if (member != null)
- result.addDeletedResource(member);
- }
- }
-
- result.setNewEntries((CPListElement[])existingEntries.toArray(new CPListElement[existingEntries.size()]));
-
- return result;
- }
-
- /**
- * Get the <code>IIncludePathEntry</code> from the project and
- * convert it into a list of <code>CPListElement</code>s.
- *
- * @param project the JavaScript project to get it's include path entries from
- * @return a list of <code>CPListElement</code>s corresponding to the
- * include path entries of the project
- * @throws JavaScriptModelException
- */
- public static List getExistingEntries(IJavaScriptProject project) throws JavaScriptModelException {
- IIncludePathEntry[] classpathEntries= project.getRawIncludepath();
- ArrayList newClassPath= new ArrayList();
- for (int i= 0; i < classpathEntries.length; i++) {
- IIncludePathEntry curr= classpathEntries[i];
- newClassPath.add(CPListElement.createFromExisting(curr, project));
- }
- return newClassPath;
- }
-
- /**
- * Try to find the corresponding and modified <code>CPListElement</code> for the root
- * in the list of elements and return it.
- * If no one can be found, the roots <code>ClasspathEntry</code> is converted to a
- * <code>CPListElement</code> and returned.
- *
- * @param elements a list of <code>CPListElements</code>
- * @param root the root to find the <code>ClasspathEntry</code> for represented by
- * a <code>CPListElement</code>
- * @return the <code>CPListElement</code> found in the list (matching by using the path) or
- * the roots own <code>IIncludePathEntry</code> converted to a <code>CPListElement</code>.
- * @throws JavaScriptModelException
- */
- public static CPListElement getClasspathEntry(List elements, IPackageFragmentRoot root) throws JavaScriptModelException {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- for (int i= 0; i < elements.size(); i++) {
- CPListElement element= (CPListElement) elements.get(i);
- if (element.getPath().equals(root.getPath()) && element.getEntryKind() == entry.getEntryKind())
- return (CPListElement) elements.get(i);
- }
- CPListElement newElement= CPListElement.createFromExisting(entry, root.getJavaScriptProject());
- elements.add(newElement);
- return newElement;
- }
-
- /**
- * Get the source folder of a given <code>IResource</code> element,
- * starting with the resource's parent.
- *
- * @param resource the resource to get the fragment root from
- * @param project the JavaScript project
- * @param monitor progress monitor, can be <code>null</code>
- * @return resolved fragment root, or <code>null</code> the resource is not (in) a source folder
- * @throws JavaScriptModelException
- */
- public static IPackageFragmentRoot getFragmentRoot(IResource resource, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- IJavaScriptElement javaElem= null;
- if (resource.getFullPath().equals(project.getPath()))
- return project.getPackageFragmentRoot(resource);
- IContainer container= resource.getParent();
- do {
- if (container instanceof IFolder)
- javaElem= JavaScriptCore.create((IFolder) container);
- if (container.getFullPath().equals(project.getPath())) {
- javaElem= project;
- break;
- }
- container= container.getParent();
- if (container == null)
- return null;
- } while (javaElem == null || !(javaElem instanceof IPackageFragmentRoot));
- if (javaElem instanceof IJavaScriptProject) {
- if (!isSourceFolder((IJavaScriptProject)javaElem))
- return null;
- javaElem= project.getPackageFragmentRoot(project.getResource());
- }
- return (IPackageFragmentRoot) javaElem;
- }
-
- /**
- * Get the <code>IIncludePathEntry</code> for the
- * given path by looking up all
- * build path entries on the project
- *
- * @param path the path to find a build path entry for
- * @param project the JavaScript project
- * @return the <code>IIncludePathEntry</code> corresponding
- * to the <code>path</code> or <code>null</code> if there
- * is no such entry
- * @throws JavaScriptModelException
- */
- public static IIncludePathEntry getClasspathEntryFor(IPath path, IJavaScriptProject project, int entryKind) throws JavaScriptModelException {
- IIncludePathEntry[] entries= project.getRawIncludepath();
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry entry= entries[i];
- if (entry.getPath().equals(path) && equalEntryKind(entry, entryKind))
- return entry;
- }
- return null;
- }
-
- /**
- * Determines whether the current selection (of type
- * <code>IJavaScriptUnit</code> or <code>IPackageFragment</code>)
- * is on the inclusion filter of it's parent source folder.
- *
- * @param selection the current Java element
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @return <code>true</code> if the current selection is included,
- * <code>false</code> otherwise.
- * @throws JavaScriptModelException
- */
- public static boolean isIncluded(IJavaScriptElement selection, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_ContainsPath, 4);
- IPackageFragmentRoot root= (IPackageFragmentRoot) selection.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null)
- return false;
- return contains(selection.getPath().removeFirstSegments(root.getPath().segmentCount()), entry.getInclusionPatterns(), new SubProgressMonitor(monitor, 2));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Find out whether the <code>IResource</code> excluded or not.
- *
- * @param resource the resource to be checked
- * @param project the Java project
- * @return <code>true</code> if the resource is excluded, <code>
- * false</code> otherwise
- * @throws JavaScriptModelException
- */
- public static boolean isExcluded(IResource resource, IJavaScriptProject project) throws JavaScriptModelException {
- IPackageFragmentRoot root= getFragmentRoot(resource, project, null);
- if (root == null)
- return false;
- String fragmentName= getName(resource.getFullPath(), root.getPath());
- fragmentName= completeName(fragmentName);
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- return entry != null && contains(new Path(fragmentName), entry.getExclusionPatterns(), null);
- }
-
- /**
- * Find out whether one of the <code>IResource</code>'s parents
- * is excluded.
- *
- * @param resource check the resources parents whether they are
- * excluded or not
- * @param project the Java project
- * @return <code>true</code> if there is an excluded parent,
- * <code>false</code> otherwise
- * @throws JavaScriptModelException
- */
- public static boolean parentExcluded(IResource resource, IJavaScriptProject project) throws JavaScriptModelException {
- if (resource.getFullPath().equals(project.getPath()))
- return false;
- IPackageFragmentRoot root= getFragmentRoot(resource, project, null);
- if (root == null) {
- return true;
- }
- IPath path= resource.getFullPath().removeFirstSegments(root.getPath().segmentCount());
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null)
- return true; // there is no build path entry, this is equal to the fact that the parent is excluded
- while (path.segmentCount() > 0) {
- if (contains(path, entry.getExclusionPatterns(), null))
- return true;
- path= path.removeLastSegments(1);
- }
- return false;
- }
-
- public static String escapeSpecialChars(String value) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
-
- switch (c) {
- case '&':
- buf.append("&amp;"); //$NON-NLS-1$
- break;
- case '<':
- buf.append("&lt;"); //$NON-NLS-1$
- break;
- case '>':
- buf.append("&gt;"); //$NON-NLS-1$
- break;
- case '\'':
- buf.append("&apos;"); //$NON-NLS-1$
- break;
- case '\"':
- buf.append("&quot;"); //$NON-NLS-1$
- break;
- case 160:
- buf.append(" "); //$NON-NLS-1$
- break;
- default:
- buf.append(c);
- break;
- }
- }
- return buf.toString();
- }
-
-
- /**
- * Check whether the <code>IJavaScriptProject</code>
- * is a source folder
- *
- * @param project the project to test
- * @return <code>true</code> if <code>project</code> is a source folder
- * <code>false</code> otherwise.
- */
- public static boolean isSourceFolder(IJavaScriptProject project) throws JavaScriptModelException {
- return ClasspathModifier.getClasspathEntryFor(project.getPath(), project, IIncludePathEntry.CPE_SOURCE) != null;
- }
-
- /**
- * Check whether the <code>IPackageFragment</code>
- * corresponds to the project's default fragment.
- *
- * @param fragment the package fragment to be checked
- * @return <code>true</code> if is the default package fragment,
- * <code>false</code> otherwise.
- */
- public static boolean isDefaultFragment(IPackageFragment fragment) {
- return fragment.getElementName().length() == 0;
- }
-
- /**
- * Determines whether the inclusion filter of the element's source folder is empty
- * or not
- * @return <code>true</code> if the inclusion filter is empty,
- * <code>false</code> otherwise.
- * @throws JavaScriptModelException
- */
- public static boolean includeFiltersEmpty(IResource resource, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_ExamineInputFilters, 4);
- IPackageFragmentRoot root= getFragmentRoot(resource, project, new SubProgressMonitor(monitor, 4));
- if (root != null) {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- return entry.getInclusionPatterns().length == 0;
- }
- return true;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Check whether the input paramenter of type <code>
- * IPackageFragmentRoot</code> has either it's inclusion or
- * exclusion filter or both set (that means they are
- * not empty).
- *
- * @param root the fragment root to be inspected
- * @return <code>true</code> inclusion or exclusion filter set,
- * <code>false</code> otherwise.
- */
- public static boolean filtersSet(IPackageFragmentRoot root) throws JavaScriptModelException {
- if (root == null)
- return false;
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- IPath[] inclusions= entry.getInclusionPatterns();
- IPath[] exclusions= entry.getExclusionPatterns();
- if (inclusions != null && inclusions.length > 0)
- return true;
- if (exclusions != null && exclusions.length > 0)
- return true;
- return false;
- }
-
- /**
- * Add a resource to the build path.
- *
- * @param resource the resource to be added to the build path
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @return returns the new element of type <code>IPackageFragmentRoot</code> that has been added to the build path
- * @throws CoreException
- * @throws OperationCanceledException
- */
- public static CPListElement addToClasspath(IResource resource, List existingEntries, List newEntries, IJavaScriptProject project, IProgressMonitor monitor) throws OperationCanceledException, CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_AddToBuildpath, 2);
- exclude(resource.getFullPath(), existingEntries, newEntries, project, new SubProgressMonitor(monitor, 1));
- CPListElement entry= new CPListElement(project, IIncludePathEntry.CPE_SOURCE, resource.getFullPath(), resource);
- return entry;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Add a Java element to the build path.
- *
- * @param javaElement element to be added to the build path
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @return returns the new element of type <code>IPackageFragmentRoot</code> that has been added to the build path
- * @throws CoreException
- * @throws OperationCanceledException
- */
- public static CPListElement addToClasspath(IJavaScriptElement javaElement, List existingEntries, List newEntries, IJavaScriptProject project, IProgressMonitor monitor) throws OperationCanceledException, CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_AddToBuildpath, 10);
- CPListElement entry= new CPListElement(project, IIncludePathEntry.CPE_SOURCE, javaElement.getPath(), javaElement.getResource());
- return entry;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Remove the Java project from the build path
- *
- * @param project the project to be removed
- * @param existingEntries a list of existing <code>CPListElement</code>. This list
- * will be traversed and the entry for the project will be removed.
- * @param monitor progress monitor, can be <code>null</code>
- * @return returns the Java project
- */
- public static IJavaScriptProject removeFromClasspath(IJavaScriptProject project, List existingEntries, IProgressMonitor monitor) {
- CPListElement elem= getListElement(project.getPath(), existingEntries);
- if (elem != null) {
- existingEntries.remove(elem);
- }
- return project;
- }
-
- /**
- * Remove <code>path</code> from inclusion/exlusion filters in all <code>existingEntries</code>
- *
- * @param path the path to remove
- * @param project the Java project
- * @param existingEntries a list of <code>CPListElement</code> representing the build path
- * entries of the project.
- * @return returns a <code>List</code> of <code>CPListElement</code> of modified elements, not null.
- */
- public static List removeFilters(IPath path, IJavaScriptProject project, List existingEntries) {
- if (path == null)
- return Collections.EMPTY_LIST;
-
- IPath projPath= project.getPath();
- if (projPath.isPrefixOf(path)) {
- path= path.removeFirstSegments(projPath.segmentCount()).addTrailingSeparator();
- }
-
- List result= new ArrayList();
- for (Iterator iter= existingEntries.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- boolean hasChange= false;
- IPath[] exlusions= (IPath[])element.getAttribute(CPListElement.EXCLUSION);
- if (exlusions != null) {
- List exlusionList= new ArrayList(exlusions.length);
- for (int i= 0; i < exlusions.length; i++) {
- if (!exlusions[i].equals(path)) {
- exlusionList.add(exlusions[i]);
- } else {
- hasChange= true;
- }
- }
- element.setAttribute(CPListElement.EXCLUSION, exlusionList.toArray(new IPath[exlusionList.size()]));
- }
-
- IPath[] inclusion= (IPath[])element.getAttribute(CPListElement.INCLUSION);
- if (inclusion != null) {
- List inclusionList= new ArrayList(inclusion.length);
- for (int i= 0; i < inclusion.length; i++) {
- if (!inclusion[i].equals(path)) {
- inclusionList.add(inclusion[i]);
- } else {
- hasChange= true;
- }
- }
- element.setAttribute(CPListElement.INCLUSION, inclusionList.toArray(new IPath[inclusionList.size()]));
- }
- if (hasChange) {
- result.add(element);
- }
- }
- return result;
- }
-
- /**
- * Exclude an element with a given name and absolute path
- * from the build path.
- *
- * @param name the name of the element to be excluded
- * @param fullPath the absolute path of the element
- * @param entry the build path entry to be modified
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @return a <code>IResource</code> corresponding to the excluded element
- * @throws JavaScriptModelException
- */
- private static IResource exclude(String name, IPath fullPath, CPListElement entry, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- IResource result;
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_Excluding, 6);
- IPath[] excludedPath= (IPath[]) entry.getAttribute(CPListElement.EXCLUSION);
- IPath[] newExcludedPath= new IPath[excludedPath.length + 1];
- name= completeName(name);
- IPath path= new Path(name);
- if (!contains(path, excludedPath, new SubProgressMonitor(monitor, 2))) {
- System.arraycopy(excludedPath, 0, newExcludedPath, 0, excludedPath.length);
- newExcludedPath[excludedPath.length]= path;
- entry.setAttribute(CPListElement.EXCLUSION, newExcludedPath);
- entry.setAttribute(CPListElement.INCLUSION, remove(path, (IPath[]) entry.getAttribute(CPListElement.INCLUSION), new SubProgressMonitor(monitor, 4)));
- }
- result= fullPath == null ? null : getResource(fullPath, project);
- } finally {
- monitor.done();
- }
- return result;
- }
-
- /**
- * Exclude an object at a given path.
- * This means that the exclusion filter for the
- * corresponding <code>IPackageFragmentRoot</code> needs to be modified.
- *
- * First, the fragment root needs to be found. To do so, the new entries
- * are and the existing entries are traversed for a match and the entry
- * with the path is removed from one of those lists.
- *
- * Note: the <code>IJavaScriptElement</code>'s fragment (if there is one)
- * is not allowed to be excluded! However, inclusion (or simply no
- * filter) on the parent fragment is allowed.
- *
- * @param path absolute path of an object to be excluded
- * @param existingEntries a list of existing build path entries
- * @param newEntries a list of new build path entries
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- */
- public static void exclude(IPath path, List existingEntries, List newEntries, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_Excluding, 1);
- CPListElement elem= null;
- CPListElement existingElem= null;
- int i= 0;
- do {
- i++;
- IPath rootPath= path.removeLastSegments(i);
-
- if (rootPath.segmentCount() == 0)
- return;
-
- elem= getListElement(rootPath, newEntries);
- existingElem= getListElement(rootPath, existingEntries);
- } while (existingElem == null && elem == null);
- if (elem == null) {
- elem= existingElem;
- }
- exclude(path.removeFirstSegments(path.segmentCount() - i).toString(), null, elem, project, new SubProgressMonitor(monitor, 1));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Exclude a <code>IJavaScriptElement</code>. This means that the exclusion filter for the
- * corresponding <code>IPackageFragmentRoot</code>s need to be modified.
- *
- * Note: the <code>IJavaScriptElement</code>'s fragment (if there is one)
- * is not allowed to be excluded! However, inclusion (or simply no
- * filter) on the parent fragment is allowed.
- *
- * @param javaElement the Java element to be excluded
- * @param entry the <code>CPListElement</code> representing the
- * <code>IIncludePathEntry</code> of the Java element's root.
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- *
- * @return the resulting <code>IResource<code>
- * @throws JavaScriptModelException
- */
- public static IResource exclude(IJavaScriptElement javaElement, CPListElement entry, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- String name= getName(javaElement.getPath(), entry.getPath());
- return exclude(name, javaElement.getPath(), entry, project, new SubProgressMonitor(monitor, 1));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Inverse operation to <code>exclude</code>.
- * The resource removed from it's fragment roots exlusion filter.
- *
- * Note: the <code>IJavaScriptElement</code>'s fragment (if there is one)
- * is not allowed to be excluded! However, inclusion (or simply no
- * filter) on the parent fragment is allowed.
- *
- * @param resource the resource to be unexcluded
- * @param entry the <code>CPListElement</code> representing the
- * <code>IIncludePathEntry</code> of the resource's root.
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @throws JavaScriptModelException
- *
- */
- public static void unExclude(IResource resource, CPListElement entry, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_RemoveExclusion, 10);
- String name= getName(resource.getFullPath(), entry.getPath());
- IPath[] excludedPath= (IPath[]) entry.getAttribute(CPListElement.EXCLUSION);
- IPath[] newExcludedPath= remove(new Path(completeName(name)), excludedPath, new SubProgressMonitor(monitor, 3));
- entry.setAttribute(CPListElement.EXCLUSION, newExcludedPath);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Resets inclusion and exclusion filters for the given
- * <code>IJavaScriptElement</code>
- *
- * @param element element to reset it's filters
- * @param entry the <code>CPListElement</code> to reset its filters for
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @throws JavaScriptModelException
- */
- public static void resetFilters(IJavaScriptElement element, CPListElement entry, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_ResetFilters, 3);
-
- List exclusionList= getFoldersOnCP(element.getPath(), project, new SubProgressMonitor(monitor, 2));
-
- IPath[] exclusions= (IPath[]) exclusionList.toArray(new IPath[exclusionList.size()]);
-
- entry.setAttribute(CPListElement.INCLUSION, new IPath[0]);
- entry.setAttribute(CPListElement.EXCLUSION, exclusions);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Try to find the corresponding and modified <code>CPListElement</code> for the provided
- * <code>CPListElement</code> in the list of elements and return it.
- * If no one can be found, the provided <code>CPListElement</code> is returned.
- *
- * @param elements a list of <code>CPListElements</code>
- * @param cpElement the <code>CPListElement</code> to find the corresponding entry in
- * the list
- * @return the <code>CPListElement</code> found in the list (matching by using the path) or
- * the second <code>CPListElement</code> parameter itself if there is no match.
- */
- public static CPListElement getClasspathEntry(List elements, CPListElement cpElement) {
- for (int i= 0; i < elements.size(); i++) {
- if (((CPListElement) elements.get(i)).getPath().equals(cpElement.getPath()))
- return (CPListElement) elements.get(i);
- }
- elements.add(cpElement);
- return cpElement;
- }
-
- /**
- * For a given path, find the corresponding element in the list.
- *
- * @param path the path to found an entry for
- * @param elements a list of <code>CPListElement</code>s
- * @return the mathed <code>CPListElement</code> or <code>null</code> if
- * no match could be found
- */
- public static CPListElement getListElement(IPath path, List elements) {
- for (int i= 0; i < elements.size(); i++) {
- CPListElement element= (CPListElement) elements.get(i);
- if (element.getEntryKind() == IIncludePathEntry.CPE_SOURCE && element.getPath().equals(path)) {
- return element;
- }
- }
- return null;
- }
-
- public static void commitClassPath(List newEntries, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- monitor.beginTask("", 2); //$NON-NLS-1$
-
- try {
- IIncludePathEntry[] entries= convert(newEntries);
-
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(project, entries);
- if (!status.isOK())
- throw new JavaScriptModelException(status);
-
- project.setRawIncludepath(entries, new SubProgressMonitor(monitor, 2));
- } finally {
- monitor.done();
- }
- }
-
- public static void commitClassPath(CPJavaProject cpProject, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- monitor.beginTask("", 2); //$NON-NLS-1$
-
- try {
- IIncludePathEntry[] entries= convert(cpProject.getCPListElements());
-
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(cpProject.getJavaProject(), entries);
- if (!status.isOK())
- throw new JavaScriptModelException(status);
-
- cpProject.getJavaProject().setRawIncludepath(entries, new SubProgressMonitor(monitor, 2));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * For a given list of entries, find out what representation they
- * will have in the project and return a list with corresponding
- * elements.
- *
- * @param entries a list of entries to find an appropriate representation
- * for. The list can contain elements of two types:
- * <li><code>IResource</code></li>
- * <li><code>IJavaScriptElement</code></li>
- * @param project the Java project
- * @return a list of elements corresponding to the passed entries.
- */
- public static List getCorrespondingElements(List entries, IJavaScriptProject project) {
- List result= new ArrayList();
- for (int i= 0; i < entries.size(); i++) {
- Object element= entries.get(i);
- IPath path;
- if (element instanceof IResource)
- path= ((IResource) element).getFullPath();
- else
- path= ((IJavaScriptElement) element).getPath();
- IResource resource= getResource(path, project);
- if (resource != null) {
- IJavaScriptElement elem= JavaScriptCore.create(resource);
- if (elem != null && project.isOnIncludepath(elem))
- result.add(elem);
- else
- result.add(resource);
- }
-
- }
- return result;
- }
-
- /**
- * Returns for the given absolute path the corresponding
- * resource, this is either element of type <code>IFile</code>
- * or <code>IFolder</code>.
- *
- * @param path an absolute path to a resource
- * @param project the Java project
- * @return the resource matching to the path. Can be
- * either an <code>IFile</code> or an <code>IFolder</code>.
- */
- private static IResource getResource(IPath path, IJavaScriptProject project) {
- return project.getProject().getWorkspace().getRoot().findMember(path);
- }
-
- /**
- * Find out whether the provided path equals to one
- * in the array.
- *
- * @param path path to find an equivalent for
- * @param paths set of paths to compare with
- * @param monitor progress monitor, can be <code>null</code>
- * @return <code>true</code> if there is an occurrence, <code>
- * false</code> otherwise
- */
- private static boolean contains(IPath path, IPath[] paths, IProgressMonitor monitor) {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- if (path == null)
- return false;
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_ComparePaths, paths.length);
- if (path.getFileExtension() == null)
- path= new Path(completeName(path.toString()));
- for (int i= 0; i < paths.length; i++) {
- if (paths[i].equals(path))
- return true;
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- return false;
- }
-
- /**
- * Add a '/' at the end of the name if
- * it does not end with '.java', or other Java-like extension.
- *
- * @param name append '/' at the end if
- * necessary
- * @return modified string
- */
- private static String completeName(String name) {
- if (!JavaScriptCore.isJavaScriptLikeFileName(name)) {
- name= name + "/"; //$NON-NLS-1$
- name= name.replace('.', '/');
- return name;
- }
- return name;
- }
-
- /**
- * Removes <code>path</code> out of the set of given <code>
- * paths</code>. If the path is not contained, then the
- * initially provided array of paths is returned.
- *
- * Only the first occurrence will be removed.
- *
- * @param path path to be removed
- * @param paths array of path to apply the removal on
- * @param monitor progress monitor, can be <code>null</code>
- * @return array which does not contain <code>path</code>
- */
- private static IPath[] remove(IPath path, IPath[] paths, IProgressMonitor monitor) {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_RemovePath, paths.length + 5);
- if (!contains(path, paths, new SubProgressMonitor(monitor, 5)))
- return paths;
-
- ArrayList newPaths= new ArrayList();
- for (int i= 0; i < paths.length; i++) {
- monitor.worked(1);
- if (!paths[i].equals(path))
- newPaths.add(paths[i]);
- }
-
- return (IPath[]) newPaths.toArray(new IPath[newPaths.size()]);
- } finally {
- monitor.done();
- }
-
- }
-
- /**
- * Find all folders that are on the build path and
- * <code>path</code> is a prefix of those folders
- * path entry, that is, all folders which are a
- * subfolder of <code>path</code>.
- *
- * For example, if <code>path</code>=/MyProject/src
- * then all folders having a path like /MyProject/src/*,
- * where * can be any valid string are returned if
- * they are also on the project's build path.
- *
- * @param path absolute path
- * @param project the Java project
- * @param monitor progress monitor, can be <code>null</code>
- * @return an array of paths which belong to subfolders
- * of <code>path</code> and which are on the build path
- * @throws JavaScriptModelException
- */
- private static List getFoldersOnCP(IPath path, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- List srcFolders= new ArrayList();
- IIncludePathEntry[] cpEntries= project.getRawIncludepath();
- for (int i= 0; i < cpEntries.length; i++) {
- IPath cpPath= cpEntries[i].getPath();
- if (path.isPrefixOf(cpPath) && path.segmentCount() + 1 == cpPath.segmentCount())
- srcFolders.add(new Path(completeName(cpPath.lastSegment())));
- }
- return srcFolders;
- }
-
- /**
- * Returns a string corresponding to the <code>path</code>
- * with the <code>rootPath<code>'s number of segments
- * removed
- *
- * @param path path to remove segments
- * @param rootPath provides the number of segments to
- * be removed
- * @return a string corresponding to the mentioned
- * action
- */
- private static String getName(IPath path, IPath rootPath) {
- return path.removeFirstSegments(rootPath.segmentCount()).toString();
- }
-
- /**
- * Sets and validates the new entries. Note that the elments of
- * the list containing the new entries will be added to the list of
- * existing entries (therefore, there is no return list for this method).
- *
- * @param existingEntries a list of existing classpath entries
- * @param newEntries a list of entries to be added to the existing ones
- * @param project the Java project
- * @param monitor a progress monitor, can be <code>null</code>
- * @throws CoreException in case that validation on one of the new entries fails
- */
- public static void setNewEntry(List existingEntries, List newEntries, IJavaScriptProject project, IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_SetNewEntry, existingEntries.size());
- for (int i= 0; i < newEntries.size(); i++) {
- CPListElement entry= (CPListElement) newEntries.get(i);
- validateAndAddEntry(entry, existingEntries, project);
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Convert a list of <code>CPListElement</code>s to
- * an array of <code>IIncludePathEntry</code>.
- *
- * @param list the list to be converted
- * @return an array containing build path entries
- * corresponding to the list
- */
- private static IIncludePathEntry[] convert(List list) {
- IIncludePathEntry[] entries= new IIncludePathEntry[list.size()];
- for (int i= 0; i < list.size(); i++) {
- CPListElement element= (CPListElement) list.get(i);
- entries[i]= element.getClasspathEntry();
- }
- return entries;
- }
-
- /**
- * Validate the new entry in the context of the existing entries. Furthermore,
- * check if exclusion filters need to be applied and do so if necessary.
- *
- * If validation was successfull, add the new entry to the list of existing entries.
- *
- * @param entry the entry to be validated and added to the list of existing entries.
- * @param existingEntries a list of existing entries representing the build path
- * @param project the Java project
- * @throws CoreException in case that validation fails
- */
- private static void validateAndAddEntry(CPListElement entry, List existingEntries, IJavaScriptProject project) throws CoreException {
- IPath path= entry.getPath();
- IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
- IStatus validate= workspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
- StatusInfo rootStatus= new StatusInfo();
- rootStatus.setOK();
- boolean isExternal= isExternalArchiveOrLibrary(entry, project);
- if (!isExternal && validate.matches(IStatus.ERROR) && !project.getPath().equals(path)) {
- rootStatus.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
- throw new CoreException(rootStatus);
- } else {
- if (!isExternal && !project.getPath().equals(path)) {
- IResource res= workspaceRoot.findMember(path);
- if (res != null) {
- if (res.getType() != IResource.FOLDER && res.getType() != IResource.FILE) {
- rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
- throw new CoreException(rootStatus);
- }
- } else {
- URI projLocation= project.getProject().getLocationURI();
- if (projLocation != null) {
- IFileStore store= EFS.getStore(projLocation).getChild(path);
- if (store.fetchInfo().exists()) {
- rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
- throw new CoreException(rootStatus);
- }
- }
- }
- }
-
- for (int i= 0; i < existingEntries.size(); i++) {
- CPListElement curr= (CPListElement) existingEntries.get(i);
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (path.equals(curr.getPath()) && !project.getPath().equals(path)) {
- rootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExisting);
- throw new CoreException(rootStatus);
- }
- }
- }
-
- if (!isExternal && !entry.getPath().equals(project.getPath()))
- exclude(entry.getPath(), existingEntries, new ArrayList(), project, null);
-
- insertAtEndOfCategory(entry, existingEntries);
-
- IIncludePathEntry[] entries= convert(existingEntries);
-
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(project, entries);
- if (!status.isOK()) {
- rootStatus.setError(status.getMessage());
- throw new CoreException(rootStatus);
- }
-
- if (isSourceFolder(project) || project.getPath().equals(path)) {
- rootStatus.setWarning(NewWizardMessages.NewSourceFolderWizardPage_warning_ReplaceSF);
- return;
- }
-
- rootStatus.setOK();
- return;
- }
- }
-
- private static void insertAtEndOfCategory(CPListElement entry, List existingEntries) {
- int length= existingEntries.size();
- CPListElement[] elements= (CPListElement[])existingEntries.toArray(new CPListElement[length]);
- int i= 0;
- while (i < length && elements[i].getClasspathEntry().getEntryKind() != entry.getClasspathEntry().getEntryKind()) {
- i++;
- }
- if (i < length) {
- i++;
- while (i < length && elements[i].getClasspathEntry().getEntryKind() == entry.getClasspathEntry().getEntryKind()) {
- i++;
- }
- existingEntries.add(i, entry);
- return;
- }
-
- switch (entry.getClasspathEntry().getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- existingEntries.add(0, entry);
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_PROJECT:
- default:
- existingEntries.add(entry);
- break;
- }
- }
-
- private static boolean isExternalArchiveOrLibrary(CPListElement entry, IJavaScriptProject project) {
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY || entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- if (entry.getResource() instanceof IFolder) {
- return false;
- }
- return true;
- }
- return false;
- }
-
- /**
- * Test if the provided kind is of type
- * <code>IIncludePathEntry.CPE_SOURCE</code>
- *
- * @param entry the classpath entry to be compared with the provided type
- * @param kind the kind to be checked
- * @return <code>true</code> if kind equals
- * <code>IIncludePathEntry.CPE_SOURCE</code>,
- * <code>false</code> otherwise
- */
- private static boolean equalEntryKind(IIncludePathEntry entry, int kind) {
- return entry.getEntryKind() == kind;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/IBuildpathModifierListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/IBuildpathModifierListener.java
deleted file mode 100644
index c2ecbeb3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/IBuildpathModifierListener.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.buildpath;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IBuildpathModifierListener {
-
- public void buildpathChanged(BuildpathDelta delta);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchy.java
deleted file mode 100644
index 462d9312..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchy.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CallHierarchy {
- private static final String PREF_USE_IMPLEMENTORS= "PREF_USE_IMPLEMENTORS"; //$NON-NLS-1$
- private static final String PREF_USE_FILTERS = "PREF_USE_FILTERS"; //$NON-NLS-1$
- private static final String PREF_FILTERS_LIST = "PREF_FILTERS_LIST"; //$NON-NLS-1$
-
- private static final String DEFAULT_IGNORE_FILTERS = "java.*,javax.*"; //$NON-NLS-1$
- private static CallHierarchy fgInstance;
- private IJavaScriptSearchScope fSearchScope;
- private StringMatcher[] fFilters;
-
- public static CallHierarchy getDefault() {
- if (fgInstance == null) {
- fgInstance = new CallHierarchy();
- }
-
- return fgInstance;
- }
-
- public boolean isSearchUsingImplementorsEnabled() {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
-
- return settings.getBoolean(PREF_USE_IMPLEMENTORS);
- }
-
- public void setSearchUsingImplementorsEnabled(boolean enabled) {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
-
- settings.setValue(PREF_USE_IMPLEMENTORS, enabled);
- }
-
- public Collection getImplementingMethods(IFunction method) {
- if (isSearchUsingImplementorsEnabled()) {
- IJavaScriptElement[] result = Implementors.getInstance().searchForImplementors(new IJavaScriptElement[] {
- method
- }, new NullProgressMonitor());
-
- if ((result != null) && (result.length > 0)) {
- return Arrays.asList(result);
- }
- }
-
- return new ArrayList(0);
- }
-
- public MethodWrapper getCallerRoot(IFunction method) {
- return new CallerMethodWrapper(null, new MethodCall(method));
- }
-
- public MethodWrapper getCalleeRoot(IFunction method) {
- return new CalleeMethodWrapper(null, new MethodCall(method));
- }
-
- public static CallLocation getCallLocation(Object element) {
- CallLocation callLocation = null;
-
- if (element instanceof MethodWrapper) {
- MethodWrapper methodWrapper = (MethodWrapper) element;
- MethodCall methodCall = methodWrapper.getMethodCall();
-
- if (methodCall != null) {
- callLocation = methodCall.getFirstCallLocation();
- }
- } else if (element instanceof CallLocation) {
- callLocation = (CallLocation) element;
- }
-
- return callLocation;
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- if (fSearchScope == null) {
- fSearchScope= SearchEngine.createWorkspaceScope();
- }
-
- return fSearchScope;
- }
-
- public void setSearchScope(IJavaScriptSearchScope searchScope) {
- this.fSearchScope = searchScope;
- }
-
- /**
- * Checks whether the fully qualified name is ignored by the set filters.
- *
- * @param fullyQualifiedName
- *
- * @return True if the fully qualified name is ignored.
- */
- public boolean isIgnored(String fullyQualifiedName) {
- if ((getIgnoreFilters() != null) && (getIgnoreFilters().length > 0)) {
- for (int i = 0; i < getIgnoreFilters().length; i++) {
- String fullyQualifiedName1 = fullyQualifiedName;
-
- if (getIgnoreFilters()[i].match(fullyQualifiedName1)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public boolean isFilterEnabled() {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
- return settings.getBoolean(PREF_USE_FILTERS);
- }
-
- public void setFilterEnabled(boolean filterEnabled) {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
- settings.setValue(PREF_USE_FILTERS, filterEnabled);
- }
-
- /**
- * Returns the current filters as a string.
- * @return returns the filters
- */
- public String getFilters() {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
-
- return settings.getString(PREF_FILTERS_LIST);
- }
-
- public void setFilters(String filters) {
- fFilters = null;
-
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
- settings.setValue(PREF_FILTERS_LIST, filters);
- }
-
- /**
- * Returns filters for packages which should not be included in the search results.
- *
- * @return StringMatcher[]
- */
- private StringMatcher[] getIgnoreFilters() {
- if (fFilters == null) {
- String filterString = null;
-
- if (isFilterEnabled()) {
- filterString = getFilters();
-
- if (filterString == null) {
- filterString = DEFAULT_IGNORE_FILTERS;
- }
- }
-
- if (filterString != null) {
- fFilters = parseList(filterString);
- } else {
- fFilters = null;
- }
- }
-
- return fFilters;
- }
-
- /**
- * Parses the comma separated string into an array of StringMatcher objects
- * @param listString the string to parse
- *
- * @return list
- */
- private static StringMatcher[] parseList(String listString) {
- List list = new ArrayList(10);
- StringTokenizer tokenizer = new StringTokenizer(listString, ","); //$NON-NLS-1$
-
- while (tokenizer.hasMoreTokens()) {
- String textFilter = tokenizer.nextToken().trim();
- list.add(new StringMatcher(textFilter, false, false));
- }
-
- return (StringMatcher[]) list.toArray(new StringMatcher[list.size()]);
- }
-
- static JavaScriptUnit getCompilationUnitNode(IMember member, boolean resolveBindings) {
- ITypeRoot typeRoot= member.getTypeRoot();
- try {
- if (typeRoot.exists() && typeRoot.getBuffer() != null) {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(typeRoot);
- parser.setResolveBindings(resolveBindings);
- return (JavaScriptUnit) parser.createAST(null);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.java
deleted file mode 100644
index 0c58f912..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import org.eclipse.osgi.util.NLS;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class CallHierarchyMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallHierarchyMessages";//$NON-NLS-1$
-
- private CallHierarchyMessages() {
- // Do not instantiate
- }
-
- public static String CallerMethodWrapper_taskname;
- public static String CalleeMethodWrapper_taskname;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CallHierarchyMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties
deleted file mode 100644
index 23407fa3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
-# (report 36180: Callers/Callees view)
-###############################################################################
-CallerMethodWrapper_taskname=Finding callers...
-CalleeMethodWrapper_taskname=Finding callees...
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyVisitor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyVisitor.java
deleted file mode 100644
index d83007a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyVisitor.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public abstract class CallHierarchyVisitor {
- public void preVisit(MethodWrapper methodWrapper) {
- }
-
- public void postVisit(MethodWrapper methodWrapper) {
- }
-
- public boolean visit(MethodWrapper methodWrapper) {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallLocation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallLocation.java
deleted file mode 100644
index 829df7c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallLocation.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CallLocation implements IAdaptable {
- public static final int UNKNOWN_LINE_NUMBER= -1;
- private IMember fMember;
- private IMember fCalledMember;
- private int fStart;
- private int fEnd;
-
- private String fCallText;
- private int fLineNumber;
-
- public CallLocation(IMember member, IMember calledMember, int start, int end, int lineNumber) {
- this.fMember = member;
- this.fCalledMember = calledMember;
- this.fStart = start;
- this.fEnd = end;
- this.fLineNumber= lineNumber;
- }
-
- /**
- * @return IFunction
- */
- public IMember getCalledMember() {
- return fCalledMember;
- }
-
- /**
- *
- */
- public int getEnd() {
- return fEnd;
- }
-
- public IMember getMember() {
- return fMember;
- }
-
- /**
- *
- */
- public int getStart() {
- return fStart;
- }
-
- public int getLineNumber() {
- initCallTextAndLineNumber();
- return fLineNumber;
- }
-
- public String getCallText() {
- initCallTextAndLineNumber();
- return fCallText;
- }
-
- private void initCallTextAndLineNumber() {
- if (fCallText != null)
- return;
-
- IBuffer buffer= getBufferForMember();
- if (buffer == null || buffer.getLength() < fEnd) { //binary, without source attachment || buffer contents out of sync (bug 121900)
- fCallText= ""; //$NON-NLS-1$
- fLineNumber= UNKNOWN_LINE_NUMBER;
- return;
- }
-
- fCallText= buffer.getText(fStart, (fEnd - fStart));
-
- if (fLineNumber == UNKNOWN_LINE_NUMBER) {
- Document document= new Document(buffer.getContents());
- try {
- fLineNumber= document.getLineOfOffset(fStart) + 1;
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /**
- * Returns the IBuffer for the IMember represented by this CallLocation.
- *
- * @return IBuffer for the IMember or null if the member doesn't have a buffer (for
- * example if it is a binary file without source attachment).
- */
- private IBuffer getBufferForMember() {
- IBuffer buffer = null;
- try {
- IOpenable openable = fMember.getOpenable();
- if (openable != null && fMember.exists()) {
- buffer = openable.getBuffer();
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return buffer;
- }
-
- public String toString() {
- return getCallText();
- }
-
- public Object getAdapter(Class adapter) {
- if (IJavaScriptElement.class.isAssignableFrom(adapter)) {
- return getMember();
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallSearchResultCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallSearchResultCollector.java
deleted file mode 100644
index 7a466ba7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallSearchResultCollector.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-class CallSearchResultCollector {
- private Map fCalledMembers;
-
- public CallSearchResultCollector() {
- this.fCalledMembers = createCalledMethodsData();
- }
-
- public Map getCallers() {
- return fCalledMembers;
- }
-
- protected void addMember(IMember member, IMember calledMember, int start, int end) {
- addMember(member, calledMember, start, end, CallLocation.UNKNOWN_LINE_NUMBER);
- }
-
- protected void addMember(IMember member, IMember calledMember, int start, int end, int lineNumber) {
- if ((member != null) && (calledMember != null)) {
- if (!isIgnored(calledMember)) {
- MethodCall methodCall = (MethodCall) fCalledMembers.get(calledMember.getHandleIdentifier());
-
- if (methodCall == null) {
- methodCall = new MethodCall(calledMember);
- fCalledMembers.put(calledMember.getHandleIdentifier(), methodCall);
- }
-
- methodCall.addCallLocation(new CallLocation(member, calledMember, start,
- end, lineNumber));
- }
- }
- }
-
- protected Map createCalledMethodsData() {
- return new HashMap();
- }
-
- /**
- * Method isIgnored.
- * @param enclosingElement
- * @return boolean
- */
- private boolean isIgnored(IMember enclosingElement) {
- IType type = getTypeOfElement(enclosingElement);
- String fullyQualifiedName = (type!=null)? type.getFullyQualifiedName() :
- enclosingElement.getJavaScriptUnit().getElementName();
-
- return CallHierarchy.getDefault().isIgnored(fullyQualifiedName);
- }
-
- private IType getTypeOfElement(IMember element) {
- if (element.getElementType() == IJavaScriptElement.TYPE) {
- return (IType) element;
- }
-
- return element.getDeclaringType();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java
deleted file mode 100644
index a719888c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeAnalyzerVisitor.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-class CalleeAnalyzerVisitor extends ASTVisitor {
- private CallSearchResultCollector fSearchResults;
- private IFunction fMethod;
- private JavaScriptUnit fCompilationUnit;
- private IProgressMonitor fProgressMonitor;
- private int fMethodEndPosition;
- private int fMethodStartPosition;
-
- CalleeAnalyzerVisitor(IFunction method, JavaScriptUnit compilationUnit, IProgressMonitor progressMonitor) {
- fSearchResults = new CallSearchResultCollector();
- this.fMethod = method;
- this.fCompilationUnit= compilationUnit;
- this.fProgressMonitor = progressMonitor;
-
- try {
- ISourceRange sourceRange = method.getSourceRange();
- this.fMethodStartPosition = sourceRange.getOffset();
- this.fMethodEndPosition = fMethodStartPosition + sourceRange.getLength();
- } catch (JavaScriptModelException jme) {
- JavaScriptPlugin.log(jme);
- }
- }
-
- /**
- * Method getCallees.
- *
- * @return CallerElement
- */
- public Map getCallees() {
- return fSearchResults.getCallers();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- progressMonitorWorked(1);
- if (!isFurtherTraversalNecessary(node)) {
- return false;
- }
-
- if (isNodeWithinMethod(node)) {
- addMethodCall(node.resolveConstructorBinding(), node);
- }
-
- return true;
- }
-
- /**
- * Find all constructor invocations (<code>this(...)</code>) from the called method.
- * Since we only traverse into the AST on the wanted method declaration, this method
- * should not hit on more constructor invocations than those in the wanted method.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- progressMonitorWorked(1);
- if (!isFurtherTraversalNecessary(node)) {
- return false;
- }
-
- if (isNodeWithinMethod(node)) {
- addMethodCall(node.resolveConstructorBinding(), node);
- }
-
- return true;
- }
-
- /**
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- progressMonitorWorked(1);
- return isFurtherTraversalNecessary(node);
- }
-
- /**
- * Find all method invocations from the called method. Since we only traverse into
- * the AST on the wanted method declaration, this method should not hit on more
- * method invocations than those in the wanted method.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- progressMonitorWorked(1);
- if (!isFurtherTraversalNecessary(node)) {
- return false;
- }
-
- if (isNodeWithinMethod(node)) {
- addMethodCall(node.resolveMethodBinding(), node);
- }
-
- return true;
- }
-
- /**
- * Find invocations of the supertype's constructor from the called method
- * (=constructor). Since we only traverse into the AST on the wanted method
- * declaration, this method should not hit on more method invocations than those in
- * the wanted method.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- progressMonitorWorked(1);
- if (!isFurtherTraversalNecessary(node)) {
- return false;
- }
-
- if (isNodeWithinMethod(node)) {
- addMethodCall(node.resolveConstructorBinding(), node);
- }
-
- return true;
- }
-
- /**
- * Find all method invocations from the called method. Since we only traverse into
- * the AST on the wanted method declaration, this method should not hit on more
- * method invocations than those in the wanted method.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- progressMonitorWorked(1);
- if (!isFurtherTraversalNecessary(node)) {
- return false;
- }
-
- if (isNodeWithinMethod(node)) {
- addMethodCall(node.resolveMethodBinding(), node);
- }
-
- return true;
- }
-
- /**
- * When an anonymous class declaration is reached, the traversal should not go further since it's not
- * supposed to consider calls inside the anonymous inner class as calls from the outer method.
- *
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- return isNodeEnclosingMethod(node);
- }
-
-
- /**
- * Adds the specified method binding to the search results.
- *
- * @param calledMethodBinding
- * @param node
- */
- protected void addMethodCall(IFunctionBinding calledMethodBinding, ASTNode node) {
- try {
- if (calledMethodBinding != null) {
- fProgressMonitor.worked(1);
-
- ITypeBinding calledTypeBinding = calledMethodBinding.getDeclaringClass();
- IType calledType = null;
-
- if (!calledTypeBinding.isAnonymous()) {
- calledType = (IType) calledTypeBinding.getJavaElement();
- } else {
- if (!"java.lang.Object".equals(calledTypeBinding.getSuperclass().getQualifiedName())) { //$NON-NLS-1$
- calledType= (IType) calledTypeBinding.getSuperclass().getJavaElement();
- }
- }
-
- IFunction calledMethod = findIncludingSupertypes(calledMethodBinding,
- calledType, fProgressMonitor);
-
- IMember referencedMember= null;
- if (calledMethod == null) {
- if (calledMethodBinding.isConstructor() && calledMethodBinding.getParameterTypes().length == 0) {
- referencedMember= calledType;
- }
- } else {
-
- if (!isIgnoredBySearchScope(calledMethod)) {
- referencedMember= calledMethod;
- }
- }
- final int position= node.getStartPosition();
- final int number= fCompilationUnit.getLineNumber(position);
- fSearchResults.addMember(fMethod, referencedMember, position, position + node.getLength(), number < 1 ? 1 : number);
- }
- } catch (JavaScriptModelException jme) {
- JavaScriptPlugin.log(jme);
- }
- }
-
- private static IFunction findIncludingSupertypes(IFunctionBinding method, IType type, IProgressMonitor pm) throws JavaScriptModelException {
- IFunction inThisType= Bindings.findMethod(method, type);
- if (inThisType != null)
- return inThisType;
- IType[] superTypes= JavaModelUtil.getAllSuperTypes(type, pm);
- for (int i= 0; i < superTypes.length; i++) {
- IFunction m= Bindings.findMethod(method, superTypes[i]);
- if (m != null)
- return m;
- }
- return null;
- }
-
- private boolean isIgnoredBySearchScope(IFunction enclosingElement) {
- if (enclosingElement != null) {
- return !getSearchScope().encloses(enclosingElement);
- } else {
- return false;
- }
- }
-
- private IJavaScriptSearchScope getSearchScope() {
- return CallHierarchy.getDefault().getSearchScope();
- }
-
- private boolean isNodeWithinMethod(ASTNode node) {
- int nodeStartPosition = node.getStartPosition();
- int nodeEndPosition = nodeStartPosition + node.getLength();
-
- if (nodeStartPosition < fMethodStartPosition) {
- return false;
- }
-
- if (nodeEndPosition > fMethodEndPosition) {
- return false;
- }
-
- return true;
- }
-
- private boolean isNodeEnclosingMethod(ASTNode node) {
- int nodeStartPosition = node.getStartPosition();
- int nodeEndPosition = nodeStartPosition + node.getLength();
-
- if (nodeStartPosition < fMethodStartPosition && nodeEndPosition > fMethodEndPosition) {
- // Is the method completely enclosed by the node?
- return true;
- }
- return false;
- }
-
- private boolean isFurtherTraversalNecessary(ASTNode node) {
- return isNodeWithinMethod(node) || isNodeEnclosingMethod(node);
- }
-
-// private IFunction findImplementingMethods(IFunction calledMethod) {
-// Collection implementingMethods = CallHierarchy.getDefault()
-// .getImplementingMethods(calledMethod);
-//
-// if ((implementingMethods.size() == 0) || (implementingMethods.size() > 1)) {
-// return calledMethod;
-// } else {
-// return (IFunction) implementingMethods.iterator().next();
-// }
-// }
-
- private void progressMonitorWorked(int work) {
- if (fProgressMonitor != null) {
- fProgressMonitor.worked(work);
- if (fProgressMonitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeMethodWrapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeMethodWrapper.java
deleted file mode 100644
index 5edcae0f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CalleeMethodWrapper.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-class CalleeMethodWrapper extends MethodWrapper {
- private Comparator fMethodWrapperComparator = new MethodWrapperComparator();
-
- private static class MethodWrapperComparator implements Comparator {
- /* (non-Javadoc)
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- */
- public int compare(Object o1, Object o2) {
- MethodWrapper m1 = (MethodWrapper) o1;
- MethodWrapper m2 = (MethodWrapper) o2;
-
- CallLocation callLocation1 = m1.getMethodCall().getFirstCallLocation();
- CallLocation callLocation2 = m2.getMethodCall().getFirstCallLocation();
-
- if ((callLocation1 != null) && (callLocation2 != null)) {
- if (callLocation1.getStart() == callLocation2.getStart()) {
- return callLocation1.getEnd() - callLocation2.getEnd();
- }
-
- return callLocation1.getStart() - callLocation2.getStart();
- }
-
- return 0;
- }
- }
-
- /**
- * Constructor for CalleeMethodWrapper.
- */
- public CalleeMethodWrapper(MethodWrapper parent, MethodCall methodCall) {
- super(parent, methodCall);
- }
-
- /* Returns the calls sorted after the call location
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#getCalls()
- */
- public MethodWrapper[] getCalls(IProgressMonitor progressMonitor) {
- MethodWrapper[] result = super.getCalls(progressMonitor);
- Arrays.sort(result, fMethodWrapperComparator);
-
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#getTaskName()
- */
- protected String getTaskName() {
- return CallHierarchyMessages.CalleeMethodWrapper_taskname;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#createMethodWrapper(org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodCall)
- */
- protected MethodWrapper createMethodWrapper(MethodCall methodCall) {
- return new CalleeMethodWrapper(this, methodCall);
- }
-
- /**
- * Find callees called from the current method.
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#findChildren(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected Map findChildren(IProgressMonitor progressMonitor) {
- if (getMember().exists() && getMember().getElementType() == IJavaScriptElement.METHOD) {
- JavaScriptUnit cu= CallHierarchy.getCompilationUnitNode(getMember(), true);
- if (progressMonitor != null) {
- progressMonitor.worked(5);
- }
-
- if (cu != null) {
- CalleeAnalyzerVisitor visitor = new CalleeAnalyzerVisitor((IFunction) getMember(),
- cu, progressMonitor);
-
- cu.accept(visitor);
- return visitor.getCallees();
- }
- }
- return new HashMap(0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallerMethodWrapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallerMethodWrapper.java
deleted file mode 100644
index 8a9059fb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallerMethodWrapper.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-class CallerMethodWrapper extends MethodWrapper {
- public CallerMethodWrapper(MethodWrapper parent, MethodCall methodCall) {
- super(parent, methodCall);
- }
-
- protected IJavaScriptSearchScope getSearchScope() {
- return CallHierarchy.getDefault().getSearchScope();
- }
-
- protected String getTaskName() {
- return CallHierarchyMessages.CallerMethodWrapper_taskname;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#createMethodWrapper(org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodCall)
- */
- protected MethodWrapper createMethodWrapper(MethodCall methodCall) {
- return new CallerMethodWrapper(this, methodCall);
- }
-
- /**
- * @return The result of the search for children
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper#findChildren(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected Map findChildren(IProgressMonitor progressMonitor) {
- try {
- MethodReferencesSearchRequestor searchRequestor= new MethodReferencesSearchRequestor();
- SearchEngine searchEngine= new SearchEngine();
-
- IProgressMonitor monitor= new SubProgressMonitor(progressMonitor, 95, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- IJavaScriptSearchScope defaultSearchScope= getSearchScope();
- boolean isWorkspaceScope= SearchEngine.createWorkspaceScope().equals(defaultSearchScope);
-
- for (Iterator iter= getMembers().iterator(); iter.hasNext();) {
- checkCanceled(progressMonitor);
-
- IMember member= (IMember) iter.next();
- SearchPattern pattern= SearchPattern.createPattern(member, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptSearchScope searchScope= isWorkspaceScope ? getAccurateSearchScope(defaultSearchScope, member) : defaultSearchScope;
- searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, searchRequestor,
- monitor);
- }
- return searchRequestor.getCallers();
-
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return new HashMap(0);
- }
- }
-
- private IJavaScriptSearchScope getAccurateSearchScope(IJavaScriptSearchScope defaultSearchScope, IMember member) throws JavaScriptModelException {
- if (! JdtFlags.isPrivate(member))
- return defaultSearchScope;
-
- if (member.getJavaScriptUnit() != null) {
- return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member.getJavaScriptUnit() });
- } else if (member.getClassFile() != null) {
- // member could be called from an inner class-> search
- // package fragment (see also bug 109053):
- return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT) });
- } else {
- return defaultSearchScope;
- }
- }
-
- /**
- * Returns a collection of IMember instances representing what to search for
- */
- private Collection getMembers() {
- Collection result = new ArrayList();
-
- result.add(getMember());
-
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java
deleted file mode 100644
index c50322f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.Collection;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IType;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IImplementorFinder {
-
- /**
- * Find implementors of the specified IType instance.
- */
- public abstract Collection findImplementingTypes(IType type,
- IProgressMonitor progressMonitor);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/Implementors.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/Implementors.java
deleted file mode 100644
index 6c3780d2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/Implementors.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class Implementors {
- private static Implementors fgInstance;
-
- /**
- * Returns the shared instance.
- */
- public static Implementors getInstance() {
- if (fgInstance == null) {
- fgInstance = new Implementors();
- }
-
- return fgInstance;
- }
-
- /**
- * Searches for implementors of the specified Java elements. Currently, only IFunction
- * instances are searched for. Also, only the first element of the elements
- * parameter is taken into consideration.
- *
- * @param elements
- *
- * @return An array of found implementing Java elements (currently only IFunction
- * instances)
- */
- public IJavaScriptElement[] searchForImplementors(IJavaScriptElement[] elements,
- IProgressMonitor progressMonitor) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java
deleted file mode 100644
index eb326c1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class JavaImplementorFinder implements IImplementorFinder {
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.callhierarchy.IImplementorFinder#findImplementingTypes(org.eclipse.wst.jsdt.core.IType, org.eclipse.core.runtime.IProgressMonitor)
- */
- public Collection findImplementingTypes(IType type, IProgressMonitor progressMonitor) {
- ITypeHierarchy typeHierarchy;
-
- try {
- typeHierarchy = type.newTypeHierarchy(progressMonitor);
-
- IType[] implementingTypes = typeHierarchy.getAllClasses();
- HashSet result = new HashSet(Arrays.asList(implementingTypes));
-
- return result;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodCall.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodCall.java
deleted file mode 100644
index 3efe7a50..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodCall.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IMember;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class MethodCall {
- private IMember fMember;
- private List fCallLocations;
-
- /**
- * @param enclosingElement
- */
- public MethodCall(IMember enclosingElement) {
- this.fMember = enclosingElement;
- }
-
- /**
- *
- */
- public Collection getCallLocations() {
- return fCallLocations;
- }
-
- public CallLocation getFirstCallLocation() {
- if ((fCallLocations != null) && !fCallLocations.isEmpty()) {
- return (CallLocation) fCallLocations.get(0);
- } else {
- return null;
- }
- }
-
- public boolean hasCallLocations() {
- return fCallLocations != null && fCallLocations.size() > 0;
- }
-
- /**
- * @return Object
- */
- public Object getKey() {
- return getMember().getHandleIdentifier();
- }
-
- /**
- *
- */
- public IMember getMember() {
- return fMember;
- }
-
- /**
- * @param location
- */
- public void addCallLocation(CallLocation location) {
- if (fCallLocations == null) {
- fCallLocations = new ArrayList();
- }
-
- fCallLocations.add(location);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodReferencesSearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodReferencesSearchRequestor.java
deleted file mode 100644
index 5eff1846..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodReferencesSearchRequestor.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-class MethodReferencesSearchRequestor extends SearchRequestor {
- private CallSearchResultCollector fSearchResults;
- private boolean fRequireExactMatch = true;
-
- MethodReferencesSearchRequestor() {
- fSearchResults = new CallSearchResultCollector();
- }
-
- public Map getCallers() {
- return fSearchResults.getCallers();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.wst.jsdt.core.search.SearchMatch)
- */
- public void acceptSearchMatch(SearchMatch match) {
- if (fRequireExactMatch && (match.getAccuracy() != SearchMatch.A_ACCURATE)) {
- return;
- }
-
- if (match.isInsideDocComment()) {
- return;
- }
-
- if (match.getElement() != null && match.getElement() instanceof IMember) {
- IMember member= (IMember) match.getElement();
- switch (member.getElementType()) {
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.INITIALIZER:
- fSearchResults.addMember(member, member, match.getOffset(), match.getOffset()+match.getLength());
- break;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodWrapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodWrapper.java
deleted file mode 100644
index efb9a939..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/MethodWrapper.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.callhierarchy;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.PlatformObject;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.internal.ui.callhierarchy.MethodWrapperWorkbenchAdapter;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public abstract class MethodWrapper extends PlatformObject {
- private Map fElements = null;
-
- /*
- * A cache of previously found methods. This cache should be searched
- * before adding a "new" method object reference to the list of elements.
- * This way previously found methods won't be searched again.
- */
- private Map fMethodCache;
- private MethodCall fMethodCall;
- private MethodWrapper fParent;
- private int fLevel;
-
- /**
- * Constructor CallerElement.
- */
- public MethodWrapper(MethodWrapper parent, MethodCall methodCall) {
- Assert.isNotNull(methodCall);
-
- if (parent == null) {
- setMethodCache(new HashMap());
- fLevel = 1;
- } else {
- setMethodCache(parent.getMethodCache());
- fLevel = parent.getLevel() + 1;
- }
-
- this.fMethodCall = methodCall;
- this.fParent = parent;
- }
-
- public Object getAdapter(Class adapter) {
- if (adapter == IJavaScriptElement.class) {
- return getMember();
- } else if (adapter == IWorkbenchAdapter.class){
- return new MethodWrapperWorkbenchAdapter(this);
- } else {
- return null;
- }
- }
-
- /**
- * @return the child caller elements of this element
- */
- public MethodWrapper[] getCalls(IProgressMonitor progressMonitor) {
- if (fElements == null) {
- doFindChildren(progressMonitor);
- }
-
- MethodWrapper[] result = new MethodWrapper[fElements.size()];
- int i = 0;
-
- for (Iterator iter = fElements.keySet().iterator(); iter.hasNext();) {
- MethodCall methodCall = getMethodCallFromMap(fElements, iter.next());
- result[i++] = createMethodWrapper(methodCall);
- }
-
- return result;
- }
-
- public int getLevel() {
- return fLevel;
- }
-
- public IMember getMember() {
- return getMethodCall().getMember();
- }
-
- public MethodCall getMethodCall() {
- return fMethodCall;
- }
-
- public String getName() {
- if (getMethodCall() != null) {
- return getMethodCall().getMember().getElementName();
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-
- public MethodWrapper getParent() {
- return fParent;
- }
-
- public boolean equals(Object oth) {
- if (this == oth) {
- return true;
- }
-
- if (oth == null) {
- return false;
- }
-
- if (oth instanceof MethodWrapperWorkbenchAdapter) {
- //Note: A MethodWrapper is equal to a referring MethodWrapperWorkbenchAdapter and vice versa (bug 101677).
- oth= ((MethodWrapperWorkbenchAdapter) oth).getMethodWrapper();
- }
-
- if (oth.getClass() != getClass()) {
- return false;
- }
-
- MethodWrapper other = (MethodWrapper) oth;
-
- if (this.fParent == null) {
- if (other.fParent != null) {
- return false;
- }
- } else {
- if (!this.fParent.equals(other.fParent)) {
- return false;
- }
- }
-
- if (this.getMethodCall() == null) {
- if (other.getMethodCall() != null) {
- return false;
- }
- } else {
- if (!this.getMethodCall().equals(other.getMethodCall())) {
- return false;
- }
- }
-
- return true;
- }
-
- public int hashCode() {
- final int PRIME = 1000003;
- int result = 0;
-
- if (fParent != null) {
- result = (PRIME * result) + fParent.hashCode();
- }
-
- if (getMethodCall() != null) {
- result = (PRIME * result) + getMethodCall().getMember().hashCode();
- }
-
- return result;
- }
-
- private void setMethodCache(Map methodCache) {
- fMethodCache = methodCache;
- }
-
- protected abstract String getTaskName();
-
- private void addCallToCache(MethodCall methodCall) {
- Map cachedCalls = lookupMethod(this.getMethodCall());
- cachedCalls.put(methodCall.getKey(), methodCall);
- }
-
- protected abstract MethodWrapper createMethodWrapper(MethodCall methodCall);
-
- private void doFindChildren(IProgressMonitor progressMonitor) {
- Map existingResults = lookupMethod(getMethodCall());
-
- if (existingResults != null) {
- fElements = new HashMap();
- fElements.putAll(existingResults);
- } else {
- initCalls();
-
- if (progressMonitor != null) {
- progressMonitor.beginTask(getTaskName(), 100);
- }
-
- try {
- performSearch(progressMonitor);
- } finally {
- if (progressMonitor != null) {
- progressMonitor.done();
- }
- }
-
- // ModalContext.run(getRunnableWithProgress(), true, getProgressMonitor(),
- // Display.getCurrent());
- }
- }
-
- /**
- * Determines if the method represents a recursion call (i.e. whether the
- * method call is already in the cache.)
- *
- * @return True if the call is part of a recursion
- */
- public boolean isRecursive() {
- MethodWrapper current = getParent();
-
- while (current != null) {
- if (getMember().getHandleIdentifier().equals(current.getMember()
- .getHandleIdentifier())) {
- return true;
- }
-
- current = current.getParent();
- }
-
- return false;
- }
-
- /**
- * This method finds the children of the current IFunction (either callers or
- * callees, depending on the concrete subclass.
- * @return The result of the search for children
- */
- protected abstract Map findChildren(IProgressMonitor progressMonitor);
-
- private Map getMethodCache() {
- return fMethodCache;
- }
-
- private void initCalls() {
- this.fElements = new HashMap();
-
- initCacheForMethod();
- }
-
- /**
- * Looks up a previously created search result in the "global" cache.
- * @return the List of previously found search results
- */
- private Map lookupMethod(MethodCall methodCall) {
- return (Map) getMethodCache().get(methodCall.getKey());
- }
-
- private void performSearch(IProgressMonitor progressMonitor) {
- fElements = findChildren(progressMonitor);
-
- for (Iterator iter = fElements.keySet().iterator(); iter.hasNext();) {
- checkCanceled(progressMonitor);
-
- MethodCall methodCall = getMethodCallFromMap(fElements, iter.next());
- addCallToCache(methodCall);
- }
- }
-
- private MethodCall getMethodCallFromMap(Map elements, Object key) {
- return (MethodCall) elements.get(key);
- }
-
- private void initCacheForMethod() {
- Map cachedCalls = new HashMap();
- getMethodCache().put(this.getMethodCall().getKey(), cachedCalls);
- }
-
- /**
- * Checks with the progress monitor to see whether the creation of the type hierarchy
- * should be canceled. Should be regularly called
- * so that the user can cancel.
- *
- * @exception OperationCanceledException if cancelling the operation has been requested
- * @see IProgressMonitor#isCanceled
- */
- protected void checkCanceled(IProgressMonitor progressMonitor) {
- if (progressMonitor != null && progressMonitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
-
- /**
- * Allows a visitor to traverse the call hierarchy. The visiting is stopped when
- * a recursive node is reached.
- *
- * @param visitor
- */
- public void accept(CallHierarchyVisitor visitor, IProgressMonitor progressMonitor) {
- if (getParent() != null && getParent().isRecursive()) {
- return;
- }
- checkCanceled(progressMonitor);
-
- visitor.preVisit(this);
- if (visitor.visit(this)) {
- MethodWrapper[] methodWrappers= getCalls(progressMonitor);
- for (int i= 0; i < methodWrappers.length; i++) {
- methodWrappers[i].accept(visitor, progressMonitor);
- }
- }
- visitor.postVisit(this);
-
- if (progressMonitor != null) {
- progressMonitor.worked(1);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java
deleted file mode 100644
index 2114b4ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class AddCustomConstructorOperation implements IWorkspaceRunnable {
-
- /** Should the resulting edit be applied? */
- private boolean fApply= true;
-
- /** The super constructor method binding */
- private final IFunctionBinding fBinding;
-
- /** The variable bindings to implement */
- private final IVariableBinding[] fBindings;
-
- /** The variable binding keys for which a constructor was generated */
- private final List fCreated= new ArrayList();
-
- /** The resulting text edit */
- private TextEdit fEdit= null;
-
- /** The insertion point, or <code>null</code> */
- private final IJavaScriptElement fInsert;
-
- /** Should the call to the super constructor be omitted? */
- private boolean fOmitSuper= false;
-
- /** Should the compilation unit content be saved? */
- private final boolean fSave;
-
- /** The code generation settings to use */
- private final CodeGenerationSettings fSettings;
-
- /** The type declaration to add the constructors to */
- private final IType fType;
-
- /** The compilation unit ast node */
- private final JavaScriptUnit fUnit;
-
- /** The visibility flags of the new constructor */
- private int fVisibility= 0;
-
- /**
- * Creates a new add custom constructor operation.
- *
- * @param type the type to add the methods to
- * @param insert the insertion point, or <code>null</code>
- * @param unit the compilation unit ast node
- * @param bindings the variable bindings to use in the constructor
- * @param binding the method binding of the super constructor
- * @param settings the code generation settings to use
- * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
- * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
- */
- public AddCustomConstructorOperation(final IType type, final IJavaScriptElement insert, final JavaScriptUnit unit, final IVariableBinding[] bindings, final IFunctionBinding binding, final CodeGenerationSettings settings, final boolean apply, final boolean save) {
- Assert.isNotNull(type);
- Assert.isNotNull(unit);
- Assert.isNotNull(bindings);
- Assert.isNotNull(settings);
- fType= type;
- fInsert= insert;
- fUnit= unit;
- fBindings= bindings;
- fBinding= binding;
- fSettings= settings;
- fSave= save;
- fApply= apply;
- }
-
- /**
- * Returns the resulting text edit.
- *
- * @return the resulting text edit
- */
- public final TextEdit getResultingEdit() {
- return fEdit;
- }
-
- /**
- * Returns the scheduling rule for this operation.
- *
- * @return the scheduling rule
- */
- public final ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * Returns the visibility modifier of the generated constructors.
- *
- * @return the visibility modifier
- */
- public final int getVisibility() {
- return fVisibility;
- }
-
- /**
- * Should the call to the super constructor be omitted?
- *
- * @return <code>true</code> to omit the call, <code>false</code> otherwise
- */
- public final boolean isOmitSuper() {
- return fOmitSuper;
- }
-
- /*
- * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(CodeGenerationMessages.AddCustomConstructorOperation_description);
- fCreated.clear();
- final IJavaScriptUnit unit= fType.getJavaScriptUnit();
- final CompilationUnitRewrite rewrite= new CompilationUnitRewrite(unit, fUnit);
- ITypeBinding binding= null;
- ListRewrite rewriter= null;
- if (fType.isAnonymous()) {
- final ClassInstanceCreation creation= (ClassInstanceCreation) ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), fType.getNameRange()), ClassInstanceCreation.class);
- if (creation != null) {
- binding= creation.resolveTypeBinding();
- final AnonymousClassDeclaration declaration= creation.getAnonymousClassDeclaration();
- if (declaration != null)
- rewriter= rewrite.getASTRewrite().getListRewrite(declaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- }
- } else {
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), fType.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null) {
- binding= declaration.resolveBinding();
- rewriter= rewrite.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
- }
- }
- if (binding != null && rewriter != null) {
- ITextFileBuffer buffer= null;
- IDocument document= null;
- try {
- if (!JavaModelUtil.isPrimary(unit))
- document= new Document(unit.getBuffer().getContents());
- else {
- buffer= RefactoringFileBuffers.acquire(unit);
- document= buffer.getDocument();
- }
- ASTNode insertion= null;
- if (fInsert instanceof IFunction)
- insertion= ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), ((IFunction) fInsert).getNameRange()), FunctionDeclaration.class);
- FunctionDeclaration stub= StubUtility2.createConstructorStub(rewrite.getCu(), rewrite.getASTRewrite(), rewrite.getImportRewrite(), binding, rewrite.getAST(), fOmitSuper ? null : fBinding, fBindings, fVisibility, fSettings);
- if (stub != null) {
- fCreated.addAll(Arrays.asList(fBindings));
- if (insertion != null)
- rewriter.insertBefore(stub, insertion, null);
- else
- rewriter.insertLast(stub, null);
- }
- final Change result= rewrite.createChange();
- if (result instanceof CompilationUnitChange) {
- final CompilationUnitChange change= (CompilationUnitChange) result;
- final TextEdit edit= change.getEdit();
- if (edit != null) {
- try {
- fEdit= edit;
- if (fApply)
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- if (fSave) {
- if (buffer != null)
- buffer.commit(new SubProgressMonitor(monitor, 1), true);
- else
- unit.getBuffer().setContents(document.get());
- }
- } catch (Exception exception) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, exception.getLocalizedMessage(), exception));
- }
- }
- }
- } finally {
- if (buffer != null)
- RefactoringFileBuffers.release(unit);
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Determines whether the call to the super constructor should be omitted.
- *
- * @param omit <code>true</code> to omit the call, <code>false</code> otherwise
- */
- public final void setOmitSuper(final boolean omit) {
- fOmitSuper= omit;
- }
-
- /**
- * Sets the visibility modifier of the generated constructors.
- *
- * @param visibility the visibility modifier
- */
- public final void setVisibility(final int visibility) {
- fVisibility= visibility;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java
deleted file mode 100644
index 809568a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class AddDelegateMethodsOperation implements IWorkspaceRunnable {
-
- /** Should the resulting edit be applied? */
- private boolean fApply= true;
-
- /** The method binding keys for which a method was generated */
- private final List fCreated= new ArrayList();
-
- /** The resulting text edit */
- private TextEdit fEdit= null;
-
- /** The insertion point, or <code>null</code> */
- private final IJavaScriptElement fInsert;
-
- /** The method binding keys to implement */
- private final String[] fMethodKeys;
-
- /** Should the compilation unit content be saved? */
- private final boolean fSave;
-
- /** The code generation settings to use */
- private final CodeGenerationSettings fSettings;
-
- /** The type declaration to add the methods to */
- private final IType fType;
-
- /** The compilation unit ast node */
- private final JavaScriptUnit fUnit;
-
- /** The variable binding keys to implement */
- private final String[] fVariableKeys;
-
- /**
- * Creates a new add delegate methods operation.
- *
- * @param type the type to add the methods to
- * @param insert the insertion point, or <code>null</code>
- * @param variableKeys the variable binding keys to implement
- * @param methodKeys the method binding keys to implement
- * @param settings the code generation settings to use
- * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
- * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
- */
- public AddDelegateMethodsOperation(final IType type, final IJavaScriptElement insert, final JavaScriptUnit unit, final String[] variableKeys, final String[] methodKeys, final CodeGenerationSettings settings, final boolean apply, final boolean save) {
- Assert.isNotNull(type);
- Assert.isNotNull(unit);
- Assert.isNotNull(variableKeys);
- Assert.isNotNull(methodKeys);
- Assert.isNotNull(settings);
- Assert.isTrue(variableKeys.length == methodKeys.length);
- fType= type;
- fInsert= insert;
- fUnit= unit;
- fVariableKeys= variableKeys;
- fMethodKeys= methodKeys;
- fSettings= settings;
- fSave= save;
- fApply= apply;
- }
-
- /**
- * Returns the method binding keys for which a method has been generated.
- *
- * @return the method binding keys
- */
- public final String[] getCreatedMethods() {
- final String[] keys= new String[fCreated.size()];
- fCreated.toArray(keys);
- return keys;
- }
-
- /**
- * Returns the resulting text edit.
- *
- * @return the resulting text edit
- */
- public final TextEdit getResultingEdit() {
- return fEdit;
- }
-
- /**
- * Returns the scheduling rule for this operation.
- *
- * @return the scheduling rule
- */
- public final ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /*
- * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(CodeGenerationMessages.AddDelegateMethodsOperation_monitor_message);
- fCreated.clear();
- final IJavaScriptUnit unit= fType.getJavaScriptUnit();
- final CompilationUnitRewrite rewrite= new CompilationUnitRewrite(unit, fUnit);
- ITypeBinding binding= null;
- ListRewrite rewriter= null;
- if (fType.isAnonymous()) {
- final ClassInstanceCreation creation= (ClassInstanceCreation) ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), fType.getNameRange()), ClassInstanceCreation.class);
- if (creation != null) {
- binding= creation.resolveTypeBinding();
- final AnonymousClassDeclaration declaration= creation.getAnonymousClassDeclaration();
- if (declaration != null)
- rewriter= rewrite.getASTRewrite().getListRewrite(declaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- }
- } else {
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), fType.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null) {
- binding= declaration.resolveBinding();
- rewriter= rewrite.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
- }
- }
- if (binding != null && rewriter != null) {
- final IBinding[][] bindings= StubUtility2.getDelegatableMethods(rewrite.getAST(), binding);
- if (bindings != null && bindings.length > 0) {
- ITextFileBuffer buffer= null;
- IDocument document= null;
- try {
- if (!JavaModelUtil.isPrimary(unit))
- document= new Document(unit.getBuffer().getContents());
- else {
- buffer= RefactoringFileBuffers.acquire(unit);
- document= buffer.getDocument();
- }
- ASTNode insertion= null;
- if (fInsert instanceof IFunction)
- insertion= ASTNodes.getParent(NodeFinder.perform(rewrite.getRoot(), ((IFunction) fInsert).getNameRange()), FunctionDeclaration.class);
- String variableKey= null;
- String methodKey= null;
- FunctionDeclaration stub= null;
- for (int index= 0; index < fMethodKeys.length; index++) {
- methodKey= fMethodKeys[index];
- variableKey= fVariableKeys[index];
- if (monitor.isCanceled())
- break;
- for (int offset= 0; offset < bindings.length; offset++) {
- if (bindings[offset][0].getKey().equals(variableKey) && bindings[offset][1].getKey().equals(methodKey)) {
- stub= StubUtility2.createDelegationStub(rewrite.getCu(), rewrite.getASTRewrite(), rewrite.getImportRewrite(), rewrite.getAST(), bindings[offset], fSettings);
- if (stub != null) {
- fCreated.add(methodKey);
- if (insertion != null)
- rewriter.insertBefore(stub, insertion, null);
- else
- rewriter.insertLast(stub, null);
- }
- break;
- }
- }
- }
- final Change result= rewrite.createChange();
- if (result instanceof CompilationUnitChange) {
- final CompilationUnitChange change= (CompilationUnitChange) result;
- final TextEdit edit= change.getEdit();
- if (edit != null) {
- try {
- fEdit= edit;
- if (fApply)
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- if (fSave) {
- if (buffer != null)
- buffer.commit(new SubProgressMonitor(monitor, 1), true);
- else
- unit.getBuffer().setContents(document.get());
- }
- } catch (Exception exception) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, exception.getLocalizedMessage(), exception));
- }
- }
- }
- } finally {
- if (buffer != null)
- RefactoringFileBuffers.release(unit);
- }
- }
- }
- } finally {
- monitor.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddGetterSetterOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddGetterSetterOperation.java
deleted file mode 100644
index a32d434a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddGetterSetterOperation.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class AddGetterSetterOperation implements IWorkspaceRunnable {
-
- /** The empty strings constant */
- private static final String[] EMPTY_STRINGS= new String[0];
-
- /** The accessor fields */
- private final IField[] fAccessorFields;
-
- /** Should the resulting edit be applied? */
- private boolean fApply= true;
-
- /** The resulting text edit */
- private TextEdit fEdit= null;
-
- /** The getter fields */
- private final IField[] fGetterFields;
-
- /** The insertion point, or <code>null</code> */
- private final IJavaScriptElement fInsert;
-
- /** Should the compilation unit content be saved? */
- private final boolean fSave;
-
- /** The setter fields */
- private final IField[] fSetterFields;
-
- /** The code generation settings to use */
- private final CodeGenerationSettings fSettings;
-
- /** Should all existing members be skipped? */
- private boolean fSkipAllExisting= false;
-
- /** The skip existing request query */
- private final IRequestQuery fSkipExistingQuery;
-
- /** Should the accessors be sorted? */
- private boolean fSort= false;
-
- /** The type declaration to add the constructors to */
- private final IType fType;
-
- /** The compilation unit ast node */
- private final JavaScriptUnit fASTRoot;
-
- /** The visibility flags of the new accessors */
- private int fVisibility= Modifier.PUBLIC;
-
- /**
- * Creates a new add getter setter operation.
- *
- * @param type the type to add the accessors to
- * @param getters the fields to create getters for
- * @param setters the fields to create setters for
- * @param accessors the fields to create both
- * @param unit the compilation unit ast node
- * @param skipExistingQuery the request query
- * @param insert the insertion point, or <code>null</code>
- * @param settings the code generation settings to use
- * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
- * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
- */
- public AddGetterSetterOperation(final IType type, final IField[] getters, final IField[] setters, final IField[] accessors, final JavaScriptUnit unit, final IRequestQuery skipExistingQuery, final IJavaScriptElement insert, final CodeGenerationSettings settings, final boolean apply, final boolean save) {
- Assert.isNotNull(type);
- Assert.isNotNull(unit);
- Assert.isNotNull(settings);
- fType= type;
- fGetterFields= getters;
- fSetterFields= setters;
- fAccessorFields= accessors;
- fASTRoot= unit;
- fSkipExistingQuery= skipExistingQuery;
- fInsert= insert;
- fSettings= settings;
- fSave= save;
- fApply= apply;
- }
-
- /**
- * Adds a new accessor for the specified field.
- *
- * @param type the type
- * @param field the field
- * @param contents the contents of the accessor method
- * @param rewrite the list rewrite to use
- * @param insertion the insertion point
- * @throws JavaScriptModelException if an error occurs
- */
- private void addNewAccessor(final IType type, final IField field, final String contents, final ListRewrite rewrite, final ASTNode insertion) throws JavaScriptModelException {
- final String delimiter= StubUtility.getLineDelimiterUsed(type);
- final FunctionDeclaration declaration= (FunctionDeclaration) rewrite.getASTRewrite().createStringPlaceholder(CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, contents, 0, null, delimiter, field.getJavaScriptProject()), ASTNode.FUNCTION_DECLARATION);
- if (insertion != null)
- rewrite.insertBefore(declaration, insertion, null);
- else
- rewrite.insertLast(declaration, null);
- }
-
- /**
- * Generates a new getter method for the specified field
- *
- * @param field the field
- * @param rewrite the list rewrite to use
- * @throws CoreException if an error occurs
- * @throws OperationCanceledException if the operation has been cancelled
- */
- private void generateGetterMethod(final IField field, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
- final IType type= field.getDeclaringType();
- final String name= GetterSetterUtil.getGetterName(field, null);
- final IFunction existing= JavaModelUtil.findMethod(name, EMPTY_STRINGS, false, type);
- if (existing == null || !querySkipExistingMethods(existing)) {
- IJavaScriptElement sibling= null;
- if (existing != null) {
- sibling= StubUtility.findNextSibling(existing);
- removeExistingAccessor(existing, rewrite);
- } else
- sibling= fInsert;
- ASTNode insertion= null;
- if (sibling instanceof IFunction)
- insertion= ASTNodes.getParent(NodeFinder.perform(rewrite.getParent().getRoot(), ((IFunction) fInsert).getNameRange()), FunctionDeclaration.class);
- addNewAccessor(type, field, GetterSetterUtil.getGetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
- }
- }
-
- /**
- * Generates a new setter method for the specified field
- *
- * @param field the field
- * @param astRewrite
- * @param rewrite the list rewrite to use
- * @throws CoreException if an error occurs
- * @throws OperationCanceledException if the operation has been cancelled
- */
- private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
- final IType type= field.getDeclaringType();
- final String name= GetterSetterUtil.getSetterName(field, null);
- final IFunction existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
- if (existing == null || querySkipExistingMethods(existing)) {
- IJavaScriptElement sibling= null;
- if (existing != null) {
- sibling= StubUtility.findNextSibling(existing);
- removeExistingAccessor(existing, rewrite);
- } else
- sibling= fInsert;
- ASTNode insertion= null;
- if (sibling instanceof IFunction)
- insertion= ASTNodes.getParent(NodeFinder.perform(fASTRoot, ((IFunction) fInsert).getNameRange()), FunctionDeclaration.class);
- addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
- }
- }
-
- /**
- * Returns the resulting text edit.
- *
- * @return the resulting text edit
- */
- public final TextEdit getResultingEdit() {
- return fEdit;
- }
-
- /**
- * Returns the scheduling rule for this operation.
- *
- * @return the scheduling rule
- */
- public final ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * Returns the visibility modifier of the generated constructors.
- *
- * @return the visibility modifier
- */
- public final int getVisibility() {
- return fVisibility;
- }
-
- /**
- * Should all existing members be skipped?
- *
- * @return <code>true</code> if they should be skipped, <code>false</code> otherwise
- */
- public final boolean isSkipAllExisting() {
- return fSkipAllExisting;
- }
-
- /**
- * Queries the user whether to skip existing methods.
- *
- * @param method the method in question
- * @return <code>true</code> to skip existing methods, <code>false</code> otherwise
- * @throws OperationCanceledException if the operation has been cancelled
- */
- private boolean querySkipExistingMethods(final IFunction method) throws OperationCanceledException {
- if (!fSkipAllExisting) {
- switch (fSkipExistingQuery.doQuery(method)) {
- case IRequestQuery.CANCEL:
- throw new OperationCanceledException();
- case IRequestQuery.NO:
- return false;
- case IRequestQuery.YES_ALL:
- fSkipAllExisting= true;
- }
- }
- return true;
- }
-
- /**
- * Removes an existing accessor method.
- *
- * @param accessor the accessor method to remove
- * @param rewrite the list rewrite to use
- * @throws JavaScriptModelException if an error occurs
- */
- private void removeExistingAccessor(final IFunction accessor, final ListRewrite rewrite) throws JavaScriptModelException {
- final FunctionDeclaration declaration= (FunctionDeclaration) ASTNodes.getParent(NodeFinder.perform(rewrite.getParent().getRoot(), accessor.getNameRange()), FunctionDeclaration.class);
- if (declaration != null)
- rewrite.remove(declaration, null);
- }
-
- /*
- * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.setTaskName(CodeGenerationMessages.AddGetterSetterOperation_description);
- monitor.beginTask("", fGetterFields.length + fSetterFields.length); //$NON-NLS-1$
- final IJavaScriptUnit unit= fType.getJavaScriptUnit();
- final ASTRewrite astRewrite= ASTRewrite.create(fASTRoot.getAST());
- ListRewrite listRewriter= null;
- if (fType.isAnonymous()) {
- final ClassInstanceCreation creation= (ClassInstanceCreation) ASTNodes.getParent(NodeFinder.perform(fASTRoot, fType.getNameRange()), ClassInstanceCreation.class);
- if (creation != null) {
- final AnonymousClassDeclaration declaration= creation.getAnonymousClassDeclaration();
- if (declaration != null)
- listRewriter= astRewrite.getListRewrite(declaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- }
- } else {
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fASTRoot, fType.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null)
- listRewriter= astRewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
- }
- if (listRewriter == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, CodeGenerationMessages.AddGetterSetterOperation_error_input_type_not_found, null));
- }
-
- fSkipAllExisting= (fSkipExistingQuery == null);
- if (!fSort) {
- for (int index= 0; index < fAccessorFields.length; index++) {
- generateGetterMethod(fAccessorFields[index], listRewriter);
- generateSetterMethod(fAccessorFields[index], astRewrite, listRewriter);
- monitor.worked(1);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
- }
- for (int index= 0; index < fGetterFields.length; index++) {
- generateGetterMethod(fGetterFields[index], listRewriter);
- monitor.worked(1);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
- for (int index= 0; index < fSetterFields.length; index++) {
- generateSetterMethod(fSetterFields[index], astRewrite, listRewriter);
- monitor.worked(1);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
- fEdit= astRewrite.rewriteAST();
- if (fApply) {
- JavaModelUtil.applyEdit(unit, fEdit, fSave, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Determines whether existing members should be skipped.
- *
- * @param skip <code>true</code> to skip existing members, <code>false</code> otherwise
- */
- public final void setSkipAllExisting(final boolean skip) {
- fSkipAllExisting= skip;
- }
-
- public void setSort(boolean sort) {
- fSort= sort;
- }
-
- /**
- * Sets the visibility modifier of the generated constructors.
- *
- * @param visibility the visibility modifier
- */
- public final void setVisibility(final int visibility) {
- fVisibility= visibility;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddImportsOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddImportsOperation.java
deleted file mode 100644
index 93b6f6b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddImportsOperation.java
+++ /dev/null
@@ -1,406 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeNameMatchCollector;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.SimilarElementsRequestor;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class AddImportsOperation implements IWorkspaceRunnable {
-
- public static interface IChooseImportQuery {
- /**
- * Selects an import from a list of choices.
- * @param openChoices Array of found types
- * @param containerName Name type to be imported
- * @return Returns <code>null</code> to cancel the operation, or the
- * selected imports.
- */
- TypeNameMatch chooseImport(TypeNameMatch[] openChoices, String containerName);
- }
-
- private IJavaScriptUnit fCompilationUnit;
- private final int fSelectionOffset;
- private final int fSelectionLength;
- private final IChooseImportQuery fQuery;
- private IStatus fStatus;
- private boolean fDoSave;
-
-
- /**
- * Generate import statements for the passed java elements
- * Elements must be of type IType (-> single import) or IPackageFragment
- * (on-demand-import). Other JavaElements are ignored
- * @param cu The compilation unit
- * @param selectionOffset Start of the current text selection
- * @param selectionLength End of the current text selection
- * @param query Query element to be used for UI interaction or <code>null</code> to not select anything
- * when multiple possibilities are available
- * @param save If set, the result will be saved
- */
- public AddImportsOperation(IJavaScriptUnit cu, int selectionOffset, int selectionLength, IChooseImportQuery query, boolean save) {
- super();
- Assert.isNotNull(cu);
-
- fCompilationUnit= cu;
- fSelectionOffset= selectionOffset;
- fSelectionLength= selectionLength;
- fQuery= query;
- fStatus= Status.OK_STATUS;
- fDoSave= save;
- }
-
- /**
- * @return Returns the status.
- */
- public IStatus getStatus() {
- return fStatus;
- }
-
- /**
- * Runs the operation.
- * @param monitor The progress monitor
- * @throws CoreException
- * @throws OperationCanceledException Runtime error thrown when operation is canceled.
- */
- public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- try {
- monitor.beginTask(CodeGenerationMessages.AddImportsOperation_description, 4);
-
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(fCompilationUnit, ASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 1));
-
- ImportRewrite importRewrite= StubUtility.createImportRewrite(astRoot, true);
-
- MultiTextEdit res= new MultiTextEdit();
-
- TextEdit edit= evaluateEdits(astRoot, importRewrite, fSelectionOffset, fSelectionLength, new SubProgressMonitor(monitor, 1));
- if (edit == null) {
- return;
- }
- res.addChild(edit);
-
- TextEdit importsEdit= importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
- res.addChild(importsEdit);
-
- JavaModelUtil.applyEdit(fCompilationUnit, res, fDoSave, new SubProgressMonitor(monitor, 1));
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- } finally {
- monitor.done();
- }
- }
-
- private TextEdit evaluateEdits(JavaScriptUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws BadLocationException, JavaScriptModelException {
- SimpleName nameNode= null;
- if (root != null) { // got an AST
- ASTNode node= NodeFinder.perform(root, offset, length);
-
- if (node instanceof QualifiedName) {
- nameNode= ((QualifiedName) node).getName();
- } else if (node instanceof SimpleName) {
- nameNode= (SimpleName) node;
- }
- }
-
- String name, simpleName, containerName;
- int qualifierStart;
- int simpleNameStart;
- if (nameNode != null) {
- simpleName= nameNode.getIdentifier();
- simpleNameStart= nameNode.getStartPosition();
- if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
- Name qualifier= ((QualifiedName) nameNode.getParent()).getQualifier();
- containerName= qualifier.getFullyQualifiedName();
- name= JavaModelUtil.concatenateName(containerName, simpleName);
- qualifierStart= qualifier.getStartPosition();
- } else if (nameNode.getParent().getLocationInParent() == QualifiedType.NAME_PROPERTY) {
- Type qualifier= ((QualifiedType) nameNode.getParent().getParent()).getQualifier();
- containerName= ASTNodes.asString(qualifier);
- name= JavaModelUtil.concatenateName(containerName, simpleName);
- qualifierStart= qualifier.getStartPosition();
- } else if (nameNode.getLocationInParent() == FunctionInvocation.NAME_PROPERTY) {
- ASTNode qualifier= ((FunctionInvocation) nameNode.getParent()).getExpression();
- if (qualifier instanceof Name) {
- containerName= ASTNodes.asString(qualifier);
- name= JavaModelUtil.concatenateName(containerName, simpleName);
- qualifierStart= qualifier.getStartPosition();
- } else {
- return null;
- }
- } else {
- containerName= ""; //$NON-NLS-1$
- name= simpleName;
- qualifierStart= simpleNameStart;
- }
-
- IBinding binding= nameNode.resolveBinding();
- if (binding != null && !binding.isRecovered()) {
- if (binding instanceof ITypeBinding) {
- ITypeBinding typeBinding= (ITypeBinding) binding;
- String qualifiedBindingName= typeBinding.getQualifiedName();
- if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
- return null;
- }
-
- String res= importRewrite.addImport(typeBinding);
- if (containerName.length() > 0 && !res.equals(simpleName)) {
- // adding import failed
- return null;
- }
- return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
- } else if (binding instanceof IVariableBinding || binding instanceof IFunctionBinding) {
- boolean isField= binding instanceof IVariableBinding;
- ITypeBinding declaringClass= isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IFunctionBinding) binding).getDeclaringClass();
- if (declaringClass == null) {
- return null; // variableBinding.getDeclaringClass() is null for array.length
- }
- if (Modifier.isStatic(binding.getModifiers())) {
- if (Modifier.isPrivate(declaringClass.getModifiers())) {
- fStatus= JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, declaringClass.getName()), null);
- return null;
- }
-
- if (containerName.length() > 0) {
- if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName()) ) {
- String res= importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
- if (!res.equals(simpleName)) {
- // adding import failed
- return null;
- }
- return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, ""); //$NON-NLS-1$
- }
- }
- }
- return null; // no static imports for packages
- } else {
- return null;
- }
- }
- if (binding != null && binding.getKind() != IBinding.TYPE) {
- // recovered binding
- return null;
- }
-
- } else {
- IBuffer buffer= fCompilationUnit.getBuffer();
-
- qualifierStart= getNameStart(buffer, offset);
- int nameEnd= getNameEnd(buffer, offset + length);
- int len= nameEnd - qualifierStart;
- name= buffer.getText(qualifierStart, len).trim();
- if (name.length() == 0) {
- return null;
- }
-
- simpleName= Signature.getSimpleName(name);
- containerName= Signature.getQualifier(name);
-
- simpleNameStart= getSimpleNameStart(buffer, qualifierStart, containerName);
-
- int res= importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
- if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
- fStatus= JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
- return null;
- } else if (res == ImportRewriteContext.RES_NAME_FOUND) {
- return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, ""); //$NON-NLS-1$
- }
- }
- IJavaScriptSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { fCompilationUnit.getJavaScriptProject() });
-
- TypeNameMatch[] types= findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
- if (types.length == 0) {
- fStatus= JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, simpleName), null);
- return null;
- }
-
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- TypeNameMatch chosen;
- if (types.length > 1 && fQuery != null) {
- chosen= fQuery.chooseImport(types, containerName);
- if (chosen == null) {
- throw new OperationCanceledException();
- }
- } else {
- chosen= types[0];
- }
- importRewrite.addImport(chosen.getFullyQualifiedName());
- return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, ""); //$NON-NLS-1$
- }
-
-
- private int getNameStart(IBuffer buffer, int pos) throws BadLocationException {
- while (pos > 0) {
- char ch= buffer.getChar(pos - 1);
- if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
- return pos;
- }
- pos--;
- }
- return pos;
- }
-
- private int getNameEnd(IBuffer doc, int pos) throws BadLocationException {
- if (pos > 0) {
- if (Character.isWhitespace(doc.getChar(pos - 1))) {
- return pos;
- }
- }
- int len= doc.getLength();
- while (pos < len) {
- char ch= doc.getChar(pos);
- if (!Character.isJavaIdentifierPart(ch)) {
- return pos;
- }
- pos++;
- }
- return pos;
- }
-
- private int getSimpleNameStart(IBuffer buffer, int nameStart, String containerName) throws BadLocationException {
- int containerLen= containerName.length();
- int docLen= buffer.getLength();
- if ((containerLen > 0) && (nameStart + containerLen + 1 < docLen)) {
- for (int k= 0; k < containerLen; k++) {
- if (buffer.getChar(nameStart + k) != containerName.charAt(k)) {
- return nameStart;
- }
- }
- if (buffer.getChar(nameStart + containerLen) == '.') {
- return nameStart + containerLen + 1;
- }
- }
- return nameStart;
- }
-
- private int getSearchForConstant(int typeKinds) {
- final int CLASSES= SimilarElementsRequestor.CLASSES;
-
- switch (typeKinds & (CLASSES)) {
- case CLASSES: return IJavaScriptSearchConstants.CLASS;
- default: return IJavaScriptSearchConstants.TYPE;
- }
- }
-
-
- /*
- * Finds a type by the simple name.
- */
- private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaScriptSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor) throws JavaScriptModelException {
- boolean is50OrHigher= JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaScriptProject());
-
- int typeKinds= SimilarElementsRequestor.ALL_TYPES;
- if (nameNode != null) {
- typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
- }
-
- ArrayList typeInfos= new ArrayList();
- TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
- int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
- new SearchEngine().searchAllTypeNames(null, matchMode, simpleTypeName.toCharArray(), matchMode, getSearchForConstant(typeKinds), searchScope, requestor, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
-
- ArrayList typeRefsFound= new ArrayList(typeInfos.size());
- for (int i= 0, len= typeInfos.size(); i < len; i++) {
- TypeNameMatch curr= (TypeNameMatch) typeInfos.get(i);
- if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
- if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr)) {
- typeRefsFound.add(curr);
- }
- }
- }
- return (TypeNameMatch[]) typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
- }
-
- private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) {
- return (typeKinds & SimilarElementsRequestor.CLASSES) != 0;
- }
-
-
- private boolean isVisible(TypeNameMatch curr) {
- int flags= curr.getModifiers();
- if (Flags.isPrivate(flags)) {
- return false;
- }
- if (Flags.isPublic(flags)) {
- return true;
- }
- return curr.getPackageName().equals(fCompilationUnit.getParent().getElementName());
- }
-
-
- /**
- * @return Returns the scheduling rule for this operation
- */
- public ISchedulingRule getScheduleRule() {
- return fCompilationUnit.getJavaScriptProject().getResource();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java
deleted file mode 100644
index 70c57050..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class AddJavaDocStubOperation implements IWorkspaceRunnable {
-
- private IMember[] fMembers;
-
- public AddJavaDocStubOperation(IMember[] members) {
- super();
- fMembers= members;
- }
-
- private String createTypeComment(IType type, String lineDelimiter) throws CoreException {
- return CodeGeneration.getTypeComment(type.getJavaScriptUnit(), type.getTypeQualifiedName('.'), lineDelimiter);
- }
-
- private String createMethodComment(IFunction meth, String lineDelimiter) throws CoreException {
- IType declaringType= meth.getDeclaringType();
-
- IFunction overridden= null;
- if (!meth.isConstructor() && declaringType!=null) {
- ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType);
- MethodOverrideTester tester= new MethodOverrideTester(declaringType, hierarchy);
- overridden= tester.findOverriddenMethod(meth, true);
- }
- return CodeGeneration.getMethodComment(meth, overridden, lineDelimiter);
- }
-
- private String createFieldComment(IField field, String lineDelimiter) throws JavaScriptModelException, CoreException {
- String typeName= Signature.toString(field.getTypeSignature());
- String fieldName= field.getElementName();
- return CodeGeneration.getFieldComment(field.getJavaScriptUnit(), typeName, fieldName, lineDelimiter);
- }
-
- /**
- * @return Returns the scheduling rule for this operation
- */
- public ISchedulingRule getScheduleRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * Runs the operation.
- * @throws OperationCanceledException Runtime error thrown when operation is cancelled.
- */
- public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- if (fMembers.length == 0) {
- return;
- }
- try {
- monitor.beginTask(CodeGenerationMessages.AddJavaDocStubOperation_description, fMembers.length + 2);
-
- addJavadocComments(monitor);
- } finally {
- monitor.done();
- }
- }
- /* moved this so we this can be re-used in web component */
-
- protected IDocument getDocument(IJavaScriptUnit cu, IProgressMonitor monitor) throws CoreException {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- IPath path= cu.getPath();
- try {
- manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
- return manager.getTextFileBuffer(path).getDocument();
-
-
- }finally {
- manager.disconnect(path, LocationKind.IFILE,new SubProgressMonitor(monitor, 1));
- }
- }
-
- private void addJavadocComments(IProgressMonitor monitor) throws CoreException {
- IJavaScriptUnit cu= fMembers[0].getJavaScriptUnit();
-
-
- try {
- IDocument document= getDocument(cu,monitor);
-
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
- MultiTextEdit edit= new MultiTextEdit();
-
- for (int i= 0; i < fMembers.length; i++) {
- IMember curr= fMembers[i];
- int memberStartOffset= getMemberStartOffset(curr, document);
-
- String comment= null;
- switch (curr.getElementType()) {
- case IJavaScriptElement.TYPE:
- comment= createTypeComment((IType) curr, lineDelim);
- break;
- case IJavaScriptElement.FIELD:
- comment= createFieldComment((IField) curr, lineDelim);
- break;
- case IJavaScriptElement.METHOD:
- comment= createMethodComment((IFunction) curr, lineDelim);
- break;
- }
- if (comment == null) {
- StringBuffer buf= new StringBuffer();
- buf.append("/**").append(lineDelim); //$NON-NLS-1$
- buf.append(" *").append(lineDelim); //$NON-NLS-1$
- buf.append(" */").append(lineDelim); //$NON-NLS-1$
- comment= buf.toString();
- } else {
- if (!comment.endsWith(lineDelim)) {
- comment= comment + lineDelim;
- }
- }
-
- final IJavaScriptProject project= cu.getJavaScriptProject();
- IRegion region= document.getLineInformationOfOffset(memberStartOffset);
-
- String line= document.get(region.getOffset(), region.getLength());
- String indentString= Strings.getIndentString(line, project);
-
- String indentedComment= Strings.changeIndent(comment, 0, project, indentString, lineDelim);
-
- edit.addChild(new InsertEdit(memberStartOffset, indentedComment));
-
- monitor.worked(1);
- }
- edit.apply(document); // apply all edits
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- } finally {
-
- }
- }
-
- private int getMemberStartOffset(IMember curr, IDocument document) throws JavaScriptModelException {
- int offset= curr.getSourceRange().getOffset();
- TokenScanner scanner= new TokenScanner(document, curr.getJavaScriptProject());
- try {
- return scanner.getNextStartOffset(offset, true); // read to the first real non comment token
- } catch (CoreException e) {
- // ignore
- }
- return offset;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java
deleted file mode 100644
index b7e9b9fe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class AddUnimplementedConstructorsOperation implements IWorkspaceRunnable {
-
- /** Should the resulting edit be applied? */
- private final boolean fApply;
-
- /** The qualified names of the generated imports */
- private String[] fCreatedImports;
-
- /** The method binding keys for which a constructor was generated */
- private final List fCreatedMethods= new ArrayList();
-
- /** Should the import edits be applied? */
- private final boolean fImports;
-
- /** The insertion point, or <code>-1</code> */
- private final int fInsertPos;
-
- /** The method bindings to implement */
- private final IFunctionBinding[] fConstructorsToImplement;
-
- /** Should the call to the super constructor be omitted? */
- private boolean fOmitSuper;
-
- /** Should the compilation unit content be saved? */
- private final boolean fSave;
-
- /** Specified if comments should be created */
- private boolean fCreateComments;
-
- /** The type declaration to add the constructors to */
- private final ITypeBinding fType;
-
- /** The compilation unit AST node */
- private final JavaScriptUnit fASTRoot;
-
- /** The visibility flags of the new constructor */
- private int fVisibility;
-
- /**
- * Creates a new add unimplemented constructors operation.
- *
- * @param astRoot the compilation unit AST node
- * @param type the type to add the methods to
- * @param constructorsToImplement the method binding keys to implement
- * @param insertPos the insertion point, or <code>-1</code>
- * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
- * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
- * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
- */
- public AddUnimplementedConstructorsOperation(JavaScriptUnit astRoot, ITypeBinding type, IFunctionBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
- if (astRoot == null || !(astRoot.getJavaElement() instanceof IJavaScriptUnit)) {
- throw new IllegalArgumentException("AST must not be null and has to be created from a IJavaScriptUnit"); //$NON-NLS-1$
- }
- if (type == null) {
- throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
- }
- ASTNode node= astRoot.findDeclaringNode(type);
- if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
- throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
- }
-
- fType= type;
- fInsertPos= insertPos;
- fASTRoot= astRoot;
- fConstructorsToImplement= constructorsToImplement;
- fSave= save;
- fApply= apply;
- fImports= imports;
-
- fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaScriptProject());
- fVisibility= Modifier.PUBLIC;
- fOmitSuper= false;
- }
-
- /**
- * Returns the method binding keys for which a constructor has been generated.
- *
- * @return the method binding keys
- */
- public String[] getCreatedConstructors() {
- final String[] keys= new String[fCreatedMethods.size()];
- fCreatedMethods.toArray(keys);
- return keys;
- }
-
- /**
- * Returns the qualified names of the generated imports.
- *
- * @return the generated imports
- */
- public String[] getCreatedImports() {
- return fCreatedImports;
- }
-
- /**
- * Returns the scheduling rule for this operation.
- *
- * @return the scheduling rule
- */
- public ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * Returns the visibility of the constructors.
- *
- * @return the visibility
- */
- public int getVisibility() {
- return fVisibility;
- }
-
- /**
- * Returns whether the super call should be omitted.
- *
- * @return <code>true</code> to omit the super call, <code>false</code> otherwise
- */
- public boolean isOmitSuper() {
- return fOmitSuper;
- }
-
- /**
- * Determines whether to create comments.
- * @param comments <code>true</code> to create comments, <code>false</code> otherwise
- */
- public void setCreateComments(final boolean comments) {
- fCreateComments= comments;
- }
-
- /*
- * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask("", 2); //$NON-NLS-1$
- monitor.setTaskName(CodeGenerationMessages.AddUnimplementedMethodsOperation_description);
- fCreatedMethods.clear();
- IJavaScriptUnit cu= (IJavaScriptUnit) fASTRoot.getJavaElement();
-
- AST ast= fASTRoot.getAST();
-
- ASTRewrite astRewrite= ASTRewrite.create(ast);
- ImportRewrite importRewrite= StubUtility.createImportRewrite(fASTRoot, true);
-
- ITypeBinding currTypeBinding= fType;
- ListRewrite memberRewriter= null;
-
- ASTNode node= fASTRoot.findDeclaringNode(currTypeBinding);
- if (node instanceof AnonymousClassDeclaration) {
- memberRewriter= astRewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- } else if (node instanceof AbstractTypeDeclaration) {
- ChildListPropertyDescriptor property= ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty();
- memberRewriter= astRewrite.getListRewrite(node, property);
- } else {
- throw new IllegalArgumentException();
- // not possible, we checked this in the constructor
- }
-
- final CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaScriptProject());
- settings.createComments= fCreateComments;
-
- ASTNode insertion= getNodeToInsertBefore(memberRewriter);
-
- IFunctionBinding[] toImplement= fConstructorsToImplement;
- if (toImplement == null) {
- toImplement= StubUtility2.getVisibleConstructors(currTypeBinding, true, true);
- }
-
- int deprecationCount= 0;
- for (int i= 0; i < toImplement.length; i++) {
- if (toImplement[i].isDeprecated())
- deprecationCount++;
- }
- boolean createDeprecated= deprecationCount == toImplement.length;
- for (int i= 0; i < toImplement.length; i++) {
- IFunctionBinding curr= toImplement[i];
- if (!curr.isDeprecated() || createDeprecated) {
- FunctionDeclaration stub= StubUtility2.createConstructorStub(cu, astRewrite, importRewrite, curr, currTypeBinding.getName(), fVisibility, fOmitSuper, true, settings);
- if (stub != null) {
- fCreatedMethods.add(curr.getKey());
- if (insertion != null)
- memberRewriter.insertBefore(stub, insertion, null);
- else
- memberRewriter.insertLast(stub, null);
- }
- }
- }
- MultiTextEdit edit= new MultiTextEdit();
-
- TextEdit importEdits= importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
- fCreatedImports= importRewrite.getCreatedImports();
- if (fImports) {
- edit.addChild(importEdits);
- }
- edit.addChild(astRewrite.rewriteAST());
-
- if (fApply) {
- JavaModelUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Determines whether the super call should be omitted.
- *
- * @param omit <code>true</code> to omit the super call, <code>false</code> otherwise
- */
- public void setOmitSuper(final boolean omit) {
- fOmitSuper= omit;
- }
-
- /**
- * Determines the visibility of the constructors.
- *
- * @param visibility the visibility
- */
- public void setVisibility(final int visibility) {
- fVisibility= visibility;
- }
-
- private ASTNode getNodeToInsertBefore(ListRewrite rewriter) {
- if (fInsertPos != -1) {
- List members= rewriter.getOriginalList();
- for (int i= 0; i < members.size(); i++) {
- ASTNode curr= (ASTNode) members.get(i);
- if (curr.getStartPosition() >= fInsertPos) {
- return curr;
- }
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java
deleted file mode 100644
index 58da9140..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class AddUnimplementedMethodsOperation implements IWorkspaceRunnable {
-
- /** Should the resulting edit be applied? */
- private final boolean fApply;
-
- /** The qualified names of the generated imports */
- private String[] fCreatedImports;
-
- /** The method binding keys for which a method was generated */
- private final List fCreatedMethods= new ArrayList();
-
- /** Should the import edits be applied? */
- private final boolean fImports;
-
- /** The insertion point, or <code>-1</code> */
- private final int fInsertPos;
-
- /** The method bindings to implement */
- private final IFunctionBinding[] fMethodsToImplement;
-
- /** Should the compilation unit content be saved? */
- private final boolean fSave;
-
- /** Specified if comments should be created */
- private boolean fDoCreateComments;
-
- /** The type declaration to add the methods to */
- private final ITypeBinding fType;
-
- /** The compilation unit AST node */
- private final JavaScriptUnit fASTRoot;
-
- /**
- * Creates a new add unimplemented methods operation.
- *
- * @param astRoot the compilation unit AST node
- * @param type the type to add the methods to
- * @param methodsToImplement the method bindings to implement or <code>null</code> to implement all unimplemented methods
- * @param insertPos the insertion point, or <code>-1</code>
- * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
- * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
- * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
- */
- public AddUnimplementedMethodsOperation(JavaScriptUnit astRoot, ITypeBinding type, IFunctionBinding[] methodsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
- if (astRoot == null || !(astRoot.getJavaElement() instanceof IJavaScriptUnit)) {
- throw new IllegalArgumentException("AST must not be null and has to be created from a IJavaScriptUnit"); //$NON-NLS-1$
- }
- if (type == null) {
- throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
- }
- ASTNode node= astRoot.findDeclaringNode(type);
- if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
- throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
- }
-
- fType= type;
- fInsertPos= insertPos;
- fASTRoot= astRoot;
- fMethodsToImplement= methodsToImplement;
- fSave= save;
- fApply= apply;
- fImports= imports;
-
- fDoCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaScriptProject());
- }
-
- public void setCreateComments(boolean createComments) {
- fDoCreateComments= createComments;
- }
-
-
- /**
- * Returns the qualified names of the generated imports.
- *
- * @return the generated imports
- */
- public final String[] getCreatedImports() {
- if (fCreatedImports != null) {
- return fCreatedImports;
- }
- return new String[0];
- }
-
- /**
- * Returns the method binding keys for which a method has been generated.
- *
- * @return the method binding keys
- */
- public final String[] getCreatedMethods() {
- final String[] keys= new String[fCreatedMethods.size()];
- fCreatedMethods.toArray(keys);
- return keys;
- }
-
- /**
- * Returns the scheduling rule for this operation.
- *
- * @return the scheduling rule
- */
- public final ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /*
- * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask("", 2); //$NON-NLS-1$
- monitor.setTaskName(CodeGenerationMessages.AddUnimplementedMethodsOperation_description);
- fCreatedMethods.clear();
- IJavaScriptUnit cu= (IJavaScriptUnit) fASTRoot.getJavaElement();
-
- AST ast= fASTRoot.getAST();
-
- ASTRewrite astRewrite= ASTRewrite.create(ast);
- ImportRewrite importRewrite= StubUtility.createImportRewrite(fASTRoot, true);
-
- ITypeBinding currTypeBinding= fType;
- ListRewrite memberRewriter= null;
-
- ASTNode node= fASTRoot.findDeclaringNode(currTypeBinding);
- if (node instanceof AnonymousClassDeclaration) {
- memberRewriter= astRewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- } else if (node instanceof AbstractTypeDeclaration) {
- ChildListPropertyDescriptor property= ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty();
- memberRewriter= astRewrite.getListRewrite(node, property);
- } else {
- throw new IllegalArgumentException();
- // not possible, we checked this in the constructor
- }
-
- final CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaScriptProject());
- settings.createComments= fDoCreateComments;
-
- ASTNode insertion= getNodeToInsertBefore(memberRewriter);
-
- IFunctionBinding[] methodsToImplement= fMethodsToImplement;
- if (methodsToImplement == null) {
- methodsToImplement= StubUtility2.getUnimplementedMethods(currTypeBinding);
- }
-
- ImportRewriteContext context= null;
- int insertionPosition= fInsertPos;
- if (insertionPosition == -1 && fASTRoot.types().size() > 0) {
- AbstractTypeDeclaration firstTypeDecl= (AbstractTypeDeclaration)fASTRoot.types().get(0);
- insertionPosition= firstTypeDecl.getStartPosition();
- if (insertionPosition != -1) {
- context= new ContextSensitiveImportRewriteContext(fASTRoot, insertionPosition, importRewrite);
- }
- }
-
- for (int i= 0; i < methodsToImplement.length; i++) {
- IFunctionBinding curr= methodsToImplement[i];
- FunctionDeclaration stub= StubUtility2.createImplementationStub(cu, astRewrite, importRewrite, ast, curr, currTypeBinding.getName(), settings, false, context);
- if (stub != null) {
- fCreatedMethods.add(curr.getKey());
- if (insertion != null)
- memberRewriter.insertBefore(stub, insertion, null);
- else
- memberRewriter.insertLast(stub, null);
- }
- }
- MultiTextEdit edit= new MultiTextEdit();
-
- TextEdit importEdits= importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
- fCreatedImports= importRewrite.getCreatedImports();
- if (fImports) {
- edit.addChild(importEdits);
- }
- edit.addChild(astRewrite.rewriteAST());
-
- if (fApply) {
- JavaModelUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- private ASTNode getNodeToInsertBefore(ListRewrite rewriter) {
- if (fInsertPos != -1) {
- List members= rewriter.getOriginalList();
- for (int i= 0; i < members.size(); i++) {
- ASTNode curr= (ASTNode) members.get(i);
- if (curr.getStartPosition() >= fInsertPos) {
- return curr;
- }
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java
deleted file mode 100644
index 913459db..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import org.eclipse.osgi.util.NLS;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class CodeGenerationMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationMessages";//$NON-NLS-1$
-
- private CodeGenerationMessages() {
- // Do not instantiate
- }
-
- public static String AddGetterSetterOperation_description;
- public static String AddGetterSetterOperation_error_input_type_not_found;
- public static String AddImportsOperation_description;
- public static String AddImportsOperation_error_not_visible_class;
- public static String AddImportsOperation_error_notresolved_message;
- public static String AddImportsOperation_error_importclash;
- public static String AddUnimplementedMethodsOperation_description;
- public static String AddCustomConstructorOperation_description;
- public static String OrganizeImportsOperation_description;
- public static String AddJavaDocStubOperation_description;
- public static String AddDelegateMethodsOperation_monitor_message;
- public static String GenerateHashCodeEqualsOperation_description;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CodeGenerationMessages.class);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties
deleted file mode 100644
index a4a54e2a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties
+++ /dev/null
@@ -1,28 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-AddGetterSetterOperation_description=Generate Getters and Setters...
-AddGetterSetterOperation_error_input_type_not_found=Could not find the selected type element
-
-AddImportsOperation_description=Adding import...
-AddImportsOperation_error_notresolved_message=Type ''{0}'' could not be found or is not visible.
-AddImportsOperation_error_importclash=Import would conflict with an other import declaration.
-AddImportsOperation_error_not_visible_class=''{0}'' is not visible in the current context. Can add import statement.
-AddUnimplementedMethodsOperation_description=Adding unimplemented functions...
-
-AddCustomConstructorOperation_description=Adding new constructor...
-
-OrganizeImportsOperation_description=Organizing imports of {0}...
-
-AddJavaDocStubOperation_description=Create JSDoc stub...
-
-AddDelegateMethodsOperation_monitor_message=Adding delegate methods...
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationSettings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationSettings.java
deleted file mode 100644
index d46a969f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationSettings.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CodeGenerationSettings {
-
- public boolean createComments= true;
- public boolean useKeywordThis= false;
-
- public String[] importOrder= new String[0];
- public int importThreshold= 99;
- public int staticImportThreshold= 99;
- public boolean importIgnoreLowercase= true;
- public boolean overrideAnnotation= false;
-
- public int tabWidth;
- public int indentWidth;
-
-
-
- public void setSettings(CodeGenerationSettings settings) {
- settings.createComments= createComments;
- settings.useKeywordThis= useKeywordThis;
- settings.importOrder= importOrder;
- settings.importThreshold= importThreshold;
- settings.staticImportThreshold= staticImportThreshold;
- settings.importIgnoreLowercase= importIgnoreLowercase;
- settings.overrideAnnotation= overrideAnnotation;
- settings.tabWidth= tabWidth;
- settings.indentWidth= indentWidth;
- }
-
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ContextSensitiveImportRewriteContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ContextSensitiveImportRewriteContext.java
deleted file mode 100644
index c1ac01d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ContextSensitiveImportRewriteContext.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ContextSensitiveImportRewriteContext extends ImportRewriteContext {
-
- private final JavaScriptUnit fCompilationUnit;
- private final int fPosition;
- private IBinding[] fDeclarationsInScope;
- private Name[] fImportedNames;
- private final ImportRewrite fImportRewrite;
-
- public ContextSensitiveImportRewriteContext(JavaScriptUnit compilationUnit, int position, ImportRewrite importRewrite) {
- fCompilationUnit= compilationUnit;
- fPosition= position;
- fImportRewrite= importRewrite;
- fDeclarationsInScope= null;
- fImportedNames= null;
- }
-
- public int findInContext(String qualifier, String name, int kind) {
- int defaultResult= fImportRewrite.getDefaultImportRewriteContext().findInContext(qualifier, name, kind);
- if (defaultResult != ImportRewriteContext.RES_NAME_UNKNOWN)
- return defaultResult;
-
- if (fImportRewrite.isImportMatchesType()) {
- IBinding[] declarationsInScope = getDeclarationsInScope();
- for (int i = 0; i < declarationsInScope.length; i++) {
- if (declarationsInScope[i] instanceof ITypeBinding) {
- ITypeBinding typeBinding = (ITypeBinding) declarationsInScope[i];
- if (isSameType(typeBinding, qualifier, name)) {
- return RES_NAME_FOUND;
- } else if (isConflicting(typeBinding, name)) {
- return RES_NAME_CONFLICT;
- }
- } else if (declarationsInScope[i] != null) {
- if (isConflicting(declarationsInScope[i], name)) {
- return RES_NAME_CONFLICT;
- }
- }
- }
- Name[] names = getImportedNames();
- for (int i = 0; i < names.length; i++) {
- IBinding binding = names[i].resolveBinding();
- if (binding instanceof ITypeBinding) {
- ITypeBinding typeBinding = (ITypeBinding) binding;
- if (isConflictingType(typeBinding, qualifier, name)) {
- return RES_NAME_CONFLICT;
- }
- }
- }
- List list = fCompilationUnit.types();
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- AbstractTypeDeclaration type = (AbstractTypeDeclaration) iter
- .next();
- ITypeBinding binding = type.resolveBinding();
- if (binding != null) {
- if (isSameType(binding, qualifier, name)) {
- return RES_NAME_FOUND;
- } else {
- ITypeBinding decl = containingDeclaration(binding,
- qualifier, name);
- while (decl != null && !decl.equals(binding)) {
- int modifiers = decl.getModifiers();
- if (Modifier.isPrivate(modifiers))
- return RES_NAME_CONFLICT;
- decl = decl.getDeclaringClass();
- }
- }
- }
- }
- }
- String[] addedImports= fImportRewrite.getAddedImports();
- String qualifiedName= JavaModelUtil.concatenateName(qualifier, name);
- for (int i= 0; i < addedImports.length; i++) {
- String addedImport= addedImports[i];
- if (qualifiedName.equals(addedImport)) {
- return RES_NAME_FOUND;
- } else {
- if (isConflicting(name, addedImport))
- return RES_NAME_CONFLICT;
- }
- }
-
-// if (qualifier.equals("java.lang")) { //$NON-NLS-1$
-// //No explicit import statement required
-// IJavaScriptElement parent= fCompilationUnit.getJavaElement().getParent();
-// if (parent instanceof IPackageFragment) {
-// IPackageFragment packageFragment= (IPackageFragment)parent;
-// try {
-// IJavaScriptUnit[] compilationUnits= packageFragment.getCompilationUnits();
-// for (int i= 0; i < compilationUnits.length; i++) {
-// IJavaScriptUnit cu= compilationUnits[i];
-// IType[] allTypes= cu.getAllTypes();
-// for (int j= 0; j < allTypes.length; j++) {
-// IType type= allTypes[j];
-// String packageTypeName= type.getFullyQualifiedName();
-// if (isConflicting(name, packageTypeName))
-// return RES_NAME_CONFLICT;
-// }
-// }
-// } catch (JavaScriptModelException e) {
-// }
-// }
-// }
-
- return RES_NAME_UNKNOWN;
- }
-
- private boolean isConflicting(String name, String importt) {
- int index= importt.lastIndexOf('.');
- String importedName;
- if (index == -1) {
- importedName= importt;
- } else {
- importedName= importt.substring(index + 1, importt.length());
- }
- if (importedName.equals(name)) {
- return true;
- }
- return false;
- }
-
- private ITypeBinding containingDeclaration(ITypeBinding binding, String qualifier, String name) {
- ITypeBinding[] declaredTypes= binding.getDeclaredTypes();
- for (int i= 0; i < declaredTypes.length; i++) {
- ITypeBinding childBinding= declaredTypes[i];
- if (isSameType(childBinding, qualifier, name)) {
- return childBinding;
- } else {
- ITypeBinding result= containingDeclaration(childBinding, qualifier, name);
- if (result != null) {
- return result;
- }
- }
- }
- return null;
- }
-
- private boolean isConflicting(IBinding binding, String name) {
- return binding.getName().equals(name);
- }
-
- private boolean isSameType(ITypeBinding binding, String qualifier, String name) {
- String qualifiedName= JavaModelUtil.concatenateName(qualifier, name);
- return binding.getQualifiedName().equals(qualifiedName);
- }
-
- private boolean isConflictingType(ITypeBinding binding, String qualifier, String name) {
- binding= binding.getTypeDeclaration();
- return !isSameType(binding, qualifier, name) && isConflicting(binding, name);
- }
-
- private IBinding[] getDeclarationsInScope() {
- if (fDeclarationsInScope == null) {
- ScopeAnalyzer analyzer= new ScopeAnalyzer(fCompilationUnit);
- fDeclarationsInScope= analyzer.getDeclarationsInScope(fPosition, ScopeAnalyzer.METHODS | ScopeAnalyzer.TYPES | ScopeAnalyzer.VARIABLES);
- }
- return fDeclarationsInScope;
- }
-
- private Name[] getImportedNames() {
- if (fImportedNames == null) {
- IJavaScriptProject project= null;
- IJavaScriptElement javaElement= fCompilationUnit.getJavaElement();
- if (javaElement != null)
- project= javaElement.getJavaScriptProject();
-
- List imports= new ArrayList();
- ImportReferencesCollector.collect(fCompilationUnit, project, null, imports, null);
- fImportedNames= (Name[])imports.toArray(new Name[imports.size()]);
- }
- return fImportedNames;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/GetterSetterUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/GetterSetterUtil.java
deleted file mode 100644
index a6750e69..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/GetterSetterUtil.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.NamingConventions;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class GetterSetterUtil {
-
- private static final String[] EMPTY= new String[0];
-
- //no instances
- private GetterSetterUtil(){
- }
-
- public static String getGetterName(IField field, String[] excludedNames) throws JavaScriptModelException {
- boolean useIs= StubUtility.useIsForBooleanGetters(field.getJavaScriptProject());
- return getGetterName(field, excludedNames, useIs);
- }
-
- private static String getGetterName(IField field, String[] excludedNames, boolean useIsForBoolGetters) throws JavaScriptModelException {
- if (excludedNames == null) {
- excludedNames= EMPTY;
- }
- return getGetterName(field.getJavaScriptProject(), field.getElementName(), field.getFlags(), useIsForBoolGetters && JavaModelUtil.isBoolean(field), excludedNames);
- }
-
- public static String getGetterName(IVariableBinding variableType, IJavaScriptProject project, String[] excludedNames, boolean isBoolean) {
- boolean useIs= StubUtility.useIsForBooleanGetters(project) && isBoolean;
- return getGetterName(project, variableType.getName(), variableType.getModifiers(), useIs, excludedNames);
- }
-
- public static String getGetterName(IJavaScriptProject project, String fieldName, int flags, boolean isBoolean, String[] excludedNames){
- return NamingConventions.suggestGetterName(project, fieldName, flags, isBoolean, excludedNames);
- }
-
- public static String getSetterName(IVariableBinding variableType, IJavaScriptProject project, String[] excludedNames, boolean isBoolean) {
- return getSetterName(project, variableType.getName(), variableType.getModifiers(), isBoolean, excludedNames);
- }
-
- public static String getSetterName(IJavaScriptProject project, String fieldName, int flags, boolean isBoolean, String[] excludedNames){
- return NamingConventions.suggestSetterName(project, fieldName, flags, isBoolean, excludedNames);
- }
-
- public static String getSetterName(IField field, String[] excludedNames) throws JavaScriptModelException {
- if (excludedNames == null) {
- excludedNames= EMPTY;
- }
- return NamingConventions.suggestSetterName(field.getJavaScriptProject(), field.getElementName(), field.getFlags(), JavaModelUtil.isBoolean(field), excludedNames);
- }
-
- public static IFunction getGetter(IField field) throws JavaScriptModelException{
- if (field.getDeclaringType()==null)
- return null;
- String getterName= getGetterName(field, EMPTY, true);
- IFunction primaryCandidate= JavaModelUtil.findMethod(getterName, new String[0], false, field.getDeclaringType());
- if (! JavaModelUtil.isBoolean(field) || (primaryCandidate != null && primaryCandidate.exists()))
- return primaryCandidate;
- //bug 30906 describes why we need to look for other alternatives here (try with get... for booleans)
- String secondCandidateName= getGetterName(field, EMPTY, false);
- return JavaModelUtil.findMethod(secondCandidateName, new String[0], false, field.getDeclaringType());
- }
-
- public static IFunction getSetter(IField field) throws JavaScriptModelException{
- if (field.getDeclaringType()==null)
- return null;
- String[] args= new String[] { field.getTypeSignature() };
- return JavaModelUtil.findMethod(getSetterName(field, EMPTY), args, false, field.getDeclaringType());
- }
-
- /**
- * Create a stub for a getter of the given field using getter/setter templates. The resulting code
- * has to be formatted and indented.
- * @param field The field to create a getter for
- * @param setterName The chosen name for the setter
- * @param addComments If <code>true</code>, comments will be added.
- * @param flags The flags signaling visibility, if static, synchronized or final
- * @return Returns the generated stub.
- * @throws CoreException
- */
- public static String getSetterStub(IField field, String setterName, boolean addComments, int flags) throws CoreException {
-
- String fieldName= field.getElementName();
- IType parentType= field.getDeclaringType();
-
- String returnSig= field.getTypeSignature();
- String typeName= Signature.toString(returnSig);
-
- IJavaScriptProject project= field.getJavaScriptProject();
-
- String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(project, fieldName, field.getFlags());
- String argname= StubUtility.suggestArgumentName(project, accessorName, EMPTY);
-
- boolean isStatic= Flags.isStatic(flags);
-
- String lineDelim= "\n"; // Use default line delimiter, as generated stub has to be formatted anyway //$NON-NLS-1$
- StringBuffer buf= new StringBuffer();
- if (addComments) {
- String comment= CodeGeneration.getSetterComment(field.getJavaScriptUnit(), parentType.getTypeQualifiedName('.'), setterName, field.getElementName(), typeName, argname, accessorName, lineDelim);
- if (comment != null) {
- buf.append(comment);
- buf.append(lineDelim);
- }
- }
- buf.append(JdtFlags.getVisibilityString(flags));
- buf.append(' ');
- if (isStatic)
- buf.append("static "); //$NON-NLS-1$
-
- buf.append("void "); //$NON-NLS-1$
- buf.append(setterName);
- buf.append('(');
- buf.append(typeName);
- buf.append(' ');
- buf.append(argname);
- buf.append(") {"); //$NON-NLS-1$
- buf.append(lineDelim);
-
- boolean useThis= StubUtility.useThisForFieldAccess(project);
- if (argname.equals(fieldName) || (useThis && !isStatic)) {
- if (isStatic)
- fieldName= parentType.getElementName() + '.' + fieldName;
- else
- fieldName= "this." + fieldName; //$NON-NLS-1$
- }
- String body= CodeGeneration.getSetterMethodBodyContent(field.getJavaScriptUnit(), parentType.getTypeQualifiedName('.'), setterName, fieldName, argname, lineDelim);
- if (body != null) {
- buf.append(body);
- }
- buf.append("}"); //$NON-NLS-1$
- buf.append(lineDelim);
- return buf.toString();
- }
-
- /**
- * Create a stub for a getter of the given field using getter/setter templates. The resulting code
- * has to be formatted and indented.
- * @param field The field to create a getter for
- * @param getterName The chosen name for the getter
- * @param addComments If <code>true</code>, comments will be added.
- * @param flags The flags signaling visibility, if static, synchronized or final
- * @return Returns the generated stub.
- * @throws CoreException
- */
- public static String getGetterStub(IField field, String getterName, boolean addComments, int flags) throws CoreException {
- String fieldName= field.getElementName();
- IType parentType= field.getDeclaringType();
-
- boolean isStatic= Flags.isStatic(flags);
-
- String typeName= Signature.toString(field.getTypeSignature());
- String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(field.getJavaScriptProject(), fieldName, field.getFlags());
-
- String lineDelim= "\n"; // Use default line delimiter, as generated stub has to be formatted anyway //$NON-NLS-1$
- StringBuffer buf= new StringBuffer();
- if (addComments) {
- String comment= CodeGeneration.getGetterComment(field.getJavaScriptUnit(), parentType.getTypeQualifiedName('.'), getterName, field.getElementName(), typeName, accessorName, lineDelim);
- if (comment != null) {
- buf.append(comment);
- buf.append(lineDelim);
- }
- }
-
- buf.append(JdtFlags.getVisibilityString(flags));
- buf.append(' ');
- if (isStatic)
- buf.append("static "); //$NON-NLS-1$
-
- buf.append(typeName);
- buf.append(' ');
- buf.append(getterName);
- buf.append("() {"); //$NON-NLS-1$
- buf.append(lineDelim);
-
- boolean useThis= StubUtility.useThisForFieldAccess(field.getJavaScriptProject());
- if (useThis && !isStatic) {
- fieldName= "this." + fieldName; //$NON-NLS-1$
- }
-
- String body= CodeGeneration.getGetterMethodBodyContent(field.getJavaScriptUnit(), parentType.getTypeQualifiedName('.'), getterName, fieldName, lineDelim);
- if (body != null) {
- buf.append(body);
- }
- buf.append("}"); //$NON-NLS-1$
- buf.append(lineDelim);
- return buf.toString();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/IRequestQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/IRequestQuery.java
deleted file mode 100644
index 070d9ca0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/IRequestQuery.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import org.eclipse.wst.jsdt.core.IMember;
-
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IRequestQuery {
-
- // return codes
- public static final int CANCEL= 0;
- public static final int NO= 1;
- public static final int YES= 2;
- public static final int YES_ALL= 3;
-
- /**
- * Do the callback. Returns YES, NO, YES_ALL or CANCEL
- */
- int doQuery(IMember member);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ImportReferencesCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ImportReferencesCollector.java
deleted file mode 100644
index 65788ec5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/ImportReferencesCollector.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ImportReferencesCollector extends GenericVisitor {
-
- public static void collect(ASTNode node, IJavaScriptProject project, Region rangeLimit, Collection resultingTypeImports, Collection resultingStaticImports) {
- JavaScriptUnit astRoot= (JavaScriptUnit) node.getRoot();
- node.accept(new ImportReferencesCollector(project, astRoot, rangeLimit, resultingTypeImports, resultingStaticImports));
- }
-
-
- private JavaScriptUnit fASTRoot;
- private Region fSubRange;
- private Collection/*<Name>*/ fTypeImports;
- private Collection/*<Name>*/ fStaticImports;
-
- private ImportReferencesCollector(IJavaScriptProject project, JavaScriptUnit astRoot, Region rangeLimit, Collection resultingTypeImports, Collection resultingStaticImports) {
- super(true);
- fTypeImports= resultingTypeImports;
- fStaticImports= resultingStaticImports;
- fSubRange= rangeLimit;
- if (project == null || !JavaModelUtil.is50OrHigher(project)) {
- fStaticImports= null; // do not collect
- }
- fASTRoot= astRoot;
- }
-
- public ImportReferencesCollector(IJavaScriptProject project, Region rangeLimit, Collection resultingTypeImports, Collection resultingStaticImports) {
- this(project, null, rangeLimit, resultingTypeImports, resultingStaticImports);
- }
-
- public JavaScriptUnit getASTRoot(ASTNode node) {
- if (fASTRoot == null) {
- fASTRoot= (JavaScriptUnit) node.getRoot();
- }
- return fASTRoot;
- }
-
- private boolean isAffected(ASTNode node) {
- if (fSubRange == null) {
- return true;
- }
- int nodeStart= node.getStartPosition();
- int offset= fSubRange.getOffset();
- return nodeStart + node.getLength() > offset && (offset + fSubRange.getLength()) > nodeStart;
- }
-
-
- private void addReference(SimpleName name) {
- if (isAffected(name)) {
- fTypeImports.add(name);
- }
- }
-
- private void typeRefFound(Name node) {
- if (node != null) {
- while (node.isQualifiedName()) {
- node= ((QualifiedName) node).getQualifier();
- }
- addReference((SimpleName) node);
- }
- }
-
- private void possibleTypeRefFound(Name node) {
- while (node.isQualifiedName()) {
- node= ((QualifiedName) node).getQualifier();
- }
- IBinding binding= node.resolveBinding();
- if (binding == null || binding.getKind() == IBinding.TYPE) {
- // if the binding is null, we cannot determine if
- // we have a type binding or not, so we will assume
- // we do.
- addReference((SimpleName) node);
- }
- }
-
- private void possibleStaticImportFound(Name name) {
- if (fStaticImports == null) {
- return;
- }
-
- while (name.isQualifiedName()) {
- name= ((QualifiedName) name).getQualifier();
- }
- if (!isAffected(name)) {
- return;
- }
-
- IBinding binding= name.resolveBinding();
- if (binding == null || binding instanceof ITypeBinding || !Modifier.isStatic(binding.getModifiers()) || ((SimpleName) name).isDeclaration()) {
- return;
- }
-
- if (binding instanceof IVariableBinding) {
- IVariableBinding varBinding= (IVariableBinding) binding;
- if (varBinding.isField()) {
- varBinding= varBinding.getVariableDeclaration();
- ITypeBinding declaringClass= varBinding.getDeclaringClass();
- if (declaringClass != null && !declaringClass.isLocal()) {
- if (new ScopeAnalyzer(getASTRoot(name)).isDeclaredInScope(varBinding, (SimpleName)name, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY))
- return;
- fStaticImports.add(name);
- }
- }
- } else if (binding instanceof IFunctionBinding) {
- IFunctionBinding methodBinding= ((IFunctionBinding) binding).getMethodDeclaration();
- ITypeBinding declaringClass= methodBinding.getDeclaringClass();
- if (declaringClass != null && !declaringClass.isLocal()) {
- if (new ScopeAnalyzer(getASTRoot(name)).isDeclaredInScope(methodBinding, (SimpleName)name, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY))
- return;
- fStaticImports.add(name);
- }
- }
-
- }
-
- private void doVisitChildren(List elements) {
- int nElements= elements.size();
- for (int i= 0; i < nElements; i++) {
- ((ASTNode) elements.get(i)).accept(this);
- }
- }
-
- private void doVisitNode(ASTNode node) {
- if (node != null) {
- node.accept(this);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visitNode(org.eclipse.wst.jsdt.core.dom.ASTNode)
- */
- protected boolean visitNode(ASTNode node) {
- return isAffected(node);
- }
-
- /*
- * @see ASTVisitor#visit(ArrayType)
- */
- public boolean visit(ArrayType node) {
- doVisitNode(node.getElementType());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleType)
- */
- public boolean visit(SimpleType node) {
- typeRefFound(node.getName());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedType)
- */
- public boolean visit(QualifiedType node) {
- // nothing to do here, let the qualifier be visited
- return true;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- possibleTypeRefFound(node); // possible ref
- possibleStaticImportFound(node);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- doVisitChildren(node.annotations());
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- typeRefFound(node.getQualifier());
- return false;
- }
-
- private void evalQualifyingExpression(Expression expr, Name selector) {
- if (expr != null) {
- if (expr instanceof Name) {
- Name name= (Name) expr;
- possibleTypeRefFound(name);
- possibleStaticImportFound(name);
- } else {
- expr.accept(this);
- }
- } else if (selector != null) {
- possibleStaticImportFound(selector);
- }
- }
-
- /*
- * @see ASTVisitor#visit(ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- doVisitChildren(node.typeArguments());
- doVisitNode(node.getType());
- evalQualifyingExpression(node.getExpression(), null);
- if (node.getAnonymousClassDeclaration() != null) {
- node.getAnonymousClassDeclaration().accept(this);
- }
- doVisitChildren(node.arguments());
- return false;
- }
-
- /*
- * @see ASTVisitor#endVisit(FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- evalQualifyingExpression(node.getExpression(), node.getName());
- doVisitChildren(node.typeArguments());
- doVisitChildren(node.arguments());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- if (!isAffected(node)) {
- return false;
- }
-
- evalQualifyingExpression(node.getExpression(), null);
- doVisitChildren(node.typeArguments());
- doVisitChildren(node.arguments());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldAccess)
- */
- public boolean visit(FieldAccess node) {
- evalQualifyingExpression(node.getExpression(), node.getName());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleName)
- */
- public boolean visit(SimpleName node) {
- // if the call gets here, it can only be a variable reference
- possibleStaticImportFound(node);
- return false;
- }
-
-
-
- /*
- * @see ASTVisitor#visit(TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- if (!isAffected(node)) {
- return false;
- }
- return true;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- if (!isAffected(node)) {
- return false;
- }
- doVisitNode(node.getJavadoc());
-
- if (node.getAST().apiLevel() >= AST.JLS3) {
- doVisitChildren(node.modifiers());
- }
-
- if (!node.isConstructor()) {
- doVisitNode(node.getReturnType2());
- }
- doVisitChildren(node.parameters());
- Iterator iter=node.thrownExceptions().iterator();
- while (iter.hasNext()) {
- typeRefFound((Name) iter.next());
- }
- doVisitNode(node.getBody());
- return false;
- }
-
- public boolean visit(TagElement node) {
- String tagName= node.getTagName();
- List list= node.fragments();
- int idx= 0;
- if (tagName != null && !list.isEmpty()) {
- Object first= list.get(0);
- if (first instanceof Name) {
- if ("@throws".equals(tagName) || "@exception".equals(tagName)) { //$NON-NLS-1$//$NON-NLS-2$
- typeRefFound((Name) first);
- } else if ("@see".equals(tagName) || "@link".equals(tagName) || "@linkplain".equals(tagName)) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- Name name= (Name) first;
- possibleTypeRefFound(name);
- }
- idx++;
- }
- }
- for (int i= idx; i < list.size(); i++) {
- doVisitNode((ASTNode) list.get(i));
- }
- return false;
- }
-
- public boolean visit(MemberRef node) {
- Name qualifier= node.getQualifier();
- if (qualifier != null) {
- typeRefFound(qualifier);
- }
- return false;
- }
-
- public boolean visit(FunctionRef node) {
- Name qualifier= node.getQualifier();
- if (qualifier != null) {
- typeRefFound(qualifier);
- }
- List list= node.parameters();
- if (list != null) {
- doVisitChildren(list); // visit FunctionRefParameter with Type
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/OrganizeImportsOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
deleted file mode 100644
index 3288429c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
+++ /dev/null
@@ -1,546 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeNameMatchCollector;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.SimilarElementsRequestor;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class OrganizeImportsOperation implements IWorkspaceRunnable {
- public static interface IChooseImportQuery {
- /**
- * Selects imports from a list of choices.
- * @param openChoices From each array, a type reference has to be selected
- * @param ranges For each choice the range of the corresponding type reference.
- * @return Returns <code>null</code> to cancel the operation, or the
- * selected imports.
- */
- TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges);
- }
-
-
- private static class TypeReferenceProcessor {
-
- private static class UnresolvedTypeData {
- final SimpleName ref;
- final int typeKinds;
- final List foundInfos;
-
- public UnresolvedTypeData(SimpleName ref) {
- this.ref= ref;
- this.typeKinds= ASTResolving.getPossibleTypeKinds(ref, true);
- this.foundInfos= new ArrayList(3);
- }
-
- public void addInfo(TypeNameMatch info) {
- for (int i= this.foundInfos.size() - 1; i >= 0; i--) {
- TypeNameMatch curr= (TypeNameMatch) this.foundInfos.get(i);
- if (curr.getTypeContainerName().equals(info.getTypeContainerName())) {
- return; // not added. already contains type with same name
- }
- }
- foundInfos.add(info);
- }
- }
-
- private Set fOldSingleImports;
- private Set fOldDemandImports;
-
- private Set fImplicitImports;
-
- private ImportRewrite fImpStructure;
-
- private boolean fDoIgnoreLowerCaseNames;
-
- private IPackageFragment fCurrPackage;
-
- private ScopeAnalyzer fAnalyzer;
- private boolean fAllowDefaultPackageImports;
-
- private Map fUnresolvedTypes;
- private Set fImportsAdded;
- private TypeNameMatch[][] fOpenChoices;
- private SourceRange[] fSourceRanges;
-
-
- public TypeReferenceProcessor(Set oldSingleImports, Set oldDemandImports, JavaScriptUnit root, ImportRewrite impStructure, boolean ignoreLowerCaseNames) {
- fOldSingleImports= oldSingleImports;
- fOldDemandImports= oldDemandImports;
- fImpStructure= impStructure;
- fDoIgnoreLowerCaseNames= ignoreLowerCaseNames;
-
- IJavaScriptUnit cu= impStructure.getCompilationUnit();
-
- fImplicitImports= new HashSet(3);
- fImplicitImports.add(""); //$NON-NLS-1$
- fImplicitImports.add("java.lang"); //$NON-NLS-1$
- fImplicitImports.add(cu.getParent().getElementName());
-
- fAnalyzer= new ScopeAnalyzer(root);
-
- fCurrPackage= (IPackageFragment) cu.getParent();
-
- fAllowDefaultPackageImports= cu.getJavaScriptProject().getOption(JavaScriptCore.COMPILER_COMPLIANCE, true).equals(JavaScriptCore.VERSION_1_3);
-
- fImportsAdded= new HashSet();
- fUnresolvedTypes= new HashMap();
- }
-
- private boolean needsImport(ITypeBinding typeBinding, SimpleName ref) {
- if (!typeBinding.isTopLevel() && !typeBinding.isMember() || typeBinding.isRecovered()) {
- return false; // no imports for anonymous, local, primitive types or parameters types
- }
- int modifiers= typeBinding.getModifiers();
- if (Modifier.isPrivate(modifiers)) {
- return false; // imports for privates are not required
- }
- ITypeBinding currTypeBinding= Bindings.getBindingOfParentType(ref);
- if (currTypeBinding == null) {
- return false; // not in a type
- }
- if (!Modifier.isPublic(modifiers)) {
- if (!currTypeBinding.getPackage().getName().equals(typeBinding.getPackage().getName())) {
- return false; // not visible
- }
- }
-
- ASTNode parent= ref.getParent();
- while (parent instanceof Type) {
- parent= parent.getParent();
- }
- if (parent instanceof AbstractTypeDeclaration && parent.getParent() instanceof JavaScriptUnit) {
- return true;
- }
-
- if (typeBinding.isMember()) {
- if (fAnalyzer.isDeclaredInScope(typeBinding, ref, ScopeAnalyzer.TYPES | ScopeAnalyzer.CHECK_VISIBILITY))
- return false;
- }
- return true;
- }
-
-
- /**
- * Tries to find the given type name and add it to the import structure.
- * @param ref the name node
- */
- public void add(SimpleName ref) {
- String typeName= ref.getIdentifier();
-
- if (fImportsAdded.contains(typeName)) {
- return;
- }
-
- IBinding binding= ref.resolveBinding();
- if (binding != null) {
- if (binding.getKind() != IBinding.TYPE) {
- return;
- }
- ITypeBinding typeBinding= (ITypeBinding) binding;
- if (typeBinding.isArray()) {
- typeBinding= typeBinding.getElementType();
- }
- typeBinding= typeBinding.getTypeDeclaration();
- if (!typeBinding.isRecovered()) {
- if (needsImport(typeBinding, ref)) {
- fImpStructure.addImport(typeBinding);
- fImportsAdded.add(typeName);
- }
- return;
- }
- } else {
- if (fDoIgnoreLowerCaseNames && typeName.length() > 0) {
- char ch= typeName.charAt(0);
- if (Strings.isLowerCase(ch) && Character.isLetter(ch)) {
- return;
- }
- }
- }
- fImportsAdded.add(typeName);
- fUnresolvedTypes.put(typeName, new UnresolvedTypeData(ref));
- }
-
- public boolean process(IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- int nUnresolved= fUnresolvedTypes.size();
- if (nUnresolved == 0) {
- return false;
- }
- char[][] allTypes= new char[nUnresolved][];
- int i= 0;
- for (Iterator iter= fUnresolvedTypes.keySet().iterator(); iter.hasNext();) {
- allTypes[i++]= ((String) iter.next()).toCharArray();
- }
- final ArrayList typesFound= new ArrayList();
- final IJavaScriptProject project= fCurrPackage.getJavaScriptProject();
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { project });
- TypeNameMatchCollector collector= new TypeNameMatchCollector(typesFound);
- new SearchEngine().searchAllTypeNames(null, allTypes, scope, collector, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
-
- boolean is50OrHigher= JavaModelUtil.is50OrHigher(project);
-
- for (i= 0; i < typesFound.size(); i++) {
- TypeNameMatch curr= (TypeNameMatch) typesFound.get(i);
- UnresolvedTypeData data= (UnresolvedTypeData) fUnresolvedTypes.get(curr.getSimpleTypeName());
- if (data != null && isVisible(curr) && isOfKind(curr, data.typeKinds, is50OrHigher)) {
- if (fAllowDefaultPackageImports || curr.getPackageName().length() > 0) {
- data.addInfo(curr);
- }
- }
- }
-
- ArrayList openChoices= new ArrayList(nUnresolved);
- ArrayList sourceRanges= new ArrayList(nUnresolved);
- for (Iterator iter= fUnresolvedTypes.values().iterator(); iter.hasNext();) {
- UnresolvedTypeData data= (UnresolvedTypeData) iter.next();
- TypeNameMatch[] openChoice= processTypeInfo(data.foundInfos);
- if (openChoice != null) {
- openChoices.add(openChoice);
- sourceRanges.add(new SourceRange(data.ref.getStartPosition(), data.ref.getLength()));
- }
- }
- if (openChoices.isEmpty()) {
- return false;
- }
- fOpenChoices= (TypeNameMatch[][]) openChoices.toArray(new TypeNameMatch[openChoices.size()][]);
- fSourceRanges= (SourceRange[]) sourceRanges.toArray(new SourceRange[sourceRanges.size()]);
- return true;
- } finally {
- monitor.done();
- }
- }
-
- private TypeNameMatch[] processTypeInfo(List typeRefsFound) {
- int nFound= typeRefsFound.size();
- if (nFound == 0) {
- // nothing found
- return null;
- } else if (nFound == 1) {
- TypeNameMatch typeRef= (TypeNameMatch) typeRefsFound.get(0);
- fImpStructure.addImport(typeRef.getFullyQualifiedName());
- return null;
- } else {
- String typeToImport= null;
- boolean ambiguousImports= false;
-
- // multiple found, use old imports to find an entry
- for (int i= 0; i < nFound; i++) {
- TypeNameMatch typeRef= (TypeNameMatch) typeRefsFound.get(i);
- String fullName= typeRef.getFullyQualifiedName();
- String containerName= typeRef.getTypeContainerName();
- if (fOldSingleImports.contains(fullName)) {
- // was single-imported
- fImpStructure.addImport(fullName);
- return null;
- } else if (fOldDemandImports.contains(containerName) || fImplicitImports.contains(containerName)) {
- if (typeToImport == null) {
- typeToImport= fullName;
- } else { // more than one import-on-demand
- ambiguousImports= true;
- }
- }
- }
-
- if (typeToImport != null && !ambiguousImports) {
- fImpStructure.addImport(typeToImport);
- return null;
- }
- // return the open choices
- return (TypeNameMatch[]) typeRefsFound.toArray(new TypeNameMatch[nFound]);
- }
- }
-
- private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) {
- return (typeKinds & SimilarElementsRequestor.CLASSES) != 0;
- }
-
- private boolean isVisible(TypeNameMatch curr) {
- int flags= curr.getModifiers();
- if (Flags.isPrivate(flags)) {
- return false;
- }
- if (Flags.isPublic(flags)) {
- return true;
- }
- return curr.getPackageName().equals(fCurrPackage.getElementName());
- }
-
- public TypeNameMatch[][] getChoices() {
- return fOpenChoices;
- }
-
- public ISourceRange[] getChoicesSourceRanges() {
- return fSourceRanges;
- }
- }
-
- private boolean fDoSave;
-
- private boolean fIgnoreLowerCaseNames;
-
- private IChooseImportQuery fChooseImportQuery;
-
- private int fNumberOfImportsAdded;
- private int fNumberOfImportsRemoved;
-
- private IProblem fParsingError;
- private IJavaScriptUnit fCompilationUnit;
-
- private JavaScriptUnit fASTRoot;
-
- private final boolean fAllowSyntaxErrors;
-
- public OrganizeImportsOperation(IJavaScriptUnit cu, JavaScriptUnit astRoot, boolean ignoreLowerCaseNames, boolean save, boolean allowSyntaxErrors, IChooseImportQuery chooseImportQuery) throws CoreException {
- fCompilationUnit= cu;
- fASTRoot= astRoot;
-
- fDoSave= save;
- fIgnoreLowerCaseNames= ignoreLowerCaseNames;
- fAllowSyntaxErrors= allowSyntaxErrors;
- fChooseImportQuery= chooseImportQuery;
-
- fNumberOfImportsAdded= 0;
- fNumberOfImportsRemoved= 0;
-
- fParsingError= null;
- }
-
- /**
- * Runs the operation.
- * @param monitor the progress monitor
- * @throws CoreException thrown when the operation failed
- * @throws OperationCanceledException Runtime error thrown when operation is canceled.
- */
- public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- try {
- monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, fCompilationUnit.getElementName()), 10);
-
- TextEdit edit= createTextEdit(new SubProgressMonitor(monitor, 9));
- if (edit == null)
- return;
-
- JavaModelUtil.applyEdit(fCompilationUnit, edit, fDoSave, new SubProgressMonitor(monitor, 1));
- } finally {
- monitor.done();
- }
- }
-
- public TextEdit createTextEdit(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- try {
- fNumberOfImportsAdded= 0;
- fNumberOfImportsRemoved= 0;
-
- monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, fCompilationUnit.getElementName()), 9);
-
- JavaScriptUnit astRoot= fASTRoot;
- if (astRoot == null) {
- astRoot= ASTProvider.getASTProvider().getAST(fCompilationUnit, ASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 2));
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- } else {
- monitor.worked(2);
- }
-
- ImportRewrite importsRewrite= StubUtility.createImportRewrite(astRoot, false);
-
- Set/*<String>*/ oldSingleImports= new HashSet();
- Set/*<String>*/ oldDemandImports= new HashSet();
- List/*<SimpleName>*/ typeReferences= new ArrayList();
- List/*<SimpleName>*/ staticReferences= new ArrayList();
-
- if (!collectReferences(astRoot, typeReferences, staticReferences, oldSingleImports, oldDemandImports))
- return null;
-
- monitor.worked(1);
-
- TypeReferenceProcessor processor= new TypeReferenceProcessor(oldSingleImports, oldDemandImports, astRoot, importsRewrite, fIgnoreLowerCaseNames);
-
- Iterator refIterator= typeReferences.iterator();
- while (refIterator.hasNext()) {
- SimpleName typeRef= (SimpleName) refIterator.next();
- processor.add(typeRef);
- }
-
- boolean hasOpenChoices= processor.process(new SubProgressMonitor(monitor, 3));
- addStaticImports(staticReferences, importsRewrite);
-
- if (hasOpenChoices && fChooseImportQuery != null) {
- TypeNameMatch[][] choices= processor.getChoices();
- ISourceRange[] ranges= processor.getChoicesSourceRanges();
- TypeNameMatch[] chosen= fChooseImportQuery.chooseImports(choices, ranges);
- if (chosen == null) {
- // cancel pressed by the user
- throw new OperationCanceledException();
- }
- for (int i= 0; i < chosen.length; i++) {
- TypeNameMatch typeInfo= chosen[i];
- importsRewrite.addImport(typeInfo.getFullyQualifiedName());
- }
- }
-
- TextEdit result= importsRewrite.rewriteImports(new SubProgressMonitor(monitor, 3));
-
- determineImportDifferences(importsRewrite, oldSingleImports, oldDemandImports);
-
- return result;
- } finally {
- monitor.done();
- }
- }
-
- private void determineImportDifferences(ImportRewrite importsStructure, Set oldSingleImports, Set oldDemandImports) {
- ArrayList importsAdded= new ArrayList();
- importsAdded.addAll(Arrays.asList(importsStructure.getCreatedImports()));
- importsAdded.addAll(Arrays.asList(importsStructure.getCreatedStaticImports()));
-
- Object[] content= oldSingleImports.toArray();
- for (int i= 0; i < content.length; i++) {
- String importName= (String) content[i];
- if (importsAdded.remove(importName))
- oldSingleImports.remove(importName);
- }
- content= oldDemandImports.toArray();
- for (int i= 0; i < content.length; i++) {
- String importName= (String) content[i];
- if (importsAdded.remove(importName + ".*")) //$NON-NLS-1$
- oldDemandImports.remove(importName);
- }
- fNumberOfImportsAdded= importsAdded.size();
- fNumberOfImportsRemoved= oldSingleImports.size() + oldDemandImports.size();
- }
-
-
- private void addStaticImports(List/*<SimpleName>*/ staticReferences, ImportRewrite importsStructure) {
- for (int i= 0; i < staticReferences.size(); i++) {
- Name name= (Name) staticReferences.get(i);
- IBinding binding= name.resolveBinding();
- if (binding != null) { // paranoia check
- importsStructure.addStaticImport(binding);
- }
- }
- }
-
-
- // find type references in a compilation unit
- private boolean collectReferences(JavaScriptUnit astRoot, List typeReferences, List staticReferences, Set oldSingleImports, Set oldDemandImports) {
- if (!fAllowSyntaxErrors) {
- IProblem[] problems= astRoot.getProblems();
- for (int i= 0; i < problems.length; i++) {
- IProblem curr= problems[i];
- if (curr.isError() && (curr.getID() & IProblem.Syntax) != 0) {
- fParsingError= problems[i];
- return false;
- }
- }
- }
- List imports= astRoot.imports();
- for (int i= 0; i < imports.size(); i++) {
- ImportDeclaration curr= (ImportDeclaration) imports.get(i);
- String id= ASTResolving.getFullName(curr.getName());
- if (curr.isOnDemand()) {
- oldDemandImports.add(id);
- } else {
- oldSingleImports.add(id);
- }
- }
-
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- ImportReferencesCollector.collect(astRoot, project, null, typeReferences, staticReferences);
-
- return true;
- }
-
- /**
- * After executing the operation, returns <code>null</code> if the operation has been executed successfully or
- * the range where parsing failed.
- * @return returns the parse error
- */
- public IProblem getParseError() {
- return fParsingError;
- }
-
- public int getNumberOfImportsAdded() {
- return fNumberOfImportsAdded;
- }
-
- public int getNumberOfImportsRemoved() {
- return fNumberOfImportsRemoved;
- }
-
- /**
- * @return Returns the scheduling rule for this operation
- */
- public ISchedulingRule getScheduleRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/SortMembersOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/SortMembersOperation.java
deleted file mode 100644
index bc4d476d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/SortMembersOperation.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.Comparator;
-import java.util.List;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.util.JavaScriptUnitSorter;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-
-import com.ibm.icu.text.Collator;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class SortMembersOperation implements IWorkspaceRunnable {
-
-
- /**
- * Default comparator for body declarations.
- */
- public static class DefaultJavaElementComparator implements Comparator {
-
- private final Collator fCollator;
- private final MembersOrderPreferenceCache fMemberOrderCache;
- private final boolean fDoNotSortFields;
-
- public DefaultJavaElementComparator(boolean doNotSortFields) {
- fDoNotSortFields= doNotSortFields;
- fCollator= Collator.getInstance();
- fMemberOrderCache= JavaScriptPlugin.getDefault().getMemberOrderPreferenceCache();
- }
-
- private int category(BodyDeclaration bodyDeclaration) {
- switch (bodyDeclaration.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- {
- FunctionDeclaration method= (FunctionDeclaration) bodyDeclaration;
- if (method.isConstructor()) {
- return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
- }
- int flags= method.getModifiers();
- if (Modifier.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX);
- }
- case ASTNode.FIELD_DECLARATION :
- {
- int flags= ((FieldDeclaration) bodyDeclaration).getModifiers();
- if (Modifier.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX);
- }
- case ASTNode.INITIALIZER :
- {
- int flags= ((Initializer) bodyDeclaration).getModifiers();
- if (Modifier.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX);
- }
- case ASTNode.TYPE_DECLARATION :
- return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX);
-
- }
- return 0; // should never happen
- }
-
- private int getMemberCategory(int kind) {
- return fMemberOrderCache.getCategoryIndex(kind);
- }
-
- /**
- * This comparator follows the contract defined in JavaScriptUnitSorter.sort.
- * @see Comparator#compare(java.lang.Object, java.lang.Object)
- * @see JavaScriptUnitSorter#sort(int, org.eclipse.wst.jsdt.core.IJavaScriptUnit, int[], java.util.Comparator, int, org.eclipse.core.runtime.IProgressMonitor)
- */
- public int compare(Object e1, Object e2) {
- BodyDeclaration bodyDeclaration1= (BodyDeclaration) e1;
- BodyDeclaration bodyDeclaration2= (BodyDeclaration) e2;
- int cat1= category(bodyDeclaration1);
- int cat2= category(bodyDeclaration2);
-
- if (cat1 != cat2) {
- return cat1 - cat2;
- }
-
- if (fMemberOrderCache.isSortByVisibility()) {
- int flags1= JdtFlags.getVisibilityCode(bodyDeclaration1);
- int flags2= JdtFlags.getVisibilityCode(bodyDeclaration2);
- int vis= fMemberOrderCache.getVisibilityIndex(flags1) - fMemberOrderCache.getVisibilityIndex(flags2);
- if (vis != 0) {
- return vis;
- }
- }
-
- switch (bodyDeclaration1.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION :
- {
- FunctionDeclaration method1= (FunctionDeclaration) bodyDeclaration1;
- FunctionDeclaration method2= (FunctionDeclaration) bodyDeclaration2;
-
- if (fMemberOrderCache.isSortByVisibility()) {
- int vis= fMemberOrderCache.getVisibilityIndex(method1.getModifiers()) - fMemberOrderCache.getVisibilityIndex(method2.getModifiers());
- if (vis != 0) {
- return vis;
- }
- }
-
- String name1= method1.getName().getIdentifier();
- String name2= method2.getName().getIdentifier();
-
- // method declarations (constructors) are sorted by name
- int cmp= this.fCollator.compare(name1, name2);
- if (cmp != 0) {
- return cmp;
- }
-
- // if names equal, sort by parameter types
- List parameters1= method1.parameters();
- List parameters2= method2.parameters();
- int length1= parameters1.size();
- int length2= parameters2.size();
-
- int len= Math.min(length1, length2);
- for (int i= 0; i < len; i++) {
- SingleVariableDeclaration param1= (SingleVariableDeclaration) parameters1.get(i);
- SingleVariableDeclaration param2= (SingleVariableDeclaration) parameters2.get(i);
- cmp= this.fCollator.compare(buildSignature(param1.getType()), buildSignature(param2.getType()));
- if (cmp != 0) {
- return cmp;
- }
- }
- if (length1 != length2) {
- return length1 - length2;
- }
- return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2);
- }
- case ASTNode.FIELD_DECLARATION :
- {
- if (!fDoNotSortFields) {
- FieldDeclaration field1= (FieldDeclaration) bodyDeclaration1;
- FieldDeclaration field2= (FieldDeclaration) bodyDeclaration2;
-
- String name1= ((VariableDeclarationFragment) field1.fragments().get(0)).getName().getIdentifier();
- String name2= ((VariableDeclarationFragment) field2.fragments().get(0)).getName().getIdentifier();
-
- // field declarations are sorted by name
- return compareNames(bodyDeclaration1, bodyDeclaration2, name1, name2);
- } else {
- return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2);
- }
- }
- case ASTNode.INITIALIZER :
- {
- // preserve relative order
- return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2);
- }
- case ASTNode.TYPE_DECLARATION :
- {
- AbstractTypeDeclaration type1= (AbstractTypeDeclaration) bodyDeclaration1;
- AbstractTypeDeclaration type2= (AbstractTypeDeclaration) bodyDeclaration2;
-
- String name1= type1.getName().getIdentifier();
- String name2= type2.getName().getIdentifier();
-
- // typedeclarations are sorted by name
- return compareNames(bodyDeclaration1, bodyDeclaration2, name1, name2);
- }
- }
- return 0;
- }
-
- private int preserveRelativeOrder(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) {
- int value1= ((Integer) bodyDeclaration1.getProperty(JavaScriptUnitSorter.RELATIVE_ORDER)).intValue();
- int value2= ((Integer) bodyDeclaration2.getProperty(JavaScriptUnitSorter.RELATIVE_ORDER)).intValue();
- return value1 - value2;
- }
-
- private int compareNames(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2, String name1, String name2) {
- int cmp= this.fCollator.compare(name1, name2);
- if (cmp != 0) {
- return cmp;
- }
- return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2);
- }
-
- private String buildSignature(Type type) {
- return ASTNodes.asString(type);
- }
- }
-
-
- private IJavaScriptUnit fCompilationUnit;
- private int[] fPositions;
- private final boolean fDoNotSortFields;
-
- /**
- * Creates the operation.
- * @param cu The working copy of a compilation unit.
- * @param positions Positions to track or <code>null</code> if no positions
- * should be tracked.
- */
- public SortMembersOperation(IJavaScriptUnit cu, int[] positions, boolean doNotSortFields) {
- fCompilationUnit= cu;
- fPositions= positions;
- fDoNotSortFields= doNotSortFields;
- }
-
-
- /**
- * Runs the operation.
- */
- public void run(IProgressMonitor monitor) throws CoreException {
- JavaScriptUnitSorter.sort(AST.JLS3, fCompilationUnit, fPositions, new DefaultJavaElementComparator(fDoNotSortFields), 0, monitor);
- }
-
- /**
- * @return Returns the scheduling rule for this operation
- */
- public ISchedulingRule getScheduleRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility.java
deleted file mode 100644
index 4c9913ee..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility.java
+++ /dev/null
@@ -1,1474 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.io.IOException;
-import java.lang.reflect.Modifier;
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.jface.text.templates.persistence.TemplateStore;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.NamingConventions;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContext;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProjectTemplateStore;
-import org.eclipse.wst.jsdt.ui.CodeStyleConfiguration;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class StubUtility {
-
- private static final String[] EMPTY= new String[0];
-
- private static final Set VALID_TYPE_BODY_TEMPLATES;
- static {
- VALID_TYPE_BODY_TEMPLATES= new HashSet();
- VALID_TYPE_BODY_TEMPLATES.add(CodeTemplateContextType.CLASSBODY_ID);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- */
- public static String getMethodBodyContent(boolean isConstructor, IJavaScriptProject project, String destTypeName, String methodName, String bodyStatement, String lineDelimiter) throws CoreException {
- String templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB_ID : CodeTemplateContextType.METHODSTUB_ID;
- Template template= getCodeTemplate(templateName, project);
- if (template == null) {
- return bodyStatement;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
- context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement);
- String str= evaluateTemplate(context, template, new String[] { CodeTemplateContextType.BODY_STATEMENT });
- if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) {
- return bodyStatement;
- }
- return str;
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- */
- public static String getGetterMethodBodyContent(IJavaScriptProject project, String destTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException {
- String templateName= CodeTemplateContextType.GETTERSTUB_ID;
- Template template= getCodeTemplate(templateName, project);
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
- context.setVariable(CodeTemplateContextType.FIELD, fieldName);
-
- return evaluateTemplate(context, template);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- */
- public static String getSetterMethodBodyContent(IJavaScriptProject project, String destTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException {
- String templateName= CodeTemplateContextType.SETTERSTUB_ID;
- Template template= getCodeTemplate(templateName, project);
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
- context.setVariable(CodeTemplateContextType.FIELD, fieldName);
- context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName);
- context.setVariable(CodeTemplateContextType.PARAM, paramName);
-
- return evaluateTemplate(context, template);
- }
-
- public static String getCatchBodyContent(IJavaScriptUnit cu, String exceptionType, String variableName, ASTNode locationInAST, String lineDelimiter) throws CoreException {
- String enclosingType= ""; //$NON-NLS-1$
- String enclosingMethod= ""; //$NON-NLS-1$
-
- if (locationInAST != null) {
- FunctionDeclaration parentMethod= ASTResolving.findParentMethodDeclaration(locationInAST);
- if (parentMethod != null) {
- enclosingMethod= parentMethod.getName().getIdentifier();
- locationInAST= parentMethod;
- }
- ASTNode parentType= ASTResolving.findParentType(locationInAST);
- if (parentType instanceof AbstractTypeDeclaration) {
- enclosingType= ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
- }
- }
- return getCatchBodyContent(cu, exceptionType, variableName, enclosingType, enclosingMethod, lineDelimiter);
- }
-
-
- public static String getCatchBodyContent(IJavaScriptUnit cu, String exceptionType, String variableName, String enclosingType, String enclosingMethod, String lineDelimiter) throws CoreException {
- Template template= getCodeTemplate(CodeTemplateContextType.CATCHBLOCK_ID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
-
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, enclosingType);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, enclosingMethod);
- context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, exceptionType);
- context.setVariable(CodeTemplateContextType.EXCEPTION_VAR, variableName);
- return evaluateTemplate(context, template);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getCompilationUnitContent(IJavaScriptUnit, String, String, String, String)
- */
- public static String getCompilationUnitContent(IJavaScriptUnit cu, String fileComment, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
- IPackageFragment pack= (IPackageFragment) cu.getParent();
- String packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$
- return getCompilationUnitContent(cu, packDecl, fileComment, typeComment, typeContent, lineDelimiter);
- }
-
- public static String getCompilationUnitContent(IJavaScriptUnit cu, String packDecl, String fileComment, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
- Template template= getCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
-
- IJavaScriptProject project= cu.getJavaScriptProject();
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, packDecl);
- context.setVariable(CodeTemplateContextType.TYPE_COMMENT, typeComment != null ? typeComment : ""); //$NON-NLS-1$
- context.setVariable(CodeTemplateContextType.FILE_COMMENT, fileComment != null ? fileComment : ""); //$NON-NLS-1$
- context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, typeContent);
- context.setVariable(CodeTemplateContextType.TYPENAME, JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName()));
-
- String[] fullLine= { CodeTemplateContextType.PACKAGE_DECLARATION, CodeTemplateContextType.FILE_COMMENT, CodeTemplateContextType.TYPE_COMMENT };
- return evaluateTemplate(context, template, fullLine);
- }
-
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getFileComment(IJavaScriptUnit, String)
- */
- public static String getFileComment(IJavaScriptUnit cu, String lineDelimiter) throws CoreException {
- Template template= getCodeTemplate(CodeTemplateContextType.FILECOMMENT_ID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
-
- IJavaScriptProject project= cu.getJavaScriptProject();
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.TYPENAME, JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName()));
- return evaluateTemplate(context, template);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getTypeComment(IJavaScriptUnit, String, String[], String)
- */
- public static String getTypeComment(IJavaScriptUnit cu, String typeQualifiedName, String lineDelim) throws CoreException {
- Template template= getCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelim);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature.getQualifier(typeQualifiedName));
- context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getSimpleName(typeQualifiedName));
-
- TemplateBuffer buffer;
- try {
- buffer= context.evaluate(template);
- } catch (BadLocationException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- } catch (TemplateException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- }
- String str= buffer.getString();
- if (Strings.containsOnlyWhitespaces(str)) {
- return null;
- }
-
- TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
- if (position == null) {
- return str;
- }
-
- IDocument document= new Document(str);
- int[] tagOffsets= position.getOffsets();
- for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
- try {
- insertTag(document, tagOffsets[i], position.getLength(), EMPTY, EMPTY, null, false, lineDelim);
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
- return document.get();
- }
-
- /*
- * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
- */
- public static String[] getParameterTypeNamesForSeeTag(IFunctionBinding binding) {
- ITypeBinding[] typeBindings= binding.getParameterTypes();
- String[] result= new String[typeBindings.length];
- for (int i= 0; i < result.length; i++) {
- ITypeBinding curr= typeBindings[i];
- curr= curr.getTypeDeclaration(); // no parameterized types
- result[i]= curr.getQualifiedName();
- }
- return result;
- }
-
- /*
- * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
- */
- private static String[] getParameterTypeNamesForSeeTag(IFunction overridden) {
- try {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(overridden.getJavaScriptProject());
- IBinding[] bindings= parser.createBindings(new IJavaScriptElement[] { overridden }, null);
- if (bindings.length == 1 && bindings[0] instanceof IFunctionBinding) {
- return getParameterTypeNamesForSeeTag((IFunctionBinding) bindings[0]);
- }
- } catch (IllegalStateException e) {
- // method does not exist
- }
- // fall back code. Not good for generic methods!
- String[] paramTypes= overridden.getParameterTypes();
- String[] paramTypeNames= new String[paramTypes.length];
- for (int i= 0; i < paramTypes.length; i++) {
- paramTypeNames[i]= Signature.toString(paramTypes[i]);
- }
- return paramTypeNames;
- }
-
- private static String getSeeTag(String declaringClassQualifiedName, String methodName, String[] parameterTypesQualifiedNames) {
- StringBuffer buf= new StringBuffer();
- buf.append("@see "); //$NON-NLS-1$
- buf.append(declaringClassQualifiedName);
- buf.append('#');
- buf.append(methodName);
- buf.append('(');
- for (int i= 0; i < parameterTypesQualifiedNames.length; i++) {
- if (i > 0) {
- buf.append(", "); //$NON-NLS-1$
- }
- buf.append(parameterTypesQualifiedNames[i]);
- }
- buf.append(')');
- return buf.toString();
- }
-
- /**
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getTypeBody(String, IJavaScriptUnit, String, String)
- */
- public static String getTypeBody(String templateID, IJavaScriptUnit cu, String typeName, String lineDelim) throws CoreException {
- if ( !VALID_TYPE_BODY_TEMPLATES.contains(templateID)) {
- throw new IllegalArgumentException("Invalid code template ID: " + templateID); //$NON-NLS-1$
- }
-
- Template template= getCodeTemplate(templateID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelim);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.TYPENAME, typeName);
-
- return evaluateTemplate(context, template);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getMethodComment(IJavaScriptUnit, String, String, String[], String[], String, String[], IFunction, String)
- */
- public static String getMethodComment(IJavaScriptUnit cu, String typeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IFunction target, boolean delegate, String lineDelimiter) throws CoreException {
- String templateName= CodeTemplateContextType.METHODCOMMENT_ID;
- if (retTypeSig == null) {
- templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
- } else if (target != null) {
- if (delegate)
- templateName= CodeTemplateContextType.DELEGATECOMMENT_ID;
- else
- templateName= CodeTemplateContextType.OVERRIDECOMMENT_ID;
- }
- Template template= getCodeTemplate(templateName, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
-
- if (retTypeSig != null) {
- context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature.toString(retTypeSig));
- }
- if (target != null && target.getDeclaringType()!=null) {
- String targetTypeName= target.getDeclaringType().getFullyQualifiedName('.');
- String[] targetParamTypeNames= getParameterTypeNamesForSeeTag(target);
- if (delegate)
- context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetTypeName, methodName, targetParamTypeNames));
- else
- context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetTypeName, methodName, targetParamTypeNames));
- }
- TemplateBuffer buffer;
- try {
- buffer= context.evaluate(template);
- } catch (BadLocationException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- } catch (TemplateException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- }
- if (buffer == null) {
- return null;
- }
-
- String str= buffer.getString();
- if (Strings.containsOnlyWhitespaces(str)) {
- return null;
- }
- TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
- if (position == null) {
- return str;
- }
-
- IDocument document= new Document(str);
- String[] exceptionNames= new String[excTypeSig.length];
- for (int i= 0; i < excTypeSig.length; i++) {
- exceptionNames[i]= Signature.toString(excTypeSig[i]);
- }
- String returnType= retTypeSig != null ? Signature.toString(retTypeSig) : null;
- int[] tagOffsets= position.getOffsets();
- for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
- try {
- insertTag(document, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, false, lineDelimiter);
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
- return document.get();
- }
-
- // remove lines for empty variables
- private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
- IDocument doc= new Document(buffer.getString());
- int nLines= doc.getNumberOfLines();
- MultiTextEdit edit= new MultiTextEdit();
- HashSet removedLines= new HashSet();
- for (int i= 0; i < variables.length; i++) {
- TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
- if (position == null || position.getLength() > 0) {
- continue;
- }
- int[] offsets= position.getOffsets();
- for (int k= 0; k < offsets.length; k++) {
- int line= doc.getLineOfOffset(offsets[k]);
- IRegion lineInfo= doc.getLineInformation(line);
- int offset= lineInfo.getOffset();
- String str= doc.get(offset, lineInfo.getLength());
- if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
- int nextStart= doc.getLineOffset(line + 1);
- edit.addChild(new DeleteEdit(offset, nextStart - offset));
- }
- }
- }
- edit.apply(doc, 0);
- return doc.get();
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- */
- public static String getFieldComment(IJavaScriptUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException {
- Template template= getCodeTemplate(CodeTemplateContextType.FIELDCOMMENT_ID, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName);
- context.setVariable(CodeTemplateContextType.FIELD, fieldName);
-
- return evaluateTemplate(context, template);
- }
-
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getSetterComment(IJavaScriptUnit, String, String, String, String, String, String, String)
- */
- public static String getSetterComment(IJavaScriptUnit cu, String typeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException {
- String templateName= CodeTemplateContextType.SETTERCOMMENT_ID;
- Template template= getCodeTemplate(templateName, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
-
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
- context.setVariable(CodeTemplateContextType.FIELD, fieldName);
- context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType);
- context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName);
- context.setVariable(CodeTemplateContextType.PARAM, paramName);
-
- return evaluateTemplate(context, template);
- }
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getGetterComment(IJavaScriptUnit, String, String, String, String, String, String)
- */
- public static String getGetterComment(IJavaScriptUnit cu, String typeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException {
- String templateName= CodeTemplateContextType.GETTERCOMMENT_ID;
- Template template= getCodeTemplate(templateName, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
- context.setVariable(CodeTemplateContextType.FIELD, fieldName);
- context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType);
- context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName);
-
- return evaluateTemplate(context, template);
- }
-
- private static String evaluateTemplate(CodeTemplateContext context, Template template) throws CoreException {
- TemplateBuffer buffer;
- try {
- buffer= context.evaluate(template);
- } catch (BadLocationException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- } catch (TemplateException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- }
- if (buffer == null)
- return null;
- String str= buffer.getString();
- if (Strings.containsOnlyWhitespaces(str)) {
- return null;
- }
- return str;
- }
-
- private static String evaluateTemplate(CodeTemplateContext context, Template template, String[] fullLineVariables) throws CoreException {
- TemplateBuffer buffer;
- try {
- buffer= context.evaluate(template);
- if (buffer == null)
- return null;
- String str= fixEmptyVariables(buffer, fullLineVariables);
- if (Strings.containsOnlyWhitespaces(str)) {
- return null;
- }
- return str;
- } catch (BadLocationException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- } catch (TemplateException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- }
- }
-
-
- /*
- * Don't use this method directly, use CodeGeneration.
- * @see org.eclipse.wst.jsdt.ui.CodeGeneration#getMethodComment(IJavaScriptUnit, String, FunctionDeclaration, boolean, String, String[], String)
- */
- public static String getMethodComment(IJavaScriptUnit cu, String typeName, FunctionDeclaration decl, boolean isDeprecated, String targetName, String targetMethodDeclaringTypeName, String[] targetMethodParameterTypeNames, boolean delegate, String lineDelimiter) throws CoreException {
- if (typeName==null)
- typeName=""; //$NON-NLS-1$
- boolean needsTarget= targetMethodDeclaringTypeName != null && targetMethodParameterTypeNames != null;
- String templateName= CodeTemplateContextType.METHODCOMMENT_ID;
- if (decl.isConstructor()) {
- templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
- } else if (needsTarget) {
- if (delegate)
- templateName= CodeTemplateContextType.DELEGATECOMMENT_ID;
- else
- templateName= CodeTemplateContextType.OVERRIDECOMMENT_ID;
- }
- Template template= getCodeTemplate(templateName, cu.getJavaScriptProject());
- if (template == null) {
- return null;
- }
- CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaScriptProject(), lineDelimiter);
- context.setCompilationUnitVariables(cu);
- context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
- context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier());
- if (!decl.isConstructor() &&getReturnType(decl)!=null) {
- context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(getReturnType(decl)));
- }
- if (needsTarget) {
- if (delegate)
- context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
- else
- context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
- }
-
- TemplateBuffer buffer;
- try {
- buffer= context.evaluate(template);
- } catch (BadLocationException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- } catch (TemplateException e) {
- throw new CoreException(Status.CANCEL_STATUS);
- }
- if (buffer == null)
- return null;
- String str= buffer.getString();
- if (Strings.containsOnlyWhitespaces(str)) {
- return null;
- }
- TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
- if (position == null) {
- return str;
- }
-
- IDocument textBuffer= new Document(str);
- List params= decl.parameters();
- String[] paramNames= new String[params.size()];
- for (int i= 0; i < paramNames.length; i++) {
- SingleVariableDeclaration elem= (SingleVariableDeclaration) params.get(i);
- paramNames[i]= elem.getName().getIdentifier();
- }
- List exceptions= decl.thrownExceptions();
- String[] exceptionNames= new String[exceptions.size()];
- for (int i= 0; i < exceptionNames.length; i++) {
- exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) exceptions.get(i));
- }
-
- String returnType= null;
- if (!decl.isConstructor()) {
- returnType= ASTNodes.asString(getReturnType(decl));
- }
- int[] tagOffsets= position.getOffsets();
- for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
- try {
- insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, isDeprecated, lineDelimiter);
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
- return textBuffer.get();
- }
-
- /**
- * @deprecated Deprecated to avoid deprecated warnings
- */
- private static ASTNode getReturnType(FunctionDeclaration decl) {
- // used from API, can't eliminate
- return (decl.getAST().apiLevel() == AST.JLS2) ? decl.getReturnType() : decl.getReturnType2();
- }
-
-
- private static TemplateVariable findVariable(TemplateBuffer buffer, String variable) {
- TemplateVariable[] positions= buffer.getVariables();
- for (int i= 0; i < positions.length; i++) {
- TemplateVariable curr= positions[i];
- if (variable.equals(curr.getType())) {
- return curr;
- }
- }
- return null;
- }
-
- private static void insertTag(IDocument textBuffer, int offset, int length, String[] paramNames, String[] exceptionNames, String returnType, boolean isDeprecated, String lineDelimiter) throws BadLocationException {
- IRegion region= textBuffer.getLineInformationOfOffset(offset);
- if (region == null) {
- return;
- }
- String lineStart= textBuffer.get(region.getOffset(), offset - region.getOffset());
-
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < paramNames.length; i++) {
- if (buf.length() > 0) {
- buf.append(lineDelimiter).append(lineStart);
- }
- buf.append("@param ").append(paramNames[i]); //$NON-NLS-1$
- }
- if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$
- if (buf.length() > 0) {
- buf.append(lineDelimiter).append(lineStart);
- }
- buf.append("@returns"); //$NON-NLS-1$
- if(!returnType.equals("any")) { //$NON-NLS-1$
- buf.append(" {" + returnType + "}"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- if (exceptionNames != null) {
- for (int i= 0; i < exceptionNames.length; i++) {
- if (buf.length() > 0) {
- buf.append(lineDelimiter).append(lineStart);
- }
- buf.append("@throws ").append(exceptionNames[i]); //$NON-NLS-1$
- }
- }
- if (isDeprecated) {
- if (buf.length() > 0) {
- buf.append(lineDelimiter).append(lineStart);
- }
- buf.append("@deprecated"); //$NON-NLS-1$
- }
- if (buf.length() == 0 && isAllCommentWhitespace(lineStart)) {
- int prevLine= textBuffer.getLineOfOffset(offset) -1;
- if (prevLine > 0) {
- IRegion prevRegion= textBuffer.getLineInformation(prevLine);
- int prevLineEnd= prevRegion.getOffset() + prevRegion.getLength();
- // clear full line
- textBuffer.replace(prevLineEnd, offset + length - prevLineEnd, ""); //$NON-NLS-1$
- return;
- }
- }
- textBuffer.replace(offset, length, buf.toString());
- }
-
- private static boolean isAllCommentWhitespace(String lineStart) {
- for (int i= 0; i < lineStart.length(); i++) {
- char ch= lineStart.charAt(i);
- if (!Character.isWhitespace(ch) && ch != '*') {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Returns the line delimiter which is used in the specified project.
- *
- * @param project the java project, or <code>null</code>
- * @return the used line delimiter
- */
- public static String getLineDelimiterUsed(IJavaScriptProject project) {
- return getProjectLineDelimiter(project);
- }
-
- private static String getProjectLineDelimiter(IJavaScriptProject javaProject) {
- IProject project= null;
- if (javaProject != null)
- project= javaProject.getProject();
-
- String lineDelimiter= getLineDelimiterPreference(project);
- if (lineDelimiter != null)
- return lineDelimiter;
-
- return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public static String getLineDelimiterPreference(IProject project) {
- IScopeContext[] scopeContext;
- if (project != null) {
- // project preference
- scopeContext= new IScopeContext[] { new ProjectScope(project) };
- String lineDelimiter= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
- if (lineDelimiter != null)
- return lineDelimiter;
- }
- // workspace preference
- scopeContext= new IScopeContext[] { new InstanceScope() };
- String platformDefault= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- return Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, platformDefault, scopeContext);
- }
-
- /**
- * Examines a string and returns the first line delimiter found.
- */
- public static String getLineDelimiterUsed(IJavaScriptElement elem) {
- while (elem != null && !(elem instanceof IOpenable)) {
- elem= elem.getParent();
- }
- if (elem != null) {
- try {
- return ((IOpenable) elem).findRecommendedLineSeparator();
- } catch (JavaScriptModelException exception) {
- // Use project setting
- }
- }
- return getProjectLineDelimiter(null);
- }
-
- /**
- * Evaluates the indentation used by a Java element. (in tabulators)
- */
- public static int getIndentUsed(IJavaScriptElement elem) throws JavaScriptModelException {
- if (elem instanceof ISourceReference) {
- IJavaScriptUnit cu= (IJavaScriptUnit) elem.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- IBuffer buf= cu.getBuffer();
- int offset= ((ISourceReference)elem).getSourceRange().getOffset();
- int i= offset;
- // find beginning of line
- while (i > 0 && !IndentManipulation.isLineDelimiterChar(buf.getChar(i - 1)) ){
- i--;
- }
- return Strings.computeIndentUnits(buf.getText(i, offset - i), elem.getJavaScriptProject());
- }
- }
- return 0;
- }
-
- /**
- * Returns the element after the give element.
- */
- public static IJavaScriptElement findNextSibling(IJavaScriptElement member) throws JavaScriptModelException {
- IJavaScriptElement parent= member.getParent();
- if (parent instanceof IParent) {
- IJavaScriptElement[] elements= ((IParent)parent).getChildren();
- for (int i= elements.length - 2; i >= 0 ; i--) {
- if (member.equals(elements[i])) {
- return elements[i+1];
- }
- }
- }
- return null;
- }
-
- public static String getTodoTaskTag(IJavaScriptProject project) {
- String markers= null;
- if (project == null) {
- markers= JavaScriptCore.getOption(JavaScriptCore.COMPILER_TASK_TAGS);
- } else {
- markers= project.getOption(JavaScriptCore.COMPILER_TASK_TAGS, true);
- }
-
- if (markers != null && markers.length() > 0) {
- int idx= markers.indexOf(',');
- if (idx == -1) {
- return markers;
- } else {
- return markers.substring(0, idx);
- }
- }
- return null;
- }
-
- private static String removeTypeArguments(String baseName) {
- int idx= baseName.indexOf('<');
- if (idx != -1) {
- return baseName.substring(0, idx);
- }
- return baseName;
- }
-
-
- // --------------------------- name suggestions --------------------------
-
- public static final int STATIC_FIELD= 1;
- public static final int INSTANCE_FIELD= 2;
- public static final int CONSTANT_FIELD= 3;
- public static final int PARAMETER= 4;
- public static final int LOCAL= 5;
-
- public static String[] getVariableNameSuggestions(int variableKind, IJavaScriptProject project, ITypeBinding expectedType, Expression assignedExpression, Collection excluded) {
- LinkedHashSet res= new LinkedHashSet(); // avoid duplicates but keep order
-
- if (assignedExpression != null) {
- String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
- if (nameFromExpression != null) {
- add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
- }
- }
- if (expectedType != null) {
- expectedType= Bindings.normalizeTypeBinding(expectedType);
- if (expectedType != null) {
- int dim= 0;
- if (expectedType.isArray()) {
- dim= expectedType.getDimensions();
- expectedType= expectedType.getElementType();
- }
- String typeName= expectedType.getQualifiedName();
- if (typeName.length() > 0) {
- String[] names= getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false);
- for (int i= 0; i < names.length; i++) {
- res.add(names[i]);
- }
- }
- }
- }
- if (assignedExpression != null) {
- // add at end, less important
- String nameFromParent= getBaseNameFromLocationInParent(project, assignedExpression);
- if (nameFromParent != null) {
- add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
- }
- }
- if (res.isEmpty()) {
- return getDefaultVariableNameSuggestions(variableKind, excluded);
- }
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- public static String[] getVariableNameSuggestions(int variableKind, IJavaScriptProject project, Type expectedType, Expression assignedExpression, Collection excluded) {
- LinkedHashSet res= new LinkedHashSet(); // avoid duplicates but keep order
-
- if (assignedExpression != null) {
- String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
- if (nameFromExpression != null) {
- add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
- }
- }
- if (expectedType != null) {
- int dim= 0;
- if (expectedType.isArrayType()) {
- ArrayType arrayType= (ArrayType) expectedType;
- dim= arrayType.getDimensions();
- expectedType= arrayType.getElementType();
- }
-
- String typeName= ASTNodes.asString(expectedType);
-
- if (typeName.length() > 0) {
- String[] names= getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false);
- for (int i= 0; i < names.length; i++) {
- res.add(names[i]);
- }
- }
- }
- if (assignedExpression != null) {
- // add at end, less important
- String nameFromParent= getBaseNameFromLocationInParent(project, assignedExpression);
- if (nameFromParent != null) {
- add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
- }
- }
- if (res.isEmpty()) {
- return getDefaultVariableNameSuggestions(variableKind, excluded);
- }
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- private static String[] getDefaultVariableNameSuggestions(int variableKind, Collection excluded) {
- String prop= variableKind == CONSTANT_FIELD ? "X" : "x"; //$NON-NLS-1$//$NON-NLS-2$
- String name= prop;
- int i= 1;
- while (excluded.contains(name)) {
- name= prop + i++;
- }
- return new String[] { name };
- }
-
- /**
- * Returns variable name suggestions for the given base name. This is a layer over the JDT.Core NamingConventions API to fix its shortcomings. JDT UI code should only use this
- * API.
- * @param variableKind Specifies what type the variable is: {@link #LOCAL}, {@link #PARAMETER}, {@link #STATIC_FIELD}, {@link #INSTANCE_FIELD} or {@link #CONSTANT_FIELD}.
- * @param project the current project
- * @param baseName the base name to make a suggestion on. the base name is expected to be a name without any pre- or suffixes in singular form. Type name are accepted as well.
- * @param dimensions if greater than 0, the resulting name will be in plural form
- * @param excluded a collection containing all excluded names or <code>null</code> if no names are excluded
- * @param evaluateDefault if set, the result is guaranteed to contain at least one result. If not, the result can be an empty array.
- *
- * @return returns the name suggestions sorted by relevance (best proposal first). If <code>evaluateDefault</code> is set to true, the returned array is never empty.
- * If <code>evaluateDefault</code> is set to false, an empty array is returned if there is no good suggestion for the given base name.
- */
- public static String[] getVariableNameSuggestions(int variableKind, IJavaScriptProject project, String baseName, int dimensions, Collection excluded, boolean evaluateDefault) {
- String name= workaround38111(baseName);
- name= removeTypeArguments(name);
- String packageName= new String(); // not used, so don't compute for now
- String[] result= null;
-
- switch (variableKind) {
- case CONSTANT_FIELD:
- result= getConstantSuggestions(project, packageName, name, dimensions, excluded);
- break;
- case STATIC_FIELD:
- result= sortByLength(NamingConventions.suggestFieldNames(project, packageName, name, dimensions, Flags.AccStatic, getExcludedArray(excluded)));
- break;
- case INSTANCE_FIELD:
- result= sortByLength(NamingConventions.suggestFieldNames(project, packageName, name, dimensions, 0, getExcludedArray(excluded)));
- break;
- case PARAMETER:
- result= sortByLength(NamingConventions.suggestArgumentNames(project, packageName, name, dimensions, getExcludedArray(excluded)));
- break;
- case LOCAL:
- result= sortByLength(NamingConventions.suggestLocalVariableNames(project, packageName, name, dimensions, getExcludedArray(excluded)));
- break;
- }
- if (evaluateDefault) {
- if (result.length == 0) {
- result= getDefaultVariableNameSuggestions(variableKind, excluded);
- }
- } else if (variableKind != CONSTANT_FIELD) {
- // see 166464 API DCR: specify if naming convention should return default value or not
- String defaultValue= "NAME"; // default as chosen by jdt.core //$NON-NLS-1$
- if (!name.toUpperCase().endsWith(defaultValue) && result[0].toUpperCase().endsWith(defaultValue)) {
- return new String[0];
- }
- }
- return result;
- }
-
- private static String[] getExcludedArray(Collection excluded) {
- if (excluded == null) {
- return null;
- } else if (excluded instanceof ExcludedCollection) {
- return ((ExcludedCollection) excluded).getExcludedArray();
- }
- return (String[]) excluded.toArray(new String[excluded.size()]);
- }
-
-
- private static final String[] KNOWN_METHOD_NAME_PREFIXES= { "get", "is", "to"}; //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$
-
-
- private static void add(String[] names, Set result) {
- for (int i= 0; i < names.length; i++) {
- result.add(names[i]);
- }
- }
-
- private static String getBaseNameFromExpression(IJavaScriptProject project, Expression assignedExpression, int variableKind) {
- String name= null;
-
- if (assignedExpression instanceof Name) {
- Name simpleNode= (Name) assignedExpression;
- IBinding binding= simpleNode.resolveBinding();
- if (binding instanceof IVariableBinding)
- return removePrefixAndSuffixForVariable(project, (IVariableBinding) binding);
-
- return ASTNodes.getSimpleNameIdentifier(simpleNode);
- } else if (assignedExpression instanceof FunctionInvocation) {
- SimpleName name2 = ((FunctionInvocation) assignedExpression).getName();
- if (name2!=null)
- name= name2.getIdentifier();
- } else if (assignedExpression instanceof SuperMethodInvocation) {
- name= ((SuperMethodInvocation) assignedExpression).getName().getIdentifier();
- } else if (assignedExpression instanceof FieldAccess) {
- return ((FieldAccess) assignedExpression).getName().getIdentifier();
- } else if (variableKind == CONSTANT_FIELD && (assignedExpression instanceof StringLiteral || assignedExpression instanceof NumberLiteral)) {
- String string= assignedExpression instanceof StringLiteral ? ((StringLiteral) assignedExpression).getLiteralValue() : ((NumberLiteral) assignedExpression).getToken();
- StringBuffer res= new StringBuffer();
- boolean needsUnderscore= false;
- for (int i= 0; i < string.length(); i++) {
- char ch= string.charAt(i);
- if (Character.isJavaIdentifierPart(ch)) {
- if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) {
- res.append('_');
- }
- res.append(ch);
- needsUnderscore= false;
- } else {
- needsUnderscore= res.length() > 0;
- }
- }
- if (res.length() > 0) {
- return res.toString();
- }
- }
- if (name != null) {
- for (int i= 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
- String curr= KNOWN_METHOD_NAME_PREFIXES[i];
- if (name.startsWith(curr)) {
- if (name.equals(curr)) {
- return null; // don't suggest 'get' as variable name
- } else if (Character.isUpperCase(name.charAt(curr.length()))) {
- return name.substring(curr.length());
- }
- }
- }
- }
- return name;
- }
-
- private static String getBaseNameFromLocationInParent(IJavaScriptProject project, Expression assignedExpression) {
- StructuralPropertyDescriptor location= assignedExpression.getLocationInParent();
- if (location == FunctionInvocation.ARGUMENTS_PROPERTY) {
- FunctionInvocation parent= (FunctionInvocation) assignedExpression.getParent();
- IFunctionBinding binding= parent.resolveMethodBinding();
- int index= parent.arguments().indexOf(assignedExpression);
- if (binding != null && index != -1) {
- return getParameterName(binding, index);
- }
- } else if (location == ClassInstanceCreation.ARGUMENTS_PROPERTY) {
- ClassInstanceCreation parent= (ClassInstanceCreation) assignedExpression.getParent();
- IFunctionBinding binding= parent.resolveConstructorBinding();
- int index= parent.arguments().indexOf(assignedExpression);
- if (binding != null && index != -1) {
- return getParameterName(binding, index);
- }
- } else if (location == SuperMethodInvocation.ARGUMENTS_PROPERTY) {
- SuperMethodInvocation parent= (SuperMethodInvocation) assignedExpression.getParent();
- IFunctionBinding binding= parent.resolveMethodBinding();
- int index= parent.arguments().indexOf(assignedExpression);
- if (binding != null && index != -1) {
- return getParameterName(binding, index);
- }
- } else if (location == ConstructorInvocation.ARGUMENTS_PROPERTY) {
- ConstructorInvocation parent= (ConstructorInvocation) assignedExpression.getParent();
- IFunctionBinding binding= parent.resolveConstructorBinding();
- int index= parent.arguments().indexOf(assignedExpression);
- if (binding != null && index != -1) {
- return getParameterName(binding, index);
- }
- } else if (location == SuperConstructorInvocation.ARGUMENTS_PROPERTY) {
- SuperConstructorInvocation parent= (SuperConstructorInvocation) assignedExpression.getParent();
- IFunctionBinding binding= parent.resolveConstructorBinding();
- int index= parent.arguments().indexOf(assignedExpression);
- if (binding != null && index != -1) {
- return getParameterName(binding, index);
- }
- }
- return null;
- }
-
- private static String getParameterName(IFunctionBinding binding, int index) {
- try {
- IJavaScriptElement javaElement= binding.getJavaElement();
- if (javaElement instanceof IFunction) {
- IFunction method= (IFunction) javaElement;
- if (method.getOpenable().getBuffer() != null) { // avoid dummy names and lookup from Javadoc
- String[] parameterNames= method.getParameterNames();
- if (index < parameterNames.length) {
- return NamingConventions.removePrefixAndSuffixForArgumentName(method.getJavaScriptProject(), parameterNames[index]);
- }
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return null;
- }
-
- public static String[] getArgumentNameSuggestions(IType type,IJavaScriptUnit compUnit, String[] excluded) {
- String baseName= (type!=null)?JavaModelUtil.getFullyQualifiedName(type) : compUnit.getElementName();
- return getVariableNameSuggestions(PARAMETER, compUnit.getJavaScriptProject(),baseName, 0, new ExcludedCollection(excluded), true);
- }
-
- public static String[] getArgumentNameSuggestions(IType type, String[] excluded) {
- return getVariableNameSuggestions(PARAMETER, type.getJavaScriptProject(), JavaModelUtil.getFullyQualifiedName(type), 0, new ExcludedCollection(excluded), true);
- }
-
- public static String[] getArgumentNameSuggestions(IJavaScriptProject project, Type type, String[] excluded) {
- int dim= 0;
- if (type.isArrayType()) {
- ArrayType arrayType= (ArrayType) type;
- dim= arrayType.getDimensions();
- type= arrayType.getElementType();
- }
-
- return getVariableNameSuggestions(PARAMETER, project, ASTNodes.asString(type), dim, new ExcludedCollection(excluded), true);
- }
-
- public static String[] getArgumentNameSuggestions(IJavaScriptProject project, ITypeBinding binding, String[] excluded) {
- return getVariableNameSuggestions(PARAMETER, project, binding, null, new ExcludedCollection(excluded));
- }
-
- public static String[] getArgumentNameSuggestions(IJavaScriptProject project, String baseName, int dimensions, String[] excluded) {
- return getVariableNameSuggestions(PARAMETER, project, baseName, dimensions, new ExcludedCollection(excluded), true);
- }
-
- public static String[] getFieldNameSuggestions(IType type, int fieldModifiers, String[] excluded) {
- return getFieldNameSuggestions(type.getJavaScriptProject(), JavaModelUtil.getFullyQualifiedName(type), 0, fieldModifiers, excluded);
- }
-
- public static String[] getFieldNameSuggestions(IJavaScriptProject project, String baseName, int dimensions, int modifiers, String[] excluded) {
- if (Flags.isStatic(modifiers)) {
- return getVariableNameSuggestions(STATIC_FIELD, project, baseName, dimensions, new ExcludedCollection(excluded), true);
- }
- return getVariableNameSuggestions(INSTANCE_FIELD, project, baseName, dimensions, new ExcludedCollection(excluded), true);
- }
-
- private static String[] getConstantSuggestions(IJavaScriptProject project, String packageName, String typeName, int dimensions, Collection excluded) {
- //TODO: workaround JDT/Core bug 85946
-
- String string= Signature.getSimpleName(typeName);
-
- StringBuffer buf= new StringBuffer();
- boolean wasUpperCase= true;
- for (int i= 0; i < string.length() ; i++) {
- char ch= string.charAt(i);
- if (Character.isUpperCase(ch)) {
- if (!wasUpperCase) {
- buf.append('_');
- }
- buf.append(ch);
- } else {
- buf.append(Character.toUpperCase(ch));
- wasUpperCase= ch == '_'; // avoid duplicate underscores
- }
- }
- ArrayList res= new ArrayList();
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
-
- boolean nameStarts= true;
- for (int i= 0; i < buf.length(); i++) {
- if (nameStarts) {
- String prop= buf.substring(i);
- if (!excluded.contains(prop) && JavaScriptConventions.validateFieldName(prop, sourceLevel, complianceLevel).isOK()) {
- res.add(prop);
- }
- }
- char ch= buf.charAt(i);
- nameStarts= ch == '_';
- }
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- private static String getCamelCaseFromUpper(String string) {
- StringBuffer result= new StringBuffer();
- boolean lastWasUnderscore= false;
- for (int i= 0; i < string.length(); i++) {
- char ch= string.charAt(i);
- if (Character.isUpperCase(ch)) {
- if (!lastWasUnderscore) {
- ch= Character.toLowerCase(ch);
- }
- result.append(ch);
- lastWasUnderscore= false;
- } else if (ch == '_') {
- lastWasUnderscore= true;
- } else {
- return string; // abort
- }
- }
- return result.toString();
- }
-
- public static String[] getLocalNameSuggestions(IJavaScriptProject project, String baseName, int dimensions, String[] excluded) {
- return getVariableNameSuggestions(LOCAL, project, baseName, dimensions, new ExcludedCollection(excluded), true);
- }
-
- private static String[] sortByLength(String[] proposals) {
- Arrays.sort(proposals, new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((String) o2).length() - ((String) o1).length();
- }
- });
- return proposals;
- }
-
- private static String workaround38111(String baseName) {
- if (BASE_TYPES.contains(baseName))
- return baseName;
- return Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1);
- }
-
- private static final List BASE_TYPES= Arrays.asList(
- new String[] {"boolean", "byte", "char", "double", "float", "int", "long", "short"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-
- public static String suggestArgumentName(IJavaScriptProject project, String baseName, String[] excluded) {
- return suggestVariableName(PARAMETER, project, baseName, 0, excluded);
- }
-
- private static String suggestVariableName(int varKind, IJavaScriptProject project, String baseName, int dimension, String[] excluded) {
- return getVariableNameSuggestions(varKind, project, baseName, dimension, new ExcludedCollection(excluded), true)[0];
- }
-
-
- public static String[][] suggestArgumentNamesWithProposals(IJavaScriptProject project, String[] paramNames) {
- String[][] newNames= new String[paramNames.length][];
- ArrayList takenNames= new ArrayList();
-
- // Ensure that the code generation preferences are respected
- for (int i= 0; i < paramNames.length; i++) {
- String curr= paramNames[i];
- String baseName= NamingConventions.removePrefixAndSuffixForArgumentName(project, curr);
-
- String[] proposedNames= getVariableNameSuggestions(PARAMETER, project, curr, 0, takenNames, true);
- if (!curr.equals(baseName)) {
- // make the existing name to favourite
- LinkedHashSet updatedNames= new LinkedHashSet();
- updatedNames.add(curr);
- for (int k= 0; k < proposedNames.length; k++) {
- updatedNames.add(proposedNames[k]);
- }
- proposedNames= (String[]) updatedNames.toArray(new String[updatedNames.size()]);
- }
- newNames[i]= proposedNames;
- takenNames.add(proposedNames[0]);
- }
- return newNames;
- }
-
- public static String[][] suggestArgumentNamesWithProposals(IJavaScriptProject project, IFunctionBinding binding) {
- int nParams= binding.getParameterTypes().length;
- if (nParams > 0) {
- try {
- IFunction method= (IFunction) binding.getMethodDeclaration().getJavaElement();
- if (method != null) {
- return suggestArgumentNamesWithProposals(project, method.getParameterNames());
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- String[][] names= new String[nParams][];
- for (int i= 0; i < names.length; i++) {
- names[i]= new String[] { "arg" + i }; //$NON-NLS-1$
- }
- return names;
- }
-
-
- public static String[] suggestArgumentNames(IJavaScriptProject project, IFunctionBinding binding) {
- int nParams= binding.getParameterTypes().length;
-
- if (nParams > 0) {
- try {
- IFunction method= (IFunction) binding.getMethodDeclaration().getJavaElement();
- if (method != null) {
- String[] paramNames= method.getParameterNames();
- String[] namesArray= new String[0];
- ArrayList newNames= new ArrayList(paramNames.length);
- // Ensure that the code generation preferences are respected
- for (int i= 0; i < paramNames.length; i++) {
- String curr= paramNames[i];
- String baseName= NamingConventions.removePrefixAndSuffixForArgumentName(project, curr);
- if (!curr.equals(baseName)) {
- // make the existing name the favourite
- newNames.add(curr);
- } else {
- newNames.add(suggestArgumentName(project, curr, namesArray));
- }
- namesArray= (String[]) newNames.toArray(new String[newNames.size()]);
- }
- return namesArray;
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- String[] names= new String[nParams];
- for (int i= 0; i < names.length; i++) {
- names[i]= "arg" + i; //$NON-NLS-1$
- }
- return names;
- }
-
- public static String removePrefixAndSuffixForVariable(IJavaScriptProject project, IVariableBinding binding) {
- if (binding.isField()) {
- if (Modifier.isStatic(binding.getModifiers()) && Modifier.isFinal(binding.getModifiers())) {
- return getCamelCaseFromUpper(binding.getName());
- } else {
- return NamingConventions.removePrefixAndSuffixForFieldName(project, binding.getName(), binding.getModifiers());
- }
- } else if (binding.isParameter()) {
- return NamingConventions.removePrefixAndSuffixForArgumentName(project, binding.getName());
- } else {
- return NamingConventions.removePrefixAndSuffixForLocalVariableName(project, binding.getName());
- }
- }
-
- private static class ExcludedCollection extends AbstractList {
- private String[] fExcluded;
- public ExcludedCollection(String[] excluded) {
- fExcluded = excluded;
- }
- public String[] getExcludedArray() {
- return fExcluded;
- }
- public int size() {
- return fExcluded.length;
- }
- public Object get(int index) {
- return fExcluded[index];
- }
- public int indexOf(Object o) {
- if (o instanceof String) {
- for (int i= 0; i < fExcluded.length; i++) {
- if (o.equals(fExcluded[i]))
- return i;
- }
- }
- return -1;
- }
- public boolean contains(Object o) {
- return indexOf(o) != -1;
- }
- }
-
-
- public static boolean hasFieldName(IJavaScriptProject project, String name) {
- String prefixes= project.getOption(JavaScriptCore.CODEASSIST_FIELD_PREFIXES, true);
- String suffixes= project.getOption(JavaScriptCore.CODEASSIST_FIELD_SUFFIXES, true);
- String staticPrefixes= project.getOption(JavaScriptCore.CODEASSIST_STATIC_FIELD_PREFIXES, true);
- String staticSuffixes= project.getOption(JavaScriptCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true);
-
-
- return hasPrefixOrSuffix(prefixes, suffixes, name)
- || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name);
- }
-
- public static boolean hasParameterName(IJavaScriptProject project, String name) {
- String prefixes= project.getOption(JavaScriptCore.CODEASSIST_ARGUMENT_PREFIXES, true);
- String suffixes= project.getOption(JavaScriptCore.CODEASSIST_ARGUMENT_SUFFIXES, true);
- return hasPrefixOrSuffix(prefixes, suffixes, name);
- }
-
- public static boolean hasLocalVariableName(IJavaScriptProject project, String name) {
- String prefixes= project.getOption(JavaScriptCore.CODEASSIST_LOCAL_PREFIXES, true);
- String suffixes= project.getOption(JavaScriptCore.CODEASSIST_LOCAL_SUFFIXES, true);
- return hasPrefixOrSuffix(prefixes, suffixes, name);
- }
-
- public static boolean hasConstantName(String name) {
- return Character.isUpperCase(name.charAt(0));
- }
-
-
- private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, String name) {
- final String listSeparartor= ","; //$NON-NLS-1$
-
- StringTokenizer tok= new StringTokenizer(prefixes, listSeparartor);
- while (tok.hasMoreTokens()) {
- String curr= tok.nextToken();
- if (name.startsWith(curr)) {
- return true;
- }
- }
-
- tok= new StringTokenizer(suffixes, listSeparartor);
- while (tok.hasMoreTokens()) {
- String curr= tok.nextToken();
- if (name.endsWith(curr)) {
- return true;
- }
- }
- return false;
- }
-
- // -------------------- preference access -----------------------
-
- public static boolean useThisForFieldAccess(IJavaScriptProject project) {
- return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_KEYWORD_THIS, project)).booleanValue();
- }
-
- public static boolean useIsForBooleanGetters(IJavaScriptProject project) {
- return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, project)).booleanValue();
- }
-
- public static String getExceptionVariableName(IJavaScriptProject project) {
- return PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, project);
- }
-
- public static boolean doAddComments(IJavaScriptProject project) {
- return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, project)).booleanValue();
- }
-
- public static void setCodeTemplate(String templateId, String pattern, IJavaScriptProject project) {
- TemplateStore codeTemplateStore= JavaScriptPlugin.getDefault().getCodeTemplateStore();
- TemplatePersistenceData data= codeTemplateStore.getTemplateData(templateId);
- Template orig= data.getTemplate();
- Template copy= new Template(orig.getName(), orig.getDescription(), orig.getContextTypeId(), pattern, true);
- data.setTemplate(copy);
- }
-
- private static Template getCodeTemplate(String id, IJavaScriptProject project) {
- if (project == null)
- return JavaScriptPlugin.getDefault().getCodeTemplateStore().findTemplateById(id);
- ProjectTemplateStore projectStore= new ProjectTemplateStore(project.getProject());
- try {
- projectStore.load();
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
- return projectStore.findTemplateById(id);
- }
-
-
- public static ImportRewrite createImportRewrite(IJavaScriptUnit cu, boolean restoreExistingImports) throws JavaScriptModelException {
- return CodeStyleConfiguration.createImportRewrite(cu, restoreExistingImports);
- }
-
- public static ImportRewrite createImportRewrite(JavaScriptUnit astRoot, boolean restoreExistingImports) {
- return CodeStyleConfiguration.createImportRewrite(astRoot, restoreExistingImports);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility2.java
deleted file mode 100644
index ee71fea1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/StubUtility2.java
+++ /dev/null
@@ -1,696 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.codemanipulation;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.NamingConventions;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IPackageBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public final class StubUtility2 {
-
- public static FunctionDeclaration createConstructorStub(IJavaScriptUnit unit, ASTRewrite rewrite, ImportRewrite imports, IFunctionBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, CodeGenerationSettings settings) throws CoreException {
- AST ast= rewrite.getAST();
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
- decl.setName(ast.newSimpleName(type));
- decl.setConstructor(true);
-
- List parameters= createParameters(unit, imports, ast, binding, decl, null);
-
- Block body= ast.newBlock();
- decl.setBody(body);
-
- String delimiter= StubUtility.getLineDelimiterUsed(unit);
- String bodyStatement= ""; //$NON-NLS-1$
- if (!omitSuperForDefConst || !parameters.isEmpty()) {
- SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
- SingleVariableDeclaration varDecl= null;
- for (Iterator iterator= parameters.iterator(); iterator.hasNext();) {
- varDecl= (SingleVariableDeclaration) iterator.next();
- invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
- }
- bodyStatement= ASTNodes.asFormattedString(invocation, 0, delimiter, unit.getJavaScriptProject().getOptions(true));
- }
-
- if (todo) {
- String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), true, bodyStatement, delimiter);
- if (placeHolder != null) {
- ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
- body.statements().add(todoNode);
- }
- } else {
- ASTNode statementNode= rewrite.createStringPlaceholder(bodyStatement, ASTNode.RETURN_STATEMENT);
- body.statements().add(statementNode);
- }
-
- if (settings != null && settings.createComments) {
- String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
- public static FunctionDeclaration createConstructorStub(IJavaScriptUnit unit, ASTRewrite rewrite, ImportRewrite imports, ITypeBinding typeBinding, AST ast, IFunctionBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
-
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
- decl.setName(ast.newSimpleName(typeBinding.getName()));
- decl.setConstructor(true);
-
- List parameters= decl.parameters();
- if (superConstructor != null) {
-
- createParameters(unit, imports, ast, superConstructor, decl, null);
- }
-
- Block body= ast.newBlock();
- decl.setBody(body);
-
- String delimiter= StubUtility.getLineDelimiterUsed(unit);
-
- if (superConstructor != null) {
- SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
- SingleVariableDeclaration varDecl= null;
- for (Iterator iterator= parameters.iterator(); iterator.hasNext();) {
- varDecl= (SingleVariableDeclaration) iterator.next();
- invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
- }
- body.statements().add(invocation);
- }
-
- List prohibited= new ArrayList();
- for (final Iterator iterator= parameters.iterator(); iterator.hasNext();)
- prohibited.add(((SingleVariableDeclaration) iterator.next()).getName().getIdentifier());
- String param= null;
- List list= new ArrayList(prohibited);
- String[] excluded= null;
- for (int i= 0; i < variableBindings.length; i++) {
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- var.setType(imports.addImport(variableBindings[i].getType(), ast));
- excluded= new String[list.size()];
- list.toArray(excluded);
- param= getParameterName(unit, variableBindings[i], excluded);
- list.add(param);
- var.setName(ast.newSimpleName(param));
- parameters.add(var);
- }
-
- list= new ArrayList(prohibited);
- for (int i= 0; i < variableBindings.length; i++) {
- excluded= new String[list.size()];
- list.toArray(excluded);
- final String paramName= getParameterName(unit, variableBindings[i], excluded);
- list.add(paramName);
- final String fieldName= variableBindings[i].getName();
- Expression expression= null;
- if (paramName.equals(fieldName) || settings.useKeywordThis) {
- FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fieldName));
- expression= access;
- } else
- expression= ast.newSimpleName(fieldName);
- Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide(expression);
- assignment.setRightHandSide(ast.newSimpleName(paramName));
- assignment.setOperator(Assignment.Operator.ASSIGN);
- body.statements().add(ast.newExpressionStatement(assignment));
- }
-
- if (settings != null && settings.createComments) {
- String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
- public static FunctionDeclaration createDelegationStub(IJavaScriptUnit unit, ASTRewrite rewrite, ImportRewrite imports, AST ast, IBinding[] bindings, CodeGenerationSettings settings) throws CoreException {
- Assert.isNotNull(bindings);
- Assert.isNotNull(settings);
- Assert.isTrue(bindings.length == 2);
- Assert.isTrue(bindings[0] instanceof IVariableBinding);
- Assert.isTrue(bindings[1] instanceof IFunctionBinding);
-
- IVariableBinding variableBinding= (IVariableBinding) bindings[0];
- IFunctionBinding methodBinding= (IFunctionBinding) bindings[1];
-
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, methodBinding.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
-
- decl.setName(ast.newSimpleName(methodBinding.getName()));
- decl.setConstructor(false);
-
- decl.setReturnType2(imports.addImport(methodBinding.getReturnType(), ast));
-
- List parameters= decl.parameters();
- ITypeBinding[] params= methodBinding.getParameterTypes();
- String[] paramNames= StubUtility.suggestArgumentNames(unit.getJavaScriptProject(), methodBinding);
- for (int i= 0; i < params.length; i++) {
- SingleVariableDeclaration varDecl= ast.newSingleVariableDeclaration();
-
- if (methodBinding.isVarargs() && params[i].isArray() && i == params.length - 1) {
- StringBuffer buffer= new StringBuffer(imports.addImport(params[i].getElementType()));
- for (int dim= 1; dim < params[i].getDimensions(); dim++)
- buffer.append("[]"); //$NON-NLS-1$
- varDecl.setType(ASTNodeFactory.newType(ast, buffer.toString()));
- varDecl.setVarargs(true);
- } else
- varDecl.setType(imports.addImport(params[i], ast));
-
- varDecl.setName(ast.newSimpleName(paramNames[i]));
- parameters.add(varDecl);
- }
-
- Block body= ast.newBlock();
- decl.setBody(body);
-
- String delimiter= StubUtility.getLineDelimiterUsed(unit);
-
- Statement statement= null;
- FunctionInvocation invocation= ast.newFunctionInvocation();
- invocation.setName(ast.newSimpleName(methodBinding.getName()));
- List arguments= invocation.arguments();
- for (int i= 0; i < params.length; i++)
- arguments.add(ast.newSimpleName(paramNames[i]));
- if (settings.useKeywordThis) {
- FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(variableBinding.getName()));
- invocation.setExpression(access);
- } else
- invocation.setExpression(ast.newSimpleName(variableBinding.getName()));
- if (methodBinding.getReturnType().isPrimitive() && methodBinding.getReturnType().getName().equals("void")) {//$NON-NLS-1$
- statement= ast.newExpressionStatement(invocation);
- } else {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(invocation);
- statement= returnStatement;
- }
- body.statements().add(statement);
-
- ITypeBinding declaringType= variableBinding.getDeclaringClass();
- if (declaringType == null) { // can be null for
- return decl;
- }
-
- String qualifiedName= declaringType.getQualifiedName();
- IPackageBinding packageBinding= declaringType.getPackage();
- if (packageBinding != null) {
- if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
- qualifiedName= qualifiedName.substring(packageBinding.getName().length());
- }
-
- if (settings.createComments) {
- /*
- * TODO: have API for delegate method comments This is an inlined
- * version of
- * {@link CodeGeneration#getMethodComment(IJavaScriptUnit, String, FunctionDeclaration, IFunctionBinding, String)}
- */
- methodBinding= methodBinding.getMethodDeclaration();
- String declaringClassQualifiedName= methodBinding.getDeclaringClass().getQualifiedName();
- String linkToMethodName= methodBinding.getName();
- String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(methodBinding);
- String string= StubUtility.getMethodComment(unit, qualifiedName, decl, methodBinding.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
- public static FunctionDeclaration createImplementationStub(IJavaScriptUnit unit, ASTRewrite rewrite, ImportRewrite imports, AST ast, IFunctionBinding binding, String type, CodeGenerationSettings settings, boolean deferred, ImportRewriteContext context) throws CoreException {
-
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.modifiers().addAll(getImplementationModifiers(ast, binding, deferred));
-
- decl.setName(ast.newSimpleName(binding.getName()));
- decl.setConstructor(false);
-
- decl.setReturnType2(imports.addImport(binding.getReturnType(), ast, context));
-
- List parameters= createParameters(unit, imports, ast, binding, decl, context);
-
- String delimiter= StubUtility.getLineDelimiterUsed(unit);
- if (!deferred) {
- Map options= unit.getJavaScriptProject().getOptions(true);
-
- Block body= ast.newBlock();
- decl.setBody(body);
-
- String bodyStatement= ""; //$NON-NLS-1$
- if (Modifier.isAbstract(binding.getModifiers())) {
- Expression expression= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
- if (expression != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
- }
- } else {
- SuperMethodInvocation invocation= ast.newSuperMethodInvocation();
- invocation.setName(ast.newSimpleName(binding.getName()));
- SingleVariableDeclaration varDecl= null;
- for (Iterator iterator= parameters.iterator(); iterator.hasNext();) {
- varDecl= (SingleVariableDeclaration) iterator.next();
- invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
- }
- Expression expression= invocation;
- Type returnType= decl.getReturnType2();
- if (returnType != null && (returnType instanceof PrimitiveType) && ((PrimitiveType) returnType).getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
- bodyStatement= ASTNodes.asFormattedString(ast.newExpressionStatement(expression), 0, delimiter, options);
- } else {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
- }
- }
-
- String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), false, bodyStatement, delimiter);
- if (placeHolder != null) {
- ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
- body.statements().add(todoNode);
- }
- }
-
- if (settings.createComments) {
- String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
-
- return decl;
- }
-
- public static FunctionDeclaration createImplementationStub(IJavaScriptUnit unit, ASTRewrite rewrite, ImportRewrite importRewrite, IFunctionBinding binding, String type, boolean deferred, CodeGenerationSettings settings) throws CoreException {
- AST ast= rewrite.getAST();
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.modifiers().addAll(getImplementationModifiers(ast, binding, deferred));
-
- decl.setName(ast.newSimpleName(binding.getName()));
- decl.setConstructor(false);
-
- decl.setReturnType2(createTypeNode(importRewrite, binding.getReturnType(), ast));
-
- List parameters= createParameters(unit, importRewrite, ast, binding, decl);
-
- String delimiter= StubUtility.getLineDelimiterUsed(unit);
- if (!deferred) {
- Map options= unit.getJavaScriptProject().getOptions(true);
-
- Block body= ast.newBlock();
- decl.setBody(body);
-
- String bodyStatement= ""; //$NON-NLS-1$
- if (Modifier.isAbstract(binding.getModifiers())) {
- Expression expression= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
- if (expression != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
- }
- } else {
- SuperMethodInvocation invocation= ast.newSuperMethodInvocation();
- invocation.setName(ast.newSimpleName(binding.getName()));
- SingleVariableDeclaration varDecl= null;
- for (Iterator iterator= parameters.iterator(); iterator.hasNext();) {
- varDecl= (SingleVariableDeclaration) iterator.next();
- invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
- }
- Expression expression= invocation;
- Type returnType= decl.getReturnType2();
- if (returnType instanceof PrimitiveType && ((PrimitiveType) returnType).getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
- bodyStatement= ASTNodes.asFormattedString(ast.newExpressionStatement(expression), 0, delimiter, options);
- } else {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
- }
- }
-
- String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), false, bodyStatement, delimiter);
- if (placeHolder != null) {
- ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
- body.statements().add(todoNode);
- }
- }
-
- if (settings != null && settings.createComments) {
- String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
- private static List createParameters(IJavaScriptUnit unit, ImportRewrite imports, AST ast, IFunctionBinding binding, FunctionDeclaration decl, ImportRewriteContext context) {
- List parameters= decl.parameters();
- ITypeBinding[] params= binding.getParameterTypes();
- String[] paramNames= StubUtility.suggestArgumentNames(unit.getJavaScriptProject(), binding);
- for (int i= 0; i < params.length; i++) {
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- if (binding.isVarargs() && params[i].isArray() && i == params.length - 1) {
- StringBuffer buffer= new StringBuffer(imports.addImport(params[i].getElementType(), context));
- for (int dim= 1; dim < params[i].getDimensions(); dim++)
- buffer.append("[]"); //$NON-NLS-1$
- var.setType(ASTNodeFactory.newType(ast, buffer.toString()));
- var.setVarargs(true);
- } else
- var.setType(imports.addImport(params[i], ast, context));
- var.setName(ast.newSimpleName(paramNames[i]));
- parameters.add(var);
- }
- return parameters;
- }
-
- private static List createParameters(IJavaScriptUnit unit, ImportRewrite imports, AST ast, IFunctionBinding binding, FunctionDeclaration decl) {
- List parameters= decl.parameters();
- ITypeBinding[] params= binding.getParameterTypes();
- String[] paramNames= StubUtility.suggestArgumentNames(unit.getJavaScriptProject(), binding);
- for (int i= 0; i < params.length; i++) {
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- if (binding.isVarargs() && params[i].isArray() && i == params.length - 1) {
- final ITypeBinding elementType= params[i].getElementType();
- StringBuffer buffer= new StringBuffer(imports != null ? imports.addImport(elementType) : elementType.getQualifiedName());
- for (int dim= 1; dim < params[i].getDimensions(); dim++)
- buffer.append("[]"); //$NON-NLS-1$
- var.setType(ASTNodeFactory.newType(ast, buffer.toString()));
- var.setVarargs(true);
- } else
- var.setType(createTypeNode(imports, params[i], ast));
- var.setName(ast.newSimpleName(paramNames[i]));
- parameters.add(var);
- }
- return parameters;
- }
-
- private static Type createTypeNode(ImportRewrite importRewrite, ITypeBinding binding, AST ast) {
- if (importRewrite != null)
- return importRewrite.addImport(binding, ast);
- return createTypeNode(binding, ast);
- }
-
- private static Type createTypeNode(ITypeBinding binding, AST ast) {
- if (binding.isPrimitive())
- return ast.newPrimitiveType(PrimitiveType.toCode(binding.getName()));
- ITypeBinding normalized= Bindings.normalizeTypeBinding(binding);
- if (normalized == null)
- return ast.newSimpleType(ast.newSimpleName("invalid")); //$NON-NLS-1$
- else if (normalized.isArray())
- return ast.newArrayType(createTypeNode(normalized.getElementType(), ast), normalized.getDimensions());
- String qualified= Bindings.getRawQualifiedName(normalized);
- if (qualified.length() > 0) {
- return ast.newSimpleType(ASTNodeFactory.newName(ast, qualified));
- }
- return ast.newSimpleType(ASTNodeFactory.newName(ast, Bindings.getRawName(normalized)));
- }
-
- private static IFunctionBinding findMethodBinding(IFunctionBinding method, List allMethods) {
- for (int i= 0; i < allMethods.size(); i++) {
- IFunctionBinding curr= (IFunctionBinding) allMethods.get(i);
- if (Bindings.isSubsignature(method, curr)) {
- return curr;
- }
- }
- return null;
- }
-
- private static IFunctionBinding findOverridingMethod(IFunctionBinding method, List allMethods) {
- for (int i= 0; i < allMethods.size(); i++) {
- IFunctionBinding curr= (IFunctionBinding) allMethods.get(i);
- if (Bindings.areOverriddenMethods(curr, method) || Bindings.isSubsignature(curr, method))
- return curr;
- }
- return null;
- }
-
- public static IBinding[][] getDelegatableMethods(AST ast, ITypeBinding binding) {
- final List tuples= new ArrayList();
- final List declared= new ArrayList();
- IFunctionBinding[] typeMethods= binding.getDeclaredMethods();
- for (int index= 0; index < typeMethods.length; index++)
- declared.add(typeMethods[index]);
- IVariableBinding[] typeFields= binding.getDeclaredFields();
- for (int index= 0; index < typeFields.length; index++) {
- IVariableBinding fieldBinding= typeFields[index];
- if (fieldBinding.isField())
- getDelegatableMethods(ast, tuples, new ArrayList(declared), fieldBinding, fieldBinding.getType(), binding);
- }
- // list of tuple<IVariableBinding, IFunctionBinding>
- return (IBinding[][]) tuples.toArray(new IBinding[tuples.size()][2]);
- }
-
- private static void getDelegatableMethods(AST ast, List tuples, List methods, IVariableBinding fieldBinding, ITypeBinding typeBinding, ITypeBinding binding) {
- boolean match= false;
- IFunctionBinding[] candidates= getDelegateCandidates(typeBinding, binding);
- for (int index= 0; index < candidates.length; index++) {
- match= false;
- final IFunctionBinding methodBinding= candidates[index];
- for (int offset= 0; offset < methods.size() && !match; offset++) {
- if (Bindings.areOverriddenMethods((IFunctionBinding) methods.get(offset), methodBinding))
- match= true;
- }
- if (!match) {
- tuples.add(new IBinding[] { fieldBinding, methodBinding });
- methods.add(methodBinding);
- }
- }
- final ITypeBinding superclass= typeBinding.getSuperclass();
- if (superclass != null)
- getDelegatableMethods(ast, tuples, methods, fieldBinding, superclass, binding);
- }
-
- private static IFunctionBinding[] getDelegateCandidates(ITypeBinding binding, ITypeBinding hierarchy) {
- List allMethods= new ArrayList();
- IFunctionBinding[] typeMethods= binding.getDeclaredMethods();
- for (int index= 0; index < typeMethods.length; index++) {
- final int modifiers= typeMethods[index].getModifiers();
- if (!typeMethods[index].isConstructor() && !Modifier.isStatic(modifiers) && (Modifier.isPublic(modifiers))) {
-// IFunctionBinding result= Bindings.findOverriddenMethodInHierarchy(hierarchy, typeMethods[index]);
-// ITypeBinding[] parameterBindings= typeMethods[index].getParameterTypes();
- boolean upper= false;
- if (!upper)
- allMethods.add(typeMethods[index]);
- }
- }
- return (IFunctionBinding[]) allMethods.toArray(new IFunctionBinding[allMethods.size()]);
- }
-
- private static List getImplementationModifiers(AST ast, IFunctionBinding method, boolean deferred) {
- int modifiers= method.getModifiers() & ~Modifier.ABSTRACT & ~Modifier.NATIVE & ~Modifier.PRIVATE;
- if (deferred) {
- modifiers= modifiers & ~Modifier.PROTECTED;
- modifiers= modifiers | Modifier.PUBLIC;
- }
- return ASTNodeFactory.newModifiers(ast, modifiers);
- }
-
- public static IFunctionBinding[] getOverridableMethods(AST ast, ITypeBinding typeBinding, boolean isSubType) {
- List allMethods= new ArrayList();
- IFunctionBinding[] typeMethods= typeBinding.getDeclaredMethods();
- for (int index= 0; index < typeMethods.length; index++) {
- final int modifiers= typeMethods[index].getModifiers();
- if (!typeMethods[index].isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers))
- allMethods.add(typeMethods[index]);
- }
- ITypeBinding clazz= typeBinding.getSuperclass();
- while (clazz != null) {
- IFunctionBinding[] methods= clazz.getDeclaredMethods();
- for (int offset= 0; offset < methods.length; offset++) {
- final int modifiers= methods[offset].getModifiers();
- if (!methods[offset].isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
- if (findOverridingMethod(methods[offset], allMethods) == null)
- allMethods.add(methods[offset]);
- }
- }
- clazz= clazz.getSuperclass();
- }
- clazz= typeBinding;
- while (clazz != null) {
- clazz= clazz.getSuperclass();
- }
- if (!isSubType)
- allMethods.removeAll(Arrays.asList(typeMethods));
- int modifiers= 0;
-
- for (int index= allMethods.size() - 1; index >= 0; index--) {
- IFunctionBinding method= (IFunctionBinding) allMethods.get(index);
- modifiers= method.getModifiers();
- if (Modifier.isFinal(modifiers))
- allMethods.remove(index);
- }
-
- return (IFunctionBinding[]) allMethods.toArray(new IFunctionBinding[allMethods.size()]);
- }
-
-// private static void getOverridableMethods(AST ast, ITypeBinding superBinding, List allMethods) {
-// IFunctionBinding[] methods= superBinding.getDeclaredMethods();
-// for (int offset= 0; offset < methods.length; offset++) {
-// final int modifiers= methods[offset].getModifiers();
-// if (!methods[offset].isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
-// if (findOverridingMethod(methods[offset], allMethods) == null && !Modifier.isStatic(modifiers))
-// allMethods.add(methods[offset]);
-// }
-// }
-// }
-
- private static String getParameterName(IJavaScriptUnit unit, IVariableBinding binding, String[] excluded) {
- final String name= NamingConventions.removePrefixAndSuffixForFieldName(unit.getJavaScriptProject(), binding.getName(), binding.getModifiers());
- return StubUtility.suggestArgumentName(unit.getJavaScriptProject(), name, excluded);
- }
-
- public static IFunctionBinding[] getUnimplementedMethods(ITypeBinding typeBinding) {
- ArrayList allMethods= new ArrayList();
- ArrayList toImplement= new ArrayList();
-
- IFunctionBinding[] typeMethods= typeBinding.getDeclaredMethods();
- for (int i= 0; i < typeMethods.length; i++) {
- IFunctionBinding curr= typeMethods[i];
- int modifiers= curr.getModifiers();
- if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
- allMethods.add(curr);
- }
- }
-
- ITypeBinding superClass= typeBinding.getSuperclass();
- while (superClass != null) {
- typeMethods= superClass.getDeclaredMethods();
- for (int i= 0; i < typeMethods.length; i++) {
- IFunctionBinding curr= typeMethods[i];
- int modifiers= curr.getModifiers();
- if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
- if (findMethodBinding(curr, allMethods) == null) {
- allMethods.add(curr);
- }
- }
- }
- superClass= superClass.getSuperclass();
- }
-
- for (int i= 0; i < allMethods.size(); i++) {
- IFunctionBinding curr= (IFunctionBinding) allMethods.get(i);
- int modifiers= curr.getModifiers();
- if ((Modifier.isAbstract(modifiers)) && (typeBinding != curr.getDeclaringClass())) {
- // implement all abstract methods
- toImplement.add(curr);
- }
- }
-
- ITypeBinding curr= typeBinding;
- while (curr != null) {
- curr= curr.getSuperclass();
- }
-
- return (IFunctionBinding[]) toImplement.toArray(new IFunctionBinding[toImplement.size()]);
- }
-
- public static IFunctionBinding[] getVisibleConstructors(ITypeBinding binding, boolean accountExisting, boolean proposeDefault) {
- List constructorMethods= new ArrayList();
- List existingConstructors= null;
- ITypeBinding superType= binding.getSuperclass();
- if (superType == null)
- return new IFunctionBinding[0];
- if (accountExisting) {
- IFunctionBinding[] methods= binding.getDeclaredMethods();
- existingConstructors= new ArrayList(methods.length);
- for (int index= 0; index < methods.length; index++) {
- IFunctionBinding method= methods[index];
- if (method.isConstructor() && !method.isDefaultConstructor())
- existingConstructors.add(method);
- }
- }
- if (existingConstructors != null)
- constructorMethods.addAll(existingConstructors);
- IFunctionBinding[] methods= binding.getDeclaredMethods();
- IFunctionBinding[] superMethods= superType.getDeclaredMethods();
- for (int index= 0; index < superMethods.length; index++) {
- IFunctionBinding method= superMethods[index];
- if (method.isConstructor()) {
- if (Bindings.isVisibleInHierarchy(method, binding.getPackage()) && (!accountExisting || !Bindings.containsSignatureEquivalentConstructor(methods, method)))
- constructorMethods.add(method);
- }
- }
- if (existingConstructors != null)
- constructorMethods.removeAll(existingConstructors);
- if (constructorMethods.isEmpty()) {
- superType= binding;
- while (superType.getSuperclass() != null)
- superType= superType.getSuperclass();
- IFunctionBinding method= Bindings.findMethodInType(superType, "Object", new ITypeBinding[0]); //$NON-NLS-1$
- if (method != null) {
- if ((proposeDefault || (!accountExisting || (existingConstructors == null || existingConstructors.isEmpty()))) && (!accountExisting || !Bindings.containsSignatureEquivalentConstructor(methods, method)))
- constructorMethods.add(method);
- }
- }
- return (IFunctionBinding[]) constructorMethods.toArray(new IFunctionBinding[constructorMethods.size()]);
- }
-
-
-
- /**
- * Creates a new stub utility.
- */
- private StubUtility2() {
- // Not for instantiation
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTFlattener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTFlattener.java
deleted file mode 100644
index d54e736d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTFlattener.java
+++ /dev/null
@@ -1,1407 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BlockComment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ASTFlattener extends GenericVisitor {
-
- /**
- * The string buffer into which the serialized representation of the AST is
- * written.
- */
- protected StringBuffer fBuffer;
-
- /**
- * Creates a new AST printer.
- */
- public ASTFlattener() {
- this.fBuffer= new StringBuffer();
- }
-
- /**
- * Returns the string accumulated in the visit.
- *
- * @return the serialized
- */
- public String getResult() {
- return this.fBuffer.toString();
- }
-
- /**
- * Resets this printer so that it can be used again.
- */
- public void reset() {
- this.fBuffer.setLength(0);
- }
-
- public static String asString(ASTNode node) {
- ASTFlattener flattener= new ASTFlattener();
- node.accept(flattener);
- return flattener.getResult();
- }
-
-
- protected boolean visitNode(ASTNode node) {
- Assert.isTrue(false, "No implementation to flatten node: " + node.toString()); //$NON-NLS-1$
- return false;
- }
-
- /**
- * Appends the text representation of the given modifier flags, followed by a single space.
- * Used for 3.0 modifiers and annotations.
- *
- * @param ext the list of modifier and annotation nodes
- * (element type: <code>IExtendedModifiers</code>)
- */
- private void printModifiers(List ext) {
- for (Iterator it= ext.iterator(); it.hasNext();) {
- ASTNode p= (ASTNode) it.next();
- p.accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- }
- }
-
- /**
- * Appends the text representation of the given modifier flags, followed by a single space.
- * Used for JLS2 modifiers.
- *
- * @param modifiers the modifier flags
- */
- private void printModifiers(int modifiers) {
-// if (Modifier.isPublic(modifiers)) {
-// this.fBuffer.append("public ");//$NON-NLS-1$
-// }
-// if (Modifier.isProtected(modifiers)) {
-// this.fBuffer.append("protected ");//$NON-NLS-1$
-// }
-// if (Modifier.isPrivate(modifiers)) {
-// this.fBuffer.append("private ");//$NON-NLS-1$
-// }
-// if (Modifier.isStatic(modifiers)) {
-// this.fBuffer.append("static ");//$NON-NLS-1$
-// }
-// if (Modifier.isAbstract(modifiers)) {
-// this.fBuffer.append("abstract ");//$NON-NLS-1$
-// }
-// if (Modifier.isFinal(modifiers)) {
-// this.fBuffer.append("final ");//$NON-NLS-1$
-// }
-// if (Modifier.isSynchronized(modifiers)) {
-// this.fBuffer.append("synchronized ");//$NON-NLS-1$
-// }
-// if (Modifier.isVolatile(modifiers)) {
-// this.fBuffer.append("volatile ");//$NON-NLS-1$
-// }
-// if (Modifier.isNative(modifiers)) {
-// this.fBuffer.append("native ");//$NON-NLS-1$
-// }
-// if (Modifier.isStrictfp(modifiers)) {
-// this.fBuffer.append("strictfp ");//$NON-NLS-1$
-// }
-// if (Modifier.isTransient(modifiers)) {
-// this.fBuffer.append("transient ");//$NON-NLS-1$
-// }
- }
-
- /*
- * @see ASTVisitor#visit(AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- this.fBuffer.append("{");//$NON-NLS-1$
- for (Iterator it= node.bodyDeclarations().iterator(); it.hasNext();) {
- BodyDeclaration b= (BodyDeclaration) it.next();
- b.accept(this);
- }
- this.fBuffer.append("}");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayAccess)
- */
- public boolean visit(ArrayAccess node) {
- node.getArray().accept(this);
- this.fBuffer.append("[");//$NON-NLS-1$
- node.getIndex().accept(this);
- this.fBuffer.append("]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayCreation)
- */
- public boolean visit(ArrayCreation node) {
- this.fBuffer.append("new ");//$NON-NLS-1$
- ArrayType at= node.getType();
- int dims= at.getDimensions();
- Type elementType= at.getElementType();
- elementType.accept(this);
- for (Iterator it= node.dimensions().iterator(); it.hasNext();) {
- this.fBuffer.append("[");//$NON-NLS-1$
- Expression e= (Expression) it.next();
- e.accept(this);
- this.fBuffer.append("]");//$NON-NLS-1$
- dims--;
- }
- // add empty "[]" for each extra array dimension
- for (int i= 0; i < dims; i++) {
- this.fBuffer.append("[]");//$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayInitializer)
- */
- public boolean visit(ArrayInitializer node) {
- this.fBuffer.append("[");//$NON-NLS-1$
- for (Iterator it= node.expressions().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append("]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ArrayType)
- */
- public boolean visit(ArrayType node) {
- node.getComponentType().accept(this);
- this.fBuffer.append("[]");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Assignment)
- */
- public boolean visit(Assignment node) {
- node.getLeftHandSide().accept(this);
- this.fBuffer.append(node.getOperator().toString());
- node.getRightHandSide().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Block)
- */
- public boolean visit(Block node) {
- this.fBuffer.append("{");//$NON-NLS-1$
- for (Iterator it= node.statements().iterator(); it.hasNext();) {
- Statement s= (Statement) it.next();
- s.accept(this);
- }
- this.fBuffer.append("}");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BlockComment)
-
- */
- public boolean visit(BlockComment node) {
- this.fBuffer.append("/* */");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- if (node.booleanValue() == true) {
- this.fBuffer.append("true");//$NON-NLS-1$
- } else {
- this.fBuffer.append("false");//$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(BreakStatement)
- */
- public boolean visit(BreakStatement node) {
- this.fBuffer.append("break");//$NON-NLS-1$
- if (node.getLabel() != null) {
- this.fBuffer.append(" ");//$NON-NLS-1$
- node.getLabel().accept(this);
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- public boolean visit(FunctionExpression node) {
- node.getMethod().accept(this);
- return false;
- }
-
- public boolean visit(ObjectLiteral node) {
- this.fBuffer.append("{");//$NON-NLS-1$
- for (Iterator it= node.fields().iterator(); it.hasNext();) {
- ObjectLiteralField field= (ObjectLiteralField) it.next();
- field.accept(this);
- }
- this.fBuffer.append("}");//$NON-NLS-1$
- return false;
- }
-
-
-
- public boolean visit(ObjectLiteralField node) {
- node.getFieldName().accept(this);
- this.fBuffer.append(" : ");//$NON-NLS-1$
- node.getInitializer().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(CatchClause)
- */
- public boolean visit(CatchClause node) {
- this.fBuffer.append("catch (");//$NON-NLS-1$
- node.getException().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(CharacterLiteral)
- */
- public boolean visit(CharacterLiteral node) {
- this.fBuffer.append(node.getEscapedValue());
- return false;
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- this.fBuffer.append(node.getRegularExpression());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- this.fBuffer.append("new ");//$NON-NLS-1$
-// if (node.getAST().apiLevel() == AST.JLS2) {
-// node.getName().accept(this);
-// }
-// if (node.getAST().apiLevel() >= AST.JLS3) {
-// if (!node.typeArguments().isEmpty()) {
-// this.fBuffer.append("<");//$NON-NLS-1$
-// for (Iterator it= node.typeArguments().iterator(); it.hasNext();) {
-// Type t= (Type) it.next();
-// t.accept(this);
-// if (it.hasNext()) {
-// this.fBuffer.append(",");//$NON-NLS-1$
-// }
-// }
-// this.fBuffer.append(">");//$NON-NLS-1$
-// }
-// node.getType().accept(this);
-// }
- node.getMember().accept(this);
- this.fBuffer.append("(");//$NON-NLS-1$
- for (Iterator it= node.arguments().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(")");//$NON-NLS-1$
- if (node.getAnonymousClassDeclaration() != null) {
- node.getAnonymousClassDeclaration().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(JavaScriptUnit)
- */
- public boolean visit(JavaScriptUnit node) {
- if (node.getPackage() != null) {
- node.getPackage().accept(this);
- }
- for (Iterator it= node.imports().iterator(); it.hasNext();) {
- ImportDeclaration d= (ImportDeclaration) it.next();
- d.accept(this);
- }
- for (Iterator it= node.types().iterator(); it.hasNext();) {
- AbstractTypeDeclaration d= (AbstractTypeDeclaration) it.next();
- d.accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConditionalExpression)
- */
- public boolean visit(ConditionalExpression node) {
- node.getExpression().accept(this);
- this.fBuffer.append("?");//$NON-NLS-1$
- node.getThenExpression().accept(this);
- this.fBuffer.append(":");//$NON-NLS-1$
- node.getElseExpression().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.fBuffer.append("<");//$NON-NLS-1$
- for (Iterator it= node.typeArguments().iterator(); it.hasNext();) {
- Type t= (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(">");//$NON-NLS-1$
- }
- }
- this.fBuffer.append("this(");//$NON-NLS-1$
- for (Iterator it= node.arguments().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(");");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ContinueStatement)
- */
- public boolean visit(ContinueStatement node) {
- this.fBuffer.append("continue");//$NON-NLS-1$
- if (node.getLabel() != null) {
- this.fBuffer.append(" ");//$NON-NLS-1$
- node.getLabel().accept(this);
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(DoStatement)
- */
- public boolean visit(DoStatement node) {
- this.fBuffer.append("do ");//$NON-NLS-1$
- node.getBody().accept(this);
- this.fBuffer.append(" while (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(");");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EmptyStatement)
- */
- public boolean visit(EmptyStatement node) {
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(EnhancedForStatement)
-
- */
- public boolean visit(EnhancedForStatement node) {
- this.fBuffer.append("for (");//$NON-NLS-1$
- node.getParameter().accept(this);
- this.fBuffer.append(" : ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(ExpressionStatement)
- */
- public boolean visit(ExpressionStatement node) {
- node.getExpression().accept(this);
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldAccess)
- */
- public boolean visit(FieldAccess node) {
- node.getExpression().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FieldDeclaration)
- */
- public boolean visit(FieldDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getType().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- for (Iterator it= node.fragments().iterator(); it.hasNext();) {
- VariableDeclarationFragment f= (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(", ");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ForStatement)
- */
- public boolean visit(ForStatement node) {
- this.fBuffer.append("for (");//$NON-NLS-1$
- for (Iterator it= node.initializers().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- }
- this.fBuffer.append("; ");//$NON-NLS-1$
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- }
- this.fBuffer.append("; ");//$NON-NLS-1$
- for (Iterator it= node.updaters().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- }
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- public boolean visit(ForInStatement node) {
- this.fBuffer.append("for (");//$NON-NLS-1$
- if (node.getIterationVariable() != null) {
- node.getIterationVariable().accept(this);
- }
- this.fBuffer.append(" in ");//$NON-NLS-1$
- if (node.getCollection() != null) {
- node.getCollection().accept(this);
- }
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(IfStatement)
- */
- public boolean visit(IfStatement node) {
- this.fBuffer.append("if (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getThenStatement().accept(this);
- if (node.getElseStatement() != null) {
- this.fBuffer.append(" else ");//$NON-NLS-1$
- node.getElseStatement().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- if (node.isFileImport())
- return false;
- this.fBuffer.append("import ");//$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isStatic()) {
- this.fBuffer.append("static ");//$NON-NLS-1$
- }
- }
- node.getName().accept(this);
- if (node.isOnDemand()) {
- this.fBuffer.append(".*");//$NON-NLS-1$
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(InfixExpression)
- */
- public boolean visit(InfixExpression node) {
- node.getLeftOperand().accept(this);
- this.fBuffer.append(' '); // for cases like x= i - -1; or x= i++ + ++i;
- this.fBuffer.append(node.getOperator().toString());
- this.fBuffer.append(' ');
- node.getRightOperand().accept(this);
- final List extendedOperands = node.extendedOperands();
- if (extendedOperands.size() != 0) {
- this.fBuffer.append(' ');
- for (Iterator it = extendedOperands.iterator(); it.hasNext(); ) {
- this.fBuffer.append(node.getOperator().toString()).append(' ');
- Expression e = (Expression) it.next();
- e.accept(this);
- }
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(InstanceofExpression)
- */
- public boolean visit(InstanceofExpression node) {
- node.getLeftOperand().accept(this);
- this.fBuffer.append(" instanceof ");//$NON-NLS-1$
- node.getRightOperand().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Initializer)
- */
- public boolean visit(Initializer node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getBody().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Javadoc)
- */
- public boolean visit(JSdoc node) {
- this.fBuffer.append("/** ");//$NON-NLS-1$
- for (Iterator it= node.tags().iterator(); it.hasNext();) {
- ASTNode e= (ASTNode) it.next();
- e.accept(this);
- }
- this.fBuffer.append("\n */");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(LabeledStatement)
- */
- public boolean visit(LabeledStatement node) {
- node.getLabel().accept(this);
- this.fBuffer.append(": ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- public boolean visit(ListExpression node) {
- for (Iterator it= node.expressions().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(LineComment)
-
- */
- public boolean visit(LineComment node) {
- this.fBuffer.append("//\n");//$NON-NLS-1$
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(MemberRef)
-
- */
- public boolean visit(MemberRef node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- }
- this.fBuffer.append("#");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(FunctionRef)
-
- */
- public boolean visit(FunctionRef node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- }
- this.fBuffer.append("#");//$NON-NLS-1$
- node.getName().accept(this);
- this.fBuffer.append("(");//$NON-NLS-1$
- for (Iterator it= node.parameters().iterator(); it.hasNext();) {
- FunctionRefParameter e= (FunctionRefParameter) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionRefParameter)
-
- */
- public boolean visit(FunctionRefParameter node) {
- node.getType().accept(this);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isVarargs()) {
- this.fBuffer.append("...");//$NON-NLS-1$
- }
- }
- if (node.getName() != null) {
- this.fBuffer.append(" ");//$NON-NLS-1$
- node.getName().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
-// if (!node.isConstructor()) {
-// if (node.getAST().apiLevel() == AST.JLS2) {
-// node.getReturnType().accept(this);
-// } else {
-// if (node.getReturnType2() != null) {
-// node.getReturnType2().accept(this);
-// } else {
-// // methods really ought to have a return type
-// this.fBuffer.append("void");//$NON-NLS-1$
-// }
-// }
-// this.fBuffer.append(" ");//$NON-NLS-1$
-// }
- if (node.getName()!=null)
- node.getName().accept(this);
- this.fBuffer.append("(");//$NON-NLS-1$
- for (Iterator it= node.parameters().iterator(); it.hasNext();) {
- SingleVariableDeclaration v= (SingleVariableDeclaration) it.next();
- v.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(")");//$NON-NLS-1$
- for (int i= 0; i < node.getExtraDimensions(); i++) {
- this.fBuffer.append("[]"); //$NON-NLS-1$
- }
- if (!node.thrownExceptions().isEmpty()) {
- this.fBuffer.append(" throws ");//$NON-NLS-1$
- for (Iterator it= node.thrownExceptions().iterator(); it.hasNext();) {
- Name n= (Name) it.next();
- n.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(", ");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(" ");//$NON-NLS-1$
- }
- if (node.getBody() == null) {
- this.fBuffer.append(";");//$NON-NLS-1$
- } else {
- node.getBody().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.fBuffer.append("<");//$NON-NLS-1$
- for (Iterator it= node.typeArguments().iterator(); it.hasNext();) {
- Type t= (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(">");//$NON-NLS-1$
- }
- }
- SimpleName name = node.getName();
- if (name!=null)
- name.accept(this);
- this.fBuffer.append("(");//$NON-NLS-1$
- for (Iterator it= node.arguments().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(Modifier)
-
- */
- public boolean visit(Modifier node) {
- this.fBuffer.append(node.getKeyword().toString());
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(NullLiteral)
- */
- public boolean visit(NullLiteral node) {
- this.fBuffer.append("null");//$NON-NLS-1$
- return false;
- }
-
- public boolean visit(UndefinedLiteral node) {
- this.fBuffer.append("undefined");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- this.fBuffer.append(node.getToken());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- }
- this.fBuffer.append("package ");//$NON-NLS-1$
- node.getName().accept(this);
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ParenthesizedExpression)
- */
- public boolean visit(ParenthesizedExpression node) {
- this.fBuffer.append("(");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PostfixExpression)
- */
- public boolean visit(PostfixExpression node) {
- node.getOperand().accept(this);
- this.fBuffer.append(node.getOperator().toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrefixExpression)
- */
- public boolean visit(PrefixExpression node) {
- this.fBuffer.append(node.getOperator().toString());
- node.getOperand().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(PrimitiveType)
- */
- public boolean visit(PrimitiveType node) {
- this.fBuffer.append(node.getPrimitiveTypeCode().toString());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- node.getQualifier().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(QualifiedType)
-
- */
- public boolean visit(QualifiedType node) {
- node.getQualifier().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ReturnStatement)
- */
- public boolean visit(ReturnStatement node) {
- this.fBuffer.append("return");//$NON-NLS-1$
- if (node.getExpression() != null) {
- this.fBuffer.append(" ");//$NON-NLS-1$
- node.getExpression().accept(this);
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleName)
- */
- public boolean visit(SimpleName node) {
- this.fBuffer.append(node.getIdentifier());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SimpleType)
- */
- public boolean visit(SimpleType node) {
- return true;
- }
-
- /*
- * @see ASTVisitor#visit(SingleVariableDeclaration)
- */
- public boolean visit(SingleVariableDeclaration node) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
-// node.getType().accept(this);
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.isVarargs()) {
- this.fBuffer.append("...");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(" ");//$NON-NLS-1$
- node.getName().accept(this);
- for (int i= 0; i < node.getExtraDimensions(); i++) {
- this.fBuffer.append("[]"); //$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- this.fBuffer.append("=");//$NON-NLS-1$
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(StringLiteral)
- */
- public boolean visit(StringLiteral node) {
- this.fBuffer.append(node.getEscapedValue());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- if (node.getExpression() != null) {
- node.getExpression().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.fBuffer.append("<");//$NON-NLS-1$
- for (Iterator it= node.typeArguments().iterator(); it.hasNext();) {
- Type t= (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(">");//$NON-NLS-1$
- }
- }
- this.fBuffer.append("super(");//$NON-NLS-1$
- for (Iterator it= node.arguments().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(");");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperFieldAccess)
- */
- public boolean visit(SuperFieldAccess node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- this.fBuffer.append("super.");//$NON-NLS-1$
- node.getName().accept(this);
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SuperMethodInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- this.fBuffer.append("super.");//$NON-NLS-1$
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (!node.typeArguments().isEmpty()) {
- this.fBuffer.append("<");//$NON-NLS-1$
- for (Iterator it= node.typeArguments().iterator(); it.hasNext();) {
- Type t= (Type) it.next();
- t.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(">");//$NON-NLS-1$
- }
- }
- node.getName().accept(this);
- this.fBuffer.append("(");//$NON-NLS-1$
- for (Iterator it= node.arguments().iterator(); it.hasNext();) {
- Expression e= (Expression) it.next();
- e.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(",");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(")");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchCase)
- */
- public boolean visit(SwitchCase node) {
- if (node.isDefault()) {
- this.fBuffer.append("default :");//$NON-NLS-1$
- } else {
- this.fBuffer.append("case ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(":");//$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(SwitchStatement)
- */
- public boolean visit(SwitchStatement node) {
- this.fBuffer.append("switch (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- this.fBuffer.append("{");//$NON-NLS-1$
- for (Iterator it= node.statements().iterator(); it.hasNext();) {
- Statement s= (Statement) it.next();
- s.accept(this);
- }
- this.fBuffer.append("}");//$NON-NLS-1$
- return false;
- }
-
-
- /*
- * @see ASTVisitor#visit(TagElement)
-
- */
- public boolean visit(TagElement node) {
- if (node.isNested()) {
- // nested tags are always enclosed in braces
- this.fBuffer.append("{");//$NON-NLS-1$
- } else {
- // top-level tags always begin on a new line
- this.fBuffer.append("\n * ");//$NON-NLS-1$
- }
- boolean previousRequiresWhiteSpace= false;
- if (node.getTagName() != null) {
- this.fBuffer.append(node.getTagName());
- previousRequiresWhiteSpace= true;
- }
- boolean previousRequiresNewLine= false;
- for (Iterator it= node.fragments().iterator(); it.hasNext();) {
- ASTNode e= (ASTNode) it.next();
- // assume text elements include necessary leading and trailing whitespace
- // but Name, MemberRef, FunctionRef, and nested TagElement do not include white space
- boolean currentIncludesWhiteSpace= (e instanceof TextElement);
- if (previousRequiresNewLine && currentIncludesWhiteSpace) {
- this.fBuffer.append("\n * ");//$NON-NLS-1$
- }
- previousRequiresNewLine= currentIncludesWhiteSpace;
- // add space if required to separate
- if (previousRequiresWhiteSpace && !currentIncludesWhiteSpace) {
- this.fBuffer.append(" "); //$NON-NLS-1$
- }
- e.accept(this);
- previousRequiresWhiteSpace= !currentIncludesWhiteSpace && !(e instanceof TagElement);
- }
- if (node.isNested()) {
- this.fBuffer.append("}");//$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TextElement)
-
- */
- public boolean visit(TextElement node) {
- this.fBuffer.append(node.getText());
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- if (node.getQualifier() != null) {
- node.getQualifier().accept(this);
- this.fBuffer.append(".");//$NON-NLS-1$
- }
- this.fBuffer.append("this");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(ThrowStatement)
- */
- public boolean visit(ThrowStatement node) {
- this.fBuffer.append("throw ");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TryStatement)
- */
- public boolean visit(TryStatement node) {
- this.fBuffer.append("try ");//$NON-NLS-1$
- node.getBody().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- for (Iterator it= node.catchClauses().iterator(); it.hasNext();) {
- CatchClause cc= (CatchClause) it.next();
- cc.accept(this);
- }
- if (node.getFinally() != null) {
- this.fBuffer.append("finally ");//$NON-NLS-1$
- node.getFinally().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- if (node.getJavadoc() != null) {
- node.getJavadoc().accept(this);
- }
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- this.fBuffer.append("class ");//$NON-NLS-1$
- node.getName().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- if (node.getAST().apiLevel() == AST.JLS2) {
- if (node.getSuperclass() != null) {
- this.fBuffer.append("extends ");//$NON-NLS-1$
- node.getSuperclass().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- }
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- if (node.getSuperclassType() != null) {
- this.fBuffer.append("extends ");//$NON-NLS-1$
- node.getSuperclassType().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- }
- }
- this.fBuffer.append("{");//$NON-NLS-1$
- for (Iterator it= node.bodyDeclarations().iterator(); it.hasNext();) {
- BodyDeclaration d= (BodyDeclaration) it.next();
- d.accept(this);
- }
- this.fBuffer.append("}");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- node.getTypeDeclaration().accept(this);
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- node.getDeclaration().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(TypeLiteral)
- */
- public boolean visit(TypeLiteral node) {
- node.getType().accept(this);
- this.fBuffer.append(".class");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationExpression)
- */
- public boolean visit(VariableDeclarationExpression node) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
-// node.getType().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- for (Iterator it= node.fragments().iterator(); it.hasNext();) {
- VariableDeclarationFragment f= (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(", ");//$NON-NLS-1$
- }
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationFragment)
- */
- public boolean visit(VariableDeclarationFragment node) {
- node.getName().accept(this);
- for (int i= 0; i < node.getExtraDimensions(); i++) {
- this.fBuffer.append("[]");//$NON-NLS-1$
- }
- if (node.getInitializer() != null) {
- this.fBuffer.append("=");//$NON-NLS-1$
- node.getInitializer().accept(this);
- }
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(VariableDeclarationStatement)
- */
- public boolean visit(VariableDeclarationStatement node) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- printModifiers(node.getModifiers());
- }
- if (node.getAST().apiLevel() >= AST.JLS3) {
- printModifiers(node.modifiers());
- }
- node.getType().accept(this);
- this.fBuffer.append(" ");//$NON-NLS-1$
- for (Iterator it= node.fragments().iterator(); it.hasNext();) {
- VariableDeclarationFragment f= (VariableDeclarationFragment) it.next();
- f.accept(this);
- if (it.hasNext()) {
- this.fBuffer.append(", ");//$NON-NLS-1$
- }
- }
- this.fBuffer.append(";");//$NON-NLS-1$
- return false;
- }
-
- /*
- * @see ASTVisitor#visit(WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- this.fBuffer.append("while (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
- public boolean visit(WithStatement node) {
- this.fBuffer.append("with (");//$NON-NLS-1$
- node.getExpression().accept(this);
- this.fBuffer.append(") ");//$NON-NLS-1$
- node.getBody().accept(this);
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodeFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodeFactory.java
deleted file mode 100644
index ac066abd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodeFactory.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression.Operator;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ASTNodeFactory {
-
- private static final String STATEMENT_HEADER= "class __X__ { void __x__() { "; //$NON-NLS-1$
- private static final String STATEMENT_FOOTER= "}}"; //$NON-NLS-1$
-
- private static final String TYPE_HEADER= "class __X__ { abstract "; //$NON-NLS-1$
- private static final String TYPE_FOOTER= " __f__(); }}"; //$NON-NLS-1$
-
- private static class PositionClearer extends GenericVisitor {
-
- public PositionClearer() {
- super(true);
- }
-
- protected boolean visitNode(ASTNode node) {
- node.setSourceRange(-1, 0);
- return true;
- }
- }
-
- private ASTNodeFactory() {
- // no instance;
- }
-
- public static ASTNode newStatement(AST ast, String content) {
- StringBuffer buffer= new StringBuffer(STATEMENT_HEADER);
- buffer.append(content);
- buffer.append(STATEMENT_FOOTER);
- ASTParser p= ASTParser.newParser(ast.apiLevel());
- p.setSource(buffer.toString().toCharArray());
- JavaScriptUnit root= (JavaScriptUnit) p.createAST(null);
- ASTNode result= ASTNode.copySubtree(ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
- result.accept(new PositionClearer());
- return result;
- }
-
- public static Name newName(AST ast, String qualifiedName) {
- return ast.newName(qualifiedName);
- }
-
- public static Type newType(AST ast, String content) {
- StringBuffer buffer= new StringBuffer(TYPE_HEADER);
- buffer.append(content);
- buffer.append(TYPE_FOOTER);
- ASTParser p= ASTParser.newParser(ast.apiLevel());
- p.setSource(buffer.toString().toCharArray());
- JavaScriptUnit root= (JavaScriptUnit) p.createAST(null);
- List list= root.types();
- TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
- FunctionDeclaration methodDecl= typeDecl.getMethods()[0];
- ASTNode type= methodDecl.getReturnType2();
- ASTNode result= ASTNode.copySubtree(ast, type);
- result.accept(new PositionClearer());
- return (Type)result;
- }
-
- /**
- * Returns the new type node corresponding to the type of the given declaration
- * including the extra dimensions.
- * @param ast The AST to create the resulting type with.
- * @param declaration The variable declaration to get the type from
- * @return A new type node created with the given AST.
- */
- public static Type newType(AST ast, VariableDeclaration declaration) {
- Type type= ASTNodes.getType(declaration);
- int extraDim= declaration.getExtraDimensions();
-
- type= (Type) ASTNode.copySubtree(ast, type);
- for (int i= 0; i < extraDim; i++) {
- type= ast.newArrayType(type);
- }
- return type;
- }
-
- /**
- * Returns an expression that is assignable to the given type. <code>null</code> is
- * returned if the type is the 'void' type.
- *
- * @param ast The AST to create the expression for
- * @param type The type of the returned expression
- * @param extraDimensions Extra dimensions to the type
- * @return Returns the Null-literal for reference types, a boolen-literal for a boolean type, a number
- * literal for primitive types or <code>null</code> if the type is void.
- */
- public static Expression newDefaultExpression(AST ast, Type type, int extraDimensions) {
- if (extraDimensions == 0 && type.isPrimitiveType()) {
- PrimitiveType primitiveType= (PrimitiveType) type;
- if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
- return ast.newBooleanLiteral(false);
- } else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) {
- return null;
- } else {
- return ast.newNumberLiteral("0"); //$NON-NLS-1$
- }
- }
- return ast.newNullLiteral();
- }
-
- /**
- * Returns an expression that is assignable to the given typebinding. <code>null</code> is
- * returned if the type is the 'void' type.
- *
- * @param ast The AST to create the expression for
- * @param type The type binding to which the returned expression is compatible to
- * @return Returns the Null-literal for reference types, a boolen-literal for a boolean type, a number
- * literal for primitive types or <code>null</code> if the type is void.
- */
- public static Expression newDefaultExpression(AST ast, ITypeBinding type) {
- if (type.isPrimitive()) {
- String name= type.getName();
- if ("boolean".equals(name)) { //$NON-NLS-1$
- return ast.newBooleanLiteral(false);
- } else if ("void".equals(name)) { //$NON-NLS-1$
- return null;
- } else {
- return ast.newNumberLiteral("0"); //$NON-NLS-1$
- }
- }
- return ast.newNullLiteral();
- }
-
- /**
- * Returns a list of newly created Modifier nodes corresponding to the given modfier flags.
- * @param ast The ast to create the nodes for.
- * @param modifiers The modifier flags describing the modifier nodes to create.
- * @return Returns a list of nodes of type {@link Modifier}.
- */
- public static List newModifiers(AST ast, int modifiers) {
- return ast.newModifiers(modifiers);
- }
-
- /**
- * Returns a list of newly created Modifier nodes corresponding to a given list of existing modifiers.
- * @param ast The ast to create the nodes for.
- * @param modifierNodes The modifier nodes describing the modifier nodes to create. Only
- * nodes of type {@link Modifier} are looked at and cloned. To create a full copy of the list consider
- * to use {@link ASTNode#copySubtrees(AST, List)}.
- * @return Returns a list of nodes of type {@link Modifier}.
- */
- public static List newModifiers(AST ast, List modifierNodes) {
- List res= new ArrayList(modifierNodes.size());
- for (int i= 0; i < modifierNodes.size(); i++) {
- Object curr= modifierNodes.get(i);
- if (curr instanceof Modifier) {
- res.add(ast.newModifier(((Modifier) curr).getKeyword()));
- }
- }
- return res;
- }
-
- public static Expression newInfixExpression(AST ast, Operator operator, ArrayList/*<Expression>*/ operands) {
- if (operands.size() == 1)
- return (Expression) operands.get(0);
-
- InfixExpression result= ast.newInfixExpression();
- result.setOperator(operator);
- result.setLeftOperand((Expression) operands.get(0));
- result.setRightOperand((Expression) operands.get(1));
- result.extendedOperands().addAll(operands.subList(2, operands.size()));
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodes.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodes.java
deleted file mode 100644
index 95c34386..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ASTNodes.java
+++ /dev/null
@@ -1,805 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug Encapsulate field can fail when two variables in one variable declaration (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=51540).
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Message;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ASTNodes {
-
- public static final int NODE_ONLY= 0;
- public static final int INCLUDE_FIRST_PARENT= 1;
- public static final int INCLUDE_ALL_PARENTS= 2;
-
- public static final int WARNING= 1 << 0;
- public static final int ERROR= 1 << 1;
- public static final int PROBLEMS= WARNING | ERROR;
-
- private static final Message[] EMPTY_MESSAGES= new Message[0];
- private static final IProblem[] EMPTY_PROBLEMS= new IProblem[0];
-
- private static final int CLEAR_VISIBILITY= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE);
-
-
- private ASTNodes() {
- // no instance;
- }
-
- public static String asString(ASTNode node) {
- ASTFlattener flattener= new ASTFlattener();
- node.accept(flattener);
- return flattener.getResult();
- }
-
- public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map options) {
- String unformatted= asString(node);
- TextEdit edit= CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
- if (edit != null) {
- return CodeFormatterUtil.evaluateFormatterEdit(unformatted, edit, null);
- }
- return unformatted; // unknown node
- }
-
- /**
- * Returns the list that contains the given ASTNode. If the node
- * isn't part of any list, <code>null</code> is returned.
- *
- * @param node the node in question
- * @return the list that contains the node or <code>null</code>
- */
- public static List getContainingList(ASTNode node) {
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent != null && locationInParent.isChildListProperty()) {
- return (List) node.getParent().getStructuralProperty(locationInParent);
- }
- return null;
- }
-
- /**
- * Returns a list of the direct children of a node. The siblings are ordered by start offset.
- * @param node the node to get the children for
- * @return the children
- */
- public static List getChildren(ASTNode node) {
- ChildrenCollector visitor= new ChildrenCollector();
- node.accept(visitor);
- return visitor.result;
- }
-
- private static class ChildrenCollector extends GenericVisitor {
- public List result;
-
- public ChildrenCollector() {
- super(true);
- result= null;
- }
- protected boolean visitNode(ASTNode node) {
- if (result == null) { // first visitNode: on the node's parent: do nothing, return true
- result= new ArrayList();
- return true;
- }
- result.add(node);
- return false;
- }
- }
-
- /**
- * Returns true if this is an existing node, i.e. it was created as part of
- * a parsing process of a source code file. Returns false if this is a newly
- * created node which has not yet been given a source position.
- *
- * @param node the node to be tested.
- * @return true if this is an existing node, false if not.
- */
- public static boolean isExistingNode(ASTNode node) {
- return node.getStartPosition() != -1;
- }
-
- /**
- * Returns the element type. This is a convenience method that returns its
- * argument if it is a simple type and the element type if the parameter is an array type.
- * @param type The type to get the element type from.
- * @return The element type of the type or the type itself.
- */
- public static Type getElementType(Type type) {
- if (! type.isArrayType())
- return type;
- return ((ArrayType)type).getElementType();
- }
-
- public static ASTNode findDeclaration(IBinding binding, ASTNode root) {
- root= root.getRoot();
- if (root instanceof JavaScriptUnit) {
- return ((JavaScriptUnit)root).findDeclaringNode(binding);
- }
- return null;
- }
-
- public static VariableDeclaration findVariableDeclaration(IVariableBinding binding, ASTNode root) {
- if (binding.isField())
- return null;
- ASTNode result= findDeclaration(binding, root);
- if (result instanceof VariableDeclaration)
- return (VariableDeclaration)result;
-
- return null;
- }
-
- /**
- * Returns the type node for the given declaration.
- * @param declaration the declaration
- * @return the type node
- */
- public static Type getType(VariableDeclaration declaration) {
- if (declaration instanceof SingleVariableDeclaration) {
- return ((SingleVariableDeclaration)declaration).getType();
- } else if (declaration instanceof VariableDeclarationFragment) {
- ASTNode parent= ((VariableDeclarationFragment)declaration).getParent();
- if (parent instanceof VariableDeclarationExpression)
- return ((VariableDeclarationExpression)parent).getType();
- else if (parent instanceof VariableDeclarationStatement)
- return ((VariableDeclarationStatement)parent).getType();
- else if (parent instanceof FieldDeclaration)
- return ((FieldDeclaration)parent).getType();
- }
- Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$
- return null;
- }
-
- public static int getDimensions(VariableDeclaration declaration) {
- int dim= declaration.getExtraDimensions();
- Type type= getType(declaration);
- if (type instanceof ArrayType) {
- dim += ((ArrayType) type).getDimensions();
- }
- return dim;
- }
-
- public static List getModifiers(VariableDeclaration declaration) {
- Assert.isNotNull(declaration);
- if (declaration instanceof SingleVariableDeclaration) {
- return ((SingleVariableDeclaration)declaration).modifiers();
- } else if (declaration instanceof VariableDeclarationFragment) {
- ASTNode parent= declaration.getParent();
- if (parent instanceof VariableDeclarationExpression)
- return ((VariableDeclarationExpression)parent).modifiers();
- else if (parent instanceof VariableDeclarationStatement)
- return ((VariableDeclarationStatement)parent).modifiers();
- }
- return new ArrayList(0);
- }
-
- public static boolean isSingleDeclaration(VariableDeclaration declaration) {
- Assert.isNotNull(declaration);
- if (declaration instanceof SingleVariableDeclaration) {
- return true;
- } else if (declaration instanceof VariableDeclarationFragment) {
- ASTNode parent= declaration.getParent();
- if (parent instanceof VariableDeclarationExpression)
- return ((VariableDeclarationExpression)parent).fragments().size() == 1;
- else if (parent instanceof VariableDeclarationStatement)
- return ((VariableDeclarationStatement)parent).fragments().size() == 1;
- }
- return false;
- }
-
- public static boolean isLiteral(Expression expression) {
- int type= expression.getNodeType();
- return type == ASTNode.BOOLEAN_LITERAL || type == ASTNode.CHARACTER_LITERAL || type == ASTNode.NULL_LITERAL ||
- type == ASTNode.NUMBER_LITERAL || type == ASTNode.STRING_LITERAL || type == ASTNode.TYPE_LITERAL||
- type == ASTNode.UNDEFINED_LITERAL || type == ASTNode.OBJECT_LITERAL || type == ASTNode.REGULAR_EXPRESSION_LITERAL;
-
- }
-
- public static boolean isLabel(SimpleName name) {
- int parentType= name.getParent().getNodeType();
- return parentType == ASTNode.LABELED_STATEMENT ||
- parentType == ASTNode.BREAK_STATEMENT || parentType != ASTNode.CONTINUE_STATEMENT;
- }
-
- public static boolean isStatic(BodyDeclaration declaration) {
- return Modifier.isStatic(declaration.getModifiers());
- }
-
- public static List getBodyDeclarations(ASTNode node) {
- if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration)node).bodyDeclarations();
- } else if (node instanceof AnonymousClassDeclaration) {
- return ((AnonymousClassDeclaration)node).bodyDeclarations();
- }
- // should not happen.
- Assert.isTrue(false);
- return null;
- }
-
- public static ChildListPropertyDescriptor getBodyDeclarationsProperty(ASTNode node) {
- if (node instanceof JavaScriptUnit) {
- return JavaScriptUnit.STATEMENTS_PROPERTY;
- } else if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration)node).getBodyDeclarationsProperty();
- } else if (node instanceof AnonymousClassDeclaration) {
- return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
- }
-
- // should not happen.
- Assert.isTrue(false);
- return null;
- }
-
- public static String getTypeName(Type type) {
- final StringBuffer buffer= new StringBuffer();
- ASTVisitor visitor= new ASTVisitor() {
- public boolean visit(PrimitiveType node) {
- buffer.append(node.getPrimitiveTypeCode().toString());
- return false;
- }
- public boolean visit(SimpleName node) {
- buffer.append(node.getIdentifier());
- return false;
- }
- public boolean visit(QualifiedName node) {
- buffer.append(node.getName().getIdentifier());
- return false;
- }
- public void endVisit(ArrayType node) {
- buffer.append("[]"); //$NON-NLS-1$
- }
- };
- type.accept(visitor);
- return buffer.toString();
- }
-
- public static InfixExpression.Operator convertToInfixOperator(Assignment.Operator operator) {
- if (operator.equals(Assignment.Operator.PLUS_ASSIGN))
- return InfixExpression.Operator.PLUS;
-
- if (operator.equals(Assignment.Operator.MINUS_ASSIGN))
- return InfixExpression.Operator.MINUS;
-
- if (operator.equals(Assignment.Operator.TIMES_ASSIGN))
- return InfixExpression.Operator.TIMES;
-
- if (operator.equals(Assignment.Operator.DIVIDE_ASSIGN))
- return InfixExpression.Operator.DIVIDE;
-
- if (operator.equals(Assignment.Operator.BIT_AND_ASSIGN))
- return InfixExpression.Operator.AND;
-
- if (operator.equals(Assignment.Operator.BIT_OR_ASSIGN))
- return InfixExpression.Operator.OR;
-
- if (operator.equals(Assignment.Operator.BIT_XOR_ASSIGN))
- return InfixExpression.Operator.XOR;
-
- if (operator.equals(Assignment.Operator.REMAINDER_ASSIGN))
- return InfixExpression.Operator.REMAINDER;
-
- if (operator.equals(Assignment.Operator.LEFT_SHIFT_ASSIGN))
- return InfixExpression.Operator.LEFT_SHIFT;
-
- if (operator.equals(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN))
- return InfixExpression.Operator.RIGHT_SHIFT_SIGNED;
-
- if (operator.equals(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN))
- return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED;
-
- Assert.isTrue(false, "Cannot convert assignment operator"); //$NON-NLS-1$
- return null;
- }
-
- /**
- * Returns true if a node at a given location is a body of a control statement. Such body nodes are
- * interesting as when replacing them, it has to be evaluates if a Block is needed instead.
- * E.g. <code> if (x) do(); -> if (x) { do1(); do2() } </code>
- *
- * @param locationInParent Location of the body node
- * @return Returns true if the location is a body node location of a control statement.
- */
- public static boolean isControlStatementBody(StructuralPropertyDescriptor locationInParent) {
- return locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
- || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
- || locationInParent == ForStatement.BODY_PROPERTY
- || locationInParent == ForInStatement.BODY_PROPERTY
- || locationInParent == EnhancedForStatement.BODY_PROPERTY
- || locationInParent == WhileStatement.BODY_PROPERTY
- || locationInParent == DoStatement.BODY_PROPERTY;
- }
-
- public static boolean needsParentheses(Expression expression) {
- int type= expression.getNodeType();
- return type == ASTNode.INFIX_EXPRESSION || type == ASTNode.CONDITIONAL_EXPRESSION ||
- type == ASTNode.PREFIX_EXPRESSION || type == ASTNode.POSTFIX_EXPRESSION ||
- type == ASTNode.INSTANCEOF_EXPRESSION;
- }
-
-
- public static boolean substituteMustBeParenthesized(Expression substitute, Expression location) {
- if (!needsParentheses(substitute))
- return false;
-
- ASTNode parent= location.getParent();
- if (parent instanceof VariableDeclarationFragment){
- VariableDeclarationFragment vdf= (VariableDeclarationFragment)parent;
- if (vdf.getInitializer().equals(location))
- return false;
- } else if (parent instanceof FunctionInvocation){
- FunctionInvocation mi= (FunctionInvocation)parent;
- if (mi.arguments().contains(location))
- return false;
- } else if (parent instanceof ReturnStatement)
- return false;
-
- return true;
- }
-
- public static ASTNode getParent(ASTNode node, Class parentClass) {
- do {
- node= node.getParent();
- } while (node != null && !parentClass.isInstance(node));
- return node;
- }
-
- public static ASTNode getParent(ASTNode node, int nodeType) {
- do {
- node= node.getParent();
- } while (node != null && node.getNodeType() != nodeType);
- return node;
- }
-
- public static ASTNode findParent(ASTNode node, StructuralPropertyDescriptor[][] pathes) {
- for (int p= 0; p < pathes.length; p++) {
- StructuralPropertyDescriptor[] path= pathes[p];
- ASTNode current= node;
- int d= path.length - 1;
- for (; d >= 0 && current != null; d--) {
- StructuralPropertyDescriptor descriptor= path[d];
- if (!descriptor.equals(current.getLocationInParent()))
- break;
- current= current.getParent();
- }
- if (d < 0)
- return current;
- }
- return null;
- }
-
- public static ASTNode getNormalizedNode(ASTNode node) {
- ASTNode current= node;
- // normalize name
- if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) {
- current= current.getParent();
- }
- // normalize type
- if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) ||
- SimpleType.NAME_PROPERTY.equals(current.getLocationInParent())) {
- current= current.getParent();
- }
- return current;
- }
-
- public static boolean isParent(ASTNode node, ASTNode parent) {
- Assert.isNotNull(parent);
- do {
- node= node.getParent();
- if (node == parent)
- return true;
- } while (node != null);
- return false;
- }
-
- public static int getExclusiveEnd(ASTNode node){
- return node.getStartPosition() + node.getLength();
- }
-
- public static int getInclusiveEnd(ASTNode node){
- return node.getStartPosition() + node.getLength() - 1;
- }
-
- public static IFunctionBinding getMethodBinding(Name node) {
- IBinding binding= node.resolveBinding();
- if (binding instanceof IFunctionBinding)
- return (IFunctionBinding)binding;
- return null;
- }
-
- public static IVariableBinding getVariableBinding(Name node) {
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding)
- return (IVariableBinding)binding;
- return null;
- }
-
- public static IVariableBinding getLocalVariableBinding(Name node) {
- IVariableBinding result= getVariableBinding(node);
- if (result == null || result.isField())
- return null;
-
- return result;
- }
-
- public static IVariableBinding getFieldBinding(Name node) {
- IVariableBinding result= getVariableBinding(node);
- if (result == null || !result.isField())
- return null;
-
- return result;
- }
-
- public static ITypeBinding getTypeBinding(Name node) {
- IBinding binding= node.resolveBinding();
- if (binding instanceof ITypeBinding)
- return (ITypeBinding)binding;
- return null;
- }
-
- /**
- * Returns the receiver's type binding of the given method invocation.
- *
- * @param invocation method invocation to resolve type of
- * @return the type binding of the receiver
- */
- public static ITypeBinding getReceiverTypeBinding(FunctionInvocation invocation) {
- ITypeBinding result= null;
- Expression exp= invocation.getExpression();
- if(exp != null) {
- return exp.resolveTypeBinding();
- }
- else {
- AbstractTypeDeclaration type= (AbstractTypeDeclaration)getParent(invocation, AbstractTypeDeclaration.class);
- if (type != null)
- return type.resolveBinding();
- }
- return result;
- }
-
- public static ITypeBinding getEnclosingType(ASTNode node) {
- while(node != null) {
- if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration)node).resolveBinding();
- } else if (node instanceof AnonymousClassDeclaration) {
- return ((AnonymousClassDeclaration)node).resolveBinding();
- } else if (node instanceof JavaScriptUnit) {
- return ((JavaScriptUnit)node).resolveBinding();
- }
- node= node.getParent();
- }
- return null;
- }
-
- public static IProblem[] getProblems(ASTNode node, int scope, int severity) {
- ASTNode root= node.getRoot();
- if (!(root instanceof JavaScriptUnit))
- return EMPTY_PROBLEMS;
- IProblem[] problems= ((JavaScriptUnit)root).getProblems();
- if (root == node)
- return problems;
- final int iterations= computeIterations(scope);
- List result= new ArrayList(5);
- for (int i= 0; i < problems.length; i++) {
- IProblem problem= problems[i];
- boolean consider= false;
- if ((severity & PROBLEMS) == PROBLEMS)
- consider= true;
- else if ((severity & WARNING) != 0)
- consider= problem.isWarning();
- else if ((severity & ERROR) != 0)
- consider= problem.isError();
- if (consider) {
- ASTNode temp= node;
- int count= iterations;
- do {
- int nodeOffset= temp.getStartPosition();
- int problemOffset= problem.getSourceStart();
- if (nodeOffset <= problemOffset && problemOffset < nodeOffset + temp.getLength()) {
- result.add(problem);
- count= 0;
- } else {
- count--;
- }
- } while ((temp= temp.getParent()) != null && count > 0);
- }
- }
- return (IProblem[]) result.toArray(new IProblem[result.size()]);
- }
-
- public static Message[] getMessages(ASTNode node, int flags) {
- ASTNode root= node.getRoot();
- if (!(root instanceof JavaScriptUnit))
- return EMPTY_MESSAGES;
- Message[] messages= ((JavaScriptUnit)root).getMessages();
- if (root == node)
- return messages;
- final int iterations= computeIterations(flags);
- List result= new ArrayList(5);
- for (int i= 0; i < messages.length; i++) {
- Message message= messages[i];
- ASTNode temp= node;
- int count= iterations;
- do {
- int nodeOffset= temp.getStartPosition();
- int messageOffset= message.getStartPosition();
- if (nodeOffset <= messageOffset && messageOffset < nodeOffset + temp.getLength()) {
- result.add(message);
- count= 0;
- } else {
- count--;
- }
- } while ((temp= temp.getParent()) != null && count > 0);
- }
- return (Message[]) result.toArray(new Message[result.size()]);
- }
-
- private static int computeIterations(int flags) {
- switch (flags) {
- case NODE_ONLY:
- return 1;
- case INCLUDE_ALL_PARENTS:
- return Integer.MAX_VALUE;
- case INCLUDE_FIRST_PARENT:
- return 2;
- default:
- return 1;
- }
- }
-
-
- private static int getOrderPreference(BodyDeclaration member, MembersOrderPreferenceCache store) {
- int memberType= member.getNodeType();
- int modifiers= member.getModifiers();
-
- switch (memberType) {
- case ASTNode.TYPE_DECLARATION:
- return store.getCategoryIndex(MembersOrderPreferenceCache.TYPE_INDEX) * 2;
- case ASTNode.FIELD_DECLARATION:
- if (Modifier.isStatic(modifiers)) {
- int index= store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX) * 2;
- if (Modifier.isFinal(modifiers)) {
- return index; // first final static, then static
- }
- return index + 1;
- }
- return store.getCategoryIndex(MembersOrderPreferenceCache.FIELDS_INDEX) * 2;
- case ASTNode.INITIALIZER:
- if (Modifier.isStatic(modifiers)) {
- return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX) * 2;
- }
- return store.getCategoryIndex(MembersOrderPreferenceCache.INIT_INDEX) * 2;
- case ASTNode.FUNCTION_DECLARATION:
- if (Modifier.isStatic(modifiers)) {
- return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_METHODS_INDEX) * 2;
- }
- if (((FunctionDeclaration) member).isConstructor()) {
- return store.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX) * 2;
- }
- return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2;
- default:
- return 100;
- }
- }
-
- /**
- * Computes the insertion index to be used to add the given member to the
- * the list <code>container</code>.
- * @param member the member to add
- * @param container a list containing objects of type <code>BodyDeclaration</code>
- * @return the insertion index to be used
- */
- public static int getInsertionIndex(BodyDeclaration member, List container) {
- int containerSize= container.size();
-
- MembersOrderPreferenceCache orderStore= JavaScriptPlugin.getDefault().getMemberOrderPreferenceCache();
-
- int orderIndex= getOrderPreference(member, orderStore);
-
- int insertPos= containerSize;
- int insertPosOrderIndex= -1;
-
- for (int i= containerSize - 1; i >= 0; i--) {
- int currOrderIndex= getOrderPreference((BodyDeclaration) container.get(i), orderStore);
- if (orderIndex == currOrderIndex) {
- if (insertPosOrderIndex != orderIndex) { // no perfect match yet
- insertPos= i + 1; // after a same kind
- insertPosOrderIndex= orderIndex; // perfect match
- }
- } else if (insertPosOrderIndex != orderIndex) { // not yet a perfect match
- if (currOrderIndex < orderIndex) { // we are bigger
- if (insertPosOrderIndex == -1) {
- insertPos= i + 1; // after
- insertPosOrderIndex= currOrderIndex;
- }
- } else {
- insertPos= i; // before
- insertPosOrderIndex= currOrderIndex;
- }
- }
- }
- return insertPos;
- }
-
- public static SimpleName getLeftMostSimpleName(Name name) {
- if (name instanceof SimpleName) {
- return (SimpleName)name;
- } else {
- final SimpleName[] result= new SimpleName[1];
- ASTVisitor visitor= new ASTVisitor() {
- public boolean visit(QualifiedName qualifiedName) {
- Name left= qualifiedName.getQualifier();
- if (left instanceof SimpleName)
- result[0]= (SimpleName)left;
- else
- left.accept(this);
- return false;
- }
- };
- name.accept(visitor);
- return result[0];
- }
- }
-
- public static SimpleType getLeftMostSimpleType(QualifiedType type) {
- final SimpleType[] result= new SimpleType[1];
- ASTVisitor visitor= new ASTVisitor() {
- public boolean visit(QualifiedType qualifiedType) {
- Type left= qualifiedType.getQualifier();
- if (left instanceof SimpleType)
- result[0]= (SimpleType)left;
- else
- left.accept(this);
- return false;
- }
- };
- type.accept(visitor);
- return result[0];
- }
-
- public static Name getTopMostName(Name name) {
- Name result= name;
- while(result.getParent() instanceof Name) {
- result= (Name)result.getParent();
- }
- return result;
- }
-
- public static Type getTopMostType(Type type) {
- Type result= type;
- while(result.getParent() instanceof Type) {
- result= (Type)result.getParent();
- }
- return result;
- }
-
- public static int changeVisibility(int modifiers, int visibility) {
- return (modifiers & CLEAR_VISIBILITY) | visibility;
- }
-
- /**
- * Adds flags to the given node and all its descendants.
- * @param root The root node
- * @param flags The flags to set
- */
- public static void setFlagsToAST(ASTNode root, final int flags) {
- root.accept(new GenericVisitor(true) {
- protected boolean visitNode(ASTNode node) {
- node.setFlags(node.getFlags() | flags);
- return true;
- }
- });
- }
-
- public static String getQualifier(Name name) {
- if (name.isQualifiedName()) {
- return ((QualifiedName) name).getQualifier().getFullyQualifiedName();
- }
- return ""; //$NON-NLS-1$
- }
-
- public static String getSimpleNameIdentifier(Name name) {
- if (name.isQualifiedName()) {
- return ((QualifiedName) name).getName().getIdentifier();
- } else {
- return ((SimpleName) name).getIdentifier();
- }
- }
-
- public static boolean isDeclaration(Name name) {
- if (name.isQualifiedName()) {
- return ((QualifiedName) name).getName().isDeclaration();
- } else {
- return ((SimpleName) name).isDeclaration();
- }
- }
-
- public static Modifier findModifierNode(int flag, List modifiers) {
- for (int i= 0; i < modifiers.size(); i++) {
- Object curr= modifiers.get(i);
- if (curr instanceof Modifier && ((Modifier) curr).getKeyword().toFlagValue() == flag) {
- return (Modifier) curr;
- }
- }
- return null;
- }
-
- public static ITypeBinding getTypeBinding(JavaScriptUnit root, IType type) throws JavaScriptModelException {
- if (type.isAnonymous()) {
- final ClassInstanceCreation creation= (ClassInstanceCreation) getParent(NodeFinder.perform(root, type.getNameRange()), ClassInstanceCreation.class);
- if (creation != null)
- return creation.resolveTypeBinding();
- } else {
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getParent(NodeFinder.perform(root, type.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null)
- return declaration.resolveBinding();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Bindings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Bindings.java
deleted file mode 100644
index d512e8b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Bindings.java
+++ /dev/null
@@ -1,1014 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IPackageBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class Bindings {
-
- public static final String ARRAY_LENGTH_FIELD_BINDING_STRING= "(array type):length";//$NON-NLS-1$
- private Bindings() {
- // No instance
- }
-
- /**
- * Checks if the two bindings are equals. First an identity check is
- * made an then the key of the bindings are compared.
- * @param b1 first binding treated as <code>this</code>. So it must
- * not be <code>null</code>
- * @param b2 the second binding.
- * @return boolean
- */
- public static boolean equals(IBinding b1, IBinding b2) {
- return b1.isEqualTo(b2);
- }
-
- /**
- * Checks if the two arrays of bindings have the same length and
- * their elements are equal. Uses
- * <code>Bindings.equals(IBinding, IBinding)</code> to compare.
- * @param b1 the first array of bindings. Must not be <code>null</code>.
- * @param b2 the second array of bindings.
- * @return boolean
- */
- public static boolean equals(IBinding[] b1, IBinding[] b2) {
- Assert.isNotNull(b1);
- if (b1 == b2)
- return true;
- if (b2 == null)
- return false;
- if (b1.length != b2.length)
- return false;
- for (int i= 0; i < b1.length; i++) {
- if (! Bindings.equals(b1[i], b2[i]))
- return false;
- }
- return true;
- }
-
- public static int hashCode(IBinding binding){
- Assert.isNotNull(binding);
- String key= binding.getKey();
- if (key == null)
- return binding.hashCode();
- return key.hashCode();
- }
-
- /**
- * Note: this method is for debugging and testing purposes only.
- * There are tests whose pre-computed test results rely on the returned String's format.
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider
- */
- public static String asString(IBinding binding) {
- if (binding instanceof IFunctionBinding)
- return asString((IFunctionBinding)binding);
- else if (binding instanceof ITypeBinding)
- return ((ITypeBinding)binding).getQualifiedName();
- else if (binding instanceof IVariableBinding)
- return asString((IVariableBinding)binding);
- return binding.toString();
- }
-
- private static String asString(IVariableBinding variableBinding) {
- if (! variableBinding.isField())
- return variableBinding.toString();
- if (variableBinding.getDeclaringClass() == null) {
- Assert.isTrue(variableBinding.getName().equals("length"));//$NON-NLS-1$
- return ARRAY_LENGTH_FIELD_BINDING_STRING;
- }
- StringBuffer result= new StringBuffer();
- result.append(variableBinding.getDeclaringClass().getName());
- result.append(':');
- result.append(variableBinding.getName());
- return result.toString();
- }
-
- private static String asString(IFunctionBinding method) {
- StringBuffer result= new StringBuffer();
- result.append(method.getDeclaringClass().getName());
- result.append(':');
- result.append(method.getName());
- result.append('(');
- ITypeBinding[] parameters= method.getParameterTypes();
- int lastComma= parameters.length - 1;
- for (int i= 0; i < parameters.length; i++) {
- ITypeBinding parameter= parameters[i];
- result.append(parameter.getName());
- if (i < lastComma)
- result.append(", "); //$NON-NLS-1$
- }
- result.append(')');
- return result.toString();
- }
-
- public static String getTypeQualifiedName(ITypeBinding type) {
- List result= new ArrayList(5);
- createName(type, false, result);
-
- StringBuffer buffer= new StringBuffer();
- for (int i= 0; i < result.size(); i++) {
- if (i > 0) {
- buffer.append('.');
- }
- buffer.append(((String) result.get(i)));
- }
- return buffer.toString();
- }
-
- /**
- * Returns the fully qualified name of the specified type binding.
- * <p>
- * If the binding resolves to a generic type, the fully qualified name of the raw type is returned.
- *
- * @param type the type binding to get its fully qualified name
- * @return the fully qualified name
- */
- public static String getFullyQualifiedName(ITypeBinding type) {
- String name= type.getQualifiedName();
- final int index= name.indexOf('<');
- if (index > 0)
- name= name.substring(0, index);
- return name;
- }
-
- public static String getImportName(IBinding binding) {
- ITypeBinding declaring= null;
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return getRawQualifiedName((ITypeBinding) binding);
- case IBinding.PACKAGE:
- return binding.getName() + ".*"; //$NON-NLS-1$
- case IBinding.METHOD:
- declaring= ((IFunctionBinding) binding).getDeclaringClass();
- break;
- case IBinding.VARIABLE:
- declaring= ((IVariableBinding) binding).getDeclaringClass();
- if (declaring == null) {
- return binding.getName(); // array.length
- }
-
- break;
- default:
- return binding.getName();
- }
- return JavaModelUtil.concatenateName(getRawQualifiedName(declaring), binding.getName());
- }
-
-
- private static void createName(ITypeBinding type, boolean includePackage, List list) {
- ITypeBinding baseType= type;
- if (type.isArray()) {
- baseType= type.getElementType();
- }
- if (!baseType.isPrimitive() && !baseType.isNullType()) {
- ITypeBinding declaringType= baseType.getDeclaringClass();
- if (declaringType != null) {
- createName(declaringType, includePackage, list);
- } else if (includePackage && !baseType.getPackage().isUnnamed()) {
- String[] components= baseType.getPackage().getNameComponents();
- for (int i= 0; i < components.length; i++) {
- list.add(components[i]);
- }
- }
- }
- if (!baseType.isAnonymous()) {
- list.add(type.getName());
- } else {
- list.add("$local$"); //$NON-NLS-1$
- }
- }
-
-
- public static String[] getNameComponents(ITypeBinding type) {
- List result= new ArrayList(5);
- createName(type, false, result);
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- public static String[] getAllNameComponents(ITypeBinding type) {
- List result= new ArrayList(5);
- createName(type, true, result);
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- public static ITypeBinding getTopLevelType(ITypeBinding type) {
- ITypeBinding parent= type.getDeclaringClass();
- while (parent != null) {
- type= parent;
- parent= type.getDeclaringClass();
- }
- return type;
- }
-
- /**
- * Checks whether the passed type binding is a runtime exception.
- *
- * @param thrownException the type binding
- *
- * @return <code>true</code> if the passed type binding is a runtime exception;
- * otherwise <code>false</code> is returned
- */
- public static boolean isRuntimeException(ITypeBinding thrownException) {
- if (thrownException == null || thrownException.isPrimitive() || thrownException.isArray())
- return false;
- return findTypeInHierarchy(thrownException, "java.lang.RuntimeException") != null; //$NON-NLS-1$
- }
-
- /**
- * Finds the field specified by <code>fieldName<code> in
- * the given <code>type</code>. Returns <code>null</code> if no such field exits.
- * @param type the type to search the field in
- * @param fieldName the field name
- * @return the binding representing the field or <code>null</code>
- */
- public static IVariableBinding findFieldInType(ITypeBinding type, String fieldName) {
- if (type.isPrimitive())
- return null;
- IVariableBinding[] fields= type.getDeclaredFields();
- for (int i= 0; i < fields.length; i++) {
- IVariableBinding field= fields[i];
- if (field.getName().equals(fieldName))
- return field;
- }
- return null;
- }
-
- /**
- * Finds the field specified by <code>fieldName</code> in
- * the type hierarchy denoted by the given type. Returns <code>null</code> if no such field
- * exists. If the field is defined in more than one super type only the first match is
- * returned. First the super class is examined and than the implemented interfaces.
- * @param type The type to search the field in
- * @param fieldName The name of the field to find
- * @return the variable binding representing the field
- */
- public static IVariableBinding findFieldInHierarchy(ITypeBinding type, String fieldName) {
- IVariableBinding field= findFieldInType(type, fieldName);
- if (field != null)
- return field;
- ITypeBinding superClass= type.getSuperclass();
- if (superClass != null) {
- field= findFieldInHierarchy(superClass, fieldName);
- if (field != null)
- return field;
- }
- return null;
- }
-
- /**
- * Finds the method specified by <code>methodName<code> and </code>parameters</code> in
- * the given <code>type</code>. Returns <code>null</code> if no such method exits.
- * @param type The type to search the method in
- * @param methodName The name of the method to find
- * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only
- * the name is matched and parameters are ignored.
- * @return the method binding representing the method
- */
- public static IFunctionBinding findMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
- if (type.isPrimitive())
- return null;
- IFunctionBinding[] methods= type.getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- if (parameters == null) {
- if (methodName.equals(methods[i].getName()))
- return methods[i];
- } else {
- if (isEqualMethod(methods[i], methodName, parameters))
- return methods[i];
- }
- }
- return null;
- }
-
- /**
- * Finds the method specified by <code>methodName</code> and </code>parameters</code> in
- * the type hierarchy denoted by the given type. Returns <code>null</code> if no such method
- * exists. If the method is defined in more than one super type only the first match is
- * returned. First the super class is examined and than the implemented interfaces.
- * @param type The type to search the method in
- * @param methodName The name of the method to find
- * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored.
- * @return the method binding representing the method
- */
- public static IFunctionBinding findMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
- if (type==null)
- return null;
- IFunctionBinding method= findMethodInType(type, methodName, parameters);
- if (method != null)
- return method;
- ITypeBinding superClass= type.getSuperclass();
- if (superClass != null) {
- method= findMethodInHierarchy(superClass, methodName, parameters);
- if (method != null)
- return method;
- }
- return null;
- }
-
- /**
- * Finds the method specified by <code>methodName<code> and </code>parameters</code> in
- * the given <code>type</code>. Returns <code>null</code> if no such method exits.
- * @param type The type to search the method in
- * @param methodName The name of the method to find
- * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored.
- * @return the method binding representing the method
- */
- public static IFunctionBinding findMethodInType(ITypeBinding type, String methodName, String[] parameters) {
- if (type.isPrimitive())
- return null;
- IFunctionBinding[] methods= type.getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- if (parameters == null) {
- if (methodName.equals(methods[i].getName()))
- return methods[i];
- } else {
- if (isEqualMethod(methods[i], methodName, parameters))
- return methods[i];
- }
- }
- return null;
- }
-
- /**
- * Finds the method specified by <code>methodName</code> and </code>parameters</code> in
- * the type hierarchy denoted by the given type. Returns <code>null</code> if no such method
- * exists. If the method is defined in more than one super type only the first match is
- * returned. First the super class is examined and than the implemented interfaces.
- * @param type the type to search the method in
- * @param methodName The name of the method to find
- * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored.
- * @return the method binding representing the method
- */
- public static IFunctionBinding findMethodInHierarchy(ITypeBinding type, String methodName, String[] parameters) {
- IFunctionBinding method= findMethodInType(type, methodName, parameters);
- if (method != null)
- return method;
- ITypeBinding superClass= type.getSuperclass();
- if (superClass != null) {
- method= findMethodInHierarchy(superClass, methodName, parameters);
- if (method != null)
- return method;
- }
- return null;
- }
-
- /**
- * Finds the method in the given <code>type</code> that is overridden by the specified <code>method<code>.
- * Returns <code>null</code> if no such method exits.
- * @param type The type to search the method in
- * @param method The specified method that would override the result
- * @return the method binding of the method that is overridden by the specified <code>method<code>, or <code>null</code>
- */
- public static IFunctionBinding findOverriddenMethodInType(ITypeBinding type, IFunctionBinding method) {
- IFunctionBinding[] methods= type.getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- if (isSubsignature(method, methods[i]))
- return methods[i];
- }
- return null;
- }
-
- /**
- * Finds a method in the hierarchy of <code>type</code> that is overridden by </code>binding</code>.
- * Returns <code>null</code> if no such method exists. If the method is defined in more than one super type only the first match is
- * returned. First the super class is examined and than the implemented interfaces.
- * @param type The type to search the method in
- * @param binding The method that overrides
- * @return the method binding overridden the method
- */
- public static IFunctionBinding findOverriddenMethodInHierarchy(ITypeBinding type, IFunctionBinding binding) {
- IFunctionBinding method= findOverriddenMethodInType(type, binding);
- if (method != null)
- return method;
- ITypeBinding superClass= type.getSuperclass();
- if (superClass != null) {
- method= findOverriddenMethodInHierarchy(superClass, binding);
- if (method != null)
- return method;
- }
- return null;
- }
-
-
- /**
- * Finds the method that is overridden by the given method. The search is bottom-up, so this
- * returns the nearest defining/declaring method.
- * @param overriding overriding method
- * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible.
- * @return the method binding representing the method
- */
- public static IFunctionBinding findOverriddenMethod(IFunctionBinding overriding, boolean testVisibility) {
- int modifiers= overriding.getModifiers();
- if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || overriding.isConstructor()) {
- return null;
- }
-
- ITypeBinding type= overriding.getDeclaringClass();
- if (type.getSuperclass() != null) {
- IFunctionBinding res= findOverriddenMethodInHierarchy(type.getSuperclass(), overriding);
- if (res != null && !Modifier.isPrivate(res.getModifiers())) {
- if (!testVisibility || isVisibleInHierarchy(res, overriding.getDeclaringClass().getPackage())) {
- return res;
- }
- }
- }
- return null;
- }
-
-
- public static boolean isVisibleInHierarchy(IFunctionBinding member, IPackageBinding pack) {
- int otherflags= member.getModifiers();
- ITypeBinding declaringType= member.getDeclaringClass();
- if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags)) {
- return true;
- } else if (Modifier.isPrivate(otherflags)) {
- return false;
- }
- return declaringType != null && pack == declaringType.getPackage();
- }
-
- /**
- * Returns all super types (classes and interfaces) for the given type.
- * @param type The type to get the supertypes of.
- * @return all super types (excluding <code>type</code>)
- */
- public static ITypeBinding[] getAllSuperTypes(ITypeBinding type) {
- Set result= new HashSet();
- collectSuperTypes(type, result);
- result.remove(type);
- return (ITypeBinding[]) result.toArray(new ITypeBinding[result.size()]);
- }
-
- private static void collectSuperTypes(ITypeBinding curr, Set collection) {
- if (collection.add(curr)) {
- ITypeBinding superClass= curr.getSuperclass();
- if (superClass != null) {
- collectSuperTypes(superClass, collection);
- }
- }
- }
-
- /**
- * Method to visit a type hierarchy defined by a given type.
- *
- * @param type the type which hierarchy is to be visited
- * @param visitor the visitor
- * @return <code>false</code> if the visiting got interrupted
- */
- public static boolean visitHierarchy(ITypeBinding type, TypeBindingVisitor visitor) {
- boolean result= visitSuperclasses(type, visitor);
- return result;
- }
-
- /**
- * Method to visit a super class hierarchy defined by a given type.
- *
- * @param type the type which super class hierarchy is to be visited
- * @param visitor the visitor
- * @return <code>false</code> if the visiting got interrupted
- */
- public static boolean visitSuperclasses(ITypeBinding type, TypeBindingVisitor visitor) {
- while ((type= type.getSuperclass()) != null) {
- if (!visitor.visit(type)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Tests whether the two methods are erasure-equivalent.
- * @deprecated use {@link #isSubsignature(IFunctionBinding, IFunctionBinding)}
- */
- //TODO: rename to isErasureEquivalentMethod and change to two IFunctionBinding parameters
- public static boolean isEqualMethod(IFunctionBinding method, String methodName, ITypeBinding[] parameters) {
- if (!method.getName().equals(methodName))
- return false;
-
- ITypeBinding[] methodParameters= method.getParameterTypes();
- if (methodParameters.length != parameters.length)
- return false;
- for (int i= 0; i < parameters.length; i++) {
- if (!equals(methodParameters[i].getErasure(), parameters[i].getErasure()))
- return false;
- }
- //Can't use this fix, since some clients assume that this method tests erasure equivalence:
-// if (method.getTypeParameters().length == 0) {
-// //a method without type parameters cannot be overridden by one that declares type parameters -> can be exact here
-// for (int i= 0; i < parameters.length; i++) {
-// if ( ! (equals(methodParameters[i], parameters[i])
-// || equals(methodParameters[i].getErasure(), parameters[i]))) // subsignature
-// return false;
-// }
-// } else {
-// //this will find all overridden methods, but may generate false positives in some cases:
-// for (int i= 0; i < parameters.length; i++) {
-// if (!equals(methodParameters[i].getErasure(), parameters[i].getErasure()))
-// return false;
-// }
-// }
- return true;
- }
-
- /**
- * @param overriding overriding method (m1)
- * @param overridden overridden method (m2)
- * @return <code>true</code> iff the method <code>m1</code> is a subsignature of the method <code>m2</code>.
- * This is one of the requirements for m1 to override m2.
- * Accessibility and return types are not taken into account.
- * Note that subsignature is <em>not</em> symmetric!
- */
- public static boolean isSubsignature(IFunctionBinding overriding, IFunctionBinding overridden) {
- //TODO: use IFunctionBinding#isSubsignature(..) once it is tested and fixed (only erasure of m1's parameter types, considering type variable counts, doing type variable substitution
- if (!overriding.getName().equals(overridden.getName()))
- return false;
-
- ITypeBinding[] m1Params= overriding.getParameterTypes();
- ITypeBinding[] m2Params= overridden.getParameterTypes();
- if (m1Params.length != m2Params.length)
- return false;
-
- // m1TypeParams.length == m2TypeParams.length == 0
- if (equals(m1Params, m2Params))
- return true;
- for (int i= 0; i < m1Params.length; i++) {
- ITypeBinding m1Param= m1Params[i];
- if (! (equals(m1Param, m2Params[i].getErasure()))) // can erase m2
- return false;
- }
- return true;
-
- }
-
- /**
- * @param method
- * @param methodName
- * @param parameters
- * @return <code>true</code> iff the method
- * m1 (with name <code>methodName</code> and method parameters <code>parameters</code>)
- * is a subsignature of the method <code>m2</code>. Accessibility and return types are not taken into account.
- */
- public static boolean isEqualMethod(IFunctionBinding method, String methodName, String[] parameters) {
- if (!method.getName().equals(methodName))
- return false;
-
- ITypeBinding[] methodParameters= method.getParameterTypes();
- if (methodParameters.length != parameters.length)
- return false;
- String first, second;
- int index;
- for (int i= 0; i < parameters.length; i++) {
- first= parameters[i];
- index= first.indexOf('<');
- if (index > 0)
- first= first.substring(0, index);
- second= methodParameters[i].getErasure().getQualifiedName();
- index= second.indexOf('<');
- if (index > 0)
- second= second.substring(0, index);
- if (!first.equals(second))
- return false;
- }
- return true;
- }
-
- /**
- * Finds a type binding for a given fully qualified type in the hierarchy of a type.
- * Returns <code>null</code> if no type binding is found.
- * @param hierarchyType the binding representing the hierarchy
- * @param fullyQualifiedTypeName the fully qualified name to search for
- * @return the type binding
- */
- public static ITypeBinding findTypeInHierarchy(ITypeBinding hierarchyType, String fullyQualifiedTypeName) {
- if (hierarchyType.isArray() || hierarchyType.isPrimitive()) {
- return null;
- }
- if (fullyQualifiedTypeName.equals(hierarchyType.getQualifiedName())) {
- return hierarchyType;
- }
- ITypeBinding superClass= hierarchyType.getSuperclass();
- if (superClass != null) {
- ITypeBinding res= findTypeInHierarchy(superClass, fullyQualifiedTypeName);
- if (res != null) {
- return res;
- }
- }
- return null;
- }
-
- /**
- * Returns the binding of the variable written in an Assignment.
- * @param assignment The assignment
- * @return The binding or <code>null</code> if no bindings are available.
- */
- public static IVariableBinding getAssignedVariable(Assignment assignment) {
- Expression leftHand = assignment.getLeftHandSide();
- switch (leftHand.getNodeType()) {
- case ASTNode.SIMPLE_NAME:
- return (IVariableBinding) ((SimpleName) leftHand).resolveBinding();
- case ASTNode.QUALIFIED_NAME:
- return (IVariableBinding) ((QualifiedName) leftHand).getName().resolveBinding();
- case ASTNode.FIELD_ACCESS:
- return ((FieldAccess) leftHand).resolveFieldBinding();
- case ASTNode.SUPER_FIELD_ACCESS:
- return ((SuperFieldAccess) leftHand).resolveFieldBinding();
- default:
- return null;
- }
- }
-
- /**
- * Returns <code>true</code> if the given type is a super type of a candidate.
- * <code>true</code> is returned if the two type bindings are identical (TODO)
- * @param possibleSuperType the type to inspect
- * @param type the type whose super types are looked at
- * @return <code>true</code> iff <code>possibleSuperType</code> is
- * a super type of <code>type</code> or is equal to it
- */
- public static boolean isSuperType(ITypeBinding possibleSuperType, ITypeBinding type) {
- if (type.isArray() || type.isPrimitive()) {
- return false;
- }
- if (Bindings.equals(type, possibleSuperType)) {
- return true;
- }
- ITypeBinding superClass= type.getSuperclass();
- if (superClass != null) {
- if (isSuperType(possibleSuperType, superClass)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Finds the compilation unit where the type of the given <code>ITypeBinding</code> is defined,
- * using the class path defined by the given Java project. Returns <code>null</code>
- * if no compilation unit is found (e.g. type binding is from a binary type)
- * @param typeBinding the type binding to search for
- * @param project the project used as a scope
- * @return the compilation unit containing the type
- * @throws JavaScriptModelException if an errors occurs in the Java model
- */
- public static IJavaScriptUnit findCompilationUnit(ITypeBinding typeBinding, IJavaScriptProject project) throws JavaScriptModelException {
- IJavaScriptElement type= typeBinding.getJavaElement();
- if (type instanceof IType)
- return ((IType) type).getJavaScriptUnit();
- else
- return null;
- }
-
- /**
- * Finds a method for the given <code>IFunctionBinding</code>. Returns
- * <code>null</code> if the type doesn't contain a corresponding method.
- * @param method the method to find
- * @param type the type to look in
- * @return the corresponding IFunction or <code>null</code>
- * @throws JavaScriptModelException if an error occurs in the Java model
- * @deprecated Use {@link #findMethodInHierarchy(ITypeBinding, String, String[])} or {@link JavaModelUtil}
- */
- public static IFunction findMethod(IFunctionBinding method, IType type) throws JavaScriptModelException {
- method= method.getMethodDeclaration();
-
- IFunction[] candidates= type.getFunctions();
- for (int i= 0; i < candidates.length; i++) {
- IFunction candidate= candidates[i];
- if (candidate.getElementName().equals(method.getName()) && sameParameters(method, candidate)) {
- return candidate;
- }
- }
- return null;
- }
-
- //---- Helper methods to convert a method ---------------------------------------------
-
- private static boolean sameParameters(IFunctionBinding method, IFunction candidate) throws JavaScriptModelException {
- ITypeBinding[] methodParamters= method.getParameterTypes();
- String[] candidateParameters= candidate.getParameterTypes();
- if (methodParamters.length != candidateParameters.length)
- return false;
- IType scope= candidate.getDeclaringType();
- for (int i= 0; i < methodParamters.length; i++) {
- ITypeBinding methodParameter= methodParamters[i];
- String candidateParameter= candidateParameters[i];
- if (!sameParameter(methodParameter, candidateParameter, scope))
- return false;
- }
- return true;
- }
-
- private static boolean sameParameter(ITypeBinding type, String candidate, IType scope) throws JavaScriptModelException {
- if (type.getDimensions() != Signature.getArrayCount(candidate))
- return false;
-
- // Normalizes types
- if (type.isArray())
- type= type.getElementType();
- candidate= Signature.getElementType(candidate);
-
- if ((Signature.getTypeSignatureKind(candidate) == Signature.BASE_TYPE_SIGNATURE) != type.isPrimitive()) {
- return false;
- }
-
- if (type.isPrimitive()) {
- return type.getName().equals(Signature.toString(candidate));
- } else {
- type= type.getErasure();
-
- if (candidate.charAt(Signature.getArrayCount(candidate)) == Signature.C_RESOLVED) {
- return Signature.toString(candidate).equals(Bindings.getFullyQualifiedName(type));
- } else {
- String[][] qualifiedCandidates= scope.resolveType(Signature.toString(candidate));
- if (qualifiedCandidates == null || qualifiedCandidates.length == 0)
- return false;
- String packageName= type.getPackage().isUnnamed() ? "" : type.getPackage().getName(); //$NON-NLS-1$
- String typeName= getTypeQualifiedName(type);
- for (int i= 0; i < qualifiedCandidates.length; i++) {
- String[] qualifiedCandidate= qualifiedCandidates[i];
- if ( qualifiedCandidate[0].equals(packageName) &&
- qualifiedCandidate[1].equals(typeName))
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Normalizes a type binding received from an expression to a type binding that can be used in a declaration signature.
- * Anonymous types are normalized, to the super class or interface. For null or void bindings
- * <code>null</code> is returned.
- * @param binding the binding to normalize
- * @return the normalized binding
- */
- public static ITypeBinding normalizeTypeBinding(ITypeBinding binding) {
- if (binding != null && !binding.isNullType() && !isVoidType(binding)) {
- if (binding.isAnonymous()) {
- return binding.getSuperclass();
- }
- return binding;
- }
- return null;
- }
-
- public static boolean isVoidType(ITypeBinding binding) {
- return "void".equals(binding.getName()); //$NON-NLS-1$
- }
-
- /**
- * Normalizes the binding so that it can be used as a type inside a declaration
- * (e.g. variable declaration, method return type, parameter type, ...). For
- * null bindings Object is returned.
- * @param binding binding to normalize
- * @param ast current ast
- *
- * @return the normalized type to be used in declarations
- */
- public static ITypeBinding normalizeForDeclarationUse(ITypeBinding binding, AST ast) {
- if (binding.isNullType())
- return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- if (binding.isPrimitive())
- return binding;
- binding= normalizeTypeBinding(binding);
- return binding;
- }
-
- /**
- * Returns the type binding of the node's parent type declaration.
- * @param node
- * @return the type binding of the node's parent type declaration
- */
- public static ITypeBinding getBindingOfParentType(ASTNode node) {
- while (node != null) {
- if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration) node).resolveBinding();
- } else if (node instanceof AnonymousClassDeclaration) {
- return ((AnonymousClassDeclaration) node).resolveBinding();
- } else if (node instanceof JavaScriptUnit) {
- return ((JavaScriptUnit) node).resolveBinding();
- }
- node= node.getParent();
- }
- return null;
- }
-
- /**
- * Returns the type binding of the node's type context or null if the node is an annotation, type parameter or super type declaration of a tope level type.
- * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body.
- * @param node
- * @return the type binding of the node's parent type context
- */
- public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) {
- StructuralPropertyDescriptor lastLocation= null;
-
- while (node != null) {
- if (node instanceof AbstractTypeDeclaration) {
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node;
- if (lastLocation == decl.getBodyDeclarationsProperty()) {
- return decl.resolveBinding();
- }
- } else if (node instanceof AnonymousClassDeclaration) {
- return ((AnonymousClassDeclaration) node).resolveBinding();
- }
- lastLocation= node.getLocationInParent();
- node= node.getParent();
- }
- return null;
- }
-
-
- public static String getRawName(ITypeBinding binding) {
- String name= binding.getName();
- return name;
- }
-
-
- public static String getRawQualifiedName(ITypeBinding binding) {
- final String EMPTY= ""; //$NON-NLS-1$
-
- if (binding.isAnonymous() || binding.isLocal()) {
- return EMPTY;
- }
-
- if (binding.isPrimitive() || binding.isNullType()) {
- return binding.getName();
- }
-
- if (binding.isArray()) {
- String elementTypeQualifiedName = getRawQualifiedName(binding.getElementType());
- if (elementTypeQualifiedName.length() != 0) {
- StringBuffer stringBuffer= new StringBuffer(elementTypeQualifiedName);
- stringBuffer.append('[').append(']');
- return stringBuffer.toString();
- } else {
- return EMPTY;
- }
- }
- if (binding.isMember()) {
- String outerName= getRawQualifiedName(binding.getDeclaringClass());
- if (outerName.length() > 0) {
- StringBuffer buffer= new StringBuffer();
- buffer.append(outerName);
- buffer.append('.');
- buffer.append(getRawName(binding));
- return buffer.toString();
- } else {
- return EMPTY;
- }
-
- } else if (binding.isTopLevel()) {
- IPackageBinding packageBinding= binding.getPackage();
- StringBuffer buffer= new StringBuffer();
- if (packageBinding != null && packageBinding.getName().length() > 0) {
- buffer.append(packageBinding.getName()).append('.');
- }
- buffer.append(getRawName(binding));
- return buffer.toString();
- }
- return EMPTY;
- }
-
-
- /**
- * Tests if the given node is a declaration, not a instance of a generic type, method or field.
- * Declarations can be found in AST with JavaScriptUnit.findDeclaringNode
- * @param binding binding to test
- * @return returns <code>true</code> if the binding is a declaration binding
- */
- public static boolean isDeclarationBinding(IBinding binding) {
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return ((ITypeBinding) binding).getTypeDeclaration() == binding;
- case IBinding.VARIABLE:
- return ((IVariableBinding) binding).getVariableDeclaration() == binding;
- case IBinding.METHOD:
- return ((IFunctionBinding) binding).getMethodDeclaration() == binding;
- }
- return true;
- }
-
-
- public static IBinding getDeclaration(IBinding binding) {
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return ((ITypeBinding) binding).getTypeDeclaration();
- case IBinding.VARIABLE:
- return ((IVariableBinding) binding).getVariableDeclaration();
- case IBinding.METHOD:
- return ((IFunctionBinding) binding).getMethodDeclaration();
- }
- return binding;
- }
-
-
- /**
- * @deprecated Need to review: Use {@link #isSubsignature(IFunctionBinding, IFunctionBinding)} if the two bindings
- * are in the same hierarchy (directly overrides each other), or {@link #findMethodInHierarchy(ITypeBinding, String, ITypeBinding[])}
- * else.
- */
- public static boolean containsSignatureEquivalentConstructor(IFunctionBinding[] candidates, IFunctionBinding overridable) {
- for (int index= 0; index < candidates.length; index++) {
- if (isSignatureEquivalentConstructor(candidates[index], overridable))
- return true;
- }
- return false;
- }
-
- private static boolean isSignatureEquivalentConstructor(IFunctionBinding overridden, IFunctionBinding overridable) {
-
- if (!overridden.isConstructor() || !overridable.isConstructor())
- return false;
-
- if (overridden.isDefaultConstructor())
- return false;
-
- return areSubTypeCompatible(overridden, overridable);
- }
-
- /**
- * @deprecated Need to review: Use {@link #isSubsignature(IFunctionBinding, IFunctionBinding)} if the two bindings
- * are in the same hierarchy (directly overrides each other), or {@link #findMethodInHierarchy(ITypeBinding, String, ITypeBinding[])}
- * else.
- */
- public static boolean areOverriddenMethods(IFunctionBinding overridden, IFunctionBinding overridable) {
-
- if (!overridden.getName().equals(overridable.getName()))
- return false;
-
- return areSubTypeCompatible(overridden, overridable);
- }
-
- private static boolean areSubTypeCompatible(IFunctionBinding overridden, IFunctionBinding overridable) {
-
- if (overridden.getParameterTypes().length != overridable.getParameterTypes().length)
- return false;
-
- ITypeBinding overriddenReturn= overridden.getReturnType();
- ITypeBinding overridableReturn= overridable.getReturnType();
- if (overriddenReturn == null || overridableReturn == null)
- return false;
-
- if (!overriddenReturn.getErasure().isSubTypeCompatible(overridableReturn.getErasure()))
- return false;
-
- ITypeBinding[] overriddenTypes= overridden.getParameterTypes();
- ITypeBinding[] overridableTypes= overridable.getParameterTypes();
- Assert.isTrue(overriddenTypes.length == overridableTypes.length);
- for (int index= 0; index < overriddenTypes.length; index++) {
- final ITypeBinding overridableErasure= overridableTypes[index].getErasure();
- final ITypeBinding overriddenErasure= overriddenTypes[index].getErasure();
- if (!overridableErasure.isSubTypeCompatible(overriddenErasure) || !overridableErasure.getKey().equals(overriddenErasure.getKey()))
- return false;
- }
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/BodyDeclarationRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/BodyDeclarationRewrite.java
deleted file mode 100644
index fa81383e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/BodyDeclarationRewrite.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.List;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class BodyDeclarationRewrite {
-
- private ASTNode fTypeNode;
- private ListRewrite fListRewrite;
-
- public static BodyDeclarationRewrite create(ASTRewrite rewrite, ASTNode typeNode) {
- return new BodyDeclarationRewrite(rewrite, typeNode);
- }
-
- private BodyDeclarationRewrite(ASTRewrite rewrite, ASTNode typeNode) {
- ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(typeNode);
- fTypeNode= typeNode;
- fListRewrite= rewrite.getListRewrite(typeNode, property);
- }
-
- public void insert(BodyDeclaration decl, TextEditGroup description) {
- List container= ASTNodes.getBodyDeclarations(fTypeNode);
- int index= ASTNodes.getInsertionIndex(decl, container);
- fListRewrite.insertAt(decl, index, description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/CodeScopeBuilder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/CodeScopeBuilder.java
deleted file mode 100644
index 3f894660..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/CodeScopeBuilder.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CodeScopeBuilder extends ASTVisitor {
-
- public static class Scope {
- private Scope fParent;
- private int fStart;
- private int fLength;
- private List fNames;
- private List fChildren;
- private int fCursorOffset;
- Scope(Scope parent, int start, int length) {
- fParent= parent;
- fStart= start;
- fLength= length;
- if (fParent != null)
- fParent.addChild(this);
- }
- public void setCursor(int offset) {
- fCursorOffset= offset;
- }
- private void addChild(Scope child) {
- if (fChildren == null)
- fChildren= new ArrayList(2);
- fChildren.add(child);
- }
- private void addName(String name) {
- if (fNames == null)
- fNames= new ArrayList(2);
- fNames.add(name);
- }
- public Scope findScope(int start, int length) {
- if (fStart <= start && start + length <= fStart + fLength) {
- if (fChildren == null)
- return this;
- for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
- Scope scope= ((Scope)iter.next()).findScope(start, length);
- if (scope != null)
- return scope;
- }
- return this;
- }
- return null;
- }
- public String createName(String candidate, boolean add) {
- int i= 1;
- String result= candidate;
- while(isInUse(result)) {
- result= candidate + i++;
- }
- if (add)
- addName(result);
- return result;
- }
- public boolean isInUse(String name) {
- if (internalIsInUse(name))
- return true;
- if (fChildren != null) {
- for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
- Scope child= (Scope) iter.next();
- if (fCursorOffset < child.fStart && child.isInUseDown(name)) {
- return true;
- }
- }
- }
- return false;
- }
- private boolean internalIsInUse(String name) {
- if (fNames != null && fNames.contains(name))
- return true;
- if (fParent != null)
- return fParent.internalIsInUse(name);
- return false;
-
- }
- private boolean isInUseDown(String name) {
- if (fNames != null && fNames.contains(name))
- return true;
- if (fChildren == null)
- return false;
- for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
- Scope scope= (Scope) iter.next();
- if (scope.isInUseDown(name))
- return true;
- }
- return false;
- }
- }
-
- private IBinding fIgnoreBinding;
- private Selection fIgnoreRange;
- private Scope fScope;
- private List fScopes;
-
- public static Scope perform(BodyDeclaration node, IBinding ignore) {
- CodeScopeBuilder collector= new CodeScopeBuilder(node, ignore);
- node.accept(collector);
- return collector.fScope;
- }
-
- public static Scope perform(BodyDeclaration node, Selection ignore) {
- CodeScopeBuilder collector= new CodeScopeBuilder(node, ignore);
- node.accept(collector);
- return collector.fScope;
- }
-
- private CodeScopeBuilder(ASTNode node, IBinding ignore) {
- fScope= new Scope(null, node.getStartPosition(), node.getLength());
- fScopes= new ArrayList();
- fIgnoreBinding= ignore;
- }
-
- private CodeScopeBuilder(ASTNode node, Selection ignore) {
- fScope= new Scope(null, node.getStartPosition(), node.getLength());
- fScopes= new ArrayList();
- fIgnoreRange= ignore;
- }
-
- public boolean visit(CatchClause node) {
- // open a new scope for the exception declaration.
- fScopes.add(fScope);
- fScope= new Scope(fScope, node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(CatchClause node) {
- fScope= (Scope)fScopes.remove(fScopes.size() - 1);
- }
-
- public boolean visit(SimpleName node) {
- if (fIgnoreBinding != null && Bindings.equals(fIgnoreBinding, node.resolveBinding()))
- return false;
- if (fIgnoreRange != null && fIgnoreRange.covers(node))
- return false;
- fScope.addName(node.getIdentifier());
- return false;
- }
-
- public boolean visit(QualifiedName node) {
- // only consider the left most identifier.
- node.getQualifier().accept(this);
- return false;
- }
-
- public boolean visit(FunctionInvocation node) {
- Expression receiver= node.getExpression();
- if (receiver == null) {
- SimpleName name= node.getName();
- if (fIgnoreBinding == null || (name!=null && !Bindings.equals(fIgnoreBinding, name.resolveBinding())) )
- node.getName().accept(this);
- } else {
- receiver.accept(this);
- }
- accept(node.arguments());
- return false;
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- fScope.addName(node.getTypeDeclaration().getName().getIdentifier());
- } else {
- fScope.addName(node.getDeclaration().getName().getIdentifier());
- }
- return false;
- }
-
- public boolean visit(Block node) {
- fScopes.add(fScope);
- fScope= new Scope(fScope, node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(Block node) {
- fScope= (Scope)fScopes.remove(fScopes.size() - 1);
- }
-
- public boolean visit(ForStatement node) {
- fScopes.add(fScope);
- fScope= new Scope(fScope, node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(ForStatement node) {
- fScope= (Scope)fScopes.remove(fScopes.size() - 1);
- }
-
- private void accept(List list) {
- int size;
- if (list == null || (size= list.size()) == 0)
- return;
- for (int i= 0; i < size; i++) {
- ((ASTNode)list.get(i)).accept(this);
- }
- }
- public boolean visit(ForInStatement node) {
- fScopes.add(fScope);
- fScope= new Scope(fScope, node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(ForInStatement node) {
- fScope= (Scope)fScopes.remove(fScopes.size() - 1);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/GenericVisitor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/GenericVisitor.java
deleted file mode 100644
index 69be7742..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/GenericVisitor.java
+++ /dev/null
@@ -1,659 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BlockComment;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class GenericVisitor extends ASTVisitor {
-
- public GenericVisitor() {
- super();
- }
-
- /**
- * @param visitJavadocTags <code>true</code> if doc comment tags are
- * to be visited by default, and <code>false</code> otherwise
- * @see JSdoc#tags()
- * @see #visit(JSdoc)
-
- */
- public GenericVisitor(boolean visitJavadocTags) {
- super(visitJavadocTags);
- }
-
- //---- Hooks for subclasses -------------------------------------------------
-
- protected boolean visitNode(ASTNode node) {
- return true;
- }
-
- protected void endVisitNode(ASTNode node) {
- // do nothing
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ArrayAccess node) {
- return visitNode(node);
- }
- public boolean visit(ArrayCreation node) {
- return visitNode(node);
- }
- public boolean visit(ArrayInitializer node) {
- return visitNode(node);
- }
- public boolean visit(ArrayType node) {
- return visitNode(node);
- }
- public boolean visit(Assignment node) {
- return visitNode(node);
- }
- public boolean visit(Block node) {
- return visitNode(node);
- }
- public boolean visit(BooleanLiteral node) {
- return visitNode(node);
- }
- public boolean visit(BreakStatement node) {
- return visitNode(node);
- }
- public boolean visit(FunctionExpression node) {
- return visitNode(node);
- }
- public boolean visit(ObjectLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ObjectLiteralField node) {
- return visitNode(node);
- }
- public boolean visit(CatchClause node) {
- return visitNode(node);
- }
- public boolean visit(CharacterLiteral node) {
- return visitNode(node);
- }
- public boolean visit(RegularExpressionLiteral node) {
- return visitNode(node);
- }
- public boolean visit(ClassInstanceCreation node) {
- return visitNode(node);
- }
- public boolean visit(JavaScriptUnit node) {
- return visitNode(node);
- }
- public boolean visit(ConditionalExpression node) {
- return visitNode(node);
- }
- public boolean visit(ConstructorInvocation node) {
- return visitNode(node);
- }
- public boolean visit(ContinueStatement node) {
- return visitNode(node);
- }
- public boolean visit(DoStatement node) {
- return visitNode(node);
- }
- public boolean visit(EmptyStatement node) {
- return visitNode(node);
- }
- public boolean visit(ExpressionStatement node) {
- return visitNode(node);
- }
- public boolean visit(FieldAccess node) {
- return visitNode(node);
- }
- public boolean visit(FieldDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ForStatement node) {
- return visitNode(node);
- }
- public boolean visit(ForInStatement node) {
- return visitNode(node);
- }
- public boolean visit(IfStatement node) {
- return visitNode(node);
- }
- public boolean visit(ImportDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(InfixExpression node) {
- return visitNode(node);
- }
- public boolean visit(InstanceofExpression node) {
- return visitNode(node);
- }
- public boolean visit(Initializer node) {
- return visitNode(node);
- }
- public boolean visit(JSdoc node) {
- if (super.visit(node))
- return visitNode(node);
- else
- return false;
- }
- public boolean visit(LabeledStatement node) {
- return visitNode(node);
- }
- public boolean visit(ListExpression node) {
- return visitNode(node);
- }
- public boolean visit(FunctionDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(FunctionInvocation node) {
- return visitNode(node);
- }
- public boolean visit(NullLiteral node) {
- return visitNode(node);
- }
- public boolean visit(UndefinedLiteral node) {
- return visitNode(node);
- }
- public boolean visit(NumberLiteral node) {
- return visitNode(node);
- }
- public boolean visit(PackageDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(ParenthesizedExpression node) {
- return visitNode(node);
- }
- public boolean visit(PostfixExpression node) {
- return visitNode(node);
- }
- public boolean visit(PrefixExpression node) {
- return visitNode(node);
- }
- public boolean visit(PrimitiveType node) {
- return visitNode(node);
- }
- public boolean visit(QualifiedName node) {
- return visitNode(node);
- }
- public boolean visit(ReturnStatement node) {
- return visitNode(node);
- }
- public boolean visit(SimpleName node) {
- return visitNode(node);
- }
- public boolean visit(SimpleType node) {
- return visitNode(node);
- }
- public boolean visit(StringLiteral node) {
- return visitNode(node);
- }
- public boolean visit(SuperConstructorInvocation node) {
- return visitNode(node);
- }
- public boolean visit(SuperFieldAccess node) {
- return visitNode(node);
- }
- public boolean visit(SuperMethodInvocation node) {
- return visitNode(node);
- }
- public boolean visit(SwitchCase node) {
- return visitNode(node);
- }
- public boolean visit(SwitchStatement node) {
- return visitNode(node);
- }
-
- public boolean visit(ThisExpression node) {
- return visitNode(node);
- }
- public boolean visit(ThrowStatement node) {
- return visitNode(node);
- }
- public boolean visit(TryStatement node) {
- return visitNode(node);
- }
- public boolean visit(TypeDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(TypeDeclarationStatement node) {
- return visitNode(node);
- }
- public boolean visit(TypeLiteral node) {
- return visitNode(node);
- }
- public boolean visit(SingleVariableDeclaration node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationExpression node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationStatement node) {
- return visitNode(node);
- }
- public boolean visit(VariableDeclarationFragment node) {
- return visitNode(node);
- }
- public boolean visit(WhileStatement node) {
- return visitNode(node);
- }
- public boolean visit(WithStatement node) {
- return visitNode(node);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BlockComment)
- */
- public boolean visit(BlockComment node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.EnhancedForStatement)
- */
- public boolean visit(EnhancedForStatement node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.LineComment)
- */
- public boolean visit(LineComment node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.MemberRef)
- */
- public boolean visit(MemberRef node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRef)
- */
- public boolean visit(FunctionRef node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionRefParameter)
- */
- public boolean visit(FunctionRefParameter node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Modifier)
- */
- public boolean visit(Modifier node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.QualifiedType)
- */
- public boolean visit(QualifiedType node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TagElement)
- */
- public boolean visit(TagElement node) {
- return visitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TextElement)
- */
- public boolean visit(TextElement node) {
- return visitNode(node);
- }
-
- public void endVisit(AnonymousClassDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(ArrayAccess node) {
- endVisitNode(node);
- }
- public void endVisit(ArrayCreation node) {
- endVisitNode(node);
- }
- public void endVisit(ArrayInitializer node) {
- endVisitNode(node);
- }
- public void endVisit(ArrayType node) {
- endVisitNode(node);
- }
- public void endVisit(Assignment node) {
- endVisitNode(node);
- }
- public void endVisit(Block node) {
- endVisitNode(node);
- }
- public void endVisit(BooleanLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(BreakStatement node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionExpression node) {
- endVisitNode(node);
- }
- public void endVisit(ObjectLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(ObjectLiteralField node) {
- endVisitNode(node);
- }
-
- public void endVisit(CatchClause node) {
- endVisitNode(node);
- }
- public void endVisit(CharacterLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(RegularExpressionLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(ClassInstanceCreation node) {
- endVisitNode(node);
- }
- public void endVisit(JavaScriptUnit node) {
- endVisitNode(node);
- }
- public void endVisit(ConditionalExpression node) {
- endVisitNode(node);
- }
- public void endVisit(ConstructorInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(ContinueStatement node) {
- endVisitNode(node);
- }
- public void endVisit(DoStatement node) {
- endVisitNode(node);
- }
- public void endVisit(EmptyStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ExpressionStatement node) {
- endVisitNode(node);
- }
- public void endVisit(FieldAccess node) {
- endVisitNode(node);
- }
- public void endVisit(FieldDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(ForStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ForInStatement node) {
- endVisitNode(node);
- }
- public void endVisit(IfStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ImportDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(InfixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(InstanceofExpression node) {
- endVisitNode(node);
- }
- public void endVisit(Initializer node) {
- endVisitNode(node);
- }
- public void endVisit(JSdoc node) {
- endVisitNode(node);
- }
- public void endVisit(LabeledStatement node) {
- endVisitNode(node);
- }
- public void endVisit(ListExpression node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(FunctionInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(NullLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(UndefinedLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(NumberLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(PackageDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(ParenthesizedExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PostfixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PrefixExpression node) {
- endVisitNode(node);
- }
- public void endVisit(PrimitiveType node) {
- endVisitNode(node);
- }
- public void endVisit(QualifiedName node) {
- endVisitNode(node);
- }
- public void endVisit(ReturnStatement node) {
- endVisitNode(node);
- }
- public void endVisit(SimpleName node) {
- endVisitNode(node);
- }
- public void endVisit(SimpleType node) {
- endVisitNode(node);
- }
- public void endVisit(StringLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(SuperConstructorInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(SuperFieldAccess node) {
- endVisitNode(node);
- }
- public void endVisit(SuperMethodInvocation node) {
- endVisitNode(node);
- }
- public void endVisit(SwitchCase node) {
- endVisitNode(node);
- }
- public void endVisit(SwitchStatement node) {
- endVisitNode(node);
- }
-
- public void endVisit(ThisExpression node) {
- endVisitNode(node);
- }
- public void endVisit(ThrowStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TryStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TypeDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(TypeDeclarationStatement node) {
- endVisitNode(node);
- }
- public void endVisit(TypeLiteral node) {
- endVisitNode(node);
- }
- public void endVisit(SingleVariableDeclaration node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationExpression node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationStatement node) {
- endVisitNode(node);
- }
- public void endVisit(VariableDeclarationFragment node) {
- endVisitNode(node);
- }
- public void endVisit(WhileStatement node) {
- endVisitNode(node);
- }
-
- public void endVisit(WithStatement node) {
- endVisitNode(node);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.BlockComment)
- */
- public void endVisit(BlockComment node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.EnhancedForStatement)
- */
- public void endVisit(EnhancedForStatement node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.LineComment)
- */
- public void endVisit(LineComment node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.MemberRef)
- */
- public void endVisit(MemberRef node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FunctionRef)
- */
- public void endVisit(FunctionRef node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FunctionRefParameter)
- */
- public void endVisit(FunctionRefParameter node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.Modifier)
- */
- public void endVisit(Modifier node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.QualifiedType)
- */
- public void endVisit(QualifiedType node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.TagElement)
- */
- public void endVisit(TagElement node) {
- endVisitNode(node);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.TextElement)
- */
- public void endVisit(TextElement node) {
- endVisitNode(node);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/HierarchicalASTVisitor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/HierarchicalASTVisitor.java
deleted file mode 100644
index ff50315c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/HierarchicalASTVisitor.java
+++ /dev/null
@@ -1,789 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BlockComment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Comment;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-
-/**
- * <p>This class provides a convenient behaviour-only
- * extension mechanism for the ASTNode hierarchy.
- * If you feel like you would like to add a method to
- * the ASTNode hierarchy (or a subtree of the hierarchy),
- * and you want to have different implementations
- * of it at different points in the hierarchy,
- * simply create a HierarchicalASTVisitor representing
- * the new method and all its implementations,
- * locating each implementation within the right
- * visit(XX) method. If you wanted to add a method implementation to abstract
- * class Foo, an ASTNode descendant, put your implementation in visit(Foo).
- * This class will provide appropriate dispatch, just as if the method
- * implementations had been added to the ASTNode hierarchy.
- * </p>
- *
- * <p><b>Details:<b></p>
- *
- * <p>This class has a visit(XX node) method for every for every
- * class (concrete or abstract) XX in the ASTNode hierarchy. In this class'
- * default implementations of these methods, the method corresponding to a given
- * ASTNode descendant class will call (and return the return value of) the
- * visit(YY) method for it's superclass YY, with the exception of the
- * visit(ASTNode) method which simply returns true, since ASTNode doesn't have a
- * superclass that is within the ASTNode hierarchy.
- * </p>
- *
- * <p>Because of this organization, when visit(XX) methods are overridden in a
- * subclass, and the visitor is applied to a node, only the most specialized
- * overridden method implementation for the node's type will be called, unless
- * this most specialized method calls other visit methods (this is discouraged)
- * or, (preferably) calls super.visit(XX node), (the reference type of the
- * parameter must be XX) which will invoke this class' implementation of the
- * method, which will, in turn, invoke the visit(YY) method corresponding to the
- * superclass, YY.
- * </p>
- *
- * <p>Thus, the dispatching behaviour achieved when
- * HierarchicalASTVisitors' visit(XX) methods, corresponding to a particular
- * concrete or abstract ASTNode descendant class, are overridden is exactly
- * analogous to the dispatching behaviour obtained when method implementations
- * are added to the same ASTNode descendant classes.
- * </p>
- */
-/*
-
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public abstract class HierarchicalASTVisitor extends ASTVisitor {
-//TODO: check callers for handling of comments
-
-//---- Begin ASTNode Hierarchy -------------------------------------
-public boolean visit(ASTNode node) {
- return true;
-}
-public void endVisit(ASTNode node) {
- // do nothing
-}
-
-public boolean visit(AnonymousClassDeclaration node) {
- return visit((ASTNode) node);
-}
-public void endVisit(AnonymousClassDeclaration node) {
- endVisit((ASTNode) node);
-}
-
-//---- Begin BodyDeclaration Hierarchy ---------------------------
-public boolean visit(BodyDeclaration node) {
- return visit((ASTNode) node);
-}
-public void endVisit(BodyDeclaration node) {
- endVisit((ASTNode) node);
-}
-
- //---- Begin AbstractTypeDeclaration Hierarchy ---------------------------
- public boolean visit(AbstractTypeDeclaration node) {
- return visit((BodyDeclaration) node);
- }
- public void endVisit(AbstractTypeDeclaration node) {
- endVisit((BodyDeclaration) node);
- }
-
-
- public boolean visit(TypeDeclaration node) {
- return visit((AbstractTypeDeclaration) node);
- }
- public void endVisit(TypeDeclaration node) {
- endVisit((AbstractTypeDeclaration) node);
- }
- //---- End AbstractTypeDeclaration Hierarchy ---------------------------
-
-
-
- public boolean visit(FieldDeclaration node) {
- return visit((BodyDeclaration) node);
- }
- public void endVisit(FieldDeclaration node) {
- endVisit((BodyDeclaration) node);
- }
-
- public boolean visit(Initializer node) {
- return visit((BodyDeclaration) node);
- }
- public void endVisit(Initializer node) {
- endVisit((BodyDeclaration) node);
- }
-
- public boolean visit(FunctionDeclaration node) {
- return visit((BodyDeclaration) node);
- }
- public void endVisit(FunctionDeclaration node) {
- endVisit((BodyDeclaration) node);
- }
-
-//---- End BodyDeclaration Hierarchy -----------------------------
-
-public boolean visit(CatchClause node) {
- return visit((ASTNode) node);
-}
-public void endVisit(CatchClause node) {
- endVisit((ASTNode) node);
-}
-
-//---- Begin Comment Hierarchy ----------------------------------
-public boolean visit(Comment node) {
- return visit((ASTNode) node);
-}
-public void endVisit(Comment node) {
- endVisit((ASTNode) node);
-}
-
- public boolean visit(BlockComment node) {
- return visit((Comment) node);
- }
- public void endVisit(BlockComment node) {
- endVisit((Comment) node);
- }
-
- public boolean visit(JSdoc node) {
- return visit((Comment) node);
- }
- public void endVisit(JSdoc node) {
- endVisit((Comment) node);
- }
-
- public boolean visit(LineComment node) {
- return visit((Comment) node);
- }
- public void endVisit(LineComment node) {
- endVisit((Comment) node);
- }
-
- public boolean visit(ListExpression node) {
- return visit((Expression) node);
- }
-//---- End Comment Hierarchy -----------------------------
-
-public boolean visit(JavaScriptUnit node) {
- return visit((ASTNode) node);
-}
-public void endVisit(JavaScriptUnit node) {
- endVisit((ASTNode) node);
-}
-
-//---- Begin Expression Hierarchy ----------------------------------
-public boolean visit(Expression node) {
- return visit((ASTNode) node);
-}
-public void endVisit(Expression node) {
- endVisit((ASTNode) node);
-}
-
-
-
- public boolean visit(ArrayAccess node) {
- return visit((Expression) node);
- }
- public void endVisit(ArrayAccess node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ArrayCreation node) {
- return visit((Expression) node);
- }
- public void endVisit(ArrayCreation node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ArrayInitializer node) {
- return visit((Expression) node);
- }
- public void endVisit(ArrayInitializer node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(Assignment node) {
- return visit((Expression) node);
- }
- public void endVisit(Assignment node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(BooleanLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(BooleanLiteral node) {
- endVisit((Expression) node);
- }
-
-
- public boolean visit(FunctionExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(FunctionExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ObjectLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(ObjectLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ObjectLiteralField node) {
- return visit((Expression) node);
- }
- public void endVisit(ObjectLiteralField node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(CharacterLiteral node) {
- return visit((Expression) node);
- }
-
- public void endVisit(CharacterLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- return visit((Expression) node);
- }
-
- public void endVisit(RegularExpressionLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ClassInstanceCreation node) {
- return visit((Expression) node);
- }
- public void endVisit(ClassInstanceCreation node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ConditionalExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(ConditionalExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(FieldAccess node) {
- return visit((Expression) node);
- }
- public void endVisit(FieldAccess node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(InfixExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(InfixExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(InstanceofExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(InstanceofExpression node) {
- endVisit((Expression) node);
- }
- public void endVisit(ListExpression node) {
- endVisit((Expression) node);
- }
- public boolean visit(FunctionInvocation node) {
- return visit((Expression) node);
- }
- public void endVisit(FunctionInvocation node) {
- endVisit((Expression) node);
- }
-
- //---- Begin Name Hierarchy ----------------------------------
- public boolean visit(Name node) {
- return visit((Expression) node);
- }
- public void endVisit(Name node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(QualifiedName node) {
- return visit((Name) node);
- }
- public void endVisit(QualifiedName node) {
- endVisit((Name) node);
- }
-
- public boolean visit(SimpleName node) {
- return visit((Name) node);
- }
- public void endVisit(SimpleName node) {
- endVisit((Name) node);
- }
-
- //---- End Name Hierarchy ------------------------------------
-
- public boolean visit(NullLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(NullLiteral node) {
- endVisit((Expression) node);
- }
- public boolean visit(UndefinedLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(UndefinedLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(NumberLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(NumberLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ParenthesizedExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(ParenthesizedExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(PostfixExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(PostfixExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(PrefixExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(PrefixExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(StringLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(StringLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(SuperFieldAccess node) {
- return visit((Expression) node);
- }
- public void endVisit(SuperFieldAccess node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(SuperMethodInvocation node) {
- return visit((Expression) node);
- }
- public void endVisit(SuperMethodInvocation node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(ThisExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(ThisExpression node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(TypeLiteral node) {
- return visit((Expression) node);
- }
- public void endVisit(TypeLiteral node) {
- endVisit((Expression) node);
- }
-
- public boolean visit(VariableDeclarationExpression node) {
- return visit((Expression) node);
- }
- public void endVisit(VariableDeclarationExpression node) {
- endVisit((Expression) node);
- }
-
- //---- End Expression Hierarchy ----------------------------------
-
-public boolean visit(ImportDeclaration node) {
- return visit((ASTNode) node);
-}
-public void endVisit(ImportDeclaration node) {
- endVisit((ASTNode) node);
-}
-
-public boolean visit(MemberRef node) {
- return visit((ASTNode) node);
-}
-public void endVisit(MemberRef node) {
- endVisit((ASTNode) node);
-}
-
-
-public boolean visit(FunctionRef node) {
- return visit((ASTNode) node);
-}
-public void endVisit(FunctionRef node) {
- endVisit((ASTNode) node);
-}
-
-public boolean visit(FunctionRefParameter node) {
- return visit((ASTNode) node);
-}
-public void endVisit(FunctionRefParameter node) {
- endVisit((ASTNode) node);
-}
-
-public boolean visit(Modifier node) {
- return visit((ASTNode) node);
-}
-public void endVisit(Modifier node) {
- endVisit((ASTNode) node);
-}
-
-public boolean visit(PackageDeclaration node) {
- return visit((ASTNode) node);
-}
-public void endVisit(PackageDeclaration node) {
- endVisit((ASTNode) node);
-}
-
-//---- Begin Statement Hierarchy ---------------------------------
-public boolean visit(Statement node) {
- return visit((ASTNode) node);
-}
-public void endVisit(Statement node) {
- endVisit((ASTNode) node);
-}
-
- public boolean visit(Block node) {
- return visit((Statement) node);
- }
- public void endVisit(Block node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(BreakStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(BreakStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ConstructorInvocation node) {
- return visit((Statement) node);
- }
- public void endVisit(ConstructorInvocation node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ContinueStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ContinueStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(DoStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(DoStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(EmptyStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(EmptyStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(EnhancedForStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(EnhancedForStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ExpressionStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ExpressionStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ForStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ForStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ForInStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ForInStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(IfStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(IfStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(LabeledStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(LabeledStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(ReturnStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ReturnStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- return visit((Statement) node);
- }
- public void endVisit(SuperConstructorInvocation node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(SwitchCase node) {
- return visit((Statement) node);
- }
- public void endVisit(SwitchCase node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(SwitchStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(SwitchStatement node) {
- endVisit((Statement) node);
- }
-
-
- public boolean visit(ThrowStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(ThrowStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(TryStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(TryStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(TypeDeclarationStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(VariableDeclarationStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(VariableDeclarationStatement node) {
- endVisit((Statement) node);
- }
-
- public boolean visit(WhileStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(WhileStatement node) {
- endVisit((Statement) node);
- }
-
-
- public boolean visit(WithStatement node) {
- return visit((Statement) node);
- }
- public void endVisit(WithStatement node) {
- endVisit((Statement) node);
- }
-
-//---- End Statement Hierarchy ----------------------------------
-
-public boolean visit(TagElement node) {
- return visit((ASTNode) node);
-}
-public void endVisit(TagElement node) {
- endVisit((ASTNode) node);
-}
-
-public boolean visit(TextElement node) {
- return visit((ASTNode) node);
-}
-public void endVisit(TextElement node) {
- endVisit((ASTNode) node);
-}
-
-
-//---- Begin Type Hierarchy --------------------------------------
-public boolean visit(Type node) {
- return visit((ASTNode) node);
-}
-public void endVisit(Type node) {
- endVisit((ASTNode) node);
-}
-
- public boolean visit(ArrayType node) {
- return visit((Type) node);
- }
- public void endVisit(ArrayType node) {
- endVisit((Type) node);
- }
-
- public boolean visit(PrimitiveType node) {
- return visit((Type) node);
- }
- public void endVisit(PrimitiveType node) {
- endVisit((Type) node);
- }
-
- public boolean visit(QualifiedType node) {
- return visit((Type) node);
- }
- public void endVisit(QualifiedType node) {
- endVisit((Type) node);
- }
-
- public boolean visit(SimpleType node) {
- return visit((Type) node);
- }
- public void endVisit(SimpleType node) {
- endVisit((Type) node);
- }
-
-//---- Begin VariableDeclaration Hierarchy ---------------------------
-public boolean visit(VariableDeclaration node) {
- return visit((ASTNode) node);
-}
-public void endVisit(VariableDeclaration node) {
- endVisit((ASTNode) node);
-}
-
- public boolean visit(SingleVariableDeclaration node) {
- return visit((VariableDeclaration) node);
- }
- public void endVisit(SingleVariableDeclaration node) {
- endVisit((VariableDeclaration) node);
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- return visit((VariableDeclaration) node);
- }
- public void endVisit(VariableDeclarationFragment node) {
- endVisit((VariableDeclaration) node);
- }
-
-//---- End VariableDeclaration Hierarchy -----------------------------
-//---- End ASTNode Hierarchy -----------------------------------------
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/JdtASTMatcher.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/JdtASTMatcher.java
deleted file mode 100644
index 9a4e0fe2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/JdtASTMatcher.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTMatcher;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class JdtASTMatcher extends ASTMatcher {
-
- public boolean match(SimpleName node, Object other) {
- boolean isomorphic= super.match(node, other);
- if (! isomorphic || !(other instanceof SimpleName))
- return false;
- SimpleName name= (SimpleName)other;
- IBinding nodeBinding= node.resolveBinding();
- IBinding otherBinding= name.resolveBinding();
- if (nodeBinding == null) {
- if (otherBinding != null) {
- return false;
- }
- } else {
- if (nodeBinding != otherBinding) {
- return false;
- }
- }
- if (node.resolveTypeBinding() != name.resolveTypeBinding())
- return false;
- return true;
- }
-
- public static boolean doNodesMatch(ASTNode one, ASTNode other) {
- Assert.isNotNull(one);
- Assert.isNotNull(other);
-
- return one.subtreeMatch(new JdtASTMatcher(), other);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LinkedNodeFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LinkedNodeFinder.java
deleted file mode 100644
index 3b7d87a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LinkedNodeFinder.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-
-
-/**
- * Find all nodes connected to a given binding or node. e.g. Declaration of a field and all references.
- * For types this includes also the constructor declaration, for methods also overridden methods
- * or methods overriding (if existing in the same AST)
-
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class LinkedNodeFinder {
-
- private LinkedNodeFinder() {
- }
-
-
- /**
- * Find all nodes connected to the given binding. e.g. Declaration of a field and all references.
- * For types this includes also the constructor declaration, for methods also overridden methods
- * or methods overriding (if existing in the same AST)
- * @param root The root of the AST tree to search
- * @param binding The binding of the searched nodes
- * @return Return
- */
- public static SimpleName[] findByBinding(ASTNode root, IBinding binding) {
- ArrayList res= new ArrayList();
- BindingFinder nodeFinder= new BindingFinder(binding, res);
- root.accept(nodeFinder);
- return (SimpleName[]) res.toArray(new SimpleName[res.size()]);
- }
-
- /**
- * Find all nodes connected to the given name node. If the node has a binding then all nodes connected
- * to this binding are returned. If the node has no binding, then all nodes that also miss a binding and have
- * the same name are returned.
- * @param root The root of the AST tree to search
- * @param name The node to find linked nodes for
- * @return Return
- */
- public static SimpleName[] findByNode(ASTNode root, SimpleName name) {
- IBinding binding = name.resolveBinding();
- if (binding != null) {
- return findByBinding(root, binding);
- }
- SimpleName[] names= findByProblems(root, name);
- if (names != null) {
- return names;
- }
- int parentKind= name.getParent().getNodeType();
- if (parentKind == ASTNode.LABELED_STATEMENT || parentKind == ASTNode.BREAK_STATEMENT || parentKind == ASTNode.CONTINUE_STATEMENT) {
- ArrayList res= new ArrayList();
- LabelFinder nodeFinder= new LabelFinder(name, res);
- root.accept(nodeFinder);
- return (SimpleName[]) res.toArray(new SimpleName[res.size()]);
- }
- return new SimpleName[] { name };
- }
-
-
-
- private static final int FIELD= 1;
- private static final int METHOD= 2;
- private static final int TYPE= 4;
- private static final int LABEL= 8;
- private static final int NAME= FIELD | TYPE;
-
- private static int getProblemKind(IProblem problem) {
- switch (problem.getID()) {
- case IProblem.UndefinedField:
- return FIELD;
- case IProblem.UndefinedMethod:
- case IProblem.UndefinedFunction:
- return METHOD;
- case IProblem.UndefinedLabel:
- return LABEL;
- case IProblem.UndefinedName:
- return NAME;
- case IProblem.UndefinedType:
- return TYPE;
- }
- return 0;
- }
-
- private static int getNameNodeProblemKind(IProblem[] problems, SimpleName nameNode) {
- int nameOffset= nameNode.getStartPosition();
- int nameInclEnd= nameOffset + nameNode.getLength() - 1;
-
- for (int i= 0; i < problems.length; i++) {
- IProblem curr= problems[i];
- if (curr.getSourceStart() == nameOffset && curr.getSourceEnd() == nameInclEnd) {
- int kind= getProblemKind(curr);
- if (kind != 0) {
- return kind;
- }
- }
- }
- return 0;
- }
-
-
- public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
- ArrayList res= new ArrayList();
-
- ASTNode astRoot = parent.getRoot();
- if (!(astRoot instanceof JavaScriptUnit)) {
- return null;
- }
-
- IProblem[] problems= ((JavaScriptUnit) astRoot).getProblems();
- int nameNodeKind= getNameNodeProblemKind(problems, nameNode);
- if (nameNodeKind == 0) { // no problem on node
- return null;
- }
-
- int bodyStart= parent.getStartPosition();
- int bodyEnd= bodyStart + parent.getLength();
-
- String name= nameNode.getIdentifier();
-
- for (int i= 0; i < problems.length; i++) {
- IProblem curr= problems[i];
- int probStart= curr.getSourceStart();
- int probEnd= curr.getSourceEnd() + 1;
-
- if (probStart > bodyStart && probEnd < bodyEnd) {
- int currKind= getProblemKind(curr);
- if ((nameNodeKind & currKind) != 0) {
- ASTNode node= NodeFinder.perform(parent, probStart, probEnd - probStart);
- if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
- res.add(node);
- }
- }
- }
- }
- return (SimpleName[]) res.toArray(new SimpleName[res.size()]);
- }
-
- private static class LabelFinder extends ASTVisitor {
-
- private SimpleName fLabel;
- private ASTNode fDefiningLabel;
- private ArrayList fResult;
-
- public LabelFinder(SimpleName label, ArrayList result) {
- super(true);
- fLabel= label;
- fResult= result;
- fDefiningLabel= null;
- }
-
- private boolean isSameLabel(SimpleName label) {
- return label != null && fLabel.getIdentifier().equals(label.getIdentifier());
- }
-
- public boolean visit(BreakStatement node) {
- SimpleName label= node.getLabel();
- if (fDefiningLabel != null && isSameLabel(label) && ASTNodes.isParent(label, fDefiningLabel)) {
- fResult.add(label);
- }
- return false;
- }
-
- public boolean visit(ContinueStatement node) {
- SimpleName label= node.getLabel();
- if (fDefiningLabel != null && isSameLabel(label) && ASTNodes.isParent(label, fDefiningLabel)) {
- fResult.add(label);
- }
- return false;
- }
-
- public boolean visit(LabeledStatement node) {
- if (fDefiningLabel == null) {
- SimpleName label= node.getLabel();
- if (fLabel == label || isSameLabel(label) && ASTNodes.isParent(fLabel, node)) {
- fDefiningLabel= node;
- fResult.add(label);
- }
- }
- node.getBody().accept(this);
- return false;
- }
- }
-
- private static class BindingFinder extends ASTVisitor {
-
- private IBinding fBinding;
- private ArrayList fResult;
-
- public BindingFinder(IBinding binding, ArrayList result) {
- super(true);
- fBinding= getDeclaration(binding);
- fResult= result;
- }
-
- public boolean visit(FunctionDeclaration node) {
- if (node.isConstructor() && fBinding.getKind() == IBinding.TYPE) {
- ASTNode typeNode= node.getParent();
- if (typeNode instanceof AbstractTypeDeclaration) {
- if (fBinding == ((AbstractTypeDeclaration) typeNode).resolveBinding()) {
- fResult.add(node.getName());
- }
- }
- }
- return true;
- }
-
- public boolean visit(TypeDeclaration node) {
- if (fBinding.getKind() == IBinding.METHOD) {
- IFunctionBinding binding= (IFunctionBinding) fBinding;
- if (binding.isConstructor() && binding.getDeclaringClass() == node.resolveBinding()) {
- fResult.add(node.getName());
- }
- }
- return true;
- }
-
-
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (binding == null || binding.getKind() != fBinding.getKind()) {
- return false;
- }
- binding= getDeclaration(binding);
-
- if (fBinding == binding) {
- fResult.add(node);
- } else if (binding.getKind() == IBinding.METHOD) {
- IFunctionBinding curr= (IFunctionBinding) binding;
- IFunctionBinding methodBinding= (IFunctionBinding) fBinding;
- if (methodBinding.overrides(curr) || curr.overrides(methodBinding)) {
- fResult.add(node);
- }
- }
- return false;
- }
-
- private static IBinding getDeclaration(IBinding binding) {
- if (binding instanceof ITypeBinding) {
- return ((ITypeBinding) binding).getTypeDeclaration();
- } else if (binding instanceof IFunctionBinding) {
- return ((IFunctionBinding) binding).getMethodDeclaration();
- } else if (binding instanceof IVariableBinding) {
- return ((IVariableBinding) binding).getVariableDeclaration();
- }
- return binding;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LocalVariableIndex.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LocalVariableIndex.java
deleted file mode 100644
index 0f2bc135..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/LocalVariableIndex.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class LocalVariableIndex extends ASTVisitor {
-
- private int fTopIndex;
-
- /**
- * Computes the maximum number of local variable declarations in the
- * given body declaration.
- *
- * @param declaration the body declaration. Must either be a method
- * declaration or an initializer.
- * @return the maximum number of local variables
- */
- public static int perform(BodyDeclaration declaration) {
- Assert.isTrue(declaration != null);
- switch (declaration.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- return internalPerform((FunctionDeclaration)declaration);
- case ASTNode.INITIALIZER:
- return internalPerform((Initializer)declaration);
- default:
- Assert.isTrue(false);
- }
- return -1;
- }
-
- private static int internalPerform(FunctionDeclaration method) {
- // we have to find the outermost method declaration since a local or anonymous
- // type can reference final variables from the outer scope.
- FunctionDeclaration target= method;
- while (ASTNodes.getParent(target, ASTNode.FUNCTION_DECLARATION) != null) {
- target= (FunctionDeclaration)ASTNodes.getParent(target, ASTNode.FUNCTION_DECLARATION);
- }
- return doPerform(target);
- }
-
- private static int internalPerform(Initializer initializer) {
- return doPerform(initializer);
- }
-
- private static int doPerform(BodyDeclaration node) {
- LocalVariableIndex counter= new LocalVariableIndex();
- node.accept(counter);
- return counter.fTopIndex;
- }
-
- public boolean visit(SingleVariableDeclaration node) {
- handleVariableBinding(node.resolveBinding());
- return true;
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- handleVariableBinding(node.resolveBinding());
- return true;
- }
-
- private void handleVariableBinding(IVariableBinding binding) {
- if (binding == null)
- return;
- fTopIndex= Math.max(fTopIndex, binding.getVariableId());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ModifierRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ModifierRewrite.java
deleted file mode 100644
index 420e6ff1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ModifierRewrite.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.List;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ModifierRewrite {
-
- public static final int VISIBILITY_MODIFIERS= Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
-
- private ListRewrite fModifierRewrite;
-// private AST fAst;
-
-
- public static ModifierRewrite create(ASTRewrite rewrite, ASTNode declNode) {
- return new ModifierRewrite(rewrite, declNode);
- }
-
- private ModifierRewrite(ASTRewrite rewrite, ASTNode declNode) {
- fModifierRewrite= evaluateListRewrite(rewrite, declNode);
-// fAst= declNode.getAST();
- }
-
- private ListRewrite evaluateListRewrite(ASTRewrite rewrite, ASTNode declNode) {
- switch (declNode.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- return rewrite.getListRewrite(declNode, FunctionDeclaration.MODIFIERS2_PROPERTY);
- case ASTNode.FIELD_DECLARATION:
- return rewrite.getListRewrite(declNode, FieldDeclaration.MODIFIERS2_PROPERTY);
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
- return rewrite.getListRewrite(declNode, VariableDeclarationExpression.MODIFIERS2_PROPERTY);
- case ASTNode.VARIABLE_DECLARATION_STATEMENT:
- return rewrite.getListRewrite(declNode, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- return rewrite.getListRewrite(declNode, SingleVariableDeclaration.MODIFIERS2_PROPERTY);
- case ASTNode.TYPE_DECLARATION:
- return rewrite.getListRewrite(declNode, TypeDeclaration.MODIFIERS2_PROPERTY);
- default:
- throw new IllegalArgumentException("node has no modifiers: " + declNode.getClass().getName()); //$NON-NLS-1$
- }
- }
-
- public ListRewrite getModifierRewrite() {
- return fModifierRewrite;
- }
-
- public void setModifiers(int modfiers, TextEditGroup editGroup) {
- internalSetModifiers(modfiers, -1, editGroup);
- }
-
- public void setModifiers(int included, int excluded, TextEditGroup editGroup) {
- internalSetModifiers(included, included | excluded, editGroup);
- }
-
- public void setVisibility(int visibilityFlags, TextEditGroup editGroup) {
- internalSetModifiers(visibilityFlags, VISIBILITY_MODIFIERS, editGroup);
- }
-
- public void copyAllModifiers(ASTNode otherDecl, TextEditGroup editGroup) {
- ListRewrite modifierList= evaluateListRewrite(fModifierRewrite.getASTRewrite(), otherDecl);
- List originalList= modifierList.getOriginalList();
- if (originalList.isEmpty()) {
- return;
- }
-
- ASTNode copy= modifierList.createCopyTarget((ASTNode) originalList.get(0), (ASTNode) originalList.get(originalList.size() - 1));
- if (copy != null) {
- fModifierRewrite.insertLast(copy, editGroup);
- }
- }
-
- private void internalSetModifiers(int modfiers, int consideredFlags, TextEditGroup editGroup) {
- // remove modifiers
-// int newModifiers= modfiers & consideredFlags;
-
-// List originalList= fModifierRewrite.getOriginalList();
-// for (int i= 0; i < originalList.size(); i++) {
-// ASTNode curr= (ASTNode) originalList.get(i);
-// if (curr instanceof Modifier) {
-// int flag= ((Modifier)curr).getKeyword().toFlagValue();
-// if ((consideredFlags & flag) != 0) {
-// if ((newModifiers & flag) == 0) {
-// fModifierRewrite.remove(curr, editGroup);
-// }
-// newModifiers &= ~flag;
-// }
-// }
-// }
-//
-// // find last annotation
-// IExtendedModifier lastAnnotation= null;
-// List extendedList= fModifierRewrite.getRewrittenList();
-// for (int i= 0; i < extendedList.size(); i++) {
-// IExtendedModifier curr= (IExtendedModifier) extendedList.get(i);
-// if (curr.isAnnotation())
-// lastAnnotation= curr;
-// }
-//
-// // add modifiers
-// List newNodes= ASTNodeFactory.newModifiers(fAst, newModifiers);
-// for (int i= 0; i < newNodes.size(); i++) {
-// Modifier curr= (Modifier) newNodes.get(i);
-// if ((curr.getKeyword().toFlagValue() & VISIBILITY_MODIFIERS) != 0) {
-// if (lastAnnotation != null)
-// fModifierRewrite.insertAfter(curr, (ASTNode) lastAnnotation, editGroup);
-// else
-// fModifierRewrite.insertFirst(curr, editGroup);
-// } else {
-// fModifierRewrite.insertLast(curr, editGroup);
-// }
-// }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/NodeFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/NodeFinder.java
deleted file mode 100644
index e9af9224..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/NodeFinder.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class NodeFinder extends GenericVisitor {
-
- /**
- * A visitor that maps a selection to a given ASTNode. The result node is
- * determined as follows:
- * <ul>
- * <li>first the visitor tries to find a node with the exact start and length</li>
- * <li>if no such node exists than the node that encloses the range defined by
- * start and end is returned.</li>
- * <li>if the length is zero than also nodes are considered where the node's
- * start or end position matches <code>start</code>.</li>
- * <li>otherwise <code>null</code> is returned.</li>
- * </ul>
- *
- * @param root the root node from which the search starts
- * @param start the start offset
- * @param length the length
- *
- * @return the result node
- *
-
- */
- public static ASTNode perform(ASTNode root, int start, int length) {
- NodeFinder finder= new NodeFinder(start, length);
- root.accept(finder);
- ASTNode result= finder.getCoveredNode();
- if (result == null || result.getStartPosition() != start || result.getLength() != length) {
- return finder.getCoveringNode();
- }
- return result;
- }
-
- public static ASTNode perform(ASTNode root, ISourceRange range) {
- return perform(root, range.getOffset(), range.getLength());
- }
-
- /**
- * A visitor that maps a selection to a given ASTNode. The result node is
- * determined as follows:
- * <ul>
- * <li>first the visitor tries to find a node that is covered by <code>start</code> and
- * <code>length</code> where either <code>start</code> and <code>length</code> exactly
- * matches the node or where the text covered before and after the node only consists
- * of white spaces or comments.</li>
- * <li>if no such node exists than the node that encloses the range defined by
- * start and end is returned.</li>
- * <li>if the length is zero than also nodes are considered where the node's
- * start or end position matches <code>start</code>.</li>
- * <li>otherwise <code>null</code> is returned.</li>
- * </ul>
- *
- * @param root the root node from which the search starts
- * @param start the start offset
- * @param length the length
- * @param source the source of the compilation unit
- *
- * @return the result node
- * @throws JavaScriptModelException if an error occurs in the Java model
- *
-
- */
- public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaScriptModelException {
- NodeFinder finder= new NodeFinder(start, length);
- root.accept(finder);
- ASTNode result= finder.getCoveredNode();
- if (result == null)
- return null;
- Selection selection= Selection.createFromStartLength(start, length);
- if (selection.covers(result)) {
- IBuffer buffer= source.getBuffer();
- if (buffer != null) {
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(buffer.getText(start, length).toCharArray());
- try {
- int token= scanner.getNextToken();
- if (token != ITerminalSymbols.TokenNameEOF) {
- int tStart= scanner.getCurrentTokenStartPosition();
- if (tStart == result.getStartPosition() - start) {
- scanner.resetTo(tStart + result.getLength(), length - 1);
- token= scanner.getNextToken();
- if (token == ITerminalSymbols.TokenNameEOF)
- return result;
- }
- }
- } catch (InvalidInputException e) {
- }
- }
- }
- return finder.getCoveringNode();
- }
-
- private int fStart;
- private int fEnd;
-
- private ASTNode fCoveringNode;
- private ASTNode fCoveredNode;
-
- public NodeFinder(int offset, int length) {
- super(true); // include Javadoc tags
- fStart= offset;
- fEnd= offset + length;
- }
-
- protected boolean visitNode(ASTNode node) {
- int nodeStart= node.getStartPosition();
- int nodeEnd= nodeStart + node.getLength();
- if (nodeEnd < fStart || fEnd < nodeStart) {
- return false;
- }
- if (nodeStart <= fStart && fEnd <= nodeEnd) {
- fCoveringNode= node;
- }
- if (fStart <= nodeStart && nodeEnd <= fEnd) {
- if (fCoveringNode == node) { // nodeStart == fStart && nodeEnd == fEnd
- fCoveredNode= node;
- return true; // look further for node with same length as parent
- } else if (fCoveredNode == null) { // no better found
- fCoveredNode= node;
- }
- return false;
- }
- return true;
- }
-
- /**
- * Returns the covered node. If more than one nodes are covered by the selection, the
- * returned node is first covered node found in a top-down traversal of the AST
- * @return ASTNode
- */
- public ASTNode getCoveredNode() {
- return fCoveredNode;
- }
-
- /**
- * Returns the covering node. If more than one nodes are covering the selection, the
- * returned node is last covering node found in a top-down traversal of the AST
- * @return ASTNode
- */
- public ASTNode getCoveringNode() {
- return fCoveringNode;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ReplaceRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ReplaceRewrite.java
deleted file mode 100644
index c7894c5d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ReplaceRewrite.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ReplaceRewrite {
-
- protected ASTRewrite fRewrite;
- protected ASTNode[] fToReplace;
- protected StructuralPropertyDescriptor fDescriptor;
-
- public static ReplaceRewrite create(ASTRewrite rewrite, ASTNode[] nodes) {
- return new ReplaceRewrite(rewrite, nodes);
- }
-
- protected ReplaceRewrite(ASTRewrite rewrite, ASTNode[] nodes) {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(nodes);
- Assert.isTrue(nodes.length > 0);
- fRewrite= rewrite;
- fToReplace= nodes;
- fDescriptor= fToReplace[0].getLocationInParent();
- if (nodes.length > 1) {
- Assert.isTrue(fDescriptor instanceof ChildListPropertyDescriptor);
- }
- }
-
- public void replace(ASTNode[] replacements, TextEditGroup description) {
- if (fToReplace.length == 1) {
- if (replacements.length == 1) {
- handleOneOne(replacements, description);
- } else {
- handleOneMany(replacements, description);
- }
- } else {
- handleManyMany(replacements, description);
- }
- }
-
- protected void handleOneOne(ASTNode[] replacements, TextEditGroup description) {
- fRewrite.replace(fToReplace[0], replacements[0], description);
- }
-
- protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
- handleManyMany(replacements, description);
- }
-
- protected void handleManyMany(ASTNode[] replacements, TextEditGroup description) {
- ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
- if (fToReplace.length == replacements.length) {
- for (int i= 0; i < fToReplace.length; i++) {
- container.replace(fToReplace[i], replacements[i], description);
- }
- } else if (fToReplace.length < replacements.length) {
- for (int i= 0; i < fToReplace.length; i++) {
- container.replace(fToReplace[i], replacements[i], description);
- }
- for (int i= fToReplace.length; i < replacements.length; i++) {
- container.insertAfter(replacements[i], replacements[i - 1], description);
- }
- } else if (fToReplace.length > replacements.length) {
- int delta= fToReplace.length - replacements.length;
- for(int i= 0; i < delta; i++) {
- container.remove(fToReplace[i], description);
- }
- for (int i= delta, r= 0; i < fToReplace.length; i++, r++) {
- container.replace(fToReplace[i], replacements[r], description);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ScopeAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ScopeAnalyzer.java
deleted file mode 100644
index 0b184036..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/ScopeAnalyzer.java
+++ /dev/null
@@ -1,787 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class ScopeAnalyzer {
-
- private static final IBinding[] NO_BINDING= new IBinding[0];
-
- /**
- * Flag to specify that method should be reported.
- */
- public static final int METHODS= 1;
-
- /**
- * Flag to specify that variables should be reported.
- */
- public static final int VARIABLES= 2;
-
- /**
- * Flag to specify that types should be reported.
- */
- public static final int TYPES= 4;
-
- /**
- * Flag to specify that only visible elements should be added.
- */
- public static final int CHECK_VISIBILITY= 16;
-
- private static interface IBindingRequestor {
- boolean acceptBinding(IBinding binding);
- }
-
- private static class DefaultBindingRequestor implements IBindingRequestor {
-
- private final List fResult;
- private final HashSet fNamesAdded;
- private final int fFlags;
- private final ITypeBinding fParentTypeBinding;
-
- public DefaultBindingRequestor(ITypeBinding parentTypeBinding, int flags) {
- fParentTypeBinding= parentTypeBinding;
- fFlags= flags;
- fResult= new ArrayList();
- fNamesAdded= new HashSet();
- }
-
- public DefaultBindingRequestor() {
- this(null, 0);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean acceptBinding(IBinding binding) {
- if (binding == null)
- return false;
-
- String signature= getSignature(binding);
- if (signature != null && fNamesAdded.add(signature)) { // avoid duplicated results from inheritance
- fResult.add(binding);
- }
- return false;
- }
-
- public List getResult() {
- if (hasFlag(CHECK_VISIBILITY, fFlags)) {
- for (int i= fResult.size() - 1; i >= 0; i--) {
- IBinding binding= (IBinding) fResult.get(i);
- if (!isVisible(binding, fParentTypeBinding)) {
- fResult.remove(i);
- }
- }
- }
- return fResult;
- }
-
- }
-
- private HashSet fTypesVisited;
-
- private JavaScriptUnit fRoot;
-
- public ScopeAnalyzer(JavaScriptUnit root) {
- fTypesVisited= new HashSet();
- fRoot= root;
- }
-
- private void clearLists() {
- fTypesVisited.clear();
- }
-
- private static String getSignature(IBinding binding) {
- if (binding != null) {
- switch (binding.getKind()) {
- case IBinding.METHOD:
- StringBuffer buf= new StringBuffer();
- buf.append('M');
- buf.append(binding.getName()).append('(');
- ITypeBinding[] parameters= ((IFunctionBinding) binding).getParameterTypes();
- for (int i= 0; i < parameters.length; i++) {
- if (i > 0) {
- buf.append(',');
- }
- ITypeBinding paramType= parameters[i].getErasure();
- buf.append(paramType.getQualifiedName());
- }
- buf.append(')');
- return buf.toString();
- case IBinding.VARIABLE:
- return 'V' + binding.getName();
- case IBinding.TYPE:
- return 'T' + binding.getName();
- }
- }
- return null;
- }
-
- static final boolean hasFlag(int property, int flags) {
- return (flags & property) != 0;
- }
-
- /**
- * Collects all elements available in a type and its hierarchy
- * @param binding The type binding
- * @param flags Flags defining the elements to report
- * @param requestor the requestor to which all results are reported
- * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required
- */
- private boolean addInherited(ITypeBinding binding, int flags, IBindingRequestor requestor) {
- if (!fTypesVisited.add(binding)) {
- return false;
- }
- if (hasFlag(VARIABLES, flags)) {
- IVariableBinding[] variableBindings= binding.getDeclaredFields();
- for (int i= 0; i < variableBindings.length; i++) {
- if (requestor.acceptBinding(variableBindings[i]))
- return true;
- }
- }
-
- if (hasFlag(METHODS, flags)) {
- IFunctionBinding[] methodBindings= binding.getDeclaredMethods();
- for (int i= 0; i < methodBindings.length; i++) {
- IFunctionBinding curr= methodBindings[i];
- if (!curr.isConstructor()) {
- if (requestor.acceptBinding(curr))
- return true;
- }
- }
- }
-
- if (hasFlag(TYPES, flags)) {
- ITypeBinding[] typeBindings= binding.getDeclaredTypes();
- for (int i= 0; i < typeBindings.length; i++) {
- ITypeBinding curr= typeBindings[i];
- if (requestor.acceptBinding(curr))
- return true;
- }
- }
-
-
- ITypeBinding superClass= binding.getSuperclass();
- if (superClass != null) {
- if (addInherited(superClass, flags, requestor)) // recursive
- return true;
- } else if (binding.isArray()) {
- if (addInherited(fRoot.getAST().resolveWellKnownType("java.lang.Object"), flags, requestor)) //$NON-NLS-1$
- return true;
- }
-
- return false;
- }
-
-
- /**
- * Collects all elements available in a type: its hierarchy and its outer scopes.
- * @param binding The type binding
- * @param flags Flags defining the elements to report
- * @param requestor the requestor to which all results are reported
- * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required
- */
- private boolean addTypeDeclarations(ITypeBinding binding, int flags, IBindingRequestor requestor) {
- if (hasFlag(TYPES, flags) && !binding.isAnonymous()) {
- if (requestor.acceptBinding(binding))
- return true;
- }
-
- addInherited(binding, flags, requestor); // add inherited
-
- if (binding.isLocal()) {
- addOuterDeclarationsForLocalType(binding, flags, requestor);
- } else {
- ITypeBinding declaringClass= binding.getDeclaringClass();
- if (declaringClass != null) {
- if (addTypeDeclarations(declaringClass, flags, requestor)) // Recursively add inherited
- return true;
- } else if (hasFlag(TYPES, flags)) {
- if (fRoot.findDeclaringNode(binding) != null) {
- List types= fRoot.types();
- for (int i= 0; i < types.size(); i++) {
- if (requestor.acceptBinding(((AbstractTypeDeclaration) types.get(i)).resolveBinding()))
- return true;
- }
- }
- }
- }
- return false;
- }
-
- private boolean addOuterDeclarationsForLocalType(ITypeBinding localBinding, int flags, IBindingRequestor requestor) {
- ASTNode node= fRoot.findDeclaringNode(localBinding);
- if (node == null) {
- return false;
- }
-
- if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) {
- if (addLocalDeclarations(node.getParent(), flags, requestor))
- return true;
-
- ITypeBinding parentTypeBinding= Bindings.getBindingOfParentType(node.getParent());
- if (parentTypeBinding != null) {
- if (addTypeDeclarations(parentTypeBinding, flags, requestor))
- return true;
- }
-
- }else if (node instanceof JavaScriptUnit) {
- addLocalDeclarations(node, flags, requestor);
- ITypeBinding parentTypeBinding= Bindings.getBindingOfParentType(node.getParent());
- if (parentTypeBinding != null) {
- if (addTypeDeclarations(parentTypeBinding, flags, requestor))
- return true;
- }
-
- IJavaScriptElement element = ((JavaScriptUnit) node).getJavaElement();
- try {
- SearchableEnvironment env = element.newSearchableNameEnvironment(new IJavaScriptUnit[]{});
- if(env!=null) {
- //SearchRequestor searchReq = new SearchRequestor(localBinding,);
- //env.findTypes(new char[] {}, true, false,flags, );
- }
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- return true;
- }
- return false;
- }
-
- private static ITypeBinding getBinding(Expression node) {
- if (node != null) {
- return node.resolveTypeBinding();
- }
- return null;
- }
-
- private static ITypeBinding getQualifier(SimpleName selector) {
- ASTNode parent= selector.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- FunctionInvocation decl= (FunctionInvocation) parent;
- if (selector == decl.getName()) {
- return getBinding(decl.getExpression());
- }
- return null;
- case ASTNode.QUALIFIED_NAME:
- QualifiedName qualifiedName= (QualifiedName) parent;
- if (selector == qualifiedName.getName()) {
- return getBinding(qualifiedName.getQualifier());
- }
- return null;
- case ASTNode.FIELD_ACCESS:
- FieldAccess fieldAccess= (FieldAccess) parent;
- if (selector == fieldAccess.getName()) {
- return getBinding(fieldAccess.getExpression());
- }
- return null;
- case ASTNode.SUPER_FIELD_ACCESS: {
- ITypeBinding curr= Bindings.getBindingOfParentType(parent);
- return curr.getSuperclass();
- }
- case ASTNode.SUPER_METHOD_INVOCATION: {
- SuperMethodInvocation superInv= (SuperMethodInvocation) parent;
- if (selector == superInv.getName()) {
- ITypeBinding curr= Bindings.getBindingOfParentType(parent);
- return curr.getSuperclass();
- }
- return null;
- }
- default:
- if (parent instanceof Type) {
- // bug 67644: in 'a.new X()', all member types of A are visible as location of X.
- ASTNode normalizedNode= ASTNodes.getNormalizedNode(parent);
- if (normalizedNode.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
- ClassInstanceCreation creation= (ClassInstanceCreation) normalizedNode.getParent();
- return getBinding(creation.getExpression());
- }
- }
- return null;
- }
- }
-
- public IBinding[] getDeclarationsInScope(SimpleName selector, int flags) {
- try {
- // special case for switch on enum
- if (selector.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) {
- ((SwitchStatement) selector.getParent().getParent()).getExpression().resolveTypeBinding();
- }
-
- ITypeBinding parentTypeBinding= Bindings.getBindingOfParentType(selector);
- if (parentTypeBinding != null) {
- ITypeBinding binding= getQualifier(selector);
- DefaultBindingRequestor requestor= new DefaultBindingRequestor(parentTypeBinding, flags);
- if (binding == null) {
- addLocalDeclarations(selector, flags, requestor);
- addTypeDeclarations(parentTypeBinding, flags, requestor);
- } else {
- addInherited(binding, flags, requestor);
- }
-
- List result= requestor.getResult();
- return (IBinding[]) result.toArray(new IBinding[result.size()]);
- }
- return NO_BINDING;
- } finally {
- clearLists();
- }
- }
-
- private static class SearchRequestor implements IBindingRequestor {
-
- private final int fFlags;
- private final ITypeBinding fParentTypeBinding;
- private final IBinding fToSearch;
- private boolean fFound;
- private boolean fIsVisible;
-
- public SearchRequestor(IBinding toSearch, ITypeBinding parentTypeBinding, int flag) {
- fFlags= flag;
- fToSearch= toSearch;
- fParentTypeBinding= parentTypeBinding;
- fFound= false;
- fIsVisible= true;
- }
-
- public boolean acceptBinding(IBinding binding) {
- if (fFound)
- return true;
-
- if (binding == null)
- return false;
-
- if (fToSearch.getKind() != binding.getKind()) {
- return false;
- }
-
- boolean checkVisibility= hasFlag(CHECK_VISIBILITY, fFlags);
- if (binding == fToSearch) {
- fFound= true;
- } else {
- IBinding bindingDeclaration= Bindings.getDeclaration(binding);
- if (bindingDeclaration == fToSearch) {
- fFound= true;
- } else if (bindingDeclaration.getName().equals(fToSearch.getName())) {
- String signature= getSignature(bindingDeclaration);
- if (signature != null && signature.equals(getSignature(fToSearch))) {
- if (checkVisibility) {
- fIsVisible= false;
- }
- return true; // found element that hides the binding to find
- }
- }
- }
-
- if (fFound && checkVisibility) {
- fIsVisible= ScopeAnalyzer.isVisible(binding, fParentTypeBinding);
- }
- return fFound;
- }
-
- public boolean found() {
- return fFound;
- }
-
- public boolean isVisible() {
- return fIsVisible;
- }
- }
-
- public boolean isDeclaredInScope(IBinding declaration, SimpleName selector, int flags) {
- try {
- // special case for switch on enum
- if (selector.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) {
- ((SwitchStatement) selector.getParent().getParent()).getExpression().resolveTypeBinding();
- }
-
- ITypeBinding parentTypeBinding= Bindings.getBindingOfParentTypeContext(selector);
- if (parentTypeBinding != null) {
- ITypeBinding binding= getQualifier(selector);
- SearchRequestor requestor= new SearchRequestor(declaration, parentTypeBinding, flags);
- if (binding == null) {
- addLocalDeclarations(selector, flags, requestor);
- if (requestor.found())
- return requestor.isVisible();
- addTypeDeclarations(parentTypeBinding, flags, requestor);
- if (requestor.found())
- return requestor.isVisible();
- } else {
- addInherited(binding, flags, requestor);
- if (requestor.found())
- return requestor.isVisible();
- }
- }
- return false;
- } finally {
- clearLists();
- }
- }
-
- public IBinding[] getDeclarationsInScope(int offset, int flags) {
- NodeFinder finder= new NodeFinder(offset, 0);
- fRoot.accept(finder);
- ASTNode node= finder.getCoveringNode();
- if (node == null) {
- return NO_BINDING;
- }
-
- if (node instanceof SimpleName) {
- return getDeclarationsInScope((SimpleName) node, flags);
- }
-
- try {
- ITypeBinding binding= Bindings.getBindingOfParentType(node);
- DefaultBindingRequestor requestor= new DefaultBindingRequestor(binding, flags);
- addLocalDeclarations(node, offset, flags, requestor);
- if (binding != null) {
- addTypeDeclarations(binding, flags, requestor);
- }
- List result= requestor.getResult();
- return (IBinding[]) result.toArray(new IBinding[result.size()]);
- } finally {
- clearLists();
- }
- }
-
- private static ITypeBinding getDeclaringType(IBinding binding) {
- switch (binding.getKind()) {
- case IBinding.VARIABLE:
- return ((IVariableBinding) binding).getDeclaringClass();
- case IBinding.METHOD:
- return ((IFunctionBinding) binding).getDeclaringClass();
- case IBinding.TYPE:
- ITypeBinding typeBinding= (ITypeBinding) binding;
- if (typeBinding.getDeclaringClass() != null) {
- return typeBinding;
- }
- return typeBinding;
- }
- return null;
- }
-
- /**
- * Evaluates if the declaration is visible in a certain context.
- * @param binding The binding of the declaration to examine
- * @param context The context to test in
- * @return Returns
- */
- public static boolean isVisible(IBinding binding, ITypeBinding context) {
- if (binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) {
- return true; // all local variables found are visible
- }
- ITypeBinding declaring= getDeclaringType(binding);
- if (declaring == null) {
- return false;
- }
-
- int modifiers= binding.getModifiers();
- if (Modifier.isPublic(modifiers)) {
- return true;
- } else if (Modifier.isProtected(modifiers) || !Modifier.isPrivate(modifiers)) {
- if (declaring.getPackage() == context.getPackage()) {
- return true;
- }
- return isTypeInScope(declaring, context, Modifier.isProtected(modifiers));
- }
- // private visibility
- return isTypeInScope(declaring, context, false);
- }
-
- private static boolean isTypeInScope(ITypeBinding declaring, ITypeBinding context, boolean includeHierarchy) {
- ITypeBinding curr= context;
- while (curr != null && curr != declaring) {
- if (includeHierarchy && Bindings.isSuperType(declaring, curr)) {
- return true;
- }
- curr= curr.getDeclaringClass();
- }
- return curr == declaring;
- }
-
-
- public IBinding[] getDeclarationsAfter(int offset, int flags) {
- try {
- NodeFinder finder= new NodeFinder(offset, 0);
- fRoot.accept(finder);
- ASTNode node= finder.getCoveringNode();
- if (node == null) {
- return null;
- }
-
- ASTNode declaration= ASTResolving.findParentStatement(node);
- while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
- declaration= declaration.getParent();
- }
-
- if (declaration instanceof Block) {
- DefaultBindingRequestor requestor= new DefaultBindingRequestor();
- DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
- declaration.accept(visitor);
- List result= requestor.getResult();
- return (IBinding[])result.toArray(new IBinding[result.size()]);
- }
- return NO_BINDING;
- } finally {
- clearLists();
- }
- }
-
-
- private class ScopeAnalyzerVisitor extends HierarchicalASTVisitor {
-
- private int fPosition;
- private int fFlags;
- private final IBindingRequestor fRequestor;
- private boolean fBreak;
-
- public ScopeAnalyzerVisitor(int position, int flags, IBindingRequestor requestor) {
- fPosition= position;
- fFlags= flags;
- fRequestor= requestor;
- fBreak= false;
- }
-
- private boolean isInside(ASTNode node) {
- int start= node.getStartPosition();
- int end= start + node.getLength();
-
- return start <= fPosition && fPosition < end;
- }
-
- public boolean visit(FunctionDeclaration node) {
- if (isInside(node)) {
- Block body= node.getBody();
- if (body != null) {
- body.accept(this);
- }
- visitBackwards(node.parameters());
- }
- return false;
- }
-
- public boolean visit(SwitchCase node) {
- // switch on enum allows to use enum constants without qualification
- if (hasFlag(VARIABLES, fFlags) && !node.isDefault() && isInside(node.getExpression())) {
- SwitchStatement switchStatement= (SwitchStatement) node.getParent();
- switchStatement.getExpression().resolveTypeBinding();
- }
- return false;
- }
-
- public boolean visit(Initializer node) {
- return !fBreak && isInside(node);
- }
-
- public boolean visit(Statement node) {
- return !fBreak && isInside(node);
- }
-
- public boolean visit(ASTNode node) {
- return false;
- }
-
- public boolean visit(Block node) {
- if (isInside(node)) {
- visitBackwards(node.statements());
- }
- return false;
- }
-
- public boolean visit(VariableDeclaration node) {
- if (hasFlag(VARIABLES, fFlags) && node.getStartPosition() < fPosition) {
- fBreak= fRequestor.acceptBinding(node.resolveBinding());
- }
- return !fBreak;
- }
-
- public boolean visit(VariableDeclarationStatement node) {
- visitBackwards(node.fragments());
- return false;
- }
-
- public boolean visit(VariableDeclarationExpression node) {
- visitBackwards(node.fragments());
- return false;
- }
-
- public boolean visit(CatchClause node) {
- if (isInside(node)) {
- node.getBody().accept(this);
- node.getException().accept(this);
- }
- return false;
- }
-
- public boolean visit(ForStatement node) {
- if (isInside(node)) {
- node.getBody().accept(this);
- visitBackwards(node.initializers());
- }
- return false;
- }
-
- public boolean visit(ForInStatement node) {
- if (isInside(node)) {
- node.getBody().accept(this);
- node.getIterationVariable().accept(this);
- }
- return false;
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- if (hasFlag(TYPES, fFlags) && node.getStartPosition() + node.getLength() < fPosition) {
- if (node.getAST().apiLevel() == AST.JLS2) {
- fBreak= fRequestor.acceptBinding(node.getTypeDeclaration().resolveBinding());
- } else {
- fBreak= fRequestor.acceptBinding(node.getDeclaration().getName().resolveBinding());
- }
- return false;
- }
- return !fBreak && isInside(node);
- }
-
- private void visitBackwards(List list) {
- if (fBreak)
- return;
-
- for (int i= list.size() - 1; i >= 0; i--) {
- ASTNode curr= (ASTNode) list.get(i);
- if (curr.getStartPosition() < fPosition) {
- curr.accept(this);
- }
- }
- }
- }
-
- private class DeclarationsAfterVisitor extends HierarchicalASTVisitor {
- private final int fPosition;
- private final int fFlags;
- private final IBindingRequestor fRequestor;
- private boolean fBreak;
-
- public DeclarationsAfterVisitor(int position, int flags, IBindingRequestor requestor) {
- fPosition= position;
- fFlags= flags;
- fRequestor= requestor;
- fBreak= false;
- }
-
- public boolean visit(ASTNode node) {
- return !fBreak;
- }
-
- public boolean visit(VariableDeclaration node) {
- if (hasFlag(VARIABLES, fFlags) && fPosition < node.getStartPosition()) {
- fBreak= fRequestor.acceptBinding(node.resolveBinding());
- }
- return false;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- return false;
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- if (hasFlag(TYPES, fFlags) && fPosition < node.getStartPosition()) {
- fBreak= fRequestor.acceptBinding(node.resolveBinding());
- }
- return false;
- }
- }
-
- private boolean addLocalDeclarations(ASTNode node, int flags, IBindingRequestor requestor) {
- return addLocalDeclarations(node, node.getStartPosition(), flags, requestor);
- }
-
-
- private boolean addLocalDeclarations(ASTNode node, int offset, int flags, IBindingRequestor requestor) {
- if (hasFlag(VARIABLES, flags) || hasFlag(TYPES, flags)) {
- BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node);
- if (declaration instanceof FunctionDeclaration || declaration instanceof Initializer) {
- ScopeAnalyzerVisitor visitor= new ScopeAnalyzerVisitor(offset, flags, requestor);
- declaration.accept(visitor);
- return visitor.fBreak;
- }
- }
- return false;
- }
-
- public Collection getUsedVariableNames(int offset, int length) {
- HashSet result= new HashSet();
- IBinding[] bindingsBefore= getDeclarationsInScope(offset, VARIABLES);
- for (int i= 0; i < bindingsBefore.length; i++) {
- result.add(bindingsBefore[i].getName());
- }
- IBinding[] bindingsAfter= getDeclarationsAfter(offset + length, VARIABLES);
- for (int i= 0; i < bindingsAfter.length; i++) {
- result.add(bindingsAfter[i].getName());
- }
- List imports= fRoot.imports();
- for (int i= 0; i < imports.size(); i++) {
- ImportDeclaration decl= (ImportDeclaration) imports.get(i);
- if (decl.isStatic() && !decl.isOnDemand()) {
- result.add(ASTNodes.getSimpleNameIdentifier(decl.getName()));
- }
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Selection.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Selection.java
deleted file mode 100644
index 7ec49af1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/Selection.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class Selection {
-
- /** Flag indicating that the AST node somehow intersects with the selection. */
- public static final int INTERSECTS= 0;
-
- /** Flag that indicates that an AST node appears before the selected nodes. */
- public static final int BEFORE= 1;
-
- /** Flag indicating that an AST node is covered by the selection. */
- public static final int SELECTED= 2;
-
- /** Flag indicating that an AST nodes appears after the selected nodes. */
- public static final int AFTER= 3;
-
- private int fStart;
- private int fLength;
- private int fExclusiveEnd;
-
- protected Selection() {
- }
-
- /**
- * Creates a new selection from the given start and length.
- *
- * @param s the start offset of the selection (inclusive)
- * @param l the length of the selection
- * @return the created selection object
- */
- public static Selection createFromStartLength(int s, int l) {
- Assert.isTrue(s >= 0 && l >= 0);
- Selection result= new Selection();
- result.fStart= s;
- result.fLength= l;
- result.fExclusiveEnd= s + l;
- return result;
- }
-
- /**
- * Creates a new selection from the given start and end.
- *
- * @param s the start offset of the selection (inclusive)
- * @param e the end offset of the selection (inclusive)
- * @return the created selection object
- */
- public static Selection createFromStartEnd(int s, int e) {
- Assert.isTrue(s >= 0 && e >= s);
- Selection result= new Selection();
- result.fStart= s;
- result.fLength= e - s + 1;
- result.fExclusiveEnd= result.fStart + result.fLength;
- return result;
- }
-
- public int getOffset() {
- return fStart;
- }
-
- public int getLength() {
- return fLength;
- }
-
- public int getInclusiveEnd() {
- return fExclusiveEnd - 1;
- }
-
- public int getExclusiveEnd() {
- return fExclusiveEnd;
- }
-
- /**
- * Returns the selection mode of the given AST node regarding this selection. Possible
- * values are <code>INTERSECTS</code>, <code>BEFORE</code>, <code>SELECTED</code>, and
- * <code>AFTER</code>.
- *
- * @param node the node to return the visit mode for
- *
- * @return the selection mode of the given AST node regarding this selection
- * @see #INTERSECTS
- * @see #BEFORE
- * @see #SELECTED
- * @see #AFTER
- */
- public int getVisitSelectionMode(ASTNode node) {
- int nodeStart= node.getStartPosition();
- int nodeEnd= nodeStart + node.getLength();
- if (nodeEnd <= fStart)
- return BEFORE;
- else if (covers(node))
- return SELECTED;
- else if (fExclusiveEnd <= nodeStart)
- return AFTER;
- return INTERSECTS;
- }
-
- public int getEndVisitSelectionMode(ASTNode node) {
- int nodeStart= node.getStartPosition();
- int nodeEnd= nodeStart + node.getLength();
- if (nodeEnd <= fStart)
- return BEFORE;
- else if (covers(node))
- return SELECTED;
- else if (nodeEnd >= fExclusiveEnd)
- return AFTER;
- return INTERSECTS;
- }
-
- // cover* methods do a closed interval check.
-
- public boolean covers(int position) {
- return fStart <= position && position < fStart + fLength;
- }
-
- public boolean covers(ASTNode node) {
- int nodeStart= node.getStartPosition();
- return fStart <= nodeStart && nodeStart + node.getLength() <= fExclusiveEnd;
- }
-
- public boolean coveredBy(ASTNode node) {
- int nodeStart= node.getStartPosition();
- return nodeStart <= fStart && fExclusiveEnd <= nodeStart + node.getLength();
- }
-
- public boolean coveredBy(IRegion region) {
- int rangeStart= region.getOffset();
- return rangeStart <= fStart && fExclusiveEnd <= rangeStart + region.getLength();
- }
-
- public boolean endsIn(ASTNode node) {
- int nodeStart= node.getStartPosition();
- return nodeStart < fExclusiveEnd && fExclusiveEnd < nodeStart + node.getLength();
- }
-
- public boolean liesOutside(ASTNode node) {
- int nodeStart= node.getStartPosition();
- int nodeEnd= nodeStart + node.getLength();
- boolean nodeBeforeSelection= nodeEnd < fStart;
- boolean selectionBeforeNode= fExclusiveEnd < nodeStart;
- return nodeBeforeSelection || selectionBeforeNode;
- }
-
- public String toString() {
- return "<start == " + fStart + ", length == " + fLength + "/>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/SelectionAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/SelectionAnalyzer.java
deleted file mode 100644
index b88c2fc7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/SelectionAnalyzer.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class SelectionAnalyzer extends GenericVisitor {
-
- private Selection fSelection;
- private boolean fTraverseSelectedNode;
- private ASTNode fLastCoveringNode;
-
- // Selected nodes
- private List fSelectedNodes;
-
- public SelectionAnalyzer(Selection selection, boolean traverseSelectedNode) {
- super(true);
- Assert.isNotNull(selection);
- fSelection= selection;
- fTraverseSelectedNode= traverseSelectedNode;
- }
-
- public boolean hasSelectedNodes() {
- return fSelectedNodes != null && !fSelectedNodes.isEmpty();
- }
-
- public ASTNode[] getSelectedNodes() {
- if (fSelectedNodes == null || fSelectedNodes.isEmpty())
- return new ASTNode[0];
- return (ASTNode[]) fSelectedNodes.toArray(new ASTNode[fSelectedNodes.size()]);
- }
-
- public ASTNode getFirstSelectedNode() {
- if (fSelectedNodes == null || fSelectedNodes.isEmpty())
- return null;
- return (ASTNode)fSelectedNodes.get(0);
- }
-
- public ASTNode getLastSelectedNode() {
- if (fSelectedNodes == null || fSelectedNodes.isEmpty())
- return null;
- return (ASTNode)fSelectedNodes.get(fSelectedNodes.size() - 1);
- }
-
- public boolean isExpressionSelected() {
- if (!hasSelectedNodes())
- return false;
- return fSelectedNodes.get(0) instanceof Expression;
- }
-
- public IRegion getSelectedNodeRange() {
- if (fSelectedNodes == null || fSelectedNodes.isEmpty())
- return null;
- ASTNode firstNode= (ASTNode)fSelectedNodes.get(0);
- ASTNode lastNode= (ASTNode)fSelectedNodes.get(fSelectedNodes.size() - 1);
- int start= firstNode.getStartPosition();
- return new Region(start, lastNode.getStartPosition() + lastNode.getLength() - start);
- }
-
- public ASTNode getLastCoveringNode() {
- return fLastCoveringNode;
- }
-
- protected Selection getSelection() {
- return fSelection;
- }
-
- //--- node management ---------------------------------------------------------
-
- protected boolean visitNode(ASTNode node) {
- // The selection lies behind the node.
- if (fSelection.liesOutside(node)) {
- return false;
- } else if (fSelection.covers(node)) {
- if (isFirstNode()) {
- handleFirstSelectedNode(node);
- } else {
- handleNextSelectedNode(node);
- }
- return fTraverseSelectedNode;
- } else if (fSelection.coveredBy(node)) {
- fLastCoveringNode= node;
- return true;
- } else if (fSelection.endsIn(node)) {
- return handleSelectionEndsIn(node);
- }
- // There is a possibility that the user has selected trailing semicolons that don't belong
- // to the statement. So dive into it to check if sub nodes are fully covered.
- return true;
- }
-
- protected void reset() {
- fSelectedNodes= null;
- }
-
- protected void handleFirstSelectedNode(ASTNode node) {
- fSelectedNodes= new ArrayList(5);
- fSelectedNodes.add(node);
- }
-
- protected void handleNextSelectedNode(ASTNode node) {
- if (getFirstSelectedNode().getParent() == node.getParent()) {
- fSelectedNodes.add(node);
- }
- }
-
- protected boolean handleSelectionEndsIn(ASTNode node) {
- return false;
- }
-
- protected List internalGetSelectedNodes() {
- return fSelectedNodes;
- }
-
- private boolean isFirstNode() {
- return fSelectedNodes == null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/StatementRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/StatementRewrite.java
deleted file mode 100644
index 1f167b41..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/StatementRewrite.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class StatementRewrite extends ReplaceRewrite {
-
- public StatementRewrite(ASTRewrite rewrite, ASTNode[] nodes) {
- super(rewrite, nodes);
- }
-
- protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
- AST ast= fToReplace[0].getAST();
- // to replace == 1, but more than one replacement. Have to check if we
- // need to insert a block to not change structure
- if (ASTNodes.isControlStatementBody(fDescriptor)) {
- Block block= ast.newBlock();
- ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- for (int i= 0; i < replacements.length; i++) {
- statements.insertLast(replacements[i], description);
- }
- fRewrite.replace(fToReplace[0], block, description);
- } else {
- ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
- container.replace(fToReplace[0], replacements[0], description);
- for (int i= 1; i < replacements.length; i++) {
- container.insertAfter(replacements[i], replacements[i - 1], description);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TokenScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TokenScanner.java
deleted file mode 100644
index e4eff575..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TokenScanner.java
+++ /dev/null
@@ -1,450 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class TokenScanner {
-
- public static final int END_OF_FILE= 20001;
- public static final int LEXICAL_ERROR= 20002;
- public static final int DOCUMENT_ERROR= 20003;
-
- private IScanner fScanner;
- private IDocument fDocument;
- private int fEndPosition;
-
- /**
- * Creates a TokenScanner
- * @param scanner The scanner to be wrapped. The scanner has to support line information
- * if the comment position methods are used.
- */
- public TokenScanner(IScanner scanner) {
- this(scanner, null);
- }
-
- /**
- * Creates a TokenScanner
- * @param scanner The scanner to be wrapped
- * @param document The document used for line information if specified
- */
- public TokenScanner(IScanner scanner, IDocument document) {
- fScanner= scanner;
- fEndPosition= fScanner.getSource().length - 1;
- fDocument= document;
- }
-
- /**
- * Creates a TokenScanner
- * @param document The textbuffer to create the scanner on
- */
- public TokenScanner(IDocument document, IJavaScriptProject project) {
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- fScanner= ToolFactory.createScanner(true, false, false, sourceLevel, complianceLevel); // no line info required
- fScanner.setSource(document.get().toCharArray());
- fDocument= document;
- fEndPosition= fScanner.getSource().length - 1;
- }
-
- /**
- * Creates a TokenScanner
- * @param cu The compliation unit to can on
- * @throws JavaScriptModelException thorwn if the buffer cannot be accessed
- */
- public TokenScanner(IJavaScriptUnit cu) throws JavaScriptModelException {
- IJavaScriptProject project= cu.getJavaScriptProject();
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- fScanner= ToolFactory.createScanner(true, false, true, sourceLevel, complianceLevel); // line info required
- fScanner.setSource(cu.getBuffer().getCharacters());
- fDocument= null; // use scanner for line information
- fEndPosition= fScanner.getSource().length - 1;
- }
-
- /**
- * Returns the wrapped scanner
- * @return IScanner
- */
- public IScanner getScanner() {
- return fScanner;
- }
-
- /**
- * Sets the scanner offset to the given offset.
- * @param offset The offset to set
- */
- public void setOffset(int offset) {
- fScanner.resetTo(offset, fEndPosition);
- }
-
- /**
- * @return Returns the offset after the current token
- */
- public int getCurrentEndOffset() {
- return fScanner.getCurrentTokenEndPosition() + 1;
- }
-
- /**
- * @return Returns the start offset of the current token
- */
- public int getCurrentStartOffset() {
- return fScanner.getCurrentTokenStartPosition();
- }
-
- /**
- * @return Returns the length of the current token
- */
- public int getCurrentLength() {
- return getCurrentEndOffset() - getCurrentStartOffset();
- }
-
- /**
- * Reads the next token.
- * @param ignoreComments If set, comments will be overread
- * @return Return the token id.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int readNext(boolean ignoreComments) throws CoreException {
- int curr= 0;
- do {
- try {
- curr= fScanner.getNextToken();
- if (curr == ITerminalSymbols.TokenNameEOF) {
- throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$
- }
- } catch (InvalidInputException e) {
- throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e));
- }
- } while (ignoreComments && isComment(curr));
- return curr;
- }
-
- /**
- * Reads the next token.
- * @param ignoreComments If set, comments will be overread.
- * @return Return the token id.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- private int readNextWithEOF(boolean ignoreComments) throws CoreException {
- int curr= 0;
- do {
- try {
- curr= fScanner.getNextToken();
- } catch (InvalidInputException e) {
- throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e));
- }
- } while (ignoreComments && isComment(curr));
- return curr;
- }
-
- /**
- * Reads the next token from the given offset.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread.
- * @return Returns the token id.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int readNext(int offset, boolean ignoreComments) throws CoreException {
- setOffset(offset);
- return readNext(ignoreComments);
- }
-
- /**
- * Reads the next token from the given offset and returns the start offset of the token.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread
- * @return Returns the start position of the next token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getNextStartOffset(int offset, boolean ignoreComments) throws CoreException {
- readNext(offset, ignoreComments);
- return getCurrentStartOffset();
- }
-
- /**
- * Reads the next token from the given offset and returns the offset after the token.
- * @param offset The offset to start reading from.
- * @param ignoreComments If set, comments will be overread
- * @return Returns the start position of the next token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getNextEndOffset(int offset, boolean ignoreComments) throws CoreException {
- readNext(offset, ignoreComments);
- return getCurrentEndOffset();
- }
-
- /**
- * Reads until a token is reached.
- * @param tok The token to read to.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public void readToToken(int tok) throws CoreException {
- int curr= 0;
- do {
- curr= readNext(false);
- } while (curr != tok);
- }
-
- /**
- * Reads until a token is reached, starting from the given offset.
- * @param tok The token to read to.
- * @param offset The offset to start reading from.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public void readToToken(int tok, int offset) throws CoreException {
- setOffset(offset);
- readToToken(tok);
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the start offset of the token.
- * @param token The token to be found.
- * @param startOffset The offset to start reading from.
- * @return Returns the start position of the found token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenStartOffset(int token, int startOffset) throws CoreException {
- readToToken(token, startOffset);
- return getCurrentStartOffset();
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the offset after the token.
- * @param token The token to be found.
- * @param startOffset Offset to start reading from
- * @return Returns the end position of the found token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenEndOffset(int token, int startOffset) throws CoreException {
- readToToken(token, startOffset);
- return getCurrentEndOffset();
- }
-
- /**
- * Reads from the given offset until a token is reached and returns the offset after the previous token.
- * @param token The token to be found.
- * @param startOffset The offset to start scanning from.
- * @return Returns the end offset of the token previous to the given token.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getPreviousTokenEndOffset(int token, int startOffset) throws CoreException {
- setOffset(startOffset);
- int res= startOffset;
- int curr= readNext(false);
- while (curr != token) {
- res= getCurrentEndOffset();
- curr= readNext(false);
- }
- return res;
- }
-
- /**
- * Evaluates the start offset of comments directly ahead of a token specified by its start offset
- *
- * @param lastPos An offset to before the node start offset. Can be 0 but better is the end location of the previous node.
- * @param nodeStart Start offset of the node to find the comments for.
- * @return Returns the start offset of comments directly ahead of a token.
- * @exception CoreException Thrown when a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenCommentStart(int lastPos, int nodeStart) throws CoreException {
- setOffset(lastPos);
-
- int prevEndPos= lastPos;
- int prevEndLine= prevEndPos > 0 ? getLineOfOffset(prevEndPos - 1) : 0;
- int nodeLine= getLineOfOffset(nodeStart);
-
- int res= -1;
-
- int curr= readNextWithEOF(false);
- int currStartPos= getCurrentStartOffset();
- int currStartLine= getLineOfOffset(currStartPos);
- while (curr != ITerminalSymbols.TokenNameEOF && nodeStart > currStartPos) {
- if (TokenScanner.isComment(curr)) {
- int linesDifference= currStartLine - prevEndLine;
- if ((linesDifference > 1) || (res == -1 && (linesDifference != 0 || nodeLine == currStartLine))) {
- res= currStartPos; // begin new
- }
- } else {
- res= -1;
- }
-
- if (curr == ITerminalSymbols.TokenNameCOMMENT_LINE) {
- prevEndLine= currStartLine;
- } else {
- prevEndLine= getLineOfOffset(getCurrentEndOffset() - 1);
- }
- curr= readNextWithEOF(false);
- currStartPos= getCurrentStartOffset();
- currStartLine= getLineOfOffset(currStartPos);
- }
- if (res == -1 || curr == ITerminalSymbols.TokenNameEOF) {
- return nodeStart;
- }
- if (currStartLine - prevEndLine > 1) {
- return nodeStart;
- }
- return res;
- }
-
- /**
- * Looks for comments after a node and returns the end position of the comment still belonging to the node.
- * @param nodeEnd The end position of the node
- * @param nextTokenStart The start positoion of the next node. Optional, can be -1
- * the line information shoould be taken from the scanner object
- * @return Returns returns the end position of the comment still belonging to the node.
- * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE)
- * or a lexical error was detected while scanning (code LEXICAL_ERROR)
- */
- public int getTokenCommentEnd(int nodeEnd, int nextTokenStart) throws CoreException {
- // assign comments to the previous comments as long they are all on the same line as the
- // node end position or if they are on the next line but there is a separation from the next
- // node
- // } //aa
- // // aa
- //
- // // bb
- // public void b...
- //
- // } /* cc */ /*
- // cc/*
- // /*dd*/
- // public void d...
-
- int prevEndLine= getLineOfOffset(nodeEnd - 1);
- int prevEndPos= nodeEnd;
- int res= nodeEnd;
- boolean sameLineComment= true;
-
- setOffset(nodeEnd);
-
-
- int curr= readNextWithEOF(false);
- while (curr == ITerminalSymbols.TokenNameCOMMENT_LINE || curr == ITerminalSymbols.TokenNameCOMMENT_BLOCK) {
- int currStartLine= getLineOfOffset(getCurrentStartOffset());
- int linesDifference= currStartLine - prevEndLine;
-
- if (linesDifference > 1) {
- return prevEndPos; // separated comments
- }
-
- if (curr == ITerminalSymbols.TokenNameCOMMENT_LINE) {
- prevEndPos= getLineEnd(currStartLine);
- prevEndLine= currStartLine;
- } else {
- prevEndPos= getCurrentEndOffset();
- prevEndLine= getLineOfOffset(prevEndPos - 1);
- }
- if (sameLineComment) {
- if (linesDifference == 0) {
- res= prevEndPos;
- } else {
- sameLineComment= false;
- }
- }
- curr= readNextWithEOF(false);
- }
- if (curr == ITerminalSymbols.TokenNameEOF) {
- return prevEndPos;
- }
- int currStartLine= getLineOfOffset(getCurrentStartOffset());
- int linesDifference= currStartLine - prevEndLine;
- if (linesDifference > 1) {
- return prevEndPos; // separated comments
- }
- return res;
- }
-
- public int getLineOfOffset(int offset) throws CoreException {
- if (fDocument != null) {
- try {
- return fDocument.getLineOfOffset(offset);
- } catch (BadLocationException e) {
- String message= "Illegal offset: " + offset; //$NON-NLS-1$
- throw new CoreException(createError(DOCUMENT_ERROR, message, e));
- }
- }
- return getScanner().getLineNumber(offset);
- }
-
- public int getLineEnd(int line) throws CoreException {
- if (fDocument != null) {
- try {
- IRegion region= fDocument.getLineInformation(line);
- return region.getOffset() + region.getLength();
- } catch (BadLocationException e) {
- String message= "Illegal line: " + line; //$NON-NLS-1$
- throw new CoreException(createError(DOCUMENT_ERROR, message, e));
- }
- }
- return getScanner().getLineEnd(line);
- }
-
- public static boolean isComment(int token) {
- return token == ITerminalSymbols.TokenNameCOMMENT_BLOCK || token == ITerminalSymbols.TokenNameCOMMENT_JAVADOC
- || token == ITerminalSymbols.TokenNameCOMMENT_LINE;
- }
-
- public static boolean isModifier(int token) {
- switch (token) {
- case ITerminalSymbols.TokenNamepublic:
- case ITerminalSymbols.TokenNameprotected:
- case ITerminalSymbols.TokenNameprivate:
- case ITerminalSymbols.TokenNamestatic:
- case ITerminalSymbols.TokenNamefinal:
- case ITerminalSymbols.TokenNameabstract:
- case ITerminalSymbols.TokenNamenative:
- case ITerminalSymbols.TokenNamevolatile:
- case ITerminalSymbols.TokenNamestrictfp:
- case ITerminalSymbols.TokenNametransient:
- case ITerminalSymbols.TokenNamesynchronized:
- return true;
- default:
- return false;
- }
- }
-
- private IStatus createError(int code, String message, Throwable e) {
- return JavaUIStatus.createError(DOCUMENT_ERROR, message, e);
- // return new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, code, message, throwable);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeBindingVisitor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeBindingVisitor.java
deleted file mode 100644
index 6d9ed6dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeBindingVisitor.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface TypeBindingVisitor {
-
- public boolean visit(ITypeBinding node);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeRules.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeRules.java
deleted file mode 100644
index 1e34a67b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/TypeRules.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType.Code;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class TypeRules {
-
- /**
- * Tests if a two primitive types are assign compatible
- * @param toAssignCode The binding of the type to assign
- * @param definedTypeCode The type of the object that is assigned
- * @return boolean Returns true if definedType = typeToAssign is true
- */
- public static boolean canAssignPrimitive(PrimitiveType.Code toAssignCode, PrimitiveType.Code definedTypeCode) {
- // definedTypeCode = typeCodeToAssign;
- if (toAssignCode == definedTypeCode) {
- return true;
- }
- if (definedTypeCode == PrimitiveType.BOOLEAN || toAssignCode == PrimitiveType.BOOLEAN) {
- return false;
- }
- if (definedTypeCode == PrimitiveType.CHAR && toAssignCode == PrimitiveType.BYTE) {
- return false;
- }
- return getTypeOrder(definedTypeCode) > getTypeOrder(toAssignCode);
- }
-
- /**
- * Tests if two types are assign compatible. Void types are never compatible.
- * @param typeToAssign The binding of the type to assign
- * @param definedType The type of the object that is assigned
- * @return boolean Returns true if definedType = typeToAssign is true
- */
- public static boolean canAssign(ITypeBinding typeToAssign, ITypeBinding definedType) {
- //see bug 80715
-
- // definedType = typeToAssign;
-
- String voidName= PrimitiveType.VOID.toString();
- if (voidName.equals(typeToAssign.getName()) || voidName.equals(definedType.getName())) {
- return false;
- }
-
- if (typeToAssign.isNullType()) {
- return !definedType.isPrimitive();
- }
- if (definedType.isArray()) {
- if (!typeToAssign.isArray()) {
- return false; // can not assign a non-array type to an array
- }
- int definedDim= definedType.getDimensions();
- int toAssignDim= typeToAssign.getDimensions();
- if (definedDim == toAssignDim) {
- definedType= definedType.getElementType();
- typeToAssign= typeToAssign.getElementType();
- if (typeToAssign.isPrimitive() && typeToAssign != definedType) {
- return false; // can't assign arrays of different primitive types to each other
- }
- // fall through
- } else if (definedDim < toAssignDim) {
- return isArrayCompatible(definedType.getElementType());
- } else {
- return false;
- }
- }
-
- if (typeToAssign.isPrimitive()) {
- if (!definedType.isPrimitive()) {
- return false;
- }
- PrimitiveType.Code toAssignCode= PrimitiveType.toCode(typeToAssign.getName());
- PrimitiveType.Code definedTypeCode= PrimitiveType.toCode(definedType.getName());
- return canAssignPrimitive(toAssignCode, definedTypeCode);
- } else {
- if (definedType.isPrimitive()) {
- return false;
- }
-
- if (typeToAssign.isArray()) {
- return isArrayCompatible(definedType);
- }
- if (isJavaLangObject(definedType)) {
- return true;
- }
- return Bindings.isSuperType(definedType, typeToAssign);
- }
- }
-
- private static int getTypeOrder(Code type) {
- if (type == PrimitiveType.BYTE)
- return 2;
- if (type == PrimitiveType.CHAR)
- return 3;
- if (type == PrimitiveType.SHORT)
- return 3;
- if (type == PrimitiveType.INT)
- return 4;
- if (type == PrimitiveType.LONG)
- return 5;
- if (type == PrimitiveType.FLOAT)
- return 6;
- if (type == PrimitiveType.DOUBLE)
- return 7;
- return 0;
- }
-
- public static boolean isArrayCompatible(ITypeBinding definedType) {
- if (definedType.isTopLevel()) {
- if (definedType.isClass()) {
- return "Object".equals(definedType.getName()) && "java.lang".equals(definedType.getPackage().getName()); //$NON-NLS-1$//$NON-NLS-2$
- } else {
- String qualifiedName= definedType.getQualifiedName();
- return "java.io.Serializable".equals(qualifiedName) || "java.lang.Cloneable".equals(qualifiedName); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- return false;
- }
-
- public static boolean isJavaLangObject(ITypeBinding definedType) {
- return definedType.isTopLevel() && definedType.isClass() && "Object".equals(definedType.getName()) && "java.lang".equals(definedType.getPackage().getName()); //$NON-NLS-1$//$NON-NLS-2$
- }
-
- /**
- * Tests if a two types are cast compatible
- * @param castType The binding of the type to cast to
- * @param bindingToCast The binding ef the expression to cast.
- * @return boolean Returns true if (castType) bindingToCast is a valid cast expression (can be unnecessary, but not invalid).
- */
- public static boolean canCast(ITypeBinding castType, ITypeBinding bindingToCast) {
- //see bug 80715
-
- String voidName= PrimitiveType.VOID.toString();
-
- if (castType.isAnonymous() || castType.isNullType() || voidName.equals(castType.getName())) {
- throw new IllegalArgumentException();
- }
-
- if (castType == bindingToCast) {
- return true;
- }
-
- if (voidName.equals(bindingToCast.getName())) {
- return false;
- }
-
- if (bindingToCast.isArray()) {
- if (!castType.isArray()) {
- return isArrayCompatible(castType); // can not cast an arraytype to a non array type (except to Object, Serializable...)
- }
-
- int toCastDim= bindingToCast.getDimensions();
- int castTypeDim= castType.getDimensions();
- if (toCastDim == castTypeDim) {
- bindingToCast= bindingToCast.getElementType();
- castType= castType.getElementType();
- if (castType.isPrimitive() && castType != bindingToCast) {
- return false; // can't assign arrays of different primitive types to each other
- }
- // fall through
- } else if (toCastDim < castTypeDim) {
- return isArrayCompatible(bindingToCast.getElementType());
- } else {
- return isArrayCompatible(castType.getElementType());
- }
- }
- if (castType.isPrimitive()) {
- if (!bindingToCast.isPrimitive()) {
- return false;
- }
- String boolName= PrimitiveType.BOOLEAN.toString();
- return (!boolName.equals(castType.getName()) && !boolName.equals(bindingToCast.getName()));
- } else {
- if (bindingToCast.isPrimitive()) {
- return false;
- }
- if (castType.isArray()) {
- return isArrayCompatible(bindingToCast);
- }
- if (isJavaLangObject(castType)) {
- return true;
- }
-
- return Bindings.isSuperType(bindingToCast, castType) || Bindings.isSuperType(castType, bindingToCast);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/VariableDeclarationRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/VariableDeclarationRewrite.java
deleted file mode 100644
index d53c01d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/VariableDeclarationRewrite.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class VariableDeclarationRewrite {
-
- public static void rewriteModifiers(final SingleVariableDeclaration declarationNode, final int includedModifiers, final int excludedModifiers, final ASTRewrite rewrite, final TextEditGroup group) {
- ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declarationNode);
- listRewrite.setModifiers(includedModifiers, excludedModifiers, group);
- }
-
- public static void rewriteModifiers(final VariableDeclarationExpression declarationNode, final int includedModifiers, final int excludedModifiers, final ASTRewrite rewrite, final TextEditGroup group) {
- ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declarationNode);
- listRewrite.setModifiers(includedModifiers, excludedModifiers, group);
- }
-
- public static void rewriteModifiers(final FieldDeclaration declarationNode, final VariableDeclarationFragment[] toChange, final int includedModifiers, final int excludedModifiers, final ASTRewrite rewrite, final TextEditGroup group) {
- final List fragmentsToChange= Arrays.asList(toChange);
- AST ast= declarationNode.getAST();
-
- List fragments= declarationNode.fragments();
- Iterator iter= fragments.iterator();
-
- ListRewrite blockRewrite;
- if (declarationNode.getParent() instanceof AbstractTypeDeclaration) {
- blockRewrite= rewrite.getListRewrite(declarationNode.getParent(), ((AbstractTypeDeclaration)declarationNode.getParent()).getBodyDeclarationsProperty());
- } else {
- blockRewrite= rewrite.getListRewrite(declarationNode.getParent(), AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- }
-
- VariableDeclarationFragment lastFragment= (VariableDeclarationFragment)iter.next();
- ASTNode lastStatement= declarationNode;
-
- int orginalModifiers= declarationNode.getModifiers();
- if (fragmentsToChange.contains(lastFragment)) {
- ListRewrite modifierRewrite= rewrite.getListRewrite(declarationNode, FieldDeclaration.MODIFIERS2_PROPERTY);
- for (Iterator iterator= declarationNode.modifiers().iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- modifierRewrite.remove(node, group);
- }
- List newModifiers= ast.newModifiers((orginalModifiers & ~excludedModifiers) | includedModifiers);
- for (Iterator iterator= newModifiers.iterator(); iterator.hasNext();) {
- modifierRewrite.insertLast((ASTNode)iterator.next(), group);
- }
- }
-
- ListRewrite fragmentsRewrite= null;
- while (iter.hasNext()) {
- VariableDeclarationFragment currentFragment= (VariableDeclarationFragment)iter.next();
-
- if (fragmentsToChange.contains(lastFragment) != fragmentsToChange.contains(currentFragment)) {
-
- FieldDeclaration newStatement= ast.newFieldDeclaration((VariableDeclarationFragment)rewrite.createMoveTarget(currentFragment));
- newStatement.setType((Type)rewrite.createCopyTarget(declarationNode.getType()));
- if (fragmentsToChange.contains(currentFragment)) {
- newStatement.modifiers().addAll(ast.newModifiers((orginalModifiers & ~excludedModifiers) | includedModifiers));
- } else {
- newStatement.modifiers().addAll(ast.newModifiers(orginalModifiers));
- }
- blockRewrite.insertAfter(newStatement, lastStatement, group);
-
- fragmentsRewrite= rewrite.getListRewrite(newStatement, FieldDeclaration.FRAGMENTS_PROPERTY);
- lastStatement= newStatement;
- } else if (fragmentsRewrite != null) {
- ASTNode fragment0= rewrite.createMoveTarget(currentFragment);
- fragmentsRewrite.insertLast(fragment0, group);
- }
- lastFragment= currentFragment;
- }
- }
-
- public static void rewriteModifiers(final VariableDeclarationStatement declarationNode, final VariableDeclarationFragment[] toChange, final int includedModifiers, final int excludedModifiers, ASTRewrite rewrite, final TextEditGroup group) {
- final List fragmentsToChange= Arrays.asList(toChange);
- AST ast= declarationNode.getAST();
-
- List fragments= declarationNode.fragments();
- Iterator iter= fragments.iterator();
-
- ListRewrite blockRewrite= rewrite.getListRewrite(declarationNode.getParent(), Block.STATEMENTS_PROPERTY);
-
- VariableDeclarationFragment lastFragment= (VariableDeclarationFragment)iter.next();
- ASTNode lastStatement= declarationNode;
-
- int orginalModifiers= declarationNode.getModifiers();
- if (fragmentsToChange.contains(lastFragment)) {
- ListRewrite modifierRewrite= rewrite.getListRewrite(declarationNode, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
- for (Iterator iterator= declarationNode.modifiers().iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- modifierRewrite.remove(node, group);
- }
- List newModifiers= ast.newModifiers((orginalModifiers & ~excludedModifiers) | includedModifiers);
- for (Iterator iterator= newModifiers.iterator(); iterator.hasNext();) {
- modifierRewrite.insertLast((ASTNode)iterator.next(), group);
- }
- }
-
- ListRewrite fragmentsRewrite= null;
- while (iter.hasNext()) {
- VariableDeclarationFragment currentFragment= (VariableDeclarationFragment)iter.next();
-
- if (fragmentsToChange.contains(lastFragment) != fragmentsToChange.contains(currentFragment)) {
-
- VariableDeclarationStatement newStatement= ast.newVariableDeclarationStatement((VariableDeclarationFragment)rewrite.createMoveTarget(currentFragment));
- newStatement.setType((Type)rewrite.createCopyTarget(declarationNode.getType()));
- if (fragmentsToChange.contains(currentFragment)) {
- newStatement.modifiers().addAll(ast.newModifiers((orginalModifiers & ~excludedModifiers) | includedModifiers));
- } else {
- newStatement.modifiers().addAll(ast.newModifiers(orginalModifiers));
- }
- blockRewrite.insertAfter(newStatement, lastStatement, group);
-
- fragmentsRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.FRAGMENTS_PROPERTY);
- lastStatement= newStatement;
- } else if (fragmentsRewrite != null) {
- ASTNode fragment0= rewrite.createMoveTarget(currentFragment);
- fragmentsRewrite.insertLast(fragment0, group);
- }
- lastFragment= currentFragment;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragment.java
deleted file mode 100644
index 1c4eb44f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragment.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-
-/**
- * @see org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment
- * @see org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory
- */
-abstract class ASTFragment implements IASTFragment {
-
- /**
- * Tries to create or find as many fragments as possible
- * such that each fragment f matches
- * this fragment and f.getNode() is <code>node</code>
- */
- abstract IASTFragment[] getMatchingFragmentsWithNode(ASTNode node);
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragmentFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragmentFactory.java
deleted file mode 100644
index 05408050..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragmentFactory.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-
-/**
- * Creates various differing kinds of IASTFragments, all through
- * a very narrow interface. The kind of IASTFragment produced will depend
- * on properties of the parameters supplied to the factory methods, such
- * as the types and characteristics of AST nodes, or the location of
- * source ranges.
- *
- * In general, the client will not be aware of exactly what kind of
- * fragment is obtained from these methods. Beyond the functionality
- * provided by the IASTFragment interface, the client can know, however,
- * based on the parameters passed, some things about the created fragment.
- * See the documentation of the factory methods.
- *
- * @see IASTFragment
- *
- */
-public class ASTFragmentFactory {
-
- // Factory Methods: /////////////////////////////////////////////////////////////////////////
-
- /**
- * Creates and returns a fragment representing the entire subtree
- * rooted at <code>node</code>. It is not true in general that
- * the node to which the produced IASTFragment maps (see {@link org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment IASTFragment})
- * will be <code>node</code>.
- *
- * XXX: more doc (current assertions about input vs. output)
- */
- public static IASTFragment createFragmentForFullSubtree(ASTNode node) {
- IASTFragment result= FragmentForFullSubtreeFactory.createFragmentFor(node);
- Assert.isNotNull(result);
- return result;
- }
-
- /**
- * If possible, this method creates a fragment whose source code
- * range is <code>range</code> within compilation unit <code>cu</code>,
- * and which resides somewhere within the subtree identified by
- * <code>scope</code>.
- *
- * XXX: more doc (current assertions about input vs. output)
- *
- * @param range The source range which the create fragment must have.
- * @param scope A node identifying the AST subtree in which the fragment must lie.
- * @param cu The compilation unit to which the source range applies, and to which the AST corresponds.
- * @return IASTFragment A fragment whose source range is <code>range</code> within
- * compilation unit <code>cu</code>, residing somewhere within the
- * AST subtree identified by <code>scope</code>.
- * @throws JavaScriptModelException
- */
- public static IASTFragment createFragmentForSourceRange(SourceRange range, ASTNode scope, IJavaScriptUnit cu) throws JavaScriptModelException {
- SelectionAnalyzer sa= new SelectionAnalyzer(Selection.createFromStartLength(range.getOffset(), range.getLength()), false);
- scope.accept(sa);
-
- if (isSingleNodeSelected(sa, range, cu))
- return ASTFragmentFactory.createFragmentForFullSubtree(sa.getFirstSelectedNode());
- if (isEmptySelectionCoveredByANode(range, sa))
- return ASTFragmentFactory.createFragmentForFullSubtree(sa.getLastCoveringNode());
- return ASTFragmentFactory.createFragmentForSubPartBySourceRange(sa.getLastCoveringNode(), range, cu);
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
-
-
- private static boolean isEmptySelectionCoveredByANode(SourceRange range, SelectionAnalyzer sa) {
- return range.getLength() == 0 && sa.getFirstSelectedNode() == null && sa.getLastCoveringNode() != null;
- }
-
- private static boolean isSingleNodeSelected(SelectionAnalyzer sa, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- return sa.getSelectedNodes().length == 1 && !rangeIncludesNonWhitespaceOutsideNode(range, sa.getFirstSelectedNode(), cu);
- }
- private static boolean rangeIncludesNonWhitespaceOutsideNode(SourceRange range, ASTNode node, IJavaScriptUnit cu) throws JavaScriptModelException {
- return Util.rangeIncludesNonWhitespaceOutsideRange(range, new SourceRange(node), cu.getBuffer());
- }
-
-
- /**
- * Returns <code>null</code> if the indices, taken with respect to
- * the node, do not correspond to a valid node-sub-part
- * fragment.
- */
- private static IASTFragment createFragmentForSubPartBySourceRange(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- return FragmentForSubPartBySourceRangeFactory.createFragmentFor(node, range, cu);
- }
-
- private static class FragmentForFullSubtreeFactory extends FragmentFactory {
- public static IASTFragment createFragmentFor(ASTNode node) {
- return new FragmentForFullSubtreeFactory().createFragment(node);
- }
-
- public boolean visit(InfixExpression node) {
- /* Try creating an associative infix expression fragment
- /* for the full subtree. If this is not applicable,
- * try something more generic.
- */
- IASTFragment fragment= AssociativeInfixExpressionFragment.createFragmentForFullSubtree(node);
- if(fragment == null)
- return visit((Expression) node);
-
- setFragment(fragment);
- return false;
- }
- public boolean visit(Expression node) {
- setFragment(new SimpleExpressionFragment(node));
- return false;
- }
- public boolean visit(ASTNode node) {
- setFragment(new SimpleFragment(node));
- return false;
- }
- }
- private static class FragmentForSubPartBySourceRangeFactory extends FragmentFactory {
- private SourceRange fRange;
- private IJavaScriptUnit fCu;
-
- private JavaScriptModelException javaModelException= null;
-
- public static IASTFragment createFragmentFor(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- return new FragmentForSubPartBySourceRangeFactory().createFragment(node, range, cu);
- }
-
- public boolean visit(InfixExpression node) {
- try {
- setFragment(createInfixExpressionSubPartFragmentBySourceRange(node, fRange, fCu));
- } catch(JavaScriptModelException e) {
- javaModelException= e;
- }
- return false;
- }
-
- public boolean visit(ASTNode node) {
- //let fragment be null
- return false;
- }
-
- protected IASTFragment createFragment(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- fRange= range;
- fCu= cu;
- IASTFragment result= createFragment(node);
- if(javaModelException != null)
- throw javaModelException;
- return result;
- }
-
- private static IExpressionFragment createInfixExpressionSubPartFragmentBySourceRange(InfixExpression node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- return AssociativeInfixExpressionFragment.createSubPartFragmentBySourceRange(node, range, cu);
- }
- }
- private static abstract class FragmentFactory extends HierarchicalASTVisitor {
- private IASTFragment fFragment;
-
- protected IASTFragment createFragment(ASTNode node) {
- fFragment= null;
- node.accept(this);
- return fFragment;
- }
-
- protected final IASTFragment getFragment() {
- return fFragment;
- }
- protected final void setFragment(IASTFragment fragment) {
- Assert.isTrue(!isFragmentSet());
- fFragment= fragment;
- }
- protected final boolean isFragmentSet() {
- return getFragment() != null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTMatchingFragmentFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTMatchingFragmentFinder.java
deleted file mode 100644
index 8cd38c99..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTMatchingFragmentFinder.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-
-class ASTMatchingFragmentFinder extends GenericVisitor {
-
- public static IASTFragment[] findMatchingFragments(ASTNode scope, ASTFragment toMatch) {
- return new ASTMatchingFragmentFinder(toMatch).findMatches(scope);
- }
-
- private ASTFragment fFragmentToMatch;
- private Set fMatches= new HashSet();
-
- private ASTMatchingFragmentFinder(ASTFragment toMatch) {
- super(true);
- fFragmentToMatch= toMatch;
- }
- private IASTFragment[] findMatches(ASTNode scope) {
- fMatches.clear();
- scope.accept(this);
- return getMatches();
- }
- private IASTFragment[] getMatches() {
- return (IASTFragment[]) fMatches.toArray(new IASTFragment[fMatches.size()]);
- }
-
- public boolean visit(JSdoc node) {
- return false;
- }
-
- protected boolean visitNode(ASTNode node) {
- IASTFragment[] localMatches= fFragmentToMatch.getMatchingFragmentsWithNode(node);
- for(int i= 0; i < localMatches.length; i++) {
- fMatches.add(localMatches[i]);
- }
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/AssociativeInfixExpressionFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/AssociativeInfixExpressionFragment.java
deleted file mode 100644
index 8a89b878..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/AssociativeInfixExpressionFragment.java
+++ /dev/null
@@ -1,437 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.JdtASTMatcher;
-
-class AssociativeInfixExpressionFragment extends ASTFragment implements IExpressionFragment {
-
- private final List/*<Expression>*/ fOperands;
- private final InfixExpression fGroupRoot;
-
- public static IExpressionFragment createSubPartFragmentBySourceRange(InfixExpression node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException {
- Assert.isNotNull(node);
- Assert.isNotNull(range);
- Assert.isTrue(!range.covers(node));
- Assert.isTrue(new SourceRange(node).covers(range));
-
- if(!isAssociativeInfix(node))
- return null;
-
- InfixExpression groupRoot= findGroupRoot(node);
- Assert.isTrue(isAGroupRoot(groupRoot));
-
- List/*<Expression>*/ groupMembers= AssociativeInfixExpressionFragment.findGroupMembersInOrderFor(groupRoot);
- List/*<Expression>*/ subGroup= findSubGroupForSourceRange(groupMembers, range);
- if(subGroup.isEmpty() || rangeIncludesExtraNonWhitespace(range, subGroup, cu))
- return null;
-
- return new AssociativeInfixExpressionFragment(groupRoot, subGroup);
- }
-
- public static IExpressionFragment createFragmentForFullSubtree(InfixExpression node) {
- Assert.isNotNull(node);
-
- if(!isAssociativeInfix(node))
- return null;
-
- InfixExpression groupRoot= findGroupRoot(node);
- Assert.isTrue(isAGroupRoot(groupRoot));
-
- List/*<Expression>*/ groupMembers= AssociativeInfixExpressionFragment.findGroupMembersInOrderFor(node);
-
- return new AssociativeInfixExpressionFragment(groupRoot, groupMembers);
- }
-
- private static InfixExpression findGroupRoot(InfixExpression node) {
- Assert.isTrue(isAssociativeInfix(node));
-
- while(!isAGroupRoot(node)) {
- ASTNode parent= node.getParent();
-
- Assert.isNotNull(parent);
- Assert.isTrue(isAssociativeInfix(parent));
- Assert.isTrue(((InfixExpression) parent).getOperator() == node.getOperator());
-
- node= (InfixExpression) parent;
- }
-
- return node;
- }
-
- private static List findSubGroupForSourceRange(List/*<Expression>*/ group, SourceRange range) {
- Assert.isTrue(!group.isEmpty());
-
- List subGroup= new ArrayList();
-
- boolean entered= false, exited= false;
- if(range.getOffset() == ((ASTNode)group.get(0)).getStartPosition())
- entered= true;
- for(int i= 0; i < group.size() - 1; i++) {
- ASTNode member= (ASTNode) group.get(i);
- ASTNode nextMember= (ASTNode) group.get(i + 1);
-
- if(entered) {
- subGroup.add(member);
- if(rangeEndsBetween(range, member, nextMember)) {
- exited= true;
- break;
- }
-
- } else {
- if(rangeStartsBetween(range, member, nextMember))
- entered= true;
- }
- }
- ASTNode lastGroupMember= (ASTNode)group.get(group.size() - 1);
- if(range.getEndExclusive() == new SourceRange(lastGroupMember).getEndExclusive()) {
- subGroup.add(lastGroupMember);
- exited= true;
- }
-
- if(!exited)
- return new ArrayList(0);
- return subGroup;
- }
-
- private static boolean rangeStartsBetween(SourceRange range, ASTNode first, ASTNode next) {
- int pos= range.getOffset();
- return first.getStartPosition() + first.getLength() <= pos
- && pos <= next.getStartPosition();
- }
-
- private static boolean rangeEndsBetween(SourceRange range, ASTNode first, ASTNode next) {
- int pos= range.getEndExclusive();
- return first.getStartPosition() + first.getLength() <= pos
- && pos <= next.getStartPosition();
- }
-
- private static boolean rangeIncludesExtraNonWhitespace(SourceRange range, List/*<Expression>*/ operands, IJavaScriptUnit cu) throws JavaScriptModelException {
- return Util.rangeIncludesNonWhitespaceOutsideRange(range, getRangeOfOperands(operands), cu.getBuffer());
- }
-
- private static SourceRange getRangeOfOperands(List/*<Expression>*/ operands) {
- Expression first= (Expression) operands.get(0);
- Expression last= (Expression) operands.get(operands.size() - 1);
- return new SourceRange(first.getStartPosition(), last.getStartPosition() + last.getLength() - first.getStartPosition());
- }
-
- public IASTFragment[] getMatchingFragmentsWithNode(ASTNode node) {
- IASTFragment fragmentForNode= ASTFragmentFactory.createFragmentForFullSubtree(node);
- if (fragmentForNode instanceof AssociativeInfixExpressionFragment) {
- AssociativeInfixExpressionFragment kin= (AssociativeInfixExpressionFragment)fragmentForNode;
- return kin.getSubFragmentsWithMyNodeMatching(this);
- } else {
- return new IASTFragment[0];
- }
- }
-
- /**
- * Returns List of Lists of <code>ASTNode</code>s
- */
- private static List getMatchingContiguousNodeSubsequences(List source, List toMatch) {
- //naive implementation:
-
- List subsequences= new ArrayList();
-
- for(int i= 0; i < source.size();) {
- if(matchesAt(i, source, toMatch)) {
- subsequences.add(source.subList(i, i + toMatch.size()));
- i += toMatch.size();
- } else
- i++;
- }
-
- return subsequences;
- }
-
- private static boolean matchesAt(int index, List subject, List toMatch) {
- if(index + toMatch.size() > subject.size())
- return false;
- for(int i= 0; i < toMatch.size(); i++, index++) {
- if(!JdtASTMatcher.doNodesMatch(
- (ASTNode) subject.get(index), (ASTNode) toMatch.get(i)
- )
- )
- return false;
- }
- return true;
- }
-
- private static boolean isAGroupRoot(ASTNode node) {
- Assert.isNotNull(node);
-
- return isAssociativeInfix(node)
- && !isParentInfixWithSameOperator((InfixExpression) node);
- }
-
- private static boolean isAssociativeInfix(ASTNode node) {
- return node instanceof InfixExpression && isOperatorAssociative(((InfixExpression)node).getOperator());
- }
-
- private static boolean isParentInfixWithSameOperator(InfixExpression node) {
- return node.getParent() instanceof InfixExpression
- && ((InfixExpression) node.getParent()).getOperator() == node.getOperator();
- }
-
- private static boolean isOperatorAssociative(InfixExpression.Operator operator) {
- return operator == InfixExpression.Operator.PLUS
- || operator == InfixExpression.Operator.TIMES
- || operator == InfixExpression.Operator.XOR
- || operator == InfixExpression.Operator.OR
- || operator == InfixExpression.Operator.AND
- || operator == InfixExpression.Operator.CONDITIONAL_OR
- || operator == InfixExpression.Operator.CONDITIONAL_AND;
- }
-
- private AssociativeInfixExpressionFragment(InfixExpression groupRoot, List/*<Expression>*/ operands) {
- Assert.isTrue(isAGroupRoot(groupRoot));
- Assert.isTrue(operands.size() >= 2);
- fGroupRoot= groupRoot;
- fOperands= Collections.unmodifiableList(operands);
- }
-
- public boolean matches(IASTFragment other) {
- if (! other.getClass().equals(getClass()))
- return false;
-
- AssociativeInfixExpressionFragment otherOfKind= (AssociativeInfixExpressionFragment) other;
- return getOperator() == otherOfKind.getOperator()
- && doOperandsMatch(otherOfKind);
- }
-
- private boolean doOperandsMatch(AssociativeInfixExpressionFragment other) {
- if (getOperands().size() != other.getOperands().size())
- return false;
-
- Iterator myOperands= getOperands().iterator();
- Iterator othersOperands= other.getOperands().iterator();
-
- while (myOperands.hasNext() && othersOperands.hasNext()) {
- ASTNode myOperand= (ASTNode) myOperands.next();
- ASTNode othersOperand= (ASTNode) othersOperands.next();
-
- if (! JdtASTMatcher.doNodesMatch(myOperand, othersOperand))
- return false;
- }
-
- return true;
- }
-
- public IASTFragment[] getSubFragmentsMatching(IASTFragment toMatch) {
- return union(
- getSubFragmentsWithMyNodeMatching(toMatch),
- getSubFragmentsWithAnotherNodeMatching(toMatch)
- );
- }
-
- private IASTFragment[] getSubFragmentsWithMyNodeMatching(IASTFragment toMatch) {
- if(toMatch.getClass() != getClass())
- return new IASTFragment[0];
-
- AssociativeInfixExpressionFragment kinToMatch= (AssociativeInfixExpressionFragment) toMatch;
- if(kinToMatch.getOperator() != getOperator())
- return new IASTFragment[0];
-
- List matchingSubsequences=
- getMatchingContiguousNodeSubsequences(
- getOperands(),
- kinToMatch.getOperands()
- );
-
- IASTFragment[] matches= new IASTFragment[matchingSubsequences.size()];
- for(int i= 0; i < matchingSubsequences.size(); i++) {
- IASTFragment match= new AssociativeInfixExpressionFragment(
- fGroupRoot,
- (List) matchingSubsequences.get(i)
- );
- Assert.isTrue(match.matches(toMatch) || toMatch.matches(match));
- matches[i]= match;
- }
- return matches;
- }
-
- private IASTFragment[] getSubFragmentsWithAnotherNodeMatching(IASTFragment toMatch) {
- IASTFragment[] result= new IASTFragment[0];
- for (Iterator iter= getOperands().iterator(); iter.hasNext();) {
- ASTNode operand= (ASTNode) iter.next();
- result= union(result, ASTMatchingFragmentFinder.findMatchingFragments(operand, (ASTFragment)toMatch));
- }
- return result;
- }
- private static IASTFragment[] union(IASTFragment[] a1, IASTFragment[] a2) {
- IASTFragment[] union= new IASTFragment[a1.length + a2.length];
- System.arraycopy(a1, 0, union, 0, a1.length);
- System.arraycopy(a2, 0, union, a1.length, a2.length);
- return union;
-
- //TODO: this would be a REAL union...:
-// ArrayList union= new ArrayList();
-// for (int i= 0; i < a1.length; i++) {
-// union.add(a1[i]);
-// }
-// for (int i= 0; i < a2.length; i++) {
-// if (! union.contains(a2[i]))
-// union.add(a2[i]);
-// }
-// return (IASTFragment[]) union.toArray(new IASTFragment[union.size()]);
- }
-
-
- /**
- * Note that this fragment does not directly
- * represent this expression node, but rather
- * a part of it.
- */
- public Expression getAssociatedExpression() {
- return fGroupRoot;
- }
-
- /**
- * Note that this fragment does not directly
- * represent this node, but rather a particular sort of
- * part of its subtree.
- */
- public ASTNode getAssociatedNode() {
- return fGroupRoot;
- }
-
- public InfixExpression getGroupRoot() {
- return fGroupRoot;
- }
-
- public int getLength() {
- return getEndPositionExclusive() - getStartPosition();
- }
-
- private int getEndPositionExclusive() {
- List operands= getOperands();
- ASTNode lastNode= (ASTNode) operands.get(operands.size() - 1);
- return lastNode.getStartPosition() + lastNode.getLength();
- }
-
- public int getStartPosition() {
- return ((ASTNode) getOperands().get(0)).getStartPosition();
- }
-
- public List getOperands() {
- return fOperands;
- }
-
- public InfixExpression.Operator getOperator() {
- return fGroupRoot.getOperator();
- }
-
- public Expression createCopyTarget(ASTRewrite rewrite) throws JavaScriptModelException {
- List allOperands= findGroupMembersInOrderFor(fGroupRoot);
- if (allOperands.size() == fOperands.size()) {
- return (Expression) rewrite.createCopyTarget(fGroupRoot);
- }
-
- JavaScriptUnit root= (JavaScriptUnit) fGroupRoot.getRoot();
- IJavaScriptUnit cu= (IJavaScriptUnit) root.getJavaElement();
- String source= cu.getBuffer().getText(getStartPosition(), getLength());
- return (Expression) rewrite.createStringPlaceholder(source, ASTNode.INFIX_EXPRESSION);
-
-// //Todo: see whether we could copy bigger chunks of the original selection
-// // (probably only possible from extendedOperands list or from nested InfixExpressions)
-// InfixExpression result= rewrite.getAST().newInfixExpression();
-// result.setOperator(getOperator());
-// Expression first= (Expression) fOperands.get(0);
-// Expression second= (Expression) fOperands.get(1);
-// result.setLeftOperand((Expression) rewrite.createCopyTarget(first));
-// result.setRightOperand((Expression) rewrite.createCopyTarget(second));
-// for (int i= 2; i < fOperands.size(); i++) {
-// Expression next= (Expression) fOperands.get(i);
-// result.extendedOperands().add(rewrite.createCopyTarget(next));
-// }
-// return result;
- }
-
- public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
- List allOperands= findGroupMembersInOrderFor(fGroupRoot);
- if (allOperands.size() == fOperands.size()) {
- rewrite.replace(fGroupRoot, replacement, textEditGroup);
- return;
- }
-
- // Could maybe be done with less edits.
- // Problem is that the nodes to replace may not be all in the same InfixExpression.
- int first= allOperands.indexOf(fOperands.get(0));
- int after= first + fOperands.size();
- ArrayList newOperands= new ArrayList();
- for (int i= 0; i < allOperands.size(); i++) {
- if (i < first || after <= i) {
- newOperands.add(rewrite.createCopyTarget((Expression) allOperands.get(i)));
- } else /* i == first */ {
- newOperands.add(replacement);
- i= after - 1;
- }
- }
- Expression newExpression= ASTNodeFactory.newInfixExpression(rewrite.getAST(), getOperator(), newOperands);
- rewrite.replace(getGroupRoot(), newExpression, textEditGroup);
- }
-
- private static ArrayList/*<Expression>*/ findGroupMembersInOrderFor(InfixExpression groupRoot) {
- return new GroupMemberFinder(groupRoot).fMembersInOrder;
- }
-
- private static class GroupMemberFinder extends GenericVisitor {
- private ArrayList/*<Expression>*/ fMembersInOrder= new ArrayList();
- private InfixExpression fGroupRoot;
-
- public GroupMemberFinder(InfixExpression groupRoot) {
- super(true);
- Assert.isTrue(isAssociativeInfix(groupRoot));
- fGroupRoot= groupRoot;
- fGroupRoot.accept(this);
- }
- protected boolean visitNode(ASTNode node) {
- if (node instanceof InfixExpression && ((InfixExpression) node).getOperator() == fGroupRoot.getOperator())
- return true;
-
- fMembersInOrder.add(node);
- return false;
- }
- }
-
- public int hashCode() {
- return fGroupRoot.hashCode();
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AssociativeInfixExpressionFragment other= (AssociativeInfixExpressionFragment) obj;
- return fGroupRoot.equals(other.fGroupRoot) && fOperands.equals(other.fOperands);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IASTFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IASTFragment.java
deleted file mode 100644
index 27944664..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IASTFragment.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-
-/**
- * An IASTFragment represents 'part' of an AST, but
- * not necessarily a subtree of the AST. A fragment
- * may simply be an instance of some sort of pattern
- * or formation in an AST.
- * Such "fragments", however, do correspond to a
- * contiguous source code region, and, thus, posses a
- * source start position, and a source length. Every
- * fragment maps to an ASTNode, although this mapping is
- * not necessarily straightforward, and more than one
- * fragment may map to a given node.
- *
- * Fragments support abstract operations, which
- * support the notion of 'matching' fragments.
- * One operation determines whether a fragment 'matches'
- * a given fragment. Another operation finds all
- * sub-fragments (fragments contained within a
- * parent fragment, including the parent itself)
- * which 'match' another given fragment.
- *
- */
-public interface IASTFragment {
-
- /**
- * Determines whether <code> other </code>
- * 'matches' <code> this </code>.
- * This binary operation should be reflexive,
- * symmetric, and transitive.
- *
- * That two node match does not imply that their source ranges
- * are the same, or that they map (via getAssociatedNode()) to the
- * same node.
- */
- public boolean matches(IASTFragment other);
-
- /**
- * Returns (at least some approximation of) a maximal set of
- * sub-fragments of this fragment which match <code> toMatch </code>
- */
- public IASTFragment[] getSubFragmentsMatching(IASTFragment toMatch);
-
- /**
- * Every fragment maps to a node.
- * Multiple fragments can map to the same node.
- *
- * @return ASTNode The node to which this fragment maps.
- */
- public ASTNode getAssociatedNode();
-
- /**
- * Every fragment has a source start position.
- *
- * @return int The source start position.
- */
- public int getStartPosition();
-
- /**
- * Every fragment has a source length.
- *
- * @return int The source length.
- */
- public int getLength();
-
- /**
- * Replaces this fragment with the given replacement node.
- *
- * @param rewrite an ASTRewrite
- * @param replacement replacement for this fragment
- * @param textEditGroup a description or <code>null</code>
- */
- public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IExpressionFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IExpressionFragment.java
deleted file mode 100644
index b30011f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/IExpressionFragment.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-
-/**
- * Represents a fragment (@see IASTFragment) for which the node
- * to which the fragment maps is an Expression.
- */
-public interface IExpressionFragment extends IASTFragment {
-
- /**
- * Every IASTFragment maps to an ASTNode, although this mapping may
- * not be straightforward, and more than one fragment may map to the
- * same node.
- * An IExpressionFragment maps, specifically, to an Expression.
- *
- * @return Expression The node to which this fragment maps.
- */
- public Expression getAssociatedExpression();
-
- /**
- * Creates a copy of this IExpressionFragment.
- *
- * @param rewrite an ASTRewrite
- * @return a copy of this IExpressionFragment, ready for use in the given
- * rewrite
- * @throws JavaScriptModelException
- */
- public Expression createCopyTarget(ASTRewrite rewrite) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleExpressionFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleExpressionFragment.java
deleted file mode 100644
index 58adaabd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleExpressionFragment.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-
-class SimpleExpressionFragment extends SimpleFragment implements IExpressionFragment {
- SimpleExpressionFragment(Expression node) {
- super(node);
- }
-
- public Expression getAssociatedExpression() {
- return (Expression) getAssociatedNode();
- }
-
- public Expression createCopyTarget(ASTRewrite rewrite) {
- return (Expression) rewrite.createCopyTarget(getAssociatedNode());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleFragment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleFragment.java
deleted file mode 100644
index a89b7cb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/SimpleFragment.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.JdtASTMatcher;
-
-class SimpleFragment extends ASTFragment {
- private final ASTNode fNode;
-
- SimpleFragment(ASTNode node) {
- Assert.isNotNull(node);
- fNode= node;
- }
-
- public IASTFragment[] getMatchingFragmentsWithNode(ASTNode node) {
- if (! JdtASTMatcher.doNodesMatch(getAssociatedNode(), node))
- return new IASTFragment[0];
-
- IASTFragment match= ASTFragmentFactory.createFragmentForFullSubtree(node);
- Assert.isTrue(match.matches(this) || this.matches(match));
- return new IASTFragment[] { match };
- }
-
- public boolean matches(IASTFragment other) {
- return other.getClass().equals(getClass()) && JdtASTMatcher.doNodesMatch(other.getAssociatedNode(), getAssociatedNode());
- }
-
- public IASTFragment[] getSubFragmentsMatching(IASTFragment toMatch) {
- return ASTMatchingFragmentFinder.findMatchingFragments(getAssociatedNode(), (ASTFragment) toMatch);
- }
-
- public int getStartPosition() {
- return fNode.getStartPosition();
- }
-
- public int getLength() {
- return fNode.getLength();
- }
-
- public ASTNode getAssociatedNode() {
- return fNode;
- }
-
- public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
- rewrite.replace(fNode, replacement, textEditGroup);
- }
-
- public int hashCode() {
- return fNode.hashCode();
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- SimpleFragment other= (SimpleFragment) obj;
- return fNode.equals(other.fNode);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/Util.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/Util.java
deleted file mode 100644
index 533546de..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/Util.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.dom.fragments;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-
-/**
- * This class houses a collection of static methods which do not refer to,
- * or otherwise depend on, other classes in this package. Each
- * package-visible method is called by more than one other class in this
- * package. Since they do not depend on other classes in this package,
- * they could be moved to some less specialized package.
- */
-class Util {
- static boolean rangeIncludesNonWhitespaceOutsideRange(SourceRange selection, SourceRange nodes, IBuffer buffer) {
- if(!selection.covers(nodes))
- return false;
-
- //TODO: skip leading comments. Consider that leading line comment must be followed by newline!
- if(!isJustWhitespace(selection.getOffset(), nodes.getOffset(), buffer))
- return true;
- if(!isJustWhitespaceOrComment(nodes.getOffset() + nodes.getLength(), selection.getOffset() + selection.getLength(), buffer))
- return true;
- return false;
- }
- private static boolean isJustWhitespace(int start, int end, IBuffer buffer) {
- if (start == end)
- return true;
- Assert.isTrue(start <= end);
- return 0 == buffer.getText(start, end - start).trim().length();
- }
- private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) {
- if (start == end)
- return true;
- Assert.isTrue(start <= end);
- String trimmedText= buffer.getText(start, end - start).trim();
- if (0 == trimmedText.length()) {
- return true;
- } else {
- IScanner scanner= ToolFactory.createScanner(false, false, false, null);
- scanner.setSource(trimmedText.toCharArray());
- try {
- return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF;
- } catch (InvalidInputException e) {
- return false;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/AbstractFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/AbstractFix.java
deleted file mode 100644
index 8d2481df..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/AbstractFix.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-
-public abstract class AbstractFix implements IFix {
-
- public static abstract class AbstractFixRewriteOperation implements IFixRewriteOperation {
-
- protected Type importType(final ITypeBinding toImport, final ASTNode accessor, ImportRewrite imports, final JavaScriptUnit compilationUnit) {
- ImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(compilationUnit, accessor.getStartPosition(), imports);
- return imports.addImport(toImport, compilationUnit.getAST(), importContext);
- }
-
- protected TextEditGroup createTextEditGroup(String label) {
- if (label.length() > 0){
- return new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
- } else {
- return new TextEditGroup(label);
- }
- }
-
- public String getAdditionalInfo() {
- return null;
- }
- }
-
- private final String fName;
- private final IJavaScriptUnit fCompilationUnit;
- private final IFixRewriteOperation[] fFixRewrites;
- private final JavaScriptUnit fUnit;
- private IStatus fStatus;
-
- protected AbstractFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- fName= name;
- fCompilationUnit= (IJavaScriptUnit)compilationUnit.getJavaElement();
- fFixRewrites= fixRewriteOperations;
- fUnit= compilationUnit;
- fStatus= StatusInfo.OK_STATUS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getName()
- */
- public String getDescription() {
- return fName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getCompilationUnit()
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#createChange()
- */
- public TextChange createChange() throws CoreException {
- if (fFixRewrites == null || fFixRewrites.length == 0)
- return null;
-
- CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(getCompilationUnit(), fUnit);
-
- List/*<TextEditGroup>*/ groups= new ArrayList();
-
- for (int i= 0; i < fFixRewrites.length; i++) {
- fFixRewrites[i].rewriteAST(cuRewrite, groups);
- }
-
- CompilationUnitChange result= cuRewrite.createChange(getDescription(), true, null);
- if (result == null)
- return null;
-
- for (Iterator iter= groups.iterator(); iter.hasNext();) {
- TextEditGroup group= (TextEditGroup)iter.next();
- result.addTextEditGroup(group);
- }
- return result;
- }
-
- public String getAdditionalInfo(){
- StringBuffer sb= new StringBuffer();
- for (int i = 0; i < fFixRewrites.length; i++) {
- IFixRewriteOperation frw = fFixRewrites[i];
- if (frw instanceof AbstractFixRewriteOperation) {
- AbstractFixRewriteOperation fro= (AbstractFixRewriteOperation) frw;
- String info= fro.getAdditionalInfo();
- if (info != null)
- sb.append(info);
- }
- }
- if (sb.length() > 0) {
- return sb.toString();
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getStatus()
- */
- public IStatus getStatus() {
- return fStatus;
- }
-
- public void setStatus(IStatus status) {
- fStatus= status;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java
deleted file mode 100644
index 83215c70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java
+++ /dev/null
@@ -1,1246 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - https://bugs.eclipse.org/bugs/show_bug.cgi?id=168954
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-
-public class CleanUpConstants {
-
- /**
- * False value
- *
- *
- */
- public static final String FALSE= "false"; //$NON-NLS-1$
-
- /**
- * True value
- *
- *
- */
- public static final String TRUE= "true"; //$NON-NLS-1$
-
- /**
- * Format Java Source Code <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMAT_SOURCE_CODE= "cleanup.format_source_code"; //$NON-NLS-1$
-
- /**
- * Format comments. Specify which comment with:<br>
- * {@link #FORMAT_JAVADOC}<br>
- * {@link #FORMAT_MULTI_LINE_COMMENT}<br>
- * {@link #FORMAT_SINGLE_LINE_COMMENT} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated replaced by {@link #FORMAT_SOURCE_CODE}
- */
- public static final String FORMAT_COMMENT= "cleanup.format_comment"; //$NON-NLS-1$
-
- /**
- * Format single line comments. Only has an effect if
- * {@link #FORMAT_COMMENT} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated replaced by {@link org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants#FORMATTER_COMMENT_FORMAT_LINE_COMMENT}
- */
- public static final String FORMAT_SINGLE_LINE_COMMENT= "cleanup.format_single_line_comment"; //$NON-NLS-1$
-
- /**
- * Format multi line comments. Only has an effect if {@link #FORMAT_COMMENT}
- * is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated replaced by {@link org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants#FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT}
- */
- public static final String FORMAT_MULTI_LINE_COMMENT= "cleanup.format_multi_line_comment"; //$NON-NLS-1$
-
- /**
- * Format javadoc comments. Only has an effect if {@link #FORMAT_COMMENT} is
- * TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- * @deprecated replaced by {@link org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants#FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT}
- */
- public static final String FORMAT_JAVADOC= "cleanup.format_javadoc"; //$NON-NLS-1$
-
- /**
- * Removes trailing whitespace in compilation units<br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMAT_REMOVE_TRAILING_WHITESPACES= "cleanup.remove_trailing_whitespaces"; //$NON-NLS-1$
-
- /**
- * Removes trailing whitespace in compilation units on all lines<br>
- * Only has an effect if {@link #FORMAT_REMOVE_TRAILING_WHITESPACES} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMAT_REMOVE_TRAILING_WHITESPACES_ALL= "cleanup.remove_trailing_whitespaces_all"; //$NON-NLS-1$
-
- /**
- * Removes trailing whitespace in compilation units on all lines which
- * contain an other characters then whitespace<br>
- * Only has an effect if {@link #FORMAT_REMOVE_TRAILING_WHITESPACES} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY= "cleanup.remove_trailing_whitespaces_ignore_empty"; //$NON-NLS-1$
-
- /**
- * Controls access qualifiers for instance fields. For detailed settings use<br>
- * {@link #MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS}<br>
- * {@link #MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS= "cleanup.use_this_for_non_static_field_access"; //$NON-NLS-1$
-
- /**
- * Adds a 'this' qualifier to field accesses.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * int fField;
- * void foo() {fField= 10;} -&gt; void foo() {this.fField= 10;}
- * </pre></code> <br>
- * Only has an effect if {@link #MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS}
- * is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS= "cleanup.always_use_this_for_non_static_field_access"; //$NON-NLS-1$
-
- /**
- * Removes 'this' qualifier to field accesses.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * int fField;
- * void foo() {this.fField= 10;} -&gt; void foo() {fField= 10;}
- * </pre></code> <br>
- * Only has an effect if {@link #MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS}
- * is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY= "cleanup.use_this_for_non_static_field_access_only_if_necessary"; //$NON-NLS-1$
-
- /**
- * Controls access qualifiers for instance methods. For detailed settings
- * use<br>
- * {@link #MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS}<br>
- * {@link #MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS= "cleanup.use_this_for_non_static_method_access"; //$NON-NLS-1$
-
- /**
- * Adds a 'this' qualifier to method accesses.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * int method(){};
- * void foo() {method()} -&gt; void foo() {this.method();}
- * </pre></code> <br>
- * Only has an effect if {@link #MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS}
- * is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS= "cleanup.always_use_this_for_non_static_method_access"; //$NON-NLS-1$
-
- /**
- * Removes 'this' qualifier to field accesses.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * int fField;
- * void foo() {this.fField= 10;} -&gt; void foo() {fField= 10;}
- * </pre></code> <br>
- * Only has an effect if {@link #MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS}
- * is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY= "cleanup.use_this_for_non_static_method_access_only_if_necessary"; //$NON-NLS-1$
-
- /**
- * Controls access qualifiers for static members. For detailed settings use<br>
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD}<br>
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS}<br>
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD}<br>
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS}
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS= "cleanup.qualify_static_member_accesses_with_declaring_class"; //$NON-NLS-1$
-
- /**
- * Qualify static field accesses with declaring type.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * class E {
- * public static int i;
- * void foo() {i= 10;} -&gt; void foo() {E.i= 10;}
- * }
- * </code></pre>
- *
- * <br>
- * Only has an effect if
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD= "cleanup.qualify_static_field_accesses_with_declaring_class"; //$NON-NLS-1$
-
- /**
- * Qualifies static method accesses with declaring type.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * class E {
- * public static int m();
- * void foo() {m();} -&gt; void foo() {E.m();}
- * }
- * </code></pre>
- *
- * <br>
- * Only has an effect if
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD= "cleanup.qualify_static_method_accesses_with_declaring_class"; //$NON-NLS-1$
-
- /**
- * Changes indirect accesses to static members to direct ones.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * class E {public static int i;}
- * class ESub extends E {
- * void foo() {ESub.i= 10;} -&gt; void foo() {E.i= 10;}
- * }
- * </code></pre>
- *
- * <br>
- * Only has an effect if
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS= "cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class"; //$NON-NLS-1$
-
- /**
- * Changes non static accesses to static members to static accesses.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * class E {
- * public static int i;
- * void foo() {(new E()).i= 10;} -&gt; void foo() {E.i= 10;}
- * }
- * </code></pre>
- *
- * <br>
- * Only has an effect if
- * {@link #MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS= "cleanup.qualify_static_member_accesses_through_instances_with_declaring_class"; //$NON-NLS-1$
-
- /**
- * Controls the usage of blocks around single control statement bodies. For
- * detailed settings use<br>
- * {@link #CONTROL_STATMENTS_USE_BLOCKS_ALWAYS}<br>
- * {@link #CONTROL_STATMENTS_USE_BLOCKS_NEVER}<br>
- * {@link #CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String CONTROL_STATEMENTS_USE_BLOCKS= "cleanup.use_blocks"; //$NON-NLS-1$
-
- /**
- * Adds block to control statement body if the body is not a block.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * if (b) foo(); -&gt; if (b) {foo();}
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #CONTROL_STATEMENTS_USE_BLOCKS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String CONTROL_STATMENTS_USE_BLOCKS_ALWAYS= "cleanup.always_use_blocks"; //$NON-NLS-1$
-
- /**
- * Remove unnecessary blocks in control statement bodies if they contain a
- * single return or throw statement.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * if (b) {return;} -&gt; if (b) return;
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #CONTROL_STATEMENTS_USE_BLOCKS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW= "cleanup.use_blocks_only_for_return_and_throw"; //$NON-NLS-1$
-
- /**
- * Remove unnecessary blocks in control statement bodies.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * if (b) {foo();} -&gt; if (b) foo();
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #CONTROL_STATEMENTS_USE_BLOCKS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String CONTROL_STATMENTS_USE_BLOCKS_NEVER= "cleanup.never_use_blocks"; //$NON-NLS-1$
-
- /**
- * Convert for loops to enhanced for loops.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * for (int i = 0; i &lt; array.length; i++) {} -&gt; for (int element : array) {}
- * </code></pre>
- *
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED= "cleanup.convert_to_enhanced_for_loop"; //$NON-NLS-1$
-
- /**
- * Controls the usage of parenthesis in expressions. For detailed settings
- * use<br>
- * {@link #EXPRESSIONS_USE_PARENTHESES_ALWAYS}<br>
- * {@link #EXPRESSIONS_USE_PARENTHESES_NEVER}<br>
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String EXPRESSIONS_USE_PARENTHESES= "cleanup.use_parentheses_in_expressions"; //$NON-NLS-1$
-
- /**
- * Add paranoic parenthesis around conditional expressions.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * boolean b= i &gt; 10 &amp;&amp; i &lt; 100 || i &gt; 20;
- * -&gt;
- * boolean b= ((i &gt; 10) &amp;&amp; (i &lt; 100)) || (i &gt; 20);
- * </pre></code> <br>
- * Only has an effect if {@link #EXPRESSIONS_USE_PARENTHESES} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String EXPRESSIONS_USE_PARENTHESES_ALWAYS= "cleanup.always_use_parentheses_in_expressions"; //$NON-NLS-1$
-
- /**
- * Remove unnecessary parenthesis around conditional expressions.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * boolean b= ((i &gt; 10) &amp;&amp; (i &lt; 100)) || (i &gt; 20);
- * -&gt;
- * boolean b= i &gt; 10 &amp;&amp; i &lt; 100 || i &gt; 20;
- * </pre></code> <br>
- * Only has an effect if {@link #EXPRESSIONS_USE_PARENTHESES} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String EXPRESSIONS_USE_PARENTHESES_NEVER= "cleanup.never_use_parentheses_in_expressions"; //$NON-NLS-1$
-
- /**
- * Controls the usage of 'final' modifier for variable declarations. For
- * detailed settings use:<br>
- * {@link #VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES}<br>
- * {@link #VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS}<br>
- * {@link #VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String VARIABLE_DECLARATIONS_USE_FINAL= "cleanup.make_variable_declarations_final"; //$NON-NLS-1$
-
- /**
- * Add a final modifier to private fields where possible i.e.:
- *
- * <pre><code>
- * private int field= 0; -&gt; private final int field= 0;
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #VARIABLE_DECLARATIONS_USE_FINAL} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS= "cleanup.make_private_fields_final"; //$NON-NLS-1$
-
- /**
- * Add a final modifier to method parameters where possible i.e.:
- *
- * <pre><code>
- * void foo(int i) {} -&gt; void foo(final int i) {}
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #VARIABLE_DECLARATIONS_USE_FINAL} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS= "cleanup.make_parameters_final"; //$NON-NLS-1$
-
- /**
- * Add a final modifier to local variables where possible i.e.:
- *
- * <pre><code>
- * int i= 0; -&gt; final int i= 0;
- * </code></pre>
- *
- * <br>
- * Only has an effect if {@link #VARIABLE_DECLARATIONS_USE_FINAL} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES= "cleanup.make_local_variable_final"; //$NON-NLS-1$
-
- /**
- * Adds type parameters to raw type references.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * List l; -&gt; List&lt;Object&gt; l;
- * </code></pre>
- *
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Not set<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String VARIABLE_DECLARATION_USE_TYPE_ARGUMENTS_FOR_RAW_TYPE_REFERENCES= "cleanup.use_arguments_for_raw_type_references"; //$NON-NLS-1$
-
- /**
- * Removes unused imports. <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_IMPORTS= "cleanup.remove_unused_imports"; //$NON-NLS-1$
-
- /**
- * Controls the removal of unused private members. For detailed settings
- * use:<br>
- * {@link #REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS}<br>
- * {@link #REMOVE_UNUSED_CODE_PRIVATE_FELDS}<br>
- * {@link #REMOVE_UNUSED_CODE_PRIVATE_METHODS}<br>
- * {@link #REMOVE_UNUSED_CODE_PRIVATE_TYPES} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_PRIVATE_MEMBERS= "cleanup.remove_unused_private_members"; //$NON-NLS-1$
-
- /**
- * Removes unused private types. <br>
- * Only has an effect if {@link #REMOVE_UNUSED_CODE_PRIVATE_MEMBERS} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_PRIVATE_TYPES= "cleanup.remove_unused_private_types"; //$NON-NLS-1$
-
- /**
- * Removes unused private constructors. <br>
- * Only has an effect if {@link #REMOVE_UNUSED_CODE_PRIVATE_MEMBERS} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS= "cleanup.remove_private_constructors"; //$NON-NLS-1$
-
- /**
- * Removes unused private fields. <br>
- * Only has an effect if {@link #REMOVE_UNUSED_CODE_PRIVATE_MEMBERS} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_PRIVATE_FELDS= "cleanup.remove_unused_private_fields"; //$NON-NLS-1$
-
- /**
- * Removes unused private methods. <br>
- * Only has an effect if {@link #REMOVE_UNUSED_CODE_PRIVATE_MEMBERS} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_PRIVATE_METHODS= "cleanup.remove_unused_private_methods"; //$NON-NLS-1$
-
- /**
- * Removes unused local variables. <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNUSED_CODE_LOCAL_VARIABLES= "cleanup.remove_unused_local_variables"; //$NON-NLS-1$
-
- /**
- * Removes unused casts. <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNNECESSARY_CASTS= "cleanup.remove_unnecessary_casts"; //$NON-NLS-1$
-
- /**
- * Remove unnecessary '$NON-NLS$' tags.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * String s; //$NON-NLS-1$ -&gt; String s;
- * </code></pre>
- *
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String REMOVE_UNNECESSARY_NLS_TAGS= "cleanup.remove_unnecessary_nls_tags"; //$NON-NLS-1$
-
- /**
- * Controls whether missing annotations should be added to the code. For
- * detailed settings use:<br>
- * {@link #ADD_MISSING_ANNOTATIONS_DEPRECATED}<br>
- * {@value #ADD_MISSING_ANNOTATIONS_OVERRIDE} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_ANNOTATIONS= "cleanup.add_missing_annotations"; //$NON-NLS-1$
-
- /**
- * Add '@Override' annotation in front of overriding methods.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * class E1 {void foo();}
- * class E2 extends E1 {
- * void foo(); -&gt; @Override void foo();
- * }
- * </pre></code> <br>
- * Only has an effect if {@link #ADD_MISSING_ANNOTATIONS} is TRUE
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by
- * {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_ANNOTATIONS_OVERRIDE= "cleanup.add_missing_override_annotations"; //$NON-NLS-1$
-
- /**
- * Add '@Deprecated' annotation in front of deprecated members.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * /**@deprecated* /
- * int i;
- * -&gt;
- * /**@deprecated* /
- * @Deprecated
- * int i;
- * </pre></code> <br>
- * Only has an effect if {@link #ADD_MISSING_ANNOTATIONS} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_ANNOTATIONS_DEPRECATED= "cleanup.add_missing_deprecated_annotations"; //$NON-NLS-1$
-
- /**
- * Controls whether missing serial version ids should be added to the code.
- * For detailed settings use:<br>
- * {@link #ADD_MISSING_SERIAL_VERSION_ID_DEFAULT}<br>
- * {@link #ADD_MISSING_SERIAL_VERSION_ID_GENERATED} <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_SERIAL_VERSION_ID= "cleanup.add_serial_version_id"; //$NON-NLS-1$
-
- /**
- * Adds a generated serial version id to subtypes of java.io.Serializable
- * and java.io.Externalizable
- *
- * public class E implements Serializable {} -> public class E implements
- * Serializable { private static final long serialVersionUID = 4381024239L; }
- * <br>
- * Only has an effect if {@link #ADD_MISSING_SERIAL_VERSION_ID} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_SERIAL_VERSION_ID_GENERATED= "cleanup.add_generated_serial_version_id"; //$NON-NLS-1$
-
- /**
- * Adds a default serial version it to subtypes of java.io.Serializable and
- * java.io.Externalizable
- *
- * public class E implements Serializable {} -> public class E implements
- * Serializable { private static final long serialVersionUID = 1L; } <br>
- * Only has an effect if {@link #ADD_MISSING_SERIAL_VERSION_ID} is TRUE <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_SERIAL_VERSION_ID_DEFAULT= "cleanup.add_default_serial_version_id"; //$NON-NLS-1$
-
- /**
- * Add '$NON-NLS$' tags to non externalized strings.
- * <p>
- * i.e.:
- *
- * <pre><code>
- * String s= &quot;&quot;; -&gt; String s= &quot;&quot;; //$NON-NLS-1$
- * </code></pre>
- *
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ADD_MISSING_NLS_TAGS= "cleanup.add_missing_nls_tags"; //$NON-NLS-1$
-
- /**
- * If true the imports are organized while cleaning up code.
- *
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String ORGANIZE_IMPORTS= "cleanup.organize_imports"; //$NON-NLS-1$
-
- /**
- * Should members be sorted?
- * <br><br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #SORT_MEMBERS_ALL
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String SORT_MEMBERS = "cleanup.sort_members"; //$NON-NLS-1$
-
- /**
- * If sorting members, should fields, enum constants and initializers also be sorted?
- * <br>
- * This has only an effect if {@link #SORT_MEMBERS} is also enabled.
- * <br>
- * <br>
- * Possible values: {TRUE, FALSE}<br>
- * Default value: Value returned by {@link #getEclipseDefaultSettings()}<br>
- * <br>
- *
- * @see #SORT_MEMBERS
- * @see #TRUE
- * @see #FALSE
- *
- */
- public static final String SORT_MEMBERS_ALL = "cleanup.sort_members_all"; //$NON-NLS-1$
-
- /**
- * Should the Clean Up Wizard be shown when executing the Clean Up Action?
- * <br>
- * <br>
- * Possible values: {<code><b>true</b></code>,
- * <code><b>false</b></code>}<br>
- * Default value: <code><b>true</b></code><br>
- * <br>
- *
- *
- */
- public static final String SHOW_CLEAN_UP_WIZARD= "cleanup.showwizard"; //$NON-NLS-1$
-
- /**
- * A key to a serialized string in the <code>InstanceScope</code>
- * containing all the profiles.<br>
- * Following code snippet can load the profiles:
- *
- * <pre><code>
- * List profiles= new ProfileStore(CLEANUP_PROFILES, new CleanUpVersioner()).readProfiles(new InstanceScope());
- * </code></pre>
- *
- *
- */
- public static final String CLEANUP_PROFILES= "org.eclipse.wst.jsdt.ui.cleanupprofiles"; //$NON-NLS-1$
-
- /**
- * Stores the id of the clean up profile used when executing clean up.<br>
- * <br>
- * Possible values: String value<br>
- * Default value: {@link #DEFAULT_PROFILE} <br>
- *
- *
- */
- public final static String CLEANUP_PROFILE= "cleanup_profile"; //$NON-NLS-1$$
-
- /**
- * Stores the id of the clean up profile used when executing clean up on
- * save.<br>
- * <br>
- * Possible values: String value<br>
- * Default value: {@link #DEFAULT_SAVE_PARTICIPANT_PROFILE} <br>
- *
- *
- */
- public static final String CLEANUP_ON_SAVE_PROFILE= "cleanup.on_save_profile_id"; //$NON-NLS-1$
-
- /**
- * A key to the version of the profile stored in the preferences.<br>
- * <br>
- * Possible values: Integer value<br>
- * Default value: {@link org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner#CURRENT_VERSION} <br>
- *
- *
- */
- public final static String CLEANUP_SETTINGS_VERSION_KEY= "cleanup_settings_version"; //$NON-NLS-1$
-
- /**
- * Id of the 'Eclipse [built-in]' profile.<br>
- * <br>
- *
- *
- */
- public final static String ECLIPSE_PROFILE= "org.eclipse.wst.jsdt.ui.default.eclipse_clean_up_profile"; //$NON-NLS-1$
-
- /**
- * Id of the 'Save Participant [built-in]' profile.<br>
- * <br>
- *
- *
- */
- public final static String SAVE_PARTICIPANT_PROFILE= "org.eclipse.wst.jsdt.ui.default.save_participant_clean_up_profile"; //$NON-NLS-1$
-
- public static final String CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS= "cleanup.on_save_use_additional_actions"; //$NON-NLS-1$
-
- /**
- * The id of the profile used as a default profile when executing clean up.<br>
- * <br>
- * Possible values: String value<br>
- * Default value: {@link #ECLIPSE_PROFILE} <br>
- *
- *
- */
- public final static String DEFAULT_PROFILE= ECLIPSE_PROFILE;
-
- /**
- * The id of the profile used as a default profile when executing clean up
- * on save.<br>
- * <br>
- * Possible values: String value<br>
- * Default value: {@link #SAVE_PARTICIPANT_PROFILE} <br>
- *
- *
- */
- public final static String DEFAULT_SAVE_PARTICIPANT_PROFILE= SAVE_PARTICIPANT_PROFILE;
-
- public static Map getEclipseDefaultSettings() {
- final HashMap result= new HashMap();
-
- //Member Accesses
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY, TRUE);
-
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY, TRUE);
-
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, TRUE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD, FALSE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD, FALSE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, TRUE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, TRUE);
-
- //Control Statements
- result.put(CONTROL_STATEMENTS_USE_BLOCKS, FALSE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_ALWAYS, TRUE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW, FALSE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_NEVER, FALSE);
-
- result.put(CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, FALSE);
-
- //Expressions
- result.put(EXPRESSIONS_USE_PARENTHESES, FALSE);
- result.put(EXPRESSIONS_USE_PARENTHESES_NEVER, TRUE);
- result.put(EXPRESSIONS_USE_PARENTHESES_ALWAYS, FALSE);
-
- //Variable Declarations
- result.put(VARIABLE_DECLARATIONS_USE_FINAL, FALSE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, TRUE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, FALSE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, TRUE);
-
- //Unused Code
- result.put(REMOVE_UNUSED_CODE_IMPORTS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, FALSE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_FELDS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_METHODS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_TYPES, TRUE);
- result.put(REMOVE_UNUSED_CODE_LOCAL_VARIABLES, FALSE);
-
- //Unnecessary Code
- result.put(REMOVE_UNNECESSARY_CASTS, TRUE);
- result.put(REMOVE_UNNECESSARY_NLS_TAGS, TRUE);
-
- //Missing Code
- result.put(ADD_MISSING_ANNOTATIONS, TRUE);
- result.put(ADD_MISSING_ANNOTATIONS_OVERRIDE, TRUE);
- result.put(ADD_MISSING_ANNOTATIONS_DEPRECATED, TRUE);
-
- result.put(ADD_MISSING_SERIAL_VERSION_ID, FALSE);
- result.put(ADD_MISSING_SERIAL_VERSION_ID_GENERATED, FALSE);
- result.put(ADD_MISSING_SERIAL_VERSION_ID_DEFAULT, TRUE);
-
- result.put(ADD_MISSING_NLS_TAGS, FALSE);
-
- //Code Organising
- result.put(FORMAT_SOURCE_CODE, FALSE);
-
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES, FALSE);
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES_ALL, TRUE);
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY, FALSE);
-
- result.put(ORGANIZE_IMPORTS, FALSE);
-
- result.put(SORT_MEMBERS, FALSE);
- result.put(SORT_MEMBERS_ALL, FALSE);
-
- return result;
- }
-
- public static Map getSaveParticipantSettings() {
- final HashMap result= new HashMap();
-
- //Member Accesses
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY, TRUE);
-
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS, FALSE);
- result.put(MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY, TRUE);
-
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, FALSE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD, FALSE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD, FALSE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, TRUE);
- result.put(MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, TRUE);
-
- //Control Statements
- result.put(CONTROL_STATEMENTS_USE_BLOCKS, FALSE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_ALWAYS, TRUE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW, FALSE);
- result.put(CONTROL_STATMENTS_USE_BLOCKS_NEVER, FALSE);
-
- result.put(CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, FALSE);
-
- //Expressions
- result.put(EXPRESSIONS_USE_PARENTHESES, FALSE);
- result.put(EXPRESSIONS_USE_PARENTHESES_NEVER, TRUE);
- result.put(EXPRESSIONS_USE_PARENTHESES_ALWAYS, FALSE);
-
- //Variable Declarations
- result.put(VARIABLE_DECLARATIONS_USE_FINAL, TRUE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, FALSE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, FALSE);
- result.put(VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, TRUE);
-
- //Unused Code
- result.put(REMOVE_UNUSED_CODE_IMPORTS, FALSE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, FALSE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_FELDS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_METHODS, TRUE);
- result.put(REMOVE_UNUSED_CODE_PRIVATE_TYPES, TRUE);
- result.put(REMOVE_UNUSED_CODE_LOCAL_VARIABLES, FALSE);
-
- //Unnecessary Code
- result.put(REMOVE_UNNECESSARY_CASTS, TRUE);
- result.put(REMOVE_UNNECESSARY_NLS_TAGS, FALSE);
-
- //Missing Code
- result.put(ADD_MISSING_ANNOTATIONS, TRUE);
- result.put(ADD_MISSING_ANNOTATIONS_OVERRIDE, TRUE);
- result.put(ADD_MISSING_ANNOTATIONS_DEPRECATED, TRUE);
-
- result.put(ADD_MISSING_SERIAL_VERSION_ID, FALSE);
- result.put(ADD_MISSING_SERIAL_VERSION_ID_GENERATED, FALSE);
- result.put(ADD_MISSING_SERIAL_VERSION_ID_DEFAULT, TRUE);
-
- result.put(ADD_MISSING_NLS_TAGS, FALSE);
-
- //Code Organising
- result.put(FORMAT_SOURCE_CODE, FALSE);
-
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES, FALSE);
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES_ALL, TRUE);
- result.put(FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY, FALSE);
-
- result.put(ORGANIZE_IMPORTS, TRUE);
-
- result.put(SORT_MEMBERS, FALSE);
- result.put(SORT_MEMBERS_ALL, FALSE);
-
- result.put(CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS, FALSE);
-
- return result;
- }
-
- public static void initDefaults(IPreferenceStore store) {
- final Map settings= getEclipseDefaultSettings();
- for (final Iterator iterator= settings.keySet().iterator(); iterator.hasNext();) {
- final String key= (String)iterator.next();
- store.setDefault(key, (String)settings.get(key));
- }
-
- store.setDefault(SHOW_CLEAN_UP_WIZARD, true);
- store.setDefault(CLEANUP_PROFILE, DEFAULT_PROFILE);
- store.setDefault(CLEANUP_ON_SAVE_PROFILE, DEFAULT_SAVE_PARTICIPANT_PROFILE);
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPostSaveListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPostSaveListener.java
deleted file mode 100644
index 0005d590..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPostSaveListener.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension4;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.IRefactoringCoreStatusCodes;
-import org.eclipse.ltk.core.refactoring.IUndoManager;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.PerformChangeOperation;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.ui.refactoring.RefactoringUI;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.UndoEdit;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring.CleanUpChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.IPostSaveListener;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CleanUpPostSaveListener implements IPostSaveListener {
-
- private static class CleanUpSaveUndo extends TextFileChange {
-
- private final IFile fFile;
- private final UndoEdit[] fUndos;
- private final long fDocumentStamp;
- private final long fFileStamp;
-
- public CleanUpSaveUndo(String name, IFile file, UndoEdit[] undos, long documentStamp, long fileStamp) {
- super(name, file);
- Assert.isNotNull(undos);
-
- fDocumentStamp= documentStamp;
- fFileStamp= fileStamp;
- fFile= file;
- fUndos= undos;
- }
-
- public final boolean needsSaving() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- if (isValid(pm).hasFatalError())
- return new NullChange();
-
- if (pm == null)
- pm= new NullProgressMonitor();
-
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- pm.beginTask("", 2); //$NON-NLS-1$
- ITextFileBuffer buffer= null;
- try {
- manager.connect(fFile.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- buffer= manager.getTextFileBuffer(fFile.getFullPath(), LocationKind.IFILE);
- IDocument document= buffer.getDocument();
-
- long oldFileValue= fFile.getModificationStamp();
- long oldDocValue;
- if (document instanceof IDocumentExtension4) {
- oldDocValue= ((IDocumentExtension4)document).getModificationStamp();
- } else {
- oldDocValue= oldFileValue;
- }
-
- // perform the changes
- LinkedList list= new LinkedList();
- for (int index= 0; index < fUndos.length; index++) {
- UndoEdit edit= fUndos[index];
- UndoEdit redo= edit.apply(document, TextEdit.CREATE_UNDO);
- list.addFirst(redo);
- }
-
- boolean stampSetted= false;
-
- if (document instanceof IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) {
- try {
- ((IDocumentExtension4)document).replace(0, 0, "", fDocumentStamp); //$NON-NLS-1$
- stampSetted= true;
- } catch (BadLocationException e) {
- String message= e.getMessage();
- if (message == null)
- message= "BadLocationException"; //$NON-NLS-1$
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IRefactoringCoreStatusCodes.BAD_LOCATION, message, e));
- }
- }
-
- buffer.commit(pm, false);
- if (!stampSetted) {
- fFile.revertModificationStamp(fFileStamp);
- }
-
- return new CleanUpSaveUndo(getName(), fFile, ((UndoEdit[]) list.toArray(new UndoEdit[list.size()])), oldDocValue, oldFileValue);
- } catch (BadLocationException e) {
- String message= e.getMessage();
- if (message == null)
- message= "BadLocationException"; //$NON-NLS-1$
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IRefactoringCoreStatusCodes.BAD_LOCATION, message, e));
- } finally {
- if (buffer != null)
- manager.disconnect(fFile.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- }
- }
- }
-
- public static final String POSTSAVELISTENER_ID= "org.eclipse.wst.jsdt.ui.postsavelistener.cleanup"; //$NON-NLS-1$
- private static final String WARNING_VALUE= "warning"; //$NON-NLS-1$
- private static final String ERROR_VALUE= "error"; //$NON-NLS-1$
-
- /**
- * {@inheritDoc}
- */
- public void saved(IJavaScriptUnit unit, IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- monitor.beginTask(getName(), IProgressMonitor.UNKNOWN);
-
- try {
- if (!ActionUtil.isOnBuildPath(unit))
- return;
-
- IProject project= unit.getJavaScriptProject().getProject();
- Map settings= CleanUpPreferenceUtil.loadSaveParticipantOptions(new ProjectScope(project));
- if (settings == null) {
- IEclipsePreferences contextNode= new InstanceScope().getNode(JavaScriptUI.ID_PLUGIN);
- String id= contextNode.get(CleanUpConstants.CLEANUP_ON_SAVE_PROFILE, null);
- if (id == null) {
- id= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).get(CleanUpConstants.CLEANUP_ON_SAVE_PROFILE, CleanUpConstants.DEFAULT_SAVE_PARTICIPANT_PROFILE);
- }
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, Messages.format(FixMessages.CleanUpPostSaveListener_unknown_profile_error_message, id)));
- }
-
- ICleanUp[] cleanUps;
- if (CleanUpConstants.TRUE.equals(settings.get(CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS))) {
- cleanUps= CleanUpRefactoring.createCleanUps(settings);
- } else {
- HashMap filteredSettins= new HashMap();
- filteredSettins.put(CleanUpConstants.FORMAT_SOURCE_CODE, settings.get(CleanUpConstants.FORMAT_SOURCE_CODE));
- filteredSettins.put(CleanUpConstants.ORGANIZE_IMPORTS, settings.get(CleanUpConstants.ORGANIZE_IMPORTS));
- cleanUps= CleanUpRefactoring.createCleanUps(filteredSettins);
- }
-
- long oldFileValue= unit.getResource().getModificationStamp();
- long oldDocValue= getDocumentStamp((IFile)unit.getResource(), new SubProgressMonitor(monitor, 2));
-
- CompositeChange result= new CompositeChange(FixMessages.CleanUpPostSaveListener_SaveAction_ChangeName);
- LinkedList undoEdits= new LinkedList();
-
- IUndoManager manager= RefactoringCore.getUndoManager();
-
- try {
- manager.aboutToPerformChange(result);
-
- do {
- RefactoringStatus preCondition= new RefactoringStatus();
- for (int i= 0; i < cleanUps.length; i++) {
- RefactoringStatus conditions= cleanUps[i].checkPreConditions(unit.getJavaScriptProject(), new IJavaScriptUnit[] {unit}, new SubProgressMonitor(monitor, 5));
- preCondition.merge(conditions);
- }
- if (showStatus(preCondition) != Window.OK)
- return;
-
- Map options= new HashMap();
- for (int i= 0; i < cleanUps.length; i++) {
- Map map= cleanUps[i].getRequiredOptions();
- if (map != null) {
- options.putAll(map);
- }
- }
-
- JavaScriptUnit ast= null;
- if (requiresAST(cleanUps, unit)) {
- ast= createAst(unit, options, new SubProgressMonitor(monitor, 10));
- }
-
- List undoneCleanUps= new ArrayList();
- CleanUpChange change= CleanUpRefactoring.calculateChange(ast, unit, cleanUps, undoneCleanUps);
-
- RefactoringStatus postCondition= new RefactoringStatus();
- for (int i= 0; i < cleanUps.length; i++) {
- RefactoringStatus conditions= cleanUps[i].checkPostConditions(new SubProgressMonitor(monitor, 1));
- postCondition.merge(conditions);
- }
- if (showStatus(postCondition) != Window.OK)
- return;
-
- if (change != null) {
- result.add(change);
-
- change.setSaveMode(TextFileChange.LEAVE_DIRTY);
- change.initializeValidationData(new NullProgressMonitor());
-
- PerformChangeOperation performChangeOperation= RefactoringUI.createUIAwareChangeOperation(change);
- performChangeOperation.setSchedulingRule(unit.getSchedulingRule());
-
- performChangeOperation.run(new SubProgressMonitor(monitor, 5));
-
- performChangeOperation.getUndoChange();
- undoEdits.addFirst(change.getUndoEdit());
- }
-
- cleanUps= (ICleanUp[])undoneCleanUps.toArray(new ICleanUp[undoneCleanUps.size()]);
- } while (cleanUps.length > 0);
- } finally {
- manager.changePerformed(result, true);
- }
-
- if (undoEdits.size() > 0) {
- UndoEdit[] undoEditArray= (UndoEdit[])undoEdits.toArray(new UndoEdit[undoEdits.size()]);
- CleanUpSaveUndo undo= new CleanUpSaveUndo(result.getName(), (IFile)unit.getResource(), undoEditArray, oldDocValue, oldFileValue);
- undo.initializeValidationData(new NullProgressMonitor());
- manager.addUndo(result.getName(), undo);
- }
- } finally {
- monitor.done();
- }
- }
-
- private int showStatus(RefactoringStatus status) {
- if (!status.hasError())
- return Window.OK;
-
- Shell shell= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
-
- Dialog dialog= RefactoringUI.createRefactoringStatusDialog(status, shell, "", false); //$NON-NLS-1$
- return dialog.open();
- }
-
- private long getDocumentStamp(IFile file, IProgressMonitor monitor) throws CoreException {
- final ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- final IPath path= file.getFullPath();
-
- monitor.beginTask("", 2); //$NON-NLS-1$
-
- ITextFileBuffer buffer= null;
- try {
- manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
- buffer= manager.getTextFileBuffer(path, LocationKind.IFILE);
- IDocument document= buffer.getDocument();
-
- if (document instanceof IDocumentExtension4) {
- return ((IDocumentExtension4)document).getModificationStamp();
- } else {
- return file.getModificationStamp();
- }
- } finally {
- if (buffer != null)
- manager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
- monitor.done();
- }
- }
-
- private boolean requiresAST(ICleanUp[] cleanUps, IJavaScriptUnit unit) throws CoreException {
- for (int i= 0; i < cleanUps.length; i++) {
- if (cleanUps[i].requireAST(unit))
- return true;
- }
-
- return false;
- }
-
- private JavaScriptUnit createAst(IJavaScriptUnit unit, Map cleanUpOptions, IProgressMonitor monitor) {
- IJavaScriptProject project= unit.getJavaScriptProject();
- if (compatibleOptions(project, cleanUpOptions)) {
- JavaScriptUnit ast= ASTProvider.getASTProvider().getAST(unit, ASTProvider.WAIT_NO, monitor);
- if (ast != null)
- return ast;
- }
-
- ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setSource(unit);
- Map compilerOptions= RefactoringASTParser.getCompilerOptions(unit.getJavaScriptProject());
- compilerOptions.putAll(cleanUpOptions);
- parser.setCompilerOptions(compilerOptions);
-
- return (JavaScriptUnit)parser.createAST(monitor);
- }
-
- private boolean compatibleOptions(IJavaScriptProject project, Map cleanUpOptions) {
- if (cleanUpOptions.size() == 0)
- return true;
-
- Map projectOptions= project.getOptions(true);
-
- for (Iterator iterator= cleanUpOptions.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- String projectOption= (String)projectOptions.get(key);
- String cleanUpOption= (String)cleanUpOptions.get(key);
- if (!strongerEquals(projectOption, cleanUpOption))
- return false;
- }
-
- return true;
- }
-
- private boolean strongerEquals(String projectOption, String cleanUpOption) {
- if (projectOption == null)
- return false;
-
- if (ERROR_VALUE.equals(cleanUpOption)) {
- return ERROR_VALUE.equals(projectOption);
- } else if (WARNING_VALUE.equals(cleanUpOption)) {
- return ERROR_VALUE.equals(projectOption) || WARNING_VALUE.equals(projectOption);
- }
-
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return FixMessages.CleanUpPostSaveListener_name;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getId() {
- return POSTSAVELISTENER_ID;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPreferenceUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPreferenceUtil.java
deleted file mode 100644
index 33ba88c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpPreferenceUtil.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpMessages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpProfileManager;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileStore;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.BuiltInProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.KeySet;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CleanUpPreferenceUtil {
-
- public static final String SAVE_PARTICIPANT_KEY_PREFIX= "sp_"; //$NON-NLS-1$
-
- public static Map loadOptions(IScopeContext context) {
- return loadOptions(context, CleanUpConstants.CLEANUP_PROFILE, CleanUpConstants.DEFAULT_PROFILE);
- }
-
- private static Map loadOptions(IScopeContext context, String profileIdKey, String defaultProfileId) {
- IEclipsePreferences contextNode= context.getNode(JavaScriptUI.ID_PLUGIN);
- String id= contextNode.get(profileIdKey, null);
-
- if (id != null && ProjectScope.SCOPE.equals(context.getName())) {
- return loadFromProject(context);
- }
-
- InstanceScope instanceScope= new InstanceScope();
- if (id == null) {
- if (ProjectScope.SCOPE.equals(context.getName())) {
- id= instanceScope.getNode(JavaScriptUI.ID_PLUGIN).get(profileIdKey, null);
- }
- if (id == null) {
- id= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).get(profileIdKey, defaultProfileId);
- }
- }
-
- List builtInProfiles= getBuiltInProfiles();
- for (Iterator iterator= builtInProfiles.iterator(); iterator.hasNext();) {
- Profile profile= (Profile)iterator.next();
- if (id.equals(profile.getID()))
- return profile.getSettings();
- }
-
- if (id.equals(CleanUpConstants.SAVE_PARTICIPANT_PROFILE))
- return CleanUpConstants.getSaveParticipantSettings();
-
- CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
- ProfileStore profileStore= new ProfileStore(CleanUpConstants.CLEANUP_PROFILES, versioner);
-
- List list= null;
- try {
- list= profileStore.readProfiles(instanceScope);
- } catch (CoreException e1) {
- JavaScriptPlugin.log(e1);
- }
- if (list == null)
- return null;
-
- for (Iterator iterator= list.iterator(); iterator.hasNext();) {
- Profile profile= (Profile)iterator.next();
- if (id.equals(profile.getID()))
- return profile.getSettings();
- }
-
- return null;
- }
-
- private static Map loadFromProject(IScopeContext context) {
- final Map profileOptions= new HashMap();
- IEclipsePreferences uiPrefs= context.getNode(JavaScriptUI.ID_PLUGIN);
-
- CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
-
- Map defaultSettings= CleanUpConstants.getEclipseDefaultSettings();
- KeySet[] keySets= CleanUpProfileManager.KEY_SETS;
-
- boolean hasValues= false;
- for (int i= 0; i < keySets.length; i++) {
- KeySet keySet= keySets[i];
- IEclipsePreferences preferences= context.getNode(keySet.getNodeName());
- for (final Iterator keyIter = keySet.getKeys().iterator(); keyIter.hasNext(); ) {
- final String key= (String) keyIter.next();
- Object val= preferences.get(key, null);
- if (val != null) {
- hasValues= true;
- } else {
- val= defaultSettings.get(key);
- }
- profileOptions.put(key, val);
- }
- }
-
- if (!hasValues)
- return null;
-
- int version= uiPrefs.getInt(CleanUpConstants.CLEANUP_SETTINGS_VERSION_KEY, versioner.getFirstVersion());
- if (version == versioner.getCurrentVersion())
- return profileOptions;
-
- CustomProfile profile= new CustomProfile("tmp", profileOptions, version, versioner.getProfileKind()); //$NON-NLS-1$
- versioner.update(profile);
- return profile.getSettings();
- }
-
- public static Map loadSaveParticipantOptions(IScopeContext context) {
- IEclipsePreferences node;
- if (hasSettingsInScope(context)) {
- node= context.getNode(JavaScriptUI.ID_PLUGIN);
- } else {
- IScopeContext instanceScope= new InstanceScope();
- if (hasSettingsInScope(instanceScope)) {
- node= instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
- } else {
- return CleanUpConstants.getSaveParticipantSettings();
- }
- }
-
- Map result= new HashMap();
- Map defaultSettings= CleanUpConstants.getSaveParticipantSettings();
- for (Iterator iterator= defaultSettings.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- result.put(key, node.get(SAVE_PARTICIPANT_KEY_PREFIX + key, CleanUpConstants.FALSE));
- }
-
- return result;
- }
-
- public static void saveSaveParticipantOptions(IScopeContext context, Map settings) {
- IEclipsePreferences node= context.getNode(JavaScriptUI.ID_PLUGIN);
- for (Iterator iterator= settings.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- node.put(SAVE_PARTICIPANT_KEY_PREFIX + key, (String)settings.get(key));
- }
- }
-
- private static boolean hasSettingsInScope(IScopeContext context) {
- IEclipsePreferences node= context.getNode(JavaScriptUI.ID_PLUGIN);
-
- Map defaultSettings= CleanUpConstants.getSaveParticipantSettings();
- for (Iterator iterator= defaultSettings.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- if (node.get(SAVE_PARTICIPANT_KEY_PREFIX + key, null) != null)
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns a list of {@link org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile} stored in the <code>scope</code>
- * including the built in profiles.
- * @param scope the context from which to retrieve the profiles
- * @return list of profiles, not null
- *
- */
- public static List loadProfiles(IScopeContext scope) {
-
- CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
- ProfileStore profileStore= new ProfileStore(CleanUpConstants.CLEANUP_PROFILES, versioner);
-
- List list= null;
- try {
- list= profileStore.readProfiles(scope);
- } catch (CoreException e1) {
- JavaScriptPlugin.log(e1);
- }
- if (list == null) {
- list= getBuiltInProfiles();
- } else {
- list.addAll(getBuiltInProfiles());
- }
-
- return list;
- }
-
- /**
- * Returns a list of built in clean up profiles
- * @return the list of built in profiles, not null
- *
- */
- public static List getBuiltInProfiles() {
- ArrayList result= new ArrayList();
-
- final Profile eclipseProfile= new BuiltInProfile(CleanUpConstants.ECLIPSE_PROFILE, CleanUpMessages.CleanUpProfileManager_ProfileName_EclipseBuildIn, CleanUpConstants.getEclipseDefaultSettings(), 2, CleanUpProfileVersioner.CURRENT_VERSION, CleanUpProfileVersioner.PROFILE_KIND);
- result.add(eclipseProfile);
-
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpRefactoring.java
deleted file mode 100644
index 43027729..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpRefactoring.java
+++ /dev/null
@@ -1,1057 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.ContentStamp;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringTickProvider;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.text.edits.TextEditVisitor;
-import org.eclipse.text.edits.UndoEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MultiStateCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.CodeFormatCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.CommentFormatCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ControlStatementsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ExpressionsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.SortMembersCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.StringCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.UnusedCodeCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IScheduledRefactoring;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class CleanUpRefactoring extends Refactoring implements IScheduledRefactoring {
-
- public static class CleanUpChange extends CompilationUnitChange {
-
- private UndoEdit fUndoEdit;
-
- public CleanUpChange(String name, IJavaScriptUnit cunit) {
- super(name, cunit);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Change createUndoChange(UndoEdit edit, ContentStamp stampToRestore) {
- fUndoEdit= edit;
- return super.createUndoChange(edit, stampToRestore);
- }
-
- public UndoEdit getUndoEdit() {
- return fUndoEdit;
- }
- }
-
- private static class FixCalculationException extends RuntimeException {
-
- private static final long serialVersionUID= 3807273310144726165L;
-
- private final CoreException fException;
-
- public FixCalculationException(CoreException exception) {
- fException= exception;
- }
-
- public CoreException getException() {
- return fException;
- }
- }
-
- private static class ParseListElement {
-
- private final IJavaScriptUnit fUnit;
- private final ICleanUp[] fCleanUpsArray;
-
- public ParseListElement(IJavaScriptUnit unit, ICleanUp[] cleanUps) {
- fUnit= unit;
- fCleanUpsArray= cleanUps;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- public ICleanUp[] getCleanUps() {
- return fCleanUpsArray;
- }
- }
-
- private final class CleanUpRefactoringProgressMonitor extends SubProgressMonitor {
-
- private double fRealWork;
- private int fFlushCount;
- private final int fSize;
- private final int fIndex;
-
- private CleanUpRefactoringProgressMonitor(IProgressMonitor monitor, int ticks, int size, int index) {
- super(monitor, ticks);
- fFlushCount= 0;
- fSize= size;
- fIndex= index;
- }
-
- /**
- * {@inheritDoc}
- */
- public void internalWorked(double work) {
- fRealWork+= work;
- }
-
- public void flush() {
- super.internalWorked(fRealWork);
- reset();
- fFlushCount++;
- }
-
- public void reset() {
- fRealWork= 0.0;
- }
-
- public void done() {}
-
- public int getIndex() {
- return fIndex + fFlushCount;
- }
-
- public String getSubTaskMessage(IJavaScriptUnit source) {
- String typeName= source.getElementName();
- return Messages.format(FixMessages.CleanUpRefactoring_ProcessingCompilationUnit_message, new Object[] {new Integer(getIndex()), new Integer(fSize), typeName});
- }
- }
-
- private static class CleanUpASTRequestor extends ASTRequestor {
-
- private final List/*<ParseListElement>*/fUndoneElements;
- private final Hashtable/*<IJavaScriptUnit, Change>*/fSolutions;
- private final Hashtable/*<IJavaScriptUnit, ICleanUp[]>*/fCompilationUnitCleanUpMap;
- private final CleanUpRefactoringProgressMonitor fMonitor;
-
- public CleanUpASTRequestor(List parseList, Hashtable solutions, CleanUpRefactoringProgressMonitor monitor) {
- fSolutions= solutions;
- fMonitor= monitor;
- fUndoneElements= new ArrayList();
- fCompilationUnitCleanUpMap= new Hashtable(parseList.size());
- for (Iterator iter= parseList.iterator(); iter.hasNext();) {
- ParseListElement element= (ParseListElement)iter.next();
- fCompilationUnitCleanUpMap.put(element.getCompilationUnit(), element.getCleanUps());
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void acceptAST(IJavaScriptUnit source, JavaScriptUnit ast) {
-
- fMonitor.subTask(fMonitor.getSubTaskMessage(source));
-
- IJavaScriptUnit primary= (IJavaScriptUnit)source.getPrimaryElement();
- ICleanUp[] cleanUps= (ICleanUp[])fCompilationUnitCleanUpMap.get(primary);
-
- ICleanUp[] rejectedCleanUps= calculateSolutions(source, ast, cleanUps);
-
- if (rejectedCleanUps.length > 0) {
- fUndoneElements.add(new ParseListElement(primary, rejectedCleanUps));
- fMonitor.reset();
- } else {
- fMonitor.flush();
- }
- }
-
- public void acceptSource(IJavaScriptUnit source) {
- acceptAST(source, null);
- }
-
- public List getUndoneElements() {
- return fUndoneElements;
- }
-
- private ICleanUp[] calculateSolutions(IJavaScriptUnit source, JavaScriptUnit ast, ICleanUp[] cleanUps) {
- List/*<ICleanUp>*/result= new ArrayList();
- CleanUpChange solution;
- try {
- solution= calculateChange(ast, source, cleanUps, result);
- } catch (CoreException e) {
- throw new FixCalculationException(e);
- }
-
- if (solution != null) {
- try {
- integrateSolution(solution, source);
- } catch (JavaScriptModelException e) {
- throw new FixCalculationException(e);
- }
- }
-
- return (ICleanUp[])result.toArray(new ICleanUp[result.size()]);
- }
-
- private void integrateSolution(CleanUpChange solution, IJavaScriptUnit source) throws JavaScriptModelException {
- IJavaScriptUnit primary= source.getPrimary();
-
- List changes= (List)fSolutions.get(primary);
- if (changes == null) {
- changes= new ArrayList();
- fSolutions.put(primary, changes);
- }
- changes.add(solution);
- }
- }
-
- private static abstract class CleanUpParser {
-
- private static final int MAX_AT_ONCE;
- static {
- long maxMemory= Runtime.getRuntime().maxMemory();
- int ratio= (int)Math.round((double)maxMemory / (64 * 0x100000));
- switch (ratio) {
- case 0:
- MAX_AT_ONCE= 25;
- break;
- case 1:
- MAX_AT_ONCE= 100;
- break;
- case 2:
- MAX_AT_ONCE= 200;
- break;
- case 3:
- MAX_AT_ONCE= 300;
- break;
- case 4:
- MAX_AT_ONCE= 400;
- break;
- default:
- MAX_AT_ONCE= 500;
- break;
- }
- }
-
- public void createASTs(IJavaScriptUnit[] units, String[] bindingKeys, CleanUpASTRequestor requestor, IProgressMonitor monitor) {
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- try {
- monitor.beginTask("", units.length); //$NON-NLS-1$
-
- List list= Arrays.asList(units);
- int end= 0;
- int cursor= 0;
- while (cursor < units.length) {
- end= Math.min(end + MAX_AT_ONCE, units.length);
- List toParse= list.subList(cursor, end);
-
- createParser().createASTs((IJavaScriptUnit[])toParse.toArray(new IJavaScriptUnit[toParse.size()]), bindingKeys, requestor, new SubProgressMonitor(monitor, toParse.size()));
- cursor= end;
- }
- } finally {
- monitor.done();
- }
- }
-
- protected abstract ASTParser createParser();
- }
-
- private class CleanUpFixpointIterator {
-
- private List/*<ParseListElement>*/fParseList;
- private final Hashtable/*<IJavaScriptUnit, List<CleanUpChange>>*/fSolutions;
- private final Hashtable/*<IJavaScriptUnit (primary), IJavaScriptUnit (working copy)>*/fWorkingCopies;
- private final IJavaScriptProject fProject;
- private final Map fCleanUpOptions;
- private final int fSize;
- private int fIndex;
-
- public CleanUpFixpointIterator(IJavaScriptProject project, IJavaScriptUnit[] units, ICleanUp[] cleanUps) {
- fProject= project;
- fSolutions= new Hashtable(units.length);
- fWorkingCopies= new Hashtable();
-
- fParseList= new ArrayList(units.length);
- for (int i= 0; i < units.length; i++) {
- fParseList.add(new ParseListElement(units[i], cleanUps));
- }
-
- fCleanUpOptions= new Hashtable();
- for (int i= 0; i < cleanUps.length; i++) {
- ICleanUp cleanUp= cleanUps[i];
- Map currentCleanUpOption= cleanUp.getRequiredOptions();
- if (currentCleanUpOption != null)
- fCleanUpOptions.putAll(currentCleanUpOption);
- }
-
- fSize= units.length;
- fIndex= 1;
- }
-
- public boolean hasNext() {
- return !fParseList.isEmpty();
- }
-
- public void next(IProgressMonitor monitor) throws CoreException {
- List parseList= new ArrayList();
- List sourceList= new ArrayList();
-
- try {
- for (Iterator iter= fParseList.iterator(); iter.hasNext();) {
- ParseListElement element= (ParseListElement)iter.next();
-
- IJavaScriptUnit compilationUnit= element.getCompilationUnit();
- if (fSolutions.containsKey(compilationUnit)) {
- if (fWorkingCopies.containsKey(compilationUnit)) {
- compilationUnit= (IJavaScriptUnit)fWorkingCopies.get(compilationUnit);
- } else {
- compilationUnit= compilationUnit.getWorkingCopy(new WorkingCopyOwner() {}, null);
- fWorkingCopies.put(compilationUnit.getPrimary(), compilationUnit);
- }
- applyChange(compilationUnit, (List)fSolutions.get(compilationUnit.getPrimary()));
- }
-
- if (requiresAST(compilationUnit, element.getCleanUps())) {
- parseList.add(compilationUnit);
- } else {
- sourceList.add(compilationUnit);
- }
- }
-
- CleanUpRefactoringProgressMonitor cuMonitor= new CleanUpRefactoringProgressMonitor(monitor, parseList.size() + sourceList.size(), fSize, fIndex);
- CleanUpASTRequestor requestor= new CleanUpASTRequestor(fParseList, fSolutions, cuMonitor);
- CleanUpParser parser= new CleanUpParser() {
- protected ASTParser createParser() {
- ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
- result.setResolveBindings(true);
- result.setProject(fProject);
-
- Map options= RefactoringASTParser.getCompilerOptions(fProject);
- options.putAll(fCleanUpOptions);
- result.setCompilerOptions(options);
- return result;
- }
- };
- try {
- IJavaScriptUnit[] units= (IJavaScriptUnit[])parseList.toArray(new IJavaScriptUnit[parseList.size()]);
- parser.createASTs(units, new String[0], requestor, cuMonitor);
- } catch (FixCalculationException e) {
- throw e.getException();
- }
-
- for (Iterator iterator= sourceList.iterator(); iterator.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit)iterator.next();
- requestor.acceptSource(cu);
- }
-
- fParseList= requestor.getUndoneElements();
- fIndex= cuMonitor.getIndex();
- } finally {
- }
- }
-
- public void dispose() {
- for (Iterator iterator= fWorkingCopies.values().iterator(); iterator.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit)iterator.next();
- try {
- cu.discardWorkingCopy();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- private boolean requiresAST(IJavaScriptUnit compilationUnit, ICleanUp[] cleanUps) throws CoreException {
- for (int i= 0; i < cleanUps.length; i++) {
- if (cleanUps[i].requireAST(compilationUnit))
- return true;
- }
- return false;
- }
-
- public Change[] getResult() {
-
- Change[] result= new Change[fSolutions.size()];
- int i=0;
- for (Iterator iterator= fSolutions.entrySet().iterator(); iterator.hasNext();) {
- Map.Entry entry= (Map.Entry)iterator.next();
-
- List changes= (List)entry.getValue();
- IJavaScriptUnit unit= (IJavaScriptUnit)entry.getKey();
-
- int saveMode;
- try {
- if (fLeaveFilesDirty || unit.getBuffer().hasUnsavedChanges()) {
- saveMode= TextFileChange.LEAVE_DIRTY;
- } else {
- saveMode= TextFileChange.FORCE_SAVE;
- }
- } catch (JavaScriptModelException e) {
- saveMode= TextFileChange.LEAVE_DIRTY;
- JavaScriptPlugin.log(e);
- }
-
- if (changes.size() == 1) {
- CleanUpChange change= (CleanUpChange)changes.get(0);
- change.setSaveMode(saveMode);
- result[i]= change;
- } else {
- MultiStateCompilationUnitChange mscuc= new MultiStateCompilationUnitChange(getChangeName(unit), unit);
- for (int j= 0; j < changes.size(); j++) {
- mscuc.addChange(createGroupFreeChange((CleanUpChange)changes.get(j)));
- }
- mscuc.setSaveMode(saveMode);
- result[i]= mscuc;
- }
-
- i++;
- }
-
- return result;
- }
-
- private TextChange createGroupFreeChange(CleanUpChange change) {
- CleanUpChange result= new CleanUpChange(change.getName(), change.getCompilationUnit());
- result.setEdit(change.getEdit());
- result.setSaveMode(change.getSaveMode());
- return result;
- }
-
- private void applyChange(IJavaScriptUnit compilationUnit, List changes) throws JavaScriptModelException, CoreException {
- if (changes.size() == 1) {
- CleanUpChange change= (CleanUpChange)changes.get(changes.size() - 1);
- compilationUnit.getBuffer().setContents(change.getPreviewContent(null));
- } else {
- MultiStateCompilationUnitChange mscuc= new MultiStateCompilationUnitChange("", compilationUnit.getPrimary()); //$NON-NLS-1$
- for (int i= 0; i < changes.size(); i++) {
- mscuc.addChange((CleanUpChange)changes.get(i));
- }
- compilationUnit.getBuffer().setContents(mscuc.getPreviewContent(null));
- }
- }
- }
-
- private static final RefactoringTickProvider CLEAN_UP_REFACTORING_TICK_PROVIDER= new RefactoringTickProvider(0, 1, 0, 0);
-
- private final List/*<ICleanUp>*/fCleanUps;
- private final Hashtable/*<IJavaScriptProject, List<IJavaScriptUnit>*/fProjects;
- private Change fChange;
- private boolean fLeaveFilesDirty;
- private final String fName;
-
- public CleanUpRefactoring() {
- this(FixMessages.CleanUpRefactoring_Refactoring_name);
- }
-
- public CleanUpRefactoring(String name) {
- fName= name;
- fCleanUps= new ArrayList();
- fProjects= new Hashtable();
- }
-
- public void addCompilationUnit(IJavaScriptUnit unit) {
- IJavaScriptProject javaProject= unit.getJavaScriptProject();
- if (!fProjects.containsKey(javaProject))
- fProjects.put(javaProject, new ArrayList());
-
- List cus= (List)fProjects.get(javaProject);
- cus.add(unit);
- }
-
- public void clearCompilationUnits() {
- fProjects.clear();
- }
-
- public boolean hasCompilationUnits() {
- return !fProjects.isEmpty();
- }
-
- public IJavaScriptUnit[] getCompilationUnits() {
- List cus= new ArrayList();
- for (Iterator iter= fProjects.values().iterator(); iter.hasNext();) {
- List pcus= (List)iter.next();
- cus.addAll(pcus);
- }
- return (IJavaScriptUnit[])cus.toArray(new IJavaScriptUnit[cus.size()]);
- }
-
- public void addCleanUp(ICleanUp fix) {
- fCleanUps.add(fix);
- }
-
- public void clearCleanUps() {
- fCleanUps.clear();
- }
-
- public boolean hasCleanUps() {
- return !fCleanUps.isEmpty();
- }
-
- public ICleanUp[] getCleanUps() {
- return (ICleanUp[])fCleanUps.toArray(new ICleanUp[fCleanUps.size()]);
- }
-
- public IJavaScriptProject[] getProjects() {
- return (IJavaScriptProject[])fProjects.keySet().toArray(new IJavaScriptProject[fProjects.keySet().size()]);
- }
-
- public void setLeaveFilesDirty(boolean leaveFilesDirty) {
- fLeaveFilesDirty= leaveFilesDirty;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Refactoring#getName()
- */
- public String getName() {
- return fName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Refactoring#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- if (pm != null) {
- pm.beginTask("", 1); //$NON-NLS-1$
- pm.worked(1);
- pm.done();
- }
- return new RefactoringStatus();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Refactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- if (pm != null) {
- pm.beginTask("", 1); //$NON-NLS-1$
- pm.worked(1);
- pm.done();
- }
- return fChange;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Refactoring#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
-
- if (pm == null)
- pm= new NullProgressMonitor();
-
- if (fProjects.size() == 0 || fCleanUps.size() == 0) {
- pm.beginTask("", 1); //$NON-NLS-1$
- pm.worked(1);
- pm.done();
- fChange= new NullChange();
-
- return new RefactoringStatus();
- }
-
- int cuCount= 0;
- for (Iterator iter= fProjects.keySet().iterator(); iter.hasNext();) {
- IJavaScriptProject project= (IJavaScriptProject)iter.next();
- cuCount+= ((List)fProjects.get(project)).size();
- }
-
- RefactoringStatus result= new RefactoringStatus();
-
- pm.beginTask("", cuCount * 2 * fCleanUps.size() + 4 * fCleanUps.size()); //$NON-NLS-1$
- try {
- DynamicValidationStateChange change= new DynamicValidationStateChange(getName());
- change.setSchedulingRule(getSchedulingRule());
- for (Iterator projectIter= fProjects.keySet().iterator(); projectIter.hasNext();) {
- IJavaScriptProject project= (IJavaScriptProject)projectIter.next();
-
- List compilationUnits= (List)fProjects.get(project);
- IJavaScriptUnit[] cus= (IJavaScriptUnit[])compilationUnits.toArray(new IJavaScriptUnit[compilationUnits.size()]);
-
- ICleanUp[] cleanUps= (ICleanUp[])fCleanUps.toArray(new ICleanUp[fCleanUps.size()]);
- result.merge(initialize(project));
- if (result.hasFatalError())
- return result;
-
- result.merge(checkPreConditions(project, cus, new SubProgressMonitor(pm, 3 * cleanUps.length)));
- if (result.hasFatalError())
- return result;
-
- Change[] changes= cleanUpProject(project, cus, cleanUps, pm);
-
- result.merge(checkPostConditions(new SubProgressMonitor(pm, cleanUps.length)));
- if (result.hasFatalError())
- return result;
-
- for (int i= 0; i < changes.length; i++) {
- change.add(changes[i]);
- }
- }
- fChange= change;
-
- List files= new ArrayList();
- findFilesToBeModified(change, files);
- result.merge(Checks.validateModifiesFiles((IFile[])files.toArray(new IFile[files.size()]), getValidationContext()));
- if (result.hasFatalError())
- return result;
- } finally {
- pm.done();
- }
-
- return result;
- }
-
- private void findFilesToBeModified(CompositeChange change, List result) throws JavaScriptModelException {
- Change[] children= change.getChildren();
- for (int i= 0; i < children.length; i++) {
- Change child= children[i];
- if (child instanceof CompositeChange) {
- findFilesToBeModified((CompositeChange)child, result);
- } else if (child instanceof MultiStateCompilationUnitChange) {
- result.add(((MultiStateCompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
- } else if (child instanceof CompilationUnitChange) {
- result.add(((CompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
- }
- }
- }
-
- private Change[] cleanUpProject(IJavaScriptProject project, IJavaScriptUnit[] compilationUnits, ICleanUp[] cleanUps, IProgressMonitor monitor) throws CoreException {
- CleanUpFixpointIterator iter= new CleanUpFixpointIterator(project, compilationUnits, cleanUps);
-
- SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 2 * compilationUnits.length * cleanUps.length);
- subMonitor.beginTask("", compilationUnits.length); //$NON-NLS-1$
- subMonitor.subTask(Messages.format(FixMessages.CleanUpRefactoring_Parser_Startup_message, project.getElementName()));
- try {
- while (iter.hasNext()) {
- iter.next(subMonitor);
- }
-
- return iter.getResult();
- } finally {
- iter.dispose();
- subMonitor.done();
- }
- }
-
- private RefactoringStatus initialize(IJavaScriptProject javaProject) throws CoreException {
- Map options= CleanUpPreferenceUtil.loadOptions(new ProjectScope(javaProject.getProject()));
- if (options == null) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(FixMessages.CleanUpRefactoring_could_not_retrive_profile, javaProject.getElementName()));
- }
-
- ICleanUp[] cleanUps= getCleanUps();
- for (int j= 0; j < cleanUps.length; j++) {
- cleanUps[j].initialize(options);
- }
-
- return new RefactoringStatus();
- }
-
- private RefactoringStatus checkPreConditions(IJavaScriptProject javaProject, IJavaScriptUnit[] compilationUnits, IProgressMonitor monitor) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
-
- ICleanUp[] cleanUps= getCleanUps();
- monitor.beginTask("", compilationUnits.length * cleanUps.length); //$NON-NLS-1$
- monitor.subTask(Messages.format(FixMessages.CleanUpRefactoring_Initialize_message, javaProject.getElementName()));
- try {
- for (int j= 0; j < cleanUps.length; j++) {
- result.merge(cleanUps[j].checkPreConditions(javaProject, compilationUnits, new SubProgressMonitor(monitor, compilationUnits.length)));
- if (result.hasFatalError())
- return result;
- }
- } finally {
- monitor.done();
- }
-
- return result;
- }
-
- private RefactoringStatus checkPostConditions(SubProgressMonitor monitor) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
-
- ICleanUp[] cleanUps= getCleanUps();
- monitor.beginTask("", cleanUps.length); //$NON-NLS-1$
- monitor.subTask(FixMessages.CleanUpRefactoring_checkingPostConditions_message);
- try {
- for (int j= 0; j < cleanUps.length; j++) {
- result.merge(cleanUps[j].checkPostConditions(new SubProgressMonitor(monitor, 1)));
- if (result.hasFatalError())
- return result;
- }
- } finally {
- monitor.done();
- }
- return result;
- }
-
- private static String getChangeName(IJavaScriptUnit compilationUnit) {
- StringBuffer buf= new StringBuffer();
- JavaScriptElementLabels.getCompilationUnitLabel(compilationUnit, JavaScriptElementLabels.ALL_DEFAULT, buf);
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
-
- StringBuffer buf2= new StringBuffer();
- JavaScriptElementLabels.getPackageFragmentLabel((IPackageFragment)compilationUnit.getParent(), JavaScriptElementLabels.P_QUALIFIED, buf2);
- buf.append(buf2.toString().replace('.', '/'));
-
- return buf.toString();
- }
-
- public static CleanUpChange calculateChange(JavaScriptUnit ast, IJavaScriptUnit source, ICleanUp[] cleanUps, List undoneCleanUps) throws CoreException {
- if (cleanUps.length == 0)
- return null;
-
- CleanUpChange solution= null;
- int i= 0;
- do {
- ICleanUp cleanUp= cleanUps[i];
- IFix fix;
- if (ast == null || !cleanUp.requireAST(source)) {
- fix= cleanUp.createFix(source);
- } else {
- fix= cleanUp.createFix(ast);
- }
- if (fix != null) {
- TextChange current= fix.createChange();
- TextEdit currentEdit= pack(current.getEdit());
-
- if (solution != null) {
- if (intersects(currentEdit, solution.getEdit())) {
- undoneCleanUps.add(cleanUp);
- } else {
- CleanUpChange merge= new CleanUpChange(FixMessages.CleanUpRefactoring_clean_up_multi_chang_name, source);
- merge.setEdit(merge(currentEdit, solution.getEdit()));
-
- copyChangeGroups(merge, solution);
- copyChangeGroups(merge, current);
-
- solution= merge;
- }
- } else {
- solution= new CleanUpChange(current.getName(), source);
- solution.setEdit(currentEdit);
-
- copyChangeGroups(solution, current);
- }
- }
- i++;
- } while (i < cleanUps.length && (solution == null || ast != null && !cleanUps[i].needsFreshAST(ast)));
-
- for (; i < cleanUps.length; i++) {
- undoneCleanUps.add(cleanUps[i]);
- }
- return solution;
- }
-
- private static void copyChangeGroups(CompilationUnitChange target, TextChange source) {
- TextEditBasedChangeGroup[] changeGroups= source.getChangeGroups();
- for (int i= 0; i < changeGroups.length; i++) {
- TextEditGroup textEditGroup= changeGroups[i].getTextEditGroup();
- TextEditGroup newGroup;
- if (textEditGroup instanceof CategorizedTextEditGroup) {
- String label= textEditGroup.getName();
- newGroup= new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
- } else {
- newGroup= new TextEditGroup(textEditGroup.getName());
- }
- TextEdit[] textEdits= textEditGroup.getTextEdits();
- for (int j= 0; j < textEdits.length; j++) {
- newGroup.addTextEdit(textEdits[j]);
- }
- target.addTextEditGroup(newGroup);
- }
- }
-
- private static TextEdit pack(TextEdit edit) {
- final List edits= new ArrayList();
- edit.accept(new TextEditVisitor() {
- public boolean visitNode(TextEdit node) {
- if (node instanceof MultiTextEdit)
- return true;
-
- edits.add(node);
- return false;
- }
- });
- MultiTextEdit result= new MultiTextEdit();
- for (Iterator iterator= edits.iterator(); iterator.hasNext();) {
- TextEdit child= (TextEdit)iterator.next();
- child.getParent().removeChild(child);
- TextChangeCompatibility.insert(result, child);
- }
- return result;
- }
-
- private static boolean intersects(TextEdit edit1, TextEdit edit2) {
- if (edit1 instanceof MultiTextEdit && edit2 instanceof MultiTextEdit) {
- MultiTextEdit multiTextEdit1= (MultiTextEdit)edit1;
- TextEdit[] children1= multiTextEdit1.getChildren();
-
- MultiTextEdit multiTextEdit2= (MultiTextEdit)edit2;
- TextEdit[] children2= multiTextEdit2.getChildren();
-
- int i1= 0;
- int i2= 0;
- while (i1 < children1.length && i2 < children2.length) {
- while (children1[i1].getExclusiveEnd() < children2[i2].getOffset()) {
- i1++;
- if (i1 >= children1.length)
- return false;
- }
- while (children2[i2].getExclusiveEnd() < children1[i1].getOffset()) {
- i2++;
- if (i2 >= children2.length)
- return false;
- }
- if (intersects(children1[i1], children2[i2]))
- return true;
-
- if (children1[i1].getExclusiveEnd() < children2[i2].getExclusiveEnd()) {
- i1++;
- } else {
- i2++;
- }
- }
-
- return false;
-
- } else if (edit1 instanceof MultiTextEdit) {
- MultiTextEdit multiTextEdit1= (MultiTextEdit)edit1;
- TextEdit[] children= multiTextEdit1.getChildren();
- for (int i= 0; i < children.length; i++) {
- TextEdit child= children[i];
- if (intersects(child, edit2))
- return true;
- }
- return false;
-
- } else if (edit2 instanceof MultiTextEdit) {
- MultiTextEdit multiTextEdit2= (MultiTextEdit)edit2;
- TextEdit[] children= multiTextEdit2.getChildren();
- for (int i= 0; i < children.length; i++) {
- TextEdit child= children[i];
- if (intersects(child, edit1))
- return true;
- }
- return false;
-
- } else {
- int start1= edit1.getOffset();
- int end1= start1 + edit1.getLength();
- int start2= edit2.getOffset();
- int end2= start2 + edit2.getLength();
-
- if (start1 > end2)
- return false;
-
- if (start2 > end1)
- return false;
-
- return true;
- }
- }
-
- private static TextEdit merge(TextEdit edit1, TextEdit edit2) {
- MultiTextEdit result= new MultiTextEdit();
- if (edit1 instanceof MultiTextEdit && edit2 instanceof MultiTextEdit) {
- MultiTextEdit multiTextEdit1= (MultiTextEdit)edit1;
- TextEdit[] children1= multiTextEdit1.getChildren();
-
- if (children1.length == 0)
- return edit2;
-
- MultiTextEdit multiTextEdit2= (MultiTextEdit)edit2;
- TextEdit[] children2= multiTextEdit2.getChildren();
-
- if (children2.length == 0)
- return edit1;
-
- int i1= 0;
- int i2= 0;
- while (i1 < children1.length && i2 < children2.length) {
-
- while (i1 < children1.length && children1[i1].getExclusiveEnd() < children2[i2].getOffset()) {
- edit1.removeChild(0);
- result.addChild(children1[i1]);
- i1++;
- }
- if (i1 >= children1.length) {
- for (int i= i2; i < children2.length; i++) {
- edit2.removeChild(0);
- result.addChild(children2[i]);
- }
- return result;
- }
- while (i2 < children2.length && children2[i2].getExclusiveEnd() < children1[i1].getOffset()) {
- edit2.removeChild(0);
- result.addChild(children2[i2]);
- i2++;
- }
- if (i2 >= children2.length) {
- for (int i= i1; i < children1.length; i++) {
- edit1.removeChild(0);
- result.addChild(children1[i]);
- }
- return result;
- }
-
- if (!(children1[i1].getExclusiveEnd() < children2[i2].getOffset())) {
- edit1.removeChild(0);
- edit2.removeChild(0);
- result.addChild(merge(children1[i1], children2[i2]));
- i1++;
- i2++;
- }
- }
-
- return result;
- } else if (edit1 instanceof MultiTextEdit) {
- TextEdit[] children= edit1.getChildren();
-
- int i= 0;
- while (children[i].getExclusiveEnd() < edit2.getOffset()) {
- edit1.removeChild(0);
- result.addChild(children[i]);
- i++;
- if (i >= children.length) {
- result.addChild(edit2);
- return result;
- }
- }
- edit1.removeChild(0);
- result.addChild(merge(children[i], edit2));
- i++;
- while (i < children.length) {
- edit1.removeChild(0);
- result.addChild(children[i]);
- i++;
- }
-
- return result;
- } else if (edit2 instanceof MultiTextEdit) {
- TextEdit[] children= edit2.getChildren();
-
- int i= 0;
- while (children[i].getExclusiveEnd() < edit1.getOffset()) {
- edit2.removeChild(0);
- result.addChild(children[i]);
- i++;
- if (i >= children.length) {
- result.addChild(edit1);
- return result;
- }
- }
- edit2.removeChild(0);
- result.addChild(merge(edit1, children[i]));
- i++;
- while (i < children.length) {
- edit2.removeChild(0);
- result.addChild(children[i]);
- i++;
- }
-
- return result;
- } else {
- if (edit1.getExclusiveEnd() < edit2.getOffset()) {
- result.addChild(edit1);
- result.addChild(edit2);
- } else {
- result.addChild(edit2);
- result.addChild(edit1);
- }
-
- return result;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.Refactoring#getRefactoringTickProvider()
- */
- protected RefactoringTickProvider doGetRefactoringTickProvider() {
- return CLEAN_UP_REFACTORING_TICK_PROVIDER;
- }
-
- /**
- * {@inheritDoc}
- */
- public ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- public static ICleanUp[] createCleanUps() {
- return new ICleanUp[] {
-// new CodeStyleCleanUp(),
- new ControlStatementsCleanUp(),
-// new ConvertLoopCleanUp(),
-// new VariableDeclarationCleanUp(),
- new ExpressionsCleanUp(),
- new UnusedCodeCleanUp(),
-// new Java50CleanUp(),
-// new UnnecessaryCodeCleanUp(),
- new StringCleanUp(),
- new SortMembersCleanUp(),
-// new ImportsCleanUp(),
- new CodeFormatCleanUp(),
- new CommentFormatCleanUp()};
- }
-
- public static ICleanUp[] createCleanUps(Map settings) {
- return new ICleanUp[] {
-// new CodeStyleCleanUp(settings),
- new ControlStatementsCleanUp(settings),
-// new ConvertLoopCleanUp(settings),
-// new VariableDeclarationCleanUp(settings),
- new ExpressionsCleanUp(settings),
- new UnusedCodeCleanUp(settings),
-// new Java50CleanUp(settings),
-// new UnnecessaryCodeCleanUp(settings),
- new StringCleanUp(settings),
- new SortMembersCleanUp(settings),
-// new ImportsCleanUp(settings),
- new CodeFormatCleanUp(settings),
- new CommentFormatCleanUp(settings)};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CodeStyleFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CodeStyleFix.java
deleted file mode 100644
index 3a81f082..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CodeStyleFix.java
+++ /dev/null
@@ -1,705 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * A fix which fixes code style issues.
- */
-public class CodeStyleFix extends AbstractFix {
-
- private final static class CodeStyleVisitor extends GenericVisitor {
-
- private final List/*<IFixRewriteOperation>*/ fResult;
- private final boolean fFindUnqualifiedAccesses;
- private final boolean fFindUnqualifiedStaticAccesses;
- private final boolean fFindUnqualifiedMethodAccesses;
- private final boolean fFindUnqualifiedStaticMethodAccesses;
-
- public CodeStyleVisitor(JavaScriptUnit compilationUnit,
- boolean findUnqualifiedAccesses,
- boolean findUnqualifiedStaticAccesses,
- boolean findUnqualifiedMethodAccesses,
- boolean findUnqualifiedStaticMethodAccesses,
- List resultingCollection) throws CoreException {
-
- fFindUnqualifiedAccesses= findUnqualifiedAccesses;
- fFindUnqualifiedStaticAccesses= findUnqualifiedStaticAccesses;
- fFindUnqualifiedMethodAccesses= findUnqualifiedMethodAccesses;
- fFindUnqualifiedStaticMethodAccesses= findUnqualifiedStaticMethodAccesses;
- //fImportRewrite= StubUtility.createImportRewrite(compilationUnit, true);
- fResult= resultingCollection;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(TypeDeclaration node) {
- return super.visit(node);
- }
-
- public boolean visit(QualifiedName node) {
- if (fFindUnqualifiedAccesses || fFindUnqualifiedStaticAccesses) {
- ASTNode simpleName= node;
- while (simpleName instanceof QualifiedName) {
- simpleName= ((QualifiedName) simpleName).getQualifier();
- }
- if (simpleName instanceof SimpleName) {
- handleSimpleName((SimpleName)simpleName);
- }
- }
- return false;
- }
-
- public boolean visit(SimpleName node) {
- if (fFindUnqualifiedAccesses || fFindUnqualifiedStaticAccesses) {
- handleSimpleName(node);
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(FunctionInvocation node) {
- if (!fFindUnqualifiedMethodAccesses && !fFindUnqualifiedStaticMethodAccesses)
- return true;
-
- if (node.getExpression() != null)
- return true;
-
- SimpleName name = node.getName();
- if (name!=null)
- {
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IFunctionBinding))
- return true;
- handleMethod(name, (IFunctionBinding)binding);
- }
-
- return true;
- }
-
- private void handleSimpleName(SimpleName node) {
- ASTNode firstExpression= node.getParent();
- if (firstExpression instanceof FieldAccess) {
- while (firstExpression instanceof FieldAccess) {
- firstExpression= ((FieldAccess)firstExpression).getExpression();
- }
- if (!(firstExpression instanceof SimpleName))
- return;
-
- node= (SimpleName)firstExpression;
- } else if (firstExpression instanceof SuperFieldAccess)
- return;
-
- StructuralPropertyDescriptor parentDescription= node.getLocationInParent();
- if (parentDescription == VariableDeclarationFragment.NAME_PROPERTY || parentDescription == SwitchCase.EXPRESSION_PROPERTY)
- return;
-
- IBinding binding= node.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return;
-
- handleVariable(node, (IVariableBinding) binding);
- }
-
- private void handleVariable(SimpleName node, IVariableBinding varbinding) {
- if (!varbinding.isField())
- return;
-
- ITypeBinding declaringClass= varbinding.getDeclaringClass();
- if (Modifier.isStatic(varbinding.getModifiers())) {
- if (fFindUnqualifiedStaticAccesses) {
- Initializer initializer= (Initializer) ASTNodes.getParent(node, Initializer.class);
- //Do not qualify assignments to static final fields in static initializers (would result in compile error)
- StructuralPropertyDescriptor parentDescription= node.getLocationInParent();
- if (initializer != null && Modifier.isStatic(initializer.getModifiers())
- && Modifier.isFinal(varbinding.getModifiers()) && parentDescription == Assignment.LEFT_HAND_SIDE_PROPERTY)
- return;
-
- //Do not qualify static fields if defined inside an anonymous class
- if (declaringClass.isAnonymous())
- return;
-
- fResult.add(new AddStaticQualifierOperation(declaringClass, node));
- }
- }
-// else if (fFindUnqualifiedAccesses){
-// String qualifier= getNonStaticQualifier(declaringClass, fImportRewrite, node);
-// if (qualifier == null)
-// return;
-//
-// fResult.add(new AddThisQualifierOperation(qualifier, node));
-// }
- }
-
- private void handleMethod(SimpleName node, IFunctionBinding binding) {
- ITypeBinding declaringClass= binding.getDeclaringClass();
- if (Modifier.isStatic(binding.getModifiers())) {
- if (fFindUnqualifiedStaticMethodAccesses) {
- //Do not qualify static fields if defined inside an anonymous class
- if (declaringClass.isAnonymous())
- return;
-
- fResult.add(new AddStaticQualifierOperation(declaringClass, node));
- }
- } else {
-// if (fFindUnqualifiedMethodAccesses) {
-// String qualifier= getNonStaticQualifier(declaringClass, fImportRewrite, node);
-// if (qualifier == null)
-// return;
-//
-// fResult.add(new AddThisQualifierOperation(qualifier, node));
-// }
- }
- }
- }
-
-// private static class ThisQualifierVisitor extends GenericVisitor {
-//
-// private final JavaScriptUnit fCompilationUnit;
-// private final List fOperations;
-// private final boolean fRemoveFieldQualifiers;
-// private final boolean fRemoveMethodQualifiers;
-//
-// public ThisQualifierVisitor(boolean removeFieldQualifiers,
-// boolean removeMethodQualifiers,
-// JavaScriptUnit compilationUnit,
-// List result) {
-// fRemoveFieldQualifiers= removeFieldQualifiers;
-// fRemoveMethodQualifiers= removeMethodQualifiers;
-// fCompilationUnit= compilationUnit;
-// fOperations= result;
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public boolean visit(final FieldAccess node) {
-// if (!fRemoveFieldQualifiers)
-// return true;
-//
-// Expression expression= node.getExpression();
-// if (!(expression instanceof ThisExpression))
-// return true;
-//
-// final SimpleName name= node.getName();
-// if (hasConflict(expression.getStartPosition(), name, ScopeAnalyzer.VARIABLES))
-// return true;
-//
-// fOperations.add(new AbstractFixRewriteOperation() {
-// public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
-// ASTRewrite rewrite= cuRewrite.getASTRewrite();
-//
-// TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_removeThis_groupDescription);
-// textEditGroups.add(group);
-//
-// rewrite.replace(node, rewrite.createCopyTarget(name), group);
-// }
-// });
-// return super.visit(node);
-// }
-//
-// /**
-// * {@inheritDoc}
-// */
-// public boolean visit(final FunctionInvocation node) {
-// if (!fRemoveMethodQualifiers)
-// return true;
-//
-// Expression expression= node.getExpression();
-// if (!(expression instanceof ThisExpression))
-// return true;
-//
-// final SimpleName name= node.getName();
-// if (name!=null && name.resolveBinding() == null)
-// return true;
-//
-// if (hasConflict(expression.getStartPosition(), name, ScopeAnalyzer.METHODS))
-// return true;
-//
-// Name qualifier= ((ThisExpression)expression).getQualifier();
-// if (qualifier != null) {
-// ITypeBinding declaringClass= ((IFunctionBinding)name.resolveBinding()).getDeclaringClass();
-// if (declaringClass == null)
-// return true;
-//
-// ITypeBinding caller= getDeclaringType(node);
-// if (caller == null)
-// return true;
-//
-// ITypeBinding callee= (ITypeBinding)qualifier.resolveBinding();
-// if (callee == null)
-// return true;
-//
-// if (callee.isAssignmentCompatible(declaringClass) && caller.isAssignmentCompatible(declaringClass))
-// return true;
-// }
-//
-// fOperations.add(new AbstractFixRewriteOperation() {
-// public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
-// ASTRewrite rewrite= cuRewrite.getASTRewrite();
-//
-// TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_removeThis_groupDescription);
-// textEditGroups.add(group);
-//
-// rewrite.remove(node.getExpression(), group);
-// }
-// });
-// return super.visit(node);
-// }
-//
-// private ITypeBinding getDeclaringType(FunctionInvocation node) {
-// ASTNode p= node;
-// while (p != null) {
-// p= p.getParent();
-// if (p instanceof AbstractTypeDeclaration) {
-// return ((AbstractTypeDeclaration)p).resolveBinding();
-// }
-// }
-// return null;
-// }
-//
-// private boolean hasConflict(int startPosition, SimpleName name, int flag) {
-// ScopeAnalyzer analyzer= new ScopeAnalyzer(fCompilationUnit);
-// IBinding[] declarationsInScope= analyzer.getDeclarationsInScope(startPosition, flag);
-// for (int i= 0; i < declarationsInScope.length; i++) {
-// IBinding decl= declarationsInScope[i];
-// if (decl.getName().equals(name.getIdentifier()) && name.resolveBinding() != decl)
-// return true;
-// }
-// return false;
-// }
-// }
-
-// private final static class AddThisQualifierOperation extends AbstractFixRewriteOperation {
-//
-// private final String fQualifier;
-// private final SimpleName fName;
-//
-// public AddThisQualifierOperation(String qualifier, SimpleName name) {
-// fQualifier= qualifier;
-// fName= name;
-// }
-//
-// public String getDescription() {
-// return Messages.format(FixMessages.CodeStyleFix_QualifyWithThis_description, new Object[] {fName.getIdentifier(), fQualifier});
-// }
-//
-// /* (non-Javadoc)
-// * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
-// */
-// public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
-// ASTRewrite rewrite= cuRewrite.getASTRewrite();
-// TextEditGroup group;
-// if (fName.resolveBinding() instanceof IFunctionBinding) {
-// group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithThis_description);
-// } else {
-// group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithThis_description);
-// }
-// textEditGroups.add(group);
-// rewrite.replace(fName, rewrite.createStringPlaceholder(fQualifier + '.' + fName.getIdentifier(), ASTNode.SIMPLE_NAME), group);
-// }
-// }
-
- private final static class AddStaticQualifierOperation extends AbstractFixRewriteOperation {
-
- private final SimpleName fName;
- private final ITypeBinding fDeclaringClass;
-
- public AddStaticQualifierOperation(ITypeBinding declaringClass, SimpleName name) {
- super();
- fDeclaringClass= declaringClass;
- fName= name;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
- JavaScriptUnit compilationUnit= cuRewrite.getRoot();
- importType(fDeclaringClass, fName, cuRewrite.getImportRewrite(), compilationUnit);
- TextEditGroup group;
- if (fName.resolveBinding() instanceof IFunctionBinding) {
- group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithDeclClass_description);
- } else {
- group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithDeclClass_description);
- }
- textEditGroups.add(group);
- IJavaScriptElement javaElement= fDeclaringClass.getJavaElement();
- if (javaElement instanceof IType) {
- Name qualifierName= compilationUnit.getAST().newName(((IType)javaElement).getElementName());
- SimpleName simpleName= (SimpleName)rewrite.createMoveTarget(fName);
- QualifiedName qualifiedName= compilationUnit.getAST().newQualifiedName(qualifierName, simpleName);
- rewrite.replace(fName, qualifiedName, group);
- }
- }
-
- }
-
- private final static class ToStaticAccessOperation extends AbstractFixRewriteOperation {
-
- private final ITypeBinding fDeclaringTypeBinding;
- private final Expression fQualifier;
-
- public ToStaticAccessOperation(ITypeBinding declaringTypeBinding, Expression qualifier) {
- super();
- fDeclaringTypeBinding= declaringTypeBinding;
- fQualifier= qualifier;
- }
-
- public String getAccessorName() {
- return fDeclaringTypeBinding.getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- Type type= importType(fDeclaringTypeBinding, fQualifier, cuRewrite.getImportRewrite(), cuRewrite.getRoot());
- TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_ChangeAccessUsingDeclaring_description);
- textEditGroups.add(group);
- cuRewrite.getASTRewrite().replace(fQualifier, type, group);
- }
- }
-
- public static CodeStyleFix[] createNonStaticAccessFixes(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- if (!isNonStaticAccess(problem))
- return null;
-
- ToStaticAccessOperation operations[]= createToStaticAccessOperations(compilationUnit, problem);
- if (operations == null)
- return null;
-
- String label1= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStatic_description, operations[0].getAccessorName());
- CodeStyleFix fix1= new CodeStyleFix(label1, compilationUnit, new IFixRewriteOperation[] {operations[0]});
-
- if (operations.length > 1) {
- String label2= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStaticUsingInstanceType_description, operations[1].getAccessorName());
- CodeStyleFix fix2= new CodeStyleFix(label2, compilationUnit, new IFixRewriteOperation[] {operations[1]});
- return new CodeStyleFix[] {fix1, fix2};
- }
- return new CodeStyleFix[] {fix1};
- }
-
-// public static CodeStyleFix createAddFieldQualifierFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
-// if (IProblem.UnqualifiedFieldAccess != problem.getProblemId())
-// return null;
-//
-// AddThisQualifierOperation operation= getUnqualifiedFieldAccessResolveOperation(compilationUnit, problem);
-// if (operation == null)
-// return null;
-//
-// String groupName= operation.getDescription();
-// return new CodeStyleFix(groupName, compilationUnit, new IFixRewriteOperation[] {operation});
-// }
-
- public static CodeStyleFix createIndirectAccessToStaticFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- if (!isIndirectStaticAccess(problem))
- return null;
-
- ToStaticAccessOperation operations[]= createToStaticAccessOperations(compilationUnit, problem);
- if (operations == null)
- return null;
-
- String label= Messages.format(FixMessages.CodeStyleFix_ChangeStaticAccess_description, operations[0].getAccessorName());
- return new CodeStyleFix(label, compilationUnit, new IFixRewriteOperation[] {operations[0]});
- }
-
- public static CodeStyleFix createCleanUp(JavaScriptUnit compilationUnit,
- boolean addThisQualifier,
- boolean changeNonStaticAccessToStatic,
- boolean qualifyStaticFieldAccess,
- boolean changeIndirectStaticAccessToDirect,
- boolean qualifyMethodAccess,
- boolean qualifyStaticMethodAccess,
- boolean removeFieldQualifier,
- boolean removeMethodQualifier) throws CoreException {
-
- if (!addThisQualifier && !changeNonStaticAccessToStatic && !qualifyStaticFieldAccess && !changeIndirectStaticAccessToDirect && !qualifyMethodAccess && !qualifyStaticMethodAccess && !removeFieldQualifier && !removeMethodQualifier)
- return null;
-
- List/*<IFixRewriteOperation>*/ operations= new ArrayList();
- if (addThisQualifier || qualifyStaticFieldAccess || qualifyMethodAccess || qualifyStaticMethodAccess) {
- CodeStyleVisitor codeStyleVisitor= new CodeStyleVisitor(compilationUnit, addThisQualifier, qualifyStaticFieldAccess, qualifyMethodAccess, qualifyStaticMethodAccess, operations);
- compilationUnit.accept(codeStyleVisitor);
- }
-
- IProblem[] problems= compilationUnit.getProblems();
- IProblemLocation[] locations= new IProblemLocation[problems.length];
- for (int i= 0; i < problems.length; i++) {
- locations[i]= new ProblemLocation(problems[i]);
- }
- addToStaticAccessOperations(compilationUnit, locations, changeNonStaticAccessToStatic, changeIndirectStaticAccessToDirect, operations);
-
-// if (removeFieldQualifier || removeMethodQualifier) {
-// ThisQualifierVisitor visitor= new ThisQualifierVisitor(removeFieldQualifier, removeMethodQualifier, compilationUnit, operations);
-// compilationUnit.accept(visitor);
-// }
-
- if (operations.isEmpty())
- return null;
-
- IFixRewriteOperation[] operationsArray= (IFixRewriteOperation[])operations.toArray(new IFixRewriteOperation[operations.size()]);
- return new CodeStyleFix(FixMessages.CodeStyleFix_change_name, compilationUnit, operationsArray);
- }
-
- public static CodeStyleFix createCleanUp(JavaScriptUnit compilationUnit, IProblemLocation[] problems,
- boolean addThisQualifier,
- boolean changeNonStaticAccessToStatic,
- boolean changeIndirectStaticAccessToDirect) throws CoreException {
-
- if (!addThisQualifier && !changeNonStaticAccessToStatic && !changeIndirectStaticAccessToDirect)
- return null;
-
- List/*<IFixRewriteOperation>*/ operations= new ArrayList();
-// if (addThisQualifier) {
-// for (int i= 0; i < problems.length; i++) {
-// IProblemLocation problem= problems[i];
-// if (problem.getProblemId() == IProblem.UnqualifiedFieldAccess) {
-// AddThisQualifierOperation operation= getUnqualifiedFieldAccessResolveOperation(compilationUnit, problem);
-// if (operation != null)
-// operations.add(operation);
-// }
-// }
-// }
-
- addToStaticAccessOperations(compilationUnit, problems, changeNonStaticAccessToStatic, changeIndirectStaticAccessToDirect, operations);
-
- if (operations.isEmpty())
- return null;
-
- IFixRewriteOperation[] operationsArray= (IFixRewriteOperation[])operations.toArray(new IFixRewriteOperation[operations.size()]);
- return new CodeStyleFix(FixMessages.CodeStyleFix_change_name, compilationUnit, operationsArray);
- }
-
- private static void addToStaticAccessOperations(JavaScriptUnit compilationUnit, IProblemLocation[] problems, boolean changeNonStaticAccessToStatic, boolean changeIndirectStaticAccessToDirect, List result) {
- Hashtable nonStaticAccessOps= new Hashtable();
- if (changeNonStaticAccessToStatic || changeIndirectStaticAccessToDirect) {
- for (int i= 0; i < problems.length; i++) {
- IProblemLocation problem= problems[i];
- boolean isNonStaticAccess= changeNonStaticAccessToStatic && isNonStaticAccess(problem);
- boolean isIndirectStaticAccess= changeIndirectStaticAccessToDirect && isIndirectStaticAccess(problem);
- if (isNonStaticAccess || isIndirectStaticAccess) {
- ToStaticAccessOperation[] nonStaticAccessInformation= createToStaticAccessOperations(compilationUnit, problem);
- if (nonStaticAccessInformation != null) {
- ToStaticAccessOperation op= nonStaticAccessInformation[0];
- nonStaticAccessOps.put(op.fQualifier, op);
- }
- }
- }
- }
- for (Iterator iter= nonStaticAccessOps.values().iterator(); iter.hasNext();) {
- ToStaticAccessOperation op= (ToStaticAccessOperation)iter.next();
- if (!nonStaticAccessOps.containsKey(op.fQualifier.getParent()))
- result.add(op);
- }
- }
-
- private static boolean isIndirectStaticAccess(IProblemLocation problem) {
- return (problem.getProblemId() == IProblem.IndirectAccessToStaticField
- || problem.getProblemId() == IProblem.IndirectAccessToStaticMethod);
- }
-
- private static boolean isNonStaticAccess(IProblemLocation problem) {
- return (problem.getProblemId() == IProblem.NonStaticAccessToStaticField
- || problem.getProblemId() == IProblem.NonStaticAccessToStaticMethod);
- }
-
- private static ToStaticAccessOperation[] createToStaticAccessOperations(JavaScriptUnit astRoot, IProblemLocation problem) {
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return null;
- }
-
- Expression qualifier= null;
- IBinding accessBinding= null;
-
- if (selectedNode instanceof QualifiedName) {
- QualifiedName name= (QualifiedName) selectedNode;
- qualifier= name.getQualifier();
- accessBinding= name.resolveBinding();
- } else if (selectedNode instanceof SimpleName) {
- ASTNode parent= selectedNode.getParent();
- if (parent instanceof FieldAccess) {
- FieldAccess fieldAccess= (FieldAccess) parent;
- qualifier= fieldAccess.getExpression();
- accessBinding= fieldAccess.getName().resolveBinding();
- } else if (parent instanceof QualifiedName) {
- QualifiedName qualifiedName= (QualifiedName) parent;
- qualifier= qualifiedName.getQualifier();
- accessBinding= qualifiedName.getName().resolveBinding();
- }
- } else if (selectedNode instanceof FunctionInvocation) {
- FunctionInvocation methodInvocation= (FunctionInvocation) selectedNode;
- qualifier= methodInvocation.getExpression();
- SimpleName name = methodInvocation.getName();
- if (name!=null)
- accessBinding= name.resolveBinding();
- } else if (selectedNode instanceof FieldAccess) {
- FieldAccess fieldAccess= (FieldAccess) selectedNode;
- qualifier= fieldAccess.getExpression();
- accessBinding= fieldAccess.getName().resolveBinding();
- }
-
- if (accessBinding != null && qualifier != null) {
- ToStaticAccessOperation declaring= null;
- ITypeBinding declaringTypeBinding= getDeclaringTypeBinding(accessBinding);
- if (declaringTypeBinding != null) {
- declaringTypeBinding= declaringTypeBinding.getTypeDeclaration(); // use generic to avoid any type arguments
-
- declaring= new ToStaticAccessOperation(declaringTypeBinding, qualifier);
- }
- ToStaticAccessOperation instance= null;
- ITypeBinding instanceTypeBinding= Bindings.normalizeTypeBinding(qualifier.resolveTypeBinding());
- if (instanceTypeBinding != null) {
- instanceTypeBinding= instanceTypeBinding.getTypeDeclaration(); // use generic to avoid any type arguments
- if (instanceTypeBinding.getTypeDeclaration() != declaringTypeBinding) {
- instance= new ToStaticAccessOperation(instanceTypeBinding, qualifier);
- }
- }
- if (declaring != null && instance != null) {
- return new ToStaticAccessOperation[] {declaring, instance};
- } else {
- return new ToStaticAccessOperation[] {declaring};
- }
- }
- return null;
- }
-
- private static ITypeBinding getDeclaringTypeBinding(IBinding accessBinding) {
- if (accessBinding instanceof IFunctionBinding) {
- return ((IFunctionBinding) accessBinding).getDeclaringClass();
- } else if (accessBinding instanceof IVariableBinding) {
- return ((IVariableBinding) accessBinding).getDeclaringClass();
- }
- return null;
- }
-
-// private static AddThisQualifierOperation getUnqualifiedFieldAccessResolveOperation(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
-// SimpleName name= getName(compilationUnit, problem);
-// if (name == null)
-// return null;
-//
-// IBinding binding= name.resolveBinding();
-// if (binding == null || binding.getKind() != IBinding.VARIABLE)
-// return null;
-//
-// ImportRewrite imports= StubUtility.createImportRewrite(compilationUnit, true);
-//
-// String replacement= getQualifier((IVariableBinding)binding, imports, name);
-// if (replacement == null)
-// return null;
-//
-// return new AddThisQualifierOperation(replacement, name);
-// }
-//
-// private static String getQualifier(IVariableBinding binding, ImportRewrite imports, SimpleName name) {
-// ITypeBinding declaringClass= binding.getDeclaringClass();
-// if (Modifier.isStatic(binding.getModifiers())) {
-// IJavaScriptElement javaElement= declaringClass.getJavaElement();
-// if (javaElement instanceof IType) {
-// return ((IType)javaElement).getElementName();
-// }
-// } else {
-// return getNonStaticQualifier(declaringClass, imports, name);
-// }
-//
-// return null;
-// }
-
-// private static String getNonStaticQualifier(ITypeBinding declaringClass, ImportRewrite imports, SimpleName name) {
-// ITypeBinding parentType= Bindings.getBindingOfParentType(name);
-// ITypeBinding currType= parentType;
-// while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
-// currType= currType.getDeclaringClass();
-// }
-// if (currType == null) {
-// declaringClass= declaringClass.getTypeDeclaration();
-// currType= parentType;
-// while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
-// currType= currType.getDeclaringClass();
-// }
-// }
-// if (currType != parentType) {
-// if (currType == null)
-// return null;
-//
-// if (currType.isAnonymous())
-// //If we access a field of a super class of an anonymous class
-// //then we can only qualify with 'this' but not with outer.this
-// //see bug 115277
-// return null;
-//
-// String outer= imports.addImport(currType);
-// return outer + ".this"; //$NON-NLS-1$
-// } else {
-// return "this"; //$NON-NLS-1$
-// }
-// }
-
-// private static SimpleName getName(JavaScriptUnit compilationUnit, IProblemLocation problem) {
-// ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
-//
-// while (selectedNode instanceof QualifiedName) {
-// selectedNode= ((QualifiedName) selectedNode).getQualifier();
-// }
-// if (!(selectedNode instanceof SimpleName)) {
-// return null;
-// }
-// return (SimpleName) selectedNode;
-// }
-
- private CodeStyleFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ControlStatementsFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ControlStatementsFix.java
deleted file mode 100644
index 83c60c54..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ControlStatementsFix.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-
-public class ControlStatementsFix extends AbstractFix {
-
- private final static class ControlStatementFinder extends GenericVisitor {
-
- private final List/*<IFixRewriteOperation>*/ fResult;
- private final boolean fFindControlStatementsWithoutBlock;
- private final boolean fRemoveUnnecessaryBlocks;
- private final boolean fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow;
-
- public ControlStatementFinder(boolean findControlStatementsWithoutBlock,
- boolean removeUnnecessaryBlocks,
- boolean removeUnnecessaryBlocksOnlyWhenReturnOrThrow,
- List resultingCollection) {
-
- fFindControlStatementsWithoutBlock= findControlStatementsWithoutBlock;
- fRemoveUnnecessaryBlocks= removeUnnecessaryBlocks;
- fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow= removeUnnecessaryBlocksOnlyWhenReturnOrThrow;
- fResult= resultingCollection;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visit(org.eclipse.wst.jsdt.core.dom.DoStatement)
- */
- public boolean visit(DoStatement node) {
- if (fFindControlStatementsWithoutBlock) {
- Statement doBody= node.getBody();
- if (!(doBody instanceof Block)) {
- fResult.add(new AddBlockOperation(DoStatement.BODY_PROPERTY, doBody, node));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(node, DoStatement.BODY_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow)) {
- fResult.add(new RemoveBlockOperation(node, DoStatement.BODY_PROPERTY));
- }
- }
- return super.visit(node);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visit(org.eclipse.wst.jsdt.core.dom.ForStatement)
- */
- public boolean visit(ForStatement node) {
- if (fFindControlStatementsWithoutBlock) {
- Statement forBody= node.getBody();
- if (!(forBody instanceof Block)) {
- fResult.add(new AddBlockOperation(ForStatement.BODY_PROPERTY, forBody, node));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(node, ForStatement.BODY_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow)) {
- fResult.add(new RemoveBlockOperation(node, ForStatement.BODY_PROPERTY));
- }
- }
- return super.visit(node);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(EnhancedForStatement node) {
- if (fFindControlStatementsWithoutBlock) {
- Statement forBody= node.getBody();
- if (!(forBody instanceof Block)) {
- fResult.add(new AddBlockOperation(EnhancedForStatement.BODY_PROPERTY, forBody, node));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(node, EnhancedForStatement.BODY_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow)) {
- fResult.add(new RemoveBlockOperation(node, EnhancedForStatement.BODY_PROPERTY));
- }
- }
- return super.visit(node);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visit(org.eclipse.wst.jsdt.core.dom.IfStatement)
- */
- public boolean visit(IfStatement statement) {
- if (fFindControlStatementsWithoutBlock) {
- Statement then= statement.getThenStatement();
- if (!(then instanceof Block)) {
- fResult.add(new AddBlockOperation(IfStatement.THEN_STATEMENT_PROPERTY, then, statement));
- }
- Statement elseStatement= statement.getElseStatement();
- if (elseStatement != null && !(elseStatement instanceof Block) && !(elseStatement instanceof IfStatement)) {
- fResult.add(new AddBlockOperation(IfStatement.ELSE_STATEMENT_PROPERTY, elseStatement, statement));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(statement, IfStatement.THEN_STATEMENT_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow)) {
- fResult.add(new RemoveBlockOperation(statement, IfStatement.THEN_STATEMENT_PROPERTY));
- }
- if (!(statement.getElseStatement() instanceof IfStatement)) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(statement, IfStatement.ELSE_STATEMENT_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow)) {
- fResult.add(new RemoveBlockOperation(statement, IfStatement.ELSE_STATEMENT_PROPERTY));
- }
- }
- }
- return super.visit(statement);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visit(org.eclipse.wst.jsdt.core.dom.WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- if (fFindControlStatementsWithoutBlock) {
- Statement whileBody= node.getBody();
- if (!(whileBody instanceof Block)) {
- fResult.add(new AddBlockOperation(WhileStatement.BODY_PROPERTY, whileBody, node));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(node, WhileStatement.BODY_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow))
- fResult.add(new RemoveBlockOperation(node, WhileStatement.BODY_PROPERTY));
- }
- return super.visit(node);
- }
-
- public boolean visit(WithStatement node) {
- if (fFindControlStatementsWithoutBlock) {
- Statement withBody= node.getBody();
- if (!(withBody instanceof Block)) {
- fResult.add(new AddBlockOperation(WithStatement.BODY_PROPERTY, withBody, node));
- }
- } else if (fRemoveUnnecessaryBlocks || fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow) {
- if (RemoveBlockOperation.satisfiesCleanUpPrecondition(node, WithStatement.BODY_PROPERTY, fRemoveUnnecessaryBlocksOnlyWhenReturnOrThrow))
- fResult.add(new RemoveBlockOperation(node, WithStatement.BODY_PROPERTY));
- }
- return super.visit(node);
- }
-
- }
-
- private static class IfElseIterator {
-
- private IfStatement fCursor;
-
- public IfElseIterator(IfStatement item) {
- fCursor= findStart(item);
- }
-
- public IfStatement next() {
- if (!hasNext())
- return null;
-
- IfStatement result= fCursor;
-
- if (fCursor.getElseStatement() instanceof IfStatement) {
- fCursor= (IfStatement)fCursor.getElseStatement();
- } else {
- fCursor= null;
- }
-
- return result;
- }
-
- public boolean hasNext() {
- return fCursor != null;
- }
-
- private IfStatement findStart(IfStatement item) {
- while (item.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
- item= (IfStatement)item.getParent();
- }
- return item;
- }
- }
-
- private static final class AddBlockOperation extends AbstractFixRewriteOperation {
-
- private final ChildPropertyDescriptor fBodyProperty;
- private final Statement fBody;
- private final Statement fControlStatement;
-
- public AddBlockOperation(ChildPropertyDescriptor bodyProperty, Statement body, Statement controlStatement) {
- fBodyProperty= bodyProperty;
- fBody= body;
- fControlStatement= controlStatement;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
- String label;
- if (fBodyProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
- label = FixMessages.CodeStyleFix_ChangeIfToBlock_desription;
- } else if (fBodyProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
- label = FixMessages.CodeStyleFix_ChangeElseToBlock_description;
- } else {
- label = FixMessages.CodeStyleFix_ChangeControlToBlock_description;
- }
-
- TextEditGroup group= createTextEditGroup(label);
- textEditGroups.add(group);
-
- ASTNode moveTarget= rewrite.createMoveTarget(fBody);
- Block replacingBody= cuRewrite.getRoot().getAST().newBlock();
- replacingBody.statements().add(moveTarget);
- rewrite.set(fControlStatement, fBodyProperty, replacingBody, group);
- }
-
- }
-
- static class RemoveBlockOperation extends AbstractFixRewriteOperation {
-
- private final Statement fStatement;
- private final ChildPropertyDescriptor fChild;
-
- public RemoveBlockOperation(Statement controlStatement, ChildPropertyDescriptor child) {
- fStatement= controlStatement;
- fChild= child;
- }
-
- /**
- * {@inheritDoc}
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
-
- Block block= (Block)fStatement.getStructuralProperty(fChild);
- Statement statement= (Statement)block.statements().get(0);
- Statement moveTarget= (Statement)rewrite.createMoveTarget(statement);
-
- TextEditGroup group= createTextEditGroup(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription);
- textEditGroups.add(group);
- rewrite.set(fStatement, fChild, moveTarget, group);
- }
-
- public static boolean satisfiesCleanUpPrecondition(Statement controlStatement, ChildPropertyDescriptor childDescriptor, boolean onlyReturnAndThrows) {
- return satisfiesPrecondition(controlStatement, childDescriptor, onlyReturnAndThrows, true);
- }
-
- public static boolean satisfiesQuickAssistPrecondition(Statement controlStatement, ChildPropertyDescriptor childDescriptor) {
- return satisfiesPrecondition(controlStatement, childDescriptor, false, false);
- }
-
- //Can the block around child with childDescriptor of controlStatement be removed?
- private static boolean satisfiesPrecondition(Statement controlStatement, ChildPropertyDescriptor childDescriptor, boolean onlyReturnAndThrows, boolean cleanUpCheck) {
- Object child= controlStatement.getStructuralProperty(childDescriptor);
-
- if (!(child instanceof Block))
- return false;
-
- Block block= (Block)child;
- List list= block.statements();
- if (list.size() != 1)
- return false;
-
- ASTNode singleStatement= (ASTNode)list.get(0);
-
- if (onlyReturnAndThrows)
- if (!(singleStatement instanceof ReturnStatement) && !(singleStatement instanceof ThrowStatement))
- return false;
-
- if (controlStatement instanceof IfStatement) {
- // if (true) {
- // while (true)
- // if (false)
- // ;
- // } else
- // ;
-
- if (((IfStatement)controlStatement).getThenStatement() != child)
- return true;//can always remove blocks in else part
-
- IfStatement ifStatement= (IfStatement)controlStatement;
- if (ifStatement.getElseStatement() == null)
- return true;//can always remove if no else part
-
- return !hasUnblockedIf((Statement)singleStatement, onlyReturnAndThrows, cleanUpCheck);
- } else {
- //if (true)
- // while (true) {
- // if (false)
- // ;
- // }
- //else
- // ;
- if (!hasUnblockedIf((Statement)singleStatement, onlyReturnAndThrows, cleanUpCheck))
- return true;
-
- ASTNode currentChild= controlStatement;
- ASTNode parent= currentChild.getParent();
- while (true) {
- Statement body= null;
- if (parent instanceof IfStatement) {
- body= ((IfStatement)parent).getThenStatement();
- if (body == currentChild && ((IfStatement)parent).getElseStatement() != null)//->currentChild is an unblocked then part
- return false;
- } else if (parent instanceof WhileStatement) {
- body= ((WhileStatement)parent).getBody();
- } else if (parent instanceof WithStatement) {
- body= ((WithStatement)parent).getBody();
- } else if (parent instanceof DoStatement) {
- body= ((DoStatement)parent).getBody();
- } else if (parent instanceof ForStatement) {
- body= ((ForStatement)parent).getBody();
- } else if (parent instanceof EnhancedForStatement) {
- body= ((EnhancedForStatement)parent).getBody();
- } else {
- return true;
- }
- if (body != currentChild)//->parents child is a block
- return true;
-
- currentChild= parent;
- parent= currentChild.getParent();
- }
- }
- }
-
- private static boolean hasUnblockedIf(Statement p, boolean onlyReturnAndThrows, boolean cleanUpCheck) {
- while (true) {
- if (p instanceof IfStatement) {
- return true;
- } else {
-
- ChildPropertyDescriptor childD= null;
- if (p instanceof WhileStatement) {
- childD= WhileStatement.BODY_PROPERTY;
- } else if (p instanceof WithStatement) {
- childD= WithStatement.BODY_PROPERTY;
- } else if (p instanceof ForStatement) {
- childD= ForStatement.BODY_PROPERTY;
- } else if (p instanceof EnhancedForStatement) {
- childD= EnhancedForStatement.BODY_PROPERTY;
- } else if (p instanceof DoStatement) {
- childD= DoStatement.BODY_PROPERTY;
- } else {
- return false;
- }
- Statement body= (Statement)p.getStructuralProperty(childD);
- if (body instanceof Block) {
- if (!cleanUpCheck) {
- return false;
- } else {
- if (!satisfiesPrecondition(p, childD, onlyReturnAndThrows, cleanUpCheck))
- return false;
-
- p= (Statement)((Block)body).statements().get(0);
- }
- } else {
- p= body;
- }
- }
- }
- }
-
- }
-
- public static IFix[] createRemoveBlockFix(JavaScriptUnit compilationUnit, ASTNode node) {
- Statement statement= ASTResolving.findParentStatement(node);
- if (statement == null) {
- return null;
- }
-
- if (statement instanceof Block) {
- Block block= (Block)statement;
- if (block.statements().size() != 1)
- return null;
-
- ASTNode parent= block.getParent();
- if (!(parent instanceof Statement))
- return null;
-
- statement= (Statement)parent;
- }
-
- if (statement instanceof IfStatement) {
- List result= new ArrayList();
-
- List removeAllList= new ArrayList();
-
- IfElseIterator iter= new IfElseIterator((IfStatement)statement);
- IfStatement item= null;
- while (iter.hasNext()) {
- item= iter.next();
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(item, IfStatement.THEN_STATEMENT_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(item, IfStatement.THEN_STATEMENT_PROPERTY);
- removeAllList.add(op);
- if (item == statement)
- result.add(new ControlStatementsFix(FixMessages.ControlStatementsFix_removeIfBlock_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op}));
- }
- }
-
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(item, IfStatement.ELSE_STATEMENT_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(item, IfStatement.ELSE_STATEMENT_PROPERTY);
- removeAllList.add(op);
- if (item == statement)
- result.add(new ControlStatementsFix(FixMessages.ControlStatementsFix_removeElseBlock_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op}));
- }
-
- if (removeAllList.size() > 1) {
- IFixRewriteOperation[] allConvert= (IFixRewriteOperation[])removeAllList.toArray(new IFixRewriteOperation[removeAllList.size()]);
- result.add(new ControlStatementsFix(FixMessages.ControlStatementsFix_removeIfElseBlock_proposalDescription, compilationUnit, allConvert));
- }
-
- return (IFix[])result.toArray(new IFix[result.size()]);
- } else if (statement instanceof WhileStatement) {
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(statement, WhileStatement.BODY_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(statement, WhileStatement.BODY_PROPERTY);
- return new IFix[] {new ControlStatementsFix(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op})};
- }
- } else if (statement instanceof ForStatement) {
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(statement, ForStatement.BODY_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(statement, ForStatement.BODY_PROPERTY);
- return new IFix[] {new ControlStatementsFix(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op})};
- }
- } else if (statement instanceof ForInStatement) {
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(statement, ForInStatement.BODY_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(statement, ForInStatement.BODY_PROPERTY);
- return new IFix[] {new ControlStatementsFix(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op})};
- }
- } else if (statement instanceof EnhancedForStatement) {
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(statement, EnhancedForStatement.BODY_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(statement, EnhancedForStatement.BODY_PROPERTY);
- return new IFix[] {new ControlStatementsFix(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op})};
- }
- } else if (statement instanceof DoStatement) {
- if (RemoveBlockOperation.satisfiesQuickAssistPrecondition(statement, DoStatement.BODY_PROPERTY)) {
- RemoveBlockOperation op= new RemoveBlockOperation(statement, DoStatement.BODY_PROPERTY);
- return new IFix[] {new ControlStatementsFix(FixMessages.ControlStatementsFix_removeBrackets_proposalDescription, compilationUnit, new IFixRewriteOperation[] {op})};
- }
- }
-
- return null;
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit,
- boolean convertSingleStatementToBlock,
- boolean removeUnnecessaryBlock,
- boolean removeUnnecessaryBlockContainingReturnOrThrow) throws CoreException {
-
- if (!convertSingleStatementToBlock && !removeUnnecessaryBlock && !removeUnnecessaryBlockContainingReturnOrThrow)
- return null;
-
- List operations= new ArrayList();
- ControlStatementFinder finder= new ControlStatementFinder(convertSingleStatementToBlock, removeUnnecessaryBlock, removeUnnecessaryBlockContainingReturnOrThrow, operations);
- compilationUnit.accept(finder);
-
- if (operations.isEmpty())
- return null;
-
- IFixRewriteOperation[] ops= (IFixRewriteOperation[])operations.toArray(new IFixRewriteOperation[operations.size()]);
- return new ControlStatementsFix(FixMessages.ControlStatementsFix_change_name, compilationUnit, ops);
- }
-
- protected ControlStatementsFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertForLoopOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertForLoopOperation.java
deleted file mode 100644
index 7093410e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertForLoopOperation.java
+++ /dev/null
@@ -1,639 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression.Operator;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TightSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-
-public class ConvertForLoopOperation extends ConvertLoopOperation {
-
- private static final String LENGTH_QUERY= "length"; //$NON-NLS-1$
- private static final String LITERAL_0= "0"; //$NON-NLS-1$
- private static final String LITERAL_1= "1"; //$NON-NLS-1$
- private static final class InvalidBodyError extends Error {
- private static final long serialVersionUID= 1L;
- }
-
- private IVariableBinding fIndexBinding;
- private IVariableBinding fLengthBinding;
- private IBinding fArrayBinding;
- private Expression fArrayAccess;
- private VariableDeclarationFragment fElementDeclaration;
- private final boolean fMakeFinal;
-
- public ConvertForLoopOperation(ForStatement forStatement) {
- this(forStatement, new String[0], false);
- }
-
- public ConvertForLoopOperation(ForStatement forStatement, String[] usedNames, boolean makeFinal) {
- super(forStatement, usedNames);
- fMakeFinal= makeFinal;
- }
-
- public IStatus satisfiesPreconditions() {
- ForStatement statement= getForStatement();
- JavaScriptUnit ast= (JavaScriptUnit)statement.getRoot();
-
- IJavaScriptElement javaElement= ast.getJavaElement();
- if (javaElement == null)
- return ERROR_STATUS;
-
- if (!JavaModelUtil.is50OrHigher(javaElement.getJavaScriptProject()))
- return ERROR_STATUS;
-
- if (!validateInitializers(statement))
- return ERROR_STATUS;
-
- if (!validateExpression(statement))
- return ERROR_STATUS;
-
- if (!validateUpdaters(statement))
- return ERROR_STATUS;
-
- if (!validateBody(statement))
- return ERROR_STATUS;
-
- return Status.OK_STATUS;
- }
-
- /**
- * Must be one of:
- * <ul>
- * <li>int [result]= 0;</li>
- * <li>int [result]= 0, [lengthBinding]= [arrayBinding].length;</li>
- * <li>int , [result]= 0;</li>
- * </ul>
- */
- private boolean validateInitializers(ForStatement statement) {
- List initializers= statement.initializers();
- if (initializers.size() != 1)
- return false;
-
- Expression expression= (Expression)initializers.get(0);
- if (!(expression instanceof VariableDeclarationExpression))
- return false;
-
- VariableDeclarationExpression declaration= (VariableDeclarationExpression)expression;
- ITypeBinding declarationBinding= declaration.resolveTypeBinding();
- if (declarationBinding == null)
- return false;
-
- if (!declarationBinding.isPrimitive())
- return false;
-
- if (!PrimitiveType.INT.toString().equals(declarationBinding.getQualifiedName()))
- return false;
-
- List fragments= declaration.fragments();
- if (fragments.size() == 1) {
- IVariableBinding indexBinding= getIndexBindingFromFragment((VariableDeclarationFragment)fragments.get(0));
- if (indexBinding == null)
- return false;
-
- fIndexBinding= indexBinding;
- return true;
- } else if (fragments.size() == 2) {
- IVariableBinding indexBinding= getIndexBindingFromFragment((VariableDeclarationFragment)fragments.get(0));
- if (indexBinding == null) {
- indexBinding= getIndexBindingFromFragment((VariableDeclarationFragment)fragments.get(1));
- if (indexBinding == null)
- return false;
-
- if (!validateLengthFragment((VariableDeclarationFragment)fragments.get(0)))
- return false;
- } else {
- if (!validateLengthFragment((VariableDeclarationFragment)fragments.get(1)))
- return false;
- }
-
- fIndexBinding= indexBinding;
- return true;
- }
- return false;
- }
-
- /**
- * [lengthBinding]= [arrayBinding].length
- */
- private boolean validateLengthFragment(VariableDeclarationFragment fragment) {
- Expression initializer= fragment.getInitializer();
- if (initializer == null)
- return false;
-
- if (!validateLengthQuery(initializer))
- return false;
-
- IVariableBinding lengthBinding= (IVariableBinding)fragment.getName().resolveBinding();
- if (lengthBinding == null)
- return false;
- fLengthBinding= lengthBinding;
-
- return true;
- }
-
- /**
- * Must be one of:
- * <ul>
- * <li>[result]= 0</li>
- * </ul>
- */
- private IVariableBinding getIndexBindingFromFragment(VariableDeclarationFragment fragment) {
- Expression initializer= fragment.getInitializer();
- if (!(initializer instanceof NumberLiteral))
- return null;
-
- NumberLiteral number= (NumberLiteral)initializer;
- if (!LITERAL_0.equals(number.getToken()))
- return null;
-
- return (IVariableBinding)fragment.getName().resolveBinding();
- }
-
- /**
- * Must be one of:
- * <ul>
- * <li>[indexBinding] < [result].length;</li>
- * <li>[result].length > [indexBinding];</li>
- * <li>[indexBinding] < [lengthBinding];</li>
- * <li>[lengthBinding] > [indexBinding];</li>
- * </ul>
- */
- private boolean validateExpression(ForStatement statement) {
- Expression expression= statement.getExpression();
- if (!(expression instanceof InfixExpression))
- return false;
-
- InfixExpression infix= (InfixExpression)expression;
-
- Expression left= infix.getLeftOperand();
- Expression right= infix.getRightOperand();
- if (left instanceof SimpleName && right instanceof SimpleName) {
- IVariableBinding lengthBinding= fLengthBinding;
- if (lengthBinding == null)
- return false;
-
- IBinding leftBinding= ((SimpleName)left).resolveBinding();
- IBinding righBinding= ((SimpleName)right).resolveBinding();
-
- if (fIndexBinding.equals(leftBinding)) {
- return lengthBinding.equals(righBinding);
- } else if (fIndexBinding.equals(righBinding)) {
- return lengthBinding.equals(leftBinding);
- }
-
- return false;
- } else if (left instanceof SimpleName) {
- if (!fIndexBinding.equals(((SimpleName)left).resolveBinding()))
- return false;
-
- if (!Operator.LESS.equals(infix.getOperator()))
- return false;
-
- return validateLengthQuery(right);
- } else if (right instanceof SimpleName) {
- if (!fIndexBinding.equals(((SimpleName)right).resolveBinding()))
- return false;
-
- if (!Operator.GREATER.equals(infix.getOperator()))
- return false;
-
- return validateLengthQuery(left);
- }
-
- return false;
- }
-
- /**
- * Must be one of:
- * <ul>
- * <li>[result].length</li>
- * </ul>
- */
- private boolean validateLengthQuery(Expression lengthQuery) {
- if (lengthQuery instanceof QualifiedName) {
- QualifiedName qualifiedName= (QualifiedName)lengthQuery;
- SimpleName name= qualifiedName.getName();
- if (!LENGTH_QUERY.equals(name.getIdentifier()))
- return false;
-
- Name arrayAccess= qualifiedName.getQualifier();
- ITypeBinding accessType= arrayAccess.resolveTypeBinding();
- if (accessType == null)
- return false;
-
- if (!accessType.isArray())
- return false;
-
- IBinding arrayBinding= arrayAccess.resolveBinding();
- if (arrayBinding == null)
- return false;
-
- fArrayBinding= arrayBinding;
- fArrayAccess= arrayAccess;
- return true;
- } else if (lengthQuery instanceof FieldAccess) {
- FieldAccess fieldAccess= (FieldAccess)lengthQuery;
- SimpleName name= fieldAccess.getName();
- if (!LENGTH_QUERY.equals(name.getIdentifier()))
- return false;
-
- Expression arrayAccess= fieldAccess.getExpression();
- ITypeBinding accessType= arrayAccess.resolveTypeBinding();
- if (accessType == null)
- return false;
-
- if (!accessType.isArray())
- return false;
-
- IBinding arrayBinding= getBinding(arrayAccess);
- if (arrayBinding == null)
- return false;
-
- fArrayBinding= arrayBinding;
- fArrayAccess= arrayAccess;
- return true;
- }
-
- return false;
- }
-
- /**
- * Must be one of:
- * <ul>
- * <li>[indexBinding]++</li>
- * <li>[indexBinding]+= 1</li>
- * <li>[indexBinding]= [indexBinding] + 1</li>
- * <li>[indexBinding]= 1 + [indexBinding]</li>
- * <ul>
- */
- private boolean validateUpdaters(ForStatement statement) {
- List updaters= statement.updaters();
- if (updaters.size() != 1)
- return false;
-
- Expression updater= (Expression)updaters.get(0);
- if (updater instanceof PostfixExpression) {
- PostfixExpression postfix= (PostfixExpression)updater;
-
- if (!PostfixExpression.Operator.INCREMENT.equals(postfix.getOperator()))
- return false;
-
- IBinding binding= getBinding(postfix.getOperand());
- if (!fIndexBinding.equals(binding))
- return false;
-
- return true;
- } else if (updater instanceof Assignment) {
- Assignment assignment= (Assignment)updater;
- Expression left= assignment.getLeftHandSide();
- IBinding binding= getBinding(left);
- if (!fIndexBinding.equals(binding))
- return false;
-
- if (Assignment.Operator.PLUS_ASSIGN.equals(assignment.getOperator())) {
- return isOneLiteral(assignment.getRightHandSide());
- } else if (Assignment.Operator.ASSIGN.equals(assignment.getOperator())) {
- Expression right= assignment.getRightHandSide();
- if (!(right instanceof InfixExpression))
- return false;
-
- InfixExpression infixExpression= (InfixExpression)right;
- Expression leftOperand= infixExpression.getLeftOperand();
- IBinding leftBinding= getBinding(leftOperand);
- Expression rightOperand= infixExpression.getRightOperand();
- IBinding rightBinding= getBinding(rightOperand);
-
- if (fIndexBinding.equals(leftBinding)) {
- return isOneLiteral(rightOperand);
- } else if (fIndexBinding.equals(rightBinding)) {
- return isOneLiteral(leftOperand);
- }
- }
- }
- return false;
- }
-
- private boolean isOneLiteral(Expression expression) {
- if (!(expression instanceof NumberLiteral))
- return false;
-
- NumberLiteral literal= (NumberLiteral)expression;
- return LITERAL_1.equals(literal.getToken());
- }
-
- /**
- * returns false iff
- * <ul>
- * <li><code>indexBinding</code> is used for anything else then accessing
- * an element of <code>arrayBinding</code></li>
- * <li><code>arrayBinding</code> is assigned</li>
- * <li>an element of <code>arrayBinding</code> is assigned</li>
- * <li><code>lengthBinding</code> is referenced</li>
- * </ul>
- * within <code>body</code>
- */
- private boolean validateBody(ForStatement statement) {
- Statement body= statement.getBody();
- try {
- body.accept(new GenericVisitor() {
- /**
- * {@inheritDoc}
- */
- protected boolean visitNode(ASTNode node) {
- if (node instanceof Name) {
- Name name= (Name)node;
- IBinding nameBinding= name.resolveBinding();
- if (nameBinding == null)
- throw new InvalidBodyError();
-
- if (nameBinding.equals(fIndexBinding)) {
- if (node.getLocationInParent() != ArrayAccess.INDEX_PROPERTY)
- throw new InvalidBodyError();
-
- ArrayAccess arrayAccess= (ArrayAccess)node.getParent();
- Expression array= arrayAccess.getArray();
-
- IBinding binding= getBinding(array);
- if (binding == null)
- throw new InvalidBodyError();
-
- if (!fArrayBinding.equals(binding))
- throw new InvalidBodyError();
-
- } else if (nameBinding.equals(fArrayBinding)) {
- ASTNode current= node;
- while (current != null && !(current instanceof Statement)) {
- if (current.getLocationInParent() == Assignment.LEFT_HAND_SIDE_PROPERTY)
- throw new InvalidBodyError();
-
- if (current instanceof PrefixExpression)
- throw new InvalidBodyError();
-
- if (current instanceof PostfixExpression)
- throw new InvalidBodyError();
-
- current= current.getParent();
- }
- } else if (nameBinding.equals(fLengthBinding)) {
- throw new InvalidBodyError();
- }
- }
-
- return true;
- }
-
- public boolean visit(ArrayAccess node) {
- if (fElementDeclaration != null)
- return super.visit(node);
-
- IBinding binding= getBinding(node.getArray());
- if (fArrayBinding.equals(binding)) {
- IBinding index= getBinding(node.getIndex());
- if (fIndexBinding.equals(index)) {
- if (node.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
- fElementDeclaration= (VariableDeclarationFragment)node.getParent();
- }
- }
- }
- return super.visit(node);
- }
-
- });
- } catch (InvalidBodyError e) {
- return false;
- }
-
- return true;
- }
-
- private static IBinding getBinding(Expression expression) {
- if (expression instanceof FieldAccess) {
- return ((FieldAccess)expression).resolveFieldBinding();
- } else if (expression instanceof Name) {
- return ((Name)expression).resolveBinding();
- }
-
- return null;
- }
-
- public String getIntroducedVariableName() {
- if (fElementDeclaration != null) {
- return fElementDeclaration.getName().getIdentifier();
- } else {
- ForStatement forStatement= getForStatement();
- IJavaScriptProject javaProject= ((JavaScriptUnit)forStatement.getRoot()).getJavaElement().getJavaScriptProject();
- String[] proposals= getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
- return proposals[0];
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.LinkedFix.ILinkedFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups, LinkedProposalModel positionGroups) throws CoreException {
- TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description);
- textEditGroups.add(group);
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
-
- TightSourceRangeComputer rangeComputer;
- if (rewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
- rangeComputer= (TightSourceRangeComputer)rewrite.getExtendedSourceRangeComputer();
- } else {
- rangeComputer= new TightSourceRangeComputer();
- }
- rangeComputer.addTightSourceNode(getForStatement());
- rewrite.setTargetSourceRangeComputer(rangeComputer);
-
- Statement statement= convert(cuRewrite, group, positionGroups);
- rewrite.replace(getForStatement(), statement, group);
- }
-
- protected Statement convert(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException {
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
- ImportRewrite importRewrite= cuRewrite.getImportRewrite();
-
- ForStatement forStatement= getForStatement();
-
- IJavaScriptProject javaProject= ((JavaScriptUnit)forStatement.getRoot()).getJavaElement().getJavaScriptProject();
- String[] proposals= getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
-
- String parameterName;
- if (fElementDeclaration != null) {
- parameterName= fElementDeclaration.getName().getIdentifier();
- } else {
- parameterName= proposals[0];
- }
-
- LinkedProposalPositionGroup pg= positionGroups.getPositionGroup(parameterName, true);
- if (fElementDeclaration != null)
- pg.addProposal(parameterName, null, 10);
- for (int i= 0; i < proposals.length; i++) {
- pg.addProposal(proposals[i], null, 10);
- }
-
- AST ast= forStatement.getAST();
- EnhancedForStatement result= ast.newEnhancedForStatement();
-
- SingleVariableDeclaration parameterDeclaration= createParameterDeclaration(parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal);
- result.setParameter(parameterDeclaration);
-
- result.setExpression((Expression)rewrite.createCopyTarget(fArrayAccess));
-
- convertBody(forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
- result.setBody(getBody(cuRewrite, group, positionGroups));
-
- positionGroups.setEndPosition(rewrite.track(result));
-
- return result;
- }
-
- private void convertBody(Statement body, final IBinding indexBinding, final IBinding arrayBinding, final String parameterName, final ASTRewrite rewrite, final TextEditGroup editGroup, final LinkedProposalPositionGroup pg) {
- final AST ast= body.getAST();
-
- final HashSet assignedBindings= new HashSet();
-
- body.accept(new GenericVisitor() {
- public boolean visit(ArrayAccess node) {
- IBinding binding= getBinding(node.getArray());
- if (arrayBinding.equals(binding)) {
- IBinding index= getBinding(node.getIndex());
- if (indexBinding.equals(index)) {
- replaceAccess(node);
- }
- }
-
- return super.visit(node);
- }
-
- public boolean visit(SimpleName node) {
- if (assignedBindings.contains(node.resolveBinding())) {
- replaceAccess(node);
- }
- return super.visit(node);
- }
-
- private void replaceAccess(ASTNode node) {
- if (node.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)node.getParent();
- IBinding targetBinding= fragment.getName().resolveBinding();
- if (targetBinding != null) {
- assignedBindings.add(targetBinding);
-
- VariableDeclarationStatement statement= (VariableDeclarationStatement)fragment.getParent();
-
- if (statement.fragments().size() == 1) {
- rewrite.remove(statement, editGroup);
- } else {
- ListRewrite listRewrite= rewrite.getListRewrite(statement, VariableDeclarationStatement.FRAGMENTS_PROPERTY);
- listRewrite.remove(fragment, editGroup);
- }
-
- } else {
- SimpleName name= ast.newSimpleName(parameterName);
- rewrite.replace(node, name, editGroup);
- pg.addPosition(rewrite.track(name), true);
- }
- } else {
- SimpleName name= ast.newSimpleName(parameterName);
- rewrite.replace(node, name, editGroup);
- pg.addPosition(rewrite.track(name), true);
- }
- }
- });
- }
-
- private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
- JavaScriptUnit compilationUnit= (JavaScriptUnit)arrayAccess.getRoot();
- AST ast= compilationUnit.getAST();
-
- SingleVariableDeclaration result= ast.newSingleVariableDeclaration();
-
- SimpleName name= ast.newSimpleName(parameterName);
- pg.addPosition(rewrite.track(name), true);
- result.setName(name);
-
- ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
- Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
- if (arrayTypeBinding.getDimensions() != 1) {
- type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
- }
- result.setType(type);
-
- if (fragement != null) {
- VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
- ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
- }
- if (makeFinal) {
- ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
- }
-
- return result;
- }
-
- private String[] getVariableNameProposals(ITypeBinding arrayTypeBinding, IJavaScriptProject project) {
- String[] variableNames= getUsedVariableNames();
- String[] elementSuggestions= StubUtility.getLocalNameSuggestions(project, FOR_LOOP_ELEMENT_IDENTIFIER, 0, variableNames);
-
- String type= arrayTypeBinding.getElementType().getName();
- String[] typeSuggestions= StubUtility.getLocalNameSuggestions(project, type, arrayTypeBinding.getDimensions() - 1, variableNames);
-
- String[] result= new String[elementSuggestions.length + typeSuggestions.length];
- System.arraycopy(elementSuggestions, 0, result, 0, elementSuggestions.length);
- System.arraycopy(typeSuggestions, 0, result, elementSuggestions.length, typeSuggestions.length);
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertIterableLoopOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertIterableLoopOperation.java
deleted file mode 100644
index e932fb4d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertIterableLoopOperation.java
+++ /dev/null
@@ -1,562 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ImportRemover;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TightSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-/**
- * Operation to convert for loops over iterables to enhanced for loops.
- *
- *
- */
-public final class ConvertIterableLoopOperation extends ConvertLoopOperation {
-
- /**
- * Returns the supertype of the given type with the qualified name.
- *
- * @param binding
- * the binding of the type
- * @param name
- * the qualified name of the supertype
- * @return the supertype, or <code>null</code>
- */
- private static ITypeBinding getSuperType(final ITypeBinding binding, final String name) {
-
- if (binding.isArray() || binding.isPrimitive())
- return null;
-
- if (binding.getQualifiedName().startsWith(name))
- return binding;
-
- final ITypeBinding type= binding.getSuperclass();
- if (type != null) {
- final ITypeBinding result= getSuperType(type, name);
- if (result != null)
- return result;
- }
- return null;
- }
-
- /** Has the element variable been assigned outside the for statement? */
- private boolean fAssigned= false;
-
- /** The binding of the element variable */
- private IBinding fElement= null;
-
- /** The node of the iterable object used in the expression */
- private Expression fExpression= null;
-
- /** The binding of the iterable object */
- private IBinding fIterable= null;
-
- /** Is the iterator method invoked on <code>this</code>? */
- private boolean fThis= false;
-
- /** The binding of the iterator variable */
- private IVariableBinding fIterator= null;
-
- /** The nodes of the element variable occurrences */
- private final List fOccurrences= new ArrayList(2);
-
- private EnhancedForStatement fEnhancedForLoop;
-
- private final boolean fMakeFinal;
-
- public ConvertIterableLoopOperation(ForStatement statement) {
- this(statement, new String[0], false);
- }
-
- public ConvertIterableLoopOperation(ForStatement statement, String[] usedNames, boolean makeFinal) {
- super(statement, usedNames);
- fMakeFinal= makeFinal;
- }
-
- public String getIntroducedVariableName() {
- if (fElement != null) {
- return fElement.getName();
- } else {
- return getVariableNameProposals()[0];
- }
- }
-
- private String[] getVariableNameProposals() {
-
- String[] variableNames= getUsedVariableNames();
- String[] elementSuggestions= StubUtility.getLocalNameSuggestions(getJavaProject(), FOR_LOOP_ELEMENT_IDENTIFIER, 0, variableNames);
-
- return elementSuggestions;
- }
-
- private IJavaScriptProject getJavaProject() {
- return getRoot().getJavaElement().getJavaScriptProject();
- }
-
- private JavaScriptUnit getRoot() {
- return (JavaScriptUnit)getForStatement().getRoot();
- }
-
- /**
- * Returns the expression for the enhanced for statement.
- *
- * @param rewrite
- * the AST rewrite to use
- * @return the expression node, or <code>null</code>
- */
- private Expression getExpression(final ASTRewrite rewrite) {
- if (fThis)
- return rewrite.getAST().newThisExpression();
- if (fExpression instanceof FunctionInvocation)
- return (FunctionInvocation)rewrite.createMoveTarget(fExpression);
- return (Expression)ASTNode.copySubtree(rewrite.getAST(), fExpression);
- }
-
- /**
- * Returns the iterable type from the iterator type binding.
- *
- * @param iterator
- * the iterator type binding, or <code>null</code>
- * @return the iterable type
- */
- private ITypeBinding getIterableType(final ITypeBinding iterator) {
- return getRoot().getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.LinkedFix.ILinkedFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups, final LinkedProposalModel positionGroups) throws CoreException {
- final TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description);
- textEditGroups.add(group);
-
- final ASTRewrite astRewrite= cuRewrite.getASTRewrite();
-
- TightSourceRangeComputer rangeComputer;
- if (astRewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
- rangeComputer= (TightSourceRangeComputer)astRewrite.getExtendedSourceRangeComputer();
- } else {
- rangeComputer= new TightSourceRangeComputer();
- }
- rangeComputer.addTightSourceNode(getForStatement());
- astRewrite.setTargetSourceRangeComputer(rangeComputer);
-
- Statement statement= convert(cuRewrite, group, positionGroups);
- astRewrite.replace(getForStatement(), statement, group);
- }
-
- protected Statement convert(CompilationUnitRewrite cuRewrite, final TextEditGroup group, final LinkedProposalModel positionGroups) throws CoreException {
- final AST ast= cuRewrite.getAST();
- final ASTRewrite astRewrite= cuRewrite.getASTRewrite();
- final ImportRewrite importRewrite= cuRewrite.getImportRewrite();
- final ImportRemover remover= cuRewrite.getImportRemover();
-
- fEnhancedForLoop= ast.newEnhancedForStatement();
- String[] names= getVariableNameProposals();
-
- String name;
- if (fElement != null) {
- name= fElement.getName();
- } else {
- name= names[0];
- }
- final LinkedProposalPositionGroup pg= positionGroups.getPositionGroup(name, true);
- if (fElement != null)
- pg.addProposal(name, null, 10);
- for (int i= 0; i < names.length; i++) {
- pg.addProposal(names[i], null, 10);
- }
-
- final Statement body= getForStatement().getBody();
- if (body != null) {
- final ListRewrite list;
- if (body instanceof Block) {
- list= astRewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
- for (final Iterator iterator= fOccurrences.iterator(); iterator.hasNext();) {
- final Statement parent= (Statement)ASTNodes.getParent((ASTNode)iterator.next(), Statement.class);
- if (parent != null && list.getRewrittenList().contains(parent)) {
- list.remove(parent, null);
- remover.registerRemovedNode(parent);
- }
- }
- } else {
- list= null;
- }
- final String text= name;
- body.accept(new ASTVisitor() {
-
- private boolean replace(final Expression expression) {
- final SimpleName node= ast.newSimpleName(text);
- astRewrite.replace(expression, node, group);
- remover.registerRemovedNode(expression);
- pg.addPosition(astRewrite.track(node), false);
- return false;
- }
-
- public final boolean visit(final FunctionInvocation node) {
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null && (binding.getName().equals("next") || binding.getName().equals("nextElement"))) { //$NON-NLS-1$ //$NON-NLS-2$
- final Expression expression= node.getExpression();
- if (expression instanceof Name) {
- final IBinding result= ((Name)expression).resolveBinding();
- if (result != null && result.equals(fIterator))
- return replace(node);
- } else if (expression instanceof FieldAccess) {
- final IBinding result= ((FieldAccess)expression).resolveFieldBinding();
- if (result != null && result.equals(fIterator))
- return replace(node);
- }
- }
- return super.visit(node);
- }
-
- public final boolean visit(final SimpleName node) {
- if (fElement != null) {
- final IBinding binding= node.resolveBinding();
- if (binding != null && binding.equals(fElement)) {
- final Statement parent= (Statement)ASTNodes.getParent(node, Statement.class);
- if (parent != null && (list == null || list.getRewrittenList().contains(parent)))
- pg.addPosition(astRewrite.track(node), false);
- }
- }
- return false;
- }
- });
-
- fEnhancedForLoop.setBody(getBody(cuRewrite, group, positionGroups));
- }
- final SingleVariableDeclaration declaration= ast.newSingleVariableDeclaration();
- final SimpleName simple= ast.newSimpleName(name);
- pg.addPosition(astRewrite.track(simple), true);
- declaration.setName(simple);
- final ITypeBinding iterable= getIterableType(fIterator.getType());
- declaration.setType(importType(iterable, getForStatement(), importRewrite, getRoot()));
- if (fMakeFinal) {
- ModifierRewrite.create(astRewrite, declaration).setModifiers(Modifier.FINAL, 0, group);
- }
- remover.registerAddedImport(iterable.getQualifiedName());
- fEnhancedForLoop.setParameter(declaration);
- fEnhancedForLoop.setExpression(getExpression(astRewrite));
-
- remover.registerRemovedNode(getForStatement().getExpression());
- for (Iterator iterator= getForStatement().initializers().iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- remover.registerRemovedNode(node);
- }
- for (Iterator iterator= getForStatement().updaters().iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- remover.registerRemovedNode(node);
- }
-
- return fEnhancedForLoop;
- }
-
- /**
- * Is this proposal applicable?
- *
- * @return A status with severity <code>IStatus.Error</code> if not
- * applicable
- */
- public final IStatus satisfiesPreconditions() {
- IStatus resultStatus= StatusInfo.OK_STATUS;
- if (JavaModelUtil.is50OrHigher(getJavaProject())) {
- resultStatus= checkExpressionCondition();
- if (resultStatus.getSeverity() == IStatus.ERROR)
- return resultStatus;
-
- List updateExpressions= (List)getForStatement().getStructuralProperty(ForStatement.UPDATERS_PROPERTY);
- if (updateExpressions.size() == 1) {
- resultStatus= new StatusInfo(IStatus.WARNING, Messages.format(FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpression_Warning, ((Expression)updateExpressions.get(0)).toString()));
- } else if (updateExpressions.size() > 1) {
- resultStatus= new StatusInfo(IStatus.WARNING, FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning);
- }
-
- for (final Iterator outer= getForStatement().initializers().iterator(); outer.hasNext();) {
- final Expression initializer= (Expression)outer.next();
- if (initializer instanceof VariableDeclarationExpression) {
- final VariableDeclarationExpression declaration= (VariableDeclarationExpression)initializer;
- List fragments= declaration.fragments();
- if (fragments.size() != 1) {
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- } else {
- final VariableDeclarationFragment fragment= (VariableDeclarationFragment)fragments.get(0);
- fragment.accept(new ASTVisitor() {
-
- public final boolean visit(final FunctionInvocation node) {
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null) {
- final ITypeBinding type= binding.getReturnType();
- if (type != null) {
- final String qualified= type.getQualifiedName();
- if (qualified.startsWith("java.util.Enumeration<") || qualified.startsWith("java.util.Iterator<")) { //$NON-NLS-1$ //$NON-NLS-2$
- final Expression qualifier= node.getExpression();
- if (qualifier != null) {
- final ITypeBinding resolved= qualifier.resolveTypeBinding();
- if (resolved != null) {
- final ITypeBinding iterable= getSuperType(resolved, "java.lang.Iterable"); //$NON-NLS-1$
- if (iterable != null) {
- fExpression= qualifier;
- if (qualifier instanceof Name) {
- final Name name= (Name)qualifier;
- fIterable= name.resolveBinding();
- } else if (qualifier instanceof FunctionInvocation) {
- final FunctionInvocation invocation= (FunctionInvocation)qualifier;
- fIterable= invocation.resolveMethodBinding();
- } else if (qualifier instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess)qualifier;
- fIterable= access.resolveFieldBinding();
- } else if (qualifier instanceof ThisExpression)
- fIterable= resolved;
- }
- }
- } else {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null) {
- final ITypeBinding superBinding= getSuperType(declaring, "java.lang.Iterable"); //$NON-NLS-1$
- if (superBinding != null) {
- fIterable= superBinding;
- fThis= true;
- }
- }
- }
- }
- }
- }
- return true;
- }
-
- public final boolean visit(final VariableDeclarationFragment node) {
- final IVariableBinding binding= node.resolveBinding();
- if (binding != null) {
- final ITypeBinding type= binding.getType();
- if (type != null) {
- ITypeBinding iterator= getSuperType(type, "java.util.Iterator"); //$NON-NLS-1$
- if (iterator != null)
- fIterator= binding;
- else {
- iterator= getSuperType(type, "java.util.Enumeration"); //$NON-NLS-1$
- if (iterator != null)
- fIterator= binding;
- }
- }
- }
- return true;
- }
- });
- }
- }
- }
- final Statement statement= getForStatement().getBody();
- final boolean[] otherInvocationThenNext= new boolean[] {false};
- final int[] nextInvocationCount= new int[] {0};
- if (statement != null && fIterator != null) {
- final ITypeBinding iterable= getIterableType(fIterator.getType());
- statement.accept(new ASTVisitor() {
-
- public final boolean visit(final Assignment node) {
- return visit(node.getLeftHandSide(), node.getRightHandSide());
- }
-
- private boolean visit(final Expression node) {
- if (node != null) {
- final ITypeBinding binding= node.resolveTypeBinding();
- if (binding != null && iterable.equals(binding)) {
- if (node instanceof Name) {
- final Name name= (Name)node;
- final IBinding result= name.resolveBinding();
- if (result != null) {
- fOccurrences.add(node);
- fElement= result;
- return false;
- }
- } else if (node instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess)node;
- final IBinding result= access.resolveFieldBinding();
- if (result != null) {
- fOccurrences.add(node);
- fElement= result;
- return false;
- }
- }
- }
- }
- return true;
- }
-
- private boolean visit(final Expression left, final Expression right) {
- if (right instanceof FunctionInvocation) {
-// final FunctionInvocation invocation= (FunctionInvocation)right;
-// final IFunctionBinding binding= invocation.resolveMethodBinding();
-// if (binding != null && (binding.getName().equals("next") || binding.getName().equals("nextElement"))) { //$NON-NLS-1$ //$NON-NLS-2$
-// final Expression expression= invocation.getExpression();
-// if (expression instanceof Name) {
-// final Name qualifier= (Name)expression;
-// final IBinding result= qualifier.resolveBinding();
-// if (result != null && result.equals(fIterator)) {
-// nextInvocationCount[0]++;
-// return visit(left);
-// }
-// } else if (expression instanceof FieldAccess) {
-// final FieldAccess qualifier= (FieldAccess)expression;
-// final IBinding result= qualifier.resolveFieldBinding();
-// if (result != null && result.equals(fIterator)) {
-// nextInvocationCount[0]++;
-// return visit(left);
-// }
-// }
-// } else {
-// return visit(invocation);
-// }
- } else if (right instanceof NullLiteral || right instanceof UndefinedLiteral)
- return visit(left);
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(FunctionInvocation invocation) {
- final IFunctionBinding binding= invocation.resolveMethodBinding();
- if (binding != null) {
- final Expression expression= invocation.getExpression();
- if (expression instanceof Name) {
- final Name qualifier= (Name)expression;
- final IBinding result= qualifier.resolveBinding();
- if (result != null && result.equals(fIterator)) {
-// if (!binding.getName().equals("next") && !binding.getName().equals("nextElement")) { //$NON-NLS-1$ //$NON-NLS-2$
-// otherInvocationThenNext[0]= true;
-// } else {
-// nextInvocationCount[0]++;
-// }
- }
- } else if (expression instanceof FieldAccess) {
- final FieldAccess qualifier= (FieldAccess)expression;
- final IBinding result= qualifier.resolveFieldBinding();
- if (result != null && result.equals(fIterator)) {
-// if (!binding.getName().equals("next") && !binding.getName().equals("nextElement")) { //$NON-NLS-1$ //$NON-NLS-2$
-// otherInvocationThenNext[0]= true;
-// } else {
-// nextInvocationCount[0]++;
-// }
- }
- }
- }
- return false;
- }
-
- public final boolean visit(final VariableDeclarationFragment node) {
- return visit(node.getName(), node.getInitializer());
- }
- });
- if (otherInvocationThenNext[0])
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
-
- if (nextInvocationCount[0] > 1)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- }
- final ASTNode root= getForStatement().getRoot();
- if (root != null) {
- root.accept(new ASTVisitor() {
-
- public final boolean visit(final ForStatement node) {
- return false;
- }
-
- public final boolean visit(final SimpleName node) {
- final IBinding binding= node.resolveBinding();
- if (binding != null && binding.equals(fElement))
- fAssigned= true;
- return false;
- }
- });
- }
- }
- if ((fExpression != null || fThis) && fIterable != null && fIterator != null && !fAssigned) {
- return resultStatus;
- } else {
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- }
- }
-
- private IStatus checkExpressionCondition() {
- String warningLable= FixMessages.ConvertIterableLoopOperation_semanticChangeWarning;
-
- Expression expression= getForStatement().getExpression();
- if (!(expression instanceof FunctionInvocation))
- return new StatusInfo(IStatus.WARNING, warningLable);
-
- FunctionInvocation invoc= (FunctionInvocation)expression;
- IFunctionBinding methodBinding= invoc.resolveMethodBinding();
- if (methodBinding == null)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
-
- ITypeBinding declaringClass= methodBinding.getDeclaringClass();
- if (declaringClass == null)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
-
-// String qualifiedName= declaringClass.getQualifiedName();
-// String methodName= invoc.getName().getIdentifier();
-// if (qualifiedName.startsWith("java.util.Enumeration")) { //$NON-NLS-1$
-// if (!methodName.equals("hasMoreElements")) //$NON-NLS-1$
-// return new StatusInfo(IStatus.WARNING, warningLable);
-// } else if (qualifiedName.startsWith("java.util.Iterator")) { //$NON-NLS-1$
-// if (!methodName.equals("hasNext")) //$NON-NLS-1$
-// return new StatusInfo(IStatus.WARNING, warningLable);
-// } else {
-// return new StatusInfo(IStatus.WARNING, warningLable);
-// }
-
- return StatusInfo.OK_STATUS;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopFix.java
deleted file mode 100644
index 15810449..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopFix.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- **/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-public class ConvertLoopFix extends LinkedFix {
-
- private final static class ControlStatementFinder extends GenericVisitor {
-
- //private final List/*<IFixRewriteOperation>*/fResult;
- private final Hashtable fUsedNames;
- private final boolean fFindForLoopsToConvert;
- private final boolean fConvertIterableForLoops;
- //private final boolean fMakeFinal;
-
- public ControlStatementFinder(boolean findForLoopsToConvert, boolean convertIterableForLoops, boolean makeFinal, List resultingCollection) {
- fFindForLoopsToConvert= findForLoopsToConvert;
- fConvertIterableForLoops= convertIterableForLoops;
- //fMakeFinal= makeFinal;
- //fResult= resultingCollection;
- fUsedNames= new Hashtable();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visit(org.eclipse.wst.jsdt.core.dom.ForStatement)
- */
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ForStatement)
- */
- public void endVisit(ForStatement node) {
- if (fFindForLoopsToConvert || fConvertIterableForLoops) {
- fUsedNames.remove(node);
- }
- super.endVisit(node);
- }
-
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit, boolean convertForLoops, boolean convertIterableForLoops, boolean makeFinal) {
- if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaScriptProject()))
- return null;
-
- if (!convertForLoops && !convertIterableForLoops)
- return null;
-
- List operations= new ArrayList();
- ControlStatementFinder finder= new ControlStatementFinder(convertForLoops, convertIterableForLoops, makeFinal, operations);
- compilationUnit.accept(finder);
-
- if (operations.isEmpty())
- return null;
-
- IFixRewriteOperation[] ops= (IFixRewriteOperation[])operations.toArray(new IFixRewriteOperation[operations.size()]);
- return new ConvertLoopFix(FixMessages.ControlStatementsFix_change_name, compilationUnit, ops);
- }
-
-
- public static IFix createConvertIterableLoopToEnhancedFix(JavaScriptUnit compilationUnit, ForStatement loop) {
- ConvertIterableLoopOperation loopConverter= new ConvertIterableLoopOperation(loop);
- IStatus status= loopConverter.satisfiesPreconditions();
- if (status.getSeverity() == IStatus.ERROR)
- return null;
-
- ConvertLoopFix result= new ConvertLoopFix(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, compilationUnit, new ILinkedFixRewriteOperation[] {loopConverter});
- result.setStatus(status);
- return result;
- }
-
- protected ConvertLoopFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopOperation.java
deleted file mode 100644
index 380499c8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ConvertLoopOperation.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- **/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedFix.AbstractLinkedFixRewriteOperation;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public abstract class ConvertLoopOperation extends AbstractLinkedFixRewriteOperation {
-
- protected static final String FOR_LOOP_ELEMENT_IDENTIFIER= "element"; //$NON-NLS-1$
-
- protected static final IStatus ERROR_STATUS= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), ""); //$NON-NLS-1$
-
- private final ForStatement fStatement;
- private ConvertLoopOperation fOperation;
- private final String[] fUsedNames;
-
- public ConvertLoopOperation(ForStatement statement, String[] usedNames) {
- fStatement= statement;
- fUsedNames= usedNames;
- }
-
- public void setBodyConverter(ConvertLoopOperation operation) {
- fOperation= operation;
- }
-
- public abstract String getIntroducedVariableName();
-
- public abstract IStatus satisfiesPreconditions();
-
- protected abstract Statement convert(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException;
-
- protected ForStatement getForStatement() {
- return fStatement;
- }
-
- protected Statement getBody(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException {
- if (fOperation != null) {
- return fOperation.convert(cuRewrite, group, positionGroups);
- } else {
- return (Statement)cuRewrite.getASTRewrite().createMoveTarget(getForStatement().getBody());
- }
- }
-
- protected String[] getUsedVariableNames() {
- final List results= new ArrayList();
-
- ForStatement forStatement= getForStatement();
- JavaScriptUnit root= (JavaScriptUnit)forStatement.getRoot();
-
- Collection variableNames= new ScopeAnalyzer(root).getUsedVariableNames(forStatement.getStartPosition(), forStatement.getLength());
- results.addAll(variableNames);
-
- forStatement.accept(new GenericVisitor() {
- public boolean visit(SingleVariableDeclaration node) {
- results.add(node.getName().getIdentifier());
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationFragment fragment) {
- results.add(fragment.getName().getIdentifier());
- return super.visit(fragment);
- }
- });
-
- results.addAll(Arrays.asList(fUsedNames));
-
- return (String[])results.toArray(new String[results.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ExpressionsFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ExpressionsFix.java
deleted file mode 100644
index 68502d2c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ExpressionsFix.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression.Operator;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-
-public class ExpressionsFix extends AbstractFix {
-
- private static final class MissingParenthesisVisitor extends ASTVisitor {
-
- private final ArrayList fNodes;
-
- private MissingParenthesisVisitor(ArrayList nodes) {
- fNodes= nodes;
- }
-
- public void postVisit(ASTNode node) {
- // check that parent is && or ||
- if (!(node.getParent() instanceof InfixExpression))
- return;
-
- // we want to add parenthesis around arithmetic operators and instanceof
- boolean needParenthesis = false;
- if (node instanceof InfixExpression) {
- InfixExpression expression = (InfixExpression) node;
- InfixExpression.Operator operator = expression.getOperator();
-
- InfixExpression parentExpression = (InfixExpression) node.getParent();
- InfixExpression.Operator parentOperator = parentExpression.getOperator();
-
- if (parentOperator == operator)
- return;
-
- needParenthesis= (operator == InfixExpression.Operator.LESS)
- || (operator == InfixExpression.Operator.GREATER)
- || (operator == InfixExpression.Operator.LESS_EQUALS)
- || (operator == InfixExpression.Operator.GREATER_EQUALS)
- || (operator == InfixExpression.Operator.EQUALS)
- || (operator == InfixExpression.Operator.NOT_EQUALS)
-
- || (operator == InfixExpression.Operator.CONDITIONAL_AND)
- || (operator == InfixExpression.Operator.CONDITIONAL_OR);
- }
- if (node instanceof InstanceofExpression) {
- needParenthesis = true;
- }
- if (!needParenthesis) {
- return;
- }
- fNodes.add(node);
- }
- }
-
- private static final class UnnecessaryParenthesisVisitor extends ASTVisitor {
- private final ArrayList fNodes;
-
- private UnnecessaryParenthesisVisitor(ArrayList nodes) {
- fNodes= nodes;
- }
-
- public void postVisit(ASTNode node) {
- if (!(node instanceof ParenthesizedExpression)) {
- return;
- }
- ParenthesizedExpression parenthesizedExpression= (ParenthesizedExpression) node;
- Expression expression= parenthesizedExpression.getExpression();
- while (expression instanceof ParenthesizedExpression) {
- expression= ((ParenthesizedExpression) expression).getExpression();
- }
- // if this is part of another expression, check for this and parent precedences
- if (parenthesizedExpression.getParent() instanceof Expression) {
- Expression parentExpression= (Expression) parenthesizedExpression.getParent();
- int expressionPrecedence= getExpressionPrecedence(expression);
- int parentPrecedence= getExpressionPrecedence(parentExpression);
- if ((expressionPrecedence > parentPrecedence)
- && !(parenthesizedExpression.getParent() instanceof ParenthesizedExpression)) {
- return;
- }
- // check for case when precedences for expression and parent are same
- if ((expressionPrecedence == parentPrecedence) && (parentExpression instanceof InfixExpression)) {
- //we have expr infix (expr infix expr) removing the parenthesis is equal to (expr infix expr) infix expr
- InfixExpression parentInfix= (InfixExpression) parentExpression;
- Operator parentOperator= parentInfix.getOperator();
- if (parentInfix.getLeftOperand() == parenthesizedExpression) {
- fNodes.add(node);
- } else if (isAssoziative(parentOperator)) {
- if (parentOperator == InfixExpression.Operator.PLUS) {
- if (isStringExpression(parentInfix.getLeftOperand())
- || isStringExpression(parentInfix.getRightOperand())) {
- return;
- }
- for (Iterator J= parentInfix.extendedOperands().iterator(); J.hasNext();) {
- Expression operand= (Expression) J.next();
- if (isStringExpression(operand)) {
- return;
- }
- }
- }
- fNodes.add(node);
- }
- return;
- } else if (expressionPrecedence == parentPrecedence && parentExpression instanceof ConditionalExpression) {
- if (((ConditionalExpression)parentExpression).getElseExpression() != parenthesizedExpression)
- return;
- }
- }
- fNodes.add(node);
- }
-
- //is e1 op (e2 op e3) == (e1 op e2) op e3 == e1 op e2 op e3 for 'operator'?
- private boolean isAssoziative(Operator operator) {
- if (operator == InfixExpression.Operator.PLUS)
- return true;
-
- if (operator == InfixExpression.Operator.CONDITIONAL_AND)
- return true;
-
- if (operator == InfixExpression.Operator.CONDITIONAL_OR)
- return true;
-
- if (operator == InfixExpression.Operator.AND)
- return true;
-
- if (operator == InfixExpression.Operator.OR)
- return true;
-
- if (operator == InfixExpression.Operator.XOR)
- return true;
-
- if (operator == InfixExpression.Operator.TIMES)
- return true;
-
- return false;
- }
-
- private static int getExpressionPrecedence(Expression expression) {
- if (expression instanceof PostfixExpression || expression instanceof FunctionInvocation) {
- return 0;
- }
- if (expression instanceof PrefixExpression) {
- return 1;
- }
- if (expression instanceof ClassInstanceCreation) {
- return 2;
- }
- if (expression instanceof InfixExpression) {
- InfixExpression infixExpression = (InfixExpression) expression;
- InfixExpression.Operator operator = infixExpression.getOperator();
- return getInfixOperatorPrecedence(operator);
- }
- if (expression instanceof InstanceofExpression) {
- return 6;
- }
- if (expression instanceof ConditionalExpression) {
- return 13;
- }
- if (expression instanceof Assignment) {
- return 14;
- }
- return -1;
- }
-
- private static int getInfixOperatorPrecedence(InfixExpression.Operator operator) {
- if ((operator == InfixExpression.Operator.TIMES) || (operator == InfixExpression.Operator.DIVIDE)
- || (operator == InfixExpression.Operator.REMAINDER)) {
- return 3;
- }
- if ((operator == InfixExpression.Operator.PLUS) || (operator == InfixExpression.Operator.MINUS)) {
- return 4;
- }
- if ((operator == InfixExpression.Operator.LEFT_SHIFT)
- || (operator == InfixExpression.Operator.RIGHT_SHIFT_SIGNED)
- || (operator == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED)) {
- return 5;
- }
- if ((operator == InfixExpression.Operator.LESS) || (operator == InfixExpression.Operator.GREATER)
- || (operator == InfixExpression.Operator.LESS_EQUALS)
- || (operator == InfixExpression.Operator.GREATER_EQUALS)) {
- return 6;
- }
- if ((operator == InfixExpression.Operator.EQUALS) || (operator == InfixExpression.Operator.NOT_EQUALS)) {
- return 7;
- }
- if (operator == InfixExpression.Operator.AND) {
- return 8;
- }
- if (operator == InfixExpression.Operator.XOR) {
- return 9;
- }
- if (operator == InfixExpression.Operator.OR) {
- return 10;
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_AND) {
- return 11;
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_OR) {
- return 12;
- }
- return -1;
- }
-
- }
-
- private static class AddParenthesisOperation extends AbstractFixRewriteOperation {
-
- private final Expression[] fExpressions;
-
- public AddParenthesisOperation(Expression[] expressions) {
- fExpressions= expressions;
- }
-
- /**
- * {@inheritDoc}
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- TextEditGroup group= createTextEditGroup(FixMessages.ExpressionsFix_addParanoiacParenthesis_description);
- textEditGroups.add(group);
-
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
- AST ast= cuRewrite.getRoot().getAST();
-
- for (int i= 0; i < fExpressions.length; i++) {
- // add parenthesis around expression
- Expression expression= fExpressions[i];
-
- ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
- parenthesizedExpression.setExpression((Expression) rewrite.createCopyTarget(expression));
- rewrite.replace(expression, parenthesizedExpression, group);
- }
- }
- }
-
- private static class RemoveParenthesisOperation extends AbstractFixRewriteOperation {
-
- private final HashSet/*<ParenthesizedExpression>*/ fExpressions;
-
- public RemoveParenthesisOperation(HashSet expressions) {
- fExpressions= expressions;
- }
-
- /**
- * {@inheritDoc}
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- TextEditGroup group= createTextEditGroup(FixMessages.ExpressionsFix_removeUnnecessaryParenthesis_description);
- textEditGroups.add(group);
-
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
-
- while (fExpressions.size() > 0) {
- ParenthesizedExpression parenthesizedExpression= (ParenthesizedExpression)fExpressions.iterator().next();
- fExpressions.remove(parenthesizedExpression);
- ParenthesizedExpression down= parenthesizedExpression;
- while (fExpressions.contains(down.getExpression())) {
- down= (ParenthesizedExpression)down.getExpression();
- fExpressions.remove(down);
- }
-
- ASTNode move= rewrite.createMoveTarget(down.getExpression());
-
- ParenthesizedExpression top= parenthesizedExpression;
- while (fExpressions.contains(top.getParent())) {
- top= (ParenthesizedExpression)top.getParent();
- fExpressions.remove(top);
- }
-
- rewrite.replace(top, move, group);
- }
- }
- }
-
- public static IFix createAddParanoidalParenthesisFix(JavaScriptUnit compilationUnit, ASTNode[] coveredNodes) throws CoreException {
- if (coveredNodes == null)
- return null;
-
- if (coveredNodes.length == 0)
- return null;
- // check sub-expressions in fully covered nodes
- final ArrayList changedNodes = new ArrayList();
- for (int i= 0; i < coveredNodes.length; i++) {
- ASTNode covered = coveredNodes[i];
- if (covered instanceof InfixExpression)
- covered.accept(new MissingParenthesisVisitor(changedNodes));
- }
- if (changedNodes.isEmpty())
- return null;
-
-
- IFixRewriteOperation op= new AddParenthesisOperation((Expression[])changedNodes.toArray(new Expression[changedNodes.size()]));
- return new ExpressionsFix(FixMessages.ExpressionsFix_addParanoiacParenthesis_description, compilationUnit, new IFixRewriteOperation[] {op});
- }
-
- public static IFix createRemoveUnnecessaryParenthesisFix(JavaScriptUnit compilationUnit, ASTNode[] nodes) {
- // check sub-expressions in fully covered nodes
- final ArrayList changedNodes= new ArrayList();
- for (int i= 0; i < nodes.length; i++) {
- ASTNode covered= nodes[i];
- if (covered instanceof ParenthesizedExpression || covered instanceof InfixExpression)
- covered.accept(new UnnecessaryParenthesisVisitor(changedNodes));
- }
- if (changedNodes.isEmpty())
- return null;
-
- HashSet expressions= new HashSet(changedNodes);
- RemoveParenthesisOperation op= new RemoveParenthesisOperation(expressions);
- return new ExpressionsFix(FixMessages.ExpressionsFix_removeUnnecessaryParenthesis_description, compilationUnit, new IFixRewriteOperation[] {op});
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit,
- boolean addParanoicParentesis,
- boolean removeUnnecessaryParenthesis) {
-
- if (addParanoicParentesis) {
- final ArrayList changedNodes = new ArrayList();
- compilationUnit.accept(new MissingParenthesisVisitor(changedNodes));
-
- if (changedNodes.isEmpty())
- return null;
-
- IFixRewriteOperation op= new AddParenthesisOperation((Expression[])changedNodes.toArray(new Expression[changedNodes.size()]));
- return new ExpressionsFix(FixMessages.ExpressionsFix_add_parenthesis_change_name, compilationUnit, new IFixRewriteOperation[] {op});
- } else if (removeUnnecessaryParenthesis) {
- final ArrayList changedNodes = new ArrayList();
- compilationUnit.accept(new UnnecessaryParenthesisVisitor(changedNodes));
-
- if (changedNodes.isEmpty())
- return null;
-
- HashSet expressions= new HashSet(changedNodes);
- IFixRewriteOperation op= new RemoveParenthesisOperation(expressions);
- return new ExpressionsFix(FixMessages.ExpressionsFix_remove_parenthesis_change_name, compilationUnit, new IFixRewriteOperation[] {op});
- }
- return null;
- }
-
- private static boolean isStringExpression(Expression expression) {
- ITypeBinding binding = expression.resolveTypeBinding();
- return binding.getQualifiedName().equals("java.lang.String"); //$NON-NLS-1$
- }
-
- protected ExpressionsFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java
deleted file mode 100644
index 5d3239be..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class FixMessages extends NLS {
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.fix.FixMessages"; //$NON-NLS-1$
-
- private FixMessages() {
- }
-
- public static String CleanUpPostSaveListener_name;
- public static String CleanUpPostSaveListener_SaveAction_ChangeName;
- public static String CleanUpPostSaveListener_unknown_profile_error_message;
-
- public static String CleanUpRefactoring_checkingPostConditions_message;
- public static String CleanUpRefactoring_clean_up_multi_chang_name;
- public static String CleanUpRefactoring_could_not_retrive_profile;
- public static String CleanUpRefactoring_Parser_Startup_message;
- public static String CleanUpRefactoring_Refactoring_name;
- public static String CleanUpRefactoring_ProcessingCompilationUnit_message;
- public static String CleanUpRefactoring_Initialize_message;
- public static String CodeStyleFix_change_name;
- public static String ControlStatementsFix_change_name;
-
- public static String ConvertIterableLoopOperation_RemoveUpdateExpression_Warning;
- public static String ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning;
- public static String ConvertIterableLoopOperation_semanticChangeWarning;
- public static String ExpressionsFix_add_parenthesis_change_name;
- public static String ExpressionsFix_remove_parenthesis_change_name;
- public static String ImportsFix_OrganizeImports_Description;
- public static String Java50Fix_add_annotations_change_name;
-
- public static String SortMembersFix_Change_description;
- public static String SortMembersFix_Fix_description;
- public static String UnusedCodeFix_change_name;
- public static String UnusedCodeFix_RemoveFieldOrLocal_AlteredAssignments_preview;
-
- public static String UnusedCodeFix_RemoveFieldOrLocal_description;
- public static String UnusedCodeFix_RemoveFieldOrLocal_RemovedAssignments_preview;
- public static String UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description;
- public static String UnusedCodeFix_RemoveMethod_description;
- public static String UnusedCodeFix_RemoveConstructor_description;
- public static String UnusedCodeFix_RemoveType_description;
- public static String UnusedCodeFix_RemoveImport_description;
- public static String UnusedCodeFix_RemoveCast_description;
- public static String UnusedCodeFix_RemoveUnusedType_description;
- public static String UnusedCodeFix_RemoveUnusedConstructor_description;
- public static String UnusedCodeFix_RemoveUnusedPrivateMethod_description;
- public static String UnusedCodeFix_RemoveUnusedField_description;
- public static String UnusedCodeFix_RemoveUnusedVariabl_description;
-
- public static String Java50Fix_ConvertToEnhancedForLoop_description;
- public static String Java50Fix_AddTypeParameters_description;
-
- public static String StringFix_AddRemoveNonNls_description;
- public static String StringFix_AddNonNls_description;
- public static String StringFix_RemoveNonNls_description;
-
- public static String CodeStyleFix_ChangeAccessToStatic_description;
- public static String CodeStyleFix_QualifyWithThis_description;
- public static String CodeStyleFix_ChangeAccessToStaticUsingInstanceType_description;
- public static String CodeStyleFix_ChangeStaticAccess_description;
- public static String CodeStyleFix_ChangeIfToBlock_desription;
- public static String CodeStyleFix_ChangeElseToBlock_description;
- public static String CodeStyleFix_ChangeControlToBlock_description;
- public static String CodeStyleFix_ChangeAccessUsingDeclaring_description;
- public static String CodeStyleFix_QualifyFieldWithThis_description;
- public static String CodeStyleFix_QualifyMethodWithDeclClass_description;
- public static String CodeStyleFix_QualifyFieldWithDeclClass_description;
-
- public static String ControlStatementsFix_removeIfBlock_proposalDescription;
- public static String ControlStatementsFix_removeElseBlock_proposalDescription;
- public static String ControlStatementsFix_removeIfElseBlock_proposalDescription;
- public static String ControlStatementsFix_removeBrackets_proposalDescription;
-
- public static String ExpressionsFix_addParanoiacParenthesis_description;
- public static String ExpressionsFix_removeUnnecessaryParenthesis_description;
- public static String VariableDeclarationFix_add_final_change_name;
-
- public static String VariableDeclarationFix_changeModifierOfUnknownToFinal_description;
- public static String VariableDeclarationFix_ChangeMidifiersToFinalWherPossible_description;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, FixMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties
deleted file mode 100644
index e3546bd9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties
+++ /dev/null
@@ -1,78 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-CleanUpRefactoring_Refactoring_name=Clean Up
-CleanUpRefactoring_Initialize_message=Checking preconditions for project ''{0}''
-CleanUpRefactoring_Parser_Startup_message=Processing project {0}
-CleanUpRefactoring_clean_up_multi_chang_name=Clean Up
-CleanUpRefactoring_could_not_retrive_profile=Could not retrieve profile for project ''{0}''
-CleanUpRefactoring_ProcessingCompilationUnit_message=Processing JavaScript file {0} of {1} ({2})
-CleanUpRefactoring_checkingPostConditions_message=Checking post conditions
-
-UnusedCodeFix_RemoveFieldOrLocal_description=Remove ''{0}'', keep side-effect assignments
-UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description=Remove ''{0}'' and all assignments
-UnusedCodeFix_RemoveFieldOrLocal_RemovedAssignments_preview=<br>removing <b>{0}</b> assignment(s)
-UnusedCodeFix_RemoveFieldOrLocal_AlteredAssignments_preview=<br>modifying <b>{0}</b> assignment(s)
-UnusedCodeFix_RemoveUnusedConstructor_description=Remove unused private constructor
-UnusedCodeFix_RemoveUnusedPrivateMethod_description=Remove unused private function
-UnusedCodeFix_RemoveUnusedVariabl_description=Remove unused local var
-UnusedCodeFix_RemoveMethod_description=Remove function ''{0}''
-UnusedCodeFix_RemoveConstructor_description=Remove constructor ''{0}''
-UnusedCodeFix_RemoveUnusedType_description=Remove unused private type
-UnusedCodeFix_RemoveUnusedField_description=Remove unused private var
-UnusedCodeFix_RemoveType_description=Remove type ''{0}''
-UnusedCodeFix_RemoveCast_description=Remove cast
-UnusedCodeFix_change_name=Remove unused code
-UnusedCodeFix_RemoveImport_description=Remove unused import
-
-Java50Fix_AddTypeParameters_description=Add type parameters to ''{0}''
-Java50Fix_ConvertToEnhancedForLoop_description=Convert to enhanced for loop
-StringFix_AddRemoveNonNls_description=Add/Remove '$NON-NLS$' tag
-StringFix_AddNonNls_description=Add missing '$NON-NLS$' tag
-StringFix_RemoveNonNls_description=Remove unnecessary '$NON-NLS$' tag
-
-CodeStyleFix_ChangeAccessToStatic_description=Change access to static using ''{0}'' (declaring type)
-CodeStyleFix_ChangeAccessUsingDeclaring_description=Change access to static using declaring type
-CodeStyleFix_ChangeControlToBlock_description=Change control statement body to block
-CodeStyleFix_ChangeStaticAccess_description=Change static access to ''{0}''
-CodeStyleFix_ChangeIfToBlock_desription=Change 'if' statement body to block
-CodeStyleFix_ChangeElseToBlock_description=Change 'else' statement body to block
-CodeStyleFix_QualifyWithThis_description=Qualify ''{0}'' with ''{1}''
-CodeStyleFix_QualifyMethodWithDeclClass_description=Qualify function call with declaring type
-CodeStyleFix_QualifyFieldWithThis_description=Qualify field access with 'this'
-CodeStyleFix_QualifyFieldWithDeclClass_description=Qualify var access with declaring type
-CodeStyleFix_ChangeAccessToStaticUsingInstanceType_description=Change access to static using ''{0}'' (instance type)
-
-ControlStatementsFix_removeIfBlock_proposalDescription=Change 'if' block to statement
-ControlStatementsFix_removeElseBlock_proposalDescription=Change 'else' block to statement
-ControlStatementsFix_removeIfElseBlock_proposalDescription=Change 'if-else' blocks to statements
-ControlStatementsFix_removeBrackets_proposalDescription=Remove block from body statement
-ExpressionsFix_addParanoiacParenthesis_description=Add paranoiac parenthesis for conditions
-ExpressionsFix_add_parenthesis_change_name=Add Parenthesis
-ExpressionsFix_removeUnnecessaryParenthesis_description=Remove extra parenthesis
-ExpressionsFix_remove_parenthesis_change_name=Remove Parenthesis
-
-VariableDeclarationFix_changeModifierOfUnknownToFinal_description=Change modifier to final
-VariableDeclarationFix_add_final_change_name=Add final
-VariableDeclarationFix_ChangeMidifiersToFinalWherPossible_description=Change modifiers to final where possible
-
-
-ConvertIterableLoopOperation_semanticChangeWarning=Converting the loop may change the semantics of the code.
-ConvertIterableLoopOperation_RemoveUpdateExpression_Warning=The expression ''{0}'' in the update part of the loop will be removed.
-ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning=The expressions in the update part of the loop will be removed.
-ImportsFix_OrganizeImports_Description=Organize Imports
-
-CleanUpPostSaveListener_name=Code Clean Up
-CleanUpPostSaveListener_SaveAction_ChangeName=Save Actions
-CleanUpPostSaveListener_unknown_profile_error_message=Clean Up save participant could not retrieve profile with id ''{0}''
-CodeStyleFix_change_name=Code Style Clean Up
-ControlStatementsFix_change_name=Control Statements Clean Up
-SortMembersFix_Change_description=Sort Members
-SortMembersFix_Fix_description=Sort Members
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFix.java
deleted file mode 100644
index db989c98..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFix.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- * An <code>IFix</code> can calculate a <code>TextChange</code>
- * which applied to a <code>IJavaScriptUnit</code> will fix
- * one or several problems.
- *
-
- */
-public interface IFix {
-
- /**
- * A String describing what the <code>TextChange</code> returned by
- * <code>createChange</code> will do.
- *
- * @return The description, not null
- */
- public abstract String getDescription();
-
- /**
- * A <code>TextChange</code> which applied to <code>getCompilationUnit</code>
- * will fix a problem.
- *
- * @return The change or null if no fix possible
- * @throws CoreException
- */
- public abstract TextChange createChange() throws CoreException;
-
- /**
- * The <code>IJavaScriptUnit</code> on which <code>createChange</code> should
- * be applied to fix a problem.
- *
- * @return The IJavaScriptUnit, not null
- */
- public abstract IJavaScriptUnit getCompilationUnit();
-
- /**
- * A status to inform about issues with this fix
- *
- * @return The status, not null
- */
- public abstract IStatus getStatus();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFixRewriteOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFixRewriteOperation.java
deleted file mode 100644
index d24e684d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/IFixRewriteOperation.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-
-public interface IFixRewriteOperation {
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List/*<TextEditGroup>*/ textEditGroups) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ILinkedFixRewriteOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ILinkedFixRewriteOperation.java
deleted file mode 100644
index ad9ed1f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ILinkedFixRewriteOperation.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-
-public interface ILinkedFixRewriteOperation extends IFixRewriteOperation {
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List/*<TextEditGroup>*/ textEditGroups, LinkedProposalModel linkedProposalPositions) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ImportsFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ImportsFix.java
deleted file mode 100644
index 7ae7b63b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/ImportsFix.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.OrganizeImportsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-public class ImportsFix extends AbstractFix {
-
- private static final class AmbiguousImportException extends RuntimeException {
- private static final long serialVersionUID= 1L;
- }
-
- public static IFix createCleanUp(final JavaScriptUnit cu, CodeGenerationSettings settings, boolean organizeImports, RefactoringStatus status) throws CoreException {
- if (!organizeImports)
- return null;
-
- IChooseImportQuery query= new IChooseImportQuery() {
- public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
- throw new AmbiguousImportException();
- }
- };
- OrganizeImportsOperation op= new OrganizeImportsOperation((IJavaScriptUnit)cu.getJavaElement(), cu, settings.importIgnoreLowercase, false, false, query);
- final TextEdit edit;
- try {
- edit= op.createTextEdit(null);
- } catch (AmbiguousImportException e) {
- status.addInfo(Messages.format(ActionMessages.OrganizeImportsAction_multi_error_unresolvable, getLocationString(cu)));
- return null;
- }
-
- if (op.getParseError() != null) {
- status.addInfo(Messages.format(ActionMessages.OrganizeImportsAction_multi_error_parse, getLocationString(cu)));
- return null;
- }
-
- if (edit == null)
- return null;
-
- if (op.getNumberOfImportsAdded() == 0 && op.getNumberOfImportsRemoved() == 0)
- return null;
-
- return new IFix() {
-
- public TextChange createChange() throws CoreException {
- CompilationUnitChange result= new CompilationUnitChange(getDescription(), getCompilationUnit());
- result.setEdit(edit);
- String label= getDescription();
- result.addTextEditGroup(new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label))));
- return result;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return (IJavaScriptUnit)cu.getJavaElement();
- }
-
- public String getDescription() {
- return FixMessages.ImportsFix_OrganizeImports_Description;
- }
-
- public IStatus getStatus() {
- return StatusInfo.OK_STATUS;
- }
- };
- }
-
- private static String getLocationString(final JavaScriptUnit cu) {
- return cu.getJavaElement().getPath().makeRelative().toString();
- }
-
- protected ImportsFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedFix.java
deleted file mode 100644
index 7c22461f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedFix.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-
-public class LinkedFix extends AbstractFix {
-
- public static abstract class AbstractLinkedFixRewriteOperation extends AbstractFixRewriteOperation implements ILinkedFixRewriteOperation {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- rewriteAST(cuRewrite, textEditGroups, new LinkedProposalModel());
- }
-
- }
-
- private final IFixRewriteOperation[] fFixRewrites;
- private final JavaScriptUnit fCompilationUnit;
- private final LinkedProposalModel fLinkedProposalModel;
-
- protected LinkedFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewrites) {
- super(name, compilationUnit, fixRewrites);
- fCompilationUnit= compilationUnit;
- fFixRewrites= fixRewrites;
- fLinkedProposalModel= new LinkedProposalModel();
- }
-
- public LinkedProposalModel getLinkedPositions() {
- return fLinkedProposalModel;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#createChange()
- */
- public TextChange createChange() throws CoreException {
- if (fFixRewrites == null || fFixRewrites.length == 0)
- return null;
-
- CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite((IJavaScriptUnit)fCompilationUnit.getJavaElement(), fCompilationUnit);
-
- List/*<TextEditGroup>*/ groups= new ArrayList();
-
- fLinkedProposalModel.clear();
-
- for (int i= 0; i < fFixRewrites.length; i++) {
- IFixRewriteOperation operation= fFixRewrites[i];
- if (operation instanceof ILinkedFixRewriteOperation) {
- ILinkedFixRewriteOperation linkedOperation= (ILinkedFixRewriteOperation)operation;
- linkedOperation.rewriteAST(cuRewrite, groups, fLinkedProposalModel);
- } else {
- operation.rewriteAST(cuRewrite, groups);
- }
- }
-
- CompilationUnitChange result= cuRewrite.createChange(getDescription(), true, null);
-
- for (Iterator iter= groups.iterator(); iter.hasNext();) {
- TextEditGroup group= (TextEditGroup)iter.next();
- result.addTextEditGroup(group);
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalModel.java
deleted file mode 100644
index 4005c500..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalModel.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup.PositionInformation;
-
-public class LinkedProposalModel {
-
- private Map/*<String, PositionGroup>*/ fPositionGroups;
- private LinkedProposalPositionGroup.PositionInformation fEndPosition;
-
- public void addPositionGroup(LinkedProposalPositionGroup positionGroup) {
- if (positionGroup == null) {
- throw new IllegalArgumentException("positionGroup must not be null"); //$NON-NLS-1$
- }
-
- if (fPositionGroups == null) {
- fPositionGroups= new HashMap();
- }
- fPositionGroups.put(positionGroup.getGroupId(), positionGroup);
- }
-
- public LinkedProposalPositionGroup getPositionGroup(String groupId, boolean createIfNotExisting) {
- LinkedProposalPositionGroup group= fPositionGroups != null ? (LinkedProposalPositionGroup) fPositionGroups.get(groupId) : null;
- if (createIfNotExisting && group == null) {
- group= new LinkedProposalPositionGroup(groupId);
- addPositionGroup(group);
- }
- return group;
- }
-
- public Iterator getPositionGroupIterator() {
- if (fPositionGroups == null) {
- return new Iterator() {
- public boolean hasNext() {return false;}
- public Object next() {return null;}
- public void remove() {}
- };
- }
- return fPositionGroups.values().iterator();
- }
-
-
- /**
- * Sets the end position of the linked mode to the end of the passed range.
- * @param position The position that describes the end position of the linked mode.
- */
- public void setEndPosition(PositionInformation position) {
- fEndPosition= position;
- }
-
- public void setEndPosition(ITrackedNodePosition position) {
- setEndPosition(LinkedProposalPositionGroup.createPositionInformation(position, false));
- }
-
- public PositionInformation getEndPosition() {
- return fEndPosition;
- }
-
- public boolean hasLinkedPositions() {
- return fPositionGroups != null && !fPositionGroups.isEmpty();
- }
-
- public void clear() {
- fPositionGroups= null;
- fEndPosition= null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalPositionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalPositionGroup.java
deleted file mode 100644
index 08b7e8e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/LinkedProposalPositionGroup.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class LinkedProposalPositionGroup {
-
- /**
- * {@link LinkedProposalPositionGroup.PositionInformation} describes a position
- * insinde a position group. The information provided must be accurate
- * after the document change to the proposal has been performed, but doesn't
- * need to reflect the changed done by the linking mode.
- */
- public static abstract class PositionInformation {
- public abstract int getOffset();
- public abstract int getLength();
- public abstract int getSequenceRank();
- }
-
- public static class Proposal {
-
- private String fDisplayString;
- private Image fImage;
- private int fRelevance;
-
- public Proposal(String displayString, Image image, int relevance) {
- fDisplayString= displayString;
- fImage= image;
- fRelevance= relevance;
- }
-
- public String getDisplayString() {
- return fDisplayString;
- }
-
- public Image getImage() {
- return fImage;
- }
-
- public int getRelevance() {
- return fRelevance;
- }
-
- public void setImage(Image image) {
- fImage= image;
- }
-
- public String getAdditionalProposalInfo() {
- return null;
- }
-
- public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask, LinkedModeModel model) throws CoreException {
- return new ReplaceEdit(position.getOffset(), position.getLength(), fDisplayString);
- }
- }
-
- public static PositionInformation createPositionInformation(ITrackedNodePosition pos, boolean isFirst) {
- return new TrackedNodePosition(pos, isFirst);
- }
-
- private static class TrackedNodePosition extends PositionInformation {
-
- private final ITrackedNodePosition fPos;
- private final boolean fIsFirst;
-
- public TrackedNodePosition(ITrackedNodePosition pos, boolean isFirst) {
- fPos= pos;
- fIsFirst= isFirst;
- }
-
- public int getOffset() {
- return fPos.getStartPosition();
- }
-
- public int getLength() {
- return fPos.getLength();
- }
-
- public int getSequenceRank() {
- return fIsFirst ? 0 : 1;
- }
- }
-
- private static final class JavaLinkedModeProposal extends Proposal {
- private final ITypeBinding fTypeProposal;
- private final IJavaScriptUnit fCompilationUnit;
-
- public JavaLinkedModeProposal(IJavaScriptUnit unit, ITypeBinding typeProposal, int relevance) {
- super(BindingLabelProvider.getBindingLabel(typeProposal, JavaScriptElementLabels.ALL_DEFAULT | JavaScriptElementLabels.ALL_POST_QUALIFIED), null, relevance);
- fTypeProposal= typeProposal;
- fCompilationUnit= unit;
- ImageDescriptor desc= BindingLabelProvider.getBindingImageDescriptor(fTypeProposal, BindingLabelProvider.DEFAULT_IMAGEFLAGS);
- if (desc != null) {
- setImage(JavaScriptPlugin.getImageDescriptorRegistry().get(desc));
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.PositionGroup.Proposal#computeEdits(int, org.eclipse.jface.text.link.LinkedPosition, char, int, org.eclipse.jface.text.link.LinkedModeModel)
- */
- public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask, LinkedModeModel model) throws CoreException {
- ImportRewrite impRewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
- String replaceString= impRewrite.addImport(fTypeProposal);
-
- MultiTextEdit composedEdit= new MultiTextEdit();
- composedEdit.addChild(new ReplaceEdit(position.getOffset(), position.getLength(), replaceString));
- composedEdit.addChild(impRewrite.rewriteImports(null));
- return composedEdit;
- }
- }
-
-
- private final String fGroupId;
- private final List/*<Position>*/ fPositions;
- private final List/*<Proposal>*/ fProposals;
-
-
- public LinkedProposalPositionGroup(String groupID) {
- fGroupId= groupID;
- fPositions= new ArrayList();
- fProposals= new ArrayList();
- }
-
- public void addPosition(PositionInformation position) {
- fPositions.add(position);
- }
-
- public void addProposal(Proposal proposal) {
- fProposals.add(proposal);
- }
-
-
- public void addPosition(ITrackedNodePosition position, boolean isFirst) {
- addPosition(createPositionInformation(position, isFirst));
- }
-
- public void addProposal(String displayString, Image image, int relevance) {
- addProposal(new Proposal(displayString, image, relevance));
- }
-
- public void addProposal(ITypeBinding type, IJavaScriptUnit cu, int relevance) {
- addProposal(new JavaLinkedModeProposal(cu, type, relevance));
- }
-
- public String getGroupId() {
- return fGroupId;
- }
-
- public PositionInformation[] getPositions() {
- return (PositionInformation[])fPositions.toArray(new PositionInformation[fPositions.size()]);
- }
-
- public Proposal[] getProposals() {
- return (Proposal[])fProposals.toArray(new Proposal[fProposals.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/SortMembersFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/SortMembersFix.java
deleted file mode 100644
index c496c5e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/SortMembersFix.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - https://bugs.eclipse.org/bugs/show_bug.cgi?id=168954
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.util.JavaScriptUnitSorter;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.SortMembersOperation.DefaultJavaElementComparator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-public class SortMembersFix implements IFix {
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit, boolean sortMembers, boolean sortFields) throws CoreException {
- if (!sortMembers && !sortFields)
- return null;
-
- IJavaScriptUnit cu= (IJavaScriptUnit)compilationUnit.getJavaElement();
-
- String label= FixMessages.SortMembersFix_Change_description;
- CategorizedTextEditGroup group= new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
-
- TextEdit edit= JavaScriptUnitSorter.sort(compilationUnit, new DefaultJavaElementComparator(!sortFields), 0, group, null);
- if (edit == null)
- return null;
-
- TextChange change= new CompilationUnitChange(label, cu);
- change.setEdit(edit);
- change.addTextEditGroup(group);
-
- return new SortMembersFix(change, cu);
- }
-
- private final IJavaScriptUnit fCompilationUnit;
- private final TextChange fChange;
-
- public SortMembersFix(TextChange change, IJavaScriptUnit compilationUnit) {
- fChange= change;
- fCompilationUnit= compilationUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- public TextChange createChange() throws CoreException {
- return fChange;
- }
-
- /**
- * {@inheritDoc}
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDescription() {
- return FixMessages.SortMembersFix_Fix_description;
- }
-
- /**
- * {@inheritDoc}
- */
- public IStatus getStatus() {
- return StatusInfo.OK_STATUS;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/StringFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/StringFix.java
deleted file mode 100644
index b0e6c05a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/StringFix.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSUtil;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * Fix which solves various issues with strings.
- * Supported:
- * Add missing $NON-NLS$ tag
- * Remove unnecessary $NON-NLS$ tag
- *
- */
-public class StringFix implements IFix {
-
- private final TextEditGroup[] fEditGroups;
- private final String fName;
- private final IJavaScriptUnit fCompilationUnit;
-
- public static StringFix createFix(JavaScriptUnit compilationUnit, IProblemLocation problem, boolean removeNLSTag, boolean addNLSTag) throws CoreException {
- TextEdit addEdit= null;
- IJavaScriptUnit cu= (IJavaScriptUnit)compilationUnit.getJavaElement();
- if (addNLSTag) {
- addEdit= NLSUtil.createNLSEdit(cu, problem.getOffset());
- }
- ReplaceEdit removeEdit= null;
- if (removeNLSTag) {
- IBuffer buffer= cu.getBuffer();
- if (buffer != null) {
- removeEdit= getReplace(problem.getOffset(), problem.getLength(), buffer, true);
- }
- }
-
- if (addEdit != null && removeEdit != null) {
- String label= FixMessages.StringFix_AddRemoveNonNls_description;
- return new StringFix(label, compilationUnit, new TextEditGroup[] {new TextEditGroup(label, addEdit), new TextEditGroup(label, removeEdit)});
- } else if (addEdit != null) {
- String label= FixMessages.StringFix_AddNonNls_description;
- return new StringFix(label, compilationUnit, new TextEditGroup[] {new TextEditGroup(label, addEdit)});
- } else if (removeEdit != null) {
- String label= FixMessages.StringFix_RemoveNonNls_description;
- return new StringFix(label, compilationUnit, new TextEditGroup[] {new TextEditGroup(label, removeEdit)});
- } else {
- return null;
- }
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit, boolean addNLSTag, boolean removeNLSTag) throws CoreException, JavaScriptModelException {
- if (!addNLSTag && !removeNLSTag)
- return null;
-
- IProblem[] problems= compilationUnit.getProblems();
- IProblemLocation[] locations= new IProblemLocation[problems.length];
- for (int i= 0; i < problems.length; i++) {
- locations[i]= new ProblemLocation(problems[i]);
- }
- return createCleanUp(compilationUnit, addNLSTag, removeNLSTag, locations);
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit, IProblemLocation[] problems, boolean addNLSTag, boolean removeNLSTag) throws CoreException, JavaScriptModelException {
- if (!addNLSTag && !removeNLSTag)
- return null;
-
- return createCleanUp(compilationUnit, addNLSTag, removeNLSTag, problems);
- }
-
- private static IFix createCleanUp(JavaScriptUnit compilationUnit, boolean addNLSTag, boolean removeNLSTag, IProblemLocation[] problems) throws CoreException, JavaScriptModelException {
- IJavaScriptUnit cu= (IJavaScriptUnit)compilationUnit.getJavaElement();
- List result= new ArrayList();
-
- List missingNLSProblems= new ArrayList();
- for (int i= 0; i < problems.length; i++) {
- IProblemLocation problem= problems[i];
- if (addNLSTag && problem.getProblemId() == IProblem.NonExternalizedStringLiteral) {
- missingNLSProblems.add(problem);
- }
- if (removeNLSTag && problem.getProblemId() == IProblem.UnnecessaryNLSTag) {
- IBuffer buffer= cu.getBuffer();
- if (buffer != null) {
- TextEdit edit= StringFix.getReplace(problem.getOffset(), problem.getLength(), buffer, false);
- if (edit != null) {
- String label= FixMessages.StringFix_RemoveNonNls_description;
- result.add(new CategorizedTextEditGroup(label, edit, new GroupCategorySet(new GroupCategory(label, label, label))));
- }
- }
- }
- }
- if (!missingNLSProblems.isEmpty()) {
- int[] positions= new int[missingNLSProblems.size()];
- int i=0;
- for (Iterator iter= missingNLSProblems.iterator(); iter.hasNext();) {
- IProblemLocation problem= (IProblemLocation)iter.next();
- positions[i]= problem.getOffset();
- i++;
- }
- TextEdit[] edits= NLSUtil.createNLSEdits(cu, positions);
- if (edits != null) {
- for (int j= 0; j < edits.length; j++) {
- String label= FixMessages.StringFix_AddNonNls_description;
- result.add(new CategorizedTextEditGroup(label, edits[j], new GroupCategorySet(new GroupCategory(label, label, label))));
- }
- }
- }
- if (result.isEmpty())
- return null;
-
- return new StringFix("", compilationUnit, (TextEditGroup[])result.toArray(new TextEditGroup[result.size()])); //$NON-NLS-1$
- }
-
- private static ReplaceEdit getReplace(int offset, int length, IBuffer buffer, boolean removeLeadingIndents) {
-
- String replaceString= new String();
- boolean hasMoreInComment= false;
-
- // look after the tag
- int next= offset + length;
- while (next < buffer.getLength()) {
- char ch= buffer.getChar(next);
- if (IndentManipulation.isIndentChar(ch)) {
- next++; // remove all whitespace
- } else if (IndentManipulation.isLineDelimiterChar(ch)) {
- length= next - offset;
- break;
- } else if (ch == '/') {
- next++;
- if (next == buffer.getLength() || buffer.getChar(next) != '/') {
- replaceString= "//"; //$NON-NLS-1$
- } else {
- length= next - offset - 1;
- }
- hasMoreInComment= true;
- break;
- } else {
- replaceString= "//"; //$NON-NLS-1$
- hasMoreInComment= true;
- break;
- }
- }
- if (!hasMoreInComment && removeLeadingIndents) {
- while (offset > 0 && IndentManipulation.isIndentChar(buffer.getChar(offset - 1))) {
- offset--;
- length++;
- }
- }
- if (length > 0) {
- ReplaceEdit replaceEdit= new ReplaceEdit(offset, length, replaceString);
- return replaceEdit;
- } else {
- return null;
- }
- }
-
- private StringFix(String name, JavaScriptUnit compilationUnit, TextEditGroup[] groups) {
- fName= name;
- fCompilationUnit= (IJavaScriptUnit)compilationUnit.getJavaElement();
- fEditGroups= groups;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix#createChange()
- */
- public TextChange createChange() throws CoreException {
- if (fEditGroups == null || fEditGroups.length == 0)
- return null;
-
- CompilationUnitChange result= new CompilationUnitChange(getDescription(), getCompilationUnit());
- for (int i= 0; i < fEditGroups.length; i++) {
- TextEdit[] edits= fEditGroups[i].getTextEdits();
- String groupName= fEditGroups[i].getName();
- for (int j= 0; j < edits.length; j++) {
- TextChangeCompatibility.addTextEdit(result, groupName, edits[j]);
- }
- }
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getDescription()
- */
- public String getDescription() {
- return fName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getCompilationUnit()
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getStatus()
- */
- public IStatus getStatus() {
- return StatusInfo.OK_STATUS;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/UnusedCodeFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/UnusedCodeFix.java
deleted file mode 100644
index d8ce9328..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/UnusedCodeFix.java
+++ /dev/null
@@ -1,637 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.fix.UnusedCodeCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavadocTagsSubProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * Fix which removes unused code.
- */
-public class UnusedCodeFix extends AbstractFix {
-
- private static class SideEffectFinder extends ASTVisitor {
-
- private final ArrayList fSideEffectNodes;
-
- public SideEffectFinder(ArrayList res) {
- fSideEffectNodes= res;
- }
-
- public boolean visit(Assignment node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(PostfixExpression node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(PrefixExpression node) {
- Object operator= node.getOperator();
- if (operator == PrefixExpression.Operator.INCREMENT || operator == PrefixExpression.Operator.DECREMENT) {
- fSideEffectNodes.add(node);
- }
- return false;
- }
-
- public boolean visit(FunctionInvocation node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(ClassInstanceCreation node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(SuperMethodInvocation node) {
- fSideEffectNodes.add(node);
- return false;
- }
- }
-
- private static class RemoveImportOperation extends AbstractFixRewriteOperation {
-
- private final ImportDeclaration fImportDeclaration;
-
- public RemoveImportOperation(ImportDeclaration importDeclaration) {
- fImportDeclaration= importDeclaration;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- ImportDeclaration node= fImportDeclaration;
- TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveImport_description);
- cuRewrite.getASTRewrite().remove(node, group);
- textEditGroups.add(group);
- }
-
- }
-
- private static class RemoveUnusedMemberOperation extends AbstractFixRewriteOperation {
-
- private final SimpleName[] fUnusedNames;
- private boolean fForceRemove;
- private int fRemovedAssignmentsCount;
- private int fAlteredAssignmentsCount;
-
- public RemoveUnusedMemberOperation(SimpleName[] unusedNames, boolean forceRemoveInitializer) {
- fUnusedNames= unusedNames;
- fForceRemove=forceRemoveInitializer;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix.IFixRewriteOperation#rewriteAST(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite, java.util.List)
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- for (int i= 0; i < fUnusedNames.length; i++) {
- removeUnusedName(cuRewrite.getASTRewrite(), fUnusedNames[i], cuRewrite.getRoot(), textEditGroups);
- }
- }
-
- private void removeUnusedName(ASTRewrite rewrite, SimpleName simpleName, JavaScriptUnit completeRoot, List groups) {
- IBinding binding= simpleName.resolveBinding();
- JavaScriptUnit root= (JavaScriptUnit) simpleName.getRoot();
- String displayString= getDisplayString(binding);
- TextEditGroup group= createTextEditGroup(displayString);
- groups.add(group);
- if (binding.getKind() == IBinding.METHOD) {
- IFunctionBinding decl= ((IFunctionBinding) binding).getMethodDeclaration();
- ASTNode declaration= root.findDeclaringNode(decl);
- rewrite.remove(declaration, group);
- } else if (binding.getKind() == IBinding.TYPE) {
- ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
- ASTNode declaration= root.findDeclaringNode(decl);
- if (declaration.getParent() instanceof TypeDeclarationStatement) {
- declaration= declaration.getParent();
- }
- rewrite.remove(declaration, group);
- } else if (binding.getKind() == IBinding.VARIABLE) {
- SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
- SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
- for (int i= 0; i < references.length; i++) {
- removeVariableReferences(rewrite, references[i], group);
- }
-
- IVariableBinding bindingDecl= ((IVariableBinding) nameNode.resolveBinding()).getVariableDeclaration();
- ASTNode declaringNode= completeRoot.findDeclaringNode(bindingDecl);
- if (declaringNode instanceof SingleVariableDeclaration) {
- removeParamTag(rewrite, (SingleVariableDeclaration) declaringNode, group);
- }
- } else {
- // unexpected
- }
- }
-
- private String getDisplayString(IBinding binding) {
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return FixMessages.UnusedCodeFix_RemoveUnusedType_description;
- case IBinding.METHOD:
- if (((IFunctionBinding) binding).isConstructor()) {
- return FixMessages.UnusedCodeFix_RemoveUnusedConstructor_description;
- } else {
- return FixMessages.UnusedCodeFix_RemoveUnusedPrivateMethod_description;
- }
- case IBinding.VARIABLE:
- if (((IVariableBinding) binding).isField()) {
- return FixMessages.UnusedCodeFix_RemoveUnusedField_description;
- } else {
- return FixMessages.UnusedCodeFix_RemoveUnusedVariabl_description;
- }
- default:
- return ""; //$NON-NLS-1$
- }
- }
-
- private void removeParamTag(ASTRewrite rewrite, SingleVariableDeclaration varDecl, TextEditGroup group) {
- if (varDecl.getParent() instanceof FunctionDeclaration) {
- JSdoc javadoc= ((FunctionDeclaration) varDecl.getParent()).getJavadoc();
- if (javadoc != null) {
- TagElement tagElement= JavadocTagsSubProcessor.findParamTag(javadoc, varDecl.getName().getIdentifier());
- if (tagElement != null) {
- rewrite.remove(tagElement, group);
- }
- }
- }
- }
-
- /**
- * Remove the field or variable declaration including the initializer.
- * @param rewrite the AST rewriter to use
- * @param reference a reference to the variable to remove
- * @param group the text edit group to use
- */
- private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
- ASTNode parent= reference.getParent();
- while (parent instanceof QualifiedName) {
- parent= parent.getParent();
- }
- if (parent instanceof FieldAccess) {
- parent= parent.getParent();
- }
-
- int nameParentType= parent.getNodeType();
- if (nameParentType == ASTNode.ASSIGNMENT) {
- Assignment assignment= (Assignment) parent;
- Expression rightHand= assignment.getRightHandSide();
-
- ASTNode assignParent= assignment.getParent();
- if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
- removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
- } else {
- rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
- }
- } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
- rewrite.remove(parent, group);
- } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
- ASTNode varDecl= frag.getParent();
- List fragments;
- if (varDecl instanceof VariableDeclarationExpression) {
- fragments= ((VariableDeclarationExpression) varDecl).fragments();
- } else if (varDecl instanceof FieldDeclaration) {
- fragments= ((FieldDeclaration) varDecl).fragments();
- } else {
- fragments= ((VariableDeclarationStatement) varDecl).fragments();
- }
- Expression initializer = frag.getInitializer();
- boolean sideEffectInitializer = initializer instanceof FunctionInvocation || initializer instanceof ClassInstanceCreation;
- if (fragments.size() == fUnusedNames.length) {
- if (fForceRemove) {
- rewrite.remove(varDecl, group);
- return;
- }
- if (parent.getParent() instanceof FieldDeclaration) {
- rewrite.remove(varDecl, group);
- return;
- }
- if (sideEffectInitializer){
- Expression movedInit = (Expression) rewrite.createMoveTarget(initializer);
- ExpressionStatement wrapped = rewrite.getAST().newExpressionStatement(movedInit);
- rewrite.replace(varDecl, wrapped, group);
- } else {
- rewrite.remove(varDecl, group);
- }
- } else {
- if (fForceRemove) {
- rewrite.remove(frag, group);
- return;
- }
- //multiple declarations in one line
- ASTNode declaration = parent.getParent();
- if (declaration instanceof FieldDeclaration) {
- rewrite.remove(frag, group);
- return;
- }
- if (declaration instanceof VariableDeclarationStatement) {
- ASTNode lst = declaration.getParent();
- if (lst instanceof Block)
- splitUpDeclarations(rewrite, group, frag, lst, (VariableDeclarationStatement) declaration);
- rewrite.remove(frag, group);
- return;
- }
- if (declaration instanceof VariableDeclarationExpression) {
- //keep constructors and method invocations
- if (!sideEffectInitializer){
- rewrite.remove(frag, group);
- }
- }
- }
- }
- }
-
- private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, ASTNode block, VariableDeclarationStatement originalStatement) {
- Expression initializer = frag.getInitializer();
- //keep constructors and method invocations
- if (initializer instanceof FunctionInvocation || initializer instanceof ClassInstanceCreation){
- Expression movedInitializer= (Expression) rewrite.createMoveTarget(initializer);
- ListRewrite statementRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- ExpressionStatement newInitializer= rewrite.getAST().newExpressionStatement( movedInitializer);
- statementRewrite.insertAfter(newInitializer, originalStatement, group);
-
- VariableDeclarationStatement newDeclaration= null;
- List fragments= originalStatement.fragments();
- int fragIndex= fragments.indexOf(frag);
- ListIterator fragmentIterator= fragments.listIterator(fragIndex+1);
- while (fragmentIterator.hasNext()) {
- VariableDeclarationFragment currentFragment= (VariableDeclarationFragment) fragmentIterator.next();
- VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);
- if (newDeclaration == null) {
- newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment);
- Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType());
- newDeclaration.setType(copiedType);
- } else
- newDeclaration.fragments().add(movedFragment);
- }
- if (newDeclaration != null){
- statementRewrite.insertAfter(newDeclaration, newInitializer, group);
- }
- if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){
- rewrite.remove(originalStatement, group);
- }
- }
- }
-
- private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) {
- boolean performRemove= fForceRemove;
- if (!performRemove) {
- ArrayList sideEffectNodes= new ArrayList();
- initializerNode.accept(new SideEffectFinder(sideEffectNodes));
- performRemove= sideEffectNodes.isEmpty();
- }
- if (performRemove) {
- if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
- rewrite.replace(statementNode, rewrite.getAST().newBlock(), group);
- } else {
- rewrite.remove(statementNode, group);
- }
- fRemovedAssignmentsCount++;
- } else {
- ASTNode initNode = rewrite.createMoveTarget(initializerNode);
- ExpressionStatement statement = rewrite.getAST().newExpressionStatement((Expression) initNode);
- rewrite.replace(statementNode, statement, null);
- fAlteredAssignmentsCount++;
- }
- }
-
- public String getAdditionalInfo() {
- StringBuffer sb=new StringBuffer();
- if (fRemovedAssignmentsCount>0){
- sb.append(Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_RemovedAssignments_preview,String.valueOf(fRemovedAssignmentsCount)));
- }
- if (fAlteredAssignmentsCount>0){
- sb.append(Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_AlteredAssignments_preview,String.valueOf(fAlteredAssignmentsCount)));
- }
- if (sb.length()>0) {
- return sb.toString();
- } else
- return null;
- }
- }
-
- public static UnusedCodeFix createRemoveUnusedImportFix(JavaScriptUnit compilationUnit, IProblemLocation problem) {
- int id= problem.getProblemId();
- if (id == IProblem.DuplicateImport || id == IProblem.ConflictingImport ||
- id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound) {
-
- ImportDeclaration node= getImportDeclaration(problem, compilationUnit);
- if (node != null) {
- String label= FixMessages.UnusedCodeFix_RemoveImport_description;
- RemoveImportOperation operation= new RemoveImportOperation(node);
- Map options= new Hashtable();
- options.put(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpConstants.TRUE);
- return new UnusedCodeFix(label, compilationUnit, new IFixRewriteOperation[] {operation}, options);
- }
- }
- return null;
- }
-
- public static UnusedCodeFix createUnusedMemberFix(JavaScriptUnit compilationUnit, IProblemLocation problem, boolean forceInitializerRemoval) {
- int id= problem.getProblemId();
- if (id == IProblem.UnusedPrivateMethod || id == IProblem.UnusedPrivateConstructor || id == IProblem.UnusedPrivateField ||
- id == IProblem.UnusedPrivateType || id == IProblem.LocalVariableIsNeverUsed || id == IProblem.ArgumentIsNeverUsed) {
-
- SimpleName name= getUnusedName(compilationUnit, problem);
- if (name != null) {
- IBinding binding= name.resolveBinding();
- if (binding != null) {
- if (isFormalParameterInEnhancedForStatement(name))
- return null;
-
- String label= getDisplayString(name, binding, forceInitializerRemoval);
- RemoveUnusedMemberOperation operation= new RemoveUnusedMemberOperation(new SimpleName[] {name}, forceInitializerRemoval);
- return new UnusedCodeFix(label, compilationUnit, new IFixRewriteOperation[] {operation}, getCleanUpOptions(binding));
- }
- }
- }
- return null;
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit,
- boolean removeUnusedPrivateMethods,
- boolean removeUnusedPrivateConstructors,
- boolean removeUnusedPrivateFields,
- boolean removeUnusedPrivateTypes,
- boolean removeUnusedLocalVariables,
- boolean removeUnusedImports,
- boolean removeUnusedCast) {
-
- IProblem[] problems= compilationUnit.getProblems();
- IProblemLocation[] locations= new IProblemLocation[problems.length];
- for (int i= 0; i < problems.length; i++) {
- locations[i]= new ProblemLocation(problems[i]);
- }
-
- return createCleanUp(compilationUnit, locations,
- removeUnusedPrivateMethods,
- removeUnusedPrivateConstructors,
- removeUnusedPrivateFields,
- removeUnusedPrivateTypes,
- removeUnusedLocalVariables,
- removeUnusedImports,
- removeUnusedCast);
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit, IProblemLocation[] problems,
- boolean removeUnusedPrivateMethods,
- boolean removeUnusedPrivateConstructors,
- boolean removeUnusedPrivateFields,
- boolean removeUnusedPrivateTypes,
- boolean removeUnusedLocalVariables,
- boolean removeUnusedImports,
- boolean removeUnusedCast) {
-
- List/*<IFixRewriteOperation>*/ result= new ArrayList();
- Hashtable/*<ASTNode, List>*/ variableDeclarations= new Hashtable();
- for (int i= 0; i < problems.length; i++) {
- IProblemLocation problem= problems[i];
- int id= problem.getProblemId();
-
- if (removeUnusedImports && (id == IProblem.DuplicateImport || id == IProblem.ConflictingImport ||
- id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound))
- {
- ImportDeclaration node= UnusedCodeFix.getImportDeclaration(problem, compilationUnit);
- if (node != null) {
- result.add(new RemoveImportOperation(node));
- }
- }
-
- if ((removeUnusedPrivateMethods && id == IProblem.UnusedPrivateMethod) || (removeUnusedPrivateConstructors && id == IProblem.UnusedPrivateConstructor) ||
- (removeUnusedPrivateTypes && id == IProblem.UnusedPrivateType)) {
-
- SimpleName name= getUnusedName(compilationUnit, problem);
- if (name != null) {
- IBinding binding= name.resolveBinding();
- if (binding != null) {
- result.add(new RemoveUnusedMemberOperation(new SimpleName[] {name}, false));
- }
- }
- }
-
- if ((removeUnusedLocalVariables && id == IProblem.LocalVariableIsNeverUsed) || (removeUnusedPrivateFields && id == IProblem.UnusedPrivateField)) {
- SimpleName name= getUnusedName(compilationUnit, problem);
- if (name != null) {
- IBinding binding= name.resolveBinding();
- if (binding != null && !isFormalParameterInEnhancedForStatement(name) && isSideEffectFree(name, compilationUnit)) {
- VariableDeclarationFragment parent= (VariableDeclarationFragment)ASTNodes.getParent(name, VariableDeclarationFragment.class);
- if (parent != null) {
- ASTNode varDecl= parent.getParent();
- if (!variableDeclarations.containsKey(varDecl)) {
- variableDeclarations.put(varDecl, new ArrayList());
- }
- ((List)variableDeclarations.get(varDecl)).add(name);
- } else {
- result.add(new RemoveUnusedMemberOperation(new SimpleName[] {name}, false));
- }
- }
- }
- }
- }
- for (Iterator iter= variableDeclarations.keySet().iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode)iter.next();
- List names= (List)variableDeclarations.get(node);
- result.add(new RemoveUnusedMemberOperation((SimpleName[])names.toArray(new SimpleName[names.size()]), false));
- }
-
- if (result.size() == 0)
- return null;
-
- return new UnusedCodeFix(FixMessages.UnusedCodeFix_change_name, compilationUnit, (IFixRewriteOperation[])result.toArray(new IFixRewriteOperation[result.size()]));
- }
-
- private static boolean isFormalParameterInEnhancedForStatement(SimpleName name) {
- return name.getParent() instanceof SingleVariableDeclaration && name.getParent().getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY;
- }
-
- private static boolean isSideEffectFree(SimpleName simpleName, JavaScriptUnit completeRoot) {
- SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
- SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
- for (int i= 0; i < references.length; i++) {
- if (hasSideEffect(references[i]))
- return false;
- }
- return true;
- }
-
- private static boolean hasSideEffect(SimpleName reference) {
- ASTNode parent= reference.getParent();
- while (parent instanceof QualifiedName) {
- parent= parent.getParent();
- }
- if (parent instanceof FieldAccess) {
- parent= parent.getParent();
- }
-
- ASTNode node= null;
- int nameParentType= parent.getNodeType();
- if (nameParentType == ASTNode.ASSIGNMENT) {
- Assignment assignment= (Assignment) parent;
- node= assignment.getRightHandSide();
- } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
- SingleVariableDeclaration decl= (SingleVariableDeclaration)parent;
- node= decl.getInitializer();
- if (node == null)
- return false;
- } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- node= parent;
- } else {
- return false;
- }
-
- ArrayList sideEffects= new ArrayList();
- node.accept(new SideEffectFinder(sideEffects));
- return sideEffects.size() > 0;
- }
-
- private static SimpleName getUnusedName(JavaScriptUnit compilationUnit, IProblemLocation problem) {
- ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
-
- if (selectedNode instanceof FunctionDeclaration) {
- return ((FunctionDeclaration) selectedNode).getName();
- } else if (selectedNode instanceof SimpleName) {
- return (SimpleName) selectedNode;
- }
-
- return null;
- }
-
- private static String getDisplayString(SimpleName simpleName, IBinding binding, boolean forceRemoveInitializer) {
- String name= simpleName.getIdentifier();
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return Messages.format(FixMessages.UnusedCodeFix_RemoveType_description, name);
- case IBinding.METHOD:
- if (((IFunctionBinding) binding).isConstructor()) {
- return Messages.format(FixMessages.UnusedCodeFix_RemoveConstructor_description, name);
- } else {
- return Messages.format(FixMessages.UnusedCodeFix_RemoveMethod_description, name);
- }
- case IBinding.VARIABLE:
- if (forceRemoveInitializer) {
- return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description, name);
- } else {
- return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_description, name);
- }
- default:
- return ""; //$NON-NLS-1$
- }
- }
-
- private static Map getCleanUpOptions(IBinding binding) {
- Map result= new Hashtable();
-
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpConstants.TRUE);
- switch (binding.getKind()) {
- case IBinding.TYPE:
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES, CleanUpConstants.TRUE);
- break;
- case IBinding.METHOD:
- if (((IFunctionBinding) binding).isConstructor()) {
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, CleanUpConstants.TRUE);
- } else {
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS, CleanUpConstants.TRUE);
- }
- break;
- case IBinding.VARIABLE:
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS, CleanUpConstants.TRUE);
- result.put(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES, CleanUpConstants.TRUE);
- break;
- }
-
- return result;
- }
-
- private static ImportDeclaration getImportDeclaration(IProblemLocation problem, JavaScriptUnit compilationUnit) {
- ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
- if (selectedNode != null) {
- ASTNode node= ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
- if (node instanceof ImportDeclaration) {
- return (ImportDeclaration)node;
- }
- }
- return null;
- }
-
- private final Map fCleanUpOptions;
-
- private UnusedCodeFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- this(name, compilationUnit, fixRewriteOperations, null);
- }
-
- private UnusedCodeFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations, Map options) {
- super(name, compilationUnit, fixRewriteOperations);
- if (options == null) {
- fCleanUpOptions= new Hashtable();
- } else {
- fCleanUpOptions= options;
- }
- }
-
- public UnusedCodeCleanUp getCleanUp() {
- return new UnusedCodeCleanUp(fCleanUpOptions);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/VariableDeclarationFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/VariableDeclarationFix.java
deleted file mode 100644
index cb4465f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/VariableDeclarationFix.java
+++ /dev/null
@@ -1,535 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.fix;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.VariableDeclarationRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-
-public class VariableDeclarationFix extends AbstractFix {
-
- private static class WrittenNamesFinder extends GenericVisitor {
-
- private final HashMap fResult;
-
- public WrittenNamesFinder(HashMap result) {
- fResult= result;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(SimpleName node) {
- if (node.getParent() instanceof VariableDeclarationFragment)
- return super.visit(node);
- if (node.getParent() instanceof SingleVariableDeclaration)
- return super.visit(node);
-
- IBinding binding= node.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return super.visit(node);
-
- binding= ((IVariableBinding)binding).getVariableDeclaration();
- if (ASTResolving.isWriteAccess(node)) {
- List list;
- if (fResult.containsKey(binding)) {
- list= (List)fResult.get(binding);
- } else {
- list= new ArrayList();
- }
- list.add(node);
- fResult.put(binding, list);
- }
-
- return super.visit(node);
- }
- }
-
- private static class VariableDeclarationFinder extends GenericVisitor {
-
- private final JavaScriptUnit fCompilationUnit;
- private final List fResult;
- private final HashMap fWrittenVariables;
- private final boolean fAddFinalFields;
- private final boolean fAddFinalParameters;
- private final boolean fAddFinalLocals;
-
- public VariableDeclarationFinder(boolean addFinalFields,
- boolean addFinalParameters,
- boolean addFinalLocals,
- final JavaScriptUnit compilationUnit, final List result, final HashMap writtenNames) {
-
- super();
- fAddFinalFields= addFinalFields;
- fAddFinalParameters= addFinalParameters;
- fAddFinalLocals= addFinalLocals;
- fCompilationUnit= compilationUnit;
- fResult= result;
- fWrittenVariables= writtenNames;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(FieldDeclaration node) {
- if (fAddFinalFields)
- return handleFragments(node.fragments(), node);
-
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(VariableDeclarationStatement node) {
- if (fAddFinalLocals)
- return handleFragments(node.fragments(), node);
-
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(VariableDeclarationExpression node) {
- if (fAddFinalLocals && node.fragments().size() == 1) {
- SimpleName name= ((VariableDeclarationFragment)node.fragments().get(0)).getName();
-
- IBinding binding= name.resolveBinding();
- if (binding == null)
- return false;
-
- if (fWrittenVariables.containsKey(binding))
- return false;
-
- ModifierChangeOperation op= createAddFinalOperation(name, fCompilationUnit, node);
- if (op == null)
- return false;
-
- fResult.add(op);
- return false;
- }
- return false;
- }
-
- private boolean handleFragments(List list, ASTNode declaration) {
- List toChange= new ArrayList();
-
- for (Iterator iter= list.iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)iter.next();
- SimpleName name= fragment.getName();
- IBinding resolveBinding= name.resolveBinding();
- if (canAddFinal(resolveBinding, name, declaration)) {
- IVariableBinding varbinding= (IVariableBinding)resolveBinding;
- if (varbinding.isField()) {
- if (fieldCanBeFinal(fragment, varbinding))
- toChange.add(fragment);
- } else {
- if (!fWrittenVariables.containsKey(resolveBinding))
- toChange.add(fragment);
- }
- }
- }
-
- if (toChange.size() == 0)
- return false;
-
- ModifierChangeOperation op= new ModifierChangeOperation(declaration, toChange, Modifier.FINAL, Modifier.VOLATILE);
- fResult.add(op);
- return false;
- }
-
- private boolean fieldCanBeFinal(VariableDeclarationFragment fragment, IVariableBinding binding) {
- if (Modifier.isStatic(((FieldDeclaration)fragment.getParent()).getModifiers()))
- return false;
-
- if (!fWrittenVariables.containsKey(binding)) {
- //variable is not written
- if (fragment.getInitializer() == null) {//variable is not initialized
- return false;
- } else {
- return true;
- }
- }
-
- if (fragment.getInitializer() != null)//variable is initialized and written
- return false;
-
- ITypeBinding declaringClass= binding.getDeclaringClass();
- if (declaringClass == null)
- return false;
-
- ArrayList writes= (ArrayList)fWrittenVariables.get(binding);
- if (!isWrittenInTypeConstructors(binding, writes, declaringClass))
- return false;
-
- HashSet writingConstructorBindings= new HashSet();
- ArrayList writingConstructors= new ArrayList();
- for (int i= 0; i < writes.size(); i++) {
- SimpleName name= (SimpleName)writes.get(i);
- FunctionDeclaration constructor= getWritingConstructor(name);
- if (writingConstructors.contains(constructor))//variable is written twice or more in constructor
- return false;
-
- writingConstructors.add(constructor);
- IFunctionBinding constructorBinding= constructor.resolveBinding();
- if (constructorBinding == null)
- return false;
-
- writingConstructorBindings.add(constructorBinding);
- }
-
- for (int i= 0; i < writingConstructors.size(); i++) {
- FunctionDeclaration constructor= (FunctionDeclaration)writingConstructors.get(i);
- if (callsWrittingConstructor(constructor, writingConstructorBindings))//writing constructor calls other writing constructor
- return false;
- }
-
- FunctionDeclaration constructor= (FunctionDeclaration)writingConstructors.get(0);
- TypeDeclaration typeDecl= (TypeDeclaration)ASTNodes.getParent(constructor, TypeDeclaration.class);
- if (typeDecl == null)
- return false;
-
- FunctionDeclaration[] methods= typeDecl.getMethods();
- for (int i= 0; i < methods.length; i++) {
- if (methods[i].isConstructor()) {
- IFunctionBinding methodBinding= methods[i].resolveBinding();
- if (methodBinding == null)
- return false;
-
- if (!writingConstructorBindings.contains(methodBinding)) {
- if (!callsWrittingConstructor(methods[i], writingConstructorBindings))//non writing constructor does not call a writing constructor
- return false;
- }
- }
- }
-
- return true;
- }
-
- private boolean callsWrittingConstructor(FunctionDeclaration methodDeclaration, HashSet writingConstructorBindings) {
- Block body= methodDeclaration.getBody();
- if (body == null)
- return false;
-
- List statements= body.statements();
- if (statements.size() == 0)
- return false;
-
- Statement statement= (Statement)statements.get(0);
- if (!(statement instanceof ConstructorInvocation))
- return false;
-
- ConstructorInvocation invocation= (ConstructorInvocation)statement;
- IFunctionBinding constructorBinding= invocation.resolveConstructorBinding();
- if (constructorBinding == null)
- return false;
-
- if (writingConstructorBindings.contains(constructorBinding)) {
- return true;
- } else {
- ASTNode declaration= ASTNodes.findDeclaration(constructorBinding, methodDeclaration.getParent());
- if (!(declaration instanceof FunctionDeclaration))
- return false;
-
- return callsWrittingConstructor((FunctionDeclaration)declaration, writingConstructorBindings);
- }
- }
-
- private boolean isWrittenInTypeConstructors(IVariableBinding binding, ArrayList writes, ITypeBinding declaringClass) {
-
- for (int i= 0; i < writes.size(); i++) {
- SimpleName name= (SimpleName)writes.get(i);
-
- FunctionDeclaration methodDeclaration= getWritingConstructor(name);
- if (methodDeclaration == null)
- return false;
-
- if (!methodDeclaration.isConstructor())
- return false;
-
- IFunctionBinding constructor= methodDeclaration.resolveBinding();
- if (constructor == null)
- return false;
-
- ITypeBinding declaringClass2= constructor.getDeclaringClass();
- if (!declaringClass.equals(declaringClass2))
- return false;
- }
-
- return true;
- }
-
- private FunctionDeclaration getWritingConstructor(SimpleName name) {
- Assignment assignement= (Assignment)ASTNodes.getParent(name, Assignment.class);
- if (assignement == null)
- return null;
-
- ASTNode expression= assignement.getParent();
- if (!(expression instanceof ExpressionStatement))
- return null;
-
- ASTNode block= expression.getParent();
- if (!(block instanceof Block))
- return null;
-
- ASTNode methodDeclaration= block.getParent();
- if (!(methodDeclaration instanceof FunctionDeclaration))
- return null;
-
- return (FunctionDeclaration)methodDeclaration;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(VariableDeclarationFragment node) {
- SimpleName name= node.getName();
-
- IBinding binding= name.resolveBinding();
- if (binding == null)
- return false;
-
- if (fWrittenVariables.containsKey(binding))
- return false;
-
- ModifierChangeOperation op= createAddFinalOperation(name, fCompilationUnit, node);
- if (op == null)
- return false;
-
- fResult.add(op);
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean visit(SingleVariableDeclaration node) {
- SimpleName name= node.getName();
-
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return false;
-
- IVariableBinding varBinding= (IVariableBinding)binding;
- if (fWrittenVariables.containsKey(varBinding))
- return false;
-
- if (fAddFinalParameters && fAddFinalLocals) {
-
- ModifierChangeOperation op= createAddFinalOperation(name, fCompilationUnit, node);
- if (op == null)
- return false;
-
- fResult.add(op);
- return false;
- } else if (fAddFinalParameters) {
- if (!varBinding.isParameter())
- return false;
-
- ModifierChangeOperation op= createAddFinalOperation(name, fCompilationUnit, node);
- if (op == null)
- return false;
-
- fResult.add(op);
- return false;
- } else if (fAddFinalLocals) {
- if (varBinding.isParameter())
- return false;
-
- ModifierChangeOperation op= createAddFinalOperation(name, fCompilationUnit, node);
- if (op == null)
- return false;
-
- fResult.add(op);
- return false;
- }
- return false;
- }
- }
-
- private static class ModifierChangeOperation extends AbstractFixRewriteOperation {
-
- private final ASTNode fDeclaration;
- private final List fToChange;
- private final int fIncludedModifiers;
- private final int fExcludedModifiers;
-
- public ModifierChangeOperation(ASTNode declaration, List toChange, int includedModifiers, int excludedModifiers) {
- fDeclaration= declaration;
- fToChange= toChange;
- fIncludedModifiers= includedModifiers;
- fExcludedModifiers= excludedModifiers;
- }
-
- /**
- * {@inheritDoc}
- */
- public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups) throws CoreException {
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
-
- TextEditGroup group= createTextEditGroup(FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description);
- textEditGroups.add(group);
-
- if (fDeclaration instanceof VariableDeclarationStatement) {
- VariableDeclarationFragment[] toChange= (VariableDeclarationFragment[])fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]);
- VariableDeclarationRewrite.rewriteModifiers((VariableDeclarationStatement)fDeclaration, toChange, fIncludedModifiers, fExcludedModifiers, rewrite, group);
- } else if (fDeclaration instanceof FieldDeclaration) {
- VariableDeclarationFragment[] toChange= (VariableDeclarationFragment[])fToChange.toArray(new VariableDeclarationFragment[fToChange.size()]);
- VariableDeclarationRewrite.rewriteModifiers((FieldDeclaration)fDeclaration, toChange, fIncludedModifiers, fExcludedModifiers, rewrite, group);
- } else if (fDeclaration instanceof SingleVariableDeclaration) {
- VariableDeclarationRewrite.rewriteModifiers((SingleVariableDeclaration)fDeclaration, fIncludedModifiers, fExcludedModifiers, rewrite, group);
- } else if (fDeclaration instanceof VariableDeclarationExpression) {
- VariableDeclarationRewrite.rewriteModifiers((VariableDeclarationExpression)fDeclaration, fIncludedModifiers, fExcludedModifiers, rewrite, group);
- }
- }
- }
-
- public static IFix createChangeModifierToFinalFix(final JavaScriptUnit compilationUnit, ASTNode[] selectedNodes) {
- HashMap writtenNames= new HashMap();
- WrittenNamesFinder finder= new WrittenNamesFinder(writtenNames);
- compilationUnit.accept(finder);
- List ops= new ArrayList();
- VariableDeclarationFinder visitor= new VariableDeclarationFinder(true, true, true, compilationUnit, ops, writtenNames);
- if (selectedNodes.length == 1) {
- if (selectedNodes[0] instanceof SimpleName) {
- selectedNodes[0]= selectedNodes[0].getParent();
- }
- selectedNodes[0].accept(visitor);
- } else {
- for (int i= 0; i < selectedNodes.length; i++) {
- ASTNode selectedNode= selectedNodes[i];
- selectedNode.accept(visitor);
- }
- }
- if (ops.size() == 0)
- return null;
-
- IFixRewriteOperation[] result= (IFixRewriteOperation[])ops.toArray(new IFixRewriteOperation[ops.size()]);
- String label;
- if (result.length == 1) {
- label= FixMessages.VariableDeclarationFix_changeModifierOfUnknownToFinal_description;
- } else {
- label= FixMessages.VariableDeclarationFix_ChangeMidifiersToFinalWherPossible_description;
- }
- return new VariableDeclarationFix(label, compilationUnit, result);
- }
-
- public static IFix createCleanUp(JavaScriptUnit compilationUnit,
- boolean addFinalFields, boolean addFinalParameters, boolean addFinalLocals) {
-
- if (!addFinalFields && !addFinalParameters && !addFinalLocals)
- return null;
-
- HashMap writtenNames= new HashMap();
- WrittenNamesFinder finder= new WrittenNamesFinder(writtenNames);
- compilationUnit.accept(finder);
-
- List operations= new ArrayList();
- VariableDeclarationFinder visitor= new VariableDeclarationFinder(addFinalFields, addFinalParameters, addFinalLocals, compilationUnit, operations, writtenNames);
- compilationUnit.accept(visitor);
-
- if (operations.isEmpty())
- return null;
-
- return new VariableDeclarationFix(FixMessages.VariableDeclarationFix_add_final_change_name, compilationUnit, (IFixRewriteOperation[])operations.toArray(new IFixRewriteOperation[operations.size()]));
- }
-
- private static ModifierChangeOperation createAddFinalOperation(SimpleName name, JavaScriptUnit compilationUnit, ASTNode decl) {
- if (decl == null)
- return null;
-
- IBinding binding= name.resolveBinding();
- if (!canAddFinal(binding, name, decl))
- return null;
-
- if (decl instanceof SingleVariableDeclaration) {
- return new ModifierChangeOperation(decl, new ArrayList(), Modifier.FINAL, Modifier.VOLATILE);
- } else if (decl instanceof VariableDeclarationExpression) {
- return new ModifierChangeOperation(decl, new ArrayList(), Modifier.FINAL, Modifier.VOLATILE);
- } else if (decl instanceof VariableDeclarationFragment){
- VariableDeclarationFragment frag= (VariableDeclarationFragment)decl;
- decl= decl.getParent();
- if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
- List list= new ArrayList();
- list.add(frag);
- return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.VOLATILE);
- } else if (decl instanceof VariableDeclarationExpression) {
- return new ModifierChangeOperation(decl, new ArrayList(), Modifier.FINAL, Modifier.VOLATILE);
- }
- }
-
- return null;
- }
-
- private static boolean canAddFinal(IBinding binding, SimpleName name, ASTNode declNode) {
- if (!(binding instanceof IVariableBinding))
- return false;
-
- IVariableBinding varbinding= (IVariableBinding)binding;
- if (Modifier.isFinal(varbinding.getModifiers()))
- return false;
-
- ASTNode parent= ASTNodes.getParent(declNode, VariableDeclarationExpression.class);
- if (parent != null && ((VariableDeclarationExpression)parent).fragments().size() > 1)
- return false;
-
- if (varbinding.isField() && !Modifier.isPrivate(varbinding.getModifiers()))
- return false;
-
- if (varbinding.isParameter()) {
- ASTNode varDecl= declNode.getParent();
- if (varDecl instanceof FunctionDeclaration) {
- FunctionDeclaration declaration= (FunctionDeclaration)varDecl;
- if (declaration.getBody() == null)
- return false;
- }
- }
-
- return true;
- }
-
- protected VariableDeclarationFix(String name, JavaScriptUnit compilationUnit, IFixRewriteOperation[] fixRewriteOperations) {
- super(name, compilationUnit, fixRewriteOperations);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java
deleted file mode 100644
index 645928f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.javadoc;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.SingleCharReader;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-
-
-/**
- * Reads a java doc comment from a java doc comment. Skips star-character
- * on begin of line
- */
-public class JavaDocCommentReader extends SingleCharReader {
-
- private IBuffer fBuffer;
-
- private int fCurrPos;
- private int fStartPos;
- private int fEndPos;
-
- private boolean fWasNewLine;
-
- public JavaDocCommentReader(IBuffer buf, int start, int end) {
- fBuffer= buf;
- fStartPos= start + 3;
- fEndPos= end - 2;
-
- reset();
- }
-
- /**
- * @see java.io.Reader#read()
- */
- public int read() {
- if (fCurrPos < fEndPos) {
- char ch;
- if (fWasNewLine) {
- do {
- ch= fBuffer.getChar(fCurrPos++);
- } while (fCurrPos < fEndPos && Character.isWhitespace(ch));
- if (ch == '*') {
- if (fCurrPos < fEndPos) {
- do {
- ch= fBuffer.getChar(fCurrPos++);
- } while (ch == '*');
- } else {
- return -1;
- }
- }
- } else {
- ch= fBuffer.getChar(fCurrPos++);
- }
- fWasNewLine= IndentManipulation.isLineDelimiterChar(ch);
-
- return ch;
- }
- return -1;
- }
-
- /**
- * @see java.io.Reader#close()
- */
- public void close() {
- fBuffer= null;
- }
-
- /**
- * @see java.io.Reader#reset()
- */
- public void reset() {
- fCurrPos= fStartPos;
- fWasNewLine= true;
- }
-
-
- /**
- * Returns the offset of the last read character in the passed buffer.
- */
- public int getOffset() {
- return fCurrPos;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocLocations.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocLocations.java
deleted file mode 100644
index 2cfee5f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocLocations.java
+++ /dev/null
@@ -1,582 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.javadoc;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.CorextMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIException;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathSupport;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-public class JavaDocLocations {
-
- public static final String ARCHIVE_PREFIX= "jar:"; //$NON-NLS-1$
- private static final String PREF_JAVADOCLOCATIONS= "org.eclipse.wst.jsdt.ui.javadoclocations"; //$NON-NLS-1$
- public static final String PREF_JAVADOCLOCATIONS_MIGRATED= "org.eclipse.wst.jsdt.ui.javadoclocations.migrated"; //$NON-NLS-1$
-
-
- private static final String NODE_ROOT= "javadoclocation"; //$NON-NLS-1$
- private static final String NODE_ENTRY= "location_01"; //$NON-NLS-1$
- private static final String NODE_PATH= "path"; //$NON-NLS-1$
- private static final String NODE_URL= "url"; //$NON-NLS-1$
-
- private static final QualifiedName PROJECT_JAVADOC= new QualifiedName(JavaScriptUI.ID_PLUGIN, "project_javadoc_location"); //$NON-NLS-1$
-
- public static void migrateToClasspathAttributes() {
- final Map oldLocations= loadOldForCompatibility();
- if (oldLocations.isEmpty()) {
- IPreferenceStore preferenceStore= PreferenceConstants.getPreferenceStore();
- preferenceStore.setValue(PREF_JAVADOCLOCATIONS, ""); //$NON-NLS-1$
- preferenceStore.setValue(PREF_JAVADOCLOCATIONS_MIGRATED, true);
- return;
- }
-
- Job job= new Job(CorextMessages.JavaDocLocations_migratejob_name) {
- protected IStatus run(IProgressMonitor monitor) {
- try {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor pm) throws CoreException {
- updateClasspathEntries(oldLocations, pm);
- IPreferenceStore preferenceStore= PreferenceConstants.getPreferenceStore();
- preferenceStore.setValue(PREF_JAVADOCLOCATIONS, ""); //$NON-NLS-1$
- preferenceStore.setValue(PREF_JAVADOCLOCATIONS_MIGRATED, true);
- }
- };
- new WorkbenchRunnableAdapter(runnable).run(monitor);
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- } catch (InterruptedException e) {
- // should not happen, cannot cancel
- }
- return Status.OK_STATUS;
- }
- };
- job.schedule();
- }
-
- final static void updateClasspathEntries(Map oldLocationMap, IProgressMonitor monitor) throws JavaScriptModelException {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IJavaScriptProject[] javaProjects= JavaScriptCore.create(root).getJavaScriptProjects();
- try {
- monitor.beginTask(CorextMessages.JavaDocLocations_migrate_operation, javaProjects.length);
- for (int i= 0; i < javaProjects.length; i++) {
- IJavaScriptProject project= javaProjects[i];
- String projectJavadoc= (String) oldLocationMap.get(project.getPath());
- if (projectJavadoc != null) {
- try {
- setProjectJavadocLocation(project, projectJavadoc);
- } catch (CoreException e) {
- // ignore
- }
- }
-
- IIncludePathEntry[] rawClasspath= project.getRawIncludepath();
- boolean hasChange= false;
- for (int k= 0; k < rawClasspath.length; k++) {
- IIncludePathEntry updated= getConvertedEntry(rawClasspath[k], project, oldLocationMap);
- if (updated != null) {
- rawClasspath[k]= updated;
- hasChange= true;
- }
- }
- if (hasChange) {
- project.setRawIncludepath(rawClasspath, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- private static IIncludePathEntry getConvertedEntry(IIncludePathEntry entry, IJavaScriptProject project, Map oldLocationMap) {
- IPath path= null;
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- case IIncludePathEntry.CPE_PROJECT:
- return null;
- case IIncludePathEntry.CPE_CONTAINER:
- convertContainer(entry, project, oldLocationMap);
- return null;
- case IIncludePathEntry.CPE_LIBRARY:
- path= entry.getPath();
- break;
- case IIncludePathEntry.CPE_VARIABLE:
- path= JavaScriptCore.getResolvedVariablePath(entry.getPath());
- break;
- default:
- return null;
- }
- if (path == null) {
- return null;
- }
- IIncludePathAttribute[] extraAttributes= entry.getExtraAttributes();
- for (int i= 0; i < extraAttributes.length; i++) {
- if (IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME.equals(extraAttributes[i].getName())) {
- return null;
- }
- }
- String libraryJavadocLocation= (String) oldLocationMap.get(path);
- if (libraryJavadocLocation != null) {
- CPListElement element= CPListElement.createFromExisting(entry, project);
- element.setAttribute(CPListElement.JAVADOC, libraryJavadocLocation);
- return element.getClasspathEntry();
- }
- return null;
- }
-
- private static void convertContainer(IIncludePathEntry entry, IJavaScriptProject project, Map oldLocationMap) {
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), project);
- if (container == null) {
- return;
- }
-
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- boolean hasChange= false;
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr= entries[i];
- IIncludePathEntry updatedEntry= getConvertedEntry(curr, project, oldLocationMap);
- if (updatedEntry != null) {
- entries[i]= updatedEntry;
- hasChange= true;
- }
- }
- if (hasChange) {
- BuildPathSupport.requestContainerUpdate(project, container, entries);
- }
- } catch (CoreException e) {
- // ignore
- }
- }
-
- /**
- * Sets the Javadoc location for an archive with the given path.
- */
- public static void setProjectJavadocLocation(IJavaScriptProject project, URL url) {
- try {
- String location= url != null ? url.toExternalForm() : null;
- setProjectJavadocLocation(project, location);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static void setProjectJavadocLocation(IJavaScriptProject project, String url) throws CoreException {
- project.getProject().setPersistentProperty(PROJECT_JAVADOC, url);
- }
-
- public static URL getProjectJavadocLocation(IJavaScriptProject project) {
- try {
- String prop= project.getProject().getPersistentProperty(PROJECT_JAVADOC);
- if (prop == null) {
- return null;
- }
- return new URL(prop);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
-
- public static URL getLibraryJavadocLocation(IIncludePathEntry entry) {
- if (entry == null) {
- throw new IllegalArgumentException("Entry must not be null"); //$NON-NLS-1$
- }
-
- int kind= entry.getEntryKind();
- if (kind != IIncludePathEntry.CPE_LIBRARY && kind != IIncludePathEntry.CPE_VARIABLE) {
- throw new IllegalArgumentException("Entry must be of kind CPE_LIBRARY or CPE_VARIABLE"); //$NON-NLS-1$
- }
-
- IIncludePathAttribute[] extraAttributes= entry.getExtraAttributes();
- for (int i= 0; i < extraAttributes.length; i++) {
- IIncludePathAttribute attrib= extraAttributes[i];
- if (IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
- try {
- return new URL(attrib.getValue());
- } catch (MalformedURLException e) {
- return null;
- }
- }
- }
- return null;
- }
-
- public static URL getJavadocBaseLocation(IJavaScriptElement element) throws JavaScriptModelException {
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- return getProjectJavadocLocation((IJavaScriptProject) element);
- }
-
- IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
- if (root == null) {
- return null;
- }
-
- if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null) {
- return null;
- }
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- entry= getRealClasspathEntry(root.getJavaScriptProject(), entry.getPath(), root.getPath());
- if (entry == null) {
- return null;
- }
- }
- return getLibraryJavadocLocation(entry);
- } else {
- return getProjectJavadocLocation(root.getJavaScriptProject());
- }
- }
-
- private static IIncludePathEntry getRealClasspathEntry(IJavaScriptProject jproject, IPath containerPath, IPath libPath) throws JavaScriptModelException {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- if (container != null) {
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr= entries[i];
- IIncludePathEntry resolved= JavaScriptCore.getResolvedIncludepathEntry(curr);
- if (resolved != null && libPath.equals(resolved.getPath())) {
- return curr; // return the real entry
- }
- }
- }
- return null; // not found
- }
-
-
- // loading for compatibility
-
- private static JavaUIException createException(Throwable t, String message) {
- return new JavaUIException(JavaUIStatus.createError(IStatus.ERROR, message, t));
- }
-
- private static Map/*<Path, String>*/ loadOldForCompatibility() {
- HashMap resultingOldLocations= new HashMap();
-
- // in 3.0, the javadoc locations were stored as one big string in the preferences
- String string= PreferenceConstants.getPreferenceStore().getString(PREF_JAVADOCLOCATIONS);
- if (string != null && string.length() > 0) {
- byte[] bytes;
- try {
- bytes= string.getBytes("UTF-8"); //$NON-NLS-1$
- } catch (UnsupportedEncodingException e) {
- bytes= string.getBytes();
- }
- InputStream is= new ByteArrayInputStream(bytes);
- try {
- loadFromStream(new InputSource(is), resultingOldLocations);
- PreferenceConstants.getPreferenceStore().setValue(PREF_JAVADOCLOCATIONS, ""); //$NON-NLS-1$
- return resultingOldLocations;
- } catch (CoreException e) {
- JavaScriptPlugin.log(e); // log but ignore
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
-
- // in 2.1, the Javadoc locations were stored in a file in the meta data
- // note that it is wrong to use a stream reader with XML declaring to be UTF-8
- try {
- final String STORE_FILE= "javadoclocations.xml"; //$NON-NLS-1$
- File file= JavaScriptPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
- if (file.exists()) {
- Reader reader= null;
- try {
- reader= new FileReader(file);
- loadFromStream(new InputSource(reader), resultingOldLocations);
- file.delete(); // remove file after successful store
- return resultingOldLocations;
- } catch (IOException e) {
- JavaScriptPlugin.log(e); // log but ignore
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {}
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e); // log but ignore
- }
-
- // in 2.0, the Javadoc locations were stored as one big string in the persistent properties
- // note that it is wrong to use a stream reader with XML declaring to be UTF-8
- try {
- final QualifiedName QUALIFIED_NAME= new QualifiedName(JavaScriptUI.ID_PLUGIN, "jdoclocation"); //$NON-NLS-1$
-
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- String xmlString= root.getPersistentProperty(QUALIFIED_NAME);
- if (xmlString != null) { // only set when workspace is old
- Reader reader= new StringReader(xmlString);
- try {
- loadFromStream(new InputSource(reader), resultingOldLocations);
- root.setPersistentProperty(QUALIFIED_NAME, null); // clear property
- return resultingOldLocations;
- } finally {
-
- try {
- reader.close();
- } catch (IOException e) {
- // error closing reader: ignore
- }
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e); // log but ignore
- }
- return resultingOldLocations;
- }
-
- private static void loadFromStream(InputSource inputSource, Map/*<Path, String>*/ oldLocations) throws CoreException {
- Element cpElement;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- cpElement = parser.parse(inputSource).getDocumentElement();
- } catch (SAXException e) {
- throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
- } catch (ParserConfigurationException e) {
- throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
- } catch (IOException e) {
- throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
- }
-
- if (cpElement == null) return;
- if (!cpElement.getNodeName().equalsIgnoreCase(NODE_ROOT)) {
- return;
- }
- NodeList list= cpElement.getChildNodes();
- int length= list.getLength();
- for (int i= 0; i < length; ++i) {
- Node node= list.item(i);
- short type= node.getNodeType();
- if (type == Node.ELEMENT_NODE) {
- Element element= (Element) node;
- if (element.getNodeName().equalsIgnoreCase(NODE_ENTRY)) {
- String varPath = element.getAttribute(NODE_PATH);
- String varURL = element.getAttribute(NODE_URL);
-
- oldLocations.put(Path.fromPortableString(varPath), varURL);
- }
- }
- }
- }
-
- public static URL getJavadocLocation(IJavaScriptElement element, boolean includeMemberReference) throws JavaScriptModelException {
- URL baseLocation= getJavadocBaseLocation(element);
- if (baseLocation == null) {
- return null;
- }
-
- String urlString= baseLocation.toExternalForm();
-
- StringBuffer pathBuffer= new StringBuffer(urlString);
- if (!urlString.endsWith("/")) { //$NON-NLS-1$
- pathBuffer.append('/');
- }
-
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- appendPackageSummaryPath((IPackageFragment) element, pathBuffer);
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- appendIndexPath(pathBuffer);
- break;
- case IJavaScriptElement.IMPORT_CONTAINER :
- element= element.getParent();
- //$FALL-THROUGH$
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- IType mainType= ((IJavaScriptUnit) element).findPrimaryType();
- if (mainType == null) {
- return null;
- }
- appendTypePath(mainType, pathBuffer);
- break;
- case IJavaScriptElement.CLASS_FILE :
- appendTypePath(((IClassFile) element).getType(), pathBuffer);
- break;
- case IJavaScriptElement.TYPE :
- appendTypePath((IType) element, pathBuffer);
- break;
- case IJavaScriptElement.FIELD :
- IField field= (IField) element;
- appendTypePath(field.getDeclaringType(), pathBuffer);
- if (includeMemberReference) {
- appendFieldReference(field, pathBuffer);
- }
- break;
- case IJavaScriptElement.METHOD :
- IFunction method= (IFunction) element;
- appendTypePath(method.getDeclaringType(), pathBuffer);
- if (includeMemberReference) {
- appendMethodReference(method, pathBuffer);
- }
- break;
- case IJavaScriptElement.INITIALIZER :
- appendTypePath(((IMember) element).getDeclaringType(), pathBuffer);
- break;
- case IJavaScriptElement.IMPORT_DECLARATION :
- IImportDeclaration decl= (IImportDeclaration) element;
-
- if (decl.isOnDemand()) {
- IJavaScriptElement cont= JavaModelUtil.findTypeContainer(element.getJavaScriptProject(), Signature.getQualifier(decl.getElementName()));
- if (cont instanceof IType) {
- appendTypePath((IType) cont, pathBuffer);
- } else if (cont instanceof IPackageFragment) {
- appendPackageSummaryPath((IPackageFragment) cont, pathBuffer);
- }
- } else {
- IType imp= element.getJavaScriptProject().findType(decl.getElementName());
- appendTypePath(imp, pathBuffer);
- }
- break;
- default :
- return null;
- }
-
- try {
- return new URL(pathBuffer.toString());
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- private static void appendPackageSummaryPath(IPackageFragment pack, StringBuffer buf) {
- String packPath= pack.getElementName().replace('.', '/');
- buf.append(packPath);
- buf.append("/package-summary.html"); //$NON-NLS-1$
- }
-
- private static void appendIndexPath(StringBuffer buf) {
- buf.append("index.html"); //$NON-NLS-1$
- }
-
- private static void appendTypePath(IType type, StringBuffer buf) {
- IPackageFragment pack= type.getPackageFragment();
- String packPath= pack.getElementName().replace('.', '/');
- String typePath= JavaModelUtil.getTypeQualifiedName(type);
- buf.append(packPath);
- buf.append('/');
- buf.append(typePath);
- buf.append(".html"); //$NON-NLS-1$
- }
-
- private static void appendFieldReference(IField field, StringBuffer buf) {
- buf.append('#');
- buf.append(field.getElementName());
- }
-
- private static void appendMethodReference(IFunction meth, StringBuffer buf) throws JavaScriptModelException {
- buf.append('#');
- buf.append(meth.getElementName());
-
- buf.append('(');
- String[] params= meth.getParameterTypes();
- IType declaringType= meth.getDeclaringType();
- boolean isVararg= Flags.isVarargs(meth.getFlags());
- int lastParam= params.length - 1;
- for (int i= 0; i <= lastParam; i++) {
- if (i != 0) {
- buf.append(", "); //$NON-NLS-1$
- }
- String curr= params[i];
- String fullName= JavaModelUtil.getResolvedTypeName(curr, declaringType);
- if (fullName != null) {
- buf.append(fullName);
- int dim= Signature.getArrayCount(curr);
- if (i == lastParam && isVararg) {
- dim--;
- }
- while (dim > 0) {
- buf.append("[]"); //$NON-NLS-1$
- dim--;
- }
- if (i == lastParam && isVararg) {
- buf.append("..."); //$NON-NLS-1$
- }
- }
- }
- buf.append(')');
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/AbstractJavaElementRenameChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/AbstractJavaElementRenameChange.java
deleted file mode 100644
index 0df19418..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/AbstractJavaElementRenameChange.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-
-public abstract class AbstractJavaElementRenameChange extends JDTChange {
-
- private final String fNewName;
-
- private final String fOldName;
-
- private final IPath fResourcePath;
-
- private final long fStampToRestore;
-
- protected AbstractJavaElementRenameChange(IPath resourcePath, String oldName, String newName) {
- this(resourcePath, oldName, newName, IResource.NULL_STAMP);
- }
-
- protected AbstractJavaElementRenameChange(IPath resourcePath, String oldName, String newName, long stampToRestore) {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- Assert.isNotNull(oldName, "old name"); //$NON-NLS-1$
- fResourcePath= resourcePath;
- fOldName= oldName;
- fNewName= newName;
- fStampToRestore= stampToRestore;
- }
-
- protected abstract IPath createNewPath();
-
- protected abstract Change createUndoChange(long stampToRestore) throws CoreException;
-
- protected abstract void doRename(IProgressMonitor pm) throws CoreException;
-
- public Object getModifiedElement() {
- return JavaScriptCore.create(getResource());
- }
-
- public String getNewName() {
- return fNewName;
- }
-
- public String getOldName() {
- return fOldName;
- }
-
- protected final IResource getResource() {
- return ResourcesPlugin.getWorkspace().getRoot().findMember(fResourcePath);
- }
-
- protected IPath getResourcePath() {
- return fResourcePath;
- }
-
- public final Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.AbstractRenameChange_Renaming, 1);
- IResource resource= getResource();
- IPath newPath= createNewPath();
- Change result= createUndoChange(resource.getModificationStamp());
- doRename(new SubProgressMonitor(pm, 1));
- if (fStampToRestore != IResource.NULL_STAMP) {
- IResource newResource= ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
- newResource.revertModificationStamp(fStampToRestore);
- }
- return result;
- } finally {
- pm.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/Checks.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/Checks.java
deleted file mode 100644
index 65de42e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/Checks.java
+++ /dev/null
@@ -1,829 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-/**
- * This class defines a set of reusable static checks methods.
- */
-public class Checks {
-
- /*
- * no instances
- */
- private Checks(){
- }
-
- /* Constants returned by checkExpressionIsRValue */
- public static final int IS_RVALUE= 0;
- public static final int NOT_RVALUE_MISC= 1;
- public static final int NOT_RVALUE_VOID= 2;
-
- /**
- * Checks if method will have a constructor name after renaming.
- * @param method
- * @param newMethodName
- * @param newTypeName
- * @return <code>RefactoringStatus</code> with <code>WARNING</code> severity if
- * the give method will have a constructor name after renaming
- * <code>null</code> otherwise.
- */
- public static RefactoringStatus checkIfConstructorName(IFunction method, String newMethodName, String newTypeName){
- if (! newMethodName.equals(newTypeName))
- return null;
- else
- return RefactoringStatus.createWarningStatus(
- Messages.format(RefactoringCoreMessages.Checks_constructor_name,
- new Object[] {JavaElementUtil.createMethodSignature(method), JavaModelUtil.getFullyQualifiedName(method.getDeclaringType()) } ));
- }
-
- /**
- * Checks if the given name is a valid Java field name.
- *
- * @param name the java field name.
- * @return a refactoring status containing the error message if the
- * name is not a valid java field name.
- */
- public static RefactoringStatus checkFieldName(String name) {
- return checkName(name, JavaScriptConventions.validateFieldName(name));
- }
-
- /**
- * Checks if the given name is a valid Java type parameter name.
- *
- * @param name the java type parameter name.
- * @return a refactoring status containing the error message if the
- * name is not a valid java type parameter name.
- */
- public static RefactoringStatus checkTypeParameterName(String name) {
- return checkName(name, JavaScriptConventions.validateTypeVariableName(name));
- }
-
- /**
- * Checks if the given name is a valid Java identifier.
- *
- * @param name the java identifier.
- * @return a refactoring status containing the error message if the
- * name is not a valid java identifier.
- */
- public static RefactoringStatus checkIdentifier(String name) {
- return checkName(name, JavaScriptConventions.validateIdentifier(name));
- }
-
- /**
- * Checks if the given name is a valid Java method name.
- *
- * @param name the java method name.
- * @return a refactoring status containing the error message if the
- * name is not a valid java method name.
- */
- public static RefactoringStatus checkMethodName(String name) {
- RefactoringStatus status= checkName(name, JavaScriptConventions.validateFunctionName(name));
- if (status.isOK() && startsWithUpperCase(name))
- return RefactoringStatus.createWarningStatus(RefactoringCoreMessages.Checks_method_names_lowercase);
- else
- return status;
- }
-
- /**
- * Checks if the given name is a valid Java type name.
- *
- * @param name the java method name.
- * @return a refactoring status containing the error message if the
- * name is not a valid java type name.
- */
- public static RefactoringStatus checkTypeName(String name) {
- //fix for: 1GF5Z0Z: ITPJUI:WINNT - assertion failed after renameType refactoring
-// if (name.indexOf(".") != -1) //$NON-NLS-1$
-// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.Checks_no_dot);
-// else
- return checkName(name, JavaScriptConventions.validateJavaScriptTypeName(name));
- }
-
- /**
- * Checks if the given name is a valid Java package name.
- *
- * @param name the java package name.
- * @return a refactoring status containing the error message if the
- * name is not a valid java package name.
- */
- public static RefactoringStatus checkPackageName(String name) {
- return checkName(name, JavaScriptConventions.validatePackageName(name));
- }
-
- /**
- * Checks if the given name is a valid compilation unit name.
- *
- * @param name the compilation unit name.
- * @return a refactoring status containing the error message if the
- * name is not a valid compilation unit name.
- */
- public static RefactoringStatus checkCompilationUnitName(String name) {
- return checkName(name, JavaScriptConventions.validateCompilationUnitName(name));
- }
-
- /**
- * Returns ok status if the new name is ok. This is when no other file with that name exists.
- * @param cu
- * @param newName
- * @return the status
- */
- public static RefactoringStatus checkCompilationUnitNewName(IJavaScriptUnit cu, String newName) {
- String newCUName= JavaModelUtil.getRenamedCUName(cu, newName);
- if (resourceExists(RenameResourceChange.renamedResourcePath(cu.getResource().getFullPath(), newCUName)))
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.Checks_cu_name_used, newName));
- else
- return new RefactoringStatus();
- }
-
- public static boolean startsWithUpperCase(String s) {
- if (s == null)
- return false;
- else if ("".equals(s)) //$NON-NLS-1$
- return false;
- else
- //workaround for JDK bug (see 26529)
- return s.charAt(0) == Character.toUpperCase(s.charAt(0));
- }
-
- public static boolean startsWithLowerCase(String s){
- if (s == null)
- return false;
- else if ("".equals(s)) //$NON-NLS-1$
- return false;
- else
- //workaround for JDK bug (see 26529)
- return s.charAt(0) == Character.toLowerCase(s.charAt(0));
- }
-
- public static boolean resourceExists(IPath resourcePath){
- return ResourcesPlugin.getWorkspace().getRoot().findMember(resourcePath) != null;
- }
-
- public static boolean isTopLevel(IType type){
- return type.getDeclaringType() == null;
- }
-
- public static boolean isAnonymous(IType type) throws JavaScriptModelException {
- return type.isAnonymous();
- }
-
- public static boolean isTopLevelType(IMember member){
- return member.getElementType() == IJavaScriptElement.TYPE && isTopLevel((IType) member);
- }
-
- public static boolean isInsideLocalType(IType type) throws JavaScriptModelException {
- while (type != null) {
- if (type.isLocal())
- return true;
- type= type.getDeclaringType();
- }
- return false;
- }
-
- public static boolean isAlreadyNamed(IJavaScriptElement element, String name){
- return name.equals(element.getElementName());
- }
-
-// //-------------- main and native method checks ------------------
-// public static RefactoringStatus checkForMainAndNativeMethods(IJavaScriptUnit cu) throws JavaScriptModelException {
-// return checkForMainAndNativeMethods(cu.getTypes());
-// }
-//
-// public static RefactoringStatus checkForMainAndNativeMethods(IType[] types) throws JavaScriptModelException {
-// RefactoringStatus result= new RefactoringStatus();
-// for (int i= 0; i < types.length; i++)
-// result.merge(checkForMainAndNativeMethods(types[i]));
-// return result;
-// }
-//
-// public static RefactoringStatus checkForMainAndNativeMethods(IType type) throws JavaScriptModelException {
-// RefactoringStatus result= new RefactoringStatus();
-// result.merge(checkForMainAndNativeMethods(type.getMethods()));
-// result.merge(checkForMainAndNativeMethods(type.getTypes()));
-// return result;
-// }
-//
-// private static RefactoringStatus checkForMainAndNativeMethods(IFunction[] methods) throws JavaScriptModelException {
-// RefactoringStatus result= new RefactoringStatus();
-// for (int i= 0; i < methods.length; i++) {
-// if (JdtFlags.isNative(methods[i])){
-// String msg= Messages.format(RefactoringCoreMessages.Checks_method_native,
-// new String[]{JavaModelUtil.getFullyQualifiedName(methods[i].getDeclaringType()), methods[i].getElementName(), "UnsatisfiedLinkError"});//$NON-NLS-1$
-// result.addEntry(RefactoringStatus.ERROR, msg, JavaStatusContext.create(methods[i]), Corext.getPluginId(), RefactoringStatusCodes.NATIVE_METHOD);
-// }
-// if (methods[i].isMainMethod()) {
-// String msg= Messages.format(RefactoringCoreMessages.Checks_has_main,
-// JavaModelUtil.getFullyQualifiedName(methods[i].getDeclaringType()));
-// result.addEntry(RefactoringStatus.WARNING, msg, JavaStatusContext.create(methods[i]), Corext.getPluginId(), RefactoringStatusCodes.MAIN_METHOD);
-// }
-// }
-// return result;
-// }
-
- //---- New method name checking -------------------------------------------------------------
-
- /**
- * Checks if the new method is already used in the given type.
- * @param type
- * @param methodName
- * @param parameters
- * @return the status
- */
- public static RefactoringStatus checkMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
- RefactoringStatus result= new RefactoringStatus();
- if (methodName.equals(type.getName()))
- result.addWarning(RefactoringCoreMessages.Checks_methodName_constructor);
- IFunctionBinding method= org.eclipse.wst.jsdt.internal.corext.dom.Bindings.findMethodInType(type, methodName, parameters);
- if (method != null)
- result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists,
- new Object[] {methodName, type.getName()}),
- JavaStatusContext.create(method));
- return result;
- }
-
- /**
- * Checks if the new method somehow conflicts with an already existing method in
- * the hierarchy. The following checks are done:
- * <ul>
- * <li> if the new method overrides a method defined in the given type or in one of its
- * super classes. </li>
- * </ul>
- * @param type
- * @param methodName
- * @param returnType
- * @param parameters
- * @return the status
- */
- public static RefactoringStatus checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters) {
- RefactoringStatus result= new RefactoringStatus();
- IFunctionBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
- if (method != null) {
- boolean returnTypeClash= false;
- ITypeBinding methodReturnType= method.getReturnType();
- if (returnType != null && methodReturnType != null) {
- String returnTypeKey= returnType.getKey();
- String methodReturnTypeKey= methodReturnType.getKey();
- if (returnTypeKey == null && methodReturnTypeKey == null) {
- returnTypeClash= returnType != methodReturnType;
- } else if (returnTypeKey != null && methodReturnTypeKey != null) {
- returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
- }
- }
- ITypeBinding dc= method.getDeclaringClass();
- if (returnTypeClash) {
- result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
- new Object[] {methodName, dc.getName()}),
- JavaStatusContext.create(method));
- } else {
- result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
- new Object[] {methodName, dc.getName()}),
- JavaStatusContext.create(method));
- }
- }
- return result;
- }
-
- //---- Selection checks --------------------------------------------------------------------
-
- public static boolean isExtractableExpression(ASTNode[] selectedNodes, ASTNode coveringNode) {
- ASTNode node= coveringNode;
- if (selectedNodes != null && selectedNodes.length == 1)
- node= selectedNodes[0];
- return isExtractableExpression(node);
- }
-
- public static boolean isExtractableExpression(ASTNode node) {
- if (!(node instanceof Expression))
- return false;
- if (node instanceof Name) {
- IBinding binding= ((Name) node).resolveBinding();
- return !(binding instanceof ITypeBinding);
- }
- return true;
- }
-
- public static boolean isInsideJavadoc(ASTNode node) {
- do {
- if (node.getNodeType() == ASTNode.JSDOC)
- return true;
- node= node.getParent();
- } while (node != null);
- return false;
- }
-
- /**
- * Returns a fatal error in case the name is empty. In all other cases, an
- * error based on the given status is returned.
- *
- * @param name a name
- * @param status a status
- * @return RefactoringStatus based on the given status or the name, if
- * empty.
- */
- public static RefactoringStatus checkName(String name, IStatus status) {
- RefactoringStatus result= new RefactoringStatus();
- if ("".equals(name)) //$NON-NLS-1$
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.Checks_Choose_name);
-
- if (status.isOK())
- return result;
-
- switch (status.getSeverity()){
- case IStatus.ERROR:
- return RefactoringStatus.createFatalErrorStatus(status.getMessage());
- case IStatus.WARNING:
- return RefactoringStatus.createWarningStatus(status.getMessage());
- case IStatus.INFO:
- return RefactoringStatus.createInfoStatus(status.getMessage());
- default: //no nothing
- return new RefactoringStatus();
- }
- }
-
- /**
- * Finds a method in a type
- * This searches for a method with the same name and signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type name is done
- * @param name
- * @param parameterCount
- * @param isConstructor
- * @param type
- * @return The first found method or null, if nothing found
- * @throws JavaScriptModelException
- */
- public static IFunction findMethod(String name, int parameterCount, boolean isConstructor, IType type) throws JavaScriptModelException {
- return findMethod(name, parameterCount, isConstructor, type.getFunctions());
- }
-
- /**
- * Finds a method in a type.
- * Searches for a method with the same name and the same parameter count.
- * Parameter types are <b>not</b> compared.
- * @param method
- * @param type
- * @return The first found method or null, if nothing found
- * @throws JavaScriptModelException
- */
- public static IFunction findMethod(IFunction method, IType type) throws JavaScriptModelException {
- return findMethod(method.getElementName(), method.getParameterTypes().length, method.isConstructor(), type.getFunctions());
- }
-
- /**
- * Finds a method in an array of methods.
- * Searches for a method with the same name and the same parameter count.
- * Parameter types are <b>not</b> compared.
- * @param method
- * @param methods
- * @return The first found method or null, if nothing found
- * @throws JavaScriptModelException
- */
- public static IFunction findMethod(IFunction method, IFunction[] methods) throws JavaScriptModelException {
- return findMethod(method.getElementName(), method.getParameterTypes().length, method.isConstructor(), methods);
- }
-
- public static IFunction findMethod(String name, int parameters, boolean isConstructor, IFunction[] methods) throws JavaScriptModelException {
- for (int i= methods.length-1; i >= 0; i--) {
- IFunction curr= methods[i];
- if (name.equals(curr.getElementName())) {
- if (isConstructor == curr.isConstructor()) {
- if (parameters == curr.getParameterTypes().length) {
- return curr;
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Finds a method in a type.
- * This searches for a method with the same name and signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type name is done
- * @param method
- * @param type
- * @return The first found method or null, if nothing found
- * @throws JavaScriptModelException
- */
- public static IFunction findSimilarMethod(IFunction method, IType type) throws JavaScriptModelException {
- return findSimilarMethod(method, type.getFunctions());
- }
-
- /**
- * Finds a method in an array of methods.
- * This searches for a method with the same name and signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type name is done
- * @param method
- * @param methods
- * @return The first found method or null, if nothing found
- * @throws JavaScriptModelException
- */
- public static IFunction findSimilarMethod(IFunction method, IFunction[] methods) throws JavaScriptModelException {
- boolean isConstructor= method.isConstructor();
- for (int i= 0; i < methods.length; i++) {
- IFunction otherMethod= methods[i];
- if (otherMethod.isConstructor() == isConstructor && method.isSimilar(otherMethod))
- return otherMethod;
- }
- return null;
- }
-
- /*
- * Compare two parameter signatures
- */
- public static boolean compareParamTypes(String[] paramTypes1, String[] paramTypes2) {
- if (paramTypes1.length == paramTypes2.length) {
- int i= 0;
- while (i < paramTypes1.length) {
- String t1= Signature.getSimpleName(Signature.toString(paramTypes1[i]));
- String t2= Signature.getSimpleName(Signature.toString(paramTypes2[i]));
- if (!t1.equals(t2)) {
- return false;
- }
- i++;
- }
- return true;
- }
- return false;
- }
-
- //---------------------
-
- public static RefactoringStatus checkIfCuBroken(IMember member) throws JavaScriptModelException{
- IJavaScriptUnit cu= (IJavaScriptUnit)JavaScriptCore.create(member.getJavaScriptUnit().getResource());
- if (cu == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.Checks_cu_not_created);
- else if (! cu.isStructureKnown())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.Checks_cu_not_parsed);
- return new RefactoringStatus();
- }
-
- /**
- * From SearchResultGroup[] passed as the parameter
- * this method removes all those that correspond to a non-parsable IJavaScriptUnit
- * and returns it as a result.
- * @param grouped the array of search result groups from which non parsable compilation
- * units are to be removed.
- * @param status a refactoring status to collect errors and problems
- * @return the array of search result groups
- * @throws JavaScriptModelException
- */
- public static SearchResultGroup[] excludeCompilationUnits(SearchResultGroup[] grouped, RefactoringStatus status) throws JavaScriptModelException{
- List result= new ArrayList();
- boolean wasEmpty= grouped.length == 0;
- for (int i= 0; i < grouped.length; i++){
- IResource resource= grouped[i].getResource();
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (! (element instanceof IJavaScriptUnit))
- continue;
- //XXX this is a workaround for a jcore feature that shows errors in cus only when you get the original element
- IJavaScriptUnit cu= (IJavaScriptUnit)JavaScriptCore.create(resource);
- if (! cu.isStructureKnown()){
- String path= Checks.getFullPath(cu);
- status.addError(Messages.format(RefactoringCoreMessages.Checks_cannot_be_parsed, path));
- continue; //removed, go to the next one
- }
- result.add(grouped[i]);
- }
-
- if ((!wasEmpty) && result.isEmpty())
- status.addFatalError(RefactoringCoreMessages.Checks_all_excluded);
-
- return (SearchResultGroup[])result.toArray(new SearchResultGroup[result.size()]);
- }
-
- private static final String getFullPath(IJavaScriptUnit cu) {
- Assert.isTrue(cu.exists());
- return cu.getResource().getFullPath().toString();
- }
-
-
- public static RefactoringStatus checkCompileErrorsInAffectedFiles(SearchResultGroup[] grouped) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < grouped.length; i++)
- checkCompileErrorsInAffectedFile(result, grouped[i].getResource());
- return result;
- }
-
- public static void checkCompileErrorsInAffectedFile(RefactoringStatus result, IResource resource) throws JavaScriptModelException {
- if (hasCompileErrors(resource))
- result.addWarning(Messages.format(RefactoringCoreMessages.Checks_cu_has_compile_errors, resource.getFullPath().makeRelative()));
- }
-
- public static RefactoringStatus checkCompileErrorsInAffectedFiles(SearchResultGroup[] references, IResource declaring) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < references.length; i++){
- IResource resource= references[i].getResource();
- if (resource.equals(declaring))
- declaring= null;
- checkCompileErrorsInAffectedFile(result, resource);
- }
- if (declaring != null)
- checkCompileErrorsInAffectedFile(result, declaring);
- return result;
- }
-
- private static boolean hasCompileErrors(IResource resource) throws JavaScriptModelException {
- try {
- IMarker[] problemMarkers= resource.findMarkers(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
- for (int i= 0; i < problemMarkers.length; i++) {
- if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
- return true;
- }
- return false;
- } catch (JavaScriptModelException e){
- throw e;
- } catch (CoreException e){
- throw new JavaScriptModelException(e);
- }
- }
-
- //------
- public static boolean isReadOnly(Object element) throws JavaScriptModelException{
- if (element instanceof IResource)
- return isReadOnly((IResource)element);
-
- if (element instanceof IJavaScriptElement) {
- if ((element instanceof IPackageFragmentRoot) && isClasspathDelete((IPackageFragmentRoot)element))
- return false;
- return isReadOnly(((IJavaScriptElement)element).getResource());
- }
-
- Assert.isTrue(false, "not expected to get here"); //$NON-NLS-1$
- return false;
- }
-
- public static boolean isReadOnly(IResource res) throws JavaScriptModelException {
- ResourceAttributes attributes= res.getResourceAttributes();
- if (attributes != null && attributes.isReadOnly())
- return true;
-
- if (! (res instanceof IContainer))
- return false;
-
- IContainer container= (IContainer)res;
- try {
- IResource[] children= container.members();
- for (int i= 0; i < children.length; i++) {
- if (isReadOnly(children[i]))
- return true;
- }
- return false;
- } catch (JavaScriptModelException e){
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- public static boolean isClasspathDelete(IPackageFragmentRoot pkgRoot) {
- IResource res= pkgRoot.getResource();
- if (res == null)
- return true;
- IProject definingProject= res.getProject();
- if (res.getParent() != null && pkgRoot.isArchive() && ! res.getParent().equals(definingProject))
- return true;
-
- IProject occurringProject= pkgRoot.getJavaScriptProject().getProject();
- return !definingProject.equals(occurringProject);
- }
-
- //-------- validateEdit checks ----
-
- public static RefactoringStatus validateModifiesFiles(IFile[] filesToModify, Object context) {
- RefactoringStatus result= new RefactoringStatus();
- IStatus status= Resources.checkInSync(filesToModify);
- if (!status.isOK())
- result.merge(RefactoringStatus.create(status));
- status= Resources.makeCommittable(filesToModify, context);
- if (!status.isOK()) {
- result.merge(RefactoringStatus.create(status));
- if (!result.hasFatalError()) {
- result.addFatalError(RefactoringCoreMessages.Checks_validateEdit);
- }
- }
- return result;
- }
-
- public static RefactoringStatus validateEdit(IJavaScriptUnit unit, Object context) {
- IResource resource= unit.getPrimary().getResource();
- RefactoringStatus result= new RefactoringStatus();
- if (resource == null)
- return result;
- IStatus status= Resources.checkInSync(resource);
- if (!status.isOK())
- result.merge(RefactoringStatus.create(status));
- status= Resources.makeCommittable(resource, context);
- if (!status.isOK()) {
- result.merge(RefactoringStatus.create(status));
- if (!result.hasFatalError()) {
- result.addFatalError(RefactoringCoreMessages.Checks_validateEdit);
- }
- }
- return result;
- }
-
- /**
- * Checks whether it is possible to modify the given <code>IJavaScriptElement</code>.
- * The <code>IJavaScriptElement</code> must exist and be non read-only to be modifiable.
- * Moreover, if it is a <code>IMember</code> it must not be binary.
- * The returned <code>RefactoringStatus</code> has <code>ERROR</code> severity if
- * it is not possible to modify the element.
- * @param javaElement
- * @return the status
- * @throws JavaScriptModelException
- *
- * @see IJavaScriptElement#exists
- * @see IJavaScriptElement#isReadOnly
- * @see IMember#isBinary
- * @see RefactoringStatus
- */
- public static RefactoringStatus checkAvailability(IJavaScriptElement javaElement) throws JavaScriptModelException{
- RefactoringStatus result= new RefactoringStatus();
- if (! javaElement.exists())
- result.addFatalError(Messages.format(RefactoringCoreMessages.Refactoring_not_in_model, javaElement.getElementName()));
- if (javaElement.isReadOnly())
- result.addFatalError(Messages.format(RefactoringCoreMessages.Refactoring_read_only, javaElement.getElementName()));
- if (javaElement.exists() && !javaElement.isStructureKnown())
- result.addFatalError(Messages.format(RefactoringCoreMessages.Refactoring_unknown_structure, javaElement.getElementName()));
- if (javaElement instanceof IMember && ((IMember)javaElement).isBinary())
- result.addFatalError(Messages.format(RefactoringCoreMessages.Refactoring_binary, javaElement.getElementName()));
- return result;
- }
-
- public static boolean isAvailable(IJavaScriptElement javaElement) throws JavaScriptModelException {
- if (javaElement == null)
- return false;
- if (! javaElement.exists())
- return false;
- if (javaElement.isReadOnly())
- return false;
- // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=48422
- // the Java project is now cheating regarding its children so we shouldn't
- // call isStructureKnown if the project isn't open.
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
- if (!(javaElement instanceof IJavaScriptProject) && !(javaElement instanceof ILocalVariable) && !javaElement.isStructureKnown())
- return false;
- if (javaElement instanceof IMember && ((IMember)javaElement).isBinary())
- return false;
- return true;
- }
-
- public static IType findTypeInPackage(IPackageFragment pack, String name) throws JavaScriptModelException {
- Assert.isTrue(pack.exists());
- Assert.isTrue(!pack.isReadOnly());
-
- /* IJavaScriptUnit.getType expects simple name*/
- if (name.indexOf(".") != -1) //$NON-NLS-1$
- name= name.substring(0, name.indexOf(".")); //$NON-NLS-1$
- IJavaScriptUnit[] cus= pack.getJavaScriptUnits();
- for (int i= 0; i < cus.length; i++){
- if (cus[i].getType(name).exists())
- return cus[i].getType(name);
- }
- return null;
- }
-
- public static RefactoringStatus checkTempName(String newName) {
- RefactoringStatus result= Checks.checkIdentifier(newName);
- if (result.hasFatalError())
- return result;
- if (! Checks.startsWithLowerCase(newName))
- result.addWarning(RefactoringCoreMessages.ExtractTempRefactoring_convention);
- return result;
- }
-
- public static RefactoringStatus checkEnumConstantName(String newName) {
- RefactoringStatus result= Checks.checkFieldName(newName);
- if (result.hasFatalError())
- return result;
- for (int i= 0; i < newName.length(); i++) {
- char c= newName.charAt(i);
- if (Character.isLetter(c) && !Character.isUpperCase(c)) {
- result.addWarning(RefactoringCoreMessages.RenameEnumConstRefactoring_convention);
- break;
- }
- }
- return result;
- }
-
- public static RefactoringStatus checkConstantName(String newName) {
- RefactoringStatus result= Checks.checkFieldName(newName);
- if (result.hasFatalError())
- return result;
- for (int i= 0; i < newName.length(); i++) {
- char c= newName.charAt(i);
- if (Character.isLetter(c) && !Character.isUpperCase(c)) {
- result.addWarning(RefactoringCoreMessages.ExtractConstantRefactoring_convention);
- break;
- }
- }
- return result;
- }
-
- public static boolean isException(IType iType, IProgressMonitor pm) throws JavaScriptModelException {
- try{
- if (! iType.isClass())
- return false;
- IType[] superTypes= iType.newSupertypeHierarchy(pm).getAllSuperclasses(iType);
- for (int i= 0; i < superTypes.length; i++) {
- if ("java.lang.Throwable".equals(superTypes[i].getFullyQualifiedName())) //$NON-NLS-1$
- return true;
- }
- return false;
- } finally{
- pm.done();
- }
- }
-
- /**
- * @param e
- * @return int
- * Checks.IS_RVALUE if e is an rvalue
- * Checks.NOT_RVALUE_VOID if e is not an rvalue because its type is void
- * Checks.NOT_RVALUE_MISC if e is not an rvalue for some other reason
- */
- public static int checkExpressionIsRValue(Expression e) {
- if(e instanceof Name) {
- if(!(((Name) e).resolveBinding() instanceof IVariableBinding)) {
- return NOT_RVALUE_MISC;
- }
- }
-
- ITypeBinding tb= e.resolveTypeBinding();
- if (tb == null)
- return NOT_RVALUE_MISC;
- else if (tb.getName().equals("void")) //$NON-NLS-1$
- return NOT_RVALUE_VOID;
-
- return IS_RVALUE;
- }
-
- public static boolean isDeclaredIn(VariableDeclaration tempDeclaration, Class astNodeClass) {
- ASTNode initializer= ASTNodes.getParent(tempDeclaration, astNodeClass);
- if (initializer == null)
- return false;
- ASTNode anonymous= ASTNodes.getParent(tempDeclaration, AnonymousClassDeclaration.class);
- if (anonymous == null)
- return true;
- // stupid code. Is to find out if the variable declaration isn't a field.
- if (ASTNodes.isParent(anonymous, initializer))
- return false;
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CollectingSearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CollectingSearchRequestor.java
deleted file mode 100644
index e58b4704..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CollectingSearchRequestor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-
-/**
- * Collects the results returned by a <code>SearchEngine</code>.
- */
-public class CollectingSearchRequestor extends SearchRequestor {
- private ArrayList fFound;
-
- public CollectingSearchRequestor() {
- fFound= new ArrayList();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.wst.jsdt.core.search.SearchMatch)
- */
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- fFound.add(match);
- }
-
- /**
- * @return a List of {@link SearchMatch}es (not sorted)
- */
- public List/*<SearchMatch>*/ getResults() {
- return fFound;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CuCollectingSearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CuCollectingSearchRequestor.java
deleted file mode 100644
index 1f817175..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/CuCollectingSearchRequestor.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-/**
- * Collects the results returned by a <code>SearchEngine</code>.
- * Only collects matches in CUs ands offers a scanner to trim match ranges.
- */
-public abstract class CuCollectingSearchRequestor extends CollectingSearchRequestor {
-
- private IJavaScriptUnit fCuCache;
- private IScanner fScannerCache;
-
- protected IScanner getScanner(IJavaScriptUnit unit) {
- if (unit.equals(fCuCache))
- return fScannerCache;
-
- fCuCache= unit;
- IJavaScriptProject project= unit.getJavaScriptProject();
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- fScannerCache= ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
- return fScannerCache;
- }
-
- /**
- * This is an internal method. Do not call from subclasses!
- * Use {@link #collectMatch(SearchMatch)} instead.
- * @param match
- * @throws CoreException
- * @deprecated
- */
- public final void acceptSearchMatch(SearchMatch match) throws CoreException {
- IJavaScriptUnit unit= SearchUtils.getCompilationUnit(match);
- if (unit == null)
- return;
- acceptSearchMatch(unit, match);
- }
-
- public void collectMatch(SearchMatch match) throws CoreException {
- super.acceptSearchMatch(match);
- }
-
- protected abstract void acceptSearchMatch(IJavaScriptUnit unit, SearchMatch match) throws CoreException;
-
- public void endReporting() {
- fCuCache= null;
- fScannerCache= null;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ExceptionInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ExceptionInfo.java
deleted file mode 100644
index ec35c141..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ExceptionInfo.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public class ExceptionInfo {
- private final IType fType;
- private final ITypeBinding fTypeBinding;
- private int fKind;
-
- public static final int OLD= 0;
- public static final int ADDED= 1;
- public static final int DELETED= 2;
-
- public ExceptionInfo(IType type, int kind, ITypeBinding binding) {
- Assert.isNotNull(type);
- fType= type;
- fKind= kind;
- fTypeBinding= binding;
- }
-
- public static ExceptionInfo createInfoForOldException(IType type, ITypeBinding binding){
- return new ExceptionInfo(type, OLD, binding);
- }
- public static ExceptionInfo createInfoForAddedException(IType type){
- return new ExceptionInfo(type, ADDED, null);
- }
-
- public void markAsDeleted(){
- Assert.isTrue(! isAdded());//added exception infos should be simply removed from the list
- fKind= DELETED;
- }
-
- public void markAsOld(){
- Assert.isTrue(isDeleted());
- fKind= OLD;
- }
-
- public boolean isAdded(){
- return fKind == ADDED;
- }
-
- public boolean isDeleted(){
- return fKind == DELETED;
- }
-
- public boolean isOld(){
- return fKind == OLD;
- }
-
- public IType getType() {
- return fType;
- }
-
- public int getKind() {
- return fKind;
- }
-
- /**
- * @return ITypeBinding the typeBinding (for OLD and DELETED exceptions) or <code>null</code>
- */
- public ITypeBinding getTypeBinding() {
- return fTypeBinding;
- }
-
- public String toString() {
- StringBuffer result= new StringBuffer();
- switch (fKind) {
- case OLD : result.append("OLD: "); break; //$NON-NLS-1$
- case ADDED : result.append("ADDED: "); break; //$NON-NLS-1$
- case DELETED : result.append("DELETED: "); break; //$NON-NLS-1$
- }
- if (fType == null)
- result.append("null"); //$NON-NLS-1$
- else
- result.append(fType.toString());
- return result.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java
deleted file mode 100644
index 0d82efac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-
-/**
- * Interface for search requestors used in conjunction with {@link org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2}.
- *
- *
- */
-public interface IRefactoringSearchRequestor {
-
- /**
- * Can the search match be accepted?
- *
- * @param match the search match to test
- * @return The accepted match, or <code>null</code> if not accepted
- */
- public SearchMatch acceptSearchMatch(SearchMatch match);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringContribution.java
deleted file mode 100644
index a3e9d6f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringContribution.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringContribution;
-
-/**
- * Partial implementation of a JDT refactoring contribution.
- *
- *
- */
-public abstract class JDTRefactoringContribution extends JavaScriptRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringDescriptor createDescriptor(final String id, final String project, final String description, final String comment, final Map arguments, final int flags) {
- return new JDTRefactoringDescriptor(id, project, description, comment, arguments, flags);
- }
-
- /**
- * Creates the a new refactoring instance.
- *
- * @param descriptor
- * the refactoring descriptor
- * @return the refactoring, or <code>null</code>
- * @throws CoreException
- * if an error occurs while creating the refactoring
- */
- public abstract Refactoring createRefactoring(RefactoringDescriptor descriptor) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptor.java
deleted file mode 100644
index 8d25dfd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptor.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Descriptor object of a JDT refactoring.
- *
- *
- */
-public class JDTRefactoringDescriptor extends JavaScriptRefactoringDescriptor {
-
- /**
- * Predefined argument called <code>element&lt;Number&gt;</code>.
- * <p>
- * This argument should be used to describe the elements being refactored.
- * The value of this argument does not necessarily have to uniquely identify
- * the elements. However, it must be possible to uniquely identify the
- * elements using the value of this argument in conjunction with the values
- * of the other user-defined attributes.
- * </p>
- * <p>
- * The element arguments are simply distinguished by appending a number to
- * the argument name, e.g. element1. The indices of this argument are non
- * zero-based.
- * </p>
- */
- public static final String ATTRIBUTE_ELEMENT= "element"; //$NON-NLS-1$
-
- /**
- * Predefined argument called <code>input</code>.
- * <p>
- * This argument should be used to describe the element being refactored.
- * The value of this argument does not necessarily have to uniquely identify
- * the input element. However, it must be possible to uniquely identify the
- * input element using the value of this argument in conjunction with the
- * values of the other user-defined attributes.
- * </p>
- */
- public static final String ATTRIBUTE_INPUT= "input"; //$NON-NLS-1$
-
- /**
- * Predefined argument called <code>name</code>.
- * <p>
- * This argument should be used to name the element being refactored. The
- * value of this argument may be shown in the user interface.
- * </p>
- */
- public static final String ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
-
- /**
- * Predefined argument called <code>references</code>.
- * <p>
- * This argument should be used to describe whether references to the
- * elements being refactored should be updated as well.
- * </p>
- */
- public static final String ATTRIBUTE_REFERENCES= "references"; //$NON-NLS-1$
-
- /**
- * Predefined argument called <code>selection</code>.
- * <p>
- * This argument should be used to describe user input selections within a
- * text file. The value of this argument has the format "offset length".
- * </p>
- */
- public static final String ATTRIBUTE_SELECTION= "selection"; //$NON-NLS-1$
-
- /**
- * Constant describing the deprecation resolving flag.
- * <p>
- * Clients should set this flag to indicate that the refactoring can used to
- * resolve deprecation problems of members. Refactorings which can run on
- * binary targets, but require a source attachment to work correctly, should
- * set the <code>JAR_SOURCE_ATTACHMENT</code> flag as well.
- * </p>
- */
- public static final int DEPRECATION_RESOLVING= 1 << 17;
-
- /**
- * Converts the specified element to an input handle.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param element
- * the element
- * @return a corresponding input handle
- */
- public static String elementToHandle(final String project, final IJavaScriptElement element) {
- final String handle= element.getHandleIdentifier();
- if (project != null && !(element instanceof IJavaScriptProject)) {
- final String id= element.getJavaScriptProject().getHandleIdentifier();
- return handle.substring(id.length());
- }
- return handle;
- }
-
- /**
- * Converts an input handle back to the corresponding java element.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param handle
- * the input handle
- * @return the corresponding java element, or <code>null</code> if no such
- * element exists
- */
- public static IJavaScriptElement handleToElement(final String project, final String handle) {
- return handleToElement(project, handle, true);
- }
-
- /**
- * Converts an input handle back to the corresponding java element.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param handle
- * the input handle
- * @param check
- * <code>true</code> to check for existence of the element,
- * <code>false</code> otherwise
- * @return the corresponding java element, or <code>null</code> if no such
- * element exists
- */
- public static IJavaScriptElement handleToElement(final String project, final String handle, final boolean check) {
- return handleToElement(null, project, handle, check);
- }
-
- /**
- * Converts an input handle back to the corresponding java element.
- *
- * @param owner
- * the working copy owner
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param handle
- * the input handle
- * @param check
- * <code>true</code> to check for existence of the element,
- * <code>false</code> otherwise
- * @return the corresponding java element, or <code>null</code> if no such
- * element exists
- */
- public static IJavaScriptElement handleToElement(final WorkingCopyOwner owner, final String project, final String handle, final boolean check) {
- IJavaScriptElement element= null;
- if (owner != null)
- element= JavaScriptCore.create(handle, owner);
- else
- element= JavaScriptCore.create(handle);
- if (element == null && project != null) {
- final IJavaScriptProject javaProject= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProject(project);
- final String identifier= javaProject.getHandleIdentifier();
- if (owner != null)
- element= JavaScriptCore.create(identifier + handle, owner);
- else
- element= JavaScriptCore.create(identifier + handle);
- }
- if (check && element instanceof IFunction) {
- final IFunction method= (IFunction) element;
- IFunction[] methods=null;
- if (method.getDeclaringType()!=null)
- methods=method.getDeclaringType().findMethods(method);
- else
- methods=method.getJavaScriptUnit().findFunctions(method);
- if (methods != null && methods.length > 0)
- element= methods[0];
- }
- if (element != null && (!check || element.exists()))
- return element;
- return null;
- }
-
- /**
- * Converts an input handle with the given prefix back to the corresponding
- * resource.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param handle
- * the input handle
- *
- * @return the corresponding resource, or <code>null</code> if no such
- * resource exists
- */
- public static IResource handleToResource(final String project, final String handle) {
- final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- if ("".equals(handle)) //$NON-NLS-1$
- return null;
- final IPath path= Path.fromPortableString(handle);
- if (path == null)
- return null;
- if (project != null && !"".equals(project)) //$NON-NLS-1$
- return root.getProject(project).findMember(path);
- return root.findMember(path);
- }
-
- /**
- * Converts the specified resource to an input handle.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param resource
- * the resource
- *
- * @return the input handle
- */
- public static String resourceToHandle(final String project, final IResource resource) {
- if (project != null && !"".equals(project)) //$NON-NLS-1$
- return resource.getProjectRelativePath().toPortableString();
- return resource.getFullPath().toPortableString();
- }
-
- /**
- * Creates a new JDT refactoring descriptor.
- *
- * @param id
- * the unique id of the refactoring
- * @param project
- * the project name, or <code>null</code>
- * @param description
- * the description
- * @param comment
- * the comment, or <code>null</code>
- * @param arguments
- * the argument map
- * @param flags
- * the flags
- */
- public JDTRefactoringDescriptor(final String id, final String project, final String description, final String comment, final Map arguments, final int flags) {
- super(id, arguments);
- setProject(project);
- setDescription(description);
- setComment(comment);
- setFlags(flags);
- }
-
- /**
- * Creates refactoring arguments for this refactoring descriptor.
- *
- * @return the refactoring arguments
- */
- public JavaRefactoringArguments createArguments() {
- final JavaRefactoringArguments arguments= new JavaRefactoringArguments(getProject());
- for (final Iterator iterator= getArguments().entrySet().iterator(); iterator.hasNext();) {
- final Map.Entry entry= (Entry) iterator.next();
- final String name= (String) entry.getKey();
- final String value= (String) entry.getValue();
- if (name != null && !"".equals(name) && value != null) //$NON-NLS-1$
- arguments.setAttribute(name, value);
- }
- return arguments;
- }
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringStatus status) throws CoreException {
- Refactoring refactoring= null;
- final RefactoringContribution contribution= RefactoringCore.getRefactoringContribution(getID());
- if (contribution instanceof JDTRefactoringContribution) {
- final JDTRefactoringContribution extended= (JDTRefactoringContribution) contribution;
- refactoring= extended.createRefactoring(this);
- }
- if (refactoring != null) {
- if (refactoring instanceof IScriptableRefactoring) {
- final JavaRefactoringArguments arguments= createArguments();
- if (arguments != null)
- status.merge(((IScriptableRefactoring) refactoring).initialize(arguments));
- else
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_initialization_error, getID())));
- }
- return refactoring;
- }
-
- /**
- * Converts the specified element to an input handle.
- *
- * @param element
- * the element
- * @return a corresponding input handle
- */
- public String elementToHandle(final IJavaScriptElement element) {
- Assert.isNotNull(element);
- return elementToHandle(getProject(), element);
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getArguments() {
- return super.getArguments();
- }
-
- /**
- * Converts the specified resource to an input handle.
- *
- * @param resource
- * the resource
- * @return a corresponding input handle
- */
- public String resourceToHandle(final IResource resource) {
- Assert.isNotNull(resource);
- return resourceToHandle(getProject(), resource);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptorComment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptorComment.java
deleted file mode 100644
index 8b3d2d99..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JDTRefactoringDescriptorComment.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ISimilarDeclarationUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Helper class to generate a refactoring descriptor comment.
- *
- *
- */
-public final class JDTRefactoringDescriptorComment {
-
- /** The element delimiter */
- private static final String ELEMENT_DELIMITER= RefactoringCoreMessages.JavaRefactoringDescriptorComment_element_delimiter;
-
- /** The line delimiter */
- private static final String LINE_DELIMITER= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- /**
- * Creates a composite setting.
- *
- * @param caption
- * the caption
- * @param settings
- * the settings
- * @return the composite setting
- */
- public static String createCompositeSetting(final String caption, final String[] settings) {
- Assert.isNotNull(caption);
- Assert.isNotNull(settings);
- final StringBuffer buffer= new StringBuffer(128);
- for (int index= 0; index < settings.length; index++) {
- if (settings[index] != null && !"".equals(settings[index])) { //$NON-NLS-1$
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(settings[index]);
- } else {
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_not_available);
- }
- }
- if (buffer.length() > 0)
- buffer.insert(0, caption);
- return buffer.toString();
- }
-
- /** The header of the comment */
- private final String fHeader;
-
- /** The project name, or <code>null</code> */
- private final String fProject;
-
- /** The settings list */
- private final List fSettings= new ArrayList(6);
-
- /**
- * Creates a new JDT refactoring descriptor comment.
- *
- * @param project
- * the project name, or <code>null</code>
- * @param object
- * the refactoring object to generate a comment for
- * @param header
- * the header of the comment (typically the unique description of
- * the refactoring with fully qualified element names)
- */
- public JDTRefactoringDescriptorComment(final String project, final Object object, final String header) {
- Assert.isNotNull(object);
- Assert.isNotNull(header);
- fProject= project;
- fHeader= header;
- initializeInferredSettings(object);
- }
-
- /**
- * Adds the specified setting to this comment.
- *
- * @param index
- * the index
- * @param setting
- * the setting to add
- */
- public void addSetting(final int index, final String setting) {
- Assert.isTrue(index >= 0);
- Assert.isNotNull(setting);
- Assert.isTrue(!"".equals(setting)); //$NON-NLS-1$
- fSettings.add(index, setting);
- }
-
- /**
- * Adds the specified setting to this comment.
- *
- * @param setting
- * the setting to add, or <code>null</code> for no setting
- */
- public void addSetting(final String setting) {
- if (setting != null && !"".equals(setting)) //$NON-NLS-1$
- fSettings.add(setting);
- }
-
- /**
- * Returns this comment in a human-readable string representation.
- *
- * @return this comment in string representation
- */
- public String asString() {
- final StringBuffer buffer= new StringBuffer(256);
- buffer.append(fHeader);
- if (fProject != null && !"".equals(fProject)) { //$NON-NLS-1$
- buffer.append(LINE_DELIMITER);
- buffer.append(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptorComment_original_project, fProject));
- }
- for (final Iterator iterator= fSettings.iterator(); iterator.hasNext();) {
- final String setting= (String) iterator.next();
- buffer.append(LINE_DELIMITER);
- buffer.append(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_inferred_setting_pattern, setting));
- }
- return buffer.toString();
- }
-
- /**
- * Returns the number of settings.
- *
- * @return the number of settings
- */
- public int getCount() {
- return fSettings.size();
- }
-
- /**
- * Initializes the inferred settings.
- *
- * @param object
- * the refactoring object
- */
- private void initializeInferredSettings(final Object object) {
- if (object instanceof INameUpdating) {
- final INameUpdating updating= (INameUpdating) object;
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaScriptElementLabels.getTextLabel(updating.getElements()[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- try {
- final Object element= updating.getNewElement();
- if (element != null)
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_renamed_element_pattern, JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- else {
- final String oldLabel= JavaScriptElementLabels.getTextLabel(updating.getElements()[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- final String newName= updating.getCurrentElementName();
- if (newName.length() < oldLabel.length()) {
- final String newLabel= oldLabel.substring(0, oldLabel.length() - newName.length());
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_renamed_element_pattern, newLabel + updating.getNewElementName()));
- }
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- } else if (object instanceof RefactoringProcessor) {
- final RefactoringProcessor processor= (RefactoringProcessor) object;
- final Object[] elements= processor.getElements();
- if (elements != null) {
- if (elements.length == 1 && elements[0] != null)
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaScriptElementLabels.getTextLabel(elements[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- else if (elements.length > 1) {
- final StringBuffer buffer= new StringBuffer(128);
- buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_original_elements);
- for (int index= 0; index < elements.length; index++) {
- if (elements[index] != null) {
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(JavaScriptElementLabels.getTextLabel(elements[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED));
- } else {
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_not_available);
- }
- }
- fSettings.add(buffer.toString());
- }
- }
- } else if (object instanceof IReorgPolicy) {
- final IReorgPolicy policy= (IReorgPolicy) object;
- Object destination= policy.getJavaElementDestination();
- if (destination != null)
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptorComment_destination_pattern, JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- else {
- destination= policy.getResourceDestination();
- if (destination != null)
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptorComment_destination_pattern, JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- }
- final List list= new ArrayList();
- list.addAll(Arrays.asList(policy.getJavaElements()));
- list.addAll(Arrays.asList(policy.getResources()));
- final Object[] elements= list.toArray();
- if (elements != null) {
- if (elements.length == 1 && elements[0] != null)
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaScriptElementLabels.getTextLabel(elements[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- else if (elements.length > 1) {
- final StringBuffer buffer= new StringBuffer(128);
- buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_original_elements);
- for (int index= 0; index < elements.length; index++) {
- if (elements[index] != null) {
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(JavaScriptElementLabels.getTextLabel(elements[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED));
- } else {
- buffer.append(LINE_DELIMITER);
- buffer.append(ELEMENT_DELIMITER);
- buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_not_available);
- }
- }
- fSettings.add(buffer.toString());
- }
- }
- if (object instanceof IMovePolicy) {
- final IMovePolicy extended= (IMovePolicy) object;
- if (extended.isTextualMove())
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptorComment_textual_move_only);
- }
- }
- if (object instanceof IReferenceUpdating) {
- final IReferenceUpdating updating= (IReferenceUpdating) object;
- if (updating.canEnableUpdateReferences() && updating.getUpdateReferences())
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_update_references);
- }
- if (object instanceof ISimilarDeclarationUpdating) {
- final ISimilarDeclarationUpdating updating= (ISimilarDeclarationUpdating) object;
- if (updating.canEnableSimilarDeclarationUpdating() && updating.getUpdateSimilarDeclarations()) {
- final int strategy= updating.getMatchStrategy();
- if (strategy == RenamingNameSuggestor.STRATEGY_EXACT)
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar);
- else if (strategy == RenamingNameSuggestor.STRATEGY_EMBEDDED)
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar_embedded);
- else if (strategy == RenamingNameSuggestor.STRATEGY_SUFFIX)
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar_suffix);
- }
- }
- if (object instanceof IQualifiedNameUpdating) {
- final IQualifiedNameUpdating updating= (IQualifiedNameUpdating) object;
- if (updating.canEnableQualifiedNameUpdating() && updating.getUpdateQualifiedNames()) {
- final String patterns= updating.getFilePatterns();
- if (patterns != null && !"".equals(patterns)) //$NON-NLS-1$
- fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_qualified_names_pattern, patterns.trim()));
- else
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_qualified_names);
- }
- }
- if (object instanceof ITextUpdating) {
- final ITextUpdating updating= (ITextUpdating) object;
- if (updating.canEnableTextUpdating())
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_textual_occurrences);
- }
- if (object instanceof IDelegateUpdating) {
- final IDelegateUpdating updating= (IDelegateUpdating) object;
- if (updating.canEnableDelegateUpdating() && updating.getDelegateUpdating()) {
- if (updating.getDeprecateDelegates())
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_keep_original_deprecated);
- else
- fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_keep_original);
- }
- }
- }
-
- /**
- * Removes the setting at the specified index.
- *
- * @param index
- * the index
- */
- public void removeSetting(final int index) {
- Assert.isTrue(index >= 0);
- fSettings.remove(index);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java
deleted file mode 100644
index cccc09b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-
-/**
- * Refactoring arguments which provide the ability to set arguments using
- * key-value pairs of strings.
- *
- * @see org.eclipse.ltk.core.refactoring.RefactoringContribution
- * @see org.eclipse.ltk.core.refactoring.RefactoringDescriptor
- *
- *
- */
-public final class JavaRefactoringArguments extends RefactoringArguments {
-
- /** The attribute map (element type: <code>&lt;String, String&gt;</code>) */
- private final Map fAttributes= new HashMap(2);
-
- /** The name of the project, or <code>null</code> for the workspace */
- private String fProject;
-
- /**
- * Creates a new java refactoring arguments.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- */
- public JavaRefactoringArguments(final String project) {
- Assert.isTrue(project == null || !"".equals(project)); //$NON-NLS-1$
- fProject= project;
- }
-
- /**
- * Returns the attribute with the specified name.
- *
- * @param name
- * the name of the attribute
- * @return the attribute value, or <code>null</code>
- */
- public String getAttribute(final String name) {
- return (String) fAttributes.get(name);
- }
-
- /**
- * Returns the name of the project.
- *
- * @return the name of the project, or <code>null</code> for the workspace
- */
- public String getProject() {
- return fProject;
- }
-
- /**
- * Sets the attribute with the specified name to the indicated value.
- *
- * @param name
- * the name of the attribute
- * @param value
- * the value of the attribute
- */
- public void setAttribute(final String name, final String value) {
- Assert.isNotNull(name);
- Assert.isNotNull(value);
- fAttributes.put(name, value);
- }
-
- /**
- * Sets the name of the project.
- *
- * @param project
- * the name of the project, or <code>null</code> for the
- * workspace
- */
- public void setProject(final String project) {
- Assert.isTrue(project == null || !"".equals(project)); //$NON-NLS-1$
- fProject= project;
- }
-
- /**
- * {@inheritDoc}
- */
- public String toString() {
- return getClass().getName() + fAttributes.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ParameterInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ParameterInfo.java
deleted file mode 100644
index 1c1ca18c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ParameterInfo.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-
-
-public class ParameterInfo {
-
- public static final int INDEX_FOR_ADDED= -1;
- public static final String ELLIPSIS= "..."; //$NON-NLS-1$
-
- private IVariableBinding fOldBinding;
- private ITypeBinding fOldTypeBinding;
- private final String fOldName;
- private final String fOldTypeName;
- private final int fOldIndex;
-
- private String fNewTypeName;
- private ITypeBinding fNewTypeBinding;
- private String fDefaultValue;
- private String fNewName;
- private boolean fIsDeleted;
- private boolean fCreateField=true;
- private boolean fInlined;
- private boolean fResolve= true;
-
- public ParameterInfo(String type, String name, int index) {
- this(null, null, type, name, index);
- }
-
- public ParameterInfo(IVariableBinding binding, String type, String name, int index) {
- this(binding, null, type, name, index);
- }
-
- private ParameterInfo(IVariableBinding binding, ITypeBinding typeBinding, String type, String name, int index) {
- fOldBinding= binding;
- fOldTypeBinding= typeBinding;
- fNewTypeBinding= typeBinding;
- fOldTypeName= type;
- fNewTypeName= type;
- fOldName= name;
- fNewName= name;
- fOldIndex= index;
- fDefaultValue= ""; //$NON-NLS-1$
- fIsDeleted= false;
- }
-
-
- /**
- * Creates a new ParameterInfo. Parameter is marked as added and not resolvable
- * @param type the fullyqualified type
- * @param name the name
- * @return the parameter info object
- */
- public static ParameterInfo createInfoForAddedParameter(String type, String name) {
- ParameterInfo info= new ParameterInfo("", "", INDEX_FOR_ADDED); //$NON-NLS-1$ //$NON-NLS-2$
- info.setNewTypeName(type);
- info.setNewName(name);
- info.setResolve(false);
- return info;
- }
-
- private void setResolve(boolean resolve) {
- fResolve= resolve;
- }
-
- public static ParameterInfo createInfoForAddedParameter(String type, String name, String defaultValue) {
- ParameterInfo info= new ParameterInfo("", "", INDEX_FOR_ADDED); //$NON-NLS-1$ //$NON-NLS-2$
- info.setNewTypeName(type);
- info.setNewName(name);
- info.setDefaultValue(defaultValue);
- return info;
- }
-
- public static ParameterInfo createInfoForAddedParameter(ITypeBinding typeBinding, String type, String name, String defaultValue) {
- ParameterInfo info= new ParameterInfo(null, typeBinding, "", "", INDEX_FOR_ADDED); //$NON-NLS-1$ //$NON-NLS-2$
- info.setNewTypeName(type);
- info.setNewName(name);
- info.setDefaultValue(defaultValue);
- return info;
- }
-
- public int getOldIndex() {
- return fOldIndex;
- }
-
- public boolean isDeleted(){
- return fIsDeleted;
- }
-
- public void markAsDeleted(){
- Assert.isTrue(! isAdded());//added param infos should be simply removed from the list
- fIsDeleted= true;
- }
-
- public boolean isAdded(){
- return fOldIndex == INDEX_FOR_ADDED;
- }
-
- public boolean isTypeNameChanged() {
- return !fOldTypeName.equals(fNewTypeName);
- }
-
- public boolean isRenamed() {
- return !fOldName.equals(fNewName);
- }
-
- public boolean isVarargChanged() {
- return isOldVarargs() != isNewVarargs();
- }
-
- public IVariableBinding getOldBinding() {
- return fOldBinding;
- }
-
- public String getOldTypeName() {
- return fOldTypeName;
- }
-
- public String getNewTypeName() {
- return fNewTypeName;
- }
-
- public void setNewTypeName(String type){
- Assert.isNotNull(type);
- fNewTypeName= type;
- }
-
- public ITypeBinding getNewTypeBinding() {
- return fNewTypeBinding;
- }
-
- public void setNewTypeBinding(ITypeBinding typeBinding){
- //TODO: TypeContextChecker should not resolve such a parameter at all.
- // That would also make IProblemVerifier obsolete.
- if (fResolve)
- fNewTypeBinding= typeBinding;
- }
-
- public boolean isOldVarargs() {
- return isVarargs(fOldTypeName);
- }
-
- public boolean isNewVarargs() {
- return isVarargs(fNewTypeName);
- }
-
- public String getOldName() {
- return fOldName;
- }
-
- public String getNewName() {
- return fNewName;
- }
-
- public void setNewName(String newName) {
- Assert.isNotNull(newName);
- fNewName= newName;
- }
-
- public String getDefaultValue(){
- return fDefaultValue;
- }
-
- public void setDefaultValue(String value){
- Assert.isNotNull(value);
- fDefaultValue= value;
- }
-
- public String toString() {
- return fOldTypeName + " " + fOldName + " @" + fOldIndex + " -> " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- + fNewTypeName + " " + fNewName + ": " + fDefaultValue //$NON-NLS-1$//$NON-NLS-2$
- + (fIsDeleted ? " (deleted)" : " (stays)"); //$NON-NLS-1$//$NON-NLS-2$
- }
-
- public static String stripEllipsis(String typeName) {
- if (isVarargs(typeName))
- return typeName.substring(0, typeName.length() - 3);
- else
- return typeName;
- }
-
- public static boolean isVarargs(String typeName) {
- return typeName.endsWith("..."); //$NON-NLS-1$
- }
-
- public ITypeBinding getOldTypeBinding() {
- return fOldTypeBinding;
- }
-
- public boolean isCreateField() {
- return fCreateField;
- }
-
- public void setCreateField(boolean createField) {
- fIsDeleted= createField;
- fCreateField= createField;
- }
-
- public void setOldBinding(IVariableBinding binding) {
- //TODO: remove setter again ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=102287 )
- fOldBinding=binding;
- fOldTypeBinding=binding.getType();
- fNewTypeBinding=binding.getType();
- }
-
- public void setInlined(boolean inlined) {
- fInlined=inlined;
- }
-
- public boolean isInlined() {
- return fInlined;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringAvailabilityTester.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringAvailabilityTester.java
deleted file mode 100644
index eedcbb01..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringAvailabilityTester.java
+++ /dev/null
@@ -1,1124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.infer.IInferenceFile;
-import org.eclipse.wst.jsdt.core.infer.InferrenceManager;
-import org.eclipse.wst.jsdt.core.infer.InferrenceProvider;
-import org.eclipse.wst.jsdt.core.infer.RefactoringSupport;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringActions;
-
-/**
- * Helper class to detect whether a certain refactoring can be enabled on a
- * selection.
- * <p>
- * This class has been introduced to decouple actions from the refactoring code,
- * in order not to eagerly load refactoring classes during action
- * initialization.
- * </p>
- *
- *
- */
-public final class RefactoringAvailabilityTester {
-
- public static IType getDeclaringType(IJavaScriptElement element) {
- if (element == null)
- return null;
- if (!(element instanceof IType))
- element= element.getAncestor(IJavaScriptElement.TYPE);
- return (IType) element;
- }
-
- public static IJavaScriptElement[] getJavaElements(final Object[] elements) {
- List result= new ArrayList();
- for (int index= 0; index < elements.length; index++) {
- if (elements[index] instanceof IJavaScriptElement)
- result.add(elements[index]);
- }
- return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- public static IMember[] getPullUpMembers(final IType type) throws JavaScriptModelException {
- final List list= new ArrayList(3);
- if (type.exists()) {
- IMember[] members= type.getFields();
- for (int index= 0; index < members.length; index++) {
- if (isPullUpAvailable(members[index]))
- list.add(members[index]);
- }
- members= type.getFunctions();
- for (int index= 0; index < members.length; index++) {
- if (isPullUpAvailable(members[index]))
- list.add(members[index]);
- }
- members= type.getTypes();
- for (int index= 0; index < members.length; index++) {
- if (isPullUpAvailable(members[index]))
- list.add(members[index]);
- }
- }
- return (IMember[]) list.toArray(new IMember[list.size()]);
- }
-
- public static IMember[] getPushDownMembers(final IType type) throws JavaScriptModelException {
- final List list= new ArrayList(3);
- if (type.exists()) {
- IMember[] members= type.getFields();
- for (int index= 0; index < members.length; index++) {
- if (isPushDownAvailable(members[index]))
- list.add(members[index]);
- }
- members= type.getFunctions();
- for (int index= 0; index < members.length; index++) {
- if (isPushDownAvailable(members[index]))
- list.add(members[index]);
- }
- }
- return (IMember[]) list.toArray(new IMember[list.size()]);
- }
-
- public static IResource[] getResources(final Object[] elements) {
- List result= new ArrayList();
- for (int index= 0; index < elements.length; index++) {
- if (elements[index] instanceof IResource)
- result.add(elements[index]);
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-
- public static IType getSingleSelectedType(IStructuredSelection selection) throws JavaScriptModelException {
- Object first= selection.getFirstElement();
- if (first instanceof IType)
- return (IType) first;
- if (first instanceof IJavaScriptUnit) {
- final IJavaScriptUnit unit= (IJavaScriptUnit) first;
- if (unit.exists())
- return JavaElementUtil.getMainType(unit);
- }
- return null;
- }
-
- public static IType getTopLevelType(final IMember[] members) {
- if (members != null && members.length == 1 && Checks.isTopLevelType(members[0]))
- return (IType) members[0];
- return null;
- }
-
- public static boolean isChangeSignatureAvailable(final IFunction method) throws JavaScriptModelException {
- return Checks.isAvailable(method);
- }
-
- public static boolean isChangeSignatureAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IFunction) {
- final IFunction method= (IFunction) selection.getFirstElement();
- return isChangeSignatureAvailable(method);
- }
- }
- return false;
- }
-
- public static boolean isChangeSignatureAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length == 1 && (elements[0] instanceof IFunction))
- return isChangeSignatureAvailable((IFunction) elements[0]);
- final IJavaScriptElement element= selection.resolveEnclosingElement();
- return (element instanceof IFunction) && isChangeSignatureAvailable((IFunction) element);
- }
-
- public static boolean isCommonDeclaringType(final IMember[] members) {
- if (members.length == 0)
- return false;
- final IType type= members[0].getDeclaringType();
- if (type == null)
- return false;
- for (int index= 0; index < members.length; index++) {
- if (!type.equals(members[index].getDeclaringType()))
- return false;
- }
- return true;
- }
-
- public static boolean isConvertAnonymousAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IType) {
- return isConvertAnonymousAvailable((IType) selection.getFirstElement());
- }
- }
- return false;
- }
-
- public static boolean isConvertAnonymousAvailable(final IType type) throws JavaScriptModelException {
- if (Checks.isAvailable(type)) {
- return type.isAnonymous();
- }
- return false;
- }
-
- public static boolean isConvertAnonymousAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IType type= RefactoringActions.getEnclosingType(selection);
- if (type != null)
- return RefactoringAvailabilityTester.isConvertAnonymousAvailable(type);
- return false;
- }
-
- public static boolean isCopyAvailable(final IResource[] resources, final IJavaScriptElement[] elements) throws JavaScriptModelException {
- return ReorgPolicyFactory.createCopyPolicy(resources, elements).canEnable();
- }
-
- public static boolean isDelegateCreationAvailable(final IField field) throws JavaScriptModelException {
- return false;
- }
-
- public static boolean isDeleteAvailable(final IJavaScriptElement element) throws JavaScriptModelException {
- if (!element.exists())
- return false;
- if (element instanceof IJavaScriptModel || element instanceof IJavaScriptProject)
- return false;
- if (element.getParent() != null && element.getParent().isReadOnly())
- return false;
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) element;
- if (root.isExternal() || Checks.isClasspathDelete(root)) // TODO
- // rename
- // isClasspathDelete
- return false;
- }
- if (element.getResource() == null && !RefactoringAvailabilityTester.isWorkingCopyElement(element))
- return false;
- if (element instanceof IMember && ((IMember) element).isBinary())
- return false;
- return true;
- }
-
- public static boolean isDeleteAvailable(final IResource resource) {
- if (!resource.exists() || resource.isPhantom())
- return false;
- if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT)
- return false;
- return true;
- }
-
- public static boolean isDeleteAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (!selection.isEmpty())
- return isDeleteAvailable(selection.toArray());
- return false;
- }
-
- public static boolean isDeleteAvailable(final Object[] objects) throws JavaScriptModelException {
- if (objects.length != 0) {
- final IResource[] resources= RefactoringAvailabilityTester.getResources(objects);
- final IJavaScriptElement[] elements= RefactoringAvailabilityTester.getJavaElements(objects);
- if (objects.length != resources.length + elements.length)
- return false;
- for (int index= 0; index < resources.length; index++) {
- if (!isDeleteAvailable(resources[index]))
- return false;
- }
- for (int index= 0; index < elements.length; index++) {
- if (!isDeleteAvailable(elements[index]))
- return false;
- }
- return true;
- }
- return false;
- }
-
- public static boolean isExternalizeStringsAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement javaElement= (IJavaScriptElement)element;
- if (javaElement.exists() && !javaElement.isReadOnly()) {
- int elementType= javaElement.getElementType();
- if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT) {
- return true;
- } else if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)javaElement;
- if (!root.isExternal() && !ReorgUtils.isClassFolder(root))
- return true;
- } else if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- return true;
- } else if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- IJavaScriptUnit cu= (IJavaScriptUnit)javaElement;
- if (cu.exists())
- return true;
- } else if (elementType == IJavaScriptElement.TYPE) {
- IType type= (IType)element;
- IJavaScriptUnit cu= type.getJavaScriptUnit();
- if (cu != null && cu.exists())
- return true;
- }
- }
- }
- }
- return false;
- }
-
- public static boolean isExtractConstantAvailable(final JavaTextSelection selection) {
- return (selection.resolveInClassInitializer() || selection.resolveInMethodBody() || selection.resolveInVariableInitializer()) && Checks.isExtractableExpression(selection.resolveSelectedNodes(), selection.resolveCoveringNode());
- }
-
- public static boolean isExtractInterfaceAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- Object first= selection.getFirstElement();
- if (first instanceof IType) {
- return isExtractInterfaceAvailable((IType) first);
- } else if (first instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit) first;
- if (!unit.exists() || unit.isReadOnly())
- return false;
-
- return true;
- }
- }
- return false;
- }
-
- public static boolean isExtractInterfaceAvailable(final IType type) throws JavaScriptModelException {
- return Checks.isAvailable(type) && !type.isBinary() && !type.isReadOnly() && !type.isAnonymous();
- }
-
- public static boolean isExtractInterfaceAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- return isExtractInterfaceAvailable(RefactoringActions.getEnclosingOrPrimaryType(selection));
- }
-
- public static boolean isExtractMethodAvailable(final ASTNode[] nodes) {
- if (nodes != null && nodes.length != 0) {
- if (nodes.length == 1)
- return nodes[0] instanceof Statement || Checks.isExtractableExpression(nodes[0]);
- else {
- for (int index= 0; index < nodes.length; index++) {
- if (!(nodes[index] instanceof Statement))
- return false;
- }
- return true;
- }
- }
- return false;
- }
-
- public static boolean isExtractMethodAvailable(final JavaTextSelection selection) {
- return (selection.resolveInMethodBody() || selection.resolveInClassInitializer()) && RefactoringAvailabilityTester.isExtractMethodAvailable(selection.resolveSelectedNodes());
- }
-
- public static boolean isExtractSupertypeAvailable(IMember member) throws JavaScriptModelException {
- if (!member.exists())
- return false;
- final int type= member.getElementType();
- if (type != IJavaScriptElement.METHOD && type != IJavaScriptElement.FIELD && type != IJavaScriptElement.TYPE)
- return false;
- if (!Checks.isAvailable(member))
- return false;
- if (member instanceof IType) {
- if (!JdtFlags.isStatic(member))
- return false;
- }
- if (member instanceof IFunction) {
- final IFunction method= (IFunction) member;
- if (method.isConstructor())
- return false;
- }
- return true;
- }
-
- public static boolean isExtractSupertypeAvailable(final IMember[] members) throws JavaScriptModelException {
- if (members != null && members.length != 0) {
- final IType type= getTopLevelType(members);
- if (type != null)
- return true;
- for (int index= 0; index < members.length; index++) {
- if (!isExtractSupertypeAvailable(members[index]))
- return false;
- }
- return isCommonDeclaringType(members);
- }
- return false;
- }
-
- public static boolean isExtractSupertypeAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (!selection.isEmpty()) {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IJavaScriptUnit)
- return true; // Do not force opening
- final IType type= getSingleSelectedType(selection);
- if (type != null)
- return Checks.isAvailable(type) && isExtractSupertypeAvailable(new IType[] { type});
- }
- for (final Iterator iterator= selection.iterator(); iterator.hasNext();) {
- if (!(iterator.next() instanceof IMember))
- return false;
- }
- final Set members= new HashSet();
- members.addAll(Arrays.asList(selection.toArray()));
- return isExtractSupertypeAvailable((IMember[]) members.toArray(new IMember[members.size()]));
- }
- return false;
- }
-
- public static boolean isExtractSupertypeAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= selection.resolveEnclosingElement();
- if (!(element instanceof IMember))
- return false;
- return isExtractSupertypeAvailable(new IMember[] { (IMember) element});
- }
-
- public static boolean isExtractTempAvailable(final JavaTextSelection selection) {
- final ASTNode[] nodes= selection.resolveSelectedNodes();
- return (selection.resolveInMethodBody() || selection.resolveInClassInitializer()) && (Checks.isExtractableExpression(nodes, selection.resolveCoveringNode()) || (nodes != null && nodes.length == 1 && nodes[0] instanceof ExpressionStatement));
- }
-
- public static boolean isGeneralizeTypeAvailable(final IJavaScriptElement element) throws JavaScriptModelException {
- if (element != null && element.exists()) {
- String type= null;
- if (element instanceof IFunction)
- type= ((IFunction) element).getReturnType();
- else if (element instanceof IField) {
- final IField field= (IField) element;
- type= field.getTypeSignature();
- } else if (element instanceof ILocalVariable)
- return true;
- else if (element instanceof IType) {
- return true;
- }
- if (type == null || PrimitiveType.toCode(Signature.toString(type)) != null)
- return false;
- return true;
- }
- return false;
- }
-
- public static boolean isGeneralizeTypeAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- final Object element= selection.getFirstElement();
- if (element instanceof IFunction) {
- final IFunction method= (IFunction) element;
- if (!method.exists())
- return false;
- final String type= method.getReturnType();
- if (PrimitiveType.toCode(Signature.toString(type)) == null)
- return Checks.isAvailable(method);
- } else if (element instanceof IField) {
- final IField field= (IField) element;
- if (!field.exists())
- return false;
-
- return Checks.isAvailable(field);
- }
- }
- return false;
- }
-
- public static boolean isGeneralizeTypeAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- return isGeneralizeTypeAvailable(elements[0]);
- }
-
- public static boolean isInferTypeArgumentsAvailable(final IJavaScriptElement element) throws JavaScriptModelException {
- if (!Checks.isAvailable(element)) {
- return false;
- } else if (element instanceof IJavaScriptProject) {
- IJavaScriptProject project= (IJavaScriptProject) element;
- IIncludePathEntry[] classpathEntries= project.getRawIncludepath();
- for (int i= 0; i < classpathEntries.length; i++) {
- if (classpathEntries[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE)
- return true;
- }
- return false;
- } else if (element instanceof IPackageFragmentRoot) {
- return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE;
- } else if (element instanceof IPackageFragment) {
- return ((IPackageFragment) element).getKind() == IPackageFragmentRoot.K_SOURCE;
- } else if (element instanceof IJavaScriptUnit) {
- return true;
- } else if (element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT) != null) {
- return true;
- } else {
- return false;
- }
- }
-
- public static boolean isInferTypeArgumentsAvailable(final IJavaScriptElement[] elements) throws JavaScriptModelException {
- if (elements.length == 0)
- return false;
-
- for (int i= 0; i < elements.length; i++) {
- if (!(isInferTypeArgumentsAvailable(elements[i])))
- return false;
- }
- return true;
- }
-
- public static boolean isInferTypeArgumentsAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty())
- return false;
-
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (!(element instanceof IJavaScriptElement))
- return false;
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit) element;
- if (!unit.exists() || unit.isReadOnly())
- return false;
-
- return true;
- }
- if (!isInferTypeArgumentsAvailable((IJavaScriptElement) element))
- return false;
- }
- return true;
- }
-
- public static boolean isInlineConstantAvailable(final IField field) throws JavaScriptModelException {
- return Checks.isAvailable(field) && JdtFlags.isStatic(field) && JdtFlags.isFinal(field);
- }
-
- public static boolean isInlineConstantAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty() || selection.size() != 1)
- return false;
- final Object first= selection.getFirstElement();
- return (first instanceof IField) && isInlineConstantAvailable(((IField) first));
- }
-
- public static boolean isInlineConstantAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- return (elements[0] instanceof IField) && isInlineConstantAvailable(((IField) elements[0]));
- }
-
- public static boolean isInlineMethodAvailable(IFunction method) throws JavaScriptModelException {
- if (method == null)
- return false;
- if (!method.exists())
- return false;
- if (!method.isStructureKnown())
- return false;
- if (!method.isBinary())
- return true;
- if (method.isConstructor())
- return false;
- return SourceRange.isAvailable(method.getNameRange());
- }
-
- public static boolean isInlineMethodAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty() || selection.size() != 1)
- return false;
- final Object first= selection.getFirstElement();
- return (first instanceof IFunction) && isInlineMethodAvailable(((IFunction) first));
- }
-
- public static boolean isInlineMethodAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- IJavaScriptElement element= elements[0];
- if (!(element instanceof IFunction))
- return false;
- IFunction method= (IFunction) element;
- if (!isInlineMethodAvailable((method)))
- return false;
-
- // in binary class, only activate for method declarations
- IJavaScriptElement enclosingElement= selection.resolveEnclosingElement();
- if (enclosingElement == null || enclosingElement.getAncestor(IJavaScriptElement.CLASS_FILE) == null)
- return true;
- if (!(enclosingElement instanceof IFunction))
- return false;
- IFunction enclosingMethod= (IFunction) enclosingElement;
- if (enclosingMethod.isConstructor())
- return false;
- int nameOffset= enclosingMethod.getNameRange().getOffset();
- int nameLength= enclosingMethod.getNameRange().getLength();
- return (nameOffset <= selection.getOffset()) && (selection.getOffset() + selection.getLength() <= nameOffset + nameLength);
- }
-
- public static boolean isInlineTempAvailable(final ILocalVariable variable) throws JavaScriptModelException {
- return Checks.isAvailable(variable);
- }
-
- public static boolean isInlineTempAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- return (elements[0] instanceof ILocalVariable) && isInlineTempAvailable((ILocalVariable) elements[0]);
- }
-
- public static boolean isIntroduceFactoryAvailable(final IFunction method) throws JavaScriptModelException {
- return Checks.isAvailable(method) && method.isConstructor();
- }
-
- public static boolean isIntroduceFactoryAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1 && selection.getFirstElement() instanceof IFunction)
- return isIntroduceFactoryAvailable((IFunction) selection.getFirstElement());
- return false;
- }
-
- public static boolean isIntroduceFactoryAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length == 1 && elements[0] instanceof IFunction)
- return isIntroduceFactoryAvailable((IFunction) elements[0]);
-
- // there's no IFunction for the default constructor
- if (!Checks.isAvailable(selection.resolveEnclosingElement()))
- return false;
- ASTNode node= selection.resolveCoveringNode();
- if (node == null) {
- ASTNode[] selectedNodes= selection.resolveSelectedNodes();
- if (selectedNodes != null && selectedNodes.length == 1) {
- node= selectedNodes[0];
- if (node == null)
- return false;
- } else {
- return false;
- }
- }
-
- if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
- return true;
-
- node= ASTNodes.getNormalizedNode(node);
- if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
- return true;
-
- return false;
- }
-
- public static boolean isIntroduceIndirectionAvailable(IFunction method) throws JavaScriptModelException {
- if (method == null)
- return false;
- if (!method.exists())
- return false;
- if (!method.isStructureKnown())
- return false;
- if (method.isConstructor())
- return false;
-
- return true;
- }
-
- public static boolean isIntroduceIndirectionAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty() || selection.size() != 1)
- return false;
- final Object first= selection.getFirstElement();
- return (first instanceof IFunction) && isIntroduceIndirectionAvailable(((IFunction) first));
- }
-
- public static boolean isIntroduceIndirectionAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length == 1)
- return (elements[0] instanceof IFunction) && isIntroduceIndirectionAvailable(((IFunction) elements[0]));
- ASTNode[] selectedNodes= selection.resolveSelectedNodes();
- if (selectedNodes == null || selectedNodes.length != 1)
- return false;
- switch (selectedNodes[0].getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- case ASTNode.FUNCTION_INVOCATION:
- case ASTNode.SUPER_METHOD_INVOCATION:
- return true;
- default:
- return false;
- }
- }
-
- public static boolean isIntroduceParameterAvailable(final ASTNode[] selectedNodes, ASTNode coveringNode) {
- return Checks.isExtractableExpression(selectedNodes, coveringNode);
- }
-
- public static boolean isIntroduceParameterAvailable(final JavaTextSelection selection) {
- return selection.resolveInMethodBody() && isIntroduceParameterAvailable(selection.resolveSelectedNodes(), selection.resolveCoveringNode());
- }
-
- public static boolean isMoveAvailable(final IResource[] resources, final IJavaScriptElement[] elements) throws JavaScriptModelException {
- if (elements != null) {
- for (int index= 0; index < elements.length; index++) {
- IJavaScriptElement element= elements[index];
- if (element == null || !element.exists())
- return false;
- if ((element instanceof IType) && ((IType) element).isLocal())
- return false;
- }
- }
- return ReorgPolicyFactory.createMovePolicy(resources, elements).canEnable();
- }
-
- public static boolean isMoveAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement element= selection.resolveEnclosingElement();
- if (element == null)
- return false;
- return isMoveAvailable(new IResource[0], new IJavaScriptElement[] { element});
- }
-
- public static boolean isMoveInnerAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- Object first= selection.getFirstElement();
- if (first instanceof IType) {
- return isMoveInnerAvailable((IType) first);
- }
- }
- return false;
- }
-
- public static boolean isMoveInnerAvailable(final IType type) throws JavaScriptModelException {
- return Checks.isAvailable(type) && !Checks.isAnonymous(type) && !Checks.isTopLevel(type) && !Checks.isInsideLocalType(type);
- }
-
- public static boolean isMoveInnerAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- IType type= RefactoringAvailabilityTester.getDeclaringType(selection.resolveEnclosingElement());
- if (type == null)
- return false;
- return isMoveInnerAvailable(type);
- }
-
- public static boolean isMoveMethodAvailable(final IFunction method) throws JavaScriptModelException {
- return method.exists() && !method.isConstructor() && !method.isBinary() && !method.isReadOnly() && !JdtFlags.isStatic(method);
- }
-
- public static boolean isMoveMethodAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- final Object first= selection.getFirstElement();
- return first instanceof IFunction && isMoveMethodAvailable((IFunction) first);
- }
- return false;
- }
-
- public static boolean isMoveMethodAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement method= selection.resolveEnclosingElement();
- if (!(method instanceof IFunction))
- return false;
- return isMoveMethodAvailable((IFunction) method);
- }
-
- public static boolean isMoveStaticAvailable(final IMember member) throws JavaScriptModelException {
- if (!member.exists())
- return false;
- final int type= member.getElementType();
- if (type != IJavaScriptElement.METHOD && type != IJavaScriptElement.FIELD && type != IJavaScriptElement.TYPE)
- return false;
- final IType declaring= member.getDeclaringType();
- if (declaring == null)
- return false;
- if (!Checks.isAvailable(member))
- return false;
- if (type == IJavaScriptElement.METHOD && !JdtFlags.isStatic(member))
- return false;
- if (type == IJavaScriptElement.METHOD && ((IFunction) member).isConstructor())
- return false;
- if (type == IJavaScriptElement.TYPE && !JdtFlags.isStatic(member))
- return false;
- if (!JdtFlags.isStatic(member))
- return false;
- return true;
- }
-
- public static boolean isMoveStaticAvailable(final IMember[] members) throws JavaScriptModelException {
- for (int index= 0; index < members.length; index++) {
- if (!isMoveStaticAvailable(members[index]))
- return false;
- }
- return true;
- }
-
- public static boolean isMoveStaticAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement element= selection.resolveEnclosingElement();
- if (!(element instanceof IMember))
- return false;
- return RefactoringAvailabilityTester.isMoveStaticMembersAvailable(new IMember[] { (IMember) element});
- }
-
- public static boolean isMoveStaticMembersAvailable(final IMember[] members) throws JavaScriptModelException {
- if (members == null)
- return false;
- if (members.length == 0)
- return false;
- if (!isMoveStaticAvailable(members))
- return false;
- if (!isCommonDeclaringType(members))
- return false;
- return true;
- }
-
- public static boolean isPromoteTempAvailable(final ILocalVariable variable) throws JavaScriptModelException {
- return Checks.isAvailable(variable);
- }
-
- public static boolean isPromoteTempAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- return (elements[0] instanceof ILocalVariable) && isPromoteTempAvailable((ILocalVariable) elements[0]);
- }
-
- public static boolean isPullUpAvailable(IMember member) throws JavaScriptModelException {
- if (!member.exists())
- return false;
- final int type= member.getElementType();
- if (type != IJavaScriptElement.METHOD && type != IJavaScriptElement.FIELD && type != IJavaScriptElement.TYPE)
- return false;
- if (!Checks.isAvailable(member))
- return false;
- if (member instanceof IType) {
- if (!JdtFlags.isStatic(member))
- return false;
- }
- if (member instanceof IFunction) {
- final IFunction method= (IFunction) member;
- if (method.isConstructor())
- return false;
- }
- return true;
- }
-
- public static boolean isPullUpAvailable(final IMember[] members) throws JavaScriptModelException {
- if (members != null && members.length != 0) {
- final IType type= getTopLevelType(members);
- if (type != null && getPullUpMembers(type).length != 0)
- return true;
- for (int index= 0; index < members.length; index++) {
- if (!isPullUpAvailable(members[index]))
- return false;
- }
- return isCommonDeclaringType(members);
- }
- return false;
- }
-
- public static boolean isPullUpAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (!selection.isEmpty()) {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IJavaScriptUnit)
- return true; // Do not force opening
- final IType type= getSingleSelectedType(selection);
- if (type != null)
- return Checks.isAvailable(type) && isPullUpAvailable(new IType[] { type});
- }
- for (final Iterator iterator= selection.iterator(); iterator.hasNext();) {
- if (!(iterator.next() instanceof IMember))
- return false;
- }
- final Set members= new HashSet();
- members.addAll(Arrays.asList(selection.toArray()));
- return isPullUpAvailable((IMember[]) members.toArray(new IMember[members.size()]));
- }
- return false;
- }
-
- public static boolean isPullUpAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= selection.resolveEnclosingElement();
- if (!(element instanceof IMember))
- return false;
- return isPullUpAvailable(new IMember[] { (IMember) element});
- }
-
- public static boolean isPushDownAvailable(final IMember member) throws JavaScriptModelException {
- if (!member.exists())
- return false;
- final int type= member.getElementType();
- if (type != IJavaScriptElement.METHOD && type != IJavaScriptElement.FIELD)
- return false;
- if (!Checks.isAvailable(member))
- return false;
- if (JdtFlags.isStatic(member))
- return false;
- if (type == IJavaScriptElement.METHOD) {
- final IFunction method= (IFunction) member;
- if (method.isConstructor())
- return false;
- }
- return true;
- }
-
- public static boolean isPushDownAvailable(final IMember[] members) throws JavaScriptModelException {
- if (members != null && members.length != 0) {
- final IType type= getTopLevelType(members);
- if (type != null && RefactoringAvailabilityTester.getPushDownMembers(type).length != 0)
- return true;
- for (int index= 0; index < members.length; index++) {
- if (!isPushDownAvailable(members[index]))
- return false;
- }
- return isCommonDeclaringType(members);
- }
- return false;
- }
-
- public static boolean isPushDownAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (!selection.isEmpty()) {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IJavaScriptUnit)
- return true; // Do not force opening
- final IType type= getSingleSelectedType(selection);
- if (type != null)
- return isPushDownAvailable(new IType[] { type});
- }
- for (final Iterator iterator= selection.iterator(); iterator.hasNext();) {
- if (!(iterator.next() instanceof IMember))
- return false;
- }
- final Set members= new HashSet();
- members.addAll(Arrays.asList(selection.toArray()));
- return isPushDownAvailable((IMember[]) members.toArray(new IMember[members.size()]));
- }
- return false;
- }
-
- public static boolean isPushDownAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= selection.resolveEnclosingElement();
- if (!(element instanceof IMember))
- return false;
- return isPullUpAvailable(new IMember[] { (IMember) element});
- }
-
- public static boolean isRenameAvailable(final IJavaScriptUnit unit) {
- if (unit == null)
- return false;
- if (!unit.exists())
- return false;
- if (!JavaModelUtil.isPrimary(unit))
- return false;
- if (unit.isReadOnly())
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final IJavaScriptProject project) throws JavaScriptModelException {
- if (project == null)
- return false;
- if (!Checks.isAvailable(project))
- return false;
- if (!project.isConsistent())
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final ILocalVariable variable) throws JavaScriptModelException {
- return Checks.isAvailable(variable);
- }
-
- public static boolean isRenameAvailable(final IFunction method) throws CoreException {
- if (method == null)
- return false;
- if (!Checks.isAvailable(method))
- return false;
- if (method.isConstructor())
- return false;
- if (isRenameProhibited(method))
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final IPackageFragment fragment) throws JavaScriptModelException {
- if (fragment == null)
- return false;
- if (!Checks.isAvailable(fragment))
- return false;
- if (fragment.isDefaultPackage())
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final IPackageFragmentRoot root) throws JavaScriptModelException {
- if (root == null)
- return false;
- if (!Checks.isAvailable(root))
- return false;
- if (root.isArchive())
- return false;
- if (root.isExternal())
- return false;
- if (!root.isConsistent())
- return false;
- if (root.getResource() instanceof IProject)
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final IResource resource) {
- if (resource == null)
- return false;
- if (!resource.exists())
- return false;
- if (!resource.isAccessible())
- return false;
- return true;
- }
-
- public static boolean isRenameAvailable(final IType type) throws JavaScriptModelException {
- if (type == null)
- return false;
- if (type.isAnonymous())
- return false;
- if (!Checks.isAvailable(type))
- return false;
- if (isRenameProhibited(type))
- return false;
- InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders( (IInferenceFile)type.getJavaScriptUnit());
- if (inferenceProviders.length>0 && inferenceProviders[0].getRefactoringSupport()!=null)
- {
- RefactoringSupport refactoringSupport = inferenceProviders[0].getRefactoringSupport();
- if (refactoringSupport!=null)
- return refactoringSupport.supportsClassRename();
- }
-
-
- return false;
- }
-
- public static boolean isRenameFieldAvailable(final IField field) throws JavaScriptModelException {
- return Checks.isAvailable(field);
- }
-
- public static boolean isRenameNonVirtualMethodAvailable(final IFunction method) throws JavaScriptModelException, CoreException {
- return isRenameAvailable(method) && !MethodChecks.isVirtual(method);
- }
-
- public static boolean isRenameProhibited(final IFunction method) throws CoreException {
- if (method.getElementName().equals("toString") //$NON-NLS-1$
- && (method.getNumberOfParameters() == 0) && (method.getReturnType().equals("Ljava.lang.String;") //$NON-NLS-1$
- || method.getReturnType().equals("QString;") //$NON-NLS-1$
- || method.getReturnType().equals("Qjava.lang.String;"))) //$NON-NLS-1$
- return true;
- else
- return false;
- }
-
- public static boolean isRenameProhibited(final IType type) {
- return type.getPackageFragment().getElementName().equals("java.lang"); //$NON-NLS-1$
- }
-
- public static boolean isRenameVirtualMethodAvailable(final IFunction method) throws CoreException {
- return isRenameAvailable(method) && MethodChecks.isVirtual(method);
- }
-
- public static boolean isReplaceInvocationsAvailable(IFunction method) throws JavaScriptModelException {
- if (method == null)
- return false;
- if (!method.exists())
- return false;
- if (method.isConstructor())
- return false;
- return true;
- }
-
- public static boolean isReplaceInvocationsAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty() || selection.size() != 1)
- return false;
- final Object first= selection.getFirstElement();
- return (first instanceof IFunction) && isReplaceInvocationsAvailable(((IFunction) first));
- }
-
- public static boolean isReplaceInvocationsAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- IJavaScriptElement element= elements[0];
- return (element instanceof IFunction) && isReplaceInvocationsAvailable(((IFunction) element));
- }
-
- public static boolean isSelfEncapsulateAvailable(IField field) throws JavaScriptModelException {
- return Checks.isAvailable(field);
- }
-
- public static boolean isSelfEncapsulateAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- if (selection.getFirstElement() instanceof IField) {
- final IField field= (IField) selection.getFirstElement();
- return Checks.isAvailable(field);
- }
- }
- return false;
- }
-
- public static boolean isSelfEncapsulateAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement[] elements= selection.resolveElementAtOffset();
- if (elements.length != 1)
- return false;
- return (elements[0] instanceof IField) && isSelfEncapsulateAvailable((IField) elements[0]);
- }
-
- public static boolean isUseSuperTypeAvailable(final IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() == 1) {
- final Object first= selection.getFirstElement();
- if (first instanceof IType) {
- return isUseSuperTypeAvailable((IType) first);
- } else if (first instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit) first;
- if (!unit.exists() || unit.isReadOnly())
- return false;
-
- return true;
- }
- }
- return false;
- }
-
- public static boolean isUseSuperTypeAvailable(final IType type) throws JavaScriptModelException {
- return type != null && type.exists();
- }
-
- public static boolean isUseSuperTypeAvailable(final JavaTextSelection selection) throws JavaScriptModelException {
- return isUseSuperTypeAvailable(RefactoringActions.getEnclosingOrPrimaryType(selection));
- }
-
- public static boolean isWorkingCopyElement(final IJavaScriptElement element) {
- if (element instanceof IJavaScriptUnit)
- return ((IJavaScriptUnit) element).isWorkingCopy();
- if (ReorgUtils.isInsideCompilationUnit(element))
- return ReorgUtils.getCompilationUnit(element).isWorkingCopy();
- return false;
- }
-
- private RefactoringAvailabilityTester() {
- // Not for instantiation
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringCoreMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringCoreMessages.java
deleted file mode 100644
index bb1ea47c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringCoreMessages.java
+++ /dev/null
@@ -1,2350 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class RefactoringCoreMessages extends NLS {
-
- public static String AbstractDeleteChange_deleting;
-
- public static String AbstractRenameChange_Renaming;
-
- public static String AddToClasspathChange_add;
-
- public static String Assert_assertion_failed;
-
- public static String Assert_null_argument;
-
- public static String ASTData_update_imports;
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.refactoring.refactoring";//$NON-NLS-1$
-
- public static String CallInliner_cast_analysis_error;
-
- public static String CallInliner_constructors;
-
- public static String CallInliner_execution_flow;
-
- public static String CallInliner_field_initialize_new_local;
-
- public static String CallInliner_field_initialize_self_reference;
-
- public static String CallInliner_field_initialize_write_parameter;
-
- public static String CallInliner_field_initializer_simple;
-
- public static String CallInliner_multiDeclaration;
-
- public static String CallInliner_receiver_type;
-
- public static String CallInliner_simple_functions;
-
- public static String CallInliner_super_into_this_expression;
-
- public static String Change_does_not_exist;
-
- public static String Change_has_modifications;
-
- public static String Change_is_read_only;
-
- public static String Change_is_unsaved;
-
- public static String Change_same_read_only;
-
- public static String ChangeSignatureRefactoring_add_constructor;
-
- public static String ChangeSignatureRefactoring_add_super_call;
-
- public static String ChangeSignatureRefactoring_added_exceptions;
-
- public static String ChangeSignatureRefactoring_added_parameter_pattern;
-
- public static String ChangeSignatureRefactoring_added_parameters;
-
- public static String ChangeSignatureRefactoring_already_has;
-
- public static String ChangeSignatureRefactoring_anonymous_subclass;
-
- public static String ChangeSignatureRefactoring_cannot_convert_vararg;
-
- public static String ChangeSignatureRefactoring_change_signature;
-
- public static String ChangeSignatureRefactoring_changed_parameter_pattern;
-
- public static String ChangeSignatureRefactoring_changed_parameters;
-
- public static String ChangeSignatureRefactoring_checking_preconditions;
-
- public static String ChangeSignatureRefactoring_constructor_name;
-
- public static String ChangeSignatureRefactoring_default_value;
-
- public static String ChangeSignatureRefactoring_default_visibility;
-
- public static String ChangeSignatureRefactoring_deleted_parameter_pattern;
-
- public static String ChangeSignatureRefactoring_descriptor_description;
-
- public static String ChangeSignatureRefactoring_descriptor_description_short;
-
- public static String ChangeSignatureRefactoring_duplicate_name;
-
- public static String ChangeSignatureRefactoring_invalid_expression;
-
- public static String ChangeSignatureRefactoring_method_deleted;
-
- public static String ChangeSignatureRefactoring_method_name_not_empty;
-
- public static String ChangeSignatureRefactoring_modify_Parameters;
-
- public static String ChangeSignatureRefactoring_native;
-
- public static String ChangeSignatureRefactoring_new_name_pattern;
-
- public static String ChangeSignatureRefactoring_new_return_type_pattern;
-
- public static String ChangeSignatureRefactoring_new_visibility_pattern;
-
- public static String ChangeSignatureRefactoring_no_exception_binding;
-
- public static String ChangeSignatureRefactoring_non_virtual;
-
- public static String ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different;
-
- public static String ChangeSignatureRefactoring_param_name_not_empty;
-
- public static String ChangeSignatureRefactoring_parameter_type_contains_type_variable;
-
- public static String ChangeSignatureRefactoring_parameter_used;
-
- public static String ChangeSignatureRefactoring_preview;
-
- public static String ChangeSignatureRefactoring_removed_exceptions;
-
- public static String ChangeSignatureRefactoring_removed_parameters;
-
- public static String ChangeSignatureRefactoring_restructure_parameters;
-
- public static String ChangeSignatureRefactoring_return_type_contains_type_variable;
-
- public static String ChangeSignatureRefactoring_ripple_cannot_convert_vararg;
-
- public static String ChangeSignatureRefactoring_unchanged;
-
- public static String ChangeSignatureRefactoring_update_javadoc_reference;
-
- public static String ChangeSignatureRefactoring_update_parameter_references;
-
- public static String ChangeSignatureRefactoring_update_reference;
-
- public static String ChangeSignatureRefactoring_vararg_must_be_last;
-
- public static String ChangeTypeMessages_CreateChangesForChangeType;
-
- public static String ChangeTypeRefactoring_allChanges;
-
- public static String ChangeTypeRefactoring_analyzingMessage;
-
- public static String ChangeTypeRefactoring_arraysNotSupported;
-
- public static String ChangeTypeRefactoring_cantDoIt;
-
- public static String ChangeTypeRefactoring_changes;
-
- public static String ChangeTypeRefactoring_checking_preconditions;
-
- public static String ChangeTypeRefactoring_descriptor_description;
-
- public static String ChangeTypeRefactoring_descriptor_description_short;
-
- public static String ChangeTypeRefactoring_enumsNotSupported;
-
- public static String ChangeTypeRefactoring_failedToSelectType;
-
- public static String ChangeTypeRefactoring_Generalize_Type;
-
- public static String ChangeTypeRefactoring_insideLocalTypesNotSupported;
-
- public static String ChangeTypeRefactoring_invalidSelection;
-
- public static String ChangeTypeRefactoring_javaLangObject;
-
- public static String ChangeTypeRefactoring_localTypesNotSupported;
-
- public static String ChangeTypeRefactoring_multiDeclarationsNotSupported;
-
- public static String ChangeTypeRefactoring_name;
-
- public static String ChangeTypeRefactoring_no_filed;
-
- public static String ChangeTypeRefactoring_no_method;
-
- public static String ChangeTypeRefactoring_noMatchingConstraintVariable;
-
- public static String ChangeTypeRefactoring_notSupportedOnBinary;
-
- public static String ChangeTypeRefactoring_notSupportedOnNodeType;
-
- public static String ChangeTypeRefactoring_original_element_pattern;
-
- public static String ChangeTypeRefactoring_original_type_pattern;
-
- public static String ChangeTypeRefactoring_primitivesNotSupported;
-
- public static String ChangeTypeRefactoring_refactored_type_pattern;
-
- public static String ChangeTypeRefactoring_typeChange;
-
- public static String ChangeTypeRefactoring_typeParametersNotSupported;
-
- public static String ChangeTypeRefactoring_unhandledSearchException;
-
- public static String Checks_all_excluded;
-
- public static String Checks_cannot_be_parsed;
-
- public static String Checks_Choose_name;
-
- public static String Checks_constructor_name;
-
- public static String Checks_cu_has_compile_errors;
-
- public static String Checks_cu_name_used;
-
- public static String Checks_cu_not_created;
-
- public static String Checks_cu_not_parsed;
-
- public static String Checks_has_main;
-
- public static String Checks_method_names_lowercase;
-
- public static String Checks_method_names_lowercase2;
-
- public static String Checks_method_native;
-
- public static String Checks_methodName_constructor;
-
- public static String Checks_methodName_exists;
-
- public static String Checks_methodName_overrides;
-
- public static String Checks_methodName_returnTypeClash;
-
- public static String Checks_no_dot;
-
- public static String Checks_validateEdit;
-
- public static String CodeAnalyzer_array_initializer;
-
- public static String CodeRefactoringUtil_error_message;
-
- public static String CommentAnalyzer_ends_inside_comment;
-
- public static String CommentAnalyzer_internal_error;
-
- public static String CommentAnalyzer_starts_inside_comment;
-
- public static String CompilationUnitChange_label;
-
- public static String ConvertAnonymousToNestedRefactoring_anonymous_field_access;
-
- public static String ConvertAnonymousToNestedRefactoring_another_name;
-
- public static String ConvertAnonymousToNestedRefactoring_class_name_pattern;
-
- public static String ConvertAnonymousToNestedRefactoring_compile_errors;
-
- public static String ConvertAnonymousToNestedRefactoring_declare_final;
-
- public static String ConvertAnonymousToNestedRefactoring_declare_final_static;
-
- public static String ConvertAnonymousToNestedRefactoring_declare_static;
-
- public static String ConvertAnonymousToNestedRefactoring_default_visibility;
-
- public static String ConvertAnonymousToNestedRefactoring_descriptor_description;
-
- public static String ConvertAnonymousToNestedRefactoring_descriptor_description_short;
-
- public static String ConvertAnonymousToNestedRefactoring_edit_name;
-
- public static String ConvertAnonymousToNestedRefactoring_extends_local_class;
-
- public static String ConvertAnonymousToNestedRefactoring_name;
-
- public static String ConvertAnonymousToNestedRefactoring_name_hides;
-
- public static String ConvertAnonymousToNestedRefactoring_original_pattern;
-
- public static String ConvertAnonymousToNestedRefactoring_place_caret;
-
- public static String ConvertAnonymousToNestedRefactoring_type_exists;
-
- public static String ConvertAnonymousToNestedRefactoring_visibility_pattern;
-
- public static String CopyCompilationUnitChange_copy;
-
- public static String CopyPackageChange_copy;
-
- public static String CopyPackageFragmentRootChange_copy;
-
- public static String CopyRefactoring_cu_copyOf1;
-
- public static String CopyRefactoring_cu_copyOfMore;
-
- public static String CopyRefactoring_package_copyOf1;
-
- public static String CopyRefactoring_package_copyOfMore;
-
- public static String CopyRefactoring_resource_copyOf1;
-
- public static String CopyRefactoring_resource_copyOfMore;
-
- public static String CopyRefactoring_searching;
-
- public static String CopyRefactoring_update_ref;
-
- public static String CopyResourceString_copy;
-
- public static String CreateCopyOfCompilationUnitChange_create_copy;
-
- public static String CreatePackageChange_Create_package;
-
- public static String CreatePackageChange_Creating_package;
-
- public static String DelegateCreator_cannot_create_delegate_for_type;
-
- public static String DelegateCreator_cannot_create_field_delegate_more_than_one_fragment;
-
- public static String DelegateCreator_cannot_create_field_delegate_no_initializer;
-
- public static String DelegateCreator_cannot_create_field_delegate_not_final;
-
- public static String DelegateCreator_change_category_description;
-
- public static String DelegateCreator_change_category_title;
-
- public static String DelegateCreator_keep_original_changed_plural;
-
- public static String DelegateCreator_keep_original_changed_singular;
-
- public static String DelegateCreator_use_member_instead;
-
- public static String DelegateFieldCreator_keep_original_renamed_plural;
-
- public static String DelegateFieldCreator_keep_original_renamed_singular;
-
- public static String DelegateFieldCreator_text_edit_group_label;
-
- public static String DelegateMethodCreator_keep_original_moved_plural;
-
- public static String DelegateMethodCreator_keep_original_moved_singular;
-
- public static String DelegateMethodCreator_keep_original_renamed_plural;
-
- public static String DelegateMethodCreator_keep_original_renamed_singular;
-
- public static String DelegateMethodCreator_text_edit_group_field;
-
- public static String DeleteChangeCreator_1;
-
- public static String DeleteFileChange_1;
-
- public static String DeleteFolderChange_0;
-
- public static String DeleteFromClassPathChange_remove;
-
- public static String DeletePackageFragmentRootChange_delete;
-
- public static String DeletePackageFragmentRootChange_restore_file;
-
- public static String DeleteRefactoring_1;
-
- public static String DeleteRefactoring_2;
-
- public static String DeleteRefactoring_3;
-
- public static String DeleteRefactoring_4;
-
- public static String DeleteRefactoring_5;
-
- public static String DeleteRefactoring_7;
-
- public static String DeleteRefactoring_8;
-
- public static String DeleteRefactoring_9;
-
- public static String DeleteRefactoring_delete_package_fragment_root;
-
- public static String DeleteSourceManipulationChange_0;
-
- public static String DeleteSourceManipulationChange_1;
-
- public static String DynamicValidationRefactoringChange_fatal_error;
-
- public static String DynamicValidationStateChange_workspace_changed;
-
- public static String ExtractConstantRefactoring_another_variable;
-
- public static String ExtractConstantRefactoring_change_name;
-
- public static String ExtractConstantRefactoring_checking_preconditions;
-
- public static String ExtractConstantRefactoring_constant_expression_pattern;
-
- public static String ExtractConstantRefactoring_constant_name_pattern;
-
- public static String ExtractConstantRefactoring_convention;
-
- public static String ExtractConstantRefactoring_declare_constant;
-
- public static String ExtractConstantRefactoring_default_visibility;
-
- public static String ExtractConstantRefactoring_descriptor_description;
-
- public static String ExtractConstantRefactoring_descriptor_description_short;
-
- public static String ExtractConstantRefactoring_name;
-
- public static String ExtractConstantRefactoring_no_void;
-
- public static String ExtractConstantRefactoring_not_load_time_constant;
-
- public static String ExtractConstantRefactoring_null_literals;
-
- public static String ExtractConstantRefactoring_qualify_references;
-
- public static String ExtractConstantRefactoring_replace;
-
- public static String ExtractConstantRefactoring_replace_occurrences;
-
- public static String ExtractConstantRefactoring_select_expression;
-
- public static String ExtractConstantRefactoring_syntax_error;
-
- public static String ExtractConstantRefactoring_visibility_pattern;
-
- public static String ExtractInterfaceProcessor_add_comment;
-
- public static String ExtractInterfaceProcessor_add_super_interface;
-
- public static String ExtractInterfaceProcessor_category_description;
-
- public static String ExtractInterfaceProcessor_category_name;
-
- public static String ExtractInterfaceProcessor_checking;
-
- public static String ExtractInterfaceProcessor_creating;
-
- public static String ExtractInterfaceProcessor_description_descriptor_short;
-
- public static String ExtractInterfaceProcessor_descriptor_description;
-
- public static String ExtractInterfaceProcessor_existing_compilation_unit;
-
- public static String ExtractInterfaceProcessor_existing_default_type;
-
- public static String ExtractInterfaceProcessor_existing_type;
-
- public static String ExtractInterfaceProcessor_extracted_members_pattern;
-
- public static String ExtractInterfaceProcessor_internal_error;
-
- public static String ExtractInterfaceProcessor_name;
-
- public static String ExtractInterfaceProcessor_no_annotation;
-
- public static String ExtractInterfaceProcessor_no_anonymous;
-
- public static String ExtractInterfaceProcessor_no_binary;
-
- public static String ExtractInterfaceProcessor_refactored_element_pattern;
-
- public static String ExtractInterfaceProcessor_remove_field_label;
-
- public static String ExtractInterfaceProcessor_remove_method_label;
-
- public static String ExtractInterfaceProcessor_rewrite_comment;
-
- public static String ExtractInterfaceRefactoring_name;
-
- public static String ExtractMethodAnalyzer_after_do_keyword;
-
- public static String ExtractMethodAnalyzer_ambiguous_return_value;
-
- public static String ExtractMethodAnalyzer_assignments_to_local;
-
- public static String ExtractMethodAnalyzer_branch_mismatch;
-
- public static String ExtractMethodAnalyzer_cannot_determine_return_type;
-
- public static String ExtractMethodAnalyzer_cannot_extract_anonymous_type;
-
- public static String ExtractMethodAnalyzer_cannot_extract_for_initializer;
-
- public static String ExtractMethodAnalyzer_cannot_extract_for_updater;
-
- public static String ExtractMethodAnalyzer_cannot_extract_method_name_reference;
-
- public static String ExtractMethodAnalyzer_cannot_extract_name_in_declaration;
-
- public static String ExtractMethodAnalyzer_cannot_extract_null_type;
-
- public static String ExtractMethodAnalyzer_cannot_extract_switch_case;
-
- public static String ExtractMethodAnalyzer_cannot_extract_type_reference;
-
- public static String ExtractMethodAnalyzer_cannot_extract_variable_declaration;
-
- public static String ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment;
-
- public static String ExtractMethodAnalyzer_compile_errors;
-
- public static String ExtractMethodAnalyzer_compile_errors_no_parent_binding;
-
- public static String ExtractMethodAnalyzer_leftHandSideOfAssignment;
-
- public static String ExtractMethodAnalyzer_only_method_body;
-
- public static String ExtractMethodAnalyzer_parent_mismatch;
-
- public static String ExtractMethodAnalyzer_single_expression_or_set;
-
- public static String ExtractMethodAnalyzer_super_or_this;
-
- public static String ExtractMethodRefactoring_add_method;
-
- public static String ExtractMethodRefactoring_change_name;
-
- public static String ExtractMethodRefactoring_checking_new_name;
-
- public static String ExtractMethodRefactoring_declare_thrown_exceptions;
-
- public static String ExtractMethodRefactoring_default_visibility;
-
- public static String ExtractMethodRefactoring_descriptor_description;
-
- public static String ExtractMethodRefactoring_descriptor_description_short;
-
- public static String ExtractMethodRefactoring_destination_pattern;
-
- public static String ExtractMethodRefactoring_duplicates_multi;
-
- public static String ExtractMethodRefactoring_duplicates_single;
-
- public static String ExtractMethodRefactoring_error_nameInUse;
-
- public static String ExtractMethodRefactoring_error_sameParameter;
-
- public static String ExtractMethodRefactoring_error_vararg_ordering;
-
- public static String ExtractMethodRefactoring_generate_comment;
-
- public static String ExtractMethodRefactoring_name;
-
- public static String ExtractMethodRefactoring_name_pattern;
-
- public static String ExtractMethodRefactoring_no_set_of_statements;
-
- public static String ExtractMethodRefactoring_organize_imports;
-
- public static String ExtractMethodRefactoring_replace_occurrences;
-
- public static String ExtractMethodRefactoring_substitute_with_call;
-
- public static String ExtractMethodRefactoring_visibility_pattern;
-
- public static String ExtractSupertypeProcessor_add_supertype;
-
- public static String ExtractSupertypeProcessor_category_description;
-
- public static String ExtractSupertypeProcessor_category_name;
-
- public static String ExtractSupertypeProcessor_checking;
-
- public static String ExtractSupertypeProcessor_computing_possible_types;
-
- public static String ExtractSupertypeProcessor_descriptor_description;
-
- public static String ExtractSupertypeProcessor_descriptor_description_short;
-
- public static String ExtractSupertypeProcessor_extract_supertype;
-
- public static String ExtractSupertypeProcessor_preparing;
-
- public static String ExtractSupertypeProcessor_refactored_element_pattern;
-
- public static String ExtractSupertypeProcessor_subtypes_pattern;
-
- public static String ExtractSupertypeProcessor_unexpected_exception;
-
- public static String ExtractSupertypeProcessor_unexpected_exception_on_layer;
-
- public static String ExtractTempRefactoring_another_variable;
-
- public static String ExtractTempRefactoring_array_initializer;
-
- public static String ExtractTempRefactoring_assigned_to;
-
- public static String ExtractTempRefactoring_assignment;
-
- public static String ExtractTempRefactoring_change_name;
-
- public static String ExtractTempRefactoring_checking_preconditions;
-
- public static String ExtractTempRefactoring_convention;
-
- public static String ExtractTempRefactoring_declare_final;
-
- public static String ExtractTempRefactoring_declare_local_variable;
-
- public static String ExtractTempRefactoring_descriptor_description;
-
- public static String ExtractTempRefactoring_descriptor_description_short;
-
- public static String ExtractTempRefactoring_destination_pattern;
-
- public static String ExtractTempRefactoring_explicit_constructor;
-
- public static String ExtractTempRefactoring_expr_in_method_or_initializer;
-
- public static String ExtractTempRefactoring_expression_pattern;
-
- public static String ExtractTempRefactoring_extract_temp;
-
- public static String ExtractTempRefactoring_for_initializer_updater;
-
- public static String ExtractTempRefactoring_name;
-
- public static String ExtractTempRefactoring_name_in_new;
-
- public static String ExtractTempRefactoring_name_pattern;
-
- public static String ExtractTempRefactoring_names_in_declarations;
-
- public static String ExtractTempRefactoring_no_void;
-
- public static String ExtractTempRefactoring_null_literals;
-
- public static String ExtractTempRefactoring_preview;
-
- public static String ExtractTempRefactoring_refers_to_for_variable;
-
- public static String ExtractTempRefactoring_replace;
-
- public static String ExtractTempRefactoring_replace_occurrences;
-
- public static String ExtractTempRefactoring_select_expression;
-
- public static String ExtractTempRefactoring_syntax_error;
-
- public static String ExtractTempRefactoring_update_imports;
-
- public static String FlowAnalyzer_execution_flow;
-
- public static String HierarchyRefactoring_add_member;
-
- public static String HierarchyRefactoring_annotation_members;
-
- public static String HierarchyRefactoring_does_not_exist;
-
- public static String HierarchyRefactoring_enum_members;
-
- public static String HierarchyRefactoring_gets_instantiated;
-
- public static String HierarchyRefactoring_initializer;
-
- public static String HierarchyRefactoring_interface_members;
-
- public static String HierarchyRefactoring_members_of_binary;
-
- public static String HierarchyRefactoring_members_of_read_only;
-
- public static String HierarchyRefactoring_remove_member;
-
- public static String InferTypeArgumentsRefactoring_addTypeArguments;
-
- public static String InferTypeArgumentsRefactoring_assume_clone;
-
- public static String InferTypeArgumentsRefactoring_building;
-
- public static String InferTypeArgumentsRefactoring_calculating_dependencies;
-
- public static String InferTypeArgumentsRefactoring_creatingChanges;
-
- public static String InferTypeArgumentsRefactoring_descriptor_description;
-
- public static String InferTypeArgumentsRefactoring_descriptor_description_project;
-
- public static String InferTypeArgumentsRefactoring_error_in_cu_skipped;
-
- public static String InferTypeArgumentsRefactoring_error_skipped;
-
- public static String InferTypeArgumentsRefactoring_internal_error;
-
- public static String InferTypeArgumentsRefactoring_leave_unconstrained;
-
- public static String InferTypeArgumentsRefactoring_name;
-
- public static String InferTypeArgumentsRefactoring_not50;
-
- public static String InferTypeArgumentsRefactoring_not50Library;
-
- public static String InferTypeArgumentsRefactoring_original_elements;
-
- public static String InferTypeArgumentsRefactoring_removeCast;
-
- public static String InferTypeArgumentsRefactoring_solving;
-
- public static String InitializableRefactoring_argument_not_exist;
-
- public static String InitializableRefactoring_illegal_argument;
-
- public static String InitializableRefactoring_inacceptable_arguments;
-
- public static String InitializableRefactoring_input_not_exists;
-
- public static String InitializableRefactoring_inputs_do_not_exist;
-
- public static String InlineConstantRefactoring_binary_file;
-
- public static String InlineConstantRefactoring_blank_finals;
-
- public static String InlineConstantRefactoring_descriptor_description;
-
- public static String InlineConstantRefactoring_descriptor_description_short;
-
- public static String InlineConstantRefactoring_inline;
-
- public static String InlineConstantRefactoring_Inline;
-
- public static String InlineConstantRefactoring_local_anonymous_unsupported;
-
- public static String InlineConstantRefactoring_members_declared_in_anonymous;
-
- public static String InlineConstantRefactoring_name;
-
- public static String InlineConstantRefactoring_original_pattern;
-
- public static String InlineConstantRefactoring_preview;
-
- public static String InlineConstantRefactoring_remove_declaration;
-
- public static String InlineConstantRefactoring_replace_references;
-
- public static String InlineConstantRefactoring_source_code_unavailable;
-
- public static String InlineConstantRefactoring_static_final_field;
-
- public static String InlineConstantRefactoring_syntax_errors;
-
- public static String InlineMethodRefactoring_checking_implements_error;
-
- public static String InlineMethodRefactoring_checking_overridden;
-
- public static String InlineMethodRefactoring_checking_overridden_error;
-
- public static String InlineMethodRefactoring_checking_overrides_error;
-
- public static String InlineMethodRefactoring_descriptor_description;
-
- public static String InlineMethodRefactoring_descriptor_description_short;
-
- public static String InlineMethodRefactoring_edit_delete;
-
- public static String InlineMethodRefactoring_edit_import;
-
- public static String InlineMethodRefactoring_edit_inline;
-
- public static String InlineMethodRefactoring_edit_inlineCall;
-
- public static String InlineMethodRefactoring_error_classFile;
-
- public static String InlineMethodRefactoring_error_noMethodDeclaration;
-
- public static String InlineMethodRefactoring_name;
-
- public static String InlineMethodRefactoring_nestedInvocation;
-
- public static String InlineMethodRefactoring_original_pattern;
-
- public static String InlineMethodRefactoring_processing;
-
- public static String InlineMethodRefactoring_remove_method;
-
- public static String InlineMethodRefactoring_replace_references;
-
- public static String InlineMethodRefactoring_searching;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_abstract_methods;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_methoddeclaration_has_errors;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_native_methods;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_qualified_this_expressions;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_recursive_call;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_syntax_errors;
-
- public static String InlineMethodRefactoring_SourceAnalyzer_typedeclaration_has_errors;
-
- public static String InlineTempRefactoring_assigned_more_once;
-
- public static String InlineTempRefactoring_descriptor_description;
-
- public static String InlineTempRefactoring_descriptor_description_short;
-
- public static String InlineTempRefactoring_exceptions_declared;
-
- public static String InlineTempRefactoring_for_initializers;
-
- public static String InlineTempRefactoring_inline;
-
- public static String InlineTempRefactoring_inline_edit_name;
-
- public static String InlineTempRefactoring_method_parameter;
-
- public static String InlineTempRefactoring_name;
-
- public static String InlineTempRefactoring_not_initialized;
-
- public static String InlineTempRefactoring_original_pattern;
-
- public static String InlineTempRefactoring_preview;
-
- public static String InlineTempRefactoring_remove_edit_name;
-
- public static String InlineTempRefactoring_select_temp;
-
- public static String InlineTempRefactoring_syntax_errors;
-
- public static String InlineTemRefactoring_error_message_fieldsCannotBeInlined;
-
- public static String InlineTemRefactoring_error_message_nulLiteralsCannotBeInlined;
-
- public static String IntroduceFactory_addFactoryMethod;
-
- public static String IntroduceFactory_callSitesInBinaryClass;
-
- public static String IntroduceFactory_cantCheckForInterface;
-
- public static String IntroduceFactory_cantPutFactoryInBinaryClass;
-
- public static String IntroduceFactory_cantPutFactoryMethodOnAnnotation;
-
- public static String IntroduceFactory_cantPutFactoryMethodOnInterface;
-
- public static String IntroduceFactory_checking_preconditions;
-
- public static String IntroduceFactory_checkingActivation;
-
- public static String IntroduceFactory_constructorInBinaryClass;
-
- public static String IntroduceFactory_constructorInEnum;
-
- public static String IntroduceFactory_createChanges;
-
- public static String IntroduceFactory_descriptor_description;
-
- public static String IntroduceFactory_duplicateMethodName;
-
- public static String IntroduceFactory_examiningSelection;
-
- public static String IntroduceFactory_name;
-
- public static String IntroduceFactory_noASTNodeForConstructorSearchHit;
-
- public static String IntroduceFactory_noBindingForSelectedConstructor;
-
- public static String IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl;
-
- public static String IntroduceFactory_noSuchClass;
-
- public static String IntroduceFactory_notAConstructorInvocation;
-
- public static String IntroduceFactory_protectConstructor;
-
- public static String IntroduceFactory_replaceCalls;
-
- public static String IntroduceFactory_syntaxError;
-
- public static String IntroduceFactory_unableToResolveConstructorBinding;
-
- public static String IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit;
-
- public static String IntroduceFactory_unexpectedInitializerNodeType;
-
- public static String IntroduceFactory_unsupportedNestedTypes;
-
- public static String IntroduceFactoryRefactoring_declare_private;
-
- public static String IntroduceFactoryRefactoring_descriptor_description_short;
-
- public static String IntroduceFactoryRefactoring_factory_pattern;
-
- public static String IntroduceFactoryRefactoring_original_pattern;
-
- public static String IntroduceFactoryRefactoring_owner_pattern;
-
- public static String IntroduceIndirectionRefactoring_adjusting_visibility;
-
- public static String IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify;
-
- public static String IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found;
-
- public static String IntroduceIndirectionRefactoring_call_warning_static_expression_access;
-
- public static String IntroduceIndirectionRefactoring_call_warning_super_keyword;
-
- public static String IntroduceIndirectionRefactoring_call_warning_type_arguments;
-
- public static String IntroduceIndirectionRefactoring_cannot_create_in_annotation;
-
- public static String IntroduceIndirectionRefactoring_cannot_create_in_binary;
-
- public static String IntroduceIndirectionRefactoring_cannot_create_in_nested_nonstatic;
-
- public static String IntroduceIndirectionRefactoring_cannot_create_in_readonly;
-
- public static String IntroduceIndirectionRefactoring_cannot_create_on_interface;
-
- public static String IntroduceIndirectionRefactoring_cannot_run_without_intermediary_type;
-
- public static String IntroduceIndirectionRefactoring_cannot_update_binary_target_visibility;
-
- public static String IntroduceIndirectionRefactoring_checking_activation;
-
- public static String IntroduceIndirectionRefactoring_checking_conditions;
-
- public static String IntroduceIndirectionRefactoring_class_does_not_exist_error;
-
- public static String IntroduceIndirectionRefactoring_class_not_selected_error;
-
- public static String IntroduceIndirectionRefactoring_could_not_parse_declaring_class_error;
-
- public static String IntroduceIndirectionRefactoring_declaring_pattern;
-
- public static String IntroduceIndirectionRefactoring_descriptor_description;
-
- public static String IntroduceIndirectionRefactoring_descriptor_description_short;
-
- public static String IntroduceIndirectionRefactoring_duplicate_method_name_in_declaring_class_error;
-
- public static String IntroduceIndirectionRefactoring_group_description_create_new_method;
-
- public static String IntroduceIndirectionRefactoring_group_description_replace_call;
-
- public static String IntroduceIndirectionRefactoring_introduce_indirection;
-
- public static String IntroduceIndirectionRefactoring_introduce_indirection_name;
-
- public static String IntroduceIndirectionRefactoring_looking_for_references;
-
- public static String IntroduceIndirectionRefactoring_method_pattern;
-
- public static String IntroduceIndirectionRefactoring_not_available_for_constructors;
-
- public static String IntroduceIndirectionRefactoring_not_available_for_local_or_anonymous_types;
-
- public static String IntroduceIndirectionRefactoring_not_available_on_annotation;
-
- public static String IntroduceIndirectionRefactoring_not_available_on_this_selection;
-
- public static String IntroduceIndirectionRefactoring_open_hierarchy_error;
-
- public static String IntroduceIndirectionRefactoring_original_pattern;
-
- public static String IntroduceIndirectionRefactoring_unable_determine_declaring_type;
-
- public static String IntroduceParameterRefactoring_cannot_introduce;
-
- public static String IntroduceParameterRefactoring_descriptor_description;
-
- public static String IntroduceParameterRefactoring_descriptor_description_short;
-
- public static String IntroduceParameterRefactoring_expression_in_method;
-
- public static String IntroduceParameterRefactoring_expression_pattern;
-
- public static String IntroduceParameterRefactoring_name;
-
- public static String IntroduceParameterRefactoring_no_binding;
-
- public static String IntroduceParameterRefactoring_no_void;
-
- public static String IntroduceParameterRefactoring_original_pattern;
-
- public static String IntroduceParameterRefactoring_parameter_pattern;
-
- public static String IntroduceParameterRefactoring_replace;
-
- public static String IntroduceParameterRefactoring_select;
-
- public static String IntroduceParameterRefactoring_syntax_error;
-
- public static String JavaCopyProcessor_changeName;
-
- public static String JavaCopyProcessor_processorName;
-
- public static String JavaDeleteProcessor_confirm_linked_folder_delete;
-
- public static String JavaDeleteProcessor_creating_change;
-
- public static String JavaDeleteProcessor_delete_accessors;
-
- public static String JavaDeleteProcessor_delete_linked_folder_question;
-
- public static String JavaDeleteProcessor_delete_subpackages;
-
- public static String JavaDeleteProcessor_description_plural;
-
- public static String JavaDeleteProcessor_description_singular;
-
- public static String JavaDeleteProcessor_header;
-
- public static String JavaDeleteProcessor_project_pattern;
-
- public static String JavaDeleteProcessor_unsaved_changes;
-
- public static String JavaDeleteProcessor_workspace;
-
- public static String JavaElementUtil_initializer;
-
- public static String JavaMoveProcessor_change_name;
-
- public static String JavaRefactoringDescriptor_inferred_setting_pattern;
-
- public static String JavaRefactoringDescriptor_initialization_error;
-
- public static String JavaRefactoringDescriptor_keep_original;
-
- public static String JavaRefactoringDescriptor_keep_original_deprecated;
-
- public static String JavaRefactoringDescriptor_not_available;
-
- public static String JavaRefactoringDescriptor_original_element_pattern;
-
- public static String JavaRefactoringDescriptor_original_elements;
-
- public static String JavaRefactoringDescriptor_qualified_names;
-
- public static String JavaRefactoringDescriptor_qualified_names_pattern;
-
- public static String JavaRefactoringDescriptor_rename_similar;
-
- public static String JavaRefactoringDescriptor_rename_similar_embedded;
-
- public static String JavaRefactoringDescriptor_rename_similar_suffix;
-
- public static String JavaRefactoringDescriptor_renamed_element_pattern;
-
- public static String JavaRefactoringDescriptor_textual_occurrences;
-
- public static String JavaRefactoringDescriptor_update_references;
-
- public static String JavaRefactoringDescriptorComment_destination_pattern;
-
- public static String JavaRefactoringDescriptorComment_element_delimiter;
-
- public static String JavaRefactoringDescriptorComment_original_project;
-
- public static String JavaRefactoringDescriptorComment_textual_move_only;
-
- public static String LocalTypeAnalyzer_local_type_from_outside;
-
- public static String LocalTypeAnalyzer_local_type_referenced_outside;
-
- public static String LoggedCreateTargetChange_change_name;
-
- public static String MemberCheckUtil_field_exists;
-
- public static String MemberCheckUtil_same_param_count;
-
- public static String MemberCheckUtil_signature_exists;
-
- public static String MemberCheckUtil_type_name_conflict0;
-
- public static String MemberCheckUtil_type_name_conflict1;
-
- public static String MemberCheckUtil_type_name_conflict2;
-
- public static String MemberCheckUtil_type_name_conflict3;
-
- public static String MemberCheckUtil_type_name_conflict4;
-
- public static String MemberVisibilityAdjustor_adjusting;
-
- public static String MemberVisibilityAdjustor_adjustments_description;
-
- public static String MemberVisibilityAdjustor_adjustments_name;
-
- public static String MemberVisibilityAdjustor_binary_outgoing_project;
-
- public static String MemberVisibilityAdjustor_binary_outgoing_resource;
-
- public static String MemberVisibilityAdjustor_change_visibility;
-
- public static String MemberVisibilityAdjustor_change_visibility_default;
-
- public static String MemberVisibilityAdjustor_change_visibility_field_warning;
-
- public static String MemberVisibilityAdjustor_change_visibility_method_warning;
-
- public static String MemberVisibilityAdjustor_change_visibility_private;
-
- public static String MemberVisibilityAdjustor_change_visibility_protected;
-
- public static String MemberVisibilityAdjustor_change_visibility_public;
-
- public static String MemberVisibilityAdjustor_change_visibility_type_warning;
-
- public static String MemberVisibilityAdjustor_checking;
-
- public static String MethodChecks_implements;
-
- public static String MethodChecks_overrides;
-
- public static String MoveCompilationUnitChange_default_package;
-
- public static String MoveCompilationUnitChange_name;
-
- public static String MoveCuUpdateCreator_searching;
-
- public static String MoveCuUpdateCreator_update_imports;
-
- public static String MoveCuUpdateCreator_update_references;
-
- public static String MoveInnerToTopRefactoring_already_declared;
-
- public static String MoveInnerToTopRefactoring_change_label;
-
- public static String MoveInnerToTopRefactoring_change_qualifier;
-
- public static String MoveInnerToTopRefactoring_change_visibility;
-
- public static String MoveInnerToTopRefactoring_change_visibility_constructor_warning;
-
- public static String MoveInnerToTopRefactoring_change_visibility_field_warning;
-
- public static String MoveInnerToTopRefactoring_change_visibility_method_warning;
-
- public static String MoveInnerToTopRefactoring_change_visibility_type_warning;
-
- public static String MoveInnerToTopRefactoring_compilation_Unit_exists;
-
- public static String MoveInnerToTopRefactoring_creating_change;
-
- public static String MoveInnerToTopRefactoring_creating_preview;
-
- public static String MoveInnerToTopRefactoring_declare_final;
-
- public static String MoveInnerToTopRefactoring_descriptor_description;
-
- public static String MoveInnerToTopRefactoring_descriptor_description_short;
-
- public static String MoveInnerToTopRefactoring_field_pattern;
-
- public static String MoveInnerToTopRefactoring_move_to_Top;
-
- public static String MoveInnerToTopRefactoring_name;
-
- public static String MoveInnerToTopRefactoring_name_used;
-
- public static String MoveInnerToTopRefactoring_names_start_lowercase;
-
- public static String MoveInnerToTopRefactoring_original_pattern;
-
- public static String MoveInnerToTopRefactoring_parameter_pattern;
-
- public static String MoveInnerToTopRefactoring_type_exists;
-
- public static String MoveInnerToTopRefactoring_update_constructor_reference;
-
- public static String MoveInnerToTopRefactoring_update_type_reference;
-
- public static String MoveInstanceMethodProcessor_add_moved_method;
-
- public static String MoveInstanceMethodProcessor_cannot_be_moved;
-
- public static String MoveInstanceMethodProcessor_checking;
-
- public static String MoveInstanceMethodProcessor_creating;
-
- public static String MoveInstanceMethodProcessor_deprecate_delegator_message;
-
- public static String MoveInstanceMethodProcessor_deprecate_delegator_method;
-
- public static String MoveInstanceMethodProcessor_descriptor_description;
-
- public static String MoveInstanceMethodProcessor_descriptor_description_short;
-
- public static String MoveInstanceMethodProcessor_inline_binary_project;
-
- public static String MoveInstanceMethodProcessor_inline_binary_resource;
-
- public static String MoveInstanceMethodProcessor_inline_inaccurate;
-
- public static String MoveInstanceMethodProcessor_inline_method_invocation;
-
- public static String MoveInstanceMethodProcessor_inline_overridden;
-
- public static String MoveInstanceMethodProcessor_javadoc_binary_project;
-
- public static String MoveInstanceMethodProcessor_javadoc_binary_resource;
-
- public static String MoveInstanceMethodProcessor_method_already_exists;
-
- public static String MoveInstanceMethodProcessor_method_name_pattern;
-
- public static String MoveInstanceMethodProcessor_method_type_clash;
-
- public static String MoveInstanceMethodProcessor_moved_element_pattern;
-
- public static String MoveInstanceMethodProcessor_name;
-
- public static String MoveInstanceMethodProcessor_no_annotation;
-
- public static String MoveInstanceMethodProcessor_no_binary;
-
- public static String MoveInstanceMethodProcessor_no_constructors;
-
- public static String MoveInstanceMethodProcessor_no_generic_targets;
-
- public static String MoveInstanceMethodProcessor_no_interface;
-
- public static String MoveInstanceMethodProcessor_no_native_methods;
-
- public static String MoveInstanceMethodProcessor_no_null_argument;
-
- public static String MoveInstanceMethodProcessor_no_resolved_target;
-
- public static String MoveInstanceMethodProcessor_no_static_methods;
-
- public static String MoveInstanceMethodProcessor_no_synchronized_methods;
-
- public static String MoveInstanceMethodProcessor_no_type_variables;
-
- public static String MoveInstanceMethodProcessor_parameter_name_pattern;
-
- public static String MoveInstanceMethodProcessor_potentially_recursive;
-
- public static String MoveInstanceMethodProcessor_present_type_parameter_warning;
-
- public static String MoveInstanceMethodProcessor_refers_enclosing_instances;
-
- public static String MoveInstanceMethodProcessor_remove_original_method;
-
- public static String MoveInstanceMethodProcessor_replace_body_with_delegation;
-
- public static String MoveInstanceMethodProcessor_single_implementation;
-
- public static String MoveInstanceMethodProcessor_target_element_pattern;
-
- public static String MoveInstanceMethodProcessor_target_name_already_used;
-
- public static String MoveInstanceMethodProcessor_this_reference;
-
- public static String MoveInstanceMethodProcessor_uses_super;
-
- public static String MoveInstanceMethodRefactoring_name;
-
- public static String MoveMembersRefactoring_accessed_field;
-
- public static String MoveMembersRefactoring_accessed_method;
-
- public static String MoveMembersRefactoring_accessed_type;
-
- public static String MoveMembersRefactoring_addMembers;
-
- public static String MoveMembersRefactoring_binary;
-
- public static String MoveMembersRefactoring_check_availability;
-
- public static String MoveMembersRefactoring_checking;
-
- public static String MoveMembersRefactoring_compile_errors;
-
- public static String MoveMembersRefactoring_creating;
-
- public static String MoveMembersRefactoring_deleteMembers;
-
- public static String MoveMembersRefactoring_dest_binary;
-
- public static String MoveMembersRefactoring_inside;
-
- public static String MoveMembersRefactoring_move_members;
-
- public static String MoveMembersRefactoring_Move_Members;
-
- public static String MoveMembersRefactoring_moved_field;
-
- public static String MoveMembersRefactoring_moved_method;
-
- public static String MoveMembersRefactoring_moved_type;
-
- public static String MoveMembersRefactoring_multi_var_fields;
-
- public static String MoveMembersRefactoring_native;
-
- public static String MoveMembersRefactoring_not_exist;
-
- public static String MoveMembersRefactoring_not_found;
-
- public static String MoveMembersRefactoring_Object;
-
- public static String MoveMembersRefactoring_only_public_static;
-
- public static String MoveMembersRefactoring_read_only;
-
- public static String MoveMembersRefactoring_referenceUpdate;
-
- public static String MoveMembersRefactoring_same;
-
- public static String MoveMembersRefactoring_static_declaration;
-
- public static String MovePackageChange_move;
-
- public static String MovePackageFragmentRootChange_move;
-
- public static String MoveRefactoring_0;
-
- public static String MoveRefactoring_reorganize_elements;
-
- public static String MoveRefactoring_scanning_qualified_names;
-
- public static String MoveResourceChange_move;
-
- public static String MoveStaticMemberAnalyzer_nonStatic;
-
- public static String MoveStaticMembersProcessor_description_descriptor_short_multi;
-
- public static String MoveStaticMembersProcessor_descriptor_description_multi;
-
- public static String MoveStaticMembersProcessor_descriptor_description_single;
-
- public static String MoveStaticMembersProcessor_target_element_pattern;
-
- public static String MultiStateCompilationUnitChange_name_pattern;
-
- public static String OverwriteHelper_0;
-
- public static String OverwriteHelper_1;
-
- public static String OverwriteHelper_2;
-
- public static String OverwriteHelper_3;
-
- public static String ProcessorBasedRefactoring_error_unsupported_initialization;
-
- public static String PromoteTempToFieldRefactoring_cannot_promote;
-
- public static String PromoteTempToFieldRefactoring_declare_final;
-
- public static String PromoteTempToFieldRefactoring_declare_final_static;
-
- public static String PromoteTempToFieldRefactoring_declare_static;
-
- public static String PromoteTempToFieldRefactoring_default_visibility;
-
- public static String PromoteTempToFieldRefactoring_descriptor_description;
-
- public static String PromoteTempToFieldRefactoring_descriptor_description_short;
-
- public static String PromoteTempToFieldRefactoring_editName;
-
- public static String PromoteTempToFieldRefactoring_exceptions;
-
- public static String PromoteTempToFieldRefactoring_field_pattern;
-
- public static String PromoteTempToFieldRefactoring_initialize_constructor;
-
- public static String PromoteTempToFieldRefactoring_initialize_declaration;
-
- public static String PromoteTempToFieldRefactoring_initialize_method;
-
- public static String PromoteTempToFieldRefactoring_method_parameters;
-
- public static String PromoteTempToFieldRefactoring_name;
-
- public static String PromoteTempToFieldRefactoring_Name_conflict;
-
- public static String PromoteTempToFieldRefactoring_Name_conflict_with_field;
-
- public static String PromoteTempToFieldRefactoring_only_declared_in_methods;
-
- public static String PromoteTempToFieldRefactoring_original_pattern;
-
- public static String PromoteTempToFieldRefactoring_select_declaration;
-
- public static String PromoteTempToFieldRefactoring_uses_type_declared_locally;
-
- public static String PromoteTempToFieldRefactoring_uses_types_declared_locally;
-
- public static String PromoteTempToFieldRefactoring_visibility_pattern;
-
- public static String PullUpRefactoring_add_abstract_method;
-
- public static String PullUpRefactoring_add_method_stub;
-
- public static String PullUpRefactoring_add_override_annotation;
-
- public static String PullUpRefactoring_calculating_required;
-
- public static String PullUpRefactoring_category_description;
-
- public static String PullUpRefactoring_category_name;
-
- public static String PullUpRefactoring_checking;
-
- public static String PullUpRefactoring_checking_referenced_elements;
-
- public static String PullUpRefactoring_descriptor_description;
-
- public static String PullUpRefactoring_descriptor_description_full;
-
- public static String PullUpRefactoring_descriptor_description_short;
-
- public static String PullUpRefactoring_descriptor_description_short_multiple;
-
- public static String PullUpRefactoring_different_field_type;
-
- public static String PullUpRefactoring_different_method_return_type;
-
- public static String PullUpRefactoring_field_cannot_be_accessed;
-
- public static String PullUpRefactoring_Field_declared_in_class;
-
- public static String PullUpRefactoring_field_not_accessible;
-
- public static String PullUpRefactoring_final_fields;
-
- public static String PullUpRefactoring_incompatible_langauge_constructs;
-
- public static String PullUpRefactoring_incompatible_language_constructs1;
-
- public static String PullUpRefactoring_lower_default_visibility;
-
- public static String PullUpRefactoring_lower_protected_visibility;
-
- public static String PullUpRefactoring_make_target_abstract;
-
- public static String PullUpRefactoring_method_cannot_be_accessed;
-
- public static String PullUpRefactoring_Method_declared_in_class;
-
- public static String PullUpRefactoring_method_not_accessible;
-
- public static String PullUpRefactoring_moving_static_method_to_interface;
-
- public static String PullUPRefactoring_no_all_binary;
-
- public static String PullUpRefactoring_no_java_lang_Object;
-
- public static String PullUpRefactoring_non_final_pull_up_to_interface;
-
- public static String PullUPRefactoring_not_java_lang_object;
-
- public static String PullUpRefactoring_not_this_type;
-
- public static String PullUpRefactoring_Pull_Up;
-
- public static String PullUpRefactoring_Type_declared_in_class;
-
- public static String PullUpRefactoring_type_not_accessible;
-
- public static String PullUpRefactoring_Type_variable_not_available;
-
- public static String PullUpRefactoring_Type_variable2_not_available;
-
- public static String PullUpRefactoring_Type_variable3_not_available;
-
- public static String PullUpRefactoring_Type_variables_not_available;
-
- public static String PushDownRefactoring_calculating_required;
-
- public static String PushDownRefactoring_category_description;
-
- public static String PushDownRefactoring_category_name;
-
- public static String PushDownRefactoring_change_name;
-
- public static String PushDownRefactoring_check_references;
-
- public static String PushDownRefactoring_checking;
-
- public static String PushDownRefactoring_descriptor_description;
-
- public static String PushDownRefactoring_descriptor_description_full;
-
- public static String PushDownRefactoring_descriptor_description_short;
-
- public static String PushDownRefactoring_descriptor_description_short_multi;
-
- public static String PushDownRefactoring_field_not_accessible;
-
- public static String PushDownRefactoring_make_abstract;
-
- public static String PushDownRefactoring_method_not_accessible;
-
- public static String PushDownRefactoring_name;
-
- public static String PushDownRefactoring_no_subclasses;
-
- public static String PushDownRefactoring_pushed_members_pattern;
-
- public static String PushDownRefactoring_referenced;
-
- public static String PushDownRefactoring_type_not_accessible;
-
- public static String QualifiedNameFinder_qualifiedNames_description;
-
- public static String QualifiedNameFinder_qualifiedNames_name;
-
- public static String QualifiedNameFinder_update_name;
-
- public static String QualifiedNameSearchResult_change_name;
-
- public static String ReadOnlyResourceFinder_0;
-
- public static String ReadOnlyResourceFinder_1;
-
- public static String ReadOnlyResourceFinder_2;
-
- public static String ReadOnlyResourceFinder_3;
-
- public static String Refactoring_binary;
-
- public static String Refactoring_not_in_model;
-
- public static String Refactoring_read_only;
-
- public static String Refactoring_unknown_structure;
-
- public static String RefactoringAnalyzeUtil_name_collision;
-
- public static String RefactoringSearchEngine_binary_match_grouped;
-
- public static String RefactoringSearchEngine_binary_match_ungrouped;
-
- public static String RefactoringSearchEngine_inaccurate_match;
-
- public static String RefactoringSearchEngine_non_cu_matches;
-
- public static String RefactoringSearchEngine_potential_matches;
-
- public static String RefactoringSearchEngine_searching_occurrences;
-
- public static String RefactoringSearchEngine_searching_referenced_fields;
-
- public static String RefactoringSearchEngine_searching_referenced_methods;
-
- public static String RefactoringSearchEngine_searching_referenced_types;
-
- public static String RenameAnalyzeUtil_reference_shadowed;
-
- public static String RenameAnalyzeUtil_shadows;
-
- public static String RenameCompilationUnitChange_descriptor_description;
-
- public static String RenameCompilationUnitChange_descriptor_description_short;
-
- public static String RenameCompilationUnitChange_name;
-
- public static String RenameCompilationUnitRefactoring_name;
-
- public static String RenameCompilationUnitRefactoring_not_parsed;
-
- public static String RenameCompilationUnitRefactoring_not_parsed_1;
-
- public static String RenameCompilationUnitRefactoring_same_name;
-
- public static String RenameEnumConstProcessor_change_name;
-
- public static String RenameEnumConstProcessor_descriptor_description;
-
- public static String RenameEnumConstProcessor_descriptor_description_short;
-
- public static String RenameEnumConstRefactoring_another_name;
-
- public static String RenameEnumConstRefactoring_const_already_defined;
-
- public static String RenameEnumConstRefactoring_convention;
-
- public static String RenameEnumConstRefactoring_name;
-
- public static String RenameFieldProcessor_descriptor_description;
-
- public static String RenameFieldRefactoring_already_exists;
-
- public static String RenameFieldRefactoring_another_name;
-
- public static String RenameFieldRefactoring_another_name2;
-
- public static String RenameFieldRefactoring_change_name;
-
- public static String RenameFieldRefactoring_checking;
-
- public static String RenameFieldRefactoring_declared_in_supertype;
-
- public static String RenameFieldRefactoring_deleted;
-
- public static String RenameFieldRefactoring_descriptor_description_short;
-
- public static String RenameFieldRefactoring_field_already_defined;
-
- public static String RenameFieldRefactoring_field_already_defined2;
-
- public static String RenameFieldRefactoring_hiding;
-
- public static String RenameFieldRefactoring_hiding2;
-
- public static String RenameFieldRefactoring_name;
-
- public static String RenameFieldRefactoring_overridden;
-
- public static String RenameFieldRefactoring_overridden_or_overrides;
-
- public static String RenameFieldRefactoring_searching;
-
- public static String RenameFieldRefactoring_setting_rename_getter;
-
- public static String RenameFieldRefactoring_setting_rename_settter;
-
- public static String RenameFieldRefactoring_should_start_lowercase;
-
- public static String RenameFieldRefactoring_should_start_lowercase2;
-
- public static String RenameFieldRefactoring_Update_field_declaration;
-
- public static String RenameFieldRefactoring_Update_field_reference;
-
- public static String RenameFieldRefactoring_Update_getter_occurrence;
-
- public static String RenameFieldRefactoring_Update_setter_occurrence;
-
- public static String RenameJavaProjectChange_descriptor_description;
-
- public static String RenameJavaProjectChange_rename;
-
- public static String RenameJavaProjectChange_update;
-
- public static String RenameJavaProjectProcessor_descriptor_description_short;
-
- public static String RenameJavaProjectProcessor_folder_already_exists;
-
- public static String RenameJavaProjectRefactoring_already_exists;
-
- public static String RenameJavaProjectRefactoring_read_only;
-
- public static String RenameJavaProjectRefactoring_rename;
-
- public static String RenameLocalVariableProcessor_descriptor_description;
-
- public static String RenameLocalVariableProcessor_descriptor_description_short;
-
- public static String RenameMethodInInterfaceRefactoring_already_defined;
-
- public static String RenameMethodInInterfaceRefactoring_special_case;
-
- public static String RenameMethodProcessor_change_name;
-
- public static String RenameMethodProcessor_descriptor_description;
-
- public static String RenameMethodProcessor_descriptor_description_short;
-
- public static String RenameMethodProcessor_is_binary;
-
- public static String RenameMethodRefactoring_deleted;
-
- public static String RenameMethodRefactoring_name;
-
- public static String RenameMethodRefactoring_no_binary;
-
- public static String RenameMethodRefactoring_no_native;
-
- public static String RenameMethodRefactoring_no_native_1;
-
- public static String RenameMethodRefactoring_no_read_only;
-
- public static String RenameMethodRefactoring_not_in_model;
-
- public static String RenameMethodRefactoring_same_name;
-
- public static String RenameMethodRefactoring_same_name2;
-
- public static String RenameMethodRefactoring_taskName_checkingPreconditions;
-
- public static String RenameMethodRefactoring_taskName_searchingForReferences;
-
- public static String RenameMethodRefactoring_update_declaration;
-
- public static String RenameMethodRefactoring_update_occurrence;
-
- public static String RenamePackageChange_checking_change;
-
- public static String RenamePackageChange_name;
-
- public static String RenamePackageChange_name_with_subpackages;
-
- public static String RenamePackageProcessor_descriptor_description;
-
- public static String RenamePackageProcessor_descriptor_description_short;
-
- public static String RenamePackageProcessor_rename_subpackages;
-
- public static String RenamePackageRefactoring_aleady_exists;
-
- public static String RenamePackageRefactoring_another_name;
-
- public static String RenamePackageRefactoring_change_name;
-
- public static String RenamePackageRefactoring_checking;
-
- public static String RenamePackageRefactoring_contains_type;
-
- public static String RenamePackageRefactoring_creating_change;
-
- public static String RenamePackageRefactoring_name;
-
- public static String RenamePackageRefactoring_package_exists;
-
- public static String RenamePackageRefactoring_Packagered_only;
-
- public static String RenamePackageRefactoring_resource_read_only;
-
- public static String RenamePackageRefactoring_searching;
-
- public static String RenamePackageRefactoring_searching_text;
-
- public static String RenamePackageRefactoring_update_imports;
-
- public static String RenamePackageRefactoring_update_reference;
-
- public static String RenamePrivateMethodRefactoring_hierarchy_defines;
-
- public static String RenamePrivateMethodRefactoring_hierarchy_defines2;
-
- public static String RenamePrivateMethodRefactoring_update;
-
- public static String RenameResourceChange_descriptor_description;
-
- public static String RenameResourceChange_descriptor_description_short;
-
- public static String RenameResourceChange_does_not_exist;
-
- public static String RenameResourceChange_name;
-
- public static String RenameResourceChange_rename_resource;
-
- public static String RenameResourceProcessor_name;
-
- public static String RenameResourceRefactoring_alread_exists;
-
- public static String RenameResourceRefactoring_Internal_Error;
-
- public static String RenameResourceRefactoring_invalidName;
-
- public static String RenameSourceFolderChange_descriptor_description;
-
- public static String RenameSourceFolderChange_descriptor_description_short;
-
- public static String RenameSourceFolderChange_rename;
-
- public static String RenameSourceFolderChange_rename_archive;
-
- public static String RenameSourceFolderChange_rename_external;
-
- public static String RenameSourceFolderChange_rename_linked;
-
- public static String RenameSourceFolderRefactoring_alread_exists;
-
- public static String RenameSourceFolderRefactoring_already_exists;
-
- public static String RenameSourceFolderRefactoring_blank;
-
- public static String RenameSourceFolderRefactoring_invalid_name;
-
- public static String RenameSourceFolderRefactoring_rename;
-
- public static String RenameTempRefactoring_changeName;
-
- public static String RenameTempRefactoring_lowercase;
-
- public static String RenameTempRefactoring_lowercase2;
-
- public static String RenameTempRefactoring_must_select_local;
-
- public static String RenameTempRefactoring_only_in_methods_and_initializers;
-
- public static String RenameTempRefactoring_rename;
-
- public static String RenameTypeParameterProcessor_change_name;
-
- public static String RenameTypeParameterProcessor_descriptor_description;
-
- public static String RenameTypeParameterProcessor_descriptor_description_short;
-
- public static String RenameTypeParameterProcessor_name;
-
- public static String RenameTypeParameterRefactoring_another_name;
-
- public static String RenameTypeParameterRefactoring_checking;
-
- public static String RenameTypeParameterRefactoring_class_type_parameter_already_defined;
-
- public static String RenameTypeParameterRefactoring_deleted;
-
- public static String RenameTypeParameterRefactoring_method_type_parameter_already_defined;
-
- public static String RenameTypeParameterRefactoring_searching;
-
- public static String RenameTypeParameterRefactoring_should_start_lowercase;
-
- public static String RenameTypeParameterRefactoring_type_parameter_inner_class_clash;
-
- public static String RenameTypeParameterRefactoring_update_type_parameter_declaration;
-
- public static String RenameTypeParameterRefactoring_update_type_parameter_reference;
-
- public static String RenameTypeProcessor_cannot_rename_fields_same_new_name;
-
- public static String RenameTypeProcessor_cannot_rename_locals_same_new_name;
-
- public static String RenameTypeProcessor_cannot_rename_methods_same_new_name;
-
- public static String RenameTypeProcessor_change_name;
-
- public static String RenameTypeProcessor_changeCategory_fields;
-
- public static String RenameTypeProcessor_changeCategory_fields_description;
-
- public static String RenameTypeProcessor_changeCategory_local_variables;
-
- public static String RenameTypeProcessor_changeCategory_local_variables_description;
-
- public static String RenameTypeProcessor_changeCategory_method;
-
- public static String RenameTypeProcessor_changeCategory_method_description;
-
- public static String RenameTypeProcessor_changeCategory_type;
-
- public static String RenameTypeProcessor_changeCategory_type_description;
-
- public static String RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions;
-
- public static String RenameTypeProcessor_creating_changes;
-
- public static String RenameTypeProcessor_descriptor_description;
-
- public static String RenameTypeProcessor_descriptor_description_short;
-
- public static String RenameTypeProcessor_deselected_method_is_overridden;
-
- public static String RenameTypeProcessor_progress_current_total;
-
- public static String RenameTypeProcessor_renamed_method_is_overridden;
-
- public static String RenameTypeRefactoring_another_type;
-
- public static String RenameTypeRefactoring_checking;
-
- public static String RenameTypeRefactoring_choose_another_name;
-
- public static String RenameTypeRefactoring_creating_change;
-
- public static String RenameTypeRefactoring_does_not_exist;
-
- public static String RenameTypeRefactoring_enclosed;
-
- public static String RenameTypeRefactoring_enclosed_type_native;
-
- public static String RenameTypeRefactoring_encloses;
-
- public static String RenameTypeRefactoring_exists;
-
- public static String RenameTypeRefactoring_imported;
-
- public static String RenameTypeRefactoring_local_type;
-
- public static String RenameTypeRefactoring_member_type;
-
- public static String RenameTypeRefactoring_member_type_exists;
-
- public static String RenameTypeRefactoring_name;
-
- public static String RenameTypeRefactoring_name_conflict1;
-
- public static String RenameTypeRefactoring_rename_constructor;
-
- public static String RenameTypeRefactoring_searching;
-
- public static String RenameTypeRefactoring_searching_text;
-
- public static String RenameTypeRefactoring_update;
-
- public static String RenameTypeRefactoring_update_reference;
-
- public static String RenameTypeRefactoring_will_not_rename;
-
- public static String RenameVirtualMethodRefactoring_hierarchy_declares1;
-
- public static String RenameVirtualMethodRefactoring_hierarchy_declares2;
-
- public static String RenameVirtualMethodRefactoring_requieres_renaming_native;
-
- public static String ReorgPolicy_copy;
-
- public static String ReorgPolicy_copy_package;
-
- public static String ReorgPolicy_copy_source_folder;
-
- public static String ReorgPolicy_move;
-
- public static String ReorgPolicy_move_members;
-
- public static String ReorgPolicy_move_package;
-
- public static String ReorgPolicy_move_source_folder;
-
- public static String ReorgPolicyFactory_archive;
-
- public static String ReorgPolicyFactory_cannot;
-
- public static String ReorgPolicyFactory_cannot_modify;
-
- public static String ReorgPolicyFactory_cannot1;
-
- public static String ReorgPolicyFactory_copy_compilation_unit;
-
- public static String ReorgPolicyFactory_copy_compilation_units;
-
- public static String ReorgPolicyFactory_copy_description_plural;
-
- public static String ReorgPolicyFactory_copy_description_singular;
-
- public static String ReorgPolicyFactory_copy_elements_header;
-
- public static String ReorgPolicyFactory_copy_elements_plural;
-
- public static String ReorgPolicyFactory_copy_elements_singular;
-
- public static String ReorgPolicyFactory_copy_field;
-
- public static String ReorgPolicyFactory_copy_fields;
-
- public static String ReorgPolicyFactory_copy_file;
-
- public static String ReorgPolicyFactory_copy_files;
-
- public static String ReorgPolicyFactory_copy_folder;
-
- public static String ReorgPolicyFactory_copy_folders;
-
- public static String ReorgPolicyFactory_copy_header;
-
- public static String ReorgPolicyFactory_copy_import;
-
- public static String ReorgPolicyFactory_copy_import_containers;
-
- public static String ReorgPolicyFactory_copy_import_section;
-
- public static String ReorgPolicyFactory_copy_imports;
-
- public static String ReorgPolicyFactory_copy_initializer;
-
- public static String ReorgPolicyFactory_copy_initializers;
-
- public static String ReorgPolicyFactory_copy_method;
-
- public static String ReorgPolicyFactory_copy_methods;
-
- public static String ReorgPolicyFactory_copy_package;
-
- public static String ReorgPolicyFactory_copy_package_declarations;
-
- public static String ReorgPolicyFactory_copy_package_singular;
-
- public static String ReorgPolicyFactory_copy_packages_header;
-
- public static String ReorgPolicyFactory_copy_packages_plural;
-
- public static String ReorgPolicyFactory_copy_roots_header;
-
- public static String ReorgPolicyFactory_copy_roots_plural;
-
- public static String ReorgPolicyFactory_copy_roots_singular;
-
- public static String ReorgPolicyFactory_copy_type;
-
- public static String ReorgPolicyFactory_copy_types;
-
- public static String ReorgPolicyFactory_doesnotexist0;
-
- public static String ReorgPolicyFactory_doesnotexist1;
-
- public static String ReorgPolicyFactory_element2parent;
-
- public static String ReorgPolicyFactory_external;
-
- public static String ReorgPolicyFactory_inaccessible;
-
- public static String ReorgPolicyFactory_inconsistent;
-
- public static String ReorgPolicyFactory_jmodel;
-
- public static String ReorgPolicyFactory_linked;
-
- public static String ReorgPolicyFactory_move_compilation_unit;
-
- public static String ReorgPolicyFactory_move_compilation_units;
-
- public static String ReorgPolicyFactory_move_description_plural;
-
- public static String ReorgPolicyFactory_move_description_singular;
-
- public static String ReorgPolicyFactory_move_elements_header;
-
- public static String ReorgPolicyFactory_move_elements_plural;
-
- public static String ReorgPolicyFactory_move_elements_singular;
-
- public static String ReorgPolicyFactory_move_field;
-
- public static String ReorgPolicyFactory_move_fields;
-
- public static String ReorgPolicyFactory_move_file;
-
- public static String ReorgPolicyFactory_move_files;
-
- public static String ReorgPolicyFactory_move_folder;
-
- public static String ReorgPolicyFactory_move_folders;
-
- public static String ReorgPolicyFactory_move_header;
-
- public static String ReorgPolicyFactory_move_import_containers;
-
- public static String ReorgPolicyFactory_move_import_declaration;
-
- public static String ReorgPolicyFactory_move_import_declarations;
-
- public static String ReorgPolicyFactory_move_import_section;
-
- public static String ReorgPolicyFactory_move_initializer;
-
- public static String ReorgPolicyFactory_move_initializers;
-
- public static String ReorgPolicyFactory_move_method;
-
- public static String ReorgPolicyFactory_move_methods;
-
- public static String ReorgPolicyFactory_move_package_declaration;
-
- public static String ReorgPolicyFactory_move_package_declarations;
-
- public static String ReorgPolicyFactory_move_packages_header;
-
- public static String ReorgPolicyFactory_move_packages_plural;
-
- public static String ReorgPolicyFactory_move_packages_singular;
-
- public static String ReorgPolicyFactory_move_roots_header;
-
- public static String ReorgPolicyFactory_move_roots_plural;
-
- public static String ReorgPolicyFactory_move_roots_singular;
-
- public static String ReorgPolicyFactory_move_type;
-
- public static String ReorgPolicyFactory_move_types;
-
- public static String ReorgPolicyFactory_no_resource;
-
- public static String ReorgPolicyFactory_noCopying;
-
- public static String ReorgPolicyFactory_noMoving;
-
- public static String ReorgPolicyFactory_not_this_resource;
-
- public static String ReorgPolicyFactory_package_decl;
-
- public static String ReorgPolicyFactory_package2parent;
-
- public static String ReorgPolicyFactory_packages;
-
- public static String ReorgPolicyFactory_parent;
-
- public static String ReorgPolicyFactory_phantom;
-
- public static String ReorgPolicyFactory_readonly;
-
- public static String ReorgPolicyFactory_src2nosrc;
-
- public static String ReorgPolicyFactory_src2proj;
-
- public static String ReorgPolicyFactory_src2writable;
-
- public static String ReorgPolicyFactory_structure;
-
- public static String ReorgUtils_0;
-
- public static String ReorgUtils_1;
-
- public static String ReorgUtils_10;
-
- public static String ReorgUtils_11;
-
- public static String ReorgUtils_12;
-
- public static String ReorgUtils_13;
-
- public static String ReorgUtils_14;
-
- public static String ReorgUtils_15;
-
- public static String ReorgUtils_16;
-
- public static String ReorgUtils_17;
-
- public static String ReorgUtils_18;
-
- public static String ReorgUtils_19;
-
- public static String ReorgUtils_2;
-
- public static String ReorgUtils_20;
-
- public static String ReorgUtils_3;
-
- public static String ReorgUtils_4;
-
- public static String ReorgUtils_5;
-
- public static String ReorgUtils_6;
-
- public static String ReorgUtils_7;
-
- public static String ReorgUtils_8;
-
- public static String ReorgUtils_9;
-
- public static String ReplaceInvocationsRefactoring_cannot_find_method_declaration;
-
- public static String ReplaceInvocationsRefactoring_cannot_replace_in_binary;
-
- public static String ReplaceInvocationsRefactoring_change_name;
-
- public static String ReplaceInvocationsRefactoring_descriptor_description;
-
- public static String ReplaceInvocationsRefactoring_descriptor_description_short;
-
- public static String ReplaceInvocationsRefactoring_name;
-
- public static String ReplaceInvocationsRefactoring_original_pattern;
-
- public static String ReplaceInvocationsRefactoring_replace_references;
-
- public static String ReplaceInvocationsRefactoring_select_method_to_apply;
-
- public static String RippleMethodFinder_analizing_hierarchy;
-
- public static String SelfEncapsulateField_AccessAnalyzer_cannot_convert_postfix_expression;
-
- public static String SelfEncapsulateField_AccessAnalyzer_encapsulate_postfix_access;
-
- public static String SelfEncapsulateField_AccessAnalyzer_encapsulate_prefix_access;
-
- public static String SelfEncapsulateField_AccessAnalyzer_encapsulate_read_access;
-
- public static String SelfEncapsulateField_AccessAnalyzer_encapsulate_write_access;
-
- public static String SelfEncapsulateField_add_getter;
-
- public static String SelfEncapsulateField_add_setter;
-
- public static String SelfEncapsulateField_analyzing;
-
- public static String SelfEncapsulateField_cannot_analyze_selected_field;
-
- public static String SelfEncapsulateField_change_visibility;
-
- public static String SelfEncapsulateField_checking_preconditions;
-
- public static String SelfEncapsulateField_compiler_errors_field;
-
- public static String SelfEncapsulateField_compiler_errors_update;
-
- public static String SelfEncapsulateField_create_changes;
-
- public static String SelfEncapsulateField_default_visibility;
-
- public static String SelfEncapsulateField_descriptor_description_short;
-
- public static String SelfEncapsulateField_do_not_use_accessors;
-
- public static String SelfEncapsulateField_generate_comments;
-
- public static String SelfEncapsulateField_getter_pattern;
-
- public static String SelfEncapsulateField_method_exists;
-
- public static String SelfEncapsulateField_name;
-
- public static String SelfEncapsulateField_original_pattern;
-
- public static String SelfEncapsulateField_searching_for_cunits;
-
- public static String SelfEncapsulateField_setter_pattern;
-
- public static String SelfEncapsulateField_type_not_resolveable;
-
- public static String SelfEncapsulateField_use_accessors;
-
- public static String SelfEncapsulateField_visibility_pattern;
-
- public static String SelfEncapsulateFieldRefactoring_descriptor_description;
-
- public static String SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError;
-
- public static String SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field;
-
- public static String SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError;
-
- public static String SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field;
-
- public static String SourceCreationOperation_creating_source_folder;
-
- public static String StatementAnalyzer_beginning_of_selection;
-
- public static String StatementAnalyzer_catch_argument;
-
- public static String StatementAnalyzer_do_body_expression;
-
- public static String StatementAnalyzer_doesNotCover;
-
- public static String StatementAnalyzer_end_of_selection;
-
- public static String StatementAnalyzer_for_expression_updater;
-
- public static String StatementAnalyzer_for_initializer_expression;
-
- public static String StatementAnalyzer_for_updater_body;
-
- public static String StatementAnalyzer_switch_statement;
-
- public static String StatementAnalyzer_synchronized_statement;
-
- public static String StatementAnalyzer_try_statement;
-
- public static String StatementAnalyzer_while_expression_body;
-
- public static String StubCreationOperation_creating_type_stubs;
-
- public static String SuperTypeRefactoringProcessor_category_description;
-
- public static String SuperTypeRefactoringProcessor_category_name;
-
- public static String SuperTypeRefactoringProcessor_creating;
-
- public static String SuperTypeRefactoringProcessor_update_type_occurrence;
-
- public static String SuperTypeRefactoringProcessor_use_in_instanceof_setting;
-
- public static String SuperTypeRefactoringProcessor_user_supertype_setting;
-
- public static String SurroundWithTryCatchAnalyzer_cannotHandleSuper;
-
- public static String SurroundWithTryCatchAnalyzer_cannotHandleThis;
-
- public static String SurroundWithTryCatchAnalyzer_compile_errors;
-
- public static String SurroundWithTryCatchAnalyzer_doesNotContain;
-
- public static String SurroundWithTryCatchAnalyzer_doesNotCover;
-
- public static String SurroundWithTryCatchAnalyzer_noUncaughtExceptions;
-
- public static String SurroundWithTryCatchAnalyzer_onlyStatements;
-
- public static String SurroundWithTryCatchRefactoring_name;
-
- public static String TargetProvider_cannot_local_method_in_binary;
-
- public static String TargetProvider_inaccurate_match;
-
- public static String TargetProvider_method_declaration_not_unique;
-
- public static String TextMatchUpdater_searching;
-
- public static String TextMatchUpdater_textualMatches_description;
-
- public static String TextMatchUpdater_textualMatches_name;
-
- public static String TextMatchUpdater_update;
-
- public static String TypeContextChecker_ambiguous;
-
- public static String TypeContextChecker_couldNotResolveType;
-
- public static String TypeContextChecker_invalid_return_type;
-
- public static String TypeContextChecker_invalid_return_type_syntax;
-
- public static String TypeContextChecker_invalid_type_name;
-
- public static String TypeContextChecker_invalid_type_syntax;
-
- public static String TypeContextChecker_no_vararg_below_50;
-
- public static String TypeContextChecker_not_unique;
-
- public static String TypeContextChecker_parameter_type;
-
- public static String TypeContextChecker_return_type_not_empty;
-
- public static String UndoCompilationUnitChange_no_resource;
-
- public static String UndoDeleteResourceChange_already_exists;
-
- public static String UndoDeleteResourceChange_cannot_restore;
-
- public static String UndoDeleteResourceChange_change_name;
-
- public static String UseSuperTypeProcessor_checking;
-
- public static String UseSuperTypeProcessor_creating;
-
- public static String UseSuperTypeProcessor_descriptor_description;
-
- public static String UseSuperTypeProcessor_descriptor_description_short;
-
- public static String UseSuperTypeProcessor_internal_error;
-
- public static String UseSuperTypeProcessor_name;
-
- public static String UseSuperTypeProcessor_refactored_element_pattern;
-
- public static String UseSupertypeWherePossibleRefactoring_name;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, RefactoringCoreMessages.class);
- }
-
- private RefactoringCoreMessages() {
- // Do not instantiate
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringElementFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringElementFilter.java
deleted file mode 100644
index 869bb6ec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringElementFilter.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- *
- */
-public abstract class RefactoringElementFilter {
-
- /**
- * @param cu the IJavaScriptUnit under test
- * @return <code>true</code> iff the given IJavaScriptUnit should be
- * filtered (i.e., refactorings should not touch the compilation
- * unit)
- */
- public abstract boolean filter(IJavaScriptUnit cu);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringExecutionStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringExecutionStarter.java
deleted file mode 100644
index 4d5e6312..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringExecutionStarter.java
+++ /dev/null
@@ -1,467 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.DeleteRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineConstantRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineTempRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceParameterRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ReplaceInvocationsRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameResourceProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.JavaMoveRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.fix.CleanUpRefactoringWizard;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ChangeSignatureWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ChangeTypeWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ConvertAnonymousToNestedWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ExtractSupertypeWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.InlineConstantWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.InlineTempWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IntroduceFactoryWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IntroduceIndirectionWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IntroduceParameterWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.MoveInnerToTopWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.MoveInstanceMethodWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.MoveMembersWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.PullUpWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.PushDownWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UseSupertypeWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.code.InlineMethodWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.code.ReplaceInvocationsWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.CreateTargetQueries;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.DeleteUserInterfaceManager;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.NewNameQueries;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameUserInterfaceManager;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgCopyWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgMoveWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgQueries;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.sef.SelfEncapsulateFieldWizard;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-import org.eclipse.wst.jsdt.ui.refactoring.RenameSupport;
-
-/**
- * Helper class to run refactorings from action code.
- * <p>
- * This class has been introduced to decouple actions from the refactoring code,
- * in order not to eagerly load refactoring classes during action
- * initialization.
- * </p>
- *
- *
- */
-public final class RefactoringExecutionStarter {
-
- private static RenameSupport createRenameSupport(IJavaScriptElement element, String newName, int flags) throws CoreException {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return RenameSupport.create((IJavaScriptProject) element, newName, flags);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return RenameSupport.create((IPackageFragmentRoot) element, newName);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return RenameSupport.create((IPackageFragment) element, newName, flags);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return RenameSupport.create((IJavaScriptUnit) element, newName, flags);
- case IJavaScriptElement.TYPE:
- return RenameSupport.create((IType) element, newName, flags);
- case IJavaScriptElement.METHOD:
- final IFunction method= (IFunction) element;
- if (method.isConstructor())
- return createRenameSupport(method.getDeclaringType(), newName, flags);
- else
- return RenameSupport.create((IFunction) element, newName, flags);
- case IJavaScriptElement.FIELD:
- return RenameSupport.create((IField) element, newName, flags);
- case IJavaScriptElement.LOCAL_VARIABLE:
- return RenameSupport.create((ILocalVariable) element, newName, flags);
- }
- return null;
- }
-
- public static void startChangeSignatureRefactoring(final IFunction method, final SelectionDispatchAction action, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isChangeSignatureAvailable(method))
- return;
- final ChangeSignatureRefactoring refactoring= new ChangeSignatureRefactoring(method);
- final UserInterfaceStarter starter= new UserInterfaceStarter() {
-
- public final boolean activate(final Refactoring ref, final Shell parent, final int saveMode) throws CoreException {
- final RefactoringStatus status= ref.checkInitialConditions(new NullProgressMonitor());
- if (status.hasFatalError()) {
- final RefactoringStatusEntry entry= status.getEntryMatchingSeverity(RefactoringStatus.FATAL);
- if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) {
-
- String message= entry.getMessage();
- final Object element= entry.getData();
- message= message + RefactoringMessages.RefactoringErrorDialogUtil_okToPerformQuestion;
- if (element != null && MessageDialog.openQuestion(shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, message)) {
-
- final IStructuredSelection selection= new StructuredSelection(element);
- // TODO: should not hijack this
- // ModifiyParametersAction.
- // The action is set up on an editor, but we use it
- // as if it were set up on a ViewPart.
- boolean wasEnabled= action.isEnabled();
- action.selectionChanged(selection);
- if (action.isEnabled()) {
- action.run(selection);
- } else {
- MessageDialog.openInformation(shell, ActionMessages.ModifyParameterAction_problem_title, ActionMessages.ModifyParameterAction_problem_message);
- }
- action.setEnabled(wasEnabled);
- }
- return false;
- }
- }
- return super.activate(ref, parent, saveMode);
- }
- };
- starter.initialize(new ChangeSignatureWizard(refactoring));
- try {
- starter.activate(refactoring, shell, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.RefactoringStarter_unexpected_exception);
- }
- }
-
- public static void startChangeTypeRefactoring(final IJavaScriptUnit unit, final Shell shell, final int offset, final int length) throws JavaScriptModelException {
- final ChangeTypeRefactoring refactoring= new ChangeTypeRefactoring(unit, offset, length);
- new RefactoringStarter().activate(refactoring, new ChangeTypeWizard(refactoring), shell, RefactoringMessages.ChangeTypeAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startCleanupRefactoring(IJavaScriptUnit[] cus, ICleanUp[] cleanUps, Shell shell, boolean showWizard, String actionName) throws InvocationTargetException, JavaScriptModelException {
- final CleanUpRefactoring refactoring= new CleanUpRefactoring(actionName);
- for (int i= 0; i < cus.length; i++) {
- refactoring.addCompilationUnit(cus[i]);
- }
-
- if (!showWizard) {
- for (int i= 0; i < cleanUps.length; i++) {
- refactoring.addCleanUp(cleanUps[i]);
- }
-
- IRunnableContext context;
- if (refactoring.getCompilationUnits().length > 1) {
- context= new ProgressMonitorDialog(shell);
- } else {
- context= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- }
-
- RefactoringExecutionHelper helper= new RefactoringExecutionHelper(refactoring, IStatus.INFO, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES, shell, context);
- try {
- helper.perform(true, true);
- } catch (InterruptedException e) {
- }
- } else {
- CleanUpRefactoringWizard refactoringWizard= new CleanUpRefactoringWizard(refactoring, RefactoringWizard.WIZARD_BASED_USER_INTERFACE);
- RefactoringStarter starter= new RefactoringStarter();
- starter.activate(refactoring, refactoringWizard, shell, actionName, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
- }
-
- public static void startConvertAnonymousRefactoring(final IJavaScriptUnit unit, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final ConvertAnonymousToNestedRefactoring refactoring= new ConvertAnonymousToNestedRefactoring(unit, offset, length);
- new RefactoringStarter().activate(refactoring, new ConvertAnonymousToNestedWizard(refactoring), shell, RefactoringMessages.ConvertAnonymousToNestedAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startCopyRefactoring(IResource[] resources, IJavaScriptElement[] javaElements, Shell shell) throws JavaScriptModelException {
- ICopyPolicy copyPolicy= ReorgPolicyFactory.createCopyPolicy(resources, javaElements);
- if (copyPolicy.canEnable()) {
- JavaCopyProcessor processor= new JavaCopyProcessor(copyPolicy);
- CopyRefactoring refactoring= new JavaCopyRefactoring(processor);
- RefactoringWizard wizard= new ReorgCopyWizard(refactoring);
- processor.setNewNameQueries(new NewNameQueries(wizard));
- processor.setReorgQueries(new ReorgQueries(wizard));
- new RefactoringStarter().activate(refactoring, wizard, shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_NOTHING);
- }
- }
-
- public static void startCutRefactoring(final Object[] elements, final Shell shell) throws CoreException, InterruptedException, InvocationTargetException {
- final JavaDeleteProcessor processor= new JavaDeleteProcessor(elements);
- processor.setSuggestGetterSetterDeletion(false);
- processor.setQueries(new ReorgQueries(shell));
- new RefactoringExecutionHelper(new JavaDeleteRefactoring(processor), RefactoringCore.getConditionCheckingFailedSeverity(), RefactoringSaveHelper.SAVE_NOTHING, shell, new ProgressMonitorDialog(shell)).perform(false, false);
- }
-
- public static void startDeleteRefactoring(final Object[] elements, final Shell shell) throws CoreException {
- final DeleteRefactoring refactoring= new JavaDeleteRefactoring(new JavaDeleteProcessor(elements));
- DeleteUserInterfaceManager.getDefault().getStarter(refactoring).activate(refactoring, shell, RefactoringSaveHelper.SAVE_NOTHING);
- }
-
- public static void startExtractSupertypeRefactoring(final IMember[] members, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isExtractSupertypeAvailable(members))
- return;
- IJavaScriptProject project= null;
- if (members != null && members.length > 0)
- project= members[0].getJavaScriptProject();
- final ExtractSupertypeRefactoring refactoring= new ExtractSupertypeRefactoring(new ExtractSupertypeProcessor(members, JavaPreferencesSettings.getCodeGenerationSettings(project)));
- new RefactoringStarter().activate(refactoring, new ExtractSupertypeWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static boolean startInlineConstantRefactoring(final IJavaScriptUnit unit, final JavaScriptUnit node, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final InlineConstantRefactoring refactoring= new InlineConstantRefactoring(unit, node, offset, length);
- if (! refactoring.checkStaticFinalConstantNameSelected().hasFatalError()) {
- new RefactoringStarter().activate(refactoring, new InlineConstantWizard(refactoring), shell, RefactoringMessages.InlineConstantAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- return true;
- }
- return false;
- }
-
- public static boolean startInlineMethodRefactoring(final ITypeRoot typeRoot, final JavaScriptUnit node, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(typeRoot, node, offset, length);
- if (refactoring != null) {
- new RefactoringStarter().activate(refactoring, new InlineMethodWizard(refactoring), shell, RefactoringMessages.InlineMethodAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- return true;
- }
- return false;
- }
-
- public static boolean startInlineTempRefactoring(final IJavaScriptUnit unit, JavaScriptUnit node, final ITextSelection selection, final Shell shell) throws JavaScriptModelException {
- final InlineTempRefactoring refactoring= new InlineTempRefactoring(unit, node, selection.getOffset(), selection.getLength());
- if (! refactoring.checkIfTempSelected().hasFatalError()) {
- new RefactoringStarter().activate(refactoring, new InlineTempWizard(refactoring), shell, RefactoringMessages.InlineTempAction_inline_temp, RefactoringSaveHelper.SAVE_NOTHING);
- return true;
- }
- return false;
- }
-
- public static void startIntroduceFactoryRefactoring(final IJavaScriptUnit unit, final ITextSelection selection, final Shell shell) throws JavaScriptModelException {
- final IntroduceFactoryRefactoring refactoring= new IntroduceFactoryRefactoring(unit, selection.getOffset(), selection.getLength());
- new RefactoringStarter().activate(refactoring, new IntroduceFactoryWizard(refactoring, RefactoringMessages.IntroduceFactoryAction_use_factory), shell, RefactoringMessages.IntroduceFactoryAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startIntroduceIndirectionRefactoring(final IClassFile file, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final IntroduceIndirectionRefactoring refactoring= new IntroduceIndirectionRefactoring(file, offset, length);
- new RefactoringStarter().activate(refactoring, new IntroduceIndirectionWizard(refactoring, RefactoringMessages.IntroduceIndirectionAction_dialog_title), shell, RefactoringMessages.IntroduceIndirectionAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startIntroduceIndirectionRefactoring(final IJavaScriptUnit unit, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final IntroduceIndirectionRefactoring refactoring= new IntroduceIndirectionRefactoring(unit, offset, length);
- new RefactoringStarter().activate(refactoring, new IntroduceIndirectionWizard(refactoring, RefactoringMessages.IntroduceIndirectionAction_dialog_title), shell, RefactoringMessages.IntroduceIndirectionAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startIntroduceIndirectionRefactoring(final IFunction method, final Shell shell) throws JavaScriptModelException {
- final IntroduceIndirectionRefactoring refactoring= new IntroduceIndirectionRefactoring(method);
- new RefactoringStarter().activate(refactoring, new IntroduceIndirectionWizard(refactoring, RefactoringMessages.IntroduceIndirectionAction_dialog_title), shell, RefactoringMessages.IntroduceIndirectionAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startIntroduceParameter(IJavaScriptUnit unit, int offset, int length, Shell shell) throws JavaScriptModelException {
- final IntroduceParameterRefactoring refactoring= new IntroduceParameterRefactoring(unit, offset, length);
- new RefactoringStarter().activate(refactoring, new IntroduceParameterWizard(refactoring), shell, RefactoringMessages.IntroduceParameterAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startMoveInnerRefactoring(final IType type, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isMoveInnerAvailable(type))
- return;
- final MoveInnerToTopRefactoring refactoring= new MoveInnerToTopRefactoring(type, JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject()));
- new RefactoringStarter().activate(refactoring, new MoveInnerToTopWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startMoveMethodRefactoring(final IFunction method, final Shell shell) throws JavaScriptModelException {
- final MoveInstanceMethodRefactoring refactoring= new MoveInstanceMethodRefactoring(new MoveInstanceMethodProcessor(method, JavaPreferencesSettings.getCodeGenerationSettings(method.getJavaScriptProject())));
- new RefactoringStarter().activate(refactoring, new MoveInstanceMethodWizard(refactoring), shell, RefactoringMessages.MoveInstanceMethodAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startMoveRefactoring(final IResource[] resources, final IJavaScriptElement[] elements, final Shell shell) throws JavaScriptModelException {
- IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, elements);
- if (policy.canEnable()) {
- final JavaMoveProcessor processor= new JavaMoveProcessor(policy);
- final JavaMoveRefactoring refactoring= new JavaMoveRefactoring(processor);
- final RefactoringWizard wizard= new ReorgMoveWizard(refactoring);
- processor.setCreateTargetQueries(new CreateTargetQueries(wizard));
- processor.setReorgQueries(new ReorgQueries(wizard));
- new RefactoringStarter().activate(refactoring, wizard, shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_ALL);
- }
- }
-
- public static void startMoveStaticMembersRefactoring(final IMember[] members, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isMoveStaticAvailable(members))
- return;
- final Set set= new HashSet();
- set.addAll(Arrays.asList(members));
- final IMember[] elements= (IMember[]) set.toArray(new IMember[set.size()]);
- IJavaScriptProject project= null;
- if (elements.length > 0)
- project= elements[0].getJavaScriptProject();
- final JavaMoveRefactoring refactoring= new JavaMoveRefactoring(new MoveStaticMembersProcessor(elements, JavaPreferencesSettings.getCodeGenerationSettings(project)));
- new RefactoringStarter().activate(refactoring, new MoveMembersWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
- }
-
- public static void startPullUpRefactoring(final IMember[] members, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isPullUpAvailable(members))
- return;
- IJavaScriptProject project= null;
- if (members != null && members.length > 0)
- project= members[0].getJavaScriptProject();
- final PullUpRefactoring refactoring= new PullUpRefactoring(new PullUpRefactoringProcessor(members, JavaPreferencesSettings.getCodeGenerationSettings(project)));
- new RefactoringStarter().activate(refactoring, new PullUpWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startPushDownRefactoring(final IMember[] members, final Shell shell) throws JavaScriptModelException {
- if (!RefactoringAvailabilityTester.isPushDownAvailable(members))
- return;
- final PushDownRefactoring refactoring= new PushDownRefactoring(new PushDownRefactoringProcessor(members));
- new RefactoringStarter().activate(refactoring, new PushDownWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startRenameRefactoring(final IJavaScriptElement element, final Shell shell) throws CoreException {
- final RenameSupport support= createRenameSupport(element, null, RenameSupport.UPDATE_REFERENCES);
- if (support != null && support.preCheck().isOK())
- support.openDialog(shell);
- }
-
- public static void startRenameResourceRefactoring(final IResource resource, final Shell shell) throws CoreException {
- final JavaRenameRefactoring refactoring= new JavaRenameRefactoring(new RenameResourceProcessor(resource));
- RenameUserInterfaceManager.getDefault().getStarter(refactoring).activate(refactoring, shell, RefactoringSaveHelper.SAVE_ALL);
- }
-
- public static void startReplaceInvocationsRefactoring(final ITypeRoot typeRoot, final int offset, final int length, final Shell shell) throws JavaScriptModelException {
- final ReplaceInvocationsRefactoring refactoring= new ReplaceInvocationsRefactoring(typeRoot, offset, length);
- new RefactoringStarter().activate(refactoring, new ReplaceInvocationsWizard(refactoring), shell, RefactoringMessages.ReplaceInvocationsAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startReplaceInvocationsRefactoring(final IFunction method, final Shell shell) throws JavaScriptModelException {
- final ReplaceInvocationsRefactoring refactoring= new ReplaceInvocationsRefactoring(method);
- new RefactoringStarter().activate(refactoring, new ReplaceInvocationsWizard(refactoring), shell, RefactoringMessages.ReplaceInvocationsAction_dialog_title, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- public static void startSelfEncapsulateRefactoring(final IField field, final Shell shell) {
- try {
- if (!RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
- return;
- final SelfEncapsulateFieldRefactoring refactoring= new SelfEncapsulateFieldRefactoring(field);
- new RefactoringStarter().activate(refactoring, new SelfEncapsulateFieldWizard(refactoring), shell, "", RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES); //$NON-NLS-1$
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, ActionMessages.SelfEncapsulateFieldAction_dialog_title, ActionMessages.SelfEncapsulateFieldAction_dialog_cannot_perform);
- }
- }
-
- public static void startUseSupertypeRefactoring(final IType type, final Shell shell) throws JavaScriptModelException {
- final UseSuperTypeRefactoring refactoring= new UseSuperTypeRefactoring(new UseSuperTypeProcessor(type));
- new RefactoringStarter().activate(refactoring, new UseSupertypeWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
- }
-
- private RefactoringExecutionStarter() {
- // Not for instantiation
- }
-
-// public static void startIntroduceParameterObject(IJavaScriptUnit unit, int offset, int length, Shell shell) throws CoreException {
-// IJavaScriptElement javaElement= unit.getElementAt(offset);
-// if (javaElement instanceof IFunction) {
-// IFunction method= (IFunction) javaElement;
-// startIntroduceParameterObject(method, shell);
-// }
-// }
-//
-// public static void startIntroduceParameterObject(IFunction method, Shell shell) throws CoreException {
-// RefactoringStatus availability= Checks.checkAvailability(method);
-// if (availability.hasError()){
-// MessageDialog.openError(shell, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_title, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_description);
-// return;
-// }
-// IntroduceParameterObjectRefactoring refactoring= new IntroduceParameterObjectRefactoring(method);
-// final RefactoringStatus status= refactoring.checkInitialConditions(new NullProgressMonitor());
-// if (status.hasFatalError()) {
-// final RefactoringStatusEntry entry= status.getEntryMatchingSeverity(RefactoringStatus.FATAL);
-// if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) {
-//
-// String message= entry.getMessage();
-// final Object element= entry.getData();
-// IFunction superMethod= (IFunction) element;
-// availability= Checks.checkAvailability(superMethod);
-// if (availability.hasError()){
-// MessageDialog.openError(shell, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_title, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_description);
-// return;
-// }
-// message= message + RefactoringMessages.RefactoringErrorDialogUtil_okToPerformQuestion;
-// if (element != null && MessageDialog.openQuestion(shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, message)) {
-// refactoring=new IntroduceParameterObjectRefactoring(superMethod);
-// }
-// else refactoring=null;
-// }
-// }
-// if (refactoring!=null)
-// new RefactoringStarter().activate(refactoring, new IntroduceParameterObjectWizard(refactoring), shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES);
-// }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringScopeFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringScopeFactory.java
deleted file mode 100644
index 9ac1beec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringScopeFactory.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-
-public class RefactoringScopeFactory {
-
- /*
- * Adds to <code> projects </code> IJavaScriptProject objects for all projects directly or indirectly referencing focus. @param projects IJavaProjects will be added to this set
- */
- private static void addReferencingProjects(IJavaScriptProject focus, Set projects) throws JavaScriptModelException {
- IProject[] referencingProjects= focus.getProject().getReferencingProjects();
- for (int i= 0; i < referencingProjects.length; i++) {
- IJavaScriptProject candidate= JavaScriptCore.create(referencingProjects[i]);
- if (candidate == null || projects.contains(candidate) || !candidate.exists())
- continue; // break cycle
- IIncludePathEntry entry= getReferencingClassPathEntry(candidate, focus);
- if (entry != null) {
- projects.add(candidate);
- if (entry.isExported())
- addReferencingProjects(candidate, projects);
- }
- }
- }
-
- private static void addRelatedReferencing(IJavaScriptProject focus, Set projects) throws CoreException {
- IProject[] referencingProjects= focus.getProject().getReferencingProjects();
- for (int i= 0; i < referencingProjects.length; i++) {
- IJavaScriptProject candidate= JavaScriptCore.create(referencingProjects[i]);
- if (candidate == null || projects.contains(candidate) || !candidate.exists())
- continue; // break cycle
- IIncludePathEntry entry= getReferencingClassPathEntry(candidate, focus);
- if (entry != null) {
- projects.add(candidate);
- if (entry.isExported()) {
- addRelatedReferencing(candidate, projects);
- addRelatedReferenced(candidate, projects);
- }
- }
- }
- }
-
- private static void addRelatedReferenced(IJavaScriptProject focus, Set projects) throws CoreException {
- IProject[] referencedProjects= focus.getProject().getReferencedProjects();
- for (int i= 0; i < referencedProjects.length; i++) {
- IJavaScriptProject candidate= JavaScriptCore.create(referencedProjects[i]);
- if (candidate == null || projects.contains(candidate) || !candidate.exists())
- continue; // break cycle
- IIncludePathEntry entry= getReferencingClassPathEntry(focus, candidate);
- if (entry != null) {
- projects.add(candidate);
- if (entry.isExported()) {
- addRelatedReferenced(candidate, projects);
- addRelatedReferencing(candidate, projects);
- }
- }
- }
- }
-
- /**
- * Creates a new search scope with all compilation units possibly referencing <code>javaElement</code>,
- * considering the visibility of the element.
- *
- * @param javaElement the java element
- * @return the search scope
- * @throws JavaScriptModelException if an error occurs
- */
- public static IJavaScriptSearchScope create(IJavaScriptElement javaElement) throws JavaScriptModelException {
- return RefactoringScopeFactory.create(javaElement, true);
- }
-
- /**
- * Creates a new search scope with all compilation units possibly referencing <code>javaElement</code>.
- *
- * @param javaElement the java element
- * @param considerVisibility consider visibility of javaElement iff <code>true</code>
- * @return the search scope
- * @throws JavaScriptModelException if an error occurs
- */
- public static IJavaScriptSearchScope create(IJavaScriptElement javaElement, boolean considerVisibility) throws JavaScriptModelException {
- if (considerVisibility & javaElement instanceof IMember) {
- IMember member= (IMember) javaElement;
- if (JdtFlags.isPrivate(member)) {
- if (member.getJavaScriptUnit() != null)
- return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member.getJavaScriptUnit()});
- else
- return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member});
- }
- // Removed code that does some optimizations regarding package visible members. The problem is that
- // there can be a package fragment with the same name in a different source folder or project. So we
- // have to treat package visible members like public or protected members.
- }
- return create(javaElement.getJavaScriptProject());
- }
-
- private static IJavaScriptSearchScope create(IJavaScriptProject javaProject) throws JavaScriptModelException {
- return SearchEngine.createJavaSearchScope(getAllScopeElements(javaProject), false);
- }
-
- /**
- * Creates a new search scope comprising <code>members</code>.
- *
- * @param members the members
- * @return the search scope
- * @throws JavaScriptModelException if an error occurs
- */
- public static IJavaScriptSearchScope create(IMember[] members) throws JavaScriptModelException {
- Assert.isTrue(members != null && members.length > 0);
- IMember candidate= members[0];
- int visibility= getVisibility(candidate);
- for (int i= 1; i < members.length; i++) {
- int mv= getVisibility(members[i]);
- if (mv > visibility) {
- visibility= mv;
- candidate= members[i];
- }
- }
- return create(candidate);
- }
-
- /**
- * Creates a new search scope with all projects possibly referenced
- * from the given <code>javaElements</code>.
- *
- * @param javaElements the java elements
- * @return the search scope
- */
- public static IJavaScriptSearchScope createReferencedScope(IJavaScriptElement[] javaElements) {
- Set projects= new HashSet();
- for (int i= 0; i < javaElements.length; i++) {
- projects.add(javaElements[i].getJavaScriptProject());
- }
- IJavaScriptProject[] prj= (IJavaScriptProject[]) projects.toArray(new IJavaScriptProject[projects.size()]);
- return SearchEngine.createJavaSearchScope(prj, true);
- }
-
- /**
- * Creates a new search scope with all projects possibly referenced
- * from the given <code>javaElements</code>.
- *
- * @param javaElements the java elements
- * @param includeMask the include mask
- * @return the search scope
- */
- public static IJavaScriptSearchScope createReferencedScope(IJavaScriptElement[] javaElements, int includeMask) {
- Set projects= new HashSet();
- for (int i= 0; i < javaElements.length; i++) {
- projects.add(javaElements[i].getJavaScriptProject());
- }
- IJavaScriptProject[] prj= (IJavaScriptProject[]) projects.toArray(new IJavaScriptProject[projects.size()]);
- return SearchEngine.createJavaSearchScope(prj, includeMask);
- }
-
- /**
- * Creates a new search scope containing all projects which reference or are referenced by the specified project.
- *
- * @param project the project
- * @param includeMask the include mask
- * @return the search scope
- * @throws CoreException if a referenced project could not be determined
- */
- public static IJavaScriptSearchScope createRelatedProjectsScope(IJavaScriptProject project, int includeMask) throws CoreException {
- IJavaScriptProject[] projects= getRelatedProjects(project);
- return SearchEngine.createJavaSearchScope(projects, includeMask);
- }
-
- private static IJavaScriptElement[] getAllScopeElements(IJavaScriptProject project) throws JavaScriptModelException {
- Collection sourceRoots= getAllSourceRootsInProjects(getReferencingProjects(project));
- return (IPackageFragmentRoot[]) sourceRoots.toArray(new IPackageFragmentRoot[sourceRoots.size()]);
- }
-
- /*
- * @param projects a collection of IJavaScriptProject @return Collection a collection of IPackageFragmentRoot, one element for each packageFragmentRoot which lies within a project in <code> projects </code> .
- */
- private static Collection getAllSourceRootsInProjects(Collection projects) throws JavaScriptModelException {
- List result= new ArrayList();
- for (Iterator it= projects.iterator(); it.hasNext();)
- result.addAll(getSourceRoots((IJavaScriptProject) it.next()));
- return result;
- }
-
- /*
- * Finds, if possible, a classpathEntry in one given project such that this classpath entry references another given project. If more than one entry exists for the referenced project and at least one is exported, then an exported entry will be returned.
- */
- private static IIncludePathEntry getReferencingClassPathEntry(IJavaScriptProject referencingProject, IJavaScriptProject referencedProject) throws JavaScriptModelException {
- IIncludePathEntry result= null;
- IPath path= referencedProject.getProject().getFullPath();
- IIncludePathEntry[] classpath= referencingProject.getResolvedIncludepath(true);
- for (int i= 0; i < classpath.length; i++) {
- IIncludePathEntry entry= classpath[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT && path.equals(entry.getPath())) {
- if (entry.isExported())
- return entry;
- // Consider it as a candidate. May be there is another entry that is
- // exported.
- result= entry;
- }
- }
- return result;
- }
-
- private static IJavaScriptProject[] getRelatedProjects(IJavaScriptProject focus) throws CoreException {
- final Set projects= new HashSet();
-
- addRelatedReferencing(focus, projects);
- addRelatedReferenced(focus, projects);
-
- projects.add(focus);
- return (IJavaScriptProject[]) projects.toArray(new IJavaScriptProject[projects.size()]);
- }
-
- private static Collection getReferencingProjects(IJavaScriptProject focus) throws JavaScriptModelException {
- Set projects= new HashSet();
-
- addReferencingProjects(focus, projects);
- projects.add(focus);
- return projects;
- }
-
- private static List getSourceRoots(IJavaScriptProject javaProject) throws JavaScriptModelException {
- List elements= new ArrayList();
- IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots();
- // Add all package fragment roots except archives
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (!root.isArchive())
- elements.add(root);
- }
- return elements;
- }
-
- private static int getVisibility(IMember member) throws JavaScriptModelException {
- if (JdtFlags.isPrivate(member))
- return 0;
- if (JdtFlags.isPackageVisible(member))
- return 1;
- return 4;
- }
-
- private RefactoringScopeFactory() {
- // no instances
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine.java
deleted file mode 100644
index b357f295..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.IRefactoringStatusEntryComparator;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-/**
- * Convenience wrapper for {@link SearchEngine} - performs searching and sorts the results by {@link IResource}.
- * TODO: throw CoreExceptions from search(..) methods instead of wrapped JavaModelExceptions.
- */
-public class RefactoringSearchEngine {
-
- private RefactoringSearchEngine(){
- //no instances
- }
-
- //TODO: throw CoreException
- public static IJavaScriptUnit[] findAffectedCompilationUnits(SearchPattern pattern,
- IJavaScriptSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws JavaScriptModelException {
-
- boolean hasNonCuMatches= false;
-
- class ResourceSearchRequestor extends SearchRequestor{
- boolean hasPotentialMatches= false ;
- Set resources= new HashSet(5);
- private IResource fLastResource;
-
- public void acceptSearchMatch(SearchMatch match) {
- if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) {
- hasPotentialMatches= true;
- }
- if (fLastResource != match.getResource()) {
- fLastResource= match.getResource();
- resources.add(fLastResource);
- }
- }
- }
- ResourceSearchRequestor requestor = new ResourceSearchRequestor();
- try {
- new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
-
- List result= new ArrayList(requestor.resources.size());
- for (Iterator iter= requestor.resources.iterator(); iter.hasNext(); ) {
- IResource resource= (IResource) iter.next();
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element instanceof IJavaScriptUnit) {
- result.add(element);
- } else {
- hasNonCuMatches= true;
- }
- }
- addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches);
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- //TODO: throw CoreException
- public static IJavaScriptUnit[] findAffectedCompilationUnits(SearchPattern pattern,
- IJavaScriptSearchScope scope, final IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- return findAffectedCompilationUnits(pattern, scope, pm, status, false);
- }
-
- /**
- * Performs a search and groups the resulting {@link SearchMatch}es by
- * {@link SearchResultGroup#getCompilationUnit()}.
- * @param pattern the search pattern
- * @param scope the search scope
- * @param monitor the progress monitor
- * @param status an error is added here if inaccurate or non-cu matches have been found
- * @return a {@link SearchResultGroup}[], where each {@link SearchResultGroup}
- * has a different {@link SearchMatch#getResource() getResource()}s.
- * @see SearchMatch
- * @throws JavaScriptModelException when the search failed
- */
- //TODO: throw CoreException
- public static SearchResultGroup[] search(SearchPattern pattern, IJavaScriptSearchScope scope, IProgressMonitor monitor, RefactoringStatus status)
- throws JavaScriptModelException {
- return internalSearch(new SearchEngine(), pattern, scope, new CollectingSearchRequestor(), monitor, status);
- }
-
- //TODO: throw CoreException
- public static SearchResultGroup[] search(SearchPattern pattern, WorkingCopyOwner owner, IJavaScriptSearchScope scope, IProgressMonitor monitor, RefactoringStatus status)
- throws JavaScriptModelException {
- return internalSearch(owner != null ? new SearchEngine(owner) : new SearchEngine(), pattern, scope, new CollectingSearchRequestor(), monitor, status);
- }
-
- //TODO: throw CoreException
- public static SearchResultGroup[] search(SearchPattern pattern, IJavaScriptSearchScope scope, CollectingSearchRequestor requestor,
- IProgressMonitor monitor, RefactoringStatus status) throws JavaScriptModelException {
- return internalSearch(new SearchEngine(), pattern, scope, requestor, monitor, status);
- }
-
- //TODO: throw CoreException
- public static SearchResultGroup[] search(SearchPattern pattern, WorkingCopyOwner owner, IJavaScriptSearchScope scope,
- CollectingSearchRequestor requestor, IProgressMonitor monitor, RefactoringStatus status) throws JavaScriptModelException {
- return internalSearch(owner != null ? new SearchEngine(owner) : new SearchEngine(), pattern, scope, requestor, monitor, status);
- }
-
- //TODO: throw CoreException
- private static SearchResultGroup[] internalSearch(SearchEngine searchEngine, SearchPattern pattern, IJavaScriptSearchScope scope,
- CollectingSearchRequestor requestor, IProgressMonitor monitor, RefactoringStatus status) throws JavaScriptModelException {
- try {
- searchEngine.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, monitor);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- return groupByCu(requestor.getResults(), status);
- }
-
- public static SearchResultGroup[] groupByCu(SearchMatch[] matches, RefactoringStatus status) {
- return groupByCu(Arrays.asList(matches), status);
- }
-
- /**
- * @param matchList a List of SearchMatch
- * @param status the status to report errors.
- * @return a SearchResultGroup[], grouped by SearchMatch#getResource()
- */
- public static SearchResultGroup[] groupByCu(List matchList, RefactoringStatus status) {
- Map/*<IResource, List<SearchMatch>>*/ grouped= new HashMap();
- boolean hasPotentialMatches= false;
- boolean hasNonCuMatches= false;
-
- for (Iterator iter= matchList.iterator(); iter.hasNext();) {
- SearchMatch searchMatch= (SearchMatch) iter.next();
- if (searchMatch.getAccuracy() == SearchMatch.A_INACCURATE)
- hasPotentialMatches= true;
- if (! grouped.containsKey(searchMatch.getResource()))
- grouped.put(searchMatch.getResource(), new ArrayList(1));
- ((List) grouped.get(searchMatch.getResource())).add(searchMatch);
- }
-
- for (Iterator iter= grouped.keySet().iterator(); iter.hasNext();) {
- IResource resource= (IResource) iter.next();
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (! (element instanceof IJavaScriptUnit)) {
- iter.remove();
- hasNonCuMatches= true;
- }
- }
-
- SearchResultGroup[] result= new SearchResultGroup[grouped.keySet().size()];
- int i= 0;
- for (Iterator iter= grouped.keySet().iterator(); iter.hasNext();) {
- IResource resource= (IResource) iter.next();
- List searchMatches= (List) grouped.get(resource);
- SearchMatch[] matchArray= (SearchMatch[]) searchMatches.toArray(new SearchMatch[searchMatches.size()]);
- result[i]= new SearchResultGroup(resource, matchArray);
- i++;
- }
- addStatusErrors(status, hasPotentialMatches, hasNonCuMatches);
- return result;
- }
-
- public static SearchPattern createOrPattern(IJavaScriptElement[] elements, int limitTo) {
- if (elements == null || elements.length == 0)
- return null;
- Set set= new HashSet(Arrays.asList(elements));
- Iterator iter= set.iterator();
- IJavaScriptElement first= (IJavaScriptElement)iter.next();
- SearchPattern pattern= SearchPattern.createPattern(first, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- if (pattern == null) // check for bug 90138
- throw new IllegalArgumentException("Invalid java element: " + first.getHandleIdentifier() + "\n" + first.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- while(iter.hasNext()){
- IJavaScriptElement each= (IJavaScriptElement)iter.next();
- SearchPattern nextPattern= SearchPattern.createPattern(each, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- if (nextPattern == null) // check for bug 90138
- throw new IllegalArgumentException("Invalid java element: " + each.getHandleIdentifier() + "\n" + each.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- pattern= SearchPattern.createOrPattern(pattern, nextPattern);
- }
- return pattern;
- }
-
- private static boolean containsStatusEntry(final RefactoringStatus status, final RefactoringStatusEntry other) {
- return status.getEntries(new IRefactoringStatusEntryComparator() {
- public final int compare(final RefactoringStatusEntry entry1, final RefactoringStatusEntry entry2) {
- return entry1.getMessage().compareTo(entry2.getMessage());
- }
- }, other).length > 0;
- }
-
- private static void addStatusErrors(RefactoringStatus status, boolean hasPotentialMatches, boolean hasNonCuMatches) {
- if (hasPotentialMatches) {
- final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.ERROR, RefactoringCoreMessages.RefactoringSearchEngine_potential_matches);
- if (!containsStatusEntry(status, entry))
- status.addEntry(entry);
- }
- if (hasNonCuMatches) {
- final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.ERROR, RefactoringCoreMessages.RefactoringSearchEngine_non_cu_matches);
- if (!containsStatusEntry(status, entry))
- status.addEntry(entry);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine2.java
deleted file mode 100644
index 05ecf867..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/RefactoringSearchEngine2.java
+++ /dev/null
@@ -1,726 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-/**
- * Helper class to use the search engine in refactorings.
- *
- *
- */
-public final class RefactoringSearchEngine2 {
-
- /** Default implementation of a search requestor */
- private static class DefaultSearchRequestor implements IRefactoringSearchRequestor {
-
- public final SearchMatch acceptSearchMatch(final SearchMatch match) {
- return match;
- }
- }
-
- /** Search requestor which only collects compilation units */
- private class RefactoringCompilationUnitCollector extends RefactoringSearchCollector {
-
- /** The collected compilation units */
- private final Set fCollectedUnits= new HashSet();
-
- /** The inaccurate matches */
- private final Set fInaccurateMatches= new HashSet();
-
- public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
- final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
- if (accepted != null) {
- final IResource resource= accepted.getResource();
- if (!resource.equals(fLastResource)) {
- final IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element instanceof IJavaScriptUnit)
- fCollectedUnits.add(element);
- }
- if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
- fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, accepted.getResource().getName()), null, null, RefactoringStatusEntry.NO_CODE);
- fInaccurateMatches.add(accepted);
- }
- }
- }
-
- public final void clearResults() {
- super.clearResults();
- fCollectedUnits.clear();
- fInaccurateMatches.clear();
- }
-
- public final Collection getBinaryResources() {
- return Collections.EMPTY_SET;
- }
-
- public final Collection getCollectedMatches() {
- return fCollectedUnits;
- }
-
- public final Collection getInaccurateMatches() {
- return fInaccurateMatches;
- }
- }
-
- private abstract class RefactoringSearchCollector extends SearchRequestor {
-
- protected IResource fLastResource= null;
-
- public void clearResults() {
- fLastResource= null;
- }
-
- public abstract Collection getBinaryResources();
-
- public abstract Collection getCollectedMatches();
-
- public abstract Collection getInaccurateMatches();
- }
-
- /** Search requestor which collects every search match */
- private class RefactoringSearchMatchCollector extends RefactoringSearchCollector {
-
- /** The binary resources */
- private final Set fBinaryResources= new HashSet();
-
- /** The collected matches */
- private final List fCollectedMatches= new ArrayList();
-
- /** The inaccurate matches */
- private final Set fInaccurateMatches= new HashSet();
-
- public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
- final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
- if (accepted != null) {
- fCollectedMatches.add(accepted);
- final IResource resource= accepted.getResource();
- if (!resource.equals(fLastResource)) {
- if (fBinary) {
- final IJavaScriptElement element= JavaScriptCore.create(resource);
- if (!(element instanceof IJavaScriptUnit)) {
- final IProject project= resource.getProject();
- if (!fGrouping)
- fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_ungrouped, project.getName()), null, null, RefactoringStatusEntry.NO_CODE);
- else if (!fBinaryResources.contains(resource))
- fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_grouped, project.getName()), null, null, RefactoringStatusEntry.NO_CODE);
- fBinaryResources.add(resource);
- }
- }
- if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
- fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, resource.getName()), null, null, RefactoringStatusEntry.NO_CODE);
- fInaccurateMatches.add(accepted);
- }
- }
- }
- }
-
- public final void clearResults() {
- super.clearResults();
- fCollectedMatches.clear();
- fInaccurateMatches.clear();
- fBinaryResources.clear();
- }
-
- public final Collection getBinaryResources() {
- return fBinaryResources;
- }
-
- public final Collection getCollectedMatches() {
- return fCollectedMatches;
- }
-
- public final Collection getInaccurateMatches() {
- return fInaccurateMatches;
- }
- }
-
- /** The compilation unit granularity */
- public static final int GRANULARITY_COMPILATION_UNIT= 2;
-
- /** The search match granularity */
- public static final int GRANULARITY_SEARCH_MATCH= 1;
-
- /** Should binary matches be filtered? */
- private boolean fBinary= false;
-
- /** The refactoring search collector */
- private RefactoringSearchCollector fCollector= null;
-
- /** The search granularity */
- private int fGranularity= GRANULARITY_SEARCH_MATCH;
-
- /** Should the matches be grouped by resource? */
- private boolean fGrouping= true;
-
- /** Should inaccurate matches be filtered? */
- private boolean fInaccurate= true;
-
- /** The working copy owner, or <code>null</code> */
- private WorkingCopyOwner fOwner= null;
-
- /** The search pattern, or <code>null</code> */
- private SearchPattern fPattern= null;
-
- /** The search requestor */
- private IRefactoringSearchRequestor fRequestor= new DefaultSearchRequestor();
-
- /** The search scope */
- private IJavaScriptSearchScope fScope= SearchEngine.createWorkspaceScope();
-
- /** The severity */
- private int fSeverity= RefactoringStatus.WARNING;
-
- /** The search status */
- private RefactoringStatus fStatus= new RefactoringStatus();
-
- /** The working copies */
- private IJavaScriptUnit[] fWorkingCopies= {};
-
- /**
- * Creates a new refactoring search engine.
- */
- public RefactoringSearchEngine2() {
- // Do nothing
- }
-
- /**
- * Creates a new refactoring search engine.
- *
- * @param pattern the search pattern
- */
- public RefactoringSearchEngine2(final SearchPattern pattern) {
- Assert.isNotNull(pattern);
- fPattern= pattern;
- }
-
- /**
- * Clears all results found so far, and sets resets the status to {@link RefactoringStatus#OK}.
- */
- public final void clearResults() {
- getCollector().clearResults();
- fStatus= new RefactoringStatus();
- }
-
- /**
- * Returns the affected compilation units of the previous search queries.
- * <p>
- * In order to retrieve the compilation units, grouping by resource must have been enabled before searching.
- *
- * @return the compilation units of the previous queries
- */
- public final IJavaScriptUnit[] getAffectedCompilationUnits() {
- if (fGranularity == GRANULARITY_COMPILATION_UNIT) {
- final Collection collection= getCollector().getCollectedMatches();
- final IJavaScriptUnit[] units= new IJavaScriptUnit[collection.size()];
- int index= 0;
- for (final Iterator iterator= collection.iterator(); iterator.hasNext(); index++)
- units[index]= (IJavaScriptUnit) iterator.next();
- return units;
- } else {
- final SearchResultGroup[] groups= getGroupedMatches();
- final IJavaScriptUnit[] units= new IJavaScriptUnit[groups.length];
- for (int index= 0; index < groups.length; index++)
- units[index]= groups[index].getCompilationUnit();
- return units;
- }
- }
-
- /**
- * Returns the affected java projects of the previous search queries.
- * <p>
- * In order to retrieve the java projects, grouping by resource must have been enabled before searching.
- *
- * @return the java projects of the previous queries (element type: <code>&ltIJavaProject, Collection&ltSearchResultGroup&gt&gt</code>)
- */
- public final Map getAffectedProjects() {
- final Map map= new HashMap();
- IJavaScriptProject project= null;
- IJavaScriptUnit unit= null;
- if (fGranularity == GRANULARITY_COMPILATION_UNIT) {
- final IJavaScriptUnit[] units= getAffectedCompilationUnits();
- for (int index= 0; index < units.length; index++) {
- unit= units[index];
- project= unit.getJavaScriptProject();
- if (project != null) {
- Set set= (Set) map.get(project);
- if (set == null) {
- set= new HashSet();
- map.put(project, set);
- }
- set.add(unit);
- }
- }
- } else {
- final SearchResultGroup[] groups= getGroupedMatches();
- SearchResultGroup group= null;
- for (int index= 0; index < groups.length; index++) {
- group= groups[index];
- unit= group.getCompilationUnit();
- if (unit != null) {
- project= unit.getJavaScriptProject();
- if (project != null) {
- Set set= (Set) map.get(project);
- if (set == null) {
- set= new HashSet();
- map.put(project, set);
- }
- set.add(group);
- }
- }
- }
- }
- return map;
- }
-
- /**
- * Returns the refactoring search collector.
- *
- * @return the refactoring search collector
- */
- private RefactoringSearchCollector getCollector() {
- if (fCollector == null) {
- if (fGranularity == GRANULARITY_COMPILATION_UNIT)
- fCollector= new RefactoringCompilationUnitCollector();
- else if (fGranularity == GRANULARITY_SEARCH_MATCH)
- fCollector= new RefactoringSearchMatchCollector();
- else
- Assert.isTrue(false);
- }
- return fCollector;
- }
-
- /**
- * Returns the found search matches in grouped by their containing resource.
- *
- * @return the found search matches
- */
- private SearchResultGroup[] getGroupedMatches() {
- final Map grouped= new HashMap();
- List matches= null;
- IResource resource= null;
- SearchMatch match= null;
- for (final Iterator iterator= getSearchMatches().iterator(); iterator.hasNext();) {
- match= (SearchMatch) iterator.next();
- resource= match.getResource();
- if (!grouped.containsKey(resource))
- grouped.put(resource, new ArrayList(4));
- matches= (List) grouped.get(resource);
- matches.add(match);
- }
- if (fBinary) {
- final Collection collection= getCollector().getBinaryResources();
- for (final Iterator iterator= grouped.keySet().iterator(); iterator.hasNext();) {
- resource= (IResource) iterator.next();
- if (collection.contains(resource))
- iterator.remove();
- }
- }
- final SearchResultGroup[] result= new SearchResultGroup[grouped.keySet().size()];
- int index= 0;
- for (final Iterator iterator= grouped.keySet().iterator(); iterator.hasNext();) {
- resource= (IResource) iterator.next();
- matches= (List) grouped.get(resource);
- result[index++]= new SearchResultGroup(resource, ((SearchMatch[]) matches.toArray(new SearchMatch[matches.size()])));
- }
- return result;
- }
-
- /**
- * Returns the search pattern currently used for searching.
- *
- * @return the search pattern
- */
- public final SearchPattern getPattern() {
- return fPattern;
- }
-
- /**
- * Returns the results of the previous search queries.
- * <p>
- * The result depends on the following conditions:
- * <ul>
- * <li>If the search granularity is {@link #GRANULARITY_COMPILATION_UNIT}, the results are elements of type {@link IJavaScriptUnit}.</li>
- * <li>If grouping by resource is enabled, the results are elements of type {@link SearchResultGroup}, otherwise the elements are of type {@link SearchMatch}.</li>
- * </ul>
- *
- * @return the results of the previous queries
- */
- public final Object[] getResults() {
- if (fGranularity == GRANULARITY_COMPILATION_UNIT)
- return getAffectedCompilationUnits();
- else {
- if (fGrouping)
- return getGroupedMatches();
- else
- return getUngroupedMatches();
- }
- }
-
- /**
- * Returns the search matches filtered by their accuracy.
- *
- * @return the filtered search matches
- */
- private Collection getSearchMatches() {
- Collection results= null;
- if (fInaccurate) {
- results= new LinkedList(getCollector().getCollectedMatches());
- final Collection collection= getCollector().getInaccurateMatches();
- SearchMatch match= null;
- for (final Iterator iterator= results.iterator(); iterator.hasNext();) {
- match= (SearchMatch) iterator.next();
- if (collection.contains(match))
- iterator.remove();
- }
- } else
- results= getCollector().getCollectedMatches();
- return results;
- }
-
- /**
- * Returns the refactoring status of this search engine.
- *
- * @return the refactoring status
- */
- public final RefactoringStatus getStatus() {
- return fStatus;
- }
-
- /**
- * Returns the found search matches in no particular order.
- *
- * @return the found search matches
- */
- private SearchMatch[] getUngroupedMatches() {
- Collection results= null;
- if (fBinary) {
- results= new LinkedList(getSearchMatches());
- final Collection collection= getCollector().getBinaryResources();
- SearchMatch match= null;
- for (final Iterator iterator= results.iterator(); iterator.hasNext();) {
- match= (SearchMatch) iterator.next();
- if (collection.contains(match.getResource()))
- iterator.remove();
- }
- } else
- results= getSearchMatches();
- final SearchMatch[] matches= new SearchMatch[results.size()];
- results.toArray(matches);
- return matches;
- }
-
- /**
- * Performs the search according to the specified pattern.
- *
- * @param monitor the progress monitor, or <code>null</code>
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void searchPattern(final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(fPattern);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.RefactoringSearchEngine_searching_occurrences);
- try {
- SearchEngine engine= null;
- if (fOwner != null)
- engine= new SearchEngine(fOwner);
- else
- engine= new SearchEngine(fWorkingCopies);
- engine.search(fPattern, SearchUtils.getDefaultSearchParticipants(), fScope, getCollector(), new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- throw new JavaScriptModelException(exception);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Performs the search of referenced fields.
- *
- * @param element the java element whose referenced fields have to be found
- * @param monitor the progress monitor, or <code>null</code>
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void searchReferencedFields(final IJavaScriptElement element, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(element);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.RefactoringSearchEngine_searching_referenced_fields);
- try {
- SearchEngine engine= null;
- if (fOwner != null)
- engine= new SearchEngine(fOwner);
- else
- engine= new SearchEngine(fWorkingCopies);
- engine.searchDeclarationsOfAccessedFields(element, getCollector(), new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- throw new JavaScriptModelException(exception);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Performs the search of referenced methods.
- *
- * @param element the java element whose referenced methods have to be found
- * @param monitor the progress monitor, or <code>null</code>
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void searchReferencedMethods(final IJavaScriptElement element, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(element);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.RefactoringSearchEngine_searching_referenced_methods);
- try {
- SearchEngine engine= null;
- if (fOwner != null)
- engine= new SearchEngine(fOwner);
- else
- engine= new SearchEngine(fWorkingCopies);
- engine.searchDeclarationsOfSentMessages(element, getCollector(), new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- throw new JavaScriptModelException(exception);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Performs the search of referenced types.
- *
- * @param element the java element whose referenced types have to be found
- * @param monitor the progress monitor, or <code>null</code>
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void searchReferencedTypes(final IJavaScriptElement element, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(element);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.RefactoringSearchEngine_searching_referenced_types);
- try {
- SearchEngine engine= null;
- if (fOwner != null)
- engine= new SearchEngine(fOwner);
- else
- engine= new SearchEngine(fWorkingCopies);
- engine.searchDeclarationsOfReferencedTypes(element, getCollector(), new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- throw new JavaScriptModelException(exception);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Sets the conjunction of search patterns to be used during search.
- * <p>
- * This method must be called before {@link RefactoringSearchEngine2#searchPattern(IProgressMonitor)}
- *
- * @param first the first search pattern to set
- * @param second the second search pattern to set
- */
- public final void setAndPattern(final SearchPattern first, final SearchPattern second) {
- Assert.isNotNull(first);
- Assert.isNotNull(second);
- fPattern= SearchPattern.createAndPattern(first, second);
- }
-
- /**
- * Determines how search matches are filtered.
- * <p>
- * This method must be called before start searching. The default is to filter inaccurate matches only.
- *
- * @param inaccurate <code>true</code> to filter inaccurate matches, <code>false</code> otherwise
- * @param binary <code>true</code> to filter binary matches, <code>false</code> otherwise
- */
- public final void setFiltering(final boolean inaccurate, final boolean binary) {
- fInaccurate= inaccurate;
- fBinary= binary;
- }
-
- /**
- * Sets the granularity to use during the searches.
- * <p>
- * This method must be called before start searching. The default is a granularity of {@link #GRANULARITY_SEARCH_MATCH}.
- *
- * @param granularity The granularity to use. Must be one of the <code>GRANULARITY_XXX</code> constants.
- */
- public final void setGranularity(final int granularity) {
- Assert.isTrue(granularity == GRANULARITY_COMPILATION_UNIT || granularity == GRANULARITY_SEARCH_MATCH);
- fGranularity= granularity;
- }
-
- /**
- * Sets the working copies to take precedence during the searches.
- * <p>
- * This method must be called before start searching. The default is to use no working copies
- *
- * @param copies the working copies to use
- */
- public final void setWorkingCopies(final IJavaScriptUnit[] copies) {
- Assert.isNotNull(copies);
- fWorkingCopies= new IJavaScriptUnit[copies.length];
- System.arraycopy(copies, 0, fWorkingCopies, 0, copies.length);
- }
-
- /**
- * Determines how search matches are grouped.
- * <p>
- * This method must be called before start searching. The default is to group by containing resource.
- *
- * @param grouping <code>true</code> to group matches by their containing resource, <code>false</code> otherwise
- */
- public final void setGrouping(final boolean grouping) {
- fGrouping= grouping;
- }
-
- /**
- * Sets the disjunction of search patterns to be used during search.
- * <p>
- * This method must be called before {@link RefactoringSearchEngine2#searchPattern(IProgressMonitor)}
- *
- * @param first the first search pattern to set
- * @param second the second search pattern to set
- */
- public final void setOrPattern(final SearchPattern first, final SearchPattern second) {
- Assert.isNotNull(first);
- Assert.isNotNull(second);
- fPattern= SearchPattern.createOrPattern(first, second);
- }
-
- /**
- * Sets the working copy owner to use during search.
- * <p>
- * This method must be called before start searching. The default is to use no working copy owner.
- *
- * @param owner the working copy owner to use, or <code>null</code> to use none
- */
- public final void setOwner(final WorkingCopyOwner owner) {
- fOwner= owner;
- }
-
- /**
- * Sets the search pattern to be used during search.
- * <p>
- * This method must be called before {@link RefactoringSearchEngine2#searchPattern(IProgressMonitor)}
- *
- * @param elements the set of elements
- * @param limitTo determines the nature of the expected matches. This is a combination of {@link org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants}.
- */
- public final void setPattern(final IJavaScriptElement[] elements, final int limitTo) {
- Assert.isNotNull(elements);
- Assert.isTrue(elements.length > 0);
- SearchPattern pattern= SearchPattern.createPattern(elements[0], limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptElement element= null;
- for (int index= 1; index < elements.length; index++) {
- element= elements[index];
- pattern= SearchPattern.createOrPattern(pattern, SearchPattern.createPattern(element, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- }
- setPattern(pattern);
- }
-
- /**
- * Sets the search pattern to be used during search.
- * <p>
- * This method must be called before {@link RefactoringSearchEngine2#searchPattern(IProgressMonitor)}
- *
- * @param pattern the search pattern to set
- */
- public final void setPattern(final SearchPattern pattern) {
- Assert.isNotNull(pattern);
- fPattern= pattern;
- }
-
- /**
- * Sets the search requestor for this search engine.
- * <p>
- * This method must be called before start searching. The default is a non-filtering search requestor.
- *
- * @param requestor the search requestor to set
- */
- public final void setRequestor(final IRefactoringSearchRequestor requestor) {
- Assert.isNotNull(requestor);
- fRequestor= requestor;
- }
-
- /**
- * Sets the search scope for this search engine.
- * <p>
- * This method must be called before start searching. The default is the entire workspace as search scope.
- *
- * @param scope the search scope to set
- */
- public final void setScope(final IJavaScriptSearchScope scope) {
- Assert.isNotNull(scope);
- fScope= scope;
- }
-
- /**
- * Sets the severity of the generated status entries.
- * <p>
- * This method must be called before start searching. The default is a severity of {@link RefactoringStatus#OK}.
- *
- * @param severity the severity to set
- */
- public final void setSeverity(final int severity) {
- Assert.isTrue(severity == RefactoringStatus.WARNING || severity == RefactoringStatus.INFO || severity == RefactoringStatus.FATAL || severity == RefactoringStatus.ERROR);
- fSeverity= severity;
- }
-
- /**
- * Sets the refactoring status for this search engine.
- * <p>
- * This method must be called before start searching. The default is an empty status with status {@link RefactoringStatus#OK}.
- *
- * @param status the refactoring status to set
- */
- public final void setStatus(final RefactoringStatus status) {
- Assert.isNotNull(status);
- fStatus= status;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ReturnTypeInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ReturnTypeInfo.java
deleted file mode 100644
index fe4e5922..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/ReturnTypeInfo.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public class ReturnTypeInfo {
-
- private final String fOldTypeName;
- private String fNewTypeName;
- private ITypeBinding fNewTypeBinding;
-
- public ReturnTypeInfo(String returnType) {
- fOldTypeName= returnType;
- fNewTypeName= returnType;
- }
-
- public String getOldTypeName() {
- return fOldTypeName;
- }
-
- public String getNewTypeName() {
- return fNewTypeName;
- }
-
- public void setNewTypeName(String type){
- Assert.isNotNull(type);
- fNewTypeName= type;
- }
-
- public ITypeBinding getNewTypeBinding() {
- return fNewTypeBinding;
- }
-
- public void setNewTypeBinding(ITypeBinding typeBinding){
- fNewTypeBinding= typeBinding;
- }
-
- public boolean isTypeNameChanged() {
- return !fOldTypeName.equals(fNewTypeName);
- }
-
- public String toString() {
- return fOldTypeName + " -> " + fNewTypeName; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/SearchResultGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/SearchResultGroup.java
deleted file mode 100644
index 21c51bc4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/SearchResultGroup.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-public class SearchResultGroup {
-
- private final IResource fResouce;
- private final List fSearchMatches;
-
- public SearchResultGroup(IResource res, SearchMatch[] matches){
- Assert.isNotNull(matches);
- fResouce= res;
- fSearchMatches= new ArrayList(Arrays.asList(matches));
- }
-
- public void add(SearchMatch match) {
- Assert.isNotNull(match);
- fSearchMatches.add(match);
- }
-
- public IResource getResource() {
- return fResouce;
- }
-
- public SearchMatch[] getSearchResults() {
- return (SearchMatch[]) fSearchMatches.toArray(new SearchMatch[fSearchMatches.size()]);
- }
-
- public static IResource[] getResources(SearchResultGroup[] searchResultGroups){
- Set resourceSet= new HashSet(searchResultGroups.length);
- for (int i= 0; i < searchResultGroups.length; i++) {
- resourceSet.add(searchResultGroups[i].getResource());
- }
- return (IResource[]) resourceSet.toArray(new IResource[resourceSet.size()]);
- }
-
- public IJavaScriptUnit getCompilationUnit(){
- if (getSearchResults() == null || getSearchResults().length == 0)
- return null;
- return SearchUtils.getCompilationUnit(getSearchResults()[0]);
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer(fResouce.getFullPath().toString());
- buf.append('\n');
- for (int i= 0; i < fSearchMatches.size(); i++) {
- SearchMatch match= (SearchMatch) fSearchMatches.get(i);
- buf.append(" ").append(match.getOffset()).append(", ").append(match.getLength()); //$NON-NLS-1$//$NON-NLS-2$
- buf.append(match.getAccuracy() == SearchMatch.A_ACCURATE ? "; acc" : "; inacc"); //$NON-NLS-1$//$NON-NLS-2$
- if (match.isInsideDocComment())
- buf.append("; inDoc"); //$NON-NLS-1$
- if (match.getElement() instanceof IJavaScriptElement)
- buf.append("; in: ").append(((IJavaScriptElement) match.getElement()).getElementName()); //$NON-NLS-1$
- buf.append('\n');
- }
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/StubTypeContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/StubTypeContext.java
deleted file mode 100644
index b3f5127a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/StubTypeContext.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-public class StubTypeContext {
- private String fBeforeString;
- private String fAfterString;
- private final IJavaScriptUnit fCuHandle;
-
- public StubTypeContext(IJavaScriptUnit cuHandle, String beforeString, String afterString) {
- fCuHandle= cuHandle;
- fBeforeString= beforeString;
- fAfterString= afterString;
- }
-
- public IJavaScriptUnit getCuHandle() {
- return fCuHandle;
- }
-
- public String getBeforeString() {
- return fBeforeString;
- }
-
- public String getAfterString() {
- return fAfterString;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypeContextChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypeContextChecker.java
deleted file mode 100644
index c789f45a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypeContextChecker.java
+++ /dev/null
@@ -1,753 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IExtendedModifier;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTFlattener;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeNameMatchCollector;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-
-public class TypeContextChecker {
-
- public interface IProblemVerifier {
-
- boolean isError(IProblem problem, ASTNode node);
-
- }
-
- private static class MethodTypesChecker {
-
- private static final String METHOD_NAME= "__$$__"; //$NON-NLS-1$
-
- private final IFunction fMethod;
- private final StubTypeContext fStubTypeContext;
- private final List/*<ParameterInfo>*/ fParameterInfos;
- private final ReturnTypeInfo fReturnTypeInfo;
-
- private final IProblemVerifier fProblemVerifier;
-
- public MethodTypesChecker(IFunction method, StubTypeContext stubTypeContext, List/*<ParameterInfo>*/ parameterInfos, ReturnTypeInfo returnTypeInfo, IProblemVerifier problemVerifier) {
- fMethod= method;
- fStubTypeContext= stubTypeContext;
- fParameterInfos= parameterInfos;
- fReturnTypeInfo= returnTypeInfo;
- fProblemVerifier= problemVerifier;
- }
-
- public RefactoringStatus[] checkAndResolveMethodTypes() throws CoreException {
-
- /* ECMA3 no variable or return types */
- if(!JavaScriptCore.IS_ECMASCRIPT4) return new RefactoringStatus[0];
-
- RefactoringStatus[] results= new MethodTypesSyntaxChecker(fMethod, fParameterInfos, fReturnTypeInfo).checkSyntax();
- for (int i= 0; i < results.length; i++)
- if (results[i] != null && results[i].hasFatalError())
- return results;
-
- int parameterCount= fParameterInfos.size();
- String[] types= new String[parameterCount + 1];
- for (int i= 0; i < parameterCount; i++)
- types[i]= ParameterInfo.stripEllipsis(((ParameterInfo) fParameterInfos.get(i)).getNewTypeName());
- types[parameterCount]= fReturnTypeInfo.getNewTypeName();
- RefactoringStatus[] semanticsResults= new RefactoringStatus[parameterCount + 1];
- ITypeBinding[] typeBindings= resolveBindings(types, semanticsResults, true);
-
- boolean needsSecondPass= false;
- for (int i= 0; i < types.length; i++)
- if (typeBindings[i] == null || ! semanticsResults[i].isOK())
- needsSecondPass= true;
-
- RefactoringStatus[] semanticsResults2= new RefactoringStatus[parameterCount + 1];
- if (needsSecondPass)
- typeBindings= resolveBindings(types, semanticsResults2, false);
-
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo parameterInfo= (ParameterInfo) fParameterInfos.get(i);
- if (parameterInfo.getOldTypeBinding() != null && ! parameterInfo.isTypeNameChanged()) {
- parameterInfo.setNewTypeBinding(parameterInfo.getOldTypeBinding());
- } else {
- parameterInfo.setNewTypeBinding(typeBindings[i]);
- if (typeBindings[i] == null || (needsSecondPass && ! semanticsResults2[i].isOK())) {
- if (results[i] == null)
- results[i]= semanticsResults2[i];
- else
- results[i].merge(semanticsResults2[i]);
- }
- }
- }
- fReturnTypeInfo.setNewTypeBinding(typeBindings[fParameterInfos.size()]);
- if (typeBindings[parameterCount] == null || (needsSecondPass && ! semanticsResults2[parameterCount].isOK())) {
- if (results[parameterCount] == null)
- results[parameterCount]= semanticsResults2[parameterCount];
- else
- results[parameterCount].merge(semanticsResults2[parameterCount]);
- }
-
- return results;
- }
-
- private ITypeBinding[] resolveBindings(String[] types, RefactoringStatus[] results, boolean firstPass) throws CoreException {
- //TODO: split types into parameterTypes and returnType
- int parameterCount= types.length - 1;
- ITypeBinding[] typeBindings= new ITypeBinding[types.length];
-
- StringBuffer cuString= new StringBuffer();
- cuString.append(fStubTypeContext.getBeforeString());
- int offsetBeforeMethodName= appendMethodDeclaration(cuString, types, parameterCount);
- cuString.append(fStubTypeContext.getAfterString());
-
- // need a working copy to tell the parser where to resolve (package visible) types
- IJavaScriptUnit wc= fMethod.getJavaScriptUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
- try {
- wc.getBuffer().setContents(cuString.toString());
- JavaScriptUnit compilationUnit= new RefactoringASTParser(AST.JLS3).parse(wc, true);
- ASTNode method= NodeFinder.perform(compilationUnit, offsetBeforeMethodName, METHOD_NAME.length()).getParent();
- Type[] typeNodes= new Type[types.length];
- if (method instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) method;
- typeNodes[parameterCount]= methodDeclaration.getReturnType2();
- List/*<SingleVariableDeclaration>*/ parameters= methodDeclaration.parameters();
- for (int i= 0; i < parameterCount; i++)
- typeNodes[i]= ((SingleVariableDeclaration) parameters.get(i)).getType();
-
- }
-
- for (int i= 0; i < types.length; i++) {
- Type type= typeNodes[i];
- if (type == null) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_couldNotResolveType, types[i]);
- results[i]= RefactoringStatus.createErrorStatus(msg);
- continue;
- }
- results[i]= new RefactoringStatus();
- IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
- if (problems.length > 0) {
- for (int p= 0; p < problems.length; p++)
- if (isError(problems[p], type))
- results[i].addError(problems[p].getMessage());
- }
- typeBindings[i]= type.resolveBinding();
- typeBindings[i]= handleBug84585(typeBindings[i]);
- if (firstPass && typeBindings[i] == null)
- types[i]= qualifyTypes(type, results[i]);
- }
- return typeBindings;
- } finally {
- wc.discardWorkingCopy();
- }
- }
-
- private boolean isError(IProblem problem, Type type) {
- if (fProblemVerifier != null)
- return fProblemVerifier.isError(problem, type);
- return true;
- }
-
- private int appendMethodDeclaration(StringBuffer cuString, String[] types, int parameterCount) throws JavaScriptModelException {
- if (Flags.isStatic(fMethod.getFlags()))
- cuString.append("static "); //$NON-NLS-1$
-
- cuString.append(types[parameterCount]).append(' ');
- int offsetBeforeMethodName= cuString.length();
- cuString.append(METHOD_NAME).append('(');
- for (int i= 0; i < parameterCount; i++) {
- if (i > 0)
- cuString.append(',');
- cuString.append(types[i]).append(" p").append(i); //$NON-NLS-1$
- }
- cuString.append(");"); //$NON-NLS-1$
-
- return offsetBeforeMethodName;
- }
-
- private String qualifyTypes(Type type, final RefactoringStatus result) throws CoreException {
- class NestedException extends RuntimeException {
- private static final long serialVersionUID= 1L;
- NestedException(CoreException e) {
- super(e);
- }
- }
- ASTFlattener flattener= new ASTFlattener() {
- public boolean visit(SimpleName node) {
- appendResolved(node.getIdentifier());
- return false;
- }
- public boolean visit(QualifiedName node) {
- appendResolved(node.getFullyQualifiedName());
- return false;
- }
- public boolean visit(QualifiedType node) {
- appendResolved(ASTNodes.asString(node));
- return false;
- }
- private void appendResolved(String typeName) {
- String resolvedType;
- try {
- resolvedType= resolveType(typeName, result, fMethod.getDeclaringType(), null);
- } catch (CoreException e) {
- throw new NestedException(e);
- }
- this.fBuffer.append(resolvedType);
- }
- };
- try {
- type.accept(flattener);
- } catch (NestedException e) {
- throw ((CoreException) e.getCause());
- }
- return flattener.getResult();
- }
-
- private static String resolveType(String elementTypeName, RefactoringStatus status, IType declaringType, IProgressMonitor pm) throws CoreException {
- String[][] fqns= declaringType.resolveType(elementTypeName);
- if (fqns != null) {
- if (fqns.length == 1) {
- return JavaModelUtil.concatenateName(fqns[0][0], fqns[0][1]);
- } else if (fqns.length > 1){
- String[] keys= {elementTypeName, String.valueOf(fqns.length)};
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_ambiguous, keys);
- status.addError(msg);
- return elementTypeName;
- }
- }
-
- List typeRefsFound= findTypeInfos(elementTypeName, declaringType, pm);
- if (typeRefsFound.size() == 0){
- String[] keys= {elementTypeName};
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_not_unique, keys);
- status.addError(msg);
- return elementTypeName;
- } else if (typeRefsFound.size() == 1){
- TypeNameMatch typeInfo= (TypeNameMatch) typeRefsFound.get(0);
- return typeInfo.getFullyQualifiedName();
- } else {
- Assert.isTrue(typeRefsFound.size() > 1);
- String[] keys= {elementTypeName, String.valueOf(typeRefsFound.size())};
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_ambiguous, keys);
- status.addError(msg);
- return elementTypeName;
- }
- }
-
- private static List findTypeInfos(String typeName, IType contextType, IProgressMonitor pm) throws JavaScriptModelException {
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptProject[]{contextType.getJavaScriptProject()}, true);
- IPackageFragment currPackage= contextType.getPackageFragment();
- ArrayList collectedInfos= new ArrayList();
- TypeNameMatchCollector requestor= new TypeNameMatchCollector(collectedInfos);
- int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
- new SearchEngine().searchAllTypeNames(null, matchMode, typeName.toCharArray(), matchMode, IJavaScriptSearchConstants.TYPE, scope, requestor, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, pm);
-
- List result= new ArrayList();
- for (Iterator iter= collectedInfos.iterator(); iter.hasNext();) {
- TypeNameMatch curr= (TypeNameMatch) iter.next();
- IType type= curr.getType();
- if (type != null) {
- boolean visible=true;
- try {
- visible= JavaModelUtil.isVisible(type, currPackage);
- } catch (JavaScriptModelException e) {
- //Assume visibile if not available
- }
- if (visible) {
- result.add(curr);
- }
- }
- }
- return result;
- }
-
- }
-
- private static class MethodTypesSyntaxChecker {
-
- private final IFunction fMethod;
- private final List/*<ParameterInfo>*/ fParameterInfos;
- private final ReturnTypeInfo fReturnTypeInfo;
-
- public MethodTypesSyntaxChecker(IFunction method, List/*<ParameterInfo>*/ parameterInfos, ReturnTypeInfo returnTypeInfo) {
- fMethod= method;
- fParameterInfos= parameterInfos;
- fReturnTypeInfo= returnTypeInfo;
- }
-
- public RefactoringStatus[] checkSyntax() {
- /* No checks for ECMA 3 */
- if(!JavaScriptCore.IS_ECMASCRIPT4) return new RefactoringStatus[0];
- int parameterCount= fParameterInfos.size();
- RefactoringStatus[] results= new RefactoringStatus[parameterCount + 1];
- results[parameterCount]= checkReturnTypeSyntax();
- for (int i= 0; i < parameterCount; i++) {
- ParameterInfo info= (ParameterInfo) fParameterInfos.get(i);
- results[i]= checkParameterTypeSyntax(info);
- }
- return results;
- }
-
- private RefactoringStatus checkParameterTypeSyntax(ParameterInfo info) {
- if (! info.isAdded() && ! info.isTypeNameChanged())
- return null;
- return TypeContextChecker.checkParameterTypeSyntax(info.getNewTypeName(), fMethod.getJavaScriptProject());
- }
-
- private RefactoringStatus checkReturnTypeSyntax() {
- String newTypeName= fReturnTypeInfo.getNewTypeName();
- if ("".equals(newTypeName.trim())) { //$NON-NLS-1$
- String msg= RefactoringCoreMessages.TypeContextChecker_return_type_not_empty;
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- List problemsCollector= new ArrayList(0);
- Type parsedType= parseType(newTypeName, fMethod.getJavaScriptProject(), problemsCollector);
- if (parsedType == null) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_return_type, new String[]{newTypeName});
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- if (problemsCollector.size() == 0)
- return null;
-
- RefactoringStatus result= new RefactoringStatus();
- for (Iterator iter= problemsCollector.iterator(); iter.hasNext();) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_return_type_syntax, new String[]{newTypeName, (String) iter.next()});
- result.addError(msg);
- }
- return result;
- }
-
- private static boolean isVoidArrayType(Type type){
- if (! type.isArrayType())
- return false;
-
- ArrayType arrayType= (ArrayType)type;
- if (! arrayType.getComponentType().isPrimitiveType())
- return false;
- PrimitiveType primitiveType= (PrimitiveType)arrayType.getComponentType();
- return (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID);
- }
-
- }
-
- private static Type parseType(String typeString, IJavaScriptProject javaProject, List/*<IProblem>*/ problemsCollector) {
- if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$
- return null;
- if (! typeString.trim().equals(typeString))
- return null;
-
- StringBuffer cuBuff= new StringBuffer();
- cuBuff.append("interface A{"); //$NON-NLS-1$
- int offset= cuBuff.length();
- cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$
-
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(cuBuff.toString().toCharArray());
- p.setProject(javaProject);
- JavaScriptUnit cu= (JavaScriptUnit) p.createAST(null);
- Selection selection= Selection.createFromStartLength(offset, typeString.length());
- SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
- cu.accept(analyzer);
- ASTNode selected= analyzer.getFirstSelectedNode();
- if (!(selected instanceof Type))
- return null;
- Type type= (Type)selected;
- if (MethodTypesSyntaxChecker.isVoidArrayType(type))
- return null;
- IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
- if (problems.length > 0) {
- for (int i= 0; i < problems.length; i++)
- problemsCollector.add(problems[i].getMessage());
- }
-
- String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
- if (typeString.equals(typeNodeRange))
- return type;
- else
- return null;
- }
-
- private static ITypeBinding handleBug84585(ITypeBinding typeBinding) {
- if (typeBinding == null)
- return null;
- else
- return typeBinding;
- }
-
- public static RefactoringStatus[] checkAndResolveMethodTypes(IFunction method, StubTypeContext stubTypeContext, List parameterInfos, ReturnTypeInfo returnTypeInfo, IProblemVerifier problemVerifier) throws CoreException {
- MethodTypesChecker checker= new MethodTypesChecker(method, stubTypeContext, parameterInfos, returnTypeInfo, problemVerifier);
- return checker.checkAndResolveMethodTypes();
- }
-
- public static RefactoringStatus[] checkMethodTypesSyntax(IFunction method, List parameterInfos, ReturnTypeInfo returnTypeInfo) {
- MethodTypesSyntaxChecker checker= new MethodTypesSyntaxChecker(method, parameterInfos, returnTypeInfo);
- return checker.checkSyntax();
- }
-
- public static RefactoringStatus checkParameterTypeSyntax(String type, IJavaScriptProject project) {
- String newTypeName= ParameterInfo.stripEllipsis(type.trim()).trim();
-
- if ("".equals(newTypeName.trim())){ //$NON-NLS-1$
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_parameter_type, new String[]{type});
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
-
- if (ParameterInfo.isVarargs(type) && ! JavaModelUtil.is50OrHigher(project)) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_no_vararg_below_50, new String[]{type});
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
-
- List problemsCollector= new ArrayList(0);
- Type parsedType= parseType(newTypeName, project, problemsCollector);
- boolean valid= parsedType != null;
- if (valid && parsedType instanceof PrimitiveType)
- valid= ! PrimitiveType.VOID.equals(((PrimitiveType) parsedType).getPrimitiveTypeCode());
- if (! valid) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_type_name, new String[]{newTypeName});
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- if (problemsCollector.size() == 0)
- return null;
-
- RefactoringStatus result= new RefactoringStatus();
- for (Iterator iter= problemsCollector.iterator(); iter.hasNext();) {
- String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_invalid_type_syntax, new String[]{newTypeName, (String) iter.next()});
- result.addError(msg);
- }
- return result;
- }
-
- public static StubTypeContext createStubTypeContext(IJavaScriptUnit cu, JavaScriptUnit root, int focalPosition) throws CoreException {
- IDocument document= RefactoringFileBuffers.acquire(cu).getDocument();
- try {
- StringBuffer bufBefore= new StringBuffer();
- StringBuffer bufAfter= new StringBuffer();
-
- int introEnd= 0;
- PackageDeclaration pack= root.getPackage();
- if (pack != null)
- introEnd= pack.getStartPosition() + pack.getLength();
- List imports= root.imports();
- if (imports.size() > 0) {
- ImportDeclaration lastImport= (ImportDeclaration) imports.get(imports.size() - 1);
- introEnd= lastImport.getStartPosition() + lastImport.getLength();
- }
- try {
- bufBefore.append(document.get(0, introEnd));
- } catch (BadLocationException e) {
- throw new RuntimeException(e); // doesn't happen
- }
-
- fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types());
- bufBefore.append(' ');
- bufAfter.insert(0, ' ');
- return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString());
-
- } finally {
- RefactoringFileBuffers.release(cu);
- }
- }
-
- private static void fillWithTypeStubs(final StringBuffer bufBefore, final StringBuffer bufAfter, final int focalPosition, List/*<? extends BodyDeclaration>*/ types) {
- StringBuffer buf;
- for (Iterator iter= types.iterator(); iter.hasNext();) {
- BodyDeclaration bodyDeclaration= (BodyDeclaration) iter.next();
- if (! (bodyDeclaration instanceof AbstractTypeDeclaration)) {
- //account for local classes:
- if (! (bodyDeclaration instanceof FunctionDeclaration))
- continue;
- int bodyStart= bodyDeclaration.getStartPosition();
- int bodyEnd= bodyDeclaration.getStartPosition() + bodyDeclaration.getLength();
- if (! (bodyStart < focalPosition && focalPosition < bodyEnd))
- continue;
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) bodyDeclaration;
- buf= bufBefore;
- appendModifiers(buf, methodDeclaration.modifiers());
- buf.append(" void "); //$NON-NLS-1$
- buf.append(methodDeclaration.getName().getIdentifier());
- buf.append("(){\n"); //$NON-NLS-1$
- Block body= methodDeclaration.getBody();
- body.accept(new HierarchicalASTVisitor() {
- public boolean visit(AbstractTypeDeclaration node) {
- fillWithTypeStubs(bufBefore, bufAfter, focalPosition, Collections.singletonList(node));
- return false;
- }
- public boolean visit(ClassInstanceCreation node) {
- AnonymousClassDeclaration anonDecl= node.getAnonymousClassDeclaration();
- if (anonDecl == null)
- return false;
- int anonStart= anonDecl.getStartPosition();
- int anonEnd= anonDecl.getStartPosition() + anonDecl.getLength();
- if (! (anonStart < focalPosition && focalPosition < anonEnd))
- return false;
- bufBefore.append(" new "); //$NON-NLS-1$
- bufBefore.append(node.getType().toString());
- bufBefore.append("(){\n"); //$NON-NLS-1$
- fillWithTypeStubs(bufBefore, bufAfter, focalPosition, anonDecl.bodyDeclarations());
- bufAfter.insert(0, "};\n"); //$NON-NLS-1$
- return false;
- }
- });
- buf= bufAfter;
- buf.append("}\n"); //$NON-NLS-1$
- continue;
- }
-
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) bodyDeclaration;
- buf= decl.getStartPosition() < focalPosition ? bufBefore : bufAfter;
- appendModifiers(buf, decl.modifiers());
-
- if (decl instanceof TypeDeclaration) {
- TypeDeclaration type= (TypeDeclaration) decl;
- buf.append("class "); //$NON-NLS-1$
- buf.append(type.getName().getIdentifier());
- if (type.getSuperclassType() != null) {
- buf.append(" extends "); //$NON-NLS-1$
- buf.append(ASTNodes.asString(type.getSuperclassType()));
- }
- }
-
- buf.append("{\n"); //$NON-NLS-1$
- fillWithTypeStubs(bufBefore, bufAfter, focalPosition, decl.bodyDeclarations());
- buf= decl.getStartPosition() + decl.getLength() < focalPosition ? bufBefore : bufAfter;
- buf.append("}\n"); //$NON-NLS-1$
- }
- }
-
- private static void appendModifiers(StringBuffer buf, List modifiers) {
- for (Iterator iterator= modifiers.iterator(); iterator.hasNext();) {
- IExtendedModifier extendedModifier= (IExtendedModifier) iterator.next();
- if (extendedModifier.isModifier()) {
- Modifier modifier= (Modifier) extendedModifier;
- buf.append(modifier.getKeyword().toString()).append(' ');
- }
- }
- }
-
- public static StubTypeContext createSuperInterfaceStubTypeContext(String typeName, IType enclosingType, IPackageFragment packageFragment) {
- return createSupertypeStubTypeContext(typeName, true, enclosingType, packageFragment);
- }
-
- public static StubTypeContext createSuperClassStubTypeContext(String typeName, IType enclosingType, IPackageFragment packageFragment) {
- return createSupertypeStubTypeContext(typeName, false, enclosingType, packageFragment);
- }
-
- private static StubTypeContext createSupertypeStubTypeContext(String typeName, boolean isInterface, IType enclosingType, IPackageFragment packageFragment) {
- StubTypeContext stubTypeContext;
- String prolog= "class " + typeName + (isInterface ? " implements " : " extends "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- String epilog= " {} "; //$NON-NLS-1$
- if (enclosingType != null) {
- try {
- IJavaScriptUnit cu= enclosingType.getJavaScriptUnit();
- ISourceRange typeSourceRange= enclosingType.getSourceRange();
- int focalPosition= typeSourceRange.getOffset() + typeSourceRange.getLength() - 1; // before closing brace
-
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(cu);
- parser.setFocalPosition(focalPosition);
- JavaScriptUnit compilationUnit= (JavaScriptUnit) parser.createAST(null);
-
- stubTypeContext= createStubTypeContext(cu, compilationUnit, focalPosition);
- stubTypeContext= new StubTypeContext(stubTypeContext.getCuHandle(),
- stubTypeContext.getBeforeString() + prolog,
- epilog + stubTypeContext.getAfterString());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- stubTypeContext= new StubTypeContext(null, null, null);
- }
-
- } else if (packageFragment != null) {
- IJavaScriptUnit cu= packageFragment.getJavaScriptUnit(JavaTypeCompletionProcessor.DUMMY_CU_NAME);
- stubTypeContext= new StubTypeContext(cu, "package " + packageFragment.getElementName() + ";" + prolog, epilog); //$NON-NLS-1$//$NON-NLS-2$
-
- } else {
- stubTypeContext= new StubTypeContext(null, null, null);
- }
- return stubTypeContext;
- }
-
- public static Type parseSuperClass(String superClass) {
- return parseSuperType(superClass, false);
- }
-
- public static Type parseSuperInterface(String superInterface) {
- return parseSuperType(superInterface, true);
- }
-
- private static Type parseSuperType(String superType, boolean isInterface) {
- if (! superType.trim().equals(superType)) {
- return null;
- }
-
- StringBuffer cuBuff= new StringBuffer();
- if (isInterface)
- cuBuff.append("class __X__ implements "); //$NON-NLS-1$
- else
- cuBuff.append("class __X__ extends "); //$NON-NLS-1$
- int offset= cuBuff.length();
- cuBuff.append(superType).append(" {}"); //$NON-NLS-1$
-
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(cuBuff.toString().toCharArray());
- Map options= new HashMap();
- JavaModelUtil.set50CompilanceOptions(options);
- p.setCompilerOptions(options);
- JavaScriptUnit cu= (JavaScriptUnit) p.createAST(null);
- ASTNode selected= NodeFinder.perform(cu, offset, superType.length());
- if (selected instanceof Name)
- selected= selected.getParent();
- if (selected.getStartPosition() != offset
- || selected.getLength() != superType.length()
- || ! (selected instanceof Type)
- || selected instanceof PrimitiveType) {
- return null;
- }
- Type type= (Type) selected;
-
- String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
- if (! superType.equals(typeNodeRange)){
- return null;
- }
- return type;
- }
-
- public static ITypeBinding resolveSuperClass(String superclass, IType typeHandle, StubTypeContext superClassContext) {
- StringBuffer cuString= new StringBuffer();
- cuString.append(superClassContext.getBeforeString());
- cuString.append(superclass);
- cuString.append(superClassContext.getAfterString());
-
- try {
- IJavaScriptUnit wc= typeHandle.getJavaScriptUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
- try {
- wc.getBuffer().setContents(cuString.toString());
- JavaScriptUnit compilationUnit= new RefactoringASTParser(AST.JLS3).parse(wc, true);
- ASTNode type= NodeFinder.perform(compilationUnit, superClassContext.getBeforeString().length(),
- superclass.length());
- if (type instanceof Type) {
- return handleBug84585(((Type) type).resolveBinding());
- } else if (type instanceof Name) {
- ASTNode parent= type.getParent();
- if (parent instanceof Type)
- return handleBug84585(((Type) parent).resolveBinding());
- }
- throw new IllegalStateException();
- } finally {
- wc.discardWorkingCopy();
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
-
- public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) {
- ITypeBinding[] result= new ITypeBinding[interfaces.length];
-
- int[] interfaceOffsets= new int[interfaces.length];
- StringBuffer cuString= new StringBuffer();
- cuString.append(superInterfaceContext.getBeforeString());
- int last= interfaces.length - 1;
- for (int i= 0; i <= last; i++) {
- interfaceOffsets[i]= cuString.length();
- cuString.append(interfaces[i]);
- if (i != last)
- cuString.append(", "); //$NON-NLS-1$
- }
- cuString.append(superInterfaceContext.getAfterString());
-
- try {
- IJavaScriptUnit wc= typeHandle.getJavaScriptUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
- try {
- wc.getBuffer().setContents(cuString.toString());
- JavaScriptUnit compilationUnit= new RefactoringASTParser(AST.JLS3).parse(wc, true);
- for (int i= 0; i <= last; i++) {
- ASTNode type= NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length());
- if (type instanceof Type) {
- result[i]= handleBug84585(((Type) type).resolveBinding());
- } else if (type instanceof Name) {
- ASTNode parent= type.getParent();
- if (parent instanceof Type) {
- result[i]= handleBug84585(((Type) parent).resolveBinding());
- } else {
- throw new IllegalStateException();
- }
- } else {
- throw new IllegalStateException();
- }
- }
- } finally {
- wc.discardWorkingCopy();
- }
- } catch (JavaScriptModelException e) {
- // won't happen
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypedSource.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypedSource.java
deleted file mode 100644
index 7b2fb2f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/TypedSource.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-
-/**
- * A tuple used to keep source of an element and its type.
- * @see IJavaScriptElement
- * @see org.eclipse.wst.jsdt.core.ISourceReference
- */
-public class TypedSource {
-
- private static class SourceTuple {
-
- private SourceTuple(IJavaScriptUnit unit) {
- this.unit= unit;
- }
- private IJavaScriptUnit unit;
- private JavaScriptUnit node;
- }
-
- private final String fSource;
- private final int fType;
-
- private TypedSource(String source, int type){
- Assert.isNotNull(source);
- Assert.isTrue(canCreateForType(type));
- fSource= source;
- fType= type;
- }
-
- public static TypedSource create(String source, int type) {
- if (source == null || ! canCreateForType(type))
- return null;
- return new TypedSource(source, type);
- }
-
- public String getSource() {
- return fSource;
- }
-
- public int getType() {
- return fType;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (! (other instanceof TypedSource))
- return false;
-
- TypedSource ts= (TypedSource)other;
- return ts.getSource().equals(getSource()) && ts.getType() == getType();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getSource().hashCode() ^ (97 * getType());
- }
-
- private static boolean canCreateForType(int type){
- return type == IJavaScriptElement.FIELD
- || type == IJavaScriptElement.TYPE
- || type == IJavaScriptElement.IMPORT_CONTAINER
- || type == IJavaScriptElement.IMPORT_DECLARATION
- || type == IJavaScriptElement.INITIALIZER
- || type == IJavaScriptElement.METHOD;
- }
-
-
- public static void sortByType(TypedSource[] typedSources){
- Arrays.sort(typedSources, createTypeComparator());
- }
-
- public static Comparator createTypeComparator() {
- return new Comparator(){
- public int compare(Object arg0, Object arg1) {
- return ((TypedSource)arg0).getType() - ((TypedSource)arg1).getType();
- }
- };
- }
- public static TypedSource[] createTypedSources(IJavaScriptElement[] javaElements) throws CoreException {
- //Map<IJavaScriptUnit, List<IJavaScriptElement>>
- Map grouped= ReorgUtils.groupByCompilationUnit(Arrays.asList(javaElements));
- List result= new ArrayList(javaElements.length);
- for (Iterator iter= grouped.keySet().iterator(); iter.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit) iter.next();
- for (Iterator iterator= ((List) grouped.get(cu)).iterator(); iterator.hasNext();) {
- SourceTuple tuple= new SourceTuple(cu);
- TypedSource[] ts= createTypedSources((IJavaScriptElement) iterator.next(), tuple);
- if (ts != null)
- result.addAll(Arrays.asList(ts));
- }
- }
- return (TypedSource[]) result.toArray(new TypedSource[result.size()]);
- }
-
- private static TypedSource[] createTypedSources(IJavaScriptElement elem, SourceTuple tuple) throws CoreException {
- if (! ReorgUtils.isInsideCompilationUnit(elem))
- return null;
- if (elem.getElementType() == IJavaScriptElement.IMPORT_CONTAINER)
- return createTypedSourcesForImportContainer(tuple, (IImportContainer)elem);
- else if (elem.getElementType() == IJavaScriptElement.FIELD)
- return new TypedSource[] {create(getFieldSource((IField)elem, tuple), elem.getElementType())};
- return new TypedSource[] {create(getSourceOfDeclararationNode(elem, tuple.unit), elem.getElementType())};
- }
-
- private static TypedSource[] createTypedSourcesForImportContainer(SourceTuple tuple, IImportContainer container) throws JavaScriptModelException, CoreException {
- IJavaScriptElement[] imports= container.getChildren();
- List result= new ArrayList(imports.length);
- for (int i= 0; i < imports.length; i++) {
- result.addAll(Arrays.asList(createTypedSources(imports[i], tuple)));
- }
- return (TypedSource[]) result.toArray(new TypedSource[result.size()]);
- }
-
- private static String getFieldSource(IField field, SourceTuple tuple) throws CoreException {
- if (tuple.node == null) {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(tuple.unit);
- tuple.node= (JavaScriptUnit) parser.createAST(null);
- }
- FieldDeclaration declaration= ASTNodeSearchUtil.getFieldDeclarationNode(field, tuple.node);
- if (declaration.fragments().size() == 1)
- return getSourceOfDeclararationNode(field, tuple.unit);
- VariableDeclarationFragment declarationFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, tuple.node);
- IBuffer buffer= tuple.unit.getBuffer();
- StringBuffer buff= new StringBuffer();
- buff.append(buffer.getText(declaration.getStartPosition(), ((ASTNode) declaration.fragments().get(0)).getStartPosition() - declaration.getStartPosition()));
- buff.append(buffer.getText(declarationFragment.getStartPosition(), declarationFragment.getLength()));
- buff.append(";"); //$NON-NLS-1$
- return buff.toString();
- }
-
- private static String getSourceOfDeclararationNode(IJavaScriptElement elem, IJavaScriptUnit cu) throws JavaScriptModelException, CoreException {
- Assert.isTrue(elem.getElementType() != IJavaScriptElement.IMPORT_CONTAINER);
- if (elem instanceof ISourceReference) {
- ISourceReference reference= (ISourceReference) elem;
- String source= reference.getSource();
- if (source != null)
- return Strings.trimIndentation(source, cu.getJavaScriptProject(), false);
- }
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JDTChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JDTChange.java
deleted file mode 100644
index 07be3d01..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JDTChange.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.base;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension4;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-/**
- * JDT specific change object.
- */
-public abstract class JDTChange extends Change {
-
- private long fModificationStamp;
- private boolean fReadOnly;
-
- private static class ValidationState {
- private IResource fResource;
- private int fKind;
- private boolean fDirty;
- private boolean fReadOnly;
- private long fModificationStamp;
- private ITextFileBuffer fTextFileBuffer;
- public static final int RESOURCE= 1;
- public static final int DOCUMENT= 2;
- public ValidationState(IResource resource) {
- fResource= resource;
- if (resource instanceof IFile) {
- initializeFile((IFile)resource);
- } else {
- initializeResource(resource);
- }
- }
- public void checkDirty(RefactoringStatus status, long stampToMatch, IProgressMonitor pm) throws CoreException {
- if (fDirty) {
- if (fKind == DOCUMENT && fTextFileBuffer != null && stampToMatch == fModificationStamp) {
- fTextFileBuffer.commit(pm, false);
- } else {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_is_unsaved, fResource.getFullPath().toString()));
- }
- }
- }
- public void checkDirty(RefactoringStatus status) {
- if (fDirty) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_is_unsaved, fResource.getFullPath().toString()));
- }
- }
- public void checkReadOnly(RefactoringStatus status) {
- if (fReadOnly) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_is_read_only, fResource.getFullPath().toString()));
- }
- }
- public void checkSameReadOnly(RefactoringStatus status, boolean valueToMatch) {
- if (fReadOnly != valueToMatch) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_same_read_only,
- fResource.getFullPath().toString()));
- }
- }
- public void checkModificationStamp(RefactoringStatus status, long stampToMatch) {
- if (fKind == DOCUMENT) {
- if (stampToMatch != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && fModificationStamp != stampToMatch) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_has_modifications, fResource.getFullPath().toString()));
- }
- } else {
- if (stampToMatch != IResource.NULL_STAMP && fModificationStamp != stampToMatch) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_has_modifications, fResource.getFullPath().toString()));
-
- }
- }
- }
- private void initializeFile(IFile file) {
- fTextFileBuffer= getBuffer(file);
- if (fTextFileBuffer == null) {
- initializeResource(file);
- } else {
- IDocument document= fTextFileBuffer.getDocument();
- fDirty= fTextFileBuffer.isDirty();
- fReadOnly= Resources.isReadOnly(file);
- if (document instanceof IDocumentExtension4) {
- fKind= DOCUMENT;
- fModificationStamp= ((IDocumentExtension4)document).getModificationStamp();
- } else {
- fKind= RESOURCE;
- fModificationStamp= file.getModificationStamp();
- }
- }
-
- }
- private void initializeResource(IResource resource) {
- fKind= RESOURCE;
- fDirty= false;
- fReadOnly= Resources.isReadOnly(resource);
- fModificationStamp= resource.getModificationStamp();
- }
- }
-
- protected static final int NONE= 0;
- protected static final int READ_ONLY= 1 << 0;
- protected static final int DIRTY= 1 << 1;
- private static final int SAVE= 1 << 2;
- protected static final int SAVE_IF_DIRTY= SAVE | DIRTY;
-
- protected JDTChange() {
- fModificationStamp= IResource.NULL_STAMP;
- fReadOnly= false;
- }
-
- public void initializeValidationData(IProgressMonitor pm) {
- IResource resource= getResource(getModifiedElement());
- if (resource != null) {
- fModificationStamp= getModificationStamp(resource);
- fReadOnly= Resources.isReadOnly(resource);
- }
- }
-
- // protected final RefactoringStatus isValid(IProgressMonitor pm, boolean checkReadOnly, boolean checkDirty) throws CoreException {
- protected final RefactoringStatus isValid(IProgressMonitor pm, int flags) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- try {
- RefactoringStatus result= new RefactoringStatus();
- Object modifiedElement= getModifiedElement();
- checkExistence(result, modifiedElement);
- if (result.hasFatalError())
- return result;
- if (flags == NONE)
- return result;
- IResource resource= getResource(modifiedElement);
- if (resource != null) {
- ValidationState state= new ValidationState(resource);
- state.checkModificationStamp(result, fModificationStamp);
- if (result.hasFatalError())
- return result;
- state.checkSameReadOnly(result, fReadOnly);
- if (result.hasFatalError())
- return result;
- if ((flags & READ_ONLY) != 0) {
- state.checkReadOnly(result);
- if (result.hasFatalError())
- return result;
- }
- if ((flags & DIRTY) != 0) {
- if ((flags & SAVE) != 0) {
- state.checkDirty(result, fModificationStamp, new SubProgressMonitor(pm, 1));
- } else {
- state.checkDirty(result);
- }
- }
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- protected static void checkIfModifiable(RefactoringStatus status, Object element, int flags) {
- checkIfModifiable(status, getResource(element), flags);
- }
-
- protected static void checkIfModifiable(RefactoringStatus result, IResource resource, int flags) {
- checkExistence(result, resource);
- if (result.hasFatalError())
- return;
- if (flags == NONE)
- return;
- ValidationState state= new ValidationState(resource);
- if ((flags & READ_ONLY) != 0) {
- state.checkReadOnly(result);
- if (result.hasFatalError())
- return;
- }
- if ((flags & DIRTY) != 0) {
- state.checkDirty(result);
- }
- }
-
- protected static void checkExistence(RefactoringStatus status, Object element) {
- if (element == null) {
- status.addFatalError(RefactoringCoreMessages.DynamicValidationStateChange_workspace_changed);
-
- } else if (element instanceof IResource && !((IResource)element).exists()) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_does_not_exist, ((IResource)element).getFullPath().toString()));
- } else if (element instanceof IJavaScriptElement && !((IJavaScriptElement)element).exists()) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.Change_does_not_exist, ((IJavaScriptElement)element).getElementName()));
- }
- }
-
- private static IResource getResource(Object element) {
- if (element instanceof IResource) {
- return (IResource)element;
- }
- if (element instanceof IJavaScriptUnit) {
- return ((IJavaScriptUnit)element).getPrimary().getResource();
- }
- if (element instanceof IJavaScriptElement) {
- return ((IJavaScriptElement)element).getResource();
- }
- if (element instanceof IAdaptable) {
- return (IResource)((IAdaptable)element).getAdapter(IResource.class);
- }
- return null;
- }
-
- public String toString() {
- return getName();
- }
-
- public long getModificationStamp(IResource resource) {
- if (!(resource instanceof IFile))
- return resource.getModificationStamp();
- IFile file= (IFile)resource;
- ITextFileBuffer buffer= getBuffer(file);
- if (buffer == null) {
- return file.getModificationStamp();
- } else {
- IDocument document= buffer.getDocument();
- if (document instanceof IDocumentExtension4) {
- return ((IDocumentExtension4)document).getModificationStamp();
- } else {
- return file.getModificationStamp();
- }
- }
- }
-
- private static ITextFileBuffer getBuffer(IFile file) {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- return manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStatusContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStatusContext.java
deleted file mode 100644
index 5647cc38..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStatusContext.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.base;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-
-/**
- * A Java element context that can be used to annotate a </code>RefactoringStatusEntry<code>
- * with detailed information about an error detected in an <code>IJavaScriptElement</code>.
- */
-public abstract class JavaStatusContext extends RefactoringStatusContext {
-
- private static class MemberSourceContext extends JavaStatusContext {
- private IMember fMember;
- private MemberSourceContext(IMember member) {
- fMember= member;
- }
- public boolean isBinary() {
- return fMember.isBinary();
- }
- public IJavaScriptUnit getCompilationUnit() {
- return fMember.getJavaScriptUnit();
- }
- public IClassFile getClassFile() {
- return fMember.getClassFile();
- }
- public ISourceRange getSourceRange() {
- try {
- return fMember.getSourceRange();
- } catch (JavaScriptModelException e) {
- return new SourceRange(0,0);
- }
- }
- }
-
- private static class ImportDeclarationSourceContext extends JavaStatusContext {
- private IImportDeclaration fImportDeclartion;
- private ImportDeclarationSourceContext(IImportDeclaration declaration) {
- fImportDeclartion= declaration;
- }
- public boolean isBinary() {
- return false;
- }
- public IJavaScriptUnit getCompilationUnit() {
- return (IJavaScriptUnit)fImportDeclartion.getParent().getParent();
- }
- public IClassFile getClassFile() {
- return null;
- }
- public ISourceRange getSourceRange() {
- try {
- return fImportDeclartion.getSourceRange();
- } catch (JavaScriptModelException e) {
- return new SourceRange(0,0);
- }
- }
- }
-
- private static class CompilationUnitSourceContext extends JavaStatusContext {
- private IJavaScriptUnit fCUnit;
- private ISourceRange fSourceRange;
- private CompilationUnitSourceContext(IJavaScriptUnit cunit, ISourceRange range) {
- fCUnit= cunit;
- fSourceRange= range;
- if (fSourceRange == null)
- fSourceRange= new SourceRange(0,0);
- }
- public boolean isBinary() {
- return false;
- }
- public IJavaScriptUnit getCompilationUnit() {
- return fCUnit;
- }
- public IClassFile getClassFile() {
- return null;
- }
- public ISourceRange getSourceRange() {
- return fSourceRange;
- }
- public String toString() {
- return getSourceRange() + " in " + super.toString(); //$NON-NLS-1$
- }
- }
-
- private static class ClassFileSourceContext extends JavaStatusContext {
- private IClassFile fClassFile;
- private ISourceRange fSourceRange;
- private ClassFileSourceContext(IClassFile classFile, ISourceRange range) {
- fClassFile= classFile;
- fSourceRange= range;
- if (fSourceRange == null)
- fSourceRange= new SourceRange(0,0);
- }
- public boolean isBinary() {
- return true;
- }
- public IJavaScriptUnit getCompilationUnit() {
- return null;
- }
- public IClassFile getClassFile() {
- return fClassFile;
- }
- public ISourceRange getSourceRange() {
- return fSourceRange;
- }
- public String toString() {
- return getSourceRange() + " in " + super.toString(); //$NON-NLS-1$
- }
- }
-
- /**
- * Creates an status entry context for the given member
- *
- * @param member the java member for which the context is supposed
- * to be created
- * @return the status entry context or <code>null</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(IMember member) {
- if (member == null || !member.exists())
- return null;
- return new MemberSourceContext(member);
- }
-
- /**
- * Creates an status entry context for the given import declaration
- *
- * @param declaration the import declaration for which the context is
- * supposed to be created
- * @return the status entry context or <code>null</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(IImportDeclaration declaration) {
- if (declaration == null || !declaration.exists())
- return null;
- return new ImportDeclarationSourceContext(declaration);
- }
-
- /**
- * Creates an status entry context for the given method binding
- *
- * @param method the method binding for which the context is supposed to be created
- * @return the status entry context or <code>Context.NULL_CONTEXT</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(IFunctionBinding method) {
- return create((IFunction) method.getJavaElement());
- }
-
- /**
- * Creates an status entry context for the given type root.
- *
- * @param typeRoot the type root containing the error
- * @return the status entry context or <code>Context.NULL_CONTEXT</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(ITypeRoot typeRoot) {
- return create(typeRoot, (ISourceRange)null);
- }
-
- /**
- * Creates an status entry context for the given type root and source range.
- *
- * @param typeRoot the type root containing the error
- * @param range the source range that has caused the error or
- * <code>null</code> if the source range is unknown
- * @return the status entry context or <code>null</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(ITypeRoot typeRoot, ISourceRange range) {
- if (typeRoot instanceof IJavaScriptUnit)
- return new CompilationUnitSourceContext((IJavaScriptUnit) typeRoot, range);
- else if (typeRoot instanceof IClassFile)
- return new ClassFileSourceContext((IClassFile) typeRoot, range);
- else
- return null;
- }
-
- /**
- * Creates an status entry context for the given type root and AST node.
- *
- * @param typeRoot the type root containing the error
- * @param node an astNode denoting the source range that has caused the error
- *
- * @return the status entry context or <code>Context.NULL_CONTEXT</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(ITypeRoot typeRoot, ASTNode node) {
- ISourceRange range= null;
- if (node != null)
- range= new SourceRange(node.getStartPosition(), node.getLength());
- return create(typeRoot, range);
- }
-
- /**
- * Creates an status entry context for the given type root and selection.
- *
- * @param typeRoot the type root containing the error
- * @param selection a selection denoting the source range that has caused the error
- *
- * @return the status entry context or <code>Context.NULL_CONTEXT</code> if the
- * context cannot be created
- */
- public static RefactoringStatusContext create(ITypeRoot typeRoot, Selection selection) {
- ISourceRange range= null;
- if (selection != null)
- range= new SourceRange(selection.getOffset(), selection.getLength());
- return create(typeRoot, range);
- }
-
- /**
- * Returns whether this context is for a class file.
- *
- * @return <code>true</code> if from a class file, and <code>false</code> if
- * from a compilation unit
- */
- public abstract boolean isBinary();
-
- /**
- * Returns the compilation unit this context is working on. Returns <code>null</code>
- * if the context is a binary context.
- *
- * @return the compilation unit
- */
- public abstract IJavaScriptUnit getCompilationUnit();
-
- /**
- * Returns the class file this context is working on. Returns <code>null</code>
- * if the context is not a binary context.
- *
- * @return the class file
- */
- public abstract IClassFile getClassFile();
-
- /**
- * Returns the source range associated with this element.
- *
- * @return the source range
- */
- public abstract ISourceRange getSourceRange();
-
- /* (non-Javadoc)
- * Method declared on Context.
- */
- public Object getCorrespondingElement() {
- if (isBinary())
- return getClassFile();
- else
- return getCompilationUnit();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStringStatusContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStringStatusContext.java
deleted file mode 100644
index 9c9f35de..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/JavaStringStatusContext.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.base;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-
-/**
- * A Java string context can be used to annotate a </code>RefactoringStatusEntry<code>
- * with detailed information about an error detected in Java source code represented
- * by a string.
- */
-public class JavaStringStatusContext extends RefactoringStatusContext {
-
- private String fSource;
- private ISourceRange fSourceRange;
-
- /**
- * Creates a new <code>JavaStringStatusContext</code>.
- *
- * @param source the source code containing the error
- * @param range a source range inside <code>source</code> or
- * <code>null</code> if no special source range is known.
- */
- public JavaStringStatusContext(String source, ISourceRange range){
- Assert.isNotNull(source);
- fSource= source;
- fSourceRange= range;
- }
-
- public String getSource() {
- return fSource;
- }
-
- public ISourceRange getSourceRange() {
- return fSourceRange;
- }
-
- /* (non-Javadoc)
- * @see RefactoringStatusContext#getCorrespondingElement()
- */
- public Object getCorrespondingElement() {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/RefactoringStatusCodes.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/RefactoringStatusCodes.java
deleted file mode 100644
index d4c7947d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/base/RefactoringStatusCodes.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.base;
-
-public class RefactoringStatusCodes {
-
- private RefactoringStatusCodes() {
- }
-
- public static final int OVERRIDES_ANOTHER_METHOD= 1;
- public static final int METHOD_DECLARED_IN_INTERFACE= 2;
-
- public static final int EXPRESSION_NOT_RVALUE= 64;
- public static final int EXPRESSION_NOT_RVALUE_VOID= 65;
- public static final int EXTRANEOUS_TEXT= 66;
-
- public static final int NOT_STATIC_FINAL_SELECTED= 128;
- public static final int SYNTAX_ERRORS= 129;
- public static final int DECLARED_IN_CLASSFILE= 130;
- public static final int CANNOT_INLINE_BLANK_FINAL= 131;
- public static final int LOCAL_AND_ANONYMOUS_NOT_SUPPORTED= 132;
- public static final int REFERENCE_IN_CLASSFILE= 133;
-
- public static final int NATIVE_METHOD= 192;
- public static final int MAIN_METHOD= 193;
-
- // inline method error codes
- public static final int INLINE_METHOD_FIELD_INITIALIZER= 256;
- public static final int INLINE_METHOD_LOCAL_INITIALIZER= 257;
- public static final int INLINE_METHOD_NULL_BINDING= 258;
- public static final int INLINE_METHOD_ONLY_SIMPLE_FUNCTIONS= 259;
- public static final int INLINE_METHOD_EXECUTION_FLOW= 260;
- public static final int INLINE_METHOD_INITIALIZER_IN_FRAGEMENT= 261;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/AbstractCodeCreationOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/AbstractCodeCreationOperation.java
deleted file mode 100644
index 2c8453ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/AbstractCodeCreationOperation.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.binary;
-
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.URI;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Partial implementation of a code creation operation.
- *
- *
- */
-public abstract class AbstractCodeCreationOperation implements IWorkspaceRunnable {
-
- /** The URI where to output the stubs */
- protected final URI fOutputURI;
-
- /** The list of packages to create stubs for */
- protected final List fPackages;
-
- /**
- * Creates a new abstract code creation operation.
- *
- * @param uri
- * the URI where to output the code
- * @param packages
- * the list of packages to create code for
- */
- protected AbstractCodeCreationOperation(final URI uri, final List packages) {
- Assert.isNotNull(uri);
- Assert.isNotNull(packages);
- fOutputURI= uri;
- fPackages= packages;
- }
-
- /**
- * Creates a new compilation unit with the given contents.
- *
- * @param store
- * the file store
- * @param name
- * the name of the compilation unit
- * @param content
- * the content of the compilation unit
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs while creating the compilation unit
- */
- protected void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor monitor) throws CoreException {
- OutputStream stream= null;
- try {
- stream= new BufferedOutputStream(store.getChild(name).openOutputStream(EFS.NONE, new SubProgressMonitor(monitor, 1)));
- try {
- stream.write(content.getBytes());
- } catch (IOException exception) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, exception.getLocalizedMessage(), exception));
- }
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException exception) {
- // Do nothing
- }
- }
- }
- }
-
- /**
- * Creates a package fragment with the given name.
- *
- * @param store
- * the file store
- * @param name
- * the name of the package
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs while creating the package fragment
- */
- protected void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor monitor) throws CoreException {
- store.mkdir(EFS.NONE, monitor);
- }
-
- /**
- * Returns the operation label.
- *
- * @return the operation label
- */
- protected abstract String getOperationLabel();
-
- /**
- * Runs the stub generation on the specified class file.
- *
- * @param file
- * the class file
- * @param parent
- * the parent store
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs
- */
- protected abstract void run(IClassFile file, IFileStore parent, IProgressMonitor monitor) throws CoreException;
-
- /**
- * {@inheritDoc}
- */
- public void run(IProgressMonitor monitor) throws CoreException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- monitor.beginTask(getOperationLabel(), 100 * fPackages.size());
- try {
- final StringBuffer buffer= new StringBuffer(128);
- for (final Iterator iterator= fPackages.iterator(); iterator.hasNext();) {
- final IPackageFragment fragment= (IPackageFragment) iterator.next();
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100);
- final IClassFile[] files= fragment.getClassFiles();
- final int size= files.length;
- subMonitor.beginTask(getOperationLabel(), size * 50);
- final String name= fragment.getElementName();
- IFileStore store= EFS.getStore(fOutputURI);
- if (!"".equals(name)) { //$NON-NLS-1$
- final String pack= name;
- buffer.setLength(0);
- buffer.append(name);
- final int length= buffer.length();
- for (int index= 0; index < length; index++) {
- if (buffer.charAt(index) == '.')
- buffer.setCharAt(index, '/');
- }
- store= store.getChild(new Path(buffer.toString()));
- if (!pack.startsWith(".")) //$NON-NLS-1$
- createPackageFragment(store, pack, new SubProgressMonitor(subMonitor, 10));
- } else
- createPackageFragment(store, "", new SubProgressMonitor(subMonitor, 10)); //$NON-NLS-1$
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 30);
- try {
- subsubMonitor.beginTask(getOperationLabel(), size * 100);
- for (int index= 0; index < size; index++) {
- if (subMonitor.isCanceled())
- throw new OperationCanceledException();
- run(files[index], store, new SubProgressMonitor(subsubMonitor, 100));
- }
- } finally {
- subsubMonitor.done();
- }
- }
- } finally {
- monitor.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java
deleted file mode 100644
index 270d2f9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.binary;
-
-import java.net.URI;
-import java.util.List;
-
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Operation, which run, creates source code for a list of binary package
- * fragments with attached source.
- *
- *
- */
-public class SourceCreationOperation extends AbstractCodeCreationOperation {
-
- /**
- * Creates a new source creation operation.
- *
- * @param uri
- * the URI where to output the source
- * @param packages
- * the list of packages to create source for
- */
- public SourceCreationOperation(final URI uri, final List packages) {
- super(uri, packages);
- }
-
- /**
- * Returns the operation label.
- *
- * @return the operation label
- */
- protected String getOperationLabel() {
- return RefactoringCoreMessages.SourceCreationOperation_creating_source_folder;
- }
-
- /**
- * Runs the stub generation on the specified class file.
- *
- * @param file
- * the class file
- * @param parent
- * the parent store
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs
- */
- protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(getOperationLabel(), 2);
- final IType type= file.getType();
- if (type.isAnonymous() || type.isLocal() || type.isMember())
- return;
- final String source= file.getSource();
- createCompilationUnit(parent, type.getElementName() + ".java", source != null ? source : "", monitor); //$NON-NLS-1$ //$NON-NLS-2$
- } finally {
- monitor.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java
deleted file mode 100644
index 8a885e20..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.binary;
-
-import java.net.URI;
-import java.util.List;
-
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Operation, which run, creates structurally equivalent stub types for a list
- * of binary package fragments.
- *
- *
- */
-public class StubCreationOperation extends AbstractCodeCreationOperation {
-
- /** Should stubs for private member be generated as well? */
- protected final boolean fStubInvisible;
-
- /**
- * Creates a new stub creation operation.
- *
- * @param uri
- * the URI where to output the stubs
- * @param packages
- * the list of packages to create stubs for
- */
- public StubCreationOperation(final URI uri, final List packages) {
- this(uri, packages, false);
- }
-
- /**
- * Creates a new stub creation operation.
- *
- * @param uri
- * the URI where to output the stubs
- * @param packages
- * the list of packages to create stubs for
- * @param stub
- * <code>true</code> to generate stubs for private and package
- * visible members as well, <code>false</code> otherwise
- */
- public StubCreationOperation(final URI uri, final List packages, final boolean stub) {
- super(uri, packages);
- fStubInvisible= stub;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getOperationLabel() {
- return RefactoringCoreMessages.StubCreationOperation_creating_type_stubs;
- }
-
- /**
- * Runs the stub generation on the specified class file.
- *
- * @param file
- * the class file
- * @param parent
- * the parent store
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs
- */
- protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 2);
- SubProgressMonitor subProgressMonitor= new SubProgressMonitor(monitor, 1);
- final IType type= file.getType();
- if (type.isAnonymous() || type.isLocal() || type.isMember())
- return;
- String source= new StubCreator(fStubInvisible).createStub(type, subProgressMonitor);
- createCompilationUnit(parent, type.getElementName() + ".java", source, monitor); //$NON-NLS-1$
- } finally {
- monitor.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreator.java
deleted file mode 100644
index 1077359a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreator.java
+++ /dev/null
@@ -1,255 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.binary;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class StubCreator {
-
- /** The internal string buffer */
- protected StringBuffer fBuffer;
-
- /** Should stubs for private member be generated as well? */
- protected final boolean fStubInvisible;
-
- public StubCreator(final boolean stubInvisible) {
- fStubInvisible= stubInvisible;
- }
-
- protected void appendEnumConstants(final IType type) throws JavaScriptModelException {
- final IField[] fields= type.getFields();
- final List list= new ArrayList(fields.length);
-
- for (int index= 0; index < list.size(); index++) {
- if (index > 0)
- fBuffer.append(","); //$NON-NLS-1$
- fBuffer.append(((IField) list.get(index)).getElementName());
- }
- fBuffer.append(";"); //$NON-NLS-1$
- }
-
- protected void appendExpression(final String signature) {
- fBuffer.append("("); //$NON-NLS-1$
- fBuffer.append(Signature.toString(signature));
- fBuffer.append(")"); //$NON-NLS-1$
- fBuffer.append("null"); //$NON-NLS-1$
- }
-
- protected void appendFieldDeclaration(final IField field) throws JavaScriptModelException {
- appendFlags(field);
- fBuffer.append(" "); //$NON-NLS-1$
- final String signature= field.getTypeSignature();
- fBuffer.append(Signature.toString(signature));
- fBuffer.append(" "); //$NON-NLS-1$
- fBuffer.append(field.getElementName());
- fBuffer.append(";"); //$NON-NLS-1$
- }
-
- protected void appendFlags(final IMember member) throws JavaScriptModelException {
- int flags= member.getFlags();
- final int kind= member.getElementType();
- if (kind == IJavaScriptElement.TYPE) {
- flags&= ~Flags.AccSuper;
- final IType type= (IType) member;
- if (!type.isMember())
- flags&= ~Flags.AccPrivate;
- }
- if (kind == IJavaScriptElement.METHOD) {
- flags&= ~Flags.AccVarargs;
- }
- if (flags != 0)
- fBuffer.append(Flags.toString(flags));
- }
-
- protected void appendMembers(final IType type, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 1);
- final IJavaScriptElement[] children= type.getChildren();
- for (int index= 0; index < children.length; index++) {
- final IMember child= (IMember) children[index];
- final int flags= child.getFlags();
- final boolean isPrivate= Flags.isPrivate(flags);
- final boolean isDefault= !Flags.isPublic(flags) && !isPrivate;
- final boolean stub= fStubInvisible || (!isPrivate && !isDefault);
- if (child instanceof IType) {
- if (stub)
- appendTypeDeclaration((IType) child, new SubProgressMonitor(monitor, 1));
- } else if (child instanceof IField) {
- if (stub)
- appendFieldDeclaration((IField) child);
- } else if (child instanceof IFunction) {
- final IFunction method= (IFunction) child;
- final String name= method.getElementName();
-
- boolean skip= !stub || name.equals("<clinit>"); //$NON-NLS-1$
- if (method.isConstructor())
- skip= false;
- if (!skip)
- appendMethodDeclaration(method);
- }
- fBuffer.append("\n"); //$NON-NLS-1$
- }
- } finally {
- monitor.done();
- }
- }
-
- protected void appendMethodBody(final IFunction method) throws JavaScriptModelException {
- if (method.isConstructor()) {
- final IType declaringType= method.getDeclaringType();
- String superSignature= declaringType.getSuperclassTypeSignature();
- if (superSignature != null) {
- final IType superclass= declaringType.getJavaScriptProject().findType(Signature.getSignatureQualifier(superSignature), Signature.getSignatureSimpleName(superSignature));
- if (superclass != null) {
- final IFunction[] superMethods= superclass.getFunctions();
- IFunction superConstructor= null;
- final int length= superMethods.length;
- for (int index= 0; index < length; index++) {
- final IFunction superMethod= superMethods[index];
- if (superMethod.isConstructor() && !Flags.isPrivate(superMethod.getFlags())) {
- superConstructor= superMethod;
- break;
- }
- }
- if (superConstructor != null) {
- final String[] superParameters= superConstructor.getParameterTypes();
- final int paramLength= superParameters.length;
- if (paramLength != 0) {
- fBuffer.append("super("); //$NON-NLS-1$
- for (int index= 0; index < paramLength; index++) {
- if (index > 0)
- fBuffer.append(","); //$NON-NLS-1$
- appendExpression(superParameters[index]);
- }
- fBuffer.append(");"); //$NON-NLS-1$
- }
- }
- }
- }
- } else {
- String returnType= method.getReturnType();
- if (!Signature.SIG_VOID.equals(returnType)) {
- fBuffer.append("return "); //$NON-NLS-1$
- appendExpression(returnType);
- fBuffer.append(";"); //$NON-NLS-1$
- }
- }
- }
-
- protected void appendMethodDeclaration(final IFunction method) throws JavaScriptModelException {
- appendFlags(method);
- fBuffer.append(" "); //$NON-NLS-1$
- final String returnType= method.getReturnType();
- if (!method.isConstructor()) {
- fBuffer.append(Signature.toString(returnType));
- fBuffer.append(" "); //$NON-NLS-1$
- }
- fBuffer.append(method.getElementName());
- fBuffer.append("("); //$NON-NLS-1$
- final String[] parameterTypes= method.getParameterTypes();
- final int flags= method.getFlags();
- final boolean varargs= Flags.isVarargs(flags);
- final int parameterLength= parameterTypes.length;
- for (int index= 0; index < parameterLength; index++) {
- if (index > 0)
- fBuffer.append(","); //$NON-NLS-1$
- fBuffer.append(Signature.toString(parameterTypes[index]));
- if (varargs && index == parameterLength - 1) {
- final int length= fBuffer.length();
- if (length >= 2 && fBuffer.indexOf("[]", length - 2) >= 0) //$NON-NLS-1$
- fBuffer.setLength(length - 2);
- fBuffer.append("..."); //$NON-NLS-1$
- }
- fBuffer.append(" "); //$NON-NLS-1$
- appendMethodParameterName(method, index);
- }
- fBuffer.append(")"); //$NON-NLS-1$
- if (Flags.isAbstract(flags))
- fBuffer.append(";"); //$NON-NLS-1$
- else {
- fBuffer.append("{\n"); //$NON-NLS-1$
- appendMethodBody(method);
- fBuffer.append("}"); //$NON-NLS-1$
- }
- }
-
- protected void appendMethodParameterName(IFunction method, int index) {
- fBuffer.append("a"); //$NON-NLS-1$
- fBuffer.append(index);
- }
-
- protected void appendTopLevelType(final IType type, IProgressMonitor subProgressMonitor) throws JavaScriptModelException {
- String packageName= type.getPackageFragment().getElementName();
- if (packageName.length() > 0) {
- fBuffer.append("package "); //$NON-NLS-1$
- fBuffer.append(packageName);
- fBuffer.append(";\n"); //$NON-NLS-1$
- }
- appendTypeDeclaration(type, subProgressMonitor);
- }
-
- protected void appendTypeDeclaration(final IType type, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 1);
- if (type.isClass()) {
- appendFlags(type);
- fBuffer.append(" class "); //$NON-NLS-1$
- fBuffer.append(type.getElementName());
- final String signature= type.getSuperclassTypeSignature();
- if (signature != null) {
- fBuffer.append(" extends "); //$NON-NLS-1$
- fBuffer.append(Signature.toString(signature));
- }
- fBuffer.append("{\n"); //$NON-NLS-1$
- appendMembers(type, new SubProgressMonitor(monitor, 1));
- fBuffer.append("}"); //$NON-NLS-1$
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * @param topLevelType
- * @param monitor
- * progress monitor, can be <code>null</code>
- * @return source stub
- * @throws JavaScriptModelException
- */
- public String createStub(IType topLevelType, IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isTrue(Checks.isTopLevel(topLevelType));
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- fBuffer= new StringBuffer(2046);
- appendTopLevelType(topLevelType, monitor);
- String result= fBuffer.toString();
- fBuffer= null;
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AbstractDeleteChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AbstractDeleteChange.java
deleted file mode 100644
index f7cf5412..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AbstractDeleteChange.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-
-abstract class AbstractDeleteChange extends JDTChange {
-
- protected abstract Change doDelete(IProgressMonitor pm) throws CoreException;
-
- /* non java-doc
- * @see IChange#perform(ChangeContext, IProgressMonitor)
- */
- public final Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.AbstractDeleteChange_deleting, 1);
- Change undo= doDelete(pm);
- return undo;
- } finally {
- pm.done();
- }
- }
-
- protected static void saveFileIfNeeded(IFile file, IProgressMonitor pm) throws CoreException {
- ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
- if (buffer != null && buffer.isDirty() && buffer.isStateValidated() && buffer.isSynchronized()) {
- pm.beginTask("", 2); //$NON-NLS-1$
- buffer.commit(new SubProgressMonitor(pm, 1), false);
- file.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(pm, 1));
- pm.done();
- } else {
- pm.beginTask("", 1); //$NON-NLS-1$
- pm.worked(1);
- pm.done();
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AddToClasspathChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AddToClasspathChange.java
deleted file mode 100644
index fdec213f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/AddToClasspathChange.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-
-public class AddToClasspathChange extends JDTChange {
-
- private IJavaScriptProject fProjectHandle;
- private IIncludePathEntry fEntryToAdd;
-
- public AddToClasspathChange(IJavaScriptProject project, IIncludePathEntry entryToAdd) {
- fProjectHandle= project;
- fEntryToAdd= entryToAdd;
- }
-
- public AddToClasspathChange(IJavaScriptProject project, String sourceFolderName){
- this(project, JavaScriptCore.newSourceEntry(project.getPath().append(sourceFolderName)));
- }
-
- /**
- * Adds a new project class path entry to the project.
- * @param project
- * @param newProjectEntry (must be absolute <code>IPath</code>)
- */
- public AddToClasspathChange(IJavaScriptProject project, IPath newProjectEntry){
- this(project, JavaScriptCore.newProjectEntry(newProjectEntry));
- }
-
- public AddToClasspathChange(IJavaScriptProject project, int entryKind, IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath){
- this(project, createNewClasspathEntry(entryKind, path, sourceAttachmentPath, sourceAttachmentRootPath));
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // .classpath file will be handled by JDT/Core.
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- pm.beginTask(getName(), 1);
- try {
- if (validateClasspath()) {
- getJavaProject().setRawIncludepath(getNewClasspathEntries(), new SubProgressMonitor(pm, 1));
- IPath classpathEntryPath= JavaScriptCore.getResolvedIncludepathEntry(fEntryToAdd).getPath();
- return new DeleteFromClasspathChange(classpathEntryPath, getJavaProject());
- } else {
- return new NullChange();
- }
- } finally {
- pm.done();
- }
- }
-
- public boolean validateClasspath() throws JavaScriptModelException {
- IJavaScriptProject javaProject= getJavaProject();
- IIncludePathEntry[] newClasspathEntries= getNewClasspathEntries();
- return JavaScriptConventions.validateClasspath(javaProject, newClasspathEntries).isOK();
- }
-
- private IIncludePathEntry[] getNewClasspathEntries() throws JavaScriptModelException{
- IIncludePathEntry[] entries= getJavaProject().getRawIncludepath();
- List cp= new ArrayList(entries.length + 1);
- cp.addAll(Arrays.asList(entries));
- cp.add(fEntryToAdd);
- return (IIncludePathEntry[])cp.toArray(new IIncludePathEntry[cp.size()]);
- }
-
- private static IIncludePathEntry createNewClasspathEntry(int kind, IPath path, IPath sourceAttach, IPath sourceAttachRoot){
- switch(kind){
- case IIncludePathEntry.CPE_LIBRARY:
- return JavaScriptCore.newLibraryEntry(path, sourceAttach, sourceAttachRoot);
- case IIncludePathEntry.CPE_PROJECT:
- return JavaScriptCore.newProjectEntry(path);
- case IIncludePathEntry.CPE_SOURCE:
- return JavaScriptCore.newSourceEntry(path);
- case IIncludePathEntry.CPE_VARIABLE:
- return JavaScriptCore.newVariableEntry(path, sourceAttach, sourceAttachRoot);
- case IIncludePathEntry.CPE_CONTAINER:
- return JavaScriptCore.newContainerEntry(path);
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private IJavaScriptProject getJavaProject(){
- return fProjectHandle;
- }
-
- public String getName() {
- return RefactoringCoreMessages.AddToClasspathChange_add + getJavaProject().getElementName();
-
- }
-
- public Object getModifiedElement() {
- return getJavaProject();
- }
-
- public IIncludePathEntry getClasspathEntry() {
- return fEntryToAdd;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitChange.java
deleted file mode 100644
index 23990999..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitChange.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.ContentStamp;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.UndoEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class CompilationUnitChange extends TextFileChange {
-
- private final IJavaScriptUnit fCUnit;
-
- /** The (optional) refactoring descriptor */
- private ChangeDescriptor fDescriptor;
-
- /**
- * Creates a new <code>CompilationUnitChange</code>.
- *
- * @param name the change's name mainly used to render the change in the UI
- * @param cunit the compilation unit this text change works on
- */
- public CompilationUnitChange(String name, IJavaScriptUnit cunit) {
- super(name, getFile(cunit));
- Assert.isNotNull(cunit);
- fCUnit= cunit;
- setTextType("js"); //$NON-NLS-1$
- }
-
- private static IFile getFile(IJavaScriptUnit cunit) {
- return (IFile) cunit.getResource();
- }
-
- /* non java-doc
- * Method declared in IChange.
- */
- public Object getModifiedElement(){
- return fCUnit;
- }
-
- /**
- * Returns the compilation unit this change works on.
- *
- * @return the compilation unit this change works on
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- fCUnit.becomeWorkingCopy(new SubProgressMonitor(pm, 1));
- return super.acquireDocument(new SubProgressMonitor(pm, 1));
- }
-
- /**
- * {@inheritDoc}
- */
- protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException {
- boolean isModified= isDocumentModified();
- super.releaseDocument(document, pm);
- try {
- fCUnit.discardWorkingCopy();
- } finally {
- if (isModified && !isDocumentAcquired()) {
- if (fCUnit.isWorkingCopy())
- JavaModelUtil.reconcile(fCUnit);
- else
- fCUnit.makeConsistent(pm);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected Change createUndoChange(UndoEdit edit, ContentStamp stampToRestore) {
- try {
- return new UndoCompilationUnitChange(getName(), fCUnit, edit, stampToRestore, getSaveMode());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getAdapter(Class adapter) {
- if (IJavaScriptUnit.class.equals(adapter))
- return fCUnit;
- return super.getAdapter(adapter);
- }
-
- /**
- * Sets the refactoring descriptor for this change
- *
- * @param descriptor the descriptor to set
- */
- public void setDescriptor(ChangeDescriptor descriptor) {
- fDescriptor= descriptor;
- }
-
- /**
- * {@inheritDoc}
- */
- public ChangeDescriptor getDescriptor() {
- return fDescriptor;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitReorgChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitReorgChange.java
deleted file mode 100644
index 72620062..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CompilationUnitReorgChange.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-abstract class CompilationUnitReorgChange extends JDTChange {
-
- private String fCuHandle;
- private String fOldPackageHandle;
- private String fNewPackageHandle;
-
- private INewNameQuery fNewNameQuery;
-
- CompilationUnitReorgChange(IJavaScriptUnit cu, IPackageFragment dest, INewNameQuery newNameQuery) {
- fCuHandle= cu.getHandleIdentifier();
- fNewPackageHandle= dest.getHandleIdentifier();
- fNewNameQuery= newNameQuery;
- fOldPackageHandle= cu.getParent().getHandleIdentifier();
- }
-
- CompilationUnitReorgChange(IJavaScriptUnit cu, IPackageFragment dest) {
- this(cu, dest, null);
- }
-
- CompilationUnitReorgChange(String oldPackageHandle, String newPackageHandle, String cuHandle) {
- fOldPackageHandle= oldPackageHandle;
- fNewPackageHandle= newPackageHandle;
- fCuHandle= cuHandle;
- }
-
- public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask(getName(), 1);
- try {
- IJavaScriptUnit unit= getCu();
- ResourceMapping mapping= JavaElementResourceMapping.create(unit);
- Change result= doPerformReorg(new SubProgressMonitor(pm, 1));
- markAsExecuted(unit, mapping);
- return result;
- } finally {
- pm.done();
- }
- }
-
- abstract Change doPerformReorg(IProgressMonitor pm) throws CoreException, OperationCanceledException;
-
- public Object getModifiedElement() {
- return getCu();
- }
-
- IJavaScriptUnit getCu() {
- return (IJavaScriptUnit)JavaScriptCore.create(fCuHandle);
- }
-
- IPackageFragment getOldPackage() {
- return (IPackageFragment)JavaScriptCore.create(fOldPackageHandle);
- }
-
- IPackageFragment getDestinationPackage() {
- return (IPackageFragment)JavaScriptCore.create(fNewPackageHandle);
- }
-
- String getNewName() throws OperationCanceledException {
- if (fNewNameQuery == null)
- return null;
- return fNewNameQuery.getNewName();
- }
-
- static String getPackageName(IPackageFragment pack) {
- if (pack.isDefaultPackage())
- return RefactoringCoreMessages.MoveCompilationUnitChange_default_package;
- else
- return pack.getElementName();
- }
-
- private void markAsExecuted(IJavaScriptUnit unit, ResourceMapping mapping) {
- ReorgExecutionLog log= (ReorgExecutionLog)getAdapter(ReorgExecutionLog.class);
- if (log != null) {
- log.markAsProcessed(unit);
- log.markAsProcessed(mapping);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyCompilationUnitChange.java
deleted file mode 100644
index 33eb87e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyCompilationUnitChange.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class CopyCompilationUnitChange extends CompilationUnitReorgChange {
-
- public CopyCompilationUnitChange(IJavaScriptUnit cu, IPackageFragment dest, INewNameQuery newNameQuery){
- super(cu, dest, newNameQuery);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // Copy compilation unit change isn't undoable and isn't used
- // as a redo/undo change right now. Furthermore the current
- // implementation allows copying dirty files. In this case only
- // the content on disk is copied.
- return super.isValid(pm, NONE);
- }
-
- Change doPerformReorg(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- getCu().copy(getDestinationPackage(), null, getNewName(), true, pm);
- return null;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.CopyCompilationUnitChange_copy,
- new String[]{getCu().getElementName(), getPackageName(getDestinationPackage())});
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageChange.java
deleted file mode 100644
index 33872f42..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageChange.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class CopyPackageChange extends PackageReorgChange {
-
- public CopyPackageChange(IPackageFragment pack, IPackageFragmentRoot dest, INewNameQuery nameQuery){
- super(pack, dest, nameQuery);
- }
-
- protected Change doPerformReorg(IProgressMonitor pm) throws JavaScriptModelException, OperationCanceledException {
- getPackage().copy(getDestination(), null, getNewName(), true, pm);
- return null;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.CopyPackageChange_copy,
- new String[]{ getPackage().getElementName(), getDestination().getElementName()});
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageFragmentRootChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageFragmentRootChange.java
deleted file mode 100644
index 48db03d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyPackageFragmentRootChange.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class CopyPackageFragmentRootChange extends PackageFragmentRootReorgChange {
-
- public CopyPackageFragmentRootChange(IPackageFragmentRoot root, IProject destination, INewNameQuery newNameQuery, IPackageFragmentRootManipulationQuery updateClasspathQuery) {
- super(root, destination, newNameQuery, updateClasspathQuery);
- }
-
- protected Change doPerformReorg(IPath destinationPath, IProgressMonitor pm) throws JavaScriptModelException {
- getRoot().copy(destinationPath, getResourceUpdateFlags(), getUpdateModelFlags(true), null, pm);
- return null;
- }
-
- public String getName() {
- String[] keys= {getRoot().getElementName(), getDestinationProject().getName()};
- return Messages.format(RefactoringCoreMessages.CopyPackageFragmentRootChange_copy, keys);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyResourceChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyResourceChange.java
deleted file mode 100644
index e3252eaf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CopyResourceChange.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class CopyResourceChange extends ResourceReorgChange {
-
- public CopyResourceChange(IResource res, IContainer dest, INewNameQuery newNameQuery){
- super(res, dest, newNameQuery);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // Copy resource change isn't undoable and isn't used
- // as a redo/undo change right now. Furthermore the current
- // implementation allows copying dirty files. In this case only
- // the content on disk is copied.
- return super.isValid(pm, NONE);
- }
-
- protected Change doPerformReorg(IPath path, IProgressMonitor pm) throws CoreException{
- getResource().copy(path, getReorgFlags(), pm);
- return null;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.CopyResourceString_copy,
- new String[]{getResource().getFullPath().toString(), getDestination().getName()});
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreateCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreateCompilationUnitChange.java
deleted file mode 100644
index 75e76611..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreateCompilationUnitChange.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class CreateCompilationUnitChange extends CreateTextFileChange {
-
- private final IJavaScriptUnit fUnit;
-
- public CreateCompilationUnitChange(IJavaScriptUnit unit, String source, String encoding) {
- super(unit.getResource().getFullPath(), source, encoding, "java"); //$NON-NLS-1$
- fUnit= unit;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.CompilationUnitChange_label, new String[] { fUnit.getElementName(), getPath(fUnit.getResource()) });
- }
-
- private String getPath(IResource resource) {
- final StringBuffer buffer= new StringBuffer(resource.getProject().getName());
- final String path= resource.getParent().getProjectRelativePath().toString();
- if (path.length() > 0) {
- buffer.append('/');
- buffer.append(path);
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreatePackageChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreatePackageChange.java
deleted file mode 100644
index a5a760aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/CreatePackageChange.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-
-public class CreatePackageChange extends JDTChange {
-
- private IPackageFragment fPackageFragment;
-
- public CreatePackageChange(IPackageFragment pack) {
- fPackageFragment= pack;
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) {
- // Don't do any checking. Peform handles the case
- // that the package already exists. Furthermore
- // create package change isn't used as a undo
- // redo change right now
- return new RefactoringStatus();
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.CreatePackageChange_Creating_package, 1);
-
- if (fPackageFragment.exists()) {
- return new NullChange();
- } else {
- IPackageFragmentRoot root= (IPackageFragmentRoot) fPackageFragment.getParent();
- root.createPackageFragment(fPackageFragment.getElementName(), false, pm);
-
- return new DeleteFolderChange((IFolder) fPackageFragment.getResource(), true);
- }
- } finally {
- pm.done();
- }
- }
-
- public String getName() {
- return RefactoringCoreMessages.CreatePackageChange_Create_package;
- }
-
- public Object getModifiedElement() {
- return fPackageFragment;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFileChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFileChange.java
deleted file mode 100644
index ee42ef28..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFileChange.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class DeleteFileChange extends AbstractDeleteChange {
-
- private final IPath fPath;
- private final boolean fIsExecuteChange;
-
- public DeleteFileChange(IFile file, boolean executeChange) {
- Assert.isNotNull(file, "file"); //$NON-NLS-1$
- fPath= Utils.getResourcePath(file);
- fIsExecuteChange= executeChange;
- }
-
- private IFile getFile(){
- return Utils.getFile(fPath);
- }
-
- /* non java-doc
- * @see IChange#getName()
- */
- public String getName() {
- return Messages.format(RefactoringCoreMessages.DeleteFileChange_1, fPath.lastSegment());
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- if (fIsExecuteChange) {
- // no need for checking since we already prompt the
- // user if the file is dirty or read only
- return super.isValid(pm, NONE);
- } else {
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
- }
-
- /* non java-doc
- * @see IChange#getModifiedLanguageElement()
- */
- public Object getModifiedElement() {
- return getFile();
- }
-
- /* non java-doc
- * @see DeleteChange#doDelete(IProgressMonitor)
- */
- protected Change doDelete(IProgressMonitor pm) throws CoreException {
- IFile file= getFile();
- Assert.isNotNull(file);
- Assert.isTrue(file.exists());
- pm.beginTask("", 3); //$NON-NLS-1$
- saveFileIfNeeded(file, new SubProgressMonitor(pm, 1));
-
- ResourceDescription resourceDescription = ResourceDescription.fromResource(file);
- file.delete(false, true, new SubProgressMonitor(pm, 1));
- resourceDescription.recordStateFromHistory(file, new SubProgressMonitor(pm, 1));
- pm.done();
-
- return new UndoDeleteResourceChange(resourceDescription);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFolderChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFolderChange.java
deleted file mode 100644
index 4aabef7d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFolderChange.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class DeleteFolderChange extends AbstractDeleteChange {
-
- private final IPath fPath;
- private final boolean fIsExecuteChange;
-
- public DeleteFolderChange(IFolder folder, boolean isExecuteChange) {
- this(getFolderPath(folder), isExecuteChange);
- }
-
- public DeleteFolderChange(IPath path, boolean isExecuteChange) {
- fPath= path;
- fIsExecuteChange= isExecuteChange;
- }
-
- public static IPath getFolderPath(IFolder folder){
- return folder.getFullPath().removeFirstSegments(ResourcesPlugin.getWorkspace().getRoot().getFullPath().segmentCount());
- }
-
- public static IFolder getFolder(IPath path){
- return ResourcesPlugin.getWorkspace().getRoot().getFolder(path);
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.DeleteFolderChange_0, fPath.lastSegment());
- }
-
- public Object getModifiedElement() {
- return getFolder(fPath);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- if (fIsExecuteChange) {
- // no need to do additional checking since the dialog
- // already prompts the user if there are dirty
- // or read only files in the folder. The change is
- // currently not used as a undo/redo change
- return super.isValid(pm, NONE);
- } else {
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
- }
-
- protected Change doDelete(IProgressMonitor pm) throws CoreException{
- IFolder folder= getFolder(fPath);
- Assert.isTrue(folder.exists());
- pm.beginTask("", 3); //$NON-NLS-1$
- folder.accept(new IResourceVisitor() {
- public boolean visit(IResource resource) throws CoreException {
- if (resource instanceof IFile) {
- // progress is covered outside.
- saveFileIfNeeded((IFile)resource, new NullProgressMonitor());
- }
- return true;
- }
- }, IResource.DEPTH_INFINITE, false);
- pm.worked(1);
-
- ResourceDescription resourceDescription = ResourceDescription.fromResource(folder);
- folder.delete(false, true, new SubProgressMonitor(pm, 1));
- resourceDescription.recordStateFromHistory(folder, new SubProgressMonitor(pm, 1));
- pm.done();
-
- return new UndoDeleteResourceChange(resourceDescription);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFromClasspathChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFromClasspathChange.java
deleted file mode 100644
index c70a7989..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteFromClasspathChange.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-
-public class DeleteFromClasspathChange extends JDTChange {
-
- private final String fProjectHandle;
- private final IPath fPathToDelete;
-
- private IPath fPath;
- private IPath fSourceAttachmentPath;
- private IPath fSourceAttachmentRootPath;
- private int fEntryKind;
-
- public DeleteFromClasspathChange(IPackageFragmentRoot root) {
- this(root.getPath(), root.getJavaScriptProject());
- }
-
- DeleteFromClasspathChange(IPath pathToDelete, IJavaScriptProject project){
- Assert.isNotNull(pathToDelete);
- fPathToDelete= pathToDelete;
- fProjectHandle= project.getHandleIdentifier();
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // we have checked the .classpath file in the delete change.
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- pm.beginTask(getName(), 1);
- try{
- IJavaScriptProject project= getJavaProject();
- IIncludePathEntry[] cp= project.getRawIncludepath();
- IIncludePathEntry[] newCp= new IIncludePathEntry[cp.length-1];
- int i= 0;
- int j= 0;
- while (j < newCp.length) {
- IIncludePathEntry current= JavaScriptCore.getResolvedIncludepathEntry(cp[i]);
- if (current != null && toBeDeleted(current)) {
- i++;
- setDeletedEntryProperties(current);
- }
-
- newCp[j]= cp[i];
- i++;
- j++;
- }
-
- IIncludePathEntry last= JavaScriptCore.getResolvedIncludepathEntry(cp[cp.length - 1]);
- if (last != null && toBeDeleted(last))
- setDeletedEntryProperties(last);
-
- project.setRawIncludepath(newCp, pm);
-
- return new AddToClasspathChange(getJavaProject(), fEntryKind, fPath,
- fSourceAttachmentPath, fSourceAttachmentRootPath);
- } finally {
- pm.done();
- }
- }
-
- private boolean toBeDeleted(IIncludePathEntry entry){
- if (entry == null) //safety net
- return false;
- return fPathToDelete.equals(entry.getPath());
- }
-
- private void setDeletedEntryProperties(IIncludePathEntry entry){
- fEntryKind= entry.getEntryKind();
- fPath= entry.getPath();
- fSourceAttachmentPath= entry.getSourceAttachmentPath();
- fSourceAttachmentRootPath= entry.getSourceAttachmentRootPath();
- }
-
- private IJavaScriptProject getJavaProject(){
- return (IJavaScriptProject)JavaScriptCore.create(fProjectHandle);
- }
-
- public String getName() {
- return RefactoringCoreMessages.DeleteFromClassPathChange_remove + getJavaProject().getElementName();
- }
-
- public Object getModifiedElement() {
- return getJavaProject();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeletePackageFragmentRootChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeletePackageFragmentRootChange.java
deleted file mode 100644
index 429e150f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeletePackageFragmentRootChange.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map.Entry;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class DeletePackageFragmentRootChange extends AbstractDeleteChange {
-
- private final String fHandle;
- private final boolean fIsExecuteChange;
- private final IPackageFragmentRootManipulationQuery fUpdateClasspathQuery;
-
- public DeletePackageFragmentRootChange(IPackageFragmentRoot root, boolean isExecuteChange,
- IPackageFragmentRootManipulationQuery updateClasspathQuery) {
- Assert.isNotNull(root);
- Assert.isTrue(! root.isExternal());
- fHandle= root.getHandleIdentifier();
- fIsExecuteChange= isExecuteChange;
- fUpdateClasspathQuery= updateClasspathQuery;
- }
-
- public String getName() {
- String[] keys= {getRoot().getElementName()};
- return Messages.format(RefactoringCoreMessages.DeletePackageFragmentRootChange_delete, keys);
- }
-
- public Object getModifiedElement() {
- return getRoot();
- }
-
- private IPackageFragmentRoot getRoot(){
- return (IPackageFragmentRoot)JavaScriptCore.create(fHandle);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- if (fIsExecuteChange) {
- // don't check for read-only resources since we already
- // prompt the user via a dialog to confirm deletion of
- // read only resource. The change is currently not used
- // as
- return super.isValid(pm, DIRTY);
- } else {
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
- }
-
- protected Change doDelete(IProgressMonitor pm) throws CoreException {
- if (! confirmDeleteIfReferenced())
- return new NullChange();
- int resourceUpdateFlags= IResource.KEEP_HISTORY;
- int jCoreUpdateFlags= IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH | IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_INCLUDEPATH;
-
- pm.beginTask("", 2); //$NON-NLS-1$
- IPackageFragmentRoot root= getRoot();
- IResource rootResource= root.getResource();
- CompositeChange result= new CompositeChange(getName());
-
- ResourceDescription rootDescription = ResourceDescription.fromResource(rootResource);
- IJavaScriptProject[] referencingProjects= JavaElementUtil.getReferencingProjects(root);
- HashMap/*<IFile, String>*/ classpathFilesContents= new HashMap();
- for (int i= 0; i < referencingProjects.length; i++) {
- IJavaScriptProject javaProject= referencingProjects[i];
- IFile classpathFile= javaProject.getJSDTScopeFile(); //$NON-NLS-1$
- if (classpathFile.exists()) {
- classpathFilesContents.put(classpathFile, getFileContents(classpathFile));
- }
- }
-
- root.delete(resourceUpdateFlags, jCoreUpdateFlags, new SubProgressMonitor(pm, 1));
-
- rootDescription.recordStateFromHistory(rootResource, new SubProgressMonitor(pm, 1));
- for (Iterator iterator= classpathFilesContents.entrySet().iterator(); iterator.hasNext();) {
- Entry entry= (Entry) iterator.next();
- IFile file= (IFile) entry.getKey();
- String contents= (String) entry.getValue();
- //Restore time stamps? This should probably be some sort of UndoTextFileChange.
- TextFileChange classpathUndo= new TextFileChange(Messages.format(RefactoringCoreMessages.DeletePackageFragmentRootChange_restore_file, file.getFullPath().toOSString()), file);
- classpathUndo.setEdit(new ReplaceEdit(0, getFileLength(file), contents));
- result.add(classpathUndo);
- }
- result.add(new UndoDeleteResourceChange(rootDescription));
-
- pm.done();
- return result;
- }
-
- private static String getFileContents(IFile file) throws CoreException {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- IPath path= file.getFullPath();
- manager.connect(path, LocationKind.IFILE, new NullProgressMonitor());
- try {
- return manager.getTextFileBuffer(path, LocationKind.IFILE).getDocument().get();
- } finally {
- manager.disconnect(path, LocationKind.IFILE, new NullProgressMonitor());
- }
- }
-
- private static int getFileLength(IFile file) throws CoreException {
- // Cannot use file buffers here, since they are not yet in sync at this point.
- InputStream contents= file.getContents();
- InputStreamReader reader;
- try {
- reader= new InputStreamReader(contents, file.getCharset());
- } catch (UnsupportedEncodingException e) {
- JavaScriptPlugin.log(e);
- reader= new InputStreamReader(contents);
- }
- try {
- return (int) reader.skip(Integer.MAX_VALUE);
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, Corext.getPluginId(), e.getMessage(), e));
- }
- }
-
- private boolean confirmDeleteIfReferenced() throws JavaScriptModelException {
- if (! getRoot().isArchive()) //for source folders, you don't ask, just do it
- return true;
- if (fUpdateClasspathQuery == null)
- return true;
- IJavaScriptProject[] referencingProjects= JavaElementUtil.getReferencingProjects(getRoot());
- if (referencingProjects.length <= 1)
- return true;
- return fUpdateClasspathQuery.confirmManipulation(getRoot(), referencingProjects);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteSourceManipulationChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteSourceManipulationChange.java
deleted file mode 100644
index 87c2f837..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DeleteSourceManipulationChange.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceManipulation;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Caveat: undo of package fragment deletes is provided by a wrapping
- * UndoablePackageDeleteChange. This change returns a NullChange as undo for package fragments.
- */
-public class DeleteSourceManipulationChange extends AbstractDeleteChange {
-
- private final String fHandle;
- private final boolean fIsExecuteChange;
-
- public DeleteSourceManipulationChange(ISourceManipulation sm, boolean isExecuteChange) {
- Assert.isNotNull(sm);
- fHandle= getJavaElement(sm).getHandleIdentifier();
- fIsExecuteChange= isExecuteChange;
- }
-
- /*
- * @see IChange#getName()
- */
- public String getName() {
- return Messages.format(RefactoringCoreMessages.DeleteSourceManipulationChange_0, getElementName());
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- ISourceManipulation element= getSourceManipulation();
- if (fIsExecuteChange) {
- if (element instanceof IJavaScriptUnit) {
- // don't check anything in this case. We have a warning dialog
- // already presented to the user that the file is dirty.
- return super.isValid(pm, NONE);
- } else {
- return super.isValid(pm, DIRTY);
- }
- } else {
- return super.isValid(pm, READ_ONLY | DIRTY);
- }
- }
-
- private String getElementName() {
- IJavaScriptElement javaElement= getJavaElement(getSourceManipulation());
- if (JavaElementUtil.isDefaultPackage(javaElement))
- return RefactoringCoreMessages.DeleteSourceManipulationChange_1;
- return javaElement.getElementName();
- }
-
- /*
- * @see IChange#getModifiedLanguageElement()
- */
- public Object getModifiedElement() {
- return JavaScriptCore.create(fHandle);
- }
-
- /*
- * @see DeleteChange#doDelete(IProgressMonitor)
- */
- protected Change doDelete(IProgressMonitor pm) throws CoreException {
- ISourceManipulation element= getSourceManipulation();
- // we have to save dirty compilation units before deleting them. Otherwise
- // we will end up showing ghost compilation units in the package explorer
- // since the primary working copy still exists.
- if (element instanceof IJavaScriptUnit) {
- pm.beginTask("", 2); //$NON-NLS-1$
- IJavaScriptUnit unit= (IJavaScriptUnit)element;
- saveCUnitIfNeeded(unit, new SubProgressMonitor(pm, 1));
-
- IResource resource= unit.getResource();
- ResourceDescription resourceDescription = ResourceDescription.fromResource(resource);
- element.delete(false, new SubProgressMonitor(pm, 1));
- resourceDescription.recordStateFromHistory(resource, new SubProgressMonitor(pm, 1));
- return new UndoDeleteResourceChange(resourceDescription);
-
- } else if (element instanceof IPackageFragment) {
- IJavaScriptUnit[] units= ((IPackageFragment)element).getJavaScriptUnits();
- pm.beginTask("", units.length + 1); //$NON-NLS-1$
- for (int i = 0; i < units.length; i++) {
- // fix https://bugs.eclipse.org/bugs/show_bug.cgi?id=66835
- saveCUnitIfNeeded(units[i], new SubProgressMonitor(pm, 1));
- }
- element.delete(false, new SubProgressMonitor(pm, 1));
- return new NullChange(); // caveat: real undo implemented by UndoablePackageDeleteChange
-
- } else {
- element.delete(false, pm);
- return null; //should not happen
- }
- }
-
- private ISourceManipulation getSourceManipulation() {
- return (ISourceManipulation) getModifiedElement();
- }
-
- private static IJavaScriptElement getJavaElement(ISourceManipulation sm) {
- //all known ISourceManipulations are IJavaElements
- return (IJavaScriptElement)sm;
- }
-
- private static void saveCUnitIfNeeded(IJavaScriptUnit unit, IProgressMonitor pm) throws CoreException {
- saveFileIfNeeded((IFile)unit.getResource(), pm);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationRefactoringChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationRefactoringChange.java
deleted file mode 100644
index 6480e004..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationRefactoringChange.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Dynamic validation state change with support for refactoring descriptors.
- *
- *
- */
-public final class DynamicValidationRefactoringChange extends DynamicValidationStateChange {
-
- /** The refactoring descriptor */
- private final RefactoringDescriptor fDescriptor;
-
- /**
- * Creates a new dynamic validation refactoring change.
- *
- * @param descriptor
- * the refactoring descriptor
- * @param name
- * the name of the change
- */
- public DynamicValidationRefactoringChange(final JavaScriptRefactoringDescriptor descriptor, final String name) {
- super(name);
- Assert.isNotNull(descriptor);
- fDescriptor= descriptor;
- }
-
- /**
- * Creates a new dynamic validation refactoring change.
- *
- * @param descriptor
- * the refactoring descriptor
- * @param name
- * the name of the change
- * @param changes
- * the changes
- */
- public DynamicValidationRefactoringChange(final JavaScriptRefactoringDescriptor descriptor, final String name, final Change[] changes) {
- super(name, changes);
- Assert.isNotNull(descriptor);
- Assert.isTrue(!descriptor.validateDescriptor().hasFatalError(), RefactoringCoreMessages.DynamicValidationRefactoringChange_fatal_error);
- fDescriptor= descriptor;
- }
-
- /**
- * {@inheritDoc}
- */
- public ChangeDescriptor getDescriptor() {
- return new RefactoringChangeDescriptor(fDescriptor);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationStateChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationStateChange.java
deleted file mode 100644
index 24175dd9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/DynamicValidationStateChange.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-//import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class DynamicValidationStateChange extends CompositeChange implements WorkspaceTracker.Listener {
-
- private boolean fListenerRegistered= false;
- private RefactoringStatus fValidationState= null;
- private long fTimeStamp;
- private ISchedulingRule fSchedulingRule;
-
- // 30 minutes
- private static final long LIFE_TIME= 30 * 60 * 1000;
-
- public DynamicValidationStateChange(Change change) {
- super(change.getName());
- add(change);
- markAsSynthetic();
- fSchedulingRule= ResourcesPlugin.getWorkspace().getRoot();
- }
-
- public DynamicValidationStateChange(String name) {
- super(name);
- markAsSynthetic();
- fSchedulingRule= ResourcesPlugin.getWorkspace().getRoot();
- }
-
- public DynamicValidationStateChange(String name, Change[] changes) {
- super(name, changes);
- markAsSynthetic();
- fSchedulingRule= ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * {@inheritDoc}
- */
- public void initializeValidationData(IProgressMonitor pm) {
- super.initializeValidationData(pm);
- WorkspaceTracker.INSTANCE.addListener(this);
- fListenerRegistered= true;
- fTimeStamp= System.currentTimeMillis();
- }
-
- public void dispose() {
- if (fListenerRegistered) {
- WorkspaceTracker.INSTANCE.removeListener(this);
- fListenerRegistered= false;
- }
- super.dispose();
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- if (fValidationState == null) {
- return super.isValid(pm);
- }
- return fValidationState;
- }
-
- /**
- * {@inheritDoc}
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- final Change[] result= new Change[1];
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- result[0]= DynamicValidationStateChange.super.perform(monitor);
- }
- };
- JavaScriptCore.run(runnable, fSchedulingRule, pm);
- return result[0];
- }
-
- /**
- * {@inheritDoc}
- */
- protected Change createUndoChange(Change[] childUndos) {
- DynamicValidationStateChange result= new DynamicValidationStateChange(getName());
- for (int i= 0; i < childUndos.length; i++) {
- result.add(childUndos[i]);
- }
- return result;
- }
-
- public void workspaceChanged() {
- long currentTime= System.currentTimeMillis();
- if (currentTime - fTimeStamp < LIFE_TIME)
- return;
- fValidationState= RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.DynamicValidationStateChange_workspace_changed);
- // remove listener from workspace tracker
- WorkspaceTracker.INSTANCE.removeListener(this);
- fListenerRegistered= false;
- // clear up the children to not hang onto too much memory
- Change[] children= clear();
- for (int i= 0; i < children.length; i++) {
- final Change change= children[i];
- SafeRunner.run(new ISafeRunnable() {
- public void run() throws Exception {
- change.dispose();
- }
- public void handleException(Throwable exception) {
- JavaScriptPlugin.log(exception);
- }
- });
- }
- }
-
- public void setSchedulingRule(ISchedulingRule schedulingRule) {
- fSchedulingRule= schedulingRule;
- }
-
- public ISchedulingRule getSchedulingRule() {
- return fSchedulingRule;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveCompilationUnitChange.java
deleted file mode 100644
index 6c007353..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveCompilationUnitChange.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class MoveCompilationUnitChange extends CompilationUnitReorgChange {
-
- private boolean fUndoable;
- private long fStampToRestore;
-
- public MoveCompilationUnitChange(IJavaScriptUnit cu, IPackageFragment newPackage){
- super(cu, newPackage);
- fStampToRestore= IResource.NULL_STAMP;
- }
-
- private MoveCompilationUnitChange(IPackageFragment oldPackage, String cuName, IPackageFragment newPackage, long stampToRestore) {
- super(oldPackage.getHandleIdentifier(), newPackage.getHandleIdentifier(), oldPackage.getJavaScriptUnit(cuName).getHandleIdentifier());
- fStampToRestore= stampToRestore;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.MoveCompilationUnitChange_name,
- new String[]{getCu().getElementName(), getPackageName(getDestinationPackage())});
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- return super.isValid(pm, READ_ONLY | SAVE_IF_DIRTY);
- }
-
- Change doPerformReorg(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- String name;
- String newName= getNewName();
- if (newName == null)
- name= getCu().getElementName();
- else
- name= newName;
-
- // get current modification stamp
- long currentStamp= IResource.NULL_STAMP;
- IResource resource= getCu().getResource();
- if (resource != null) {
- currentStamp= resource.getModificationStamp();
- }
-
- fUndoable= ! getDestinationPackage().getJavaScriptUnit(name).exists();
-
- // perform the move and restore modification stamp
- getCu().move(getDestinationPackage(), null, newName, true, pm);
- if (fStampToRestore != IResource.NULL_STAMP) {
- IJavaScriptUnit moved= getDestinationPackage().getJavaScriptUnit(name);
- IResource movedResource= moved.getResource();
- if (movedResource != null) {
- movedResource.revertModificationStamp(fStampToRestore);
- }
- }
-
- if (fUndoable) {
- return new MoveCompilationUnitChange(getDestinationPackage(), getCu().getElementName(), getOldPackage(), currentStamp);
- } else {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageChange.java
deleted file mode 100644
index cfbbe070..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageChange.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class MovePackageChange extends PackageReorgChange {
-
- public MovePackageChange(IPackageFragment pack, IPackageFragmentRoot dest){
- super(pack, dest, null);
- }
-
- protected Change doPerformReorg(IProgressMonitor pm) throws JavaScriptModelException, OperationCanceledException {
- getPackage().move(getDestination(), null, getNewName(), true, pm);
- return null;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.MovePackageChange_move,
- new String[]{getPackage().getElementName(), getDestination().getElementName()});
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageFragmentRootChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageFragmentRootChange.java
deleted file mode 100644
index 6af716dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MovePackageFragmentRootChange.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class MovePackageFragmentRootChange extends PackageFragmentRootReorgChange {
-
- public MovePackageFragmentRootChange(IPackageFragmentRoot root, IProject destination, IPackageFragmentRootManipulationQuery updateClasspathQuery) {
- super(root, destination, null, updateClasspathQuery);
- }
-
- protected Change doPerformReorg(IPath destinationPath, IProgressMonitor pm) throws JavaScriptModelException {
- getRoot().move(destinationPath, getResourceUpdateFlags(), getUpdateModelFlags(false), null, pm);
- return null;
- }
-
- public String getName() {
- String[] keys= {getRoot().getElementName(), getDestinationProject().getName()};
- return Messages.format(RefactoringCoreMessages.MovePackageFragmentRootChange_move, keys);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveResourceChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveResourceChange.java
deleted file mode 100644
index d4e522ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MoveResourceChange.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class MoveResourceChange extends ResourceReorgChange {
-
- public MoveResourceChange(IResource res, IContainer dest){
- super(res, dest, null);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // We already present a dialog to the user if he
- // moves read-only resources. Since moving a resource
- // doesn't do a validate edit (it actually doesn't
- // change the content we can't check for READ only
- // here.
- return super.isValid(pm, DIRTY);
- }
-
- /* non java-doc
- * @see ResourceReorgChange#doPerform(IPath, IProgressMonitor)
- */
- protected Change doPerformReorg(IPath path, IProgressMonitor pm) throws CoreException{
- getResource().move(path, getReorgFlags(), pm);
- return null;
- }
- public String getName() {
- return Messages.format(RefactoringCoreMessages.MoveResourceChange_move,
- new String[]{getResource().getFullPath().toString(), getDestination().getName()});
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MultiStateCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MultiStateCompilationUnitChange.java
deleted file mode 100644
index 592d09b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/MultiStateCompilationUnitChange.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ltk.core.refactoring.MultiStateTextFileChange;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Multi state compilation unit change for composite refactorings.
- *
- *
- */
-public final class MultiStateCompilationUnitChange extends MultiStateTextFileChange {
-
- /** The compilation unit */
- private final IJavaScriptUnit fUnit;
-
- /**
- * Creates a new multi state compilation unit change.
- *
- * @param name
- * the name of the change
- * @param unit
- * the compilation unit
- */
- public MultiStateCompilationUnitChange(final String name, final IJavaScriptUnit unit) {
- super(name, (IFile) unit.getResource());
-
- fUnit= unit;
-
- setTextType("js"); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.Change#getAdapter(java.lang.Class)
- */
- public final Object getAdapter(final Class adapter) {
-
- if (IJavaScriptUnit.class.equals(adapter))
- return fUnit;
-
- return super.getAdapter(adapter);
- }
-
- /**
- * Returns the compilation unit.
- *
- * @return the compilation unit
- */
- public final IJavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return Messages.format(RefactoringCoreMessages.MultiStateCompilationUnitChange_name_pattern, new String[] { fUnit.getElementName(), getPath(fUnit.getResource()) });
- }
-
- /**
- * Returns the path of the resource to display.
- *
- * @param resource
- * the resource
- * @return the path
- */
- private String getPath(IResource resource) {
- final StringBuffer buffer= new StringBuffer(resource.getProject().getName());
- final String path= resource.getParent().getProjectRelativePath().toString();
- if (path.length() > 0) {
- buffer.append('/');
- buffer.append(path);
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java
deleted file mode 100644
index 3cc23f89..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-abstract class PackageFragmentRootReorgChange extends JDTChange {
-
- private final String fRootHandle;
- private final IPath fDestinationPath;
- private final INewNameQuery fNewNameQuery;
- private final IPackageFragmentRootManipulationQuery fUpdateClasspathQuery;
-
- PackageFragmentRootReorgChange(IPackageFragmentRoot root, IProject destination, INewNameQuery newNameQuery,
- IPackageFragmentRootManipulationQuery updateClasspathQuery) {
- Assert.isTrue(! root.isExternal());
- fRootHandle= root.getHandleIdentifier();
- fDestinationPath= Utils.getResourcePath(destination);
- fNewNameQuery= newNameQuery;
- fUpdateClasspathQuery= updateClasspathQuery;
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // we already ask for confirmation of move read only
- // resources. Furthermore we don't do a validate
- // edit since move source folders doesn't change
- // an content
- return isValid(pm, NONE);
- }
-
- public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask(getName(), 2);
- try {
- String newName= getNewResourceName();
- IPackageFragmentRoot root= getRoot();
- ResourceMapping mapping= JavaElementResourceMapping.create(root);
- final Change result= doPerformReorg(getDestinationProjectPath().append(newName), new SubProgressMonitor(pm, 1));
- markAsExecuted(root, mapping);
- return result;
- } finally {
- pm.done();
- }
- }
-
- protected abstract Change doPerformReorg(IPath destinationPath, IProgressMonitor pm) throws JavaScriptModelException;
-
- public Object getModifiedElement() {
- return getRoot();
- }
-
- protected IPackageFragmentRoot getRoot(){
- return (IPackageFragmentRoot)JavaScriptCore.create(fRootHandle);
- }
-
- protected IPath getDestinationProjectPath(){
- return fDestinationPath;
- }
-
- protected IProject getDestinationProject(){
- return Utils.getProject(getDestinationProjectPath());
- }
-
- private String getNewResourceName() throws OperationCanceledException {
- if (fNewNameQuery == null)
- return getRoot().getElementName();
- String name= fNewNameQuery.getNewName();
- if (name == null)
- return getRoot().getElementName();
- return name;
- }
-
- protected int getUpdateModelFlags(boolean isCopy) throws JavaScriptModelException{
- final int destination= IPackageFragmentRoot.DESTINATION_PROJECT_INCLUDEPATH;
- final int replace= IPackageFragmentRoot.REPLACE;
- final int originating;
- final int otherProjects;
- if (isCopy){
- originating= 0; //ORIGINATING_PROJECT_INCLUDEPATH does not apply to copy
- otherProjects= 0;//OTHER_REFERRING_PROJECTS_INCLUDEPATH does not apply to copy
- } else{
- originating= IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH;
- otherProjects= IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_INCLUDEPATH;
- }
-
- if (! JavaScriptCore.create(getDestinationProject()).exists())
- return replace | originating;
-
- if (fUpdateClasspathQuery == null)
- return replace | originating | destination;
-
- IJavaScriptProject[] referencingProjects= JavaElementUtil.getReferencingProjects(getRoot());
- if (referencingProjects.length <= 1)
- return replace | originating | destination;
-
- boolean updateOtherProjectsToo= fUpdateClasspathQuery.confirmManipulation(getRoot(), referencingProjects);
- if (updateOtherProjectsToo)
- return replace | originating | destination | otherProjects;
- else
- return replace | originating | destination;
- }
-
- protected int getResourceUpdateFlags(){
- return IResource.KEEP_HISTORY | IResource.SHALLOW;
- }
-
- private void markAsExecuted(IPackageFragmentRoot root, ResourceMapping mapping) {
- ReorgExecutionLog log= (ReorgExecutionLog)getAdapter(ReorgExecutionLog.class);
- if (log != null) {
- log.markAsProcessed(root);
- log.markAsProcessed(mapping);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageReorgChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageReorgChange.java
deleted file mode 100644
index f5159ba7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/PackageReorgChange.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-abstract class PackageReorgChange extends JDTChange {
-
- private String fPackageHandle;
- private String fDestinationHandle;
- private INewNameQuery fNameQuery;
-
- PackageReorgChange(IPackageFragment pack, IPackageFragmentRoot dest, INewNameQuery nameQuery) {
- fPackageHandle= pack.getHandleIdentifier();
- fDestinationHandle= dest.getHandleIdentifier();
- fNameQuery= nameQuery;
- }
-
- abstract Change doPerformReorg(IProgressMonitor pm) throws JavaScriptModelException, OperationCanceledException;
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- // it is enough to check the package only since package reorg changes
- // are not undoable. Don't check for read only here since
- // we already ask for user confirmation and moving a read
- // only package doesn't go thorugh validate edit (no
- // file content is modified).
- return isValid(pm, NONE);
- }
-
- public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- pm.beginTask(getName(), 1);
- try {
- IPackageFragment pack= getPackage();
- ResourceMapping mapping= JavaElementResourceMapping.create(pack);
- final Change result= doPerformReorg(pm);
- markAsExecuted(pack, mapping);
- return result;
- } finally {
- pm.done();
- }
- }
-
- public Object getModifiedElement() {
- return getPackage();
- }
-
- IPackageFragmentRoot getDestination() {
- return (IPackageFragmentRoot)JavaScriptCore.create(fDestinationHandle);
- }
-
- IPackageFragment getPackage() {
- return (IPackageFragment)JavaScriptCore.create(fPackageHandle);
- }
-
- String getNewName() throws OperationCanceledException {
- if (fNameQuery == null)
- return null;
- return fNameQuery.getNewName();
- }
-
- private void markAsExecuted(IPackageFragment pack, ResourceMapping mapping) {
- ReorgExecutionLog log= (ReorgExecutionLog)getAdapter(ReorgExecutionLog.class);
- if (log != null) {
- log.markAsProcessed(pack);
- log.markAsProcessed(mapping);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java
deleted file mode 100644
index ef838e5d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-/**
- * Composite change with an associated refactoring descriptor.
- *
- *
- */
-public final class RefactoringDescriptorChange extends CompositeChange {
-
- /** The refactoring descriptor */
- private RefactoringDescriptor fDescriptor;
-
- /**
- * Creates a new refactoring descriptor change.
- *
- * @param descriptor
- * the refactoring descriptor
- * @param name
- * the name
- */
- public RefactoringDescriptorChange(final RefactoringDescriptor descriptor, final String name) {
- super(name);
- Assert.isNotNull(descriptor);
- fDescriptor= descriptor;
- }
-
- /**
- * Creates a new refactoring descriptor change.
- *
- * @param descriptor
- * the refactoring descriptor
- * @param name
- * the name
- * @param changes
- * the changes
- */
- public RefactoringDescriptorChange(final RefactoringDescriptor descriptor, final String name, final Change[] changes) {
- super(name, changes);
- Assert.isNotNull(descriptor);
- fDescriptor= descriptor;
- }
-
- /**
- * {@inheritDoc}
- */
- public ChangeDescriptor getDescriptor() {
- return new RefactoringChangeDescriptor(fDescriptor);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameCompilationUnitChange.java
deleted file mode 100644
index 8314263e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameCompilationUnitChange.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.AbstractJavaElementRenameChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class RenameCompilationUnitChange extends AbstractJavaElementRenameChange {
-
- public RenameCompilationUnitChange(IJavaScriptUnit unit, String newName) {
- this(unit.getResource().getFullPath(), unit.getElementName(), newName, IResource.NULL_STAMP);
- Assert.isTrue(!unit.isReadOnly(), "compilation unit must not be read-only"); //$NON-NLS-1$
- }
-
- private RenameCompilationUnitChange(IPath resourcePath, String oldName, String newName, long stampToRestore) {
- super(resourcePath, oldName, newName, stampToRestore);
- }
-
- protected IPath createNewPath() {
- final IPath path= getResourcePath();
- if (path.getFileExtension() != null)
- return path.removeFileExtension().removeLastSegments(1).append(getNewName());
- else
- return path.removeLastSegments(1).append(getNewName());
- }
-
- protected Change createUndoChange(long stampToRestore) throws JavaScriptModelException {
- return new RenameCompilationUnitChange(createNewPath(), getNewName(), getOldName(), stampToRestore);
- }
-
- protected void doRename(IProgressMonitor pm) throws CoreException {
- IJavaScriptUnit cu= (IJavaScriptUnit) getModifiedElement();
- if (cu != null)
- cu.rename(getNewName(), false, pm);
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_name, new String[] { getOldName(), getNewName()});
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- return super.isValid(pm, READ_ONLY | SAVE_IF_DIRTY);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameJavaProjectChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameJavaProjectChange.java
deleted file mode 100644
index fdf54e6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameJavaProjectChange.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.AbstractJavaElementRenameChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class RenameJavaProjectChange extends AbstractJavaElementRenameChange {
-
- private boolean fUpdateReferences;
-
- public RenameJavaProjectChange(IJavaScriptProject project, String newName, boolean updateReferences) {
- this(project.getPath(), project.getElementName(), newName, IResource.NULL_STAMP, updateReferences);
- Assert.isTrue(!project.isReadOnly(), "should not be read only"); //$NON-NLS-1$
- }
-
- private RenameJavaProjectChange(IPath resourcePath, String oldName, String newName, long stampToRestore, boolean updateReferences) {
- super(resourcePath, oldName, newName);
- fUpdateReferences= updateReferences;
- }
-
- private IIncludePathEntry createModifiedEntry(IIncludePathEntry oldEntry) {
- return JavaScriptCore.newProjectEntry(createNewPath(), oldEntry.getAccessRules(), oldEntry.combineAccessRules(), oldEntry.getExtraAttributes(), oldEntry.isExported());
- }
-
- protected IPath createNewPath() {
- return getResourcePath().removeLastSegments(1).append(getNewName());
- }
-
- protected Change createUndoChange(long stampToRestore) throws JavaScriptModelException {
- return new RenameJavaProjectChange(createNewPath(), getNewName(), getOldName(), stampToRestore, fUpdateReferences);
- }
-
- protected void doRename(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(getName(), 2);
- if (fUpdateReferences)
- modifyClassPaths(new SubProgressMonitor(pm, 1));
- IProject project= getProject();
- if (project != null) {
- IProjectDescription description= project.getDescription();
- description.setName(getNewName());
- project.move(description, IResource.FORCE | IResource.SHALLOW, new SubProgressMonitor(pm, 1));
- }
- } finally {
- pm.done();
- }
- }
-
- private IJavaScriptProject getJavaProject() {
- return (IJavaScriptProject) getModifiedElement();
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.RenameJavaProjectChange_rename, new String[] { getOldName(), getNewName()});
- }
-
- private IProject getProject() {
- IJavaScriptProject jp= getJavaProject();
- if (jp == null)
- return null;
- return jp.getProject();
- }
-
- private boolean isOurEntry(IIncludePathEntry cpe) {
- if (cpe.getEntryKind() != IIncludePathEntry.CPE_PROJECT)
- return false;
- if (!cpe.getPath().equals(getResourcePath()))
- return false;
- return true;
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- return isValid(pm, DIRTY);
- }
-
- private void modifyClassPath(IJavaScriptProject referencingProject, IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 1); //$NON-NLS-1$
- IIncludePathEntry[] oldEntries= referencingProject.getRawIncludepath();
- IIncludePathEntry[] newEntries= new IIncludePathEntry[oldEntries.length];
- for (int i= 0; i < newEntries.length; i++) {
- if (isOurEntry(oldEntries[i]))
- newEntries[i]= createModifiedEntry(oldEntries[i]);
- else
- newEntries[i]= oldEntries[i];
- }
- referencingProject.setRawIncludepath(newEntries, pm);
- pm.done();
- }
-
- private void modifyClassPaths(IProgressMonitor pm) throws JavaScriptModelException {
- IProject[] referencing= getProject().getReferencingProjects();
- pm.beginTask(RefactoringCoreMessages.RenameJavaProjectChange_update, referencing.length);
- for (int i= 0; i < referencing.length; i++) {
- IJavaScriptProject jp= JavaScriptCore.create(referencing[i]);
- if (jp != null && jp.exists()) {
- modifyClassPath(jp, new SubProgressMonitor(pm, 1));
- } else {
- pm.worked(1);
- }
- }
- pm.done();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenamePackageChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenamePackageChange.java
deleted file mode 100644
index e02583a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenamePackageChange.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.AbstractJavaElementRenameChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class RenamePackageChange extends AbstractJavaElementRenameChange {
-
- private static IPath createPath(String packageName) {
- return new Path(packageName.replace('.', IPath.SEPARATOR));
- }
-
- private Map fCompilationUnitStamps;
-
- private final boolean fRenameSubpackages;
-
- public RenamePackageChange(IPackageFragment pack, String newName, boolean renameSubpackages) {
- this(pack.getPath(), pack.getElementName(), newName, IResource.NULL_STAMP, null, renameSubpackages);
- Assert.isTrue(!pack.isReadOnly(), "package must not be read only"); //$NON-NLS-1$
- }
-
- private RenamePackageChange(IPath resourcePath, String oldName, String newName, long stampToRestore, Map compilationUnitStamps, boolean renameSubpackages) {
- super(resourcePath, oldName, newName, stampToRestore);
- fCompilationUnitStamps= compilationUnitStamps;
- fRenameSubpackages= renameSubpackages;
- }
-
- private void addStamps(Map stamps, IJavaScriptUnit[] units) {
- for (int i= 0; i < units.length; i++) {
- IResource resource= units[i].getResource();
- long stamp= IResource.NULL_STAMP;
- if (resource != null && (stamp= resource.getModificationStamp()) != IResource.NULL_STAMP) {
- stamps.put(resource, new Long(stamp));
- }
- }
- }
-
- protected IPath createNewPath() {
- IPackageFragment oldPackage= getPackage();
- IPath oldPackageName= createPath(oldPackage.getElementName());
- IPath newPackageName= createPath(getNewName());
- return getResourcePath().removeLastSegments(oldPackageName.segmentCount()).append(newPackageName);
- }
-
- protected IPath createNewPath(IPackageFragment oldPackage) {
- IPath oldPackagePath= createPath(oldPackage.getElementName());
- IPath newPackagePath= createPath(getNewName(oldPackage));
- return oldPackage.getPath().removeLastSegments(oldPackagePath.segmentCount()).append(newPackagePath);
- }
-
- protected Change createUndoChange(long stampToRestore) throws CoreException {
- IPackageFragment pack= getPackage();
- if (pack == null)
- return new NullChange();
- Map stamps= new HashMap();
- if (!fRenameSubpackages) {
- addStamps(stamps, pack.getJavaScriptUnits());
- } else {
- IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack);
- for (int i= 0; i < allPackages.length; i++) {
- IPackageFragment currentPackage= allPackages[i];
- addStamps(stamps, currentPackage.getJavaScriptUnits());
- }
- }
- return new RenamePackageChange(createNewPath(), getNewName(), getOldName(), stampToRestore, stamps, fRenameSubpackages);
- // Note: This reverse change only works if the renamePackage change did
- // not merge the source package into an existing target.
- }
-
- protected void doRename(IProgressMonitor pm) throws CoreException {
- IPackageFragment pack= getPackage();
- if (pack == null)
- return;
-
- if (!fRenameSubpackages) {
- renamePackage(pack, pm, createNewPath(), getNewName());
- } else {
- IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack);
-
- pm.beginTask("", allPackages.length); //$NON-NLS-1$
- try {
- for (int i= 0; i < allPackages.length; i++) {
- IPackageFragment currentPackage= allPackages[i];
- renamePackage(currentPackage, new SubProgressMonitor(pm, 1), createNewPath(currentPackage), getNewName(currentPackage));
- }
- } finally {
- pm.done();
- }
- }
- }
-
- public String getName() {
- String msg= fRenameSubpackages ? RefactoringCoreMessages.RenamePackageChange_name_with_subpackages : RefactoringCoreMessages.RenamePackageChange_name;
- return Messages.format(msg, new String[] { getOldName(), getNewName()});
- }
-
- private String getNewName(IPackageFragment subpackage) {
- return getNewName() + subpackage.getElementName().substring(getOldName().length());
- }
-
- private IPackageFragment getPackage() {
- return (IPackageFragment) getModifiedElement();
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- RefactoringStatus result;
- try {
- result= new RefactoringStatus();
- IJavaScriptElement element= (IJavaScriptElement) getModifiedElement();
- // don't check for read-only since we don't go through
- // validate edit.
- result.merge(isValid(new SubProgressMonitor(pm, 1), DIRTY));
- if (result.hasFatalError())
- return result;
- if (element != null && element.exists() && element instanceof IPackageFragment) {
- IPackageFragment pack= (IPackageFragment) element;
- if (fRenameSubpackages) {
- IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack);
- SubProgressMonitor subPm= new SubProgressMonitor(pm, 1);
- subPm.beginTask("", allPackages.length); //$NON-NLS-1$
- for (int i= 0; i < allPackages.length; i++) {
- // don't check for read-only since we don't go through
- // validate edit.
- checkIfModifiable(result, allPackages[i], DIRTY);
- if (result.hasFatalError())
- return result;
- isValid(result, allPackages[i], new SubProgressMonitor(subPm, 1));
- }
- } else {
- isValid(result, pack, new SubProgressMonitor(pm, 1));
- }
- }
- } finally {
- pm.done();
- }
- return result;
- }
-
- private void isValid(RefactoringStatus result, IPackageFragment pack, IProgressMonitor pm) throws JavaScriptModelException {
- IJavaScriptUnit[] units= pack.getJavaScriptUnits();
- pm.beginTask("", units.length); //$NON-NLS-1$
- for (int i= 0; i < units.length; i++) {
- pm.subTask(Messages.format(RefactoringCoreMessages.RenamePackageChange_checking_change, pack.getElementName()));
- checkIfModifiable(result, units[i], READ_ONLY | DIRTY);
- pm.worked(1);
- }
- pm.done();
- }
-
- private void renamePackage(IPackageFragment pack, IProgressMonitor pm, IPath newPath, String newName) throws JavaScriptModelException, CoreException {
- pack.rename(newName, false, pm);
- if (fCompilationUnitStamps != null) {
- IPackageFragment newPack= (IPackageFragment) JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath));
- if (newPack.exists()) {
- IJavaScriptUnit[] units= newPack.getJavaScriptUnits();
- for (int i= 0; i < units.length; i++) {
- IResource resource= units[i].getResource();
- if (resource != null) {
- Long stamp= (Long) fCompilationUnitStamps.get(resource);
- if (stamp != null) {
- resource.revertModificationStamp(stamp.longValue());
- }
- }
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameResourceChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameResourceChange.java
deleted file mode 100644
index 28243f6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameResourceChange.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class RenameResourceChange extends JDTChange {
-
- public static IPath renamedResourcePath(IPath path, String newName) {
- return path.removeLastSegments(1).append(newName);
- }
-
- private final String fComment;
-
- private final RefactoringDescriptor fDescriptor;
-
- private final String fNewName;
-
- private final IPath fResourcePath;
-
- private final long fStampToRestore;
-
- private RenameResourceChange(RefactoringDescriptor descriptor, IPath resourcePath, String newName, String comment, long stampToRestore) {
- fDescriptor= descriptor;
- fResourcePath= resourcePath;
- fNewName= newName;
- fComment= comment;
- fStampToRestore= stampToRestore;
- }
-
- public RenameResourceChange(RefactoringDescriptor descriptor, IResource resource, String newName, String comment) {
- this(descriptor, resource.getFullPath(), newName, comment, IResource.NULL_STAMP);
- }
-
- public ChangeDescriptor getDescriptor() {
- if (fDescriptor != null)
- return new RefactoringChangeDescriptor(fDescriptor);
- return null;
- }
-
- public Object getModifiedElement() {
- return getResource();
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.RenameResourceChange_name, new String[] { fResourcePath.toString(), fNewName});
- }
-
- public String getNewName() {
- return fNewName;
- }
-
- private IResource getResource() {
- return ResourcesPlugin.getWorkspace().getRoot().findMember(fResourcePath);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- IResource resource= getResource();
- if (resource == null || !resource.exists()) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.RenameResourceChange_does_not_exist, fResourcePath.toString()));
- } else {
- return super.isValid(pm, DIRTY);
- }
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.RenameResourceChange_rename_resource, 1);
-
- IResource resource= getResource();
- long currentStamp= resource.getModificationStamp();
- IPath newPath= renamedResourcePath(fResourcePath, fNewName);
- resource.move(newPath, IResource.SHALLOW, pm);
- if (fStampToRestore != IResource.NULL_STAMP) {
- IResource newResource= ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
- newResource.revertModificationStamp(fStampToRestore);
- }
- String oldName= fResourcePath.lastSegment();
- return new RenameResourceChange(null, newPath, oldName, fComment, currentStamp);
- } finally {
- pm.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java
deleted file mode 100644
index 69a91609..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.AbstractJavaElementRenameChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public final class RenameSourceFolderChange extends AbstractJavaElementRenameChange {
-
- private static RefactoringStatus checkIfModifiable(IPackageFragmentRoot root, IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- checkExistence(result, root);
- if (result.hasFatalError())
- return result;
-
- if (root.isArchive()) {
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_rename_archive, root.getElementName()));
- return result;
- }
-
- if (root.isExternal()) {
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_rename_external, root.getElementName()));
- return result;
- }
-
- checkExistence(result, root.getCorrespondingResource());
- if (result.hasFatalError())
- return result;
-
- if (root.getCorrespondingResource().isLinked()) {
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_rename_linked, root.getElementName()));
- return result;
- }
-
- return result;
- }
-
- public RenameSourceFolderChange(IPackageFragmentRoot sourceFolder, String newName) {
- this(sourceFolder.getPath(), sourceFolder.getElementName(), newName, IResource.NULL_STAMP);
- Assert.isTrue(!sourceFolder.isReadOnly(), "should not be read only"); //$NON-NLS-1$
- Assert.isTrue(!sourceFolder.isArchive(), "should not be an archive"); //$NON-NLS-1$
- }
-
- private RenameSourceFolderChange(IPath resourcePath, String oldName, String newName, long stampToRestore) {
- super(resourcePath, oldName, newName);
- }
-
- protected IPath createNewPath() {
- return getResourcePath().removeLastSegments(1).append(getNewName());
- }
-
- protected Change createUndoChange(long stampToRestore) {
- return new RenameSourceFolderChange(createNewPath(), getNewName(), getOldName(), stampToRestore);
- }
-
- protected void doRename(IProgressMonitor pm) throws CoreException {
- IPackageFragmentRoot sourceFolder= getSourceFolder();
- if (sourceFolder != null)
- sourceFolder.move(getNewPath(), getCoreMoveFlags(), getJavaModelUpdateFlags(), null, pm);
- }
-
- private int getCoreMoveFlags() {
- if (getResource().isLinked())
- return IResource.SHALLOW;
- else
- return IResource.NONE;
- }
-
- private int getJavaModelUpdateFlags() {
- return IPackageFragmentRoot.DESTINATION_PROJECT_INCLUDEPATH | IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH | IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_INCLUDEPATH | IPackageFragmentRoot.REPLACE;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_rename, new String[] { getOldName(), getNewName()});
- }
-
- private IPath getNewPath() {
- return getResource().getFullPath().removeLastSegments(1).append(getNewName());
- }
-
- private IPackageFragmentRoot getSourceFolder() {
- return (IPackageFragmentRoot) getModifiedElement();
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- pm.beginTask("", 2); //$NON-NLS-1$
- result.merge(isValid(new SubProgressMonitor(pm, 1), DIRTY));
- if (result.hasFatalError())
- return result;
- IPackageFragmentRoot sourceFolder= getSourceFolder();
- result.merge(checkIfModifiable(sourceFolder, new SubProgressMonitor(pm, 1)));
-
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/ResourceReorgChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/ResourceReorgChange.java
deleted file mode 100644
index ba538c2a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/ResourceReorgChange.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-
-abstract class ResourceReorgChange extends JDTChange {
-
- private final IPath fResourcePath;
- private final boolean fIsFile;
- private final IPath fDestinationPath;
- private final boolean fIsDestinationProject;
- private final INewNameQuery fNewNameQuery;
-
- ResourceReorgChange(IResource res, IContainer dest, INewNameQuery nameQuery){
- Assert.isTrue(res instanceof IFile || res instanceof IFolder);
- fIsFile= (res instanceof IFile);
- fResourcePath= Utils.getResourcePath(res);
-
- Assert.isTrue(dest instanceof IProject || dest instanceof IFolder);
- fIsDestinationProject= (dest instanceof IProject);
- fDestinationPath= Utils.getResourcePath(dest);
- fNewNameQuery= nameQuery;
- }
-
- protected abstract Change doPerformReorg(IPath path, IProgressMonitor pm) throws CoreException;
-
- /* non java-doc
- * @see IChange#perform(ChangeContext, IProgressMonitor)
- */
- public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- try{
- pm.beginTask(getName(), 2);
-
- String newName= getNewResourceName();
- IResource resource= getResource();
- boolean performReorg= deleteIfAlreadyExists(new SubProgressMonitor(pm, 1), newName);
- if (!performReorg)
- return null;
- final Change result= doPerformReorg(getDestinationPath(newName), new SubProgressMonitor(pm, 1));
- markAsExecuted(resource);
- return result;
- } finally {
- pm.done();
- }
- }
-
- protected IPath getDestinationPath(String newName) {
- return getDestination().getFullPath().append(newName);
- }
-
- /**
- * returns false if source and destination are the same (in workspace or on disk)
- * in such case, no action should be performed
- */
- private boolean deleteIfAlreadyExists(IProgressMonitor pm, String newName) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- IResource current= getDestination().findMember(newName);
- if (current == null)
- return true;
- if (! current.exists())
- return true;
-
- IResource resource= getResource();
- Assert.isNotNull(resource);
-
- if (ReorgUtils.areEqualInWorkspaceOrOnDisk(resource, current))
- return false;
-
- if (current instanceof IFile)
- ((IFile)current).delete(false, true, new SubProgressMonitor(pm, 1));
- else if (current instanceof IFolder)
- ((IFolder)current).delete(false, true, new SubProgressMonitor(pm, 1));
- else
- Assert.isTrue(false);
-
- return true;
- }
-
-
- private String getNewResourceName() throws OperationCanceledException {
- if (fNewNameQuery == null)
- return getResource().getName();
- String name= fNewNameQuery.getNewName();
- if (name == null)
- return getResource().getName();
- return name;
- }
-
- /* non java-doc
- * @see IChange#getModifiedLanguageElement()
- */
- public Object getModifiedElement() {
- return getResource();
- }
-
- private IFile getFile(){
- return Utils.getFile(fResourcePath);
- }
-
- private IFolder getFolder(){
- return Utils.getFolder(fResourcePath);
- }
-
- protected IResource getResource(){
- if (fIsFile)
- return getFile();
- else
- return getFolder();
- }
-
- IContainer getDestination(){
- if (fIsDestinationProject)
- return Utils.getProject(fDestinationPath);
- else
- return Utils.getFolder(fDestinationPath);
- }
-
- protected int getReorgFlags() {
- return IResource.KEEP_HISTORY | IResource.SHALLOW;
- }
-
- private void markAsExecuted(IResource resource) {
- ReorgExecutionLog log= (ReorgExecutionLog)getAdapter(ReorgExecutionLog.class);
- if (log != null) {
- log.markAsProcessed(resource);
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/TextChangeCompatibility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/TextChangeCompatibility.java
deleted file mode 100644
index c8990cee..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/TextChangeCompatibility.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditChangeGroup;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-
-
-/**
- * A utility class to provide compatibility with the old
- * text change API of adding text edits directly and auto
- * inserting them into the tree.
- */
-public class TextChangeCompatibility {
-
- public static void addTextEdit(TextChange change, String name, TextEdit edit) throws MalformedTreeException {
- Assert.isNotNull(change);
- Assert.isNotNull(name);
- Assert.isNotNull(edit);
- TextEdit root= change.getEdit();
- if (root == null) {
- root= new MultiTextEdit();
- change.setEdit(root);
- }
- insert(root, edit);
- change.addTextEditGroup(new TextEditGroup(name, edit));
- }
-
- public static void addTextEdit(TextChange change, String name, TextEdit edit, GroupCategorySet groupCategories) throws MalformedTreeException {
- Assert.isNotNull(change);
- Assert.isNotNull(name);
- Assert.isNotNull(edit);
- TextEdit root= change.getEdit();
- if (root == null) {
- root= new MultiTextEdit();
- change.setEdit(root);
- }
- insert(root, edit);
- change.addTextEditChangeGroup(new TextEditChangeGroup(
- change,
- new CategorizedTextEditGroup(name, edit, groupCategories)));
- }
-
- public static void insert(TextEdit parent, TextEdit edit) throws MalformedTreeException {
- if (!parent.hasChildren()) {
- parent.addChild(edit);
- return;
- }
- TextEdit[] children= parent.getChildren();
- // First dive down to find the right parent.
- for (int i= 0; i < children.length; i++) {
- TextEdit child= children[i];
- if (covers(child, edit)) {
- insert(child, edit);
- return;
- }
- }
- // We have the right parent. Now check if some of the children have to
- // be moved under the new edit since it is covering it.
- int removed= 0;
- for (int i= 0; i < children.length; i++) {
- TextEdit child= children[i];
- if (covers(edit, child)) {
- parent.removeChild(i - removed++);
- edit.addChild(child);
- }
- }
- parent.addChild(edit);
- }
-
- private static boolean covers(TextEdit thisEdit, TextEdit otherEdit) {
- if (thisEdit.getLength() == 0) // an insertion point can't cover anything
- return false;
-
- int thisOffset= thisEdit.getOffset();
- int thisEnd= thisEdit.getExclusiveEnd();
- if (otherEdit.getLength() == 0) {
- int otherOffset= otherEdit.getOffset();
- return thisOffset < otherOffset && otherOffset < thisEnd;
- } else {
- int otherOffset= otherEdit.getOffset();
- int otherEnd= otherEdit.getExclusiveEnd();
- return thisOffset <= otherOffset && otherEnd <= thisEnd;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java
deleted file mode 100644
index abaeb28b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ContentStamp;
-import org.eclipse.ltk.core.refactoring.UndoTextFileChange;
-import org.eclipse.text.edits.UndoEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/* package */ class UndoCompilationUnitChange extends UndoTextFileChange {
-
- private IJavaScriptUnit fCUnit;
-
- public UndoCompilationUnitChange(String name, IJavaScriptUnit unit, UndoEdit undo, ContentStamp stampToRestore, int saveMode) throws CoreException {
- super(name, getFile(unit), undo, stampToRestore, saveMode);
- fCUnit= unit;
- }
-
- private static IFile getFile(IJavaScriptUnit cunit) throws CoreException {
- IFile file= (IFile)cunit.getResource();
- if (file == null)
- throw new CoreException(new Status(
- IStatus.ERROR,
- JavaScriptPlugin.getPluginId(),
- IStatus.ERROR,
- Messages.format(
- RefactoringCoreMessages.UndoCompilationUnitChange_no_resource,
- cunit.getElementName()),
- null)
- );
- return file;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getModifiedElement() {
- return fCUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- protected Change createUndoChange(UndoEdit edit, ContentStamp stampToRestore) throws CoreException {
- return new UndoCompilationUnitChange(getName(), fCUnit, edit, stampToRestore, getSaveMode());
- }
-
- /**
- * {@inheritDoc}
- */
- public Change perform(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- fCUnit.becomeWorkingCopy(new SubProgressMonitor(pm,1));
- try {
- return super.perform(new SubProgressMonitor(pm,1));
- } finally {
- fCUnit.discardWorkingCopy();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoDeleteResourceChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoDeleteResourceChange.java
deleted file mode 100644
index 02f83289..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoDeleteResourceChange.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-
-public class UndoDeleteResourceChange extends Change {
-
- private final ResourceDescription fResourceDescription;
-
- public UndoDeleteResourceChange(ResourceDescription resourceDescription) {
- fResourceDescription= resourceDescription;
- }
-
- public void initializeValidationData(IProgressMonitor pm) {
-
- }
-
- public Object getModifiedElement() {
- return null;
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.UndoDeleteResourceChange_change_name, fResourceDescription.getName());
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- if (! fResourceDescription.isValid()) {
- return RefactoringStatus.createFatalErrorStatus(
- Messages.format(
- RefactoringCoreMessages.UndoDeleteResourceChange_cannot_restore,
- fResourceDescription.getName()));
- }
-
- if (fResourceDescription.verifyExistence(true)) {
- return RefactoringStatus.createFatalErrorStatus(
- Messages.format(
- RefactoringCoreMessages.UndoDeleteResourceChange_already_exists,
- fResourceDescription.getName()));
- }
-
- return new RefactoringStatus();
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- IResource created= fResourceDescription.createResource(pm);
- created.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(pm, 1));
- if (created instanceof IFile) {
- return new DeleteFileChange((IFile) created, false);
- } else if (created instanceof IFolder) {
- return new DeleteFolderChange((IFolder) created, false);
- } else {
- return null; // should not happen
- }
- }
-
- public String toString() {
- return "Remove " + fResourceDescription.getName(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoablePackageDeleteChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoablePackageDeleteChange.java
deleted file mode 100644
index 3fce112c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoablePackageDeleteChange.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ui.ide.undo.ResourceDescription;
-
-public class UndoablePackageDeleteChange extends DynamicValidationStateChange {
-
- private final List/*<IResource>*/ fPackageDeletes;
-
- public UndoablePackageDeleteChange(String name, List/*<IResource>*/ packageDeletes) {
- super(name);
- fPackageDeletes= packageDeletes;
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- int count= fPackageDeletes.size();
- pm.beginTask("", count * 3); //$NON-NLS-1$
- ResourceDescription[] packageDeleteDescriptions= new ResourceDescription[fPackageDeletes.size()];
- for (int i= 0; i < fPackageDeletes.size(); i++) {
- IResource resource= (IResource) fPackageDeletes.get(i);
- packageDeleteDescriptions[i]= ResourceDescription.fromResource(resource);
- pm.worked(1);
- }
-
- DynamicValidationStateChange result= (DynamicValidationStateChange) super.perform(new SubProgressMonitor(pm, count));
-
- for (int i= 0; i < fPackageDeletes.size(); i++) {
- IResource resource= (IResource) fPackageDeletes.get(i);
- ResourceDescription resourceDescription= packageDeleteDescriptions[i];
- resourceDescription.recordStateFromHistory(resource, new SubProgressMonitor(pm, 1));
- result.add(new UndoDeleteResourceChange(resourceDescription));
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/Utils.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/Utils.java
deleted file mode 100644
index a9d48cce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/Utils.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-
-class Utils {
-
- //no instances
- private Utils(){
- }
-
- static IPath getResourcePath(IResource resource){
- return resource.getFullPath().removeFirstSegments(ResourcesPlugin.getWorkspace().getRoot().getFullPath().segmentCount());
- }
-
- static IFile getFile(IPath path){
- return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
- }
-
- static IFolder getFolder(IPath path){
- return ResourcesPlugin.getWorkspace().getRoot().getFolder(path);
- }
-
- static IProject getProject(IPath path){
- return (IProject)ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/WorkspaceTracker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/WorkspaceTracker.java
deleted file mode 100644
index 0280c735..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/WorkspaceTracker.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.changes;
-
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.ListenerList;
-
-
-public class WorkspaceTracker {
-
- public final static WorkspaceTracker INSTANCE= new WorkspaceTracker();
-
- public interface Listener {
- public void workspaceChanged();
- }
-
- private ListenerList fListeners;
- private ResourceListener fResourceListener;
-
- private WorkspaceTracker() {
- fListeners= new ListenerList();
- }
-
- private class ResourceListener implements IResourceChangeListener {
- public void resourceChanged(IResourceChangeEvent event) {
- workspaceChanged();
- }
- }
-
- private void workspaceChanged() {
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ((Listener)listeners[i]).workspaceChanged();
- }
- }
-
- public void addListener(Listener l) {
- fListeners.add(l);
- if (fResourceListener == null) {
- fResourceListener= new ResourceListener();
- ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceListener);
- }
- }
-
- public void removeListener(Listener l) {
- if (fListeners.size() == 0)
- return;
- fListeners.remove(l);
- if (fListeners.size() == 0) {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(fResourceListener);
- fResourceListener= null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/AstMatchingNodeFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/AstMatchingNodeFinder.java
deleted file mode 100644
index 998a9c9b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/AstMatchingNodeFinder.java
+++ /dev/null
@@ -1,594 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.wst.jsdt.core.dom.ASTMatcher;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BlockComment;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.LineComment;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.JdtASTMatcher;
-
-class AstMatchingNodeFinder {
-
- private AstMatchingNodeFinder(){
- }
-
- public static ASTNode[] findMatchingNodes(ASTNode scope, ASTNode node){
- Visitor visitor= new Visitor(node);
- scope.accept(visitor);
- return visitor.getMatchingNodes();
- }
-
- private static class Visitor extends ASTVisitor{
-
- Collection fFound;
- ASTMatcher fMatcher;
- ASTNode fNodeToMatch;
-
- Visitor(ASTNode nodeToMatch){
- fNodeToMatch= nodeToMatch;
- fFound= new ArrayList();
- fMatcher= new JdtASTMatcher();
- }
-
- ASTNode[] getMatchingNodes(){
- return (ASTNode[]) fFound.toArray(new ASTNode[fFound.size()]);
- }
-
- private boolean matches(ASTNode node){
- fFound.add(node);
- return false;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ArrayAccess node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ArrayCreation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ArrayInitializer node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ArrayType node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(Assignment node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(Block node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(BooleanLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(BreakStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FunctionExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ObjectLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ObjectLiteralField node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(CatchClause node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(CharacterLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
- public boolean visit(RegularExpressionLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ClassInstanceCreation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(JavaScriptUnit node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ConditionalExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ConstructorInvocation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ContinueStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(DoStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(EmptyStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ExpressionStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FieldAccess node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FieldDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ForStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ForInStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(IfStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ImportDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(InfixExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(Initializer node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(InstanceofExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(JSdoc node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(LabeledStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
-
- public boolean visit(ListExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
- public boolean visit(FunctionDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FunctionInvocation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
-
- public boolean visit(NullLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(UndefinedLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(NumberLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(PackageDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ParenthesizedExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(PostfixExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(PrefixExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(PrimitiveType node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(QualifiedName node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ReturnStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SimpleName node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SimpleType node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SingleVariableDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(StringLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SuperFieldAccess node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SuperMethodInvocation node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SwitchCase node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(SwitchStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
-
- public boolean visit(ThisExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(ThrowStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TryStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TypeDeclaration node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TypeLiteral node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationExpression node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(WhileStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
-
- public boolean visit(WithStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(BlockComment node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(EnhancedForStatement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(LineComment node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(MemberRef node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FunctionRef node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(FunctionRefParameter node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(Modifier node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(QualifiedType node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TagElement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
-
- public boolean visit(TextElement node) {
- if (node.subtreeMatch(fMatcher, fNodeToMatch))
- return matches(node);
- return super.visit(node);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallContext.java
deleted file mode 100644
index 29be0762..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallContext.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.CodeScopeBuilder;
-
-public class CallContext {
-
- public ASTNode invocation;
- public String[] arguments;
- public String receiver;
- public boolean receiverIsStatic;
- public CodeScopeBuilder.Scope scope;
- public int callMode;
- public ImportRewrite importer;
-
- public CallContext(ASTNode inv, CodeScopeBuilder.Scope s, int cm, ImportRewrite i) {
- super();
- invocation= inv;
- scope= s;
- callMode= cm;
- importer= i;
- }
-
- public ITypeBinding getReceiverType() {
- Expression expression= Invocations.getExpression(invocation);
- if (expression != null) {
- return expression.resolveTypeBinding();
- }
- IFunctionBinding method= Invocations.resolveBinding(invocation);
- if (method != null) {
- return method.getDeclaringClass();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallInliner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallInliner.java
deleted file mode 100644
index 55d88aa5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CallInliner.java
+++ /dev/null
@@ -1,833 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for:
- * o bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- * o bug inline method: compile error (array related)
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38471)
- * o inline call that is used in a field initializer
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38137)
- * o inline call a field initializer: could detect self reference
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=44417)
- * o Allow 'this' constructor to be inlined
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.CodeScopeBuilder;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.LocalVariableIndex;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InputFlowAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class CallInliner {
-
- private IJavaScriptUnit fCUnit;
- private ASTRewrite fRewrite;
- private ImportRewrite fImportRewrite;
- private ITextFileBuffer fBuffer;
- private SourceProvider fSourceProvider;
- private TypeEnvironment fTypeEnvironment;
-
- private BodyDeclaration fBodyDeclaration;
- private CodeScopeBuilder.Scope fRootScope;
- private int fNumberOfLocals;
-
- private ASTNode fInvocation;
-
- private int fInsertionIndex;
- private ListRewrite fListRewrite;
-
- private boolean fNeedsStatement;
- private ASTNode fTargetNode;
- private FlowContext fFlowContext;
- private FlowInfo fFlowInfo;
- private CodeScopeBuilder.Scope fInvocationScope;
- private boolean fFieldInitializer;
- private List fLocals;
- private CallContext fContext;
-
- private class InlineEvaluator extends HierarchicalASTVisitor {
- private ParameterData fFormalArgument;
- private boolean fResult;
- public InlineEvaluator(ParameterData argument) {
- fFormalArgument= argument;
- }
- public boolean getResult() {
- return fResult;
- }
- private boolean setResult(boolean result) {
- fResult= result;
- return false;
- }
- public boolean visit(Expression node) {
- int accessMode= fFormalArgument.getSimplifiedAccessMode();
- if (accessMode == FlowInfo.WRITE)
- return setResult(false);
- if (accessMode == FlowInfo.UNUSED)
- return setResult(true);
- if (ASTNodes.isLiteral(node))
- return setResult(true);
- return setResult(fFormalArgument.getNumberOfAccesses() <= 1);
- }
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding) {
- int accessMode = fFormalArgument.getSimplifiedAccessMode();
- if (accessMode == FlowInfo.READ || accessMode == FlowInfo.UNUSED)
- return setResult(true);
- // from now on we only have write accesses.
- IVariableBinding vb= (IVariableBinding)binding;
- if (vb.isField())
- return setResult(false);
- return setResult(fFlowInfo.hasAccessMode(fFlowContext, vb, FlowInfo.UNUSED | FlowInfo.WRITE));
- }
- return setResult(false);
- }
- public boolean visit(FieldAccess node) {
- return visit(node.getName());
- }
- public boolean visit(SuperFieldAccess node) {
- return visit(node.getName());
- }
- public boolean visit(ThisExpression node) {
- int accessMode= fFormalArgument.getSimplifiedAccessMode();
- if (accessMode == FlowInfo.READ || accessMode == FlowInfo.UNUSED)
- return setResult(true);
- return setResult(false);
- }
- }
-
-// private static class AmbiguousMethodAnalyzer implements TypeBindingVisitor {
-// private TypeEnvironment fTypeEnvironment;
-// private TType[] fTypes;
-// private IFunctionBinding fOriginal;
-//
-// public AmbiguousMethodAnalyzer(TypeEnvironment typeEnvironment, IFunctionBinding original, TType[] types) {
-// fTypeEnvironment= typeEnvironment;
-// fOriginal= original;
-// fTypes= types;
-// }
-// public boolean visit(ITypeBinding node) {
-// IFunctionBinding[] methods= node.getDeclaredMethods();
-// for (int i= 0; i < methods.length; i++) {
-// IFunctionBinding candidate= methods[i];
-// if (candidate == fOriginal) {
-// continue;
-// }
-// if (fOriginal.getName().equals(candidate.getName())) {
-// if (canImplicitlyCall(candidate)) {
-// return false;
-// }
-// }
-// }
-// return true;
-// }
-// /**
-// * Returns <code>true</code> if the method can be called without explicit casts;
-// * otherwise <code>false</code>.
-// */
-// private boolean canImplicitlyCall(IFunctionBinding candidate) {
-// ITypeBinding[] parameters= candidate.getParameterTypes();
-// if (parameters.length != fTypes.length) {
-// return false;
-// }
-// for (int i= 0; i < parameters.length; i++) {
-// if (!fTypes[i].canAssignTo(fTypeEnvironment.create(parameters[i]))) {
-// return false;
-// }
-// }
-// return true;
-// }
-// }
-
- public CallInliner(IJavaScriptUnit unit, JavaScriptUnit targetAstRoot, SourceProvider provider) throws CoreException {
- super();
- fCUnit= unit;
- fBuffer= RefactoringFileBuffers.acquire(fCUnit);
- fSourceProvider= provider;
- fImportRewrite= StubUtility.createImportRewrite(targetAstRoot, true);
- fLocals= new ArrayList(3);
- fRewrite= ASTRewrite.create(targetAstRoot.getAST());
- fRewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
- fTypeEnvironment= new TypeEnvironment();
- }
-
- public void dispose() {
- try {
- RefactoringFileBuffers.release(fCUnit);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
-
- public ImportRewrite getImportEdit() {
- return fImportRewrite;
- }
-
- public ASTNode getTargetNode() {
- return fTargetNode;
- }
-
- public void initialize(BodyDeclaration declaration) {
- fBodyDeclaration= declaration;
- fRootScope= CodeScopeBuilder.perform(declaration, fSourceProvider.getDeclaration().resolveBinding());
- fNumberOfLocals= 0;
- switch (declaration.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- case ASTNode.INITIALIZER:
- fNumberOfLocals= LocalVariableIndex.perform(declaration);
- break;
- }
- }
-
- public RefactoringStatus initialize(ASTNode invocation, int severity) {
- RefactoringStatus result= new RefactoringStatus();
- fInvocation= invocation;
- fLocals= new ArrayList(3);
-
- checkMethodDeclaration(result, severity);
- if (result.getSeverity() >= severity)
- return result;
-
- initializeRewriteState();
- initializeTargetNode();
- flowAnalysis();
-
- fContext= new CallContext(fInvocation, fInvocationScope, fTargetNode.getNodeType(), fImportRewrite);
-
- try {
- computeRealArguments();
- computeReceiver();
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- checkInvocationContext(result, severity);
-
- return result;
- }
-
- private void initializeRewriteState() {
- // field initializer can be inside of a block if used in a local class
- // but block can't be a child of field initializer
- if(ASTNodes.getParent(fInvocation, ASTNode.FIELD_DECLARATION) != null) {
- fFieldInitializer= true;
- }
- }
-
- private void initializeTargetNode() {
- ASTNode parent= fInvocation.getParent();
- int nodeType= parent.getNodeType();
- if (nodeType == ASTNode.EXPRESSION_STATEMENT || nodeType == ASTNode.RETURN_STATEMENT) {
- fTargetNode= parent;
- } else {
- fTargetNode= fInvocation;
- }
- }
-
- // the checks depend on invocation context and therefore can't be done in SourceAnalyzer
- private void checkMethodDeclaration(RefactoringStatus result, int severity) {
- FunctionDeclaration methodDeclaration= fSourceProvider.getDeclaration();
- // it is not allowed to inline constructor invocation only if it is used for class instance creation
- // if constructor is invoked from another constructor then we can inline such invocation
- if (fInvocation.getNodeType() != ASTNode.CONSTRUCTOR_INVOCATION && methodDeclaration.isConstructor()) {
- result.addEntry(new RefactoringStatusEntry(
- severity,
- RefactoringCoreMessages.CallInliner_constructors,
- JavaStatusContext.create(fCUnit, fInvocation)));
- }
- if (fSourceProvider.hasSuperMethodInvocation() && fInvocation.getNodeType() == ASTNode.FUNCTION_INVOCATION) {
- Expression receiver= ((FunctionInvocation)fInvocation).getExpression();
- if (receiver instanceof ThisExpression) {
- result.addEntry(new RefactoringStatusEntry(
- severity,
- RefactoringCoreMessages.CallInliner_super_into_this_expression,
- JavaStatusContext.create(fCUnit, fInvocation)));
- }
- }
- }
-
- private void checkInvocationContext(RefactoringStatus result, int severity) {
- if (fInvocation.getNodeType() == ASTNode.FUNCTION_INVOCATION) {
- Expression exp= ((FunctionInvocation)fInvocation).getExpression();
- if (exp != null && exp.resolveTypeBinding() == null) {
- addEntry(result, RefactoringCoreMessages.CallInliner_receiver_type,
- RefactoringStatusCodes.INLINE_METHOD_NULL_BINDING, severity);
- return;
- }
- }
- int nodeType= fTargetNode.getNodeType();
- if (nodeType == ASTNode.EXPRESSION_STATEMENT) {
- if (fSourceProvider.isExecutionFlowInterrupted()) {
- addEntry(result, RefactoringCoreMessages.CallInliner_execution_flow,
- RefactoringStatusCodes.INLINE_METHOD_EXECUTION_FLOW, severity);
- return;
- }
- } else if (nodeType == ASTNode.FUNCTION_INVOCATION) {
- ASTNode parent= fTargetNode.getParent();
- if (isReturnStatement(parent)) {
- //support inlining even if the execution flow is interrupted
- return;
- }
- if (fSourceProvider.isExecutionFlowInterrupted()) {
- addEntry(result, RefactoringCoreMessages.CallInliner_execution_flow,
- RefactoringStatusCodes.INLINE_METHOD_EXECUTION_FLOW, severity);
- return;
- }
- if (isAssignment(parent) || isSingleDeclaration(parent)) {
- // we support inlining expression in assigment and initializers as
- // long as the execution flow isn't interrupted.
- return;
- } else {
- boolean isFieldDeclaration= ASTNodes.getParent(fInvocation, FieldDeclaration.class) != null;
- if (!fSourceProvider.isSimpleFunction()) {
- if (isMultiDeclarationFragment(parent)) {
- addEntry(result, RefactoringCoreMessages.CallInliner_multiDeclaration,
- RefactoringStatusCodes.INLINE_METHOD_INITIALIZER_IN_FRAGEMENT, severity);
- } else if (isFieldDeclaration) {
- addEntry(result,
- RefactoringCoreMessages.CallInliner_field_initializer_simple,
- RefactoringStatusCodes.INLINE_METHOD_FIELD_INITIALIZER, severity);
- } else {
- addEntry(result, RefactoringCoreMessages.CallInliner_simple_functions,
- RefactoringStatusCodes.INLINE_METHOD_ONLY_SIMPLE_FUNCTIONS, severity);
- }
- return;
- }
- if (isFieldDeclaration) {
- int argumentsCount= fContext.arguments.length;
- for (int i= 0; i < argumentsCount; i++) {
- ParameterData parameter= fSourceProvider.getParameterData(i);
- if(parameter.isWrite()) {
- addEntry(result,
- RefactoringCoreMessages.CallInliner_field_initialize_write_parameter,
- RefactoringStatusCodes.INLINE_METHOD_FIELD_INITIALIZER, severity);
- return;
- }
- }
- if(fLocals.size() > 0) {
- addEntry(result,
- RefactoringCoreMessages.CallInliner_field_initialize_new_local,
- RefactoringStatusCodes.INLINE_METHOD_FIELD_INITIALIZER, severity);
- return;
- }
- // verify that the field is not referenced by the initializer method
- VariableDeclarationFragment variable= (VariableDeclarationFragment)ASTNodes.getParent(fInvocation, ASTNode.VARIABLE_DECLARATION_FRAGMENT);
- if(fSourceProvider.isVariableReferenced(variable.resolveBinding())) {
- addEntry(result,
- RefactoringCoreMessages.CallInliner_field_initialize_self_reference,
- RefactoringStatusCodes.INLINE_METHOD_FIELD_INITIALIZER, severity);
- return;
- }
- }
- }
- }
- }
-
- private static boolean isAssignment(ASTNode node) {
- return node instanceof Assignment;
- }
-
- private static boolean isReturnStatement(ASTNode node) {
- return node instanceof ReturnStatement;
- }
-
- private static boolean isSingleDeclaration(ASTNode node) {
- int type= node.getNodeType();
- if (type == ASTNode.SINGLE_VARIABLE_DECLARATION)
- return true;
- if (type == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- node= node.getParent();
- if (node.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT) {
- VariableDeclarationStatement vs= (VariableDeclarationStatement)node;
- return vs.fragments().size() == 1;
- }
- }
- return false;
- }
-
- private static boolean isMultiDeclarationFragment(ASTNode node) {
- int nodeType= node.getNodeType();
- if (nodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- node= node.getParent();
- if (node.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT) {
- VariableDeclarationStatement vs= (VariableDeclarationStatement)node;
- return vs.fragments().size() > 1;
- }
- }
- return false;
- }
-
- private void addEntry(RefactoringStatus result, String message, int code, int severity) {
- result.addEntry(new RefactoringStatusEntry(
- severity, message,
- JavaStatusContext.create(fCUnit, fInvocation),
- Corext.getPluginId(),
- code, null));
- }
-
- private void flowAnalysis() {
- fInvocationScope= fRootScope.findScope(fTargetNode.getStartPosition(), fTargetNode.getLength());
- fInvocationScope.setCursor(fTargetNode.getStartPosition());
- fFlowContext= new FlowContext(0, fNumberOfLocals + 1);
- fFlowContext.setConsiderAccessMode(true);
- fFlowContext.setComputeMode(FlowContext.ARGUMENTS);
- Selection selection= Selection.createFromStartLength(fInvocation.getStartPosition(), fInvocation.getLength());
- switch (fBodyDeclaration.getNodeType()) {
- case ASTNode.INITIALIZER:
- case ASTNode.FIELD_DECLARATION:
- case ASTNode.FUNCTION_DECLARATION:
- fFlowInfo= new InputFlowAnalyzer(fFlowContext, selection, true).perform(fBodyDeclaration);
- break;
- default:
- Assert.isTrue(false, "Should not happen"); //$NON-NLS-1$
- }
- }
-
- public RefactoringStatus perform(TextEditGroup textEditGroup) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- String[] blocks= fSourceProvider.getCodeBlocks(fContext);
- if(!fFieldInitializer) {
- initializeInsertionPoint(fSourceProvider.getNumberOfStatements() + fLocals.size());
- }
-
- addNewLocals(textEditGroup);
- replaceCall(result, blocks, textEditGroup);
- return result;
- }
-
- public TextEdit getModifications() {
- return fRewrite.rewriteAST(fBuffer.getDocument(), fCUnit.getJavaScriptProject().getOptions(true));
- }
-
- private void computeRealArguments() throws BadLocationException {
- List arguments= Invocations.getArguments(fInvocation);
- Set canNotInline= crossCheckArguments(arguments);
- boolean needsVarargBoxing= needsVarargBoxing(arguments);
- int varargIndex= fSourceProvider.getVarargIndex();
- String[] realArguments= new String[needsVarargBoxing ? varargIndex + 1 : arguments.size()];
- for (int i= 0; i < (needsVarargBoxing ? varargIndex : arguments.size()); i++) {
- Expression expression= (Expression)arguments.get(i);
- ParameterData parameter= fSourceProvider.getParameterData(i);
- if (canInline(expression, parameter) && !canNotInline.contains(expression)) {
- realArguments[i] = getContent(expression);
- // fixes bugs #35905, #38471
- if (argumentNeedsParenthesis(expression, parameter)) {
- realArguments[i] = "(" + realArguments[i] + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- String name= fInvocationScope.createName(parameter.getName(), true);
- realArguments[i]= name;
- fLocals.add(createLocalDeclaration(
- parameter.getTypeBinding(), name,
- (Expression)fRewrite.createCopyTarget(expression)));
- }
- }
- if (needsVarargBoxing) {
- ParameterData parameter= fSourceProvider.getParameterData(varargIndex);
- String name= fInvocationScope.createName(parameter.getName(), true);
- realArguments[varargIndex]= name;
- AST ast= fInvocation.getAST();
- Type type= fImportRewrite.addImport(parameter.getTypeBinding(), ast);
- VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
- fragment.setName(ast.newSimpleName(name));
- ArrayInitializer initializer= ast.newArrayInitializer();
- for (int i= varargIndex; i < arguments.size(); i++) {
- initializer.expressions().add(fRewrite.createCopyTarget((ASTNode)arguments.get(i)));
- }
- fragment.setInitializer(initializer);
- VariableDeclarationStatement decl= ast.newVariableDeclarationStatement(fragment);
- decl.setType(type);
- fLocals.add(decl);
- }
- fContext.arguments= realArguments;
- }
-
- private boolean needsVarargBoxing(List arguments) {
- if (!fSourceProvider.isVarargs())
- return false;
- /*
- if (!fSourceProvider.hasArrayAccess())
- return false;
- */
- int index= fSourceProvider.getVarargIndex();
- // we have varags but the call doesn't pass any arguments
- if (index >= arguments.size())
- return true;
- // parameter is array type
- // one arg
- if (index == arguments.size() - 1) {
- ITypeBinding argument= ((Expression)arguments.get(index)).resolveTypeBinding();
- if (argument == null)
- return false;
- ITypeBinding parameter= fSourceProvider.getParameterData(index).getTypeBinding();
- return !fTypeEnvironment.create(argument).canAssignTo(fTypeEnvironment.create(parameter));
- }
- return true;
- }
-
- private boolean argumentNeedsParenthesis(Expression expression, ParameterData param) {
- if (expression instanceof ArrayCreation)
- return true;
- int argPrecedence= OperatorPrecedence.getValue(expression);
- int paramPrecedence= param.getOperatorPrecedence();
- if (argPrecedence != -1 && paramPrecedence != -1)
- return argPrecedence < paramPrecedence;
-
- return false;
- }
-
- private void computeReceiver() throws BadLocationException {
- Expression receiver= Invocations.getExpression(fInvocation);
- if (receiver == null)
- return;
- final boolean isName= receiver instanceof Name;
- if (isName)
- fContext.receiverIsStatic= ((Name)receiver).resolveBinding() instanceof ITypeBinding;
- if (ASTNodes.isLiteral(receiver) || isName || receiver instanceof ThisExpression) {
- fContext.receiver= fBuffer.getDocument().get(receiver.getStartPosition(), receiver.getLength());
- return;
- }
- switch(fSourceProvider.getReceiversToBeUpdated()) {
- case 0:
- // Make sure we evaluate the current receiver. Best is to assign to
- // local.
- fLocals.add(createLocalDeclaration(
- receiver.resolveTypeBinding(),
- fInvocationScope.createName("r", true), //$NON-NLS-1$
- (Expression)fRewrite.createCopyTarget(receiver)));
- return;
- case 1:
- fContext.receiver= fBuffer.getDocument().get(receiver.getStartPosition(), receiver.getLength());
- return;
- default:
- String local= fInvocationScope.createName("r", true); //$NON-NLS-1$
- fLocals.add(createLocalDeclaration(
- receiver.resolveTypeBinding(),
- local,
- (Expression)fRewrite.createCopyTarget(receiver)));
- fContext.receiver= local;
- return;
- }
- }
-
- private void addNewLocals(TextEditGroup textEditGroup) {
- if (fLocals.isEmpty())
- return;
- for (Iterator iter= fLocals.iterator(); iter.hasNext();) {
- ASTNode element= (ASTNode)iter.next();
- fListRewrite.insertAt(element, fInsertionIndex++, textEditGroup);
- }
- }
-
- private void replaceCall(RefactoringStatus status, String[] blocks, TextEditGroup textEditGroup) {
- // Inline empty body
- if (blocks.length == 0) {
- if (fNeedsStatement) {
- fRewrite.replace(fTargetNode, fTargetNode.getAST().newEmptyStatement(), textEditGroup);
- } else {
- fRewrite.remove(fTargetNode, textEditGroup);
- }
- } else {
- ASTNode node= null;
- for (int i= 0; i < blocks.length - 1; i++) {
- node= fRewrite.createStringPlaceholder(blocks[i], ASTNode.RETURN_STATEMENT);
- fListRewrite.insertAt(node, fInsertionIndex++, textEditGroup);
- }
- String block= blocks[blocks.length - 1];
- // We can inline a call where the declaration is a function and the call itself
- // is a statement. In this case we have to create a temporary variable if the
- // returned expression must be evaluated.
- if (fContext.callMode == ASTNode.EXPRESSION_STATEMENT && fSourceProvider.hasReturnValue()) {
- if (fSourceProvider.mustEvaluateReturnedExpression()) {
- if (fSourceProvider.returnValueNeedsLocalVariable()) {
- IFunctionBinding invocation= Invocations.resolveBinding(fInvocation);
- node= createLocalDeclaration(
- invocation.getReturnType(),
- fInvocationScope.createName(fSourceProvider.getMethodName(), true),
- (Expression)fRewrite.createStringPlaceholder(block, ASTNode.FUNCTION_INVOCATION));
- } else {
- node= fTargetNode.getAST().newExpressionStatement(
- (Expression)fRewrite.createStringPlaceholder(block, ASTNode.FUNCTION_INVOCATION));
- }
- } else {
- node= null;
- }
- } else if (fTargetNode instanceof Expression) {
- node= fRewrite.createStringPlaceholder(block, ASTNode.FUNCTION_INVOCATION);
-
- if (needsParenthesis()) {
- ParenthesizedExpression pExp= fTargetNode.getAST().newParenthesizedExpression();
- pExp.setExpression((Expression)node);
- node= pExp;
- }
- } else {
- node= fRewrite.createStringPlaceholder(block, ASTNode.RETURN_STATEMENT);
- }
-
- // Now replace the target node with the source node
- if (node != null) {
- if (fTargetNode == null) {
- fListRewrite.insertAt(node, fInsertionIndex++, textEditGroup);
- } else {
- fRewrite.replace(fTargetNode, node, textEditGroup);
- }
- } else {
- if (fTargetNode != null) {
- fRewrite.remove(fTargetNode, textEditGroup);
- }
- }
- }
- }
- private boolean needsParenthesis() {
- if (!fSourceProvider.needsReturnedExpressionParenthesis())
- return false;
- ASTNode parent= fTargetNode.getParent();
- int type= parent.getNodeType();
- return
- type == ASTNode.FUNCTION_INVOCATION ||
- (parent instanceof Expression && type != ASTNode.ASSIGNMENT) ||
- (fSourceProvider.returnsConditionalExpression() &&
- type == ASTNode.VARIABLE_DECLARATION_FRAGMENT &&
- ((VariableDeclarationFragment)parent).getInitializer() == fTargetNode);
- }
-
- private VariableDeclarationStatement createLocalDeclaration(ITypeBinding type, String name, Expression initializer) {
- String typeName= fImportRewrite.addImport(type);
- VariableDeclarationStatement decl= (VariableDeclarationStatement)ASTNodeFactory.newStatement(
- fInvocation.getAST(), typeName + " " + name + ";"); //$NON-NLS-1$ //$NON-NLS-2$
- ((VariableDeclarationFragment)decl.fragments().get(0)).setInitializer(initializer);
- return decl;
- }
-
- /**
- * Checks whether arguments are passed to the method which do some assignments
- * inside the expression. If so these arguments can't be inlined into the
- * calling method since the assignments might be reorder. An example is:
- * <code>
- * add((field=args).length,field.hashCode());
- * </code>
- * Field might not be initialized when the arguments are reorder in the called
- * method.
- */
- private Set crossCheckArguments(List arguments) {
- final Set assigned= new HashSet();
- final Set result= new HashSet();
- for (Iterator iter= arguments.iterator(); iter.hasNext();) {
- final Expression expression= (Expression) iter.next();
- expression.accept(new ASTVisitor() {
- public boolean visit(Assignment node) {
- Expression lhs= node.getLeftHandSide();
- if (lhs instanceof Name) {
- IBinding binding= ((Name)lhs).resolveBinding();
- if (binding instanceof IVariableBinding) {
- assigned.add(binding);
- result.add(expression);
- }
- }
- return true;
- }
- });
- }
- for (Iterator iter= arguments.iterator(); iter.hasNext();) {
- final Expression expression= (Expression) iter.next();
- if (!result.contains(expression)) {
- expression.accept(new HierarchicalASTVisitor() {
- public boolean visit(Name node) {
- IBinding binding= node.resolveBinding();
- if (binding != null && assigned.contains(binding))
- result.add(expression);
- return false;
- }
- });
- }
- }
- return result;
- }
-
- private boolean canInline(Expression actualParameter, ParameterData formalParameter) {
- InlineEvaluator evaluator= new InlineEvaluator(formalParameter);
- actualParameter.accept(evaluator);
- return evaluator.getResult();
- }
-
- private void initializeInsertionPoint(int nos) {
- fInsertionIndex= -1;
- fNeedsStatement= false;
- // if we have a constructor invocation the invocation itself is already a statement
- ASTNode parentStatement= fInvocation instanceof Statement
- ? fInvocation
- : ASTNodes.getParent(fInvocation, Statement.class);
- ASTNode container= parentStatement.getParent();
- int type= container.getNodeType();
- if (type == ASTNode.BLOCK) {
- Block block= (Block)container;
- fListRewrite= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- fInsertionIndex= fListRewrite.getRewrittenList().indexOf(parentStatement);
- } else if (type == ASTNode.SWITCH_STATEMENT) {
- SwitchStatement switchStatement= (SwitchStatement)container;
- fListRewrite= fRewrite.getListRewrite(switchStatement, SwitchStatement.STATEMENTS_PROPERTY);
- fInsertionIndex= fListRewrite.getRewrittenList().indexOf(parentStatement);
- } else if (isControlStatement(container) || type == ASTNode.LABELED_STATEMENT) {
- fNeedsStatement= true;
- if (nos > 1 || needsBlockAroundDanglingIf()) {
- Block block= fInvocation.getAST().newBlock();
- fInsertionIndex= 0;
- Statement currentStatement= null;
- switch(type) {
- case ASTNode.LABELED_STATEMENT:
- currentStatement= ((LabeledStatement)container).getBody();
- break;
- case ASTNode.FOR_STATEMENT:
- currentStatement= ((ForStatement)container).getBody();
- break;
- case ASTNode.FOR_IN_STATEMENT:
- currentStatement= ((ForInStatement)container).getBody();
- break;
- case ASTNode.ENHANCED_FOR_STATEMENT:
- currentStatement= ((EnhancedForStatement)container).getBody();
- break;
- case ASTNode.WHILE_STATEMENT:
- currentStatement= ((WhileStatement)container).getBody();
- break;
- case ASTNode.WITH_STATEMENT:
- currentStatement= ((WithStatement)container).getBody();
- break;
- case ASTNode.DO_STATEMENT:
- currentStatement= ((DoStatement)container).getBody();
- break;
- case ASTNode.IF_STATEMENT:
- IfStatement node= (IfStatement)container;
- Statement thenPart= node.getThenStatement();
- if (fTargetNode == thenPart || ASTNodes.isParent(fTargetNode, thenPart)) {
- currentStatement= thenPart;
- } else {
- currentStatement= node.getElseStatement();
- }
- break;
- }
- Assert.isNotNull(currentStatement);
- fRewrite.replace(currentStatement, block, null);
- fListRewrite= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- // The method to be inlined is not the body of the control statement.
- if (currentStatement != fTargetNode) {
- fListRewrite.insertLast(fRewrite.createCopyTarget(currentStatement), null);
- } else {
- // We can't replace a copy with something else. So we
- // have to insert all statements to be inlined.
- fTargetNode= null;
- }
- }
- }
- // We only insert one new statement or we delete the existing call.
- // So there is no need to have an insertion index.
- }
-
- private boolean needsBlockAroundDanglingIf() {
- /* see https://bugs.eclipse.org/bugs/show_bug.cgi?id=169331
- *
- * Situation:
- * boolean a, b;
- * void toInline() {
- * if (a)
- * hashCode();
- * }
- * void m() {
- * if (b)
- * toInline();
- * else
- * toString();
- * }
- * => needs block around inlined "if (a)..." to avoid attaching else to wrong if.
- */
- return fTargetNode.getLocationInParent() == IfStatement.THEN_STATEMENT_PROPERTY
- && fTargetNode.getParent().getStructuralProperty(IfStatement.ELSE_STATEMENT_PROPERTY) != null
- && fSourceProvider.isDangligIf();
- }
-
- private String getContent(ASTNode node) throws BadLocationException {
- return fBuffer.getDocument().get(node.getStartPosition(), node.getLength());
- }
-
- private boolean isControlStatement(ASTNode node) {
- int type= node.getNodeType();
- return type == ASTNode.IF_STATEMENT || type == ASTNode.FOR_STATEMENT || type == ASTNode.ENHANCED_FOR_STATEMENT ||
- type == ASTNode.WHILE_STATEMENT || type == ASTNode.DO_STATEMENT;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CodeRefactoringUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CodeRefactoringUtil.java
deleted file mode 100644
index 6ebd034f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/CodeRefactoringUtil.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class CodeRefactoringUtil {
-
- public static RefactoringStatus checkMethodSyntaxErrors(int selectionStart, int selectionLength, JavaScriptUnit cuNode, String invalidSelectionMessage){
- SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(selectionStart, selectionLength), true);
- cuNode.accept(analyzer);
- ASTNode coveringNode= analyzer.getLastCoveringNode();
- if (! (coveringNode instanceof Block) || ! (coveringNode.getParent() instanceof FunctionDeclaration))
- return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage);
- if (ASTNodes.getMessages(coveringNode, ASTNodes.NODE_ONLY).length == 0)
- return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage);
-
- FunctionDeclaration methodDecl= (FunctionDeclaration)coveringNode.getParent();
- String[] keys= {methodDecl.getName().getIdentifier()};
- String message= Messages.format(RefactoringCoreMessages.CodeRefactoringUtil_error_message, keys);
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- public static int getIndentationLevel(ASTNode node, IJavaScriptUnit unit) throws CoreException {
- IPath fullPath= unit.getCorrespondingResource().getFullPath();
- try{
- FileBuffers.getTextFileBufferManager().connect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
- ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(fullPath, LocationKind.IFILE);
- try {
- IRegion region= buffer.getDocument().getLineInformationOfOffset(node.getStartPosition());
- return Strings.computeIndentUnits(buffer.getDocument().get(region.getOffset(), region.getLength()), unit.getJavaScriptProject());
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return 0;
- } finally {
- FileBuffers.getTextFileBufferManager().disconnect(fullPath, LocationKind.IFILE, new NullProgressMonitor());
- }
- }
-
- private CodeRefactoringUtil() {}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConstantChecks.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConstantChecks.java
deleted file mode 100644
index f9b0ccfa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConstantChecks.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IExpressionFragment;
-
-class ConstantChecks {
- private static abstract class ExpressionChecker extends ASTVisitor {
-
- private final IExpressionFragment fExpression;
- protected boolean fResult= true;
-
- public ExpressionChecker(IExpressionFragment ex) {
- fExpression= ex;
- }
- public boolean check() {
- fResult= true;
- fExpression.getAssociatedNode().accept(this);
- return fResult;
- }
- }
-
- private static class LoadTimeConstantChecker extends ExpressionChecker {
- public LoadTimeConstantChecker(IExpressionFragment ex) {
- super(ex);
- }
-
- public boolean visit(SuperFieldAccess node) {
- fResult= false;
- return false;
- }
- public boolean visit(SuperMethodInvocation node) {
- fResult= false;
- return false;
- }
- public boolean visit(ThisExpression node) {
- fResult= false;
- return false;
- }
- public boolean visit(FieldAccess node) {
- fResult= new LoadTimeConstantChecker((IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(node.getExpression())).check();
- return false;
- }
- public boolean visit(FunctionInvocation node) {
- if(node.getExpression() == null) {
- visitName(node.getName());
- } else {
- fResult= new LoadTimeConstantChecker((IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(node.getExpression())).check();
- }
-
- return false;
- }
- public boolean visit(QualifiedName node) {
- return visitName(node);
- }
- public boolean visit(SimpleName node) {
- return visitName(node);
- }
-
- private boolean visitName(Name name) {
- fResult= checkName(name);
- return false; //Do not descend further
- }
-
- private boolean checkName(Name name) {
- IBinding binding= name.resolveBinding();
- if (binding == null)
- return true; /* If the binding is null because of compile errors etc.,
- scenarios which may have been deemed unacceptable in
- the presence of semantic information will be admitted. */
-
- // If name represents a member:
- if (binding instanceof IVariableBinding || binding instanceof IFunctionBinding)
- return isMemberReferenceValidInClassInitialization(name);
- else if (binding instanceof ITypeBinding)
- return true;
- else {
- /* IPackageBinding is not expected, as a package name not
- used as a type name prefix is not expected in such an
- expression. Other types are not expected either.
- */
- Assert.isTrue(false);
- return true;
- }
- }
-
- private boolean isMemberReferenceValidInClassInitialization(Name name) {
- IBinding binding= name.resolveBinding();
- Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IFunctionBinding);
-
- if(name instanceof SimpleName)
- return Modifier.isStatic(binding.getModifiers());
- else {
- Assert.isTrue(name instanceof QualifiedName);
- return checkName(((QualifiedName) name).getQualifier());
- }
- }
- }
-
- private static class StaticFinalConstantChecker extends ExpressionChecker {
- public StaticFinalConstantChecker(IExpressionFragment ex) {
- super(ex);
- }
-
- public boolean visit(SuperFieldAccess node) {
- fResult= false;
- return false;
- }
- public boolean visit(SuperMethodInvocation node) {
- fResult= false;
- return false;
- }
- public boolean visit(ThisExpression node) {
- fResult= false;
- return false;
- }
-
- public boolean visit(QualifiedName node) {
- return visitName(node);
- }
- public boolean visit(SimpleName node) {
- return visitName(node);
- }
- private boolean visitName(Name name) {
- IBinding binding= name.resolveBinding();
- if(binding == null) {
- /* If the binding is null because of compile errors etc.,
- scenarios which may have been deemed unacceptable in
- the presence of semantic information will be admitted.
- Descend deeper.
- */
- return true;
- }
-
- int modifiers= binding.getModifiers();
- if(binding instanceof IVariableBinding) {
- if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) {
- fResult= false;
- return false;
- }
- } else if(binding instanceof IFunctionBinding) {
- if (!Modifier.isStatic(modifiers)) {
- fResult= false;
- return false;
- }
- } else if(binding instanceof ITypeBinding) {
- return false; // It's o.k. Don't descend deeper.
-
- } else {
- /* IPackageBinding is not expected, as a package name not
- used as a type name prefix is not expected in such an
- expression. Other types are not expected either.
- */
- Assert.isTrue(false);
- return false;
- }
-
- //Descend deeper:
- return true;
- }
- }
-
- public static boolean isStaticFinalConstant(IExpressionFragment ex) {
- return new StaticFinalConstantChecker(ex).check();
- }
-
- public static boolean isLoadTimeConstant(IExpressionFragment ex) {
- return new LoadTimeConstantChecker(ex).check();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java
deleted file mode 100644
index 2c0db01f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java
+++ /dev/null
@@ -1,1032 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * N.Metchev@teamphone.com - contributed fixes for
- * - convert anonymous to nested should sometimes declare class as static [refactoring]
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=43360)
- * - Convert anonymous to nested: should show error if field form outer anonymous type is references [refactoring]
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=48282)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ModifierCorrectionSubProcessor;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ConvertAnonymousToNestedRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FINAL= "final"; //$NON-NLS-1$
- private static final String ATTRIBUTE_STATIC= "static"; //$NON-NLS-1$
-
- private static final String KEY_TYPE_NAME= "type_name"; //$NON-NLS-1$
- private static final String KEY_PARAM_NAME_EXT= "param_name_ext"; //$NON-NLS-1$
- private static final String KEY_PARAM_NAME_CONST= "param_name_const"; //$NON-NLS-1$
- private static final String KEY_FIELD_NAME_EXT= "field_name_ext"; //$NON-NLS-1$
-
- public static class TypeVariableFinder extends ASTVisitor {
-
- private final List fFound= new ArrayList();
-
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- node.resolveTypeBinding();
- return true;
- }
-
- public final ITypeBinding[] getResult() {
- final ITypeBinding[] result= new ITypeBinding[fFound.size()];
- fFound.toArray(result);
- return result;
- }
- }
-
- private int fSelectionStart;
- private int fSelectionLength;
- private IJavaScriptUnit fCu;
-
- private int fVisibility; /* see Modifier */
- private boolean fDeclareFinal= true;
- private boolean fDeclareStatic;
- private String fClassName= ""; //$NON-NLS-1$
-
- private JavaScriptUnit fCompilationUnitNode;
- private AnonymousClassDeclaration fAnonymousInnerClassNode;
- private Set fClassNamesUsed;
- private boolean fSelfInitializing= false;
-
- private LinkedProposalModel fLinkedProposalModel;
-
- /**
- * Creates a new convert anonymous to nested refactoring
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public ConvertAnonymousToNestedRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- Assert.isTrue(unit == null || unit.exists());
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= unit;
- fAnonymousInnerClassNode= null;
- fCompilationUnitNode= null;
- }
-
- public ConvertAnonymousToNestedRefactoring(AnonymousClassDeclaration declaration) {
- Assert.isTrue(declaration != null);
-
- ASTNode astRoot= declaration.getRoot();
- Assert.isTrue(astRoot instanceof JavaScriptUnit);
- fCompilationUnitNode= (JavaScriptUnit) astRoot;
-
- IJavaScriptElement javaElement= fCompilationUnitNode.getJavaElement();
- Assert.isTrue(javaElement instanceof IJavaScriptUnit);
-
- fCu= (IJavaScriptUnit) javaElement;
- fSelectionStart= declaration.getStartPosition();
- fSelectionLength= declaration.getLength();
- }
-
- public void setLinkedProposalModel(LinkedProposalModel linkedProposalModel) {
- fLinkedProposalModel= linkedProposalModel;
- }
-
- public int[] getAvailableVisibilities() {
- if (isLocalInnerType()) {
- return new int[] { Modifier.NONE };
- } else {
- return new int[] { Modifier.PUBLIC, Modifier.PROTECTED, Modifier.NONE, Modifier.PRIVATE };
- }
- }
-
- public boolean isLocalInnerType() {
- return ASTNodes.getParent(ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class), ASTNode.ANONYMOUS_CLASS_DECLARATION) != null;
- }
-
- public int getVisibility() {
- return fVisibility;
- }
-
- public void setVisibility(int visibility) {
- Assert.isTrue(visibility == Modifier.PRIVATE || visibility == Modifier.NONE || visibility == Modifier.PROTECTED || visibility == Modifier.PUBLIC);
- fVisibility= visibility;
- }
-
- public void setClassName(String className) {
- Assert.isNotNull(className);
- fClassName= className;
- }
-
- public boolean canEnableSettingFinal() {
- return true;
- }
-
- public boolean getDeclareFinal() {
- return fDeclareFinal;
- }
-
- public boolean getDeclareStatic() {
- return fDeclareStatic;
- }
-
- public void setDeclareFinal(boolean declareFinal) {
- fDeclareFinal= declareFinal;
- }
-
- public void setDeclareStatic(boolean declareStatic) {
- fDeclareStatic= declareStatic;
- }
-
- public String getName() {
- return RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_name;
- }
-
- private boolean useThisForFieldAccess() {
- return StubUtility.useThisForFieldAccess(fCu.getJavaScriptProject());
- }
-
- private boolean doAddComments() {
- return StubUtility.doAddComments(fCu.getJavaScriptProject());
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= Checks.validateModifiesFiles(
- ResourceUtil.getFiles(new IJavaScriptUnit[]{fCu}),
- getValidationContext());
- if (result.hasFatalError())
- return result;
-
- initAST(pm);
-
- if (fAnonymousInnerClassNode == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_place_caret);
- if (!fSelfInitializing)
- initializeDefaults();
- if (getSuperConstructorBinding() == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_compile_errors);
- if (getSuperTypeBinding().isLocal())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_extends_local_class);
- return new RefactoringStatus();
- }
-
- private void initializeDefaults() {
- fVisibility= isLocalInnerType() ? Modifier.NONE : Modifier.PRIVATE;
- fDeclareStatic = mustInnerClassBeStatic();
- }
-
- private void initAST(IProgressMonitor pm) {
- if (fCompilationUnitNode == null) {
- fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
- }
- if (fAnonymousInnerClassNode == null) {
- fAnonymousInnerClassNode= getAnonymousInnerClass(NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
- }
- if (fAnonymousInnerClassNode != null) {
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
- if (declaration instanceof TypeDeclaration) {
- final AbstractTypeDeclaration[] nested= ((TypeDeclaration) declaration).getTypes();
- fClassNamesUsed= new HashSet(nested.length);
- for (int index= 0; index < nested.length; index++)
- fClassNamesUsed.add(nested[index].getName().getIdentifier());
- } else
- fClassNamesUsed= Collections.EMPTY_SET;
- }
- }
-
- private static AnonymousClassDeclaration getAnonymousInnerClass(ASTNode node) {
- if (node == null)
- return null;
- if (node instanceof AnonymousClassDeclaration)
- return (AnonymousClassDeclaration)node;
- if (node instanceof ClassInstanceCreation) {
- AnonymousClassDeclaration anon= ((ClassInstanceCreation)node).getAnonymousClassDeclaration();
- if (anon != null)
- return anon;
- }
- node= ASTNodes.getNormalizedNode(node);
- if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
- AnonymousClassDeclaration anon= ((ClassInstanceCreation)node.getParent()).getAnonymousClassDeclaration();
- if (anon != null)
- return anon;
- }
- return (AnonymousClassDeclaration)ASTNodes.getParent(node, AnonymousClassDeclaration.class);
- }
-
- public RefactoringStatus validateInput() {
- RefactoringStatus result= Checks.checkTypeName(fClassName);
- if (result.hasFatalError())
- return result;
-
- if (fClassNamesUsed.contains(fClassName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_type_exists);
- IFunctionBinding superConstructorBinding = getSuperConstructorBinding();
- if (superConstructorBinding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_compile_errors);
- if (fClassName.equals(superConstructorBinding.getDeclaringClass().getName()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_another_name);
- if (classNameHidesEnclosingType())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_name_hides);
- return result;
- }
-
- private boolean accessesAnonymousFields() {
- List anonymousInnerFieldTypes = getAllEnclosingAnonymousTypesField();
- List accessedField = getAllAccessedFields();
- final Iterator it = anonymousInnerFieldTypes.iterator();
- while(it.hasNext()) {
- final IVariableBinding variableBinding = (IVariableBinding) it.next();
- final Iterator it2 = accessedField.iterator();
- while (it2.hasNext()) {
- IVariableBinding variableBinding2 = (IVariableBinding) it2.next();
- if(Bindings.equals(variableBinding, variableBinding2)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private List getAllAccessedFields() {
- final List accessedFields= new ArrayList();
-
- ASTVisitor visitor= new ASTVisitor() {
-
- public boolean visit(FieldAccess node) {
- final IVariableBinding binding= node.resolveFieldBinding();
- if (binding != null)
- accessedFields.add(binding);
- return super.visit(node);
- }
-
- public boolean visit(QualifiedName node) {
- final IBinding binding= node.resolveBinding();
- if (binding != null && binding instanceof IVariableBinding) {
- IVariableBinding variable= (IVariableBinding) binding;
- if (variable.isField())
- accessedFields.add(binding);
- }
- return super.visit(node);
- }
-
- public boolean visit(SimpleName node) {
- final IBinding binding= node.resolveBinding();
- if (binding != null && binding instanceof IVariableBinding) {
- IVariableBinding variable= (IVariableBinding) binding;
- if (variable.isField())
- accessedFields.add(binding);
- }
- return super.visit(node);
- }
-
- public boolean visit(SuperFieldAccess node) {
- final IVariableBinding binding= node.resolveFieldBinding();
- if (binding != null)
- accessedFields.add(binding);
- return super.visit(node);
- }
- };
- fAnonymousInnerClassNode.accept(visitor);
-
- return accessedFields;
- }
-
- private List getAllEnclosingAnonymousTypesField() {
- final List ans= new ArrayList();
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
- AnonymousClassDeclaration anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, ASTNode.ANONYMOUS_CLASS_DECLARATION);
- while (anonymous != null) {
- if (ASTNodes.isParent(anonymous, declaration)) {
- ITypeBinding binding= anonymous.resolveBinding();
- if (binding != null) {
- ans.addAll(Arrays.asList(binding.getDeclaredFields()));
- }
- } else {
- break;
- }
- anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(anonymous, ASTNode.ANONYMOUS_CLASS_DECLARATION);
- }
- return ans;
- }
-
- private boolean classNameHidesEnclosingType() {
- ITypeBinding type= ((AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class)).resolveBinding();
- while (type != null) {
- if (fClassName.equals(type.getName()))
- return true;
- type= type.getDeclaringClass();
- }
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- try {
- RefactoringStatus status= validateInput();
- if (accessesAnonymousFields())
- status.merge(RefactoringStatus.createErrorStatus(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_anonymous_field_access));
- return status;
- } finally {
- pm.done();
- }
- }
-
- public CompilationUnitChange createCompilationUnitChange(IProgressMonitor pm) throws CoreException {
- final CompilationUnitRewrite rewrite= new CompilationUnitRewrite(fCu, fCompilationUnitNode);
- addNestedClass(rewrite, null);
- modifyConstructorCall(rewrite, null);
- return rewrite.createChange(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_name, false, pm);
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- final CompilationUnitChange result= createCompilationUnitChange(pm);
- result.setDescriptor(createRefactoringDescriptor());
- return result;
- }
-
- private RefactoringChangeDescriptor createRefactoringDescriptor() {
- final ITypeBinding binding= fAnonymousInnerClassNode.resolveBinding();
- final String[] labels= new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringMethod(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final Map arguments= new HashMap();
- final String projectName= fCu.getJavaScriptProject().getElementName();
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- final String description= RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_descriptor_description_short;
- final String header= Messages.format(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_descriptor_description, labels);
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(projectName, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_class_name_pattern, fClassName));
- String visibility= JdtFlags.getVisibilityString(fVisibility);
- if (visibility.length() == 0)
- visibility= RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_default_visibility;
- comment.addSetting(Messages.format(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_visibility_pattern, visibility));
- if (fDeclareFinal && fDeclareStatic)
- comment.addSetting(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_declare_final_static);
- else if (fDeclareFinal)
- comment.addSetting(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_declare_final);
- else if (fDeclareStatic)
- comment.addSetting(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_declare_static);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.CONVERT_ANONYMOUS, projectName, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fClassName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + ' ' + new Integer(fSelectionLength).toString());
- arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
- arguments.put(ATTRIBUTE_STATIC, Boolean.valueOf(fDeclareStatic).toString());
- arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
- return new RefactoringChangeDescriptor(descriptor);
- }
-
- private void modifyConstructorCall(CompilationUnitRewrite rewrite, ITypeBinding[] parameters) {
- rewrite.getASTRewrite().replace(fAnonymousInnerClassNode.getParent(), createNewClassInstanceCreation(rewrite, parameters), null);
- }
-
- private ASTNode createNewClassInstanceCreation(CompilationUnitRewrite rewrite, ITypeBinding[] parameters) {
- AST ast= fAnonymousInnerClassNode.getAST();
- ClassInstanceCreation newClassCreation= ast.newClassInstanceCreation();
- newClassCreation.setAnonymousClassDeclaration(null);
- Type type= null;
- SimpleName newNameNode= ast.newSimpleName(fClassName);
- if (parameters.length > 0) {
- } else
- type= ast.newSimpleType(newNameNode);
- newClassCreation.setType(type);
- copyArguments(rewrite, newClassCreation);
- addArgumentsForLocalsUsedInInnerClass(rewrite, newClassCreation);
-
- addLinkedPosition(KEY_TYPE_NAME, newNameNode, rewrite.getASTRewrite(), true);
-
- return newClassCreation;
- }
-
- private void addArgumentsForLocalsUsedInInnerClass(CompilationUnitRewrite rewrite, ClassInstanceCreation newClassCreation) {
- IVariableBinding[] usedLocals= getUsedLocalVariables();
- for (int i= 0; i < usedLocals.length; i++) {
- final AST ast= fAnonymousInnerClassNode.getAST();
- final IVariableBinding binding= usedLocals[i];
- Name name= ast.newSimpleName(binding.getName());
- newClassCreation.arguments().add(name);
- }
- }
-
- private void copyArguments(CompilationUnitRewrite rewrite, ClassInstanceCreation newClassCreation) {
- for (Iterator iter= ((ClassInstanceCreation) fAnonymousInnerClassNode.getParent()).arguments().iterator(); iter.hasNext(); )
- newClassCreation.arguments().add(rewrite.getASTRewrite().createCopyTarget((Expression)iter.next()));
- }
-
- private void addNestedClass(CompilationUnitRewrite rewrite, ITypeBinding[] typeParameters) throws CoreException {
- final AbstractTypeDeclaration declarations= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
- int index= findIndexOfFistNestedClass(declarations.bodyDeclarations());
- if (index == -1)
- index= 0;
- rewrite.getASTRewrite().getListRewrite(declarations, declarations.getBodyDeclarationsProperty()).insertAt(createNewNestedClass(rewrite), index, null);
- }
-
- private static int findIndexOfFistNestedClass(List bodyDeclarations) {
- for (int i= 0, n= bodyDeclarations.size(); i < n; i++) {
- BodyDeclaration each= (BodyDeclaration)bodyDeclarations.get(i);
- if (isNestedType(each))
- return i;
- }
- return -1;
- }
-
- private static boolean isNestedType(BodyDeclaration each) {
- if (!(each instanceof AbstractTypeDeclaration))
- return false;
- return (each.getParent() instanceof AbstractTypeDeclaration);
- }
-
- private AbstractTypeDeclaration createNewNestedClass(CompilationUnitRewrite rewrite) throws CoreException {
- final AST ast= fAnonymousInnerClassNode.getAST();
-
- final TypeDeclaration newDeclaration= ast.newTypeDeclaration();
- newDeclaration.setJavadoc(null);
- newDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiersForNestedClass()));
- newDeclaration.setName(ast.newSimpleName(fClassName));
-
- setSuperType(newDeclaration);
-
- IJavaScriptProject project= fCu.getJavaScriptProject();
-
- IVariableBinding[] bindings= getUsedLocalVariables();
- ArrayList fieldNames= new ArrayList();
- for (int i= 0; i < bindings.length; i++) {
- String name= StubUtility.removePrefixAndSuffixForVariable(project, bindings[i]);
- String[] fieldNameProposals= StubUtility.getVariableNameSuggestions(StubUtility.INSTANCE_FIELD, project, name, 0, fieldNames, true);
- fieldNames.add(fieldNameProposals[0]);
-
-
- if (fLinkedProposalModel != null) {
- LinkedProposalPositionGroup positionGroup= fLinkedProposalModel.getPositionGroup(KEY_FIELD_NAME_EXT + i, true);
- for (int k= 0; k < fieldNameProposals.length; k++) {
- positionGroup.addProposal(fieldNameProposals[k], null, fieldNameProposals.length - k);
- }
- }
- }
- String[] allFieldNames= (String[]) fieldNames.toArray(new String[fieldNames.size()]);
-
- List newBodyDeclarations= newDeclaration.bodyDeclarations();
-
- createFieldsForAccessedLocals(rewrite, bindings, allFieldNames, newBodyDeclarations);
-
- FunctionDeclaration newConstructorDecl= createNewConstructor(rewrite, bindings, allFieldNames);
- if (newConstructorDecl != null) {
- newBodyDeclarations.add(newConstructorDecl);
- }
-
- updateAndMoveBodyDeclarations(rewrite, bindings, allFieldNames, newBodyDeclarations, newConstructorDecl);
-
- if (doAddComments()) {
- String string= CodeGeneration.getTypeComment(rewrite.getCu(), fClassName, StubUtility.getLineDelimiterUsed(fCu));
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.getASTRewrite().createStringPlaceholder(string, ASTNode.JSDOC);
- newDeclaration.setJavadoc(javadoc);
- }
- }
- if (fLinkedProposalModel != null) {
- addLinkedPosition(KEY_TYPE_NAME, newDeclaration.getName(), rewrite.getASTRewrite(), false);
- ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite.getASTRewrite(), newDeclaration.modifiers(), false);
- }
-
- return newDeclaration;
- }
-
- private void updateAndMoveBodyDeclarations(CompilationUnitRewrite rewriter, IVariableBinding[] bindings, String[] fieldNames, List newBodyDeclarations, FunctionDeclaration newConstructorDecl) throws JavaScriptModelException {
- final ASTRewrite astRewrite= rewriter.getASTRewrite();
- final AST ast= astRewrite.getAST();
-
- final boolean useThisAccess= useThisForFieldAccess();
-
- int fieldInsertIndex= newConstructorDecl != null ? newBodyDeclarations.lastIndexOf(newConstructorDecl) : newBodyDeclarations.size();
-
- for (Iterator iterator= fAnonymousInnerClassNode.bodyDeclarations().iterator(); iterator.hasNext();) {
- BodyDeclaration body= (BodyDeclaration) iterator.next();
-
- for (int i= 0; i < bindings.length; i++) {
- SimpleName[] names= LinkedNodeFinder.findByBinding(body, bindings[i]);
- String fieldName= fieldNames[i];
- for (int k= 0; k < names.length; k++) {
- SimpleName newNode= ast.newSimpleName(fieldName);
- if (useThisAccess) {
- FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(newNode);
- astRewrite.replace(names[k], access, null);
- } else {
- astRewrite.replace(names[k], newNode, null);
- }
- addLinkedPosition(KEY_FIELD_NAME_EXT + i, newNode, astRewrite, false);
- }
- }
- if (body instanceof Initializer || body instanceof FieldDeclaration) {
- newBodyDeclarations.add(fieldInsertIndex++, astRewrite.createMoveTarget(body));
- } else {
- newBodyDeclarations.add(astRewrite.createMoveTarget(body));
- }
- }
-
- if (newConstructorDecl != null) {
- // move initialization of existing fields to constructor if an outer is referenced
- List bodyStatements= newConstructorDecl.getBody().statements();
-
- List fieldsToInitializeInConstructor= getFieldsToInitializeInConstructor();
- for (Iterator iter= fieldsToInitializeInConstructor.iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) iter.next();
- Expression initializer= fragment.getInitializer();
- Expression replacement= (Expression) astRewrite.get(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY);
- if (replacement == initializer) {
- replacement= (Expression) astRewrite.createMoveTarget(initializer);
- }
- astRewrite.remove(initializer, null);
- SimpleName fieldNameNode= ast.newSimpleName(fragment.getName().getIdentifier());
- bodyStatements.add(newFieldAssignment(ast, fieldNameNode, replacement, useThisAccess));
- }
- }
- }
-
- private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List newBodyDeclarations) {
- final ImportRewrite importRewrite= rewrite.getImportRewrite();
- final ASTRewrite astRewrite= rewrite.getASTRewrite();
- final AST ast= astRewrite.getAST();
-
- for (int i= 0; i < varBindings.length; i++) {
- VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
- fragment.setExtraDimensions(0);
- fragment.setInitializer(null);
- fragment.setName(ast.newSimpleName(fieldNames[i]));
- FieldDeclaration field= ast.newFieldDeclaration(fragment);
- ITypeBinding varType= varBindings[i].getType();
- field.setType(importRewrite.addImport(varType, ast));
- field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL));
- if (doAddComments()) {
- try {
- String string= CodeGeneration.getFieldComment(rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu));
- if (string != null) {
- JSdoc javadoc= (JSdoc) astRewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- field.setJavadoc(javadoc);
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
- newBodyDeclarations.add(field);
-
- addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false);
- }
- }
-
- private void addLinkedPosition(String key, ASTNode nodeToTrack, ASTRewrite rewrite, boolean isFirst) {
- if (fLinkedProposalModel != null) {
- fLinkedProposalModel.getPositionGroup(key, true).addPosition(rewrite.track(nodeToTrack), isFirst);
- }
- }
-
-
- private IVariableBinding[] getUsedLocalVariables() {
- final Set result= new HashSet(0);
- collectRefrencedVariables(fAnonymousInnerClassNode, result);
- ArrayList usedLocals= new ArrayList();
- for (Iterator iterator= result.iterator(); iterator.hasNext();) {
- IVariableBinding next= (IVariableBinding) iterator.next();
- if (isBindingToTemp(next)) {
- usedLocals.add(next);
- }
- }
- return (IVariableBinding[])usedLocals.toArray(new IVariableBinding[usedLocals.size()]);
- }
-
- private void collectRefrencedVariables(ASTNode root, final Set result) {
- root.accept(new ASTVisitor() {
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding)
- result.add(binding);
- return true;
- }
- });
- }
-
- private boolean isBindingToTemp(IVariableBinding variable) {
- if (variable.isField())
- return false;
- if (!Modifier.isFinal(variable.getModifiers()))
- return false;
- ASTNode declaringNode= fCompilationUnitNode.findDeclaringNode(variable);
- if (declaringNode == null)
- return false;
- if (ASTNodes.isParent(declaringNode, fAnonymousInnerClassNode))
- return false;
- return true;
- }
-
- private FunctionDeclaration createNewConstructor(CompilationUnitRewrite rewrite, IVariableBinding[] bindings, String[] fieldNames) throws JavaScriptModelException {
- ClassInstanceCreation instanceCreation= (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
-
- if (instanceCreation.arguments().isEmpty() && bindings.length == 0)
- return null;
-
- IJavaScriptProject project= fCu.getJavaScriptProject();
- AST ast= rewrite.getAST();
- ImportRewrite importRewrite= rewrite.getImportRewrite();
- ASTRewrite astRewrite= rewrite.getASTRewrite();
-
- FunctionDeclaration newConstructor= ast.newFunctionDeclaration();
- newConstructor.setConstructor(true);
- newConstructor.setExtraDimensions(0);
- newConstructor.setJavadoc(null);
- newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, fVisibility));
- newConstructor.setName(ast.newSimpleName(fClassName));
- addLinkedPosition(KEY_TYPE_NAME, newConstructor.getName(), astRewrite, false);
-
- newConstructor.setBody(ast.newBlock());
-
- List newStatements= newConstructor.getBody().statements();
-
- List newParameters= newConstructor.parameters();
- List newParameterNames= new ArrayList();
-
- // add parameters for elements passed with the instance creation
- if (!instanceCreation.arguments().isEmpty()) {
- IFunctionBinding constructorBinding= getSuperConstructorBinding();
- if (constructorBinding != null) {
- SuperConstructorInvocation superConstructorInvocation= ast.newSuperConstructorInvocation();
- ITypeBinding[] parameterTypes= constructorBinding.getParameterTypes();
- String[][] parameterNames= StubUtility.suggestArgumentNamesWithProposals(project, constructorBinding);
- for (int i= 0; i < parameterNames.length; i++) {
- String[] nameProposals= parameterNames[i];
- String paramName= nameProposals[0];
-
- SingleVariableDeclaration param= newParameterDeclaration(ast, importRewrite, paramName, parameterTypes[i]);
- newParameters.add(param);
- newParameterNames.add(paramName);
-
- SimpleName newSIArgument= ast.newSimpleName(paramName);
- superConstructorInvocation.arguments().add(newSIArgument);
-
- if (fLinkedProposalModel != null) {
- LinkedProposalPositionGroup positionGroup= fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_CONST+ String.valueOf(i), true);
- positionGroup.addPosition(astRewrite.track(param.getName()), false);
- positionGroup.addPosition(astRewrite.track(newSIArgument), false);
- for (int k= 0; k < nameProposals.length; k++) {
- positionGroup.addProposal(nameProposals[k], null, nameProposals.length - k);
- }
- }
- }
- newStatements.add(superConstructorInvocation);
- }
- }
- // add parameters for all outer variables used
- boolean useThisAccess= useThisForFieldAccess();
- for (int i= 0; i < bindings.length; i++) {
- String baseName= StubUtility.removePrefixAndSuffixForVariable(project, bindings[i]);
- String[] paramNameProposals= StubUtility.getVariableNameSuggestions(StubUtility.PARAMETER, project, baseName, 0, newParameterNames, true);
- String paramName= paramNameProposals[0];
-
- SingleVariableDeclaration param= newParameterDeclaration(ast, importRewrite, paramName, bindings[i].getType());
- newParameters.add(param);
- newParameterNames.add(paramName);
-
- String fieldName= fieldNames[i];
- SimpleName fieldNameNode= ast.newSimpleName(fieldName);
- SimpleName paramNameNode= ast.newSimpleName(paramName);
- newStatements.add(newFieldAssignment(ast, fieldNameNode, paramNameNode, useThisAccess || newParameterNames.contains(fieldName)));
-
- if (fLinkedProposalModel != null) {
- LinkedProposalPositionGroup positionGroup= fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_EXT+ String.valueOf(i), true);
- positionGroup.addPosition(astRewrite.track(param.getName()), false);
- positionGroup.addPosition(astRewrite.track(paramNameNode), false);
- for (int k= 0; k < paramNameProposals.length; k++) {
- positionGroup.addProposal(paramNameProposals[k], null, paramNameProposals.length - k);
- }
-
- fLinkedProposalModel.getPositionGroup(KEY_FIELD_NAME_EXT + i, true).addPosition(astRewrite.track(fieldNameNode), false);
- }
- }
-
- if (doAddComments()) {
- try {
- String[] allParamNames= (String[]) newParameterNames.toArray(new String[newParameterNames.size()]);
- String string= CodeGeneration.getMethodComment(fCu, fClassName, fClassName, allParamNames, new String[0], null, null, StubUtility.getLineDelimiterUsed(fCu));
- if (string != null) {
- JSdoc javadoc= (JSdoc) astRewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- newConstructor.setJavadoc(javadoc);
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- return newConstructor;
- }
-
- private Statement newFieldAssignment(AST ast, SimpleName fieldNameNode, Expression initializer, boolean useThisAccess) {
- Assignment assignment= ast.newAssignment();
- if (useThisAccess) {
- FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(fieldNameNode);
- assignment.setLeftHandSide(access);
- } else {
- assignment.setLeftHandSide(fieldNameNode);
- }
- assignment.setOperator(Assignment.Operator.ASSIGN);
- assignment.setRightHandSide(initializer);
-
- return ast.newExpressionStatement(assignment);
- }
-
-
- // live List of VariableDeclarationFragments
- private List getFieldsToInitializeInConstructor() {
- List result= new ArrayList(0);
- for (Iterator iter= fAnonymousInnerClassNode.bodyDeclarations().iterator(); iter.hasNext(); ) {
- Object element= iter.next();
- if (element instanceof FieldDeclaration) {
- List fragments= ((FieldDeclaration) element).fragments();
- for (Iterator fragmentIter= fragments.iterator(); fragmentIter.hasNext(); ) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragmentIter.next();
- if (isToBeInitializerInConstructor(fragment, result))
- result.add(fragment);
- }
- }
- }
- return result;
- }
-
- private boolean isToBeInitializerInConstructor(VariableDeclarationFragment fragment, List fieldsToInitialize) {
- return fragment.getInitializer() != null && areLocalsUsedIn(fragment.getInitializer(), fieldsToInitialize);
- }
-
- private boolean areLocalsUsedIn(Expression fieldInitializer, List fieldsToInitialize) {
- Set localsUsed= new HashSet(0);
- collectRefrencedVariables(fieldInitializer, localsUsed);
-
- ITypeBinding anonType= fAnonymousInnerClassNode.resolveBinding();
-
- for (Iterator iterator= localsUsed.iterator(); iterator.hasNext();) {
- IVariableBinding curr= (IVariableBinding) iterator.next();
- if (isBindingToTemp(curr)) { // reference a local from outside
- return true;
- } else if (curr.isField() && (curr.getDeclaringClass() == anonType) && fieldsToInitialize.contains(fCompilationUnitNode.findDeclaringNode(curr))) {
- return true; // references a field that references a local from outside
- }
- }
- return false;
- }
-
- private IFunctionBinding getSuperConstructorBinding() {
- //workaround for missing java core functionality - finding a
- // super constructor for an anonymous class creation
- IFunctionBinding anonConstr= ((ClassInstanceCreation) fAnonymousInnerClassNode.getParent()).resolveConstructorBinding();
- if (anonConstr == null)
- return null;
- ITypeBinding superClass= anonConstr.getDeclaringClass().getSuperclass();
- IFunctionBinding[] superMethods= superClass.getDeclaredMethods();
- for (int i= 0; i < superMethods.length; i++) {
- IFunctionBinding superMethod= superMethods[i];
- if (superMethod.isConstructor() && parameterTypesMatch(superMethod, anonConstr))
- return superMethod;
- }
- Assert.isTrue(false);//there's no way - it must be there
- return null;
- }
-
- private static boolean parameterTypesMatch(IFunctionBinding m1, IFunctionBinding m2) {
- ITypeBinding[] m1Params= m1.getParameterTypes();
- ITypeBinding[] m2Params= m2.getParameterTypes();
- if (m1Params.length != m2Params.length)
- return false;
- for (int i= 0; i < m2Params.length; i++) {
- if (!m1Params[i].equals(m2Params[i]))
- return false;
- }
- return true;
- }
-
- private SingleVariableDeclaration newParameterDeclaration(AST ast, ImportRewrite importRewrite, String paramName, ITypeBinding paramType) {
- SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
- param.setExtraDimensions(0);
- param.setInitializer(null);
- param.setType(importRewrite.addImport(paramType, ast));
- param.setName(ast.newSimpleName(paramName));
- return param;
- }
-
- private void setSuperType(TypeDeclaration declaration) throws JavaScriptModelException {
- ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
- ITypeBinding binding= classInstanceCreation.resolveTypeBinding();
- if (binding == null)
- return;
- Type newType= (Type) ASTNode.copySubtree(fAnonymousInnerClassNode.getAST(), classInstanceCreation.getType());
- if (binding.getSuperclass().getQualifiedName().equals("java.lang.Object")) { //$NON-NLS-1$
- return;
- } else {
- declaration.setSuperclassType(newType);
- }
- }
-
- private ITypeBinding getSuperTypeBinding() {
- ITypeBinding types= fAnonymousInnerClassNode.resolveBinding();
- return types.getSuperclass();
- }
-
- private int createModifiersForNestedClass() {
- int flags= fVisibility;
- if (fDeclareFinal)
- flags|= Modifier.FINAL;
- if (mustInnerClassBeStatic() || fDeclareStatic)
- flags|= Modifier.STATIC;
- return flags;
- }
-
- public boolean mustInnerClassBeStatic() {
- ITypeBinding typeBinding = ((AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class)).resolveBinding();
- ASTNode current = fAnonymousInnerClassNode.getParent();
- boolean ans = false;
- while(current != null) {
- switch(current.getNodeType()) {
- case ASTNode.ANONYMOUS_CLASS_DECLARATION:
- {
- AnonymousClassDeclaration enclosingAnonymousClassDeclaration= (AnonymousClassDeclaration)current;
- ITypeBinding binding= enclosingAnonymousClassDeclaration.resolveBinding();
- if (binding != null && Bindings.isSuperType(typeBinding, binding.getSuperclass())) {
- return false;
- }
- break;
- }
- case ASTNode.FIELD_DECLARATION:
- {
- FieldDeclaration enclosingFieldDeclaration= (FieldDeclaration)current;
- if (Modifier.isStatic(enclosingFieldDeclaration.getModifiers())) {
- ans = true;
- }
- break;
- }
- case ASTNode.FUNCTION_DECLARATION:
- {
- FunctionDeclaration enclosingMethodDeclaration = (FunctionDeclaration)current;
- if (Modifier.isStatic(enclosingMethodDeclaration.getModifiers())) {
- ans = true;
- }
- break;
- }
- case ASTNode.TYPE_DECLARATION:
- {
- return ans;
- }
- }
- current = current.getParent();
- }
- return ans;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- fSelfInitializing= true;
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.CONVERT_ANONYMOUS);
- else {
- fCu= (IJavaScriptUnit) element;
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fClassName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= flag;
- }
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String declareStatic= extended.getAttribute(ATTRIBUTE_STATIC);
- if (declareStatic != null) {
- fDeclareStatic= Boolean.valueOf(declareStatic).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_STATIC));
- final String declareFinal= extended.getAttribute(ATTRIBUTE_FINAL);
- if (declareFinal != null) {
- fDeclareFinal= Boolean.valueOf(declareStatic).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FINAL));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExceptionAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExceptionAnalyzer.java
deleted file mode 100644
index edcb19bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExceptionAnalyzer.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.AbstractExceptionAnalyzer;
-
-/* package */ class ExceptionAnalyzer extends AbstractExceptionAnalyzer {
-
- public static ITypeBinding[] perform(ASTNode[] statements) {
- ExceptionAnalyzer analyzer= new ExceptionAnalyzer();
- for (int i= 0; i < statements.length; i++) {
- statements[i].accept(analyzer);
- }
- List exceptions= analyzer.getCurrentExceptions();
- return (ITypeBinding[]) exceptions.toArray(new ITypeBinding[exceptions.size()]);
- }
-
- public boolean visit(ThrowStatement node) {
- ITypeBinding exception= node.getExpression().resolveTypeBinding();
- if (exception == null) // Safety net for null bindings when compiling fails.
- return true;
-
- addException(exception);
- return true;
- }
-
- public boolean visit(FunctionInvocation node) {
- SimpleName name = node.getName();
- if (name!=null)
- return handleExceptions((IFunctionBinding)name.resolveBinding());
- else
- return true;
- }
-
- public boolean visit(SuperMethodInvocation node) {
- return handleExceptions((IFunctionBinding)node.getName().resolveBinding());
- }
-
- public boolean visit(ClassInstanceCreation node) {
- return handleExceptions(node.resolveConstructorBinding());
- }
-
- private boolean handleExceptions(IFunctionBinding binding) {
- if (binding == null)
- return true;
- addExceptions(null);
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
deleted file mode 100644
index 74f60076..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
+++ /dev/null
@@ -1,831 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IExpressionFragment;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RefactoringDescriptorChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ModifierCorrectionSubProcessor;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ExtractConstantRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
- private static final String ATTRIBUTE_QUALIFY= "qualify"; //$NON-NLS-1$
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
-
- private static final String MODIFIER= "static final"; //$NON-NLS-1$
-
- private static final String KEY_NAME= "name"; //$NON-NLS-1$
- private static final String KEY_TYPE= "type"; //$NON-NLS-1$
-
- private CompilationUnitRewrite fCuRewrite;
- private int fSelectionStart;
- private int fSelectionLength;
- private IJavaScriptUnit fCu;
-
- private IExpressionFragment fSelectedExpression;
- private Type fConstantTypeCache;
- private boolean fReplaceAllOccurrences= true; //default value
- private boolean fQualifyReferencesWithDeclaringClassName= false; //default value
-
- private String fVisibility= JdtFlags.VISIBILITY_STRING_PRIVATE; //default value
- private boolean fTargetIsInterface= false;
- private String fConstantName;
- private String[] fExcludedVariableNames;
-
- private boolean fSelectionAllStaticFinal;
- private boolean fAllStaticFinalCheckPerformed= false;
-
- private List fBodyDeclarations;
-
- //Constant Declaration Location
- private BodyDeclaration fToInsertAfter;
- private boolean fInsertFirst;
-
- private CompilationUnitChange fChange;
- private String[] fGuessedConstNames;
-
- private LinkedProposalModel fLinkedProposalModel;
-
- /**
- * Creates a new extract constant refactoring
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public ExtractConstantRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= unit;
- fCuRewrite= null;
- fLinkedProposalModel= null;
- fConstantName= ""; //$NON-NLS-1$
- }
-
- public ExtractConstantRefactoring(JavaScriptUnit astRoot, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- Assert.isTrue(astRoot.getTypeRoot() instanceof IJavaScriptUnit);
-
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= (IJavaScriptUnit) astRoot.getTypeRoot();
- fCuRewrite= new CompilationUnitRewrite(fCu, astRoot);
- fLinkedProposalModel= null;
- fConstantName= ""; //$NON-NLS-1$
- }
-
- public void setLinkedProposalModel(LinkedProposalModel linkedProposalModel) {
- fLinkedProposalModel= linkedProposalModel;
- }
-
- public String getName() {
- return RefactoringCoreMessages.ExtractConstantRefactoring_name;
- }
-
- public boolean replaceAllOccurrences() {
- return fReplaceAllOccurrences;
- }
-
- public void setReplaceAllOccurrences(boolean replaceAllOccurrences) {
- fReplaceAllOccurrences= replaceAllOccurrences;
- }
-
- public void setVisibility(String am) {
- Assert.isTrue(
- am == JdtFlags.VISIBILITY_STRING_PRIVATE || am == JdtFlags.VISIBILITY_STRING_PROTECTED || am == JdtFlags.VISIBILITY_STRING_PACKAGE || am == JdtFlags.VISIBILITY_STRING_PUBLIC
- );
- fVisibility= am;
- }
-
- public String getVisibility() {
- return fVisibility;
- }
-
- public boolean getTargetIsInterface() {
- return fTargetIsInterface;
- }
-
- public boolean qualifyReferencesWithDeclaringClassName() {
- return fQualifyReferencesWithDeclaringClassName;
- }
-
- public void setQualifyReferencesWithDeclaringClassName(boolean qualify) {
- fQualifyReferencesWithDeclaringClassName= qualify;
- }
-
- public String guessConstantName() throws JavaScriptModelException {
- String[] proposals= guessConstantNames();
- if (proposals.length > 0)
- return proposals[0];
- else
- return fConstantName;
- }
-
- /**
- * @return proposed variable names (may be empty, but not null).
- * The first proposal should be used as "best guess" (if it exists).
- */
- public String[] guessConstantNames() {
- if (fGuessedConstNames == null) {
- try {
- Expression expression= getSelectedExpression().getAssociatedExpression();
- if (expression != null) {
- ITypeBinding binding= expression.resolveTypeBinding();
- fGuessedConstNames= StubUtility.getVariableNameSuggestions(StubUtility.CONSTANT_FIELD, fCu.getJavaScriptProject(), binding, expression, Arrays.asList(getExcludedVariableNames()));
- }
- } catch (JavaScriptModelException e) {
- }
- if (fGuessedConstNames == null)
- fGuessedConstNames= new String[0];
- }
- return fGuessedConstNames;
- }
-
-
- private String[] getExcludedVariableNames() {
- if (fExcludedVariableNames == null) {
- try {
- IExpressionFragment expr= getSelectedExpression();
- Collection takenNames= new ScopeAnalyzer(fCuRewrite.getRoot()).getUsedVariableNames(expr.getStartPosition(), expr.getLength());
- fExcludedVariableNames= (String[]) takenNames.toArray(new String[takenNames.size()]);
- } catch (JavaScriptModelException e) {
- fExcludedVariableNames= new String[0];
- }
- }
- return fExcludedVariableNames;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 7); //$NON-NLS-1$
-
- RefactoringStatus result= Checks.validateEdit(fCu, getValidationContext());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- if (fCuRewrite == null) {
- JavaScriptUnit cuNode= RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
- fCuRewrite= new CompilationUnitRewrite(fCu, cuNode);
- } else {
- pm.worked(3);
- }
- result.merge(checkSelection(new SubProgressMonitor(pm, 3)));
-
- if (result.hasFatalError())
- return result;
-
- if (isLiteralNodeSelected())
- fReplaceAllOccurrences= false;
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- public boolean selectionAllStaticFinal() {
- Assert.isTrue(fAllStaticFinalCheckPerformed);
- return fSelectionAllStaticFinal;
- }
-
- private void checkAllStaticFinal() throws JavaScriptModelException {
- fSelectionAllStaticFinal= ConstantChecks.isStaticFinalConstant(getSelectedExpression());
- fAllStaticFinalCheckPerformed= true;
- }
-
- private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaScriptModelException {
- try {
- pm.beginTask("", 2); //$NON-NLS-1$
-
- IExpressionFragment selectedExpression= getSelectedExpression();
-
- if (selectedExpression == null) {
- String message= RefactoringCoreMessages.ExtractConstantRefactoring_select_expression;
- return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, fCuRewrite.getRoot(), message);
- }
- pm.worked(1);
-
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkExpression());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- private RefactoringStatus checkExpressionBinding() throws JavaScriptModelException {
- return checkExpressionFragmentIsRValue();
- }
-
- private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaScriptModelException {
- /* Moved this functionality to Checks, to allow sharing with
- ExtractTempRefactoring, others */
- switch(Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
- case Checks.NOT_RVALUE_MISC:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractConstantRefactoring_select_expression, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
- case Checks.NOT_RVALUE_VOID:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractConstantRefactoring_no_void, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
- case Checks.IS_RVALUE:
- return new RefactoringStatus();
- default:
- Assert.isTrue(false); return null;
- }
- }
-
- // !!! -- same as in ExtractTempRefactoring
- private boolean isLiteralNodeSelected() throws JavaScriptModelException {
- IExpressionFragment fragment= getSelectedExpression();
- if (fragment == null)
- return false;
- Expression expression= fragment.getAssociatedExpression();
- if (expression == null)
- return false;
- switch (expression.getNodeType()) {
- case ASTNode.BOOLEAN_LITERAL :
- case ASTNode.CHARACTER_LITERAL :
- case ASTNode.NULL_LITERAL :
- case ASTNode.NUMBER_LITERAL :
- case ASTNode.UNDEFINED_LITERAL :
- case ASTNode.REGULAR_EXPRESSION_LITERAL :
- return true;
-
- default :
- return false;
- }
- }
-
- private RefactoringStatus checkExpression() throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkExpressionBinding());
- if(result.hasFatalError())
- return result;
- checkAllStaticFinal();
-
- IExpressionFragment selectedExpression= getSelectedExpression();
- Expression associatedExpression= selectedExpression.getAssociatedExpression();
- if (associatedExpression instanceof NullLiteral)
- result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
- else if (!ConstantChecks.isLoadTimeConstant(selectedExpression))
- result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
- else if (associatedExpression instanceof SimpleName) {
- if (associatedExpression.getParent() instanceof QualifiedName && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
- || associatedExpression.getParent() instanceof FieldAccess && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
- }
-
- return result;
- }
-
- public void setConstantName(String newName) {
- Assert.isNotNull(newName);
- fConstantName= newName;
- }
-
- public String getConstantName() {
- return fConstantName;
- }
-
- /**
- * This method performs checks on the constant name which are
- * quick enough to be performed every time the ui input component
- * contents are changed.
- *
- * @return return the resulting status
- * @throws JavaScriptModelException thrown when the operation could not be executed
- */
- public RefactoringStatus checkConstantNameOnChange() throws JavaScriptModelException {
- if (Arrays.asList(getExcludedVariableNames()).contains(fConstantName))
- return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_another_variable, getConstantName()));
- return Checks.checkConstantName(getConstantName());
- }
-
- // !! similar to ExtractTempRefactoring equivalent
- public String getConstantSignaturePreview() throws JavaScriptModelException {
- String space= " "; //$NON-NLS-1$
- return getVisibility() + space + MODIFIER + space + getConstantTypeName() + space + fConstantName;
- }
-
- public CompilationUnitChange createTextChange(IProgressMonitor pm) throws CoreException {
- createConstantDeclaration();
- replaceExpressionsWithConstant();
- return fCuRewrite.createChange(RefactoringCoreMessages.ExtractConstantRefactoring_change_name, true, pm);
- }
-
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ExtractConstantRefactoring_checking_preconditions, 4);
-
- /* Note: some checks are performed on change of input widget
- * values. (e.g. see ExtractConstantRefactoring.checkConstantNameOnChange())
- */
-
- //TODO: possibly add more checking for name conflicts that might
- // lead to a change in behaviour
-
- try {
- RefactoringStatus result= new RefactoringStatus();
- fChange= createTextChange(new SubProgressMonitor(pm, 2));
-
- String newCuSource= fChange.getPreviewContent(new NullProgressMonitor());
- JavaScriptUnit newCUNode= new RefactoringASTParser(AST.JLS3).parse(newCuSource, fCu, true, true, null);
-
- IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
- for (int i= 0; i < newProblems.length; i++) {
- IProblem problem= newProblems[i];
- if (problem.isError())
- result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, new SourceRange(problem))));
- }
-
- fConstantTypeCache= null;
- fCuRewrite.clearASTAndImportRewrites();
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- private void createConstantDeclaration() throws CoreException {
- Type type= getConstantType();
-
- IExpressionFragment fragment= getSelectedExpression();
- String initializerSource= fCu.getBuffer().getText(fragment.getStartPosition(), fragment.getLength());
-
- AST ast= fCuRewrite.getAST();
- VariableDeclarationFragment variableDeclarationFragment= ast.newVariableDeclarationFragment();
- variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
- variableDeclarationFragment.setInitializer((Expression) fCuRewrite.getASTRewrite().createStringPlaceholder(initializerSource, ASTNode.SIMPLE_NAME));
-
- FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(variableDeclarationFragment);
- fieldDeclaration.setType(type);
- Modifier.ModifierKeyword accessModifier= Modifier.ModifierKeyword.toKeyword(fVisibility);
- if (accessModifier != null)
- fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
- fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
- fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
-
- boolean createComments= JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaScriptProject()).createComments;
- if (createComments) {
- String comment= CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
- if (comment != null && comment.length() > 0) {
- JSdoc doc= (JSdoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JSDOC);
- fieldDeclaration.setJavadoc(doc);
- }
- }
-
- AbstractTypeDeclaration parent= getContainingTypeDeclarationNode();
- ListRewrite listRewrite= fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
- TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
- if (insertFirst()) {
- listRewrite.insertFirst(fieldDeclaration, msg);
- } else {
- listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
- }
-
- if (fLinkedProposalModel != null) {
- ASTRewrite rewrite= fCuRewrite.getASTRewrite();
- LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
- nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true);
-
- String[] nameSuggestions= guessConstantNames();
- if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
- nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1);
- }
- for (int i= 0; i < nameSuggestions.length; i++) {
- nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
- }
-
- LinkedProposalPositionGroup typeGroup= fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
- typeGroup.addPosition(rewrite.track(type), true);
-
- ITypeBinding typeBinding= fragment.getAssociatedExpression().resolveTypeBinding();
- if (typeBinding != null) {
- ITypeBinding[] relaxingTypes= ASTResolving.getNarrowingTypes(ast, typeBinding);
- for (int i= 0; i < relaxingTypes.length; i++) {
- typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
- }
- }
- ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), false);
- }
- }
-
- private Type getConstantType() throws JavaScriptModelException {
- if (fConstantTypeCache == null) {
- IExpressionFragment fragment= getSelectedExpression();
- ITypeBinding typeBinding= fragment.getAssociatedExpression().resolveTypeBinding();
- AST ast= fCuRewrite.getAST();
- typeBinding= Bindings.normalizeForDeclarationUse(typeBinding, ast);
- fConstantTypeCache= fCuRewrite.getImportRewrite().addImport(typeBinding, ast);
- }
- return fConstantTypeCache;
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- if (JdtFlags.getVisibilityCode(fVisibility) != Modifier.PRIVATE)
- flags|= RefactoringDescriptor.STRUCTURAL_CHANGE;
- String pattern= ""; //$NON-NLS-1$
- try {
- pattern= BindingLabelProvider.getBindingLabel(getContainingTypeBinding(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED) + "."; //$NON-NLS-1$
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String expression= ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
- final String description= Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description_short, fConstantName);
- final String header= Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description, new String[] { pattern + fConstantName, expression});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_constant_name_pattern, fConstantName));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_constant_expression_pattern, expression));
- String visibility= fVisibility;
- if ("".equals(visibility)) //$NON-NLS-1$
- visibility= RefactoringCoreMessages.ExtractConstantRefactoring_default_visibility;
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_visibility_pattern, visibility));
- if (fReplaceAllOccurrences)
- comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_replace_occurrences);
- if (fQualifyReferencesWithDeclaringClassName)
- comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_qualify_references);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.EXTRACT_CONSTANT, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fConstantName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
- arguments.put(ATTRIBUTE_QUALIFY, Boolean.valueOf(fQualifyReferencesWithDeclaringClassName).toString());
- arguments.put(ATTRIBUTE_VISIBILITY, new Integer(JdtFlags.getVisibilityCode(fVisibility)).toString());
- return new RefactoringDescriptorChange(descriptor, RefactoringCoreMessages.ExtractConstantRefactoring_name, new Change[] { fChange});
- }
-
- private void replaceExpressionsWithConstant() throws JavaScriptModelException {
- ASTRewrite astRewrite= fCuRewrite.getASTRewrite();
- AST ast= astRewrite.getAST();
-
- IASTFragment[] fragmentsToReplace= getFragmentsToReplace();
- for (int i= 0; i < fragmentsToReplace.length; i++) {
- IASTFragment fragment= fragmentsToReplace[i];
-
- SimpleName ref= ast.newSimpleName(fConstantName);
- Name replacement= ref;
- if (qualifyReferencesWithDeclaringClassName()) {
- replacement= ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref);
- }
- TextEditGroup description= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_replace);
-
- fragment.replace(astRewrite, replacement, description);
- if (fLinkedProposalModel != null)
- fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(astRewrite.track(ref), false);
- }
- }
-
- private void computeConstantDeclarationLocation() throws JavaScriptModelException {
- if (isDeclarationLocationComputed())
- return;
-
- BodyDeclaration lastStaticDependency= null;
- Iterator decls= getBodyDeclarations();
-
- Assert.isTrue(decls.hasNext()); /* Admissible selected expressions must occur
- within a body declaration. Thus, the
- class/interface in which such an expression occurs
- must have at least one body declaration */
-
- while (decls.hasNext()) {
- BodyDeclaration decl= (BodyDeclaration) decls.next();
-
- int modifiers;
- if (decl instanceof FieldDeclaration)
- modifiers= ((FieldDeclaration) decl).getModifiers();
- else if (decl instanceof Initializer)
- modifiers= ((Initializer) decl).getModifiers();
- else {
- continue; /* this declaration is not a field declaration
- or initializer, so the placement of the constant
- declaration relative to it does not matter */
- }
-
- if (Modifier.isStatic(modifiers) && depends(getSelectedExpression(), decl))
- lastStaticDependency= decl;
- }
-
- if(lastStaticDependency == null)
- fInsertFirst= true;
- else
- fToInsertAfter= lastStaticDependency;
- }
-
- /* bd is a static field declaration or static initializer */
- private static boolean depends(IExpressionFragment selected, BodyDeclaration bd) {
- /* We currently consider selected to depend on bd only if db includes a declaration
- * of a static field on which selected depends.
- *
- * A more accurate strategy might be to also check if bd contains (or is) a
- * static initializer containing code which changes the value of a static field on
- * which selected depends. However, if a static is written to multiple times within
- * during class initialization, it is difficult to predict which value should be used.
- * This would depend on which value is used by expressions instances for which the new
- * constant will be substituted, and there may be many of these; in each, the
- * static field in question may have taken on a different value (if some of these uses
- * occur within static initializers).
- */
-
- if(bd instanceof FieldDeclaration) {
- FieldDeclaration fieldDecl = (FieldDeclaration) bd;
- for(Iterator fragments = fieldDecl.fragments().iterator(); fragments.hasNext();) {
- VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.next();
- SimpleName staticFieldName = fragment.getName();
- if(selected.getSubFragmentsMatching(ASTFragmentFactory.createFragmentForFullSubtree(staticFieldName)).length != 0)
- return true;
- }
- }
- return false;
- }
-
- private boolean isDeclarationLocationComputed() {
- return fInsertFirst == true || fToInsertAfter != null;
- }
-
- private boolean insertFirst() throws JavaScriptModelException {
- if(!isDeclarationLocationComputed())
- computeConstantDeclarationLocation();
- return fInsertFirst;
- }
-
- private BodyDeclaration getNodeToInsertConstantDeclarationAfter() throws JavaScriptModelException {
- if(!isDeclarationLocationComputed())
- computeConstantDeclarationLocation();
- return fToInsertAfter;
- }
-
- private Iterator getBodyDeclarations() throws JavaScriptModelException {
- if(fBodyDeclarations == null)
- fBodyDeclarations= getContainingTypeDeclarationNode().bodyDeclarations();
- return fBodyDeclarations.iterator();
- }
-
- private String getConstantTypeName() throws JavaScriptModelException {
- return ASTNodes.asString(getConstantType());
- }
-
- private static boolean isStaticFieldOrStaticInitializer(BodyDeclaration node) {
- if(node instanceof FunctionDeclaration || node instanceof AbstractTypeDeclaration)
- return false;
-
- int modifiers;
- if(node instanceof FieldDeclaration) {
- modifiers = ((FieldDeclaration) node).getModifiers();
- } else if(node instanceof Initializer) {
- modifiers = ((Initializer) node).getModifiers();
- } else {
- Assert.isTrue(false);
- return false;
- }
-
- if(!Modifier.isStatic(modifiers))
- return false;
-
- return true;
- }
-
- /*
- * Elements returned by next() are BodyDeclaration
- * instances.
- */
- private Iterator getReplacementScope() throws JavaScriptModelException {
- boolean declPredecessorReached= false;
-
- Collection scope= new ArrayList();
- for(Iterator bodyDeclarations = getBodyDeclarations(); bodyDeclarations.hasNext();) {
- BodyDeclaration bodyDeclaration= (BodyDeclaration) bodyDeclarations.next();
-
- if(bodyDeclaration == getNodeToInsertConstantDeclarationAfter())
- declPredecessorReached= true;
-
- if(insertFirst() || declPredecessorReached || !isStaticFieldOrStaticInitializer(bodyDeclaration))
- scope.add(bodyDeclaration);
- }
- return scope.iterator();
- }
-
- private IASTFragment[] getFragmentsToReplace() throws JavaScriptModelException {
- List toReplace = new ArrayList();
- if (fReplaceAllOccurrences) {
- Iterator replacementScope = getReplacementScope();
- while(replacementScope.hasNext()) {
- BodyDeclaration bodyDecl = (BodyDeclaration) replacementScope.next();
- IASTFragment[] allMatches= ASTFragmentFactory.createFragmentForFullSubtree(bodyDecl).getSubFragmentsMatching(getSelectedExpression());
- IASTFragment[] replaceableMatches = retainOnlyReplacableMatches(allMatches);
- for(int i = 0; i < replaceableMatches.length; i++)
- toReplace.add(replaceableMatches[i]);
- }
- } else if (canReplace(getSelectedExpression()))
- toReplace.add(getSelectedExpression());
- return (IASTFragment[]) toReplace.toArray(new IASTFragment[toReplace.size()]);
- }
-
- // !! - like one in ExtractTempRefactoring
- private static IASTFragment[] retainOnlyReplacableMatches(IASTFragment[] allMatches) {
- List result= new ArrayList(allMatches.length);
- for (int i= 0; i < allMatches.length; i++) {
- if (canReplace(allMatches[i]))
- result.add(allMatches[i]);
- }
- return (IASTFragment[]) result.toArray(new IASTFragment[result.size()]);
- }
-
- // !! - like one in ExtractTempRefactoring
- private static boolean canReplace(IASTFragment fragment) {
- ASTNode node= fragment.getAssociatedNode();
- ASTNode parent= node.getParent();
- if (parent instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent;
- if (node.equals(vdf.getName()))
- return false;
- }
- if (parent instanceof ExpressionStatement)
- return false;
- if (parent instanceof SwitchCase)
- return false;
- return true;
- }
-
- private IExpressionFragment getSelectedExpression() throws JavaScriptModelException {
- if(fSelectedExpression != null)
- return fSelectedExpression;
-
- IASTFragment selectedFragment= ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCuRewrite.getRoot(), fCu);
-
- if (selectedFragment instanceof IExpressionFragment
- && ! Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
- fSelectedExpression= (IExpressionFragment) selectedFragment;
- }
-
- return fSelectedExpression;
- }
-
- private AbstractTypeDeclaration getContainingTypeDeclarationNode() throws JavaScriptModelException {
- AbstractTypeDeclaration result= (AbstractTypeDeclaration) ASTNodes.getParent(getSelectedExpression().getAssociatedNode(), AbstractTypeDeclaration.class);
- Assert.isNotNull(result);
- return result;
- }
-
- private ITypeBinding getContainingTypeBinding() throws JavaScriptModelException {
- ITypeBinding result= getContainingTypeDeclarationNode().resolveBinding();
- Assert.isNotNull(result);
- return result;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.EXTRACT_CONSTANT);
- else
- fCu= (IJavaScriptUnit) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= JdtFlags.getVisibilityString(flag);
- }
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fConstantName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplaceAllOccurrences= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- final String declareFinal= extended.getAttribute(ATTRIBUTE_QUALIFY);
- if (declareFinal != null) {
- fQualifyReferencesWithDeclaringClassName= Boolean.valueOf(declareFinal).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_QUALIFY));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
deleted file mode 100644
index 1cb4b897..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
+++ /dev/null
@@ -1,719 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.Message;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LocalVariableIndex;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InputFlowAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.CodeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/* package */ class ExtractMethodAnalyzer extends CodeAnalyzer {
-
- public static final int ERROR= -2;
- public static final int UNDEFINED= -1;
- public static final int NO= 0;
- public static final int EXPRESSION= 1;
- public static final int ACCESS_TO_LOCAL= 2;
- public static final int RETURN_STATEMENT_VOID= 3;
- public static final int RETURN_STATEMENT_VALUE= 4;
- public static final int MULTIPLE= 5;
-
- /** This is either a method declaration or an initializer */
- private BodyDeclaration fEnclosingBodyDeclaration;
- private IFunctionBinding fEnclosingMethodBinding;
- private int fMaxVariableId;
-
- private int fReturnKind;
- private Type fReturnType;
-
- private FlowInfo fInputFlowInfo;
- private FlowContext fInputFlowContext;
-
- private IVariableBinding[] fArguments;
- private IVariableBinding[] fMethodLocals;
- private ITypeBinding[] fTypeVariables;
-
- private IVariableBinding fReturnValue;
- private IVariableBinding[] fCallerLocals;
- private IVariableBinding fReturnLocal;
-
- private ITypeBinding[] fAllExceptions;
- private ITypeBinding fExpressionBinding;
-
- private boolean fForceStatic;
- private boolean fIsLastStatementSelected;
-
- public ExtractMethodAnalyzer(IJavaScriptUnit unit, Selection selection) throws JavaScriptModelException {
- super(unit, selection, false);
- }
-
- public BodyDeclaration getEnclosingBodyDeclaration() {
- return fEnclosingBodyDeclaration;
- }
-
- public int getReturnKind() {
- return fReturnKind;
- }
-
- public boolean extractsExpression() {
- return fReturnKind == EXPRESSION;
- }
-
- public Type getReturnType() {
- return fReturnType;
- }
-
- public boolean generateImport() {
- switch (fReturnKind) {
- case EXPRESSION:
- return true;
- default:
- return false;
- }
- }
-
- public IVariableBinding[] getArguments() {
- return fArguments;
- }
-
- public IVariableBinding[] getMethodLocals() {
- return fMethodLocals;
- }
-
- public IVariableBinding getReturnValue() {
- return fReturnValue;
- }
-
- public IVariableBinding[] getCallerLocals() {
- return fCallerLocals;
- }
-
- public IVariableBinding getReturnLocal() {
- return fReturnLocal;
- }
-
- public ITypeBinding getExpressionBinding() {
- return fExpressionBinding;
- }
-
- public boolean getForceStatic() {
- return fForceStatic;
- }
-
- public ITypeBinding[] getTypeVariables() {
- return fTypeVariables;
- }
-
- //---- Activation checking ---------------------------------------------------------------------------
-
- public RefactoringStatus checkInitialConditions(ImportRewrite rewriter) {
- RefactoringStatus result= getStatus();
- checkExpression(result);
- if (result.hasFatalError())
- return result;
-
- fReturnKind= UNDEFINED;
- fMaxVariableId= LocalVariableIndex.perform(fEnclosingBodyDeclaration);
- if (analyzeSelection(result).hasFatalError())
- return result;
-
- int returns= fReturnKind == NO ? 0 : 1;
- if (fReturnValue != null) {
- fReturnKind= ACCESS_TO_LOCAL;
- returns++;
- }
- if (isExpressionSelected()) {
- fReturnKind= EXPRESSION;
- returns++;
- }
-
- if (returns > 1) {
- result.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_ambiguous_return_value, JavaStatusContext.create(fCUnit, getSelection()));
- fReturnKind= MULTIPLE;
- return result;
- }
- initReturnType(rewriter);
- return result;
- }
-
- private void checkExpression(RefactoringStatus status) {
- ASTNode[] nodes= getSelectedNodes();
- if (nodes != null && nodes.length == 1) {
- ASTNode node= nodes[0];
- if (node instanceof Type) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node));
- } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node));
- }
- }
- }
-
- private void initReturnType(ImportRewrite rewriter) {
- AST ast= fEnclosingBodyDeclaration.getAST();
- fReturnType= null;
- switch (fReturnKind) {
- case ACCESS_TO_LOCAL:
- VariableDeclaration declaration= ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
- fReturnType= ASTNodeFactory.newType(ast, declaration);
- break;
- case EXPRESSION:
- Expression expression= (Expression)getFirstSelectedNode();
- if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
- fExpressionBinding= ((ClassInstanceCreation)expression).getType().resolveBinding();
- } else {
- fExpressionBinding= expression.resolveTypeBinding();
- }
- if (fExpressionBinding != null) {
- if (fExpressionBinding.isNullType()) {
- getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
- } else {
- ITypeBinding normalizedBinding= Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
- if (normalizedBinding != null) {
- fReturnType= rewriter.addImport(normalizedBinding, ast);
- }
- }
- } else {
- fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
- getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
- }
- break;
- case RETURN_STATEMENT_VALUE:
- if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.FUNCTION_DECLARATION)
- fReturnType= ((FunctionDeclaration)fEnclosingBodyDeclaration).getReturnType2();
- break;
- default:
- fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
- }
- if (fReturnType == null)
- fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
- }
-
- // !!! -- +/- same as in ExtractTempRefactoring
- public boolean isLiteralNodeSelected() {
- ASTNode[] nodes= getSelectedNodes();
- if (nodes.length != 1)
- return false;
- ASTNode node= nodes[0];
- switch (node.getNodeType()) {
- case ASTNode.BOOLEAN_LITERAL :
- case ASTNode.CHARACTER_LITERAL :
- case ASTNode.NULL_LITERAL :
- case ASTNode.NUMBER_LITERAL :
- case ASTNode.UNDEFINED_LITERAL :
- case ASTNode.REGULAR_EXPRESSION_LITERAL :
- return true;
-
- default :
- return false;
- }
- }
-
- //---- Input checking -----------------------------------------------------------------------------------
-
- public void checkInput(RefactoringStatus status, String methodName, AST ast) {
- ITypeBinding[] arguments= getArgumentTypes();
- ITypeBinding type= ASTNodes.getEnclosingType(fEnclosingBodyDeclaration);
- status.merge(Checks.checkMethodInType(type, methodName, arguments));
- status.merge(Checks.checkMethodInHierarchy(type.getSuperclass(), methodName, null, arguments));
- }
-
- private ITypeBinding[] getArgumentTypes() {
- ITypeBinding[] result= new ITypeBinding[fArguments.length];
- for (int i= 0; i < fArguments.length; i++) {
- result[i]= fArguments[i].getType();
- }
- return result;
- }
-
- private RefactoringStatus analyzeSelection(RefactoringStatus status) {
- fInputFlowContext= new FlowContext(0, fMaxVariableId + 1);
- fInputFlowContext.setConsiderAccessMode(true);
- fInputFlowContext.setComputeMode(FlowContext.ARGUMENTS);
-
- InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(fInputFlowContext);
- fInputFlowInfo= flowAnalyzer.perform(getSelectedNodes());
-
- if (fInputFlowInfo.branches()) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch, JavaStatusContext.create(fCUnit, getSelection()));
- fReturnKind= ERROR;
- return status;
- }
- if (fInputFlowInfo.isValueReturn()) {
- fReturnKind= RETURN_STATEMENT_VALUE;
- } else if (fInputFlowInfo.isVoidReturn() || (fInputFlowInfo.isPartialReturn() && isVoidMethod() && isLastStatementSelected())) {
- fReturnKind= RETURN_STATEMENT_VOID;
- } else if (fInputFlowInfo.isNoReturn() || fInputFlowInfo.isThrow() || fInputFlowInfo.isUndefined()) {
- fReturnKind= NO;
- }
-
- if (fReturnKind == UNDEFINED) {
- status.addError(RefactoringCoreMessages.FlowAnalyzer_execution_flow, JavaStatusContext.create(fCUnit, getSelection()));
- fReturnKind= NO;
- }
- computeInput();
- computeExceptions();
- computeOutput(status);
- if (status.hasFatalError())
- return status;
-
- adjustArgumentsAndMethodLocals();
- compressArrays();
- return status;
- }
-
- private boolean isVoidMethod() {
- // if we have an initializer
- if (fEnclosingMethodBinding == null)
- return true;
- ITypeBinding binding= fEnclosingMethodBinding.getReturnType();
- if (fEnclosingBodyDeclaration.getAST().resolveWellKnownType("void").equals(binding)) //$NON-NLS-1$
- return true;
- return false;
- }
-
- public boolean isLastStatementSelected() {
- return fIsLastStatementSelected;
- }
-
- private void computeLastStatementSelected() {
- ASTNode[] nodes= getSelectedNodes();
- if (nodes.length == 0) {
- fIsLastStatementSelected= false;
- } else {
- Block body= null;
- if (fEnclosingBodyDeclaration instanceof FunctionDeclaration) {
- body= ((FunctionDeclaration) fEnclosingBodyDeclaration).getBody();
- } else if (fEnclosingBodyDeclaration instanceof Initializer) {
- body= ((Initializer) fEnclosingBodyDeclaration).getBody();
- }
- if (body != null) {
- List statements= body.statements();
- fIsLastStatementSelected= nodes[nodes.length - 1] == statements.get(statements.size() - 1);
- }
- }
- }
-
- private void computeInput() {
- int argumentMode= FlowInfo.READ | FlowInfo.READ_POTENTIAL | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN;
- fArguments= removeSelectedDeclarations(fInputFlowInfo.get(fInputFlowContext, argumentMode));
- fMethodLocals= removeSelectedDeclarations(fInputFlowInfo.get(fInputFlowContext, FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL));
- fTypeVariables= computeTypeVariables(fInputFlowInfo.getTypeVariables());
- }
-
- private IVariableBinding[] removeSelectedDeclarations(IVariableBinding[] bindings) {
- List result= new ArrayList(bindings.length);
- Selection selection= getSelection();
- for (int i= 0; i < bindings.length; i++) {
- ASTNode decl= ((JavaScriptUnit)fEnclosingBodyDeclaration.getRoot()).findDeclaringNode(bindings[i]);
- if (!selection.covers(decl))
- result.add(bindings[i]);
- }
- return (IVariableBinding[])result.toArray(new IVariableBinding[result.size()]);
- }
-
- private ITypeBinding[] computeTypeVariables(ITypeBinding[] bindings) {
- Selection selection= getSelection();
- Set result= new HashSet();
- // first remove all type variables that come from outside of the method
- // or are covered by the selection
- JavaScriptUnit compilationUnit= (JavaScriptUnit)fEnclosingBodyDeclaration.getRoot();
- for (int i= 0; i < bindings.length; i++) {
- ASTNode decl= compilationUnit.findDeclaringNode(bindings[i]);
- if (decl == null || (!selection.covers(decl) && decl.getParent() instanceof FunctionDeclaration))
- result.add(bindings[i]);
- }
- // all all type variables which are needed since a local variable uses it
-// for (int i= 0; i < fArguments.length; i++) {
-// IVariableBinding arg= fArguments[i];
-// }
- return (ITypeBinding[])result.toArray(new ITypeBinding[result.size()]);
- }
-
- private void computeOutput(RefactoringStatus status) {
- // First find all writes inside the selection.
- FlowContext flowContext= new FlowContext(0, fMaxVariableId + 1);
- flowContext.setConsiderAccessMode(true);
- flowContext.setComputeMode(FlowContext.RETURN_VALUES);
- FlowInfo returnInfo= new InOutFlowAnalyzer(flowContext).perform(getSelectedNodes());
- IVariableBinding[] returnValues= returnInfo.get(flowContext, FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN);
-
- // Compute a selection that exactly covers the selected nodes
- IRegion region= getSelectedNodeRange();
- Selection selection= Selection.createFromStartLength(region.getOffset(), region.getLength());
-
- int counter= 0;
- flowContext.setComputeMode(FlowContext.ARGUMENTS);
- FlowInfo argInfo= new InputFlowAnalyzer(flowContext, selection, true).perform(fEnclosingBodyDeclaration);
- IVariableBinding[] reads= argInfo.get(flowContext, FlowInfo.READ | FlowInfo.READ_POTENTIAL | FlowInfo.UNKNOWN);
- outer: for (int i= 0; i < returnValues.length && counter <= 1; i++) {
- IVariableBinding binding= returnValues[i];
- for (int x= 0; x < reads.length; x++) {
- if (reads[x] == binding) {
- counter++;
- fReturnValue= binding;
- continue outer;
- }
- }
- }
- switch (counter) {
- case 0:
- fReturnValue= null;
- break;
- case 1:
- break;
- default:
- fReturnValue= null;
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_assignments_to_local, JavaStatusContext.create(fCUnit, getSelection()));
- return;
- }
- List callerLocals= new ArrayList(5);
- FlowInfo localInfo= new InputFlowAnalyzer(flowContext, selection, false).perform(fEnclosingBodyDeclaration);
- IVariableBinding[] writes= localInfo.get(flowContext, FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN);
- for (int i= 0; i < writes.length; i++) {
- IVariableBinding write= writes[i];
- if (getSelection().covers(ASTNodes.findDeclaration(write, fEnclosingBodyDeclaration)))
- callerLocals.add(write);
- }
- fCallerLocals= (IVariableBinding[])callerLocals.toArray(new IVariableBinding[callerLocals.size()]);
- if (fReturnValue != null && getSelection().covers(ASTNodes.findDeclaration(fReturnValue, fEnclosingBodyDeclaration)))
- fReturnLocal= fReturnValue;
- }
-
- private void adjustArgumentsAndMethodLocals() {
- for (int i= 0; i < fArguments.length; i++) {
- IVariableBinding argument= fArguments[i];
- // Both arguments and locals consider FlowInfo.WRITE_POTENTIAL. But at the end a variable
- // can either be a local of an argument. Fix this based on the compute return type which
- // didn't exist when we computed the locals and arguments (see computeInput())
- if (fInputFlowInfo.hasAccessMode(fInputFlowContext, argument, FlowInfo.WRITE_POTENTIAL)) {
- if (argument != fReturnValue)
- fArguments[i]= null;
- // We didn't remove the argument. So we have to remove the local declaration
- if (fArguments[i] != null) {
- for (int l= 0; l < fMethodLocals.length; l++) {
- if (fMethodLocals[l] == argument)
- fMethodLocals[l]= null;
- }
- }
- }
- }
- }
-
- private void compressArrays() {
- fArguments= compressArray(fArguments);
- fCallerLocals= compressArray(fCallerLocals);
- fMethodLocals= compressArray(fMethodLocals);
- }
-
- private IVariableBinding[] compressArray(IVariableBinding[] array) {
- if (array == null)
- return null;
- int size= 0;
- for (int i= 0; i < array.length; i++) {
- if (array[i] != null)
- size++;
- }
- if (size == array.length)
- return array;
- IVariableBinding[] result= new IVariableBinding[size];
- for (int i= 0, r= 0; i < array.length; i++) {
- if (array[i] != null)
- result[r++]= array[i];
- }
- return result;
- }
-
- //---- Change creation ----------------------------------------------------------------------------------
-
- public void aboutToCreateChange() {
- }
-
- //---- Exceptions -----------------------------------------------------------------------------------------
-
- public ITypeBinding[] getExceptions(boolean includeRuntimeExceptions, AST ast) {
- if (includeRuntimeExceptions)
- return fAllExceptions;
- List result= new ArrayList(fAllExceptions.length);
- for (int i= 0; i < fAllExceptions.length; i++) {
- ITypeBinding exception= fAllExceptions[i];
- if (!includeRuntimeExceptions && Bindings.isRuntimeException(exception))
- continue;
- result.add(exception);
- }
- return (ITypeBinding[]) result.toArray(new ITypeBinding[result.size()]);
- }
-
- private void computeExceptions() {
- fAllExceptions= ExceptionAnalyzer.perform(getSelectedNodes());
- }
-
- //---- Special visitor methods ---------------------------------------------------------------------------
-
- protected void handleNextSelectedNode(ASTNode node) {
- super.handleNextSelectedNode(node);
- checkParent(node);
- }
-
- protected boolean handleSelectionEndsIn(ASTNode node) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_doesNotCover, JavaStatusContext.create(fCUnit, node));
- return super.handleSelectionEndsIn(node);
- }
-
- private void checkParent(ASTNode node) {
- ASTNode firstParent= getFirstSelectedNode().getParent();
- do {
- node= node.getParent();
- if (node == firstParent)
- return;
- } while (node != null);
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_parent_mismatch);
- }
-
- public void endVisit(JavaScriptUnit node) {
- RefactoringStatus status= getStatus();
- superCall: {
- if (status.hasFatalError())
- break superCall;
- if (!hasSelectedNodes()) {
- ASTNode coveringNode= getLastCoveringNode();
- if (coveringNode instanceof Block && coveringNode.getParent() instanceof FunctionDeclaration) {
- FunctionDeclaration methodDecl= (FunctionDeclaration)coveringNode.getParent();
- Message[] messages= ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY);
- if (messages.length > 0) {
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors,
- methodDecl.getName().getIdentifier()), JavaStatusContext.create(fCUnit, methodDecl));
- break superCall;
- }
- }
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_only_method_body);
- break superCall;
- }
- fEnclosingBodyDeclaration= (BodyDeclaration)ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
- if (fEnclosingBodyDeclaration == null ||
- (fEnclosingBodyDeclaration.getNodeType() != ASTNode.FUNCTION_DECLARATION &&
- fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_only_method_body);
- break superCall;
- } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding);
- break superCall;
- } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- fEnclosingMethodBinding= ((FunctionDeclaration)fEnclosingBodyDeclaration).resolveBinding();
- }
- if (!isSingleExpressionOrStatementSet()) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set);
- break superCall;
- }
- if (isExpressionSelected()) {
- ASTNode expression= getFirstSelectedNode();
- if (expression instanceof Name) {
- Name name= (Name)expression;
- if (name.resolveBinding() instanceof ITypeBinding) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference);
- break superCall;
- }
- if (name.resolveBinding() instanceof IFunctionBinding) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference);
- }
- if (name.isSimpleName() && ((SimpleName)name).isDeclaration()) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration);
- break superCall;
- }
- }
- fForceStatic=
- ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null ||
- ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null;
- }
- status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection()));
- computeLastStatementSelected();
- }
- super.endVisit(node);
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- boolean result= super.visit(node);
- if (isFirstSelectedNode(node)) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_anonymous_type, JavaStatusContext.create(fCUnit, node));
- return false;
- }
- return result;
- }
-
- public boolean visit(Assignment node) {
- boolean result= super.visit(node);
- if (getSelection().getVisitSelectionMode(node.getLeftHandSide()) == Selection.SELECTED) {
- invalidSelection(
- RefactoringCoreMessages.ExtractMethodAnalyzer_leftHandSideOfAssignment,
- JavaStatusContext.create(fCUnit, node));
- return false;
- }
- return result;
- }
-
- public boolean visit(DoStatement node) {
- boolean result= super.visit(node);
-
- try {
- int actionStart= getTokenScanner().getTokenEndOffset(ITerminalSymbols.TokenNamedo, node.getStartPosition());
- if (getSelection().getOffset() == actionStart) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_after_do_keyword, JavaStatusContext.create(fCUnit, getSelection()));
- return false;
- }
- } catch (CoreException e) {
- // ignore
- }
-
- return result;
- }
-
- public boolean visit(FunctionDeclaration node) {
- Block body= node.getBody();
- if (body == null)
- return false;
- Selection selection= getSelection();
- int nodeStart= body.getStartPosition();
- int nodeExclusiveEnd= nodeStart + body.getLength();
- // if selection node inside of the method body ignore method
- if (!(nodeStart < selection.getOffset() && selection.getExclusiveEnd() < nodeExclusiveEnd))
- return false;
- return super.visit(node);
- }
-
- public boolean visit(ConstructorInvocation node) {
- return visitConstructorInvocation(node, super.visit(node));
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- return visitConstructorInvocation(node, super.visit(node));
- }
-
- private boolean visitConstructorInvocation(ASTNode node, boolean superResult) {
- if (getSelection().getVisitSelectionMode(node) == Selection.SELECTED) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_super_or_this, JavaStatusContext.create(fCUnit, node));
- return false;
- }
- return superResult;
- }
-
- public void endVisit(ForInStatement node) {
- if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
- if (node.getIterationVariable().equals(getFirstSelectedNode())) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_initializer, JavaStatusContext.create(fCUnit, getSelection()));
-// } else if (node.updaters().contains(getLastSelectedNode())) {
-// invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_updater, JavaStatusContext.create(fCUnit, getSelection()));
- }
- }
- super.endVisit(node);
- }
-
-
- public boolean visit(VariableDeclarationFragment node) {
- boolean result= super.visit(node);
- if (isFirstSelectedNode(node)) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node));
- return false;
- }
- return result;
- }
-
- public void endVisit(ForStatement node) {
- if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
- if (node.initializers().contains(getFirstSelectedNode())) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_initializer, JavaStatusContext.create(fCUnit, getSelection()));
- } else if (node.updaters().contains(getLastSelectedNode())) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_updater, JavaStatusContext.create(fCUnit, getSelection()));
- }
- }
- super.endVisit(node);
- }
-
- public void endVisit(VariableDeclarationExpression node) {
- checkTypeInDeclaration(node.getType());
- super.endVisit(node);
- }
-
- public void endVisit(VariableDeclarationStatement node) {
- checkTypeInDeclaration(node.getType());
- super.endVisit(node);
- }
-
- private boolean isFirstSelectedNode(ASTNode node) {
- return getSelection().getVisitSelectionMode(node) == Selection.SELECTED && getFirstSelectedNode() == node;
- }
-
- private void checkTypeInDeclaration(Type node) {
- if (getSelection().getEndVisitSelectionMode(node) == Selection.SELECTED && getFirstSelectedNode() == node) {
- invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration, JavaStatusContext.create(fCUnit, getSelection()));
- }
- }
-
- private boolean isSingleExpressionOrStatementSet() {
- ASTNode first= getFirstSelectedNode();
- if (first == null)
- return true;
- if (first instanceof Expression && getSelectedNodes().length != 1)
- return false;
- return true;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
deleted file mode 100644
index fe5e40ba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
+++ /dev/null
@@ -1,993 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTFlattener;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.BodyDeclarationRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.StatementRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Extracts a method in a compilation unit based on a text selection range.
- */
-public class ExtractMethodRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DESTINATION= "destination"; //$NON-NLS-1$
- private static final String ATTRIBUTE_COMMENTS= "comments"; //$NON-NLS-1$
- private static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
- private static final String ATTRIBUTE_EXCEPTIONS= "exceptions"; //$NON-NLS-1$
-
- private IJavaScriptUnit fCUnit;
- private JavaScriptUnit fRoot;
- private ImportRewrite fImportRewriter;
- private int fSelectionStart;
- private int fSelectionLength;
- private AST fAST;
- private ASTRewrite fRewriter;
- private IDocument fDocument;
- private ExtractMethodAnalyzer fAnalyzer;
- private int fVisibility;
- private String fMethodName;
- private boolean fThrowRuntimeExceptions;
- private List fParameterInfos;
- private Set fUsedNames;
- private boolean fGenerateJavadoc;
- private boolean fReplaceDuplicates;
- private SnippetFinder.Match[] fDuplicates;
- private int fDestinationIndex= 0;
- // either of type TypeDeclaration or AnonymousClassDeclaration
- private ASTNode fDestination;
- // either of type TypeDeclaration or AnonymousClassDeclaration
- private ASTNode[] fDestinations;
-
- private static final String EMPTY= ""; //$NON-NLS-1$
-
- private static class UsedNamesCollector extends ASTVisitor {
- private Set result= new HashSet();
- private Set fIgnore= new HashSet();
- public static Set perform(ASTNode[] nodes) {
- UsedNamesCollector collector= new UsedNamesCollector();
- for (int i= 0; i < nodes.length; i++) {
- nodes[i].accept(collector);
- }
- return collector.result;
- }
- public boolean visit(FieldAccess node) {
- Expression exp= node.getExpression();
- if (exp != null)
- fIgnore.add(node.getName());
- return true;
- }
- public void endVisit(FieldAccess node) {
- fIgnore.remove(node.getName());
- }
- public boolean visit(FunctionInvocation node) {
- Expression exp= node.getExpression();
- if (exp != null) {
- SimpleName name = node.getName();
- if (name!=null)
- fIgnore.add(name);
- }
- return true;
- }
- public void endVisit(FunctionInvocation node) {
- SimpleName name = node.getName();
- if (name!=null)
- fIgnore.remove(name);
- }
- public boolean visit(QualifiedName node) {
- fIgnore.add(node.getName());
- return true;
- }
- public void endVisit(QualifiedName node) {
- fIgnore.remove(node.getName());
- }
- public boolean visit(SimpleName node) {
- if (!fIgnore.contains(node))
- result.add(node.getIdentifier());
- return true;
- }
- public boolean visit(TypeDeclaration node) {
- return visitType(node);
- }
- private boolean visitType(AbstractTypeDeclaration node) {
- result.add(node.getName().getIdentifier());
- // don't dive into type declaration since they open a new
- // context.
- return false;
- }
- }
-
- /**
- * Creates a new extract method refactoring
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public ExtractMethodRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) throws CoreException {
- fCUnit= unit;
- fMethodName= "extracted"; //$NON-NLS-1$
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fVisibility= -1;
- if (unit != null)
- initialize(unit);
- }
-
- private void initialize(IJavaScriptUnit cu) throws CoreException {
- fImportRewriter= StubUtility.createImportRewrite(cu, true);
- }
-
- public String getName() {
- return RefactoringCoreMessages.ExtractMethodRefactoring_name;
- }
-
- /**
- * Checks if the refactoring can be activated. Activation typically means, if a
- * corresponding menu entry can be added to the UI.
- *
- * @param pm a progress monitor to report progress during activation checking.
- * @return the refactoring status describing the result of the activation check.
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- pm.beginTask("", 100); //$NON-NLS-1$
-
- if (fSelectionStart < 0 || fSelectionLength == 0)
- return mergeTextSelectionStatus(result);
-
- IFile[] changedFiles= ResourceUtil.getFiles(new IJavaScriptUnit[]{fCUnit});
- result.merge(Checks.validateModifiesFiles(changedFiles, getValidationContext()));
- if (result.hasFatalError())
- return result;
- result.merge(ResourceChangeChecker.checkFilesToBeChanged(changedFiles, new SubProgressMonitor(pm, 1)));
-
- fRoot= RefactoringASTParser.parseWithASTProvider(fCUnit, true, new SubProgressMonitor(pm, 99));
- fAST= fRoot.getAST();
- fRoot.accept(createVisitor());
-
- result.merge(fAnalyzer.checkInitialConditions(fImportRewriter));
- if (result.hasFatalError())
- return result;
- if (fVisibility == -1) {
-// setVisibility(Modifier.PRIVATE);
- fVisibility=0;
- }
- initializeParameterInfos();
- initializeUsedNames();
- initializeDuplicates();
- initializeDestinations();
- return result;
- }
-
- private ASTVisitor createVisitor() throws JavaScriptModelException {
- fAnalyzer= new ExtractMethodAnalyzer(fCUnit, Selection.createFromStartLength(fSelectionStart, fSelectionLength));
- return fAnalyzer;
- }
-
- /**
- * Sets the method name to be used for the extracted method.
- *
- * @param name the new method name.
- */
- public void setMethodName(String name) {
- fMethodName= name;
- }
-
- /**
- * Returns the method name to be used for the extracted method.
- * @return the method name to be used for the extracted method.
- */
- public String getMethodName() {
- return fMethodName;
- }
-
- /**
- * Sets the visibility of the new method.
- *
- * @param visibility the visibility of the new method. Valid values are
- * "public", "protected", "", and "private"
- */
- public void setVisibility(int visibility) {
- fVisibility= visibility;
- }
-
- /**
- * Returns the visibility of the new method.
- *
- * @return the visibility of the new method
- */
- public int getVisibility() {
- return fVisibility;
- }
-
- /**
- * Returns the parameter infos.
- * @return a list of parameter infos.
- */
- public List getParameterInfos() {
- return fParameterInfos;
- }
-
- /**
- * Sets whether the new method signature throws runtime exceptions.
- *
- * @param throwRuntimeExceptions flag indicating if the new method
- * throws runtime exceptions
- */
- public void setThrowRuntimeExceptions(boolean throwRuntimeExceptions) {
- fThrowRuntimeExceptions= throwRuntimeExceptions;
- }
-
- /**
- * Checks if the new method name is a valid method name. This method doesn't
- * check if a method with the same name already exists in the hierarchy. This
- * check is done in <code>checkInput</code> since it is expensive.
- */
- public RefactoringStatus checkMethodName() {
- return Checks.checkMethodName(fMethodName);
- }
-
- public ASTNode[] getDestinations() {
- return fDestinations;
- }
-
- public void setDestination(int index) {
- fDestination= fDestinations[index];
- fDestinationIndex= index;
- }
-
- /**
- * Checks if the parameter names are valid.
- */
- public RefactoringStatus checkParameterNames() {
- RefactoringStatus result= new RefactoringStatus();
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo parameter= (ParameterInfo)iter.next();
- result.merge(Checks.checkIdentifier(parameter.getNewName()));
- for (Iterator others= fParameterInfos.iterator(); others.hasNext();) {
- ParameterInfo other= (ParameterInfo) others.next();
- if (parameter != other && other.getNewName().equals(parameter.getNewName())) {
- result.addError(Messages.format(
- RefactoringCoreMessages.ExtractMethodRefactoring_error_sameParameter,
- other.getNewName()));
- return result;
- }
- }
- if (parameter.isRenamed() && fUsedNames.contains(parameter.getNewName())) {
- result.addError(Messages.format(
- RefactoringCoreMessages.ExtractMethodRefactoring_error_nameInUse,
- parameter.getNewName()));
- return result;
- }
- }
- return result;
- }
-
- /**
- * Checks if varargs are ordered correctly.
- */
- public RefactoringStatus checkVarargOrder() {
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo)iter.next();
- if (info.isOldVarargs() && iter.hasNext()) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(
- RefactoringCoreMessages.ExtractMethodRefactoring_error_vararg_ordering,
- info.getOldName()));
- }
- }
- return new RefactoringStatus();
- }
-
- /**
- * Returns the names already in use in the selected statements/expressions.
- *
- * @return names already in use.
- */
- public Set getUsedNames() {
- return fUsedNames;
- }
-
- /* (non-Javadoc)
- * Method declared in Refactoring
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ExtractMethodRefactoring_checking_new_name, 2);
- pm.subTask(EMPTY);
-
- RefactoringStatus result= checkMethodName();
- result.merge(checkParameterNames());
- result.merge(checkVarargOrder());
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- BodyDeclaration node= fAnalyzer.getEnclosingBodyDeclaration();
- if (node != null) {
- fAnalyzer.checkInput(result, fMethodName, fAST);
- pm.worked(1);
- }
- pm.done();
- return result;
- }
-
- /* (non-Javadoc)
- * Method declared in IRefactoring
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- if (fMethodName == null)
- return null;
- pm.beginTask("", 2); //$NON-NLS-1$
- fAnalyzer.aboutToCreateChange();
- BodyDeclaration declaration= fAnalyzer.getEnclosingBodyDeclaration();
- fRewriter= ASTRewrite.create(declaration.getAST());
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCUnit.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- ITypeBinding type= null;
- if (fDestination instanceof AbstractTypeDeclaration) {
- final AbstractTypeDeclaration decl= (AbstractTypeDeclaration) fDestination;
- type= decl.resolveBinding();
- } else if (fDestination instanceof AnonymousClassDeclaration) {
- final AnonymousClassDeclaration decl= (AnonymousClassDeclaration) fDestination;
- type= decl.resolveBinding();
- }
- IFunctionBinding method= null;
- final BodyDeclaration enclosing= fAnalyzer.getEnclosingBodyDeclaration();
- if (enclosing instanceof FunctionDeclaration) {
- final FunctionDeclaration node= (FunctionDeclaration) enclosing;
- method= node.resolveBinding();
- }
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- final String description= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_descriptor_description_short, fMethodName);
- final String label= method != null ? BindingLabelProvider.getBindingLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) : '{' + JavaScriptElementLabels.ELLIPSIS_STRING + '}';
- final String header= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_descriptor_description, new String[] { getSignature(), label, BindingLabelProvider.getBindingLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_name_pattern, fMethodName));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_destination_pattern, BindingLabelProvider.getBindingLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
-// String visibility= JdtFlags.getVisibilityString(fVisibility);
-// if ("".equals(visibility)) //$NON-NLS-1$
-// visibility= RefactoringCoreMessages.ExtractMethodRefactoring_default_visibility;
-// comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_visibility_pattern, visibility));
-// if (fThrowRuntimeExceptions)
-// comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_declare_thrown_exceptions);
- if (fReplaceDuplicates)
- comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_replace_occurrences);
- if (fGenerateJavadoc)
- comment.addSetting(RefactoringCoreMessages.ExtractMethodRefactoring_generate_comment);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.EXTRACT_METHOD, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCUnit));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fMethodName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
-// arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
- arguments.put(ATTRIBUTE_DESTINATION, new Integer(fDestinationIndex).toString());
-// arguments.put(ATTRIBUTE_EXCEPTIONS, Boolean.valueOf(fThrowRuntimeExceptions).toString());
- arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fGenerateJavadoc).toString());
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceDuplicates).toString());
- final CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
- result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
- result.setDescriptor(new RefactoringChangeDescriptor(descriptor));
-
- MultiTextEdit root= new MultiTextEdit();
- result.setEdit(root);
- // This is cheap since the compilation unit is already open in a editor.
- IPath path= ((IFile)fCUnit.getPrimary().getResource()).getFullPath();
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- try {
- bufferManager.connect(path, LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- fDocument= bufferManager.getTextFileBuffer(path, LocationKind.IFILE).getDocument();
-
- ASTNode[] selectedNodes= fAnalyzer.getSelectedNodes();
- fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes,
- fDocument, fSelectionStart, fSelectionLength));
-
- TextEditGroup substituteDesc= new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, fMethodName));
- result.addTextEditGroup(substituteDesc);
-
- FunctionDeclaration mm= createNewMethod(fMethodName, true, selectedNodes, fDocument.getLineDelimiter(0), substituteDesc);
-
- TextEditGroup insertDesc= new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, fMethodName));
- result.addTextEditGroup(insertDesc);
-
- ASTNode afterDecl = declaration.getBodyChild();
- if (fDestination == fDestinations[0] || afterDecl==null) {
- ChildListPropertyDescriptor desc= (ChildListPropertyDescriptor)afterDecl.getLocationInParent();
- ListRewrite container= fRewriter.getListRewrite(afterDecl.getParent(), desc);
- container.insertAfter(mm, afterDecl, insertDesc);
- } else {
- BodyDeclarationRewrite container= BodyDeclarationRewrite.create(fRewriter, fDestination);
- container.insert(mm, insertDesc);
- }
-
- replaceDuplicates(result);
-
- if (fImportRewriter.hasRecordedChanges()) {
- TextEdit edit= fImportRewriter.rewriteImports(null);
- root.addChild(edit);
- result.addTextEditGroup(new TextEditGroup(
- RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports,
- new TextEdit[] {edit}
- ));
- }
- root.addChild(fRewriter.rewriteAST(fDocument, fCUnit.getJavaScriptProject().getOptions(true)));
- } catch (BadLocationException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- e.getMessage(), e));
- } finally {
- bufferManager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- pm.done();
- }
- return result;
- }
-
- /**
- * Returns the signature of the new method.
- *
- * @return the signature of the extracted method
- */
- public String getSignature() {
- return getSignature(fMethodName);
- }
-
- /**
- * Returns the signature of the new method.
- *
- * @param methodName the method name used for the new method
- * @return the signature of the extracted method
- */
- public String getSignature(String methodName) {
- FunctionDeclaration method= null;
- try {
- method= createNewMethod(methodName, false, null, StubUtility.getLineDelimiterUsed(fCUnit), null);
- } catch (CoreException cannotHappen) {
- // we don't generate a code block and java comments.
- Assert.isTrue(false);
- } catch (BadLocationException e) {
- // we don't generate a code block and java comments.
- Assert.isTrue(false);
- }
- method.setBody(fAST.newBlock());
- ASTFlattener flattener= new ASTFlattener() {
- public boolean visit(Block node) {
- return false;
- }
- };
- method.accept(flattener);
- return flattener.getResult();
- }
-
- /**
- * Returns the number of duplicate code snippets found.
- *
- * @return the number of duplicate code fragments
- */
- public int getNumberOfDuplicates() {
- if (fDuplicates == null)
- return 0;
- int result=0;
- for (int i= 0; i < fDuplicates.length; i++) {
- if (!fDuplicates[i].isMethodBody())
- result++;
- }
- return result;
- }
-
- public boolean getReplaceDuplicates() {
- return fReplaceDuplicates;
- }
-
- public void setReplaceDuplicates(boolean replace) {
- fReplaceDuplicates= replace;
- }
-
- public void setGenerateJavadoc(boolean generate) {
- fGenerateJavadoc= generate;
- }
-
- public boolean getGenerateJavadoc() {
- return fGenerateJavadoc;
- }
-
- //---- Helper methods ------------------------------------------------------------------------
-
- private void initializeParameterInfos() {
- IVariableBinding[] arguments= fAnalyzer.getArguments();
- fParameterInfos= new ArrayList(arguments.length);
- ASTNode root= fAnalyzer.getEnclosingBodyDeclaration();
- ParameterInfo vararg= null;
- for (int i= 0; i < arguments.length; i++) {
- IVariableBinding argument= arguments[i];
- if (argument == null)
- continue;
- VariableDeclaration declaration= ASTNodes.findVariableDeclaration(argument, root);
- boolean isVarargs= declaration instanceof SingleVariableDeclaration
- ? ((SingleVariableDeclaration)declaration).isVarargs()
- : false;
- ParameterInfo info= new ParameterInfo(argument, getType(declaration, isVarargs), argument.getName(), i);
- if (isVarargs) {
- vararg= info;
- } else {
- fParameterInfos.add(info);
- }
- }
- if (vararg != null) {
- fParameterInfos.add(vararg);
- }
- }
-
- private void initializeUsedNames() {
- fUsedNames= UsedNamesCollector.perform(fAnalyzer.getSelectedNodes());
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo parameter= (ParameterInfo)iter.next();
- fUsedNames.remove(parameter.getOldName());
- }
- }
-
- private void initializeDuplicates() {
- ASTNode start= fAnalyzer.getEnclosingBodyDeclaration();
- while(!(start instanceof JavaScriptUnit) &&
- !(start instanceof AbstractTypeDeclaration) &&
- !(start instanceof AnonymousClassDeclaration)) {
- start= start.getParent();
- }
-
- fDuplicates= SnippetFinder.perform(start, fAnalyzer.getSelectedNodes());
- fReplaceDuplicates= fDuplicates.length > 0 && ! fAnalyzer.isLiteralNodeSelected();
- }
-
- private void initializeDestinations() {
- List result= new ArrayList();
- BodyDeclaration decl= fAnalyzer.getEnclosingBodyDeclaration();
- ASTNode current= getNextParent(decl);
- result.add(current);
- if (decl instanceof FunctionDeclaration) {
- ITypeBinding binding= ASTNodes.getEnclosingType(current);
- ASTNode next= getNextParent(current);
- while (next != null && binding != null && binding.isNested() && !Modifier.isStatic(binding.getDeclaredModifiers())) {
- result.add(next);
- current= next;
- binding= ASTNodes.getEnclosingType(current);
- next= getNextParent(next);
- }
- }
- fDestinations= (ASTNode[])result.toArray(new ASTNode[result.size()]);
- fDestination= fDestinations[fDestinationIndex];
- }
-
- private ASTNode getNextParent(ASTNode node) {
- do {
- node= node.getParent();
- } while (node != null && !(
- (node instanceof JavaScriptUnit) ||(node instanceof AbstractTypeDeclaration) || (node instanceof AnonymousClassDeclaration)));
- return node;
- }
-
- private RefactoringStatus mergeTextSelectionStatus(RefactoringStatus status) {
- status.addFatalError(RefactoringCoreMessages.ExtractMethodRefactoring_no_set_of_statements);
- return status;
- }
-
- private String getType(VariableDeclaration declaration, boolean isVarargs) {
- String type= ASTNodes.asString(ASTNodeFactory.newType(declaration.getAST(), declaration));
- if (isVarargs)
- return type + ParameterInfo.ELLIPSIS;
- else
- return type;
- }
-
- //---- Code generation -----------------------------------------------------------------------
-
- private ASTNode[] createCallNodes(SnippetFinder.Match duplicate) {
- List result= new ArrayList(2);
-
- IVariableBinding[] locals= fAnalyzer.getCallerLocals();
- for (int i= 0; i < locals.length; i++) {
- result.add(createDeclaration(locals[i], null));
- }
-
- FunctionInvocation invocation= fAST.newFunctionInvocation();
- invocation.setName(fAST.newSimpleName(fMethodName));
- List arguments= invocation.arguments();
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo parameter= ((ParameterInfo)fParameterInfos.get(i));
- arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
- }
-
- ASTNode call;
- int returnKind= fAnalyzer.getReturnKind();
- switch (returnKind) {
- case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
- IVariableBinding binding= fAnalyzer.getReturnLocal();
- if (binding != null) {
- VariableDeclarationStatement decl= createDeclaration(getMappedBinding(duplicate, binding), invocation);
- call= decl;
- } else {
- Assignment assignment= fAST.newAssignment();
- assignment.setLeftHandSide(ASTNodeFactory.newName(fAST,
- getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
- assignment.setRightHandSide(invocation);
- call= assignment;
- }
- break;
- case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
- ReturnStatement rs= fAST.newReturnStatement();
- rs.setExpression(invocation);
- call= rs;
- break;
- default:
- call= invocation;
- }
-
- if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
- call= fAST.newExpressionStatement((Expression)call);
- }
- result.add(call);
-
- // We have a void return statement. The code looks like
- // extracted();
- // return;
- if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
- result.add(fAST.newReturnStatement());
- }
- return (ASTNode[])result.toArray(new ASTNode[result.size()]);
- }
-
- private IVariableBinding getMappedBinding(SnippetFinder.Match duplicate, IVariableBinding org) {
- if (duplicate == null)
- return org;
- return duplicate.getMappedBinding(org);
- }
-
- private String getMappedName(SnippetFinder.Match duplicate, ParameterInfo paramter) {
- if (duplicate == null)
- return paramter.getOldName();
- return duplicate.getMappedName(paramter.getOldBinding()).getIdentifier();
- }
-
- private void replaceDuplicates(CompilationUnitChange result) {
- int numberOf= getNumberOfDuplicates();
- if (numberOf == 0 || !fReplaceDuplicates)
- return;
- String label= null;
- if (numberOf == 1)
- label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, fMethodName);
- else
- label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, fMethodName);
-
- TextEditGroup description= new TextEditGroup(label);
- result.addTextEditGroup(description);
-
- for (int d= 0; d < fDuplicates.length; d++) {
- SnippetFinder.Match duplicate= fDuplicates[d];
- if (!duplicate.isMethodBody()) {
- ASTNode[] callNodes= createCallNodes(duplicate);
- new StatementRewrite(fRewriter, duplicate.getNodes()).replace(callNodes, description);
- }
- }
- }
-
- private FunctionDeclaration createNewMethod(String name, boolean code, ASTNode[] selectedNodes, String lineDelimiter, TextEditGroup substitute) throws CoreException, BadLocationException {
- FunctionDeclaration result= fAST.newFunctionDeclaration();
- int modifiers= fVisibility;
- if (Modifier.isStatic(fAnalyzer.getEnclosingBodyDeclaration().getModifiers()) || fAnalyzer.getForceStatic()) {
- modifiers|= Modifier.STATIC;
- }
-
- result.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, modifiers));
- result.setReturnType2((Type)ASTNode.copySubtree(fAST, fAnalyzer.getReturnType()));
- result.setName(fAST.newSimpleName(name));
-
- List parameters= result.parameters();
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo)fParameterInfos.get(i);
- VariableDeclaration infoDecl= getVariableDeclaration(info);
- SingleVariableDeclaration parameter= fAST.newSingleVariableDeclaration();
- parameter.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, ASTNodes.getModifiers(infoDecl)));
- parameter.setType(ASTNodeFactory.newType(fAST, infoDecl));
- parameter.setName(fAST.newSimpleName(info.getNewName()));
- parameter.setVarargs(info.isNewVarargs());
- parameters.add(parameter);
- }
-
- List exceptions= result.thrownExceptions();
- ITypeBinding[] exceptionTypes= fAnalyzer.getExceptions(fThrowRuntimeExceptions, fAST);
- for (int i= 0; i < exceptionTypes.length; i++) {
- ITypeBinding exceptionType= exceptionTypes[i];
- exceptions.add(ASTNodeFactory.newName(fAST, fImportRewriter.addImport(exceptionType)));
- }
- if (code) {
- result.setBody(createMethodBody(result, selectedNodes, substitute));
- if (fGenerateJavadoc) {
- AbstractTypeDeclaration enclosingType=
- (AbstractTypeDeclaration)ASTNodes.getParent(fAnalyzer.getEnclosingBodyDeclaration(), AbstractTypeDeclaration.class);
-
- String typeName = (enclosingType!=null)?enclosingType.getName().getIdentifier():null;
- String string= CodeGeneration.getMethodComment(fCUnit, typeName, result, null, lineDelimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc)fRewriter.createStringPlaceholder(string, ASTNode.JSDOC);
- result.setJavadoc(javadoc);
- }
- }
- }
-
- return result;
- }
-
- private Block createMethodBody(FunctionDeclaration method, ASTNode[] selectedNodes, TextEditGroup substitute) throws BadLocationException, CoreException {
- Block result= fAST.newBlock();
- ListRewrite statements= fRewriter.getListRewrite(result, Block.STATEMENTS_PROPERTY);
-
- // Locals that are not passed as an arguments since the extracted method only
- // writes to them
- IVariableBinding[] methodLocals= fAnalyzer.getMethodLocals();
- for (int i= 0; i < methodLocals.length; i++) {
- if (methodLocals[i] != null) {
- result.statements().add(createDeclaration(methodLocals[i], null));
- }
- }
-
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo parameter= (ParameterInfo)iter.next();
- if (parameter.isRenamed()) {
- for (int n= 0; n < selectedNodes.length; n++) {
- SimpleName[] oldNames= LinkedNodeFinder.findByBinding(selectedNodes[n], parameter.getOldBinding());
- for (int i= 0; i < oldNames.length; i++) {
- fRewriter.replace(oldNames[i], fAST.newSimpleName(parameter.getNewName()), null);
- }
- }
- }
- }
-
- boolean extractsExpression= fAnalyzer.isExpressionSelected();
- ASTNode[] callNodes= createCallNodes(null);
- ASTNode replacementNode;
- if (callNodes.length == 1) {
- replacementNode= callNodes[0];
- } else {
- replacementNode= fRewriter.createGroupNode(callNodes);
- }
- if (extractsExpression) {
- // if we have an expression then only one node is selected.
- ITypeBinding binding= fAnalyzer.getExpressionBinding();
- if (binding != null && (!binding.isPrimitive() || !"void".equals(binding.getName()))) { //$NON-NLS-1$
- ReturnStatement rs= fAST.newReturnStatement();
- rs.setExpression((Expression)fRewriter.createMoveTarget(selectedNodes[0]));
- statements.insertLast(rs, null);
- } else {
- ExpressionStatement st= fAST.newExpressionStatement((Expression)fRewriter.createMoveTarget(selectedNodes[0]));
- statements.insertLast(st, null);
- }
- fRewriter.replace(selectedNodes[0], replacementNode, substitute);
- } else {
- if (selectedNodes.length == 1) {
- statements.insertLast(fRewriter.createMoveTarget(selectedNodes[0]), substitute);
- fRewriter.replace(selectedNodes[0], replacementNode, substitute);
- } else {
- ListRewrite source= fRewriter.getListRewrite(
- selectedNodes[0].getParent(),
- (ChildListPropertyDescriptor)selectedNodes[0].getLocationInParent());
- ASTNode toMove= source.createMoveTarget(
- selectedNodes[0], selectedNodes[selectedNodes.length - 1],
- replacementNode, substitute);
- statements.insertLast(toMove, substitute);
- }
- IVariableBinding returnValue= fAnalyzer.getReturnValue();
- if (returnValue != null) {
- ReturnStatement rs= fAST.newReturnStatement();
- rs.setExpression(fAST.newSimpleName(getName(returnValue)));
- statements.insertLast(rs, null);
- }
- }
- return result;
- }
-
- private String getName(IVariableBinding binding) {
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo)iter.next();
- if (Bindings.equals(binding, info.getOldBinding())) {
- return info.getNewName();
- }
- }
- return binding.getName();
- }
-
- private VariableDeclaration getVariableDeclaration(ParameterInfo parameter) {
- return ASTNodes.findVariableDeclaration(parameter.getOldBinding(), fAnalyzer.getEnclosingBodyDeclaration());
- }
-
- private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) {
- VariableDeclaration original= ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration());
- VariableDeclarationFragment fragment= fAST.newVariableDeclarationFragment();
- fragment.setName((SimpleName)ASTNode.copySubtree(fAST, original.getName()));
- fragment.setInitializer(intilizer);
- VariableDeclarationStatement result= fAST.newVariableDeclarationStatement(fragment);
- result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original)));
- result.setType(ASTNodeFactory.newType(fAST, original));
- return result;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCUnit;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.EXTRACT_METHOD);
- else {
- fCUnit= (IJavaScriptUnit) element;
- try {
- initialize(fCUnit);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= flag;
- }
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fMethodName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String destination= extended.getAttribute(ATTRIBUTE_DESTINATION);
- if (destination != null && !"".equals(destination)) {//$NON-NLS-1$
- int index= 0;
- try {
- index= Integer.parseInt(destination);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DESTINATION));
- }
- fDestinationIndex= index;
- }
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplaceDuplicates= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- final String comments= extended.getAttribute(ATTRIBUTE_COMMENTS);
- if (comments != null)
- fGenerateJavadoc= Boolean.valueOf(comments).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_COMMENTS));
- final String exceptions= extended.getAttribute(ATTRIBUTE_EXCEPTIONS);
- if (exceptions != null)
- fThrowRuntimeExceptions= Boolean.valueOf(exceptions).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_EXCEPTIONS));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java
deleted file mode 100644
index 6e636d23..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java
+++ /dev/null
@@ -1,1007 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IExpressionFragment;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RefactoringDescriptorChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Extract Local Variable (from selected expression inside method or initializer).
- */
-public class ExtractTempRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FINAL= "final"; //$NON-NLS-1$
-
- private static final class ForStatementChecker extends ASTVisitor {
-
- private final Collection fForInitializerVariables;
-
- private boolean fReferringToForVariable= false;
-
- public ForStatementChecker(Collection forInitializerVariables) {
- Assert.isNotNull(forInitializerVariables);
- fForInitializerVariables= forInitializerVariables;
- }
-
- public boolean isReferringToForVariable() {
- return fReferringToForVariable;
- }
-
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (binding != null && fForInitializerVariables.contains(binding)) {
- fReferringToForVariable= true;
- }
- return false;
- }
- }
-
-
-
- private static boolean allArraysEqual(Object[][] arrays, int position) {
- Object element= arrays[0][position];
- for (int i= 0; i < arrays.length; i++) {
- Object[] array= arrays[i];
- if (!element.equals(array[position]))
- return false;
- }
- return true;
- }
-
- private static boolean canReplace(IASTFragment fragment) {
- ASTNode node= fragment.getAssociatedNode();
- ASTNode parent= node.getParent();
- if (parent instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent;
- if (node.equals(vdf.getName()))
- return false;
- }
- if (isMethodParameter(node))
- return false;
- if (isThrowableInCatchBlock(node))
- return false;
- if (parent instanceof ExpressionStatement)
- return false;
- if (isLeftValue(node))
- return false;
- if (isReferringToLocalVariableFromFor((Expression) node))
- return false;
- if (isUsedInForInitializerOrUpdater((Expression) node))
- return false;
- if (parent instanceof SwitchCase)
- return false;
- return true;
- }
-
- private static Object[] getArrayPrefix(Object[] array, int prefixLength) {
- Assert.isTrue(prefixLength <= array.length);
- Assert.isTrue(prefixLength >= 0);
- Object[] prefix= new Object[prefixLength];
- for (int i= 0; i < prefix.length; i++) {
- prefix[i]= array[i];
- }
- return prefix;
- }
-
- // return List<IVariableBinding>
- private static List getForInitializedVariables(VariableDeclarationExpression variableDeclarations) {
- List forInitializerVariables= new ArrayList(1);
- for (Iterator iter= variableDeclarations.fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) iter.next();
- IVariableBinding binding= fragment.resolveBinding();
- if (binding != null)
- forInitializerVariables.add(binding);
- }
- return forInitializerVariables;
- }
-
- private static Object[] getLongestArrayPrefix(Object[][] arrays) {
- int length= -1;
- if (arrays.length == 0)
- return new Object[0];
- int minArrayLength= arrays[0].length;
- for (int i= 1; i < arrays.length; i++)
- minArrayLength= Math.min(minArrayLength, arrays[i].length);
-
- for (int i= 0; i < minArrayLength; i++) {
- if (!allArraysEqual(arrays, i))
- break;
- length++;
- }
- if (length == -1)
- return new Object[0];
- return getArrayPrefix(arrays[0], length + 1);
- }
-
- private static ASTNode[] getParents(ASTNode node) {
- ASTNode current= node;
- List parents= new ArrayList();
- do {
- parents.add(current.getParent());
- current= current.getParent();
- } while (current.getParent() != null);
- Collections.reverse(parents);
- return (ASTNode[]) parents.toArray(new ASTNode[parents.size()]);
- }
-
- private static boolean isLeftValue(ASTNode node) {
- ASTNode parent= node.getParent();
- if (parent instanceof Assignment) {
- Assignment assignment= (Assignment) parent;
- if (assignment.getLeftHandSide() == node)
- return true;
- }
- if (parent instanceof PostfixExpression)
- return true;
- if (parent instanceof PrefixExpression) {
- PrefixExpression.Operator op= ((PrefixExpression) parent).getOperator();
- if (op.equals(PrefixExpression.Operator.DECREMENT))
- return true;
- if (op.equals(PrefixExpression.Operator.INCREMENT))
- return true;
- return false;
- }
- return false;
- }
-
- private static boolean isMethodParameter(ASTNode node) {
- return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof FunctionDeclaration);
- }
-
- private static boolean isReferringToLocalVariableFromFor(Expression expression) {
- ASTNode current= expression;
- ASTNode parent= current.getParent();
- while (parent != null && !(parent instanceof BodyDeclaration)) {
- if (parent instanceof ForStatement) {
- ForStatement forStmt= (ForStatement) parent;
- if (forStmt.initializers().contains(current) || forStmt.updaters().contains(current) || forStmt.getExpression() == current) {
- List initializers= forStmt.initializers();
- if (initializers.size() == 1 && initializers.get(0) instanceof VariableDeclarationExpression) {
- List forInitializerVariables= getForInitializedVariables((VariableDeclarationExpression) initializers.get(0));
- ForStatementChecker checker= new ForStatementChecker(forInitializerVariables);
- expression.accept(checker);
- if (checker.isReferringToForVariable())
- return true;
- }
- }
- }
- else if (parent instanceof ForInStatement) {
- ForInStatement forInStmt= (ForInStatement) parent;
- if (forInStmt.getIterationVariable().equals(current) || forInStmt.getCollection() == current) {
- if (forInStmt.getIterationVariable() instanceof VariableDeclarationStatement) {
- List forInitializerVariables= new ArrayList(1);
- forInitializerVariables.add( ((VariableDeclarationStatement) forInStmt.getIterationVariable()).resolveBinding());
- ForStatementChecker checker= new ForStatementChecker(forInitializerVariables);
- expression.accept(checker);
- if (checker.isReferringToForVariable())
- return true;
- }
- }
- }
- current= parent;
- parent= current.getParent();
- }
- return false;
- }
-
- private static boolean isThrowableInCatchBlock(ASTNode node) {
- return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof CatchClause);
- }
-
- private static boolean isUsedInForInitializerOrUpdater(Expression expression) {
- ASTNode parent= expression.getParent();
- if (parent instanceof ForStatement) {
- ForStatement forStmt= (ForStatement) parent;
- return forStmt.initializers().contains(expression) || forStmt.updaters().contains(expression);
- }
- return false;
- }
-
- private static IASTFragment[] retainOnlyReplacableMatches(IASTFragment[] allMatches) {
- List result= new ArrayList(allMatches.length);
- for (int i= 0; i < allMatches.length; i++) {
- if (canReplace(allMatches[i]))
- result.add(allMatches[i]);
- }
- return (IASTFragment[]) result.toArray(new IASTFragment[result.size()]);
- }
-
- private JavaScriptUnit fCompilationUnitNode;
-
- private CompilationUnitRewrite fCURewrite;
-
- private IJavaScriptUnit fCu;
-
- private boolean fDeclareFinal;
-
- private String[] fExcludedVariableNames;
-
- private boolean fReplaceAllOccurrences;
-
- // caches:
- private IExpressionFragment fSelectedExpression;
-
- private int fSelectionLength;
-
- private int fSelectionStart;
-
- private String fTempName;
- private String[] fGuessedTempNames;
-
- private TextChange fChange;
-
- private LinkedProposalModel fLinkedProposalModel;
-
- private static final String KEY_NAME= "name"; //$NON-NLS-1$
-// private static final String KEY_TYPE= "type"; //$NON-NLS-1$
-
-
- /**
- * Creates a new extract temp refactoring
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public ExtractTempRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= unit;
- fCompilationUnitNode= null;
-
- fReplaceAllOccurrences= true; // default
- fDeclareFinal= false; // default
- fTempName= ""; //$NON-NLS-1$
-
- fLinkedProposalModel= null;
- }
-
- public ExtractTempRefactoring(JavaScriptUnit astRoot, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- Assert.isTrue(astRoot.getTypeRoot() instanceof IJavaScriptUnit);
-
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= (IJavaScriptUnit) astRoot.getTypeRoot();
- fCompilationUnitNode= astRoot;
-
- fReplaceAllOccurrences= true; // default
- fDeclareFinal= false; // default
- fTempName= ""; //$NON-NLS-1$
-
- fLinkedProposalModel= null;
- }
-
- public void setLinkedProposalModel(LinkedProposalModel linkedProposalModel) {
- fLinkedProposalModel= linkedProposalModel;
- }
-
- private void addReplaceExpressionWithTemp() throws JavaScriptModelException {
- IASTFragment[] fragmentsToReplace= retainOnlyReplacableMatches(getMatchingFragments());
- //TODO: should not have to prune duplicates here...
- ASTRewrite rewrite= fCURewrite.getASTRewrite();
- HashSet seen= new HashSet();
- for (int i= 0; i < fragmentsToReplace.length; i++) {
- IASTFragment fragment= fragmentsToReplace[i];
- if (! seen.add(fragment))
- continue;
- SimpleName tempName= fCURewrite.getAST().newSimpleName(fTempName);
- TextEditGroup description= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_replace);
-
- fragment.replace(rewrite, tempName, description);
- if (fLinkedProposalModel != null)
- fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(tempName), false);
- }
- }
-
- private RefactoringStatus checkExpression() throws JavaScriptModelException {
- Expression selectedExpression= getSelectedExpression().getAssociatedExpression();
- if (selectedExpression != null) {
- final ASTNode parent= selectedExpression.getParent();
- if (selectedExpression instanceof NullLiteral) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
- } else if (selectedExpression instanceof ArrayInitializer) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
- } else if (selectedExpression instanceof Assignment) {
- if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
- else
- return null;
-
- } else if (selectedExpression instanceof SimpleName) {
- if ((((SimpleName) selectedExpression)).isDeclaration())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
- if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
- }
- }
-
- return null;
- }
-
- // !! Same as in ExtractConstantRefactoring
- private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaScriptModelException {
- switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
- case Checks.NOT_RVALUE_MISC:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_select_expression, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
- case Checks.NOT_RVALUE_VOID:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_no_void, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
- case Checks.IS_RVALUE:
- return new RefactoringStatus();
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public TextChange createTextChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 3);
-
- fCURewrite= new CompilationUnitRewrite(fCu, fCompilationUnitNode);
- fCURewrite.getASTRewrite().setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
-
- doCreateChange(new SubProgressMonitor(pm, 2));
-
- return fCURewrite.createChange(RefactoringCoreMessages.ExtractTempRefactoring_change_name, true, new SubProgressMonitor(pm, 1));
- } finally {
- pm.done();
- }
- }
-
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- fChange= createTextChange(pm);
-
- RefactoringStatus result= new RefactoringStatus();
- if (Arrays.asList(getExcludedVariableNames()).contains(fTempName))
- result.addWarning(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_another_variable, fTempName));
-
- result.merge(checkMatchingFragments());
-
- fChange.setKeepPreviewEdits(true);
- checkNewSource(result);
-
- return result;
- }
-
- private final JDTRefactoringDescriptor createRefactoringDescriptor() {
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final String description= Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, fTempName);
- final String expression= ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
- final String header= Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description, new String[] { fTempName, expression});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, fTempName));
- final BodyDeclaration decl= (BodyDeclaration) ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class);
- if (decl instanceof FunctionDeclaration) {
- final IFunctionBinding method= ((FunctionDeclaration) decl).resolveBinding();
- final String label= method != null ? BindingLabelProvider.getBindingLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) : '{' + JavaScriptElementLabels.ELLIPSIS_STRING + '}';
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label));
- }
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, expression));
- if (fReplaceAllOccurrences)
- comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences);
- if (fDeclareFinal)
- comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.EXTRACT_LOCAL_VARIABLE, project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fTempName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
- arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
- return descriptor;
- }
-
- private void doCreateChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 1);
- try {
- createTempDeclaration();
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- addReplaceExpressionWithTemp();
- } finally {
- pm.done();
- }
- }
-
- private void checkNewSource(RefactoringStatus result) throws CoreException {
- String newCuSource= fChange.getPreviewContent(new NullProgressMonitor());
- JavaScriptUnit newCUNode= new RefactoringASTParser(AST.JLS3).parse(newCuSource, fCu, true, true, null);
- IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
- for (int i= 0; i < newProblems.length; i++) {
- IProblem problem= newProblems[i];
- if (problem.isError())
- result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, new SourceRange(problem))));
- }
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 6); //$NON-NLS-1$
-
- RefactoringStatus result= Checks.validateModifiesFiles(ResourceUtil.getFiles(new IJavaScriptUnit[] { fCu}), getValidationContext());
- if (result.hasFatalError())
- return result;
-
- if (fCompilationUnitNode == null) {
- fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
- } else {
- pm.worked(3);
- }
-
- result.merge(checkSelection(new SubProgressMonitor(pm, 3)));
- if (!result.hasFatalError() && isLiteralNodeSelected())
- fReplaceAllOccurrences= false;
- return result;
-
- } finally {
- pm.done();
- }
- }
-
- private RefactoringStatus checkMatchingFragments() throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- IASTFragment[] matchingFragments= getMatchingFragments();
- for (int i= 0; i < matchingFragments.length; i++) {
- ASTNode node= matchingFragments[i].getAssociatedNode();
- if (isLeftValue(node) && !isReferringToLocalVariableFromFor((Expression) node)) {
- String msg= RefactoringCoreMessages.ExtractTempRefactoring_assigned_to;
- result.addWarning(msg, JavaStatusContext.create(fCu, node));
- }
- }
- return result;
- }
-
- private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaScriptModelException {
- try {
- pm.beginTask("", 8); //$NON-NLS-1$
-
- IExpressionFragment selectedExpression= getSelectedExpression();
-
- if (selectedExpression == null) {
- String message= RefactoringCoreMessages.ExtractTempRefactoring_select_expression;
- return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, fCompilationUnitNode, message);
- }
- pm.worked(1);
-
- if (isUsedInExplicitConstructorCall())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_explicit_constructor);
- pm.worked(1);
-
- if (getEnclosingBodyNode() == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_expr_in_method_or_initializer);
- pm.worked(1);
-
- ASTNode associatedNode= selectedExpression.getAssociatedNode();
- if (associatedNode instanceof Name && associatedNode.getParent() instanceof ClassInstanceCreation && associatedNode.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_name_in_new);
- pm.worked(1);
-
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkExpression());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- result.merge(checkExpressionFragmentIsRValue());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_for_initializer_updater);
- pm.worked(1);
-
- if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_refers_to_for_variable);
- pm.worked(1);
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- public RefactoringStatus checkTempName(String newName) {
- RefactoringStatus status= Checks.checkTempName(newName);
- if (Arrays.asList(getExcludedVariableNames()).contains(newName))
- status.addWarning(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_another_variable, newName));
- return status;
- }
-
- private void createAndInsertTempDeclaration() throws CoreException {
- Expression initializer= getSelectedExpression().createCopyTarget(fCURewrite.getASTRewrite());
- VariableDeclarationStatement vds= createTempDeclaration(initializer);
-
- if ((!fReplaceAllOccurrences) || (retainOnlyReplacableMatches(getMatchingFragments()).length <= 1)) {
- insertAt(getSelectedExpression().getAssociatedNode(), vds);
- return;
- }
-
- ASTNode[] firstReplaceNodeParents= getParents(getFirstReplacedExpression().getAssociatedNode());
- ASTNode[] commonPath= findDeepestCommonSuperNodePathForReplacedNodes();
- Assert.isTrue(commonPath.length <= firstReplaceNodeParents.length);
-
- ASTNode deepestCommonParent= firstReplaceNodeParents[commonPath.length - 1];
- if (deepestCommonParent instanceof Block)
- insertAt(firstReplaceNodeParents[commonPath.length], vds);
- else
- insertAt(deepestCommonParent, vds);
- }
-
- private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException {
- AST ast= fCURewrite.getAST();
-
- VariableDeclarationFragment vdf= ast.newVariableDeclarationFragment();
- vdf.setName(ast.newSimpleName(fTempName));
- vdf.setInitializer(initializer);
-
- VariableDeclarationStatement vds= ast.newVariableDeclarationStatement(vdf);
-// if (fDeclareFinal) {
-// vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
-// }
-// vds.setType(createTempType());
-
- if (fLinkedProposalModel != null) {
- ASTRewrite rewrite= fCURewrite.getASTRewrite();
- LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
- nameGroup.addPosition(rewrite.track(vdf.getName()), true);
-
- String[] nameSuggestions= guessTempNames();
- if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) {
- nameGroup.addProposal(fTempName, null, nameSuggestions.length + 1);
- }
- for (int i= 0; i < nameSuggestions.length; i++) {
- nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
- }
- }
- return vds;
- }
-
- private void insertAt(ASTNode target, Statement declaration) throws JavaScriptModelException {
- ASTRewrite rewrite= fCURewrite.getASTRewrite();
- TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable);
-
- ASTNode parent= target.getParent();
- while (! (parent instanceof Block)) {
- StructuralPropertyDescriptor locationInParent= target.getLocationInParent();
- if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
- || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
- || locationInParent == ForStatement.BODY_PROPERTY
- || locationInParent == ForInStatement.BODY_PROPERTY
- || locationInParent == EnhancedForStatement.BODY_PROPERTY
- || locationInParent == DoStatement.BODY_PROPERTY
- || locationInParent == WhileStatement.BODY_PROPERTY
- || locationInParent == WithStatement.BODY_PROPERTY
- ) {
- Block replacement= rewrite.getAST().newBlock();
- ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
- replacementRewrite.insertFirst(declaration, null);
- replacementRewrite.insertLast(rewrite.createMoveTarget(target), null);
- rewrite.replace(target, replacement, groupDescription);
- return;
- }
- target= parent;
- parent= parent.getParent();
- }
- ListRewrite listRewrite= rewrite.getListRewrite(parent, Block.STATEMENTS_PROPERTY);
- listRewrite.insertBefore(declaration, target, groupDescription);
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 1);
- JDTRefactoringDescriptor descriptor= createRefactoringDescriptor();
- return new RefactoringDescriptorChange(descriptor, RefactoringCoreMessages.ExtractTempRefactoring_extract_temp, new Change[] { fChange});
- } finally {
- pm.done();
- }
- }
-
- private void createTempDeclaration() throws CoreException {
- if (shouldReplaceSelectedExpressionWithTempDeclaration())
- replaceSelectedExpressionWithTempDeclaration();
- else
- createAndInsertTempDeclaration();
- }
-
- public boolean declareFinal() {
- return fDeclareFinal;
- }
-
- private ASTNode[] findDeepestCommonSuperNodePathForReplacedNodes() throws JavaScriptModelException {
- ASTNode[] matchNodes= getMatchNodes();
-
- ASTNode[][] matchingNodesParents= new ASTNode[matchNodes.length][];
- for (int i= 0; i < matchNodes.length; i++) {
- matchingNodesParents[i]= getParents(matchNodes[i]);
- }
- List l= Arrays.asList(getLongestArrayPrefix(matchingNodesParents));
- return (ASTNode[]) l.toArray(new ASTNode[l.size()]);
- }
-
- private Block getEnclosingBodyNode() throws JavaScriptModelException {
- ASTNode node= getSelectedExpression().getAssociatedNode();
- do {
- switch (node.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- return ((FunctionDeclaration) node).getBody();
- case ASTNode.INITIALIZER:
- return ((Initializer) node).getBody();
- }
- node= node.getParent();
- } while (node != null);
- return null;
- }
-
- private String[] getExcludedVariableNames() {
- if (fExcludedVariableNames == null) {
- try {
- IBinding[] bindings= new ScopeAnalyzer(fCompilationUnitNode).getDeclarationsInScope(getSelectedExpression().getStartPosition(), ScopeAnalyzer.VARIABLES);
- fExcludedVariableNames= new String[bindings.length];
- for (int i= 0; i < bindings.length; i++) {
- fExcludedVariableNames[i]= bindings[i].getName();
- }
- } catch (JavaScriptModelException e) {
- fExcludedVariableNames= new String[0];
- }
- }
- return fExcludedVariableNames;
- }
-
- private IExpressionFragment getFirstReplacedExpression() throws JavaScriptModelException {
- if (!fReplaceAllOccurrences)
- return getSelectedExpression();
- IASTFragment[] nodesToReplace= retainOnlyReplacableMatches(getMatchingFragments());
- if (nodesToReplace.length == 0)
- return getSelectedExpression();
- Comparator comparator= new Comparator() {
-
- public int compare(Object o1, Object o2) {
- return ((IASTFragment) o1).getStartPosition() - ((IASTFragment) o2).getStartPosition();
- }
- };
- Arrays.sort(nodesToReplace, comparator);
- return (IExpressionFragment) nodesToReplace[0];
- }
-
- private IASTFragment[] getMatchingFragments() throws JavaScriptModelException {
- if (fReplaceAllOccurrences) {
- IASTFragment[] allMatches= ASTFragmentFactory.createFragmentForFullSubtree(getEnclosingBodyNode()).getSubFragmentsMatching(getSelectedExpression());
- return allMatches;
- } else
- return new IASTFragment[] { getSelectedExpression()};
- }
-
- private ASTNode[] getMatchNodes() throws JavaScriptModelException {
- IASTFragment[] matches= retainOnlyReplacableMatches(getMatchingFragments());
- ASTNode[] result= new ASTNode[matches.length];
- for (int i= 0; i < matches.length; i++)
- result[i]= matches[i].getAssociatedNode();
- return result;
- }
-
- public String getName() {
- return RefactoringCoreMessages.ExtractTempRefactoring_name;
- }
-
-
- private IExpressionFragment getSelectedExpression() throws JavaScriptModelException {
- if (fSelectedExpression != null)
- return fSelectedExpression;
- IASTFragment selectedFragment= ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);
-
- if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
- fSelectedExpression= (IExpressionFragment) selectedFragment;
- } else if (selectedFragment != null) {
- if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
- ExpressionStatement exprStatement= (ExpressionStatement) selectedFragment.getAssociatedNode();
- Expression expression= exprStatement.getExpression();
- fSelectedExpression= (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
- } else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
- Assignment assignment= (Assignment) selectedFragment.getAssociatedNode();
- fSelectedExpression= (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
- }
- }
-
- return fSelectedExpression;
- }
-
-// private Type createTempType() throws CoreException {
-// Expression expression= getSelectedExpression().getAssociatedExpression();
-//
-// Type resultingType= null;
-// ITypeBinding typeBinding= expression.resolveTypeBinding();
-//
-// ASTRewrite rewrite= fCURewrite.getASTRewrite();
-// AST ast= rewrite.getAST();
-//
-// if (expression instanceof ClassInstanceCreation) {
-// resultingType= (Type) rewrite.createCopyTarget(((ClassInstanceCreation) expression).getType());
-// } else if (expression instanceof CastExpression) {
-// resultingType= (Type) rewrite.createCopyTarget(((CastExpression) expression).getType());
-// } else {
-// if (typeBinding == null) {
-// typeBinding= ASTResolving.guessBindingForReference(expression);
-// }
-// if (typeBinding != null) {
-// typeBinding= Bindings.normalizeForDeclarationUse(typeBinding, ast);
-// resultingType= fCURewrite.getImportRewrite().addImport(typeBinding, ast);
-// } else {
-// resultingType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
-// }
-// }
-// if (fLinkedProposalModel != null) {
-// LinkedProposalPositionGroup typeGroup= fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
-// typeGroup.addPosition(rewrite.track(resultingType), false);
-// if (typeBinding != null) {
-// ITypeBinding[] relaxingTypes= ASTResolving.getNarrowingTypes(ast, typeBinding);
-// for (int i= 0; i < relaxingTypes.length; i++) {
-// typeGroup.addProposal(relaxingTypes[i], fCURewrite.getCu(), relaxingTypes.length - i);
-// }
-// }
-// }
-// return resultingType;
-// }
-
- public String guessTempName() {
- String[] proposals= guessTempNames();
- if (proposals.length == 0)
- return fTempName;
- else
- return proposals[0];
- }
-
- /**
- * @return proposed variable names (may be empty, but not null). The first proposal should be used as "best guess" (if it exists).
- */
- public String[] guessTempNames() {
- if (fGuessedTempNames == null) {
- try {
- Expression expression= getSelectedExpression().getAssociatedExpression();
- if (expression != null) {
- ITypeBinding binding= expression.resolveTypeBinding();
- fGuessedTempNames= StubUtility.getVariableNameSuggestions(StubUtility.LOCAL, fCu.getJavaScriptProject(), binding, expression, Arrays.asList(getExcludedVariableNames()));
- }
- } catch (JavaScriptModelException e) {
- }
- if (fGuessedTempNames == null)
- fGuessedTempNames= new String[0];
- }
- return fGuessedTempNames;
- }
-
- private boolean isLiteralNodeSelected() throws JavaScriptModelException {
- IExpressionFragment fragment= getSelectedExpression();
- if (fragment == null)
- return false;
- Expression expression= fragment.getAssociatedExpression();
- if (expression == null)
- return false;
- switch (expression.getNodeType()) {
- case ASTNode.BOOLEAN_LITERAL:
- case ASTNode.CHARACTER_LITERAL:
- case ASTNode.NULL_LITERAL:
- case ASTNode.NUMBER_LITERAL:
- case ASTNode.REGULAR_EXPRESSION_LITERAL:
- case ASTNode.UNDEFINED_LITERAL:
- return true;
-
- default:
- return false;
- }
- }
-
- private boolean isUsedInExplicitConstructorCall() throws JavaScriptModelException {
- Expression selectedExpression= getSelectedExpression().getAssociatedExpression();
- if (ASTNodes.getParent(selectedExpression, ConstructorInvocation.class) != null)
- return true;
- if (ASTNodes.getParent(selectedExpression, SuperConstructorInvocation.class) != null)
- return true;
- return false;
- }
-
- public boolean replaceAllOccurrences() {
- return fReplaceAllOccurrences;
- }
-
- private void replaceSelectedExpressionWithTempDeclaration() throws CoreException {
- ASTRewrite rewrite= fCURewrite.getASTRewrite();
- Expression selectedExpression= getSelectedExpression().getAssociatedExpression(); // whole expression selected
-
- Expression initializer= (Expression) rewrite.createMoveTarget(selectedExpression);
- ASTNode replacement= createTempDeclaration(initializer); // creates a VariableDeclarationStatement
-
- ExpressionStatement parent= (ExpressionStatement) selectedExpression.getParent();
- if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) {
- Block block= rewrite.getAST().newBlock();
- block.statements().add(replacement);
- replacement= block;
-
- }
- rewrite.replace(parent, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable));
- }
-
- public void setDeclareFinal(boolean declareFinal) {
- fDeclareFinal= declareFinal;
- }
-
- public void setReplaceAllOccurrences(boolean replaceAllOccurrences) {
- fReplaceAllOccurrences= replaceAllOccurrences;
- }
-
- public void setTempName(String newName) {
- fTempName= newName;
- }
-
- private boolean shouldReplaceSelectedExpressionWithTempDeclaration() throws JavaScriptModelException {
- IExpressionFragment selectedFragment= getSelectedExpression();
- return selectedFragment.getAssociatedNode().getParent() instanceof ExpressionStatement
- && selectedFragment.matches(ASTFragmentFactory.createFragmentForFullSubtree(selectedFragment.getAssociatedNode()));
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.EXTRACT_LOCAL_VARIABLE);
- else
- fCu= (IJavaScriptUnit) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fTempName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplaceAllOccurrences= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- final String declareFinal= extended.getAttribute(ATTRIBUTE_FINAL);
- if (declareFinal != null) {
- fDeclareFinal= Boolean.valueOf(declareFinal).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FINAL));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineConstantRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineConstantRefactoring.java
deleted file mode 100644
index b90ee414..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineConstantRefactoring.java
+++ /dev/null
@@ -1,970 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ImportReferencesCollector;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IExpressionFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.IRefactoringSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TightSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class InlineConstantRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
- private static final String ATTRIBUTE_REMOVE= "remove"; //$NON-NLS-1$
-
- private static class InlineTargetCompilationUnit {
-
- private static class InitializerTraversal extends HierarchicalASTVisitor {
-
- private static boolean areInSameType(ASTNode one, ASTNode other) {
- ASTNode onesContainer= getContainingTypeDeclaration(one);
- ASTNode othersContainer= getContainingTypeDeclaration(other);
-
- if (onesContainer == null || othersContainer == null)
- return false;
-
- ITypeBinding onesContainerBinding= getTypeBindingForTypeDeclaration(onesContainer);
- ITypeBinding othersContainerBinding= getTypeBindingForTypeDeclaration(othersContainer);
-
- Assert.isNotNull(onesContainerBinding);
- Assert.isNotNull(othersContainerBinding);
-
- String onesKey= onesContainerBinding.getKey();
- String othersKey= othersContainerBinding.getKey();
-
- if (onesKey == null || othersKey == null)
- return false;
-
- return onesKey.equals(othersKey);
- }
-
- private static boolean isStaticAccess(SimpleName memberName) {
- IBinding binding= memberName.resolveBinding();
- Assert.isTrue(binding instanceof IVariableBinding || binding instanceof IFunctionBinding || binding instanceof ITypeBinding);
-
- if (binding instanceof ITypeBinding)
- return true;
-
- if (binding instanceof IVariableBinding)
- return ((IVariableBinding) binding).isField();
-
- int modifiers= binding.getModifiers();
- return Modifier.isStatic(modifiers);
- }
-
- private static ASTNode getContainingTypeDeclaration(ASTNode node) {
- while (node != null && !(node instanceof AbstractTypeDeclaration) && !(node instanceof AnonymousClassDeclaration)) {
- node= node.getParent();
- }
- return node;
- }
-
- private static ITypeBinding getTypeBindingForTypeDeclaration(ASTNode declaration) {
- if (declaration instanceof AnonymousClassDeclaration)
- return ((AnonymousClassDeclaration) declaration).resolveBinding();
-
- if (declaration instanceof AbstractTypeDeclaration)
- return ((AbstractTypeDeclaration) declaration).resolveBinding();
-
- Assert.isTrue(false);
- return null;
- }
-
- private final Expression fInitializer;
- private ASTRewrite fInitializerRewrite;
- private final HashSet fStaticImportsInInitializer2;
-
- // cache:
- private Set fNamesDeclaredLocallyAtNewLocation;
-
- private final Expression fNewLocation;
- private final HashSet fStaticImportsInReference;
- private final CompilationUnitRewrite fNewLocationCuRewrite;
-
- public InitializerTraversal(Expression initializer, HashSet staticImportsInInitializer, Expression newLocation, HashSet staticImportsInReference, CompilationUnitRewrite newLocationCuRewrite) {
- fInitializer= initializer;
- fInitializerRewrite= ASTRewrite.create(initializer.getAST());
- fStaticImportsInInitializer2= staticImportsInInitializer;
-
- fNewLocation= newLocation;
- fStaticImportsInReference= staticImportsInReference;
- fNewLocationCuRewrite= newLocationCuRewrite;
-
- perform(initializer);
- }
-
- /**
- * @param scope not a TypeDeclaration
- * @return Set containing Strings representing simple names
- */
- private Set getLocallyDeclaredNames(BodyDeclaration scope) {
- Assert.isTrue(!(scope instanceof AbstractTypeDeclaration));
-
- final Set result= new HashSet();
-
- if (scope instanceof FieldDeclaration)
- return result;
-
- scope.accept(new HierarchicalASTVisitor() {
-
- public boolean visit(AbstractTypeDeclaration node) {
- Assert.isTrue(node.getParent() instanceof TypeDeclarationStatement);
-
- result.add(node.getName().getIdentifier());
- return false;
- }
-
- public boolean visit(AnonymousClassDeclaration anonDecl) {
- return false;
- }
-
- public boolean visit(VariableDeclaration varDecl) {
- result.add(varDecl.getName().getIdentifier());
- return false;
- }
- });
- return result;
- }
-
- public ASTRewrite getInitializerRewrite() {
- return fInitializerRewrite;
- }
-
- private void perform(Expression initializer) {
- initializer.accept(this);
- if (initializer instanceof FunctionInvocation || initializer instanceof SuperMethodInvocation) {
- addExplicitTypeArgumentsIfNecessary(initializer);
- }
- }
-
- private void addExplicitTypeArgumentsIfNecessary(Expression invocation) {
- if (Invocations.isResolvedTypeInferredFromExpectedType(invocation)) {
- ASTNode referenceContext= fNewLocation.getParent();
- if (! (referenceContext instanceof VariableDeclarationFragment
- || referenceContext instanceof SingleVariableDeclaration
- || referenceContext instanceof Assignment)) {
- Invocations.resolveBinding(invocation);
- }
- }
- }
-
- public boolean visit(FieldAccess fieldAccess) {
- fieldAccess.getExpression().accept(this);
- return false;
- }
-
- public boolean visit(FunctionInvocation invocation) {
- if (invocation.getExpression() == null)
- qualifyUnqualifiedMemberNameIfNecessary(invocation.getName());
- else
- invocation.getExpression().accept(this);
-
- for (Iterator it= invocation.arguments().iterator(); it.hasNext();)
- ((Expression) it.next()).accept(this);
-
- return false;
- }
-
- public boolean visit(Name name) {
- SimpleName leftmost= getLeftmost(name);
-
- IBinding leftmostBinding= leftmost.resolveBinding();
- if (leftmostBinding instanceof IVariableBinding || leftmostBinding instanceof IFunctionBinding || leftmostBinding instanceof ITypeBinding) {
- if (shouldUnqualify(leftmost))
- unqualifyMemberName(leftmost);
- else
- qualifyUnqualifiedMemberNameIfNecessary(leftmost);
- }
-
- if (leftmostBinding instanceof ITypeBinding) {
- String addedImport= fNewLocationCuRewrite.getImportRewrite().addImport((ITypeBinding) leftmostBinding);
- fNewLocationCuRewrite.getImportRemover().registerAddedImport(addedImport);
- }
-
- return false;
- }
-
- private void qualifyUnqualifiedMemberNameIfNecessary(SimpleName memberName) {
- if (shouldQualify(memberName))
- qualifyMemberName(memberName);
- }
-
- private boolean shouldUnqualify(SimpleName memberName) {
- if (areInSameType(memberName, fNewLocation))
- return ! mayBeShadowedByLocalDeclaration(memberName);
-
- return false;
- }
-
- private void unqualifyMemberName(SimpleName memberName) {
- if (doesParentQualify(memberName))
- fInitializerRewrite.replace(memberName.getParent(), memberName, null);
- }
-
- private boolean shouldQualify(SimpleName memberName) {
- if (! areInSameType(fInitializer, fNewLocation))
- return true;
-
- return mayBeShadowedByLocalDeclaration(memberName);
- }
-
- private boolean mayBeShadowedByLocalDeclaration(SimpleName memberName) {
- return getNamesDeclaredLocallyAtNewLocation().contains(memberName.getIdentifier());
- }
-
- private Set getNamesDeclaredLocallyAtNewLocation() {
- if (fNamesDeclaredLocallyAtNewLocation != null)
- return fNamesDeclaredLocallyAtNewLocation;
-
- BodyDeclaration enclosingBodyDecl= (BodyDeclaration) ASTNodes.getParent(fNewLocation, BodyDeclaration.class);
- Assert.isTrue(!(enclosingBodyDecl instanceof AbstractTypeDeclaration));
-
- return fNamesDeclaredLocallyAtNewLocation= getLocallyDeclaredNames(enclosingBodyDecl);
- }
-
- private void qualifyMemberName(SimpleName memberName) {
- if (isStaticAccess(memberName)) {
- IBinding memberBinding= memberName.resolveBinding();
-
- if (memberBinding instanceof IVariableBinding || memberBinding instanceof IFunctionBinding) {
- if (fStaticImportsInReference.contains(fNewLocation)) { // use static import if reference location used static import
- importStatically(memberName, memberBinding);
- return;
- } else if (fStaticImportsInInitializer2.contains(memberName)) { // use static import if already imported statically in initializer
- importStatically(memberName, memberBinding);
- return;
- }
- }
- qualifyToTopLevelClass(memberName); //otherwise: qualify and import non-static
- }
- }
-
- private void importStatically(SimpleName toImport, IBinding binding) {
- String newName= fNewLocationCuRewrite.getImportRewrite().addStaticImport(binding);
- fNewLocationCuRewrite.getImportRemover().registerAddedStaticImport(binding);
-
- Name newReference= ASTNodeFactory.newName(fInitializerRewrite.getAST(), newName);
- fInitializerRewrite.replace(toImport, newReference, null);
- }
-
- private void qualifyToTopLevelClass(SimpleName toQualify) {
- ITypeBinding declaringClass= getDeclaringClassBinding(toQualify);
- if (declaringClass == null)
- return;
-
- Type newQualification= fNewLocationCuRewrite.getImportRewrite().addImport(declaringClass, fInitializerRewrite.getAST());
- fNewLocationCuRewrite.getImportRemover().registerAddedImports(newQualification);
-
- SimpleName newToQualify= (SimpleName) fInitializerRewrite.createMoveTarget(toQualify);
- Type newType= fInitializerRewrite.getAST().newQualifiedType(newQualification, newToQualify);
- fInitializerRewrite.replace(toQualify, newType, null);
- }
-
- private static ITypeBinding getDeclaringClassBinding(SimpleName memberName) {
-
- IBinding binding= memberName.resolveBinding();
- if (binding instanceof IFunctionBinding)
- return ((IFunctionBinding) binding).getDeclaringClass();
-
- if (binding instanceof IVariableBinding)
- return ((IVariableBinding) binding).getDeclaringClass();
-
- if (binding instanceof ITypeBinding)
- return ((ITypeBinding) binding).getDeclaringClass();
-
- Assert.isTrue(false);
- return null;
-
- }
-
- }
-
- private final Expression fInitializer;
- private final IJavaScriptUnit fInitializerUnit;
- private final VariableDeclarationFragment fOriginalDeclaration;
-
- /** The references in this compilation unit, represented as AST Nodes in the parsed representation of the compilation unit */
- private final Expression[] fReferences;
- private final VariableDeclarationFragment fDeclarationToRemove;
- private final CompilationUnitRewrite fCuRewrite;
- private final TightSourceRangeComputer fSourceRangeComputer;
- private final HashSet fStaticImportsInInitializer;
- private final boolean fIs15;
-
- private InlineTargetCompilationUnit(CompilationUnitRewrite cuRewrite, Name[] references, InlineConstantRefactoring refactoring, HashSet staticImportsInInitializer) throws JavaScriptModelException {
- fInitializer= refactoring.getInitializer();
- fInitializerUnit= refactoring.getDeclaringCompilationUnit();
-
- fCuRewrite= cuRewrite;
- fSourceRangeComputer= new TightSourceRangeComputer();
- fCuRewrite.getASTRewrite().setTargetSourceRangeComputer(fSourceRangeComputer);
- if (refactoring.getRemoveDeclaration() && refactoring.getReplaceAllReferences() && cuRewrite.getCu().equals(fInitializerUnit))
- fDeclarationToRemove= refactoring.getDeclaration();
- else
- fDeclarationToRemove= null;
-
- fOriginalDeclaration= refactoring.getDeclaration();
-
- fReferences= new Expression[references.length];
- for (int i= 0; i < references.length; i++)
- fReferences[i]= getQualifiedReference(references[i]);
-
- fIs15= JavaModelUtil.is50OrHigher(cuRewrite.getCu().getJavaScriptProject());
- fStaticImportsInInitializer= fIs15 ? staticImportsInInitializer : new HashSet(0);
- }
-
- private static Expression getQualifiedReference(Name fieldName) {
- if (doesParentQualify(fieldName))
- return (Expression) fieldName.getParent();
-
- return fieldName;
- }
-
- private static boolean doesParentQualify(Name fieldName) {
- ASTNode parent= fieldName.getParent();
- Assert.isNotNull(parent);
-
- if (parent instanceof FieldAccess && ((FieldAccess) parent).getName() == fieldName)
- return true;
-
- if (parent instanceof QualifiedName && ((QualifiedName) parent).getName() == fieldName)
- return true;
-
- if (parent instanceof FunctionInvocation && ((FunctionInvocation) parent).getName() == fieldName)
- return true;
-
- return false;
- }
-
- public CompilationUnitChange getChange() throws CoreException {
- for (int i= 0; i < fReferences.length; i++)
- inlineReference(fReferences[i]);
-
- removeConstantDeclarationIfNecessary();
-
- return fCuRewrite.createChange();
- }
-
- private void inlineReference(Expression reference) throws CoreException {
- ASTNode importDecl= ASTNodes.getParent(reference, ImportDeclaration.class);
- if (importDecl != null)
- return; // don't inline into static imports
-
- String modifiedInitializer= prepareInitializerForLocation(reference);
- if (modifiedInitializer == null)
- return;
-
- TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.InlineConstantRefactoring_Inline);
- Expression newReference= (Expression) fCuRewrite.getASTRewrite().createStringPlaceholder(modifiedInitializer, reference.getNodeType());
-
- if (fInitializer instanceof ArrayInitializer) {
- ArrayCreation arrayCreation= fCuRewrite.getAST().newArrayCreation();
- ArrayType arrayType= (ArrayType) ASTNodeFactory.newType(fCuRewrite.getAST(), fOriginalDeclaration);
- arrayCreation.setType(arrayType);
-
- ArrayInitializer newArrayInitializer= (ArrayInitializer) fCuRewrite.getASTRewrite().createStringPlaceholder(modifiedInitializer,
- ASTNode.ARRAY_INITIALIZER);
- arrayCreation.setInitializer(newArrayInitializer);
- newReference= arrayCreation;
-
- ITypeBinding typeToAddToImport= ASTNodes.getType(fOriginalDeclaration).resolveBinding();
- fCuRewrite.getImportRewrite().addImport(typeToAddToImport);
- fCuRewrite.getImportRemover().registerAddedImport(typeToAddToImport.getName());
- }
-
- if (shouldParenthesizeSubstitute(fInitializer, reference)) {
- ParenthesizedExpression parenthesized= fCuRewrite.getAST().newParenthesizedExpression();
- parenthesized.setExpression(newReference);
- newReference= parenthesized;
- }
- fCuRewrite.getASTRewrite().replace(reference, newReference, msg);
- fSourceRangeComputer.addTightSourceNode(reference);
- fCuRewrite.getImportRemover().registerRemovedNode(reference);
- }
-
- private String prepareInitializerForLocation(Expression location) throws CoreException {
- HashSet staticImportsInReference= new HashSet();
- final IJavaScriptProject project= fCuRewrite.getCu().getJavaScriptProject();
- if (fIs15)
- location.accept(new ImportReferencesCollector(project, null, new ArrayList(), staticImportsInReference));
- InitializerTraversal traversal= new InitializerTraversal(fInitializer, fStaticImportsInInitializer, location, staticImportsInReference, fCuRewrite);
- ASTRewrite initializerRewrite= traversal.getInitializerRewrite();
- IDocument document= new Document(fInitializerUnit.getBuffer().getContents()); // could reuse document when generating and applying undo edits
-
- final RangeMarker marker= new RangeMarker(fInitializer.getStartPosition(), fInitializer.getLength());
- TextEdit[] rewriteEdits= initializerRewrite.rewriteAST(document, fInitializerUnit.getJavaScriptProject().getOptions(true)).removeChildren();
- marker.addChildren(rewriteEdits);
- try {
- marker.apply(document, TextEdit.UPDATE_REGIONS);
- String rewrittenInitializer= document.get(marker.getOffset(), marker.getLength());
- IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
- int oldIndent= Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project);
- return Strings.changeIndent(rewrittenInitializer, oldIndent, project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- return fInitializerUnit.getBuffer().getText(fInitializer.getStartPosition(), fInitializer.getLength());
- }
-
- private static boolean shouldParenthesizeSubstitute(Expression substitute, Expression location) {
- if (substitute instanceof Assignment) // for esthetic reasons
- return true;
- else
- return ASTNodes.substituteMustBeParenthesized(substitute, location);
- }
-
- private void removeConstantDeclarationIfNecessary() throws CoreException {
- if (fDeclarationToRemove == null)
- return;
-
- FieldDeclaration parentDeclaration= (FieldDeclaration) fDeclarationToRemove.getParent();
- ASTNode toRemove;
- if (parentDeclaration.fragments().size() == 1)
- toRemove= parentDeclaration;
- else
- toRemove= fDeclarationToRemove;
-
- TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.InlineConstantRefactoring_remove_declaration);
- fCuRewrite.getASTRewrite().remove(toRemove, msg);
- fCuRewrite.getImportRemover().registerRemovedNode(toRemove);
- }
- }
-
- // ---- End InlineTargetCompilationUnit ----------------------------------------------------------------------------------------------
-
- private static SimpleName getLeftmost(Name name) {
- if (name instanceof SimpleName)
- return (SimpleName) name;
-
- return getLeftmost(((QualifiedName) name).getQualifier());
- }
-
- private int fSelectionStart;
- private int fSelectionLength;
-
- private IJavaScriptUnit fSelectionCu;
- private CompilationUnitRewrite fSelectionCuRewrite;
- private Name fSelectedConstantName;
-
- private IField fField;
- private CompilationUnitRewrite fDeclarationCuRewrite;
- private VariableDeclarationFragment fDeclaration;
- private boolean fDeclarationSelected;
- private boolean fDeclarationSelectedChecked= false;
- private boolean fInitializerAllStaticFinal;
- private boolean fInitializerChecked= false;
-
- private boolean fRemoveDeclaration= false;
- private boolean fReplaceAllReferences= true;
-
- private CompilationUnitChange[] fChanges;
-
- /**
- * Creates a new inline constant refactoring.
- * <p>
- * This constructor is only used by <code>DelegateCreator</code>.
- * </p>
- *
- * @param field the field to inline
- */
- public InlineConstantRefactoring(IField field) {
- Assert.isNotNull(field);
- Assert.isTrue(!field.isBinary());
- fField= field;
- }
-
- /**
- * Creates a new inline constant refactoring.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param node the compilation unit node, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public InlineConstantRefactoring(IJavaScriptUnit unit, JavaScriptUnit node, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionCu= unit;
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- if (unit != null)
- initialize(unit, node);
- }
-
- private void initialize(IJavaScriptUnit cu, JavaScriptUnit node) {
- fSelectionCuRewrite= new CompilationUnitRewrite(cu, node);
- fSelectedConstantName= findConstantNameNode();
- }
-
- private Name findConstantNameNode() {
- ASTNode node= NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
- if (node == null)
- return null;
- if (node instanceof FieldAccess)
- node= ((FieldAccess) node).getName();
- if (!(node instanceof Name))
- return null;
- Name name= (Name) node;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return null;
- IVariableBinding variableBinding= (IVariableBinding) binding;
- if (!variableBinding.isField())
- return null;
- int modifiers= binding.getModifiers();
- if (! (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
- return null;
-
- return name;
- }
-
- public RefactoringStatus checkStaticFinalConstantNameSelected() {
- if (fSelectedConstantName == null)
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_static_final_field, null, Corext.getPluginId(), RefactoringStatusCodes.NOT_STATIC_FINAL_SELECTED, null);
-
- return new RefactoringStatus();
- }
-
- public String getName() {
- return RefactoringCoreMessages.InlineConstantRefactoring_name;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 3); //$NON-NLS-1$
-
- if (!fSelectionCu.isStructureKnown())
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_syntax_errors, null, Corext.getPluginId(), RefactoringStatusCodes.SYNTAX_ERRORS, null);
-
- RefactoringStatus result= checkStaticFinalConstantNameSelected();
- if (result.hasFatalError())
- return result;
-
- result.merge(findField());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- result.merge(findDeclaration());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- result.merge(checkInitializer());
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- return result;
-
- } finally {
- pm.done();
- }
- }
-
- private RefactoringStatus findField() throws JavaScriptModelException {
- fField= (IField) ((IVariableBinding) fSelectedConstantName.resolveBinding()).getJavaElement();
- if (fField != null && ! fField.exists())
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_local_anonymous_unsupported, null, Corext.getPluginId(), RefactoringStatusCodes.LOCAL_AND_ANONYMOUS_NOT_SUPPORTED, null);
-
- return null;
- }
- private RefactoringStatus findDeclaration() throws JavaScriptModelException {
- fDeclarationSelectedChecked= true;
- fDeclarationSelected= false;
- ASTNode parent= fSelectedConstantName.getParent();
- if (parent instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment parentDeclaration= (VariableDeclarationFragment) parent;
- if (parentDeclaration.getName() == fSelectedConstantName) {
- fDeclarationSelected= true;
- fDeclarationCuRewrite= fSelectionCuRewrite;
- fDeclaration= (VariableDeclarationFragment) fSelectedConstantName.getParent();
- return null;
- }
- }
-
- VariableDeclarationFragment declaration= (VariableDeclarationFragment) fSelectionCuRewrite.getRoot().findDeclaringNode(fSelectedConstantName.resolveBinding());
- if (declaration != null) {
- fDeclarationCuRewrite= fSelectionCuRewrite;
- fDeclaration= declaration;
- return null;
- }
-
- if (fField.getJavaScriptUnit() == null)
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_binary_file, null, Corext.getPluginId(), RefactoringStatusCodes.DECLARED_IN_CLASSFILE, null);
-
- fDeclarationCuRewrite= new CompilationUnitRewrite(fField.getJavaScriptUnit());
- fDeclaration= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(fField, fDeclarationCuRewrite.getRoot());
- return null;
- }
-
- private RefactoringStatus checkInitializer() {
- Expression initializer= getInitializer();
- if (initializer == null)
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.InlineConstantRefactoring_blank_finals, null, Corext.getPluginId(), RefactoringStatusCodes.CANNOT_INLINE_BLANK_FINAL, null);
-
- fInitializerAllStaticFinal= ConstantChecks.isStaticFinalConstant((IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(initializer));
- fInitializerChecked= true;
- return new RefactoringStatus();
- }
-
- private VariableDeclarationFragment getDeclaration() throws JavaScriptModelException {
- return fDeclaration;
- }
-
- private Expression getInitializer() {
- return fDeclaration.getInitializer();
- }
-
- private IJavaScriptUnit getDeclaringCompilationUnit() throws JavaScriptModelException {
- return fField.getJavaScriptUnit();
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- pm.beginTask("", 3); //$NON-NLS-1$
-
- try {
- List/*<CompilationUnitChange>*/changes= new ArrayList();
- HashSet staticImportsInInitializer= new HashSet();
- ImportReferencesCollector importReferencesCollector= new ImportReferencesCollector(fField.getJavaScriptProject(), null, new ArrayList(), staticImportsInInitializer);
- getInitializer().accept(importReferencesCollector);
-
- if (getReplaceAllReferences()) {
- SearchResultGroup[] searchResultGroups= findReferences(pm, result);
- for (int i= 0; i < searchResultGroups.length; i++) {
- if (pm.isCanceled())
- throw new OperationCanceledException();
- SearchResultGroup group= searchResultGroups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
-
- CompilationUnitRewrite cuRewrite= getCuRewrite(cu);
- Name[] references= extractReferenceNodes(group.getSearchResults(), cuRewrite.getRoot());
- InlineTargetCompilationUnit targetCompilationUnit= new InlineTargetCompilationUnit(
- cuRewrite, references, this, staticImportsInInitializer);
- changes.add(targetCompilationUnit.getChange());
- }
-
- } else {
- Assert.isTrue(! isDeclarationSelected());
- InlineTargetCompilationUnit targetForOnlySelectedReference= new InlineTargetCompilationUnit(
- fSelectionCuRewrite, new Name[] { fSelectedConstantName }, this, staticImportsInInitializer);
- changes.add(targetForOnlySelectedReference.getChange());
- }
-
- if (result.hasFatalError())
- return result;
-
- if (getRemoveDeclaration() && getReplaceAllReferences()) {
- boolean declarationRemoved= false;
- for (Iterator iter= changes.iterator(); iter.hasNext();) {
- CompilationUnitChange change= (CompilationUnitChange) iter.next();
- if (change.getCompilationUnit().equals(fDeclarationCuRewrite.getCu())) {
- declarationRemoved= true;
- break;
- }
- }
- if (! declarationRemoved) {
- InlineTargetCompilationUnit targetForDeclaration= new InlineTargetCompilationUnit(fDeclarationCuRewrite, new Name[0], this, staticImportsInInitializer);
- CompilationUnitChange change= targetForDeclaration.getChange();
- if (change != null)
- changes.add(change);
- }
- }
-
- IJavaScriptUnit[] cus= new IJavaScriptUnit[changes.size()];
- for (int i= 0; i < changes.size(); i++) {
- CompilationUnitChange change= (CompilationUnitChange) changes.get(i);
- cus[i]= change.getCompilationUnit();
- }
- result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(cus), getValidationContext()));
-
- pm.worked(1);
-
- fChanges= (CompilationUnitChange[]) changes.toArray(new CompilationUnitChange[changes.size()]);
-
- return result;
-
- } finally {
- fSelectionCuRewrite= null;
- fSelectedConstantName= null;
- fDeclarationCuRewrite= null;
- fDeclaration= null;
- pm.done();
- }
- }
-
- private Name[] extractReferenceNodes(SearchMatch[] searchResults, JavaScriptUnit cuNode) {
- Name[] references= new Name[searchResults.length];
- for (int i= 0; i < searchResults.length; i++)
- references[i]= (Name) NodeFinder.perform(cuNode, searchResults[i].getOffset(), searchResults[i].getLength());
- return references;
- }
-
- private CompilationUnitRewrite getCuRewrite(IJavaScriptUnit cu) {
- CompilationUnitRewrite cuRewrite;
- if (cu.equals(fSelectionCu)) {
- cuRewrite= fSelectionCuRewrite;
- } else if (cu.equals(fField.getJavaScriptUnit())) {
- cuRewrite= fDeclarationCuRewrite;
- } else {
- cuRewrite= new CompilationUnitRewrite(cu);
- }
- return cuRewrite;
- }
-
- private SearchResultGroup[] findReferences(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fField, IJavaScriptSearchConstants.REFERENCES));
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(fField));
- engine.setStatus(status);
- engine.setRequestor(new IRefactoringSearchRequestor() {
- public SearchMatch acceptSearchMatch(SearchMatch match) {
- return match.isInsideDocComment() ? null : match;
- }
- });
- engine.searchPattern(new SubProgressMonitor(pm, 1));
- return (SearchResultGroup[]) engine.getResults();
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.InlineConstantRefactoring_preview, 2);
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fSelectionCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- try {
- if (!Flags.isPrivate(fField.getFlags()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.InlineConstantRefactoring_descriptor_description_short, fField.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.InlineConstantRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fField, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fField.getParent(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.InlineConstantRefactoring_original_pattern, JavaScriptElementLabels.getElementLabel(fField, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- if (fRemoveDeclaration)
- comment.addSetting(RefactoringCoreMessages.InlineConstantRefactoring_remove_declaration);
- if (fReplaceAllReferences)
- comment.addSetting(RefactoringCoreMessages.InlineConstantRefactoring_replace_references);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.INLINE_CONSTANT, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fSelectionCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_REMOVE, Boolean.valueOf(fRemoveDeclaration).toString());
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllReferences).toString());
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.InlineConstantRefactoring_inline, fChanges);
- } finally {
- pm.done();
- fChanges= null;
- }
- }
-
- private void checkInvariant() {
- if (isDeclarationSelected())
- Assert.isTrue(fReplaceAllReferences);
- }
-
- public boolean getRemoveDeclaration() {
- return fRemoveDeclaration;
- }
-
- public boolean getReplaceAllReferences() {
- checkInvariant();
- return fReplaceAllReferences;
- }
-
- public boolean isDeclarationSelected() {
- Assert.isTrue(fDeclarationSelectedChecked);
- return fDeclarationSelected;
- }
-
- public boolean isInitializerAllStaticFinal() {
- Assert.isTrue(fInitializerChecked);
- return fInitializerAllStaticFinal;
- }
-
- public void setRemoveDeclaration(boolean removeDeclaration) {
- fRemoveDeclaration= removeDeclaration;
- }
-
- public void setReplaceAllReferences(boolean replaceAllReferences) {
- fReplaceAllReferences= replaceAllReferences;
- checkInvariant();
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- }
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- return createInputFatalStatus(element, IJavaScriptRefactorings.INLINE_CONSTANT);
- else {
- if (element instanceof IJavaScriptUnit) {
- fSelectionCu= (IJavaScriptUnit) element;
- if (selection == null)
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- } else if (element instanceof IField) {
- final IField field= (IField) element;
- try {
- final ISourceRange range= field.getNameRange();
- if (range != null) {
- fSelectionStart= range.getOffset();
- fSelectionLength= range.getLength();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, IJavaScriptRefactorings.INLINE_CONSTANT));
- } catch (JavaScriptModelException exception) {
- return createInputFatalStatus(element, IJavaScriptRefactorings.INLINE_CONSTANT);
- }
- fSelectionCu= field.getJavaScriptUnit();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}));
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setSource(fSelectionCu);
- final JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(null);
- initialize(fSelectionCu, unit);
- if (checkStaticFinalConstantNameSelected().hasFatalError())
- return createInputFatalStatus(element, IJavaScriptRefactorings.INLINE_CONSTANT);
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplaceAllReferences= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- final String remove= extended.getAttribute(ATTRIBUTE_REMOVE);
- if (remove != null)
- fRemoveDeclaration= Boolean.valueOf(remove).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REMOVE));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineMethodRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
deleted file mode 100644
index e3db73e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
+++ /dev/null
@@ -1,566 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for:
- * o inline call that is used in a field initializer
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38137)
- * o Allow 'this' constructor to be inlined
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/*
- * Open items:
- * - generate import statements for newly generated local variable declarations.
- * - forbid cases like foo(foo(10)) when inlining foo().
- * - case ref.foo(); and we want to inline foo. Inline a method in a different context;
- * - optimize code when the method to be inlined returns an argument and that one is
- * assigned to a parameter again. No need for a separate local (important to be able
- * to reverse extract method correctly).
- */
-public class InlineMethodRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_MODE= "mode"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DELETE= "delete"; //$NON-NLS-1$
-
- public static class Mode {
- private Mode() {
- }
- public static final Mode INLINE_ALL= new Mode();
- public static final Mode INLINE_SINGLE= new Mode();
- }
-
- private ITypeRoot fInitialTypeRoot;
- private ASTNode fInitialNode;
- private TextChangeManager fChangeManager;
- private SourceProvider fSourceProvider;
- private TargetProvider fTargetProvider;
- /**
- * must never be true if fInitialUnit instanceof IClassFile
- */
- private boolean fDeleteSource;
- private Mode fCurrentMode;
- private Mode fInitialMode;
- private int fSelectionStart;
- private int fSelectionLength;
-
- private InlineMethodRefactoring(ITypeRoot typeRoot, ASTNode node, int offset, int length) {
- Assert.isNotNull(typeRoot);
- Assert.isTrue(JavaElementUtil.isSourceAvailable(typeRoot));
- Assert.isNotNull(node);
- fInitialTypeRoot= typeRoot;
- fInitialNode= node;
- fSelectionStart= offset;
- fSelectionLength= length;
- }
-
- private InlineMethodRefactoring(IJavaScriptUnit unit, FunctionInvocation node, int offset, int length) {
- this(unit, (ASTNode)node, offset, length);
- fTargetProvider= TargetProvider.create(unit, node);
- fInitialMode= fCurrentMode= Mode.INLINE_SINGLE;
- fDeleteSource= false;
- }
-
- private InlineMethodRefactoring(IJavaScriptUnit unit, SuperMethodInvocation node, int offset, int length) {
- this(unit, (ASTNode)node, offset, length);
- fTargetProvider= TargetProvider.create(unit, node);
- fInitialMode= fCurrentMode= Mode.INLINE_SINGLE;
- fDeleteSource= false;
- }
-
- private InlineMethodRefactoring(IJavaScriptUnit unit, ConstructorInvocation node, int offset, int length) {
- this(unit, (ASTNode)node, offset, length);
- fTargetProvider= TargetProvider.create(unit, node);
- fInitialMode= fCurrentMode= Mode.INLINE_SINGLE;
- fDeleteSource= false;
- }
-
- private InlineMethodRefactoring(ITypeRoot typeRoot, FunctionDeclaration node, int offset, int length) {
- this(typeRoot, (ASTNode)node, offset, length);
- fSourceProvider= new SourceProvider(typeRoot, node);
- fTargetProvider= TargetProvider.create(node);
- fInitialMode= fCurrentMode= Mode.INLINE_ALL;
- fDeleteSource= canEnableDeleteSource();
- }
-
- /**
- * Creates a new inline method refactoring
- * @param unit the compilation unit or class file
- * @param node the compilation unit node
- * @param selectionStart
- * @param selectionLength
- */
- public static InlineMethodRefactoring create(ITypeRoot unit, JavaScriptUnit node, int selectionStart, int selectionLength) {
- ASTNode target= getTargetNode(unit, node, selectionStart, selectionLength);
- if (target == null)
- return null;
- if (target.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
-
- return new InlineMethodRefactoring(unit, (FunctionDeclaration)target, selectionStart, selectionLength);
- } else {
- IJavaScriptUnit cu= (IJavaScriptUnit) unit;
- if (target.getNodeType() == ASTNode.FUNCTION_INVOCATION) {
- return new InlineMethodRefactoring(cu, (FunctionInvocation)target, selectionStart, selectionLength);
- } else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
- return new InlineMethodRefactoring(cu, (SuperMethodInvocation)target, selectionStart, selectionLength);
- } else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
- return new InlineMethodRefactoring(cu, (ConstructorInvocation)target, selectionStart, selectionLength);
- }
- }
- return null;
- }
-
- public String getName() {
- return RefactoringCoreMessages.InlineMethodRefactoring_name;
- }
-
- public boolean canEnableDeleteSource() {
- return ! (fSourceProvider.getTypeRoot() instanceof IClassFile);
- }
-
- public boolean getDeleteSource() {
- return fDeleteSource;
- }
-
- public void setDeleteSource(boolean remove) {
- if (remove)
- Assert.isTrue(canEnableDeleteSource());
- fDeleteSource= remove;
- }
-
- public Mode getInitialMode() {
- return fInitialMode;
- }
-
- public RefactoringStatus setCurrentMode(Mode mode) throws JavaScriptModelException {
- if (fCurrentMode == mode)
- return new RefactoringStatus();
- Assert.isTrue(getInitialMode() == Mode.INLINE_SINGLE);
- fCurrentMode= mode;
- if (mode == Mode.INLINE_SINGLE) {
- if (fInitialNode instanceof FunctionInvocation)
- fTargetProvider= TargetProvider.create((IJavaScriptUnit) fInitialTypeRoot, (FunctionInvocation)fInitialNode);
- else if (fInitialNode instanceof SuperMethodInvocation)
- fTargetProvider= TargetProvider.create((IJavaScriptUnit) fInitialTypeRoot, (SuperMethodInvocation)fInitialNode);
- else if (fInitialNode instanceof ConstructorInvocation)
- fTargetProvider= TargetProvider.create((IJavaScriptUnit) fInitialTypeRoot, (ConstructorInvocation)fInitialNode);
- else
- throw new IllegalStateException(String.valueOf(fInitialNode));
- } else {
- fTargetProvider= TargetProvider.create(fSourceProvider.getDeclaration());
- }
- return fTargetProvider.checkActivation();
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- if (fSourceProvider == null && Invocations.isInvocation(fInitialNode)) {
- fSourceProvider= resolveSourceProvider(result, fInitialTypeRoot, fInitialNode);
- if (result.hasFatalError())
- return result;
- }
- fTargetProvider.setSourceProvider(fSourceProvider);
- result.merge(fSourceProvider.checkActivation());
- result.merge(fTargetProvider.checkActivation());
- return result;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 20); //$NON-NLS-1$
- fChangeManager= new TextChangeManager();
- RefactoringStatus result= new RefactoringStatus();
- fSourceProvider.initialize();
- fTargetProvider.initialize();
- pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
- RefactoringStatus searchStatus= new RefactoringStatus();
- IJavaScriptUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, new SubProgressMonitor(pm, 1));
- if (searchStatus.hasFatalError()) {
- result.merge(searchStatus);
- return result;
- }
- IFile[] filesToBeModified= getFilesToBeModified(units);
- result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
- if (result.hasFatalError())
- return result;
- result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
- checkOverridden(result, new SubProgressMonitor(pm, 4));
- IProgressMonitor sub= new SubProgressMonitor(pm, 15);
- sub.beginTask("", units.length * 3); //$NON-NLS-1$
- for (int c= 0; c < units.length; c++) {
- IJavaScriptUnit unit= units[c];
- sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, unit.getElementName()));
- CallInliner inliner= null;
- try {
- boolean added= false;
- MultiTextEdit root= new MultiTextEdit();
- CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
- change.setEdit(root);
- BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
- if (bodies.length == 0)
- continue;
- inliner= new CallInliner(unit, (JavaScriptUnit) bodies[0].getRoot(), fSourceProvider);
- for (int b= 0; b < bodies.length; b++) {
- BodyDeclaration body= bodies[b];
- inliner.initialize(body);
- RefactoringStatus nestedInvocations= new RefactoringStatus();
- ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
- fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
- for (int i= 0; i < invocations.length; i++) {
- ASTNode invocation= invocations[i];
- result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
- if (result.hasFatalError())
- break;
- if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
- added= true;
- TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
- change.addTextEditGroup(group);
- result.merge(inliner.perform(group));
- } else {
- fDeleteSource= false;
- }
- }
- // do this after we have inlined the method calls. We still want
- // to generate the modifications.
- if (!nestedInvocations.isOK()) {
- result.merge(nestedInvocations);
- fDeleteSource= false;
- }
- }
- if (!added) {
- fChangeManager.remove(unit);
- } else {
- root.addChild(inliner.getModifications());
- ImportRewrite rewrite= inliner.getImportEdit();
- if (rewrite.hasRecordedChanges()) {
- TextEdit edit= rewrite.rewriteImports(null);
- if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
- root.addChild(edit);
- change.addTextEditGroup(
- new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
- }
- }
- }
- } finally {
- if (inliner != null)
- inliner.dispose();
- }
- sub.worked(1);
- if (sub.isCanceled())
- throw new OperationCanceledException();
- }
- result.merge(searchStatus);
- sub.done();
- pm.done();
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- if (fDeleteSource && fCurrentMode == Mode.INLINE_ALL) {
- TextChange change= fChangeManager.get((IJavaScriptUnit) fSourceProvider.getTypeRoot());
- TextEdit delete= fSourceProvider.getDeleteEdit();
- TextEditGroup description= new TextEditGroup(
- RefactoringCoreMessages.InlineMethodRefactoring_edit_delete, new TextEdit[] { delete });
- TextEdit root= change.getEdit();
- if (root != null) {
- // TODO instead of finding the right insert position the call inliner should
- // reuse the AST & rewriter of the source provide and we should rewrite the
- // whole AST at the end. However, since recursive calls aren't allowed there
- // shouldn't be a text edit overlap.
- // root.addChild(delete);
- TextChangeCompatibility.insert(root, delete);
- } else {
- change.setEdit(delete);
- }
- change.addTextEditGroup(description);
- }
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fInitialTypeRoot.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- final IFunctionBinding binding= fSourceProvider.getDeclaration().resolveBinding();
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (!Modifier.isPrivate(binding.getModifiers()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- final String description= Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_descriptor_description_short, binding.getName());
- final String header= Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- if (fDeleteSource)
- comment.addSetting(RefactoringCoreMessages.InlineMethodRefactoring_remove_method);
- if (fCurrentMode == Mode.INLINE_ALL)
- comment.addSetting(RefactoringCoreMessages.InlineMethodRefactoring_replace_references);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.INLINE_METHOD, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fInitialTypeRoot));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_DELETE, Boolean.valueOf(fDeleteSource).toString());
- arguments.put(ATTRIBUTE_MODE, new Integer(fCurrentMode == Mode.INLINE_ALL ? 1 : 0).toString());
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.InlineMethodRefactoring_edit_inlineCall, fChangeManager.getAllChanges());
- }
-
- private static SourceProvider resolveSourceProvider(RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) throws JavaScriptModelException {
- JavaScriptUnit root= (JavaScriptUnit)invocation.getRoot();
- IFunctionBinding methodBinding= Invocations.resolveBinding(invocation);
- if (methodBinding == null) {
- status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
- return null;
- }
- FunctionDeclaration declaration= (FunctionDeclaration)root.findDeclaringNode(methodBinding);
- if (declaration != null) {
- return new SourceProvider(typeRoot, declaration);
- }
- IFunction method= (IFunction)methodBinding.getJavaElement();
- if (method != null) {
- JavaScriptUnit methodDeclarationAstRoot;
- IJavaScriptUnit methodCu= method.getJavaScriptUnit();
- if (methodCu != null) {
- methodDeclarationAstRoot= new RefactoringASTParser(AST.JLS3).parse(methodCu, true);
- } else {
- IClassFile classFile= method.getClassFile();
- if (! JavaElementUtil.isSourceAvailable(classFile)) {
- String methodLabel= JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.M_PARAMETER_TYPES);
- status.addFatalError(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel));
- return null;
- }
- methodDeclarationAstRoot= new RefactoringASTParser(AST.JLS3).parse(classFile, true);
- }
- ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey());
- if (node instanceof FunctionDeclaration) {
- return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (FunctionDeclaration) node);
- }
- }
- status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
- return null;
- }
-
- private static ASTNode getTargetNode(ITypeRoot typeRoot, JavaScriptUnit root, int offset, int length) {
- ASTNode node= null;
- try {
- node= checkNode(NodeFinder.perform(root, offset, length, typeRoot), typeRoot);
- } catch(JavaScriptModelException e) {
- // Do nothing
- }
- if (node != null)
- return node;
- return checkNode(NodeFinder.perform(root, offset, length), typeRoot);
- }
-
- private static ASTNode checkNode(ASTNode node, IJavaScriptElement unit) {
- if (node == null)
- return null;
- if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
- node= node.getParent();
- } else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
- node= ((ExpressionStatement)node).getExpression();
- }
- switch(node.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- return node;
- case ASTNode.FUNCTION_INVOCATION:
- case ASTNode.SUPER_METHOD_INVOCATION:
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return unit instanceof IJavaScriptUnit ? node : null; // don't start on invocations in binary
- }
- return null;
- }
-
- private IFile[] getFilesToBeModified(IJavaScriptUnit[] units) {
- List result= new ArrayList(units.length + 1);
- IFile file;
- for (int i= 0; i < units.length; i++) {
- file= getFile(units[i]);
- if (file != null)
- result.add(file);
- }
- if (fDeleteSource) {
- file= getFile((IJavaScriptUnit) fSourceProvider.getTypeRoot());
- if (file != null && !result.contains(file))
- result.add(file);
- }
- return (IFile[])result.toArray(new IFile[result.size()]);
- }
-
- private IFile getFile(IJavaScriptUnit unit) {
- unit= unit.getPrimary();
- IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE)
- return (IFile)resource;
- return null;
- }
-
- private void checkOverridden(RefactoringStatus status, IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 9); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
- FunctionDeclaration decl= fSourceProvider.getDeclaration();
- IFunction method= (IFunction) decl.resolveBinding().getJavaElement();
- if (method == null || Flags.isPrivate(method.getFlags())) {
- pm.worked(8);
- return;
- }
- IType type= method.getDeclaringType();
- if (type==null) {
- pm.worked(8);
- return;
- }
- ITypeHierarchy hierarchy= type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
- checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
- checkSuperClasses(status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
- pm.setTaskName(""); //$NON-NLS-1$
- }
-
- private void checkSubTypes(RefactoringStatus result, IFunction method, IType[] types, IProgressMonitor pm) {
- checkTypes(
- result, method, types,
- RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden_error,
- pm);
- }
-
- private void checkSuperClasses(RefactoringStatus result, IFunction method, IType[] types, IProgressMonitor pm) {
- checkTypes(
- result, method, types,
- RefactoringCoreMessages.InlineMethodRefactoring_checking_overrides_error,
- pm);
- }
- private void checkTypes(RefactoringStatus result, IFunction method, IType[] types, String key, IProgressMonitor pm) {
- pm.beginTask("", types.length); //$NON-NLS-1$
- for (int i= 0; i < types.length; i++) {
- pm.worked(1);
- IFunction[] overridden= types[i].findMethods(method);
- if (overridden != null && overridden.length > 0) {
- result.addError(
- Messages.format(key, types[i].getElementName()),
- JavaStatusContext.create(overridden[0]));
- }
- }
- }
-
- private ASTNode[] removeNestedCalls(RefactoringStatus status, IJavaScriptUnit unit, ASTNode[] invocations) {
- if (invocations.length <= 1)
- return invocations;
- ASTNode[] parents= new ASTNode[invocations.length];
- for (int i= 0; i < invocations.length; i++) {
- parents[i]= invocations[i].getParent();
- }
- for (int i= 0; i < invocations.length; i++) {
- removeNestedCalls(status, unit, parents, invocations, i);
- }
- List result= new ArrayList();
- for (int i= 0; i < invocations.length; i++) {
- if (invocations[i] != null)
- result.add(invocations[i]);
- }
- return (ASTNode[])result.toArray(new ASTNode[result.size()]);
- }
-
- private void removeNestedCalls(RefactoringStatus status, IJavaScriptUnit unit, ASTNode[] parents, ASTNode[] invocations, int index) {
- ASTNode invocation= invocations[index];
- for (int i= 0; i < parents.length; i++) {
- ASTNode parent= parents[i];
- while (parent != null) {
- if (parent == invocation) {
- status.addError(RefactoringCoreMessages.InlineMethodRefactoring_nestedInvocation,
- JavaStatusContext.create(unit, parent));
- invocations[index]= null;
- }
- parent= parent.getParent();
- }
- }
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments generic= (JavaRefactoringArguments) arguments;
- final String delete= generic.getAttribute(ATTRIBUTE_DELETE);
- if (delete != null) {
- fDeleteSource= Boolean.valueOf(delete).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE));
- final String value= generic.getAttribute(ATTRIBUTE_MODE);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- int mode= 0;
- try {
- mode= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MODE));
- }
- try {
- setCurrentMode(mode == 1 ? Mode.INLINE_ALL : Mode.INLINE_SINGLE);
- } catch (JavaScriptModelException exception) {
- return RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage());
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineTempRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineTempRefactoring.java
deleted file mode 100644
index 3fd11604..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/InlineTempRefactoring.java
+++ /dev/null
@@ -1,437 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TempDeclarationFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TempOccurrenceAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class InlineTempRefactoring extends ScriptableRefactoring {
-
- private int fSelectionStart;
- private int fSelectionLength;
- private IJavaScriptUnit fCu;
-
- //the following fields are set after the construction
- private VariableDeclaration fVariableDeclaration;
- private SimpleName[] fReferences;
- private JavaScriptUnit fASTRoot;
-
- /**
- * Creates a new inline constant refactoring.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param node compilation unit node, or <code>null</code>
- * @param selectionStart
- * @param selectionLength
- */
- public InlineTempRefactoring(IJavaScriptUnit unit, JavaScriptUnit node, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= unit;
-
- fASTRoot= node;
- fVariableDeclaration= null;
- }
-
- /**
- * Creates a new inline constant refactoring.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public InlineTempRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
- this(unit, null, selectionStart, selectionLength);
- }
-
- public InlineTempRefactoring(VariableDeclaration decl) {
- fVariableDeclaration= decl;
- ASTNode astRoot= decl.getRoot();
- Assert.isTrue(astRoot instanceof JavaScriptUnit);
- fASTRoot= (JavaScriptUnit) astRoot;
- Assert.isTrue(fASTRoot.getJavaElement() instanceof IJavaScriptUnit);
-
- fSelectionStart= decl.getStartPosition();
- fSelectionLength= decl.getLength();
- fCu= (IJavaScriptUnit) fASTRoot.getJavaElement();
- }
-
- public RefactoringStatus checkIfTempSelected() {
- VariableDeclaration decl= getVariableDeclaration();
- if (decl == null) {
- return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, getASTRoot(), RefactoringCoreMessages.InlineTempRefactoring_select_temp);
- }
- if (decl.getParent() instanceof FieldDeclaration) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTemRefactoring_error_message_fieldsCannotBeInlined);
- }
- return new RefactoringStatus();
- }
-
- private JavaScriptUnit getASTRoot() {
- if (fASTRoot == null) {
- fASTRoot= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
- }
- return fASTRoot;
- }
-
- public VariableDeclaration getVariableDeclaration() {
- if (fVariableDeclaration == null) {
- fVariableDeclaration= TempDeclarationFinder.findTempDeclaration(getASTRoot(), fSelectionStart, fSelectionLength);
- }
- return fVariableDeclaration;
- }
-
- /*
- * @see IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.InlineTempRefactoring_name;
- }
-
- /*
- * @see Refactoring#checkActivation(IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 1); //$NON-NLS-1$
-
- RefactoringStatus result= Checks.validateModifiesFiles(ResourceUtil.getFiles(new IJavaScriptUnit[]{fCu}), getValidationContext());
- if (result.hasFatalError())
- return result;
-
- VariableDeclaration declaration= getVariableDeclaration();
-
- result.merge(checkSelection(declaration));
- if (result.hasFatalError())
- return result;
-
- result.merge(checkInitializer(declaration));
- return result;
- } finally {
- pm.done();
- }
- }
-
- private RefactoringStatus checkInitializer(VariableDeclaration decl) {
- if (decl.getInitializer().getNodeType() == ASTNode.NULL_LITERAL)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTemRefactoring_error_message_nulLiteralsCannotBeInlined);
- return null;
- }
-
- private RefactoringStatus checkSelection(VariableDeclaration decl) {
- ASTNode parent= decl.getParent();
- if (parent instanceof FunctionDeclaration) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_method_parameter);
- }
-
- if (parent instanceof CatchClause) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_exceptions_declared);
- }
-
- if (parent instanceof VariableDeclarationExpression && parent.getLocationInParent() == ForStatement.INITIALIZERS_PROPERTY) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_for_initializers);
- }
-
- if (decl.getInitializer() == null) {
- String message= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_not_initialized, decl.getName().getIdentifier());
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- return checkAssignments(decl);
- }
-
- private RefactoringStatus checkAssignments(VariableDeclaration decl) {
- TempAssignmentFinder assignmentFinder= new TempAssignmentFinder(decl);
- getASTRoot().accept(assignmentFinder);
- if (!assignmentFinder.hasAssignments())
- return new RefactoringStatus();
- ASTNode firstAssignment= assignmentFinder.getFirstAssignment();
- int start= firstAssignment.getStartPosition();
- int length= firstAssignment.getLength();
- ISourceRange range= new SourceRange(start, length);
- RefactoringStatusContext context= JavaStatusContext.create(fCu, range);
- String message= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_assigned_more_once, decl.getName().getIdentifier());
- return RefactoringStatus.createFatalErrorStatus(message, context);
- }
-
- /*
- * @see Refactoring#checkInput(IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 1); //$NON-NLS-1$
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- //----- changes
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.InlineTempRefactoring_preview, 2);
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
-
- final IVariableBinding binding= getVariableDeclaration().resolveBinding();
- String text= null;
- final IFunctionBinding method= binding.getDeclaringMethod();
- if (method != null)
- text= BindingLabelProvider.getBindingLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- else
- text= '{' + JavaScriptElementLabels.ELLIPSIS_STRING + '}';
- final String description= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_descriptor_description_short, binding.getName());
- final String header= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), text});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.InlineTempRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.INLINE_LOCAL_VARIABLE, project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, String.valueOf(fSelectionStart) + ' ' + String.valueOf(fSelectionLength));
-
- CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(fCu, fASTRoot);
-
- inlineTemp(cuRewrite);
- removeTemp(cuRewrite);
-
- final CompilationUnitChange result= cuRewrite.createChange(RefactoringCoreMessages.InlineTempRefactoring_inline, false, new SubProgressMonitor(pm, 1));
- result.setDescriptor(new RefactoringChangeDescriptor(descriptor));
- return result;
- } finally {
- pm.done();
- }
- }
-
- private void inlineTemp(CompilationUnitRewrite cuRewrite) throws JavaScriptModelException {
- SimpleName[] references= getReferences();
-
- TextEditGroup groupDesc= cuRewrite.createGroupDescription(RefactoringCoreMessages.InlineTempRefactoring_inline_edit_name);
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
-
- for (int i= 0; i < references.length; i++){
- SimpleName curr= references[i];
- ASTNode initializerCopy= getInitializerSource(cuRewrite, curr);
- rewrite.replace(curr, initializerCopy, groupDesc);
- }
- }
-
- private boolean needsBrackets(SimpleName name, VariableDeclaration variableDeclaration) {
- Expression initializer= variableDeclaration.getInitializer();
- if (initializer instanceof Assignment) //for esthetic reasons
- return true;
-
- return ASTNodes.substituteMustBeParenthesized(initializer, name);
- }
-
-
- private void removeTemp(CompilationUnitRewrite cuRewrite) throws JavaScriptModelException {
- VariableDeclaration variableDeclaration= getVariableDeclaration();
- TextEditGroup groupDesc= cuRewrite.createGroupDescription(RefactoringCoreMessages.InlineTempRefactoring_remove_edit_name);
- ASTNode parent= variableDeclaration.getParent();
- ASTRewrite rewrite= cuRewrite.getASTRewrite();
- if (parent instanceof VariableDeclarationStatement && ((VariableDeclarationStatement) parent).fragments().size() == 1) {
- rewrite.remove(parent, groupDesc);
- } else {
- rewrite.remove(variableDeclaration, groupDesc);
- }
- }
-
- private Expression getInitializerSource(CompilationUnitRewrite rewrite, SimpleName reference) throws JavaScriptModelException {
- Expression copy= getModifiedInitializerSource(rewrite, reference);
- boolean brackets= needsBrackets(reference, getVariableDeclaration());
- if (brackets) {
- ParenthesizedExpression parentExpr= rewrite.getAST().newParenthesizedExpression();
- parentExpr.setExpression(copy);
- return parentExpr;
- }
- return copy;
- }
-
- private Expression getModifiedInitializerSource(CompilationUnitRewrite rewrite, SimpleName reference) throws JavaScriptModelException {
- VariableDeclaration varDecl= getVariableDeclaration();
- Expression initializer= varDecl.getInitializer();
-
- ASTNode referenceContext= reference.getParent();
- if (isInvocation(initializer)) {
- if (Invocations.isResolvedTypeInferredFromExpectedType(initializer)) {
- if (! (referenceContext instanceof VariableDeclarationFragment
- || referenceContext instanceof SingleVariableDeclaration
- || referenceContext instanceof Assignment)) {
- Invocations.resolveBinding(initializer);
- String newSource= createParameterizedInvocation(initializer, new Type[0]);
- return (Expression) rewrite.getASTRewrite().createStringPlaceholder(newSource, initializer.getNodeType());
- }
- }
- }
-
- Expression copy= (Expression) rewrite.getASTRewrite().createCopyTarget(initializer);
- if (initializer instanceof ArrayInitializer && ASTNodes.getDimensions(varDecl) > 0) {
- ArrayType newType= (ArrayType) ASTNodeFactory.newType(rewrite.getAST(), varDecl);
-
- ArrayCreation newArrayCreation= rewrite.getAST().newArrayCreation();
- newArrayCreation.setType(newType);
- newArrayCreation.setInitializer((ArrayInitializer) copy);
- return newArrayCreation;
- }
- return copy;
- }
-
- private String createParameterizedInvocation(Expression invocation, Type[] typeArgumentNodes) throws JavaScriptModelException {
- ASTRewrite rewrite= ASTRewrite.create(invocation.getAST());
- ListRewrite typeArgsRewrite= rewrite.getListRewrite(invocation, Invocations.getTypeArgumentsProperty(invocation));
- for (int i= 0; i < typeArgumentNodes.length; i++) {
- typeArgsRewrite.insertLast(typeArgumentNodes[i], null);
- }
-
- IDocument document= new Document(fCu.getBuffer().getContents());
- final RangeMarker marker= new RangeMarker(invocation.getStartPosition(), invocation.getLength());
- IJavaScriptProject project= fCu.getJavaScriptProject();
- TextEdit[] rewriteEdits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
- marker.addChildren(rewriteEdits);
- try {
- marker.apply(document, TextEdit.UPDATE_REGIONS);
- String rewrittenInitializer= document.get(marker.getOffset(), marker.getLength());
- IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
- int oldIndent= Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project);
- return Strings.changeIndent(rewrittenInitializer, oldIndent, project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- //fallback:
- return fCu.getBuffer().getText(invocation.getStartPosition(), invocation.getLength());
- }
-
- private static boolean isInvocation(Expression node) {
- return node instanceof FunctionInvocation || node instanceof SuperMethodInvocation;
- }
-
- public SimpleName[] getReferences() {
- if (fReferences != null)
- return fReferences;
- TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(getVariableDeclaration(), false);
- analyzer.perform();
- fReferences= analyzer.getReferenceNodes();
- return fReferences;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INLINE_LOCAL_VARIABLE);
- else {
- fCu= (IJavaScriptUnit) element;
- if (checkIfTempSelected().hasFatalError())
- return createInputFatalStatus(element, IJavaScriptRefactorings.INLINE_LOCAL_VARIABLE);
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
deleted file mode 100644
index 04cfd483..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
+++ /dev/null
@@ -1,1238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ASTCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring class that permits the substitution of a factory method
- * for direct calls to a given constructor.
- * @author rfuhrer
- */
-public class IntroduceFactoryRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_PROTECT= "protect"; //$NON-NLS-1$
-
- /**
- * The handle for the compilation unit holding the selection that was
- * passed into this refactoring.
- */
- private IJavaScriptUnit fCUHandle;
-
- /**
- * The AST for the compilation unit holding the selection that was
- * passed into this refactoring.
- */
- private JavaScriptUnit fCU;
-
- /**
- * Handle for compilation unit in which the factory method/class/interface will be
- * generated.
- */
- private IJavaScriptUnit fFactoryUnitHandle;
-
- /**
- * The start of the original textual selection in effect when this refactoring
- * was initiated. If the refactoring was initiated from a structured selection
- * (e.g. from the outline view), then this refers to the textual selection that
- * corresponds to the structured selection item.
- */
- private int fSelectionStart;
-
- /**
- * The length of the original textual selection in effect when this refactoring
- * was initiated. If the refactoring was initiated from a structured selection
- * (e.g. from the outline view), then this refers to the textual selection that
- * corresponds to the structured selection item.
- */
- private int fSelectionLength;
-
- /**
- * The AST node corresponding to the user's textual selection.
- */
- private ASTNode fSelectedNode;
-
- /**
- * The method binding for the selected constructor.
- */
- private IFunctionBinding fCtorBinding;
-
- /**
- * <code>TypeDeclaration</code> for class containing the constructor to be
- * encapsulated.
- */
- private AbstractTypeDeclaration fCtorOwningClass;
-
- /**
- * The name to be given to the generated factory method.
- */
- private String fNewMethodName= null;
-
- /**
- * An array of <code>SearchResultGroup</code>'s of all call sites
- * that refer to the constructor signature in question.
- */
- private SearchResultGroup[] fAllCallsTo;
-
- /**
- * The class that will own the factory method/class/interface.
- */
- private AbstractTypeDeclaration fFactoryOwningClass;
-
- /**
- * The newly-generated factory method.
- */
- private FunctionDeclaration fFactoryMethod= null;
-
- /**
- * An array containing the names of the constructor's formal arguments,
- * if available, otherwise "arg1" ... "argN".
- */
- private String[] fFormalArgNames= null;
-
- /**
- * An array of <code>ITypeBinding</code>'s that describes the types of
- * the constructor arguments, in order.
- */
- private ITypeBinding[] fArgTypes;
-
- /**
- * True iff the given constructor has a varargs signature.
- */
- private boolean fCtorIsVarArgs;
-
- /**
- * If true, change the visibility of the constructor to protected to better
- * encapsulate it.
- */
- private boolean fProtectConstructor= true;
-
- /**
- * An <code>ImportRewrite</code> that manages imports needed to satisfy
- * newly-introduced type references in the <code>IJavaScriptUnit</code>
- * currently being rewritten during <code>createChange()</code>.
- */
- private ImportRewrite fImportRewriter;
-
- /**
- * True iff there are call sites for the constructor to be encapsulated
- * located in binary classes.
- */
- private boolean fCallSitesInBinaryUnits;
-
- /**
- * <code>JavaScriptUnit</code> in which the factory is to be created.
- */
- private JavaScriptUnit fFactoryCU;
-
- /**
- * The fully qualified name of the factory class. This is only used
- * if invoked from a refactoring script.
- */
- private String fFactoryClassName;
-
- private int fConstructorVisibility= Modifier.PRIVATE;
-
- /**
- * Creates a new <code>IntroduceFactoryRefactoring</code> with the given selection
- * on the given compilation unit.
- * @param cu the <code>IJavaScriptUnit</code> in which the user selection was made, or <code>null</code> if invoked from scripting
- * @param selectionStart the start of the textual selection in <code>cu</code>
- * @param selectionLength the length of the textual selection in <code>cu</code>
- */
- public IntroduceFactoryRefactoring(IJavaScriptUnit cu, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCUHandle= cu;
- if (cu != null)
- initialize();
- }
-
- private void initialize() {
- fCU= ASTCreator.createAST(fCUHandle, null);
- }
-
- /**
- * Finds and returns the <code>ASTNode</code> for the given source text
- * selection, if it is an entire constructor call or the class name portion
- * of a constructor call or constructor declaration, or null otherwise.
- * @param unit The compilation unit in which the selection was made
- * @param offset The textual offset of the start of the selection
- * @param length The length of the selection in characters
- * @return ClassInstanceCreation or FunctionDeclaration
- */
- private ASTNode getTargetNode(IJavaScriptUnit unit, int offset, int length) {
- ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
- if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
- return node;
- if (node.getNodeType() == ASTNode.FUNCTION_DECLARATION && ((FunctionDeclaration)node).isConstructor())
- return node;
- // we have some sub node. Make sure its the right child of the parent
- StructuralPropertyDescriptor location= node.getLocationInParent();
- ASTNode parent= node.getParent();
- if (location == ClassInstanceCreation.TYPE_PROPERTY) {
- return parent;
- } else if (location == FunctionDeclaration.NAME_PROPERTY && ((FunctionDeclaration)parent).isConstructor()) {
- return parent;
- }
- return null;
- }
-
- /**
- * Determines what kind of AST node was selected, and returns an error status
- * if the kind of node is inappropriate for this refactoring.
- * @param pm
- * @return a RefactoringStatus indicating whether the selection is valid
- * @throws JavaScriptModelException
- */
- private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaScriptModelException {
- try {
- pm.beginTask(RefactoringCoreMessages.IntroduceFactory_examiningSelection, 2);
-
- fSelectedNode= getTargetNode(fCUHandle, fSelectionStart, fSelectionLength);
-
- if (fSelectedNode == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_notAConstructorInvocation);
-
- // getTargetNode() must return either a ClassInstanceCreation or a
- // constructor FunctionDeclaration; nothing else.
- if (fSelectedNode instanceof ClassInstanceCreation) {
- ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation)fSelectedNode;
- fCtorBinding= classInstanceCreation.resolveConstructorBinding();
- } else if (fSelectedNode instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration)fSelectedNode;
- fCtorBinding= methodDeclaration.resolveBinding();
- }
-
- if (fCtorBinding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unableToResolveConstructorBinding);
-
- // If this constructor is of a generic type, get the generic version,
- // not some instantiation thereof.
- fCtorBinding= fCtorBinding.getMethodDeclaration();
-
- if (fNewMethodName == null)
- fNewMethodName= "create" + fCtorBinding.getName();//$NON-NLS-1$
-
- pm.worked(1);
-
- // We don't handle constructors of nested types at the moment
- if (fCtorBinding.getDeclaringClass().isNested())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unsupportedNestedTypes);
-
- ITypeBinding ctorType= fCtorBinding.getDeclaringClass();
- IType ctorOwningType= (IType) ctorType.getJavaElement();
-
- if (ctorOwningType.isBinary())
- // Can't modify binary CU; don't know what CU to put factory method
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_constructorInBinaryClass);
-
- // Put the generated factory method inside the type that owns the constructor
- fFactoryUnitHandle= ctorOwningType.getJavaScriptUnit();
- fFactoryCU= getASTFor(fFactoryUnitHandle);
-
- Name ctorOwnerName= (Name) NodeFinder.perform(fFactoryCU, ctorOwningType.getNameRange());
-
- fCtorOwningClass= (AbstractTypeDeclaration) ASTNodes.getParent(ctorOwnerName, AbstractTypeDeclaration.class);
- fFactoryOwningClass= fCtorOwningClass;
-
- pm.worked(1);
-
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.IntroduceFactory_checkingActivation, 1);
-
- if (!fCUHandle.isStructureKnown())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_syntaxError);
-
- return checkSelection(new SubProgressMonitor(pm, 1));
- } finally {
- pm.done();
- }
- }
-
- /**
- * Returns the set of compilation units that will be affected by this
- * particular invocation of this refactoring. This in general includes
- * the class containing the constructor in question, as well as all
- * call sites to the constructor.
- * @return IJavaScriptUnit[]
- */
- private IJavaScriptUnit[] collectAffectedUnits(SearchResultGroup[] searchHits) {
- Collection result= new ArrayList();
- boolean hitInFactoryClass= false;
-
- for(int i=0; i < searchHits.length; i++) {
- SearchResultGroup rg= searchHits[i];
- IJavaScriptUnit icu= rg.getCompilationUnit();
-
- result.add(icu);
- if (icu.equals(fFactoryUnitHandle))
- hitInFactoryClass= true;
- }
- if (!hitInFactoryClass)
- result.add(fFactoryUnitHandle);
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- /**
- * Returns a <code>SearchPattern</code> that finds all calls to the constructor
- * identified by the argument <code>methodBinding</code>.
- */
- private SearchPattern createSearchPattern(IFunction ctor, IFunctionBinding methodBinding) {
- Assert.isNotNull(methodBinding,
- RefactoringCoreMessages.IntroduceFactory_noBindingForSelectedConstructor);
-
- if (ctor != null)
- return SearchPattern.createPattern(ctor, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- else { // perhaps a synthetic method? (but apparently not always... hmmm...)
- // Can't find an IFunction for this method, so build a string pattern instead
- StringBuffer buf= new StringBuffer();
-
- buf.append(methodBinding.getDeclaringClass().getQualifiedName())
- .append("(");//$NON-NLS-1$
- for(int i=0; i < fArgTypes.length; i++) {
- if (i != 0)
- buf.append(","); //$NON-NLS-1$
- buf.append(fArgTypes[i].getQualifiedName());
- }
- buf.append(")"); //$NON-NLS-1$
- return SearchPattern.createPattern(buf.toString(), IJavaScriptSearchConstants.CONSTRUCTOR,
- IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- }
- }
-
- private IJavaScriptSearchScope createSearchScope(IFunction ctor, IFunctionBinding binding) throws JavaScriptModelException {
- if (ctor != null) {
- return RefactoringScopeFactory.create(ctor);
- } else {
- ITypeBinding type= Bindings.getTopLevelType(binding.getDeclaringClass());
- return RefactoringScopeFactory.create(type.getJavaElement());
- }
- }
-
- /**
- * Returns an array of <code>SearchResultGroup</code>'s like the argument,
- * but omitting those groups that have no corresponding compilation unit
- * (i.e. are binary and therefore can't be modified).
- */
- private SearchResultGroup[] excludeBinaryUnits(SearchResultGroup[] groups) {
- Collection/*<SearchResultGroup>*/ result= new ArrayList();
-
- for (int i = 0; i < groups.length; i++) {
- SearchResultGroup rg= groups[i];
- IJavaScriptUnit unit= rg.getCompilationUnit();
-
- if (unit != null) // Ignore hits within a binary unit
- result.add(rg);
- else
- fCallSitesInBinaryUnits= true;
- }
- return (SearchResultGroup[]) result.toArray(new SearchResultGroup[result.size()]);
- }
-
- /**
- * Search for all calls to the given <code>IFunctionBinding</code> in the project
- * that contains the compilation unit <code>fCUHandle</code>.
- * @param methodBinding
- * @param pm
- * @param status
- * @return an array of <code>SearchResultGroup</code>'s that identify the search matches
- * @throws JavaScriptModelException
- */
- private SearchResultGroup[] searchForCallsTo(IFunctionBinding methodBinding, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- IFunction method= (IFunction) methodBinding.getJavaElement();
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(createSearchPattern(method, methodBinding));
- engine.setFiltering(true, true);
- engine.setScope(createSearchScope(method, methodBinding));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(pm, 1));
- return (SearchResultGroup[]) engine.getResults();
- }
-
- /**
- * Returns an array of <code>SearchResultGroup</code>'s containing all method
- * calls in the Java project that invoke the constructor identified by the given
- * <code>IFunctionBinding</code>
- * @param ctorBinding an <code>IFunctionBinding</code> identifying a particular
- * constructor signature to search for
- * @param pm an <code>IProgressMonitor</code> to use during this potentially
- * lengthy operation
- * @param status
- * @return an array of <code>SearchResultGroup</code>'s identifying all
- * calls to the given constructor signature
- */
- private SearchResultGroup[] findAllCallsTo(IFunctionBinding ctorBinding, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- SearchResultGroup[] groups= excludeBinaryUnits(searchForCallsTo(ctorBinding, pm, status));
-
- return groups;
- }
-
- private IType findNonPrimaryType(String fullyQualifiedName, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- SearchPattern p= SearchPattern.createPattern(fullyQualifiedName, IJavaScriptSearchConstants.TYPE, IJavaScriptSearchConstants.DECLARATIONS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(p);
-
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(fCtorBinding.getJavaElement().getJavaScriptProject()));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(pm, 1));
-
- SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
-
- if (groups.length != 0) {
- for(int i= 0; i < groups.length; i++) {
- SearchMatch[] matches= groups[i].getSearchResults();
- for(int j= 0; j < matches.length; j++) {
- if (matches[j].getAccuracy() == SearchMatch.A_ACCURATE)
- return (IType) matches[j].getElement();
- }
- }
- }
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.IntroduceFactory_checking_preconditions, 1);
- RefactoringStatus result= new RefactoringStatus();
-
- if (fFactoryClassName != null)
- result.merge(setFactoryClass(fFactoryClassName));
- if (result.hasFatalError())
- return result;
- fArgTypes= fCtorBinding.getParameterTypes();
- fCtorIsVarArgs= fCtorBinding.isVarargs();
- fAllCallsTo= findAllCallsTo(fCtorBinding, pm, result);
- fFormalArgNames= findCtorArgNames();
-
- IJavaScriptUnit[] affectedFiles= collectAffectedUnits(fAllCallsTo);
- result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(affectedFiles), getValidationContext()));
-
- if (fCallSitesInBinaryUnits)
- result.merge(RefactoringStatus.createWarningStatus(RefactoringCoreMessages.IntroduceFactory_callSitesInBinaryClass));
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- /**
- * Returns an array containing the argument names for the constructor
- * identified by <code>fCtorBinding</code>, if available, or default
- * names if unavailable (e.g. if the constructor resides in a binary unit).
- */
- private String[] findCtorArgNames() {
- int numArgs= fCtorBinding.getParameterTypes().length;
- String[] names= new String[numArgs];
-
- JavaScriptUnit ctorUnit= (JavaScriptUnit) ASTNodes.getParent(fCtorOwningClass, JavaScriptUnit.class);
- FunctionDeclaration ctorDecl= (FunctionDeclaration) ctorUnit.findDeclaringNode(fCtorBinding.getKey());
-
- if (ctorDecl != null) {
- List formalArgs= ctorDecl.parameters();
- int i= 0;
-
- for(Iterator iter= formalArgs.iterator(); iter.hasNext(); i++) {
- SingleVariableDeclaration svd= (SingleVariableDeclaration) iter.next();
-
- names[i]= svd.getName().getIdentifier();
- }
- return names;
- }
-
- // Have no way of getting the formal argument names; just fake it.
- for(int i=0; i < numArgs; i++)
- names[i]= "arg" + (i+1); //$NON-NLS-1$
-
- return names;
- }
-
- /**
- * Creates and returns a new FunctionDeclaration that represents the factory
- * method to be used in place of direct calls to the constructor in question.
- * @param ast An AST used as a factory for various AST nodes
- * @param ctorBinding binding for the constructor being wrapped
- * @param unitRewriter the ASTRewrite to be used
- */
- private FunctionDeclaration createFactoryMethod(AST ast, IFunctionBinding ctorBinding, ASTRewrite unitRewriter) {
- FunctionDeclaration newMethod= ast.newFunctionDeclaration();
- SimpleName newMethodName= ast.newSimpleName(fNewMethodName);
- ClassInstanceCreation newCtorCall= ast.newClassInstanceCreation();
- ReturnStatement ret= ast.newReturnStatement();
- Block body= ast.newBlock();
- List stmts= body.statements();
- String retTypeName= ctorBinding.getName();
-
- createFactoryMethodSignature(ast, newMethod);
-
- newMethod.setName(newMethodName);
- newMethod.setBody(body);
-
- setMethodReturnType(newMethod, retTypeName, null, ast);
-
- newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
-
- setCtorTypeArguments(newCtorCall, retTypeName, null, ast);
-
- createFactoryMethodConstructorArgs(ast, newCtorCall);
-
- ret.setExpression(newCtorCall);
- stmts.add(ret);
-
- return newMethod;
- }
-
- /**
- * Sets the type being instantiated in the given constructor call, including
- * specifying any necessary type arguments.
- * @param newCtorCall the constructor call to modify
- * @param ctorTypeName the simple name of the type being instantiated
- * @param ctorOwnerTypeParameters the formal type parameters of the type being
- * instantiated
- * @param ast utility object used to create AST nodes
- */
- private void setCtorTypeArguments(ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
- if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type
- newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName));
- }
-
- /**
- * Sets the return type of the factory method, including any necessary type
- * arguments. E.g., for constructor <code>Foo()</code> in <code>Foo&lt;T&gt;</code>,
- * the factory method defines a method type parameter <code>&lt;T&gt;</code> and
- * returns a <code>Foo&lt;T&gt;</code>.
- * @param newMethod the method whose return type is to be set
- * @param retTypeName the simple name of the return type (without type parameters)
- * @param ctorOwnerTypeParameters the formal type parameters of the type that the
- * factory method instantiates (whose constructor is being encapsulated)
- * @param ast utility object used to create AST nodes
- */
- private void setMethodReturnType(FunctionDeclaration newMethod, String retTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
- if (ctorOwnerTypeParameters.length == 0)
- newMethod.setReturnType2(ast.newSimpleType(ast.newSimpleName(retTypeName)));
- }
-
- /**
- * Creates and adds the necessary argument declarations to the given factory method.<br>
- * An argument is needed for each original constructor argument for which the
- * evaluation of the actual arguments across all calls was not able to be
- * pushed inside the factory method (e.g. arguments with side-effects, references
- * to fields if the factory method is to be static or reside in a factory class,
- * or arguments that varied across the set of constructor calls).<br>
- * <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
- * @param ast utility object used to create AST nodes
- * @param newMethod the <code>FunctionDeclaration</code> for the factory method
- */
- private void createFactoryMethodSignature(AST ast, FunctionDeclaration newMethod) {
- List argDecls= newMethod.parameters();
-
- for(int i=0; i < fArgTypes.length; i++) {
- SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
- Type argType;
-
- if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
- // The trailing varargs arg has an extra array dimension, compared to
- // what we need to pass to setType()...
- argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
- fArgTypes[i].getDimensions()-1, ast);
- argDecl.setVarargs(true);
- } else
- argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);
-
- argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
- argDecl.setType(argType);
- argDecls.add(argDecl);
- }
- }
-
- /**
- * Returns a Type that describes the given ITypeBinding. If the binding
- * refers to an object type, use the import rewriter to determine whether
- * the reference requires a new import, or instead needs to be qualified.<br>
- * Like ASTNodeFactory.newType(), but for the handling of imports.
- * @param extraDims number of extra array dimensions to add to the resulting type
- */
- private Type typeNodeForTypeBinding(ITypeBinding argType, int extraDims, AST ast) {
- if (extraDims > 0) {
- return ast.newArrayType(typeNodeForTypeBinding(argType, 0, ast), extraDims);
-
- } else if (argType.isArray()) {
- Type elementType= typeNodeForTypeBinding(argType.getElementType(), extraDims, ast);
- return ast.newArrayType(elementType, argType.getDimensions());
-
- } else {
- return fImportRewriter.addImport(argType, ast);
- }
- }
-
- /**
- * Create the list of actual arguments to the constructor call that is
- * encapsulated inside the factory method, and associate the arguments
- * with the given constructor call object.
- * @param ast utility object used to create AST nodes
- * @param newCtorCall the newly-generated constructor call to be wrapped inside
- * the factory method
- */
- private void createFactoryMethodConstructorArgs(AST ast, ClassInstanceCreation newCtorCall) {
- List argList= newCtorCall.arguments();
-
- for(int i=0; i < fArgTypes.length; i++) {
- ASTNode ctorArg= ast.newSimpleName(fFormalArgNames[i]);
-
- argList.add(ctorArg);
- }
- }
-
- /**
- * Creates and returns a new FunctionInvocation node to represent a call to
- * the factory method that replaces a direct constructor call.<br>
- * The original constructor call is marked as replaced by the new method
- * call with the ASTRewrite instance fCtorCallRewriter.
- * @param ast utility object used to create AST nodes
- * @param ctorCall the ClassInstanceCreation to be marked as replaced
- */
- private FunctionInvocation createFactoryMethodCall(AST ast, ClassInstanceCreation ctorCall,
- ASTRewrite unitRewriter, TextEditGroup gd) {
- FunctionInvocation factoryMethodCall= ast.newFunctionInvocation();
-
- List actualFactoryArgs= factoryMethodCall.arguments();
- List actualCtorArgs= ctorCall.arguments();
-
- // Need to use a qualified name for the factory method if we're not
- // in the context of the class holding the factory.
- AbstractTypeDeclaration callOwner= (AbstractTypeDeclaration) ASTNodes.getParent(ctorCall, AbstractTypeDeclaration.class);
- ITypeBinding callOwnerBinding= callOwner.resolveBinding();
-
- if (callOwnerBinding == null ||
- !Bindings.equals(callOwner.resolveBinding(), fFactoryOwningClass.resolveBinding())) {
- String qualifier= fImportRewriter.addImport(fFactoryOwningClass.resolveBinding());
- factoryMethodCall.setExpression(ASTNodeFactory.newName(ast, qualifier));
- }
-
- factoryMethodCall.setName(ast.newSimpleName(fNewMethodName));
-
- for(int i=0; i < actualCtorArgs.size(); i++) {
- Expression actualCtorArg= (Expression) actualCtorArgs.get(i);
- ASTNode movedArg= unitRewriter.createMoveTarget(actualCtorArg);
-
- actualFactoryArgs.add(movedArg);
-// unitRewriter.createMove(actualCtorArg);
-// ASTNode rewrittenArg= rewriteArgument(actualCtorArg);
-// actualFactoryArgs.add(rewrittenArg);
- }
-
- unitRewriter.replace(ctorCall, factoryMethodCall, gd);
-
- return factoryMethodCall;
- }
-
- /**
- * Returns true iff the given <code>IJavaScriptUnit</code> is the unit
- * containing the original constructor.
- * @param unit
- */
- private boolean isConstructorUnit(IJavaScriptUnit unit) {
- return unit.equals(ASTCreator.getCu(fCtorOwningClass));
- }
-
- /**
- * Returns true iff we should actually change the original constructor's
- * visibility to <code>protected</code>. This takes into account the user-
- * requested mode and whether the constructor's compilation unit is in
- * source form.
- */
- private boolean shouldProtectConstructor() {
- return fProtectConstructor && fCtorOwningClass != null;
- }
-
- /**
- * Creates and adds the necessary change to make the constructor method protected.
- * Returns false iff the constructor didn't exist (i.e. was implicit)
- */
- private boolean protectConstructor(JavaScriptUnit unitAST, ASTRewrite unitRewriter, TextEditGroup declGD) {
- FunctionDeclaration constructor= (FunctionDeclaration) unitAST.findDeclaringNode(fCtorBinding.getKey());
-
- // No need to rewrite the modifiers if the visibility is what we already want it to be.
- if (constructor == null || (JdtFlags.getVisibilityCode(constructor)) == fConstructorVisibility)
- return false;
- ModifierRewrite.create(unitRewriter, constructor).setVisibility(fConstructorVisibility, declGD);
- return true;
- }
-
- /**
- * Add all changes necessary on the <code>IJavaScriptUnit</code> in the given
- * <code>SearchResultGroup</code> to implement the refactoring transformation
- * to the given <code>CompilationUnitChange</code>.
- * @param rg the <code>SearchResultGroup</code> for which changes should be created
- * @param unitChange the CompilationUnitChange object for the compilation unit in question
- * @throws CoreException
- */
- private boolean addAllChangesFor(SearchResultGroup rg, IJavaScriptUnit unitHandle, CompilationUnitChange unitChange) throws CoreException {
-// IJavaScriptUnit unitHandle= rg.getCompilationUnit();
- Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
- JavaScriptUnit unit= getASTFor(unitHandle);
- ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST());
- MultiTextEdit root= new MultiTextEdit();
- boolean someChange= false;
-
- unitChange.setEdit(root);
- fImportRewriter= StubUtility.createImportRewrite(unit, true);
-
- // First create the factory method
- if (unitHandle.equals(fFactoryUnitHandle)) {
- TextEditGroup factoryGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);
-
- createFactoryChange(unitRewriter, unit, factoryGD);
- unitChange.addTextEditGroup(factoryGD);
- someChange= true;
- }
-
- // Now rewrite all the constructor calls to use the factory method
- if (rg != null)
- if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
- someChange= true;
-
- // Finally, make the constructor private, if requested.
- if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
- TextEditGroup declGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);
-
- if (protectConstructor(unit, unitRewriter, declGD)) {
- unitChange.addTextEditGroup(declGD);
- someChange= true;
- }
- }
-
- if (someChange) {
- root.addChild(unitRewriter.rewriteAST());
- root.addChild(fImportRewriter.rewriteImports(null));
- }
-
- return someChange;
- }
-
- /**
- * Returns an AST for the given compilation unit handle.<br>
- * If this is the unit containing the selection or the unit in which the factory
- * is to reside, checks the appropriate field (<code>fCU</code> or <code>fFactoryCU</code>,
- * respectively) and initializes the field with a new AST only if not already done.
- */
- private JavaScriptUnit getASTFor(IJavaScriptUnit unitHandle) {
- if (unitHandle.equals(fCUHandle)) { // is this the unit containing the selection?
- if (fCU == null) {
- fCU= ASTCreator.createAST(unitHandle, null);
- if (fCU.equals(fFactoryUnitHandle)) // if selection unit and factory unit are the same...
- fFactoryCU= fCU; // ...make sure the factory unit gets initialized
- }
- return fCU;
- } else if (unitHandle.equals(fFactoryUnitHandle)) { // is this the "factory unit"?
- if (fFactoryCU == null)
- fFactoryCU= ASTCreator.createAST(unitHandle, null);
- return fFactoryCU;
- } else
- return ASTCreator.createAST(unitHandle, null);
- }
-
- /**
- * Use the given <code>ASTRewrite</code> to replace direct calls to the constructor
- * with calls to the newly-created factory method.
- * @param rg the <code>SearchResultGroup</code> indicating all of the constructor references
- * @param unit the <code>JavaScriptUnit</code> to be rewritten
- * @param unitRewriter the rewriter
- * @param unitChange the compilation unit change
- * @throws CoreException
- * @return true iff at least one constructor call site was rewritten.
- */
- private boolean replaceConstructorCalls(SearchResultGroup rg, JavaScriptUnit unit,
- ASTRewrite unitRewriter, CompilationUnitChange unitChange)
- throws CoreException {
- Assert.isTrue(ASTCreator.getCu(unit).equals(rg.getCompilationUnit()));
- SearchMatch[] hits= rg.getSearchResults();
- AST ctorCallAST= unit.getAST();
- boolean someCallPatched= false;
-
- for(int i=0; i < hits.length; i++) {
- ClassInstanceCreation creation= getCtorCallAt(hits[i].getOffset(), hits[i].getLength(), unit);
-
- if (creation != null) {
- TextEditGroup gd= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_replaceCalls);
-
- createFactoryMethodCall(ctorCallAST, creation, unitRewriter, gd);
- unitChange.addTextEditGroup(gd);
- someCallPatched= true;
- }
- }
- return someCallPatched;
- }
-
- /**
- * Look "in the vicinity" of the given range to find the <code>ClassInstanceCreation</code>
- * node that this search hit identified. Necessary because the <code>SearchEngine</code>
- * doesn't always cough up text extents that <code>NodeFinder.perform()</code> agrees with.
- * @param start
- * @param length
- * @param unitAST
- * @return may return null if this is really a constructor->constructor call (e.g. "this(...)")
- */
- private ClassInstanceCreation getCtorCallAt(int start, int length, JavaScriptUnit unitAST) throws CoreException {
- IJavaScriptUnit unitHandle= ASTCreator.getCu(unitAST);
- ASTNode node= NodeFinder.perform(unitAST, start, length);
-
- if (node == null)
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
- Messages.format(RefactoringCoreMessages.IntroduceFactory_noASTNodeForConstructorSearchHit,
- new Object[] { Integer.toString(start), Integer.toString(start + length),
- unitHandle.getSource().substring(start, start + length),
- unitHandle.getElementName() }),
- null));
-
- if (node instanceof ClassInstanceCreation) {
- return (ClassInstanceCreation) node;
- } else if (node instanceof VariableDeclaration) {
- Expression init= ((VariableDeclaration) node).getInitializer();
-
- if (init instanceof ClassInstanceCreation) {
- return (ClassInstanceCreation) init;
- } else if (init != null)
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
- Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedInitializerNodeType,
- new Object[] { init.toString(), unitHandle.getElementName() }),
- null));
- else
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
- Messages.format(RefactoringCoreMessages.IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl,
- new Object[] { node.toString() }),
- null));
- } else if (node instanceof ConstructorInvocation) {
- // This is a call we can bypass; it's from one constructor flavor
- // to another flavor on the same class.
- return null;
- } else if (node instanceof SuperConstructorInvocation) {
- // This is a call we can bypass; it's from one constructor flavor
- // to another flavor on the same class.
- fConstructorVisibility= Modifier.PROTECTED;
- return null;
- } else if (node instanceof ExpressionStatement) {
- Expression expr= ((ExpressionStatement) node).getExpression();
-
- if (expr instanceof ClassInstanceCreation)
- return (ClassInstanceCreation) expr;
- else
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
- Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit,
- new Object[] { expr.toString(), unitHandle.getElementName() }),
- null));
- } else if (node instanceof SimpleName && (node.getParent() instanceof FunctionDeclaration || node.getParent() instanceof AbstractTypeDeclaration)) {
- // We seem to have been given a hit for an implicit call to the base-class constructor.
- // Do nothing with this (implicit) call, but have to make sure we make the derived class
- // doesn't lose access to the base-class constructor (so make it 'protected', not 'private').
- fConstructorVisibility= Modifier.PROTECTED;
- return null;
- } else
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
- Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit,
- new Object[] { node.getClass().getName() + "('" + node.toString() + "')", unitHandle.getElementName() }), //$NON-NLS-1$ //$NON-NLS-2$
- null));
- }
-
- /**
- * Perform the AST rewriting necessary on the given <code>JavaScriptUnit</code>
- * to create the factory method. The method will reside on the type identified by
- * <code>fFactoryOwningClass</code>.
- * @param unitRewriter
- * @param unit
- * @param gd the <code>GroupDescription</code> to associate with the changes made
- */
- private void createFactoryChange(ASTRewrite unitRewriter, JavaScriptUnit unit, TextEditGroup gd) {
- // ================================================================================
- // First add the factory itself (method, class, and interface as needed/directed by user)
- AST ast= unit.getAST();
-
- fFactoryMethod= createFactoryMethod(ast, fCtorBinding, unitRewriter);
-
- AbstractTypeDeclaration factoryOwner= (AbstractTypeDeclaration) unit.findDeclaringNode(fFactoryOwningClass.resolveBinding().getKey());
- fImportRewriter.addImport(fCtorOwningClass.resolveBinding());
-
- int idx= ASTNodes.getInsertionIndex(fFactoryMethod, factoryOwner.bodyDeclarations());
-
- if (idx < 0) idx= 0; // Guard against bug in getInsertionIndex()
- unitRewriter.getListRewrite(factoryOwner, factoryOwner.getBodyDeclarationsProperty()).insertAt(fFactoryMethod, idx, gd);
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.IntroduceFactory_createChanges, fAllCallsTo.length);
- final ITypeBinding binding= fFactoryOwningClass.resolveBinding();
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCUHandle.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- if (binding.isNested() && !binding.isMember())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- final String description= Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_descriptor_description_short, fCtorOwningClass.getName());
- final String header= Messages.format(RefactoringCoreMessages.IntroduceFactory_descriptor_description, new String[] { fNewMethodName, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(fCtorBinding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(fCtorBinding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_factory_pattern, fNewMethodName));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_owner_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- if (fProtectConstructor)
- comment.addSetting(RefactoringCoreMessages.IntroduceFactoryRefactoring_declare_private);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.INTRODUCE_FACTORY, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCUHandle));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fNewMethodName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1, descriptor.elementToHandle(binding.getJavaElement()));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_PROTECT, Boolean.valueOf(fProtectConstructor).toString());
- final DynamicValidationStateChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.IntroduceFactory_name);
- boolean hitInFactoryClass= false;
- boolean hitInCtorClass= false;
- for (int i= 0; i < fAllCallsTo.length; i++) {
- SearchResultGroup rg= fAllCallsTo[i];
- IJavaScriptUnit unitHandle= rg.getCompilationUnit();
- CompilationUnitChange cuChange= new CompilationUnitChange(getName(), unitHandle);
-
- if (addAllChangesFor(rg, unitHandle, cuChange))
- result.add(cuChange);
-
- if (unitHandle.equals(fFactoryUnitHandle))
- hitInFactoryClass= true;
- if (unitHandle.equals(ASTCreator.getCu(fCtorOwningClass)))
- hitInCtorClass= true;
-
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- if (!hitInFactoryClass) { // Handle factory class if no search hits there
- CompilationUnitChange cuChange= new CompilationUnitChange(getName(), fFactoryUnitHandle);
- addAllChangesFor(null, fFactoryUnitHandle, cuChange);
- result.add(cuChange);
- }
- if (!hitInCtorClass && !fFactoryUnitHandle.equals(ASTCreator.getCu(fCtorOwningClass))) { // Handle constructor-owning class if no search hits there
- CompilationUnitChange cuChange= new CompilationUnitChange(getName(), ASTCreator.getCu(fCtorOwningClass));
- addAllChangesFor(null, ASTCreator.getCu(fCtorOwningClass), cuChange);
- result.add(cuChange);
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.IntroduceFactory_name;
- }
-
- /**
- * Returns the name to be used for the generated factory method.
- */
- public String getNewMethodName() {
- return fNewMethodName;
- }
-
- /**
- * Sets the name to be used for the generated factory method.<br>
- * Returns a <code>RefactoringStatus</code> that indicates whether the
- * given name is valid for the new factory method.
- * @param newMethodName the name to be used for the generated factory method
- */
- public RefactoringStatus setNewMethodName(String newMethodName) {
- Assert.isNotNull(newMethodName);
- fNewMethodName = newMethodName;
-
- RefactoringStatus stat= Checks.checkMethodName(newMethodName);
-
- stat.merge(isUniqueMethodName(newMethodName));
-
- return stat;
- }
-
- /**
- * Returns a <code>RefactoringStatus</code> that identifies whether the
- * the name <code>newMethodName</code> is available to use as the name of
- * the new factory method within the factory-owner class (either a to-be-
- * created factory class or the constructor-owning class, depending on the
- * user options).
- * @param methodName
- */
- private RefactoringStatus isUniqueMethodName(String methodName) {
- boolean conflict= hasMethod(fFactoryOwningClass, methodName);
-
- return conflict ? RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceFactory_duplicateMethodName + methodName) : new RefactoringStatus();
- }
-
- /**
- * Returns true iff the given <code>AbstractTypeDeclaration</code> has a method with
- * the given name.
- * @param type
- * @param name
- */
- private boolean hasMethod(AbstractTypeDeclaration type, String name) {
- List decls= type.bodyDeclarations();
-
- for (Iterator iter = decls.iterator(); iter.hasNext();) {
- BodyDeclaration decl = (BodyDeclaration) iter.next();
- if (decl instanceof FunctionDeclaration) {
- if (((FunctionDeclaration) decl).getName().getIdentifier().equals(name))
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns true iff the selected constructor can be protected.
- */
- public boolean canProtectConstructor() {
- return fFactoryCU.findDeclaringNode(fCtorBinding.getKey()) != null;
- }
-
- /**
- * If the argument is true, change the visibility of the constructor to
- * <code>protected</code>, thereby encapsulating it.
- * @param protectConstructor
- */
- public void setProtectConstructor(boolean protectConstructor) {
- fProtectConstructor = protectConstructor;
- }
-
- /**
- * Returns the project on behalf of which this refactoring was invoked.
- */
- public IJavaScriptProject getProject() {
- return fCUHandle.getJavaScriptProject();
- }
-
- /**
- * Sets the class on which the generated factory method is to be placed.
- * @param fullyQualifiedTypeName an <code>IType</code> referring to an existing class
- */
- public RefactoringStatus setFactoryClass(String fullyQualifiedTypeName) {
- IType factoryType;
-
- try {
- factoryType= findFactoryClass(fullyQualifiedTypeName);
- if (factoryType == null)
- return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.IntroduceFactory_noSuchClass, fullyQualifiedTypeName));
-
- } catch (JavaScriptModelException e) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_cantCheckForInterface);
- }
-
- IJavaScriptUnit factoryUnitHandle= factoryType.getJavaScriptUnit();
-
- if (factoryType.isBinary())
- return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceFactory_cantPutFactoryInBinaryClass);
- else {
- try {
- if (!fFactoryUnitHandle.equals(factoryUnitHandle)) {
- fFactoryCU= getASTFor(factoryUnitHandle);
- fFactoryUnitHandle= factoryUnitHandle;
- }
- fFactoryOwningClass= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fFactoryCU, factoryType.getNameRange()), AbstractTypeDeclaration.class);
-
- String factoryPkg= factoryType.getPackageFragment().getElementName();
- String ctorPkg= fCtorOwningClass.resolveBinding().getPackage().getName();
-
- if (!factoryPkg.equals(ctorPkg))
- fConstructorVisibility= Modifier.PUBLIC;
- else if (fFactoryOwningClass != fCtorOwningClass)
- fConstructorVisibility= 0; // No such thing as Modifier.PACKAGE...
-
-
- if (fFactoryOwningClass != fCtorOwningClass)
- fConstructorVisibility= 0; // No such thing as Modifier.PACKAGE...
-
- } catch (JavaScriptModelException e) {
- return RefactoringStatus.createFatalErrorStatus(e.getMessage());
- }
- return new RefactoringStatus();
- }
- }
-
- /**
- * Finds the factory class associated with the fully qualified name.
- * @param fullyQualifiedTypeName the fully qualified type name
- * @return the factory class, or <code>null</code> if not found
- * @throws JavaScriptModelException if an error occurs while finding the factory class
- */
- private IType findFactoryClass(String fullyQualifiedTypeName) throws JavaScriptModelException {
- IType factoryType= getProject().findType(fullyQualifiedTypeName);
- if (factoryType == null) // presumably a non-primary type; try the search engine
- factoryType= findNonPrimaryType(fullyQualifiedTypeName, new NullProgressMonitor(), new RefactoringStatus());
- return factoryType;
- }
-
- /**
- * Returns the name of the class on which the generated factory method is
- * to be placed.
- */
- public String getFactoryClassName() {
- return fFactoryOwningClass.resolveBinding().getQualifiedName();
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INTRODUCE_FACTORY);
- else {
- fCUHandle= (IJavaScriptUnit) element;
- initialize();
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INTRODUCE_FACTORY);
- else {
- final IType type= (IType) element;
- fFactoryClassName= type.getFullyQualifiedName();
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fNewMethodName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String protect= extended.getAttribute(ATTRIBUTE_PROTECT);
- if (protect != null) {
- fProtectConstructor= Boolean.valueOf(protect).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_PROTECT));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java
deleted file mode 100644
index 52257a07..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java
+++ /dev/null
@@ -1,1275 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RippleMethodFinder2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- *
- * This refactoring creates a wrapper around a certain method and redirects callers of the original
- * method to the newly created method (called "intermediary method").
- *
- * If invoked on a method call, the user may select whether to only update the selected call or
- * all other calls as well. If invoked on a method declaration, the user may select whether to
- * update calls at all. An intermediary method will be created in both cases.
- *
- * Creating indirections is possible for both source and binary methods. Select an invocation of the method or
- * the declaring method itself, for example in the outline view.
- *
- * Note that in case of methods inside generic types, the parameters of the declaring type of the selected method
- * will be added to the method definition, rendering it generic as well.
- *
- * If any of the calls cannot see the intermediary method due to visibility problems with enclosing types
- * of the intermediary method, visibility will be adjusted. If the intermediary method is not able to
- * see the target method, this refactoring will try to adjust the visibility of the target method and
- * enclosing types as well. However, the latter is only possible if the target method is from source.
- *
- *
- *
- */
-public class IntroduceIndirectionRefactoring extends ScriptableRefactoring {
-
- /**
- * The compilation unit in which the user invoked this refactoring (if any)
- */
- private IJavaScriptUnit fSelectionCompilationUnit;
- /**
- * The class file (with source) in which the user invoked this refactoring (if any)
- */
- private IClassFile fSelectionClassFile;
- /**
- * The start of the user selection inside the selected
- * compilation unit (if any)
- */
- private int fSelectionStart;
- /**
- * The length of the user selection inside the selected
- * compilation unit (if any)
- */
- private int fSelectionLength;
- /**
- * The selected FunctionInvocation (if any). This field is used
- * to update this particular invocation in non-reference mode.
- */
- private FunctionInvocation fSelectionMethodInvocation;
-
- // Intermediary information:
-
- /**
- * The class in which to place the intermediary method
- */
- private IType fIntermediaryClass;
- /**
- * The binding of the intermediary class
- */
- private ITypeBinding fIntermediaryClassBinding;
- /**
- * The name of the intermediary method
- */
- private String fIntermediaryMethodName;
- /**
- * The type for the additional parameter for the intermediary. This
- * type is determined from all known references.
- */
- private ITypeBinding fIntermediaryFirstParameterType;
-
- // Target information:
-
- /**
- * The originally selected target method (i.e., the one to be encapsulated)
- */
- private IFunction fTargetMethod;
- /**
- * The binding of the originally selected target method
- */
- private IFunctionBinding fTargetMethodBinding;
-
- // Other information:
-
- /**
- * If true, all references to the target method are replaced with calls to
- * the intermediary.
- */
- private boolean fUpdateReferences;
- /**
- * CompilationUnitRewrites for all affected cus
- */
- private Map/* <IJavaScriptUnit,CompilationUnitRewrite> */fRewrites;
- /**
- * Text change manager (actually a CompilationUnitChange manager) which
- * manages all changes.
- */
- private TextChangeManager fTextChangeManager;
-
- // Visibility
-
- /**
- * The visibility adjustor
- */
- private MemberVisibilityAdjustor fAdjustor;
- /**
- * Visibility adjustments for the intermediary
- */
- private Map/*IMember, IVisibilityAdjustment*/ fIntermediaryAdjustments;
-
-
- private class NoOverrideProgressMonitor extends SubProgressMonitor {
-
- public NoOverrideProgressMonitor(IProgressMonitor monitor, int ticks) {
- super(monitor, ticks, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- }
-
- public void setTaskName(String name) {
- // do nothing
- }
- }
-
- // ********* CONSTRUCTORS AND CLASS CREATION ************
-
- public IntroduceIndirectionRefactoring(IJavaScriptUnit unit, int offset, int length) {
- fSelectionCompilationUnit= unit;
- initialize(offset, length);
- }
-
- public IntroduceIndirectionRefactoring(IClassFile file, int offset, int length) {
- fSelectionClassFile= file;
- initialize(offset, length);
- }
-
- public IntroduceIndirectionRefactoring(IFunction method) {
- fTargetMethod= method;
- initialize(0, 0);
- }
-
- private void initialize(int offset, int length) {
- fSelectionStart= offset;
- fSelectionLength= length;
- fUpdateReferences= true;
- }
-
- // ********* UI INTERACTION AND STARTUP OPTIONS ************
-
- public String getName() {
- return RefactoringCoreMessages.IntroduceIndirectionRefactoring_introduce_indirection_name;
- }
-
- public IJavaScriptProject getProject() {
- if (fSelectionCompilationUnit != null)
- return fSelectionCompilationUnit.getJavaScriptProject();
- if (fSelectionClassFile != null)
- return fSelectionClassFile.getJavaScriptProject();
- if (fTargetMethod != null)
- return fTargetMethod.getJavaScriptProject();
- return null;
- }
-
- public IPackageFragment getInvocationPackage() {
- return fSelectionCompilationUnit != null ? (IPackageFragment) fSelectionCompilationUnit.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT) : null;
- }
-
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- public void setEnableUpdateReferences(boolean updateReferences) {
- fUpdateReferences= updateReferences;
- }
-
- public RefactoringStatus setIntermediaryMethodName(String newMethodName) {
- Assert.isNotNull(newMethodName);
- fIntermediaryMethodName= newMethodName;
- RefactoringStatus stat= Checks.checkMethodName(newMethodName);
- stat.merge(checkOverloading());
- return stat;
- }
-
- private RefactoringStatus checkOverloading() {
- try {
- if (fIntermediaryClass != null) {
- IFunction[] toCheck= fIntermediaryClass.getFunctions();
- for (int i= 0; i < toCheck.length; i++) {
- IFunction method= toCheck[i];
- if (method.getElementName().equals(fIntermediaryMethodName))
- return RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_duplicate_method_name_in_declaring_class_error,
- fIntermediaryMethodName));
- }
- }
- } catch (JavaScriptModelException e) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_could_not_parse_declaring_class_error);
- }
- return new RefactoringStatus();
- }
-
- public String getIntermediaryMethodName() {
- return fIntermediaryMethodName;
- }
-
- /**
- * @param fullyQualifiedTypeName
- * @return status for type name. Use {@link #setIntermediaryMethodName(String)} to check for overridden methods.
- */
- public RefactoringStatus setIntermediaryClassName(String fullyQualifiedTypeName) {
- IType target= null;
-
- try {
- if (fullyQualifiedTypeName.length() == 0)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_class_not_selected_error);
-
- // find type (now including secondaries)
- target= getProject().findType(fullyQualifiedTypeName, new NullProgressMonitor());
- if (target == null || !target.exists())
- return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_class_does_not_exist_error, fullyQualifiedTypeName));
- } catch (JavaScriptModelException e) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_unable_determine_declaring_type);
- }
-
- if (target.isReadOnly())
- return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_readonly);
-
- if (target.isBinary())
- return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_binary);
-
- fIntermediaryClass= target;
-
- return new RefactoringStatus();
- }
-
- /**
- * Returns the class name of the intermediary class, or the empty string if none has been set yet.
- * @return the intermediary class name or the empty string
- */
- public String getIntermediaryClassName() {
- return fIntermediaryClass != null ? JavaModelUtil.getFullyQualifiedName(fIntermediaryClass) : ""; //$NON-NLS-1$
- }
-
- // ********** CONDITION CHECKING **********
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- try {
- pm.beginTask(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_activation, 1);
- fRewrites= new HashMap();
-
- // This refactoring has been invoked on
- // (1) a TextSelection inside an IJavaScriptUnit or inside an IClassFile (definitely with source), or
- // (2) an IFunction inside a IJavaScriptUnit or inside an IClassFile (with or without source)
-
- if (fTargetMethod == null) {
- // (1) invoked on a text selection
-
- if (fSelectionStart == 0)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
-
- // if a text selection exists, source is available.
- JavaScriptUnit selectionCURoot;
- ASTNode selectionNode;
- if (fSelectionCompilationUnit != null) {
- // compilation unit - could use CuRewrite later on
- selectionCURoot= getCachedCURewrite(fSelectionCompilationUnit).getRoot();
- selectionNode= getSelectedNode(fSelectionCompilationUnit, selectionCURoot, fSelectionStart, fSelectionLength);
- } else {
- // binary class file - no cu rewrite
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setSource(fSelectionClassFile);
- selectionCURoot= (JavaScriptUnit) parser.createAST(null);
- selectionNode= getSelectedNode(null, selectionCURoot, fSelectionStart, fSelectionLength);
- }
-
- if (selectionNode == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
-
- IFunctionBinding targetMethodBinding= null;
-
- if (selectionNode.getNodeType() == ASTNode.FUNCTION_INVOCATION) {
- targetMethodBinding= ((FunctionInvocation) selectionNode).resolveMethodBinding();
- } else if (selectionNode.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- targetMethodBinding= ((FunctionDeclaration) selectionNode).resolveBinding();
- } else if (selectionNode.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
- // Allow invocation on super methods calls. makes sense as other
- // calls or even only the declaration can be updated.
- targetMethodBinding= ((SuperMethodInvocation) selectionNode).resolveMethodBinding();
- } else {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
- }
- fTargetMethodBinding= targetMethodBinding.getMethodDeclaration(); // resolve generics
- fTargetMethod= (IFunction) fTargetMethodBinding.getJavaElement();
-
- //allow single updating mode if an invocation was selected and the invocation can be updated
- if (selectionNode instanceof FunctionInvocation && fSelectionCompilationUnit != null)
- fSelectionMethodInvocation= (FunctionInvocation) selectionNode;
-
- } else {
- // (2) invoked on an IFunction: Source may not be available
-
-// if (fTargetMethod.getDeclaringType().isAnnotation())
-// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_annotation);
-
- if (fTargetMethod.getJavaScriptUnit() != null) {
- // source method
- JavaScriptUnit selectionCURoot= getCachedCURewrite(fTargetMethod.getJavaScriptUnit()).getRoot();
- FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fTargetMethod, selectionCURoot);
- fTargetMethodBinding= declaration.resolveBinding().getMethodDeclaration();
- } else {
- // binary method - no CURewrite available (and none needed as we cannot update the method anyway)
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(fTargetMethod.getJavaScriptProject());
- IBinding[] bindings= parser.createBindings(new IJavaScriptElement[] { fTargetMethod }, null);
- fTargetMethodBinding= ((IFunctionBinding) bindings[0]).getMethodDeclaration();
- }
- }
-
- if (fTargetMethod == null || fTargetMethodBinding == null || (!RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(fTargetMethod)))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
-
-// if (fTargetMethod.getDeclaringType().isLocal() || fTargetMethod.getDeclaringType().isAnonymous())
-// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_local_or_anonymous_types);
-
- if (fTargetMethod.isConstructor())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_constructors);
-
- if (fIntermediaryMethodName == null)
- fIntermediaryMethodName= fTargetMethod.getElementName();
-
- if (fIntermediaryClass == null) {
- if (fSelectionCompilationUnit != null && !fSelectionCompilationUnit.isReadOnly())
- fIntermediaryClass= getEnclosingInitialSelectionMember().getDeclaringType();
- else if (!fTargetMethod.isBinary() && !fTargetMethod.isReadOnly())
- fIntermediaryClass= fTargetMethod.getDeclaringType();
- }
-
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
-
- RefactoringStatus result= new RefactoringStatus();
- fTextChangeManager= new TextChangeManager();
- fIntermediaryFirstParameterType= null;
- fIntermediaryClassBinding= null;
- for (Iterator iter= fRewrites.values().iterator(); iter.hasNext();)
- ((CompilationUnitRewrite) iter.next()).clearASTAndImportRewrites();
-
- int startupTicks= 5;
- int hierarchyTicks= 5;
- int visibilityTicks= 5;
- int referenceTicks= fUpdateReferences ? 30 : 5;
- int creationTicks= 5;
-
- pm.beginTask("", startupTicks + hierarchyTicks + visibilityTicks + referenceTicks + creationTicks); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
-
- result.merge(Checks.checkMethodName(fIntermediaryMethodName));
- if (result.hasFatalError())
- return result;
-
- if (fIntermediaryClass == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_run_without_intermediary_type);
-
- // intermediary class is already non binary/non-enum/non-interface.
- CompilationUnitRewrite imRewrite= getCachedCURewrite(fIntermediaryClass.getJavaScriptUnit());
- fIntermediaryClassBinding= typeToBinding(fIntermediaryClass, imRewrite.getRoot());
-
- fAdjustor= new MemberVisibilityAdjustor(fIntermediaryClass, fIntermediaryClass);
- fIntermediaryAdjustments= new HashMap();
-
- // check static method in non-static nested type
- if (fIntermediaryClassBinding.isNested() && !Modifier.isStatic(fIntermediaryClassBinding.getModifiers()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_nested_nonstatic, JavaStatusContext.create(fIntermediaryClass));
-
- pm.worked(startupTicks);
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- if (fUpdateReferences) {
- pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_looking_for_references); //$NON-NLS-1$
- result.merge(updateReferences(new NoOverrideProgressMonitor(pm, referenceTicks)));
- pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
- } else {
- // only update the declaration and/or a selected method invocation
- if (fSelectionMethodInvocation != null) {
- fIntermediaryFirstParameterType= getExpressionType(fSelectionMethodInvocation);
- final IMember enclosing= getEnclosingInitialSelectionMember();
- // create an edit for this particular call
- result.merge(updateMethodInvocation(fSelectionMethodInvocation, enclosing, getCachedCURewrite(fSelectionCompilationUnit)));
-
- if (!isRewriteKept(fSelectionCompilationUnit))
- createChangeAndDiscardRewrite(fSelectionCompilationUnit);
-
- // does call see the intermediary method?
- // => increase visibility of the type of the intermediary method.
- result.merge(adjustVisibility(fIntermediaryClass, enclosing.getDeclaringType(), new NoOverrideProgressMonitor(pm, 0)));
- }
- pm.worked(referenceTicks);
- }
-
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- if (fIntermediaryFirstParameterType == null)
- fIntermediaryFirstParameterType= fTargetMethodBinding.getDeclaringClass();
-
- // The target type and method may have changed - update them
-
- IType actualTargetType= (IType) fIntermediaryFirstParameterType.getJavaElement();
- if (fTargetMethod.getDeclaringType()==null || !fTargetMethod.getDeclaringType().equals(actualTargetType)) {
- IFunction actualTargetMethod= new MethodOverrideTester(actualTargetType, actualTargetType.newSupertypeHierarchy(null)).findOverriddenMethodInHierarchy(actualTargetType, fTargetMethod);
- fTargetMethod= actualTargetMethod;
- fTargetMethodBinding= findMethodBindingInHierarchy(fIntermediaryFirstParameterType, actualTargetMethod);
- Assert.isNotNull(fTargetMethodBinding);
- }
-
- result.merge(checkCanCreateIntermediaryMethod());
- createIntermediaryMethod();
- pm.worked(creationTicks);
-
- pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_adjusting_visibility); //$NON-NLS-1$
- result.merge(updateTargetVisibility(new NoOverrideProgressMonitor(pm, 0)));
- result.merge(updateIntermediaryVisibility(new NoOverrideProgressMonitor(pm, 0)));
- pm.worked(visibilityTicks);
- pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
-
- createChangeAndDiscardRewrite(fIntermediaryClass.getJavaScriptUnit());
-
- result.merge(Checks.validateModifiesFiles(getAllFilesToModify(), getValidationContext()));
- pm.done();
-
- return result;
- }
-
- private RefactoringStatus updateTargetVisibility(IProgressMonitor monitor) throws JavaScriptModelException, CoreException {
-
- RefactoringStatus result= new RefactoringStatus();
-
- // Adjust the visibility of the method and of the referenced type. Note that
- // the target method may not be in the target type; and in this case, the type
- // of the target method does not need a visibility adjustment.
-
- // This method is called after all other changes have been
- // created. Changes induced by this method will be attached to those changes.
-
- result.merge(adjustVisibility((IType) fIntermediaryFirstParameterType.getJavaElement(), fIntermediaryClass, monitor));
- if (result.hasError())
- return result; // binary
-
- ModifierKeyword neededVisibility= getNeededVisibility(fTargetMethod, fIntermediaryClass);
- if (neededVisibility != null) {
-
- result.merge(adjustVisibility(fTargetMethod, neededVisibility, monitor));
- if (result.hasError())
- return result; // binary
-
- if (fTargetMethod.getDeclaringType()!=null) {
- // Need to adjust the overridden methods of the target method.
- ITypeHierarchy hierarchy = fTargetMethod.getDeclaringType()
- .newTypeHierarchy(null);
- MethodOverrideTester tester = new MethodOverrideTester(
- fTargetMethod.getDeclaringType(), hierarchy);
- IType[] subtypes = hierarchy.getAllSubtypes(fTargetMethod
- .getDeclaringType());
- for (int i = 0; i < subtypes.length; i++) {
- IFunction method = tester.findOverridingMethodInType(
- subtypes[i], fTargetMethod);
- if (method != null && method.exists()) {
- result.merge(adjustVisibility(method, neededVisibility, monitor));
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- if (result.hasError())
- return result; // binary
- }
- }
- }
- }
-
- return result;
- }
-
- private RefactoringStatus updateIntermediaryVisibility(NoOverrideProgressMonitor monitor) throws JavaScriptModelException {
- return rewriteVisibility(fIntermediaryAdjustments, fRewrites, monitor);
- }
-
- private RefactoringStatus updateReferences(IProgressMonitor monitor) throws CoreException {
-
- RefactoringStatus result= new RefactoringStatus();
-
- monitor.beginTask("", 90); //$NON-NLS-1$
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- IFunction[] ripple= RippleMethodFinder2.getRelatedMethods(fTargetMethod, false, new NoOverrideProgressMonitor(monitor, 10), null);
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- SearchResultGroup[] references= Checks.excludeCompilationUnits(getReferences(ripple, new NoOverrideProgressMonitor(monitor, 10), result), result);
-
- if (result.hasFatalError())
- return result;
-
- result.merge(Checks.checkCompileErrorsInAffectedFiles(references));
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- int ticksPerCU= references.length == 0 ? 0 : 70 / references.length;
-
- for (int i= 0; i < references.length; i++) {
- SearchResultGroup group= references[i];
- SearchMatch[] searchResults= group.getSearchResults();
- CompilationUnitRewrite currentCURewrite= getCachedCURewrite(group.getCompilationUnit());
-
- for (int j= 0; j < searchResults.length; j++) {
-
- SearchMatch match= searchResults[j];
- if (match.isInsideDocComment())
- continue;
-
- IMember enclosingMember= (IMember) match.getElement();
- ASTNode target= getSelectedNode(group.getCompilationUnit(), currentCURewrite.getRoot(), match.getOffset(), match.getLength());
-
- if (target instanceof SuperMethodInvocation) {
- // Cannot retarget calls to super - add a warning
- result.merge(createWarningAboutCall(enclosingMember, target, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_super_keyword));
- continue;
- }
-
- Assert.isTrue(target instanceof FunctionInvocation, "Element of call should be a FunctionInvocation."); //$NON-NLS-1$
-
- FunctionInvocation invocation= (FunctionInvocation) target;
- ITypeBinding typeBinding= getExpressionType(invocation);
-
- if (fIntermediaryFirstParameterType == null) {
- // no highest type yet
- fIntermediaryFirstParameterType= typeBinding.getTypeDeclaration();
- } else {
- // check if current type is higher
- result.merge(findCommonParent(typeBinding.getTypeDeclaration()));
- }
-
- if (result.hasFatalError())
- return result;
-
- // create an edit for this particular call
- result.merge(updateMethodInvocation(invocation, enclosingMember, currentCURewrite));
-
- // does call see the intermediary method?
- // => increase visibility of the type of the intermediary method.
- result.merge(adjustVisibility(fIntermediaryClass, enclosingMember.getDeclaringType(), new NoOverrideProgressMonitor(monitor, 0)));
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
-
- if (!isRewriteKept(group.getCompilationUnit()))
- createChangeAndDiscardRewrite(group.getCompilationUnit());
-
- monitor.worked(ticksPerCU);
- }
-
- monitor.done();
- return result;
- }
-
- private RefactoringStatus findCommonParent(ITypeBinding typeBinding) throws JavaScriptModelException {
-
- RefactoringStatus status= new RefactoringStatus();
-
- ITypeBinding highest= fIntermediaryFirstParameterType;
- ITypeBinding current= typeBinding;
-
- if (current.equals(highest) || Bindings.isSuperType(highest, current))
- // current is the same as highest or highest is already a supertype of current in the same hierarchy => no change
- return status;
-
- // find lowest common supertype with the method
- // search in bottom-up order
- ITypeBinding[] currentAndSupers= getTypeAndAllSuperTypes(current);
- ITypeBinding[] highestAndSupers= getTypeAndAllSuperTypes(highest);
-
- ITypeBinding foundBinding= null;
- for (int i1= 0; i1 < currentAndSupers.length; i1++) {
- for (int i2= 0; i2 < highestAndSupers.length; i2++) {
- if (highestAndSupers[i2].isEqualTo(currentAndSupers[i1])
- && (Bindings.findMethodInHierarchy(highestAndSupers[i2], fTargetMethodBinding.getName(), fTargetMethodBinding.getParameterTypes()) != null)) {
- foundBinding= highestAndSupers[i2];
- break;
- }
- }
- if (foundBinding != null)
- break;
- }
-
- if (foundBinding != null) {
- fIntermediaryFirstParameterType= foundBinding;
- } else {
- String type1= fIntermediaryFirstParameterType.getQualifiedName();
- String type2= current.getQualifiedName();
- status.addFatalError(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_open_hierarchy_error, new String[] { type1, type2 }));
- }
-
- return status;
- }
-
- // ******************** CHANGE CREATION ***********************
-
- public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fTargetMethod.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final IType declaring= fTargetMethod.getDeclaringType();
- try {
- if (declaring.isLocal() || declaring.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_descriptor_description_short, fTargetMethod.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getTextLabel(fTargetMethod, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_original_pattern, JavaScriptElementLabels.getTextLabel(fTargetMethod, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_method_pattern, fIntermediaryMethodName));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_declaring_pattern, JavaScriptElementLabels.getTextLabel(fIntermediaryClass, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- if (fUpdateReferences)
- comment.addSetting(RefactoringCoreMessages.JavaRefactoringDescriptor_update_references);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.INTRODUCE_INDIRECTION, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fTargetMethod));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fIntermediaryMethodName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1, descriptor.elementToHandle(fIntermediaryClass));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES, Boolean.valueOf(fUpdateReferences).toString());
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.IntroduceIndirectionRefactoring_introduce_indirection, fTextChangeManager.getAllChanges());
- }
-
- // ******************* CREATE INTERMEDIARY **********************
-
- /**
- * Checks whether the target method can be created. Note that this
- * can only be done after fDelegateParameterType has been initialized.
- * @return resulting status
- * @throws JavaScriptModelException
- */
- private RefactoringStatus checkCanCreateIntermediaryMethod() throws JavaScriptModelException {
- // check if method already exists:
- List parameterBindings= new ArrayList();
- if (!isStaticTarget())
- parameterBindings.add(fIntermediaryFirstParameterType);
- parameterBindings.addAll(Arrays.asList(fTargetMethodBinding.getParameterTypes()));
- return Checks.checkMethodInType(fIntermediaryClassBinding, fIntermediaryMethodName, (ITypeBinding[]) parameterBindings.toArray(new ITypeBinding[parameterBindings.size()]));
- }
-
- private void createIntermediaryMethod() throws CoreException {
-
- CompilationUnitRewrite imRewrite= getCachedCURewrite(fIntermediaryClass.getJavaScriptUnit());
- AST ast= imRewrite.getAST();
- FunctionDeclaration intermediary= ast.newFunctionDeclaration();
-
- // Name
- intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));
-
- // Flags
- List modifiers= intermediary.modifiers();
- modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
- modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
-
- // Parameters
- String targetParameterName= StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());
-
- if (!isStaticTarget()) {
- // Add first param
- SingleVariableDeclaration parameter= imRewrite.getAST().newSingleVariableDeclaration();
- Type t= imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST());
- parameter.setType(t);
- parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
- intermediary.parameters().add(parameter);
- }
- // Add other params
- copyArguments(intermediary, imRewrite);
-
- // Return type
- intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast));
-
- // Body
- FunctionInvocation invocation= imRewrite.getAST().newFunctionInvocation();
- invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
- if (isStaticTarget()) {
- Type type= imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast);
- invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(type)));
- } else {
- invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
- }
- copyInvocationParameters(invocation, ast);
- Statement call= encapsulateInvocation(intermediary, invocation);
-
- final Block body= imRewrite.getAST().newBlock();
- body.statements().add(call);
- intermediary.setBody(body);
-
- // method comment
- IJavaScriptUnit targetCU= imRewrite.getCu();
- if (StubUtility.doAddComments(targetCU.getJavaScriptProject())) {
- String comment= CodeGeneration.getMethodComment(targetCU, getIntermediaryClassName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
- if (comment != null) {
- JSdoc javadoc= (JSdoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JSDOC);
- intermediary.setJavadoc(javadoc);
- }
- }
-
- // Add the completed method to the intermediary type:
-
- // Intermediary class is non-anonymous
- AbstractTypeDeclaration type= (AbstractTypeDeclaration) typeToDeclaration(fIntermediaryClass, imRewrite.getRoot());
- ChildListPropertyDescriptor typeBodyDeclarationsProperty= typeToBodyDeclarationProperty(fIntermediaryClass, imRewrite.getRoot());
-
- ListRewrite bodyDeclarationsListRewrite= imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
- bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite
- .createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
- }
-
- private Statement encapsulateInvocation(FunctionDeclaration declaration, FunctionInvocation invocation) {
- final Type type= declaration.getReturnType2();
-
- if (type == null || (type instanceof PrimitiveType && PrimitiveType.VOID.equals( ((PrimitiveType) type).getPrimitiveTypeCode())))
- return invocation.getAST().newExpressionStatement(invocation);
-
- ReturnStatement statement= invocation.getAST().newReturnStatement();
- statement.setExpression(invocation);
- return statement;
- }
-
- private void copyInvocationParameters(FunctionInvocation invocation, AST ast) throws JavaScriptModelException {
- String[] names= fTargetMethod.getParameterNames();
- for (int i= 0; i < names.length; i++)
- invocation.arguments().add(ast.newSimpleName(names[i]));
- }
-
- private void copyArguments(FunctionDeclaration intermediary, CompilationUnitRewrite rew) throws JavaScriptModelException {
- String[] names= fTargetMethod.getParameterNames();
- ITypeBinding[] types= fTargetMethodBinding.getParameterTypes();
- for (int i= 0; i < names.length; i++) {
- ITypeBinding typeBinding= types[i];
- SingleVariableDeclaration newElement= rew.getAST().newSingleVariableDeclaration();
- newElement.setName(rew.getAST().newSimpleName(names[i]));
-
- if (i == (names.length - 1) && fTargetMethodBinding.isVarargs()) {
- newElement.setVarargs(true);
- if (typeBinding.isArray())
- typeBinding= typeBinding.getComponentType();
- }
-
- newElement.setType(rew.getImportRewrite().addImport(typeBinding, rew.getAST()));
- intermediary.parameters().add(newElement);
- }
- }
-
- // ******************* UPDATE CALLS **********************
-
- private RefactoringStatus updateMethodInvocation(FunctionInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaScriptModelException {
-
- RefactoringStatus status= new RefactoringStatus();
-
- // If the method invocation utilizes type arguments, skip this
- // call as the new target method may have additional parameters
- if (originalInvocation.typeArguments().size() > 0)
- return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_type_arguments);
-
- FunctionInvocation newInvocation= unitRewriter.getAST().newFunctionInvocation();
- List newInvocationArgs= newInvocation.arguments();
- List originalInvocationArgs= originalInvocation.arguments();
-
- // static call => always use a qualifier
- String qualifier= unitRewriter.getImportRewrite().addImport(fIntermediaryClassBinding);
- newInvocation.setExpression(ASTNodeFactory.newName(unitRewriter.getAST(), qualifier));
- newInvocation.setName(unitRewriter.getAST().newSimpleName(getIntermediaryMethodName()));
-
- final Expression expression= originalInvocation.getExpression();
-
- if (!isStaticTarget()) {
- // Add the expression as the first parameter
- if (expression == null) {
- // There is no expression for this call. Use a (possibly qualified) "this" expression.
- ThisExpression expr= unitRewriter.getAST().newThisExpression();
- RefactoringStatus qualifierStatus= qualifyThisExpression(expr, originalInvocation, enclosing, unitRewriter);
- status.merge(qualifierStatus);
- if (qualifierStatus.hasEntries())
- // warning means don't include this invocation
- return status;
- newInvocationArgs.add(expr);
- } else {
- ASTNode expressionAsParam= unitRewriter.getASTRewrite().createMoveTarget(expression);
- newInvocationArgs.add(expressionAsParam);
- }
- } else {
- if (expression != null) {
- // Check if expression is the class name. If not, there may
- // be side effects (e.g. inside methods) -> don't update
- if (! (expression instanceof Name) || ASTNodes.getTypeBinding((Name) expression) == null)
- return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_static_expression_access);
- }
- }
-
- for (int i= 0; i < originalInvocationArgs.size(); i++) {
- Expression originalInvocationArg= (Expression) originalInvocationArgs.get(i);
- ASTNode movedArg= unitRewriter.getASTRewrite().createMoveTarget(originalInvocationArg);
- newInvocationArgs.add(movedArg);
- }
-
- unitRewriter.getASTRewrite().replace(originalInvocation, newInvocation,
- unitRewriter.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_replace_call));
-
- return status;
- }
-
- /**
- * Attempts to qualify a "this" expression for a method invocation with an appropriate qualifier.
- * The invoked method is analyzed according to the following specs:
- *
- * 'this' must be qualified iff method is declared in an enclosing type or a supertype of an enclosing type
- *
- * 1) The method is declared somewhere outside of the cu of the invocation
- * 1a) inside a supertype of the current type
- * 1b) inside a supertype of an enclosing type
- * 2) The method is declared inside of the cu of the invocation
- * 2a) inside the type of the invocation
- * 2b) outside the type of the invocation
- *
- * In case of 1a) and 2b), qualify with the enclosing type.
- * @param expr
- * @param originalInvocation
- * @param enclosing
- * @param unitRewriter
- * @return resulting status
- *
- */
- private RefactoringStatus qualifyThisExpression(ThisExpression expr, FunctionInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) {
-
- RefactoringStatus status= new RefactoringStatus();
-
- IFunctionBinding methodBinding= originalInvocation.resolveMethodBinding();
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) ASTNodes.findDeclaration(methodBinding, originalInvocation.getRoot());
-
- ITypeBinding currentTypeBinding= null;
- if (methodDeclaration != null) {
- // Case 1) : Declaring class is inside this cu => use its name if it's declared in an enclosing type
- if (ASTNodes.isParent(originalInvocation, methodDeclaration.getParent()))
- currentTypeBinding= methodBinding.getDeclaringClass();
- else
- currentTypeBinding= ASTNodes.getEnclosingType(originalInvocation);
- } else {
- // Case 2) : Declaring class is outside of this cu => find subclass in this cu
- ASTNode currentTypeDeclaration= getEnclosingTypeDeclaration(originalInvocation);
- currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
- while (currentTypeDeclaration != null && (Bindings.findMethodInHierarchy(currentTypeBinding, methodBinding.getName(), methodBinding.getParameterTypes()) == null)) {
- currentTypeDeclaration= getEnclosingTypeDeclaration(currentTypeDeclaration.getParent());
- currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
- }
- }
-
- if (currentTypeBinding == null) {
- status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found));
- return status;
- }
-
- ITypeBinding typeOfCall= ASTNodes.getEnclosingType(originalInvocation);
- if (!typeOfCall.equals(currentTypeBinding)) {
- if (currentTypeBinding.isAnonymous()) {
- // Cannot qualify, see bug 115277
- status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify));
- } else {
- expr.setQualifier(unitRewriter.getAST().newSimpleName(currentTypeBinding.getName()));
- }
- } else {
- // do not qualify, only use "this.".
- }
-
- return status;
- }
-
- // ********* SMALL HELPERS ********************
-
- /*
- * Helper method for finding an IFunction inside a binding hierarchy
- */
- private IFunctionBinding findMethodBindingInHierarchy(ITypeBinding currentTypeBinding, IFunction methodDeclaration) {
- IFunctionBinding[] bindings= currentTypeBinding.getDeclaredMethods();
- for (int i= 0; i < bindings.length; i++)
- if (methodDeclaration.equals(bindings[i].getJavaElement()))
- return bindings[i];
-
- ITypeBinding superClass= currentTypeBinding.getSuperclass();
- if (superClass != null) {
- IFunctionBinding b= findMethodBindingInHierarchy(superClass, methodDeclaration);
- if (b != null)
- return b;
- }
- return null;
- }
-
- /*
- * Helper method for retrieving a *bottom-up* list of super type bindings
- */
- private ITypeBinding[] getTypeAndAllSuperTypes(ITypeBinding type) {
- List result= new ArrayList();
- collectSuperTypes(type, result);
- return (ITypeBinding[]) result.toArray(new ITypeBinding[result.size()]);
- }
-
- private void collectSuperTypes(ITypeBinding curr, List list) {
- if (list.add(curr.getTypeDeclaration())) {
- ITypeBinding superClass= curr.getSuperclass();
- if (superClass != null) {
- collectSuperTypes(superClass, list);
- }
- }
- }
-
- private CompilationUnitRewrite getCachedCURewrite(IJavaScriptUnit unit) {
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) fRewrites.get(unit);
- if (rewrite == null) {
- rewrite= new CompilationUnitRewrite(unit);
- fRewrites.put(unit, rewrite);
- }
- return rewrite;
- }
-
- private boolean isRewriteKept(IJavaScriptUnit compilationUnit) {
- return fIntermediaryClass.getJavaScriptUnit().equals(compilationUnit);
- }
-
- private void createChangeAndDiscardRewrite(IJavaScriptUnit compilationUnit) throws CoreException {
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) fRewrites.get(compilationUnit);
- if (rewrite != null) {
- fTextChangeManager.manage(compilationUnit, rewrite.createChange());
- fRewrites.remove(compilationUnit);
- }
- }
-
- private SearchResultGroup[] getReferences(IFunction[] methods, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(methods, IJavaScriptSearchConstants.REFERENCES);
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(fIntermediaryClass, false);
- return RefactoringSearchEngine.search(pattern, scope, pm, status);
- }
-
- private ITypeBinding typeToBinding(IType type, JavaScriptUnit root) throws JavaScriptModelException {
- ASTNode typeNode= typeToDeclaration(type, root);
- if (type.isAnonymous()) {
- return ((AnonymousClassDeclaration) typeNode).resolveBinding();
- } else {
- return ((AbstractTypeDeclaration) typeNode).resolveBinding();
- }
- }
-
- private ASTNode typeToDeclaration(IType type, JavaScriptUnit root) throws JavaScriptModelException {
- Name intermediateName= (Name) NodeFinder.perform(root, type.getNameRange());
- if (type.isAnonymous()) {
- return ASTNodes.getParent(intermediateName, AnonymousClassDeclaration.class);
- } else {
- return ASTNodes.getParent(intermediateName, AbstractTypeDeclaration.class);
- }
- }
-
- private ASTNode getEnclosingTypeDeclaration(ASTNode node) {
- while (node != null) {
- if (node instanceof AbstractTypeDeclaration) {
- return node;
- } else if (node instanceof AnonymousClassDeclaration) {
- return node;
- }
- node= node.getParent();
- }
- return null;
- }
-
- private ChildListPropertyDescriptor typeToBodyDeclarationProperty(IType type, JavaScriptUnit root) throws JavaScriptModelException {
- ASTNode typeDeclaration= typeToDeclaration(type, root);
- if (typeDeclaration instanceof AbstractTypeDeclaration)
- return ((AbstractTypeDeclaration) typeDeclaration).getBodyDeclarationsProperty();
- else if (typeDeclaration instanceof AnonymousClassDeclaration)
- return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
-
- Assert.isTrue(false);
- return null;
- }
-
- private RefactoringStatus createWarningAboutCall(IMember enclosing, ASTNode concreteNode, String message) {
- String name= JavaScriptElementLabels.getElementLabel(enclosing, JavaScriptElementLabels.ALL_DEFAULT);
- String container= JavaScriptElementLabels.getElementLabel(enclosing.getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- return RefactoringStatus.createWarningStatus(Messages.format(message, new String[] { name, container }), JavaStatusContext.create(enclosing.getJavaScriptUnit(), concreteNode));
- }
-
- private ITypeBinding getExpressionType(FunctionInvocation invocation) {
- Expression expression= invocation.getExpression();
- ITypeBinding typeBinding= null;
- if (expression == null) {
- typeBinding= invocation.resolveMethodBinding().getDeclaringClass();
- } else {
- typeBinding= expression.resolveTypeBinding();
- }
-
- Assert.isNotNull(typeBinding, "Type binding of target expression may not be null"); //$NON-NLS-1$
- return typeBinding;
- }
-
- private IFile[] getAllFilesToModify() {
- List cus= new ArrayList();
- cus.addAll(Arrays.asList(fTextChangeManager.getAllCompilationUnits()));
- return ResourceUtil.getFiles((IJavaScriptUnit[]) cus.toArray(new IJavaScriptUnit[cus.size()]));
- }
-
- private boolean isStaticTarget() throws JavaScriptModelException {
- return Flags.isStatic(fTargetMethod.getFlags());
- }
-
- private IMember getEnclosingInitialSelectionMember() throws JavaScriptModelException {
- return (IMember) fSelectionCompilationUnit.getElementAt(fSelectionStart);
- }
-
- private static ASTNode getSelectedNode(IJavaScriptUnit unit, JavaScriptUnit root, int offset, int length) {
- ASTNode node= null;
- try {
- if (unit != null)
- node= checkNode(NodeFinder.perform(root, offset, length, unit));
- else
- node= checkNode(NodeFinder.perform(root, offset, length));
- } catch (JavaScriptModelException e) {
- // Do nothing
- }
- if (node != null)
- return node;
- return checkNode(NodeFinder.perform(root, offset, length));
- }
-
- private static ASTNode checkNode(ASTNode node) {
- if (node == null)
- return null;
- if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
- node= node.getParent();
- } else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
- node= ((ExpressionStatement) node).getExpression();
- }
- switch (node.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- case ASTNode.FUNCTION_DECLARATION:
- case ASTNode.SUPER_METHOD_INVOCATION:
- return node;
- }
- return null;
- }
-
- // ***************** VISIBILITY ********************
-
- private ModifierKeyword getNeededVisibility(IMember whoToAdjust, IMember fromWhereToLook) throws JavaScriptModelException {
- return fAdjustor.getVisibilityThreshold(fromWhereToLook, whoToAdjust, new NullProgressMonitor());
- }
-
- private RefactoringStatus adjustVisibility(IMember whoToAdjust, IMember fromWhereToLook, IProgressMonitor monitor) throws CoreException {
- return adjustVisibility(whoToAdjust, getNeededVisibility(whoToAdjust, fromWhereToLook), true, monitor);
- }
-
- private RefactoringStatus adjustVisibility(IMember whoToAdjust, ModifierKeyword neededVisibility, IProgressMonitor monitor) throws CoreException {
- return adjustVisibility(whoToAdjust, neededVisibility, false, monitor);
- }
-
- private RefactoringStatus adjustVisibility(IMember whoToAdjust, ModifierKeyword neededVisibility, boolean alsoIncreaseEnclosing, IProgressMonitor monitor) throws CoreException {
-
- Map adjustments;
- if (isRewriteKept(whoToAdjust.getJavaScriptUnit()))
- adjustments= fIntermediaryAdjustments;
- else
- adjustments= new HashMap();
-
- int existingAdjustments= adjustments.size();
- addAdjustment(whoToAdjust, neededVisibility, adjustments);
-
- if (alsoIncreaseEnclosing)
- while (whoToAdjust.getDeclaringType() != null) {
- whoToAdjust= whoToAdjust.getDeclaringType();
- addAdjustment(whoToAdjust, neededVisibility, adjustments);
- }
-
- boolean hasNewAdjustments= (adjustments.size() - existingAdjustments) > 0;
- if (hasNewAdjustments && ( (whoToAdjust.isReadOnly() || whoToAdjust.isBinary())))
- return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_update_binary_target_visibility, new String[] { JavaScriptElementLabels
- .getElementLabel(whoToAdjust, JavaScriptElementLabels.ALL_DEFAULT) }), JavaStatusContext.create(whoToAdjust));
-
- RefactoringStatus status= new RefactoringStatus();
-
- // Don't create a rewrite if it is not necessary
- if (!hasNewAdjustments)
- return status;
-
- try {
- monitor.beginTask(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting, 2);
- Map rewrites;
- if (!isRewriteKept(whoToAdjust.getJavaScriptUnit())) {
- CompilationUnitRewrite rewrite= new CompilationUnitRewrite(whoToAdjust.getJavaScriptUnit());
- rewrite.setResolveBindings(false);
- rewrites= new HashMap();
- rewrites.put(whoToAdjust.getJavaScriptUnit(), rewrite);
- status.merge(rewriteVisibility(adjustments, rewrites, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
- rewrite.attachChange((CompilationUnitChange) fTextChangeManager.get(whoToAdjust.getJavaScriptUnit()), true, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- private RefactoringStatus rewriteVisibility(Map adjustments, Map rewrites, IProgressMonitor monitor) throws JavaScriptModelException {
- RefactoringStatus status= new RefactoringStatus();
- fAdjustor.setRewrites(rewrites);
- fAdjustor.setAdjustments(adjustments);
- fAdjustor.setStatus(status);
- fAdjustor.rewriteVisibility(monitor);
- return status;
- }
-
- private void addAdjustment(IMember whoToAdjust, ModifierKeyword neededVisibility, Map adjustments) throws JavaScriptModelException {
- ModifierKeyword currentVisibility= ModifierKeyword.fromFlagValue(JdtFlags.getVisibilityCode(whoToAdjust));
- if (MemberVisibilityAdjustor.hasLowerVisibility(currentVisibility, neededVisibility)
- && MemberVisibilityAdjustor.needsVisibilityAdjustments(whoToAdjust, neededVisibility, adjustments))
- adjustments.put(whoToAdjust, new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(whoToAdjust, neededVisibility,
- RefactoringStatus.createWarningStatus(Messages.format(MemberVisibilityAdjustor.getMessage(whoToAdjust), new String[] {
- MemberVisibilityAdjustor.getLabel(whoToAdjust), MemberVisibilityAdjustor.getLabel(neededVisibility) }), JavaStatusContext
- .create(whoToAdjust))));
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.METHOD)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INTRODUCE_INDIRECTION);
- else
- fTargetMethod= (IFunction) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INTRODUCE_INDIRECTION);
- else
- fIntermediaryClass= (IType) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1));
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- return setIntermediaryMethodName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java
deleted file mode 100644
index bc9a766c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java
+++ /dev/null
@@ -1,575 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Felix Pahl (fpahl@web.de) - contributed fix for:
- * o introduce parameter throws NPE if there are compiler errors
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=48325)
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.ASTFragmentFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.fragments.IExpressionFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RefactoringDescriptorChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.BodyUpdater;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class IntroduceParameterRefactoring extends ScriptableRefactoring implements IDelegateUpdating {
-
- private static final String ATTRIBUTE_ARGUMENT= "argument"; //$NON-NLS-1$
-
- private static final String[] KNOWN_METHOD_NAME_PREFIXES= {"get", "is"}; //$NON-NLS-2$ //$NON-NLS-1$
-
- private IJavaScriptUnit fSourceCU;
- private int fSelectionStart;
- private int fSelectionLength;
-
- private IFunction fMethod;
- private ChangeSignatureRefactoring fChangeSignatureRefactoring;
- private ParameterInfo fParameter;
- private String fParameterName;
- private RefactoringArguments fArguments;
-
- private Expression fSelectedExpression;
- private String[] fExcludedParameterNames;
-
- /**
- * Creates a new introduce parameter refactoring.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public IntroduceParameterRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSourceCU= unit;
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- }
-
- // ------------------- IDelegateUpdating ----------------------
-
- public boolean canEnableDelegateUpdating() {
- return true;
- }
-
- public boolean getDelegateUpdating() {
- return (fChangeSignatureRefactoring != null) ? fChangeSignatureRefactoring.getDelegateUpdating() : false;
- }
-
- public void setDelegateUpdating(boolean updating) {
- if (fChangeSignatureRefactoring != null)
- fChangeSignatureRefactoring.setDelegateUpdating(updating);
- }
-
- public void setDeprecateDelegates(boolean deprecate) {
- if (fChangeSignatureRefactoring != null)
- fChangeSignatureRefactoring.setDeprecateDelegates(deprecate);
- }
-
- public boolean getDeprecateDelegates() {
- return (fChangeSignatureRefactoring != null) ? fChangeSignatureRefactoring.getDeprecateDelegates() : false;
- }
-
- // ------------------- /IDelegateUpdating ---------------------
-
- public String getName() {
- return RefactoringCoreMessages.IntroduceParameterRefactoring_name;
- }
-
- //--- checkActivation
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", 7); //$NON-NLS-1$
-
- if (! fSourceCU.isStructureKnown())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_syntax_error);
-
- IJavaScriptElement enclosingElement= SelectionConverter.resolveEnclosingElement(fSourceCU, new TextSelection(fSelectionStart, fSelectionLength));
- if (! (enclosingElement instanceof IFunction))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
-
- fMethod= (IFunction) enclosingElement;
- pm.worked(1);
-
- RefactoringStatus result= new RefactoringStatus();
- if (fArguments != null) {
- // invoked by script
- fChangeSignatureRefactoring= new ChangeSignatureRefactoring(null);
- result= fChangeSignatureRefactoring.initialize(fArguments);
- if (!result.hasFatalError()) {
- fChangeSignatureRefactoring.setValidationContext(getValidationContext());
- result.merge(fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 2)));
- if (result.hasFatalError())
- return result;
- } else {
- pm.worked(2);
- return result;
- }
- } else {
- // first try:
- fChangeSignatureRefactoring= RefactoringAvailabilityTester.isChangeSignatureAvailable(fMethod) ? new ChangeSignatureRefactoring(fMethod) : null;
- if (fChangeSignatureRefactoring == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
- fChangeSignatureRefactoring.setValidationContext(getValidationContext());
- result.merge(fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 1)));
- if (result.hasFatalError()) {
- RefactoringStatusEntry entry= result.getEntryMatchingSeverity(RefactoringStatus.FATAL);
- if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) {
- // second try:
- IFunction method= (IFunction) entry.getData();
- fChangeSignatureRefactoring= RefactoringAvailabilityTester.isChangeSignatureAvailable(method) ? new ChangeSignatureRefactoring(method) : null;
- if (fChangeSignatureRefactoring == null) {
- String msg= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_cannot_introduce, entry.getMessage());
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- result= fChangeSignatureRefactoring.checkInitialConditions(new SubProgressMonitor(pm, 1));
- if (result.hasFatalError())
- return result;
- } else {
- return result;
- }
- } else {
- pm.worked(1);
- }
- }
-
- CompilationUnitRewrite cuRewrite= fChangeSignatureRefactoring.getBaseCuRewrite();
- if (! cuRewrite.getCu().equals(fSourceCU))
- cuRewrite= new CompilationUnitRewrite(fSourceCU); // TODO: should try to avoid throwing away this AST
-
- initializeSelectedExpression(cuRewrite);
- pm.worked(1);
-
- result.merge(checkSelection(cuRewrite, new SubProgressMonitor(pm, 3)));
- if (result.hasFatalError())
- return result;
-
- initializeExcludedParameterNames(cuRewrite);
-
- addParameterInfo(cuRewrite);
-
- fChangeSignatureRefactoring.setBodyUpdater(new BodyUpdater() {
- public void updateBody(FunctionDeclaration methodDeclaration, CompilationUnitRewrite rewrite, RefactoringStatus updaterResult) {
- replaceSelectedExpression(rewrite);
- }
- });
-
- return result;
- } finally {
- pm.done();
- if (fChangeSignatureRefactoring != null)
- fChangeSignatureRefactoring.setValidationContext(null);
- }
- }
-
- private void addParameterInfo(CompilationUnitRewrite cuRewrite) throws JavaScriptModelException {
- ITypeBinding typeBinding= Bindings.normalizeForDeclarationUse(fSelectedExpression.resolveTypeBinding(), fSelectedExpression.getAST());
- String typeName= cuRewrite.getImportRewrite().addImport(typeBinding);
- String name= fParameterName != null ? fParameterName : guessedParameterName();
- String defaultValue= fSourceCU.getBuffer().getText(fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());
- fParameter= ParameterInfo.createInfoForAddedParameter(typeBinding, typeName, name, defaultValue);
- if (fArguments == null) {
- List parameterInfos= fChangeSignatureRefactoring.getParameterInfos();
- int parametersCount= parameterInfos.size();
- if (parametersCount > 0 && ((ParameterInfo) parameterInfos.get(parametersCount - 1)).isOldVarargs())
- parameterInfos.add(parametersCount - 1, fParameter);
- else
- parameterInfos.add(fParameter);
- }
- }
-
- private void replaceSelectedExpression(CompilationUnitRewrite cuRewrite) {
- if (! fSourceCU.equals(cuRewrite.getCu()))
- return;
- // TODO: do for all methodDeclarations and replace matching fragments?
-
- // cannot use fSelectedExpression here, since it could be from another AST (if method was replaced by overridden):
- Expression expression= (Expression) NodeFinder.perform(cuRewrite.getRoot(), fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());
-
- ASTNode newExpression= cuRewrite.getRoot().getAST().newSimpleName(fParameter.getNewName());
- String description= RefactoringCoreMessages.IntroduceParameterRefactoring_replace;
- cuRewrite.getASTRewrite().replace(expression, newExpression, cuRewrite.createGroupDescription(description));
- }
-
- private void initializeSelectedExpression(CompilationUnitRewrite cuRewrite) throws JavaScriptModelException {
- IASTFragment fragment= ASTFragmentFactory.createFragmentForSourceRange(
- new SourceRange(fSelectionStart, fSelectionLength), cuRewrite.getRoot(), cuRewrite.getCu());
-
- if (! (fragment instanceof IExpressionFragment))
- return;
-
- //TODO: doesn't handle selection of partial Expressions
- Expression expression= ((IExpressionFragment) fragment).getAssociatedExpression();
- if (fragment.getStartPosition() != expression.getStartPosition()
- || fragment.getLength() != expression.getLength())
- return;
-
- if (Checks.isInsideJavadoc(expression))
- return;
-
- fSelectedExpression= expression;
- }
-
- private RefactoringStatus checkSelection(CompilationUnitRewrite cuRewrite, IProgressMonitor pm) {
- if (fSelectedExpression == null){
- String message= RefactoringCoreMessages.IntroduceParameterRefactoring_select;
- return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, cuRewrite.getRoot(), message);
- }
-
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) ASTNodes.getParent(fSelectedExpression, FunctionDeclaration.class);
- if (methodDeclaration == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
- if (methodDeclaration.resolveBinding() == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_no_binding);
- //TODO: check for rippleMethods -> find matching fragments, consider callers of all rippleMethods
-
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkExpression());
- if (result.hasFatalError())
- return result;
-
- result.merge(checkExpressionBinding());
- if (result.hasFatalError())
- return result;
-
-// if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression()))
-// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.for_initializer_updater")); //$NON-NLS-1$
-// pm.worked(1);
-//
-// if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression()))
-// return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.refers_to_for_variable")); //$NON-NLS-1$
-// pm.worked(1);
-
- return result;
- }
-
- private RefactoringStatus checkExpression() {
- //TODO: adjust error messages (or generalize for all refactorings on expression-selections?)
- Expression selectedExpression= fSelectedExpression;
-
- if (selectedExpression instanceof Name && selectedExpression.getParent() instanceof ClassInstanceCreation)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_name_in_new);
- //TODO: let's just take the CIC automatically (no ambiguity -> no problem -> no dialog ;-)
-
- if (selectedExpression instanceof NullLiteral) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
- } else if (selectedExpression instanceof ArrayInitializer) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
- } else if (selectedExpression instanceof Assignment) {
- if (selectedExpression.getParent() instanceof Expression)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
- else
- return null;
-
- } else if (selectedExpression instanceof SimpleName){
- if ((((SimpleName)selectedExpression)).isDeclaration())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
- if (selectedExpression.getParent() instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
- || selectedExpression.getParent() instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
- }
-
- return null;
- }
-
- private RefactoringStatus checkExpressionBinding() {
- return checkExpressionFragmentIsRValue();
- }
-
- // !! +/- same as in ExtractConstantRefactoring & ExtractTempRefactoring
- private RefactoringStatus checkExpressionFragmentIsRValue() {
- switch(Checks.checkExpressionIsRValue(fSelectedExpression)) {
- case Checks.NOT_RVALUE_MISC:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.IntroduceParameterRefactoring_select, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
- case Checks.NOT_RVALUE_VOID:
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.IntroduceParameterRefactoring_no_void, null, Corext.getPluginId(), RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
- case Checks.IS_RVALUE:
- return new RefactoringStatus();
- default:
- Assert.isTrue(false); return null;
- }
- }
-
- public List getParameterInfos() {
- return fChangeSignatureRefactoring.getParameterInfos();
- }
-
- public ParameterInfo getAddedParameterInfo() {
- return fParameter;
- }
-
- public String getMethodSignaturePreview() throws JavaScriptModelException {
- return fChangeSignatureRefactoring.getNewMethodSignature();
- }
-
-//--- Input setting/validation
-
- public void setParameterName(String name) {
- Assert.isNotNull(name);
- fParameter.setNewName(name);
- }
-
- /**
- * must only be called <i>after</i> checkActivation()
- * @return guessed parameter name
- */
- public String guessedParameterName() {
- String[] proposals= guessParameterNames();
- if (proposals.length == 0)
- return ""; //$NON-NLS-1$
- else
- return proposals[0];
- }
-
-// --- TODO: copied from ExtractTempRefactoring - should extract ------------------------------
-
- /**
- * Must only be called <i>after</i> checkActivation().
- * The first proposal should be used as "best guess" (if it exists).
- * @return proposed variable names (may be empty, but not null).
- */
- public String[] guessParameterNames() {
- LinkedHashSet proposals= new LinkedHashSet(); //retain ordering, but prevent duplicates
- if (fSelectedExpression instanceof FunctionInvocation){
- proposals.addAll(guessTempNamesFromMethodInvocation((FunctionInvocation) fSelectedExpression, fExcludedParameterNames));
- }
- proposals.addAll(guessTempNamesFromExpression(fSelectedExpression, fExcludedParameterNames));
- return (String[]) proposals.toArray(new String[proposals.size()]);
- }
-
- private List/*<String>*/ guessTempNamesFromMethodInvocation(FunctionInvocation selectedMethodInvocation, String[] excludedVariableNames) {
- SimpleName name = selectedMethodInvocation.getName();
-
- String methodName;
- if (name!=null)
- {
- methodName= name.getIdentifier();
- for (int i= 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
- String prefix= KNOWN_METHOD_NAME_PREFIXES[i];
- if (! methodName.startsWith(prefix))
- continue; //not this prefix
- if (methodName.length() == prefix.length())
- return Collections.EMPTY_LIST; // prefix alone -> don't take method name
- char firstAfterPrefix= methodName.charAt(prefix.length());
- if (! Character.isUpperCase(firstAfterPrefix))
- continue; //not uppercase after prefix
- //found matching prefix
- String proposal= Character.toLowerCase(firstAfterPrefix) + methodName.substring(prefix.length() + 1);
- methodName= proposal;
- break;
- }
- }
- else
- methodName="indirectFunctionCall"; //$NON-NLS-1$
- String[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaScriptProject(), methodName, 0, excludedVariableNames);
- return Arrays.asList(proposals);
- }
-
- private List/*<String>*/ guessTempNamesFromExpression(Expression selectedExpression, String[] excluded) {
- ITypeBinding expressionBinding= Bindings.normalizeForDeclarationUse(
- selectedExpression.resolveTypeBinding(),
- selectedExpression.getAST());
- String typeName= getQualifiedName(expressionBinding);
- if (typeName.length() == 0)
- typeName= expressionBinding.getName();
- if (typeName.length() == 0)
- return Collections.EMPTY_LIST;
- int typeParamStart= typeName.indexOf("<"); //$NON-NLS-1$
- if (typeParamStart != -1)
- typeName= typeName.substring(0, typeParamStart);
- String[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaScriptProject(), typeName, expressionBinding.getDimensions(), excluded);
- return Arrays.asList(proposals);
- }
-
-// ----------------------------------------------------------------------
-
- private static String getQualifiedName(ITypeBinding typeBinding) {
- if (typeBinding.isAnonymous())
- return getQualifiedName(typeBinding.getSuperclass());
- if (! typeBinding.isArray())
- return typeBinding.getQualifiedName();
- else
- return typeBinding.getElementType().getQualifiedName();
- }
-
- private void initializeExcludedParameterNames(CompilationUnitRewrite cuRewrite) {
- IBinding[] bindings= new ScopeAnalyzer(cuRewrite.getRoot()).getDeclarationsInScope(
- fSelectedExpression.getStartPosition(), ScopeAnalyzer.VARIABLES);
- fExcludedParameterNames= new String[bindings.length];
- for (int i= 0; i < fExcludedParameterNames.length; i++) {
- fExcludedParameterNames[i]= bindings[i].getName();
- }
- }
-
- public RefactoringStatus validateInput() {
- return fChangeSignatureRefactoring.checkSignature();
- }
-
-//--- checkInput
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- fChangeSignatureRefactoring.setValidationContext(getValidationContext());
- RefactoringStatus result;
- try {
- result= fChangeSignatureRefactoring.checkFinalConditions(pm);
- } finally {
- fChangeSignatureRefactoring.setValidationContext(null);
- }
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- fChangeSignatureRefactoring.setValidationContext(getValidationContext());
- Change result;
- try {
- result= fChangeSignatureRefactoring.createChange(pm);
- } finally {
- fChangeSignatureRefactoring.setValidationContext(null);
- }
- if (result != null) {
- final ChangeDescriptor descriptor= result.getDescriptor();
- if (descriptor instanceof RefactoringChangeDescriptor) {
- final RefactoringDescriptor refactoringDescriptor= ((RefactoringChangeDescriptor) descriptor).getRefactoringDescriptor();
- if (refactoringDescriptor instanceof JDTRefactoringDescriptor) {
- final JDTRefactoringDescriptor extended= (JDTRefactoringDescriptor) refactoringDescriptor;
- final Map arguments= new HashMap();
- arguments.put(ATTRIBUTE_ARGUMENT, fParameter.getNewName());
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.putAll(extended.getArguments());
- String signature= fChangeSignatureRefactoring.getMethodName();
- try {
- signature= fChangeSignatureRefactoring.getOldMethodSignature();
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_descriptor_description_short, fChangeSignatureRefactoring.getMethod().getElementName());
- final String header= Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_descriptor_description, new String[] { fParameter.getNewName(), signature, ASTNodes.asString(fSelectedExpression)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(extended.getProject(), this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_original_pattern, JavaScriptElementLabels.getTextLabel(fChangeSignatureRefactoring.getMethod(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_pattern, ASTNodes.asString(fSelectedExpression)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceParameterRefactoring_parameter_pattern, getAddedParameterInfo().getNewName()));
- result= new RefactoringDescriptorChange(new JDTRefactoringDescriptor(IJavaScriptRefactorings.INTRODUCE_PARAMETER, extended.getProject(), description, comment.asString(), arguments, extended.getFlags()), RefactoringCoreMessages.IntroduceParameterRefactoring_name, new Change[] { result});
- }
- }
- }
- return result;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- fArguments= arguments;
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.INTRODUCE_PARAMETER);
- else
- fSourceCU= ((IFunction) element).getJavaScriptUnit();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(ATTRIBUTE_ARGUMENT);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fParameterName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ARGUMENT));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateCreator_keep_original_changed_plural;
- else
- return RefactoringCoreMessages.DelegateCreator_keep_original_changed_singular;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/Invocations.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/Invocations.java
deleted file mode 100644
index 58d63bc5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/Invocations.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for:
- * o Allow 'this' constructor to be inlined
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-
-public class Invocations {
-
- public static List getArguments(ASTNode invocation) {
- switch(invocation.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- return ((FunctionInvocation)invocation).arguments();
- case ASTNode.SUPER_METHOD_INVOCATION:
- return ((SuperMethodInvocation)invocation).arguments();
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return ((ConstructorInvocation)invocation).arguments();
- default:
- throw new IllegalArgumentException(invocation.toString());
- }
- }
-
- public static Expression getExpression(ASTNode invocation) {
- switch(invocation.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- return ((FunctionInvocation)invocation).getExpression();
- case ASTNode.SUPER_METHOD_INVOCATION:
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return null;
- default:
- throw new IllegalArgumentException(invocation.toString());
- }
- }
-
- public static boolean isInvocation(ASTNode node) {
- int type= node.getNodeType();
- return type == ASTNode.FUNCTION_INVOCATION || type == ASTNode.SUPER_METHOD_INVOCATION ||
- type == ASTNode.CONSTRUCTOR_INVOCATION;
- }
-
- public static IFunctionBinding resolveBinding(ASTNode invocation) {
- switch(invocation.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- SimpleName name = ((FunctionInvocation)invocation).getName();
- if (name!=null)
- return (IFunctionBinding)name.resolveBinding();
- else
- return ((FunctionInvocation)invocation).resolveMethodBinding();
- case ASTNode.SUPER_METHOD_INVOCATION:
- return ((SuperMethodInvocation)invocation).resolveMethodBinding();
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return ((ConstructorInvocation)invocation).resolveConstructorBinding();
- default:
- throw new IllegalArgumentException(invocation.toString());
- }
- }
-
- public static boolean isResolvedTypeInferredFromExpectedType(Expression invocation) {
- switch(invocation.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- return ((FunctionInvocation) invocation).isResolvedTypeInferredFromExpectedType();
- case ASTNode.SUPER_METHOD_INVOCATION:
- return ((SuperMethodInvocation) invocation).isResolvedTypeInferredFromExpectedType();
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return false;
- default:
- throw new IllegalArgumentException(invocation.toString());
- }
- }
-
- public static ChildListPropertyDescriptor getTypeArgumentsProperty(Expression invocation) {
- switch(invocation.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- return FunctionInvocation.TYPE_ARGUMENTS_PROPERTY;
- case ASTNode.SUPER_METHOD_INVOCATION:
- return SuperMethodInvocation.TYPE_ARGUMENTS_PROPERTY;
- case ASTNode.CONSTRUCTOR_INVOCATION:
- return ConstructorInvocation.TYPE_ARGUMENTS_PROPERTY;
- default:
- throw new IllegalArgumentException(invocation.toString());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java
deleted file mode 100644
index b2e09b85..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class LocalTypeAnalyzer extends ASTVisitor {
-
- private Selection fSelection;
- private List fTypeDeclarationsBefore= new ArrayList(2);
- private List fTypeDeclarationsSelected= new ArrayList(2);
- private String fBeforeTypeReferenced;
- private String fSelectedTypeReferenced;
-
- //---- Analyzing statements ----------------------------------------------------------------
-
- public static RefactoringStatus perform(BodyDeclaration declaration, Selection selection) {
- LocalTypeAnalyzer analyzer= new LocalTypeAnalyzer(selection);
- declaration.accept(analyzer);
- RefactoringStatus result= new RefactoringStatus();
- analyzer.check(result);
- return result;
- }
-
- private LocalTypeAnalyzer(Selection selection) {
- fSelection= selection;
- }
-
- public boolean visit(SimpleName node) {
- if (node.isDeclaration())
- return true;
- IBinding binding= node.resolveBinding();
- if (binding instanceof ITypeBinding)
- processLocalTypeBinding((ITypeBinding) binding, fSelection.getVisitSelectionMode(node));
-
- return true;
- }
-
- public boolean visit(TypeDeclaration node) {
- return visitType(node);
- }
-
- private boolean visitType(AbstractTypeDeclaration node) {
- int mode= fSelection.getVisitSelectionMode(node);
- switch (mode) {
- case Selection.BEFORE:
- fTypeDeclarationsBefore.add(node);
- break;
- case Selection.SELECTED:
- fTypeDeclarationsSelected.add(node);
- break;
- }
- return true;
- }
-
- private void processLocalTypeBinding(ITypeBinding binding, int mode) {
- switch (mode) {
- case Selection.SELECTED:
- if (fBeforeTypeReferenced != null)
- break;
- if (checkBinding(fTypeDeclarationsBefore, binding))
- fBeforeTypeReferenced= RefactoringCoreMessages.LocalTypeAnalyzer_local_type_from_outside;
- break;
- case Selection.AFTER:
- if (fSelectedTypeReferenced != null)
- break;
- if (checkBinding(fTypeDeclarationsSelected, binding))
- fSelectedTypeReferenced= RefactoringCoreMessages.LocalTypeAnalyzer_local_type_referenced_outside;
- break;
- }
- }
-
- private boolean checkBinding(List declarations, ITypeBinding binding) {
- for (Iterator iter= declarations.iterator(); iter.hasNext();) {
- AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)iter.next();
- if (declaration.resolveBinding() == binding) {
- return true;
- }
- }
- return false;
- }
-
- private void check(RefactoringStatus status) {
- if (fBeforeTypeReferenced != null)
- status.addFatalError(fBeforeTypeReferenced);
- if (fSelectedTypeReferenced != null)
- status.addFatalError(fSelectedTypeReferenced);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/NameCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/NameCollector.java
deleted file mode 100644
index e1dc19bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/NameCollector.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-
-class NameCollector extends GenericVisitor {
- private List names= new ArrayList();
- private Selection fSelection;
- public NameCollector(ASTNode node) {
- fSelection= Selection.createFromStartLength(node.getStartPosition(), node.getLength());
- }
- protected boolean visitNode(ASTNode node) {
- if (node.getStartPosition() > fSelection.getInclusiveEnd())
- return true;
- if (fSelection.coveredBy(node))
- return true;
- return false;
- }
- public boolean visit(SimpleName node) {
- names.add(node.getIdentifier());
- return super.visit(node);
- }
- public boolean visit(VariableDeclarationStatement node) {
- return true;
- }
- public boolean visit(VariableDeclarationFragment node) {
- boolean result= super.visit(node);
- if (!result)
- names.add(node.getName().getIdentifier());
- return result;
- }
- public boolean visit(SingleVariableDeclaration node) {
- boolean result= super.visit(node);
- if (!result)
- names.add(node.getName().getIdentifier());
- return result;
- }
- public boolean visit(TypeDeclarationStatement node) {
- names.add(node.getDeclaration().getName().getIdentifier());
- return false;
- }
-
- List getNames() {
- return names;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/OperatorPrecedence.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/OperatorPrecedence.java
deleted file mode 100644
index 8dbdfaa9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/OperatorPrecedence.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression.Operator;
-
-public class OperatorPrecedence {
-
- private static final int ASSIGNMENT= 0;
- private static final int CONDITIONAL= 1;
- private static final int CONDITIONAL_OR= 2;
- private static final int CONDITIONAL_AND= 3;
- private static final int BITWISE_INCLUSIVE_OR= 4;
- private static final int BITWISE_EXCLUSIVE_OR= 5;
- private static final int BITWISE_AND= 6;
- private static final int EQUALITY= 7;
- private static final int RATIONAL= 8;
- private static final int SHIFT= 9;
- private static final int ADDITIVE= 10;
- private static final int MULTIPLICATIVE= 11;
- private static final int PREFIX= 12;
- private static final int POSTFIX= 13;
-
- public static int getValue(Expression expression) {
- if (expression instanceof InfixExpression) {
- return getNormalizedValue((InfixExpression)expression);
- } else if (expression instanceof PostfixExpression) {
- return getNormalizedValue((PostfixExpression)expression);
- } else if (expression instanceof PrefixExpression) {
- return getNormalizedValue((PrefixExpression)expression);
- } else if (expression instanceof Assignment) {
- return getNormalizedValue((Assignment)expression);
- } else if (expression instanceof ConditionalExpression) {
- return getNormalizedValue((ConditionalExpression)expression);
- } else if (expression instanceof InstanceofExpression) {
- return getNormalizedValue((InstanceofExpression)expression);
- }
- return -1;
- }
-
- private static int getNormalizedValue(Assignment ass) {
- return ASSIGNMENT;
- }
-
- private static int getNormalizedValue(ConditionalExpression exp) {
- return CONDITIONAL;
- }
-
- private static int getNormalizedValue(InfixExpression exp) {
- Operator operator= exp.getOperator();
- if (operator == Operator.CONDITIONAL_OR) {
- return CONDITIONAL_OR;
- } else if (operator == Operator.CONDITIONAL_AND) {
- return CONDITIONAL_AND;
- } else if (operator == Operator.OR) {
- return BITWISE_INCLUSIVE_OR;
- } else if (operator == Operator.XOR) {
- return BITWISE_EXCLUSIVE_OR;
- } else if (operator == Operator.AND) {
- return BITWISE_AND;
- } else if (operator == Operator.EQUALS || operator == Operator.NOT_EQUALS) {
- return EQUALITY;
- } else if (operator == Operator.LESS || operator == Operator.LESS_EQUALS || operator == Operator.GREATER || operator == Operator.GREATER_EQUALS) {
- return RATIONAL;
- } else if (operator == Operator.LEFT_SHIFT || operator == Operator.RIGHT_SHIFT_SIGNED || operator == Operator.RIGHT_SHIFT_UNSIGNED) {
- return SHIFT;
- } else if (operator == Operator.PLUS || operator == Operator.MINUS) {
- return ADDITIVE;
- } else if (operator == Operator.REMAINDER || operator == Operator.DIVIDE || operator == Operator.TIMES) {
- return MULTIPLICATIVE;
- }
- return -1;
- }
-
- private static int getNormalizedValue(InstanceofExpression exp) {
- return RATIONAL;
- }
-
- private static int getNormalizedValue(PrefixExpression exp) {
- return PREFIX;
- }
-
- private static int getNormalizedValue(PostfixExpression exp) {
- return POSTFIX;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ParameterData.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ParameterData.java
deleted file mode 100644
index 43108bde..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ParameterData.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-
-/* package */ class ParameterData {
-
- public static final String PROPERTY= ParameterData.class.getName();
-
- private SingleVariableDeclaration fDeclaration;
- private int fAccessMode;
- private List fReferences;
- private int fOperatorPrecedence;
-
- public ParameterData(SingleVariableDeclaration decl) {
- super();
- fDeclaration= decl;
- fAccessMode= FlowInfo.UNUSED;
- fReferences= new ArrayList(2);
- fOperatorPrecedence= -1;
- }
-
- public String getName() {
- return fDeclaration.getName().getIdentifier();
- }
-
- public ITypeBinding getTypeBinding() {
- return fDeclaration.resolveBinding().getType();
- }
-
- public void addReference(ASTNode node) {
- fReferences.add(node);
- }
-
- public List references() {
- return fReferences;
- }
-
- public void setAccessMode(int mode) {
- fAccessMode= mode;
- }
-
- public boolean isUnused() {
- return fAccessMode == FlowInfo.UNUSED;
- }
-
- public boolean isReadOnly() {
- return (fAccessMode & (FlowInfo.READ | FlowInfo.READ_POTENTIAL)) != 0;
- }
-
- public boolean isWrite() {
- return (fAccessMode & (FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN)) != 0;
- }
-
- public int getSimplifiedAccessMode() {
- if (isWrite())
- return FlowInfo.WRITE;
- if (isReadOnly())
- return FlowInfo.READ;
- return FlowInfo.UNUSED;
- }
-
- public int getNumberOfAccesses() {
- return fReferences.size();
- }
-
- public boolean needsEvaluation() {
- if (fReferences.size() <= 1)
- return false;
- return true;
- }
-
- public void setOperatorPrecedence(ASTNode node, int precedence) {
- setOperatorPrecedence(precedence);
- }
-
- private void setOperatorPrecedence(int newValue) {
- if (newValue == -1) {
- fOperatorPrecedence= newValue;
- } else if (fOperatorPrecedence == -1) {
- fOperatorPrecedence= newValue;
- } else {
- fOperatorPrecedence= Math.min(fOperatorPrecedence, newValue);
- }
- }
-
- public int getOperatorPrecedence() {
- return fOperatorPrecedence;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java
deleted file mode 100644
index d395b260..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java
+++ /dev/null
@@ -1,929 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TempDeclarationFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TempOccurrenceAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class PromoteTempToFieldRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_STATIC= "static"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FINAL= "final"; //$NON-NLS-1$
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
- private static final String ATTRIBUTE_INITIALIZE= "initialize"; //$NON-NLS-1$
-
- private int fSelectionStart;
- private int fSelectionLength;
- private IJavaScriptUnit fCu;
-
- public static final int INITIALIZE_IN_FIELD= 0;
- public static final int INITIALIZE_IN_METHOD= 1;
- public static final int INITIALIZE_IN_CONSTRUCTOR= 2;
-
- private static final String LINKED_NAME= "name"; //$NON-NLS-1$
-
- //------ settings ---------//
- private String fFieldName;
- private int fVisibility; /*see Modifier*/
- private boolean fDeclareStatic;
- private boolean fDeclareFinal;
- private int fInitializeIn; /*see INITIALIZE_IN_* constraints */
-
- //------ fields used for computations ---------//
- private JavaScriptUnit fCompilationUnitNode;
- private VariableDeclaration fTempDeclarationNode;
- //------ analysis ---------//
- private boolean fInitializerUsesLocalTypes;
- private boolean fTempTypeUsesClassTypeVariables;
- //------ scripting --------//
- private boolean fSelfInitializing= false;
- private LinkedProposalModel fLinkedProposalModel;
-
- /**
- * Creates a new promote temp to field refactoring.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @param selectionStart
- * @param selectionLength
- */
- public PromoteTempToFieldRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength){
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- fCu= unit;
-
- fFieldName= ""; //$NON-NLS-1$
- fVisibility= Modifier.PRIVATE;
- fDeclareStatic= false;
- fDeclareFinal= false;
- fInitializeIn= INITIALIZE_IN_METHOD;
- fLinkedProposalModel= null;
- }
-
- /**
- * Creates a new promote temp to field refactoring.
- * @param declaration the variable declaration node to convert to a field
- */
- public PromoteTempToFieldRefactoring(VariableDeclaration declaration) {
- Assert.isTrue(declaration != null);
- fTempDeclarationNode= declaration;
- IVariableBinding resolveBinding= declaration.resolveBinding();
- Assert.isTrue(resolveBinding != null && !resolveBinding.isParameter() && !resolveBinding.isField());
-
- ASTNode root= declaration.getRoot();
- Assert.isTrue(root instanceof JavaScriptUnit);
- fCompilationUnitNode= (JavaScriptUnit) root;
-
- IJavaScriptElement input= fCompilationUnitNode.getJavaElement();
- Assert.isTrue(input instanceof IJavaScriptUnit);
- fCu= (IJavaScriptUnit) input;
-
- fSelectionStart= declaration.getStartPosition();
- fSelectionLength= declaration.getLength();
-
- fFieldName= ""; //$NON-NLS-1$
- fVisibility= Modifier.PRIVATE;
- fDeclareStatic= false;
- fDeclareFinal= false;
- fInitializeIn= INITIALIZE_IN_METHOD;
- fLinkedProposalModel= null;
- }
-
- public String getName() {
- return RefactoringCoreMessages.PromoteTempToFieldRefactoring_name;
- }
-
- public int[] getAvailableVisibilities(){
- return new int[]{Modifier.PUBLIC, Modifier.PROTECTED, Modifier.NONE, Modifier.PRIVATE};
- }
-
- public int getVisibility() {
- return fVisibility;
- }
-
- public boolean getDeclareFinal() {
- return fDeclareFinal;
- }
-
- public boolean getDeclareStatic() {
- return fDeclareStatic;
- }
-
- public int getInitializeIn() {
- return fInitializeIn;
- }
-
- public void setVisibility(int accessModifier) {
- Assert.isTrue(accessModifier == Modifier.PRIVATE ||
- accessModifier == Modifier.NONE ||
- accessModifier == Modifier.PROTECTED ||
- accessModifier == Modifier.PUBLIC);
- fVisibility= accessModifier;
- }
-
- public void setDeclareFinal(boolean declareFinal) {
- fDeclareFinal= declareFinal;
- }
-
- public void setDeclareStatic(boolean declareStatic) {
- fDeclareStatic= declareStatic;
- }
-
- public void setFieldName(String fieldName) {
- Assert.isNotNull(fieldName);
- fFieldName= fieldName;
- }
-
- public void setInitializeIn(int initializeIn) {
- Assert.isTrue( initializeIn == INITIALIZE_IN_CONSTRUCTOR ||
- initializeIn == INITIALIZE_IN_FIELD ||
- initializeIn == INITIALIZE_IN_METHOD);
- fInitializeIn= initializeIn;
- }
-
- public boolean canEnableSettingStatic(){
- return fInitializeIn != INITIALIZE_IN_CONSTRUCTOR &&
- ! isTempDeclaredInStaticMethod() &&
- ! fTempTypeUsesClassTypeVariables;
- }
-
- public boolean canEnableSettingFinal(){
- if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
- return canEnableSettingDeclareInConstructors() && ! tempHasAssignmentsOtherThanInitialization();
- else if (fInitializeIn == INITIALIZE_IN_FIELD)
- return canEnableSettingDeclareInFieldDeclaration() && ! tempHasAssignmentsOtherThanInitialization();
- else if (getMethodDeclaration().isConstructor())
- return !tempHasAssignmentsOtherThanInitialization();
- else
- return false;
- }
-
- private boolean tempHasAssignmentsOtherThanInitialization() {
- TempAssignmentFinder assignmentFinder= new TempAssignmentFinder(fTempDeclarationNode);
- fCompilationUnitNode.accept(assignmentFinder);
- return assignmentFinder.hasAssignments();
- }
-
- public boolean canEnableSettingDeclareInConstructors(){
- return ! fDeclareStatic &&
- ! fInitializerUsesLocalTypes &&
- ! getMethodDeclaration().isConstructor() &&
- ! isDeclaredInAnonymousClass() &&
- ! isTempDeclaredInStaticMethod() &&
- tempHasInitializer();
- }
-
- public boolean canEnableSettingDeclareInMethod(){
- return ! fDeclareFinal &&
- tempHasInitializer();
- }
- private boolean tempHasInitializer() {
- return getTempInitializer() != null;
- }
-
- public boolean canEnableSettingDeclareInFieldDeclaration(){
- return ! fInitializerUsesLocalTypes && tempHasInitializer();
- }
-
- private Expression getTempInitializer() {
- return fTempDeclarationNode.getInitializer();
- }
-
- private boolean isTempDeclaredInStaticMethod() {
- return Modifier.isStatic(getMethodDeclaration().getModifiers());
- }
-
- private FunctionDeclaration getMethodDeclaration(){
- return (FunctionDeclaration)ASTNodes.getParent(fTempDeclarationNode, FunctionDeclaration.class);
- }
-
- private boolean isDeclaredInAnonymousClass() {
- return null != ASTNodes.getParent(fTempDeclarationNode, AnonymousClassDeclaration.class);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= Checks.validateModifiesFiles(
- ResourceUtil.getFiles(new IJavaScriptUnit[]{fCu}),
- getValidationContext());
- if (result.hasFatalError())
- return result;
-
- initAST(pm);
-
- if (fTempDeclarationNode == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_select_declaration);
-
- if (! Checks.isDeclaredIn(fTempDeclarationNode, FunctionDeclaration.class))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_only_declared_in_methods);
-
- if (isMethodParameter())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_method_parameters);
-
- if (isTempAnExceptionInCatchBlock())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions);
-
- result.merge(checkTempTypeForLocalTypeUsage());
- if (result.hasFatalError())
- return result;
-
- checkTempInitializerForLocalTypeUsage();
-
- if (!fSelfInitializing)
- initializeDefaults();
- return result;
- }
-
- private void initializeDefaults() {
- fVisibility= Modifier.PRIVATE;
- fDeclareStatic= Modifier.isStatic(getMethodDeclaration().getModifiers());
- fDeclareFinal= false;
- if (canEnableSettingDeclareInMethod())
- fInitializeIn= INITIALIZE_IN_METHOD;
- else if (canEnableSettingDeclareInFieldDeclaration())
- fInitializeIn= INITIALIZE_IN_FIELD;
- else if (canEnableSettingDeclareInConstructors())
- fInitializeIn= INITIALIZE_IN_CONSTRUCTOR;
- }
-
- public String[] guessFieldNames() {
- String rawTempName= StubUtility.removePrefixAndSuffixForVariable(fCu.getJavaScriptProject(), fTempDeclarationNode.resolveBinding());
- String[] excludedNames= getNamesOfFieldsInDeclaringType();
- int dim= ASTNodes.getDimensions(fTempDeclarationNode);
- return StubUtility.getFieldNameSuggestions(fCu.getJavaScriptProject(), rawTempName, dim, getModifiers(), excludedNames);
- }
-
- private String getInitialFieldName() {
- String[] suggestedNames= guessFieldNames();
- if (suggestedNames.length > 0) {
- if (fLinkedProposalModel != null) {
- LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(LINKED_NAME, true);
- for (int i= 0; i < suggestedNames.length; i++) {
- nameGroup.addProposal(suggestedNames[i], null, suggestedNames.length - i);
- }
- }
- return suggestedNames[0];
- } else {
- return fTempDeclarationNode.getName().getIdentifier();
- }
- }
-
- private String[] getNamesOfFieldsInDeclaringType() {
- final AbstractTypeDeclaration type= getEnclosingType();
- if (type instanceof TypeDeclaration) {
- FieldDeclaration[] fields= ((TypeDeclaration) type).getFields();
- List result= new ArrayList(fields.length);
- for (int i= 0; i < fields.length; i++) {
- for (Iterator iter= fields[i].fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment field= (VariableDeclarationFragment) iter.next();
- result.add(field.getName().getIdentifier());
- }
- }
- return (String[]) result.toArray(new String[result.size()]);
- }
- return new String[] {};
- }
-
- private void checkTempInitializerForLocalTypeUsage() {
- Expression initializer= fTempDeclarationNode.getInitializer();
- if (initializer == null)
- return;
-
- LocalTypeAndVariableUsageAnalyzer localTypeAnalyer= new LocalTypeAndVariableUsageAnalyzer(null);
- initializer.accept(localTypeAnalyer);
- fInitializerUsesLocalTypes= ! localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
- }
-
- private RefactoringStatus checkTempTypeForLocalTypeUsage(){
- VariableDeclarationStatement vds= getTempDeclarationStatement();
- if (vds == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
- Type type= vds.getType();
- ITypeBinding binding= type.resolveBinding();
- if (binding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
-
- LocalTypeAndVariableUsageAnalyzer analyzer= new LocalTypeAndVariableUsageAnalyzer(null);
- type.accept(analyzer);
- boolean usesLocalTypes= ! analyzer.getUsageOfEnclosingNodes().isEmpty();
- fTempTypeUsesClassTypeVariables= analyzer.getClassTypeVariablesUsed();
- if (usesLocalTypes)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_uses_type_declared_locally);
- return null;
- }
-
- private VariableDeclarationStatement getTempDeclarationStatement() {
- return (VariableDeclarationStatement) ASTNodes.getParent(fTempDeclarationNode, VariableDeclarationStatement.class);
- }
-
- private boolean isTempAnExceptionInCatchBlock() {
- return (fTempDeclarationNode.getParent() instanceof CatchClause);
- }
-
- private boolean isMethodParameter() {
- return (fTempDeclarationNode.getParent() instanceof FunctionDeclaration);
- }
-
- private void initAST(IProgressMonitor pm){
- if (fCompilationUnitNode == null) {
- fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
- fTempDeclarationNode= TempDeclarationFinder.findTempDeclaration(fCompilationUnitNode, fSelectionStart, fSelectionLength);
- }
- }
-
- public RefactoringStatus validateInput(){
- return Checks.checkFieldName(fFieldName);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- try{
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkClashesWithExistingFields());
- if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
- result.merge(checkClashesInConstructors());
- return result;
- } finally {
- pm.done();
- }
- }
-
- private RefactoringStatus checkClashesInConstructors() {
- Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
- Assert.isTrue(!isDeclaredInAnonymousClass());
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getMethodDeclaration().getParent();
- if (declaration instanceof TypeDeclaration) {
- FunctionDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
- for (int i= 0; i < methods.length; i++) {
- FunctionDeclaration method= methods[i];
- if (!method.isConstructor())
- continue;
- NameCollector nameCollector= new NameCollector(method) {
- protected boolean visitNode(ASTNode node) {
- return true;
- }
- };
- method.accept(nameCollector);
- List names= nameCollector.getNames();
- if (names.contains(fFieldName)) {
- String[] keys= { fFieldName, BindingLabelProvider.getBindingLabel(method.resolveBinding(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- String msg= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict, keys);
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- }
- }
- return null;
- }
-
- private RefactoringStatus checkClashesWithExistingFields(){
- FieldDeclaration[] existingFields= getFieldDeclarations(getBodyDeclarationListOfDeclaringType());
- for (int i= 0; i < existingFields.length; i++) {
- FieldDeclaration declaration= existingFields[i];
- VariableDeclarationFragment[] fragments= (VariableDeclarationFragment[]) declaration.fragments().toArray(new VariableDeclarationFragment[declaration.fragments().size()]);
- for (int j= 0; j < fragments.length; j++) {
- VariableDeclarationFragment fragment= fragments[j];
- if (fFieldName.equals(fragment.getName().getIdentifier())){
- //cannot conflict with more than 1 name
- RefactoringStatusContext context= JavaStatusContext.create(fCu, fragment);
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict_with_field, context);
- }
- }
- }
- return null;
- }
-
- private ChildListPropertyDescriptor getBodyDeclarationListOfDeclaringType(){
- ASTNode methodParent= getMethodDeclaration().getParent();
- if (methodParent instanceof AbstractTypeDeclaration)
- return ((AbstractTypeDeclaration) methodParent).getBodyDeclarationsProperty();
- if (methodParent instanceof AnonymousClassDeclaration)
- return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
- Assert.isTrue(false);
- return null;
- }
-
- private FieldDeclaration[] getFieldDeclarations(ChildListPropertyDescriptor descriptor) {
- final List bodyDeclarations= (List) getMethodDeclaration().getParent().getStructuralProperty(descriptor);
- List fields= new ArrayList(1);
- for (Iterator iter= bodyDeclarations.iterator(); iter.hasNext();) {
- Object each= iter.next();
- if (each instanceof FieldDeclaration)
- fields.add(each);
- }
- return (FieldDeclaration[]) fields.toArray(new FieldDeclaration[fields.size()]);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- if (fFieldName.length() == 0) {
- fFieldName= getInitialFieldName();
- }
-
- ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST());
- if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer())
- addLocalDeclarationSplit(rewrite);
- else
- addLocalDeclarationRemoval(rewrite);
- if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
- addInitializersToConstructors(rewrite);
- addTempRenames(rewrite);
- addFieldDeclaration(rewrite);
- return createChange(rewrite);
- } finally {
- pm.done();
- }
- }
-
- private void addTempRenames(ASTRewrite rewrite) {
- boolean noNameChange= fFieldName.equals(fTempDeclarationNode.getName().getIdentifier());
- if (fLinkedProposalModel == null && noNameChange) {
- return; // no changes needed
- }
- TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(fTempDeclarationNode, false);
- analyzer.perform();
- SimpleName[] tempRefs= analyzer.getReferenceNodes(); // no javadocs (refactoring not for parameters)
-
-
- for (int j= 0; j < tempRefs.length; j++) {
- SimpleName occurence= tempRefs[j];
- if (noNameChange) {
- addLinkedName(rewrite, occurence, false);
- } else {
- SimpleName newName= getAST().newSimpleName(fFieldName);
- addLinkedName(rewrite, newName, false);
- rewrite.replace(occurence, newName, null);
- }
- }
- }
-
- private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
- Assert.isTrue(! isDeclaredInAnonymousClass());
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent();
- final FunctionDeclaration[] constructors= getAllConstructors(declaration);
- if (constructors.length == 0) {
- AST ast= rewrite.getAST();
- FunctionDeclaration newConstructor= ast.newFunctionDeclaration();
- newConstructor.setConstructor(true);
- newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
- newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
- newConstructor.setJavadoc(getNewConstructorComment(rewrite));
- newConstructor.setBody(ast.newBlock());
-
- addFieldInitializationToConstructor(rewrite, newConstructor);
-
- int insertionIndex= computeInsertIndexForNewConstructor(declaration);
- rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
- } else {
- for (int index= 0; index < constructors.length; index++) {
- if (shouldInsertTempInitialization(constructors[index]))
- addFieldInitializationToConstructor(rewrite, constructors[index]);
- }
- }
- }
-
- private String getEnclosingTypeName() {
- return getEnclosingType().getName().getIdentifier();
- }
-
- private AbstractTypeDeclaration getEnclosingType() {
- return (AbstractTypeDeclaration)ASTNodes.getParent(getTempDeclarationStatement(), AbstractTypeDeclaration.class);
- }
-
- private JSdoc getNewConstructorComment(ASTRewrite rewrite) throws CoreException {
- if (StubUtility.doAddComments(fCu.getJavaScriptProject())){
- String comment= CodeGeneration.getMethodComment(fCu, getEnclosingTypeName(), getEnclosingTypeName(), new String[0], new String[0], null, null, StubUtility.getLineDelimiterUsed(fCu));
- if (comment != null && comment.length() > 0) {
- return (JSdoc) rewrite.createStringPlaceholder(comment, ASTNode.JSDOC);
- }
- }
- return null;
- }
-
- private int computeInsertIndexForNewConstructor(AbstractTypeDeclaration declaration) {
- List declarations= declaration.bodyDeclarations();
- if (declarations.isEmpty())
- return 0;
- int index= findFirstMethodIndex(declaration);
- if (index == -1)
- return declarations.size();
- else
- return index;
- }
-
- private int findFirstMethodIndex(AbstractTypeDeclaration typeDeclaration) {
- for (int i= 0, n= typeDeclaration.bodyDeclarations().size(); i < n; i++) {
- if (typeDeclaration.bodyDeclarations().get(i) instanceof FunctionDeclaration)
- return i;
- }
- return -1;
- }
-
- private void addFieldInitializationToConstructor(ASTRewrite rewrite, FunctionDeclaration constructor) throws JavaScriptModelException {
- if (constructor.getBody() == null)
- constructor.setBody(getAST().newBlock());
- ExpressionStatement newStatement= createExpressionStatementThatInitializesField(rewrite);
- rewrite.getListRewrite(constructor.getBody(), Block.STATEMENTS_PROPERTY).insertLast(newStatement, null);
- }
-
- private static boolean shouldInsertTempInitialization(FunctionDeclaration constructor){
- Assert.isTrue(constructor.isConstructor());
- if (constructor.getBody() == null)
- return false;
- List statements= constructor.getBody().statements();
- if (statements == null)
- return false;
- if (statements.size() > 0 && statements.get(0) instanceof ConstructorInvocation)
- return false;
- return true;
- }
-
- private static FunctionDeclaration[] getAllConstructors(AbstractTypeDeclaration typeDeclaration) {
- if (typeDeclaration instanceof TypeDeclaration) {
- FunctionDeclaration[] allMethods= ((TypeDeclaration) typeDeclaration).getMethods();
- List result= new ArrayList(Math.min(allMethods.length, 1));
- for (int i= 0; i < allMethods.length; i++) {
- FunctionDeclaration declaration= allMethods[i];
- if (declaration.isConstructor())
- result.add(declaration);
- }
- return (FunctionDeclaration[]) result.toArray(new FunctionDeclaration[result.size()]);
- }
- return new FunctionDeclaration[] {};
- }
-
- private Change createChange(ASTRewrite rewrite) throws CoreException {
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final IVariableBinding binding= fTempDeclarationNode.resolveBinding();
- final String description= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_descriptor_description_short, binding.getName());
- final String header= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringMethod(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_field_pattern, fFieldName));
- switch (fInitializeIn) {
- case INITIALIZE_IN_CONSTRUCTOR:
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_initialize_constructor);
- break;
- case INITIALIZE_IN_FIELD:
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_initialize_declaration);
- break;
- case INITIALIZE_IN_METHOD:
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_initialize_method);
- break;
- }
- String visibility= JdtFlags.getVisibilityString(fVisibility);
- if ("".equals(visibility)) //$NON-NLS-1$
- visibility= RefactoringCoreMessages.PromoteTempToFieldRefactoring_default_visibility;
- comment.addSetting(Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_visibility_pattern, visibility));
- if (fDeclareFinal && fDeclareStatic)
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_declare_final_static);
- else if (fDeclareFinal)
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_declare_final);
- else if (fDeclareStatic)
- comment.addSetting(RefactoringCoreMessages.PromoteTempToFieldRefactoring_declare_static);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.CONVERT_LOCAL_VARIABLE, project, description, comment.asString(), arguments, RefactoringDescriptor.STRUCTURAL_CHANGE);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fFieldName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_STATIC, Boolean.valueOf(fDeclareStatic).toString());
- arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
- arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
- arguments.put(ATTRIBUTE_INITIALIZE, new Integer(fInitializeIn).toString());
- final CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu);
- result.setDescriptor(new RefactoringChangeDescriptor(descriptor));
- TextEdit resultingEdits= rewrite.rewriteAST();
- TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits);
- return result;
- }
-
- private void addLocalDeclarationSplit(ASTRewrite rewrite) throws JavaScriptModelException {
- VariableDeclarationStatement tempDeclarationStatement= getTempDeclarationStatement();
- Block block= (Block)tempDeclarationStatement.getParent();//XXX can it be anything else?
- int statementIndex= block.statements().indexOf(tempDeclarationStatement);
- Assert.isTrue(statementIndex != -1);
- List fragments= tempDeclarationStatement.fragments();
- int fragmentIndex= fragments.indexOf(fTempDeclarationNode);
- Assert.isTrue(fragmentIndex != -1);
-
- for (int i1= fragmentIndex, n = fragments.size(); i1 < n; i1++) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)fragments.get(i1);
- rewrite.remove(fragment, null);
- }
- if (fragmentIndex == 0)
- rewrite.remove(tempDeclarationStatement, null);
-
- Assert.isTrue(tempHasInitializer());
- rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertAt(createExpressionStatementThatInitializesField(rewrite), statementIndex + 1, null);
-
- if (fragmentIndex + 1 < fragments.size()){
- VariableDeclarationFragment firstFragmentAfter= (VariableDeclarationFragment)fragments.get(fragmentIndex + 1);
- VariableDeclarationFragment copyfirstFragmentAfter= (VariableDeclarationFragment)rewrite.createCopyTarget(firstFragmentAfter);
- VariableDeclarationStatement statement= getAST().newVariableDeclarationStatement(copyfirstFragmentAfter);
- Type type= (Type)rewrite.createCopyTarget(tempDeclarationStatement.getType());
- statement.setType(type);
- List modifiers= tempDeclarationStatement.modifiers();
- if (modifiers.size() > 0) {
- ListRewrite modifiersRewrite= rewrite.getListRewrite(tempDeclarationStatement, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
- ASTNode firstModifier= (ASTNode) modifiers.get(0);
- ASTNode lastModifier= (ASTNode) modifiers.get(modifiers.size() - 1);
- ASTNode modifiersCopy= modifiersRewrite.createCopyTarget(firstModifier, lastModifier);
- statement.modifiers().add(modifiersCopy);
- }
- for (int i= fragmentIndex + 2; i < fragments.size(); i++) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)fragments.get(i);
- VariableDeclarationFragment fragmentCopy= (VariableDeclarationFragment)rewrite.createCopyTarget(fragment);
- statement.fragments().add(fragmentCopy);
- }
- rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertAt(statement, statementIndex + 2, null);
- }
- }
-
- private ExpressionStatement createExpressionStatementThatInitializesField(ASTRewrite rewrite) throws JavaScriptModelException{
- AST ast= getAST();
- Assignment assignment= ast.newAssignment();
- SimpleName fieldName= ast.newSimpleName(fFieldName);
- addLinkedName(rewrite, fieldName, true);
- assignment.setLeftHandSide(fieldName);
- assignment.setRightHandSide(getTempInitializerCopy(rewrite));
- return ast.newExpressionStatement(assignment);
- }
-
- private void addLinkedName(ASTRewrite rewrite, SimpleName fieldName, boolean isFirst) {
- if (fLinkedProposalModel != null) {
- fLinkedProposalModel.getPositionGroup(LINKED_NAME, true).addPosition(rewrite.track(fieldName), isFirst);
- }
- }
-
- private Expression getTempInitializerCopy(ASTRewrite rewrite) throws JavaScriptModelException {
- final Expression initializer= (Expression) rewrite.createCopyTarget(getTempInitializer());
- if (initializer instanceof ArrayInitializer && ASTNodes.getDimensions(fTempDeclarationNode) > 0) {
- ArrayCreation arrayCreation= rewrite.getAST().newArrayCreation();
- arrayCreation.setType((ArrayType) ASTNodeFactory.newType(rewrite.getAST(), fTempDeclarationNode));
- arrayCreation.setInitializer((ArrayInitializer) initializer);
- return arrayCreation;
- }
- return initializer;
- }
-
- private void addLocalDeclarationRemoval(ASTRewrite rewrite) {
- VariableDeclarationStatement tempDeclarationStatement= getTempDeclarationStatement();
- List fragments= tempDeclarationStatement.fragments();
-
- int fragmentIndex= fragments.indexOf(fTempDeclarationNode);
- Assert.isTrue(fragmentIndex != -1);
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)fragments.get(fragmentIndex);
- rewrite.remove(fragment, null);
- if (fragments.size() == 1)
- rewrite.remove(tempDeclarationStatement, null);
- }
-
- private void addFieldDeclaration(ASTRewrite rewrite) {
- final ChildListPropertyDescriptor descriptor= getBodyDeclarationListOfDeclaringType();
- FieldDeclaration[] fields= getFieldDeclarations(getBodyDeclarationListOfDeclaringType());
- final ASTNode parent= getMethodDeclaration().getParent();
- int insertIndex;
- if (fields.length == 0)
- insertIndex= 0;
- else
- insertIndex= ((List) parent.getStructuralProperty(descriptor)).indexOf(fields[fields.length - 1]) + 1;
-
- final FieldDeclaration declaration= createNewFieldDeclaration(rewrite);
- rewrite.getListRewrite(parent, descriptor).insertAt(declaration, insertIndex, null);
- }
-
- private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) {
- AST ast= getAST();
- VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
- SimpleName variableName= ast.newSimpleName(fFieldName);
- fragment.setName(variableName);
- addLinkedName(rewrite, variableName, false);
- fragment.setExtraDimensions(fTempDeclarationNode.getExtraDimensions());
- if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()){
- Expression initializer= (Expression)rewrite.createCopyTarget(getTempInitializer());
- fragment.setInitializer(initializer);
- }
- FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(fragment);
-
- VariableDeclarationStatement vds= getTempDeclarationStatement();
- Type type= (Type)rewrite.createCopyTarget(vds.getType());
- fieldDeclaration.setType(type);
- fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers()));
- return fieldDeclaration;
- }
-
- private int getModifiers() {
- int flags= fVisibility;
- if (fDeclareFinal)
- flags |= Modifier.FINAL;
- if (fDeclareStatic)
- flags |= Modifier.STATIC;
- return flags;
- }
-
- private AST getAST(){
- return fTempDeclarationNode.getAST();
- }
-
- private static class LocalTypeAndVariableUsageAnalyzer extends HierarchicalASTVisitor{
- private final List fLocalDefinitions= new ArrayList(0); // List of IBinding (Variable and Type)
- private final List fLocalReferencesToEnclosing= new ArrayList(0); // List of ASTNodes
- private final List fMethodTypeVariables;
- private boolean fClassTypeVariablesUsed= false;
- public LocalTypeAndVariableUsageAnalyzer(ITypeBinding[] methodTypeVariables) {
- fMethodTypeVariables= Arrays.asList(methodTypeVariables);
- }
- public List getUsageOfEnclosingNodes(){
- return fLocalReferencesToEnclosing;
- }
- public boolean getClassTypeVariablesUsed() {
- return fClassTypeVariablesUsed;
- }
- public boolean visit(SimpleName node) {
- ITypeBinding typeBinding= node.resolveTypeBinding();
- if (typeBinding != null && typeBinding.isLocal()) {
- if (node.isDeclaration()) {
- fLocalDefinitions.add(typeBinding);
- } else if (! fLocalDefinitions.contains(typeBinding)) {
- fLocalReferencesToEnclosing.add(node);
- }
- }
- IBinding binding= node.resolveBinding();
- if (binding != null && binding.getKind() == IBinding.VARIABLE && ! ((IVariableBinding)binding).isField()) {
- if (node.isDeclaration()) {
- fLocalDefinitions.add(binding);
- } else if (! fLocalDefinitions.contains(binding)) {
- fLocalReferencesToEnclosing.add(node);
- }
- }
- return super.visit(node);
- }
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- fSelfInitializing= true;
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.CONVERT_LOCAL_VARIABLE);
- else
- fCu= (IJavaScriptUnit) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= flag;
- }
- final String initialize= extended.getAttribute(ATTRIBUTE_INITIALIZE);
- if (initialize != null && !"".equals(initialize)) {//$NON-NLS-1$
- int value= 0;
- try {
- value= Integer.parseInt(initialize);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INITIALIZE));
- }
- fInitializeIn= value;
- }
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fFieldName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String declareStatic= extended.getAttribute(ATTRIBUTE_STATIC);
- if (declareStatic != null) {
- fDeclareStatic= Boolean.valueOf(declareStatic).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_STATIC));
- final String declareFinal= extended.getAttribute(ATTRIBUTE_FINAL);
- if (declareFinal != null) {
- fDeclareFinal= Boolean.valueOf(declareFinal).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FINAL));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
-
- public void setLinkedProposalModel(LinkedProposalModel model) {
- fLinkedProposalModel= model;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ReplaceInvocationsRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ReplaceInvocationsRefactoring.java
deleted file mode 100644
index f0547f40..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ReplaceInvocationsRefactoring.java
+++ /dev/null
@@ -1,554 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.binary.StubCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ReplaceInvocationsRefactoring extends ScriptableRefactoring {
-
- private static final String ID_REPLACE_INVOCATIONS= "org.eclipse.wst.jsdt.ui.replace.invocations"; //$NON-NLS-1$
- private static final String ATTRIBUTE_MODE= "mode"; //$NON-NLS-1$
-
- public static class Mode {
- private Mode() {
- }
- public static final Mode REPLACE_ALL= new Mode();
- public static final Mode REPLACE_SINGLE= new Mode();
- }
-
- private final ITypeRoot fSelectionTypeRoot;
- /**
- * only set if initial mode is REPLACE_SINGLE
- */
- private final int fSelectionStart;
- /**
- * only set if initial mode is REPLACE_SINGLE
- */
- private final int fSelectionLength;
-
- private ASTNode fSelectionNode;
- /**
- * only set after checkInitialConditions
- */
- private IFunction fMethod;
-
- private String fBody;
- private String[] fParameterNames;
-
- private SourceProvider fSourceProvider; // resolved once in checkInitialConditions
- private TargetProvider fTargetProvider; // flexible
-
- private TextChangeManager fChangeManager;
- private IFunctionBinding fMethodBinding;
-
- public ReplaceInvocationsRefactoring(ITypeRoot typeRoot, int offset, int length) {
- fSelectionTypeRoot= typeRoot;
- fSelectionStart= offset;
- fSelectionLength= length;
- }
-
- public ReplaceInvocationsRefactoring(IFunction method) {
- fMethod= method;
- fSelectionTypeRoot= method.getTypeRoot();
- fSelectionStart= -1;
- fSelectionLength= -1;
- }
-
- public String getName() {
- return RefactoringCoreMessages.ReplaceInvocationsRefactoring_name;
- }
-
- /**
- * Only to be called after {@link #checkInitialConditions(IProgressMonitor)}
- */
- public boolean canReplaceSingle() {
- return fSelectionNode instanceof FunctionInvocation;
- }
-
- /**
- * Only to be called after {@link #checkInitialConditions(IProgressMonitor)}
- */
- public RefactoringStatus setCurrentMode(Mode mode) throws JavaScriptModelException {
- if (fTargetProvider.isSingle() == (mode == Mode.REPLACE_SINGLE))
- return new RefactoringStatus();
- Assert.isTrue(canReplaceSingle());
- if (mode == Mode.REPLACE_SINGLE) {
- fTargetProvider= TargetProvider.create((IJavaScriptUnit) fSelectionTypeRoot, (FunctionInvocation) fSelectionNode);
- } else {
- fTargetProvider= TargetProvider.create(fSourceProvider.getDeclaration());
- }
- return fTargetProvider.checkActivation();
- }
-
- public void setBody(String body, String[] parameterNames) {
- //TODO: validate parameter name count and body
- fBody= body;
- fParameterNames= parameterNames;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- // TargetProvider must get an untampered AST with original invocation node
- // SourceProvider must get a tweaked AST with method body / parameter names replaced
-
- RefactoringStatus result= new RefactoringStatus();
-
- if (fMethod == null) {
- if (! (fSelectionTypeRoot instanceof IJavaScriptUnit))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_replace_in_binary);
-
- IJavaScriptUnit cu= (IJavaScriptUnit) fSelectionTypeRoot;
- JavaScriptUnit root= new RefactoringASTParser(AST.JLS3).parse(cu, true);
- fSelectionNode= getTargetNode(cu, root, fSelectionStart, fSelectionLength);
- if (fSelectionNode == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_select_method_to_apply);
-
- if (fSelectionNode.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) fSelectionNode;
- fTargetProvider= TargetProvider.create(methodDeclaration);
- fMethodBinding= methodDeclaration.resolveBinding();
- } else {
- FunctionInvocation methodInvocation= (FunctionInvocation) fSelectionNode;
- fTargetProvider= TargetProvider.create(cu, methodInvocation);
- fMethodBinding= methodInvocation.resolveMethodBinding();
- }
- if (fMethodBinding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
- fMethod= (IFunction) fMethodBinding.getJavaElement();
-
- } else {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(fMethod.getJavaScriptProject());
- IBinding[] bindings= parser.createBindings(new IJavaScriptElement[] { fMethod }, null);
- fMethodBinding= (IFunctionBinding) bindings[0];
- if (fMethodBinding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
-
- fTargetProvider= TargetProvider.create(fMethodBinding);
- }
-
- result.merge(fTargetProvider.checkActivation());
- return result;
- }
-
- private SourceProvider resolveSourceProvider(IFunctionBinding methodBinding, RefactoringStatus status) throws JavaScriptModelException {
- final IFunction method= (IFunction) methodBinding.getJavaElement();
-
- ITypeRoot typeRoot;
- IDocument source;
- JavaScriptUnit methodDeclarationAstRoot;
-
- IJavaScriptUnit methodCu= (method).getJavaScriptUnit();
- if (methodCu != null) {
- typeRoot= methodCu;
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(methodCu);
- parser.setFocalPosition(method.getNameRange().getOffset());
- JavaScriptUnit compilationUnit= (JavaScriptUnit) parser.createAST(null);
- FunctionDeclaration methodDecl= (FunctionDeclaration) NodeFinder.perform(compilationUnit, method.getNameRange()).getParent();
- AST ast= compilationUnit.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- Block newBody= ast.newBlock();
- newBody.statements().add(rewrite.createStringPlaceholder(fBody, ASTNode.EMPTY_STATEMENT));
- rewrite.replace(methodDecl.getBody(), newBody, null);
- List parameters= methodDecl.parameters();
- for (int i= 0; i < parameters.size(); i++) {
- SingleVariableDeclaration parameter= (SingleVariableDeclaration) parameters.get(i);
- rewrite.set(parameter.getName(), SimpleName.IDENTIFIER_PROPERTY, fParameterNames[i], null);
- }
- TextEdit textEdit= rewrite.rewriteAST();
- Document document= new Document(methodCu.getBuffer().getContents());
- try {
- textEdit.apply(document);
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- source= document;
-
- methodDeclarationAstRoot= new RefactoringASTParser(AST.JLS3).parse(source.get(), methodCu, true, true, null);
-
- } else {
- IClassFile classFile= method.getClassFile();
- //TODO: use source if available?
- StubCreator stubCreator= new StubCreator(true) {
- protected void appendMethodBody(IFunction currentMethod) throws JavaScriptModelException {
- if (currentMethod.equals(method)) {
- fBuffer.append(fBody);
- } else {
- super.appendMethodBody(currentMethod);
- }
- }
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.binary.StubCreator#appendMethodParameterName(org.eclipse.wst.jsdt.core.IFunction, int)
- */
- protected void appendMethodParameterName(IFunction currentMethod, int index) {
- if (currentMethod.equals(method)) {
- fBuffer.append(fParameterNames[index]);
- } else {
- super.appendMethodParameterName(currentMethod, index);
- }
- }
- };
-
- String stub= stubCreator.createStub(classFile.getType(), null);
- source= new Document(stub);
- methodDeclarationAstRoot= new RefactoringASTParser(AST.JLS3).parse(stub, classFile, true, true, null);
- typeRoot= classFile;
- }
- ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getKey());
- if (node instanceof FunctionDeclaration) {
- return new SourceProvider(typeRoot, source, (FunctionDeclaration) node);
- } else {
- status.addFatalError(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_find_method_declaration);
- return null;
- }
- }
-
- /**
- * @return an invocation or declaration node
- */
- private static ASTNode getTargetNode(IJavaScriptUnit unit, JavaScriptUnit root, int offset, int length) {
- ASTNode node= null;
- try {
- node= checkNode(NodeFinder.perform(root, offset, length, unit), unit);
- } catch(JavaScriptModelException e) {
- // Do nothing
- }
- if (node != null)
- return node;
- return checkNode(NodeFinder.perform(root, offset, length), unit);
- }
-
- private static ASTNode checkNode(ASTNode node, IJavaScriptUnit unit) {
- if (node == null)
- return null;
- if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
- node= node.getParent();
- } else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
- node= ((ExpressionStatement)node).getExpression();
- }
- switch(node.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- case ASTNode.FUNCTION_INVOCATION:
-// not yet...
-// case ASTNode.SUPER_METHOD_INVOCATION:
-// case ASTNode.CONSTRUCTOR_INVOCATION:
- return node;
- }
- return null;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 20); //$NON-NLS-1$
- fChangeManager= new TextChangeManager();
- RefactoringStatus result= new RefactoringStatus();
-
- fSourceProvider= resolveSourceProvider(fMethodBinding, result);
- if (result.hasFatalError())
- return result;
-
- result.merge(fSourceProvider.checkActivation());
- if (result.hasFatalError())
- return result;
-
- fSourceProvider.initialize();
- fTargetProvider.initialize();
- pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
- RefactoringStatus searchStatus= new RefactoringStatus();
- IJavaScriptUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, new SubProgressMonitor(pm, 1));
- if (searchStatus.hasFatalError()) {
- result.merge(searchStatus);
- return result;
- }
- IFile[] filesToBeModified= getFilesToBeModified(units);
- result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
- if (result.hasFatalError())
- return result;
- result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
- checkOverridden(result, new SubProgressMonitor(pm, 4));
- IProgressMonitor sub= new SubProgressMonitor(pm, 15);
- sub.beginTask("", units.length * 3); //$NON-NLS-1$
- for (int c= 0; c < units.length; c++) {
- IJavaScriptUnit unit= units[c];
- sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, unit.getElementName()));
- CallInliner inliner= null;
- try {
- boolean added= false;
- MultiTextEdit root= new MultiTextEdit();
- CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
- change.setEdit(root);
- BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
- if (bodies.length == 0)
- continue;
- inliner= new CallInliner(unit, (JavaScriptUnit) bodies[0].getRoot(), fSourceProvider);
- for (int b= 0; b < bodies.length; b++) {
- BodyDeclaration body= bodies[b];
- inliner.initialize(body);
- RefactoringStatus nestedInvocations= new RefactoringStatus();
- ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
- fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
- for (int i= 0; i < invocations.length; i++) {
- ASTNode invocation= invocations[i];
- result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
- if (result.hasFatalError())
- break;
- if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
- added= true;
- TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
- change.addTextEditGroup(group);
- result.merge(inliner.perform(group));
- }
- }
- // do this after we have inlined the method calls. We still want
- // to generate the modifications.
- result.merge(nestedInvocations);
- }
- if (!added) {
- fChangeManager.remove(unit);
- } else {
- root.addChild(inliner.getModifications());
- ImportRewrite rewrite= inliner.getImportEdit();
- if (rewrite.hasRecordedChanges()) {
- TextEdit edit= rewrite.rewriteImports(null);
- if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
- root.addChild(edit);
- change.addTextEditGroup(
- new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
- }
- }
- }
- } finally {
- if (inliner != null)
- inliner.dispose();
- }
- sub.worked(1);
- if (sub.isCanceled())
- throw new OperationCanceledException();
- }
- result.merge(searchStatus);
- sub.done();
- pm.done();
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- // TODO: update for fSelectionStart == -1
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fSelectionTypeRoot.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final IFunctionBinding binding= fSourceProvider.getDeclaration().resolveBinding();
- int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- if (!Modifier.isPrivate(binding.getModifiers()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- final String description= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description_short, binding.getName());
- final String header= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringClass(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- if (!fTargetProvider.isSingle())
- comment.addSetting(RefactoringCoreMessages.ReplaceInvocationsRefactoring_replace_references);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(ID_REPLACE_INVOCATIONS, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fSelectionTypeRoot));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_MODE, new Integer(fTargetProvider.isSingle() ? 0 : 1).toString());
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ReplaceInvocationsRefactoring_change_name, fChangeManager.getAllChanges());
- }
-
- private IFile[] getFilesToBeModified(IJavaScriptUnit[] units) {
- List result= new ArrayList(units.length + 1);
- IFile file;
- for (int i= 0; i < units.length; i++) {
- file= getFile(units[i]);
- if (file != null)
- result.add(file);
- }
- return (IFile[])result.toArray(new IFile[result.size()]);
- }
-
- private IFile getFile(IJavaScriptUnit unit) {
- unit= unit.getPrimary();
- IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE)
- return (IFile)resource;
- return null;
- }
-
- private void checkOverridden(RefactoringStatus status, IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 9); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
- FunctionDeclaration decl= fSourceProvider.getDeclaration();
- IFunction method= (IFunction) decl.resolveBinding().getJavaElement();
- if (method == null || Flags.isPrivate(method.getFlags())) {
- pm.worked(8);
- return;
- }
- IType type= method.getDeclaringType();
- ITypeHierarchy hierarchy= type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
- checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
- checkSuperClasses(status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
- pm.setTaskName(""); //$NON-NLS-1$
- }
-
- private void checkSubTypes(RefactoringStatus result, IFunction method, IType[] types, IProgressMonitor pm) {
- checkTypes(
- result, method, types,
- RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden_error,
- pm);
- }
-
- private void checkSuperClasses(RefactoringStatus result, IFunction method, IType[] types, IProgressMonitor pm) {
- checkTypes(
- result, method, types,
- RefactoringCoreMessages.InlineMethodRefactoring_checking_overrides_error,
- pm);
- }
-
- private void checkTypes(RefactoringStatus result, IFunction method, IType[] types, String key, IProgressMonitor pm) {
- pm.beginTask("", types.length); //$NON-NLS-1$
- for (int i= 0; i < types.length; i++) {
- pm.worked(1);
- IFunction[] overridden= types[i].findMethods(method);
- if (overridden != null && overridden.length > 0) {
- result.addError(
- Messages.format(key, types[i].getElementName()),
- JavaStatusContext.create(overridden[0]));
- }
- }
- }
-
- private ASTNode[] removeNestedCalls(RefactoringStatus status, IJavaScriptUnit unit, ASTNode[] invocations) {
- if (invocations.length <= 1)
- return invocations;
- ASTNode[] parents= new ASTNode[invocations.length];
- for (int i= 0; i < invocations.length; i++) {
- parents[i]= invocations[i].getParent();
- }
- for (int i= 0; i < invocations.length; i++) {
- removeNestedCalls(status, unit, parents, invocations, i);
- }
- List result= new ArrayList();
- for (int i= 0; i < invocations.length; i++) {
- if (invocations[i] != null)
- result.add(invocations[i]);
- }
- return (ASTNode[])result.toArray(new ASTNode[result.size()]);
- }
-
- private void removeNestedCalls(RefactoringStatus status, IJavaScriptUnit unit, ASTNode[] parents, ASTNode[] invocations, int index) {
- ASTNode invocation= invocations[index];
- for (int i= 0; i < parents.length; i++) {
- ASTNode parent= parents[i];
- while (parent != null) {
- if (parent == invocation) {
- status.addError(RefactoringCoreMessages.InlineMethodRefactoring_nestedInvocation,
- JavaStatusContext.create(unit, parent));
- invocations[index]= null;
- }
- parent= parent.getParent();
- }
- }
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments generic= (JavaRefactoringArguments) arguments;
- final String value= generic.getAttribute(ATTRIBUTE_MODE);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- int mode= 0;
- try {
- mode= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MODE));
- }
- try {
- setCurrentMode(mode == 1 ? Mode.REPLACE_ALL : Mode.REPLACE_SINGLE);
- } catch (JavaScriptModelException exception) {
- return RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage());
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- public IFunction getMethod() {
- return fMethod;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ScriptableRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ScriptableRefactoring.java
deleted file mode 100644
index 4204601e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ScriptableRefactoring.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Partial implementation of a scriptable refactoring which provides a comment
- * for the history.
- *
- *
- */
-public abstract class ScriptableRefactoring extends Refactoring implements IScriptableRefactoring, ICommentProvider {
-
- /**
- * Creates a fatal error status telling that the input element does not
- * exist.
- *
- * @param element
- * the input element, or <code>null</code>
- * @param name
- * the name of the refactoring
- * @param id
- * the id of the refactoring
- * @return the refactoring status
- */
- public static RefactoringStatus createInputFatalStatus(final Object element, final String name, final String id) {
- Assert.isNotNull(name);
- Assert.isNotNull(id);
- if (element != null)
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_input_not_exists, new String[] { JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), name, id}));
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_inputs_do_not_exist, new String[] { name, id}));
- }
-
- /**
- * Creates a warning status telling that the input element does not exist.
- *
- * @param element
- * the input element, or <code>null</code>
- * @param name
- * the name of the refactoring
- * @param id
- * the id of the refactoring
- * @return the refactoring status
- */
- public static RefactoringStatus createInputWarningStatus(final Object element, final String name, final String id) {
- Assert.isNotNull(name);
- Assert.isNotNull(id);
- if (element != null)
- return RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_input_not_exists, new String[] { JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), name, id}));
- else
- return RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_inputs_do_not_exist, new String[] { name, id}));
- }
-
- /** The comment */
- private String fComment;
-
- /**
- * {@inheritDoc}
- */
- public boolean canEnableComment() {
- return true;
- }
-
- /**
- * Creates a fatal error status telling that the input element does not
- * exist.
- *
- * @param element
- * the input element, or <code>null</code>
- * @param id
- * the id of the refactoring
- * @return the refactoring status
- */
- public final RefactoringStatus createInputFatalStatus(final Object element, final String id) {
- return createInputFatalStatus(element, getName(), id);
- }
-
- /**
- * Creates a warning status telling that the input element does not exist.
- *
- * @param element
- * the input element, or <code>null</code>
- * @param id
- * the id of the refactoring
- * @return the refactoring status
- */
- public final RefactoringStatus createInputWarningStatus(final Object element, final String id) {
- return createInputWarningStatus(element, getName(), id);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getComment() {
- return fComment;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setComment(String comment) {
- fComment= comment;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SnippetFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SnippetFinder.java
deleted file mode 100644
index 81b6c922..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SnippetFinder.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTMatcher;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-
-
-/* package */ class SnippetFinder extends GenericVisitor {
-
- public static class Match {
- private List fNodes;
- private Map fLocalMappings;
-
- public Match() {
- fNodes= new ArrayList(10);
- fLocalMappings= new HashMap();
- }
- public void add(ASTNode node) {
- fNodes.add(node);
- }
- public boolean hasCorrectNesting(ASTNode node) {
- if (fNodes.size() == 0)
- return true;
- ASTNode parent= node.getParent();
- if(((ASTNode)fNodes.get(0)).getParent() != parent)
- return false;
- // Here we know that we have two elements. In this case the
- // parent must be a block or a switch statement. Otherwise a
- // snippet like "if (true) foo(); else foo();" would match
- // the pattern "foo(); foo();"
- int nodeType= parent.getNodeType();
- return nodeType == ASTNode.BLOCK || nodeType == ASTNode.SWITCH_STATEMENT;
- }
- public ASTNode[] getNodes() {
- return (ASTNode[])fNodes.toArray(new ASTNode[fNodes.size()]);
- }
- public void addLocal(IVariableBinding org, SimpleName local) {
- fLocalMappings.put(org, local);
- }
- public SimpleName getMappedName(IVariableBinding org) {
- return (SimpleName)fLocalMappings.get(org);
- }
- public IVariableBinding getMappedBinding(IVariableBinding org) {
- SimpleName name= (SimpleName) fLocalMappings.get(org);
- return ASTNodes.getVariableBinding(name);
- }
- public boolean isEmpty() {
- return fNodes.isEmpty() && fLocalMappings.isEmpty();
- }
- /**
- * Tests if the whole duplicate is the full body of a method. If so
- * don't replace it since we would replace a method body with a new
- * method body which doesn't make to much sense.
- *
- * @return whether the duplicte is the whole method body
- */
- public boolean isMethodBody() {
- ASTNode first= (ASTNode)fNodes.get(0);
- if (first.getParent() == null)
- return false;
- ASTNode candidate= first.getParent().getParent();
- if (candidate == null || candidate.getNodeType() != ASTNode.FUNCTION_DECLARATION)
- return false;
- FunctionDeclaration method= (FunctionDeclaration)candidate;
- return method.getBody().statements().size() == fNodes.size();
- }
- public FunctionDeclaration getEnclosingMethod() {
- ASTNode first= (ASTNode)fNodes.get(0);
- return (FunctionDeclaration)ASTNodes.getParent(first, ASTNode.FUNCTION_DECLARATION);
- }
- }
-
- private class Matcher extends ASTMatcher {
- public boolean match(SimpleName candidate, Object s) {
- if (!(s instanceof SimpleName))
- return false;
-
- SimpleName snippet= (SimpleName)s;
- if (candidate.isDeclaration() != snippet.isDeclaration())
- return false;
-
- IBinding cb= candidate.resolveBinding();
- IBinding sb= snippet.resolveBinding();
- if (cb == null || sb == null)
- return false;
- IVariableBinding vcb= ASTNodes.getVariableBinding(candidate);
- IVariableBinding vsb= ASTNodes.getVariableBinding(snippet);
- if (vcb == null || vsb == null)
- return Bindings.equals(cb, sb);
- if (!vcb.isField() && !vsb.isField() && Bindings.equals(vcb.getType(), vsb.getType())) {
- SimpleName mapped= fMatch.getMappedName(vsb);
- if (mapped != null) {
- IVariableBinding mappedBinding= ASTNodes.getVariableBinding(mapped);
- if (!Bindings.equals(vcb, mappedBinding))
- return false;
- }
- fMatch.addLocal(vsb, candidate);
- return true;
- }
- return Bindings.equals(cb, sb);
- }
- }
-
- private List fResult= new ArrayList(2);
- private Match fMatch;
- private ASTNode[] fSnippet;
- private int fIndex;
- private Matcher fMatcher;
- private int fTypes;
-
- private SnippetFinder(ASTNode[] snippet) {
- super(true);
- fSnippet= snippet;
- fMatcher= new Matcher();
- reset();
- }
-
- public static Match[] perform(ASTNode start, ASTNode[] snippet) {
- Assert.isTrue(start instanceof JavaScriptUnit || start instanceof AbstractTypeDeclaration || start instanceof AnonymousClassDeclaration);
- SnippetFinder finder= new SnippetFinder(snippet);
- start.accept(finder);
- for (Iterator iter = finder.fResult.iterator(); iter.hasNext();) {
- Match match = (Match)iter.next();
- ASTNode[] nodes= match.getNodes();
- // doesn't match if the candidate is the left hand side of an
- // assignment and the snippet consists of a single node.
- // Otherwise y= i; i= z; results in y= e(); e()= z;
- if (nodes.length == 1 && isLeftHandSideOfAssignment(nodes[0])) {
- iter.remove();
- }
- }
- return (Match[])finder.fResult.toArray(new Match[finder.fResult.size()]);
- }
-
- private static boolean isLeftHandSideOfAssignment(ASTNode node) {
- ASTNode parent= node.getParent();
- return parent != null && parent.getNodeType() == ASTNode.ASSIGNMENT && ((Assignment)parent).getLeftHandSide() == node;
- }
-
- public boolean visit(TypeDeclaration node) {
- if (++fTypes > 1)
- return false;
- return super.visit(node);
- }
-
- public void endVisit(TypeDeclaration node) {
- --fTypes;
- super.endVisit(node);
- }
-
- protected boolean visitNode(ASTNode node) {
- if (matches(node)) {
- return false;
- } else if (!isResetted()){
- reset();
- if (matches(node))
- return false;
- }
- return true;
- }
-
- private boolean matches(ASTNode node) {
- if (isSnippetNode(node))
- return false;
- if (node.subtreeMatch(fMatcher, fSnippet[fIndex]) && fMatch.hasCorrectNesting(node)) {
- fMatch.add(node);
- fIndex++;
- if (fIndex == fSnippet.length) {
- fResult.add(fMatch);
- reset();
- }
- return true;
- }
- return false;
- }
-
- private boolean isResetted() {
- return fIndex == 0 && fMatch.isEmpty();
- }
-
- private void reset() {
- fIndex= 0;
- fMatch= new Match();
- }
-
- private boolean isSnippetNode(ASTNode node) {
- for (int i= 0; i < fSnippet.length; i++) {
- if (node == fSnippet[i])
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceAnalyzer.java
deleted file mode 100644
index 4f5ad6ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceAnalyzer.java
+++ /dev/null
@@ -1,465 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for:
- * o bug "Inline refactoring showed bogus error" (see bugzilla
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=42753)
- * o Allow 'this' constructor to be inlined
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ImportReferencesCollector;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.LocalVariableIndex;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer;
-
-class SourceAnalyzer {
-
- public static class NameData {
- private String fName;
- private List fReferences;
- public NameData(String n) {
- fName= n;
- fReferences= new ArrayList(2);
- }
- public String getName() {
- return fName;
- }
- public void addReference(SimpleName ref) {
- fReferences.add(ref);
- }
- public List references() {
- return fReferences;
- }
- }
-
- private class ActivationAnalyzer extends ASTVisitor {
- public RefactoringStatus status= new RefactoringStatus();
- private ASTNode fLastNode= getLastNode();
- private IFunctionBinding fBinding= getBinding();
- public boolean visit(ReturnStatement node) {
- if (node != fLastNode) {
- fInterruptedExecutionFlow= true;
- }
- return true;
- }
- public boolean visit(TypeDeclaration node) {
- return false;
- }
- public boolean visit(AnonymousClassDeclaration node) {
- return false;
- }
- public boolean visit(FunctionInvocation node) {
- IFunctionBinding methodBinding= node.resolveMethodBinding();
- if (methodBinding != null)
- methodBinding.getMethodDeclaration();
- if (fBinding != null && methodBinding != null && fBinding.isEqualTo(methodBinding) && !status.hasFatalError()) {
- status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_recursive_call);
- return false;
- }
- return true;
- }
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (binding == null && !status.hasFatalError()) {
- // fixes bug #42753
- if (!ASTNodes.isLabel(node)) {
- status.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors,
- JavaStatusContext.create(fTypeRoot, fDeclaration));
- return false;
- }
- }
- return true;
- }
- public boolean visit(ThisExpression node) {
- if (node.getQualifier() != null) {
- status.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_qualified_this_expressions,
- JavaStatusContext.create(fTypeRoot, node));
- return false;
- }
- return true;
- }
- private ASTNode getLastNode() {
- List statements= fDeclaration.getBody().statements();
- if (statements.size() == 0)
- return null;
- return (ASTNode)statements.get(statements.size() - 1);
- }
- private IFunctionBinding getBinding() {
- IFunctionBinding result= fDeclaration.resolveBinding();
- if (result != null)
- return result.getMethodDeclaration();
- return result;
- }
- }
-
- private class UpdateCollector extends ASTVisitor {
- private int fTypeCounter;
- public boolean visit(TypeDeclaration node) {
- return visitType(node);
- }
- public void endVisit(TypeDeclaration node) {
- fTypeCounter--;
- }
- private boolean visitType(AbstractTypeDeclaration node) {
- if (fTypeCounter++ == 0) {
- addNameReference(node.getName());
- }
- return true;
- }
- public boolean visit(AnonymousClassDeclaration node) {
- fTypeCounter++;
- return true;
- }
- public void endVisit(AnonymousClassDeclaration node) {
- fTypeCounter--;
- }
- public boolean visit(FieldAccess node) {
- // only visit the expression and not the simple name
- node.getExpression().accept(this);
- addReferencesToName(node.getName());
- return false;
- }
- public boolean visit(FunctionDeclaration node) {
- if (node.isConstructor()) {
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
- NameData name= (NameData)fNames.get(decl.getName().resolveBinding());
- if (name != null) {
- name.addReference(node.getName());
- }
- }
- return true;
- }
- public boolean visit(FunctionInvocation node) {
- if (fTypeCounter == 0) {
- Expression receiver= node.getExpression();
- if (receiver == null && !isStaticallyImported(node.getName())) {
- fImplicitReceivers.add(node);
- }
- }
- return true;
- }
- public boolean visit(SuperMethodInvocation node) {
- if (fTypeCounter == 0) {
- fHasSuperMethodInvocation= true;
- }
- return true;
- }
- public boolean visist(SuperConstructorInvocation node) {
- if (fTypeCounter == 0) {
- fHasSuperMethodInvocation= true;
- }
- return true;
- }
- public boolean visit(ClassInstanceCreation node) {
- if (fTypeCounter == 0) {
- Expression receiver= node.getExpression();
- if (receiver == null) {
- if (node.resolveTypeBinding().isLocal())
- fImplicitReceivers.add(node);
- }
- }
- return true;
- }
- public boolean visit(SingleVariableDeclaration node) {
- if (fTypeCounter == 0)
- addNameReference(node.getName());
- return true;
- }
- public boolean visit(VariableDeclarationFragment node) {
- if (fTypeCounter == 0)
- addNameReference(node.getName());
- return true;
- }
- public boolean visit(SimpleName node) {
- addReferencesToName(node);
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding) {
- IVariableBinding vb= (IVariableBinding)binding;
- if (vb.isField() && ! isStaticallyImported(node)) {
- Name topName= ASTNodes.getTopMostName(node);
- if (node == topName || node == ASTNodes.getLeftMostSimpleName(topName)) {
- StructuralPropertyDescriptor location= node.getLocationInParent();
- if (location != SingleVariableDeclaration.NAME_PROPERTY
- && location != VariableDeclarationFragment.NAME_PROPERTY) {
- fImplicitReceivers.add(node);
- }
- }
- } else if (!vb.isField()) {
- // we have a local. Check if it is a parameter.
- ParameterData data= (ParameterData)fParameters.get(binding);
- if (data != null) {
- ASTNode parent= node.getParent();
- if (parent instanceof Expression) {
- int precedence= OperatorPrecedence.getValue((Expression)parent);
- if (precedence != -1) {
- data.setOperatorPrecedence(node, precedence);
- }
- }
- }
- }
- }
- return true;
- }
- public boolean visit(ThisExpression node) {
- if (fTypeCounter == 0) {
- fImplicitReceivers.add(node);
- }
- return true;
- }
- private void addReferencesToName(SimpleName node) {
- IBinding binding= node.resolveBinding();
- ParameterData data= (ParameterData)fParameters.get(binding);
- if (data != null)
- data.addReference(node);
-
- NameData name= (NameData)fNames.get(binding);
- if (name != null)
- name.addReference(node);
- }
- private void addNameReference(SimpleName name) {
- fNames.put(name.resolveBinding(), new NameData(name.getIdentifier()));
- }
- private void addTypeVariableReference(ITypeBinding variable, SimpleName name) {
- NameData data= (NameData)fTypeParameterMapping.get(variable);
- if (data == null) {
- data= (NameData)fMethodTypeParameterMapping.get(variable);
- }
- data.addReference(name);
- }
- private boolean isStaticallyImported(Name name) {
- return fStaticsToImport.contains(name);
- }
- }
-
- private class VarargAnalyzer extends ASTVisitor {
- private IBinding fParameter;
- public VarargAnalyzer(IBinding parameter) {
- fParameter= parameter;
- }
- public boolean visit(ArrayAccess node) {
- Expression array= node.getArray();
- if (array instanceof SimpleName && fParameter.isEqualTo(((SimpleName)array).resolveBinding())) {
- fArrayAccess= true;
- }
- return true;
- }
- }
-
- private ITypeRoot fTypeRoot;
- private FunctionDeclaration fDeclaration;
- private Map fParameters;
- private Map fNames;
- private List fImplicitReceivers;
-
- private boolean fArrayAccess;
- private boolean fHasSuperMethodInvocation;
-
- private List/*<Name>*/ fTypesToImport;
- private List/*<Name>*/ fStaticsToImport;
-
- private List/*<NameData>*/ fTypeParameterReferences;
- private Map/*<ITypeBinding, NameData>*/ fTypeParameterMapping;
-
- private List/*<NameData>*/ fMethodTypeParameterReferences;
- private Map/*<ITypeBinding, NameData>*/ fMethodTypeParameterMapping;
-
- private boolean fInterruptedExecutionFlow;
-
- public SourceAnalyzer(ITypeRoot typeRoot, FunctionDeclaration declaration) {
- super();
- fTypeRoot= typeRoot;
- fDeclaration= declaration;
- }
-
- public boolean isExecutionFlowInterrupted() {
- return fInterruptedExecutionFlow;
- }
-
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- if (!fTypeRoot.isStructureKnown()) {
- result.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_syntax_errors,
- JavaStatusContext.create(fTypeRoot));
- return result;
- }
- IProblem[] problems= ASTNodes.getProblems(fDeclaration, ASTNodes.NODE_ONLY, ASTNodes.ERROR);
- if (problems.length > 0) {
- result.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors,
- JavaStatusContext.create(fTypeRoot, fDeclaration));
- return result;
- }
- final IFunctionBinding declarationBinding= fDeclaration.resolveBinding();
- if (declarationBinding != null) {
- final int modifiers= declarationBinding.getModifiers();
- if (Modifier.isAbstract(modifiers)) {
- result.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_abstract_methods, JavaStatusContext.create(fTypeRoot, fDeclaration));
- return result;
- } else if (Modifier.isNative(modifiers)) {
- result.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_native_methods, JavaStatusContext.create(fTypeRoot, fDeclaration));
- return result;
- }
- } else {
- result.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_methoddeclaration_has_errors, JavaStatusContext.create(fTypeRoot));
- return result;
- }
- ActivationAnalyzer analyzer= new ActivationAnalyzer();
- fDeclaration.accept(analyzer);
- result.merge(analyzer.status);
- if (!result.hasFatalError()) {
- List parameters= fDeclaration.parameters();
- fParameters= new HashMap(parameters.size() * 2);
- for (Iterator iter= parameters.iterator(); iter.hasNext();) {
- SingleVariableDeclaration element= (SingleVariableDeclaration) iter.next();
- IVariableBinding binding= element.resolveBinding();
- if (binding == null) {
- result.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors,
- JavaStatusContext.create(fTypeRoot, fDeclaration));
- return result;
- }
- fParameters.put(binding, element.getProperty(ParameterData.PROPERTY));
- }
- fNames= new HashMap();
- fImplicitReceivers= new ArrayList(2);
-
- fTypeParameterReferences= new ArrayList(0);
- fTypeParameterMapping= new HashMap();
- ITypeBinding declaringType= declarationBinding.getDeclaringClass();
- if (declaringType == null) {
- result.addFatalError(
- RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_typedeclaration_has_errors,
- JavaStatusContext.create(fTypeRoot));
- return result;
- }
-
- fMethodTypeParameterReferences= new ArrayList(0);
- fMethodTypeParameterMapping= new HashMap();
- }
- if (fDeclaration.isVarargs()) {
- List parameters= fDeclaration.parameters();
- VarargAnalyzer vAnalyzer= new VarargAnalyzer(
- ((SingleVariableDeclaration)parameters.get(parameters.size() - 1)).getName().resolveBinding());
- fDeclaration.getBody().accept(vAnalyzer);
- }
- return result;
- }
-
- public void initialize() {
- Block body= fDeclaration.getBody();
- // first collect the static imports. This is necessary to not mark
- // static imported fields and methods as implicit visible.
- fTypesToImport= new ArrayList();
- fStaticsToImport= new ArrayList();
- ImportReferencesCollector collector= new ImportReferencesCollector(
- fTypeRoot.getJavaScriptProject(), null, fTypesToImport, fStaticsToImport);
- body.accept(collector);
-
- // Now collect implicit references and name references
- body.accept(new UpdateCollector());
-
- int numberOfLocals= LocalVariableIndex.perform(fDeclaration);
- FlowContext context= new FlowContext(0, numberOfLocals + 1);
- context.setConsiderAccessMode(true);
- context.setComputeMode(FlowContext.MERGE);
- InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(context);
- FlowInfo info= flowAnalyzer.perform(getStatements());
-
- for (Iterator iter= fDeclaration.parameters().iterator(); iter.hasNext();) {
- SingleVariableDeclaration element= (SingleVariableDeclaration) iter.next();
- IVariableBinding binding= element.resolveBinding();
- ParameterData data= (ParameterData)element.getProperty(ParameterData.PROPERTY);
- data.setAccessMode(info.getAccessMode(context, binding));
- }
- }
-
- public Collection getUsedNames() {
- return fNames.values();
- }
-
- public List getImplicitReceivers() {
- return fImplicitReceivers;
- }
-
- public List getTypesToImport() {
- return fTypesToImport;
- }
-
- public List getStaticsToImport() {
- return fStaticsToImport;
- }
-
- public List getTypeParameterReferences() {
- return fTypeParameterReferences;
- }
-
- public List getMethodTypeParameterReferences() {
- return fMethodTypeParameterReferences;
- }
-
- public boolean hasArrayAccess() {
- return fArrayAccess;
- }
-
- public boolean hasSuperMethodInvocation() {
- return fHasSuperMethodInvocation;
- }
-
- private ASTNode[] getStatements() {
- List statements= fDeclaration.getBody().statements();
- return (ASTNode[]) statements.toArray(new ASTNode[statements.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceProvider.java
deleted file mode 100644
index 5e274cdb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/SourceProvider.java
+++ /dev/null
@@ -1,637 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * o bug "inline method - doesn't handle implicit cast" (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941).
- * o inline call that is used in a field initializer
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38137)
- * o inline call a field initializer: could detect self reference
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=44417)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditProcessor;
-import org.eclipse.text.edits.UndoEdit;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.CodeScopeBuilder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.SourceAnalyzer.NameData;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * A SourceProvider encapsulates a piece of code (source) and the logic
- * to inline it into given CallContexts.
- */
-public class SourceProvider {
-
- private ITypeRoot fTypeRoot;
- private IDocument fDocument;
- private FunctionDeclaration fDeclaration;
- private SourceAnalyzer fAnalyzer;
- private boolean fMustEvalReturnedExpression;
- private boolean fReturnValueNeedsLocalVariable;
- private List fReturnExpressions;
- private IDocument fSource;
-
- private static final int EXPRESSION_MODE= 1;
- private static final int STATEMENT_MODE= 2;
- private static final int RETURN_STATEMENT_MODE= 3;
- private int fMarkerMode;
-
-
- private class ReturnAnalyzer extends ASTVisitor {
- public boolean visit(ReturnStatement node) {
- Expression expression= node.getExpression();
- if (!(ASTNodes.isLiteral(expression) || expression instanceof Name)) {
- fMustEvalReturnedExpression= true;
- }
- if (Invocations.isInvocation(expression) || expression instanceof ClassInstanceCreation) {
- fReturnValueNeedsLocalVariable= false;
- }
- fReturnExpressions.add(expression);
- return false;
- }
- }
-
- public SourceProvider(ITypeRoot typeRoot, FunctionDeclaration declaration) {
- super();
- fTypeRoot= typeRoot;
- fDeclaration= declaration;
- List parameters= fDeclaration.parameters();
- for (Iterator iter= parameters.iterator(); iter.hasNext();) {
- SingleVariableDeclaration element= (SingleVariableDeclaration)iter.next();
- ParameterData data= new ParameterData(element);
- element.setProperty(ParameterData.PROPERTY, data);
- }
- fAnalyzer= new SourceAnalyzer(fTypeRoot, fDeclaration);
- fReturnValueNeedsLocalVariable= true;
- fReturnExpressions= new ArrayList();
- }
-
- /**
- * TODO: unit's source does not match contents of source document and declaration node.
- */
- public SourceProvider(ITypeRoot typeRoot, IDocument source, FunctionDeclaration declaration) {
- this(typeRoot, declaration);
- fSource= source;
- }
-
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- return fAnalyzer.checkActivation();
- }
-
- public void initialize() throws JavaScriptModelException {
- fDocument= fSource == null ? new Document(fTypeRoot.getBuffer().getContents()) : fSource;
- fAnalyzer.initialize();
- if (hasReturnValue()) {
- ASTNode last= getLastStatement();
- if (last != null) {
- ReturnAnalyzer analyzer= new ReturnAnalyzer();
- last.accept(analyzer);
- }
- }
- }
-
- public boolean isExecutionFlowInterrupted() {
- return fAnalyzer.isExecutionFlowInterrupted();
- }
-
- static class VariableReferenceFinder extends ASTVisitor {
- private boolean fResult;
- private IVariableBinding fBinding;
- public VariableReferenceFinder(IVariableBinding binding) {
- fBinding= binding;
- }
- public boolean getResult() {
- return fResult;
- }
- public boolean visit(SimpleName node) {
- if(!fResult) {
- fResult= Bindings.equals(fBinding, node.resolveBinding());
- }
- return false;
- }
- }
-
- /**
- * Checks whether variable is referenced by the method declaration or not.
- *
- * @param binding binding of variable to check.
- * @return <code>true</code> if variable is referenced by the method, otherwise <code>false</code>
- */
- public boolean isVariableReferenced(IVariableBinding binding) {
- VariableReferenceFinder finder= new VariableReferenceFinder(binding);
- fDeclaration.accept(finder);
- return finder.getResult();
- }
-
- public boolean hasReturnValue() {
- IFunctionBinding binding= fDeclaration.resolveBinding();
- return binding.getReturnType() != fDeclaration.getAST().resolveWellKnownType("void"); //$NON-NLS-1$
- }
-
- // returns true if the declaration has a vararg and
- // the body contains an array access to the vararg
- public boolean hasArrayAccess() {
- return fAnalyzer.hasArrayAccess();
- }
-
- public boolean hasSuperMethodInvocation() {
- return fAnalyzer.hasSuperMethodInvocation();
- }
-
- public boolean mustEvaluateReturnedExpression() {
- return fMustEvalReturnedExpression;
- }
-
- public boolean returnValueNeedsLocalVariable() {
- return fReturnValueNeedsLocalVariable;
- }
-
- public int getNumberOfStatements() {
- return fDeclaration.getBody().statements().size();
- }
-
- public boolean isSimpleFunction() {
- List statements= fDeclaration.getBody().statements();
- if (statements.size() != 1)
- return false;
- return statements.get(0) instanceof ReturnStatement;
- }
-
- public boolean isLastStatementReturn() {
- List statements= fDeclaration.getBody().statements();
- if (statements.size() == 0)
- return false;
- return statements.get(statements.size() - 1) instanceof ReturnStatement;
- }
-
- public boolean isDangligIf() {
- List statements= fDeclaration.getBody().statements();
- if (statements.size() != 1)
- return false;
-
- Object statement= statements.get(0);
- if (! (statement instanceof IfStatement))
- return false;
-
- return ((IfStatement) statement).getElseStatement() == null;
- }
-
- public FunctionDeclaration getDeclaration() {
- return fDeclaration;
- }
-
- public String getMethodName() {
- return fDeclaration.getName().getIdentifier();
- }
-
- public ITypeBinding getReturnType() {
- return fDeclaration.resolveBinding().getReturnType();
- }
-
- public List getReturnExpressions() {
- return fReturnExpressions;
- }
-
- public boolean returnTypeMatchesReturnExpressions() {
- ITypeBinding returnType= getReturnType();
- for (Iterator iter= fReturnExpressions.iterator(); iter.hasNext();) {
- Expression expression= (Expression)iter.next();
- if (!Bindings.equals(returnType, expression.resolveTypeBinding()))
- return false;
- }
- return true;
- }
-
- public ParameterData getParameterData(int index) {
- SingleVariableDeclaration decl= (SingleVariableDeclaration)fDeclaration.parameters().get(index);
- return (ParameterData)decl.getProperty(ParameterData.PROPERTY);
- }
-
- public ITypeRoot getTypeRoot() {
- return fTypeRoot;
- }
-
- public boolean needsReturnedExpressionParenthesis() {
- ASTNode last= getLastStatement();
- if (last instanceof ReturnStatement) {
- return ASTNodes.needsParentheses(((ReturnStatement)last).getExpression());
- }
- return false;
- }
-
- public boolean returnsConditionalExpression() {
- ASTNode last= getLastStatement();
- if (last instanceof ReturnStatement) {
- return ((ReturnStatement)last).getExpression() instanceof ConditionalExpression;
- }
- return false;
- }
-
- public int getReceiversToBeUpdated() {
- return fAnalyzer.getImplicitReceivers().size();
- }
-
- public boolean isVarargs() {
- return fDeclaration.isVarargs();
- }
-
- public int getVarargIndex() {
- return fDeclaration.parameters().size() - 1;
- }
-
- public TextEdit getDeleteEdit() {
- final ASTRewrite rewriter= ASTRewrite.create(fDeclaration.getAST());
- rewriter.remove(fDeclaration, null);
- return rewriter.rewriteAST(fDocument, fTypeRoot.getJavaScriptProject().getOptions(true));
- }
-
- public String[] getCodeBlocks(CallContext context) throws CoreException {
- final ASTRewrite rewriter= ASTRewrite.create(fDeclaration.getAST());
- replaceParameterWithExpression(rewriter, context.arguments);
- updateImplicitReceivers(rewriter, context);
- makeNamesUnique(rewriter, context.scope);
- updateTypeReferences(rewriter, context);
- updateStaticReferences(rewriter, context);
- updateMethodTypeVariable(rewriter, context);
-
- List ranges= null;
- if (hasReturnValue()) {
- if (context.callMode == ASTNode.RETURN_STATEMENT) {
- ranges= getStatementRanges();
- } else {
- ranges= getExpressionRanges();
- }
- } else {
- ASTNode last= getLastStatement();
- if (last != null && last.getNodeType() == ASTNode.RETURN_STATEMENT) {
- ranges= getReturnStatementRanges();
- } else {
- ranges= getStatementRanges();
- }
- }
-
- final TextEdit dummy= rewriter.rewriteAST(fDocument, fTypeRoot.getJavaScriptProject().getOptions(true));
- int size= ranges.size();
- RangeMarker[] markers= new RangeMarker[size];
- for (int i= 0; i < markers.length; i++) {
- IRegion range= (IRegion)ranges.get(i);
- markers[i]= new RangeMarker(range.getOffset(), range.getLength());
- }
- int split;
- if (size <= 1) {
- split= Integer.MAX_VALUE;
- } else {
- IRegion region= (IRegion)ranges.get(0);
- split= region.getOffset() + region.getLength();
- }
- TextEdit[] edits= dummy.removeChildren();
- for (int i= 0; i < edits.length; i++) {
- TextEdit edit= edits[i];
- int pos= edit.getOffset() >= split ? 1 : 0;
- markers[pos].addChild(edit);
- }
- MultiTextEdit root= new MultiTextEdit(0, fDocument.getLength());
- root.addChildren(markers);
-
- try {
- TextEditProcessor processor= new TextEditProcessor(fDocument, root, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS);
- UndoEdit undo= processor.performEdits();
- String[] result= getBlocks(markers);
- // It is faster to undo the changes than coping the buffer over and over again.
- processor= new TextEditProcessor(fDocument, undo, TextEdit.UPDATE_REGIONS);
- processor.performEdits();
- return result;
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return new String[] {};
- }
-
- private void replaceParameterWithExpression(ASTRewrite rewriter, String[] expressions) {
- for (int i= 0; i < expressions.length; i++) {
- String expression= expressions[i];
- ParameterData parameter= getParameterData(i);
- List references= parameter.references();
- for (Iterator iter= references.iterator(); iter.hasNext();) {
- ASTNode element= (ASTNode) iter.next();
- ASTNode newNode= rewriter.createStringPlaceholder(expression, element.getNodeType());
- rewriter.replace(element, newNode, null);
- }
- }
- }
-
- private void makeNamesUnique(ASTRewrite rewriter, CodeScopeBuilder.Scope scope) {
- Collection usedCalleeNames= fAnalyzer.getUsedNames();
- for (Iterator iter= usedCalleeNames.iterator(); iter.hasNext();) {
- SourceAnalyzer.NameData nd= (SourceAnalyzer.NameData) iter.next();
- if (scope.isInUse(nd.getName())) {
- String newName= scope.createName(nd.getName(), true);
- List references= nd.references();
- for (Iterator refs= references.iterator(); refs.hasNext();) {
- SimpleName element= (SimpleName) refs.next();
- ASTNode newNode= rewriter.createStringPlaceholder(newName, ASTNode.FUNCTION_INVOCATION);
- rewriter.replace(element, newNode, null);
- }
- }
- }
- }
-
- private void updateImplicitReceivers(ASTRewrite rewriter, CallContext context) {
- if (context.receiver == null)
- return;
- List implicitReceivers= fAnalyzer.getImplicitReceivers();
- for (Iterator iter= implicitReceivers.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode)iter.next();
- if (node instanceof FunctionInvocation) {
- final FunctionInvocation inv= (FunctionInvocation)node;
- rewriter.set(inv, FunctionInvocation.EXPRESSION_PROPERTY, createReceiver(rewriter, context, (IFunctionBinding)inv.getName().resolveBinding()), null);
- } else if (node instanceof ClassInstanceCreation) {
- final ClassInstanceCreation inst= (ClassInstanceCreation)node;
- rewriter.set(inst, ClassInstanceCreation.EXPRESSION_PROPERTY, createReceiver(rewriter, context, inst.resolveConstructorBinding()), null);
- } else if (node instanceof ThisExpression) {
- rewriter.replace(node, rewriter.createStringPlaceholder(context.receiver, ASTNode.FUNCTION_INVOCATION), null);
- } else if (node instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess)node;
- rewriter.set(access, FieldAccess.EXPRESSION_PROPERTY, createReceiver(rewriter, context, access.resolveFieldBinding()), null);
- } else if (node instanceof SimpleName && ((SimpleName)node).resolveBinding() instanceof IVariableBinding) {
- IVariableBinding vb= (IVariableBinding)((SimpleName)node).resolveBinding();
- if (vb.isField()) {
- Expression receiver= createReceiver(rewriter, context, vb);
- if (receiver != null) {
- FieldAccess access= node.getAST().newFieldAccess();
- ASTNode target= rewriter.createMoveTarget(node);
- access.setName((SimpleName)target);
- access.setExpression(receiver);
- rewriter.replace(node, access, null);
- }
- }
- }
- }
- }
-
- private void updateTypeReferences(ASTRewrite rewriter, CallContext context) {
- ImportRewrite importer= context.importer;
- for (Iterator iter= fAnalyzer.getTypesToImport().iterator(); iter.hasNext();) {
- Name element= (Name)iter.next();
- ITypeBinding binding= ASTNodes.getTypeBinding(element);
- if (binding != null && !binding.isLocal()) {
- // We have collected names not types. So we have to import
- // the declaration type if we reference a parameterized type
- // since we have an entry for every name node (e.g. one for
- // Vector and one for Integer in Vector<Integer>.
- String s= importer.addImport(binding);
- if (!ASTNodes.asString(element).equals(s)) {
- rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
- }
- }
- }
- }
-
- private void updateStaticReferences(ASTRewrite rewriter, CallContext context) {
- ImportRewrite importer= context.importer;
- for (Iterator iter= fAnalyzer.getStaticsToImport().iterator(); iter.hasNext();) {
- Name element= (Name)iter.next();
- IBinding binding= element.resolveBinding();
- if (binding != null) {
- String s= importer.addStaticImport(binding);
- if (!ASTNodes.asString(element).equals(s)) {
- rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
- }
- }
- }
-
- }
-
- private Expression createReceiver(ASTRewrite rewriter, CallContext context, IFunctionBinding method) {
- String receiver= getReceiver(context, method.getModifiers());
- if (receiver == null)
- return null;
- return (Expression)rewriter.createStringPlaceholder(receiver, ASTNode.FUNCTION_INVOCATION);
- }
-
- private Expression createReceiver(ASTRewrite rewriter, CallContext context, IVariableBinding field) {
- String receiver= getReceiver(context, field.getModifiers());
- if (receiver == null)
- return null;
- return (Expression)rewriter.createStringPlaceholder(receiver, ASTNode.SIMPLE_NAME);
- }
-
- private String getReceiver(CallContext context, int modifiers) {
- String receiver= context.receiver;
- ITypeBinding invocationType= ASTNodes.getEnclosingType(context.invocation);
- ITypeBinding sourceType= fDeclaration.resolveBinding().getDeclaringClass();
- if (!context.receiverIsStatic && Modifier.isStatic(modifiers)) {
- if ("this".equals(receiver) && invocationType != null && Bindings.equals(invocationType, sourceType)) { //$NON-NLS-1$
- receiver= null;
- } else {
- receiver= context.importer.addImport(sourceType);
- }
- }
- return receiver;
- }
-
- private void updateMethodTypeVariable(ASTRewrite rewriter, CallContext context) {
- IFunctionBinding method= Invocations.resolveBinding(context.invocation);
- if (method == null)
- return;
- rewriteReferences(rewriter, null, fAnalyzer.getMethodTypeParameterReferences());
- }
-
- private void rewriteReferences(ASTRewrite rewriter, ITypeBinding[] typeArguments, List typeParameterReferences) {
- if (typeArguments.length == 0)
- return;
- Assert.isTrue(typeArguments.length == typeParameterReferences.size());
- for (int i= 0; i < typeArguments.length; i++) {
- SourceAnalyzer.NameData refData= (NameData)typeParameterReferences.get(i);
- List references= refData.references();
- String newName= typeArguments[i].getName();
- for (Iterator iter= references.iterator(); iter.hasNext();) {
- SimpleName name= (SimpleName)iter.next();
- rewriter.replace(name, rewriter.createStringPlaceholder(newName, ASTNode.SIMPLE_NAME), null);
- }
- }
- }
-
- private ASTNode getLastStatement() {
- List statements= fDeclaration.getBody().statements();
- if (statements.isEmpty())
- return null;
- return (ASTNode)statements.get(statements.size() - 1);
- }
-
- private List getReturnStatementRanges() {
- fMarkerMode= RETURN_STATEMENT_MODE;
- List result= new ArrayList(1);
- List statements= fDeclaration.getBody().statements();
- int size= statements.size();
- if (size <= 1)
- return result;
- result.add(createRange(statements, size - 2));
- return result;
- }
-
- private List getStatementRanges() {
- fMarkerMode= STATEMENT_MODE;
- List result= new ArrayList(1);
- List statements= fDeclaration.getBody().statements();
- int size= statements.size();
- if (size == 0)
- return result;
- result.add(createRange(statements, size - 1));
- return result;
- }
-
- private List getExpressionRanges() {
- fMarkerMode= EXPRESSION_MODE;
- List result= new ArrayList(2);
- List statements= fDeclaration.getBody().statements();
- ReturnStatement rs= null;
- int size= statements.size();
- ASTNode node;
- switch (size) {
- case 0:
- return result;
- case 1:
- node= (ASTNode)statements.get(0);
- if (node.getNodeType() == ASTNode.RETURN_STATEMENT) {
- rs= (ReturnStatement)node;
- } else {
- result.add(new Region(node.getStartPosition(), node.getLength()));
- }
- break;
- default: {
- node= (ASTNode)statements.get(size - 1);
- if (node.getNodeType() == ASTNode.RETURN_STATEMENT) {
- result.add(createRange(statements, size - 2));
- rs= (ReturnStatement)node;
- } else {
- result.add(createRange(statements, size - 1));
- }
- break;
- }
- }
- if (rs != null) {
- Expression exp= rs.getExpression();
- result.add(new Region(exp.getStartPosition(), exp.getLength()));
- }
- return result;
- }
-
- private IRegion createRange(List statements, int end) {
- ASTNode first= (ASTNode)statements.get(0);
- ASTNode root= first.getRoot();
- if (root instanceof JavaScriptUnit) {
- JavaScriptUnit unit= (JavaScriptUnit)root;
- int start= unit.getExtendedStartPosition(first);
- ASTNode last= (ASTNode)statements.get(end);
- int length = unit.getExtendedStartPosition(last) - start + unit.getExtendedLength(last);
- IRegion range= new Region(start, length);
- return range;
- } else {
- int start= first.getStartPosition();
- ASTNode last= (ASTNode)statements.get(end);
- int length = last.getStartPosition() - start + last.getLength();
- IRegion range= new Region(start, length);
- return range;
- }
- }
-
- private String[] getBlocks(RangeMarker[] markers) throws BadLocationException {
- String[] result= new String[markers.length];
- for (int i= 0; i < markers.length; i++) {
- RangeMarker marker= markers[i];
- String content= fDocument.get(marker.getOffset(), marker.getLength());
- String lines[]= Strings.convertIntoLines(content);
- Strings.trimIndentation(lines, fTypeRoot.getJavaScriptProject(), false);
- if (fMarkerMode == STATEMENT_MODE && lines.length == 2 && isSingleControlStatementWithoutBlock()) {
- lines[1]= CodeFormatterUtil.createIndentString(1, fTypeRoot.getJavaScriptProject()) + lines[1];
- }
- result[i]= Strings.concatenate(lines, TextUtilities.getDefaultLineDelimiter(fDocument));
- }
- return result;
- }
-
- private boolean isSingleControlStatementWithoutBlock() {
- List statements= fDeclaration.getBody().statements();
- int size= statements.size();
- if (size != 1)
- return false;
- Statement statement= (Statement) statements.get(size - 1);
- int nodeType= statement.getNodeType();
- if (nodeType == ASTNode.IF_STATEMENT) {
- IfStatement ifStatement= (IfStatement) statement;
- return !(ifStatement.getThenStatement() instanceof Block)
- && !(ifStatement.getElseStatement() instanceof Block);
- } else if (nodeType == ASTNode.FOR_STATEMENT) {
- return !(((ForStatement)statement).getBody() instanceof Block);
- } else if (nodeType == ASTNode.WHILE_STATEMENT) {
- return !(((WhileStatement)statement).getBody() instanceof Block);
- } else if (nodeType == ASTNode.WITH_STATEMENT) {
- return !(((WithStatement)statement).getBody() instanceof Block);
- } else if (nodeType == ASTNode.FOR_IN_STATEMENT) {
- return !(((ForInStatement)statement).getBody() instanceof Block);
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TargetProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TargetProvider.java
deleted file mode 100644
index 21d2437e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TargetProvider.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for:
- * o Allow 'this' constructor to be inlined
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.IRefactoringSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-/**
- * A TargetProvider provides all targets that have to be adapted, i.e. all method invocations that should be inlined.
- */
-abstract class TargetProvider {
-
- public static final boolean BUG_CORE_130317= true; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=130317
-
- protected SourceProvider fSourceProvider;
-
- //TODO: not used...
- public void setSourceProvider(SourceProvider sourceProvider) {
- Assert.isNotNull(sourceProvider);
- fSourceProvider= sourceProvider;
- }
-
- public abstract void initialize();
-
- public abstract IJavaScriptUnit[] getAffectedCompilationUnits(RefactoringStatus status, IProgressMonitor pm) throws JavaScriptModelException;
-
- public abstract BodyDeclaration[] getAffectedBodyDeclarations(IJavaScriptUnit unit, IProgressMonitor pm);
-
- // constructor invocation is not an expression but a statement
- public abstract ASTNode[] getInvocations(BodyDeclaration declaration, IProgressMonitor pm);
-
- public abstract RefactoringStatus checkActivation() throws JavaScriptModelException;
-
- public abstract int getStatusSeverity();
-
- public boolean isSingle() {
- return false;
- }
-
- public static TargetProvider create(IJavaScriptUnit cu, FunctionInvocation invocation) {
- return new SingleCallTargetProvider(cu, invocation);
- }
-
- public static TargetProvider create(IJavaScriptUnit cu, SuperMethodInvocation invocation) {
- return new SingleCallTargetProvider(cu, invocation);
- }
-
- public static TargetProvider create(IJavaScriptUnit cu, ConstructorInvocation invocation) {
- return new SingleCallTargetProvider(cu, invocation);
- }
-
- public static TargetProvider create(FunctionDeclaration declaration) {
- IFunctionBinding method= declaration.resolveBinding();
- if (method == null)
- return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_method_declaration_not_unique));
- ITypeBinding type= method.getDeclaringClass();
- if (type.isLocal()) {
- if (((IType) type.getJavaElement()).isBinary()) {
- return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_cannot_local_method_in_binary));
- } else {
- IType declaringClassOfLocal= (IType) type.getDeclaringClass().getJavaElement();
- return new LocalTypeTargetProvider(declaringClassOfLocal.getJavaScriptUnit(), declaration);
- }
- } else {
- return new MemberTypeTargetProvider(declaration.resolveBinding());
- }
- }
-
- public static TargetProvider create(IFunctionBinding methodBinding) {
- return new MemberTypeTargetProvider(methodBinding);
- }
-
- static void fastDone(IProgressMonitor pm) {
- if (pm == null)
- return;
- pm.beginTask("", 1); //$NON-NLS-1$
- pm.worked(1);
- pm.done();
- }
-
- static class ErrorTargetProvider extends TargetProvider {
- private RefactoringStatus fErrorStatus;
- public ErrorTargetProvider(RefactoringStatus status) {
- fErrorStatus= status;
- }
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- return fErrorStatus;
- }
- public void initialize() {
- }
- public IJavaScriptUnit[] getAffectedCompilationUnits(RefactoringStatus status, IProgressMonitor pm) throws JavaScriptModelException {
- return null;
- }
- public BodyDeclaration[] getAffectedBodyDeclarations(IJavaScriptUnit unit, IProgressMonitor pm) {
- return null;
- }
- public ASTNode[] getInvocations(BodyDeclaration declaration, IProgressMonitor pm) {
- return null;
- }
- public int getStatusSeverity() {
- return 0;
- }
- }
-
- static class SingleCallTargetProvider extends TargetProvider {
- private IJavaScriptUnit fCUnit;
- private ASTNode fInvocation;
- private boolean fIterated;
- public SingleCallTargetProvider(IJavaScriptUnit cu, ASTNode invocation) {
- Assert.isNotNull(cu);
- Assert.isNotNull(invocation);
- Assert.isTrue(Invocations.isInvocation(invocation));
- fCUnit= cu;
- fInvocation= invocation;
- }
- public void initialize() {
- fIterated= false;
- }
- public IJavaScriptUnit[] getAffectedCompilationUnits(RefactoringStatus status, IProgressMonitor pm) {
- return new IJavaScriptUnit[] { fCUnit };
- }
- public BodyDeclaration[] getAffectedBodyDeclarations(IJavaScriptUnit unit, IProgressMonitor pm) {
- Assert.isTrue(unit == fCUnit);
- if (fIterated)
- return new BodyDeclaration[0];
- fastDone(pm);
- return new BodyDeclaration[] {
- (BodyDeclaration)ASTNodes.getParent(fInvocation, BodyDeclaration.class)
- };
- }
-
- public ASTNode[] getInvocations(BodyDeclaration declaration, IProgressMonitor pm) {
- fastDone(pm);
- if (fIterated)
- return null;
- fIterated= true;
- return new ASTNode[] { fInvocation };
- }
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- return new RefactoringStatus();
- }
- public int getStatusSeverity() {
- return RefactoringStatus.FATAL;
- }
- public boolean isSingle() {
- return true;
- }
- }
-
- private static class BodyData {
- public BodyDeclaration fBody;
- private List fInvocations;
- public BodyData(BodyDeclaration declaration) {
- fBody= declaration;
- }
- public void addInvocation(ASTNode node) {
- if (fInvocations == null)
- fInvocations= new ArrayList(2);
- fInvocations.add(node);
- }
- public ASTNode[] getInvocations() {
- return (ASTNode[])fInvocations.toArray(new ASTNode[fInvocations.size()]);
- }
- public boolean hasInvocations() {
- return fInvocations != null && !fInvocations.isEmpty();
- }
- public BodyDeclaration getDeclaration() {
- return fBody;
- }
- }
-
- private static class InvocationFinder extends ASTVisitor {
- Map/*<BodyDeclaration, BodyData>*/ result= new HashMap(2);
- Stack/*<BodyData>*/ fBodies= new Stack();
- BodyData fCurrent;
- private IFunctionBinding fBinding;
- public InvocationFinder(IFunctionBinding binding) {
- Assert.isNotNull(binding);
- fBinding= binding.getMethodDeclaration();
- Assert.isNotNull(fBinding);
- }
- public boolean visit(FunctionInvocation node) {
- if (matches(node.getName().resolveBinding()) && fCurrent != null) {
- fCurrent.addInvocation(node);
- }
- return true;
- }
- public boolean visit(SuperMethodInvocation node) {
- if (matches(node.getName().resolveBinding()) && fCurrent != null) {
- fCurrent.addInvocation(node);
- }
- return true;
- }
- public boolean visit(ConstructorInvocation node) {
- if (matches(node.resolveConstructorBinding()) && fCurrent != null) {
- fCurrent.addInvocation(node);
- }
- return true;
- }
- public boolean visit(ClassInstanceCreation node) {
- if (matches(node.resolveConstructorBinding()) && fCurrent != null) {
- fCurrent.addInvocation(node);
- }
- return true;
- }
- public boolean visit(TypeDeclaration node) {
- return visitType();
- }
- public void endVisit(TypeDeclaration node) {
- endVisitType();
- }
-
- private boolean visitType() {
- fBodies.add(fCurrent);
- fCurrent= null;
- return true;
- }
- private void endVisitType() {
- fCurrent= (BodyData)fBodies.remove(fBodies.size() - 1);
- }
- public boolean visit(FieldDeclaration node) {
- fBodies.add(fCurrent);
- fCurrent= new BodyData(node);
- return true;
- }
- public void endVisit(FieldDeclaration node) {
- if (fCurrent.hasInvocations()) {
- result.put(node, fCurrent);
- }
- endVisitType();
- }
- public boolean visit(FunctionDeclaration node) {
- fBodies.add(fCurrent);
- fCurrent= new BodyData(node);
- return true;
- }
- public void endVisit(FunctionDeclaration node) {
- if (fCurrent.hasInvocations()) {
- result.put(node, fCurrent);
- }
- endVisitType();
-
- }
- public boolean visit(Initializer node) {
- fBodies.add(fCurrent);
- fCurrent= new BodyData(node);
- return true;
- }
- public void endVisit(Initializer node) {
- if (fCurrent.hasInvocations()) {
- result.put(node, fCurrent);
- }
- endVisitType();
- }
- private boolean matches(IBinding binding) {
- if (!(binding instanceof IFunctionBinding))
- return false;
- if (BUG_CORE_130317)
- return fBinding.getKey().equals(((IFunctionBinding)binding).getMethodDeclaration().getKey());
- else
- return fBinding.isEqualTo(((IFunctionBinding)binding).getMethodDeclaration());
- }
- }
-
- private static class LocalTypeTargetProvider extends TargetProvider {
- private IJavaScriptUnit fCUnit;
- private FunctionDeclaration fDeclaration;
- private Map fBodies;
- public LocalTypeTargetProvider(IJavaScriptUnit unit, FunctionDeclaration declaration) {
- Assert.isNotNull(unit);
- Assert.isNotNull(declaration);
- fCUnit= unit;
- fDeclaration= declaration;
- }
- public void initialize() {
- InvocationFinder finder= new InvocationFinder(fDeclaration.resolveBinding());
- ASTNode type= ASTNodes.getParent(fDeclaration, AbstractTypeDeclaration.class);
- type.accept(finder);
- fBodies= finder.result;
- }
- public IJavaScriptUnit[] getAffectedCompilationUnits(RefactoringStatus status, IProgressMonitor pm) {
- fastDone(pm);
- return new IJavaScriptUnit[] { fCUnit };
- }
-
- public BodyDeclaration[] getAffectedBodyDeclarations(IJavaScriptUnit unit, IProgressMonitor pm) {
- Assert.isTrue(unit == fCUnit);
- Set result= fBodies.keySet();
- fastDone(pm);
- return (BodyDeclaration[])result.toArray(new BodyDeclaration[result.size()]);
- }
-
- public ASTNode[] getInvocations(BodyDeclaration declaration, IProgressMonitor pm) {
- BodyData data= (BodyData)fBodies.get(declaration);
- Assert.isNotNull(data);
- fastDone(pm);
- return data.getInvocations();
- }
-
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- return new RefactoringStatus();
- }
-
- public int getStatusSeverity() {
- return RefactoringStatus.ERROR;
- }
- }
-
- private static class MemberTypeTargetProvider extends TargetProvider {
- private final IFunctionBinding fMethodBinding;
- private Map fCurrentBodies;
- public MemberTypeTargetProvider(IFunctionBinding methodBinding) {
- Assert.isNotNull(methodBinding);
- fMethodBinding= methodBinding;
- }
- public void initialize() {
- // do nothing.
- }
-
- public IJavaScriptUnit[] getAffectedCompilationUnits(final RefactoringStatus status, IProgressMonitor pm) throws JavaScriptModelException {
- IFunction method= (IFunction)fMethodBinding.getJavaElement();
- Assert.isTrue(method != null);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(method, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setGranularity(RefactoringSearchEngine2.GRANULARITY_COMPILATION_UNIT);
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(method));
- engine.setRequestor(new IRefactoringSearchRequestor() {
- public SearchMatch acceptSearchMatch(SearchMatch match) {
- if (match.isInsideDocComment())
- return null;
- if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
- Object element= match.getElement();
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement jElement= (IJavaScriptElement)element;
- IJavaScriptUnit unit= (IJavaScriptUnit)jElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (unit != null) {
- status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match,
- JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength())));
- return null;
- }
- }
- status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match);
- return null;
- } else {
- return match;
- }
- }
- });
- engine.searchPattern(new SubProgressMonitor(pm, 1));
- return engine.getAffectedCompilationUnits();
- }
-
- public BodyDeclaration[] getAffectedBodyDeclarations(IJavaScriptUnit unit, IProgressMonitor pm) {
- ASTNode root= new RefactoringASTParser(AST.JLS3).parse(unit, true);
- InvocationFinder finder= new InvocationFinder(fMethodBinding);
- root.accept(finder);
- fCurrentBodies= finder.result;
- Set result= fCurrentBodies.keySet();
- fastDone(pm);
- return (BodyDeclaration[])result.toArray(new BodyDeclaration[result.size()]);
- }
-
- public ASTNode[] getInvocations(BodyDeclaration declaration, IProgressMonitor pm) {
- BodyData data= (BodyData)fCurrentBodies.get(declaration);
- Assert.isNotNull(data);
- fastDone(pm);
- return data.getInvocations();
- }
-
- public RefactoringStatus checkActivation() throws JavaScriptModelException {
- return new RefactoringStatus();
- }
-
- public int getStatusSeverity() {
- return RefactoringStatus.ERROR;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TempAssignmentFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TempAssignmentFinder.java
deleted file mode 100644
index 03b00a06..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/TempAssignmentFinder.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression.Operator;
-
-public class TempAssignmentFinder extends ASTVisitor{
- private ASTNode fFirstAssignment;
- private IVariableBinding fTempBinding;
-
- TempAssignmentFinder(VariableDeclaration tempDeclaration){
- fTempBinding= tempDeclaration.resolveBinding();
- }
-
- private boolean isNameReferenceToTemp(Name name){
- return fTempBinding == name.resolveBinding();
- }
-
- private boolean isAssignmentToTemp(Assignment assignment){
- if (fTempBinding == null)
- return false;
-
- if (! (assignment.getLeftHandSide() instanceof Name))
- return false;
- Name ref= (Name)assignment.getLeftHandSide();
- return isNameReferenceToTemp(ref);
- }
-
- boolean hasAssignments(){
- return fFirstAssignment != null;
- }
-
- ASTNode getFirstAssignment(){
- return fFirstAssignment;
- }
-
- //-- visit methods
-
- public boolean visit(Assignment assignment) {
- if (! isAssignmentToTemp(assignment))
- return true;
-
- fFirstAssignment= assignment;
- return false;
- }
-
- public boolean visit(PostfixExpression postfixExpression) {
- if (postfixExpression.getOperand() == null)
- return true;
- if (! (postfixExpression.getOperand() instanceof SimpleName))
- return true;
- SimpleName simpleName= (SimpleName)postfixExpression.getOperand();
- if (! isNameReferenceToTemp(simpleName))
- return true;
-
- fFirstAssignment= postfixExpression;
- return false;
- }
-
- public boolean visit(PrefixExpression prefixExpression) {
- if (prefixExpression.getOperand() == null)
- return true;
- if (! (prefixExpression.getOperand() instanceof SimpleName))
- return true;
- if (! prefixExpression.getOperator().equals(Operator.DECREMENT) &&
- ! prefixExpression.getOperator().equals(Operator.INCREMENT))
- return true;
- SimpleName simpleName= (SimpleName)prefixExpression.getOperand();
- if (! isNameReferenceToTemp(simpleName))
- return true;
-
- fFirstAssignment= prefixExpression;
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BlockFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BlockFlowInfo.java
deleted file mode 100644
index 7142c3c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BlockFlowInfo.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class BlockFlowInfo extends GenericSequentialFlowInfo {
-
- public BlockFlowInfo() {
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BranchFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BranchFlowInfo.java
deleted file mode 100644
index f5406498..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/BranchFlowInfo.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import java.util.HashSet;
-
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-
-class BranchFlowInfo extends FlowInfo {
-
- public BranchFlowInfo(SimpleName label, FlowContext context) {
- super(NO_RETURN);
- fBranches= new HashSet(2);
- fBranches.add(makeString(label));
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ConditionalFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ConditionalFlowInfo.java
deleted file mode 100644
index ea62fbce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ConditionalFlowInfo.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-
-
-class ConditionalFlowInfo extends FlowInfo {
-
- public ConditionalFlowInfo() {
- super(NO_RETURN);
- }
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void merge(FlowInfo truePart, FlowInfo falsePart, FlowContext context) {
- if (truePart == null && falsePart == null)
- return;
-
- GenericConditionalFlowInfo cond= new GenericConditionalFlowInfo();
- if (truePart != null)
- cond.mergeAccessMode(truePart, context);
-
- if (falsePart != null)
- cond.mergeAccessMode(falsePart, context);
-
- if (truePart == null || falsePart == null)
- cond.mergeEmptyCondition(context);
-
- mergeAccessModeSequential(cond, context);
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/DoWhileFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/DoWhileFlowInfo.java
deleted file mode 100644
index 4dfabee7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/DoWhileFlowInfo.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class DoWhileFlowInfo extends FlowInfo {
-
- private boolean fActionBranches;
-
- public void mergeAction(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- fActionBranches= info.branches();
-
- assign(info);
-
- if (fActionBranches && fReturnKind == VALUE_RETURN) {
- fReturnKind= PARTIAL_RETURN;
- }
-
- }
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (fActionBranches || fReturnKind == VALUE_RETURN || fReturnKind == VOID_RETURN || info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/EnhancedForFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/EnhancedForFlowInfo.java
deleted file mode 100644
index f0e6b19e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/EnhancedForFlowInfo.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class EnhancedForFlowInfo extends FlowInfo {
-
- public void mergeParameter(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeExpression(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeAction(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- info.mergeEmptyCondition(context);
-
- mergeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java
deleted file mode 100644
index 87786643..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java
+++ /dev/null
@@ -1,889 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-
-/**
- * Special flow analyzer to determine the return value of the extracted method
- * and the variables which have to be passed to the method.
- *
- * Note: This analyzer doesn't do a full flow analysis. For example it doesn't
- * do dead code analysis or variable initialization analysis. It analyses the
- * the first access to a variable (read or write) and if all execution paths
- * return a value.
- */
-abstract class FlowAnalyzer extends GenericVisitor {
-
- static protected class SwitchData {
- private boolean fHasDefaultCase;
- private List fRanges= new ArrayList(4);
- private List fInfos= new ArrayList(4);
- public void setHasDefaultCase() {
- fHasDefaultCase= true;
- }
- public boolean hasDefaultCase() {
- return fHasDefaultCase;
- }
- public void add(IRegion range, FlowInfo info) {
- fRanges.add(range);
- fInfos.add(info);
- }
- public IRegion[] getRanges() {
- return (IRegion[]) fRanges.toArray(new IRegion[fRanges.size()]);
- }
- public FlowInfo[] getInfos() {
- return (FlowInfo[]) fInfos.toArray(new FlowInfo[fInfos.size()]);
- }
- public FlowInfo getInfo(int index) {
- return (FlowInfo)fInfos.get(index);
- }
- }
-
- private HashMap fData = new HashMap(100);
- /* package */ FlowContext fFlowContext= null;
-
- public FlowAnalyzer(FlowContext context) {
- fFlowContext= context;
- }
-
- protected abstract boolean createReturnFlowInfo(ReturnStatement node);
-
- protected abstract boolean traverseNode(ASTNode node);
-
- protected boolean skipNode(ASTNode node) {
- return !traverseNode(node);
- }
-
- protected final boolean visitNode(ASTNode node) {
- return traverseNode(node);
- }
-
- //---- Hooks to create Flow info objects. User may introduce their own infos.
-
- protected ReturnFlowInfo createReturn(ReturnStatement statement) {
- return new ReturnFlowInfo(statement);
- }
-
- protected ThrowFlowInfo createThrow() {
- return new ThrowFlowInfo();
- }
-
- protected BranchFlowInfo createBranch(SimpleName label) {
- return new BranchFlowInfo(label, fFlowContext);
- }
-
- protected GenericSequentialFlowInfo createSequential() {
- return new GenericSequentialFlowInfo();
- }
-
- protected ConditionalFlowInfo createConditional() {
- return new ConditionalFlowInfo();
- }
-
- protected EnhancedForFlowInfo createEnhancedFor() {
- return new EnhancedForFlowInfo();
- }
-
- protected ForFlowInfo createFor() {
- return new ForFlowInfo();
- }
-
- protected TryFlowInfo createTry() {
- return new TryFlowInfo();
- }
-
- protected WhileFlowInfo createWhile() {
- return new WhileFlowInfo();
- }
- protected WithFlowInfo createWith() {
- return new WithFlowInfo();
- }
-
- protected IfFlowInfo createIf() {
- return new IfFlowInfo();
- }
-
- protected DoWhileFlowInfo createDoWhile() {
- return new DoWhileFlowInfo();
- }
-
- protected SwitchFlowInfo createSwitch() {
- return new SwitchFlowInfo();
- }
-
- protected BlockFlowInfo createBlock() {
- return new BlockFlowInfo();
- }
-
- protected MessageSendFlowInfo createMessageSendFlowInfo() {
- return new MessageSendFlowInfo();
- }
-
- protected FlowContext getFlowContext() {
- return fFlowContext;
- }
-
- //---- Helpers to access flow analysis objects ----------------------------------------
-
- protected FlowInfo getFlowInfo(ASTNode node) {
- return (FlowInfo)fData.remove(node);
- }
-
- protected void setFlowInfo(ASTNode node, FlowInfo info) {
- fData.put(node, info);
- }
-
- protected FlowInfo assignFlowInfo(ASTNode target, ASTNode source) {
- FlowInfo result= getFlowInfo(source);
- setFlowInfo(target, result);
- return result;
- }
-
- protected FlowInfo accessFlowInfo(ASTNode node) {
- return (FlowInfo)fData.get(node);
- }
-
- //---- Helpers to process sequential flow infos -------------------------------------
-
- protected GenericSequentialFlowInfo processSequential(ASTNode parent, List nodes) {
- GenericSequentialFlowInfo result= createSequential(parent);
- process(result, nodes);
- return result;
- }
-
- protected GenericSequentialFlowInfo processSequential(ASTNode parent, ASTNode node1) {
- GenericSequentialFlowInfo result= createSequential(parent);
- if (node1 != null)
- result.merge(getFlowInfo(node1), fFlowContext);
- return result;
- }
-
- protected GenericSequentialFlowInfo processSequential(ASTNode parent, ASTNode node1, ASTNode node2) {
- GenericSequentialFlowInfo result= createSequential(parent);
- if (node1 != null)
- result.merge(getFlowInfo(node1), fFlowContext);
- if (node2 != null)
- result.merge(getFlowInfo(node2), fFlowContext);
- return result;
- }
-
- protected GenericSequentialFlowInfo createSequential(ASTNode parent) {
- GenericSequentialFlowInfo result= createSequential();
- setFlowInfo(parent, result);
- return result;
- }
-
- protected GenericSequentialFlowInfo createSequential(List nodes) {
- GenericSequentialFlowInfo result= createSequential();
- process(result, nodes);
- return result;
- }
-
- //---- Generic merge methods --------------------------------------------------------
-
- protected void process(GenericSequentialFlowInfo info, List nodes) {
- if (nodes == null)
- return;
- for (Iterator iter= nodes.iterator(); iter.hasNext();) {
- info.merge(getFlowInfo((ASTNode)iter.next()), fFlowContext);
- }
- }
-
- protected void process(GenericSequentialFlowInfo info, ASTNode node) {
- if (node != null)
- info.merge(getFlowInfo(node), fFlowContext);
- }
-
- protected void process(GenericSequentialFlowInfo info, ASTNode node1, ASTNode node2) {
- if (node1 != null)
- info.merge(getFlowInfo(node1), fFlowContext);
- if (node2 != null)
- info.merge(getFlowInfo(node2), fFlowContext);
- }
-
- //---- special visit methods -------------------------------------------------------
-
- public boolean visit(EmptyStatement node) {
- // Empty statements aren't of any interest.
- return false;
- }
-
- public boolean visit(TryStatement node) {
- if (traverseNode(node)) {
- fFlowContext.pushExcptions(node);
- node.getBody().accept(this);
- fFlowContext.popExceptions();
- List catchClauses= node.catchClauses();
- for (Iterator iter= catchClauses.iterator(); iter.hasNext();) {
- ((CatchClause)iter.next()).accept(this);
- }
- Block finallyBlock= node.getFinally();
- if (finallyBlock != null) {
- finallyBlock.accept(this);
- }
- }
- return false;
- }
-
- //---- Helper to process switch statement ----------------------------------------
-
- protected SwitchData createSwitchData(SwitchStatement node) {
- SwitchData result= new SwitchData();
- List statements= node.statements();
- if (statements.isEmpty())
- return result;
-
- int start= -1, end= -1;
- GenericSequentialFlowInfo info= null;
-
- for (Iterator iter= statements.iterator(); iter.hasNext(); ) {
- Statement statement= (Statement)iter.next();
- if (statement instanceof SwitchCase) {
- SwitchCase switchCase= (SwitchCase)statement;
- if (switchCase.isDefault()) {
- result.setHasDefaultCase();
- }
- if (info == null) {
- info= createSequential();
- start= statement.getStartPosition();
- } else {
- if (info.isReturn() || info.isPartialReturn() || info.branches()) {
- result.add(new Region(start, end - start + 1), info);
- info= createSequential();
- start= statement.getStartPosition();
- }
- }
- } else {
- info.merge(getFlowInfo(statement), fFlowContext);
- }
- end= statement.getStartPosition() + statement.getLength() - 1;
- }
- result.add(new Region(start, end - start + 1), info);
- return result;
- }
-
- protected void endVisit(SwitchStatement node, SwitchData data) {
- SwitchFlowInfo switchFlowInfo= createSwitch();
- setFlowInfo(node, switchFlowInfo);
- switchFlowInfo.mergeTest(getFlowInfo(node.getExpression()), fFlowContext);
- FlowInfo[] cases= data.getInfos();
- for (int i= 0; i < cases.length; i++)
- switchFlowInfo.mergeCase(cases[i], fFlowContext);
- switchFlowInfo.mergeDefault(data.hasDefaultCase(), fFlowContext);
- switchFlowInfo.removeLabel(null);
- }
-
- //---- concret endVisit methods ---------------------------------------------------
-
- public void endVisit(AnonymousClassDeclaration node) {
- if (skipNode(node))
- return;
- FlowInfo info= processSequential(node, node.bodyDeclarations());
- info.setNoReturn();
- }
-
- public void endVisit(ArrayAccess node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getArray(), node.getIndex());
- }
-
- public void endVisit(ArrayCreation node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getType());
- process(info, node.dimensions());
- process(info, node.getInitializer());
- }
-
- public void endVisit(ArrayInitializer node) {
- if (skipNode(node))
- return;
- processSequential(node, node.expressions());
- }
-
- public void endVisit(ArrayType node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getElementType());
- }
-
- public void endVisit(Assignment node) {
- if (skipNode(node))
- return;
- FlowInfo lhs= getFlowInfo(node.getLeftHandSide());
- FlowInfo rhs= getFlowInfo(node.getRightHandSide());
- if (lhs instanceof LocalFlowInfo) {
- LocalFlowInfo llhs= (LocalFlowInfo)lhs;
- llhs.setWriteAccess(fFlowContext);
- if (node.getOperator() != Assignment.Operator.ASSIGN) {
- GenericSequentialFlowInfo tmp= createSequential();
- tmp.merge(new LocalFlowInfo(llhs, FlowInfo.READ, fFlowContext), fFlowContext);
- tmp.merge(rhs, fFlowContext);
- rhs= tmp;
- }
- }
- GenericSequentialFlowInfo info= createSequential(node);
- // first process right and side and then left hand side.
- info.merge(rhs, fFlowContext);
- info.merge(lhs, fFlowContext);
- }
-
- public void endVisit(Block node) {
- if (skipNode(node))
- return;
- BlockFlowInfo info= createBlock();
- setFlowInfo(node, info);
- process(info, node.statements());
- }
-
- public void endVisit(BooleanLiteral node) {
- // Leaf node.
- }
-
- public void endVisit(BreakStatement node) {
- if (skipNode(node))
- return;
- setFlowInfo(node, createBranch(node.getLabel()));
- }
-
- public void endVisit(CatchClause node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getException(), node.getBody());
- }
-
- public void endVisit(CharacterLiteral node) {
- // Leaf node.
- }
-
- public void endVisit(ClassInstanceCreation node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getExpression());
- process(info, node.getType());
- process(info, node.arguments());
- process(info, node.getMember());
- process(info, node.getAnonymousClassDeclaration());
- }
-
- public void endVisit(JavaScriptUnit node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.imports());
- process(info, node.types());
- }
-
- public void endVisit(ConditionalExpression node) {
- if (skipNode(node))
- return;
- ConditionalFlowInfo info= createConditional();
- setFlowInfo(node, info);
- info.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- info.merge(
- getFlowInfo(node.getThenExpression()),
- getFlowInfo(node.getElseExpression()),
- fFlowContext);
- }
-
- public void endVisit(ConstructorInvocation node) {
- if (skipNode(node))
- return;
- processSequential(node, node.arguments());
- }
-
- public void endVisit(ContinueStatement node) {
- if (skipNode(node))
- return;
- setFlowInfo(node, createBranch(node.getLabel()));
- }
-
- public void endVisit(DoStatement node) {
- if (skipNode(node))
- return;
- DoWhileFlowInfo info= createDoWhile();
- setFlowInfo(node, info);
- info.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- info.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- info.removeLabel(null);
- }
-
- public void endVisit(EmptyStatement node) {
- // Leaf node.
- }
-
- public void endVisit(EnhancedForStatement node) {
- if (skipNode(node))
- return;
- EnhancedForFlowInfo forInfo= createEnhancedFor();
- setFlowInfo(node, forInfo);
- forInfo.mergeParameter(getFlowInfo(node.getParameter()), fFlowContext);
- forInfo.mergeExpression(getFlowInfo(node.getExpression()), fFlowContext);
- forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- forInfo.removeLabel(null);
- }
-
-
- public void endVisit(ExpressionStatement node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getExpression());
- }
-
- public void endVisit(FieldAccess node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getExpression(), node.getName());
- }
-
- public void endVisit(FieldDeclaration node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getType());
- process(info, node.fragments());
- }
-
- public void endVisit(ForStatement node) {
- if (skipNode(node))
- return;
- ForFlowInfo forInfo= createFor();
- setFlowInfo(node, forInfo);
- forInfo.mergeInitializer(createSequential(node.initializers()), fFlowContext);
- forInfo.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- // Increments are executed after the action.
- forInfo.mergeIncrement(createSequential(node.updaters()), fFlowContext);
- forInfo.removeLabel(null);
- }
- public void endVisit(ForInStatement node) {
- if (skipNode(node))
- return;
- EnhancedForFlowInfo forInfo= createEnhancedFor();
- setFlowInfo(node, forInfo);
- forInfo.mergeParameter(getFlowInfo(node.getIterationVariable()), fFlowContext);
- forInfo.mergeExpression(getFlowInfo(node.getCollection()), fFlowContext);
- forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- forInfo.removeLabel(null);
- }
-
-
- public void endVisit(IfStatement node) {
- if (skipNode(node))
- return;
- IfFlowInfo info= createIf();
- setFlowInfo(node, info);
- info.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- info.merge(getFlowInfo(node.getThenStatement()), getFlowInfo(node.getElseStatement()), fFlowContext);
- }
-
- public void endVisit(ImportDeclaration node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getName());
- }
-
- public void endVisit(InfixExpression node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getLeftOperand(), node.getRightOperand());
- process(info, node.extendedOperands());
- }
-
- public void endVisit(InstanceofExpression node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getLeftOperand(), node.getRightOperand());
- }
-
- public void endVisit(Initializer node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getBody());
- }
-
- public void endVisit(JSdoc node) {
- // no influence on flow analysis
- }
-
- public void endVisit(LabeledStatement node) {
- if (skipNode(node))
- return;
- FlowInfo info= assignFlowInfo(node, node.getBody());
- if (info != null)
- info.removeLabel(node.getLabel());
- }
-
- public void endVisit(ListExpression node) {
- if (skipNode(node))
- return;
- processSequential(node, node.expressions());
- }
-
-
-
- public void endVisit(FunctionDeclaration node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getReturnType2());
- process(info, node.parameters());
- process(info, node.thrownExceptions());
- process(info, node.getBody());
- }
-
- public void endVisit(FunctionInvocation node) {
- endVisitMethodInvocation(node, node.getExpression(), node.arguments(), getMethodBinding(node.getName()));
- }
-
-
- public void endVisit(NullLiteral node) {
- // Leaf node.
- }
-
- public void endVisit(NumberLiteral node) {
- // Leaf node.
- }
-
- public void endVisit(PackageDeclaration node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getName());
- }
-
- public void endVisit(ParenthesizedExpression node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getExpression());
- }
-
- public void endVisit(PostfixExpression node) {
- endVisitIncDecOperation(node, node.getOperand());
- }
-
- public void endVisit(PrefixExpression node) {
- PrefixExpression.Operator op= node.getOperator();
- if (PrefixExpression.Operator.INCREMENT.equals(op) || PrefixExpression.Operator.DECREMENT.equals(op)) {
- endVisitIncDecOperation(node, node.getOperand());
- } else {
- assignFlowInfo(node, node.getOperand());
- }
- }
-
- public void endVisit(PrimitiveType node) {
- // Leaf node
- }
-
- public void endVisit(QualifiedName node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getQualifier(), node.getName());
- }
-
- public void endVisit(QualifiedType node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getQualifier(), node.getName());
- }
-
- public void endVisit(ReturnStatement node) {
- if (skipNode(node))
- return;
-
- if (createReturnFlowInfo(node)) {
- ReturnFlowInfo info= createReturn(node);
- setFlowInfo(node, info);
- info.merge(getFlowInfo(node.getExpression()), fFlowContext);
- } else {
- assignFlowInfo(node, node.getExpression());
- }
- }
-
- public void endVisit(SimpleName node) {
- if (skipNode(node) || node.isDeclaration())
- return;
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding) {
- IVariableBinding variable= (IVariableBinding)binding;
- if (!variable.isField() && !variable.isGlobal()) {
- setFlowInfo(node, new LocalFlowInfo(
- variable,
- FlowInfo.READ,
- fFlowContext));
- }
- }
- }
-
- public void endVisit(SimpleType node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getName());
- }
-
-
- public void endVisit(SingleVariableDeclaration node) {
- if (skipNode(node))
- return;
-
- IVariableBinding binding= node.resolveBinding();
- LocalFlowInfo nameInfo= null;
- Expression initializer= node.getInitializer();
- if (binding != null && !binding.isField() && initializer != null) {
- nameInfo= new LocalFlowInfo(binding, FlowInfo.WRITE, fFlowContext);
- }
- GenericSequentialFlowInfo info= processSequential(node, node.getType(), initializer);
- info.merge(nameInfo, fFlowContext);
- }
-
- public void endVisit(StringLiteral node) {
- // Leaf node
- }
-
- public void endVisit(SuperConstructorInvocation node) {
- endVisitMethodInvocation(node, node.getExpression(), node.arguments(), node.resolveConstructorBinding());
- }
-
- public void endVisit(SuperFieldAccess node) {
- if (skipNode(node))
- return;
- processSequential(node, node.getQualifier(), node.getName());
- }
-
- public void endVisit(SuperMethodInvocation node) {
- endVisitMethodInvocation(node, node.getQualifier(), node.arguments(), getMethodBinding(node.getName()));
- }
-
- public void endVisit(SwitchCase node) {
- endVisitNode(node);
- }
-
- public void endVisit(SwitchStatement node) {
- if (skipNode(node))
- return;
- endVisit(node, createSwitchData(node));
- }
-
-
- public void endVisit(ThisExpression node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getQualifier());
- }
-
- public void endVisit(ThrowStatement node) {
- if (skipNode(node))
- return;
- ThrowFlowInfo info= createThrow();
- setFlowInfo(node, info);
- Expression expression= node.getExpression();
- info.merge(getFlowInfo(expression), fFlowContext);
- info.mergeException(expression.resolveTypeBinding(), fFlowContext);
- }
-
- public void endVisit(TryStatement node) {
- if (skipNode(node))
- return;
- TryFlowInfo info= createTry();
- setFlowInfo(node, info);
- info.mergeTry(getFlowInfo(node.getBody()), fFlowContext);
- info.removeExceptions(node);
- for (Iterator iter= node.catchClauses().iterator(); iter.hasNext();) {
- CatchClause element= (CatchClause)iter.next();
- info.mergeCatch(getFlowInfo(element), fFlowContext);
- }
- info.mergeFinally(getFlowInfo(node.getFinally()), fFlowContext);
- }
-
- // TODO account for enums and annotations
-
- public void endVisit(TypeDeclaration node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getSuperclassType());
- process(info, node.bodyDeclarations());
- info.setNoReturn();
- }
-
- public void endVisit(TypeDeclarationStatement node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getDeclaration());
- }
-
- public void endVisit(TypeLiteral node) {
- if (skipNode(node))
- return;
- assignFlowInfo(node, node.getType());
- }
-
- public void endVisit(VariableDeclarationExpression node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getType());
- process(info, node.fragments());
- }
-
- public void endVisit(VariableDeclarationStatement node) {
- if (skipNode(node))
- return;
- GenericSequentialFlowInfo info= processSequential(node, node.getType());
- process(info, node.fragments());
- }
-
- public void endVisit(VariableDeclarationFragment node) {
- if (skipNode(node))
- return;
-
- IVariableBinding binding= node.resolveBinding();
- LocalFlowInfo nameInfo= null;
- Expression initializer= node.getInitializer();
- if (binding != null && !binding.isField() && initializer != null) {
- nameInfo= new LocalFlowInfo(binding, FlowInfo.WRITE, fFlowContext);
- }
- GenericSequentialFlowInfo info= processSequential(node, initializer);
- info.merge(nameInfo, fFlowContext);
- }
-
- public void endVisit(WhileStatement node) {
- if (skipNode(node))
- return;
- WhileFlowInfo info= createWhile();
- setFlowInfo(node, info);
- info.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- info.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- info.removeLabel(null);
- }
- public void endVisit(WithStatement node) {
- if (skipNode(node))
- return;
- WithFlowInfo info= createWith();
- setFlowInfo(node, info);
- info.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
- info.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- info.removeLabel(null);
- }
-
- private void endVisitMethodInvocation(ASTNode node, ASTNode receiver, List arguments, IFunctionBinding binding) {
- if (skipNode(node))
- return;
- MessageSendFlowInfo info= createMessageSendFlowInfo();
- setFlowInfo(node, info);
- for (Iterator iter= arguments.iterator(); iter.hasNext();) {
- Expression arg= (Expression) iter.next();
- info.mergeArgument(getFlowInfo(arg), fFlowContext);
- }
- info.mergeReceiver(getFlowInfo(receiver), fFlowContext);
- }
-
- private void endVisitIncDecOperation(Expression node, Expression operand) {
- if (skipNode(node))
- return;
- FlowInfo info= getFlowInfo(operand);
- if (info instanceof LocalFlowInfo) {
- // Normally we should do this in the parent node since the write access take place later.
- // But I couldn't come up with a case where this influences the flow analysis. So I kept
- // it here to simplify the code.
- GenericSequentialFlowInfo result= createSequential(node);
- result.merge(info, fFlowContext);
- result.merge(
- new LocalFlowInfo((LocalFlowInfo)info, FlowInfo.WRITE, fFlowContext),
- fFlowContext);
- } else {
- setFlowInfo(node, info);
- }
- }
-
- private IFunctionBinding getMethodBinding(Name name) {
- if (name == null)
- return null;
- IBinding binding= name.resolveBinding();
- if (binding instanceof IFunctionBinding)
- return (IFunctionBinding)binding;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowContext.java
deleted file mode 100644
index 0731a3eb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowContext.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-
-
-public class FlowContext {
-
- private static class Enum {
- }
-
- public static final Enum MERGE= new Enum();
- public static final Enum ARGUMENTS= new Enum();
- public static final Enum RETURN_VALUES= new Enum();
-
- private int fStart;
- private int fLength;
- private boolean fConsiderAccessMode;
- private boolean fLoopReentranceMode;
- private Enum fComputeMode;
- private IVariableBinding[] fLocals;
- private List fExceptionStack;
-
- private static final List EMPTY_CATCH_CLAUSE= new ArrayList(0);
-
- public FlowContext(int start, int length) {
- fStart= start;
- fLength= length;
- fExceptionStack= new ArrayList(3);
- }
-
- public void setConsiderAccessMode(boolean b) {
- fConsiderAccessMode= b;
- }
-
- public void setComputeMode(Enum mode) {
- fComputeMode= mode;
- }
-
- void setLoopReentranceMode(boolean b) {
- fLoopReentranceMode= b;
- }
-
- int getArrayLength() {
- return fLength;
- }
-
- int getStartingIndex() {
- return fStart;
- }
-
- boolean considerAccessMode() {
- return fConsiderAccessMode;
- }
-
- boolean isLoopReentranceMode() {
- return fLoopReentranceMode;
- }
-
- boolean computeMerge() {
- return fComputeMode == MERGE;
- }
-
- boolean computeArguments() {
- return fComputeMode == ARGUMENTS;
- }
-
- boolean computeReturnValues() {
- return fComputeMode == RETURN_VALUES;
- }
-
- public IVariableBinding getLocalFromId(int id) {
- return getLocalFromIndex(id - fStart);
- }
-
- public IVariableBinding getLocalFromIndex(int index) {
- if (fLocals == null || index > fLocals.length)
- return null;
- return fLocals[index];
- }
-
- public int getIndexFromLocal(IVariableBinding local) {
- if (fLocals == null)
- return -1;
- for (int i= 0; i < fLocals.length; i++) {
- if (fLocals[i] == local)
- return i;
- }
- return -1;
- }
-
- void manageLocal(IVariableBinding local) {
- if (fLocals == null)
- fLocals= new IVariableBinding[fLength];
- fLocals[local.getVariableId() - fStart]= local;
- }
-
- //---- Exception handling --------------------------------------------------------
-
- void pushExcptions(TryStatement node) {
- List catchClauses= node.catchClauses();
- if (catchClauses == null)
- catchClauses= EMPTY_CATCH_CLAUSE;
- fExceptionStack.add(catchClauses);
- }
-
- void popExceptions() {
- Assert.isTrue(fExceptionStack.size() > 0);
- fExceptionStack.remove(fExceptionStack.size() - 1);
- }
-
- boolean isExceptionCaught(ITypeBinding excpetionType) {
- for (Iterator exceptions= fExceptionStack.iterator(); exceptions.hasNext(); ) {
- for (Iterator catchClauses= ((List)exceptions.next()).iterator(); catchClauses.hasNext(); ) {
- SingleVariableDeclaration catchedException= ((CatchClause)catchClauses.next()).getException();
- IVariableBinding binding= catchedException.resolveBinding();
- if (binding == null)
- continue;
- ITypeBinding catchedType= binding.getType();
- while (catchedType != null) {
- if (catchedType == excpetionType)
- return true;
- catchedType= catchedType.getSuperclass();
- }
- }
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowInfo.java
deleted file mode 100644
index d0accc3f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/FlowInfo.java
+++ /dev/null
@@ -1,515 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-
-public abstract class FlowInfo {
-
- // Return statement handling.
- protected static final int NOT_POSSIBLE= 0;
- protected static final int UNDEFINED= 1;
- protected static final int NO_RETURN= 2;
- protected static final int PARTIAL_RETURN= 3;
- protected static final int VOID_RETURN= 4;
- protected static final int VALUE_RETURN= 5;
- protected static final int THROW= 6;
-
- // Local access handling.
- public static final int UNUSED= 1 << 0;
- public static final int READ= 1 << 1;
- public static final int READ_POTENTIAL= 1 << 2;
- public static final int WRITE= 1 << 3;
- public static final int WRITE_POTENTIAL= 1 << 4;
- public static final int UNKNOWN= 1 << 5;
-
- // Table to merge access modes for condition statements (e.g branch[x] || branch[y]).
- private static final int[][] ACCESS_MODE_CONDITIONAL_TABLE= {
- /* UNUSED READ READ_POTENTIAL WRTIE WRITE_POTENTIAL UNKNOWN */
- /* UNUSED */ { UNUSED, READ_POTENTIAL, READ_POTENTIAL, WRITE_POTENTIAL, WRITE_POTENTIAL, UNKNOWN },
- /* READ */ { READ_POTENTIAL, READ, READ_POTENTIAL, UNKNOWN, UNKNOWN, UNKNOWN },
- /* READ_POTENTIAL */ { READ_POTENTIAL, READ_POTENTIAL, READ_POTENTIAL, UNKNOWN, UNKNOWN, UNKNOWN },
- /* WRITE */ { WRITE_POTENTIAL, UNKNOWN, UNKNOWN, WRITE, WRITE_POTENTIAL, UNKNOWN },
- /* WRITE_POTENTIAL */ { WRITE_POTENTIAL, UNKNOWN, UNKNOWN, WRITE_POTENTIAL, WRITE_POTENTIAL, UNKNOWN },
- /* UNKNOWN */ { UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN }
- };
-
- // Table to change access mode if there is an open branch statement
- private static final int[] ACCESS_MODE_OPEN_BRANCH_TABLE= {
- /* UNUSED READ READ_POTENTIAL WRTIE WRITE_POTENTIAL UNKNOWN */
- UNUSED, READ_POTENTIAL, READ_POTENTIAL, WRITE_POTENTIAL, WRITE_POTENTIAL, UNKNOWN
- };
-
- // Table to merge return modes for condition statements (y: fReturnKind, x: other.fReturnKind)
- private static final int[][] RETURN_KIND_CONDITIONAL_TABLE = {
- /* NOT_POSSIBLE UNDEFINED NO_RETURN PARTIAL_RETURN VOID_RETURN VALUE_RETURN THROW */
- /* NOT_POSSIBLE */ { NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE },
- /* UNDEFINED */ { NOT_POSSIBLE, UNDEFINED, NO_RETURN, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW },
- /* NO_RETURN */ { NOT_POSSIBLE, NO_RETURN, NO_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, NO_RETURN },
- /* PARTIAL_RETURN */ { NOT_POSSIBLE, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN },
- /* VOID_RETURN */ { NOT_POSSIBLE, VOID_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, VOID_RETURN, NOT_POSSIBLE, VOID_RETURN },
- /* VALUE_RETURN */ { NOT_POSSIBLE, VALUE_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, NOT_POSSIBLE, VALUE_RETURN, VALUE_RETURN },
- /* THROW */ { NOT_POSSIBLE, THROW, NO_RETURN, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW }
- };
-
- // Table to merge return modes for sequential statements (y: fReturnKind, x: other.fReturnKind)
- private static final int[][] RETURN_KIND_SEQUENTIAL_TABLE = {
- /* NOT_POSSIBLE UNDEFINED NO_RETURN PARTIAL_RETURN VOID_RETURN VALUE_RETURN THROW */
- /* NOT_POSSIBLE */ { NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE, NOT_POSSIBLE },
- /* UNDEFINED */ { NOT_POSSIBLE, UNDEFINED, NO_RETURN, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW },
- /* NO_RETURN */ { NOT_POSSIBLE, NO_RETURN, NO_RETURN, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW },
- /* PARTIAL_RETURN */ { NOT_POSSIBLE, PARTIAL_RETURN, PARTIAL_RETURN, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW },
- /* VOID_RETURN */ { NOT_POSSIBLE, VOID_RETURN, VOID_RETURN, PARTIAL_RETURN, VOID_RETURN, NOT_POSSIBLE, NOT_POSSIBLE },
- /* VALUE_RETURN */ { NOT_POSSIBLE, VALUE_RETURN, VALUE_RETURN, PARTIAL_RETURN, NOT_POSSIBLE, VALUE_RETURN, NOT_POSSIBLE },
- /* THROW */ { NOT_POSSIBLE, THROW, THROW, PARTIAL_RETURN, VOID_RETURN, VALUE_RETURN, THROW }
- };
-
- protected static final String UNLABELED = "@unlabeled"; //$NON-NLS-1$
- protected static final IVariableBinding[] EMPTY_ARRAY= new IVariableBinding[0];
-
- protected int fReturnKind;
- protected int[] fAccessModes;
- protected Set fBranches;
- protected Set fExceptions;
- protected Set fTypeVariables;
-
- protected FlowInfo() {
- this(UNDEFINED);
- }
-
- protected FlowInfo(int returnKind) {
- fReturnKind= returnKind;
- }
-
- //---- General Helpers ----------------------------------------------------------
-
- protected void assignExecutionFlow(FlowInfo right) {
- fReturnKind= right.fReturnKind;
- fBranches= right.fBranches;
- fExceptions= right.fExceptions;
- }
-
- protected void assignAccessMode(FlowInfo right) {
- fAccessModes= right.fAccessModes;
- }
-
- protected void assign(FlowInfo right) {
- assignExecutionFlow(right);
- assignAccessMode(right);
- }
-
- protected void mergeConditional(FlowInfo info, FlowContext context) {
- mergeAccessModeConditional(info, context);
- mergeExecutionFlowConditional(info, context);
- mergeTypeVariablesConditional(info, context);
- }
-
- protected void mergeSequential(FlowInfo info, FlowContext context) {
- mergeAccessModeSequential(info, context);
- mergeExecutionFlowSequential(info, context);
- mergeTypeVariablesSequential(info, context);
- }
-
- //---- Return Kind ------------------------------------------------------------------
-
- public void setNoReturn() {
- fReturnKind= NO_RETURN;
- }
-
- public boolean isUndefined() {
- return fReturnKind == UNDEFINED;
- }
-
- public boolean isNoReturn() {
- return fReturnKind == NO_RETURN;
- }
-
- public boolean isPartialReturn() {
- return fReturnKind == PARTIAL_RETURN;
- }
-
- public boolean isVoidReturn() {
- return fReturnKind == VOID_RETURN;
- }
-
- public boolean isValueReturn() {
- return fReturnKind == VALUE_RETURN;
- }
-
- public boolean isThrow() {
- return fReturnKind == THROW;
- }
-
- public boolean isReturn() {
- return fReturnKind == VOID_RETURN || fReturnKind == VALUE_RETURN;
- }
-
- //---- Branches -------------------------------------------------------------------------
-
- public boolean branches() {
- return fBranches != null && !fBranches.isEmpty();
- }
-
- protected Set getBranches() {
- return fBranches;
- }
-
- protected void removeLabel(SimpleName label) {
- if (fBranches != null) {
- fBranches.remove(makeString(label));
- if (fBranches.isEmpty())
- fBranches= null;
- }
- }
-
- protected static String makeString(SimpleName label) {
- if (label == null)
- return UNLABELED;
- else
- return label.getIdentifier();
- }
-
- //---- Exceptions -----------------------------------------------------------------------
-
- public ITypeBinding[] getExceptions() {
- if (fExceptions == null)
- return new ITypeBinding[0];
- return (ITypeBinding[]) fExceptions.toArray(new ITypeBinding[fExceptions.size()]);
- }
-
- protected boolean hasUncaughtException() {
- return fExceptions != null && !fExceptions.isEmpty();
- }
-
- protected void addException(ITypeBinding type) {
- if (fExceptions == null)
- fExceptions= new HashSet(2);
- fExceptions.add(type);
- }
-
- protected void removeExceptions(TryStatement node) {
- if (fExceptions == null)
- return;
-
- List catchClauses= node.catchClauses();
- if (catchClauses.isEmpty())
- return;
- // Make sure we have a copy since we are modifing the fExceptions list
- ITypeBinding[] exceptions= (ITypeBinding[]) fExceptions.toArray(new ITypeBinding[fExceptions.size()]);
- for (int i= 0; i < exceptions.length; i++) {
- handleException(catchClauses, exceptions[i]);
- }
- if (fExceptions.isEmpty())
- fExceptions= null;
- }
-
- private void handleException(List catchClauses, ITypeBinding type) {
- for (Iterator iter= catchClauses.iterator(); iter.hasNext();) {
- IVariableBinding binding= ((CatchClause)iter.next()).getException().resolveBinding();
- if (binding == null)
- continue;
- ITypeBinding catchedType= binding.getType();
- while (catchedType != null) {
- if (catchedType == type) {
- fExceptions.remove(type);
- return;
- }
- catchedType= catchedType.getSuperclass();
- }
- }
- }
-
- //---- Type parameters -----------------------------------------------------------------
-
- public ITypeBinding[] getTypeVariables() {
- if (fTypeVariables == null)
- return new ITypeBinding[0];
- return (ITypeBinding[])fTypeVariables.toArray(new ITypeBinding[fTypeVariables.size()]);
- }
-
- protected void addTypeVariable(ITypeBinding typeParameter) {
- if (fTypeVariables == null)
- fTypeVariables= new HashSet();
- fTypeVariables.add(typeParameter);
- }
-
- private void mergeTypeVariablesSequential(FlowInfo otherInfo, FlowContext context) {
- fTypeVariables= mergeSets(fTypeVariables, otherInfo.fTypeVariables);
- }
-
- private void mergeTypeVariablesConditional(FlowInfo otherInfo, FlowContext context) {
- fTypeVariables= mergeSets(fTypeVariables, otherInfo.fTypeVariables);
- }
-
- //---- Execution flow -------------------------------------------------------------------
-
- private void mergeExecutionFlowSequential(FlowInfo otherInfo, FlowContext context) {
- int other= otherInfo.fReturnKind;
- if (branches() && other == VALUE_RETURN)
- other= PARTIAL_RETURN;
- fReturnKind= RETURN_KIND_SEQUENTIAL_TABLE[fReturnKind][other];
- mergeBranches(otherInfo, context);
- mergeExceptions(otherInfo, context);
- }
-
- private void mergeExecutionFlowConditional(FlowInfo otherInfo, FlowContext context) {
- fReturnKind= RETURN_KIND_CONDITIONAL_TABLE[fReturnKind][otherInfo.fReturnKind];
- mergeBranches(otherInfo, context);
- mergeExceptions(otherInfo, context);
- }
-
- private void mergeBranches(FlowInfo otherInfo, FlowContext context) {
- fBranches= mergeSets(fBranches, otherInfo.fBranches);
- }
-
- private void mergeExceptions(FlowInfo otherInfo, FlowContext context) {
- fExceptions= mergeSets(fExceptions, otherInfo.fExceptions);
- }
-
- private static Set mergeSets(Set thisSet, Set otherSet) {
- if (otherSet != null) {
- if (thisSet == null) {
- thisSet= otherSet;
- } else {
- Iterator iter= otherSet.iterator();
- while (iter.hasNext()) {
- thisSet.add(iter.next());
- }
- }
- }
- return thisSet;
- }
-
- //---- Local access handling --------------------------------------------------
-
- /**
- * Returns an array of <code>IVariableBinding</code> that conform to the given
- * access mode <code>mode</code>.
- *
- * @param context the flow context object used to compute this flow info
- * @param mode the access type. Valid values are <code>READ</code>, <code>WRITE</code>,
- * <code>UNKNOWN</code> and any combination of them.
- * @return an array of local variable bindings conforming to the given type.
- */
- public IVariableBinding[] get(FlowContext context, int mode) {
- List result= new ArrayList();
- int[] locals= getAccessModes();
- if (locals == null)
- return EMPTY_ARRAY;
- for (int i= 0; i < locals.length; i++) {
- int accessMode= locals[i];
- if ((accessMode & mode) != 0)
- result.add(context.getLocalFromIndex(i));
- }
- return (IVariableBinding[])result.toArray(new IVariableBinding[result.size()]);
- }
-
- /**
- * Checks whether the given local variable binding has the given access
- * mode.
- *
- * @return <code>true</code> if the binding has the given access mode.
- * <code>False</code> otherwise
- */
- public boolean hasAccessMode(FlowContext context, IVariableBinding local, int mode) {
- boolean unusedMode= (mode & UNUSED) != 0;
- if (fAccessModes == null && unusedMode)
- return true;
- int index= context.getIndexFromLocal(local);
- if (index == -1)
- return unusedMode;
- return (fAccessModes[index] & mode) != 0;
- }
-
- /**
- * Returns the access mode of the local variable identified by the given binding.
- *
- * @param context the flow context used during flow analysis
- * @param local the local variable of interest
- * @return the access mode of the local variable
- */
- public int getAccessMode(FlowContext context, IVariableBinding local) {
- if (fAccessModes == null)
- return UNUSED;
- int index= context.getIndexFromLocal(local);
- if (index == -1)
- return UNUSED;
- return fAccessModes[index];
- }
-
- protected int[] getAccessModes() {
- return fAccessModes;
- }
-
- protected void clearAccessMode(IVariableBinding binding, FlowContext context) {
- if (fAccessModes == null) // all are unused
- return;
- fAccessModes[binding.getVariableId() - context.getStartingIndex()]= UNUSED;
- }
-
- protected void mergeAccessModeSequential(FlowInfo otherInfo, FlowContext context) {
- if (!context.considerAccessMode())
- return;
-
- int[] others= otherInfo.fAccessModes;
- if (others == null) // others are all unused. So nothing to do
- return;
-
- // Must not consider return kind since a return statement can't control execution flow
- // inside a method. It always leaves the method.
- if (branches() || hasUncaughtException()) {
- for (int i= 0; i < others.length; i++)
- others[i]= ACCESS_MODE_OPEN_BRANCH_TABLE[getIndex(others[i])];
- }
-
- if (fAccessModes == null) { // all current variables are unused
- fAccessModes= others;
- return;
- }
-
- if (context.computeArguments()) {
- handleComputeArguments(others);
- } else if (context.computeReturnValues()) {
- handleComputeReturnValues(others);
- } else if (context.computeMerge()) {
- handleMergeValues(others);
- }
- }
-
- private void handleComputeReturnValues(int[] others) {
- for (int i= 0; i < fAccessModes.length; i++) {
- int accessmode= fAccessModes[i];
- int othermode= others[i];
- if (accessmode == WRITE)
- continue;
- if (accessmode == WRITE_POTENTIAL) {
- if (othermode == WRITE)
- fAccessModes[i]= WRITE;
- continue;
- }
-
- if (others[i] != UNUSED)
- fAccessModes[i]= othermode;
- }
- }
-
- private void handleComputeArguments(int[] others) {
- for (int i= 0; i < fAccessModes.length; i++) {
- int accessMode= fAccessModes[i];
- int otherMode= others[i];
- if (accessMode == UNUSED) {
- fAccessModes[i]= otherMode;
- } else if (accessMode == WRITE_POTENTIAL && (otherMode == READ || otherMode == READ_POTENTIAL)) {
- // Read always supersedes a potential write even if the read is potential as well
- // (we have to consider the potential read as an argument then).
- fAccessModes[i]= otherMode;
- } else if (accessMode == WRITE_POTENTIAL && otherMode == WRITE) {
- fAccessModes[i]= WRITE;
- }
- }
- }
-
- private void handleMergeValues(int[] others) {
- for (int i= 0; i < fAccessModes.length; i++) {
- fAccessModes[i]= ACCESS_MODE_CONDITIONAL_TABLE
- [getIndex(fAccessModes[i])]
- [getIndex(others[i])];
- }
- }
-
- protected void createAccessModeArray(FlowContext context) {
- fAccessModes= new int[context.getArrayLength()];
- for (int i= 0; i < fAccessModes.length; i++) {
- fAccessModes[i]= UNUSED;
- }
- }
-
- protected void mergeAccessModeConditional(FlowInfo otherInfo, FlowContext context) {
- if (!context.considerAccessMode())
- return;
-
- int[] others= otherInfo.fAccessModes;
- // first access
- if (fAccessModes == null) {
- if (others != null)
- fAccessModes= others;
- else
- createAccessModeArray(context);
- return;
- } else {
- if (others == null) {
- for (int i= 0; i < fAccessModes.length; i++) {
- int unused_index= getIndex(UNUSED);
- fAccessModes[i]= ACCESS_MODE_CONDITIONAL_TABLE
- [getIndex(fAccessModes[i])]
- [unused_index];
- }
- } else {
- for (int i= 0; i < fAccessModes.length; i++) {
- fAccessModes[i]= ACCESS_MODE_CONDITIONAL_TABLE
- [getIndex(fAccessModes[i])]
- [getIndex(others[i])];
- }
- }
- }
- }
-
- protected void mergeEmptyCondition(FlowContext context) {
- if (fReturnKind == VALUE_RETURN || fReturnKind == VOID_RETURN)
- fReturnKind= PARTIAL_RETURN;
-
- if (!context.considerAccessMode())
- return;
-
- if (fAccessModes == null) {
- createAccessModeArray(context);
- return;
- }
-
- int unused_index= getIndex(UNUSED);
- for (int i= 0; i < fAccessModes.length; i++) {
- fAccessModes[i]= ACCESS_MODE_CONDITIONAL_TABLE
- [getIndex(fAccessModes[i])]
- [unused_index];
- }
- }
-
- private static int getIndex(int accessMode) {
- // Fast log function
- switch (accessMode) {
- case UNUSED:
- return 0;
- case READ:
- return 1;
- case READ_POTENTIAL:
- return 2;
- case WRITE:
- return 3;
- case WRITE_POTENTIAL:
- return 4;
- case UNKNOWN:
- return 5;
- }
- return -1;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ForFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ForFlowInfo.java
deleted file mode 100644
index e78cd57c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ForFlowInfo.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class ForFlowInfo extends FlowInfo {
-
- public void mergeInitializer(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeIncrement(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- info.mergeEmptyCondition(context);
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeAction(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- info.mergeEmptyCondition(context);
-
- mergeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericConditionalFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericConditionalFlowInfo.java
deleted file mode 100644
index ebe72f3e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericConditionalFlowInfo.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-
-
-class GenericConditionalFlowInfo extends FlowInfo {
-
- public GenericConditionalFlowInfo() {
- super(UNDEFINED);
- }
-
- public void merge(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeConditional(info, context);
- }
-
- public void mergeAccessMode(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeAccessModeConditional(info, context);
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericSequentialFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericSequentialFlowInfo.java
deleted file mode 100644
index eee153eb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/GenericSequentialFlowInfo.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-
-
-class GenericSequentialFlowInfo extends FlowInfo {
-
- public GenericSequentialFlowInfo() {
- super(NO_RETURN);
- }
-
- public void merge(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeSequential(info, context);
- }
-
- public void mergeAccessMode(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/IfFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/IfFlowInfo.java
deleted file mode 100644
index eef6513c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/IfFlowInfo.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class IfFlowInfo extends FlowInfo {
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeAccessModeSequential(info, context);
- }
-
- public void merge(FlowInfo thenPart, FlowInfo elsePart, FlowContext context) {
- if (thenPart == null && elsePart == null)
- return;
-
- GenericConditionalFlowInfo cond= new GenericConditionalFlowInfo();
- if (thenPart != null)
- cond.merge(thenPart, context);
-
- if (elsePart != null)
- cond.merge(elsePart, context);
-
- if (thenPart == null || elsePart == null)
- cond.mergeEmptyCondition(context);
-
- mergeSequential(cond, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InOutFlowAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InOutFlowAnalyzer.java
deleted file mode 100644
index a2c66ad7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InOutFlowAnalyzer.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-
-public class InOutFlowAnalyzer extends FlowAnalyzer {
-
- public InOutFlowAnalyzer(FlowContext context) {
- super(context);
- }
-
- public FlowInfo perform(ASTNode[] selectedNodes) {
- FlowContext context= getFlowContext();
- GenericSequentialFlowInfo result= createSequential();
- for (int i= 0; i < selectedNodes.length; i++) {
- ASTNode node= selectedNodes[i];
- node.accept(this);
- result.merge(getFlowInfo(node), context);
- }
- return result;
- }
-
- protected boolean traverseNode(ASTNode node) {
- // we are only traversing the selected nodes.
- return true;
- }
-
- protected boolean createReturnFlowInfo(ReturnStatement node) {
- // we are only traversing selected nodes.
- return true;
- }
-
- public void endVisit(Block node) {
- super.endVisit(node);
- clearAccessMode(accessFlowInfo(node), node.statements());
- }
-
- public void endVisit(CatchClause node) {
- super.endVisit(node);
- clearAccessMode(accessFlowInfo(node), node.getException());
- }
-
- public void endVisit(EnhancedForStatement node) {
- super.endVisit(node);
- clearAccessMode(accessFlowInfo(node), node.getParameter());
- }
-
- public void endVisit(ForStatement node) {
- super.endVisit(node);
- clearAccessMode(accessFlowInfo(node), node.initializers());
- }
- public void endVisit(ForInStatement node) {
- super.endVisit(node);
- if (node.getIterationVariable() instanceof VariableDeclarationStatement)
- clearAccessMode(accessFlowInfo(node), (VariableDeclarationStatement)node.getIterationVariable());
- }
-
- public void endVisit(FunctionDeclaration node) {
- super.endVisit(node);
- FlowInfo info= accessFlowInfo(node);
- for (Iterator iter= node.parameters().iterator(); iter.hasNext();) {
- clearAccessMode(info, (SingleVariableDeclaration)iter.next());
- }
- }
-
- private void clearAccessMode(FlowInfo info, SingleVariableDeclaration decl) {
- IVariableBinding binding= decl.resolveBinding();
- if (binding != null && !binding.isField())
- info.clearAccessMode(binding, fFlowContext);
- }
- private void clearAccessMode(FlowInfo info, VariableDeclarationStatement decl) {
- IVariableBinding binding= decl.resolveBinding();
- if (binding != null && !binding.isField())
- info.clearAccessMode(binding, fFlowContext);
- }
-
- private void clearAccessMode(FlowInfo info, List nodes) {
- if (nodes== null || nodes.isEmpty() || info == null)
- return;
- for (Iterator iter= nodes.iterator(); iter.hasNext(); ) {
- Object node= iter.next();
- Iterator fragments= null;
- if (node instanceof VariableDeclarationStatement) {
- fragments= ((VariableDeclarationStatement)node).fragments().iterator();
- } else if (node instanceof VariableDeclarationExpression) {
- fragments= ((VariableDeclarationExpression)node).fragments().iterator();
- }
- if (fragments != null) {
- while (fragments.hasNext()) {
- clearAccessMode(info, (VariableDeclarationFragment)fragments.next());
- }
- }
- }
- }
-
- private void clearAccessMode(FlowInfo info, VariableDeclarationFragment fragment) {
- IVariableBinding binding= fragment.resolveBinding();
- if (binding != null && !binding.isField())
- info.clearAccessMode(binding, fFlowContext);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java
deleted file mode 100644
index bfb35c95..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * o inline call that is used in a field initializer
- * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38137)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-
-public class InputFlowAnalyzer extends FlowAnalyzer {
-
- private static class LoopReentranceVisitor extends FlowAnalyzer {
- private Selection fSelection;
- private ASTNode fLoopNode;
- public LoopReentranceVisitor(FlowContext context, Selection selection, ASTNode loopNode) {
- super(context);
- fSelection= selection;
- fLoopNode= loopNode;
- }
- protected boolean traverseNode(ASTNode node) {
- return true; // end <= fSelection.end || fSelection.enclosedBy(start, end);
- }
- protected boolean createReturnFlowInfo(ReturnStatement node) {
- // Make sure that the whole return statement is selected or located before the selection.
- return node.getStartPosition() + node.getLength() <= fSelection.getExclusiveEnd();
- }
- protected ASTNode getLoopNode() {
- return fLoopNode;
- }
- public void process(ASTNode node) {
- try {
- fFlowContext.setLoopReentranceMode(true);
- node.accept(this);
- } finally {
- fFlowContext.setLoopReentranceMode(false);
- }
- }
- public void endVisit(DoStatement node) {
- if (skipNode(node))
- return;
- DoWhileFlowInfo info= createDoWhile();
- setFlowInfo(node, info);
- info.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
- // No need to merge the condition. It was already considered by the InputFlowAnalyzer.
- info.removeLabel(null);
- }
- public void endVisit(ForInStatement node) {
- if (skipNode(node))
- return;
- FlowInfo paramInfo= getFlowInfo(node.getIterationVariable());
- FlowInfo expressionInfo= getFlowInfo(node.getCollection());
- FlowInfo actionInfo= getFlowInfo(node.getBody());
- EnhancedForFlowInfo forInfo= createEnhancedFor();
- setFlowInfo(node, forInfo);
- // If the for statement is the outermost loop then we only have to consider
- // the action. The parameter and expression are only evaluated once.
- if (node == fLoopNode) {
- forInfo.mergeAction(actionInfo, fFlowContext);
- } else {
- // Inner for loops are evaluated in the sequence expression, parameter,
- // action.
- forInfo.mergeExpression(expressionInfo, fFlowContext);
- forInfo.mergeParameter(paramInfo, fFlowContext);
- forInfo.mergeAction(actionInfo, fFlowContext);
- }
- forInfo.removeLabel(null);
- }
-
- public void endVisit(EnhancedForStatement node) {
- if (skipNode(node))
- return;
- FlowInfo paramInfo= getFlowInfo(node.getParameter());
- FlowInfo expressionInfo= getFlowInfo(node.getExpression());
- FlowInfo actionInfo= getFlowInfo(node.getBody());
- EnhancedForFlowInfo forInfo= createEnhancedFor();
- setFlowInfo(node, forInfo);
- // If the for statement is the outermost loop then we only have to consider
- // the action. The parameter and expression are only evaluated once.
- if (node == fLoopNode) {
- forInfo.mergeAction(actionInfo, fFlowContext);
- } else {
- // Inner for loops are evaluated in the sequence expression, parameter,
- // action.
- forInfo.mergeExpression(expressionInfo, fFlowContext);
- forInfo.mergeParameter(paramInfo, fFlowContext);
- forInfo.mergeAction(actionInfo, fFlowContext);
- }
- forInfo.removeLabel(null);
- }
-
- public void endVisit(ForStatement node) {
- if (skipNode(node))
- return;
- FlowInfo initInfo= createSequential(node.initializers());
- FlowInfo conditionInfo= getFlowInfo(node.getExpression());
- FlowInfo incrementInfo= createSequential(node.updaters());
- FlowInfo actionInfo= getFlowInfo(node.getBody());
- ForFlowInfo forInfo= createFor();
- setFlowInfo(node, forInfo);
- // the for statement is the outermost loop. In this case we only have
- // to consider the increment, condition and action.
- if (node == fLoopNode) {
- forInfo.mergeIncrement(incrementInfo, fFlowContext);
- forInfo.mergeCondition(conditionInfo, fFlowContext);
- forInfo.mergeAction(actionInfo, fFlowContext);
- } else {
- // we have to merge two different cases. One if we reenter the for statement
- // immediatelly (that means we have to consider increments, condition and action)
- // and the other case if we reenter the for in the next loop of
- // the outer loop. Then we have to consider initializations, condtion and action.
- // For a conditional flow info that means:
- // (initializations | increments) & condition & action.
- GenericConditionalFlowInfo initIncr= new GenericConditionalFlowInfo();
- initIncr.merge(initInfo, fFlowContext);
- initIncr.merge(incrementInfo, fFlowContext);
- forInfo.mergeAccessModeSequential(initIncr, fFlowContext);
- forInfo.mergeCondition(conditionInfo, fFlowContext);
- forInfo.mergeAction(actionInfo, fFlowContext);
- }
- forInfo.removeLabel(null);
- }
- }
-
- private Selection fSelection;
- private boolean fDoLoopReentrance;
- private LoopReentranceVisitor fLoopReentranceVisitor;
-
- public InputFlowAnalyzer(FlowContext context, Selection selection, boolean doLoopReentrance) {
- super(context);
- fSelection= selection;
- Assert.isNotNull(fSelection);
- fDoLoopReentrance= doLoopReentrance;
- }
-
- public FlowInfo perform(BodyDeclaration node) {
- Assert.isTrue(!(node instanceof AbstractTypeDeclaration));
- node.accept(this);
- return getFlowInfo(node);
- }
-
- protected boolean traverseNode(ASTNode node) {
- return node.getStartPosition() + node.getLength() > fSelection.getInclusiveEnd();
- }
-
- protected boolean createReturnFlowInfo(ReturnStatement node) {
- // Make sure that the whole return statement is located after the selection. There can be cases like
- // return i + [x + 10] * 10; In this case we must not create a return info node.
- return node.getStartPosition() >= fSelection.getInclusiveEnd();
- }
-
- public boolean visit(DoStatement node) {
- createLoopReentranceVisitor(node);
- return super.visit(node);
- }
-
- public boolean visit(EnhancedForStatement node) {
- createLoopReentranceVisitor(node);
- return super.visit(node);
- }
-
- public boolean visit(ForStatement node) {
- createLoopReentranceVisitor(node);
- return super.visit(node);
- }
-
- public boolean visit(ForInStatement node) {
- createLoopReentranceVisitor(node);
- return super.visit(node);
- }
-
- public boolean visit(WhileStatement node) {
- createLoopReentranceVisitor(node);
- return super.visit(node);
- }
-
- private void createLoopReentranceVisitor(ASTNode node) {
- if (fLoopReentranceVisitor == null && fDoLoopReentrance)
- fLoopReentranceVisitor= new LoopReentranceVisitor(fFlowContext, fSelection, node);
- }
-
- public void endVisit(ConditionalExpression node) {
- if (skipNode(node))
- return;
- Expression thenPart= node.getThenExpression();
- Expression elsePart= node.getElseExpression();
- if ((thenPart != null && fSelection.coveredBy(thenPart)) ||
- (elsePart != null && fSelection.coveredBy(elsePart))) {
- GenericSequentialFlowInfo info= createSequential();
- setFlowInfo(node, info);
- endVisitConditional(info, node.getExpression(), new ASTNode[] {thenPart, elsePart});
- } else {
- super.endVisit(node);
- }
- }
-
- public void endVisit(DoStatement node) {
- super.endVisit(node);
- handleLoopReentrance(node);
- }
-
- public void endVisit(IfStatement node) {
- if (skipNode(node))
- return;
- Statement thenPart= node.getThenStatement();
- Statement elsePart= node.getElseStatement();
- if ((thenPart != null && fSelection.coveredBy(thenPart)) ||
- (elsePart != null && fSelection.coveredBy(elsePart))) {
- GenericSequentialFlowInfo info= createSequential();
- setFlowInfo(node, info);
- endVisitConditional(info, node.getExpression(), new ASTNode[] {thenPart, elsePart});
- } else {
- super.endVisit(node);
- }
- }
-
- public void endVisit(EnhancedForStatement node) {
- super.endVisit(node);
- handleLoopReentrance(node);
- }
-
- public void endVisit(ForStatement node) {
- super.endVisit(node);
- handleLoopReentrance(node);
- }
- public void endVisit(ForInStatement node) {
- super.endVisit(node);
- handleLoopReentrance(node);
- }
-
- public void endVisit(SwitchStatement node) {
- if (skipNode(node))
- return;
- SwitchData data= createSwitchData(node);
- IRegion[] ranges= data.getRanges();
- for (int i= 0; i < ranges.length; i++) {
- IRegion range= ranges[i];
- if (fSelection.coveredBy(range)) {
- GenericSequentialFlowInfo info= createSequential();
- setFlowInfo(node, info);
- info.merge(getFlowInfo(node.getExpression()), fFlowContext);
- info.merge(data.getInfo(i), fFlowContext);
- info.removeLabel(null);
- return;
- }
- }
- super.endVisit(node, data);
- }
-
- public void endVisit(WhileStatement node) {
- super.endVisit(node);
- handleLoopReentrance(node);
- }
-
- private void endVisitConditional(GenericSequentialFlowInfo info, ASTNode condition, ASTNode[] branches) {
- info.merge(getFlowInfo(condition), fFlowContext);
- for (int i= 0; i < branches.length; i++) {
- ASTNode branch= branches[i];
- if (branch != null && fSelection.coveredBy(branch)) {
- info.merge(getFlowInfo(branch), fFlowContext);
- break;
- }
- }
- }
-
- private void handleLoopReentrance(ASTNode node) {
- if (!fSelection.coveredBy(node) || fLoopReentranceVisitor == null || fLoopReentranceVisitor.getLoopNode() != node)
- return;
-
- fLoopReentranceVisitor.process(node);
- GenericSequentialFlowInfo info= createSequential();
- info.merge(getFlowInfo(node), fFlowContext);
- info.merge(fLoopReentranceVisitor.getFlowInfo(node), fFlowContext);
- setFlowInfo(node, info);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java
deleted file mode 100644
index b6f63170..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/LocalFlowInfo.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-
-class LocalFlowInfo extends FlowInfo {
-
- private int fVariableId;
-
- public LocalFlowInfo(IVariableBinding binding, int localAccessMode, FlowContext context) {
- super(NO_RETURN);
- fVariableId= binding.getVariableId();
- if (context.considerAccessMode()) {
- createAccessModeArray(context);
- fAccessModes[fVariableId - context.getStartingIndex()]= localAccessMode;
- context.manageLocal(binding);
- }
- }
-
- public LocalFlowInfo(LocalFlowInfo info, int localAccessMode, FlowContext context) {
- super(NO_RETURN);
- fVariableId= info.fVariableId;
- if (context.considerAccessMode()) {
- createAccessModeArray(context);
- fAccessModes[fVariableId - context.getStartingIndex()]= localAccessMode;
- }
- }
-
- public void setWriteAccess(FlowContext context) {
- if (context.considerAccessMode()) {
- fAccessModes[fVariableId - context.getStartingIndex()]= FlowInfo.WRITE;
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/MessageSendFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/MessageSendFlowInfo.java
deleted file mode 100644
index e8ab71a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/MessageSendFlowInfo.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-
-class MessageSendFlowInfo extends FlowInfo {
-
- public MessageSendFlowInfo() {
- super(NO_RETURN);
- }
-
- public void mergeArgument(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeSequential(info, context);
- }
-
- public void mergeReceiver(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeSequential(info, context);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java
deleted file mode 100644
index 7282b4b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-
-class ReturnFlowInfo extends FlowInfo {
-
- public ReturnFlowInfo(ReturnStatement node) {
- super(getReturnFlag(node));
- }
-
- public void merge(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- assignAccessMode(info);
- }
-
- private static int getReturnFlag(ReturnStatement node) {
- Expression expression= node.getExpression();
- if (expression == null || expression.resolveTypeBinding() == node.getAST().resolveWellKnownType("void")) //$NON-NLS-1$
- return VOID_RETURN;
- return VALUE_RETURN;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/SwitchFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/SwitchFlowInfo.java
deleted file mode 100644
index 65392ce3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/SwitchFlowInfo.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class SwitchFlowInfo extends FlowInfo {
- private GenericConditionalFlowInfo fCases;
- private boolean fHasNullCaseInfo;
-
- public SwitchFlowInfo() {
- fCases= new GenericConditionalFlowInfo();
- }
-
- public void mergeTest(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
- mergeSequential(info, context);
- }
-
- public void mergeCase(FlowInfo info, FlowContext context) {
- if (info == null) {
- fHasNullCaseInfo= true;
- return;
- }
- fCases.mergeConditional(info, context);
- }
-
- public void mergeDefault(boolean defaultCaseExists, FlowContext context) {
- if (!defaultCaseExists || fHasNullCaseInfo)
- fCases.mergeEmptyCondition(context);
- mergeSequential(fCases, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ThrowFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ThrowFlowInfo.java
deleted file mode 100644
index 98edbe11..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ThrowFlowInfo.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-class ThrowFlowInfo extends FlowInfo {
-
- public ThrowFlowInfo() {
- super(THROW);
- }
-
- public void merge(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- assignAccessMode(info);
- }
-
- public void mergeException(ITypeBinding exception, FlowContext context) {
- if (exception != null && context.isExceptionCaught(exception))
- addException(exception);
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TryFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TryFlowInfo.java
deleted file mode 100644
index 44f9d39e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TryFlowInfo.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class TryFlowInfo extends FlowInfo {
-
- public TryFlowInfo() {
- super();
- }
-
- public void mergeTry(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- assign(info);
- }
-
- public void mergeCatch(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeConditional(info, context);
- }
-
- public void mergeFinally(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TypeVariableFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TypeVariableFlowInfo.java
deleted file mode 100644
index 5309ad8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/TypeVariableFlowInfo.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-class TypeVariableFlowInfo extends FlowInfo {
-
- public TypeVariableFlowInfo(ITypeBinding binding, FlowContext context) {
- super(NO_RETURN);
- addTypeVariable(binding);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WhileFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WhileFlowInfo.java
deleted file mode 100644
index c816f67c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WhileFlowInfo.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class WhileFlowInfo extends FlowInfo {
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeAction(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- info.mergeEmptyCondition(context);
-
- mergeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WithFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WithFlowInfo.java
deleted file mode 100644
index 4393a686..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/WithFlowInfo.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow;
-
-class WithFlowInfo extends FlowInfo {
-
- public void mergeCondition(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- mergeAccessModeSequential(info, context);
- }
-
- public void mergeAction(FlowInfo info, FlowContext context) {
- if (info == null)
- return;
-
- info.mergeEmptyCondition(context);
-
- mergeSequential(info, context);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateCreator.java
deleted file mode 100644
index a944b5d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateCreator.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.delegates;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-/**
- * <p>
- * This class implements functionality for creating delegates of renamed or moved
- * members pointing to the original element and containing a
- * deprecation message. The delegate is always created in the source file of the
- * original element and is either added directly after the original element or
- * replaces it. Use this class as follows:
- * </p>
- *
- * <pre>
- * DelegateCreator myCreator= new DelegateMethodCreator();
- * myCreator.setRewrite(... cu-rewrite of modified file...);
- * myCreator.setDeclaration(... declaration of moved/renamed member ...);
- *
- * ... additional initialization methods, see below...
- *
- * myCreator.prepareDelegate();
- *
- * ... do something with the delegate before the edit is created ...
- *
- * myCreator.createEdit();
- * </pre>
- *
- * <p>
- * Before prepareDelegate(), depending on whether the member is moved or
- * renamed, or both, as well as other concerns, the following methods may be
- * called:
- * </p>
- *
- * <pre>
- * myCreator.setNewLocation(... new location where the member was moved ...);
- * myCreator.setNewName(... new name of the member if renamed ...);
- * myCreator.setDeclareDeprecated(... false or true ...);
- * myCreator.setCopy(... false or true...);
- * </pre>
- *
- * <p>
- * Note that removing or adding imports related to delegate creation is
- * generally the responsibility of the caller. As an exception, the import for a
- * target type set via setNewLocation() will be added by this class.
- * </p>
- *
- * <p>
- * This class is intended to be subclassed by specialized creators for concrete
- * element types like methods or fields.
- * </p>
- *
- *
- *
- */
-public abstract class DelegateCreator {
-
- public static final GroupCategorySet CATEGORY_DELEGATE= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.delegate", RefactoringCoreMessages.DelegateCreator_change_category_title, RefactoringCoreMessages.DelegateCreator_change_category_description)); //$NON-NLS-1$
-
- /*
- * We are dealing with two CURewrites here:
- *
- * 1) The original rewrite which is passed in from the outside. One import may
- * be registered with this CURewrite in case setNewLocation() is called.
- * On createEdit(), the complete delegate code will be added to the CURewrite's
- * ASTRewrite (add or replace).
- *
- * 2) A new CuRewrite from which we'll only use the ASTRewrite to build the new delegate.
- *
- */
- private CompilationUnitRewrite fOriginalRewrite;
- private CompilationUnitRewrite fDelegateRewrite;
-
- private boolean fIsMoveToAnotherFile;
- private boolean fCopy;
- private boolean fDeclareDeprecated;
- private boolean fInsertBefore;
-
- private BodyDeclaration fDeclaration;
- private String fNewElementName;
- private ITypeBinding fDestinationTypeBinding;
- private Type fDestinationType;
- private ITrackedNodePosition fTrackedPosition;
-
- private CodeGenerationSettings fPreferences;
-
- public DelegateCreator() {
- fCopy= true;
- fDeclareDeprecated= true;
- fInsertBefore= false;
- }
-
- /**
- * Sets the compilation unit rewrite of the declaration to create a delegate
- * for. Must always be called prior to prepareDelegate(). Bindings need not
- * be resolved.
- *
- * @param rewrite the CompilationUnitRewrite.
- */
- public void setSourceRewrite(CompilationUnitRewrite rewrite) {
- fOriginalRewrite= rewrite;
- fPreferences= JavaPreferencesSettings.getCodeGenerationSettings(rewrite.getCu().getJavaScriptProject());
-
- fDelegateRewrite= new CompilationUnitRewrite(rewrite.getCu(), rewrite.getRoot());
- fDelegateRewrite.getASTRewrite().setTargetSourceRangeComputer(rewrite.getASTRewrite().getExtendedSourceRangeComputer());
- }
-
- /**
- * Sets the old member declaration. Must always be called prior to
- * prepareDelegate().
- *
- * @param declaration the BodyDeclaration
- */
- public void setDeclaration(BodyDeclaration declaration) {
- fDeclaration= declaration;
- }
-
- /**
- * Set the name of the new element. This is optional, but if set it must be
- * called prior to prepareDelegate().
- *
- * @param newName the String with the new name
- */
- public void setNewElementName(String newName) {
- fNewElementName= newName;
- }
-
- /**
- * Set the location of the new element. This is optional, but if set it must
- * be called prior to prepareDelegate().
- *
- * @param binding the ITypeBinding of the old type
- */
- public void setNewLocation(ITypeBinding binding) {
- fDestinationTypeBinding= binding;
- }
-
- /**
- * Set whether the existing element should be copied and the copy made
- * delegate (true), or the original element should be changed to become the
- * delegate (false). This is optional, but if set it must be called prior to
- * prepareDelegate().
- *
- * The default is true (create a copy).
- *
- * @param isCopy true if a copy should be created
- */
- public void setCopy(boolean isCopy) {
- fCopy= isCopy;
- }
-
- /**
- * Sets whether a deprecation message including a link to the new element
- * should be added to the javadoc of the delegate. This is optional, but if
- * set it must be called prior to prepareDelegate().
- *
- * The default is true (create deprecation message).
- *
- * @param declareDeprecated true if the member should be deprecated
- */
- public void setDeclareDeprecated(boolean declareDeprecated) {
- fDeclareDeprecated= declareDeprecated;
- }
-
- /**
- * When in copy mode, use this method to control the insertion point of the
- * delegate. If the parameter is true, the delegate gets inserted before the
- * original declaration. If false, the delegate gets inserted after the
- * original declaration.
- *
- * The default is false (do not insert before).
- *
- * @param insertBefore insertion point
- */
- public void setInsertBefore(boolean insertBefore) {
- fInsertBefore= insertBefore;
- }
-
- // Methods to be overridden by subclasses
-
- /**
- * Initializes the creator. Must set the "new" name of the element if not
- * already set.
- *
- */
- protected abstract void initialize();
-
- /**
- *
- * Creates the body of the delegate.
- *
- * @param declaration the member declaration
- * @return the body of the delegate
- * @throws JavaScriptModelException
- */
- protected abstract ASTNode createBody(BodyDeclaration declaration) throws JavaScriptModelException;
-
- /**
- * Creates the javadoc reference to the old member to be put inside the
- * javadoc comment.
- *
- * This method is only called if isDeclareDeprecated() == true.
- *
- * @param declaration the member declaration
- * @return the javadoc link node
- * @throws JavaScriptModelException
- */
- protected abstract ASTNode createDocReference(BodyDeclaration declaration) throws JavaScriptModelException;
-
- /**
- * Returns the node of the declaration on which to add the body.
- *
- * @param declaration the member declaration
- * @return the body head
- */
- protected abstract ASTNode getBodyHead(BodyDeclaration declaration);
-
- /**
- * Returns the javadoc property descriptor. The javadoc will be added using
- * this descriptor.
- *
- * @return property descriptor
- */
- protected abstract ChildPropertyDescriptor getJavaDocProperty();
-
- /**
- * Returns the body property descriptor. The body of the delegate will be
- * added using this descriptor.
- *
- * @return property descriptor
- */
- protected abstract ChildPropertyDescriptor getBodyProperty();
-
-
- // Getters for subclasses
-
- protected boolean isMoveToAnotherFile() {
- return fIsMoveToAnotherFile;
- }
-
- protected AST getAst() {
- return fDelegateRewrite.getAST();
- }
-
- protected BodyDeclaration getDeclaration() {
- return fDeclaration;
- }
-
- protected String getNewElementName() {
- return fNewElementName;
- }
-
- /**
- * Prepares the delegate member. The delegate member will have the same
- * signature as the old member and contain a call to the new member and a
- * javadoc reference with a reference to the new member.
- *
- * All references to the new member will contain the new name of the member
- * and/or new declaring type, if any.
- *
- */
- public void prepareDelegate() throws JavaScriptModelException {
- Assert.isNotNull(fDelegateRewrite);
- Assert.isNotNull(fDeclaration);
-
- initialize();
-
- // Moving to a new type?
- if (fDestinationTypeBinding != null) {
- fDestinationType= fOriginalRewrite.getImportRewrite().addImport(fDestinationTypeBinding, getAst());
- fIsMoveToAnotherFile= true;
- } else
- fIsMoveToAnotherFile= false;
-
- fTrackedPosition= fDelegateRewrite.getASTRewrite().track(fDeclaration);
-
- ASTNode delegateBody= createBody(fDeclaration);
- if (delegateBody != null) {
- // is null for interface and abstract methods
- fDelegateRewrite.getASTRewrite().set(getBodyHead(fDeclaration), getBodyProperty(), delegateBody, null);
- }
-
- if (fDeclareDeprecated) {
- createJavadoc();
- }
- }
-
- /**
- * Creates the javadoc for the delegate.
- *
- * @throws JavaScriptModelException
- */
- private void createJavadoc() throws JavaScriptModelException {
- TagElement tag= getDelegateJavadocTag(fDeclaration);
-
- JSdoc comment= fDeclaration.getJavadoc();
- if (comment == null) {
- comment= getAst().newJSdoc();
- comment.tags().add(tag);
- fDelegateRewrite.getASTRewrite().set(fDeclaration, getJavaDocProperty(), comment, null);
- } else
- fDelegateRewrite.getASTRewrite().getListRewrite(comment, JSdoc.TAGS_PROPERTY).insertLast(tag, null);
- }
-
- /**
- * Performs the actual rewriting and adds an edit to the ASTRewrite set with
- * {@link #setSourceRewrite(CompilationUnitRewrite)}.
- *
- * @throws JavaScriptModelException
- */
- public void createEdit() throws JavaScriptModelException {
- try {
- IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents());
- TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaScriptProject().getOptions(true));
- edit.apply(document, TextEdit.UPDATE_REGIONS);
-
- String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()),
- fPreferences.tabWidth, fPreferences.indentWidth, false);
-
- ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());
-
- CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
- ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
- if (fCopy)
- if (fInsertBefore)
- bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
- else
- bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
- else
- bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- protected abstract String getTextEditGroupLabel();
-
- /**
- * Returns the binding of the declaration.
- *
- * @return the binding of the declaration
- */
- protected abstract IBinding getDeclarationBinding();
-
- /**
- * Returns a new rewrite with the delegate changes registered. This rewrite
- * can be used in-between calls to prepareDelegate() and createEdit() to add
- * additional changes to the delegate.
- *
- * @return CompilationUnitRewrite the new rewrite
- */
- public CompilationUnitRewrite getDelegateRewrite() {
- return fDelegateRewrite;
- }
-
- // ******************* INTERNAL HELPERS ***************************
-
- private TagElement getDelegateJavadocTag(BodyDeclaration declaration) throws JavaScriptModelException {
- Assert.isNotNull(declaration);
-
- String msg= RefactoringCoreMessages.DelegateCreator_use_member_instead;
- int firstParam= msg.indexOf("{0}"); //$NON-NLS-1$
- Assert.isTrue(firstParam != -1);
-
- List fragments= new ArrayList();
- TextElement text= getAst().newTextElement();
- text.setText(msg.substring(0, firstParam).trim());
- fragments.add(text);
-
- fragments.add(createJavadocMemberReferenceTag(declaration, getAst()));
-
- text= getAst().newTextElement();
- text.setText(msg.substring(firstParam + 3).trim());
- fragments.add(text);
-
- final TagElement tag= getAst().newTagElement();
- tag.setTagName(TagElement.TAG_DEPRECATED);
- tag.fragments().addAll(fragments);
- return tag;
- }
-
- private TagElement createJavadocMemberReferenceTag(BodyDeclaration declaration, final AST ast) throws JavaScriptModelException {
- Assert.isNotNull(ast);
- Assert.isNotNull(declaration);
- ASTNode javadocReference= createDocReference(declaration);
- final TagElement element= ast.newTagElement();
- element.setTagName(TagElement.TAG_LINK);
- element.fragments().add(javadocReference);
- return element;
- }
-
- protected Expression getAccess() {
- return isMoveToAnotherFile() ? createDestinationTypeName() : null;
- }
-
- protected Name createDestinationTypeName() {
- return ASTNodeFactory.newName(getAst(), ASTNodes.asString(fDestinationType));
- }
-
- private ChildListPropertyDescriptor getTypeBodyDeclarationsProperty() {
- ASTNode parent= fDeclaration.getParent();
-
- if (parent instanceof JavaScriptUnit)
- return JavaScriptUnit.STATEMENTS_PROPERTY;
- else if (parent instanceof AbstractTypeDeclaration)
- return ((AbstractTypeDeclaration) parent).getBodyDeclarationsProperty();
- else if (parent instanceof AnonymousClassDeclaration)
- return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
-
- Assert.isTrue(false);
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateFieldCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateFieldCreator.java
deleted file mode 100644
index d8f1f569..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateFieldCreator.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.delegates;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Delegate creator for static fields. Note that this implementation assumes a
- * field <strong>with only one fragment</strong>. See
- * {@link org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor#getASTMembers(org.eclipse.ltk.core.refactoring.RefactoringStatus)}
- * for more information.
- *
- *
- */
-public class DelegateFieldCreator extends DelegateCreator {
-
- private VariableDeclarationFragment fOldFieldFragment;
-
- protected void initialize() {
-
- Assert.isTrue(getDeclaration() instanceof FieldDeclaration);
- Assert.isTrue(((FieldDeclaration) getDeclaration()).fragments().size() == 1);
-
- fOldFieldFragment= (VariableDeclarationFragment) ((FieldDeclaration) getDeclaration()).fragments().get(0);
- if (getNewElementName() == null)
- setNewElementName(fOldFieldFragment.getName().getIdentifier());
-
- setInsertBefore(false); // delegate must be inserted after the original field that is referenced in the initializer
- }
-
- protected ASTNode createBody(BodyDeclaration fd) throws JavaScriptModelException {
- FieldDeclaration result= (FieldDeclaration) fd;
- Expression initializer= createDelegateFieldInitializer(result);
- return initializer;
- }
-
- protected ASTNode createDocReference(BodyDeclaration declaration) {
- MemberRef ref= getAst().newMemberRef();
- ref.setName(getAst().newSimpleName(getNewElementName()));
-
- if (isMoveToAnotherFile())
- ref.setQualifier(createDestinationTypeName());
- return ref;
- }
-
- protected ASTNode getBodyHead(BodyDeclaration result) {
- return fOldFieldFragment;
- }
-
- protected ChildPropertyDescriptor getJavaDocProperty() {
- return FieldDeclaration.JAVADOC_PROPERTY;
- }
-
- protected ChildPropertyDescriptor getBodyProperty() {
- return VariableDeclarationFragment.INITIALIZER_PROPERTY;
- }
-
- protected IBinding getDeclarationBinding() {
- return fOldFieldFragment.resolveBinding();
- }
-
- protected String getTextEditGroupLabel() {
- return RefactoringCoreMessages.DelegateFieldCreator_text_edit_group_label;
- }
-
- // ******************* INTERNAL HELPERS ***************************
-
- private Expression createDelegateFieldInitializer(final FieldDeclaration declaration) throws JavaScriptModelException {
- Assert.isNotNull(declaration);
-
- Expression qualification= getAccess();
- if (qualification != null) {
- FieldAccess access= getAst().newFieldAccess();
- access.setExpression(qualification);
- access.setName(getAst().newSimpleName(getNewElementName()));
- return access;
- } else {
- SimpleName access= getAst().newSimpleName(getNewElementName());
- return access;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateMethodCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateMethodCreator.java
deleted file mode 100644
index 7fd428bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/delegates/DelegateMethodCreator.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.delegates;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Delegate creator for static and non-static methods.
- *
- *
- */
-public class DelegateMethodCreator extends DelegateCreator {
-
- private ASTNode fDelegateInvocation;
- private FunctionRef fDocMethodReference;
-
- protected void initialize() {
-
- Assert.isTrue(getDeclaration() instanceof FunctionDeclaration);
-
- if (getNewElementName() == null)
- setNewElementName(((FunctionDeclaration) getDeclaration()).getName().getIdentifier());
-
- setInsertBefore(true);
- }
-
- protected ASTNode createBody(BodyDeclaration bd) throws JavaScriptModelException {
-
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) bd;
-
- // interface or abstract method ? => don't create a method body.
- if (methodDeclaration.getBody() == null)
- return null;
-
- return createDelegateMethodBody(methodDeclaration);
- }
-
- protected ASTNode createDocReference(final BodyDeclaration declaration) throws JavaScriptModelException {
- fDocMethodReference= getAst().newFunctionRef();
- fDocMethodReference.setName(getAst().newSimpleName(getNewElementName()));
- if (isMoveToAnotherFile())
- fDocMethodReference.setQualifier(createDestinationTypeName());
- createArguments((FunctionDeclaration) declaration, fDocMethodReference.parameters(), false);
- return fDocMethodReference;
- }
-
- protected ASTNode getBodyHead(BodyDeclaration result) {
- return result;
- }
-
- protected ChildPropertyDescriptor getJavaDocProperty() {
- return FunctionDeclaration.JAVADOC_PROPERTY;
- }
-
- protected ChildPropertyDescriptor getBodyProperty() {
- return FunctionDeclaration.BODY_PROPERTY;
- }
-
- /**
- * @return the delegate incovation, either a {@link ConstructorInvocation}
- * or a {@link FunctionInvocation}. May be null if the delegate
- * method is abstract (and therefore has no body at all)
- */
- public ASTNode getDelegateInvocation() {
- return fDelegateInvocation;
- }
-
- /**
- * @return the javadoc reference to the old method in the javadoc comment.
- * May be null if no comment was created.
- */
- public FunctionRef getJavadocReference() {
- return fDocMethodReference;
- }
-
- /**
- * Creates the corresponding statement for the method invocation, based on
- * the return type.
- *
- * @param declaration the method declaration where the invocation statement
- * is inserted
- * @param invocation the method invocation being encapsulated by the
- * resulting statement
- * @return the corresponding statement
- */
- protected Statement createMethodInvocation(final FunctionDeclaration declaration, final FunctionInvocation invocation) {
- Assert.isNotNull(declaration);
- Assert.isNotNull(invocation);
- Statement statement= null;
- final Type type= declaration.getReturnType2();
- if (type == null)
- statement= createExpressionStatement(invocation);
- else {
- if (type instanceof PrimitiveType) {
- final PrimitiveType primitive= (PrimitiveType) type;
- if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID))
- statement= createExpressionStatement(invocation);
- else
- statement= createReturnStatement(invocation);
- } else
- statement= createReturnStatement(invocation);
- }
- return statement;
- }
-
- /**
- * {@inheritDoc}
- */
- protected IBinding getDeclarationBinding() {
- final FunctionDeclaration declaration= (FunctionDeclaration) getDeclaration();
- return declaration.resolveBinding();
- }
-
- private void createArguments(final FunctionDeclaration declaration, final List arguments, boolean methodInvocation) throws JavaScriptModelException {
- Assert.isNotNull(declaration);
- Assert.isNotNull(arguments);
- SingleVariableDeclaration variable= null;
- final int size= declaration.parameters().size();
- for (int index= 0; index < size; index++) {
- variable= (SingleVariableDeclaration) declaration.parameters().get(index);
-
- if (methodInvocation) {
- // we are creating method invocation parameters
- final SimpleName expression= getAst().newSimpleName(variable.getName().getIdentifier());
- arguments.add(expression);
- } else {
- // we are creating type info for the javadoc
- final FunctionRefParameter parameter= getAst().newFunctionRefParameter();
- parameter.setType(ASTNodeFactory.newType(getAst(), variable));
- if ((index == size - 1) && declaration.isVarargs())
- parameter.setVarargs(true);
- arguments.add(parameter);
- }
- }
- }
-
- private Block createDelegateMethodBody(final FunctionDeclaration declaration) throws JavaScriptModelException {
- Assert.isNotNull(declaration);
-
- FunctionDeclaration old= (FunctionDeclaration) getDeclaration();
- List arguments;
- Statement call;
- if (old.isConstructor()) {
- ConstructorInvocation invocation= getAst().newConstructorInvocation();
- arguments= invocation.arguments();
- call= invocation;
- fDelegateInvocation= invocation;
- } else {
- FunctionInvocation invocation= getAst().newFunctionInvocation();
- invocation.setName(getAst().newSimpleName(getNewElementName()));
- invocation.setExpression(getAccess());
- arguments= invocation.arguments();
- call= createMethodInvocation(declaration, invocation);
- fDelegateInvocation= invocation;
- }
- createArguments(declaration, arguments, true);
-
- final Block body= getAst().newBlock();
- body.statements().add(call);
-
- return body;
- }
-
- /**
- * Creates a new expression statement for the method invocation.
- *
- * @param invocation the method invocation
- * @return the corresponding statement
- */
- private ExpressionStatement createExpressionStatement(final FunctionInvocation invocation) {
- Assert.isNotNull(invocation);
- return invocation.getAST().newExpressionStatement(invocation);
- }
-
- /**
- * Creates a new return statement for the method invocation.
- *
- * @param invocation the method invocation to create a return statement for
- * @return the corresponding statement
- */
- private ReturnStatement createReturnStatement(final FunctionInvocation invocation) {
- Assert.isNotNull(invocation);
- final ReturnStatement statement= invocation.getAST().newReturnStatement();
- statement.setExpression(invocation);
- return statement;
- }
-
- protected String getTextEditGroupLabel() {
- return RefactoringCoreMessages.DelegateMethodCreator_text_edit_group_field;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassCreator.java
deleted file mode 100644
index d5fde788..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassCreator.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-import com.ibm.icu.text.Collator;
-
-public class AccessorClassCreator {
-
- private final IJavaScriptUnit fCu;
- private final String fAccessorClassName;
- private final IPath fAccessorPath;
- private final IPath fResourceBundlePath;
- private final IPackageFragment fAccessorPackage;
- private final boolean fIsEclipseNLS;
- private final NLSSubstitution[] fNLSSubstitutions;
- private final String fSubstitutionPattern;
-
- private AccessorClassCreator(IJavaScriptUnit cu, String accessorClassname, IPath accessorPath, IPackageFragment accessorPackage, IPath resourceBundlePath, boolean isEclipseNLS, NLSSubstitution[] nlsSubstitutions, String substitutionPattern) {
- fCu= cu;
- fAccessorClassName= accessorClassname;
- fAccessorPath= accessorPath;
- fAccessorPackage= accessorPackage;
- fResourceBundlePath= resourceBundlePath;
- fIsEclipseNLS= isEclipseNLS;
- fNLSSubstitutions= nlsSubstitutions;
- fSubstitutionPattern= substitutionPattern;
- }
-
- public static Change create(IJavaScriptUnit cu, String accessorClassname, IPath accessorPath, IPackageFragment accessorPackage, IPath resourceBundlePath, boolean isEclipseNLS, NLSSubstitution[] nlsSubstitutions, String substitutionPattern, IProgressMonitor pm) throws CoreException {
- AccessorClassCreator accessorClass= new AccessorClassCreator(cu, accessorClassname, accessorPath, accessorPackage, resourceBundlePath, isEclipseNLS, nlsSubstitutions, substitutionPattern);
-
- return new CreateTextFileChange(accessorPath, accessorClass.createAccessorCUSource(pm), null, "java"); //$NON-NLS-1$
- }
-
- private String createAccessorCUSource(IProgressMonitor pm) throws CoreException {
- IProject project= getFileHandle(fAccessorPath).getProject();
- String lineDelimiter= StubUtility.getLineDelimiterPreference(project);
- return CodeFormatterUtil.format(CodeFormatter.K_JAVASCRIPT_UNIT, getUnformattedSource(pm), 0, null, lineDelimiter, fCu.getJavaScriptProject());
- }
-
- private static IFile getFileHandle(IPath filePath) {
- if (filePath == null)
- return null;
- return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
- }
-
- private String getUnformattedSource(IProgressMonitor pm) throws CoreException {
- IJavaScriptUnit newCu= null;
- try {
- newCu= fAccessorPackage.getJavaScriptUnit(fAccessorPath.lastSegment()).getWorkingCopy(null);
-
- String typeComment= null, fileComment= null;
- final IJavaScriptProject project= newCu.getJavaScriptProject();
- final String lineDelim= StubUtility.getLineDelimiterUsed(project);
- if (StubUtility.doAddComments(project)) {
- typeComment= CodeGeneration.getTypeComment(newCu, fAccessorClassName, lineDelim);
- fileComment= CodeGeneration.getFileComment(newCu, lineDelim);
- }
- String classContent= createClass(lineDelim);
- String cuContent= CodeGeneration.getCompilationUnitContent(newCu, fileComment, typeComment, classContent, lineDelim);
- if (cuContent == null) {
- StringBuffer buf= new StringBuffer();
- if (fileComment != null) {
- buf.append(fileComment).append(lineDelim);
- }
- if (!fAccessorPackage.isDefaultPackage()) {
- buf.append("package ").append(fAccessorPackage.getElementName()).append(';'); //$NON-NLS-1$
- }
- buf.append(lineDelim).append(lineDelim);
- if (typeComment != null) {
- buf.append(typeComment).append(lineDelim);
- }
- buf.append(classContent);
- cuContent= buf.toString();
- }
-
- newCu.getBuffer().setContents(cuContent);
- addImportsToAccessorCu(newCu, pm);
- return newCu.getSource();
- } finally {
- if (newCu != null) {
- newCu.discardWorkingCopy();
- }
- }
- }
-
- private void addImportsToAccessorCu(IJavaScriptUnit newCu, IProgressMonitor pm) throws CoreException {
- ImportRewrite is= StubUtility.createImportRewrite(newCu, true);
- if (fIsEclipseNLS) {
- is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$
- } else {
- is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$
- is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$
- }
- TextEdit edit= is.rewriteImports(pm);
- JavaModelUtil.applyEdit(newCu, edit, false, null);
- }
-
- private String createClass(String lineDelim) throws CoreException {
- if (fIsEclipseNLS) {
- MembersOrderPreferenceCache sortOrder= JavaScriptPlugin.getDefault().getMemberOrderPreferenceCache();
- int constructorIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
- int fieldIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX);
- int initIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX);
-
- String constructor= createConstructor(lineDelim) + lineDelim;
- String initializer= createStaticInitializer(lineDelim) + lineDelim;
- String fields= createStaticFields(lineDelim) + lineDelim;
-
- StringBuffer result= new StringBuffer();
- result.append("public class ").append(fAccessorClassName).append(" extends NLS {"); //$NON-NLS-1$ //$NON-NLS-2$
- result.append("private static final String ").append(NLSRefactoring.BUNDLE_NAME).append(" = \"").append(getResourceBundleName()).append("\"; "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- result.append(NLSElement.createTagText(1)).append(lineDelim);
-
- if (constructorIdx < fieldIdx) {
- if (fieldIdx < initIdx) {
- result.append(constructor);
- result.append(fields);
- result.append(initializer);
- } else {
- result.append(constructor);
- result.append(initializer);
- result.append(fields);
- }
- } else {
- if (constructorIdx < initIdx) {
- result.append(fields);
- result.append(constructor);
- result.append(initializer);
- } else {
- result.append(fields);
- result.append(initializer);
- result.append(constructor);
- }
- }
-
- result.append('}').append(lineDelim);
-
- return result.toString();
- } else {
- MembersOrderPreferenceCache sortOrder= JavaScriptPlugin.getDefault().getMemberOrderPreferenceCache();
- int constructorIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
- int methodIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX);
-
- String constructor= lineDelim + createConstructor(lineDelim);
- String method= lineDelim + createGetStringMethod(lineDelim);
-
- StringBuffer result= new StringBuffer();
- result.append("public class ").append(fAccessorClassName).append(" {"); //$NON-NLS-1$ //$NON-NLS-2$
- result.append("private static final String ").append(NLSRefactoring.BUNDLE_NAME); //$NON-NLS-1$
- result.append(" = \"").append(getResourceBundleName()).append("\"; ").append(NLSElement.createTagText(1)).append(lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
-
- result.append(lineDelim).append("private static final ResourceBundle ").append(getResourceBundleConstantName()); //$NON-NLS-1$
- result.append("= ResourceBundle.getBundle(").append(NLSRefactoring.BUNDLE_NAME).append(");").append(lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
-
- if (constructorIdx < methodIdx) {
- result.append(constructor);
- result.append(method);
- } else {
- result.append(constructor);
- result.append(method);
- }
-
- result.append(lineDelim).append('}').append(lineDelim);
-
- return result.toString();
- }
- }
-
- private String getResourceBundleConstantName() {
- return "RESOURCE_BUNDLE";//$NON-NLS-1$
- }
-
- private String createStaticFields(String lineDelim) {
- HashSet added= new HashSet();
- List subs= new ArrayList();
- for (int i= 0; i < fNLSSubstitutions.length; i++) {
- NLSSubstitution substitution= fNLSSubstitutions[i];
- int newState= substitution.getState();
- if ((substitution.hasStateChanged() || substitution.isAccessorRename())&& newState == NLSSubstitution.EXTERNALIZED) {
- if (added.add(substitution.getKey()))
- subs.add(substitution);
- }
- }
- Collections.sort(subs, new Comparator() {
- private Collator fCollator= Collator.getInstance();
- public int compare(Object o1, Object o2) {
- NLSSubstitution s0= (NLSSubstitution)o1;
- NLSSubstitution s1= (NLSSubstitution)o2;
- return fCollator.compare(s0.getKey(), s1.getKey());
- }
- });
- StringBuffer buf= new StringBuffer();
- for (Iterator iter= subs.iterator(); iter.hasNext();) {
- NLSSubstitution element= (NLSSubstitution)iter.next();
- appendStaticField(buf, element);
- }
- return buf.toString();
- }
-
- private void appendStaticField(StringBuffer buf, NLSSubstitution substitution) {
- buf.append("public static String "); //$NON-NLS-1$
- buf.append(substitution.getKey());
- buf.append(';');
- }
-
- private String createGetStringMethod(String lineDelim) throws CoreException {
- StringBuffer result= new StringBuffer();
-
- result.append("public static String "); //$NON-NLS-1$
- int i= fSubstitutionPattern.indexOf(NLSRefactoring.KEY);
- if (i != -1) {
- result.append(fSubstitutionPattern.substring(0, i));
- result.append("String key"); //$NON-NLS-1$
- result.append(fSubstitutionPattern.substring(i + NLSRefactoring.KEY.length()));
- } else {
- //fallback
- result.append("getString(String key)"); //$NON-NLS-1$
- }
- result.append('{').append(lineDelim);
-
- result.append("try {").append(lineDelim) //$NON-NLS-1$
- .append("return ") //$NON-NLS-1$
- .append(getResourceBundleConstantName()).append(".getString(key);").append(lineDelim) //$NON-NLS-1$
- .append("} catch (MissingResourceException e) {").append(lineDelim) //$NON-NLS-1$
- .append("return '!' + key + '!';").append(lineDelim) //$NON-NLS-1$
- .append("}"); //$NON-NLS-1$
-
- result.append(lineDelim).append('}');
- return result.toString();
- }
-
- private String createStaticInitializer(String lineDelim) throws CoreException {
- return "static {" //$NON-NLS-1$
- + lineDelim
- + "// initialize resource bundle" //$NON-NLS-1$
- + lineDelim
- + "NLS.initializeMessages(BUNDLE_NAME, " + fAccessorClassName + ".class);" //$NON-NLS-1$ //$NON-NLS-2$
- + lineDelim
- + "}"; //$NON-NLS-1$
- }
-
- private String createConstructor(String lineDelim) {
- return "private " + fAccessorClassName + "(){" + //$NON-NLS-2$//$NON-NLS-1$
- lineDelim + '}';
- }
-
- /* Currently not used.
- private String createGetStringMethodComment() throws CoreException {
- if (fCodeGenerationSettings.createComments) {
- String comment= CodeGeneration.getMethodComment(fCu, fAccessorClassName, "getString", //$NON-NLS-1$
- new String[]{"key"}, //$NON-NLS-1$
- new String[0], "QString;", //$NON-NLS-1$
- null, lineDelim);
- if (comment == null) {
- return "";//$NON-NLS-1$
- }
-
- return comment + lineDelim;
- } else {
- return "";//$NON-NLS-1$
- }
- }
- */
-
- private String getPropertyFileName() {
- return fResourceBundlePath.lastSegment();
- }
-
- private String getPropertyFileNameWithoutExtension() {
- String fileName= getPropertyFileName();
- return fileName.substring(0, fileName.indexOf(NLSRefactoring.PROPERTY_FILE_EXT));
- }
-
- private String getResourceBundleName() throws CoreException {
- IResource res= ResourcesPlugin.getWorkspace().getRoot().findMember(fResourceBundlePath.removeLastSegments(1));
- if (res != null && res.exists()) {
- IJavaScriptElement el= JavaScriptCore.create(res);
- if (el instanceof IPackageFragment) {
- IPackageFragment p= (IPackageFragment) el;
- return p.getElementName() + '.' + getPropertyFileNameWithoutExtension();
- } else
- if ((el instanceof IPackageFragmentRoot) || (el instanceof IJavaScriptProject)) {
- return getPropertyFileNameWithoutExtension();
- }
- }
- throw new CoreException(new StatusInfo(IStatus.ERROR, "Resourcebundle not specified")); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassModifier.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassModifier.java
deleted file mode 100644
index 5f2028c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassModifier.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-import com.ibm.icu.text.Collator;
-
-public class AccessorClassModifier {
-
- private JavaScriptUnit fRoot;
- private AST fAst;
- private ASTRewrite fASTRewrite;
- private ListRewrite fListRewrite;
- private IJavaScriptUnit fCU;
- private List fFields;
-
- private AccessorClassModifier(IJavaScriptUnit cu) throws CoreException {
-
- fCU= cu;
-
- fRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(cu, ASTProvider.WAIT_YES, null);
- fAst= fRoot.getAST();
- fASTRewrite= ASTRewrite.create(fAst);
-
- AbstractTypeDeclaration parent= null;
- if (fRoot.types().size() > 0) {
- parent= (AbstractTypeDeclaration)fRoot.types().get(0);
- fFields= new ArrayList();
- parent.accept(new GenericVisitor() {
- /**
- * {@inheritDoc}
- */
- public boolean visit(FieldDeclaration node) {
- int modifiers= node.getModifiers();
- if (!Modifier.isPublic(modifiers))
- return false;
-
- if (!Modifier.isStatic(modifiers))
- return false;
-
- List fragments= node.fragments();
- if (fragments.size() != 1)
- return false;
-
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)fragments.get(0);
- if (fragment.getInitializer() != null)
- return false;
-
- fFields.add(node);
- return false;
- }
- });
- fListRewrite= fASTRewrite.getListRewrite(parent, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
- } else {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.INTERNAL_ERROR, NLSMessages.AccessorClassModifier_missingType, null);
- throw new CoreException(status);
- }
- }
-
- private TextEdit getTextEdit() throws CoreException {
- IDocument document= null;
-
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- IPath path= fCU.getPath();
-
- if (manager != null && path != null) {
- manager.connect(path, LocationKind.NORMALIZE, null);
- try {
- ITextFileBuffer buffer= manager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- if (buffer != null)
- document= buffer.getDocument();
- } finally {
- manager.disconnect(path, LocationKind.NORMALIZE, null);
- }
- }
-
- if (document == null)
- document= new Document(fCU.getSource());
-
- return fASTRewrite.rewriteAST(document, fCU.getJavaScriptProject().getOptions(true));
- }
-
- public static Change create(IJavaScriptUnit cu, NLSSubstitution[] substitutions) throws CoreException {
-
- Map newKeyToSubstMap= NLSPropertyFileModifier.getNewKeyToSubstitutionMap(substitutions);
- Map oldKeyToSubstMap= NLSPropertyFileModifier.getOldKeyToSubstitutionMap(substitutions);
-
- AccessorClassModifier sourceModification= new AccessorClassModifier(cu);
-
- String message= Messages.format(NLSMessages.NLSSourceModifier_change_description, cu.getElementName());
-
- TextChange change= new CompilationUnitChange(message, cu);
- MultiTextEdit multiTextEdit= new MultiTextEdit();
- change.setEdit(multiTextEdit);
-
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (NLSPropertyFileModifier.doRemove(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- sourceModification.removeKey(substitution, change);
- }
- }
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (substitution.isKeyRename() && NLSPropertyFileModifier.doReplace(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- sourceModification.renameKey(substitution, change);
- }
- }
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (NLSPropertyFileModifier.doInsert(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- sourceModification.addKey(substitution, change);
- }
- }
-
- if (change.getChangeGroups().length == 0)
- return null;
-
- change.addEdit(sourceModification.getTextEdit());
-
- return change;
- }
-
- private void removeKey(NLSSubstitution sub, TextChange change) throws CoreException {
- ASTNode node= findField(fRoot, sub.getKey());
- if (node == null)
- return;
-
- String name= Messages.format(NLSMessages.AccessorClassModifier_remove_entry, sub.getKey());
- TextEditGroup editGroup= new TextEditGroup(name);
- fListRewrite.remove(node, editGroup);
- change.addTextEditGroup(editGroup);
- fFields.remove(node);
- }
-
- private void renameKey(NLSSubstitution sub, TextChange change) throws CoreException {
- ASTNode node= findField(fRoot, sub.getInitialKey());
- if (node == null)
- return;
-
- String name= Messages.format(NLSMessages.AccessorClassModifier_replace_entry, sub.getKey());
- TextEditGroup editGroup= new TextEditGroup(name);
- fListRewrite.remove(node, editGroup);
- fFields.remove(node);
-
- addKey(sub, change, editGroup);
-
- change.addTextEditGroup(editGroup);
- }
-
- private ASTNode findField(ASTNode astRoot, final String name) {
-
- class STOP_VISITING extends RuntimeException {
- private static final long serialVersionUID= 1L;
- }
-
- final ASTNode[] result= new ASTNode[1];
-
- try {
- astRoot.accept(new ASTVisitor() {
-
- public boolean visit(VariableDeclarationFragment node) {
- if (name.equals(node.getName().getFullyQualifiedName())) {
- result[0]= node.getParent();
- throw new STOP_VISITING();
- }
- return true;
- }
- });
- } catch (STOP_VISITING ex) {
- // stop visiting AST
- }
-
- return result[0];
- }
-
- private void addKey(NLSSubstitution sub, TextChange change) throws CoreException {
- String name= Messages.format(NLSMessages.AccessorClassModifier_add_entry, sub.getKey());
- TextEditGroup editGroup= new TextEditGroup(name);
- change.addTextEditGroup(editGroup);
- addKey(sub, change, editGroup);
- }
-
- private void addKey(NLSSubstitution sub, TextChange change, TextEditGroup editGroup) throws CoreException {
-
- if (fListRewrite == null)
- return;
-
- String key= sub.getKey();
- FieldDeclaration fieldDeclaration= getNewFinalStringFieldDeclaration(key);
-
- Iterator iter= fFields.iterator();
- int insertionPosition= 0;
- if (iter.hasNext()) {
- Collator collator= Collator.getInstance();
- FieldDeclaration existingFieldDecl= (FieldDeclaration)iter.next();
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)existingFieldDecl.fragments().get(0);
- String identifier= fragment.getName().getIdentifier();
- if (collator.compare(key, identifier) != 1) {
- insertionPosition= 0;
- fListRewrite.insertBefore(fieldDeclaration, existingFieldDecl, editGroup);
- } else {
- insertionPosition++;
- while (iter.hasNext()) {
- FieldDeclaration next= (FieldDeclaration)iter.next();
- fragment= (VariableDeclarationFragment)next.fragments().get(0);
- identifier= fragment.getName().getIdentifier();
- if (collator.compare(key, identifier) == -1) {
- break;
- }
- insertionPosition++;
- existingFieldDecl= next;
- }
- fListRewrite.insertAfter(fieldDeclaration, existingFieldDecl, editGroup);
- }
- } else {
- insertionPosition= 0;
- fListRewrite.insertLast(fieldDeclaration, editGroup);
- }
- fFields.add(insertionPosition, fieldDeclaration);
- }
-
- private FieldDeclaration getNewFinalStringFieldDeclaration(String name) {
- VariableDeclarationFragment variableDeclarationFragment= fAst.newVariableDeclarationFragment();
- variableDeclarationFragment.setName(fAst.newSimpleName(name));
-
- FieldDeclaration fieldDeclaration= fAst.newFieldDeclaration(variableDeclarationFragment);
- fieldDeclaration.setType(fAst.newSimpleType(fAst.newSimpleName("String"))); //$NON-NLS-1$
- fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
- fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
-
- return fieldDeclaration;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassReference.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassReference.java
deleted file mode 100644
index 45051cde..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/AccessorClassReference.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public class AccessorClassReference {
-
- private ITypeBinding fBinding;
- private Region fRegion;
- private String fResourceBundleName;
-
- public AccessorClassReference(ITypeBinding typeBinding, String resourceBundleName, Region accessorRegion) {
- super();
- fBinding= typeBinding;
- fRegion= accessorRegion;
- fResourceBundleName= resourceBundleName;
- }
-
- public ITypeBinding getBinding() {
- return fBinding;
- }
-
- public String getName() {
- return fBinding.getName();
- }
-
- public Region getRegion() {
- return fRegion;
- }
-
- public String getResourceBundleName() {
- return fResourceBundleName;
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof AccessorClassReference) {
- AccessorClassReference cmp = (AccessorClassReference) obj;
- return fBinding == cmp.fBinding;
- }
- return false;
- }
-
- public int hashCode() {
- return fBinding.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/KeyValuePair.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/KeyValuePair.java
deleted file mode 100644
index d9fdbaee..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/KeyValuePair.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-public class KeyValuePair {
-
- public String fKey;
- public String fValue;
-
- public KeyValuePair(String key, String value) {
- fKey= key;
- fValue= value;
- }
-
- public String getKey() {
- return fKey;
- }
-
- public void setKey(String key) {
- fKey= key;
- }
-
- public String getValue() {
- return fValue;
- }
-
- public void setValue(String value) {
- fValue= value;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java
deleted file mode 100644
index 7f982d8b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.Region;
-
-public class NLSElement {
-
- public static final String TAG_PREFIX= "//$NON-NLS-"; //$NON-NLS-1$
- public static final int TAG_PREFIX_LENGTH= TAG_PREFIX.length();
- public static final String TAG_POSTFIX= "$"; //$NON-NLS-1$
- public static final int TAG_POSTFIX_LENGTH= TAG_POSTFIX.length();
-
- /** The original string denoted by the position */
- private String fValue;
- /** The position of the original string */
- private Region fPosition;
-
- /** Position of the // $NON_NLS_*$ tag */
- private Region fTagPosition;
-
- /** Index of the Element in an NLSLine */
- private int fIndex;
- private boolean fIsEclipseNLS;
- private AccessorClassReference fAccessorClassReference;
-
- /**
- * Creates a new NLS element for the given string and position.
- */
- public NLSElement(String value, int start, int length, int index, boolean isEclipseNLS) {
- fValue= value;
- fIndex= index;
- Assert.isNotNull(fValue);
- fPosition= new Region(start, length);
- fIsEclipseNLS= isEclipseNLS;
- }
-
- /**
- * Returns the position of the string to be NLSed.
- * @return Returns the position of the string to be NLSed
- */
- public Region getPosition() {
- return fPosition;
- }
-
- /**
- * Returns the actual string value.
- * @return the actual string value
- */
- public String getValue() {
- return fValue;
- }
-
- /**
- * Sets the actual string value.
- */
- public void setValue(String value) {
- fValue= value;
- }
-
- /**
- * Sets the tag position if one is associated with the NLS element.
- */
- public void setTagPosition(int start, int length) {
- fTagPosition= new Region(start, length);
- }
-
- /**
- * Returns the tag position for this element. The method can return <code>null</code>.
- * In this case no tag has been found for this NLS element.
- */
- public Region getTagPosition() {
- return fTagPosition;
- }
-
- /**
- * Returns <code>true</code> if the NLS element has an asscociated $NON-NLS-*$ tag.
- * Otherwise <code>false</code> is returned.
- */
- public boolean hasTag() {
- return fTagPosition != null && fTagPosition.getLength() > 0;
- }
-
- public static String createTagText(int index) {
- return TAG_PREFIX + index + TAG_POSTFIX;
- }
-
- public String getTagText() {
- return TAG_PREFIX + (fIndex + 1) + TAG_POSTFIX;
- }
-
- /* (Non-Javadoc)
- * Method declared in Object.
- * only for debugging
- */
- public String toString() {
- return fPosition + ": " + fValue + " Tag position: " + //$NON-NLS-2$ //$NON-NLS-1$
- (hasTag() ? fTagPosition.toString() : "no tag found"); //$NON-NLS-1$
- }
-
- //--------------- Eclipse NLS mechanism support ---------------
-
- /**
- * Returns whether the standard resource bundle mechanism or
- * the Eclipse NLSing mechanism is used.
- *
- * @return <code>true</code> if the standard resource bundle mechanism
- * is used and <code>false</code> NLSing is done the Eclipse way
- *
- */
- public boolean isEclipseNLS() {
- return fIsEclipseNLS;
- }
-
- /**
- * Sets the accessor class reference for this element.
- * <p>
- * Note: this call is only valid when the element is
- * using the Eclipse NLS mechanism.
- * </p>
- *
- * @param accessorClassRef the accessor class reference
- *
- */
- public void setAccessorClassReference(AccessorClassReference accessorClassRef) {
- Assert.isTrue(fIsEclipseNLS);
- fAccessorClassReference= accessorClassRef;
- }
-
- /**
- * Returns the accessor class reference for this element.
- * <p>
- * Note: this call is only valid when the element is
- * using the Eclipse NLS mechanism.
- * </p>
- *
- * @return the accessor class reference
- *
- */
- public AccessorClassReference getAccessorClassReference() {
- Assert.isTrue(fIsEclipseNLS);
- return fAccessorClassReference;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHint.java
deleted file mode 100644
index 58e8d1e3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHint.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Region;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-/**
- * calculates hints for the nls-refactoring out of a compilation unit.
- * - package fragments of the accessor class and the resource bundle
- * - accessor class name, resource bundle name
- */
-public class NLSHint {
-
- private String fAccessorName;
- private IPackageFragment fAccessorPackage;
- private String fResourceBundleName;
- private IPackageFragment fResourceBundlePackage;
- private NLSSubstitution[] fSubstitutions;
-
- public NLSHint(IJavaScriptUnit cu, JavaScriptUnit astRoot) {
- Assert.isNotNull(cu);
- Assert.isNotNull(astRoot);
-
- IPackageFragment cuPackage= (IPackageFragment) cu.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
-
- fAccessorName= NLSRefactoring.DEFAULT_ACCESSOR_CLASSNAME;
- fAccessorPackage= cuPackage;
- fResourceBundleName= NLSRefactoring.DEFAULT_PROPERTY_FILENAME + NLSRefactoring.PROPERTY_FILE_EXT;
- fResourceBundlePackage= cuPackage;
-
- IJavaScriptProject project= cu.getJavaScriptProject();
- NLSLine[] lines= createRawLines(cu);
-
- AccessorClassReference accessClassRef= findFirstAccessorReference(lines, astRoot);
-
- if (accessClassRef == null) {
- // Look for Eclipse NLS approach
- List eclipseNLSLines= new ArrayList();
- accessClassRef= createEclipseNLSLines(getDocument(cu), astRoot, eclipseNLSLines);
- if (!eclipseNLSLines.isEmpty()) {
- NLSLine[] rawLines= lines;
- int rawLinesLength= rawLines.length;
- int eclipseLinesLength= eclipseNLSLines.size();
- lines= new NLSLine[rawLinesLength + eclipseLinesLength];
- for (int i= 0; i < rawLinesLength; i++)
- lines[i]= rawLines[i];
- for (int i= 0; i < eclipseLinesLength; i++)
- lines[i+rawLinesLength]= (NLSLine)eclipseNLSLines.get(i);
- }
- }
-
- Properties props= null;
- if (accessClassRef != null)
- props= NLSHintHelper.getProperties(project, accessClassRef);
-
- if (props == null)
- props= new Properties();
-
- fSubstitutions= createSubstitutions(lines, props, astRoot);
-
- if (accessClassRef != null) {
- fAccessorName= accessClassRef.getName();
- ITypeBinding accessorClassBinding= accessClassRef.getBinding();
-
- try {
- IPackageFragment accessorPack= NLSHintHelper.getPackageOfAccessorClass(project, accessorClassBinding);
- if (accessorPack != null) {
- fAccessorPackage= accessorPack;
- }
-
- String fullBundleName= accessClassRef.getResourceBundleName();
- if (fullBundleName != null) {
- fResourceBundleName= Signature.getSimpleName(fullBundleName) + NLSRefactoring.PROPERTY_FILE_EXT;
- String packName= Signature.getQualifier(fullBundleName);
-
- IPackageFragment pack= NLSHintHelper.getResourceBundlePackage(project, packName, fResourceBundleName);
- if (pack != null) {
- fResourceBundlePackage= pack;
- }
- }
- } catch (JavaScriptModelException e) {
- }
- }
- }
-
- private AccessorClassReference createEclipseNLSLines(final IDocument document, JavaScriptUnit astRoot, List nlsLines) {
-
- final AccessorClassReference[] firstAccessor= new AccessorClassReference[1];
- final SortedMap lineToNLSLine= new TreeMap();
-
- astRoot.accept(new ASTVisitor() {
-
- private IJavaScriptUnit fCache_CU;
- private JavaScriptUnit fCache_AST;
-
- public boolean visit(QualifiedName node) {
- ITypeBinding type= node.getQualifier().resolveTypeBinding();
- if (type != null) {
- ITypeBinding superType= type.getSuperclass();
- if (superType != null && NLS.class.getName().equals(superType.getQualifiedName())) {
- Integer line;
- try {
- line = new Integer(document.getLineOfOffset(node.getStartPosition()));
- } catch (BadLocationException e) {
- return true; // ignore and continue
- }
- NLSLine nlsLine= (NLSLine)lineToNLSLine.get(line);
- if (nlsLine == null) {
- nlsLine= new NLSLine(line.intValue());
- lineToNLSLine.put(line, nlsLine);
- }
- SimpleName name= node.getName();
- NLSElement element= new NLSElement(node.getName().getIdentifier(), name.getStartPosition(),
- name.getLength(), nlsLine.size() - 1, true);
- nlsLine.add(element);
- String bundleName;
- try {
- IJavaScriptUnit bundleCU= (IJavaScriptUnit)type.getJavaElement().getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (fCache_CU == null || !fCache_CU.equals(bundleCU) || fCache_AST == null) {
- fCache_CU= bundleCU;
- if (fCache_CU != null)
- fCache_AST= JavaScriptPlugin.getDefault().getASTProvider().getAST(fCache_CU, ASTProvider.WAIT_YES, null);
- else
- fCache_AST= null;
- }
- bundleName = NLSHintHelper.getResourceBundleName(fCache_AST);
- } catch (JavaScriptModelException e) {
- return true; // ignore this accessor and continue
- }
- element.setAccessorClassReference(new AccessorClassReference(type, bundleName, new Region(node.getStartPosition(), node.getLength())));
-
- if (firstAccessor[0] == null)
- firstAccessor[0]= element.getAccessorClassReference();
-
- }
- }
- return true;
- }
- });
-
- nlsLines.addAll(lineToNLSLine.values());
- return firstAccessor[0];
- }
-
- private IDocument getDocument(IJavaScriptUnit cu) {
- IPath path= cu.getPath();
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- manager.connect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- return null;
- }
-
- try {
- ITextFileBuffer buffer= manager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- if (buffer != null)
- return buffer.getDocument();
- } finally {
- try {
- manager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- return null;
- }
- }
- return null;
- }
-
- private NLSSubstitution[] createSubstitutions(NLSLine[] lines, Properties props, JavaScriptUnit astRoot) {
- List result= new ArrayList();
-
- for (int i= 0; i < lines.length; i++) {
- NLSElement[] elements= lines[i].getElements();
- for (int j= 0; j < elements.length; j++) {
- NLSElement nlsElement= elements[j];
- if (nlsElement.hasTag()) {
- AccessorClassReference accessorClassReference= NLSHintHelper.getAccessorClassReference(astRoot, nlsElement);
- if (accessorClassReference == null) {
- // no accessor class => not translated
- result.add(new NLSSubstitution(NLSSubstitution.IGNORED, stripQuotes(nlsElement.getValue()), nlsElement));
- } else {
- String key= stripQuotes(nlsElement.getValue());
- String value= props.getProperty(key);
- result.add(new NLSSubstitution(NLSSubstitution.EXTERNALIZED, key, value, nlsElement, accessorClassReference));
- }
- } else if (nlsElement.isEclipseNLS()) {
- String key= nlsElement.getValue();
- result.add(new NLSSubstitution(NLSSubstitution.EXTERNALIZED, key, props.getProperty(key), nlsElement, nlsElement.getAccessorClassReference()));
- } else {
- result.add(new NLSSubstitution(NLSSubstitution.INTERNALIZED, stripQuotes(nlsElement.getValue()), nlsElement));
- }
- }
- }
- return (NLSSubstitution[]) result.toArray(new NLSSubstitution[result.size()]);
- }
-
- private static AccessorClassReference findFirstAccessorReference(NLSLine[] lines, JavaScriptUnit astRoot) {
- for (int i= 0; i < lines.length; i++) {
- NLSElement[] elements= lines[i].getElements();
- for (int j= 0; j < elements.length; j++) {
- NLSElement nlsElement= elements[j];
- if (nlsElement.hasTag()) {
- AccessorClassReference accessorClassReference= NLSHintHelper.getAccessorClassReference(astRoot, nlsElement);
- if (accessorClassReference != null) {
- return accessorClassReference;
- }
- }
- }
- }
-
- // try to find a access with missing //non-nls tag (bug 75155)
- for (int i= 0; i < lines.length; i++) {
- NLSElement[] elements= lines[i].getElements();
- for (int j= 0; j < elements.length; j++) {
- NLSElement nlsElement= elements[j];
- if (!nlsElement.hasTag()) {
- AccessorClassReference accessorClassReference= NLSHintHelper.getAccessorClassReference(astRoot, nlsElement);
- if (accessorClassReference != null) {
- return accessorClassReference;
- }
- }
- }
- }
- return null;
- }
-
- private static String stripQuotes(String str) {
- return str.substring(1, str.length() - 1);
- }
-
- private static NLSLine[] createRawLines(IJavaScriptUnit cu) {
- try {
- return NLSScanner.scan(cu);
- } catch (JavaScriptModelException x) {
- return new NLSLine[0];
- } catch (InvalidInputException x) {
- return new NLSLine[0];
- }
- }
-
-
- public String getAccessorClassName() {
- return fAccessorName;
- }
-
-// public boolean isEclipseNLS() {
-// return fIsEclipseNLS;
-// }
-
- public IPackageFragment getAccessorClassPackage() {
- return fAccessorPackage;
- }
-
- public String getResourceBundleName() {
- return fResourceBundleName;
- }
-
- public IPackageFragment getResourceBundlePackage() {
- return fResourceBundlePackage;
- }
-
- public NLSSubstitution[] getSubstitutions() {
- return fSubstitutions;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHintHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHintHelper.java
deleted file mode 100644
index cc79c2ba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSHintHelper.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-public class NLSHintHelper {
-
- private NLSHintHelper() {
- }
-
- /**
- * Returns the accessor binding info or <code>null</code> if this element is not a nls'ed entry
- */
- public static AccessorClassReference getAccessorClassReference(JavaScriptUnit astRoot, NLSElement nlsElement) {
- IRegion region= nlsElement.getPosition();
- return getAccessorClassReference(astRoot, region);
- }
-
- /**
- * Returns the accessor binding info or <code>null</code> if this element is not a nls'ed entry
- */
- public static AccessorClassReference getAccessorClassReference(JavaScriptUnit astRoot, IRegion region) {
- ASTNode nlsStringLiteral= NodeFinder.perform(astRoot, region.getOffset(), region.getLength());
- if (nlsStringLiteral == null) {
- return null; // not found
- }
- ASTNode parent= nlsStringLiteral.getParent();
-
- ITypeBinding accessorBinding= null;
- if (parent instanceof FunctionInvocation) {
- FunctionInvocation methodInvocation= (FunctionInvocation) parent;
- List args= methodInvocation.arguments();
- if (args.indexOf(nlsStringLiteral) != 0) {
- return null; // must be first argument in lookup method
- }
-
- Expression firstArgument= (Expression)args.get(0);
- ITypeBinding argumentBinding= firstArgument.resolveTypeBinding();
- if (argumentBinding == null || !argumentBinding.getQualifiedName().equals("java.lang.String")) { //$NON-NLS-1$
- return null;
- }
-
- ITypeBinding typeBinding= methodInvocation.resolveTypeBinding();
- if (typeBinding == null || !typeBinding.getQualifiedName().equals("java.lang.String")) { //$NON-NLS-1$
- return null;
- }
-
- IFunctionBinding methodBinding= methodInvocation.resolveMethodBinding();
- if (methodBinding == null || !Modifier.isStatic(methodBinding.getModifiers())) {
- return null; // only static methods qualify
- }
-
- accessorBinding= methodBinding.getDeclaringClass();
- } else if (parent instanceof QualifiedName) {
- QualifiedName name= (QualifiedName)parent;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return null;
-
- IVariableBinding variableBinding= (IVariableBinding)binding;
- if (!Modifier.isStatic(variableBinding.getModifiers()))
- return null;
-
- accessorBinding= variableBinding.getDeclaringClass();
- } else if (parent instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment decl= (VariableDeclarationFragment)parent;
- if (decl.getInitializer() != null)
- return null;
-
- IBinding binding= decl.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return null;
-
- IVariableBinding variableBinding= (IVariableBinding)binding;
- if (!Modifier.isStatic(variableBinding.getModifiers()))
- return null;
-
- if (!Modifier.isPublic(variableBinding.getModifiers()))
- return null;
-
- accessorBinding= variableBinding.getDeclaringClass();
- }
- if (accessorBinding == null)
- return null;
-
- String resourceBundleName;
- try {
- resourceBundleName= getResourceBundleName(accessorBinding);
- } catch (JavaScriptModelException e) {
- return null;
- }
-
- if (resourceBundleName != null)
- return new AccessorClassReference(accessorBinding, resourceBundleName, new Region(parent.getStartPosition(), parent.getLength()));
-
- return null;
- }
-
- public static IPackageFragment getPackageOfAccessorClass(IJavaScriptProject javaProject, ITypeBinding accessorBinding) throws JavaScriptModelException {
- if (accessorBinding != null) {
- IJavaScriptUnit unit= Bindings.findCompilationUnit(accessorBinding, javaProject);
- if (unit != null) {
- return (IPackageFragment) unit.getParent();
- }
- }
- return null;
- }
-
- public static String getResourceBundleName(ITypeBinding accessorClassBinding) throws JavaScriptModelException {
- IJavaScriptElement je= accessorClassBinding.getJavaElement();
- if (je == null)
- return null;
-
- IOpenable openable= je.getOpenable();
- IJavaScriptElement container= null;
- if (openable instanceof IJavaScriptUnit)
- container= (IJavaScriptUnit)openable;
- else if (openable instanceof IClassFile)
- container= (IClassFile)openable;
- else
- Assert.isLegal(false);
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(container, ASTProvider.WAIT_YES, null);
-
- return getResourceBundleName(astRoot);
- }
-
- public static String getResourceBundleName(IJavaScriptUnit unit) throws JavaScriptModelException {
- return getResourceBundleName(JavaScriptPlugin.getDefault().getASTProvider().getAST(unit, ASTProvider.WAIT_YES, null));
- }
-
- public static String getResourceBundleName(IClassFile classFile) throws JavaScriptModelException {
- return getResourceBundleName(JavaScriptPlugin.getDefault().getASTProvider().getAST(classFile, ASTProvider.WAIT_YES, null));
- }
-
- public static String getResourceBundleName(JavaScriptUnit astRoot) throws JavaScriptModelException {
-
- if (astRoot == null)
- return null;
-
- final Map resultCollector= new HashMap(5);
- final Object RESULT_KEY= new Object();
- final Object FIELD_KEY= new Object();
-
- astRoot.accept(new ASTVisitor() {
-
- public boolean visit(FunctionInvocation node) {
- IFunctionBinding method= node.resolveMethodBinding();
- if (method == null)
- return true;
-
- String name= method.getDeclaringClass().getQualifiedName();
- if (!("java.util.ResourceBundle".equals(name) && "getBundle".equals(method.getName()) && node.arguments().size() > 0) && //old school //$NON-NLS-1$ //$NON-NLS-2$
- !("org.eclipse.osgi.util.NLS".equals(name) && "initializeMessages".equals(method.getName()) && node.arguments().size() == 2)) //Eclipse style //$NON-NLS-1$ //$NON-NLS-2$
- return true;
-
- Expression argument= (Expression)node.arguments().get(0);
- String bundleName= getBundleName(argument);
- if (bundleName != null)
- resultCollector.put(RESULT_KEY, bundleName);
-
- if (argument instanceof Name) {
- Object fieldNameBinding= ((Name)argument).resolveBinding();
- if (fieldNameBinding != null)
- resultCollector.put(FIELD_KEY, fieldNameBinding);
- }
-
- return false;
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- Expression initializer= node.getInitializer();
- String bundleName= getBundleName(initializer);
- if (bundleName != null) {
- Object fieldNameBinding= node.getName().resolveBinding();
- if (fieldNameBinding != null)
- resultCollector.put(fieldNameBinding, bundleName);
- return false;
- }
- return true;
- }
-
- public boolean visit(Assignment node) {
- if (node.getLeftHandSide() instanceof Name) {
- String bundleName= getBundleName(node.getRightHandSide());
- if (bundleName != null) {
- Object fieldNameBinding= ((Name)node.getLeftHandSide()).resolveBinding();
- if (fieldNameBinding != null) {
- resultCollector.put(fieldNameBinding, bundleName);
- return false;
- }
- }
- }
- return true;
- }
-
- private String getBundleName(Expression initializer) {
- if (initializer instanceof StringLiteral)
- return ((StringLiteral)initializer).getLiteralValue();
-
- if (initializer instanceof FunctionInvocation) {
- FunctionInvocation methInvocation= (FunctionInvocation)initializer;
- Expression exp= methInvocation.getExpression();
- if ((exp != null) && (exp instanceof TypeLiteral)) {
- SimpleType simple= (SimpleType)((TypeLiteral) exp).getType();
- ITypeBinding typeBinding= simple.resolveBinding();
- if (typeBinding != null)
- return typeBinding.getQualifiedName();
- }
- }
- return null;
- }
-
- });
-
-
- Object fieldName;
- String result;
-
- // First try hard-coded bundle name String field names from NLS tooling:
- Iterator iter= resultCollector.keySet().iterator();
- while (iter.hasNext()) {
- Object o= iter.next();
- if (!(o instanceof IBinding))
- continue;
- IBinding binding= (IBinding)o;
- fieldName= binding.getName();
- if (fieldName.equals("BUNDLE_NAME") || fieldName.equals("RESOURCE_BUNDLE") || fieldName.equals("bundleName")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- result= (String)resultCollector.get(binding);
- if (result != null)
- return result;
- }
- }
-
- result= (String)resultCollector.get(RESULT_KEY);
- if (result != null)
- return result;
-
- fieldName= resultCollector.get(FIELD_KEY);
- if (fieldName != null)
- return (String)resultCollector.get(fieldName);
-
- return null;
- }
-
- public static IPackageFragment getResourceBundlePackage(IJavaScriptProject javaProject, String packageName, String resourceName) throws JavaScriptModelException {
- IPackageFragmentRoot[] allRoots= javaProject.getAllPackageFragmentRoots();
- for (int i= 0; i < allRoots.length; i++) {
- IPackageFragmentRoot root= allRoots[i];
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IPackageFragment packageFragment= root.getPackageFragment(packageName);
- if (packageFragment.exists()) {
- Object[] resources= packageFragment.isDefaultPackage() ? root.getNonJavaScriptResources() : packageFragment.getNonJavaScriptResources();
- for (int j= 0; j < resources.length; j++) {
- Object object= resources[j];
- if (object instanceof IFile) {
- IFile file= (IFile) object;
- if (file.getName().equals(resourceName)) {
- return packageFragment;
- }
- }
- }
- }
- }
- }
- return null;
- }
-
- public static IStorage getResourceBundle(IJavaScriptUnit compilationUnit) throws JavaScriptModelException {
- IJavaScriptProject project= compilationUnit.getJavaScriptProject();
- if (project == null)
- return null;
-
- String name= getResourceBundleName(compilationUnit);
- if (name == null)
- return null;
-
- String packName= Signature.getQualifier(name);
- String resourceName= Signature.getSimpleName(name) + NLSRefactoring.PROPERTY_FILE_EXT;
-
- return getResourceBundle(project, packName, resourceName);
- }
-
- public static IStorage getResourceBundle(IJavaScriptProject javaProject, String packageName, String resourceName) throws JavaScriptModelException {
- IPackageFragmentRoot[] allRoots= javaProject.getAllPackageFragmentRoots();
- for (int i= 0; i < allRoots.length; i++) {
- IPackageFragmentRoot root= allRoots[i];
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IStorage storage= getResourceBundle(root, packageName, resourceName);
- if (storage != null)
- return storage;
- }
- }
- return null;
- }
-
- public static IStorage getResourceBundle(IPackageFragmentRoot root, String packageName, String resourceName) throws JavaScriptModelException {
- IPackageFragment packageFragment= root.getPackageFragment(packageName);
- if (packageFragment.exists()) {
- Object[] resources= packageFragment.isDefaultPackage() ? root.getNonJavaScriptResources() : packageFragment.getNonJavaScriptResources();
- for (int j= 0; j < resources.length; j++) {
- Object object= resources[j];
- if (JavaModelUtil.isOpenableStorage(object)) {
- IStorage storage= (IStorage)object;
- if (storage.getName().equals(resourceName)) {
- return storage;
- }
- }
- }
- }
- return null;
- }
-
- public static IStorage getResourceBundle(IJavaScriptProject javaProject, AccessorClassReference accessorClassReference) throws JavaScriptModelException {
- String resourceBundle= accessorClassReference.getResourceBundleName();
- if (resourceBundle == null)
- return null;
-
- String resourceName= Signature.getSimpleName(resourceBundle) + NLSRefactoring.PROPERTY_FILE_EXT;
- String packName= Signature.getQualifier(resourceBundle);
- ITypeBinding accessorClass= accessorClassReference.getBinding();
-
- if (accessorClass.isFromSource())
- return getResourceBundle(javaProject, packName, resourceName);
- else if (accessorClass.getJavaElement() != null)
- return getResourceBundle((IPackageFragmentRoot)accessorClass.getJavaElement().getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT), packName, resourceName);
-
- return null;
- }
-
- /**
- * Reads the properties from the given storage and
- * returns it.
- *
- * @param javaProject the Java project
- * @param accessorClassReference the accessor class reference
- * @return the properties or <code>null</code> if it was not successfully read
- */
- public static Properties getProperties(IJavaScriptProject javaProject, AccessorClassReference accessorClassReference) {
- try {
- IStorage storage= NLSHintHelper.getResourceBundle(javaProject, accessorClassReference);
- return getProperties(storage);
- } catch (JavaScriptModelException ex) {
- // sorry no properties
- return null;
- }
- }
-
- /**
- * Reads the properties from the given storage and
- * returns it.
- *
- * @param storage the storage
- * @return the properties or <code>null</code> if it was not successfully read
- */
- public static Properties getProperties(IStorage storage) {
- if (storage == null)
- return null;
-
- Properties props= new Properties();
- InputStream is= null;
-
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- if (manager != null) {
- ITextFileBuffer buffer= manager.getTextFileBuffer(storage.getFullPath(), LocationKind.NORMALIZE);
- if (buffer != null) {
- IDocument document= buffer.getDocument();
- is= new ByteArrayInputStream(document.get().getBytes());
- }
- }
-
- // Fallback: read from storage
- if (is == null)
- is= storage.getContents();
-
- props.load(is);
-
- } catch (IOException e) {
- // sorry no properties
- return null;
- } catch (CoreException e) {
- // sorry no properties
- return null;
- } finally {
- if (is != null) try {
- is.close();
- } catch (IOException e) {
- // return properties anyway but log
- JavaScriptPlugin.log(e);
- }
- }
- return props;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSLine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSLine.java
deleted file mode 100644
index b24f17b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSLine.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-
-
-public class NLSLine {
-
- private int fLineNumber;
- private List fElements;
-
- public NLSLine(int lineNumber) {
- fLineNumber= lineNumber;
- Assert.isTrue(fLineNumber >= 0);
- fElements= new ArrayList();
- }
-
- public int getLineNumber() {
- return fLineNumber;
- }
-
- /**
- * Adds a NLS element to this line.
- */
- public void add(NLSElement element) {
- Assert.isNotNull(element);
- fElements.add(element);
- }
-
- public NLSElement[] getElements() {
- return (NLSElement[]) fElements.toArray(new NLSElement[fElements.size()]);
- }
-
- public NLSElement get(int index) {
- return (NLSElement)fElements.get(index);
- }
-
- public boolean exists(int index) {
- return index >= 0 && index < fElements.size();
- }
-
- public int size(){
- return fElements.size();
- }
-
- /* non javaDoc
- * only for debugging
- * @see Object#toString()
- */
- public String toString() {
- StringBuffer result= new StringBuffer();
- result.append("Line: " + fLineNumber + "\n"); //$NON-NLS-2$ //$NON-NLS-1$
- for (Iterator iter= fElements.iterator(); iter.hasNext(); ) {
- result.append("\t"); //$NON-NLS-1$
- result.append(iter.next().toString());
- result.append("\n"); //$NON-NLS-1$
- }
- return result.toString();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.java
deleted file mode 100644
index 96eea074..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class NLSMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSMessages";//$NON-NLS-1$
-
- private NLSMessages() {
- // Do not instantiate
- }
-
- public static String NLSSourceModifier_replace_value;
- public static String NLSSourceModifier_replace_key;
- public static String NLSSourceModifier_externalize;
- public static String NLSSourceModifier_remove_tag;
- public static String NLSSourceModifier_change_description;
- public static String NLSSourceModifier_replace_accessor;
- public static String NLSSourceModifier_remove_accessor;
- public static String NLSSourceModifier_add_tag;
- public static String NLSRefactoring_compilation_unit;
- public static String NLSRefactoring_checking;
- public static String NLSRefactoring_pattern_empty;
- public static String NLSRefactoring_pattern_does_not_contain;
- public static String NLSRefactoring_Only_the_first_occurrence_of;
- public static String NLSRefactoring_null;
- public static String NLSRefactoring_empty;
- public static String NLSRefactoring_should_not_contain;
- public static String NLSRefactoring_nothing_to_do;
- public static String NLSRefactoring_will_be_created;
- public static String NLSRefactoring_no_strings;
- public static String NLSRefactoring_warning;
- public static String NLSRefactoring_change_name;
- public static String AccessorClassModifier_add_entry;
- public static String AccessorClassModifier_remove_entry;
- public static String AccessorClassModifier_replace_entry;
- public static String AccessorClassModifier_missingType;
- public static String NLSPropertyFileModifier_add_entry;
- public static String NLSPropertyFileModifier_change_name;
- public static String NLSPropertyFileModifier_replace_entry;
- public static String NLSPropertyFileModifier_remove_entry;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, NLSMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties
deleted file mode 100644
index d24228e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties
+++ /dev/null
@@ -1,45 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-NLSSourceModifier_replace_value=Rename value ''{0}'' to ''{1}''
-NLSSourceModifier_replace_key=Replace key ''{0}'' to ''{1}''
-NLSSourceModifier_externalize=Externalize string: ''{0}'' (key ''{1}'')
-NLSSourceModifier_remove_tag=Remove tag
-NLSSourceModifier_change_description=Externalize strings in ''{0}''
-NLSSourceModifier_replace_accessor=Replace accessor ''{0}'' to ''{1}''
-NLSSourceModifier_remove_accessor=Internalize string: ''{0}'' (key ''{1}'')
-NLSSourceModifier_add_tag=Add tag for ''{0}''
-
-NLSRefactoring_compilation_unit=Externalize strings in ''{0}''
-NLSRefactoring_checking=Checking preconditions...
-NLSRefactoring_pattern_empty=Code pattern is empty
-NLSRefactoring_pattern_does_not_contain=Code pattern does not contain ''{0}''
-NLSRefactoring_Only_the_first_occurrence_of=Only the first occurrence of ''{0}'' will be substituted
-NLSRefactoring_null=Key must not be null
-NLSRefactoring_empty=Key must not be empty
-NLSRefactoring_should_not_contain=Key ''{0}'' should not contain ''{1}''
-NLSRefactoring_nothing_to_do=Nothing to do
-NLSRefactoring_will_be_created=Property file ''{0}'' does not exist and will be created.
-NLSRefactoring_no_strings=No strings to externalize found in ''{0}''
-NLSRefactoring_change_name=Externalize Strings
-NLSRefactoring_warning=Keys should not start with characters \'!\' or \'#\'
-
-AccessorClassModifier_add_entry=Add entry ''{0}''
-AccessorClassModifier_remove_entry=Remove entry ''{0}''
-AccessorClassModifier_replace_entry=Rename entry ''{0}''
-AccessorClassModifier_missingType=Top-level type is missing.
-
-NLSPropertyFileModifier_add_entry=Add entry ''{0}''
-NLSPropertyFileModifier_change_name=Append to property file: ''{0}''
-NLSPropertyFileModifier_replace_entry=Rename entry ''{0}''
-NLSPropertyFileModifier_remove_entry=Remove entry ''{0}''
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSPropertyFileModifier.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSPropertyFileModifier.java
deleted file mode 100644
index 7a90e80d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSPropertyFileModifier.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.jface.text.Document;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.DocumentChange;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-
-public class NLSPropertyFileModifier {
-
- public static Change create(NLSSubstitution[] nlsSubstitutions, IPath propertyFilePath) throws CoreException {
-
- String name= Messages.format(NLSMessages.NLSPropertyFileModifier_change_name, propertyFilePath.toString());
- TextChange textChange= null;
- if (!Checks.resourceExists(propertyFilePath)) {
- IProject project= getFileHandle(propertyFilePath).getProject();
- String lineDelimiter= StubUtility.getLineDelimiterPreference(project);
- Document document= new Document();
- document.setInitialLineDelimiter(lineDelimiter);
- textChange= new DocumentChange(name, document);
- addChanges(textChange, nlsSubstitutions);
- textChange.perform(new NullProgressMonitor());
-
- String encoding= null;
- IContentType javaPropertiesContentType= Platform.getContentTypeManager().getContentType("org.eclipse.wst.jsdt.core.javaProperties"); //$NON-NLS-1$
- IContentType[] contentTypes= Platform.getContentTypeManager().findContentTypesFor(propertyFilePath.lastSegment());
- if (contentTypes.length == 0 || contentTypes.length > 1 || !contentTypes[0].equals(javaPropertiesContentType)) {
- if (javaPropertiesContentType != null)
- encoding= javaPropertiesContentType.getDefaultCharset();
- if (encoding == null)
- encoding= "ISO-8859-1"; //$NON-NLS-1$
- }
-
- return new CreateTextFileChange(propertyFilePath, textChange.getCurrentContent(new NullProgressMonitor()), encoding, "properties"); //$NON-NLS-1$
- }
-
- textChange= new TextFileChange(name, getPropertyFile(propertyFilePath));
- textChange.setTextType("properties"); //$NON-NLS-1$
-
- addChanges(textChange, nlsSubstitutions);
-
- return textChange;
- }
-
- private static IFile getPropertyFile(IPath propertyFilePath) {
- return (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(propertyFilePath);
- }
-
- private static IFile getFileHandle(IPath propertyFilePath) {
- if (propertyFilePath == null)
- return null;
- return ResourcesPlugin.getWorkspace().getRoot().getFile(propertyFilePath);
- }
-
- private static void addChanges(TextChange textChange, NLSSubstitution[] substitutions) throws CoreException {
- PropertyFileDocumentModel model= new PropertyFileDocumentModel(textChange.getCurrentDocument(new NullProgressMonitor()));
-
- Map newKeyToSubstMap= getNewKeyToSubstitutionMap(substitutions);
- Map oldKeyToSubstMap= getOldKeyToSubstitutionMap(substitutions);
-
- addInsertEdits(textChange, substitutions, newKeyToSubstMap, oldKeyToSubstMap, model);
- addRemoveEdits(textChange, substitutions, newKeyToSubstMap, oldKeyToSubstMap, model);
- addReplaceEdits(textChange, substitutions, newKeyToSubstMap, oldKeyToSubstMap, model);
- }
-
- /**
- * Maps the new keys to a substitutions. If a substitution is not in the map then it is a duplicate.
- */
- static HashMap getNewKeyToSubstitutionMap(NLSSubstitution[] substitutions) {
- HashMap keyToSubstMap= new HashMap(substitutions.length);
- // find all duplicates
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution curr= substitutions[i];
- if (curr.getState() == NLSSubstitution.EXTERNALIZED) {
- NLSSubstitution val= (NLSSubstitution) keyToSubstMap.get(curr.getKey());
- if (val == null || (val.hasPropertyFileChange() && !curr.hasPropertyFileChange())) {
- keyToSubstMap.put(curr.getKey(), curr); // store if first or if stored in new and we are existing
- }
- }
- }
- return keyToSubstMap;
- }
-
- /**
- * Maps the old keys to a substitutions. If a substitution is not in the map then it is a duplicate.
- */
- static HashMap getOldKeyToSubstitutionMap(NLSSubstitution[] substitutions) {
- HashMap keyToSubstMap= new HashMap(substitutions.length);
- // find all duplicates
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution curr= substitutions[i];
- if (curr.getInitialState() == NLSSubstitution.EXTERNALIZED) {
- String key= curr.getInitialKey();
- if (key != null) {
- NLSSubstitution fav= (NLSSubstitution) keyToSubstMap.get(key);
- if (fav == null || (fav.hasStateChanged() && !curr.hasStateChanged())) {
- keyToSubstMap.put(key, curr); // store if first or if stored will not be externalized anymore
- }
- }
- }
- }
- return keyToSubstMap;
- }
-
- static boolean doReplace(NLSSubstitution substitution, Map newKeyToSubstMap, Map oldKeyToSubstMap) {
- if (substitution.getState() != NLSSubstitution.EXTERNALIZED || substitution.hasStateChanged() || substitution.getInitialValue() == null) {
- return false; // was not in property file before
- }
- if (oldKeyToSubstMap.get(substitution.getInitialKey()) != substitution) {
- return false; // not the owner of this key
- }
- if (substitution.isKeyRename() || substitution.isValueRename()) {
- if (newKeyToSubstMap.get(substitution.getKey()) == substitution) { // only rename if we're not a duplicate. duplicates will be removed
- return true;
- }
- }
- return false;
- }
-
- private static void addReplaceEdits(TextChange textChange, NLSSubstitution[] substitutions, Map newKeyToSubstMap, Map oldKeyToSubstMap, PropertyFileDocumentModel model) {
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (doReplace(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- KeyValuePair initialPair= new KeyValuePair(substitution.getInitialKey(), substitution.getInitialValue());
- KeyValuePair newPair= new KeyValuePair(substitution.getKey(), substitution.getValueNonEmpty());
- TextEdit edit= model.replace(initialPair, newPair);
- if (edit != null) {
- TextChangeCompatibility.addTextEdit(textChange, Messages.format(NLSMessages.NLSPropertyFileModifier_replace_entry, substitution.getKey()), edit);
- }
- }
- }
- }
-
- static boolean doInsert(NLSSubstitution substitution, Map newKeyToSubstMap, Map oldKeyToSubstMap) {
- if (substitution.getState() != NLSSubstitution.EXTERNALIZED) {
- return false; // does not go into the property file
- }
- if (!substitution.hasStateChanged() && substitution.getInitialValue() != null) {
- if (!substitution.isKeyRename() || oldKeyToSubstMap.get(substitution.getInitialKey()) == substitution) {
- return false; // no key rename and was not a duplicate
- }
- }
- if (newKeyToSubstMap.get(substitution.getKey()) == substitution) { // only insert if we're not a duplicate
- return true;
- }
- return false;
- }
-
- private static void addInsertEdits(TextChange textChange, NLSSubstitution[] substitutions, Map newKeyToSubstMap, Map oldKeyToSubstMap, PropertyFileDocumentModel model) {
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (doInsert(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- String value= substitution.getValueNonEmpty();
- KeyValuePair curr= new KeyValuePair(substitution.getKey(), value);
-
- InsertEdit insert= model.insert(curr);
- String message= Messages.format(NLSMessages.NLSPropertyFileModifier_add_entry, curr.getKey());
- TextChangeCompatibility.addTextEdit(textChange, message, insert);
- }
- }
- }
-
- static boolean doRemove(NLSSubstitution substitution, Map newKeyToSubstMap, Map oldKeyToSubstMap) {
- if (substitution.getInitialState() != NLSSubstitution.EXTERNALIZED || substitution.getInitialKey() == null) {
- return false; // was not in property file before
- }
- if (oldKeyToSubstMap.get(substitution.getInitialKey()) != substitution) {
- return false; // not the owner of this key
- }
- if (substitution.hasStateChanged()) {
- return true; // was externalized, but not anymore
- } else {
- if (substitution.hasPropertyFileChange() && newKeyToSubstMap.get(substitution.getKey()) != substitution) {
- return true; // has been changed to an already existing
- }
- }
- return false;
- }
-
- private static void addRemoveEdits(TextChange textChange, NLSSubstitution[] substitutions, Map newKeyToSubstMap, Map oldKeyToSubstMap, PropertyFileDocumentModel model) {
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (doRemove(substitution, newKeyToSubstMap, oldKeyToSubstMap)) {
- TextEdit edit= model.remove(substitution.getInitialKey());
- if (edit != null) {
- TextChangeCompatibility.addTextEdit(textChange, Messages.format(NLSMessages.NLSPropertyFileModifier_remove_entry, substitution.getInitialKey()), edit);
- }
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSRefactoring.java
deleted file mode 100644
index 5d514b21..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSRefactoring.java
+++ /dev/null
@@ -1,527 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-public class NLSRefactoring extends Refactoring {
-
- public static final String BUNDLE_NAME= "BUNDLE_NAME"; //$NON-NLS-1$
- public static final String PROPERTY_FILE_EXT= ".properties"; //$NON-NLS-1$
- public static final String DEFAULT_ACCESSOR_CLASSNAME= "Messages"; //$NON-NLS-1$
-
- public static final String KEY= "${key}"; //$NON-NLS-1$
- public static final String DEFAULT_SUBST_PATTERN= "getString(" + KEY + ")"; //$NON-NLS-1$ //$NON-NLS-2$
-
- public static final String DEFAULT_PROPERTY_FILENAME= "messages"; //$NON-NLS-1$
-
- //private IPath fPropertyFilePath;
-
- private String fAccessorClassName;
- private IPackageFragment fAccessorClassPackage;
- private String fResourceBundleName;
- private IPackageFragment fResourceBundlePackage;
-
- private String fSubstitutionPattern;
- private IJavaScriptUnit fCu;
- private NLSSubstitution[] fSubstitutions;
-
- private String fPrefix;
-
- /**
- * <code>true</code> if the standard resource bundle mechanism
- * is used and <code>false</code> NLSing is done the Eclipse way.
- */
- private boolean fIsEclipseNLS;
-
- private NLSRefactoring(IJavaScriptUnit cu) {
- Assert.isNotNull(cu);
- fCu= cu;
-
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(fCu, ASTProvider.WAIT_YES, null);
- NLSHint nlsHint= new NLSHint(fCu, astRoot);
-
- fSubstitutions= nlsHint.getSubstitutions();
- setAccessorClassName(nlsHint.getAccessorClassName());
- setAccessorClassPackage(nlsHint.getAccessorClassPackage());
- setIsEclipseNLS(detectIsEclipseNLS());
- setResourceBundleName(nlsHint.getResourceBundleName());
- setResourceBundlePackage(nlsHint.getResourceBundlePackage());
- setSubstitutionPattern(DEFAULT_SUBST_PATTERN);
-
- String cuName= fCu.getElementName();
- if (fIsEclipseNLS)
- setPrefix(cuName.substring(0, cuName.length() - 5) + "_"); // A.java -> A_ //$NON-NLS-1$
- else
- setPrefix(cuName.substring(0, cuName.length() - 4)); // A.java -> A.
- }
-
- public static NLSRefactoring create(IJavaScriptUnit cu) {
- if (cu == null || !cu.exists())
- return null;
- return new NLSRefactoring(cu);
- }
-
- /**
- * no validation is done
- *
- * @param pattern
- * Example: "Messages.getString(${key})". Must not be
- * <code>null</code>. should (but does not have to) contain
- * NLSRefactoring.KEY (default value is $key$) only the first
- * occurrence of this key will be used
- */
- public void setSubstitutionPattern(String pattern) {
- Assert.isNotNull(pattern);
- fSubstitutionPattern= pattern;
- }
-
- /**
- * to show the pattern in the UI
- */
- public String getSubstitutionPattern() {
- if (fIsEclipseNLS)
- return KEY;
- else
- return fSubstitutionPattern;
- }
-
- public IJavaScriptUnit getCu() {
- return fCu;
- }
-
- public String getName() {
- return Messages.format(NLSMessages.NLSRefactoring_compilation_unit, fCu.getElementName());
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
-
- if (fSubstitutions.length == 0) {
- String message= Messages.format(NLSMessages.NLSRefactoring_no_strings, fCu.getElementName());
- return RefactoringStatus.createFatalErrorStatus(message);
- }
- return new RefactoringStatus();
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- checkParameters();
- try {
-
- pm.beginTask(NLSMessages.NLSRefactoring_checking, 5);
-
- RefactoringStatus result= new RefactoringStatus();
-
- result.merge(checkIfAnythingToDo());
- if (result.hasFatalError()) {
- return result;
- }
- pm.worked(1);
-
- result.merge(validateModifiesFiles());
- if (result.hasFatalError()) {
- return result;
- }
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- result.merge(checkSubstitutionPattern());
- pm.worked(1);
-
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
-
- result.merge(checkKeys());
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- if (!propertyFileExists() && willModifyPropertyFile()) {
- String msg= Messages.format(NLSMessages.NLSRefactoring_will_be_created, getPropertyFilePath().toString());
- result.addInfo(msg);
- }
- pm.worked(1);
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- try {
- checkParameters();
-
- pm.beginTask("", 3); //$NON-NLS-1$
-
- final DynamicValidationStateChange result= new DynamicValidationStateChange(NLSMessages.NLSRefactoring_change_name);
-
- boolean createAccessorClass= willCreateAccessorClass();
- if (NLSSubstitution.countItems(fSubstitutions, NLSSubstitution.EXTERNALIZED) == 0) {
- createAccessorClass= false;
- }
- if (createAccessorClass) {
- result.add(AccessorClassCreator.create(fCu, fAccessorClassName, getAccessorCUPath(), fAccessorClassPackage, getPropertyFilePath(), fIsEclipseNLS, fSubstitutions, getSubstitutionPattern(), new SubProgressMonitor(pm, 1)));
- }
- pm.worked(1);
-
- if (willModifySource()) {
- result.add(NLSSourceModifier.create(getCu(), fSubstitutions, getSubstitutionPattern(), fAccessorClassPackage, fAccessorClassName, fIsEclipseNLS));
- }
- pm.worked(1);
-
- if (willModifyPropertyFile()) {
- result.add(NLSPropertyFileModifier.create(fSubstitutions, getPropertyFilePath()));
- if (isEclipseNLS() && !createAccessorClass) {
- Change change= AccessorClassModifier.create(getAccessorCu(), fSubstitutions);
- if (change != null)
- result.add(change);
- }
- }
- pm.worked(1);
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- private void checkParameters() {
- Assert.isNotNull(fSubstitutions);
- Assert.isNotNull(fAccessorClassPackage);
-
- // these values have defaults ...
- Assert.isNotNull(fAccessorClassName);
- Assert.isNotNull(getSubstitutionPattern());
- }
-
- private IFile[] getAllFilesToModify() {
-
- List files= new ArrayList(2);
- if (willModifySource()) {
- IResource resource= fCu.getResource();
- if (resource.exists()) {
- files.add(resource);
- }
- }
-
- if (willModifyPropertyFile()) {
- IFile file= getPropertyFileHandle();
- if (file.exists()) {
- files.add(file);
- }
- }
-
- if (willModifyAccessorClass()) {
- IFile file= getAccessorClassFileHandle();
- if (file.exists()) {
- files.add(file);
- }
- }
-
- return (IFile[]) files.toArray(new IFile[files.size()]);
- }
-
- public IFile getPropertyFileHandle() {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(getPropertyFilePath());
- }
-
- public IPath getPropertyFilePath() {
- return fResourceBundlePackage.getPath().append(fResourceBundleName);
- }
-
- public IFile getAccessorClassFileHandle() {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(getAccessorClassFilePath());
- }
-
- public IPath getAccessorClassFilePath() {
- return getAccessorCUPath();
- }
-
- private RefactoringStatus validateModifiesFiles() {
- return Checks.validateModifiesFiles(getAllFilesToModify(), getValidationContext());
- }
-
- //should stop checking if fatal error
- private RefactoringStatus checkIfAnythingToDo() throws JavaScriptModelException {
- if (NLSSubstitution.countItems(fSubstitutions, NLSSubstitution.EXTERNALIZED) != 0 && willCreateAccessorClass())
- return null;
-
- if (willModifyPropertyFile())
- return null;
-
- if (willModifySource())
- return null;
-
- RefactoringStatus result= new RefactoringStatus();
- result.addFatalError(NLSMessages.NLSRefactoring_nothing_to_do);
- return result;
- }
-
- private boolean propertyFileExists() {
- return getPropertyFileHandle().exists();
- }
-
- private RefactoringStatus checkSubstitutionPattern() {
- String pattern= getSubstitutionPattern();
-
- RefactoringStatus result= new RefactoringStatus();
- if (pattern.trim().length() == 0) {//
- result.addError(NLSMessages.NLSRefactoring_pattern_empty);
- }
-
- if (pattern.indexOf(KEY) == -1) {
- String msg= Messages.format(NLSMessages.NLSRefactoring_pattern_does_not_contain, KEY);
- result.addWarning(msg);
- }
-
- if (pattern.indexOf(KEY) != pattern.lastIndexOf(KEY)) {
- String msg= Messages.format(NLSMessages.NLSRefactoring_Only_the_first_occurrence_of, KEY);
- result.addWarning(msg);
- }
-
- return result;
- }
-
- private RefactoringStatus checkKeys() {
- RefactoringStatus result= new RefactoringStatus();
- NLSSubstitution[] subs= fSubstitutions;
- for (int i= 0; i < subs.length; i++) {
- NLSSubstitution substitution= subs[i];
- if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
- result.merge(checkKey(substitution.getKey()));
- }
- }
- return result;
- }
-
- private static RefactoringStatus checkKey(String key) {
- RefactoringStatus result= new RefactoringStatus();
-
- if (key == null)
- result.addFatalError(NLSMessages.NLSRefactoring_null);
-
- if (key.startsWith("!") || key.startsWith("#")) { //$NON-NLS-1$ //$NON-NLS-2$
- RefactoringStatusContext context= new JavaStringStatusContext(key, new SourceRange(0, 0));
- result.addWarning(NLSMessages.NLSRefactoring_warning, context);
- }
-
- if ("".equals(key.trim())) //$NON-NLS-1$
- result.addFatalError(NLSMessages.NLSRefactoring_empty);
-
- final String[] UNWANTED_STRINGS= {" ", ":", "\"", "\\", "'", "?", "="}; //$NON-NLS-7$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- //feature in resource bundle - does not work properly if keys have ":"
- for (int i= 0; i < UNWANTED_STRINGS.length; i++) {
- if (key.indexOf(UNWANTED_STRINGS[i]) != -1) {
- String[] args= {key, UNWANTED_STRINGS[i]};
- String msg= Messages.format(NLSMessages.NLSRefactoring_should_not_contain, args);
- result.addError(msg);
- }
- }
- return result;
- }
-
- public boolean willCreateAccessorClass() throws JavaScriptModelException {
-
- IJavaScriptUnit compilationUnit= getAccessorCu();
- if (compilationUnit.exists()) {
- return false;
- }
-
- if (typeNameExistsInPackage(fAccessorClassPackage, fAccessorClassName)) {
- return false;
- }
-
- return (!Checks.resourceExists(getAccessorCUPath()));
- }
-
- private IJavaScriptUnit getAccessorCu() {
- return fAccessorClassPackage.getJavaScriptUnit(getAccessorCUName());
- }
-
- private boolean willModifySource() {
- NLSSubstitution[] subs= fSubstitutions;
- for (int i= 0; i < subs.length; i++) {
- if (subs[i].hasSourceChange())
- return true;
- }
- return false;
- }
-
- private boolean willModifyPropertyFile() {
- NLSSubstitution[] subs= fSubstitutions;
- for (int i= 0; i < subs.length; i++) {
- NLSSubstitution substitution= subs[i];
- if (substitution.hasPropertyFileChange()) {
- return true;
- }
- }
- return false;
- }
-
- private boolean willModifyAccessorClass() {
- if (!isEclipseNLS())
- return false;
-
- NLSSubstitution[] subs= fSubstitutions;
- for (int i= 0; i < subs.length; i++) {
- NLSSubstitution substitution= subs[i];
- if (substitution.hasAccessorClassChange()) {
- return true;
- }
- }
- return false;
- }
-
- private boolean typeNameExistsInPackage(IPackageFragment pack, String name) throws JavaScriptModelException {
- return Checks.findTypeInPackage(pack, name) != null;
- }
-
- private String getAccessorCUName() {
- return getAccessorClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX;
- }
-
- private IPath getAccessorCUPath() {
- return fAccessorClassPackage.getPath().append(getAccessorCUName());
- }
-
- public NLSSubstitution[] getSubstitutions() {
- return fSubstitutions;
- }
-
- public String getPrefix() {
- return fPrefix;
- }
-
- public void setPrefix(String prefix) {
- fPrefix= prefix;
- if (fSubstitutions != null) {
- for (int i= 0; i < fSubstitutions.length; i++)
- fSubstitutions[i].setPrefix(prefix);
- }
- }
-
- public void setAccessorClassName(String name) {
- Assert.isNotNull(name);
- fAccessorClassName= name;
- }
-
- public void setAccessorClassPackage(IPackageFragment packageFragment) {
- Assert.isNotNull(packageFragment);
- fAccessorClassPackage= packageFragment;
- }
-
- /**
- * Sets whether the Eclipse NLSing mechanism or
- * standard resource bundle mechanism is used.
- *
- * @param isEclipseNLS <code>true</code> if NLSing is done the Eclipse way
- * and <code>false</code> if the standard resource bundle mechanism is used
- *
- */
- public void setIsEclipseNLS(boolean isEclipseNLS) {
- fIsEclipseNLS= isEclipseNLS;
- }
-
- public void setResourceBundlePackage(IPackageFragment resourceBundlePackage) {
- Assert.isNotNull(resourceBundlePackage);
- fResourceBundlePackage= resourceBundlePackage;
- }
-
- public void setResourceBundleName(String resourceBundleName) {
- Assert.isNotNull(resourceBundleName);
- fResourceBundleName= resourceBundleName;
- }
-
- public IPackageFragment getAccessorClassPackage() {
- return fAccessorClassPackage;
- }
-
- /**
- * Computes whether the Eclipse NLSing mechanism is used.
- *
- * @return <code>true</code> if NLSing is done the Eclipse way
- * and <code>false</code> if the standard resource bundle mechanism is used
- *
- */
- public boolean detectIsEclipseNLS() {
- if (getAccessorClassPackage() != null) {
- IJavaScriptUnit accessorCU= getAccessorClassPackage().getJavaScriptUnit(getAccessorCUName());
- IType type= accessorCU.getType(getAccessorClassName());
- if (type.exists()) {
- try {
- String superclassName= type.getSuperclassName();
- if (!"NLS".equals(superclassName) && !NLS.class.getName().equals(superclassName)) //$NON-NLS-1$
- return false;
- IType superclass= type.newSupertypeHierarchy(null).getSuperclass(type);
- return superclass != null && NLS.class.getName().equals(superclass.getFullyQualifiedName());
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
- }
- return fIsEclipseNLS;
- }
-
- /**
- * Returns whether the Eclipse NLSing mechanism or
- * the standard resource bundle mechanism is used.
- *
- * @return <code>true</code> if NLSing is done the Eclipse way
- * and <code>false</code> if the standard resource bundle mechanism is used
- *
- */
- public boolean isEclipseNLS() {
- return fIsEclipseNLS;
- }
-
- public IPackageFragment getResourceBundlePackage() {
- return fResourceBundlePackage;
- }
-
- public String getAccessorClassName() {
- return fAccessorClassName;
- }
-
- public String getResourceBundleName() {
- return fResourceBundleName;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSScanner.java
deleted file mode 100644
index f602811f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSScanner.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-
-public class NLSScanner {
-
- //no instances
- private NLSScanner() {
- }
-
- /**
- * Returns a list of NLSLines found in the compilation unit
- */
- public static NLSLine[] scan(IJavaScriptUnit cu) throws JavaScriptModelException, InvalidInputException {
- return scan(cu.getBuffer().getCharacters());
- }
-
- /**
- * Returns a list of NLSLines found in the string
- */
- public static NLSLine[] scan(String s) throws InvalidInputException {
- return scan(s.toCharArray());
- }
-
- private static NLSLine[] scan(char[] content) throws InvalidInputException {
- List lines= new ArrayList();
- IScanner scanner= ToolFactory.createScanner(true, true, false, true);
- scanner.setSource(content);
- int token= scanner.getNextToken();
- int currentLineNr= -1;
- int previousLineNr= -1;
- NLSLine currentLine= null;
- int nlsElementIndex= 0;
-
- while (token != ITerminalSymbols.TokenNameEOF) {
- switch (token) {
- case ITerminalSymbols.TokenNameStringLiteral:
- currentLineNr= scanner.getLineNumber(scanner.getCurrentTokenStartPosition());
- if (currentLineNr != previousLineNr) {
- currentLine= new NLSLine(currentLineNr - 1);
- lines.add(currentLine);
- previousLineNr= currentLineNr;
- nlsElementIndex= 0;
- }
- String value= new String(scanner.getCurrentTokenSource());
- currentLine.add(
- new NLSElement(
- value,
- scanner.getCurrentTokenStartPosition(),
- scanner.getCurrentTokenEndPosition() + 1 - scanner.getCurrentTokenStartPosition(),
- nlsElementIndex++,
- false));
- break;
- case ITerminalSymbols.TokenNameCOMMENT_LINE:
- if (currentLineNr != scanner.getLineNumber(scanner.getCurrentTokenStartPosition()))
- break;
-
- parseTags(currentLine, scanner);
- break;
- }
- token= scanner.getNextToken();
- }
- NLSLine[] result;
- try {
- result= (NLSLine[]) lines.toArray(new NLSLine[lines.size()]);
- IDocument document= new Document(String.valueOf(scanner.getSource()));
- for (int i= 0; i < result.length; i++) {
- setTagPositions(document, result[i]);
- }
- } catch (BadLocationException exception) {
- throw new InvalidInputException();
- }
- return result;
- }
-
- private static void parseTags(NLSLine line, IScanner scanner) {
- String s= new String(scanner.getCurrentTokenSource());
- int pos= s.indexOf(NLSElement.TAG_PREFIX);
- while (pos != -1) {
- int start= pos + NLSElement.TAG_PREFIX_LENGTH;
- int end= s.indexOf(NLSElement.TAG_POSTFIX, start);
- if (end < 0)
- return; //no error recovery
-
- String index= s.substring(start, end);
- int i= 0;
- try {
- i= Integer.parseInt(index) - 1; // Tags are one based not zero based.
- } catch (NumberFormatException e) {
- return; //ignore the exception - no error recovery
- }
- if (line.exists(i)) {
- NLSElement element= line.get(i);
- element.setTagPosition(scanner.getCurrentTokenStartPosition() + pos, end - pos + 1);
- } else {
- return; //no error recovery
- }
- pos= s.indexOf(NLSElement.TAG_PREFIX, start);
- }
- }
-
- private static void setTagPositions(IDocument document, NLSLine line) throws BadLocationException {
- IRegion info= document.getLineInformation(line.getLineNumber());
- int defaultValue= info.getOffset() + info.getLength();
- NLSElement[] elements= line.getElements();
- for (int i= 0; i < elements.length; i++) {
- NLSElement element= elements[i];
- if (!element.hasTag()) {
- element.setTagPosition(computeInsertOffset(elements, i, defaultValue), 0);
- }
- }
- }
-
- private static int computeInsertOffset(NLSElement[] elements, int index, int defaultValue) {
- NLSElement previousTagged= findPreviousTagged(index, elements);
- if (previousTagged != null)
- return previousTagged.getTagPosition().getOffset() + previousTagged.getTagPosition().getLength();
- NLSElement nextTagged= findNextTagged(index, elements);
- if (nextTagged != null)
- return nextTagged.getTagPosition().getOffset();
- return defaultValue;
- }
-
- private static NLSElement findPreviousTagged(int startIndex, NLSElement[] elements){
- int i= startIndex - 1;
- while (i >= 0){
- if (elements[i].hasTag())
- return elements[i];
- i--;
- }
- return null;
- }
-
- private static NLSElement findNextTagged(int startIndex, NLSElement[] elements){
- int i= startIndex + 1;
- while (i < elements.length){
- if (elements[i].hasTag())
- return elements[i];
- i++;
- }
- return null;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSourceModifier.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSourceModifier.java
deleted file mode 100644
index 79e2a745..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSourceModifier.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class NLSSourceModifier {
-
- private final String fSubstitutionPattern;
- private final boolean fIsEclipseNLS;
-
- private NLSSourceModifier(String substitutionPattern, boolean isEclipseNLS) {
- fSubstitutionPattern= substitutionPattern;
- fIsEclipseNLS= isEclipseNLS;
- }
-
- public static Change create(IJavaScriptUnit cu, NLSSubstitution[] subs, String substitutionPattern, IPackageFragment accessorPackage, String accessorClassName, boolean isEclipseNLS) throws CoreException {
-
- NLSSourceModifier sourceModification= new NLSSourceModifier(substitutionPattern, isEclipseNLS);
-
- String message= Messages.format(NLSMessages.NLSSourceModifier_change_description, cu.getElementName());
-
- TextChange change= new CompilationUnitChange(message, cu);
- MultiTextEdit multiTextEdit= new MultiTextEdit();
- change.setEdit(multiTextEdit);
-
- accessorClassName= sourceModification.createImportForAccessor(multiTextEdit, accessorClassName, accessorPackage, cu);
-
- for (int i= 0; i < subs.length; i++) {
- NLSSubstitution substitution= subs[i];
- int newState= substitution.getState();
- if (substitution.hasStateChanged()) {
- if (newState == NLSSubstitution.EXTERNALIZED) {
- if (substitution.getInitialState() == NLSSubstitution.INTERNALIZED) {
- sourceModification.addNLS(substitution, change, accessorClassName);
- } else if (substitution.getInitialState() == NLSSubstitution.IGNORED) {
- sourceModification.addAccessor(substitution, change, accessorClassName);
- }
- } else if (newState == NLSSubstitution.INTERNALIZED) {
- if (substitution.getInitialState() == NLSSubstitution.IGNORED) {
- sourceModification.deleteTag(substitution, change);
- if (substitution.isValueRename()) {
- sourceModification.replaceValue(substitution, change);
- }
- } else if (substitution.getInitialState() == NLSSubstitution.EXTERNALIZED) {
- sourceModification.deleteAccessor(substitution, change, cu);
- if (!isEclipseNLS)
- sourceModification.deleteTag(substitution, change);
- }
- } else if (newState == NLSSubstitution.IGNORED) {
- if (substitution.getInitialState() == NLSSubstitution.INTERNALIZED) {
- sourceModification.addNLS(substitution, change, accessorClassName);
- if (substitution.isValueRename()) {
- sourceModification.replaceValue(substitution, change);
- }
- } else {
- if (substitution.getInitialState() == NLSSubstitution.EXTERNALIZED) {
- sourceModification.deleteAccessor(substitution, change, cu);
- }
- }
- }
- } else {
- if (newState == NLSSubstitution.EXTERNALIZED) {
- if (substitution.isKeyRename()) {
- sourceModification.replaceKey(substitution, change);
- }
- if (substitution.isAccessorRename()) {
- sourceModification.replaceAccessor(substitution, change);
- }
- } else {
- if (substitution.isValueRename()) {
- sourceModification.replaceValue(substitution, change);
- }
- }
- }
- }
-
- return change;
- }
-
- /**
- * @param substitution
- * @param change
- */
- private void replaceAccessor(NLSSubstitution substitution, TextChange change) {
- AccessorClassReference accessorClassRef= substitution.getAccessorClassReference();
- if (accessorClassRef != null) {
- Region region= accessorClassRef.getRegion();
- int len= accessorClassRef.getName().length();
- String[] args= {accessorClassRef.getName(), substitution.getUpdatedAccessor()};
- TextChangeCompatibility.addTextEdit(change, Messages.format(NLSMessages.NLSSourceModifier_replace_accessor, args),
- new ReplaceEdit(region.getOffset(), len, substitution.getUpdatedAccessor())); //
- }
-
- }
-
- private void replaceKey(NLSSubstitution substitution, TextChange change) {
- Region region= substitution.getNLSElement().getPosition();
- String[] args= {substitution.getInitialKey(), substitution.getKey()};
-
- ReplaceEdit replaceEdit;
- if (fIsEclipseNLS)
- replaceEdit= new ReplaceEdit(region.getOffset(), region.getLength(), substitution.getKey());
- else
- replaceEdit= new ReplaceEdit(region.getOffset(), region.getLength(), '\"' + unwindEscapeChars(substitution.getKey()) + '\"'); //
-
- TextChangeCompatibility.addTextEdit(change, Messages.format(NLSMessages.NLSSourceModifier_replace_key, args), replaceEdit);
- }
-
- private void replaceValue(NLSSubstitution substitution, TextChange change) {
- Region region= substitution.getNLSElement().getPosition();
- String[] args= {substitution.getInitialValue(), substitution.getValueNonEmpty()};
- TextChangeCompatibility.addTextEdit(change, Messages.format(NLSMessages.NLSSourceModifier_replace_value, args),
- new ReplaceEdit(region.getOffset(), region.getLength(), '\"' + unwindEscapeChars(substitution.getValueNonEmpty()) + '\"')); //
- }
-
- private void deleteAccessor(NLSSubstitution substitution, TextChange change, IJavaScriptUnit cu) throws CoreException {
- AccessorClassReference accessorClassRef= substitution.getAccessorClassReference();
- if (accessorClassRef != null) {
- Region region= accessorClassRef.getRegion();
- String[] args= {substitution.getValueNonEmpty(), substitution.getKey()};
- String label= Messages.format(NLSMessages.NLSSourceModifier_remove_accessor, args);
- String replaceString= '\"' + unwindEscapeChars(substitution.getValueNonEmpty()) + '\"';
- TextChangeCompatibility.addTextEdit(change, label, new ReplaceEdit(region.getOffset(), region.getLength(), replaceString));
- if (fIsEclipseNLS && substitution.getState() != NLSSubstitution.INTERNALIZED) {
-
- Region position= substitution.getNLSElement().getPosition();
- int lineStart= getLineStart(cu.getBuffer(), position.getOffset());
- int lineEnd= getLineEnd(cu.getBuffer(), position.getOffset());
- String cuLine= cu.getBuffer().getText(lineStart, lineEnd - lineStart);
- StringBuffer buf= new StringBuffer(cuLine);
- buf.replace(region.getOffset() - lineStart, region.getOffset() + region.getLength() - lineStart, replaceString);
- try {
- NLSLine[] allLines= NLSScanner.scan(buf.toString());
-
- NLSLine nlsLine= allLines[0];
- NLSElement element= findElement(nlsLine, position.getOffset() - lineStart - accessorClassRef.getName().length() - 1);
- if (element == null || element.hasTag())
- return;
-
- NLSElement[] elements= nlsLine.getElements();
- int indexInElementList= Arrays.asList(elements).indexOf(element);
- String editText= ' ' + NLSElement.createTagText(indexInElementList + 1); //tags are 1-based
- TextChangeCompatibility.addTextEdit(change, label, new InsertEdit(lineEnd, editText));
-
- } catch (InvalidInputException e) {
-
- }
- }
- }
- }
-
- private int getLineEnd(IBuffer buffer, int offset) {
- int pos= offset;
- int length= buffer.getLength();
- while (pos < length && !isDelemiter(buffer.getChar(pos))) {
- pos++;
- }
- return pos;
- }
-
- private int getLineStart(IBuffer buffer, int offset) {
- int pos= offset;
- while (pos >= 0 && !isDelemiter(buffer.getChar(pos))) {
- pos--;
- }
- return pos + 1;
- }
-
- private boolean isDelemiter(char ch) {
- String[] delem= TextUtilities.DELIMITERS;
- for (int i= 0; i < delem.length; i++) {
- if (delem[i].length() == 1 && ch == delem[i].charAt(0))
- return true;
- }
- return false;
- }
-
- private static boolean isPositionInElement(NLSElement element, int position) {
- Region elementPosition= element.getPosition();
- return (elementPosition.getOffset() <= position && position <= elementPosition.getOffset() + elementPosition.getLength());
- }
-
- private static NLSElement findElement(NLSLine line, int position) {
- NLSElement[] elements= line.getElements();
- for (int i= 0; i < elements.length; i++) {
- NLSElement element= elements[i];
- if (isPositionInElement(element, position))
- return element;
- }
- return null;
- }
-
- // TODO: not dry
- private String unwindEscapeChars(String s) {
- StringBuffer sb= new StringBuffer(s.length());
- int length= s.length();
- for (int i= 0; i < length; i++) {
- char c= s.charAt(i);
- sb.append(getUnwoundString(c));
- }
- return sb.toString();
- }
-
- private String getUnwoundString(char c) {
- switch (c) {
- case '\b' :
- return "\\b";//$NON-NLS-1$
- case '\t' :
- return "\\t";//$NON-NLS-1$
- case '\n' :
- return "\\n";//$NON-NLS-1$
- case '\f' :
- return "\\f";//$NON-NLS-1$
- case '\r' :
- return "\\r";//$NON-NLS-1$
- case '\\' :
- return "\\\\";//$NON-NLS-1$
- }
- return String.valueOf(c);
- }
-
- private void deleteTag(NLSSubstitution substitution, TextChange change) {
- Region textRegion= substitution.getNLSElement().getTagPosition();
-
- TextChangeCompatibility.addTextEdit(change, NLSMessages.NLSSourceModifier_remove_tag,
- new DeleteEdit(textRegion.getOffset(), textRegion.getLength()));
- }
-
- private String createImportForAccessor(MultiTextEdit parent, String accessorClassName, IPackageFragment accessorPackage, IJavaScriptUnit cu) throws CoreException {
- IType type= accessorPackage.getJavaScriptUnit(accessorClassName + JavaModelUtil.DEFAULT_CU_SUFFIX).getType(accessorClassName);
- String fullyQualifiedName= type.getFullyQualifiedName();
-
- ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true);
- String nameToUse= importRewrite.addImport(fullyQualifiedName);
- TextEdit edit= importRewrite.rewriteImports(null);
- parent.addChild(edit);
-
- return nameToUse;
- }
-
- private void addNLS(NLSSubstitution sub, TextChange change, String accessorName) {
- if (sub.getState() == NLSSubstitution.INTERNALIZED)
- return;
-
- NLSElement element= sub.getNLSElement();
-
- addAccessor(sub, change, accessorName);
-
- if (!fIsEclipseNLS || sub.getState() == NLSSubstitution.IGNORED) {
- // Add $NON-NLS-n tag
- String arg= sub.getState() == NLSSubstitution.EXTERNALIZED ? sub.getKey() : sub.getValueNonEmpty();
- String name= Messages.format(NLSMessages.NLSSourceModifier_add_tag, arg);
- TextChangeCompatibility.addTextEdit(change, name, createAddTagChange(element));
- }
- }
-
- private void addAccessor(NLSSubstitution sub, TextChange change, String accessorName) {
- if (sub.getState() == NLSSubstitution.EXTERNALIZED) {
- NLSElement element= sub.getNLSElement();
- Region position= element.getPosition();
- String[] args= {sub.getValueNonEmpty(), sub.getKey()};
- String text= Messages.format(NLSMessages.NLSSourceModifier_externalize, args);
-
- String resourceGetter= createResourceGetter(sub.getKey(), accessorName);
-
- TextEdit edit= new ReplaceEdit(position.getOffset(), position.getLength(), resourceGetter);
- if (fIsEclipseNLS && element.getTagPosition() != null) {
- MultiTextEdit multiEdit= new MultiTextEdit();
- multiEdit.addChild(edit);
- Region tagPosition= element.getTagPosition();
- multiEdit.addChild(new DeleteEdit(tagPosition.getOffset(), tagPosition.getLength()));
- edit= multiEdit;
- }
- TextChangeCompatibility.addTextEdit(change, text, edit);
- }
- }
-
- private TextEdit createAddTagChange(NLSElement element) {
- int offset= element.getTagPosition().getOffset(); //to be changed
- String text= ' ' + element.getTagText();
- return new InsertEdit(offset, text);
- }
-
- private String createResourceGetter(String key, String accessorName) {
- StringBuffer buf= new StringBuffer();
- buf.append(accessorName);
- buf.append('.');
-
- if (fIsEclipseNLS)
- buf.append(key);
- else {
- //we just replace the first occurrence of KEY in the pattern
- int i= fSubstitutionPattern.indexOf(NLSRefactoring.KEY);
- if (i != -1) {
- buf.append(fSubstitutionPattern.substring(0, i));
- buf.append('"').append(key).append('"');
- buf.append(fSubstitutionPattern.substring(i + NLSRefactoring.KEY.length()));
- }
- }
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java
deleted file mode 100644
index b8b630b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.Properties;
-
-import org.eclipse.core.runtime.Assert;
-
-
-public class NLSSubstitution {
- public static final int EXTERNALIZED= 0;
- public static final int IGNORED= 1;
- public static final int INTERNALIZED= 2;
-
- public static final int DEFAULT= EXTERNALIZED;
- public static final int STATE_COUNT= 3;
-
- private int fState;
- private String fKey;
- /**
- *
- */
- private String fCachedPrefixPlusKey;
- private String fValue;
-
- private int fInitialState;
- private String fInitialKey;
- private String fInitialValue;
-
- private NLSElement fNLSElement;
- private AccessorClassReference fAccessorClassReference;
-
- private String fNewAccessorClassName;
-
- private String fPrefix= ""; //$NON-NLS-1$
-
-
- public NLSSubstitution(int state, String value, NLSElement element) {
- fNLSElement= element;
- fValue= value;
- fState= state;
- fInitialState= state;
- fInitialValue= value;
- fCachedPrefixPlusKey= null;
- Assert.isTrue(state == EXTERNALIZED || state == IGNORED || state == INTERNALIZED);
- }
-
- /**
- * value == null indicates a corrupt substitution.
- */
- public NLSSubstitution(int state, String key, String value, NLSElement element, AccessorClassReference accessorClassReference) {
- this(state,value,element);
- if (state != EXTERNALIZED) {
- throw new IllegalArgumentException("Set to INTERNALIZE/IGNORED State with different Constructor"); //$NON-NLS-1$
- }
- fKey= key;
- fInitialKey= key;
- fAccessorClassReference= accessorClassReference;
- fNewAccessorClassName= null;
- }
-
- //util
- public static int countItems(NLSSubstitution[] elems, int task) {
- Assert.isTrue(task == NLSSubstitution.EXTERNALIZED || task == NLSSubstitution.IGNORED || task == NLSSubstitution.INTERNALIZED);
- int result= 0;
- for (int i= 0; i < elems.length; i++) {
- if (elems[i].fState == task) {
- result++;
- }
- }
- return result;
- }
-
- public NLSElement getNLSElement() {
- return fNLSElement;
- }
-
- public String getKeyWithoutPrefix() {
- return fKey;
- }
-
- /**
- * Returns key dependent on state.
- * @return prefix + key when
- */
- public String getKey() {
- if ((fState == EXTERNALIZED) && hasStateChanged()) {
- if (fCachedPrefixPlusKey == null) {
- int length= 0;
- if (fPrefix != null)
- length= length + fPrefix.length();
- if (fKey != null)
- length= length + fKey.length();
- StringBuffer sb= new StringBuffer(length);
- sb.append(fPrefix);
- sb.append(fKey);
- fCachedPrefixPlusKey= sb.toString();
- }
- return fCachedPrefixPlusKey;
- }
- return fKey;
- }
-
- public void setKey(String key) {
- if (fState != EXTERNALIZED) {
- throw new IllegalStateException("Must be in Externalized State !"); //$NON-NLS-1$
- }
- fCachedPrefixPlusKey= null;
- fKey= key;
- }
-
- public void setValue(String value) {
- fValue= value;
- }
-
- public void setInitialValue(String value) {
- fInitialValue= value;
- }
-
- /**
- * Value can be null.
- */
- public String getValue() {
- return fValue;
- }
-
- public String getValueNonEmpty() {
- if (fValue == null) {
- return ""; //$NON-NLS-1$
- }
- return fValue;
- }
-
- public int getState() {
- return fState;
- }
-
- public void setState(int state) {
- fCachedPrefixPlusKey= null;
- fState= state;
- }
-
- public void setUpdatedAccessor(String accessorClassName) {
- fNewAccessorClassName= accessorClassName;
- }
-
- public String getUpdatedAccessor() {
- return fNewAccessorClassName;
- }
-
- public boolean hasStateChanged() {
- return fState != fInitialState;
- }
-
- public boolean isKeyRename() {
- return (fInitialKey != null && !fInitialKey.equals(fKey));
- }
-
- public boolean isValueRename() {
- return (fInitialValue != null && !fInitialValue.equals(fValue));
- }
-
- public boolean isAccessorRename() {
- return (fAccessorClassReference != null) && (fNewAccessorClassName != null) && !fNewAccessorClassName.equals(fAccessorClassReference.getName());
- }
-
-
- public boolean hasPropertyFileChange() {
- if (fInitialState != EXTERNALIZED && fState != EXTERNALIZED) {
- return false;
- }
- if (fInitialState != fState) {
- return true;
- }
- if (fState == EXTERNALIZED) {
- if (fInitialValue == null) {
- return true; // recreate entry in property file
- } else if (!fInitialValue.equals(fValue)) {
- return true; // change of value
- }
- if (!fInitialKey.equals(fKey)) {
- return true; // change of key
- }
- }
- return false;
- }
-
- public boolean hasAccessorClassChange() {
- if (fInitialState != EXTERNALIZED && fState != EXTERNALIZED) {
- return false;
- }
- if (fInitialState != fState) {
- return true;
- }
- if (fState == EXTERNALIZED) {
- if (fInitialValue == null) {
- return true; // recreate entry in property file
- } else if (!fInitialValue.equals(fValue)) {
- return false; // change of value
- }
- if (!fInitialKey.equals(fKey)) {
- return true; // change of key
- }
- }
- return false;
- }
-
- public boolean hasSourceChange() {
- if (hasStateChanged()) {
- return true;
- }
- if (fState == EXTERNALIZED) {
- if (!fInitialKey.equals(fKey)) {
- return true; // change of key
- }
- if (isAccessorRename()) {
- return true;
- }
- } else {
- if (!fInitialValue.equals(fValue)) {
- return true; // change of value
- }
- }
- return false;
- }
-
- public int getInitialState() {
- return fInitialState;
- }
-
- public String getInitialKey() {
- return fInitialKey;
- }
-
- public String getInitialValue() {
- return fInitialValue;
- }
-
- public AccessorClassReference getAccessorClassReference() {
- return fAccessorClassReference;
- }
-
- /**
- * Sets the prefix.
- */
- public void setPrefix(String prefix) {
- fPrefix= prefix;
- fCachedPrefixPlusKey= null;
- }
-
- public boolean isConflicting(NLSSubstitution[] substitutions) {
- if (fState == EXTERNALIZED) {
- String currKey= getKey();
- String currValue= getValueNonEmpty();
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (substitution != this && substitution.getState() == EXTERNALIZED) {
- // same key but different value
- if (currKey.equals(substitution.getKey()) && !currValue.equals(substitution.getValueNonEmpty())) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- private String internalGetKeyWithoutPrefix() {
- if (fState == EXTERNALIZED && fPrefix != null && fKey != null && fKey.indexOf(fPrefix) == 0)
- return fKey.substring(fPrefix.length());
- return fKey;
- }
-
- public void generateKey(NLSSubstitution[] substitutions) {
- if (fState != EXTERNALIZED || ((fState == EXTERNALIZED) && hasStateChanged())) {
- int min= Integer.MAX_VALUE;
- int max= Integer.MIN_VALUE;
-
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (substitution == this || substitution.fState != EXTERNALIZED)
- continue;
- try {
- int value= Integer.parseInt(substitution.internalGetKeyWithoutPrefix());
- min= Math.min(min, value);
- max= Math.max(max, value);
- } catch (NumberFormatException ex) {
-
- }
- }
-
- fCachedPrefixPlusKey= null;
- if (min == Integer.MAX_VALUE)
- fKey= createKey(0);
- else if (min > 0)
- fKey= createKey(min-1);
- else
- fKey= createKey(max + 1);
- }
- }
-
- public static void updateSubtitutions(NLSSubstitution[] substitutions, Properties props, String accessorClassName) {
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && !substitution.hasStateChanged()) {
- substitution.setInitialValue(props.getProperty(substitution.getKey()));
- substitution.setUpdatedAccessor(accessorClassName);
- }
- }
- }
-
- public void revert() {
- fState= fInitialState;
- fKey= fInitialKey;
- fCachedPrefixPlusKey= null;
- fValue= fInitialValue;
- }
-
- private String createKey(int counter) {
- return String.valueOf(counter);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSUtil.java
deleted file mode 100644
index e039fce1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSUtil.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.Region;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-
-
-public class NLSUtil {
-
- //no instances
- private NLSUtil() {
- }
-
- /**
- * Returns null if an error occurred.
- * closes the stream
- */
- public 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) {
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException ex) {
- }
- }
- }
- return null;
- }
-
- /**
- * Creates and returns an NLS tag edit for a string that is at the specified position in
- * a compilation unit. Returns <code>null</code> if the string is already NLSed
- * or the edit could not be created for some other reason.
- * @throws CoreException
- */
- public static TextEdit createNLSEdit(IJavaScriptUnit cu, int position) throws CoreException {
- NLSLine nlsLine= scanCurrentLine(cu, position);
- if (nlsLine == null)
- return null;
- NLSElement element= findElement(nlsLine, position);
- if (element.hasTag())
- return null;
- NLSElement[] elements= nlsLine.getElements();
- int indexInElementList= Arrays.asList(elements).indexOf(element);
- int editOffset= computeInsertOffset(elements, indexInElementList, cu);
- String editText= ' ' + NLSElement.createTagText(indexInElementList + 1); //tags are 1-based
- return new InsertEdit(editOffset, editText);
- }
-
- /**
- * Creates and returns NLS tag edits for strings that are at the specified positions in
- * a compilation unit. Returns <code>null</code> if all the strings are already NLSed
- * or the edits could not be created for some other reason.
- * @throws CoreException
- */
- public static TextEdit[] createNLSEdits(IJavaScriptUnit cu, int[] positions) throws CoreException {
- List result= new ArrayList();
- try {
- NLSLine[] allLines= NLSScanner.scan(cu);
- for (int i= 0; i < allLines.length; i++) {
- NLSLine line= allLines[i];
- NLSElement[] elements= line.getElements();
- for (int j= 0; j < elements.length; j++) {
- NLSElement element= elements[j];
- if (!element.hasTag()) {
- for (int k= 0; k < positions.length; k++) {
- if (isPositionInElement(element, positions[k])) {
- int editOffset;
- if (j==0) {
- if (elements.length > j+1) {
- editOffset= elements[j+1].getTagPosition().getOffset();
- } else {
- editOffset= findLineEnd(cu, element.getPosition().getOffset());
- }
- } else {
- Region previousPosition= elements[j-1].getTagPosition();
- editOffset= previousPosition.getOffset() + previousPosition.getLength();
- }
- String editText= ' ' + NLSElement.createTagText(j + 1); //tags are 1-based
- result.add(new InsertEdit(editOffset, editText));
- }
- }
- }
- }
- }
- } catch (InvalidInputException e) {
- return null;
- }
- if (result.isEmpty())
- return null;
-
- return (TextEdit[])result.toArray(new TextEdit[result.size()]);
- }
-
- private static NLSLine scanCurrentLine(IJavaScriptUnit cu, int position) throws JavaScriptModelException {
- try {
- Assert.isTrue(position >= 0 && position <= cu.getBuffer().getLength());
- NLSLine[] allLines= NLSScanner.scan(cu);
- for (int i= 0; i < allLines.length; i++) {
- NLSLine line= allLines[i];
- if (findElement(line, position) != null)
- return line;
- }
- return null;
- } catch (InvalidInputException e) {
- return null;
- }
- }
-
- private static boolean isPositionInElement(NLSElement element, int position) {
- Region elementPosition= element.getPosition();
- return (elementPosition.getOffset() <= position && position <= elementPosition.getOffset() + elementPosition.getLength());
- }
-
- private static NLSElement findElement(NLSLine line, int position) {
- NLSElement[] elements= line.getElements();
- for (int i= 0; i < elements.length; i++) {
- NLSElement element= elements[i];
- if (isPositionInElement(element, position))
- return element;
- }
- return null;
- }
-
- //we try to find a good place to put the nls tag
- //first, try to find the previous nlsed-string and try putting after its tag
- //if no such string exists, try finding the next nlsed-string try putting before its tag
- //otherwise, find the line end and put the tag there
- private static int computeInsertOffset(NLSElement[] elements, int index, IJavaScriptUnit cu) throws CoreException {
- NLSElement previousTagged= findPreviousTagged(index, elements);
- if (previousTagged != null)
- return previousTagged.getTagPosition().getOffset() + previousTagged.getTagPosition().getLength();
- NLSElement nextTagged= findNextTagged(index, elements);
- if (nextTagged != null)
- return nextTagged.getTagPosition().getOffset();
- return findLineEnd(cu, elements[index].getPosition().getOffset());
- }
-
- private static NLSElement findPreviousTagged(int startIndex, NLSElement[] elements) {
- int i= startIndex - 1;
- while (i >= 0) {
- if (elements[i].hasTag())
- return elements[i];
- i--;
- }
- return null;
- }
-
- private static NLSElement findNextTagged(int startIndex, NLSElement[] elements) {
- int i= startIndex + 1;
- while (i < elements.length) {
- if (elements[i].hasTag())
- return elements[i];
- i++;
- }
- return null;
- }
-
- private static int findLineEnd(IJavaScriptUnit cu, int position) throws JavaScriptModelException {
- IBuffer buffer= cu.getBuffer();
- int length= buffer.getLength();
- for (int i= position; i < length; i++) {
- if (IndentManipulation.isLineDelimiterChar(buffer.getChar(i))) {
- return i;
- }
- }
- return length;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/PropertyFileDocumentModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/PropertyFileDocumentModel.java
deleted file mode 100644
index c783eb26..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/PropertyFileDocumentModel.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-
-public class PropertyFileDocumentModel {
-
- private static final char[] HEX_DIGITS = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
- private List fKeyValuePairs;
- private String fLineDelimiter;
-
- public PropertyFileDocumentModel(IDocument document) {
- parsePropertyDocument(document);
- fLineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
- }
-
- public int getIndex(String key) {
- for (int i= 0; i < fKeyValuePairs.size(); i++) {
- KeyValuePairModell keyValuePair = (KeyValuePairModell) fKeyValuePairs.get(i);
- if (keyValuePair.getKey().equals(key)) {
- return i;
- }
- }
- return -1;
- }
-
-
- public InsertEdit insert(String key, String value) {
- return insert(new KeyValuePair(key, value));
- }
-
- public InsertEdit insert(KeyValuePair keyValuePair) {
- KeyValuePairModell keyValuePairModell = new KeyValuePairModell(keyValuePair);
- int index = findInsertPosition(keyValuePairModell);
- KeyValuePairModell insertHere = (KeyValuePairModell) fKeyValuePairs.get(index);
- int offset = insertHere.fOffset - insertHere.fLeadingWhiteSpaces;
-
- String extra= ""; //$NON-NLS-1$
- if (insertHere instanceof LastKeyValuePair && ((LastKeyValuePair)insertHere).needsNewLine()) {
- extra= fLineDelimiter;
- ((LastKeyValuePair)insertHere).resetNeedsNewLine();
- }
- return new InsertEdit(offset, extra + keyValuePairModell.getEncodedText(fLineDelimiter));
- }
-
- public InsertEdit[] insert(KeyValuePair[] keyValuePairs) {
- InsertEdit[] inserts = new InsertEdit[keyValuePairs.length];
- for (int i = 0; i < keyValuePairs.length; i++) {
- inserts[i] = insert(keyValuePairs[i]);
- }
- return inserts;
- }
-
- public DeleteEdit remove(String key) {
- for (Iterator iter = fKeyValuePairs.iterator(); iter.hasNext();) {
- KeyValuePairModell keyValuePair = (KeyValuePairModell) iter.next();
- if (keyValuePair.fKey.equals(key)) {
- KeyValuePairModell next = (KeyValuePairModell) iter.next();
- return new DeleteEdit(keyValuePair.fOffset, next.fOffset - keyValuePair.fOffset);
- }
- }
- return null;
- }
-
- public ReplaceEdit replace(KeyValuePair toReplace, KeyValuePair replaceWith) {
- for (Iterator iter = fKeyValuePairs.iterator(); iter.hasNext();) {
- KeyValuePairModell keyValuePair = (KeyValuePairModell) iter.next();
- if (keyValuePair.fKey.equals(toReplace.getKey())) {
- String newText = new KeyValuePairModell(replaceWith).getEncodedText(fLineDelimiter);
- KeyValuePairModell next = (KeyValuePairModell) iter.next();
- int range = next.fOffset - keyValuePair.fOffset;
- return new ReplaceEdit(keyValuePair.fOffset, range, newText);
- }
- }
- return null;
- }
-
- private int findInsertPosition(KeyValuePairModell keyValuePair) {
- int insertIndex = 0;
- int maxMatch = Integer.MIN_VALUE;
- for (int i=0; i<fKeyValuePairs.size(); i++) {
- KeyValuePairModell element = (KeyValuePairModell) fKeyValuePairs.get(i);
- int match = element.compareTo(keyValuePair);
- if (match >= maxMatch) {
- insertIndex = i;
- maxMatch = match;
- }
- }
-
- if (insertIndex < fKeyValuePairs.size() - 1) {
- insertIndex++;
- }
-
- return insertIndex;
- }
-
- private void parsePropertyDocument(IDocument document) {
- fKeyValuePairs = new ArrayList();
-
- SimpleLineReader reader = new SimpleLineReader(document);
- int offset = 0;
- String line = reader.readLine();
- int leadingWhiteSpaces = 0;
- while (line != null) {
- if (!SimpleLineReader.isCommentOrWhiteSpace(line)) {
- int idx = getIndexOfSeparationCharacter(line);
- if (idx != -1) {
- String key= line.substring(0, idx);
- String value= line.substring(idx + 1);
- fKeyValuePairs.add(new KeyValuePairModell(key, value, offset, leadingWhiteSpaces));
- leadingWhiteSpaces = 0;
- }
- } else {
- leadingWhiteSpaces += line.length();
- }
- offset += line.length();
- line = reader.readLine();
- }
- int lastLine= document.getNumberOfLines() - 1;
- boolean needsNewLine= false;
- try {
- needsNewLine= !(document.getLineLength(lastLine) == 0);
- } catch (BadLocationException ignore) {
- // treat last line having no new line
- }
- LastKeyValuePair lastKeyValuePair = new LastKeyValuePair(offset, needsNewLine);
- fKeyValuePairs.add(lastKeyValuePair);
- }
-
- private int getIndexOfSeparationCharacter(String line) {
- int minIndex = -1;
- int indexOfEven = line.indexOf('=');
- int indexOfColumn = line.indexOf(':');
- int indexOfBlank = line.indexOf(' ');
-
- if ((indexOfEven != -1) && (indexOfColumn != -1)) {
- minIndex = Math.min(indexOfEven, indexOfColumn);
- } else {
- minIndex = Math.max(indexOfEven, indexOfColumn);
- }
-
- if ((minIndex != -1) && (indexOfBlank != -1)) {
- minIndex = Math.min(minIndex, indexOfBlank);
- } else {
- minIndex = Math.max(minIndex, indexOfBlank);
- }
-
- return minIndex;
- }
-
- public static String unwindEscapeChars(String s){
- StringBuffer sb= new StringBuffer(s.length());
- int length= s.length();
- for (int i= 0; i < length; i++){
- char c= s.charAt(i);
- sb.append(getUnwoundString(c));
- }
- return sb.toString();
- }
-
- public static String unwindValue(String value) {
- return escapeLeadingWhiteSpaces(escapeCommentChars(unwindEscapeChars(value)));
- }
-
- private static String getUnwoundString(char c){
- switch(c){
- case '\b' :
- return "\\b";//$NON-NLS-1$
- case '\t' :
- return "\\t";//$NON-NLS-1$
- case '\n' :
- return "\\n";//$NON-NLS-1$
- case '\f' :
- return "\\f";//$NON-NLS-1$
- case '\r' :
- return "\\r";//$NON-NLS-1$
-
-// These can be used unescaped in properties file:
-// case '\"' :
-// return "\\\"";//$NON-NLS-1$
-// case '\'' :
-// return "\\\'";//$NON-NLS-1$
-
- case '\\' :
- return "\\\\";//$NON-NLS-1$
-
-// This is only done when writing to the .properties file in #unwindValue(String)
-// case '!':
-// return "\\!";//$NON-NLS-1$
-// case '#':
-// return "\\#";//$NON-NLS-1$
-
- default:
- if (((c < 0x0020) || (c > 0x007e))){
- return new StringBuffer()
- .append('\\')
- .append('u')
- .append(toHex((c >> 12) & 0xF))
- .append(toHex((c >> 8) & 0xF))
- .append(toHex((c >> 4) & 0xF))
- .append(toHex( c & 0xF)).toString();
-
- } else
- return String.valueOf(c);
- }
- }
-
- private static char toHex(int halfByte) {
- return HEX_DIGITS[(halfByte & 0xF)];
- }
-
- private static String escapeCommentChars(String string) {
- StringBuffer sb = new StringBuffer(string.length() + 5);
- for (int i = 0; i < string.length(); i++) {
- char c = string.charAt(i);
- switch (c) {
- case '!':
- sb.append("\\!"); //$NON-NLS-1$
- break;
- case '#':
- sb.append("\\#"); //$NON-NLS-1$
- break;
- default:
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
- private static String escapeLeadingWhiteSpaces(String str) {
- int firstNonWhiteSpace= findFirstNonWhiteSpace(str);
- StringBuffer buf= new StringBuffer(firstNonWhiteSpace);
- for (int i = 0; i < firstNonWhiteSpace; i++) {
- buf.append('\\');
- buf.append(str.charAt(i));
- }
- buf.append(str.substring(firstNonWhiteSpace));
- return buf.toString();
- }
-
- /**
- * returns the length if only whitespaces
- */
- private static int findFirstNonWhiteSpace(String s) {
- for (int i = 0; i < s.length(); i++) {
- if (!Character.isWhitespace(s.charAt(i)))
- return i;
- }
- return s.length();
- }
-
- private static class KeyValuePairModell extends KeyValuePair implements Comparable {
-
- int fOffset;
- int fLeadingWhiteSpaces;
-
- public KeyValuePairModell(String key, String value, int offset, int leadingWhiteSpaces) {
- super(key, value);
- fOffset = offset;
- fLeadingWhiteSpaces = leadingWhiteSpaces;
- }
-
- public KeyValuePairModell(KeyValuePair keyValuePair) {
- super(keyValuePair.fKey, keyValuePair.fValue);
- }
-
- public String getEncodedText(String lineDelimiter) {
- return PropertyFileDocumentModel.unwindEscapeChars(fKey) + '=' + PropertyFileDocumentModel.unwindValue(fValue) + lineDelimiter;
- }
-
- public int compareTo(Object o) {
- int counter = 0;
- String key = ((KeyValuePair) o).fKey;
- int minLen = Math.min(key.length(), fKey.length());
- int diffLen = Math.abs(key.length() - fKey.length());
- for (int i=0; i<minLen; i++) {
- if (key.charAt(i) == fKey.charAt(i)) {
- counter++;
- } else {
- break;
- }
- }
- return counter - diffLen;
- }
- }
-
- /**
- * anchor element for a list of KeyValuePairs. (it is greater than every
- * other KeyValuePair)
- */
- private static class LastKeyValuePair extends KeyValuePairModell {
-
- private boolean fNeedsNewLine;
-
- public LastKeyValuePair(int offset, boolean needsNewLine) {
- super("last", "key", offset, 0); //$NON-NLS-1$ //$NON-NLS-2$
- fNeedsNewLine= needsNewLine;
- }
- public int compareTo(Object o) {
- return 1;
- }
- public boolean needsNewLine() {
- return fNeedsNewLine;
- }
- public void resetNeedsNewLine() {
- fNeedsNewLine= false;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/SimpleLineReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/SimpleLineReader.java
deleted file mode 100644
index 40fce7ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/SimpleLineReader.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Simple LineReader Helper. Returns lines including "line-break" characters.
- */
-public class SimpleLineReader {
-
- private IDocument fInput;
- private int fCurrLine;
-
- public SimpleLineReader(IDocument input) {
- fInput = input;
- fCurrLine= 0;
- }
-
- public String readLine() {
- int nLines= fInput.getNumberOfLines();
- if (fCurrLine >= nLines) {
- return null;
- }
-
- try {
- IRegion region= fInput.getLineInformation(fCurrLine++);
- String content= fInput.get(region.getOffset(), region.getLength());
-
- int start= region.getOffset();
-
- boolean continuesOnNext= content.endsWith("\\") && !isCommentOrWhiteSpace(content); //$NON-NLS-1$
-
- while (continuesOnNext && fCurrLine < nLines) {
- region= fInput.getLineInformation(fCurrLine++);
- content= fInput.get(region.getOffset(), region.getLength());
- continuesOnNext= content.endsWith("\\") && !isCommentOrWhiteSpace(content); //$NON-NLS-1$
- }
- int end;
- if (fCurrLine < nLines) {
- end= fInput.getLineOffset(fCurrLine); // beginning of next
- } else {
- end= fInput.getLength();
- if (end == start) {
- return null; // nd of file, empty line -> null
- }
- }
- return fInput.get(start, end - start);
- } catch (BadLocationException e) {
- // should not happen
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- public static boolean isCommentOrWhiteSpace(String line) {
- line = line.trim();
- return (line.length() == 0) || line.charAt(0) == '!' || line.charAt(0) == '#';
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateFileChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateFileChange.java
deleted file mode 100644
index 49a95d2b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateFileChange.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileInfo;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class CreateFileChange extends JDTChange {
-
- private String fChangeName;
-
- private IPath fPath;
- private String fSource;
- private String fEncoding;
- private boolean fExplicitEncoding;
- private long fStampToRestore;
-
- public CreateFileChange(IPath path, String source, String encoding) {
- this(path, source, encoding, IResource.NULL_STAMP);
- }
-
- public CreateFileChange(IPath path, String source, String encoding, long stampToRestore) {
- Assert.isNotNull(path, "path"); //$NON-NLS-1$
- Assert.isNotNull(source, "source"); //$NON-NLS-1$
- fPath= path;
- fSource= source;
- fEncoding= encoding;
- fExplicitEncoding= fEncoding != null;
- fStampToRestore= stampToRestore;
- }
-
- /*
- private CreateFileChange(IPath path, String source, String encoding, long stampToRestore, boolean explicit) {
- Assert.isNotNull(path, "path"); //$NON-NLS-1$
- Assert.isNotNull(source, "source"); //$NON-NLS-1$
- Assert.isNotNull(encoding, "encoding"); //$NON-NLS-1$
- fPath= path;
- fSource= source;
- fEncoding= encoding;
- fStampToRestore= stampToRestore;
- fExplicitEncoding= explicit;
- }
- */
-
- protected void setEncoding(String encoding, boolean explicit) {
- Assert.isNotNull(encoding, "encoding"); //$NON-NLS-1$
- fEncoding= encoding;
- fExplicitEncoding= explicit;
- }
-
- public String getName() {
- if (fChangeName == null)
- return Messages.format(NLSChangesMessages.createFile_Create_file, fPath.toOSString());
- else
- return fChangeName;
- }
-
- public void setName(String name) {
- fChangeName= name;
- }
-
- protected void setSource(String source) {
- fSource= source;
- }
-
- protected String getSource() {
- return fSource;
- }
-
- protected void setPath(IPath path) {
- fPath= path;
- }
-
- protected IPath getPath() {
- return fPath;
- }
-
- public Object getModifiedElement() {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
-
- URI location= file.getLocationURI();
- if (location == null) {
- result.addFatalError(Messages.format(
- NLSChangesMessages.CreateFileChange_error_unknownLocation,
- file.getFullPath().toString()));
- return result;
- }
-
- IFileInfo jFile= EFS.getStore(location).fetchInfo();
- if (jFile.exists()) {
- result.addFatalError(Messages.format(
- NLSChangesMessages.CreateFileChange_error_exists,
- file.getFullPath().toString()));
- return result;
- }
- return result;
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
-
- InputStream is= null;
- try {
- pm.beginTask(NLSChangesMessages.createFile_creating_resource, 3);
-
- initializeEncoding();
- IFile file= getOldFile(new SubProgressMonitor(pm, 1));
- /*
- if (file.exists()) {
- CompositeChange composite= new CompositeChange(getName());
- composite.add(new DeleteFileChange(file));
- composite.add(new CreateFileChange(fPath, fSource, fEncoding, fStampToRestore, fExplicitEncoding));
- pm.worked(1);
- return composite.perform(new SubProgressMonitor(pm, 1));
- } else { */
- try {
- is= new ByteArrayInputStream(fSource.getBytes(fEncoding));
- file.create(is, false, new SubProgressMonitor(pm, 1));
- if (fStampToRestore != IResource.NULL_STAMP) {
- file.revertModificationStamp(fStampToRestore);
- }
- if (fExplicitEncoding) {
- file.setCharset(fEncoding, new SubProgressMonitor(pm, 1));
- } else {
- pm.worked(1);
- }
- return new DeleteFileChange(file);
- } catch (UnsupportedEncodingException e) {
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
- } finally {
- try {
- if (is != null)
- is.close();
- } catch (IOException ioe) {
- throw new JavaScriptModelException(ioe, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- } finally {
- pm.done();
- }
- }
- }
-
- protected IFile getOldFile(IProgressMonitor pm) throws OperationCanceledException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
- } finally {
- pm.done();
- }
- }
-
- private void initializeEncoding() {
- if (fEncoding == null) {
- fExplicitEncoding= false;
- IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
- if (file != null) {
- try {
- if (file.exists()) {
- fEncoding= file.getCharset(false);
- if (fEncoding == null) {
- fEncoding= file.getCharset(true);
- } else {
- fExplicitEncoding= true;
- }
- } else {
- IContentType contentType= Platform.getContentTypeManager().findContentTypeFor(file.getName());
- if (contentType != null)
- fEncoding= contentType.getDefaultCharset();
- if (fEncoding == null)
- fEncoding= file.getCharset(true);
- }
- } catch (CoreException e) {
- fEncoding= ResourcesPlugin.getEncoding();
- fExplicitEncoding= true;
- }
- } else {
- fEncoding= ResourcesPlugin.getEncoding();
- fExplicitEncoding= true;
- }
- }
- Assert.isNotNull(fEncoding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateTextFileChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateTextFileChange.java
deleted file mode 100644
index 91a895f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/CreateTextFileChange.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSUtil;
-
-public class CreateTextFileChange extends CreateFileChange {
-
- private final String fTextType;
-
- public CreateTextFileChange(IPath path, String source, String encoding, String textType) {
- super(path, source, encoding);
- fTextType= textType;
- }
-
- public String getTextType() {
- return fTextType;
- }
-
- public String getCurrentContent() throws JavaScriptModelException {
- IFile file= getOldFile(new NullProgressMonitor());
- if (! file.exists())
- return ""; //$NON-NLS-1$
- InputStream stream= null;
- try{
- stream= file.getContents();
- String encoding= file.getCharset();
- String c= NLSUtil.readString(stream, encoding);
- return (c == null) ? "": c; //$NON-NLS-1$
- } catch (CoreException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.CORE_EXCEPTION);
- } finally {
- try {
- if (stream != null)
- stream.close();
- } catch (IOException x) {
- }
- }
- }
-
- public String getPreview() {
- return getSource();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/DeleteFileChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/DeleteFileChange.java
deleted file mode 100644
index bd04185e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/DeleteFileChange.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.util.IOCloser;
-
-public class DeleteFileChange extends JDTChange {
-
- private IPath fPath;
- private String fSource;
-
- public DeleteFileChange(IFile file){
- Assert.isNotNull(file, "file"); //$NON-NLS-1$
- fPath= file.getFullPath().removeFirstSegments(ResourcesPlugin.getWorkspace().getRoot().getFullPath().segmentCount());
- }
-
- public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
- return isValid(pm, READ_ONLY | DIRTY);
- }
-
- public Change perform(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(NLSChangesMessages.deleteFile_deleting_resource, 1);
- IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
- Assert.isNotNull(file);
- Assert.isTrue(file.exists());
- Assert.isTrue(!file.isReadOnly());
- fSource= getSource(file);
- CreateFileChange undo= createUndoChange(file, fPath, file.getModificationStamp(), fSource);
- file.delete(true, true, pm);
- return undo;
- } finally {
- pm.done();
- }
- }
-
- private String getSource(IFile file) throws CoreException {
- String encoding= null;
- try {
- encoding= file.getCharset();
- } catch (CoreException ex) {
- // fall through. Take default encoding.
- }
-
- StringBuffer sb= new StringBuffer();
- BufferedReader br= null;
- InputStream in= null;
- try {
- in= file.getContents();
- if (encoding != null)
- br= new BufferedReader(new InputStreamReader(in, encoding));
- else
- br= new BufferedReader(new InputStreamReader(in));
- int read= 0;
- while ((read= br.read()) != -1)
- sb.append((char) read);
- } catch (IOException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- } finally {
- try{
- IOCloser.rethrows(br, in);
- } catch (IOException e){
- throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION);
- }
- }
- return sb.toString();
- }
-
- private static CreateFileChange createUndoChange(IFile file, IPath path, long stampToRestore, String source) {
- String encoding;
- try {
- encoding= file.getCharset(false);
- } catch (CoreException e) {
- encoding= null;
- }
- return new CreateFileChange(path, source, encoding, stampToRestore);
- }
-
- public String getName() {
- return NLSChangesMessages.deleteFile_Delete_File;
- }
-
- public Object getModifiedElement() {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.java
deleted file mode 100644
index b0ec25aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class NLSChangesMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.NLSChangesMessages";//$NON-NLS-1$
-
- private NLSChangesMessages() {
- // Do not instantiate
- }
-
- public static String createFile_creating_resource;
- public static String createFile_Create_file;
- public static String deleteFile_deleting_resource;
- public static String deleteFile_Delete_File;
-
- public static String CreateFileChange_error_exists;
- public static String CreateFileChange_error_unknownLocation;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, NLSChangesMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties
deleted file mode 100644
index 3848d089..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-createFile_creating_resource=Creating file...
-createFile_Create_file=Create file {0}
-deleteFile_deleting_resource=Deleting file...
-deleteFile_Delete_File=Delete File
-CreateFileChange_error_exists=File ''{0}'' already exists
-CreateFileChange_error_unknownLocation=The location for file ''{0}'' is unknown
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/JavaProcessors.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/JavaProcessors.java
deleted file mode 100644
index 707a7804..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/JavaProcessors.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.participants;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-
-/**
- * Utility class to deal with Java element processors.
- */
-public class JavaProcessors {
-
- public static String[] computeAffectedNatures(IJavaScriptElement element) throws CoreException {
- if (element instanceof IMember) {
- IMember member= (IMember)element;
- if (JdtFlags.isPrivate(member)) {
- return element.getJavaScriptProject().getProject().getDescription().getNatureIds();
- }
- }
- IJavaScriptProject project= element.getJavaScriptProject();
- return ResourceProcessors.computeAffectedNatures(project.getProject());
- }
-
- public static String[] computeAffectedNaturs(IJavaScriptElement[] elements) throws CoreException {
- Set result= new HashSet();
- for (int i= 0; i < elements.length; i++) {
- String[] natures= computeAffectedNatures(elements[i]);
- for (int j= 0; j < natures.length; j++) {
- result.add(natures[j]);
- }
- }
- return (String[])result.toArray(new String[result.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/RefactoringProcessors.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/RefactoringProcessors.java
deleted file mode 100644
index ca2cccec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/RefactoringProcessors.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.participants;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-
-public class RefactoringProcessors {
-
- public static String[] getNatures(IProject[] projects) throws CoreException {
- Set result= new HashSet();
- for (int i= 0; i < projects.length; i++) {
- String[] pns= projects[i].getDescription().getNatureIds();
- for (int p = 0; p < pns.length; p++) {
- result.add(pns[p]);
- }
- }
- return (String[])result.toArray(new String[result.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java
deleted file mode 100644
index edcfae60..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.participants;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CopyArguments;
-import org.eclipse.ltk.core.refactoring.participants.CopyParticipant;
-import org.eclipse.ltk.core.refactoring.participants.CreateArguments;
-import org.eclipse.ltk.core.refactoring.participants.CreateParticipant;
-import org.eclipse.ltk.core.refactoring.participants.DeleteArguments;
-import org.eclipse.ltk.core.refactoring.participants.DeleteParticipant;
-import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
-import org.eclipse.ltk.core.refactoring.participants.MoveParticipant;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameParticipant;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-
-
-/**
- * A data structure to collect resource modifications.
- *
- *
- */
-public class ResourceModifications {
-
- private List/*<IResource>*/ fCreate;
- private List/*<IResource>*/ fDelete;
-
- private List/*<IResource>*/ fMove;
- private List/*<MoveArguments>*/ fMoveArguments;
-
- private List/*<IResource>*/ fRename;
- private List/*<RenameArguments>*/ fRenameArguments;
-
- private List/*<IResource>*/ fCopy;
- private List/*<CopyArguments>*/ fCopyArguments;
-
- private int fIgnoreCount;
- private List/*<DeltaDescription>*/ fDeltaDescriptions;
-
- public static abstract class DeltaDescription {
- protected IResource fResource;
- public DeltaDescription(IResource resource) {
- fResource= resource;
- }
- public abstract void buildDelta(IResourceChangeDescriptionFactory builder);
- public abstract IPath getDestinationPath();
-
- }
- public static class DeleteDescription extends DeltaDescription {
- public DeleteDescription(IResource resource) {
- super(resource);
- }
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- builder.delete(fResource);
- }
- public IPath getDestinationPath() {
- return null;
- }
- }
- public static class ChangedDescription extends DeltaDescription {
- public ChangedDescription(IFile resource) {
- super(resource);
- }
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- builder.change((IFile)fResource);
- }
- public IPath getDestinationPath() {
- return null;
- }
- }
- public static class CreateDescription extends DeltaDescription {
- public CreateDescription(IResource resource) {
- super(resource);
- }
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- builder.create(fResource);
- }
- public IPath getDestinationPath() {
- return fResource.getFullPath();
- }
- }
- public static class MoveDescription extends DeltaDescription {
- private IPath fDestination;
- public MoveDescription(IResource resource, IPath destination) {
- super(resource);
- fDestination= destination;
- }
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- builder.move(fResource, fDestination);
- }
- public IPath getDestinationPath() {
- return fDestination;
- }
- }
- public static class CopyDescription extends DeltaDescription {
- private IPath fDestination;
- public CopyDescription(IResource resource, IPath destination) {
- super(resource);
- fDestination= destination;
- }
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- builder.copy(fResource, fDestination);
- }
- public IPath getDestinationPath() {
- return fDestination;
- }
- }
-
- /**
- * Adds the given file to the list of changed files.
- *
- * @param file the changed file
- */
- public void addChanged(IFile file) {
- if (fIgnoreCount == 0) {
- internalAdd(new ChangedDescription(file));
- }
- }
-
- /**
- * Adds the given resource to the list of resources
- * to be created.
- *
- * @param create the resource to be add to the list of
- * resources to be created
- */
- public void addCreate(IResource create) {
- if (fCreate == null)
- fCreate= new ArrayList(2);
- fCreate.add(create);
- if (fIgnoreCount == 0) {
- internalAdd(new CreateDescription(create));
- }
- }
-
- /**
- * Adds the given resource to the list of resources
- * to be deleted.
- *
- * @param delete the resource to be deleted
- */
- public void addDelete(IResource delete) {
- if (fDelete == null)
- fDelete= new ArrayList(2);
- fDelete.add(delete);
- if (fIgnoreCount == 0) {
- internalAdd(new DeleteDescription(delete));
- }
- }
-
- /**
- * Adds the given resource to the list of resources
- * to be moved.
- *
- * @param move the resource to be moved
- */
- public void addMove(IResource move, MoveArguments arguments) {
- if (fMove == null) {
- fMove= new ArrayList(2);
- fMoveArguments= new ArrayList(2);
- }
- fMove.add(move);
- fMoveArguments.add(arguments);
- if (fIgnoreCount == 0) {
- IPath destination= ((IResource)arguments.getDestination()).getFullPath().append(move.getName());
- internalAdd(new MoveDescription(move, destination));
- }
- }
-
- /**
- * Adds the given resource to the list of resources
- * to be copied.
- *
- * @param copy the resource to be copied
- */
- public void addCopy(IResource copy, CopyArguments arguments) {
- if (fCopy == null) {
- fCopy= new ArrayList(2);
- fCopyArguments= new ArrayList(2);
- }
- fCopy.add(copy);
- fCopyArguments.add(arguments);
- addCopyDelta(copy, arguments);
- }
-
- /**
- * Adds the given resource to the list of renamed
- * resources.
- *
- * @param rename the resource to be renamed
- * @param arguments the arguments of the rename
- */
- public void addRename(IResource rename, RenameArguments arguments) {
- Assert.isNotNull(rename);
- Assert.isNotNull(arguments);
- if (fRename == null) {
- fRename= new ArrayList(2);
- fRenameArguments= new ArrayList(2);
- }
- fRename.add(rename);
- fRenameArguments.add(arguments);
- if (fIgnoreCount == 0) {
- IPath newPath= rename.getFullPath().removeLastSegments(1).append(arguments.getNewName());
- internalAdd(new MoveDescription(rename, newPath));
- }
- }
-
- public RefactoringParticipant[] getParticipants(RefactoringStatus status, RefactoringProcessor processor, String[] natures, SharableParticipants shared) {
- List result= new ArrayList(5);
- if (fDelete != null) {
- DeleteArguments arguments= new DeleteArguments();
- for (Iterator iter= fDelete.iterator(); iter.hasNext();) {
- DeleteParticipant[] deletes= ParticipantManager.loadDeleteParticipants(status,
- processor, iter.next(),
- arguments, natures, shared);
- result.addAll(Arrays.asList(deletes));
- }
- }
- if (fCreate != null) {
- CreateArguments arguments= new CreateArguments();
- for (Iterator iter= fCreate.iterator(); iter.hasNext();) {
- CreateParticipant[] creates= ParticipantManager.loadCreateParticipants(status,
- processor, iter.next(),
- arguments, natures, shared);
- result.addAll(Arrays.asList(creates));
- }
- }
- if (fMove != null) {
- for (int i= 0; i < fMove.size(); i++) {
- Object element= fMove.get(i);
- MoveArguments arguments= (MoveArguments)fMoveArguments.get(i);
- MoveParticipant[] moves= ParticipantManager.loadMoveParticipants(status,
- processor, element,
- arguments, natures, shared);
- result.addAll(Arrays.asList(moves));
-
- }
- }
- if (fCopy != null) {
- for (int i= 0; i < fCopy.size(); i++) {
- Object element= fCopy.get(i);
- CopyArguments arguments= (CopyArguments)fCopyArguments.get(i);
- CopyParticipant[] copies= ParticipantManager.loadCopyParticipants(status,
- processor, element,
- arguments, natures, shared);
- result.addAll(Arrays.asList(copies));
- }
- }
- if (fRename != null) {
- for (int i= 0; i < fRename.size(); i++) {
- Object resource= fRename.get(i);
- RenameArguments arguments= (RenameArguments) fRenameArguments.get(i);
- RenameParticipant[] renames= ParticipantManager.loadRenameParticipants(status,
- processor, resource,
- arguments, natures, shared);
- result.addAll(Arrays.asList(renames));
- }
- }
- return (RefactoringParticipant[])result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- public void ignoreForDelta() {
- fIgnoreCount++;
- }
-
- public void trackForDelta() {
- fIgnoreCount--;
- }
-
- public void addDelta(DeltaDescription description) {
- if (fIgnoreCount > 0)
- return;
- internalAdd(description);
- }
-
- public void addCopyDelta(IResource copy, CopyArguments arguments) {
- if (fIgnoreCount == 0) {
- IPath destination= ((IResource)arguments.getDestination()).getFullPath().append(copy.getName());
- internalAdd(new CopyDescription(copy, destination));
- }
- }
-
- /**
- * Checks if the resource will exist in the future based on
- * the recorded resource modifications.
- *
- * @param resource the resource to check
- * @return whether the resource will exist or not
- */
- public boolean willExist(IResource resource) {
- if (fDeltaDescriptions == null)
- return false;
- IPath fullPath= resource.getFullPath();
- for (Iterator iter= fDeltaDescriptions.iterator(); iter.hasNext();) {
- DeltaDescription delta= (DeltaDescription) iter.next();
- if (fullPath.equals(delta.getDestinationPath()))
- return true;
- }
- return false;
- }
-
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- if (fDeltaDescriptions == null)
- return;
- for (Iterator iter= fDeltaDescriptions.iterator(); iter.hasNext();) {
- ((DeltaDescription) iter.next()).buildDelta(builder);
- }
- }
-
- public static void buildMoveDelta(IResourceChangeDescriptionFactory builder, IResource resource, RenameArguments args) {
- IPath newPath= resource.getFullPath().removeLastSegments(1).append(args.getNewName());
- builder.move(resource, newPath);
- }
-
- public static void buildMoveDelta(IResourceChangeDescriptionFactory builder, IResource resource, MoveArguments args) {
- IPath destination= ((IResource)args.getDestination()).getFullPath().append(resource.getName());
- builder.move(resource, destination);
- }
-
- public static void buildCopyDelta(IResourceChangeDescriptionFactory builder, IResource resource, CopyArguments args) {
- IPath destination= ((IResource)args.getDestination()).getFullPath().append(resource.getName());
- builder.copy(resource, destination);
- }
-
- private void internalAdd(DeltaDescription description) {
- if (fDeltaDescriptions == null)
- fDeltaDescriptions= new ArrayList();
- fDeltaDescriptions.add(description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceProcessors.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceProcessors.java
deleted file mode 100644
index e3e7c226..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceProcessors.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.participants;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-
-public class ResourceProcessors {
-
- public static String[] computeAffectedNatures(IResource resource) throws CoreException {
- IProject project= resource.getProject();
- Set result= new HashSet();
- Set visitedProjects= new HashSet();
- computeNatures(result, visitedProjects, project);
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public static String[] computeAffectedNatures(IResource[] resources) throws CoreException {
- Set result= new HashSet();
- Set visitedProjects= new HashSet();
- for (int i= 0; i < resources.length; i++) {
- computeNatures(result, visitedProjects, resources[i].getProject());
- }
- return (String[])result.toArray(new String[result.size()]);
- }
-
- private static void computeNatures(Set result, Set visitedProjects, IProject focus) throws CoreException {
- if (visitedProjects.contains(focus))
- return;
- String[] pns= focus.getDescription().getNatureIds();
- for (int p = 0; p < pns.length; p++) {
- result.add(pns[p]);
- }
- visitedProjects.add(focus);
- IProject[] referencing= focus.getReferencingProjects();
- for (int i= 0; i < referencing.length; i++) {
- computeNatures(result, visitedProjects, referencing[i]);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties
deleted file mode 100644
index bf8b55e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties
+++ /dev/null
@@ -1,1354 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-# NLS properties for the Refactoring Core
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring
-Assert_assertion_failed=assertion failed;
-Assert_null_argument=null argument;
-
-ProcessorBasedRefactoring_error_unsupported_initialization=The refactoring processor ''{0}'' has no support for refactoring scripts.
-
-InitializableRefactoring_argument_not_exist=The refactoring script argument ''{0}'' is missing in the refactoring script.
-InitializableRefactoring_input_not_exists=The refactoring ''{1}'' ({2}) cannot be performed, since its input ''{0}'' does not exist.
-InitializableRefactoring_inputs_do_not_exist=The refactoring ''{0}'' ({1}) cannot be performed, since its input does not exist.
-InitializableRefactoring_illegal_argument=The value ''{0}'' of the refactoring script argument ''{1}'' is invalid.
-InitializableRefactoring_inacceptable_arguments=This refactoring does not accept the specified refactoring argument.
-
-DynamicValidationStateChange_workspace_changed=The workspace has been modified since the refactoring change object has been created
-DynamicValidationRefactoringChange_fatal_error=Validation of refactoring descriptor returns fatal error status.
-
-Checks_Choose_name=Choose a name.
-Checks_all_excluded=All resources have been excluded from refactoring. Cannot proceed
-Checks_cannot_be_parsed=''{0}'' has syntax errors. Content of that file will not be updated.
-Checks_cu_not_created=JavaScript file could not be created for this element.
-Checks_cu_not_parsed=This refactoring cannot be performed correctly due to syntax errors in the JavaScript file. To perform this operation you will need to fix the errors.
-Checks_cu_has_compile_errors=Code modification may not be accurate as affected resource ''{0}'' has compile errors.
-Checks_no_dot=Type name cannot contain a dot (.).
-Checks_cu_name_used=JavaScript file ''{0}.js'' already exists
-Checks_method_native=Method ''{1}'' in file ''{0}'' is native. Running the modified program will cause {2}.
-Checks_methodName_constructor=New function name has constructor name.
-Checks_methodName_exists=Function ''{0}'' already exists in type ''{1}''.
-Checks_methodName_overrides=New function ''{0}'' overrides an existing function in type ''{1}''.
-Checks_methodName_returnTypeClash=New function ''{0}'' overrides a function declared in type ''{1}'' that uses a different return type.
-Checks_has_main=Type {0} contains a main function - some applications (such as scripts) may not work after refactoring.
-Checks_constructor_name=If you proceed, the function ''{0}'' in ''{1}'' will have a constructor name.
-Checks_method_names_lowercase=This name is discouraged. According to convention, names of functions should start with a lowercase letter.
-Checks_method_names_lowercase2=The function name ''{0}'' in type ''{1}'' is discouraged. According to convention, names of functions should start with a lowercase letter.
-Checks_validateEdit= Team provider refused file modification.
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.base
-#######################################
-
-Change_is_unsaved={0} is unsaved.
-Change_is_read_only={0} is read only.
-Change_has_modifications={0} has been modified since the refactoring got executed.
-Change_does_not_exist=''{0}'' does not exist anymore.
-Change_same_read_only= The read only state of {0} has changed.
-
-UndoCompilationUnitChange_no_resource= JavaScript file ''{0}'' does not have an underlying file.
-UndoDeleteResourceChange_change_name=Restore ''{0}''
-UndoDeleteResourceChange_cannot_restore=There is not enough information to create or restore ''{0}''.
-UndoDeleteResourceChange_already_exists=Cannot create or restore ''{0}'' because it already exists.
-
-Refactoring_binary={0} is binary
-Refactoring_not_in_model={0} does not exist in the model
-Refactoring_read_only={0} is read only
-Refactoring_unknown_structure={0} - unknown structure
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.changes
-#######################################
-AbstractRenameChange_Renaming=Renaming...
-
-RenameResourceChange_rename_resource=rename resource
-RenameResourceChange_name=Rename ''{0}'' to ''{1}''
-RenameResourceChange_does_not_exist=''{0}'' does not exist
-RenameResourceChange_descriptor_description=Rename resource ''{0}'' to ''{1}''
-RenameResourceChange_descriptor_description_short=Rename resource ''{0}''
-
-DeleteFromClassPathChange_remove=Remove entry from classpath of Java project:
-
-MovePackageChange_move=Move package ''{0}'' to ''{1}''
-MoveResourceChange_move=Move resource ''{0}'' to ''{1}''
-
-RenameJavaProjectChange_rename=Rename Java Project ''{0}'' to ''{1}''
-RenameJavaProjectChange_update=Updating classpaths
-
-RenameSourceFolderChange_rename=Rename Source Folder ''{0}'' to ''{1}''
-RenameSourceFolderChange_rename_archive=Cannot rename archive {0}
-RenameSourceFolderChange_rename_external=Cannot rename external archive {0}
-RenameSourceFolderChange_descriptor_description=Rename source folder ''{0}'' to ''{1}''
-RenameSourceFolderChange_descriptor_description_short=Rename source folder ''{0}''
-RenameSourceFolderChange_rename_linked=Cannot rename linked source folder {0}
-
-AbstractDeleteChange_deleting=deleting
-
-CreatePackageChange_Creating_package=Creating package
-CreatePackageChange_Create_package=Create package
-
-AddToClasspathChange_add=Add entry to classpath of Java project:
-
-CopyCompilationUnitChange_copy=Copy ''{0}'' to ''{1}''
-
-CopyPackageChange_copy=Copy package ''{0}'' to ''{1}''
-
-RenamePackageChange_checking_change=Checking change for: {0}
-RenamePackageChange_name_with_subpackages=Rename package ''{0}'' and subpackages to ''{1}''
-RenamePackageChange_name=Rename package ''{0}'' to ''{1}''
-
-MoveCompilationUnitChange_default_package=root directory
-MoveCompilationUnitChange_name=Move JavaScript file ''{0}'' to ''{1}''
-
-RenameCompilationUnitChange_name=Rename JavaScript file ''{0}'' to ''{1}''
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.code
-#######################################
-
-#-- Extract Method -------------------------------------------
-LocalTypeAnalyzer_local_type_from_outside=Selected block references a local type declared outside the selection.
-LocalTypeAnalyzer_local_type_referenced_outside=A local type declared in the selected block is referenced outside the selection.
-
-FlowAnalyzer_execution_flow=Selected statements contain a return statement but not all possible execution flows end in a return. Semantics may not be preserved if you proceed.
-
-ExtractMethodAnalyzer_assignments_to_local=Ambiguous return value: selected block contains more than one assignment to local variable.
-ExtractMethodAnalyzer_only_method_body=Cannot extract new function from selection. Only statements from a method body can be extracted.
-ExtractMethodAnalyzer_after_do_keyword=Selection may not start immediately after the \'do\' keyword.
-ExtractMethodAnalyzer_super_or_this=Cannot extract super or this call from constructor.
-ExtractMethodAnalyzer_cannot_determine_return_type=Cannot determine expression's return type. Using void instead.
-ExtractMethodAnalyzer_branch_mismatch=Selection contains branch statement but corresponding branch target is not selected.
-ExtractMethodAnalyzer_parent_mismatch=Not all selected statements are enclosed by the same parent statement.
-ExtractMethodAnalyzer_cannot_extract_anonymous_type=Cannot extract the body of a anonymous type declaration. Select whole declaration.
-ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment=Cannot extract a variable declaration fragment. Select whole declaration statement.
-ExtractMethodAnalyzer_cannot_extract_for_initializer=Cannot extract initialization part of a \'for\' statement.
-ExtractMethodAnalyzer_cannot_extract_for_updater=Cannot extract increment part of a \'for\' statement.
-ExtractMethodAnalyzer_cannot_extract_variable_declaration=Cannot extract parts of a variable declaration. Select whole declaration.
-ExtractMethodAnalyzer_cannot_extract_type_reference=Cannot extract a single type reference.
-ExtractMethodAnalyzer_cannot_extract_switch_case=Cannot extract the expression of a case statement.
-ExtractMethodAnalyzer_cannot_extract_method_name_reference=Cannot extract a single function name.
-ExtractMethodAnalyzer_cannot_extract_name_in_declaration=Cannot extract the name part of a declaration.
-ExtractMethodAnalyzer_compile_errors_no_parent_binding=The selection cannot cannot be analyzed because of compilation errors in the enclosing type. To perform the operation you will need to fix the errors.
-ExtractMethodAnalyzer_ambiguous_return_value=Ambiguous return value: expression, access to local or return statement extracted.
-ExtractMethodAnalyzer_compile_errors=The function''s body cannot be analyzed because of compilation errors in function ''{0}''. To perform the operation you will need to fix the errors.
-ExtractMethodAnalyzer_leftHandSideOfAssignment=Cannot extract the left-hand side of an assignment.
-ExtractMethodAnalyzer_single_expression_or_set=Can only extract a single expression or a set of statements.
-ExtractMethodAnalyzer_cannot_extract_null_type=Cannot extract null expression.
-
-ExtractMethodRefactoring_name=Extract Function
-ExtractMethodRefactoring_add_method=Create new function ''{0}'' from selected statement(s)
-ExtractMethodRefactoring_checking_new_name=Checking new function name
-ExtractMethodRefactoring_no_set_of_statements=Selection does not mark a set of statements. Only statements from a function body can be extracted.
-ExtractMethodRefactoring_substitute_with_call=Substitute statement(s) with call to {0}
-ExtractMethodRefactoring_change_name=Extract Function
-ExtractMethodRefactoring_name_pattern=Function name: ''{0}''
-ExtractMethodRefactoring_organize_imports=Organize Imports
-ExtractMethodRefactoring_duplicates_single=replace duplicate code fragment with call to {0}
-ExtractMethodRefactoring_duplicates_multi=replace duplicate code fragments with call to {0}
-ExtractMethodRefactoring_generate_comment=Generate function comment
-ExtractMethodRefactoring_error_nameInUse=''{0}'' is already used as a name in the selected code
-ExtractMethodRefactoring_error_sameParameter=A parameter ''{0}'' already exists
-ExtractMethodRefactoring_visibility_pattern=Declared visibility: ''{0}''
-ExtractMethodRefactoring_replace_occurrences=Replace occurrences of statements with function
-ExtractMethodRefactoring_error_vararg_ordering=The variable arity parameter ''{0}'' cannot be followed by another parameter
-ExtractMethodRefactoring_descriptor_description=Extract function ''{0}'' from ''{1}'' to ''{2}''
-ExtractMethodRefactoring_descriptor_description_short=Extract function ''{0}''
-ExtractMethodRefactoring_destination_pattern=Destination type: ''{0}''
-ExtractMethodRefactoring_default_visibility=(default)
-ExtractMethodRefactoring_declare_thrown_exceptions=Declare thrown runtime exceptions
-
-#-- Inline Method ------------------------------------------------------
-InlineMethodRefactoring_name= Inline Function
-InlineMethodRefactoring_searching= Searching for references...
-InlineMethodRefactoring_processing= Processing {0}
-InlineMethodRefactoring_edit_inline= Inline function invocation
-InlineMethodRefactoring_edit_delete= Delete function declaration
-InlineMethodRefactoring_edit_inlineCall= Inline Function
-InlineMethodRefactoring_edit_import= Update import statements
-InlineMethodRefactoring_error_classFile=Cannot inline function ''{0}'' since it is declared in a class file without source attachment.
-InlineMethodRefactoring_remove_method=Remove function declaration
-InlineMethodRefactoring_nestedInvocation=Nested invocation. Only the innermost invocation will be inlined.
-InlineMethodRefactoring_original_pattern=Original element: ''{0}''
-InlineMethodRefactoring_error_noMethodDeclaration= Unable to resolve corresponding function declaration.
-InlineMethodRefactoring_checking_overridden= Checking for overridden functions...
-InlineMethodRefactoring_replace_references=Replace all references to function with statements
-InlineMethodRefactoring_descriptor_description=Inline function ''{0}'' in ''{1}''
-InlineMethodRefactoring_descriptor_description_short=Inline function ''{0}''
-
-# The three keys below are referenced indirectly by passing a string to a helper
-# method. Do not remove them even if they are marked as unused.
-InlineMethodRefactoring_checking_overridden_error= Type {0} overrides function to be inlined.
-InlineMethodRefactoring_checking_overrides_error= Function to be inlined overrides function from class {0}.
-InlineMethodRefactoring_checking_implements_error= Function to be inlined implements function from interface {0}.
-# End of do-not-remove section.
-
-InlineMethodRefactoring_SourceAnalyzer_recursive_call=Function declaration contains recursive call.
-InlineMethodRefactoring_SourceAnalyzer_native_methods=Cannot inline native functions
-InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors=The function declaration contains compile errors. To perform the operation you will need to fix the errors.
-InlineMethodRefactoring_SourceAnalyzer_typedeclaration_has_errors=The type declaration contains compile errors. To perform the operation you will need to fix the errors.
-InlineMethodRefactoring_SourceAnalyzer_methoddeclaration_has_errors=The function declaration contains compile errors. To perform the operation you will need to fix the errors.
-
-InlineMethodRefactoring_SourceAnalyzer_qualified_this_expressions=Cannot inline a function that uses qualified this expressions.
-InlineMethodRefactoring_SourceAnalyzer_syntax_errors=The JavaScript file containing this function declaration has syntax errors. To perform the operation you will need to fix the errors.
-InlineMethodRefactoring_SourceAnalyzer_abstract_methods=Cannot inline abstract functions.
-
-CallInliner_receiver_type=Cannot determine receiver\'s type.
-CallInliner_execution_flow=Cannot inline function. Return statement in function declaration interrupts execution flow.
-CallInliner_multiDeclaration=Cannot inline function used as an initializer in a multi fragment variable declaration.
-CallInliner_simple_functions=Inlining is only possible on simple functions (consisting of a single return statement), or functions used in an assignment.
-CallInliner_field_initializer_simple=In var initializers inlining is only supported for simple functions (e.g. functions consisting of a single return statement).
-CallInliner_field_initialize_new_local=Cannot inline var initializer because new local variable is required.
-CallInliner_super_into_this_expression=Cannot inline a super invocation into a this expression.
-CallInliner_field_initialize_write_parameter=Cannot inline var initializer because one of the function parameters is used as an assignment target and will require new local variable.
-CallInliner_field_initialize_self_reference=Cannot inline function. Function references the var to be initialized.
-CallInliner_constructors=Cannot inline a constructor invocation that is used as a class instance creation.
-CallInliner_cast_analysis_error=Cannot analyze call context to determine if implicit cast is needed.
-
-TargetProvider_inaccurate_match=Inaccurate references to function found. References will be ignored.
-TargetProvider_method_declaration_not_unique=Cannot uniquely resolve function to be inlined.
-TargetProvider_cannot_local_method_in_binary=Cannot inline local function in binary type.
-
-#-- SEF ------------------------------------------------------
-SelfEncapsulateField_AccessAnalyzer_encapsulate_read_access=Encapsulate read access
-SelfEncapsulateField_AccessAnalyzer_encapsulate_write_access=Encapsulate write access
-SelfEncapsulateField_AccessAnalyzer_encapsulate_prefix_access=Encapsulate prefix access
-SelfEncapsulateField_AccessAnalyzer_encapsulate_postfix_access=Encapsulate postfix access
-SelfEncapsulateField_AccessAnalyzer_cannot_convert_postfix_expression=Cannot convert postfix expression. It is used inside another expression.
-SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError=Function {0}() does not exist in {1}
-
-SelfEncapsulateField_name=Encapsulate Var
-SelfEncapsulateField_method_exists=A function ''{0}'' already exists in type ''{1}''.
-SelfEncapsulateField_use_accessors=Use getter and setter functions in declaring type
-SelfEncapsulateField_compiler_errors_field=Cannot analyze var ''{0}'' due to the following compiler error: {1}
-SelfEncapsulateField_compiler_errors_update={0} contains compiler errors. This may affect var access update.
-SelfEncapsulateField_type_not_resolveable=The type of the selected var cannot be resolved. An import statement may be missing.
-SelfEncapsulateField_cannot_analyze_selected_field=Cannot analyze selected var ''{0}''
-SelfEncapsulateField_descriptor_description_short=Encapsulate var ''{0}''
-SelfEncapsulateFieldRefactoring_descriptor_description=Encapsulate var ''{0}'' in ''{1}''
-SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError=No such function ''{0}''
-SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field=The function {0} is static while the var {1} is not static
-SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field=The function {0} is not static while the var {1} is static
-SelfEncapsulateField_checking_preconditions=Checking preconditions..
-SelfEncapsulateField_searching_for_cunits=Searching for affected JavaScript files...
-SelfEncapsulateField_do_not_use_accessors=Do not use getter and setter functions in declaring type
-SelfEncapsulateField_analyzing=Analyzing...
-SelfEncapsulateField_create_changes=Create changes
-SelfEncapsulateField_getter_pattern=Getter function name: ''{0}''
-SelfEncapsulateField_setter_pattern=Setter function name: ''{0}''
-SelfEncapsulateField_change_visibility=Change visibility to private
-SelfEncapsulateField_original_pattern=Original element: ''{0}''
-SelfEncapsulateField_default_visibility=(default)
-SelfEncapsulateField_visibility_pattern=Var visibility: ''{0}''
-SelfEncapsulateField_generate_comments=Generate function comments
-SelfEncapsulateField_add_setter=Add Setter function
-SelfEncapsulateField_add_getter=Add Getter function
-
-#-- inline temp ------------------------------------------------------
-InlineTempRefactoring_name=Inline Local Variable
-InlineTempRefactoring_syntax_errors=This JavaScript file contains syntax errors. To perform the operation you will need to fix the errors.
-InlineTempRefactoring_select_temp=A local variable declaration or reference must be selected to activate this refactoring.
-InlineTempRefactoring_method_parameter=Cannot inline function parameters.
-InlineTempRefactoring_exceptions_declared=Cannot inline exceptions declared in \'catch\' clauses.
-InlineTempRefactoring_descriptor_description=Inline local variable ''{0}'' in ''{1}''
-InlineTempRefactoring_descriptor_description_short=Inline local variable ''{0}''
-InlineTempRefactoring_not_initialized=Local variable ''{0}'' is not initialized at declaration.
-InlineTempRefactoring_assigned_more_once=Local variable ''{0}'' is assigned more than once.
-InlineTempRefactoring_preview=Checking preconditions...
-InlineTempRefactoring_inline=Inline local variable
-InlineTempRefactoring_inline_edit_name=Replace variable reference with expression
-InlineTempRefactoring_remove_edit_name=Remove variable declaration
-InlineTempRefactoring_for_initializers=Cannot inline variables declared in the initializer list of a \'for\' statement.
-InlineTempRefactoring_original_pattern=Original element: ''{0}''
-
-#-- extract temp ------------------------------------------------------
-ExtractTempRefactoring_name=Extract Local Variable
-ExtractTempRefactoring_select_expression=An expression must be selected to activate this refactoring.
-ExtractTempRefactoring_syntax_error=This file contains syntax errors. To perform this operation you will need to fix the errors.
-ExtractTempRefactoring_explicit_constructor=Code from explicit constructor calls cannot be extracted to a variable.
-ExtractTempRefactoring_expression_pattern=Variable expression: ''{0}''
-ExtractTempRefactoring_expr_in_method_or_initializer=An expression used in a function or in an initializer must be selected to activate this refactoring.
-ExtractTempRefactoring_no_void=Cannot extract an expression of type \'void\'.
-ExtractTempRefactoring_null_literals=Cannot extract single null literals.
-ExtractTempRefactoring_declare_final=Declare variable 'final'
-ExtractTempRefactoring_array_initializer=Operation not applicable to an array initializer.
-ExtractTempRefactoring_another_variable=A variable with name ''{0}'' is already defined in the visible scope.
-ExtractTempRefactoring_assignment=Cannot extract assignment that is part of another expression.
-ExtractTempRefactoring_convention=This name is discouraged. According to convention, names of local variables should start with a lowercase letter.
-ExtractTempRefactoring_checking_preconditions=Checking preconditions...
-ExtractTempRefactoring_preview=Checking preconditions...
-ExtractTempRefactoring_extract_temp=Extract Local Variable
-ExtractTempRefactoring_update_imports=Update imports
-ExtractTempRefactoring_declare_local_variable=Add variable declaration
-ExtractTempRefactoring_descriptor_description=Extract local variable ''{0}'' from expression ''{1}''
-ExtractTempRefactoring_descriptor_description_short=Extract local variable ''{0}''
-ExtractTempRefactoring_replace=Replace expression with variable reference
-ExtractTempRefactoring_name_in_new=Cannot extract this name - try selecting the whole instance creation expression.
-ExtractTempRefactoring_name_pattern=Variable name: ''{0}''
-ExtractTempRefactoring_names_in_declarations=An expression has to be selected to activate this refactoring. Names used in declarations are not expressions.
-ExtractTempRefactoring_assigned_to=The selected expression is assigned. Extracting may change the program\'s semantics.
-ExtractTempRefactoring_change_name=Extract Local Variable
-ExtractTempRefactoring_refers_to_for_variable=Cannot extract expression, since it refers to a variable declared in the initializer of the enclosing \'for\' statement.
-ExtractTempRefactoring_replace_occurrences=Replace occurrences of expression with variable
-ExtractTempRefactoring_destination_pattern=Destination function: ''{0}''
-ExtractTempRefactoring_for_initializer_updater=Cannot extract \'for\' initializer or updater.
-
-#-- extract constant --------------------------------------------------
-ExtractConstantRefactoring_name=Extract Constant
-ExtractConstantRefactoring_descriptor_description=Extract constant ''{0}'' from expression ''{1}''
-ExtractConstantRefactoring_descriptor_description_short=Extract constant ''{0}''
-ExtractConstantRefactoring_select_expression=An expression must be selected to activate this refactoring.
-ExtractConstantRefactoring_visibility_pattern=Declared visibility: ''{0}''
-ExtractConstantRefactoring_replace_occurrences=Replace occurrences of expression with constant
-ExtractConstantRefactoring_qualify_references=Qualify references to constant
-ExtractConstantRefactoring_syntax_error=This file contains syntax errors. To perform this operation you will need to fix the errors.
-ExtractConstantRefactoring_declare_constant=Add constant declaration
-ExtractConstantRefactoring_default_visibility=(default)
-ExtractConstantRefactoring_replace=Replace expression with constant reference
-ExtractConstantRefactoring_another_variable=A variable with name ''{0}'' is already defined in the visible scope.
-ExtractConstantRefactoring_no_void=Cannot extract an expression of type \'void\'.
-ExtractConstantRefactoring_null_literals=Cannot extract single null literals.
-ExtractConstantRefactoring_not_load_time_constant=Cannot extract this expression - it is not a valid static constant.
-ExtractConstantRefactoring_convention=This name is discouraged. According to convention, names of class constants do not contain lowercase letters.
-ExtractConstantRefactoring_change_name=Extract Constant
-ExtractConstantRefactoring_checking_preconditions=Checking preconditions...
-ExtractConstantRefactoring_constant_name_pattern=Constant name: ''{0}''
-ExtractConstantRefactoring_constant_expression_pattern=Constant expression: ''{0}''
-
-#-- introduce parameter --------------------------------------------------
-IntroduceParameterRefactoring_name=Introduce Parameter
-IntroduceParameterRefactoring_syntax_error=This JavaScript file contains syntax errors. To perform the operation you will need to fix the errors.
-IntroduceParameterRefactoring_select=An expression must be selected to activate this refactoring.
-IntroduceParameterRefactoring_expression_in_method=An expression used in a function must be selected to activate this refactoring.
-IntroduceParameterRefactoring_expression_pattern=Parameter expression: ''{0}''
-IntroduceParameterRefactoring_descriptor_description=Introduce parameter ''{0}'' for ''{1}'' from expression ''{2}''
-IntroduceParameterRefactoring_descriptor_description_short=Introduce parameter for ''{0}''
-IntroduceParameterRefactoring_cannot_introduce=Cannot introduce parameter: {0}.
-IntroduceParameterRefactoring_original_pattern=Original element: ''{0}''
-IntroduceParameterRefactoring_parameter_pattern=Parameter name: ''{0}''
-IntroduceParameterRefactoring_no_binding=Cannot resolve binding of enclosing function declaration.
-IntroduceParameterRefactoring_no_void=Cannot introduce a parameter from an expression of type \'void\'.
-IntroduceParameterRefactoring_replace=Replace expression with a parameter reference
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.rename
-#######################################
-RenameCompilationUnitRefactoring_name=Rename JavaScript File
-RenameCompilationUnitRefactoring_not_parsed={0} has syntax errors. No references will be updated if you proceed
-RenameCompilationUnitRefactoring_not_parsed_1={0} has syntax errors.
-RenameCompilationUnitChange_descriptor_description=Rename JavaScript file ''{0}'' to ''{1}''
-RenameCompilationUnitChange_descriptor_description_short=Rename JavaScript file ''{0}''
-RenameCompilationUnitRefactoring_same_name=The name has not been changed.
-
-RenameEnumConstRefactoring_name=Rename Enum Constant
-RenameEnumConstRefactoring_convention=This name is discouraged. According to convention, names of enum constants do not contain lowercase letters.
-RenameEnumConstRefactoring_another_name=Choose another name.
-RenameEnumConstRefactoring_const_already_defined=Enum constant with this name is already defined.
-RenameEnumConstProcessor_descriptor_description=Rename enum constant ''{0}'' of ''{1}'' to ''{2}''
-RenameEnumConstProcessor_descriptor_description_short=Rename enum constant ''{0}''
-RenameEnumConstProcessor_change_name=Rename Enum Constant
-
-RenameFieldRefactoring_name=Rename Var
-RenameFieldRefactoring_searching=Searching for references...
-RenameFieldRefactoring_checking=Checking preconditions...
-RenameFieldRefactoring_hiding=After renaming, the var ''{0}'' will be hidden in the scope of the var ''{1}'' declared in type ''{2}''
-RenameFieldRefactoring_hiding2=After renaming, the var named ''{0}'' declared in type ''{1}'' will be hidden in the scope of the var ''{2}''
-RenameFieldRefactoring_another_name=Choose another name.
-RenameFieldRefactoring_another_name2=The var ''{0}'' in type ''{1}'' already has the assigned name.
-RenameFieldRefactoring_field_already_defined=A var with this name is already defined.
-RenameFieldRefactoring_field_already_defined2=A var with name ''{0}'' is already defined in ''{1}''.
-RenameFieldRefactoring_deleted=The selected var has been deleted from ''{0}''
-RenameFieldRefactoring_already_exists=Function ''{0}'' already exists in ''{1}''
-RenameFieldRefactoring_overridden=Function ''{0}'' is overridden or overrides another function
-RenameFieldRefactoring_change_name=Rename Var
-RenameFieldRefactoring_overridden_or_overrides=Function ''{0}'' is overridden or overrides another function
-RenameFieldRefactoring_Update_getter_occurrence=Update getter occurrence
-RenameFieldRefactoring_Update_setter_occurrence=Update setter occurrence
-RenameFieldRefactoring_Update_field_declaration=Update var declaration
-RenameFieldRefactoring_descriptor_description_short=Rename var ''{0}''
-RenameFieldRefactoring_Update_field_reference=Update var reference
-RenameFieldRefactoring_should_start_lowercase=The var name is discouraged. According to convention, var names should start with a lowercase letter.
-RenameFieldRefactoring_setting_rename_settter=Rename setter function for var
-RenameFieldRefactoring_should_start_lowercase2= The var name ''{0}'' in type ''{1}'' is discouraged. According to convention, var names should start with a lowercase letter.
-RenameFieldRefactoring_declared_in_supertype=Cannot be renamed because it is declared in a supertype
-RenameFieldRefactoring_setting_rename_getter=Rename getter function for var
-RenameFieldProcessor_descriptor_description=Rename var ''{0}'' in ''{1}'' to ''{2}''
-
-RenameTypeParameterRefactoring_deleted=The selected type variable has been deleted from ''{0}''
-RenameTypeParameterProcessor_name=Rename Type Variable
-RenameTypeParameterProcessor_change_name=Rename Type Variable
-RenameTypeParameterRefactoring_should_start_lowercase=This name is discouraged. According to convention, names of type variables do not contain lowercase letters.
-RenameTypeParameterProcessor_descriptor_description=Rename type variable ''{0}'' of ''{1}'' to ''{2}''
-RenameTypeParameterProcessor_descriptor_description_short=Rename type variable ''{0}''
-RenameTypeParameterRefactoring_another_name=Choose another name.
-RenameTypeParameterRefactoring_method_type_parameter_already_defined=A type variable with this name is already defined in the declaring function.
-RenameTypeParameterRefactoring_class_type_parameter_already_defined=A type variable with this name is already defined in the declaring type.
-RenameTypeParameterRefactoring_searching=Searching for references...
-RenameTypeParameterRefactoring_checking=Checking preconditions...
-RenameTypeParameterRefactoring_update_type_parameter_declaration=Update type variable declaration
-RenameTypeParameterRefactoring_update_type_parameter_reference=Update type variable reference
-RenameTypeParameterRefactoring_type_parameter_inner_class_clash=The new type variable name conflicts with the name of the inner class ''{0}''.
-
-RenamePackageRefactoring_another_name=Choose another name.
-RenamePackageRefactoring_checking=Checking preconditions...
-RenamePackageRefactoring_creating_change=Preparing preview...
-RenamePackageRefactoring_package_exists=Package already exists
-RenamePackageRefactoring_searching=Searching for references...
-RenamePackageRefactoring_update_reference=Update package reference
-RenamePackageRefactoring_update_imports=Update imports
-RenamePackageRefactoring_name=Rename Package
-RenamePackageRefactoring_aleady_exists=Package ''{0}'' already exists in this project in folder ''{1}''
-
-RenameMethodInInterfaceRefactoring_already_defined=A related type declares a function with the new name (and same number of parameters)
-RenameMethodInInterfaceRefactoring_special_case=Cannot rename this function because it is a special case (see the language specification section 9.2 for details)
-
-RenameMethodRefactoring_name=Rename Function
-RenameMethodRefactoring_no_binary=Related function ''{0}'' (declared in ''{1}'') is binary. Refactoring cannot be performed.
-RenameMethodRefactoring_no_native=Renaming native functions will cause an unsatisfied link error on runtime.
-RenameMethodRefactoring_no_native_1=Related function ''{0}'' (declared in ''{1}'') is native. Renaming will cause an UnsatisfiedLinkError on runtime.
-RenameMethodRefactoring_no_read_only=Related function ''{0}'' (declared in ''{1}'') is read-only. Refactoring cannot be performed.
-RenameMethodRefactoring_not_in_model=Related function ''{0}'' (declared in ''{1}'') does not exist in the model.
-RenameMethodRefactoring_same_name=This name already exists.
-RenameMethodRefactoring_same_name2=The function ''{0}'' in type ''{1}'' already has the assigned name.
-RenameMethodRefactoring_update_occurrence=Update function reference
-RenameMethodRefactoring_update_declaration=Update function declaration
-RenameMethodRefactoring_deleted=The selected function has been deleted from ''{0}''
-RenameMethodRefactoring_taskName_checkingPreconditions=Checking preconditions...
-RenameMethodRefactoring_taskName_searchingForReferences=Searching for references...
-
-RenameMethodProcessor_descriptor_description=Rename function ''{0}'' to ''{1}''
-RenameMethodProcessor_descriptor_description_short=Rename function ''{0}''
-RenameMethodProcessor_is_binary=Function to be renamed is binary.
-RenameMethodProcessor_change_name=Rename Function
-
-RenamePrivateMethodRefactoring_hierarchy_defines=''{0}'' or a type in its hierarchy defines a function ''{1}'' with the same number of parameters and the same parameter type names.
-RenamePrivateMethodRefactoring_hierarchy_defines2=''{0}'' or a type in its hierarchy defines a function ''{1}'' with the same number of parameters, but different parameter type names.
-RenamePrivateMethodRefactoring_update=Update function reference
-
-RenameVirtualMethodRefactoring_requieres_renaming_native=Renaming ''{0}'' requires renaming a native function. Renaming will cause {1} on runtime.
-RenameVirtualMethodRefactoring_hierarchy_declares1=Hierarchy declares a function ''{0}'' with the same number of parameters, but different parameter type names.
-RenameVirtualMethodRefactoring_hierarchy_declares2=Hierarchy declares a function ''{0}'' with the same number of parameters and the same parameter type names.
-
-RenameLocalVariableProcessor_descriptor_description=Rename local variable ''{0}'' in ''{1}'' to ''{2}''
-RenameLocalVariableProcessor_descriptor_description_short=Rename local variable ''{0}''
-
-RenameTypeRefactoring_checking=Checking preconditions...
-RenameTypeRefactoring_choose_another_name=Please choose another name.
-RenameTypeRefactoring_creating_change=Preparing preview...
-RenameTypeRefactoring_rename_constructor=rename constructor
-RenameTypeRefactoring_searching=Searching for references...
-RenameTypeRefactoring_update_reference=Update type reference
-RenameTypeRefactoring_name=Rename Type
-RenameTypeRefactoring_enclosed=Type ''{0}'' is enclosed in a type named ''{1}''
-RenameTypeRefactoring_encloses=Type ''{0}'' encloses a type named ''{1}''
-RenameTypeRefactoring_exists=Type named ''{0}'' already exists in package ''{1}''
-RenameTypeRefactoring_imported=Type named ''{0}'' is imported (single-type-import) in ''{1}'' (a JavaScript file must not import and declare a type with the same name)
-RenameTypeRefactoring_member_type_exists=Another member type named ''{0}'' already exists in ''{1}''
-RenameTypeRefactoring_enclosed_type_native=A type enclosed in type ''{0}'' declares a native function. Renaming will cause an unsatisfied link error on runtime.
-RenameTypeProcessor_descriptor_description=Rename type ''{0}'' to ''{1}''
-RenameTypeProcessor_descriptor_description_short=Rename type ''{0}''
-RenameTypeProcessor_progress_current_total=({0}/{1})
-
-RenameTypeProcessor_changeCategory_type=Rename Type Changes
-RenameTypeProcessor_change_name=Rename Type
-RenameTypeProcessor_creating_changes=Creating changes...
-RenameTypeProcessor_changeCategory_type_description=Changes to rename the type
-RenameTypeProcessor_deselected_method_is_overridden=The unselected function ''{0}'' in type ''{1}'' is overridden. All related overridden functions have been unselected as well.
-RenameTypeProcessor_changeCategory_method=Rename Function Changes
-RenameTypeProcessor_changeCategory_fields=Rename Var Changes
-RenameTypeProcessor_changeCategory_local_variables=Rename Local Variable Changes
-RenameTypeProcessor_renamed_method_is_overridden=One of the overridden functions around ''{0}'' in type ''{1}'' have been given a custom name, but it is overridden. All related overridden functions have been deselected.
-RenameTypeProcessor_changeCategory_local_variables_description=Changes to rename similarly named local variables
-RenameTypeProcessor_changeCategory_method_description=Changes to rename similarly named functions
-RenameTypeProcessor_changeCategory_fields_description=Changes to rename similarly named vars
-RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions=Checking preconditions for similarly named elements...
-RenameTypeProcessor_cannot_rename_methods_same_new_name=The two functions ''{0}'' and ''{1}'' in type ''{2}'' cannot be renamed to the same new name ''{3}''.
-RenameTypeProcessor_cannot_rename_fields_same_new_name=The two vars ''{0}'' and ''{1}'' in type ''{2}'' cannot be renamed to the same new name ''{3}''.
-RenameTypeProcessor_cannot_rename_locals_same_new_name=The two local variables ''{0}'' and ''{1}'' in ''{2}'' (type ''{3}'') may clash if renamed to the same new name ''{4}''.
-
-RenameTypeRefactoring_name_conflict1=Name conflict with type ''{0}'' in ''{1}''
-RenameTypeRefactoring_searching_text=searching for textual occurrences
-RenameTypeRefactoring_update=Type declaration update
-RenameTypeRefactoring_does_not_exist=Type ''{0}'' does not exist in the saved version of ''{1}''
-RenameTypeRefactoring_will_not_rename=JavaScript file will not be renamed
-RenameTypeRefactoring_local_type=Local Type declared inside ''{0}'' is named {1}
-RenameTypeRefactoring_member_type=Member Type declared inside ''{0}'' is named {1}
-RenameTypeRefactoring_another_type=Another type named ''{0} is referenced in ''{1}''
-
-TextMatchUpdater_update=Update textual occurrence
-TextMatchUpdater_searching=searching for textual occurrences in:
-TextMatchUpdater_textualMatches_name=Textual Changes
-TextMatchUpdater_textualMatches_description=Changes to textual occurrences in comments and strings
-
-QualifiedNameFinder_qualifiedNames_name=Qualified Name Changes
-QualifiedNameFinder_qualifiedNames_description=Changes to qualified names in non-Java files
-
-RippleMethodFinder_analizing_hierarchy=analyzing hierarchy
-
-RefactoringAnalyzeUtil_name_collision=Name collision with name ''{0}''
-
-RefactoringSearchEngine_binary_match_ungrouped=An occurrence in a binary type in project ''{0}'' has been found. These occurrences will not be updated, which may lead to compile errors if you proceed.
-RefactoringSearchEngine_binary_match_grouped=Occurrences in binary types in project ''{0}'' have been found. These occurrences will not be updated, which may lead to compile errors if you proceed.
-RefactoringSearchEngine_inaccurate_match=Inaccurate matches have been found in resource ''{0}''. Please review changes on the preview page.
-RefactoringSearchEngine_searching_occurrences=Searching for occurrences...
-RefactoringSearchEngine_searching_referenced_types=Searching for referenced types...
-RefactoringSearchEngine_searching_referenced_fields=Searching for referenced vars...
-RefactoringSearchEngine_searching_referenced_methods=Searching for referenced functions...
-RefactoringSearchEngine_potential_matches=Found potential matches. Please review changes on the preview page.
-RefactoringSearchEngine_non_cu_matches=Found matches in binary types. Occurrences will not be updated, which may lead to compile errors if you proceed.
-
-ReplaceInvocationsRefactoring_select_method_to_apply=Select a function declaration or function invocation to apply this refactoring.
-ReplaceInvocationsRefactoring_descriptor_description=Replace invocations of ''{0}'' in ''{1}''
-ReplaceInvocationsRefactoring_original_pattern=Original element: ''{0}''
-ReplaceInvocationsRefactoring_replace_references=Replace all references to function with body
-ReplaceInvocationsRefactoring_name=Replace Invocations
-ReplaceInvocationsRefactoring_change_name=Replace Invocations
-ReplaceInvocationsRefactoring_cannot_replace_in_binary=Cannot replace invocation in a binary function.
-
-RenameTempRefactoring_must_select_local=A local variable declaration or reference must be selected to activate this refactoring
-RenameTempRefactoring_only_in_methods_and_initializers=Only local variables declared in functions and initializers can be renamed
-RenameTempRefactoring_lowercase=This name is discouraged. According to convention, names of local variables should start with a lowercase letter.
-RenameTempRefactoring_lowercase2=The variable name ''{0}'' in ''{1}'' (type ''{2}'') is discouraged. According to convention, names of local variables should start with a lowercase letter.
-RenameTempRefactoring_rename=Rename Local Variable
-RenameTempRefactoring_changeName=Update local variable reference
-
-MethodChecks_overrides=The selected function overrides function ''{0}'' declared in type ''{1}''.
-MethodChecks_implements=The selected function is an implementation of function ''{0}'' declared in type ''{1}''
-
-RenameJavaProjectRefactoring_rename=Rename Java Project
-RenameJavaProjectRefactoring_already_exists=A project with that name already exists
-RenameJavaProjectChange_descriptor_description=Rename Java project ''{0}'' to ''{1}''
-RenameJavaProjectProcessor_folder_already_exists=A folder with that name already exists.
-RenameJavaProjectProcessor_descriptor_description_short=Rename Java project ''{0}''
-RenameJavaProjectRefactoring_read_only=Project ''{0}'' is marked as read-only
-
-RenamePackageRefactoring_searching_text=searching for text matches
-RenamePackageRefactoring_Packagered_only=Package ''{0}'' is read-only.
-RenamePackageRefactoring_resource_read_only=Resource corresponding to package ''{0}'' is read-only. Click ''Continue'' if still you want to rename it.
-RenamePackageProcessor_descriptor_description=Rename package ''{0}'' to ''{1}''
-RenamePackageProcessor_rename_subpackages=Rename subpackages of the package
-RenamePackageProcessor_descriptor_description_short=Rename package ''{0}''
-RenamePackageRefactoring_contains_type=Package ''{0}'' already contains a type named ''{1}''
-RenamePackageRefactoring_change_name=Rename Package
-
-RenameResourceRefactoring_Internal_Error=Internal Error
-RenameResourceRefactoring_alread_exists=A file or folder with this name already exists
-RenameResourceRefactoring_invalidName=This is an invalid name for a file or folder
-
-RenameSourceFolderRefactoring_blank=Name must not start or end with a blank
-RenameSourceFolderRefactoring_invalid_name=This is an invalid name for a file or folder
-RenameSourceFolderRefactoring_already_exists=An element with this name already exists
-RenameSourceFolderRefactoring_alread_exists=An element with this name already exists
-RenameSourceFolderRefactoring_rename=Rename Source Folder
-
-################ Rename Processors #########################################
-
-RenameResourceProcessor_name=Rename Resource
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.reorg
-#######################################
-MoveRefactoring_reorganize_elements=Reorganize elements
-
-DeleteRefactoring_delete_package_fragment_root= Deleting a package fragment root
-
-MoveCuUpdateCreator_update_imports=Update imports
-MoveCuUpdateCreator_searching=Searching for references to types in ''{0}''
-MoveCuUpdateCreator_update_references=Update references
-
-CopyRefactoring_cu_copyOf1=CopyOf{0}
-CopyRefactoring_cu_copyOfMore=Copy_{0}_of_{1}
-CopyRefactoring_resource_copyOf1=Copy of {0}
-CopyRefactoring_resource_copyOfMore=Copy ({0}) of {1}
-CopyRefactoring_package_copyOf1={0}.copy
-CopyRefactoring_package_copyOfMore={1}.copy{0}
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.structure
-#######################################
-ExtractSupertypeProcessor_computing_possible_types=Computing possible types...
-ExtractSupertypeProcessor_refactored_element_pattern=Extracted class: ''{0}''
-ExtractSupertypeProcessor_category_description=Changes to extract the new class
-ExtractSupertypeProcessor_extract_supertype=Extract Superclass
-ExtractSupertypeProcessor_subtypes_pattern=Sub types:
-ExtractSupertypeProcessor_descriptor_description=Extract superclass ''{0}'' from ''{1}''
-ExtractSupertypeProcessor_descriptor_description_short=Extract superclass ''{0}''
-ExtractSupertypeProcessor_checking=Checking preconditions...
-ExtractSupertypeProcessor_preparing=Preparing refactoring...
-ExtractSupertypeProcessor_category_name=Extract Superclass Changes
-ExtractSupertypeProcessor_add_supertype=Add extracted type
-ExtractSupertypeProcessor_unexpected_exception_on_layer=An unexpected exception occurred while creating working copies. See the error log for more details.
-ExtractSupertypeProcessor_unexpected_exception=An unexpected exception occurred while creating a change. See the error log for more details.
-
-PullUpRefactoring_Pull_Up=Pull Up
-PullUpRefactoring_no_java_lang_Object=Pull up is not available on members declared in 'Object'.
-PullUpRefactoring_not_this_type=Pull Up is not available on type ''{0}'', since it does not have super types to which members could be pulled up.
-PullUpRefactoring_category_name=Pull Up Changes
-PullUPRefactoring_no_all_binary=Pull up is not available on this type. All super types are binary.
-PullUPRefactoring_not_java_lang_object=Pull up is not available on this type. Type has no super types.
-PullUpRefactoring_final_fields=Moving final vars will result in compilation errors if they are not initialized on creation or in constructors
-PullUpRefactoring_checking_referenced_elements=Checking referenced elements...
-PullUpRefactoring_type_not_accessible=Type ''{0}'' referenced in one of the moved elements is not accessible from type ''{1}''
-PullUpRefactoring_field_not_accessible=Var ''{0}'' referenced in one of the moved elements is not accessible from type ''{1}''
-PullUpRefactoring_method_not_accessible=Function ''{0}'' referenced in one of the moved elements is not accessible from type ''{1}''
-PullUpRefactoring_different_method_return_type=Function ''{0}'' declared in type''{1}'' has a different return type than its moved counterpart, which will result in compile errors if you proceed
-PullUpRefactoring_different_field_type=Var ''{0}'' declared in type ''{1}'' has a different type than its moved counterpart
-PullUpRefactoring_lower_default_visibility=Function ''{0}'' declared in type ''{1}'' has visibility lower than ''default'', which will result in compile errors if you proceed
-PullUpRefactoring_lower_protected_visibility=Function ''{0}'' declared in type ''{1}'' has visibility lower than ''protected'', which will result in compile errors if you proceed
-PullUpRefactoring_checking=Checking preconditions...
-PullUpRefactoring_add_method_stub=Add function stub
-PullUpRefactoring_add_abstract_method=Add abstract function declaration
-PullUpRefactoring_make_target_abstract=Make destination class abstract
-PullUpRefactoring_calculating_required=Computing required members...
-PullUpRefactoring_category_description=Changes to pull up members
-PullUpRefactoring_Field_declared_in_class=Var ''{0}'' is declared in class ''{1}''. Moving it may result in changed program semantics.
-PullUpRefactoring_add_override_annotation=Add '@Override' annotation
-PullUpRefactoring_Method_declared_in_class=Function ''{0}'' is declared in class ''{1}''. Moving it may result in changed program semantics.
-PullUpRefactoring_field_cannot_be_accessed=Var ''{0}'' cannot be accessed from ''{1}''
-PullUpRefactoring_method_cannot_be_accessed=Function ''{0}'' cannot be accessed from ''{1}''
-PullUpRefactoring_Type_declared_in_class=Type ''{0}'' is declared in class ''{1}''. Moving it may result in changed program semantics.
-PullUpRefactoring_descriptor_description=Pull up members from ''{0}'' to ''{1}''
-PullUpRefactoring_descriptor_description_full=Pull up ''{0}'' from ''{1}'' to ''{2}''
-PullUpRefactoring_descriptor_description_short=Pull up ''{0}'' to ''{1}''
-PullUpRefactoring_descriptor_description_short_multiple=Pull up members to ''{0}''
-PullUpRefactoring_Type_variable_not_available=The type parameter ''{0}'' cannot be mapped to the super type ''{1}''
-PullUpRefactoring_Type_variable2_not_available=The type parameters ''{0}'' and ''{1}'' cannot be mapped to the super type ''{2}''
-PullUpRefactoring_Type_variable3_not_available=The type parameters ''{0}'', ''{1}'' and ''{2}'' cannot be mapped to the super type ''{3}''
-PullUpRefactoring_Type_variables_not_available=Several type parameters cannot be mapped to the super type ''{0}''
-PullUpRefactoring_non_final_pull_up_to_interface=Moving non-final vars to an interface will result in compile errors if they are not initialized on creation or in constructors
-PullUpRefactoring_incompatible_langauge_constructs=Moving ''{0}'' which contains annotations to destination type ''{1}'' will result in compile errors, since the destination is not J2SE 5.0 compatible.
-PullUpRefactoring_incompatible_language_constructs1=Moving ''{0}'' which contains varargs to destination type ''{1}'' will result in compile errors, since the destination is not J2SE 5.0 compatible.
-PullUpRefactoring_moving_static_method_to_interface=Moving ''{0}'' which is declared ''static'' will result in compile errors, since the interface function is hidden by the static function.
-
-MemberCheckUtil_signature_exists=Function ''{0}'' (with the same signature) already exists in type ''{1}'', which will result in compile errors if you proceed
-MemberCheckUtil_same_param_count=Function ''{0}'' (with the same number of parameters) already exists in type ''{1}''
-MemberCheckUtil_field_exists=Field ''{0}'' already exists in type ''{1}'', which will result in compile errors if you proceed
-MemberCheckUtil_type_name_conflict0=Nested type ''{0}'' already exists in type ''{1}'', which will result in compile errors if you proceed
-MemberCheckUtil_type_name_conflict1=Destination type has the same simple name as ''{0}'', which will result in compile errors if you proceed
-MemberCheckUtil_type_name_conflict2=Destination type is enclosed in a type that has the same simple name as ''{0}'', which will result in compile errors if you proceed
-MemberCheckUtil_type_name_conflict3=Destination type has the same simple name as ''{0}'' (enclosed in ''{1}''), which will result in compile errors if you proceed
-MemberCheckUtil_type_name_conflict4=Destination type is enclosed in a type that has the same simple name as ''{0}'' (enclosed in ''{1}''), which will result in compile errors if you proceed
-
-MoveMembersRefactoring_Move_Members=Move Members
-MoveMembersRefactoring_compile_errors=Operation cannot be performed due to compile errors in ''{0}''. To perform this operation you will need to fix the errors.
-MoveMembersRefactoring_deleteMembers= Delete members
-MoveMembersRefactoring_addMembers= Add members
-MoveMembersRefactoring_referenceUpdate= Update reference to moved member
-MoveMembersRefactoring_static_declaration=Static members can be declared only in top level or static types.
-MoveMembersRefactoring_check_availability=Check availability of members after move
-MoveMembersRefactoring_multi_var_fields=Only var declarations with single variable declaration fragments can be moved.
-MoveMembersRefactoring_only_public_static=Only 'public static' types and 'public static final' vars with variable initializers can be moved to an interface.
-MoveMembersRefactoring_Object=Move is not allowed on members declared in 'Object'.
-MoveMembersRefactoring_binary=Pull up is not allowed on members of binary types.
-MoveMembersRefactoring_read_only=Pull up is not allowed on members of read-only types.
-MoveMembersRefactoring_move_members=Move members
-MoveMembersRefactoring_not_found=Destination type ''{0}'' cannot be found
-MoveMembersRefactoring_same=Destination and source types are the same (''{0}'')
-MoveMembersRefactoring_inside=Destination type ''{1}'' is inside moved member''{0}''.
-MoveMembersRefactoring_not_exist=Destination type ''{0}'' does not exist
-MoveMembersRefactoring_dest_binary=Destination type ''{0}'' is binary
-MoveMembersRefactoring_native=Moved function ''{0}'' is native. You will need to update native libraries.
-MoveMembersRefactoring_moved_field=In ''{2}'', moved var ''{0}'' will not be visible from ''{1}''
-MoveMembersRefactoring_accessed_field=Accessed var ''{0}'' will not be visible from ''{1}''
-MoveMembersRefactoring_moved_method=In ''{2}'', moved function ''{0}'' will not be visible from ''{1}''
-MoveMembersRefactoring_accessed_method=Accessed function ''{0}'' will not be visible from ''{1}''
-MoveMembersRefactoring_moved_type=In ''{2}'', moved type ''{0}'' will not be visible from ''{2}''
-MoveMembersRefactoring_accessed_type=Accessed type ''{0}'' will not be visible from ''{1}''
-MoveMembersRefactoring_creating=Checking preconditions...
-MoveMembersRefactoring_checking=Checking preconditions...
-MoveRefactoring_scanning_qualified_names=Searching for qualified names...
-
-QualifiedNameFinder_update_name=Update qualified name
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.surround
-#######################################
-
-SurroundWithTryCatchRefactoring_name=Surround with try/catch Block
-SurroundWithTryCatchAnalyzer_doesNotCover=Selection does not cover a set of statements. Extend selection to a valid range using the "Expand Selection With" actions from the Edit menu.
-SurroundWithTryCatchAnalyzer_doesNotContain=Selection does not contain statements from a function body or static initializer.
-SurroundWithTryCatchAnalyzer_noUncaughtExceptions=No uncaught exceptions are thrown by the selected code.
-SurroundWithTryCatchAnalyzer_onlyStatements=Only statements can be surrounded with try/catch blocks.
-SurroundWithTryCatchAnalyzer_cannotHandleSuper=Cannot surround a super constructor call.
-SurroundWithTryCatchAnalyzer_cannotHandleThis=Cannot surround a constructor invocation.
-SurroundWithTryCatchAnalyzer_compile_errors=The selected code cannot be analyzed because of compilation errors. To perform this operation you will need to fix the errors.
-
-#######################################
-# org.eclipse.wst.jsdt.internal.core.refactoring.util
-#######################################
-
-CommentAnalyzer_internal_error=Internal error during precondition checking.
-CommentAnalyzer_ends_inside_comment=Selection ends inside a comment.
-CommentAnalyzer_starts_inside_comment=Selection begins inside a comment.
-
-StatementAnalyzer_doesNotCover=The selection does not cover a set of statements or an expression. Extend selection to a valid range using the "Expand Selection To" actions from the Edit menu.
-StatementAnalyzer_beginning_of_selection=The beginning of the selection contains characters that do not belong to a statement.
-StatementAnalyzer_end_of_selection=The end of the selection contains characters that do not belong to a statement.
-StatementAnalyzer_do_body_expression=Operation not applicable to a \'do\' statement's body and expression.
-StatementAnalyzer_for_initializer_expression=Operation not applicable to a \'for\' statement's initializer and expression part.
-StatementAnalyzer_for_expression_updater=Operation not applicable to a \'for\' statement's expression and updater part.
-StatementAnalyzer_for_updater_body=Operation not applicable to a \'for\' statement's updater and body part.
-StatementAnalyzer_catch_argument=Operation is not applicable to a catch block's argument declaration.
-StatementAnalyzer_while_expression_body=Operation not applicable to a while statement's expression and body.
-StatementAnalyzer_try_statement=Selection must either cover whole try statement or parts of try, catch, or finally block.
-StatementAnalyzer_switch_statement=Selection must either cover whole switch statement or parts of a single case block.
-StatementAnalyzer_synchronized_statement=Selection must either cover whole synchronized statement or parts of the synchronized block.
-
-CodeAnalyzer_array_initializer=Operation not applicable to an array initializer.
-JavaElementUtil_initializer=initializer
-
-#######################################
-# other
-#######################################
-CopyResourceString_copy=Copy resource ''{0}'' to ''{1}''
-
-RenameAnalyzeUtil_shadows=Problem in ''{0}''. Another name will shadow access to the renamed element
-RenameAnalyzeUtil_reference_shadowed=Problem in ''{0}''. The reference to ''{1}'' will be shadowed by a renamed declaration
-CopyRefactoring_update_ref=Update type reference
-CopyRefactoring_searching=Searching
-CodeRefactoringUtil_error_message=The body of the function ''{0}'' cannot be analyzed because of compilation errors in that function. To perform the operation you will need to fix the errors.
-InlineTemRefactoring_error_message_nulLiteralsCannotBeInlined=Null literals cannot be inlined
-InlineTemRefactoring_error_message_fieldsCannotBeInlined=Cannot inline vars
-
-HierarchyRefactoring_initializer=initializer
-HierarchyRefactoring_add_member=Add member declaration
-HierarchyRefactoring_remove_member=Remove member declaration
-HierarchyRefactoring_does_not_exist=One of the elements does not exist in the saved version of the file
-HierarchyRefactoring_gets_instantiated=Class ''{0}'' cannot be made abstract because it is instantiated
-HierarchyRefactoring_interface_members=Members in interfaces cannot be moved.
-HierarchyRefactoring_annotation_members=Members in annotations cannot be moved.
-HierarchyRefactoring_enum_members=Members in enumerations cannot be moved.
-HierarchyRefactoring_members_of_binary=Moving of members declared in binary types is not supported
-HierarchyRefactoring_members_of_read_only=Moving of members declared in read-only types is not supported
-
-PushDownRefactoring_name=Push Down
-PushDownRefactoring_no_subclasses=Push Down is not allowed on type ''{0}'', since it does not have subclasses to which members could be pushed down.
-PushDownRefactoring_category_name=Push Down Changes
-PushDownRefactoring_make_abstract=Make type abstract
-PushDownRefactoring_calculating_required=Calculating required members...
-PushDownRefactoring_category_description=Changes to push down members
-PushDownRefactoring_change_name=Push down
-PushDownRefactoring_referenced=Pushed down member ''{0}'' is referenced by ''{1}''
-PushDownRefactoring_check_references=Checking referenced elements...
-PushDownRefactoring_type_not_accessible=Type ''{0}'' referenced in one of the pushed elements is not accessible from type ''{1}''
-PushDownRefactoring_field_not_accessible=Var ''{0}'' referenced in one of the pushed elements is not accessible from type ''{1}''
-PushDownRefactoring_method_not_accessible=Function ''{0}'' referenced in one of the pushed elements is not accessible from type ''{1}''
-PushDownRefactoring_checking=Checking preconditions...
-PushDownRefactoring_descriptor_description=Push down members from ''{0}''
-PushDownRefactoring_pushed_members_pattern=Pushed members:
-PushDownRefactoring_descriptor_description_full=Push down ''{0}'' from ''{1}''
-PushDownRefactoring_descriptor_description_short_multi=Push down ''{0}''
-PushDownRefactoring_descriptor_description_short=Push down
-
-ChangeSignatureRefactoring_modify_Parameters=Change Function Signature
-ChangeSignatureRefactoring_restructure_parameters=Change Function Signature
-ChangeSignatureRefactoring_checking_preconditions=Checking preconditions...
-ChangeSignatureRefactoring_descriptor_description=Change function ''{0}'' to ''{1}''
-ChangeSignatureRefactoring_new_visibility_pattern=New visibility: ''{0}''
-ChangeSignatureRefactoring_descriptor_description_short=Change function ''{0}''
-ChangeSignatureRefactoring_method_deleted=The selected function has been deleted from ''{0}''.
-ChangeSignatureRefactoring_native=Function ''{0}'' declared in type ''{1}'' is native. Reordering parameters will cause UnsatisfiedLinkError on runtime if you do not update your native libraries.
-ChangeSignatureRefactoring_duplicate_name=Duplicate parameter name: ''{0}''.
-ChangeSignatureRefactoring_return_type_contains_type_variable=The return type ''{0}'' contains the type variable ''{1}'', which may not be available in related functions.
-ChangeSignatureRefactoring_method_name_not_empty=The function name cannot be empty.
-ChangeSignatureRefactoring_default_value=Enter the default value for parameter ''{0}''.
-ChangeSignatureRefactoring_default_visibility=(default)
-ChangeSignatureRefactoring_invalid_expression=''{0}'' is not a valid expression.
-ChangeSignatureRefactoring_parameter_type_contains_type_variable=The type ''{0}'' of parameter ''{1}'' contains the type variable ''{2}'', which may not be available in related functions.
-ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different=The old and new function signatures do not differ sufficiently for creating a delegate function. Delegate will introduce compile errors.
-ChangeSignatureRefactoring_unchanged=Function signature and return type are unchanged.
-ChangeSignatureRefactoring_parameter_used=Removed parameter ''{0}'' is used in function ''{1}'' declared in type ''{2}''.
-ChangeSignatureRefactoring_anonymous_subclass=anonymous subclass of ''{0}''
-ChangeSignatureRefactoring_removed_parameters=Removed parameters:
-ChangeSignatureRefactoring_removed_exceptions=Removed exceptions:
-ChangeSignatureRefactoring_non_virtual=Changing visibility to \'private\' will make this function non-virtual, which may affect the program\'s behavior.
-ChangeSignatureRefactoring_already_has=Function ''{0}'' already has a parameter named ''{1}''.
-ChangeSignatureRefactoring_preview=Preparing preview
-ChangeSignatureRefactoring_constructor_name=The function should not have the same name as the declaring type.
-ChangeSignatureRefactoring_no_exception_binding=Cannot resolve the type binding of a thrown exception. Compilation errors must be fixed before this refactoring can be performed.
-ChangeSignatureRefactoring_param_name_not_empty=Enter the name for parameter {0}.
-ChangeSignatureRefactoring_change_signature=Change signature
-ChangeSignatureRefactoring_changed_parameters=Changed parameters:
-ChangeSignatureRefactoring_update_reference=Update reference
-ChangeSignatureRefactoring_new_name_pattern=New name: ''{0}''
-ChangeSignatureRefactoring_update_parameter_references=Update parameter references
-ChangeSignatureRefactoring_update_javadoc_reference=Update JSDoc reference
-ChangeSignatureRefactoring_deleted_parameter_pattern={0} {1}
-ChangeSignatureRefactoring_changed_parameter_pattern={0} {1}
-ChangeSignatureRefactoring_new_return_type_pattern=New return type: ''{0}''
-ChangeSignatureRefactoring_added_parameter_pattern={0} {1}
-ChangeSignatureRefactoring_add_super_call=Add super constructor call
-ChangeSignatureRefactoring_add_constructor=Add constructor
-ChangeSignatureRefactoring_added_parameters=Added parameters:
-ChangeSignatureRefactoring_added_exceptions=Added exceptions:
-ChangeSignatureRefactoring_cannot_convert_vararg=The variable arity ellipsis (...) cannot be removed from the last parameter ''{0}''.
-ChangeSignatureRefactoring_vararg_must_be_last=The variable arity parameter ''{0}'' cannot be followed by another parameter.
-ChangeSignatureRefactoring_ripple_cannot_convert_vararg=The last parameter ''{0}'' must end with an ellipsis (...), since it is a variable arity parameter in type ''{1}''.
-
-TypeContextChecker_couldNotResolveType=Could not resolve type ''{0}''.
-TypeContextChecker_ambiguous=Parameter type name ''{0}'' is ambiguous. There are {1} types with that name.
-TypeContextChecker_not_unique=Parameter type name ''{0}'' cannot be uniquely resolved or is not a valid type name.
-TypeContextChecker_parameter_type=Enter the type for parameter ''{0}''.
-TypeContextChecker_no_vararg_below_50=''{0}'' is not a valid parameter type; variable arity parameters are only supported if the source level is 5.0.
-TypeContextChecker_invalid_type_name=''{0}'' is not a valid parameter type.
-TypeContextChecker_invalid_type_syntax=''{0}'' is not a valid parameter type: {1}.
-TypeContextChecker_return_type_not_empty=The return type cannot be empty.
-TypeContextChecker_invalid_return_type=''{0}'' is not a valid return type.
-TypeContextChecker_invalid_return_type_syntax=''{0}'' is not a valid return type: {1}.
-
-MoveInnerToTopRefactoring_names_start_lowercase=This name is discouraged. According to convention, names of instance vars and local variables start with a lowercase letter.
-MoveInnerToTopRefactoring_already_declared=A var named ''{0}'' is already declared in type ''{1}''
-MoveInnerToTopRefactoring_compilation_Unit_exists=A JavaScript file named ''{0}'' already exists in package ''{1}''
-MoveInnerToTopRefactoring_name_used=Name ''{0}'' is used as a parameter name in one of the constructors of type ''{1}''
-MoveInnerToTopRefactoring_name=Convert Member Type to Top Level
-MoveInnerToTopRefactoring_creating_change=Creating change
-MoveInnerToTopRefactoring_update_type_reference=Update type reference
-MoveInnerToTopRefactoring_descriptor_description=Convert member type ''{0}'' in ''{1}'' to top level type
-MoveInnerToTopRefactoring_descriptor_description_short=Convert member type ''{0}'' to top level
-MoveInnerToTopRefactoring_update_constructor_reference=Update constructor occurrence
-MoveInnerToTopRefactoring_move_to_Top=Convert Member Type to Top Level
-MoveInnerToTopRefactoring_change_visibility=Change visibility to default
-MoveInnerToTopRefactoring_parameter_pattern=Parameter name: ''{0}''
-MoveInnerToTopRefactoring_change_visibility_type_warning=The visibility of type ''{0}'' will be changed to default.
-MoveInnerToTopRefactoring_change_visibility_method_warning=The visibility of function ''{0}'' will be changed to default.
-MoveInnerToTopRefactoring_change_visibility_constructor_warning=The visibility of constructor ''{0}'' will be changed to default.
-MoveInnerToTopRefactoring_change_visibility_field_warning=The visibility of var ''{0}'' will be changed to default.
-MoveInnerToTopRefactoring_change_qualifier=Qualify class name
-MoveInnerToTopRefactoring_type_exists=Type named ''{0}'' already exists in package ''{1}''
-
-UseSupertypeWherePossibleRefactoring_name=Use Supertype Where Possible
-UseSuperTypeProcessor_name=Use Supertype
-UseSuperTypeProcessor_internal_error=Internal error during precondition checking. Consult log for detailed error description.
-UseSuperTypeProcessor_descriptor_description=Use super type ''{0}'' instead of ''{1}''
-UseSuperTypeProcessor_descriptor_description_short=Use super type ''{0}''
-UseSuperTypeProcessor_refactored_element_pattern=Super type: ''{0}''
-UseSuperTypeProcessor_creating=Checking preconditions...
-UseSuperTypeProcessor_checking=Checking preconditions...
-
-SuperTypeRefactoringProcessor_creating=Checking preconditions...
-SuperTypeRefactoringProcessor_category_name=Use Supertype Changes
-SuperTypeRefactoringProcessor_update_type_occurrence=Update type occurrence
-SuperTypeRefactoringProcessor_user_supertype_setting=Use super type where possible
-SuperTypeRefactoringProcessor_use_in_instanceof_setting=Use super type in 'instanceof' expressions
-SuperTypeRefactoringProcessor_category_description=Changes to replace type by supertype
-
-MoveInstanceMethodRefactoring_name=Move Function
-MoveInstanceMethodProcessor_name= Move Function
-MoveInstanceMethodProcessor_no_static_methods=This refactoring cannot be used to move static functions.
-MoveInstanceMethodProcessor_single_implementation=This refactoring cannot be used to move abstract functions.
-MoveInstanceMethodProcessor_no_native_methods=This refactoring cannot be used to move native functions.
-MoveInstanceMethodProcessor_no_synchronized_methods=This refactoring cannot be used to move synchronized functions.
-MoveInstanceMethodProcessor_no_constructors=This refactoring cannot be used to move a constructor.
-MoveInstanceMethodProcessor_uses_super=The function cannot be moved, since it uses the 'super' keyword.
-MoveInstanceMethodProcessor_refers_enclosing_instances=The function cannot be moved, since it has references to enclosing instances.
-MoveInstanceMethodProcessor_potentially_recursive=This refactoring cannot be used to move potentially recursive functions.
-MoveInstanceMethodProcessor_cannot_be_moved=This function cannot be moved, since no possible targets have been found. An instance function can be moved to source classes that are used as types of its parameters or types of vars declared in the same class as the function.
-MoveInstanceMethodProcessor_no_type_variables=This function cannot be moved, since it contains references to non-local type parameters.
-MoveInstanceMethodProcessor_no_generic_targets=This function cannot be moved to the specified target, since the target is a generic entity.
-MoveInstanceMethodProcessor_no_binary=Cannot move functions to binary types.
-MoveInstanceMethodProcessor_no_interface=This refactoring cannot be used to move interface functions.
-MoveInstanceMethodProcessor_no_annotation=This refactoring cannot be used to move annotation functions.
-MoveInstanceMethodProcessor_this_reference=A reference to 'this' has been found
-MoveInstanceMethodProcessor_no_resolved_target=The target of the function could not be resolved.
-MoveInstanceMethodProcessor_no_null_argument=The function invocation ''{0}'' cannot be updated, since it uses ''null'' as argument.
-MoveInstanceMethodProcessor_target_name_already_used=The name of the target conflicts with the function parameter ''{0}''.
-MoveInstanceMethodProcessor_target_element_pattern=Target element: ''{0}''
-MoveInstanceMethodProcessor_replace_body_with_delegation=Create delegate function
-MoveInstanceMethodProcessor_present_type_parameter_warning=The type parameter ''{0}'' is already present in the target type ''{1}'' and will be removed from the function.
-MoveInstanceMethodProcessor_remove_original_method=Remove function declaration
-MoveInstanceMethodProcessor_inline_method_invocation=Update function invocation
-MoveInstanceMethodProcessor_deprecate_delegator_method=Deprecate delegate function
-MoveInstanceMethodProcessor_deprecate_delegator_message=Use {0} instead
-MoveInstanceMethodProcessor_add_moved_method=Add function declaration
-MoveInstanceMethodProcessor_inline_binary_project=The function invocations to the moved function in project ''{0}'' cannot be updated, since the project is binary.
-MoveInstanceMethodProcessor_inline_binary_resource=The function invocations to the moved function in resource ''{0}'' cannot be updated.
-MoveInstanceMethodProcessor_javadoc_binary_project=JSDoc references to the moved function in project ''{0}'' cannot be updated, since the project is binary.
-MoveInstanceMethodProcessor_descriptor_description=Move function ''{0}'' to ''{1}''
-MoveInstanceMethodProcessor_parameter_name_pattern=Parameter name: ''{0}''
-MoveInstanceMethodProcessor_descriptor_description_short=Move function ''{0}''
-MoveInstanceMethodProcessor_javadoc_binary_resource=JSDoc references to the moved function in resource ''{0}'' cannot be updated.
-MoveInstanceMethodProcessor_inline_inaccurate=A function invocation to the original function in ''{0}'' could not be fully resolved.
-MoveInstanceMethodProcessor_inline_overridden=The function invocations to ''{0}'' cannot be updated, since the original function is used polymorphically.
-MoveInstanceMethodProcessor_method_already_exists=A function with name ''{0}'' already exists in the target type ''{1}''.
-MoveInstanceMethodProcessor_moved_element_pattern=Moved function: {0}
-MoveInstanceMethodProcessor_method_type_clash=The function cannot have the same name as its target type ''{0}''.
-MoveInstanceMethodProcessor_method_name_pattern=Function name: ''{0}''
-MoveInstanceMethodProcessor_creating=Checking preconditions...
-MoveInstanceMethodProcessor_checking=Checking preconditions...
-
-ExtractInterfaceRefactoring_name=Extract Interface
-ExtractInterfaceProcessor_name= Extract Interface
-ExtractInterfaceProcessor_no_binary=Cannot extract interfaces from binary types.
-ExtractInterfaceProcessor_no_annotation=Cannot extract interfaces from annotations.
-ExtractInterfaceProcessor_no_anonymous=Cannot extract interfaces from anonymous types.
-ExtractInterfaceProcessor_add_comment=Add function comment
-ExtractInterfaceProcessor_existing_type=A type named ''{0}'' already exists in package ''{1}''
-ExtractInterfaceProcessor_category_name=Extract Interface Changes
-ExtractInterfaceProcessor_existing_default_type=A type named ''{0}'' already exists in the default package
-ExtractInterfaceProcessor_category_description=Changes to extract the new interface
-ExtractInterfaceProcessor_remove_field_label=Remove var declaration
-ExtractInterfaceProcessor_remove_method_label=Remove function declaration
-ExtractInterfaceProcessor_add_super_interface=Add super interface
-ExtractInterfaceProcessor_descriptor_description=Extract interface ''{0}'' from ''{1}''
-ExtractInterfaceProcessor_description_descriptor_short=Extract interface ''{0}''
-ExtractInterfaceProcessor_existing_compilation_unit=A JavaScript file named ''{0}'' already exists in package ''{1}''
-ExtractInterfaceProcessor_extracted_members_pattern=Extracted members:
-ExtractInterfaceProcessor_refactored_element_pattern=Extracted interface: ''{0}''
-ExtractInterfaceProcessor_internal_error=An internal error occurred during precondition checking. See the error log for more details.
-ExtractInterfaceProcessor_rewrite_comment=Rewrite function comment
-ExtractInterfaceProcessor_creating=Checking preconditions...
-ExtractInterfaceProcessor_checking=Checking preconditions...
-
-#Begin - Do not remove
-MemberVisibilityAdjustor_binary_outgoing_project=The elements in project ''{0}'' referenced from ''{1}'' cannot be updated, since the project is binary.
-MemberVisibilityAdjustor_binary_outgoing_resource=The elements in resource ''{0}'' referenced from ''{1}'' cannot be updated.
-MemberVisibilityAdjustor_change_visibility_type_warning=The visibility of type ''{0}'' will be changed to {1}.
-MemberVisibilityAdjustor_change_visibility_method_warning=The visibility of function ''{0}'' will be changed to {1}.
-MemberVisibilityAdjustor_change_visibility_field_warning=The visibility of var ''{0}'' will be changed to {1}.
-#End - Do not remove
-MemberVisibilityAdjustor_change_visibility_default=default
-MemberVisibilityAdjustor_change_visibility_public=public
-MemberVisibilityAdjustor_change_visibility_protected=protected
-MemberVisibilityAdjustor_change_visibility_private=private
-MemberVisibilityAdjustor_change_visibility=Change visibility to {0}
-
-MemberVisibilityAdjustor_adjusting=Adjusting visibility...
-MemberVisibilityAdjustor_checking=Checking visibility...
-
-MemberVisibilityAdjustor_adjustments_name=Visibility Changes
-MemberVisibilityAdjustor_adjustments_description=Changes to adjust the visibility of elements
-
-CopyPackageFragmentRootChange_copy=Copy source folder ''{0}'' to project ''{1}''
-
-DeletePackageFragmentRootChange_delete=Delete source folder ''{0}''
-DeletePackageFragmentRootChange_restore_file=Restore file ''{0}''
-
-DelegateCreator_use_member_instead=Use {0} instead
-DelegateCreator_change_category_title=Keep Original Function Changes
-DelegateCreator_change_category_description=Changes to keep the original member as delegate to new member
-DelegateCreator_keep_original_changed_plural=&Keep original functions as delegates to changed functions
-DelegateCreator_cannot_create_field_delegate_not_final=Cannot create delegate for var ''{0}'' - var is not final.
-DelegateCreator_cannot_create_field_delegate_no_initializer=Cannot create delegate for var ''{0}'' - not initializer found.
-DelegateCreator_cannot_create_field_delegate_more_than_one_fragment=Cannot add delegate for var ''{0}'' - more than one fragment in this declaration.
-DelegateCreator_cannot_create_delegate_for_type=Cannot create a delegate for type ''{0}'' - delegate creation is not available for types.
-DelegateCreator_keep_original_changed_singular=&Keep original function as delegate to changed function
-
-DelegateMethodCreator_text_edit_group_field=Keep original function as delegate
-DelegateMethodCreator_keep_original_renamed_plural=&Keep original functions as delegates to renamed functions
-DelegateMethodCreator_keep_original_moved_plural=&Keep original functions as delegates to moved functions
-DelegateMethodCreator_keep_original_moved_singular=&Keep original function as delegate to moved function
-DelegateMethodCreator_keep_original_renamed_singular=&Keep original function as delegate to renamed function
-DelegateFieldCreator_text_edit_group_label=Keep original var as delegate
-DelegateFieldCreator_keep_original_renamed_plural=&Keep original vars as delegates to renamed vars
-DelegateFieldCreator_keep_original_renamed_singular=&Keep original var as delegate to renamed var
-
-MovePackageFragmentRootChange_move=Move Package Fragment Root ''{0}'' to project ''{1}''
-
-PromoteTempToFieldRefactoring_name=Convert Local Variable to Var
-PromoteTempToFieldRefactoring_select_declaration=Select a declaration or a reference to a local variable.
-PromoteTempToFieldRefactoring_default_visibility=(default)
-PromoteTempToFieldRefactoring_visibility_pattern=Declared visibility: ''{0}''
-PromoteTempToFieldRefactoring_only_declared_in_methods=Only local variables declared in functions can be converted to vars.
-PromoteTempToFieldRefactoring_method_parameters=Cannot convert function parameters to vars.
-PromoteTempToFieldRefactoring_original_pattern=Original element: ''{0}''
-PromoteTempToFieldRefactoring_initialize_method=Initialize var in function
-PromoteTempToFieldRefactoring_exceptions=Cannot convert exceptions declared in catch clauses to vars.
-PromoteTempToFieldRefactoring_uses_types_declared_locally=Cannot convert this local variable to a var because it uses types or variables declared locally in the function.
-PromoteTempToFieldRefactoring_cannot_promote=Cannot convert this local variable to a var.
-PromoteTempToFieldRefactoring_declare_static=Declare var 'static'
-PromoteTempToFieldRefactoring_uses_type_declared_locally=Cannot convert this local variable to a var because it uses a type declared locally in the function.
-PromoteTempToFieldRefactoring_Name_conflict=Name conflict with name ''{0}'' used in ''{1}''
-PromoteTempToFieldRefactoring_field_pattern=Var name: ''{0}''
-PromoteTempToFieldRefactoring_declare_final=Declare var 'final'
-PromoteTempToFieldRefactoring_Name_conflict_with_field=Name conflict with existing var
-PromoteTempToFieldRefactoring_descriptor_description=Convert local variable ''{0}'' in ''{1}'' to var
-PromoteTempToFieldRefactoring_descriptor_description_short=Convert local variable ''{0}'' to var
-PromoteTempToFieldRefactoring_initialize_constructor=Initialize var in class constructor
-PromoteTempToFieldRefactoring_initialize_declaration=Initialize var in declaration
-PromoteTempToFieldRefactoring_declare_final_static=Declare var 'final' and 'static'
-PromoteTempToFieldRefactoring_editName=Convert local variable to var
-
-ConvertAnonymousToNestedRefactoring_name=Convert Anonymous Class to Nested
-ConvertAnonymousToNestedRefactoring_place_caret=Place the caret inside an anonymous class.
-ConvertAnonymousToNestedRefactoring_type_exists=Nested type with that name already exists.
-ConvertAnonymousToNestedRefactoring_another_name=Choose another name.
-ConvertAnonymousToNestedRefactoring_name_hides=Class name hides an enclosing type name.
-ConvertAnonymousToNestedRefactoring_compile_errors=This refactoring cannot be performed due to compile errors in the JavaScript file. To perform this operation you will need to fix the errors.
-ConvertAnonymousToNestedRefactoring_declare_final=Declare class \'final\'
-ConvertAnonymousToNestedRefactoring_declare_static=Declare class \'static\'
-ConvertAnonymousToNestedRefactoring_anonymous_field_access=Class accesses vars in enclosing anonymous type. The refactored code will not compile.
-ConvertAnonymousToNestedRefactoring_descriptor_description=Convert anonymous class ''{0}'' in ''{1}'' to nested class
-ConvertAnonymousToNestedRefactoring_descriptor_description_short=Convert anonymous class to nested
-ConvertAnonymousToNestedRefactoring_declare_final_static=Declare class \'final\' and \'static\'
-ConvertAnonymousToNestedRefactoring_edit_name=Convert anonymous class to nested class
-ConvertAnonymousToNestedRefactoring_extends_local_class=Cannot convert this anonymous class to a nested class since it extends a local class.
-ConvertAnonymousToNestedRefactoring_class_name_pattern=Class name: ''{0}''
-ConvertAnonymousToNestedRefactoring_visibility_pattern=Declared visibility: ''{0}''
-ConvertAnonymousToNestedRefactoring_default_visibility=(default)
-ConvertAnonymousToNestedRefactoring_original_pattern=Original element: ''{0}''
-
-InlineConstantRefactoring_members_declared_in_anonymous=Cannot inline since the initializer to be inlined refers to members declared in an anonymous class scope (not supported).
-InlineConstantRefactoring_Inline=Inline Constant
-InlineConstantRefactoring_syntax_errors=This file contains syntax errors. To perform this operation you will need to fix the errors.
-InlineConstantRefactoring_local_anonymous_unsupported=Inlining of constants defined in local or anonymous classes is not supported.
-InlineConstantRefactoring_static_final_field=A static final var must be selected.
-InlineConstantRefactoring_blank_finals=Inline Constant cannot inline blank finals.
-InlineConstantRefactoring_binary_file=Cannot inline this constant, since it is declared in a binary file.
-InlineConstantRefactoring_preview=Generating preview ...
-InlineConstantRefactoring_inline=Inline Constant
-InlineConstantRefactoring_remove_declaration=Remove constant declaration
-InlineConstantRefactoring_original_pattern=Original element: ''{0}''
-InlineConstantRefactoring_replace_references=Replace all references to constant with expression
-InlineConstantRefactoring_name=Inline Constant
-InlineConstantRefactoring_source_code_unavailable=References in ''{0}'' cannot be inlined since source code is not available
-InlineConstantRefactoring_descriptor_description=Inline constant ''{0}'' in ''{1}''
-InlineConstantRefactoring_descriptor_description_short=Inline constant ''{0}''
-
-DeleteFileChange_1=Delete file ''{0}''
-
-DeleteFolderChange_0=Delete folder ''{0}''
-
-DeleteSourceManipulationChange_0=Delete ''{0}''
-DeleteSourceManipulationChange_1=./
-
-JavaCopyProcessor_changeName=Copy
-JavaMoveProcessor_change_name=Move
-JavaCopyProcessor_processorName=Copy
-
-MoveRefactoring_0=Move
-
-OverwriteHelper_0=Confirm Overwriting
-OverwriteHelper_1=''{0}'' exists in the selected destination. Do you want to overwrite?
-
-OverwriteHelper_2=Element exists in Destination
-OverwriteHelper_3=The element ''{0}'' exists in the selected destination. You can either skip the element or cancel the whole operation.
-
-ReadOnlyResourceFinder_0=Confirm Delete of Read-Only Elements
-ReadOnlyResourceFinder_1=The selected elements contain read-only resources. Do you still want to delete them?
-ReadOnlyResourceFinder_2=Confirm Move of Read-Only Elements
-ReadOnlyResourceFinder_3=The selected elements contain read-only resources. Do you still want to move them?
-
-MoveInnerToTopRefactoring_creating_preview=Creating preview
-MoveInnerToTopRefactoring_original_pattern=Original element: ''{0}''
-MoveInnerToTopRefactoring_change_label=Convert Member Type to Top Level
-MoveInnerToTopRefactoring_field_pattern=Var name: ''{0}''
-MoveInnerToTopRefactoring_declare_final=Declare var 'final'
-
-# ---- Reorg
-ReorgPolicy_copy=Copy Resources
-ReorgPolicy_copy_source_folder=Copy Source Folders
-ReorgPolicy_copy_package=Copy Packages
-ReorgPolicy_move_source_folder=Move Source Folders
-ReorgPolicy_move_package=Move Packages
-ReorgPolicy_move=Move Resources
-ReorgPolicy_move_members=Move Elements
-ReorgPolicyFactory_doesnotexist0=The selected element cannot be the destination of this operation
-ReorgPolicyFactory_readonly=The selected destination is read-only
-ReorgPolicyFactory_structure=The structure of the selected destination is not known
-ReorgPolicyFactory_inconsistent=The selected destination is not consistent with its underlying resource or buffer
-ReorgPolicyFactory_archive=The selected destination is an archive
-ReorgPolicyFactory_external=The selected destination is external to the workbench
-ReorgPolicyFactory_phantom=The selected destination does not exist or is a phantom resource
-ReorgPolicyFactory_inaccessible=The selected destination is not accessible
-ReorgPolicyFactory_not_this_resource=The selected resource cannot be used as a destination
-ReorgPolicyFactory_copy_roots_plural=Copy source folders
-ReorgPolicyFactory_copy_roots_header=Copy {0} source folder(s) to ''{1}''
-ReorgPolicyFactory_copy_initializers=Copy initializers
-ReorgPolicyFactory_copy_initializer=Copy initializer
-ReorgPolicyFactory_move_roots_plural=Move source folders
-ReorgPolicyFactory_move_roots_header=Move {0} source folder(s) to ''{1}''
-ReorgPolicyFactory_move_initializers=Move initializers
-ReorgPolicyFactory_move_initializer=Move initializer
-ReorgPolicyFactory_copy_description_plural=Copy elements
-ReorgPolicyFactory_copy_roots_singular=Copy source folder
-ReorgPolicyFactory_copy_import_section=Copy import section
-ReorgPolicyFactory_copy_packages_plural=Copy packages
-ReorgPolicyFactory_copy_package_singular=Copy package
-ReorgPolicyFactory_copy_package_declarations=Copy package declarations
-ReorgPolicyFactory_copy_compilation_unit=Copy JavaScript file
-ReorgPolicyFactory_copy_elements_singular=Copy element
-ReorgPolicyFactory_copy_compilation_units=Copy JavaScript files
-ReorgPolicyFactory_copy_import_containers=Copy import sections
-ReorgPolicyFactory_copy_packages_header=Copy {0} package(s) to ''{1}''
-ReorgPolicyFactory_copy_elements_plural=Copy elements
-ReorgPolicyFactory_copy_elements_header=Copy {0} element(s) to ''{1}''
-ReorgPolicyFactory_copy_description_singular=Copy element
-ReorgPolicyFactory_move_description_plural=Move elements
-ReorgPolicyFactory_move_import_declaration=Move import declaration
-ReorgPolicyFactory_move_packages_singular=Move package
-ReorgPolicyFactory_move_package_declarations=Move package declarations
-ReorgPolicyFactory_move_package_declaration=Move package declaration
-ReorgPolicyFactory_move_elements_singular=Move element
-ReorgPolicyFactory_move_compilation_units=Move JavaScript files
-ReorgPolicyFactory_move_import_containers=Move import sections
-ReorgPolicyFactory_move_roots_singular=Move source folder
-ReorgPolicyFactory_move_import_section=Move import section
-ReorgPolicyFactory_move_packages_plural=Move packages
-ReorgPolicyFactory_move_packages_header=Move {0} package(s) to ''{1}''
-ReorgPolicyFactory_move_elements_plural=Move elements
-ReorgPolicyFactory_move_elements_header=Move {0} element(s) to ''{1}''
-ReorgPolicyFactory_move_compilation_unit=Move JavaScript file
-ReorgPolicyFactory_move_description_singular=Move element
-ReorgPolicyFactory_move_import_declarations=Move import declarations
-ReorgPolicyFactory_linked=Linked resources can only be copied to projects
-ReorgPolicyFactory_no_resource=A resource cannot be the destination for the selected elements.
-ReorgPolicyFactory_copy_header=Copy {0} elements(s) to ''{1}''
-ReorgPolicyFactory_copy_folders=Copy folders
-ReorgPolicyFactory_copy_methods=Copy functions
-ReorgPolicyFactory_copy_imports=Copy import declarations
-ReorgPolicyFactory_copy_package=Copy package declaration
-ReorgPolicyFactory_copy_files=Copy files
-ReorgPolicyFactory_copy_types=Copy types
-ReorgPolicyFactory_copy_field=Copy var
-ReorgPolicyFactory_copy_folder=Copy folder
-ReorgPolicyFactory_copy_fields=Copy vars
-ReorgPolicyFactory_copy_method=Copy function
-ReorgPolicyFactory_copy_import=Copy import declaration
-ReorgPolicyFactory_copy_file=Copy file
-ReorgPolicyFactory_copy_type=Copy type
-ReorgPolicyFactory_move_header=Move {0} elements(s) to ''{1}''
-ReorgPolicyFactory_move_folders=Move folders
-ReorgPolicyFactory_move_methods=Move functions
-ReorgPolicyFactory_move_files=Move files
-ReorgPolicyFactory_move_types=Move types
-ReorgPolicyFactory_move_field=Move var
-ReorgPolicyFactory_move_folder=Move folder
-ReorgPolicyFactory_move_fields=Move vars
-ReorgPolicyFactory_move_method=Move function
-ReorgPolicyFactory_move_file=Move file
-ReorgPolicyFactory_move_type=Move type
-ReorgPolicyFactory_doesnotexist1=The selected element cannot be the destination for this operation
-ReorgPolicyFactory_cannot_modify=The selected destination element cannot be modified
-ReorgPolicyFactory_cannot=The selected element cannot be the destination for this operation
-ReorgPolicyFactory_package_decl=Package declarations are not available as destinations
-ReorgPolicyFactory_src2proj=Source folders can only be copied to Java projects
-ReorgPolicyFactory_jmodel=The Java Model cannot be the destination of this operation
-ReorgPolicyFactory_src2writable=Source folders cannot be copied to read-only elements
-ReorgPolicyFactory_src2nosrc=Source folders cannot be copied or moved to projects that contain no source folders
-ReorgPolicyFactory_packages=Packages can only be moved or copied to source folders or Java projects that do not have source folders
-ReorgPolicyFactory_cannot1=The selected element cannot be the destination of this operation
-ReorgPolicyFactory_noCopying=Copying is not available
-ReorgPolicyFactory_element2parent=Elements cannot be moved to their own parents.
-ReorgPolicyFactory_package2parent=A package cannot be moved to its own parent.
-ReorgPolicyFactory_parent=A file or folder cannot be moved to its own parent.
-ReorgPolicyFactory_noMoving=Moving is not available
-
-ReorgUtils_0=file ''{0}''
-ReorgUtils_1=folder ''{0}''
-ReorgUtils_2=project ''{0}''
-ReorgUtils_3=class file ''{0}''
-ReorgUtils_4=file ''{0}''
-ReorgUtils_5=var ''{0}''
-ReorgUtils_6=the import container
-ReorgUtils_7=import declaration ''{0}''
-ReorgUtils_8=the initializer
-ReorgUtils_9=Java project ''{0}''
-ReorgUtils_10=constructor ''{0}''
-ReorgUtils_11=function ''{0}''
-ReorgUtils_12=package declaration ''{0}''
-ReorgUtils_13=the default package
-ReorgUtils_14=package ''{0}''
-ReorgUtils_15=source folder ''{0}''
-ReorgUtils_16=class folder ''{0}''
-ReorgUtils_17=package fragment root ''{0}''
-ReorgUtils_18=type ''{0}''
-ReorgUtils_19=new {0}() '{'...}
-ReorgUtils_20=anonymous type ''{0}''
-DeleteChangeCreator_1=Delete elements
-
-DeleteRefactoring_1=Analyzing...
-DeleteRefactoring_2=Confirm Referenced Archive Delete
-DeleteRefactoring_3=Archive file ''{0}'' is referenced by the following project(s). Do you still want to delete it?
-DeleteRefactoring_4=Confirm Folder Delete
-DeleteRefactoring_5=Folder ''{0}'' contains a Java source folder. Deleting it will delete the source folder as well. Do you still wish to delete it?
-DeleteRefactoring_7=Delete
-DeleteRefactoring_8=Confirm Delete of Getters/Setters
-DeleteRefactoring_9=Do you also want to delete getter/setter functions for var ''{0}''?
-JavaDeleteProcessor_unsaved_changes= File ''{0}'' has unsaved changes.
-JavaDeleteProcessor_creating_change=Creating change...
-JavaDeleteProcessor_description_singular=Delete element
-JavaDeleteProcessor_description_plural=Delete elements
-JavaDeleteProcessor_project_pattern=project ''{0}''
-JavaDeleteProcessor_workspace=workspace
-JavaDeleteProcessor_header=Delete {0} element(s) from {1}
-JavaDeleteProcessor_delete_subpackages=Delete subpackages
-JavaDeleteProcessor_delete_accessors=Delete getters and setters
-JavaDeleteProcessor_confirm_linked_folder_delete=Confirm Linked Folder Delete
-JavaDeleteProcessor_delete_linked_folder_question=Are you sure you want to delete the linked package ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.
-
-JavaRefactoringDescriptor_initialization_error=The refactoring ''{0}'' cannot be initialized, since it does not implement the interface ''IScriptableRefactoring''.
-JavaRefactoringDescriptor_update_references=Update references to refactored element
-JavaRefactoringDescriptor_rename_similar=Rename similarly named elements
-JavaRefactoringDescriptor_qualified_names=Update fully qualified names in non-Java files
-JavaRefactoringDescriptor_keep_original=Keep original element as delegate to refactored element
-JavaRefactoringDescriptor_not_available=N/A
-JavaRefactoringDescriptor_rename_similar_suffix=Rename similarly named elements, also find name suffixes
-JavaRefactoringDescriptor_textual_occurrences=Update textual occurrences in comments and strings
-JavaRefactoringDescriptor_inferred_setting_pattern=- {0}
-JavaRefactoringDescriptor_original_element_pattern=Original element: ''{0}''
-JavaRefactoringDescriptor_original_elements=Original elements:
-JavaRefactoringDescriptor_renamed_element_pattern=Renamed element: ''{0}''
-JavaRefactoringDescriptor_rename_similar_embedded=Rename similarly named elements, also find embedded names
-JavaRefactoringDescriptor_qualified_names_pattern=Update fully qualified names in ''{0}'' files
-JavaRefactoringDescriptor_keep_original_deprecated=Keep original element as deprecated delegate to refactored element
-JavaRefactoringDescriptorComment_element_delimiter=\ \ \ \ \
-JavaRefactoringDescriptorComment_textual_move_only=Textual move only
-JavaRefactoringDescriptorComment_destination_pattern=Destination element: ''{0}''
-JavaRefactoringDescriptorComment_original_project=- Original project: ''{0}''
-
-MoveStaticMemberAnalyzer_nonStatic=Replacing non-static access to static member with static access
-MoveStaticMembersProcessor_descriptor_description_single=Move ''{0}'' to ''{1}''
-MoveStaticMembersProcessor_description_descriptor_short_multi=Move member ''{0}''
-MoveStaticMembersProcessor_descriptor_description_multi=Move {0} members to ''{1}''
-MoveStaticMembersProcessor_target_element_pattern=Destination type: ''{0}''
-
-#
-# Introduce Factory
-IntroduceFactory_name=Introduce Factory
-IntroduceFactory_checkingActivation=Checking preconditions...
-IntroduceFactory_syntaxError=Syntax errors in JavaScript file; unable to proceed.
-IntroduceFactory_checking_preconditions=Checking preconditions...
-IntroduceFactory_examiningSelection=Examining selection...
-IntroduceFactory_notAConstructorInvocation=Selected entity is not a constructor invocation or definition.
-#
-IntroduceFactory_noASTNodeForConstructorSearchHit=Cannot find AST node for constructor search hit @ [''{0}'', ''{1}'']: <''{2}''> in JavaScript file ''{3}''
-IntroduceFactory_unexpectedInitializerNodeType=Unexpected AST node type for initializer when searching for constructor call: ''{0}'' in JavaScript file ''{1}''
-IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl=Could not find AST node for constructor call inside ''{0}''
-IntroduceFactoryRefactoring_descriptor_description_short=Introduce factory for ''{0}''
-IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit=Unexpected AST node type for constructor search hit: ''{0}'' in JavaScript file ''{1}''
-IntroduceFactory_noBindingForSelectedConstructor=Could not resolve binding of selected constructor; possibly a reference to an unknown type.
-#
-IntroduceFactory_addFactoryMethod=Add factory function
-IntroduceFactory_replaceCalls=Replace constructor calls with calls to factory function
-IntroduceFactory_protectConstructor=Protect constructor
-#
-IntroduceFactory_unsupportedNestedTypes=Introduce Factory does not support constructors on nested types.
-IntroduceFactory_duplicateMethodName=Duplicate function name:
-IntroduceFactory_createChanges=Creating changes...
-IntroduceFactory_constructorInBinaryClass=Introduce Factory is not supported when the constructor is in a binary class.
-IntroduceFactoryRefactoring_owner_pattern=Owner class: ''{0}''
-IntroduceFactory_unableToResolveConstructorBinding=Unable to resolve call target; check for possible compilation errors
-IntroduceFactory_callSitesInBinaryClass=Constructor call sites in binary classes cannot be replaced by factory function calls.
-IntroduceFactory_descriptor_description=Introduce factory ''{0}'' in ''{1}'' for constructor ''{2}''
-IntroduceFactory_noSuchClass=Class ''{0}'' does not exist.
-IntroduceFactory_cantPutFactoryMethodOnInterface=Cannot place factory function on an interface
-IntroduceFactory_cantPutFactoryMethodOnAnnotation=Cannot place factory function on an annotation
-IntroduceFactory_cantCheckForInterface=Unable to determine whether factory type is an interface
-IntroduceFactory_cantPutFactoryInBinaryClass=Cannot place factory inside binary class
-IntroduceFactoryRefactoring_original_pattern=Original element: ''{0}''
-IntroduceFactoryRefactoring_factory_pattern=Factory name: ''{0}''
-IntroduceFactoryRefactoring_declare_private=Declare original constructor 'private'
-IntroduceFactory_constructorInEnum=Introduce Factory is not supported for constructors of enumerated types.
-
-#--- Generalize Declared Type
-ChangeTypeRefactoring_Generalize_Type=Generalize Declared Type
-ChangeTypeRefactoring_checking_preconditions=Checking preconditions...
-ChangeTypeRefactoring_changes=Computing changes
-ChangeTypeRefactoring_name=Generalize Declared Type
-ChangeTypeRefactoring_cantDoIt=Type of selected declaration cannot be changed
-ChangeTypeRefactoring_notSupportedOnNodeType=Generalize Declared Type is only supported on declarations of variables, parameters, and vars, and on function return types.
-ChangeTypeRefactoring_notSupportedOnBinary=Generalize Declared Type is not allowed on return types and parameters of functions that override binary functions.
-ChangeTypeRefactoring_invalidSelection=Invalid selection for Generalize Declared Type.
-ChangeTypeRefactoring_multiDeclarationsNotSupported=Multi-declarations currently not handled.
-ChangeTypeRefactoring_noMatchingConstraintVariable=No constraint variable matches the selected ASTNode.
-ChangeTypeRefactoring_unhandledSearchException=exception occurred during search:
-ChangeTypeRefactoring_original_element_pattern=Original element: ''{0}''
-ChangeTypeRefactoring_failedToSelectType=failed to select type:
-ChangeTypeMessages_CreateChangesForChangeType=Creating changes for Generalize Declared Type...
-ChangeTypeRefactoring_javaLangObject=Object
-ChangeTypeRefactoring_arraysNotSupported=Generalize Declared Type is not supported on array types.
-ChangeTypeRefactoring_localTypesNotSupported=Generalize Declared Type is not supported on local types.
-ChangeTypeRefactoring_primitivesNotSupported=Generalize Declared Type is not supported on primitive types.
-ChangeTypeRefactoring_descriptor_description=Generalize declared type of ''{0}'' to ''{1}''
-ChangeTypeRefactoring_original_type_pattern=Original type: ''{0}''
-ChangeTypeRefactoring_refactored_type_pattern=Refactored type: ''{0}''
-ChangeTypeRefactoring_descriptor_description_short=Generalize declared type
-ChangeTypeRefactoring_typeChange=Change declared type from ''{0}'' to ''{1}''
-ChangeTypeRefactoring_allChanges=Generalize Declared Type
-ChangeTypeRefactoring_analyzingMessage=Analyzing...
-ChangeTypeRefactoring_no_method=Selection cannot be mapped to a function
-ChangeTypeRefactoring_no_filed=Selection cannot be mapped to a var
-ChangeTypeRefactoring_insideLocalTypesNotSupported=Generalize Declared Type is currently not supported inside local types.
-ChangeTypeRefactoring_typeParametersNotSupported=Generalize Declared Type is not supported on type parameters.
-ChangeTypeRefactoring_enumsNotSupported=Generalize Declared Type is not supported on enumerated types.
-
-#--- Introduce Indirection
-IntroduceIndirectionRefactoring_introduce_indirection_name=Introduce Indirection
-IntroduceIndirectionRefactoring_duplicate_method_name_in_declaring_class_error=Duplicate function name ''{0}'' in declaring class
-IntroduceIndirectionRefactoring_could_not_parse_declaring_class_error=Could not parse declaring class.
-IntroduceIndirectionRefactoring_class_does_not_exist_error=Class ''{0}'' does not exist.
-IntroduceIndirectionRefactoring_class_not_selected_error=Please select a declaring class.
-IntroduceIndirectionRefactoring_cannot_create_in_annotation=Cannot place new function on an annotation.
-IntroduceIndirectionRefactoring_cannot_create_on_interface=Cannot place new function on an interface.
-IntroduceIndirectionRefactoring_unable_determine_declaring_type=Unable to determine whether declaring type is an interface.
-IntroduceIndirectionRefactoring_cannot_create_in_readonly=Cannot place new function in a read only class.
-IntroduceIndirectionRefactoring_cannot_create_in_binary=Cannot place new function in a binary class.
-IntroduceIndirectionRefactoring_checking_activation=Checking activation of Introduce Indirection...
-IntroduceIndirectionRefactoring_not_available_on_this_selection=Introduce Indirection is not available on this selection. Select a function invocation or a function declaration.
-IntroduceIndirectionRefactoring_not_available_on_annotation=Introduce Indirection is not supported on annotation types.
-IntroduceIndirectionRefactoring_not_available_for_local_or_anonymous_types=Introduce Indirection is not supported on functions inside local or anonymous types.
-IntroduceIndirectionRefactoring_not_available_for_constructors=Introduce Indirection is not available for constructors.
-IntroduceIndirectionRefactoring_checking_conditions=Checking preconditions...
-IntroduceIndirectionRefactoring_method_pattern=Function name: ''{0}''
-IntroduceIndirectionRefactoring_declaring_pattern=Declaring type: ''{0}''
-IntroduceIndirectionRefactoring_cannot_create_in_nested_nonstatic=Cannot create a static function in a nested non-static type.
-IntroduceIndirectionRefactoring_looking_for_references=Looking for references...
-IntroduceIndirectionRefactoring_descriptor_description=Introduce indirection for ''{0}'' in ''{1}''
-IntroduceIndirectionRefactoring_descriptor_description_short=Introduce indirection for ''{0}''
-IntroduceIndirectionRefactoring_adjusting_visibility=Adjusting visibility...
-IntroduceIndirectionRefactoring_call_warning_super_keyword=A reference function invocation in ''{0}'' in type ''{1}'' invokes the target function using the super keyword. Cannot replace this occurrence.
-IntroduceIndirectionRefactoring_open_hierarchy_error=Found function invocations with the different types ''{0}'' and ''{1}'' from an open ended type hierarchy. No possible target.
-IntroduceIndirectionRefactoring_original_pattern=Original element: ''{0}''
-IntroduceIndirectionRefactoring_introduce_indirection=Introduce Indirection
-IntroduceIndirectionRefactoring_group_description_create_new_method=Create new function
-IntroduceIndirectionRefactoring_call_warning_type_arguments=A function invocation in ''{0}'' in type ''{1}'' uses type arguments. This occurrence will not be updated.
-IntroduceIndirectionRefactoring_call_warning_static_expression_access=The target function is static, but a function invocation in ''{0}'' in type ''{1}'' is based on an expression rather than the class itself. This occurrence will not be updated.
-IntroduceIndirectionRefactoring_group_description_replace_call=Replace function invocation
-IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found=The declaring type of a function invocation in ''{0}'' in type ''{1}'' could not be found. This occurrence will not be updated.
-IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify=The declaring type of a function invocation in ''{0}'' in type ''{1}'' is anonymous and therefore cannot be qualified. This occurrence will not be updated.
-IntroduceIndirectionRefactoring_cannot_update_binary_target_visibility=A visibility update is needed for the member ''{0}'' or an enclosing type, but the member is not writeable. Refactoring will introduce compile errors.
-IntroduceIndirectionRefactoring_cannot_run_without_intermediary_type=Cannot run Introduce Indirection without a target class.
-
-#--- Infer Type Arguments
-InferTypeArgumentsRefactoring_name=Infer Type Arguments
-InferTypeArgumentsRefactoring_not50=Project ''{0}'' cannot be processed since its compiler source level is below 5.0.
-InferTypeArgumentsRefactoring_calculating_dependencies=Calculating dependencies...
-InferTypeArgumentsRefactoring_descriptor_description_project=Infer generic type arguments on ''{0}''
-InferTypeArgumentsRefactoring_descriptor_description=Infer generic type arguments
-InferTypeArgumentsRefactoring_building=Building constraints system...
-InferTypeArgumentsRefactoring_solving=Solving constraints...
-InferTypeArgumentsRefactoring_creatingChanges=Creating changes...
-InferTypeArgumentsRefactoring_internal_error=Internal error while inferring type arguments in ''{0}''.
-InferTypeArgumentsRefactoring_addTypeArguments=Add type arguments
-InferTypeArgumentsRefactoring_original_elements=Original elements:
-InferTypeArgumentsRefactoring_removeCast=Remove cast
-InferTypeArgumentsRefactoring_not50Library=Project ''{0}'' cannot be processed since its JRE System Library version is below 5.0.
-InferTypeArgumentsRefactoring_assume_clone=Assume clone() returns an instance of the receiver type
-InferTypeArgumentsRefactoring_error_skipped=An unexpected error happened while processing ''{0}''. The rest of this JavaScript file has been skipped.
-InferTypeArgumentsRefactoring_error_in_cu_skipped=Compile errors found in ''{0}''. The JavaScript file has been skipped.
-InferTypeArgumentsRefactoring_leave_unconstrained=Leave unconstrained type arguments raw
-
-#--- Miscellaneous
-QualifiedNameSearchResult_change_name= Textual qualified name modifications
-
-ASTData_update_imports=Update imports
-
-StubCreationOperation_creating_type_stubs=Creating type stubs...
-SourceCreationOperation_creating_source_folder=Creating source folder...
-
-CompilationUnitChange_label=Create ''{0}'' - {1}
-
-MultiStateCompilationUnitChange_name_pattern={0} - {1}
-ReplaceInvocationsRefactoring_cannot_find_method_declaration=Cannot find function declaration
-ReplaceInvocationsRefactoring_descriptor_description_short=Replace invocations of ''{0}''
-CreateCopyOfCompilationUnitChange_create_copy=Copy JavaScript file ''{0}'' - {1}
-LoggedCreateTargetChange_change_name=Create move target
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/GenericRefactoringHandleTransplanter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/GenericRefactoringHandleTransplanter.java
deleted file mode 100644
index 26b44234..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/GenericRefactoringHandleTransplanter.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-
-public class GenericRefactoringHandleTransplanter {
-
- public final IJavaScriptElement transplantHandle(IJavaScriptElement element) {
- IJavaScriptElement parent= element.getParent();
- if (parent != null)
- parent= transplantHandle(parent); // recursive
-
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return transplantHandle((IJavaScriptModel) element);
-
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return transplantHandle((IJavaScriptProject) element);
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return transplantHandle((IJavaScriptProject) parent, (IPackageFragmentRoot) element);
-
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return transplantHandle((IPackageFragmentRoot) parent, (IPackageFragment) element);
-
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return transplantHandle((IPackageFragment) parent, (IJavaScriptUnit) element);
-
- case IJavaScriptElement.CLASS_FILE:
- return transplantHandle((IPackageFragment) parent, (IClassFile) element);
-
- case IJavaScriptElement.TYPE:
- return transplantHandle(parent, (IType) element);
-
- case IJavaScriptElement.FIELD:
- return transplantHandle((IType) parent, (IField) element);
-
- case IJavaScriptElement.METHOD:
- return transplantHandle((IType) parent, (IFunction) element);
-
- case IJavaScriptElement.INITIALIZER:
- return transplantHandle((IType) parent, (IInitializer) element);
-
- case IJavaScriptElement.IMPORT_CONTAINER:
- return transplantHandle((IJavaScriptUnit) parent, (IImportContainer) element);
-
- case IJavaScriptElement.IMPORT_DECLARATION:
- return transplantHandle((IImportContainer) parent, (IImportDeclaration) element);
-
- case IJavaScriptElement.LOCAL_VARIABLE:
- return transplantHandle((ILocalVariable) element);
-
- default:
- throw new IllegalArgumentException(element.toString());
- }
-
- }
-
- protected IJavaScriptModel transplantHandle(IJavaScriptModel element) {
- return element;
- }
-
- protected IJavaScriptProject transplantHandle(IJavaScriptProject element) {
- return element;
- }
-
- protected IPackageFragmentRoot transplantHandle(IJavaScriptProject parent, IPackageFragmentRoot element) {
- return element;
- }
-
- protected IPackageFragment transplantHandle(IPackageFragmentRoot parent, IPackageFragment element) {
- return parent.getPackageFragment(element.getElementName());
- }
-
- protected IJavaScriptUnit transplantHandle(IPackageFragment parent, IJavaScriptUnit element) {
- return parent.getJavaScriptUnit(element.getElementName());
- }
-
- protected IClassFile transplantHandle(IPackageFragment parent, IClassFile element) {
- return parent.getClassFile(element.getElementName());
- }
-
- protected IType transplantHandle(IJavaScriptElement parent, IType element) {
- switch (parent.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return ((IJavaScriptUnit) parent).getType(element.getElementName());
- case IJavaScriptElement.CLASS_FILE:
- return ((IClassFile) parent).getType();
- case IJavaScriptElement.METHOD:
- return ((IFunction) parent).getType(element.getElementName(), element.getOccurrenceCount());
- case IJavaScriptElement.FIELD:
- return ((IField) parent).getType(element.getElementName(), element.getOccurrenceCount());
- case IJavaScriptElement.INITIALIZER:
- return ((IInitializer) parent).getType(element.getElementName(), element.getOccurrenceCount());
- case IJavaScriptElement.TYPE:
- return ((IType) parent).getType(element.getElementName(), element.getOccurrenceCount());
- default:
- throw new IllegalStateException(element.toString());
- }
- }
-
- protected IField transplantHandle(IType parent, IField element) {
- return parent.getField(element.getElementName());
- }
-
- protected IFunction transplantHandle(IType parent, IFunction element) {
- return parent.getFunction(element.getElementName(), element.getParameterTypes());
- }
-
- protected IInitializer transplantHandle(IType parent, IInitializer element) {
- return parent.getInitializer(element.getOccurrenceCount());
- }
-
- protected IImportContainer transplantHandle(IJavaScriptUnit parent, IImportContainer element) {
- return parent.getImportContainer();
- }
-
- protected IImportDeclaration transplantHandle(IImportContainer parent, IImportDeclaration element) {
- return parent.getImport(element.getElementName());
- }
-
- protected ILocalVariable transplantHandle(ILocalVariable element) {
- return element; // can't get from parent!
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameProcessor.java
deleted file mode 100644
index c0bd6978..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameProcessor.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-
-public abstract class JavaRenameProcessor extends RenameProcessor implements IScriptableRefactoring, INameUpdating, ICommentProvider {
-
- private String fNewElementName;
- private String fComment;
- private RenameModifications fRenameModifications;
-
- public final RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- return getRenameModifications().loadParticipants(status, this, getAffectedProjectNatures(), shared);
- }
-
- public final RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException, OperationCanceledException {
- ResourceChangeChecker checker= (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory();
- RefactoringStatus result= doCheckFinalConditions(pm, context);
- if (result.hasFatalError())
- return result;
- IFile[] changed= getChangedFiles();
- for (int i= 0; i < changed.length; i++) {
- deltaFactory.change(changed[i]);
- }
- RenameModifications renameModifications= getRenameModifications();
- renameModifications.buildDelta(deltaFactory);
- renameModifications.buildValidateEdits((ValidateEditChecker)context.getChecker(ValidateEditChecker.class));
- return result;
- }
-
- private RenameModifications getRenameModifications() throws CoreException {
- if (fRenameModifications == null)
- fRenameModifications= computeRenameModifications();
- return fRenameModifications;
- }
-
- protected abstract RenameModifications computeRenameModifications() throws CoreException;
-
- protected abstract RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException, OperationCanceledException;
-
- protected abstract IFile[] getChangedFiles() throws CoreException;
-
- protected abstract String[] getAffectedProjectNatures() throws CoreException;
-
- public void setNewElementName(String newName) {
- Assert.isNotNull(newName);
- fNewElementName= newName;
- }
-
- public String getNewElementName() {
- return fNewElementName;
- }
-
- /**
- * @return a save mode from {@link org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper}
- *
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper
- */
- public abstract int getSaveMode();
-
- public final boolean canEnableComment() {
- return true;
- }
-
- public final String getComment() {
- return fComment;
- }
-
- public final void setComment(String comment) {
- fComment= comment;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java
deleted file mode 100644
index 03a511be..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * A rename refactoring which can be initialized with refactoring arguments.
- *
- *
- */
-public final class JavaRenameRefactoring extends RenameRefactoring implements IScriptableRefactoring {
-
- /**
- * Creates a new java rename refactoring.
- *
- * @param processor
- * the rename processor to use
- */
- public JavaRenameRefactoring(final RenameProcessor processor) {
- super(processor);
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodChecks.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodChecks.java
deleted file mode 100644
index b55d49dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodChecks.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-
-public class MethodChecks {
-
- //no instances
- private MethodChecks(){
- }
-
- public static boolean isVirtual(IFunction method) throws JavaScriptModelException {
- if (method.isConstructor())
- return false;
- if (JdtFlags.isPrivate(method))
- return false;
- if (JdtFlags.isStatic(method))
- return false;
- if (method.getDeclaringType()==null)
- return false;
- return true;
- }
-
- public static boolean isVirtual(IFunctionBinding methodBinding){
- if (methodBinding.isConstructor())
- return false;
- if (Modifier.isPrivate(methodBinding.getModifiers())) //TODO is this enough?
- return false;
- if (Modifier.isStatic(methodBinding.getModifiers())) //TODO is this enough?
- return false;
- return true;
- }
-
- public static RefactoringStatus checkIfOverridesAnother(IFunction method, ITypeHierarchy hierarchy) throws JavaScriptModelException {
- IFunction overrides= MethodChecks.overridesAnotherMethod(method, hierarchy);
- if (overrides == null)
- return null;
-
- RefactoringStatusContext context= JavaStatusContext.create(overrides);
- String message= Messages.format(RefactoringCoreMessages.MethodChecks_overrides,
- new String[]{JavaElementUtil.createMethodSignature(overrides), JavaModelUtil.getFullyQualifiedName(overrides.getDeclaringType())});
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, message, context, Corext.getPluginId(), RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD, overrides);
- }
-
- public static IFunction overridesAnotherMethod(IFunction method, ITypeHierarchy hierarchy) throws JavaScriptModelException {
- MethodOverrideTester tester= new MethodOverrideTester(method.getDeclaringType(), hierarchy);
- IFunction found= tester.findDeclaringMethod(method, true);
- boolean overrides= (found != null && !found.equals(method) && (!JdtFlags.isStatic(found)) && (!JdtFlags.isPrivate(found)));
- if (overrides)
- return found;
- else
- return null;
- }
-
- /**
- * Locates the topmost method of an override ripple and returns it. If none
- * is found, null is returned.
- *
- * @param method the IFunction which may be part of a ripple
- * @param typeHierarchy a ITypeHierarchy of the declaring type of the method. May be null
- * @param monitor an IProgressMonitor
- * @return the topmost method of the ripple, or null if none
- * @throws JavaScriptModelException
- */
- public static IFunction getTopmostMethod(IFunction method, ITypeHierarchy typeHierarchy, IProgressMonitor monitor) throws JavaScriptModelException {
-
- Assert.isNotNull(method);
-
- ITypeHierarchy hierarchy= typeHierarchy;
- IFunction topmostMethod= null;
- final IType declaringType= method.getDeclaringType();
- if (declaringType==null)
- return method;
-
- if ((hierarchy == null) || !declaringType.equals(hierarchy.getType()))
- hierarchy= declaringType.newTypeHierarchy(monitor);
-
- if (hierarchy == null)
- hierarchy= declaringType.newSupertypeHierarchy(monitor);
- IFunction overrides= overridesAnotherMethod(method, hierarchy);
- if (overrides != null && !overrides.equals(method))
- topmostMethod= overrides;
-
- return topmostMethod;
- }
-
- /**
- * Finds all overridden methods of a certain method.
- *
- */
- public static IFunction[] getOverriddenMethods(IFunction method, IProgressMonitor monitor) throws CoreException {
-
- Assert.isNotNull(method);
- return RippleMethodFinder2.getRelatedMethods(method, monitor, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java
deleted file mode 100644
index 5dafad3c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.search.MethodReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CuCollectingSearchRequestor;
-
-class MethodOccurenceCollector extends CuCollectingSearchRequestor {
-
- private final String fName;
-
- public MethodOccurenceCollector(String methodName) {
- fName= methodName;
- }
-
- public void acceptSearchMatch(IJavaScriptUnit unit, SearchMatch match) throws CoreException {
- if (match instanceof MethodReferenceMatch
- && ((MethodReferenceMatch) match).isSuperInvocation()
- && match.getAccuracy() == SearchMatch.A_INACCURATE) {
- return; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491
- }
-
- if (match.isImplicit()) { // see bug 94062
- collectMatch(match);
- return;
- }
-
- int start= match.getOffset();
- int length= match.getLength();
- String matchText= unit.getBuffer().getText(start, length);
-
- //direct match:
- if (fName.equals(matchText)) {
- collectMatch(match);
- return;
- }
-
- //Not a standard reference -- use scanner to find last identifier token before left parenthesis:
- IScanner scanner= getScanner(unit);
- scanner.setSource(matchText.toCharArray());
- int simpleNameStart= -1;
- int simpleNameEnd= -1;
- try {
- int token = scanner.getNextToken();
- while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLPAREN) { // reference in code includes arguments in parentheses
- if (token == ITerminalSymbols.TokenNameIdentifier) {
- simpleNameStart= scanner.getCurrentTokenStartPosition();
- simpleNameEnd= scanner.getCurrentTokenEndPosition();
- }
- token = scanner.getNextToken();
- }
- } catch (InvalidInputException e){
- //ignore
- }
- if (simpleNameStart != -1) {
- match.setOffset(start + simpleNameStart);
- match.setLength(simpleNameEnd + 1 - simpleNameStart);
- }
- collectMatch(match);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java
deleted file mode 100644
index 4719bce5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class RefactoringAnalyzeUtil {
-
- private RefactoringAnalyzeUtil() {
- //no instances
- }
-
- public static IRegion[] getNewRanges(TextEdit[] edits, TextChange change){
- IRegion[] result= new IRegion[edits.length];
- for (int i= 0; i < edits.length; i++) {
- result[i]= RefactoringAnalyzeUtil.getNewTextRange(edits[i], change);
- }
- return result;
- }
-
- public static RefactoringStatus reportProblemNodes(String modifiedWorkingCopySource, SimpleName[] problemNodes) {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < problemNodes.length; i++) {
- RefactoringStatusContext context= new JavaStringStatusContext(modifiedWorkingCopySource, new SourceRange(problemNodes[i]));
- result.addError(Messages.format(RefactoringCoreMessages.RefactoringAnalyzeUtil_name_collision, problemNodes[i].getIdentifier()), context);
- }
- return result;
- }
-
-
- public static FunctionDeclaration getMethodDeclaration(TextEdit edit, TextChange change, JavaScriptUnit cuNode){
- ASTNode decl= RefactoringAnalyzeUtil.findSimpleNameNode(RefactoringAnalyzeUtil.getNewTextRange(edit, change), cuNode);
- return ((FunctionDeclaration)ASTNodes.getParent(decl, FunctionDeclaration.class));
- }
-
- public static Block getBlock(TextEdit edit, TextChange change, JavaScriptUnit cuNode){
- ASTNode decl= RefactoringAnalyzeUtil.findSimpleNameNode(RefactoringAnalyzeUtil.getNewTextRange(edit, change), cuNode);
- return ((Block)ASTNodes.getParent(decl, Block.class));
- }
-
- public static IProblem[] getIntroducedCompileProblems(JavaScriptUnit newCUNode, JavaScriptUnit oldCuNode) {
- Set subResult= new HashSet();
- Set oldProblems= getOldProblems(oldCuNode);
- IProblem[] newProblems= ASTNodes.getProblems(newCUNode, ASTNodes.INCLUDE_ALL_PARENTS, ASTNodes.PROBLEMS);
- for (int i= 0; i < newProblems.length; i++) {
- IProblem correspondingOld= findCorrespondingProblem(oldProblems, newProblems[i]);
- if (correspondingOld == null)
- subResult.add(newProblems[i]);
- }
- return (IProblem[]) subResult.toArray(new IProblem[subResult.size()]);
- }
-
- public static IRegion getNewTextRange(TextEdit edit, TextChange change){
- return change.getPreviewEdit(edit).getRegion();
- }
-
- private static IProblem findCorrespondingProblem(Set oldProblems, IProblem iProblem) {
- for (Iterator iter= oldProblems.iterator(); iter.hasNext();) {
- IProblem oldProblem= (IProblem) iter.next();
- if (isCorresponding(oldProblem, iProblem))
- return oldProblem;
- }
- return null;
- }
-
- private static boolean isCorresponding(IProblem oldProblem, IProblem iProblem) {
- if (oldProblem.getID() != iProblem.getID())
- return false;
- if (! oldProblem.getMessage().equals(iProblem.getMessage()))
- return false;
- return true;
- }
-
- private static SimpleName getSimpleName(ASTNode node){
- if (node instanceof SimpleName)
- return (SimpleName)node;
- if (node instanceof VariableDeclaration)
- return ((VariableDeclaration)node).getName();
- return null;
- }
-
- private static SimpleName findSimpleNameNode(IRegion range, JavaScriptUnit cuNode) {
- ASTNode node= NodeFinder.perform(cuNode, range.getOffset(), range.getLength());
- return getSimpleName(node);
- }
-
- private static Set getOldProblems(JavaScriptUnit oldCuNode) {
- return new HashSet(Arrays.asList(ASTNodes.getProblems(oldCuNode, ASTNodes.INCLUDE_ALL_PARENTS, ASTNodes.PROBLEMS)));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java
deleted file mode 100644
index 5dbf172a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-
-
-/**
- * Helper class to transplant a IJavaScriptElement handle from a certain state of the
- * Java Model into another.
- *
- * The changes to the workspace include one type rename, a number of field
- * renames, and a number of method renames including signature changes.
- *
- * The returned handle exists in the target model state.
- *
- *
- *
- */
-public class RefactoringHandleTransplanter {
-
- private final IType fOldType;
- private final IType fNewType;
- private final Map/*<IJavaScriptElement, String>*/ fRefactoredSimilarElements;
-
- /**
- * @param oldType old type
- * @param newType renamed type
- * @param refactoredSimilarElements map from similar element (IJavaScriptElement) to new name (String), or <code>null</code>
- */
- public RefactoringHandleTransplanter(IType oldType, IType newType, Map/*<IJavaScriptElement, String>*/ refactoredSimilarElements) {
- fOldType= oldType;
- fNewType= newType;
- if (refactoredSimilarElements == null)
- fRefactoredSimilarElements= Collections.EMPTY_MAP;
- else
- fRefactoredSimilarElements= refactoredSimilarElements;
- }
-
- /**
- * Converts the handle. Handle need not exist, but must be a source
- * reference.
- *
- * @param handle
- * @return the new handle
- */
- public IMember transplantHandle(IMember handle) {
-
- /*
- * Create a list of handles from top-level type to the handle
- */
- final LinkedList oldElements= new LinkedList();
- addElements(handle, oldElements);
-
- /*
- * Step through the elements and re-locate them in the new parents.
- */
- final IMember[] newElements= convertElements((IMember[]) oldElements.toArray(new IMember[0]));
-
- return newElements[newElements.length - 1];
- }
-
- private void addElements(IMember element, LinkedList chain) {
- chain.addFirst(element);
- IJavaScriptElement parent= element.getParent();
- if (parent instanceof IMember)
- addElements((IMember) parent, chain);
- }
-
- private IMember[] convertElements(IMember[] oldElements) {
-
- final IMember[] newElements= new IMember[oldElements.length];
- final IMember first= oldElements[0];
-
- Assert.isTrue(first instanceof IType);
-
- if (first.equals(fOldType))
- // We renamed a top level type.
- newElements[0]= fNewType;
- else
- newElements[0]= first;
-
- /*
- * Note that we only need to translate the information necessary to
- * create new handles. For example, the return type of a method is not
- * relevant; neither is information about generic specifics in types.
- */
-
- for (int i= 1; i < oldElements.length; i++) {
- final IJavaScriptElement newParent= newElements[i - 1];
- final IJavaScriptElement currentElement= oldElements[i];
- switch (newParent.getElementType()) {
- case IJavaScriptElement.TYPE: {
- switch (currentElement.getElementType()) {
- case IJavaScriptElement.TYPE: {
- final String newName= resolveTypeName((IType) currentElement);
- newElements[i]= ((IType) newParent).getType(newName);
- break;
- }
- case IJavaScriptElement.METHOD: {
- final String newName= resolveElementName(currentElement);
- final String[] newParameterTypes= resolveParameterTypes((IFunction) currentElement);
- newElements[i]= ((IType) newParent).getFunction(newName, newParameterTypes);
- break;
- }
- case IJavaScriptElement.INITIALIZER: {
- final IInitializer initializer= (IInitializer) currentElement;
- newElements[i]= ((IType) newParent).getInitializer(initializer.getOccurrenceCount());
- break;
- }
- case IJavaScriptElement.FIELD: {
- final String newName= resolveElementName(currentElement);
- newElements[i]= ((IType) newParent).getField(newName);
- break;
- }
- }
- break;
- }
- case IJavaScriptElement.METHOD: {
- switch (currentElement.getElementType()) {
- case IJavaScriptElement.TYPE: {
- newElements[i]= resolveTypeInMember((IFunction) newParent, (IType) currentElement);
- break;
- }
- }
- break;
- }
- case IJavaScriptElement.INITIALIZER: {
- switch (currentElement.getElementType()) {
- case IJavaScriptElement.TYPE: {
- newElements[i]= resolveTypeInMember((IInitializer) newParent, (IType) currentElement);
- break;
- }
- }
- break;
- }
- case IJavaScriptElement.FIELD: {
- switch (currentElement.getElementType()) {
- case IJavaScriptElement.TYPE: {
- // anonymous type in field declaration
- newElements[i]= resolveTypeInMember((IField) newParent, (IType) currentElement);
- break;
- }
- }
- break;
- }
- }
- }
- return newElements;
- }
-
- private String[] resolveParameterTypes(IFunction method) {
- final String[] oldParameterTypes= method.getParameterTypes();
- final String[] newparams= new String[oldParameterTypes.length];
-
- final String[] possibleOldSigs= new String[4];
- possibleOldSigs[0]= Signature.createTypeSignature(fOldType.getElementName(), false);
- possibleOldSigs[1]= Signature.createTypeSignature(fOldType.getElementName(), true);
- possibleOldSigs[2]= Signature.createTypeSignature(fOldType.getFullyQualifiedName(), false);
- possibleOldSigs[3]= Signature.createTypeSignature(fOldType.getFullyQualifiedName(), true);
-
- final String[] possibleNewSigs= new String[4];
- possibleNewSigs[0]= Signature.createTypeSignature(fNewType.getElementName(), false);
- possibleNewSigs[1]= Signature.createTypeSignature(fNewType.getElementName(), true);
- possibleNewSigs[2]= Signature.createTypeSignature(fNewType.getFullyQualifiedName(), false);
- possibleNewSigs[3]= Signature.createTypeSignature(fNewType.getFullyQualifiedName(), true);
-
- // Textually replace all occurrences
- // This handles stuff like Map<SomeClass, some.package.SomeClass>
- for (int i= 0; i < oldParameterTypes.length; i++) {
- newparams[i]= oldParameterTypes[i];
- for (int j= 0; j < possibleOldSigs.length; j++) {
- newparams[i]= replaceAll(newparams[i], possibleOldSigs[j], possibleNewSigs[j]);
- }
- }
- return newparams;
- }
-
- private String resolveElementName(IJavaScriptElement element) {
- final String newName= (String) fRefactoredSimilarElements.get(element);
- if (newName != null)
- return newName;
- else
- return element.getElementName();
- }
-
- private IMember resolveTypeInMember(final IMember newParent, IType oldChild) {
- // Local type or anonymous type. Only local types can be renamed.
- String newName= ""; //$NON-NLS-1$
- if (oldChild.getElementName().length() != 0)
- newName= resolveTypeName(oldChild);
- return newParent.getType(newName, oldChild.getOccurrenceCount());
- }
-
- private String resolveTypeName(IType type) {
- return type.equals(fOldType) ? fNewType.getElementName() : type.getElementName();
- }
-
- private static String replaceAll(final String source, final String replaceFrom, final String replaceTo) {
- final StringBuffer buf= new StringBuffer(source.length());
- int currentIndex= 0;
- int matchIndex;
- while ((matchIndex= source.indexOf(replaceFrom, currentIndex)) != -1) {
- buf.append(source.substring(currentIndex, matchIndex));
- buf.append(replaceTo);
- currentIndex= matchIndex + replaceFrom.length();
- }
- buf.append(source.substring(currentIndex));
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringScanner.java
deleted file mode 100644
index 769c81d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RefactoringScanner.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-
-
-public class RefactoringScanner {
-
- private static int NO_MATCH= 0;
- private static int MATCH_QUALIFIED= 1;
- private static int MATCH_UNQUALIFIED= 2;
-
- public static class TextMatch {
-
- private int fStartPosition;
- private boolean fQualified;
-
- private TextMatch(int startPosition, boolean qualified) {
- fStartPosition= startPosition;
- fQualified= qualified;
- }
-
- /**
- * @return the offset where the unqualified name starts
- */
- public int getStartPosition() {
- return fStartPosition;
- }
-
- public boolean isQualified() {
- return fQualified;
- }
- }
-
- private final String fName;
- private final String fQualifier;
-
- private IScanner fScanner;
- private Set fMatches; //Set<TextMatch>
-
-
- public RefactoringScanner(String name, String qualifier) {
- Assert.isNotNull(name);
- Assert.isNotNull(qualifier);
- fName= name;
- fQualifier= qualifier;
- }
-
- public void scan(IJavaScriptUnit cu) throws JavaScriptModelException {
- char[] chars= cu.getBuffer().getCharacters();
- fMatches= new HashSet();
- fScanner= ToolFactory.createScanner(true, true, false, true);
- fScanner.setSource(chars);
-
-// IImportContainer importContainer= cu.getImportContainer();
-// if (importContainer.exists())
-// fNoFlyZone= importContainer.getSourceRange();
-// else
-// fNoFlyZone= null;
-
- doScan();
- fScanner= null;
- }
-
- /** only for testing */
- public void scan(String text) {
- char[] chars= text.toCharArray();
- fMatches= new HashSet();
- fScanner= ToolFactory.createScanner(true, true, false, true);
- fScanner.setSource(chars);
- doScan();
- fScanner= null;
- }
-
- private void doScan() {
- try{
- int token = fScanner.getNextToken();
- while (token != ITerminalSymbols.TokenNameEOF) {
- switch (token) {
- case ITerminalSymbols.TokenNameStringLiteral :
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
- case ITerminalSymbols.TokenNameCOMMENT_LINE :
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
- parseCurrentToken();
- }
- token = fScanner.getNextToken();
- }
- } catch (InvalidInputException e){
- //ignore
- }
- }
-
- private static boolean isWholeWord(String value, int from, int to){
- if (from > 0) {
- char ch= value.charAt(from - 1);
- if (Character.isLetterOrDigit(ch) || ch == '_') {
- return false;
- }
- }
- if (to < value.length()) {
- char ch= value.charAt(to);
- if (Character.isLetterOrDigit(ch) || ch == '_' ) {
- return false;
- }
- }
- return true;
- }
-
- private void parseCurrentToken() {
- // only works for references without whitespace
- String value = new String(fScanner.getRawTokenSource());
- int start= fScanner.getCurrentTokenStartPosition();
- int index= value.indexOf(fName);
- while (index != -1) {
- if (isWholeWord(value, index, index + fName.length())) {
- int ok= isQualifierOK(value, index);
- if (ok > NO_MATCH)
- addMatch(start + index, ok);
- }
- index= value.indexOf(fName, index + 1);
- }
- }
-
- private int isQualifierOK(String value, int nameStart) {
- // only works for references without whitespace
- int qualifierAfter= nameStart - 1;
- if (qualifierAfter < 0)
- // there is absolutely nothing before the name itself in the string
- return MATCH_UNQUALIFIED;
-
- char charBeforeName= value.charAt(qualifierAfter);
- if (! isQualifierSeparator(charBeforeName))
- // the char before the name is not a # or . - should not get here anyway
- return MATCH_UNQUALIFIED; // NO_MATCH ?
-
- boolean canFinish= charBeforeName == '#';
- // work through the qualifier from back to front
- for (int i= 0; i < fQualifier.length() ; i++) {
- int qualifierCharPos= qualifierAfter - 1 - i;
- if (qualifierCharPos < 0)
- // the position does not exist, return OK if last read char was a non-separator
- return canFinish ? MATCH_UNQUALIFIED : NO_MATCH;
-
- char qualifierChar= value.charAt(qualifierCharPos);
- char goalQualifierChar= fQualifier.charAt(fQualifier.length() - 1 - i);
- if (qualifierChar != goalQualifierChar)
- // the chars do not match. return OK if last read char was a non-separator and the current one a non-qualifier
- return (canFinish && !isQualifierPart(qualifierChar)) ? MATCH_UNQUALIFIED : NO_MATCH;
-
- canFinish= ! isQualifierSeparator(qualifierChar);
- }
- int beforeQualifierPos= qualifierAfter - fQualifier.length() - 1;
- if (beforeQualifierPos >= 0) {
- char beforeQualifierChar= value.charAt(beforeQualifierPos);
- if (Character.isJavaIdentifierPart(beforeQualifierChar)) {
- return NO_MATCH;
- }
- if (isQualifierSeparator(beforeQualifierChar)) {
- if (beforeQualifierPos > 0) {
- /*
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=142508 :
- * If the character before the qualifier separator is not
- * an identifier part, then accept the match.
- */
- char precedingOne= value.charAt(beforeQualifierPos - 1);
- if (Character.isJavaIdentifierPart(precedingOne)) {
- return NO_MATCH;
- }
- }
- }
- return MATCH_QUALIFIED;
-
- }
- return MATCH_QUALIFIED;
- }
-
- private boolean isQualifierPart(char ch) {
- return Character.isJavaIdentifierPart(ch) || isQualifierSeparator(ch);
- }
-
- private boolean isQualifierSeparator(char c) {
- return ".#".indexOf(c) != -1; //$NON-NLS-1$
- }
-
- private void addMatch(int matchStart, int matchCode) {
- fMatches.add(new TextMatch(matchStart, matchCode == MATCH_QUALIFIED));
- }
-
- /**
- * @return Set of TextMatch
- */
- public Set getMatches() {
- return fMatches;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java
deleted file mode 100644
index bee83880..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditChangeGroup;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.search.FieldDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.MethodDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-class RenameAnalyzeUtil {
-
- private static class ProblemNodeFinder {
-
- private ProblemNodeFinder() {
- //static
- }
-
- public static SimpleName[] getProblemNodes(ASTNode methodNode, VariableDeclaration variableNode, TextEdit[] edits, TextChange change) {
- String key= variableNode.resolveBinding().getKey();
- NameNodeVisitor visitor= new NameNodeVisitor(edits, change, key);
- methodNode.accept(visitor);
- return visitor.getProblemNodes();
- }
-
- private static class NameNodeVisitor extends ASTVisitor {
-
- private Collection fRanges;
- private Collection fProblemNodes;
- private String fKey;
-
- public NameNodeVisitor(TextEdit[] edits, TextChange change, String key) {
- Assert.isNotNull(edits);
- Assert.isNotNull(key);
-
- fRanges= new HashSet(Arrays.asList(RefactoringAnalyzeUtil.getNewRanges(edits, change)));
- fProblemNodes= new ArrayList(0);
- fKey= key;
- }
-
- public SimpleName[] getProblemNodes() {
- return (SimpleName[]) fProblemNodes.toArray(new SimpleName[fProblemNodes.size()]);
- }
-
- //----- visit methods
-
- public boolean visit(SimpleName node) {
- VariableDeclaration decl= getVariableDeclaration(node);
- if (decl == null)
- return super.visit(node);
-
- IVariableBinding binding= decl.resolveBinding();
- if (binding == null)
- return super.visit(node);
-
- boolean keysEqual= fKey.equals(binding.getKey());
- boolean rangeInSet= fRanges.contains(new Region(node.getStartPosition(), node.getLength()));
-
- if (keysEqual && !rangeInSet)
- fProblemNodes.add(node);
-
- if (!keysEqual && rangeInSet)
- fProblemNodes.add(node);
-
- /*
- * if (!keyEquals && !rangeInSet)
- * ok, different local variable.
- *
- * if (keyEquals && rangeInSet)
- * ok, renamed local variable & has been renamed.
- */
-
- return super.visit(node);
- }
- }
- }
-
- static class LocalAnalyzePackage {
- public final TextEdit fDeclarationEdit;
- public final TextEdit[] fOccurenceEdits;
-
- public LocalAnalyzePackage(final TextEdit declarationEdit, final TextEdit[] occurenceEdits) {
- fDeclarationEdit = declarationEdit;
- fOccurenceEdits = occurenceEdits;
- }
- }
-
- private RenameAnalyzeUtil() {
- //no instance
- }
-
- static RefactoringStatus analyzeRenameChanges(TextChangeManager manager, SearchResultGroup[] oldOccurrences, SearchResultGroup[] newOccurrences) {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < oldOccurrences.length; i++) {
- SearchResultGroup oldGroup= oldOccurrences[i];
- SearchMatch[] oldSearchResults= oldGroup.getSearchResults();
- IJavaScriptUnit cunit= oldGroup.getCompilationUnit();
- if (cunit == null)
- continue;
- for (int j= 0; j < oldSearchResults.length; j++) {
- SearchMatch oldSearchResult= oldSearchResults[j];
- if (! RenameAnalyzeUtil.existsInNewOccurrences(oldSearchResult, newOccurrences, manager)){
- addShadowsError(cunit, oldSearchResult, result);
- }
- }
- }
- return result;
- }
-
- static IJavaScriptUnit findWorkingCopyForCu(IJavaScriptUnit[] newWorkingCopies, IJavaScriptUnit cu){
- IJavaScriptUnit original= cu == null ? null : cu.getPrimary();
- for (int i= 0; i < newWorkingCopies.length; i++) {
- if (newWorkingCopies[i].getPrimary().equals(original))
- return newWorkingCopies[i];
- }
- return null;
- }
-
- static IJavaScriptUnit[] createNewWorkingCopies(IJavaScriptUnit[] compilationUnitsToModify, TextChangeManager manager, WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
- pm.beginTask("", compilationUnitsToModify.length); //$NON-NLS-1$
- IJavaScriptUnit[] newWorkingCopies= new IJavaScriptUnit[compilationUnitsToModify.length];
- for (int i= 0; i < compilationUnitsToModify.length; i++) {
- IJavaScriptUnit cu= compilationUnitsToModify[i];
- newWorkingCopies[i]= createNewWorkingCopy(cu, manager, owner, new SubProgressMonitor(pm, 1));
- }
- pm.done();
- return newWorkingCopies;
- }
-
- static IJavaScriptUnit createNewWorkingCopy(IJavaScriptUnit cu, TextChangeManager manager,
- WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
- IJavaScriptUnit newWc= cu.getWorkingCopy(owner, null);
- String previewContent= manager.get(cu).getPreviewContent(new NullProgressMonitor());
- newWc.getBuffer().setContents(previewContent);
- newWc.reconcile(IJavaScriptUnit.NO_AST, false, owner, pm);
- return newWc;
- }
-
- private static boolean existsInNewOccurrences(SearchMatch searchResult, SearchResultGroup[] newOccurrences, TextChangeManager manager) {
- SearchResultGroup newGroup= findOccurrenceGroup(searchResult.getResource(), newOccurrences);
- if (newGroup == null)
- return false;
-
- IRegion oldEditRange= getCorrespondingEditChangeRange(searchResult, manager);
- if (oldEditRange == null)
- return false;
-
- SearchMatch[] newSearchResults= newGroup.getSearchResults();
- int oldRangeOffset = oldEditRange.getOffset();
- for (int i= 0; i < newSearchResults.length; i++) {
- if (newSearchResults[i].getOffset() == oldRangeOffset)
- return true;
- }
- return false;
- }
-
- private static IRegion getCorrespondingEditChangeRange(SearchMatch searchResult, TextChangeManager manager) {
- TextChange change= getTextChange(searchResult, manager);
- if (change == null)
- return null;
-
- IRegion oldMatchRange= createTextRange(searchResult);
- TextEditChangeGroup[] editChanges= change.getTextEditChangeGroups();
- for (int i= 0; i < editChanges.length; i++) {
- if (oldMatchRange.equals(editChanges[i].getRegion()))
- return TextEdit.getCoverage(change.getPreviewEdits(editChanges[i].getTextEdits()));
- }
- return null;
- }
-
- private static TextChange getTextChange(SearchMatch searchResult, TextChangeManager manager) {
- IJavaScriptUnit cu= SearchUtils.getCompilationUnit(searchResult);
- if (cu == null)
- return null;
- return manager.get(cu);
- }
-
- private static IRegion createTextRange(SearchMatch searchResult) {
- return new Region(searchResult.getOffset(), searchResult.getLength());
- }
-
- private static SearchResultGroup findOccurrenceGroup(IResource resource, SearchResultGroup[] newOccurrences) {
- for (int i= 0; i < newOccurrences.length; i++) {
- if (newOccurrences[i].getResource().equals(resource))
- return newOccurrences[i];
- }
- return null;
- }
-
-//--- find missing changes in BOTH directions
-
- //TODO: Currently filters out declarations (MethodDeclarationMatch, FieldDeclarationMatch).
- //Long term solution: only pass reference search results in.
- static RefactoringStatus analyzeRenameChanges2(TextChangeManager manager,
- SearchResultGroup[] oldReferences, SearchResultGroup[] newReferences, String newElementName) {
- RefactoringStatus result= new RefactoringStatus();
-
- HashMap cuToNewResults= new HashMap(newReferences.length);
- for (int i1= 0; i1 < newReferences.length; i1++) {
- IJavaScriptUnit cu= newReferences[i1].getCompilationUnit();
- if (cu != null)
- cuToNewResults.put(cu.getPrimary(), newReferences[i1].getSearchResults());
- }
-
- for (int i= 0; i < oldReferences.length; i++) {
- SearchResultGroup oldGroup= oldReferences[i];
- SearchMatch[] oldMatches= oldGroup.getSearchResults();
- IJavaScriptUnit cu= oldGroup.getCompilationUnit();
- if (cu == null)
- continue;
-
- SearchMatch[] newSearchMatches= (SearchMatch[]) cuToNewResults.remove(cu);
- if (newSearchMatches == null) {
- for (int j = 0; j < oldMatches.length; j++) {
- SearchMatch oldMatch = oldMatches[j];
- addShadowsError(cu, oldMatch, result);
- }
- } else {
- analyzeChanges(cu, manager.get(cu), oldMatches, newSearchMatches, newElementName, result);
- }
- }
-
- for (Iterator iter= cuToNewResults.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry= (Entry) iter.next();
- IJavaScriptUnit cu= (IJavaScriptUnit) entry.getKey();
- SearchMatch[] newSearchMatches= (SearchMatch[]) entry.getValue();
- for (int i= 0; i < newSearchMatches.length; i++) {
- SearchMatch newMatch= newSearchMatches[i];
- addReferenceShadowedError(cu, newMatch, newElementName, result);
- }
- }
- return result;
- }
-
- private static void analyzeChanges(IJavaScriptUnit cu, TextChange change,
- SearchMatch[] oldMatches, SearchMatch[] newMatches, String newElementName, RefactoringStatus result) {
- Map updatedOldOffsets= getUpdatedChangeOffsets(change, oldMatches);
- for (int i= 0; i < newMatches.length; i++) {
- SearchMatch newMatch= newMatches[i];
- Integer offsetInNew= new Integer(newMatch.getOffset());
- SearchMatch oldMatch= (SearchMatch) updatedOldOffsets.remove(offsetInNew);
- if (oldMatch == null) {
- addReferenceShadowedError(cu, newMatch, newElementName, result);
- }
- }
- for (Iterator iter= updatedOldOffsets.values().iterator(); iter.hasNext();) {
- // remaining old matches are not found any more -> they have been shadowed
- SearchMatch oldMatch= (SearchMatch) iter.next();
- addShadowsError(cu, oldMatch, result);
- }
- }
-
- /** @return Map &lt;Integer updatedOffset, SearchMatch oldMatch&gt; */
- private static Map getUpdatedChangeOffsets(TextChange change, SearchMatch[] oldMatches) {
- Map/*<Integer updatedOffset, SearchMatch oldMatch>*/ updatedOffsets= new HashMap();
- Map oldToUpdatedOffsets= getEditChangeOffsetUpdates(change);
- for (int i= 0; i < oldMatches.length; i++) {
- SearchMatch oldMatch= oldMatches[i];
- Integer updatedOffset= (Integer) oldToUpdatedOffsets.get(new Integer(oldMatch.getOffset()));
- if (updatedOffset == null)
- updatedOffset= new Integer(-1); //match not updated
- updatedOffsets.put(updatedOffset, oldMatch);
- }
- return updatedOffsets;
- }
-
- /** @return Map &lt;Integer oldOffset, Integer updatedOffset&gt; */
- private static Map getEditChangeOffsetUpdates(TextChange change) {
- TextEditChangeGroup[] editChanges= change.getTextEditChangeGroups();
- Map/*<oldOffset, newOffset>*/ offsetUpdates= new HashMap(editChanges.length);
- for (int i= 0; i < editChanges.length; i++) {
- TextEditChangeGroup editChange= editChanges[i];
- IRegion oldRegion= editChange.getRegion();
- if (oldRegion == null)
- continue;
- IRegion updatedRegion= TextEdit.getCoverage(change.getPreviewEdits(editChange.getTextEdits()));
- if (updatedRegion == null)
- continue;
-
- offsetUpdates.put(new Integer(oldRegion.getOffset()), new Integer(updatedRegion.getOffset()));
- }
- return offsetUpdates;
- }
-
- private static void addReferenceShadowedError(IJavaScriptUnit cu, SearchMatch newMatch, String newElementName, RefactoringStatus result) {
- //Found a new match with no corresponding old match.
- //-> The new match is a reference which was pointing to another element,
- //but that other element has been shadowed
-
- //TODO: should not have to filter declarations:
- if (newMatch instanceof MethodDeclarationMatch || newMatch instanceof FieldDeclarationMatch)
- return;
- ISourceRange range= getOldSourceRange(newMatch);
- RefactoringStatusContext context= JavaStatusContext.create(cu, range);
- String message= Messages.format(
- RefactoringCoreMessages.RenameAnalyzeUtil_reference_shadowed,
- new String[] {cu.getElementName(), newElementName});
- result.addError(message, context);
- }
-
- private static ISourceRange getOldSourceRange(SearchMatch newMatch) {
- // cannot transfom offset in preview to offset in original -> just show enclosing method
- IJavaScriptElement newMatchElement= (IJavaScriptElement) newMatch.getElement();
- IJavaScriptElement primaryElement= newMatchElement.getPrimaryElement();
- ISourceRange range= null;
- if (primaryElement.exists() && primaryElement instanceof ISourceReference) {
- try {
- range= ((ISourceReference) primaryElement).getSourceRange();
- } catch (JavaScriptModelException e) {
- // can live without source range
- }
- }
- return range;
- }
-
- private static void addShadowsError(IJavaScriptUnit cu, SearchMatch oldMatch, RefactoringStatus result) {
- // Old match not found in new matches -> reference has been shadowed
-
- //TODO: should not have to filter declarations:
- if (oldMatch instanceof MethodDeclarationMatch || oldMatch instanceof FieldDeclarationMatch)
- return;
- ISourceRange range= new SourceRange(oldMatch.getOffset(), oldMatch.getLength());
- RefactoringStatusContext context= JavaStatusContext.create(cu, range);
- String message= Messages.format(RefactoringCoreMessages.RenameAnalyzeUtil_shadows, cu.getElementName());
- result.addError(message, context);
- }
-
- /**
- * This method analyzes a set of local variable renames inside one cu. It checks whether
- * any new compile errors have been introduced by the rename(s) and whether the correct
- * node(s) has/have been renamed.
- *
- * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
- * @param cuChange the TextChange containing all local variable changes to be applied.
- * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
- * @param statementsRecovery whether statements recovery should be performed when parsing the changed CU
- * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
- * @throws CoreException thrown if there was an error greating the preview content of the change
- */
- public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, JavaScriptUnit oldCUNode, boolean statementsRecovery) throws CoreException {
-
- RefactoringStatus result= new RefactoringStatus();
- IJavaScriptUnit compilationUnit= (IJavaScriptUnit) oldCUNode.getJavaElement();
-
- String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
- JavaScriptUnit newCUNode= new RefactoringASTParser(AST.JLS3).parse(newCuSource, compilationUnit, true, statementsRecovery, null);
-
- result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
- if (result.hasError())
- return result;
-
- for (int i= 0; i < analyzePackages.length; i++) {
- ASTNode enclosing= getEnclosingBlockOrMethod(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);
-
- // get new declaration
- IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
- ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
- Assert.isTrue(newDeclaration instanceof Name);
-
- VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
- Assert.isNotNull(declaration);
-
- SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
- result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
- }
- return result;
- }
-
- private static VariableDeclaration getVariableDeclaration(Name node) {
- IBinding binding= node.resolveBinding();
- if (binding == null && node.getParent() instanceof VariableDeclaration)
- return (VariableDeclaration) node.getParent();
-
- if (binding != null && binding.getKind() == IBinding.VARIABLE) {
- JavaScriptUnit cu= (JavaScriptUnit) ASTNodes.getParent(node, JavaScriptUnit.class);
- return ASTNodes.findVariableDeclaration( ((IVariableBinding) binding), cu);
- }
- return null;
- }
-
- private static ASTNode getEnclosingBlockOrMethod(TextEdit declarationEdit, TextChange change, JavaScriptUnit newCUNode) {
- ASTNode enclosing= RefactoringAnalyzeUtil.getBlock(declarationEdit, change, newCUNode);
- if (enclosing == null)
- enclosing= RefactoringAnalyzeUtil.getMethodDeclaration(declarationEdit, change, newCUNode);
- return enclosing;
- }
-
- private static RefactoringStatus analyzeCompileErrors(String newCuSource, JavaScriptUnit newCUNode, JavaScriptUnit oldCUNode) {
- RefactoringStatus result= new RefactoringStatus();
- IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, oldCUNode);
- for (int i= 0; i < newProblems.length; i++) {
- IProblem problem= newProblems[i];
- if (problem.isError())
- result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, new SourceRange(problem))));
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameCompilationUnitProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameCompilationUnitProcessor.java
deleted file mode 100644
index fd35e7ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameCompilationUnitProcessor.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.IResourceMapper;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptElementMapper;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.RenameTypeArguments;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameResourceDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ISimilarDeclarationUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-public final class RenameCompilationUnitProcessor extends JavaRenameProcessor implements IReferenceUpdating, ITextUpdating, IQualifiedNameUpdating, ISimilarDeclarationUpdating, IResourceMapper, IJavaScriptElementMapper {
-
- private RenameTypeProcessor fRenameTypeProcessor= null;
- private boolean fWillRenameType= false;
- private IJavaScriptUnit fCu;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameCompilationUnitProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename compilation unit processor.
- * @param unit the compilation unit, or <code>null</code> if invoked by scripting
- * @throws CoreException
- */
- public RenameCompilationUnitProcessor(IJavaScriptUnit unit) throws CoreException {
- fCu= unit;
- if (fCu != null) {
- computeRenameTypeRefactoring();
- setNewElementName(fCu.getElementName());
- }
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() {
- return RefactoringAvailabilityTester.isRenameAvailable(fCu);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameCompilationUnitRefactoring_name;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fCu);
- }
-
- public Object[] getElements() {
- return new Object[] {fCu};
- }
-
- protected RenameModifications computeRenameModifications() {
- RenameModifications result= new RenameModifications();
- result.rename(fCu, new RenameArguments(getNewElementName(), getUpdateReferences()));
- if (fRenameTypeProcessor != null) {
- String newTypeName= removeFileNameExtension(getNewElementName());
- RenameTypeArguments arguments= new RenameTypeArguments(newTypeName, getUpdateReferences(), getUpdateSimilarDeclarations(), getSimilarElements());
- result.rename(fRenameTypeProcessor.getType(), arguments, getUpdateSimilarDeclarations()
- ? new RenameTypeProcessor.ParticipantDescriptorFilter()
- : null);
- }
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- if (!fWillRenameType) {
- IFile file= ResourceUtil.getFile(fCu);
- if (file != null)
- return new IFile[] {file};
- }
- return new IFile[0];
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES;
- }
-
- //---- IRenameProcessor -------------------------------------
-
- public String getCurrentElementName() {
- return getSimpleCUName();
- }
-
- public String getCurrentElementQualifier() {
- IPackageFragment pack= (IPackageFragment) fCu.getParent();
- return pack.getElementName();
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws CoreException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- String typeName= removeFileNameExtension(newName);
- RefactoringStatus result= Checks.checkCompilationUnitName(newName);
- if (fWillRenameType)
- result.merge(fRenameTypeProcessor.checkNewElementName(typeName));
- if (Checks.isAlreadyNamed(fCu, newName))
- result.addFatalError(RefactoringCoreMessages.RenameCompilationUnitRefactoring_same_name);
- return result;
- }
-
- public void setNewElementName(String newName) {
- super.setNewElementName(newName);
- if (fWillRenameType)
- fRenameTypeProcessor.setNewElementName(removeFileNameExtension(newName));
- }
-
- public Object getNewElement() {
- IJavaScriptElement parent= fCu.getParent();
- if (parent.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT)
- return fCu; //??
- IPackageFragment pack= (IPackageFragment)parent;
- if (JavaScriptConventions.validateCompilationUnitName(getNewElementName()).getSeverity() == IStatus.ERROR)
- return fCu; //??
- return pack.getJavaScriptUnit(getNewElementName());
- }
-
- //---- ITextUpdating ---------------------------------------------
-
- public boolean canEnableTextUpdating() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.canEnableUpdateReferences();
- }
-
- public boolean getUpdateTextualMatches() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.getUpdateTextualMatches();
- }
-
- public void setUpdateTextualMatches(boolean update) {
- if (fRenameTypeProcessor != null)
- fRenameTypeProcessor.setUpdateTextualMatches(update);
- }
-
- //---- IReferenceUpdating -----------------------------------
-
- public boolean canEnableUpdateReferences() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.canEnableUpdateReferences();
- }
-
- public void setUpdateReferences(boolean update) {
- if (fRenameTypeProcessor != null)
- fRenameTypeProcessor.setUpdateReferences(update);
- }
-
- public boolean getUpdateReferences(){
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.getUpdateReferences();
- }
-
- //---- IQualifiedNameUpdating -------------------------------
-
- public boolean canEnableQualifiedNameUpdating() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.canEnableQualifiedNameUpdating();
- }
-
- public boolean getUpdateQualifiedNames() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.getUpdateQualifiedNames();
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- if (fRenameTypeProcessor == null)
- return;
- fRenameTypeProcessor.setUpdateQualifiedNames(update);
- }
-
- public String getFilePatterns() {
- if (fRenameTypeProcessor == null)
- return null;
- return fRenameTypeProcessor.getFilePatterns();
- }
-
- public void setFilePatterns(String patterns) {
- if (fRenameTypeProcessor == null)
- return;
- fRenameTypeProcessor.setFilePatterns(patterns);
- }
-
- // ---- ISimilarDeclarationUpdating ------------------------------
-
- public boolean canEnableSimilarDeclarationUpdating() {
- if (fRenameTypeProcessor == null)
- return false;
- else
- return fRenameTypeProcessor.canEnableSimilarDeclarationUpdating();
- }
-
- public void setUpdateSimilarDeclarations(boolean update) {
- if (fRenameTypeProcessor == null)
- return;
- fRenameTypeProcessor.setUpdateSimilarDeclarations(update);
- }
-
- public boolean getUpdateSimilarDeclarations() {
- if (fRenameTypeProcessor == null)
- return false;
- return fRenameTypeProcessor.getUpdateSimilarDeclarations();
- }
-
- public int getMatchStrategy() {
- if (fRenameTypeProcessor == null)
- return RenamingNameSuggestor.STRATEGY_EXACT; // method should not be called in this case anyway ...
- return fRenameTypeProcessor.getMatchStrategy();
- }
-
- public void setMatchStrategy(int selectedStrategy) {
- if (fRenameTypeProcessor == null)
- return;
- fRenameTypeProcessor.setMatchStrategy(selectedStrategy);
- }
-
- public IJavaScriptElement[] getSimilarElements() {
- if (fRenameTypeProcessor == null)
- return null;
- return fRenameTypeProcessor.getSimilarElements();
- }
-
- public IResource getRefactoredResource(IResource element) {
- if (fRenameTypeProcessor == null)
- return element;
- return fRenameTypeProcessor.getRefactoredResource(element);
- }
-
- public IJavaScriptElement getRefactoredJavaScriptElement(IJavaScriptElement element) {
- if (fRenameTypeProcessor == null)
- return element;
- return fRenameTypeProcessor.getRefactoredJavaScriptElement(element);
- }
-
- // --- preconditions ----------------------------------
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- if (fRenameTypeProcessor != null && ! fCu.isStructureKnown()){
- fRenameTypeProcessor= null;
- fWillRenameType= false;
- return new RefactoringStatus();
- }
-
- //for a test case what it's needed, see bug 24248
- //(the type might be gone from the editor by now)
- if (fWillRenameType && fRenameTypeProcessor != null && ! fRenameTypeProcessor.getType().exists()){
- fRenameTypeProcessor= null;
- fWillRenameType= false;
- return new RefactoringStatus();
- }
-
- // we purposely do not check activation of the renameTypeRefactoring here.
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- try{
- if (fWillRenameType && (!fCu.isStructureKnown())){
- RefactoringStatus result1= new RefactoringStatus();
-
- RefactoringStatus result2= new RefactoringStatus();
- result2.merge(Checks.checkCompilationUnitNewName(fCu, getNewElementName()));
- if (result2.hasFatalError())
- result1.addError(Messages.format(RefactoringCoreMessages.RenameCompilationUnitRefactoring_not_parsed_1, fCu.getElementName()));
- else
- result1.addError(Messages.format(RefactoringCoreMessages.RenameCompilationUnitRefactoring_not_parsed, fCu.getElementName()));
- result1.merge(result2);
- }
-
- if (fWillRenameType) {
- return fRenameTypeProcessor.checkFinalConditions(pm, context);
- } else {
- return Checks.checkCompilationUnitNewName(fCu, getNewElementName());
- }
- } finally{
- pm.done();
- }
- }
-
- private void computeRenameTypeRefactoring() throws CoreException{
-// if (getSimpleCUName().indexOf(".") != -1) { //$NON-NLS-1$
- fRenameTypeProcessor= null;
- fWillRenameType= false;
- return;
-// }
-// IType type= getTypeWithTheSameName();
-// if (type != null) {
-// fRenameTypeProcessor= new RenameTypeProcessor(type);
-// } else {
-// fRenameTypeProcessor= null;
-// }
-// fWillRenameType= fRenameTypeProcessor != null && fCu.isStructureKnown();
- }
-
- private IType getTypeWithTheSameName() {
- try {
- IType[] topLevelTypes= fCu.getTypes();
- String name= getSimpleCUName();
- for (int i = 0; i < topLevelTypes.length; i++) {
- if (name.equals(topLevelTypes[i].getElementName()))
- return topLevelTypes[i];
- }
- return null;
- } catch (CoreException e) {
- return null;
- }
- }
-
- private String getSimpleCUName() {
- return removeFileNameExtension(fCu.getElementName());
- }
-
- /**
- * Removes the extension (whatever comes after the last '.') from the given file name.
- */
- private static String removeFileNameExtension(String fileName) {
- if (fileName.lastIndexOf(".") == -1) //$NON-NLS-1$
- return fileName;
- return fileName.substring(0, fileName.lastIndexOf(".")); //$NON-NLS-1$
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- // renaming the file is taken care of in renameTypeRefactoring
- if (fWillRenameType)
- return fRenameTypeProcessor.createChange(pm);
- fRenameTypeProcessor= null;
- final String newName= getNewElementName();
- final IResource resource= fCu.getResource();
- if (resource != null && resource.isLinked()) {
- final IProject project= resource.getProject();
- final String name= project.getName();
- final String description= Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_descriptor_description_short, resource.getName());
- final String header= Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_descriptor_description, new String[] { resource.getFullPath().toString(), newName});
- final String comment= new JDTRefactoringDescriptorComment(name, this, header).asString();
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE;
- final RenameResourceDescriptor descriptor= new RenameResourceDescriptor();
- descriptor.setProject(name);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setResource(resource);
- descriptor.setNewName(newName);
- return new DynamicValidationStateChange(new RenameResourceChange(descriptor, resource, newName, comment));
- }
- String label= null;
- final IPackageFragment fragment= (IPackageFragment) fCu.getParent();
- if (!fragment.isDefaultPackage())
- label= fragment.getElementName() + "." + fCu.getElementName(); //$NON-NLS-1$
- else
- label= fCu.getElementName();
- final String name= fCu.getJavaScriptProject().getElementName();
- final String description= Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_descriptor_description_short, fCu.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameCompilationUnitChange_descriptor_description, new String[] { label, newName});
- final String comment= new JDTRefactoringDescriptorComment(name, this, header).asString();
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE;
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_JAVASCRIPT_UNIT);
- descriptor.setProject(name);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fCu);
- descriptor.setNewName(newName);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameCompilationUnitRefactoring_name, new Change[] { new RenameCompilationUnitChange(fCu, newName)});
- }
-
- /**
- * {@inheritDoc}
- */
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- if (fWillRenameType)
- return fRenameTypeProcessor.postCreateChange(participantChanges, pm);
- return super.postCreateChange(participantChanges, pm);
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (!(arguments instanceof JavaRefactoringArguments)) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- }
-
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle == null) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- }
-
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_JAVASCRIPT_UNIT);
-
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name == null || name.length() == 0)
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
-
- fCu= (IJavaScriptUnit) element;
- try {
- computeRenameTypeRefactoring();
- setNewElementName(name);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_JAVASCRIPT_UNIT);
- }
- return new RefactoringStatus();
- }
-
- /**
- * @return the RenameTypeProcessor or <code>null</code> if no type will be renamed
- */
- public RenameTypeProcessor getRenameTypeProcessor() {
- return fRenameTypeProcessor;
- }
-
- public boolean isWillRenameType() {
- return fWillRenameType;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameFieldProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameFieldProcessor.java
deleted file mode 100644
index 8f2a6e86..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameFieldProcessor.java
+++ /dev/null
@@ -1,907 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CollectingSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateFieldCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class RenameFieldProcessor extends JavaRenameProcessor implements IReferenceUpdating, ITextUpdating, IDelegateUpdating {
-
- protected static final String ATTRIBUTE_TEXTUAL_MATCHES= "textual"; //$NON-NLS-1$
- private static final String ATTRIBUTE_RENAME_GETTER= "getter"; //$NON-NLS-1$
- private static final String ATTRIBUTE_RENAME_SETTER= "setter"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DELEGATE= "delegate"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DEPRECATE= "deprecate"; //$NON-NLS-1$
-
- protected IField fField;
- private SearchResultGroup[] fReferences;
- private TextChangeManager fChangeManager;
- protected boolean fUpdateReferences;
- protected boolean fUpdateTextualMatches;
- private boolean fRenameGetter;
- private boolean fRenameSetter;
- private boolean fIsComposite;
- private GroupCategorySet fCategorySet;
- private boolean fDelegateUpdating;
- private boolean fDelegateDeprecation;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameFieldProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename field processor.
- * @param field the field, or <code>null</code> if invoked by scripting
- */
- public RenameFieldProcessor(IField field) {
- this(field, new TextChangeManager(true), null);
- fIsComposite= false;
- }
-
- /**
- * Creates a new rename field processor.
- * <p>
- * This constructor is only used by <code>RenameTypeProcessor</code>.
- * </p>
- * @param field the field
- * @param manager the change manager
- * @param categorySet the group category set
- */
- RenameFieldProcessor(IField field, TextChangeManager manager, GroupCategorySet categorySet) {
- initialize(field);
- fChangeManager= manager;
- fCategorySet= categorySet;
- fDelegateUpdating= false;
- fDelegateDeprecation= true;
- fIsComposite= true;
- }
-
- private void initialize(IField field) {
- fField= field;
- if (fField != null)
- setNewElementName(fField.getElementName());
- fUpdateReferences= true;
- fUpdateTextualMatches= false;
-
- fRenameGetter= false;
- fRenameSetter= false;
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameFieldAvailable(fField);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameFieldRefactoring_name;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fField);
- }
-
- public IField getField() {
- return fField;
- }
-
- public Object[] getElements() {
- return new Object[] { fField};
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- result.rename(fField, new RenameArguments(getNewElementName(), getUpdateReferences()));
- if (fRenameGetter) {
- IFunction getter= getGetter();
- if (getter != null) {
- result.rename(getter, new RenameArguments(getNewGetterName(), getUpdateReferences()));
- }
- }
- if (fRenameSetter) {
- IFunction setter= getSetter();
- if (setter != null) {
- result.rename(setter, new RenameArguments(getNewSetterName(), getUpdateReferences()));
- }
- }
- return result;
- }
-
- protected IFile[] getChangedFiles() {
- return ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
- }
-
- //---- IRenameProcessor -------------------------------------
-
- public final String getCurrentElementName(){
- return fField.getElementName();
- }
-
- public final String getCurrentElementQualifier(){
- return JavaModelUtil.getFullyQualifiedName(fField.getDeclaringType());
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws CoreException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- RefactoringStatus result= Checks.checkFieldName(newName);
-
- if (isInstanceField(fField) && (!Checks.startsWithLowerCase(newName)))
- result.addWarning(fIsComposite
- ? Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase2, new String[] { newName, fField.getDeclaringType().getElementName() })
- : RefactoringCoreMessages.RenameFieldRefactoring_should_start_lowercase);
-
- if (Checks.isAlreadyNamed(fField, newName))
- result.addError(fIsComposite
- ? Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_another_name2, new String[] { newName, fField.getDeclaringType().getElementName() })
- : RefactoringCoreMessages.RenameFieldRefactoring_another_name,
- JavaStatusContext.create(fField));
-
- boolean exists = (fField.getDeclaringType()!=null) ?
- fField.getDeclaringType().getField(newName).exists() :
- fField.getJavaScriptUnit().getField(newName).exists() ;
- if (exists)
- result.addError(fIsComposite
- ? Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined2, new String[] { newName, fField.getDeclaringType().getElementName() })
- : RefactoringCoreMessages.RenameFieldRefactoring_field_already_defined,
- JavaStatusContext.create(fField.getDeclaringType().getField(newName)));
- return result;
- }
-
- public Object getNewElement() {
- return (fField.getDeclaringType()!=null) ?
- fField.getDeclaringType().getField(getNewElementName()):
- fField.getJavaScriptUnit().getField(getNewElementName());
- }
-
- //---- ITextUpdating2 ---------------------------------------------
-
- public boolean canEnableTextUpdating() {
- return true;
- }
-
- public boolean getUpdateTextualMatches() {
- return fUpdateTextualMatches;
- }
-
- public void setUpdateTextualMatches(boolean update) {
- fUpdateTextualMatches= update;
- }
-
- //---- IReferenceUpdating -----------------------------------
-
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- public void setUpdateReferences(boolean update) {
- fUpdateReferences= update;
- }
-
- public boolean getUpdateReferences(){
- return fUpdateReferences;
- }
-
- //-- getter/setter --------------------------------------------------
-
- /**
- * @return Error message or <code>null</code> if getter can be renamed.
- * @throws CoreException
- */
- public String canEnableGetterRenaming() throws CoreException{
- IFunction getter= getGetter();
- if (getter == null)
- return ""; //$NON-NLS-1$
- final NullProgressMonitor monitor= new NullProgressMonitor();
- if (MethodChecks.isVirtual(getter)) {
- final ITypeHierarchy hierarchy= getter.getDeclaringType().newTypeHierarchy(monitor);
- if (MethodChecks.overridesAnotherMethod(getter, hierarchy) != null)
- return RefactoringCoreMessages.RenameFieldRefactoring_declared_in_supertype;
- }
- return null;
- }
-
- /**
- * @return Error message or <code>null</code> if setter can be renamed.
- * @throws CoreException
- */
- public String canEnableSetterRenaming() throws CoreException{
- IFunction setter= getSetter();
- if (setter == null)
- return ""; //$NON-NLS-1$
- final NullProgressMonitor monitor= new NullProgressMonitor();
- if (MethodChecks.isVirtual(setter)) {
- final ITypeHierarchy hierarchy= setter.getDeclaringType().newTypeHierarchy(monitor);
- if (MethodChecks.overridesAnotherMethod(setter, hierarchy) != null)
- return RefactoringCoreMessages.RenameFieldRefactoring_declared_in_supertype;
- }
- return null;
- }
-
- public boolean getRenameGetter() {
- return fRenameGetter;
- }
-
- public void setRenameGetter(boolean renameGetter) {
- fRenameGetter= renameGetter;
- }
-
- public boolean getRenameSetter() {
- return fRenameSetter;
- }
-
- public void setRenameSetter(boolean renameSetter) {
- fRenameSetter= renameSetter;
- }
-
- public IFunction getGetter() throws CoreException {
- return GetterSetterUtil.getGetter(fField);
- }
-
- public IFunction getSetter() throws CoreException {
- return GetterSetterUtil.getSetter(fField);
- }
-
- public String getNewGetterName() throws CoreException {
- IFunction primaryGetterCandidate= JavaModelUtil.findMethod(GetterSetterUtil.getGetterName(fField, new String[0]), new String[0], false, fField.getDeclaringType());
- if (! JavaModelUtil.isBoolean(fField) || (primaryGetterCandidate != null && primaryGetterCandidate.exists()))
- return GetterSetterUtil.getGetterName(fField.getJavaScriptProject(), getNewElementName(), fField.getFlags(), JavaModelUtil.isBoolean(fField), null);
- //bug 30906 describes why we need to look for other alternatives here
- return GetterSetterUtil.getGetterName(fField.getJavaScriptProject(), getNewElementName(), fField.getFlags(), false, null);
- }
-
- public String getNewSetterName() throws CoreException {
- return GetterSetterUtil.getSetterName(fField.getJavaScriptProject(), getNewElementName(), fField.getFlags(), JavaModelUtil.isBoolean(fField), null);
- }
-
- // ------------------- IDelegateUpdating ----------------------
-
- public boolean canEnableDelegateUpdating() {
- return (getDelegateCount() > 0);
- }
-
- public boolean getDelegateUpdating() {
- return fDelegateUpdating;
- }
-
- public void setDelegateUpdating(boolean update) {
- fDelegateUpdating= update;
- }
-
- public void setDeprecateDelegates(boolean deprecate) {
- fDelegateDeprecation= deprecate;
- }
-
- public boolean getDeprecateDelegates() {
- return fDelegateDeprecation;
- }
-
- /**
- * Returns the maximum number of delegates which can
- * be created for the input elements of this refactoring.
- *
- * @return maximum number of delegates
- */
- public int getDelegateCount() {
- int count= 0;
- try {
- if (RefactoringAvailabilityTester.isDelegateCreationAvailable(getField()))
- count++;
- if (fRenameGetter && getGetter() != null)
- count++;
- if (fRenameSetter && getSetter() != null)
- count++;
- } catch (CoreException e) {
- // no-op
- }
- return count;
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- IField primary= (IField) fField.getPrimaryElement();
- if (primary == null || !primary.exists()) {
- String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_deleted, fField.getJavaScriptUnit().getElementName());
- return RefactoringStatus.createFatalErrorStatus(message);
- }
- fField= primary;
-
- return Checks.checkIfCuBroken(fField);
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- try{
- pm.beginTask("", 18); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
- RefactoringStatus result= new RefactoringStatus();
- result.merge(Checks.checkIfCuBroken(fField));
- if (result.hasFatalError())
- return result;
- result.merge(checkNewElementName(getNewElementName()));
- pm.worked(1);
- result.merge(checkEnclosingHierarchy());
- pm.worked(1);
- result.merge(checkNestedHierarchy(fField.getDeclaringType()));
- pm.worked(1);
-
- if (fUpdateReferences){
- pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_searching);
- fReferences= getReferences(new SubProgressMonitor(pm, 3), result);
- pm.setTaskName(RefactoringCoreMessages.RenameFieldRefactoring_checking);
- } else {
- fReferences= new SearchResultGroup[0];
- pm.worked(3);
- }
-
- if (fUpdateReferences)
- result.merge(analyzeAffectedCompilationUnits());
- else
- Checks.checkCompileErrorsInAffectedFile(result, fField.getResource());
-
- if (getGetter() != null && fRenameGetter){
- result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getGetter(), getNewGetterName()));
- result.merge(Checks.checkIfConstructorName(getGetter(), getNewGetterName(), fField.getDeclaringType().getElementName()));
- } else {
- pm.worked(1);
- }
-
- if (getSetter() != null && fRenameSetter){
- result.merge(checkAccessor(new SubProgressMonitor(pm, 1), getSetter(), getNewSetterName()));
- result.merge(Checks.checkIfConstructorName(getSetter(), getNewSetterName(), fField.getDeclaringType().getElementName()));
- } else {
- pm.worked(1);
- }
-
- result.merge(createChanges(new SubProgressMonitor(pm, 10)));
- if (result.hasFatalError())
- return result;
-
- return result;
- } finally{
- pm.done();
- }
- }
-
- //----------
- private RefactoringStatus checkAccessor(IProgressMonitor pm, IFunction existingAccessor, String newAccessorName) throws CoreException{
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkAccessorDeclarations(pm, existingAccessor));
- result.merge(checkNewAccessor(existingAccessor, newAccessorName));
- return result;
- }
-
- private RefactoringStatus checkNewAccessor(IFunction existingAccessor, String newAccessorName) throws CoreException{
- RefactoringStatus result= new RefactoringStatus();
- IFunction accessor= JavaModelUtil.findMethod(newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType());
- if (accessor == null || !accessor.exists())
- return null;
-
- String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
- new String[]{JavaElementUtil.createMethodSignature(accessor), JavaModelUtil.getFullyQualifiedName(fField.getDeclaringType())});
- result.addError(message, JavaStatusContext.create(accessor));
- return result;
- }
-
- private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IFunction existingAccessor) throws CoreException{
- RefactoringStatus result= new RefactoringStatus();
- SearchPattern pattern= SearchPattern.createPattern(existingAccessor, IJavaScriptSearchConstants.DECLARATIONS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptSearchScope scope= SearchEngine.createHierarchyScope(fField.getDeclaringType());
- SearchResultGroup[] groupDeclarations= RefactoringSearchEngine.search(pattern, scope, pm, result);
- Assert.isTrue(groupDeclarations.length > 0);
- if (groupDeclarations.length != 1){
- String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_overridden,
- JavaElementUtil.createMethodSignature(existingAccessor));
- result.addError(message);
- } else {
- SearchResultGroup group= groupDeclarations[0];
- Assert.isTrue(group.getSearchResults().length > 0);
- if (group.getSearchResults().length != 1){
- String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides,
- JavaElementUtil.createMethodSignature(existingAccessor));
- result.addError(message);
- }
- }
- return result;
- }
-
- private static boolean isInstanceField(IField field) throws CoreException{
- return ! JdtFlags.isStatic(field);
- }
-
- private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException {
- if (type==null)
- return null;
- IType[] nestedTypes= type.getTypes();
- if (nestedTypes == null)
- return null;
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < nestedTypes.length; i++){
- IField otherField= nestedTypes[i].getField(getNewElementName());
- if (otherField.exists()){
- String msg= Messages.format(
- RefactoringCoreMessages.RenameFieldRefactoring_hiding,
- new String[]{fField.getElementName(), getNewElementName(), JavaModelUtil.getFullyQualifiedName(nestedTypes[i])});
- result.addWarning(msg, JavaStatusContext.create(otherField));
- }
- result.merge(checkNestedHierarchy(nestedTypes[i]));
- }
- return result;
- }
-
- private RefactoringStatus checkEnclosingHierarchy() {
- IType current= fField.getDeclaringType();
- if (current==null || Checks.isTopLevel(current))
- return null;
- RefactoringStatus result= new RefactoringStatus();
- while (current != null){
- IField otherField= current.getField(getNewElementName());
- if (otherField.exists()){
- String msg= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_hiding2,
- new String[]{getNewElementName(), JavaModelUtil.getFullyQualifiedName(current), otherField.getElementName()});
- result.addWarning(msg, JavaStatusContext.create(otherField));
- }
- current= current.getDeclaringType();
- }
- return result;
- }
-
- /*
- * (non java-doc)
- * Analyzes all compilation units in which type is referenced
- */
- private RefactoringStatus analyzeAffectedCompilationUnits() throws CoreException{
- RefactoringStatus result= new RefactoringStatus();
- fReferences= Checks.excludeCompilationUnits(fReferences, result);
- if (result.hasFatalError())
- return result;
-
- result.merge(Checks.checkCompileErrorsInAffectedFiles(fReferences));
- return result;
- }
-
- private SearchPattern createSearchPattern(){
- return SearchPattern.createPattern(fField, IJavaScriptSearchConstants.REFERENCES);
- }
-
- private IJavaScriptSearchScope createRefactoringScope() throws CoreException{
- return RefactoringScopeFactory.create(fField);
- }
-
- private SearchResultGroup[] getReferences(IProgressMonitor pm, RefactoringStatus status) throws CoreException{
- return RefactoringSearchEngine.search(createSearchPattern(), createRefactoringScope(), pm, status);
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.RenameFieldRefactoring_checking, 1);
- final TextChange[] changes= fChangeManager.getAllChanges();
- final List list= new ArrayList(changes.length);
- list.addAll(Arrays.asList(changes));
- String project= null;
- IJavaScriptProject javaProject= fField.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
- try {
- if (!Flags.isPrivate(fField.getFlags()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final IType declaring= fField.getDeclaringType();
- try {
- if ( declaring!=null && (declaring.isAnonymous() || declaring.isLocal()))
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_descriptor_description_short, fField.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameFieldProcessor_descriptor_description, new String[] { fField.getElementName(), JavaScriptElementLabels.getElementLabel(fField.getParent(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED), getNewElementName()});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- if (fRenameGetter)
- comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_getter);
- if (fRenameSetter)
- comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_settter);
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_FIELD);
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment.asString());
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fField);
- descriptor.setNewName(getNewElementName());
- descriptor.setUpdateReferences(fUpdateReferences);
- descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
- descriptor.setRenameGetters(fRenameGetter);
- descriptor.setRenameSetters(fRenameSetter);
- descriptor.setKeepOriginal(fDelegateUpdating);
- descriptor.setDeprecateDelegate(fDelegateDeprecation);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameFieldRefactoring_change_name, (Change[]) list.toArray(new Change[list.size()]));
- } finally {
- monitor.done();
- }
- }
-
- private RefactoringStatus createChanges(IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.RenameFieldRefactoring_checking, 10);
- RefactoringStatus result= new RefactoringStatus();
- if (!fIsComposite)
- fChangeManager.clear();
-
- // Delegate creation requires ASTRewrite which
- // creates a new change -> do this first.
- if (fDelegateUpdating)
- result.merge(addDelegates());
-
- addDeclarationUpdate();
-
- if (fUpdateReferences) {
- addReferenceUpdates(new SubProgressMonitor(pm, 1));
- result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 2)));
- if (result.hasFatalError())
- return result;
- } else {
- pm.worked(3);
- }
-
- if (getGetter() != null && fRenameGetter) {
- addGetterOccurrences(new SubProgressMonitor(pm, 1), result);
- } else {
- pm.worked(1);
- }
-
- if (getSetter() != null && fRenameSetter) {
- addSetterOccurrences(new SubProgressMonitor(pm, 1), result);
- } else {
- pm.worked(1);
- }
-
- if (fUpdateTextualMatches) {
- addTextMatches(new SubProgressMonitor(pm, 5));
- } else {
- pm.worked(5);
- }
- pm.done();
- return result;
- }
-
- private void addDeclarationUpdate() throws CoreException {
- ISourceRange nameRange= fField.getNameRange();
- TextEdit textEdit= new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName());
- IJavaScriptUnit cu= fField.getJavaScriptUnit();
- String groupName= RefactoringCoreMessages.RenameFieldRefactoring_Update_field_declaration;
- addTextEdit(fChangeManager.get(cu), groupName, textEdit);
- }
-
- private RefactoringStatus addDelegates() throws JavaScriptModelException, CoreException {
-
- RefactoringStatus status= new RefactoringStatus();
- CompilationUnitRewrite rewrite= new CompilationUnitRewrite(fField.getJavaScriptUnit());
- rewrite.setResolveBindings(true);
-
- // add delegate for the field
- if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) {
- FieldDeclaration fieldDeclaration= ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot());
- if (fieldDeclaration.fragments().size() > 1) {
- status.addWarning(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_more_than_one_fragment, fField
- .getElementName()), JavaStatusContext.create(fField));
- } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)).getInitializer() == null) {
- status.addWarning(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, fField
- .getElementName()), JavaStatusContext.create(fField));
- } else {
- DelegateFieldCreator creator= new DelegateFieldCreator();
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setDeclaration(fieldDeclaration);
- creator.setNewElementName(getNewElementName());
- creator.setSourceRewrite(rewrite);
- creator.prepareDelegate();
- creator.createEdit();
- }
- }
-
- // add delegates for getter and setter methods
- // there may be getters even if the field is static final
- if (getGetter() != null && fRenameGetter)
- addMethodDelegate(getGetter(), getNewGetterName(), rewrite);
- if (getSetter() != null && fRenameSetter)
- addMethodDelegate(getSetter(), getNewSetterName(), rewrite);
-
- final CompilationUnitChange change= rewrite.createChange();
- if (change != null) {
- change.setKeepPreviewEdits(true);
- fChangeManager.manage(fField.getJavaScriptUnit(), change);
- }
-
- return status;
- }
-
- private void addMethodDelegate(IFunction getter, String newName, CompilationUnitRewrite rewrite) throws JavaScriptModelException {
- FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(getter, rewrite.getRoot());
- DelegateCreator creator= new DelegateMethodCreator();
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setDeclaration(declaration);
- creator.setNewElementName(newName);
- creator.setSourceRewrite(rewrite);
- creator.prepareDelegate();
- creator.createEdit();
- }
-
- private void addTextEdit(TextChange change, String groupName, TextEdit textEdit) {
- if (fIsComposite)
- TextChangeCompatibility.addTextEdit(change, groupName, textEdit, fCategorySet);
- else
- TextChangeCompatibility.addTextEdit(change, groupName, textEdit);
-
- }
-
- private void addReferenceUpdates(IProgressMonitor pm) {
- pm.beginTask("", fReferences.length); //$NON-NLS-1$
- String editName= RefactoringCoreMessages.RenameFieldRefactoring_Update_field_reference;
- for (int i= 0; i < fReferences.length; i++){
- IJavaScriptUnit cu= fReferences[i].getCompilationUnit();
- if (cu == null)
- continue;
- SearchMatch[] results= fReferences[i].getSearchResults();
- for (int j= 0; j < results.length; j++){
- addTextEdit(fChangeManager.get(cu), editName, createTextChange(results[j]));
- }
- pm.worked(1);
- }
- }
-
- private TextEdit createTextChange(SearchMatch match) {
- return new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
- }
-
- private void addGetterOccurrences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- addAccessorOccurrences(pm, getGetter(), RefactoringCoreMessages.RenameFieldRefactoring_Update_getter_occurrence, getNewGetterName(), status);
- }
-
- private void addSetterOccurrences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- addAccessorOccurrences(pm, getSetter(), RefactoringCoreMessages.RenameFieldRefactoring_Update_setter_occurrence, getNewSetterName(), status);
- }
-
- private void addAccessorOccurrences(IProgressMonitor pm, IFunction accessor, String editName, String newAccessorName, RefactoringStatus status) throws CoreException {
- Assert.isTrue(accessor.exists());
-
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(accessor);
- SearchPattern pattern= SearchPattern.createPattern(accessor, IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- SearchResultGroup[] groupedResults= RefactoringSearchEngine.search(
- pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);
-
- for (int i= 0; i < groupedResults.length; i++) {
- IJavaScriptUnit cu= groupedResults[i].getCompilationUnit();
- if (cu == null)
- continue;
- SearchMatch[] results= groupedResults[i].getSearchResults();
- for (int j= 0; j < results.length; j++){
- SearchMatch searchResult= results[j];
- TextEdit edit= new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
- addTextEdit(fChangeManager.get(cu), editName, edit);
- }
- }
- }
-
- private void addTextMatches(IProgressMonitor pm) throws CoreException {
- TextMatchUpdater.perform(pm, createRefactoringScope(), this, fChangeManager, fReferences);
- }
-
- //----------------
- private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
- IJavaScriptUnit[] newWorkingCopies= null;
- WorkingCopyOwner newWCOwner= new WorkingCopyOwner() { /* must subclass */ };
- try {
- pm.beginTask("", 2); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
- SearchResultGroup[] oldReferences= fReferences;
-
- List compilationUnitsToModify= new ArrayList();
- if (fIsComposite) {
- // limited change set, no accessors.
- for (int i= 0; i < oldReferences.length; i++)
- compilationUnitsToModify.add(oldReferences[i].getCompilationUnit());
- compilationUnitsToModify.add(fField.getJavaScriptUnit());
- } else {
- // include all cus, including accessors
- compilationUnitsToModify.addAll(Arrays.asList(fChangeManager.getAllCompilationUnits()));
- }
-
- newWorkingCopies= RenameAnalyzeUtil.createNewWorkingCopies((IJavaScriptUnit[]) compilationUnitsToModify.toArray(new IJavaScriptUnit[compilationUnitsToModify.size()]),
- fChangeManager, newWCOwner, new SubProgressMonitor(pm, 1));
-
- SearchResultGroup[] newReferences= getNewReferences(new SubProgressMonitor(pm, 1), result, newWCOwner, newWorkingCopies);
- result.merge(RenameAnalyzeUtil.analyzeRenameChanges2(fChangeManager, oldReferences, newReferences, getNewElementName()));
- return result;
- } finally{
- pm.done();
- if (newWorkingCopies != null){
- for (int i= 0; i < newWorkingCopies.length; i++) {
- newWorkingCopies[i].discardWorkingCopy();
- }
- }
- }
- }
-
- private SearchResultGroup[] getNewReferences(IProgressMonitor pm, RefactoringStatus status, WorkingCopyOwner owner, IJavaScriptUnit[] newWorkingCopies) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- IJavaScriptUnit declaringCuWorkingCopy= RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getJavaScriptUnit());
- if (declaringCuWorkingCopy == null)
- return new SearchResultGroup[0];
-
- IField field= getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
- if (field == null || ! field.exists())
- return new SearchResultGroup[0];
-
- CollectingSearchRequestor requestor= null;
- if (fDelegateUpdating && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
- // There will be two new matches inside the delegate (the invocation
- // and the javadoc) which are OK and must not be reported.
- final IField oldField= getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
- requestor= new CollectingSearchRequestor() {
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- if (!oldField.equals(match.getElement()))
- super.acceptSearchMatch(match);
- }
- };
- } else
- requestor= new CollectingSearchRequestor();
-
- SearchPattern newPattern= SearchPattern.createPattern(field, IJavaScriptSearchConstants.REFERENCES);
- return RefactoringSearchEngine.search(newPattern, owner, createRefactoringScope(), requestor, new SubProgressMonitor(pm, 1), status);
- }
-
- private IField getFieldInWorkingCopy(IJavaScriptUnit newWorkingCopyOfDeclaringCu, String elementName) throws CoreException{
- IType type= fField.getDeclaringType();
- IType typeWc= (IType) JavaModelUtil.findInCompilationUnit(newWorkingCopyOfDeclaringCu, type);
- if (typeWc == null)
- return null;
-
- return typeWc.getField(elementName);
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.FIELD)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_FIELD);
- else
- fField= (IField) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String matches= extended.getAttribute(ATTRIBUTE_TEXTUAL_MATCHES);
- if (matches != null) {
- fUpdateTextualMatches= Boolean.valueOf(matches).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TEXTUAL_MATCHES));
- final String getters= extended.getAttribute(ATTRIBUTE_RENAME_GETTER);
- if (getters != null)
- fRenameGetter= Boolean.valueOf(getters).booleanValue();
- else
- fRenameGetter= false;
- final String setters= extended.getAttribute(ATTRIBUTE_RENAME_SETTER);
- if (setters != null)
- fRenameSetter= Boolean.valueOf(setters).booleanValue();
- else
- fRenameSetter= false;
- final String delegate= extended.getAttribute(ATTRIBUTE_DELEGATE);
- if (delegate != null) {
- fDelegateUpdating= Boolean.valueOf(delegate).booleanValue();
- } else
- fDelegateUpdating= false;
- final String deprecate= extended.getAttribute(ATTRIBUTE_DEPRECATE);
- if (deprecate != null) {
- fDelegateDeprecation= Boolean.valueOf(deprecate).booleanValue();
- } else
- fDelegateDeprecation= false;
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateFieldCreator_keep_original_renamed_plural;
- else
- return RefactoringCoreMessages.DelegateFieldCreator_keep_original_renamed_singular;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameJavaProjectProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameJavaProjectProcessor.java
deleted file mode 100644
index 5b0936d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameJavaProjectProcessor.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.net.URI;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameJavaProjectChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-public final class RenameJavaProjectProcessor extends JavaRenameProcessor implements IReferenceUpdating {
-
- private IJavaScriptProject fProject;
- private boolean fUpdateReferences;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameJavaProjectProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename java project processor.
- * @param project the java project, or <code>null</code> if invoked by scripting
- */
- public RenameJavaProjectProcessor(IJavaScriptProject project) {
- fProject= project;
- if (fProject != null)
- setNewElementName(fProject.getElementName());
- fUpdateReferences= true;
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fProject);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameJavaProjectRefactoring_rename;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fProject);
- }
-
- public Object[] getElements() {
- return new Object[] {fProject};
- }
-
- public Object getNewElement() throws CoreException {
- IPath newPath= fProject.getPath().removeLastSegments(1).append(getNewElementName());
- return JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot().findMember(newPath));
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- result.rename(fProject, new RenameArguments(getNewElementName(), getUpdateReferences()));
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- IFile projectFile= fProject.getProject().getFile(".project"); //$NON-NLS-1$
- if (projectFile != null && projectFile.exists()) {
- return new IFile[] {projectFile};
- }
- return new IFile[0];
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_ALL;
- }
-
- //---- IReferenceUpdating --------------------------------------
-
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- public void setUpdateReferences(boolean update) {
- fUpdateReferences= update;
- }
-
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
-
- //---- IRenameProcessor ----------------------------------------------
-
- public String getCurrentElementName() {
- return fProject.getElementName();
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return new RefactoringStatus();
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws CoreException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- RefactoringStatus result= RefactoringStatus.create(ResourcesPlugin.getWorkspace().validateName(newName, IResource.PROJECT));
- if (result.hasFatalError())
- return result;
-
- if (projectNameAlreadyExists(newName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameJavaProjectRefactoring_already_exists);
- if (projectFolderAlreadyExists(newName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameJavaProjectProcessor_folder_already_exists);
-
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try{
- if (isReadOnly()){
- String message= Messages.format(RefactoringCoreMessages.RenameJavaProjectRefactoring_read_only,
- fProject.getElementName());
- return RefactoringStatus.createErrorStatus(message);
- }
- return new RefactoringStatus();
- } finally{
- pm.done();
- }
- }
-
- private boolean isReadOnly() {
- return Resources.isReadOnly(fProject.getResource());
- }
-
- private boolean projectNameAlreadyExists(String newName){
- return ResourcesPlugin.getWorkspace().getRoot().getProject(newName).exists();
- }
-
- private boolean projectFolderAlreadyExists(String newName) throws CoreException {
- boolean isNotInWorkpace= fProject.getProject().getDescription().getLocationURI() != null;
- if (isNotInWorkpace)
- return false; // projects outside of the workspace are not renamed
- URI locationURI= fProject.getProject().getLocationURI();
- IFileStore projectStore= EFS.getStore(locationURI);
- IFileStore newProjectStore= projectStore.getParent().getChild(newName);
- return newProjectStore.fetchInfo().exists();
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- final String description= Messages.format(RefactoringCoreMessages.RenameJavaProjectProcessor_descriptor_description_short, fProject.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameJavaProjectChange_descriptor_description, new String[] { fProject.getElementName(), getNewElementName()});
- final String comment= new JDTRefactoringDescriptorComment(null, this, header).asString();
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE;
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_JAVA_PROJECT);
- descriptor.setProject(null);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fProject);
- descriptor.setNewName(getNewElementName());
- descriptor.setUpdateReferences(fUpdateReferences);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameJavaProjectRefactoring_rename, new Change[] { new RenameJavaProjectChange(fProject, getNewElementName(), fUpdateReferences)});
- } finally {
- monitor.done();
- }
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_PROJECT)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_JAVA_PROJECT);
- else
- fProject= (IJavaScriptProject) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java
deleted file mode 100644
index 3577be7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameLocalVariableDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RefactoringDescriptorChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameAnalyzeUtil.LocalAnalyzePackage;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class RenameLocalVariableProcessor extends JavaRenameProcessor implements IReferenceUpdating {
-
- private ILocalVariable fLocalVariable;
- private IJavaScriptUnit fCu;
-
- //the following fields are set or modified after the construction
- private boolean fUpdateReferences;
- private String fCurrentName;
- private String fNewName;
- private JavaScriptUnit fCompilationUnitNode;
- private VariableDeclaration fTempDeclarationNode;
- private TextChange fChange;
-
- private boolean fIsComposite;
- private GroupCategorySet fCategorySet;
- private TextChangeManager fChangeManager;
- private RenameAnalyzeUtil.LocalAnalyzePackage fLocalAnalyzePackage;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameLocalVariableProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename local variable processor.
- * @param localVariable the local variable, or <code>null</code> if invoked by scripting
- */
- public RenameLocalVariableProcessor(ILocalVariable localVariable) {
- fLocalVariable= localVariable;
- fUpdateReferences= true;
- if (localVariable != null)
- fCu= (IJavaScriptUnit) localVariable.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- fNewName= ""; //$NON-NLS-1$
- fIsComposite= false;
- }
-
- /**
- * Creates a new rename local variable processor.
- * <p>
- * This constructor is only used by <code>RenameTypeProcessor</code>.
- * </p>
- *
- * @param localVariable the local variable
- * @param manager the change manager
- * @param node the compilation unit node
- * @param categorySet the group category set
- */
- RenameLocalVariableProcessor(ILocalVariable localVariable, TextChangeManager manager, JavaScriptUnit node, GroupCategorySet categorySet) {
- this(localVariable);
- fChangeManager= manager;
- fCategorySet= categorySet;
- fCompilationUnitNode= node;
- fIsComposite= true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameProcessor#getAffectedProjectNatures()
- */
- protected final String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fLocalVariable);
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public Object[] getElements() {
- return new Object[] { fLocalVariable };
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
- */
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameTempRefactoring_rename;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fLocalVariable);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating#canEnableUpdateReferences()
- */
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameProcessor#getUpdateReferences()
- */
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating#setUpdateReferences(boolean)
- */
- public void setUpdateReferences(boolean updateReferences) {
- fUpdateReferences= updateReferences;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating#getCurrentElementName()
- */
- public String getCurrentElementName() {
- return fCurrentName;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating#getNewElementName()
- */
- public String getNewElementName() {
- return fNewName;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating#setNewElementName(java.lang.String)
- */
- public void setNewElementName(String newName) {
- Assert.isNotNull(newName);
- fNewName= newName;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating#getNewElement()
- */
- public Object getNewElement() {
- return null; //cannot create an ILocalVariable
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- initAST();
- if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local);
- if (! Checks.isDeclaredIn(fTempDeclarationNode, FunctionDeclaration.class)
- && ! Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers);
-
- initNames();
- return new RefactoringStatus();
- }
-
- private void initAST() throws JavaScriptModelException {
- if (!fIsComposite)
- fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
- ISourceRange sourceRange= fLocalVariable.getNameRange();
- ASTNode name= NodeFinder.perform(fCompilationUnitNode, sourceRange);
- if (name == null)
- return;
- if (name.getParent() instanceof VariableDeclaration)
- fTempDeclarationNode= (VariableDeclaration) name.getParent();
- }
-
- private void initNames(){
- fCurrentName= fTempDeclarationNode.getName().getIdentifier();
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- result.rename(fLocalVariable, new RenameArguments(getNewElementName(), getUpdateReferences()));
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- return new IFile[] {ResourceUtil.getFile(fCu)};
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_NOTHING;
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context)
- throws CoreException, OperationCanceledException {
- try {
- pm.beginTask("", 1); //$NON-NLS-1$
-
- RefactoringStatus result= checkNewElementName(fNewName);
- if (result.hasFatalError())
- return result;
- createEdits();
- if (!fIsComposite) {
- LocalAnalyzePackage[] localAnalyzePackages= new RenameAnalyzeUtil.LocalAnalyzePackage[] { fLocalAnalyzePackage };
- result.merge(RenameAnalyzeUtil.analyzeLocalRenames(localAnalyzePackages, fChange, fCompilationUnitNode, true));
- }
- return result;
- } finally {
- pm.done();
- if (fIsComposite) {
- // end of life cycle for this processor
- fChange= null;
- fCompilationUnitNode= null;
- fTempDeclarationNode= null;
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating#checkNewElementName(java.lang.String)
- */
- public RefactoringStatus checkNewElementName(String newName) throws JavaScriptModelException {
- RefactoringStatus result= Checks.checkFieldName(newName);
- if (! Checks.startsWithLowerCase(newName))
- if (fIsComposite) {
- final String nameOfParent= (fLocalVariable.getParent() instanceof IFunction) ? fLocalVariable.getParent().getElementName() : RefactoringCoreMessages.JavaElementUtil_initializer;
- final String nameOfType= fLocalVariable.getAncestor(IJavaScriptElement.TYPE).getElementName();
- result.addWarning(Messages.format(RefactoringCoreMessages.RenameTempRefactoring_lowercase2, new String[] { newName, nameOfParent, nameOfType }));
- } else {
- result.addWarning(RefactoringCoreMessages.RenameTempRefactoring_lowercase);
- }
- return result;
- }
-
- private void createEdits() {
- TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition());
- TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit);
-
- TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length];
- TextEdit unparentedDeclarationEdit= null;
-
- fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu);
- MultiTextEdit rootEdit= new MultiTextEdit();
- fChange.setEdit(rootEdit);
- fChange.setKeepPreviewEdits(true);
-
- for (int i= 0; i < allRenameEdits.length; i++) {
- if (fIsComposite) {
- // Add a copy of the text edit (text edit may only have one
- // parent) to keep problem reporting code clean
- TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet);
-
- // Add a separate copy for problem reporting
- allUnparentedRenameEdits[i]= allRenameEdits[i].copy();
- if (allRenameEdits[i].equals(declarationEdit))
- unparentedDeclarationEdit= allUnparentedRenameEdits[i];
- }
- rootEdit.addChild(allRenameEdits[i]);
- fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i]));
- }
-
- // store information for analysis
- if (fIsComposite) {
- fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits);
- } else
- fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits);
- }
-
- private TextEdit[] getAllRenameEdits(TextEdit declarationEdit) {
- if (! fUpdateReferences)
- return new TextEdit[] { declarationEdit };
-
- TempOccurrenceAnalyzer fTempAnalyzer= new TempOccurrenceAnalyzer(fTempDeclarationNode, true);
- fTempAnalyzer.perform();
- int[] referenceOffsets= fTempAnalyzer.getReferenceAndJavadocOffsets();
-
- TextEdit[] allRenameEdits= new TextEdit[referenceOffsets.length + 1];
- for (int i= 0; i < referenceOffsets.length; i++)
- allRenameEdits[i]= createRenameEdit(referenceOffsets[i]);
- allRenameEdits[referenceOffsets.length]= declarationEdit;
- return allRenameEdits;
- }
-
- private TextEdit createRenameEdit(int offset) {
- return new ReplaceEdit(offset, fCurrentName.length(), fNewName);
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.RenameTypeProcessor_creating_changes, 1);
- Change change= fChange;
- if (change != null) {
- final ISourceRange range= fLocalVariable.getNameRange();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final String header= Messages.format(RefactoringCoreMessages.RenameLocalVariableProcessor_descriptor_description, new String[] { fCurrentName, JavaScriptElementLabels.getElementLabel(fLocalVariable.getParent(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED), fNewName});
- final String description= Messages.format(RefactoringCoreMessages.RenameLocalVariableProcessor_descriptor_description_short, fCurrentName);
- final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
- final RenameLocalVariableDescriptor descriptor= new RenameLocalVariableDescriptor();
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(RefactoringDescriptor.NONE);
- descriptor.setCompilationUnit(fCu);
- descriptor.setNewName(getNewElementName());
- descriptor.setSelection(range);
- descriptor.setUpdateReferences(fUpdateReferences);
- final RefactoringDescriptorChange result= new RefactoringDescriptorChange(descriptor, RefactoringCoreMessages.RenameTempRefactoring_rename, new Change[] { change});
- result.markAsSynthetic();
- change= result;
- }
- return change;
- } finally {
- monitor.done();
- }
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element != null && element.exists()) {
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- fCu= (IJavaScriptUnit) element;
- } else if (element.getElementType() == IJavaScriptElement.LOCAL_VARIABLE) {
- fLocalVariable= (ILocalVariable) element;
- fCu= (IJavaScriptUnit) fLocalVariable.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (fCu == null)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE);
- } else
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE);
- } else
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- if (fCu != null && fLocalVariable == null) {
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- try {
- final IJavaScriptElement[] elements= fCu.codeSelect(offset, length);
- if (elements != null) {
- for (int index= 0; index < elements.length; index++) {
- final IJavaScriptElement element= elements[index];
- if (element instanceof ILocalVariable)
- fLocalVariable= (ILocalVariable) element;
- }
- }
- if (fLocalVariable == null)
- return ScriptableRefactoring.createInputFatalStatus(null, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- }
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- public RenameAnalyzeUtil.LocalAnalyzePackage getLocalAnalyzePackage() {
- return fLocalAnalyzePackage;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java
deleted file mode 100644
index d446745f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java
+++ /dev/null
@@ -1,883 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IFunctionContainer;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.MethodDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public abstract class RenameMethodProcessor extends JavaRenameProcessor implements IReferenceUpdating, IDelegateUpdating {
-
- private static final String ATTRIBUTE_DELEGATE= "delegate"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DEPRECATE= "deprecate"; //$NON-NLS-1$
-
- private SearchResultGroup[] fOccurrences;
- private boolean fUpdateReferences;
- private IFunction fMethod;
- private Set/*<IFunction>*/ fMethodsToRename;
- private TextChangeManager fChangeManager;
- private WorkingCopyOwner fWorkingCopyOwner;
- private boolean fIsComposite;
- private GroupCategorySet fCategorySet;
- private boolean fDelegateUpdating;
- private boolean fDelegateDeprecation;
- protected boolean fInitialized= false;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameMethodProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename method processor.
- * @param method the method, or <code>null</code> if invoked by scripting
- */
- protected RenameMethodProcessor(IFunction method) {
- this(method, new TextChangeManager(true), null);
- fIsComposite= false;
- }
-
- /**
- * Creates a new rename method processor.
- * <p>
- * This constructor is only invoked by <code>RenameTypeProcessor</code>.
- * </p>
- *
- * @param method the method
- * @param manager the change manager
- * @param categorySet the group category set
- */
- protected RenameMethodProcessor(IFunction method, TextChangeManager manager, GroupCategorySet categorySet) {
- initialize(method);
- fChangeManager= manager;
- fCategorySet= categorySet;
- fDelegateUpdating= false;
- fDelegateDeprecation= true;
- fIsComposite= true;
- }
-
- protected void initialize(IFunction method) {
- fMethod= method;
- if (!fInitialized) {
- if (method != null)
- setNewElementName(method.getElementName());
- fUpdateReferences= true;
- initializeWorkingCopyOwner();
- }
- }
-
- protected void initializeWorkingCopyOwner() {
- fWorkingCopyOwner= new WorkingCopyOwner() {/*must subclass*/};
- }
-
- protected void setData(RenameMethodProcessor other) {
- fUpdateReferences= other.fUpdateReferences;
- setNewElementName(other.getNewElementName());
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fMethod);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameMethodRefactoring_name;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fMethod);
- }
-
- public Object[] getElements() {
- return new Object[] {fMethod};
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- RenameArguments args= new RenameArguments(getNewElementName(), getUpdateReferences());
- for (Iterator iter= fMethodsToRename.iterator(); iter.hasNext();) {
- IFunction method= (IFunction) iter.next();
- result.rename(method, args);
- }
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- return ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES;
- }
-
- //---- INameUpdating -------------------------------------
-
- public final String getCurrentElementName(){
- return fMethod.getElementName();
- }
-
- public final RefactoringStatus checkNewElementName(String newName) {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
-
- RefactoringStatus status= Checks.checkName(newName, JavaScriptConventions.validateFunctionName(newName));
- if (status.isOK() && Checks.startsWithUpperCase(newName))
- status= RefactoringStatus.createWarningStatus(fIsComposite
- ? Messages.format(RefactoringCoreMessages.Checks_method_names_lowercase2, new String[] { newName, fMethod.getDeclaringType().getElementName()})
- : RefactoringCoreMessages.Checks_method_names_lowercase);
-
- if (Checks.isAlreadyNamed(fMethod, newName))
- status.addFatalError(fIsComposite
- ? Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_same_name2, new String[] { newName, fMethod.getDeclaringType().getElementName() } )
- : RefactoringCoreMessages.RenameMethodRefactoring_same_name,
- JavaStatusContext.create(fMethod));
- return status;
- }
-
- public Object getNewElement() {
- if (fMethod.getDeclaringType()!=null)
- return fMethod.getDeclaringType().getFunction(getNewElementName(), fMethod.getParameterTypes());
- return fMethod.getJavaScriptUnit().getFunction(getNewElementName(), fMethod.getParameterTypes());
- }
-
- public final IFunction getMethod() {
- return fMethod;
- }
-
- private void initializeMethodsToRename(IProgressMonitor pm) throws CoreException {
- if (fMethodsToRename == null)
- fMethodsToRename= new HashSet(Arrays.asList(MethodChecks.getOverriddenMethods(getMethod(), pm)));
- }
-
- protected void setMethodsToRename(IFunction[] methods) {
- fMethodsToRename= new HashSet(Arrays.asList(methods));
- }
-
- protected Set getMethodsToRename() {
- return fMethodsToRename;
- }
-
- //---- IReferenceUpdating -----------------------------------
-
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- public final void setUpdateReferences(boolean update) {
- fUpdateReferences= update;
- }
-
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
-
- //------------------- IDelegateUpdating ----------------------
-
- public boolean canEnableDelegateUpdating() {
- return true;
- }
-
- public boolean getDelegateUpdating() {
- return fDelegateUpdating;
- }
-
- public void setDelegateUpdating(boolean updating) {
- fDelegateUpdating= updating;
- }
-
- public boolean getDeprecateDelegates() {
- return fDelegateDeprecation;
- }
-
- public void setDeprecateDelegates(boolean deprecate) {
- fDelegateDeprecation= deprecate;
- }
-
- //----------- preconditions ------------------
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- if (! fMethod.exists()){
- String message= Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_deleted,
- fMethod.getJavaScriptUnit().getElementName());
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- RefactoringStatus result= Checks.checkAvailability(fMethod);
- if (result.hasFatalError())
- return result;
- result.merge(Checks.checkIfCuBroken(fMethod));
- return result;
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- try{
- RefactoringStatus result= new RefactoringStatus();
- pm.beginTask("", 9); //$NON-NLS-1$
- // TODO workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=40367
- if (!Checks.isAvailable(fMethod)) {
- result.addFatalError(RefactoringCoreMessages.RenameMethodProcessor_is_binary, JavaStatusContext.create(fMethod));
- return result;
- }
- result.merge(Checks.checkIfCuBroken(fMethod));
- if (result.hasFatalError())
- return result;
- pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
- result.merge(checkNewElementName(getNewElementName()));
- if (result.hasFatalError())
- return result;
-
- boolean mustAnalyzeShadowing;
- IFunction[] newNameMethods= searchForDeclarationsOfClashingMethods(new SubProgressMonitor(pm, 1));
- if (newNameMethods.length == 0) {
- mustAnalyzeShadowing= false;
- pm.worked(1);
- } else {
- IType[] outerTypes= searchForOuterTypesOfReferences(newNameMethods, new SubProgressMonitor(pm, 1));
- if (outerTypes.length > 0) {
- //There exists a reference to a clashing method, where the reference is in a nested type.
- //That nested type could be a type in a ripple method's hierarchy, which could
- //cause the reference to bind to the new ripple method instead of to
- //its old binding (a method of an enclosing scope).
- //-> Getting *more* references than before -> Semantics not preserved.
- //Example: RenamePrivateMethodTests#testFail6()
- //TODO: could pass declaringTypes to the RippleMethodFinder and check whether
- //a hierarchy contains one of outerTypes (or an outer type of an outerType, recursively).
- mustAnalyzeShadowing= true;
-
- } else {
- boolean hasOldRefsInInnerTypes= true;
- //TODO: to implement this optimization:
- //- move search for references to before this check.
- //- collect references in inner types.
- //- for each reference, check for all supertypes and their enclosing types
- //(recursively), whether they declare a rippleMethod
- if (hasOldRefsInInnerTypes) {
- //There exists a reference to a ripple method in a nested type
- //of a type in the hierarchy of any ripple method.
- //When that reference is renamed, and one of the supertypes of the
- //nested type declared a method matching the new name, then
- //the renamed reference will bind to the method in its supertype,
- //since inherited methods bind stronger than methods from enclosing scopes.
- //Getting *less* references than before -> Semantics not preserved.
- //Examples: RenamePrivateMethodTests#testFail2(), RenamePrivateMethodTests#testFail5()
- mustAnalyzeShadowing= true;
- } else {
- mustAnalyzeShadowing= false;
- }
- }
- }
-
- initializeMethodsToRename(new SubProgressMonitor(pm, 1));
- pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_searchingForReferences);
- fOccurrences= getOccurrences(new SubProgressMonitor(pm, 3), result);
- pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
-
- if (fUpdateReferences)
- result.merge(checkRelatedMethods());
-
- result.merge(analyzeCompilationUnits()); //removes CUs with syntax errors
- pm.worked(1);
-
- if (result.hasFatalError())
- return result;
-
- createChanges(new SubProgressMonitor(pm, 1), result);
- if (fUpdateReferences & mustAnalyzeShadowing)
- result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 1)));
- else
- pm.worked(1);
-
- return result;
- } finally{
- pm.done();
- }
- }
-
- private IType[] searchForOuterTypesOfReferences(IFunction[] newNameMethods, IProgressMonitor pm) throws CoreException {
- final Set outerTypesOfReferences= new HashSet();
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(newNameMethods, IJavaScriptSearchConstants.REFERENCES);
- IJavaScriptSearchScope scope= createRefactoringScope(getMethod());
- SearchRequestor requestor= new SearchRequestor() {
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- IMember member= (IMember) match.getElement();
- IType declaring= member.getDeclaringType();
- if (declaring == null)
- return;
- IType outer= declaring.getDeclaringType();
- if (outer != null)
- outerTypesOfReferences.add(declaring);
- }
- };
- new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(),
- scope, requestor, pm);
- return (IType[]) outerTypesOfReferences.toArray(new IType[outerTypesOfReferences.size()]);
- }
-
- private IFunction[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
- final List results= new ArrayList();
- SearchPattern pattern= createNewMethodPattern();
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(getMethod().getJavaScriptProject());
- SearchRequestor requestor= new SearchRequestor() {
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- Object method= match.getElement();
- if (method instanceof IFunction) // check for bug 90138: [refactoring] [rename] Renaming method throws internal exception
- results.add(method);
- else
- JavaScriptPlugin.logErrorMessage("Unexpected element in search match: " + match.toString()); //$NON-NLS-1$
- }
- };
- new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
- return (IFunction[]) results.toArray(new IFunction[results.size()]);
- }
-
- private SearchPattern createNewMethodPattern() throws JavaScriptModelException {
- StringBuffer stringPattern= new StringBuffer(getNewElementName()).append('(');
- int paramCount= getMethod().getNumberOfParameters();
- for (int i= 0; i < paramCount; i++) {
- if (i > 0)
- stringPattern.append(',');
- stringPattern.append('*');
- }
- stringPattern.append(')');
-
- return SearchPattern.createPattern(stringPattern.toString(), IJavaScriptSearchConstants.FUNCTION,
- IJavaScriptSearchConstants.DECLARATIONS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- }
-
- protected final IJavaScriptSearchScope createRefactoringScope() throws CoreException {
- return createRefactoringScope(fMethod);
- }
- //TODO: shouldn't scope take all ripple methods into account?
- protected static final IJavaScriptSearchScope createRefactoringScope(IFunction method) throws CoreException {
- return RefactoringScopeFactory.create(method);
- }
-
- SearchPattern createOccurrenceSearchPattern() {
- HashSet methods= new HashSet(fMethodsToRename);
- methods.add(fMethod);
- IFunction[] ms= (IFunction[]) methods.toArray(new IFunction[methods.size()]);
- return RefactoringSearchEngine.createOrPattern(ms, IJavaScriptSearchConstants.ALL_OCCURRENCES);
- }
-
- SearchResultGroup[] getOccurrences(){
- return fOccurrences;
- }
-
- /*
- * XXX made protected to allow overriding and working around bug 39700
- */
- protected SearchResultGroup[] getOccurrences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- SearchPattern pattern= createOccurrenceSearchPattern();
- return RefactoringSearchEngine.search(pattern, createRefactoringScope(),
- new MethodOccurenceCollector(getMethod().getElementName()), pm, status);
- }
-
- private RefactoringStatus checkRelatedMethods() throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- for (Iterator iter= fMethodsToRename.iterator(); iter.hasNext(); ) {
- IFunction method= (IFunction)iter.next();
-
- if (method.getDeclaringType()!=null)
- result.merge(Checks.checkIfConstructorName(method, getNewElementName(), method.getDeclaringType().getElementName()));
-
- String[] msgData= new String[]{method.getElementName(), method.getJavaScriptUnit().getElementName()};
-// String[] msgData= new String[]{method.getElementName(), JavaModelUtil.getFullyQualifiedName(method.getDeclaringType())};
- if (! method.exists()){
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData));
- continue;
- }
- if (method.isBinary())
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData));
- if (method.isReadOnly())
- result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData));
- }
- return result;
- }
-
- private RefactoringStatus analyzeCompilationUnits() throws CoreException {
- if (fOccurrences.length == 0)
- return null;
-
- RefactoringStatus result= new RefactoringStatus();
- fOccurrences= Checks.excludeCompilationUnits(fOccurrences, result);
- if (result.hasFatalError())
- return result;
-
- result.merge(Checks.checkCompileErrorsInAffectedFiles(fOccurrences));
-
- return result;
- }
-
- //-------
-
- private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
- IJavaScriptUnit[] newDeclarationWCs= null;
- try {
- pm.beginTask("", 4); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
- IJavaScriptUnit[] declarationCUs= getDeclarationCUs();
- newDeclarationWCs= RenameAnalyzeUtil.createNewWorkingCopies(declarationCUs,
- fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));
-
- IFunction[] wcOldMethods= new IFunction[fMethodsToRename.size()];
- IFunction[] wcNewMethods= new IFunction[fMethodsToRename.size()];
- int i= 0;
- for (Iterator iter= fMethodsToRename.iterator(); iter.hasNext(); i++) {
- IFunction method= (IFunction) iter.next();
- IJavaScriptUnit newCu= RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, method.getJavaScriptUnit());
- IFunctionContainer typeWc= (IFunctionContainer) JavaModelUtil.findInCompilationUnit(newCu, method.getParent());
- if (typeWc == null)
- continue;
- wcOldMethods[i]= getMethodInWorkingCopy(method, getCurrentElementName(), typeWc);
- wcNewMethods[i]= getMethodInWorkingCopy(method, getNewElementName(), typeWc);
- }
-
-// SearchResultGroup[] newOccurrences= findNewOccurrences(newMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3));
- SearchResultGroup[] newOccurrences= batchFindNewOccurrences(wcNewMethods, wcOldMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3), result);
-
- result.merge(RenameAnalyzeUtil.analyzeRenameChanges2(fChangeManager, fOccurrences, newOccurrences, getNewElementName()));
- return result;
- } finally{
- pm.done();
- if (newDeclarationWCs != null){
- for (int i= 0; i < newDeclarationWCs.length; i++) {
- newDeclarationWCs[i].discardWorkingCopy();
- }
- }
- }
- }
-
- //Lower memory footprint than batchFindNewOccurrences. Not used because it is too slow.
- //Final solution is maybe to do searches in chunks of ~ 50 CUs.
-// private SearchResultGroup[] findNewOccurrences(IFunction[] newMethods, IJavaScriptUnit[] newDeclarationWCs, IProgressMonitor pm) throws CoreException {
-// pm.beginTask("", fOccurrences.length * 2); //$NON-NLS-1$
-//
-// SearchPattern refsPattern= RefactoringSearchEngine.createOrPattern(newMethods, IJavaScriptSearchConstants.REFERENCES);
-// SearchParticipant[] searchParticipants= SearchUtils.getDefaultSearchParticipants();
-// IJavaScriptSearchScope scope= RefactoringScopeFactory.create(newMethods);
-// MethodOccurenceCollector requestor= new MethodOccurenceCollector(getNewElementName());
-// SearchEngine searchEngine= new SearchEngine(fWorkingCopyOwner);
-//
-// //TODO: should process only references
-// for (int j= 0; j < fOccurrences.length; j++) { //should be getReferences()
-// //cut memory peak by holding only one reference CU at a time in memory
-// IJavaScriptUnit originalCu= fOccurrences[j].getCompilationUnit();
-// IJavaScriptUnit newWc= null;
-// try {
-// IJavaScriptUnit wc= RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, originalCu);
-// if (wc == null) {
-// newWc= RenameAnalyzeUtil.createNewWorkingCopy(originalCu, fChangeManager, fWorkingCopyOwner,
-// new SubProgressMonitor(pm, 1));
-// }
-// searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
-// } finally {
-// if (newWc != null)
-// newWc.discardWorkingCopy();
-// }
-// }
-// SearchResultGroup[] newResults= RefactoringSearchEngine.groupByResource(requestor.getResults());
-// pm.done();
-// return newResults;
-// }
-
- private SearchResultGroup[] batchFindNewOccurrences(IFunction[] wcNewMethods, final IFunction[] wcOldMethods, IJavaScriptUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
-
- SearchPattern refsPattern= RefactoringSearchEngine.createOrPattern(wcNewMethods, IJavaScriptSearchConstants.REFERENCES);
- SearchParticipant[] searchParticipants= SearchUtils.getDefaultSearchParticipants();
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(wcNewMethods);
-
- MethodOccurenceCollector requestor;
- if (getDelegateUpdating()) {
- // There will be two new matches inside the delegate(s) (the invocation
- // and the javadoc) which are OK and must not be reported.
- // Note that except these ocurrences, the delegate bodies are empty
- // (as they were created this way).
- requestor= new MethodOccurenceCollector(getNewElementName()) {
- public void acceptSearchMatch(IJavaScriptUnit unit, SearchMatch match) throws CoreException {
- for (int i= 0; i < wcOldMethods.length; i++)
- if (wcOldMethods[i].equals(match.getElement()))
- return;
- super.acceptSearchMatch(unit, match);
- }
- };
- } else
- requestor= new MethodOccurenceCollector(getNewElementName());
-
- SearchEngine searchEngine= new SearchEngine(fWorkingCopyOwner);
-
- ArrayList needWCs= new ArrayList();
- HashSet declaringCUs= new HashSet(newDeclarationWCs.length);
- for (int i= 0; i < newDeclarationWCs.length; i++)
- declaringCUs.add(newDeclarationWCs[i].getPrimary());
- for (int i= 0; i < fOccurrences.length; i++) {
- IJavaScriptUnit cu= fOccurrences[i].getCompilationUnit();
- if (! declaringCUs.contains(cu))
- needWCs.add(cu);
- }
- IJavaScriptUnit[] otherWCs= null;
- try {
- otherWCs= RenameAnalyzeUtil.createNewWorkingCopies(
- (IJavaScriptUnit[]) needWCs.toArray(new IJavaScriptUnit[needWCs.size()]),
- fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));
- searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
- } finally {
- pm.done();
- if (otherWCs != null) {
- for (int i= 0; i < otherWCs.length; i++) {
- otherWCs[i].discardWorkingCopy();
- }
- }
- }
- SearchResultGroup[] newResults= RefactoringSearchEngine.groupByCu(requestor.getResults(), status);
- return newResults;
- }
-
- private IJavaScriptUnit[] getDeclarationCUs() {
- Set cus= new HashSet();
- for (Iterator iter= fMethodsToRename.iterator(); iter.hasNext();) {
- IFunction method= (IFunction) iter.next();
- cus.add(method.getJavaScriptUnit());
- }
- return (IJavaScriptUnit[]) cus.toArray(new IJavaScriptUnit[cus.size()]);
- }
-
- private IFunction getMethodInWorkingCopy(IFunction method, String elementName, IFunctionContainer typeWc) throws CoreException{
- String[] paramTypeSignatures= method.getParameterTypes();
- return typeWc.getFunction(elementName, paramTypeSignatures);
- }
-
- //-------
- private static IFunction[] classesDeclareMethodName(ITypeHierarchy hier, List classes, IFunction method, String newName) throws CoreException {
- Set result= new HashSet();
- IType type= method.getDeclaringType();
- List subtypes= Arrays.asList(hier.getAllSubtypes(type));
-
- int parameterCount= method.getParameterTypes().length;
- boolean isMethodPrivate= JdtFlags.isPrivate(method);
-
- for (Iterator iter= classes.iterator(); iter.hasNext(); ){
- IType clazz= (IType) iter.next();
- IFunction[] methods= clazz.getFunctions();
- boolean isSubclass= subtypes.contains(clazz);
- for (int j= 0; j < methods.length; j++) {
- IFunction foundMethod= Checks.findMethod(newName, parameterCount, false, new IFunction[] {methods[j]});
- if (foundMethod == null)
- continue;
- if (isSubclass || type.equals(clazz))
- result.add(foundMethod);
- else if ((! isMethodPrivate) && (! JdtFlags.isPrivate(methods[j])))
- result.add(foundMethod);
- }
- }
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- }
-
- final static IFunction[] hierarchyDeclaresMethodName(IProgressMonitor pm, ITypeHierarchy hierarchy, IFunction method, String newName) throws CoreException {
- Set result= new HashSet();
- IType type= method.getDeclaringType();
- IFunction foundMethod= Checks.findMethod(newName, method.getParameterTypes().length, false, type);
- if (foundMethod != null)
- result.add(foundMethod);
-
- IFunction[] foundInHierarchyClasses= classesDeclareMethodName(hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName);
- if (foundInHierarchyClasses != null)
- result.addAll(Arrays.asList(foundInHierarchyClasses));
-
- IFunction[] foundInImplementingClasses= classesDeclareMethodName(hierarchy, Arrays.asList(new IType[0]), method, newName);
- if (foundInImplementingClasses != null)
- result.addAll(Arrays.asList(foundInImplementingClasses));
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- final TextChange[] changes= fChangeManager.getAllChanges();
- final List list= new ArrayList(changes.length);
- list.addAll(Arrays.asList(changes));
- String project= null;
- IJavaScriptProject javaProject= fMethod.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
- try {
- if (!Flags.isPrivate(fMethod.getFlags()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final IType declaring= fMethod.getDeclaringType();
- try {
- if (declaring!=null && (declaring.isAnonymous() || declaring.isLocal()))
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short, fMethod.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameMethodProcessor_descriptor_description, new String[] { JavaScriptElementLabels.getTextLabel(fMethod, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), getNewElementName()});
- final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_METHOD);
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fMethod);
- descriptor.setNewName(getNewElementName());
- descriptor.setUpdateReferences(fUpdateReferences);
- descriptor.setKeepOriginal(fDelegateUpdating);
- descriptor.setDeprecateDelegate(fDelegateDeprecation);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameMethodProcessor_change_name, (Change[]) list.toArray(new Change[list.size()]));
- } finally {
- monitor.done();
- }
- }
-
- private TextChangeManager createChanges(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- if (!fIsComposite)
- fChangeManager.clear();
- addOccurrences(fChangeManager, pm, status);
- return fChangeManager;
- }
-
- void addOccurrences(TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException/*thrown in subtype*/{
- pm.beginTask("", fOccurrences.length); //$NON-NLS-1$
- for (int i= 0; i < fOccurrences.length; i++){
- IJavaScriptUnit cu= fOccurrences[i].getCompilationUnit();
- if (cu == null)
- continue;
-
- SearchMatch[] results= fOccurrences[i].getSearchResults();
-
- // Split matches into declaration and non-declaration matches
-
- List declarationsInThisCu= new ArrayList();
- List referencesInThisCu= new ArrayList();
-
- for (int j= 0; j < results.length; j++) {
- if (results[j] instanceof MethodDeclarationMatch)
- declarationsInThisCu.add(results[j]);
- else
- referencesInThisCu.add(results[j]);
- }
-
- // First, handle the declarations
- if (declarationsInThisCu.size() > 0) {
-
- if (fDelegateUpdating) {
- // Update with delegates
- CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu);
- rewrite.setResolveBindings(true);
-
- for (Iterator iter= declarationsInThisCu.iterator(); iter.hasNext();) {
- SearchMatch element= (SearchMatch) iter.next();
- FunctionDeclaration method= ASTNodeSearchUtil.getMethodDeclarationNode((IFunction) element.getElement(), rewrite.getRoot());
- DelegateCreator creator= new DelegateMethodCreator();
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setDeclaration(method);
- creator.setSourceRewrite(rewrite);
- creator.setNewElementName(getNewElementName());
- creator.prepareDelegate();
- creator.createEdit();
- }
- // Need to handle all delegates first as this
- // creates a completely new change object.
- TextChange changeForThisCu= rewrite.createChange();
- changeForThisCu.setKeepPreviewEdits(true);
- manager.manage(cu, changeForThisCu);
- }
-
- // Update the normal methods
- for (Iterator iter= declarationsInThisCu.iterator(); iter.hasNext();) {
- SearchMatch element= (SearchMatch) iter.next();
- simpleUpdate(element, cu, manager.get(cu));
- }
- }
-
- // Second, handle references
- if (fUpdateReferences) {
- for (Iterator iter= referencesInThisCu.iterator(); iter.hasNext();) {
- SearchMatch element= (SearchMatch) iter.next();
- simpleUpdate(element, cu, manager.get(cu));
- }
- }
-
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- pm.done();
- }
-
- private void simpleUpdate(SearchMatch element, IJavaScriptUnit cu, TextChange textChange) {
- String editName= RefactoringCoreMessages.RenameMethodRefactoring_update_occurrence;
- ReplaceEdit replaceEdit= createReplaceEdit(element, cu);
- addTextEdit(textChange, editName, replaceEdit);
- }
-
- protected final ReplaceEdit createReplaceEdit(SearchMatch searchResult, IJavaScriptUnit cu) {
- if (searchResult.isImplicit()) { // handle Annotation Element references, see bug 94062
- StringBuffer sb= new StringBuffer(getNewElementName());
- if (JavaScriptCore.INSERT.equals(cu.getJavaScriptProject().getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, true)))
- sb.append(' ');
- sb.append('=');
- if (JavaScriptCore.INSERT.equals(cu.getJavaScriptProject().getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, true)))
- sb.append(' ');
- return new ReplaceEdit(searchResult.getOffset(), 0, sb.toString());
- } else {
- return new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), getNewElementName());
- }
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- fInitialized= true;
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- final String refactoring= getRefactoring().getName();
- if (element instanceof IFunction) {
- final IFunction method= (IFunction) element;
- final IType declaring= method.getDeclaringType();
- if (declaring != null && declaring.exists()) {
- final IFunction[] methods= declaring.findMethods(method);
- if (methods != null && methods.length == 1 && methods[0] != null) {
- if (!methods[0].exists())
- return ScriptableRefactoring.createInputFatalStatus(methods[0], refactoring, IJavaScriptRefactorings.RENAME_METHOD);
- fMethod= methods[0];
- initializeWorkingCopyOwner();
- } else
- return ScriptableRefactoring.createInputFatalStatus(null, refactoring, IJavaScriptRefactorings.RENAME_METHOD);
- } else
- {
- final IJavaScriptUnit unit= method.getJavaScriptUnit();
- if (unit != null && unit.exists()) {
- final IFunction[] methods= unit.findFunctions(method);
- if (methods != null && methods.length == 1 && methods[0] != null) {
- if (!methods[0].exists())
- return ScriptableRefactoring.createInputFatalStatus(methods[0], refactoring, IJavaScriptRefactorings.RENAME_METHOD);
- fMethod= methods[0];
- initializeWorkingCopyOwner();
- } else
- return ScriptableRefactoring.createInputFatalStatus(null, refactoring, IJavaScriptRefactorings.RENAME_METHOD);
- } else
- return ScriptableRefactoring.createInputFatalStatus(element, refactoring, IJavaScriptRefactorings.RENAME_METHOD);
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String delegate= extended.getAttribute(ATTRIBUTE_DELEGATE);
- if (delegate != null) {
- fDelegateUpdating= Boolean.valueOf(delegate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELEGATE));
- final String deprecate= extended.getAttribute(ATTRIBUTE_DEPRECATE);
- if (deprecate != null) {
- fDelegateDeprecation= Boolean.valueOf(deprecate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- protected void addTextEdit(TextChange change, String editName, ReplaceEdit replaceEdit) {
- if (fIsComposite)
- TextChangeCompatibility.addTextEdit(change, editName, replaceEdit, fCategorySet);
- else
- TextChangeCompatibility.addTextEdit(change, editName, replaceEdit);
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameModifications.java
deleted file mode 100644
index 847d73b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameModifications.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.IParticipantDescriptorFilter;
-import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.refactoring.RenameTypeArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceModifications;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.RefactoringModifications;
-
-public class RenameModifications extends RefactoringModifications {
-
- private List fRename;
- private List fRenameArguments;
- private List fParticipantDescriptorFilter;
-
- public RenameModifications() {
- fRename= new ArrayList();
- fRenameArguments= new ArrayList();
- fParticipantDescriptorFilter= new ArrayList();
- }
-
- public void rename(IResource resource, RenameArguments args) {
- add(resource, args, null);
- }
-
- public void rename(IJavaScriptProject project, RenameArguments args) {
- add(project, args, null);
- IProject rProject= project.getProject();
- if (rProject != null) {
- getResourceModifications().addRename(rProject, args);
- IProject[] referencingProjects= rProject.getReferencingProjects();
- for (int i= 0; i < referencingProjects.length; i++) {
- IFile classpath= getClasspathFile(referencingProjects[i]);
- if (classpath != null) {
- getResourceModifications().addChanged(classpath);
- }
- }
- }
- }
-
- public void rename(IPackageFragmentRoot sourceFolder, RenameArguments arguments) {
- add(sourceFolder, arguments, null);
- if (sourceFolder.getResource() != null) {
- getResourceModifications().addRename(sourceFolder.getResource(), arguments);
- }
- }
-
- public void rename(IPackageFragment rootPackage, RenameArguments args, boolean renameSubPackages) throws CoreException {
- add(rootPackage, args, null);
- IPackageFragment[] allSubPackages= null;
- if (renameSubPackages) {
- allSubPackages= getSubpackages(rootPackage);
- for (int i= 0; i < allSubPackages.length; i++) {
- IPackageFragment pack= allSubPackages[i];
- RenameArguments subArgs= new RenameArguments(
- getNewPackageName(rootPackage, args.getNewName(), pack.getElementName()),
- args.getUpdateReferences());
- add(pack, subArgs, null);
- }
- }
- IContainer container= (IContainer)rootPackage.getResource();
- if (container == null)
- return;
- IContainer target= (IContainer) ((IPackageFragmentRoot)rootPackage.getParent()).
- getPackageFragment(args.getNewName()).getResource();
- if ((!rootPackage.hasSubpackages() || renameSubPackages) && canMove(container, target)) {
- createIncludingParents(target.getParent());
- if (container.getParent().equals(target.getParent())) {
- getResourceModifications().addRename(container, new RenameArguments(target.getName(), args.getUpdateReferences()));
- } else {
- // This is a little tricky. The problem is that the refactoring participants
- // don't support a generic move like the resource API does. So for the delta
- // we generate one move, however for the participants we have to generate single
- // moves and deletes.
- try {
- getResourceModifications().ignoreForDelta();
- addAllResourceModifications(rootPackage, args, renameSubPackages, allSubPackages);
- } finally {
- getResourceModifications().trackForDelta();
- }
- getResourceModifications().addDelta(new ResourceModifications.MoveDescription(container, target.getFullPath()));
- }
- } else {
- addAllResourceModifications(rootPackage, args, renameSubPackages, allSubPackages);
- }
- }
-
- public void rename(IJavaScriptUnit unit, RenameArguments args) {
- add(unit, args, null);
- if (unit.getResource() != null) {
- getResourceModifications().addRename(unit.getResource(), new RenameArguments(args.getNewName(), args.getUpdateReferences()));
- }
- }
-
- public void rename(IType type, RenameTypeArguments args, IParticipantDescriptorFilter filter) {
- add(type, args, filter);
- }
-
- public void rename(IField field, RenameArguments args) {
- add(field, args, null);
- }
-
- public void rename(IFunction method, RenameArguments args) {
- add(method, args, null);
- }
-
- public void rename(ILocalVariable variable, RenameArguments args) {
- add(variable, args, null);
- }
-
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- for (int i= 0; i < fRename.size(); i++) {
- Object element= fRename.get(i);
- if (element instanceof IResource) {
- ResourceModifications.buildMoveDelta(builder, (IResource) element, (RenameArguments) fRenameArguments.get(i));
- }
- }
- getResourceModifications().buildDelta(builder);
- }
-
- public void buildValidateEdits(ValidateEditChecker checker) {
- for (Iterator iter= fRename.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit)element;
- IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE) {
- checker.addFile((IFile)resource);
- }
- }
- }
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) {
- List result= new ArrayList();
- for (int i= 0; i < fRename.size(); i++) {
- result.addAll(Arrays.asList(ParticipantManager.loadRenameParticipants(status,
- owner, fRename.get(i),
- (RenameArguments) fRenameArguments.get(i),
- (IParticipantDescriptorFilter) fParticipantDescriptorFilter.get(i),
- natures, shared)));
- }
- result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared)));
- return (RefactoringParticipant[]) result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- private void add(Object element, RefactoringArguments args, IParticipantDescriptorFilter filter) {
- Assert.isNotNull(element);
- Assert.isNotNull(args);
- fRename.add(element);
- fRenameArguments.add(args);
- fParticipantDescriptorFilter.add(filter);
- }
-
- private void addAllResourceModifications(IPackageFragment rootPackage, RenameArguments args, boolean renameSubPackages, IPackageFragment[] allSubPackages) throws CoreException {
- addResourceModifications(rootPackage, args, rootPackage, renameSubPackages);
- if (renameSubPackages) {
- for (int i= 0; i < allSubPackages.length; i++) {
- IPackageFragment pack= allSubPackages[i];
- addResourceModifications(rootPackage, args, pack, renameSubPackages);
- }
- }
- }
-
- private void addResourceModifications(IPackageFragment rootPackage, RenameArguments args, IPackageFragment pack, boolean renameSubPackages) throws CoreException {
- IContainer container= (IContainer)pack.getResource();
- if (container == null)
- return;
- IFolder target= computeTargetFolder(rootPackage, args, pack);
- createIncludingParents(target);
- MoveArguments arguments= new MoveArguments(target, args.getUpdateReferences());
- IResource[] resourcesToMove= collectResourcesOfInterest(pack);
- Set allMembers= new HashSet(Arrays.asList(container.members()));
- for (int i= 0; i < resourcesToMove.length; i++) {
- IResource toMove= resourcesToMove[i];
- getResourceModifications().addMove(toMove, arguments);
- allMembers.remove(toMove);
- }
- for (Iterator iter= allMembers.iterator(); iter.hasNext();) {
- IResource element= (IResource) iter.next();
- if (element instanceof IFile) {
- getResourceModifications().addDelete(element);
- iter.remove();
- }
- }
- if (renameSubPackages && rootPackage.equals(pack)
- || ! renameSubPackages && allMembers.isEmpty()) {
- getResourceModifications().addDelete(container);
- }
- }
-
- private boolean canMove(IContainer source, IContainer target) {
- return !target.exists() && !source.getFullPath().isPrefixOf(target.getFullPath());
- }
-
- private IPackageFragment[] getSubpackages(IPackageFragment pack) throws CoreException {
- IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent();
- IJavaScriptElement[] allPackages= root.getChildren();
- if (pack.isDefaultPackage())
- return new IPackageFragment[0];
- ArrayList result= new ArrayList();
- String prefix= pack.getElementName() + '.';
- for (int i= 0; i < allPackages.length; i++) {
- IPackageFragment currentPackage= (IPackageFragment) allPackages[i];
- if (currentPackage.getElementName().startsWith(prefix))
- result.add(currentPackage);
- }
- return (IPackageFragment[]) result.toArray(new IPackageFragment[result.size()]);
- }
-
- private IFolder computeTargetFolder(IPackageFragment rootPackage, RenameArguments args, IPackageFragment pack) {
- IPath path= pack.getParent().getPath();
- path= path.append(getNewPackageName(rootPackage, args.getNewName(), pack.getElementName()).replace('.', IPath.SEPARATOR));
- IFolder target= ResourcesPlugin.getWorkspace().getRoot().getFolder(path);
- return target;
- }
-
- private String getNewPackageName(IPackageFragment rootPackage, String newPackageName, String oldSubPackageName) {
- String oldPackageName= rootPackage.getElementName();
- return newPackageName + oldSubPackageName.substring(oldPackageName.length());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameNonVirtualMethodProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameNonVirtualMethodProcessor.java
deleted file mode 100644
index b722738c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameNonVirtualMethodProcessor.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.MethodDeclarationMatch;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-public class RenameNonVirtualMethodProcessor extends RenameMethodProcessor {
-
- /**
- * Creates a new rename method processor.
- * <p>
- * This constructor is only invoked by <code>RenameTypeProcessor</code>.
- * </p>
- *
- * @param method the method
- * @param manager the change manager
- * @param categorySet the group category set
- */
- RenameNonVirtualMethodProcessor(IFunction method, TextChangeManager manager, GroupCategorySet categorySet) {
- super(method, manager, categorySet);
- }
-
- /**
- * Creates a new rename method processor.
- * @param method the method, or <code>null</code> if invoked by scripting
- */
- public RenameNonVirtualMethodProcessor(IFunction method) {
- super(method);
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameNonVirtualMethodAvailable(getMethod());
- }
-
- //----------- preconditions --------------
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext checkContext) throws CoreException {
- try{
- pm.beginTask("", 3); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
- result.merge(super.doCheckFinalConditions(new SubProgressMonitor(pm, 1), checkContext));
- if (result.hasFatalError())
- return result;
-
- final IFunction method= getMethod();
- final IType declaring= method.getDeclaringType();
- final String name= getNewElementName();
- if (declaring!=null)
- {
- IFunction[] hierarchyMethods= hierarchyDeclaresMethodName(
- new SubProgressMonitor(pm, 1), declaring.newTypeHierarchy(new SubProgressMonitor(pm, 1)), method, name);
-
- for (int i= 0; i < hierarchyMethods.length; i++) {
- IFunction hierarchyMethod= hierarchyMethods[i];
- RefactoringStatusContext context= JavaStatusContext.create(hierarchyMethod);
- if (Checks.compareParamTypes(method.getParameterTypes(), hierarchyMethod.getParameterTypes())) {
- String message= Messages.format(
- RefactoringCoreMessages.RenamePrivateMethodRefactoring_hierarchy_defines,
- new String[]{JavaModelUtil.getFullyQualifiedName(
- declaring), name});
- result.addError(message, context);
- }else {
- String message= Messages.format(
- RefactoringCoreMessages.RenamePrivateMethodRefactoring_hierarchy_defines2,
- new String[]{JavaModelUtil.getFullyQualifiedName(
- declaring), name});
- result.addWarning(message, context);
- }
- }
- }
- return result;
- } finally{
- pm.done();
- }
- }
-
- /*
- * The code below is needed to due bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=39700.
- * Declaration in hierarchy doesn't take visibility into account.
- */
-
- /*
- * XXX working around bug 39700
- */
- protected SearchResultGroup[] getOccurrences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- SearchPattern pattern= createReferenceSearchPattern();
- SearchResultGroup[] groups= RefactoringSearchEngine.search(pattern, createRefactoringScope(),
- new MethodOccurenceCollector(getMethod().getElementName()), new SubProgressMonitor(pm, 1), status);
- //Workaround bug 39700. Manually add declaration match:
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu.equals(getDeclaringCU())) {
- IResource resource= group.getResource();
- int start= getMethod().getNameRange().getOffset();
- int length= getMethod().getNameRange().getLength();
- MethodDeclarationMatch declarationMatch= new MethodDeclarationMatch(getMethod(), SearchMatch.A_ACCURATE, start, length, SearchEngine.getDefaultSearchParticipant(), resource);
- group.add(declarationMatch);
- break;//no need to go further
- }
- }
- return groups;
- }
-
- /*
- * @see RenameMethodProcessor#addOccurrences(org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager, org.eclipse.core.runtime.IProgressMonitor, RefactoringStatus)
- */
- void addOccurrences(TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- // declaration update must be registered first
- addDeclarationUpdate(manager);
- if (getUpdateReferences())
- addReferenceUpdates(manager, pm, status);
- pm.worked(1);
- }
-
- private IJavaScriptUnit getDeclaringCU() {
- return getMethod().getJavaScriptUnit();
- }
-
- /*
- * @see RenameMethodProcessor#createOccurrenceSearchPattern(org.eclipse.core.runtime.IProgressMonitor)
- */
- SearchPattern createOccurrenceSearchPattern(IProgressMonitor pm) {
- pm.beginTask("", 1); //$NON-NLS-1$
- SearchPattern pattern= SearchPattern.createPattern(getMethod(), IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- pm.done();
- return pattern;
- }
-
- private SearchPattern createReferenceSearchPattern() {
- return SearchPattern.createPattern(getMethod(), IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- }
-
- final void addDeclarationUpdate(TextChangeManager manager) throws CoreException {
-
- if (getDelegateUpdating()) {
- // create the delegate
- CompilationUnitRewrite rewrite= new CompilationUnitRewrite(getDeclaringCU());
- rewrite.setResolveBindings(true);
- FunctionDeclaration methodDeclaration= ASTNodeSearchUtil.getMethodDeclarationNode(getMethod(), rewrite.getRoot());
- DelegateMethodCreator creator= new DelegateMethodCreator();
- creator.setDeclaration(methodDeclaration);
- creator.setDeclareDeprecated(getDeprecateDelegates());
- creator.setSourceRewrite(rewrite);
- creator.setCopy(true);
- creator.setNewElementName(getNewElementName());
- creator.prepareDelegate();
- creator.createEdit();
- CompilationUnitChange cuChange= rewrite.createChange();
- if (cuChange != null) {
- cuChange.setKeepPreviewEdits(true);
- manager.manage(getDeclaringCU(), cuChange);
- }
- }
-
- String editName= RefactoringCoreMessages.RenameMethodRefactoring_update_declaration;
- ISourceRange nameRange= getMethod().getNameRange();
- ReplaceEdit replaceEdit= new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName());
- addTextEdit(manager.get(getDeclaringCU()), editName, replaceEdit);
- }
-
- private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- SearchResultGroup[] grouped= getReferences(pm, status);
- for (int i= 0; i < grouped.length; i++) {
- SearchResultGroup group= grouped[i];
- SearchMatch[] results= group.getSearchResults();
- IJavaScriptUnit cu= group.getCompilationUnit();
- TextChange change= manager.get(cu);
- for (int j= 0; j < results.length; j++){
- String editName= RefactoringCoreMessages.RenamePrivateMethodRefactoring_update;
- ReplaceEdit replaceEdit= createReplaceEdit(results[j], cu);
- addTextEdit(change, editName, replaceEdit);
-
- }
- }
- }
-
- private SearchResultGroup[] getReferences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- //TODO: should not do the search again!
- pm.beginTask("", 2); //$NON-NLS-1$
- SearchPattern pattern= createReferenceSearchPattern();
- return RefactoringSearchEngine.search(pattern, createRefactoringScope(),
- new MethodOccurenceCollector(getMethod().getElementName()), new SubProgressMonitor(pm, 1), status);
- }
-
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_renamed_plural;
- else
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_renamed_singular;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamePackageProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamePackageProcessor.java
deleted file mode 100644
index 4f7fbe4b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamePackageProcessor.java
+++ /dev/null
@@ -1,1073 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.Map.Entry;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.IResourceMapper;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptElementMapper;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenamePackageChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor.ImportsManager.ImportChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.Changes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.CommentAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameSearchResult;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-public class RenamePackageProcessor extends JavaRenameProcessor implements
- IReferenceUpdating, ITextUpdating, IQualifiedNameUpdating, IResourceMapper, IJavaScriptElementMapper {
-
- private static final String ATTRIBUTE_QUALIFIED= "qualified"; //$NON-NLS-1$
- private static final String ATTRIBUTE_TEXTUAL_MATCHES= "textual"; //$NON-NLS-1$
- private static final String ATTRIBUTE_PATTERNS= "patterns"; //$NON-NLS-1$
- private static final String ATTRIBUTE_HIERARCHICAL= "hierarchical"; //$NON-NLS-1$
-
- private IPackageFragment fPackage;
-
- private TextChangeManager fChangeManager;
- private ImportsManager fImportsManager;
- private QualifiedNameSearchResult fQualifiedNameSearchResult;
-
- private boolean fUpdateReferences;
- private boolean fUpdateTextualMatches;
- private boolean fUpdateQualifiedNames;
- private String fFilePatterns;
- private boolean fRenameSubpackages;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renamePackageProcessor"; //$NON-NLS-1$
- private RenamePackageChange fRenamePackageChange;
-
- /**
- * Creates a new rename package processor.
- * @param fragment the package fragment, or <code>null</code> if invoked by scripting
- */
- public RenamePackageProcessor(IPackageFragment fragment) {
- fPackage= fragment;
- if (fPackage != null)
- setNewElementName(fPackage.getElementName());
- fUpdateReferences= true;
- fUpdateTextualMatches= false;
- fRenameSubpackages= false;
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fPackage);
- }
-
- public String getProcessorName(){
- return RefactoringCoreMessages.RenamePackageRefactoring_name;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fPackage);
- }
-
- public Object[] getElements() {
- return new Object[] {fPackage};
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- result.rename(fPackage, new RenameArguments(getNewElementName(), getUpdateReferences()), fRenameSubpackages);
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- Set combined= new HashSet();
- combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits())));
- if (fRenameSubpackages) {
- IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(fPackage);
- for (int i= 0; i < allPackages.length; i++) {
- combined.addAll(Arrays.asList(ResourceUtil.getFiles(allPackages[i].getJavaScriptUnits())));
- }
- } else {
- combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getJavaScriptUnits())));
- }
- if (fQualifiedNameSearchResult != null)
- combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles()));
- return (IFile[]) combined.toArray(new IFile[combined.size()]);
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_ALL;
- }
-
- //---- ITextUpdating -------------------------------------------------
-
- public boolean canEnableTextUpdating() {
- return true;
- }
-
- public boolean getUpdateTextualMatches() {
- return fUpdateTextualMatches;
- }
-
- public void setUpdateTextualMatches(boolean update) {
- fUpdateTextualMatches= update;
- }
-
- //---- IReferenceUpdating --------------------------------------
-
- public boolean canEnableUpdateReferences() {
- return true;
- }
-
- public void setUpdateReferences(boolean update) {
- fUpdateReferences= update;
- }
-
- public boolean getUpdateReferences(){
- return fUpdateReferences;
- }
-
- //---- IQualifiedNameUpdating ----------------------------------
-
- public boolean canEnableQualifiedNameUpdating() {
- return !fPackage.isDefaultPackage();
- }
-
- public boolean getUpdateQualifiedNames() {
- return fUpdateQualifiedNames;
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- fUpdateQualifiedNames= update;
- }
-
- public String getFilePatterns() {
- return fFilePatterns;
- }
-
- public void setFilePatterns(String patterns) {
- Assert.isNotNull(patterns);
- fFilePatterns= patterns;
- }
-
- //---- IResourceMapper ----------------------------------
-
- public IResource getRefactoredResource(IResource element) {
- IFolder packageFolder= (IFolder) fPackage.getResource();
- if (packageFolder == null)
- return element;
-
- IContainer newPackageFolder= (IContainer) getNewPackage().getResource();
-
- if (packageFolder.equals(element))
- return newPackageFolder;
-
- IPath packagePath= packageFolder.getProjectRelativePath();
- IPath elementPath= element.getProjectRelativePath();
-
- if (packagePath.isPrefixOf(elementPath)) {
- if (fRenameSubpackages || (element instanceof IFile && packageFolder.equals(element.getParent()))) {
- IPath pathInPackage= elementPath.removeFirstSegments(packagePath.segmentCount());
- if (element instanceof IFile)
- return newPackageFolder.getFile(pathInPackage);
- else
- return newPackageFolder.getFolder(pathInPackage);
- }
- }
- return element;
- }
-
- //---- IJavaScriptElementMapper ----------------------------------
-
- public IJavaScriptElement getRefactoredJavaScriptElement(IJavaScriptElement element) {
- return new GenericRefactoringHandleTransplanter() {
- protected IPackageFragment transplantHandle(IPackageFragmentRoot parent, IPackageFragment element) {
- if (! fRenameSubpackages) {
- if (fPackage.equals(element))
- return getNewPackage();
- } else {
- String packName= element.getElementName();
- String packageName= fPackage.getElementName();
- if (fPackage.getParent().equals(parent)
- && packName.startsWith(packageName + '.')) {
- String newPackName= getNewElementName() + packName.substring(packageName.length() - 1);
- return getPackageFragmentRoot().getPackageFragment(newPackName);
- }
- }
- return super.transplantHandle(parent, element);
- }
-
- protected IFunction transplantHandle(IType parent, IFunction element) {
- String[] parameterTypes= resolveParameterTypes(element);
- return parent.getFunction(element.getElementName(), parameterTypes);
- }
-
- private String[] resolveParameterTypes(IFunction method) {
- final String[] oldParameterTypes= method.getParameterTypes();
- final String[] newparams= new String[oldParameterTypes.length];
-
- final String[] possibleOldSigs= new String[2];
- //using type signature, since there is no package signature
- possibleOldSigs[0]= Signature.createTypeSignature(fPackage.getElementName(), false);
- possibleOldSigs[1]= Signature.createTypeSignature(fPackage.getElementName(), true);
-
- final String[] possibleNewSigs= new String[2];
- possibleNewSigs[0]= Signature.createTypeSignature(getNewElementName(), false);
- possibleNewSigs[1]= Signature.createTypeSignature(getNewElementName(), true);
-
- // Textually replace all occurrences
- // This handles stuff like Map<SomeClass, some.package.SomeClass>
- for (int i= 0; i < oldParameterTypes.length; i++) {
- newparams[i]= oldParameterTypes[i];
- for (int j= 0; j < possibleOldSigs.length; j++) {
- newparams[i]= replaceAll(newparams[i], possibleOldSigs[j], possibleNewSigs[j]);
- }
- }
- return newparams;
- }
-
- private String replaceAll(final String source, final String replaceFrom, final String replaceTo) {
- final StringBuffer buf= new StringBuffer(source.length());
- int currentIndex= 0;
- int matchIndex;
- while ((matchIndex= source.indexOf(replaceFrom, currentIndex)) != -1) {
- buf.append(source.substring(currentIndex, matchIndex));
- buf.append(replaceTo);
- currentIndex= matchIndex + replaceFrom.length();
- }
- buf.append(source.substring(currentIndex));
- return buf.toString();
- }
- }.transplantHandle(element);
- }
-
- //----
-
- public boolean canEnableRenameSubpackages() throws JavaScriptModelException {
- return fPackage.hasSubpackages();
- }
-
- public boolean getRenameSubpackages() {
- return fRenameSubpackages;
- }
-
- public void setRenameSubpackages(boolean rename) {
- fRenameSubpackages= rename;
- }
-
- //---- IRenameProcessor ----------------------------------------------
-
- public final String getCurrentElementName(){
- return fPackage.getElementName();
- }
-
- public String getCurrentElementQualifier() {
- return ""; //$NON-NLS-1$
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws CoreException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- RefactoringStatus result= Checks.checkPackageName(newName);
- if (Checks.isAlreadyNamed(fPackage, newName))
- result.addFatalError(RefactoringCoreMessages.RenamePackageRefactoring_another_name);
- result.merge(checkPackageInCurrentRoot(newName));
- return result;
- }
-
- public Object getNewElement(){
- return getNewPackage();
- }
-
- private IPackageFragment getNewPackage() {
- IPackageFragmentRoot root= getPackageFragmentRoot();
- return root.getPackageFragment(getNewElementName());
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- try{
- pm.beginTask("", 23 + (fUpdateQualifiedNames ? 10 : 0) + (fUpdateTextualMatches ? 10 : 0)); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.RenamePackageRefactoring_checking);
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkNewElementName(getNewElementName()));
-// pm.worked(1);
-// result.merge(checkForMainAndNativeMethods());
- pm.worked(2);
-
- if (fPackage.isReadOnly()){
- String message= Messages.format(RefactoringCoreMessages.RenamePackageRefactoring_Packagered_only, fPackage.getElementName());
- result.addFatalError(message);
- } else if (Resources.isReadOnly(fPackage.getResource())) {
- String message= Messages.format(RefactoringCoreMessages.RenamePackageRefactoring_resource_read_only, fPackage.getElementName());
- result.addError(message);
- }
-
- result.merge(checkPackageName(getNewElementName()));
- if (result.hasFatalError())
- return result;
-
- fChangeManager= new TextChangeManager();
- fImportsManager= new ImportsManager();
-
- SubProgressMonitor subPm= new SubProgressMonitor(pm, 16);
- if (fRenameSubpackages) {
- IPackageFragment[] allSubpackages= JavaElementUtil.getPackageAndSubpackages(fPackage);
- subPm.beginTask("", allSubpackages.length); //$NON-NLS-1$
- for (int i= 0; i < allSubpackages.length; i++) {
- new PackageRenamer(allSubpackages[i], this, fChangeManager, fImportsManager).doRename(new SubProgressMonitor(subPm, 1), result);
- }
- subPm.done();
- } else {
- new PackageRenamer(fPackage, this, fChangeManager, fImportsManager).doRename(subPm, result);
- }
-
- fImportsManager.rewriteImports(fChangeManager, new SubProgressMonitor(pm, 3));
-
- if (fUpdateTextualMatches) {
- pm.subTask(RefactoringCoreMessages.RenamePackageRefactoring_searching_text);
- TextMatchUpdater.perform(new SubProgressMonitor(pm, 10), RefactoringScopeFactory.create(fPackage), this, fChangeManager, new SearchResultGroup[0]);
- }
-
- if (fUpdateQualifiedNames)
- computeQualifiedNameMatches(new SubProgressMonitor(pm, 10));
-
- return result;
- } finally{
- pm.done();
- }
- }
-
- public IPackageFragment getPackage() {
- return fPackage;
- }
-
-// private RefactoringStatus checkForMainAndNativeMethods() throws CoreException{
-// RefactoringStatus result= new RefactoringStatus();
-// if (fRenameSubpackages) {
-// IPackageFragment[] allSubpackages= JavaElementUtil.getPackageAndSubpackages(fPackage);
-// for (int i= 0; i < allSubpackages.length; i++) {
-// IJavaScriptUnit[] cus= allSubpackages[i].getCompilationUnits();
-// for (int c= 0; c < cus.length; c++)
-// result.merge(Checks.checkForMainAndNativeMethods(cus[c]));
-// }
-// } else {
-// IJavaScriptUnit[] cus= fPackage.getCompilationUnits();
-// for (int i= 0; i < cus.length; i++)
-// result.merge(Checks.checkForMainAndNativeMethods(cus[i]));
-// }
-// return result;
-// }
-//
- /*
- * returns true if the new name is ok if the specified root.
- * if a package fragment with this name exists and has java resources,
- * then the name is not ok.
- */
- public static boolean isPackageNameOkInRoot(String newName, IPackageFragmentRoot root) throws CoreException {
- IPackageFragment pack= root.getPackageFragment(newName);
- if (! pack.exists())
- return true;
- else if (! pack.hasSubpackages()) //leaves are no good
- return false;
- else if (pack.containsJavaResources())
- return false;
- else if (pack.getNonJavaScriptResources().length != 0)
- return false;
- else
- return true;
- }
-
- private RefactoringStatus checkPackageInCurrentRoot(String newName) throws CoreException {
- if (isPackageNameOkInRoot(newName, getPackageFragmentRoot()))
- return null;
- else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenamePackageRefactoring_package_exists);
- }
-
- private IPackageFragmentRoot getPackageFragmentRoot() {
- return ((IPackageFragmentRoot)fPackage.getParent());
- }
-
- private RefactoringStatus checkPackageName(String newName) throws CoreException {
- RefactoringStatus status= new RefactoringStatus();
- IPackageFragmentRoot[] roots= fPackage.getJavaScriptProject().getPackageFragmentRoots();
- Set topLevelTypeNames= getTopLevelTypeNames();
- for (int i= 0; i < roots.length; i++) {
- if (! isPackageNameOkInRoot(newName, roots[i])){
- String message= Messages.format(RefactoringCoreMessages.RenamePackageRefactoring_aleady_exists, new Object[]{getNewElementName(), roots[i].getElementName()});
- status.merge(RefactoringStatus.createWarningStatus(message));
- status.merge(checkTypeNameConflicts(roots[i], newName, topLevelTypeNames));
- }
- }
- return status;
- }
-
- private Set getTopLevelTypeNames() throws CoreException {
- IJavaScriptUnit[] cus= fPackage.getJavaScriptUnits();
- Set result= new HashSet(2 * cus.length);
- for (int i= 0; i < cus.length; i++) {
- result.addAll(getTopLevelTypeNames(cus[i]));
- }
- return result;
- }
-
- private static Collection getTopLevelTypeNames(IJavaScriptUnit iCompilationUnit) throws CoreException {
- IType[] types= iCompilationUnit.getTypes();
- List result= new ArrayList(types.length);
- for (int i= 0; i < types.length; i++) {
- result.add(types[i].getElementName());
- }
- return result;
- }
-
- private RefactoringStatus checkTypeNameConflicts(IPackageFragmentRoot root, String newName, Set topLevelTypeNames) throws CoreException {
- IPackageFragment otherPack= root.getPackageFragment(newName);
- if (fPackage.equals(otherPack))
- return null;
- IJavaScriptUnit[] cus= otherPack.getJavaScriptUnits();
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < cus.length; i++) {
- result.merge(checkTypeNameConflicts(cus[i], topLevelTypeNames));
- }
- return result;
- }
-
- private RefactoringStatus checkTypeNameConflicts(IJavaScriptUnit iCompilationUnit, Set topLevelTypeNames) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- IType[] types= iCompilationUnit.getTypes();
- String packageName= iCompilationUnit.getParent().getElementName();
- for (int i= 0; i < types.length; i++) {
- String name= types[i].getElementName();
- if (topLevelTypeNames.contains(name)){
- String[] keys= {packageName, name};
- String msg= Messages.format(RefactoringCoreMessages.RenamePackageRefactoring_contains_type, keys);
- RefactoringStatusContext context= JavaStatusContext.create(types[i]);
- result.addError(msg, context);
- }
- }
- return result;
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.RenamePackageRefactoring_creating_change, 1);
- final RenameJavaScriptElementDescriptor descriptor= createRefactoringDescriptor();
- final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenamePackageRefactoring_change_name);
- result.addAll(fChangeManager.getAllChanges());
- fRenamePackageChange= new RenamePackageChange( fPackage, getNewElementName(), fRenameSubpackages);
- result.add(fRenamePackageChange);
- monitor.worked(1);
- return result;
- } finally {
- fChangeManager= null;
- fImportsManager= null;
- monitor.done();
- }
- }
-
- private RenameJavaScriptElementDescriptor createRefactoringDescriptor() {
- String project= null;
- IJavaScriptProject javaProject= fPackage.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final String description= Messages.format(RefactoringCoreMessages.RenamePackageProcessor_descriptor_description_short, fPackage.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenamePackageProcessor_descriptor_description, new String[] { fPackage.getElementName(), getNewElementName()});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- if (fRenameSubpackages)
- comment.addSetting(RefactoringCoreMessages.RenamePackageProcessor_rename_subpackages);
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_PACKAGE);
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment.asString());
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fPackage);
- descriptor.setNewName(getNewElementName());
- descriptor.setUpdateReferences(fUpdateReferences);
- descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
- descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
- if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
- descriptor.setFileNamePatterns(fFilePatterns);
- descriptor.setUpdateHierarchy(fRenameSubpackages);
- return descriptor;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- if (fQualifiedNameSearchResult != null) {
- CompositeChange parent= (CompositeChange) fRenamePackageChange.getParent();
- try {
- /*
- * Sneak text changes in before the package rename to ensure
- * modified files are still at original location (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=154238)
- */
- parent.remove(fRenamePackageChange);
- parent.add(fQualifiedNameSearchResult.getSingleChange(Changes.getModifiedFiles(participantChanges)));
- } finally {
- fQualifiedNameSearchResult= null;
- parent.add(fRenamePackageChange);
- fRenamePackageChange= null;
- }
- }
- return null;
- }
-
- private void computeQualifiedNameMatches(IProgressMonitor pm) throws CoreException {
- if (fQualifiedNameSearchResult == null)
- fQualifiedNameSearchResult= new QualifiedNameSearchResult();
- QualifiedNameFinder.process(fQualifiedNameSearchResult, fPackage.getElementName(), getNewElementName(),
- fFilePatterns, fPackage.getJavaScriptProject().getProject(), pm);
- }
-
- public String getNewPackageName(String oldSubPackageName) {
- String oldPackageName= getPackage().getElementName();
- return getNewElementName() + oldSubPackageName.substring(oldPackageName.length());
- }
-
- private static class PackageRenamer {
- private final IPackageFragment fPackage;
- private final RenamePackageProcessor fProcessor;
- private final TextChangeManager fTextChangeManager;
- private final ImportsManager fImportsManager;
-
- /** references to fPackage (can include star imports which also import namesake package fragments) */
- private SearchResultGroup[] fOccurrences;
-
- /** References in CUs from fOccurrences and fPackage to types in namesake packages.
- * <p>These need an import with the old package name.
- * <p>- from fOccurrences (without namesakes): may have shared star import
- * (star-import not updated here, but for fOccurrences)
- * <p>- from fPackage: may have unimported references to types of namesake packages
- * <p>- both: may have unused imports of namesake packages.
- * <p>Mutable List of SearchResultGroup. */
- private List fReferencesToTypesInNamesakes;
-
- /** References in CUs from namesake packages to types in fPackage.
- * <p>These need an import with the new package name.
- * <p>Mutable List of SearchResultGroup. */
- private List fReferencesToTypesInPackage;
-
- public PackageRenamer(IPackageFragment pack, RenamePackageProcessor processor, TextChangeManager textChangeManager, ImportsManager importsManager) {
- fPackage= pack;
- fProcessor= processor;
- fTextChangeManager= textChangeManager;
- fImportsManager= importsManager;
- }
-
- void doRename(IProgressMonitor pm, RefactoringStatus result) throws CoreException {
- pm.beginTask("", 16); //$NON-NLS-1$
- if (fProcessor.getUpdateReferences()){
- pm.setTaskName(RefactoringCoreMessages.RenamePackageRefactoring_searching);
- fOccurrences= getReferences(new SubProgressMonitor(pm, 4), result);
- fReferencesToTypesInNamesakes= getReferencesToTypesInNamesakes(new SubProgressMonitor(pm, 4), result);
- fReferencesToTypesInPackage= getReferencesToTypesInPackage(new SubProgressMonitor(pm, 4), result);
- pm.setTaskName(RefactoringCoreMessages.RenamePackageRefactoring_checking);
- result.merge(analyzeAffectedCompilationUnits());
- pm.worked(1);
- } else {
- fOccurrences= new SearchResultGroup[0];
- pm.worked(13);
- }
-
- if (result.hasFatalError())
- return;
-
- if (fProcessor.getUpdateReferences())
- addReferenceUpdates(new SubProgressMonitor(pm, 3));
- else
- pm.worked(3);
-
- pm.done();
- }
-
- private SearchResultGroup[] getReferences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(fPackage);
- SearchPattern pattern= SearchPattern.createPattern(fPackage, IJavaScriptSearchConstants.REFERENCES);
- return RefactoringSearchEngine.search(pattern, scope, pm, status);
- }
-
- private void addReferenceUpdates(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", fOccurrences.length + fReferencesToTypesInPackage.size() + fReferencesToTypesInNamesakes.size()); //$NON-NLS-1$
- for (int i= 0; i < fOccurrences.length; i++){
- IJavaScriptUnit cu= fOccurrences[i].getCompilationUnit();
- if (cu == null)
- continue;
- SearchMatch[] results= fOccurrences[i].getSearchResults();
- for (int j= 0; j < results.length; j++){
- SearchMatch result= results[j];
- IJavaScriptElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
- if (enclosingElement instanceof IImportDeclaration) {
- IImportDeclaration importDeclaration= (IImportDeclaration) enclosingElement;
- String updatedImport= getUpdatedImport(importDeclaration);
- updateImport(cu, importDeclaration, updatedImport);
- } else { // is reference
- TextChangeCompatibility.addTextEdit(fTextChangeManager.get(cu), RefactoringCoreMessages.RenamePackageRefactoring_update_reference, createTextChange(result));
- }
- }
- if (fReferencesToTypesInNamesakes.size() != 0) {
- SearchResultGroup typeRefsRequiringOldNameImport= extractGroupFor(cu, fReferencesToTypesInNamesakes);
- if (typeRefsRequiringOldNameImport != null)
- addTypeImports(typeRefsRequiringOldNameImport);
- }
- if (fReferencesToTypesInPackage.size() != 0) {
- SearchResultGroup typeRefsRequiringNewNameImport= extractGroupFor(cu, fReferencesToTypesInPackage);
- if (typeRefsRequiringNewNameImport != null)
- updateTypeImports(typeRefsRequiringNewNameImport);
- }
- pm.worked(1);
- }
-
- if (fReferencesToTypesInNamesakes.size() != 0) {
- for (Iterator iter= fReferencesToTypesInNamesakes.iterator(); iter.hasNext();) {
- SearchResultGroup referencesToTypesInNamesakes= (SearchResultGroup) iter.next();
- addTypeImports(referencesToTypesInNamesakes);
- pm.worked(1);
- }
- }
- if (fReferencesToTypesInPackage.size() != 0) {
- for (Iterator iter= fReferencesToTypesInPackage.iterator(); iter.hasNext();) {
- SearchResultGroup namesakeReferencesToPackage= (SearchResultGroup) iter.next();
- updateTypeImports(namesakeReferencesToPackage);
- pm.worked(1);
- }
- }
- pm.done();
- }
-
- /** Removes the found SearchResultGroup from the list iff found.
- * @param searchResultGroups List of SearchResultGroup
- * @return the SearchResultGroup for cu, or null iff not found */
- private static SearchResultGroup extractGroupFor(IJavaScriptUnit cu, List searchResultGroups) {
- for (Iterator iter= searchResultGroups.iterator(); iter.hasNext();) {
- SearchResultGroup group= (SearchResultGroup) iter.next();
- if (cu.equals(group.getCompilationUnit())) {
- iter.remove();
- return group;
- }
- }
- return null;
- }
-
- private TextEdit createTextChange(SearchMatch searchResult) {
- return new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), getNewPackageName());
- }
-
- private RefactoringStatus analyzeAffectedCompilationUnits() throws CoreException {
- //TODO: also for both fReferencesTo...; only check each CU once!
- RefactoringStatus result= new RefactoringStatus();
- fOccurrences= Checks.excludeCompilationUnits(fOccurrences, result);
- if (result.hasFatalError())
- return result;
-
- result.merge(Checks.checkCompileErrorsInAffectedFiles(fOccurrences));
- return result;
- }
-
- /**
- * @return search scope with
- * <p>- fPackage and
- * <p>- all CUs from fOccurrences which are not in a namesake package
- */
- private IJavaScriptSearchScope getPackageAndOccurrencesWithoutNamesakesScope() {
- List scopeList= new ArrayList();
- scopeList.add(fPackage);
- for (int i= 0; i < fOccurrences.length; i++) {
- IJavaScriptUnit cu= fOccurrences[i].getCompilationUnit();
- if (cu == null)
- continue;
- IPackageFragment pack= (IPackageFragment) cu.getParent();
- if (! pack.getElementName().equals(fPackage.getElementName()))
- scopeList.add(cu);
- }
- return SearchEngine.createJavaSearchScope((IJavaScriptElement[]) scopeList.toArray(new IJavaScriptElement[scopeList.size()]));
- }
-
- private List getReferencesToTypesInNamesakes(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- // e.g. renaming B-p.p; project C requires B, X and has ref to B-p.p and X-p.p;
- // goal: find refs to X-p.p in CUs from fOccurrences
-
- // (1) find namesake packages (scope: all packages referenced by CUs in fOccurrences and fPackage)
- IJavaScriptElement[] elements= new IJavaScriptElement[fOccurrences.length + 1];
- for (int i= 0; i < fOccurrences.length; i++) {
- elements[i]= fOccurrences[i].getCompilationUnit();
- }
- elements[fOccurrences.length]= fPackage;
- IJavaScriptSearchScope namesakePackagesScope= RefactoringScopeFactory.createReferencedScope(elements);
- IPackageFragment[] namesakePackages= getNamesakePackages(namesakePackagesScope, new SubProgressMonitor(pm, 1));
- if (namesakePackages.length == 0) {
- pm.done();
- return new ArrayList(0);
- }
-
- // (2) find refs in fOccurrences and fPackage to namesake packages
- // (from fOccurrences (without namesakes): may have shared star import)
- // (from fPackage: may have unimported references to types of namesake packages)
- IType[] typesToSearch= getTypesInPackages(namesakePackages);
- if (typesToSearch.length == 0) {
- pm.done();
- return new ArrayList(0);
- }
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaScriptSearchConstants.REFERENCES);
- IJavaScriptSearchScope scope= getPackageAndOccurrencesWithoutNamesakesScope();
- SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, new SubProgressMonitor(pm, 1), status);
- pm.done();
- return new ArrayList(Arrays.asList(results));
- }
-
- private List getReferencesToTypesInPackage(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", 2); //$NON-NLS-1$
- IJavaScriptSearchScope referencedFromNamesakesScope= RefactoringScopeFactory.create(fPackage);
- IPackageFragment[] namesakePackages= getNamesakePackages(referencedFromNamesakesScope, new SubProgressMonitor(pm, 1));
- if (namesakePackages.length == 0) {
- pm.done();
- return new ArrayList(0);
- }
-
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(namesakePackages);
- IType[] typesToSearch= getTypesInPackage(fPackage);
- if (typesToSearch.length == 0) {
- pm.done();
- return new ArrayList(0);
- }
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaScriptSearchConstants.REFERENCES);
- SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, new SubProgressMonitor(pm, 1), status);
- pm.done();
- return new ArrayList(Arrays.asList(results));
- }
-
- private IType[] getTypesInPackage(IPackageFragment packageFragment) throws JavaScriptModelException {
- List types= new ArrayList();
- addContainedTypes(packageFragment, types);
- return (IType[]) types.toArray(new IType[types.size()]);
- }
-
- /**
- * @return all package fragments in <code>scope</code> with same name as <code>fPackage</code>, excluding fPackage
- */
- private IPackageFragment[] getNamesakePackages(IJavaScriptSearchScope scope, IProgressMonitor pm) throws CoreException {
- SearchPattern pattern= SearchPattern.createPattern(fPackage.getElementName(), IJavaScriptSearchConstants.PACKAGE, IJavaScriptSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
-
- final HashSet packageFragments= new HashSet();
- SearchRequestor requestor= new SearchRequestor() {
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- IJavaScriptElement enclosingElement= SearchUtils.getEnclosingJavaElement(match);
- if (enclosingElement instanceof IPackageFragment) {
- IPackageFragment pack= (IPackageFragment) enclosingElement;
- if (! fPackage.equals(pack))
- packageFragments.add(pack);
- }
- }
- };
- new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
-
- return (IPackageFragment[]) packageFragments.toArray(new IPackageFragment[packageFragments.size()]);
- }
-
- private IType[] getTypesInPackages(IPackageFragment[] packageFragments) throws JavaScriptModelException {
- List types= new ArrayList();
- for (int i= 0; i < packageFragments.length; i++) {
- IPackageFragment pack= packageFragments[i];
- addContainedTypes(pack, types);
- }
- return (IType[]) types.toArray(new IType[types.size()]);
- }
-
- private void addContainedTypes(IPackageFragment pack, List typesCollector) throws JavaScriptModelException {
- IJavaScriptElement[] children= pack.getChildren();
- for (int c= 0; c < children.length; c++) {
- IJavaScriptElement child= children[c];
- if (child instanceof IJavaScriptUnit) {
- typesCollector.addAll(Arrays.asList(((IJavaScriptUnit) child).getTypes()));
- } else if (child instanceof IClassFile) {
- typesCollector.add(((IClassFile) child).getType());
- }
- }
- }
-
- private void updateImport(IJavaScriptUnit cu, IImportDeclaration importDeclaration, String updatedImport) throws JavaScriptModelException {
- ImportChange importChange= fImportsManager.getImportChange(cu);
- if (Flags.isStatic(importDeclaration.getFlags())) {
- importChange.removeStaticImport(importDeclaration.getElementName());
- importChange.addStaticImport(Signature.getQualifier(updatedImport), Signature.getSimpleName(updatedImport));
- } else {
- importChange.removeImport(importDeclaration.getElementName());
- importChange.addImport(updatedImport);
- }
- }
-
- /**
- * Add new imports to types in <code>typeReferences</code> with package <code>fPackage</code>.
- */
- private void addTypeImports(SearchResultGroup typeReferences) throws CoreException {
- SearchMatch[] searchResults= typeReferences.getSearchResults();
- for (int i= 0; i < searchResults.length; i++) {
- SearchMatch result= searchResults[i];
- IJavaScriptElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
- if (! (enclosingElement instanceof IImportDeclaration)) {
- String reference= getNormalizedTypeReference(result);
- if (! reference.startsWith(fPackage.getElementName())) {
- // is unqualified
- reference= cutOffInnerTypes(reference);
- ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
- importChange.addImport(fPackage.getElementName() + '.' + reference);
- }
- }
- }
- }
-
- /**
- * Add new imports to types in <code>typeReferences</code> with package <code>fNewElementName</code>
- * and remove old import with <code>fPackage</code>.
- */
- private void updateTypeImports(SearchResultGroup typeReferences) throws CoreException {
- SearchMatch[] searchResults= typeReferences.getSearchResults();
- for (int i= 0; i < searchResults.length; i++) {
- SearchMatch result= searchResults[i];
- IJavaScriptElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
- if (enclosingElement instanceof IImportDeclaration) {
- IImportDeclaration importDeclaration= (IImportDeclaration) enclosingElement;
- updateImport(typeReferences.getCompilationUnit(), importDeclaration, getUpdatedImport(importDeclaration));
- } else {
- String reference= getNormalizedTypeReference(result);
- if (! reference.startsWith(fPackage.getElementName())) {
- reference= cutOffInnerTypes(reference);
- ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
- importChange.removeImport(fPackage.getElementName() + '.' + reference);
- importChange.addImport(getNewPackageName() + '.' + reference);
- } // else: already found & updated with package reference search
- }
- }
- }
-
- private static String getNormalizedTypeReference(SearchMatch searchResult) throws JavaScriptModelException {
- IJavaScriptUnit cu= SearchUtils.getCompilationUnit(searchResult);
- String reference= cu.getBuffer().getText(searchResult.getOffset(), searchResult.getLength());
- //reference may be package-qualified -> normalize (remove comments, etc.):
- return CommentAnalyzer.normalizeReference(reference);
- }
-
- private static String cutOffInnerTypes(String reference) {
- int dotPos= reference.indexOf('.'); // cut off inner types
- if (dotPos != -1)
- reference= reference.substring(0, dotPos);
- return reference;
- }
-
- private String getUpdatedImport(IImportDeclaration importDeclaration) {
- String fullyQualifiedImportType= importDeclaration.getElementName();
- int offsetOfDotBeforeTypeName= fPackage.getElementName().length();
- String result= getNewPackageName() + fullyQualifiedImportType.substring(offsetOfDotBeforeTypeName);
- return result;
- }
-
- private String getNewPackageName() {
- return fProcessor.getNewPackageName(fPackage.getElementName());
- }
- }
-
- /**
- * Collector for import additions/removals.
- * Saves all changes for a one-pass rewrite.
- */
- static class ImportsManager {
- public static class ImportChange {
- private ArrayList/*<String>*/ fStaticToRemove= new ArrayList();
- private ArrayList/*<String[2]>*/ fStaticToAdd= new ArrayList();
- private ArrayList/*<String>*/ fToRemove= new ArrayList();
- private ArrayList/*<String>*/ fToAdd= new ArrayList();
-
- public void removeStaticImport(String elementName) {
- fStaticToRemove.add(elementName);
- }
-
- public void addStaticImport(String declaringType, String memberName) {
- fStaticToAdd.add(new String[] {declaringType, memberName});
- }
-
- public void removeImport(String elementName) {
- fToRemove.add(elementName);
- }
-
- public void addImport(String elementName) {
- fToAdd.add(elementName);
- }
- }
-
- private HashMap/*<IJavaScriptUnit, ImportChange>*/ fImportChanges= new HashMap();
-
- public ImportChange getImportChange(IJavaScriptUnit cu) {
- ImportChange importChange= (ImportChange) fImportChanges.get(cu);
- if (importChange == null) {
- importChange= new ImportChange();
- fImportChanges.put(cu, importChange);
- }
- return importChange;
- }
-
- public void rewriteImports(TextChangeManager changeManager, IProgressMonitor pm) throws CoreException {
- for (Iterator iter= fImportChanges.entrySet().iterator(); iter.hasNext();) {
- Entry entry= (Entry) iter.next();
- IJavaScriptUnit cu= (IJavaScriptUnit) entry.getKey();
- ImportChange importChange= (ImportChange) entry.getValue();
-
- ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true);
- importRewrite.setFilterImplicitImports(false);
- for (Iterator iterator= importChange.fStaticToRemove.iterator(); iterator.hasNext();) {
- importRewrite.removeStaticImport((String) iterator.next());
- }
- for (Iterator iterator= importChange.fToRemove.iterator(); iterator.hasNext();) {
- importRewrite.removeImport((String) iterator.next());
- }
- for (Iterator iterator= importChange.fStaticToAdd.iterator(); iterator.hasNext();) {
- String[] toAdd= (String[]) iterator.next();
- importRewrite.addStaticImport(toAdd[0], toAdd[1], true);
- }
- for (Iterator iterator= importChange.fToAdd.iterator(); iterator.hasNext();) {
- importRewrite.addImport((String) iterator.next());
- }
-
- if (importRewrite.hasRecordedChanges()) {
- TextEdit importEdit= importRewrite.rewriteImports(pm);
- String name= RefactoringCoreMessages.RenamePackageRefactoring_update_imports;
- try {
- TextChangeCompatibility.addTextEdit(changeManager.get(cu), name, importEdit);
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.logErrorMessage("MalformedTreeException while processing cu " + cu); //$NON-NLS-1$
- throw e;
- }
- }
- }
- }
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_PACKAGE);
- else
- fPackage= (IPackageFragment) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String patterns= extended.getAttribute(ATTRIBUTE_PATTERNS);
- if (patterns != null && !"".equals(patterns)) //$NON-NLS-1$
- fFilePatterns= patterns;
- else
- fFilePatterns= ""; //$NON-NLS-1$
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String matches= extended.getAttribute(ATTRIBUTE_TEXTUAL_MATCHES);
- if (matches != null) {
- fUpdateTextualMatches= Boolean.valueOf(matches).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TEXTUAL_MATCHES));
- final String qualified= extended.getAttribute(ATTRIBUTE_QUALIFIED);
- if (qualified != null) {
- fUpdateQualifiedNames= Boolean.valueOf(qualified).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_QUALIFIED));
- final String hierarchical= extended.getAttribute(ATTRIBUTE_HIERARCHICAL);
- if (hierarchical != null) {
- fRenameSubpackages= Boolean.valueOf(hierarchical).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_HIERARCHICAL));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameResourceProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameResourceProcessor.java
deleted file mode 100644
index dbeb5e40..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameResourceProcessor.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameResourceDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-public class RenameResourceProcessor extends RenameProcessor implements IScriptableRefactoring, ICommentProvider, INameUpdating {
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameResourceProcessor"; //$NON-NLS-1$
-
- private String fComment;
-
- private String fNewElementName;
-
- private RenameModifications fRenameModifications;
-
- private IResource fResource;
-
- /**
- * Creates a new rename resource processor.
- *
- * @param resource
- * the resource, or <code>null</code> if invoked by scripting
- */
- public RenameResourceProcessor(IResource resource) {
- fResource= resource;
- if (resource != null) {
- setNewElementName(resource.getName());
- }
- }
-
- public boolean canEnableComment() {
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws JavaScriptModelException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- fRenameModifications= new RenameModifications();
- fRenameModifications.rename(fResource, new RenameArguments(getNewElementName(), getUpdateReferences()));
-
- ResourceChangeChecker checker= (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory();
- fRenameModifications.buildDelta(deltaFactory);
-
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return RefactoringStatus.create(Resources.checkInSync(fResource));
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws JavaScriptModelException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- IContainer c= fResource.getParent();
- if (c == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameResourceRefactoring_Internal_Error);
-
- if (c.findMember(newName) != null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameResourceRefactoring_alread_exists);
-
- if (!c.getFullPath().isValidSegment(newName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameResourceRefactoring_invalidName);
-
- RefactoringStatus result= RefactoringStatus.create(c.getWorkspace().validateName(newName, fResource.getType()));
- if (!result.hasFatalError())
- result.merge(RefactoringStatus.create(c.getWorkspace().validatePath(createNewPath(newName), fResource.getType())));
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- String project= null;
- if (fResource.getType() != IResource.PROJECT)
- project= fResource.getProject().getName();
- final String header= Messages.format(RefactoringCoreMessages.RenameResourceChange_descriptor_description, new String[] { fResource.getFullPath().toString(), getNewElementName()});
- final String description= Messages.format(RefactoringCoreMessages.RenameResourceChange_descriptor_description_short, fResource.getName());
- final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
- final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE;
- final RenameResourceDescriptor descriptor= new RenameResourceDescriptor();
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setResource(fResource);
- descriptor.setNewName(getNewElementName());
- return new DynamicValidationStateChange(new RenameResourceChange(descriptor, fResource, getNewElementName(), comment));
- } finally {
- pm.done();
- }
- }
-
- private String createNewPath(String newName) {
- return fResource.getFullPath().removeLastSegments(1).append(newName).toString();
- }
-
- public String[] getAffectedProjectNatures() throws CoreException {
- return ResourceProcessors.computeAffectedNatures(fResource);
- }
-
- public String getComment() {
- return fComment;
- }
-
- public String getCurrentElementName() {
- return fResource.getName();
- }
-
- public Object[] getElements() {
- return new Object[] { fResource};
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public Object getNewElement() {
- return ResourcesPlugin.getWorkspace().getRoot().findMember(createNewPath(getNewElementName()));
- }
-
- public String getNewElementName() {
- return fNewElementName;
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameResourceProcessor_name;
- }
-
- public boolean getUpdateReferences() {
- return true;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- fResource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle);
- if (fResource == null || !fResource.exists())
- return ScriptableRefactoring.createInputFatalStatus(fResource, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_RESOURCE);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- public boolean isApplicable() throws JavaScriptModelException {
- return RefactoringAvailabilityTester.isRenameAvailable(fResource);
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- return fRenameModifications.loadParticipants(status, this, getAffectedProjectNatures(), shared);
- }
-
- public void setComment(final String comment) {
- fComment= comment;
- }
-
- public void setNewElementName(String newName) {
- Assert.isNotNull(newName);
- fNewElementName= newName;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameSourceFolderProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameSourceFolderProcessor.java
deleted file mode 100644
index d21b81f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameSourceFolderProcessor.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameSourceFolderChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-public final class RenameSourceFolderProcessor extends JavaRenameProcessor {
-
- private static final String ATTRIBUTE_PATH= "path"; //$NON-NLS-1$
- private static final String ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
-
- private IPackageFragmentRoot fSourceFolder;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameSourceFolderProcessor"; //$NON-NLS-1$
-
- /**
- * Creates a new rename source folder processor.
- * @param root the package fragment root, or <code>null</code> if invoked by scripting
- */
- public RenameSourceFolderProcessor(IPackageFragmentRoot root) {
- fSourceFolder= root;
- if (root != null)
- setNewElementName(root.getElementName());
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fSourceFolder);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameSourceFolderRefactoring_rename;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fSourceFolder);
- }
-
- public Object[] getElements() {
- return new Object[] {fSourceFolder};
- }
-
- public Object getNewElement() throws CoreException {
- IPackageFragmentRoot[] roots= fSourceFolder.getJavaScriptProject().getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (roots[i].getElementName().equals(getNewElementName()))
- return roots[i];
- }
- return null;
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_ALL;
- }
-
- protected RenameModifications computeRenameModifications() throws CoreException {
- RenameModifications result= new RenameModifications();
- result.rename(fSourceFolder, new RenameArguments(getNewElementName(), getUpdateReferences()));
- return result;
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- return new IFile[0];
- }
-
- //---- IRenameProcessor ----------------------------------------------
-
- public String getCurrentElementName() {
- return fSourceFolder.getElementName();
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return new RefactoringStatus();
- }
-
- public RefactoringStatus checkNewElementName(String newName) throws CoreException {
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- if (! newName.trim().equals(newName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_blank);
-
- IContainer c= fSourceFolder.getResource().getParent();
- if (! c.getFullPath().isValidSegment(newName))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_invalid_name);
-
- RefactoringStatus result= RefactoringStatus.create(c.getWorkspace().validateName(newName, IResource.FOLDER));
- if (result.hasFatalError())
- return result;
-
- result.merge(RefactoringStatus.create(c.getWorkspace().validatePath(createNewPath(newName), IResource.FOLDER)));
- if (result.hasFatalError())
- return result;
-
- IJavaScriptProject project= fSourceFolder.getJavaScriptProject();
- IPath p= project.getProject().getFullPath().append(newName);
- if (project.findPackageFragmentRoot(p) != null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_already_exists);
-
- if (project.getProject().findMember(new Path(newName)) != null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_alread_exists);
- return result;
- }
-
- private String createNewPath(String newName) {
- return fSourceFolder.getPath().removeLastSegments(1).append(newName).toString();
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try{
- return new RefactoringStatus();
- } finally{
- pm.done();
- }
- }
-
- public boolean getUpdateReferences() {
- return true;
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 1);
- try {
- final IResource resource= fSourceFolder.getResource();
- final String project= resource.getProject().getName();
- final String newName= getNewElementName();
- final String description= Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_descriptor_description_short, fSourceFolder.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameSourceFolderChange_descriptor_description, new String[] { resource.getFullPath().toString(), newName});
- final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_SOURCE_FOLDER);
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(RefactoringDescriptor.NONE);
- descriptor.setJavaElement(fSourceFolder);
- descriptor.setNewName(newName);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameSourceFolderRefactoring_rename, new Change[] { new RenameSourceFolderChange(fSourceFolder, newName)});
- } finally {
- monitor.done();
- }
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments generic= (JavaRefactoringArguments) arguments;
- final String path= generic.getAttribute(ATTRIBUTE_PATH);
- if (path != null) {
- final IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(path));
- if (resource == null || !resource.exists())
- return ScriptableRefactoring.createInputFatalStatus(resource, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_SOURCE_FOLDER);
- else
- fSourceFolder= (IPackageFragmentRoot) JavaScriptCore.create(resource);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_PATH));
- final String name= generic.getAttribute(ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_NAME));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameTypeProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameTypeProcessor.java
deleted file mode 100644
index 5a63c08e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameTypeProcessor.java
+++ /dev/null
@@ -1,1702 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProduct;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.IResourceMapper;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.IParticipantDescriptorFilter;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptElementMapper;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.RenameTypeArguments;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeReferenceMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ISimilarDeclarationUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.Changes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameSearchResult;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class RenameTypeProcessor extends JavaRenameProcessor implements ITextUpdating, IReferenceUpdating, IQualifiedNameUpdating, ISimilarDeclarationUpdating, IResourceMapper, IJavaScriptElementMapper {
-
- private static final String ATTRIBUTE_QUALIFIED= "qualified"; //$NON-NLS-1$
- private static final String ATTRIBUTE_TEXTUAL_MATCHES= "textual"; //$NON-NLS-1$
- private static final String ATTRIBUTE_PATTERNS= "patterns"; //$NON-NLS-1$
- private static final String ATTRIBUTE_SIMILAR_DECLARATIONS= "similarDeclarations"; //$NON-NLS-1$
- private static final String ATTRIBUTE_MATCHING_STRATEGY= "matchStrategy"; //$NON-NLS-1$
-
- private static final GroupCategorySet CATEGORY_TYPE_RENAME= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.refactoring.rename.renameType.type", RefactoringCoreMessages.RenameTypeProcessor_changeCategory_type, RefactoringCoreMessages.RenameTypeProcessor_changeCategory_type_description)); //$NON-NLS-1$
- private static final GroupCategorySet CATEGORY_METHOD_RENAME= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.refactoring.rename.renameType.method", RefactoringCoreMessages.RenameTypeProcessor_changeCategory_method, RefactoringCoreMessages.RenameTypeProcessor_changeCategory_method_description)); //$NON-NLS-1$
- private static final GroupCategorySet CATEGORY_FIELD_RENAME= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.refactoring.rename.renameType.field", RefactoringCoreMessages.RenameTypeProcessor_changeCategory_fields, RefactoringCoreMessages.RenameTypeProcessor_changeCategory_fields_description)); //$NON-NLS-1$
- private static final GroupCategorySet CATEGORY_LOCAL_RENAME= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.refactoring.rename.renameType.local", RefactoringCoreMessages.RenameTypeProcessor_changeCategory_local_variables, RefactoringCoreMessages.RenameTypeProcessor_changeCategory_local_variables_description)); //$NON-NLS-1$
-
- private IType fType;
- private SearchResultGroup[] fReferences;
- private TextChangeManager fChangeManager;
- private QualifiedNameSearchResult fQualifiedNameSearchResult;
-
- private boolean fUpdateReferences;
-
- private boolean fUpdateTextualMatches;
-
- private boolean fUpdateQualifiedNames;
- private String fFilePatterns;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.renameTypeProcessor"; //$NON-NLS-1$
-
- // --- similar elements
-
- private boolean fUpdateSimilarElements;
- private Map/* <IJavaScriptElement, String> */fFinalSimilarElementToName= null;
- private int fRenamingStrategy;
-
- // Preloaded information for the UI.
- private LinkedHashMap/* <IJavaScriptElement, String> */fPreloadedElementToName= null;
- private Map/* <IJavaScriptElement, Boolean> */fPreloadedElementToSelection= null;
- private LinkedHashMap/* <IJavaScriptElement, String> */fPreloadedElementToNameDefault= null;
-
- // Cache information to decide whether to
- // re-update references and preload info
- private String fCachedNewName= null;
- private boolean fCachedRenameSimilarElements= false;
- private int fCachedRenamingStrategy= -1;
- private RefactoringStatus fCachedRefactoringStatus= null;
-
- public static final class ParticipantDescriptorFilter implements IParticipantDescriptorFilter {
-
- public boolean select(IConfigurationElement element, RefactoringStatus status) {
- IConfigurationElement[] params= element.getChildren(PARAM);
- for (int i= 0; i < params.length; i++) {
- IConfigurationElement param= params[i];
- if ("handlesSimilarDeclarations".equals(param.getAttribute(NAME)) && //$NON-NLS-1$
- "false".equals(param.getAttribute(VALUE))) { //$NON-NLS-1$
- return false;
- }
- }
- return true;
- }
- }
-
- private class NoOverrideProgressMonitor extends SubProgressMonitor {
- public NoOverrideProgressMonitor(IProgressMonitor monitor, int ticks) {
- super(monitor, ticks, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- }
- public void setTaskName(String name) {
- // do nothing
- }
- }
-
- /**
- * Creates a new rename type processor.
- * @param type the type, or <code>null</code> if invoked by scripting
- */
- public RenameTypeProcessor(IType type) {
- fType= type;
- if (type != null)
- setNewElementName(type.getElementName());
- fUpdateReferences= true; //default is yes
- fUpdateTextualMatches= false;
- fUpdateSimilarElements= false; // default is no
- fRenamingStrategy= RenamingNameSuggestor.STRATEGY_EXACT;
- }
-
- public IType getType() {
- return fType;
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameAvailable(fType);
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.RenameTypeRefactoring_name;
- }
-
- protected String[] getAffectedProjectNatures() throws CoreException {
- return JavaProcessors.computeAffectedNatures(fType);
- }
-
- public Object[] getElements() {
- return new Object[] {fType};
- }
-
- protected RenameModifications computeRenameModifications() {
- RenameModifications result= new RenameModifications();
- result.rename(fType, new RenameTypeArguments(getNewElementName(), getUpdateReferences(),
- getUpdateSimilarDeclarations(), getSimilarElements()), createParticipantDescriptorFilter());
- if (isPrimaryType()) {
- IJavaScriptUnit cu= fType.getJavaScriptUnit();
- String newCUName= getNewCompilationUnit().getElementName();
- result.rename(cu, new RenameArguments(newCUName, getUpdateReferences()));
- }
- return result;
- }
-
- /*
- * Note: this is a handle-only method!
- */
- private boolean isPrimaryType() {
- String cuName= fType.getJavaScriptUnit().getElementName();
- String typeName= fType.getElementName();
- return Checks.isTopLevel(fType) && JavaScriptCore.removeJavaScriptLikeExtension(cuName).equals(typeName);
- }
-
- //---- IRenameProcessor ----------------------------------------------
-
- public String getCurrentElementName(){
- return fType.getElementName();
- }
-
- public String getCurrentElementQualifier(){
- return JavaModelUtil.getTypeContainerName(fType);
- }
-
- public RefactoringStatus checkNewElementName(String newName){
- Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
- RefactoringStatus result= Checks.checkTypeName(newName);
- if (Checks.isAlreadyNamed(fType, newName))
- result.addFatalError(RefactoringCoreMessages.RenameTypeRefactoring_choose_another_name);
- return result;
- }
-
- public Object getNewElement() {
- if (Checks.isTopLevel(fType)) {
- return getNewCompilationUnit().getType(getNewElementName());
- } else {
- return fType.getDeclaringType().getType(getNewElementName());
- }
- }
-
- private IJavaScriptUnit getNewCompilationUnit() {
- IJavaScriptUnit cu= fType.getJavaScriptUnit();
- if (isPrimaryType()) {
- IPackageFragment parent= fType.getPackageFragment();
- String renamedCUName= JavaModelUtil.getRenamedCUName(cu, getNewElementName());
- return parent.getJavaScriptUnit(renamedCUName);
- } else {
- return cu;
- }
- }
-
- //---- JavaRenameProcessor -------------------------------------------
-
- protected RenameArguments createRenameArguments() {
- return new RenameTypeArguments(getNewElementName(), getUpdateReferences(),
- getUpdateSimilarDeclarations(), getSimilarElements());
- }
-
- protected IParticipantDescriptorFilter createParticipantDescriptorFilter() {
- if (!getUpdateSimilarDeclarations())
- return null;
- return new ParticipantDescriptorFilter();
- }
-
- protected IFile[] getChangedFiles() throws CoreException {
- List result= new ArrayList();
- result.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits())));
- if (fQualifiedNameSearchResult != null)
- result.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles()));
- if (willRenameCU())
- result.add(ResourceUtil.getFile(fType.getJavaScriptUnit()));
- return (IFile[]) result.toArray(new IFile[result.size()]);
- }
-
- public int getSaveMode() {
- return RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES;
- }
-
- //---- ITextUpdating -------------------------------------------------
-
- public boolean canEnableTextUpdating() {
- return true;
- }
-
- public boolean getUpdateTextualMatches() {
- return fUpdateTextualMatches;
- }
- public void setUpdateTextualMatches(boolean update) {
- fUpdateTextualMatches= update;
- }
-
- //---- IReferenceUpdating --------------------------------------
-
- public void setUpdateReferences(boolean update){
- fUpdateReferences= update;
- }
-
- public boolean canEnableUpdateReferences(){
- return true;
- }
-
- public boolean getUpdateReferences(){
- return fUpdateReferences;
- }
-
- //---- IQualifiedNameUpdating ----------------------------------
-
- public boolean canEnableQualifiedNameUpdating() {
- return !fType.getPackageFragment().isDefaultPackage() && !(fType.getParent() instanceof IType);
- }
-
- public boolean getUpdateQualifiedNames() {
- return fUpdateQualifiedNames;
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- fUpdateQualifiedNames= update;
- }
-
- public String getFilePatterns() {
- return fFilePatterns;
- }
-
- public void setFilePatterns(String patterns) {
- Assert.isNotNull(patterns);
- fFilePatterns= patterns;
- }
-
- // ---- ISimilarDeclarationUpdating
-
- public boolean canEnableSimilarDeclarationUpdating() {
-
- IProduct product= Platform.getProduct();
- if (product != null) {
- String property= product.getProperty("org.eclipse.wst.jsdt.ui.refactoring.handlesSimilarDeclarations"); //$NON-NLS-1$
- if ("false".equalsIgnoreCase(property)) //$NON-NLS-1$
- return false;
- }
-
- return true;
- }
-
- public void setUpdateSimilarDeclarations(boolean update) {
- fUpdateSimilarElements= update;
- }
-
- public boolean getUpdateSimilarDeclarations() {
- return fUpdateSimilarElements;
- }
-
- public int getMatchStrategy() {
- return fRenamingStrategy;
-
- }
-
- public void setMatchStrategy(int selectedStrategy) {
- fRenamingStrategy= selectedStrategy;
- }
-
- /**
- * @return the similar elements of the type, i.e. IFields, IMethods, and
- * ILocalVariables. Returns <code>null</code> iff similar declaration updating
- * is not requested.
- */
- public IJavaScriptElement[] getSimilarElements() {
- if (fFinalSimilarElementToName == null)
- return null;
- Set keys= fFinalSimilarElementToName.keySet();
- return (IJavaScriptElement[])keys.toArray(new IJavaScriptElement[keys.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public IResource getRefactoredResource(IResource element) {
- if (element instanceof IFile) {
- if (Checks.isTopLevel(fType) && element.equals(fType.getResource()))
- return getNewCompilationUnit().getResource();
- }
- return element;
- }
-
- /**
- * {@inheritDoc}
- */
- public IJavaScriptElement getRefactoredJavaScriptElement(IJavaScriptElement element) {
- if (element instanceof IJavaScriptUnit) {
- if (Checks.isTopLevel(fType) && element.equals(fType.getJavaScriptUnit()))
- return getNewCompilationUnit();
- } else if (element instanceof IMember) {
- final IType newType= (IType) getNewElement();
- final RefactoringHandleTransplanter transplanter= new RefactoringHandleTransplanter(fType, newType, fFinalSimilarElementToName);
- return transplanter.transplantHandle((IMember) element);
- }
- return element;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- IType primary= (IType) fType.getPrimaryElement();
- if (primary == null || !primary.exists()) {
- String message= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_does_not_exist, new String[] { JavaModelUtil.getFullyQualifiedName(fType), fType.getJavaScriptUnit().getElementName()});
- return RefactoringStatus.createFatalErrorStatus(message);
- }
- fType= primary;
- return Checks.checkIfCuBroken(fType);
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- Assert.isNotNull(fType, "type"); //$NON-NLS-1$
- Assert.isNotNull(getNewElementName(), "newName"); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
-
- int referenceSearchTicks= fUpdateReferences || fUpdateSimilarElements ? 15 : 0;
- int affectedCusTicks= fUpdateReferences || fUpdateSimilarElements ? 10 : 1;
- int similarElementTicks= fUpdateSimilarElements ? 85 : 0;
- int createChangeTicks = 5;
- int qualifiedNamesTicks= fUpdateQualifiedNames ? 50 : 0;
-
- try{
- pm.beginTask("", 12 + referenceSearchTicks + affectedCusTicks + similarElementTicks + createChangeTicks + qualifiedNamesTicks); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.RenameTypeRefactoring_checking);
-
- fChangeManager= new TextChangeManager(true);
-
- result.merge(checkNewElementName(getNewElementName()));
- if (result.hasFatalError())
- return result;
- result.merge(Checks.checkIfCuBroken(fType));
- if (result.hasFatalError())
- return result;
- pm.worked(1);
-
- result.merge(checkTypesInCompilationUnit());
- pm.worked(1);
-
- result.merge(checkForMethodsWithConstructorNames());
- pm.worked(1);
-
- result.merge(checkImportedTypes());
- pm.worked(1);
-
- if (Checks.isTopLevel(fType) && (JdtFlags.isPublic(fType)))
- result.merge(Checks.checkCompilationUnitNewName(fType.getJavaScriptUnit(), getNewElementName()));
- pm.worked(1);
-
- if (isPrimaryType())
- result.merge(checkNewPathValidity());
- pm.worked(1);
-
- result.merge(checkEnclosingTypes());
- pm.worked(1);
-
- result.merge(checkEnclosedTypes());
- pm.worked(1);
-
- result.merge(checkTypesInPackage());
- pm.worked(1);
-
- result.merge(checkTypesImportedInCu());
- pm.worked(1);
-
-// result.merge(Checks.checkForMainAndNativeMethods(fType));
-// pm.worked(1);
-
- // before doing any expensive analysis
- if (result.hasFatalError())
- return result;
-
- result.merge(analyseEnclosedTypes());
- pm.worked(1);
- // before doing _the really_ expensive analysis
- if (result.hasFatalError())
- return result;
-
- // Load references, including similarly named elements
- if (fUpdateReferences || fUpdateSimilarElements) {
- pm.setTaskName(RefactoringCoreMessages.RenameTypeRefactoring_searching);
- result.merge(initializeReferences(new SubProgressMonitor(pm, referenceSearchTicks)));
- } else {
- fReferences= new SearchResultGroup[0];
- }
-
- pm.setTaskName(RefactoringCoreMessages.RenameTypeRefactoring_checking);
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- if (fUpdateReferences || fUpdateSimilarElements) {
- result.merge(analyzeAffectedCompilationUnits(new SubProgressMonitor(pm, affectedCusTicks)));
- } else {
- Checks.checkCompileErrorsInAffectedFile(result, fType.getResource());
- pm.worked(affectedCusTicks);
- }
-
- if (result.hasFatalError())
- return result;
-
- if (fUpdateSimilarElements) {
- result.merge(initializeSimilarElementsRenameProcessors(new SubProgressMonitor(pm, similarElementTicks), context));
- if (result.hasFatalError())
- return result;
- }
-
- createChanges(new SubProgressMonitor(pm, createChangeTicks));
-
- if (fUpdateQualifiedNames)
- computeQualifiedNameMatches(new SubProgressMonitor(pm, qualifiedNamesTicks));
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- /**
- * Initializes the references to the type and the similarly named elements. This
- * method creates both the fReferences and the fPreloadedElementToName
- * fields.
- *
- * May be called from the UI.
- * @param monitor
- * @return initialization status
- * @throws JavaScriptModelException some fundamental error with the underlying model
- * @throws OperationCanceledException if user canceled the task
- *
- */
- public RefactoringStatus initializeReferences(IProgressMonitor monitor) throws JavaScriptModelException, OperationCanceledException {
-
- Assert.isNotNull(fType);
- Assert.isNotNull(getNewElementName());
-
- // Do not search again if the preconditions have not changed.
- // Search depends on the type, the new name, the similarly named elements, and
- // the strategy
-
- if (fReferences != null && (getNewElementName().equals(fCachedNewName)) && (fCachedRenameSimilarElements == getUpdateSimilarDeclarations()) && (fCachedRenamingStrategy == fRenamingStrategy))
- return fCachedRefactoringStatus;
-
- fCachedNewName= getNewElementName();
- fCachedRenameSimilarElements= fUpdateSimilarElements;
- fCachedRenamingStrategy= fRenamingStrategy;
- fCachedRefactoringStatus= new RefactoringStatus();
-
-
- try {
- SearchPattern pattern= SearchPattern.createPattern(fType, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- fReferences= RefactoringSearchEngine.search(
- pattern,
- RefactoringScopeFactory.create(fType),
- new TypeOccurrenceCollector(fType),
- monitor,
- fCachedRefactoringStatus);
- fReferences= Checks.excludeCompilationUnits(fReferences, fCachedRefactoringStatus);
-
- fPreloadedElementToName= new LinkedHashMap();
- fPreloadedElementToSelection= new HashMap();
-
- final String unQualifiedTypeName= fType.getElementName();
-
- monitor.beginTask("", fReferences.length); //$NON-NLS-1$
-
- if (getUpdateSimilarDeclarations()) {
-
- RenamingNameSuggestor sugg= new RenamingNameSuggestor(fRenamingStrategy);
-
- for (int i= 0; i < fReferences.length; i++) {
- final IJavaScriptUnit cu= fReferences[i].getCompilationUnit();
- if (cu == null)
- continue;
-
- final SearchMatch[] results= fReferences[i].getSearchResults();
-
- for (int j= 0; j < results.length; j++) {
-
- if (! (results[j] instanceof TypeReferenceMatch))
- continue;
-
- final TypeReferenceMatch match= (TypeReferenceMatch) results[j];
- final List matches= new ArrayList();
-
- if (match.getLocalElement() != null)
- matches.add(match.getLocalElement());
- else
- matches.add(match.getElement());
-
- final IJavaScriptElement[] others= match.getOtherElements();
- if (others != null)
- matches.addAll(Arrays.asList(others));
-
- for (Iterator iter= matches.iterator(); iter.hasNext();) {
- final IJavaScriptElement element= (IJavaScriptElement) iter.next();
-
- if (! (element instanceof IFunction) && ! (element instanceof IField) && ! (element instanceof ILocalVariable))
- continue;
-
- if (!isInDeclaredType(match.getOffset(), element))
- continue;
-
- if (element instanceof IField) {
- final IField currentField= (IField) element;
- final String newFieldName= sugg.suggestNewFieldName(currentField.getJavaScriptProject(), currentField.getElementName(), Flags.isStatic(currentField.getFlags()),
- unQualifiedTypeName, getNewElementName());
-
- if (newFieldName != null)
- fPreloadedElementToName.put(currentField, newFieldName);
- }
-
- if (element instanceof IFunction) {
- final IFunction currentMethod= (IFunction) element;
- addMethodRename(unQualifiedTypeName, sugg, currentMethod);
- }
-
- if (element instanceof ILocalVariable) {
- final ILocalVariable currentLocal= (ILocalVariable) element;
- final boolean isParameter;
-
- if (JavaModelUtil.isParameter(currentLocal)) {
- addMethodRename(unQualifiedTypeName, sugg, (IFunction) currentLocal.getParent());
- isParameter= true;
- } else
- isParameter= false;
-
- final String newLocalName= sugg
- .suggestNewLocalName(currentLocal.getJavaScriptProject(), currentLocal.getElementName(), isParameter, unQualifiedTypeName, getNewElementName());
-
- if (newLocalName != null)
- fPreloadedElementToName.put(currentLocal, newLocalName);
- }
- }
- }
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
- }
-
- for (Iterator iter= fPreloadedElementToName.keySet().iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- fPreloadedElementToSelection.put(element, Boolean.TRUE);
- }
- fPreloadedElementToNameDefault= (LinkedHashMap) fPreloadedElementToName.clone();
-
- } catch (OperationCanceledException e) {
- fReferences= null;
- fPreloadedElementToName= null;
- throw new OperationCanceledException();
- }
- return fCachedRefactoringStatus;
- }
-
- /**
- * @param matchOffset
- * @param parentElement
- * @return true iff the given search match offset (must be a match of a type
- * reference) lies before the element name of its enclosing java element,
- * false if not. In other words: If this method returns true, the match is
- * the declared type (or return type) of the enclosing element.
- * @throws JavaScriptModelException
- *
- */
- private boolean isInDeclaredType(int matchOffset, IJavaScriptElement parentElement) throws JavaScriptModelException {
- if (parentElement != null) {
- int enclosingNameOffset= 0;
- if (parentElement instanceof IFunction || parentElement instanceof IField)
- enclosingNameOffset= ((IMember) parentElement).getNameRange().getOffset();
- else if (parentElement instanceof ILocalVariable)
- enclosingNameOffset= ((ILocalVariable) parentElement).getNameRange().getOffset();
-
- return (matchOffset < enclosingNameOffset);
- }
- return false;
- }
-
- private void addMethodRename(final String unQualifiedTypeName, RenamingNameSuggestor sugg, final IFunction currentMethod) throws JavaScriptModelException {
- if (!currentMethod.isConstructor()) {
- final String newMethodName= sugg.suggestNewMethodName(currentMethod.getElementName(), unQualifiedTypeName, getNewElementName());
-
- if (newMethodName != null)
- fPreloadedElementToName.put(currentMethod, newMethodName);
- }
- }
-
- private RefactoringStatus checkNewPathValidity() {
- IContainer c= fType.getJavaScriptUnit().getResource().getParent();
-
- String notRename= RefactoringCoreMessages.RenameTypeRefactoring_will_not_rename;
- IStatus status= c.getWorkspace().validateName(getNewElementName(), IResource.FILE);
- if (status.getSeverity() == IStatus.ERROR)
- return RefactoringStatus.createWarningStatus(status.getMessage() + ". " + notRename); //$NON-NLS-1$
-
- status= c.getWorkspace().validatePath(createNewPath(getNewElementName()), IResource.FILE);
- if (status.getSeverity() == IStatus.ERROR)
- return RefactoringStatus.createWarningStatus(status.getMessage() + ". " + notRename); //$NON-NLS-1$
-
- return new RefactoringStatus();
- }
-
- private String createNewPath(String newName) {
- return fType.getJavaScriptUnit().getResource().getFullPath().removeLastSegments(1).append(newName).toString();
- }
-
- private RefactoringStatus checkTypesImportedInCu() throws CoreException {
- IImportDeclaration imp= getImportedType(fType.getJavaScriptUnit(), getNewElementName());
-
- if (imp == null)
- return null;
-
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_imported,
- new Object[]{getNewElementName(), fType.getJavaScriptUnit().getResource().getFullPath()});
- IJavaScriptElement grandParent= imp.getParent().getParent();
- if (grandParent instanceof IJavaScriptUnit)
- return RefactoringStatus.createErrorStatus(msg, JavaStatusContext.create(imp));
-
- return null;
- }
-
- private RefactoringStatus checkTypesInPackage() throws CoreException {
- IType type= Checks.findTypeInPackage(fType.getPackageFragment(), getNewElementName());
- if (type == null || ! type.exists())
- return null;
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_exists,
- new String[]{getNewElementName(), fType.getPackageFragment().getElementName()});
- return RefactoringStatus.createErrorStatus(msg, JavaStatusContext.create(type));
- }
-
- private RefactoringStatus checkEnclosedTypes() throws CoreException {
- IType enclosedType= findEnclosedType(fType, getNewElementName());
- if (enclosedType == null)
- return null;
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_encloses,
- new String[]{JavaModelUtil.getFullyQualifiedName(fType), getNewElementName()});
- return RefactoringStatus.createErrorStatus(msg, JavaStatusContext.create(enclosedType));
- }
-
- private RefactoringStatus checkEnclosingTypes() {
- IType enclosingType= findEnclosingType(fType, getNewElementName());
- if (enclosingType == null)
- return null;
-
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_enclosed,
- new String[]{JavaModelUtil.getFullyQualifiedName(fType), getNewElementName()});
- return RefactoringStatus.createErrorStatus(msg, JavaStatusContext.create(enclosingType));
- }
-
- private static IType findEnclosedType(IType type, String newName) throws CoreException {
- IType[] enclosedTypes= type.getTypes();
- for (int i= 0; i < enclosedTypes.length; i++){
- if (newName.equals(enclosedTypes[i].getElementName()) || findEnclosedType(enclosedTypes[i], newName) != null)
- return enclosedTypes[i];
- }
- return null;
- }
-
- private static IType findEnclosingType(IType type, String newName) {
- IType enclosing= type.getDeclaringType();
- while (enclosing != null){
- if (newName.equals(enclosing.getElementName()))
- return enclosing;
- else
- enclosing= enclosing.getDeclaringType();
- }
- return null;
- }
-
- private static IImportDeclaration getImportedType(IJavaScriptUnit cu, String typeName) throws CoreException {
- IImportDeclaration[] imports= cu.getImports();
- String dotTypeName= "." + typeName; //$NON-NLS-1$
- for (int i= 0; i < imports.length; i++){
- if (imports[i].getElementName().endsWith(dotTypeName))
- return imports[i];
- }
- return null;
- }
-
- private RefactoringStatus checkForMethodsWithConstructorNames() throws CoreException{
- IFunction[] methods= fType.getFunctions();
- for (int i= 0; i < methods.length; i++){
- if (methods[i].isConstructor())
- continue;
- RefactoringStatus check= Checks.checkIfConstructorName(methods[i], methods[i].getElementName(), getNewElementName());
- if (check != null)
- return check;
- }
- return null;
- }
-
- private RefactoringStatus checkImportedTypes() throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- IImportDeclaration[] imports= fType.getJavaScriptUnit().getImports();
- for (int i= 0; i < imports.length; i++)
- analyzeImportDeclaration(imports[i], result);
- return result;
- }
-
- private RefactoringStatus checkTypesInCompilationUnit() {
- RefactoringStatus result= new RefactoringStatus();
- if (! Checks.isTopLevel(fType)){ //the other case checked in checkTypesInPackage
- IType siblingType= fType.getDeclaringType().getType(getNewElementName());
- if (siblingType.exists()){
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type_exists,
- new String[]{getNewElementName(), JavaModelUtil.getFullyQualifiedName(fType.getDeclaringType())});
- result.addError(msg, JavaStatusContext.create(siblingType));
- }
- }
- return result;
- }
-
- private RefactoringStatus analyseEnclosedTypes() throws CoreException {
- final ISourceRange typeRange= fType.getSourceRange();
- final RefactoringStatus result= new RefactoringStatus();
- JavaScriptUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(fType.getJavaScriptUnit(), false);
- cuNode.accept(new ASTVisitor(){
-
- public boolean visit(TypeDeclaration node){ // enums and annotations can't be local
- if (node.getStartPosition() <= typeRange.getOffset())
- return true;
- if (node.getStartPosition() > typeRange.getOffset() + typeRange.getLength())
- return true;
-
- if (getNewElementName().equals(node.getName().getIdentifier())){
- RefactoringStatusContext context= JavaStatusContext.create(fType.getJavaScriptUnit(), node);
- String msg= null;
- if (node.isLocalTypeDeclaration()){
- msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_local_type,
- new String[]{JavaElementUtil.createSignature(fType), getNewElementName()});
- }
- else if (node.isMemberTypeDeclaration()){
- msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type,
- new String[]{JavaElementUtil.createSignature(fType), getNewElementName()});
- }
- if (msg != null)
- result.addError(msg, context);
- }
-
- FunctionDeclaration[] methods= node.getMethods();
- for (int i= 0; i < methods.length; i++) {
- if (Modifier.isNative(methods[i].getModifiers())){
- RefactoringStatusContext context= JavaStatusContext.create(fType.getJavaScriptUnit(), methods[i]);
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_enclosed_type_native, node.getName().getIdentifier());
- result.addWarning(msg, context);
- }
- }
- return true;
- }
- });
- return result;
- }
-
- private static IJavaScriptUnit getCompilationUnit(IImportDeclaration imp) {
- return (IJavaScriptUnit)imp.getParent().getParent();
- }
-
- private void analyzeImportedTypes(IType[] types, RefactoringStatus result, IImportDeclaration imp) throws CoreException {
- for (int i= 0; i < types.length; i++) {
- //could this be a problem (same package imports)?
- if (JdtFlags.isPublic(types[i]) && types[i].getElementName().equals(getNewElementName())){
- String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_name_conflict1,
- new Object[]{JavaModelUtil.getFullyQualifiedName(types[i]), getFullPath(getCompilationUnit(imp))});
- result.addError(msg, JavaStatusContext.create(imp));
- }
- }
- }
-
- private static IJavaScriptElement convertFromImportDeclaration(IImportDeclaration declaration) throws CoreException {
- if (declaration.isOnDemand()){
- String packageName= declaration.getElementName().substring(0, declaration.getElementName().length() - 2);
- return JavaModelUtil.findTypeContainer(declaration.getJavaScriptProject(), packageName);
- } else
- return JavaModelUtil.findTypeContainer(declaration.getJavaScriptProject(), declaration.getElementName());
- }
-
- private void analyzeImportDeclaration(IImportDeclaration imp, RefactoringStatus result) throws CoreException{
- if (!imp.isOnDemand())
- return; //analyzed earlier
-
- IJavaScriptElement imported= convertFromImportDeclaration(imp);
- if (imported == null)
- return;
-
- if (imported instanceof IPackageFragment){
- IJavaScriptUnit[] cus= ((IPackageFragment)imported).getJavaScriptUnits();
- for (int i= 0; i < cus.length; i++) {
- analyzeImportedTypes(cus[i].getTypes(), result, imp);
- }
- } else {
- //cast safe: see JavaModelUtility.convertFromImportDeclaration
- analyzeImportedTypes(((IType)imported).getTypes(), result, imp);
- }
- }
-
- /*
- * Analyzes all compilation units in which type is referenced
- */
- private RefactoringStatus analyzeAffectedCompilationUnits(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
-
- result.merge(Checks.checkCompileErrorsInAffectedFiles(fReferences, fType.getResource()));
-
- pm.beginTask("", fReferences.length); //$NON-NLS-1$
- result.merge(checkConflictingTypes(pm));
- return result;
- }
-
- private RefactoringStatus checkConflictingTypes(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(fType);
- SearchPattern pattern= SearchPattern.createPattern(getNewElementName(),
- IJavaScriptSearchConstants.TYPE, IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptUnit[] cusWithReferencesToConflictingTypes= RefactoringSearchEngine.findAffectedCompilationUnits(pattern, scope, pm, result);
- if (cusWithReferencesToConflictingTypes.length == 0)
- return result;
- IJavaScriptUnit[] cusWithReferencesToRenamedType= getCus(fReferences);
-
- IJavaScriptUnit[] intersection= isIntersectionEmpty(cusWithReferencesToRenamedType, cusWithReferencesToConflictingTypes);
- if (intersection.length == 0)
- return result;
-
- for (int i= 0; i < intersection.length; i++) {
- RefactoringStatusContext context= JavaStatusContext.create(intersection[i]);
- String message= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_another_type,
- new String[]{getNewElementName(), intersection[i].getElementName()});
- result.addError(message, context);
- }
- return result;
- }
-
- private static IJavaScriptUnit[] isIntersectionEmpty(IJavaScriptUnit[] a1, IJavaScriptUnit[] a2){
- Set set1= new HashSet(Arrays.asList(a1));
- Set set2= new HashSet(Arrays.asList(a2));
- set1.retainAll(set2);
- return (IJavaScriptUnit[]) set1.toArray(new IJavaScriptUnit[set1.size()]);
- }
-
- private static IJavaScriptUnit[] getCus(SearchResultGroup[] searchResultGroups){
- List cus= new ArrayList(searchResultGroups.length);
- for (int i= 0; i < searchResultGroups.length; i++) {
- IJavaScriptUnit cu= searchResultGroups[i].getCompilationUnit();
- if (cu != null)
- cus.add(cu);
- }
- return (IJavaScriptUnit[]) cus.toArray(new IJavaScriptUnit[cus.size()]);
- }
-
- private static String getFullPath(IJavaScriptUnit cu) {
- Assert.isTrue(cu.exists());
- return cu.getResource().getFullPath().toString();
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 4);
- String project= null;
- IJavaScriptProject javaProject= fType.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
- try {
- if (!Flags.isPrivate(fType.getFlags()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- if (fType.isAnonymous() || fType.isLocal())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description_short, fType.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), getNewElementName()});
- final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
- final RenameJavaScriptElementDescriptor descriptor= new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_TYPE);
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment);
- descriptor.setFlags(flags);
- descriptor.setJavaElement(fType);
- descriptor.setNewName(getNewElementName());
- descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
- descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
- descriptor.setUpdateReferences(fUpdateReferences);
- if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
- descriptor.setFileNamePatterns(fFilePatterns);
- descriptor.setUpdateSimilarDeclarations(fUpdateSimilarElements);
- descriptor.setMatchStrategy(fRenamingStrategy);
- final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameTypeProcessor_change_name);
-
- if (fChangeManager.containsChangesIn(fType.getJavaScriptUnit())) {
- TextChange textChange= fChangeManager.get(fType.getJavaScriptUnit());
- if (textChange instanceof TextFileChange) {
- ((TextFileChange) textChange).setSaveMode(TextFileChange.FORCE_SAVE);
- }
- }
- result.addAll(fChangeManager.getAllChanges());
- if (willRenameCU()) {
- IResource resource= fType.getJavaScriptUnit().getResource();
- if (resource != null && resource.isLinked()) {
- String ext= resource.getFileExtension();
- String renamedResourceName;
- if (ext == null)
- renamedResourceName= getNewElementName();
- else
- renamedResourceName= getNewElementName() + '.' + ext;
- result.add(new RenameResourceChange(null, fType.getJavaScriptUnit().getResource(), renamedResourceName, comment));
- } else {
- String renamedCUName= JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), getNewElementName());
- result.add(new RenameCompilationUnitChange(fType.getJavaScriptUnit(), renamedCUName));
- }
- }
- monitor.worked(1);
- return result;
- } finally {
- fChangeManager= null;
- }
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- if (fQualifiedNameSearchResult != null) {
- try {
- return fQualifiedNameSearchResult.getSingleChange(Changes.getModifiedFiles(participantChanges));
- } finally {
- fQualifiedNameSearchResult= null;
- }
- } else {
- return null;
- }
- }
-
- private boolean willRenameCU() throws CoreException{
- String name = JavaScriptCore.removeJavaScriptLikeExtension(fType.getJavaScriptUnit().getElementName());
- if (! (Checks.isTopLevel(fType) && name.equals(fType.getElementName())))
- return false;
- if (! checkNewPathValidity().isOK())
- return false;
- if (! Checks.checkCompilationUnitNewName(fType.getJavaScriptUnit(), getNewElementName()).isOK())
- return false;
- return true;
- }
-
- private void createChanges(IProgressMonitor pm) throws CoreException {
- try{
- pm.beginTask("", 12); //$NON-NLS-1$
- pm.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_creating_changes);
-
- if (fUpdateReferences)
- addReferenceUpdates(fChangeManager, new SubProgressMonitor(pm, 3));
-
- // Similar names updates have already been added.
-
- pm.worked(1);
-
- IResource resource= fType.getJavaScriptUnit().getResource();
- // if we have a linked resource then we don't use CU renaming
- // directly. So we have to update the code by ourselves.
- if ((resource != null && resource.isLinked()) || !willRenameCU()) {
- addTypeDeclarationUpdate(fChangeManager);
- pm.worked(1);
-
- addConstructorRenames(fChangeManager);
- pm.worked(1);
- } else {
- pm.worked(2);
- }
-
- if (fUpdateTextualMatches) {
- pm.subTask(RefactoringCoreMessages.RenameTypeRefactoring_searching_text);
- TextMatchUpdater.perform(new SubProgressMonitor(pm, 1), RefactoringScopeFactory.create(fType), this, fChangeManager, fReferences);
- if (fUpdateSimilarElements)
- addSimilarElementsTextualUpdates(fChangeManager, new SubProgressMonitor(pm, 3));
- }
-
- } finally{
- pm.done();
- }
- }
-
- private void addTypeDeclarationUpdate(TextChangeManager manager) throws CoreException {
- String name= RefactoringCoreMessages.RenameTypeRefactoring_update;
- int typeNameLength= fType.getElementName().length();
- IJavaScriptUnit cu= fType.getJavaScriptUnit();
- TextChangeCompatibility.addTextEdit(manager.get(cu), name, new ReplaceEdit(fType.getNameRange().getOffset(), typeNameLength, getNewElementName()));
- }
-
- private void addConstructorRenames(TextChangeManager manager) throws CoreException {
- IJavaScriptUnit cu= fType.getJavaScriptUnit();
- IFunction[] methods= fType.getFunctions();
- int typeNameLength= fType.getElementName().length();
- for (int i= 0; i < methods.length; i++){
- if (methods[i].isConstructor()) {
- /*
- * constructor declarations cannot be fully qualified so we can use simple replace here
- *
- * if (methods[i].getNameRange() == null), then it's a binary file so it's wrong anyway
- * (checked as a precondition)
- */
- String name= RefactoringCoreMessages.RenameTypeRefactoring_rename_constructor;
- TextChangeCompatibility.addTextEdit(manager.get(cu), name, new ReplaceEdit(methods[i].getNameRange().getOffset(), typeNameLength, getNewElementName()));
- }
- }
- }
-
- private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
- pm.beginTask("", fReferences.length); //$NON-NLS-1$
- for (int i= 0; i < fReferences.length; i++){
- IJavaScriptUnit cu= fReferences[i].getCompilationUnit();
- if (cu == null)
- continue;
-
- String name= RefactoringCoreMessages.RenameTypeRefactoring_update_reference;
- SearchMatch[] results= fReferences[i].getSearchResults();
-
- for (int j= 0; j < results.length; j++){
- SearchMatch match= results[j];
- ReplaceEdit replaceEdit= new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
- TextChangeCompatibility.addTextEdit(manager.get(cu), name, replaceEdit, CATEGORY_TYPE_RENAME);
- }
- pm.worked(1);
- }
- }
-
- private void computeQualifiedNameMatches(IProgressMonitor pm) throws CoreException {
- IPackageFragment fragment= fType.getPackageFragment();
- if (fQualifiedNameSearchResult == null)
- fQualifiedNameSearchResult= new QualifiedNameSearchResult();
- QualifiedNameFinder.process(fQualifiedNameSearchResult, fType.getFullyQualifiedName(),
- fragment.getElementName() + "." + getNewElementName(), //$NON-NLS-1$
- fFilePatterns, fType.getJavaScriptProject().getProject(), pm);
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.RENAME_TYPE);
- else
- fType= (IType) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- setNewElementName(name);
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String patterns= extended.getAttribute(ATTRIBUTE_PATTERNS);
- if (patterns != null && !"".equals(patterns)) //$NON-NLS-1$
- fFilePatterns= patterns;
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String matches= extended.getAttribute(ATTRIBUTE_TEXTUAL_MATCHES);
- if (matches != null) {
- fUpdateTextualMatches= Boolean.valueOf(matches).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TEXTUAL_MATCHES));
- final String qualified= extended.getAttribute(ATTRIBUTE_QUALIFIED);
- if (qualified != null) {
- fUpdateQualifiedNames= Boolean.valueOf(qualified).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_QUALIFIED));
- final String similarDeclarations= extended.getAttribute(ATTRIBUTE_SIMILAR_DECLARATIONS);
- if (similarDeclarations != null)
- fUpdateSimilarElements= Boolean.valueOf(similarDeclarations).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_SIMILAR_DECLARATIONS));
- final String similarDeclarationsMatchingStrategy= extended.getAttribute(ATTRIBUTE_MATCHING_STRATEGY);
- if (similarDeclarationsMatchingStrategy != null) {
- try {
- fRenamingStrategy= Integer.valueOf(similarDeclarationsMatchingStrategy).intValue();
- } catch (NumberFormatException e) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] {similarDeclarationsMatchingStrategy, ATTRIBUTE_QUALIFIED}));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MATCHING_STRATEGY));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- // --------- Similar names
-
- /**
- * Creates and initializes the refactoring processors for similarly named elements
- * @param progressMonitor
- * @param context
- * @return status
- * @throws CoreException
- */
- private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
-
- Assert.isNotNull(fPreloadedElementToName);
- Assert.isNotNull(fPreloadedElementToSelection);
-
- final RefactoringStatus status= new RefactoringStatus();
- final Set handledTopLevelMethods= new HashSet();
- final Set warnings= new HashSet();
- final List processors= new ArrayList();
- fFinalSimilarElementToName= new HashMap();
-
- JavaScriptUnit currentResolvedCU= null;
- IJavaScriptUnit currentCU= null;
-
- int current= 0;
- final int max= fPreloadedElementToName.size();
-
- progressMonitor.beginTask("", max * 3); //$NON-NLS-1$
- progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
-
- for (Iterator iter= fPreloadedElementToName.keySet().iterator(); iter.hasNext();) {
-
- final IJavaScriptElement element= (IJavaScriptElement) iter.next();
-
- current++;
- progressMonitor.worked(3);
-
- // not selected? -> skip
- if (! ((Boolean) (fPreloadedElementToSelection.get(element))).booleanValue())
- continue;
-
- // already registered? (may happen with overridden methods) -> skip
- if (fFinalSimilarElementToName.containsKey(element))
- continue;
-
- // JavaScriptUnit changed? (note: fPreloadedElementToName is sorted by JavaScriptUnit)
- IJavaScriptUnit newCU= (IJavaScriptUnit) element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
-
- if (!newCU.equals(currentCU)) {
-
- checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
-
- if (status.hasFatalError())
- return status;
-
- // reset values
- currentResolvedCU= null;
- currentCU= newCU;
- processors.clear();
- }
-
- final String newName= (String) fPreloadedElementToName.get(element);
- RefactoringProcessor processor= null;
-
- if (element instanceof ILocalVariable) {
- final ILocalVariable currentLocal= (ILocalVariable) element;
-
- if (currentResolvedCU == null)
- currentResolvedCU= new RefactoringASTParser(AST.JLS3).parse(currentCU, true);
-
- processor= createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
-
- // don't check for conflicting rename => is done by #checkCUCompleteConditions().
-
- if (status.hasFatalError())
- return status;
- fFinalSimilarElementToName.put(currentLocal, newName);
- }
- if (element instanceof IField) {
- final IField currentField= (IField) element;
- processor= createFieldRenameProcessor(currentField, newName);
-
- status.merge(checkForConflictingRename(currentField, newName));
- if (status.hasFatalError())
- return status;
- fFinalSimilarElementToName.put(currentField, newName);
- }
- if (element instanceof IFunction) {
- IFunction currentMethod= (IFunction) element;
- if (MethodChecks.isVirtual(currentMethod)) {
-
- final IType declaringType= currentMethod.getDeclaringType();
- ITypeHierarchy hierarchy= null;
- hierarchy= declaringType.newTypeHierarchy(new NullProgressMonitor());
-
- final IFunction topmost= MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
- if (topmost != null)
- currentMethod= topmost;
- if (handledTopLevelMethods.contains(currentMethod))
- continue;
- handledTopLevelMethods.add(currentMethod);
- final IFunction[] ripples= MethodChecks.getOverriddenMethods(currentMethod, new NullProgressMonitor());
-
- if (checkForWarnings(warnings, newName, ripples))
- continue;
-
- status.merge(checkForConflictingRename(ripples, newName));
- if (status.hasFatalError())
- return status;
-
- processor= createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
- fFinalSimilarElementToName.put(currentMethod, newName);
- for (int i= 0; i < ripples.length; i++) {
- fFinalSimilarElementToName.put(ripples[i], newName);
- }
- } else {
-
- status.merge(checkForConflictingRename(new IFunction[] { currentMethod }, newName));
- if (status.hasFatalError())
- break;
-
- fFinalSimilarElementToName.put(currentMethod, newName);
-
- processor= createNonVirtualMethodRenameProcessor(currentMethod, newName);
- }
- }
-
- progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max)}));
-
- status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
-
- if (status.hasFatalError())
- return status;
-
- status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
-
- if (status.hasFatalError())
- return status;
-
- processors.add(processor);
-
- progressMonitor.worked(1);
-
- if (progressMonitor.isCanceled())
- throw new OperationCanceledException();
- }
-
- // check last CU
- checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
-
- status.merge(addWarnings(warnings));
-
- progressMonitor.done();
- return status;
- }
-
- private void checkCUCompleteConditions(final RefactoringStatus status, JavaScriptUnit currentResolvedCU, IJavaScriptUnit currentCU, List processors) throws CoreException {
-
- // check local variable conditions
- List locals= getProcessorsOfType(processors, RenameLocalVariableProcessor.class);
- if (!locals.isEmpty()) {
- RenameAnalyzeUtil.LocalAnalyzePackage[] analyzePackages= new RenameAnalyzeUtil.LocalAnalyzePackage[locals.size()];
- TextChangeManager manager= new TextChangeManager();
- int current= 0;
- TextChange textChange= manager.get(currentCU);
- textChange.setKeepPreviewEdits(true);
- for (Iterator iterator= locals.iterator(); iterator.hasNext();) {
- RenameLocalVariableProcessor localProcessor= (RenameLocalVariableProcessor) iterator.next();
- RenameAnalyzeUtil.LocalAnalyzePackage analyzePackage= localProcessor.getLocalAnalyzePackage();
- analyzePackages[current]= analyzePackage;
- for (int i= 0; i < analyzePackage.fOccurenceEdits.length; i++) {
- TextChangeCompatibility.addTextEdit(textChange, "", analyzePackage.fOccurenceEdits[i], GroupCategorySet.NONE); //$NON-NLS-1$
- }
- current++;
- }
- status.merge(RenameAnalyzeUtil.analyzeLocalRenames(analyzePackages, textChange, currentResolvedCU, false));
- }
-
- /*
- * There is room for performance improvement here: One could move
- * shadowing analyzes out of the field and method processors and perform
- * it here, thus saving on working copy creation. Drawback is increased
- * heap consumption.
- */
- }
-
- private List getProcessorsOfType(List processors, Class type) {
- List tmp= new ArrayList();
- for (Iterator iter= processors.iterator(); iter.hasNext();) {
- RefactoringProcessor element= (RefactoringProcessor) iter.next();
- if (element.getClass().equals(type))
- tmp.add(element);
- }
- return tmp;
- }
-
- // ------------------ Error checking -------------
-
- /**
- * Checks whether one of the given methods, which will all be renamed to
- * "newName", shares a type with another already registered method which is
- * renamed to the same new name and shares the same parameters.
- * @param methods
- * @param newName
- * @return status
- *
- * @see #checkForConflictingRename(IField, String)
- */
- private RefactoringStatus checkForConflictingRename(IFunction[] methods, String newName) {
- RefactoringStatus status= new RefactoringStatus();
- for (Iterator iter= fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- if (element instanceof IFunction) {
- IFunction alreadyRegisteredMethod= (IFunction) element;
- String alreadyRegisteredMethodName= (String) fFinalSimilarElementToName.get(element);
- for (int i= 0; i < methods.length; i++) {
- IFunction method2= methods[i];
- if ( (alreadyRegisteredMethodName.equals(newName)) && (method2.getDeclaringType().equals(alreadyRegisteredMethod.getDeclaringType()))
- && (sameParams(alreadyRegisteredMethod, method2))) {
- String message= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_cannot_rename_methods_same_new_name, new String[] { alreadyRegisteredMethod.getElementName(),
- method2.getElementName(), alreadyRegisteredMethod.getDeclaringType().getFullyQualifiedName(), newName });
- status.addFatalError(message);
- return status;
- }
- }
- }
- }
- return status;
- }
-
- private static boolean sameParams(IFunction method, IFunction method2) {
-
- if (method.getNumberOfParameters() != method2.getNumberOfParameters())
- return false;
-
- String[] params= method.getParameterTypes();
- String[] params2= method2.getParameterTypes();
-
- for (int i= 0; i < params.length; i++) {
- String t1= Signature.getSimpleName(Signature.toString(params[i]));
- String t2= Signature.getSimpleName(Signature.toString(params2[i]));
- if (!t1.equals(t2)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * If suffix matching is enabled, the refactoring may suggest two fields to
- * have the same name which reside in the same type. Same thing may also
- * happen if the user makes poor choices for the field names.
- *
- * Consider: FooBarThing fFooBarThing; FooBarThing fBarThing;
- *
- * Rename "FooBarThing" to "DifferentHunk". Suggestion for both fields is
- * "fDifferentHunk" (and rightly so).
- * @param currentField
- * @param newName
- * @return status
- */
- private RefactoringStatus checkForConflictingRename(IField currentField, String newName) {
- RefactoringStatus status= new RefactoringStatus();
- for (Iterator iter= fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- if (element instanceof IField) {
- IField alreadyRegisteredField= (IField) element;
- String alreadyRegisteredFieldName= (String) fFinalSimilarElementToName.get(element);
- if (alreadyRegisteredFieldName.equals(newName)) {
- if (alreadyRegisteredField.getDeclaringType().equals(currentField.getDeclaringType())) {
-
- String message= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_cannot_rename_fields_same_new_name, new String[] { alreadyRegisteredField.getElementName(),
- currentField.getElementName(), alreadyRegisteredField.getDeclaringType().getFullyQualifiedName(), newName });
- status.addFatalError(message);
- return status;
- }
- }
- }
- }
- return status;
- }
-
- private RefactoringStatus addWarnings(final Set warnings) {
- RefactoringStatus status= new RefactoringStatus();
-
- // Remove deleted ripple methods from user selection and add warnings
- for (Iterator iter= warnings.iterator(); iter.hasNext();) {
- final Warning warning= (Warning) iter.next();
- final IFunction[] elements= warning.getRipple();
- if (warning.isSelectionWarning()) {
- String message= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_deselected_method_is_overridden,
- new String[] { JavaScriptElementLabels.getElementLabel(elements[0], JavaScriptElementLabels.ALL_DEFAULT),
- JavaScriptElementLabels.getElementLabel(elements[0].getDeclaringType(), JavaScriptElementLabels.ALL_DEFAULT) });
- status.addWarning(message);
- }
- if (warning.isNameWarning()) {
- String message= Messages.format(
- RefactoringCoreMessages.RenameTypeProcessor_renamed_method_is_overridden, new String[] {
- JavaScriptElementLabels.getElementLabel(elements[0], JavaScriptElementLabels.ALL_DEFAULT),
- JavaScriptElementLabels.getElementLabel(elements[0].getDeclaringType(), JavaScriptElementLabels.ALL_DEFAULT) });
- status.addWarning(message);
- }
- for (int i= 0; i < elements.length; i++)
- fPreloadedElementToSelection.put(elements[i], Boolean.FALSE);
- }
- return status;
- }
-
- /*
- * If one of the methods of this ripple was deselected or renamed by
- * the user, deselect the whole chain and add warnings.
- */
- private boolean checkForWarnings(final Set warnings, final String newName, final IFunction[] ripples) {
-
- boolean addSelectionWarning= false;
- boolean addNameWarning= false;
- for (int i= 0; i < ripples.length; i++) {
- String newNameOfRipple= (String) fPreloadedElementToName.get(ripples[i]);
- Boolean selected= (Boolean) fPreloadedElementToSelection.get(ripples[i]);
-
- // selected may be null here due to supermethods like
- // setSomeClass(Object class) (subsignature match)
- // Don't add a warning.
- if (selected == null)
- continue;
-
- if (!selected.booleanValue())
- addSelectionWarning= true;
-
- if (!newName.equals(newNameOfRipple))
- addNameWarning= true;
- }
- if (addSelectionWarning || addNameWarning)
- warnings.add(new Warning(ripples, addSelectionWarning, addNameWarning));
-
- return (addSelectionWarning || addNameWarning);
- }
-
- private class Warning {
-
- private IFunction[] fRipple;
- private boolean fSelectionWarning;
- private boolean fNameWarning;
-
- public Warning(IFunction[] ripple, boolean isSelectionWarning, boolean isNameWarning) {
- fRipple= ripple;
- fSelectionWarning= isSelectionWarning;
- fNameWarning= isNameWarning;
- }
-
- public boolean isNameWarning() {
- return fNameWarning;
- }
-
- public IFunction[] getRipple() {
- return fRipple;
- }
-
- public boolean isSelectionWarning() {
- return fSelectionWarning;
- }
- }
-
- // ----------------- Processor creation --------
-
- private RenameMethodProcessor createVirtualMethodRenameProcessor(IFunction currentMethod, String newMethodName, IFunction[] ripples, ITypeHierarchy hierarchy) throws JavaScriptModelException {
- RenameMethodProcessor processor= new RenameVirtualMethodProcessor(currentMethod, ripples, fChangeManager, hierarchy, CATEGORY_METHOD_RENAME);
- initMethodProcessor(processor, newMethodName);
- return processor;
- }
-
- private RenameMethodProcessor createNonVirtualMethodRenameProcessor(IFunction currentMethod, String newMethodName) {
- RenameMethodProcessor processor= new RenameNonVirtualMethodProcessor(currentMethod, fChangeManager, CATEGORY_METHOD_RENAME);
- initMethodProcessor(processor, newMethodName);
- return processor;
- }
-
- private void initMethodProcessor(RenameMethodProcessor processor, String newMethodName) {
- processor.setNewElementName(newMethodName);
- processor.setUpdateReferences(getUpdateReferences());
- }
-
- private RenameFieldProcessor createFieldRenameProcessor(final IField field, final String newName) {
- final RenameFieldProcessor processor= new RenameFieldProcessor(field, fChangeManager, CATEGORY_FIELD_RENAME);
- processor.setNewElementName(newName);
- processor.setRenameGetter(false);
- processor.setRenameSetter(false);
- processor.setUpdateReferences(getUpdateReferences());
- processor.setUpdateTextualMatches(false);
- return processor;
- }
-
- private RenameLocalVariableProcessor createLocalRenameProcessor(final ILocalVariable local, final String newName, final JavaScriptUnit compilationUnit) {
- final RenameLocalVariableProcessor processor= new RenameLocalVariableProcessor(local, fChangeManager, compilationUnit, CATEGORY_LOCAL_RENAME);
- processor.setNewElementName(newName);
- processor.setUpdateReferences(getUpdateReferences());
- return processor;
- }
-
- // ----------- Edit creation -----------
-
-
- /**
- * Updates textual matches for fields.
- *
- * Strategy for matching text matches: Match and replace all fully qualified
- * field names, but non-qualified field names only iff there are no fields
- * which have the same original, but a different new name. Don't add java
- * references; duplicate edits may be created but do not matter.
- * @param manager
- * @param monitor
- * @throws CoreException
- */
- private void addSimilarElementsTextualUpdates(TextChangeManager manager, IProgressMonitor monitor) throws CoreException {
-
- final Map simpleNames= new HashMap();
- final List forbiddenSimpleNames= new ArrayList();
-
- for (Iterator iter= fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
- final IJavaScriptElement element= (IJavaScriptElement) iter.next();
- if (element instanceof IField) {
-
- if (forbiddenSimpleNames.contains(element.getElementName()))
- continue;
-
- final String registeredNewName= (String) simpleNames.get(element.getElementName());
- final String newNameToCheck= (String) fFinalSimilarElementToName.get(element);
- if (registeredNewName == null)
- simpleNames.put(element.getElementName(), newNameToCheck);
- else if (!registeredNewName.equals(newNameToCheck))
- forbiddenSimpleNames.add(element.getElementName());
- }
- }
-
- for (Iterator iter= fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
- final IJavaScriptElement element= (IJavaScriptElement) iter.next();
- if (element instanceof IField) {
- final IField field= (IField) element;
- final String newName= (String) fFinalSimilarElementToName.get(field);
- TextMatchUpdater.perform(monitor, RefactoringScopeFactory.create(field), field.getElementName(), field.getDeclaringType().getFullyQualifiedName(), newName, manager,
- new SearchResultGroup[0], forbiddenSimpleNames.contains(field.getElementName()));
- }
- }
- }
-
- // ------ UI interaction
-
- /**
- * @return the map of similarly named elements (IJavaScriptElement -> String with new name)
- * This map is live. Callers may change the new names of the elements; they
- * may not change the key set.
- */
- public Map/* <IJavaScriptElement, String> */getSimilarElementsToNewNames() {
- return fPreloadedElementToName;
- }
-
- /**
- * @return the map of similarly named elements (IJavaScriptElement -> Boolean if selected) This
- * map is live. Callers may change the selection status of the elements;
- * they may not change the key set.
- */
- public Map/* <IJavaScriptElement, Boolean> */getSimilarElementsToSelection() {
- return fPreloadedElementToSelection;
- }
-
- /**
- * Resets the element maps back to the original status. This affects the
- * maps returned in {@link #getSimilarElementsToNewNames() } and
- * {@link #getSimilarElementsToSelection() }. All new names are reset to
- * the calculated ones and every element gets selected.
- */
- public void resetSelectedSimilarElements() {
- Assert.isNotNull(fPreloadedElementToName);
- for (Iterator iter= fPreloadedElementToNameDefault.keySet().iterator(); iter.hasNext();) {
- final IJavaScriptElement element= (IJavaScriptElement) iter.next();
- fPreloadedElementToName.put(element, fPreloadedElementToNameDefault.get(element));
- fPreloadedElementToSelection.put(element, Boolean.TRUE);
- }
- }
-
- /**
- * @return true iff the "update similarly named elements" flag is set AND the
- * search yielded some elements to be renamed.
- */
- public boolean hasSimilarElementsToRename() {
- if (!fUpdateSimilarElements)
- return false;
- if (fPreloadedElementToName == null)
- return false;
- if (fPreloadedElementToName.size() == 0)
- return false;
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameVirtualMethodProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameVirtualMethodProcessor.java
deleted file mode 100644
index 1f03e0f8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameVirtualMethodProcessor.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-
-public class RenameVirtualMethodProcessor extends RenameMethodProcessor {
-
- private IFunction fOriginalMethod;
- private boolean fActivationChecked;
- private ITypeHierarchy fCachedHierarchy= null;
-
- /**
- * Creates a new rename method processor.
- * @param method the method, or <code>null</code> if invoked by scripting
- */
- public RenameVirtualMethodProcessor(IFunction method) {
- super(method);
- fOriginalMethod= getMethod();
- }
-
- /*
- * int. not javadoc'd
- *
- * Protected constructor; only called from RenameTypeProcessor. Initializes
- * the method processor with an already resolved top level and ripple
- * methods.
- *
- */
- RenameVirtualMethodProcessor(IFunction topLevel, IFunction[] ripples, TextChangeManager changeManager, ITypeHierarchy hierarchy, GroupCategorySet categorySet) {
- super(topLevel, changeManager, categorySet);
- fOriginalMethod= getMethod();
- fActivationChecked= true; // is top level
- fCachedHierarchy= hierarchy; // may be null
- setMethodsToRename(ripples);
- }
-
- public IFunction getOriginalMethod() {
- return fOriginalMethod;
- }
-
- private ITypeHierarchy getCachedHierarchy(IType declaring, IProgressMonitor monitor) throws JavaScriptModelException {
- if (fCachedHierarchy != null && declaring.equals(fCachedHierarchy.getType()))
- return fCachedHierarchy;
- fCachedHierarchy= declaring.newTypeHierarchy(new SubProgressMonitor(monitor, 1));
- return fCachedHierarchy;
- }
-
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isRenameVirtualMethodAvailable(getMethod());
- }
-
- //------------ preconditions -------------
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException {
- RefactoringStatus result= super.checkInitialConditions(monitor);
- if (result.hasFatalError())
- return result;
- try{
- monitor.beginTask("", 3); //$NON-NLS-1$
- if (!fActivationChecked) {
- // the following code may change the method to be changed.
- IFunction method= getMethod();
- fOriginalMethod= method;
-
- ITypeHierarchy hierarchy= null;
- IType declaringType= method.getDeclaringType();
- if (declaringType!=null)
- hierarchy= getCachedHierarchy(declaringType, new SubProgressMonitor(monitor, 1));
-
- IFunction topmost= getMethod();
- if (MethodChecks.isVirtual(topmost))
- topmost= MethodChecks.getTopmostMethod(getMethod(), hierarchy, monitor);
- if (topmost != null)
- initialize(topmost);
- fActivationChecked= true;
- }
- } finally{
- monitor.done();
- }
- return result;
- }
-
- protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext checkContext) throws CoreException {
- try{
- pm.beginTask("", 9); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
-
- result.merge(super.doCheckFinalConditions(new SubProgressMonitor(pm, 7), checkContext));
- if (result.hasFatalError())
- return result;
-
- final IFunction method= getMethod();
- final IType declaring= method.getDeclaringType();
- final ITypeHierarchy hierarchy= getCachedHierarchy(declaring, new SubProgressMonitor(pm, 1));
- final String name= getNewElementName();
-
- IFunction[] hierarchyMethods= hierarchyDeclaresMethodName(new SubProgressMonitor(pm, 1), hierarchy, method, name);
- for (int i= 0; i < hierarchyMethods.length; i++) {
- IFunction hierarchyMethod= hierarchyMethods[i];
- RefactoringStatusContext context= JavaStatusContext.create(hierarchyMethod);
- if (Checks.compareParamTypes(method.getParameterTypes(), hierarchyMethod.getParameterTypes())) {
- result.addError(Messages.format(
- RefactoringCoreMessages.RenameVirtualMethodRefactoring_hierarchy_declares2,
- name), context);
- } else {
- result.addWarning(Messages.format(
- RefactoringCoreMessages.RenameVirtualMethodRefactoring_hierarchy_declares1,
- name), context);
- }
- }
-
- fCachedHierarchy= null;
- return result;
- } finally{
- pm.done();
- }
- }
-
- //---- Interface checks -------------------------------------
-
- private IFunction[] relatedTypeDeclaresMethodName(IProgressMonitor pm, IFunction method, String newName) throws CoreException {
- try{
- Set result= new HashSet();
- Set types= getRelatedTypes();
- pm.beginTask("", types.size()); //$NON-NLS-1$
- for (Iterator iter= types.iterator(); iter.hasNext(); ) {
- final IFunction found= Checks.findMethod(method, (IType)iter.next());
- final IType declaring= found.getDeclaringType();
- result.addAll(Arrays.asList(hierarchyDeclaresMethodName(new SubProgressMonitor(pm, 1), declaring.newTypeHierarchy(new SubProgressMonitor(pm, 1)), found, newName)));
- }
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- } finally {
- pm.done();
- }
- }
-
- private boolean isSpecialCase() throws CoreException {
- String[] noParams= new String[0];
- String[] specialNames= new String[]{"toString", "toString", "toString", "toString", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "getClass", "getClass", "notify", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "notifyAll", "wait"}; //$NON-NLS-2$ //$NON-NLS-1$
- String[][] specialParamTypes= new String[][]{noParams, noParams, noParams, noParams,
- noParams, noParams, //$NON-NLS-2$ //$NON-NLS-1$
- noParams, noParams, noParams};
- String[] specialReturnTypes= new String[]{"QString;", "QString;", "Qjava.lang.String;", "Qjava.lang.String;", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "QClass;", "Qjava.lang.Class;", //$NON-NLS-2$ //$NON-NLS-1$
- Signature.SIG_VOID, Signature.SIG_VOID, Signature.SIG_VOID};
- Assert.isTrue((specialNames.length == specialParamTypes.length) && (specialParamTypes.length == specialReturnTypes.length));
- for (int i= 0; i < specialNames.length; i++){
- if (specialNames[i].equals(getNewElementName())
- && Checks.compareParamTypes(getMethod().getParameterTypes(), specialParamTypes[i])
- && !specialReturnTypes[i].equals(getMethod().getReturnType())){
- return true;
- }
- }
- return false;
- }
-
- private Set getRelatedTypes() {
- Set methods= getMethodsToRename();
- Set result= new HashSet(methods.size());
- for (Iterator iter= methods.iterator(); iter.hasNext(); ){
- result.add(((IFunction)iter.next()).getDeclaringType());
- }
- return result;
- }
-
- //---- Class checks -------------------------------------
-
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- final RefactoringStatus status= super.initialize(arguments);
- fOriginalMethod= getMethod();
- return status;
- }
-
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_renamed_plural;
- else
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_renamed_singular;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamingNameSuggestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamingNameSuggestor.java
deleted file mode 100644
index ee860b92..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenamingNameSuggestor.java
+++ /dev/null
@@ -1,570 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordIterator;
-
-import com.ibm.icu.text.BreakIterator;
-
-/**
- * This class contains methods for suggesting new names for variables or methods
- * whose name consists at least partly of the name of their declaring type (or
- * in case of methods, the return type or a parameter type).
- *
- * The methods return the newly suggested method or variable name in case of a
- * match, or null in case nothing matched.
- *
- * In any case, prefixes and suffixes are removed from variable names. As method
- * names have no configurable suffixes or prefixes, they are left unchanged. The
- * remaining name is called "stripped element name".
- *
- * After the match according to the strategy, prefixes and suffixes are
- * reapplied to the names.
- *
- * EXACT STRATEGY (always performed).
- * ----------------------------------------------------------------
- *
- * The stripped element name is directly compared with the type name:
- *
- * a) the first character must match case-insensitive
- *
- * b) all other characters must match case-sensitive
- *
- * In case of a match, the new type name is returned (first character adapted,
- * respectively). Suffixes/Prefixes are reapplied.
- *
- * Note that this also matches fields with names like "SomeField", "fsomeField",
- * and method names like "JavaElement()".
- *
- * EMBEDDED STRATEGY (performed second if chosen by user).
- * ----------------------------------------------------------------
- *
- * A search is performed in the stripped element name for the old type name:
- *
- * a) the first character must match case-insensitive
- *
- * b) all other characters must match case-sensitive
- *
- * c) the stripped element name must end after the type name, or the next
- * character must be a non-letter, or the next character must be upper cased.
- *
- * In case of a match, the new type is inserted into the stripped element name,
- * replacing the old type name, first character adapted to the correct case.
- * Suffixes/Prefixes are reapplied.
- *
- * Note that this also matches methods with names like "createjavaElement()" or
- * fields like "fjavaElementCache".
- *
- * SUFFIX STRATEGY (performed third if chosen by user)
- * ----------------------------------------------------------------
- *
- * The new and old type names are analyzed for "camel case suffixes", that is,
- * substrings which begin with an uppercased letter. For example,
- * "SimpleJavaElement" is split into the three hunks "Simple",
- * "Java", and "Element". If one type name has more suffixes than the
- * other, both are stripped to the smaller size.
- *
- * Then, a search is performed in the stripped variable name hunks from back to
- * front. At least the last hunk must be found, others may then extend the match.
- * Each hunk must match like in the exact strategy, i.e.
- *
- * a) the first character must match case-insensitive
- *
- * b) all other characters must match case-sensitive
- *
- * In case of a match, the matched hunks of the new type replace
- * the hunks of the old type. Suffixes/Prefixes are reapplied.
- *
- * Note that numbers and other non-letter characters belong to the previous
- * camel case substring.
- *
- *
- *
- *
- */
-public class RenamingNameSuggestor {
-
- /*
- * ADDITIONAL OPTIONS
- * ----------------------------------------------------------------
- *
- * There are two additional flags which may be set in this class to allow
- * better matching of special cases:
- *
- * a) Special treatment of leading "I"s in type names, i.e. interface names
- * like "IJavaScriptElement". If the corresponding flag is set, leading "I"s are
- * stripped from type names if the second char is also uppercase to allow
- * exact matching of variable names like "javaElement" for type
- * "IJavaScriptElement". Note that embedded matching already matches cases like
- * this.
- *
- * b) Special treatment of all-uppercase type names or all-uppercase type
- * name camel-case hunks, i.e. names like "AST" or "PersonalURL". If the
- * corresponding flag is set, the type name hunks will be transformed such
- * that variables like "fAst", "ast", "personalUrl", or "url" are found as
- * well. The target name will be transformed too if it is an
- * all-uppercase type name camel-case hunk as well.
- *
- * NOTE that in exact or embedded mode, the whole type name must be
- * all-uppercase to allow matching custom-lowercased variable names, i.e.
- * there are no attempts to "guess" which hunk of the new name should be lowercased
- * to match a partly lowercased variable name. In suffix mode, hunks of the
- * new type which are at the same position as in the old type will be
- * lowercased if necessary.
- *
- * c) Support for (english) plural forms. If the corresponding flag is set, the
- * suggestor will try to match variables which have plural forms of the
- * type name, for example "handies" for "Handy" or "phones" for "MobilePhone".
- * The target name will be transformed as well, i.e. conversion like
- * "fHandies" -> "fPhones" are supported.
- *
- */
-
- public static final int STRATEGY_EXACT= 1;
- public static final int STRATEGY_EMBEDDED= 2;
- public static final int STRATEGY_SUFFIX= 3;
-
- private static final String PLURAL_S= "s"; //$NON-NLS-1$
- private static final String PLURAL_IES= "ies"; //$NON-NLS-1$
- private static final String SINGULAR_Y= "y"; //$NON-NLS-1$
-
- private int fStrategy;
- private String[] fFieldPrefixes;
- private String[] fFieldSuffixes;
- private String[] fStaticFieldPrefixes;
- private String[] fStaticFieldSuffixes;
- private String[] fLocalPrefixes;
- private String[] fLocalSuffixes;
- private String[] fArgumentPrefixes;
- private String[] fArgumentSuffixes;
-
- private boolean fExtendedInterfaceNameMatching;
- private boolean fExtendedAllUpperCaseHunkMatching;
- private boolean fExtendedPluralMatching;
-
- public RenamingNameSuggestor() {
- this(STRATEGY_SUFFIX);
- }
-
- public RenamingNameSuggestor(int strategy) {
-
- Assert.isTrue(strategy >= 1 && strategy <= 3);
-
- fStrategy= strategy;
- fExtendedInterfaceNameMatching= true;
- fExtendedAllUpperCaseHunkMatching= true;
- fExtendedPluralMatching= true;
-
- resetPrefixes();
- }
-
- public String suggestNewFieldName(IJavaScriptProject project, String oldFieldName, boolean isStatic, String oldTypeName, String newTypeName) {
-
- initializePrefixesAndSuffixes(project);
-
- if (isStatic)
- return suggestNewVariableName(fStaticFieldPrefixes, fStaticFieldSuffixes, oldFieldName, oldTypeName, newTypeName);
- else
- return suggestNewVariableName(fFieldPrefixes, fFieldSuffixes, oldFieldName, oldTypeName, newTypeName);
- }
-
- public String suggestNewLocalName(IJavaScriptProject project, String oldLocalName, boolean isArgument, String oldTypeName, String newTypeName) {
-
- initializePrefixesAndSuffixes(project);
-
- if (isArgument)
- return suggestNewVariableName(fArgumentPrefixes, fArgumentSuffixes, oldLocalName, oldTypeName, newTypeName);
- else
- return suggestNewVariableName(fLocalPrefixes, fLocalSuffixes, oldLocalName, oldTypeName, newTypeName);
- }
-
- public String suggestNewMethodName(String oldMethodName, String oldTypeName, String newTypeName) {
-
- Assert.isNotNull(oldMethodName);
- Assert.isNotNull(oldTypeName);
- Assert.isNotNull(newTypeName);
- Assert.isTrue(oldMethodName.length() > 0);
- Assert.isTrue(oldTypeName.length() > 0);
- Assert.isTrue(newTypeName.length() > 0);
-
- resetPrefixes();
-
- return match(oldTypeName, newTypeName, oldMethodName);
- }
-
- public String suggestNewVariableName(String[] prefixes, String[] suffixes, String oldVariableName, String oldTypeName, String newTypeName) {
-
- Assert.isNotNull(prefixes);
- Assert.isNotNull(suffixes);
- Assert.isNotNull(oldVariableName);
- Assert.isNotNull(oldTypeName);
- Assert.isNotNull(newTypeName);
- Assert.isTrue(oldVariableName.length() > 0);
- Assert.isTrue(oldTypeName.length() > 0);
- Assert.isTrue(newTypeName.length() > 0);
-
- final String usedPrefix= findLongestPrefix(oldVariableName, prefixes);
- final String usedSuffix= findLongestSuffix(oldVariableName, suffixes);
- final String strippedVariableName= oldVariableName.substring(usedPrefix.length(), oldVariableName.length() - usedSuffix.length());
-
- String newVariableName= match(oldTypeName, newTypeName, strippedVariableName);
- return (newVariableName != null) ? usedPrefix + newVariableName + usedSuffix : null;
- }
-
- // -------------------------------------- Match methods
-
- private String match(final String oldTypeName, final String newTypeName, final String strippedVariableName) {
-
- String oldType= oldTypeName;
- String newType= newTypeName;
-
- if (fExtendedInterfaceNameMatching && isInterfaceName(oldType) && isInterfaceName(newType)) {
- oldType= getInterfaceName(oldType);
- newType= getInterfaceName(newType);
- }
-
- String newVariableName= matchDirect(oldType, newType, strippedVariableName);
-
- if (fExtendedPluralMatching && newVariableName == null && canPluralize(oldType))
- newVariableName= matchDirect(pluralize(oldType), pluralize(newType), strippedVariableName);
-
- return newVariableName;
- }
-
- private String matchDirect(String oldType, String newType, final String strippedVariableName) {
- /*
- * Use all strategies applied by the user. Always start with exact
- * matching.
- *
- * Note that suffix matching may not match the whole type name if the
- * new type name has a smaller camel case chunk count.
- */
-
- String newVariableName= exactMatch(oldType, newType, strippedVariableName);
- if (newVariableName == null && fStrategy >= STRATEGY_EMBEDDED)
- newVariableName= embeddedMatch(oldType, newType, strippedVariableName);
- if (newVariableName == null && fStrategy >= STRATEGY_SUFFIX)
- newVariableName= suffixMatch(oldType, newType, strippedVariableName);
-
- return newVariableName;
- }
-
- private String exactMatch(final String oldTypeName, final String newTypeName, final String strippedVariableName) {
-
- String newName= exactDirectMatch(oldTypeName, newTypeName, strippedVariableName);
- if (newName != null)
- return newName;
-
- if (fExtendedAllUpperCaseHunkMatching && isUpperCaseCamelCaseHunk(oldTypeName)) {
- String oldTN= getFirstUpperRestLowerCased(oldTypeName);
- String newTN= isUpperCaseCamelCaseHunk(newTypeName) ? getFirstUpperRestLowerCased(newTypeName) : newTypeName;
- newName= exactDirectMatch(oldTN, newTN, strippedVariableName);
- }
-
- return newName;
- }
-
- private String exactDirectMatch(final String oldTypeName, final String newTypeName, final String strippedVariableName) {
-
- if (strippedVariableName.equals(oldTypeName))
- return newTypeName;
-
- if (strippedVariableName.equals(getLowerCased(oldTypeName)))
- return getLowerCased(newTypeName);
-
- return null;
- }
-
- private String embeddedMatch(String oldTypeName, String newTypeName, String strippedVariableName) {
-
- // possibility of a match?
- final String lowerCaseVariable= strippedVariableName.toLowerCase();
- final String lowerCaseOldTypeName= oldTypeName.toLowerCase();
- int presumedIndex= lowerCaseVariable.indexOf(lowerCaseOldTypeName);
-
- while (presumedIndex != -1) {
- // it may be there
- final String presumedTypeName= strippedVariableName.substring(presumedIndex, presumedIndex + oldTypeName.length());
- final String prefix= strippedVariableName.substring(0, presumedIndex);
- final String suffix= strippedVariableName.substring(presumedIndex + oldTypeName.length());
-
- // can match at all? (depends on suffix)
- if (startsNewHunk(suffix)) {
-
- String name= exactMatch(oldTypeName, newTypeName, presumedTypeName);
- if (name != null)
- return prefix + name + suffix;
- }
-
- // did not match -> find next occurrence
- presumedIndex= lowerCaseVariable.indexOf(lowerCaseOldTypeName, presumedIndex + 1);
- }
-
- return null;
- }
-
- private String suffixMatch(final String oldType, final String newType, final String strippedVariableName) {
-
- // get an array of all camel-cased elements from both types + the
- // variable
- String[] suffixesOld= getSuffixes(oldType);
- String[] suffixesNew= getSuffixes(newType);
- String[] suffixesVar= getSuffixes(strippedVariableName);
-
- // get an equal-sized array of the last n camel-cased elements
- int min= Math.min(suffixesOld.length, suffixesNew.length);
- String[] suffixesOldEqual= new String[min];
- String[] suffixesNewEqual= new String[min];
- System.arraycopy(suffixesOld, suffixesOld.length - min, suffixesOldEqual, 0, min);
- System.arraycopy(suffixesNew, suffixesNew.length - min, suffixesNewEqual, 0, min);
-
- // find endIndex. endIndex is the index of the last hunk of the old type
- // name in the variable name.
- int endIndex= -1;
- for (int j= suffixesVar.length - 1; j >= 0; j--) {
- String newHunkName= exactMatch(suffixesOldEqual[suffixesOldEqual.length - 1], suffixesNewEqual[suffixesNewEqual.length - 1], suffixesVar[j]);
- if (newHunkName != null) {
- endIndex= j;
- break;
- }
- }
-
- if (endIndex == -1)
- return null; // last hunk not found -> no match
-
- int stepBack= 0;
- int lastSuffixMatched= -1;
- int hunkInVarName= -1;
- for (int i= suffixesOldEqual.length - 1; i >= 0; i--) {
-
- hunkInVarName= endIndex - stepBack;
- stepBack++;
-
- if (hunkInVarName < 0) {
- // we have reached the beginning of the variable name
- break;
- }
-
- // try to match this hunk:
- String newHunkName= exactMatch(suffixesOldEqual[i], suffixesNewEqual[i], suffixesVar[hunkInVarName]);
-
- if (newHunkName == null)
- break; // only match complete suffixes
-
- suffixesVar[hunkInVarName]= newHunkName;
- lastSuffixMatched= i;
- }
-
- if (lastSuffixMatched == 0) {
- // we have matched ALL type hunks in the variable name,
- // insert any new prefixes of the new type name
- int newPrefixes= suffixesNew.length - suffixesNewEqual.length;
- if (newPrefixes > 0) {
-
- // Propagate lowercased start to the front
- if (Character.isLowerCase(suffixesVar[hunkInVarName].charAt(0)) && Character.isUpperCase(suffixesOldEqual[lastSuffixMatched].charAt(0))) {
- suffixesVar[hunkInVarName]= getUpperCased(suffixesVar[hunkInVarName]);
- suffixesNew[0]= getLowerCased(suffixesNew[0]);
- }
-
- String[] newVariableName= new String[suffixesVar.length + newPrefixes];
- System.arraycopy(suffixesVar, 0, newVariableName, 0, hunkInVarName); // hunks before type name in variable name
- System.arraycopy(suffixesNew, 0, newVariableName, hunkInVarName, newPrefixes); // new hunks in new type name
- System.arraycopy(suffixesVar, hunkInVarName, newVariableName, hunkInVarName + newPrefixes, suffixesVar.length - hunkInVarName); // matched + rest hunks
- suffixesVar= newVariableName;
- }
- }
-
- String varName= concat(suffixesVar);
- if (varName.equals(strippedVariableName))
- return null; // no "silly suggestions"
- else
- return varName;
- }
-
-
- // ---------------- Helper methods
-
- /**
- * True if the string is the beginning of a new camel case hunk. False if it
- * is not.
- */
- private boolean startsNewHunk(String string) {
-
- if (string.length() == 0)
- return true;
-
- return isLegalChar(string.charAt(0));
- }
-
- /**
- * True if hunk is longer than 1 character and all letters in the hunk are
- * uppercase. False if not.
- */
- private boolean isUpperCaseCamelCaseHunk(String hunk) {
- if (hunk.length() < 2)
- return false;
-
- for (int i= 0; i < hunk.length(); i++) {
- if (!isLegalChar(hunk.charAt(i)))
- return false;
- }
- return true;
- }
-
- /**
- * False if the character is a letter and it is lowercase. True in all other
- * cases.
- */
- private boolean isLegalChar(char c) {
- if (Character.isLetter(c))
- return Character.isUpperCase(c);
- return true;
- }
-
- /**
- * Grab a list of camelCase-separated suffixes from the typeName, for
- * example:
- *
- * "JavaElementName" => { "Java", "Element", "Name }
- *
- * "ASTNode" => { "AST", "Node" }
- *
- */
- private String[] getSuffixes(String typeName) {
- List suffixes= new ArrayList();
- JavaWordIterator iterator= new JavaWordIterator();
- iterator.setText(typeName);
- int lastmatch= 0;
- int match;
- while ( (match= iterator.next()) != BreakIterator.DONE) {
- suffixes.add(typeName.substring(lastmatch, match));
- lastmatch= match;
- }
- return (String[]) suffixes.toArray(new String[0]);
- }
-
- private String concat(String[] suffixesNewEqual) {
- StringBuffer returner= new StringBuffer();
- for (int j= 0; j < suffixesNewEqual.length; j++) {
- returner.append(suffixesNewEqual[j]);
- }
- return returner.toString();
- }
-
- private String getLowerCased(String name) {
- if (name.length() > 1)
- return Character.toLowerCase(name.charAt(0)) + name.substring(1);
- else
- return name.toLowerCase();
- }
-
- private String getUpperCased(String name) {
- if (name.length() > 1)
- return Character.toUpperCase(name.charAt(0)) + name.substring(1);
- else
- return name.toLowerCase();
- }
-
- private String getFirstUpperRestLowerCased(String name) {
- if (name.length() > 1)
- return Character.toUpperCase(name.charAt(0)) + name.substring(1).toLowerCase();
- else
- return name.toLowerCase();
- }
-
- private boolean isInterfaceName(String typeName) {
- return ( (typeName.length() >= 2) && typeName.charAt(0) == 'I' && Character.isUpperCase(typeName.charAt(1)));
- }
-
- private String getInterfaceName(String typeName) {
- return typeName.substring(1);
- }
-
- private String findLongestPrefix(String name, String[] prefixes) {
- String usedPrefix= ""; //$NON-NLS-1$
- int bestLen= 0;
- for (int i= 0; i < prefixes.length; i++) {
- if (name.startsWith(prefixes[i])) {
- if (prefixes[i].length() > bestLen) {
- bestLen= prefixes[i].length();
- usedPrefix= prefixes[i];
- }
- }
- }
- return usedPrefix;
- }
-
- private String findLongestSuffix(String name, String[] suffixes) {
- String usedPrefix= ""; //$NON-NLS-1$
- int bestLen= 0;
- for (int i= 0; i < suffixes.length; i++) {
- if (name.endsWith(suffixes[i])) {
- if (suffixes[i].length() > bestLen) {
- bestLen= suffixes[i].length();
- usedPrefix= suffixes[i];
- }
- }
- }
- return usedPrefix;
- }
-
- /**
- * Returns true if the type name can be pluralized by a string operation.
- * This is always the case if it does not already end with an "s".
- */
- private boolean canPluralize(String typeName) {
- return !typeName.endsWith(PLURAL_S);
- }
-
- private String pluralize(String typeName) {
- if (typeName.endsWith(SINGULAR_Y))
- typeName= typeName.substring(0, typeName.length() - 1).concat(PLURAL_IES);
- else if (!typeName.endsWith(PLURAL_S))
- typeName= typeName.concat(PLURAL_S);
- return typeName;
- }
-
- private void resetPrefixes() {
- String[] empty= new String[0];
- fFieldPrefixes= empty;
- fFieldSuffixes= empty;
- fStaticFieldPrefixes= empty;
- fStaticFieldSuffixes= empty;
- fLocalPrefixes= empty;
- fLocalSuffixes= empty;
- fArgumentPrefixes= empty;
- fArgumentSuffixes= empty;
- }
-
- private void initializePrefixesAndSuffixes(IJavaScriptProject project) {
- fFieldPrefixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_FIELD_PREFIXES);
- fFieldSuffixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_FIELD_SUFFIXES);
- fStaticFieldPrefixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_STATIC_FIELD_PREFIXES);
- fStaticFieldSuffixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_STATIC_FIELD_SUFFIXES);
- fLocalPrefixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_LOCAL_PREFIXES);
- fLocalSuffixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_LOCAL_SUFFIXES);
- fArgumentPrefixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_ARGUMENT_PREFIXES);
- fArgumentSuffixes= readCommaSeparatedPreference(project, JavaScriptCore.CODEASSIST_ARGUMENT_SUFFIXES);
- }
-
- private String[] readCommaSeparatedPreference(IJavaScriptProject project, String option) {
- String list= project.getOption(option, true);
- return list == null ? new String[0] : list.split(","); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RippleMethodFinder2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RippleMethodFinder2.java
deleted file mode 100644
index c08d58a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RippleMethodFinder2.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IRegion;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-public class RippleMethodFinder2 {
-
- private final IFunction fMethod;
- private List/*<IFunction>*/ fDeclarations;
- private ITypeHierarchy fHierarchy;
- private Map/*IType, IFunction*/ fTypeToMethod;
- private Set/*IType*/ fRootTypes;
- private MultiMap/*IType, IType*/ fRootReps;
- private Map/*IType, ITypeHierarchy*/ fRootHierarchies;
- private UnionFind fUnionFind;
- private boolean fExcludeBinaries;
-
- private static class MultiMap {
- HashMap/*<IType, Collection>*/ fImplementation= new HashMap();
-
- public void put(IType key, IType value) {
- Collection collection= (Collection) fImplementation.get(key);
- if (collection == null) {
- collection= new HashSet();
- fImplementation.put(key, collection);
- }
- collection.add(value);
- }
-
- public Collection get(IType key) {
- return (Collection) fImplementation.get(key);
- }
- }
- private static class UnionFind {
- HashMap/*<IType, IType>*/ fElementToRepresentative= new HashMap();
-
- public void init(IType type) {
- fElementToRepresentative.put(type, type);
- }
-
- //path compression:
- public IType find(IType element) {
- IType root= element;
- IType rep= (IType) fElementToRepresentative.get(root);
- while (rep != null && ! rep.equals(root)) {
- root= rep;
- rep= (IType) fElementToRepresentative.get(root);
- }
- if (rep == null)
- return null;
-
- rep= (IType) fElementToRepresentative.get(element);
- while (! rep.equals(root)) {
- IType temp= element;
- element= rep;
- fElementToRepresentative.put(temp, root);
- rep= (IType) fElementToRepresentative.get(element);
- }
- return root;
- }
-
-// //straightforward:
-// public IType find(IType element) {
-// IType current= element;
-// IType rep= (IType) fElementToRepresentative.get(current);
-// while (rep != null && ! rep.equals(current)) {
-// current= rep;
-// rep= (IType) fElementToRepresentative.get(current);
-// }
-// if (rep == null)
-// return null;
-// else
-// return current;
-// }
-
- public void union(IType rep1, IType rep2) {
- fElementToRepresentative.put(rep1, rep2);
- }
- }
-
-
- private RippleMethodFinder2(IFunction method, boolean excludeBinaries){
- fMethod= method;
- fExcludeBinaries= excludeBinaries;
- }
-
- public static IFunction[] getRelatedMethods(IFunction method, boolean excludeBinaries, IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
- try{
- if (! MethodChecks.isVirtual(method))
- return new IFunction[]{ method };
-
- return new RippleMethodFinder2(method, excludeBinaries).getAllRippleMethods(pm, owner);
- } finally{
- pm.done();
- }
- }
- public static IFunction[] getRelatedMethods(IFunction method, IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
- return getRelatedMethods(method, true, pm, owner);
- }
-
- private IFunction[] getAllRippleMethods(IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
- pm.beginTask("", 4); //$NON-NLS-1$
-
- findAllDeclarations(new SubProgressMonitor(pm, 1), owner);
- //TODO: report binary methods to an error status
- //TODO: report assertion as error status and fall back to only return fMethod
- //check for bug 81058:
- Assert.isTrue(fDeclarations.contains(fMethod), "Search for method declaration did not find original element"); //$NON-NLS-1$
-
- createHierarchyOfDeclarations(new SubProgressMonitor(pm, 1), owner);
- createTypeToMethod();
- createUnionFind();
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- fHierarchy= null;
- fRootTypes= null;
-
- Map/*IType, List<IType>*/ partitioning= new HashMap();
- for (Iterator iter= fTypeToMethod.keySet().iterator(); iter.hasNext();) {
- IType type= (IType) iter.next();
- IType rep= fUnionFind.find(type);
- List/*<IType>*/ types= (List) partitioning.get(rep);
- if (types == null)
- types= new ArrayList();
- types.add(type);
- partitioning.put(rep, types);
- }
- Assert.isTrue(partitioning.size() > 0);
- if (partitioning.size() == 1)
- return (IFunction[]) fDeclarations.toArray(new IFunction[fDeclarations.size()]);
-
- //Multiple partitions; must look out for nasty marriage cases
- //(types inheriting method from two ancestors, but without redeclaring it).
- IType methodTypeRep= fUnionFind.find(fMethod.getDeclaringType());
- List/*<IType>*/ relatedTypes= (List) partitioning.get(methodTypeRep);
- boolean hasRelatedInterfaces= false;
- List/*<IFunction>*/ relatedMethods= new ArrayList();
- for (Iterator iter= relatedTypes.iterator(); iter.hasNext();) {
- IType relatedType= (IType) iter.next();
- relatedMethods.add(fTypeToMethod.get(relatedType));
- }
-
- //Definition: An alien type is a type that is not a related type. The set of
- // alien types diminishes as new types become related (a.k.a marry a relatedType).
-
- List/*<IFunction>*/ alienDeclarations= new ArrayList(fDeclarations);
- fDeclarations= null;
- alienDeclarations.removeAll(relatedMethods);
- List/*<IType>*/ alienTypes= new ArrayList();
- boolean hasAlienInterfaces= false;
- for (Iterator iter= alienDeclarations.iterator(); iter.hasNext();) {
- IFunction alienDeclaration= (IFunction) iter.next();
- IType alienType= alienDeclaration.getDeclaringType();
- alienTypes.add(alienType);
- }
- if (alienTypes.size() == 0) //no nasty marriage scenarios without types to marry with...
- return (IFunction[]) relatedMethods.toArray(new IFunction[relatedMethods.size()]);
- if (! hasRelatedInterfaces && ! hasAlienInterfaces) //no nasty marriage scenarios without interfaces...
- return (IFunction[]) relatedMethods.toArray(new IFunction[relatedMethods.size()]);
-
- //find all subtypes of related types:
- HashSet/*<IType>*/ relatedSubTypes= new HashSet();
- List/*<IType>*/ relatedTypesToProcess= new ArrayList(relatedTypes);
- while (relatedTypesToProcess.size() > 0) {
- //TODO: would only need subtype hierarchies of all top-of-ripple relatedTypesToProcess
- for (Iterator iter= relatedTypesToProcess.iterator(); iter.hasNext();) {
- if (pm.isCanceled())
- throw new OperationCanceledException();
- IType relatedType= (IType) iter.next();
- ITypeHierarchy hierarchy= getCachedHierarchy(relatedType, owner, new SubProgressMonitor(pm, 1));
- if (hierarchy == null)
- hierarchy= relatedType.newTypeHierarchy(owner, new SubProgressMonitor(pm, 1));
- IType[] allSubTypes= hierarchy.getAllSubtypes(relatedType);
- for (int i= 0; i < allSubTypes.length; i++)
- relatedSubTypes.add(allSubTypes[i]);
- }
- relatedTypesToProcess.clear(); //processed; make sure loop terminates
-
- HashSet/*<IType>*/ marriedAlienTypeReps= new HashSet();
- for (Iterator iter= alienTypes.iterator(); iter.hasNext();) {
- if (pm.isCanceled())
- throw new OperationCanceledException();
- IType alienType= (IType) iter.next();
- IFunction alienMethod= (IFunction) fTypeToMethod.get(alienType);
- ITypeHierarchy hierarchy= getCachedHierarchy(alienType, owner, new SubProgressMonitor(pm, 1));
- if (hierarchy == null)
- hierarchy= alienType.newTypeHierarchy(owner, new SubProgressMonitor(pm, 1));
- IType[] allSubtypes= hierarchy.getAllSubtypes(alienType);
- for (int i= 0; i < allSubtypes.length; i++) {
- IType subtype= allSubtypes[i];
- if (relatedSubTypes.contains(subtype)) {
- if (JavaModelUtil.isVisibleInHierarchy(alienMethod, subtype.getPackageFragment())) {
- marriedAlienTypeReps.add(fUnionFind.find(alienType));
- } else {
- // not overridden
- }
- }
- }
- }
-
- if (marriedAlienTypeReps.size() == 0)
- return (IFunction[]) relatedMethods.toArray(new IFunction[relatedMethods.size()]);
-
- for (Iterator iter= marriedAlienTypeReps.iterator(); iter.hasNext();) {
- IType marriedAlienTypeRep= (IType) iter.next();
- List/*<IType>*/ marriedAlienTypes= (List) partitioning.get(marriedAlienTypeRep);
- for (Iterator iterator= marriedAlienTypes.iterator(); iterator.hasNext();) {
- IType marriedAlienInterfaceType= (IType) iterator.next();
- relatedMethods.add(fTypeToMethod.get(marriedAlienInterfaceType));
- }
- alienTypes.removeAll(marriedAlienTypes); //not alien any more
- relatedTypesToProcess.addAll(marriedAlienTypes); //process freshly married types again
- }
- }
-
- fRootReps= null;
- fRootHierarchies= null;
- fTypeToMethod= null;
- fUnionFind= null;
-
- return (IFunction[]) relatedMethods.toArray(new IFunction[relatedMethods.size()]);
- }
-
- private ITypeHierarchy getCachedHierarchy(IType type, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException {
- IType rep= fUnionFind.find(type);
- if (rep != null) {
- Collection collection= fRootReps.get(rep);
- for (Iterator iter= collection.iterator(); iter.hasNext();) {
- IType root= (IType) iter.next();
- ITypeHierarchy hierarchy= (ITypeHierarchy) fRootHierarchies.get(root);
- if (hierarchy == null) {
- hierarchy= root.newTypeHierarchy(owner, new SubProgressMonitor(monitor, 1));
- fRootHierarchies.put(root, hierarchy);
- }
- if (hierarchy.contains(type))
- return hierarchy;
- }
- }
- return null;
- }
-
- private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
- fDeclarations= new ArrayList();
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fMethod, IJavaScriptSearchConstants.DECLARATIONS | IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE | IJavaScriptSearchConstants.IGNORE_RETURN_TYPE, SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE));
- if (owner != null)
- engine.setOwner(owner);
- engine.setScope(RefactoringScopeFactory.createRelatedProjectsScope(fMethod.getJavaScriptProject(), IJavaScriptSearchScope.SOURCES | IJavaScriptSearchScope.APPLICATION_LIBRARIES | IJavaScriptSearchScope.SYSTEM_LIBRARIES));
- engine.setFiltering(false, fExcludeBinaries);
- engine.setGrouping(false);
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- final SearchMatch[] matches= (SearchMatch[]) engine.getResults();
- IFunction method= null;
- for (int index= 0; index < matches.length; index++) {
- method= (IFunction) matches[index].getElement();
- if (method != null)
- fDeclarations.add(method);
- }
- }
-
- private void createHierarchyOfDeclarations(IProgressMonitor pm, WorkingCopyOwner owner) throws JavaScriptModelException {
- IRegion region= JavaScriptCore.newRegion();
- for (Iterator iter= fDeclarations.iterator(); iter.hasNext();) {
- IType declaringType= ((IFunction) iter.next()).getDeclaringType();
- region.add(declaringType);
- }
- fHierarchy= JavaScriptCore.newTypeHierarchy(region, owner, pm);
- }
-
- private void createTypeToMethod() {
- fTypeToMethod= new HashMap();
- for (Iterator iter= fDeclarations.iterator(); iter.hasNext();) {
- IFunction declaration= (IFunction) iter.next();
- fTypeToMethod.put(declaration.getDeclaringType(), declaration);
- }
- }
-
- private void createUnionFind() throws JavaScriptModelException {
- fRootTypes= new HashSet(fTypeToMethod.keySet());
- fUnionFind= new UnionFind();
- for (Iterator iter= fTypeToMethod.keySet().iterator(); iter.hasNext();) {
- IType type= (IType) iter.next();
- fUnionFind.init(type);
- }
- for (Iterator iter= fTypeToMethod.keySet().iterator(); iter.hasNext();) {
- IType type= (IType) iter.next();
- uniteWithSupertypes(type, type);
- }
- fRootReps= new MultiMap();
- for (Iterator iter= fRootTypes.iterator(); iter.hasNext();) {
- IType type= (IType) iter.next();
- IType rep= fUnionFind.find(type);
- if (rep != null)
- fRootReps.put(rep, type);
- }
- fRootHierarchies= new HashMap();
- }
-
- private void uniteWithSupertypes(IType anchor, IType type) throws JavaScriptModelException {
- IType supertype = fHierarchy.getSuperclass(type);
-
- IType superRep= fUnionFind.find(supertype);
- if (superRep == null) {
- //Type doesn't declare method, but maybe supertypes?
- uniteWithSupertypes(anchor, supertype);
- } else {
- //check whether method in supertype is really overridden:
- IMember superMethod= (IMember) fTypeToMethod.get(supertype);
- if (JavaModelUtil.isVisibleInHierarchy(superMethod, anchor.getPackageFragment())) {
- IType rep= fUnionFind.find(anchor);
- fUnionFind.union(rep, superRep);
- // current type is no root anymore
- fRootTypes.remove(anchor);
- uniteWithSupertypes(supertype, supertype);
- } else {
- //Not overridden -> overriding chain ends here.
- }
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempDeclarationFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempDeclarationFinder.java
deleted file mode 100644
index 4afe12aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempDeclarationFinder.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-
-public class TempDeclarationFinder {
-
- //no instances
- private TempDeclarationFinder(){}
-
- /**
- * @return <code>null</code> if the selection is invalid or does not cover a temp
- * declaration or reference.
- */
- public static VariableDeclaration findTempDeclaration(JavaScriptUnit cu, int selectionOffset, int selectionLength) {
- TempSelectionAnalyzer analyzer= new TempSelectionAnalyzer(selectionOffset, selectionLength);
- cu.accept(analyzer);
-
- ASTNode[] selected= analyzer.getSelectedNodes();
- if (selected == null || selected.length != 1)
- return null;
-
- ASTNode selectedNode= selected[0];
- if (selectedNode instanceof VariableDeclaration)
- return (VariableDeclaration)selectedNode;
-
- if (selectedNode instanceof Name){
- Name reference= (Name)selectedNode;
- IBinding binding= reference.resolveBinding();
- if (binding == null)
- return null;
- ASTNode declaringNode= cu.findDeclaringNode(binding);
- if (declaringNode instanceof VariableDeclaration)
- return (VariableDeclaration)declaringNode;
- else
- return null;
- } else if (selectedNode instanceof VariableDeclarationStatement){
- VariableDeclarationStatement vds= (VariableDeclarationStatement)selectedNode;
- if (vds.fragments().size() != 1)
- return null;
- return (VariableDeclaration)vds.fragments().get(0);
- }
- return null;
- }
-
- /*
- * Class used to extract selected nodes from an AST.
- * Subclassing <code>SelectionAnalyzer</code> is needed to support activation
- * when only a part of the <code>VariableDeclaration</code> node is selected
- */
- private static class TempSelectionAnalyzer extends SelectionAnalyzer {
-
- private ASTNode fNode;
-
- TempSelectionAnalyzer(int selectionOffset, int selectionLength){
- super(Selection.createFromStartLength(selectionOffset, selectionLength), true);
- }
-
- //overridden
- public boolean visitNode(ASTNode node) {
- if (node instanceof VariableDeclaration)
- return visitVariableDeclaration((VariableDeclaration)node);
- else if (node instanceof SimpleName)
- return visitSimpleName((SimpleName)node);
- else
- return super.visitNode(node);
- }
-
- private boolean addNodeAndStop(ASTNode node){
- fNode= node;
- return false;
- }
-
- private boolean visitSimpleName(SimpleName name) {
- if (getSelection().coveredBy(name))
- return addNodeAndStop(name);
- return super.visitNode(name);
- }
-
- private boolean visitVariableDeclaration(VariableDeclaration vd) {
- if (vd.getInitializer() != null){
- int start= vd.getStartPosition();
- IRegion declarationRange= new Region(start, vd.getInitializer().getStartPosition() - start);
- if (getSelection().coveredBy(declarationRange))
- return addNodeAndStop(vd);
- else
- return super.visitNode(vd);
- } else {
- if (getSelection().coveredBy(vd))
- return addNodeAndStop(vd);
- else
- return super.visitNode(vd);
- }
- }
-
- //overridden
- public ASTNode[] getSelectedNodes() {
- if (fNode != null)
- return new ASTNode[] { fNode };
- return super.getSelectedNodes();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempOccurrenceAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempOccurrenceAnalyzer.java
deleted file mode 100644
index b1aef21a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TempOccurrenceAnalyzer.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-
-
-public class TempOccurrenceAnalyzer extends ASTVisitor {
- /** Set of SimpleName */
- private Set fReferenceNodes;
- /** Set of SimpleName */
- private Set fJavadocNodes;
-
- private VariableDeclaration fTempDeclaration;
- private IBinding fTempBinding;
- private boolean fAnalyzeJavadoc;
-
- private boolean fIsInJavadoc;
-
- public TempOccurrenceAnalyzer(VariableDeclaration tempDeclaration, boolean analyzeJavadoc){
- Assert.isNotNull(tempDeclaration);
- fReferenceNodes= new HashSet();
- fJavadocNodes= new HashSet();
- fAnalyzeJavadoc= analyzeJavadoc;
- fTempDeclaration= tempDeclaration;
- fTempBinding= tempDeclaration.resolveBinding();
- fIsInJavadoc= false;
- }
-
- public void perform() {
- ASTNode cuNode= ASTNodes.getParent(fTempDeclaration, JavaScriptUnit.class);
- cuNode.accept(this);
- }
-
- public int[] getReferenceOffsets(){
- int[] offsets= new int[fReferenceNodes.size()];
- addOffsets(offsets, 0, fReferenceNodes);
- return offsets;
- }
-
- public int[] getReferenceAndJavadocOffsets(){
- int[] offsets= new int[fReferenceNodes.size() + fJavadocNodes.size()];
- addOffsets(offsets, 0, fReferenceNodes);
- addOffsets(offsets, fReferenceNodes.size(), fJavadocNodes);
- return offsets;
- }
-
- private void addOffsets(int[] offsets, int start, Set nodeSet) {
- int i= start;
- for (Iterator iter= nodeSet.iterator(); iter.hasNext(); i++) {
- ASTNode node= (ASTNode) iter.next();
- offsets[i]= node.getStartPosition();
- }
- }
-
- public int getNumberOfReferences() {
- return fReferenceNodes.size();
- }
-
- public SimpleName[] getReferenceNodes() {
- return (SimpleName[]) fReferenceNodes.toArray(new SimpleName[fReferenceNodes.size()]);
- }
-
- public SimpleName[] getJavadocNodes() {
- return (SimpleName[]) fJavadocNodes.toArray(new SimpleName[fJavadocNodes.size()]);
- }
-
- public SimpleName[] getReferenceAndDeclarationNodes() {
- SimpleName[] nodes= (SimpleName[]) fReferenceNodes.toArray(new SimpleName[fReferenceNodes.size() + 1]);
- nodes[fReferenceNodes.size()]= fTempDeclaration.getName();
- return nodes;
- }
-
- //------- visit ------ (don't call)
-
- public boolean visit(JSdoc node) {
- if (fAnalyzeJavadoc)
- fIsInJavadoc= true;
- return fAnalyzeJavadoc;
- }
-
- public void endVisit(JSdoc node) {
- fIsInJavadoc= false;
- }
-
- public boolean visit(SimpleName node){
- if (node.getParent() instanceof VariableDeclaration){
- if (((VariableDeclaration)node.getParent()).getName() == node)
- return true; //don't include declaration
- }
-
- if (fTempBinding != null && fTempBinding == node.resolveBinding()) {
- if (fIsInJavadoc)
- fJavadocNodes.add(node);
- else
- fReferenceNodes.add(node);
- }
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TextMatchUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TextMatchUpdater.java
deleted file mode 100644
index 5e61f219..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TextMatchUpdater.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RefactoringScanner.TextMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-
-class TextMatchUpdater {
-
- private static final String TEXT_EDIT_LABEL= RefactoringCoreMessages.TextMatchUpdater_update;
-
- private static final GroupCategorySet TEXTUAL_MATCHES= new GroupCategorySet(
- new GroupCategory("org.eclipse.wst.jsdt.internal.corext.textualMatches", //$NON-NLS-1$
- RefactoringCoreMessages.TextMatchUpdater_textualMatches_name,
- RefactoringCoreMessages.TextMatchUpdater_textualMatches_description));
-
- private final IJavaScriptSearchScope fScope;
- private final TextChangeManager fManager;
- private final SearchResultGroup[] fReferences;
- private final boolean fOnlyQualified;
-
- private final RefactoringScanner fScanner;
- private final String fNewName;
- private final int fCurrentNameLength;
-
- private TextMatchUpdater(TextChangeManager manager, IJavaScriptSearchScope scope, String currentName, String currentQualifier, String newName, SearchResultGroup[] references, boolean onlyQualified){
- Assert.isNotNull(manager);
- Assert.isNotNull(scope);
- Assert.isNotNull(references);
- fManager= manager;
- fScope= scope;
- fReferences= references;
- fOnlyQualified= onlyQualified;
-
- fNewName= newName;
- fCurrentNameLength= currentName.length();
- fScanner= new RefactoringScanner(currentName, currentQualifier);
- }
-
- static void perform(IProgressMonitor pm, IJavaScriptSearchScope scope, String currentName, String currentQualifier, String newName, TextChangeManager manager, SearchResultGroup[] references, boolean onlyQualified) throws JavaScriptModelException{
- new TextMatchUpdater(manager, scope, currentName, currentQualifier, newName, references, onlyQualified).updateTextMatches(pm);
- }
-
- static void perform(IProgressMonitor pm, IJavaScriptSearchScope scope, ITextUpdating processor, TextChangeManager manager, SearchResultGroup[] references) throws JavaScriptModelException{
- new TextMatchUpdater(manager, scope, processor.getCurrentElementName(), processor.getCurrentElementQualifier(), processor.getNewElementName(), references, false).updateTextMatches(pm);
- }
-
- private void updateTextMatches(IProgressMonitor pm) throws JavaScriptModelException {
- try{
- IProject[] projectsInScope= getProjectsInScope();
-
- pm.beginTask("", projectsInScope.length); //$NON-NLS-1$
-
- for (int i =0 ; i < projectsInScope.length; i++){
- if (pm.isCanceled())
- throw new OperationCanceledException();
- addTextMatches(projectsInScope[i], new SubProgressMonitor(pm, 1));
- }
- } finally{
- pm.done();
- }
- }
-
- private IProject[] getProjectsInScope() {
- IPath[] enclosingProjects= fScope.enclosingProjectsAndJars();
- Set enclosingProjectSet= new HashSet();
- enclosingProjectSet.addAll(Arrays.asList(enclosingProjects));
-
- ArrayList projectsInScope= new ArrayList();
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i =0 ; i < projects.length; i++){
- if (enclosingProjectSet.contains(projects[i].getFullPath()))
- projectsInScope.add(projects[i]);
- }
-
- return (IProject[]) projectsInScope.toArray(new IProject[projectsInScope.size()]);
- }
-
- private void addTextMatches(IResource resource, IProgressMonitor pm) throws JavaScriptModelException{
- try{
- String task= RefactoringCoreMessages.TextMatchUpdater_searching + resource.getFullPath();
- if (resource instanceof IFile){
- IJavaScriptElement element= JavaScriptCore.create(resource);
- // don't start pm task (flickering label updates; finally {pm.done()} is enough)
- if (!(element instanceof IJavaScriptUnit))
- return;
- if (! element.exists())
- return;
- if (! fScope.encloses(element))
- return;
- addCuTextMatches((IJavaScriptUnit) element);
-
- } else if (resource instanceof IContainer){
- IResource[] members= ((IContainer) resource).members();
- pm.beginTask(task, members.length);
- pm.subTask(task);
- for (int i = 0; i < members.length; i++) {
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- addTextMatches(members[i], new SubProgressMonitor(pm, 1));
- }
- }
- } catch (JavaScriptModelException e){
- throw e;
- } catch (CoreException e){
- throw new JavaScriptModelException(e);
- } finally{
- pm.done();
- }
- }
-
- private void addCuTextMatches(IJavaScriptUnit cu) throws JavaScriptModelException{
- fScanner.scan(cu);
- Set matches= fScanner.getMatches(); //Set of TextMatch
- if (matches.size() == 0)
- return;
-
- removeReferences(cu, matches);
- if (matches.size() != 0)
- addTextUpdates(cu, matches);
- }
-
- private void removeReferences(IJavaScriptUnit cu, Set matches) {
- for (int i= 0; i < fReferences.length; i++) {
- SearchResultGroup group= fReferences[i];
- if (cu.equals(group.getCompilationUnit())) {
- removeReferences(matches, group);
- }
- }
- }
-
- private void removeReferences(Set matches, SearchResultGroup group) {
- SearchMatch[] searchResults= group.getSearchResults();
- for (int r= 0; r < searchResults.length; r++) {
- //int start= searchResults[r].getStart(); // doesn't work for pack.ReferencedType
- int unqualifiedStart= searchResults[r].getOffset() + searchResults[r].getLength() - fCurrentNameLength;
- for (Iterator iter= matches.iterator(); iter.hasNext();) {
- TextMatch element= (TextMatch) iter.next();
- if (element.getStartPosition() == unqualifiedStart)
- iter.remove();
- }
- }
- }
-
- private void addTextUpdates(IJavaScriptUnit cu, Set matches) {
- for (Iterator resultIter= matches.iterator(); resultIter.hasNext();){
- TextMatch match= (TextMatch) resultIter.next();
- if (!match.isQualified() && fOnlyQualified)
- continue;
- int matchStart= match.getStartPosition();
- ReplaceEdit edit= new ReplaceEdit(matchStart, fCurrentNameLength, fNewName);
- try {
- TextChangeCompatibility.addTextEdit(fManager.get(cu), TEXT_EDIT_LABEL, edit, TEXTUAL_MATCHES);
- } catch (MalformedTreeException e) {
- // conflicting update -> omit text match
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TypeOccurrenceCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TypeOccurrenceCollector.java
deleted file mode 100644
index 7f844dbf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/TypeOccurrenceCollector.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.rename;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CuCollectingSearchRequestor;
-
-public class TypeOccurrenceCollector extends CuCollectingSearchRequestor {
-
- final String fOldName;
- final String fOldQualifiedName;
-
- public TypeOccurrenceCollector(IType type) {
- fOldName= type.getElementName();
- fOldQualifiedName= type.getFullyQualifiedName('.');
- }
-
- public void acceptSearchMatch(IJavaScriptUnit unit, SearchMatch match) throws CoreException {
- collectMatch(acceptSearchMatch2(unit, match));
- }
-
- public SearchMatch acceptSearchMatch2(IJavaScriptUnit unit, SearchMatch match) throws CoreException {
- int start= match.getOffset();
- int length= match.getLength();
-
- //unqualified:
- String matchText= unit.getBuffer().getText(start, length);
- if (fOldName.equals(matchText)) {
- return match;
- }
-
- //(partially) qualified:
- if (fOldQualifiedName.endsWith(matchText)) {
- //e.g. rename B and p.A.B ends with match A.B
- int simpleNameLenght= fOldName.length();
- match.setOffset(start + length - simpleNameLenght);
- match.setLength(simpleNameLenght);
- return match;
- }
-
- //Not a standard reference -- use scanner to find last identifier token:
- IScanner scanner= getScanner(unit);
- scanner.setSource(matchText.toCharArray());
- int simpleNameStart= -1;
- int simpleNameEnd= -1;
- try {
- int token = scanner.getNextToken();
- while (token != ITerminalSymbols.TokenNameEOF) {
- if (token == ITerminalSymbols.TokenNameIdentifier) {
- simpleNameStart= scanner.getCurrentTokenStartPosition();
- simpleNameEnd= scanner.getCurrentTokenEndPosition();
- }
- token = scanner.getNextToken();
- }
- } catch (InvalidInputException e){
- //ignore
- }
- if (simpleNameStart != -1) {
- match.setOffset(start + simpleNameStart);
- match.setLength(simpleNameEnd + 1 - simpleNameStart);
- }
- return match;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/todo.txt b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/todo.txt
deleted file mode 100644
index 39e63bed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/todo.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-- TextUpdating is currently commented out.
-- File problems with RenameSupport that is API. Currently commented out.
-- questionable if the rename refactoring should return its processor ? \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ASTNodeDeleteUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ASTNodeDeleteUtil.java
deleted file mode 100644
index ec823437..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ASTNodeDeleteUtil.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-
-public class ASTNodeDeleteUtil {
-
- private static ASTNode[] getNodesToDelete(IJavaScriptElement element, JavaScriptUnit cuNode) throws JavaScriptModelException {
- // fields are different because you don't delete the whole declaration but only a fragment of it
- if (element.getElementType() == IJavaScriptElement.FIELD) {
- return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
- }
- if (element.getElementType() == IJavaScriptElement.TYPE && ((IType) element).isLocal()) {
- IType type= (IType) element;
- if (type.isAnonymous()) {
- if (type.getParent().getElementType() == IJavaScriptElement.FIELD) {
- final ISourceRange range= type.getSourceRange();
- if (range != null) {
- final ASTNode node= ASTNodeSearchUtil.getAstNode(cuNode, range.getOffset(), range.getLength());
- if (node instanceof AnonymousClassDeclaration)
- return new ASTNode[] { node};
- }
- }
- return new ASTNode[] { ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode)};
- } else {
- ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
- // we have to delete the TypeDeclarationStatement
- nodes[0]= nodes[0].getParent();
- return nodes;
- }
- }
- return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
- }
-
- private static Set getRemovedNodes(final List removed, final CompilationUnitRewrite rewrite) {
- final Set result= new HashSet();
- rewrite.getRoot().accept(new GenericVisitor(true) {
-
- protected boolean visitNode(ASTNode node) {
- if (removed.contains(node))
- result.add(node);
- return true;
- }
- });
- return result;
- }
-
- public static void markAsDeleted(IJavaScriptElement[] javaElements, CompilationUnitRewrite rewrite, TextEditGroup group) throws JavaScriptModelException {
- final List removed= new ArrayList();
- for (int i= 0; i < javaElements.length; i++) {
- markAsDeleted(removed, javaElements[i], rewrite, group);
- }
- propagateFieldDeclarationNodeDeletions(removed, rewrite, group);
- }
-
- private static void markAsDeleted(List list, IJavaScriptElement element, CompilationUnitRewrite rewrite, TextEditGroup group) throws JavaScriptModelException {
- ASTNode[] declarationNodes= getNodesToDelete(element, rewrite.getRoot());
- for (int i= 0; i < declarationNodes.length; i++) {
- ASTNode node= declarationNodes[i];
- if (node != null) {
- list.add(node);
- rewrite.getASTRewrite().remove(node, group);
- rewrite.getImportRemover().registerRemovedNode(node);
- }
- }
- }
-
- private static void propagateFieldDeclarationNodeDeletions(final List removed, final CompilationUnitRewrite rewrite, final TextEditGroup group) {
- Set removedNodes= getRemovedNodes(removed, rewrite);
- for (Iterator iter= removedNodes.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode) iter.next();
- if (node instanceof VariableDeclarationFragment) {
- if (node.getParent() instanceof FieldDeclaration) {
- FieldDeclaration fd= (FieldDeclaration) node.getParent();
- if (!removed.contains(fd) && removedNodes.containsAll(fd.fragments()))
- rewrite.getASTRewrite().remove(fd, group);
- rewrite.getImportRemover().registerRemovedNode(fd);
- } else if (node.getParent() instanceof VariableDeclarationStatement) {
- VariableDeclarationStatement stmt= (VariableDeclarationStatement) node.getParent();
- if (!removed.contains(stmt) && removedNodes.containsAll(stmt.fragments()))
- rewrite.getASTRewrite().remove(stmt, group);
- rewrite.getImportRemover().registerRemovedNode(stmt);
-
- }
- }
- }
- }
-
- private ASTNodeDeleteUtil() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ArrayTypeConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ArrayTypeConverter.java
deleted file mode 100644
index e5057a1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ArrayTypeConverter.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-class ArrayTypeConverter {
-
- private ArrayTypeConverter() {
- }
-
- static IFile[] toFileArray(Object[] objects){
- List l= Arrays.asList(objects);
- return (IFile[]) l.toArray(new IFile[l.size()]);
- }
-
- static IFolder[] toFolderArray(Object[] objects){
- List l= Arrays.asList(objects);
- return (IFolder[]) l.toArray(new IFolder[l.size()]);
- }
-
- static IJavaScriptUnit[] toCuArray(Object[] objects){
- List l= Arrays.asList(objects);
- return (IJavaScriptUnit[]) l.toArray(new IJavaScriptUnit[l.size()]);
- }
-
- static IPackageFragmentRoot[] toPackageFragmentRootArray(Object[] objects){
- List l= Arrays.asList(objects);
- return (IPackageFragmentRoot[]) l.toArray(new IPackageFragmentRoot[l.size()]);
- }
-
- static IPackageFragment[] toPackageArray(Object[] objects){
- List l= Arrays.asList(objects);
- return (IPackageFragment[]) l.toArray(new IPackageFragment[l.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CopyModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CopyModifications.java
deleted file mode 100644
index 34eac447..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CopyModifications.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CopyArguments;
-import org.eclipse.ltk.core.refactoring.participants.IParticipantDescriptorFilter;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceModifications;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-public class CopyModifications extends RefactoringModifications {
-
- private List fCopies;
- private List fCopyArguments;
- private List fParticipantDescriptorFilter;
-
- public CopyModifications() {
- fCopies= new ArrayList();
- fCopyArguments= new ArrayList();
- fParticipantDescriptorFilter= new ArrayList();
- }
-
- public void copy(IResource resource, CopyArguments args) {
- add(resource, args, null);
- }
-
- public void copy(IJavaScriptElement element, CopyArguments javaArgs, CopyArguments resourceArgs) throws CoreException {
- switch(element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- copy((IPackageFragmentRoot)element, javaArgs, resourceArgs);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- copy((IPackageFragment)element, javaArgs, resourceArgs);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- copy((IJavaScriptUnit)element, javaArgs, resourceArgs);
- break;
- default:
- add(element, javaArgs, null);
- }
- }
-
- public void copy(IPackageFragmentRoot sourceFolder, CopyArguments javaArgs, CopyArguments resourceArgs) {
- add(sourceFolder, javaArgs, null);
- ResourceMapping mapping= JavaElementResourceMapping.create(sourceFolder);
- if (mapping != null) {
- add(mapping, resourceArgs, null);
- }
- IResource sourceResource= sourceFolder.getResource();
- if (sourceResource != null) {
- getResourceModifications().addCopyDelta(sourceResource, resourceArgs);
- IFile classpath= getClasspathFile((IResource) resourceArgs.getDestination());
- if (classpath != null) {
- getResourceModifications().addChanged(classpath);
- }
- }
- }
-
- public void copy(IPackageFragment pack, CopyArguments javaArgs, CopyArguments resourceArgs) throws CoreException {
- add(pack, javaArgs, null);
- ResourceMapping mapping= JavaElementResourceMapping.create(pack);
- if (mapping != null) {
- add(mapping, resourceArgs, null);
- }
- IPackageFragmentRoot javaDestination= (IPackageFragmentRoot) javaArgs.getDestination();
- if (javaDestination.getResource() == null)
- return;
- IPackageFragment newPack= javaDestination.getPackageFragment(pack.getElementName());
- // Here we have a special case. When we copy a package into the same source
- // folder than the user will choose an "unused" name at the end which will
- // lead to the fact that we can copy the pack. Unfortunately we don't know
- // the new name yet, so we use the current package name.
- if (!pack.hasSubpackages() && (!newPack.exists() || pack.equals(newPack))) {
- // we can do a simple move
- IContainer resourceDestination= newPack.getResource().getParent();
- createIncludingParents(resourceDestination);
- getResourceModifications().addCopyDelta(pack.getResource(), resourceArgs);
- } else {
- IContainer resourceDestination= (IContainer) newPack.getResource();
- createIncludingParents(resourceDestination);
- CopyArguments arguments= new CopyArguments(resourceDestination, resourceArgs.getExecutionLog());
- IResource[] resourcesToCopy= collectResourcesOfInterest(pack);
- for (int i= 0; i < resourcesToCopy.length; i++) {
- IResource toCopy= resourcesToCopy[i];
- getResourceModifications().addCopyDelta(toCopy, arguments);
- }
- }
- }
-
- public void copy(IJavaScriptUnit unit, CopyArguments javaArgs, CopyArguments resourceArgs) throws CoreException {
- add(unit, javaArgs, null);
- ResourceMapping mapping= JavaElementResourceMapping.create(unit);
- if (mapping != null) {
- add(mapping, resourceArgs, null);
- }
- if (unit.getResource() != null) {
- getResourceModifications().addCopyDelta(unit.getResource(), resourceArgs);
- }
- }
-
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- for (int i= 0; i < fCopies.size(); i++) {
- Object element= fCopies.get(i);
- if (element instanceof IResource) {
- ResourceModifications.buildCopyDelta(builder, (IResource) element, (CopyArguments) fCopyArguments.get(i));
- }
- }
- getResourceModifications().buildDelta(builder);
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) {
- List result= new ArrayList();
- for (int i= 0; i < fCopies.size(); i++) {
- result.addAll(Arrays.asList(ParticipantManager.loadCopyParticipants(status,
- owner, fCopies.get(i),
- (CopyArguments) fCopyArguments.get(i),
- (IParticipantDescriptorFilter) fParticipantDescriptorFilter.get(i),
- natures, shared)));
- }
- result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared)));
- return (RefactoringParticipant[]) result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- private void add(Object element, RefactoringArguments args, IParticipantDescriptorFilter filter) {
- Assert.isNotNull(element);
- Assert.isNotNull(args);
- fCopies.add(element);
- fCopyArguments.add(args);
- fParticipantDescriptorFilter.add(filter);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateCopyOfCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateCopyOfCompilationUnitChange.java
deleted file mode 100644
index acd68fa4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateCopyOfCompilationUnitChange.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.IRefactoringSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TypeOccurrenceCollector;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public final class CreateCopyOfCompilationUnitChange extends CreateTextFileChange {
-
- private static TextChangeManager createChangeManager(IProgressMonitor monitor, IJavaScriptUnit copy, String newName) throws CoreException {
- TextChangeManager manager= new TextChangeManager();
- SearchResultGroup refs= getReferences(copy, monitor);
- if (refs == null)
- return manager;
- if (refs.getCompilationUnit() == null)
- return manager;
-
- String name= RefactoringCoreMessages.CopyRefactoring_update_ref;
- SearchMatch[] results= refs.getSearchResults();
- for (int j= 0; j < results.length; j++) {
- SearchMatch searchResult= results[j];
- if (searchResult.getAccuracy() == SearchMatch.A_INACCURATE)
- continue;
- int offset= searchResult.getOffset();
- int length= searchResult.getLength();
- TextChangeCompatibility.addTextEdit(manager.get(copy), name, new ReplaceEdit(offset, length, newName));
- }
- return manager;
- }
-
- private static SearchPattern createSearchPattern(IType type) throws JavaScriptModelException {
- SearchPattern pattern= SearchPattern.createPattern(type, IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IFunction[] constructors= JavaElementUtil.getAllConstructors(type);
- if (constructors.length == 0)
- return pattern;
- SearchPattern constructorDeclarationPattern= RefactoringSearchEngine.createOrPattern(constructors, IJavaScriptSearchConstants.DECLARATIONS);
- return SearchPattern.createOrPattern(pattern, constructorDeclarationPattern);
- }
-
- private static String getCopiedFileSource(IProgressMonitor monitor, IJavaScriptUnit unit, String newTypeName) throws CoreException {
- IJavaScriptUnit copy= unit.getPrimary().getWorkingCopy(null);
- try {
- TextChangeManager manager= createChangeManager(monitor, copy, newTypeName);
- String result= manager.get(copy).getPreviewContent(new NullProgressMonitor());
- return result;
- } finally {
- copy.discardWorkingCopy();
- }
- }
-
- private static SearchResultGroup getReferences(final IJavaScriptUnit copy, IProgressMonitor monitor) throws JavaScriptModelException {
- final IJavaScriptUnit[] copies= new IJavaScriptUnit[] { copy};
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(copies);
- final IType type= copy.findPrimaryType();
- if (type == null)
- return null;
- SearchPattern pattern= createSearchPattern(type);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(pattern);
- engine.setScope(scope);
- engine.setWorkingCopies(copies);
- engine.searchPattern(monitor);
- engine.setRequestor(new IRefactoringSearchRequestor() {
- TypeOccurrenceCollector fTypeOccurrenceCollector= new TypeOccurrenceCollector(type);
- public SearchMatch acceptSearchMatch(SearchMatch match) {
- try {
- return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
- }
- });
- final Object[] results= engine.getResults();
- // Assert.isTrue(results.length <= 1);
- // just 1 file or none, but inaccurate matches can play bad here (see
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=106127)
- for (int index= 0; index < results.length; index++) {
- SearchResultGroup group= (SearchResultGroup) results[index];
- if (group.getCompilationUnit().equals(copy))
- return group;
- }
- return null;
- }
-
- private final INewNameQuery fNameQuery;
-
- private final IJavaScriptUnit fOldCu;
-
- public CreateCopyOfCompilationUnitChange(IPath path, String source, IJavaScriptUnit oldCu, INewNameQuery nameQuery) {
- super(path, source, null, "java"); //$NON-NLS-1$
- fOldCu= oldCu;
- fNameQuery= nameQuery;
- setEncoding(oldCu);
- }
-
- public String getName() {
- return Messages.format(RefactoringCoreMessages.CreateCopyOfCompilationUnitChange_create_copy, new String[] { fOldCu.getElementName(), getPathLabel(fOldCu.getResource())});
- }
-
- protected IFile getOldFile(IProgressMonitor monitor) throws OperationCanceledException {
- try {
- monitor.beginTask("", 12); //$NON-NLS-1$
- String oldSource= super.getSource();
- IPath oldPath= super.getPath();
- String newTypeName= fNameQuery.getNewName();
- try {
- String newSource= getCopiedFileSource(new SubProgressMonitor(monitor, 9), fOldCu, newTypeName);
- setSource(newSource);
- setPath(fOldCu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(fOldCu, newTypeName)));
- return super.getOldFile(new SubProgressMonitor(monitor, 1));
- } catch (CoreException e) {
- setSource(oldSource);
- setPath(oldPath);
- return super.getOldFile(new SubProgressMonitor(monitor, 2));
- }
- } finally {
- monitor.done();
- }
- }
-
- private String getPathLabel(IResource resource) {
- final StringBuffer buffer= new StringBuffer(resource.getProject().getName());
- final String path= resource.getParent().getProjectRelativePath().toString();
- if (path.length() > 0) {
- buffer.append('/');
- buffer.append(path);
- }
- return buffer.toString();
- }
-
- private void markAsExecuted(IJavaScriptUnit unit, ResourceMapping mapping) {
- ReorgExecutionLog log= (ReorgExecutionLog) getAdapter(ReorgExecutionLog.class);
- if (log != null) {
- log.markAsProcessed(unit);
- log.markAsProcessed(mapping);
- }
- }
-
- public Change perform(IProgressMonitor monitor) throws CoreException {
- ResourceMapping mapping= JavaElementResourceMapping.create(fOldCu);
- final Change result= super.perform(monitor);
- markAsExecuted(fOldCu, mapping);
- return result;
- }
-
- private void setEncoding(IJavaScriptUnit unit) {
- IResource resource= unit.getResource();
- // no file so the encoding is taken from the target
- if (!(resource instanceof IFile))
- return;
- IFile file= (IFile) resource;
- try {
- String encoding= file.getCharset(false);
- if (encoding != null) {
- setEncoding(encoding, true);
- } else {
- encoding= file.getCharset(true);
- if (encoding != null) {
- setEncoding(encoding, false);
- }
- }
- } catch (CoreException e) {
- // Take encoding from target
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java
deleted file mode 100644
index 22c3e5a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * Objects of this class can be used as a log to trace the creation of new
- * destinations during refactorings like move.
- *
- *
- */
-public final class CreateTargetExecutionLog {
-
- private Map fCreations= new LinkedHashMap(2);
-
- /**
- * Returns the element which got created for the given selection.
- *
- * @param selection
- * the selection
- * @return the created element, or <code>null</code>
- */
- public Object getCreatedElement(Object selection) {
- return fCreations.get(selection);
- }
-
- /**
- * Returns all created elements.
- *
- * @return all created elements
- */
- public Object[] getCreatedElements() {
- return fCreations.values().toArray();
- }
-
- /**
- * Returns all selected elements.
- *
- * @return all selected elements
- */
- public Object[] getSelectedElements() {
- return fCreations.keySet().toArray();
- }
-
- /**
- * Logs that the given element got created by the refactoring.
- *
- * @param selection
- * the selected object
- * @param element
- * the element that got created for the selection
- */
- public void markAsCreated(Object selection, Object element) {
- fCreations.put(selection, element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteChangeCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteChangeCreator.java
deleted file mode 100644
index eb432e8c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteChangeCreator.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceManipulation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DeleteFileChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DeleteFolderChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DeleteFromClasspathChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DeletePackageFragmentRootChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DeleteSourceManipulationChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.UndoablePackageDeleteChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-
-
-class DeleteChangeCreator {
- private DeleteChangeCreator() {
- //private
- }
-
- /**
- * @param packageDeletes a list of {@link IResource}s that will be deleted
- * by the delete operation of the {@link IPackageFragment}s in
- * <code>javaElements</code>, or <code>null</code> iff
- * <code>javaElements</code> does not contain package fragments
- */
- static Change createDeleteChange(TextChangeManager manager, IResource[] resources,
- IJavaScriptElement[] javaElements, String changeName, List/*<IResource>*/ packageDeletes) throws CoreException {
- /*
- * Problem: deleting a package and subpackages can result in
- * multiple package fragments in fJavaElements but only
- * one folder in packageDeletes. The way to handle this is to make the undo
- * change of individual package delete changes an empty change, and
- * add take care of the undo in UndoablePackageDeleteChange.
- */
- DynamicValidationStateChange result;
- if (packageDeletes.size() > 0) {
- result= new UndoablePackageDeleteChange(changeName, packageDeletes);
- } else {
- result= new DynamicValidationStateChange(changeName);
- }
-
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (! ReorgUtils.isInsideCompilationUnit(element))
- result.add(createDeleteChange(element));
- }
-
- for (int i= 0; i < resources.length; i++) {
- result.add(createDeleteChange(resources[i]));
- }
-
- Map grouped= ReorgUtils.groupByCompilationUnit(getElementsSmallerThanCu(javaElements));
- if (grouped.size() != 0 ){
- Assert.isNotNull(manager);
- for (Iterator iter= grouped.keySet().iterator(); iter.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit) iter.next();
- result.add(createDeleteChange(cu, (List)grouped.get(cu), manager));
- }
- }
-
- return result;
- }
-
- private static Change createDeleteChange(IResource resource) {
- Assert.isTrue(! (resource instanceof IWorkspaceRoot));//cannot be done
- Assert.isTrue(! (resource instanceof IProject)); //project deletion is handled by the workbench
- if (resource instanceof IFile)
- return new DeleteFileChange((IFile)resource, true);
- if (resource instanceof IFolder)
- return new DeleteFolderChange((IFolder)resource, true);
- Assert.isTrue(false);//there're no more kinds
- return null;
- }
-
- /*
- * List<IJavaScriptElement> javaElements
- */
- private static Change createDeleteChange(IJavaScriptUnit cu, List javaElements, TextChangeManager manager) throws CoreException {
- JavaScriptUnit cuNode= RefactoringASTParser.parseWithASTProvider(cu, false, null);
- CompilationUnitRewrite rewriter= new CompilationUnitRewrite(cu, cuNode);
- IJavaScriptElement[] elements= (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]);
- ASTNodeDeleteUtil.markAsDeleted(elements, rewriter, null);
- return addTextEditFromRewrite(manager, cu, rewriter.getASTRewrite());
- }
-
- private static TextChange addTextEditFromRewrite(TextChangeManager manager, IJavaScriptUnit cu, ASTRewrite rewrite) throws CoreException {
- try {
- ITextFileBuffer buffer= RefactoringFileBuffers.acquire(cu);
- TextEdit resultingEdits= rewrite.rewriteAST(buffer.getDocument(), cu.getJavaScriptProject().getOptions(true));
- TextChange textChange= manager.get(cu);
- if (textChange instanceof TextFileChange) {
- TextFileChange tfc= (TextFileChange) textChange;
- if (cu.isWorkingCopy())
- tfc.setSaveMode(TextFileChange.LEAVE_DIRTY);
- }
- String message= RefactoringCoreMessages.DeleteChangeCreator_1;
- TextChangeCompatibility.addTextEdit(textChange, message, resultingEdits);
- return textChange;
- } finally {
- RefactoringFileBuffers.release(cu);
- }
- }
-
- //List<IJavaScriptElement>
- private static List getElementsSmallerThanCu(IJavaScriptElement[] javaElements){
- List result= new ArrayList();
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (ReorgUtils.isInsideCompilationUnit(element))
- result.add(element);
- }
- return result;
- }
-
- private static Change createDeleteChange(IJavaScriptElement javaElement) {
- Assert.isTrue(! ReorgUtils.isInsideCompilationUnit(javaElement));
-
- switch(javaElement.getElementType()){
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return createPackageFragmentRootDeleteChange((IPackageFragmentRoot)javaElement);
-
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return createSourceManipulationDeleteChange((IPackageFragment)javaElement);
-
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return createSourceManipulationDeleteChange((IJavaScriptUnit)javaElement);
-
- case IJavaScriptElement.CLASS_FILE:
- //if this assert fails, it means that a precondition is missing
- Assert.isTrue(((IClassFile)javaElement).getResource() instanceof IFile);
- return createDeleteChange(((IClassFile)javaElement).getResource());
-
- case IJavaScriptElement.JAVASCRIPT_MODEL: //cannot be done
- Assert.isTrue(false);
- return null;
-
- case IJavaScriptElement.JAVASCRIPT_PROJECT: //handled differently
- Assert.isTrue(false);
- return null;
-
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- Assert.isTrue(false);//not done here
- return null;
- default:
- Assert.isTrue(false);//there's no more kinds
- return new NullChange();
- }
- }
-
- private static Change createSourceManipulationDeleteChange(ISourceManipulation element) {
- //XXX workaround for bug 31384, in case of linked ISourceManipulation delete the resource
- if (element instanceof IJavaScriptUnit || element instanceof IPackageFragment){
- IResource resource;
- if (element instanceof IJavaScriptUnit)
- resource= ReorgUtils.getResource((IJavaScriptUnit)element);
- else
- resource= ((IPackageFragment)element).getResource();
- if (resource != null && resource.isLinked())
- return createDeleteChange(resource);
- }
- return new DeleteSourceManipulationChange(element, true);
- }
-
- private static Change createPackageFragmentRootDeleteChange(IPackageFragmentRoot root) {
- IResource resource= root.getResource();
- if (resource != null && resource.isLinked()){
- //XXX using this code is a workaround for jcore bug 31998
- //jcore cannot handle linked stuff
- //normally, we should always create DeletePackageFragmentRootChange
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.DeleteRefactoring_delete_package_fragment_root);
-
- composite.add(new DeleteFromClasspathChange(root));
- Assert.isTrue(! Checks.isClasspathDelete(root));//checked in preconditions
- composite.add(createDeleteChange(resource));
-
- return composite;
- } else {
- Assert.isTrue(! root.isExternal());
- // TODO remove the query argument
- return new DeletePackageFragmentRootChange(root, true, null);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteModifications.java
deleted file mode 100644
index 05f6cd87..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/DeleteModifications.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.DeleteArguments;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-
-/**
- * A modification collector for Java element delete operations.
- */
-public class DeleteModifications extends RefactoringModifications {
-
- private List/*<IJavaScriptElement>*/ fDelete;
-
- /**
- * Contains the actual packages when executing
- * <code>handlePackageFragmentDelete</code>. This is part of the
- * algorithm to check if a parent folder can be deleted.
- */
- private List/*<IPackageFragment>*/ fPackagesToDelete;
-
- public DeleteModifications() {
- fDelete= new ArrayList();
- fPackagesToDelete= new ArrayList();
- }
-
- public void delete(IResource resource) {
- getResourceModifications().addDelete(resource);
- }
-
- public void delete(IResource[] resources) {
- for (int i= 0; i < resources.length; i++) {
- delete(resources[i]);
- }
- }
-
- public void delete(IJavaScriptElement[] elements) throws CoreException {
- for (int i= 0; i < elements.length; i++) {
- delete(elements[i]);
- }
- }
-
- public void delete(IJavaScriptElement element) throws CoreException {
- switch(element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- fDelete.add(element);
- if (element.getResource() != null)
- getResourceModifications().addDelete(element.getResource());
- return;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- fDelete.add(element);
- IResource resource= element.getResource();
- // Flag an resource change even if we have an archive. If it is
- // internal (we have a underlying resource then we have a resource
- // change.
- if (resource != null)
- getResourceModifications().addDelete(resource);
- IJavaScriptProject[] referencingProjects= JavaElementUtil.getReferencingProjects((IPackageFragmentRoot) element);
- for (int i= 0; i < referencingProjects.length; i++) {
- IFile classpath= referencingProjects[i].getJSDTScopeFile(); //$NON-NLS-1$
- getResourceModifications().addChanged(classpath);
- }
- return;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- fDelete.add(element);
- fPackagesToDelete.add(element);
- return;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- fDelete.add(element);
- IType[] types= ((IJavaScriptUnit)element).getTypes();
- fDelete.addAll(Arrays.asList(types));
- if (element.getResource() != null)
- getResourceModifications().addDelete(element.getResource());
- return;
- default:
- fDelete.add(element);
- }
-
- }
-
- /**
- * @return a List of IResources that are removed by package deletes
- */
- public List/*<IResource>*/ postProcess() throws CoreException {
- ArrayList resourcesCollector= new ArrayList();
- for (Iterator iter= fPackagesToDelete.iterator(); iter.hasNext();) {
- IPackageFragment pack= (IPackageFragment) iter.next();
- handlePackageFragmentDelete(pack, resourcesCollector);
- }
- return resourcesCollector;
- }
-
- public void buildDelta(IResourceChangeDescriptionFactory deltaFactory) {
- getResourceModifications().buildDelta(deltaFactory);
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) {
- List result= new ArrayList();
- for (Iterator iter= fDelete.iterator(); iter.hasNext();) {
- result.addAll(Arrays.asList(ParticipantManager.loadDeleteParticipants(status,
- owner, iter.next(),
- new DeleteArguments(), natures, shared)));
- }
- result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared)));
- return (RefactoringParticipant[]) result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- /**
- * This method collects file and folder deletion for notifying
- * participants. Participants will get notified of
- *
- * * deletion of the package (in any case)
- * * deletion of files within the package if only the files are deleted without
- * the package folder ("package cleaning")
- * * deletion of the package folder if it is not only cleared and if its parent
- * is not removed as well.
- *
- * All deleted resources are added to <code>resourcesCollector</code>
- *
- * @param resourcesCollector a collector for IResources to be deleted
- */
- private void handlePackageFragmentDelete(IPackageFragment pack, ArrayList resourcesCollector) throws CoreException {
- final IContainer container= (IContainer)pack.getResource();
- if (container == null)
- return;
-
- final IResource[] members= container.members();
-
- /*
- * Check whether this package is removed completely or only cleared.
- * The default package can never be removed completely.
- */
- if (!pack.isDefaultPackage() && canRemoveCompletely(pack)) {
- // This package is removed completely, which means its folder will be
- // deleted as well. We only notify participants of the folder deletion
- // if the parent folder of this folder will not be deleted as well:
- boolean parentIsMarked= false;
- final IPackageFragment parent= JavaElementUtil.getParentSubpackage(pack);
- if (parent == null) {
- // "Parent" is the default package which will never be
- // deleted physically
- parentIsMarked= false;
- } else {
- // Parent is marked if it is in the list
- parentIsMarked= fPackagesToDelete.contains(parent);
- }
-
- if (parentIsMarked) {
- // Parent is marked, but is it really deleted or only cleared?
- if (canRemoveCompletely(parent)) {
- // Parent can be removed completely, so we do not add
- // this folder to the list.
- } else {
- // Parent cannot be removed completely, but as this folder
- // can be removed, we notify the participant
- resourcesCollector.add(container);
- getResourceModifications().addDelete(container);
- }
- } else {
- // Parent will not be removed, but we will
- resourcesCollector.add(container);
- getResourceModifications().addDelete(container);
- }
- } else {
- // This package is only cleared because it has subpackages (=subfolders)
- // which are not deleted. As the package is only cleared, its folder
- // will not be removed and so we must notify the participant of the deleted children.
- for (int m= 0; m < members.length; m++) {
- IResource member= members[m];
- if (member instanceof IFile) {
- IFile file= (IFile)member;
- if ("class".equals(file.getFileExtension()) && file.isDerived()) //$NON-NLS-1$
- continue;
- if (pack.isDefaultPackage() && ! JavaScriptCore.isJavaScriptLikeFileName(file.getName()))
- continue;
- resourcesCollector.add(member);
- getResourceModifications().addDelete(member);
- }
- if (!pack.isDefaultPackage() && member instanceof IFolder) {
- // Normally, folder children of packages are packages
- // as well, but in case they have been removed from the build
- // path, notify the participant
- IPackageFragment frag= (IPackageFragment) JavaScriptCore.create(member);
- if (frag == null) {
- resourcesCollector.add(member);
- getResourceModifications().addDelete(member);
- }
- }
- }
- }
- }
-
- /**
- * Returns true if this initially selected package is really deletable
- * (if it has non-selected sub packages, it may only be cleared).
- */
- private boolean canRemoveCompletely(IPackageFragment pack) throws JavaScriptModelException {
- final IPackageFragment[] subPackages= JavaElementUtil.getPackageAndSubpackages(pack);
- for (int i= 0; i < subPackages.length; i++) {
- if (!(subPackages[i].equals(pack)) && !(fPackagesToDelete.contains(subPackages[i])))
- return false;
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IConfirmQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IConfirmQuery.java
deleted file mode 100644
index 0292f0f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IConfirmQuery.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.runtime.OperationCanceledException;
-
-public interface IConfirmQuery {
- public boolean confirm(String question) throws OperationCanceledException;
- public boolean confirm(String question, Object[] elements) throws OperationCanceledException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQueries.java
deleted file mode 100644
index 984399e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQueries.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-public interface ICreateTargetQueries {
-
- ICreateTargetQuery createNewPackageQuery();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQuery.java
deleted file mode 100644
index dc7cfc90..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ICreateTargetQuery.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-
-public interface ICreateTargetQuery {
- /**
- * Creates and returns a new target.
- *
- * @param selection the current destination
- * @return the newly created target
- */
- Object getCreatedTarget(Object selection);
-
- /**
- * @return the label for the "Create ***..." button
- */
- String getNewButtonLabel();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQueries.java
deleted file mode 100644
index 9af7cffd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQueries.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-public interface INewNameQueries {
- public INewNameQuery createNewCompilationUnitNameQuery(IJavaScriptUnit cu, String initialSuggestedName) throws OperationCanceledException;
- public INewNameQuery createNewResourceNameQuery(IResource res, String initialSuggestedName) throws OperationCanceledException;
- public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String initialSuggestedName) throws OperationCanceledException;
- public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) throws OperationCanceledException;
- public INewNameQuery createNullQuery();
- public INewNameQuery createStaticQuery(String newName) throws OperationCanceledException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQuery.java
deleted file mode 100644
index 82d6097a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/INewNameQuery.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.runtime.OperationCanceledException;
-
-public interface INewNameQuery {
- public String getNewName() throws OperationCanceledException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IPackageFragmentRootManipulationQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IPackageFragmentRootManipulationQuery.java
deleted file mode 100644
index abe75559..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IPackageFragmentRootManipulationQuery.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-/**
- * Query that can be used when manipulating package fragment roots.
- * Depending on the context, <code>confirmManipulation</code> can be used to
- * determine whether, for example, the package fragment root is to be deleted or
- * not or if the classpath of the referencing projects is to be updated.
- */
-public interface IPackageFragmentRootManipulationQuery {
-
- public boolean confirmManipulation(IPackageFragmentRoot root, IJavaScriptProject[] referencingProjects);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgDestinationValidator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgDestinationValidator.java
deleted file mode 100644
index e55a8bc8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgDestinationValidator.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public interface IReorgDestinationValidator {
-
- public boolean canChildrenBeDestinations(IResource resource);
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement);
- public boolean canElementBeDestination(IResource resource);
- public boolean canElementBeDestination(IJavaScriptElement javaElement);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgPolicy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgPolicy.java
deleted file mode 100644
index 6e4eddd0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgPolicy.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-
-public interface IReorgPolicy extends IReferenceUpdating, IQualifiedNameUpdating, IScriptableRefactoring {
-
- public ChangeDescriptor getDescriptor();
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor monitor, CheckConditionsContext context, IReorgQueries queries) throws CoreException;
- public RefactoringStatus setDestination(IResource resource) throws JavaScriptModelException;
- public RefactoringStatus setDestination(IJavaScriptElement javaElement) throws JavaScriptModelException;
-
- public boolean canEnable() throws JavaScriptModelException;
- public boolean canChildrenBeDestinations(IResource resource);
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement);
- public boolean canElementBeDestination(IResource resource);
- public boolean canElementBeDestination(IJavaScriptElement javaElement);
-
- public IResource[] getResources();
- public IJavaScriptElement[] getJavaElements();
-
- public IResource getResourceDestination();
- public IJavaScriptElement getJavaElementDestination();
-
- public boolean hasAllInputSet();
-
- public boolean canUpdateReferences();
- public boolean canUpdateQualifiedNames();
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor processor, String[] natures, SharableParticipants shared) throws CoreException;
-
- public String getPolicyId();
-
- public static interface ICopyPolicy extends IReorgPolicy{
- public Change createChange(IProgressMonitor monitor, INewNameQueries queries) throws JavaScriptModelException;
- public ReorgExecutionLog getReorgExecutionLog();
- }
- public static interface IMovePolicy extends IReorgPolicy{
- public Change createChange(IProgressMonitor monitor) throws JavaScriptModelException;
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor monitor) throws CoreException;
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries);
- public boolean isTextualMove();
- public CreateTargetExecutionLog getCreateTargetExecutionLog();
- public void setDestinationCheck(boolean check);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgQueries.java
deleted file mode 100644
index 28444d70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/IReorgQueries.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-public interface IReorgQueries {
-
- public static final int CONFIRM_DELETE_EMPTY_CUS= 2;
-
- public static final int CONFIRM_DELETE_FOLDERS_CONTAINING_SOURCE_FOLDERS= 4;
-
- public static final int CONFIRM_DELETE_GETTER_SETTER= 1;
-
- public static final int CONFIRM_DELETE_LINKED_PARENT= 8;
-
- public static final int CONFIRM_DELETE_REFERENCED_ARCHIVES= 3;
-
- public static final int CONFIRM_OVERWRITING= 6;
-
- public static final int CONFIRM_READ_ONLY_ELEMENTS= 5;
-
- public static final int CONFIRM_SKIPPING= 7;
-
- IConfirmQuery createSkipQuery(String queryTitle, int queryID);
-
- IConfirmQuery createYesNoQuery(String queryTitle, boolean allowCancel, int queryID);
-
- IConfirmQuery createYesYesToAllNoNoToAllQuery(String queryTitle, boolean allowCancel, int queryID);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java
deleted file mode 100644
index 151dd1d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-
-/**
- * Descriptor object of a JDT copy refactoring.
- *
- *
- */
-public final class JDTCopyRefactoringDescriptor extends JDTRefactoringDescriptor {
-
- /** The reorg execution log */
- private final ReorgExecutionLog fLog;
-
- /**
- * Creates a new JDT copy refactoring descriptor.
- *
- * @param log
- * the reorg execution log
- * @param id
- * the unique id of the refactoring
- * @param project
- * the project name, or <code>null</code>
- * @param description
- * the description
- * @param comment
- * the comment, or <code>null</code>
- * @param arguments
- * the argument map
- * @param flags
- * the flags
- */
- public JDTCopyRefactoringDescriptor(final ReorgExecutionLog log, final String id, final String project, final String description, final String comment, final Map arguments, final int flags) {
- super(id, project, description, comment, arguments, flags);
- Assert.isNotNull(log);
- fLog= log;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getArguments() {
- final Map arguments= new HashMap(super.getArguments());
- ReorgPolicyFactory.storeReorgExecutionLog(getProject(), arguments, fLog);
- return arguments;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java
deleted file mode 100644
index 996196ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-
-/**
- * Descriptor object of a JDT move refactoring.
- *
- *
- */
-public final class JDTMoveRefactoringDescriptor extends JDTRefactoringDescriptor {
-
- /** The create target execution log */
- private final CreateTargetExecutionLog fLog;
-
- /**
- * Creates a new JDT move refactoring descriptor.
- *
- * @param log
- * the create target execution log
- * @param id
- * the unique id of the refactoring
- * @param project
- * the project name, or <code>null</code>
- * @param description
- * the description
- * @param comment
- * the comment, or <code>null</code>
- * @param arguments
- * the argument map
- * @param flags
- * the flags
- */
- public JDTMoveRefactoringDescriptor(final CreateTargetExecutionLog log, final String id, final String project, final String description, final String comment, final Map arguments, final int flags) {
- super(id, project, description, comment, arguments, flags);
- Assert.isNotNull(log);
- fLog= log;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getArguments() {
- final Map arguments= new HashMap(super.getArguments());
- ReorgPolicyFactory.storeCreateTargetExecutionLog(getProject(), arguments, fLog);
- return arguments;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyProcessor.java
deleted file mode 100644
index b115b349..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyProcessor.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.CopyProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-public final class JavaCopyProcessor extends CopyProcessor implements IReorgDestinationValidator, IScriptableRefactoring, ICommentProvider {
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.CopyProcessor"; //$NON-NLS-1$
-
- private String fComment;
-
- private ICopyPolicy fCopyPolicy;
-
- private ReorgExecutionLog fExecutionLog;
-
- private INewNameQueries fNewNameQueries;
-
- private IReorgQueries fReorgQueries;
-
- public JavaCopyProcessor(ICopyPolicy copyPolicy) {
- fCopyPolicy= copyPolicy;
- }
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- return fCopyPolicy.canChildrenBeDestinations(javaElement);
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return fCopyPolicy.canChildrenBeDestinations(resource);
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- return fCopyPolicy.canElementBeDestination(javaElement);
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return fCopyPolicy.canElementBeDestination(resource);
- }
-
- public boolean canEnableComment() {
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- Assert.isNotNull(fNewNameQueries, "Missing new name queries"); //$NON-NLS-1$
- Assert.isNotNull(fReorgQueries, "Missing reorg queries"); //$NON-NLS-1$
- pm.beginTask("", 2); //$NON-NLS-1$
- RefactoringStatus result= fCopyPolicy.checkFinalConditions(new SubProgressMonitor(pm, 1), context, fReorgQueries);
- result.merge(context.check(new SubProgressMonitor(pm, 1)));
- return result;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(fCopyPolicy.getResources()))));
- IResource[] javaResources= ReorgUtils.getResources(fCopyPolicy.getJavaElements());
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- Assert.isNotNull(fNewNameQueries);
- Assert.isTrue(fCopyPolicy.getJavaElementDestination() == null || fCopyPolicy.getResourceDestination() == null);
- Assert.isTrue(fCopyPolicy.getJavaElementDestination() != null || fCopyPolicy.getResourceDestination() != null);
- try {
- final DynamicValidationStateChange result= new DynamicValidationStateChange(getChangeName()) {
-
- public Object getAdapter(Class adapter) {
- if (ReorgExecutionLog.class.equals(adapter))
- return fExecutionLog;
- return super.getAdapter(adapter);
- }
-
- public ChangeDescriptor getDescriptor() {
- return fCopyPolicy.getDescriptor();
- }
-
- public Change perform(IProgressMonitor pm2) throws CoreException {
- try {
- super.perform(pm2);
- } catch (OperationCanceledException e) {
- fExecutionLog.markAsCanceled();
- throw e;
- }
- return null;
- }
- };
- Change change= fCopyPolicy.createChange(pm, new MonitoringNewNameQueries(fNewNameQueries, fExecutionLog));
- if (change instanceof CompositeChange) {
- CompositeChange subComposite= (CompositeChange) change;
- result.merge(subComposite);
- } else {
- result.add(change);
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- private String[] getAffectedProjectNatures() throws CoreException {
- String[] jNatures= JavaProcessors.computeAffectedNaturs(fCopyPolicy.getJavaElements());
- String[] rNatures= ResourceProcessors.computeAffectedNatures(fCopyPolicy.getResources());
- Set result= new HashSet();
- result.addAll(Arrays.asList(jNatures));
- result.addAll(Arrays.asList(rNatures));
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- private String getChangeName() {
- return RefactoringCoreMessages.JavaCopyProcessor_changeName;
- }
-
- public String getComment() {
- return fComment;
- }
-
- public Object getCommonParentForInputElements() {
- return new ParentChecker(fCopyPolicy.getResources(), fCopyPolicy.getJavaElements()).getCommonParent();
- }
-
- public Object[] getElements() {
- IJavaScriptElement[] jElements= fCopyPolicy.getJavaElements();
- IResource[] resources= fCopyPolicy.getResources();
- List result= new ArrayList(jElements.length + resources.length);
- result.addAll(Arrays.asList(jElements));
- result.addAll(Arrays.asList(resources));
- return result.toArray();
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return fCopyPolicy.getJavaElements();
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.JavaCopyProcessor_processorName;
- }
-
- public IResource[] getResources() {
- return fCopyPolicy.getResources();
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- setReorgQueries(new NullReorgQueries());
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- fCopyPolicy= ReorgPolicyFactory.createCopyPolicy(status, extended);
- if (fCopyPolicy != null && !status.hasFatalError()) {
- status.merge(fCopyPolicy.initialize(arguments));
- if (!status.hasFatalError()) {
- final ReorgExecutionLog log= ReorgPolicyFactory.loadReorgExecutionLog(status, extended);
- if (log != null && !status.hasFatalError())
- setNewNameQueries(new LoggedNewNameQueries(log));
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return status;
- }
-
- public boolean isApplicable() throws CoreException {
- return fCopyPolicy.canEnable();
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants) throws CoreException {
- RefactoringParticipant[] result= fCopyPolicy.loadParticipants(status, this, getAffectedProjectNatures(), sharedParticipants);
- fExecutionLog= fCopyPolicy.getReorgExecutionLog();
- return result;
- }
-
- public void setComment(String comment) {
- fComment= comment;
- }
-
- public RefactoringStatus setDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- return fCopyPolicy.setDestination(destination);
- }
-
- public RefactoringStatus setDestination(IResource destination) throws JavaScriptModelException {
- return fCopyPolicy.setDestination(destination);
- }
-
- public void setNewNameQueries(INewNameQueries newNameQueries) {
- Assert.isNotNull(newNameQueries);
- fNewNameQueries= newNameQueries;
- }
-
- public void setReorgQueries(IReorgQueries queries) {
- Assert.isNotNull(queries);
- fReorgQueries= queries;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java
deleted file mode 100644
index 5244dbb8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CopyProcessor;
-import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * A copy refactoring which can be initialized with refactoring arguments.
- *
- *
- */
-public final class JavaCopyRefactoring extends CopyRefactoring implements IScriptableRefactoring {
-
- /**
- * Creates a new java copy refactoring.
- *
- * @param processor
- * the copy processor to use
- */
- public JavaCopyRefactoring(CopyProcessor processor) {
- super(processor);
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteProcessor.java
deleted file mode 100644
index 503ee3f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteProcessor.java
+++ /dev/null
@@ -1,884 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.DeleteProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public final class JavaDeleteProcessor extends DeleteProcessor implements IScriptableRefactoring, ICommentProvider {
-
- private static final String ATTRIBUTE_RESOURCES= "resources"; //$NON-NLS-1$
- private static final String ATTRIBUTE_ELEMENTS= "elements"; //$NON-NLS-1$
- private static final String ATTRIBUTE_SUGGEST_ACCESSORS= "accessors"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DELETE_SUBPACKAGES= "subPackages"; //$NON-NLS-1$
-
- private boolean fAccessorsDeleted;
- private boolean fWasCanceled;
- private boolean fSuggestGetterSetterDeletion;
- private Object[] fElements;
- private IResource[] fResources;
- private IJavaScriptElement[] fJavaElements;
- private IReorgQueries fDeleteQueries;
- private DeleteModifications fDeleteModifications;
- private String fComment;
-
- private Change fDeleteChange;
- private boolean fDeleteSubPackages;
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.DeleteProcessor"; //$NON-NLS-1$
-
- public JavaDeleteProcessor(Object[] elements) {
- fElements= elements;
- if (fElements != null) {
- fResources= RefactoringAvailabilityTester.getResources(elements);
- fJavaElements= RefactoringAvailabilityTester.getJavaElements(elements);
- }
- fSuggestGetterSetterDeletion= true;
- fDeleteSubPackages= false;
- fWasCanceled= false;
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public boolean isApplicable() throws CoreException {
- if (fElements.length == 0)
- return false;
- if (fElements.length != fResources.length + fJavaElements.length)
- return false;
- for (int i= 0; i < fResources.length; i++) {
- if (!RefactoringAvailabilityTester.isDeleteAvailable(fResources[i]))
- return false;
- }
- for (int i= 0; i < fJavaElements.length; i++) {
- if (!RefactoringAvailabilityTester.isDeleteAvailable(fJavaElements[i]))
- return false;
- }
- return true;
- }
-
- public boolean needsProgressMonitor() {
- if (fResources != null && fResources.length > 0)
- return true;
- if (fJavaElements != null) {
- for (int i= 0; i < fJavaElements.length; i++) {
- int type= fJavaElements[i].getElementType();
- if (type <= IJavaScriptElement.CLASS_FILE)
- return true;
- }
- }
- return false;
-
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.DeleteRefactoring_7;
- }
-
- public Object[] getElements() {
- return fElements;
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- return fDeleteModifications.loadParticipants(status, this, getAffectedProjectNatures(), shared);
- }
-
- private String[] getAffectedProjectNatures() throws CoreException {
- String[] jNatures= JavaProcessors.computeAffectedNaturs(fJavaElements);
- String[] rNatures= ResourceProcessors.computeAffectedNatures(fResources);
- Set result= new HashSet();
- result.addAll(Arrays.asList(jNatures));
- result.addAll(Arrays.asList(rNatures));
- return (String[])result.toArray(new String[result.size()]);
- }
-
- /*
- * This has to be customizable because when drag and drop is performed on a field,
- * you don't want to suggest deleting getter/setter if only the field was moved.
- */
- public void setSuggestGetterSetterDeletion(boolean suggest){
- fSuggestGetterSetterDeletion= suggest;
- }
-
- public void setDeleteSubPackages(boolean selection) {
- fDeleteSubPackages= selection;
- }
-
- public boolean getDeleteSubPackages() {
- return fDeleteSubPackages;
- }
-
- public boolean hasSubPackagesToDelete() {
- try {
- for (int i= 0; i < fJavaElements.length; i++) {
- if (fJavaElements[i] instanceof IPackageFragment) {
- IPackageFragment packageFragment= (IPackageFragment) fJavaElements[i];
- if (packageFragment.isDefaultPackage())
- continue; // see bug 132576 (can remove this if(..) continue; statement when bug is fixed)
- if (packageFragment.hasSubpackages())
- return true;
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-
- public void setQueries(IReorgQueries queries){
- Assert.isNotNull(queries);
- fDeleteQueries= queries;
- }
-
- public IJavaScriptElement[] getJavaElementsToDelete(){
- return fJavaElements;
- }
-
- public boolean wasCanceled() {
- return fWasCanceled;
- }
-
- public IResource[] getResourcesToDelete(){
- return fResources;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- Assert.isNotNull(fDeleteQueries);//must be set before checking activation
- RefactoringStatus result= new RefactoringStatus();
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotLinked(fResources))));
- IResource[] javaResources= ReorgUtils.getResources(fJavaElements);
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement element= fJavaElements[i];
- if (element instanceof IType && ((IType)element).isAnonymous()) {
- // work around for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=44450
- // result.addFatalError("Currently, there isn't any support to delete an anonymous type.");
- }
- }
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.DeleteRefactoring_1, 1);
- try{
- fWasCanceled= false;
- RefactoringStatus result= new RefactoringStatus();
-
- recalculateElementsToDelete();
-
- checkDirtyCompilationUnits(result);
- checkDirtyResources(result);
- fDeleteModifications= new DeleteModifications();
- fDeleteModifications.delete(fResources);
- fDeleteModifications.delete(fJavaElements);
- List/*<IResource>*/ packageDeletes= fDeleteModifications.postProcess();
-
- TextChangeManager manager= new TextChangeManager();
- fDeleteChange= DeleteChangeCreator.createDeleteChange(manager, fResources, fJavaElements, getProcessorName(), packageDeletes);
-
- ResourceChangeChecker checker= (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory();
- fDeleteModifications.buildDelta(deltaFactory);
- IFile[] files= ResourceUtil.getFiles(manager.getAllCompilationUnits());
- for (int i= 0; i < files.length; i++) {
- deltaFactory.change(files[i]);
- }
- return result;
- } catch (OperationCanceledException e) {
- fWasCanceled= true;
- throw e;
- } catch (JavaScriptModelException e){
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- } finally{
- pm.done();
- }
- }
-
- private void checkDirtyCompilationUnits(RefactoringStatus result) throws CoreException {
- if (fJavaElements == null || fJavaElements.length == 0)
- return;
- for (int je= 0; je < fJavaElements.length; je++) {
- IJavaScriptElement element= fJavaElements[je];
- if (element instanceof IJavaScriptUnit) {
- checkDirtyCompilationUnit(result, (IJavaScriptUnit)element);
- } else if (element instanceof IPackageFragment) {
- IJavaScriptUnit[] units= ((IPackageFragment)element).getJavaScriptUnits();
- for (int u = 0; u < units.length; u++) {
- checkDirtyCompilationUnit(result, units[u]);
- }
- }
- }
- }
-
- private void checkDirtyCompilationUnit(RefactoringStatus result, IJavaScriptUnit cunit) {
- IResource resource= cunit.getResource();
- if (resource == null || resource.getType() != IResource.FILE)
- return;
- checkDirtyFile(result, (IFile)resource);
- }
-
- private void checkDirtyResources(final RefactoringStatus result) throws CoreException {
- for (int i= 0; i < fResources.length; i++) {
- IResource resource= fResources[i];
- resource.accept(new IResourceVisitor() {
- public boolean visit(IResource visitedResource) throws CoreException {
- if (visitedResource instanceof IFile) {
- checkDirtyFile(result, (IFile)visitedResource);
- }
- return true;
- }
- }, IResource.DEPTH_INFINITE, false);
- }
- }
-
- private void checkDirtyFile(RefactoringStatus result, IFile file) {
- if (file == null || !file.exists())
- return;
- ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
- if (buffer != null && buffer.isDirty()) {
- if (buffer.isStateValidated() && buffer.isSynchronized()) {
- result.addWarning(Messages.format(
- RefactoringCoreMessages.JavaDeleteProcessor_unsaved_changes,
- file.getFullPath().toString()));
- } else {
- result.addFatalError(Messages.format(
- RefactoringCoreMessages.JavaDeleteProcessor_unsaved_changes,
- file.getFullPath().toString()));
- }
- }
- }
-
- /*
- * The set of elements that will eventually be deleted may be very different from the set
- * originally selected - there may be fewer, more or different elements.
- * This method is used to calculate the set of elements that will be deleted - if necessary,
- * it asks the user.
- */
- private void recalculateElementsToDelete() throws CoreException {
- //the sequence is critical here
- fAccessorsDeleted= false;
- if (fDeleteSubPackages) /* add subpackages first, to allow removing elements with parents in selection etc. */
- addSubPackages();
-
- removeElementsWithParentsInSelection(); /*ask before adding empty cus - you don't want to ask if you, for example delete
- *the package, in which the cus live*/
- removeUnconfirmedFoldersThatContainSourceFolders(); /* a selected folder may be a parent of a source folder
- * we must inform the user about it and ask if ok to delete the folder*/
- removeUnconfirmedReferencedArchives();
-// addEmptyCusToDelete();
- removeJavaElementsChildrenOfJavaElements();/*because adding cus may create elements (types in cus)
- *whose parents are in selection*/
- confirmDeletingReadOnly(); /*after empty cus - you want to ask for all cus that are to be deleted*/
-
- if (fSuggestGetterSetterDeletion)
- addGettersSetters();/*at the end - this cannot invalidate anything*/
-
- addDeletableParentPackagesOnPackageDeletion(); /* do not change the sequence in fJavaElements after this method */
- }
-
- /**
- * Adds all subpackages of the selected packages to the list of items to be
- * deleted.
- *
- * @throws JavaScriptModelException
- */
- private void addSubPackages() throws JavaScriptModelException {
-
- final Set javaElements= new HashSet();
- for (int i= 0; i < fJavaElements.length; i++) {
- if (fJavaElements[i] instanceof IPackageFragment) {
- javaElements.addAll(Arrays.asList(JavaElementUtil.getPackageAndSubpackages((IPackageFragment) fJavaElements[i])));
- } else {
- javaElements.add(fJavaElements[i]);
- }
- }
-
- fJavaElements= (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]);
- }
-
- /**
- * Add deletable parent packages to the list of items to delete.
- *
- * @throws CoreException
- */
- private void addDeletableParentPackagesOnPackageDeletion() throws CoreException {
-
- final List/* <IPackageFragment */initialPackagesToDelete= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.PACKAGE_FRAGMENT);
-
- if (initialPackagesToDelete.size() == 0)
- return;
-
- // Move from inner to outer packages
- Collections.sort(initialPackagesToDelete, new Comparator() {
- public int compare(Object arg0, Object arg1) {
- IPackageFragment one= (IPackageFragment) arg0;
- IPackageFragment two= (IPackageFragment) arg1;
- return two.getElementName().compareTo(one.getElementName());
- }
- });
-
- // Get resources and java elements which will be deleted as well
- final Set/* <IResource> */deletedChildren= new HashSet();
- deletedChildren.addAll(Arrays.asList(fResources));
- for (int i= 0; i < fJavaElements.length; i++) {
- if (!ReorgUtils.isInsideCompilationUnit(fJavaElements[i]))
- deletedChildren.add(fJavaElements[i].getResource());
- }
-
- // new package list in the right sequence
- final List/* <IPackageFragment */allFragmentsToDelete= new ArrayList();
-
- for (Iterator outerIter= initialPackagesToDelete.iterator(); outerIter.hasNext();) {
- final IPackageFragment currentPackageFragment= (IPackageFragment) outerIter.next();
-
- // The package will at least be cleared
- allFragmentsToDelete.add(currentPackageFragment);
-
- if (canRemoveCompletely(currentPackageFragment, initialPackagesToDelete)) {
-
- final IPackageFragment parent= JavaElementUtil.getParentSubpackage(currentPackageFragment);
- if (parent != null && !initialPackagesToDelete.contains(parent)) {
-
- final List/* <IPackageFragment> */emptyParents= new ArrayList();
- addDeletableParentPackages(parent, initialPackagesToDelete, deletedChildren, emptyParents);
-
- // Add parents in the right sequence (inner to outer)
- allFragmentsToDelete.addAll(emptyParents);
- }
- }
- }
-
- // Remove resources in deleted packages; and the packages as well
- final List/* <IJavaScriptElement> */javaElements= new ArrayList();
- for (int i= 0; i < fJavaElements.length; i++) {
- if (!(fJavaElements[i] instanceof IPackageFragment)) {
- // remove children of deleted packages
- final IPackageFragment frag= (IPackageFragment) fJavaElements[i].getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- if (!allFragmentsToDelete.contains(frag))
- javaElements.add(fJavaElements[i]);
- }
- }
- // Re-add deleted packages - note the (new) sequence
- javaElements.addAll(allFragmentsToDelete);
-
- // Remove resources in deleted folders
- final List/* <IResource> */resources= new ArrayList();
- for (int i= 0; i < fResources.length; i++) {
- IResource parent= fResources[i];
- if (parent.getType() == IResource.FILE)
- parent= parent.getParent();
- if (!deletedChildren.contains(parent))
- resources.add(fResources[i]);
- }
-
- fJavaElements= (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]);
- fResources= (IResource[]) resources.toArray(new IResource[resources.size()]);
- }
-
- /**
- * Returns true if this initially selected package is really deletable
- * (if it has non-selected subpackages, it may only be cleared).
- *
- */
- private boolean canRemoveCompletely(IPackageFragment pack, List packagesToDelete) throws JavaScriptModelException {
- final IPackageFragment[] subPackages= JavaElementUtil.getPackageAndSubpackages(pack);
- for (int i= 0; i < subPackages.length; i++) {
- if (!(subPackages[i].equals(pack)) && !(packagesToDelete.contains(subPackages[i])))
- return false;
- }
- return true;
- }
-
- /**
- * Adds deletable parent packages of the fragment "frag" to the list
- * "deletableParentPackages"; also adds the resources of those packages to the
- * set "resourcesToDelete".
- *
- */
- private void addDeletableParentPackages(IPackageFragment frag, List initialPackagesToDelete, Set resourcesToDelete, List deletableParentPackages)
- throws CoreException {
-
- if (frag.getResource().isLinked()) {
- final IConfirmQuery query= fDeleteQueries.createYesNoQuery(RefactoringCoreMessages.JavaDeleteProcessor_confirm_linked_folder_delete, false, IReorgQueries.CONFIRM_DELETE_LINKED_PARENT);
- if (!query.confirm(Messages.format(RefactoringCoreMessages.JavaDeleteProcessor_delete_linked_folder_question, new String[] { frag.getResource().getName() })))
- return;
- }
-
- final IResource[] children= (((IContainer) frag.getResource())).members();
- for (int i= 0; i < children.length; i++) {
- // Child must be a package fragment already in the list,
- // or a resource which is deleted as well.
- if (!resourcesToDelete.contains(children[i]))
- return;
- }
- resourcesToDelete.add(frag.getResource());
- deletableParentPackages.add(frag);
-
- final IPackageFragment parent= JavaElementUtil.getParentSubpackage(frag);
- if (parent != null && !initialPackagesToDelete.contains(parent))
- addDeletableParentPackages(parent, initialPackagesToDelete, resourcesToDelete, deletableParentPackages);
- }
-
- // ask for confirmation of deletion of all package fragment roots that are
- // on classpaths of other projects
- private void removeUnconfirmedReferencedArchives() throws JavaScriptModelException {
- String queryTitle= RefactoringCoreMessages.DeleteRefactoring_2;
- IConfirmQuery query= fDeleteQueries.createYesYesToAllNoNoToAllQuery(queryTitle, true, IReorgQueries.CONFIRM_DELETE_REFERENCED_ARCHIVES);
- removeUnconfirmedReferencedPackageFragmentRoots(query);
- removeUnconfirmedReferencedArchiveFiles(query);
- }
-
- private void removeUnconfirmedReferencedArchiveFiles(IConfirmQuery query) throws JavaScriptModelException, OperationCanceledException {
- List filesToSkip= new ArrayList(0);
- for (int i= 0; i < fResources.length; i++) {
- IResource resource= fResources[i];
- if (! (resource instanceof IFile))
- continue;
-
- IJavaScriptProject project= JavaScriptCore.create(resource.getProject());
- if (project == null || ! project.exists())
- continue;
- IPackageFragmentRoot root= project.findPackageFragmentRoot(resource.getFullPath());
- if (root == null)
- continue;
- List referencingProjects= Arrays.asList(JavaElementUtil.getReferencingProjects(root));
- if (skipDeletingReferencedRoot(query, root, referencingProjects))
- filesToSkip.add(resource);
- }
- removeFromSetToDelete((IFile[]) filesToSkip.toArray(new IFile[filesToSkip.size()]));
- }
-
- private void removeUnconfirmedReferencedPackageFragmentRoots(IConfirmQuery query) throws JavaScriptModelException, OperationCanceledException {
- List rootsToSkip= new ArrayList(0);
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement element= fJavaElements[i];
- if (! (element instanceof IPackageFragmentRoot))
- continue;
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- ArrayList referencingProjects= new ArrayList(Arrays.asList(JavaElementUtil.getReferencingProjects(root)));
- referencingProjects.remove(root.getJavaScriptProject());
- if (skipDeletingReferencedRoot(query, root, referencingProjects))
- rootsToSkip.add(root);
- }
- removeFromSetToDelete((IJavaScriptElement[]) rootsToSkip.toArray(new IJavaScriptElement[rootsToSkip.size()]));
- }
-
- private static boolean skipDeletingReferencedRoot(IConfirmQuery query, IPackageFragmentRoot root, List referencingProjects) throws OperationCanceledException {
- if (referencingProjects.isEmpty() || root == null || ! root.exists() ||! root.isArchive())
- return false;
- String question= Messages.format(RefactoringCoreMessages.DeleteRefactoring_3, root.getElementName());
- return ! query.confirm(question, referencingProjects.toArray());
- }
-
- private void removeUnconfirmedFoldersThatContainSourceFolders() throws CoreException {
- String queryTitle= RefactoringCoreMessages.DeleteRefactoring_4;
- IConfirmQuery query= fDeleteQueries.createYesYesToAllNoNoToAllQuery(queryTitle, true, IReorgQueries.CONFIRM_DELETE_FOLDERS_CONTAINING_SOURCE_FOLDERS);
- List foldersToSkip= new ArrayList(0);
- for (int i= 0; i < fResources.length; i++) {
- IResource resource= fResources[i];
- if (resource instanceof IFolder){
- IFolder folder= (IFolder)resource;
- if (containsSourceFolder(folder)){
- String question= Messages.format(RefactoringCoreMessages.DeleteRefactoring_5, folder.getName());
- if (! query.confirm(question))
- foldersToSkip.add(folder);
- }
- }
- }
- removeFromSetToDelete((IResource[]) foldersToSkip.toArray(new IResource[foldersToSkip.size()]));
- }
-
- private static boolean containsSourceFolder(IFolder folder) throws CoreException {
- IResource[] subFolders= folder.members();
- for (int i = 0; i < subFolders.length; i++) {
- if (! (subFolders[i] instanceof IFolder))
- continue;
- IJavaScriptElement element= JavaScriptCore.create(folder);
- if (element instanceof IPackageFragmentRoot)
- return true;
- if (element instanceof IPackageFragment)
- continue;
- if (containsSourceFolder((IFolder)subFolders[i]))
- return true;
- }
- return false;
- }
-
- private void removeElementsWithParentsInSelection() {
- ParentChecker parentUtil= new ParentChecker(fResources, fJavaElements);
- parentUtil.removeElementsWithAncestorsOnList(false);
- fJavaElements= parentUtil.getJavaElements();
- fResources= parentUtil.getResources();
- }
-
- private void removeJavaElementsChildrenOfJavaElements(){
- ParentChecker parentUtil= new ParentChecker(fResources, fJavaElements);
- parentUtil.removeElementsWithAncestorsOnList(true);
- fJavaElements= parentUtil.getJavaElements();
- }
-
- public Change createChange(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringCoreMessages.JavaDeleteProcessor_creating_change, 1);
- final Map arguments= new HashMap();
- final String description= fElements.length == 1 ? RefactoringCoreMessages.JavaDeleteProcessor_description_singular : RefactoringCoreMessages.JavaDeleteProcessor_description_plural;
- final IProject resource= getSingleProject();
- final String project= resource != null ? resource.getName() : null;
- final String source= project != null ? Messages.format(RefactoringCoreMessages.JavaDeleteProcessor_project_pattern, project) : RefactoringCoreMessages.JavaDeleteProcessor_workspace;
- final String header= Messages.format(RefactoringCoreMessages.JavaDeleteProcessor_header, new String[] { String.valueOf(fElements.length), source});
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- if (fDeleteSubPackages)
- comment.addSetting(RefactoringCoreMessages.JavaDeleteProcessor_delete_subpackages);
- if (fAccessorsDeleted)
- comment.addSetting(RefactoringCoreMessages.JavaDeleteProcessor_delete_accessors);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.DELETE, project, description, comment.asString(), arguments, flags);
- arguments.put(ATTRIBUTE_DELETE_SUBPACKAGES, Boolean.valueOf(fDeleteSubPackages).toString());
- arguments.put(ATTRIBUTE_SUGGEST_ACCESSORS, Boolean.valueOf(fSuggestGetterSetterDeletion).toString());
- arguments.put(ATTRIBUTE_RESOURCES, new Integer(fResources.length).toString());
- for (int offset= 0; offset < fResources.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.resourceToHandle(fResources[offset]));
- arguments.put(ATTRIBUTE_ELEMENTS, new Integer(fJavaElements.length).toString());
- for (int offset= 0; offset < fJavaElements.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fResources.length + 1), descriptor.elementToHandle(fJavaElements[offset]));
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.DeleteRefactoring_7, new Change[] { fDeleteChange});
- } finally {
- monitor.done();
- }
- }
-
- private IProject getSingleProject() {
- IProject first= null;
- for (int index= 0; index < fElements.length; index++) {
- IProject project= null;
- if (fElements[index] instanceof IJavaScriptElement)
- project= ((IJavaScriptElement) fElements[index]).getJavaScriptProject().getProject();
- else if (fElements[index] instanceof IResource)
- project= ((IResource) fElements[index]).getProject();
- if (project != null) {
- if (first == null)
- first= project;
- else if (!project.equals(first))
- return null;
- }
- }
- return first;
- }
-
- private void addToSetToDelete(IJavaScriptElement[] newElements){
- fJavaElements= ReorgUtils.union(fJavaElements, newElements);
- }
-
- private void removeFromSetToDelete(IResource[] resourcesToNotDelete) {
- fResources= ReorgUtils.setMinus(fResources, resourcesToNotDelete);
- }
-
- private void removeFromSetToDelete(IJavaScriptElement[] elementsToNotDelete) {
- fJavaElements= ReorgUtils.setMinus(fJavaElements, elementsToNotDelete);
- }
-
- private void addGettersSetters() throws JavaScriptModelException {
- IField[] fields= getFields(fJavaElements);
- if (fields.length == 0)
- return;
- //IField -> IFunction[]
- Map getterSetterMapping= createGetterSetterMapping(fields);
- if (getterSetterMapping.isEmpty())
- return;
- removeAlreadySelectedMethods(getterSetterMapping);
- if (getterSetterMapping.isEmpty())
- return;
- fAccessorsDeleted= true;
- List gettersSettersToAdd= getGettersSettersToDelete(getterSetterMapping);
- addToSetToDelete((IFunction[]) gettersSettersToAdd.toArray(new IFunction[gettersSettersToAdd.size()]));
- }
-
- private List getGettersSettersToDelete(Map getterSetterMapping) {
- List gettersSettersToAdd= new ArrayList(getterSetterMapping.size());
- String queryTitle= RefactoringCoreMessages.DeleteRefactoring_8;
- IConfirmQuery getterSetterQuery= fDeleteQueries.createYesYesToAllNoNoToAllQuery(queryTitle, true, IReorgQueries.CONFIRM_DELETE_GETTER_SETTER);
- for (Iterator iter= getterSetterMapping.keySet().iterator(); iter.hasNext();) {
- IField field= (IField) iter.next();
- Assert.isTrue(hasGetter(getterSetterMapping, field) || hasSetter(getterSetterMapping, field));
- String deleteGetterSetter= Messages.format(RefactoringCoreMessages.DeleteRefactoring_9, JavaElementUtil.createFieldSignature(field));
- if (getterSetterQuery.confirm(deleteGetterSetter)){
- if (hasGetter(getterSetterMapping, field))
- gettersSettersToAdd.add(getGetter(getterSetterMapping, field));
- if (hasSetter(getterSetterMapping, field))
- gettersSettersToAdd.add(getSetter(getterSetterMapping, field));
- }
- }
- return gettersSettersToAdd;
- }
-
- //note: modifies the mapping
- private void removeAlreadySelectedMethods(Map getterSetterMapping) {
- List elementsToDelete= Arrays.asList(fJavaElements);
- for (Iterator iter= getterSetterMapping.keySet().iterator(); iter.hasNext();) {
- IField field= (IField) iter.next();
- //remove getter
- IFunction getter= getGetter(getterSetterMapping, field);
- if (getter != null && elementsToDelete.contains(getter))
- removeGetterFromMapping(getterSetterMapping, field);
-
- //remove setter
- IFunction setter= getSetter(getterSetterMapping, field);
- if (setter != null && elementsToDelete.contains(setter))
- removeSetterFromMapping(getterSetterMapping, field);
-
- //both getter and setter already included
- if (! hasGetter(getterSetterMapping, field) && ! hasSetter(getterSetterMapping, field))
- iter.remove();
- }
- }
-
- /*
- * IField -> IFunction[] (array of 2 - [getter, setter], one of which can be null)
- */
- private static Map createGetterSetterMapping(IField[] fields) throws JavaScriptModelException {
- Map result= new HashMap();
- for (int i= 0; i < fields.length; i++) {
- IField field= fields[i];
- IFunction[] getterSetter= getGetterSetter(field);
- if (getterSetter != null)
- result.put(field, getterSetter);
- }
- return result;
- }
- private static boolean hasSetter(Map getterSetterMapping, IField field){
- return getterSetterMapping.containsKey(field) &&
- getSetter(getterSetterMapping, field) != null;
- }
- private static boolean hasGetter(Map getterSetterMapping, IField field){
- return getterSetterMapping.containsKey(field) &&
- getGetter(getterSetterMapping, field) != null;
- }
- private static void removeGetterFromMapping(Map getterSetterMapping, IField field){
- ((IFunction[])getterSetterMapping.get(field))[0]= null;
- }
- private static void removeSetterFromMapping(Map getterSetterMapping, IField field){
- ((IFunction[])getterSetterMapping.get(field))[1]= null;
- }
- private static IFunction getGetter(Map getterSetterMapping, IField field){
- return ((IFunction[])getterSetterMapping.get(field))[0];
- }
- private static IFunction getSetter(Map getterSetterMapping, IField field){
- return ((IFunction[])getterSetterMapping.get(field))[1];
- }
- private static IField[] getFields(IJavaScriptElement[] elements){
- List fields= new ArrayList(3);
- for (int i= 0; i < elements.length; i++) {
- if (elements[i] instanceof IField)
- fields.add(elements[i]);
- }
- return (IField[]) fields.toArray(new IField[fields.size()]);
- }
-
- /*
- * returns an array of 2 [getter, setter] or null if no getter or setter exists
- */
- private static IFunction[] getGetterSetter(IField field) throws JavaScriptModelException {
- IFunction getter= GetterSetterUtil.getGetter(field);
- IFunction setter= GetterSetterUtil.getSetter(field);
- if ((getter != null && getter.exists()) || (setter != null && setter.exists()))
- return new IFunction[]{getter, setter};
- else
- return null;
- }
-
- //----------- read-only confirmation business ------
- private void confirmDeletingReadOnly() throws CoreException {
- if (! ReadOnlyResourceFinder.confirmDeleteOfReadOnlyElements(fJavaElements, fResources, fDeleteQueries))
- throw new OperationCanceledException(); //saying 'no' to this one is like cancelling the whole operation
- }
-
- //----------- empty CUs related method
- private void addEmptyCusToDelete() throws JavaScriptModelException {
- Set cusToEmpty= getCusToEmpty();
- addToSetToDelete((IJavaScriptUnit[]) cusToEmpty.toArray(new IJavaScriptUnit[cusToEmpty.size()]));
- }
-
- private Set getCusToEmpty() throws JavaScriptModelException {
- Set result= new HashSet();
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement element= fJavaElements[i];
- IJavaScriptUnit cu= ReorgUtils.getCompilationUnit(element);
- if (cu != null && ! result.contains(cu) && willHaveAllTopLevelTypesDeleted(cu))
- result.add(cu);
- }
- return result;
- }
-
- private boolean willHaveAllTopLevelTypesDeleted(IJavaScriptUnit cu) throws JavaScriptModelException {
- Set elementSet= new HashSet(Arrays.asList(fJavaElements));
- IType[] topLevelTypes= cu.getTypes();
- for (int i= 0; i < topLevelTypes.length; i++) {
- if (! elementSet.contains(topLevelTypes[i]))
- return false;
- }
- return true;
- }
-
- public boolean canEnableComment() {
- return true;
- }
-
- public String getComment() {
- return fComment;
- }
-
- public void setComment(String comment) {
- fComment= comment;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- setQueries(new NullReorgQueries());
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String subPackages= extended.getAttribute(ATTRIBUTE_DELETE_SUBPACKAGES);
- if (subPackages != null) {
- fDeleteSubPackages= Boolean.valueOf(subPackages).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE_SUBPACKAGES));
- final String suggest= extended.getAttribute(ATTRIBUTE_SUGGEST_ACCESSORS);
- if (suggest != null) {
- fSuggestGetterSetterDeletion= Boolean.valueOf(suggest).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_SUGGEST_ACCESSORS));
- int resourceCount= 0;
- int elementCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_RESOURCES);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- resourceCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_RESOURCES));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_RESOURCES));
- value= extended.getAttribute(ATTRIBUTE_ELEMENTS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- elementCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ELEMENTS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ELEMENTS));
- String handle= null;
- List elements= new ArrayList();
- for (int index= 0; index < resourceCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle);
- if (resource == null || !resource.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(resource, getRefactoring().getName(), IJavaScriptRefactorings.DELETE));
- else
- elements.add(resource);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fResources= (IResource[]) elements.toArray(new IResource[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < elementCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (resourceCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.DELETE));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fJavaElements= (IJavaScriptElement[]) elements.toArray(new IJavaScriptElement[elements.size()]);
- fElements= new Object[fResources.length + fJavaElements.length];
- System.arraycopy(fResources, 0, fElements, 0, fResources.length);
- System.arraycopy(fJavaElements, 0, fElements, fResources.length, fJavaElements.length);
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return status;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java
deleted file mode 100644
index 9449a613..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.DeleteProcessor;
-import org.eclipse.ltk.core.refactoring.participants.DeleteRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * A delete refactoring which can be initialized with refactoring arguments.
- *
- *
- */
-public final class JavaDeleteRefactoring extends DeleteRefactoring implements IScriptableRefactoring {
-
- /**
- * Creates a new java delete refactoring.
- *
- * @param processor
- * the delete processor to use
- */
- public JavaDeleteRefactoring(DeleteProcessor processor) {
- super(processor);
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaElementTransfer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaElementTransfer.java
deleted file mode 100644
index 88f8b203..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaElementTransfer.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class JavaElementTransfer extends ByteArrayTransfer {
-
- /**
- * Singleton instance.
- */
- private static final JavaElementTransfer fInstance= new JavaElementTransfer();
-
- // Create a unique ID to make sure that different Eclipse
- // applications use different "types" of <code>JavaElementTransfer</code>
- private static final String TYPE_NAME= "java-element-transfer-format:" + System.currentTimeMillis() + ":" + fInstance.hashCode(); //$NON-NLS-2$//$NON-NLS-1$
-
- private static final int TYPEID= registerType(TYPE_NAME);
-
- private JavaElementTransfer() {
- }
-
- /**
- * Returns the singleton instance.
- *
- * @return the singleton instance
- */
- public static JavaElementTransfer getInstance() {
- return fInstance;
- }
-
- /* (non-Javadoc)
- * Method declared on Transfer.
- */
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
- /* (non-Javadoc)
- * Returns the type names.
- *
- * @return the list of type names
- */
- protected String[] getTypeNames() {
- return new String[] { TYPE_NAME };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.dnd.Transfer#javaToNative(java.lang.Object, org.eclipse.swt.dnd.TransferData)
- */
- protected void javaToNative(Object data, TransferData transferData) {
- if (!(data instanceof IJavaScriptElement[]))
- return;
-
- IJavaScriptElement[] javaElements= (IJavaScriptElement[]) data;
- /*
- * The element serialization format is:
- * (int) number of element
- * Then, the following for each element:
- * (String) handle identifier
- */
-
- try {
- ByteArrayOutputStream out= new ByteArrayOutputStream();
- DataOutputStream dataOut= new DataOutputStream(out);
-
- //write the number of elements
- dataOut.writeInt(javaElements.length);
-
- //write each element
- for (int i= 0; i < javaElements.length; i++) {
- writeJavaElement(dataOut, javaElements[i]);
- }
-
- //cleanup
- dataOut.close();
- out.close();
- byte[] bytes= out.toByteArray();
- super.javaToNative(bytes, transferData);
- } catch (IOException e) {
- //it's best to send nothing if there were problems
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.dnd.Transfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
- */
- protected Object nativeToJava(TransferData transferData) {
- /*
- * The element serialization format is:
- * (int) number of element
- * Then, the following for each element:
- * (String) handle identifier
- */
-
- byte[] bytes= (byte[]) super.nativeToJava(transferData);
- if (bytes == null)
- return null;
- DataInputStream in= new DataInputStream(new ByteArrayInputStream(bytes));
- try {
- int count= in.readInt();
- IJavaScriptElement[] results= new IJavaScriptElement[count];
- for (int i= 0; i < count; i++) {
- results[i]= readJavaElement(in);
- }
- return results;
- } catch (IOException e) {
- return null;
- }
- }
-
- private IJavaScriptElement readJavaElement(DataInputStream dataIn) throws IOException {
- String handleIdentifier= dataIn.readUTF();
- return JavaScriptCore.create(handleIdentifier);
- }
-
- private static void writeJavaElement(DataOutputStream dataOut, IJavaScriptElement element) throws IOException {
- dataOut.writeUTF(element.getHandleIdentifier());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaMoveProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaMoveProcessor.java
deleted file mode 100644
index 28591e24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaMoveProcessor.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.MoveProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-public final class JavaMoveProcessor extends MoveProcessor implements IScriptableRefactoring, ICommentProvider, IQualifiedNameUpdating, IReorgDestinationValidator {
-
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.MoveProcessor"; //$NON-NLS-1$
-
- private String fComment;
-
- private ICreateTargetQueries fCreateTargetQueries;
-
- private IMovePolicy fMovePolicy;
-
- private IReorgQueries fReorgQueries;
-
- private boolean fWasCanceled;
-
- public JavaMoveProcessor(IMovePolicy policy) {
- fMovePolicy= policy;
- }
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- return fMovePolicy.canChildrenBeDestinations(javaElement);
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return fMovePolicy.canChildrenBeDestinations(resource);
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- return fMovePolicy.canElementBeDestination(javaElement);
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return fMovePolicy.canElementBeDestination(resource);
- }
-
- public boolean canEnableComment() {
- return true;
- }
-
- public boolean canEnableQualifiedNameUpdating() {
- return fMovePolicy.canEnableQualifiedNameUpdating();
- }
-
- public boolean canUpdateQualifiedNames() {
- return fMovePolicy.canUpdateQualifiedNames();
- }
-
- public boolean canUpdateReferences() {
- return fMovePolicy.canUpdateReferences();
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- try {
- Assert.isNotNull(fReorgQueries);
- fWasCanceled= false;
- return fMovePolicy.checkFinalConditions(pm, context, fReorgQueries);
- } catch (OperationCanceledException e) {
- fWasCanceled= true;
- throw e;
- }
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- RefactoringStatus result= new RefactoringStatus();
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(fMovePolicy.getResources()))));
- IResource[] javaResources= ReorgUtils.getResources(fMovePolicy.getJavaElements());
- result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
- return result;
- } finally {
- pm.done();
- }
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- Assert.isTrue(fMovePolicy.getJavaElementDestination() == null || fMovePolicy.getResourceDestination() == null);
- Assert.isTrue(fMovePolicy.getJavaElementDestination() != null || fMovePolicy.getResourceDestination() != null);
- try {
- final DynamicValidationStateChange result= new DynamicValidationStateChange(RefactoringCoreMessages.JavaMoveProcessor_change_name) {
-
- public ChangeDescriptor getDescriptor() {
- return fMovePolicy.getDescriptor();
- }
-
- public Change perform(IProgressMonitor pm2) throws CoreException {
- Change change= super.perform(pm2);
- Change[] changes= getChildren();
- for (int index= 0; index < changes.length; index++) {
- if (!(changes[index] instanceof TextEditBasedChange))
- return null;
- }
- return change;
- }
- };
- CreateTargetExecutionLog log= null;
- if (fCreateTargetQueries instanceof MonitoringCreateTargetQueries) {
- final MonitoringCreateTargetQueries queries= (MonitoringCreateTargetQueries) fCreateTargetQueries;
- final ICreateTargetQueries delegate= queries.getDelegate();
- if (delegate instanceof LoggedCreateTargetQueries)
- log= queries.getCreateTargetExecutionLog();
- }
- if (log != null) {
- final Object[] selected= log.getSelectedElements();
- for (int index= 0; index < selected.length; index++) {
- result.add(new LoggedCreateTargetChange(selected[index], fCreateTargetQueries));
- }
- }
- Change change= fMovePolicy.createChange(pm);
- if (change instanceof CompositeChange) {
- CompositeChange subComposite= (CompositeChange) change;
- result.merge(subComposite);
- } else {
- result.add(change);
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- private String[] getAffectedProjectNatures() throws CoreException {
- String[] jNatures= JavaProcessors.computeAffectedNaturs(fMovePolicy.getJavaElements());
- String[] rNatures= ResourceProcessors.computeAffectedNatures(fMovePolicy.getResources());
- Set result= new HashSet();
- result.addAll(Arrays.asList(jNatures));
- result.addAll(Arrays.asList(rNatures));
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- public String getComment() {
- return fComment;
- }
-
- public Object getCommonParentForInputElements() {
- return new ParentChecker(fMovePolicy.getResources(), fMovePolicy.getJavaElements()).getCommonParent();
- }
-
- public ICreateTargetQuery getCreateTargetQuery() {
- return fMovePolicy.getCreateTargetQuery(fCreateTargetQueries);
- }
-
- protected Object getDestination() {
- IJavaScriptElement je= fMovePolicy.getJavaElementDestination();
- if (je != null)
- return je;
- return fMovePolicy.getResourceDestination();
- }
-
- public Object[] getElements() {
- List result= new ArrayList();
- result.addAll(Arrays.asList(fMovePolicy.getJavaElements()));
- result.addAll(Arrays.asList(fMovePolicy.getResources()));
- return result.toArray();
- }
-
- public String getFilePatterns() {
- return fMovePolicy.getFilePatterns();
- }
-
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return fMovePolicy.getJavaElements();
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.MoveRefactoring_0;
- }
-
- public IResource[] getResources() {
- return fMovePolicy.getResources();
- }
-
- public boolean getUpdateQualifiedNames() {
- return fMovePolicy.getUpdateQualifiedNames();
- }
-
- public boolean getUpdateReferences() {
- if (!canUpdateReferences())
- return false;
- return fMovePolicy.getUpdateReferences();
- }
-
- public boolean hasAllInputSet() {
- return fMovePolicy.hasAllInputSet();
- }
-
- public boolean hasDestinationSet() {
- return fMovePolicy.getJavaElementDestination() != null || fMovePolicy.getResourceDestination() != null;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- setReorgQueries(new NullReorgQueries());
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- fMovePolicy= ReorgPolicyFactory.createMovePolicy(status, arguments);
- if (fMovePolicy != null && !status.hasFatalError()) {
- final CreateTargetExecutionLog log= ReorgPolicyFactory.loadCreateTargetExecutionLog(status, extended);
- if (log != null && !status.hasFatalError()) {
- fMovePolicy.setDestinationCheck(false);
- fCreateTargetQueries= new MonitoringCreateTargetQueries(new LoggedCreateTargetQueries(log), log);
- }
- status.merge(fMovePolicy.initialize(arguments));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return status;
- }
-
- public boolean isApplicable() throws CoreException {
- return fMovePolicy.canEnable();
- }
-
- public boolean isTextualMove() {
- return fMovePolicy.isTextualMove();
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants shared) throws CoreException {
- return fMovePolicy.loadParticipants(status, this, getAffectedProjectNatures(), shared);
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- return fMovePolicy.postCreateChange(participantChanges, pm);
- }
-
- public void setComment(String comment) {
- fComment= comment;
- }
-
- public void setCreateTargetQueries(ICreateTargetQueries queries) {
- Assert.isNotNull(queries);
- fCreateTargetQueries= new MonitoringCreateTargetQueries(queries, fMovePolicy.getCreateTargetExecutionLog());
- }
-
- public RefactoringStatus setDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- return fMovePolicy.setDestination(destination);
- }
-
- public RefactoringStatus setDestination(IResource destination) throws JavaScriptModelException {
- return fMovePolicy.setDestination(destination);
- }
-
- public void setFilePatterns(String patterns) {
- fMovePolicy.setFilePatterns(patterns);
- }
-
- public void setReorgQueries(IReorgQueries queries) {
- Assert.isNotNull(queries);
- fReorgQueries= queries;
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- fMovePolicy.setUpdateQualifiedNames(update);
- }
-
- public void setUpdateReferences(boolean update) {
- fMovePolicy.setUpdateReferences(update);
- }
-
- public boolean wasCanceled() {
- return fWasCanceled;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetChange.java
deleted file mode 100644
index cdc831cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetChange.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JDTChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Change to create move targets during scripting of move refactorings.
- *
- *
- */
-public final class LoggedCreateTargetChange extends JDTChange {
-
- /** The queries */
- private final ICreateTargetQueries fQueries;
-
- /** The selection */
- private Object fSelection;
-
- /**
- * Creates a new logged create target change.
- *
- * @param selection
- * the selection
- * @param queries
- * the queries
- */
- public LoggedCreateTargetChange(Object selection, ICreateTargetQueries queries) {
- fSelection= selection;
- fQueries= queries;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getModifiedElement() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return RefactoringCoreMessages.LoggedCreateTargetChange_change_name;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus isValid(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if (fSelection instanceof IJavaScriptElement) {
- final IJavaScriptElement element= (IJavaScriptElement) fSelection;
- if (!Checks.isAvailable(element))
- RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.RenameResourceChange_does_not_exist, JavaScriptElementLabels.getTextLabel(fSelection, JavaScriptElementLabels.ALL_DEFAULT)));
- } else if (fSelection instanceof IResource) {
- final IResource resource= (IResource) fSelection;
- if (!resource.exists())
- RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.RenameResourceChange_does_not_exist, JavaScriptElementLabels.getTextLabel(fSelection, JavaScriptElementLabels.ALL_DEFAULT)));
- }
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public Change perform(IProgressMonitor monitor) throws CoreException {
- fQueries.createNewPackageQuery().getCreatedTarget(fSelection);
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetQueries.java
deleted file mode 100644
index e396d639..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedCreateTargetQueries.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-
-/**
- * Logged implementation of new create target queries.
- *
- *
- */
-public final class LoggedCreateTargetQueries implements ICreateTargetQueries {
-
- /** Default implementation of create target query */
- private final class CreateTargetQuery implements ICreateTargetQuery {
-
- private void createJavaProject(IProject project) throws CoreException {
- if (!project.exists()) {
- BuildPathsBlock.createProject(project, null, new NullProgressMonitor());
- BuildPathsBlock.addJavaNature(project, new NullProgressMonitor());
- }
- }
-
- private void createPackageFragmentRoot(IPackageFragmentRoot root) throws CoreException {
- final IJavaScriptProject project= root.getJavaScriptProject();
- if (!project.exists())
- createJavaProject(project.getProject());
- final IFolder folder= project.getProject().getFolder(root.getElementName());
- if (!folder.exists())
- CoreUtility.createFolder(folder, true, true, new NullProgressMonitor());
- final List list= Arrays.asList(project.getRawIncludepath());
- list.add(JavaScriptCore.newSourceEntry(folder.getFullPath()));
- project.setRawIncludepath((IIncludePathEntry[]) list.toArray(new IIncludePathEntry[list.size()]), new NullProgressMonitor());
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getCreatedTarget(final Object selection) {
- final Object target= fLog.getCreatedElement(selection);
- if (target instanceof IPackageFragment) {
- final IPackageFragment fragment= (IPackageFragment) target;
- final IJavaScriptElement parent= fragment.getParent();
- if (parent instanceof IPackageFragmentRoot) {
- try {
- final IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
- if (!root.exists())
- createPackageFragmentRoot(root);
- if (!fragment.exists())
- root.createPackageFragment(fragment.getElementName(), true, new NullProgressMonitor());
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- return null;
- }
- }
- } else if (target instanceof IFolder) {
- try {
- final IFolder folder= (IFolder) target;
- final IProject project= folder.getProject();
- if (!project.exists())
- createJavaProject(project);
- if (!folder.exists())
- CoreUtility.createFolder(folder, true, true, new NullProgressMonitor());
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- return null;
- }
- }
- return target;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getNewButtonLabel() {
- return "unused"; //$NON-NLS-1$
- }
- }
-
- /** The create target execution log */
- private final CreateTargetExecutionLog fLog;
-
- /**
- * Creates a new logged create target queries.
- *
- * @param log
- * the create target execution log
- */
- public LoggedCreateTargetQueries(final CreateTargetExecutionLog log) {
- Assert.isNotNull(log);
- fLog= log;
- }
-
- /**
- * {@inheritDoc}
- */
- public ICreateTargetQuery createNewPackageQuery() {
- return new CreateTargetQuery();
- }
-
- /**
- * Returns the create target execution log.
- *
- * @return the create target execution log
- */
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fLog;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedNewNameQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedNewNameQueries.java
deleted file mode 100644
index 234e3d80..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/LoggedNewNameQueries.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-/**
- * Logged implementation of new name queries.
- *
- *
- */
-public final class LoggedNewNameQueries implements INewNameQueries {
-
- /** Default implementation of a new name query */
- private final class NewNameQuery implements INewNameQuery {
-
- /** The name */
- private final String fName;
-
- /** The object */
- private final Object fObject;
-
- /**
- * Creates a new new name query.
- *
- * @param object
- * the object
- * @param name
- * the initial suggested name
- */
- public NewNameQuery(final Object object, String name) {
- fObject= object;
- fName= name;
- }
-
- /**
- * Returns the new name of the compilation unit, without any extension.
- *
- * @return the new name, or <code>null</code>
- */
- private String getCompilationUnitName() {
- String name= fLog.getNewName(fObject);
- if (name != null) {
- int index= name.lastIndexOf('.');
- if (index > 0)
- name= name.substring(0, index);
- }
- return name;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getNewName() {
- String name= null;
- if (fObject instanceof IJavaScriptUnit)
- name= getCompilationUnitName();
- else
- name= fLog.getNewName(fObject);
- if (name == null)
- name= fName;
- return fName;
- }
- }
-
- /** Null implementation of new name query */
- private static final class NullNewNameQuery implements INewNameQuery {
-
- /**
- * {@inheritDoc}
- */
- public String getNewName() {
- return "null"; //$NON-NLS-1$
- }
- }
-
- /** The reorg execution log */
- private final ReorgExecutionLog fLog;
-
- /**
- * Creates a new logged new name queries.
- *
- * @param log
- * the reorg execution log
- */
- public LoggedNewNameQueries(final ReorgExecutionLog log) {
- fLog= log;
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createNewCompilationUnitNameQuery(final IJavaScriptUnit unit, final String initialSuggestedName) {
- return new NewNameQuery(unit, initialSuggestedName);
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createNewPackageFragmentRootNameQuery(final IPackageFragmentRoot root, final String initialSuggestedName) {
- return new NewNameQuery(root, initialSuggestedName);
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createNewPackageNameQuery(final IPackageFragment fragment, final String initialSuggestedName) {
- return new NewNameQuery(fragment, initialSuggestedName);
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createNewResourceNameQuery(final IResource resource, final String initialSuggestedName) {
- return new NewNameQuery(resource, initialSuggestedName);
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createNullQuery() {
- return new NullNewNameQuery();
- }
-
- /**
- * {@inheritDoc}
- */
- public INewNameQuery createStaticQuery(final String name) {
- return new INewNameQuery() {
-
- public String getNewName() {
- return name;
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java
deleted file mode 100644
index 1fecf0b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-/**
- * Creates a new monitoring create target queries.
- *
- *
- */
-public final class MonitoringCreateTargetQueries implements ICreateTargetQueries {
-
- private final ICreateTargetQueries fDelegate;
-
- private final CreateTargetExecutionLog fLog;
-
- /**
- * Creates a new monitoring create target queries.
- *
- * @param delegate
- * the delegate
- * @param log
- * the creation log
- */
- public MonitoringCreateTargetQueries(ICreateTargetQueries delegate, CreateTargetExecutionLog log) {
- fDelegate= delegate;
- fLog= log;
- }
-
- /**
- * {@inheritDoc}
- */
- public ICreateTargetQuery createNewPackageQuery() {
- return new ICreateTargetQuery() {
-
- public Object getCreatedTarget(Object selection) {
- final Object target= fDelegate.createNewPackageQuery().getCreatedTarget(selection);
- fLog.markAsCreated(selection, target);
- return target;
- }
-
- public String getNewButtonLabel() {
- return fDelegate.createNewPackageQuery().getNewButtonLabel();
- }
- };
- }
-
- /**
- * Returns the create target execution log.
- *
- * @return the create target execution log
- */
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fLog;
- }
-
- /**
- * Returns the delegate queries.
- *
- * @return the delegate queries
- */
- public ICreateTargetQueries getDelegate() {
- return fDelegate;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringNewNameQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringNewNameQueries.java
deleted file mode 100644
index 996c68f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringNewNameQueries.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-
-public class MonitoringNewNameQueries implements INewNameQueries {
- private INewNameQueries fDelegate;
- private ReorgExecutionLog fExecutionLog;
- public MonitoringNewNameQueries(INewNameQueries delegate, ReorgExecutionLog log) {
- fDelegate= delegate;
- fExecutionLog= log;
- }
- public INewNameQuery createNewCompilationUnitNameQuery(final IJavaScriptUnit cu, final String initialSuggestedName) {
- return new INewNameQuery() {
- public String getNewName() throws OperationCanceledException {
- String result= fDelegate.createNewCompilationUnitNameQuery(cu, initialSuggestedName).getNewName();
- String newName= JavaModelUtil.getRenamedCUName(cu, result);
- fExecutionLog.setNewName(cu, newName);
- ResourceMapping mapping= JavaElementResourceMapping.create(cu);
- if (mapping != null) {
- fExecutionLog.setNewName(mapping, newName);
- }
- return result;
- }
- };
- }
- public INewNameQuery createNewPackageFragmentRootNameQuery(final IPackageFragmentRoot root, final String initialSuggestedName) {
- return new INewNameQuery() {
- public String getNewName() throws OperationCanceledException {
- String result= fDelegate.createNewPackageFragmentRootNameQuery(root, initialSuggestedName).getNewName();
- fExecutionLog.setNewName(root, result);
- ResourceMapping mapping= JavaElementResourceMapping.create(root);
- if (mapping != null) {
- fExecutionLog.setNewName(mapping, result);
- }
- return result;
- }
- };
- }
- public INewNameQuery createNewPackageNameQuery(final IPackageFragment pack, final String initialSuggestedName) {
- return new INewNameQuery() {
- public String getNewName() throws OperationCanceledException {
- String result= fDelegate.createNewPackageNameQuery(pack, initialSuggestedName).getNewName();
- fExecutionLog.setNewName(pack, result);
- ResourceMapping mapping= JavaElementResourceMapping.create(pack);
- if (mapping != null) {
- int index= result.lastIndexOf('.');
- String newFolderName= index == -1 ? result : result.substring(index + 1);
- fExecutionLog.setNewName(mapping, newFolderName);
- }
- return result;
- }
- };
- }
- public INewNameQuery createNewResourceNameQuery(final IResource res, final String initialSuggestedName) {
- return new INewNameQuery() {
- public String getNewName() throws OperationCanceledException {
- String result= fDelegate.createNewResourceNameQuery(res, initialSuggestedName).getNewName();
- fExecutionLog.setNewName(res, result);
- return result;
- }
- };
- }
- public INewNameQuery createNullQuery() {
- return fDelegate.createNullQuery();
- }
- public INewNameQuery createStaticQuery(String newName) {
- return fDelegate.createStaticQuery(newName);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java
deleted file mode 100644
index 5df98257..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeReferenceMatch;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CollectingSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ReferenceFinderUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class MoveCuUpdateCreator {
-
- private final String fNewPackage;
- private IJavaScriptUnit[] fCus;
- private IPackageFragment fDestination;
-
- private Map fImportRewrites; //IJavaScriptUnit -> ImportEdit
-
- public MoveCuUpdateCreator(IJavaScriptUnit cu, IPackageFragment pack){
- this(new IJavaScriptUnit[]{cu}, pack);
- }
-
- public MoveCuUpdateCreator(IJavaScriptUnit[] cus, IPackageFragment pack){
- Assert.isNotNull(cus);
- Assert.isNotNull(pack);
- fCus= cus;
- fDestination= pack;
- fImportRewrites= new HashMap();
- fNewPackage= fDestination.isDefaultPackage() ? "" : fDestination.getElementName() + '.'; //$NON-NLS-1$
- }
-
- public TextChangeManager createChangeManager(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException{
- pm.beginTask("", 5); //$NON-NLS-1$
- try{
- TextChangeManager changeManager= new TextChangeManager();
- addUpdates(changeManager, new SubProgressMonitor(pm, 4), status);
- addImportRewriteUpdates(changeManager);
- return changeManager;
- } catch (JavaScriptModelException e){
- throw e;
- } catch (CoreException e){
- throw new JavaScriptModelException(e);
- } finally{
- pm.done();
- }
-
- }
-
- private void addImportRewriteUpdates(TextChangeManager changeManager) throws CoreException {
- for (Iterator iter= fImportRewrites.keySet().iterator(); iter.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit) iter.next();
- ImportRewrite importRewrite= (ImportRewrite) fImportRewrites.get(cu);
- if (importRewrite != null && importRewrite.hasRecordedChanges()) {
- TextChangeCompatibility.addTextEdit(changeManager.get(cu), RefactoringCoreMessages.MoveCuUpdateCreator_update_imports, importRewrite.rewriteImports(null));
- }
- }
- }
-
- private void addUpdates(TextChangeManager changeManager, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- pm.beginTask("", fCus.length); //$NON-NLS-1$
- for (int i= 0; i < fCus.length; i++){
- if (pm.isCanceled())
- throw new OperationCanceledException();
-
- addUpdates(changeManager, fCus[i], new SubProgressMonitor(pm, 1), status);
- }
- }
-
- private void addUpdates(TextChangeManager changeManager, IJavaScriptUnit movedUnit, IProgressMonitor pm, RefactoringStatus status) throws CoreException{
- try{
- pm.beginTask("", 3); //$NON-NLS-1$
- pm.subTask(Messages.format(RefactoringCoreMessages.MoveCuUpdateCreator_searching, movedUnit.getElementName()));
-
- if (isInAnotherFragmentOfSamePackage(movedUnit, fDestination)){
- pm.worked(3);
- return;
- }
-
- addImportToSourcePackageTypes(movedUnit, new SubProgressMonitor(pm, 1));
- removeImportsToDestinationPackageTypes(movedUnit);
- addReferenceUpdates(changeManager, movedUnit, new SubProgressMonitor(pm, 2), status);
- } finally{
- pm.done();
- }
- }
-
- private void addReferenceUpdates(TextChangeManager changeManager, IJavaScriptUnit movedUnit, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException, CoreException {
- List cuList= Arrays.asList(fCus);
- SearchResultGroup[] references= getReferences(movedUnit, pm, status);
- for (int i= 0; i < references.length; i++) {
- SearchResultGroup searchResultGroup= references[i];
- IJavaScriptUnit referencingCu= searchResultGroup.getCompilationUnit();
- if (referencingCu == null)
- continue;
-
- boolean simpleReferencesNeedNewImport= simpleReferencesNeedNewImport(movedUnit, referencingCu, cuList);
- SearchMatch[] results= searchResultGroup.getSearchResults();
- for (int j= 0; j < results.length; j++) {
- // TODO: should update type references with results from addImport
- TypeReference reference= (TypeReference) results[j];
- if (reference.isImportDeclaration()) {
- ImportRewrite rewrite= getImportRewrite(referencingCu);
- IImportDeclaration importDecl= (IImportDeclaration) SearchUtils.getEnclosingJavaElement(results[j]);
- if (Flags.isStatic(importDecl.getFlags())) {
- rewrite.removeStaticImport(importDecl.getElementName());
- addStaticImport(movedUnit, importDecl, rewrite);
- } else {
- rewrite.removeImport(importDecl.getElementName());
- rewrite.addImport(createStringForNewImport(movedUnit, importDecl));
- }
- } else if (reference.isQualified()) {
- TextChange textChange= changeManager.get(referencingCu);
- String changeName= RefactoringCoreMessages.MoveCuUpdateCreator_update_references;
- TextEdit replaceEdit= new ReplaceEdit(reference.getOffset(), reference.getSimpleNameStart() - reference.getOffset(), fNewPackage);
- TextChangeCompatibility.addTextEdit(textChange, changeName, replaceEdit);
- } else if (simpleReferencesNeedNewImport) {
- ImportRewrite importEdit= getImportRewrite(referencingCu);
- String typeName= reference.getSimpleName();
- importEdit.addImport(getQualifiedType(fDestination.getElementName(), typeName));
- }
- }
- }
- }
-
- private void addStaticImport(IJavaScriptUnit movedUnit, IImportDeclaration importDecl, ImportRewrite rewrite) {
- String old= importDecl.getElementName();
- int oldPackLength= movedUnit.getParent().getElementName().length();
-
- StringBuffer result= new StringBuffer(fDestination.getElementName());
- if (oldPackLength == 0) // move FROM default package
- result.append('.').append(old);
- else if (result.length() == 0) // move TO default package
- result.append(old.substring(oldPackLength + 1)); // cut "."
- else
- result.append(old.substring(oldPackLength));
- int index= result.lastIndexOf("."); //$NON-NLS-1$
- if (index > 0 && index < result.length() - 1)
- rewrite.addStaticImport(result.substring(0, index), result.substring(index + 1, result.length()), true);
- }
-
- private String getQualifiedType(String packageName, String typeName) {
- if (packageName.length() == 0)
- return typeName;
- else
- return packageName + '.' + typeName;
- }
-
- private String createStringForNewImport(IJavaScriptUnit movedUnit, IImportDeclaration importDecl) {
- String old= importDecl.getElementName();
- int oldPackLength= movedUnit.getParent().getElementName().length();
-
- StringBuffer result= new StringBuffer(fDestination.getElementName());
- if (oldPackLength == 0) // move FROM default package
- result.append('.').append(old);
- else if (result.length() == 0) // move TO default package
- result.append(old.substring(oldPackLength + 1)); // cut "."
- else
- result.append(old.substring(oldPackLength));
- return result.toString();
- }
-
- private void removeImportsToDestinationPackageTypes(IJavaScriptUnit movedUnit) throws CoreException{
- ImportRewrite importEdit= getImportRewrite(movedUnit);
- IType[] destinationTypes= getDestinationPackageTypes();
- for (int i= 0; i < destinationTypes.length; i++) {
- importEdit.removeImport(JavaModelUtil.getFullyQualifiedName(destinationTypes[i]));
- }
- }
-
- private IType[] getDestinationPackageTypes() throws JavaScriptModelException {
- List types= new ArrayList();
- if (fDestination.exists()) {
- IJavaScriptUnit[] cus= fDestination.getJavaScriptUnits();
- for (int i= 0; i < cus.length; i++) {
- types.addAll(Arrays.asList(cus[i].getAllTypes()));
- }
- }
- return (IType[]) types.toArray(new IType[types.size()]);
- }
-
- private void addImportToSourcePackageTypes(IJavaScriptUnit movedUnit, IProgressMonitor pm) throws CoreException{
- List cuList= Arrays.asList(fCus);
- IType[] allCuTypes= movedUnit.getAllTypes();
- IType[] referencedTypes= ReferenceFinderUtil.getTypesReferencedIn(allCuTypes, pm);
- ImportRewrite importEdit= getImportRewrite(movedUnit);
- importEdit.setFilterImplicitImports(false);
- IPackageFragment srcPack= (IPackageFragment)movedUnit.getParent();
- for (int i= 0; i < referencedTypes.length; i++) {
- IType iType= referencedTypes[i];
- if (! iType.exists())
- continue;
- if (! iType.getPackageFragment().equals(srcPack))
- continue;
- if (cuList.contains(iType.getJavaScriptUnit()))
- continue;
- importEdit.addImport(JavaModelUtil.getFullyQualifiedName(iType));
- }
- }
-
- private ImportRewrite getImportRewrite(IJavaScriptUnit cu) throws CoreException{
- if (fImportRewrites.containsKey(cu))
- return (ImportRewrite)fImportRewrites.get(cu);
- ImportRewrite importEdit= StubUtility.createImportRewrite(cu, true);
- fImportRewrites.put(cu, importEdit);
- return importEdit;
- }
-
- private boolean simpleReferencesNeedNewImport(IJavaScriptUnit movedUnit, IJavaScriptUnit referencingCu, List cuList) {
- if (referencingCu.equals(movedUnit))
- return false;
- if (cuList.contains(referencingCu))
- return false;
- if (isReferenceInAnotherFragmentOfSamePackage(referencingCu, movedUnit)) {
- /* Destination package is different from source, since
- * isDestinationAnotherFragmentOfSamePackage(movedUnit) was false in addUpdates(.) */
- return true;
- }
-
- //heuristic
- if (referencingCu.getImport(movedUnit.getParent().getElementName() + ".*").exists()) //$NON-NLS-1$
- return true; // has old star import
- if (referencingCu.getParent().equals(movedUnit.getParent()))
- return true; //is moved away from same package
- return false;
- }
-
- private boolean isReferenceInAnotherFragmentOfSamePackage(IJavaScriptUnit referencingCu, IJavaScriptUnit movedUnit) {
- if (referencingCu == null)
- return false;
- if (! (referencingCu.getParent() instanceof IPackageFragment))
- return false;
- IPackageFragment pack= (IPackageFragment) referencingCu.getParent();
- return isInAnotherFragmentOfSamePackage(movedUnit, pack);
- }
-
- private static boolean isInAnotherFragmentOfSamePackage(IJavaScriptUnit cu, IPackageFragment pack) {
- if (! (cu.getParent() instanceof IPackageFragment))
- return false;
- IPackageFragment cuPack= (IPackageFragment) cu.getParent();
- return ! cuPack.equals(pack) && JavaModelUtil.isSamePackage(cuPack, pack);
- }
-
- private static SearchResultGroup[] getReferences(IJavaScriptUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
- final SearchPattern pattern= RefactoringSearchEngine.createOrPattern(unit.getChildren(), IJavaScriptSearchConstants.REFERENCES);
- if (pattern != null)
- return RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(unit), new Collector(((IPackageFragment) unit.getParent())), new SubProgressMonitor(pm, 1), status);
- return new SearchResultGroup[] {};
- }
-
- private final static class Collector extends CollectingSearchRequestor {
- private IPackageFragment fSource;
- private IScanner fScanner;
-
- public Collector(IPackageFragment source) {
- fSource= source;
- fScanner= ToolFactory.createScanner(false, false, false, false);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.CollectingSearchRequestor#acceptSearchMatch(SearchMatch)
- */
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- /*
- * Processing is done in collector to reuse the buffer which was
- * already required by the search engine to locate the matches.
- */
- // [start, end[ include qualification.
- IJavaScriptElement element= SearchUtils.getEnclosingJavaElement(match);
- int accuracy= match.getAccuracy();
- int start= match.getOffset();
- int length= match.getLength();
- boolean insideDocComment= match.isInsideDocComment();
- IResource res= match.getResource();
- if (element.getAncestor(IJavaScriptElement.IMPORT_DECLARATION) != null) {
- super.acceptSearchMatch(TypeReference.createImportReference(element, accuracy, start, length, insideDocComment, res));
- } else {
- IJavaScriptUnit unit= (IJavaScriptUnit) element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (unit != null) {
- IBuffer buffer= unit.getBuffer();
- String matchText= buffer.getText(start, length);
- if (fSource.isDefaultPackage()) {
- super.acceptSearchMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
- } else {
- // assert: matchText doesn't start nor end with comment
- int simpleNameStart= getLastSimpleNameStart(matchText);
- if (simpleNameStart != 0) {
- super.acceptSearchMatch(TypeReference.createQualifiedReference(element, accuracy, start, length, insideDocComment, res, start + simpleNameStart));
- } else {
- super.acceptSearchMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
- }
- }
- }
- }
- }
-
- private int getLastSimpleNameStart(String reference) {
- fScanner.setSource(reference.toCharArray());
- int lastIdentifierStart= -1;
- try {
- int tokenType= fScanner.getNextToken();
- while (tokenType != ITerminalSymbols.TokenNameEOF) {
- if (tokenType == ITerminalSymbols.TokenNameIdentifier)
- lastIdentifierStart= fScanner.getCurrentTokenStartPosition();
- tokenType= fScanner.getNextToken();
- }
- } catch (InvalidInputException e) {
- JavaScriptPlugin.log(e);
- }
- return lastIdentifierStart;
- }
- }
-
-
- private final static class TypeReference extends TypeReferenceMatch {
- private String fSimpleTypeName;
- private int fSimpleNameStart;
-
- private TypeReference(IJavaScriptElement enclosingElement, int accuracy, int start, int length,
- boolean insideDocComment, IResource resource, int simpleNameStart, String simpleName) {
- super(enclosingElement, accuracy, start, length,
- insideDocComment, SearchEngine.getDefaultSearchParticipant(), resource);
- fSimpleNameStart= simpleNameStart;
- fSimpleTypeName= simpleName;
- }
-
- public static TypeReference createQualifiedReference(IJavaScriptElement enclosingElement, int accuracy, int start, int length,
- boolean insideDocComment, IResource resource, int simpleNameStart) {
- Assert.isTrue(start < simpleNameStart && simpleNameStart < start + length);
- return new TypeReference(enclosingElement, accuracy, start, length, insideDocComment, resource, simpleNameStart, null);
- }
-
- public static TypeReference createImportReference(IJavaScriptElement enclosingElement, int accuracy, int start, int length,
- boolean insideDocComment, IResource resource) {
- return new TypeReference(enclosingElement, accuracy, start, length, insideDocComment, resource, -1, null);
- }
-
- public static TypeReference createSimpleReference(IJavaScriptElement enclosingElement, int accuracy, int start, int length,
- boolean insideDocComment, IResource resource, String simpleName) {
- return new TypeReference(enclosingElement, accuracy, start, length, insideDocComment, resource, -1, simpleName);
- }
-
- public boolean isImportDeclaration() {
- return SearchUtils.getEnclosingJavaElement(this).getAncestor(IJavaScriptElement.IMPORT_DECLARATION) != null;
- }
-
- public boolean isQualified() {
- return fSimpleNameStart != -1;
- }
-
- public boolean isSimpleReference() {
- return fSimpleTypeName != null;
- }
-
- /**
- * @return start offset of simple type name, or -1 iff ! isQualified()
- */
- public int getSimpleNameStart() {
- return fSimpleNameStart;
- }
-
- /**
- * @return simple type name, or null iff ! isSimpleName()
- */
- public String getSimpleName() {
- return fSimpleTypeName;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveModifications.java
deleted file mode 100644
index e674eeec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MoveModifications.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.IParticipantDescriptorFilter;
-import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceModifications;
-
-public class MoveModifications extends RefactoringModifications {
-
- private List fMoves;
- private List fMoveArguments;
- private List fParticipantDescriptorFilter;
-
- public MoveModifications() {
- fMoves= new ArrayList();
- fMoveArguments= new ArrayList();
- fParticipantDescriptorFilter= new ArrayList();
- }
-
- public void move(IResource resource, MoveArguments args) {
- add(resource, args, null);
- }
-
- public void move(IPackageFragmentRoot sourceFolder, MoveArguments arguments) {
- add(sourceFolder, arguments, null);
- IResource sourceResource= sourceFolder.getResource();
- if (sourceResource != null) {
- getResourceModifications().addMove(sourceResource,
- new MoveArguments(getResourceDestination(arguments), arguments.getUpdateReferences()));
- IFile classpath= getClasspathFile(sourceResource);
- if (classpath != null) {
- getResourceModifications().addChanged(classpath);
- }
- classpath= getClasspathFile(getResourceDestination(arguments));
- if (classpath != null) {
- getResourceModifications().addChanged(classpath);
- }
- }
- }
-
- public void move(IPackageFragment pack, MoveArguments args) throws CoreException {
- add(pack, args, null);
- if (pack.getResource() == null)
- return;
- IPackageFragmentRoot javaDestination= (IPackageFragmentRoot) args.getDestination();
- if (javaDestination.getResource() == null)
- return;
- IPackageFragment newPack= javaDestination.getPackageFragment(pack.getElementName());
- if (!pack.hasSubpackages() && !newPack.exists()) {
- // we can do a simple move
- IContainer resourceDestination= newPack.getResource().getParent();
- createIncludingParents(resourceDestination);
- getResourceModifications().addMove(
- pack.getResource(),
- new MoveArguments(resourceDestination, args.getUpdateReferences()));
- } else {
- IContainer resourceSource= (IContainer)pack.getResource();
- IContainer resourceDestination= (IContainer) newPack.getResource();
- createIncludingParents(resourceDestination);
- MoveArguments arguments= new MoveArguments(resourceDestination, args.getUpdateReferences());
- IResource[] resourcesToMove= collectResourcesOfInterest(pack);
- Set allMembers= new HashSet(Arrays.asList(resourceSource.members()));
- for (int i= 0; i < resourcesToMove.length; i++) {
- IResource toMove= resourcesToMove[i];
- getResourceModifications().addMove(toMove, arguments);
- allMembers.remove(toMove);
- }
- for (Iterator iter= allMembers.iterator(); iter.hasNext();) {
- IResource element= (IResource) iter.next();
- if (element instanceof IFile) {
- getResourceModifications().addDelete(element);
- iter.remove();
- }
- }
- if (allMembers.isEmpty()) {
- getResourceModifications().addDelete(resourceSource);
- }
- }
- }
-
- public void move(IJavaScriptUnit unit, MoveArguments args) throws CoreException {
- add(unit, args, null);
- IType[] types= unit.getTypes();
- for (int tt= 0; tt < types.length; tt++) {
- add(types[tt], args, null);
- }
- IResource resourceDestination= getResourceDestination(args);
- if (resourceDestination != null && unit.getResource() != null) {
- getResourceModifications().addMove(unit.getResource(), new MoveArguments(resourceDestination, args.getUpdateReferences()));
- }
- }
-
- public void buildDelta(IResourceChangeDescriptionFactory builder) {
- for (int i= 0; i < fMoves.size(); i++) {
- Object element= fMoves.get(i);
- if (element instanceof IResource) {
- ResourceModifications.buildMoveDelta(builder, (IResource) element, (MoveArguments) fMoveArguments.get(i));
- }
- }
- getResourceModifications().buildDelta(builder);
- }
-
- public void buildValidateEdits(ValidateEditChecker checker) {
- for (Iterator iter= fMoves.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit)element;
- IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE) {
- checker.addFile((IFile)resource);
- }
- }
- }
- }
-
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) {
- List result= new ArrayList();
- for (int i= 0; i < fMoves.size(); i++) {
- result.addAll(Arrays.asList(ParticipantManager.loadMoveParticipants(status,
- owner, fMoves.get(i),
- (MoveArguments) fMoveArguments.get(i),
- (IParticipantDescriptorFilter) fParticipantDescriptorFilter.get(i),
- natures, shared)));
- }
- result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared)));
- return (RefactoringParticipant[]) result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- private void add(Object element, RefactoringArguments args, IParticipantDescriptorFilter filter) {
- Assert.isNotNull(element);
- Assert.isNotNull(args);
- fMoves.add(element);
- fMoveArguments.add(args);
- fParticipantDescriptorFilter.add(filter);
- }
-
- private IResource getResourceDestination(MoveArguments args) {
- Object genericDestination= args.getDestination();
- IResource resourceDestination= null;
- if (genericDestination instanceof IJavaScriptElement) {
- resourceDestination= ((IJavaScriptElement)genericDestination).getResource();
- } else if (genericDestination instanceof IResource) {
- resourceDestination= (IResource)genericDestination;
- }
- return resourceDestination;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java
deleted file mode 100644
index 0690618a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.runtime.OperationCanceledException;
-
-/**
- * Null implementation of reorg queries.
- *
- *
- */
-public final class NullReorgQueries implements IReorgQueries {
-
- /** Null implementation of confirm query */
- private static final class NullConfirmQuery implements IConfirmQuery {
-
- /**
- * {@inheritDoc}
- */
- public boolean confirm(String question) throws OperationCanceledException {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean confirm(String question, Object[] elements) throws OperationCanceledException {
- return true;
- }
- }
-
- /** The null query */
- private static final IConfirmQuery NULL_QUERY= new NullConfirmQuery();
-
- /**
- * {@inheritDoc}
- */
- public IConfirmQuery createSkipQuery(String queryTitle, int queryID) {
- return NULL_QUERY;
- }
-
- /**
- * {@inheritDoc}
- */
- public IConfirmQuery createYesNoQuery(String queryTitle, boolean allowCancel, int queryID) {
- return NULL_QUERY;
- }
-
- /**
- * {@inheritDoc}
- */
- public IConfirmQuery createYesYesToAllNoNoToAllQuery(String queryTitle, boolean allowCancel, int queryID) {
- return NULL_QUERY;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/OverwriteHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/OverwriteHelper.java
deleted file mode 100644
index fadbfbea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/OverwriteHelper.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-class OverwriteHelper {
- private Object fDestination;
- private IFile[] fFiles= new IFile[0];
- private IFolder[] fFolders= new IFolder[0];
- private IJavaScriptUnit[] fCus= new IJavaScriptUnit[0];
- private IPackageFragmentRoot[] fRoots= new IPackageFragmentRoot[0];
- private IPackageFragment[] fPackageFragments= new IPackageFragment[0];
-
- public void setFiles(IFile[] files) {
- Assert.isNotNull(files);
- fFiles= files;
- }
-
- public void setFolders(IFolder[] folders) {
- Assert.isNotNull(folders);
- fFolders= folders;
- }
-
- public void setCus(IJavaScriptUnit[] cus) {
- Assert.isNotNull(cus);
- fCus= cus;
- }
-
- public void setPackageFragmentRoots(IPackageFragmentRoot[] roots) {
- Assert.isNotNull(roots);
- fRoots= roots;
- }
-
- public void setPackages(IPackageFragment[] fragments) {
- Assert.isNotNull(fragments);
- fPackageFragments= fragments;
- }
-
- public IFile[] getFilesWithoutUnconfirmedOnes() {
- return fFiles;
- }
-
- public IFolder[] getFoldersWithoutUnconfirmedOnes() {
- return fFolders;
- }
-
- public IJavaScriptUnit[] getCusWithoutUnconfirmedOnes() {
- return fCus;
- }
-
- public IPackageFragmentRoot[] getPackageFragmentRootsWithoutUnconfirmedOnes() {
- return fRoots;
- }
-
- public IPackageFragment[] getPackagesWithoutUnconfirmedOnes() {
- return fPackageFragments;
- }
-
- public void confirmOverwriting(IReorgQueries reorgQueries, IJavaScriptElement destination) {
- Assert.isNotNull(destination);
- fDestination= destination;
- confirmOverwritting(reorgQueries);
- }
-
- public void confirmOverwriting(IReorgQueries reorgQueries, IResource destination) {
- Assert.isNotNull(destination);
- Assert.isNotNull(reorgQueries);
- fDestination= destination;
- confirmOverwritting(reorgQueries);
- }
-
- private void confirmOverwritting(IReorgQueries reorgQueries) {
- IConfirmQuery overwriteQuery= reorgQueries.createYesYesToAllNoNoToAllQuery(RefactoringCoreMessages.OverwriteHelper_0, true, IReorgQueries.CONFIRM_OVERWRITING);
- IConfirmQuery skipQuery= reorgQueries.createSkipQuery(RefactoringCoreMessages.OverwriteHelper_2, IReorgQueries.CONFIRM_SKIPPING);
- confirmFileOverwritting(overwriteQuery);
- confirmFolderOverwritting(skipQuery);
- confirmCuOverwritting(overwriteQuery);
- confirmPackageFragmentRootOverwritting(skipQuery);
- confirmPackageOverwritting(overwriteQuery);
- }
-
- private void confirmPackageFragmentRootOverwritting(IConfirmQuery overwriteQuery) {
- List toNotOverwrite= new ArrayList(1);
- for (int i= 0; i < fRoots.length; i++) {
- IPackageFragmentRoot root= fRoots[i];
- if (canOverwrite(root) && ! skip(root.getElementName(), overwriteQuery))
- toNotOverwrite.add(root);
- }
- IPackageFragmentRoot[] roots= (IPackageFragmentRoot[]) toNotOverwrite.toArray(new IPackageFragmentRoot[toNotOverwrite.size()]);
- fRoots= ArrayTypeConverter.toPackageFragmentRootArray(ReorgUtils.setMinus(fRoots, roots));
- }
-
- private void confirmCuOverwritting(IConfirmQuery overwriteQuery) {
- List cusToNotOverwrite= new ArrayList(1);
- for (int i= 0; i < fCus.length; i++) {
- IJavaScriptUnit cu= fCus[i];
- if (canOverwrite(cu) && ! overwrite(cu, overwriteQuery))
- cusToNotOverwrite.add(cu);
- }
- IJavaScriptUnit[] cus= (IJavaScriptUnit[]) cusToNotOverwrite.toArray(new IJavaScriptUnit[cusToNotOverwrite.size()]);
- fCus= ArrayTypeConverter.toCuArray(ReorgUtils.setMinus(fCus, cus));
- }
-
- private void confirmFolderOverwritting(IConfirmQuery overwriteQuery) {
- List foldersToNotOverwrite= new ArrayList(1);
- for (int i= 0; i < fFolders.length; i++) {
- IFolder folder= fFolders[i];
- if (canOverwrite(folder) && ! skip(folder.getName(), overwriteQuery))
- foldersToNotOverwrite.add(folder);
- }
- IFolder[] folders= (IFolder[]) foldersToNotOverwrite.toArray(new IFolder[foldersToNotOverwrite.size()]);
- fFolders= ArrayTypeConverter.toFolderArray(ReorgUtils.setMinus(fFolders, folders));
- }
-
- private void confirmFileOverwritting(IConfirmQuery overwriteQuery) {
- List filesToNotOverwrite= new ArrayList(1);
- for (int i= 0; i < fFiles.length; i++) {
- IFile file= fFiles[i];
- if (canOverwrite(file) && ! overwrite(file, overwriteQuery))
- filesToNotOverwrite.add(file);
- }
- IFile[] files= (IFile[]) filesToNotOverwrite.toArray(new IFile[filesToNotOverwrite.size()]);
- fFiles= ArrayTypeConverter.toFileArray(ReorgUtils.setMinus(fFiles, files));
- }
-
- private void confirmPackageOverwritting(IConfirmQuery overwriteQuery){
- List toNotOverwrite= new ArrayList(1);
- for (int i= 0; i < fPackageFragments.length; i++) {
- IPackageFragment pack= fPackageFragments[i];
- if (canOverwrite(pack) && ! overwrite(pack, overwriteQuery))
- toNotOverwrite.add(pack);
- }
- IPackageFragment[] packages= (IPackageFragment[]) toNotOverwrite.toArray(new IPackageFragment[toNotOverwrite.size()]);
- fPackageFragments= ArrayTypeConverter.toPackageArray(ReorgUtils.setMinus(fPackageFragments, packages));
- }
-
- private boolean canOverwrite(IPackageFragment pack) {
- Assert.isTrue(fDestination instanceof IPackageFragmentRoot);
- IPackageFragmentRoot destination= (IPackageFragmentRoot)fDestination;
- return ! destination.equals(pack.getParent()) && destination.getPackageFragment(pack.getElementName()).exists();
- }
-
- private boolean canOverwrite(IResource resource) {
- if (resource == null)
- return false;
- IResource destinationResource= ResourceUtil.getResource(fDestination);
- if (destinationResource.equals(resource.getParent()))
- return false;
- if (destinationResource instanceof IContainer) {
- IContainer container= (IContainer)destinationResource;
- IResource member= container.findMember(resource.getName());
- if (member == null || !member.exists())
- return false;
- if (member instanceof IContainer) {
- try {
- if (((IContainer)member).members().length == 0)
- return false;
- } catch (CoreException e) {
- return true;
- }
- }
- return true;
- }
- return false;
- }
-
- private boolean canOverwrite(IPackageFragmentRoot root) {
- Assert.isTrue(fDestination instanceof IJavaScriptProject);
- IJavaScriptProject destination= (IJavaScriptProject)fDestination;
- IFolder conflict= destination.getProject().getFolder(root.getElementName());
- try {
- return !destination.equals(root.getParent()) && conflict.exists() && conflict.members().length > 0;
- } catch (CoreException e) {
- return true;
- }
- }
-
- private boolean canOverwrite(IJavaScriptUnit cu) {
- if (fDestination instanceof IPackageFragment){
- IPackageFragment destination= (IPackageFragment)fDestination;
- return ! destination.equals(cu.getParent()) && destination.getJavaScriptUnit(cu.getElementName()).exists();
- } else {
- return canOverwrite(ReorgUtils.getResource(cu));
- }
- }
-
- private static boolean overwrite(IResource resource, IConfirmQuery overwriteQuery){
- return overwrite(resource.getName(), overwriteQuery);
- }
-
- private static boolean overwrite(IJavaScriptElement element, IConfirmQuery overwriteQuery){
- return overwrite(element.getElementName(), overwriteQuery);
- }
-
- private static boolean overwrite(String name, IConfirmQuery overwriteQuery){
- String question= Messages.format(RefactoringCoreMessages.OverwriteHelper_1, name);
- return overwriteQuery.confirm(question);
- }
- private static boolean skip(String name, IConfirmQuery overwriteQuery){
- String question= Messages.format(RefactoringCoreMessages.OverwriteHelper_3, name);
- return overwriteQuery.confirm(question);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ParentChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ParentChecker.java
deleted file mode 100644
index a1ad7477..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ParentChecker.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-public class ParentChecker {
- private IResource[] fResources;
- private IJavaScriptElement[] fJavaElements;
-
- public ParentChecker(IResource[] resources, IJavaScriptElement[] javaElements) {
- Assert.isNotNull(resources);
- Assert.isNotNull(javaElements);
- fResources= resources;
- fJavaElements= javaElements;
- }
-
- public boolean haveCommonParent() {
- return getCommonParent() != null;
- }
-
- public Object getCommonParent(){
- if (fJavaElements.length == 0 && fResources.length == 0)
- return null;
- if (! resourcesHaveCommonParent() || ! javaElementsHaveCommonParent())
- return null;
- if (fJavaElements.length == 0){
- IResource commonResourceParent= getCommonResourceParent();
- Assert.isNotNull(commonResourceParent);
- IJavaScriptElement convertedToJava= JavaScriptCore.create(commonResourceParent);
- if (convertedToJava != null && convertedToJava.exists())
- return convertedToJava;
- else
- return commonResourceParent;
- }
- if (fResources.length == 0)
- return getCommonJavaElementParent();
-
- IResource commonResourceParent= getCommonResourceParent();
- IJavaScriptElement commonJavaElementParent= getCommonJavaElementParent();
- Assert.isNotNull(commonJavaElementParent);
- Assert.isNotNull(commonResourceParent);
- IJavaScriptElement convertedToJava= JavaScriptCore.create(commonResourceParent);
- if (convertedToJava == null ||
- ! convertedToJava.exists() ||
- ! commonJavaElementParent.equals(convertedToJava))
- return null;
- return commonJavaElementParent;
- }
-
- private IJavaScriptElement getCommonJavaElementParent() {
- Assert.isNotNull(fJavaElements);
- Assert.isTrue(fJavaElements.length > 0);//safe - checked before
- return fJavaElements[0].getParent();
- }
-
- private IResource getCommonResourceParent() {
- Assert.isNotNull(fResources);
- Assert.isTrue(fResources.length > 0);//safe - checked before
- return fResources[0].getParent();
- }
-
- private boolean javaElementsHaveCommonParent() {
- if (fJavaElements.length == 0)
- return true;
- IJavaScriptElement firstParent= fJavaElements[0].getParent();
- Assert.isNotNull(firstParent); //this should never happen
- for (int i= 1; i < fJavaElements.length; i++) {
- if (! firstParent.equals(fJavaElements[i].getParent()))
- return false;
- }
- return true;
- }
-
- private boolean resourcesHaveCommonParent() {
- if (fResources.length == 0)
- return true;
- IResource firstParent= fResources[0].getParent();
- Assert.isNotNull(firstParent);
- for (int i= 1; i < fResources.length; i++) {
- if (! firstParent.equals(fResources[i].getParent()))
- return false;
- }
- return true;
- }
-
- public IResource[] getResources(){
- return fResources;
- }
-
- public IJavaScriptElement[] getJavaElements(){
- return fJavaElements;
- }
-
- public void removeElementsWithAncestorsOnList(boolean removeOnlyJavaElements) {
- if (! removeOnlyJavaElements){
- removeResourcesDescendantsOfResources();
- removeResourcesDescendantsOfJavaElements();
- }
- removeJavaElementsDescendantsOfJavaElements();
-// removeJavaElementsChildrenOfResources(); //this case is covered by removeUnconfirmedArchives
- }
-
- private void removeResourcesDescendantsOfJavaElements() {
- List subResources= new ArrayList(3);
- for (int i= 0; i < fResources.length; i++) {
- IResource subResource= fResources[i];
- for (int j= 0; j < fJavaElements.length; j++) {
- IJavaScriptElement superElements= fJavaElements[j];
- if (isDescendantOf(subResource, superElements))
- subResources.add(subResource);
- }
- }
- removeFromSetToDelete((IResource[]) subResources.toArray(new IResource[subResources.size()]));
- }
-
- private void removeJavaElementsDescendantsOfJavaElements() {
- List subElements= new ArrayList(3);
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement subElement= fJavaElements[i];
- for (int j= 0; j < fJavaElements.length; j++) {
- IJavaScriptElement superElement= fJavaElements[j];
- if (isDescendantOf(subElement, superElement))
- subElements.add(subElement);
- }
- }
- removeFromSetToDelete((IJavaScriptElement[]) subElements.toArray(new IJavaScriptElement[subElements.size()]));
- }
-
- private void removeResourcesDescendantsOfResources() {
- List subResources= new ArrayList(3);
- for (int i= 0; i < fResources.length; i++) {
- IResource subResource= fResources[i];
- for (int j= 0; j < fResources.length; j++) {
- IResource superResource= fResources[j];
- if (isDescendantOf(subResource, superResource))
- subResources.add(subResource);
- }
- }
- removeFromSetToDelete((IResource[]) subResources.toArray(new IResource[subResources.size()]));
- }
-
- public static boolean isDescendantOf(IResource subResource, IJavaScriptElement superElement) {
- IResource parent= subResource.getParent();
- while(parent != null){
- IJavaScriptElement el= JavaScriptCore.create(parent);
- if (el != null && el.exists() && el.equals(superElement))
- return true;
- parent= parent.getParent();
- }
- return false;
- }
-
- public static boolean isDescendantOf(IJavaScriptElement subElement, IJavaScriptElement superElement) {
- if (subElement.equals(superElement))
- return false;
- IJavaScriptElement parent= subElement.getParent();
- while(parent != null){
- if (parent.equals(superElement))
- return true;
- parent= parent.getParent();
- }
- return false;
- }
-
- public static boolean isDescendantOf(IResource subResource, IResource superResource) {
- return ! subResource.equals(superResource) && superResource.getFullPath().isPrefixOf(subResource.getFullPath());
- }
-
- private void removeFromSetToDelete(IResource[] resourcesToNotDelete) {
- fResources= ReorgUtils.setMinus(fResources, resourcesToNotDelete);
- }
-
- private void removeFromSetToDelete(IJavaScriptElement[] elementsToNotDelete) {
- fJavaElements= ReorgUtils.setMinus(fJavaElements, elementsToNotDelete);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReadOnlyResourceFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReadOnlyResourceFinder.java
deleted file mode 100644
index 0a815d99..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReadOnlyResourceFinder.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-
-
-class ReadOnlyResourceFinder{
- private ReadOnlyResourceFinder(){
- }
-
- static boolean confirmDeleteOfReadOnlyElements(IJavaScriptElement[] javaElements, IResource[] resources, IReorgQueries queries) throws CoreException {
- String queryTitle= RefactoringCoreMessages.ReadOnlyResourceFinder_0;
- String question= RefactoringCoreMessages.ReadOnlyResourceFinder_1;
- return ReadOnlyResourceFinder.confirmOperationOnReadOnlyElements(queryTitle, question, javaElements, resources, queries);
- }
-
- static boolean confirmMoveOfReadOnlyElements(IJavaScriptElement[] javaElements, IResource[] resources, IReorgQueries queries) throws CoreException {
- String queryTitle= RefactoringCoreMessages.ReadOnlyResourceFinder_2;
- String question= RefactoringCoreMessages.ReadOnlyResourceFinder_3;
- return ReadOnlyResourceFinder.confirmOperationOnReadOnlyElements(queryTitle, question, javaElements, resources, queries);
- }
-
- private static boolean confirmOperationOnReadOnlyElements(String queryTitle, String question, IJavaScriptElement[] javaElements, IResource[] resources, IReorgQueries queries) throws CoreException {
- boolean hasReadOnlyResources= ReadOnlyResourceFinder.hasReadOnlyResourcesAndSubResources(javaElements, resources);
- if (hasReadOnlyResources) {
- IConfirmQuery query= queries.createYesNoQuery(queryTitle, false, IReorgQueries.CONFIRM_READ_ONLY_ELEMENTS);
- return query.confirm(question);
- }
- return true;
- }
-
- private static boolean hasReadOnlyResourcesAndSubResources(IJavaScriptElement[] javaElements, IResource[] resources) throws CoreException {
- return (hasReadOnlyResourcesAndSubResources(resources)||
- hasReadOnlyResourcesAndSubResources(javaElements));
- }
-
- private static boolean hasReadOnlyResourcesAndSubResources(IJavaScriptElement[] javaElements) throws CoreException {
- for (int i= 0; i < javaElements.length; i++) {
- if (hasReadOnlyResourcesAndSubResources(javaElements[i]))
- return true;
- }
- return false;
- }
-
- private static boolean hasReadOnlyResourcesAndSubResources(IJavaScriptElement javaElement) throws CoreException {
- switch(javaElement.getElementType()){
- case IJavaScriptElement.CLASS_FILE:
- //if this assert fails, it means that a precondition is missing
- Assert.isTrue(((IClassFile)javaElement).getResource() instanceof IFile);
- //$FALL-THROUGH$
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- IResource resource= ReorgUtils.getResource(javaElement);
- return (resource != null && Resources.isReadOnly(resource));
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- IResource packResource= ReorgUtils.getResource(javaElement);
- if (packResource == null)
- return false;
- IPackageFragment pack= (IPackageFragment)javaElement;
- if (Resources.isReadOnly(packResource))
- return true;
- Object[] nonJava= pack.getNonJavaScriptResources();
- for (int i= 0; i < nonJava.length; i++) {
- Object object= nonJava[i];
- if (object instanceof IResource && hasReadOnlyResourcesAndSubResources((IResource)object))
- return true;
- }
- return hasReadOnlyResourcesAndSubResources(pack.getChildren());
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot root= (IPackageFragmentRoot) javaElement;
- if (root.isArchive())
- return false;
- IResource pfrResource= ReorgUtils.getResource(javaElement);
- if (pfrResource == null)
- return false;
- if (Resources.isReadOnly(pfrResource))
- return true;
- Object[] nonJava1= root.getNonJavaScriptResources();
- for (int i= 0; i < nonJava1.length; i++) {
- Object object= nonJava1[i];
- if (object instanceof IResource && hasReadOnlyResourcesAndSubResources((IResource)object))
- return true;
- }
- return hasReadOnlyResourcesAndSubResources(root.getChildren());
-
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.TYPE:
- return false;
- default:
- Assert.isTrue(false);//not handled here
- return false;
- }
- }
-
- private static boolean hasReadOnlyResourcesAndSubResources(IResource[] resources) throws CoreException {
- for (int i= 0; i < resources.length; i++) {
- if (hasReadOnlyResourcesAndSubResources(resources[i]))
- return true;
- }
- return false;
- }
-
- private static boolean hasReadOnlyResourcesAndSubResources(IResource resource) throws CoreException {
- if (resource.isLinked()) //we don't want to count these because we never actually delete linked resources
- return false;
- if (Resources.isReadOnly(resource))
- return true;
- if (resource instanceof IContainer)
- return hasReadOnlyResourcesAndSubResources(((IContainer)resource).members());
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/RefactoringModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/RefactoringModifications.java
deleted file mode 100644
index c294423c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/RefactoringModifications.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.ResourceModifications;
-
-public abstract class RefactoringModifications {
-
- private ResourceModifications fResourceModifications;
-
- public RefactoringModifications() {
- fResourceModifications= new ResourceModifications();
- }
-
- public ResourceModifications getResourceModifications() {
- return fResourceModifications;
- }
-
- public abstract RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared);
-
- public abstract void buildDelta(IResourceChangeDescriptionFactory builder);
-
- public void buildValidateEdits(ValidateEditChecker checker) {
- // Default implementation does nothing.
- }
-
- protected void createIncludingParents(IContainer container) {
- while (container != null && !(container.exists() || getResourceModifications().willExist(container))) {
- getResourceModifications().addCreate(container);
- container= container.getParent();
- }
- }
-
- protected IResource[] collectResourcesOfInterest(IPackageFragment source) throws CoreException {
- IJavaScriptElement[] children = source.getChildren();
- int childOfInterest = IJavaScriptElement.JAVASCRIPT_UNIT;
- if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
- childOfInterest = IJavaScriptElement.CLASS_FILE;
- }
- ArrayList result = new ArrayList(children.length);
- for (int i = 0; i < children.length; i++) {
- IJavaScriptElement child = children[i];
- if (child.getElementType() == childOfInterest && child.getResource() != null) {
- result.add(child.getResource());
- }
- }
- // Gather non-java resources
- Object[] nonJavaResources = source.getNonJavaScriptResources();
- for (int i= 0; i < nonJavaResources.length; i++) {
- Object element= nonJavaResources[i];
- if (element instanceof IResource) {
- result.add(element);
- }
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-
- protected IFile getClasspathFile(IResource resource) {
- IProject project= resource.getProject();
- if (project == null)
- return null;
- IFolder rscPath = project.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY);
- IResource result= rscPath.findMember(JavaProject.CLASSPATH_FILENAME); //$NON-NLS-1$
- if (result instanceof IFile)
- return (IFile)result;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
deleted file mode 100644
index 08d3da7b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
+++ /dev/null
@@ -1,3474 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.CopyArguments;
-import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CopyCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CopyPackageChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CopyPackageFragmentRootChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CopyResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MoveCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MovePackageChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MovePackageFragmentRootChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MoveResourceChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ImportRewriteUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.Changes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.QualifiedNameSearchResult;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public final class ReorgPolicyFactory {
-
- private static final class ActualSelectionComputer {
-
- private final IJavaScriptElement[] fJavaElements;
-
- private final IResource[] fResources;
-
- public ActualSelectionComputer(IJavaScriptElement[] javaElements, IResource[] resources) {
- fJavaElements= javaElements;
- fResources= resources;
- }
-
- public IJavaScriptElement[] getActualJavaElementsToReorg() throws JavaScriptModelException {
- List result= new ArrayList();
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement element= fJavaElements[i];
- if (element == null)
- continue;
-// if (element instanceof IType) {
-// IType type= (IType) element;
-// IJavaScriptUnit cu= type.getCompilationUnit();
-// if (cu != null && type.getDeclaringType() == null && cu.exists() && cu.getTypes().length == 1 && !result.contains(cu))
-// result.add(cu);
-// else if (!result.contains(type))
-// result.add(type);
-// } else
- if (!result.contains(element)) {
- result.add(element);
- }
- }
- return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- public IResource[] getActualResourcesToReorg() {
- Set javaElementSet= new HashSet(Arrays.asList(fJavaElements));
- List result= new ArrayList();
- for (int i= 0; i < fResources.length; i++) {
- if (fResources[i] == null)
- continue;
- IJavaScriptElement element= JavaScriptCore.create(fResources[i]);
- if (element == null || !element.exists() || !javaElementSet.contains(element))
- if (!result.contains(fResources[i]))
- result.add(fResources[i]);
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
-
- }
- }
-
- private static final class CopyFilesFoldersAndCusPolicy extends FilesFoldersAndCusReorgPolicy implements ICopyPolicy {
-
- private static final String POLICY_COPY_RESOURCE= "org.eclipse.wst.jsdt.ui.copyResources"; //$NON-NLS-1$
-
- private static Change copyCuToPackage(IJavaScriptUnit cu, IPackageFragment dest, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- // XXX workaround for bug 31998 we will have to disable renaming of
- // linked packages (and cus)
- IResource res= ReorgUtils.getResource(cu);
- if (res != null && res.isLinked()) {
- if (ResourceUtil.getResource(dest) instanceof IContainer)
- return copyFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest), nameProposer, copyQueries);
- }
-
- String newName= nameProposer.createNewName(cu, dest);
- Change simpleCopy= new CopyCompilationUnitChange(cu, dest, copyQueries.createStaticQuery(newName));
- if (newName == null || newName.equals(cu.getElementName()))
- return simpleCopy;
-
- try {
- IPath newPath= cu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(cu, newName));
- INewNameQuery nameQuery= copyQueries.createNewCompilationUnitNameQuery(cu, newName);
- return new CreateCopyOfCompilationUnitChange(newPath, cu.getSource(), cu, nameQuery);
- } catch (CoreException e) {
- // Using inferred change
- return simpleCopy;
- }
- }
-
- private static Change copyFileToContainer(IJavaScriptUnit cu, IContainer dest, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- IResource resource= ReorgUtils.getResource(cu);
- return createCopyResourceChange(resource, nameProposer, copyQueries, dest);
- }
-
- private static Change createCopyResourceChange(IResource resource, NewNameProposer nameProposer, INewNameQueries copyQueries, IContainer destination) {
- if (resource == null || destination == null)
- return new NullChange();
- INewNameQuery nameQuery;
- String name= nameProposer.createNewName(resource, destination);
- if (name == null)
- nameQuery= copyQueries.createNullQuery();
- else
- nameQuery= copyQueries.createNewResourceNameQuery(resource, name);
- return new CopyResourceChange(resource, destination, nameQuery);
- }
-
- private CopyModifications fModifications;
-
- private ReorgExecutionLog fReorgExecutionLog;
-
- CopyFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders, IJavaScriptUnit[] cus) {
- super(files, folders, cus);
- }
-
- private Change createChange(IJavaScriptUnit unit, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- IPackageFragment pack= getDestinationAsPackageFragment();
- if (pack != null)
- return copyCuToPackage(unit, pack, nameProposer, copyQueries);
- IContainer container= getDestinationAsContainer();
- return copyFileToContainer(unit, container, nameProposer, copyQueries);
- }
-
- public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) {
- IFile[] file= getFiles();
- IFolder[] folders= getFolders();
- IJavaScriptUnit[] cus= getCus();
- pm.beginTask("", cus.length + file.length + folders.length); //$NON-NLS-1$
- NewNameProposer nameProposer= new NewNameProposer();
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy);
- composite.markAsSynthetic();
- for (int i= 0; i < cus.length; i++) {
- composite.add(createChange(cus[i], nameProposer, copyQueries));
- pm.worked(1);
- }
- if (pm.isCanceled())
- throw new OperationCanceledException();
- for (int i= 0; i < file.length; i++) {
- composite.add(createChange(file[i], nameProposer, copyQueries));
- pm.worked(1);
- }
- if (pm.isCanceled())
- throw new OperationCanceledException();
- for (int i= 0; i < folders.length; i++) {
- composite.add(createChange(folders[i], nameProposer, copyQueries));
- pm.worked(1);
- }
- pm.done();
- return composite;
- }
-
- private Change createChange(IResource resource, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- IContainer dest= getDestinationAsContainer();
- return createCopyResourceChange(resource, nameProposer, copyQueries, dest);
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- protected String getDescriptionPlural() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_FOLDERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_folders;
- case ONLY_FILES:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_files;
- case ONLY_CUS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_units;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_plural;
- }
-
- protected String getDescriptionSingular() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_FOLDERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_folder;
- case ONLY_FILES:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_file;
- case ONLY_CUS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_unit;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_singular;
- }
-
- private Object getDestination() {
- Object result= getDestinationAsPackageFragment();
- if (result != null)
- return result;
- return getDestinationAsContainer();
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
- fModifications= new CopyModifications();
- fReorgExecutionLog= new ReorgExecutionLog();
- CopyArguments jArgs= new CopyArguments(getDestination(), fReorgExecutionLog);
- CopyArguments rArgs= new CopyArguments(getDestinationAsContainer(), fReorgExecutionLog);
- IJavaScriptUnit[] cus= getCus();
- for (int i= 0; i < cus.length; i++) {
- fModifications.copy(cus[i], jArgs, rArgs);
- }
- IResource[] resources= ReorgUtils.union(getFiles(), getFolders());
- for (int i= 0; i < resources.length; i++) {
- fModifications.copy(resources[i], rArgs);
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_COPY_RESOURCE;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- public ReorgExecutionLog getReorgExecutionLog() {
- return fReorgExecutionLog;
- }
- }
-
- private static final class CopyPackageFragmentRootsPolicy extends PackageFragmentRootsReorgPolicy implements ICopyPolicy {
-
- private static final String POLICY_COPY_ROOTS= "org.eclipse.wst.jsdt.ui.copyRoots"; //$NON-NLS-1$
-
- private CopyModifications fModifications;
-
- private ReorgExecutionLog fReorgExecutionLog;
-
- public CopyPackageFragmentRootsPolicy(IPackageFragmentRoot[] roots) {
- super(roots);
- }
-
- private Change createChange(IPackageFragmentRoot root, IJavaScriptProject destination, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- IResource res= root.getResource();
- IProject destinationProject= destination.getProject();
- String newName= nameProposer.createNewName(res, destinationProject);
- INewNameQuery nameQuery;
- if (newName == null)
- nameQuery= copyQueries.createNullQuery();
- else
- nameQuery= copyQueries.createNewPackageFragmentRootNameQuery(root, newName);
- // TODO fix the query problem
- return new CopyPackageFragmentRootChange(root, destinationProject, nameQuery, null);
- }
-
- public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) {
- NewNameProposer nameProposer= new NewNameProposer();
- IPackageFragmentRoot[] roots= getPackageFragmentRoots();
- pm.beginTask("", roots.length); //$NON-NLS-1$
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_source_folder);
- composite.markAsSynthetic();
- IJavaScriptProject destination= getDestinationJavaProject();
- Assert.isNotNull(destination);
- for (int i= 0; i < roots.length; i++) {
- composite.add(createChange(roots[i], destination, nameProposer, copyQueries));
- pm.worked(1);
- }
- pm.done();
- return composite;
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- protected String getDescriptionPlural() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_plural;
- }
-
- protected String getDescriptionSingular() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new CopyModifications();
- fReorgExecutionLog= new ReorgExecutionLog();
- CopyArguments javaArgs= new CopyArguments(getDestinationJavaProject(), fReorgExecutionLog);
- CopyArguments resourceArgs= new CopyArguments(getDestinationJavaProject().getProject(), fReorgExecutionLog);
- IPackageFragmentRoot[] roots= getRoots();
- for (int i= 0; i < roots.length; i++) {
- fModifications.copy(roots[i], javaArgs, resourceArgs);
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_COPY_ROOTS;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- public ReorgExecutionLog getReorgExecutionLog() {
- return fReorgExecutionLog;
- }
- }
-
- private static final class CopyPackagesPolicy extends PackagesReorgPolicy implements ICopyPolicy {
-
- private static final String POLICY_COPY_PACKAGES= "org.eclipse.wst.jsdt.ui.copyPackages"; //$NON-NLS-1$
-
- private CopyModifications fModifications;
-
- private ReorgExecutionLog fReorgExecutionLog;
-
- public CopyPackagesPolicy(IPackageFragment[] packageFragments) {
- super(packageFragments);
- }
-
- private Change createChange(IPackageFragment pack, IPackageFragmentRoot destination, NewNameProposer nameProposer, INewNameQueries copyQueries) {
- String newName= nameProposer.createNewName(pack, destination);
- if (newName == null || JavaScriptConventions.validatePackageName(newName).getSeverity() < IStatus.ERROR) {
- INewNameQuery nameQuery;
- if (newName == null)
- nameQuery= copyQueries.createNullQuery();
- else
- nameQuery= copyQueries.createNewPackageNameQuery(pack, newName);
- return new CopyPackageChange(pack, destination, nameQuery);
- } else {
- if (destination.getResource() instanceof IContainer) {
- IContainer dest= (IContainer) destination.getResource();
- IResource res= pack.getResource();
- INewNameQuery nameQuery= copyQueries.createNewResourceNameQuery(res, newName);
- return new CopyResourceChange(res, dest, nameQuery);
- } else {
- return new NullChange();
- }
- }
- }
-
- public Change createChange(IProgressMonitor pm, INewNameQueries newNameQueries) throws JavaScriptModelException {
- NewNameProposer nameProposer= new NewNameProposer();
- IPackageFragment[] fragments= getPackages();
- pm.beginTask("", fragments.length); //$NON-NLS-1$
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_package);
- composite.markAsSynthetic();
- IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot();
- for (int i= 0; i < fragments.length; i++) {
- composite.add(createChange(fragments[i], root, nameProposer, newNameQueries));
- pm.worked(1);
- }
- pm.done();
- return composite;
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- protected String getDescriptionPlural() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_plural;
- }
-
- protected String getDescriptionSingular() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new CopyModifications();
- fReorgExecutionLog= new ReorgExecutionLog();
- IPackageFragmentRoot destination= getDestinationAsPackageFragmentRoot();
- CopyArguments javaArgs= new CopyArguments(destination, fReorgExecutionLog);
- CopyArguments resourceArgs= new CopyArguments(destination.getResource(), fReorgExecutionLog);
- IPackageFragment[] packages= getPackages();
- for (int i= 0; i < packages.length; i++) {
- fModifications.copy(packages[i], javaArgs, resourceArgs);
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_COPY_PACKAGES;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- public ReorgExecutionLog getReorgExecutionLog() {
- return fReorgExecutionLog;
- }
- }
-
- private static final class CopySubCuElementsPolicy extends SubCuElementReorgPolicy implements ICopyPolicy {
-
- private static final String POLICY_COPY_MEMBERS= "org.eclipse.wst.jsdt.ui.copyMembers"; //$NON-NLS-1$
-
- private CopyModifications fModifications;
-
- private ReorgExecutionLog fReorgExecutionLog;
-
- CopySubCuElementsPolicy(IJavaScriptElement[] javaElements) {
- super(javaElements);
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- return super.canEnable() && (getSourceCu() != null || getSourceClassFile() != null);
- }
-
- public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) throws JavaScriptModelException {
- try {
- JavaScriptUnit sourceCuNode= createSourceCuNode();
- IJavaScriptUnit targetCu= getDestinationCu();
- CompilationUnitRewrite targetRewriter= new CompilationUnitRewrite(targetCu);
- IJavaScriptElement[] javaElements= getJavaElements();
- for (int i= 0; i < javaElements.length; i++) {
- copyToDestination(javaElements[i], targetRewriter, sourceCuNode, targetRewriter.getRoot());
- }
- return createCompilationUnitChange(targetCu, targetRewriter);
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- private JavaScriptUnit createSourceCuNode() {
- Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
- Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- if (getSourceCu() != null)
- parser.setSource(getSourceCu());
- else
- parser.setSource(getSourceClassFile());
- return (JavaScriptUnit) parser.createAST(null);
- }
-
- public IFile[] getAllModifiedFiles() {
- return ReorgUtils.getFiles(new IResource[] { ReorgUtils.getResource(getDestinationCu())});
- }
-
- protected String getDescriptionPlural() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_TYPES:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_types;
- case ONLY_FIELDS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_fields;
- case ONLY_METHODS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_methods;
- case ONLY_INITIALIZERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializers;
- case ONLY_PACKAGE_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_declarations;
- case ONLY_IMPORT_CONTAINERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_containers;
- case ONLY_IMPORT_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_imports;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_plural;
- }
-
- protected String getDescriptionSingular() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_TYPES:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_type;
- case ONLY_FIELDS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_field;
- case ONLY_METHODS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_method;
- case ONLY_INITIALIZERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializer;
- case ONLY_PACKAGE_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_package;
- case ONLY_IMPORT_CONTAINERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_section;
- case ONLY_IMPORT_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_import;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new CopyModifications();
- fReorgExecutionLog= new ReorgExecutionLog();
- CopyArguments args= new CopyArguments(getJavaElementDestination(), fReorgExecutionLog);
- IJavaScriptElement[] javaElements= getJavaElements();
- for (int i= 0; i < javaElements.length; i++) {
- fModifications.copy(javaElements[i], args, null);
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_COPY_MEMBERS;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.COPY;
- }
-
- public ReorgExecutionLog getReorgExecutionLog() {
- return fReorgExecutionLog;
- }
-
- private IClassFile getSourceClassFile() {
- // all have a common parent, so all must be in the same classfile
- // we checked before that the array in not null and not empty
- return (IClassFile) getJavaElements()[0].getAncestor(IJavaScriptElement.CLASS_FILE);
- }
- }
-
- private static abstract class FilesFoldersAndCusReorgPolicy extends ReorgPolicy {
-
- protected static final int ONLY_CUS= 2;
-
- protected static final int ONLY_FILES= 1;
-
- protected static final int ONLY_FOLDERS= 0;
-
- private static IContainer getAsContainer(IResource resDest) {
- if (resDest instanceof IContainer)
- return (IContainer) resDest;
- if (resDest instanceof IFile)
- return ((IFile) resDest).getParent();
- return null;
- }
-
- private IJavaScriptUnit[] fCus;
-
- private IFile[] fFiles;
-
- private IFolder[] fFolders;
-
- public FilesFoldersAndCusReorgPolicy(IFile[] files, IFolder[] folders, IJavaScriptUnit[] cus) {
- fFiles= files;
- fFolders= folders;
- fCus= cus;
- }
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return true;
- default:
- return false;
- }
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return resource instanceof IContainer;
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return true;
- default:
- return false;
- }
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return resource instanceof IProject || resource instanceof IFolder;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries);
- confirmOverwriting(reorgQueries);
- return status;
- }
-
- private void confirmOverwriting(IReorgQueries reorgQueries) {
- OverwriteHelper helper= new OverwriteHelper();
- helper.setFiles(fFiles);
- helper.setFolders(fFolders);
- helper.setCus(fCus);
- IPackageFragment destPack= getDestinationAsPackageFragment();
- if (destPack != null) {
- helper.confirmOverwriting(reorgQueries, destPack);
- } else {
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer != null)
- helper.confirmOverwriting(reorgQueries, destinationAsContainer);
- }
- fFiles= helper.getFilesWithoutUnconfirmedOnes();
- fFolders= helper.getFoldersWithoutUnconfirmedOnes();
- fCus= helper.getCusWithoutUnconfirmedOnes();
- }
-
- protected boolean containsLinkedResources() {
- return ReorgUtils.containsLinkedResources(fFiles) || ReorgUtils.containsLinkedResources(fFolders) || ReorgUtils.containsLinkedResources(fCus);
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) {
- return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- protected final int getContentKind() {
- final int length= fCus.length + fFiles.length + fFolders.length;
- if (length == fCus.length)
- return ONLY_CUS;
- else if (length == fFiles.length)
- return ONLY_FILES;
- else if (length == fFolders.length)
- return ONLY_FOLDERS;
- return -1;
- }
-
- protected final IJavaScriptUnit[] getCus() {
- return fCus;
- }
-
- public final ChangeDescriptor getDescriptor() {
- final Map arguments= new HashMap();
- final int length= fFiles.length + fFolders.length + fCus.length;
- final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural();
- final IProject resource= getSingleProject();
- final String project= resource != null ? resource.getName() : null;
- final String header= Messages.format(getHeaderPattern(), new String[] { String.valueOf(length), getDestinationLabel()});
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags);
- arguments.put(ATTRIBUTE_POLICY, getPolicyId());
- arguments.put(ATTRIBUTE_FILES, new Integer(fFiles.length).toString());
- for (int offset= 0; offset < fFiles.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.resourceToHandle(fFiles[offset]));
- arguments.put(ATTRIBUTE_FOLDERS, new Integer(fFolders.length).toString());
- for (int offset= 0; offset < fFolders.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fFiles.length + 1), descriptor.resourceToHandle(fFolders[offset]));
- arguments.put(ATTRIBUTE_UNITS, new Integer(fCus.length).toString());
- for (int offset= 0; offset < fCus.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fFolders.length + fFiles.length + 1), descriptor.elementToHandle(fCus[offset]));
- arguments.putAll(getRefactoringArguments(project));
- return new RefactoringChangeDescriptor(descriptor);
- }
-
- protected final IContainer getDestinationAsContainer() {
- IResource resDest= getResourceDestination();
- if (resDest != null)
- return getAsContainer(resDest);
- IJavaScriptElement jelDest= getJavaElementDestination();
- Assert.isNotNull(jelDest);
- return getAsContainer(ReorgUtils.getResource(jelDest));
- }
-
- protected final IPackageFragment getDestinationAsPackageFragment() {
- IPackageFragment javaAsPackage= getJavaDestinationAsPackageFragment(getJavaElementDestination());
- if (javaAsPackage != null)
- return javaAsPackage;
- return getResourceDestinationAsPackageFragment(getResourceDestination());
- }
-
- protected final IJavaScriptElement getDestinationContainerAsJavaElement() {
- if (getJavaElementDestination() != null)
- return getJavaElementDestination();
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer == null)
- return null;
- IJavaScriptElement je= JavaScriptCore.create(destinationAsContainer);
- if (je != null && je.exists())
- return je;
- return null;
- }
-
- protected final IFile[] getFiles() {
- return fFiles;
- }
-
- protected final IFolder[] getFolders() {
- return fFolders;
- }
-
- private IPackageFragment getJavaDestinationAsPackageFragment(IJavaScriptElement javaDest) {
- if (javaDest == null || (fCheckDestination && !javaDest.exists()))
- return null;
- if (javaDest instanceof IPackageFragment)
- return (IPackageFragment) javaDest;
- if (javaDest instanceof IPackageFragmentRoot)
- return ((IPackageFragmentRoot) javaDest).getPackageFragment(""); //$NON-NLS-1$
- if (javaDest instanceof IJavaScriptProject) {
- try {
- IPackageFragmentRoot root= ReorgUtils.getCorrespondingPackageFragmentRoot((IJavaScriptProject) javaDest);
- if (root != null)
- return root.getPackageFragment(""); //$NON-NLS-1$
- } catch (JavaScriptModelException e) {
- // fall through
- }
- }
- return (IPackageFragment) javaDest.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- }
-
- public final IJavaScriptElement[] getJavaElements() {
- return fCus;
- }
-
- private IPackageFragment getResourceDestinationAsPackageFragment(IResource resource) {
- if (resource instanceof IFile)
- return getJavaDestinationAsPackageFragment(JavaScriptCore.create(resource.getParent()));
- return null;
- }
-
- public final IResource[] getResources() {
- return ReorgUtils.union(fFiles, fFolders);
- }
-
- private IProject getSingleProject() {
- IProject result= null;
- for (int index= 0; index < fFiles.length; index++) {
- if (result == null)
- result= fFiles[index].getProject();
- else if (!result.equals(fFiles[index].getProject()))
- return null;
- }
- for (int index= 0; index < fFolders.length; index++) {
- if (result == null)
- result= fFolders[index].getProject();
- else if (!result.equals(fFolders[index].getProject()))
- return null;
- }
- for (int index= 0; index < fCus.length; index++) {
- if (result == null)
- result= fCus[index].getJavaScriptProject().getProject();
- else if (!result.equals(fCus[index].getJavaScriptProject().getProject()))
- return null;
- }
- return result;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- int fileCount= 0;
- int folderCount= 0;
- int unitCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_FILES);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- fileCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FILES));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FILES));
- value= extended.getAttribute(ATTRIBUTE_FOLDERS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- folderCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FOLDERS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FOLDERS));
- value= extended.getAttribute(ATTRIBUTE_UNITS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- unitCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_UNITS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_UNITS));
- String handle= null;
- List elements= new ArrayList();
- for (int index= 0; index < fileCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle);
- if (resource == null || !resource.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(resource, getProcessorId(), getRefactoringId()));
- else
- elements.add(resource);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fFiles= (IFile[]) elements.toArray(new IFile[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < folderCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (fileCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle);
- if (resource == null || !resource.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(resource, getProcessorId(), getRefactoringId()));
- else
- elements.add(resource);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fFolders= (IFolder[]) elements.toArray(new IFolder[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < unitCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (folderCount + fileCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId()));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fCus= (IJavaScriptUnit[]) elements.toArray(new IJavaScriptUnit[elements.size()]);
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- status.merge(super.initialize(arguments));
- return status;
- }
-
- private boolean isChildOfOrEqualToAnyFolder(IResource resource) {
- for (int i= 0; i < fFolders.length; i++) {
- IFolder folder= fFolders[i];
- if (folder.equals(resource) || ParentChecker.isDescendantOf(resource, folder))
- return true;
- }
- return false;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- Assert.isNotNull(javaElement);
- if (!fCheckDestination)
- return new RefactoringStatus();
- if (!javaElement.exists())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist0);
- if (javaElement instanceof IJavaScriptModel)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
-
- if (javaElement.isReadOnly())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_readonly);
-
- if (!javaElement.isStructureKnown())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_structure);
-
- if (javaElement instanceof IOpenable) {
- IOpenable openable= (IOpenable) javaElement;
- if (!openable.isConsistent())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inconsistent);
- }
-
- if (javaElement instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) javaElement;
- if (root.isArchive())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_archive);
- if (root.isExternal())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_external);
- }
-
- if (ReorgUtils.isInsideCompilationUnit(javaElement)) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
- }
-
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer == null || isChildOfOrEqualToAnyFolder(destinationAsContainer))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
-
- if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(javaElement))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus verifyDestination(IResource resource) throws JavaScriptModelException {
- Assert.isNotNull(resource);
- if (!resource.exists() || resource.isPhantom())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
- if (!resource.isAccessible())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
-
- if (resource.getType() == IResource.ROOT)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
-
- if (isChildOfOrEqualToAnyFolder(resource))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource);
-
- if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(resource))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
-
- return new RefactoringStatus();
- }
- }
-
- private static final class MoveFilesFoldersAndCusPolicy extends FilesFoldersAndCusReorgPolicy implements IMovePolicy {
-
- private static final String POLICY_MOVE_RESOURCES= "org.eclipse.wst.jsdt.ui.moveResources"; //$NON-NLS-1$
-
- private static Change moveCuToPackage(IJavaScriptUnit cu, IPackageFragment dest) {
- // XXX workaround for bug 31998 we will have to disable renaming of
- // linked packages (and cus)
- IResource resource= cu.getResource();
- if (resource != null && resource.isLinked()) {
- if (ResourceUtil.getResource(dest) instanceof IContainer)
- return moveFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest));
- }
- return new MoveCompilationUnitChange(cu, dest);
- }
-
- private static Change moveFileToContainer(IJavaScriptUnit cu, IContainer dest) {
- return new MoveResourceChange(cu.getResource(), dest);
- }
-
- private TextChangeManager fChangeManager;
-
- private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog();
-
- private String fFilePatterns;
-
- private MoveModifications fModifications;
-
- private QualifiedNameSearchResult fQualifiedNameSearchResult;
-
- private boolean fUpdateQualifiedNames;
-
- private boolean fUpdateReferences;
-
- MoveFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders, IJavaScriptUnit[] cus) {
- super(files, folders, cus);
- fUpdateReferences= true;
- fUpdateQualifiedNames= false;
- fQualifiedNameSearchResult= new QualifiedNameSearchResult();
- }
-
- public boolean canEnableQualifiedNameUpdating() {
- return getCus().length > 0 && !JavaElementUtil.isDefaultPackage(getCommonParent());
- }
-
- public boolean canEnableUpdateReferences() {
- return getCus().length > 0;
- }
-
- public boolean canUpdateQualifiedNames() {
- IPackageFragment pack= getDestinationAsPackageFragment();
- return (canEnableQualifiedNameUpdating() && pack != null && !pack.isDefaultPackage());
- }
-
- public boolean canUpdateReferences() {
- if (getCus().length == 0)
- return false;
- IPackageFragment pack= getDestinationAsPackageFragment();
- if (pack != null && pack.isDefaultPackage())
- return false;
- Object commonParent= getCommonParent();
- if (JavaElementUtil.isDefaultPackage(commonParent))
- return false;
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- try {
- pm.beginTask("", fUpdateQualifiedNames ? 7 : 3); //$NON-NLS-1$
- RefactoringStatus result= new RefactoringStatus();
- confirmMovingReadOnly(reorgQueries);
- fChangeManager= createChangeManager(new SubProgressMonitor(pm, 2), result);
- if (fUpdateQualifiedNames)
- computeQualifiedNameMatches(new SubProgressMonitor(pm, 4));
- result.merge(super.checkFinalConditions(new SubProgressMonitor(pm, 1), context, reorgQueries));
- return result;
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- } finally {
- pm.done();
- }
- }
-
- private void computeQualifiedNameMatches(IProgressMonitor pm) throws JavaScriptModelException {
- if (!fUpdateQualifiedNames)
- return;
- IPackageFragment destination= getDestinationAsPackageFragment();
- if (destination != null) {
- IJavaScriptUnit[] cus= getCus();
- pm.beginTask("", cus.length); //$NON-NLS-1$
- pm.subTask(RefactoringCoreMessages.MoveRefactoring_scanning_qualified_names);
-// for (int i= 0; i < cus.length; i++) {
-// IJavaScriptUnit cu= cus[i];
-// IType[] types= cu.getTypes();
-// IProgressMonitor typesMonitor= new SubProgressMonitor(pm, 1);
-// typesMonitor.beginTask("", types.length); //$NON-NLS-1$
-// for (int j= 0; j < types.length; j++) {
-// handleType(types[j], destination, new SubProgressMonitor(typesMonitor, 1));
-// if (typesMonitor.isCanceled())
-// throw new OperationCanceledException();
-// }
-// typesMonitor.done();
-// }
- }
- pm.done();
- }
-
- private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException {
- if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries))
- throw new OperationCanceledException();
- }
-
- private Change createChange(IJavaScriptUnit cu) {
- IPackageFragment pack= getDestinationAsPackageFragment();
- if (pack != null)
- return moveCuToPackage(cu, pack);
- IContainer container= getDestinationAsContainer();
- if (container == null)
- return new NullChange();
- return moveFileToContainer(cu, container);
- }
-
- public Change createChange(IProgressMonitor pm) throws JavaScriptModelException {
- if (!fUpdateReferences) {
- return createSimpleMoveChange(pm);
- } else {
- return createReferenceUpdatingMoveChange(pm);
- }
- }
-
- private Change createChange(IResource res) {
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer == null)
- return new NullChange();
- return new MoveResourceChange(res, destinationAsContainer);
- }
-
- private TextChangeManager createChangeManager(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- pm.beginTask("", 1);//$NON-NLS-1$
- try {
- if (!fUpdateReferences)
- return new TextChangeManager();
-
- IPackageFragment packageDest= getDestinationAsPackageFragment();
- if (packageDest != null) {
- MoveCuUpdateCreator creator= new MoveCuUpdateCreator(getCus(), packageDest);
- return creator.createChangeManager(new SubProgressMonitor(pm, 1), status);
- } else
- return new TextChangeManager();
- } finally {
- pm.done();
- }
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- private Change createReferenceUpdatingMoveChange(IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 2 + (fUpdateQualifiedNames ? 1 : 0)); //$NON-NLS-1$
- try {
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move);
- composite.markAsSynthetic();
- // XX workaround for bug 13558
- // <workaround>
- if (fChangeManager == null) {
- fChangeManager= createChangeManager(new SubProgressMonitor(pm, 1), new RefactoringStatus());
- // TODO: non-CU matches silently dropped
- RefactoringStatus status= Checks.validateModifiesFiles(getAllModifiedFiles(), null);
- if (status.hasFatalError())
- fChangeManager= new TextChangeManager();
- }
- // </workaround>
-
- composite.merge(new CompositeChange(RefactoringCoreMessages.MoveRefactoring_reorganize_elements, fChangeManager.getAllChanges()));
-
- Change fileMove= createSimpleMoveChange(new SubProgressMonitor(pm, 1));
- if (fileMove instanceof CompositeChange) {
- composite.merge(((CompositeChange) fileMove));
- } else {
- composite.add(fileMove);
- }
- return composite;
- } finally {
- pm.done();
- }
- }
-
- private Change createSimpleMoveChange(IProgressMonitor pm) {
- CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move);
- result.markAsSynthetic();
- IFile[] files= getFiles();
- IFolder[] folders= getFolders();
- IJavaScriptUnit[] cus= getCus();
- pm.beginTask("", files.length + folders.length + cus.length); //$NON-NLS-1$
- for (int i= 0; i < files.length; i++) {
- result.add(createChange(files[i]));
- pm.worked(1);
- }
- if (pm.isCanceled())
- throw new OperationCanceledException();
- for (int i= 0; i < folders.length; i++) {
- result.add(createChange(folders[i]));
- pm.worked(1);
- }
- if (pm.isCanceled())
- throw new OperationCanceledException();
- for (int i= 0; i < cus.length; i++) {
- result.add(createChange(cus[i]));
- pm.worked(1);
- }
- pm.done();
- return result;
- }
-
- public IFile[] getAllModifiedFiles() {
- Set result= new HashSet();
- result.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits())));
- result.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles()));
- if (getDestinationAsPackageFragment() != null && getUpdateReferences())
- result.addAll(Arrays.asList(ResourceUtil.getFiles(getCus())));
- return (IFile[]) result.toArray(new IFile[result.size()]);
- }
-
- private Object getCommonParent() {
- return new ParentChecker(getResources(), getJavaElements()).getCommonParent();
- }
-
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fCreateTargetExecutionLog;
- }
-
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) {
- return createQueries.createNewPackageQuery();
- }
-
- protected String getDescriptionPlural() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_FOLDERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_folders;
- case ONLY_FILES:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_files;
- case ONLY_CUS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_units;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_move_description_plural;
- }
-
- protected String getDescriptionSingular() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_FOLDERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_folder;
- case ONLY_FILES:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_file;
- case ONLY_CUS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_unit;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_move_description_singular;
- }
-
- public String getFilePatterns() {
- return fFilePatterns;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new MoveModifications();
- IPackageFragment pack= getDestinationAsPackageFragment();
- IContainer container= getDestinationAsContainer();
- Object unitDestination= null;
- if (pack != null)
- unitDestination= pack;
- else
- unitDestination= container;
-
- // don't use fUpdateReferences directly since it is only valid if
- // canUpdateReferences is true
- boolean updateReferenes= canUpdateReferences() && getUpdateReferences();
- if (unitDestination != null) {
- IJavaScriptUnit[] units= getCus();
- for (int i= 0; i < units.length; i++) {
- fModifications.move(units[i], new MoveArguments(unitDestination, updateReferenes));
- }
- }
- if (container != null) {
- IFile[] files= getFiles();
- for (int i= 0; i < files.length; i++) {
- fModifications.move(files[i], new MoveArguments(container, updateReferenes));
- }
- IFolder[] folders= getFolders();
- for (int i= 0; i < folders.length; i++) {
- fModifications.move(folders[i], new MoveArguments(container, updateReferenes));
- }
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_MOVE_RESOURCES;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- protected Map getRefactoringArguments(String project) {
- final Map arguments= new HashMap();
- arguments.putAll(super.getRefactoringArguments(project));
- if (fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
- arguments.put(ATTRIBUTE_PATTERNS, fFilePatterns);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES, Boolean.valueOf(fUpdateReferences).toString());
- arguments.put(ATTRIBUTE_QUALIFIED, Boolean.valueOf(fUpdateQualifiedNames).toString());
- return arguments;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- public boolean getUpdateQualifiedNames() {
- return fUpdateQualifiedNames;
- }
-
- public boolean getUpdateReferences() {
- return fUpdateReferences;
- }
-
- private void handleType(IType type, IPackageFragment destination, IProgressMonitor pm) {
- QualifiedNameFinder.process(fQualifiedNameSearchResult, type.getFullyQualifiedName(), destination.getElementName() + "." + type.getTypeQualifiedName(), //$NON-NLS-1$
- fFilePatterns, type.getJavaScriptProject().getProject(), pm);
- }
-
- public boolean hasAllInputSet() {
- return super.hasAllInputSet() && !canUpdateReferences() && !canUpdateQualifiedNames();
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String patterns= extended.getAttribute(ATTRIBUTE_PATTERNS);
- if (patterns != null && !"".equals(patterns)) //$NON-NLS-1$
- fFilePatterns= patterns;
- else
- fFilePatterns= ""; //$NON-NLS-1$
- final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES);
- if (references != null) {
- fUpdateReferences= Boolean.valueOf(references).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES));
- final String qualified= extended.getAttribute(ATTRIBUTE_QUALIFIED);
- if (qualified != null) {
- fUpdateQualifiedNames= Boolean.valueOf(qualified).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_QUALIFIED));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return super.initialize(arguments);
- }
-
- public boolean isTextualMove() {
- return false;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- if (fQualifiedNameSearchResult != null) {
- return fQualifiedNameSearchResult.getSingleChange(Changes.getModifiedFiles(participantChanges));
- } else {
- return null;
- }
- }
-
- public void setDestinationCheck(boolean check) {
- fCheckDestination= check;
- }
-
- public void setFilePatterns(String patterns) {
- Assert.isNotNull(patterns);
- fFilePatterns= patterns;
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- fUpdateQualifiedNames= update;
- }
-
- public void setUpdateReferences(boolean update) {
- fUpdateReferences= update;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- RefactoringStatus superStatus= super.verifyDestination(destination);
- if (superStatus.hasFatalError())
- return superStatus;
-
- Object commonParent= new ParentChecker(getResources(), getJavaElements()).getCommonParent();
- if (destination.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer != null && destinationAsContainer.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
- IPackageFragment destinationAsPackage= getDestinationAsPackageFragment();
- if (destinationAsPackage != null && destinationAsPackage.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
-
- return superStatus;
- }
-
- protected RefactoringStatus verifyDestination(IResource destination) throws JavaScriptModelException {
- RefactoringStatus superStatus= super.verifyDestination(destination);
- if (superStatus.hasFatalError())
- return superStatus;
-
- Object commonParent= getCommonParent();
- if (destination.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
- IContainer destinationAsContainer= getDestinationAsContainer();
- if (destinationAsContainer != null && destinationAsContainer.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
- IJavaScriptElement destinationContainerAsPackage= getDestinationContainerAsJavaElement();
- if (destinationContainerAsPackage != null && destinationContainerAsPackage.equals(commonParent))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
-
- return superStatus;
- }
- }
-
- private static final class MovePackageFragmentRootsPolicy extends PackageFragmentRootsReorgPolicy implements IMovePolicy {
-
- private static final String POLICY_MOVE_ROOTS= "org.eclipse.wst.jsdt.ui.moveRoots"; //$NON-NLS-1$
-
- private static boolean isParentOfAny(IJavaScriptProject javaProject, IPackageFragmentRoot[] roots) {
- for (int i= 0; i < roots.length; i++) {
- if (ReorgUtils.isParentInWorkspaceOrOnDisk(roots[i], javaProject))
- return true;
- }
- return false;
- }
-
- private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog();
-
- private MoveModifications fModifications;
-
- MovePackageFragmentRootsPolicy(IPackageFragmentRoot[] roots) {
- super(roots);
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- if (!super.canEnable())
- return false;
- IPackageFragmentRoot[] roots= getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (roots[i].isReadOnly() && !(roots[i].isArchive())) {
- final ResourceAttributes attributes= roots[i].getResource().getResourceAttributes();
- if (attributes == null || attributes.isReadOnly())
- return false;
- }
- }
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- try {
- RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries);
- confirmMovingReadOnly(reorgQueries);
- return status;
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException {
- if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries))
- throw new OperationCanceledException();
- }
-
- private Change createChange(IPackageFragmentRoot root, IJavaScriptProject destination) {
- // /XXX fix the query
- return new MovePackageFragmentRootChange(root, destination.getProject(), null);
- }
-
- public Change createChange(IProgressMonitor pm) throws JavaScriptModelException {
- IPackageFragmentRoot[] roots= getPackageFragmentRoots();
- pm.beginTask("", roots.length); //$NON-NLS-1$
- CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_source_folder);
- composite.markAsSynthetic();
- IJavaScriptProject destination= getDestinationJavaProject();
- Assert.isNotNull(destination);
- for (int i= 0; i < roots.length; i++) {
- composite.add(createChange(roots[i], destination));
- pm.worked(1);
- }
- pm.done();
- return composite;
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fCreateTargetExecutionLog;
- }
-
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) {
- return null;
- }
-
- protected String getDescriptionPlural() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_plural;
- }
-
- protected String getDescriptionSingular() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new MoveModifications();
- IJavaScriptProject destination= getDestinationJavaProject();
- boolean updateReferences= canUpdateReferences() && getUpdateReferences();
- if (destination != null) {
- IPackageFragmentRoot[] roots= getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- fModifications.move(roots[i], new MoveArguments(destination, updateReferences));
- }
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_MOVE_ROOTS;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- public boolean isTextualMove() {
- return false;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- return null;
- }
-
- public void setDestinationCheck(boolean check) {
- fCheckDestination= check;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- RefactoringStatus superStatus= super.verifyDestination(javaElement);
- if (superStatus.hasFatalError())
- return superStatus;
- IJavaScriptProject javaProject= getDestinationJavaProject();
- if (isParentOfAny(javaProject, getPackageFragmentRoots()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent);
- return superStatus;
- }
- }
-
- private static final class MovePackagesPolicy extends PackagesReorgPolicy implements IMovePolicy {
-
- private static final String POLICY_MOVE_PACKAGES= "org.eclipse.wst.jsdt.ui.movePackages"; //$NON-NLS-1$
-
- private static boolean isParentOfAny(IPackageFragmentRoot root, IPackageFragment[] fragments) {
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- if (ReorgUtils.isParentInWorkspaceOrOnDisk(fragment, root))
- return true;
- }
- return false;
- }
-
- private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog();
-
- private MoveModifications fModifications;
-
- MovePackagesPolicy(IPackageFragment[] packageFragments) {
- super(packageFragments);
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- try {
- RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries);
- confirmMovingReadOnly(reorgQueries);
- return status;
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException {
- if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries))
- throw new OperationCanceledException();
- }
-
- private Change createChange(IPackageFragment pack, IPackageFragmentRoot destination) {
- return new MovePackageChange(pack, destination);
- }
-
- public Change createChange(IProgressMonitor pm) throws JavaScriptModelException {
- IPackageFragment[] fragments= getPackages();
- pm.beginTask("", fragments.length); //$NON-NLS-1$
- CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_package);
- result.markAsSynthetic();
- IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot();
- for (int i= 0; i < fragments.length; i++) {
- result.add(createChange(fragments[i], root));
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- pm.done();
- return result;
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fCreateTargetExecutionLog;
- }
-
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) {
- return null;
- }
-
- protected String getDescriptionPlural() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_plural;
- }
-
- protected String getDescriptionSingular() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_header;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- if (fModifications != null)
- return fModifications;
-
- fModifications= new MoveModifications();
- boolean updateReferences= canUpdateReferences() && getUpdateReferences();
- IPackageFragment[] packages= getPackages();
- IPackageFragmentRoot javaDestination= getDestinationAsPackageFragmentRoot();
- for (int i= 0; i < packages.length; i++) {
- fModifications.move(packages[i], new MoveArguments(javaDestination, updateReferences));
- }
- return fModifications;
- }
-
- public String getPolicyId() {
- return POLICY_MOVE_PACKAGES;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- public boolean isTextualMove() {
- return false;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- return null;
- }
-
- public void setDestinationCheck(boolean check) {
- fCheckDestination= check;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- RefactoringStatus superStatus= super.verifyDestination(javaElement);
- if (superStatus.hasFatalError())
- return superStatus;
-
- IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot();
- if (isParentOfAny(root, getPackages()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_package2parent);
- return superStatus;
- }
- }
-
- private static final class MoveSubCuElementsPolicy extends SubCuElementReorgPolicy implements IMovePolicy {
-
- private static final String POLICY_MOVE_MEMBERS= "org.eclipse.wst.jsdt.ui.moveMembers"; //$NON-NLS-1$
-
- private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog();
-
- MoveSubCuElementsPolicy(IJavaScriptElement[] javaElements) {
- super(javaElements);
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- return super.canEnable() && getSourceCu() != null;
- }
-
- public Change createChange(IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask("", 3); //$NON-NLS-1$
- try {
- final IJavaScriptUnit sourceCu= getSourceCu();
- JavaScriptUnit sourceCuNode= RefactoringASTParser.parseWithASTProvider(sourceCu, false, new SubProgressMonitor(pm, 1));
- CompilationUnitRewrite sourceRewriter= new CompilationUnitRewrite(sourceCu, sourceCuNode);
- IJavaScriptUnit destinationCu= getDestinationCu();
- CompilationUnitRewrite targetRewriter;
- if (sourceCu.equals(destinationCu)) {
- targetRewriter= sourceRewriter;
- pm.worked(1);
- } else {
- JavaScriptUnit destinationCuNode= RefactoringASTParser.parseWithASTProvider(destinationCu, false, new SubProgressMonitor(pm, 1));
- targetRewriter= new CompilationUnitRewrite(destinationCu, destinationCuNode);
- }
- IJavaScriptElement[] javaElements= getJavaElements();
- for (int i= 0; i < javaElements.length; i++) {
- copyToDestination(javaElements[i], targetRewriter, sourceRewriter.getRoot(), targetRewriter.getRoot());
- }
- ASTNodeDeleteUtil.markAsDeleted(javaElements, sourceRewriter, null);
- Change targetCuChange= createCompilationUnitChange(destinationCu, targetRewriter);
- if (sourceCu.equals(destinationCu)) {
- return targetCuChange;
- } else {
- CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_members);
- result.markAsSynthetic();
- result.add(targetCuChange);
-// if (Arrays.asList(getJavaElements()).containsAll(Arrays.asList(sourceCu.getTypes())))
-// result.add(DeleteChangeCreator.createDeleteChange(null, new IResource[0], new IJavaScriptUnit[] {sourceCu}, RefactoringCoreMessages.ReorgPolicy_move, null));
-// else
- result.add(createCompilationUnitChange(sourceCu, sourceRewriter));
- return result;
- }
- } catch (JavaScriptModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- } finally {
- pm.done();
- }
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) {
- return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- public IFile[] getAllModifiedFiles() {
- return ReorgUtils.getFiles(new IResource[] { ReorgUtils.getResource(getSourceCu()), ReorgUtils.getResource(getDestinationCu())});
- }
-
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return fCreateTargetExecutionLog;
- }
-
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) {
- return null;
- }
-
- protected String getDescriptionPlural() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_TYPES:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_types;
- case ONLY_FIELDS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_fields;
- case ONLY_METHODS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_methods;
- case ONLY_INITIALIZERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_initializers;
- case ONLY_PACKAGE_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declarations;
- case ONLY_IMPORT_CONTAINERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_import_containers;
- case ONLY_IMPORT_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declarations;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_plural;
- }
-
- protected String getDescriptionSingular() {
- final int kind= getContentKind();
- switch (kind) {
- case ONLY_TYPES:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_type;
- case ONLY_FIELDS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_field;
- case ONLY_METHODS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_method;
- case ONLY_INITIALIZERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_initializer;
- case ONLY_PACKAGE_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declaration;
- case ONLY_IMPORT_CONTAINERS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_import_section;
- case ONLY_IMPORT_DECLARATIONS:
- return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declaration;
- }
- return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_singular;
- }
-
- protected String getHeaderPattern() {
- return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_header;
- }
-
- public String getPolicyId() {
- return POLICY_MOVE_MEMBERS;
- }
-
- protected String getProcessorId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- protected String getRefactoringId() {
- return IJavaScriptRefactorings.MOVE;
- }
-
- public boolean isTextualMove() {
- return true;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- return null;
- }
-
- public void setDestinationCheck(boolean check) {
- fCheckDestination= check;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- IJavaScriptElement[] elements= getJavaElements();
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement parent= destination.getParent();
- while (parent != null) {
- if (parent.equals(elements[i]))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
- parent= parent.getParent();
- }
- }
-
- RefactoringStatus superStatus= super.verifyDestination(destination);
- if (superStatus.hasFatalError())
- return superStatus;
-
- Object commonParent= new ParentChecker(new IResource[0], getJavaElements()).getCommonParent();
- if (destination.equals(commonParent) || Arrays.asList(getJavaElements()).contains(destination))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent);
- return superStatus;
- }
- }
-
- private static final class NewNameProposer {
-
- private static boolean isNewNameOk(IContainer container, String newName) {
- return container.findMember(newName) == null;
- }
-
- private static boolean isNewNameOk(IPackageFragment dest, String newName) {
- return !dest.getJavaScriptUnit(newName).exists();
- }
-
- private static boolean isNewNameOk(IPackageFragmentRoot root, String newName) {
- return !root.getPackageFragment(newName).exists();
- }
-
- private final Set fAutoGeneratedNewNames= new HashSet(2);
-
- public String createNewName(IJavaScriptUnit cu, IPackageFragment destination) {
- if (isNewNameOk(destination, cu.getElementName()))
- return null;
- if (!ReorgUtils.isParentInWorkspaceOrOnDisk(cu, destination))
- return null;
- int i= 1;
- while (true) {
- String newName;
- if (i == 1)
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_cu_copyOf1, cu.getElementName());
- else
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_cu_copyOfMore, new String[] { String.valueOf(i), cu.getElementName()});
- if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) {
- fAutoGeneratedNewNames.add(newName);
- return JavaScriptCore.removeJavaScriptLikeExtension(newName);
- }
- i++;
- }
- }
-
- public String createNewName(IPackageFragment pack, IPackageFragmentRoot destination) {
- if (isNewNameOk(destination, pack.getElementName()))
- return null;
- if (!ReorgUtils.isParentInWorkspaceOrOnDisk(pack, destination))
- return null;
- int i= 1;
- while (true) {
- String newName;
- if (i == 1)
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_package_copyOf1, pack.getElementName());
- else
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_package_copyOfMore, new String[] { String.valueOf(i), pack.getElementName()});
- if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) {
- fAutoGeneratedNewNames.add(newName);
- return newName;
- }
- i++;
- }
- }
-
- public String createNewName(IResource res, IContainer destination) {
- if (isNewNameOk(destination, res.getName()))
- return null;
- if (!ReorgUtils.isParentInWorkspaceOrOnDisk(res, destination))
- return null;
- int i= 1;
- while (true) {
- String newName;
- if (i == 1)
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_resource_copyOf1, res.getName());
- else
- newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_resource_copyOfMore, new String[] { String.valueOf(i), res.getName()});
- if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) {
- fAutoGeneratedNewNames.add(newName);
- return newName;
- }
- i++;
- }
- }
- }
-
- private static final class NoCopyPolicy extends ReorgPolicy implements ICopyPolicy {
-
- public boolean canEnable() throws JavaScriptModelException {
- return false;
- }
-
- public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) {
- return new NullChange();
- }
-
- protected String getDescriptionPlural() {
- return UNUSED_STRING;
- }
-
- protected String getDescriptionSingular() {
- return UNUSED_STRING;
- }
-
- public ChangeDescriptor getDescriptor() {
- return null;
- }
-
- protected String getHeaderPattern() {
- return UNUSED_STRING;
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return new IJavaScriptElement[0];
- }
-
- public String getPolicyId() {
- return NO_POLICY;
- }
-
- protected String getProcessorId() {
- return NO_ID;
- }
-
- protected String getRefactoringId() {
- return NO_ID;
- }
-
- public ReorgExecutionLog getReorgExecutionLog() {
- return null;
- }
-
- public IResource[] getResources() {
- return new IResource[0];
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying);
- }
-
- protected RefactoringStatus verifyDestination(IResource resource) throws JavaScriptModelException {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying);
- }
- }
-
- private static final class NoMovePolicy extends ReorgPolicy implements IMovePolicy {
-
- public boolean canEnable() throws JavaScriptModelException {
- return false;
- }
-
- public Change createChange(IProgressMonitor pm) {
- return new NullChange();
- }
-
- public CreateTargetExecutionLog getCreateTargetExecutionLog() {
- return new CreateTargetExecutionLog();
- }
-
- public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) {
- return null;
- }
-
- protected String getDescriptionPlural() {
- return UNUSED_STRING;
- }
-
- protected String getDescriptionSingular() {
- return UNUSED_STRING;
- }
-
- public ChangeDescriptor getDescriptor() {
- return null;
- }
-
- protected String getHeaderPattern() {
- return UNUSED_STRING;
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return new IJavaScriptElement[0];
- }
-
- public String getPolicyId() {
- return NO_POLICY;
- }
-
- protected String getProcessorId() {
- return NO_ID;
- }
-
- protected String getRefactoringId() {
- return NO_ID;
- }
-
- public IResource[] getResources() {
- return new IResource[0];
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- return new RefactoringStatus();
- }
-
- public boolean isTextualMove() {
- return true;
- }
-
- public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
- return null;
- }
-
- public void setDestinationCheck(boolean check) {
- fCheckDestination= check;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving);
- }
-
- protected RefactoringStatus verifyDestination(IResource resource) throws JavaScriptModelException {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving);
- }
- }
-
- private static abstract class PackageFragmentRootsReorgPolicy extends ReorgPolicy {
-
- private IPackageFragmentRoot[] fPackageFragmentRoots;
-
- public PackageFragmentRootsReorgPolicy(IPackageFragmentRoot[] roots) {
- fPackageFragmentRoots= roots;
- }
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return true;
- default:
- return false;
- }
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return false;
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- return javaElement.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT;
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return false;
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- if (!super.canEnable())
- return false;
- for (int i= 0; i < fPackageFragmentRoots.length; i++) {
- if (!(ReorgUtils.isSourceFolder(fPackageFragmentRoots[i]) || (fPackageFragmentRoots[i].isArchive() && !fPackageFragmentRoots[i].isExternal())))
- return false;
- }
- if (ReorgUtils.containsLinkedResources(fPackageFragmentRoots))
- return false;
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries);
- confirmOverwriting(reorgQueries);
- return status;
- }
-
- private void confirmOverwriting(IReorgQueries reorgQueries) {
- OverwriteHelper oh= new OverwriteHelper();
- oh.setPackageFragmentRoots(fPackageFragmentRoots);
- IJavaScriptProject javaProject= getDestinationJavaProject();
- oh.confirmOverwriting(reorgQueries, javaProject);
- fPackageFragmentRoots= oh.getPackageFragmentRootsWithoutUnconfirmedOnes();
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) {
- return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- public final ChangeDescriptor getDescriptor() {
- final Map arguments= new HashMap();
- final int length= fPackageFragmentRoots.length;
- final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural();
- final IProject resource= getSingleProject();
- final String project= resource != null ? resource.getName() : null;
- final String header= Messages.format(getHeaderPattern(), new String[] { String.valueOf(length), getDestinationLabel()});
- int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags);
- arguments.put(ATTRIBUTE_POLICY, getPolicyId());
- arguments.put(ATTRIBUTE_ROOTS, new Integer(fPackageFragmentRoots.length).toString());
- for (int offset= 0; offset < fPackageFragmentRoots.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fPackageFragmentRoots[offset]));
- arguments.putAll(getRefactoringArguments(project));
- return new RefactoringChangeDescriptor(descriptor);
- }
-
- private IJavaScriptProject getDestinationAsJavaProject(IJavaScriptElement javaElementDestination) {
- if (javaElementDestination == null)
- return null;
- else
- return javaElementDestination.getJavaScriptProject();
- }
-
- protected IJavaScriptProject getDestinationJavaProject() {
- return getDestinationAsJavaProject(getJavaElementDestination());
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return fPackageFragmentRoots;
- }
-
- protected IPackageFragmentRoot[] getPackageFragmentRoots() {
- return fPackageFragmentRoots;
- }
-
- public IResource[] getResources() {
- return new IResource[0];
- }
-
- public IPackageFragmentRoot[] getRoots() {
- return fPackageFragmentRoots;
- }
-
- private IProject getSingleProject() {
- IProject result= null;
- for (int index= 0; index < fPackageFragmentRoots.length; index++) {
- if (result == null)
- result= fPackageFragmentRoots[index].getJavaScriptProject().getProject();
- else if (!result.equals(fPackageFragmentRoots[index].getJavaScriptProject().getProject()))
- return null;
- }
- return result;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- int rootCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_ROOTS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- rootCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ROOTS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ROOTS));
- String handle= null;
- List elements= new ArrayList();
- for (int index= 0; index < rootCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId()));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fPackageFragmentRoots= (IPackageFragmentRoot[]) elements.toArray(new IPackageFragmentRoot[elements.size()]);
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- status.merge(super.initialize(arguments));
- return status;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- Assert.isNotNull(javaElement);
- if (!fCheckDestination)
- return new RefactoringStatus();
- if (!javaElement.exists())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
- if (javaElement instanceof IJavaScriptModel)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
- if (!(javaElement instanceof IJavaScriptProject || javaElement instanceof IPackageFragmentRoot))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
- if (javaElement.isReadOnly())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable);
- if (ReorgUtils.isPackageFragmentRoot(javaElement.getJavaScriptProject()))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc);
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus verifyDestination(IResource resource) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
- }
- }
-
- private static abstract class PackagesReorgPolicy extends ReorgPolicy {
-
- private IPackageFragment[] fPackageFragments;
-
- public PackagesReorgPolicy(IPackageFragment[] packageFragments) {
- fPackageFragments= packageFragments;
- }
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- // can be nested
- // (with exclusion
- // filters)
- return true;
- default:
- return false;
- }
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return false;
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return true;
- default:
- return false;
- }
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return false;
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- for (int i= 0; i < fPackageFragments.length; i++) {
- if (JavaElementUtil.isDefaultPackage(fPackageFragments[i]) || fPackageFragments[i].isReadOnly())
- return false;
- }
- if (ReorgUtils.containsLinkedResources(fPackageFragments))
- return false;
- return true;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- RefactoringStatus refactoringStatus= super.checkFinalConditions(pm, context, reorgQueries);
- confirmOverwriting(reorgQueries);
- return refactoringStatus;
- }
-
- private void confirmOverwriting(IReorgQueries reorgQueries) throws JavaScriptModelException {
- OverwriteHelper helper= new OverwriteHelper();
- helper.setPackages(fPackageFragments);
- IPackageFragmentRoot destRoot= getDestinationAsPackageFragmentRoot();
- helper.confirmOverwriting(reorgQueries, destRoot);
- fPackageFragments= helper.getPackagesWithoutUnconfirmedOnes();
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) {
- return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- public final ChangeDescriptor getDescriptor() {
- final Map arguments= new HashMap();
- final int length= fPackageFragments.length;
- final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural();
- final IProject resource= getSingleProject();
- final String project= resource != null ? resource.getName() : null;
- final String header= Messages.format(getHeaderPattern(), new String[] { String.valueOf(length), getDestinationLabel()});
- int flags= JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_MIGRATION | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags);
- arguments.put(ATTRIBUTE_POLICY, getPolicyId());
- arguments.put(ATTRIBUTE_FRAGMENTS, new Integer(fPackageFragments.length).toString());
- for (int offset= 0; offset < fPackageFragments.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fPackageFragments[offset]));
- arguments.putAll(getRefactoringArguments(project));
- return new RefactoringChangeDescriptor(descriptor);
- }
-
- protected IPackageFragmentRoot getDestinationAsPackageFragmentRoot() throws JavaScriptModelException {
- return getDestinationAsPackageFragmentRoot(getJavaElementDestination());
- }
-
- private IPackageFragmentRoot getDestinationAsPackageFragmentRoot(IJavaScriptElement javaElement) throws JavaScriptModelException {
- if (javaElement == null)
- return null;
-
- if (javaElement instanceof IPackageFragmentRoot)
- return (IPackageFragmentRoot) javaElement;
-
- if (javaElement instanceof IPackageFragment) {
- IPackageFragment pack= (IPackageFragment) javaElement;
- if (pack.getParent() instanceof IPackageFragmentRoot)
- return (IPackageFragmentRoot) pack.getParent();
- }
-
- if (javaElement instanceof IJavaScriptProject)
- return ReorgUtils.getCorrespondingPackageFragmentRoot((IJavaScriptProject) javaElement);
- return null;
- }
-
- public IJavaScriptElement[] getJavaElements() {
- return fPackageFragments;
- }
-
- protected IPackageFragment[] getPackages() {
- return fPackageFragments;
- }
-
- public IResource[] getResources() {
- return new IResource[0];
- }
-
- private IProject getSingleProject() {
- IProject result= null;
- for (int index= 0; index < fPackageFragments.length; index++) {
- if (result == null)
- result= fPackageFragments[index].getJavaScriptProject().getProject();
- else if (!result.equals(fPackageFragments[index].getJavaScriptProject().getProject()))
- return null;
- }
- return result;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- int fragmentCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_FRAGMENTS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- fragmentCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FRAGMENTS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FRAGMENTS));
- String handle= null;
- List elements= new ArrayList();
- for (int index= 0; index < fragmentCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT)
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId()));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fPackageFragments= (IPackageFragment[]) elements.toArray(new IPackageFragment[elements.size()]);
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- status.merge(super.initialize(arguments));
- return status;
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement javaElement) throws JavaScriptModelException {
- Assert.isNotNull(javaElement);
- if (!fCheckDestination)
- return new RefactoringStatus();
- if (!javaElement.exists())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
- if (javaElement instanceof IJavaScriptModel)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
- IPackageFragmentRoot destRoot= getDestinationAsPackageFragmentRoot(javaElement);
- if (!ReorgUtils.isSourceFolder(destRoot))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_packages);
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus verifyDestination(IResource resource) {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_packages);
- }
- }
-
- private static abstract class ReorgPolicy implements IReorgPolicy {
-
- private static final String ATTRIBUTE_DESTINATION= "destination"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_TARGET= "target"; //$NON-NLS-1$
-
- protected boolean fCheckDestination= true;
-
- private IJavaScriptElement fJavaElementDestination;
-
- private IResource fResourceDestination;
-
- public boolean canChildrenBeDestinations(IJavaScriptElement javaElement) {
- return true;
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return true;
- }
-
- public boolean canElementBeDestination(IJavaScriptElement javaElement) {
- return true;
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return true;
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- IResource[] resources= getResources();
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (!resource.exists() || resource.isPhantom() || !resource.isAccessible())
- return false;
- }
-
- IJavaScriptElement[] javaElements= getJavaElements();
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (!element.exists())
- return false;
- }
- return true;
- }
-
- public boolean canEnableQualifiedNameUpdating() {
- return false;
- }
-
- public boolean canEnableUpdateReferences() {
- return false;
- }
-
- public boolean canUpdateQualifiedNames() {
- Assert.isTrue(false);
- // should not be called if
- // canEnableQualifiedNameUpdating is not
- // overridden and returns false
- return false;
- }
-
- public boolean canUpdateReferences() {
- return false;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException {
- Assert.isNotNull(reorgQueries);
- ResourceChangeChecker checker= (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class);
- IFile[] allModifiedFiles= getAllModifiedFiles();
- RefactoringModifications modifications= getModifications();
- IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory();
- for (int i= 0; i < allModifiedFiles.length; i++) {
- deltaFactory.change(allModifiedFiles[i]);
- }
- if (modifications != null) {
- modifications.buildDelta(deltaFactory);
- modifications.buildValidateEdits((ValidateEditChecker) context.getChecker(ValidateEditChecker.class));
- }
- return new RefactoringStatus();
- }
-
- public IFile[] getAllModifiedFiles() {
- return new IFile[0];
- }
-
- protected abstract String getDescriptionPlural();
-
- protected abstract String getDescriptionSingular();
-
- protected String getDestinationLabel() {
- Object destination= getJavaElementDestination();
- if (destination == null)
- destination= getResourceDestination();
- return JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- }
-
- public String getFilePatterns() {
- Assert.isTrue(false);
- // should not be called if
- // canEnableQualifiedNameUpdating is not
- // overridden and returns false
- return null;
- }
-
- protected abstract String getHeaderPattern();
-
- public final IJavaScriptElement getJavaElementDestination() {
- return fJavaElementDestination;
- }
-
- protected RefactoringModifications getModifications() throws CoreException {
- return null;
- }
-
- protected abstract String getProcessorId();
-
- protected Map getRefactoringArguments(String project) {
- final Map arguments= new HashMap();
- final IJavaScriptElement element= getJavaElementDestination();
- if (element != null)
- arguments.put(ATTRIBUTE_DESTINATION, JDTRefactoringDescriptor.elementToHandle(project, element));
- else {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
- final IResource resource= getResourceDestination();
- if (resource != null)
- arguments.put(ATTRIBUTE_TARGET, JDTRefactoringDescriptor.resourceToHandle(null, resource));
- }
- return arguments;
- }
-
- protected abstract String getRefactoringId();
-
- public final IResource getResourceDestination() {
- return fResourceDestination;
- }
-
- public boolean getUpdateQualifiedNames() {
- Assert.isTrue(false);
- // should not be called if
- // canEnableQualifiedNameUpdating is not
- // overridden and returns false
- return false;
- }
-
- public boolean getUpdateReferences() {
- Assert.isTrue(false);
- // should not be called if
- // canUpdateReferences is not overridden and
- // returns false
- return false;
- }
-
- public boolean hasAllInputSet() {
- return fJavaElementDestination != null || fResourceDestination != null;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(ATTRIBUTE_DESTINATION);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element != null) {
- if (fCheckDestination && !element.exists())
- return ScriptableRefactoring.createInputFatalStatus(element, getProcessorId(), getRefactoringId());
- else {
- try {
- return setDestination(element);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}));
- }
- }
- } else {
- // Leave for compatibility
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
- final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle);
- if (resource == null || (fCheckDestination && !resource.exists()))
- return ScriptableRefactoring.createInputFatalStatus(resource, getProcessorId(), getRefactoringId());
- else {
- try {
- return setDestination(resource);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}));
- }
- }
- }
- } else {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
- handle= extended.getAttribute(ATTRIBUTE_TARGET);
- if (handle != null) {
- final IResource resource= JDTRefactoringDescriptor.handleToResource(null, handle);
- if (resource == null || (fCheckDestination && !resource.exists()))
- return ScriptableRefactoring.createInputFatalStatus(resource, getProcessorId(), getRefactoringId());
- else {
- try {
- return setDestination(resource);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}));
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- }
-
- public final RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor processor, String[] natures, SharableParticipants shared) throws CoreException {
- RefactoringModifications modifications= getModifications();
- if (modifications != null) {
- return modifications.loadParticipants(status, processor, natures, shared);
- } else {
- return new RefactoringParticipant[0];
- }
- }
-
- public final RefactoringStatus setDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- Assert.isNotNull(destination);
- fJavaElementDestination= null;
- fResourceDestination= null;
- fJavaElementDestination= destination;
- return verifyDestination(destination);
- }
-
- public final RefactoringStatus setDestination(IResource destination) throws JavaScriptModelException {
- Assert.isNotNull(destination);
- fJavaElementDestination= null;
- fResourceDestination= null;
- fResourceDestination= destination;
- return verifyDestination(destination);
- }
-
- public void setFilePatterns(String patterns) {
- Assert.isTrue(false);
- // should not be called if
- // canEnableQualifiedNameUpdating is not
- // overridden and returns false
- }
-
- public void setUpdateQualifiedNames(boolean update) {
- Assert.isTrue(false);
- // should not be called if
- // canEnableQualifiedNameUpdating is not
- // overridden and returns false
- }
-
- public void setUpdateReferences(boolean update) {
- Assert.isTrue(false);
- // should not be called if
- // canUpdateReferences is not overridden and
- // returns false
- }
-
- protected abstract RefactoringStatus verifyDestination(IJavaScriptElement destination) throws JavaScriptModelException;
-
- protected abstract RefactoringStatus verifyDestination(IResource destination) throws JavaScriptModelException;
- }
-
- private static abstract class SubCuElementReorgPolicy extends ReorgPolicy {
-
- protected static final int ONLY_FIELDS= 1;
-
- protected static final int ONLY_IMPORT_CONTAINERS= 5;
-
- protected static final int ONLY_IMPORT_DECLARATIONS= 6;
-
- protected static final int ONLY_INITIALIZERS= 3;
-
- protected static final int ONLY_METHODS= 2;
-
- protected static final int ONLY_PACKAGE_DECLARATIONS= 4;
-
- protected static final int ONLY_TYPES= 0;
-
- protected static CompilationUnitChange createCompilationUnitChange(IJavaScriptUnit cu, CompilationUnitRewrite rewrite) throws CoreException {
- CompilationUnitChange change= rewrite.createChange();
- if (change != null) {
- if (cu.isWorkingCopy())
- change.setSaveMode(TextFileChange.LEAVE_DIRTY);
- }
- return change;
- }
-
- protected static final IJavaScriptUnit getDestinationCu(IJavaScriptElement destination) {
- if (destination instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) destination;
- return (IJavaScriptUnit) destination.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
- private static IJavaScriptUnit getEnclosingCu(IJavaScriptElement destination) {
- if (destination instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) destination;
- return (IJavaScriptUnit) destination.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
- private static IType getEnclosingType(IJavaScriptElement destination) {
- if (destination instanceof IType)
- return (IType) destination;
- return (IType) destination.getAncestor(IJavaScriptElement.TYPE);
- }
-
- private static String getUnindentedSource(ISourceReference sourceReference) throws JavaScriptModelException {
- Assert.isTrue(sourceReference instanceof IJavaScriptElement);
- String[] lines= Strings.convertIntoLines(sourceReference.getSource());
- final IJavaScriptProject project= ((IJavaScriptElement) sourceReference).getJavaScriptProject();
- Strings.trimIndentation(lines, project, false);
- return Strings.concatenate(lines, StubUtility.getLineDelimiterUsed((IJavaScriptElement) sourceReference));
- }
-
- private IJavaScriptElement[] fJavaElements;
-
- SubCuElementReorgPolicy(IJavaScriptElement[] javaElements) {
- fJavaElements= javaElements;
- }
-
- public boolean canChildrenBeDestinations(IResource resource) {
- return false;
- }
-
- public boolean canElementBeDestination(IResource resource) {
- return false;
- }
-
- public boolean canEnable() throws JavaScriptModelException {
- if (!super.canEnable())
- return false;
- for (int i= 0; i < fJavaElements.length; i++) {
- if (fJavaElements[i] instanceof IMember) {
- IMember member= (IMember) fJavaElements[i];
- // we can copy some binary members, but not all
- if (member.isBinary() && member.getSourceRange() == null)
- return false;
- }
- }
- return true;
- }
-
- private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, JavaScriptUnit sourceCuNode, JavaScriptUnit destinationCuNode) throws JavaScriptModelException {
- IJavaScriptElement[] importDeclarations= container.getChildren();
- for (int i= 0; i < importDeclarations.length; i++) {
- Assert.isTrue(importDeclarations[i] instanceof IImportDeclaration);
- IImportDeclaration importDeclaration= (IImportDeclaration) importDeclarations[i];
- copyImportToDestination(importDeclaration, rewrite, sourceCuNode, destinationCuNode);
- }
- }
-
- private void copyImportToDestination(IImportDeclaration declaration, ASTRewrite targetRewrite, JavaScriptUnit sourceCuNode, JavaScriptUnit destinationCuNode) throws JavaScriptModelException {
- ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
- ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode);
- targetRewrite.getListRewrite(destinationCuNode, JavaScriptUnit.IMPORTS_PROPERTY).insertLast(copiedNode, null);
- }
-
- private void copyInitializerToDestination(IInitializer initializer, CompilationUnitRewrite targetRewriter, JavaScriptUnit sourceCuNode, JavaScriptUnit targetCuNode) throws JavaScriptModelException {
- BodyDeclaration newInitializer= (BodyDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(initializer), ASTNode.INITIALIZER);
- copyMemberToDestination(initializer, targetRewriter, sourceCuNode, targetCuNode, newInitializer);
- }
-
- private void copyMemberToDestination(IMember member, CompilationUnitRewrite targetRewriter, JavaScriptUnit sourceCuNode, JavaScriptUnit targetCuNode, BodyDeclaration newMember) throws JavaScriptModelException {
- IJavaScriptElement javaElementDestination= getJavaElementDestination();
- ASTNode nodeDestination;
- ASTNode destinationContainer;
- switch (javaElementDestination.getElementType()) {
- case IJavaScriptElement.INITIALIZER:
- nodeDestination= ASTNodeSearchUtil.getInitializerNode((IInitializer) javaElementDestination, targetCuNode);
- destinationContainer= nodeDestination.getParent();
- break;
- case IJavaScriptElement.FIELD:
- nodeDestination= ASTNodeSearchUtil.getFieldOrEnumConstantDeclaration((IField) javaElementDestination, targetCuNode);
- destinationContainer= nodeDestination.getParent();
- break;
- case IJavaScriptElement.METHOD:
- nodeDestination= ASTNodeSearchUtil.getMethodOrAnnotationTypeMemberDeclarationNode((IFunction) javaElementDestination, targetCuNode);
- destinationContainer= nodeDestination.getParent();
- break;
- case IJavaScriptElement.TYPE:
- nodeDestination= null;
- IType typeDestination= (IType) javaElementDestination;
- if (typeDestination.isAnonymous())
- destinationContainer= ASTNodeSearchUtil.getClassInstanceCreationNode(typeDestination, targetCuNode).getAnonymousClassDeclaration();
- else
- destinationContainer= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(typeDestination, targetCuNode);
- break;
- default:
- nodeDestination= null;
- destinationContainer= null;
- }
- if (!(member instanceof IInitializer)) {
- BodyDeclaration decl= ASTNodeSearchUtil.getBodyDeclarationNode(member, sourceCuNode);
- if (decl != null)
- ImportRewriteUtil.addImports(targetRewriter, decl, new HashMap(), new HashMap(), false);
- }
- if (destinationContainer != null) {
- ListRewrite listRewrite;
- if (destinationContainer instanceof AbstractTypeDeclaration) {
- listRewrite= targetRewriter.getASTRewrite().getListRewrite(destinationContainer, ((AbstractTypeDeclaration) destinationContainer).getBodyDeclarationsProperty());
- } else
- listRewrite= targetRewriter.getASTRewrite().getListRewrite(destinationContainer, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
-
- if (nodeDestination != null) {
- final List list= listRewrite.getOriginalList();
- final int index= list.indexOf(nodeDestination);
- if (index > 0 && index < list.size() - 1) {
- listRewrite.insertBefore(newMember, (ASTNode) list.get(index), null);
- } else
- listRewrite.insertLast(newMember, null);
- } else
- listRewrite.insertAt(newMember, ASTNodes.getInsertionIndex(newMember, listRewrite.getRewrittenList()), null);
- return; // could insert into/after destination
- }
- // fall-back / default:
-// final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(getDestinationAsType(), targetCuNode.);
- targetRewriter.getASTRewrite().getListRewrite(targetCuNode, JavaScriptUnit.STATEMENTS_PROPERTY).insertLast(newMember, null);
- }
-
- private void copyMethodToDestination(IFunction method, CompilationUnitRewrite targetRewriter, JavaScriptUnit sourceCuNode, JavaScriptUnit targetCuNode) throws JavaScriptModelException {
- BodyDeclaration newMethod= (BodyDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(method), ASTNode.FUNCTION_DECLARATION);
- copyMemberToDestination(method, targetRewriter, sourceCuNode, targetCuNode, newMethod);
- }
-
- protected void copyToDestination(IJavaScriptElement element, CompilationUnitRewrite targetRewriter, JavaScriptUnit sourceCuNode, JavaScriptUnit targetCuNode) throws CoreException {
- final ASTRewrite rewrite= targetRewriter.getASTRewrite();
- switch (element.getElementType()) {
- case IJavaScriptElement.FIELD:
- copyMemberToDestination((IMember) element, targetRewriter, sourceCuNode, targetCuNode, createNewFieldDeclarationNode(((IField) element), rewrite, sourceCuNode));
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- copyImportsToDestination((IImportContainer) element, rewrite, sourceCuNode, targetCuNode);
- break;
- case IJavaScriptElement.IMPORT_DECLARATION:
- copyImportToDestination((IImportDeclaration) element, rewrite, sourceCuNode, targetCuNode);
- break;
- case IJavaScriptElement.INITIALIZER:
- copyInitializerToDestination((IInitializer) element, targetRewriter, sourceCuNode, targetCuNode);
- break;
- case IJavaScriptElement.METHOD:
- copyMethodToDestination((IFunction) element, targetRewriter, sourceCuNode, targetCuNode);
- break;
- case IJavaScriptElement.TYPE:
- copyTypeToDestination((IType) element, targetRewriter, sourceCuNode, targetCuNode);
- break;
-
- default:
- Assert.isTrue(false);
- }
- }
-
- private void copyTypeToDestination(IType type, CompilationUnitRewrite targetRewriter, JavaScriptUnit sourceCuNode, JavaScriptUnit targetCuNode) throws JavaScriptModelException {
- AbstractTypeDeclaration newType= (AbstractTypeDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(type), ASTNode.TYPE_DECLARATION);
- IType enclosingType= getEnclosingType(getJavaElementDestination());
- if (enclosingType != null) {
- copyMemberToDestination(type, targetRewriter, sourceCuNode, targetCuNode, newType);
- } else {
- targetRewriter.getASTRewrite().getListRewrite(targetCuNode, JavaScriptUnit.TYPES_PROPERTY).insertLast(newType, null);
- }
- }
-
- private BodyDeclaration createNewFieldDeclarationNode(IField field, ASTRewrite rewrite, JavaScriptUnit sourceCuNode) throws CoreException {
- AST targetAst= rewrite.getAST();
- ITextFileBuffer buffer= null;
- BodyDeclaration newDeclaration= null;
- IJavaScriptUnit unit= field.getJavaScriptUnit();
- try {
- buffer= RefactoringFileBuffers.acquire(unit);
- IDocument document= buffer.getDocument();
- BodyDeclaration bodyDeclaration= ASTNodeSearchUtil.getFieldOrEnumConstantDeclaration(field, sourceCuNode);
- if (bodyDeclaration instanceof FieldDeclaration) {
- FieldDeclaration fieldDeclaration= (FieldDeclaration) bodyDeclaration;
- if (fieldDeclaration.fragments().size() == 1)
- return (FieldDeclaration) ASTNode.copySubtree(targetAst, fieldDeclaration);
- VariableDeclarationFragment originalFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, sourceCuNode);
- VariableDeclarationFragment copiedFragment= (VariableDeclarationFragment) ASTNode.copySubtree(targetAst, originalFragment);
- newDeclaration= targetAst.newFieldDeclaration(copiedFragment);
- ((FieldDeclaration) newDeclaration).setType((Type) ASTNode.copySubtree(targetAst, fieldDeclaration.getType()));
- } else
- Assert.isTrue(false);
- if (newDeclaration != null) {
- newDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(targetAst, bodyDeclaration.getModifiers()));
- JSdoc javadoc= bodyDeclaration.getJavadoc();
- if (javadoc != null)
- newDeclaration.setJavadoc((JSdoc) rewrite.createStringPlaceholder(document.get(javadoc.getStartPosition(), javadoc.getLength()), ASTNode.JSDOC));
- }
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- } finally {
- if (buffer != null)
- RefactoringFileBuffers.release(unit);
- }
- return newDeclaration;
- }
-
- protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) {
- return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags);
- }
-
- protected final int getContentKind() {
- final int types= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.TYPE).size();
- final int fields= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.FIELD).size();
- final int methods= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.METHOD).size();
- final int initializers= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.INITIALIZER).size();
- final int container= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.IMPORT_CONTAINER).size();
- final int imp= ReorgUtils.getElementsOfType(fJavaElements, IJavaScriptElement.IMPORT_DECLARATION).size();
- final int length= types + fields + methods + initializers + container + imp;
- if (length == types)
- return ONLY_TYPES;
- else if (length == fields)
- return ONLY_FIELDS;
- else if (length == methods)
- return ONLY_METHODS;
- else if (length == initializers)
- return ONLY_INITIALIZERS;
- else if (length == container)
- return ONLY_IMPORT_CONTAINERS;
- else if (length == imp)
- return ONLY_IMPORT_DECLARATIONS;
- return -1;
- }
-
- public final ChangeDescriptor getDescriptor() {
- final Map arguments= new HashMap();
- final int length= fJavaElements.length;
- final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural();
- final IProject resource= getSingleProject();
- final String project= resource != null ? resource.getName() : null;
- final String header= Messages.format(getHeaderPattern(), new String[] { String.valueOf(length), getDestinationLabel()});
- int flags= JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_MIGRATION | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags);
- arguments.put(ATTRIBUTE_POLICY, getPolicyId());
- arguments.put(ATTRIBUTE_MEMBERS, new Integer(fJavaElements.length).toString());
- for (int offset= 0; offset < fJavaElements.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fJavaElements[offset]));
- arguments.putAll(getRefactoringArguments(project));
- return new RefactoringChangeDescriptor(descriptor);
- }
-
- private IType getDestinationAsType() throws JavaScriptModelException {
- IJavaScriptElement destination= getJavaElementDestination();
- IType enclosingType= getEnclosingType(destination);
- if (enclosingType != null)
- return enclosingType;
- IJavaScriptUnit enclosingCu= getEnclosingCu(destination);
- Assert.isNotNull(enclosingCu);
- IType mainType= JavaElementUtil.getMainType(enclosingCu);
- Assert.isNotNull(mainType);
- return mainType;
- }
-
- protected final IJavaScriptUnit getDestinationCu() {
- return getDestinationCu(getJavaElementDestination());
- }
-
- public final IJavaScriptElement[] getJavaElements() {
- return fJavaElements;
- }
-
- public final IResource[] getResources() {
- return new IResource[0];
- }
-
- private IProject getSingleProject() {
- IProject result= null;
- for (int index= 0; index < fJavaElements.length; index++) {
- if (result == null)
- result= fJavaElements[index].getJavaScriptProject().getProject();
- else if (!result.equals(fJavaElements[index].getJavaScriptProject().getProject()))
- return null;
- }
- return result;
- }
-
- protected final IJavaScriptUnit getSourceCu() {
- // all have a common parent, so all must be in the same cu
- // we checked before that the array in not null and not empty
- return (IJavaScriptUnit) fJavaElements[0].getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- final RefactoringStatus status= new RefactoringStatus();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- int memberCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_MEMBERS);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- memberCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MEMBERS));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MEMBERS));
- String handle= null;
- List elements= new ArrayList();
- for (int index= 0; index < memberCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId()));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fJavaElements= (IJavaScriptElement[]) elements.toArray(new IJavaScriptElement[elements.size()]);
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- status.merge(super.initialize(arguments));
- return status;
- }
-
- private RefactoringStatus recursiveVerifyDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- Assert.isNotNull(destination);
- if (!fCheckDestination)
- return new RefactoringStatus();
- if (!destination.exists())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist1);
- if (destination instanceof IJavaScriptModel)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
- if (!(destination instanceof IJavaScriptUnit) && !ReorgUtils.isInsideCompilationUnit(destination))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
-
- IJavaScriptUnit destinationCu= getDestinationCu(destination);
- Assert.isNotNull(destinationCu);
- if (destinationCu.isReadOnly())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot_modify);
-
- switch (destination.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- int[] types0= new int[] { IJavaScriptElement.FIELD, IJavaScriptElement.INITIALIZER, IJavaScriptElement.METHOD};
- if (ReorgUtils.hasElementsOfType(getJavaElements(), types0))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
- break;
-
- case IJavaScriptElement.IMPORT_CONTAINER:
- if (ReorgUtils.hasElementsNotOfType(getJavaElements(), IJavaScriptElement.IMPORT_DECLARATION))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
- break;
-
- case IJavaScriptElement.IMPORT_DECLARATION:
- if (ReorgUtils.hasElementsNotOfType(getJavaElements(), IJavaScriptElement.IMPORT_DECLARATION))
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
- break;
-
- case IJavaScriptElement.FIELD:// fall thru
- case IJavaScriptElement.INITIALIZER:// fall thru
- case IJavaScriptElement.METHOD:// fall thru
- return recursiveVerifyDestination(destination.getParent());
-
- case IJavaScriptElement.TYPE:
- int[] types1= new int[] { IJavaScriptElement.IMPORT_DECLARATION, IJavaScriptElement.IMPORT_CONTAINER};
- if (ReorgUtils.hasElementsOfType(getJavaElements(), types1))
- return recursiveVerifyDestination(destination.getParent());
- break;
- }
-
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus verifyDestination(IJavaScriptElement destination) throws JavaScriptModelException {
- return recursiveVerifyDestination(destination);
- }
-
- protected final RefactoringStatus verifyDestination(IResource destination) throws JavaScriptModelException {
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_no_resource);
- }
- }
-
- private static final String ATTRIBUTE_FILES= "files"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_FOLDERS= "folders"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_FRAGMENTS= "fragments"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_LOG= "log"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_MEMBERS= "members"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_PATTERNS= "patterns"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_POLICY= "policy"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_QUALIFIED= "qualified"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_ROOTS= "roots"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_UNITS= "units"; //$NON-NLS-1$
-
- private static final String DELIMITER_ELEMENT= "\t"; //$NON-NLS-1$
-
- private static final String DELIMITER_RECORD= "\n"; //$NON-NLS-1$
-
- private static final String NO_ID= "no_id"; //$NON-NLS-1$
-
- private static final String NO_POLICY= "no_policy"; //$NON-NLS-1$
-
- private static final String UNUSED_STRING= "unused"; //$NON-NLS-1$
-
- private static boolean containsNull(Object[] objects) {
- for (int i= 0; i < objects.length; i++) {
- if (objects[i] == null)
- return true;
- }
- return false;
- }
-
- public static ICopyPolicy createCopyPolicy(IResource[] resources, IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- return (ICopyPolicy) createReorgPolicy(true, resources, javaElements);
- }
-
- public static ICopyPolicy createCopyPolicy(RefactoringStatus status, RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String policy= extended.getAttribute(ATTRIBUTE_POLICY);
- if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
- if (CopyFilesFoldersAndCusPolicy.POLICY_COPY_RESOURCE.equals(policy)) {
- return new CopyFilesFoldersAndCusPolicy(null, null, null);
- } else if (CopyPackageFragmentRootsPolicy.POLICY_COPY_ROOTS.equals(policy)) {
- return new CopyPackageFragmentRootsPolicy(null);
- } else if (CopyPackagesPolicy.POLICY_COPY_PACKAGES.equals(policy)) {
- return new CopyPackagesPolicy(null);
- } else if (CopySubCuElementsPolicy.POLICY_COPY_MEMBERS.equals(policy)) {
- return new CopySubCuElementsPolicy(null);
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { policy, ATTRIBUTE_POLICY})));
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY)));
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
- return null;
- }
-
- public static IMovePolicy createMovePolicy(IResource[] resources, IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- return (IMovePolicy) createReorgPolicy(false, resources, javaElements);
- }
-
- public static IMovePolicy createMovePolicy(RefactoringStatus status, RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String policy= extended.getAttribute(ATTRIBUTE_POLICY);
- if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
- if (MoveFilesFoldersAndCusPolicy.POLICY_MOVE_RESOURCES.equals(policy)) {
- return new MoveFilesFoldersAndCusPolicy(null, null, null);
- } else if (MovePackageFragmentRootsPolicy.POLICY_MOVE_ROOTS.equals(policy)) {
- return new MovePackageFragmentRootsPolicy(null);
- } else if (MovePackagesPolicy.POLICY_MOVE_PACKAGES.equals(policy)) {
- return new MovePackagesPolicy(null);
- } else if (MoveSubCuElementsPolicy.POLICY_MOVE_MEMBERS.equals(policy)) {
- return new MoveSubCuElementsPolicy(null);
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { policy, ATTRIBUTE_POLICY})));
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY)));
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
- return null;
- }
-
- private static IReorgPolicy createReorgPolicy(boolean copy, IResource[] selectedResources, IJavaScriptElement[] selectedJavaElements) throws JavaScriptModelException {
- final IReorgPolicy NO;
- if (copy)
- NO= new NoCopyPolicy();
- else
- NO= new NoMovePolicy();
-
- ActualSelectionComputer selectionComputer= new ActualSelectionComputer(selectedJavaElements, selectedResources);
- IResource[] resources= selectionComputer.getActualResourcesToReorg();
- IJavaScriptElement[] javaElements= selectionComputer.getActualJavaElementsToReorg();
-
- if ((resources.length + javaElements.length == 0) || containsNull(resources) || containsNull(javaElements) || ReorgUtils.isArchiveMember(javaElements) || ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.JAVASCRIPT_PROJECT) || ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.JAVASCRIPT_MODEL) || ReorgUtils.hasElementsOfType(resources, IResource.PROJECT | IResource.ROOT) || !new ParentChecker(resources, javaElements).haveCommonParent())
- return NO;
-
- if (ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.PACKAGE_FRAGMENT)) {
- if (resources.length != 0 || ReorgUtils.hasElementsNotOfType(javaElements, IJavaScriptElement.PACKAGE_FRAGMENT))
- return NO;
- if (copy)
- return new CopyPackagesPolicy(ArrayTypeConverter.toPackageArray(javaElements));
- else
- return new MovePackagesPolicy(ArrayTypeConverter.toPackageArray(javaElements));
- }
-
- if (ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)) {
- if (resources.length != 0 || ReorgUtils.hasElementsNotOfType(javaElements, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT))
- return NO;
- if (copy)
- return new CopyPackageFragmentRootsPolicy(ArrayTypeConverter.toPackageFragmentRootArray(javaElements));
- else
- return new MovePackageFragmentRootsPolicy(ArrayTypeConverter.toPackageFragmentRootArray(javaElements));
- }
-
- if (ReorgUtils.hasElementsOfType(resources, IResource.FILE | IResource.FOLDER) || ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.JAVASCRIPT_UNIT)) {
- if (ReorgUtils.hasElementsNotOfType(javaElements, IJavaScriptElement.JAVASCRIPT_UNIT))
- return NO;
- if (ReorgUtils.hasElementsNotOfType(resources, IResource.FILE | IResource.FOLDER))
- return NO;
- if (copy)
- return new CopyFilesFoldersAndCusPolicy(ReorgUtils.getFiles(resources), ReorgUtils.getFolders(resources), ArrayTypeConverter.toCuArray(javaElements));
- else
- return new MoveFilesFoldersAndCusPolicy(ReorgUtils.getFiles(resources), ReorgUtils.getFolders(resources), ArrayTypeConverter.toCuArray(javaElements));
- }
-
- if (hasElementsSmallerThanCuOrClassFile(javaElements)) {
- // assertions guaranteed by common parent
- Assert.isTrue(resources.length == 0);
- Assert.isTrue(!ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.JAVASCRIPT_UNIT));
- Assert.isTrue(!ReorgUtils.hasElementsOfType(javaElements, IJavaScriptElement.CLASS_FILE));
- Assert.isTrue(!hasElementsLargerThanCuOrClassFile(javaElements));
- if (copy)
- return new CopySubCuElementsPolicy(javaElements);
- else
- return new MoveSubCuElementsPolicy(javaElements);
- }
- return NO;
- }
-
- private static boolean hasElementsLargerThanCuOrClassFile(IJavaScriptElement[] javaElements) {
- for (int i= 0; i < javaElements.length; i++) {
- if (!ReorgUtils.isInsideCompilationUnit(javaElements[i]) && !ReorgUtils.isInsideClassFile(javaElements[i]))
- return true;
- }
- return false;
- }
-
- private static boolean hasElementsSmallerThanCuOrClassFile(IJavaScriptElement[] javaElements) {
- for (int i= 0; i < javaElements.length; i++) {
- if (ReorgUtils.isInsideCompilationUnit(javaElements[i]))
- return true;
- if (ReorgUtils.isInsideClassFile(javaElements[i]))
- return true;
- }
- return false;
- }
-
- public static CreateTargetExecutionLog loadCreateTargetExecutionLog(RefactoringStatus status, JavaRefactoringArguments arguments) {
- CreateTargetExecutionLog log= new CreateTargetExecutionLog();
- final String value= arguments.getAttribute(ATTRIBUTE_LOG);
- if (value != null) {
- final StringTokenizer tokenizer= new StringTokenizer(value, DELIMITER_RECORD, false);
- while (tokenizer.hasMoreTokens()) {
- final String token= tokenizer.nextToken();
- processCreateTargetExecutionRecord(log, arguments, token);
- }
- }
- return log;
- }
-
- public static ReorgExecutionLog loadReorgExecutionLog(RefactoringStatus status, JavaRefactoringArguments arguments) {
- ReorgExecutionLog log= new ReorgExecutionLog();
- final String value= arguments.getAttribute(ATTRIBUTE_LOG);
- if (value != null) {
- final StringTokenizer tokenizer= new StringTokenizer(value, DELIMITER_RECORD, false);
- while (tokenizer.hasMoreTokens()) {
- final String token= tokenizer.nextToken();
- processReorgExecutionRecord(log, arguments, token);
- }
- }
- return log;
- }
-
- private static void processCreateTargetExecutionRecord(CreateTargetExecutionLog log, JavaRefactoringArguments arguments, String token) {
- final StringTokenizer tokenizer= new StringTokenizer(token, DELIMITER_ELEMENT, false);
- String value= null;
- if (tokenizer.hasMoreTokens()) {
- value= tokenizer.nextToken();
- Object selection= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value, false);
- if (selection == null)
- selection= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value);
- if (selection != null && tokenizer.hasMoreTokens()) {
- value= tokenizer.nextToken();
- Object created= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value, false);
- if (created == null)
- created= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value);
- if (created != null)
- log.markAsCreated(selection, created);
- }
- }
- }
-
- private static void processReorgExecutionRecord(ReorgExecutionLog log, JavaRefactoringArguments arguments, String token) {
- final StringTokenizer tokenizer= new StringTokenizer(token, DELIMITER_ELEMENT, false);
- String value= null;
- if (tokenizer.hasMoreTokens()) {
- value= tokenizer.nextToken();
- Object element= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value);
- if (element == null)
- element= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value);
- if (tokenizer.hasMoreTokens()) {
- final boolean processed= Boolean.valueOf(tokenizer.nextToken()).booleanValue();
- if (processed) {
- log.markAsProcessed(element);
- if (element instanceof IJavaScriptElement)
- log.markAsProcessed(JavaElementResourceMapping.create((IJavaScriptElement) element));
- }
- if (tokenizer.hasMoreTokens()) {
- final boolean renamed= Boolean.valueOf(tokenizer.nextToken()).booleanValue();
- if (renamed && tokenizer.hasMoreTokens()) {
- final String name= tokenizer.nextToken();
- log.setNewName(element, name);
- if (element instanceof IJavaScriptElement)
- log.setNewName(JavaElementResourceMapping.create((IJavaScriptElement) element), name);
- }
- }
- }
- }
- }
-
- public static void storeCreateTargetExecutionLog(String project, Map arguments, CreateTargetExecutionLog log) {
- if (log != null) {
- final StringBuffer buffer= new StringBuffer(64);
- final Object[] selections= log.getSelectedElements();
- for (int index= 0; index < selections.length; index++) {
- final Object selection= selections[index];
- if (selection != null) {
- final Object created= log.getCreatedElement(selection);
- if (created != null) {
- storeLogElement(buffer, project, selection);
- buffer.append(DELIMITER_ELEMENT);
- storeLogElement(buffer, project, created);
- buffer.append(DELIMITER_RECORD);
- }
-
- }
- }
- final String value= new String(buffer.toString().trim());
- if (!"".equals(value)) //$NON-NLS-1$
- arguments.put(ATTRIBUTE_LOG, value);
- }
- }
-
- private static boolean storeLogElement(StringBuffer buffer, String project, Object object) {
- if (object instanceof IJavaScriptElement) {
- final IJavaScriptElement element= (IJavaScriptElement) object;
- buffer.append(JDTRefactoringDescriptor.elementToHandle(project, element));
- return true;
- } else if (object instanceof IResource) {
- final IResource resource= (IResource) object;
- buffer.append(JDTRefactoringDescriptor.resourceToHandle(project, resource));
- return true;
- }
- return false;
- }
-
- public static void storeReorgExecutionLog(String project, Map arguments, ReorgExecutionLog log) {
- if (log != null) {
- final Set set= new HashSet();
- set.addAll(Arrays.asList(log.getProcessedElements()));
- set.addAll(Arrays.asList(log.getRenamedElements()));
- final StringBuffer buffer= new StringBuffer(64);
- for (final Iterator iterator= set.iterator(); iterator.hasNext();) {
- final Object object= iterator.next();
- if (storeLogElement(buffer, project, object)) {
- buffer.append(DELIMITER_ELEMENT);
- buffer.append(log.isProcessed(object));
- buffer.append(DELIMITER_ELEMENT);
- final boolean renamed= log.isRenamed(object);
- buffer.append(renamed);
- if (renamed) {
- buffer.append(DELIMITER_ELEMENT);
- buffer.append(log.getNewName(object));
- }
- buffer.append(DELIMITER_RECORD);
- }
- }
- final String value= new String(buffer.toString().trim());
- if (!"".equals(value)) //$NON-NLS-1$
- arguments.put(ATTRIBUTE_LOG, value);
- }
- }
-
- private ReorgPolicyFactory() {
- // private
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgUtils.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgUtils.java
deleted file mode 100644
index ac62d965..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/ReorgUtils.java
+++ /dev/null
@@ -1,603 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-
-public class ReorgUtils {
-
- //workaround for bug 18311
- private static final ISourceRange fgUnknownRange= new SourceRange(-1, 0);
-
- private ReorgUtils() {
- }
-
- public static boolean isArchiveMember(IJavaScriptElement[] elements) {
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement element= elements[i];
- IPackageFragmentRoot root= (IPackageFragmentRoot)element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null && root.isArchive())
- return true;
- }
- return false;
- }
-
- public static boolean containsOnlyProjects(List elements){
- if (elements.isEmpty())
- return false;
- for(Iterator iter= elements.iterator(); iter.hasNext(); ) {
- if (! isProject(iter.next()))
- return false;
- }
- return true;
- }
-
- public static boolean isProject(Object element){
- return (element instanceof IJavaScriptProject) || (element instanceof IProject);
- }
-
- public static boolean isInsideCompilationUnit(IJavaScriptElement element) {
- return !(element instanceof IJavaScriptUnit) &&
- hasAncestorOfType(element, IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
- public static boolean isInsideClassFile(IJavaScriptElement element) {
- return !(element instanceof IClassFile) &&
- hasAncestorOfType(element, IJavaScriptElement.CLASS_FILE);
- }
-
- public static boolean hasAncestorOfType(IJavaScriptElement element, int type){
- return element.getAncestor(type) != null;
- }
-
- /**
- * May be <code>null</code>.
- */
- public static IJavaScriptUnit getCompilationUnit(IJavaScriptElement javaElement){
- if (javaElement instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) javaElement;
- return (IJavaScriptUnit) javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
- /**
- * some of the returned elements may be <code>null</code>.
- */
- public static IJavaScriptUnit[] getCompilationUnits(IJavaScriptElement[] javaElements){
- IJavaScriptUnit[] result= new IJavaScriptUnit[javaElements.length];
- for (int i= 0; i < javaElements.length; i++) {
- result[i]= getCompilationUnit(javaElements[i]);
- }
- return result;
- }
-
- public static IResource getResource(IJavaScriptElement element){
- if (element instanceof IJavaScriptUnit)
- return ((IJavaScriptUnit)element).getPrimary().getResource();
- else
- return element.getResource();
- }
-
- public static IResource[] getResources(IJavaScriptElement[] elements) {
- IResource[] result= new IResource[elements.length];
- for (int i= 0; i < elements.length; i++) {
- result[i]= ReorgUtils.getResource(elements[i]);
- }
- return result;
- }
-
- public static String getName(IResource resource) {
- String pattern= createNamePattern(resource);
- String[] args= createNameArguments(resource);
- return Messages.format(pattern, args);
- }
-
- private static String createNamePattern(IResource resource) {
- switch(resource.getType()){
- case IResource.FILE:
- return RefactoringCoreMessages.ReorgUtils_0;
- case IResource.FOLDER:
- return RefactoringCoreMessages.ReorgUtils_1;
- case IResource.PROJECT:
- return RefactoringCoreMessages.ReorgUtils_2;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private static String[] createNameArguments(IResource resource) {
- return new String[]{resource.getName()};
- }
-
- public static String getName(IJavaScriptElement element) throws JavaScriptModelException {
- String pattern= createNamePattern(element);
- String[] args= createNameArguments(element);
- return Messages.format(pattern, args);
- }
-
- private static String[] createNameArguments(IJavaScriptElement element) throws JavaScriptModelException {
- switch(element.getElementType()){
- case IJavaScriptElement.CLASS_FILE:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.FIELD:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.IMPORT_CONTAINER:
- return new String[0];
- case IJavaScriptElement.IMPORT_DECLARATION:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.INITIALIZER:
- return new String[0];
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.METHOD:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return new String[]{element.getElementName()};
- case IJavaScriptElement.TYPE:
- IType type= (IType)element;
- String name= type.getElementName();
- if (name.length() == 0 && type.isAnonymous()) {
- String superclassName= Signature.getSimpleName(type.getSuperclassName());
- return new String[]{Messages.format(RefactoringCoreMessages.ReorgUtils_19, superclassName)};
- }
- return new String[]{element.getElementName()};
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private static String createNamePattern(IJavaScriptElement element) throws JavaScriptModelException {
- switch(element.getElementType()){
- case IJavaScriptElement.CLASS_FILE:
- return RefactoringCoreMessages.ReorgUtils_3;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return RefactoringCoreMessages.ReorgUtils_4;
- case IJavaScriptElement.FIELD:
- return RefactoringCoreMessages.ReorgUtils_5;
- case IJavaScriptElement.IMPORT_CONTAINER:
- return RefactoringCoreMessages.ReorgUtils_6;
- case IJavaScriptElement.IMPORT_DECLARATION:
- return RefactoringCoreMessages.ReorgUtils_7;
- case IJavaScriptElement.INITIALIZER:
- return RefactoringCoreMessages.ReorgUtils_8;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return RefactoringCoreMessages.ReorgUtils_9;
- case IJavaScriptElement.METHOD:
- if (((IFunction)element).isConstructor())
- return RefactoringCoreMessages.ReorgUtils_10;
- else
- return RefactoringCoreMessages.ReorgUtils_11;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- if (JavaElementUtil.isDefaultPackage(element))
- return RefactoringCoreMessages.ReorgUtils_13;
- else
- return RefactoringCoreMessages.ReorgUtils_14;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- if (isSourceFolder(element))
- return RefactoringCoreMessages.ReorgUtils_15;
- if (isClassFolder(element))
- return RefactoringCoreMessages.ReorgUtils_16;
- return RefactoringCoreMessages.ReorgUtils_17;
- case IJavaScriptElement.TYPE:
- IType type= (IType)element;
- if (type.getElementName().length() == 0 && type.isAnonymous())
- return RefactoringCoreMessages.ReorgUtils_20;
- return RefactoringCoreMessages.ReorgUtils_18;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public static IResource[] getResources(List elements) {
- List resources= new ArrayList(elements.size());
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IResource)
- resources.add(element);
- }
- return (IResource[]) resources.toArray(new IResource[resources.size()]);
- }
-
- public static IJavaScriptElement[] getJavaElements(List elements) {
- List resources= new ArrayList(elements.size());
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptElement)
- resources.add(element);
- }
- return (IJavaScriptElement[]) resources.toArray(new IJavaScriptElement[resources.size()]);
- }
-
- public static IWorkingSet[] getWorkingSets(List elements) {
- List result= new ArrayList(1);
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IWorkingSet) {
- result.add(element);
- }
- }
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
-
- public static boolean hasSourceAvailable(IMember member) throws JavaScriptModelException{
- return ! member.isBinary() ||
- (member.getSourceRange() != null && ! fgUnknownRange.equals(member.getSourceRange()));
- }
-
- public static IResource[] setMinus(IResource[] setToRemoveFrom, IResource[] elementsToRemove) {
- Set setMinus= new HashSet(setToRemoveFrom.length - setToRemoveFrom.length);
- setMinus.addAll(Arrays.asList(setToRemoveFrom));
- setMinus.removeAll(Arrays.asList(elementsToRemove));
- return (IResource[]) setMinus.toArray(new IResource[setMinus.size()]);
- }
-
- public static IJavaScriptElement[] setMinus(IJavaScriptElement[] setToRemoveFrom, IJavaScriptElement[] elementsToRemove) {
- Set setMinus= new HashSet(setToRemoveFrom.length - setToRemoveFrom.length);
- setMinus.addAll(Arrays.asList(setToRemoveFrom));
- setMinus.removeAll(Arrays.asList(elementsToRemove));
- return (IJavaScriptElement[]) setMinus.toArray(new IJavaScriptElement[setMinus.size()]);
- }
-
- public static IJavaScriptElement[] union(IJavaScriptElement[] set1, IJavaScriptElement[] set2) {
- List union= new ArrayList(set1.length + set2.length);//use lists to avoid sequence problems
- addAll(set1, union);
- addAll(set2, union);
- return (IJavaScriptElement[]) union.toArray(new IJavaScriptElement[union.size()]);
- }
-
- public static IResource[] union(IResource[] set1, IResource[] set2) {
- List union= new ArrayList(set1.length + set2.length);//use lists to avoid sequence problems
- addAll(ReorgUtils.getNotNulls(set1), union);
- addAll(ReorgUtils.getNotNulls(set2), union);
- return (IResource[]) union.toArray(new IResource[union.size()]);
- }
-
- private static void addAll(Object[] array, List list) {
- for (int i= 0; i < array.length; i++) {
- if (! list.contains(array[i]))
- list.add(array[i]);
- }
- }
-
- public static Set union(Set set1, Set set2){
- Set union= new HashSet(set1.size() + set2.size());
- union.addAll(set1);
- union.addAll(set2);
- return union;
- }
-
- public static IType[] getMainTypes(IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- List result= new ArrayList();
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (element instanceof IType && JavaElementUtil.isMainType((IType)element))
- result.add(element);
- }
- return (IType[]) result.toArray(new IType[result.size()]);
- }
-
- public static IFolder[] getFolders(IResource[] resources) {
- Set result= getResourcesOfType(resources, IResource.FOLDER);
- return (IFolder[]) result.toArray(new IFolder[result.size()]);
- }
-
- public static IFile[] getFiles(IResource[] resources) {
- Set result= getResourcesOfType(resources, IResource.FILE);
- return (IFile[]) result.toArray(new IFile[result.size()]);
- }
-
- //the result can be cast down to the requested type array
- public static Set getResourcesOfType(IResource[] resources, int typeMask){
- Set result= new HashSet(resources.length);
- for (int i= 0; i < resources.length; i++) {
- if (isOfType(resources[i], typeMask))
- result.add(resources[i]);
- }
- return result;
- }
-
- //the result can be cast down to the requested type array
- //type is _not_ a mask
- public static List getElementsOfType(IJavaScriptElement[] javaElements, int type){
- List result= new ArrayList(javaElements.length);
- for (int i= 0; i < javaElements.length; i++) {
- if (isOfType(javaElements[i], type))
- result.add(javaElements[i]);
- }
- return result;
- }
-
- public static boolean hasElementsNotOfType(IResource[] resources, int typeMask) {
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource != null && ! isOfType(resource, typeMask))
- return true;
- }
- return false;
- }
-
- //type is _not_ a mask
- public static boolean hasElementsNotOfType(IJavaScriptElement[] javaElements, int type) {
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (element != null && ! isOfType(element, type))
- return true;
- }
- return false;
- }
-
- //type is _not_ a mask
- public static boolean hasElementsOfType(IJavaScriptElement[] javaElements, int type) {
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (element != null && isOfType(element, type))
- return true;
- }
- return false;
- }
-
- public static boolean hasElementsOfType(IJavaScriptElement[] javaElements, int[] types) {
- for (int i= 0; i < types.length; i++) {
- if (hasElementsOfType(javaElements, types[i])) return true;
- }
- return false;
- }
-
- public static boolean hasElementsOfType(IResource[] resources, int typeMask) {
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource != null && isOfType(resource, typeMask))
- return true;
- }
- return false;
- }
-
- private static boolean isOfType(IJavaScriptElement element, int type) {
- return element.getElementType() == type;//this is _not_ a mask
- }
-
- private static boolean isOfType(IResource resource, int type) {
- return resource != null && isFlagSet(resource.getType(), type);
- }
-
- private static boolean isFlagSet(int flags, int flag){
- return (flags & flag) != 0;
- }
-
- public static boolean isSourceFolder(IJavaScriptElement javaElement) throws JavaScriptModelException {
- return (javaElement instanceof IPackageFragmentRoot) &&
- ((IPackageFragmentRoot)javaElement).getKind() == IPackageFragmentRoot.K_SOURCE;
- }
-
- public static boolean isClassFolder(IJavaScriptElement javaElement) throws JavaScriptModelException {
- return (javaElement instanceof IPackageFragmentRoot) &&
- ((IPackageFragmentRoot)javaElement).getKind() == IPackageFragmentRoot.K_BINARY;
- }
-
- public static boolean isPackageFragmentRoot(IJavaScriptProject javaProject) throws JavaScriptModelException{
- return getCorrespondingPackageFragmentRoot(javaProject) != null;
- }
-
- private static boolean isPackageFragmentRootCorrespondingToProject(IPackageFragmentRoot root) {
- return root.getResource() instanceof IProject;
- }
-
- public static IPackageFragmentRoot getCorrespondingPackageFragmentRoot(IJavaScriptProject p) throws JavaScriptModelException {
- IPackageFragmentRoot[] roots= p.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (isPackageFragmentRootCorrespondingToProject(roots[i]))
- return roots[i];
- }
- return null;
- }
-
- public static boolean containsLinkedResources(IResource[] resources){
- for (int i= 0; i < resources.length; i++) {
- if (resources[i] != null && resources[i].isLinked()) return true;
- }
- return false;
- }
-
- public static boolean containsLinkedResources(IJavaScriptElement[] javaElements){
- for (int i= 0; i < javaElements.length; i++) {
- IResource res= getResource(javaElements[i]);
- if (res != null && res.isLinked()) return true;
- }
- return false;
- }
-
- public static boolean canBeDestinationForLinkedResources(IResource resource) {
- return resource.isAccessible() && resource instanceof IProject;
- }
-
- public static boolean canBeDestinationForLinkedResources(IJavaScriptElement javaElement) {
- if (javaElement instanceof IPackageFragmentRoot){
- return isPackageFragmentRootCorrespondingToProject((IPackageFragmentRoot)javaElement);
- } else if (javaElement instanceof IJavaScriptProject){
- return true;//XXX ???
- } else return false;
- }
-
- public static boolean isParentInWorkspaceOrOnDisk(IPackageFragment pack, IPackageFragmentRoot root){
- if (pack == null)
- return false;
- IJavaScriptElement packParent= pack.getParent();
- if (packParent == null)
- return false;
- if (packParent.equals(root))
- return true;
- IResource packageResource= ResourceUtil.getResource(pack);
- IResource packageRootResource= ResourceUtil.getResource(root);
- return isParentInWorkspaceOrOnDisk(packageResource, packageRootResource);
- }
-
- public static boolean isParentInWorkspaceOrOnDisk(IPackageFragmentRoot root, IJavaScriptProject javaProject){
- if (root == null)
- return false;
- IJavaScriptElement rootParent= root.getParent();
- if (rootParent == null)
- return false;
- if (rootParent.equals(root))
- return true;
- IResource packageResource= ResourceUtil.getResource(root);
- IResource packageRootResource= ResourceUtil.getResource(javaProject);
- return isParentInWorkspaceOrOnDisk(packageResource, packageRootResource);
- }
-
- public static boolean isParentInWorkspaceOrOnDisk(IJavaScriptUnit cu, IPackageFragment dest){
- if (cu == null)
- return false;
- IJavaScriptElement cuParent= cu.getParent();
- if (cuParent == null)
- return false;
- if (cuParent.equals(dest))
- return true;
- IResource cuResource= cu.getResource();
- IResource packageResource= ResourceUtil.getResource(dest);
- return isParentInWorkspaceOrOnDisk(cuResource, packageResource);
- }
-
- public static boolean isParentInWorkspaceOrOnDisk(IResource res, IResource maybeParent){
- if (res == null)
- return false;
- return areEqualInWorkspaceOrOnDisk(res.getParent(), maybeParent);
- }
-
- public static boolean areEqualInWorkspaceOrOnDisk(IResource r1, IResource r2){
- if (r1 == null || r2 == null)
- return false;
- if (r1.equals(r2))
- return true;
- URI r1Location= r1.getLocationURI();
- URI r2Location= r2.getLocationURI();
- if (r1Location == null || r2Location == null)
- return false;
- return r1Location.equals(r2Location);
- }
-
- public static IResource[] getNotNulls(IResource[] resources) {
- Collection result= new ArrayList(resources.length);
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource != null && ! result.contains(resource))
- result.add(resource);
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-
- public static IResource[] getNotLinked(IResource[] resources) {
- Collection result= new ArrayList(resources.length);
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource != null && ! result.contains(resource) && ! resource.isLinked())
- result.add(resource);
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-
- /* List<IJavaScriptElement> javaElements
- * return IJavaScriptUnit -> List<IJavaScriptElement>
- */
- public static Map groupByCompilationUnit(List javaElements){
- Map result= new HashMap();
- for (Iterator iter= javaElements.iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- IJavaScriptUnit cu= ReorgUtils.getCompilationUnit(element);
- if (cu != null){
- if (! result.containsKey(cu))
- result.put(cu, new ArrayList(1));
- ((List)result.get(cu)).add(element);
- }
- }
- return result;
- }
-
- public static void splitIntoJavaElementsAndResources(Object[] elements, List javaElementResult, List resourceResult) {
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- if (element instanceof IJavaScriptElement) {
- javaElementResult.add(element);
- } else if (element instanceof IResource) {
- IResource resource= (IResource)element;
- IJavaScriptElement jElement= JavaScriptCore.create(resource);
- if (jElement != null && jElement.exists())
- javaElementResult.add(jElement);
- else
- resourceResult.add(resource);
- }
- }
- }
-
- public static boolean containsElementOrParent(Set elements, IJavaScriptElement element) {
- IJavaScriptElement curr= element;
- do {
- if (elements.contains(curr))
- return true;
- curr= curr.getParent();
- } while (curr != null);
- return false;
- }
-
- public static boolean containsElementOrParent(Set elements, IResource element) {
- IResource curr= element;
- do {
- if (elements.contains(curr))
- return true;
- IJavaScriptElement jElement= JavaScriptCore.create(curr);
- if (jElement != null && jElement.exists()) {
- return containsElementOrParent(elements, jElement);
- }
- curr= curr.getParent();
- } while (curr != null);
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/SourceReferenceUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/SourceReferenceUtil.java
deleted file mode 100644
index b05730c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/SourceReferenceUtil.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-public class SourceReferenceUtil {
-
- //no instances
- private SourceReferenceUtil(){}
-
- public static IFile getFile(ISourceReference ref) {
- IJavaScriptUnit unit= getCompilationUnit(ref);
- return (IFile) unit.getPrimary().getResource();
- }
-
- public static IJavaScriptUnit getCompilationUnit(ISourceReference o){
- Assert.isTrue(! (o instanceof IClassFile));
-
- if (o instanceof IJavaScriptUnit)
- return (IJavaScriptUnit)o;
- if (o instanceof IJavaScriptElement)
- return (IJavaScriptUnit) ((IJavaScriptElement)o).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- return null;
- }
-
- private static boolean hasParentInSet(IJavaScriptElement elem, Set set){
- IJavaScriptElement parent= elem.getParent();
- while (parent != null) {
- if (set.contains(parent))
- return true;
- parent= parent.getParent();
- }
- return false;
- }
-
- public static ISourceReference[] removeAllWithParentsSelected(ISourceReference[] elems){
- Set set= new HashSet(Arrays.asList(elems));
- List result= new ArrayList(elems.length);
- for (int i= 0; i < elems.length; i++) {
- ISourceReference elem= elems[i];
- if (! (elem instanceof IJavaScriptElement))
- result.add(elem);
- else{
- if (! hasParentInSet(((IJavaScriptElement)elem), set))
- result.add(elem);
- }
- }
- return (ISourceReference[]) result.toArray(new ISourceReference[result.size()]);
- }
-
- /**
- * @return IFile -> List of ISourceReference (elements from that file)
- */
- public static Map groupByFile(ISourceReference[] elems) {
- Map map= new HashMap();
- for (int i= 0; i < elems.length; i++) {
- ISourceReference elem= elems[i];
- IFile file= SourceReferenceUtil.getFile(elem);
- if (! map.containsKey(file))
- map.put(file, new ArrayList());
- ((List)map.get(file)).add(elem);
- }
- return map;
- }
-
- public static ISourceReference[] sortByOffset(ISourceReference[] methods){
- Arrays.sort(methods, new Comparator(){
- public int compare(Object o1, Object o2){
- try{
- return ((ISourceReference)o2).getSourceRange().getOffset() - ((ISourceReference)o1).getSourceRange().getOffset();
- } catch (JavaScriptModelException e){
- return o2.hashCode() - o1.hashCode();
- }
- }
- });
- return methods;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java
deleted file mode 100644
index a3143457..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
-
-/**
- * Refactoring contribution for the change method signature refactoring.
- *
- *
- */
-public final class ChangeMethodSignatureRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ChangeSignatureRefactoring(null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java
deleted file mode 100644
index 80cf08b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
-
-/**
- * Refactoring contribution for the extract interface refactoring.
- *
- *
- */
-public final class ChangeTypeRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ChangeTypeRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java
deleted file mode 100644
index 8120fe4e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring;
-
-/**
- * Refactoring contribution for the convert anonymous refactoring.
- *
- *
- */
-public final class ConvertAnonymousRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ConvertAnonymousToNestedRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java
deleted file mode 100644
index bdbb16c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyRefactoring;
-
-/**
- * Refactoring contribution for the copy refactoring.
- *
- *
- */
-public final class CopyRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new JavaCopyRefactoring(new JavaCopyProcessor(null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java
deleted file mode 100644
index 50e7e373..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteRefactoring;
-
-/**
- * Refactoring contribution for the delete refactoring.
- *
- *
- */
-public final class DeleteRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new JavaDeleteRefactoring(new JavaDeleteProcessor(null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractConstantRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractConstantRefactoringContribution.java
deleted file mode 100644
index d148d929..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractConstantRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
-
-/**
- * Refactoring contribution for the extract constant refactoring.
- *
- *
- */
-public final class ExtractConstantRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ExtractConstantRefactoring((IJavaScriptUnit) null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java
deleted file mode 100644
index d43c39a2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractMethodRefactoring;
-
-/**
- * Refactoring contribution for the extract method refactoring.
- *
- *
- */
-public final class ExtractMethodRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ExtractMethodRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java
deleted file mode 100644
index 5da79514..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeRefactoring;
-
-/**
- * Refactoring contribution for the extract supertype refactoring.
- *
- *
- */
-public final class ExtractSupertypeRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ExtractSupertypeRefactoring(new ExtractSupertypeProcessor(null, null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractTempRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractTempRefactoringContribution.java
deleted file mode 100644
index 7e183c56..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractTempRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractTempRefactoring;
-
-/**
- * Refactoring contribution for the extract temp refactoring.
- *
- *
- */
-public final class ExtractTempRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new ExtractTempRefactoring((IJavaScriptUnit) null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java
deleted file mode 100644
index 564b7416..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineConstantRefactoring;
-
-/**
- * Refactoring contribution for the inline constant refactoring.
- *
- *
- */
-public final class InlineConstantRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new InlineConstantRefactoring(null, null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineMethodRefactoringContribution.java
deleted file mode 100644
index 6a2f4e8c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineMethodRefactoringContribution.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Refactoring contribution for the inline method refactoring.
- *
- *
- */
-public final class InlineMethodRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- int selectionStart= -1;
- int selectionLength= -1;
- IJavaScriptUnit unit= null;
- JavaScriptUnit node= null;
- RefactoringArguments arguments= null;
- if (descriptor instanceof JDTRefactoringDescriptor) {
- final JDTRefactoringDescriptor extended= (JDTRefactoringDescriptor) descriptor;
- arguments= extended.createArguments();
- }
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- selectionStart= offset;
- selectionLength= length;
- } else
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}), null));
- }
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_inputs_do_not_exist, new String[] { RefactoringCoreMessages.InlineMethodRefactoring_name, IJavaScriptRefactorings.INLINE_METHOD}), null));
- else {
- if (element instanceof IJavaScriptUnit) {
- unit= (IJavaScriptUnit) element;
- if (selection == null)
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION), null));
- } else if (element instanceof IFunction) {
- final IFunction method= (IFunction) element;
- try {
- final ISourceRange range= method.getNameRange();
- if (range != null) {
- selectionStart= range.getOffset();
- selectionLength= range.getLength();
- } else
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}), null));
- } catch (JavaScriptModelException exception) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_inputs_do_not_exist, new String[] { RefactoringCoreMessages.InlineMethodRefactoring_name, IJavaScriptRefactorings.INLINE_METHOD}), exception));
- }
- unit= method.getJavaScriptUnit();
- } else
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT}), null));
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setSource(unit);
- node= (JavaScriptUnit) parser.createAST(null);
- }
- } else
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT), null));
- } else
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments, null));
- return InlineMethodRefactoring.create(unit, node, selectionStart, selectionLength);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java
deleted file mode 100644
index 9a9f9eb4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineTempRefactoring;
-
-/**
- * Refactoring contribution for the inline temp refactoring.
- *
- *
- */
-public final class InlineTempRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new InlineTempRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java
deleted file mode 100644
index f40b286c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring;
-
-/**
- * Refactoring contribution for the introduce factory refactoring.
- *
- *
- */
-public final class IntroduceFactoryRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new IntroduceFactoryRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java
deleted file mode 100644
index 89add449..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring;
-
-/**
- * Refactoring contribution for the introduce indirection refactoring.
- *
- *
- */
-public final class IntroduceIndirectionRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new IntroduceIndirectionRefactoring(null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java
deleted file mode 100644
index 23f56336..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceParameterRefactoring;
-
-/**
- * Refactoring contribution for the introduce parameter refactoring.
- *
- *
- */
-public final class IntroduceParameterRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new IntroduceParameterRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java
deleted file mode 100644
index d7988b17..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring;
-
-/**
- * Refactoring contribution for the move member type refactoring.
- *
- *
- */
-public final class MoveMemberTypeRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new MoveInnerToTopRefactoring(null, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java
deleted file mode 100644
index f73c14af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodRefactoring;
-
-/**
- * Refactoring contribution for the move method refactoring.
- *
- *
- */
-public final class MoveMethodRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new MoveInstanceMethodRefactoring(new MoveInstanceMethodProcessor(null, null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java
deleted file mode 100644
index 197c24d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.JavaMoveRefactoring;
-
-/**
- * Refactoring contribution for the move refactoring.
- *
- *
- */
-public final class MoveRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new JavaMoveRefactoring(new JavaMoveProcessor(null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java
deleted file mode 100644
index c14e00d3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.MoveStaticMembersDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.JavaMoveRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor;
-
-/**
- * Refactoring contribution for the move static members refactoring.
- *
- *
- */
-public final class MoveStaticMembersRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new JavaMoveRefactoring(new MoveStaticMembersProcessor(null, null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new MoveStaticMembersDescriptor();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java
deleted file mode 100644
index f8a14cc1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
-
-/**
- * Refactoring contribution for the extract interface refactoring.
- *
- *
- */
-public final class PromoteTempToFieldRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new PromoteTempToFieldRefactoring(null, 0, 0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java
deleted file mode 100644
index 855c1472..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor;
-
-/**
- * Refactoring contribution for the pull up refactoring.
- *
- *
- */
-public final class PullUpRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new PullUpRefactoring(new PullUpRefactoringProcessor(null, null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java
deleted file mode 100644
index 1e16dded..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor;
-
-/**
- * Refactoring contribution for the push down refactoring.
- *
- *
- */
-public final class PushDownRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new PushDownRefactoring(new PushDownRefactoringProcessor(null));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameCompilationUnitRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameCompilationUnitRefactoringContribution.java
deleted file mode 100644
index 77389407..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameCompilationUnitRefactoringContribution.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-
-/**
- * Refactoring contribution for the rename compilation unit refactoring.
- *
- *
- */
-public final class RenameCompilationUnitRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new JavaRenameRefactoring(new RenameCompilationUnitProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_JAVASCRIPT_UNIT);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameFieldRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameFieldRefactoringContribution.java
deleted file mode 100644
index c4bb9650..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameFieldRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-
-/**
- * Refactoring contribution for the rename field refactoring.
- *
- *
- */
-public final class RenameFieldRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameFieldProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_FIELD);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameJavaProjectRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameJavaProjectRefactoringContribution.java
deleted file mode 100644
index 5da7960d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameJavaProjectRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameJavaProjectProcessor;
-
-/**
- * Refactoring contribution for the rename java project refactoring.
- *
- *
- */
-public final class RenameJavaProjectRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameJavaProjectProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_JAVA_PROJECT);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameLocalVariableRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameLocalVariableRefactoringContribution.java
deleted file mode 100644
index 57b6f024..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameLocalVariableRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameLocalVariableProcessor;
-
-/**
- * Refactoring contribution for the rename local variable refactoring.
- *
- *
- */
-public final class RenameLocalVariableRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameLocalVariableProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameMethodRefactoringContribution.java
deleted file mode 100644
index f006bdea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameMethodRefactoringContribution.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import java.util.Map;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor;
-
-/**
- * Refactoring contribution for the rename method refactoring.
- *
- *
- */
-public final class RenameMethodRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws JavaScriptModelException {
- String project= descriptor.getProject();
- Map arguments= ((JDTRefactoringDescriptor) descriptor).getArguments();
- String input= (String) arguments.get(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- IFunction method= (IFunction) JDTRefactoringDescriptor.handleToElement(project, input);
-
- JavaRenameProcessor processor;
- if (MethodChecks.isVirtual(method)) {
- processor= new RenameVirtualMethodProcessor(method);
- } else {
- processor= new RenameNonVirtualMethodProcessor(method);
- }
- return new JavaRenameRefactoring(processor);
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_METHOD);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenamePackageRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenamePackageRefactoringContribution.java
deleted file mode 100644
index c1a81c6a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenamePackageRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-
-/**
- * Refactoring contribution for the rename package refactoring.
- *
- *
- */
-public final class RenamePackageRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenamePackageProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_PACKAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameResourceRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameResourceRefactoringContribution.java
deleted file mode 100644
index 793463b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameResourceRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameResourceProcessor;
-
-/**
- * Refactoring contribution for the rename resource refactoring.
- *
- *
- */
-public final class RenameResourceRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameResourceProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_RESOURCE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameSourceFolderRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameSourceFolderRefactoringContribution.java
deleted file mode 100644
index 61e7c1fd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameSourceFolderRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameSourceFolderProcessor;
-
-/**
- * Refactoring contribution for the rename source folder refactoring.
- *
- *
- */
-public final class RenameSourceFolderRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameSourceFolderProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_SOURCE_FOLDER);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameTypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameTypeRefactoringContribution.java
deleted file mode 100644
index a6a42852..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/RenameTypeRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-
-/**
- * Refactoring contribution for the rename type refactoring.
- *
- *
- */
-public final class RenameTypeRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public Refactoring createRefactoring(final RefactoringDescriptor descriptor) {
- return new JavaRenameRefactoring(new RenameTypeProcessor(null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new RenameJavaScriptElementDescriptor(IJavaScriptRefactorings.RENAME_TYPE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java
deleted file mode 100644
index c658eea8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring;
-
-/**
- * Refactoring contribution for the self encapsulate field refactoring.
- *
- *
- */
-public final class SelfEncapsulateRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new SelfEncapsulateFieldRefactoring(null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java
deleted file mode 100644
index d0df51c8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.scripting;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.UseSupertypeDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeRefactoring;
-
-/**
- * Refactoring contribution for the use supertype refactoring.
- *
- *
- */
-public final class UseSupertypeRefactoringContribution extends JDTRefactoringContribution {
-
- /**
- * {@inheritDoc}
- */
- public final Refactoring createRefactoring(final RefactoringDescriptor descriptor) throws CoreException {
- return new UseSuperTypeRefactoring(new UseSuperTypeProcessor(null, null));
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringDescriptor createDescriptor() {
- return new UseSupertypeDescriptor();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/AccessAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/AccessAnalyzer.java
deleted file mode 100644
index 95db7177..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/AccessAnalyzer.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * jens.lukowski@gmx.de - contributed code to convert prefix and postfix
- * expressions into a combination of setter and getter calls.
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.sef;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-
-/**
- * Analyzer to find all references to the field and to determine how to convert
- * them into setter or getter calls.
- */
-class AccessAnalyzer extends ASTVisitor {
-
- private IJavaScriptUnit fCUnit;
- private IVariableBinding fFieldBinding;
- private ITypeBinding fDeclaringClassBinding;
- private String fGetter;
- private String fSetter;
- private ASTRewrite fRewriter;
- private ImportRewrite fImportRewriter;
- private List fGroupDescriptions;
- private RefactoringStatus fStatus;
- private boolean fSetterMustReturnValue;
- private boolean fEncapsulateDeclaringClass;
- private boolean fIsFieldFinal;
-
- private boolean fRemoveStaticImport;
- private boolean fReferencingGetter;
- private boolean fReferencingSetter;
-
- private static final String READ_ACCESS= RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_encapsulate_read_access;
- private static final String WRITE_ACCESS= RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_encapsulate_write_access;
- private static final String PREFIX_ACCESS= RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_encapsulate_prefix_access;
- private static final String POSTFIX_ACCESS= RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_encapsulate_postfix_access;
-
- public AccessAnalyzer(SelfEncapsulateFieldRefactoring refactoring, IJavaScriptUnit unit, IVariableBinding field, ITypeBinding declaringClass, ASTRewrite rewriter, ImportRewrite importRewrite) {
- Assert.isNotNull(refactoring);
- Assert.isNotNull(unit);
- Assert.isNotNull(field);
- Assert.isNotNull(declaringClass);
- Assert.isNotNull(rewriter);
- Assert.isNotNull(importRewrite);
- fCUnit= unit;
- fFieldBinding= field.getVariableDeclaration();
- fDeclaringClassBinding= declaringClass;
- fRewriter= rewriter;
- fImportRewriter= importRewrite;
- fGroupDescriptions= new ArrayList();
- fGetter= refactoring.getGetterName();
- fSetter= refactoring.getSetterName();
- fEncapsulateDeclaringClass= refactoring.getEncapsulateDeclaringClass();
- fIsFieldFinal= false;
-
- fStatus= new RefactoringStatus();
- }
-
- public boolean getSetterMustReturnValue() {
- return fSetterMustReturnValue;
- }
-
- public RefactoringStatus getStatus() {
- return fStatus;
- }
-
- public List getGroupDescriptions() {
- return fGroupDescriptions;
- }
-
- public boolean visit(Assignment node) {
- Expression lhs= node.getLeftHandSide();
- if (!considerBinding(resolveBinding(lhs), lhs))
- return true;
-
- checkParent(node);
- if (!fIsFieldFinal) {
- // Write access.
- AST ast= node.getAST();
- FunctionInvocation invocation= ast.newFunctionInvocation();
- invocation.setName(ast.newSimpleName(fSetter));
- fReferencingSetter= true;
- Expression receiver= getReceiver(lhs);
- if (receiver != null)
- invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver));
- List arguments= invocation.arguments();
- if (node.getOperator() == Assignment.Operator.ASSIGN) {
- arguments.add(fRewriter.createCopyTarget(node.getRightHandSide()));
- } else {
- // This is the compound assignment case: field+= 10;
- boolean needsParentheses= ASTNodes.needsParentheses(node.getRightHandSide());
- InfixExpression exp= ast.newInfixExpression();
- exp.setOperator(ASTNodes.convertToInfixOperator(node.getOperator()));
- FunctionInvocation getter= ast.newFunctionInvocation();
- getter.setName(ast.newSimpleName(fGetter));
- fReferencingGetter= true;
- if (receiver != null)
- getter.setExpression((Expression)fRewriter.createCopyTarget(receiver));
- exp.setLeftOperand(getter);
- Expression rhs= (Expression)fRewriter.createCopyTarget(node.getRightHandSide());
- if (needsParentheses) {
- ParenthesizedExpression p= ast.newParenthesizedExpression();
- p.setExpression(rhs);
- rhs= p;
- }
- exp.setRightOperand(rhs);
- arguments.add(exp);
- }
- fRewriter.replace(node, invocation, createGroupDescription(WRITE_ACCESS));
- }
- node.getRightHandSide().accept(this);
- return false;
- }
-
- public boolean visit(SimpleName node) {
- if (!node.isDeclaration() && considerBinding(node.resolveBinding(), node)) {
- fReferencingGetter= true;
- fRewriter.replace(
- node,
- fRewriter.createStringPlaceholder(fGetter + "()", ASTNode.FUNCTION_INVOCATION), //$NON-NLS-1$
- createGroupDescription(READ_ACCESS));
- }
- return true;
- }
-
- public boolean visit(ImportDeclaration node) {
- if (considerBinding(node.resolveBinding(), node)) {
- fRemoveStaticImport= true;
- }
- return false;
- }
-
- public boolean visit(PrefixExpression node) {
- Expression operand= node.getOperand();
- if (!considerBinding(resolveBinding(operand), operand))
- return true;
-
- PrefixExpression.Operator operator= node.getOperator();
- if (operator != PrefixExpression.Operator.INCREMENT && operator != PrefixExpression.Operator.DECREMENT)
- return true;
-
- checkParent(node);
-
- fRewriter.replace(node,
- createInvocation(node.getAST(), node.getOperand(), node.getOperator().toString()),
- createGroupDescription(PREFIX_ACCESS));
- return false;
- }
-
- public boolean visit(PostfixExpression node) {
- Expression operand= node.getOperand();
- if (!considerBinding(resolveBinding(operand), operand))
- return true;
-
- ASTNode parent= node.getParent();
- if (!(parent instanceof ExpressionStatement)) {
- fStatus.addError(RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_cannot_convert_postfix_expression,
- JavaStatusContext.create(fCUnit, new SourceRange(node)));
- return false;
- }
- fRewriter.replace(node,
- createInvocation(node.getAST(), node.getOperand(), node.getOperator().toString()),
- createGroupDescription(POSTFIX_ACCESS));
- return false;
- }
-
- public boolean visit(FunctionDeclaration node) {
- String name= node.getName().getIdentifier();
- if (name.equals(fGetter) || name.equals(fSetter))
- return false;
- return true;
- }
-
- public void endVisit(JavaScriptUnit node) {
- // If we don't had a static import to the field we don't
- // have to add any, even if we generated a setter or
- // getter access.
- if (!fRemoveStaticImport)
- return;
-
- ITypeBinding type= fFieldBinding.getDeclaringClass();
- String fieldName= fFieldBinding.getName();
- String typeName= type.getQualifiedName();
- if (fRemoveStaticImport) {
- fImportRewriter.removeStaticImport(typeName + "." + fieldName); //$NON-NLS-1$
- }
- if (fReferencingGetter) {
- fImportRewriter.addStaticImport(typeName, fGetter, false);
- }
- if (fReferencingSetter) {
- fImportRewriter.addStaticImport(typeName, fSetter, false);
- }
- }
-
- private boolean considerBinding(IBinding binding, ASTNode node) {
- if (!(binding instanceof IVariableBinding))
- return false;
- boolean result= Bindings.equals(fFieldBinding, ((IVariableBinding)binding).getVariableDeclaration());
- if (!result || fEncapsulateDeclaringClass)
- return result;
-
- if (binding instanceof IVariableBinding) {
- AbstractTypeDeclaration type= (AbstractTypeDeclaration)ASTNodes.getParent(node, AbstractTypeDeclaration.class);
- if (type != null) {
- ITypeBinding declaringType= type.resolveBinding();
- return !Bindings.equals(fDeclaringClassBinding, declaringType);
- }
- }
- return true;
- }
-
- private void checkParent(ASTNode node) {
- ASTNode parent= node.getParent();
- if (!(parent instanceof ExpressionStatement))
- fSetterMustReturnValue= true;
- }
-
- private IBinding resolveBinding(Expression expression) {
- if (expression instanceof SimpleName)
- return ((SimpleName)expression).resolveBinding();
- else if (expression instanceof QualifiedName)
- return ((QualifiedName)expression).resolveBinding();
- else if (expression instanceof FieldAccess)
- return ((FieldAccess)expression).getName().resolveBinding();
- return null;
- }
-
- private Expression getReceiver(Expression expression) {
- int type= expression.getNodeType();
- switch(type) {
- case ASTNode.SIMPLE_NAME:
- return null;
- case ASTNode.QUALIFIED_NAME:
- return ((QualifiedName)expression).getQualifier();
- case ASTNode.FIELD_ACCESS:
- return ((FieldAccess)expression).getExpression();
- }
- return null;
- }
-
- private FunctionInvocation createInvocation(AST ast, Expression operand, String operator) {
- Expression receiver= getReceiver(operand);
- FunctionInvocation invocation= ast.newFunctionInvocation();
- invocation.setName(ast.newSimpleName(fSetter));
- if (receiver != null)
- invocation.setExpression((Expression)fRewriter.createCopyTarget(receiver));
- InfixExpression argument= ast.newInfixExpression();
- invocation.arguments().add(argument);
- if ("++".equals(operator)) { //$NON-NLS-1$
- argument.setOperator(InfixExpression.Operator.PLUS);
- } else if ("--".equals(operator)) { //$NON-NLS-1$
- argument.setOperator(InfixExpression.Operator.MINUS);
- } else {
- Assert.isTrue(false, "Should not happen"); //$NON-NLS-1$
- }
- FunctionInvocation getter= ast.newFunctionInvocation();
- getter.setName(ast.newSimpleName(fGetter));
- if (receiver != null)
- getter.setExpression((Expression)fRewriter.createCopyTarget(receiver));
- argument.setLeftOperand(getter);
- argument.setRightOperand(ast.newNumberLiteral("1")); //$NON-NLS-1$
-
- fReferencingGetter= true;
- fReferencingSetter= true;
-
- return invocation;
- }
-
- private TextEditGroup createGroupDescription(String name) {
- TextEditGroup result= new TextEditGroup(name);
- fGroupDescriptions.add(result);
- return result;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java
deleted file mode 100644
index 7337fceb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java
+++ /dev/null
@@ -1,823 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * jens.lukowski@gmx.de - contributed code to convert prefix and postfix
- * expressions into a combination of setter and getter calls.
- * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for
- * bug Encapsulate field can fail when two variables in one variable declaration (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=51540).
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.sef;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.NamingConventions;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.Message;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Encapsulates a field into getter and setter calls.
- */
-public class SelfEncapsulateFieldRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
- private static final String ATTRIBUTE_GETTER= "getter"; //$NON-NLS-1$
- private static final String ATTRIBUTE_SETTER= "setter"; //$NON-NLS-1$
- private static final String ATTRIBUTE_INSERTION= "insertion"; //$NON-NLS-1$
- private static final String ATTRIBUTE_COMMENTS= "comments"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DECLARING= "declaring"; //$NON-NLS-1$
-
- private IField fField;
- private TextChangeManager fChangeManager;
-
- private JavaScriptUnit fRoot;
- private VariableDeclarationFragment fFieldDeclaration;
- private ASTRewrite fRewriter;
- private ImportRewrite fImportRewrite;
-
- private int fVisibility= -1;
- private String fGetterName;
- private String fSetterName;
- private String fArgName;
- private boolean fSetterMustReturnValue;
- private int fInsertionIndex; // -1 represents as first method.
- private boolean fEncapsulateDeclaringClass;
- private boolean fGenerateJavadoc;
-
- private List fUsedReadNames;
- private List fUsedModifyNames;
- private boolean fConsiderVisibility=true;
-
- private static final String NO_NAME= ""; //$NON-NLS-1$
-
- /**
- * Creates a new self encapsulate field refactoring.
- * @param field the field, or <code>null</code> if invoked by scripting
- * @throws JavaScriptModelException
- */
- public SelfEncapsulateFieldRefactoring(IField field) throws JavaScriptModelException {
- fEncapsulateDeclaringClass= true;
- fChangeManager= new TextChangeManager();
- fField= field;
- if (field != null)
- initialize(field);
- }
-
- private void initialize(IField field) throws JavaScriptModelException {
- fGetterName= GetterSetterUtil.getGetterName(field, null);
- fSetterName= GetterSetterUtil.getSetterName(field, null);
- fArgName= NamingConventions.removePrefixAndSuffixForFieldName(field.getJavaScriptProject(), field.getElementName(), field.getFlags());
- checkArgName();
- }
-
- public IField getField() {
- return fField;
- }
-
- public String getGetterName() {
- return fGetterName;
- }
-
- public void setGetterName(String name) {
- fGetterName= name;
- Assert.isNotNull(fGetterName);
- }
-
- public String getSetterName() {
- return fSetterName;
- }
-
- public void setSetterName(String name) {
- fSetterName= name;
- Assert.isNotNull(fSetterName);
- }
-
- public void setInsertionIndex(int index) {
- fInsertionIndex= index;
- }
-
- public int getVisibility() {
- return fVisibility;
- }
-
- public void setVisibility(int visibility) {
- fVisibility= visibility;
- }
-
- public void setEncapsulateDeclaringClass(boolean encapsulateDeclaringClass) {
- fEncapsulateDeclaringClass= encapsulateDeclaringClass;
- }
-
- public boolean getEncapsulateDeclaringClass() {
- return fEncapsulateDeclaringClass;
- }
-
- public boolean getGenerateJavadoc() {
- return fGenerateJavadoc;
- }
-
- public void setGenerateJavadoc(boolean value) {
- fGenerateJavadoc= value;
- }
-
- //----activation checking ----------------------------------------------------------
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- if (fVisibility < 0)
- fVisibility= (fField.getFlags() & (Flags.AccPublic | Flags.AccPrivate));
- RefactoringStatus result= new RefactoringStatus();
- result.merge(Checks.checkAvailability(fField));
- if (result.hasFatalError())
- return result;
- fRoot= new RefactoringASTParser(AST.JLS3).parse(fField.getJavaScriptUnit(), true, pm);
- ISourceRange sourceRange= fField.getNameRange();
- ASTNode node= NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
- if (node == null) {
- return mappingErrorFound(result, node);
- }
- fFieldDeclaration= (VariableDeclarationFragment)ASTNodes.getParent(node, VariableDeclarationFragment.class);
- if (fFieldDeclaration == null) {
- return mappingErrorFound(result, node);
- }
- if (fFieldDeclaration.resolveBinding() == null) {
- if (!processCompilerError(result, node))
- result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
- return result;
- }
- computeUsedNames();
- fRewriter= ASTRewrite.create(fRoot.getAST());
- return result;
- }
-
- private RefactoringStatus mappingErrorFound(RefactoringStatus result, ASTNode node) {
- if (node != null && (node.getFlags() & ASTNode.MALFORMED) != 0 && processCompilerError(result, node))
- return result;
- result.addFatalError(getMappingErrorMessage());
- return result;
- }
-
- private boolean processCompilerError(RefactoringStatus result, ASTNode node) {
- Message[] messages= ASTNodes.getMessages(node, ASTNodes.INCLUDE_ALL_PARENTS);
- if (messages.length == 0)
- return false;
- result.addFatalError(Messages.format(
- RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_field,
- new String[] { fField.getElementName(), messages[0].getMessage()}));
- return true;
- }
-
- private String getMappingErrorMessage() {
- return Messages.format(
- RefactoringCoreMessages.SelfEncapsulateField_cannot_analyze_selected_field,
- new String[] {fField.getElementName()});
- }
-
- //---- Input checking ----------------------------------------------------------
-
- public RefactoringStatus checkMethodNames() {
- return checkMethodNames(isUsingLocalGetter(),isUsingLocalSetter());
- }
-
- public RefactoringStatus checkMethodNames(boolean usingLocalGetter, boolean usingLocalSetter) {
- RefactoringStatus result= new RefactoringStatus();
- IType declaringType= fField.getDeclaringType();
- checkName(result, fGetterName, fUsedReadNames, declaringType, usingLocalGetter, fField);
- checkName(result, fSetterName, fUsedModifyNames, declaringType, usingLocalSetter, fField);
- return result;
- }
-
- private static void checkName(RefactoringStatus status, String name, List usedNames, IType type, boolean reUseExistingField, IField field) {
- if ("".equals(name)) { //$NON-NLS-1$
- status.addFatalError(RefactoringCoreMessages.Checks_Choose_name);
- return;
- }
- boolean isStatic=false;
- try {
- isStatic= Flags.isStatic(field.getFlags());
- } catch (JavaScriptModelException e) {
- }
- status.merge(Checks.checkMethodName(name));
- for (Iterator iter= usedNames.iterator(); iter.hasNext(); ) {
- IFunctionBinding method= (IFunctionBinding)iter.next();
- String selector= method.getName();
- if (selector.equals(name)) {
- if (!reUseExistingField) {
- status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_method_exists, new String[] { BindingLabelProvider.getBindingLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), type.getElementName() }));
- } else {
- boolean methodIsStatic= Modifier.isStatic(method.getModifiers());
- if (methodIsStatic && !isStatic)
- status.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field, new String[] { method.getName(), field.getElementName() }));
- if (!methodIsStatic && isStatic)
- status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field, new String[] { method.getName(), field.getElementName() }));
- return;
- }
-
- }
- }
- if (reUseExistingField)
- status.addFatalError(Messages.format(
- RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError,
- new String[] {name, type.getElementName()}));
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- fChangeManager.clear();
- pm.beginTask(NO_NAME, 12);
- pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);
- boolean usingLocalGetter=isUsingLocalGetter();
- boolean usingLocalSetter=isUsingLocalSetter();
- result.merge(checkMethodNames(usingLocalGetter,usingLocalSetter));
- pm.worked(1);
- if (result.hasFatalError())
- return result;
- pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
- final SubProgressMonitor subPm= new SubProgressMonitor(pm, 5);
- IJavaScriptUnit[] affectedCUs= RefactoringSearchEngine.findAffectedCompilationUnits(
- SearchPattern.createPattern(fField, IJavaScriptSearchConstants.REFERENCES),
- RefactoringScopeFactory.create(fField, fConsiderVisibility),
- subPm,
- result, true);
-
- checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
- if (result.hasFatalError())
- return result;
-
- pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
- IProgressMonitor sub= new SubProgressMonitor(pm, 5);
- sub.beginTask(NO_NAME, affectedCUs.length);
- IVariableBinding fieldIdentifier= fFieldDeclaration.resolveBinding();
- ITypeBinding declaringClass=
- ((AbstractTypeDeclaration)ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding();
- List ownerDescriptions= new ArrayList();
- IJavaScriptUnit owner= fField.getJavaScriptUnit();
- fImportRewrite= StubUtility.createImportRewrite(fRoot, true);
-
- for (int i= 0; i < affectedCUs.length; i++) {
- IJavaScriptUnit unit= affectedCUs[i];
- sub.subTask(unit.getElementName());
- JavaScriptUnit root= null;
- ASTRewrite rewriter= null;
- ImportRewrite importRewrite;
- List descriptions;
- if (owner.equals(unit)) {
- root= fRoot;
- rewriter= fRewriter;
- importRewrite= fImportRewrite;
- descriptions= ownerDescriptions;
- } else {
- root= new RefactoringASTParser(AST.JLS3).parse(unit, true);
- rewriter= ASTRewrite.create(root.getAST());
- descriptions= new ArrayList();
- importRewrite= StubUtility.createImportRewrite(root, true);
- }
- checkCompileErrors(result, root, unit);
- AccessAnalyzer analyzer= new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
- root.accept(analyzer);
- result.merge(analyzer.getStatus());
- if (!fSetterMustReturnValue)
- fSetterMustReturnValue= analyzer.getSetterMustReturnValue();
- if (result.hasFatalError()) {
- fChangeManager.clear();
- return result;
- }
- descriptions.addAll(analyzer.getGroupDescriptions());
- if (!owner.equals(unit))
- createEdits(unit, rewriter, descriptions, importRewrite);
- sub.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(),usingLocalSetter, usingLocalGetter));
- createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);
-
- sub.done();
- IFile[] filesToBeModified= ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
- result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
- if (result.hasFatalError())
- return result;
- ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
- return result;
- }
-
- private void createEdits(IJavaScriptUnit unit, ASTRewrite rewriter, List groups, ImportRewrite importRewrite) throws CoreException {
- TextChange change= fChangeManager.get(unit);
- MultiTextEdit root= new MultiTextEdit();
- change.setEdit(root);
- root.addChild(importRewrite.rewriteImports(null));
- root.addChild(rewriter.rewriteAST());
- for (Iterator iter= groups.iterator(); iter.hasNext();) {
- change.addTextEditGroup((TextEditGroup)iter.next());
- }
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fField.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final IType declaring= fField.getDeclaringType();
- try {
- if (declaring.isAnonymous() || declaring.isLocal())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.SelfEncapsulateField_descriptor_description_short, fField.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fField, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_original_pattern, JavaScriptElementLabels.getElementLabel(fField, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_getter_pattern, fGetterName));
- comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_setter_pattern, fSetterName));
- String visibility= JdtFlags.getVisibilityString(fVisibility);
- if ("".equals(visibility)) //$NON-NLS-1$
- visibility= RefactoringCoreMessages.SelfEncapsulateField_default_visibility;
- comment.addSetting(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_visibility_pattern, visibility));
- if (fEncapsulateDeclaringClass)
- comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_use_accessors);
- else
- comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_do_not_use_accessors);
- if (fGenerateJavadoc)
- comment.addSetting(RefactoringCoreMessages.SelfEncapsulateField_generate_comments);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.ENCAPSULATE_FIELD, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fField));
- arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
- arguments.put(ATTRIBUTE_INSERTION, new Integer(fInsertionIndex).toString());
- arguments.put(ATTRIBUTE_SETTER, fSetterName);
- arguments.put(ATTRIBUTE_GETTER, fGetterName);
- arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fGenerateJavadoc).toString());
- arguments.put(ATTRIBUTE_DECLARING, Boolean.valueOf(fEncapsulateDeclaringClass).toString());
- final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, getName());
- TextChange[] changes= fChangeManager.getAllChanges();
- pm.beginTask(NO_NAME, changes.length);
- pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_create_changes);
- for (int i= 0; i < changes.length; i++) {
- result.add(changes[i]);
- pm.worked(1);
- }
- pm.done();
- return result;
- }
-
- public String getName() {
- return RefactoringCoreMessages.SelfEncapsulateField_name;
- }
-
- //---- Helper methods -------------------------------------------------------------
-
- private void checkCompileErrors(RefactoringStatus result, JavaScriptUnit root, IJavaScriptUnit element) {
- IProblem[] messages= root.getProblems();
- for (int i= 0; i < messages.length; i++) {
- IProblem problem= messages[i];
- if (!isIgnorableProblem(problem)) {
- result.addError(Messages.format(
- RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_update,
- element.getElementName()), JavaStatusContext.create(element));
- return;
- }
- }
- }
-
- private void checkInHierarchy(RefactoringStatus status, boolean usingLocalGetter, boolean usingLocalSetter) {
- AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class);
- ITypeBinding type= declaration.resolveBinding();
- if (type != null) {
- ITypeBinding fieldType= fFieldDeclaration.resolveBinding().getType();
- checkMethodInHierarchy(type, fGetterName, fieldType, new ITypeBinding[0], status, usingLocalGetter);
- checkMethodInHierarchy(type, fSetterName, fFieldDeclaration.getAST().resolveWellKnownType("void"), //$NON-NLS-1$
- new ITypeBinding[] {fieldType}, status, usingLocalSetter);
- }
- }
-
- public static void checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters, RefactoringStatus result, boolean reUseMethod) {
- IFunctionBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
- if (method != null) {
- boolean returnTypeClash= false;
- ITypeBinding methodReturnType= method.getReturnType();
- if (returnType != null && methodReturnType != null) {
- String returnTypeKey= returnType.getKey();
- String methodReturnTypeKey= methodReturnType.getKey();
- if (returnTypeKey == null && methodReturnTypeKey == null) {
- returnTypeClash= returnType != methodReturnType;
- } else if (returnTypeKey != null && methodReturnTypeKey != null) {
- returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
- }
- }
- ITypeBinding dc= method.getDeclaringClass();
- if (returnTypeClash) {
- result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
- new Object[] {methodName, dc.getName()}),
- JavaStatusContext.create(method));
- } else {
- if (!reUseMethod)
- result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
- new Object[] {methodName, dc.getName()}),
- JavaStatusContext.create(method));
- }
- } else {
- if (reUseMethod){
- result.addError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError,
- new Object[] {methodName}),
- JavaStatusContext.create(method));
- }
- }
- }
-
- private void computeUsedNames() {
- fUsedReadNames= new ArrayList(0);
- fUsedModifyNames= new ArrayList(0);
- IVariableBinding binding= fFieldDeclaration.resolveBinding();
- ITypeBinding type= binding.getType();
- IFunctionBinding[] methods= binding.getDeclaringClass().getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- IFunctionBinding method= methods[i];
- ITypeBinding[] parameters= methods[i].getParameterTypes();
- if (parameters == null || parameters.length == 0) {
- fUsedReadNames.add(method);
- } else if (parameters.length == 1 && parameters[0] == type) {
- fUsedModifyNames.add(method);
- }
- }
- }
-
- private List addGetterSetterChanges(JavaScriptUnit root, ASTRewrite rewriter, String lineDelimiter, boolean usingLocalSetter, boolean usingLocalGetter) throws CoreException {
- List result= new ArrayList(2);
- AST ast= root.getAST();
- FieldDeclaration decl= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, ASTNode.FIELD_DECLARATION);
- int position= 0;
- int numberOfMethods= 0;
- List members= ASTNodes.getBodyDeclarations(decl.getParent());
- for (Iterator iter= members.iterator(); iter.hasNext();) {
- BodyDeclaration element= (BodyDeclaration)iter.next();
- if (element.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- if (fInsertionIndex == -1) {
- break;
- } else if (fInsertionIndex == numberOfMethods) {
- position++;
- break;
- }
- numberOfMethods++;
- }
- position++;
- }
- TextEditGroup description;
- ListRewrite rewrite= fRewriter.getListRewrite(decl.getParent(), getBodyDeclarationsProperty(decl.getParent()));
- if (!JdtFlags.isFinal(fField) && !usingLocalSetter) {
- description= new TextEditGroup(RefactoringCoreMessages.SelfEncapsulateField_add_setter);
- result.add(description);
- rewrite.insertAt(createSetterMethod(ast, rewriter, lineDelimiter), position++, description);
- }
- if (!usingLocalGetter){
- description= new TextEditGroup(RefactoringCoreMessages.SelfEncapsulateField_add_getter);
- result.add(description);
- rewrite.insertAt(createGetterMethod(ast, rewriter, lineDelimiter), position, description);
- }
- if (!JdtFlags.isPrivate(fField))
- result.add(makeDeclarationPrivate(rewriter, decl));
- return result;
- }
-
- private TextEditGroup makeDeclarationPrivate(ASTRewrite rewriter, FieldDeclaration decl) {
- AST ast= rewriter.getAST();
- TextEditGroup description= new TextEditGroup(RefactoringCoreMessages.SelfEncapsulateField_change_visibility);
- if (decl.fragments().size() > 1) {
- //TODO: doesn't work for cases like this: int field1, field2= field1, field3= field2; // keeping refs to field
- rewriter.remove(fFieldDeclaration, description);
- ChildListPropertyDescriptor descriptor= getBodyDeclarationsProperty(decl.getParent());
- VariableDeclarationFragment newField= (VariableDeclarationFragment) rewriter.createCopyTarget(fFieldDeclaration);
- FieldDeclaration fieldDecl= ast.newFieldDeclaration(newField);
- fieldDecl.setType((Type)rewriter.createCopyTarget(decl.getType()));
- fieldDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE));
- rewriter.getListRewrite(decl.getParent(), descriptor).insertAfter(fieldDecl, decl, description);
- } else {
- ModifierRewrite.create(rewriter, decl).setVisibility(Modifier.PRIVATE, description);
- }
- return description;
- }
-
- private ChildListPropertyDescriptor getBodyDeclarationsProperty(ASTNode declaration) {
- if (declaration instanceof AnonymousClassDeclaration)
- return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
- else if (declaration instanceof AbstractTypeDeclaration)
- return ((AbstractTypeDeclaration) declaration).getBodyDeclarationsProperty();
- Assert.isTrue(false);
- return null;
- }
-
- private FunctionDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
- FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
- Type type= field.getType();
- FunctionDeclaration result= ast.newFunctionDeclaration();
- result.setName(ast.newSimpleName(fSetterName));
- result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
- if (fSetterMustReturnValue) {
- result.setReturnType2((Type)rewriter.createCopyTarget(type));
- }
- SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
- result.parameters().add(param);
- param.setName(ast.newSimpleName(fArgName));
- param.setType((Type)rewriter.createCopyTarget(type));
-
- Block block= ast.newBlock();
- result.setBody(block);
- Assignment ass= ast.newAssignment();
- ass.setLeftHandSide(createFieldAccess(ast));
- ass.setRightHandSide(ast.newSimpleName(fArgName));
- if (fSetterMustReturnValue) {
- ReturnStatement rs= ast.newReturnStatement();
- rs.setExpression(ass);
- block.statements().add(rs);
- } else {
- block.statements().add(ast.newExpressionStatement(ass));
- }
-
- if (fGenerateJavadoc) {
- String string= CodeGeneration.getSetterComment(
- fField.getJavaScriptUnit() , getTypeName(field.getParent()), fSetterName,
- fField.getElementName(), ASTNodes.asString(type), fArgName,
- NamingConventions.removePrefixAndSuffixForFieldName(fField.getJavaScriptProject(), fField.getElementName(), fField.getFlags()),
- lineDelimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc)fRewriter.createStringPlaceholder(string, ASTNode.JSDOC);
- result.setJavadoc(javadoc);
- }
- }
- return result;
- }
-
- private FunctionDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
- FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
- Type type= field.getType();
- FunctionDeclaration result= ast.newFunctionDeclaration();
- result.setName(ast.newSimpleName(fGetterName));
- result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
- result.setReturnType2((Type)rewriter.createCopyTarget(type));
-
- Block block= ast.newBlock();
- result.setBody(block);
- ReturnStatement rs= ast.newReturnStatement();
- rs.setExpression(ast.newSimpleName(fField.getElementName()));
- block.statements().add(rs);
- if (fGenerateJavadoc) {
- String string= CodeGeneration.getGetterComment(
- fField.getJavaScriptUnit() , getTypeName(field.getParent()), fGetterName,
- fField.getElementName(), ASTNodes.asString(type),
- NamingConventions.removePrefixAndSuffixForFieldName(fField.getJavaScriptProject(), fField.getElementName(), fField.getFlags()),
- lineDelimiter);
- if (string != null) {
- JSdoc javadoc= (JSdoc)fRewriter.createStringPlaceholder(string, ASTNode.JSDOC);
- result.setJavadoc(javadoc);
- }
- }
- return result;
- }
-
- private int createModifiers() throws JavaScriptModelException {
- int result= 0;
- if (Flags.isPublic(fVisibility))
- result |= Modifier.PUBLIC;
- else if (Flags.isPrivate(fVisibility))
- result |= Modifier.PRIVATE;
- if (JdtFlags.isStatic(fField))
- result |= Modifier.STATIC;
- return result;
- }
-
- private Expression createFieldAccess(AST ast) throws JavaScriptModelException {
- String fieldName= fField.getElementName();
- if (fArgName.equals(fieldName)) {
- if (JdtFlags.isStatic(fField)) {
- return ast.newQualifiedName(
- ast.newSimpleName(fField.getDeclaringType().getElementName()),
- ast.newSimpleName(fieldName));
- } else {
- FieldAccess result= ast.newFieldAccess();
- result.setExpression(ast.newThisExpression());
- result.setName(ast.newSimpleName(fieldName));
- return result;
- }
- } else {
- return ast.newSimpleName(fieldName);
- }
- }
-
- private void checkArgName() {
- String fieldName= fField.getElementName();
- boolean isStatic= true;
- try {
- isStatic= JdtFlags.isStatic(fField);
- } catch(JavaScriptModelException e) {
- }
- IJavaScriptProject project= fField.getJavaScriptProject();
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String compliance= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
-
- if ((isStatic && fArgName.equals(fieldName) && fieldName.equals(fField.getDeclaringType().getElementName()))
- || JavaScriptConventions.validateIdentifier(fArgName, sourceLevel, compliance).getSeverity() == IStatus.ERROR)
- fArgName= "_" + fArgName; //$NON-NLS-1$
- }
-
- private String getTypeName(ASTNode type) {
- if (type instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration)type).getName().getIdentifier();
- } else if (type instanceof AnonymousClassDeclaration) {
- ClassInstanceCreation node= (ClassInstanceCreation)ASTNodes.getParent(type, ClassInstanceCreation.class);
- return ASTNodes.asString(node.getType());
- }
- Assert.isTrue(false, "Should not happen"); //$NON-NLS-1$
- return null;
- }
-
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.FIELD)
- return createInputFatalStatus(element, IJavaScriptRefactorings.ENCAPSULATE_FIELD);
- else {
- fField= (IField) element;
- try {
- initialize(fField);
- } catch (JavaScriptModelException exception) {
- return createInputFatalStatus(element, IJavaScriptRefactorings.ENCAPSULATE_FIELD);
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- String name= extended.getAttribute(ATTRIBUTE_GETTER);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fGetterName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_GETTER));
- name= extended.getAttribute(ATTRIBUTE_SETTER);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fSetterName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_SETTER));
- final String encapsulate= extended.getAttribute(ATTRIBUTE_DECLARING);
- if (encapsulate != null) {
- fEncapsulateDeclaringClass= Boolean.valueOf(encapsulate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DECLARING));
- final String matches= extended.getAttribute(ATTRIBUTE_COMMENTS);
- if (matches != null) {
- fGenerateJavadoc= Boolean.valueOf(matches).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_COMMENTS));
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= flag;
- }
- final String insertion= extended.getAttribute(ATTRIBUTE_INSERTION);
- if (insertion != null && !"".equals(insertion)) {//$NON-NLS-1$
- int index= 0;
- try {
- index= Integer.parseInt(insertion);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INSERTION));
- }
- fInsertionIndex= index;
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- public boolean isUsingLocalGetter() {
- IType declaringType= fField.getDeclaringType();
- return checkName(fGetterName, fUsedReadNames, declaringType);
- }
-
- public boolean isUsingLocalSetter() {
- IType declaringType= fField.getDeclaringType();
- return checkName(fSetterName, fUsedModifyNames, declaringType);
- }
-
- private static boolean checkName(String name, List usedNames, IType type) {
- for (Iterator iter= usedNames.iterator(); iter.hasNext(); ) {
- IFunctionBinding method= (IFunctionBinding)iter.next();
- String selector= method.getName();
- if (selector.equals(name)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isIgnorableProblem(IProblem problem) {
- if (problem.getID() == IProblem.NotVisibleField)
- return true;
- return false;
- }
-
- public boolean isConsiderVisibility() {
- return fConsiderVisibility;
- }
-
- public void setConsiderVisibility(boolean considerVisibility) {
- fConsiderVisibility= considerVisibility;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ASTNodeSearchUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ASTNodeSearchUtil.java
deleted file mode 100644
index 4897cf71..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ASTNodeSearchUtil.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-
-public class ASTNodeSearchUtil {
-
- private ASTNodeSearchUtil() {
- //no instance
- }
-
- public static ASTNode[] getAstNodes(SearchMatch[] searchResults, JavaScriptUnit cuNode) {
- List result= new ArrayList(searchResults.length);
- for (int i= 0; i < searchResults.length; i++) {
- ASTNode node= getAstNode(searchResults[i], cuNode);
- if (node != null)
- result.add(node);
- }
- return (ASTNode[]) result.toArray(new ASTNode[result.size()]);
- }
-
- public static ASTNode getAstNode(SearchMatch searchResult, JavaScriptUnit cuNode) {
- ASTNode selectedNode= getAstNode(cuNode, searchResult.getOffset(), searchResult.getLength());
- if (selectedNode == null)
- return null;
- if (selectedNode.getParent() == null)
- return null;
- return selectedNode;
- }
-
- public static ASTNode getAstNode(JavaScriptUnit cuNode, int start, int length){
- SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(start, length), true);
- cuNode.accept(analyzer);
- //XXX workaround for jdt core feature 23527
- ASTNode node= analyzer.getFirstSelectedNode();
- if (node == null && analyzer.getLastCoveringNode() instanceof SuperConstructorInvocation)
- node= analyzer.getLastCoveringNode().getParent();
- else if (node == null && analyzer.getLastCoveringNode() instanceof ConstructorInvocation)
- node= analyzer.getLastCoveringNode().getParent();
-
- if (node == null)
- return null;
-
- ASTNode parentNode= node.getParent();
-
- if (parentNode instanceof FunctionDeclaration){
- FunctionDeclaration md= (FunctionDeclaration)parentNode;
- if (!(node instanceof SimpleName)
- && md.isConstructor()
- && md.getBody() != null
- && md.getBody().statements().size() > 0
- &&(md.getBody().statements().get(0) instanceof ConstructorInvocation || md.getBody().statements().get(0) instanceof SuperConstructorInvocation)
- &&((ASTNode)md.getBody().statements().get(0)).getLength() == length + 1)
- return (ASTNode)md.getBody().statements().get(0);
- }
-
- if (parentNode instanceof SuperConstructorInvocation){
- if (parentNode.getLength() == length + 1)
- return parentNode;
- }
- if (parentNode instanceof ConstructorInvocation){
- if (parentNode.getLength() == length + 1)
- return parentNode;
- }
- return node;
- }
-
- public static FunctionDeclaration getMethodDeclarationNode(IFunction iMethod, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (FunctionDeclaration)ASTNodes.getParent(getNameNode(iMethod, cuNode), FunctionDeclaration.class);
- }
-
- public static BodyDeclaration getMethodOrAnnotationTypeMemberDeclarationNode(IFunction iMethod, JavaScriptUnit cuNode) throws JavaScriptModelException {
-// if (JdtFlags.isAnnotation(iMethod.getDeclaringType()))
-// return getAnnotationTypeMemberDeclarationNode(iMethod, cuNode);
-// else
- return getMethodDeclarationNode(iMethod, cuNode);
- }
-
- public static VariableDeclarationFragment getFieldDeclarationFragmentNode(IField iField, JavaScriptUnit cuNode) throws JavaScriptModelException {
- ASTNode node= getNameNode(iField, cuNode);
- if (node instanceof VariableDeclarationFragment)
- return (VariableDeclarationFragment)node;
- return (VariableDeclarationFragment)ASTNodes.getParent(node, VariableDeclarationFragment.class);
- }
-
- public static FieldDeclaration getFieldDeclarationNode(IField iField, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (FieldDeclaration) ASTNodes.getParent(getNameNode(iField, cuNode), FieldDeclaration.class);
- }
-
-
- public static BodyDeclaration getFieldOrEnumConstantDeclaration(IField iField, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return getFieldDeclarationNode(iField, cuNode);
- }
-
-
- public static BodyDeclaration getBodyDeclarationNode(IMember iMember, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (BodyDeclaration) ASTNodes.getParent(getNameNode(iMember, cuNode), BodyDeclaration.class);
- }
-
- public static AbstractTypeDeclaration getAbstractTypeDeclarationNode(IType iType, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (AbstractTypeDeclaration) ASTNodes.getParent(getNameNode(iType, cuNode), AbstractTypeDeclaration.class);
- }
-
- public static TypeDeclaration getTypeDeclarationNode(IType iType, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (TypeDeclaration) ASTNodes.getParent(getNameNode(iType, cuNode), TypeDeclaration.class);
- }
-
- public static ClassInstanceCreation getClassInstanceCreationNode(IType iType, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (ClassInstanceCreation) ASTNodes.getParent(getNameNode(iType, cuNode), ClassInstanceCreation.class);
- }
-
- public static List getBodyDeclarationList(IType iType, JavaScriptUnit cuNode) throws JavaScriptModelException {
- if (iType.isAnonymous())
- return getClassInstanceCreationNode(iType, cuNode).getAnonymousClassDeclaration().bodyDeclarations();
- else
- return getAbstractTypeDeclarationNode(iType, cuNode).bodyDeclarations();
- }
-
- //returns an array because of the import container, which does not represent 1 node but many
- //for fields, it returns the whole declaration node
- public static ASTNode[] getDeclarationNodes(IJavaScriptElement element, JavaScriptUnit cuNode) throws JavaScriptModelException {
- switch(element.getElementType()){
- case IJavaScriptElement.FIELD:
- return new ASTNode[]{getFieldOrEnumConstantDeclaration((IField) element, cuNode)};
- case IJavaScriptElement.IMPORT_CONTAINER:
- return getImportNodes((IImportContainer)element, cuNode);
- case IJavaScriptElement.IMPORT_DECLARATION:
- return new ASTNode[]{getImportDeclarationNode((IImportDeclaration)element, cuNode)};
- case IJavaScriptElement.INITIALIZER:
- return new ASTNode[]{getInitializerNode((IInitializer)element, cuNode)};
- case IJavaScriptElement.METHOD:
- return new ASTNode[]{getMethodOrAnnotationTypeMemberDeclarationNode((IFunction) element, cuNode)};
- case IJavaScriptElement.TYPE:
- return new ASTNode[]{getAbstractTypeDeclarationNode((IType) element, cuNode)};
- default:
- Assert.isTrue(false, String.valueOf(element.getElementType()));
- return null;
- }
- }
-
- private static ASTNode getNameNode(IMember iMember, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return NodeFinder.perform(cuNode, iMember.getNameRange());
- }
-
- public static ImportDeclaration getImportDeclarationNode(IImportDeclaration reference, JavaScriptUnit cuNode) throws JavaScriptModelException {
- return (ImportDeclaration) findNode(reference.getSourceRange(), cuNode);
- }
-
- public static ASTNode[] getImportNodes(IImportContainer reference, JavaScriptUnit cuNode) throws JavaScriptModelException {
- IJavaScriptElement[] imps= reference.getChildren();
- ASTNode[] result= new ASTNode[imps.length];
- for (int i= 0; i < imps.length; i++) {
- result[i]= getImportDeclarationNode((IImportDeclaration)imps[i], cuNode);
- }
- return result;
- }
-
- public static Initializer getInitializerNode(IInitializer initializer, JavaScriptUnit cuNode) throws JavaScriptModelException {
- ASTNode node= findNode(initializer.getSourceRange(), cuNode);
- if (node instanceof Initializer)
- return (Initializer) node;
- if (node instanceof Block && node.getParent() instanceof Initializer)
- return (Initializer) node.getParent();
- return null;
- }
-
- private static ASTNode findNode(ISourceRange range, JavaScriptUnit cuNode){
- NodeFinder nodeFinder= new NodeFinder(range.getOffset(), range.getLength());
- cuNode.accept(nodeFinder);
- ASTNode coveredNode= nodeFinder.getCoveredNode();
- if (coveredNode != null)
- return coveredNode;
- else
- return nodeFinder.getCoveringNode();
- }
-
- public static ASTNode[] findNodes(SearchMatch[] searchResults, JavaScriptUnit cuNode) {
- List result= new ArrayList(searchResults.length);
- for (int i= 0; i < searchResults.length; i++) {
- ASTNode node= findNode(searchResults[i], cuNode);
- if (node != null)
- result.add(node);
- }
- return (ASTNode[]) result.toArray(new ASTNode[result.size()]);
- }
-
- public static ASTNode findNode(SearchMatch searchResult, JavaScriptUnit cuNode) {
- ASTNode selectedNode= NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
- if (selectedNode == null)
- return null;
- if (selectedNode.getParent() == null)
- return null;
- return selectedNode;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/BodyUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/BodyUpdater.java
deleted file mode 100644
index ac555781..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/BodyUpdater.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-
-
-public abstract class BodyUpdater {
-
- /**
- * Updates the body of a method declaration. This method is called by the
- * {@link ChangeSignatureRefactoring} and allows implementors to refactor the body
- * of the given method declaration.
- *
- * @param methodDeclaration
- * @param cuRewrite
- * @param result
- * @throws CoreException
- */
- public abstract void updateBody(FunctionDeclaration methodDeclaration, CompilationUnitRewrite cuRewrite, RefactoringStatus result) throws CoreException;
-
- /**
- * Returns whether {@link ChangeSignatureRefactoring} should check if
- * deleted parameters are currently used in the method body.
- *
- * @return <code>true</code> by default, subclasses can override
- */
- public boolean needsParameterUsedCheck() {
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
deleted file mode 100644
index c63089d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
+++ /dev/null
@@ -1,2623 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.Corext;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ExceptionInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ReturnTypeInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypeContextChecker;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypeContextChecker.IProblemVerifier;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.RefactoringStatusCodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RippleMethodFinder2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.TempOccurrenceAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavadocUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TightSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ChangeSignatureRefactoring extends ScriptableRefactoring implements IDelegateUpdating {
-
- private static final String ATTRIBUTE_RETURN= "return"; //$NON-NLS-1$
- private static final String ATTRIBUTE_VISIBILITY= "visibility"; //$NON-NLS-1$
- private static final String ATTRIBUTE_PARAMETER= "parameter"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DEFAULT= "default"; //$NON-NLS-1$
- private static final String ATTRIBUTE_KIND= "kind"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DELEGATE= "delegate"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DEPRECATE= "deprecate"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FUNCTION_HEAD="function"; //$NON-NLS-1$
-
- private static final boolean PREFIX_FUNCTION_HEAD = true;
-
-
- private List fParameterInfos;
-
- private CompilationUnitRewrite fBaseCuRewrite;
- private List fExceptionInfos;
- protected TextChangeManager fChangeManager;
- protected List/*<Change>*/ fOtherChanges;
- private IFunction fMethod;
- private IFunction fTopMethod;
- private IFunction[] fRippleMethods;
- private SearchResultGroup[] fOccurrences;
- private ReturnTypeInfo fReturnTypeInfo;
- private String fMethodName;
- private int fVisibility;
-// private static final String CONST_CLASS_DECL = "class A{";//$NON-NLS-1$
- private static final String CONST_ASSIGN = " i="; //$NON-NLS-1$
- private static final String CONST_CLOSE = ";"; //$NON-NLS-1$
-
- private StubTypeContext fContextCuStartEnd;
- private int fOldVarargIndex; // initialized in checkVarargs()
-
- private BodyUpdater fBodyUpdater;
- private IDefaultValueAdvisor fDefaultValueAdvisor;
-
- private ITypeHierarchy fCachedTypeHierarchy= null;
- private boolean fDelegateUpdating;
- private boolean fDelegateDeprecation;
-
- /**
- * Creates a new change signature refactoring.
- * @param method the method, or <code>null</code> if invoked by scripting framework
- * @throws JavaScriptModelException
- */
- public ChangeSignatureRefactoring(IFunction method) throws JavaScriptModelException {
- fMethod= method;
- fOldVarargIndex= -1;
- fDelegateUpdating= false;
- fDelegateDeprecation= true;
- if (fMethod != null) {
- fParameterInfos= createParameterInfoList(method);
- // fExceptionInfos is created in checkInitialConditions
- fReturnTypeInfo= new ReturnTypeInfo(Signature.toString(Signature.getReturnType(fMethod.getSignature())));
- fMethodName= fMethod.getElementName();
- fVisibility= JdtFlags.getVisibilityCode(fMethod);
- }
- }
-
- private static List createParameterInfoList(IFunction method) {
- try {
- String[] typeNames= method.getParameterTypes();
- String[] oldNames= method.getParameterNames();
- List result= new ArrayList(typeNames.length);
- for (int i= 0; i < oldNames.length; i++){
- ParameterInfo parameterInfo;
- if (i == oldNames.length - 1 && Flags.isVarargs(method.getFlags())) {
- String varargSignature= typeNames[i];
- int arrayCount= Signature.getArrayCount(varargSignature);
- String baseSignature= Signature.getElementType(varargSignature);
- if (arrayCount > 1)
- baseSignature= Signature.createArraySignature(baseSignature, arrayCount - 1);
- parameterInfo= new ParameterInfo(Signature.toString(baseSignature) + ParameterInfo.ELLIPSIS, oldNames[i], i);
- } else {
- parameterInfo= new ParameterInfo(Signature.toString(typeNames[i]), oldNames[i], i);
- }
- result.add(parameterInfo);
- }
- return result;
- } catch(JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return new ArrayList(0);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.ChangeSignatureRefactoring_modify_Parameters;
- }
-
- public IFunction getMethod() {
- return fMethod;
- }
-
- public String getMethodName() {
- return fMethodName;
- }
-
- public String getReturnTypeString() {
- return fReturnTypeInfo.getNewTypeName();
- }
-
- public void setNewMethodName(String newMethodName){
- Assert.isNotNull(newMethodName);
- fMethodName= newMethodName;
- }
-
- public void setNewReturnTypeName(String newReturnTypeName){
- Assert.isNotNull(newReturnTypeName);
- fReturnTypeInfo.setNewTypeName(newReturnTypeName);
- }
-
- public boolean canChangeNameAndReturnType(){
- try {
- return ! fMethod.isConstructor();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return false;
- }
- }
-
- /**
- * @return visibility
- * @see org.eclipse.wst.jsdt.core.dom.Modifier
- */
- public int getVisibility(){
- return fVisibility;
- }
-
- /**
- * @param visibility new visibility
- * @see org.eclipse.wst.jsdt.core.dom.Modifier
- */
- public void setVisibility(int visibility){
- Assert.isTrue( visibility == Modifier.PUBLIC ||
- visibility == Modifier.PROTECTED ||
- visibility == Modifier.NONE ||
- visibility == Modifier.PRIVATE);
- fVisibility= visibility;
- }
-
- /*
- * @see JdtFlags
- */
- public int[] getAvailableVisibilities() throws JavaScriptModelException{
-// if (fTopMethod.getDeclaringType().isInterface())
-// return new int[]{Modifier.PUBLIC};
-// else if (fTopMethod.getDeclaringType().isEnum() && fTopMethod.isConstructor())
-// return new int[]{ Modifier.NONE,
-// Modifier.PRIVATE};
-// else
- return new int[]{ Modifier.PUBLIC,
- Modifier.PROTECTED,
- Modifier.NONE,
- Modifier.PRIVATE};
- }
-
- /**
- *
- * @return List of <code>ParameterInfo</code> objects.
- */
- public List getParameterInfos(){
- return fParameterInfos;
- }
-
- /**
- * @return List of <code>ExceptionInfo</code> objects.
- */
- public List getExceptionInfos(){
- return fExceptionInfos;
- }
-
- public void setBodyUpdater(BodyUpdater bodyUpdater) {
- fBodyUpdater= bodyUpdater;
- }
-
- public CompilationUnitRewrite getBaseCuRewrite() {
- return fBaseCuRewrite;
- }
-
- //------------------- IDelegateUpdating ----------------------
-
- public boolean canEnableDelegateUpdating() {
- return true;
- }
-
- public boolean getDelegateUpdating() {
- return fDelegateUpdating;
- }
-
- public void setDelegateUpdating(boolean updating) {
- fDelegateUpdating= updating;
- }
-
- public void setDeprecateDelegates(boolean deprecate) {
- fDelegateDeprecation= deprecate;
- }
-
- public boolean getDeprecateDelegates() {
- return fDelegateDeprecation;
- }
-
- //------------------- /IDelegateUpdating ---------------------
-
- public RefactoringStatus checkSignature() {
- return checkSignature(false, doGetProblemVerifier());
- }
-
- private RefactoringStatus checkSignature(boolean resolveBindings, IProblemVerifier problemVerifier) {
- RefactoringStatus result= new RefactoringStatus();
- checkMethodName(result);
- if (result.hasFatalError())
- return result;
-
- checkParameterNamesAndValues(result);
- if (result.hasFatalError())
- return result;
-
- checkForDuplicateParameterNames(result);
- if (result.hasFatalError())
- return result;
-
- try {
- RefactoringStatus[] typeStati;
- if (resolveBindings)
- typeStati= TypeContextChecker.checkAndResolveMethodTypes(fMethod, getStubTypeContext(), getNotDeletedInfos(), fReturnTypeInfo, problemVerifier);
- else
- typeStati= TypeContextChecker.checkMethodTypesSyntax(fMethod, getNotDeletedInfos(), fReturnTypeInfo);
- for (int i= 0; i < typeStati.length; i++)
- result.merge(typeStati[i]);
-
- result.merge(checkVarargs());
- } catch (CoreException e) {
- //cannot do anything here
- throw new RuntimeException(e);
- }
-
- //checkExceptions() unnecessary (IType always ok)
- return result;
- }
-
- public boolean isSignatureSameAsInitial() throws JavaScriptModelException {
- if (! isVisibilitySameAsInitial())
- return false;
- if (! isMethodNameSameAsInitial())
- return false;
- if (! isReturnTypeSameAsInitial())
- return false;
- if (! areExceptionsSameAsInitial())
- return false;
-
- if (fMethod.getNumberOfParameters() == 0 && fParameterInfos.isEmpty())
- return true;
-
- if (areNamesSameAsInitial() && isOrderSameAsInitial() && areParameterTypesSameAsInitial())
- return true;
-
- return false;
- }
-
- /**
- * @return true if the new method cannot coexist with the old method since
- * the signatures are too much alike
- * @throws JavaScriptModelException
- */
- public boolean isSignatureClashWithInitial() throws JavaScriptModelException {
-
- if (!isMethodNameSameAsInitial())
- return false; // name has changed.
-
- if (fMethod.getNumberOfParameters() == 0 && fParameterInfos.isEmpty())
- return true; // name is equal and both parameter lists are empty
-
- // name is equal and there are some parameters.
- // check if there are more or less parameters than before
-
- int no= getNotDeletedInfos().size();
-
- if (fMethod.getNumberOfParameters() != no)
- return false;
-
- // name is equal and parameter count is equal.
- // check whether types remained the same
-
- if (isOrderSameAsInitial())
- return areParameterTypesSameAsInitial();
- else
- return false; // could be more specific here
- }
-
- private boolean areParameterTypesSameAsInitial() {
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (! info.isAdded() && ! info.isDeleted() && info.isTypeNameChanged())
- return false;
- }
- return true;
- }
-
- private boolean isReturnTypeSameAsInitial() throws JavaScriptModelException {
- return ! fReturnTypeInfo.isTypeNameChanged();
- }
-
- private boolean isMethodNameSameAsInitial() {
- return fMethodName.equals(fMethod.getElementName());
- }
-
- private boolean areExceptionsSameAsInitial() {
- for (Iterator iter= fExceptionInfos.iterator(); iter.hasNext();) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (! info.isOld())
- return false;
- }
- return true;
- }
-
- private void checkParameterNamesAndValues(RefactoringStatus result) {
- int i= 1;
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext(); i++) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isDeleted())
- continue;
- checkParameterName(result, info, i);
- if (result.hasFatalError())
- return;
- if (info.isAdded()) {
- checkParameterDefaultValue(result, info);
- if (result.hasFatalError())
- return;
- }
- }
- }
-
- private void checkParameterName(RefactoringStatus result, ParameterInfo info, int position) {
- if (info.getNewName().trim().length() == 0) {
- result.addFatalError(Messages.format(
- RefactoringCoreMessages.ChangeSignatureRefactoring_param_name_not_empty, Integer.toString(position)));
- } else {
- result.merge(Checks.checkTempName(info.getNewName()));
- }
- }
-
- private void checkMethodName(RefactoringStatus result) {
- if (isMethodNameSameAsInitial() || ! canChangeNameAndReturnType())
- return;
- if ("".equals(fMethodName.trim())) { //$NON-NLS-1$
- String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_method_name_not_empty;
- result.addFatalError(msg);
- return;
- }
- if (fMethodName.equals(fMethod.getDeclaringType().getElementName())) {
- String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_constructor_name;
- result.addWarning(msg);
- }
- result.merge(Checks.checkMethodName(fMethodName));
- }
-
- private void checkParameterDefaultValue(RefactoringStatus result, ParameterInfo info) {
- if (fDefaultValueAdvisor != null)
- return;
- if (info.isNewVarargs()) {
- if (! isValidVarargsExpression(info.getDefaultValue())){
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_invalid_expression, new String[]{info.getDefaultValue()});
- result.addFatalError(msg);
- }
- return;
- }
-
- if (info.getDefaultValue().trim().equals("")){ //$NON-NLS-1$
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_default_value, new String[]{info.getNewName()});
- result.addFatalError(msg);
- return;
- }
- if (! isValidExpression(info.getDefaultValue())){
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_invalid_expression, new String[]{info.getDefaultValue()});
- result.addFatalError(msg);
- }
- }
-
- private RefactoringStatus checkVarargs() throws JavaScriptModelException {
- RefactoringStatus result= checkOriginalVarargs();
- if (result != null)
- return result;
-
- if (fRippleMethods != null) {
- for (int iRipple= 0; iRipple < fRippleMethods.length; iRipple++) {
- IFunction rippleMethod= fRippleMethods[iRipple];
- if (! JdtFlags.isVarargs(rippleMethod))
- continue;
-
- // Vararg method can override method that takes an array as last argument
- fOldVarargIndex= rippleMethod.getNumberOfParameters() - 1;
- List notDeletedInfos= getNotDeletedInfos();
- for (int i= 0; i < notDeletedInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo) notDeletedInfos.get(i);
- if (fOldVarargIndex != -1 && info.getOldIndex() == fOldVarargIndex && ! info.isNewVarargs()) {
- String rippleMethodType= JavaModelUtil.getFullyQualifiedName(rippleMethod.getDeclaringType());
- String message= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_ripple_cannot_convert_vararg, new Object[] {info.getNewName(), rippleMethodType});
- return RefactoringStatus.createFatalErrorStatus(message, JavaStatusContext.create(rippleMethod));
- }
- }
- }
- }
-
- return null;
- }
-
- private RefactoringStatus checkOriginalVarargs() throws JavaScriptModelException {
- if (JdtFlags.isVarargs(fMethod))
- fOldVarargIndex= fMethod.getNumberOfParameters() - 1;
- List notDeletedInfos= getNotDeletedInfos();
- for (int i= 0; i < notDeletedInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo) notDeletedInfos.get(i);
- if (info.isOldVarargs() && ! info.isNewVarargs())
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_cannot_convert_vararg, info.getNewName()));
- if (i != notDeletedInfos.size() - 1) {
- // not the last parameter
- if (info.isNewVarargs())
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_vararg_must_be_last, info.getNewName()));
- }
- }
- return null;
- }
-
- private RefactoringStatus checkTypeVariables() throws JavaScriptModelException {
- if (fRippleMethods.length == 1)
- return null;
-
- RefactoringStatus result= new RefactoringStatus();
- if (fReturnTypeInfo.isTypeNameChanged() && fReturnTypeInfo.getNewTypeBinding() != null) {
- HashSet typeVariablesCollector= new HashSet();
- collectTypeVariables(fReturnTypeInfo.getNewTypeBinding(), typeVariablesCollector);
- if (typeVariablesCollector.size() != 0) {
- ITypeBinding first= (ITypeBinding) typeVariablesCollector.iterator().next();
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_return_type_contains_type_variable, new String[] {fReturnTypeInfo.getNewTypeName(), first.getName()});
- result.addError(msg);
- }
- }
-
- for (Iterator iter= getNotDeletedInfos().iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isTypeNameChanged() && info.getNewTypeBinding() != null) {
- HashSet typeVariablesCollector= new HashSet();
- collectTypeVariables(info.getNewTypeBinding(), typeVariablesCollector);
- if (typeVariablesCollector.size() != 0) {
- ITypeBinding first= (ITypeBinding) typeVariablesCollector.iterator().next();
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_parameter_type_contains_type_variable, new String[] {info.getNewTypeName(), info.getNewName(), first.getName()});
- result.addError(msg);
- }
- }
- }
- return result;
- }
-
- private void collectTypeVariables(ITypeBinding typeBinding, Set typeVariablesCollector) {
- if (typeBinding.isArray()) {
- collectTypeVariables(typeBinding.getElementType(), typeVariablesCollector);
-
- }
- }
-
- public static boolean isValidExpression(String string){
- String trimmed= string.trim();
- StringBuffer cuBuff= new StringBuffer();
- cuBuff.append(CONST_ASSIGN);
- int offset= cuBuff.length();
- cuBuff.append(trimmed)
- .append(CONST_CLOSE);
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(cuBuff.toString().toCharArray());
- JavaScriptUnit cu= (JavaScriptUnit) p.createAST(null);
- Selection selection= Selection.createFromStartLength(offset, trimmed.length());
- SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
- cu.accept(analyzer);
- ASTNode selected= analyzer.getFirstSelectedNode();
- return (selected instanceof Expression) &&
- trimmed.equals(cuBuff.substring(cu.getExtendedStartPosition(selected), cu.getExtendedStartPosition(selected) + cu.getExtendedLength(selected)));
- /*
- if ("".equals(trimmed)) //speed up for a common case //$NON-NLS-1$
- return false;
- StringBuffer cuBuff= new StringBuffer();
- cuBuff.append(CONST_CLASS_DECL)
- .append("Object") //$NON-NLS-1$
- .append(CONST_ASSIGN);
- int offset= cuBuff.length();
- cuBuff.append(trimmed)
- .append(CONST_CLOSE);
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(cuBuff.toString().toCharArray());
- JavaScriptUnit cu= (JavaScriptUnit) p.createAST(null);
- Selection selection= Selection.createFromStartLength(offset, trimmed.length());
- SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
- cu.accept(analyzer);
- ASTNode selected= analyzer.getFirstSelectedNode();
- return (selected instanceof Expression) &&
- trimmed.equals(cuBuff.substring(cu.getExtendedStartPosition(selected), cu.getExtendedStartPosition(selected) + cu.getExtendedLength(selected)));
- */
- }
-
- public static boolean isValidVarargsExpression(String string) {
- String trimmed= string.trim();
- if ("".equals(trimmed)) //speed up for a common case //$NON-NLS-1$
- return true;
- StringBuffer cuBuff= new StringBuffer();
- cuBuff.append("class A{ {m("); //$NON-NLS-1$
- int offset= cuBuff.length();
- cuBuff.append(trimmed)
- .append(");}}"); //$NON-NLS-1$
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(cuBuff.toString().toCharArray());
- JavaScriptUnit cu= (JavaScriptUnit) p.createAST(null);
- Selection selection= Selection.createFromStartLength(offset, trimmed.length());
- SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
- cu.accept(analyzer);
- ASTNode[] selectedNodes= analyzer.getSelectedNodes();
- if (selectedNodes.length == 0)
- return false;
- for (int i= 0; i < selectedNodes.length; i++) {
- if (! (selectedNodes[i] instanceof Expression))
- return false;
- }
- return true;
- }
-
- public StubTypeContext getStubTypeContext() {
- try {
- if (fContextCuStartEnd == null)
- fContextCuStartEnd= TypeContextChecker.createStubTypeContext(getCu(), fBaseCuRewrite.getRoot(), fMethod.getSourceRange().getOffset());
- } catch (CoreException e) {
- //cannot do anything here
- throw new RuntimeException(e);
- }
- return fContextCuStartEnd;
- }
-
- private ITypeHierarchy getCachedTypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException {
- if (fCachedTypeHierarchy == null)
- fCachedTypeHierarchy= fMethod.getDeclaringType().newTypeHierarchy(new SubProgressMonitor(monitor, 1));
- return fCachedTypeHierarchy;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask("", 5); //$NON-NLS-1$
- RefactoringStatus result= Checks.checkIfCuBroken(fMethod);
- if (result.hasFatalError())
- return result;
- if (fMethod == null || !fMethod.exists()) {
- String message= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_method_deleted, getCu().getElementName());
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-// if (fMethod.getDeclaringType().isInterface()) {
-// fTopMethod= MethodChecks.overridesAnotherMethod(fMethod, fMethod.getDeclaringType().newSupertypeHierarchy(new SubProgressMonitor(monitor, 1)));
-// monitor.worked(1);
-// } else
- if (MethodChecks.isVirtual(fMethod)) {
- ITypeHierarchy hierarchy= getCachedTypeHierarchy(new SubProgressMonitor(monitor, 1));
- fTopMethod= null;
- if (fTopMethod == null)
- fTopMethod= MethodChecks.overridesAnotherMethod(fMethod, hierarchy);
- }
- if (fTopMethod == null)
- fTopMethod= fMethod;
- if (! fTopMethod.equals(fMethod)) {
- RefactoringStatusContext context= JavaStatusContext.create(fTopMethod);
- String message= Messages.format(RefactoringCoreMessages.MethodChecks_overrides,
- new String[]{JavaElementUtil.createMethodSignature(fTopMethod), JavaModelUtil.getFullyQualifiedName(fTopMethod.getDeclaringType())});
- return RefactoringStatus.createStatus(RefactoringStatus.FATAL, message, context, Corext.getPluginId(), RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD, fTopMethod);
-
- }
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- if (fBaseCuRewrite == null || !fBaseCuRewrite.getCu().equals(getCu())) {
- fBaseCuRewrite= new CompilationUnitRewrite(getCu());
- fBaseCuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
- }
- monitor.worked(1);
- result.merge(createExceptionInfoList());
- monitor.worked(1);
- return result;
- } finally {
- monitor.done();
- }
- }
-
- private RefactoringStatus createExceptionInfoList() {
- if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
- fExceptionInfos= new ArrayList(0);
- try {
- ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
- if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof FunctionDeclaration))
- return null;
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) nameNode.getParent();
- List exceptions= methodDeclaration.thrownExceptions();
- List result= new ArrayList(exceptions.size());
- for (int i= 0; i < exceptions.size(); i++) {
- Name name= (Name) exceptions.get(i);
- ITypeBinding typeBinding= name.resolveTypeBinding();
- if (typeBinding == null)
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
- IType type= (IType) typeBinding.getJavaElement();
- result.add(ExceptionInfo.createInfoForOldException(type, typeBinding));
- }
- fExceptionInfos= result;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_checking_preconditions, 8);
- RefactoringStatus result= new RefactoringStatus();
- clearManagers();
- fBaseCuRewrite.clearASTAndImportRewrites();
- fBaseCuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
-
- if (isSignatureSameAsInitial())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_unchanged);
- result.merge(checkSignature(true, doGetProblemVerifier()));
- if (result.hasFatalError())
- return result;
-
- if (fDelegateUpdating && isSignatureClashWithInitial())
- result.merge(RefactoringStatus.createErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different ));
-
- fRippleMethods= RippleMethodFinder2.getRelatedMethods(fMethod, new SubProgressMonitor(pm, 1), null);
- result.merge(checkVarargs());
- if (result.hasFatalError())
- return result;
-
- fOccurrences= findOccurrences(new SubProgressMonitor(pm, 1), result);
-
- result.merge(checkVisibilityChanges());
- result.merge(checkTypeVariables());
-
- //TODO:
- // We need a common way of dealing with possible compilation errors for all occurrences,
- // including visibility problems, shadowing and missing throws declarations.
-
- if (! isOrderSameAsInitial())
- result.merge(checkReorderings(new SubProgressMonitor(pm, 1)));
- else
- pm.worked(1);
-
- //TODO (bug 58616): check whether changed signature already exists somewhere in the ripple,
- // - error if exists
- // - warn if exists with different parameter types (may cause overloading)
-
- if (! areNamesSameAsInitial())
- result.merge(checkRenamings(new SubProgressMonitor(pm, 1)));
- else
- pm.worked(1);
- if (result.hasFatalError())
- return result;
-
-// resolveTypesWithoutBindings(new SubProgressMonitor(pm, 1)); // already done in checkSignature(true)
-
- createChangeManager(new SubProgressMonitor(pm, 1), result);
- fCachedTypeHierarchy= null;
-
- if (mustAnalyzeAstOfDeclaringCu())
- result.merge(checkCompilationofDeclaringCu()); //TODO: should also check in ripple methods (move into createChangeManager)
- if (result.hasFatalError())
- return result;
-
- result.merge(validateModifiesFiles());
- return result;
- } finally {
- pm.done();
- }
- }
-
- protected IProblemVerifier doGetProblemVerifier() {
- return null;
- }
-
- private void clearManagers() {
- fChangeManager= null;
- fOtherChanges= new ArrayList();
- }
-
- private RefactoringStatus checkVisibilityChanges() throws JavaScriptModelException {
- if (isVisibilitySameAsInitial())
- return null;
- if (fRippleMethods.length == 1)
- return null;
- Assert.isTrue(JdtFlags.getVisibilityCode(fMethod) != Modifier.PRIVATE);
- if (fVisibility == Modifier.PRIVATE)
- return RefactoringStatus.createWarningStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_non_virtual);
- return null;
- }
-
- public String getOldMethodSignature() throws JavaScriptModelException{
- StringBuffer buff= new StringBuffer();
-
- int flags= getMethod().getFlags();
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- buff.append(getVisibilityString(flags));
- if (Flags.isStatic(flags))
- buff.append("static "); //$NON-NLS-1$
- }
-
- if(PREFIX_FUNCTION_HEAD) {
- buff.append(ATTRIBUTE_FUNCTION_HEAD + " "); //$NON-NLS-1$
- }
-
- if (! getMethod().isConstructor() && JavaScriptCore.IS_ECMASCRIPT4)
- buff.append(fReturnTypeInfo.getOldTypeName())
- .append(' ');
-
- buff.append(JavaScriptElementLabels.getElementLabel(fMethod.getParent(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED));
- buff.append('.');
- buff.append(fMethod.getElementName())
- .append(Signature.C_PARAM_START)
- .append(getOldMethodParameters())
- .append(Signature.C_PARAM_END);
-
- buff.append(getOldMethodThrows());
-
- return buff.toString();
- }
-
- public String getNewMethodSignature() throws JavaScriptModelException{
- StringBuffer buff= new StringBuffer();
- if(PREFIX_FUNCTION_HEAD) {
- buff.append(ATTRIBUTE_FUNCTION_HEAD + " "); //$NON-NLS-1$
- }
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- buff.append(getVisibilityString(fVisibility));
- if (Flags.isStatic(getMethod().getFlags()))
- buff.append("static "); //$NON-NLS-1$
- }
- if (! getMethod().isConstructor() && JavaScriptCore.IS_ECMASCRIPT4)
- buff.append(getReturnTypeString()).append(' ');
-
- buff.append(getMethodName())
- .append(Signature.C_PARAM_START)
- .append(getMethodParameters())
- .append(Signature.C_PARAM_END);
- if(JavaScriptCore.IS_ECMASCRIPT4)
- buff.append(getMethodThrows());
-
- return buff.toString();
- }
-
- private String getVisibilityString(int visibility) {
- String visibilityString= JdtFlags.getVisibilityString(visibility);
- if ("".equals(visibilityString)) //$NON-NLS-1$
- return visibilityString;
- return visibilityString + ' ';
- }
-
- private String getMethodThrows() {
- final String throwsString= " throws "; //$NON-NLS-1$
- StringBuffer buff= new StringBuffer(throwsString);
- for (Iterator iter= fExceptionInfos.iterator(); iter.hasNext(); ) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (! info.isDeleted()) {
- buff.append(info.getType().getElementName());
- buff.append(", "); //$NON-NLS-1$
- }
- }
- if (buff.length() == throwsString.length())
- return ""; //$NON-NLS-1$
- buff.delete(buff.length() - 2, buff.length());
- return buff.toString();
- }
-
- private String getOldMethodThrows() {
- final String throwsString= " throws "; //$NON-NLS-1$
- StringBuffer buff= new StringBuffer(throwsString);
- for (Iterator iter= fExceptionInfos.iterator(); iter.hasNext(); ) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (! info.isAdded()) {
- buff.append(info.getType().getElementName());
- buff.append(", "); //$NON-NLS-1$
- }
- }
- if (buff.length() == throwsString.length())
- return ""; //$NON-NLS-1$
- buff.delete(buff.length() - 2, buff.length());
- return buff.toString();
- }
-
- private void checkForDuplicateParameterNames(RefactoringStatus result){
- Set found= new HashSet();
- Set doubled= new HashSet();
- for (Iterator iter = getNotDeletedInfos().iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo)iter.next();
- String newName= info.getNewName();
- if (found.contains(newName) && !doubled.contains(newName)){
- result.addFatalError(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_duplicate_name, newName));
- doubled.add(newName);
- } else {
- found.add(newName);
- }
- }
- }
-
- private IJavaScriptUnit getCu() {
- return fMethod.getJavaScriptUnit();
- }
-
- private boolean mustAnalyzeAstOfDeclaringCu() throws JavaScriptModelException{
- if (JdtFlags.isAbstract(getMethod()))
- return false;
- else
- return true;
- }
-
- private RefactoringStatus checkCompilationofDeclaringCu() throws CoreException {
- IJavaScriptUnit cu= getCu();
- TextChange change= fChangeManager.get(cu);
- String newCuSource= change.getPreviewContent(new NullProgressMonitor());
- JavaScriptUnit newCUNode= new RefactoringASTParser(AST.JLS3).parse(newCuSource, cu, true, false, null);
- IProblem[] problems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fBaseCuRewrite.getRoot());
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < problems.length; i++) {
- IProblem problem= problems[i];
- if (shouldReport(problem, newCUNode))
- result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, new SourceRange(problem))));
- }
- return result;
- }
-
- private boolean shouldReport(IProblem problem, JavaScriptUnit cu) {
- if (! problem.isError())
- return false;
- if (problem.getID() == IProblem.UndefinedType) //reported when trying to import
- return false;
- ASTNode node= ASTNodeSearchUtil.getAstNode(cu, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart());
- IProblemVerifier verifier= doGetProblemVerifier();
- if (verifier != null)
- return verifier.isError(problem, node);
- return true;
- }
-
- private String getOldMethodParameters() {
- StringBuffer buff= new StringBuffer();
- int i= 0;
- for (Iterator iter= getNotAddedInfos().iterator(); iter.hasNext(); i++) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (i != 0 )
- buff.append(", "); //$NON-NLS-1$
- buff.append(createDeclarationString(info));
- }
- return buff.toString();
- }
-
- private String getMethodParameters() {
- StringBuffer buff= new StringBuffer();
- int i= 0;
- for (Iterator iter= getNotDeletedInfos().iterator(); iter.hasNext(); i++) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (i != 0 )
- buff.append(", "); //$NON-NLS-1$
- buff.append(createDeclarationString(info));
- }
- return buff.toString();
- }
-
- private List getAddedInfos(){
- List result= new ArrayList(1);
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isAdded())
- result.add(info);
- }
- return result;
- }
-
- private List getDeletedInfos(){
- List result= new ArrayList(1);
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isDeleted())
- result.add(info);
- }
- return result;
- }
-
- private List getNotAddedInfos(){
- List all= new ArrayList(fParameterInfos);
- all.removeAll(getAddedInfos());
- return all;
- }
-
- private List getNotDeletedInfos(){
- List all= new ArrayList(fParameterInfos);
- all.removeAll(getDeletedInfos());
- return all;
- }
-
- private boolean areNamesSameAsInitial() {
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isRenamed())
- return false;
- }
- return true;
- }
-
- private boolean isOrderSameAsInitial(){
- int i= 0;
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext(); i++) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.getOldIndex() != i) // includes info.isAdded()
- return false;
- if (info.isDeleted())
- return false;
- }
- return true;
- }
-
- private RefactoringStatus checkReorderings(IProgressMonitor pm) throws JavaScriptModelException {
- try{
- pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_checking_preconditions, 1);
- return checkNativeMethods();
- } finally{
- pm.done();
- }
- }
-
- private RefactoringStatus checkRenamings(IProgressMonitor pm) throws JavaScriptModelException {
- try{
- pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_checking_preconditions, 1);
- return checkParameterNamesInRippleMethods();
- } finally{
- pm.done();
- }
- }
-
- private RefactoringStatus checkParameterNamesInRippleMethods() throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- Set newParameterNames= getNewParameterNamesList();
- for (int i= 0; i < fRippleMethods.length; i++) {
- String[] paramNames= fRippleMethods[i].getParameterNames();
- for (int j= 0; j < paramNames.length; j++) {
- if (newParameterNames.contains(paramNames[j])){
- String[] args= new String[]{JavaElementUtil.createMethodSignature(fRippleMethods[i]), paramNames[j]};
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_already_has, args);
- RefactoringStatusContext context= JavaStatusContext.create(fRippleMethods[i].getJavaScriptUnit(), fRippleMethods[i].getNameRange());
- result.addError(msg, context);
- }
- }
- }
- return result;
- }
-
- private Set getNewParameterNamesList() {
- Set oldNames= getOriginalParameterNames();
- Set currentNames= getNamesOfNotDeletedParameters();
- currentNames.removeAll(oldNames);
- return currentNames;
- }
-
- private Set getNamesOfNotDeletedParameters() {
- Set result= new HashSet();
- for (Iterator iter= getNotDeletedInfos().iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- result.add(info.getNewName());
- }
- return result;
- }
-
- private Set getOriginalParameterNames() {
- Set result= new HashSet();
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (! info.isAdded())
- result.add(info.getOldName());
- }
- return result;
- }
-
- private RefactoringStatus checkNativeMethods() throws JavaScriptModelException{
- RefactoringStatus result= new RefactoringStatus();
- return result;
- }
-
- private IFile[] getAllFilesToModify(){
- return ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
- }
-
- private RefactoringStatus validateModifiesFiles(){
- return Checks.validateModifiesFiles(getAllFilesToModify(), getValidationContext());
- }
-
- public Change createChange(IProgressMonitor pm) {
- pm.beginTask("", 1); //$NON-NLS-1$
- try {
- final TextChange[] changes= fChangeManager.getAllChanges();
- final List list= new ArrayList(changes.length);
- list.addAll(fOtherChanges);
- list.addAll(Arrays.asList(changes));
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fMethod.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
- try {
- if (!Flags.isPrivate(fMethod.getFlags()))
- flags|= RefactoringDescriptor.MULTI_CHANGE;
- final IType declaring= fMethod.getDeclaringType();
- if (declaring!=null && (declaring.isAnonymous() || declaring.isLocal()))
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- JDTRefactoringDescriptor descriptor= null;
- try {
- final String description= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_descriptor_description_short, fMethod.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_descriptor_description, new String[] { getOldMethodSignature(), getNewMethodSignature()});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- if (!fMethod.getElementName().equals(fMethodName))
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_new_name_pattern, fMethodName));
- if (!isVisibilitySameAsInitial()) {
- String visibility= JdtFlags.getVisibilityString(fVisibility);
- if ("".equals(visibility)) //$NON-NLS-1$
- visibility= RefactoringCoreMessages.ChangeSignatureRefactoring_default_visibility;
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_new_visibility_pattern, visibility));
- }
- if (fReturnTypeInfo.isTypeNameChanged())
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_new_return_type_pattern, fReturnTypeInfo.getNewTypeName()));
- List deleted= new ArrayList();
- List added= new ArrayList();
- List changed= new ArrayList();
- for (final Iterator iterator= fParameterInfos.iterator(); iterator.hasNext();) {
- final ParameterInfo info= (ParameterInfo) iterator.next();
- if (info.isDeleted())
- deleted.add(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_deleted_parameter_pattern, new String[] { info.getOldTypeName(), info.getOldName()}));
- else if (info.isAdded())
- added.add(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_added_parameter_pattern, new String[] { info.getNewTypeName(), info.getNewName()}));
- else if (info.isRenamed() || info.isTypeNameChanged() || info.isVarargChanged())
- changed.add(Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_changed_parameter_pattern, new String[] { info.getOldTypeName(), info.getOldName()}));
- }
- if (!added.isEmpty())
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ChangeSignatureRefactoring_added_parameters, (String[]) added.toArray(new String[added.size()])));
- if (!deleted.isEmpty())
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ChangeSignatureRefactoring_removed_parameters, (String[]) deleted.toArray(new String[deleted.size()])));
- if (!changed.isEmpty())
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ChangeSignatureRefactoring_changed_parameters, (String[]) changed.toArray(new String[changed.size()])));
- added.clear();
- deleted.clear();
- changed.clear();
- for (final Iterator iterator= fExceptionInfos.iterator(); iterator.hasNext();) {
- final ExceptionInfo info= (ExceptionInfo) iterator.next();
- if (info.isAdded())
- added.add(info.getType().getElementName());
- else if (info.isDeleted())
- deleted.add(info.getType().getElementName());
- }
- if (!added.isEmpty())
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ChangeSignatureRefactoring_added_exceptions, (String[]) added.toArray(new String[added.size()])));
- if (!deleted.isEmpty())
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ChangeSignatureRefactoring_removed_exceptions, (String[]) deleted.toArray(new String[deleted.size()])));
- descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.CHANGE_METHOD_SIGNATURE, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fMethod));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fMethodName);
- arguments.put(ATTRIBUTE_DELEGATE, Boolean.valueOf(fDelegateUpdating).toString());
- arguments.put(ATTRIBUTE_DEPRECATE, Boolean.valueOf(fDelegateDeprecation).toString());
- if (fReturnTypeInfo.isTypeNameChanged())
- arguments.put(ATTRIBUTE_RETURN, fReturnTypeInfo.getNewTypeName());
- try {
- if (!isVisibilitySameAsInitial())
- arguments.put(ATTRIBUTE_VISIBILITY, new Integer(fVisibility).toString());
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- int count= 1;
- for (final Iterator iterator= fParameterInfos.iterator(); iterator.hasNext();) {
- final ParameterInfo info= (ParameterInfo) iterator.next();
- final StringBuffer buffer= new StringBuffer(64);
- buffer.append(info.getOldTypeName());
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(info.getOldName());
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(info.getOldIndex());
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(info.getNewTypeName());
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(info.getNewName());
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(info.isDeleted());
- arguments.put(ATTRIBUTE_PARAMETER + count, buffer.toString());
- final String value= info.getDefaultValue();
- if (value != null && !"".equals(value)) //$NON-NLS-1$
- arguments.put(ATTRIBUTE_DEFAULT + count, value);
- count++;
- }
- count= 1;
- for (final Iterator iterator= fExceptionInfos.iterator(); iterator.hasNext();) {
- final ExceptionInfo info= (ExceptionInfo) iterator.next();
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count, descriptor.elementToHandle(info.getType()));
- arguments.put(ATTRIBUTE_KIND + count, new Integer(info.getKind()).toString());
- count++;
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- return null;
- }
- return new DynamicValidationRefactoringChange(descriptor, doGetRefactoringChangeName(), (Change[]) list.toArray(new Change[list.size()]));
- } finally {
- pm.done();
- clearManagers();
- }
- }
-
- protected String doGetRefactoringChangeName() {
- return RefactoringCoreMessages.ChangeSignatureRefactoring_restructure_parameters;
- }
-
- private TextChangeManager createChangeManager(IProgressMonitor pm, RefactoringStatus result) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_preview, 2);
- fChangeManager= new TextChangeManager();
- boolean isNoArgConstructor= isNoArgConstructor();
- Map namedSubclassMapping= null;
- if (isNoArgConstructor){
- //create only when needed;
- namedSubclassMapping= createNamedSubclassMapping(new SubProgressMonitor(pm, 1));
- }else{
- pm.worked(1);
- }
- for (int i= 0; i < fOccurrences.length; i++) {
- if (pm.isCanceled())
- throw new OperationCanceledException();
- SearchResultGroup group= fOccurrences[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu == null)
- continue;
- CompilationUnitRewrite cuRewrite;
- if (cu.equals(getCu())) {
- cuRewrite= fBaseCuRewrite;
- } else {
- cuRewrite= new CompilationUnitRewrite(cu);
- cuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
- }
- ASTNode[] nodes= ASTNodeSearchUtil.findNodes(group.getSearchResults(), cuRewrite.getRoot());
-
- //IntroduceParameterObjectRefactoring needs to update declarations first:
- List/*<OccurrenceUpdate>*/ deferredUpdates= new ArrayList();
- for (int j= 0; j < nodes.length; j++) {
- OccurrenceUpdate update= createOccurrenceUpdate(nodes[j], cuRewrite, result);
- if (update instanceof DeclarationUpdate) {
- update.updateNode();
- } else {
- deferredUpdates.add(update);
- }
- }
- for (Iterator iter= deferredUpdates.iterator(); iter.hasNext();) {
- ((OccurrenceUpdate) iter.next()).updateNode();
- }
-
- if (isNoArgConstructor && namedSubclassMapping.containsKey(cu)){
- //only non-anonymous subclasses may have noArgConstructors to modify - see bug 43444
- Set subtypes= (Set)namedSubclassMapping.get(cu);
- for (Iterator iter= subtypes.iterator(); iter.hasNext();) {
- IType subtype= (IType) iter.next();
- AbstractTypeDeclaration subtypeNode= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(subtype, cuRewrite.getRoot());
- if (subtypeNode != null)
- modifyImplicitCallsToNoArgConstructor(subtypeNode, cuRewrite);
- }
- }
- TextChange change= cuRewrite.createChange();
- if (change != null)
- fChangeManager.manage(cu, change);
- }
-
- pm.done();
- return fChangeManager;
- }
-
- //Map<IJavaScriptUnit, Set<IType>>
- private Map createNamedSubclassMapping(IProgressMonitor pm) throws JavaScriptModelException{
- IType[] subclasses= getCachedTypeHierarchy(new SubProgressMonitor(pm, 1)).getSubclasses(fMethod.getDeclaringType());
- Map result= new HashMap();
- for (int i= 0; i < subclasses.length; i++) {
- IType subclass= subclasses[i];
- if (subclass.isAnonymous())
- continue;
- IJavaScriptUnit cu= subclass.getJavaScriptUnit();
- if (! result.containsKey(cu))
- result.put(cu, new HashSet());
- ((Set)result.get(cu)).add(subclass);
- }
- return result;
- }
-
- private void modifyImplicitCallsToNoArgConstructor(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) {
- FunctionDeclaration[] constructors= getAllConstructors(subclass);
- if (constructors.length == 0){
- addNewConstructorToSubclass(subclass, cuRewrite);
- } else {
- for (int i= 0; i < constructors.length; i++) {
- if (! containsImplicitCallToSuperConstructor(constructors[i]))
- continue;
- addExplicitSuperConstructorCall(constructors[i], cuRewrite);
- }
- }
- }
-
- private void addExplicitSuperConstructorCall(FunctionDeclaration constructor, CompilationUnitRewrite cuRewrite) {
- SuperConstructorInvocation superCall= constructor.getAST().newSuperConstructorInvocation();
- addArgumentsToNewSuperConstructorCall(superCall, cuRewrite);
- String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_super_call;
- TextEditGroup description= cuRewrite.createGroupDescription(msg);
- cuRewrite.getASTRewrite().getListRewrite(constructor.getBody(), Block.STATEMENTS_PROPERTY).insertFirst(superCall, description);
- }
-
- private void addArgumentsToNewSuperConstructorCall(SuperConstructorInvocation superCall, CompilationUnitRewrite cuRewrite) {
- int i= 0;
- for (Iterator iter= getNotDeletedInfos().iterator(); iter.hasNext(); i++) {
- ParameterInfo info= (ParameterInfo) iter.next();
- Expression newExpression= createNewExpression(info, getParameterInfos(), superCall.arguments(), cuRewrite, (FunctionDeclaration) ASTNodes.getParent(superCall, FunctionDeclaration.class));
- if (newExpression != null)
- superCall.arguments().add(newExpression);
- }
- }
-
- private static boolean containsImplicitCallToSuperConstructor(FunctionDeclaration constructor) {
- Assert.isTrue(constructor.isConstructor());
- Block body= constructor.getBody();
- if (body == null)
- return false;
- if (body.statements().size() == 0)
- return true;
- if (body.statements().get(0) instanceof ConstructorInvocation)
- return false;
- if (body.statements().get(0) instanceof SuperConstructorInvocation)
- return false;
- return true;
- }
-
- private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) {
- AST ast= subclass.getAST();
- FunctionDeclaration newConstructor= ast.newFunctionDeclaration();
- newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier()));
- newConstructor.setConstructor(true);
- newConstructor.setExtraDimensions(0);
- newConstructor.setJavadoc(null);
- newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass)));
- newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
- Block body= ast.newBlock();
- newConstructor.setBody(body);
- SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation();
- addArgumentsToNewSuperConstructorCall(superCall, cuRewrite);
- body.statements().add(superCall);
-
- String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor;
- TextEditGroup description= cuRewrite.createGroupDescription(msg);
- cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description);
-
- // TODO use AbstractTypeDeclaration
- }
-
- private static int getAccessModifier(AbstractTypeDeclaration subclass) {
- int modifiers= subclass.getModifiers();
- if (Modifier.isPublic(modifiers))
- return Modifier.PUBLIC;
- else if (Modifier.isProtected(modifiers))
- return Modifier.PROTECTED;
- else if (Modifier.isPrivate(modifiers))
- return Modifier.PRIVATE;
- else
- return Modifier.NONE;
- }
-
- private FunctionDeclaration[] getAllConstructors(AbstractTypeDeclaration typeDeclaration) {
- BodyDeclaration decl;
- List result= new ArrayList(1);
- for (Iterator it = typeDeclaration.bodyDeclarations().listIterator(); it.hasNext(); ) {
- decl= (BodyDeclaration) it.next();
- if (decl instanceof FunctionDeclaration && ((FunctionDeclaration) decl).isConstructor())
- result.add(decl);
- }
- return (FunctionDeclaration[]) result.toArray(new FunctionDeclaration[result.size()]);
- }
-
- private boolean isNoArgConstructor() throws JavaScriptModelException {
- return fMethod.isConstructor() && fMethod.getNumberOfParameters() == 0;
- }
-
- private Expression createNewExpression(ParameterInfo info, List parameterInfos, List nodes, CompilationUnitRewrite cuRewrite, FunctionDeclaration method) {
- if (info.isNewVarargs() && info.getDefaultValue().trim().length() == 0)
- return null;
- else {
- if (fDefaultValueAdvisor == null)
- return (Expression) cuRewrite.getASTRewrite().createStringPlaceholder(info.getDefaultValue(), ASTNode.FUNCTION_INVOCATION);
- else
- return fDefaultValueAdvisor.createDefaultExpression(nodes, info, parameterInfos, method, false, cuRewrite);
- }
- }
-
- private boolean isVisibilitySameAsInitial() throws JavaScriptModelException {
- return fVisibility == JdtFlags.getVisibilityCode(fMethod);
- }
-
- private IJavaScriptSearchScope createRefactoringScope() throws JavaScriptModelException{
- return RefactoringScopeFactory.create(fMethod);
- }
-
- private SearchResultGroup[] findOccurrences(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException{
- if (fMethod.isConstructor()){
- // workaround for bug 27236:
- return ConstructorReferenceFinder.getConstructorOccurrences(fMethod, pm, status);
- }else{
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(fRippleMethods, IJavaScriptSearchConstants.ALL_OCCURRENCES);
- return RefactoringSearchEngine.search(pattern, createRefactoringScope(), pm, status);
- }
- }
-
- private static String createDeclarationString(ParameterInfo info) {
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- String newTypeName= info.getNewTypeName();
- int index= newTypeName.indexOf('.');
- if (index != -1){
- newTypeName= newTypeName.substring(index+1);
- }
- return newTypeName + " " + info.getNewName(); //$NON-NLS-1$
- }else {
- return info.getNewName();
- }
- }
-
- private OccurrenceUpdate createOccurrenceUpdate(ASTNode node, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
-
- if (isReferenceNode(node))
- return new ReferenceUpdate(node, cuRewrite, result);
-
- else if (node instanceof SimpleName && node.getParent() instanceof FunctionDeclaration)
- return new DeclarationUpdate((FunctionDeclaration) node.getParent(), cuRewrite, result);
-
- else if (node instanceof MemberRef || node instanceof FunctionRef)
- return new DocReferenceUpdate(node, cuRewrite, result);
-
- else if (ASTNodes.getParent(node, ImportDeclaration.class) != null)
- return new StaticImportUpdate((ImportDeclaration) ASTNodes.getParent(node, ImportDeclaration.class), cuRewrite, result);
-
- else
- return new NullOccurrenceUpdate(node, cuRewrite, result);
- }
-
- private static boolean isReferenceNode(ASTNode node){
- switch (node.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION :
- case ASTNode.SUPER_METHOD_INVOCATION :
- case ASTNode.CLASS_INSTANCE_CREATION :
- case ASTNode.CONSTRUCTOR_INVOCATION :
- case ASTNode.SUPER_CONSTRUCTOR_INVOCATION :
- return true;
-
- default :
- return false;
- }
- }
-
- abstract class OccurrenceUpdate {
- protected final CompilationUnitRewrite fCuRewrite;
- protected final TextEditGroup fDescription;
- protected RefactoringStatus fResult;
-
- protected OccurrenceUpdate(CompilationUnitRewrite cuRewrite, TextEditGroup description, RefactoringStatus result) {
- fCuRewrite= cuRewrite;
- fDescription= description;
- fResult= result;
- }
-
- protected final ASTRewrite getASTRewrite() {
- return fCuRewrite.getASTRewrite();
- }
-
- protected final ImportRewrite getImportRewrite() {
- return fCuRewrite.getImportRewrite();
- }
-
- protected final ImportRemover getImportRemover() {
- return fCuRewrite.getImportRemover();
- }
-
- protected final CompilationUnitRewrite getCompilationUnitRewrite() {
- return fCuRewrite;
- }
-
- public abstract void updateNode() throws CoreException;
-
- protected void registerImportRemoveNode(ASTNode node) {
- getImportRemover().registerRemovedNode(node);
- }
-
- protected final void reshuffleElements() {
- if (isOrderSameAsInitial())
- return;
-
- //varargs; method(p1, p2, .., pn), call(a1, a2, .., ax) :
- // if (method_was_vararg) {
- // assert fOldVarargIndex != -1
- // if (vararg_retained) {
- // assert vararg_is_last_non_deleted (pn)
- // assert no_other_varargs
- // => reshuffle [1..n-1] then append remaining nodes [n..x], possibly none
- //
- // } else (vararg_deleted) {
- // assert all_are_non_vararg
- // => reshuffle [1..n-1], drop all remaining nodes [n..x], possibly none
- // }
- //
- // } else if (method_became_vararg) {
- // assert n == x
- // assert fOldVarargIndex == -1
- // => reshuffle [1..n]
- //
- // } else (JLS2_case) {
- // assert n == x
- // assert fOldVarargIndex == -1
- // => reshuffle [1..n]
- // }
-
- ListRewrite listRewrite= getParamgumentsRewrite();
- Map newOldMap= new LinkedHashMap();
- List nodes= listRewrite.getRewrittenList();
- Iterator rewriteIter= nodes.iterator();
- List original= listRewrite.getOriginalList();
- for (Iterator iter= original.iterator(); iter.hasNext();) {
- newOldMap.put(rewriteIter.next(),iter.next());
- }
- List newNodes= new ArrayList();
- // register removed nodes, and collect nodes in new sequence:
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo) fParameterInfos.get(i);
- int oldIndex= info.getOldIndex();
-
- if (info.isDeleted()) {
- if (oldIndex != fOldVarargIndex) {
- registerImportRemoveNode((ASTNode) nodes.get(oldIndex));
- } else {
- //vararg deleted -> remove all remaining nodes:
- for (int n= oldIndex; n < nodes.size(); n++) {
- registerImportRemoveNode((ASTNode) nodes.get(n));
- }
- }
-
- } else if (info.isAdded()) {
- ASTNode newParamgument= createNewParamgument(info, fParameterInfos, nodes);
- if (newParamgument != null)
- newNodes.add(newParamgument);
-
- } else /* parameter stays */ {
- if (oldIndex != fOldVarargIndex) {
- ASTNode oldNode= (ASTNode) nodes.get(oldIndex);
- ASTNode movedNode= moveNode(oldNode, getASTRewrite());
- newNodes.add(movedNode);
- } else {
- //vararg stays and is last parameter -> copy all remaining nodes:
- for (int n= oldIndex; n < nodes.size(); n++) {
- ASTNode oldNode= (ASTNode) nodes.get(n);
- ASTNode movedNode= moveNode(oldNode, getASTRewrite());
- newNodes.add(movedNode);
- }
- }
- }
- }
-
- Iterator nodesIter= nodes.iterator();
- Iterator newIter= newNodes.iterator();
- //replace existing nodes with new ones:
- while (nodesIter.hasNext() && newIter.hasNext()) {
- ASTNode node= (ASTNode) nodesIter.next();
- ASTNode newNode= (ASTNode) newIter.next();
- if (!ASTNodes.isExistingNode(node)) //XXX:should better be addressed in ListRewriteEvent.replaceEntry(ASTNode, ASTNode)
- listRewrite.replace((ASTNode) newOldMap.get(node), newNode, fDescription);
- else
- listRewrite.replace(node, newNode, fDescription);
- }
- //remove remaining existing nodes:
- while (nodesIter.hasNext()) {
- ASTNode node= (ASTNode) nodesIter.next();
- if (!ASTNodes.isExistingNode(node))
- listRewrite.remove((ASTNode) newOldMap.get(node), fDescription);
- else
- listRewrite.remove(node, fDescription);
- }
- //add additional new nodes:
- while (newIter.hasNext()) {
- ASTNode node= (ASTNode) newIter.next();
- listRewrite.insertLast(node, fDescription);
- }
- }
-
- /**
- * @return ListRewrite of parameters or arguments
- */
- protected abstract ListRewrite getParamgumentsRewrite();
-
- protected final void changeParamguments() {
- for (Iterator iter= getParameterInfos().iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (info.isAdded() || info.isDeleted())
- continue;
-
- if (info.isRenamed())
- changeParamgumentName(info);
-
- if (info.isTypeNameChanged())
- changeParamgumentType(info);
- }
- }
-
- protected void changeParamgumentName(ParameterInfo info) {
- // no-op
- }
-
- protected void changeParamgumentType(ParameterInfo info) {
- // no-op
- }
-
- protected final void replaceTypeNode(Type typeNode, String newTypeName, ITypeBinding newTypeBinding){
- Type newTypeNode= createNewTypeNode(newTypeName, newTypeBinding);
- getASTRewrite().replace(typeNode, newTypeNode, fDescription);
- registerImportRemoveNode(typeNode);
- getTightSourceRangeComputer().addTightSourceNode(typeNode);
- }
-
- /**
- * @param info
- * @param parameterInfos TODO
- * @param nodes TODO
- * @return a new method parameter or argument, or <code>null</code> for an empty vararg argument
- */
- protected abstract ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes);
-
- protected abstract SimpleName getMethodNameNode();
-
- protected final void changeMethodName() {
- if (! isMethodNameSameAsInitial()) {
- SimpleName nameNode= getMethodNameNode();
- SimpleName newNameNode= nameNode.getAST().newSimpleName(fMethodName);
- getASTRewrite().replace(nameNode, newNameNode, fDescription);
- registerImportRemoveNode(nameNode);
- getTightSourceRangeComputer().addTightSourceNode(nameNode);
- }
- }
-
- protected final Type createNewTypeNode(String newTypeName, ITypeBinding newTypeBinding) {
- Type newTypeNode;
- if (newTypeBinding == null) {
- if (fDefaultValueAdvisor != null)
- newTypeNode= fDefaultValueAdvisor.createType(newTypeName, getMethodNameNode().getStartPosition(), getCompilationUnitRewrite());
- else
- newTypeNode= (Type) getASTRewrite().createStringPlaceholder(newTypeName, ASTNode.SIMPLE_TYPE);
- //Don't import if not resolved.
- } else {
- newTypeNode= getImportRewrite().addImport(newTypeBinding, fCuRewrite.getAST());
- getImportRemover().registerAddedImports(newTypeNode);
- }
- return newTypeNode;
- }
-
- protected final TightSourceRangeComputer getTightSourceRangeComputer() {
- return (TightSourceRangeComputer) fCuRewrite.getASTRewrite().getExtendedSourceRangeComputer();
- }
- }
-
- class ReferenceUpdate extends OccurrenceUpdate {
- /** isReferenceNode(fNode) */
- private ASTNode fNode;
-
- protected ReferenceUpdate(ASTNode node, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
- super(cuRewrite, cuRewrite.createGroupDescription(RefactoringCoreMessages.ChangeSignatureRefactoring_update_reference), result);
- fNode= node; //holds: Assert.isTrue(isReferenceNode(node));
- }
-
- public void updateNode() {
- reshuffleElements();
- changeMethodName();
- }
-
- /** @return {@inheritDoc} (element type: Expression) */
- protected ListRewrite getParamgumentsRewrite() {
- if (fNode instanceof FunctionInvocation)
- return getASTRewrite().getListRewrite(fNode, FunctionInvocation.ARGUMENTS_PROPERTY);
-
- if (fNode instanceof SuperMethodInvocation)
- return getASTRewrite().getListRewrite(fNode, SuperMethodInvocation.ARGUMENTS_PROPERTY);
-
- if (fNode instanceof ClassInstanceCreation)
- return getASTRewrite().getListRewrite(fNode, ClassInstanceCreation.ARGUMENTS_PROPERTY);
-
- if (fNode instanceof ConstructorInvocation)
- return getASTRewrite().getListRewrite(fNode, ConstructorInvocation.ARGUMENTS_PROPERTY);
-
- if (fNode instanceof SuperConstructorInvocation)
- return getASTRewrite().getListRewrite(fNode, SuperConstructorInvocation.ARGUMENTS_PROPERTY);
-
-
- return null;
- }
-
- protected ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) {
- CompilationUnitRewrite cuRewrite= getCompilationUnitRewrite();
- FunctionDeclaration declaration= (FunctionDeclaration) ASTNodes.getParent(fNode, FunctionDeclaration.class);
- if (isRecursiveReference()) {
- return createNewExpressionRecursive(info, parameterInfos, nodes, cuRewrite, declaration);
- } else
- return createNewExpression(info, parameterInfos, nodes, cuRewrite, declaration);
- }
-
- private Expression createNewExpressionRecursive(ParameterInfo info, List parameterInfos, List nodes, CompilationUnitRewrite cuRewrite, FunctionDeclaration methodDeclaration) {
- if (fDefaultValueAdvisor != null && info.isAdded()) {
- return fDefaultValueAdvisor.createDefaultExpression(nodes, info, parameterInfos, methodDeclaration, true, cuRewrite);
- }
- return (Expression) getASTRewrite().createStringPlaceholder(info.getNewName(), ASTNode.FUNCTION_INVOCATION);
- }
-
- protected SimpleName getMethodNameNode() {
- if (fNode instanceof FunctionInvocation)
- return ((FunctionInvocation)fNode).getName();
-
- if (fNode instanceof SuperMethodInvocation)
- return ((SuperMethodInvocation)fNode).getName();
-
- return null;
- }
-
- private boolean isRecursiveReference() {
- FunctionDeclaration enclosingMethodDeclaration= (FunctionDeclaration) ASTNodes.getParent(fNode, FunctionDeclaration.class);
- if (enclosingMethodDeclaration == null)
- return false;
-
- IFunctionBinding enclosingMethodBinding= enclosingMethodDeclaration.resolveBinding();
- if (enclosingMethodBinding == null)
- return false;
-
- if (fNode instanceof FunctionInvocation)
- return enclosingMethodBinding == ((FunctionInvocation)fNode).resolveMethodBinding();
-
- if (fNode instanceof SuperMethodInvocation) {
- IFunctionBinding methodBinding= ((SuperMethodInvocation)fNode).resolveMethodBinding();
- return isSameMethod(methodBinding, enclosingMethodBinding);
- }
-
- if (fNode instanceof ClassInstanceCreation)
- return enclosingMethodBinding == ((ClassInstanceCreation)fNode).resolveConstructorBinding();
-
- if (fNode instanceof ConstructorInvocation)
- return enclosingMethodBinding == ((ConstructorInvocation)fNode).resolveConstructorBinding();
-
- if (fNode instanceof SuperConstructorInvocation) {
- return false; //Constructors don't override -> enclosing has not been changed -> no recursion
- }
-
- Assert.isTrue(false);
- return false;
- }
-
- /**
- * @param m1 method 1
- * @param m2 method 2
- * @return true iff
- * <ul><li>the methods are both constructors with same argument types, or</li>
- * <li>the methods have the same name and the same argument types</li></ul>
- */
- private boolean isSameMethod(IFunctionBinding m1, IFunctionBinding m2) {
- if (m1.isConstructor()) {
- if (! m2.isConstructor())
- return false;
- } else {
- if (! m1.getName().equals(m2.getName()))
- return false;
- }
-
- ITypeBinding[] m1Parameters= m1.getParameterTypes();
- ITypeBinding[] m2Parameters= m2.getParameterTypes();
- if (m1Parameters.length != m2Parameters.length)
- return false;
- for (int i= 0; i < m1Parameters.length; i++) {
- if (m1Parameters[i].getErasure() != m2Parameters[i].getErasure())
- return false;
- }
- return true;
- }
-
- }
-
- class DeclarationUpdate extends OccurrenceUpdate {
- private FunctionDeclaration fMethDecl;
-
- protected DeclarationUpdate(FunctionDeclaration decl, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
- super(cuRewrite, cuRewrite.createGroupDescription(RefactoringCoreMessages.ChangeSignatureRefactoring_change_signature), result);
- fMethDecl= decl;
- }
-
- // Prevent import removing if delegate is created.
- protected void registerImportRemoveNode(ASTNode node) {
- if (!fDelegateUpdating)
- super.registerImportRemoveNode(node);
- }
-
- public void updateNode() throws CoreException {
- changeParamguments();
-
- if (canChangeNameAndReturnType()) {
- changeMethodName();
- changeReturnType();
- }
-
- if (needsVisibilityUpdate())
- changeVisibility();
- reshuffleElements();
- changeExceptions();
-
- changeJavadocTags();
-
- if (fBodyUpdater == null || fBodyUpdater.needsParameterUsedCheck())
- checkIfDeletedParametersUsed();
-
- if (fBodyUpdater != null)
- fBodyUpdater.updateBody(fMethDecl, fCuRewrite, fResult);
-
- if (fDelegateUpdating)
- addDelegate();
- }
-
- private void addDelegate() throws JavaScriptModelException {
-
- DelegateMethodCreator creator= new DelegateMethodCreator();
- creator.setDeclaration(fMethDecl);
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setSourceRewrite(fCuRewrite);
- creator.prepareDelegate();
-
- /*
- * The delegate now contains a call and a javadoc reference to the
- * old method (i.e., to itself).
- *
- * Use ReferenceUpdate() / DocReferenceUpdate() to update these
- * references like any other reference.
- */
- final ASTNode delegateInvocation= creator.getDelegateInvocation();
- if (delegateInvocation != null)
- // may be null if the delegate is an interface method or
- // abstract -> no body
- new ReferenceUpdate(delegateInvocation, creator.getDelegateRewrite(), fResult).updateNode();
- new DocReferenceUpdate(creator.getJavadocReference(), creator.getDelegateRewrite(), fResult).updateNode();
-
- creator.createEdit();
- }
-
- /** @return {@inheritDoc} (element type: SingleVariableDeclaration) */
- protected ListRewrite getParamgumentsRewrite() {
- return getASTRewrite().getListRewrite(fMethDecl, FunctionDeclaration.PARAMETERS_PROPERTY);
- }
-
- protected void changeParamgumentName(ParameterInfo info) {
- SingleVariableDeclaration param= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex());
- if (! info.getOldName().equals(param.getName().getIdentifier()))
- return; //don't change if original parameter name != name in rippleMethod
-
- String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_update_parameter_references;
- TextEditGroup description= fCuRewrite.createGroupDescription(msg);
- TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(param, false);
- analyzer.perform();
- SimpleName[] paramOccurrences= analyzer.getReferenceAndDeclarationNodes(); // @param tags are updated in changeJavaDocTags()
- for (int j= 0; j < paramOccurrences.length; j++) {
- SimpleName occurence= paramOccurrences[j];
- getASTRewrite().set(occurence, SimpleName.IDENTIFIER_PROPERTY, info.getNewName(), description);
- }
- }
-
- protected void changeParamgumentType(ParameterInfo info) {
- SingleVariableDeclaration oldParam= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex());
- getASTRewrite().set(oldParam, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.valueOf(info.isNewVarargs()), fDescription);
- replaceTypeNode(oldParam.getType(), ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding());
- removeExtraDimensions(oldParam);
- }
-
- private void removeExtraDimensions(SingleVariableDeclaration oldParam) {
- if (oldParam.getExtraDimensions() != 0) {
- getASTRewrite().set(oldParam, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), fDescription);
- }
- }
-
- private void changeReturnType() throws JavaScriptModelException {
- if (isReturnTypeSameAsInitial())
- return;
- replaceTypeNode(fMethDecl.getReturnType2(), fReturnTypeInfo.getNewTypeName(), fReturnTypeInfo.getNewTypeBinding());
- removeExtraDimensions(fMethDecl);
- //Remove expression from return statement when changed to void? No, would lose information!
- //Could add return statement with default value and add todo comment, but compile error is better.
- }
-
- private void removeExtraDimensions(FunctionDeclaration methDecl) {
- if (methDecl.getExtraDimensions() != 0)
- getASTRewrite().set(methDecl, FunctionDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), fDescription);
- }
-
- private boolean needsVisibilityUpdate() throws JavaScriptModelException {
- if (isVisibilitySameAsInitial())
- return false;
- if (isIncreasingVisibility())
- return JdtFlags.isHigherVisibility(fVisibility, JdtFlags.getVisibilityCode(fMethDecl));
- else
- return JdtFlags.isHigherVisibility(JdtFlags.getVisibilityCode(fMethDecl), fVisibility);
- }
-
- private boolean isIncreasingVisibility() throws JavaScriptModelException{
- return JdtFlags.isHigherVisibility(fVisibility, JdtFlags.getVisibilityCode(fMethod));
- }
-
- private void changeVisibility() {
- ModifierRewrite.create(getASTRewrite(), fMethDecl).setVisibility(fVisibility, fDescription);
- }
-
- private void changeExceptions() {
- for (Iterator iter= fExceptionInfos.iterator(); iter.hasNext();) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (info.isOld())
- continue;
- if (info.isDeleted())
- removeExceptionFromNodeList(info, fMethDecl.thrownExceptions());
- else
- addExceptionToNodeList(info, getASTRewrite().getListRewrite(fMethDecl, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY));
- }
- }
-
- private void removeExceptionFromNodeList(ExceptionInfo toRemove, List exceptionsNodeList) {
- ITypeBinding typeToRemove= toRemove.getTypeBinding();
- for (Iterator iter= exceptionsNodeList.iterator(); iter.hasNext(); ) {
- Name currentName= (Name) iter.next();
- ITypeBinding currentType= currentName.resolveTypeBinding();
- /* Maybe remove all subclasses of typeToRemove too.
- * Problem:
- * - B extends A;
- * - A.m() throws IOException, Exception;
- * - B.m() throws IOException, AWTException;
- * Removing Exception should remove AWTException,
- * but NOT remove IOException (or a subclass of JavaScriptModelException). */
- // if (Bindings.isSuperType(typeToRemove, currentType))
- if (currentType == null)
- continue; // newly added or unresolvable type
- if (Bindings.equals(currentType, typeToRemove) || toRemove.getType().getElementName().equals(currentType.getName())) {
- getASTRewrite().remove(currentName, fDescription);
- registerImportRemoveNode(currentName);
- }
- }
- }
-
- private void addExceptionToNodeList(ExceptionInfo exceptionInfo, ListRewrite exceptionListRewrite) {
- String fullyQualified= JavaModelUtil.getFullyQualifiedName(exceptionInfo.getType());
- for (Iterator iter= exceptionListRewrite.getOriginalList().iterator(); iter.hasNext(); ) {
- Name exName= (Name) iter.next();
- //XXX: existing superclasses of the added exception are redundant and could be removed
- ITypeBinding typeBinding= exName.resolveTypeBinding();
- if (typeBinding == null)
- continue; // newly added or unresolvable type
- if (typeBinding.getQualifiedName().equals(fullyQualified))
- return; // don't add it again
- }
- String importedType= getImportRewrite().addImport(JavaModelUtil.getFullyQualifiedName(exceptionInfo.getType()));
- getImportRemover().registerAddedImport(importedType);
- ASTNode exNode= getASTRewrite().createStringPlaceholder(importedType, ASTNode.SIMPLE_NAME);
- exceptionListRewrite.insertLast(exNode, fDescription);
- }
-
- private void changeJavadocTags() throws JavaScriptModelException {
- //update tags in javadoc: @param, @return, @exception, @throws, ...
- JSdoc javadoc= fMethDecl.getJavadoc();
- if (javadoc == null)
- return;
-
- ITypeBinding typeBinding= Bindings.getBindingOfParentType(fMethDecl);
- if (typeBinding == null)
- return;
- IFunctionBinding methodBinding= fMethDecl.resolveBinding();
- if (methodBinding == null)
- return;
-
- boolean isTopOfRipple= (Bindings.findOverriddenMethod(methodBinding, false) == null);
- //add tags: only iff top of ripple; change and remove: always.
- //TODO: should have preference for adding tags in (overriding) methods (with template: todo, inheritDoc, ...)
-
- List tags= javadoc.tags(); // List of TagElement
- ListRewrite tagsRewrite= getASTRewrite().getListRewrite(javadoc, JSdoc.TAGS_PROPERTY);
-
- if (! isReturnTypeSameAsInitial()) {
- if (PrimitiveType.VOID.toString().equals(fReturnTypeInfo.getNewTypeName())) {
- for (int i = 0; i < tags.size(); i++) {
- TagElement tag= (TagElement) tags.get(i);
- if (TagElement.TAG_RETURN.equals(tag.getTagName())) {
- getASTRewrite().remove(tag, fDescription);
- registerImportRemoveNode(tag);
- }
- }
- } else if (isTopOfRipple && Signature.SIG_VOID.equals(fMethod.getReturnType())){
- TagElement returnNode= createReturnTag();
- TagElement previousTag= findTagElementToInsertAfter(tags, TagElement.TAG_RETURN);
- insertTag(returnNode, previousTag, tagsRewrite);
- tags= tagsRewrite.getRewrittenList();
- }
- }
-
- if (! (areNamesSameAsInitial() && isOrderSameAsInitial())) {
- ArrayList paramTags= new ArrayList(); // <TagElement>, only not deleted tags with simpleName
- // delete & rename:
- for (Iterator iter = tags.iterator(); iter.hasNext(); ) {
- TagElement tag = (TagElement) iter.next();
- String tagName= tag.getTagName();
- List fragments= tag.fragments();
- if (! (TagElement.TAG_PARAM.equals(tagName) && fragments.size() > 0 && fragments.get(0) instanceof SimpleName))
- continue;
- SimpleName simpleName= (SimpleName) fragments.get(0);
- String identifier= simpleName.getIdentifier();
- boolean removed= false;
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo) fParameterInfos.get(i);
- if (identifier.equals(info.getOldName())) {
- if (info.isDeleted()) {
- getASTRewrite().remove(tag, fDescription);
- registerImportRemoveNode(tag);
- removed= true;
- } else if (info.isRenamed()) {
- SimpleName newName= simpleName.getAST().newSimpleName(info.getNewName());
- getASTRewrite().replace(simpleName, newName, fDescription);
- registerImportRemoveNode(tag);
- }
- break;
- }
- }
- if (! removed)
- paramTags.add(tag);
- }
- tags= tagsRewrite.getRewrittenList();
-
- if (! isOrderSameAsInitial()) {
- // reshuffle (sort in declaration sequence) & add (only add to top of ripple):
- TagElement previousTag= findTagElementToInsertAfter(tags, TagElement.TAG_PARAM);
- boolean first= true; // workaround for bug 92111: preserve first tag if possible
- // reshuffle:
- for (Iterator infoIter= fParameterInfos.iterator(); infoIter.hasNext();) {
- ParameterInfo info= (ParameterInfo) infoIter.next();
- String oldName= info.getOldName();
- String newName= info.getNewName();
- if (info.isAdded()) {
- first= false;
- if (! isTopOfRipple)
- continue;
- TagElement paramNode= JavadocUtil.createParamTag(newName, fCuRewrite.getRoot().getAST(), fCuRewrite.getCu().getJavaScriptProject());
- insertTag(paramNode, previousTag, tagsRewrite);
- previousTag= paramNode;
- } else {
- for (Iterator tagIter= paramTags.iterator(); tagIter.hasNext();) {
- TagElement tag= (TagElement) tagIter.next();
- SimpleName tagName= (SimpleName) tag.fragments().get(0);
- if (oldName.equals(tagName.getIdentifier())) {
- tagIter.remove();
- if (first) {
- previousTag= tag;
- } else {
- TagElement movedTag= (TagElement) getASTRewrite().createMoveTarget(tag);
- getASTRewrite().remove(tag, fDescription);
- insertTag(movedTag, previousTag, tagsRewrite);
- previousTag= movedTag;
- }
- }
- first= false;
- }
- }
- }
- // params with bad names:
- for (Iterator iter= paramTags.iterator(); iter.hasNext();) {
- TagElement tag= (TagElement) iter.next();
- TagElement movedTag= (TagElement) getASTRewrite().createMoveTarget(tag);
- getASTRewrite().remove(tag, fDescription);
- insertTag(movedTag, previousTag, tagsRewrite);
- previousTag= movedTag;
- }
- }
- tags= tagsRewrite.getRewrittenList();
- }
-
- if (! areExceptionsSameAsInitial()) {
- // collect exceptionTags and remove deleted:
- ArrayList exceptionTags= new ArrayList(); // <TagElement>, only not deleted tags with name
- for (int i= 0; i < tags.size(); i++) {
- TagElement tag= (TagElement) tags.get(i);
- if (! TagElement.TAG_THROWS.equals(tag.getTagName()) && ! TagElement.TAG_EXCEPTION.equals(tag.getTagName()))
- continue;
- if (! (tag.fragments().size() > 0 && tag.fragments().get(0) instanceof Name))
- continue;
- boolean tagDeleted= false;
- Name name= (Name) tag.fragments().get(0);
- for (int j= 0; j < fExceptionInfos.size(); j++) {
- ExceptionInfo info= (ExceptionInfo) fExceptionInfos.get(j);
- if (info.isDeleted()) {
- boolean remove= false;
- final ITypeBinding nameBinding= name.resolveTypeBinding();
- if (nameBinding != null) {
- final ITypeBinding infoBinding= info.getTypeBinding();
- if (infoBinding != null && Bindings.equals(infoBinding, nameBinding))
- remove= true;
- else if (info.getType().getElementName().equals(nameBinding.getName()))
- remove= true;
- if (remove) {
- getASTRewrite().remove(tag, fDescription);
- registerImportRemoveNode(tag);
- tagDeleted= true;
- break;
- }
- }
- }
- }
- if (! tagDeleted)
- exceptionTags.add(tag);
- }
- // reshuffle:
- tags= tagsRewrite.getRewrittenList();
- TagElement previousTag= findTagElementToInsertAfter(tags, TagElement.TAG_THROWS);
- for (Iterator infoIter= fExceptionInfos.iterator(); infoIter.hasNext();) {
- ExceptionInfo info= (ExceptionInfo) infoIter.next();
- if (info.isAdded()) {
- if (!isTopOfRipple)
- continue;
- TagElement excptNode= createExceptionTag(info.getType().getElementName());
- insertTag(excptNode, previousTag, tagsRewrite);
- previousTag= excptNode;
- } else {
- for (Iterator tagIter= exceptionTags.iterator(); tagIter.hasNext();) {
- TagElement tag= (TagElement) tagIter.next();
- Name tagName= (Name) tag.fragments().get(0);
- final ITypeBinding nameBinding= tagName.resolveTypeBinding();
- if (nameBinding != null) {
- boolean process= false;
- final ITypeBinding infoBinding= info.getTypeBinding();
- if (infoBinding != null && Bindings.equals(infoBinding, nameBinding))
- process= true;
- else if (info.getType().getElementName().equals(nameBinding.getName()))
- process= true;
- if (process) {
- tagIter.remove();
- TagElement movedTag= (TagElement) getASTRewrite().createMoveTarget(tag);
- getASTRewrite().remove(tag, fDescription);
- insertTag(movedTag, previousTag, tagsRewrite);
- previousTag= movedTag;
- }
- }
- }
- }
- }
- // exceptions with bad names:
- for (Iterator iter= exceptionTags.iterator(); iter.hasNext();) {
- TagElement tag= (TagElement) iter.next();
- TagElement movedTag= (TagElement) getASTRewrite().createMoveTarget(tag);
- getASTRewrite().remove(tag, fDescription);
- insertTag(movedTag, previousTag, tagsRewrite);
- previousTag= movedTag;
- }
- }
- }
-
- private TagElement createReturnTag() {
- TagElement returnNode= getASTRewrite().getAST().newTagElement();
- returnNode.setTagName(TagElement.TAG_RETURN);
-
- TextElement textElement= getASTRewrite().getAST().newTextElement();
- String text= StubUtility.getTodoTaskTag(fCuRewrite.getCu().getJavaScriptProject());
- if (text != null)
- textElement.setText(text); //TODO: use template with {@todo} ...
- returnNode.fragments().add(textElement);
-
- return returnNode;
- }
-
- private TagElement createExceptionTag(String simpleName) {
- TagElement excptNode= getASTRewrite().getAST().newTagElement();
- excptNode.setTagName(TagElement.TAG_THROWS);
-
- SimpleName nameNode= getASTRewrite().getAST().newSimpleName(simpleName);
- excptNode.fragments().add(nameNode);
-
- TextElement textElement= getASTRewrite().getAST().newTextElement();
- String text= StubUtility.getTodoTaskTag(fCuRewrite.getCu().getJavaScriptProject());
- if (text != null)
- textElement.setText(text); //TODO: use template with {@todo} ...
- excptNode.fragments().add(textElement);
-
- return excptNode;
- }
-
- private void insertTag(TagElement tag, TagElement previousTag, ListRewrite tagsRewrite) {
- if (previousTag == null)
- tagsRewrite.insertFirst(tag, fDescription);
- else
- tagsRewrite.insertAfter(tag, previousTag, fDescription);
- }
-
- /**
- * @param tags existing tags
- * @param tagName name of tag to add
- * @return the <code>TagElement<code> just before a new <code>TagElement</code> with name <code>tagName</code>,
- * or <code>null</code>.
- */
- private TagElement findTagElementToInsertAfter(List tags, String tagName) {
- List tagOrder= Arrays.asList(new String[] {
- TagElement.TAG_AUTHOR,
- TagElement.TAG_VERSION,
- TagElement.TAG_PARAM,
- TagElement.TAG_RETURN,
- TagElement.TAG_THROWS,
- TagElement.TAG_EXCEPTION,
- TagElement.TAG_SEE,
- TagElement.TAG_SINCE,
- TagElement.TAG_SERIAL,
- TagElement.TAG_SERIALFIELD,
- TagElement.TAG_SERIALDATA,
- TagElement.TAG_DEPRECATED,
- TagElement.TAG_VALUE
- });
- int goalOrdinal= tagOrder.indexOf(tagName);
- if (goalOrdinal == -1) // unknown tag -> to end
- return (tags.size() == 0) ? null : (TagElement) tags.get(tags.size());
- for (int i= 0; i < tags.size(); i++) {
- int tagOrdinal= tagOrder.indexOf(((TagElement) tags.get(i)).getTagName());
- if (tagOrdinal >= goalOrdinal)
- return (i == 0) ? null : (TagElement) tags.get(i-1);
- }
- return (tags.size() == 0) ? null : (TagElement) tags.get(tags.size()-1);
- }
-
- //TODO: already reported as compilation error -> don't report there?
- private void checkIfDeletedParametersUsed() {
- for (Iterator iter= getDeletedInfos().iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex());
- TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(paramDecl, false);
- analyzer.perform();
- SimpleName[] paramRefs= analyzer.getReferenceNodes();
-
- if (paramRefs.length > 0){
- RefactoringStatusContext context= JavaStatusContext.create(fCuRewrite.getCu(), paramRefs[0]);
- String typeName= getFullTypeName(fMethDecl);
- Object[] keys= new String[]{paramDecl.getName().getIdentifier(),
- fMethDecl.getName().getIdentifier(),
- typeName};
- String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_parameter_used, keys);
- fResult.addError(msg, context);
- }
- }
- }
-
- private String getFullTypeName(FunctionDeclaration decl) {
- ASTNode node= decl;
- while (true) {
- node= node.getParent();
- if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration) node).getName().getIdentifier();
- } else if (node instanceof ClassInstanceCreation) {
- ClassInstanceCreation cic= (ClassInstanceCreation) node;
- return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, new String[]{ASTNodes.asString(cic.getType())});
- }
- }
- }
-
- protected ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) {
- return createNewSingleVariableDeclaration(info);
- }
-
- private SingleVariableDeclaration createNewSingleVariableDeclaration(ParameterInfo info) {
- SingleVariableDeclaration newP= getASTRewrite().getAST().newSingleVariableDeclaration();
- newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName()));
- newP.setType(createNewTypeNode(ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding()));
- newP.setVarargs(info.isNewVarargs());
- return newP;
- }
-
- protected SimpleName getMethodNameNode() {
- return fMethDecl.getName();
- }
-
- }
-
- class DocReferenceUpdate extends OccurrenceUpdate {
- /** instanceof MemberRef || FunctionRef */
- private ASTNode fNode;
-
- protected DocReferenceUpdate(ASTNode node, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
- super(cuRewrite, cuRewrite.createGroupDescription(RefactoringCoreMessages.ChangeSignatureRefactoring_update_javadoc_reference), result);
- fNode= node;
- }
-
- public void updateNode() {
- if (fNode instanceof FunctionRef) {
- changeParamguments();
- reshuffleElements();
- }
- if (canChangeNameAndReturnType())
- changeMethodName();
- }
-
- protected ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) {
- return createNewMethodRefParameter(info);
- }
-
- private FunctionRefParameter createNewMethodRefParameter(ParameterInfo info) {
- FunctionRefParameter newP= getASTRewrite().getAST().newFunctionRefParameter();
-
- // only add name iff first parameter already has a name:
- List parameters= getParamgumentsRewrite().getOriginalList();
- if (parameters.size() > 0)
- if (((FunctionRefParameter) parameters.get(0)).getName() != null)
- newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName()));
-
- newP.setType(createNewDocRefType(info));
- newP.setVarargs(info.isNewVarargs());
- return newP;
- }
-
- private Type createNewDocRefType(ParameterInfo info) {
- String newTypeName= ParameterInfo.stripEllipsis(info.getNewTypeName());
- ITypeBinding newTypeBinding= info.getNewTypeBinding();
- if (newTypeBinding != null)
- newTypeBinding= newTypeBinding.getErasure(); //see bug 83127: Javadoc references are raw (erasures)
- return createNewTypeNode(newTypeName, newTypeBinding);
- }
-
- protected SimpleName getMethodNameNode() {
- if (fNode instanceof MemberRef)
- return ((MemberRef) fNode).getName();
-
- if (fNode instanceof FunctionRef)
- return ((FunctionRef) fNode).getName();
-
- return null;
- }
-
- /** @return {@inheritDoc} (element type: FunctionRefParameter) */
- protected ListRewrite getParamgumentsRewrite() {
- return getASTRewrite().getListRewrite(fNode, FunctionRef.PARAMETERS_PROPERTY);
- }
-
- protected void changeParamgumentName(ParameterInfo info) {
- if (! (fNode instanceof FunctionRef))
- return;
-
- FunctionRefParameter oldParam= (FunctionRefParameter) ((FunctionRef) fNode).parameters().get(info.getOldIndex());
- SimpleName oldParamName= oldParam.getName();
- if (oldParamName != null)
- getASTRewrite().set(oldParamName, SimpleName.IDENTIFIER_PROPERTY, info.getNewName(), fDescription);
- }
-
- protected void changeParamgumentType(ParameterInfo info) {
- if (! (fNode instanceof FunctionRef))
- return;
-
- FunctionRefParameter oldParam= (FunctionRefParameter) ((FunctionRef) fNode).parameters().get(info.getOldIndex());
- Type oldTypeNode= oldParam.getType();
- Type newTypeNode= createNewDocRefType(info);
- if (info.isNewVarargs()) {
- if (info.isOldVarargs() && ! oldParam.isVarargs()) {
- // leave as array reference of old reference was not vararg
- newTypeNode= getASTRewrite().getAST().newArrayType(newTypeNode);
- } else {
- getASTRewrite().set(oldParam, FunctionRefParameter.VARARGS_PROPERTY, Boolean.TRUE, fDescription);
- }
- } else {
- if (oldParam.isVarargs()) {
- getASTRewrite().set(oldParam, FunctionRefParameter.VARARGS_PROPERTY, Boolean.FALSE, fDescription);
- }
- }
-
- getASTRewrite().replace(oldTypeNode, newTypeNode, fDescription);
- registerImportRemoveNode(oldTypeNode);
- }
- }
-
- class StaticImportUpdate extends OccurrenceUpdate {
-
- private final ImportDeclaration fImportDecl;
-
- public StaticImportUpdate(ImportDeclaration importDecl, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
- super(cuRewrite, null, result);
- fImportDecl= importDecl;
- }
-
- public void updateNode() throws JavaScriptModelException {
- ImportRewrite importRewrite= fCuRewrite.getImportRewrite();
- QualifiedName name= (QualifiedName) fImportDecl.getName();
- //will be removed by importRemover if not used elsewhere ... importRewrite.removeStaticImport(name.getFullyQualifiedName());
- importRewrite.addStaticImport(name.getQualifier().getFullyQualifiedName(), fMethodName, false);
- }
-
- protected ListRewrite getParamgumentsRewrite() {
- return null;
- }
-
- protected ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) {
- return null;
- }
-
- protected SimpleName getMethodNameNode() {
- return null;
- }
- }
-
- class NullOccurrenceUpdate extends OccurrenceUpdate {
- private ASTNode fNode;
- protected NullOccurrenceUpdate(ASTNode node, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
- super(cuRewrite, null, result);
- fNode= node;
- }
- public void updateNode() throws JavaScriptModelException {
- int start= fNode.getStartPosition();
- int length= fNode.getLength();
- String msg= "Cannot update found node: nodeType=" + fNode.getNodeType() + "; " //$NON-NLS-1$//$NON-NLS-2$
- + fNode.toString() + "[" + start + ", " + length + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- JavaScriptPlugin.log(new Exception(msg + ":\n" + fCuRewrite.getCu().getSource().substring(start, start + length))); //$NON-NLS-1$
- fResult.addError(msg, JavaStatusContext.create(fCuRewrite.getCu(), fNode));
- }
- protected ListRewrite getParamgumentsRewrite() {
- return null;
- }
- protected ASTNode createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) {
- return null;
- }
- protected SimpleName getMethodNameNode() {
- return null;
- }
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.METHOD)
- return createInputFatalStatus(element, IJavaScriptRefactorings.CHANGE_METHOD_SIGNATURE);
- else {
- fMethod= (IFunction) element;
- fMethodName= fMethod.getElementName();
- try {
- fVisibility= JdtFlags.getVisibilityCode(fMethod);
- fReturnTypeInfo= new ReturnTypeInfo(Signature.toString(Signature.getReturnType(fMethod.getSignature())));
- } catch (JavaScriptModelException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, ATTRIBUTE_VISIBILITY));
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null) {
- fMethodName= name;
- final RefactoringStatus status= Checks.checkMethodName(fMethodName);
- if (status.hasError())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String type= extended.getAttribute(ATTRIBUTE_RETURN);
- if (type != null && !"".equals(type)) //$NON-NLS-1$
- fReturnTypeInfo= new ReturnTypeInfo(type);
- final String visibility= extended.getAttribute(ATTRIBUTE_VISIBILITY);
- if (visibility != null && !"".equals(visibility)) {//$NON-NLS-1$
- int flag= 0;
- try {
- flag= Integer.parseInt(visibility);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_VISIBILITY));
- }
- fVisibility= flag;
- }
- int count= 1;
- String attribute= ATTRIBUTE_PARAMETER + count;
- String value= null;
- fParameterInfos= new ArrayList(3);
- while ((value= extended.getAttribute(attribute)) != null) {
- StringTokenizer tokenizer= new StringTokenizer(value);
- if (tokenizer.countTokens() < 6)
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, ATTRIBUTE_PARAMETER));
- String oldTypeName= tokenizer.nextToken();
- String oldName= tokenizer.nextToken();
- String oldIndex= tokenizer.nextToken();
- String newTypeName= tokenizer.nextToken();
- String newName= tokenizer.nextToken();
- String deleted= tokenizer.nextToken();
- ParameterInfo info= null;
- try {
- info= new ParameterInfo(oldTypeName, oldName, Integer.valueOf(oldIndex).intValue());
- info.setNewTypeName(newTypeName);
- info.setNewName(newName);
- if (Boolean.valueOf(deleted).booleanValue())
- info.markAsDeleted();
- fParameterInfos.add(info);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, ATTRIBUTE_PARAMETER));
- }
- final String result= extended.getAttribute(ATTRIBUTE_DEFAULT + count);
- if (result != null && !"".equals(result)) //$NON-NLS-1$
- info.setDefaultValue(result);
- count++;
- attribute= ATTRIBUTE_PARAMETER + count;
- }
- count= 1;
- fExceptionInfos= new ArrayList(2);
- attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- while ((value= extended.getAttribute(attribute)) != null) {
- ExceptionInfo info= null;
- final String kind= extended.getAttribute(ATTRIBUTE_KIND + count);
- if (kind != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), value, false);
- if (element == null || !element.exists())
- return createInputFatalStatus(element, IJavaScriptRefactorings.CHANGE_METHOD_SIGNATURE);
- else {
- try {
- info= new ExceptionInfo((IType) element, Integer.valueOf(kind).intValue(), null);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, ATTRIBUTE_KIND));
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, ATTRIBUTE_KIND));
- fExceptionInfos.add(info);
- count++;
- attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- }
- final String deprecate= extended.getAttribute(ATTRIBUTE_DEPRECATE);
- if (deprecate != null) {
- fDelegateDeprecation= Boolean.valueOf(deprecate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE));
- final String delegate= extended.getAttribute(ATTRIBUTE_DELEGATE);
- if (delegate != null) {
- fDelegateUpdating= Boolean.valueOf(delegate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELEGATE));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * If this occurrence update is called from within a declaration update
- * (i.e., to update the call inside the newly created delegate), the old
- * node does not yet exist and therefore cannot be a move target.
- *
- * Normally, always use createMoveTarget as this has the advantage of
- * being able to add changes inside changed nodes (for example, a method
- * call within a method call, see test case #4) and preserving comments
- * inside calls.
- * @param oldNode original node
- * @param rewrite an AST rewrite
- * @return the node to insert at the target location
- */
- protected ASTNode moveNode(ASTNode oldNode, ASTRewrite rewrite) {
- ASTNode movedNode;
- if (ASTNodes.isExistingNode(oldNode))
- movedNode= rewrite.createMoveTarget(oldNode); //node must be one of ast
- else
- movedNode= ASTNode.copySubtree(rewrite.getAST(), oldNode);
- return movedNode;
- }
-
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateCreator_keep_original_changed_plural;
- else
- return RefactoringCoreMessages.DelegateCreator_keep_original_changed_singular;
- }
-
- public IDefaultValueAdvisor getDefaultValueAdvisor() {
- return fDefaultValueAdvisor;
- }
-
- public void setDefaultValueAdvisor(IDefaultValueAdvisor defaultValueAdvisor) {
- fDefaultValueAdvisor= defaultValueAdvisor;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
deleted file mode 100644
index b7bce07a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
+++ /dev/null
@@ -1,1419 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CollectingSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RippleMethodFinder2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ASTCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompositeOrTypeConstraint;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ConstraintCollector;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ConstraintOperator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ConstraintVariableFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ExpressionVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.FullConstraintCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ITypeConstraint;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ParameterTypeVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ReturnTypeVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.SimpleTypeConstraint;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.TypeConstraintFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.TypeVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * @author tip
- */
-public class ChangeTypeRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_TYPE= "type"; //$NON-NLS-1$
-
- private final Map/*<IJavaScriptUnit, Collection<ITypeConstraint>>*/ fConstraintCache;
- /**
- * Offset of the selected text area.
- */
- private int fSelectionStart;
-
- /**
- * Length of the selected text area.
- */
- private int fSelectionLength;
-
- /**
- * Offset of the effective selection
- */
- private int fEffectiveSelectionStart;
-
- /**
- * Length of the effective selection
- */
- private int fEffectiveSelectionLength;
-
- /**
- * IJavaScriptUnit containing the selection.
- */
- private IJavaScriptUnit fCu;
-
- /**
- * If the selection corresponds to a method parameter/return type, this field stores
- * a reference to its IFunctionBinding, otherwise this field remains null. Used during
- * search for references in other CUs, and for determining the ConstraintVariable
- * that corresponds to the selection
- */
- private IFunctionBinding fMethodBinding;
-
- /**
- * If the selection corresponds to a method parameter, this field stores the parameter
- * index (0 = first parameter for static methods, 0 = this for nonstatic methods). The
- * value -1 is stored in the field if the selection corresponds to a method return type.
- */
- private int fParamIndex;
-
- /**
- * The name of the selected parameter, or <code>null</code>.
- */
- private String fParamName;
-
- /**
- * If the selection corresponds to a field, this field stores a reference to its IVariableBinding,
- * otherwise this field remains null. Used during search for references in other CUs.
- */
- private IVariableBinding fFieldBinding;
-
- /**
- * The compilation units that contain constraint variables related to the selection
- */
- private IJavaScriptUnit[] fAffectedUnits;
-
- /**
- * The constraint variables that are of interest to this refactoring. This includes
- * the constraint var. corresponding to the text selection, and possibly additional
- * elements due to method overriding, method calls, etc.
- */
- private Collection/*<ConstraintVariable>*/ fRelevantVars;
-
- /**
- * The set of types (other than the original type) that can be given to
- * the selected ASTNode.
- */
- private final Collection/*<IType>*/ fValidTypes;
-
- /**
- * The type constraints that are related to the selected ASTNode.
- */
- private Collection/*<ITypeConstraint>*/ fRelevantConstraints;
-
- /**
- * All type constraints in affected compilation units.
- */
- private Collection/*<ITypeConstraint>*/ fAllConstraints;
-
- /**
- * The name of the new type of the selected declaration.
- */
- private String fSelectedTypeName;
-
- /**
- * The new type of the selected declaration.
- */
- private ITypeBinding fSelectedType;
-
- /**
- * Organizes SearchResults by JavaScriptUnit
- */
- private Map/*<IJavaScriptUnit,SearchResultGroup>*/ fCuToSearchResultGroup= new HashMap();
-
-
- /**
- * ITypeBinding for java.lang.Object
- */
- private ITypeBinding fObject;
-
- public ITypeBinding getObject(){
- return fObject;
- }
-
- /**
- * Control debugging output.
- */
- private static final boolean DEBUG= false;
-
- private ConstraintVariable fCv;
- private IBinding fSelectionBinding;
- private ITypeBinding fSelectionTypeBinding;
- private ConstraintCollector fCollector;
-
- public ChangeTypeRefactoring(IJavaScriptUnit cu, int selectionStart, int selectionLength) {
- this(cu, selectionStart, selectionLength, null);
- }
-
- /**
- * Constructor for ChangeTypeRefactoring (invoked from tests only)
- */
- public ChangeTypeRefactoring(IJavaScriptUnit cu, int selectionStart, int selectionLength, String selectedType) {
- Assert.isTrue(selectionStart >= 0);
- Assert.isTrue(selectionLength >= 0);
-
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
-
- fEffectiveSelectionStart= selectionStart;
- fEffectiveSelectionLength= selectionLength;
-
- fCu= cu;
-
- if (selectedType != null)
- fSelectedTypeName= selectedType;
-
- fConstraintCache= new HashMap();
- fValidTypes= new HashSet();
- }
-
- // ------------------------------------------------------------------------------------------------- //
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- if (fCu == null || !fCu.isStructureKnown())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_invalidSelection);
- return checkSelection(new SubProgressMonitor(pm, 1));
- }
-
- private void setSelectionRanges(Expression exp){
- fEffectiveSelectionStart= exp.getStartPosition();
- fEffectiveSelectionLength= exp.getLength();
- fSelectionBinding= ExpressionVariable.resolveBinding(exp);
- setOriginalType(exp.resolveTypeBinding());
- }
-
- /**
- * Check if the right type of AST Node is selected. Create the TypeHierarchy needed to
- * bring up the wizard.
- */
- private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaScriptModelException {
- try {
- pm.beginTask("", 5); //$NON-NLS-1$
-
- ASTNode node= getTargetNode(fCu, fSelectionStart, fSelectionLength);
- if (DEBUG) {
- System.out.println(
- "selection: [" //$NON-NLS-1$
- + fSelectionStart
- + "," //$NON-NLS-1$
- + (fSelectionStart + fSelectionLength)
- + "] in " //$NON-NLS-1$
- + fCu.getElementName());
- System.out.println("node= " + node + ", type= " + node.getClass().getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- TypeConstraintFactory typeConstraintFactory = new TypeConstraintFactory(){
- public boolean filter(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator o){
- if (o.isStrictSubtypeOperator()) //TODO: explain why these can be excluded
- return true;
- //Don't create constraint if fSelectionTypeBinding is not involved:
- if (v1.getBinding() != null && v2.getBinding() != null
- && ! Bindings.equals(v1.getBinding(), fSelectionTypeBinding)
- && ! Bindings.equals(v2.getBinding(), fSelectionTypeBinding)) {
- if (PRINT_STATS) fNrFiltered++;
- return true;
- }
- return super.filter(v1, v2, o);
- }
- };
- fCollector= new ConstraintCollector(new FullConstraintCreator(new ConstraintVariableFactory(), typeConstraintFactory));
- String selectionValid= determineSelection(node);
- if (selectionValid != null){
- if (DEBUG){
- System.out.println("invalid selection: " + selectionValid); //$NON-NLS-1$
- }
- return RefactoringStatus.createFatalErrorStatus(selectionValid);
- }
-
- if (fMethodBinding != null) {
- IFunction selectedMethod= (IFunction) fMethodBinding.getJavaElement();
- if (selectedMethod == null){
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_insideLocalTypesNotSupported);
- }
- }
-
- pm.worked(1);
-
- RefactoringStatus result= new RefactoringStatus();
-
- if (DEBUG){
- System.out.println("fSelectionTypeBinding: " + fSelectionTypeBinding.getName()); //$NON-NLS-1$
- }
-
- // produce error message if array or primitive type is selected
- if (fSelectionTypeBinding.isArray()){
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_arraysNotSupported);
- }
- if (fSelectionTypeBinding.isPrimitive()){
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_primitivesNotSupported);
- }
- if (checkOverriddenBinaryMethods())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnBinary);
-
- if (fSelectionTypeBinding.isLocal()){
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_localTypesNotSupported);
- }
-
- if (fFieldBinding != null && fFieldBinding.getDeclaringClass().isLocal()){
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeTypeRefactoring_insideLocalTypesNotSupported);
- }
-
- pm.worked(1);
-
- if (fSelectedType != null){ // if invoked from unit test, compute valid types here
- computeValidTypes(new NullProgressMonitor());
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- private boolean checkOverriddenBinaryMethods() throws JavaScriptModelException {
- if (fMethodBinding != null){
- Set declaringSupertypes= getDeclaringSuperTypes(fMethodBinding);
- for (Iterator iter= declaringSupertypes.iterator(); iter.hasNext();) {
- ITypeBinding superType= (ITypeBinding) iter.next();
- IFunctionBinding overriddenMethod= findMethod(fMethodBinding, superType);
- Assert.isNotNull(overriddenMethod);//because we asked for declaring types
- IFunction iMethod= (IFunction) overriddenMethod.getJavaElement();
- if (iMethod.isBinary()){
- return true;
- }
- }
- }
- return false;
- }
-
- // copied from FullConstraintCreator
- private static IFunctionBinding findMethod(IFunctionBinding methodBinding, ITypeBinding type) {
- if (methodBinding.getDeclaringClass().equals(type))
- return methodBinding;
- return Bindings.findOverriddenMethodInType(type, methodBinding);
- }
-
- // copied from FullConstraintCreator
- private static Set getDeclaringSuperTypes(IFunctionBinding methodBinding) {
- ITypeBinding[] allSuperTypes= Bindings.getAllSuperTypes(methodBinding.getDeclaringClass());
- Set result= new HashSet();
- for (int i= 0; i < allSuperTypes.length; i++) {
- ITypeBinding type= allSuperTypes[i];
- if (findMethod(methodBinding, type) != null)
- result.add(type);
- }
- return result;
- }
-
- /**
- * Do the actual work of computing allowable types. Invoked by the wizard when
- * "compute" button is pressed
- */
- public Collection/*<IType>*/ computeValidTypes(IProgressMonitor pm) {
-
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_checking_preconditions, 100);
-
- try {
- fCv= findConstraintVariableForSelectedNode(new SubProgressMonitor(pm, 3));
- if (DEBUG) System.out.println("selected CV: " + fCv + //$NON-NLS-1$
- " (" + fCv.getClass().getName() + //$NON-NLS-1$
- ")"); //$NON-NLS-1$
-
- if (pm.isCanceled())
- throw new OperationCanceledException();
- fRelevantVars= findRelevantConstraintVars(fCv, new SubProgressMonitor(pm, 50));
-
- if (DEBUG)
- printCollection("relevant vars:", fRelevantVars); //$NON-NLS-1$
-
- if (pm.isCanceled())
- throw new OperationCanceledException();
- fRelevantConstraints= findRelevantConstraints(fRelevantVars, new SubProgressMonitor(pm, 30));
-
- if (pm.isCanceled())
- throw new OperationCanceledException();
- fValidTypes.addAll(computeValidTypes(fSelectionTypeBinding, fRelevantVars,
- fRelevantConstraints, new SubProgressMonitor(pm, 20)));
-
- if (DEBUG)
- printCollection("valid types:", getValidTypeNames()); //$NON-NLS-1$
- } catch (CoreException e) {
- JavaScriptPlugin.logErrorMessage("Error occurred during computation of valid types: " + e.toString()); //$NON-NLS-1$
- fValidTypes.clear(); // error occurred during computation of valid types
- }
-
- pm.done();
-
- return fValidTypes;
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_checking_preconditions, 1);
-
- RefactoringStatus result= Checks.validateModifiesFiles(
- ResourceUtil.getFiles(fAffectedUnits), getValidationContext());
-
- pm.done();
- return result;
- }
-// TODO: do sanity check somewhere if the refactoring changes any files.
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeMessages_CreateChangesForChangeType, 1);
- try {
- Map/* <IJavaScriptUnit,Set<ConstraintVariable>> */relevantVarsByUnit= new HashMap/* <IJavaScriptUnit,HashSet<ConstraintVariable>> */();
- groupChangesByCompilationUnit(relevantVarsByUnit);
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fCu.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final String description= RefactoringCoreMessages.ChangeTypeRefactoring_descriptor_description_short;
- final String header= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(fSelectionBinding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(fSelectedType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_original_element_pattern, BindingLabelProvider.getBindingLabel(fSelectionBinding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_original_type_pattern, BindingLabelProvider.getBindingLabel(getOriginalType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_refactored_type_pattern, BindingLabelProvider.getBindingLabel(fSelectedType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.GENERALIZE_TYPE, project, description, comment.asString(), arguments, (RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCu));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
- arguments.put(ATTRIBUTE_TYPE, fSelectedType.getQualifiedName());
- final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ChangeTypeRefactoring_allChanges);
- for (Iterator/* <IJavaScriptUnit> */it= relevantVarsByUnit.keySet().iterator(); it.hasNext();) {
- IJavaScriptUnit icu= (IJavaScriptUnit) it.next();
- Set/* <ConstraintVariable> */cVars= (Set) relevantVarsByUnit.get(icu);
- CompilationUnitChange cuChange= new CompilationUnitChange(getName(), icu);
- addAllChangesFor(icu, cVars, cuChange);
- result.add(cuChange);
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- return result;
- } finally {
- pm.done();
- }
- }
-
- /**
- * Apply all changes related to a single IJavaScriptUnit
- */
- private void addAllChangesFor(IJavaScriptUnit icu, Set vars, CompilationUnitChange unitChange) throws CoreException {
- JavaScriptUnit unit= new RefactoringASTParser(AST.JLS3).parse(icu, false);
- ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST());
- MultiTextEdit root= new MultiTextEdit();
- unitChange.setEdit(root); // Adam sez don't need this, but then unitChange.addGroupDescription() fails an assertion!
-
- String typeName= updateImports(unit, root);
- updateCu(unit, vars, unitChange, unitRewriter, typeName);
- root.addChild(unitRewriter.rewriteAST());
- }
-
- private class SourceRangeComputer extends TargetSourceRangeComputer {
- public SourceRange computeSourceRange(ASTNode node) {
- return new SourceRange(node.getStartPosition(),node.getLength());
- }
- }
-
- private void updateCu(JavaScriptUnit unit, Set vars, CompilationUnitChange unitChange,
- ASTRewrite unitRewriter, String typeName) throws JavaScriptModelException {
-
- // use custom SourceRangeComputer to avoid losing comments
- unitRewriter.setTargetSourceRangeComputer(new SourceRangeComputer());
-
- for (Iterator it=vars.iterator(); it.hasNext(); ){
- ConstraintVariable cv = (ConstraintVariable)it.next();
- ASTNode decl= findDeclaration(unit, cv);
- if ((decl instanceof SimpleName || decl instanceof QualifiedName) && cv instanceof ExpressionVariable) {
- ASTNode gp= decl.getParent().getParent();
- updateType(unit, getType(gp), unitChange, unitRewriter, typeName); // local variable or parameter
- } else if (decl instanceof FunctionDeclaration || decl instanceof FieldDeclaration) {
- updateType(unit, getType(decl), unitChange, unitRewriter, typeName); // method return or field type
- }
- }
- }
-
- private void updateType(JavaScriptUnit cu, Type oldType, CompilationUnitChange unitChange,
- ASTRewrite unitRewriter, String typeName) {
-
- String oldName= fSelectionTypeBinding.getName();
- String description= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_typeChange, new String[] {oldName, typeName});
- TextEditGroup gd= new TextEditGroup(description);
- AST ast= cu.getAST();
-
- ASTNode nodeToReplace= oldType;
-
- //TODO handle types other than simple & parameterized (e.g., arrays)
- Assert.isTrue(fSelectedType.isClass());
-
- Type newType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeName));
-
- unitRewriter.replace(nodeToReplace, newType, gd);
- unitChange.addTextEditGroup(gd);
- }
-
- private void groupChangesByCompilationUnit(Map relevantVarsByUnit) throws JavaScriptModelException {
- for (Iterator it= fRelevantVars.iterator(); it.hasNext();) {
- ConstraintVariable cv= (ConstraintVariable) it.next();
- if (!(cv instanceof ExpressionVariable) && !(cv instanceof ReturnTypeVariable)){
- continue;
- }
- IJavaScriptUnit icu = null;
- if (cv instanceof ExpressionVariable) {
- ExpressionVariable ev = (ExpressionVariable)cv;
- icu = ev.getCompilationUnitRange().getCompilationUnit();
- } else if (cv instanceof ReturnTypeVariable){
- ReturnTypeVariable rtv = (ReturnTypeVariable)cv;
- IFunctionBinding mb= rtv.getMethodBinding();
- icu= ((IFunction) mb.getJavaElement()).getJavaScriptUnit();
- }
- if (!relevantVarsByUnit.containsKey(icu)){
- relevantVarsByUnit.put(icu, new HashSet/*<ConstraintVariable>*/());
- }
- ((Set)relevantVarsByUnit.get(icu)).add(cv);
- }
- }
-
- private ASTNode findDeclaration(JavaScriptUnit root, ConstraintVariable cv) throws JavaScriptModelException {
-
- if (fFieldBinding != null){
- IField f= (IField) fFieldBinding.getJavaElement();
- return ASTNodeSearchUtil.getFieldDeclarationNode(f, root);
- }
-
- if (cv instanceof ExpressionVariable){
- for (Iterator iter= fAllConstraints.iterator(); iter.hasNext();) {
- ITypeConstraint constraint= (ITypeConstraint) iter.next();
- if (constraint.isSimpleTypeConstraint()){
- SimpleTypeConstraint stc= (SimpleTypeConstraint)constraint;
- if (stc.isDefinesConstraint() && stc.getLeft().equals(cv)){
- ConstraintVariable right= stc.getRight();
- if (right instanceof TypeVariable){
- TypeVariable typeVariable= (TypeVariable)right;
- return NodeFinder.perform(root, typeVariable.getCompilationUnitRange().getSourceRange());
- }
- }
- }
- }
- } else if (cv instanceof ReturnTypeVariable) {
- ReturnTypeVariable rtv= (ReturnTypeVariable) cv;
- IFunctionBinding mb= rtv.getMethodBinding();
- IFunction im= (IFunction) mb.getJavaElement();
- return ASTNodeSearchUtil.getMethodDeclarationNode(im, root);
- }
- return null;
- }
-
- private static Type getType(ASTNode node) {
- switch(node.getNodeType()){
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- return ((SingleVariableDeclaration) node).getType();
- case ASTNode.FIELD_DECLARATION:
- return ((FieldDeclaration) node).getType();
- case ASTNode.VARIABLE_DECLARATION_STATEMENT:
- return ((VariableDeclarationStatement) node).getType();
- case ASTNode.FUNCTION_DECLARATION:
- return ((FunctionDeclaration)node).getReturnType2();
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.ChangeTypeRefactoring_name;
- }
-
- // ------------------------------------------------------------------------------------------------- //
- // Method for examining if a suitable kind of ASTNode was selected. Information about this node and
- // its parents in the AST are stored in fields fBinding, theMethod, and theField
-
- /**
- * Determines what kind of ASTNode has been selected. A non-null String containing an error message
- * is returned if the ChangeTypeRefactoring refactoring cannot be applied to the selected ASTNode.
- * A return value of null indicates a valid selection.
- */
- private String determineSelection(ASTNode node) {
- if (node == null) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_invalidSelection;
- } else {
-
- if (DEBUG) System.out.println("node nodeType= " + node.getClass().getName()); //$NON-NLS-1$
- if (DEBUG) System.out.println("parent nodeType= " + node.getParent().getClass().getName()); //$NON-NLS-1$
- if (DEBUG) System.out.println("GrandParent nodeType= " + node.getParent().getParent().getClass().getName()); //$NON-NLS-1$
-
- ASTNode parent= node.getParent();
- ASTNode grandParent= parent.getParent();
- if (grandParent == null)
- return nodeTypeNotSupported();
-
- // adjustment needed if part of a qualified name is selected
- ASTNode current= null;
- if (node.getNodeType() == ASTNode.QUALIFIED_NAME){
- current= node;
- while (current.getNodeType() == ASTNode.QUALIFIED_NAME){
- current= current.getParent();
- }
- if (current.getNodeType() != ASTNode.SIMPLE_TYPE){
- return nodeTypeNotSupported();
- }
- node= current.getParent();
- } else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME){
- current= parent;
- while (current.getNodeType() == ASTNode.QUALIFIED_NAME){
- current= current.getParent();
- }
- if (current.getNodeType() != ASTNode.SIMPLE_TYPE){
- return nodeTypeNotSupported();
- }
- node= current.getParent();
- }
-
- fObject= node.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- switch (node.getNodeType()) {
- case ASTNode.SIMPLE_NAME :
- return simpleNameSelected((SimpleName)node);
- case ASTNode.VARIABLE_DECLARATION_STATEMENT :
- return variableDeclarationStatementSelected((VariableDeclarationStatement) node);
- case ASTNode.FIELD_DECLARATION :
- return fieldDeclarationSelected((FieldDeclaration) node);
- case ASTNode.SINGLE_VARIABLE_DECLARATION :
- return singleVariableDeclarationSelected((SingleVariableDeclaration) node);
- default :
- return nodeTypeNotSupported();
- }
- }
- }
- /**
- * The selection corresponds to an ASTNode on which "ChangeTypeRefactoring" is not defined.
- */
- private static String nodeTypeNotSupported() {
- return RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnNodeType;
- }
-
- /**
- * The selection corresponds to a SingleVariableDeclaration
- */
- private String singleVariableDeclarationSelected(SingleVariableDeclaration svd) {
- SimpleName name = svd.getName();
- setSelectionRanges(name);
- return simpleNameSelected(name);
- }
-
- /**
- * The selection corresponds to a VariableDeclarationStatement
- */
- private String variableDeclarationStatementSelected(VariableDeclarationStatement vds) {
- if (vds.fragments().size() != 1) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- } else {
- VariableDeclarationFragment elem= (VariableDeclarationFragment) vds.fragments().iterator().next();
- SimpleName name= elem.getName();
- setSelectionRanges(name);
- return simpleNameSelected(name);
- }
- }
-
- /**
- * The selection corresponds to a FieldDeclaration
- */
- private String fieldDeclarationSelected(FieldDeclaration fieldDeclaration) {
- if (fieldDeclaration.fragments().size() != 1) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- } else {
- VariableDeclarationFragment elem= (VariableDeclarationFragment) fieldDeclaration.fragments().iterator().next();
- fFieldBinding= elem.resolveBinding();
- SimpleName name= elem.getName();
- setSelectionRanges(name);
- return simpleNameSelected(name);
- }
- }
-
- /**
- * The selection corresponds to a SimpleName
- */
- private String simpleNameSelected(SimpleName simpleName) {
- ASTNode parent= simpleName.getParent();
- ASTNode grandParent= parent.getParent();
-
- if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){
- VariableDeclarationStatement vds= (VariableDeclarationStatement)parent;
- if (vds.fragments().size() > 1){
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- }
- } else if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- if (grandParent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){
- VariableDeclarationStatement vds= (VariableDeclarationStatement)grandParent;
- if (vds.fragments().size() > 1) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- }
- setSelectionRanges(simpleName);
- } else if (grandParent.getNodeType() == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
- VariableDeclarationExpression vde= (VariableDeclarationExpression)grandParent;
- if (vde.fragments().size() > 1) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- }
- setSelectionRanges(simpleName);
- } else if (grandParent.getNodeType() == ASTNode.FIELD_DECLARATION) {
- FieldDeclaration fd= (FieldDeclaration)grandParent;
- if (fd.fragments().size() > 1){
- return RefactoringCoreMessages.ChangeTypeRefactoring_multiDeclarationsNotSupported;
- }
- VariableDeclarationFragment fragment = (VariableDeclarationFragment)parent;
- fFieldBinding= fragment.resolveBinding();
- setSelectionRanges(fragment.getName());
- } else {
- return RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnNodeType;
- }
- } else if (parent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION) {
- SingleVariableDeclaration singleVariableDeclaration= (SingleVariableDeclaration) parent;
- if ((grandParent.getNodeType() == ASTNode.FUNCTION_DECLARATION)) {
- fMethodBinding= ((FunctionDeclaration)grandParent).resolveBinding();
- setOriginalType(simpleName.resolveTypeBinding());
- fParamIndex= ((FunctionDeclaration)grandParent).parameters().indexOf(parent);
- fParamName= singleVariableDeclaration.getName().getIdentifier();
- } else {
- setSelectionRanges(singleVariableDeclaration.getName());
- }
- } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE && (grandParent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION)) {
- ASTNode greatGrandParent= grandParent.getParent();
- SingleVariableDeclaration singleVariableDeclaration= (SingleVariableDeclaration) grandParent;
- if (singleVariableDeclaration.getExtraDimensions() > 0) {
- return RefactoringCoreMessages.ChangeTypeRefactoring_arraysNotSupported;
- }
- if (greatGrandParent != null && greatGrandParent.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- fMethodBinding= ((FunctionDeclaration)greatGrandParent).resolveBinding();
- fParamIndex= ((FunctionDeclaration)greatGrandParent).parameters().indexOf(grandParent);
- fParamName= singleVariableDeclaration.getName().getIdentifier();
- setSelectionRanges(simpleName);
- } else {
- setSelectionRanges(singleVariableDeclaration.getName());
- }
- } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE && grandParent.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- fMethodBinding= ((FunctionDeclaration)grandParent).resolveBinding();
- setOriginalType(fMethodBinding.getReturnType());
- fParamIndex= -1;
- } else if (parent.getNodeType() == ASTNode.FUNCTION_DECLARATION &&
- grandParent.getNodeType() == ASTNode.TYPE_DECLARATION) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration)parent;
- if (methodDeclaration.getName().equals(simpleName) || methodDeclaration.thrownExceptions().contains(simpleName)){
- return RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnNodeType;
- }
- fMethodBinding= ((FunctionDeclaration)parent).resolveBinding();
- fParamIndex= -1;
- } else if (
- parent.getNodeType() == ASTNode.SIMPLE_TYPE && (grandParent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT)) {
- return variableDeclarationStatementSelected((VariableDeclarationStatement) grandParent);
- } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE &&
- grandParent.getNodeType() == ASTNode.FIELD_DECLARATION) {
- return fieldDeclarationSelected((FieldDeclaration) grandParent);
- } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE &&
- grandParent.getNodeType() == ASTNode.ARRAY_TYPE){
- return RefactoringCoreMessages.ChangeTypeRefactoring_arraysNotSupported;
- } else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME){
- setSelectionRanges(simpleName);
- } else {
- return RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnNodeType;
- }
- return null;
- }
-
- // ------------------------------------------------------------------------------------------------- //
- // Methods for examining & solving type constraints. This includes:
- // (1) locating the ConstraintVariable corresponding to the selected ASTNode
- // (2) finding all ConstraintVariables "related" to (1) via overriding, method calls, field access
- // (3) find all ITypeConstraints of interest that mention ConstraintVariables in (2)
- // (4) determining all ITypes for which the ITypeConstraints in (3) are satisfied
-
- /**
- * Find a ConstraintVariable that corresponds to the selected ASTNode.
- */
- private ConstraintVariable findConstraintVariableForSelectedNode(IProgressMonitor pm) {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, 100);
- IJavaScriptUnit[] cus= { fCu }; // only search in CU containing selection
-
- if (DEBUG){
- System.out.println("Effective selection: " + fEffectiveSelectionStart + "/" + fEffectiveSelectionLength); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Collection/*<ITypeConstraint>*/ allConstraints= getConstraints(cus, new SubProgressMonitor(pm, 50));
-
- IProgressMonitor subMonitor= new SubProgressMonitor(pm, 50);
- subMonitor.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, allConstraints.size());
- for (Iterator it= allConstraints.iterator(); it.hasNext(); ) {
- subMonitor.worked(1);
- ITypeConstraint tc= (ITypeConstraint)it.next();
- if (! (tc instanceof SimpleTypeConstraint))
- continue;
- SimpleTypeConstraint stc= (SimpleTypeConstraint) tc;
- if (matchesSelection(stc.getLeft()))
- return stc.getLeft();
- if (matchesSelection(stc.getRight()))
- return stc.getRight();
- }
- subMonitor.done();
- pm.done();
- Assert.isTrue(false, RefactoringCoreMessages.ChangeTypeRefactoring_noMatchingConstraintVariable);
- return null;
- }
-
- /**
- * Determine if a given ConstraintVariable matches the selected ASTNode.
- */
- private boolean matchesSelection(ConstraintVariable cv){
- if (cv instanceof ExpressionVariable){
- ExpressionVariable ev= (ExpressionVariable)cv;
- return (fSelectionBinding != null && Bindings.equals(fSelectionBinding, ev.getExpressionBinding()));
- } else if (cv instanceof ParameterTypeVariable){
- ParameterTypeVariable ptv = (ParameterTypeVariable)cv;
- if (fMethodBinding != null && Bindings.equals(ptv.getMethodBinding(), fMethodBinding) &&
- ptv.getParameterIndex() == fParamIndex){
- return true;
- }
- } else if (cv instanceof ReturnTypeVariable){
- ReturnTypeVariable rtv = (ReturnTypeVariable)cv;
- if (fMethodBinding != null && Bindings.equals(rtv.getMethodBinding(), fMethodBinding) &&
- fParamIndex == -1){
- return true;
- }
- }
- return false;
- }
-
- /**
- * Determine the set of constraint variables related to the selected
- * expression. In addition to the expression itself, this consists of
- * any expression that is defines-equal to it, and any expression equal
- * to it.
- */
- private Collection/*<ConstraintVariable>*/ findRelevantConstraintVars(ConstraintVariable cv, IProgressMonitor pm) throws CoreException {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, 150);
- Collection/*<ConstraintVariable>*/ result= new HashSet();
- result.add(cv);
- IJavaScriptUnit[] cus= collectAffectedUnits(new SubProgressMonitor(pm, 50));
- Collection/*<ITypeConstraint>*/ allConstraints= getConstraints(cus, new SubProgressMonitor(pm, 50));
-
- List/*<ConstraintVariable>*/ workList= new ArrayList(result);
- while(! workList.isEmpty()){
-
- pm.worked(10);
-
- ConstraintVariable first= (ConstraintVariable)workList.remove(0);
- for (Iterator iter= allConstraints.iterator(); iter.hasNext();) {
- pm.worked(1);
- ITypeConstraint typeConstraint= (ITypeConstraint) iter.next();
- if (! typeConstraint.isSimpleTypeConstraint())
- continue;
- SimpleTypeConstraint stc= (SimpleTypeConstraint)typeConstraint;
- if (! stc.isDefinesConstraint() && ! stc.isEqualsConstraint())
- continue;
- ConstraintVariable match= match(first, stc.getLeft(), stc.getRight());
- if (match instanceof ExpressionVariable
- || match instanceof ParameterTypeVariable
- || match instanceof ReturnTypeVariable){
- if (! result.contains(match)){
- workList.add(match);
- result.add(match);
- }
- }
- }
- }
-
- pm.done();
-
- return result;
- }
- private static ConstraintVariable match(ConstraintVariable matchee, ConstraintVariable left, ConstraintVariable right) {
- if (matchee.equals(left))
- return right;
- if (matchee.equals(right))
- return left;
- return null;
- }
-
- /**
- * Select the type constraints that involve the selected ASTNode.
- */
- private Collection/*<ITypeConstraint>*/ findRelevantConstraints(Collection/*<ConstraintVariable>*/ relevantConstraintVars,
- IProgressMonitor pm) throws CoreException {
-
- IJavaScriptUnit[] cus= collectAffectedUnits(new SubProgressMonitor(pm, 100));
-
- fAllConstraints= getConstraints(cus, new SubProgressMonitor(pm, 900));
-
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, 1000 + fAllConstraints.size());
-
-
- if (DEBUG) printCollection("type constraints: ", fAllConstraints); //$NON-NLS-1$
- Collection/*<ITypeConstraint>*/ result= new ArrayList();
- for (Iterator it= fAllConstraints.iterator(); it.hasNext(); ) {
- ITypeConstraint tc= (ITypeConstraint)it.next();
- if (tc.isSimpleTypeConstraint()) {
- SimpleTypeConstraint stc= (SimpleTypeConstraint) tc;
- if (stc.isDefinesConstraint() || stc.isEqualsConstraint())
- continue;
- if (stc.getLeft().equals(stc.getRight()))
- continue;
- if (isNull(stc.getLeft()))
- continue;
- if (relevantConstraintVars.contains(stc.getLeft()) || relevantConstraintVars.contains(stc.getRight()))
- result.add(tc);
- } else {
- CompositeOrTypeConstraint cotc= (CompositeOrTypeConstraint) tc;
- ITypeConstraint[] components= cotc.getConstraints();
- for (int i= 0; i < components.length; i++) {
- ITypeConstraint component= components[i];
- SimpleTypeConstraint simpleComponent= (SimpleTypeConstraint) component;
- if (relevantConstraintVars.contains(simpleComponent.getLeft()))
- result.add(tc);
- }
- }
- pm.worked(1);
- }
- if (DEBUG)
- printCollection("selected constraints: ", result); //$NON-NLS-1$
- pm.done();
- return result;
- }
-
- /**
- * Finds the declaration of the ASTNode in a given AST at a specified offset and with a specified length
- */
- private static ASTNode findDeclaration(final ASTNode root, final int start, final int length){
- ASTNode node= NodeFinder.perform(root, start, length);
- Assert.isTrue(node instanceof SimpleName, String.valueOf(node.getNodeType()));
- Assert.isTrue(root instanceof JavaScriptUnit, String.valueOf(root.getNodeType()));
- return ((JavaScriptUnit)root).findDeclaringNode(((SimpleName)node).resolveBinding());
- }
-
- // For debugging
- static String print(Collection/*<ITypeBinding>*/ types){
- if (types.isEmpty())
- return "{ }"; //$NON-NLS-1$
- String result = "{ "; //$NON-NLS-1$
- for (Iterator it=types.iterator(); it.hasNext(); ){
- ITypeBinding type= (ITypeBinding)it.next();
- result += type.getQualifiedName();
- if (it.hasNext()){
- result += ", "; //$NON-NLS-1$
- } else {
- result += " }"; //$NON-NLS-1$
- }
- }
- return result;
- }
-
-
- /**
- * Determines the set of types for which a set of type constraints is satisfied.
- */
- private Collection/*<ITypeBinding>*/ computeValidTypes(ITypeBinding originalType,
- Collection/*<ConstraintVariable>*/ relevantVars,
- Collection/*<ITypeConstraint>*/ relevantConstraints,
- IProgressMonitor pm) throws JavaScriptModelException {
-
- Collection/*<ITypeBinding>*/ result= new HashSet();
- IJavaScriptProject project= fCu.getJavaScriptProject();
-
- Collection/*<ITypeBinding>*/ allTypes = new HashSet/*<IType>*/();
- allTypes.addAll(getAllSuperTypes(originalType));
-
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, allTypes.size());
-
- for (Iterator/*<ITypeBinding>*/ it= allTypes.iterator(); it.hasNext(); ) {
- ITypeBinding type= (ITypeBinding)it.next();
- if (isValid(project, type, relevantVars, relevantConstraints, new SubProgressMonitor(pm, 1))) {
- result.add(type);
- }
- }
- // "changing" to the original type is a no-op
- result.remove(originalType);
-
- // TODO: remove all types that are not visible --- need to check visibility in the CUs for
- // all relevant constraint variables
-
- pm.done();
-
- return result;
- }
-
- /**
- * Determines if a given type satisfies a set of type constraints.
- */
- private boolean isValid(IJavaScriptProject project,
- ITypeBinding type,
- Collection/*<ConstraintVariable>*/ relevantVars,
- Collection/*<ITypeConstraint>*/ constraints,
- IProgressMonitor pm) throws JavaScriptModelException {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, constraints.size());
- for (Iterator it= constraints.iterator(); it.hasNext(); ) {
- ITypeConstraint tc= (ITypeConstraint)it.next();
- if (tc instanceof SimpleTypeConstraint) {
- if (!(isValidSimpleConstraint(project, type, relevantVars, (SimpleTypeConstraint) tc)))
- return false;
- } else if (tc instanceof CompositeOrTypeConstraint) {
- if (!(isValidOrConstraint(project, type, relevantVars, (CompositeOrTypeConstraint) tc)))
- return false;
- }
- pm.worked(1);
- }
- pm.done();
- return true;
- }
-
- private boolean isValidSimpleConstraint(IJavaScriptProject project, ITypeBinding type,
- Collection/*<ConstraintVariable>*/ relevantVars,
- SimpleTypeConstraint stc) throws JavaScriptModelException{
- if (relevantVars.contains(stc.getLeft())) { // upper bound
- if (!isSubTypeOf(type, findType(stc.getRight()))) {
- return false;
- }
- }
- return true;
- }
-
- private boolean isValidOrConstraint(IJavaScriptProject project, ITypeBinding type,
- Collection/*<ConstraintVariable>*/ relevantVars,
- CompositeOrTypeConstraint cotc) throws JavaScriptModelException{
- ITypeConstraint[] components= cotc.getConstraints();
- for (int i= 0; i < components.length; i++) {
- if (components[i] instanceof SimpleTypeConstraint) {
- SimpleTypeConstraint sc= (SimpleTypeConstraint) components[i];
- if (relevantVars.contains(sc.getLeft())) { // upper bound
- if (isSubTypeOf(type, findType(sc.getRight())))
- return true;
- } else if (relevantVars.contains(sc.getRight())) { // lower bound
- if (isSubTypeOf(findType(sc.getLeft()), type))
- return true;
- }
- }
- }
- return false;
- }
-
-
- private ITypeBinding findType(ConstraintVariable cv) {
- return cv.getBinding();
- }
-
- /**
- * Gather constraints associated with a set of compilation units.
- */
- private Collection/*<ITypeConstraint>*/ getConstraints(IJavaScriptUnit[] referringCus, IProgressMonitor pm) {
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, referringCus.length);
- Collection/*<ITypeConstraint>*/ result= new ArrayList();
- for (int i= 0; i < referringCus.length; i++) {
- result.addAll(getConstraints(referringCus[i]));
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- pm.done();
- return result;
- }
-
- private List/*<ITypeConstraint>*/ getConstraints(IJavaScriptUnit unit) {
- if (fConstraintCache.containsKey(unit))
- return (List) fConstraintCache.get(unit);
-
- JavaScriptUnit cu= ASTCreator.createAST(unit, null);
-
- // only generate type constraints for relevant FunctionDeclaration subtrees
- if (fMethodBinding != null && fCuToSearchResultGroup.containsKey(unit)){
- SearchResultGroup group= (SearchResultGroup) fCuToSearchResultGroup.get(unit);
- ASTNode[] nodes= ASTNodeSearchUtil.getAstNodes(group.getSearchResults(), cu);
- for (int i=0; i < nodes.length; i++){
- ASTNode node = nodes[i];
- if (fMethodBinding != null){
- // find FunctionDeclaration above it in the tree
- ASTNode n= node;
- while (!(n instanceof FunctionDeclaration)){
- n = n.getParent();
- }
- FunctionDeclaration md = (FunctionDeclaration)n;
- md.accept(fCollector);
- }
- }
- } else {
- cu.accept(fCollector);
- }
- List/*<ITypeConstraint>*/ constraints= Arrays.asList(fCollector.getConstraints());
- fConstraintCache.put(unit, constraints);
- return constraints;
- }
-
- /**
- * update a JavaScriptUnit's imports after changing the type of declarations
- */
- private String updateImports(JavaScriptUnit astRoot, MultiTextEdit rootEdit) throws CoreException{
- ImportRewrite rewrite= StubUtility.createImportRewrite(astRoot, true);
- String typeName= rewrite.addImport(fSelectedType.getQualifiedName());
- rootEdit.addChild(rewrite.rewriteImports(null));
- return typeName;
- }
-
- // ------------------------------------------------------------------------------------------------- //
- // Miscellaneous helper methods
-
- /**
- * Returns the Collection<IType> of types that can be given to the selected declaration.
- */
- public Collection/*<IType>*/ getValidTypes() {
- return fValidTypes;
- }
-
- public ITypeBinding getOriginalType(){
- return fSelectionTypeBinding;
- }
-
- private void setOriginalType(ITypeBinding originalType){
- fSelectionTypeBinding= originalType;
- fSelectedType= findSuperTypeByName(originalType, fSelectedTypeName);
- }
-
- public String getTarget() {
- String typeName= fSelectionTypeBinding == null ? "" : fSelectionTypeBinding.getName() + " "; //$NON-NLS-1$//$NON-NLS-2$
- if (fFieldBinding != null) {
- return typeName + fFieldBinding.getName();
- } else if (fMethodBinding != null) {
- if (fParamIndex == -1) {
- return typeName + fMethodBinding.getName() + "(...)"; //$NON-NLS-1$
- } else {
- return typeName + fParamName;
- }
- } else if (fSelectionBinding != null) {
- return typeName + fSelectionBinding.getName();
- } else {
- return typeName;
- }
- }
-
- /**
- * Returns the Collection<String> of names of types that can be given to the selected declaration.
- * (used in tests only)
- */
- public Collection/*<String>*/ getValidTypeNames() {
- Collection/*<String>*/ typeNames= new ArrayList();
- for (Iterator it= fValidTypes.iterator(); it.hasNext();) {
- ITypeBinding type= (ITypeBinding) it.next();
- typeNames.add(type.getQualifiedName());
- }
-
- return typeNames;
- }
-
- /**
- * Find the ASTNode for the given source text selection, if it is a type
- * declaration, or null otherwise.
- * @param unit The compilation unit in which the selection was made
- * @param offset
- * @param length
- * @return ASTNode
- */
- private ASTNode getTargetNode(IJavaScriptUnit unit, int offset, int length) {
- JavaScriptUnit root= ASTCreator.createAST(unit, null);
- ASTNode node= NodeFinder.perform(root, offset, length);
- return node;
- }
-
- /**
- * Determines the set of compilation units that may give rise to type constraints that
- * we are interested in. This involves searching for overriding/overridden methods,
- * method calls, field accesses.
- */
- private IJavaScriptUnit[] collectAffectedUnits(IProgressMonitor pm) throws CoreException {
- // BUG: currently, no type constraints are generated for methods that are related
- // but that do not override each other. As a result, we may miss certain relevant
- // variables
-
- pm.beginTask(RefactoringCoreMessages.ChangeTypeRefactoring_analyzingMessage, 100);
-
- if (fAffectedUnits != null) {
- if (DEBUG) printCollection("affected units: ", Arrays.asList(fAffectedUnits)); //$NON-NLS-1$
- pm.worked(100);
- return fAffectedUnits;
- }
- if (fMethodBinding != null) {
- if (fMethodBinding != null) {
-
-
- IFunction selectedMethod= (IFunction) fMethodBinding.getJavaElement();
- if (selectedMethod == null) {
- // can't happen since we checked it up front in check initial conditions
- Assert.isTrue(false, RefactoringCoreMessages.ChangeTypeRefactoring_no_method);
- }
-
- // the following code fragment appears to be the source of a memory leak, when
- // GT is repeatedly applied
-
- IFunction root= selectedMethod;
-
- // end code fragment
-
- IFunction[] rippleMethods= RippleMethodFinder2.getRelatedMethods(
- root, new SubProgressMonitor(pm, 15), null);
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(
- rippleMethods, IJavaScriptSearchConstants.ALL_OCCURRENCES);
-
- // To compute the scope we have to use the selected method. Otherwise we
- // might start from the wrong project.
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(selectedMethod);
- CollectingSearchRequestor csr= new CollectingSearchRequestor();
-
- SearchResultGroup[] groups= RefactoringSearchEngine.search(
- pattern,
- null,
- scope,
- csr,
- new SubProgressMonitor(pm, 80),
- new RefactoringStatus()); //TODO: deal with errors from non-CU matches
-
- fAffectedUnits= getCus(groups);
- }
- } else if (fFieldBinding != null) {
- IField iField= (IField) fFieldBinding.getJavaElement();
- if (iField == null) {
- // can't happen since we checked it up front in check initial conditions
- Assert.isTrue(false, RefactoringCoreMessages.ChangeTypeRefactoring_no_filed);
- }
- SearchPattern pattern= SearchPattern.createPattern(
- iField, IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(iField);
- CollectingSearchRequestor csr= new CollectingSearchRequestor();
- SearchResultGroup[] groups=
- RefactoringSearchEngine.search(pattern, null, scope, csr, new SubProgressMonitor(pm, 100),
- new RefactoringStatus()); //TODO: deal with errors from non-CU matches
- fAffectedUnits= getCus(groups);
- } else {
- // otherwise, selection was a local variable and we only have to search the CU
- // containing the selection
- fAffectedUnits= new IJavaScriptUnit[] { fCu };
- }
- if (DEBUG) {
- System.out.println("Determining affected CUs:"); //$NON-NLS-1$
- for (int i= 0; i < fAffectedUnits.length; i++) {
- System.out.println(" affected CU: " + fAffectedUnits[i].getElementName()); //$NON-NLS-1$
- }
- }
- pm.done();
- return fAffectedUnits;
- }
-
- public void setSelectedType(ITypeBinding type){
- fSelectedType= type;
- }
-
- // -------------------------------------------------------------------------------------------- //
- // TODO The following utility methods should probably be moved to another class
-
- /**
- * Determines if a constraint variable corresponds to the constant "null".
- */
- private static boolean isNull(ConstraintVariable cv) {
- return cv instanceof ExpressionVariable && ((ExpressionVariable)cv).getExpressionType() == ASTNode.NULL_LITERAL;
- }
-
-
- /**
- * For debugging.
- */
- void printCollection(String title, Collection/*<Object>*/ l) {
- System.out.println(l.size() + " " + title); //$NON-NLS-1$
- for (Iterator it= l.iterator(); it.hasNext();) {
- System.out.println(" " + it.next()); //$NON-NLS-1$
- }
- }
-
- /**
- * Returns the compilation units that contain the search results.
- */
- private IJavaScriptUnit[] getCus(SearchResultGroup[] groups) {
- List result= new ArrayList(groups.length);
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu != null) {
- result.add(cu);
- fCuToSearchResultGroup.put(cu, group);
- }
- }
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- /**
- * This always includes the type itself. It will include type
- * Object for any type other than Object
- */
- public Set/*<ITypeBinding>*/ getAllSuperTypes(ITypeBinding type){
- Set/*<ITypeBinding>*/ result= new HashSet();
- result.add(type);
- if (type.getSuperclass() != null){
- result.addAll(getAllSuperTypes(type.getSuperclass()));
- }
- if ((type != fObject) && !contains(result, fObject)){
- result.add(fObject);
- }
- return result;
- }
-
- private ITypeBinding findSuperTypeByName(ITypeBinding type, String superTypeName){
- Set/*<ITypeBinding>*/ superTypes= getAllSuperTypes(type);
- for (Iterator/*<ITypeBinding>*/ it= superTypes.iterator(); it.hasNext(); ){
- ITypeBinding sup= (ITypeBinding)it.next();
- if (sup.getQualifiedName().equals(superTypeName)){
- return sup;
- }
- }
- return null;
- }
-
- public boolean isSubTypeOf(ITypeBinding type1, ITypeBinding type2){
-
- Set superTypes= getAllSuperTypes(type1);
- return contains(superTypes, type2);
- }
-
- private static boolean contains(Collection/*<ITypeBinding>*/ c, ITypeBinding binding){
- for (Iterator/*<ITypeBinding>*/ it=c.iterator(); it.hasNext(); ){
- ITypeBinding b = (ITypeBinding)it.next();
- if (Bindings.equals(b, binding)) return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String selection= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_SELECTION);
- if (selection != null) {
- int offset= -1;
- int length= -1;
- final StringTokenizer tokenizer= new StringTokenizer(selection);
- if (tokenizer.hasMoreTokens())
- offset= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (tokenizer.hasMoreTokens())
- length= Integer.valueOf(tokenizer.nextToken()).intValue();
- if (offset >= 0 && length >= 0) {
- fSelectionStart= offset;
- fSelectionLength= length;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION}));
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_SELECTION));
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT)
- return createInputFatalStatus(element, IJavaScriptRefactorings.GENERALIZE_TYPE);
- else
- fCu= (IJavaScriptUnit) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String type= extended.getAttribute(ATTRIBUTE_TYPE);
- if (type != null && !"".equals(type)) //$NON-NLS-1$
- fSelectedTypeName= type;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TYPE));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/CompilationUnitRewrite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/CompilationUnitRewrite.java
deleted file mode 100644
index f7cd9eb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/CompilationUnitRewrite.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * A {@link CompilationUnitRewrite} holds all data structures that are typically
- * required for non-trivial refactorings. All getters are initialized lazily to
- * avoid lengthy processing in
- * {@link org.eclipse.ltk.core.refactoring.Refactoring#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)}.
- * <p>
- * Bindings are resolved by default, but can be disabled with <code>setResolveBindings(false)</code>.
- * </p>
- */
-public class CompilationUnitRewrite {
- //TODO: add RefactoringStatus fStatus;?
- private IJavaScriptUnit fCu;
- private List/*<TextEditGroup>*/ fTextEditGroups= new ArrayList();
-
- private JavaScriptUnit fRoot; // lazily initialized
- private ASTRewrite fRewrite; // lazily initialized
- private ImportRewrite fImportRewrite; // lazily initialized
- private ImportRemover fImportRemover; // lazily initialized
- private boolean fResolveBindings= true;
- private boolean fStatementsRecovery= false;
- private boolean fBindingsRecovery= false;
- private final WorkingCopyOwner fOwner;
- private IDocument fRememberContent= null;
-
-
- public CompilationUnitRewrite(IJavaScriptUnit cu) {
- this(null, cu, null);
- }
-
- public CompilationUnitRewrite(WorkingCopyOwner owner, IJavaScriptUnit cu) {
- this(owner, cu, null);
- }
-
- public CompilationUnitRewrite(IJavaScriptUnit cu, JavaScriptUnit root) {
- this(null, cu, root);
- }
-
- public CompilationUnitRewrite(WorkingCopyOwner owner, IJavaScriptUnit cu, JavaScriptUnit root) {
- fOwner= owner;
- fCu= cu;
- fRoot= root;
- }
-
- public void rememberContent() {
- fRememberContent= new Document();
- }
-
-
- /**
- * Requests that the compiler should provide binding information for the AST
- * nodes it creates. To be effective, this method must be called before any
- * of {@link #getRoot()},{@link #getASTRewrite()},
- * {@link #getImportRemover()}. This method has no effect if the target object
- * has been created with {@link #CompilationUnitRewrite(IJavaScriptUnit, JavaScriptUnit)}.
- * <p>
- * Defaults to <b><code>true</code></b> (do resolve bindings).
- * </p>
- *
- * @param resolve
- * <code>true</code> if bindings are wanted, and
- * <code>false</code> if bindings are not of interest
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#setResolveBindings(boolean)
- * Note: The default value (<code>true</code>) differs from the one of
- * the corresponding method in ASTParser.
- */
- public void setResolveBindings(boolean resolve) {
- fResolveBindings= resolve;
- }
-
- /**
- * Requests that the compiler should perform statements recovery.
- * To be effective, this method must be called before any
- * of {@link #getRoot()},{@link #getASTRewrite()},
- * {@link #getImportRemover()}. This method has no effect if the target object
- * has been created with {@link #CompilationUnitRewrite(IJavaScriptUnit, JavaScriptUnit)}.
- * <p>
- * Defaults to <b><code>false</code></b> (do not perform statements recovery).
- * </p>
- *
- * @param statementsRecovery whether statements recovery should be performed
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#setStatementsRecovery(boolean)
- */
- public void setStatementsRecovery(boolean statementsRecovery) {
- fStatementsRecovery= statementsRecovery;
- }
-
- /**
- * Requests that the compiler should perform bindings recovery.
- * To be effective, this method must be called before any
- * of {@link #getRoot()},{@link #getASTRewrite()},
- * {@link #getImportRemover()}. This method has no effect if the target object
- * has been created with {@link #CompilationUnitRewrite(IJavaScriptUnit, JavaScriptUnit)}.
- * <p>
- * Defaults to <b><code>false</code></b> (do not perform bindings recovery).
- * </p>
- *
- * @param bindingsRecovery whether bindings recovery should be performed
- * @see org.eclipse.wst.jsdt.core.dom.ASTParser#setBindingsRecovery(boolean)
- */
- public void setBindingRecovery(boolean bindingsRecovery) {
- fBindingsRecovery= bindingsRecovery;
- }
-
- public void clearASTRewrite() {
- fRewrite= null;
- fTextEditGroups= new ArrayList();
- }
-
- public void clearImportRewrites() {
- fImportRewrite= null;
- }
-
- public void clearASTAndImportRewrites() {
- clearASTRewrite();
- fImportRewrite= null;
- }
-
- public CategorizedTextEditGroup createCategorizedGroupDescription(String name, GroupCategorySet set) {
- CategorizedTextEditGroup result= new CategorizedTextEditGroup(name, set);
- fTextEditGroups.add(result);
- return result;
- }
-
- public TextEditGroup createGroupDescription(String name) {
- TextEditGroup result= new TextEditGroup(name);
- fTextEditGroups.add(result);
- return result;
- }
-
-
- public CompilationUnitChange createChange() throws CoreException {
- return createChange(true, null);
- }
-
- /**
- * Creates a compilation unit change based on the events recorded by this compilation unit rewrite.
- * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code> otherwise
- * @param monitor the progress monitor or <code>null</code>
- * @return a {@link CompilationUnitChange}, or <code>null</code> for an empty change
- * @throws CoreException when text buffer acquisition or import rewrite text edit creation fails
- * @throws IllegalArgumentException when the AST rewrite encounters problems
- */
- public CompilationUnitChange createChange(boolean generateGroups, IProgressMonitor monitor) throws CoreException {
- return createChange(fCu.getElementName(), generateGroups, monitor);
- }
-
- /**
- * Creates a compilation unit change based on the events recorded by this compilation unit rewrite.
- * @param name the name of the change to create
- * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code> otherwise
- * @param monitor the progress monitor or <code>null</code>
- * @return a {@link CompilationUnitChange}, or <code>null</code> for an empty change
- * @throws CoreException when text buffer acquisition or import rewrite text edit creation fails
- * @throws IllegalArgumentException when the AST rewrite encounters problems
- */
- public CompilationUnitChange createChange(String name, boolean generateGroups, IProgressMonitor monitor) throws CoreException {
- CompilationUnitChange cuChange= new CompilationUnitChange(name, fCu);
- MultiTextEdit multiEdit= new MultiTextEdit();
- cuChange.setEdit(multiEdit);
- return attachChange(cuChange, generateGroups, monitor);
- }
-
-
- /**
- * Attaches the changes of this compilation unit rewrite to the given CU Change. The given
- * change <b>must</b> either have no root edit, or a MultiTextEdit as a root edit.
- * The edits in the given change <b>must not</b> overlap with the changes of
- * this compilation unit.
- *
- * @param cuChange existing CompilationUnitChange with a MultiTextEdit root or no root at all.
- * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code> otherwise
- * @param monitor the progress monitor or <code>null</code>
- * @return a change combining the changes of this rewrite and the given rewrite.
- * @throws CoreException
- */
- public CompilationUnitChange attachChange(CompilationUnitChange cuChange, boolean generateGroups, IProgressMonitor monitor) throws CoreException {
- try {
- boolean needsAstRewrite= fRewrite != null; // TODO: do we need something like ASTRewrite#hasChanges() here?
- boolean needsImportRemoval= fImportRemover != null && fImportRemover.hasRemovedNodes();
- boolean needsImportRewrite= fImportRewrite != null && fImportRewrite.hasRecordedChanges() || needsImportRemoval;
- if (!needsAstRewrite && !needsImportRemoval && !needsImportRewrite)
- return null;
-
- MultiTextEdit multiEdit= (MultiTextEdit) cuChange.getEdit();
- if (multiEdit == null) {
- multiEdit= new MultiTextEdit();
- cuChange.setEdit(multiEdit);
- }
-
- if (needsAstRewrite) {
- TextEdit rewriteEdit;
- if (fRememberContent != null) {
- rewriteEdit= fRewrite.rewriteAST(fRememberContent, fCu.getJavaScriptProject().getOptions(true));
- } else {
- rewriteEdit= fRewrite.rewriteAST();
- }
- if (!isEmptyEdit(rewriteEdit)) {
- multiEdit.addChild(rewriteEdit);
- if (generateGroups) {
- for (Iterator iter= fTextEditGroups.iterator(); iter.hasNext();) {
- TextEditGroup group= (TextEditGroup) iter.next();
- cuChange.addTextEditGroup(group);
- }
- }
- }
- }
- if (needsImportRemoval) {
- fImportRemover.applyRemoves(getImportRewrite());
- }
- if (needsImportRewrite) {
- TextEdit importsEdit= fImportRewrite.rewriteImports(monitor);
- if (!isEmptyEdit(importsEdit)) {
- multiEdit.addChild(importsEdit);
- String importUpdateName= RefactoringCoreMessages.ASTData_update_imports;
- cuChange.addTextEditGroup(new TextEditGroup(importUpdateName, importsEdit));
- }
- } else {
-
- }
- if (isEmptyEdit(multiEdit))
- return null;
- return cuChange;
- } finally {
- if (monitor != null)
- monitor.done();
- }
- }
-
- private static boolean isEmptyEdit(TextEdit edit) {
- return edit.getClass() == MultiTextEdit.class && ! edit.hasChildren();
- }
-
- public IJavaScriptUnit getCu() {
- return fCu;
- }
-
- public JavaScriptUnit getRoot() {
- if (fRoot == null)
- fRoot= new RefactoringASTParser(AST.JLS3).parse(fCu, fOwner, fResolveBindings, fStatementsRecovery, fBindingsRecovery, null);
- return fRoot;
- }
-
- public AST getAST() {
- return getRoot().getAST();
- }
-
- public ASTRewrite getASTRewrite() {
- if (fRewrite == null) {
- fRewrite= ASTRewrite.create(getRoot().getAST());
- if (fRememberContent != null) { // wain until ast rewrite is accessed first
- try {
- fRememberContent.set(fCu.getSource());
- } catch (JavaScriptModelException e) {
- fRememberContent= null;
- }
- }
- }
- return fRewrite;
- }
-
- public ImportRewrite getImportRewrite() {
- if (fImportRewrite == null) {
- // lazily initialized to avoid lengthy processing in checkInitialConditions(..)
- try {
- if (fRoot == null) {
- fImportRewrite= StubUtility.createImportRewrite(fCu, true);
- } else {
- fImportRewrite= StubUtility.createImportRewrite(getRoot(), true);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- throw new IllegalStateException(e.getMessage()); // like ASTParser#createAST(..) does
- }
- }
- return fImportRewrite;
-
- }
-
- public ImportRemover getImportRemover() {
- if (fImportRemover == null) {
- fImportRemover= new ImportRemover(fCu.getJavaScriptProject(), getRoot());
- }
- return fImportRemover;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ConstructorReferenceFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ConstructorReferenceFinder.java
deleted file mode 100644
index 3f24bf8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ConstructorReferenceFinder.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-/**
- * This class is used to find references to constructors.
- */
-class ConstructorReferenceFinder {
- private final IType fType;
- private final IFunction[] fConstructors;
-
- private ConstructorReferenceFinder(IType type) throws JavaScriptModelException{
- fConstructors= JavaElementUtil.getAllConstructors(type);
- fType= type;
- }
-
- private ConstructorReferenceFinder(IFunction constructor){
- fConstructors= new IFunction[]{constructor};
- fType= constructor.getDeclaringType();
- }
-
- public static SearchResultGroup[] getConstructorReferences(IType type, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException{
- return new ConstructorReferenceFinder(type).getConstructorReferences(pm, null, IJavaScriptSearchConstants.REFERENCES, status);
- }
-
- public static SearchResultGroup[] getConstructorReferences(IType type, WorkingCopyOwner owner, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException{
- return new ConstructorReferenceFinder(type).getConstructorReferences(pm, owner, IJavaScriptSearchConstants.REFERENCES, status);
- }
-
- public static SearchResultGroup[] getConstructorOccurrences(IFunction constructor, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException{
- Assert.isTrue(constructor.isConstructor());
- return new ConstructorReferenceFinder(constructor).getConstructorReferences(pm, null, IJavaScriptSearchConstants.ALL_OCCURRENCES, status);
- }
-
- private SearchResultGroup[] getConstructorReferences(IProgressMonitor pm, WorkingCopyOwner owner, int limitTo, RefactoringStatus status) throws JavaScriptModelException{
- IJavaScriptSearchScope scope= createSearchScope();
- SearchPattern pattern= RefactoringSearchEngine.createOrPattern(fConstructors, limitTo);
- if (pattern == null){
- if (fConstructors.length != 0)
- return new SearchResultGroup[0];
- return getImplicitConstructorReferences(pm, owner, status);
- }
- return removeUnrealReferences(RefactoringSearchEngine.search(pattern, owner, scope, pm, status));
- }
-
- //XXX this method is a workaround for jdt core bug 27236
- private SearchResultGroup[] removeUnrealReferences(SearchResultGroup[] groups) {
- List result= new ArrayList(groups.length);
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu == null)
- continue;
- JavaScriptUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(cu, false);
- SearchMatch[] allSearchResults= group.getSearchResults();
- List realConstructorReferences= new ArrayList(Arrays.asList(allSearchResults));
- for (int j= 0; j < allSearchResults.length; j++) {
- SearchMatch searchResult= allSearchResults[j];
- if (! isRealConstructorReferenceNode(ASTNodeSearchUtil.getAstNode(searchResult, cuNode)))
- realConstructorReferences.remove(searchResult);
- }
- if (! realConstructorReferences.isEmpty())
- result.add(new SearchResultGroup(group.getResource(), (SearchMatch[]) realConstructorReferences.toArray(new SearchMatch[realConstructorReferences.size()])));
- }
- return (SearchResultGroup[]) result.toArray(new SearchResultGroup[result.size()]);
- }
-
- //XXX this method is a workaround for jdt core bug 27236
- private boolean isRealConstructorReferenceNode(ASTNode node){
- String typeName= fConstructors[0].getDeclaringType().getElementName();
- if (node.getParent() instanceof AbstractTypeDeclaration
- && ((AbstractTypeDeclaration) node.getParent()).getNameProperty().equals(node.getLocationInParent())) {
- //Example:
- // class A{
- // A(){}
- // }
- // class B extends A {}
- //==> "B" is found as reference to A()
- return false;
- }
- if (node.getParent() instanceof FunctionDeclaration
- && FunctionDeclaration.NAME_PROPERTY.equals(node.getLocationInParent())) {
- FunctionDeclaration md= (FunctionDeclaration)node.getParent();
- if (md.isConstructor() && ! md.getName().getIdentifier().equals(typeName)) {
- //Example:
- // class A{
- // A(){}
- // }
- // class B extends A{
- // B(){}
- // }
- //==> "B" in "B(){}" is found as reference to A()
- return false;
- }
- }
- return true;
- }
-
- private IJavaScriptSearchScope createSearchScope() throws JavaScriptModelException{
- if (fConstructors.length == 0)
- return RefactoringScopeFactory.create(fType);
- return RefactoringScopeFactory.create(getMostVisibleConstructor());
- }
-
- private IFunction getMostVisibleConstructor() throws JavaScriptModelException {
- Assert.isTrue(fConstructors.length > 0);
- IFunction candidate= fConstructors[0];
- int visibility= JdtFlags.getVisibilityCode(fConstructors[0]);
- for (int i= 1; i < fConstructors.length; i++) {
- IFunction constructor= fConstructors[i];
- if (JdtFlags.isHigherVisibility(JdtFlags.getVisibilityCode(constructor), visibility))
- candidate= constructor;
- }
- return candidate;
- }
-
- private SearchResultGroup[] getImplicitConstructorReferences(IProgressMonitor pm, WorkingCopyOwner owner, RefactoringStatus status) throws JavaScriptModelException {
- pm.beginTask("", 2); //$NON-NLS-1$
- List searchMatches= new ArrayList();
- searchMatches.addAll(getImplicitConstructorReferencesFromHierarchy(owner, new SubProgressMonitor(pm, 1)));
- searchMatches.addAll(getImplicitConstructorReferencesInClassCreations(owner, new SubProgressMonitor(pm, 1), status));
- pm.done();
- return RefactoringSearchEngine.groupByCu((SearchMatch[]) searchMatches.toArray(new SearchMatch[searchMatches.size()]), status);
- }
-
- //List of SearchResults
- private List getImplicitConstructorReferencesInClassCreations(WorkingCopyOwner owner, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- //XXX workaround for jdt core bug 23112
- SearchPattern pattern= SearchPattern.createPattern(fType, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- IJavaScriptSearchScope scope= RefactoringScopeFactory.create(fType);
- SearchResultGroup[] refs= RefactoringSearchEngine.search(pattern, owner, scope, pm, status);
- List result= new ArrayList();
- for (int i= 0; i < refs.length; i++) {
- SearchResultGroup group= refs[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu == null)
- continue;
- JavaScriptUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(cu, false);
- SearchMatch[] results= group.getSearchResults();
- for (int j= 0; j < results.length; j++) {
- SearchMatch searchResult= results[j];
- ASTNode node= ASTNodeSearchUtil.getAstNode(searchResult, cuNode);
- if (isImplicitConstructorReferenceNodeInClassCreations(node))
- result.add(searchResult);
- }
- }
- return result;
- }
-
- public static boolean isImplicitConstructorReferenceNodeInClassCreations(ASTNode node) {
- if (node instanceof Type) {
- final ASTNode parent= node.getParent();
- if (parent instanceof ClassInstanceCreation) {
- return (node.equals(((ClassInstanceCreation) parent).getType()));
- }
- }
- return false;
- }
-
- //List of SearchResults
- private List getImplicitConstructorReferencesFromHierarchy(WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException{
- IType[] subTypes= getNonBinarySubtypes(owner, fType, pm);
- List result= new ArrayList(subTypes.length);
- for (int i= 0; i < subTypes.length; i++) {
- result.addAll(getAllSuperConstructorInvocations(subTypes[i]));
- }
- return result;
- }
-
- private static IType[] getNonBinarySubtypes(WorkingCopyOwner owner, IType type, IProgressMonitor monitor) throws JavaScriptModelException{
- ITypeHierarchy hierarchy= null;
- if (owner == null)
- hierarchy= type.newTypeHierarchy(monitor);
- else
- hierarchy= type.newSupertypeHierarchy(owner, monitor);
- IType[] subTypes= hierarchy.getAllSubtypes(type);
- List result= new ArrayList(subTypes.length);
- for (int i= 0; i < subTypes.length; i++) {
- if (! subTypes[i].isBinary()) {
- result.add(subTypes[i]);
- }
- }
- return (IType[]) result.toArray(new IType[result.size()]);
- }
-
- //Collection of SearchResults
- private static Collection getAllSuperConstructorInvocations(IType type) throws JavaScriptModelException {
- IFunction[] constructors= JavaElementUtil.getAllConstructors(type);
- JavaScriptUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(type.getJavaScriptUnit(), false);
- List result= new ArrayList(constructors.length);
- for (int i= 0; i < constructors.length; i++) {
- ASTNode superCall= getSuperConstructorCallNode(constructors[i], cuNode);
- if (superCall != null)
- result.add(createSearchResult(superCall, constructors[i]));
- }
- return result;
- }
-
- private static SearchMatch createSearchResult(ASTNode superCall, IFunction constructor) {
- int start= superCall.getStartPosition();
- int end= ASTNodes.getInclusiveEnd(superCall); //TODO: why inclusive?
- IResource resource= constructor.getResource();
- return new SearchMatch(constructor, SearchMatch.A_ACCURATE, start, end - start,
- SearchEngine.getDefaultSearchParticipant(), resource);
- }
-
- private static SuperConstructorInvocation getSuperConstructorCallNode(IFunction constructor, JavaScriptUnit cuNode) throws JavaScriptModelException {
- Assert.isTrue(constructor.isConstructor());
- FunctionDeclaration constructorNode= ASTNodeSearchUtil.getMethodDeclarationNode(constructor, cuNode);
- Assert.isTrue(constructorNode.isConstructor());
- Block body= constructorNode.getBody();
- Assert.isNotNull(body);
- List statements= body.statements();
- if (! statements.isEmpty() && statements.get(0) instanceof SuperConstructorInvocation)
- return (SuperConstructorInvocation)statements.get(0);
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractInterfaceConstraintsSolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractInterfaceConstraintsSolver.java
deleted file mode 100644
index 690328a7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractInterfaceConstraintsSolver.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsModel;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsSolver;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeSet;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ImmutableTypeVariable2;
-
-/**
- * Type constraint solver to solve the extract interface problem.
- */
-public final class ExtractInterfaceConstraintsSolver extends SuperTypeConstraintsSolver {
-
- /** The extracted type name, without any qualification or type parameters */
- private final String fName;
-
- /**
- * Creates a new extract interface constraints solver.
- *
- * @param model the model to solve
- * @param name the name of the extracted type
- */
- public ExtractInterfaceConstraintsSolver(final SuperTypeConstraintsModel model, final String name) {
- super(model);
- Assert.isNotNull(name);
- fName= name;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsSolver#computeTypeEstimate(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2)
- */
- protected final ITypeSet computeTypeEstimate(final ConstraintVariable2 variable) {
- final TType type= variable.getType();
- if (variable instanceof ImmutableTypeVariable2 || !type.getErasure().equals(fModel.getSubType().getErasure()))
- return SuperTypeSet.createTypeSet(type);
- final TType[] types= type.getInterfaces();
- for (int index= 0; index < types.length; index++) {
- if (types[index].getName().startsWith(fName) && types[index].getErasure().equals(fModel.getSuperType().getErasure()))
- return SuperTypeSet.createTypeSet(type, types[index]);
- }
- return SuperTypeSet.createTypeSet(type);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeProcessor.java
deleted file mode 100644
index e21a2ac1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeProcessor.java
+++ /dev/null
@@ -1,1110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditCopier;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CreateCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MultiStateCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring processor for the extract supertype refactoring.
- *
- *
- */
-public final class ExtractSupertypeProcessor extends PullUpRefactoringProcessor {
-
- /** The extract attribute */
- private static final String ATTRIBUTE_EXTRACT= "extract"; //$NON-NLS-1$
-
- /** The types attribute */
- private static final String ATTRIBUTE_TYPES= "types"; //$NON-NLS-1$
-
- /** The extract supertype group category set */
- private static final GroupCategorySet SET_EXTRACT_SUPERTYPE= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.extractSupertype", //$NON-NLS-1$
- RefactoringCoreMessages.ExtractSupertypeProcessor_category_name, RefactoringCoreMessages.ExtractSupertypeProcessor_category_description));
-
- /**
- * The changes of the working copy layer (element type:
- * &lt;IJavaScriptUnit, TextEditBasedChange&gt;)
- * <p>
- * The compilation units are all primary working copies or normal
- * compilation units.
- * </p>
- */
- private final Map fLayerChanges= new HashMap();
-
- /** The possible extract supertype candidates, or the empty array */
- private IType[] fPossibleCandidates= {};
-
- /** The source of the supertype */
- private String fSuperSource;
-
- /** The name of the extracted type */
- private String fTypeName= ""; //$NON-NLS-1$
-
- /** The types where to extract the supertype */
- private IType[] fTypesToExtract= {};
-
- /**
- * Creates a new extract supertype refactoring processor.
- *
- * @param members
- * the members to extract, or <code>null</code> if invoked by
- * scripting
- * @param settings
- * the code generation settings, or <code>null</code> if
- * invoked by scripting
- */
- public ExtractSupertypeProcessor(final IMember[] members, final CodeGenerationSettings settings) {
- super(members, settings, true);
- if (members != null) {
- final IType declaring= getDeclaringType();
- if (declaring != null)
- fTypesToExtract= new IType[] { declaring};
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected final RefactoringStatus checkDeclaringSuperTypes(final IProgressMonitor monitor) throws JavaScriptModelException {
- return new RefactoringStatus();
- }
-
- protected CompilationUnitRewrite getCompilationUnitRewrite(final Map rewrites, final IJavaScriptUnit unit) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(unit);
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- if (rewrite == null) {
- rewrite= new CompilationUnitRewrite(fOwner, unit);
- rewrite.rememberContent();
- rewrites.put(unit, rewrite);
- }
- return rewrite;
- }
-
- /**
- * Checks whether the compilation unit to be extracted is valid.
- *
- * @return a status describing the outcome of the
- */
- public RefactoringStatus checkExtractedCompilationUnit() {
- final RefactoringStatus status= new RefactoringStatus();
- final IJavaScriptUnit cu= getDeclaringType().getJavaScriptUnit();
- if (fTypeName == null || "".equals(fTypeName)) //$NON-NLS-1$
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.Checks_Choose_name);
- status.merge(Checks.checkTypeName(fTypeName));
- if (status.hasFatalError())
- return status;
- status.merge(Checks.checkCompilationUnitName(JavaModelUtil.getRenamedCUName(cu, fTypeName)));
- if (status.hasFatalError())
- return status;
- status.merge(Checks.checkCompilationUnitNewName(cu, fTypeName));
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractSupertypeProcessor_checking);
- status.merge(checkExtractedCompilationUnit());
- if (status.hasFatalError())
- return status;
- return super.checkFinalConditions(new SubProgressMonitor(monitor, 1), context);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Computes the destination type based on the new name.
- *
- * @param name the new name
- * @return the destination type
- */
- public IType computeExtractedType(final String name) {
- if (name != null && !name.equals("")) {//$NON-NLS-1$
- final IType declaring= getDeclaringType();
- try {
- final IJavaScriptUnit[] units= declaring.getPackageFragment().getJavaScriptUnits(fOwner);
- final String newName= JavaModelUtil.getRenamedCUName(declaring.getJavaScriptUnit(), name);
- IJavaScriptUnit result= null;
- for (int index= 0; index < units.length; index++) {
- if (units[index].getElementName().equals(newName))
- result= units[index];
- }
- if (result != null) {
- final IType type= result.getType(name);
- setDestinationType(type);
- return type;
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- try {
- final Map arguments= new HashMap();
- String project= null;
- final IType declaring= getDeclaringType();
- final IJavaScriptProject javaProject= declaring.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- try {
- if (declaring.isLocal() || declaring.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.ExtractSupertypeProcessor_descriptor_description_short, fTypeName);
- final String header= Messages.format(RefactoringCoreMessages.ExtractSupertypeProcessor_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fCachedDeclaringType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final IType[] types= getTypesToExtract();
- String[] settings= new String[types.length];
- for (int index= 0; index < settings.length; index++)
- settings[index]= JavaScriptElementLabels.getElementLabel(types[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ExtractSupertypeProcessor_subtypes_pattern, settings));
- comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractSupertypeProcessor_refactored_element_pattern, JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- settings= new String[fMembersToMove.length];
- for (int index= 0; index < settings.length; index++)
- settings[index]= JavaScriptElementLabels.getElementLabel(fMembersToMove[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ExtractInterfaceProcessor_extracted_members_pattern, settings));
- addSuperTypeSettings(comment, true);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.EXTRACT_SUPERCLASS, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fTypeName);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(getDeclaringType()));
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplace).toString());
- arguments.put(ATTRIBUTE_INSTANCEOF, Boolean.valueOf(fInstanceOf).toString());
- arguments.put(ATTRIBUTE_STUBS, Boolean.valueOf(fCreateMethodStubs).toString());
- arguments.put(ATTRIBUTE_EXTRACT, new Integer(fMembersToMove.length).toString());
- for (int offset= 0; offset < fMembersToMove.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fMembersToMove[offset]));
- arguments.put(ATTRIBUTE_DELETE, new Integer(fDeletedMethods.length).toString());
- for (int offset= 0; offset < fDeletedMethods.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fMembersToMove.length + 1), descriptor.elementToHandle(fDeletedMethods[offset]));
- arguments.put(ATTRIBUTE_ABSTRACT, new Integer(fAbstractMethods.length).toString());
- for (int offset= 0; offset < fAbstractMethods.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fMembersToMove.length + fDeletedMethods.length + 1), descriptor.elementToHandle(fAbstractMethods[offset]));
- arguments.put(ATTRIBUTE_TYPES, new Integer(fTypesToExtract.length).toString());
- for (int offset= 0; offset < fTypesToExtract.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fMembersToMove.length + fDeletedMethods.length + fAbstractMethods.length + 1), descriptor.elementToHandle(fTypesToExtract[offset]));
- final DynamicValidationRefactoringChange change= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ExtractSupertypeProcessor_extract_supertype, fChangeManager.getAllChanges());
- final IFile file= ResourceUtil.getFile(declaring.getJavaScriptUnit());
- if (fSuperSource != null && fSuperSource.length() > 0)
- change.add(new CreateCompilationUnitChange(declaring.getPackageFragment().getJavaScriptUnit(JavaModelUtil.getRenamedCUName(declaring.getJavaScriptUnit(), fTypeName)), fSuperSource, file.getCharset(false)));
- return change;
- } finally {
- monitor.done();
- clearCaches();
- }
- }
-
- /**
- * Creates the new extracted supertype.
- *
- * @param superType
- * the super type, or <code>null</code> if no super type (ie.
- * <code>java.lang.Object</code>) is available
- * @param monitor
- * the progress monitor
- * @return a status describing the outcome of the operation
- * @throws CoreException
- * if an error occurs
- */
- protected final RefactoringStatus createExtractedSuperType(final IType superType, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(monitor);
- fSuperSource= null;
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 20);
- final IType declaring= getDeclaringType();
- final CompilationUnitRewrite declaringRewrite= new CompilationUnitRewrite(fOwner, declaring.getJavaScriptUnit());
- final AbstractTypeDeclaration declaringDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(declaring, declaringRewrite.getRoot());
- if (declaringDeclaration != null) {
- final String name= JavaModelUtil.getRenamedCUName(declaring.getJavaScriptUnit(), fTypeName);
- final IJavaScriptUnit original= declaring.getPackageFragment().getJavaScriptUnit(name);
- final IJavaScriptUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 10));
- fSuperSource= createSuperTypeSource(copy, superType, declaringDeclaration, status, new SubProgressMonitor(monitor, 10));
- if (fSuperSource != null) {
- copy.getBuffer().setContents(fSuperSource);
- JavaModelUtil.reconcile(copy);
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Creates a working copy for the modified subtype.
- *
- * @param unit
- * the compilation unit
- * @param root
- * the compilation unit node
- * @param subDeclaration
- * the declaration of the subtype to modify
- * @param extractedType
- * the extracted super type
- * @param extractedBinding
- * the binding of the extracted super type
- * @param status
- * the refactoring status
- */
- protected final void createModifiedSubType(final IJavaScriptUnit unit, final JavaScriptUnit root, final IType extractedType, final ITypeBinding extractedBinding, final AbstractTypeDeclaration subDeclaration, final RefactoringStatus status) {
- Assert.isNotNull(unit);
- Assert.isNotNull(subDeclaration);
- Assert.isNotNull(extractedType);
- try {
- final CompilationUnitRewrite rewrite= new CompilationUnitRewrite(fOwner, unit, root);
- createTypeSignature(rewrite, subDeclaration, extractedType, extractedBinding, new NullProgressMonitor());
- final Document document= new Document(unit.getBuffer().getContents());
- final CompilationUnitChange change= rewrite.createChange();
- if (change != null) {
- fLayerChanges.put(unit.getPrimary(), change);
- final TextEdit edit= change.getEdit();
- if (edit != null) {
- final TextEditCopier copier= new TextEditCopier(edit);
- final TextEdit copy= copier.perform();
- copy.apply(document, TextEdit.NONE);
- }
- }
- final IJavaScriptUnit copy= getSharedWorkingCopy(unit, new NullProgressMonitor());
- copy.getBuffer().setContents(document.get());
- JavaModelUtil.reconcile(copy);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- }
- }
-
- /**
- * Creates the necessary constructors for the extracted supertype.
- *
- * @param targetRewrite
- * the target compilation unit rewrite
- * @param superType
- * the super type, or <code>null</code> if no super type (ie.
- * <code>java.lang.Object</code>) is available
- * @param targetDeclaration
- * the type declaration of the target type
- * @param status
- * the refactoring status
- */
- protected final void createNecessaryConstructors(final CompilationUnitRewrite targetRewrite, final IType superType, final AbstractTypeDeclaration targetDeclaration, final RefactoringStatus status) {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(targetDeclaration);
- if (superType != null) {
- final ITypeBinding binding= targetDeclaration.resolveBinding();
- if (binding != null && binding.isClass()) {
- final IFunctionBinding[] bindings= StubUtility2.getVisibleConstructors(binding, true, true);
- int deprecationCount= 0;
- for (int i= 0; i < bindings.length; i++) {
- if (bindings[i].isDeprecated())
- deprecationCount++;
- }
- final ListRewrite rewrite= targetRewrite.getASTRewrite().getListRewrite(targetDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
- if (rewrite != null) {
- boolean createDeprecated= deprecationCount == bindings.length;
- for (int i= 0; i < bindings.length; i++) {
- IFunctionBinding curr= bindings[i];
- if (!curr.isDeprecated() || createDeprecated) {
- FunctionDeclaration stub;
- try {
- stub= StubUtility2.createConstructorStub(targetRewrite.getCu(), targetRewrite.getASTRewrite(), targetRewrite.getImportRewrite(), curr, binding.getName(), Modifier.PUBLIC, false, false, fSettings);
- if (stub != null)
- rewrite.insertLast(stub, null);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * Creates the source for the new compilation unit containing the supertype.
- *
- * @param extractedWorkingCopy
- * the working copy of the new extracted supertype
- * @param superType
- * the super type, or <code>null</code> if no super type (ie.
- * <code>java.lang.Object</code>) is available
- * @param declaringDeclaration
- * the declaration of the declaring type
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to display progress
- * @return the source of the new compilation unit, or <code>null</code>
- * @throws CoreException
- * if an error occurs
- */
- protected final String createSuperTypeSource(final IJavaScriptUnit extractedWorkingCopy, final IType superType, final AbstractTypeDeclaration declaringDeclaration, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(extractedWorkingCopy);
- Assert.isNotNull(declaringDeclaration);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- String source= null;
- try {
- monitor.beginTask("", 2); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing);
- final IType declaring= getDeclaringType();
- final String delimiter= StubUtility.getLineDelimiterUsed(extractedWorkingCopy.getJavaScriptProject());
- String typeComment= null;
- String fileComment= null;
- if (fSettings.createComments) {
- typeComment= CodeGeneration.getTypeComment(extractedWorkingCopy, fTypeName, delimiter);
- fileComment= CodeGeneration.getFileComment(extractedWorkingCopy, delimiter);
- }
- final StringBuffer buffer= new StringBuffer(64);
- final ITypeBinding binding= declaringDeclaration.resolveBinding();
- if (binding != null) {
- final ITypeBinding superBinding= binding.getSuperclass();
- if (superBinding != null)
- fTypeBindings.add(superBinding);
- }
- final String imports= createTypeImports(extractedWorkingCopy, monitor);
- if (imports != null && !"".equals(imports)) { //$NON-NLS-1$
- buffer.append(imports);
- }
- createTypeDeclaration(extractedWorkingCopy, superType, declaringDeclaration, typeComment, buffer, status, new SubProgressMonitor(monitor, 1));
- source= createTypeTemplate(extractedWorkingCopy, "", fileComment, "", buffer.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- if (source == null) {
- if (!declaring.getPackageFragment().isDefaultPackage()) {
- if (imports.length() > 0)
- buffer.insert(0, imports);
- buffer.insert(0, "package " + declaring.getPackageFragment().getElementName() + ";"); //$NON-NLS-1$//$NON-NLS-2$
- }
- source= buffer.toString();
- }
- final IDocument document= new Document(source);
- final TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, source, 0, delimiter, extractedWorkingCopy.getJavaScriptProject().getOptions(true));
- if (edit != null) {
- try {
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- }
- source= document.get();
- }
- } finally {
- monitor.done();
- }
- return source;
- }
-
- /**
- * Creates the declaration of the new supertype, excluding any comments or
- * package declaration.
- *
- * @param extractedWorkingCopy
- * the working copy of the new extracted supertype
- * @param superType
- * the super type, or <code>null</code> if no super type (ie.
- * <code>java.lang.Object</code>) is available
- * @param declaringDeclaration
- * the declaration of the declaring type
- * @param comment
- * the comment of the new type declaration
- * @param buffer
- * the string buffer containing the declaration
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs
- */
- protected final void createTypeDeclaration(final IJavaScriptUnit extractedWorkingCopy, final IType superType, final AbstractTypeDeclaration declaringDeclaration, final String comment, final StringBuffer buffer, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(extractedWorkingCopy);
- Assert.isNotNull(declaringDeclaration);
- Assert.isNotNull(buffer);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing);
- final IJavaScriptProject project= extractedWorkingCopy.getJavaScriptProject();
- final String delimiter= StubUtility.getLineDelimiterUsed(project);
- if (comment != null && !"".equals(comment)) { //$NON-NLS-1$
- buffer.append(comment);
- buffer.append(delimiter);
- }
- buffer.append(JdtFlags.VISIBILITY_STRING_PUBLIC);
- if (superType != null && Flags.isAbstract(superType.getFlags())) {
- buffer.append(' ');
- buffer.append("abstract "); //$NON-NLS-1$
- }
- buffer.append(' ');
- buffer.append("class "); //$NON-NLS-1$
- buffer.append(fTypeName);
- if (superType != null && !"java.lang.Object".equals(superType.getFullyQualifiedName())) { //$NON-NLS-1$
- buffer.append(' ');
- buffer.append("extends "); //$NON-NLS-1$
- buffer.append(superType.getElementName());
- }
- buffer.append(" {"); //$NON-NLS-1$
- buffer.append(delimiter);
- buffer.append(delimiter);
- buffer.append('}');
- final String string= buffer.toString();
- extractedWorkingCopy.getBuffer().setContents(string);
- final IDocument document= new Document(string);
- final CompilationUnitRewrite targetRewrite= new CompilationUnitRewrite(fOwner, extractedWorkingCopy);
- final AbstractTypeDeclaration targetDeclaration= (AbstractTypeDeclaration) targetRewrite.getRoot().types().get(0);
- createTypeSignature(targetRewrite, superType, declaringDeclaration, targetDeclaration);
- createNecessaryConstructors(targetRewrite, superType, targetDeclaration, status);
- final TextEdit edit= targetRewrite.createChange().getEdit();
- try {
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- }
- buffer.setLength(0);
- buffer.append(document.get());
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates a new type signature of a subtype.
- *
- * @param subRewrite
- * the compilation unit rewrite of a subtype
- * @param declaration
- * the type declaration of a subtype
- * @param extractedType
- * the extracted super type
- * @param extractedBinding
- * the binding of the extracted super type
- * @param monitor
- * the progress monitor to use
- * @throws JavaScriptModelException
- * if the type parameters cannot be retrieved
- */
- protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(subRewrite);
- Assert.isNotNull(declaration);
- Assert.isNotNull(extractedType);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10);
- final AST ast= subRewrite.getAST();
- Type type= null;
- if (extractedBinding != null) {
- type= subRewrite.getImportRewrite().addImport(extractedBinding, ast);
- } else {
- subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.'));
- type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName()));
- }
- subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.'));
- final ASTRewrite rewriter= subRewrite.getASTRewrite();
- if (type != null && declaration instanceof TypeDeclaration) {
- final TypeDeclaration extended= (TypeDeclaration) declaration;
- final Type superClass= extended.getSuperclassType();
- if (superClass != null) {
- rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
- subRewrite.getImportRemover().registerRemovedNode(superClass);
- } else
- rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the type signature of the extracted supertype.
- *
- * @param targetRewrite
- * the target compilation unit rewrite
- * @param superType
- * the super type, or <code>null</code> if no super type (ie.
- * <code>java.lang.Object</code>) is available
- * @param declaringDeclaration
- * the declaration of the declaring type
- * @param targetDeclaration
- * the type declaration of the target type
- */
- protected final void createTypeSignature(final CompilationUnitRewrite targetRewrite, final IType superType, final AbstractTypeDeclaration declaringDeclaration, final AbstractTypeDeclaration targetDeclaration) {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(declaringDeclaration);
- Assert.isNotNull(targetDeclaration);
- if (declaringDeclaration instanceof TypeDeclaration) {
- final TypeDeclaration declaration= (TypeDeclaration) declaringDeclaration;
- final Type superclassType= declaration.getSuperclassType();
- if (superclassType != null) {
- Type type= null;
- final ITypeBinding binding= superclassType.resolveBinding();
- if (binding != null) {
- type= targetRewrite.getImportRewrite().addImport(binding, targetRewrite.getAST());
- targetRewrite.getImportRemover().registerAddedImports(type);
- }
- if (type != null && targetDeclaration instanceof TypeDeclaration) {
- final TypeDeclaration extended= (TypeDeclaration) targetDeclaration;
- final Type targetSuperType= extended.getSuperclassType();
- if (targetSuperType != null) {
- targetRewrite.getASTRewrite().replace(targetSuperType, type, null);
- } else {
- targetRewrite.getASTRewrite().set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, null);
- }
- }
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus createWorkingCopyLayer(final IProgressMonitor monitor) {
- Assert.isNotNull(monitor);
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 70);
- status.merge(super.createWorkingCopyLayer(new SubProgressMonitor(monitor, 10)));
- final IType declaring= getDeclaringType();
- status.merge(createExtractedSuperType(getDeclaringSuperTypeHierarchy(new SubProgressMonitor(monitor, 10)).getSuperclass(declaring), new SubProgressMonitor(monitor, 10)));
- if (status.hasFatalError())
- return status;
- final IType extractedType= computeExtractedType(fTypeName);
- setDestinationType(extractedType);
- final List subTypes= new ArrayList(Arrays.asList(fTypesToExtract));
- if (!subTypes.contains(declaring))
- subTypes.add(declaring);
- final Map unitToTypes= new HashMap(subTypes.size());
- final Set units= new HashSet(subTypes.size());
- for (int index= 0; index < subTypes.size(); index++) {
- final IType type= (IType) subTypes.get(index);
- final IJavaScriptUnit unit= type.getJavaScriptUnit();
- units.add(unit);
- Collection collection= (Collection) unitToTypes.get(unit);
- if (collection == null) {
- collection= new ArrayList(2);
- unitToTypes.put(unit, collection);
- }
- collection.add(type);
- }
- final Map projectToUnits= new HashMap();
- Collection collection= null;
- IJavaScriptProject project= null;
- IJavaScriptUnit current= null;
- for (final Iterator iterator= units.iterator(); iterator.hasNext();) {
- current= (IJavaScriptUnit) iterator.next();
- project= current.getJavaScriptProject();
- collection= (Collection) projectToUnits.get(project);
- if (collection == null) {
- collection= new ArrayList();
- projectToUnits.put(project, collection);
- }
- collection.add(current);
- }
- final ITypeBinding[] extractBindings= { null};
- final ASTParser extractParser= ASTParser.newParser(AST.JLS3);
- extractParser.setWorkingCopyOwner(fOwner);
- extractParser.setResolveBindings(true);
- extractParser.setProject(project);
- extractParser.setSource(extractedType.getJavaScriptUnit());
- final JavaScriptUnit extractUnit= (JavaScriptUnit) extractParser.createAST(new SubProgressMonitor(monitor, 10));
- if (extractUnit != null) {
- final AbstractTypeDeclaration extractDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(extractedType, extractUnit);
- if (extractDeclaration != null)
- extractBindings[0]= extractDeclaration.resolveBinding();
- }
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 30);
- try {
- final Set keySet= projectToUnits.keySet();
- subMonitor.beginTask("", keySet.size()); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing);
- for (final Iterator iterator= keySet.iterator(); iterator.hasNext();) {
- project= (IJavaScriptProject) iterator.next();
- collection= (Collection) projectToUnits.get(project);
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 1);
- try {
- subsubMonitor.beginTask("", collection.size()); //$NON-NLS-1$
- subsubMonitor.setTaskName(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing);
- parser.createASTs((IJavaScriptUnit[]) collection.toArray(new IJavaScriptUnit[collection.size()]), new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- try {
- final Collection types= (Collection) unitToTypes.get(unit);
- if (types != null) {
- for (final Iterator innerIterator= types.iterator(); innerIterator.hasNext();) {
- final IType currentType= (IType) innerIterator.next();
- final AbstractTypeDeclaration currentDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(currentType, node);
- if (currentDeclaration != null)
- createModifiedSubType(unit, node, extractedType, extractBindings[0], currentDeclaration, status);
- }
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
- } finally {
- subsubMonitor.worked(1);
- }
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, subsubMonitor);
- } finally {
- subsubMonitor.done();
- }
- }
- } finally {
- subMonitor.done();
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- public IType[] getCandidateTypes(final RefactoringStatus status, final IProgressMonitor monitor) {
- Assert.isNotNull(monitor);
- if (fPossibleCandidates == null || fPossibleCandidates.length == 0) {
- final IType declaring= getDeclaringType();
- if (declaring != null) {
- try {
- monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_computing_possible_types, 10);
- final IType superType= getDeclaringSuperTypeHierarchy(new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).getSuperclass(declaring);
- if (superType != null) {
- fPossibleCandidates= superType.newTypeHierarchy(fOwner, new SubProgressMonitor(monitor, 9, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).getSubclasses(superType);
- final LinkedList list= new LinkedList(Arrays.asList(fPossibleCandidates));
- final Set names= new HashSet();
- for (final Iterator iterator= list.iterator(); iterator.hasNext();) {
- final IType type= (IType) iterator.next();
- if (type.isReadOnly() || type.isBinary() || type.isAnonymous() || !type.isClass() || names.contains(type.getFullyQualifiedName()))
- iterator.remove();
- else
- names.add(type.getFullyQualifiedName());
- }
- fPossibleCandidates= (IType[]) list.toArray(new IType[list.size()]);
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- } finally {
- monitor.done();
- }
- }
- }
- return fPossibleCandidates;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getElements() {
- return new Object[] { getDeclaringType()};
- }
-
- /**
- * Returns the extracted type.
- *
- * @return the extracted type, or <code>null</code>
- */
- public IType getExtractedType() {
- return getDestinationType();
- }
-
- /**
- * Returns the type name.
- *
- * @return the type name
- */
- public String getTypeName() {
- return fTypeName;
- }
-
- /**
- * Returns the types to extract. The declaring type may or may not be
- * contained in the result.
- *
- * @return the types to extract
- */
- public IType[] getTypesToExtract() {
- return fTypesToExtract;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null && !"".equals(name)) //$NON-NLS-1$
- fTypeName= name;
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS);
- IType type= null;
- final IJavaScriptUnit unit= ((IType) element).getJavaScriptUnit();
- if (unit != null && unit.exists()) {
- try {
- final IJavaScriptUnit copy= getSharedWorkingCopy(unit, new NullProgressMonitor());
- final IJavaScriptElement[] elements= copy.findElements(element);
- if (elements != null && elements.length == 1 && elements[0] instanceof IType && elements[0].exists())
- type= (IType) elements[0];
- } catch (JavaScriptModelException exception) {
- // TODO: log exception
- }
- }
- if (type != null)
- fCachedDeclaringType= type;
- else
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String stubs= extended.getAttribute(ATTRIBUTE_STUBS);
- if (stubs != null) {
- fCreateMethodStubs= Boolean.valueOf(stubs).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_STUBS));
- final String instance= extended.getAttribute(ATTRIBUTE_INSTANCEOF);
- if (instance != null) {
- fInstanceOf= Boolean.valueOf(instance).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INSTANCEOF));
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplace= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- int extractCount= 0;
- int abstractCount= 0;
- int deleteCount= 0;
- int typeCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_ABSTRACT);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- abstractCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ABSTRACT));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ABSTRACT));
- value= extended.getAttribute(ATTRIBUTE_DELETE);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- deleteCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE));
- value= extended.getAttribute(ATTRIBUTE_EXTRACT);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- extractCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_EXTRACT));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_EXTRACT));
- value= extended.getAttribute(ATTRIBUTE_TYPES);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- typeCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TYPES));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TYPES));
- final RefactoringStatus status= new RefactoringStatus();
- List elements= new ArrayList();
- for (int index= 0; index < extractCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(fOwner, extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fMembersToMove= (IMember[]) elements.toArray(new IMember[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < deleteCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (extractCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(fOwner, extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fDeletedMethods= (IFunction[]) elements.toArray(new IFunction[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < abstractCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (extractCount + abstractCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(fOwner, extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fAbstractMethods= (IFunction[]) elements.toArray(new IFunction[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < typeCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (extractCount + abstractCount + deleteCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(fOwner, extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.EXTRACT_SUPERCLASS));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fTypesToExtract= (IType[]) elements.toArray(new IType[elements.size()]);
- IJavaScriptProject project= null;
- if (fMembersToMove.length > 0)
- project= fMembersToMove[0].getJavaScriptProject();
- fSettings= JavaPreferencesSettings.getCodeGenerationSettings(project);
- if (!status.isOK())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException {
- try {
- final IJavaScriptUnit extractedUnit= getExtractedType().getJavaScriptUnit();
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- for (final Iterator iterator= fCompilationUnitRewrites.keySet().iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- if (unit.equals(extractedUnit)) {
- rewrite= (CompilationUnitRewrite) fCompilationUnitRewrites.get(unit);
- if (rewrite != null) {
- CompilationUnitChange change= rewrite.createChange();
-
- if (change != null) {
- final TextEdit edit= ((TextChange) change).getEdit();
- if (edit != null) {
- final IDocument document= new Document(fSuperSource);
- try {
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- fSuperSource= document.get();
- manager.remove(extractedUnit);
- }
- }
- }
- } else {
- rewrite= (CompilationUnitRewrite) fCompilationUnitRewrites.get(unit);
- if (rewrite != null) {
- final CompilationUnitChange layerChange= (CompilationUnitChange) fLayerChanges.get(unit.getPrimary());
- final CompilationUnitChange rewriteChange= rewrite.createChange();
- if (rewriteChange != null && layerChange != null) {
- final MultiStateCompilationUnitChange change= new MultiStateCompilationUnitChange(rewriteChange.getName(), unit);
- change.addChange(layerChange);
- change.addChange(rewriteChange);
- fLayerChanges.remove(unit.getPrimary());
- manager.manage(unit, change);
- } else if (layerChange != null) {
- manager.manage(unit, layerChange);
- fLayerChanges.remove(unit.getPrimary());
- } else if (rewriteChange != null) {
- manager.manage(unit, rewriteChange);
- }
- }
- }
- }
- for (Iterator iterator= fLayerChanges.entrySet().iterator(); iterator.hasNext();) {
- final Map.Entry entry= (Map.Entry) iterator.next();
- manager.manage((IJavaScriptUnit) entry.getKey(), (TextEditBasedChange) entry.getValue());
- }
- IJavaScriptUnit[] units= manager.getAllCompilationUnits();
- for (int index= 0; index < units.length; index++) {
- if (units[index].getPath().equals(extractedUnit.getPath()))
- manager.remove(units[index]);
- }
- } finally {
- fLayerChanges.clear();
- }
- }
-
- /**
- * Resets the changes necessary for the working copy layer.
- */
- public void resetChanges() {
- fLayerChanges.clear();
- }
-
- /**
- * Sets the type name.
- *
- * @param name
- * the type name
- */
- public void setTypeName(final String name) {
- Assert.isNotNull(name);
- fTypeName= name;
- }
-
- /**
- * Sets the types to extract. Must be a subset of
- * <code>getPossibleCandidates()</code>. If the declaring type is not
- * contained, it will automatically be added.
- *
- * @param types
- * the types to extract
- */
- public void setTypesToExtract(final IType[] types) {
- Assert.isNotNull(types);
- fTypesToExtract= types;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java
deleted file mode 100644
index 7f9de1dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Refactoring to extract a supertype from a class.
- *
- *
- */
-public final class ExtractSupertypeRefactoring extends PullUpRefactoring {
-
- /**
- * Creates a new extract supertype refactoring.
- *
- * @param processor
- * the extract supertype refactoring processor to use
- */
- public ExtractSupertypeRefactoring(final ExtractSupertypeProcessor processor) {
- super(processor);
- }
-
- /**
- * Returns the extract supertype processor.
- *
- * @return the extract supertype processor.
- */
- public ExtractSupertypeProcessor getExtractSupertypeProcessor() {
- return (ExtractSupertypeProcessor) getProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return RefactoringCoreMessages.ExtractSupertypeProcessor_extract_supertype;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/HierarchyProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/HierarchyProcessor.java
deleted file mode 100644
index 07295fd7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/HierarchyProcessor.java
+++ /dev/null
@@ -1,634 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IExtendedModifier;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsModel;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsSolver;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Partial implementation of a hierarchy refactoring processor used in pull up,
- * push down and extract supertype refactorings.
- * <p>
- * This processor provides common functionality to move members in a type
- * hierarchy, and to perform a "Use Supertype" refactoring afterwards.
- * </p>
- *
- *
- */
-public abstract class HierarchyProcessor extends SuperTypeRefactoringProcessor {
-
- /**
- * AST node visitor which performs the actual mapping.
- */
- public static class TypeVariableMapper extends ASTVisitor {
-
- /** The type variable mapping to use */
- protected final TypeVariableMaplet[] fMapping;
-
- /** The AST rewrite to use */
- protected final ASTRewrite fRewrite;
-
- /**
- * Creates a new type variable mapper.
- *
- * @param rewrite
- * The AST rewrite to use
- * @param mapping
- * The type variable mapping to use
- */
- public TypeVariableMapper(final ASTRewrite rewrite, final TypeVariableMaplet[] mapping) {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(mapping);
- fRewrite= rewrite;
- fMapping= mapping;
- }
-
- public final boolean visit(final SimpleName node) {
- final ITypeBinding binding= node.resolveTypeBinding();
- return true;
- }
- }
-
- protected static boolean areAllFragmentsDeleted(final FieldDeclaration declaration, final List declarationNodes) {
- for (final Iterator iterator= declaration.fragments().iterator(); iterator.hasNext();) {
- if (!declarationNodes.contains(iterator.next()))
- return false;
- }
- return true;
- }
-
- protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite sourceRewriter, IType destination, IMember[] members) {
- RefactoringStatus status= new RefactoringStatus();
- if (!JavaModelUtil.is50OrHigher(destination.getJavaScriptProject())) {
- for (int index= 0; index < members.length; index++) {
- if (members[index] instanceof IFunction) {
- final IFunction method= (IFunction) members[index];
- try {
- if (Flags.isVarargs(method.getFlags()))
- status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.PullUpRefactoring_incompatible_language_constructs1, new String[] { JavaScriptElementLabels.getTextLabel(members[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_DEFAULT)}), JavaStatusContext.create(members[index])));
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- }
- return status;
- }
-
- protected static void copyAnnotations(final FieldDeclaration oldField, final FieldDeclaration newField) {
- final AST ast= newField.getAST();
- for (int index= 0, n= oldField.modifiers().size(); index < n; index++) {
- final IExtendedModifier modifier= (IExtendedModifier) oldField.modifiers().get(index);
- final List modifiers= newField.modifiers();
- }
- }
-
- protected static void copyAnnotations(final FunctionDeclaration oldMethod, final FunctionDeclaration newMethod) {
- final AST ast= newMethod.getAST();
- for (int index= 0, n= oldMethod.modifiers().size(); index < n; index++) {
- final IExtendedModifier modifier= (IExtendedModifier) oldMethod.modifiers().get(index);
- final List modifiers= newMethod.modifiers();
- }
- }
-
- protected static void copyJavadocNode(final ASTRewrite rewrite, final IMember member, final BodyDeclaration oldDeclaration, final BodyDeclaration newDeclaration) throws JavaScriptModelException {
- final JSdoc predecessor= oldDeclaration.getJavadoc();
- if (predecessor != null) {
- final IDocument buffer= new Document(member.getJavaScriptUnit().getBuffer().getContents());
- try {
- final String[] lines= Strings.convertIntoLines(buffer.get(predecessor.getStartPosition(), predecessor.getLength()));
- Strings.trimIndentation(lines, member.getJavaScriptProject(), false);
- final JSdoc successor= (JSdoc) rewrite.createStringPlaceholder(Strings.concatenate(lines, TextUtilities.getDefaultLineDelimiter(buffer)), ASTNode.JSDOC);
- newDeclaration.setJavadoc(successor);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
-
- protected static void copyThrownExceptions(final FunctionDeclaration oldMethod, final FunctionDeclaration newMethod) {
- final AST ast= newMethod.getAST();
- for (int index= 0, n= oldMethod.thrownExceptions().size(); index < n; index++)
- newMethod.thrownExceptions().add(index, ASTNode.copySubtree(ast, (Name) oldMethod.thrownExceptions().get(index)));
- }
-
- protected static String createLabel(final IMember member) {
- if (member instanceof IType)
- return JavaScriptElementLabels.getTextLabel(member, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- else if (member instanceof IFunction)
- return JavaScriptElementLabels.getTextLabel(member, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- else if (member instanceof IField)
- return JavaScriptElementLabels.getTextLabel(member, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- else if (member instanceof IInitializer)
- return RefactoringCoreMessages.HierarchyRefactoring_initializer;
- Assert.isTrue(false);
- return null;
- }
-
- protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final JavaScriptUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaScriptModelException {
- final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
- newFragment.setExtraDimensions(oldFieldFragment.getExtraDimensions());
- if (oldFieldFragment.getInitializer() != null) {
- Expression newInitializer= null;
- if (mapping.length > 0)
- newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getJavaScriptUnit(), mapping, rewrite);
- else
- newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getJavaScriptUnit(), rewrite);
- newFragment.setInitializer(newInitializer);
- }
- newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
- final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
- final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
- copyJavadocNode(rewrite, field, oldField, newField);
- copyAnnotations(oldField, newField);
- newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
- final Type oldType= oldField.getType();
- Type newType= null;
- if (mapping.length > 0) {
- newType= createPlaceholderForType(oldType, field.getJavaScriptUnit(), mapping, rewrite);
- } else
- newType= createPlaceholderForType(oldType, field.getJavaScriptUnit(), rewrite);
- newField.setType(newType);
- return newField;
- }
-
- protected static Expression createPlaceholderForExpression(final Expression expression, final IJavaScriptUnit declaringCu, final ASTRewrite rewrite) throws JavaScriptModelException {
- return (Expression) rewrite.createStringPlaceholder(declaringCu.getBuffer().getText(expression.getStartPosition(), expression.getLength()), ASTNode.FUNCTION_INVOCATION);
- }
-
- protected static Expression createPlaceholderForExpression(final Expression expression, final IJavaScriptUnit declaringCu, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite) throws JavaScriptModelException {
- Expression result= null;
- try {
- final IDocument document= new Document(declaringCu.getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(expression.getAST());
- final ITrackedNodePosition position= rewriter.track(expression);
- expression.accept(new TypeVariableMapper(rewriter, mapping));
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- result= (Expression) rewrite.createStringPlaceholder(document.get(position.getStartPosition(), position.getLength()), ASTNode.FUNCTION_INVOCATION);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return result;
- }
-
- protected static BodyDeclaration createPlaceholderForProtectedTypeDeclaration(final BodyDeclaration bodyDeclaration, final JavaScriptUnit declaringCuNode, final IJavaScriptUnit declaringCu, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaScriptModelException {
- String text= null;
- try {
- final ASTRewrite rewriter= ASTRewrite.create(bodyDeclaration.getAST());
- ModifierRewrite.create(rewriter, bodyDeclaration).setVisibility(Modifier.PROTECTED, null);
- final ITrackedNodePosition position= rewriter.track(bodyDeclaration);
- final IDocument document= new Document(declaringCu.getBuffer().getText(declaringCuNode.getStartPosition(), declaringCuNode.getLength()));
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.UPDATE_REGIONS);
- text= document.get(position.getStartPosition(), position.getLength());
- } catch (BadLocationException exception) {
- text= getNewText(bodyDeclaration, declaringCu, removeIndentation);
- }
- return (BodyDeclaration) rewrite.createStringPlaceholder(text, ASTNode.TYPE_DECLARATION);
- }
-
- protected static BodyDeclaration createPlaceholderForProtectedTypeDeclaration(final BodyDeclaration bodyDeclaration, final JavaScriptUnit declaringCuNode, final IJavaScriptUnit declaringCu, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaScriptModelException {
- BodyDeclaration result= null;
- try {
- final IDocument document= new Document(declaringCu.getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(bodyDeclaration.getAST());
- final ITrackedNodePosition position= rewriter.track(bodyDeclaration);
- bodyDeclaration.accept(new TypeVariableMapper(rewriter, mapping) {
-
-
- public final boolean visit(final TypeDeclaration node) {
- ModifierRewrite.create(fRewrite, bodyDeclaration).setVisibility(Modifier.PROTECTED, null);
- return true;
- }
- });
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- result= (BodyDeclaration) rewrite.createStringPlaceholder(document.get(position.getStartPosition(), position.getLength()), ASTNode.TYPE_DECLARATION);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return result;
- }
-
- protected static SingleVariableDeclaration createPlaceholderForSingleVariableDeclaration(final SingleVariableDeclaration declaration, final IJavaScriptUnit declaringCu, final ASTRewrite rewrite) throws JavaScriptModelException {
- return (SingleVariableDeclaration) rewrite.createStringPlaceholder(declaringCu.getBuffer().getText(declaration.getStartPosition(), declaration.getLength()), ASTNode.SINGLE_VARIABLE_DECLARATION);
- }
-
- protected static SingleVariableDeclaration createPlaceholderForSingleVariableDeclaration(final SingleVariableDeclaration declaration, final IJavaScriptUnit declaringCu, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite) throws JavaScriptModelException {
- SingleVariableDeclaration result= null;
- try {
- final IDocument document= new Document(declaringCu.getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(declaration.getAST());
- final ITrackedNodePosition position= rewriter.track(declaration);
- declaration.accept(new TypeVariableMapper(rewriter, mapping));
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- result= (SingleVariableDeclaration) rewrite.createStringPlaceholder(document.get(position.getStartPosition(), position.getLength()), ASTNode.SINGLE_VARIABLE_DECLARATION);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return result;
- }
-
- protected static Type createPlaceholderForType(final Type type, final IJavaScriptUnit declaringCu, final ASTRewrite rewrite) throws JavaScriptModelException {
- return (Type) rewrite.createStringPlaceholder(declaringCu.getBuffer().getText(type.getStartPosition(), type.getLength()), ASTNode.SIMPLE_TYPE);
- }
-
- protected static Type createPlaceholderForType(final Type type, final IJavaScriptUnit declaringCu, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite) throws JavaScriptModelException {
- Type result= null;
- try {
- final IDocument document= new Document(declaringCu.getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(type.getAST());
- final ITrackedNodePosition position= rewriter.track(type);
- type.accept(new TypeVariableMapper(rewriter, mapping));
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- result= (Type) rewrite.createStringPlaceholder(document.get(position.getStartPosition(), position.getLength()), ASTNode.SIMPLE_TYPE);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return result;
- }
-
- protected static BodyDeclaration createPlaceholderForTypeDeclaration(final BodyDeclaration bodyDeclaration, final IJavaScriptUnit declaringCu, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaScriptModelException {
- return (BodyDeclaration) rewrite.createStringPlaceholder(getNewText(bodyDeclaration, declaringCu, removeIndentation), ASTNode.TYPE_DECLARATION);
- }
-
- protected static BodyDeclaration createPlaceholderForTypeDeclaration(final BodyDeclaration bodyDeclaration, final IJavaScriptUnit declaringCu, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaScriptModelException {
- BodyDeclaration result= null;
- try {
- final IDocument document= new Document(declaringCu.getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(bodyDeclaration.getAST());
- final ITrackedNodePosition position= rewriter.track(bodyDeclaration);
- bodyDeclaration.accept(new TypeVariableMapper(rewriter, mapping));
- rewriter.rewriteAST(document, declaringCu.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- result= (BodyDeclaration) rewrite.createStringPlaceholder(document.get(position.getStartPosition(), position.getLength()), ASTNode.TYPE_DECLARATION);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- return result;
- }
-
- protected static void deleteDeclarationNodes(final CompilationUnitRewrite sourceRewriter, final boolean sameCu, final CompilationUnitRewrite unitRewriter, final List members, final GroupCategorySet set) throws JavaScriptModelException {
- final List declarationNodes= getDeclarationNodes(unitRewriter.getRoot(), members);
- for (final Iterator iterator= declarationNodes.iterator(); iterator.hasNext();) {
- final ASTNode node= (ASTNode) iterator.next();
- final ASTRewrite rewriter= unitRewriter.getASTRewrite();
- final ImportRemover remover= unitRewriter.getImportRemover();
- if (node instanceof VariableDeclarationFragment) {
- if (node.getParent() instanceof FieldDeclaration) {
- final FieldDeclaration declaration= (FieldDeclaration) node.getParent();
- if (areAllFragmentsDeleted(declaration, declarationNodes)) {
- rewriter.remove(declaration, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
- if (!sameCu)
- remover.registerRemovedNode(declaration);
- } else {
- rewriter.remove(node, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
- if (!sameCu)
- remover.registerRemovedNode(node);
- }
- }
- } else {
- rewriter.remove(node, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
- if (!sameCu)
- remover.registerRemovedNode(node);
- }
- }
- }
-
- protected static List getDeclarationNodes(final JavaScriptUnit cuNode, final List members) throws JavaScriptModelException {
- final List result= new ArrayList(members.size());
- for (final Iterator iterator= members.iterator(); iterator.hasNext();) {
- final IMember member= (IMember) iterator.next();
- ASTNode node= null;
- if (member instanceof IField) {
- node= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, cuNode);
- } else if (member instanceof IType)
- node= ASTNodeSearchUtil.getAbstractTypeDeclarationNode((IType) member, cuNode);
- else if (member instanceof IFunction)
- node= ASTNodeSearchUtil.getMethodDeclarationNode((IFunction) member, cuNode);
- if (node != null)
- result.add(node);
- }
- return result;
- }
-
- protected static String getNewText(final ASTNode node, final IJavaScriptUnit declaringCu, final boolean removeIndentation) throws JavaScriptModelException {
- final String result= declaringCu.getBuffer().getText(node.getStartPosition(), node.getLength());
- if (removeIndentation)
- return getUnindentedText(result, declaringCu);
-
- return result;
- }
-
- protected static String getUnindentedText(final String text, final IJavaScriptUnit declaringCu) throws JavaScriptModelException {
- final String[] lines= Strings.convertIntoLines(text);
- Strings.trimIndentation(lines, declaringCu.getJavaScriptProject(), false);
- return Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(declaringCu));
- }
-
- /** The cached declaring type */
- protected IType fCachedDeclaringType;
-
- /** The cached member references */
- protected final Map fCachedMembersReferences= new HashMap(2);
-
- /** The cached type references */
- protected IType[] fCachedReferencedTypes;
-
- /** The text edit based change manager */
- protected TextEditBasedChangeManager fChangeManager;
-
- /** Does the refactoring use a working copy layer? */
- protected final boolean fLayer;
-
- /** The members to move (may be in working copies) */
- protected IMember[] fMembersToMove;
-
- /**
- * Creates a new hierarchy processor.
- *
- * @param members
- * the members, or <code>null</code> if invoked by scripting
- * @param layer
- * <code>true</code> to create a working copy layer,
- * <code>false</code> otherwise
- */
- protected HierarchyProcessor(final IMember[] members, final CodeGenerationSettings settings, boolean layer) {
- super(settings);
- fLayer= layer;
- if (members != null) {
- fMembersToMove= (IMember[]) SourceReferenceUtil.sortByOffset(members);
- if (layer && fMembersToMove.length > 0) {
- final IJavaScriptUnit original= fMembersToMove[0].getJavaScriptUnit();
- if (original != null) {
- try {
- final IJavaScriptUnit copy= getSharedWorkingCopy(original.getPrimary(), new NullProgressMonitor());
- if (copy != null) {
- for (int index= 0; index < fMembersToMove.length; index++) {
- final IJavaScriptElement[] elements= copy.findElements(fMembersToMove[index]);
- if (elements != null && elements.length > 0 && elements[0] instanceof IMember) {
- fMembersToMove[index]= (IMember) elements[0];
- }
- }
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- }
- }
-
- protected boolean canBeAccessedFrom(final IMember member, final IType target, final ITypeHierarchy hierarchy) throws JavaScriptModelException {
- Assert.isTrue(!(member instanceof IInitializer));
- return member.exists();
- }
-
- protected RefactoringStatus checkConstructorCalls(final IType type, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 2);
- final RefactoringStatus result= new RefactoringStatus();
- final SearchResultGroup[] groups= ConstructorReferenceFinder.getConstructorReferences(type, fOwner, new SubProgressMonitor(monitor, 1), result);
- final String message= Messages.format(RefactoringCoreMessages.HierarchyRefactoring_gets_instantiated, new Object[] { JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
-
- IJavaScriptUnit unit= null;
- for (int index= 0; index < groups.length; index++) {
- unit= groups[index].getCompilationUnit();
- if (unit != null) {
- final JavaScriptUnit cuNode= RefactoringASTParser.parseWithASTProvider(unit, false, new SubProgressMonitor(monitor, 1));
- final ASTNode[] references= ASTNodeSearchUtil.getAstNodes(groups[index].getSearchResults(), cuNode);
- ASTNode node= null;
- for (int offset= 0; offset < references.length; offset++) {
- node= references[offset];
- if ((node instanceof ClassInstanceCreation) || ConstructorReferenceFinder.isImplicitConstructorReferenceNodeInClassCreations(node)) {
- final RefactoringStatusContext context= JavaStatusContext.create(unit, node);
- result.addError(message, context);
- }
- }
- }
- }
- return result;
- } finally {
- monitor.done();
- }
- }
-
- protected RefactoringStatus checkDeclaringType(final IProgressMonitor monitor) throws JavaScriptModelException {
- final IType type= getDeclaringType();
- if (type.isBinary())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.HierarchyRefactoring_members_of_binary);
- if (type.isReadOnly())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.HierarchyRefactoring_members_of_read_only);
- return new RefactoringStatus();
- }
-
- protected RefactoringStatus checkIfMembersExist() {
- final RefactoringStatus result= new RefactoringStatus();
- IMember member= null;
- for (int index= 0; index < fMembersToMove.length; index++) {
- member= fMembersToMove[index];
- if (member == null || !member.exists())
- result.addFatalError(RefactoringCoreMessages.HierarchyRefactoring_does_not_exist);
- }
- return result;
- }
-
- protected void clearCaches() {
- fCachedReferencedTypes= null;
- }
-
- protected void copyParameters(final ASTRewrite rewrite, final IJavaScriptUnit unit, final FunctionDeclaration oldMethod, final FunctionDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaScriptModelException {
- SingleVariableDeclaration newDeclaration= null;
- for (int index= 0, size= oldMethod.parameters().size(); index < size; index++) {
- final SingleVariableDeclaration oldDeclaration= (SingleVariableDeclaration) oldMethod.parameters().get(index);
- if (mapping.length > 0)
- newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, mapping, rewrite);
- else
- newDeclaration= createPlaceholderForSingleVariableDeclaration(oldDeclaration, unit, rewrite);
- newMethod.parameters().add(index, newDeclaration);
- }
- }
-
- protected void copyReturnType(final ASTRewrite rewrite, final IJavaScriptUnit unit, final FunctionDeclaration oldMethod, final FunctionDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaScriptModelException {
- Type newReturnType= null;
- if (mapping.length > 0)
- newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, mapping, rewrite);
- else
- newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, rewrite);
- newMethod.setReturnType2(newReturnType);
- }
-
- protected SuperTypeConstraintsSolver createContraintSolver(final SuperTypeConstraintsModel model) {
- return new SuperTypeConstraintsSolver(model);
- }
-
- public IType getDeclaringType() {
- if (fCachedDeclaringType != null)
- return fCachedDeclaringType;
- fCachedDeclaringType= RefactoringAvailabilityTester.getTopLevelType(fMembersToMove);
- if (fCachedDeclaringType == null)
- fCachedDeclaringType= fMembersToMove[0].getDeclaringType();
- return fCachedDeclaringType;
- }
-
- public IMember[] getMembersToMove() {
- return fMembersToMove;
- }
-
- protected IType[] getTypesReferencedInMovedMembers(final IProgressMonitor monitor) throws JavaScriptModelException {
- if (fCachedReferencedTypes == null) {
- final IType[] types= ReferenceFinderUtil.getTypesReferencedIn(fMembersToMove, fOwner, monitor);
- final List result= new ArrayList(types.length);
- final List members= Arrays.asList(fMembersToMove);
- for (int index= 0; index < types.length; index++) {
- if (!members.contains(types[index]) && !types[index].equals(getDeclaringType()))
- result.add(types[index]);
- }
- fCachedReferencedTypes= new IType[result.size()];
- result.toArray(fCachedReferencedTypes);
- }
- return fCachedReferencedTypes;
- }
-
- protected boolean hasNonMovedReferences(final IMember member, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- if (!fCachedMembersReferences.containsKey(member)) {
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setFiltering(true, true);
- engine.setStatus(status);
- engine.setOwner(fOwner);
- engine.setScope(RefactoringScopeFactory.create(member));
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- fCachedMembersReferences.put(member, engine.getResults());
- }
- final SearchResultGroup[] groups= (SearchResultGroup[]) fCachedMembersReferences.get(member);
- if (groups.length == 0)
- return false;
- else if (groups.length > 1)
- return true;
- final IJavaScriptUnit unit= groups[0].getCompilationUnit();
- if (!getDeclaringType().getJavaScriptUnit().equals(unit))
- return true;
- final SearchMatch[] matches= groups[0].getSearchResults();
- for (int index= 0; index < matches.length; index++) {
- if (!isMovedReference(matches[index]))
- return true;
- }
- return false;
- }
-
- protected boolean isMovedReference(final SearchMatch match) throws JavaScriptModelException {
- ISourceRange range= null;
- for (int index= 0; index < fMembersToMove.length; index++) {
- range= fMembersToMove[index].getSourceRange();
- if (range.getOffset() <= match.getOffset() && range.getOffset() + range.getLength() >= match.getOffset())
- return true;
- }
- return false;
- }
-
- public RefactoringParticipant[] loadParticipants(final RefactoringStatus status, final SharableParticipants sharedParticipants) throws CoreException {
- return new RefactoringParticipant[0];
- }
-
- protected boolean needsVisibilityAdjustment(final IMember member, final boolean references, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- if (JdtFlags.isPublic(member))
- return false;
- if (!references)
- return true;
- return hasNonMovedReferences(member, monitor, status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IDefaultValueAdvisor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IDefaultValueAdvisor.java
deleted file mode 100644
index 0f00b58d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IDefaultValueAdvisor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-
-public interface IDefaultValueAdvisor {
-
- /**
- * Creates a default expression for an added parameter for a given method invocation.
- *
- * @param invocationArguments arguments of the method invocation
- * @param addedInfo the added ParamterInfo object
- * @param parameterInfos all ParameterInfo objects, including the added ParameterInfo
- * @param enclosingMethod the Method that encloses the invocation. Can be null if there is no enclosing method
- * @param isRecursive true if called from a recursive invocation
- * @param cuRewrite the CompilationUnitRewrite to use for rewrite, imports etc..
- * @return a new Expression to be used as argument for the new parameter
- */
- Expression createDefaultExpression(List/*<Expression>*/ invocationArguments, ParameterInfo addedInfo, List/*<ParameterInfo>*/ parameterInfos, FunctionDeclaration enclosingMethod, boolean isRecursive, CompilationUnitRewrite cuRewrite);
-
- /**
- * Create a type for the added parameter.
- *
- * @param newTypeName the fully qualified name of the type
- * @param startPosition the position where the type is defined in a compilation unit
- * @param cuRewrite the CompilationUnitRewrite to use for rewrite, imports etc..
- * @return the new type to be used in default expressions
- */
- Type createType(String newTypeName, int startPosition, CompilationUnitRewrite cuRewrite);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IMemberActionInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IMemberActionInfo.java
deleted file mode 100644
index fbeb8782..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/IMemberActionInfo.java
+++ /dev/null
@@ -1,14 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-public interface IMemberActionInfo {
- public boolean isActive();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRemover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRemover.java
deleted file mode 100644
index 8ed33a73..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRemover.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ImportReferencesCollector;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-public class ImportRemover {
-
- private static class StaticImportData {
-
- private boolean fField;
-
- private String fMember;
-
- private String fQualifier;
-
- private StaticImportData(String qualifier, String member, boolean field) {
- fQualifier= qualifier;
- fMember= member;
- fField= field;
- }
- }
-
- private Set/* <String> */fAddedImports= new HashSet();
-
- private Set/* <StaticImportData> */fAddedStaticImports= new HashSet();
-
- private final IJavaScriptProject fProject;
-
- private List/* <ASTNode> */fRemovedNodes= new ArrayList();
-
- private final JavaScriptUnit fRoot;
-
- public ImportRemover(IJavaScriptProject project, JavaScriptUnit root) {
- fProject= project;
- fRoot= root;
- }
-
- private void divideTypeRefs(List/* <SimpleName> */importNames, List/* <SimpleName> */staticNames, List/* <SimpleName> */removedRefs, List/* <SimpleName> */unremovedRefs) {
- int[] removedStartsEnds= new int[2 * fRemovedNodes.size()];
- for (int index= 0; index < fRemovedNodes.size(); index++) {
- ASTNode node= (ASTNode) fRemovedNodes.get(index);
- int start= node.getStartPosition();
- removedStartsEnds[2 * index]= start;
- removedStartsEnds[2 * index + 1]= start + node.getLength();
- }
- for (Iterator iterator= importNames.iterator(); iterator.hasNext();) {
- SimpleName name= (SimpleName) iterator.next();
- if (isInRemoved(name, removedStartsEnds))
- removedRefs.add(name);
- else
- unremovedRefs.add(name);
- }
- for (Iterator iterator= staticNames.iterator(); iterator.hasNext();) {
- SimpleName name= (SimpleName) iterator.next();
- if (isInRemoved(name, removedStartsEnds))
- removedRefs.add(name);
- else
- unremovedRefs.add(name);
- }
- }
-
- public IBinding[] getImportsToRemove() {
- ArrayList/* <SimpleName> */importNames= new ArrayList();
- ArrayList/* <SimpleName> */staticNames= new ArrayList();
- fRoot.accept(new ImportReferencesCollector(fProject, null, importNames, staticNames));
- List/* <SimpleName> */removedRefs= new ArrayList();
- List/* <SimpleName> */unremovedRefs= new ArrayList();
- divideTypeRefs(importNames, staticNames, removedRefs, unremovedRefs);
- if (removedRefs.size() == 0)
- return new IBinding[0];
-
- HashMap/* <String, IBinding> */potentialRemoves= getPotentialRemoves(removedRefs);
- for (Iterator iterator= unremovedRefs.iterator(); iterator.hasNext();) {
- SimpleName name= (SimpleName) iterator.next();
- potentialRemoves.remove(name.getIdentifier());
- }
-
- Collection importsToRemove= potentialRemoves.values();
- return (IBinding[]) importsToRemove.toArray(new IBinding[importsToRemove.size()]);
- }
-
- private HashMap getPotentialRemoves(List removedRefs) {
- HashMap/* <String, IBinding> */potentialRemoves= new HashMap();
- for (Iterator iterator= removedRefs.iterator(); iterator.hasNext();) {
- SimpleName name= (SimpleName) iterator.next();
- if (fAddedImports.contains(name.getIdentifier()) || hasAddedStaticImport(name))
- continue;
- IBinding binding= name.resolveBinding();
- if (binding != null)
- potentialRemoves.put(name.getIdentifier(), binding);
- }
- return potentialRemoves;
- }
-
- private boolean hasAddedStaticImport(SimpleName name) {
- IBinding binding= name.resolveBinding();
- if (binding instanceof IVariableBinding) {
- IVariableBinding variable= (IVariableBinding) binding;
- return hasAddedStaticImport(variable.getDeclaringClass().getQualifiedName(), variable.getName(), true);
- } else if (binding instanceof IFunctionBinding) {
- IFunctionBinding method= (IFunctionBinding) binding;
- return hasAddedStaticImport(method.getDeclaringClass().getQualifiedName(), method.getName(), false);
- }
- return false;
- }
-
- private boolean hasAddedStaticImport(String qualifier, String member, boolean field) {
- StaticImportData data= null;
- for (final Iterator iterator= fAddedStaticImports.iterator(); iterator.hasNext();) {
- data= (StaticImportData) iterator.next();
- if (data.fQualifier.equals(qualifier) && data.fMember.equals(member) && data.fField == field)
- return true;
- }
- return false;
- }
-
- public boolean hasRemovedNodes() {
- return fRemovedNodes.size() != 0;
- }
-
- private boolean isInRemoved(SimpleName ref, int[] removedStartsEnds) {
- int start= ref.getStartPosition();
- int end= start + ref.getLength();
- for (int index= 0; index < removedStartsEnds.length; index+= 2) {
- if (start >= removedStartsEnds[index] && end <= removedStartsEnds[index + 1])
- return true;
- }
- return false;
- }
-
- public void registerAddedImport(String typeName) {
- int dot= typeName.lastIndexOf('.');
- if (dot == -1)
- fAddedImports.add(typeName);
- else
- fAddedImports.add(typeName.substring(dot + 1));
- }
-
- public void registerAddedImports(Type newTypeNode) {
- newTypeNode.accept(new ASTVisitor(true) {
-
- private void addName(SimpleName name) {
- fAddedImports.add(name.getIdentifier());
- }
-
- public boolean visit(QualifiedName node) {
- addName(node.getName());
- return false;
- }
-
- public boolean visit(QualifiedType node) {
- addName(node.getName());
- return false;
- }
-
- public boolean visit(SimpleName node) {
- addName(node);
- return false;
- }
- });
- }
-
- public void registerAddedStaticImport(String qualifier, String member, boolean field) {
- fAddedStaticImports.add(new StaticImportData(qualifier, member, field));
- }
-
- public void registerAddedStaticImport(IBinding binding) {
- if (binding instanceof IVariableBinding) {
- ITypeBinding declaringType= ((IVariableBinding) binding).getDeclaringClass();
- fAddedStaticImports.add(new StaticImportData(Bindings.getRawQualifiedName(declaringType), binding.getName(), true));
-
- } else if (binding instanceof IFunctionBinding) {
- ITypeBinding declaringType= ((IFunctionBinding) binding).getDeclaringClass();
- fAddedStaticImports.add(new StaticImportData(Bindings.getRawQualifiedName(declaringType), binding.getName(), false));
-
- } else {
- throw new IllegalArgumentException(binding.toString());
- }
- }
-
- public void registerRemovedNode(ASTNode removed) {
- fRemovedNodes.add(removed);
- }
-
-
- public void applyRemoves(ImportRewrite importRewrite) {
- IBinding[] bindings= getImportsToRemove();
- for (int i= 0; i < bindings.length; i++) {
- if (bindings[i] instanceof ITypeBinding) {
- ITypeBinding typeBinding= (ITypeBinding) bindings[i];
- importRewrite.removeImport(typeBinding.getTypeDeclaration().getQualifiedName());
- } else if (bindings[i] instanceof IFunctionBinding) {
- IFunctionBinding binding= (IFunctionBinding) bindings[i];
- importRewrite.removeStaticImport(binding.getDeclaringClass().getQualifiedName() + '.' + binding.getName());
- } else if (bindings[i] instanceof IVariableBinding) {
- IVariableBinding binding= (IVariableBinding) bindings[i];
- importRewrite.removeStaticImport(binding.getDeclaringClass().getQualifiedName() + '.' + binding.getName());
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRewriteUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRewriteUtil.java
deleted file mode 100644
index 4fdf79b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ImportRewriteUtil.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ImportReferencesCollector;
-
-/**
- * Utility methods to manage static and non-static imports of a compilation unit.
- *
- *
- */
-public final class ImportRewriteUtil {
-
- /**
- * Adds the necessary imports for an AST node to the specified compilation unit.
- *
- * @param rewrite the compilation unit rewrite whose compilation unit's imports should be updated
- * @param node the AST node specifying the element for which imports should be added
- * @param typeImports the map of name nodes to strings (element type: Map <Name, String>).
- * @param staticImports the map of name nodes to strings (element type: Map <Name, String>).
- * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
- */
- public static void addImports(final CompilationUnitRewrite rewrite, final ASTNode node, final Map typeImports, final Map staticImports, final boolean declarations) {
- addImports(rewrite, node, typeImports, staticImports, null, declarations);
- }
-
- /**
- * Adds the necessary imports for an AST node to the specified compilation unit.
- *
- * @param rewrite the compilation unit rewrite whose compilation unit's imports should be updated
- * @param node the AST node specifying the element for which imports should be added
- * @param typeImports the map of name nodes to strings (element type: Map <Name, String>).
- * @param staticImports the map of name nodes to strings (element type: Map <Name, String>).
- * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
- * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
- */
- public static void addImports(final CompilationUnitRewrite rewrite, final ASTNode node, final Map typeImports, final Map staticImports, final Collection excludeBindings, final boolean declarations) {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(node);
- Assert.isNotNull(typeImports);
- Assert.isNotNull(staticImports);
- final Set types= new HashSet();
- final Set members= new HashSet();
- final ImportReferencesCollector collector= new ImportReferencesCollector(rewrite.getCu().getJavaScriptProject(), null, types, members) {
-
- public final boolean visit(final Block block) {
- Assert.isNotNull(block);
- if (declarations && block.getParent() instanceof FunctionDeclaration)
- return false;
- return super.visit(block);
- }
- };
- node.accept(collector);
- final ImportRewrite rewriter= rewrite.getImportRewrite();
- final ImportRemover remover= rewrite.getImportRemover();
- Name name= null;
- IBinding binding= null;
- for (final Iterator iterator= types.iterator(); iterator.hasNext();) {
- name= (Name) iterator.next();
- binding= name.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ITypeBinding type= (ITypeBinding) binding;
- if (excludeBindings == null || !excludeBindings.contains(type)) {
- typeImports.put(name, rewriter.addImport(type));
- remover.registerAddedImport(type.getQualifiedName());
- }
- }
- }
- for (final Iterator iterator= members.iterator(); iterator.hasNext();) {
- name= (Name) iterator.next();
- binding= name.resolveBinding();
- if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- final ITypeBinding declaring= variable.getDeclaringClass();
- if (declaring != null && (excludeBindings == null || !excludeBindings.contains(variable))) {
- staticImports.put(name, rewriter.addStaticImport(variable));
- remover.registerAddedStaticImport(declaring.getQualifiedName(), variable.getName(), true);
- }
- } else if (binding instanceof IFunctionBinding) {
- final IFunctionBinding method= (IFunctionBinding) binding;
- final ITypeBinding declaring= method.getDeclaringClass();
- if (declaring != null && (excludeBindings == null || !excludeBindings.contains(method))) {
- staticImports.put(name, rewriter.addStaticImport(method));
- remover.registerAddedStaticImport(declaring.getQualifiedName(), method.getName(), false);
- }
- }
- }
- }
-
- /**
- * Collects the necessary imports for an element represented by the specified AST node.
- *
- * @param project the java project containing the element
- * @param node the AST node specifying the element for which imports should be collected
- * @param typeBindings the set of type bindings (element type: Set <ITypeBinding>).
- * @param staticBindings the set of bindings (element type: Set <IBinding>).
- * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
- */
- public static void collectImports(final IJavaScriptProject project, final ASTNode node, final Collection typeBindings, final Collection staticBindings, final boolean declarations) {
- collectImports(project, node, typeBindings, staticBindings, null, declarations);
- }
-
- /**
- * Collects the necessary imports for an element represented by the specified AST node.
- *
- * @param project the java project containing the element
- * @param node the AST node specifying the element for which imports should be collected
- * @param typeBindings the set of type bindings (element type: Set <ITypeBinding>).
- * @param staticBindings the set of bindings (element type: Set <IBinding>).
- * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
- * @param declarations <code>true</code> if method declarations are treated as abstract, <code>false</code> otherwise
- */
- public static void collectImports(final IJavaScriptProject project, final ASTNode node, final Collection typeBindings, final Collection staticBindings, final Collection excludeBindings, final boolean declarations) {
- Assert.isNotNull(project);
- Assert.isNotNull(node);
- Assert.isNotNull(typeBindings);
- Assert.isNotNull(staticBindings);
- final Set types= new HashSet();
- final Set members= new HashSet();
- final ImportReferencesCollector collector= new ImportReferencesCollector(project, null, types, members) {
-
- public final boolean visit(final Block block) {
- Assert.isNotNull(block);
- if (declarations && block.getParent() instanceof FunctionDeclaration)
- return false;
- return super.visit(block);
- }
- };
- node.accept(collector);
- Name name= null;
- IBinding binding= null;
- for (final Iterator iterator= types.iterator(); iterator.hasNext();) {
- name= (Name) iterator.next();
- binding= name.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ITypeBinding type= (ITypeBinding) binding;
- if (excludeBindings == null || !excludeBindings.contains(type))
- typeBindings.add(type);
- }
- }
- for (final Iterator iterator= members.iterator(); iterator.hasNext();) {
- name= (Name) iterator.next();
- binding= name.resolveBinding();
- if (binding != null && (excludeBindings == null || !excludeBindings.contains(binding)))
- staticBindings.add(binding);
- }
- }
-
- private ImportRewriteUtil() {
- // Not for instantiation
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java
deleted file mode 100644
index 1e1063d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.MoveProcessor;
-import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * A move refactoring which can be initialized with refactoring arguments.
- *
- *
- */
-public class JavaMoveRefactoring extends MoveRefactoring implements IScriptableRefactoring {
-
- /**
- * Creates a new java move refactoring.
- *
- * @param processor
- * the move processor to use
- */
- public JavaMoveRefactoring(final MoveProcessor processor) {
- super(processor);
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberCheckUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberCheckUtil.java
deleted file mode 100644
index 27c9bded..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberCheckUtil.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-class MemberCheckUtil {
-
- private MemberCheckUtil(){
- //static only
- }
-
- public static RefactoringStatus checkMembersInDestinationType(IMember[] members, IType destinationType) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < members.length; i++) {
- if (members[i].getElementType() == IJavaScriptElement.METHOD)
- checkMethodInType(destinationType, result, (IFunction)members[i]);
- else if (members[i].getElementType() == IJavaScriptElement.FIELD)
- checkFieldInType(destinationType, result, (IField)members[i]);
- else if (members[i].getElementType() == IJavaScriptElement.TYPE)
- checkTypeInType(destinationType, result, (IType)members[i]);
- }
- return result;
- }
-
- private static void checkMethodInType(IType destinationType, RefactoringStatus result, IFunction method) throws JavaScriptModelException {
- IFunction[] destinationTypeMethods= destinationType.getFunctions();
- IFunction found= findMethod(method, destinationTypeMethods);
- if (found != null){
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), found.getSourceRange());
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_signature_exists,
- new String[]{method.getElementName(), JavaModelUtil.getFullyQualifiedName(destinationType)});
- result.addError(message, context);
- } else {
- IFunction similar= Checks.findMethod(method, destinationType);
- if (similar != null){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_same_param_count,
- new String[]{method.getElementName(), JavaModelUtil.getFullyQualifiedName(destinationType)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), similar.getSourceRange());
- result.addWarning(message, context);
- }
- }
- }
-
- private static void checkFieldInType(IType destinationType, RefactoringStatus result, IField field) throws JavaScriptModelException {
- IField destinationTypeField= destinationType.getField(field.getElementName());
- if (! destinationTypeField.exists())
- return;
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_field_exists,
- new String[]{field.getElementName(), JavaModelUtil.getFullyQualifiedName(destinationType)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationTypeField.getSourceRange());
- result.addError(message, context);
- }
-
- private static void checkTypeInType(IType destinationType, RefactoringStatus result, IType type) throws JavaScriptModelException {
- String typeName= type.getElementName();
- IType destinationTypeType= destinationType.getType(typeName);
- if (destinationTypeType.exists()){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_type_name_conflict0,
- new String[]{typeName, JavaModelUtil.getFullyQualifiedName(destinationType)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationTypeType.getNameRange());
- result.addError(message, context);
- } else {
- //need to check the hierarchy of enclosing and enclosed types
- if (destinationType.getElementName().equals(typeName)){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_type_name_conflict1,
- new String[]{JavaModelUtil.getFullyQualifiedName(type)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationType.getNameRange());
- result.addError(message, context);
- }
- if (typeNameExistsInEnclosingTypeChain(destinationType, typeName)){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_type_name_conflict2,
- new String[]{JavaModelUtil.getFullyQualifiedName(type)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationType.getNameRange());
- result.addError(message, context);
- }
- checkHierarchyOfEnclosedTypes(destinationType, result, type);
- }
- }
-
- private static void checkHierarchyOfEnclosedTypes(IType destinationType, RefactoringStatus result, IType type) throws JavaScriptModelException {
- IType[] enclosedTypes= getAllEnclosedTypes(type);
- for (int i= 0; i < enclosedTypes.length; i++) {
- IType enclosedType= enclosedTypes[i];
- if (destinationType.getElementName().equals(enclosedType.getElementName())){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_type_name_conflict3,
- new String[]{JavaModelUtil.getFullyQualifiedName(enclosedType), JavaModelUtil.getFullyQualifiedName(type)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationType.getNameRange());
- result.addError(message, context);
- }
- if (typeNameExistsInEnclosingTypeChain(destinationType, enclosedType.getElementName())){
- String message= Messages.format(RefactoringCoreMessages.MemberCheckUtil_type_name_conflict4,
- new String[]{JavaModelUtil.getFullyQualifiedName(enclosedType), JavaModelUtil.getFullyQualifiedName(type)});
- RefactoringStatusContext context= JavaStatusContext.create(destinationType.getJavaScriptUnit(), destinationType.getNameRange());
- result.addError(message, context);
- }
- }
- }
-
- private static IType[] getAllEnclosedTypes(IType type) throws JavaScriptModelException {
- List result= new ArrayList(2);
- IType[] directlyEnclosed= type.getTypes();
- result.addAll(Arrays.asList(directlyEnclosed));
- for (int i= 0; i < directlyEnclosed.length; i++) {
- IType enclosedType= directlyEnclosed[i];
- result.addAll(Arrays.asList(getAllEnclosedTypes(enclosedType)));
- }
- return (IType[]) result.toArray(new IType[result.size()]);
- }
-
- private static boolean typeNameExistsInEnclosingTypeChain(IType type, String typeName){
- IType enclosing= type.getDeclaringType();
- while (enclosing != null){
- if (enclosing.getElementName().equals(typeName))
- return true;
- enclosing= enclosing.getDeclaringType();
- }
- return false;
- }
-
- /**
- * Finds a method in a list of methods. Compares methods by signature
- * (only SimpleNames of types), and not by the declaring type.
- * @return The found method or <code>null</code>, if nothing found
- */
- public static IFunction findMethod(IFunction method, IFunction[] allMethods) throws JavaScriptModelException {
- String name= method.getElementName();
- String[] paramTypes= method.getParameterTypes();
- boolean isConstructor= method.isConstructor();
-
- for (int i= 0; i < allMethods.length; i++) {
- if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, allMethods[i]))
- return allMethods[i];
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberVisibilityAdjustor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberVisibilityAdjustor.java
deleted file mode 100644
index b709bb6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MemberVisibilityAdjustor.java
+++ /dev/null
@@ -1,1331 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IExtendedModifier;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Helper class to adjust the visibilities of members with respect to a reference element.
- *
- *
- */
-public final class MemberVisibilityAdjustor {
-
- /**
- * The visibility group category set.
- *
- *
- */
- public static final GroupCategorySet SET_VISIBILITY_ADJUSTMENTS= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.visibilityAdjustments", //$NON-NLS-1$
- RefactoringCoreMessages.MemberVisibilityAdjustor_adjustments_name, RefactoringCoreMessages.MemberVisibilityAdjustor_adjustments_description));
-
- /** Description of a member visibility adjustment */
- public static class IncomingMemberVisibilityAdjustment implements IVisibilityAdjustment {
-
- /** The keyword representing the adjusted visibility */
- protected final ModifierKeyword fKeyword;
-
- /** The member whose visibility has been adjusted */
- protected final IMember fMember;
-
- /** Does the visibility adjustment need rewriting? */
- protected boolean fNeedsRewriting= true;
-
- /** The associated refactoring status */
- protected final RefactoringStatus fRefactoringStatus;
-
- /**
- * Creates a new incoming member visibility adjustment.
- *
- * @param member the member which is adjusted
- * @param keyword the keyword representing the adjusted visibility
- * @param status the associated status, or <code>null</code>
- */
- public IncomingMemberVisibilityAdjustment(final IMember member, final ModifierKeyword keyword, final RefactoringStatus status) {
- Assert.isNotNull(member);
- Assert.isTrue(!(member instanceof IInitializer));
- Assert.isTrue(isVisibilityKeyword(keyword));
- fMember= member;
- fKeyword= keyword;
- fRefactoringStatus= status;
- }
-
- /**
- * Returns the visibility keyword.
- *
- * @return the visibility keyword
- */
- public final ModifierKeyword getKeyword() {
- return fKeyword;
- }
-
- /**
- * Returns the adjusted member.
- *
- * @return the adjusted member
- */
- public final IMember getMember() {
- return fMember;
- }
-
- /**
- * Returns the associated refactoring status.
- *
- * @return the associated refactoring status
- */
- public final RefactoringStatus getStatus() {
- return fRefactoringStatus;
- }
-
- /**
- * Does the visibility adjustment need rewriting?
- *
- * @return <code>true</code> if it needs rewriting, <code>false</code> otherwise
- */
- public final boolean needsRewriting() {
- return fNeedsRewriting;
- }
-
- /**
- * Rewrites the visibility adjustment.
- *
- * @param adjustor the java element visibility adjustor
- * @param rewrite the AST rewrite to use
- * @param root the root of the AST used in the rewrite
- * @param group the text edit group description to use, or <code>null</code>
- * @param status the refactoring status, or <code>null</code>
- * @throws JavaScriptModelException if an error occurs
- */
- protected final void rewriteVisibility(final MemberVisibilityAdjustor adjustor, final ASTRewrite rewrite, final JavaScriptUnit root, final CategorizedTextEditGroup group, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(adjustor);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(root);
- final int visibility= fKeyword != null ? fKeyword.toFlagValue() : Modifier.NONE;
- if (fMember instanceof IField) {
- final VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) fMember, root);
- final FieldDeclaration declaration= (FieldDeclaration) fragment.getParent();
- if (declaration.fragments().size() == 1)
- ModifierRewrite.create(rewrite, declaration).setVisibility(visibility, group);
- else {
- final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
- newFragment.setName((SimpleName) rewrite.createCopyTarget(fragment.getName()));
- final FieldDeclaration newDeclaration= rewrite.getAST().newFieldDeclaration(newFragment);
- newDeclaration.setType((Type) rewrite.createCopyTarget(declaration.getType()));
- IExtendedModifier extended= null;
- for (final Iterator iterator= declaration.modifiers().iterator(); iterator.hasNext();) {
- extended= (IExtendedModifier) iterator.next();
- if (extended.isModifier()) {
- final Modifier modifier= (Modifier) extended;
- final int flag= modifier.getKeyword().toFlagValue();
- if ((flag & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)) != 0)
- continue;
- }
- newDeclaration.modifiers().add(rewrite.createCopyTarget((ASTNode) extended));
- }
- ModifierRewrite.create(rewrite, newDeclaration).setVisibility(visibility, group);
- final AbstractTypeDeclaration type= (AbstractTypeDeclaration) declaration.getParent();
- rewrite.getListRewrite(type, type.getBodyDeclarationsProperty()).insertAfter(newDeclaration, declaration, null);
- final ListRewrite list= rewrite.getListRewrite(declaration, FieldDeclaration.FRAGMENTS_PROPERTY);
- list.remove(fragment, group);
- if (list.getRewrittenList().isEmpty())
- rewrite.remove(declaration, null);
- }
- if (status != null)
- adjustor.fStatus.merge(status);
- } else if (fMember != null) {
- final BodyDeclaration declaration= ASTNodeSearchUtil.getBodyDeclarationNode(fMember, root);
- if (declaration != null) {
- ModifierRewrite.create(rewrite, declaration).setVisibility(visibility, group);
- if (status != null)
- adjustor.fStatus.merge(status);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.IVisibilityAdjustment#rewriteVisibility(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor, org.eclipse.core.runtime.IProgressMonitor)
- */
- public void rewriteVisibility(final MemberVisibilityAdjustor adjustor, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(adjustor);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting);
- if (fNeedsRewriting) {
- if (adjustor.fRewrite != null && adjustor.fRoot != null)
- rewriteVisibility(adjustor, adjustor.fRewrite, adjustor.fRoot, null, fRefactoringStatus);
- else {
- final CompilationUnitRewrite rewrite= adjustor.getCompilationUnitRewrite(fMember.getJavaScriptUnit());
- rewriteVisibility(adjustor, rewrite.getASTRewrite(), rewrite.getRoot(), rewrite.createCategorizedGroupDescription(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility, getLabel(getKeyword())), SET_VISIBILITY_ADJUSTMENTS), fRefactoringStatus);
- }
- } else if (fRefactoringStatus != null)
- adjustor.fStatus.merge(fRefactoringStatus);
- monitor.worked(1);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Determines whether the visibility adjustment needs rewriting.
- *
- * @param rewriting <code>true</code> if it needs rewriting, <code>false</code> otherwise
- */
- public final void setNeedsRewriting(final boolean rewriting) {
- fNeedsRewriting= rewriting;
- }
- }
-
- /** Interface for visibility adjustments */
- public interface IVisibilityAdjustment {
-
- /**
- * Rewrites the visibility adjustment.
- *
- * @param adjustor the java element visibility adjustor
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if an error occurs
- */
- public void rewriteVisibility(MemberVisibilityAdjustor adjustor, IProgressMonitor monitor) throws JavaScriptModelException;
- }
-
- /** Description of an outgoing member visibility adjustment */
- public static class OutgoingMemberVisibilityAdjustment extends IncomingMemberVisibilityAdjustment {
-
- /**
- * Creates a new outgoing member visibility adjustment.
- *
- * @param member the member which is adjusted
- * @param keyword the keyword representing the adjusted visibility
- * @param status the associated status
- */
- public OutgoingMemberVisibilityAdjustment(final IMember member, final ModifierKeyword keyword, final RefactoringStatus status) {
- super(member, keyword, status);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.IVisibilityAdjustment#rewriteVisibility(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor, org.eclipse.core.runtime.IProgressMonitor)
- */
- public void rewriteVisibility(final MemberVisibilityAdjustor adjustor, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(adjustor);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting);
- if (fNeedsRewriting) {
- final CompilationUnitRewrite rewrite= adjustor.getCompilationUnitRewrite(fMember.getJavaScriptUnit());
- rewriteVisibility(adjustor, rewrite.getASTRewrite(), rewrite.getRoot(), rewrite.createCategorizedGroupDescription(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility, getLabel(getKeyword())), SET_VISIBILITY_ADJUSTMENTS), fRefactoringStatus);
- }
- monitor.worked(1);
- } finally {
- monitor.done();
- }
- }
- }
-
- /**
- * Returns the label for the specified java element.
- *
- * @param element the element to get the label for
- * @return the label for the element
- */
- public static String getLabel(final IJavaScriptElement element) {
- Assert.isNotNull(element);
- return JavaScriptElementLabels.getElementLabel(element, JavaScriptElementLabels.ALL_FULLY_QUALIFIED | JavaScriptElementLabels.ALL_DEFAULT);
- }
-
- /**
- * Returns the label for the specified visibility keyword.
- *
- * @param keyword the keyword to get the label for, or <code>null</code> for default visibility
- * @return the label for the keyword
- */
- public static String getLabel(final ModifierKeyword keyword) {
- Assert.isTrue(isVisibilityKeyword(keyword));
- if (keyword == null)
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default;
- else if (ModifierKeyword.PUBLIC_KEYWORD.equals(keyword))
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
- else if (ModifierKeyword.PROTECTED_KEYWORD.equals(keyword))
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_protected;
- else
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_private;
- }
-
- /**
- * Returns the message string for the specified member.
- *
- * @param member the member to get the string for
- * @return the string for the member
- */
- public static String getMessage(final IMember member) {
- Assert.isTrue(member instanceof IType || member instanceof IFunction || member instanceof IField);
- if (member instanceof IType)
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning;
- else if (member instanceof IFunction)
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning;
- else
- return RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_field_warning;
- }
-
- /**
- * Do the specified modifiers represent a lower visibility than the required threshold?
- *
- * @param modifiers the modifiers to test
- * @param threshold the visibility threshold to compare with
- * @return <code>true</code> if the visibility is lower than required, <code>false</code> otherwise
- */
- public static boolean hasLowerVisibility(final int modifiers, final int threshold) {
- if (Modifier.isPrivate(threshold))
- return false;
- else if (Modifier.isPublic(threshold))
- return !Modifier.isPublic(modifiers);
- else if (Modifier.isProtected(threshold))
- return !Modifier.isProtected(modifiers) && !Modifier.isPublic(modifiers);
- else
- return Modifier.isPrivate(modifiers);
- }
-
- /**
- * Does the specified modifier keyword represent a lower visibility than the required threshold?
- *
- * @param keyword the visibility keyword to test, or <code>null</code> for default visibility
- * @param threshold the visibility threshold keyword to compare with, or <code>null</code> to compare with default visibility
- * @return <code>true</code> if the visibility is lower than required, <code>false</code> otherwise
- */
- public static boolean hasLowerVisibility(final ModifierKeyword keyword, final ModifierKeyword threshold) {
- Assert.isTrue(isVisibilityKeyword(keyword));
- Assert.isTrue(isVisibilityKeyword(threshold));
- return hasLowerVisibility(keyword != null ? keyword.toFlagValue() : Modifier.NONE, threshold != null ? threshold.toFlagValue() : Modifier.NONE);
- }
-
- /**
- * Is the specified severity a refactoring status severity?
- *
- * @param severity the severity to test
- * @return <code>true</code> if it is a refactoring status severity, <code>false</code> otherwise
- */
- private static boolean isStatusSeverity(final int severity) {
- return severity == RefactoringStatus.ERROR || severity == RefactoringStatus.FATAL || severity == RefactoringStatus.INFO || severity == RefactoringStatus.OK || severity == RefactoringStatus.WARNING;
- }
-
- /**
- * Is the specified modifier keyword a visibility keyword?
- *
- * @param keyword the keyword to test, or <code>null</code>
- * @return <code>true</code> if it is a visibility keyword, <code>false</code> otherwise
- */
- private static boolean isVisibilityKeyword(final ModifierKeyword keyword) {
- return keyword == null || ModifierKeyword.PUBLIC_KEYWORD.equals(keyword) || ModifierKeyword.PROTECTED_KEYWORD.equals(keyword) || ModifierKeyword.PRIVATE_KEYWORD.equals(keyword);
- }
-
- /**
- * Is the specified modifier a visibility modifier?
- *
- * @param modifier the keyword to test
- * @return <code>true</code> if it is a visibility modifier, <code>false</code> otherwise
- */
- private static boolean isVisibilityModifier(final int modifier) {
- return modifier == Modifier.NONE || modifier == Modifier.PUBLIC || modifier == Modifier.PROTECTED || modifier == Modifier.PRIVATE;
- }
-
- /**
- * Converts a given modifier keyword into a visibility flag.
- *
- * @param keyword the keyword to convert
- * @return the visibility flag
- */
- private static int keywordToVisibility(final ModifierKeyword keyword) {
- int visibility= 0;
- if (keyword == ModifierKeyword.PUBLIC_KEYWORD)
- visibility= Flags.AccPublic;
- else if (keyword == ModifierKeyword.PRIVATE_KEYWORD)
- visibility= Flags.AccPrivate;
- return visibility;
- }
-
- /**
- * Does the specified member need further visibility adjustment?
- *
- * @param member the member to test
- * @param threshold the visibility threshold to test for
- * @param adjustments the map of members to visibility adjustments
- * @return <code>true</code> if the member needs further adjustment, <code>false</code> otherwise
- */
- public static boolean needsVisibilityAdjustments(final IMember member, final int threshold, final Map adjustments) {
- Assert.isNotNull(member);
- Assert.isTrue(isVisibilityModifier(threshold));
- Assert.isNotNull(adjustments);
- final IncomingMemberVisibilityAdjustment adjustment= (IncomingMemberVisibilityAdjustment) adjustments.get(member);
- if (adjustment != null) {
- final ModifierKeyword keyword= adjustment.getKeyword();
- return hasLowerVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), threshold);
- }
- return true;
- }
-
- /**
- * Does the specified member need further visibility adjustment?
- *
- * @param member the member to test
- * @param threshold the visibility threshold to test for, or <code>null</code> for default visibility
- * @param adjustments the map of members to visibility adjustments
- * @return <code>true</code> if the member needs further adjustment, <code>false</code> otherwise
- */
- public static boolean needsVisibilityAdjustments(final IMember member, final ModifierKeyword threshold, final Map adjustments) {
- Assert.isNotNull(member);
- Assert.isNotNull(adjustments);
- final IncomingMemberVisibilityAdjustment adjustment= (IncomingMemberVisibilityAdjustment) adjustments.get(member);
- if (adjustment != null)
- return hasLowerVisibility(adjustment.getKeyword(), threshold);
- return true;
- }
-
- /** The map of members to visibility adjustments */
- private Map fAdjustments= new HashMap();
-
- /** Should incoming references be adjusted? */
- private boolean fIncoming= true;
-
- /** Should outgoing references be adjusted? */
- private boolean fOutgoing= true;
-
- /** The referenced element causing the visibility adjustment */
- private final IMember fReferenced;
-
- /** The referencing java element */
- private final IJavaScriptElement fReferencing;
-
- /** The AST rewrite to use for reference visibility adjustments, or <code>null</code> to use a compilation unit rewrite */
- private ASTRewrite fRewrite= null;
-
- /** The map of compilation units to compilation unit rewrites */
- private Map fRewrites= new HashMap(3);
-
- /** The root node of the AST rewrite for reference visibility adjustments, or <code>null</code> to use a compilation unit rewrite */
- private JavaScriptUnit fRoot= null;
-
- /** The incoming search scope */
- private IJavaScriptSearchScope fScope;
-
- /** The status of the visibility adjustment */
- private RefactoringStatus fStatus= new RefactoringStatus();
-
- /** The type hierarchy cache */
- private final Map fTypeHierarchies= new HashMap();
-
- /** The visibility message severity */
- private int fVisibilitySeverity= RefactoringStatus.WARNING;
-
- /** The working copy owner, or <code>null</code> to use none */
- private WorkingCopyOwner fOwner= null;
-
- /**
- * Creates a new java element visibility adjustor.
- *
- * @param referencing the referencing element used to compute the visibility
- * @param referenced the referenced member which causes the visibility changes
- */
- public MemberVisibilityAdjustor(final IJavaScriptElement referencing, final IMember referenced) {
- Assert.isTrue(!(referenced instanceof IInitializer));
- Assert.isTrue(referencing instanceof IJavaScriptUnit || referencing instanceof IType || referencing instanceof IPackageFragment);
- fScope= RefactoringScopeFactory.createReferencedScope(new IJavaScriptElement[] { referenced}, IJavaScriptSearchScope.REFERENCED_PROJECTS | IJavaScriptSearchScope.SOURCES | IJavaScriptSearchScope.APPLICATION_LIBRARIES);
- fReferencing= referencing;
- fReferenced= referenced;
- }
-
- /**
- * Adjusts the visibility of the specified member.
- *
- * @param element the "source" point from which to calculate the visibility
- * @param referencedMovedElement the moved element which may be adjusted in visibility
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if the visibility adjustment could not be computed
- */
- private void adjustIncomingVisibility(final IJavaScriptElement element, IMember referencedMovedElement, final IProgressMonitor monitor) throws JavaScriptModelException {
- final ModifierKeyword threshold= getVisibilityThreshold(element, referencedMovedElement, monitor);
- int flags= referencedMovedElement.getFlags();
- IType declaring= referencedMovedElement.getDeclaringType();
- if (hasLowerVisibility(flags, threshold == null ? Modifier.NONE : threshold.toFlagValue()) && needsVisibilityAdjustment(referencedMovedElement, threshold))
- fAdjustments.put(referencedMovedElement, new IncomingMemberVisibilityAdjustment(referencedMovedElement, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(getMessage(referencedMovedElement), new String[] { getLabel(referencedMovedElement), getLabel(threshold)}), JavaStatusContext.create(referencedMovedElement), null, RefactoringStatusEntry.NO_CODE, null)));
- }
-
- /**
- * Check whether anyone accesses the members of the moved type from the
- * outside. Those may need to have their visibility adjusted.
- * @param member
- * @param monitor
- * @throws JavaScriptModelException
- */
- private void adjustMemberVisibility(final IMember member, final IProgressMonitor monitor) throws JavaScriptModelException {
-
- if (member instanceof IType) {
- // recursively check accessibility of member type's members
- final IJavaScriptElement[] typeMembers= ((IType) member).getChildren();
- for (int i= 0; i < typeMembers.length; i++) {
- if (! (typeMembers[i] instanceof IInitializer))
- adjustMemberVisibility((IMember) typeMembers[i], monitor);
- }
- }
-
- if ((member.equals(fReferenced)) || (Modifier.isPublic(member.getFlags())))
- return;
-
- final SearchResultGroup[] references= findReferences(member, monitor);
- for (int i= 0; i < references.length; i++) {
- final SearchMatch[] searchResults= references[i].getSearchResults();
- for (int k= 0; k < searchResults.length; k++) {
- final IJavaScriptElement referenceToMember= (IJavaScriptElement) searchResults[k].getElement();
- if (fAdjustments.get(member) == null && referenceToMember instanceof IMember && !isInsideMovedMember(referenceToMember)) {
- // check whether the member is still visible from the
- // destination. As we are moving a type, the destination is
- // a package or another type.
- adjustIncomingVisibility(fReferencing, member, new SubProgressMonitor(monitor, 1));
- }
- }
- }
- }
-
- /**
- * Is the specified member inside the moved member?
- * @param element the element
- * @return <code>true</code> if it is inside, <code>false</code> otherwise
- */
- private boolean isInsideMovedMember(final IJavaScriptElement element) {
- IJavaScriptElement current= element;
- while ((current= current.getParent()) != null)
- if (current.equals(fReferenced))
- return true;
- return false;
- }
-
- /**
- * Finds references to the specified member.
- * @param member the member
- * @param monitor the progress monitor to use
- * @return the search result groups
- * @throws JavaScriptModelException if an error occurs during search
- */
- private SearchResultGroup[] findReferences(final IMember member, final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setOwner(fOwner);
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(member));
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- return (SearchResultGroup[]) engine.getResults();
- }
-
- /**
- * Adjusts the visibility of the member based on the incoming references
- * represented by the specified search result groups.
- *
- * If there is at least one reference to the moved element from outside the
- * moved element, visibility must be increased such that the moved element
- * (fReferenced) is still visible at the target from all references. This
- * effectively means that the old element (fReferenced) must be visible from
- * the new location (fReferencing).
- *
- * @param groups the search result groups representing the references
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- private void adjustIncomingVisibility(final SearchResultGroup[] groups, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask("", groups.length); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- SearchMatch[] matches= null;
- boolean adjusted= false;
- for (int index= 0; index < groups.length; index++) {
- matches= groups[index].getSearchResults();
- for (int offset= 0; offset < matches.length; offset++) {
- final Object element= matches[offset].getElement();
- if (element instanceof IMember && !isInsideMovedMember((IMember) element)) {
- // found one reference which is not inside the moved
- // element => adjust visibility of the moved element
- adjustIncomingVisibility(fReferencing, fReferenced, monitor);
- adjusted= true; // one adjustment is enough
- break;
- }
- }
- if (adjusted)
- break;
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Adjusts the visibility of the referenced field found in a compilation unit.
- *
- * @param field the referenced field to adjust
- * @param threshold the visibility threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if an error occurs
- */
- private void adjustOutgoingVisibility(final IField field, final ModifierKeyword threshold) throws JavaScriptModelException {
- Assert.isTrue(!field.isBinary() && !field.isReadOnly());
- //bug 100555 (moving inner class to top level class; taking private fields with you)
- final IType declaring= field.getDeclaringType();
- if (declaring != null && declaring.equals(fReferenced)) return;
- if (hasLowerVisibility(field.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(field, threshold))
- adjustOutgoingVisibility(field, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_field_warning);
- }
-
- /**
- * Adjusts the visibility of the referenced body declaration.
- *
- * @param member the member where to adjust the visibility
- * @param threshold the visibility keyword representing the required visibility, or <code>null</code> for default visibility
- * @param template the message template to use
- * @throws JavaScriptModelException if an error occurs
- */
- private void adjustOutgoingVisibility(final IMember member, final ModifierKeyword threshold, final String template) throws JavaScriptModelException {
- Assert.isTrue(!member.isBinary() && !member.isReadOnly());
- boolean adjust= true;
- final IType declaring= member.getDeclaringType();
- if (declaring != null && (declaring.equals(fReferenced)))
- adjust= false;
- if (adjust && hasLowerVisibility(member.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(member, threshold))
- fAdjustments.put(member, new OutgoingMemberVisibilityAdjustment(member, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(template, new String[] { JavaScriptElementLabels.getTextLabel(member, JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.ALL_FULLY_QUALIFIED), getLabel(threshold)}), JavaStatusContext.create(member), null, RefactoringStatusEntry.NO_CODE, null)));
- }
-
- /**
- * Adjusts the visibilities of the referenced element from the search match found in a compilation unit.
- *
- * @param match the search match representing the element declaration
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if the visibility could not be determined
- */
- private void adjustOutgoingVisibility(final SearchMatch match, final IProgressMonitor monitor) throws JavaScriptModelException {
- final Object element= match.getElement();
- if (element instanceof IMember) {
- final IMember member= (IMember) element;
- if (!member.isBinary() && !member.isReadOnly() && !isInsideMovedMember(member)) {
- adjustOutgoingVisibilityChain(member, monitor);
- }
- }
- }
-
- private void adjustOutgoingVisibilityChain(final IMember member, final IProgressMonitor monitor) throws JavaScriptModelException {
-
- if (!Modifier.isPublic(member.getFlags())) {
- final ModifierKeyword threshold= computeOutgoingVisibilityThreshold(fReferencing, member, monitor);
- if (member instanceof IFunction) {
- adjustOutgoingVisibility(member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning);
- } else if (member instanceof IField) {
- adjustOutgoingVisibility((IField) member, threshold);
- } else if (member instanceof IType) {
- adjustOutgoingVisibility(member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning);
- }
- }
-
- if (member.getDeclaringType() != null)
- adjustOutgoingVisibilityChain(member.getDeclaringType(), monitor);
- }
-
- /**
- * Adjusts the visibilities of the outgoing references from the member represented by the specified search result groups.
- *
- * @param groups the search result groups representing the references
- * @param monitor the progress monitor to us
- * @throws JavaScriptModelException if the visibility could not be determined
- */
- private void adjustOutgoingVisibility(final SearchResultGroup[] groups, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask("", groups.length); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- IJavaScriptElement element= null;
- SearchMatch[] matches= null;
- SearchResultGroup group= null;
- for (int index= 0; index < groups.length; index++) {
- group= groups[index];
- element= JavaScriptCore.create(group.getResource());
- if (element instanceof IJavaScriptUnit) {
- matches= group.getSearchResults();
- for (int offset= 0; offset < matches.length; offset++)
- adjustOutgoingVisibility(matches[offset], new SubProgressMonitor(monitor, 1));
- } // else if (element != null)
- // fStatus.merge(RefactoringStatus.createStatus(fFailureSeverity, RefactoringCoreMessages.getFormattedString("MemberVisibilityAdjustor.binary.outgoing.project", new String[] { element.getJavaProject().getElementName(), getLabel(fReferenced)}), null, null, RefactoringStatusEntry.NO_CODE, null)); //$NON-NLS-1$
- // else if (group.getResource() != null)
- // fStatus.merge(RefactoringStatus.createStatus(fFailureSeverity, RefactoringCoreMessages.getFormattedString("MemberVisibilityAdjustor.binary.outgoing.resource", new String[] { group.getResource().getName(), getLabel(fReferenced)}), null, null, RefactoringStatusEntry.NO_CODE, null)); //$NON-NLS-1$
-
- // TW: enable when bug 78387 is fixed
-
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Adjusts the visibilities of the referenced and referencing elements.
- *
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void adjustVisibility(final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask("", 7); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fReferenced, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setScope(fScope);
- engine.setStatus(fStatus);
- engine.setOwner(fOwner);
- if (fIncoming) {
- // check calls to the referenced (moved) element, adjust element
- // visibility if necessary.
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- adjustIncomingVisibility((SearchResultGroup[]) engine.getResults(), new SubProgressMonitor(monitor, 1));
- engine.clearResults();
- // If the moved element is a type: Adjust visibility of members
- // of the type if they are accessed outside of the moved type
- if (fReferenced instanceof IType) {
- final IType type= (IType) fReferenced;
- adjustMemberVisibility(type, new SubProgressMonitor(monitor, 1));
- }
- }
- if (fOutgoing) {
- /*
- * Search for the types, fields, and methods which
- * are called/acted upon inside the referenced element (the one
- * to be moved) and assure that they are also visible from
- * within the referencing element (the destination type (or
- * package if move to new type)).
- */
- engine.searchReferencedTypes(fReferenced, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- engine.searchReferencedFields(fReferenced, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- engine.searchReferencedMethods(fReferenced, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- adjustOutgoingVisibility((SearchResultGroup[]) engine.getResults(), new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Computes the visibility threshold for the referenced element.
- *
- * @param referencing the referencing element
- * @param referenced the referenced element
- * @param monitor the progress monitor to use
- * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- public ModifierKeyword getVisibilityThreshold(final IJavaScriptElement referencing, final IMember referenced, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isTrue(!(referencing instanceof IInitializer));
- Assert.isTrue(!(referenced instanceof IInitializer));
- ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- final int referencingType= referencing.getElementType();
- final int referencedType= referenced.getElementType();
- switch (referencedType) {
- case IJavaScriptElement.TYPE: {
- final IType typeReferenced= (IType) referenced;
- final IJavaScriptUnit referencedUnit= typeReferenced.getJavaScriptUnit();
- switch (referencingType) {
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToType((IType) referencing, typeReferenced, monitor);
- break;
- }
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD: {
- final IMember member= (IMember) referencing;
- if (typeReferenced.equals(member.getDeclaringType()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.equals(member.getJavaScriptUnit()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (typeReferenced.getPackageFragment().equals(member.getDeclaringType().getPackageFragment()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (typeReferenced.getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- case IJavaScriptElement.FIELD: {
- final IField fieldReferenced= (IField) referenced;
- final IJavaScriptUnit referencedUnit= fieldReferenced.getJavaScriptUnit();
- switch (referencingType) {
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToField((IType) referencing, fieldReferenced, monitor);
- break;
- }
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD: {
- final IMember member= (IMember) referencing;
- if (fieldReferenced.getDeclaringType().equals(member.getDeclaringType()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.equals(member.getJavaScriptUnit()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (fieldReferenced.getDeclaringType().getPackageFragment().equals(member.getDeclaringType().getPackageFragment()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (fieldReferenced.getDeclaringType().getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- case IJavaScriptElement.METHOD: {
- final IFunction methodReferenced= (IFunction) referenced;
- final IJavaScriptUnit referencedUnit= methodReferenced.getJavaScriptUnit();
- switch (referencingType) {
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToMethod((IType) referencing, methodReferenced, monitor);
- break;
- }
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD: {
- final IMember member= (IMember) referencing;
- if (methodReferenced.getDeclaringType().equals(member.getDeclaringType()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.equals(member.getJavaScriptUnit()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (methodReferenced.getDeclaringType().getPackageFragment().equals(member.getDeclaringType().getPackageFragment()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (methodReferenced.getDeclaringType().getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- default:
- Assert.isTrue(false);
- }
- } finally {
- monitor.done();
- }
- return keyword;
- }
-
- /**
- * Computes the visibility threshold for the referenced element.
- *
- * @param referencing the referencing element
- * @param referenced the referenced element
- * @param monitor the progress monitor to use
- * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- private ModifierKeyword computeOutgoingVisibilityThreshold(final IJavaScriptElement referencing, final IMember referenced, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isTrue(referencing instanceof IJavaScriptUnit || referencing instanceof IType || referencing instanceof IPackageFragment);
- Assert.isTrue(referenced instanceof IType || referenced instanceof IField || referenced instanceof IFunction);
- ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- final int referencingType= referencing.getElementType();
- final int referencedType= referenced.getElementType();
- switch (referencedType) {
- case IJavaScriptElement.TYPE: {
- final IType typeReferenced= (IType) referenced;
- switch (referencingType) {
- case IJavaScriptElement.JAVASCRIPT_UNIT: {
- final IJavaScriptUnit unit= (IJavaScriptUnit) referencing;
- final IJavaScriptUnit referencedUnit= typeReferenced.getJavaScriptUnit();
- if (referencedUnit != null && referencedUnit.equals(unit))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.getParent().equals(unit.getParent()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToType((IType) referencing, typeReferenced, monitor);
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (typeReferenced.getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- case IJavaScriptElement.FIELD: {
- final IField fieldReferenced= (IField) referenced;
- final IJavaScriptUnit referencedUnit= fieldReferenced.getJavaScriptUnit();
- switch (referencingType) {
- case IJavaScriptElement.JAVASCRIPT_UNIT: {
- final IJavaScriptUnit unit= (IJavaScriptUnit) referencing;
- if (referencedUnit != null && referencedUnit.equals(unit))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.getParent().equals(unit.getParent()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToField((IType) referencing, fieldReferenced, monitor);
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (fieldReferenced.getDeclaringType().getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- case IJavaScriptElement.METHOD: {
- final IFunction methodReferenced= (IFunction) referenced;
- final IJavaScriptUnit referencedUnit= methodReferenced.getJavaScriptUnit();
- switch (referencingType) {
- case IJavaScriptElement.JAVASCRIPT_UNIT: {
- final IJavaScriptUnit unit= (IJavaScriptUnit) referencing;
- if (referencedUnit != null && referencedUnit.equals(unit))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && referencedUnit.getParent().equals(unit.getParent()))
- keyword= null;
- break;
- }
- case IJavaScriptElement.TYPE: {
- keyword= thresholdTypeToMethod((IType) referencing, methodReferenced, monitor);
- break;
- }
- case IJavaScriptElement.PACKAGE_FRAGMENT: {
- final IPackageFragment fragment= (IPackageFragment) referencing;
- if (methodReferenced.getDeclaringType().getPackageFragment().equals(fragment))
- keyword= null;
- break;
- }
- default:
- Assert.isTrue(false);
- }
- break;
- }
- default:
- Assert.isTrue(false);
- }
- } finally {
- monitor.done();
- }
- return keyword;
- }
-
- /**
- * Returns the existing visibility adjustments (element type: Map <IMember, IVisibilityAdjustment>).
- *
- * @return the visibility adjustments
- */
- public final Map getAdjustments() {
- return fAdjustments;
- }
-
- /**
- * Returns a compilation unit rewrite for the specified compilation unit.
- *
- * @param unit the compilation unit to get the rewrite for
- * @return the rewrite for the compilation unit
- */
- private CompilationUnitRewrite getCompilationUnitRewrite(final IJavaScriptUnit unit) {
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) fRewrites.get(unit);
- if (rewrite == null) {
- if (fOwner == null)
- rewrite= new CompilationUnitRewrite(unit);
- else
- rewrite= new CompilationUnitRewrite(fOwner, unit);
- }
- return rewrite;
- }
-
- /**
- * Returns a cached type hierarchy for the specified type.
- *
- * @param type the type to get the hierarchy for
- * @param monitor the progress monitor to use
- * @return the type hierarchy
- * @throws JavaScriptModelException if the type hierarchy could not be created
- */
- private ITypeHierarchy getTypeHierarchy(final IType type, final IProgressMonitor monitor) throws JavaScriptModelException {
- ITypeHierarchy hierarchy= null;
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
- try {
- hierarchy= (ITypeHierarchy) fTypeHierarchies.get(type);
- if (hierarchy == null) {
- if (fOwner == null)
- hierarchy= type.newSupertypeHierarchy(new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- else
- hierarchy= type.newSupertypeHierarchy(fOwner, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- }
- } finally {
- monitor.done();
- }
- } finally {
- monitor.done();
- }
- return hierarchy;
- }
-
- /**
- * Does the specified member need further visibility adjustment?
- *
- * @param member the member to test
- * @param threshold the visibility threshold to test for
- * @return <code>true</code> if the member needs further adjustment, <code>false</code> otherwise
- */
- private boolean needsVisibilityAdjustment(final IMember member, final ModifierKeyword threshold) {
- Assert.isNotNull(member);
- return needsVisibilityAdjustments(member, threshold, fAdjustments);
- }
-
- /**
- * Rewrites the computed adjustments for the specified compilation unit.
- *
- * @param unit the compilation unit to rewrite the adjustments
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void rewriteVisibility(final IJavaScriptUnit unit, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask("", fAdjustments.keySet().size()); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting);
- IMember member= null;
- IVisibilityAdjustment adjustment= null;
- for (final Iterator iterator= fAdjustments.keySet().iterator(); iterator.hasNext();) {
- member= (IMember) iterator.next();
- if (unit.equals(member.getJavaScriptUnit())) {
- adjustment= (IVisibilityAdjustment) fAdjustments.get(member);
- if (adjustment != null)
- adjustment.rewriteVisibility(this, new SubProgressMonitor(monitor, 1));
- }
- }
- } finally {
- fTypeHierarchies.clear();
- monitor.done();
- }
- }
-
- /**
- * Rewrites the computed adjustments.
- *
- * @param monitor the progress monitor to use
- * @throws JavaScriptModelException if an error occurs during search
- */
- public final void rewriteVisibility(final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask("", fAdjustments.keySet().size()); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting);
- IMember member= null;
- IVisibilityAdjustment adjustment= null;
- for (final Iterator iterator= fAdjustments.keySet().iterator(); iterator.hasNext();) {
- member= (IMember) iterator.next();
- adjustment= (IVisibilityAdjustment) fAdjustments.get(member);
- if (adjustment != null)
- adjustment.rewriteVisibility(this, new SubProgressMonitor(monitor, 1));
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
- } finally {
- fTypeHierarchies.clear();
- monitor.done();
- }
- }
-
- /**
- * Sets the existing visibility adjustments to be taken into account (element type: Map <IMember, IVisibilityAdjustment>).
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to take no existing adjustments into account.
- *
- * @param adjustments the existing adjustments to set
- */
- public final void setAdjustments(final Map adjustments) {
- Assert.isNotNull(adjustments);
- fAdjustments= adjustments;
- }
-
- /**
- * Sets the severity of failure messages.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is a status with value {@link RefactoringStatus#ERROR}.
- *
- * @param severity the severity of failure messages
- */
- public final void setFailureSeverity(final int severity) {
- Assert.isTrue(isStatusSeverity(severity));
- }
-
- /**
- * Determines whether incoming references should be adjusted.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to adjust incoming references.
- *
- * @param incoming <code>true</code> if incoming references should be adjusted, <code>false</code> otherwise
- */
- public final void setIncoming(final boolean incoming) {
- fIncoming= incoming;
- }
-
- /**
- * Determines whether outgoing references should be adjusted.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to adjust outgoing references.
- *
- * @param outgoing <code>true</code> if outgoing references should be adjusted, <code>false</code> otherwise
- */
- public final void setOutgoing(final boolean outgoing) {
- fOutgoing= outgoing;
- }
-
- /**
- * Sets the AST rewrite to use for member visibility adjustments.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to use a compilation unit rewrite.
- *
- * @param rewrite the AST rewrite to set
- * @param root the root of the AST used in the rewrite
- */
- public final void setRewrite(final ASTRewrite rewrite, final JavaScriptUnit root) {
- Assert.isTrue(rewrite == null || root != null);
- fRewrite= rewrite;
- fRoot= root;
- }
-
- /**
- * Sets the compilation unit rewrites used by this adjustor (element type: Map <IJavaScriptUnit, CompilationUnitRewrite>).
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to use no existing rewrites.
- *
- * @param rewrites the map of compilation units to compilation unit rewrites to set
- */
- public final void setRewrites(final Map rewrites) {
- Assert.isNotNull(rewrites);
- fRewrites= rewrites;
- }
-
- /**
- * Sets the incoming search scope used by this adjustor.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is the whole workspace as scope.
- *
- * @param scope the search scope to set
- */
- public final void setScope(final IJavaScriptSearchScope scope) {
- Assert.isNotNull(scope);
- fScope= scope;
- }
-
- /**
- * Sets the working copy owner used by this adjustor.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is to use none.
- *
- * @param owner the working copy owner, or <code>null</code> to use none
- */
- public final void setOwner(final WorkingCopyOwner owner) {
- fOwner= owner;
- }
-
- /**
- * Sets the refactoring status used by this adjustor.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is a fresh status with status {@link RefactoringStatus#OK}.
- *
- * @param status the refactoring status to set
- */
- public final void setStatus(final RefactoringStatus status) {
- Assert.isNotNull(status);
- fStatus= status;
- }
-
- /**
- * Sets the severity of visibility messages.
- * <p>
- * This method must be called before calling {@link MemberVisibilityAdjustor#adjustVisibility(IProgressMonitor)}. The default is a status with value {@link RefactoringStatus#WARNING}.
- *
- * @param severity the severity of visibility messages
- */
- public final void setVisibilitySeverity(final int severity) {
- Assert.isTrue(isStatusSeverity(severity));
- fVisibilitySeverity= severity;
- }
-
- /**
- * Returns the visibility threshold from a type to a field.
- *
- * @param referencing the referencing type
- * @param referenced the referenced field
- * @param monitor the progress monitor to use
- * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- private ModifierKeyword thresholdTypeToField(final IType referencing, final IField referenced, final IProgressMonitor monitor) throws JavaScriptModelException {
- ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
- final IJavaScriptUnit referencedUnit= referenced.getJavaScriptUnit();
- if (referenced.getDeclaringType().equals(referencing))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else {
- final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
- final IType superType= hierarchy.getSuperclass(referencing);
-
- if (superType.equals(referenced.getDeclaringType())) {
- keyword= ModifierKeyword.PROTECTED_KEYWORD;
- return keyword;
- }
- }
- final IJavaScriptUnit typeUnit= referencing.getJavaScriptUnit();
- if (referencedUnit != null && referencedUnit.equals(typeUnit))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
- keyword= null;
- return keyword;
- }
-
- /**
- * Returns the visibility threshold from a type to a method.
- *
- * @param referencing the referencing type
- * @param referenced the referenced method
- * @param monitor the progress monitor to use
- * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- private ModifierKeyword thresholdTypeToMethod(final IType referencing, final IFunction referenced, final IProgressMonitor monitor) throws JavaScriptModelException {
- final IJavaScriptUnit referencedUnit= referenced.getJavaScriptUnit();
- ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
- if (referenced.getDeclaringType().equals(referencing))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else {
- final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
- final IType superType= hierarchy.getSuperclass(referencing);
-
- if (superType.equals(referenced.getDeclaringType())) {
- keyword= ModifierKeyword.PROTECTED_KEYWORD;
- return keyword;
- }
-
- }
- final IJavaScriptUnit typeUnit= referencing.getJavaScriptUnit();
- if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
- if (referenced.getDeclaringType().getDeclaringType() != null)
- keyword= null;
- else
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- } else if (referencedUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
- keyword= null;
- return keyword;
- }
-
- /**
- * Returns the visibility threshold from a type to another type.
- *
- * @param referencing the referencing type
- * @param referenced the referenced type
- * @param monitor the progress monitor to use
- * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
- * @throws JavaScriptModelException if the java elements could not be accessed
- */
- private ModifierKeyword thresholdTypeToType(final IType referencing, final IType referenced, final IProgressMonitor monitor) throws JavaScriptModelException {
- ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
- final IJavaScriptUnit referencedUnit= referenced.getJavaScriptUnit();
- if (referencing.equals(referenced.getDeclaringType()))
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- else {
- final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
- final IType superType = hierarchy.getSuperclass(referencing);
-
- if (superType.equals(referenced)) {
- keyword= null;
- return keyword;
- }
- }
- final IJavaScriptUnit typeUnit= referencing.getJavaScriptUnit();
- if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
- if (referenced.getDeclaringType() != null)
- keyword= null;
- else
- keyword= ModifierKeyword.PRIVATE_KEYWORD;
- } else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
- keyword= null;
- return keyword;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
deleted file mode 100644
index 591ae670..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
+++ /dev/null
@@ -1,1488 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.IRefactoringStatusEntryComparator;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CreateCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavadocUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public final class MoveInnerToTopRefactoring extends ScriptableRefactoring {
-
- private static final String ATTRIBUTE_FIELD= "field"; //$NON-NLS-1$
- private static final String ATTRIBUTE_MANDATORY= "mandatory"; //$NON-NLS-1$
- private static final String ATTRIBUTE_POSSIBLE= "possible"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FINAL= "final"; //$NON-NLS-1$
- private static final String ATTRIBUTE_FIELD_NAME= "fieldName"; //$NON-NLS-1$
- private static final String ATTRIBUTE_PARAMETER_NAME= "parameterName"; //$NON-NLS-1$
-
- private static class MemberAccessNodeCollector extends ASTVisitor {
-
- private final List fFieldAccesses= new ArrayList(0);
-
- private final ITypeHierarchy fHierarchy;
-
- private final List fMethodAccesses= new ArrayList(0);
-
- private final List fSimpleNames= new ArrayList(0);
-
- MemberAccessNodeCollector(ITypeHierarchy hierarchy) {
- Assert.isNotNull(hierarchy);
- fHierarchy= hierarchy;
- }
-
- FieldAccess[] getFieldAccesses() {
- return (FieldAccess[]) fFieldAccesses.toArray(new FieldAccess[fFieldAccesses.size()]);
- }
-
- FunctionInvocation[] getMethodInvocations() {
- return (FunctionInvocation[]) fMethodAccesses.toArray(new FunctionInvocation[fMethodAccesses.size()]);
- }
-
- SimpleName[] getSimpleFieldNames() {
- return (SimpleName[]) fSimpleNames.toArray(new SimpleName[fSimpleNames.size()]);
- }
-
- public boolean visit(FieldAccess node) {
- final ITypeBinding declaring= MoveInnerToTopRefactoring.getDeclaringTypeBinding(node);
- if (declaring != null) {
- final IType type= (IType) declaring.getJavaElement();
- if (type != null && fHierarchy.contains(type))
- fFieldAccesses.add(node);
- }
- return super.visit(node);
- }
-
- public boolean visit(FunctionInvocation node) {
- final ITypeBinding declaring= MoveInnerToTopRefactoring.getDeclaringTypeBinding(node);
- if (declaring != null) {
- final IType type= (IType) declaring.getJavaElement();
- if (type != null && fHierarchy.contains(type))
- fMethodAccesses.add(node);
- }
- return super.visit(node);
- }
-
- public boolean visit(SimpleName node) {
- if (node.getParent() instanceof QualifiedName)
- return super.visit(node);
- IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding) {
- IVariableBinding variable= (IVariableBinding) binding;
- ITypeBinding declaring= variable.getDeclaringClass();
- if (variable.isField() && declaring != null) {
- final IType type= (IType) declaring.getJavaElement();
- if (type != null && fHierarchy.contains(type)) {
- fSimpleNames.add(node);
- return false;
- }
- }
- }
- return super.visit(node);
- }
-
- public boolean visit(ThisExpression node) {
- final Name qualifier= node.getQualifier();
- if (qualifier != null) {
- final ITypeBinding binding= qualifier.resolveTypeBinding();
- if (binding != null) {
- final IType type= (IType) binding.getJavaElement();
- if (type != null && fHierarchy.contains(type)) {
- fSimpleNames.add(qualifier);
- return false;
- }
- }
- }
- return super.visit(node);
- }
- }
-
- private class TypeReferenceQualifier extends ASTVisitor {
-
- private final TextEditGroup fGroup;
-
- private final ITypeBinding fTypeBinding;
-
- public TypeReferenceQualifier(final ITypeBinding type, final TextEditGroup group) {
- Assert.isNotNull(type);
- Assert.isNotNull(type.getDeclaringClass());
- fTypeBinding= type;
- fGroup= group;
- }
-
- public boolean visit(final ClassInstanceCreation node) {
- Assert.isNotNull(node);
- if (fCreateInstanceField) {
- final AST ast= node.getAST();
- final Type type= node.getType();
- final ITypeBinding binding= type.resolveBinding();
- if (binding != null && binding.getDeclaringClass() != null && !Bindings.equals(binding, fTypeBinding) && fSourceRewrite.getRoot().findDeclaringNode(binding) != null) {
- if (!Modifier.isStatic(binding.getModifiers())) {
- Expression expression= null;
- if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- expression= access;
- } else
- expression= ast.newSimpleName(fEnclosingInstanceFieldName);
- if (node.getExpression() != null)
- fSourceRewrite.getImportRemover().registerRemovedNode(node.getExpression());
- fSourceRewrite.getASTRewrite().set(node, ClassInstanceCreation.EXPRESSION_PROPERTY, expression, fGroup);
- } else
- addTypeQualification(type, fSourceRewrite, fGroup);
- }
- }
- return true;
- }
-
- public boolean visit(final QualifiedType node) {
- Assert.isNotNull(node);
- return false;
- }
-
- public boolean visit(final SimpleType node) {
- Assert.isNotNull(node);
- if (!(node.getParent() instanceof ClassInstanceCreation)) {
- final ITypeBinding binding= node.resolveBinding();
- if (binding != null) {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null && !Bindings.equals(declaring, fTypeBinding.getDeclaringClass()) && !Bindings.equals(binding, fTypeBinding) && fSourceRewrite.getRoot().findDeclaringNode(binding) != null && Modifier.isStatic(binding.getModifiers()))
- addTypeQualification(node, fSourceRewrite, fGroup);
- }
- }
- return super.visit(node);
- }
-
- public boolean visit(final ThisExpression node) {
- Assert.isNotNull(node);
- final Name name= node.getQualifier();
- if (name != null && name.isSimpleName()) {
- final AST ast= node.getAST();
- Expression expression= null;
- if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- expression= access;
- } else
- expression= ast.newSimpleName(fEnclosingInstanceFieldName);
- fSourceRewrite.getASTRewrite().replace(node, expression, null);
- }
- return super.visit(node);
- }
- }
-
- private static boolean containsNonStatic(FieldAccess[] accesses) {
- for (int i= 0; i < accesses.length; i++) {
- if (!isStatic(accesses[i]))
- return true;
- }
- return false;
- }
-
- private static boolean containsNonStatic(FunctionInvocation[] invocations) {
- for (int i= 0; i < invocations.length; i++) {
- if (!isStatic(invocations[i]))
- return true;
- }
- return false;
- }
-
- private static boolean containsNonStatic(SimpleName[] fieldNames) {
- for (int i= 0; i < fieldNames.length; i++) {
- if (!isStaticFieldName(fieldNames[i]))
- return true;
- }
- return false;
- }
-
- private static boolean containsStatusEntry(final RefactoringStatus status, final RefactoringStatusEntry other) {
- return status.getEntries(new IRefactoringStatusEntryComparator() {
-
- public final int compare(final RefactoringStatusEntry entry1, final RefactoringStatusEntry entry2) {
- return entry1.getMessage().compareTo(entry2.getMessage());
- }
- }, other).length > 0;
- }
-
- private static AbstractTypeDeclaration findTypeDeclaration(IType enclosing, AbstractTypeDeclaration[] declarations) {
- String typeName= enclosing.getElementName();
- for (int i= 0; i < declarations.length; i++) {
- AbstractTypeDeclaration declaration= declarations[i];
- if (declaration.getName().getIdentifier().equals(typeName))
- return declaration;
- }
- return null;
- }
-
- private static AbstractTypeDeclaration findTypeDeclaration(IType type, JavaScriptUnit unit) {
- final List types= getDeclaringTypes(type);
- types.add(type);
- AbstractTypeDeclaration[] declarations= (AbstractTypeDeclaration[]) unit.types().toArray(new AbstractTypeDeclaration[unit.types().size()]);
- AbstractTypeDeclaration declaration= null;
- for (final Iterator iterator= types.iterator(); iterator.hasNext();) {
- IType enclosing= (IType) iterator.next();
- declaration= findTypeDeclaration(enclosing, declarations);
- Assert.isNotNull(declaration);
- declarations= getAbstractTypeDeclarations(declaration);
- }
- Assert.isNotNull(declaration);
- return declaration;
- }
-
- public static AbstractTypeDeclaration[] getAbstractTypeDeclarations(final AbstractTypeDeclaration declaration) {
- int typeCount= 0;
- for (Iterator iterator= declaration.bodyDeclarations().listIterator(); iterator.hasNext();) {
- if (iterator.next() instanceof AbstractTypeDeclaration) {
- typeCount++;
- }
- }
- AbstractTypeDeclaration[] declarations= new AbstractTypeDeclaration[typeCount];
- int next= 0;
- for (final Iterator iterator= declaration.bodyDeclarations().listIterator(); iterator.hasNext();) {
- Object object= iterator.next();
- if (object instanceof AbstractTypeDeclaration) {
- declarations[next++]= (AbstractTypeDeclaration) object;
- }
- }
- return declarations;
- }
-
- private static ITypeBinding getDeclaringTypeBinding(FieldAccess fieldAccess) {
- IVariableBinding varBinding= fieldAccess.resolveFieldBinding();
- if (varBinding == null)
- return null;
- return varBinding.getDeclaringClass();
- }
-
- private static ITypeBinding getDeclaringTypeBinding(FunctionInvocation methodInvocation) {
- IFunctionBinding binding= methodInvocation.resolveMethodBinding();
- if (binding == null)
- return null;
- return binding.getDeclaringClass();
- }
-
- // List of ITypes
- private static List getDeclaringTypes(IType type) {
- IType declaringType= type.getDeclaringType();
- if (declaringType == null)
- return new ArrayList(0);
- List result= getDeclaringTypes(declaringType);
- result.add(declaringType);
- return result;
- }
-
- private static String[] getFieldNames(IType type) {
- try {
- IField[] fields= type.getFields();
- List result= new ArrayList(fields.length);
- for (int i= 0; i < fields.length; i++) {
- result.add(fields[i].getElementName());
- }
- return (String[]) result.toArray(new String[result.size()]);
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
-
- private static Set getMergedSet(Set s1, Set s2) {
- Set result= new HashSet();
- result.addAll(s1);
- result.addAll(s2);
- return result;
- }
-
- private static String[] getParameterNamesOfAllConstructors(IType type) throws JavaScriptModelException {
- IFunction[] constructors= JavaElementUtil.getAllConstructors(type);
- Set result= new HashSet();
- for (int i= 0; i < constructors.length; i++) {
- result.addAll(Arrays.asList(constructors[i].getParameterNames()));
- }
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- private static ASTNode[] getReferenceNodesIn(JavaScriptUnit cuNode, Map references, IJavaScriptUnit cu) {
- SearchMatch[] results= (SearchMatch[]) references.get(cu);
- if (results == null)
- return new ASTNode[0];
- return ASTNodeSearchUtil.getAstNodes(results, cuNode);
- }
-
- private static boolean isCorrespondingTypeBinding(ITypeBinding binding, IType type) {
- if (binding == null)
- return false;
- return Bindings.getFullyQualifiedName(binding).equals(JavaElementUtil.createSignature(type));
- }
-
- private static boolean isStatic(FieldAccess access) {
- IVariableBinding fieldBinding= access.resolveFieldBinding();
- if (fieldBinding == null)
- return false;
- return JdtFlags.isStatic(fieldBinding);
- }
-
- private static boolean isStatic(FunctionInvocation invocation) {
- IFunctionBinding methodBinding= invocation.resolveMethodBinding();
- if (methodBinding == null)
- return false;
- return JdtFlags.isStatic(methodBinding);
- }
-
- private static boolean isStaticFieldName(SimpleName name) {
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return false;
- IVariableBinding variableBinding= (IVariableBinding) binding;
- if (!variableBinding.isField())
- return false;
- return JdtFlags.isStatic(variableBinding);
- }
-
- private TextChangeManager fChangeManager;
-
- private CodeGenerationSettings fCodeGenerationSettings;
-
- private boolean fCreateInstanceField;
-
- private String fEnclosingInstanceFieldName;
-
- private boolean fIsInstanceFieldCreationMandatory;
-
- private boolean fIsInstanceFieldCreationPossible;
-
- private boolean fMarkInstanceFieldAsFinal;
-
- private String fNameForEnclosingInstanceConstructorParameter;
-
- private String fNewSourceOfInputType;
-
- private CompilationUnitRewrite fSourceRewrite;
-
- private Collection fStaticImports;
-
- private IType fType;
-
- private String fQualifiedTypeName;
-
- private Collection fTypeImports;
-
- /**
- * Creates a new move inner to top refactoring.
- * @param type the type, or <code>null</code> if invoked by scripting
- * @param settings the code generation settings, or <code>null</code> if invoked by scripting
- * @throws JavaScriptModelException
- */
- public MoveInnerToTopRefactoring(IType type, CodeGenerationSettings settings) throws JavaScriptModelException {
- fType= type;
- fCodeGenerationSettings= settings;
- fMarkInstanceFieldAsFinal= true; // default
- if (fType != null)
- initialize();
- }
-
- private void initialize() throws JavaScriptModelException {
- fQualifiedTypeName= JavaModelUtil.concatenateName(fType.getPackageFragment().getElementName(), fType.getElementName());
- fEnclosingInstanceFieldName= getInitialNameForEnclosingInstanceField();
- fSourceRewrite= new CompilationUnitRewrite(fType.getJavaScriptUnit());
- fIsInstanceFieldCreationPossible= !(JdtFlags.isStatic(fType));
- fIsInstanceFieldCreationMandatory= fIsInstanceFieldCreationPossible && isInstanceFieldCreationMandatory();
- fCreateInstanceField= fIsInstanceFieldCreationMandatory;
- }
-
- private void addEnclosingInstanceDeclaration(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- final AST ast= declaration.getAST();
- final VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
- fragment.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- final FieldDeclaration newField= ast.newFieldDeclaration(fragment);
- newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getEnclosingInstanceAccessModifiers()));
- newField.setType(createEnclosingType(ast));
- final String comment= CodeGeneration.getFieldComment(fType.getJavaScriptUnit(), declaration.getName().getIdentifier(), fEnclosingInstanceFieldName, StubUtility.getLineDelimiterUsed(fType.getJavaScriptProject()));
- if (comment != null && comment.length() > 0) {
- final JSdoc doc= (JSdoc) rewrite.createStringPlaceholder(comment, ASTNode.JSDOC);
- newField.setJavadoc(doc);
- }
- rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(newField, null);
- }
-
- private void addImportsToTargetUnit(final IJavaScriptUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaScriptModelException {
- monitor.beginTask("", 2); //$NON-NLS-1$
- try {
- ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true);
- if (fTypeImports != null) {
- ITypeBinding type= null;
- for (final Iterator iterator= fTypeImports.iterator(); iterator.hasNext();) {
- type= (ITypeBinding) iterator.next();
- rewrite.addImport(type);
- }
- }
- if (fStaticImports != null) {
- IBinding binding= null;
- for (final Iterator iterator= fStaticImports.iterator(); iterator.hasNext();) {
- binding= (IBinding) iterator.next();
- rewrite.addStaticImport(binding);
- }
- }
- fTypeImports= null;
- fStaticImports= null;
- TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
- JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1));
- } finally {
- monitor.done();
- }
- }
-
- private void addInheritedTypeQualifications(final AbstractTypeDeclaration declaration, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
- Assert.isNotNull(declaration);
- Assert.isNotNull(targetRewrite);
- final JavaScriptUnit unit= (JavaScriptUnit) declaration.getRoot();
- final ITypeBinding binding= declaration.resolveBinding();
- if (binding != null) {
- Type type= null;
- if (declaration instanceof TypeDeclaration) {
- type= ((TypeDeclaration) declaration).getSuperclassType();
- if (type != null && unit.findDeclaringNode(binding) != null)
- addTypeQualification(type, targetRewrite, group);
- }
- }
- }
-
- private void addParameterToConstructor(final ASTRewrite rewrite, final FunctionDeclaration declaration) throws JavaScriptModelException {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(declaration);
- final AST ast= declaration.getAST();
- final String name= getNameForEnclosingInstanceConstructorParameter();
- final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
- variable.setType(createEnclosingType(ast));
- variable.setName(ast.newSimpleName(name));
- rewrite.getListRewrite(declaration, FunctionDeclaration.PARAMETERS_PROPERTY).insertFirst(variable, null);
- JavadocUtil.addParamJavadoc(name, declaration, rewrite, fType.getJavaScriptProject(), null);
- }
-
- private void addSimpleTypeQualification(final CompilationUnitRewrite targetRewrite, final ITypeBinding declaring, final SimpleType simpleType, final TextEditGroup group) {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(declaring);
- Assert.isNotNull(simpleType);
- final AST ast= targetRewrite.getRoot().getAST();
- if (!(simpleType.getName() instanceof QualifiedName)) {
- targetRewrite.getASTRewrite().replace(simpleType, ast.newQualifiedType(targetRewrite.getImportRewrite().addImport(declaring, ast), ast.newSimpleName(simpleType.getName().getFullyQualifiedName())), group);
- targetRewrite.getImportRemover().registerRemovedNode(simpleType);
- }
- }
-
- private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
- Assert.isNotNull(type);
- Assert.isNotNull(targetRewrite);
- final ITypeBinding binding= type.resolveBinding();
- if (binding != null) {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null) {
- if (type instanceof SimpleType) {
- final SimpleType simpleType= (SimpleType) type;
- addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
- }
- }
- }
- }
-
- private RefactoringStatus checkConstructorParameterNames() {
- RefactoringStatus result= new RefactoringStatus();
- JavaScriptUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(fType.getJavaScriptUnit(), false);
- FunctionDeclaration[] nodes= getConstructorDeclarationNodes(findTypeDeclaration(fType, cuNode));
- for (int i= 0; i < nodes.length; i++) {
- FunctionDeclaration constructor= nodes[i];
- for (Iterator iter= constructor.parameters().iterator(); iter.hasNext();) {
- SingleVariableDeclaration param= (SingleVariableDeclaration) iter.next();
- if (fEnclosingInstanceFieldName.equals(param.getName().getIdentifier())) {
- String msg= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_name_used, new String[] { param.getName().getIdentifier(), fType.getElementName()});
- result.addError(msg, JavaStatusContext.create(fType.getJavaScriptUnit(), param));
- }
- }
- }
- return result;
- }
-
- public RefactoringStatus checkEnclosingInstanceName(String name) {
- if (!fCreateInstanceField)
- return new RefactoringStatus();
- RefactoringStatus result= Checks.checkFieldName(name);
- if (!Checks.startsWithLowerCase(name))
- result.addWarning(RefactoringCoreMessages.MoveInnerToTopRefactoring_names_start_lowercase);
-
- if (fType.getField(name).exists()) {
- Object[] keys= new String[] { name, fType.getElementName()};
- String msg= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_already_declared, keys);
- result.addError(msg, JavaStatusContext.create(fType.getField(name)));
- }
- return result;
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 2);//$NON-NLS-1$
- try {
- RefactoringStatus result= new RefactoringStatus();
-
- if (JdtFlags.isStatic(fType))
- result.merge(checkEnclosingInstanceName(fEnclosingInstanceFieldName));
-
- if (fType.getPackageFragment().getJavaScriptUnit((JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), fType.getElementName()))).exists()) {
- String message= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_compilation_Unit_exists, new String[] { (JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), fType.getElementName())), fType.getPackageFragment().getElementName()});
- result.addFatalError(message);
- }
- result.merge(checkEnclosingInstanceName(fEnclosingInstanceFieldName));
- result.merge(Checks.checkCompilationUnitName((JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), fType.getElementName()))));
- result.merge(checkConstructorParameterNames());
- result.merge(checkTypeNameInPackage());
- fChangeManager= createChangeManager(new SubProgressMonitor(pm, 1), result);
- result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), getValidationContext()));
- return result;
- } finally {
- pm.done();
- }
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException {
- return Checks.checkIfCuBroken(fType);
- }
-
- private RefactoringStatus checkTypeNameInPackage() throws JavaScriptModelException {
- IType type= Checks.findTypeInPackage(fType.getPackageFragment(), fType.getElementName());
- if (type == null || !type.exists())
- return null;
- String message= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_type_exists, new String[] { fType.getElementName(), fType.getPackageFragment().getElementName()});
- return RefactoringStatus.createErrorStatus(message);
- }
-
- private Expression createAccessExpressionToEnclosingInstanceFieldText(ASTNode node, IBinding binding, AbstractTypeDeclaration declaration) {
- if (Modifier.isStatic(binding.getModifiers()))
- return node.getAST().newName(JavaModelUtil.getTypeQualifiedName(fType.getDeclaringType()));
- else if ((isInAnonymousTypeInsideInputType(node, declaration) || isInLocalTypeInsideInputType(node, declaration) || isInNonStaticMemberTypeInsideInputType(node, declaration)))
- return createQualifiedReadAccessExpressionForEnclosingInstance(node.getAST());
- else
- return createReadAccessExpressionForEnclosingInstance(node.getAST());
- }
-
- public Change createChange(final IProgressMonitor monitor) throws CoreException {
- monitor.beginTask(RefactoringCoreMessages.MoveInnerToTopRefactoring_creating_change, 1);
- final Map arguments= new HashMap();
- String project= null;
- IJavaScriptProject javaProject= fType.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- final String description= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_descriptor_description_short, fType.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fType.getParent(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_original_pattern, JavaScriptElementLabels.getElementLabel(fType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- final boolean enclosing= fEnclosingInstanceFieldName != null && !"".equals(fEnclosingInstanceFieldName); //$NON-NLS-1$
- if (enclosing)
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_field_pattern, fEnclosingInstanceFieldName));
- if (fNameForEnclosingInstanceConstructorParameter != null && !"".equals(fNameForEnclosingInstanceConstructorParameter)) //$NON-NLS-1$
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_parameter_pattern, fNameForEnclosingInstanceConstructorParameter));
- if (enclosing && fMarkInstanceFieldAsFinal)
- comment.addSetting(RefactoringCoreMessages.MoveInnerToTopRefactoring_declare_final);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.CONVERT_MEMBER_TYPE, project, description, comment.asString(), arguments, RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.STRUCTURAL_CHANGE | JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fType));
- if (enclosing)
- arguments.put(ATTRIBUTE_FIELD_NAME, fEnclosingInstanceFieldName);
- if (fNameForEnclosingInstanceConstructorParameter != null && !"".equals(fNameForEnclosingInstanceConstructorParameter)) //$NON-NLS-1$
- arguments.put(ATTRIBUTE_PARAMETER_NAME, fNameForEnclosingInstanceConstructorParameter);
- arguments.put(ATTRIBUTE_FIELD, Boolean.valueOf(fCreateInstanceField).toString());
- arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fMarkInstanceFieldAsFinal).toString());
- arguments.put(ATTRIBUTE_POSSIBLE, Boolean.valueOf(fIsInstanceFieldCreationPossible).toString());
- arguments.put(ATTRIBUTE_MANDATORY, Boolean.valueOf(fIsInstanceFieldCreationMandatory).toString());
- final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.MoveInnerToTopRefactoring_move_to_Top);
- result.addAll(fChangeManager.getAllChanges());
- result.add(createCompilationUnitForMovedType(new SubProgressMonitor(monitor, 1)));
- return result;
- }
-
- private TextChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- final TextChangeManager manager= new TextChangeManager();
- try {
- monitor.beginTask(RefactoringCoreMessages.MoveInnerToTopRefactoring_creating_preview, 4);
- final Map rewrites= new HashMap(2);
- fSourceRewrite.clearASTAndImportRewrites();
- rewrites.put(fSourceRewrite.getCu(), fSourceRewrite);
- final MemberVisibilityAdjustor adjustor= new MemberVisibilityAdjustor(fType.getPackageFragment(), fType);
- adjustor.setRewrites(rewrites);
- adjustor.setVisibilitySeverity(RefactoringStatus.WARNING);
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
- adjustor.setStatus(status);
- adjustor.adjustVisibility(new SubProgressMonitor(monitor, 1));
- final Map parameters= new LinkedHashMap();
- final ITypeBinding[] bindings= new ITypeBinding[parameters.values().size()];
- parameters.values().toArray(bindings);
- final Map typeReferences= createTypeReferencesMapping(new SubProgressMonitor(monitor, 1), status);
- Map constructorReferences= null;
- if (JdtFlags.isStatic(fType))
- constructorReferences= new HashMap(0);
- else
- constructorReferences= createConstructorReferencesMapping(new SubProgressMonitor(monitor, 1), status);
- if (fCreateInstanceField) {
- // must increase visibility of all member types up
- // to the top level type to allow this
- IType type= fType;
- ModifierKeyword keyword= null;
- while ( (type= type.getDeclaringType()) != null) {
- if ((!adjustor.getAdjustments().containsKey(type)) && (Modifier.isPrivate(type.getFlags())))
- adjustor.getAdjustments().put(type, new OutgoingMemberVisibilityAdjustment(type, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning, new String[] { MemberVisibilityAdjustor.getLabel(type), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(type.getJavaScriptUnit(), type.getSourceRange()))));
- }
- }
- monitor.worked(1);
- for (final Iterator iterator= getMergedSet(typeReferences.keySet(), constructorReferences.keySet()).iterator(); iterator.hasNext();) {
- final IJavaScriptUnit unit= (IJavaScriptUnit) iterator.next();
- final CompilationUnitRewrite targetRewrite= getCompilationUnitRewrite(unit);
- createCompilationUnitRewrite(bindings, targetRewrite, typeReferences, constructorReferences, adjustor.getAdjustments().containsKey(fType), fType.getJavaScriptUnit(), unit, false, status, monitor);
- if (unit.equals(fType.getJavaScriptUnit())) {
- try {
- adjustor.setStatus(new RefactoringStatus());
- adjustor.rewriteVisibility(targetRewrite.getCu(), new SubProgressMonitor(monitor, 1));
- } finally {
- adjustor.setStatus(status);
- }
- fNewSourceOfInputType= createNewSource(targetRewrite, unit);
- targetRewrite.clearASTAndImportRewrites();
- createCompilationUnitRewrite(bindings, targetRewrite, typeReferences, constructorReferences, adjustor.getAdjustments().containsKey(fType), fType.getJavaScriptUnit(), unit, true, status, monitor);
- }
- adjustor.rewriteVisibility(targetRewrite.getCu(), new SubProgressMonitor(monitor, 1));
- manager.manage(unit, targetRewrite.createChange());
- }
- } finally {
- monitor.done();
- }
- return manager;
- }
-
- private Change createCompilationUnitForMovedType(IProgressMonitor pm) throws CoreException {
- IJavaScriptUnit newCuWC= null;
- try {
- newCuWC= fType.getPackageFragment().getJavaScriptUnit(JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), fType.getElementName())).getWorkingCopy(null);
- String source= createSourceForNewCu(newCuWC, pm);
- return new CreateCompilationUnitChange(fType.getPackageFragment().getJavaScriptUnit(JavaModelUtil.getRenamedCUName(fType.getJavaScriptUnit(), fType.getElementName())), source, null);
- } finally {
- if (newCuWC != null)
- newCuWC.discardWorkingCopy();
- }
- }
-
- private void createCompilationUnitRewrite(final ITypeBinding[] parameters, final CompilationUnitRewrite targetRewrite, final Map typeReferences, final Map constructorReferences, boolean visibilityWasAdjusted, final IJavaScriptUnit sourceUnit, final IJavaScriptUnit targetUnit, final boolean remove, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(parameters);
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(typeReferences);
- Assert.isNotNull(constructorReferences);
- Assert.isNotNull(sourceUnit);
- Assert.isNotNull(targetUnit);
- final JavaScriptUnit root= targetRewrite.getRoot();
- final ASTRewrite rewrite= targetRewrite.getASTRewrite();
- if (targetUnit.equals(sourceUnit)) {
- final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, root);
- final TextEditGroup qualifierGroup= fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_qualifier);
- ITypeBinding binding= declaration.resolveBinding();
- if (!remove) {
- if (!JdtFlags.isStatic(fType) && fCreateInstanceField) {
- if (JavaElementUtil.getAllConstructors(fType).length == 0)
- createConstructor(declaration, rewrite);
- else
- modifyConstructors(declaration, rewrite);
- addInheritedTypeQualifications(declaration, targetRewrite, qualifierGroup);
- addEnclosingInstanceDeclaration(declaration, rewrite);
- }
- fTypeImports= new HashSet();
- fStaticImports= new HashSet();
- ImportRewriteUtil.collectImports(fType.getJavaScriptProject(), declaration, fTypeImports, fStaticImports, false);
- if (binding != null)
- fTypeImports.remove(binding);
- }
- modifyAccessToEnclosingInstance(targetRewrite, declaration, status, monitor);
- if (binding != null) {
- modifyInterfaceMemberModifiers(binding);
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null)
- declaration.accept(new TypeReferenceQualifier(binding, null));
- }
- final TextEditGroup groupMove= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_label);
- if (remove) {
- rewrite.remove(declaration, groupMove);
- targetRewrite.getImportRemover().registerRemovedNode(declaration);
- } else {
- // Bug 101017/96308: Rewrite the visibility of the element to be
- // moved and add a warning.
-
- // Note that this cannot be done in the MemberVisibilityAdjustor, as the private and
- // static flags must always be cleared when moving to new type.
- int newFlags= JdtFlags.clearFlag(Modifier.STATIC, declaration.getModifiers());
-
- if (!visibilityWasAdjusted) {
- if (Modifier.isPrivate(declaration.getModifiers()) || Modifier.isProtected(declaration.getModifiers())) {
- newFlags= JdtFlags.clearFlag(Modifier.PROTECTED | Modifier.PRIVATE, newFlags);
- final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(fSourceRewrite.getCu()));
- if (!containsStatusEntry(status, entry))
- status.addEntry(entry);
- }
- }
-
- ModifierRewrite.create(rewrite, declaration).setModifiers(newFlags, groupMove);
- }
- }
- ASTNode[] references= getReferenceNodesIn(root, typeReferences, targetUnit);
- for (int index= 0; index < references.length; index++)
- updateTypeReference(parameters, references[index], targetRewrite, targetUnit);
- references= getReferenceNodesIn(root, constructorReferences, targetUnit);
- for (int index= 0; index < references.length; index++)
- updateConstructorReference(parameters, references[index], targetRewrite, targetUnit);
- }
-
- private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- final AST ast= declaration.getAST();
- final FunctionDeclaration constructor= ast.newFunctionDeclaration();
- constructor.setConstructor(true);
- constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
- final String comment= CodeGeneration.getMethodComment(fType.getJavaScriptUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaScriptProject()));
- if (comment != null && comment.length() > 0) {
- final JSdoc doc= (JSdoc) rewrite.createStringPlaceholder(comment, ASTNode.JSDOC);
- constructor.setJavadoc(doc);
- }
- if (fCreateInstanceField) {
- final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
- final String name= getNameForEnclosingInstanceConstructorParameter();
- variable.setName(ast.newSimpleName(name));
- variable.setType(createEnclosingType(ast));
- constructor.parameters().add(variable);
- final Block body= ast.newBlock();
- final Assignment assignment= ast.newAssignment();
- if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- assignment.setLeftHandSide(access);
- } else
- assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
- assignment.setRightHandSide(ast.newSimpleName(name));
- final Statement statement= ast.newExpressionStatement(assignment);
- body.statements().add(statement);
- constructor.setBody(body);
- } else
- constructor.setBody(ast.newBlock());
- rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
- }
-
- // Map<IJavaScriptUnit, SearchMatch[]>
- private Map createConstructorReferencesMapping(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- SearchResultGroup[] groups= ConstructorReferenceFinder.getConstructorReferences(fType, pm, status);
- Map result= new HashMap();
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu == null)
- continue;
- result.put(cu, group.getSearchResults());
- }
- return result;
- }
-
- private Expression createEnclosingInstanceCreationString(final ASTNode node, final IJavaScriptUnit cu) throws JavaScriptModelException {
- Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
- Assert.isNotNull(cu);
- Expression expression= null;
- if (node instanceof ClassInstanceCreation)
- expression= ((ClassInstanceCreation) node).getExpression();
- else
- expression= ((SuperConstructorInvocation) node).getExpression();
- final AST ast= node.getAST();
- if (expression != null)
- return expression;
- else if (JdtFlags.isStatic(fType))
- return null;
- else if (isInsideSubclassOfDeclaringType(node))
- return ast.newThisExpression();
- else if ((node.getStartPosition() >= fType.getSourceRange().getOffset() && ASTNodes.getExclusiveEnd(node) <= fType.getSourceRange().getOffset() + fType.getSourceRange().getLength())) {
- if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- return access;
- } else
- return ast.newSimpleName(fEnclosingInstanceFieldName);
- } else if (isInsideTypeNestedInDeclaringType(node)) {
- final ThisExpression qualified= ast.newThisExpression();
- qualified.setQualifier(ast.newSimpleName(fType.getDeclaringType().getElementName()));
- return qualified;
- }
- return null;
- }
-
- private Type createEnclosingType(final AST ast) throws JavaScriptModelException {
- Assert.isNotNull(ast);
- final Type type= ASTNodeFactory.newType(ast, JavaModelUtil.getTypeQualifiedName(fType.getDeclaringType()));
- return type;
- }
-
- private String createNewSource(final CompilationUnitRewrite targetRewrite, final IJavaScriptUnit unit) throws CoreException, JavaScriptModelException {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(unit);
- TextChange change= targetRewrite.createChange();
- if (change == null)
- change= new CompilationUnitChange("", unit); //$NON-NLS-1$
- final String source= change.getPreviewContent(new NullProgressMonitor());
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(fType.getJavaScriptProject());
- parser.setResolveBindings(false);
- parser.setSource(source.toCharArray());
- final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, (JavaScriptUnit) parser.createAST(null));
- return source.substring(declaration.getStartPosition(), ASTNodes.getExclusiveEnd(declaration));
- }
-
- private Expression createQualifiedReadAccessExpressionForEnclosingInstance(AST ast) {
- ThisExpression expression= ast.newThisExpression();
- expression.setQualifier(ast.newName(new String[] { fType.getElementName()}));
- FieldAccess access= ast.newFieldAccess();
- access.setExpression(expression);
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- return access;
- }
-
- private Expression createReadAccessExpressionForEnclosingInstance(AST ast) {
- if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
- return access;
- }
- return ast.newSimpleName(fEnclosingInstanceFieldName);
- }
-
- private String createSourceForNewCu(final IJavaScriptUnit unit, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(unit);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 2); //$NON-NLS-1$
- final String separator= StubUtility.getLineDelimiterUsed(fType.getJavaScriptProject());
- final String block= getAlignedSourceBlock(unit, fNewSourceOfInputType);
- String content= CodeGeneration.getCompilationUnitContent(unit, null, block, separator);
- if (content == null || block.startsWith("/*") || block.startsWith("//")) { //$NON-NLS-1$//$NON-NLS-2$
- final StringBuffer buffer= new StringBuffer();
- if (!fType.getPackageFragment().isDefaultPackage()) {
- buffer.append("package ").append(fType.getPackageFragment().getElementName()).append(';'); //$NON-NLS-1$
- }
- buffer.append(separator).append(separator);
- buffer.append(block);
- content= buffer.toString();
- }
- unit.getBuffer().setContents(content);
- addImportsToTargetUnit(unit, new SubProgressMonitor(monitor, 1));
- } finally {
- monitor.done();
- }
- return unit.getSource();
- }
-
- // Map<IJavaScriptUnit, SearchMatch[]>
- private Map createTypeReferencesMapping(IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fType, IJavaScriptSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(fType));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(pm, 1));
- final SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
- Map result= new HashMap();
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- IJavaScriptUnit cu= group.getCompilationUnit();
- if (cu == null)
- continue;
- result.put(cu, group.getSearchResults());
- }
- return result;
- }
-
- private String getAlignedSourceBlock(final IJavaScriptUnit unit, final String block) {
- Assert.isNotNull(block);
- final String[] lines= Strings.convertIntoLines(block);
- Strings.trimIndentation(lines, unit.getJavaScriptProject(), false);
- return Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(fType.getJavaScriptProject()));
- }
-
- private CompilationUnitRewrite getCompilationUnitRewrite(final IJavaScriptUnit unit) {
- Assert.isNotNull(unit);
- if (unit.equals(fType.getJavaScriptUnit()))
- return fSourceRewrite;
- return new CompilationUnitRewrite(unit);
- }
-
- private FunctionDeclaration[] getConstructorDeclarationNodes(final AbstractTypeDeclaration declaration) {
- if (declaration instanceof TypeDeclaration) {
- final FunctionDeclaration[] declarations= ((TypeDeclaration) declaration).getMethods();
- final List result= new ArrayList(2);
- for (int index= 0; index < declarations.length; index++) {
- if (declarations[index].isConstructor())
- result.add(declarations[index]);
- }
- return (FunctionDeclaration[]) result.toArray(new FunctionDeclaration[result.size()]);
- }
- return new FunctionDeclaration[] {};
- }
-
- public boolean getCreateInstanceField() {
- return fCreateInstanceField;
- }
-
- private int getEnclosingInstanceAccessModifiers() {
- if (fMarkInstanceFieldAsFinal)
- return Modifier.PRIVATE | Modifier.FINAL;
- else
- return Modifier.PRIVATE;
- }
-
- public String getEnclosingInstanceName() {
- return fEnclosingInstanceFieldName;
- }
-
- private String getInitialNameForEnclosingInstanceField() {
- IType enclosingType= fType.getDeclaringType();
- if (enclosingType == null)
- return ""; //$NON-NLS-1$
- String[] suggestedNames= StubUtility.getFieldNameSuggestions(fType.getDeclaringType(), getEnclosingInstanceAccessModifiers(), getFieldNames(fType));
- if (suggestedNames.length > 0)
- return suggestedNames[0];
- String name= enclosingType.getElementName();
- if (name.equals("")) //$NON-NLS-1$
- return ""; //$NON-NLS-1$
- return Character.toLowerCase(name.charAt(0)) + name.substring(1);
- }
-
- public IType getInputType() {
- return fType;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.base.IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.MoveInnerToTopRefactoring_name;
- }
-
- private String getNameForEnclosingInstanceConstructorParameter() throws JavaScriptModelException {
- if (fNameForEnclosingInstanceConstructorParameter != null)
- return fNameForEnclosingInstanceConstructorParameter;
-
- String[] suggestedNames= StubUtility.getArgumentNameSuggestions(fType.getDeclaringType(), getParameterNamesOfAllConstructors(fType));
- if (suggestedNames.length > 0)
- fNameForEnclosingInstanceConstructorParameter= suggestedNames[0];
- else
- fNameForEnclosingInstanceConstructorParameter= fEnclosingInstanceFieldName;
- return fNameForEnclosingInstanceConstructorParameter;
- }
-
- private String[] getNewConstructorParameterNames() throws JavaScriptModelException {
- if (!fCreateInstanceField)
- return new String[0];
- return new String[] { getNameForEnclosingInstanceConstructorParameter()};
- }
-
- private ASTNode getNewQualifiedNameNode(ITypeBinding[] parameters, Name name) {
- final AST ast= name.getAST();
- boolean raw= false;
- final ITypeBinding binding= name.resolveTypeBinding();
- return ast.newName(fQualifiedTypeName);
- }
-
- private ASTNode getNewUnqualifiedTypeNode(ITypeBinding[] parameters, Name name) {
- final AST ast= name.getAST();
- boolean raw= false;
- final ITypeBinding binding= name.resolveTypeBinding();
- return ast.newSimpleType(ast.newSimpleName(fType.getElementName()));
- }
-
- private boolean insertExpressionAsParameter(ClassInstanceCreation cic, ASTRewrite rewrite, IJavaScriptUnit cu, TextEditGroup group) throws JavaScriptModelException {
- final Expression expression= createEnclosingInstanceCreationString(cic, cu);
- if (expression == null)
- return false;
- rewrite.getListRewrite(cic, ClassInstanceCreation.ARGUMENTS_PROPERTY).insertFirst(expression, group);
- return true;
- }
-
- private boolean insertExpressionAsParameter(SuperConstructorInvocation sci, ASTRewrite rewrite, IJavaScriptUnit cu, TextEditGroup group) throws JavaScriptModelException {
- final Expression expression= createEnclosingInstanceCreationString(sci, cu);
- if (expression == null)
- return false;
- rewrite.getListRewrite(sci, SuperConstructorInvocation.ARGUMENTS_PROPERTY).insertFirst(expression, group);
- return true;
- }
-
- public boolean isCreatingInstanceFieldMandatory() {
- return fIsInstanceFieldCreationMandatory;
- }
-
- public boolean isCreatingInstanceFieldPossible() {
- return fIsInstanceFieldCreationPossible;
- }
-
- private boolean isInAnonymousTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
- final AnonymousClassDeclaration anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(node, AnonymousClassDeclaration.class);
- return anonymous != null && ASTNodes.isParent(anonymous, declaration);
- }
-
- private boolean isInLocalTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
- final TypeDeclarationStatement statement= (TypeDeclarationStatement) ASTNodes.getParent(node, TypeDeclarationStatement.class);
- return statement != null && ASTNodes.isParent(statement, declaration);
- }
-
- private boolean isInNonStaticMemberTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
- final AbstractTypeDeclaration nested= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
- return nested != null && !declaration.equals(nested) && !Modifier.isStatic(nested.getFlags()) && ASTNodes.isParent(nested, declaration);
- }
-
- private boolean isInsideSubclassOfDeclaringType(ASTNode node) {
- Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
- Assert.isNotNull(declaration);
-
- final AnonymousClassDeclaration anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(node, AnonymousClassDeclaration.class);
- boolean isAnonymous= anonymous != null && ASTNodes.isParent(anonymous, declaration);
- if (isAnonymous)
- return anonymous != null && isSubclassBindingOfEnclosingType(anonymous.resolveBinding());
- return isSubclassBindingOfEnclosingType(declaration.resolveBinding());
- }
-
- private boolean isInsideTypeNestedInDeclaringType(ASTNode node) {
- Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
- Assert.isNotNull(declaration);
- ITypeBinding enclosing= declaration.resolveBinding();
- while (enclosing != null) {
- if (isCorrespondingTypeBinding(enclosing, fType.getDeclaringType()))
- return true;
- enclosing= enclosing.getDeclaringClass();
- }
- return false;
- }
-
- private boolean isInstanceFieldCreationMandatory() throws JavaScriptModelException {
- final MemberAccessNodeCollector collector= new MemberAccessNodeCollector(fType.getDeclaringType().newSupertypeHierarchy(new NullProgressMonitor()));
- findTypeDeclaration(fType, fSourceRewrite.getRoot()).accept(collector);
- return containsNonStatic(collector.getFieldAccesses()) || containsNonStatic(collector.getMethodInvocations()) || containsNonStatic(collector.getSimpleFieldNames());
- }
-
- public boolean isInstanceFieldMarkedFinal() {
- return fMarkInstanceFieldAsFinal;
- }
-
- private boolean isSubclassBindingOfEnclosingType(ITypeBinding binding) {
- while (binding != null) {
- if (isCorrespondingTypeBinding(binding, fType.getDeclaringType()))
- return true;
- binding= binding.getSuperclass();
- }
- return false;
- }
-
- /*
- * This method qualifies accesses from within the moved type to the (now former) enclosed
- * type of the moved type. Note that all visibility changes have already been scheduled
- * in the visibility adjustor.
- */
- private void modifyAccessToEnclosingInstance(final CompilationUnitRewrite targetRewrite, final AbstractTypeDeclaration declaration, final RefactoringStatus status, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(declaration);
- Assert.isNotNull(monitor);
- final Set handledMethods= new HashSet();
- final Set handledFields= new HashSet();
- final MemberAccessNodeCollector collector= new MemberAccessNodeCollector(fType.getDeclaringType().newSupertypeHierarchy(new SubProgressMonitor(monitor, 1)));
- declaration.accept(collector);
- modifyAccessToMethodsFromEnclosingInstance(targetRewrite, handledMethods, collector.getMethodInvocations(), declaration, status);
- modifyAccessToFieldsFromEnclosingInstance(targetRewrite, handledFields, collector.getFieldAccesses(), declaration, status);
- modifyAccessToFieldsFromEnclosingInstance(targetRewrite, handledFields, collector.getSimpleFieldNames(), declaration, status);
- }
-
- private void modifyAccessToFieldsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, Set handledFields, FieldAccess[] fieldAccesses, AbstractTypeDeclaration declaration, RefactoringStatus status) {
- FieldAccess access= null;
- for (int index= 0; index < fieldAccesses.length; index++) {
- access= fieldAccesses[index];
- Assert.isNotNull(access.getExpression());
- if (!(access.getExpression() instanceof ThisExpression) || (!(((ThisExpression) access.getExpression()).getQualifier() != null)))
- continue;
-
- final IVariableBinding binding= access.resolveFieldBinding();
- if (binding != null) {
- targetRewrite.getASTRewrite().replace(access.getExpression(), createAccessExpressionToEnclosingInstanceFieldText(access, binding, declaration), null);
- targetRewrite.getImportRemover().registerRemovedNode(access.getExpression());
- }
- }
- }
-
- private void modifyAccessToFieldsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, Set handledFields, SimpleName[] simpleNames, AbstractTypeDeclaration declaration, RefactoringStatus status) {
- IBinding binding= null;
- SimpleName simpleName= null;
- IVariableBinding variable= null;
- for (int index= 0; index < simpleNames.length; index++) {
- simpleName= simpleNames[index];
- binding= simpleName.resolveBinding();
- if (binding != null && binding instanceof IVariableBinding && !(simpleName.getParent() instanceof FieldAccess)) {
- variable= (IVariableBinding) binding;
- final FieldAccess access= simpleName.getAST().newFieldAccess();
- access.setExpression(createAccessExpressionToEnclosingInstanceFieldText(simpleName, variable, declaration));
- access.setName(simpleName.getAST().newSimpleName(simpleName.getIdentifier()));
- targetRewrite.getASTRewrite().replace(simpleName, access, null);
- targetRewrite.getImportRemover().registerRemovedNode(simpleName);
- }
- }
- }
-
- private void modifyAccessToMethodsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, Set handledMethods, FunctionInvocation[] methodInvocations, AbstractTypeDeclaration declaration, RefactoringStatus status) {
- IFunctionBinding binding= null;
- FunctionInvocation invocation= null;
- for (int index= 0; index < methodInvocations.length; index++) {
- invocation= methodInvocations[index];
- binding= invocation.resolveMethodBinding();
- if (binding != null) {
- final Expression target= invocation.getExpression();
- if (target == null) {
- final Expression expression= createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration);
- targetRewrite.getASTRewrite().set(invocation, FunctionInvocation.EXPRESSION_PROPERTY, expression, null);
- } else {
- if (!(invocation.getExpression() instanceof ThisExpression) || !(((ThisExpression) invocation.getExpression()).getQualifier() != null))
- continue;
- targetRewrite.getASTRewrite().replace(target, createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration), null);
- targetRewrite.getImportRemover().registerRemovedNode(target);
- }
- }
- }
- }
-
- private void modifyConstructors(AbstractTypeDeclaration declaration, ASTRewrite rewrite) throws CoreException {
- final FunctionDeclaration[] declarations= getConstructorDeclarationNodes(declaration);
- for (int index= 0; index < declarations.length; index++) {
- Assert.isTrue(declarations[index].isConstructor());
- addParameterToConstructor(rewrite, declarations[index]);
- setEnclosingInstanceFieldInConstructor(rewrite, declarations[index]);
- }
- }
-
- private void modifyInterfaceMemberModifiers(final ITypeBinding binding) {
- Assert.isNotNull(binding);
- ITypeBinding declaring= binding.getDeclaringClass();
- while (declaring != null) {
- declaring= declaring.getDeclaringClass();
- }
- if (declaring != null) {
- final ASTNode node= ASTNodes.findDeclaration(binding, fSourceRewrite.getRoot());
- if (node instanceof AbstractTypeDeclaration) {
- ModifierRewrite.create(fSourceRewrite.getASTRewrite(), node).setVisibility(Modifier.PUBLIC, null);
- }
- }
- }
-
- public void setCreateInstanceField(boolean create) {
- Assert.isTrue(fIsInstanceFieldCreationPossible);
- Assert.isTrue(!fIsInstanceFieldCreationMandatory);
- fCreateInstanceField= create;
- }
-
- private void setEnclosingInstanceFieldInConstructor(ASTRewrite rewrite, FunctionDeclaration decl) throws JavaScriptModelException {
- final AST ast= decl.getAST();
- final Block body= decl.getBody();
- final List statements= body.statements();
- if (statements.isEmpty()) {
- final Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide(createReadAccessExpressionForEnclosingInstance(ast));
- assignment.setRightHandSide(ast.newSimpleName(getNameForEnclosingInstanceConstructorParameter()));
- rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertFirst(ast.newExpressionStatement(assignment), null);
- } else {
- final Statement first= (Statement) statements.get(0);
- if (first instanceof ConstructorInvocation) {
- rewrite.getListRewrite(first, ConstructorInvocation.ARGUMENTS_PROPERTY).insertFirst(ast.newSimpleName(fEnclosingInstanceFieldName), null);
- } else {
- int index= 0;
- if (first instanceof SuperConstructorInvocation)
- index++;
- final Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide(createReadAccessExpressionForEnclosingInstance(ast));
- assignment.setRightHandSide(ast.newSimpleName(getNameForEnclosingInstanceConstructorParameter()));
- rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(ast.newExpressionStatement(assignment), index, null);
- }
- }
- }
-
- public void setEnclosingInstanceName(String name) {
- Assert.isNotNull(name);
- fEnclosingInstanceFieldName= name;
- }
-
- public void setMarkInstanceFieldAsFinal(boolean mark) {
- fMarkInstanceFieldAsFinal= mark;
- }
-
- private void updateConstructorReference(final ClassInstanceCreation creation, final CompilationUnitRewrite targetRewrite, final IJavaScriptUnit unit, TextEditGroup group) throws JavaScriptModelException {
- Assert.isNotNull(creation);
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(unit);
- final ASTRewrite rewrite= targetRewrite.getASTRewrite();
- if (fCreateInstanceField)
- insertExpressionAsParameter(creation, rewrite, unit, group);
- final Expression expression= creation.getExpression();
- if (expression != null) {
- rewrite.remove(expression, null);
- targetRewrite.getImportRemover().registerRemovedNode(expression);
- }
- }
-
- private void updateConstructorReference(ITypeBinding[] parameters, ASTNode reference, CompilationUnitRewrite targetRewrite, IJavaScriptUnit cu) throws CoreException {
- final TextEditGroup group= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_update_constructor_reference);
- if (reference instanceof SuperConstructorInvocation)
- updateConstructorReference((SuperConstructorInvocation) reference, targetRewrite, cu, group);
- else if (reference instanceof ClassInstanceCreation)
- updateConstructorReference((ClassInstanceCreation) reference, targetRewrite, cu, group);
- else if (reference.getParent() instanceof ClassInstanceCreation)
- updateConstructorReference((ClassInstanceCreation) reference.getParent(), targetRewrite, cu, group);
- }
-
- private void updateConstructorReference(final SuperConstructorInvocation invocation, final CompilationUnitRewrite targetRewrite, final IJavaScriptUnit unit, TextEditGroup group) throws CoreException {
- Assert.isNotNull(invocation);
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(unit);
- final ASTRewrite rewrite= targetRewrite.getASTRewrite();
- if (fCreateInstanceField)
- insertExpressionAsParameter(invocation, rewrite, unit, group);
- final Expression expression= invocation.getExpression();
- if (expression != null) {
- rewrite.remove(expression, null);
- targetRewrite.getImportRemover().registerRemovedNode(expression);
- }
- }
-
- private boolean updateNameReference(ITypeBinding[] parameters, Name name, CompilationUnitRewrite targetRewrite, TextEditGroup group) {
- if (ASTNodes.asString(name).equals(fType.getFullyQualifiedName('.'))) {
- targetRewrite.getASTRewrite().replace(name, getNewQualifiedNameNode(parameters, name), group);
- targetRewrite.getImportRemover().registerRemovedNode(name);
- return true;
- }
- targetRewrite.getASTRewrite().replace(name, getNewUnqualifiedTypeNode(parameters, name), group);
- targetRewrite.getImportRemover().registerRemovedNode(name);
- return true;
- }
-
- private boolean updateReference(ITypeBinding[] parameters, ASTNode node, CompilationUnitRewrite rewrite, TextEditGroup group) {
- if (node instanceof QualifiedName)
- return updateNameReference(parameters, (QualifiedName) node, rewrite, group);
- else if (node instanceof SimpleType)
- return updateNameReference(parameters, ((SimpleType) node).getName(), rewrite, group);
- else
- return false;
- }
-
- private void updateReferenceInImport(ImportDeclaration enclosingImport, ASTNode node, CompilationUnitRewrite rewrite) throws CoreException {
- final IBinding binding= enclosingImport.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ITypeBinding type= (ITypeBinding) binding;
- final ImportRewrite rewriter= rewrite.getImportRewrite();
- if (enclosingImport.isStatic()) {
- final String oldImport= ASTNodes.asString(node);
- final StringBuffer buffer= new StringBuffer(oldImport);
- final String typeName= fType.getDeclaringType().getElementName();
- final int index= buffer.indexOf(typeName);
- if (index >= 0) {
- buffer.delete(index, index + typeName.length() + 1);
- final String newImport= buffer.toString();
- if (enclosingImport.isOnDemand()) {
- rewriter.removeStaticImport(oldImport + ".*"); //$NON-NLS-1$
- rewriter.addStaticImport(newImport, "*", false); //$NON-NLS-1$
- } else {
- rewriter.removeStaticImport(oldImport);
- final int offset= newImport.lastIndexOf('.');
- if (offset >= 0 && offset < newImport.length() - 1) {
- rewriter.addStaticImport(newImport.substring(0, offset), newImport.substring(offset + 1), false);
- }
- }
- }
- } else
- rewriter.removeImport(type.getQualifiedName());
- }
- }
-
- private void updateTypeReference(ITypeBinding[] parameters, ASTNode node, CompilationUnitRewrite rewrite, IJavaScriptUnit cu) throws CoreException {
- ImportDeclaration enclosingImport= (ImportDeclaration) ASTNodes.getParent(node, ImportDeclaration.class);
- if (enclosingImport != null)
- updateReferenceInImport(enclosingImport, node, rewrite);
- else {
- final TextEditGroup group= rewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_update_type_reference);
- updateReference(parameters, node, rewrite, group);
- if (!fType.getPackageFragment().equals(cu.getParent())) {
- final String name= fType.getPackageFragment().getElementName() + '.' + fType.getElementName();
- rewrite.getImportRemover().registerAddedImport(name);
- rewrite.getImportRewrite().addImport(name);
- }
- }
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return createInputFatalStatus(element, IJavaScriptRefactorings.CONVERT_MEMBER_TYPE);
- else {
- fType= (IType) element;
- fCodeGenerationSettings= JavaPreferencesSettings.getCodeGenerationSettings(fType.getJavaScriptProject());
- try {
- initialize();
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String fieldName= extended.getAttribute(ATTRIBUTE_FIELD_NAME);
- if (fieldName != null && !"".equals(fieldName)) //$NON-NLS-1$
- fEnclosingInstanceFieldName= fieldName;
- final String parameterName= extended.getAttribute(ATTRIBUTE_PARAMETER_NAME);
- if (parameterName != null && !"".equals(parameterName)) //$NON-NLS-1$
- fNameForEnclosingInstanceConstructorParameter= parameterName;
- final String createField= extended.getAttribute(ATTRIBUTE_FIELD);
- if (createField != null) {
- fCreateInstanceField= Boolean.valueOf(createField).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FIELD));
- final String markFinal= extended.getAttribute(ATTRIBUTE_FINAL);
- if (markFinal != null) {
- fMarkInstanceFieldAsFinal= Boolean.valueOf(markFinal).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FINAL));
- final String possible= extended.getAttribute(ATTRIBUTE_POSSIBLE);
- if (possible != null) {
- fIsInstanceFieldCreationPossible= Boolean.valueOf(possible).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POSSIBLE));
- final String mandatory= extended.getAttribute(ATTRIBUTE_MANDATORY);
- if (mandatory != null)
- fIsInstanceFieldCreationMandatory= Boolean.valueOf(mandatory).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MANDATORY));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodProcessor.java
deleted file mode 100644
index ac0cee96..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodProcessor.java
+++ /dev/null
@@ -1,2980 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.MoveProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.text.edits.TextEditProcessor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionRefParameter;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.IVisibilityAdjustment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavadocUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring processor to move instance methods.
- */
-public final class MoveInstanceMethodProcessor extends MoveProcessor implements IScriptableRefactoring, IDelegateUpdating, ICommentProvider {
-
- /**
- * AST visitor to find references to parameters occurring in anonymous
- * classes of a method body.
- */
- public final class AnonymousClassReferenceFinder extends AstNodeFinder {
-
- /** The anonymous class nesting counter */
- protected int fAnonymousClass= 0;
-
- /** The declaring type of the method declaration */
- protected final ITypeBinding fDeclaringType;
-
- /**
- * Creates a new anonymous class reference finder.
- *
- * @param declaration
- * the method declaration to search for references
- */
- public AnonymousClassReferenceFinder(final FunctionDeclaration declaration) {
- fDeclaringType= declaration.resolveBinding().getDeclaringClass();
- }
-
- public final void endVisit(final AnonymousClassDeclaration node) {
- Assert.isNotNull(node);
- if (fAnonymousClass > 0)
- fAnonymousClass--;
- super.endVisit(node);
- }
-
- public final boolean visit(final AnonymousClassDeclaration node) {
- Assert.isNotNull(node);
- fAnonymousClass++;
- return super.visit(node);
- }
-
- public final boolean visit(final FunctionInvocation node) {
- Assert.isNotNull(node);
- if (fAnonymousClass > 0) {
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null) {
- if (node.getExpression() == null && !Modifier.isStatic(binding.getModifiers()))
- fResult.add(node.getName());
- }
- }
- return true;
- }
-
- public boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- if (fAnonymousClass > 0) {
- if (!(node.getParent() instanceof FieldAccess)) {
- final IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- final ITypeBinding declaring= variable.getDeclaringClass();
- if (declaring != null && Bindings.equals(declaring, fDeclaringType))
- fResult.add(node);
- }
- }
- }
- return false;
- }
- }
-
- /**
- * Partial implementation of an ast node finder.
- */
- protected static class AstNodeFinder extends ASTVisitor {
-
- /** The found ast nodes */
- protected final Set fResult= new HashSet();
-
- /** The status of the find operation */
- protected final RefactoringStatus fStatus= new RefactoringStatus();
-
- /**
- * Returns the result set.
- *
- * @return the result set
- */
- public final Set getResult() {
- return fResult;
- }
-
- /**
- * Returns the status of the find operation.
- *
- * @return the status of the operation
- */
- public final RefactoringStatus getStatus() {
- return fStatus;
- }
- }
-
- class DelegateInstanceMethodCreator extends DelegateMethodCreator {
-
- private Map fAdjustments;
-
- private boolean fNeededInsertion;
-
- private Map fRewrites;
-
- public DelegateInstanceMethodCreator(Map adjustments, Map rewrites) {
- super();
- fAdjustments= adjustments;
- fRewrites= rewrites;
- }
-
- protected ASTNode createBody(BodyDeclaration bd) throws JavaScriptModelException {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) bd;
- final FunctionInvocation invocation= getAst().newFunctionInvocation();
- invocation.setName(getAst().newSimpleName(getNewElementName()));
- invocation.setExpression(createSimpleTargetAccessExpression(methodDeclaration));
- fNeededInsertion= createArgumentList(methodDeclaration, invocation.arguments(), new VisibilityAdjustingArgumentFactory(getAst(), fRewrites, fAdjustments));
- final Block block= getAst().newBlock();
- block.statements().add(createMethodInvocation(methodDeclaration, invocation));
- if (!fSourceRewrite.getCu().equals(fTargetType.getJavaScriptUnit()))
- fSourceRewrite.getImportRemover().registerRemovedNode(methodDeclaration.getBody());
- return block;
- }
-
- protected ASTNode createDocReference(final BodyDeclaration declaration) throws JavaScriptModelException {
- return MoveInstanceMethodProcessor.this.createMethodReference((FunctionDeclaration) declaration, getAst());
- }
-
- protected boolean getNeededInsertion() {
- return fNeededInsertion;
- }
- }
-
- /**
- * AST visitor to find 'this' references to enclosing instances.
- */
- public final class EnclosingInstanceReferenceFinder extends AstNodeFinder {
-
- /** The list of enclosing types */
- private final List fEnclosingTypes= new ArrayList(3);
-
- /**
- * Creates a new enclosing instance reference finder.
- *
- * @param binding
- * the declaring type
- */
- public EnclosingInstanceReferenceFinder(final ITypeBinding binding) {
- Assert.isNotNull(binding);
- ITypeBinding declaring= binding.getDeclaringClass();
- while (declaring != null) {
- fEnclosingTypes.add(declaring);
- declaring= declaring.getDeclaringClass();
- }
- }
-
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- final IBinding binding= node.resolveBinding();
- ITypeBinding declaring= null;
- if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- if (Flags.isStatic(variable.getModifiers()))
- return false;
- declaring= variable.getDeclaringClass();
- } else if (binding instanceof IFunctionBinding) {
- final IFunctionBinding method= (IFunctionBinding) binding;
- if (Flags.isStatic(method.getModifiers()))
- return false;
- declaring= method.getDeclaringClass();
- }
- if (declaring != null) {
- ITypeBinding enclosing= null;
- for (final Iterator iterator= fEnclosingTypes.iterator(); iterator.hasNext();) {
- enclosing= (ITypeBinding) iterator.next();
- if (Bindings.equals(enclosing, declaring)) {
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_refers_enclosing_instances, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- fResult.add(node);
- break;
- }
- }
- }
- return false;
- }
-
- public final boolean visit(final ThisExpression node) {
- Assert.isNotNull(node);
- if (node.getQualifier() != null) {
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_refers_enclosing_instances, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- fResult.add(node);
- }
- return false;
- }
- }
-
- /**
- * AST visitor to find references to type variables or generic types.
- */
- public final class GenericReferenceFinder extends AstNodeFinder {
-
- /** The type parameter binding keys */
- protected final Set fBindings= new HashSet();
-
- /**
- * Creates a new generic reference finder.
- *
- * @param declaration
- * the method declaration
- */
- public GenericReferenceFinder(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleName)
- */
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- final IBinding binding= node.resolveBinding();
- return true;
- }
- }
-
- /**
- * Factory for method argument declaration or expression nodes.
- */
- protected static interface IArgumentFactory {
-
- /**
- * Returns a argument node for the specified variable binding.
- *
- * @param binding
- * the binding to create a argument node for
- * @param last
- * <code>true</code> if the argument represented by this
- * node is the last one in its declaring method
- * @return the corresponding node
- * @throws JavaScriptModelException
- * if an error occurs
- */
- public ASTNode getArgumentNode(IVariableBinding binding, boolean last) throws JavaScriptModelException;
-
- /**
- * Returns a target node for the current target.
- *
- * @return the corresponding node
- * @throws JavaScriptModelException
- * if an error occurs
- */
- public ASTNode getTargetNode() throws JavaScriptModelException;
- }
-
- /**
- * AST visitor to rewrite the body of the moved method.
- */
- public final class MethodBodyRewriter extends ASTVisitor {
-
- /** The anonymous class nesting counter */
- protected int fAnonymousClass= 0;
-
- /** The method declaration to rewrite */
- protected final FunctionDeclaration fDeclaration;
-
- /** The set of handled method invocations */
- protected final Set fMethodDeclarations= new HashSet();
-
- /** The source ast rewrite to use */
- protected final ASTRewrite fRewrite;
-
- /** The existing static imports */
- protected final Set fStaticImports= new HashSet();
-
- /** The refactoring status */
- protected final RefactoringStatus fStatus= new RefactoringStatus();
-
- /** The target compilation unit rewrite to use */
- protected final CompilationUnitRewrite fTargetRewrite;
-
- /**
- * Creates a new method body rewriter.
- *
- * @param targetRewrite
- * the target compilation unit rewrite to use
- * @param rewrite
- * the source ast rewrite to use
- * @param sourceDeclaration
- * the source method declaration
- */
- public MethodBodyRewriter(final CompilationUnitRewrite targetRewrite, final ASTRewrite rewrite, final FunctionDeclaration sourceDeclaration) {
- Assert.isNotNull(targetRewrite);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(sourceDeclaration);
- fTargetRewrite= targetRewrite;
- fRewrite= rewrite;
- fDeclaration= sourceDeclaration;
- fStaticImports.clear();
- ImportRewriteUtil.collectImports(fMethod.getJavaScriptProject(), sourceDeclaration, new HashSet(), fStaticImports, false);
- }
-
- public final void endVisit(final AnonymousClassDeclaration node) {
- Assert.isNotNull(node);
- if (fAnonymousClass > 0)
- fAnonymousClass--;
- super.endVisit(node);
- }
-
- public final boolean visit(final AnonymousClassDeclaration node) {
- Assert.isNotNull(node);
- fAnonymousClass++;
- return super.visit(node);
- }
-
- public final boolean visit(final ClassInstanceCreation node) {
- Assert.isNotNull(node);
- if (node.getParent() instanceof ClassInstanceCreation) {
- final AnonymousClassDeclaration declaration= node.getAnonymousClassDeclaration();
- if (declaration != null)
- visit(declaration);
- return false;
- }
- return super.visit(node);
- }
-
- public final boolean visit(final FieldAccess node) {
- Assert.isNotNull(node);
- final Expression expression= node.getExpression();
- final IVariableBinding variable= node.resolveFieldBinding();
- final AST ast= fRewrite.getAST();
- if (expression instanceof ThisExpression) {
- if (Bindings.equals(fTarget, variable)) {
- if (fAnonymousClass > 0) {
- final ThisExpression target= ast.newThisExpression();
- target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
- fRewrite.replace(node, target, null);
- } else
- fRewrite.replace(node, ast.newThisExpression(), null);
- return false;
- }
- }
- if (expression instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess) expression;
- final IBinding binding= access.getName().resolveBinding();
- if ((access.getExpression() instanceof ThisExpression) && Bindings.equals(fTarget, binding)) {
- fRewrite.replace(node, ast.newSimpleName(node.getName().getIdentifier()), null);
- return false;
- }
- } else if (expression != null) {
- final IFunctionBinding method= fDeclaration.resolveBinding();
- if (variable != null && method != null && !JdtFlags.isStatic(variable) && Bindings.equals(method.getDeclaringClass(), variable.getDeclaringClass())) {
- fRewrite.replace(expression, ast.newSimpleName(fTargetName), null);
- return false;
- }
- }
- return true;
- }
-
- public final void visit(final List nodes) {
- Assert.isNotNull(nodes);
- ASTNode node= null;
- for (final Iterator iterator= nodes.iterator(); iterator.hasNext();) {
- node= (ASTNode) iterator.next();
- node.accept(this);
- }
- }
-
- public final boolean visit(final FunctionInvocation node) {
- Assert.isNotNull(node);
- final Expression expression= node.getExpression();
- final IFunctionBinding method= node.resolveMethodBinding();
- if (method != null) {
- final ASTRewrite rewrite= fRewrite;
- if (expression == null) {
- final AST ast= node.getAST();
- if (!JdtFlags.isStatic(method))
- rewrite.set(node, FunctionInvocation.EXPRESSION_PROPERTY, ast.newSimpleName(fTargetName), null);
- else
- rewrite.set(node, FunctionInvocation.EXPRESSION_PROPERTY, ast.newSimpleType(ast.newSimpleName(fMethod.getDeclaringType().getElementName())), null);
- return true;
- } else {
- if (expression instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess) expression;
- if (Bindings.equals(access.resolveFieldBinding(), fTarget)) {
- rewrite.remove(expression, null);
- visit(node.arguments());
- return false;
- }
- } else if (expression instanceof Name) {
- final Name name= (Name) expression;
- if (Bindings.equals(name.resolveBinding(), fTarget)) {
- rewrite.remove(expression, null);
- visit(node.arguments());
- return false;
- }
- }
- }
- }
- return true;
- }
-
- public final boolean visit(final QualifiedName node) {
- Assert.isNotNull(node);
- IBinding binding= node.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ITypeBinding type= (ITypeBinding) binding;
- if (type.isClass() && type.getDeclaringClass() != null) {
- final String name= fTargetRewrite.getImportRewrite().addImport(type);
- if (name != null && name.length() > 0) {
- fRewrite.replace(node, ASTNodeFactory.newName(node.getAST(), name), null);
- return false;
- }
- }
- }
- binding= node.getQualifier().resolveBinding();
- if (Bindings.equals(binding, fTarget)) {
- fRewrite.replace(node, fRewrite.createCopyTarget(node.getName()), null);
- return false;
- }
- return true;
- }
-
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- final AST ast= node.getAST();
- final ASTRewrite rewrite= fRewrite;
- final IBinding binding= node.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ITypeBinding type= (ITypeBinding) binding;
- if (type.isClass() && type.getDeclaringClass() != null) {
- final String name= fTargetRewrite.getImportRewrite().addImport(type);
- if (name != null && name.length() > 0) {
- fRewrite.replace(node, ASTNodeFactory.newName(ast, name), null);
- return false;
- }
- }
- }
- if (Bindings.equals(binding, fTarget))
- if (fAnonymousClass > 0) {
- final ThisExpression target= ast.newThisExpression();
- target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
- fRewrite.replace(node, target, null);
- } else
- rewrite.replace(node, ast.newThisExpression(), null);
- else if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- final IFunctionBinding method= fDeclaration.resolveBinding();
- final ITypeBinding declaring= variable.getDeclaringClass();
- if (method != null) {
- if (Bindings.equals(method.getDeclaringClass(), declaring)) {
- if (JdtFlags.isStatic(variable))
- rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
- else {
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newSimpleName(fTargetName));
- access.setName(ast.newSimpleName(node.getFullyQualifiedName()));
- rewrite.replace(node, access, null);
- }
- } else if (!(node.getParent() instanceof QualifiedName) && JdtFlags.isStatic(variable) && !fStaticImports.contains(variable)) {
- rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
- }
- }
- }
- return false;
- }
-
- public final boolean visit(final ThisExpression node) {
- Assert.isNotNull(node);
- fRewrite.replace(node, node.getAST().newSimpleName(fTargetName), null);
- return false;
- }
- }
-
- /**
- * AST visitor to find read-only fields of the declaring class of 'this'.
- */
- public static class ReadyOnlyFieldFinder extends ASTVisitor {
-
- /**
- * Returns the field binding associated with this expression.
- *
- * @param expression
- * the expression to get the field binding for
- * @return the field binding, if the expression denotes a field access
- * or a field name, <code>null</code> otherwise
- */
- protected static IVariableBinding getFieldBinding(final Expression expression) {
- Assert.isNotNull(expression);
- if (expression instanceof FieldAccess)
- return (IVariableBinding) ((FieldAccess) expression).getName().resolveBinding();
- if (expression instanceof Name) {
- final IBinding binding= ((Name) expression).resolveBinding();
- if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- if (variable.isField())
- return variable;
- }
- }
- return null;
- }
-
- /**
- * Is the specified name a qualified entity, e.g. preceded by 'this',
- * 'super' or part of a method invocation?
- *
- * @param name
- * the name to check
- * @return <code>true</code> if this entity is qualified,
- * <code>false</code> otherwise
- */
- protected static boolean isQualifiedEntity(final Name name) {
- Assert.isNotNull(name);
- final ASTNode parent= name.getParent();
- if ((parent instanceof QualifiedName && ((QualifiedName) parent).getName().equals(name)) || (parent instanceof FieldAccess && ((FieldAccess) parent).getName().equals(name)) || (parent instanceof SuperFieldAccess))
- return true;
- else if (parent instanceof FunctionInvocation) {
- final FunctionInvocation invocation= (FunctionInvocation) parent;
- return invocation.getExpression() != null && invocation.getName().equals(name);
- }
- return false;
- }
-
- /** The list of found bindings */
- protected final List fBindings= new LinkedList();
-
- /** The keys of the found bindings */
- protected final Set fFound= new HashSet();
-
- /** The keys of the written bindings */
- protected final Set fWritten= new HashSet();
-
- /**
- * Creates a new read only field finder.
- *
- * @param binding
- * The declaring class of the method declaring to find fields
- * for
- */
- public ReadyOnlyFieldFinder(final ITypeBinding binding) {
- Assert.isNotNull(binding);
- final IVariableBinding[] bindings= binding.getDeclaredFields();
- IVariableBinding variable= null;
- for (int index= 0; index < bindings.length; index++) {
- variable= bindings[index];
- if (!fFound.contains(variable.getKey())) {
- fFound.add(variable.getKey());
- fBindings.add(variable);
- }
- }
- }
-
- /**
- * Returns all fields of the declaring class plus the ones references in
- * the visited method declaration.
- *
- * @return all fields of the declaring class plus the references ones
- */
- public final IVariableBinding[] getDeclaredFields() {
- final IVariableBinding[] result= new IVariableBinding[fBindings.size()];
- fBindings.toArray(result);
- return result;
- }
-
- /**
- * Returns all fields of the declaring class which are not written by
- * the visited method declaration.
- *
- * @return all fields which are not written
- */
- public final IVariableBinding[] getReadOnlyFields() {
- IVariableBinding binding= null;
- final List list= new LinkedList(fBindings);
- for (final Iterator iterator= list.iterator(); iterator.hasNext();) {
- binding= (IVariableBinding) iterator.next();
- if (fWritten.contains(binding.getKey()))
- iterator.remove();
- }
- final IVariableBinding[] result= new IVariableBinding[list.size()];
- list.toArray(result);
- return result;
- }
-
- public final boolean visit(final Assignment node) {
- Assert.isNotNull(node);
- final IVariableBinding binding= getFieldBinding(node.getLeftHandSide());
- if (binding != null)
- fWritten.add(binding.getKey());
- return true;
- }
-
- public final boolean visit(final FieldAccess node) {
- Assert.isNotNull(node);
- if (node.getExpression() instanceof ThisExpression) {
- final IVariableBinding binding= (IVariableBinding) node.getName().resolveBinding();
- if (binding != null) {
- final String key= binding.getKey();
- if (!fFound.contains(key)) {
- fFound.add(key);
- fBindings.add(binding);
- }
- }
- }
- return true;
- }
-
- public final boolean visit(final PostfixExpression node) {
- final IVariableBinding binding= getFieldBinding(node.getOperand());
- if (binding != null)
- fWritten.add(binding.getKey());
- return true;
- }
-
- public final boolean visit(final PrefixExpression node) {
- final IVariableBinding binding= getFieldBinding(node.getOperand());
- if (binding != null)
- fWritten.add(binding.getKey());
- return false;
- }
-
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- final IBinding binding= node.resolveBinding();
- if (binding != null)
- if (isFieldAccess(node) && !isQualifiedEntity(node)) {
- final IVariableBinding variable= (IVariableBinding) binding;
- final String key= variable.getKey();
- if (!fFound.contains(key)) {
- fFound.add(key);
- fBindings.add(variable);
- }
- }
- return false;
- }
- }
-
- /**
- * AST visitor to find recursive calls to the method.
- */
- public final class RecursiveCallFinder extends AstNodeFinder {
-
- /** The method binding */
- protected final IFunctionBinding fBinding;
-
- /**
- * Creates a new recursive call finder.
- *
- * @param declaration
- * the method declaration
- */
- public RecursiveCallFinder(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- fBinding= declaration.resolveBinding();
- }
-
- public final boolean visit(final FunctionInvocation node) {
- Assert.isNotNull(node);
- final Expression expression= node.getExpression();
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding == null || (!Modifier.isStatic(binding.getModifiers()) && Bindings.equals(binding, fBinding) && (expression == null || expression instanceof ThisExpression))) {
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_potentially_recursive, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- fResult.add(node);
- return false;
- }
- return true;
- }
- }
-
- /**
- * AST visitor to find 'super' references.
- */
- public final class SuperReferenceFinder extends AstNodeFinder {
-
- public final boolean visit(final AnonymousClassDeclaration node) {
- return false;
- }
-
- public final boolean visit(final SuperFieldAccess node) {
- Assert.isNotNull(node);
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_uses_super, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- fResult.add(node);
- return false;
- }
-
- public final boolean visit(final SuperMethodInvocation node) {
- Assert.isNotNull(node);
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_uses_super, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- fResult.add(node);
- return false;
- }
-
- public final boolean visit(final TypeDeclaration node) {
- return false;
- }
- }
-
- /**
- * AST visitor to find references to 'this'.
- */
- public final class ThisReferenceFinder extends AstNodeFinder {
-
- public final boolean visit(final FunctionInvocation node) {
- Assert.isNotNull(node);
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null && !JdtFlags.isStatic(binding) && node.getExpression() == null) {
- fResult.add(node);
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_this_reference, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- }
- return true;
- }
-
- public final boolean visit(final SimpleName node) {
- Assert.isNotNull(node);
- if (isFieldAccess(node) && !isTargetAccess(node)) {
- fResult.add(node);
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_this_reference, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- }
- return false;
- }
-
- public final boolean visit(final ThisExpression node) {
- Assert.isNotNull(node);
- fResult.add(node);
- fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_this_reference, JavaStatusContext.create(fMethod.getJavaScriptUnit(), node)));
- return false;
- }
- }
-
- /**
- * Argument factory which adjusts the visibilities of the argument types.
- */
- public class VisibilityAdjustingArgumentFactory implements IArgumentFactory {
-
- /** The visibility adjustments */
- private final Map fAdjustments;
-
- /** The ast to use for new nodes */
- private final AST fAst;
-
- /** The compilation unit rewrites */
- private final Map fRewrites;
-
- /**
- * Creates a new visibility adjusting argument factory.
- *
- * @param ast
- * the ast to use for new nodes
- * @param rewrites
- * the compilation unit rewrites
- * @param adjustments
- * the map of elements to visibility adjustments
- */
- public VisibilityAdjustingArgumentFactory(final AST ast, final Map rewrites, final Map adjustments) {
- Assert.isNotNull(ast);
- Assert.isNotNull(rewrites);
- Assert.isNotNull(adjustments);
- fAst= ast;
- fRewrites= rewrites;
- fAdjustments= adjustments;
- }
-
- protected final void adjustTypeVisibility(final ITypeBinding binding) throws JavaScriptModelException {
- Assert.isNotNull(binding);
- final IJavaScriptElement element= binding.getJavaElement();
- if (element instanceof IType) {
- final IType type= (IType) element;
- if (!type.isBinary() && !type.isReadOnly() && !Flags.isPublic(type.getFlags())) {
- boolean same= false;
- final CompilationUnitRewrite rewrite= getCompilationUnitRewrite(fRewrites, type.getJavaScriptUnit());
- final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, rewrite.getRoot());
- if (declaration != null) {
- final ITypeBinding declaring= declaration.resolveBinding();
- if (declaring != null && Bindings.equals(binding.getPackage(), fTarget.getType().getPackage()))
- same= true;
- final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
- final String modifier= same ? RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default : RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
- if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : (keyword == null ? Modifier.NONE : keyword.toFlagValue())) && MemberVisibilityAdjustor.needsVisibilityAdjustments(type, keyword, fAdjustments))
- fAdjustments.put(type, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(type, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(type.getJavaScriptUnit(), declaration))));
- }
- }
- }
- }
-
- public ASTNode getArgumentNode(final IVariableBinding binding, final boolean last) throws JavaScriptModelException {
- Assert.isNotNull(binding);
- adjustTypeVisibility(binding.getType());
- return fAst.newSimpleName(binding.getName());
- }
-
- public ASTNode getTargetNode() throws JavaScriptModelException {
- return fAst.newThisExpression();
- }
- }
-
- private static final String ATTRIBUTE_DEPRECATE= "deprecate"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_INLINE= "inline"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_REMOVE= "remove"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_TARGET_INDEX= "targetIndex"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_TARGET_NAME= "targetName"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_USE_GETTER= "getter"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_USE_SETTER= "setter"; //$NON-NLS-1$
-
- /** The identifier of this processor */
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.moveInstanceMethodProcessor"; //$NON-NLS-1$
-
- /**
- * Returns the bindings of the method arguments of the specified
- * declaration.
- *
- * @param declaration
- * the method declaration
- * @return the array of method argument variable bindings
- */
- protected static IVariableBinding[] getArgumentBindings(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- final List parameters= new ArrayList(declaration.parameters().size());
- VariableDeclaration variable= null;
- IVariableBinding binding= null;
- for (final Iterator iterator= declaration.parameters().iterator(); iterator.hasNext();) {
- variable= (VariableDeclaration) iterator.next();
- binding= variable.resolveBinding();
- if (binding == null)
- return new IVariableBinding[0];
- parameters.add(binding);
- }
- final IVariableBinding[] result= new IVariableBinding[parameters.size()];
- parameters.toArray(result);
- return result;
- }
-
- /**
- * Returns the bindings of the method argument types of the specified
- * declaration.
- *
- * @param declaration
- * the method declaration
- * @return the array of method argument variable bindings
- */
- protected static ITypeBinding[] getArgumentTypes(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- final IVariableBinding[] parameters= getArgumentBindings(declaration);
- final List types= new ArrayList(parameters.length);
- IVariableBinding binding= null;
- ITypeBinding type= null;
- for (int index= 0; index < parameters.length; index++) {
- binding= parameters[index];
- type= binding.getType();
- if (type != null)
- types.add(type);
- }
- final ITypeBinding[] result= new ITypeBinding[types.size()];
- types.toArray(result);
- return result;
- }
-
- /**
- * Is the specified name a field access?
- *
- * @param name
- * the name to check
- * @return <code>true</code> if this name is a field access,
- * <code>false</code> otherwise
- */
- protected static boolean isFieldAccess(final SimpleName name) {
- Assert.isNotNull(name);
- final IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return false;
- final IVariableBinding variable= (IVariableBinding) binding;
- if (!variable.isField())
- return false;
- if ("length".equals(name.getIdentifier())) { //$NON-NLS-1$
- final ASTNode parent= name.getParent();
- if (parent instanceof QualifiedName) {
- final QualifiedName qualified= (QualifiedName) parent;
- final ITypeBinding type= qualified.getQualifier().resolveTypeBinding();
- if (type != null && type.isArray())
- return false;
- }
- }
- return !Modifier.isStatic(variable.getModifiers());
- }
-
- /** The candidate targets */
- private IVariableBinding[] fCandidateTargets= new IVariableBinding[0];
-
- /** The text change manager */
- private TextChangeManager fChangeManager= null;
-
- /** The comment */
- private String fComment;
-
- /** Should the delegator be deprecated? */
- private boolean fDelegateDeprecation= true;
-
- private boolean fDelegatingUpdating;
-
- /** Should the delegator be inlined? */
- private boolean fInline= false;
-
- /** The method to move */
- private IFunction fMethod;
-
- /** The name of the new method to generate */
- private String fMethodName;
-
- /** The possible targets */
- private IVariableBinding[] fPossibleTargets= new IVariableBinding[0];
-
- /** Should the delegator be removed after inlining? */
- private boolean fRemove= false;
-
- /** The code generation settings to apply */
- private CodeGenerationSettings fSettings;
-
- /** The source compilation unit rewrite */
- private CompilationUnitRewrite fSourceRewrite;
-
- /** The new target */
- private IVariableBinding fTarget= null;
-
- /** The name of the new target */
- private String fTargetName;
-
- /** Does the move method need a target node? */
- private boolean fTargetNode= true;
-
- /** The target type */
- private IType fTargetType= null;
-
- /** Should getter methods be used to resolve visibility issues? */
- private boolean fUseGetters= true;
-
- /** Should setter methods be used to resolve visibility issues? */
- private boolean fUseSetters= true;
-
- /**
- * Creates a new move instance method processor.
- *
- * @param method
- * the method to move, or <code>null</code> if invoked by
- * scripting
- * @param settings
- * the code generation settings to apply, or <code>null</code>
- * if invoked by scripting
- */
- public MoveInstanceMethodProcessor(final IFunction method, final CodeGenerationSettings settings) {
- fSettings= settings;
- fMethod= method;
- if (method != null)
- initialize(method);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canEnableComment() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public final boolean canEnableDelegateUpdating() {
- return true;
- }
-
- /**
- * Checks whether a method with the proposed name already exists in the
- * target type.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param status
- * the status of the condition checking
- * @throws JavaScriptModelException
- * if the declared methods of the target type could not be
- * retrieved
- */
- protected void checkConflictingMethod(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- final IFunction[] methods= fTargetType.getFunctions();
- try {
- monitor.beginTask("", methods.length); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- IFunction method= null;
- for (int index= 0; index < methods.length; index++) {
- method= methods[index];
- if (method.getElementName().equals(fMethodName) && method.getParameterTypes().length == fMethod.getParameterTypes().length - 1)
- status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_already_exists, new String[] { fMethodName, fTargetType.getElementName() }), JavaStatusContext.create(method)));
- monitor.worked(1);
- }
- if (fMethodName.equals(fTargetType.getElementName()))
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_type_clash, fMethodName), JavaStatusContext.create(fTargetType)));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Checks whether the new target name conflicts with an already existing
- * method parameter.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param status
- * the status of the condition checking
- * @throws JavaScriptModelException
- * if the method declaration of the method to move could not be
- * found
- */
- protected void checkConflictingTarget(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- VariableDeclaration variable= null;
- final List parameters= declaration.parameters();
- try {
- monitor.beginTask("", parameters.size()); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- for (final Iterator iterator= parameters.iterator(); iterator.hasNext();) {
- variable= (VariableDeclaration) iterator.next();
- if (fTargetName.equals(variable.getName().getIdentifier())) {
- status.merge(RefactoringStatus.createErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_target_name_already_used, JavaStatusContext.create(fMethod)));
- break;
- }
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor,
- * org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
- */
- public final RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(context);
- Assert.isNotNull(fTarget);
- final RefactoringStatus status= new RefactoringStatus();
- fChangeManager= new TextChangeManager();
- try {
- monitor.beginTask("", 4); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- status.merge(Checks.checkIfCuBroken(fMethod));
- if (!status.hasError()) {
- checkGenericTarget(new SubProgressMonitor(monitor, 1), status);
- if (status.isOK()) {
- final IType type= getTargetType();
- if (type != null) {
- if (type.isBinary() || type.isReadOnly() || !fMethod.exists() || fMethod.isBinary() || fMethod.isReadOnly())
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
- else {
- status.merge(Checks.checkIfCuBroken(type));
- if (!status.hasError()) {
- if (!type.exists() || type.isBinary() || type.isReadOnly())
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
- checkConflictingTarget(new SubProgressMonitor(monitor, 1), status);
- checkConflictingMethod(new SubProgressMonitor(monitor, 1), status);
- status.merge(Checks.validateModifiesFiles(computeModifiedFiles(fMethod.getJavaScriptUnit(), type.getJavaScriptUnit()), null));
- monitor.worked(1);
- if (!status.hasFatalError())
- fChangeManager= createChangeManager(status, new SubProgressMonitor(monitor, 1));
- }
- }
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_resolved_target, JavaStatusContext.create(fMethod)));
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Checks whether the target is a type variable or a generic type.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param status
- * the refactoring status
- */
- protected void checkGenericTarget(final IProgressMonitor monitor, final RefactoringStatus status) {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- final ITypeBinding binding= fTarget.getType();
- if (binding == null)
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_generic_targets, JavaStatusContext.create(fMethod)));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Checks whether the method has references to type variables or generic
- * types.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param declaration
- * the method declaration to check for generic types
- * @param status
- * the status of the condition checking
- */
- protected void checkGenericTypes(final IProgressMonitor monitor, final FunctionDeclaration declaration, final RefactoringStatus status) {
- Assert.isNotNull(monitor);
- Assert.isNotNull(declaration);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- final AstNodeFinder finder= new GenericReferenceFinder(declaration);
- declaration.accept(finder);
- if (!finder.getStatus().isOK())
- status.merge(finder.getStatus());
- } finally {
- monitor.done();
- }
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final RefactoringStatus checkInitialConditions(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask("", 4); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- status.merge(Checks.checkIfCuBroken(fMethod));
- if (!status.hasError()) {
- checkMethodDeclaration(new SubProgressMonitor(monitor, 1), status);
- if (status.isOK()) {
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- checkGenericTypes(new SubProgressMonitor(monitor, 1), declaration, status);
- checkMethodBody(new SubProgressMonitor(monitor, 1), declaration, status);
- checkPossibleTargets(new SubProgressMonitor(monitor, 1), declaration, status);
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Checks whether the instance method body is compatible with this
- * refactoring.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param declaration
- * the method declaration whose body to check
- * @param status
- * the status of the condition checking
- */
- protected void checkMethodBody(final IProgressMonitor monitor, final FunctionDeclaration declaration, final RefactoringStatus status) {
- Assert.isNotNull(monitor);
- Assert.isNotNull(declaration);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 3); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- AstNodeFinder finder= new SuperReferenceFinder();
- declaration.accept(finder);
- if (!finder.getStatus().isOK())
- status.merge(finder.getStatus());
- monitor.worked(1);
- finder= null;
- final IFunctionBinding binding= declaration.resolveBinding();
- if (binding != null) {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null)
- finder= new EnclosingInstanceReferenceFinder(declaring);
- }
- if (finder != null) {
- declaration.accept(finder);
- if (!finder.getStatus().isOK())
- status.merge(finder.getStatus());
- monitor.worked(1);
- finder= new RecursiveCallFinder(declaration);
- declaration.accept(finder);
- if (!finder.getStatus().isOK())
- status.merge(finder.getStatus());
- monitor.worked(1);
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Checks whether the instance method declaration is compatible with this
- * refactoring.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param status
- * the status of the condition checking
- * @throws JavaScriptModelException
- * if the method does not exist
- */
- protected void checkMethodDeclaration(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 2); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- final int flags= fMethod.getFlags();
- if (Flags.isStatic(flags))
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_static_methods, JavaStatusContext.create(fMethod)));
- else if (Flags.isAbstract(flags))
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_single_implementation, JavaStatusContext.create(fMethod)));
- monitor.worked(1);
- if (fMethod.isConstructor())
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_constructors, JavaStatusContext.create(fMethod)));
- monitor.worked(1);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Checks whether the method has possible targets to be moved to
- *
- * @param monitor
- * the progress monitor to display progress
- * @param declaration
- * the method declaration to check
- * @param status
- * the status of the condition checking
- */
- protected void checkPossibleTargets(final IProgressMonitor monitor, final FunctionDeclaration declaration, final RefactoringStatus status) {
- Assert.isNotNull(monitor);
- Assert.isNotNull(declaration);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- if (computeTargetCategories(declaration).length < 1)
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_cannot_be_moved, JavaStatusContext.create(fMethod)));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Searches for references to the original method.
- *
- * @param monitor
- * the progress monitor to use
- * @param status
- * the refactoring status to use
- * @return the array of search result groups
- * @throws CoreException
- * if an error occurred during search
- */
- protected SearchResultGroup[] computeMethodReferences(final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fMethod, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- return (SearchResultGroup[]) engine.getResults();
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Computes the files that are being modified by this refactoring.
- *
- * @param source
- * the source compilation unit
- * @param target
- * the target compilation unit
- * @return the modified files
- */
- protected IFile[] computeModifiedFiles(final IJavaScriptUnit source, final IJavaScriptUnit target) {
- Assert.isNotNull(source);
- Assert.isNotNull(target);
- if (source.equals(target))
- return ResourceUtil.getFiles(new IJavaScriptUnit[] { source });
- return ResourceUtil.getFiles(new IJavaScriptUnit[] { source, target });
- }
-
- /**
- * Returns the reserved identifiers in the method to move.
- *
- * @return the reserved identifiers
- * @throws JavaScriptModelException
- * if the method declaration could not be found
- */
- protected String[] computeReservedIdentifiers() throws JavaScriptModelException {
- final List names= new ArrayList();
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- if (declaration != null) {
- final List parameters= declaration.parameters();
- VariableDeclaration variable= null;
- for (int index= 0; index < parameters.size(); index++) {
- variable= (VariableDeclaration) parameters.get(index);
- names.add(variable.getName().getIdentifier());
- }
- final Block body= declaration.getBody();
- if (body != null) {
- final IBinding[] bindings= new ScopeAnalyzer(fSourceRewrite.getRoot()).getDeclarationsAfter(body.getStartPosition(), ScopeAnalyzer.VARIABLES);
- for (int index= 0; index < bindings.length; index++)
- names.add(bindings[index].getName());
- }
- }
- final String[] result= new String[names.size()];
- names.toArray(result);
- return result;
- }
-
- /**
- * Computes the target categories for the method to move.
- *
- * @param declaration
- * the method declaration
- * @return the possible targets as variable bindings of read-only fields and
- * parameters
- */
- protected IVariableBinding[] computeTargetCategories(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- if (fPossibleTargets.length == 0 || fCandidateTargets.length == 0) {
- final List possibleTargets= new ArrayList(16);
- final List candidateTargets= new ArrayList(16);
- final IFunctionBinding method= declaration.resolveBinding();
- if (method != null) {
- final ITypeBinding declaring= method.getDeclaringClass();
- IVariableBinding[] bindings= getArgumentBindings(declaration);
- ITypeBinding binding= null;
- for (int index= 0; index < bindings.length; index++) {
- binding= bindings[index].getType();
- if (binding.isClass() && binding.isFromSource()) {
- possibleTargets.add(bindings[index]);
- candidateTargets.add(bindings[index]);
- }
- }
- final ReadyOnlyFieldFinder visitor= new ReadyOnlyFieldFinder(declaring);
- declaration.accept(visitor);
- bindings= visitor.getReadOnlyFields();
- for (int index= 0; index < bindings.length; index++) {
- binding= bindings[index].getType();
- if (binding.isClass() && binding.isFromSource())
- possibleTargets.add(bindings[index]);
- }
- bindings= visitor.getDeclaredFields();
- for (int index= 0; index < bindings.length; index++) {
- binding= bindings[index].getType();
- if (binding.isClass() && binding.isFromSource())
- candidateTargets.add(bindings[index]);
- }
- }
- fPossibleTargets= new IVariableBinding[possibleTargets.size()];
- possibleTargets.toArray(fPossibleTargets);
- fCandidateTargets= new IVariableBinding[candidateTargets.size()];
- candidateTargets.toArray(fCandidateTargets);
- }
- return fPossibleTargets;
- }
-
- /**
- * Creates a visibility-adjusted target expression taking advantage of
- * existing accessor methods.
- *
- * @param enclosingElement
- * the java element which encloses the current method access.
- * @param expression
- * the expression to access the target, or <code>null</code>
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param rewrite
- * the ast rewrite to use
- * @return an adjusted target expression, or <code>null</code> if the
- * access did not have to be changed
- * @throws JavaScriptModelException
- * if an error occurs while accessing the target expression
- */
- protected Expression createAdjustedTargetExpression(final IJavaScriptElement enclosingElement, final Expression expression, final Map adjustments, final ASTRewrite rewrite) throws JavaScriptModelException {
- Assert.isNotNull(enclosingElement);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(rewrite);
- final IJavaScriptElement element= fTarget.getJavaElement();
- if (element != null && !Modifier.isPublic(fTarget.getModifiers())) {
- final IField field= (IField) fTarget.getJavaElement();
- if (field != null) {
- boolean same= field.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT).equals(enclosingElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT));
- final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
- final String modifier= same ? RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default : RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
- if (fUseGetters) {
- final IFunction getter= GetterSetterUtil.getGetter(field);
- if (getter != null) {
- final FunctionDeclaration method= ASTNodeSearchUtil.getMethodDeclarationNode(getter, fSourceRewrite.getRoot());
- if (method != null) {
- final IFunctionBinding binding= method.resolveBinding();
- if (binding != null && MemberVisibilityAdjustor.hasLowerVisibility(getter.getFlags(), same ? Modifier.NONE : (keyword == null ? Modifier.NONE : keyword.toFlagValue())) && MemberVisibilityAdjustor.needsVisibilityAdjustments(getter, keyword, adjustments))
- adjustments.put(getter, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(getter, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(getter))));
- final FunctionInvocation invocation= rewrite.getAST().newFunctionInvocation();
- invocation.setExpression(expression);
- invocation.setName(rewrite.getAST().newSimpleName(getter.getElementName()));
- return invocation;
- }
- }
- }
- if (MemberVisibilityAdjustor.hasLowerVisibility(field.getFlags(), (keyword == null ? Modifier.NONE : keyword.toFlagValue())) && MemberVisibilityAdjustor.needsVisibilityAdjustments(field, keyword, adjustments))
- adjustments.put(field, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(field, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_field_warning, new String[] { BindingLabelProvider.getBindingLabel(fTarget, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(field))));
- }
- }
- return null;
- }
-
- /**
- * Creates a generic argument list of the refactored moved method
- *
- * @param declaration
- * the method declaration of the method to move
- * @param arguments
- * the argument list to create
- * @param factory
- * the argument factory to use
- * @return <code>true</code> if a target node had to be inserted as first
- * argument, <code>false</code> otherwise
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected boolean createArgumentList(final FunctionDeclaration declaration, final List arguments, final IArgumentFactory factory) throws JavaScriptModelException {
- Assert.isNotNull(declaration);
- Assert.isNotNull(arguments);
- Assert.isNotNull(factory);
- final AstNodeFinder finder= new ThisReferenceFinder();
- declaration.accept(finder);
- IVariableBinding binding= null;
- VariableDeclaration variable= null;
- boolean added= false;
- final int size= declaration.parameters().size();
- for (int index= 0; index < size; index++) {
- variable= (VariableDeclaration) declaration.parameters().get(index);
- binding= variable.resolveBinding();
- if (binding != null) {
- if (!Bindings.equals(binding, fTarget))
- arguments.add(factory.getArgumentNode(binding, index == size - 1));
- else if (!finder.getStatus().isOK()) {
- arguments.add(factory.getTargetNode());
- added= true;
- }
- } else
- arguments.add(factory.getArgumentNode(binding, index == size - 1));
- }
- if (!finder.getStatus().isOK() && !added) {
- arguments.add(0, factory.getTargetNode());
- added= true;
- }
- return added;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 6); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating);
- final TextChange[] changes= fChangeManager.getAllChanges();
- if (changes.length == 1)
- return changes[0];
- final List list= new ArrayList(changes.length);
- list.addAll(Arrays.asList(changes));
- final Map arguments= new HashMap();
- String project= null;
- final IJavaScriptProject javaProject= fMethod.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_REFACTORING | JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final IType declaring= fMethod.getDeclaringType();
- try {
- if (declaring.isAnonymous() || declaring.isLocal())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_descriptor_description_short, fMethod.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fMethod, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(fTarget, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_moved_element_pattern, RefactoringCoreMessages.JavaRefactoringDescriptor_not_available));
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_target_element_pattern, BindingLabelProvider.getBindingLabel(fTarget, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_name_pattern, getMethodName()));
- if (needsTargetNode())
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_parameter_name_pattern, getTargetName()));
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.MOVE_METHOD, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fMethod));
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_NAME, fMethodName);
- arguments.put(ATTRIBUTE_TARGET_NAME, fTargetName);
- arguments.put(ATTRIBUTE_DEPRECATE, Boolean.valueOf(fDelegateDeprecation).toString());
- arguments.put(ATTRIBUTE_REMOVE, Boolean.valueOf(fRemove).toString());
- arguments.put(ATTRIBUTE_INLINE, Boolean.valueOf(fInline).toString());
- arguments.put(ATTRIBUTE_USE_GETTER, Boolean.valueOf(fUseGetters).toString());
- arguments.put(ATTRIBUTE_USE_SETTER, Boolean.valueOf(fUseSetters).toString());
- arguments.put(ATTRIBUTE_TARGET_INDEX, new Integer(getTargetIndex()).toString());
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.MoveInstanceMethodRefactoring_name, (Change[]) list.toArray(new Change[list.size()]));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the text change manager for this processor.
- *
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to display progress
- * @return the created text change manager
- * @throws JavaScriptModelException
- * if the method declaration could not be found
- * @throws CoreException
- * if the changes could not be generated
- */
- protected TextChangeManager createChangeManager(final RefactoringStatus status, final IProgressMonitor monitor) throws JavaScriptModelException, CoreException {
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 7); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating);
- fSourceRewrite.clearASTAndImportRewrites();
- final TextChangeManager manager= new TextChangeManager();
- final CompilationUnitRewrite targetRewrite= fMethod.getJavaScriptUnit().equals(getTargetType().getJavaScriptUnit()) ? fSourceRewrite : new CompilationUnitRewrite(getTargetType().getJavaScriptUnit());
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- final SearchResultGroup[] references= computeMethodReferences(new SubProgressMonitor(monitor, 1), status);
- final Map rewrites= new HashMap(2);
- rewrites.put(fSourceRewrite.getCu(), fSourceRewrite);
- if (!fSourceRewrite.getCu().equals(targetRewrite.getCu()))
- rewrites.put(targetRewrite.getCu(), targetRewrite);
- final ASTRewrite sourceRewrite= ASTRewrite.create(fSourceRewrite.getRoot().getAST());
- final MemberVisibilityAdjustor adjustor= new MemberVisibilityAdjustor(fTargetType, fMethod);
- adjustor.setStatus(status);
- adjustor.setVisibilitySeverity(RefactoringStatus.WARNING);
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
- adjustor.setRewrites(rewrites);
- adjustor.setRewrite(sourceRewrite, fSourceRewrite.getRoot());
- adjustor.adjustVisibility(new SubProgressMonitor(monitor, 1));
- final IDocument document= new Document(fMethod.getJavaScriptUnit().getBuffer().getContents());
- final boolean target= createMethodCopy(document, declaration, sourceRewrite, rewrites, adjustor.getAdjustments(), status, new SubProgressMonitor(monitor, 1));
- createMethodJavadocReferences(rewrites, declaration, references, target, status, new SubProgressMonitor(monitor, 1));
- if (!fSourceRewrite.getCu().equals(targetRewrite.getCu()))
- createMethodImports(targetRewrite, declaration, new SubProgressMonitor(monitor, 1), status);
- boolean removable= false;
- if (fInline) {
- removable= createMethodDelegator(rewrites, declaration, references, adjustor.getAdjustments(), target, status, new SubProgressMonitor(monitor, 1));
- if (fRemove && removable) {
- fSourceRewrite.getASTRewrite().remove(declaration, fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInstanceMethodProcessor_remove_original_method));
- if (!fSourceRewrite.getCu().equals(fTargetType.getJavaScriptUnit()))
- fSourceRewrite.getImportRemover().registerRemovedNode(declaration);
- }
- }
- if (!fRemove || !removable)
- createMethodDelegation(declaration, rewrites, adjustor.getAdjustments(), status, new SubProgressMonitor(monitor, 1));
-
- // Do not adjust visibility of a target field; references to the
- // field will be removed anyway.
- final IJavaScriptElement targetElement= fTarget.getJavaElement();
- if (targetElement != null && targetElement instanceof IField && (Flags.isPrivate(fMethod.getFlags()) || !fInline)) {
- final IVisibilityAdjustment adjustmentForTarget= (IVisibilityAdjustment) adjustor.getAdjustments().get(targetElement);
- if (adjustmentForTarget != null)
- adjustor.getAdjustments().remove(targetElement);
- }
-
- adjustor.rewriteVisibility(new SubProgressMonitor(monitor, 1));
- sourceRewrite.rewriteAST(document, fMethod.getJavaScriptProject().getOptions(true));
- createMethodSignature(document, declaration, sourceRewrite, rewrites);
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- for (final Iterator iterator= rewrites.keySet().iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- manager.manage(unit, rewrite.createChange());
- }
- return manager;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the necessary change to inline a method invocation represented by
- * a search match.
- *
- * @param rewriter
- * the current compilation unit rewrite
- * @param declaration
- * the source method declaration
- * @param match
- * the search match representing the method invocation
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param target
- * <code>true</code> if a target node had to be inserted as
- * first argument, <code>false</code> otherwise
- * @param status
- * the refactoring status
- * @return <code>true</code> if the inline change could be performed,
- * <code>false</code> otherwise
- * @throws JavaScriptModelException
- * if a problem occurred while creating the inlined target
- * expression for field targets
- */
- protected boolean createInlinedMethodInvocation(final CompilationUnitRewrite rewriter, final FunctionDeclaration declaration, final SearchMatch match, final Map adjustments, final boolean target, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(rewriter);
- Assert.isNotNull(declaration);
- Assert.isNotNull(match);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(status);
- boolean result= true;
- final ASTRewrite rewrite= rewriter.getASTRewrite();
- final ASTNode node= ASTNodeSearchUtil.findNode(match, rewriter.getRoot());
- final TextEditGroup group= rewriter.createGroupDescription(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_method_invocation);
- if (node instanceof FunctionInvocation) {
- final FunctionInvocation invocation= (FunctionInvocation) node;
- final ListRewrite list= rewrite.getListRewrite(invocation, FunctionInvocation.ARGUMENTS_PROPERTY);
- if (fTarget.isField()) {
- Expression access= null;
- if (invocation.getExpression() != null) {
- access= createInlinedTargetExpression(rewriter, (IJavaScriptElement) match.getElement(), invocation.getExpression(), adjustments, status);
- rewrite.set(invocation, FunctionInvocation.EXPRESSION_PROPERTY, access, group);
- } else
- rewrite.set(invocation, FunctionInvocation.EXPRESSION_PROPERTY, rewrite.getAST().newSimpleName(fTarget.getName()), group);
- if (target) {
- if (access == null || !(access instanceof FieldAccess))
- list.insertFirst(rewrite.getAST().newThisExpression(), null);
- else
- list.insertLast(rewrite.createCopyTarget(invocation.getExpression()), null);
- }
- } else {
- final IVariableBinding[] bindings= getArgumentBindings(declaration);
- if (bindings.length > 0) {
- int index= 0;
- for (; index < bindings.length; index++)
- if (Bindings.equals(bindings[index], fTarget))
- break;
- if (index < bindings.length && invocation.arguments().size() > index) {
- final Expression argument= (Expression) invocation.arguments().get(index);
- if (argument instanceof NullLiteral) {
- status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_null_argument, BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)), JavaStatusContext.create(rewriter.getCu(), invocation)));
- result= false;
- } else {
- if (argument instanceof ThisExpression)
- rewrite.remove(invocation.getExpression(), null);
- else
- rewrite.set(invocation, FunctionInvocation.EXPRESSION_PROPERTY, rewrite.createCopyTarget(argument), group);
- if (target) {
- if (invocation.getExpression() != null)
- list.replace(argument, rewrite.createCopyTarget(invocation.getExpression()), group);
- else {
- final ThisExpression expression= rewrite.getAST().newThisExpression();
- final AbstractTypeDeclaration member= (AbstractTypeDeclaration) ASTNodes.getParent(invocation, AbstractTypeDeclaration.class);
- if (member != null) {
- final ITypeBinding resolved= member.resolveBinding();
- if (ASTNodes.getParent(invocation, AnonymousClassDeclaration.class) != null || (resolved != null && resolved.isMember())) {
- final IFunctionBinding method= declaration.resolveBinding();
- if (method != null) {
- final ITypeBinding declaring= method.getDeclaringClass();
- if (declaring != null)
- expression.setQualifier(rewrite.getAST().newSimpleName(declaring.getName()));
- }
- }
- }
- list.replace(argument, expression, group);
- }
- } else
- list.remove(argument, group);
- }
- }
- }
- }
- if (result)
- rewrite.set(invocation, FunctionInvocation.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), group);
- }
- return result;
- }
-
- /**
- * Creates the target field expression for the inline method invocation.
- *
- * @param rewriter
- * the current compilation unit rewrite
- * @param enclosingElement
- * the enclosing java element of the method invocation.
- * @param original
- * the original method invocation expression
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param status
- * the refactoring status
- * @throws JavaScriptModelException
- * if a problem occurred while retrieving potential getter
- * methods of the target
- */
- protected Expression createInlinedTargetExpression(final CompilationUnitRewrite rewriter, final IJavaScriptElement enclosingElement, final Expression original, final Map adjustments, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(rewriter);
- Assert.isNotNull(enclosingElement);
- Assert.isNotNull(original);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(status);
- Assert.isTrue(fTarget.isField());
- final Expression expression= (Expression) ASTNode.copySubtree(fSourceRewrite.getASTRewrite().getAST(), original);
- final Expression result= createAdjustedTargetExpression(enclosingElement, expression, adjustments, fSourceRewrite.getASTRewrite());
- if (result == null) {
- final FieldAccess access= fSourceRewrite.getASTRewrite().getAST().newFieldAccess();
- access.setExpression(expression);
- access.setName(fSourceRewrite.getASTRewrite().getAST().newSimpleName(fTarget.getName()));
- return access;
- }
- return result;
- }
-
- /**
- * Creates the method arguments for the target method declaration.
- *
- * @param rewrites
- * the compilation unit rewrites
- * @param rewrite
- * the source ast rewrite
- * @param declaration
- * the source method declaration
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param status
- * the refactoring status
- * @return <code>true</code> if a target node had to be inserted as method
- * argument, <code>false</code> otherwise
- * @throws JavaScriptModelException
- * if an error occurs while accessing the types of the arguments
- */
- protected boolean createMethodArguments(final Map rewrites, final ASTRewrite rewrite, final FunctionDeclaration declaration, final Map adjustments, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(status);
- final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getJavaScriptUnit());
- final AST ast= rewriter.getRoot().getAST();
- final AstNodeFinder finder= new AnonymousClassReferenceFinder(declaration);
- declaration.accept(finder);
- final List arguments= new ArrayList(declaration.parameters().size() + 1);
- final boolean result= createArgumentList(declaration, arguments, new VisibilityAdjustingArgumentFactory(ast, rewrites, adjustments) {
-
- public final ASTNode getArgumentNode(final IVariableBinding binding, final boolean last) throws JavaScriptModelException {
- Assert.isNotNull(binding);
- final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
- final ITypeBinding type= binding.getType();
- adjustTypeVisibility(type);
- variable.setName(ast.newSimpleName(binding.getName()));
- variable.modifiers().addAll(ast.newModifiers(binding.getModifiers()));
- final IFunctionBinding method= binding.getDeclaringMethod();
- if (last && method != null && method.isVarargs()) {
- variable.setVarargs(true);
- String name= null;
- if (type.isArray()) {
- name= type.getElementType().getName();
- if (PrimitiveType.toCode(name) != null)
- variable.setType(ast.newPrimitiveType(PrimitiveType.toCode(name)));
- else
- variable.setType(ast.newSimpleType(ast.newSimpleName(name)));
- } else {
- name= type.getName();
- if (PrimitiveType.toCode(name) != null)
- variable.setType(ast.newPrimitiveType(PrimitiveType.toCode(name)));
- else
- variable.setType(ast.newSimpleType(ast.newSimpleName(name)));
- }
- } else
- variable.setType(rewriter.getImportRewrite().addImport(type, ast));
- return variable;
- }
-
- public final ASTNode getTargetNode() throws JavaScriptModelException {
- final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
- final IFunctionBinding method= declaration.resolveBinding();
- if (method != null) {
- final ITypeBinding declaring= method.getDeclaringClass();
- if (declaring != null) {
- adjustTypeVisibility(declaring);
- variable.setType(rewriter.getImportRewrite().addImport(declaring, ast));
- variable.setName(ast.newSimpleName(fTargetName));
- if (finder.getResult().size() > 0)
- variable.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
- }
- }
- return variable;
- }
- });
- final ListRewrite list= rewrite.getListRewrite(declaration, FunctionDeclaration.PARAMETERS_PROPERTY);
- ASTNode node= null;
- for (final Iterator iterator= declaration.parameters().iterator(); iterator.hasNext();) {
- node= (ASTNode) iterator.next();
- list.remove(node, null);
- }
- for (final Iterator iterator= arguments.iterator(); iterator.hasNext();) {
- node= (ASTNode) iterator.next();
- list.insertLast(node, null);
- }
- return result;
- }
-
- /**
- * Creates the method body for the target method declaration.
- *
- * @param rewriter
- * the target compilation unit rewrite
- * @param rewrite
- * the source ast rewrite
- * @param declaration
- * the source method declaration
- */
- protected void createMethodBody(final CompilationUnitRewrite rewriter, final ASTRewrite rewrite, final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- declaration.getBody().accept(new MethodBodyRewriter(rewriter, rewrite, declaration));
- }
-
- /**
- * Creates the method comment for the target method declaration.
- *
- * @param rewrite
- * the source ast rewrite
- * @param declaration
- * the source method declaration
- * @throws JavaScriptModelException
- * if the argument references could not be generated
- */
- protected void createMethodComment(final ASTRewrite rewrite, final FunctionDeclaration declaration) throws JavaScriptModelException {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(declaration);
- final JSdoc comment= declaration.getJavadoc();
- if (comment != null) {
- final List tags= new LinkedList(comment.tags());
- final IVariableBinding[] bindings= getArgumentBindings(declaration);
- final Map elements= new HashMap(bindings.length);
- String name= null;
- List fragments= null;
- TagElement element= null;
- TagElement reference= null;
- IVariableBinding binding= null;
- for (int index= 0; index < bindings.length; index++) {
- binding= bindings[index];
- for (final Iterator iterator= comment.tags().iterator(); iterator.hasNext();) {
- element= (TagElement) iterator.next();
- name= element.getTagName();
- fragments= element.fragments();
- if (name != null) {
- if (name.equals(TagElement.TAG_PARAM) && !fragments.isEmpty() && fragments.get(0) instanceof SimpleName) {
- final SimpleName simple= (SimpleName) fragments.get(0);
- if (binding.getName().equals(simple.getIdentifier())) {
- elements.put(binding.getKey(), element);
- tags.remove(element);
- }
- } else if (reference == null)
- reference= element;
- }
- }
- }
- if (bindings.length == 0 && reference == null) {
- for (final Iterator iterator= comment.tags().iterator(); iterator.hasNext();) {
- element= (TagElement) iterator.next();
- name= element.getTagName();
- fragments= element.fragments();
- if (name != null && !name.equals(TagElement.TAG_PARAM))
- reference= element;
- }
- }
- final List arguments= new ArrayList(bindings.length + 1);
- createArgumentList(declaration, arguments, new IArgumentFactory() {
-
- public final ASTNode getArgumentNode(final IVariableBinding argument, final boolean last) throws JavaScriptModelException {
- Assert.isNotNull(argument);
- if (elements.containsKey(argument.getKey()))
- return rewrite.createCopyTarget((ASTNode) elements.get(argument.getKey()));
- return JavadocUtil.createParamTag(argument.getName(), declaration.getAST(), fMethod.getJavaScriptProject());
- }
-
- public final ASTNode getTargetNode() throws JavaScriptModelException {
- return JavadocUtil.createParamTag(fTargetName, declaration.getAST(), fMethod.getJavaScriptProject());
- }
- });
- final ListRewrite rewriter= rewrite.getListRewrite(comment, JSdoc.TAGS_PROPERTY);
- ASTNode tag= null;
- for (final Iterator iterator= comment.tags().iterator(); iterator.hasNext();) {
- tag= (ASTNode) iterator.next();
- if (!tags.contains(tag))
- rewriter.remove(tag, null);
- }
- for (final Iterator iterator= arguments.iterator(); iterator.hasNext();) {
- tag= (ASTNode) iterator.next();
- if (reference != null)
- rewriter.insertBefore(tag, reference, null);
- else
- rewriter.insertLast(tag, null);
- }
- }
- }
-
- /**
- * Creates the method content of the moved method.
- *
- * @param document
- * the document representing the source compilation unit
- * @param declaration
- * the source method declaration
- * @param rewrite
- * the ast rewrite to use
- * @return the string representing the moved method body
- * @throws BadLocationException
- * if an offset into the document is invalid
- */
- protected String createMethodContent(final IDocument document, final FunctionDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
- Assert.isNotNull(document);
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
- final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
- final IJavaScriptProject project= fMethod.getJavaScriptProject();
- final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
- for (int index= 0; index < edits.length; index++)
- marker.addChild(edits[index]);
- final MultiTextEdit result= new MultiTextEdit();
- result.addChild(marker);
- final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
- processor.getRoot().addChild(result);
- processor.performEdits();
- final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
- return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
- }
-
- /**
- * Creates the necessary changes to create the delegate method with the
- * original method body.
- *
- * @param document
- * the buffer containing the source of the source compilation
- * unit
- * @param declaration
- * the method declaration to use as source
- * @param rewrite
- * the ast rewrite to use for the copy of the method body
- * @param rewrites
- * the compilation unit rewrites
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to display progress
- * @throws CoreException
- * if an error occurs
- * @return <code>true</code> if a target node had to be inserted as first
- * argument, <code>false</code> otherwise
- */
- protected boolean createMethodCopy(final IDocument document, final FunctionDeclaration declaration, final ASTRewrite rewrite, final Map rewrites, final Map adjustments, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(document);
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(rewrites);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- boolean target= false;
- final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getJavaScriptUnit());
- try {
- rewrite.set(declaration, FunctionDeclaration.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), null);
- boolean same= false;
- final IFunctionBinding binding= declaration.resolveBinding();
- if (binding != null) {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
- same= true;
- final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
- if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : (keyword == null ? Modifier.NONE : keyword.toFlagValue())) && MemberVisibilityAdjustor.needsVisibilityAdjustments(fMethod, keyword, adjustments)) {
- final MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(fMethod, keyword, RefactoringStatus.createStatus(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(fMethod), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(fMethod), null, RefactoringStatusEntry.NO_CODE, null));
- ModifierRewrite.create(rewrite, declaration).setVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), null);
- adjustment.setNeedsRewriting(false);
- adjustments.put(fMethod, adjustment);
- }
- }
- target= createMethodArguments(rewrites, rewrite, declaration, adjustments, status);
- createMethodComment(rewrite, declaration);
- createMethodBody(rewriter, rewrite, declaration);
- } finally {
- if (fMethod.getJavaScriptUnit().equals(getTargetType().getJavaScriptUnit()))
- rewriter.clearImportRewrites();
- }
- return target;
- }
-
- /**
- * Creates the necessary changes to replace the body of the method
- * declaration with an expression to invoke the delegate.
- *
- * @param declaration
- * the method declaration to replace its body
- * @param rewrites
- * the compilation unit rewrites
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to display progress
- * @throws CoreException
- * if the change could not be generated
- * @return <code>true</code> if a target node had to be inserted as first
- * argument, <code>false</code> otherwise
- */
- protected boolean createMethodDelegation(final FunctionDeclaration declaration, final Map rewrites, final Map adjustments, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(declaration);
- Assert.isNotNull(monitor);
-
- final DelegateInstanceMethodCreator creator= new DelegateInstanceMethodCreator(adjustments, rewrites);
- creator.setSourceRewrite(fSourceRewrite);
- creator.setCopy(false);
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setDeclaration(declaration);
- creator.setNewElementName(fMethodName);
- creator.prepareDelegate();
- creator.createEdit();
-
- return creator.getNeededInsertion();
- }
-
- /**
- * Creates the necessary changes to inline the method invocations to the
- * original method.
- *
- * @param rewrites
- * the map of compilation units to compilation unit rewrites
- * @param declaration
- * the source method declaration
- * @param groups
- * the search result groups representing all references to the
- * moved method, including references in comments
- * @param adjustments
- * the map of elements to visibility adjustments
- * @param target
- * <code>true</code> if a target node must be inserted as first
- * argument, <code>false</code> otherwise
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to use
- * @return <code>true</code> if all method invocations to the original
- * method declaration could be inlined, <code>false</code>
- * otherwise
- */
- protected boolean createMethodDelegator(final Map rewrites, final FunctionDeclaration declaration, final SearchResultGroup[] groups, final Map adjustments, final boolean target, final RefactoringStatus status, final IProgressMonitor monitor) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(declaration);
- Assert.isNotNull(groups);
- Assert.isNotNull(adjustments);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", groups.length); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating);
- try {
- boolean result= true;
- boolean found= false;
- final ITypeHierarchy hierarchy= fMethod.getDeclaringType().newTypeHierarchy(new SubProgressMonitor(monitor, 1));
- IType type= null;
- IFunction method= null;
- IType[] types= hierarchy.getAllSubtypes(fMethod.getDeclaringType());
- for (int index= 0; index < types.length && !found; index++) {
- type= types[index];
- method= JavaModelUtil.findMethod(fMethod.getElementName(), fMethod.getParameterTypes(), false, type);
- if (method != null)
- found= true;
- }
- types= hierarchy.getAllSuperclasses(fMethod.getDeclaringType());
- for (int index= 0; index < types.length && !found; index++) {
- type= types[index];
- method= JavaModelUtil.findMethod(fMethod.getElementName(), fMethod.getParameterTypes(), false, type);
- if (method != null)
- found= true;
- }
- if (found) {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_overridden, BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)), JavaStatusContext.create(fMethod)));
- result= false;
- } else {
- monitor.worked(1);
- SearchMatch[] matches= null;
- IJavaScriptElement element= null;
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- SearchResultGroup group= null;
- for (int index= 0; index < groups.length; index++) {
- group= groups[index];
- element= JavaScriptCore.create(group.getResource());
- if (element instanceof IJavaScriptUnit) {
- matches= group.getSearchResults();
- unit= (IJavaScriptUnit) element;
- rewrite= getCompilationUnitRewrite(rewrites, unit);
- SearchMatch match= null;
- for (int offset= 0; offset < matches.length; offset++) {
- match= matches[offset];
- if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_inaccurate, unit.getCorrespondingResource().getName()), JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength()))));
- result= false;
- } else if (!createInlinedMethodInvocation(rewrite, declaration, match, adjustments, target, status))
- result= false;
- }
- } else if (element != null) {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_binary_project, element.getJavaScriptProject().getElementName())));
- result= false;
- } else {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_binary_resource, group.getResource().getName())));
- result= false;
- }
- }
- monitor.worked(1);
- }
- return result;
- } catch (CoreException exception) {
- status.merge(RefactoringStatus.create(exception.getStatus()));
- return false;
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the necessary imports for the copied method in the target
- * compilation unit.
- *
- * @param rewrite
- * the target compilation unit rewrite
- * @param declaration
- * the source method declaration
- * @param monitor
- * the progress monitor to use
- * @param status
- * the refactoring status to use
- * @throws CoreException
- * if an error occurs
- */
- protected void createMethodImports(final CompilationUnitRewrite rewrite, final FunctionDeclaration declaration, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(declaration);
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating);
- try {
- ImportRewriteUtil.addImports(rewrite, declaration, new HashMap(), new HashMap(), false);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the necessary change to updated a comment reference represented
- * by a search match.
- *
- * @param rewrite
- * the current compilation unit rewrite
- * @param declaration
- * the source method declaration
- * @param match
- * the search match representing the method reference
- * @param targetNode
- * <code>true</code> if a target node had to be inserted as
- * first argument, <code>false</code> otherwise
- * @param status
- * the refactoring status
- */
- protected void createMethodJavadocReference(final CompilationUnitRewrite rewrite, final FunctionDeclaration declaration, final SearchMatch match, final boolean targetNode, final RefactoringStatus status) {
- Assert.isNotNull(rewrite);
- Assert.isNotNull(declaration);
- Assert.isNotNull(match);
- Assert.isNotNull(status);
- final ASTNode node= ASTNodeSearchUtil.findNode(match, rewrite.getRoot());
- if (node instanceof FunctionRef) {
- final AST ast= node.getAST();
- final FunctionRef successor= ast.newFunctionRef();
-
- rewrite.getASTRewrite().replace(node, successor, null);
- }
- }
-
- /**
- * Creates the necessary changes to update tag references to the original
- * method.
- *
- * @param rewrites
- * the map of compilation units to compilation unit rewrites
- * @param declaration
- * the source method declaration
- * @param groups
- * the search result groups representing all references to the
- * moved method, including references in comments
- * @param target
- * <code>true</code> if a target node must be inserted as first
- * argument, <code>false</code> otherwise
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to use
- */
- protected void createMethodJavadocReferences(final Map rewrites, final FunctionDeclaration declaration, final SearchResultGroup[] groups, final boolean target, final RefactoringStatus status, final IProgressMonitor monitor) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(declaration);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", groups.length); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating);
- try {
- SearchMatch[] matches= null;
- IJavaScriptElement element= null;
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- SearchResultGroup group= null;
- for (int index= 0; index < groups.length; index++) {
- group= groups[index];
- element= JavaScriptCore.create(group.getResource());
- unit= group.getCompilationUnit();
- if (element instanceof IJavaScriptUnit) {
- matches= group.getSearchResults();
- unit= (IJavaScriptUnit) element;
- rewrite= getCompilationUnitRewrite(rewrites, unit);
- SearchMatch match= null;
- for (int offset= 0; offset < matches.length; offset++) {
- match= matches[offset];
- if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_inaccurate, unit.getCorrespondingResource().getName()), JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength()))));
- } else
- createMethodJavadocReference(rewrite, declaration, match, target, status);
- }
- } else if (element != null) {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_javadoc_binary_project, element.getJavaScriptProject().getElementName())));
- } else {
- status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_javadoc_binary_resource, group.getResource().getName())));
- }
- monitor.worked(1);
- }
- } catch (CoreException exception) {
- status.merge(RefactoringStatus.create(exception.getStatus()));
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates a comment method reference to the moved method
- *
- * @param declaration
- * the method declaration of the original method
- * @param ast
- * the ast to create the method reference for
- * @return the created link tag to reference the method
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected ASTNode createMethodReference(final FunctionDeclaration declaration, final AST ast) throws JavaScriptModelException {
- Assert.isNotNull(ast);
- Assert.isNotNull(declaration);
- final FunctionRef reference= ast.newFunctionRef();
- reference.setName(ast.newSimpleName(fMethodName));
- reference.setQualifier(ASTNodeFactory.newName(ast, JavaModelUtil.getFullyQualifiedName(fTargetType)));
- createArgumentList(declaration, reference.parameters(), new IArgumentFactory() {
-
- public final ASTNode getArgumentNode(final IVariableBinding binding, final boolean last) {
- Assert.isNotNull(binding);
- final FunctionRefParameter parameter= ast.newFunctionRefParameter();
- parameter.setType(ASTNodeFactory.newType(ast, binding.getType().getName()));
- return parameter;
- }
-
- public final ASTNode getTargetNode() {
- final FunctionRefParameter parameter= ast.newFunctionRefParameter();
- final IFunctionBinding method= declaration.resolveBinding();
- if (method != null) {
- final ITypeBinding declaring= method.getDeclaringClass();
- if (declaring != null)
- parameter.setType(ASTNodeFactory.newType(ast, Bindings.getFullyQualifiedName(declaring)));
- }
- return parameter;
- }
- });
- return reference;
- }
-
- /**
- * @param document
- * the buffer containing the source of the source compilation
- * unit
- * @param declaration
- * the method declaration to use as source
- * @param rewrite
- * the ast rewrite to use for the copy of the method body
- * @param rewrites
- * the compilation unit rewrites
- * @throws JavaScriptModelException
- * if the insertion point cannot be found
- */
- protected void createMethodSignature(final IDocument document, final FunctionDeclaration declaration, final ASTRewrite rewrite, final Map rewrites) throws JavaScriptModelException {
- Assert.isNotNull(document);
- Assert.isNotNull(declaration);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(rewrites);
- try {
- final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getJavaScriptUnit());
- final FunctionDeclaration stub= (FunctionDeclaration) rewriter.getASTRewrite().createStringPlaceholder(createMethodContent(document, declaration, rewrite), ASTNode.FUNCTION_DECLARATION);
- final AbstractTypeDeclaration type= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(getTargetType(), rewriter.getRoot());
- rewriter.getASTRewrite().getListRewrite(type, type.getBodyDeclarationsProperty()).insertAt(stub, ASTNodes.getInsertionIndex(stub, type.bodyDeclarations()), rewriter.createGroupDescription(RefactoringCoreMessages.MoveInstanceMethodProcessor_add_moved_method));
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
- /**
- * Creates the expression to access the new target.
- *
- * @param declaration
- * the method declaration where to access the target
- * @return the corresponding expression
- */
- protected Expression createSimpleTargetAccessExpression(final FunctionDeclaration declaration) {
- Assert.isNotNull(declaration);
- Expression expression= null;
- final AST ast= declaration.getAST();
- final ITypeBinding type= fTarget.getDeclaringClass();
- if (type != null) {
- boolean shadows= false;
- final IVariableBinding[] bindings= getArgumentBindings(declaration);
- IVariableBinding variable= null;
- for (int index= 0; index < bindings.length; index++) {
- variable= bindings[index];
- if (fMethod.getDeclaringType().getField(variable.getName()).exists()) {
- shadows= true;
- break;
- }
- }
- if (fSettings.useKeywordThis || shadows) {
- final FieldAccess access= ast.newFieldAccess();
- access.setName(ast.newSimpleName(fTarget.getName()));
- access.setExpression(ast.newThisExpression());
- expression= access;
- } else
- expression= ast.newSimpleName(fTarget.getName());
- } else
- expression= ast.newSimpleName(fTarget.getName());
- return expression;
- }
-
- /**
- * Returns the candidate targets for the method to move.
- *
- * @return the candidate targets as variable bindings of fields and
- * parameters
- */
- public final IVariableBinding[] getCandidateTargets() {
- Assert.isNotNull(fCandidateTargets);
- return fCandidateTargets;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getComment() {
- return fComment;
- }
-
- /**
- * Returns a compilation unit rewrite for the specified compilation unit.
- *
- * @param rewrites
- * the compilation unit rewrite map
- * @param unit
- * the compilation unit
- * @return the corresponding compilation unit rewrite
- */
- protected CompilationUnitRewrite getCompilationUnitRewrite(final Map rewrites, final IJavaScriptUnit unit) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(unit);
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- if (rewrite == null) {
- rewrite= new CompilationUnitRewrite(unit);
- rewrites.put(unit, rewrite);
- }
- return rewrite;
- }
-
- /**
- * {@inheritDoc}
- */
- public final boolean getDelegateUpdating() {
- return fDelegatingUpdating;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_moved_plural;
- else
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_moved_singular;
- }
-
- /**
- * {@inheritDoc}
- */
- public final boolean getDeprecateDelegates() {
- return fDelegateDeprecation;
- }
-
- /**
- * {@inheritDoc}
- */
- public final Object[] getElements() {
- return new Object[] { fMethod };
- }
-
- /**
- * {@inheritDoc}
- */
- public final String getIdentifier() {
- return IDENTIFIER;
- }
-
- /**
- * Returns the method to be moved.
- *
- * @return the method to be moved
- */
- public final IFunction getMethod() {
- return fMethod;
- }
-
- /**
- * Returns the new method name.
- *
- * @return the name of the new method
- */
- public final String getMethodName() {
- return fMethodName;
- }
-
- /**
- * Returns the possible targets for the method to move.
- *
- * @return the possible targets as variable bindings of read-only fields and
- * parameters
- */
- public final IVariableBinding[] getPossibleTargets() {
- Assert.isNotNull(fPossibleTargets);
- return fPossibleTargets;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public final String getProcessorName() {
- return RefactoringCoreMessages.MoveInstanceMethodProcessor_name;
- }
-
- /**
- * Returns the index of the chosen target.
- *
- * @return the target index
- */
- protected final int getTargetIndex() {
- final IVariableBinding[] targets= getPossibleTargets();
- int result= -1;
- for (int index= 0; index < targets.length; index++) {
- if (Bindings.equals(fTarget, targets[index])) {
- result= index;
- break;
- }
- }
- return result;
- }
-
- /**
- * Returns the new target name.
- *
- * @return the name of the new target
- */
- public final String getTargetName() {
- return fTargetName;
- }
-
- /**
- * Returns the type of the new target.
- *
- * @return the type of the new target
- * @throws JavaScriptModelException
- * if the type does not exist
- */
- protected IType getTargetType() throws JavaScriptModelException {
- Assert.isNotNull(fTarget);
- if (fTargetType == null) {
- final ITypeBinding binding= fTarget.getType();
- if (binding != null)
- fTargetType= (IType) binding.getJavaElement();
- else
- throw new JavaScriptModelException(new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, RefactoringCoreMessages.MoveInstanceMethodProcessor_cannot_be_moved, null)));
- }
- return fTargetType;
- }
-
- /**
- * Initializes the refactoring with the given input.
- *
- * @param method
- * the method to move
- */
- protected void initialize(final IFunction method) {
- Assert.isNotNull(method);
- fSourceRewrite= new CompilationUnitRewrite(fMethod.getJavaScriptUnit());
- fMethodName= method.getElementName();
- fTargetName= suggestTargetName();
- if (fSettings == null)
- fSettings= JavaPreferencesSettings.getCodeGenerationSettings(fMethod.getJavaScriptProject());
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- final String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.METHOD)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.MOVE_METHOD);
- else {
- fMethod= (IFunction) element;
- initialize(fMethod);
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String name= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_NAME);
- if (name != null) {
- final RefactoringStatus status= setMethodName(name);
- if (status.hasError())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_NAME));
- final String deprecate= extended.getAttribute(ATTRIBUTE_DEPRECATE);
- if (deprecate != null) {
- fDelegateDeprecation= Boolean.valueOf(deprecate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE));
- final String remove= extended.getAttribute(ATTRIBUTE_REMOVE);
- if (remove != null) {
- fRemove= Boolean.valueOf(remove).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REMOVE));
- final String inline= extended.getAttribute(ATTRIBUTE_INLINE);
- if (inline != null) {
- fInline= Boolean.valueOf(inline).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INLINE));
- final String getter= extended.getAttribute(ATTRIBUTE_USE_GETTER);
- if (getter != null)
- fUseGetters= Boolean.valueOf(getter).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_USE_GETTER));
- final String setter= extended.getAttribute(ATTRIBUTE_USE_SETTER);
- if (setter != null)
- fUseSetters= Boolean.valueOf(setter).booleanValue();
- else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_USE_SETTER));
- final String target= extended.getAttribute(ATTRIBUTE_TARGET_NAME);
- if (target != null) {
- final RefactoringStatus status= setTargetName(target);
- if (status.hasError())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TARGET_NAME));
- final String value= extended.getAttribute(ATTRIBUTE_TARGET_INDEX);
- if (value != null) {
- try {
- final int index= Integer.valueOf(value).intValue();
- if (index >= 0) {
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- if (declaration != null) {
- final IVariableBinding[] bindings= computeTargetCategories(declaration);
- if (bindings != null && index < bindings.length)
- setTarget(bindings[index]);
- }
- }
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { value, ATTRIBUTE_TARGET_INDEX }));
- } catch (JavaScriptModelException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { value, ATTRIBUTE_TARGET_INDEX }));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_TARGET_INDEX));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public final boolean isApplicable() throws CoreException {
- return fMethod.exists() && !fMethod.isConstructor() && !fMethod.isBinary() && !fMethod.isReadOnly() && fMethod.getJavaScriptUnit() != null && !JdtFlags.isStatic(fMethod);
- }
-
- /**
- * Is the specified name a target access?
- *
- * @param name
- * the name to check
- * @return <code>true</code> if this name is a target access,
- * <code>false</code> otherwise
- */
- protected boolean isTargetAccess(final Name name) {
- Assert.isNotNull(name);
- final IBinding binding= name.resolveBinding();
- if (Bindings.equals(fTarget, binding))
- return true;
- if (name.getParent() instanceof FieldAccess) {
- final FieldAccess access= (FieldAccess) name.getParent();
- final Expression expression= access.getExpression();
- if (expression instanceof Name)
- return isTargetAccess((Name) expression);
- } else if (name instanceof QualifiedName) {
- final QualifiedName qualified= (QualifiedName) name;
- if (qualified.getQualifier() != null)
- return isTargetAccess(qualified.getQualifier());
- }
- return false;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus,
- * org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
- */
- public final RefactoringParticipant[] loadParticipants(final RefactoringStatus status, final SharableParticipants participants) throws CoreException {
- return new RefactoringParticipant[0];
- }
-
- /**
- * Does the moved method need a target node?
- *
- * @return <code>true</code> if it needs a target node, <code>false</code>
- * otherwise
- */
- public final boolean needsTargetNode() {
- return fTargetNode;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setComment(final String comment) {
- fComment= comment;
- }
-
- /**
- * {@inheritDoc}
- */
- public final void setDelegateUpdating(final boolean updating) {
- fDelegatingUpdating= updating;
- setInlineDelegator(!updating);
- setRemoveDelegator(!updating);
- }
-
- /**
- * {@inheritDoc}
- */
- public final void setDeprecateDelegates(final boolean deprecate) {
- fDelegateDeprecation= deprecate;
- }
-
- /**
- * Determines whether the delegator has to be inlined.
- *
- * @param inline
- * <code>true</code> to inline the delegator,
- * <code>false</code> otherwise
- */
- public final void setInlineDelegator(final boolean inline) {
- fInline= inline;
- }
-
- /**
- * Sets the new method name.
- *
- * @param name
- * the name to set
- * @return the status of the operation
- */
- public final RefactoringStatus setMethodName(final String name) {
- Assert.isNotNull(name);
- RefactoringStatus status= Checks.checkMethodName(name);
- if (status.hasFatalError())
- return status;
- fMethodName= name;
- return status;
- }
-
- /**
- * Determines whether the delegator has to be removed after inlining. Note
- * that the option to inline the delegator has to be enabled if this method
- * is called with the argument <code>true</code>.
- *
- * @param remove
- * <code>true</code> if it should be removed,
- * <code>false</code> otherwise
- */
- public final void setRemoveDelegator(final boolean remove) {
- Assert.isTrue(!remove || fInline);
- fRemove= remove;
- }
-
- /**
- * Sets the new target.
- *
- * @param target
- * the target to set
- */
- public final void setTarget(final IVariableBinding target) {
- Assert.isNotNull(target);
- fTarget= target;
- fTargetType= null;
- try {
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
- if (declaration != null) {
- final AstNodeFinder finder= new ThisReferenceFinder();
- declaration.accept(finder);
- fTargetNode= !finder.getResult().isEmpty();
- return;
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- fTargetNode= true;
- }
-
- /**
- * Sets the new target name.
- *
- * @param name
- * the name to set
- * @return the status of the operation
- */
- public final RefactoringStatus setTargetName(final String name) {
- Assert.isNotNull(name);
- final RefactoringStatus status= Checks.checkTempName(name);
- if (status.hasFatalError())
- return status;
- fTargetName= name;
- return status;
- }
-
- /**
- * Determines whether getter methods should be used to resolve visibility
- * issues.
- *
- * @param use
- * <code>true</code> if getter methods should be used,
- * <code>false</code> otherwise
- */
- public final void setUseGetters(final boolean use) {
- fUseGetters= use;
- }
-
- /**
- * Determines whether setter methods should be used to resolve visibility
- * issues.
- *
- * @param use
- * <code>true</code> if setter methods should be used,
- * <code>false</code> otherwise
- */
- public final void setUseSetters(final boolean use) {
- fUseSetters= use;
- }
-
- /**
- * Should getter methods be used to resolve visibility issues?
- *
- * @return <code>true</code> if getter methods should be used,
- * <code>false</code> otherwise
- */
- public final boolean shouldUseGetters() {
- return fUseGetters;
- }
-
- /**
- * Should setter methods be used to resolve visibility issues?
- *
- * @return <code>true</code> if setter methods should be used,
- * <code>false</code> otherwise
- */
- public final boolean shouldUseSetters() {
- return fUseSetters;
- }
-
- /**
- * Returns a best guess for the name of the new target.
- *
- * @return a best guess for the name
- */
- protected String suggestTargetName() {
- try {
-
- final String[] candidates= StubUtility.getArgumentNameSuggestions(fMethod.getDeclaringType(),fMethod.getJavaScriptUnit(), computeReservedIdentifiers());
- if (candidates.length > 0) {
- if (candidates[0].indexOf('$') < 0)
- return candidates[0];
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- return "arg"; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodRefactoring.java
deleted file mode 100644
index 73158cea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveInstanceMethodRefactoring.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-/**
- * Refactoring to move an instance method to another class.
- */
-public final class MoveInstanceMethodRefactoring extends JavaMoveRefactoring {
-
- /**
- * Creates a new move instance method refactoring.
- *
- * @param processor
- * the move instance method processor to use
- */
- public MoveInstanceMethodRefactoring(final MoveInstanceMethodProcessor processor) {
- super(processor);
- }
-
- /**
- * Returns the move instance method processor
- *
- * @return the move processor
- */
- public final MoveInstanceMethodProcessor getMoveMethodProcessor() {
- return (MoveInstanceMethodProcessor) getMoveProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public final String getName() {
- return RefactoringCoreMessages.MoveInstanceMethodRefactoring_name;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMemberAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMemberAnalyzer.java
deleted file mode 100644
index 4bdd71da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMemberAnalyzer.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IPackageBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTFlattener;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-
-/* package */ class MoveStaticMemberAnalyzer extends ASTVisitor {
-
- protected RefactoringStatus fStatus;
-
- protected ITypeBinding fSource;
- protected ITypeBinding fTarget;
- protected CompilationUnitRewrite fCuRewrite;
- protected IBinding[] fMembers;
-
- protected boolean fNeedsImport;
-
- protected Set fProcessed;
-
- protected static final String REFERENCE_UPDATE= RefactoringCoreMessages.MoveMembersRefactoring_referenceUpdate;
-
- public MoveStaticMemberAnalyzer(CompilationUnitRewrite cuRewrite, IBinding[] members, ITypeBinding source, ITypeBinding target) {
- super(true);
- fStatus= new RefactoringStatus();
- fCuRewrite= cuRewrite;
- fMembers= members;
- fSource= source;
- fTarget= target;
- fProcessed= new HashSet();
- }
-
- public RefactoringStatus getStatus() {
- return fStatus;
- }
-
- protected boolean isProcessed(ASTNode node) {
- return fProcessed.contains(node);
- }
-
- protected void rewrite(SimpleName node, ITypeBinding type) {
- AST ast= node.getAST();
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- Name dummy= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- QualifiedName name= ast.newQualifiedName(dummy, ast.newSimpleName(node.getIdentifier()));
- fCuRewrite.getASTRewrite().replace(node, name, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fCuRewrite.getImportRemover().registerRemovedNode(node);
- fProcessed.add(node);
- fNeedsImport= true;
- }
-
- protected void rewrite(QualifiedName node, ITypeBinding type) {
- rewriteName(node.getQualifier(), type);
- fProcessed.add(node.getName());
- }
-
- protected void rewrite(FieldAccess node, ITypeBinding type) {
- Expression exp= node.getExpression();
- if (exp == null) {
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- fCuRewrite.getASTRewrite().set(node, FieldAccess.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fNeedsImport= true;
- } else if (exp instanceof Name) {
- rewriteName((Name)exp, type);
- } else {
- rewriteExpression(node, exp, type);
- }
- fProcessed.add(node.getName());
- }
-
- protected void rewrite(FunctionInvocation node, ITypeBinding type) {
- Expression exp= node.getExpression();
- if (exp == null) {
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- exp= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- fCuRewrite.getASTRewrite().set(node, FunctionInvocation.EXPRESSION_PROPERTY, exp, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fNeedsImport= true;
- } else if (exp instanceof Name) {
- rewriteName((Name)exp, type);
- } else {
- rewriteExpression(node, exp, type);
- }
- fProcessed.add(node.getName());
- }
-
- protected void rewrite(MemberRef node, ITypeBinding type) {
- Name qualifier= node.getQualifier();
- if (qualifier == null) {
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- qualifier= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- fCuRewrite.getASTRewrite().set(node, MemberRef.QUALIFIER_PROPERTY, qualifier, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fNeedsImport= true;
- } else {
- rewriteName(qualifier, type);
- }
- fProcessed.add(node.getName());
- }
-
- protected void rewrite(FunctionRef node, ITypeBinding type) {
- Name qualifier= node.getQualifier();
- if (qualifier == null) {
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- qualifier= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- fCuRewrite.getASTRewrite().set(node, FunctionRef.QUALIFIER_PROPERTY, qualifier, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fNeedsImport= true;
- } else {
- rewriteName(qualifier, type);
- }
- fProcessed.add(node.getName());
- }
-
- private void rewriteName(Name name, ITypeBinding type) {
- AST creator= name.getAST();
- boolean fullyQualified= false;
- if (name instanceof QualifiedName) {
- SimpleName left= ASTNodes.getLeftMostSimpleName(name);
- if (left.resolveBinding() instanceof IPackageBinding)
- fullyQualified= true;
- }
- if (fullyQualified) {
- fCuRewrite.getASTRewrite().replace(
- name,
- ASTNodeFactory.newName(creator, type.getQualifiedName()),
- fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fCuRewrite.getImportRemover().registerRemovedNode(name);
- } else {
- Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST());
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- Name n= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
- fCuRewrite.getASTRewrite().replace(
- name,
- n,
- fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fCuRewrite.getImportRemover().registerRemovedNode(name);
- fNeedsImport= true;
- }
- }
-
- private void rewriteExpression(ASTNode node, Expression exp, ITypeBinding type) {
- fCuRewrite.getASTRewrite().replace(exp, fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST()), fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
- fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
- fCuRewrite.getImportRemover().registerRemovedNode(exp);
- fNeedsImport= true;
- nonStaticAccess(node);
- }
-
- protected void nonStaticAccess(ASTNode node) {
- fStatus.addWarning(RefactoringCoreMessages.MoveStaticMemberAnalyzer_nonStatic,
- JavaStatusContext.create(fCuRewrite.getCu(), node));
- }
-
- protected boolean isStaticAccess(Expression exp, ITypeBinding type) {
- if (!(exp instanceof Name))
- return false;
- return Bindings.equals(type, ((Name)exp).resolveBinding());
- }
-
- protected boolean isMovedMember(IBinding binding) {
- if (binding == null)
- return false;
- for (int i= 0; i < fMembers.length; i++) {
- if (Bindings.equals(fMembers[i], binding))
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java
deleted file mode 100644
index 468a3f2c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java
+++ /dev/null
@@ -1,1035 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
-import org.eclipse.ltk.core.refactoring.participants.MoveProcessor;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.MoveStaticMembersDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateFieldCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.delegates.DelegateMethodCreator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.participants.JavaProcessors;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.refactoring.IRefactoringProcessorIds;
-
-public final class MoveStaticMembersProcessor extends MoveProcessor implements IDelegateUpdating, IScriptableRefactoring, ICommentProvider {
-
- private static final String ATTRIBUTE_DELEGATE="delegate"; //$NON-NLS-1$
- private static final String ATTRIBUTE_DEPRECATE="deprecate"; //$NON-NLS-1$
- private static final String TRACKED_POSITION_PROPERTY= "MoveStaticMembersProcessor.trackedPosition"; //$NON-NLS-1$
-
- private IMember[] fMembersToMove;
- private IType fDestinationType;
- private String fDestinationTypeName;
-
- private CodeGenerationSettings fPreferences;
- private CompositeChange fChange;
- private CompilationUnitRewrite fSource;
- private ITypeBinding fSourceBinding;
- private CompilationUnitRewrite fTarget;
- private IBinding[] fMemberBindings;
- private BodyDeclaration[] fMemberDeclarations;
- private boolean fDelegateUpdating;
- private boolean fDelegateDeprecation;
- private String fComment;
-
- private static class TypeReferenceFinder extends ASTVisitor {
- List fResult= new ArrayList();
- Set fDefined= new HashSet();
- public static List perform(ASTNode root) {
- TypeReferenceFinder visitor= new TypeReferenceFinder();
- root.accept(visitor);
- return visitor.fResult;
- }
- public boolean visit(TypeDeclaration node) {
- fDefined.add(node.resolveBinding());
- return true;
- }
- public boolean visit(SimpleName node) {
- IBinding binding= node.resolveBinding();
- if (!(binding instanceof ITypeBinding))
- return true;
- if (!fDefined.contains(binding))
- fResult.add(binding);
- return true;
- }
-
- }
-
- /**
- * Creates a new move static members processor.
- * @param members the members to move, or <code>null</code> if invoked by scripting
- * @param settings the code generation settings, or <code>null</code> if invoked by scripting
- */
- public MoveStaticMembersProcessor(IMember[] members, CodeGenerationSettings settings) {
- fMembersToMove= members;
- fPreferences= settings;
- fDelegateUpdating= false;
- fDelegateDeprecation= true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isMoveStaticMembersAvailable(fMembersToMove);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getElements() {
- Object[] result= new Object[fMembersToMove.length];
- System.arraycopy(fMembersToMove, 0, result, 0, fMembersToMove.length);
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getIdentifier() {
- return IRefactoringProcessorIds.MOVE_STATIC_MEMBERS_PROCESSOR;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants) throws CoreException {
- List result= new ArrayList();
- MoveArguments args= new MoveArguments(fDestinationType, true);
- String[] natures= JavaProcessors.computeAffectedNaturs(fMembersToMove);
- for (int i= 0; i < fMembersToMove.length; i++) {
- IMember member= fMembersToMove[i];
- result.addAll(Arrays.asList(ParticipantManager.loadMoveParticipants(
- status, this, member, args, natures, sharedParticipants)));
- }
- return (RefactoringParticipant[])result.toArray(new RefactoringParticipant[result.size()]);
- }
-
- //------------------- IDelegateUpdating ----------------------
-
- public boolean canEnableDelegateUpdating() {
- try {
- for (int i= 0; i < fMembersToMove.length; i++) {
- if (isDelegateCreationAvailable(fMembersToMove[i]))
- return true;
- }
- } catch (JavaScriptModelException e) {
- return false;
- }
- return false;
- }
-
- private boolean isDelegateCreationAvailable(IMember member) throws JavaScriptModelException {
- if (member instanceof IFunction)
- return true;
- if (member instanceof IField && RefactoringAvailabilityTester.isDelegateCreationAvailable(((IField)member)))
- return true;
- return false;
- }
-
- public boolean getDelegateUpdating() {
- return fDelegateUpdating;
- }
-
- public void setDelegateUpdating(boolean updating) {
- fDelegateUpdating= updating;
- }
-
- public boolean getDeprecateDelegates() {
- return fDelegateDeprecation;
- }
-
- public void setDeprecateDelegates(boolean deprecate) {
- fDelegateDeprecation= deprecate;
- }
-
- public String getProcessorName() {
- return RefactoringCoreMessages.MoveMembersRefactoring_Move_Members;
- }
-
- public IType getDestinationType() {
- return fDestinationType;
- }
-
- public void setDestinationTypeFullyQualifiedName(String fullyQualifiedTypeName) throws JavaScriptModelException {
- Assert.isNotNull(fullyQualifiedTypeName);
- fDestinationType= resolveType(fullyQualifiedTypeName);
- //workaround for bug 36032: IJavaScriptProject#findType(..) doesn't find secondary type
- fDestinationTypeName= fullyQualifiedTypeName;
- }
-
- public IMember[] getMembersToMove() {
- return fMembersToMove;
- }
-
- public IType getDeclaringType() {
- //all methods declared in same type - checked in precondition
- return fMembersToMove[0].getDeclaringType(); //index safe - checked in areAllMoveable()
- }
-
- private IType resolveType(String qualifiedTypeName) throws JavaScriptModelException{
- IType type= getDeclaringType().getJavaScriptProject().findType(qualifiedTypeName);
- if (type == null)
- type= getDeclaringType().getJavaScriptProject().findType(getDeclaringType().getPackageFragment().getElementName(), qualifiedTypeName);
- return type;
- }
-
- //---- Activation checking ------------------------------------
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
- RefactoringStatus result= new RefactoringStatus();
- result.merge(checkDeclaringType());
- pm.worked(1);
- if (result.hasFatalError())
- return result;
-
- fSource= new CompilationUnitRewrite(fMembersToMove[0].getJavaScriptUnit());
- fSourceBinding= (ITypeBinding)((SimpleName)NodeFinder.perform(fSource.getRoot(), fMembersToMove[0].getDeclaringType().getNameRange())).resolveBinding();
- fMemberBindings= getMemberBindings();
- if (fSourceBinding == null || hasUnresolvedMemberBinding()) {
- result.addFatalError(Messages.format(
- RefactoringCoreMessages.MoveMembersRefactoring_compile_errors,
- fSource.getCu().getElementName()));
- }
- fMemberDeclarations= getASTMembers(result);
- return result;
- } finally {
- pm.done();
- }
- }
-
- private boolean hasUnresolvedMemberBinding() {
- for (int i= 0; i < fMemberBindings.length; i++) {
- if (fMemberBindings[i] == null)
- return true;
- }
- return false;
- }
-
- private RefactoringStatus checkDeclaringType(){
- IType declaringType= getDeclaringType();
-
- if (JavaModelUtil.getFullyQualifiedName(declaringType).equals("java.lang.Object")) //$NON-NLS-1$
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_Object);
-
- if (declaringType.isBinary())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_binary);
-
- if (declaringType.isReadOnly())
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveMembersRefactoring_read_only);
-
- return null;
- }
-
- //---- Input checking ------------------------------------
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
- fTarget= null;
- try {
- pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 10);
-
- RefactoringStatus result= new RefactoringStatus();
-
- fSource.clearASTAndImportRewrites();
-
- result.merge(checkDestinationType());
- if (result.hasFatalError())
- return result;
-
- result.merge(checkDestinationInsideTypeToMove());
- if (result.hasFatalError())
- return result;
-
- result.merge(MemberCheckUtil.checkMembersInDestinationType(fMembersToMove, fDestinationType));
- if (result.hasFatalError())
- return result;
-
- if (result.hasFatalError())
- return result;
-
- List modifiedCus= new ArrayList();
- createChange(modifiedCus, result, new SubProgressMonitor(pm, 7));
- IFile[] changedFiles= getAllFilesToModify(modifiedCus);
- ResourceChangeChecker checker= (ResourceChangeChecker)context.getChecker(ResourceChangeChecker.class);
- for (int i= 0; i < changedFiles.length; i++) {
- checker.getDeltaFactory().change(changedFiles[i]);
- }
-
- return result;
- } finally {
- pm.done();
- }
- }
-
- private IFile[] getAllFilesToModify(List modifiedCus) {
- Set result= new HashSet();
- IResource resource= fDestinationType.getJavaScriptUnit().getResource();
- result.add(resource);
- for (int i= 0; i < fMembersToMove.length; i++) {
- resource= fMembersToMove[i].getJavaScriptUnit().getResource();
- if (resource != null)
- result.add(resource);
- }
- for (Iterator iter= modifiedCus.iterator(); iter.hasNext();) {
- IJavaScriptUnit unit= (IJavaScriptUnit)iter.next();
- if (unit.getResource() != null)
- result.add(unit.getResource());
- }
- return (IFile[]) result.toArray(new IFile[result.size()]);
- }
-
- private RefactoringStatus checkDestinationType() throws JavaScriptModelException {
- if (fDestinationType == null){
- String message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_not_found, fDestinationTypeName);
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- if (fDestinationType.equals(getDeclaringType())){
- String message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_same,
- JavaElementUtil.createSignature(fDestinationType));
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- if (! fDestinationType.exists()){
- String message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_not_exist,
- JavaElementUtil.createSignature(fDestinationType));
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- if (fDestinationType.isBinary()){
- String message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_dest_binary,
- JavaElementUtil.createSignature(fDestinationType));
- return RefactoringStatus.createFatalErrorStatus(message);
- }
-
- RefactoringStatus result= new RefactoringStatus();
-
- if (result.hasFatalError())
- return result;
-
- // no checking required for moving interface fields to classes
-
- if (! ((JdtFlags.isStatic(fDestinationType)) || (fDestinationType.getDeclaringType() == null))){
- String message= RefactoringCoreMessages.MoveMembersRefactoring_static_declaration;
- result.addError(message);
- }
-
- return result;
- }
-
- private RefactoringStatus checkDestinationInsideTypeToMove() throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < fMembersToMove.length; i++) {
- if (! (fMembersToMove[i] instanceof IType))
- continue;
- IType type= (IType) fMembersToMove[i];
- if (fDestinationType.equals(type) || JavaElementUtil.isAncestorOf(type, fDestinationType)) {
- String message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_inside,
- new String[] {JavaModelUtil.getFullyQualifiedName(type),
- JavaModelUtil.getFullyQualifiedName(fDestinationType)});
- RefactoringStatusContext context= JavaStatusContext.create(fDestinationType.getJavaScriptUnit(), fDestinationType.getNameRange());
- result.addFatalError(message, context);
- return result;
- }
- }
- return result;
- }
-
- private RefactoringStatus checkFieldsForInterface() throws JavaScriptModelException {
- //could be more clever and make field final if it is only written once...
- RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < fMembersToMove.length; i++) {
- if (! canMoveToInterface(fMembersToMove[i])) {
- String message= RefactoringCoreMessages.MoveMembersRefactoring_only_public_static;
- result.addError(message, JavaStatusContext.create(fMembersToMove[i]));
- }
- }
- return result;
- }
-
- private boolean canMoveToInterface(IMember member) throws JavaScriptModelException {
- int flags= member.getFlags();
- switch (member.getElementType()) {
- case IJavaScriptElement.FIELD:
- VariableDeclarationFragment declaration= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, fSource.getRoot());
- if (declaration != null)
- return declaration.getInitializer() != null;
-
- case IJavaScriptElement.TYPE: {
- return (Flags.isPublic(flags) && Flags.isStatic(flags));
- }
- default:
- return false;
- }
- }
-
- private RefactoringStatus checkMovedMemberAvailability(IMember memberToMove, IProgressMonitor pm) throws JavaScriptModelException{
- RefactoringStatus result= new RefactoringStatus();
- if (memberToMove instanceof IType) { // recursively check accessibility of member type's members
- IJavaScriptElement[] typeMembers= ((IType) memberToMove).getChildren();
- pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, typeMembers.length + 1);
- for (int i= 0; i < typeMembers.length; i++) {
- if (typeMembers[i] instanceof IInitializer)
- pm.worked(1);
- else
- result.merge(checkMovedMemberAvailability((IMember) typeMembers[i], new SubProgressMonitor(pm, 1)));
- }
- } else {
- pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
- }
-
- IType[] blindAccessorTypes= getTypesNotSeeingMovedMember(memberToMove, new SubProgressMonitor(pm, 1), result);
- for (int k= 0; k < blindAccessorTypes.length; k++) {
- String message= createNonAccessibleMemberMessage(memberToMove, blindAccessorTypes[k],/*moved*/true);
- result.addError(message, JavaStatusContext.create(memberToMove));
- }
- pm.done();
- return result;
- }
-
- private IType[] getTypesNotSeeingMovedMember(IMember member, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- if (JdtFlags.isPublic(member) && JdtFlags.isPublic(fDestinationType))
- return new IType[0];
-
- HashSet blindAccessorTypes= new HashSet(); // referencing, but access to destination type illegal
- SearchResultGroup[] references= getReferences(member, new SubProgressMonitor(pm, 1), status);
- for (int i = 0; i < references.length; i++) {
- SearchMatch[] searchResults= references[i].getSearchResults();
- for (int k= 0; k < searchResults.length; k++) {
- SearchMatch searchResult= searchResults[k];
- IJavaScriptElement element= SearchUtils.getEnclosingJavaElement(searchResult);
- IType type= (IType) element.getAncestor(IJavaScriptElement.TYPE);
- if (type != null //reference can e.g. be an import declaration
- && ! blindAccessorTypes.contains(type)
- && ! isWithinMemberToMove(searchResult)
- && ! isVisibleFrom(member, getDestinationType(), type)) {
- blindAccessorTypes.add(type);
- }
- }
- }
-
- if (fDelegateUpdating && isDelegateCreationAvailable(member)) {
- // ensure moved member is visible from the delegate
- IType type= member.getDeclaringType();
- if (!blindAccessorTypes.contains(type) && !isVisibleFrom(member, getDestinationType(), type))
- blindAccessorTypes.add(type);
- }
-
- return (IType[]) blindAccessorTypes.toArray(new IType[blindAccessorTypes.size()]);
- }
-
- private String createNonAccessibleMemberMessage(IMember member, IType accessingType, boolean moved){
- //Non-visibility can have various reasons and always displaying all visibility
- //flags for all enclosing elements would be too heavy. Context reveals exact cause.
- IType declaringType= moved ? getDestinationType() : getDeclaringType();
- String message;
- switch (member.getElementType()){
- case IJavaScriptElement.FIELD: {
- if (moved)
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_moved_field,
- new String[]{JavaElementUtil.createFieldSignature((IField)member),
- JavaModelUtil.getFullyQualifiedName(accessingType),
- JavaModelUtil.getFullyQualifiedName(declaringType)});
- else
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_accessed_field,
- new String[]{JavaElementUtil.createFieldSignature((IField)member),
- JavaModelUtil.getFullyQualifiedName(accessingType)});
- return message;
- }
- case IJavaScriptElement.METHOD: {
- if (moved)
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_moved_method,
- new String[]{JavaElementUtil.createMethodSignature((IFunction)member),
- JavaModelUtil.getFullyQualifiedName(accessingType),
- JavaModelUtil.getFullyQualifiedName(declaringType)});
- else
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_accessed_method,
- new String[]{JavaElementUtil.createMethodSignature((IFunction)member),
- JavaModelUtil.getFullyQualifiedName(accessingType)});
-
- return message;
- }
- case IJavaScriptElement.TYPE:{
- if (moved)
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_moved_type,
- new String[]{JavaModelUtil.getFullyQualifiedName(((IType)member)),
- JavaModelUtil.getFullyQualifiedName(accessingType),
- JavaModelUtil.getFullyQualifiedName(declaringType)});
- else
- message= Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_accessed_type,
- new String[]{JavaModelUtil.getFullyQualifiedName(((IType)member)),
- JavaModelUtil.getFullyQualifiedName(accessingType)});
- return message;
- }
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private static SearchResultGroup[] getReferences(IMember member, IProgressMonitor monitor, RefactoringStatus status) throws JavaScriptModelException {
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(member));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(monitor, 1));
- return (SearchResultGroup[]) engine.getResults();
- }
-
- private static boolean isVisibleFrom(IMember member, IType newMemberDeclaringType, IType accessingType) throws JavaScriptModelException{
- int memberVisibility= JdtFlags.getVisibilityCode(newMemberDeclaringType);
-
- IType declaringType= newMemberDeclaringType.getDeclaringType();
- while (declaringType != null) { //get lowest visibility in all parent types of newMemberDeclaringType
- memberVisibility= JdtFlags.getLowerVisibility(
- memberVisibility, JdtFlags.getVisibilityCode(declaringType));
- declaringType= declaringType.getDeclaringType();
- }
-
- switch (memberVisibility) {
- case Modifier.PRIVATE :
- return isEqualOrEnclosedType(accessingType, newMemberDeclaringType);
-
- case Modifier.NONE :
- return JavaModelUtil.isSamePackage(accessingType.getPackageFragment(), newMemberDeclaringType.getPackageFragment());
-
- case Modifier.PROTECTED :
- return JavaModelUtil.isSamePackage(accessingType.getPackageFragment(), newMemberDeclaringType.getPackageFragment())
- || accessingType.newSupertypeHierarchy(null).contains(newMemberDeclaringType);
-
- case Modifier.PUBLIC :
- return true;
-
- default:
- Assert.isTrue(false);
- return false;
- }
- }
-
- private static boolean isEqualOrEnclosedType(IType inner, IType outer) {
- while (inner != null) {
- if (inner.equals(outer))
- return true;
- else
- inner= inner.getDeclaringType();
- }
- return false;
- }
-
- private boolean isWithinMemberToMove(SearchMatch result) throws JavaScriptModelException {
- IJavaScriptUnit referenceCU= SearchUtils.getCompilationUnit(result);
- if (! referenceCU.equals(fSource.getCu()))
- return false;
- int referenceStart= result.getOffset();
- for (int i= 0; i < fMembersToMove.length; i++) {
- ISourceRange range= fMembersToMove[i].getSourceRange();
- if (range.getOffset() <= referenceStart && range.getOffset() + range.getLength() >= referenceStart)
- return true;
- }
- return false;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.done();
- return fChange;
- }
-
- private void createChange(List modifiedCus, RefactoringStatus status, IProgressMonitor monitor) throws CoreException {
- monitor.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_creating, 5);
- final IMember[] members= getMembersToMove();
- String project= null;
- final IJavaScriptProject javaProject= getDeclaringType().getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- String header= null;
- if (members.length == 1)
- header= Messages.format(RefactoringCoreMessages.MoveStaticMembersProcessor_descriptor_description_single, new String[] { JavaScriptElementLabels.getElementLabel(members[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- else
- header= Messages.format(RefactoringCoreMessages.MoveStaticMembersProcessor_descriptor_description_multi, new String[] { String.valueOf(members.length), JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- final IType declaring= members[0].getDeclaringType();
- try {
- if (declaring.isLocal() || declaring.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= members.length == 1 ? Messages.format(RefactoringCoreMessages.MoveStaticMembersProcessor_description_descriptor_short_multi, members[0].getElementName()) : RefactoringCoreMessages.MoveMembersRefactoring_move_members;
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveStaticMembersProcessor_target_element_pattern, JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- final MoveStaticMembersDescriptor descriptor= new MoveStaticMembersDescriptor();
- descriptor.setProject(project);
- descriptor.setDescription(description);
- descriptor.setComment(comment.asString());
- descriptor.setFlags(flags);
- descriptor.setDestinationType(fDestinationType);
- descriptor.setKeepOriginal(fDelegateUpdating);
- descriptor.setDeprecateDelegate(fDelegateDeprecation);
- descriptor.setMembers(members);
- fChange= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.MoveMembersRefactoring_move_members);
- fTarget= getCuRewrite(fDestinationType.getJavaScriptUnit());
- ITypeBinding targetBinding= getDestinationBinding();
- if (targetBinding == null) {
- status.addFatalError(Messages.format(RefactoringCoreMessages.MoveMembersRefactoring_compile_errors, fTarget.getCu().getElementName()));
- monitor.done();
- return;
- }
-
- try {
- Map adjustments= new HashMap();
- IMember member= null;
- SubProgressMonitor sub= new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- sub.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_creating, fMembersToMove.length);
- Set rewritten= new HashSet();
- for (int index= 0; index < fMembersToMove.length; index++) {
- member= fMembersToMove[index];
- final MemberVisibilityAdjustor adjustor= new MemberVisibilityAdjustor(fDestinationType, member);
- adjustor.setAdjustments(adjustments);
- adjustor.setStatus(status);
- adjustor.setVisibilitySeverity(RefactoringStatus.WARNING);
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
- adjustor.setRewrite(fSource.getASTRewrite(), fSource.getRoot());
- adjustor.adjustVisibility(new NullProgressMonitor());
-
- if (fDelegateUpdating && isDelegateCreationAvailable(member)) {
- // Add a visibility adjustment so the moved member
- // will be visible from within the delegate
- ModifierKeyword threshold= adjustor.getVisibilityThreshold(member, fDestinationType, new NullProgressMonitor());
- IncomingMemberVisibilityAdjustment adjustment= (IncomingMemberVisibilityAdjustment) adjustments.get(member);
- ModifierKeyword kw= (adjustment != null) ? adjustment.getKeyword() : ModifierKeyword.fromFlagValue(JdtFlags.getVisibilityCode(member));
- if (MemberVisibilityAdjustor.hasLowerVisibility(kw, threshold)) {
- adjustments.put(member, new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(member, threshold, RefactoringStatus.createWarningStatus(Messages.format(MemberVisibilityAdjustor.getMessage(member), new String[] { MemberVisibilityAdjustor.getLabel(member), MemberVisibilityAdjustor.getLabel(threshold)}), JavaStatusContext.create(member))));
- }
- }
-
- // Check if destination type is visible from references ->
- // error message if not (for example, when moving into a private type)
- status.merge(checkMovedMemberAvailability(member, new SubProgressMonitor(sub, 1)));
- // Put rewrite info into code and into status
- for (final Iterator iterator= rewritten.iterator(); iterator.hasNext();) {
- adjustments.remove(iterator.next());
- }
- rewritten.addAll(adjustments.keySet());
- adjustor.rewriteVisibility(new NullProgressMonitor());
- }
-
- // First update references in moved members, in order to extract the
- // source.
- String[] memberSources= getUpdatedMemberSource(status, fMemberDeclarations, targetBinding);
- monitor.worked(1);
- if (status.hasFatalError())
- return;
-
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2();
- engine.setPattern(fMembersToMove, IJavaScriptSearchConstants.ALL_OCCURRENCES);
- engine.setGranularity(RefactoringSearchEngine2.GRANULARITY_COMPILATION_UNIT);
- engine.setFiltering(true, true);
- engine.setScope(RefactoringScopeFactory.create(fMembersToMove));
- engine.setStatus(status);
- engine.searchPattern(new NullProgressMonitor());
- IJavaScriptUnit[] units= engine.getAffectedCompilationUnits();
- modifiedCus.addAll(Arrays.asList(units));
- final MemberVisibilityAdjustor adjustor= new MemberVisibilityAdjustor(fDestinationType, fDestinationType);
- sub= new SubProgressMonitor(monitor, 1);
- sub.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_creating, units.length);
- for (int index= 0; index < units.length; index++) {
- IJavaScriptUnit unit= units[index];
- CompilationUnitRewrite rewrite= getCuRewrite(unit);
- adjustor.setRewrites(Collections.singletonMap(unit, rewrite));
- adjustor.setAdjustments(adjustments);
- adjustor.rewriteVisibility(unit, new SubProgressMonitor(sub, 1));
- ReferenceAnalyzer analyzer= new ReferenceAnalyzer(rewrite, fMemberBindings, targetBinding, fSourceBinding);
- rewrite.getRoot().accept(analyzer);
- status.merge(analyzer.getStatus());
- if (status.hasFatalError()) {
- fChange= null;
- return;
- }
- if (!(fSource.getCu().equals(unit) || fTarget.getCu().equals(unit)))
- fChange.add(rewrite.createChange());
- }
- status.merge(moveMembers(fMemberDeclarations, memberSources));
- fChange.add(fSource.createChange());
- modifiedCus.add(fSource.getCu());
- if (!fSource.getCu().equals(fTarget.getCu())) {
- fChange.add(fTarget.createChange());
- modifiedCus.add(fTarget.getCu());
- }
- monitor.worked(1);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
- private CompilationUnitRewrite getCuRewrite(IJavaScriptUnit unit) {
- if (fSource.getCu().equals(unit))
- return fSource;
- if (fTarget != null && fTarget.getCu().equals(unit))
- return fTarget;
- return new CompilationUnitRewrite(unit);
- }
-
- private ITypeBinding getDestinationBinding() throws JavaScriptModelException {
- ASTNode node= NodeFinder.perform(fTarget.getRoot(), fDestinationType.getNameRange());
- if (!(node instanceof SimpleName))
- return null;
- IBinding binding= ((SimpleName)node).resolveBinding();
- if (!(binding instanceof ITypeBinding))
- return null;
- return (ITypeBinding)binding;
- }
-
- private IBinding[] getMemberBindings() throws JavaScriptModelException {
- IBinding[] result= new IBinding[fMembersToMove.length];
- for (int i= 0; i < fMembersToMove.length; i++) {
- IMember member= fMembersToMove[i];
- SimpleName name= (SimpleName)NodeFinder.perform(fSource.getRoot(), member.getNameRange());
- result[i]= name.resolveBinding();
- }
- return result;
- }
-
- private String[] getUpdatedMemberSource(RefactoringStatus status, BodyDeclaration[] members, ITypeBinding target) throws CoreException, BadLocationException {
- List typeRefs= new ArrayList();
- boolean targetNeedsSourceImport= false;
- boolean isSourceNotTarget= fSource != fTarget;
- Set exclude= new HashSet();
- for (int i= 0; i < members.length; i++) {
- BodyDeclaration declaration= members[i];
- if (declaration instanceof AbstractTypeDeclaration) {
- AbstractTypeDeclaration type= (AbstractTypeDeclaration) declaration;
- ITypeBinding binding= type.resolveBinding();
- if (binding != null)
- exclude.add(binding);
- } else if (declaration instanceof FunctionDeclaration) {
- FunctionDeclaration method= (FunctionDeclaration) declaration;
- IFunctionBinding binding= method.resolveBinding();
- if (binding != null)
- exclude.add(binding);
- } else if (declaration instanceof FieldDeclaration) {
- FieldDeclaration field= (FieldDeclaration) declaration;
- for (final Iterator iterator= field.fragments().iterator(); iterator.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) iterator.next();
- IVariableBinding binding= fragment.resolveBinding();
- if (binding != null)
- exclude.add(binding);
- }
- }
- }
- for (int i= 0; i < members.length; i++) {
- BodyDeclaration declaration= members[i];
- if (isSourceNotTarget)
- typeRefs.addAll(TypeReferenceFinder.perform(declaration));
- MovedMemberAnalyzer analyzer= new MovedMemberAnalyzer(fSource, fMemberBindings, fSourceBinding, target);
- declaration.accept(analyzer);
- ImportRewriteUtil.addImports(fTarget, declaration, new HashMap(), new HashMap(), exclude, false);
-
- ITrackedNodePosition trackedPosition= fSource.getASTRewrite().track(declaration);
- declaration.setProperty(TRACKED_POSITION_PROPERTY, trackedPosition);
- targetNeedsSourceImport|= analyzer.targetNeedsSourceImport();
- status.merge(analyzer.getStatus());
- }
- // Adjust imports
- if (targetNeedsSourceImport && isSourceNotTarget) {
- fTarget.getImportRewrite().addImport(fSourceBinding);
- }
- if (isSourceNotTarget) {
- for (Iterator iter= typeRefs.iterator(); iter.hasNext();) {
- ITypeBinding binding= (ITypeBinding) iter.next();
- fTarget.getImportRewrite().addImport(binding);
- }
- }
- // extract updated members
- String[] updatedMemberSources= new String[members.length];
- IDocument document= new Document(fSource.getCu().getBuffer().getContents());
- TextEdit edit= fSource.getASTRewrite().rewriteAST(document, fSource.getCu().getJavaScriptProject().getOptions(true));
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- for (int i= 0; i < members.length; i++) {
- updatedMemberSources[i]= getUpdatedMember(document, members[i]);
- }
- fSource.clearASTRewrite();
- return updatedMemberSources;
- }
-
- private String getUpdatedMember(IDocument document, BodyDeclaration declaration) throws BadLocationException {
- ITrackedNodePosition trackedPosition= (ITrackedNodePosition) declaration.getProperty(TRACKED_POSITION_PROPERTY);
- return Strings.trimIndentation(document.get(trackedPosition.getStartPosition(), trackedPosition.getLength()), fPreferences.tabWidth, fPreferences.indentWidth, false);
- }
-
- private RefactoringStatus moveMembers(BodyDeclaration[] members, String[] sources) throws CoreException {
- RefactoringStatus result= new RefactoringStatus();
- AbstractTypeDeclaration destination= (AbstractTypeDeclaration)
- ASTNodes.getParent(
- NodeFinder.perform(fTarget.getRoot(), fDestinationType.getNameRange()),
- AbstractTypeDeclaration.class);
- ListRewrite containerRewrite= fTarget.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty());
-
- TextEditGroup delete= fSource.createGroupDescription(RefactoringCoreMessages.MoveMembersRefactoring_deleteMembers);
- TextEditGroup add= fTarget.createGroupDescription(RefactoringCoreMessages.MoveMembersRefactoring_addMembers);
- for (int i= 0; i < members.length; i++) {
- BodyDeclaration declaration= members[i];
- ASTNode removeImportsOf= null;
- boolean addedDelegate= false;
-
- if (fDelegateUpdating) {
- if (declaration instanceof FunctionDeclaration) {
-
- DelegateMethodCreator creator= new DelegateMethodCreator();
- creator.setDeclaration(declaration);
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setSourceRewrite(fSource);
- creator.setCopy(false);
- creator.setNewLocation(getDestinationBinding());
- creator.prepareDelegate();
- creator.createEdit();
-
- removeImportsOf= ((FunctionDeclaration) declaration).getBody();
- addedDelegate= true;
- }
- if (declaration instanceof FieldDeclaration) {
-
- // Note: this FieldDeclaration only has one fragment (@see #getASTMembers(RefactoringStatus))
- final VariableDeclarationFragment frag= (VariableDeclarationFragment) ((FieldDeclaration) declaration).fragments().get(0);
-
- if (!Modifier.isFinal(declaration.getModifiers())) {
- // Don't create a delegate for non-final fields
- result.addInfo(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_not_final, frag.getName()), null);
- } else if (frag.getInitializer() == null) {
- // Don't create a delegate without an initializer.
- result.addInfo(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, frag.getName()), null);
- } else {
- DelegateFieldCreator creator= new DelegateFieldCreator();
- creator.setDeclaration(declaration);
- creator.setDeclareDeprecated(fDelegateDeprecation);
- creator.setSourceRewrite(fSource);
- creator.setCopy(false);
- creator.setNewLocation(getDestinationBinding());
- creator.prepareDelegate();
- creator.createEdit();
-
- removeImportsOf= frag.getInitializer();
- addedDelegate= true;
- }
- }
- if (declaration instanceof AbstractTypeDeclaration) {
- result.addInfo(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_delegate_for_type, ((AbstractTypeDeclaration) declaration).getName().getIdentifier()),
- null);
- }
- }
-
- if (!addedDelegate) {
- fSource.getASTRewrite().remove(declaration, delete);
- removeImportsOf= declaration;
- }
-
- if (removeImportsOf != null && fSource != fTarget)
- fSource.getImportRemover().registerRemovedNode(removeImportsOf);
-
- ASTNode node= fTarget.getASTRewrite().createStringPlaceholder(sources[i], declaration.getNodeType());
- List container= containerRewrite.getRewrittenList();
- int insertionIndex= ASTNodes.getInsertionIndex((BodyDeclaration) node, container);
- containerRewrite.insertAt(node, insertionIndex, add);
- }
- return result;
- }
-
- private BodyDeclaration[] getASTMembers(RefactoringStatus status) throws JavaScriptModelException {
- BodyDeclaration[] result= new BodyDeclaration[fMembersToMove.length];
- for (int i= 0; i < fMembersToMove.length; i++) {
- IMember member= fMembersToMove[i];
- ASTNode node= NodeFinder.perform(fSource.getRoot(), member.getNameRange());
- result[i]= (BodyDeclaration)ASTNodes.getParent(node, BodyDeclaration.class);
-
- //Fix for bug 42383: exclude multiple VariableDeclarationFragments ("int a=1, b=2")
- //ReferenceAnalyzer#visit(FieldDeclaration node) depends on fragments().size() != 1 !
- if (result[i] instanceof FieldDeclaration
- && ((FieldDeclaration) result[i]).fragments().size() != 1) {
- status.addFatalError(RefactoringCoreMessages.MoveMembersRefactoring_multi_var_fields);
- return result;
- }
-
- }
-
- //Sorting members is important for field declarations referring to previous fields.
- Arrays.sort(result, new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((BodyDeclaration) o1).getStartPosition()
- - ((BodyDeclaration) o2).getStartPosition();
- }
- });
- return result;
- }
-
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.MOVE_STATIC_MEMBERS);
- else {
- fDestinationType= (IType) element;
- fDestinationTypeName= fDestinationType.getFullyQualifiedName();
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String delegate= extended.getAttribute(ATTRIBUTE_DELEGATE);
- if (delegate != null) {
- fDelegateUpdating= Boolean.valueOf(delegate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELEGATE));
- final String deprecate= extended.getAttribute(ATTRIBUTE_DEPRECATE);
- if (deprecate != null) {
- fDelegateDeprecation= Boolean.valueOf(deprecate).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE));
- int count= 1;
- final List elements= new ArrayList();
- String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- final RefactoringStatus status= new RefactoringStatus();
- while ((handle= extended.getAttribute(attribute)) != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.MOVE_STATIC_MEMBERS));
- else
- elements.add(element);
- count++;
- attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- }
- fMembersToMove= (IMember[]) elements.toArray(new IMember[elements.size()]);
- if (elements.isEmpty())
- return ScriptableRefactoring.createInputFatalStatus(null, getRefactoring().getName(), IJavaScriptRefactorings.MOVE_STATIC_MEMBERS);
- IJavaScriptProject project= null;
- if (fMembersToMove.length > 0)
- project= fMembersToMove[0].getJavaScriptProject();
- fPreferences= JavaPreferencesSettings.getCodeGenerationSettings(project);
- if (!status.isOK())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- public boolean canEnableComment() {
- return true;
- }
-
- public String getComment() {
- return fComment;
- }
-
- public void setComment(String comment) {
- fComment= comment;
- }
-
- public String getDelegateUpdatingTitle(boolean plural) {
- if (plural)
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_moved_plural;
- else
- return RefactoringCoreMessages.DelegateMethodCreator_keep_original_moved_singular;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MovedMemberAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MovedMemberAnalyzer.java
deleted file mode 100644
index ab767ec4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/MovedMemberAnalyzer.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-/**
- * Updates references in moved static members.
- * Accepts <code>BodyDeclaration</code>s.
- */
-/* package */ class MovedMemberAnalyzer extends MoveStaticMemberAnalyzer {
-/*
- * cases:
- * - access to moved member (or to member of moved member) -> do nothing.
- * - (static) access to source -> change to source, import source.
- * - (static) access to target -> change to target.
- * - access to other type -> do nothing (import is done in MoveStaticMembersRefactoring#getUpdatedMemberSource())
- */
-// TW: Adapted references to type
-// - Reference to type inside moved type:
-// - if originally resolved by qualification -> no problem
-// - if originally resolved by import -> must add import in target too (qualify if import ambiguous)
-
- public MovedMemberAnalyzer(CompilationUnitRewrite cuRewrite,
- IBinding[] members, ITypeBinding source, ITypeBinding target) {
- super(cuRewrite, members, source, target);
- }
-
- public boolean targetNeedsSourceImport() {
- return fNeedsImport;
- }
-
- //---- types and fields --------------------------
-
- public boolean visit(SimpleName node) {
- if (node.isDeclaration() || isProcessed(node))
- return super.visit(node);
- IBinding binding= node.resolveBinding();
- if (isMovedMember(binding))
- return super.visit(node);
-
- if (isSourceAccess(binding))
- rewrite(node, fSource);
- return super.visit(node);
- }
-
- public boolean visit(QualifiedName node) {
- IBinding binding= node.resolveBinding();
- if (isSourceAccess(binding)) {
- if (isMovedMember(binding)) {
- rewrite(node, fTarget);
- return false;
- } else {
- rewrite(node, fSource);
- return false;
- }
- } else if (isTargetAccess(binding)) {
- // remove qualifier:
- SimpleName replace= (SimpleName)fCuRewrite.getASTRewrite().createCopyTarget(node.getName());
- fCuRewrite.getASTRewrite().replace(node, replace, null);
- fCuRewrite.getImportRemover().registerRemovedNode(node);
- return false;
- }
- return super.visit(node);
- }
-
- public boolean visit(FieldAccess node) {
- IBinding binding= node.resolveFieldBinding();
- if (isSourceAccess(binding)) {
- if (isMovedMember(binding)) {
- if (node.getExpression() != null)
- rewrite(node, fTarget);
- } else
- rewrite(node, fSource);
-
- } else if (isTargetAccess(binding)) {
- fCuRewrite.getASTRewrite().remove(node.getExpression(), null);
- fCuRewrite.getImportRemover().registerRemovedNode(node.getExpression());
- }
- return super.visit(node);
- }
-
- //---- method invocations ----------------------------------
-
- public boolean visit(FunctionInvocation node) {
- IBinding binding= node.resolveMethodBinding();
- if (isSourceAccess(binding)) {
- if (isMovedMember(binding)) {
- if (node.getExpression() != null)
- rewrite(node, fTarget);
- } else
- rewrite(node, fSource);
-
- } else if (isTargetAccess(binding)) {
- if (node.getExpression() != null) {
- fCuRewrite.getASTRewrite().remove(node.getExpression(), null);
- fCuRewrite.getImportRemover().registerRemovedNode(node.getExpression());
- }
- }
- return super.visit(node);
- }
-
- //---- javadoc references ----------------------------------
-
- public boolean visit(MemberRef node) {
- IBinding binding= node.resolveBinding();
- if (isSourceAccess(binding)) {
- if (isMovedMember(binding)) {
- if (node.getQualifier() != null)
- rewrite(node, fTarget);
- } else
- rewrite(node, fSource);
-
- } else if (isTargetAccess(binding)) {
- // remove qualifier:
- SimpleName replace= (SimpleName)fCuRewrite.getASTRewrite().createCopyTarget(node.getName());
- fCuRewrite.getASTRewrite().replace(node, replace, null);
- fCuRewrite.getImportRemover().registerRemovedNode(node);
- }
- return super.visit(node);
- }
-
- public boolean visit(FunctionRef node) {
- IBinding binding= node.resolveBinding();
- if (isSourceAccess(binding)) {
- if (isMovedMember(binding)) {
- if (node.getQualifier() != null)
- rewrite(node, fTarget);
- } else
- rewrite(node, fSource);
-
- } else if (isTargetAccess(binding)) {
- // remove qualifier:
- SimpleName replace= (SimpleName)fCuRewrite.getASTRewrite().createCopyTarget(node.getName());
- fCuRewrite.getASTRewrite().replace(node, replace, null);
- fCuRewrite.getImportRemover().registerRemovedNode(node);
- }
- return super.visit(node);
- }
-
- //---- helper methods --------------------------------------
-
- private boolean isSourceAccess(IBinding binding) {
- if (binding instanceof IFunctionBinding) {
- IFunctionBinding method= (IFunctionBinding)binding;
- return Modifier.isStatic(method.getModifiers()) && Bindings.equals(fSource, method.getDeclaringClass());
- } else if (binding instanceof ITypeBinding) {
- ITypeBinding type= (ITypeBinding)binding;
- return Modifier.isStatic(type.getModifiers()) && Bindings.equals(fSource, type.getDeclaringClass());
- } else if (binding instanceof IVariableBinding) {
- IVariableBinding field= (IVariableBinding)binding;
- return field.isField() && Modifier.isStatic(field.getModifiers()) && Bindings.equals(fSource, field.getDeclaringClass());
- }
- return false;
- }
-
- private boolean isTargetAccess(IBinding binding) {
- if (binding instanceof IFunctionBinding) {
- IFunctionBinding method= (IFunctionBinding)binding;
- return Modifier.isStatic(method.getModifiers()) && Bindings.equals(fTarget, method.getDeclaringClass());
- } else if (binding instanceof ITypeBinding) {
- ITypeBinding type= (ITypeBinding)binding;
- return Modifier.isStatic(type.getModifiers()) && Bindings.equals(fTarget, type.getDeclaringClass());
- } else if (binding instanceof IVariableBinding) {
- IVariableBinding field= (IVariableBinding)binding;
- return field.isField() && Modifier.isStatic(field.getModifiers()) && Bindings.equals(fTarget, field.getDeclaringClass());
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoring.java
deleted file mode 100644
index cca7729b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoring.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Refactoring to pull up members in a type hierarchy.
- */
-public class PullUpRefactoring extends ProcessorBasedRefactoring implements IScriptableRefactoring {
-
- /** The refactoring processor to use */
- private final HierarchyProcessor fProcessor;
-
- /**
- * Creates a new pull up refactoring.
- *
- * @param processor
- * the pull up refactoring processor to use
- */
- public PullUpRefactoring(final HierarchyProcessor processor) {
- super(processor);
- fProcessor= processor;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringProcessor getProcessor() {
- return fProcessor;
- }
-
- /**
- * Returns the pull up processor.
- *
- * @return the pull up processor
- */
- public PullUpRefactoringProcessor getPullUpProcessor() {
- return (PullUpRefactoringProcessor) getProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java
deleted file mode 100644
index 91b96d78..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java
+++ /dev/null
@@ -1,1862 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsSolver;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ISourceConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring processor for the pull up refactoring.
- *
- *
- */
-public class PullUpRefactoringProcessor extends HierarchyProcessor {
-
- /**
- * AST node visitor which performs the actual mapping.
- */
- private static class PullUpAstNodeMapper extends TypeVariableMapper {
-
- /** Are we in an anonymous class declaration? */
- private boolean fAnonymousClassDeclaration= false;
-
- /** The source compilation unit rewrite to use */
- private final CompilationUnitRewrite fSourceRewriter;
-
- /** The super reference type */
- private final IType fSuperReferenceType;
-
- /** The target compilation unit rewrite to use */
- private final CompilationUnitRewrite fTargetRewriter;
-
- /** Are we in a type declaration statement? */
- private boolean fTypeDeclarationStatement= false;
-
- /** The binding of the enclosing method */
- private final IFunctionBinding fEnclosingMethod;
-
- /**
- * Creates a new pull up ast node mapper.
- *
- * @param sourceRewriter
- * the source compilation unit rewrite to use
- * @param targetRewriter
- * the target compilation unit rewrite to use
- * @param rewrite
- * the AST rewrite to use
- * @param type
- * the super reference type
- * @param mapping
- * the type variable mapping
- * @param enclosing the binding of the enclosing method
- */
- public PullUpAstNodeMapper(final CompilationUnitRewrite sourceRewriter, final CompilationUnitRewrite targetRewriter, final ASTRewrite rewrite, final IType type, final TypeVariableMaplet[] mapping, final IFunctionBinding enclosing) {
- super(rewrite, mapping);
- Assert.isNotNull(rewrite);
- Assert.isNotNull(type);
- fSourceRewriter= sourceRewriter;
- fTargetRewriter= targetRewriter;
- fSuperReferenceType= type;
- fEnclosingMethod= enclosing;
- }
-
- public final void endVisit(final AnonymousClassDeclaration node) {
- fAnonymousClassDeclaration= false;
- super.endVisit(node);
- }
-
- public final void endVisit(final TypeDeclarationStatement node) {
- fTypeDeclarationStatement= false;
- super.endVisit(node);
- }
-
- public final boolean visit(final AnonymousClassDeclaration node) {
- fAnonymousClassDeclaration= true;
- return super.visit(node);
- }
-
- public final boolean visit(final SuperFieldAccess node) {
- if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
- final AST ast= node.getAST();
- final FieldAccess access= ast.newFieldAccess();
- access.setExpression(ast.newThisExpression());
- access.setName(ast.newSimpleName(node.getName().getIdentifier()));
- fRewrite.replace(node, access, null);
- if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
- fSourceRewriter.getImportRemover().registerRemovedNode(node);
- return true;
- }
- return false;
- }
-
- public final boolean visit(final SuperMethodInvocation node) {
- if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
- final IBinding superBinding= node.getName().resolveBinding();
- if (superBinding instanceof IFunctionBinding) {
- final IFunctionBinding extended= (IFunctionBinding) superBinding;
- if (fEnclosingMethod != null && fEnclosingMethod.overrides(extended))
- return true;
- final ITypeBinding declaringBinding= extended.getDeclaringClass();
- if (declaringBinding != null) {
- final IType type= (IType) declaringBinding.getJavaElement();
- if (!fSuperReferenceType.equals(type))
- return true;
- }
- }
- final AST ast= node.getAST();
- final ThisExpression expression= ast.newThisExpression();
- final FunctionInvocation invocation= ast.newFunctionInvocation();
- final SimpleName simple= ast.newSimpleName(node.getName().getIdentifier());
- invocation.setName(simple);
- invocation.setExpression(expression);
- final List arguments= (List) node.getStructuralProperty(SuperMethodInvocation.ARGUMENTS_PROPERTY);
- if (arguments != null && arguments.size() > 0) {
- final ListRewrite rewriter= fRewrite.getListRewrite(invocation, FunctionInvocation.ARGUMENTS_PROPERTY);
- rewriter.insertLast(rewriter.createCopyTarget((ASTNode) arguments.get(0), (ASTNode) arguments.get(arguments.size() - 1)), null);
- }
- fRewrite.replace(node, invocation, null);
- if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
- fSourceRewriter.getImportRemover().registerRemovedNode(node);
- return true;
- }
- return false;
- }
-
- public final boolean visit(final TypeDeclarationStatement node) {
- fTypeDeclarationStatement= true;
- return super.visit(node);
- }
- }
-
- protected static final String ATTRIBUTE_ABSTRACT= "abstract"; //$NON-NLS-1$
-
- protected static final String ATTRIBUTE_DELETE= "delete"; //$NON-NLS-1$
-
- protected static final String ATTRIBUTE_PULL= "pull"; //$NON-NLS-1$
-
- protected static final String ATTRIBUTE_STUBS= "stubs"; //$NON-NLS-1$
-
- private static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.pullUpProcessor"; //$NON-NLS-1$
-
- /** The pull up group category set */
- private static final GroupCategorySet SET_PULL_UP= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.pullUp", //$NON-NLS-1$
- RefactoringCoreMessages.PullUpRefactoring_category_name, RefactoringCoreMessages.PullUpRefactoring_category_description));
-
- private static void addMatchingMember(final Map mapping, final IMember key, final IMember matchingMember) {
- Set matchingSet;
- if (mapping.containsKey(key)) {
- matchingSet= (Set) mapping.get(key);
- } else {
- matchingSet= new HashSet();
- mapping.put(key, matchingSet);
- }
- Assert.isTrue(!matchingSet.contains(matchingMember));
- matchingSet.add(matchingMember);
- }
-
- private static Block createMethodStub(final FunctionDeclaration method, final AST ast) {
- final Block body= ast.newBlock();
- final Expression expression= ASTNodeFactory.newDefaultExpression(ast, method.getReturnType2(), method.getExtraDimensions());
- if (expression != null) {
- final ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- body.statements().add(returnStatement);
- }
- return body;
- }
-
- private static Set getEffectedSubTypes(final ITypeHierarchy hierarchy, final IType type) throws JavaScriptModelException {
- IType[] types= null;
- types= hierarchy.getSubclasses(type);
- final Set result= new HashSet();
- for (int index= 0; index < types.length; index++) {
- if (JdtFlags.isAbstract(types[index]))
- result.addAll(getEffectedSubTypes(hierarchy, types[index]));
- else
- result.add(types[index]);
- }
- return result;
- }
-
- private static IMember[] getMembers(final IMember[] members, final int type) {
- final List list= Arrays.asList(JavaElementUtil.getElementsOfType(members, type));
- return (IMember[]) list.toArray(new IMember[list.size()]);
- }
-
- private static void mergeMaps(final Map result, final Map map) {
- for (final Iterator iter= result.keySet().iterator(); iter.hasNext();) {
- final IMember key= (IMember) iter.next();
- if (map.containsKey(key)) {
- final Set resultSet= (Set) result.get(key);
- final Set mapSet= (Set) map.get(key);
- resultSet.addAll(mapSet);
- }
- }
- }
-
- private static void upgradeMap(final Map result, final Map map) {
- for (final Iterator iter= map.keySet().iterator(); iter.hasNext();) {
- final IMember key= (IMember) iter.next();
- if (!result.containsKey(key)) {
- final Set mapSet= (Set) map.get(key);
- final Set resultSet= new HashSet(mapSet);
- result.put(key, resultSet);
- }
- }
- }
-
- /** The methods to be declared abstract */
- protected IFunction[] fAbstractMethods= new IFunction[0];
-
- /** The cached supertype hierarchy of the declaring type */
- private ITypeHierarchy fCachedDeclaringSuperTypeHierarchy;
-
- /** The cached type hierarchy of the destination type */
- private ITypeHierarchy fCachedDestinationTypeHierarchy;
-
- /** The cached set of skipped supertypes */
- private Set fCachedSkippedSuperTypes;
-
- /** The map of compilation units to compilation unit rewrites */
- protected Map fCompilationUnitRewrites;
-
- /** Should method stubs be generated in subtypes? */
- protected boolean fCreateMethodStubs= true;
-
- /** The methods to be deleted in subtypes */
- protected IFunction[] fDeletedMethods= new IFunction[0];
-
- /** The destination type */
- protected IType fDestinationType;
-
- /**
- * Creates a new pull up refactoring processor.
- *
- * @param members
- * the members to pull up, or <code>null</code> if invoked by
- * scripting
- * @param settings
- * the code generation settings, or <code>null</code> if
- * invoked by scripting
- */
- public PullUpRefactoringProcessor(final IMember[] members, final CodeGenerationSettings settings) {
- this(members, settings, false);
- }
-
- /**
- * Creates a new pull up refactoring processor.
- *
- * @param members
- * the members to pull up, or <code>null</code> if invoked by
- * scripting
- * @param settings
- * the code generation settings, or <code>null</code> if
- * invoked by scripting
- * @param layer
- * <code>true</code> to create a working copy layer,
- * <code>false</code> otherwise
- */
- protected PullUpRefactoringProcessor(final IMember[] members, final CodeGenerationSettings settings, final boolean layer) {
- super(members, settings, layer);
- if (members != null) {
- final IType type= RefactoringAvailabilityTester.getTopLevelType(fMembersToMove);
- try {
- if (type != null && RefactoringAvailabilityTester.getPullUpMembers(type).length != 0) {
- fCachedDeclaringType= RefactoringAvailabilityTester.getTopLevelType(fMembersToMove);
- fMembersToMove= new IMember[0];
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
-
- private void addAllRequiredPullableMembers(final List queue, final IMember member, final IProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(queue);
- Assert.isNotNull(member);
- Assert.isNotNull(monitor);
- SubProgressMonitor sub= null;
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_calculating_required, 3);
- final IFunction[] requiredMethods= ReferenceFinderUtil.getMethodsReferencedIn(new IJavaScriptElement[] { member}, fOwner, new SubProgressMonitor(monitor, 1));
- sub= new SubProgressMonitor(monitor, 1);
- boolean isStatic= false;
- try {
- sub.beginTask(RefactoringCoreMessages.PullUpRefactoring_calculating_required, requiredMethods.length);
- isStatic= JdtFlags.isStatic(member);
- for (int index= 0; index < requiredMethods.length; index++) {
- final IFunction requiredMethod= requiredMethods[index];
- if (isStatic && !JdtFlags.isStatic(requiredMethod))
- continue;
- if (isRequiredPullableMember(queue, requiredMethod) && !(MethodChecks.isVirtual(requiredMethod) && isAvailableInDestination(requiredMethod, new SubProgressMonitor(sub, 1))))
- queue.add(requiredMethod);
- }
- } finally {
- sub.done();
- }
- final IField[] requiredFields= ReferenceFinderUtil.getFieldsReferencedIn(new IJavaScriptElement[] { member}, fOwner, new SubProgressMonitor(monitor, 1));
- sub= new SubProgressMonitor(monitor, 1);
- try {
- sub.beginTask(RefactoringCoreMessages.PullUpRefactoring_calculating_required, requiredFields.length);
- isStatic= JdtFlags.isStatic(member);
- for (int index= 0; index < requiredFields.length; index++) {
- final IField requiredField= requiredFields[index];
- if (isStatic && !JdtFlags.isStatic(requiredField))
- continue;
- if (isRequiredPullableMember(queue, requiredField))
- queue.add(requiredField);
- }
- } finally {
- sub.done();
- }
- final IType[] requiredTypes= ReferenceFinderUtil.getTypesReferencedIn(new IJavaScriptElement[] { member}, fOwner, new SubProgressMonitor(monitor, 1));
- sub= new SubProgressMonitor(monitor, 1);
- try {
- sub.beginTask(RefactoringCoreMessages.PullUpRefactoring_calculating_required, requiredMethods.length);
- isStatic= JdtFlags.isStatic(member);
- for (int index= 0; index < requiredTypes.length; index++) {
- final IType requiredType= requiredTypes[index];
- if (isStatic && !JdtFlags.isStatic(requiredType))
- continue;
- if (isRequiredPullableMember(queue, requiredType))
- queue.add(requiredType);
- }
- } finally {
- sub.done();
- }
- } finally {
- monitor.done();
- }
- }
-
- private void addMethodStubForAbstractMethod(final IFunction sourceMethod, final JavaScriptUnit declaringCuNode, final AbstractTypeDeclaration typeToCreateStubIn, final IJavaScriptUnit newCu, final CompilationUnitRewrite rewriter, final Map adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- final FunctionDeclaration methodToCreateStubFor= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
- final AST ast= rewriter.getRoot().getAST();
- final FunctionDeclaration newMethod= ast.newFunctionDeclaration();
- newMethod.setBody(createMethodStub(methodToCreateStubFor, ast));
- newMethod.setConstructor(false);
- newMethod.setExtraDimensions(methodToCreateStubFor.getExtraDimensions());
- newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status)));
- newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName())));
- copyReturnType(rewriter.getASTRewrite(), getDeclaringType().getJavaScriptUnit(), methodToCreateStubFor, newMethod, null);
- copyParameters(rewriter.getASTRewrite(), getDeclaringType().getJavaScriptUnit(), methodToCreateStubFor, newMethod, null);
- copyThrownExceptions(methodToCreateStubFor, newMethod);
- newMethod.setJavadoc(createJavadocForStub(typeToCreateStubIn.getName().getIdentifier(), methodToCreateStubFor, newMethod, newCu, rewriter.getASTRewrite()));
- ImportRewriteUtil.addImports(rewriter, newMethod, new HashMap(), new HashMap(), false);
- rewriter.getASTRewrite().getListRewrite(typeToCreateStubIn, typeToCreateStubIn.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, typeToCreateStubIn.bodyDeclarations()), rewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_method_stub, SET_PULL_UP));
- }
-
- private void addNecessaryMethodStubs(final List effected, final JavaScriptUnit root, final CompilationUnitRewrite unitRewriter, final Map adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- final IType declaringType= getDeclaringType();
- final IFunction[] methods= getAbstractMethods();
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, effected.size());
- for (final Iterator iter= effected.iterator(); iter.hasNext();) {
- final IType type= (IType) iter.next();
- if (type.equals(declaringType))
- continue;
- final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, unitRewriter.getRoot());
- final IJavaScriptUnit unit= type.getJavaScriptUnit();
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
- try {
- subMonitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, methods.length);
- for (int j= 0; j < methods.length; j++) {
- final IFunction method= methods[j];
- if (null == JavaModelUtil.findMethod(method.getElementName(), method.getParameterTypes(), method.isConstructor(), type)) {
- addMethodStubForAbstractMethod(method, root, declaration, unit, unitRewriter, adjustments, new SubProgressMonitor(subMonitor, 1), status);
- }
- }
- subMonitor.done();
- } finally {
- subMonitor.done();
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- protected boolean canBeAccessedFrom(final IMember member, final IType target, final ITypeHierarchy hierarchy) throws JavaScriptModelException {
- if (super.canBeAccessedFrom(member, target, hierarchy)) {
- if (target.equals(member.getDeclaringType()))
- return true;
- if (target.equals(member))
- return true;
- if (member instanceof IFunction) {
- final IFunction method= (IFunction) member;
- final IFunction stub= target.getFunction(method.getElementName(), method.getParameterTypes());
- if (stub.exists())
- return true;
- }
- if (member.getDeclaringType() == null) {
- if (!(member instanceof IType))
- return false;
- if (JdtFlags.isPublic(member))
- return true;
- if (!JdtFlags.isPackageVisible(member))
- return false;
- if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment()))
- return true;
- final IType type= member.getDeclaringType();
- if (type != null)
- return hierarchy.contains(type);
- return false;
- }
- final IType declaringType= member.getDeclaringType();
- if (!canBeAccessedFrom(declaringType, target, hierarchy))
- return false;
- if (declaringType.equals(getDeclaringType()))
- return false;
- return true;
- }
- return false;
- }
-
- private RefactoringStatus checkAccessedFields(final IProgressMonitor monitor, final ITypeHierarchy hierarchy) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2);
- final RefactoringStatus result= new RefactoringStatus();
-
- final List pulledUpList= Arrays.asList(fMembersToMove);
- final List deletedList= Arrays.asList(getMembersToDelete(new SubProgressMonitor(monitor, 1)));
- final IField[] accessedFields= ReferenceFinderUtil.getFieldsReferencedIn(fMembersToMove, fOwner, new SubProgressMonitor(monitor, 1));
-
- final IType destination= getDestinationType();
- for (int i= 0; i < accessedFields.length; i++) {
- final IField field= accessedFields[i];
- if (!field.exists())
- continue;
-
- boolean isAccessible= pulledUpList.contains(field) || deletedList.contains(field) || canBeAccessedFrom(field, destination, hierarchy);
- if (!isAccessible) {
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_field_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(field, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- result.addError(message, JavaStatusContext.create(field));
- } else if (getSkippedSuperTypes(new SubProgressMonitor(monitor, 1)).contains(field.getDeclaringType())) {
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_field_cannot_be_accessed, new String[] { JavaScriptElementLabels.getTextLabel(field, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- result.addError(message, JavaStatusContext.create(field));
- }
- }
- monitor.done();
- return result;
- }
-
- private RefactoringStatus checkAccessedMethods(final IProgressMonitor monitor, final ITypeHierarchy hierarchy) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2);
- final RefactoringStatus result= new RefactoringStatus();
-
- final List pulledUpList= Arrays.asList(fMembersToMove);
- final List declaredAbstractList= Arrays.asList(fAbstractMethods);
- final List deletedList= Arrays.asList(getMembersToDelete(new SubProgressMonitor(monitor, 1)));
- final IFunction[] accessedMethods= ReferenceFinderUtil.getMethodsReferencedIn(fMembersToMove, fOwner, new SubProgressMonitor(monitor, 1));
-
- final IType destination= getDestinationType();
- for (int index= 0; index < accessedMethods.length; index++) {
- final IFunction method= accessedMethods[index];
- if (!method.exists())
- continue;
- boolean isAccessible= pulledUpList.contains(method) || deletedList.contains(method) || declaredAbstractList.contains(method) || canBeAccessedFrom(method, destination, hierarchy);
- if (!isAccessible) {
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_method_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- result.addError(message, JavaStatusContext.create(method));
- } else if (getSkippedSuperTypes(new SubProgressMonitor(monitor, 1)).contains(method.getDeclaringType())) {
- final String[] keys= { JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_method_cannot_be_accessed, keys);
- result.addError(message, JavaStatusContext.create(method));
- }
- }
- monitor.done();
- return result;
- }
-
- private RefactoringStatus checkAccessedTypes(final IProgressMonitor monitor, final ITypeHierarchy hierarchy) throws JavaScriptModelException {
- final RefactoringStatus result= new RefactoringStatus();
- final IType[] accessedTypes= getTypesReferencedInMovedMembers(monitor);
- final IType destination= getDestinationType();
- final List pulledUpList= Arrays.asList(fMembersToMove);
- for (int index= 0; index < accessedTypes.length; index++) {
- final IType type= accessedTypes[index];
- if (!type.exists())
- continue;
-
- if (!canBeAccessedFrom(type, destination, hierarchy) && !pulledUpList.contains(type)) {
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_type_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(destination, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- result.addError(message, JavaStatusContext.create(type));
- }
- }
- monitor.done();
- return result;
- }
-
- private RefactoringStatus checkAccesses(final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringStatus result= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 4);
- final ITypeHierarchy hierarchy= getDestinationType().newSupertypeHierarchy(fOwner, new SubProgressMonitor(monitor, 1));
- result.merge(checkAccessedTypes(new SubProgressMonitor(monitor, 1), hierarchy));
- result.merge(checkAccessedFields(new SubProgressMonitor(monitor, 1), hierarchy));
- result.merge(checkAccessedMethods(new SubProgressMonitor(monitor, 1), hierarchy));
- } finally {
- monitor.done();
- }
- return result;
- }
-
- private void checkAccessModifiers(final RefactoringStatus result, final Set notDeletedMembersInSubtypes) throws JavaScriptModelException {
- final List toDeclareAbstract= Arrays.asList(fAbstractMethods);
- for (final Iterator iter= notDeletedMembersInSubtypes.iterator(); iter.hasNext();) {
- final IMember member= (IMember) iter.next();
- if (member.getElementType() == IJavaScriptElement.METHOD && !toDeclareAbstract.contains(member)) {
- final IFunction method= ((IFunction) member);
- if (method.getDeclaringType().getPackageFragment().equals(fDestinationType.getPackageFragment())) {
- if (JdtFlags.isPrivate(method))
- result.addError(Messages.format(RefactoringCoreMessages.PullUpRefactoring_lower_default_visibility, new String[] { JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(method.getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(method));
- } else if (!JdtFlags.isPublic(method))
- result.addError(Messages.format(RefactoringCoreMessages.PullUpRefactoring_lower_protected_visibility, new String[] { JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(method.getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(method));
- }
- }
- }
-
- protected RefactoringStatus checkDeclaringSuperTypes(final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringStatus result= new RefactoringStatus();
- if (getCandidateTypes(result, monitor).length == 0 && !result.hasFatalError()) {
- final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_not_this_type, new String[] { JavaScriptElementLabels.getTextLabel(getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- return result;
- }
-
- protected RefactoringStatus checkDeclaringType(final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringStatus status= super.checkDeclaringType(monitor);
- if (JavaModelUtil.getFullyQualifiedName(getDeclaringType()).equals("java.lang.Object")) //$NON-NLS-1$
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PullUpRefactoring_no_java_lang_Object));
- status.merge(checkDeclaringSuperTypes(monitor));
- return status;
- }
-
- private void checkFieldTypes(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- final Map mapping= getMatchingMembers(getDestinationTypeHierarchy(monitor), getDestinationType(), true);
- for (int i= 0; i < fMembersToMove.length; i++) {
- if (fMembersToMove[i].getElementType() != IJavaScriptElement.FIELD)
- continue;
- final IField field= (IField) fMembersToMove[i];
- final String type= Signature.toString(field.getTypeSignature());
- Assert.isTrue(mapping.containsKey(field));
- for (final Iterator iter= ((Set) mapping.get(field)).iterator(); iter.hasNext();) {
- final IField matchingField= (IField) iter.next();
- if (field.equals(matchingField))
- continue;
- if (type.equals(Signature.toString(matchingField.getTypeSignature())))
- continue;
- final String[] keys= { JavaScriptElementLabels.getTextLabel(matchingField, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(matchingField.getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_different_field_type, keys);
- final RefactoringStatusContext context= JavaStatusContext.create(matchingField.getJavaScriptUnit(), matchingField.getSourceRange());
- status.addError(message, context);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 12);
- clearCaches();
-
- final RefactoringStatus result= new RefactoringStatus();
- result.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
- if (result.hasFatalError())
- return result;
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- result.merge(checkGenericDeclaringType(new SubProgressMonitor(monitor, 1)));
- result.merge(checkFinalFields(new SubProgressMonitor(monitor, 1)));
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- result.merge(checkAccesses(new SubProgressMonitor(monitor, 1)));
- result.merge(checkMembersInTypeAndAllSubtypes(new SubProgressMonitor(monitor, 2)));
- result.merge(checkIfSkippingOverElements(new SubProgressMonitor(monitor, 1)));
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- if (!JdtFlags.isAbstract(getDestinationType()) && getAbstractMethods().length > 0)
- result.merge(checkConstructorCalls(getDestinationType(), new SubProgressMonitor(monitor, 1)));
- else
- monitor.worked(1);
- if (result.hasFatalError())
- return result;
- fCompilationUnitRewrites= new HashMap(3);
- result.merge(checkProjectCompliance(getCompilationUnitRewrite(fCompilationUnitRewrites, getDeclaringType().getJavaScriptUnit()), getDestinationType(), fMembersToMove));
- fChangeManager= createChangeManager(new SubProgressMonitor(monitor, 1), result);
- result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), getRefactoring().getValidationContext()));
- return result;
- } finally {
- monitor.done();
- }
- }
-
- private RefactoringStatus checkFinalFields(final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringStatus result= new RefactoringStatus();
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, fMembersToMove.length);
- for (int index= 0; index < fMembersToMove.length; index++) {
- final IMember member= fMembersToMove[index];
- if (member.getElementType() == IJavaScriptElement.FIELD) {
- if (!JdtFlags.isStatic(member)) {
- if (JdtFlags.isFinal(member)) {
- final RefactoringStatusContext context= JavaStatusContext.create(member);
- result.addWarning(RefactoringCoreMessages.PullUpRefactoring_final_fields, context);
- }
- }
- }
- monitor.worked(1);
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
- monitor.done();
- return result;
- }
-
- private RefactoringStatus checkGenericDeclaringType(final SubProgressMonitor monitor) throws JavaScriptModelException {
- Assert.isNotNull(monitor);
-
- final RefactoringStatus status= new RefactoringStatus();
- try {
- final IMember[] pullables= getMembersToMove();
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, pullables.length);
- } finally {
- monitor.done();
- }
- return status;
- }
-
- private RefactoringStatus checkIfDeclaredIn(final IMember element, final IType type) throws JavaScriptModelException {
- if (element instanceof IFunction)
- return checkIfMethodDeclaredIn((IFunction) element, type);
- else if (element instanceof IField)
- return checkIfFieldDeclaredIn((IField) element, type);
- else if (element instanceof IType)
- return checkIfTypeDeclaredIn((IType) element, type);
- Assert.isTrue(false);
- return null;
- }
-
- private RefactoringStatus checkIfFieldDeclaredIn(final IField iField, final IType type) {
- final IField fieldInType= type.getField(iField.getElementName());
- if (!fieldInType.exists())
- return null;
- final String[] keys= { JavaScriptElementLabels.getTextLabel(fieldInType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_Field_declared_in_class, keys);
- final RefactoringStatusContext context= JavaStatusContext.create(fieldInType);
- return RefactoringStatus.createWarningStatus(msg, context);
- }
-
- private RefactoringStatus checkIfMethodDeclaredIn(final IFunction iMethod, final IType type) throws JavaScriptModelException {
- final IFunction methodInType= JavaModelUtil.findMethod(iMethod.getElementName(), iMethod.getParameterTypes(), iMethod.isConstructor(), type);
- if (methodInType == null || !methodInType.exists())
- return null;
- final String[] keys= { JavaScriptElementLabels.getTextLabel(methodInType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_Method_declared_in_class, keys);
- final RefactoringStatusContext context= JavaStatusContext.create(methodInType);
- return RefactoringStatus.createWarningStatus(msg, context);
- }
-
- private RefactoringStatus checkIfSkippingOverElements(final IProgressMonitor monitor) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
- try {
- final Set skippedTypes= getSkippedSuperTypes(new SubProgressMonitor(monitor, 1));
- final IType[] skipped= (IType[]) skippedTypes.toArray(new IType[skippedTypes.size()]);
- final RefactoringStatus result= new RefactoringStatus();
- for (int i= 0; i < fMembersToMove.length; i++) {
- final IMember element= fMembersToMove[i];
- for (int j= 0; j < skipped.length; j++) {
- result.merge(checkIfDeclaredIn(element, skipped[j]));
- }
- }
- return result;
- } finally {
- monitor.done();
- }
- }
-
- private RefactoringStatus checkIfTypeDeclaredIn(final IType iType, final IType type) {
- final IType typeInType= type.getType(iType.getElementName());
- if (!typeInType.exists())
- return null;
- final String[] keys= { JavaScriptElementLabels.getTextLabel(typeInType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String msg= Messages.format(RefactoringCoreMessages.PullUpRefactoring_Type_declared_in_class, keys);
- final RefactoringStatusContext context= JavaStatusContext.create(typeInType);
- return RefactoringStatus.createWarningStatus(msg, context);
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkInitialConditions(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
- final RefactoringStatus status= new RefactoringStatus();
- status.merge(checkDeclaringType(new SubProgressMonitor(monitor, 1)));
- if (status.hasFatalError())
- return status;
- status.merge(checkIfMembersExist());
- if (status.hasFatalError())
- return status;
- return status;
- } finally {
- monitor.done();
- }
- }
-
- private void checkMembersInDestinationType(final RefactoringStatus status, final Set set) throws JavaScriptModelException {
- final IMember[] destinationMembers= getCreatedDestinationMembers();
- final List list= new ArrayList(destinationMembers.length);
- list.addAll(Arrays.asList(destinationMembers));
- list.addAll(set);
- list.removeAll(Arrays.asList(fDeletedMethods));
- final IMember[] members= (IMember[]) list.toArray(new IMember[list.size()]);
- status.merge(MemberCheckUtil.checkMembersInDestinationType(members, getDestinationType()));
- }
-
- private RefactoringStatus checkMembersInTypeAndAllSubtypes(final IProgressMonitor monitor) throws JavaScriptModelException {
- final RefactoringStatus result= new RefactoringStatus();
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 3);
- final Set notDeletedMembers= getNotDeletedMembers(new SubProgressMonitor(monitor, 1));
- final Set notDeletedMembersInTargetType= new HashSet();
- final Set notDeletedMembersInSubtypes= new HashSet();
- for (final Iterator iter= notDeletedMembers.iterator(); iter.hasNext();) {
- final IMember member= (IMember) iter.next();
- if (getDestinationType().equals(member.getDeclaringType()))
- notDeletedMembersInTargetType.add(member);
- else
- notDeletedMembersInSubtypes.add(member);
- }
- checkMembersInDestinationType(result, notDeletedMembersInTargetType);
- checkAccessModifiers(result, notDeletedMembersInSubtypes);
- checkMethodReturnTypes(new SubProgressMonitor(monitor, 1), result, notDeletedMembersInSubtypes);
- checkFieldTypes(new SubProgressMonitor(monitor, 1), result);
- monitor.done();
- return result;
- }
-
- private void checkMethodReturnTypes(final IProgressMonitor monitor, final RefactoringStatus status, final Set notDeletedMembersInSubtypes) throws JavaScriptModelException {
- final Map mapping= getMatchingMembers(getDestinationTypeHierarchy(monitor), getDestinationType(), true);
- final IMember[] members= getCreatedDestinationMembers();
- for (int i= 0; i < members.length; i++) {
- if (members[i].getElementType() != IJavaScriptElement.METHOD)
- continue;
- final IFunction method= (IFunction) members[i];
- if (mapping.containsKey(method)) {
- final Set set= (Set) mapping.get(method);
- if (set != null) {
- final String returnType= Signature.toString(Signature.getReturnType(method.getSignature()).toString());
- for (final Iterator iter= set.iterator(); iter.hasNext();) {
- final IFunction matchingMethod= (IFunction) iter.next();
- if (method.equals(matchingMethod))
- continue;
- if (!notDeletedMembersInSubtypes.contains(matchingMethod))
- continue;
- if (returnType.equals(Signature.toString(Signature.getReturnType(matchingMethod.getSignature()).toString())))
- continue;
- final String[] keys= { JavaScriptElementLabels.getTextLabel(matchingMethod, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(matchingMethod.getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED)};
- final String message= Messages.format(RefactoringCoreMessages.PullUpRefactoring_different_method_return_type, keys);
- final RefactoringStatusContext context= JavaStatusContext.create(matchingMethod.getJavaScriptUnit(), matchingMethod.getNameRange());
- status.addError(message, context);
- }
- }
- }
- }
- }
-
- protected void clearCaches() {
- super.clearCaches();
- fCachedMembersReferences.clear();
- fCachedDestinationTypeHierarchy= null;
- fCachedDeclaringSuperTypeHierarchy= null;
- }
-
- private void copyBodyOfPulledUpMethod(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IFunction method, final FunctionDeclaration oldMethod, final FunctionDeclaration newMethod, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor) throws JavaScriptModelException {
- final Block body= oldMethod.getBody();
- if (body == null) {
- newMethod.setBody(null);
- return;
- }
- try {
- final IDocument document= new Document(method.getJavaScriptUnit().getBuffer().getContents());
- final ASTRewrite rewrite= ASTRewrite.create(body.getAST());
- final ITrackedNodePosition position= rewrite.track(body);
- body.accept(new PullUpAstNodeMapper(sourceRewrite, targetRewrite, rewrite, getDeclaringSuperTypeHierarchy(monitor).getSuperclass(getDeclaringType()), mapping, oldMethod.resolveBinding()));
- rewrite.rewriteAST(document, method.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- String content= document.get(position.getStartPosition(), position.getLength());
- final String[] lines= Strings.convertIntoLines(content);
- Strings.trimIndentation(lines, method.getJavaScriptProject(), false);
- content= Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
- newMethod.setBody((Block) targetRewrite.getASTRewrite().createStringPlaceholder(content, ASTNode.BLOCK));
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
- private void createAbstractMethod(final IFunction sourceMethod, final CompilationUnitRewrite sourceRewriter, final JavaScriptUnit declaringCuNode, final AbstractTypeDeclaration destination, final TypeVariableMaplet[] mapping, final CompilationUnitRewrite targetRewrite, final Map adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- final FunctionDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
- final FunctionDeclaration newMethod= targetRewrite.getAST().newFunctionDeclaration();
- newMethod.setBody(null);
- newMethod.setConstructor(false);
- newMethod.setExtraDimensions(oldMethod.getExtraDimensions());
- newMethod.setJavadoc(null);
- int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status);
- if (oldMethod.isVarargs())
- modifiers&= ~Flags.AccVarargs;
- newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(targetRewrite.getAST(), modifiers));
- newMethod.setName(((SimpleName) ASTNode.copySubtree(targetRewrite.getAST(), oldMethod.getName())));
- copyReturnType(targetRewrite.getASTRewrite(), getDeclaringType().getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyParameters(targetRewrite.getASTRewrite(), getDeclaringType().getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyThrownExceptions(oldMethod, newMethod);
- ImportRewriteUtil.addImports(targetRewrite, newMethod, new HashMap(), new HashMap(), false);
- targetRewrite.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, destination.bodyDeclarations()), targetRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_abstract_method, SET_PULL_UP));
- }
-
- /**
- * {@inheritDoc}
- */
- public Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- try {
- final Map arguments= new HashMap();
- String project= null;
- final IType declaring= getDeclaringType();
- final IJavaScriptProject javaProject= declaring.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- try {
- if (declaring.isLocal() || declaring.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= fMembersToMove.length == 1 ? Messages.format(RefactoringCoreMessages.PullUpRefactoring_descriptor_description_short, new String[] { fMembersToMove[0].getElementName(), fDestinationType.getElementName()}) : Messages.format(RefactoringCoreMessages.PullUpRefactoring_descriptor_description_short_multiple, fDestinationType.getElementName());
- final String header= fMembersToMove.length == 1 ? Messages.format(RefactoringCoreMessages.PullUpRefactoring_descriptor_description_full, new String[] { JavaScriptElementLabels.getElementLabel(fMembersToMove[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)}) : Messages.format(RefactoringCoreMessages.PullUpRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)});
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.MoveStaticMembersProcessor_target_element_pattern, JavaScriptElementLabels.getElementLabel(fDestinationType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- addSuperTypeSettings(comment, true);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.PULL_UP, project, description, comment.asString(), arguments, flags);
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fDestinationType));
- arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplace).toString());
- arguments.put(ATTRIBUTE_INSTANCEOF, Boolean.valueOf(fInstanceOf).toString());
- arguments.put(ATTRIBUTE_STUBS, Boolean.valueOf(fCreateMethodStubs).toString());
- arguments.put(ATTRIBUTE_PULL, new Integer(fMembersToMove.length).toString());
- for (int offset= 0; offset < fMembersToMove.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fMembersToMove[offset]));
- arguments.put(ATTRIBUTE_DELETE, new Integer(fDeletedMethods.length).toString());
- for (int offset= 0; offset < fDeletedMethods.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fMembersToMove.length + 1), descriptor.elementToHandle(fDeletedMethods[offset]));
- arguments.put(ATTRIBUTE_ABSTRACT, new Integer(fAbstractMethods.length).toString());
- for (int offset= 0; offset < fAbstractMethods.length; offset++)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fMembersToMove.length + fDeletedMethods.length + 1), descriptor.elementToHandle(fAbstractMethods[offset]));
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.PullUpRefactoring_Pull_Up, fChangeManager.getAllChanges());
- } finally {
- monitor.done();
- clearCaches();
- }
- }
-
- private TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 24);
- final IJavaScriptUnit source= getDeclaringType().getJavaScriptUnit();
- final IType destination= getDestinationType();
- final IJavaScriptUnit target= destination.getJavaScriptUnit();
- final CompilationUnitRewrite sourceRewriter= getCompilationUnitRewrite(fCompilationUnitRewrites, source);
- final CompilationUnitRewrite targetRewriter= getCompilationUnitRewrite(fCompilationUnitRewrites, target);
- final Map deleteMap= createMembersToDeleteMap(new SubProgressMonitor(monitor, 1));
- final Map effectedMap= createEffectedTypesMap(new SubProgressMonitor(monitor, 1));
- final IJavaScriptUnit[] units= getAffectedCompilationUnits(new SubProgressMonitor(monitor, 1));
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- final Map adjustments= new HashMap();
- MemberVisibilityAdjustor adjustor= null;
- final IProgressMonitor sub= new SubProgressMonitor(monitor, 1);
- try {
- sub.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, units.length * 11);
- for (int index= 0; index < units.length; index++) {
- unit= units[index];
- if (!(source.equals(unit) || target.equals(unit) || deleteMap.containsKey(unit) || effectedMap.containsKey(unit))) {
- sub.worked(10);
- continue;
- }
- rewrite= getCompilationUnitRewrite(fCompilationUnitRewrites, unit);
- if (deleteMap.containsKey(unit)) {
- LinkedList list= new LinkedList((List) deleteMap.get(unit));
- deleteDeclarationNodes(sourceRewriter, sourceRewriter.getCu().equals(targetRewriter.getCu()), rewrite, list, SET_PULL_UP);
- }
- final JavaScriptUnit root= sourceRewriter.getRoot();
- if (unit.equals(target)) {
- final ASTRewrite rewriter= rewrite.getASTRewrite();
- if (!JdtFlags.isAbstract(destination) && getAbstractMethods().length > 0) {
- final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(destination, rewrite.getRoot());
- ModifierRewrite.create(rewriter, declaration).setModifiers(declaration.getModifiers() | Modifier.ABSTRACT, rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_make_target_abstract, SET_PULL_UP));
- }
- final IProgressMonitor subsub= new SubProgressMonitor(sub, 1);
- final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(destination, rewrite.getRoot());
- fMembersToMove= JavaElementUtil.sortByOffset(fMembersToMove);
- subsub.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, fMembersToMove.length);
- IMember member= null;
- for (int offset= fMembersToMove.length - 1; offset >= 0; offset--) {
- member= fMembersToMove[offset];
- adjustor= new MemberVisibilityAdjustor(destination, member);
- adjustor.setRewrite(sourceRewriter.getASTRewrite(), root);
-
- // TW: set to error if bug 78387 is fixed
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
-
- adjustor.setOwner(fOwner);
- adjustor.setRewrites(fCompilationUnitRewrites);
- adjustor.setStatus(status);
- adjustor.setAdjustments(adjustments);
- adjustor.adjustVisibility(new SubProgressMonitor(subsub, 1));
- adjustments.remove(member);
- if (member instanceof IField) {
- final VariableDeclarationFragment oldField= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, root);
- if (oldField != null) {
- int flags= getModifiersWithUpdatedVisibility(member, member.getFlags(), adjustments, new SubProgressMonitor(subsub, 1), true, status);
- final FieldDeclaration newField= createNewFieldDeclarationNode(rewriter, root, (IField) member, oldField, null, new SubProgressMonitor(subsub, 1), status, flags);
- rewriter.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newField, ASTNodes.getInsertionIndex(newField, declaration.bodyDeclarations()), rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PULL_UP));
- ImportRewriteUtil.addImports(rewrite, oldField.getParent(), new HashMap(), new HashMap(), false);
- }
- } else if (member instanceof IFunction) {
- final FunctionDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode((IFunction) member, root);
- if (oldMethod != null) {
- final FunctionDeclaration newMethod= createNewMethodDeclarationNode(sourceRewriter, rewrite, ((IFunction) member), oldMethod, root, null, adjustments, new SubProgressMonitor(subsub, 1), status);
- rewriter.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, declaration.bodyDeclarations()), rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PULL_UP));
- ImportRewriteUtil.addImports(rewrite, oldMethod, new HashMap(), new HashMap(), false);
- }
- } else if (member instanceof IType) {
- final AbstractTypeDeclaration oldType= ASTNodeSearchUtil.getAbstractTypeDeclarationNode((IType) member, root);
- if (oldType != null) {
- final BodyDeclaration newType= createNewTypeDeclarationNode(((IType) member), oldType, root, null, rewriter);
- rewriter.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newType, ASTNodes.getInsertionIndex(newType, declaration.bodyDeclarations()), rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PULL_UP));
- ImportRewriteUtil.addImports(rewrite, oldType, new HashMap(), new HashMap(), false);
- }
- } else
- Assert.isTrue(false);
- subsub.worked(1);
- }
- subsub.done();
- for (int offset= 0; offset < fAbstractMethods.length; offset++)
- createAbstractMethod(fAbstractMethods[offset], sourceRewriter, root, declaration, null, rewrite, adjustments, new SubProgressMonitor(sub, 1), status);
- } else
- sub.worked(2);
- if (unit.equals(sourceRewriter.getCu())) {
- final IProgressMonitor subsub= new SubProgressMonitor(sub, 1);
- subsub.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, fAbstractMethods.length * 2);
- IFunction method= null;
- for (int offset= 0; offset < fAbstractMethods.length; offset++) {
- method= fAbstractMethods[offset];
- adjustor= new MemberVisibilityAdjustor(destination, method);
- adjustor.setRewrite(sourceRewriter.getASTRewrite(), root);
- adjustor.setRewrites(fCompilationUnitRewrites);
-
- // TW: set to error if bug 78387 is fixed
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
-
- adjustor.setOwner(fOwner);
- adjustor.setStatus(status);
- adjustor.setAdjustments(adjustments);
- if (needsVisibilityAdjustment(method, false, new SubProgressMonitor(subsub, 1), status))
- adjustments.put(method, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(method, Modifier.ModifierKeyword.PROTECTED_KEYWORD, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(method), RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_protected}), JavaStatusContext.create(method))));
- }
- } else
- sub.worked(2);
- if (effectedMap.containsKey(unit))
- addNecessaryMethodStubs((List) effectedMap.get(unit), root, rewrite, adjustments, new SubProgressMonitor(sub, 2), status);
- if (sub.isCanceled())
- throw new OperationCanceledException();
- }
- } finally {
- sub.done();
- }
- if (adjustor != null && !adjustments.isEmpty())
- adjustor.rewriteVisibility(new SubProgressMonitor(monitor, 1));
- final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
- if (fReplace) {
- final Set set= fCompilationUnitRewrites.keySet();
- for (final Iterator iterator= set.iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- rewrite= (CompilationUnitRewrite) fCompilationUnitRewrites.get(unit);
- if (rewrite != null) {
- final CompilationUnitChange change= rewrite.createChange(false, null);
- if (change != null)
- manager.manage(unit, change);
- }
- }
- TextEdit edit= null;
- TextEditBasedChange change= null;
- final Map workingcopies= new HashMap();
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
- try {
- subMonitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, set.size());
- for (final Iterator iterator= set.iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- change= manager.get(unit);
- if (change instanceof TextChange) {
- edit= ((TextChange) change).getEdit();
- if (edit != null) {
- final IJavaScriptUnit copy= createWorkingCopy(unit, edit, status, new SubProgressMonitor(monitor, 1));
- if (copy != null)
- workingcopies.put(unit, copy);
- }
- }
- }
- final IJavaScriptUnit current= (IJavaScriptUnit) workingcopies.get(sourceRewriter.getCu());
- if (current != null)
- rewriteTypeOccurrences(manager, sourceRewriter, current, new HashSet(), status, new SubProgressMonitor(monitor, 16));
- } finally {
- subMonitor.done();
- IJavaScriptUnit[] cus= manager.getAllCompilationUnits();
- for (int index= 0; index < cus.length; index++) {
- CompilationUnitChange current= (CompilationUnitChange) manager.get(cus[index]);
- if (change != null && current.getEdit() == null)
- manager.remove(cus[index]);
- }
- }
- }
- registerChanges(manager);
- return manager;
- } finally {
- fCompilationUnitRewrites.clear();
- monitor.done();
- }
- }
-
- private Map createEffectedTypesMap(final IProgressMonitor monitor) throws JavaScriptModelException {
- if (!(fCreateMethodStubs && getAbstractMethods().length > 0))
- return new HashMap(0);
- final Set effected= getEffectedSubTypes(getDestinationTypeHierarchy(monitor), getDestinationType());
- final Map result= new HashMap();
- for (final Iterator iterator= effected.iterator(); iterator.hasNext();) {
- final IType type= (IType) iterator.next();
- final IJavaScriptUnit unit= type.getJavaScriptUnit();
- if (!result.containsKey(unit))
- result.put(unit, new ArrayList(1));
- ((List) result.get(unit)).add(type);
- }
- return result;
- }
-
- private JSdoc createJavadocForStub(final String enclosingTypeName, final FunctionDeclaration oldMethod, final FunctionDeclaration newMethodNode, final IJavaScriptUnit cu, final ASTRewrite rewrite) throws CoreException {
- if (fSettings.createComments) {
- final IFunctionBinding binding= oldMethod.resolveBinding();
- if (binding != null) {
- final ITypeBinding[] params= binding.getParameterTypes();
- final String fullTypeName= JavaModelUtil.getFullyQualifiedName(getDestinationType());
- final String[] fullParamNames= new String[params.length];
- for (int i= 0; i < fullParamNames.length; i++) {
- fullParamNames[i]= Bindings.getFullyQualifiedName(params[i]);
- }
- final String comment= CodeGeneration.getMethodComment(cu, enclosingTypeName, newMethodNode, false, binding.getName(), fullTypeName, fullParamNames, StubUtility.getLineDelimiterUsed(cu));
- return (JSdoc) rewrite.createStringPlaceholder(comment, ASTNode.JSDOC);
- }
- }
- return null;
- }
-
- private Map createMembersToDeleteMap(final IProgressMonitor monitor) throws JavaScriptModelException {
- final IMember[] membersToDelete= getMembersToDelete(monitor);
- final Map result= new HashMap();
- for (int i= 0; i < membersToDelete.length; i++) {
- final IMember member= membersToDelete[i];
- final IJavaScriptUnit cu= member.getJavaScriptUnit();
- if (!result.containsKey(cu))
- result.put(cu, new ArrayList(1));
- ((List) result.get(cu)).add(member);
- }
- return result;
- }
-
- private FunctionDeclaration createNewMethodDeclarationNode(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IFunction sourceMethod, final FunctionDeclaration oldMethod, final JavaScriptUnit declaringCuNode, final TypeVariableMaplet[] mapping, final Map adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- final ASTRewrite rewrite= targetRewrite.getASTRewrite();
- final AST ast= rewrite.getAST();
- final FunctionDeclaration newMethod= ast.newFunctionDeclaration();
- copyBodyOfPulledUpMethod(sourceRewrite, targetRewrite, sourceMethod, oldMethod, newMethod, mapping, monitor);
- newMethod.setConstructor(oldMethod.isConstructor());
- newMethod.setExtraDimensions(oldMethod.getExtraDimensions());
- copyJavadocNode(rewrite, sourceMethod, oldMethod, newMethod);
- int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, sourceMethod.getFlags(), adjustments, monitor, true, status);
- if (oldMethod.isVarargs())
- modifiers&= ~Flags.AccVarargs;
- copyAnnotations(oldMethod, newMethod);
- newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
- newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, oldMethod.getName())));
- copyReturnType(rewrite, getDeclaringType().getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyParameters(rewrite, getDeclaringType().getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyThrownExceptions(oldMethod, newMethod);
- return newMethod;
- }
-
- private BodyDeclaration createNewTypeDeclarationNode(final IType type, final AbstractTypeDeclaration oldType, final JavaScriptUnit declaringCuNode, final TypeVariableMaplet[] mapping, final ASTRewrite rewrite) throws JavaScriptModelException {
- final IJavaScriptUnit declaringCu= getDeclaringType().getJavaScriptUnit();
- if (!JdtFlags.isPublic(type)) {
- if (mapping.length > 0)
- return createPlaceholderForTypeDeclaration(oldType, declaringCu, mapping, rewrite, true);
-
- return createPlaceholderForProtectedTypeDeclaration(oldType, declaringCuNode, declaringCu, rewrite, true);
- }
- if (mapping.length > 0)
- return createPlaceholderForTypeDeclaration(oldType, declaringCu, mapping, rewrite, true);
-
- return createPlaceholderForTypeDeclaration(oldType, declaringCu, rewrite, true);
- }
-
- private IJavaScriptUnit createWorkingCopy(final IJavaScriptUnit unit, final TextEdit edit, final RefactoringStatus status, final IProgressMonitor monitor) {
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
- final IJavaScriptUnit copy= getSharedWorkingCopy(unit.getPrimary(), new SubProgressMonitor(monitor, 1));
- final IDocument document= new Document(unit.getBuffer().getContents());
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- copy.getBuffer().setContents(document.get());
- JavaModelUtil.reconcile(copy);
- return copy;
- } catch (JavaScriptModelException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- } catch (MalformedTreeException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- } catch (BadLocationException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- } finally {
- monitor.done();
- }
- return null;
- }
-
- /**
- * Creates a working copy layer if necessary.
- *
- * @param monitor
- * the progress monitor to use
- * @return a status describing the outcome of the operation
- */
- protected RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
- try {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
- IJavaScriptUnit unit= getDeclaringType().getJavaScriptUnit();
- if (fLayer)
- unit= unit.findWorkingCopy(fOwner);
- resetWorkingCopies(unit);
- return new RefactoringStatus();
- } finally {
- monitor.done();
- }
- }
-
- private IFunction[] getAbstractMethods() throws JavaScriptModelException {
- final IFunction[] toDeclareAbstract= fAbstractMethods;
- final IFunction[] abstractPulledUp= getAbstractMethodsToPullUp();
- final Set result= new LinkedHashSet(toDeclareAbstract.length + abstractPulledUp.length + fMembersToMove.length);
-
- result.addAll(Arrays.asList(toDeclareAbstract));
- result.addAll(Arrays.asList(abstractPulledUp));
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- }
-
- private IFunction[] getAbstractMethodsToPullUp() throws JavaScriptModelException {
- final List result= new ArrayList(fMembersToMove.length);
- for (int i= 0; i < fMembersToMove.length; i++) {
- final IMember member= fMembersToMove[i];
- if (member instanceof IFunction && JdtFlags.isAbstract(member))
- result.add(member);
- }
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- }
-
- public IMember[] getAdditionalRequiredMembersToPullUp(final IProgressMonitor monitor) throws JavaScriptModelException {
- final IMember[] members= getCreatedDestinationMembers();
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_calculating_required, members.length);// not
- final List queue= new ArrayList(members.length);
- queue.addAll(Arrays.asList(members));
- if (queue.isEmpty())
- return new IMember[0];
- int i= 0;
- IMember current;
- do {
- current= (IMember) queue.get(i);
- addAllRequiredPullableMembers(queue, current, new SubProgressMonitor(monitor, 1));
- i++;
- if (queue.size() == i)
- current= null;
- } while (current != null);
- queue.removeAll(Arrays.asList(members));// report only additional
- return (IMember[]) queue.toArray(new IMember[queue.size()]);
- }
-
- private IJavaScriptUnit[] getAffectedCompilationUnits(final IProgressMonitor monitor) throws JavaScriptModelException {
- final IType[] allSubtypes= getDestinationTypeHierarchy(monitor).getAllSubtypes(getDestinationType());
- final Set result= new HashSet(allSubtypes.length);
- for (int i= 0; i < allSubtypes.length; i++) {
- result.add(allSubtypes[i].getJavaScriptUnit());
- }
- result.add(getDestinationType().getJavaScriptUnit());
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- public IType[] getCandidateTypes(final RefactoringStatus status, final IProgressMonitor monitor) throws JavaScriptModelException {
- final IType declaring= getDeclaringType();
- final IType[] superTypes= declaring.newSupertypeHierarchy(fOwner, monitor).getAllSuperclasses(declaring);
- final List list= new ArrayList(superTypes.length);
- int binary= 0;
- for (int index= 0; index < superTypes.length; index++) {
- final IType type= superTypes[index];
- if (type != null && type.exists() && !type.isReadOnly() && !type.isBinary() && !"java.lang.Object".equals(type.getFullyQualifiedName())) { //$NON-NLS-1$
- list.add(type);
- } else {
- if (type != null && type.isBinary()) {
- binary++;
- }
- }
- }
- if (superTypes.length == 1 && superTypes[0].getFullyQualifiedName().equals("java.lang.Object")) //$NON-NLS-1$
- status.addFatalError(RefactoringCoreMessages.PullUPRefactoring_not_java_lang_object);
- else if (superTypes.length == binary)
- status.addFatalError(RefactoringCoreMessages.PullUPRefactoring_no_all_binary);
-
- Collections.reverse(list);
- return (IType[]) list.toArray(new IType[list.size()]);
- }
-
- protected CompilationUnitRewrite getCompilationUnitRewrite(final Map rewrites, final IJavaScriptUnit unit) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(unit);
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- if (rewrite == null) {
- rewrite= new CompilationUnitRewrite(fOwner, unit);
- rewrites.put(unit, rewrite);
- }
- return rewrite;
- }
-
- private IMember[] getCreatedDestinationMembers() {
- final List result= new ArrayList(fMembersToMove.length + fAbstractMethods.length);
- result.addAll(Arrays.asList(fMembersToMove));
- result.addAll(Arrays.asList(fAbstractMethods));
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- public boolean getCreateMethodStubs() {
- return fCreateMethodStubs;
- }
-
- public ITypeHierarchy getDeclaringSuperTypeHierarchy(final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- if (fCachedDeclaringSuperTypeHierarchy != null)
- return fCachedDeclaringSuperTypeHierarchy;
- fCachedDeclaringSuperTypeHierarchy= getDeclaringType().newSupertypeHierarchy(fOwner, monitor);
- return fCachedDeclaringSuperTypeHierarchy;
- } finally {
- monitor.done();
- }
- }
-
- public IType getDestinationType() {
- return fDestinationType;
- }
-
- public ITypeHierarchy getDestinationTypeHierarchy(final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- if (fCachedDestinationTypeHierarchy != null && fCachedDestinationTypeHierarchy.getType().equals(getDestinationType()))
- return fCachedDestinationTypeHierarchy;
- fCachedDestinationTypeHierarchy= getDestinationType().newTypeHierarchy(fOwner, monitor);
- return fCachedDestinationTypeHierarchy;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getElements() {
- return fMembersToMove;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- public IMember[] getMatchingElements(final IProgressMonitor monitor, final boolean includeAbstract) throws JavaScriptModelException {
- try {
- final Set result= new HashSet();
- final IType destination= getDestinationType();
- final Map matching= getMatchingMembers(getDestinationTypeHierarchy(monitor), getDestinationType(), includeAbstract);
- for (final Iterator iterator= matching.keySet().iterator(); iterator.hasNext();) {
- final IMember key= (IMember) iterator.next();
- Assert.isTrue(!key.getDeclaringType().equals(destination));
- result.addAll((Set) matching.get(key));
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- } finally {
- monitor.done();
- }
- }
-
- private Map getMatchingMembers(final ITypeHierarchy hierarchy, final IType type, final boolean includeAbstract) throws JavaScriptModelException {
- final Map result= new HashMap();
- result.putAll(getMatchingMembersMapping(type));
- final IType[] subTypes= hierarchy.getAllSubtypes(type);
- for (int i= 0; i < subTypes.length; i++) {
- final Map map= getMatchingMembersMapping(subTypes[i]);
- mergeMaps(result, map);
- upgradeMap(result, map);
- }
- if (includeAbstract)
- return result;
-
- for (int i= 0; i < fAbstractMethods.length; i++) {
- if (result.containsKey(fAbstractMethods[i]))
- result.remove(fAbstractMethods[i]);
- }
- return result;
- }
-
- private Map getMatchingMembersMapping(final IType initial) throws JavaScriptModelException {
- final Map result= new HashMap();
- final IMember[] members= getCreatedDestinationMembers();
- for (int i= 0; i < members.length; i++) {
- final IMember member= members[i];
- if (member instanceof IFunction) {
- final IFunction method= (IFunction) member;
- final IFunction found= MemberCheckUtil.findMethod(method, initial.getFunctions());
- if (found != null)
- addMatchingMember(result, method, found);
- } else if (member instanceof IField) {
- final IField field= (IField) member;
- final IField found= initial.getField(field.getElementName());
- if (found.exists())
- addMatchingMember(result, field, found);
- } else if (member instanceof IType) {
- final IType type= (IType) member;
- final IType found= initial.getType(type.getElementName());
- if (found.exists())
- addMatchingMember(result, type, found);
- } else
- Assert.isTrue(false);
- }
-
- return result;
- }
-
- private IMember[] getMembersToDelete(final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- final IMember[] typesToDelete= getMembers(fMembersToMove, IJavaScriptElement.TYPE);
- final IMember[] matchingElements= getMatchingElements(monitor, false);
- final IMember[] matchingFields= getMembers(matchingElements, IJavaScriptElement.FIELD);
- return JavaElementUtil.merge(JavaElementUtil.merge(matchingFields, typesToDelete), fDeletedMethods);
- } finally {
- monitor.done();
- }
- }
-
- private int getModifiersWithUpdatedVisibility(final IMember member, final int modifiers, final Map adjustments, final IProgressMonitor monitor, final boolean considerReferences, final RefactoringStatus status) throws JavaScriptModelException {
- if (needsVisibilityAdjustment(member, considerReferences, monitor, status)) {
- final MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(member, Modifier.ModifierKeyword.PROTECTED_KEYWORD, RefactoringStatus.createWarningStatus(Messages.format(MemberVisibilityAdjustor.getMessage(member), new String[] { MemberVisibilityAdjustor.getLabel(member), MemberVisibilityAdjustor.getLabel(Modifier.ModifierKeyword.PROTECTED_KEYWORD)})));
- adjustment.setNeedsRewriting(false);
- adjustments.put(member, adjustment);
- return JdtFlags.clearAccessModifiers(modifiers) | Modifier.PROTECTED;
- }
- return modifiers;
- }
-
- private Set getNotDeletedMembers(final IProgressMonitor monitor) throws JavaScriptModelException {
- final Set matchingSet= new HashSet();
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 2);
- matchingSet.addAll(Arrays.asList(getMatchingElements(new SubProgressMonitor(monitor, 1), true)));
- matchingSet.removeAll(Arrays.asList(getMembersToDelete(new SubProgressMonitor(monitor, 1))));
- monitor.done();
- return matchingSet;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getProcessorName() {
- return RefactoringCoreMessages.PullUpRefactoring_Pull_Up;
- }
-
- public IMember[] getPullableMembersOfDeclaringType() {
- try {
- return RefactoringAvailabilityTester.getPullUpMembers(getDeclaringType());
- } catch (JavaScriptModelException e) {
- return new IMember[0];
- }
- }
-
- // skipped super classes are those declared in the hierarchy between the
- // declaring type of the selected members
- // and the target type
- private Set getSkippedSuperTypes(final IProgressMonitor monitor) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
- try {
- if (fCachedSkippedSuperTypes != null && getDestinationTypeHierarchy(new SubProgressMonitor(monitor, 1)).getType().equals(getDestinationType()))
- return fCachedSkippedSuperTypes;
- final ITypeHierarchy hierarchy= getDestinationTypeHierarchy(new SubProgressMonitor(monitor, 1));
- fCachedSkippedSuperTypes= new HashSet(2);
- IType current= hierarchy.getSuperclass(getDeclaringType());
- while (current != null && !current.equals(getDestinationType())) {
- fCachedSkippedSuperTypes.add(current);
- current= hierarchy.getSuperclass(current);
- }
- return fCachedSkippedSuperTypes;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PULL_UP);
- else
- fDestinationType= (IType) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- final String stubs= extended.getAttribute(ATTRIBUTE_STUBS);
- if (stubs != null) {
- fCreateMethodStubs= Boolean.valueOf(stubs).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_STUBS));
- final String instance= extended.getAttribute(ATTRIBUTE_INSTANCEOF);
- if (instance != null) {
- fInstanceOf= Boolean.valueOf(instance).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INSTANCEOF));
- final String replace= extended.getAttribute(ATTRIBUTE_REPLACE);
- if (replace != null) {
- fReplace= Boolean.valueOf(replace).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
- int pullCount= 0;
- int abstractCount= 0;
- int deleteCount= 0;
- String value= extended.getAttribute(ATTRIBUTE_ABSTRACT);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- abstractCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ABSTRACT));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ABSTRACT));
- value= extended.getAttribute(ATTRIBUTE_DELETE);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- deleteCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELETE));
- value= extended.getAttribute(ATTRIBUTE_PULL);
- if (value != null && !"".equals(value)) {//$NON-NLS-1$
- try {
- pullCount= Integer.parseInt(value);
- } catch (NumberFormatException exception) {
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_PULL));
- }
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_PULL));
- final RefactoringStatus status= new RefactoringStatus();
- List elements= new ArrayList();
- for (int index= 0; index < pullCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PULL_UP));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fMembersToMove= (IMember[]) elements.toArray(new IMember[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < deleteCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (pullCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PULL_UP));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fDeletedMethods= (IFunction[]) elements.toArray(new IFunction[elements.size()]);
- elements= new ArrayList();
- for (int index= 0; index < abstractCount; index++) {
- final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (pullCount + abstractCount + index + 1);
- handle= extended.getAttribute(attribute);
- if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PULL_UP));
- else
- elements.add(element);
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute));
- }
- fAbstractMethods= (IFunction[]) elements.toArray(new IFunction[elements.size()]);
- IJavaScriptProject project= null;
- if (fMembersToMove.length > 0)
- project= fMembersToMove[0].getJavaScriptProject();
- fSettings= JavaPreferencesSettings.getCodeGenerationSettings(project);
- if (!status.isOK())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isPullUpAvailable(fMembersToMove);
- }
-
- private boolean isAvailableInDestination(final IFunction method, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- final IType destination= getDestinationType();
- final IFunction first= JavaModelUtil.findMethod(method.getElementName(), method.getParameterTypes(), false, destination);
- if (first != null && MethodChecks.isVirtual(first))
- return true;
- final ITypeHierarchy hierarchy= getDestinationTypeHierarchy(monitor);
- final IFunction found= JavaModelUtil.findMethodInHierarchy(hierarchy, destination, method.getElementName(), method.getParameterTypes(), false);
- return found != null && MethodChecks.isVirtual(found);
- } finally {
- monitor.done();
- }
- }
-
- private boolean isRequiredPullableMember(final List queue, final IMember member) throws JavaScriptModelException {
- final IType declaring= member.getDeclaringType();
- if (declaring == null) // not a member
- return false;
- return declaring.equals(getDeclaringType()) && !queue.contains(member) && RefactoringAvailabilityTester.isPullUpAvailable(member);
- }
-
- protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException {
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- for (final Iterator iterator= fCompilationUnitRewrites.keySet().iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- rewrite= (CompilationUnitRewrite) fCompilationUnitRewrites.get(unit);
- if (rewrite != null) {
- final CompilationUnitChange change= rewrite.createChange();
- if (change != null)
- manager.manage(unit, change);
- }
- }
- }
-
- /**
- * Resets the environment before the first wizard page becomes visible.
- */
- public void resetEnvironment() {
- IJavaScriptUnit unit= getDeclaringType().getJavaScriptUnit();
- if (fLayer)
- unit= unit.findWorkingCopy(fOwner);
- resetWorkingCopies(unit);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final IJavaScriptUnit unit, final JavaScriptUnit node, final Set replacements, final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- CompilationUnitRewrite currentRewrite= null;
- final CompilationUnitRewrite existingRewrite= (CompilationUnitRewrite) fCompilationUnitRewrites.get(unit.getPrimary());
- final boolean isTouched= existingRewrite != null;
- if (isTouched)
- currentRewrite= existingRewrite;
- else
- currentRewrite= new CompilationUnitRewrite(unit, node);
- final Collection collection= (Collection) fTypeOccurrences.get(unit);
- if (collection != null && !collection.isEmpty()) {
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100);
- try {
- subMonitor.beginTask("", collection.size() * 10); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- TType estimate= null;
- ISourceConstraintVariable variable= null;
- ITypeConstraintVariable constraint= null;
- for (final Iterator iterator= collection.iterator(); iterator.hasNext();) {
- variable= (ISourceConstraintVariable) iterator.next();
- if (variable instanceof ITypeConstraintVariable) {
- constraint= (ITypeConstraintVariable) variable;
- estimate= (TType) constraint.getData(SuperTypeConstraintsSolver.DATA_TYPE_ESTIMATE);
- if (estimate != null) {
- final CompilationUnitRange range= constraint.getRange();
- if (isTouched)
- rewriteTypeOccurrence(range, estimate, requestor, currentRewrite, node, replacements, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
- else {
- final ASTNode result= NodeFinder.perform(node, range.getSourceRange());
- if (result != null)
- rewriteTypeOccurrence(estimate, currentRewrite, result, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
- }
- subMonitor.worked(10);
- }
- }
- }
- } finally {
- subMonitor.done();
- }
- }
- if (!isTouched) {
- final TextChange change= currentRewrite.createChange();
- if (change != null)
- manager.manage(unit, change);
- }
- } finally {
- monitor.done();
- }
- }
-
- protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final CompilationUnitRewrite sourceRewrite, final IJavaScriptUnit copy, final Set replacements, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.PullUpRefactoring_checking);
- final IType declaring= getDeclaringType();
- final IJavaScriptProject project= declaring.getJavaScriptProject();
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
- parser.createASTs(new IJavaScriptUnit[] { copy}, new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- try {
- final IType subType= (IType) JavaModelUtil.findInCompilationUnit(unit, declaring);
- final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(subType, node);
- if (subDeclaration != null) {
- final ITypeBinding subBinding= subDeclaration.resolveBinding();
- if (subBinding != null) {
- String name= null;
- ITypeBinding superBinding= null;
- final ITypeBinding[] superBindings= Bindings.getAllSuperTypes(subBinding);
- for (int index= 0; index < superBindings.length; index++) {
- name= superBindings[index].getName();
- if (name.startsWith(fDestinationType.getElementName()))
- superBinding= superBindings[index];
- }
- if (superBinding != null) {
- solveSuperTypeConstraints(unit, node, subType, subBinding, superBinding, new SubProgressMonitor(monitor, 80), status);
- if (!status.hasFatalError())
- rewriteTypeOccurrences(manager, this, sourceRewrite, unit, node, replacements, status, new SubProgressMonitor(monitor, 120));
- }
- }
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- }
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, new NullProgressMonitor());
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Sets the methods to declare abstract.
- *
- * @param methods
- * the methods to declare abstract
- */
- public void setAbstractMethods(final IFunction[] methods) {
- Assert.isNotNull(methods);
- fAbstractMethods= methods;
- }
-
- /**
- * Determines whether to create method stubs for non-implemented abstract
- * methods.
- *
- * @param create
- * <code>true</code> to create stubs, <code>false</code>
- * otherwise
- */
- public void setCreateMethodStubs(final boolean create) {
- fCreateMethodStubs= create;
- }
-
- /**
- * Sets the methods to delete
- *
- * @param methods
- * the methods to delete
- */
- public void setDeletedMethods(final IFunction[] methods) {
- Assert.isNotNull(methods);
- fDeletedMethods= methods;
- }
-
- /**
- * Sets the destination type.
- *
- * @param type
- * the destination type
- */
- public void setDestinationType(final IType type) {
- Assert.isNotNull(type);
- if (!type.equals(fDestinationType))
- fCachedDestinationTypeHierarchy= null;
- fDestinationType= type;
- }
-
- /**
- * Sets the members to move.
- *
- * @param members
- * the members to move
- */
- public void setMembersToMove(final IMember[] members) {
- Assert.isNotNull(members);
- fMembersToMove= (IMember[]) SourceReferenceUtil.sortByOffset(members);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoring.java
deleted file mode 100644
index 1e2a23b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoring.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Refactoring to push down members in a type hierarchy.
- */
-public final class PushDownRefactoring extends ProcessorBasedRefactoring implements IScriptableRefactoring {
-
- /** The refactoring processor to use */
- private final PushDownRefactoringProcessor fProcessor;
-
- /**
- * Creates a new push down refactoring.
- *
- * @param processor
- * the push down refactoring processor to use
- */
- public PushDownRefactoring(final PushDownRefactoringProcessor processor) {
- super(processor);
- fProcessor= processor;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringProcessor getProcessor() {
- return fProcessor;
- }
-
- /**
- * Returns the push down processor.
- *
- * @return the push down processor
- */
- public PushDownRefactoringProcessor getPushDownProcessor() {
- return (PushDownRefactoringProcessor) getProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, getProcessor().getIdentifier()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java
deleted file mode 100644
index 56a4abeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java
+++ /dev/null
@@ -1,993 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring processor for the push down refactoring.
- *
- *
- */
-public final class PushDownRefactoringProcessor extends HierarchyProcessor {
-
- public static class MemberActionInfo implements IMemberActionInfo {
-
- public static final int NO_ACTION= 2;
-
- public static final int PUSH_ABSTRACT_ACTION= 1;
-
- public static final int PUSH_DOWN_ACTION= 0;
-
- private static void assertValidAction(IMember member, int action) {
- if (member instanceof IFunction)
- Assert.isTrue(action == PUSH_ABSTRACT_ACTION || action == NO_ACTION || action == PUSH_DOWN_ACTION);
- else if (member instanceof IField)
- Assert.isTrue(action == NO_ACTION || action == PUSH_DOWN_ACTION);
- }
-
- public static MemberActionInfo create(IMember member, int action) {
- return new MemberActionInfo(member, action);
- }
-
- static IMember[] getMembers(MemberActionInfo[] infos) {
- IMember[] result= new IMember[infos.length];
- for (int i= 0; i < result.length; i++) {
- result[i]= infos[i].getMember();
- }
- return result;
- }
-
- private int fAction;
-
- private final IMember fMember;
-
- private MemberActionInfo(IMember member, int action) {
- assertValidAction(member, action);
- Assert.isTrue(member instanceof IField || member instanceof IFunction);
- fMember= member;
- fAction= action;
- }
-
- boolean copyJavadocToCopiesInSubclasses() {
- return isToBeDeletedFromDeclaringClass();
- }
-
- public int getAction() {
- return fAction;
- }
-
- public int[] getAvailableActions() {
- if (isFieldInfo())
- return new int[] { PUSH_DOWN_ACTION, NO_ACTION };
-
- return new int[] { PUSH_DOWN_ACTION, PUSH_ABSTRACT_ACTION, NO_ACTION };
- }
-
- public IMember getMember() {
- return fMember;
- }
-
- int getNewModifiersForCopyInSubclass(int oldModifiers) throws JavaScriptModelException {
- if (isFieldInfo())
- return oldModifiers;
- if (isToBeDeletedFromDeclaringClass())
- return oldModifiers;
- int modifiers= oldModifiers;
- if (isNewMethodToBeDeclaredAbstract()) {
- if (!JdtFlags.isPublic(fMember))
- modifiers= Modifier.PROTECTED | JdtFlags.clearAccessModifiers(modifiers);
- }
- return modifiers;
- }
-
- int getNewModifiersForOriginal(int oldModifiers) throws JavaScriptModelException {
- if (isFieldInfo())
- return oldModifiers;
- if (isToBeDeletedFromDeclaringClass())
- return oldModifiers;
- int modifiers= oldModifiers;
- if (isNewMethodToBeDeclaredAbstract()) {
- modifiers= JdtFlags.clearFlag(Modifier.FINAL | Modifier.NATIVE, oldModifiers);
- modifiers|= Modifier.ABSTRACT;
-
- if (!JdtFlags.isPublic(fMember))
- modifiers= Modifier.PROTECTED | JdtFlags.clearAccessModifiers(modifiers);
- }
- return modifiers;
- }
-
- public boolean isActive() {
- return getAction() != NO_ACTION;
- }
-
- public boolean isEditable() {
- if (isFieldInfo())
- return false;
- if (getAction() == MemberActionInfo.NO_ACTION)
- return false;
- return true;
- }
-
- boolean isFieldInfo() {
- return fMember instanceof IField;
- }
-
- boolean isNewMethodToBeDeclaredAbstract() throws JavaScriptModelException {
- return !isFieldInfo() && !JdtFlags.isAbstract(fMember) && fAction == PUSH_ABSTRACT_ACTION;
- }
-
- boolean isToBeCreatedInSubclassesOfDeclaringClass() {
- return fAction != NO_ACTION;
- }
-
- boolean isToBeDeletedFromDeclaringClass() {
- return isToBePushedDown();
- }
-
- public boolean isToBePushedDown() {
- return fAction == PUSH_DOWN_ACTION;
- }
-
- public void setAction(int action) {
- assertValidAction(fMember, action);
- if (isFieldInfo())
- Assert.isTrue(action != PUSH_ABSTRACT_ACTION);
- fAction= action;
- }
-
- }
-
- private static final String ATTRIBUTE_ABSTRACT= "abstract"; //$NON-NLS-1$
-
- private static final String ATTRIBUTE_PUSH= "push"; //$NON-NLS-1$
-
- /** The identifier of this processor */
- public static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.pushDownProcessor"; //$NON-NLS-1$
-
- /** The push down group category set */
- private static final GroupCategorySet SET_PUSH_DOWN= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.pushDown", //$NON-NLS-1$
- RefactoringCoreMessages.PushDownRefactoring_category_name, RefactoringCoreMessages.PushDownRefactoring_category_description));
-
- private static MemberActionInfo[] createInfosForAllPushableFieldsAndMethods(IType type) throws JavaScriptModelException {
- List result= new ArrayList();
- IMember[] pushableMembers= RefactoringAvailabilityTester.getPushDownMembers(type);
- for (int i= 0; i < pushableMembers.length; i++) {
- result.add(MemberActionInfo.create(pushableMembers[i], MemberActionInfo.NO_ACTION));
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- private static IMember[] getAbstractMembers(IMember[] members) throws JavaScriptModelException {
- List result= new ArrayList(members.length);
- for (int i= 0; i < members.length; i++) {
- IMember member= members[i];
- if (JdtFlags.isAbstract(member))
- result.add(member);
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- private static CompilationUnitRewrite getCompilationUnitRewrite(final Map rewrites, final IJavaScriptUnit unit) {
- Assert.isNotNull(rewrites);
- Assert.isNotNull(unit);
- CompilationUnitRewrite rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- if (rewrite == null) {
- rewrite= new CompilationUnitRewrite(unit);
- rewrites.put(unit, rewrite);
- }
- return rewrite;
- }
-
- private static IJavaScriptElement[] getReferencingElementsFromSameClass(IMember member, IProgressMonitor pm, RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(member);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.setFiltering(true, true);
- engine.setScope(SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member.getDeclaringType() }));
- engine.setStatus(status);
- engine.searchPattern(new SubProgressMonitor(pm, 1));
- SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
- Set result= new HashSet(3);
- for (int i= 0; i < groups.length; i++) {
- SearchResultGroup group= groups[i];
- SearchMatch[] results= group.getSearchResults();
- for (int j= 0; j < results.length; j++) {
- SearchMatch searchResult= results[i];
- result.add(SearchUtils.getEnclosingJavaElement(searchResult));
- }
- }
- return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- private ITypeHierarchy fCachedClassHierarchy;
-
- private MemberActionInfo[] fMemberInfos;
-
- /**
- * Creates a new push down refactoring processor.
- *
- * @param members
- * the members to pull up, or <code>null</code> if invoked by
- * scripting
- */
- public PushDownRefactoringProcessor(IMember[] members) {
- super(members, null, false);
- if (members != null) {
- final IType type= RefactoringAvailabilityTester.getTopLevelType(members);
- try {
- if (type != null && RefactoringAvailabilityTester.getPushDownMembers(type).length != 0) {
- fMembersToMove= new IMember[0];
- fCachedDeclaringType= type;
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
-
- private void addAllRequiredPushableMembers(List queue, IMember member, IProgressMonitor monitor) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_calculating_required, 2);
- IProgressMonitor sub= new SubProgressMonitor(monitor, 1);
- sub.beginTask(RefactoringCoreMessages.PushDownRefactoring_calculating_required, 2);
- IFunction[] requiredMethods= ReferenceFinderUtil.getMethodsReferencedIn(new IJavaScriptElement[] { member }, new SubProgressMonitor(sub, 1));
- sub= new SubProgressMonitor(sub, 1);
- sub.beginTask(RefactoringCoreMessages.PushDownRefactoring_calculating_required, requiredMethods.length);
- for (int index= 0; index < requiredMethods.length; index++) {
- IFunction method= requiredMethods[index];
- if (!MethodChecks.isVirtual(method) && (method.getDeclaringType().equals(getDeclaringType()) && !queue.contains(method) && RefactoringAvailabilityTester.isPushDownAvailable(method)))
- queue.add(method);
- }
- sub.done();
- IField[] requiredFields= ReferenceFinderUtil.getFieldsReferencedIn(new IJavaScriptElement[] { member }, new SubProgressMonitor(monitor, 1));
- for (int index= 0; index < requiredFields.length; index++) {
- IField field= requiredFields[index];
- if (field.getDeclaringType().equals(getDeclaringType()) && !queue.contains(field) && RefactoringAvailabilityTester.isPushDownAvailable(field))
- queue.add(field);
- }
- monitor.done();
- }
-
- private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown);
- for (int index= 0; index < destinationClassesForAbstract.length; index++) {
- result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, destinationClassesForAbstract[index]));
- }
- return result;
- }
-
- private RefactoringStatus checkAccessedFields(IType[] subclasses, IProgressMonitor pm) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
- List pushedDownList= Arrays.asList(membersToPushDown);
- IField[] accessedFields= ReferenceFinderUtil.getFieldsReferencedIn(membersToPushDown, pm);
- for (int i= 0; i < subclasses.length; i++) {
- IType targetClass= subclasses[i];
- ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
- for (int j= 0; j < accessedFields.length; j++) {
- IField field= accessedFields[j];
- boolean isAccessible= pushedDownList.contains(field) || canBeAccessedFrom(field, targetClass, targetSupertypes);
- if (!isAccessible) {
- String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_field_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(field, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(targetClass, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- result.addError(message, JavaStatusContext.create(field));
- }
- }
- }
- pm.done();
- return result;
- }
-
- private RefactoringStatus checkAccessedMethods(IType[] subclasses, IProgressMonitor pm) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
- List pushedDownList= Arrays.asList(membersToPushDown);
- IFunction[] accessedMethods= ReferenceFinderUtil.getMethodsReferencedIn(membersToPushDown, pm);
- for (int index= 0; index < subclasses.length; index++) {
- IType targetClass= subclasses[index];
- ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
- for (int offset= 0; offset < accessedMethods.length; offset++) {
- IFunction method= accessedMethods[offset];
- boolean isAccessible= pushedDownList.contains(method) || canBeAccessedFrom(method, targetClass, targetSupertypes);
- if (!isAccessible) {
- String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_method_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(method, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(targetClass, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- result.addError(message, JavaStatusContext.create(method));
- }
- }
- }
- pm.done();
- return result;
- }
-
- private RefactoringStatus checkAccessedTypes(IType[] subclasses, IProgressMonitor pm) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- IType[] accessedTypes= getTypesReferencedInMovedMembers(pm);
- for (int index= 0; index < subclasses.length; index++) {
- IType targetClass= subclasses[index];
- ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
- for (int offset= 0; offset < accessedTypes.length; offset++) {
- IType type= accessedTypes[offset];
- if (!canBeAccessedFrom(type, targetClass, targetSupertypes)) {
- String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_type_not_accessible, new String[] { JavaScriptElementLabels.getTextLabel(type, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getTextLabel(targetClass, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- result.addError(message, JavaStatusContext.create(type));
- }
- }
- }
- pm.done();
- return result;
- }
-
- private RefactoringStatus checkElementsAccessedByModifiedMembers(IProgressMonitor pm) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- pm.beginTask(RefactoringCoreMessages.PushDownRefactoring_check_references, 3);
- IType[] subclasses= getAbstractDestinations(new SubProgressMonitor(pm, 1));
- result.merge(checkAccessedTypes(subclasses, new SubProgressMonitor(pm, 1)));
- result.merge(checkAccessedFields(subclasses, new SubProgressMonitor(pm, 1)));
- result.merge(checkAccessedMethods(subclasses, new SubProgressMonitor(pm, 1)));
- pm.done();
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor monitor, CheckConditionsContext context) throws CoreException, OperationCanceledException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 5);
- clearCaches();
- IJavaScriptUnit unit= getDeclaringType().getJavaScriptUnit();
- if (fLayer)
- unit= unit.findWorkingCopy(fOwner);
- resetWorkingCopies(unit);
- final RefactoringStatus result= new RefactoringStatus();
- result.merge(checkMembersInDestinationClasses(new SubProgressMonitor(monitor, 1)));
- result.merge(checkElementsAccessedByModifiedMembers(new SubProgressMonitor(monitor, 1)));
- result.merge(checkReferencesToPushedDownMembers(new SubProgressMonitor(monitor, 1)));
- if (!JdtFlags.isAbstract(getDeclaringType()) && getAbstractDeclarationInfos().length != 0)
- result.merge(checkConstructorCalls(getDeclaringType(), new SubProgressMonitor(monitor, 1)));
- else
- monitor.worked(1);
- if (result.hasFatalError())
- return result;
- List members= new ArrayList(fMemberInfos.length);
- for (int index= 0; index < fMemberInfos.length; index++) {
- if (fMemberInfos[index].getAction() != MemberActionInfo.NO_ACTION)
- members.add(fMemberInfos[index].getMember());
- }
- fMembersToMove= (IMember[]) members.toArray(new IMember[members.size()]);
- fChangeManager= createChangeManager(new SubProgressMonitor(monitor, 1), result);
- if (result.hasFatalError())
- return result;
- result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), getRefactoring().getValidationContext()));
- return result;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 1);
- RefactoringStatus status= new RefactoringStatus();
- status.merge(checkPossibleSubclasses(new SubProgressMonitor(monitor, 1)));
- if (status.hasFatalError())
- return status;
- status.merge(checkDeclaringType(new SubProgressMonitor(monitor, 1)));
- if (status.hasFatalError())
- return status;
- status.merge(checkIfMembersExist());
- if (status.hasFatalError())
- return status;
- fMemberInfos= createInfosForAllPushableFieldsAndMethods(getDeclaringType());
- List list= Arrays.asList(fMembersToMove);
- for (int offset= 0; offset < fMemberInfos.length; offset++) {
- MemberActionInfo info= fMemberInfos[offset];
- if (list.contains(info.getMember()))
- info.setAction(MemberActionInfo.PUSH_DOWN_ACTION);
- }
- return status;
- } finally {
- monitor.done();
- }
- }
-
- private RefactoringStatus checkMembersInDestinationClasses(IProgressMonitor monitor) throws JavaScriptModelException {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 2);
- RefactoringStatus result= new RefactoringStatus();
- IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
-
- IType[] destinationClassesForNonAbstract= getAbstractDestinations(new SubProgressMonitor(monitor, 1));
- result.merge(checkNonAbstractMembersInDestinationClasses(membersToPushDown, destinationClassesForNonAbstract));
- List list= Arrays.asList(getAbstractMembers(getAbstractDestinations(new SubProgressMonitor(monitor, 1))));
-
- IType[] destinationClassesForAbstract= (IType[]) list.toArray(new IType[list.size()]);
- result.merge(checkAbstractMembersInDestinationClasses(membersToPushDown, destinationClassesForAbstract));
- monitor.done();
- return result;
- }
-
- private RefactoringStatus checkNonAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForNonAbstract) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- List list= new ArrayList(); // Arrays.asList does not support removing
- list.addAll(Arrays.asList(membersToPushDown));
- list.removeAll(Arrays.asList(getAbstractMembers(membersToPushDown)));
- IMember[] nonAbstractMembersToPushDown= (IMember[]) list.toArray(new IMember[list.size()]);
- for (int i= 0; i < destinationClassesForNonAbstract.length; i++) {
- result.merge(MemberCheckUtil.checkMembersInDestinationType(nonAbstractMembersToPushDown, destinationClassesForNonAbstract[i]));
- }
- return result;
- }
-
- private RefactoringStatus checkPossibleSubclasses(IProgressMonitor pm) throws JavaScriptModelException {
- IType[] modifiableSubclasses= getAbstractDestinations(pm);
- if (modifiableSubclasses.length == 0) {
- String msg= Messages.format(RefactoringCoreMessages.PushDownRefactoring_no_subclasses, new String[] { JavaScriptElementLabels.getTextLabel(getDeclaringType(), JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- return RefactoringStatus.createFatalErrorStatus(msg);
- }
- return new RefactoringStatus();
- }
-
- private RefactoringStatus checkReferencesToPushedDownMembers(IProgressMonitor monitor) throws JavaScriptModelException {
- List fields= new ArrayList(fMemberInfos.length);
- for (int index= 0; index < fMemberInfos.length; index++) {
- MemberActionInfo info= fMemberInfos[index];
- if (info.isToBePushedDown())
- fields.add(info.getMember());
- }
- IMember[] membersToPush= (IMember[]) fields.toArray(new IMember[fields.size()]);
- RefactoringStatus result= new RefactoringStatus();
- List movedMembers= Arrays.asList(MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass()));
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_check_references, membersToPush.length);
- for (int index= 0; index < membersToPush.length; index++) {
- IMember member= membersToPush[index];
- String label= createLabel(member);
- IJavaScriptElement[] referencing= getReferencingElementsFromSameClass(member, new SubProgressMonitor(monitor, 1), result);
- for (int offset= 0; offset < referencing.length; offset++) {
- IJavaScriptElement element= referencing[offset];
- if (movedMembers.contains(element))
- continue;
- if (!(element instanceof IMember))
- continue;
- IMember referencingMember= (IMember) element;
- Object[] keys= { label, createLabel(referencingMember) };
- String msg= Messages.format(RefactoringCoreMessages.PushDownRefactoring_referenced, keys);
- result.addError(msg, JavaStatusContext.create(referencingMember));
- }
- }
- monitor.done();
- return result;
- }
-
- public void computeAdditionalRequiredMembersToPushDown(IProgressMonitor monitor) throws JavaScriptModelException {
- List list= Arrays.asList(getAdditionalRequiredMembers(monitor));
- for (int index= 0; index < fMemberInfos.length; index++) {
- MemberActionInfo info= fMemberInfos[index];
- if (list.contains(info.getMember()))
- info.setAction(MemberActionInfo.PUSH_DOWN_ACTION);
- }
- }
-
- private void copyBodyOfPushedDownMethod(ASTRewrite targetRewrite, IFunction method, FunctionDeclaration oldMethod, FunctionDeclaration newMethod, TypeVariableMaplet[] mapping) throws JavaScriptModelException {
- Block body= oldMethod.getBody();
- if (body == null) {
- newMethod.setBody(null);
- return;
- }
- try {
- final IDocument document= new Document(method.getJavaScriptUnit().getBuffer().getContents());
- final ASTRewrite rewriter= ASTRewrite.create(body.getAST());
- final ITrackedNodePosition position= rewriter.track(body);
- body.accept(new TypeVariableMapper(rewriter, mapping));
- rewriter.rewriteAST(document, getDeclaringType().getJavaScriptUnit().getJavaScriptProject().getOptions(true)).apply(document, TextEdit.NONE);
- String content= document.get(position.getStartPosition(), position.getLength());
- String[] lines= Strings.convertIntoLines(content);
- Strings.trimIndentation(lines, method.getJavaScriptProject(), false);
- content= Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
- newMethod.setBody((Block) targetRewrite.createStringPlaceholder(content, ASTNode.BLOCK));
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
-
- private void copyMembers(Collection adjustors, Map adjustments, Map rewrites, RefactoringStatus status, MemberActionInfo[] infos, IType[] destinations, CompilationUnitRewrite sourceRewriter, CompilationUnitRewrite unitRewriter, IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 1);
- IType type= null;
- TypeVariableMaplet[] mapping= null;
- for (int index= 0; index < destinations.length; index++) {
- type= destinations[index];
- if (unitRewriter.getCu().equals(type.getJavaScriptUnit())) {
- IMember member= null;
- MemberVisibilityAdjustor adjustor= null;
- AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, unitRewriter.getRoot());
- for (int offset= infos.length - 1; offset >= 0; offset--) {
- member= infos[offset].getMember();
- adjustor= new MemberVisibilityAdjustor(type, member);
- if (infos[offset].isNewMethodToBeDeclaredAbstract())
- adjustor.setIncoming(false);
- adjustor.setRewrite(sourceRewriter.getASTRewrite(), sourceRewriter.getRoot());
- adjustor.setRewrites(rewrites);
-
- // TW: set to error if bug 78387 is fixed
- adjustor.setFailureSeverity(RefactoringStatus.WARNING);
-
- adjustor.setStatus(status);
- adjustor.setAdjustments(adjustments);
- adjustor.adjustVisibility(new SubProgressMonitor(monitor, 1));
- adjustments.remove(member);
- adjustors.add(adjustor);
- status.merge(checkProjectCompliance(getCompilationUnitRewrite(rewrites, getDeclaringType().getJavaScriptUnit()), type, new IMember[] {infos[offset].getMember()}));
- if (infos[offset].isFieldInfo()) {
- final VariableDeclarationFragment oldField= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) infos[offset].getMember(), sourceRewriter.getRoot());
- if (oldField != null) {
- FieldDeclaration newField= createNewFieldDeclarationNode(infos[offset], sourceRewriter.getRoot(), mapping, unitRewriter.getASTRewrite(), oldField);
- unitRewriter.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newField, ASTNodes.getInsertionIndex(newField, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN));
- ImportRewriteUtil.addImports(unitRewriter, oldField.getParent(), new HashMap(), new HashMap(), false);
- }
- } else {
- final FunctionDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode((IFunction) infos[offset].getMember(), sourceRewriter.getRoot());
- if (oldMethod != null) {
- FunctionDeclaration newMethod= createNewMethodDeclarationNode(infos[offset], sourceRewriter.getRoot(), mapping, unitRewriter, oldMethod);
- unitRewriter.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, declaration.bodyDeclarations()), unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_add_member, SET_PUSH_DOWN));
- ImportRewriteUtil.addImports(unitRewriter, oldMethod, new HashMap(), new HashMap(), false);
- }
- }
- }
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
- try {
- final Map arguments= new HashMap();
- String project= null;
- final IType declaring= getDeclaringType();
- final IJavaScriptProject javaProject= declaring.getJavaScriptProject();
- if (javaProject != null)
- project= javaProject.getElementName();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- try {
- if (declaring.isLocal() || declaring.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String description= fMembersToMove.length == 1 ? Messages.format(RefactoringCoreMessages.PushDownRefactoring_descriptor_description_short_multi, fMembersToMove[0].getElementName()) : RefactoringCoreMessages.PushDownRefactoring_descriptor_description_short;
- final String header= fMembersToMove.length == 1 ? Messages.format(RefactoringCoreMessages.PushDownRefactoring_descriptor_description_full, new String[] { JavaScriptElementLabels.getElementLabel(fMembersToMove[0], JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) }) : Messages.format(RefactoringCoreMessages.PushDownRefactoring_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(declaring, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
- final String[] settings= new String[fMembersToMove.length];
- for (int index= 0; index < settings.length; index++)
- settings[index]= JavaScriptElementLabels.getElementLabel(fMembersToMove[index], JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.PushDownRefactoring_pushed_members_pattern, settings));
- addSuperTypeSettings(comment, true);
- final JDTRefactoringDescriptor descriptor= new JDTRefactoringDescriptor(IJavaScriptRefactorings.PUSH_DOWN, project, description, comment.asString(), arguments, flags);
- if (fCachedDeclaringType != null)
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, descriptor.elementToHandle(fCachedDeclaringType));
- for (int index= 0; index < fMembersToMove.length; index++) {
- arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1), descriptor.elementToHandle(fMembersToMove[index]));
- for (int offset= 0; offset < fMemberInfos.length; offset++) {
- if (fMemberInfos[offset].getMember().equals(fMembersToMove[index])) {
- switch (fMemberInfos[offset].getAction()) {
- case MemberActionInfo.PUSH_ABSTRACT_ACTION:
- arguments.put(ATTRIBUTE_ABSTRACT + (index + 1), Boolean.valueOf(true).toString());
- break;
- case MemberActionInfo.PUSH_DOWN_ACTION:
- arguments.put(ATTRIBUTE_PUSH + (index + 1), Boolean.valueOf(true).toString());
- break;
- }
- }
- }
- }
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.PushDownRefactoring_change_name, fChangeManager.getAllChanges());
- } finally {
- pm.done();
- clearCaches();
- }
- }
-
- private TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- try {
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 7);
- final IJavaScriptUnit source= getDeclaringType().getJavaScriptUnit();
- final CompilationUnitRewrite sourceRewriter= new CompilationUnitRewrite(source);
- final Map rewrites= new HashMap(2);
- rewrites.put(source, sourceRewriter);
- IType[] types= getHierarchyOfDeclaringClass(new SubProgressMonitor(monitor, 1)).getSubclasses(getDeclaringType());
- final Set result= new HashSet(types.length + 1);
- for (int index= 0; index < types.length; index++)
- result.add(types[index].getJavaScriptUnit());
- result.add(source);
- final Map adjustments= new HashMap();
- final List adjustors= new ArrayList();
- final IJavaScriptUnit[] units= (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- IJavaScriptUnit unit= null;
- CompilationUnitRewrite rewrite= null;
- final IProgressMonitor sub= new SubProgressMonitor(monitor, 4);
- try {
- sub.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, units.length * 4);
- for (int index= 0; index < units.length; index++) {
- unit= units[index];
- rewrite= getCompilationUnitRewrite(rewrites, unit);
- if (unit.equals(sourceRewriter.getCu())) {
- final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(getDeclaringType(), rewrite.getRoot());
- if (!JdtFlags.isAbstract(getDeclaringType()) && getAbstractDeclarationInfos().length != 0)
- ModifierRewrite.create(rewrite.getASTRewrite(), declaration).setModifiers((Modifier.ABSTRACT | declaration.getModifiers()), rewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PushDownRefactoring_make_abstract, SET_PUSH_DOWN));
- deleteDeclarationNodes(sourceRewriter, false, rewrite, Arrays.asList(getDeletableMembers()), SET_PUSH_DOWN);
- MemberActionInfo[] methods= getAbstractDeclarationInfos();
- for (int offset= 0; offset < methods.length; offset++)
- declareMethodAbstract(methods[offset], sourceRewriter, rewrite);
- }
- final IMember[] members= getAbstractMembers(getAbstractDestinations(new SubProgressMonitor(monitor, 1)));
- final IType[] classes= new IType[members.length];
- for (int offset= 0; offset < members.length; offset++)
- classes[offset]= (IType) members[offset];
- copyMembers(adjustors, adjustments, rewrites, status, getAbstractMemberInfos(), classes, sourceRewriter, rewrite, sub);
- copyMembers(adjustors, adjustments, rewrites, status, getEffectedMemberInfos(), getAbstractDestinations(new SubProgressMonitor(monitor, 1)), sourceRewriter, rewrite, sub);
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
- } finally {
- sub.done();
- }
- if (!adjustors.isEmpty() && !adjustments.isEmpty()) {
- final MemberVisibilityAdjustor adjustor= (MemberVisibilityAdjustor) adjustors.get(0);
- adjustor.rewriteVisibility(new SubProgressMonitor(monitor, 1));
- }
- final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
- for (final Iterator iterator= rewrites.keySet().iterator(); iterator.hasNext();) {
- unit= (IJavaScriptUnit) iterator.next();
- rewrite= (CompilationUnitRewrite) rewrites.get(unit);
- if (rewrite != null)
- manager.manage(unit, rewrite.createChange());
- }
- return manager;
- } finally {
- monitor.done();
- }
- }
-
- private FieldDeclaration createNewFieldDeclarationNode(MemberActionInfo info, JavaScriptUnit declaringCuNode, TypeVariableMaplet[] mapping, ASTRewrite rewrite, VariableDeclarationFragment oldFieldFragment) throws JavaScriptModelException {
- Assert.isTrue(info.isFieldInfo());
- IField field= (IField) info.getMember();
- AST ast= rewrite.getAST();
- VariableDeclarationFragment newFragment= ast.newVariableDeclarationFragment();
- newFragment.setExtraDimensions(oldFieldFragment.getExtraDimensions());
- Expression initializer= oldFieldFragment.getInitializer();
- if (initializer != null) {
- Expression newInitializer= null;
- if (mapping.length > 0)
- newInitializer= createPlaceholderForExpression(initializer, field.getJavaScriptUnit(), mapping, rewrite);
- else
- newInitializer= createPlaceholderForExpression(initializer, field.getJavaScriptUnit(), rewrite);
- newFragment.setInitializer(newInitializer);
- }
- newFragment.setName(ast.newSimpleName(oldFieldFragment.getName().getIdentifier()));
- FieldDeclaration newField= ast.newFieldDeclaration(newFragment);
- FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, declaringCuNode);
- if (info.copyJavadocToCopiesInSubclasses())
- copyJavadocNode(rewrite, field, oldField, newField);
- copyAnnotations(oldField, newField);
- newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldField.getModifiers())));
- Type oldType= oldField.getType();
- IJavaScriptUnit cu= field.getJavaScriptUnit();
- Type newType= null;
- if (mapping.length > 0) {
- newType= createPlaceholderForType(oldType, cu, mapping, rewrite);
- } else
- newType= createPlaceholderForType(oldType, cu, rewrite);
- newField.setType(newType);
- return newField;
- }
-
- private FunctionDeclaration createNewMethodDeclarationNode(MemberActionInfo info, JavaScriptUnit declaringCuNode, TypeVariableMaplet[] mapping, CompilationUnitRewrite rewriter, FunctionDeclaration oldMethod) throws JavaScriptModelException {
- Assert.isTrue(!info.isFieldInfo());
- IFunction method= (IFunction) info.getMember();
- ASTRewrite rewrite= rewriter.getASTRewrite();
- AST ast= rewrite.getAST();
- FunctionDeclaration newMethod= ast.newFunctionDeclaration();
- copyBodyOfPushedDownMethod(rewrite, method, oldMethod, newMethod, mapping);
- newMethod.setConstructor(oldMethod.isConstructor());
- newMethod.setExtraDimensions(oldMethod.getExtraDimensions());
- if (info.copyJavadocToCopiesInSubclasses())
- copyJavadocNode(rewrite, method, oldMethod, newMethod);
- final IJavaScriptProject project= rewriter.getCu().getJavaScriptProject();
- copyAnnotations(oldMethod, newMethod);
- newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldMethod.getModifiers())));
- newMethod.setName(ast.newSimpleName(oldMethod.getName().getIdentifier()));
- copyReturnType(rewrite, method.getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyParameters(rewrite, method.getJavaScriptUnit(), oldMethod, newMethod, mapping);
- copyThrownExceptions(oldMethod, newMethod);
- return newMethod;
- }
-
- private void declareMethodAbstract(MemberActionInfo info, CompilationUnitRewrite sourceRewrite, CompilationUnitRewrite unitRewrite) throws JavaScriptModelException {
- Assert.isTrue(!info.isFieldInfo());
- IFunction method= (IFunction) info.getMember();
- if (JdtFlags.isAbstract(method))
- return;
- final FunctionDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(method, sourceRewrite.getRoot());
- unitRewrite.getASTRewrite().remove(declaration.getBody(), null);
- sourceRewrite.getImportRemover().registerRemovedNode(declaration.getBody());
- ModifierRewrite.create(unitRewrite.getASTRewrite(), declaration).setModifiers(info.getNewModifiersForOriginal(declaration.getModifiers()), null);
- }
-
- private MemberActionInfo[] getAbstractDeclarationInfos() throws JavaScriptModelException {
- List result= new ArrayList(fMemberInfos.length);
- for (int index= 0; index < fMemberInfos.length; index++) {
- MemberActionInfo info= fMemberInfos[index];
- if (info.isNewMethodToBeDeclaredAbstract())
- result.add(info);
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- private IType[] getAbstractDestinations(IProgressMonitor monitor) throws JavaScriptModelException {
- IType[] allDirectSubclasses= getHierarchyOfDeclaringClass(monitor).getSubclasses(getDeclaringType());
- List result= new ArrayList(allDirectSubclasses.length);
- for (int index= 0; index < allDirectSubclasses.length; index++) {
- IType subclass= allDirectSubclasses[index];
- if (subclass.exists() && !subclass.isBinary() && !subclass.isReadOnly() && subclass.getJavaScriptUnit() != null && subclass.isStructureKnown())
- result.add(subclass);
- }
- return (IType[]) result.toArray(new IType[result.size()]);
- }
-
- private MemberActionInfo[] getAbstractMemberInfos() throws JavaScriptModelException {
- List result= new ArrayList(fMemberInfos.length);
- for (int index= 0; index < fMemberInfos.length; index++) {
- MemberActionInfo info= fMemberInfos[index];
- if (info.isToBeCreatedInSubclassesOfDeclaringClass() && JdtFlags.isAbstract(info.getMember()))
- result.add(info);
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- public IMember[] getAdditionalRequiredMembers(IProgressMonitor monitor) throws JavaScriptModelException {
- IMember[] members= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
- monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_calculating_required, members.length);// not
- // true,
- // but
- // not
- // easy
- // to
- // give
- // anything
- // better
- List queue= new ArrayList(members.length);
- queue.addAll(Arrays.asList(members));
- if (queue.isEmpty())
- return new IMember[0];
- int i= 0;
- IMember current;
- do {
- current= (IMember) queue.get(i);
- addAllRequiredPushableMembers(queue, current, new SubProgressMonitor(monitor, 1));
- i++;
- if (queue.size() == i)
- current= null;
- } while (current != null);
- queue.removeAll(Arrays.asList(members));// report only additional
- return (IMember[]) queue.toArray(new IMember[queue.size()]);
- }
-
- private IMember[] getDeletableMembers() {
- List result= new ArrayList(fMemberInfos.length);
- for (int i= 0; i < fMemberInfos.length; i++) {
- MemberActionInfo info= fMemberInfos[i];
- if (info.isToBeDeletedFromDeclaringClass())
- result.add(info.getMember());
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- private MemberActionInfo[] getEffectedMemberInfos() throws JavaScriptModelException {
- List result= new ArrayList(fMemberInfos.length);
- for (int i= 0; i < fMemberInfos.length; i++) {
- MemberActionInfo info= fMemberInfos[i];
- if (info.isToBeCreatedInSubclassesOfDeclaringClass() && !JdtFlags.isAbstract(info.getMember()))
- result.add(info);
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getElements() {
- return fMembersToMove;
- }
-
- private ITypeHierarchy getHierarchyOfDeclaringClass(IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- if (fCachedClassHierarchy != null)
- return fCachedClassHierarchy;
- fCachedClassHierarchy= getDeclaringType().newTypeHierarchy(monitor);
- return fCachedClassHierarchy;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String getIdentifier() {
- return IDENTIFIER;
- }
-
- private MemberActionInfo[] getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass() throws JavaScriptModelException {
- MemberActionInfo[] abs= getAbstractMemberInfos();
- MemberActionInfo[] nonabs= getEffectedMemberInfos();
- List result= new ArrayList(abs.length + nonabs.length);
- result.addAll(Arrays.asList(abs));
- result.addAll(Arrays.asList(nonabs));
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- public MemberActionInfo[] getMemberActionInfos() {
- return fMemberInfos;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getProcessorName() {
- return RefactoringCoreMessages.PushDownRefactoring_name;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus initialize(RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PUSH_DOWN);
- else
- fCachedDeclaringType= (IType) element;
- }
- int count= 1;
- final List elements= new ArrayList();
- final List infos= new ArrayList();
- String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- final RefactoringStatus status= new RefactoringStatus();
- while ((handle= extended.getAttribute(attribute)) != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists())
- status.merge(ScriptableRefactoring.createInputWarningStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.PUSH_DOWN));
- else
- elements.add(element);
- if (extended.getAttribute(ATTRIBUTE_ABSTRACT + count) != null)
- infos.add(MemberActionInfo.create((IMember) element, MemberActionInfo.PUSH_ABSTRACT_ACTION));
- else if (extended.getAttribute(ATTRIBUTE_PUSH + count) != null)
- infos.add(MemberActionInfo.create((IMember) element, MemberActionInfo.PUSH_DOWN_ACTION));
- else
- infos.add(MemberActionInfo.create((IMember) element, MemberActionInfo.NO_ACTION));
- count++;
- attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- }
- fMembersToMove= (IMember[]) elements.toArray(new IMember[elements.size()]);
- fMemberInfos= (MemberActionInfo[]) infos.toArray(new MemberActionInfo[infos.size()]);
- if (!status.isOK())
- return status;
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isApplicable() throws CoreException {
- return RefactoringAvailabilityTester.isPushDownAvailable(fMembersToMove);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final IJavaScriptUnit unit, final JavaScriptUnit node, final Set replacements, final IProgressMonitor monitor) throws CoreException {
- // Not needed
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceAnalyzer.java
deleted file mode 100644
index b7704fed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceAnalyzer.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionRef;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-
-/**
- * Updates references to moved static members.
- * Accepts <code>JavaScriptUnit</code>s.
- */
-/* package */ class ReferenceAnalyzer extends MoveStaticMemberAnalyzer {
-
- public ReferenceAnalyzer(CompilationUnitRewrite cuRewrite, IBinding[] members, ITypeBinding target, ITypeBinding source) {
- super(cuRewrite, members, source, target);
- }
-
- public boolean needsTargetImport() {
- return fNeedsImport;
- }
-
- //---- Moved members are handled by the MovedMemberAnalyzer --------------
-
- public boolean visit(TypeDeclaration node) {
- ITypeBinding binding= node.resolveBinding();
- if (binding != null) {
- binding= binding.getTypeDeclaration();
- if (isMovedMember(binding))
- return false;
- }
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- if (isMovedMember(node.resolveBinding()))
- return false;
- return super.visit(node);
- }
-
- public boolean visit(FieldDeclaration node) {
- //see bug 42383: multiple VariableDeclarationFragments not supported:
- VariableDeclarationFragment singleFragment= (VariableDeclarationFragment) node.fragments().get(0);
- if (isMovedMember(singleFragment.resolveBinding()))
- return false; // don't update javadoc of moved field here
- return super.visit(node);
- }
-
- public boolean visit(FunctionDeclaration node) {
- if (isMovedMember(node.resolveBinding()))
- return false;
- return super.visit(node);
- }
-
-
- //---- types and fields --------------------------
-
- public boolean visit(SimpleName node) {
- if (! node.isDeclaration() && isMovedMember(node.resolveBinding()) && ! isProcessed(node))
- rewrite(node, fTarget);
- return false;
- }
-
- public boolean visit(QualifiedName node) {
- if (isMovedMember(node.resolveBinding())) {
- if (node.getParent() instanceof ImportDeclaration) {
- ITypeBinding typeBinding= node.resolveTypeBinding();
- if (typeBinding != null)
- fCuRewrite.getImportRewrite().removeImport(typeBinding.getQualifiedName());
- String imp= fCuRewrite.getImportRewrite().addImport(fTarget.getQualifiedName() + '.' + node.getName().getIdentifier());
- fCuRewrite.getImportRemover().registerAddedImport(imp);
- } else {
- rewrite(node, fTarget);
- }
- return false;
- } else {
- return super.visit(node);
- }
- }
-
- public boolean visit(FieldAccess node) {
- if (isMovedMember(node.resolveFieldBinding()))
- rewrite(node, fTarget);
- return super.visit(node);
- }
-
- //---- method invocations ----------------------------------
-
- public boolean visit(FunctionInvocation node) {
- IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null) {
- binding= binding.getMethodDeclaration();
- if (isMovedMember(binding))
- rewrite(node, fTarget);
- }
- return super.visit(node);
- }
-
- //---- javadoc references ----------------------------------
-
- public boolean visit(MemberRef node) {
- if (isMovedMember(node.resolveBinding()))
- rewrite(node, fTarget);
- return false;
- }
-
- public boolean visit(FunctionRef node) {
- if (isMovedMember(node.resolveBinding()))
- rewrite(node, fTarget);
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java
deleted file mode 100644
index f41d2431..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.CollectingSearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-
-public class ReferenceFinderUtil {
-
- private ReferenceFinderUtil(){
- //no instances
- }
-
- //----- referenced types -
-
- public static IType[] getTypesReferencedIn(IJavaScriptElement[] elements, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getTypeReferencesIn(elements, null, pm);
- Set referencedTypes= extractElements(results, IJavaScriptElement.TYPE);
- return (IType[]) referencedTypes.toArray(new IType[referencedTypes.size()]);
- }
-
- public static IType[] getTypesReferencedIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getTypeReferencesIn(elements, owner, pm);
- Set referencedTypes= extractElements(results, IJavaScriptElement.TYPE);
- return (IType[]) referencedTypes.toArray(new IType[referencedTypes.size()]);
- }
-
- private static SearchMatch[] getTypeReferencesIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- List referencedTypes= new ArrayList();
- pm.beginTask("", elements.length); //$NON-NLS-1$
- for (int i = 0; i < elements.length; i++) {
- referencedTypes.addAll(getTypeReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
- }
- pm.done();
- return (SearchMatch[]) referencedTypes.toArray(new SearchMatch[referencedTypes.size()]);
- }
-
- private static List getTypeReferencesIn(IJavaScriptElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- CollectingSearchRequestor requestor= new CollectingSearchRequestor();
- SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine();
- engine.searchDeclarationsOfReferencedTypes(element, requestor, pm);
- return requestor.getResults();
- }
-
- //----- referenced fields ----
-
- public static IField[] getFieldsReferencedIn(IJavaScriptElement[] elements, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getFieldReferencesIn(elements, null, pm);
- Set referencedFields= extractElements(results, IJavaScriptElement.FIELD);
- return (IField[]) referencedFields.toArray(new IField[referencedFields.size()]);
- }
-
- public static IField[] getFieldsReferencedIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getFieldReferencesIn(elements, owner, pm);
- Set referencedFields= extractElements(results, IJavaScriptElement.FIELD);
- return (IField[]) referencedFields.toArray(new IField[referencedFields.size()]);
- }
-
- private static SearchMatch[] getFieldReferencesIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- List referencedFields= new ArrayList();
- pm.beginTask("", elements.length); //$NON-NLS-1$
- for (int i = 0; i < elements.length; i++) {
- referencedFields.addAll(getFieldReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
- }
- pm.done();
- return (SearchMatch[]) referencedFields.toArray(new SearchMatch[referencedFields.size()]);
- }
-
- private static List getFieldReferencesIn(IJavaScriptElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- CollectingSearchRequestor requestor= new CollectingSearchRequestor();
- SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine();
- engine.searchDeclarationsOfAccessedFields(element, requestor, pm);
- return requestor.getResults();
- }
-
- //----- referenced methods ----
-
- public static IFunction[] getMethodsReferencedIn(IJavaScriptElement[] elements, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getMethodReferencesIn(elements, null, pm);
- Set referencedMethods= extractElements(results, IJavaScriptElement.METHOD);
- return (IFunction[]) referencedMethods.toArray(new IFunction[referencedMethods.size()]);
- }
-
- public static IFunction[] getMethodsReferencedIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- SearchMatch[] results= getMethodReferencesIn(elements, owner, pm);
- Set referencedMethods= extractElements(results, IJavaScriptElement.METHOD);
- return (IFunction[]) referencedMethods.toArray(new IFunction[referencedMethods.size()]);
- }
-
- private static SearchMatch[] getMethodReferencesIn(IJavaScriptElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- List referencedMethods= new ArrayList();
- pm.beginTask("", elements.length); //$NON-NLS-1$
- for (int i = 0; i < elements.length; i++) {
- referencedMethods.addAll(getMethodReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
- }
- pm.done();
- return (SearchMatch[]) referencedMethods.toArray(new SearchMatch[referencedMethods.size()]);
- }
-
- private static List getMethodReferencesIn(IJavaScriptElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaScriptModelException {
- CollectingSearchRequestor requestor= new CollectingSearchRequestor();
- SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine();
- engine.searchDeclarationsOfSentMessages(element, requestor, pm);
- return requestor.getResults();
- }
-
- public static ITypeBinding[] getTypesReferencedInDeclarations(FunctionDeclaration[] methods) {
- Set typesUsed= new HashSet();
- for (int i= 0; i < methods.length; i++) {
- typesUsed.addAll(getTypesUsedInDeclaration(methods[i]));
- }
- return (ITypeBinding[]) typesUsed.toArray(new ITypeBinding[typesUsed.size()]);
- }
-
- //set of ITypeBindings
- public static Set getTypesUsedInDeclaration(FunctionDeclaration methodDeclaration) {
- if (methodDeclaration == null)
- return new HashSet(0);
- Set result= new HashSet();
- ITypeBinding binding= null;
- Type returnType= methodDeclaration.getReturnType2();
- if (returnType != null) {
- binding = returnType.resolveBinding();
- if (binding != null)
- result.add(binding);
- }
-
- for (Iterator iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
- binding = ((SingleVariableDeclaration)iter.next()).getType().resolveBinding();
- if (binding != null)
- result.add(binding);
- }
-
- for (Iterator iter= methodDeclaration.thrownExceptions().iterator(); iter.hasNext();) {
- binding = ((Name)iter.next()).resolveTypeBinding();
- if (binding != null)
- result.add(binding);
- }
- return result;
- }
-
- /// private helpers
- private static Set extractElements(SearchMatch[] searchResults, int elementType) {
- Set elements= new HashSet();
- for (int i= 0; i < searchResults.length; i++) {
- IJavaScriptElement el= SearchUtils.getEnclosingJavaElement(searchResults[i]);
- if (el.exists() && el.getElementType() == elementType)
- elements.add(el);
- }
- return elements;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/TypeVariableMaplet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/TypeVariableMaplet.java
deleted file mode 100644
index 9cb48a7d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/TypeVariableMaplet.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-
-/**
- * Maplet from a type variable in a source class to a type variable in a target class.
- */
-public final class TypeVariableMaplet {
-
- /** The source index */
- private final int fSourceIndex;
-
- /** The source of the mapping */
- private final String fSourceName;
-
- /** The target index */
- private final int fTargetIndex;
-
- /** The target of the mapping */
- private final String fTargetName;
-
- /**
- * Creates a new type variable maplet.
- *
- * @param source
- * the simple name of the type variable in the source class
- * @param index
- * the index of the source type variable in the source class declaration
- * @param target
- * the simple name of the type variable in the range class
- * @param offset
- * the index of the range type variable in the range class declaration
- */
- public TypeVariableMaplet(final String source, final int index, final String target, final int offset) {
- Assert.isNotNull(source);
- Assert.isNotNull(target);
- Assert.isTrue(source.length() > 0);
- Assert.isTrue(target.length() > 0);
- Assert.isTrue(index >= 0);
- Assert.isTrue(offset >= 0);
- fSourceName= source;
- fTargetName= target;
- fSourceIndex= index;
- fTargetIndex= offset;
- }
-
- public final boolean equals(final Object object) {
- if (object instanceof TypeVariableMaplet) {
- final TypeVariableMaplet mapping= (TypeVariableMaplet) object;
- return mapping.getSourceName().equals(fSourceName) && mapping.getTargetName().equals(fTargetName) && mapping.getSourceIndex() == fSourceIndex && mapping.getTargetIndex() == fTargetIndex;
- }
- return false;
- }
-
- /**
- * Returns the source index of this type variable maplet.
- *
- * @return the source index of this maplet
- */
- public final int getSourceIndex() {
- return fSourceIndex;
- }
-
- /**
- * Returns the source of this type variable maplet.
- *
- * @return the source of this maplet
- */
- public final String getSourceName() {
- return fSourceName;
- }
-
- /**
- * Returns the target index of this type variable maplet.
- *
- * @return the target index of this maplet
- */
- public final int getTargetIndex() {
- return fTargetIndex;
- }
-
- /**
- * Returns the target of this type variable maplet.
- *
- * @return the target of this maplet
- */
- public final String getTargetName() {
- return fTargetName;
- }
-
- public final int hashCode() {
- return fSourceIndex | fTargetIndex | fSourceName.hashCode() | fTargetName.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeProcessor.java
deleted file mode 100644
index 6f2b7fdb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeProcessor.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.UseSupertypeDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsModel;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsSolver;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ISourceConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring processor to replace type occurrences by a super type.
- */
-public final class UseSuperTypeProcessor extends SuperTypeRefactoringProcessor {
-
- private static final String IDENTIFIER= "org.eclipse.wst.jsdt.ui.useSuperTypeProcessor"; //$NON-NLS-1$
-
- /**
- * Finds the type with the given fully qualified name (generic type
- * parameters included) in the hierarchy.
- *
- * @param type
- * The hierarchy type to find the super type in
- * @param name
- * The fully qualified name of the super type
- * @return The found super type, or <code>null</code>
- */
- protected static ITypeBinding findTypeInHierarchy(final ITypeBinding type, final String name) {
- if (type.isArray() || type.isPrimitive())
- return null;
- if (name.equals(type.getTypeDeclaration().getQualifiedName()))
- return type;
- final ITypeBinding binding= type.getSuperclass();
- if (binding != null) {
- final ITypeBinding result= findTypeInHierarchy(binding, name);
- if (result != null)
- return result;
- }
- return null;
- }
-
- /** The text change manager */
- private TextEditBasedChangeManager fChangeManager= null;
-
- /** The number of files affected by the last change generation */
- private int fChanges= 0;
-
- /** The subtype to replace */
- private IType fSubType;
-
- /** The supertype as replacement */
- private IType fSuperType= null;
-
- /**
- * Creates a new super type processor.
- *
- * @param subType
- * the subtype to replace its occurrences, or <code>null</code>
- * if invoked by scripting
- */
- public UseSuperTypeProcessor(final IType subType) {
- super(null);
- fReplace= true;
- fSubType= subType;
- }
-
- /**
- * Creates a new super type processor.
- *
- * @param subType
- * the subtype to replace its occurrences, or <code>null</code>
- * if invoked by scripting
- * @param superType
- * the supertype as replacement, or <code>null</code> if
- * invoked by scripting
- */
- public UseSuperTypeProcessor(final IType subType, final IType superType) {
- super(null);
- fReplace= true;
- fSubType= subType;
- fSuperType= superType;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor,org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
- */
- public final RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- Assert.isNotNull(context);
- final RefactoringStatus status= new RefactoringStatus();
- fChangeManager= new TextEditBasedChangeManager();
- try {
- monitor.beginTask("", 200); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_checking);
- fChangeManager= createChangeManager(new SubProgressMonitor(monitor, 200), status);
- if (!status.hasFatalError()) {
- final RefactoringStatus validation= Checks.validateModifiesFiles(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), getRefactoring().getValidationContext());
- if (!validation.isOK())
- return validation;
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final RefactoringStatus checkInitialConditions(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_checking);
- // No checks
- monitor.worked(1);
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor)
- */
- public final Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- Assert.isNotNull(monitor);
- try {
- fChanges= 0;
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- final TextEditBasedChange[] changes= fChangeManager.getAllChanges();
- if (changes != null && changes.length != 0) {
- fChanges= changes.length;
- IJavaScriptProject project= null;
- if (!fSubType.isBinary())
- project= fSubType.getJavaScriptProject();
- int flags= JavaScriptRefactoringDescriptor.JAR_MIGRATION | JavaScriptRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
- try {
- if (fSubType.isLocal() || fSubType.isAnonymous())
- flags|= JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- final String name= project != null ? project.getElementName() : null;
- final String description= Messages.format(RefactoringCoreMessages.UseSuperTypeProcessor_descriptor_description_short, fSuperType.getElementName());
- final String header= Messages.format(RefactoringCoreMessages.UseSuperTypeProcessor_descriptor_description, new String[] { JavaScriptElementLabels.getElementLabel(fSuperType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED), JavaScriptElementLabels.getElementLabel(fSubType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED) });
- final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(name, this, header);
- comment.addSetting(Messages.format(RefactoringCoreMessages.UseSuperTypeProcessor_refactored_element_pattern, JavaScriptElementLabels.getElementLabel(fSuperType, JavaScriptElementLabels.ALL_FULLY_QUALIFIED)));
- addSuperTypeSettings(comment, false);
- final UseSupertypeDescriptor descriptor= new UseSupertypeDescriptor();
- descriptor.setProject(name);
- descriptor.setDescription(description);
- descriptor.setComment(comment.asString());
- descriptor.setFlags(flags);
- descriptor.setSubtype(getSubType());
- descriptor.setSupertype(getSuperType());
- descriptor.setReplaceInstanceof(fInstanceOf);
- return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.UseSupertypeWherePossibleRefactoring_name, fChangeManager.getAllChanges());
- }
- monitor.worked(1);
- } finally {
- monitor.done();
- }
- return null;
- }
-
- /**
- * Creates the text change manager for this processor.
- *
- * @param monitor
- * the progress monitor to display progress
- * @param status
- * the refactoring status
- * @return the created text change manager
- * @throws JavaScriptModelException
- * if the method declaration could not be found
- * @throws CoreException
- * if the changes could not be generated
- */
- protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException, CoreException {
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 300); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_creating);
- final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
- final IJavaScriptProject project= fSubType.getJavaScriptProject();
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
- if (fSubType.isBinary() || fSubType.isReadOnly()) {
- final IBinding[] bindings= parser.createBindings(new IJavaScriptElement[] { fSubType, fSuperType }, new SubProgressMonitor(monitor, 50));
- if (bindings != null && bindings.length == 2 && bindings[0] instanceof ITypeBinding && bindings[1] instanceof ITypeBinding) {
- solveSuperTypeConstraints(null, null, fSubType, (ITypeBinding) bindings[0], (ITypeBinding) bindings[1], new SubProgressMonitor(monitor, 100), status);
- if (!status.hasFatalError())
- rewriteTypeOccurrences(manager, null, null, null, null, new HashSet(), status, new SubProgressMonitor(monitor, 150));
- }
- } else {
- parser.createASTs(new IJavaScriptUnit[] { fSubType.getJavaScriptUnit() }, new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- try {
- final CompilationUnitRewrite subRewrite= new CompilationUnitRewrite(fOwner, unit, node);
- final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, subRewrite.getRoot());
- if (subDeclaration != null) {
- final ITypeBinding subBinding= subDeclaration.resolveBinding();
- if (subBinding != null) {
- final ITypeBinding superBinding= findTypeInHierarchy(subBinding, fSuperType.getFullyQualifiedName('.'));
- if (superBinding != null) {
- solveSuperTypeConstraints(subRewrite.getCu(), subRewrite.getRoot(), fSubType, subBinding, superBinding, new SubProgressMonitor(monitor, 100), status);
- if (!status.hasFatalError()) {
- rewriteTypeOccurrences(manager, this, subRewrite, subRewrite.getCu(), subRewrite.getRoot(), new HashSet(), status, new SubProgressMonitor(monitor, 200));
- final TextChange change= subRewrite.createChange();
- if (change != null)
- manager.manage(subRewrite.getCu(), change);
- }
- }
- }
- }
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.UseSuperTypeProcessor_internal_error));
- }
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, new NullProgressMonitor());
- }
- return manager;
- } finally {
- monitor.done();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeRefactoringProcessor#createContraintSolver(org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints.SuperTypeConstraintsModel)
- */
- protected final SuperTypeConstraintsSolver createContraintSolver(final SuperTypeConstraintsModel model) {
- return new SuperTypeConstraintsSolver(model);
- }
-
- /**
- * Returns the number of files that are affected from the last change
- * generation.
- *
- * @return The number of files which are affected
- */
- public final int getChanges() {
- return fChanges;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public final Object[] getElements() {
- return new Object[] { fSubType };
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getIdentifier()
- */
- public final String getIdentifier() {
- return IDENTIFIER;
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getProcessorName()
- */
- public final String getProcessorName() {
- return RefactoringCoreMessages.UseSuperTypeProcessor_name;
- }
-
- /**
- * Returns the subtype to be replaced.
- *
- * @return The subtype to be replaced
- */
- public final IType getSubType() {
- return fSubType;
- }
-
- /**
- * Returns the supertype as replacement.
- *
- * @return The supertype as replacement
- */
- public final IType getSuperType() {
- return fSuperType;
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus initialize(final RefactoringArguments arguments) {
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.USE_SUPER_TYPE);
- else
- fSubType= (IType) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT));
- handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1);
- if (handle != null) {
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false);
- if (element == null || !element.exists() || element.getElementType() != IJavaScriptElement.TYPE)
- return ScriptableRefactoring.createInputFatalStatus(element, getRefactoring().getName(), IJavaScriptRefactorings.USE_SUPER_TYPE);
- else
- fSuperType= (IType) element;
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + 1));
- final String instance= extended.getAttribute(ATTRIBUTE_INSTANCEOF);
- if (instance != null) {
- fInstanceOf= Boolean.valueOf(instance).booleanValue();
- } else
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_INSTANCEOF));
- } else
- return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
- return new RefactoringStatus();
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#isApplicable()
- */
- public final boolean isApplicable() throws CoreException {
- return Checks.isAvailable(fSubType) && Checks.isAvailable(fSuperType) && !fSubType.isAnonymous() && !fSuperType.isAnonymous();
- }
-
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#loadParticipants(org.eclipse.ltk.core.refactoring.RefactoringStatus,org.eclipse.ltk.core.refactoring.participants.SharableParticipants)
- */
- public final RefactoringParticipant[] loadParticipants(final RefactoringStatus status, final SharableParticipants sharedParticipants) throws CoreException {
- return new RefactoringParticipant[0];
- }
-
- /**
- * {@inheritDoc}
- */
- protected final void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final IJavaScriptUnit unit, final JavaScriptUnit node, final Set replacements, final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- final Collection collection= (Collection) fTypeOccurrences.get(unit);
- if (collection != null && !collection.isEmpty()) {
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100);
- try {
- subMonitor.beginTask("", collection.size() * 10); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- TType estimate= null;
- ISourceConstraintVariable variable= null;
- CompilationUnitRewrite currentRewrite= null;
- final IJavaScriptUnit sourceUnit= rewrite.getCu();
- if (sourceUnit.equals(unit))
- currentRewrite= rewrite;
- else
- currentRewrite= new CompilationUnitRewrite(fOwner, unit, node);
- for (final Iterator iterator= collection.iterator(); iterator.hasNext();) {
- variable= (ISourceConstraintVariable) iterator.next();
- estimate= (TType) variable.getData(SuperTypeConstraintsSolver.DATA_TYPE_ESTIMATE);
- if (estimate != null && variable instanceof ITypeConstraintVariable) {
- final ASTNode result= NodeFinder.perform(node, ((ITypeConstraintVariable) variable).getRange().getSourceRange());
- if (result != null)
- rewriteTypeOccurrence(estimate, currentRewrite, result, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
- }
- subMonitor.worked(10);
- }
- if (!sourceUnit.equals(unit)) {
- final TextChange change= currentRewrite.createChange();
- if (change != null)
- manager.manage(unit, change);
- }
- } finally {
- subMonitor.done();
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Sets the supertype as replacement.
- *
- * @param type
- * The supertype to set
- */
- public final void setSuperType(final IType type) {
- Assert.isNotNull(type);
-
- fSuperType= type;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeRefactoring.java
deleted file mode 100644
index 73ab33d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/UseSuperTypeRefactoring.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Refactoring to replace type occurrences by a super type where possible.
- *
- *
- */
-public final class UseSuperTypeRefactoring extends ProcessorBasedRefactoring implements IScriptableRefactoring {
-
- /** The processor to use */
- private final UseSuperTypeProcessor fProcessor;
-
- /**
- * Creates a new use super type refactoring.
- *
- * @param processor
- * the processor to use
- */
- public UseSuperTypeRefactoring(final UseSuperTypeProcessor processor) {
- super(processor);
-
- fProcessor= processor;
- }
- /*
- * @see org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring#getProcessor()
- */
- public final RefactoringProcessor getProcessor() {
- return fProcessor;
- }
-
- /**
- * Returns the use super type processor.
- *
- * @return the refactoring processor
- */
- public final UseSuperTypeProcessor getUseSuperTypeProcessor() {
- return (UseSuperTypeProcessor) getProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public final RefactoringStatus initialize(final RefactoringArguments arguments) {
- Assert.isNotNull(arguments);
- final RefactoringProcessor processor= getProcessor();
- if (processor instanceof IScriptableRefactoring) {
- return ((IScriptableRefactoring) processor).initialize(arguments);
- }
- return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.ProcessorBasedRefactoring_error_unsupported_initialization, IJavaScriptRefactorings.USE_SUPER_TYPE));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/ConditionalTypeConstraint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/ConditionalTypeConstraint.java
deleted file mode 100644
index ce476de5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/ConditionalTypeConstraint.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2;
-
-/**
- * Type constraint which models conditional expression type constraints.
- */
-public final class ConditionalTypeConstraint implements ITypeConstraint2 {
-
- /** The else type variable */
- private final ConstraintVariable2 fElseVariable;
-
- /** The expression type variable */
- private final ConstraintVariable2 fExpressionVariable;
-
- /** The then type variable */
- private final ConstraintVariable2 fThenVariable;
-
- /**
- * Creates a new conditional type constraint.
- *
- * @param expressionVariable the expression type constraint variable
- * @param thenVariable the then type constraint variable
- * @param elseVariable the else type constraint variable
- */
- public ConditionalTypeConstraint(final ConstraintVariable2 expressionVariable, final ConstraintVariable2 thenVariable, final ConstraintVariable2 elseVariable) {
- Assert.isNotNull(expressionVariable);
- Assert.isNotNull(thenVariable);
- Assert.isNotNull(elseVariable);
- fExpressionVariable= expressionVariable;
- fThenVariable= thenVariable;
- fElseVariable= elseVariable;
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public final boolean equals(final Object object) {
- if (object.getClass() != ConditionalTypeConstraint.class)
- return false;
- final ITypeConstraint2 other= (ITypeConstraint2) object;
- return getLeft() == other.getLeft() && getRight() == other.getRight();
- }
-
- /**
- * Returns the expression type constraint variable.
- *
- * @return the expression type constraint variable
- */
- public final ConstraintVariable2 getExpression() {
- return fExpressionVariable;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2#getLeft()
- */
- public final ConstraintVariable2 getLeft() {
- return fThenVariable;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2#getRight()
- */
- public final ConstraintVariable2 getRight() {
- return fElseVariable;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public final int hashCode() {
- return fThenVariable.hashCode() ^ 33 * fElseVariable.hashCode();
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return fThenVariable.toString() + " <?= " + fElseVariable.toString(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/CovariantTypeConstraint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/CovariantTypeConstraint.java
deleted file mode 100644
index 72b5f105..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/CovariantTypeConstraint.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2;
-
-/**
- * Type constraint which models covariance-related types.
- */
-public final class CovariantTypeConstraint implements ITypeConstraint2 {
-
- /** The ancestor type */
- private final ConstraintVariable2 fAncestor;
-
- /** The descendant type */
- private final ConstraintVariable2 fDescendant;
-
- /**
- * Creates a new covariant type constraint.
- *
- * @param descendant the descendant type
- * @param ancestor the ancestor type
- */
- public CovariantTypeConstraint(final ConstraintVariable2 descendant, final ConstraintVariable2 ancestor) {
- Assert.isNotNull(descendant);
- Assert.isNotNull(ancestor);
- fDescendant= descendant;
- fAncestor= ancestor;
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public final boolean equals(final Object object) {
- if (object.getClass() != CovariantTypeConstraint.class)
- return false;
- final ITypeConstraint2 other= (ITypeConstraint2) object;
- return getLeft() == other.getLeft() && getRight() == other.getRight();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2#getLeft()
- */
- public final ConstraintVariable2 getLeft() {
- return fDescendant;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2#getRight()
- */
- public final ConstraintVariable2 getRight() {
- return fAncestor;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public final int hashCode() {
- return fDescendant.hashCode() ^ 35 * fAncestor.hashCode();
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return fDescendant.toString() + " <<= " + fAncestor.toString(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java
deleted file mode 100644
index 77eb43d7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java
+++ /dev/null
@@ -1,758 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Stack;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Comment;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-
-/**
- * Type constraints creator to determine the necessary constraints to replace type occurrences by a given super type.
- *
- *
- */
-public final class SuperTypeConstraintsCreator extends HierarchicalASTVisitor {
-
- /** The constraint variable property */
- private static final String PROPERTY_CONSTRAINT_VARIABLE= "cv"; //$NON-NLS-1$
-
- /**
- * Returns the original methods of the method hierarchy of the specified method.
- *
- * @param binding the method binding
- * @param type the current type
- * @param originals the original methods which have already been found (element type: <code>IFunctionBinding</code>)
- * @param implementations <code>true</code> to favor implementation methods, <code>false</code> otherwise
- */
- private static void getOriginalMethods(final IFunctionBinding binding, final ITypeBinding type, final Collection originals, final boolean implementations) {
- final ITypeBinding ancestor= type.getSuperclass();
- if (!implementations) {
- if (ancestor != null)
- getOriginalMethods(binding, ancestor, originals, implementations);
- }
- if (implementations && ancestor != null)
- getOriginalMethods(binding, ancestor, originals, implementations);
- final IFunctionBinding[] methods= type.getDeclaredMethods();
- IFunctionBinding method= null;
- for (int index= 0; index < methods.length; index++) {
- method= methods[index];
- if (!binding.getKey().equals(method.getKey())) {
- boolean match= false;
- IFunctionBinding current= null;
- for (final Iterator iterator= originals.iterator(); iterator.hasNext();) {
- current= (IFunctionBinding) iterator.next();
- if (Bindings.areOverriddenMethods(method, current))
- match= true;
- }
- if (!match && Bindings.areOverriddenMethods(binding, method))
- originals.add(method);
- }
- }
- }
-
- /** The current method declarations being processed (element type: <code>FunctionDeclaration</code>) */
- private final Stack fCurrentMethods= new Stack();
-
- /** Should instanceof expressions be rewritten? */
- private final boolean fInstanceOf;
-
- /** The type constraint model to solve */
- private final SuperTypeConstraintsModel fModel;
-
- /**
- * Creates a new super type constraints creator.
- *
- * @param model the model to create the type constraints for
- * @param instanceofs <code>true</code> to rewrite instanceof expressions, <code>false</code> otherwise
- */
- public SuperTypeConstraintsCreator(final SuperTypeConstraintsModel model, final boolean instanceofs) {
- Assert.isNotNull(model);
-
- fModel= model;
- fInstanceOf= instanceofs;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ArrayAccess)
- */
- public final void endVisit(final ArrayAccess node) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, node.getArray().getProperty(PROPERTY_CONSTRAINT_VARIABLE));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ArrayCreation)
- */
- public final void endVisit(final ArrayCreation node) {
- final ConstraintVariable2 ancestor= (ConstraintVariable2) node.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- final ArrayInitializer initializer= node.getInitializer();
- if (initializer != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) initializer.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ArrayInitializer)
- */
- public final void endVisit(final ArrayInitializer node) {
- final ITypeBinding binding= node.resolveTypeBinding();
- if (binding != null && binding.isArray()) {
- final ConstraintVariable2 ancestor= fModel.createIndependentTypeVariable(binding.getElementType());
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- Expression expression= null;
- ConstraintVariable2 descendant= null;
- final List expressions= node.expressions();
- for (int index= 0; index < expressions.size(); index++) {
- expression= (Expression) expressions.get(index);
- descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ArrayType)
- */
- public final void endVisit(final ArrayType node) {
- ArrayType array= null;
- Type component= node.getComponentType();
- while (component instanceof ArrayType) {
- array= (ArrayType) component;
- component= array.getComponentType();
- }
- final ConstraintVariable2 variable= fModel.createTypeVariable(component);
- if (variable != null) {
- component.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.Assignment)
- */
- public final void endVisit(final Assignment node) {
- final ConstraintVariable2 ancestor= (ConstraintVariable2) node.getLeftHandSide().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- final ConstraintVariable2 descendant= (ConstraintVariable2) node.getRightHandSide().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- if (ancestor != null && descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.CatchClause)
- */
- public final void endVisit(final CatchClause node) {
- final SingleVariableDeclaration declaration= node.getException();
- if (declaration != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) declaration.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null) {
- final ITypeBinding binding= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
- if (binding != null) {
- final ConstraintVariable2 ancestor= fModel.createImmutableTypeVariable(binding);
- if (ancestor != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation)
- */
- public final void endVisit(final ClassInstanceCreation node) {
- final IFunctionBinding binding= node.resolveConstructorBinding();
- if (binding != null) {
- endVisit(node.arguments(), binding);
- ConstraintVariable2 variable= null;
- final AnonymousClassDeclaration declaration= node.getAnonymousClassDeclaration();
- if (declaration != null) {
- final ITypeBinding type= declaration.resolveBinding();
- if (type != null)
- variable= fModel.createImmutableTypeVariable(type);
- } else {
- final ITypeBinding type= node.resolveTypeBinding();
- if (type != null)
- variable= fModel.createImmutableTypeVariable(type);
- }
- if (variable != null)
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ConditionalExpression)
- */
- public final void endVisit(final ConditionalExpression node) {
- ConstraintVariable2 thenVariable= null;
- ConstraintVariable2 elseVariable= null;
- final Expression thenExpression= node.getThenExpression();
- if (thenExpression != null)
- thenVariable= (ConstraintVariable2) thenExpression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- final Expression elseExpression= node.getElseExpression();
- if (elseExpression != null)
- elseVariable= (ConstraintVariable2) elseExpression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- ITypeBinding binding= node.resolveTypeBinding();
- if (binding != null) {
- if (binding.isArray())
- binding= binding.getElementType();
- final ConstraintVariable2 ancestor= fModel.createIndependentTypeVariable(binding);
- if (ancestor != null) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- if (thenVariable != null)
- fModel.createSubtypeConstraint(thenVariable, ancestor);
- if (elseVariable != null)
- fModel.createSubtypeConstraint(elseVariable, ancestor);
- if (thenVariable != null && elseVariable != null)
- fModel.createConditionalTypeConstraint(ancestor, thenVariable, elseVariable);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public final void endVisit(final ConstructorInvocation node) {
- final IFunctionBinding binding= node.resolveConstructorBinding();
- if (binding != null)
- endVisit(node.arguments(), binding);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FieldAccess)
- */
- public final void endVisit(final FieldAccess node) {
- final IVariableBinding binding= node.resolveFieldBinding();
- if (binding != null)
- endVisit(binding, node.getExpression(), node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FieldDeclaration)
- */
- public final void endVisit(final FieldDeclaration node) {
- endVisit(node.fragments(), node.getType(), node);
- }
-
- /**
- * End of visit the specified method declaration.
- *
- * @param binding the method binding
- */
- private void endVisit(final IFunctionBinding binding) {
- IFunctionBinding method= null;
- ConstraintVariable2 ancestor= null;
- final ConstraintVariable2 descendant= fModel.createReturnTypeVariable(binding);
- if (descendant != null) {
- final Collection originals= getOriginalMethods(binding);
- for (final Iterator iterator= originals.iterator(); iterator.hasNext();) {
- method= (IFunctionBinding) iterator.next();
- if (!method.getKey().equals(binding.getKey())) {
- ancestor= fModel.createReturnTypeVariable(method);
- if (ancestor != null)
- fModel.createCovariantTypeConstraint(descendant, ancestor);
- }
- }
- }
- }
-
- /**
- * End of visit the specified method invocation.
- *
- * @param binding the method binding
- * @param descendant the constraint variable of the invocation expression
- */
- private void endVisit(final IFunctionBinding binding, final ConstraintVariable2 descendant) {
- ITypeBinding declaring= null;
- IFunctionBinding method= null;
- final Collection originals= getOriginalMethods(binding);
- for (final Iterator iterator= originals.iterator(); iterator.hasNext();) {
- method= (IFunctionBinding) iterator.next();
- declaring= method.getDeclaringClass();
- if (declaring != null) {
- final ConstraintVariable2 ancestor= fModel.createDeclaringTypeVariable(declaring);
- if (ancestor != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
-
- /**
- * End of visit the thrown exception
- *
- * @param binding the type binding of the thrown exception
- * @param node the exception name node
- */
- private void endVisit(final ITypeBinding binding, final Name node) {
- final ConstraintVariable2 variable= fModel.createExceptionVariable(node);
- if (variable != null)
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- }
-
- /**
- * End of visit the field access.
- *
- * @param binding the variable binding
- * @param qualifier the qualifier expression, or <code>null</code>
- * @param access the access expression
- */
- private void endVisit(final IVariableBinding binding, final Expression qualifier, final Expression access) {
- access.setProperty(PROPERTY_CONSTRAINT_VARIABLE, fModel.createVariableVariable(binding));
- if (qualifier != null) {
- final ITypeBinding type= binding.getDeclaringClass();
- if (type != null) {
- // array.length does not have a declaring class
- final ConstraintVariable2 ancestor= fModel.createDeclaringTypeVariable(type);
- if (ancestor != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) qualifier.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
- }
-
- /**
- * End of visit the method argument list.
- *
- * @param arguments the arguments (element type: <code>Expression</code>)
- * @param binding the method binding
- */
- private void endVisit(final List arguments, final IFunctionBinding binding) {
- Expression expression= null;
- ConstraintVariable2 ancestor= null;
- ConstraintVariable2 descendant= null;
- for (int index= 0; index < arguments.size(); index++) {
- expression= (Expression) arguments.get(index);
- descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- ancestor= fModel.createMethodParameterVariable(binding, index);
- if (ancestor != null && descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
-
- /**
- * End of visit the variable declaration fragment list.
- *
- * @param fragments the fragments (element type: <code>VariableDeclarationFragment</code>)
- * @param type the type of the fragments
- * @param parent the parent of the fragment list
- */
- private void endVisit(final List fragments, final Type type, final ASTNode parent) {
- final ConstraintVariable2 ancestor= (ConstraintVariable2) type.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (ancestor != null) {
- IVariableBinding binding= null;
- ConstraintVariable2 descendant= null;
- VariableDeclarationFragment fragment= null;
- for (int index= 0; index < fragments.size(); index++) {
- fragment= (VariableDeclarationFragment) fragments.get(index);
- descendant= (ConstraintVariable2) fragment.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- binding= fragment.resolveBinding();
- if (binding != null) {
- descendant= fModel.createVariableVariable(binding);
- if (descendant != null)
- fModel.createEqualityConstraint(ancestor, descendant);
- }
- }
- parent.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public final void endVisit(final FunctionDeclaration node) {
- fCurrentMethods.pop();
- final IFunctionBinding binding= node.resolveBinding();
- if (binding != null) {
- if (!binding.isConstructor()) {
- final Type type= node.getReturnType2();
- if (type != null) {
- final ConstraintVariable2 first= fModel.createReturnTypeVariable(binding);
- final ConstraintVariable2 second= (ConstraintVariable2) type.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (first != null) {
- if (second != null)
- fModel.createEqualityConstraint(first, second);
- endVisit(binding);
- }
- }
- }
- ConstraintVariable2 ancestor= null;
- ConstraintVariable2 descendant= null;
- IVariableBinding variable= null;
- final List parameters= node.parameters();
- if (!parameters.isEmpty()) {
- final Collection originals= getOriginalMethods(binding);
- SingleVariableDeclaration declaration= null;
- for (int index= 0; index < parameters.size(); index++) {
- declaration= (SingleVariableDeclaration) parameters.get(index);
- ancestor= fModel.createMethodParameterVariable(binding, index);
- if (ancestor != null) {
- descendant= (ConstraintVariable2) declaration.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createEqualityConstraint(descendant, ancestor);
- variable= declaration.resolveBinding();
- if (variable != null) {
- descendant= fModel.createVariableVariable(variable);
- if (descendant != null)
- fModel.createEqualityConstraint(ancestor, descendant);
- }
- IFunctionBinding method= null;
- for (final Iterator iterator= originals.iterator(); iterator.hasNext();) {
- method= (IFunctionBinding) iterator.next();
- if (!method.getKey().equals(binding.getKey())) {
- descendant= fModel.createMethodParameterVariable(method, index);
- if (descendant != null)
- fModel.createEqualityConstraint(ancestor, descendant);
- }
- }
- }
- }
- }
- final List exceptions= node.thrownExceptions();
- if (!exceptions.isEmpty()) {
- final ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
- if (throwable != null) {
- ancestor= fModel.createImmutableTypeVariable(throwable);
- if (ancestor != null) {
- Name exception= null;
- for (int index= 0; index < exceptions.size(); index++) {
- exception= (Name) exceptions.get(index);
- descendant= (ConstraintVariable2) exception.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public final void endVisit(final FunctionInvocation node) {
- final IFunctionBinding binding= node.resolveMethodBinding();
- if (binding != null) {
- endVisit(node, binding);
- endVisit(node.arguments(), binding);
- final Expression expression= node.getExpression();
- if (expression != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- endVisit(binding, descendant);
- }
- }
- }
-
- /**
- * End of visit the return type of a method invocation.
- *
- * @param invocation the method invocation
- * @param binding the method binding
- */
- private void endVisit(final FunctionInvocation invocation, final IFunctionBinding binding) {
- if (!binding.isConstructor()) {
- final ConstraintVariable2 variable= fModel.createReturnTypeVariable(binding);
- if (variable != null)
- invocation.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.NullLiteral)
- */
- public final void endVisit(final NullLiteral node) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, fModel.createImmutableTypeVariable(node.resolveTypeBinding()));
- }
- public final void endVisit(final UndefinedLiteral node) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, fModel.createImmutableTypeVariable(node.resolveTypeBinding()));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression)
- */
- public final void endVisit(final ParenthesizedExpression node) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, node.getExpression().getProperty(PROPERTY_CONSTRAINT_VARIABLE));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.QualifiedName)
- */
- public final void endVisit(final QualifiedName node) {
- final ASTNode parent= node.getParent();
- final Name qualifier= node.getQualifier();
- IBinding binding= qualifier.resolveBinding();
- if (binding instanceof ITypeBinding) {
- final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength())));
- if (variable != null)
- qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
- }
- binding= node.getName().resolveBinding();
- if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration))
- endVisit((IVariableBinding) binding, qualifier, node);
- else if (binding instanceof ITypeBinding && parent instanceof FunctionDeclaration)
- endVisit((ITypeBinding) binding, node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ReturnStatement)
- */
- public final void endVisit(final ReturnStatement node) {
- final Expression expression= node.getExpression();
- if (expression != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null) {
- final FunctionDeclaration declaration= (FunctionDeclaration) fCurrentMethods.peek();
- if (declaration != null) {
- final IFunctionBinding binding= declaration.resolveBinding();
- if (binding != null) {
- final ConstraintVariable2 ancestor= fModel.createReturnTypeVariable(binding);
- if (ancestor != null) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.SimpleName)
- */
- public final void endVisit(final SimpleName node) {
- final ASTNode parent= node.getParent();
- if (!(parent instanceof ImportDeclaration) && !(parent instanceof PackageDeclaration) && !(parent instanceof AbstractTypeDeclaration)) {
- final IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding && !(parent instanceof FunctionDeclaration))
- endVisit((IVariableBinding) binding, null, node);
- else if (binding instanceof ITypeBinding && parent instanceof FunctionDeclaration)
- endVisit((ITypeBinding) binding, node);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration)
- */
- public final void endVisit(final SingleVariableDeclaration node) {
- final ConstraintVariable2 ancestor= (ConstraintVariable2) node.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (ancestor != null) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- final Expression expression= node.getInitializer();
- if (expression != null) {
- final ConstraintVariable2 descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
- if (descendant != null)
- fModel.createSubtypeConstraint(descendant, ancestor);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation)
- */
- public final void endVisit(final SuperConstructorInvocation node) {
- final IFunctionBinding binding= node.resolveConstructorBinding();
- if (binding != null)
- endVisit(node.arguments(), binding);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.SuperFieldAccess)
- */
- public final void endVisit(final SuperFieldAccess node) {
- final Name name= node.getName();
- final IBinding binding= name.resolveBinding();
- if (binding instanceof IVariableBinding)
- endVisit((IVariableBinding) binding, null, node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation)
- */
- public final void endVisit(final SuperMethodInvocation node) {
- final IFunctionBinding superBinding= node.resolveMethodBinding();
- if (superBinding != null) {
- endVisit(node.arguments(), superBinding);
- final FunctionDeclaration declaration= (FunctionDeclaration) fCurrentMethods.peek();
- if (declaration != null) {
- final IFunctionBinding subBinding= declaration.resolveBinding();
- if (subBinding != null) {
- final ConstraintVariable2 ancestor= fModel.createReturnTypeVariable(superBinding);
- if (ancestor != null) {
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
- final ConstraintVariable2 descendant= fModel.createReturnTypeVariable(subBinding);
- if (descendant != null)
- fModel.createEqualityConstraint(descendant, ancestor);
- }
- }
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.ThisExpression)
- */
- public final void endVisit(final ThisExpression node) {
- final ITypeBinding binding= node.resolveTypeBinding();
- if (binding != null)
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, fModel.createDeclaringTypeVariable(binding));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.Type)
- */
- public final void endVisit(final Type node) {
- final ASTNode parent= node.getParent();
- if (!(parent instanceof AbstractTypeDeclaration) && !(parent instanceof ClassInstanceCreation) && !(parent instanceof TypeLiteral) && (!(parent instanceof InstanceofExpression) || fInstanceOf))
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, fModel.createTypeVariable(node));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression)
- */
- public final void endVisit(final VariableDeclarationExpression node) {
- endVisit(node.fragments(), node.getType(), node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment)
- */
- public final void endVisit(final VariableDeclarationFragment node) {
- final Expression initializer= node.getInitializer();
- if (initializer != null)
- node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, initializer.getProperty(PROPERTY_CONSTRAINT_VARIABLE));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#endVisit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement)
- */
- public final void endVisit(final VariableDeclarationStatement node) {
- endVisit(node.fragments(), node.getType(), node);
- }
-
- /**
- * Returns the original methods of the method hierarchy of the specified method.
- *
- * @param binding the method binding
- * @return the original methods (element type: <code>IFunctionBinding</code>)
- */
- private Collection getOriginalMethods(final IFunctionBinding binding) {
- final Collection originals= new ArrayList();
- final ITypeBinding type= binding.getDeclaringClass();
- getOriginalMethods(binding, type, originals, false);
- getOriginalMethods(binding, type, originals, true);
- if (originals.isEmpty())
- originals.add(binding);
- return originals;
- }
-
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Comment)
- */
- public final boolean visit(final Comment node) {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ImportDeclaration)
- */
- public final boolean visit(final ImportDeclaration node) {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public final boolean visit(final FunctionDeclaration node) {
- fCurrentMethods.push(node);
- return super.visit(node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PackageDeclaration)
- */
- public final boolean visit(final PackageDeclaration node) {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThisExpression)
- */
- public final boolean visit(final ThisExpression node) {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Type)
- */
- public final boolean visit(final Type node) {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsModel.java
deleted file mode 100644
index 89bed1dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsModel.java
+++ /dev/null
@@ -1,564 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ImmutableTypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.IndependentTypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ParameterTypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ReturnTypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.SubTypeConstraint2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TypeEquivalenceSet;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.VariableVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-
-/**
- * Type constraints model to hold all type constraints to replace type occurrences by a given supertype.
- *
- *
- */
-public final class SuperTypeConstraintsModel {
-
- /** Customized implementation of a hash set */
- private static class HashedSet extends AbstractSet implements Set {
-
- /** The backing hash map */
- private final Map fImplementation= new HashMap();
-
- /*
- * @see java.util.AbstractCollection#add(java.lang.Object)
- */
- public final boolean add(final Object object) {
- return fImplementation.put(object, object) == null;
- }
-
- /**
- * Attempts to add the specified object to this set.
- *
- * @param object the object to add
- * @return An already existing object considered equal to the specified one, or the newly added object
- */
- public final Object addExisting(final Object object) {
- final Object result= fImplementation.get(object);
- if (result != null)
- return result;
- fImplementation.put(object, object);
- return object;
- }
-
- /*
- * @see java.util.AbstractCollection#clear()
- */
- public final void clear() {
- fImplementation.clear();
- }
-
- /*
- * @see java.util.AbstractCollection#contains(java.lang.Object)
- */
- public final boolean contains(final Object object) {
- return fImplementation.containsKey(object);
- }
-
- /*
- * @see java.util.AbstractCollection#isEmpty()
- */
- public final boolean isEmpty() {
- return fImplementation.isEmpty();
- }
-
- /*
- * @see java.util.AbstractCollection#iterator()
- */
- public final Iterator iterator() {
- return fImplementation.keySet().iterator();
- }
-
- /*
- * @see java.util.AbstractCollection#remove(java.lang.Object)
- */
- public final boolean remove(final Object object) {
- return fImplementation.remove(object) == object;
- }
-
- /*
- * @see java.util.AbstractCollection#size()
- */
- public final int size() {
- return fImplementation.size();
- }
- }
-
- /** The usage data */
- private static final String DATA_USAGE= "us"; //$NON-NLS-1$
-
- /** Maximal number of TTypes */
- private static final int MAX_CACHE= 64;
-
- /**
- * Returns the usage of the specified constraint variable.
- *
- * @param variable the constraint variable
- * @return the usage of the constraint variable (element type: <code>ITypeConstraint2</code>)
- */
- public static Collection getVariableUsage(final ConstraintVariable2 variable) {
- final Object data= variable.getData(DATA_USAGE);
- if (data == null)
- return Collections.EMPTY_LIST;
- else if (data instanceof Collection)
- return Collections.unmodifiableCollection((Collection) data);
- else
- return Collections.singletonList(data);
- }
-
- /**
- * Is the type represented by the specified binding a constrained type?
- *
- * @param binding the binding to check, or <code>null</code>
- * @return <code>true</code> if it is constrained, <code>false</code> otherwise
- */
- public static boolean isConstrainedType(final ITypeBinding binding) {
- return binding != null && !binding.isPrimitive();
- }
-
- /**
- * Sets the usage of the specified constraint variable.
- *
- * @param variable the constraint variable
- * @param constraint the type constraint
- */
- public static void setVariableUsage(final ConstraintVariable2 variable, ITypeConstraint2 constraint) {
- final Object data= variable.getData(DATA_USAGE);
- if (data == null)
- variable.setData(DATA_USAGE, constraint);
- else if (data instanceof Collection)
- ((Collection) data).add(constraint);
- else {
- final Collection usage= new ArrayList(2);
- usage.add(data);
- usage.add(constraint);
- variable.setData(DATA_USAGE, usage);
- }
- }
-
- /** The cast variables (element type: <code>CastVariable2</code>) */
- private final Collection fCastVariables= new ArrayList();
-
- /** The compliance level */
- private int fCompliance= 3;
-
- /** The set of constraint variables (element type: <code>ConstraintVariable2</code>) */
- private final HashedSet fConstraintVariables= new HashedSet();
-
- /** The covariant type constraints (element type: <code>CovariantTypeConstraint</code>) */
- private final Collection fCovariantTypeConstraints= new ArrayList();
-
- /** The type environment to use */
- private TypeEnvironment fEnvironment;
-
- /** The subtype to replace */
- private final TType fSubType;
-
- /** The supertype as replacement */
- private final TType fSuperType;
-
- /** The TType cache (element type: <code>&lt;String, ITypeBinding&gt;</code>) */
- private Map fTTypeCache= new LinkedHashMap(MAX_CACHE, 0.75f, true) {
-
- private static final long serialVersionUID= 1L;
-
- protected final boolean removeEldestEntry(Map.Entry entry) {
- return size() > MAX_CACHE;
- }
- };
-
- /** The set of type constraints (element type: <code>ITypeConstraint2</code>) */
- private final Set fTypeConstraints= new HashSet();
-
- /**
- * Creates a new super type constraints model.
- *
- * @param subType the subtype to replace
- * @param superType the supertype replacement
- */
- public SuperTypeConstraintsModel(final TypeEnvironment environment, TType subType, TType superType) {
- fEnvironment= environment;
- fSubType= subType;
- fSuperType= superType;
- }
-
- /**
- * Gets called when the creation of the model begins.
- */
- public final void beginCreation() {
- // Do nothing right now
- }
-
- /**
- * Creates a conditional type constraint.
- *
- * @param expressionVariable the expression type constraint variable
- * @param thenVariable the then type constraint variable
- * @param elseVariable the else type constraint variable
- */
- public final void createConditionalTypeConstraint(final ConstraintVariable2 expressionVariable, final ConstraintVariable2 thenVariable, final ConstraintVariable2 elseVariable) {
- final ITypeConstraint2 constraint= new ConditionalTypeConstraint(expressionVariable, thenVariable, elseVariable);
- if (!fTypeConstraints.contains(constraint)) {
- fTypeConstraints.add(constraint);
- setVariableUsage(expressionVariable, constraint);
- setVariableUsage(thenVariable, constraint);
- setVariableUsage(elseVariable, constraint);
- }
- }
-
- /**
- * Creates a subtype constraint.
- *
- * @param descendant the descendant type constraint variable
- * @param ancestor the ancestor type constraint variable
- */
- public final void createCovariantTypeConstraint(final ConstraintVariable2 descendant, final ConstraintVariable2 ancestor) {
- final ITypeConstraint2 constraint= new CovariantTypeConstraint(descendant, ancestor);
- if (!fTypeConstraints.contains(constraint)) {
- fTypeConstraints.add(constraint);
- fCovariantTypeConstraints.add(constraint);
- setVariableUsage(descendant, constraint);
- setVariableUsage(ancestor, constraint);
- }
- }
-
- /**
- * Creates a declaring type variable.
- * <p>
- * A declaring type variable stands for a type where something has been declared.
- * </p>
- *
- * @param type the type binding
- * @return the created declaring type variable
- */
- public final ConstraintVariable2 createDeclaringTypeVariable(ITypeBinding type) {
- if (type.isArray())
- type= type.getElementType();
- type= type.getTypeDeclaration();
- return (ConstraintVariable2) fConstraintVariables.addExisting(new ImmutableTypeVariable2(createTType(type)));
- }
-
- /**
- * Creates an equality constraint.
- *
- * @param left the left typeconstraint variable
- * @param right the right typeconstraint variable
- */
- public final void createEqualityConstraint(final ConstraintVariable2 left, final ConstraintVariable2 right) {
- if (left != null && right != null) {
- final TypeEquivalenceSet first= left.getTypeEquivalenceSet();
- final TypeEquivalenceSet second= right.getTypeEquivalenceSet();
- if (first == null) {
- if (second == null) {
- final TypeEquivalenceSet set= new TypeEquivalenceSet(left, right);
- left.setTypeEquivalenceSet(set);
- right.setTypeEquivalenceSet(set);
- } else {
- second.add(left);
- left.setTypeEquivalenceSet(second);
- }
- } else {
- if (second == null) {
- first.add(right);
- right.setTypeEquivalenceSet(first);
- } else if (first == second)
- return;
- else {
- final ConstraintVariable2[] variables= second.getContributingVariables();
- first.addAll(variables);
- for (int index= 0; index < variables.length; index++)
- variables[index].setTypeEquivalenceSet(first);
- }
- }
- }
- }
-
- /**
- * Creates an exception variable.
- *
- * @param name the name of the thrown exception
- * @return the created exception variable
- */
- public final ConstraintVariable2 createExceptionVariable(final Name name) {
- final ITypeBinding binding= name.resolveTypeBinding();
- if (isConstrainedType(binding))
- return (ConstraintVariable2) fConstraintVariables.addExisting(new TypeVariable2(createTType(binding), new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(name), name)));
- return null;
- }
-
- /**
- * Creates an immutable type variable.
- *
- * @param type the type binding
- * @return the created plain type variable
- */
- public final ConstraintVariable2 createImmutableTypeVariable(ITypeBinding type) {
- if (type.isArray())
- type= type.getElementType();
- if (isConstrainedType(type))
- return (ConstraintVariable2) fConstraintVariables.addExisting(new ImmutableTypeVariable2(createTType(type)));
- return null;
- }
-
- /**
- * Creates an independent type variable.
- * <p>
- * An independant type variable stands for an arbitrary type.
- * </p>
- *
- * @param type the type binding
- * @return the created independant type variable
- */
- public final ConstraintVariable2 createIndependentTypeVariable(ITypeBinding type) {
- if (type.isArray())
- type= type.getElementType();
- if (isConstrainedType(type))
- return (ConstraintVariable2) fConstraintVariables.addExisting(new IndependentTypeVariable2(createTType(type)));
- return null;
- }
-
- /**
- * Creates a new method parameter variable.
- *
- * @param method the method binding
- * @param index the index of the parameter
- * @return the created method parameter variable
- */
- public final ConstraintVariable2 createMethodParameterVariable(final IFunctionBinding method, final int index) {
- final ITypeBinding[] parameters= method.getParameterTypes();
- ITypeBinding binding= parameters[Math.min(index, parameters.length - 1)];
- if (binding.isArray())
- binding= binding.getElementType();
- if (isConstrainedType(binding)) {
- ConstraintVariable2 variable= null;
- final TType type= createTType(binding);
- if (method.getDeclaringClass().isFromSource())
- variable= new ParameterTypeVariable2(type, index, method.getMethodDeclaration());
- else
- variable= new ImmutableTypeVariable2(type);
- return (ConstraintVariable2) fConstraintVariables.addExisting(variable);
- }
- return null;
- }
-
- /**
- * Creates a new return type variable.
- *
- * @param method the method binding
- * @return the created return type variable
- */
- public final ConstraintVariable2 createReturnTypeVariable(final IFunctionBinding method) {
- if (!method.isConstructor()) {
- ITypeBinding binding= method.getReturnType();
- if (binding != null && binding.isArray())
- binding= binding.getElementType();
- if (binding != null && isConstrainedType(binding)) {
- ConstraintVariable2 variable= null;
- final TType type= createTType(binding);
- if (method.getDeclaringClass().isFromSource())
- variable= new ReturnTypeVariable2(type, method);
- else
- variable= new ImmutableTypeVariable2(type);
- return (ConstraintVariable2) fConstraintVariables.addExisting(variable);
- }
- }
- return null;
- }
-
- /**
- * Creates a subtype constraint.
- *
- * @param descendant the descendant type constraint variable
- * @param ancestor the ancestor type constraint variable
- */
- public final void createSubtypeConstraint(final ConstraintVariable2 descendant, final ConstraintVariable2 ancestor) {
- final ITypeConstraint2 constraint= new SubTypeConstraint2(descendant, ancestor);
- if (!fTypeConstraints.contains(constraint)) {
- fTypeConstraints.add(constraint);
- setVariableUsage(descendant, constraint);
- setVariableUsage(ancestor, constraint);
- }
- }
-
- /**
- * Creates a new TType for the corresponding binding.
- *
- * @param binding The type binding
- * @return The corresponding TType
- */
- public final TType createTType(final ITypeBinding binding) {
- final String key= binding.getKey();
- final TType cached= (TType) fTTypeCache.get(key);
- if (cached != null)
- return cached;
- final TType type= fEnvironment.create(binding);
- fTTypeCache.put(key, type);
- return type;
- }
-
- /**
- * Creates a type variable.
- *
- * @param type the type binding
- * @param range the compilation unit range
- * @return the created type variable
- */
- public final ConstraintVariable2 createTypeVariable(ITypeBinding type, final CompilationUnitRange range) {
- if (type.isArray())
- type= type.getElementType();
- if (isConstrainedType(type))
- return (ConstraintVariable2) fConstraintVariables.addExisting(new TypeVariable2(createTType(type), range));
- return null;
- }
-
- /**
- * Creates a type variable.
- *
- * @param type the type
- * @return the created type variable
- */
- public final ConstraintVariable2 createTypeVariable(final Type type) {
- ITypeBinding binding= type.resolveBinding();
- if (binding != null) {
- if (binding.isArray())
- binding= binding.getElementType();
- if (isConstrainedType(binding))
- return (ConstraintVariable2) fConstraintVariables.addExisting(new TypeVariable2(createTType(binding), new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(type), type)));
- }
- return null;
- }
-
- /**
- * Creates a variable type variable.
- *
- * @param binding the variable binding
- * @return the created variable variable
- */
- public final ConstraintVariable2 createVariableVariable(final IVariableBinding binding) {
- ITypeBinding type= binding.getType();
- if (type.isArray())
- type= type.getElementType();
- if (isConstrainedType(type)) {
- ConstraintVariable2 variable= null;
- final IVariableBinding declaration= binding.getVariableDeclaration();
- if (declaration.isField()) {
- final ITypeBinding declaring= declaration.getDeclaringClass();
- if (!declaring.isFromSource())
- variable= new ImmutableTypeVariable2(createTType(type));
- } else {
- final IFunctionBinding declaring= declaration.getDeclaringMethod();
- if (declaring != null && !declaring.getDeclaringClass().isFromSource())
- variable= new ImmutableTypeVariable2(createTType(type));
- }
- if (variable == null)
- variable= new VariableVariable2(createTType(type), declaration);
- return (ConstraintVariable2) fConstraintVariables.addExisting(variable);
- }
- return null;
- }
-
- /**
- * Gets called when the creation of the model ends.
- */
- public final void endCreation() {
- fEnvironment= null;
- fTTypeCache= null;
- }
-
- /**
- * Returns the cast variables of this model.
- *
- * @return the cast variables (element type: <code>CastVariable2</code>)
- */
- public final Collection getCastVariables() {
- return Collections.unmodifiableCollection(fCastVariables);
- }
-
- /**
- * Returns the compliance level to use.
- *
- * @return the compliance level
- */
- public final int getCompliance() {
- return fCompliance;
- }
-
- /**
- * Returns the constraint variables of this model.
- *
- * @return the constraint variables (element type: <code>ConstraintVariable2</code>)
- */
- public final Collection getConstraintVariables() {
- return Collections.unmodifiableCollection(fConstraintVariables);
- }
-
- /**
- * Returns the subtype to be replaced.
- *
- * @return the subtype to be replaced
- */
- public final TType getSubType() {
- return fSubType;
- }
-
- /**
- * Returns the supertype as replacement.
- *
- * @return the supertype as replacement
- */
- public final TType getSuperType() {
- return fSuperType;
- }
-
- /**
- * Returns the type constraints of this model.
- *
- * @return the type constraints (element type: <code>ITypeConstraint2</code>)
- */
- public final Collection getTypeConstraints() {
- return Collections.unmodifiableCollection(fTypeConstraints);
- }
-
- /**
- * Sets the compliance level to use.
- *
- * @param level the compliance level to use. The argument must be one of the <code>AST.JLSx</code> constants.
- */
- public final void setCompliance(final int level) {
- fCompliance= level;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsSolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsSolver.java
deleted file mode 100644
index d1a9e834..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsSolver.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.CastVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraint2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeConstraintVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ImmutableTypeVariable2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TypeEquivalenceSet;
-
-/**
- * Type constraint solver to solve supertype constraint models.
- *
- *
- */
-public class SuperTypeConstraintsSolver {
-
- /** The type estimate data (type: <code>TType</code>) */
- public static final String DATA_TYPE_ESTIMATE= "te"; //$NON-NLS-1$
-
- /** The type constraint model to solve */
- protected final SuperTypeConstraintsModel fModel;
-
- /** The obsolete casts (element type: <code>&ltICompilationUnit, Collection&ltCastVariable2&gt&gt</code>) */
- protected Map fObsoleteCasts= null;
-
- /** The list of constraint variables to be processed */
- protected LinkedList fProcessable= null;
-
- /** The type occurrences (element type: <code>&ltICompilationUnit, Collection&ltIDeclaredConstraintVariable&gt</code>) */
- protected Map fTypeOccurrences= null;
-
- /**
- * Creates a new super type constraints solver.
- *
- * @param model the model to solve
- */
- public SuperTypeConstraintsSolver(final SuperTypeConstraintsModel model) {
- Assert.isNotNull(model);
-
- fModel= model;
- }
-
- /**
- * Computes the necessary equality constraints for conditional expressions.
- *
- * @param constraints the type constraints (element type: <code>ITypeConstraint2</code>)
- * @param level the compliance level
- */
- private void computeConditionalTypeConstraints(final Collection constraints, final int level) {
- ITypeConstraint2 constraint= null;
- for (final Iterator iterator= constraints.iterator(); iterator.hasNext();) {
- constraint= (ITypeConstraint2) iterator.next();
- if (constraint instanceof ConditionalTypeConstraint) {
- final ConditionalTypeConstraint conditional= (ConditionalTypeConstraint) constraint;
- fModel.createEqualityConstraint(constraint.getLeft(), constraint.getRight());
- fModel.createEqualityConstraint(conditional.getExpression(), constraint.getLeft());
- fModel.createEqualityConstraint(conditional.getExpression(), constraint.getRight());
- }
- }
- }
-
- /**
- * Computes the necessary equality constraints for non-covariant return types.
- *
- * @param constraints the type constraints (element type: <code>ITypeConstraint2</code>)
- * @param level the compliance level
- */
- private void computeNonCovariantConstraints(final Collection constraints, final int level) {
- if (level != 3) {
- ITypeConstraint2 constraint= null;
- for (final Iterator iterator= constraints.iterator(); iterator.hasNext();) {
- constraint= (ITypeConstraint2) iterator.next();
- if (constraint instanceof CovariantTypeConstraint)
- fModel.createEqualityConstraint(constraint.getLeft(), constraint.getRight());
- }
- }
- }
-
- /**
- * Computes the obsolete casts for the specified cast variables.
- *
- * @param variables the cast variables (element type: <code>CastVariable2</code>)
- */
- private void computeObsoleteCasts(final Collection variables) {
- fObsoleteCasts= new HashMap();
- CastVariable2 variable= null;
- for (final Iterator iterator= variables.iterator(); iterator.hasNext();) {
- variable= (CastVariable2) iterator.next();
- final TType type= (TType) variable.getExpressionVariable().getData(DATA_TYPE_ESTIMATE);
- if (type != null && type.canAssignTo(variable.getType())) {
- final IJavaScriptUnit unit= variable.getCompilationUnit();
- Collection casts= (Collection) fObsoleteCasts.get(unit);
- if (casts != null)
- casts.add(variable);
- else {
- casts= new ArrayList(1);
- casts.add(variable);
- fObsoleteCasts.put(unit, casts);
- }
- }
- }
- }
-
- /**
- * Computes the initial type estimate for the specified constraint variable.
- *
- * @param variable the constraint variable
- * @return the initial type estimate
- */
- protected ITypeSet computeTypeEstimate(final ConstraintVariable2 variable) {
- final TType type= variable.getType();
- if (variable instanceof ImmutableTypeVariable2 || !type.getErasure().equals(fModel.getSubType().getErasure()))
- return SuperTypeSet.createTypeSet(type);
- return SuperTypeSet.createTypeSet(type, fModel.getSuperType());
- }
-
- /**
- * Computes the initial type estimates for the specified variables.
- *
- * @param variables the constraint variables (element type: <code>ConstraintVariable2</code>)
- */
- private void computeTypeEstimates(final Collection variables) {
- ConstraintVariable2 variable= null;
- for (final Iterator iterator= variables.iterator(); iterator.hasNext();) {
- variable= (ConstraintVariable2) iterator.next();
- TypeEquivalenceSet set= variable.getTypeEquivalenceSet();
- if (set == null) {
- set= new TypeEquivalenceSet(variable);
- set.setTypeEstimate(computeTypeEstimate(variable));
- variable.setTypeEquivalenceSet(set);
- } else {
- ITypeSet estimate= variable.getTypeEstimate();
- if (estimate == null) {
- final ConstraintVariable2[] contributing= set.getContributingVariables();
- estimate= SuperTypeSet.getUniverse();
- for (int index= 0; index < contributing.length; index++)
- estimate= estimate.restrictedTo(computeTypeEstimate(contributing[index]));
- set.setTypeEstimate(estimate);
- }
- }
- }
- }
-
- /**
- * Computes a single type for each of the specified constraint variables.
- *
- * @param variables the constraint variables (element type: <code>ConstraintVariable2</code>)
- */
- private void computeTypeOccurrences(final Collection variables) {
- fTypeOccurrences= new HashMap();
- final TType superErasure= fModel.getSuperType().getErasure();
- TType estimatedType= null;
- ITypeSet set= null;
- IJavaScriptUnit unit= null;
- ConstraintVariable2 variable= null;
- ITypeConstraintVariable declaration= null;
- TType variableType= null;
- for (final Iterator iterator= variables.iterator(); iterator.hasNext();) {
- variable= (ConstraintVariable2) iterator.next();
- if (variable instanceof ITypeConstraintVariable) {
- declaration= (ITypeConstraintVariable) variable;
- variableType= variable.getType();
- set= declaration.getTypeEstimate();
- if (set != null) {
- estimatedType= set.chooseSingleType();
- if (estimatedType != null) {
- final TType typeErasure= estimatedType.getErasure();
- if (!typeErasure.equals(variableType.getErasure()) && typeErasure.equals(superErasure)) {
- declaration.setData(DATA_TYPE_ESTIMATE, estimatedType);
- unit= declaration.getCompilationUnit();
- if (unit != null) {
- Collection matches= (Collection) fTypeOccurrences.get(unit);
- if (matches != null)
- matches.add(declaration);
- else {
- matches= new ArrayList(1);
- matches.add(declaration);
- fTypeOccurrences.put(unit, matches);
- }
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * Returns the computed obsolete casts.
- *
- * @return the obsolete casts (element type: <code>&ltICompilationUnit, Collection&ltCastVariable2&gt&gt</code>)
- */
- public final Map getObsoleteCasts() {
- return fObsoleteCasts;
- }
-
- /**
- * Returns the computed type occurrences.
- *
- * @return the type occurrences (element type: <code>&ltICompilationUnit, Collection&ltIDeclaredConstraintVariable&gt</code>)
- */
- public final Map getTypeOccurrences() {
- return fTypeOccurrences;
- }
-
- /**
- * Processes the given constraints on the constraint variable and propagates it.
- *
- * @param constraints the type constraints to process (element type: <code>ITypeConstraint2</code>)
- */
- private void processConstraints(final Collection constraints) {
- final int level= fModel.getCompliance();
- ITypeConstraint2 constraint= null;
- for (final Iterator iterator= constraints.iterator(); iterator.hasNext();) {
- constraint= (ITypeConstraint2) iterator.next();
- if ((level == 3 || !(constraint instanceof CovariantTypeConstraint)) && !(constraint instanceof ConditionalTypeConstraint)) {
- final ConstraintVariable2 leftVariable= constraint.getLeft();
- final ITypeSet leftEstimate= leftVariable.getTypeEstimate();
- final TypeEquivalenceSet set= leftVariable.getTypeEquivalenceSet();
- final ITypeSet newEstimate= leftEstimate.restrictedTo(constraint.getRight().getTypeEstimate());
- if (leftEstimate != newEstimate) {
- set.setTypeEstimate(newEstimate);
- fProcessable.addAll(Arrays.asList(set.getContributingVariables()));
- }
- }
- }
- }
-
- /**
- * Solves the constraints of the associated model.
- */
- public final void solveConstraints() {
- fProcessable= new LinkedList();
- final Collection variables= fModel.getConstraintVariables();
- final Collection constraints= fModel.getTypeConstraints();
- final int level= fModel.getCompliance();
- computeNonCovariantConstraints(constraints, level);
-
- // TODO: use most specific common type for AST.JLS3
- computeConditionalTypeConstraints(constraints, level);
-
- computeTypeEstimates(variables);
- fProcessable.addAll(variables);
- Collection usage= null;
- ConstraintVariable2 variable= null;
- while (!fProcessable.isEmpty()) {
- variable= (ConstraintVariable2) fProcessable.removeFirst();
- usage= SuperTypeConstraintsModel.getVariableUsage(variable);
- if (!usage.isEmpty())
- processConstraints(usage);
- else
- variable.setData(DATA_TYPE_ESTIMATE, variable.getTypeEstimate().chooseSingleType());
- }
- computeTypeOccurrences(variables);
- computeObsoleteCasts(fModel.getCastVariables());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java
deleted file mode 100644
index 395d6837..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java
+++ /dev/null
@@ -1,1250 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.BindingKey;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringScopeFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringSearchEngine2;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.SearchResultGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ICommentProvider;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-/**
- * Partial implementation of a refactoring processor solving supertype
- * constraint models.
- *
- *
- */
-public abstract class SuperTypeRefactoringProcessor extends RefactoringProcessor implements IScriptableRefactoring, ICommentProvider {
-
- // TODO: remove
- protected static final String ATTRIBUTE_INSTANCEOF= "instanceof"; //$NON-NLS-1$
-
- // TODO: remove
- protected static final String ATTRIBUTE_REPLACE= "replace"; //$NON-NLS-1$
-
- /** The super type group category set */
- protected static final GroupCategorySet SET_SUPER_TYPE= new GroupCategorySet(new GroupCategory("org.eclipse.wst.jsdt.internal.corext.superType", //$NON-NLS-1$
- RefactoringCoreMessages.SuperTypeRefactoringProcessor_category_name, RefactoringCoreMessages.SuperTypeRefactoringProcessor_category_description));
-
- /** Number of compilation units to parse at once */
- private static final int SIZE_BATCH= 500;
-
- /**
- * Returns a new ast node corresponding to the given type.
- *
- * @param rewrite
- * the compilation unit rewrite to use
- * @param type
- * the specified type
- * @return A corresponding ast node
- */
- protected static ASTNode createCorrespondingNode(final CompilationUnitRewrite rewrite, final TType type) {
- return rewrite.getImportRewrite().addImportFromSignature(new BindingKey(type.getBindingKey()).toSignature(), rewrite.getAST());
- }
-
- /** The comment */
- protected String fComment;
-
- /** Should type occurrences on instanceof's also be rewritten? */
- protected boolean fInstanceOf= false;
-
- /**
- * The obsolete casts (element type:
- * <code>&ltICompilationUnit, Collection&ltCastVariable2&gt&gt</code>)
- */
- protected Map fObsoleteCasts= null;
-
- /** The working copy owner */
- protected final WorkingCopyOwner fOwner= new WorkingCopyOwner() {
- };
-
- /** Should occurrences of the type be replaced by the supertype? */
- protected boolean fReplace= false;
-
- /** The code generation settings, or <code>null</code> */
- protected CodeGenerationSettings fSettings;
-
- /** The static bindings to import */
- protected final Set fStaticBindings= new HashSet();
-
- /** The type bindings to import */
- protected final Set fTypeBindings= new HashSet();
-
- /**
- * The type occurrences (element type:
- * <code>&ltICompilationUnit, Collection&ltIDeclaredConstraintVariable&gt&gt</code>)
- */
- protected Map fTypeOccurrences= null;
-
- /**
- * Creates a new supertype refactoring processor.
- *
- * @param settings
- * the code generation settings, or <code>null</code>
- */
- protected SuperTypeRefactoringProcessor(final CodeGenerationSettings settings) {
- fSettings= settings;
- }
-
- /**
- * Adds the refactoring settings to the specified comment.
- *
- * @param comment
- * the java refactoring descriptor comment
- * @param addUseSupertype
- * <code>true</code> to add the use supertype setting,
- * <code>false</code> otherwise
- */
- protected void addSuperTypeSettings(final JDTRefactoringDescriptorComment comment, final boolean addUseSupertype) {
- Assert.isNotNull(comment);
- if (fReplace) {
- if (addUseSupertype)
- comment.addSetting(RefactoringCoreMessages.SuperTypeRefactoringProcessor_user_supertype_setting);
- if (fInstanceOf)
- comment.addSetting(RefactoringCoreMessages.SuperTypeRefactoringProcessor_use_in_instanceof_setting);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canEnableComment() {
- return true;
- }
-
- /**
- * Creates the super type constraint solver to solve the model.
- *
- * @param model
- * the model to create a solver for
- * @return The created super type constraint solver
- */
- protected abstract SuperTypeConstraintsSolver createContraintSolver(SuperTypeConstraintsModel model);
-
- /**
- * Creates the declarations of the new supertype members.
- *
- * @param sourceRewrite
- * the source compilation unit rewrite
- * @param targetRewrite
- * the target rewrite
- * @param targetDeclaration
- * the target type declaration
- * @throws CoreException
- * if a buffer could not be retrieved
- */
- protected void createMemberDeclarations(CompilationUnitRewrite sourceRewrite, ASTRewrite targetRewrite, AbstractTypeDeclaration targetDeclaration) throws CoreException {
- // Do nothing
- }
-
- /**
- * Creates the declaration of the new supertype, excluding any comments or
- * package declaration.
- *
- * @param sourceRewrite
- * the source compilation unit rewrite
- * @param subType
- * the subtype
- * @param superName
- * the name of the supertype
- * @param sourceDeclaration
- * the type declaration of the source type
- * @param buffer
- * the string buffer containing the declaration
- * @param isInterface
- * <code>true</code> if the type declaration is an interface,
- * <code>false</code> otherwise
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs
- */
- protected final void createTypeDeclaration(final CompilationUnitRewrite sourceRewrite, final IType subType, final String superName, final AbstractTypeDeclaration sourceDeclaration, final StringBuffer buffer, boolean isInterface, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(sourceRewrite);
- Assert.isNotNull(subType);
- Assert.isNotNull(superName);
- Assert.isNotNull(sourceDeclaration);
- Assert.isNotNull(buffer);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- final String delimiter= StubUtility.getLineDelimiterUsed(subType.getJavaScriptProject());
- if (JdtFlags.isPublic(subType)) {
- buffer.append(JdtFlags.VISIBILITY_STRING_PUBLIC);
- buffer.append(" "); //$NON-NLS-1$
- }
- if (isInterface)
- buffer.append("interface "); //$NON-NLS-1$
- else
- buffer.append("class "); //$NON-NLS-1$
- buffer.append(superName);
- buffer.append(" {"); //$NON-NLS-1$
- buffer.append(delimiter);
- buffer.append(delimiter);
- buffer.append('}');
- final IDocument document= new Document(buffer.toString());
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(document.get().toCharArray());
- final JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(new SubProgressMonitor(monitor, 100));
- final ASTRewrite targetRewrite= ASTRewrite.create(unit.getAST());
- final AbstractTypeDeclaration targetDeclaration= (AbstractTypeDeclaration) unit.types().get(0);
- createMemberDeclarations(sourceRewrite, targetRewrite, targetDeclaration);
- final TextEdit edit= targetRewrite.rewriteAST(document, subType.getJavaScriptProject().getOptions(true));
- try {
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- buffer.setLength(0);
- buffer.append(document.get());
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the necessary imports for the extracted supertype.
- *
- * @param unit
- * the working copy of the new supertype
- * @param monitor
- * the progress monitor to use
- * @return the generated import declaration
- * @throws CoreException
- * if the imports could not be generated
- */
- protected final String createTypeImports(final IJavaScriptUnit unit, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(unit);
- Assert.isNotNull(monitor);
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- final ImportRewrite rewrite= StubUtility.createImportRewrite(unit, true);
- ITypeBinding type= null;
- for (final Iterator iterator= fTypeBindings.iterator(); iterator.hasNext();) {
- type= (ITypeBinding) iterator.next();
- rewrite.addImport(type);
- }
- IBinding binding= null;
- for (final Iterator iterator= fStaticBindings.iterator(); iterator.hasNext();) {
- binding= (IBinding) iterator.next();
- rewrite.addStaticImport(binding);
- }
- final IDocument document= new Document();
- try {
- rewrite.rewriteImports(new SubProgressMonitor(monitor, 100)).apply(document);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- fTypeBindings.clear();
- fStaticBindings.clear();
- return document.get();
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Creates the source for the new compilation unit containing the supertype.
- *
- * @param copy
- * the working copy of the new supertype
- * @param subType
- * the subtype
- * @param superName
- * the name of the supertype
- * @param sourceRewrite
- * the source compilation unit rewrite
- * @param declaration
- * the type declaration
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to display progress
- * @return the source of the new compilation unit, or <code>null</code>
- * @throws CoreException
- * if an error occurs
- */
- protected final String createTypeSource(final IJavaScriptUnit copy, final IType subType, final String superName, final CompilationUnitRewrite sourceRewrite, final AbstractTypeDeclaration declaration, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
- Assert.isNotNull(copy);
- Assert.isNotNull(subType);
- Assert.isNotNull(superName);
- Assert.isNotNull(sourceRewrite);
- Assert.isNotNull(declaration);
- Assert.isNotNull(status);
- Assert.isNotNull(monitor);
- String source= null;
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- final String delimiter= StubUtility.getLineDelimiterUsed(subType.getJavaScriptProject());
- String typeComment= null;
- String fileComment= null;
- if (fSettings.createComments) {
- typeComment= CodeGeneration.getTypeComment(copy, superName, delimiter);
- fileComment= CodeGeneration.getFileComment(copy, delimiter);
- }
- final StringBuffer buffer= new StringBuffer(64);
- createTypeDeclaration(sourceRewrite, subType, superName, declaration, buffer, true, status, new SubProgressMonitor(monitor, 40));
- final String imports= createTypeImports(copy, new SubProgressMonitor(monitor, 60));
- source= createTypeTemplate(copy, imports, fileComment, typeComment, buffer.toString());
- if (source == null) {
- if (!subType.getPackageFragment().isDefaultPackage()) {
- if (imports.length() > 0)
- buffer.insert(0, imports);
- buffer.insert(0, "package " + subType.getPackageFragment().getElementName() + ";"); //$NON-NLS-1$//$NON-NLS-2$
- }
- source= buffer.toString();
- }
- final IDocument document= new Document(source);
- final TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, source, 0, delimiter, copy.getJavaScriptProject().getOptions(true));
- if (edit != null) {
- try {
- edit.apply(document, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
- }
- source= document.get();
- }
- } finally {
- monitor.done();
- }
- return source;
- }
-
- /**
- * Creates the type template based on the code generation settings.
- *
- * @param unit
- * the working copy for the new supertype
- * @param imports
- * the generated imports declaration
- * @param fileComment
- * the file comment
- * @param comment
- * the type comment
- * @param content
- * the type content
- * @return a template for the supertype, or <code>null</code>
- * @throws CoreException
- * if the template could not be evaluated
- */
- protected final String createTypeTemplate(final IJavaScriptUnit unit, final String imports, String fileComment, final String comment, final String content) throws CoreException {
- Assert.isNotNull(unit);
- Assert.isNotNull(imports);
- Assert.isNotNull(content);
- final IPackageFragment fragment= (IPackageFragment) unit.getParent();
- final StringBuffer buffer= new StringBuffer();
- final String delimiter= StubUtility.getLineDelimiterUsed(unit.getJavaScriptProject());
- if (!fragment.isDefaultPackage()) {
- buffer.append("package " + fragment.getElementName() + ";"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append(delimiter);
- buffer.append(delimiter);
- }
- if (imports.length() > 0)
- buffer.append(imports);
-
- return StubUtility.getCompilationUnitContent(unit, buffer.toString(), fileComment, comment, content, delimiter);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void finalize() throws Throwable {
- resetWorkingCopies();
- }
-
- /**
- * {@inheritDoc}
- */
- public final String getComment() {
- return fComment;
- }
-
- /**
- * Returns the field which corresponds to the specified variable declaration
- * fragment
- *
- * @param fragment
- * the variable declaration fragment
- * @return the corresponding field
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final IField getCorrespondingField(final VariableDeclarationFragment fragment) throws JavaScriptModelException {
- final IBinding binding= fragment.getName().resolveBinding();
- if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- if (variable.isField()) {
- final IJavaScriptUnit unit= RefactoringASTParser.getCompilationUnit(fragment);
- final IJavaScriptElement element= unit.getElementAt(fragment.getStartPosition());
- if (element instanceof IField)
- return (IField) element;
- }
- }
- return null;
- }
-
- /**
- * Computes the compilation units of fields referencing the specified type
- * occurrences.
- *
- * @param units
- * the compilation unit map (element type:
- * <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
- * @param nodes
- * the ast nodes representing the type occurrences
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final void getFieldReferencingCompilationUnits(final Map units, final ASTNode[] nodes) throws JavaScriptModelException {
- ASTNode node= null;
- IField field= null;
- IJavaScriptProject project= null;
- for (int index= 0; index < nodes.length; index++) {
- node= nodes[index];
- project= RefactoringASTParser.getCompilationUnit(node).getJavaScriptProject();
- if (project != null) {
- final List fields= getReferencingFields(node, project);
- for (int offset= 0; offset < fields.size(); offset++) {
- field= (IField) fields.get(offset);
- Set set= (Set) units.get(project);
- if (set == null) {
- set= new HashSet();
- units.put(project, set);
- }
- final IJavaScriptUnit unit= field.getJavaScriptUnit();
- if (unit != null)
- set.add(unit);
- }
- }
- }
- }
-
- /**
- * Computes the compilation units of methods referencing the specified type
- * occurrences.
- *
- * @param units
- * the compilation unit map (element type:
- * <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
- * @param nodes
- * the ast nodes representing the type occurrences
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final void getMethodReferencingCompilationUnits(final Map units, final ASTNode[] nodes) throws JavaScriptModelException {
- ASTNode node= null;
- IFunction method= null;
- IJavaScriptProject project= null;
- for (int index= 0; index < nodes.length; index++) {
- node= nodes[index];
- project= RefactoringASTParser.getCompilationUnit(node).getJavaScriptProject();
- if (project != null) {
- method= getReferencingMethod(node);
- if (method != null) {
- Set set= (Set) units.get(project);
- if (set == null) {
- set= new HashSet();
- units.put(project, set);
- }
- final IJavaScriptUnit unit= method.getJavaScriptUnit();
- if (unit != null)
- set.add(unit);
- }
- }
- }
- }
-
- /**
- * Computes the compilation units referencing the subtype to replace.
- *
- * @param type
- * the subtype
- * @param monitor
- * the progress monitor to use
- * @param status
- * the refactoring status
- * @return the referenced compilation units (element type:
- * <code>&ltIJavaProject, Collection&ltSearchResultGroup&gt&gt</code>)
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final Map getReferencingCompilationUnits(final IType type, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2();
- engine.setOwner(fOwner);
- engine.setFiltering(true, true);
- engine.setStatus(status);
- engine.setScope(RefactoringScopeFactory.create(type));
- engine.setPattern(SearchPattern.createPattern(type, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
- engine.searchPattern(new SubProgressMonitor(monitor, 100));
- return engine.getAffectedProjects();
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Returns the fields which reference the specified ast node.
- *
- * @param node
- * the ast node
- * @param project
- * the java project
- * @return the referencing fields
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final List getReferencingFields(final ASTNode node, final IJavaScriptProject project) throws JavaScriptModelException {
- List result= Collections.EMPTY_LIST;
- if (node instanceof Type) {
- final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
- if (parent instanceof FieldDeclaration) {
- final List fragments= ((FieldDeclaration) parent).fragments();
- result= new ArrayList(fragments.size());
- VariableDeclarationFragment fragment= null;
- for (final Iterator iterator= fragments.iterator(); iterator.hasNext();) {
- fragment= (VariableDeclarationFragment) iterator.next();
- final IField field= getCorrespondingField(fragment);
- if (field != null)
- result.add(field);
- }
- }
- }
- return result;
- }
-
- /**
- * Returns the method which references the specified ast node.
- *
- * @param node
- * the ast node
- * @return the referencing method
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final IFunction getReferencingMethod(final ASTNode node) throws JavaScriptModelException {
- if (node instanceof Type) {
- final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
- if (parent instanceof FunctionDeclaration) {
- final IFunctionBinding binding= ((FunctionDeclaration) parent).resolveBinding();
- if (binding != null) {
- final IJavaScriptUnit unit= RefactoringASTParser.getCompilationUnit(node);
- final IJavaScriptElement element= unit.getElementAt(node.getStartPosition());
- if (element instanceof IFunction)
- return (IFunction) element;
- }
- }
- }
- return null;
- }
-
- protected IJavaScriptUnit getSharedWorkingCopy(final IJavaScriptUnit unit, final IProgressMonitor monitor) throws JavaScriptModelException {
- try {
- IJavaScriptUnit copy= unit.findWorkingCopy(fOwner);
- if (copy == null)
- copy= unit.getWorkingCopy(fOwner, monitor);
- return copy;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Returns whether type occurrences in instanceof's should be rewritten.
- *
- * @return <code>true</code> if they are rewritten, <code>false</code>
- * otherwise
- */
- public final boolean isInstanceOf() {
- return fInstanceOf;
- }
-
- /**
- * Should occurrences of the subtype be replaced by the supertype?
- *
- * @return <code>true</code> if the subtype should be replaced,
- * <code>false</code> otherwise
- */
- public final boolean isReplace() {
- return fReplace;
- }
-
- /**
- * Performs the first pass of processing the affected compilation units.
- *
- * @param creator
- * the constraints creator to use
- * @param units
- * the compilation unit map (element type:
- * <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
- * @param groups
- * the search result group map (element type:
- * <code>&ltICompilationUnit, SearchResultGroup&gt</code>)
- * @param unit
- * the compilation unit of the subtype
- * @param node
- * the compilation unit node of the subtype
- * @param monitor
- * the progress monitor to use
- */
- protected final void performFirstPass(final SuperTypeConstraintsCreator creator, final Map units, final Map groups, final IJavaScriptUnit unit, final JavaScriptUnit node, final IProgressMonitor monitor) {
- try {
- monitor.beginTask("", 100); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- node.accept(creator);
- monitor.worked(20);
- final SearchResultGroup group= (SearchResultGroup) groups.get(unit);
- if (group != null) {
- final ASTNode[] nodes= ASTNodeSearchUtil.getAstNodes(group.getSearchResults(), node);
- try {
- getMethodReferencingCompilationUnits(units, nodes);
- monitor.worked(40);
- getFieldReferencingCompilationUnits(units, nodes);
- monitor.worked(40);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Performs the second pass of processing the affected compilation units.
- *
- * @param creator
- * the constraints creator to use
- * @param unit
- * the compilation unit of the subtype
- * @param node
- * the compilation unit node of the subtype
- * @param monitor
- * the progress monitor to use
- */
- protected final void performSecondPass(final SuperTypeConstraintsCreator creator, final IJavaScriptUnit unit, final JavaScriptUnit node, final IProgressMonitor monitor) {
- try {
- monitor.beginTask("", 20); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- node.accept(creator);
- monitor.worked(20);
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Resets the working copies.
- */
- protected void resetWorkingCopies() {
- final IJavaScriptUnit[] units= JavaScriptCore.getWorkingCopies(fOwner);
- for (int index= 0; index < units.length; index++) {
- final IJavaScriptUnit unit= units[index];
- try {
- unit.discardWorkingCopy();
- } catch (Exception exception) {
- // Do nothing
- }
- }
- }
-
- /**
- * Resets the working copies.
- *
- * @param unit
- * the compilation unit to discard
- */
- protected void resetWorkingCopies(final IJavaScriptUnit unit) {
- final IJavaScriptUnit[] units= JavaScriptCore.getWorkingCopies(fOwner);
- for (int index= 0; index < units.length; index++) {
- if (!units[index].equals(unit)) {
- try {
- units[index].discardWorkingCopy();
- } catch (Exception exception) {
- // Do nothing
- }
- } else {
- try {
- units[index].getBuffer().setContents(unit.getPrimary().getBuffer().getContents());
- JavaModelUtil.reconcile(units[index]);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- }
-
- /**
- * Creates the necessary text edits to replace the subtype occurrence by a
- * supertype.
- *
- * @param range
- * the compilation unit range
- * @param estimate
- * the type estimate
- * @param requestor
- * the ast requestor to use
- * @param rewrite
- * the compilation unit rewrite to use
- * @param copy
- * the compilation unit node of the working copy ast
- * @param replacements
- * the set of variable binding keys of formal parameters which
- * must be replaced
- * @param group
- * the text edit group to use
- */
- protected final void rewriteTypeOccurrence(final CompilationUnitRange range, final TType estimate, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final JavaScriptUnit copy, final Set replacements, final TextEditGroup group) {
- ASTNode node= null;
- IBinding binding= null;
- final JavaScriptUnit target= rewrite.getRoot();
- node= NodeFinder.perform(copy, range.getSourceRange());
- if (node != null) {
- node= ASTNodes.getNormalizedNode(node).getParent();
- if (node instanceof VariableDeclaration) {
- binding= ((VariableDeclaration) node).resolveBinding();
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof SingleVariableDeclaration) {
- rewriteTypeOccurrence(estimate, rewrite, ((SingleVariableDeclaration) node).getType(), group);
- if (node.getParent() instanceof FunctionDeclaration) {
- binding= ((VariableDeclaration) node).resolveBinding();
- if (binding != null)
- replacements.add(binding.getKey());
- }
- }
- } else if (node instanceof VariableDeclarationStatement) {
- binding= ((VariableDeclaration) ((VariableDeclarationStatement) node).fragments().get(0)).resolveBinding();
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof VariableDeclarationFragment)
- rewriteTypeOccurrence(estimate, rewrite, ((VariableDeclarationStatement) ((VariableDeclarationFragment) node).getParent()).getType(), group);
- } else if (node instanceof FunctionDeclaration) {
- binding= ((FunctionDeclaration) node).resolveBinding();
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof FunctionDeclaration)
- rewriteTypeOccurrence(estimate, rewrite, ((FunctionDeclaration) node).getReturnType2(), group);
- } else if (node instanceof FieldDeclaration) {
- binding= ((VariableDeclaration) ((FieldDeclaration) node).fragments().get(0)).resolveBinding();
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof VariableDeclarationFragment) {
- node= node.getParent();
- if (node instanceof FieldDeclaration)
- rewriteTypeOccurrence(estimate, rewrite, ((FieldDeclaration) node).getType(), group);
- }
- } else if (node instanceof ArrayType) {
- final ASTNode type= node;
- while (node != null && !(node instanceof FunctionDeclaration) && !(node instanceof VariableDeclarationFragment))
- node= node.getParent();
- if (node != null) {
- final int delta= node.getStartPosition() + node.getLength() - type.getStartPosition();
- if (node instanceof FunctionDeclaration)
- binding= ((FunctionDeclaration) node).resolveBinding();
- else if (node instanceof VariableDeclarationFragment)
- binding= ((VariableDeclarationFragment) node).resolveBinding();
- if (binding != null) {
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof FunctionDeclaration || node instanceof VariableDeclarationFragment) {
- node= NodeFinder.perform(target, node.getStartPosition() + node.getLength() - delta, 0);
- if (node instanceof SimpleName)
- rewriteTypeOccurrence(estimate, rewrite, node, group);
- }
- }
- }
- } else if (node instanceof QualifiedName) {
- final ASTNode name= node;
- while (node != null && !(node instanceof FunctionDeclaration) && !(node instanceof VariableDeclarationFragment))
- node= node.getParent();
- if (node != null) {
- final int delta= node.getStartPosition() + node.getLength() - name.getStartPosition();
- if (node instanceof FunctionDeclaration)
- binding= ((FunctionDeclaration) node).resolveBinding();
- else if (node instanceof VariableDeclarationFragment)
- binding= ((VariableDeclarationFragment) node).resolveBinding();
- if (binding != null) {
- node= target.findDeclaringNode(binding.getKey());
- if (node instanceof SimpleName || node instanceof FunctionDeclaration || node instanceof VariableDeclarationFragment) {
- node= NodeFinder.perform(target, node.getStartPosition() + node.getLength() - delta, 0);
- if (node instanceof SimpleName)
- rewriteTypeOccurrence(estimate, rewrite, node, group);
- }
- }
- }
- }
- }
- }
-
- /**
- * Creates the necessary text edits to replace the subtype occurrence by a
- * supertype.
- *
- * @param estimate
- * the type estimate
- * @param rewrite
- * the ast rewrite to use
- * @param node
- * the ast node to rewrite
- * @param group
- * the text edit group to use
- */
- protected final void rewriteTypeOccurrence(final TType estimate, final CompilationUnitRewrite rewrite, final ASTNode node, final TextEditGroup group) {
- rewrite.getImportRemover().registerRemovedNode(node);
- rewrite.getASTRewrite().replace(node, createCorrespondingNode(rewrite, estimate), group);
- }
-
- /**
- * Creates the necessary text edits to replace the subtype occurrence by a
- * supertype.
- *
- * @param manager
- * the text change manager to use
- * @param requestor
- * the ast requestor to use
- * @param rewrite
- * the compilation unit rewrite of the subtype (not in working
- * copy mode)
- * @param unit
- * the compilation unit
- * @param node
- * the compilation unit node
- * @param replacements
- * the set of variable binding keys of formal parameters which
- * must be replaced
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if the change could not be generated
- */
- protected abstract void rewriteTypeOccurrences(TextEditBasedChangeManager manager, ASTRequestor requestor, CompilationUnitRewrite rewrite, IJavaScriptUnit unit, JavaScriptUnit node, Set replacements, IProgressMonitor monitor) throws CoreException;
-
- /**
- * Creates the necessary text edits to replace the subtype occurrences by a
- * supertype.
- *
- * @param manager
- * the text change manager to use
- * @param sourceRewrite
- * the compilation unit rewrite of the subtype (not in working
- * copy mode)
- * @param sourceRequestor
- * the ast requestor of the subtype, or <code>null</code>
- * @param subUnit
- * the compilation unit of the subtype, or <code>null</code>
- * @param subNode
- * the compilation unit node of the subtype, or <code>null</code>
- * @param replacements
- * the set of variable binding keys of formal parameters which
- * must be replaced
- * @param status
- * the refactoring status
- * @param monitor
- * the progress monitor to use
- */
- protected final void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor sourceRequestor, final CompilationUnitRewrite sourceRewrite, final IJavaScriptUnit subUnit, final JavaScriptUnit subNode, final Set replacements, final RefactoringStatus status, final IProgressMonitor monitor) {
- try {
- monitor.beginTask("", 300); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
- if (fTypeOccurrences != null) {
- final Set units= new HashSet(fTypeOccurrences.keySet());
- if (subUnit != null)
- units.remove(subUnit);
- final Map projects= new HashMap();
- Collection collection= null;
- IJavaScriptProject project= null;
- IJavaScriptUnit current= null;
- for (final Iterator iterator= units.iterator(); iterator.hasNext();) {
- current= (IJavaScriptUnit) iterator.next();
- project= current.getJavaScriptProject();
- collection= (Collection) projects.get(project);
- if (collection == null) {
- collection= new ArrayList();
- projects.put(project, collection);
- }
- collection.add(current);
- }
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 320);
- try {
- final Set keySet= projects.keySet();
- subMonitor.beginTask("", keySet.size() * 100); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- for (final Iterator iterator= keySet.iterator(); iterator.hasNext();) {
- project= (IJavaScriptProject) iterator.next();
- collection= (Collection) projects.get(project);
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100);
- try {
- subsubMonitor.beginTask("", collection.size() * 100 + 200); //$NON-NLS-1$
- subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- parser.createASTs((IJavaScriptUnit[]) collection.toArray(new IJavaScriptUnit[collection.size()]), new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- final IProgressMonitor subsubsubMonitor= new SubProgressMonitor(subsubMonitor, 100);
- try {
- subsubsubMonitor.beginTask("", 100); //$NON-NLS-1$
- subsubsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- if (sourceRewrite != null)
- rewriteTypeOccurrences(manager, this, sourceRewrite, unit, node, replacements, new SubProgressMonitor(subsubsubMonitor, 100));
- } catch (CoreException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
- } finally {
- subsubsubMonitor.done();
- }
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, new SubProgressMonitor(subsubMonitor, 200));
- } finally {
- subsubMonitor.done();
- }
- }
- try {
- if (subUnit != null && subNode != null && sourceRewrite != null && sourceRequestor != null)
- rewriteTypeOccurrences(manager, sourceRequestor, sourceRewrite, subUnit, subNode, replacements, new SubProgressMonitor(subMonitor, 20));
- } catch (CoreException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
- }
- } finally {
- subMonitor.done();
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public final void setComment(final String comment) {
- fComment= comment;
- }
-
- /**
- * Determines whether type occurrences in instanceof's should be rewritten.
- *
- * @param rewrite
- * <code>true</code> to rewrite them, <code>false</code>
- * otherwise
- */
- public final void setInstanceOf(final boolean rewrite) {
- fInstanceOf= rewrite;
- }
-
- /**
- * Determines whether occurrences of the subtype should be replaced by the
- * supertype.
- *
- * @param replace
- * <code>true</code> to replace occurrences where possible,
- * <code>false</code> otherwise
- */
- public final void setReplace(final boolean replace) {
- fReplace= replace;
- }
-
- /**
- * Solves the supertype constraints to replace subtype by a supertype.
- *
- * @param subUnit
- * the compilation unit of the subtype, or <code>null</code>
- * @param subNode
- * the compilation unit node of the subtype, or <code>null</code>
- * @param subType
- * the java element of the subtype
- * @param subBinding
- * the type binding of the subtype to replace
- * @param superBinding
- * the type binding of the supertype to use as replacement
- * @param monitor
- * the progress monitor to use
- * @param status
- * the refactoring status
- * @throws JavaScriptModelException
- * if an error occurs
- */
- protected final void solveSuperTypeConstraints(final IJavaScriptUnit subUnit, final JavaScriptUnit subNode, final IType subType, final ITypeBinding subBinding, final ITypeBinding superBinding, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaScriptModelException {
- Assert.isNotNull(subType);
- Assert.isNotNull(subBinding);
- Assert.isNotNull(superBinding);
- Assert.isNotNull(monitor);
- Assert.isNotNull(status);
- int level= 3;
- TypeEnvironment environment= new TypeEnvironment();
- final SuperTypeConstraintsModel model= new SuperTypeConstraintsModel(environment, environment.create(subBinding), environment.create(superBinding));
- final SuperTypeConstraintsCreator creator= new SuperTypeConstraintsCreator(model, fInstanceOf);
- try {
- monitor.beginTask("", 300); //$NON-NLS-1$
- monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- final Map firstPass= getReferencingCompilationUnits(subType, new SubProgressMonitor(monitor, 100), status);
- final Map secondPass= new HashMap();
- IJavaScriptProject project= null;
- Collection collection= null;
- try {
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- Object element= null;
- IJavaScriptUnit current= null;
- SearchResultGroup group= null;
- SearchMatch[] matches= null;
- final Map groups= new HashMap();
- for (final Iterator outer= firstPass.keySet().iterator(); outer.hasNext();) {
- project= (IJavaScriptProject) outer.next();
- if (level == 3 && !JavaModelUtil.is50OrHigher(project))
- level= 2;
- collection= (Collection) firstPass.get(project);
- if (collection != null) {
- for (final Iterator inner= collection.iterator(); inner.hasNext();) {
- group= (SearchResultGroup) inner.next();
- matches= group.getSearchResults();
- for (int index= 0; index < matches.length; index++) {
- element= matches[index].getElement();
- if (element instanceof IMember) {
- current= ((IMember) element).getJavaScriptUnit();
- if (current != null)
- groups.put(current, group);
- }
- }
- }
- }
- }
- Set units= null;
- final Set processed= new HashSet();
- if (subUnit != null)
- processed.add(subUnit);
- model.beginCreation();
- IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 120);
- try {
- final Set keySet= firstPass.keySet();
- subMonitor.beginTask("", keySet.size() * 100); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- for (final Iterator outer= keySet.iterator(); outer.hasNext();) {
- project= (IJavaScriptProject) outer.next();
- collection= (Collection) firstPass.get(project);
- if (collection != null) {
- units= new HashSet(collection.size());
- for (final Iterator inner= collection.iterator(); inner.hasNext();) {
- group= (SearchResultGroup) inner.next();
- matches= group.getSearchResults();
- for (int index= 0; index < matches.length; index++) {
- element= matches[index].getElement();
- if (element instanceof IMember) {
- current= ((IMember) element).getJavaScriptUnit();
- if (current != null)
- units.add(current);
- }
- }
- }
- final List batches= new ArrayList(units);
- final int size= batches.size();
- final int iterations= ((size - 1) / SIZE_BATCH) + 1;
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100);
- try {
- subsubMonitor.beginTask("", iterations * 100); //$NON-NLS-1$
- subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- final Map options= RefactoringASTParser.getCompilerOptions(project);
- for (int index= 0; index < iterations; index++) {
- final List iteration= batches.subList(index * SIZE_BATCH, Math.min(size, (index + 1) * SIZE_BATCH));
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(options);
- final IProgressMonitor subsubsubMonitor= new SubProgressMonitor(subsubMonitor, 100);
- try {
- final int count= iteration.size();
- subsubsubMonitor.beginTask("", count * 100); //$NON-NLS-1$
- subsubsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- parser.createASTs((IJavaScriptUnit[]) iteration.toArray(new IJavaScriptUnit[count]), new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- if (!processed.contains(unit)) {
- performFirstPass(creator, secondPass, groups, unit, node, new SubProgressMonitor(subsubsubMonitor, 100));
- processed.add(unit);
- } else
- subsubsubMonitor.worked(100);
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, new NullProgressMonitor());
- } finally {
- subsubsubMonitor.done();
- }
- }
- } finally {
- subsubMonitor.done();
- }
- }
- }
- } finally {
- firstPass.clear();
- subMonitor.done();
- }
- if (subUnit != null && subNode != null)
- performFirstPass(creator, secondPass, groups, subUnit, subNode, new SubProgressMonitor(subMonitor, 20));
- subMonitor= new SubProgressMonitor(monitor, 100);
- try {
- final Set keySet= secondPass.keySet();
- subMonitor.beginTask("", keySet.size() * 100); //$NON-NLS-1$
- subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- for (final Iterator iterator= keySet.iterator(); iterator.hasNext();) {
- project= (IJavaScriptProject) iterator.next();
- if (level == 3 && !JavaModelUtil.is50OrHigher(project))
- level= 2;
- collection= (Collection) secondPass.get(project);
- if (collection != null) {
- parser.setWorkingCopyOwner(fOwner);
- parser.setResolveBindings(true);
- parser.setProject(project);
- parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100);
- try {
- subsubMonitor.beginTask("", collection.size() * 100); //$NON-NLS-1$
- subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
- parser.createASTs((IJavaScriptUnit[]) collection.toArray(new IJavaScriptUnit[collection.size()]), new String[0], new ASTRequestor() {
-
- public final void acceptAST(final IJavaScriptUnit unit, final JavaScriptUnit node) {
- if (!processed.contains(unit))
- performSecondPass(creator, unit, node, new SubProgressMonitor(subsubMonitor, 100));
- else
- subsubMonitor.worked(100);
- }
-
- public final void acceptBinding(final String key, final IBinding binding) {
- // Do nothing
- }
- }, new NullProgressMonitor());
- } finally {
- subsubMonitor.done();
- }
- }
- }
- } finally {
- secondPass.clear();
- subMonitor.done();
- }
- } finally {
- model.endCreation();
- model.setCompliance(level);
- }
- final SuperTypeConstraintsSolver solver= createContraintSolver(model);
- solver.solveConstraints();
- fTypeOccurrences= solver.getTypeOccurrences();
- fObsoleteCasts= solver.getObsoleteCasts();
- } finally {
- monitor.done();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeSet.java
deleted file mode 100644
index eb4eee9b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/constraints/SuperTypeSet.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.structure.constraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.HierarchyType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet;
-
-/**
- * Optimized type sets for supertype constraint problems.
- */
-public abstract class SuperTypeSet implements ITypeSet {
-
- /** Implementation of an empty set */
- private static class SuperTypeEmptySet extends SuperTypeSet {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#chooseSingleType()
- */
- public final TType chooseSingleType() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#isEmpty()
- */
- public final boolean isEmpty() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#restrictedTo(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet)
- */
- public final ITypeSet restrictedTo(final ITypeSet set) {
- return this;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return "EMPTY"; //$NON-NLS-1$
- }
- }
-
- /** Implementation of a singleton */
- private static class SuperTypeSingletonSet extends SuperTypeSet {
-
- /** The type */
- private final TType fType;
-
- /**
- * Creates a new super type singleton set.
- *
- * @param type the type
- */
- private SuperTypeSingletonSet(final TType type) {
- fType= type;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#chooseSingleType()
- */
- public final TType chooseSingleType() {
- return fType;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#isEmpty()
- */
- public final boolean isEmpty() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#restrictedTo(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet)
- */
- public final ITypeSet restrictedTo(final ITypeSet set) {
- final TType leftErasure= fType.getErasure();
- if (set instanceof SuperTypeUniverse) {
- return this;
- } else if (set instanceof SuperTypeSingletonSet) {
- if (this == set)
- return this;
- if (fType.isNullType())
- return this;
- final SuperTypeSingletonSet singleton= (SuperTypeSingletonSet) set;
- final TType rightErasure= singleton.fType.getErasure();
- if (leftErasure.isGenericType() || rightErasure.isGenericType()) {
- if (rightErasure.equals(leftErasure) || ((HierarchyType) leftErasure).isSubType((HierarchyType) rightErasure))
- return this;
- }
- if (rightErasure.isJavaLangObject())
- return this;
- if (leftErasure.canAssignTo(rightErasure))
- return this;
- return SuperTypeSet.getEmpty();
- } else if (set instanceof SuperTypeTuple) {
- if (fType.isNullType())
- return this;
- final SuperTypeTuple tuple= (SuperTypeTuple) set;
- final TType rightErasure= tuple.fSuperType.getErasure();
- if (leftErasure.isGenericType() || rightErasure.isGenericType()) {
- if (rightErasure.equals(leftErasure) || ((HierarchyType) leftErasure).isSubType((HierarchyType) rightErasure))
- return this;
- }
- if (rightErasure.isJavaLangObject())
- return this;
- if (leftErasure.canAssignTo(rightErasure))
- return this;
- return SuperTypeSet.createTypeSet(tuple.fSubType);
- } else if (set instanceof SuperTypeEmptySet) {
- return set;
- } else
- Assert.isTrue(false);
- return null;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return fType.getPrettySignature();
- }
- }
-
- /** Implementation of a tuple */
- private static class SuperTypeTuple extends SuperTypeSet {
-
- /** The other type */
- private final TType fSubType;
-
- /** The super type */
- private final TType fSuperType;
-
- /**
- * Creates a new super type tuple.
- *
- * @param subType the sub type
- * @param superType the super type
- */
- private SuperTypeTuple(final TType subType, final TType superType) {
- fSubType= subType;
- fSuperType= superType;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#chooseSingleType()
- */
- public final TType chooseSingleType() {
- return fSuperType;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#isEmpty()
- */
- public final boolean isEmpty() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#restrictedTo(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet)
- */
- public final ITypeSet restrictedTo(final ITypeSet set) {
- if (set instanceof SuperTypeUniverse) {
- return this;
- } else if (set instanceof SuperTypeSingletonSet) {
- final SuperTypeSingletonSet singleton= (SuperTypeSingletonSet) set;
- final TType rightErasure= singleton.fType.getErasure();
- final TType subErasure= fSubType.getErasure();
- final TType superErasure= fSuperType.getErasure();
- if (subErasure.isGenericType() || superErasure.isGenericType() || rightErasure.isGenericType()) {
- if ((rightErasure.equals(subErasure) || ((HierarchyType) subErasure).isSubType((HierarchyType) rightErasure)) && (rightErasure.equals(superErasure) || ((HierarchyType) superErasure).isSubType((HierarchyType) rightErasure)))
- return this;
- }
- if (rightErasure.isJavaLangObject())
- return this;
- if (subErasure.canAssignTo(rightErasure) && superErasure.canAssignTo(rightErasure))
- return this;
- return SuperTypeSet.createTypeSet(fSubType);
- } else if (set instanceof SuperTypeTuple) {
- return this;
- } else if (set instanceof SuperTypeEmptySet) {
- return set;
- } else
- Assert.isTrue(false);
- return null;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return "[" + fSubType.getPrettySignature() + ", " + fSuperType.getPrettySignature() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
-
- /** Implementation of the type universe */
- private static class SuperTypeUniverse extends SuperTypeSet {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#chooseSingleType()
- */
- public final TType chooseSingleType() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#isEmpty()
- */
- public final boolean isEmpty() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet#restrictedTo(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet)
- */
- public final ITypeSet restrictedTo(final ITypeSet set) {
- return set;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return "UNIVERSE"; //$NON-NLS-1$
- }
- }
-
- /** The empty set */
- private static final ITypeSet fgEmpty= new SuperTypeEmptySet();
-
- /** The universe */
- private static final ITypeSet fgUniverse= new SuperTypeUniverse();
-
- /**
- * Creates a new type set.
- *
- * @param type the type to contain, or <code>null</code>
- * @return the type set, or the universe if <code>type</code> is <code>null</code>
- */
- public static ITypeSet createTypeSet(final TType type) {
- if (type == null)
- return fgUniverse;
- return new SuperTypeSingletonSet(type);
- }
-
- /**
- * Creates a new type set.
- *
- * @param subType the sub type
- * @param superType the super type
- * @return the type set, or the universe if <code>type</code> is <code>null</code>
- */
- public static ITypeSet createTypeSet(final TType subType, final TType superType) {
- if (subType == null || superType == null)
- return fgUniverse;
- return new SuperTypeTuple(subType, superType);
- }
-
- /**
- * Returns the empty set.
- *
- * @return the empty set
- */
- public static ITypeSet getEmpty() {
- return fgEmpty;
- }
-
- /**
- * Returns the universe set.
- *
- * @return the universe set
- */
- public static ITypeSet getUniverse() {
- return fgUniverse;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java
deleted file mode 100644
index 0d4abcbf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.AbstractExceptionAnalyzer;
-
-public class ExceptionAnalyzer extends AbstractExceptionAnalyzer {
-
- private Selection fSelection;
-
- private static class ExceptionComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- int d1= getDepth((ITypeBinding)o1);
- int d2= getDepth((ITypeBinding)o2);
- if (d1 < d2)
- return 1;
- if (d1 > d2)
- return -1;
- return 0;
- }
- private int getDepth(ITypeBinding binding) {
- int result= 0;
- while (binding != null) {
- binding= binding.getSuperclass();
- result++;
- }
- return result;
- }
- }
-
- private ExceptionAnalyzer(Selection selection) {
- Assert.isNotNull(selection);
- fSelection= selection;
- }
-
- public static ITypeBinding[] perform(BodyDeclaration enclosingNode, Selection selection) {
- ExceptionAnalyzer analyzer= new ExceptionAnalyzer(selection);
- enclosingNode.accept(analyzer);
- List exceptions= analyzer.getCurrentExceptions();
- if (enclosingNode.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- List thrownExceptions= ((FunctionDeclaration)enclosingNode).thrownExceptions();
- for (Iterator thrown= thrownExceptions.iterator(); thrown.hasNext();) {
- ITypeBinding thrownException= ((Name)thrown.next()).resolveTypeBinding();
- if (thrownException != null) {
- for (Iterator excep= exceptions.iterator(); excep.hasNext();) {
- ITypeBinding exception= (ITypeBinding) excep.next();
- if (exception.isAssignmentCompatible(thrownException))
- excep.remove();
- }
- }
- }
- }
- Collections.sort(exceptions, new ExceptionComparator());
- return (ITypeBinding[]) exceptions.toArray(new ITypeBinding[exceptions.size()]);
- }
-
- public boolean visit(ThrowStatement node) {
- ITypeBinding exception= node.getExpression().resolveTypeBinding();
- if (!isSelected(node) || exception == null || Bindings.isRuntimeException(exception)) // Safety net for null bindings when compiling fails.
- return true;
-
- addException(exception);
- return true;
- }
-
- public boolean visit(FunctionInvocation node) {
- if (!isSelected(node))
- return false;
- return handleExceptions(node.resolveMethodBinding(), node.getAST());
- }
-
- public boolean visit(SuperMethodInvocation node) {
- if (!isSelected(node))
- return false;
- return handleExceptions(node.resolveMethodBinding(), node.getAST());
- }
-
- public boolean visit(ClassInstanceCreation node) {
- if (!isSelected(node))
- return false;
- return handleExceptions(node.resolveConstructorBinding(), node.getAST());
- }
-
- public boolean visit(ConstructorInvocation node) {
- if (!isSelected(node))
- return false;
- return handleExceptions(node.resolveConstructorBinding(), node.getAST());
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- if (!isSelected(node))
- return false;
- return handleExceptions(node.resolveConstructorBinding(), node.getAST());
- }
-
- private boolean handleExceptions(IFunctionBinding binding, AST ast) {
- return true;
- }
-
- private boolean isSelected(ASTNode node) {
- return fSelection.getVisitSelectionMode(node) == Selection.SELECTED;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ISurroundWithTryCatchQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ISurroundWithTryCatchQuery.java
deleted file mode 100644
index 2c4350fa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/ISurroundWithTryCatchQuery.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-public interface ISurroundWithTryCatchQuery {
-
- public boolean catchRuntimeException();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/LocalDeclarationAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/LocalDeclarationAnalyzer.java
deleted file mode 100644
index 70bf7b77..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/LocalDeclarationAnalyzer.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-
-
-public class LocalDeclarationAnalyzer extends ASTVisitor {
-
- private Selection fSelection;
- private List fAffectedLocals;
-
- public static VariableDeclaration[] perform(BodyDeclaration parent, Selection selection) {
- LocalDeclarationAnalyzer analyzer= new LocalDeclarationAnalyzer(selection);
- parent.accept(analyzer);
- return (VariableDeclaration[]) analyzer.fAffectedLocals.toArray(new VariableDeclaration[analyzer.fAffectedLocals.size()]);
- }
-
- private LocalDeclarationAnalyzer(Selection selection) {
- fSelection= selection;
- fAffectedLocals= new ArrayList(1);
- }
-
- public boolean visit(SimpleName node) {
- IVariableBinding binding= null;
- if (node.isDeclaration() || !considerNode(node) || (binding= ASTNodes.getLocalVariableBinding(node)) == null)
- return false;
- handleReferenceToLocal(node, binding);
- return true;
- }
-
- private boolean considerNode(ASTNode node) {
- return fSelection.getVisitSelectionMode(node) == Selection.AFTER;
- }
-
- private void handleReferenceToLocal(SimpleName node, IVariableBinding binding) {
- VariableDeclaration declaration= ASTNodes.findVariableDeclaration(binding, node);
- if (declaration != null && fSelection.covers(declaration))
- addLocalDeclaration(declaration);
- }
-
- private void addLocalDeclaration(VariableDeclaration declaration) {
- if (!fAffectedLocals.contains(declaration))
- fAffectedLocals.add(declaration);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithAnalyzer.java
deleted file mode 100644
index 5c6a75cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithAnalyzer.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.Message;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.CodeAnalyzer;
-
-public class SurroundWithAnalyzer extends CodeAnalyzer {
-
- private VariableDeclaration[] fLocals;
-
- public SurroundWithAnalyzer(IJavaScriptUnit cunit, Selection selection) throws JavaScriptModelException {
- super(cunit, selection, false);
- }
-
- public Statement[] getSelectedStatements() {
- if (hasSelectedNodes()) {
- return (Statement[])internalGetSelectedNodes().toArray(new Statement[internalGetSelectedNodes().size()]);
- } else {
- return new Statement[0];
- }
- }
-
- public VariableDeclaration[] getAffectedLocals() {
- return fLocals;
- }
-
- public BodyDeclaration getEnclosingBodyDeclaration() {
- ASTNode node= getFirstSelectedNode();
- if (node == null)
- return null;
- return (BodyDeclaration)ASTNodes.getParent(node, BodyDeclaration.class);
- }
-
- protected boolean handleSelectionEndsIn(ASTNode node) {
- return true;
- }
-
- public void endVisit(JavaScriptUnit node) {
- postProcessSelectedNodes(internalGetSelectedNodes());
- BodyDeclaration enclosingNode= null;
- superCall: {
- if (getStatus().hasFatalError())
- break superCall;
- if (!hasSelectedNodes()) {
- ASTNode coveringNode= getLastCoveringNode();
- if (coveringNode instanceof Block) {
- Block block= (Block)coveringNode;
- Message[] messages= ASTNodes.getMessages(block, ASTNodes.NODE_ONLY);
- if (messages.length > 0) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_compile_errors,
- JavaStatusContext.create(getCompilationUnit(), block));
- break superCall;
- }
- }
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotCover);
- break superCall;
- }
- enclosingNode= (BodyDeclaration)ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
- if (!(enclosingNode instanceof FunctionDeclaration) && !(enclosingNode instanceof Initializer)) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotContain);
- break superCall;
- }
- if (!onlyStatements()) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_onlyStatements);
- }
- fLocals= LocalDeclarationAnalyzer.perform(enclosingNode, getSelection());
- }
- super.endVisit(node);
- }
-
- public void endVisit(SuperConstructorInvocation node) {
- if (getSelection().getEndVisitSelectionMode(node) == Selection.SELECTED) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_cannotHandleSuper, JavaStatusContext.create(fCUnit, node));
- }
- super.endVisit(node);
- }
-
- public void endVisit(ConstructorInvocation node) {
- if (getSelection().getEndVisitSelectionMode(node) == Selection.SELECTED) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_cannotHandleThis, JavaStatusContext.create(fCUnit, node));
- }
- super.endVisit(node);
- }
-
- protected void postProcessSelectedNodes(List selectedNodes) {
- if (selectedNodes == null || selectedNodes.size() == 0)
- return;
- if (selectedNodes.size() == 1) {
- ASTNode node= (ASTNode)selectedNodes.get(0);
- if (node instanceof Expression && node.getParent() instanceof ExpressionStatement) {
- selectedNodes.clear();
- selectedNodes.add(node.getParent());
- }
- }
- }
-
- private boolean onlyStatements() {
- ASTNode[] nodes= getSelectedNodes();
- for (int i= 0; i < nodes.length; i++) {
- if (!(nodes[i] instanceof Statement))
- return false;
- }
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java
deleted file mode 100644
index 25b313ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class SurroundWithTryCatchAnalyzer extends SurroundWithAnalyzer {
-
-
- private ISurroundWithTryCatchQuery fQuery;
- private ITypeBinding[] fExceptions;
-
- public SurroundWithTryCatchAnalyzer(IJavaScriptUnit unit, Selection selection, ISurroundWithTryCatchQuery query) throws JavaScriptModelException {
- super(unit, selection);
- fQuery= query;
- }
-
- public ITypeBinding[] getExceptions() {
- return fExceptions;
- }
-
- public void endVisit(JavaScriptUnit node) {
- BodyDeclaration enclosingNode= null;
- if (!getStatus().hasFatalError() && hasSelectedNodes())
- enclosingNode= (BodyDeclaration)ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
-
- super.endVisit(node);
- if (enclosingNode != null && !getStatus().hasFatalError()) {
- fExceptions= ExceptionAnalyzer.perform(enclosingNode, getSelection());
- if (fExceptions == null || fExceptions.length == 0) {
- if (fQuery == null) {
- invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_noUncaughtExceptions);
- } else if (fQuery.catchRuntimeException()) {
- fExceptions= new ITypeBinding[] {node.getAST().resolveWellKnownType("java.lang.RuntimeException")}; //$NON-NLS-1$
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
deleted file mode 100644
index cf6d373d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.surround;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IExtendedModifier;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.CodeScopeBuilder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Surround a set of statements with a try/catch block.
- *
- * Special case:
- *
- * URL url= file.toURL();
- *
- * In this case the variable declaration statement gets convert into a
- * declaration without initializer. So the body of the try/catch block
- * only consists of new assignments. In this case we can't move the
- * selected nodes (e.g. the declaration) into the try block.
- */
-public class SurroundWithTryCatchRefactoring extends Refactoring {
-
- private Selection fSelection;
- private ISurroundWithTryCatchQuery fQuery;
- private SurroundWithTryCatchAnalyzer fAnalyzer;
- private boolean fLeaveDirty;
-
- private IJavaScriptUnit fCUnit;
- private JavaScriptUnit fRootNode;
- private ASTRewrite fRewriter;
- private ImportRewrite fImportRewrite;
- private CodeScopeBuilder.Scope fScope;
- private ASTNode[] fSelectedNodes;
-
- private SurroundWithTryCatchRefactoring(IJavaScriptUnit cu, Selection selection, ISurroundWithTryCatchQuery query) {
- fCUnit= cu;
- fSelection= selection;
- fQuery= query;
- fLeaveDirty= false;
- }
-
- public static SurroundWithTryCatchRefactoring create(IJavaScriptUnit cu, ITextSelection selection, ISurroundWithTryCatchQuery query) {
- return new SurroundWithTryCatchRefactoring(cu, Selection.createFromStartLength(selection.getOffset(), selection.getLength()), query);
- }
-
- public static SurroundWithTryCatchRefactoring create(IJavaScriptUnit cu, int offset, int length, ISurroundWithTryCatchQuery query) {
- return new SurroundWithTryCatchRefactoring(cu, Selection.createFromStartLength(offset, length), query);
- }
-
- public void setLeaveDirty(boolean leaveDirty) {
- fLeaveDirty= leaveDirty;
- }
-
- public boolean stopExecution() {
- if (fAnalyzer == null)
- return true;
- ITypeBinding[] exceptions= fAnalyzer.getExceptions();
- return exceptions == null || exceptions.length == 0;
- }
-
- /* non Java-doc
- * @see IRefactoring#getName()
- */
- public String getName() {
- return RefactoringCoreMessages.SurroundWithTryCatchRefactoring_name;
- }
-
- public RefactoringStatus checkActivationBasics(JavaScriptUnit rootNode) throws JavaScriptModelException {
- RefactoringStatus result= new RefactoringStatus();
- fRootNode= rootNode;
-
- fAnalyzer= new SurroundWithTryCatchAnalyzer(fCUnit, fSelection, fQuery);
- fRootNode.accept(fAnalyzer);
- result.merge(fAnalyzer.getStatus());
- return result;
- }
-
-
- /*
- * @see Refactoring#checkActivation(IProgressMonitor)
- */
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- JavaScriptUnit rootNode= new RefactoringASTParser(AST.JLS3).parse(fCUnit, true, pm);
- return checkActivationBasics(rootNode);
- }
-
- /*
- * @see Refactoring#checkInput(IProgressMonitor)
- */
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- return Checks.validateModifiesFiles(
- ResourceUtil.getFiles(new IJavaScriptUnit[]{fCUnit}),
- getValidationContext());
- }
-
- /* non Java-doc
- * @see IRefactoring#createChange(IProgressMonitor)
- */
- public Change createChange(IProgressMonitor pm) throws CoreException {
- final String NN= ""; //$NON-NLS-1$
- if (pm == null) pm= new NullProgressMonitor();
- pm.beginTask(NN, 2);
- // This is cheap since the compilation unit is already open in a editor.
- IPath path= getFile().getFullPath();
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- try {
- bufferManager.connect(path, LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- IDocument document= bufferManager.getTextFileBuffer(path, LocationKind.IFILE).getDocument();
- final CompilationUnitChange result= new CompilationUnitChange(getName(), fCUnit);
- if (fLeaveDirty)
- result.setSaveMode(TextFileChange.LEAVE_DIRTY);
- MultiTextEdit root= new MultiTextEdit();
- result.setEdit(root);
- fRewriter= ASTRewrite.create(fAnalyzer.getEnclosingBodyDeclaration().getAST());
- fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(
- fAnalyzer.getSelectedNodes(), document, fSelection.getOffset(), fSelection.getLength()));
- fImportRewrite= StubUtility.createImportRewrite(fRootNode, true);
-
- fScope= CodeScopeBuilder.perform(fAnalyzer.getEnclosingBodyDeclaration(), fSelection).
- findScope(fSelection.getOffset(), fSelection.getLength());
- fScope.setCursor(fSelection.getOffset());
-
- fSelectedNodes= fAnalyzer.getSelectedNodes();
-
- createTryCatchStatement(document);
-
- if (fImportRewrite.hasRecordedChanges()) {
- TextEdit edit= fImportRewrite.rewriteImports(null);
- root.addChild(edit);
- result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] {edit} ));
- }
- TextEdit change= fRewriter.rewriteAST(document, fCUnit.getJavaScriptProject().getOptions(true));
- root.addChild(change);
- result.addTextEditGroup(new TextEditGroup(NN, new TextEdit[] {change} ));
- return result;
- } catch (BadLocationException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- e.getMessage(), e));
- } finally {
- bufferManager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(pm, 1));
- pm.done();
- }
- }
-
- private AST getAST() {
- return fRootNode.getAST();
- }
-
- private void createTryCatchStatement(IDocument document) throws CoreException, BadLocationException {
- String lineDelimiter= document.getLineDelimiter(0);
- List result= new ArrayList(1);
- TryStatement tryStatement= getAST().newTryStatement();
- ITypeBinding[] exceptions= fAnalyzer.getExceptions();
- for (int i= 0; i < exceptions.length; i++) {
- ITypeBinding exception= exceptions[i];
- String type= fImportRewrite.addImport(exception);
- CatchClause catchClause= getAST().newCatchClause();
- tryStatement.catchClauses().add(catchClause);
- SingleVariableDeclaration decl= getAST().newSingleVariableDeclaration();
- String varName= StubUtility.getExceptionVariableName(fCUnit.getJavaScriptProject());
-
- String name= fScope.createName(varName, false);
- decl.setName(getAST().newSimpleName(name));
- decl.setType(ASTNodeFactory.newType(getAST(), type));
- catchClause.setException(decl);
- Statement st= getCatchBody(type, name, lineDelimiter);
- if (st != null) {
- catchClause.getBody().statements().add(st);
- }
- }
- List variableDeclarations= getSpecialVariableDeclarationStatements();
- ListRewrite statements= fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
- boolean selectedNodeRemoved= false;
- ASTNode expressionStatement= null;
- for (int i= 0; i < fSelectedNodes.length; i++) {
- ASTNode node= fSelectedNodes[i];
- if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
- AST ast= getAST();
- VariableDeclarationStatement statement= (VariableDeclarationStatement)node;
- // Create a copy and remove the initializer
- VariableDeclarationStatement copy= (VariableDeclarationStatement)ASTNode.copySubtree(ast, statement);
- List modifiers= copy.modifiers();
- for (Iterator iter= modifiers.iterator(); iter.hasNext();) {
- IExtendedModifier modifier= (IExtendedModifier) iter.next();
- if (modifier.isModifier() && Modifier.isFinal(((Modifier)modifier).getKeyword().toFlagValue())) {
- iter.remove();
- }
- }
- List fragments= copy.fragments();
- for (Iterator iter= fragments.iterator(), original= statement.fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)iter.next();
- IVariableBinding binding= ((VariableDeclarationFragment)original.next()).resolveBinding();
- // If we want to initialize the new local then we should do a flow analysis upfront
- // to decide if the first access is a read or write.
- if (true /* binding == null */) {
- fragment.setInitializer(null);
- } else {
- fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, binding.getType()));
- }
- }
- JavaScriptUnit root= (JavaScriptUnit)statement.getRoot();
- int extendedStart= root.getExtendedStartPosition(statement);
- // we have a leading comment and the comment is covered by the selection
- if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) {
- String commentToken= document.get(extendedStart, statement.getStartPosition() - extendedStart);
- commentToken= Strings.trimTrailingTabsAndSpaces(commentToken);
- Type type= statement.getType();
- String typeName= document.get(type.getStartPosition(), type.getLength());
- copy.setType((Type)fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
- }
- result.add(copy);
- // convert the fragments into expression statements
- fragments= statement.fragments();
- if (!fragments.isEmpty()) {
- List newExpressionStatements= new ArrayList();
- for (Iterator iter= fragments.iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)iter.next();
- Expression initializer= fragment.getInitializer();
- if (initializer != null) {
- Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide((Expression)fRewriter.createCopyTarget(fragment.getName()));
- assignment.setRightHandSide((Expression)fRewriter.createCopyTarget(initializer));
- newExpressionStatements.add(ast.newExpressionStatement(assignment));
- }
- }
- if (!newExpressionStatements.isEmpty()) {
- if (fSelectedNodes.length == 1) {
- expressionStatement= fRewriter.createGroupNode((ASTNode[])newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
- } else {
- fRewriter.replace(
- statement,
- fRewriter.createGroupNode((ASTNode[])newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])),
- null);
- }
- } else {
- fRewriter.remove(statement, null);
- selectedNodeRemoved= true;
- }
- } else {
- fRewriter.remove(statement, null);
- selectedNodeRemoved= true;
- }
- }
- }
- result.add(tryStatement);
- ASTNode replacementNode;
- if (result.size() == 1) {
- replacementNode= (ASTNode)result.get(0);
- } else {
- replacementNode= fRewriter.createGroupNode((ASTNode[])result.toArray(new ASTNode[result.size()]));
- }
- if (fSelectedNodes.length == 1) {
- if (expressionStatement != null) {
- statements.insertLast(expressionStatement, null);
- } else {
- if (!selectedNodeRemoved)
- statements.insertLast(fRewriter.createMoveTarget(fSelectedNodes[0]), null);
- }
- fRewriter.replace(fSelectedNodes[0], replacementNode, null);
- } else {
- ListRewrite source= fRewriter.getListRewrite(
- fSelectedNodes[0].getParent(),
- (ChildListPropertyDescriptor)fSelectedNodes[0].getLocationInParent());
- ASTNode toMove= source.createMoveTarget(
- fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1],
- replacementNode, null);
- statements.insertLast(toMove, null);
- }
- }
-
- private List getSpecialVariableDeclarationStatements() {
- List result= new ArrayList(3);
- VariableDeclaration[] locals= fAnalyzer.getAffectedLocals();
- for (int i= 0; i < locals.length; i++) {
- ASTNode parent= locals[i].getParent();
- if (parent instanceof VariableDeclarationStatement && !result.contains(parent))
- result.add(parent);
- }
- return result;
-
- }
-
- private Statement getCatchBody(String type, String name, String lineSeparator) throws CoreException {
- String s= StubUtility.getCatchBodyContent(fCUnit, type, name, fSelectedNodes[0], lineSeparator);
- if (s == null) {
- return null;
- } else {
- return (Statement)fRewriter.createStringPlaceholder(s, ASTNode.RETURN_STATEMENT);
- }
- }
-
- private IFile getFile() {
- return (IFile) fCUnit.getPrimary().getResource();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java
deleted file mode 100644
index 5ed7a6ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-/**
- * Interface for refactorings which provide a comment for the history.
- *
- *
- */
-public interface ICommentProvider {
-
- /**
- * Performs a dynamic check whether this refactoring object is capable of
- * accepting user comments to be stored in the refactoring history. The
- * return value of this method may change according to the state of the
- * refactoring.
- */
- public boolean canEnableComment();
-
- /**
- * If <code>canEnableComment</code> returns <code>true</code>, then
- * this method is used to ask the refactoring object for the comment
- * associated with the refactoring. This call can be ignored if
- * <code>canEnableComment</code> returns <code>false</code>.
- *
- * @return the comment, or <code>null</code>
- */
- public String getComment();
-
- /**
- * If <code>canEnableComment</code> returns <code>true</code>, then
- * this method may be called to set the comment associated with the
- * refactoring. This call can be ignored if <code>canEnableComment</code>
- * returns <code>false</code>.
- *
- * @param comment
- * the comment to set, or <code>null</code>
- */
- public void setComment(String comment);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java
deleted file mode 100644
index e900fae8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-/**
- * Interface for refactorings which are able to create
- * appropriate delegates for the refactored elements.
- *
- *
- *
- */
-public interface IDelegateUpdating {
-
- /**
- * Performs a dynamic check whether this refactoring object is capable of
- * creating appropriate delegates for the refactored elements. The
- * return value of this method may change according to the state of the
- * refactoring.
- */
- public boolean canEnableDelegateUpdating();
-
- /**
- * If <code>canEnableDelegateUpdating</code> returns
- * <code>true</code>, then this method is used to ask the refactoring
- * object whether delegates will be created.
- * This call can be ignored if <code>canEnableDelegateUpdating</code>
- * returns <code>false</code>.
- */
- public boolean getDelegateUpdating();
-
- /**
- * Returns the title of the preference to update delegates in the user
- * interface.
- *
- * @param plural
- * <code>true</code> if several delegates are created,
- * <code>false</code> otherwise
- * @return the non-null string denoting the title
- */
- public String getDelegateUpdatingTitle(boolean plural);
-
- /**
- * If <code>canEnableDelegateUpdating</code> returns
- * <code>true</code>, then this method is used to ask the refactoring
- * object whether delegates will be deprecated.
- * This call can be ignored if <code>canEnableDelegateUpdating</code>
- * returns <code>false</code>.
- */
- public boolean getDeprecateDelegates();
-
- /**
- * If <code>canEnableDelegateUpdating</code> returns
- * <code>true</code>, then this method may be called to set whether
- * to create delegates.
- * This call can be ignored if <code>canEnableDelegateUpdating</code>
- * returns <code>false</code>.
- */
- public void setDelegateUpdating(boolean updating);
-
- /**
- * If <code>canEnableDelegateUpdating</code> returns
- * <code>true</code>, then this method may be called to set whether
- * to deprecate delegates.
- * This call can be ignored if <code>canEnableDelegateUpdating</code>
- * returns <code>false</code>.
- */
- public void setDeprecateDelegates(boolean deprecate);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/INameUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/INameUpdating.java
deleted file mode 100644
index 2dc703fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/INameUpdating.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-
-/**
- * Represents processors in the JDT space that rename elements.
- */
-public interface INameUpdating {
-
- /**
- * Sets new name for the entity that this refactoring is working on.
- */
- public void setNewElementName(String newName);
-
- /**
- * Get the name for the entity that this refactoring is working on.
- */
- public String getNewElementName();
-
- /**
- * Gets the current name of the entity that this refactoring is working on.
- */
- public String getCurrentElementName();
-
- /**
- * Gets the original elements. Since an <code>INameUpdating</code> only renames one element,
- * this method must return an array containing exactly one element.
- * @return an array containing exactly one element
- * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#getElements()
- */
- public Object[] getElements();
-
- /**
- * Gets the element after renaming, or <code>null</code> if not available.
- */
- public Object getNewElement() throws CoreException;
-
- /**
- * Checks if the new name is valid for the entity that this refactoring renames.
- */
- public RefactoringStatus checkNewElementName(String newName) throws CoreException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IQualifiedNameUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IQualifiedNameUpdating.java
deleted file mode 100644
index 6e4bb327..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IQualifiedNameUpdating.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-public interface IQualifiedNameUpdating {
-
- /**
- * Performs a dynamic check whether this refactoring object is capable of
- * updating qualified names in non Java files. The return value of this
- * method may change according to the state of the refactoring.
- */
- public boolean canEnableQualifiedNameUpdating();
-
- /**
- * If <code>canEnableQualifiedNameUpdating</code> returns <code>true</code>,
- * then this method is used to ask the refactoring object whether references
- * in non Java files should be updated. This call can be ignored if
- * <code>canEnableQualifiedNameUpdating</code> returns <code>false</code>.
- */
- public boolean getUpdateQualifiedNames();
-
- /**
- * If <code>canEnableQualifiedNameUpdating</code> returns <code>true</code>,
- * then this method is used to inform the refactoring object whether
- * references in non Java files should be updated. This call can be ignored
- * if <code>canEnableQualifiedNameUpdating</code> returns <code>false</code>.
- */
- public void setUpdateQualifiedNames(boolean update);
-
- public String getFilePatterns();
-
- public void setFilePatterns(String patterns);
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IReferenceUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IReferenceUpdating.java
deleted file mode 100644
index d389e4c7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IReferenceUpdating.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-public interface IReferenceUpdating {
-
- /**
- * Checks if this refactoring object is capable of updating references to the renamed element.
- */
- public boolean canEnableUpdateReferences();
-
- /**
- * If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
- * inform the refactoring object whether references should be updated.
- * This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
- */
- public void setUpdateReferences(boolean update);
-
- /**
- * If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
- * ask the refactoring object whether references should be updated.
- * This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
- */
- public boolean getUpdateReferences();
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java
deleted file mode 100644
index 29f12012..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-
-/**
- * Interface for refactorings which can be initialized when run as a refactoring
- * script.
- *
- *
- */
-public interface IScriptableRefactoring {
-
- /**
- * Initializes the refactoring with the refactoring arguments.
- *
- * @param arguments
- * the refactoring arguments
- * @return an object describing the status of the initialization. If the
- * status has severity <code>FATAL_ERROR</code>, the refactoring
- * will not be executed.
- */
- public RefactoringStatus initialize(RefactoringArguments arguments);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java
deleted file mode 100644
index 3bb2db0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-/**
- * Interface implemented by processors able to rename similar declarations.
- *
- *
- */
-public interface ISimilarDeclarationUpdating {
-
- /**
- * Checks if this refactoring object is capable of updating similar declarations
- * of the renamed element.
- *
- * This can be disabled globally by setting the product configuration property
- * "org.eclipse.wst.jsdt.ui.refactoring.handlesSimilarDeclarations" to "false".
- */
- public boolean canEnableSimilarDeclarationUpdating();
-
- /**
- * If <code>canEnableSimilarElementUpdating</code> returns
- * <code>true</code>, then this method is used to inform the refactoring
- * object whether similar declarations should be updated. This call can be
- * ignored if <code>canEnableSimilarElementUpdating</code> returns
- * <code>false</code>.
- */
- public void setUpdateSimilarDeclarations(boolean update);
-
- /**
- * If <code>canEnableSimilarElementUpdating</code> returns
- * <code>true</code>, then this method is used to ask the refactoring
- * object whether similar declarations should be updated. This call can be
- * ignored if <code>canEnableSimilarElementUpdating</code> returns
- * <code>false</code>.
- */
- public boolean getUpdateSimilarDeclarations();
-
- /**
- * If <code>canEnableSimilarElementUpdating</code> returns
- * <code>true</code>, then this method is used to set the match strategy
- * for determining similarly named elements.
- *
- * @param selectedStrategy one of the STRATEGY_* constants in {@link org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor}
- */
- public void setMatchStrategy(int selectedStrategy);
-
- /**
- * If <code>canEnableSimilarElementUpdating</code> returns
- * <code>true</code>, then this method is used to ask the refactoring
- * object which match strategy is used for determining similar elements.
- *
- * @return one of the STRATEGY_* constants in {@link org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor}
- */
- public int getMatchStrategy();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ITextUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ITextUpdating.java
deleted file mode 100644
index 1c226ab3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ITextUpdating.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.tagging;
-
-public interface ITextUpdating {
-
- /**
- * Performs a dynamic check whether this refactoring object is capable of
- * updating references to the renamed element.
- */
- public boolean canEnableTextUpdating();
-
- /**
- * If <code>canEnableTextUpdating</code> returns <code>true</code>,
- * then this method is used to ask the refactoring object whether references
- * in regular (non JavaDoc) comments and string literals should be updated.
- * This call can be ignored if <code>canEnableTextUpdating</code> returns
- * <code>false</code>.
- */
- public boolean getUpdateTextualMatches();
-
- /**
- * If <code>canEnableTextUpdating</code> returns <code>true</code>,
- * then this method is used to inform the refactoring object whether references
- * in regular (non JavaDoc) comments and string literals should be updated.
- * This call can be ignored if <code>canEnableTextUpdating</code> returns
- * <code>false</code>.
- */
- public void setUpdateTextualMatches(boolean update);
-
- /**
- * Returns the current name of the element to be renamed.
- *
- * @return the current name of the element to be renamed
- */
- public String getCurrentElementName();
-
- /**
- * Returns the current qualifier of the element to be renamed.
- *
- * @return the current qualifier of the element to be renamed
- */
- public String getCurrentElementQualifier();
-
- /**
- * Returns the new name of the element
- *
- * @return the new element name
- */
- public String getNewElementName();
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ASTCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ASTCreator.java
deleted file mode 100644
index 3c4ea31b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ASTCreator.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-
-
-public class ASTCreator {
-
- public static final String CU_PROPERTY= "org.eclipse.wst.jsdt.ui.refactoring.cu"; //$NON-NLS-1$
-
- private ASTCreator() {
- //private
- }
-
- public static JavaScriptUnit createAST(IJavaScriptUnit cu, WorkingCopyOwner workingCopyOwner) {
- JavaScriptUnit cuNode= getCuNode(workingCopyOwner, cu);
- cuNode.setProperty(CU_PROPERTY, cu);
- return cuNode;
- }
-
- private static JavaScriptUnit getCuNode(WorkingCopyOwner workingCopyOwner, IJavaScriptUnit cu) {
- ASTParser p = ASTParser.newParser(AST.JLS3);
- p.setSource(cu);
- p.setResolveBindings(true);
- p.setWorkingCopyOwner(workingCopyOwner);
- p.setCompilerOptions(RefactoringASTParser.getCompilerOptions(cu));
- return (JavaScriptUnit) p.createAST(null);
- }
-
- public static IJavaScriptUnit getCu(ASTNode node) {
- Object property= node.getRoot().getProperty(CU_PROPERTY);
- if (property instanceof IJavaScriptUnit)
- return (IJavaScriptUnit)property;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompilationUnitRange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompilationUnitRange.java
deleted file mode 100644
index 50542411..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompilationUnitRange.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-
-public final class CompilationUnitRange {
-
- private final IJavaScriptUnit fCompilationUnit;
- private final ISourceRange fSourceRange;
-
- public CompilationUnitRange(IJavaScriptUnit unit, ISourceRange range) {
- Assert.isNotNull(unit);
- Assert.isNotNull(range);
- fCompilationUnit= unit;
- fSourceRange= range;
- }
-
- public CompilationUnitRange(IJavaScriptUnit unit, ASTNode node) {
- this(unit, new SourceRange(node));
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- public ISourceRange getSourceRange() {
- return fSourceRange;
- }
-
- //rootNode must be the ast root for fCompilationUnit
- public ASTNode getNode(JavaScriptUnit rootNode) {
- NodeFinder finder= new NodeFinder(fSourceRange.getOffset(), fSourceRange.getLength());
- rootNode.accept(finder);
- ASTNode result= finder.getCoveringNode();
- if (result != null)
- return result;
- return finder.getCoveredNode();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "(" + fSourceRange.toString() + " in " + fCompilationUnit.getElementName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!(obj instanceof CompilationUnitRange))
- return false;
- CompilationUnitRange other= (CompilationUnitRange)obj;
- return fCompilationUnit.equals(other.fCompilationUnit) && fSourceRange.equals(other.fSourceRange);
- }
-
- public int hashCode() {
- return (37 * fCompilationUnit.hashCode()) ^ fSourceRange.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompositeOrTypeConstraint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompositeOrTypeConstraint.java
deleted file mode 100644
index 37dfe855..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/CompositeOrTypeConstraint.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-
-
-public class CompositeOrTypeConstraint implements ITypeConstraint{
-
- private final ITypeConstraint[] fConstraints;
-
- /* package */ CompositeOrTypeConstraint(ITypeConstraint[] constraints){
- Assert.isNotNull(constraints);
- fConstraints= sort(getCopy(constraints));
- }
-
- private static ITypeConstraint[] getCopy(ITypeConstraint[] constraints) {
- List l= Arrays.asList(constraints);
- return (ITypeConstraint[]) l.toArray(new ITypeConstraint[l.size()]);
- }
-
- private static ITypeConstraint[] sort(ITypeConstraint[] constraints) {
- //TODO bogus to sort by toString - will have to come up with something better
- Arrays.sort(constraints, new Comparator(){
- public int compare(Object o1, Object o2) {
- return o2.toString().compareTo(o1.toString());
- }
- });
- return constraints;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.experiments.ITypeConstraint#toResolvedString()
- */
- public String toResolvedString() {
- StringBuffer buff= new StringBuffer();
- for (int i= 0; i < fConstraints.length; i++) {
- ITypeConstraint constraint= fConstraints[i];
- if (i > 0)
- buff.append(" or "); //$NON-NLS-1$
- buff.append(constraint.toResolvedString());
- }
- return buff.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.experiments.ITypeConstraint#isSimpleTypeConstraint()
- */
- public boolean isSimpleTypeConstraint() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer buff= new StringBuffer();
- for (int i= 0; i < fConstraints.length; i++) {
- ITypeConstraint constraint= fConstraints[i];
- if (i > 0)
- buff.append(" or "); //$NON-NLS-1$
- buff.append(constraint.toString());
- }
- return buff.toString();
- }
-
- public ITypeConstraint[] getConstraints() {
- return fConstraints;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCollector.java
deleted file mode 100644
index 67361654..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCollector.java
+++ /dev/null
@@ -1,622 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-
-
-public final class ConstraintCollector extends ASTVisitor {
-
- private final ConstraintCreator fCreator;
- private final Set fConstraints;
-
- public ConstraintCollector() {
- this(new FullConstraintCreator());
- }
-
- public ConstraintCollector(ConstraintCreator creator) {
- Assert.isNotNull(creator);
- fCreator= creator;
- fConstraints= new LinkedHashSet();
- }
-
- private void add(ITypeConstraint[] constraints){
- fConstraints.addAll(Arrays.asList(constraints));
- }
-
- public void clear(){
- fConstraints.clear();
- }
-
- public ITypeConstraint[] getConstraints(){
- return (ITypeConstraint[]) fConstraints.toArray(new ITypeConstraint[fConstraints.size()]);
- }
-
- //------------------------- visit methods -------------------------//
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayAccess)
- */
- public boolean visit(ArrayAccess node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayCreation)
- */
- public boolean visit(ArrayCreation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayInitializer)
- */
- public boolean visit(ArrayInitializer node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayType)
- */
- public boolean visit(ArrayType node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Assignment)
- */
- public boolean visit(Assignment node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Block)
- */
- public boolean visit(Block node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BreakStatement)
- */
- public boolean visit(BreakStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.CatchClause)
- */
- public boolean visit(CatchClause node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.CharacterLiteral)
- */
- public boolean visit(RegularExpressionLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation)
- */
- public boolean visit(ClassInstanceCreation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit)
- */
- public boolean visit(JavaScriptUnit node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConditionalExpression)
- */
- public boolean visit(ConditionalExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public boolean visit(ConstructorInvocation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ContinueStatement)
- */
- public boolean visit(ContinueStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.DoStatement)
- */
- public boolean visit(DoStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.EmptyStatement)
- */
- public boolean visit(EmptyStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ExpressionStatement)
- */
- public boolean visit(ExpressionStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldAccess)
- */
- public boolean visit(FieldAccess node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldDeclaration)
- */
- public boolean visit(FieldDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ForStatement)
- */
- public boolean visit(ForStatement node) {
- add(fCreator.create(node));
- return true;
- }
- public boolean visit(FunctionExpression node) {
- add(fCreator.create(node));
- return true;
- }
- public boolean visit(ObjectLiteral node) {
- add(fCreator.create(node));
- return true;
- }
- public boolean visit(ObjectLiteralField node) {
- add(fCreator.create(node));
- return true;
- }
- public boolean visit(ForInStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.IfStatement)
- */
- public boolean visit(IfStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ImportDeclaration)
- */
- public boolean visit(ImportDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.InfixExpression)
- */
- public boolean visit(InfixExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Initializer)
- */
- public boolean visit(Initializer node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.InstanceofExpression)
- */
- public boolean visit(InstanceofExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Javadoc)
- */
- public boolean visit(JSdoc node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.LabeledStatement)
- */
- public boolean visit(LabeledStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- public boolean visit(ListExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public boolean visit(FunctionInvocation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.NullLiteral)
- */
- public boolean visit(NullLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- public boolean visit(UndefinedLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PackageDeclaration)
- */
- public boolean visit(PackageDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression)
- */
- public boolean visit(ParenthesizedExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PostfixExpression)
- */
- public boolean visit(PostfixExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PrefixExpression)
- */
- public boolean visit(PrefixExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PrimitiveType)
- */
- public boolean visit(PrimitiveType node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.QualifiedName)
- */
- public boolean visit(QualifiedName node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ReturnStatement)
- */
- public boolean visit(ReturnStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleName)
- */
- public boolean visit(SimpleName node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleType)
- */
- public boolean visit(SimpleType node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration)
- */
- public boolean visit(SingleVariableDeclaration node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.StringLiteral)
- */
- public boolean visit(StringLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation)
- */
- public boolean visit(SuperConstructorInvocation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperFieldAccess)
- */
- public boolean visit(SuperFieldAccess node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation)
- */
- public boolean visit(SuperMethodInvocation node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SwitchCase)
- */
- public boolean visit(SwitchCase node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SwitchStatement)
- */
- public boolean visit(SwitchStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThisExpression)
- */
- public boolean visit(ThisExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThrowStatement)
- */
- public boolean visit(ThrowStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TryStatement)
- */
- public boolean visit(TryStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeDeclaration)
- */
- public boolean visit(TypeDeclaration node) {
- add(fCreator.create(node));
- return true;
-
- // TODO account for enums and annotations
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeLiteral)
- */
- public boolean visit(TypeLiteral node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression)
- */
- public boolean visit(VariableDeclarationExpression node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment)
- */
- public boolean visit(VariableDeclarationFragment node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement)
- */
- public boolean visit(VariableDeclarationStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.WhileStatement)
- */
- public boolean visit(WhileStatement node) {
- add(fCreator.create(node));
- return true;
- }
-
- public boolean visit(WithStatement node) {
- add(fCreator.create(node));
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCreator.java
deleted file mode 100644
index 37dde70e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintCreator.java
+++ /dev/null
@@ -1,533 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EmptyStatement;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionExpression;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.ListExpression;
-import org.eclipse.wst.jsdt.core.dom.NullLiteral;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.UndefinedLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-
-/**
- * Empty implementation of a creator - provided to allow subclasses to override only a subset of methods.
- * Subclass to provide constraint creation functionality.
- */
-public class ConstraintCreator {
-
- public static final ITypeConstraint[] EMPTY_ARRAY= new ITypeConstraint[0];
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration)
- */
- public ITypeConstraint[] create(AnonymousClassDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayAccess)
- */
- public ITypeConstraint[] create(ArrayAccess node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayCreation)
- */
- public ITypeConstraint[] create(ArrayCreation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayInitializer)
- */
- public ITypeConstraint[] create(ArrayInitializer node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayType)
- */
- public ITypeConstraint[] create(ArrayType node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Assignment)
- */
- public ITypeConstraint[] create(Assignment node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Block)
- */
- public ITypeConstraint[] create(Block node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BooleanLiteral)
- */
- public ITypeConstraint[] create(BooleanLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BreakStatement)
- */
- public ITypeConstraint[] create(BreakStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.CatchClause)
- */
- public ITypeConstraint[] create(CatchClause node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.CharacterLiteral)
- */
- public ITypeConstraint[] create(CharacterLiteral node) {
- return EMPTY_ARRAY;
- }
-
- public ITypeConstraint[] create(RegularExpressionLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation)
- */
- public ITypeConstraint[] create(ClassInstanceCreation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit)
- */
- public ITypeConstraint[] create(JavaScriptUnit node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConditionalExpression)
- */
- public ITypeConstraint[] create(ConditionalExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public ITypeConstraint[] create(ConstructorInvocation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ContinueStatement)
- */
- public ITypeConstraint[] create(ContinueStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.DoStatement)
- */
- public ITypeConstraint[] create(DoStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.EmptyStatement)
- */
- public ITypeConstraint[] create(EmptyStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ExpressionStatement)
- */
- public ITypeConstraint[] create(ExpressionStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldAccess)
- */
- public ITypeConstraint[] create(FieldAccess node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldDeclaration)
- */
- public ITypeConstraint[] create(FieldDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ForStatement)
- */
- public ITypeConstraint[] create(ForStatement node) {
- return EMPTY_ARRAY;
- }
- public ITypeConstraint[] create(ForInStatement node) {
- return EMPTY_ARRAY;
- }
- public ITypeConstraint[] create(FunctionExpression node) {
- return EMPTY_ARRAY;
- }
- public ITypeConstraint[] create(ObjectLiteral node) {
- return EMPTY_ARRAY;
- }
- public ITypeConstraint[] create(ObjectLiteralField node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.IfStatement)
- */
- public ITypeConstraint[] create(IfStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ImportDeclaration)
- */
- public ITypeConstraint[] create(ImportDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.InfixExpression)
- */
- public ITypeConstraint[] create(InfixExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Initializer)
- */
- public ITypeConstraint[] create(Initializer node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.InstanceofExpression)
- */
- public ITypeConstraint[] create(InstanceofExpression node) {
- return EMPTY_ARRAY;
- }
-
- public ITypeConstraint[] create(ListExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Javadoc)
- */
- public ITypeConstraint[] create(JSdoc node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.LabeledStatement)
- */
- public ITypeConstraint[] create(LabeledStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public ITypeConstraint[] create(FunctionDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public ITypeConstraint[] create(FunctionInvocation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.NullLiteral)
- */
- public ITypeConstraint[] create(NullLiteral node) {
- return EMPTY_ARRAY;
- }
-
- public ITypeConstraint[] create(UndefinedLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.NumberLiteral)
- */
- public ITypeConstraint[] create(NumberLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PackageDeclaration)
- */
- public ITypeConstraint[] create(PackageDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression)
- */
- public ITypeConstraint[] create(ParenthesizedExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PostfixExpression)
- */
- public ITypeConstraint[] create(PostfixExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PrefixExpression)
- */
- public ITypeConstraint[] create(PrefixExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.PrimitiveType)
- */
- public ITypeConstraint[] create(PrimitiveType node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.QualifiedName)
- */
- public ITypeConstraint[] create(QualifiedName node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ReturnStatement)
- */
- public ITypeConstraint[] create(ReturnStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleName)
- */
- public ITypeConstraint[] create(SimpleName node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleType)
- */
- public ITypeConstraint[] create(SimpleType node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration)
- */
- public ITypeConstraint[] create(SingleVariableDeclaration node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.StringLiteral)
- */
- public ITypeConstraint[] create(StringLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation)
- */
- public ITypeConstraint[] create(SuperConstructorInvocation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperFieldAccess)
- */
- public ITypeConstraint[] create(SuperFieldAccess node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation)
- */
- public ITypeConstraint[] create(SuperMethodInvocation node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SwitchCase)
- */
- public ITypeConstraint[] create(SwitchCase node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SwitchStatement)
- */
- public ITypeConstraint[] create(SwitchStatement node) {
- return EMPTY_ARRAY;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThisExpression)
- */
- public ITypeConstraint[] create(ThisExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThrowStatement)
- */
- public ITypeConstraint[] create(ThrowStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TryStatement)
- */
- public ITypeConstraint[] create(TryStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeDeclaration)
- */
- public ITypeConstraint[] create(TypeDeclaration node) {
- return EMPTY_ARRAY;
-
- // TODO account for enums and annotations
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement)
- */
- public ITypeConstraint[] create(TypeDeclarationStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeLiteral)
- */
- public ITypeConstraint[] create(TypeLiteral node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression)
- */
- public ITypeConstraint[] create(VariableDeclarationExpression node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment)
- */
- public ITypeConstraint[] create(VariableDeclarationFragment node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement)
- */
- public ITypeConstraint[] create(VariableDeclarationStatement node) {
- return EMPTY_ARRAY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.WhileStatement)
- */
- public ITypeConstraint[] create(WhileStatement node) {
- return EMPTY_ARRAY;
- }
-
- public ITypeConstraint[] create(WithStatement node) {
- return EMPTY_ARRAY;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintOperator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintOperator.java
deleted file mode 100644
index ac204403..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintOperator.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.Assert;
-
-
-public final class ConstraintOperator {
-
- private final String fOperatorString;
- private final int fOperatorCode;
-
- private static final int CODE_SUBTYPE= 0;
- private static final int CODE_EQUALS= 1;
- private static final int CODE_DEFINES= 2;
- private static final int CODE_STRICT_SUBTYPE= 3;
-
- private static final String STRING_SUBTYPE= "<=";//$NON-NLS-1$
- private static final String STRING_EQUALS= "==";//$NON-NLS-1$
- private static final String STRING_DEFINES= "=^=";//$NON-NLS-1$
- private static final String STRING_STRICT_SUBTYPE= "<";//$NON-NLS-1$
- private static final Collection fgOperatorStrings= new HashSet(Arrays.asList(new String[] {STRING_SUBTYPE, STRING_EQUALS, STRING_DEFINES, STRING_STRICT_SUBTYPE}));
-
- private static final ConstraintOperator fgSubtype= new ConstraintOperator(STRING_SUBTYPE, CODE_SUBTYPE);
- private static final ConstraintOperator fgEquals= new ConstraintOperator(STRING_EQUALS, CODE_EQUALS);
- private static final ConstraintOperator fgDefines= new ConstraintOperator(STRING_DEFINES, CODE_DEFINES);
- private static final ConstraintOperator fgStrictSubtype= new ConstraintOperator(STRING_STRICT_SUBTYPE, CODE_STRICT_SUBTYPE);
-
- public static ConstraintOperator createSubTypeOperator() {
- return fgSubtype;
- }
-
- public static ConstraintOperator createEqualsOperator() {
- return fgEquals;
- }
-
- public static ConstraintOperator createDefinesOperator() {
- return fgDefines;
- }
-
- public static ConstraintOperator createStrictSubtypeOperator() {
- return fgStrictSubtype;
- }
-
- private ConstraintOperator(String string, int code){
- Assert.isTrue(fgOperatorStrings.contains(string));
- Assert.isTrue(code == CODE_DEFINES || code == CODE_EQUALS || code == CODE_STRICT_SUBTYPE || code == CODE_SUBTYPE);
- fOperatorString= string;
- fOperatorCode= code;
- }
-
- public String getOperatorString(){
- return fOperatorString;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return getOperatorString();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (! (obj instanceof ConstraintOperator))
- return false;
- ConstraintOperator other= (ConstraintOperator)obj;
- return fOperatorCode == other.fOperatorCode;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return fOperatorString.hashCode();
- }
-
- public final boolean isSubtypeOperator() {
- return fOperatorCode == CODE_SUBTYPE;
- }
-
- public final boolean isStrictSubtypeOperator() {
- return fOperatorCode == CODE_STRICT_SUBTYPE;
- }
-
- public final boolean isEqualsOperator() {
- return fOperatorCode == CODE_EQUALS;
- }
-
- public final boolean isDefinesOperator() {
- return fOperatorCode == CODE_DEFINES;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariable.java
deleted file mode 100644
index f7220471..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariable.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.TypeRules;
-
-public abstract class ConstraintVariable {
- /**
- * The type binding, or <code>null</code>.
- */
- private final ITypeBinding fTypeBinding;
-
- /**
- * @param binding the type binding, or <code>null</code>
- */
- protected ConstraintVariable(ITypeBinding binding) {
- fTypeBinding= binding;
- }
-
- public boolean canBeAssignedTo(ConstraintVariable targetVariable) {
- if (fTypeBinding == null || targetVariable.fTypeBinding == null)
- return false;
- return TypeRules.canAssign(fTypeBinding, targetVariable.fTypeBinding);
- }
-
- public String toResolvedString() {
- if (fTypeBinding == null)
- return "<NULL BINDING>"; //$NON-NLS-1$
- return Bindings.asString(fTypeBinding);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return toResolvedString();
- }
-
- /**
- * @return the type binding or <code>null</code>
- */
- //TODO: rename to getTypeBinding()
- public ITypeBinding getBinding() {
- return fTypeBinding;
- }
-
- /**
- * For storing additional information associated with constraint variables.
- * Added in anticipation of the generics-related refactorings.
- */
- private Object fData;
-
- public Object getData(){
- return fData;
- }
-
- public void setData(Object data){
- fData= data;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariableFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariableFactory.java
deleted file mode 100644
index c49f257d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ConstraintVariableFactory.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-/**
- * Abstract Factory for the creation of ConstraintVariables. This default factory
- * ensures that no duplicate ConstraintVariables are created, so that Object.equals()
- * can be used to compare ConstraintVariables.
- */
-public class ConstraintVariableFactory implements IConstraintVariableFactory {
-
- private Map/*<IBinding,IBinding>*/ fBindingMap= new HashMap();
-
- private Map/*<IBinding + CompilationUnitRange,ExpressionVariable>*/ fExpressionMap= new Hashtable();
- private Map/*<Integer,ExpressionVariable>*/ fLiteralMap= new HashMap();
- private Map/*<CompilationUnitRange,TypeVariable>*/ fTypeVariableMap= new HashMap();
- private Map/*<String,DeclaringTypeVariable>*/ fDeclaringTypeVariableMap= new HashMap();
- private Map/*<String,ParameterTypeVariable>*/ fParameterMap= new HashMap();
- private Map/*<String,RawBindingVariable>*/ fRawBindingMap= new HashMap();
- private Map/*<String,ReturnTypeVariable>*/ fReturnVariableMap= new HashMap();
-
- public static final boolean REPORT= false;
- protected int nrCreated=0;
- protected int nrRetrieved=0;
-
- public int getNumCreated(){
- return nrCreated;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeExpressionVariable(org.eclipse.wst.jsdt.core.dom.Expression, org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IContext)
- */
- public ConstraintVariable makeExpressionOrTypeVariable(Expression expression,
- IContext context) {
- IBinding binding= ExpressionVariable.resolveBinding(expression);
-
- if (binding instanceof ITypeBinding){
- IJavaScriptUnit cu= ASTCreator.getCu(expression);
- Assert.isNotNull(cu);
- CompilationUnitRange range= new CompilationUnitRange(cu, expression);
- return makeTypeVariable((ITypeBinding)getKey(binding), expression.toString(), range);
- }
-
- if (ASTNodes.isLiteral(expression)){
- Integer nodeType= new Integer(expression.getNodeType());
- if (! fLiteralMap.containsKey(nodeType)){
- fLiteralMap.put(nodeType, new ExpressionVariable(expression));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (ExpressionVariable) fLiteralMap.get(nodeType);
- }
-
- // For ExpressionVariables, there are two cases. If the expression has a binding
- // we use that as the key. Otherwise, we use the CompilationUnitRange. See
- // also ExpressionVariable.equals()
- ExpressionVariable ev;
- Object key;
- if (binding != null){
- key= getKey(binding);
- } else {
- key= new CompilationUnitRange(ASTCreator.getCu(expression), expression);
- }
- ev= (ExpressionVariable)fExpressionMap.get(key);
-
- if (ev != null){
- if (REPORT) nrRetrieved++;
- } else {
- ev= new ExpressionVariable(expression);
- fExpressionMap.put(key, ev);
- if (REPORT) nrCreated++;
- if (REPORT) dumpConstraintStats();
- }
- return ev;
- }
-
-
- //
- // The method IBinding.equals() does not have the desired behavior, and Bindings.equals()
- // must be used to compare bindings. We use an additional layer of Hashing.
- //
- private IBinding getKey(IBinding binding) {
- if (fBindingMap.containsKey(binding)){
- return (IBinding)fBindingMap.get(binding);
- } else {
- for (Iterator it= fBindingMap.keySet().iterator(); it.hasNext(); ){
- IBinding b2= (IBinding)it.next();
- if (Bindings.equals(binding, b2)){
- fBindingMap.put(binding, b2);
- return b2;
- }
- }
- fBindingMap.put(binding, binding);
- return binding;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeDeclaringTypeVariable(org.eclipse.wst.jsdt.core.dom.ITypeBinding)
- */
- public DeclaringTypeVariable makeDeclaringTypeVariable(ITypeBinding memberTypeBinding) {
- String key = memberTypeBinding.getKey();
- if (! fDeclaringTypeVariableMap.containsKey(key)){
- fDeclaringTypeVariableMap.put(key, new DeclaringTypeVariable(memberTypeBinding));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (DeclaringTypeVariable)fDeclaringTypeVariableMap.get(key);
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeDeclaringTypeVariable(org.eclipse.wst.jsdt.core.dom.IVariableBinding)
- */
- public DeclaringTypeVariable makeDeclaringTypeVariable(IVariableBinding fieldBinding) {
- String key= fieldBinding.getKey();
- if (! fDeclaringTypeVariableMap.containsKey(key)){
- fDeclaringTypeVariableMap.put(key, new DeclaringTypeVariable(fieldBinding));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (DeclaringTypeVariable)fDeclaringTypeVariableMap.get(key);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeDeclaringTypeVariable(org.eclipse.wst.jsdt.core.dom.IFunctionBinding)
- */
- public DeclaringTypeVariable makeDeclaringTypeVariable(IFunctionBinding methodBinding) {
- String key= methodBinding.getKey();
- if (! fDeclaringTypeVariableMap.containsKey(key)){
- fDeclaringTypeVariableMap.put(key, new DeclaringTypeVariable(methodBinding));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (DeclaringTypeVariable)fDeclaringTypeVariableMap.get(key);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeParameterTypeVariable(org.eclipse.wst.jsdt.core.dom.IFunctionBinding, int)
- */
- public ParameterTypeVariable makeParameterTypeVariable(IFunctionBinding methodBinding,
- int parameterIndex) {
- String key= methodBinding.getKey() + parameterIndex;
- if (! fParameterMap.containsKey(key)){
- fParameterMap.put(key, new ParameterTypeVariable(methodBinding, parameterIndex));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (ParameterTypeVariable)fParameterMap.get(key);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeRawBindingVariable(org.eclipse.wst.jsdt.core.dom.ITypeBinding)
- */
- public RawBindingVariable makeRawBindingVariable(ITypeBinding binding) {
- String key = binding.getKey();
- if (! fRawBindingMap.containsKey(key)){
- fRawBindingMap.put(key, new RawBindingVariable(binding));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (RawBindingVariable)fRawBindingMap.get(key);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeReturnTypeVariable(org.eclipse.wst.jsdt.core.dom.ReturnStatement)
- */
- public ReturnTypeVariable makeReturnTypeVariable(ReturnStatement returnStatement) {
- return makeReturnTypeVariable(ReturnTypeVariable.getMethod(returnStatement).resolveBinding());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeReturnTypeVariable(org.eclipse.wst.jsdt.core.dom.IFunctionBinding)
- */
- public ReturnTypeVariable makeReturnTypeVariable(IFunctionBinding methodBinding) {
- String key= methodBinding.getKey();
- if (!fReturnVariableMap.containsKey(key)){
- fReturnVariableMap.put(key, new ReturnTypeVariable(methodBinding));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (ReturnTypeVariable)fReturnVariableMap.get(key);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeTypeVariable(org.eclipse.wst.jsdt.core.dom.Type)
- */
- public TypeVariable makeTypeVariable(Type type) {
- IJavaScriptUnit cu= ASTCreator.getCu(type);
- Assert.isNotNull(cu);
- CompilationUnitRange range= new CompilationUnitRange(cu, type);
- if (! fTypeVariableMap.containsKey(range)){
- fTypeVariableMap.put(range, new TypeVariable(type));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (TypeVariable) fTypeVariableMap.get(range);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.IConstraintVariableFactory#makeTypeVariable(org.eclipse.wst.jsdt.core.dom.ITypeBinding, java.lang.String, org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange)
- */
- public TypeVariable makeTypeVariable(ITypeBinding binding, String source, CompilationUnitRange range) {
- if (! fTypeVariableMap.containsKey(range)){
- fTypeVariableMap.put(range, new TypeVariable(binding, source, range));
- if (REPORT) nrCreated++;
- } else {
- if (REPORT) nrRetrieved++;
- }
- if (REPORT) dumpConstraintStats();
- return (TypeVariable) fTypeVariableMap.get(range);
- }
-
- protected void dumpConstraintStats() {
- System.out.println("created: " + nrCreated + ", retrieved: " + nrRetrieved); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/DeclaringTypeVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/DeclaringTypeVariable.java
deleted file mode 100644
index a3b87b8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/DeclaringTypeVariable.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-/**
- * Tells the type which declares the member.
- */
-public class DeclaringTypeVariable extends ConstraintVariable{
-
- private final IBinding fMemberBinding;
-
- protected DeclaringTypeVariable(ITypeBinding memberTypeBinding) {
- super(memberTypeBinding.getDeclaringClass());
- fMemberBinding= memberTypeBinding;
- }
-
- protected DeclaringTypeVariable(IVariableBinding fieldBinding) {
- super(fieldBinding.getDeclaringClass());
- Assert.isTrue(fieldBinding.isField());
- fMemberBinding= fieldBinding;
- }
-
- protected DeclaringTypeVariable(IFunctionBinding methodBinding) {
- super(methodBinding.getDeclaringClass());
- fMemberBinding= methodBinding;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Decl(" + Bindings.asString(fMemberBinding) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public IBinding getMemberBinding() {
- return fMemberBinding;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ExpressionVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ExpressionVariable.java
deleted file mode 100644
index bf8aff56..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ExpressionVariable.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-
-public final class ExpressionVariable extends ConstraintVariable {
-
- private final CompilationUnitRange fRange;
- private final String fSource;
- private final IBinding fExpressionBinding;
- private final int fExpressionType;
-
- public ExpressionVariable(Expression expression){
- super(expression.resolveTypeBinding());
- fSource= expression.toString();
- IJavaScriptUnit cu= ASTCreator.getCu(expression);
- Assert.isNotNull(cu);
- fRange= new CompilationUnitRange(cu, expression);
- fExpressionBinding= resolveBinding(expression);
- fExpressionType= expression.getNodeType();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "[" + fSource + "]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public CompilationUnitRange getCompilationUnitRange() {
- return fRange;
- }
-
- public int getExpressionType() {
- return fExpressionType;
- }
-
- public IBinding getExpressionBinding() {
- return fExpressionBinding;
- }
-
- public static IBinding resolveBinding(Expression expression){
- if (expression instanceof Name)
- return ((Name)expression).resolveBinding();
- if (expression instanceof ParenthesizedExpression)
- return resolveBinding(((ParenthesizedExpression)expression).getExpression());
- else if (expression instanceof Assignment)
- return resolveBinding(((Assignment)expression).getLeftHandSide());//TODO ???
- else if (expression instanceof FunctionInvocation)
- return ((FunctionInvocation)expression).resolveMethodBinding();
- else if (expression instanceof SuperMethodInvocation)
- return ((SuperMethodInvocation)expression).resolveMethodBinding();
- else if (expression instanceof FieldAccess)
- return ((FieldAccess)expression).resolveFieldBinding();
- else if (expression instanceof SuperFieldAccess)
- return ((SuperFieldAccess)expression).resolveFieldBinding();
- else if (expression instanceof ConditionalExpression)
- return resolveBinding(((ConditionalExpression)expression).getThenExpression());
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/FullConstraintCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/FullConstraintCreator.java
deleted file mode 100644
index 466ec3e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/FullConstraintCreator.java
+++ /dev/null
@@ -1,675 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-
-/**
- * Default implementation of the creator. Creates all or nearly all constraints for program constructs.
- * Subclasses can provide additional checks to avoid creating constraints that are not useful for their purposes.
- */
-public class FullConstraintCreator extends ConstraintCreator{
-
- private final IConstraintVariableFactory fConstraintVariableFactory;
- private final ITypeConstraintFactory fTypeConstraintFactory;
- private IContext fContext;
-
- public FullConstraintCreator(){
- this(new ConstraintVariableFactory(), new TypeConstraintFactory());
- }
-
- public FullConstraintCreator(IConstraintVariableFactory cFactory,
- ITypeConstraintFactory tFactory) {
- Assert.isTrue(cFactory != null);
- fConstraintVariableFactory= cFactory;
- fTypeConstraintFactory= tFactory;
- fContext= new NullContext();
- }
-
- public IContext getContext() {
- return fContext;
- }
-
- public void setContext(IContext context) {
- fContext= context;
- }
-
- public ITypeConstraintFactory getConstraintFactory(){
- return fTypeConstraintFactory;
- }
-
- public IConstraintVariableFactory getConstraintVariableFactory(){
- return fConstraintVariableFactory;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ArrayInitializer)
- */
- public ITypeConstraint[] create(ArrayInitializer arrayInitializer){
- ITypeBinding arrayBinding= arrayInitializer.resolveTypeBinding();
- Assert.isTrue(arrayBinding.isArray());
- List expressions= arrayInitializer.expressions();
- List/*<ITypeConstraint>*/ constraints= new ArrayList();
- Type type= getTypeParent(arrayInitializer);
- ConstraintVariable typeVariable= fConstraintVariableFactory.makeTypeVariable(type);
- for (int i= 0; i < expressions.size(); i++) {
- Expression each= (Expression) expressions.get(i);
- ITypeConstraint[] c= fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(each, getContext()),
- typeVariable);
- constraints.addAll(Arrays.asList(c));
- }
- return (ITypeConstraint[])constraints.toArray(new ITypeConstraint[constraints.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.Assignment)
- */
- public ITypeConstraint[] create(Assignment assignment){
- return fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(assignment.getRightHandSide(), getContext()),
- fConstraintVariableFactory.makeExpressionOrTypeVariable(assignment.getLeftHandSide(), getContext()));
- }
-
- public ITypeConstraint[] create(CatchClause node) {
- SingleVariableDeclaration exception= node.getException();
- ConstraintVariable nameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(exception.getName(), getContext());
-
- ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
- nameVariable,
- fConstraintVariableFactory.makeTypeVariable(exception.getType()));
-
- ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
- ITypeConstraint[] catchBound= fTypeConstraintFactory.createSubtypeConstraint(
- nameVariable,
- fConstraintVariableFactory.makeRawBindingVariable(throwable));
-
- ArrayList result= new ArrayList();
- result.addAll(Arrays.asList(defines));
- result.addAll(Arrays.asList(catchBound));
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation)
- */
- public ITypeConstraint[] create(ClassInstanceCreation instanceCreation){
- List arguments= instanceCreation.arguments();
- List result= new ArrayList(arguments.size());
- IFunctionBinding methodBinding= instanceCreation.resolveConstructorBinding();
- result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
- if (instanceCreation.getAnonymousClassDeclaration() == null){
- ConstraintVariable constructorVar= fConstraintVariableFactory.makeExpressionOrTypeVariable(instanceCreation, getContext());
- ConstraintVariable typeVar= fConstraintVariableFactory.makeRawBindingVariable(instanceCreation.resolveTypeBinding());
- result.addAll(Arrays.asList(fTypeConstraintFactory.createDefinesConstraint(constructorVar, typeVar)));
- }
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public ITypeConstraint[] create(ConstructorInvocation invocation){
- List arguments= invocation.arguments();
- List result= new ArrayList(arguments.size());
- IFunctionBinding methodBinding= invocation.resolveConstructorBinding();
- result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldAccess)
- */
- public ITypeConstraint[] create(FieldAccess access){
- Expression expression= access.getExpression();
- SimpleName name= access.getName();
- IBinding binding= name.resolveBinding();
- if (! (binding instanceof IVariableBinding))
- return new ITypeConstraint[0];
- IVariableBinding vb= (IVariableBinding)binding;
- return createConstraintsForAccessToField(vb, expression, access);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FieldDeclaration)
- */
- public ITypeConstraint[] create(FieldDeclaration fd){
- List result= new ArrayList();
- result.addAll(Arrays.asList(getConstraintsFromFragmentList(fd.fragments(), fd.getType())));
- result.addAll(getConstraintsForHiding(fd));
- result.addAll(getConstraintsForFieldDeclaringTypes(fd));
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.InstanceofExpression)
- */
- public ITypeConstraint[] create(InstanceofExpression instanceofExpression){
- Expression expression= instanceofExpression.getLeftOperand();
- Type type= instanceofExpression.getRightOperand();
- if (isClassBinding(expression.resolveTypeBinding()) && isClassBinding(type.resolveBinding())) {
- ConstraintVariable expressionVar= fConstraintVariableFactory.makeExpressionOrTypeVariable(expression, getContext());
- ConstraintVariable typeVariable= fConstraintVariableFactory.makeTypeVariable(type);
- return createOrOrSubtypeConstraint(expressionVar, typeVariable);
- } else
- return new ITypeConstraint[0];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConditionalExpression)
- */
- public ITypeConstraint[] create(ConditionalExpression node) {
- List result= new ArrayList();
- Expression thenExpression= node.getThenExpression();
- Expression elseExpression= node.getElseExpression();
- ConstraintVariable whole= fConstraintVariableFactory.makeExpressionOrTypeVariable(node, getContext());
- ConstraintVariable ev1= fConstraintVariableFactory.makeExpressionOrTypeVariable(thenExpression, getContext());
- ConstraintVariable ev2= fConstraintVariableFactory.makeExpressionOrTypeVariable(elseExpression, getContext());
- ITypeConstraint[] constraints1= fTypeConstraintFactory.createEqualsConstraint(ev1, ev2);
- ITypeConstraint[] constraints2= fTypeConstraintFactory.createSubtypeConstraint(ev1, whole);
- ITypeConstraint[] constraints3= fTypeConstraintFactory.createSubtypeConstraint(ev2, whole);
- result.addAll(Arrays.asList(constraints1));
- result.addAll(Arrays.asList(constraints2));
- result.addAll(Arrays.asList(constraints3));
- return (ITypeConstraint[])result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public ITypeConstraint[] create(FunctionDeclaration declaration){
- List result= new ArrayList();
- IFunctionBinding methodBinding= declaration.resolveBinding();
- if (methodBinding == null)
- return new ITypeConstraint[0];
- ITypeConstraint[] constraints = fTypeConstraintFactory.createDefinesConstraint(
- fConstraintVariableFactory.makeDeclaringTypeVariable(methodBinding),
- fConstraintVariableFactory.makeRawBindingVariable(methodBinding.getDeclaringClass()));
- result.addAll(Arrays.asList(constraints));
- if (! methodBinding.isConstructor() && ! methodBinding.getReturnType().isPrimitive()){
- ConstraintVariable returnTypeBindingVariable= fConstraintVariableFactory.makeReturnTypeVariable(methodBinding);
- ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeTypeVariable(declaration.getReturnType2());
- ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
- returnTypeBindingVariable, returnTypeVariable);
- result.addAll(Arrays.asList(defines));
- }
- for (int i= 0, n= declaration.parameters().size(); i < n; i++) {
- SingleVariableDeclaration paramDecl= (SingleVariableDeclaration)declaration.parameters().get(i);
- ConstraintVariable parameterTypeVariable= fConstraintVariableFactory.makeParameterTypeVariable(methodBinding, i);
- ConstraintVariable parameterNameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(paramDecl.getName(), getContext());
- ITypeConstraint[] constraint= fTypeConstraintFactory.createDefinesConstraint(
- parameterTypeVariable, parameterNameVariable);
- result.addAll(Arrays.asList(constraint));
- }
- if (MethodChecks.isVirtual(methodBinding)){
- Collection constraintsForOverriding = getConstraintsForOverriding(methodBinding);
- result.addAll(constraintsForOverriding);
- }
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ConstraintCreator#create(org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression)
- */
- public ITypeConstraint[] create(ParenthesizedExpression node) {
- ConstraintVariable v1= fConstraintVariableFactory.makeExpressionOrTypeVariable(node, getContext());
- ConstraintVariable v2= fConstraintVariableFactory.makeExpressionOrTypeVariable(node.getExpression(), getContext());
- ITypeConstraint[] equal= fTypeConstraintFactory.createEqualsConstraint(v1, v2);
- return equal;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionInvocation)
- */
- public ITypeConstraint[] create(FunctionInvocation invocation){
- List arguments= invocation.arguments();
- List result= new ArrayList(arguments.size());
- IFunctionBinding methodBinding= invocation.resolveMethodBinding();
- if (methodBinding == null)
- return new ITypeConstraint[0];
- ITypeConstraint[] returnTypeConstraint= getReturnTypeConstraint(invocation, methodBinding);
- result.addAll(Arrays.asList(returnTypeConstraint));
- result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
- if (invocation.getExpression() != null){
- if(MethodChecks.isVirtual(methodBinding)){
- IFunctionBinding[] rootDefs= getRootDefs(methodBinding);
- Assert.isTrue(rootDefs.length > 0);
- ConstraintVariable expressionVar= fConstraintVariableFactory.makeExpressionOrTypeVariable(invocation.getExpression(), getContext());
- if (rootDefs.length == 1){
- result.addAll(Arrays.asList(fTypeConstraintFactory.createSubtypeConstraint(expressionVar, fConstraintVariableFactory.makeDeclaringTypeVariable(rootDefs[0]))));
- }else{
- Collection/*<ITypeConstraint>*/ constraints= new ArrayList();
- for (int i= 0; i < rootDefs.length; i++) {
- ConstraintVariable rootDefTypeVar= fConstraintVariableFactory.makeDeclaringTypeVariable(rootDefs[i]);
- ITypeConstraint[] tc= fTypeConstraintFactory.createSubtypeConstraint(expressionVar, rootDefTypeVar);
- constraints.addAll(Arrays.asList(tc));
- }
- ITypeConstraint[] constraintsArray= (ITypeConstraint[])constraints.toArray(new ITypeConstraint[constraints.size()]);
- if (constraintsArray.length > 0){
- result.add(fTypeConstraintFactory.createCompositeOrTypeConstraint(constraintsArray));
- }
- }
- } else {
- ConstraintVariable typeVar= fConstraintVariableFactory.makeDeclaringTypeVariable(methodBinding);
- ConstraintVariable expressionVar= fConstraintVariableFactory.makeExpressionOrTypeVariable(invocation.getExpression(), getContext());
- result.addAll(Arrays.asList(fTypeConstraintFactory.createSubtypeConstraint(expressionVar, typeVar)));
- }
- }
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.QualifiedName)
- */
- public ITypeConstraint[] create(QualifiedName qualifiedName){
- SimpleName name= qualifiedName.getName();
- Name qualifier= qualifiedName.getQualifier();
- IBinding nameBinding= name.resolveBinding();
- if (nameBinding instanceof IVariableBinding){
- IVariableBinding vb= (IVariableBinding)nameBinding;
- if (vb.isField())
- return createConstraintsForAccessToField(vb, qualifier, qualifiedName);
- } //TODO other bindings
- return new ITypeConstraint[0];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ReturnStatement)
- */
- public ITypeConstraint[] create(ReturnStatement returnStatement){
- if (returnStatement.getExpression() == null)
- return new ITypeConstraint[0];
-
- ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeReturnTypeVariable(returnStatement);
- return fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(returnStatement.getExpression(), getContext()),
- returnTypeVariable);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration)
- */
- public ITypeConstraint[] create(SingleVariableDeclaration svd){
- ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()),
- fConstraintVariableFactory.makeTypeVariable(svd.getType()));
- if (svd.getInitializer() == null)
- return defines;
- ITypeConstraint[] constraints = fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getInitializer(), getContext()),
- fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()));
- if (defines.length == 0 && constraints.length == 0){
- return new ITypeConstraint[0];
- } else if (defines.length == 0){
- return constraints;
- } else if (constraints.length == 0){
- return defines;
- } else {
- List all= new ArrayList();
- all.addAll(Arrays.asList(defines));
- all.addAll(Arrays.asList(constraints));
- return (ITypeConstraint[])all.toArray();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation)
- */
- public ITypeConstraint[] create(SuperConstructorInvocation invocation){
- List arguments= invocation.arguments();
- List result= new ArrayList(arguments.size());
- IFunctionBinding methodBinding= invocation.resolveConstructorBinding();
- result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperFieldAccess)
- */
- public ITypeConstraint[] create(SuperFieldAccess access){
- SimpleName name= access.getName();
- IBinding binding= name.resolveBinding();
- if (! (binding instanceof IVariableBinding))
- return new ITypeConstraint[0];
- IVariableBinding vb= (IVariableBinding)binding;
- return createConstraintsForAccessToField(vb, null, access);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation)
- */
- public ITypeConstraint[] create(SuperMethodInvocation invocation){
- List arguments= invocation.arguments();
- List result= new ArrayList(arguments.size());
- IFunctionBinding methodBinding= invocation.resolveMethodBinding();
- ITypeConstraint[] returnTypeConstraint= getReturnTypeConstraint(invocation, methodBinding);
- result.addAll(Arrays.asList(returnTypeConstraint));
- result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ThisExpression)
- */
- public ITypeConstraint[] create(ThisExpression expression){
- ConstraintVariable thisExpression= fConstraintVariableFactory.makeExpressionOrTypeVariable(expression, getContext());
- ConstraintVariable declaringType= fConstraintVariableFactory.makeRawBindingVariable(expression.resolveTypeBinding());//TODO fix this - can't use Decl(M) because 'this' can live outside of methods
- return fTypeConstraintFactory.createDefinesConstraint(thisExpression, declaringType);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression)
- */
- public ITypeConstraint[] create(VariableDeclarationExpression vde){
- return getConstraintsFromFragmentList(vde.fragments(), vde.getType());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment)
- */
- public ITypeConstraint[] create(VariableDeclarationFragment vdf){
- if (vdf.getInitializer() == null)
- return new ITypeConstraint[0];
- return fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(vdf.getInitializer(), getContext()),
- fConstraintVariableFactory.makeExpressionOrTypeVariable(vdf.getName(), getContext()));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement)
- */
- public ITypeConstraint[] create(VariableDeclarationStatement vds){
- return getConstraintsFromFragmentList(vds.fragments(), vds.getType());
- }
-
-
- //--------- private helpers ----------------//
-
- private Collection getConstraintsForFieldDeclaringTypes(FieldDeclaration fd) {
- Collection result= new ArrayList(fd.fragments().size());
- for (Iterator iter= fd.fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment varDecl= (VariableDeclarationFragment) iter.next();
- IVariableBinding binding= varDecl.resolveBinding();
- Assert.isTrue(binding.isField());
- result.addAll(Arrays.asList(fTypeConstraintFactory.createDefinesConstraint(
- fConstraintVariableFactory.makeDeclaringTypeVariable(binding),
- fConstraintVariableFactory.makeRawBindingVariable(binding.getDeclaringClass()))));
- }
- return result;
- }
-
- private Collection getConstraintsForHiding(FieldDeclaration fd) {
- Collection result= new ArrayList();
- for (Iterator iter= fd.fragments().iterator(); iter.hasNext();) {
- result.addAll(getConstraintsForHiding((VariableDeclarationFragment) iter.next()));
- }
- return result;
- }
-
- private Collection getConstraintsForHiding(VariableDeclarationFragment fragment) {
- Collection result= new ArrayList();
- IVariableBinding fieldBinding= fragment.resolveBinding();
- Assert.isTrue(fieldBinding.isField());
- Set declaringTypes= getDeclaringSuperTypes(fieldBinding);
- ConstraintVariable hiddingFieldVar= fConstraintVariableFactory.makeDeclaringTypeVariable(fieldBinding);
- for (Iterator iter= declaringTypes.iterator(); iter.hasNext();) {
- ITypeBinding declaringSuperType= (ITypeBinding) iter.next();
- IVariableBinding hiddenField= findField(fieldBinding, declaringSuperType);
- Assert.isTrue(hiddenField.isField());
- ConstraintVariable hiddenFieldVar= fConstraintVariableFactory.makeDeclaringTypeVariable(hiddenField);
- result.addAll(Arrays.asList(fTypeConstraintFactory.createStrictSubtypeConstraint(hiddingFieldVar, hiddenFieldVar)));
- }
- return result;
- }
-
- private ITypeConstraint[] getConstraintsFromFragmentList(List fragments, Type type) {
- int size= fragments.size();
- ConstraintVariable typeVariable= fConstraintVariableFactory.makeTypeVariable(type);
- List result= new ArrayList((size * (size - 1))/2);
- for (int i= 0; i < size; i++) {
- VariableDeclarationFragment fragment1= (VariableDeclarationFragment) fragments.get(i);
- SimpleName fragment1Name= fragment1.getName();
- result.addAll(Arrays.asList(fTypeConstraintFactory.createDefinesConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(fragment1Name, getContext()),
- typeVariable)));
- for (int j= i + 1; j < size; j++) {
- VariableDeclarationFragment fragment2= (VariableDeclarationFragment) fragments.get(j);
- result.addAll(Arrays.asList(fTypeConstraintFactory.createEqualsConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(fragment1Name, getContext()),
- fConstraintVariableFactory.makeExpressionOrTypeVariable(fragment2.getName(), getContext()))));
- }
- }
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- private Collection getConstraintsForOverriding(IFunctionBinding overriddingMethod) {
- Collection result= new ArrayList();
- Set declaringSupertypes= getDeclaringSuperTypes(overriddingMethod);
- for (Iterator iter= declaringSupertypes.iterator(); iter.hasNext();) {
- ITypeBinding superType= (ITypeBinding) iter.next();
- IFunctionBinding overriddenMethod= findMethod(overriddingMethod, superType);
- Assert.isNotNull(overriddenMethod);//because we asked for declaring types
- if (Bindings.equals(overriddingMethod, overriddenMethod)) continue;
- ITypeConstraint[] returnTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
- fConstraintVariableFactory.makeReturnTypeVariable(overriddenMethod),
- fConstraintVariableFactory.makeReturnTypeVariable(overriddingMethod));
- result.addAll(Arrays.asList(returnTypeConstraint));
- Assert.isTrue(overriddenMethod.getParameterTypes().length == overriddingMethod.getParameterTypes().length);
- for (int i= 0, n= overriddenMethod.getParameterTypes().length; i < n; i++) {
- ITypeConstraint[] parameterTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
- fConstraintVariableFactory.makeParameterTypeVariable(overriddenMethod, i),
- fConstraintVariableFactory.makeParameterTypeVariable(overriddingMethod, i));
- result.addAll(Arrays.asList(parameterTypeConstraint));
- }
- ITypeConstraint[] declaringTypeConstraint= fTypeConstraintFactory.createStrictSubtypeConstraint(
- fConstraintVariableFactory.makeDeclaringTypeVariable(overriddingMethod),
- fConstraintVariableFactory.makeDeclaringTypeVariable(overriddenMethod));
- result.addAll(Arrays.asList(declaringTypeConstraint));
- }
- return result;
- }
-
- private ITypeConstraint[] getReturnTypeConstraint(Expression invocation, IFunctionBinding methodBinding){
- if (methodBinding == null || methodBinding.isConstructor() || methodBinding.getReturnType().isPrimitive())
- return new ITypeConstraint[0];
- ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeReturnTypeVariable(methodBinding);
- ConstraintVariable invocationVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(invocation, getContext());
- return fTypeConstraintFactory.createDefinesConstraint(invocationVariable, returnTypeVariable);
- }
-
- private ITypeConstraint[] getArgumentConstraints(List arguments, IFunctionBinding methodBinding){
- List result= new ArrayList(arguments.size());
- for (int i= 0, n= arguments.size(); i < n; i++) {
- Expression argument= (Expression) arguments.get(i);
- ConstraintVariable expressionVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(argument, getContext());
- ConstraintVariable parameterTypeVariable= fConstraintVariableFactory.makeParameterTypeVariable(methodBinding, i);
- ITypeConstraint[] argConstraint= fTypeConstraintFactory.createSubtypeConstraint(expressionVariable, parameterTypeVariable);
- result.addAll(Arrays.asList(argConstraint));
- }
- return (ITypeConstraint[]) result.toArray(new ITypeConstraint[result.size()]);
- }
-
- private static Type getTypeParent(ArrayInitializer arrayInitializer) {
- if (arrayInitializer.getParent() instanceof ArrayCreation){
- return ((ArrayCreation)arrayInitializer.getParent()).getType().getElementType();
- } else if (arrayInitializer.getParent() instanceof ArrayInitializer){
- return getTypeParent((ArrayInitializer) arrayInitializer.getParent());
- } else if (arrayInitializer.getParent() instanceof VariableDeclaration){
- VariableDeclaration parent= (VariableDeclaration)arrayInitializer.getParent();
-
- if (parent.getParent() instanceof VariableDeclarationStatement){
- Type type= ((VariableDeclarationStatement)parent.getParent()).getType();
- return ASTNodes.getElementType(type);
- } else if (parent.getParent() instanceof VariableDeclarationExpression){
- Type type= ((VariableDeclarationExpression)parent.getParent()).getType();
- return ASTNodes.getElementType(type);
- } else if (parent.getParent() instanceof FieldDeclaration){
- Type type= ((FieldDeclaration)parent.getParent()).getType();
- return ASTNodes.getElementType(type);
- }
- }
- Assert.isTrue(false);//array initializers are allowed in only 2 places
- return null;
- }
-
- private ITypeConstraint[] createOrOrSubtypeConstraint(ConstraintVariable var1, ConstraintVariable var2){
- ITypeConstraint[] c1= fTypeConstraintFactory.createSubtypeConstraint(var1, var2);
- ITypeConstraint[] c2= fTypeConstraintFactory.createSubtypeConstraint(var2, var1);
- if (c1.length == 0 && c2.length == 0){
- return new ITypeConstraint[0];
- }
- return new ITypeConstraint[]{ fTypeConstraintFactory.createCompositeOrTypeConstraint(new ITypeConstraint[]{c1[0], c2[0]}) };
- }
-
- private ITypeConstraint[] createConstraintsForAccessToField(IVariableBinding fieldBinding, Expression qualifier, Expression accessExpression){
- Assert.isTrue(fieldBinding.isField());
- ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(accessExpression, getContext()),
- fConstraintVariableFactory.makeRawBindingVariable(fieldBinding.getType()));
- if (qualifier == null)
- return defines;
- ITypeConstraint[] subType= fTypeConstraintFactory.createSubtypeConstraint(
- fConstraintVariableFactory.makeExpressionOrTypeVariable(qualifier, getContext()),
- fConstraintVariableFactory.makeDeclaringTypeVariable(fieldBinding));
-
- if (defines.length == 0){
- return subType;
- } else if (subType.length == 0){
- return defines;
- } else {
- return new ITypeConstraint[]{defines[0], subType[0]};
- }
- }
-
- private static IVariableBinding findField(IVariableBinding fieldBinding, ITypeBinding type) {
- if (fieldBinding.getDeclaringClass().equals(type))
- return fieldBinding;
- return Bindings.findFieldInType(type, fieldBinding.getName());
- }
-
- /*
- * return Set of ITypeBindings
- */
- private static Set getDeclaringSuperTypes(IVariableBinding fieldBinding) {
- ITypeBinding[] allSuperTypes= Bindings.getAllSuperTypes(fieldBinding.getDeclaringClass());
- Set result= new HashSet();
- for (int i= 0; i < allSuperTypes.length; i++) {
- ITypeBinding type= allSuperTypes[i];
- if (findField(fieldBinding, type) != null)
- result.add(type);
- }
- return result;
- }
-
- //--- RootDef ----//
- protected static IFunctionBinding[] getRootDefs(IFunctionBinding methodBinding) {
- Set/*<ITypeBinding>*/ declaringSuperTypes= getDeclaringSuperTypes(methodBinding);
- Set/*<IFunctionBinding>*/ result= new LinkedHashSet();
- for (Iterator iter= declaringSuperTypes.iterator(); iter.hasNext();) {
- ITypeBinding type= (ITypeBinding) iter.next();
- if (! containsASuperType(type, declaringSuperTypes))
- result.add(findMethod(methodBinding, type));
- }
-
- if (result.size() == 0){
- result.add(methodBinding);
- }
- return (IFunctionBinding[]) result.toArray(new IFunctionBinding[result.size()]);
- }
-
- /*
- * @param declaringSuperTypes Set of ITypeBindings
- * @return <code>true</code> iff <code>declaringSuperTypes</code> contains a type
- * which is a strict supertype of <code>type</code>
- */
- private static boolean containsASuperType(ITypeBinding type, Set declaringSuperTypes) {
- for (Iterator iter= declaringSuperTypes.iterator(); iter.hasNext();) {
- ITypeBinding maybeSuperType= (ITypeBinding) iter.next();
- if (! Bindings.equals(maybeSuperType, type) && Bindings.isSuperType(maybeSuperType, type))
- return true;
- }
- return false;
- }
-
- /*
- * return Set of ITypeBindings
- */
- protected static Set getDeclaringSuperTypes(IFunctionBinding methodBinding) {
- ITypeBinding superClass = methodBinding.getDeclaringClass();
- Set allSuperTypes= new LinkedHashSet();
- allSuperTypes.addAll(Arrays.asList(Bindings.getAllSuperTypes(superClass)));
- if (allSuperTypes.isEmpty())
- allSuperTypes.add(methodBinding.getDeclaringClass()); //TODO: Why only iff empty? The declaring class is not a supertype ...
- Set result= new HashSet();
- for (Iterator iter= allSuperTypes.iterator(); iter.hasNext();) {
- ITypeBinding type= (ITypeBinding) iter.next();
- if (findMethod(methodBinding, type) != null)
- result.add(type);
- }
- return result;
- }
-
- protected static IFunctionBinding findMethod(IFunctionBinding methodBinding, ITypeBinding type) {
- if (methodBinding.getDeclaringClass().equals(type))
- return methodBinding;
- return Bindings.findOverriddenMethodInType(type, methodBinding);
- }
-
- private static boolean isClassBinding(ITypeBinding typeBinding){
- return typeBinding != null && typeBinding.isClass();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IConstraintVariableFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IConstraintVariableFactory.java
deleted file mode 100644
index 9c892683..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IConstraintVariableFactory.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-
-public interface IConstraintVariableFactory {
- ConstraintVariable makeExpressionOrTypeVariable(Expression expression, IContext context);
- DeclaringTypeVariable makeDeclaringTypeVariable(ITypeBinding memberTypeBinding);
- DeclaringTypeVariable makeDeclaringTypeVariable(IVariableBinding fieldBinding);
- DeclaringTypeVariable makeDeclaringTypeVariable(IFunctionBinding methodBinding);
- ParameterTypeVariable makeParameterTypeVariable(IFunctionBinding methodBinding, int parameterIndex);
- RawBindingVariable makeRawBindingVariable(ITypeBinding binding);
- ReturnTypeVariable makeReturnTypeVariable(ReturnStatement returnStatement);
- ReturnTypeVariable makeReturnTypeVariable(IFunctionBinding methodBinding);
- TypeVariable makeTypeVariable(Type type);
- TypeVariable makeTypeVariable(ITypeBinding binding, String source, CompilationUnitRange range);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IContext.java
deleted file mode 100644
index be67f55f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/IContext.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-/**
- * Models "contexts" for use in context-sensitive type constraint
- * analyses.
- */
-public interface IContext {
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraint.java
deleted file mode 100644
index b042dbfb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraint.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-public interface ITypeConstraint {
- /**
- * Returns the resolved representation of the constraint.
- * For example, if <code>toString</code> returns "[a] &lt;= [b]" and types of 'a' and 'b' are A and B,
- * repespectively, then this method returns "A &lt;= B".
- *
- * This method is provided for debugging purposes only.
- */
- public abstract String toResolvedString();
-
- /**
- * Returns whether this is a simple constraint. If so, it can be safely downcast to
- * <code>SimpleTypeConstraint</code>.
- */
- public boolean isSimpleTypeConstraint();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraintFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraintFactory.java
deleted file mode 100644
index e978527d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ITypeConstraintFactory.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-
-public interface ITypeConstraintFactory {
-
- public ITypeConstraint[] createSubtypeConstraint(ConstraintVariable v1, ConstraintVariable v2);
- public ITypeConstraint[] createEqualsConstraint(ConstraintVariable v1, ConstraintVariable v2);
- public ITypeConstraint[] createDefinesConstraint(ConstraintVariable v1, ConstraintVariable v2);
- public ITypeConstraint[] createStrictSubtypeConstraint(ConstraintVariable v1, ConstraintVariable v2);
-
- public CompositeOrTypeConstraint createCompositeOrTypeConstraint(ITypeConstraint[] constraints);
-
- /**
- * Allows for avoiding the creation of SimpleTypeConstraints based on properties of
- * their constituent ConstraintVariables and ConstraintOperators. Can be used to e.g.
- * avoid creation of constraints for assignments between built-in types.
- *
- * @param v1
- * @param v2
- * @param operator
- * @return whether the constraint should <em>not</em> be created
- */
- public boolean filter(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator operator);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/NullContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/NullContext.java
deleted file mode 100644
index 166a0692..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/NullContext.java
+++ /dev/null
@@ -1,16 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-public class NullContext implements IContext {
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ParameterTypeVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ParameterTypeVariable.java
deleted file mode 100644
index 61ccba18..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ParameterTypeVariable.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-public class ParameterTypeVariable extends ConstraintVariable {
-
- private final IFunctionBinding fMethodBinding;
- private final int fParameterIndex;
-
- public ParameterTypeVariable(IFunctionBinding methodBinding, int parameterIndex) {
- super(methodBinding.getParameterTypes()[parameterIndex]);
- Assert.isNotNull(methodBinding);
- Assert.isTrue(0 <= parameterIndex);
- Assert.isTrue(parameterIndex < methodBinding.getParameterTypes().length);
- fMethodBinding= methodBinding;
- fParameterIndex= parameterIndex;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "[Parameter(" + fParameterIndex + "," + Bindings.asString(fMethodBinding) + ")]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public IFunctionBinding getMethodBinding() {
- return fMethodBinding;
- }
-
- public int getParameterIndex() {
- return fParameterIndex;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/RawBindingVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/RawBindingVariable.java
deleted file mode 100644
index 6a12775d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/RawBindingVariable.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public class RawBindingVariable extends ConstraintVariable{
-
- public RawBindingVariable(ITypeBinding binding) {
- super(binding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ReturnTypeVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ReturnTypeVariable.java
deleted file mode 100644
index e23f5260..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/ReturnTypeVariable.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-public class ReturnTypeVariable extends ConstraintVariable{
-
- private final IFunctionBinding fMethodBinding;
-
- public ReturnTypeVariable(ReturnStatement returnStatement) {
- this(getMethod(returnStatement).resolveBinding());
- Assert.isNotNull(returnStatement);
- }
-
- public ReturnTypeVariable(IFunctionBinding methodBinding) {
- super(methodBinding.getReturnType());
- fMethodBinding= methodBinding;
- }
-
- public static FunctionDeclaration getMethod(ReturnStatement returnStatement) {
- return (FunctionDeclaration)ASTNodes.getParent(returnStatement, FunctionDeclaration.class);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "[" + Bindings.asString(fMethodBinding) + "]_returnType"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public IFunctionBinding getMethodBinding() {
- return fMethodBinding;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/SimpleTypeConstraint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/SimpleTypeConstraint.java
deleted file mode 100644
index 5e3bdd98..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/SimpleTypeConstraint.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-
-public final class SimpleTypeConstraint implements ITypeConstraint {
-
- private final ConstraintVariable fLeft;
- private final ConstraintVariable fRight;
- private final ConstraintOperator fOperator;
-
- /* package */ SimpleTypeConstraint(ConstraintVariable left, ConstraintVariable right, ConstraintOperator operator) {
- Assert.isNotNull(left);
- Assert.isNotNull(right);
- Assert.isNotNull(operator);
- fLeft= left;
- fRight= right;
- fOperator= operator;
- }
-
- public ConstraintVariable getLeft() {
- return fLeft;
- }
-
- public ConstraintVariable getRight() {
- return fRight;
- }
-
- public ConstraintOperator getOperator() {
- return fOperator;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString(){
- return getLeft().toString() + " " + fOperator.toString() + " " + getRight().toString(); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.experiments.TypeConstraint#toResolvedString()
- */
- public String toResolvedString() {
- return getLeft().toResolvedString() + " " + fOperator.toString() + " " + getRight().toResolvedString(); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.experiments.ITypeConstraint#isSimpleTypeConstraint()
- */
- public boolean isSimpleTypeConstraint() {
- return true;
- }
-
- public boolean isSubtypeConstraint(){
- return fOperator.isSubtypeOperator();
- }
-
- public boolean isStrictSubtypeConstraint(){
- return fOperator.isStrictSubtypeOperator();
- }
-
- public boolean isEqualsConstraint(){
- return fOperator.isEqualsOperator();
- }
-
- public boolean isDefinesConstraint(){
- return fOperator.isDefinesOperator();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeConstraintFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeConstraintFactory.java
deleted file mode 100644
index 5803cd88..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeConstraintFactory.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-public class TypeConstraintFactory implements ITypeConstraintFactory {
-
- private Map/*<ConstraintVariable, Map<ConstraintVariable, Map<ConstraintOperator, SimpleTypeConstraint>>*/ fSimpleConstraints= new HashMap();
- private Map/*<ConstraintVariable, Map<String, CompositeOrTypeConstraint>>*/ fOrConstraints= new HashMap();
-
- protected static final boolean PRINT_STATS= false;
- protected int fNrCreated= 0;
- protected int fNrFiltered= 0;
- protected int fNrRetrieved= 0;
-
- // Only to be called by the createXXXConstraint() methods
- private SimpleTypeConstraint createSimpleTypeConstraint(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator operator) {
- if (fSimpleConstraints.containsKey(v1)){
- Map m2= (Map)fSimpleConstraints.get(v1);
- if (m2.containsKey(v2)){
- Map m3= (Map)m2.get(v2);
- if (m3.containsKey(operator)){
- if (PRINT_STATS) fNrRetrieved++;
- if (PRINT_STATS) dumpStats();
- return (SimpleTypeConstraint)m3.get(operator);
- } else {
- return storeConstraint(v1, v2, operator, m3);
- }
- } else {
- Map m3= new HashMap();
- m2.put(v2, m3);
- return storeConstraint(v1, v2, operator, m3);
- }
- } else {
- Map m2= new HashMap();
- fSimpleConstraints.put(v1, m2);
- Map m3= new HashMap();
- m2.put(v2, m3);
- return storeConstraint(v1, v2, operator, m3);
- }
- }
-
- private SimpleTypeConstraint storeConstraint(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator operator, Map m3) {
- SimpleTypeConstraint constraint= new SimpleTypeConstraint(v1, v2, operator);
- m3.put(operator, constraint);
- if (PRINT_STATS) fNrCreated++;
- if (PRINT_STATS) dumpStats();
- return constraint;
- }
-
- public ITypeConstraint[] createConstraint(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator operator){
- if (filter(v1, v2, operator)){
- return new ITypeConstraint[0];
- } else {
- return new ITypeConstraint[]{ createSimpleTypeConstraint(v1, v2, operator) };
- }
- }
-
- public ITypeConstraint[] createSubtypeConstraint(ConstraintVariable v1, ConstraintVariable v2){
- return createConstraint(v1, v2, ConstraintOperator.createSubTypeOperator());
- }
-
- public ITypeConstraint[] createStrictSubtypeConstraint(ConstraintVariable v1, ConstraintVariable v2){
- return createConstraint(v1, v2, ConstraintOperator.createStrictSubtypeOperator());
- }
-
- public ITypeConstraint[] createEqualsConstraint(ConstraintVariable v1, ConstraintVariable v2){
- return createConstraint(v1, v2, ConstraintOperator.createEqualsOperator());
- }
-
- public ITypeConstraint[] createDefinesConstraint(ConstraintVariable v1, ConstraintVariable v2){
- return createConstraint(v1, v2, ConstraintOperator.createDefinesOperator());
- }
-
- /**
- * {@inheritDoc}
- * Avoid creating constraints involving primitive types and self-constraints.
- */
- public boolean filter(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator operator) {
- if ((v1.getBinding() != null && v1.getBinding().isPrimitive() &&
- v2.getBinding() != null && v2.getBinding().isPrimitive()) ||
- v1 == v2) {
- if (PRINT_STATS) fNrFiltered++;
- if (PRINT_STATS) dumpStats();
- return true;
- }
- return false;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ITypeConstraintFactory#createCompositeOrTypeConstraint(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.ITypeConstraint[])
- */
- public CompositeOrTypeConstraint createCompositeOrTypeConstraint(ITypeConstraint[] constraints){
- ConstraintVariable left= ((SimpleTypeConstraint)constraints[0]).getLeft();
- String bounds= ""; //$NON-NLS-1$
- for (int i= 0; i < constraints.length; i++){
- ConstraintVariable right= ((SimpleTypeConstraint)constraints[i]).getRight();
- ITypeBinding binding= right.getBinding();
- String typeName= binding.getQualifiedName();
- bounds= bounds + typeName +","; //$NON-NLS-1$
- }
-
- if (fOrConstraints.containsKey(left)){
- Map m2= (Map)fOrConstraints.get(left);
- if (m2.containsKey(bounds)){
- if (PRINT_STATS) fNrRetrieved++;
- if (PRINT_STATS) dumpStats();
- return (CompositeOrTypeConstraint)m2.get(bounds);
- } else {
- CompositeOrTypeConstraint constraint= new CompositeOrTypeConstraint(constraints);
- m2.put(bounds, constraint);
- if (PRINT_STATS) dumpStats();
- if (PRINT_STATS) fNrCreated++;
- return constraint;
- }
- } else {
- Map m2= new HashMap();
- fOrConstraints.put(left, m2);
- CompositeOrTypeConstraint constraint= new CompositeOrTypeConstraint(constraints);
- m2.put(bounds, constraint);
- if (PRINT_STATS) dumpStats();
- if (PRINT_STATS) fNrCreated++;
- return constraint;
- }
- }
-
- protected void dumpStats() {
- System.out.println("Constraints: " + fNrCreated + " created, " + fNrRetrieved + " retrieved, " + fNrFiltered + " filtered"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeVariable.java
deleted file mode 100644
index 470496cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/TypeVariable.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-
-public final class TypeVariable extends ConstraintVariable {
-
- private final String fSource;
- private final CompilationUnitRange fTypeRange;
-
- public TypeVariable(Type type){
- super(type.resolveBinding());
- fSource= type.toString();
- IJavaScriptUnit cu= ASTCreator.getCu(type);
- Assert.isNotNull(cu);
- fTypeRange= new CompilationUnitRange(cu, ASTNodes.getElementType(type));
- }
-
- public TypeVariable(ITypeBinding binding, String source, CompilationUnitRange range){
- super(binding);
- fSource= source;
- fTypeRange= range;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fSource;
- }
-
- public CompilationUnitRange getCompilationUnitRange() {
- return fTypeRange;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/AbstractTypeVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/AbstractTypeVariable.java
deleted file mode 100644
index f5e42acc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/AbstractTypeVariable.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public abstract class AbstractTypeVariable extends TType {
-
- protected TType[] fBounds;
-
- protected AbstractTypeVariable(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding) {
- super.initialize(binding);
- fBounds= EMPTY_TYPE_ARRAY;
- if (getEnvironment().getJavaLangObject() == null) {
- getEnvironment().initializeJavaLangObject(binding.getErasure());
- }
- }
-
- public TType getErasure() {
- if (fBounds.length == 0)
- return getEnvironment().getJavaLangObject();
- return fBounds[0].getErasure();
- }
-
- /* package */ final boolean isUnbounded() {
- if (fBounds.length == 0)
- return true;
- return fBounds[0].isJavaLangObject();
- }
-
- public final TType[] getBounds() {
- return (TType[]) fBounds.clone();
- }
-
- public final TType[] getSubTypes() {
- return EMPTY_TYPE_ARRAY;
- }
-
- protected final boolean checkAssignmentBound(TType rhs) {
- if (fBounds.length == 0)
- return true;
- for (int i= 0; i < fBounds.length; i++) {
- if (rhs.canAssignTo(fBounds[i]))
- return true;
- }
- return false;
- }
-
- protected final boolean canAssignOneBoundTo(TType lhs) {
- if (fBounds.length == 0)
- return lhs.isJavaLangObject();
- for (int i= 0; i < fBounds.length; i++) {
- if (fBounds[i].canAssignTo(lhs))
- return true;
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/ArrayType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/ArrayType.java
deleted file mode 100644
index 6db04e52..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/ArrayType.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public final class ArrayType extends TType {
- private TType fElementType;
- private int fDimensions;
-
- private TType fErasure;
-
- protected ArrayType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected ArrayType(TypeEnvironment environment, String key) {
- super(environment, key);
- }
-
- protected void initialize(ITypeBinding binding, TType elementType) {
- Assert.isTrue(binding.isArray());
- super.initialize(binding);
- fElementType= elementType;
- fDimensions= binding.getDimensions();
- if (fElementType.isStandardType() || fElementType.isGenericType() || fElementType.isPrimitiveType()) {
- fErasure= this;
- } else {
- fErasure= getEnvironment().create(binding.getErasure());
- }
- }
-
- protected void initialize(TType elementType, int dimensions) {
- fElementType= elementType;
- fDimensions= dimensions;
- if (fElementType.isStandardType() || fElementType.isGenericType() || fElementType.isPrimitiveType()) {
- fErasure= this;
- } else {
- fErasure= getEnvironment().createArrayType(elementType.getErasure(), dimensions);
- }
- }
-
- public TType getElementType() {
- return fElementType;
- }
-
- /**
- * Returns the component type of this array.
- * If getDimensions() is 1, the component type is the element type.
- * If getDimensions() is > 1, the component type is an array type
- * with element type getElementType() and dimensions getDimensions() - 1.
- *
- * @return the component type
- */
- public TType getComponentType() {
- if (fDimensions > 1)
- return getEnvironment().createArrayType(fElementType, fDimensions - 1);
- else
- return fElementType;
- }
-
- public int getDimensions() {
- return fDimensions;
- }
-
- public int getKind() {
- return ARRAY_TYPE;
- }
-
- public TType[] getSubTypes() {
- TType[] subTypes= fElementType.getSubTypes();
- TType[] result= new TType[subTypes.length];
- for (int i= 0; i < subTypes.length; i++) {
- result[i]= getEnvironment().createArrayType(subTypes[i], fDimensions);
- }
- return result;
- }
-
- public TType getErasure() {
- return fErasure;
- }
-
- public boolean doEquals(TType other) {
- ArrayType arrayType= (ArrayType)other;
- return fElementType.equals(arrayType.fElementType) && fDimensions == arrayType.fDimensions;
- }
-
- public int hashCode() {
- return fElementType.hashCode() << ARRAY_TYPE_SHIFT;
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- switch (lhs.getKind()) {
- case NULL_TYPE: return false;
- case VOID_TYPE: return false;
- case PRIMITIVE_TYPE: return false;
-
- case ARRAY_TYPE: return canAssignToArrayType((ArrayType)lhs);
-
- case GENERIC_TYPE: return false;
- case STANDARD_TYPE: return isArrayLhsCompatible(lhs);
- case PARAMETERIZED_TYPE: return false;
- case RAW_TYPE: return false;
-
- case UNBOUND_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- case SUPER_WILDCARD_TYPE:
- return ((WildcardType)lhs).checkAssignmentBound(this);
-
- case TYPE_VARIABLE: return false;
- case CAPTURE_TYPE:
- return ((CaptureType)lhs).checkLowerBound(lhs);
- }
- return false;
- }
-
- private boolean canAssignToArrayType(ArrayType lhs) {
- if (fDimensions == lhs.fDimensions) {
- // primitive type don't have any conversion for arrays.
- if (fElementType.getKind() == PRIMITIVE_TYPE || lhs.fElementType.getKind() == PRIMITIVE_TYPE)
- return fElementType.isTypeEquivalentTo(lhs.fElementType);
- return fElementType.canAssignTo(lhs.fElementType);
- }
- if (fDimensions < lhs.fDimensions)
- return false;
- return isArrayLhsCompatible(lhs.fElementType);
- }
-
- private boolean isArrayLhsCompatible(TType lhsElementType) {
- return lhsElementType.isJavaLangObject() || lhsElementType.isJavaLangCloneable() || lhsElementType.isJavaIoSerializable();
- }
-
- protected String getPlainPrettySignature() {
- StringBuffer result= new StringBuffer(fElementType.getPlainPrettySignature());
- for (int i= 0; i < fDimensions; i++) {
- result.append("[]"); //$NON-NLS-1$
- }
- return result.toString();
- }
-
- public String getName() {
- StringBuffer result= new StringBuffer(fElementType.getName());
- for (int i= 0; i < fDimensions; i++) {
- result.append("[]"); //$NON-NLS-1$
- }
- return result.toString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/CaptureType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/CaptureType.java
deleted file mode 100644
index 4a0dd3ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/CaptureType.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-
-public final class CaptureType extends AbstractTypeVariable {
-
- private WildcardType fWildcard;
- private IJavaScriptProject fJavaProject;
-
- protected CaptureType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding, IJavaScriptProject javaProject) {
- Assert.isTrue(false);
- super.initialize(binding);
- fJavaProject= javaProject;
- }
-
- public int getKind() {
- return CAPTURE_TYPE;
- }
-
- public WildcardType getWildcard() {
- return fWildcard;
- }
-
- public boolean doEquals(TType type) {
- return getBindingKey().equals(((CaptureType)type).getBindingKey())
- && fJavaProject.equals(((CaptureType)type).fJavaProject);
- }
-
- public int hashCode() {
- return getBindingKey().hashCode();
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- switch (lhs.getKind()) {
- case NULL_TYPE:
- case VOID_TYPE:
- case PRIMITIVE_TYPE:
- return false;
-
- case ARRAY_TYPE:
- return canAssignFirstBoundTo(lhs);
-
- case GENERIC_TYPE:
- return false;
-
- case STANDARD_TYPE:
- case PARAMETERIZED_TYPE:
- case RAW_TYPE:
- return canAssignOneBoundTo(lhs);
-
- case UNBOUND_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- case SUPER_WILDCARD_TYPE:
- return ((WildcardType)lhs).checkAssignmentBound(this);
-
- case TYPE_VARIABLE:
- return false; //fWildcard.doCanAssignTo(lhs);
-
- case CAPTURE_TYPE:
- return ((CaptureType)lhs).checkLowerBound(this.getWildcard());
-
- }
- return false;
- }
-
- protected boolean checkLowerBound(TType rhs) {
- if (! getWildcard().isSuperWildcardType())
- return false;
-
- return rhs.canAssignTo(getWildcard().getBound());
- }
-
- private boolean canAssignFirstBoundTo(TType lhs) {
- if (fBounds.length > 0 && fBounds[0].isArrayType()) {
- // capture of ? extends X[]
- return fBounds[0].canAssignTo(lhs);
- }
- return false;
- }
-
- public String getName() {
- return ""; //$NON-NLS-1$
- }
-
- protected String getPlainPrettySignature() {
- return "capture-of " + fWildcard.getPrettySignature(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/GenericType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/GenericType.java
deleted file mode 100644
index 0074a67b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/GenericType.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public final class GenericType extends HierarchyType {
-
- protected GenericType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding, IType javaElementType) {
- Assert.isTrue(false);
- super.initialize(binding, javaElementType);
- }
-
- public int getKind() {
- return GENERIC_TYPE;
- }
-
- public boolean doEquals(TType type) {
- return getJavaElementType().equals(((GenericType)type).getJavaElementType());
- }
-
- public int hashCode() {
- return getJavaElementType().hashCode();
- }
-
- protected boolean doCanAssignTo(TType type) {
- return false;
- }
-
- protected boolean isTypeEquivalentTo(TType other) {
- int otherElementType= other.getKind();
- if (otherElementType == RAW_TYPE || otherElementType == PARAMETERIZED_TYPE)
- return getErasure().isTypeEquivalentTo(other.getErasure());
- return super.isTypeEquivalentTo(other);
- }
-
- public String getName() {
- return getJavaElementType().getElementName();
- }
-
- protected String getPlainPrettySignature() {
- StringBuffer result= new StringBuffer(getJavaElementType().getFullyQualifiedName('.'));
- result.append("<"); //$NON-NLS-1$
- result.append(">"); //$NON-NLS-1$
- return result.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/HierarchyType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/HierarchyType.java
deleted file mode 100644
index 0de044ec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/HierarchyType.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public abstract class HierarchyType extends TType {
- private HierarchyType fSuperclass;
- private IType fJavaElementType;
-
- protected HierarchyType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding, IType javaElementType) {
- super.initialize(binding);
- Assert.isNotNull(javaElementType);
- fJavaElementType= javaElementType;
- TypeEnvironment environment= getEnvironment();
- ITypeBinding superclass= binding.getSuperclass();
- if (superclass != null) {
- fSuperclass= (HierarchyType)environment.create(superclass);
- }
- }
-
- public TType getSuperclass() {
- return fSuperclass;
- }
-
- public IType getJavaElementType() {
- return fJavaElementType;
- }
-
- public boolean isSubType(HierarchyType other) {
- if (getEnvironment() == other.getEnvironment()) {
- Map cache= getEnvironment().getSubTypeCache();
- TypeTuple key= new TypeTuple(this, other);
- Boolean value= (Boolean)cache.get(key);
- if (value != null)
- return value.booleanValue();
- boolean isSub= doIsSubType(other);
- value= Boolean.valueOf(isSub);
- cache.put(key, value);
- return isSub;
- }
- return doIsSubType(other);
- }
-
- private boolean doIsSubType(HierarchyType other) {
- if (fSuperclass != null && (other.isTypeEquivalentTo(fSuperclass) || fSuperclass.doIsSubType(other)))
- return true;
- return false;
- }
-
- protected boolean canAssignToStandardType(StandardType target) {
- if (target.isJavaLangObject())
- return true;
- return isSubType(target);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/NullType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/NullType.java
deleted file mode 100644
index ca8a4aca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/NullType.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-
-public final class NullType extends TType {
-
- protected NullType(TypeEnvironment environment) {
- super(environment, "N"); //$NON-NLS-1$
- }
-
- public int getKind() {
- return NULL_TYPE;
- }
-
- public TType[] getSubTypes() {
- throw new UnsupportedOperationException();
- }
-
- protected boolean doEquals(TType type) {
- return true;
- }
-
- public String getName() {
- return "null"; //$NON-NLS-1$
- }
-
- protected String getPlainPrettySignature() {
- return getName();
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- int kind= lhs.getKind();
- return kind != PRIMITIVE_TYPE && kind != VOID_TYPE;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/PrimitiveType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/PrimitiveType.java
deleted file mode 100644
index 018c48e1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/PrimitiveType.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-
-public final class PrimitiveType extends TType {
-
- /** Type code for the primitive type "int". */
- public static final int INT = 0;
- /** Type code for the primitive type "char". */
- public static final int CHAR = 1;
- /** Type code for the primitive type "boolean". */
- public static final int BOOLEAN = 2;
- /** Type code for the primitive type "short". */
- public static final int SHORT = 3;
- /** Type code for the primitive type "long". */
- public static final int LONG = 4;
- /** Type code for the primitive type "float". */
- public static final int FLOAT = 5;
- /** Type code for the primitive type "double". */
- public static final int DOUBLE = 6;
- /** Type code for the primitive type "byte". */
- public static final int BYTE = 7;
-
- static final String[] NAMES= {
- "int", //$NON-NLS-1$
- "char", //$NON-NLS-1$
- "boolean", //$NON-NLS-1$
- "short", //$NON-NLS-1$
- "long", //$NON-NLS-1$
- "float", //$NON-NLS-1$
- "double", //$NON-NLS-1$
- "byte"}; //$NON-NLS-1$
-
- private int fId;
-
- protected PrimitiveType(TypeEnvironment environment, int id, String signature) {
- super(environment, signature);
- fId= id;
- }
-
- public int getId() {
- return fId;
- }
-
- public int getKind() {
- return PRIMITIVE_TYPE;
- }
-
- protected boolean doEquals(TType type) {
- return fId == ((PrimitiveType)type).fId;
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- if (lhs.getKind() != PRIMITIVE_TYPE) {
- if (lhs.getKind() == STANDARD_TYPE) {
- IJavaScriptProject javaProject= ((StandardType)lhs).getJavaElementType().getJavaScriptProject();
- return getEnvironment().createBoxed(this, javaProject).canAssignTo(lhs);
- }
- return false;
- }
-
- switch (((PrimitiveType)lhs).fId) {
- case BOOLEAN :
- case BYTE :
- case CHAR :
- return false;
- case DOUBLE :
- switch (fId) {
- case BYTE :
- case CHAR :
- case SHORT :
- case INT :
- case LONG :
- case FLOAT :
- return true;
- default :
- return false;
- }
- case FLOAT :
- switch (fId) {
- case BYTE :
- case CHAR :
- case SHORT :
- case INT :
- case LONG :
- return true;
- default :
- return false;
- }
- case LONG :
- switch (fId) {
- case BYTE :
- case CHAR :
- case SHORT :
- case INT :
- return true;
- default :
- return false;
- }
- case INT :
- switch (fId) {
- case BYTE :
- case CHAR :
- case SHORT :
- return true;
- default :
- return false;
- }
- case SHORT :
- return (fId == BYTE);
- }
- return false;
- }
-
- public String getName() {
- return NAMES[fId];
- }
-
- protected String getPlainPrettySignature() {
- return NAMES[fId];
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/RawType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/RawType.java
deleted file mode 100644
index 6895f06f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/RawType.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public final class RawType extends HierarchyType {
-
- private HierarchyType fTypeDeclaration;
-
- protected RawType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding, IType javaElementType) {
- Assert.isTrue(false);
- super.initialize(binding, javaElementType);
- TypeEnvironment environment= getEnvironment();
- fTypeDeclaration= (HierarchyType)environment.create(binding.getTypeDeclaration());
- }
-
- public int getKind() {
- return RAW_TYPE;
- }
-
- public boolean doEquals(TType type) {
- return getJavaElementType().equals(((RawType)type).getJavaElementType());
- }
-
- public int hashCode() {
- return getJavaElementType().hashCode();
- }
-
- public TType getTypeDeclaration() {
- return fTypeDeclaration;
- }
-
- public TType getErasure() {
- return fTypeDeclaration;
- }
-
- /*package*/ HierarchyType getHierarchyType() {
- return fTypeDeclaration;
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- int targetType= lhs.getKind();
- switch (targetType) {
- case NULL_TYPE: return false;
- case VOID_TYPE: return false;
- case PRIMITIVE_TYPE: return false;
-
- case ARRAY_TYPE: return false;
-
- case STANDARD_TYPE: return canAssignToStandardType((StandardType)lhs);
- case GENERIC_TYPE: return false;
- case RAW_TYPE: return isSubType((HierarchyType)lhs);
-
- case UNBOUND_WILDCARD_TYPE:
- case SUPER_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- return ((WildcardType)lhs).checkAssignmentBound(this);
-
- case TYPE_VARIABLE: return false;
- case CAPTURE_TYPE:
- return ((CaptureType)lhs).checkLowerBound(this);
- }
- return false;
- }
-
- protected boolean isTypeEquivalentTo(TType other) {
- int otherElementType= other.getKind();
- if (otherElementType == PARAMETERIZED_TYPE || otherElementType == GENERIC_TYPE)
- return getErasure().isTypeEquivalentTo(other.getErasure());
- return super.isTypeEquivalentTo(other);
- }
-
- public String getName() {
- return getJavaElementType().getElementName();
- }
-
- protected String getPlainPrettySignature() {
- return getJavaElementType().getFullyQualifiedName('.');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/StandardType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/StandardType.java
deleted file mode 100644
index ede545dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/StandardType.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.wst.jsdt.core.BindingKey;
-
-
-public final class StandardType extends HierarchyType {
-
- private static final String OBJECT_KEY= BindingKey.createTypeBindingKey("java.lang.Object"); //$NON-NLS-1$
- private static final String CLONEABLE_KEY= BindingKey.createTypeBindingKey("java.lang.Cloneable"); //$NON-NLS-1$
- private static final String SERIALIZABLE_KEY= BindingKey.createTypeBindingKey("java.io.Serializable"); //$NON-NLS-1$
-
- protected StandardType(TypeEnvironment environment) {
- super(environment);
- }
-
- public int getKind() {
- return STANDARD_TYPE;
- }
-
- public boolean isJavaLangObject() {
- return OBJECT_KEY.equals(getBindingKey());
- }
-
- public boolean isJavaLangCloneable() {
- return CLONEABLE_KEY.equals(getBindingKey());
- }
-
- public boolean isJavaIoSerializable() {
- return SERIALIZABLE_KEY.equals(getBindingKey());
- }
-
- public boolean doEquals(TType type) {
- return getJavaElementType().equals(((StandardType)type).getJavaElementType());
- }
-
- public int hashCode() {
- return getJavaElementType().hashCode();
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- switch (lhs.getKind()) {
- case NULL_TYPE: return false;
- case VOID_TYPE: return false;
- case PRIMITIVE_TYPE: return canAssignToPrimitive((PrimitiveType)lhs);
-
- case ARRAY_TYPE: return false;
-
- case STANDARD_TYPE: return canAssignToStandardType((StandardType)lhs);
- case GENERIC_TYPE: return false;
- case PARAMETERIZED_TYPE: return isSubType((HierarchyType)lhs);
- case RAW_TYPE: return isSubType((HierarchyType)lhs);
-
- case UNBOUND_WILDCARD_TYPE:
- case SUPER_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- return ((WildcardType)lhs).checkAssignmentBound(this);
-
- case TYPE_VARIABLE: return false;
-
- case CAPTURE_TYPE:
- return ((CaptureType)lhs).checkLowerBound(this);
- }
- return false;
- }
-
- private boolean canAssignToPrimitive(PrimitiveType type) {
- PrimitiveType source= getEnvironment().createUnBoxed(this);
- return source != null && source.canAssignTo(type);
- }
-
- public String getName() {
- return getJavaElementType().getElementName();
- }
-
- protected String getPlainPrettySignature() {
- return getJavaElementType().getFullyQualifiedName('.');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TType.java
deleted file mode 100644
index ae5621da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TType.java
+++ /dev/null
@@ -1,574 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public abstract class TType {
-
- public static final int NULL_TYPE= 1;
- public static final int VOID_TYPE= 2;
- public static final int PRIMITIVE_TYPE= 3;
-
- public static final int ARRAY_TYPE= 4;
-
- public static final int STANDARD_TYPE= 5;
- public static final int GENERIC_TYPE= 6;
- public static final int PARAMETERIZED_TYPE= 7;
- public static final int RAW_TYPE= 8;
-
- public static final int UNBOUND_WILDCARD_TYPE= 9;
- public static final int SUPER_WILDCARD_TYPE= 10;
- public static final int EXTENDS_WILDCARD_TYPE= 11;
-
- public static final int TYPE_VARIABLE= 12;
- public static final int CAPTURE_TYPE= 13;
-
- protected static final int WILDCARD_TYPE_SHIFT= 3;
- protected static final int ARRAY_TYPE_SHIFT= 5;
-
- private static final int F_IS_CLASS= 1 << 0;
- private static final int F_IS_INTERFACE= 1 << 1;
- private static final int F_IS_ENUM= 1 << 2;
- private static final int F_IS_ANNOTATION= 1 << 3;
-
- private static final int F_IS_TOP_LEVEL= 1 << 4;
- private static final int F_IS_NESTED= 1 << 5;
- private static final int F_IS_MEMBER= 1 << 6;
- private static final int F_IS_LOCAL= 1 << 7;
- private static final int F_IS_ANONYMOUS= 1 << 8;
-
- protected static final TType[] EMPTY_TYPE_ARRAY= new TType[0];
-
- private TypeEnvironment fEnvironment;
- private String fBindingKey;
- private int fModifiers;
- private int fFlags;
-
- /**
- * Creates a new type with the given environment as an owner
- */
- protected TType(TypeEnvironment environment) {
- fEnvironment= environment;
- }
-
- /**
- * Creates a new type with the given environment as an owner
- */
- protected TType(TypeEnvironment environment, String key) {
- this(environment);
- Assert.isNotNull(key);
- fBindingKey= key;
- }
-
- /**
- * Initialized the type from the given binding
- *
- * @param binding the binding to initialize from
- */
- protected void initialize(ITypeBinding binding) {
- fBindingKey= binding.getKey();
- Assert.isNotNull(fBindingKey);
- fModifiers= binding.getModifiers();
- if (binding.isClass()) {
- fFlags= F_IS_CLASS;
- // the annotation test has to be done before test for interface
- // since annotations are interfaces as well.
- }
-
- if (binding.isTopLevel()) {
- fFlags|= F_IS_TOP_LEVEL;
- } else if (binding.isNested()) {
- fFlags|= F_IS_NESTED;
- if (binding.isMember()) {
- fFlags|= F_IS_MEMBER;
- } else if (binding.isLocal()) {
- fFlags|= F_IS_LOCAL;
- } else if (binding.isAnonymous()) {
- fFlags|= F_IS_ANONYMOUS;
- }
- }
- }
-
- /**
- * Returns the type's environment
- *
- * @return the types's environment
- */
- public TypeEnvironment getEnvironment() {
- return fEnvironment;
- }
-
- /**
- * Returns the key of the binding from which this type
- * got constructed.
- *
- * @return the binding key
- */
- public String getBindingKey() {
- return fBindingKey;
- }
-
- /**
- * Returns the modifiers for this type.
- *
- * @return the bit-wise or of <code>Modifier</code> constants
- * @see org.eclipse.wst.jsdt.core.dom.IBinding#getModifiers()
- * @see org.eclipse.wst.jsdt.core.dom.Modifier
- */
- public int getModifiers() {
- return fModifiers;
- }
-
- /**
- * Returns the element kind
- *
- * @return the element kind.
- */
- public abstract int getKind();
-
- /**
- * Returns whether this type represents <code>java.lang.Object</code> or
- * not.
- *
- * @return whether this type is <code>java.lang.Object</code> or not
- */
- public boolean isJavaLangObject() {
- return false;
- }
-
- /**
- * Returns whether this type represents <code>java.lang.Cloneable</code>
- * or not.
- *
- * @return whether this type is <code>java.lang.Cloneable</code> or not
- */
- public boolean isJavaLangCloneable() {
- return false;
- }
-
- /**
- * Returns whether this type represents <code>java.io.Serializable</code>
- * or not.
- *
- * @return whether this type is <code>java.io.Serializable</code> or not
- */
- public boolean isJavaIoSerializable() {
- return false;
- }
-
- /**
- * Returns <code>true</code> if the given type represents the null type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is the null type or not
- */
- public final boolean isNullType() {
- return getKind() == NULL_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents the void type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is the void type or not
- */
- public final boolean isVoidType() {
- return getKind() == VOID_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a primitive type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a primitive type or not
- */
- public final boolean isPrimitiveType() {
- return getKind() == PRIMITIVE_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents an array type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is an array type or not
- */
- public final boolean isArrayType() {
- return getKind() == ARRAY_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a hierarchy type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a hierarchy type or not
- */
- public final boolean isHierarchyType() {
- int elementType= getKind();
- return elementType == RAW_TYPE || elementType == PARAMETERIZED_TYPE
- || elementType == GENERIC_TYPE || elementType == STANDARD_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a standard type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a standard type or not
- */
- public final boolean isStandardType() {
- return getKind() == STANDARD_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a raw type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a raw type or not
- */
- public final boolean isRawType() {
- return getKind() == RAW_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a parameterized type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a parameterized type or not
- */
- public final boolean isParameterizedType() {
- return getKind() == PARAMETERIZED_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a generic type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a generic type or not
- */
- public final boolean isGenericType() {
- return getKind() == GENERIC_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a type variable.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a type variable or not
- */
- public final boolean isTypeVariable() {
- return getKind() == TYPE_VARIABLE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a capture type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a capture type or not
- */
- public final boolean isCaptureType() {
- return getKind() == CAPTURE_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a wildcard type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a wildcard type or not
- */
- public final boolean isWildcardType() {
- int elementType= getKind();
- return elementType == EXTENDS_WILDCARD_TYPE || elementType == UNBOUND_WILDCARD_TYPE
- || elementType == SUPER_WILDCARD_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a unbound wildcard type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a unbound wildcard type or not
- */
- public final boolean isUnboundWildcardType() {
- return getKind() == UNBOUND_WILDCARD_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents an extends wildcard type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is an extends wildcard type or not
- */
- public final boolean isExtendsWildcardType() {
- return getKind() == EXTENDS_WILDCARD_TYPE;
- }
-
- /**
- * Returns <code>true</code> if the given type represents a super wildcard type.
- * Otherwise <code>false</code> is returned.
- *
- * @return whether this type is a super wildcard type or not
- */
- public final boolean isSuperWildcardType() {
- return getKind() == SUPER_WILDCARD_TYPE;
- }
-
- /**
- * Returns whether this type represents a class.
- *
- * @return whether this type represents a class
- * @see ITypeBinding#isClass()
- */
- public final boolean isClass() {
- return (fFlags & F_IS_CLASS) != 0;
- }
-
- /**
- * Returns whether this type represents a interface.
- *
- * @return whether this type represents a interface
- * @see ITypeBinding#isInterface()
- */
- public final boolean isInterface() {
- return (fFlags & F_IS_INTERFACE) != 0;
- }
-
- /**
- * Returns whether this type represents a enumeration.
- *
- * @return whether this type represents a enumeration
- * @see ITypeBinding#isEnum()
- */
- public final boolean isEnum() {
- return (fFlags & F_IS_ENUM) != 0;
- }
-
- /**
- * Returns whether this type represents an annotation.
- *
- * @return whether this type represents an annotation
- * @see ITypeBinding#isAnnotation()
- */
- public final boolean isAnnotation() {
- return (fFlags & F_IS_ANNOTATION) != 0;
- }
-
- /**
- * Returns whether this type represents a top level type.
- *
- * @return whether this type represents a top level type
- * @see ITypeBinding#isTopLevel()
- */
- public final boolean isTopLevel() {
- return (fFlags & F_IS_TOP_LEVEL) != 0;
- }
-
- /**
- * Returns whether this type represents a nested type.
- *
- * @return whether this type represents a nested type
- * @see ITypeBinding#isNested()
- */
- public final boolean isNested() {
- return (fFlags & F_IS_NESTED) != 0;
- }
-
- /**
- * Returns whether this type represents a member type.
- *
- * @return whether this type represents a member type
- * @see ITypeBinding#isMember()
- */
- public final boolean isMember() {
- return (fFlags & F_IS_MEMBER) != 0;
- }
-
- /**
- * Returns whether this type represents a local type.
- *
- * @return whether this type represents a local type
- * @see ITypeBinding#isLocal()
- */
- public final boolean isLocal() {
- return (fFlags & F_IS_LOCAL) != 0;
- }
-
- /**
- * Returns whether this type represents an anonymous type.
- *
- * @return whether this type represents an anonymous type
- * @see ITypeBinding#isAnonymous()
- */
- public final boolean isAnonymous() {
- return (fFlags & F_IS_ANONYMOUS) != 0;
- }
-
- /**
- * Returns the super classes of this type or <code>null</code>.
- *
- * @return the super class of this type
- */
- public TType getSuperclass() {
- return null;
- }
-
- /**
- * Returns the interfaces this type implements or extends.
- *
- * @return the "super" interfaces or an empty array
- */
- public TType[] getInterfaces() {
- return EMPTY_TYPE_ARRAY;
- }
-
- public boolean isEqualTo(ITypeBinding binding) {
- if (binding == null)
- return false;
- return binding.getKey().equals(fBindingKey);
- }
-
- /**
- * {@inheritDoc}
- */
- public final boolean equals(Object other) {
- if (this == other)
- return true;
- if (!(other instanceof TType))
- return false;
- TType otherType= (TType)other;
- if (getKind() != otherType.getKind())
- return false;
- return doEquals(otherType);
- }
-
- /**
- * Performs the actual equals check.
- *
- * @param type The right hand side of the equals operation. The dynamic type
- * of the actual argument must be the same as the receiver type.
- */
- protected abstract boolean doEquals(TType type);
-
- /**
- * Returns the erasure of this type as defined by ITypeBinding#getErasure().
- *
- * @return the erasure of this type
- */
- public TType getErasure() {
- return this;
- }
-
- /**
- * Returns the type for the type declaration corresponding to this type.
- *
- * @return the type representing the declaration of this type
- * @see ITypeBinding#getTypeDeclaration()
- */
- public TType getTypeDeclaration() {
- return this;
- }
-
- /**
- * @return direct subtypes of this type
- * @throws IllegalStateException if this type's TypeEnvironment
- * was not created with rememberSubtypes == true
- */
- public TType[] getSubTypes() throws IllegalStateException {
- Map subTypes= fEnvironment.getSubTypes();
- if (subTypes == null)
- throw new IllegalStateException("This TypeEnvironment does not remember subtypes"); //$NON-NLS-1$
- List subtypes= (List) subTypes.get(this);
- if (subtypes == null)
- return EMPTY_TYPE_ARRAY;
- else
- return (TType[]) subtypes.toArray(new TType[subtypes.size()]);
- }
-
- /**
- * Answer <code>true</code> if the receiver of this method can be assigned
- * to the argument lhs (e.g lhs= this is a valid assignment).
- *
- * @param lhs the left hand side of the assignment
- * @return whether or not this type can be assigned to lhs
- */
- public final boolean canAssignTo(TType lhs) {
- if (this.isTypeEquivalentTo(lhs))
- return true;
- return doCanAssignTo(lhs);
- }
-
- /**
- * Returns whether the receiver type is type equivalent to the other type.
- * This method considers the erasure for generic, raw and parameterized
- * types.
- *
- * @return whether the receiver is type equivalent to other
- */
- protected boolean isTypeEquivalentTo(TType other) {
- return this.equals(other);
- }
-
- /**
- * Checks whether the <code>this</code> left hand side type interpreted as
- * a type argument of a parameterized type is compatible with the given type
- * <code>rhs</code>. For example if
- * <code>List&lt;this&gt;= List&lt;rhs&gt;</code> is a valid assignment.
- *
- * @return <code>true</code> iff <code>this</code> contains <code>rhs</code> according to JLS3 4.5.1.1
- */
- protected boolean checkTypeArgument(TType rhs) {
- return this.equals(rhs);
- }
-
- /**
- * Hook method to perform the actual can assign test
- *
- * @param lhs the left hand side of the assignment
- * @return whether or not this type can be assigned to lhs
- */
- protected abstract boolean doCanAssignTo(TType lhs);
-
- /**
- * Returns the name of this type as defined by {@link ITypeBinding#getName()}.
- *
- * @return the name of this type
- * @see ITypeBinding#getName()
- */
- public abstract String getName();
-
- /**
- * Returns a signature of this type which can be presented to the user.
- *
- * @return a pretty signature for this type
- */
- public String getPrettySignature() {
- return getPlainPrettySignature();
- }
-
- /**
- * Computes a plain pretty signature. For type with bounds (e.g
- * type variables and wildcards) the plain signature is different
- * than the full pretty signature.
- *
- * @return a plain pretty signature for this type
- */
- protected abstract String getPlainPrettySignature();
-
- /**
- * {@inheritDoc}
- */
- public String toString() {
- return getPrettySignature();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeEnvironment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeEnvironment.java
deleted file mode 100644
index c0798e30..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeEnvironment.java
+++ /dev/null
@@ -1,367 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.BindingKey;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-
-public class TypeEnvironment {
-
- private static class ProjectKeyPair {
- private final IJavaScriptProject fProject;
- private final String fBindingKey;
-
- public ProjectKeyPair(IJavaScriptProject project, String bindingKey) {
- fProject= project;
- fBindingKey= bindingKey;
- }
-
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (! (other instanceof ProjectKeyPair))
- return false;
- ProjectKeyPair otherPair= (ProjectKeyPair) other;
- return fProject.equals(otherPair.fProject) && fBindingKey.equals(otherPair.fBindingKey);
- }
-
- public int hashCode() {
- return fProject.hashCode() + fBindingKey.hashCode();
- }
- }
-
- /** Type code for the primitive type "int". */
- public final PrimitiveType INT= new PrimitiveType(this, PrimitiveType.INT, BindingKey.createTypeBindingKey("int")); //$NON-NLS-1$
- /** Type code for the primitive type "char". */
- public final PrimitiveType CHAR = new PrimitiveType(this, PrimitiveType.CHAR, BindingKey.createTypeBindingKey("char")); //$NON-NLS-1$
- /** Type code for the primitive type "boolean". */
- public final PrimitiveType BOOLEAN = new PrimitiveType(this, PrimitiveType.BOOLEAN, BindingKey.createTypeBindingKey("boolean")); //$NON-NLS-1$
- /** Type code for the primitive type "short". */
- public final PrimitiveType SHORT = new PrimitiveType(this, PrimitiveType.SHORT, BindingKey.createTypeBindingKey("short")); //$NON-NLS-1$
- /** Type code for the primitive type "long". */
- public final PrimitiveType LONG = new PrimitiveType(this, PrimitiveType.LONG, BindingKey.createTypeBindingKey("long")); //$NON-NLS-1$
- /** Type code for the primitive type "float". */
- public final PrimitiveType FLOAT = new PrimitiveType(this, PrimitiveType.FLOAT, BindingKey.createTypeBindingKey("float")); //$NON-NLS-1$
- /** Type code for the primitive type "double". */
- public final PrimitiveType DOUBLE = new PrimitiveType(this, PrimitiveType.DOUBLE, BindingKey.createTypeBindingKey("double")); //$NON-NLS-1$
- /** Type code for the primitive type "byte". */
- public final PrimitiveType BYTE = new PrimitiveType(this, PrimitiveType.BYTE, BindingKey.createTypeBindingKey("byte")); //$NON-NLS-1$
-
- /** Type code for the primitive type "null". */
- public final NullType NULL= new NullType(this);
-
- public final VoidType VOID= new VoidType(this);
-
- final PrimitiveType[] PRIMITIVE_TYPES= {INT, CHAR, BOOLEAN, SHORT, LONG, FLOAT, DOUBLE, BYTE};
-
- private static final String[] BOXED_PRIMITIVE_NAMES= new String[] {
- "java.lang.Integer", //$NON-NLS-1$
- "java.lang.Character", //$NON-NLS-1$
- "java.lang.Boolean", //$NON-NLS-1$
- "java.lang.Short", //$NON-NLS-1$
- "java.lang.Long", //$NON-NLS-1$
- "java.lang.Float", //$NON-NLS-1$
- "java.lang.Double", //$NON-NLS-1$
- "java.lang.Byte"}; //$NON-NLS-1$
-
- private TType OBJECT_TYPE= null;
-
- private Map/*<TType, ArrayType>*/[] fArrayTypes= new Map[] { new HashMap() };
- private Map/*<IJavaScriptElement, StandardType>*/ fStandardTypes= new HashMap();
- private Map/*<IJavaScriptElement, GenericType>*/ fGenericTypes= new HashMap();
- private Map/*<ProjectKeyPair, ParameterizedType>*/ fParameterizedTypes= new HashMap();
- private Map/*<IJavaScriptElement, RawType>*/ fRawTypes= new HashMap();
- private Map/*<ProjectKeyPair, CaptureType>*/ fCaptureTypes= new HashMap();
- private UnboundWildcardType fUnboundWildcardType= null;
-
- private static final int MAX_ENTRIES= 1024;
- private Map/*<TypeTuple, Boolean>*/ fSubTypeCache= new LinkedHashMap(50, 0.75f, true) {
- private static final long serialVersionUID= 1L;
- protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_ENTRIES;
- }
- };
-
- /**
- * Map from TType to its known subtypes, or <code>null</code> iff subtype
- * information was not requested in the constructor.
- */
- private Map/*<TType, List<TType>>*/ fSubTypes;
-
- public static ITypeBinding[] createTypeBindings(TType[] types, IJavaScriptProject project) {
- final Map mapping= new HashMap();
- List keys= new ArrayList();
- for (int i= 0; i < types.length; i++) {
- TType type= types[i];
- String bindingKey= type.getBindingKey();
- mapping.put(bindingKey, type);
- keys.add(bindingKey);
- }
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(project);
- parser.setResolveBindings(true);
- parser.createASTs(new IJavaScriptUnit[0], (String[])keys.toArray(new String[keys.size()]),
- new ASTRequestor() {
- public void acceptBinding(String bindingKey, IBinding binding) {
- mapping.put(bindingKey, binding);
- }
- }, null);
- ITypeBinding[] result= new ITypeBinding[types.length];
- for (int i= 0; i < types.length; i++) {
- TType type= types[i];
- String bindingKey= type.getBindingKey();
- Object value= mapping.get(bindingKey);
- if (value instanceof ITypeBinding) {
- result[i]= (ITypeBinding)value;
- }
- }
- return result;
- }
-
- public TypeEnvironment() {
- this(false);
- }
-
- public TypeEnvironment(boolean rememberSubtypes) {
- if (rememberSubtypes) {
- fSubTypes= new HashMap();
- }
- }
-
- Map/*<TypeTuple, Boolean>*/ getSubTypeCache() {
- return fSubTypeCache;
- }
-
- public TType create(ITypeBinding binding) {
- if (binding.isPrimitive()) {
- return createPrimitiveType(binding);
- } else if (binding.isArray()) {
- return createArrayType(binding);
- }
- if ("null".equals(binding.getName())) //$NON-NLS-1$
- return NULL;
- return createStandardType(binding);
- }
-
- public TType[] create(ITypeBinding[] bindings) {
- TType[] result= new TType[bindings.length];
- for (int i= 0; i < bindings.length; i++) {
- result[i]= create(bindings[i]);
- }
- return result;
- }
-
- /**
- * Returns the TType for java.lang.Object.
- * <p>
- * Warning: currently returns <code>null</code> unless this type environment
- * has already created its first hierarchy type.
- *
- * @return the TType for java.lang.Object
- */
- public TType getJavaLangObject() {
- return OBJECT_TYPE;
- }
-
- void initializeJavaLangObject(ITypeBinding object) {
- if (OBJECT_TYPE != null)
- return;
-
- TType objectType= createStandardType(object);
- Assert.isTrue(objectType.isJavaLangObject());
- }
-
- PrimitiveType createUnBoxed(StandardType type) {
- String name= type.getPlainPrettySignature();
- for (int i= 0; i < BOXED_PRIMITIVE_NAMES.length; i++) {
- if (BOXED_PRIMITIVE_NAMES[i].equals(name))
- return PRIMITIVE_TYPES[i];
- }
- return null;
- }
-
- StandardType createBoxed(PrimitiveType type, IJavaScriptProject focus) {
- String fullyQualifiedName= BOXED_PRIMITIVE_NAMES[type.getId()];
- try {
- IType javaElementType= focus.findType(fullyQualifiedName);
- StandardType result= (StandardType)fStandardTypes.get(javaElementType);
- if (result != null)
- return result;
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(focus);
- IBinding[] bindings= parser.createBindings(new IJavaScriptElement[] {javaElementType} , null);
- return createStandardType((ITypeBinding)bindings[0]);
- } catch (JavaScriptModelException e) {
- // fall through
- }
- return null;
- }
-
- Map/*<TType, List<TType>>*/ getSubTypes() {
- return fSubTypes;
- }
-
- private void cacheSubType(TType supertype, TType result) {
- if (fSubTypes == null)
- return;
- if (supertype == null)
- supertype= OBJECT_TYPE;
-
- ArrayList subtypes= (ArrayList) fSubTypes.get(supertype);
- if (subtypes == null) {
- subtypes= new ArrayList(5);
- fSubTypes.put(supertype, subtypes);
- } else {
- Assert.isTrue(! subtypes.contains(result));
- }
- subtypes.add(result);
- }
-
- private void cacheSubTypes(TType[] interfaces, TType result) {
- for (int i= 0; i < interfaces.length; i++) {
- cacheSubType(interfaces[i], result);
- }
- }
-
- private TType createPrimitiveType(ITypeBinding binding) {
- String name= binding.getName();
- String[] names= PrimitiveType.NAMES;
- for (int i= 0; i < names.length; i++) {
- if (name.equals(names[i])) {
- return PRIMITIVE_TYPES[i];
- }
- }
- Assert.isTrue(false, "Primitive type " + name + "unkown"); //$NON-NLS-1$//$NON-NLS-2$
- return null;
- }
-
- private ArrayType createArrayType(ITypeBinding binding) {
- int index= binding.getDimensions() - 1;
- TType elementType= create(binding.getElementType());
- Map/*<TType, ArrayType>*/ arrayTypes= getArrayTypesMap(index);
- ArrayType result= (ArrayType)arrayTypes.get(elementType);
- if (result != null)
- return result;
- result= new ArrayType(this);
- arrayTypes.put(elementType, result);
- result.initialize(binding, elementType);
- return result;
- }
-
- public ArrayType createArrayType(TType elementType, int dimensions) {
- Assert.isTrue(! elementType.isArrayType());
- Assert.isTrue(! elementType.isAnonymous());
- Assert.isTrue(dimensions > 0);
-
- int index= dimensions - 1;
- Map arrayTypes= getArrayTypesMap(index);
- ArrayType result= (ArrayType)arrayTypes.get(elementType);
- if (result != null)
- return result;
- result= new ArrayType(this, BindingKey.createArrayTypeBindingKey(elementType.getBindingKey(), dimensions));
- arrayTypes.put(elementType, result);
- result.initialize(elementType, dimensions);
- return result;
- }
-
- private Map/*<TType, ArrayType>*/ getArrayTypesMap(int index) {
- int oldLength= fArrayTypes.length;
- if (index >= oldLength) {
- Map[] newArray= new Map[index + 1];
- System.arraycopy(fArrayTypes, 0, newArray, 0, oldLength);
- fArrayTypes= newArray;
- }
- Map arrayTypes= fArrayTypes[index];
- if (arrayTypes == null) {
- arrayTypes= new HashMap();
- fArrayTypes[index]= arrayTypes;
- }
- return arrayTypes;
- }
-
- private StandardType createStandardType(ITypeBinding binding) {
- IJavaScriptElement javaElement= binding.getJavaElement();
- StandardType result= (StandardType)fStandardTypes.get(javaElement);
- if (result != null)
- return result;
- result= new StandardType(this);
- fStandardTypes.put(javaElement, result);
- result.initialize(binding, (IType)javaElement);
- if (OBJECT_TYPE == null && result.isJavaLangObject())
- OBJECT_TYPE= result;
- return result;
- }
-
- private GenericType createGenericType(ITypeBinding binding) {
- IJavaScriptElement javaElement= binding.getJavaElement();
- GenericType result= (GenericType)fGenericTypes.get(javaElement);
- if (result != null)
- return result;
- result= new GenericType(this);
- fGenericTypes.put(javaElement, result);
- result.initialize(binding, (IType)javaElement);
- cacheSubType(result.getSuperclass(), result);
- cacheSubTypes(result.getInterfaces(), result);
- return result;
- }
-
- private RawType createRawType(ITypeBinding binding) {
- IJavaScriptElement javaElement= binding.getJavaElement();
- RawType result= (RawType)fRawTypes.get(javaElement);
- if (result != null)
- return result;
- result= new RawType(this);
- fRawTypes.put(javaElement, result);
- result.initialize(binding, (IType)javaElement);
- cacheSubType(result.getSuperclass(), result);
- cacheSubTypes(result.getInterfaces(), result);
- return result;
- }
-
- private TType createUnboundWildcardType(ITypeBinding binding) {
- if (fUnboundWildcardType == null) {
- fUnboundWildcardType= new UnboundWildcardType(this);
- fUnboundWildcardType.initialize(binding);
- }
- return fUnboundWildcardType;
- }
-
- private CaptureType createCaptureType(ITypeBinding binding) {
- IJavaScriptProject javaProject= binding.getDeclaringClass().getJavaElement().getJavaScriptProject();
- String bindingKey= binding.getKey();
- ProjectKeyPair pair= new ProjectKeyPair(javaProject, bindingKey);
- CaptureType result= (CaptureType)fCaptureTypes.get(pair);
- if (result != null)
- return result;
- result= new CaptureType(this);
- fCaptureTypes.put(pair, result);
- result.initialize(binding, javaProject);
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeTuple.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeTuple.java
deleted file mode 100644
index 2e0eaa02..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/TypeTuple.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-
-public class TypeTuple {
- private TType fFirst;
- private TType fSecond;
-
- public TypeTuple(TType first, TType second) {
- super();
- fFirst= first;
- fSecond= second;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!(obj instanceof TypeTuple))
- return false;
- TypeTuple other= (TypeTuple)obj;
- return fFirst.equals(other.fFirst) && fSecond.equals(other.fSecond);
- }
-
- public int hashCode() {
- return fFirst.hashCode() << 16 + fSecond.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/UnboundWildcardType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/UnboundWildcardType.java
deleted file mode 100644
index 3da8dd64..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/UnboundWildcardType.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-public final class UnboundWildcardType extends WildcardType {
-
- protected UnboundWildcardType(TypeEnvironment environment) {
- super(environment);
- }
-
- public int getKind() {
- return UNBOUND_WILDCARD_TYPE;
- }
-
- public TType getErasure() {
- return getEnvironment().getJavaLangObject();
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- switch(lhs.getKind()) {
- case STANDARD_TYPE:
- return ((StandardType)lhs).isJavaLangObject();
- case UNBOUND_WILDCARD_TYPE:
- return true;
- case SUPER_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- return ((WildcardType)lhs).getBound().isJavaLangObject();
- case CAPTURE_TYPE:
- return ((CaptureType)lhs).checkLowerBound(this);
- default:
- return false;
- }
- }
-
- protected boolean checkTypeArgument(TType rhs) {
- switch(rhs.getKind()) {
- case ARRAY_TYPE:
- case STANDARD_TYPE:
- case PARAMETERIZED_TYPE:
- case RAW_TYPE:
- case UNBOUND_WILDCARD_TYPE:
- case EXTENDS_WILDCARD_TYPE:
- case SUPER_WILDCARD_TYPE:
- case TYPE_VARIABLE:
- case CAPTURE_TYPE:
- return true;
- default:
- return false;
- }
- }
-
- protected boolean checkAssignmentBound(TType rhs) {
- // unbound equals ? extends Object.
- return rhs.isNullType();
- }
-
- public String getName() {
- return "?"; //$NON-NLS-1$
- }
-
- protected String getPlainPrettySignature() {
- return getName();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/VoidType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/VoidType.java
deleted file mode 100644
index d1ed19ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/VoidType.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.wst.jsdt.core.Signature;
-
-
-public final class VoidType extends TType {
-
- protected VoidType(TypeEnvironment environment) {
- super(environment, Signature.createTypeSignature("void", true)); //$NON-NLS-1$
- }
-
- public int getKind() {
- return VOID_TYPE;
- }
-
- public TType[] getSubTypes() {
- throw new UnsupportedOperationException();
- }
-
- protected boolean doEquals(TType type) {
- return true;
- }
-
- protected boolean doCanAssignTo(TType lhs) {
- return false;
- }
-
- public String getName() {
- return "void"; //$NON-NLS-1$
- }
-
- protected String getPlainPrettySignature() {
- return getName();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/WildcardType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/WildcardType.java
deleted file mode 100644
index c57ba255..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/types/WildcardType.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-
-public abstract class WildcardType extends TType {
- protected TType fBound;
-
- protected WildcardType(TypeEnvironment environment) {
- super(environment);
- }
-
- protected void initialize(ITypeBinding binding) {
- Assert.isTrue(false);
- super.initialize(binding);
- }
-
- public TType getBound() {
- return fBound;
- }
-
- public TType[] getSubTypes() {
- throw new UnsupportedOperationException();
- }
-
- public boolean doEquals(TType type) {
- WildcardType other= (WildcardType)type;
- if (fBound == null)
- return other.fBound == null;
- return fBound.equals(other.fBound);
- }
-
- public int hashCode() {
- if (fBound == null)
- return super.hashCode();
- return fBound.hashCode() << WILDCARD_TYPE_SHIFT;
- }
-
- protected abstract boolean checkAssignmentBound(TType rhs);
-
- // protected abstract boolean checkTypeArgumentBound(TType rhs);
-
- protected String internalGetName(String keyword) {
- StringBuffer result= new StringBuffer("?"); //$NON-NLS-1$
- TType bound= getBound();
- if (bound != null) {
- result.append(" "); //$NON-NLS-1$
- result.append(keyword);
- result.append(" "); //$NON-NLS-1$
- result.append(bound.getName());
- }
- return result.toString();
- }
-
- protected String internalGetPrettySignature(String keyword) {
- StringBuffer result= new StringBuffer("?"); //$NON-NLS-1$
- TType bound= getBound();
- if (bound != null) {
- result.append(" "); //$NON-NLS-1$
- result.append(keyword);
- result.append(" "); //$NON-NLS-1$
- result.append(bound.getPlainPrettySignature());
- }
- return result.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArraySuperTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArraySuperTypeSet.java
deleted file mode 100644
index 5cd64833..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArraySuperTypeSet.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-/**
- * Represents the super-types of a set of array types. Special because this set
- * always includes Object.
- */
-public class ArraySuperTypeSet extends ArrayTypeSet {
- public ArraySuperTypeSet(TypeSet s) {
- super(s.getTypeSetEnvironment());
- if (s instanceof SuperTypesOfSingleton || s instanceof SuperTypesSet)
- fElemTypeSet= s.lowerBound(); // optimization: array-super(super(s)) == array-super(s)
- else
- fElemTypeSet= s;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#anyMember()
- */
- public TType anyMember() {
- return getJavaLangObject();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- if (t.equals(getJavaLangObject())) return true;
- if (!(t instanceof ArrayType))
- return false;
-
- ArrayType at= (ArrayType) t;
- TType atElemType= at.getComponentType();
-
- if (fElemTypeSet.contains(atElemType)) // try to avoid enumeration
- return true;
-
- for(Iterator iter= fElemTypeSet.iterator(); iter.hasNext(); ) {
- TType elemType= (TType) iter.next();
-
- if (TTypes.canAssignTo(elemType, atElemType))
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- if (s instanceof ArraySuperTypeSet) {
- ArraySuperTypeSet ats= (ArraySuperTypeSet) s;
-
- return fElemTypeSet.containsAll(ats.fElemTypeSet);
- } else if (s instanceof ArrayTypeSet) {
- ArrayTypeSet ats= (ArrayTypeSet) s;
-
- return fElemTypeSet.containsAll(ats.fElemTypeSet);
- } else
- return enumerate().containsAll(s);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#specialCasesIntersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (s2 instanceof ArraySuperTypeSet) {
- ArraySuperTypeSet ats2= (ArraySuperTypeSet) s2;
-
- if (ats2.fElemTypeSet.isUniverse())
- return new ArraySuperTypeSet(fElemTypeSet);
- } else if (s2 instanceof ArrayTypeSet) {
- ArrayTypeSet ats2= (ArrayTypeSet) s2;
-
- if (ats2.fElemTypeSet.isUniverse())
- return new ArrayTypeSet(fElemTypeSet); // intersection doesn't include Object, which is in 'this'
- }
- return super.specialCasesIntersectedWith(s2);
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- fEnumCache= new EnumeratedTypeSet(getTypeSetEnvironment());
- TypeSet elemSupers= fElemTypeSet.superTypes();
-
- for(Iterator iter= elemSupers.iterator(); iter.hasNext(); ) {
- TType elemSuper= (TType) iter.next();
-
- fEnumCache.add(TTypes.createArrayType(elemSuper, 1));
- }
-
- fEnumCache.add(getJavaLangObject());
- fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return true; // Object is the unique upper bound of any set of array types
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return new ArraySuperTypeSet(fElemTypeSet);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#superTypes()
- */
- public TypeSet superTypes() {
- return makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return getJavaLangObject();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return new SingletonTypeSet(getJavaLangObject(), getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.ArrayTypeSet#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj == this) return true;
- if (obj instanceof ArraySuperTypeSet) {
- ArraySuperTypeSet other= (ArraySuperTypeSet) obj;
-
- return fElemTypeSet.equals(other.fElemTypeSet);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#subTypes()
- */
- public TypeSet subTypes() {
- return getTypeSetEnvironment().getUniverseTypeSet();
- }
-
- public String toString() {
- return "{" + fID + ": array-super(" + fElemTypeSet + ")}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArrayTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArrayTypeSet.java
deleted file mode 100644
index 94e7918a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/ArrayTypeSet.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-/**
- * Represents the set of array types whose element types are in a given TypeSet.
- * I.e., ArrayTypeSet(S) = { x[] | x \in S }
- */
-public class ArrayTypeSet extends TypeSet {
- protected TypeSet fElemTypeSet;
-
- protected ArrayTypeSet(TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- }
-
- public ArrayTypeSet(TypeSet s) {
- super(s.getTypeSetEnvironment());
- fElemTypeSet= s;
- }
-
- /**
- * @return Returns the element TypeSet.
- */
- public TypeSet getElemTypeSet() {
- return fElemTypeSet;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return new ArrayTypeSet(fElemTypeSet);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return fElemTypeSet.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return new ArrayTypeSet(fElemTypeSet.upperBound());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- return new ArrayTypeSet(fElemTypeSet.lowerBound());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return fElemTypeSet.hasUniqueLowerBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return fElemTypeSet.hasUniqueUpperBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return TTypes.createArrayType(fElemTypeSet.uniqueLowerBound(), 1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return TTypes.createArrayType(fElemTypeSet.uniqueUpperBound(), 1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- if (!(t instanceof ArrayType))
- return false;
- ArrayType at= (ArrayType) t;
- return fElemTypeSet.contains(at.getComponentType());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- if (s instanceof ArrayTypeSet && !(s instanceof ArraySuperTypeSet)) {
- ArrayTypeSet ats= (ArrayTypeSet) s;
-
- return fElemTypeSet.containsAll(ats.fElemTypeSet);
- }
- for(Iterator iter= s.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
- if (!contains(t))
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- if (fEnumCache != null) return fEnumCache.iterator();
-
- return new Iterator() {
- Iterator fElemIter= fElemTypeSet.iterator();
- public boolean hasNext() {
- return fElemIter.hasNext();
- }
- public Object next() {
- return TTypes.createArrayType(((TType) fElemIter.next()), 1);
- }
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- fEnumCache= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- for(Iterator iter= fElemTypeSet.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
- fEnumCache.add(TTypes.createArrayType(t, 1));
- }
- fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return fElemTypeSet.isSingleton();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return TTypes.createArrayType(fElemTypeSet.anyMember(), 1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#superTypes()
- */
- public TypeSet superTypes() {
- return new ArraySuperTypeSet(fElemTypeSet);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj == this) return true;
- if (obj instanceof ArrayTypeSet) {
- ArrayTypeSet other= (ArrayTypeSet) obj;
-
- return fElemTypeSet.equals(other.fElemTypeSet);
- }
- return false;
- }
-
- public String toString() {
- return "{" + fID + ": array(" + fElemTypeSet + ")}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EmptyTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EmptyTypeSet.java
deleted file mode 100644
index aad90b7d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EmptyTypeSet.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public class EmptyTypeSet extends TypeSet {
-
- EmptyTypeSet(TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return new Iterator() {
- public void remove() {
- //do nothing
- }
- public boolean hasNext() {
- return false;
- }
- public Object next() {
- return null;
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return null;
- }
-
- public String toString() {
- return "{ }"; //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- return new EnumeratedTypeSet(getTypeSetEnvironment());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EnumeratedTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EnumeratedTypeSet.java
deleted file mode 100644
index 82a35d9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/EnumeratedTypeSet.java
+++ /dev/null
@@ -1,488 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-/**
- * A type-safe wrapper for Set<TType> that also adds TType-specific
- * functionality, e.g. subTypes() and superTypes().
- */
-public class EnumeratedTypeSet extends TypeSet {
- static private int sCount= 0;
-
- static public int getCount() {
- return sCount;
- }
-
- static public void resetCount() {
- sCount= 0;
- }
-
- /**
- * Set containing the TTypes in this EnumeratedTypeSet.
- */
- Set/*<TType>*/ fMembers= new LinkedHashSet();
-
- /**
- * Constructs a new EnumeratedTypeSet with the members of Set s in it.
- * All elements of s must be TTypes.
- */
- public EnumeratedTypeSet(Iterator types, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- while (types.hasNext()) {
- fMembers.add(types.next());
- }
- sCount++;
- }
-
- /**
- * Constructs an empty EnumeratedTypeSet.
- */
- public EnumeratedTypeSet(TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- sCount++;
- }
-
- /**
- * Constructs a new EnumeratedTypeSet with the given single TType in it.
- */
- public EnumeratedTypeSet(TType t, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- Assert.isNotNull(t);
- fMembers.add(t);
- sCount++;
- }
-
- /**
- * @return <code>true</code> iff this set represents the universe of TTypes
- */
- public boolean isUniverse() {
- return false;
- }
-
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o instanceof EnumeratedTypeSet) {
- EnumeratedTypeSet other= (EnumeratedTypeSet) o;
-
- return fMembers.equals(other.fMembers);
- } else if (o instanceof SingletonTypeSet) {
- SingletonTypeSet other= (SingletonTypeSet) o;
-
- return (fMembers.size() == 1) && fMembers.contains(other.anyMember());
- } else if (o instanceof TypeSet) {
- TypeSet other= (TypeSet) o;
-
- for(Iterator otherIter= other.iterator(); otherIter.hasNext(); ) {
- if (!fMembers.contains(otherIter.next()))
- return false;
- }
- for(Iterator myIter= fMembers.iterator(); myIter.hasNext(); ) {
- if (!other.contains((TType) myIter.next()))
- return false;
- }
- return true;
- } else
- return false;
- }
-
- public int hashCode() {
- return 37 + fMembers.hashCode();
- }
-
- /**
- * Computes and returns a <em>new</em> EnumeratedTypeSet representing the intersection of the
- * receiver with s2. Does not modify the receiver.
- * @param s2
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (s2 instanceof EnumeratedTypeSet) {
- EnumeratedTypeSet result= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- result.addAll(this); // copy first since retainAll() modifies in-place
- result.retainAll(s2);
- if (result.size() > 0)
- return result;
- else
- return getTypeSetEnvironment().getEmptyTypeSet();
- }
- return null;
- }
-
- /**
- * Modifies this EnumeratedTypeSet to represent the intersection of the receiver with s2.
- * @param s2
- */
- public void intersectWith(TypeSet s2) {
- if (isUniverse()) {
- if (s2.isUniverse())
- return;
- // More than an optimization: the universe never contains array types, so
- // if s2 has array types, the following will retain them, as it should.
- EnumeratedTypeSet ets2= (EnumeratedTypeSet) s2;
- fMembers= new LinkedHashSet();
- fMembers.addAll(ets2.fMembers);
- } else
- retainAll(s2);
- }
-
- /**
- * @return a new TypeSet representing the set of all sub-types of the
- * types in the receiver
- */
- public TypeSet subTypes() {
- if (isUniverse())
- return makeClone(); // subtypes(universe) = universe
-
- if (fMembers.contains(getJavaLangObject()))
- return getTypeSetEnvironment().getUniverseTypeSet();
-
- return getTypeSetEnvironment().createSubTypesSet(this);
- }
-
- public static EnumeratedTypeSet makeArrayTypesForElements(Iterator/*<TType>*/ elemTypes, TypeSetEnvironment typeSetEnvironment) {
- EnumeratedTypeSet result= new EnumeratedTypeSet(typeSetEnvironment);
-
- while (elemTypes.hasNext()) {
- TType t= (TType) elemTypes.next();
- result.add(TTypes.createArrayType(t, 1));
- }
-// result.initComplete();
- return result;
- }
-
- /**
- * @return a new TypeSet representing the set of all super-types of the
- * types in the receiver
- */
- public TypeSet superTypes() {
- if (isUniverse())
- return makeClone(); // The supertypes of the universe is the universe
-
- return getTypeSetEnvironment().createSuperTypesSet(this);
- }
-
- public TypeSet makeClone() {
- EnumeratedTypeSet result= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- result.fMembers.addAll(fMembers);
- result.initComplete();
- return result;
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#size()
- */
- public int size() {
- return fMembers.size();
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#clear()
- */
- public void clear() {
- if (isUniverse())
- fMembers= new LinkedHashSet();
- else
- fMembers.clear();
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#isEmpty()
- */
- public boolean isEmpty() {
- return fMembers.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#toArray()
- */
- public TType[] toArray() {
- return (TType[]) fMembers.toArray(new TType[fMembers.size()]);
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#add(java.lang.Object)
- */
- public boolean add(TType t) {
- // Doesn't make sense to do here what other methods do (copy-and-modify)
- Assert.isTrue(!isUniverse(), "Someone's trying to expand the universe!"); //$NON-NLS-1$
- return fMembers.add(t);
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#contains(java.lang.Object)
- */
- public boolean contains(TType t) {
- if (isUniverse())
- return true;
- return fMembers.contains(t);
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#remove(java.lang.Object)
- */
- public boolean remove(TType t) {
- if (isUniverse())
- fMembers= cloneSet(fMembers);
- return fMembers.remove(t);
- }
-
- private Set cloneSet(Set members) {
- Set result= new LinkedHashSet();
- result.addAll(members);
- return result;
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#addAll(java.util.Collection)
- */
- public boolean addAll(TypeSet s) {
- if (s instanceof EnumeratedTypeSet) {
- EnumeratedTypeSet ets= (EnumeratedTypeSet) s;
-
- return fMembers.addAll(ets.fMembers);
- } else {
- EnumeratedTypeSet ets= s.enumerate();
-
- return fMembers.addAll(ets.fMembers);
- }
- }
-
- public TypeSet addedTo(TypeSet that) {
- EnumeratedTypeSet result= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- result.addAll(this);
- result.addAll(that);
- result.initComplete();
- return result;
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#containsAll(java.util.Collection)
- */
- public boolean containsAll(TypeSet s) {
- if (isUniverse())
- return true;
- if (s.isUniverse())
- return false;
- EnumeratedTypeSet ets= s.enumerate();
-
- return fMembers.containsAll(ets.fMembers);
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#removeAll(java.util.Collection)
- */
- public boolean removeAll(EnumeratedTypeSet s) {
- if (isUniverse())
- fMembers= cloneSet(fMembers);
- return fMembers.removeAll(s.fMembers);
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#retainAll(java.util.Collection)
- */
- public boolean retainAll(TypeSet s) {
- if (s.isUniverse()) return false;
-
- EnumeratedTypeSet ets= (EnumeratedTypeSet) s;
-
- if (isUniverse()) {
- fMembers= cloneSet(ets.fMembers);
- return true;
- } else
- return fMembers.retainAll(ets.fMembers);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return fMembers.size() == 1;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return (TType) fMembers.iterator().next();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- if (fMembers.size() == 1)
- return new SingletonTypeSet((TType) fMembers.iterator().next(), getTypeSetEnvironment());
- if (fMembers.contains(getJavaLangObject()))
- return new SingletonTypeSet(getJavaLangObject(), getTypeSetEnvironment());
-
- EnumeratedTypeSet result= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- // Add to result each element of fMembers that has no proper supertype in fMembers
- result.fMembers.addAll(fMembers);
- for(Iterator iter= fMembers.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
-
- if (t.isArrayType()) {
- ArrayType at= (ArrayType) t;
- int numDims= at.getDimensions();
- for(Iterator subIter=TTypes.getAllSubTypesIterator(at.getElementType()); subIter.hasNext(); ) {
- result.fMembers.remove(TTypes.createArrayType(((TType) subIter.next()), numDims));
- }
- } else {
- for (Iterator iterator= TTypes.getAllSubTypesIterator(t); iterator.hasNext();) {
- result.fMembers.remove(iterator.next());
- }
- }
- }
- result.initComplete();
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- if (fMembers.size() == 1)
- return new SingletonTypeSet((TType) fMembers.iterator().next(), getTypeSetEnvironment());
-
- EnumeratedTypeSet result= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- // Add to result each element of fMembers that has no proper subtype in fMembers
- result.fMembers.addAll(fMembers);
-
- for(Iterator iter= fMembers.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
-
- // java.lang.Object is only in the lower bound if fMembers consists
- // of only java.lang.Object, but that case is handled above.
- if (t.equals(getJavaLangObject())) {
- result.fMembers.remove(t);
- continue;
- }
-
- if (t instanceof ArrayType) {
- ArrayType at= (ArrayType) t;
- int numDims= at.getDimensions();
- for(Iterator superIter=TTypes.getAllSuperTypesIterator(at.getElementType()); superIter.hasNext(); ) {
- result.fMembers.remove(TTypes.createArrayType(((TType) superIter.next()), numDims));
- }
- } else {
- for (Iterator iterator= TTypes.getAllSuperTypesIterator(t); iterator.hasNext();) {
- result.fMembers.remove(iterator.next());
- }
- }
- }
- if (result.size() > 0)
- return result;
- else
- return getTypeSetEnvironment().getEmptyTypeSet();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return fMembers.size() == 1;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return fMembers.size() == 1;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- if (fMembers.size() == 1)
- return (TType) fMembers.iterator().next();
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- if (fMembers.size() == 1)
- return (TType) fMembers.iterator().next();
- return null;
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#iterator()
- */
- public Iterator iterator() {
- return fMembers.iterator();
- }
-
- /* (non-Javadoc)
- * @see java.util.Set#toArray(java.lang.Object[])
- */
- public TType[] toArray(TType[] a) {
- return (TType[]) fMembers.toArray(a);
- }
-
- /**
- * Limits the display of set elements to the first sMaxElements.
- */
- private static final int sMaxElements= 10; // Integer.MAX_VALUE;
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer b= new StringBuffer();
- b.append("{" + fID+ ":"); //$NON-NLS-1$ //$NON-NLS-2$
- if (isUniverse())
- b.append(" <universe>"); //$NON-NLS-1$
- else {
- int count=0;
- Iterator iter;
- for(iter= iterator(); iter.hasNext() && count < sMaxElements; count++) {
- TType type= (TType) iter.next();
- b.append(' ')
- .append(type.getPrettySignature());
- if (iter.hasNext())
- b.append(',');
- }
- if (iter.hasNext())
- b.append(" ..."); //$NON-NLS-1$
- }
- b.append(" }"); //$NON-NLS-1$
- return b.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- return this; // (EnumeratedTypeSet) makeClone();
- }
-
- public void initComplete() {
- Assert.isTrue(! fMembers.isEmpty());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SingletonTypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SingletonTypeSet.java
deleted file mode 100644
index e9509f6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SingletonTypeSet.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public class SingletonTypeSet extends TypeSet {
- private final TType fType;
-
-
- //TODO: encapsulate in factory method and return the same set for known types
- public SingletonTypeSet(TType t, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- Assert.isNotNull(t);
- fType= t;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; //new SingletonTypeSet(fType, getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (s2.contains(fType))
- return this;
- else
- return getTypeSetEnvironment().getEmptyTypeSet();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return fType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return fType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- return fType.equals(t);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- if (s.isEmpty())
- return true;
- if (s.isSingleton())
- return s.anyMember().equals(fType);
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return new Iterator() {
- private boolean done= false;
- public void remove() {
- throw new UnsupportedOperationException();
- }
- public boolean hasNext() {
- return !done;
- }
- public Object next() {
- done= true;
- return fType;
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- EnumeratedTypeSet enumeratedTypeSet= new EnumeratedTypeSet(fType, getTypeSetEnvironment());
- enumeratedTypeSet.initComplete();
- return enumeratedTypeSet;
- }
-
- public boolean equals(Object o) {
- if (o instanceof SingletonTypeSet) {
- SingletonTypeSet other= (SingletonTypeSet) o;
-
- return fType.equals(other.fType);
- } else if (o instanceof TypeSet) {
- TypeSet other= (TypeSet) o;
-
- return other.isSingleton() && other.anyMember().equals(fType);
- } else
- return false;
- }
-
- public String toString() {
- return "{" + fID + ": " + fType.getPrettySignature() + "}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesOfSingleton.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesOfSingleton.java
deleted file mode 100644
index 55842501..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesOfSingleton.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-public class SubTypesOfSingleton extends TypeSet {
- /**
- * The "base type" defining the upper bound of this set.
- */
- private final TType fUpperBound;
-
- protected SubTypesOfSingleton(TType t, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- Assert.isNotNull(t);
- fUpperBound= t;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return fUpperBound.equals(getJavaLangObject());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; // new SubTypesOfSingleton(fUpperBound);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#subTypes()
- */
- public TypeSet subTypes() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public TypeSet specialCasesIntersectedWith(TypeSet other) {
- if (other.isSingleton() && other.anyMember().equals(fUpperBound))
- return other; // xsect(subTypes(A),A) = A
-
- if (other instanceof SubTypesOfSingleton) {
- SubTypesOfSingleton otherSub= (SubTypesOfSingleton) other;
-
- if (TTypes.canAssignTo(otherSub.fUpperBound, fUpperBound))
- return otherSub; // .makeClone();
- if (TTypes.canAssignTo(fUpperBound, otherSub.fUpperBound))
- return this; // makeClone();
- } else if (other.hasUniqueLowerBound()) {
- TType otherLower= other.uniqueLowerBound();
-
- if (otherLower.equals(fUpperBound))
- return new SingletonTypeSet(fUpperBound, getTypeSetEnvironment());
- if (otherLower != fUpperBound && TTypes.canAssignTo(fUpperBound, otherLower) ||
- ! TTypes.canAssignTo(otherLower, fUpperBound))
- return getTypeSetEnvironment().getEmptyTypeSet();
- }
-// else if (other instanceof SubTypesSet) {
-// SubTypesSet otherSub= (SubTypesSet) other;
-// TypeSet otherUppers= otherSub.upperBound();
-//
-// for(Iterator iter= otherUppers.iterator(); iter.hasNext(); ) {
-// TType t= (TType) iter.next();
-//
-// if ()
-// }
-// }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return new SingletonTypeSet(fUpperBound, getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- EnumeratedTypeSet e= enumerate();
- return e.lowerBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
-// TypeSet lowerBound= lowerBound();
-
-// return lowerBound.isSingleton();
- return false; // fast, though perhaps inaccurate, but that's ok
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- TypeSet lowerBound= lowerBound();
-
- return lowerBound.anyMember();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return fUpperBound;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(org.eclipse.wst.jsdt.core.TType)
- */
- public boolean contains(TType t) {
- if (t.equals(fUpperBound))
- return true;
- return TTypes.canAssignTo(t, fUpperBound);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet other) {
- if (isUniverse())
- return true;
-
- // Optimization: if other is also a SubTypeOfSingleton, just compare bounds
- if (other instanceof SubTypesOfSingleton) {
- SubTypesOfSingleton otherSub= (SubTypesOfSingleton) other;
- return TTypes.canAssignTo(otherSub.fUpperBound, fUpperBound);
- }
- // Optimization: if other is a SubTypesSet, just compare each of its bounds to mine
- if (other instanceof SubTypesSet) {
- SubTypesSet otherSub= (SubTypesSet) other;
- TypeSet otherUpperBounds= otherSub.upperBound();
-
- for(Iterator iter= otherUpperBounds.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
- if (! TTypes.canAssignTo(t, fUpperBound))
- return false;
- }
- return true;
- }
- // For now, no more tricks up my sleeve; get an iterator
- for(Iterator iter= other.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
-
- if (! TTypes.canAssignTo(t, fUpperBound))
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
-// return new Iterator() {
-// // First type returned is fUpperBound, then each of the subtypes, in turn
-// //
-// // If the upper bound is an array type, return the set of array types
-// // { Array(subType(elementTypeOf(fUpperBound))) }
-// private Set/*<TType>*/ subTypes= sTypeHierarchy.getAllSubtypes(getElementTypeOf(fUpperBound));
-// private Iterator/*<TType>*/ subTypeIter= subTypes.iterator();
-// private int nDims= getDimsOf(fUpperBound);
-// private int idx=-1;
-// public void remove() { /*do nothing*/}
-// public boolean hasNext() { return idx < subTypes.size(); }
-// public Object next() {
-// int i=idx++;
-// if (i < 0) return fUpperBound;
-// return makePossiblyArrayTypeFor((TType) subTypeIter.next(), nDims);
-// }
-// };
- }
-
- /**
- * Returns the element type of the given TType, if an array type, or the
- * given TType itself, otherwise.
- */
- private TType getElementTypeOf(TType t) {
- if (t instanceof ArrayType)
- return ((ArrayType) t).getElementType();
- return t;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return getElementTypeOf(fUpperBound).getSubTypes().length == 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fUpperBound;
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- if (fUpperBound instanceof ArrayType) {
- ArrayType at= (ArrayType) fUpperBound;
- fEnumCache= EnumeratedTypeSet.makeArrayTypesForElements(TTypes.getAllSubTypesIterator(at.getComponentType()),getTypeSetEnvironment());
- } else
- fEnumCache= new EnumeratedTypeSet(TTypes.getAllSubTypesIterator(fUpperBound), getTypeSetEnvironment());
-
- fEnumCache.add(fUpperBound);
- fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof SubTypesOfSingleton))
- return false;
- SubTypesOfSingleton other= (SubTypesOfSingleton) o;
-
- return other.fUpperBound.equals(fUpperBound);
- }
-
- public String toString() {
- return "<" + fID + ": subTypes(" + fUpperBound.getPrettySignature() + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesSet.java
deleted file mode 100644
index 65806632..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SubTypesSet.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-public class SubTypesSet extends TypeSet {
- /**
- * The set of "base types" defining the upper bounds of this set.
- */
- private TypeSet fUpperBounds;
-
- SubTypesSet(TypeSet superTypes) {
- super(superTypes.getTypeSetEnvironment());
- fUpperBounds= superTypes;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return fUpperBounds.isUniverse() || fUpperBounds.contains(getJavaLangObject());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; //new SubTypesSet(fUpperBounds.makeClone());
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- if (o instanceof SubTypesSet) {
- SubTypesSet other= (SubTypesSet) o;
- return other.fUpperBounds.equals(fUpperBounds);
-// } else if (o instanceof TypeSet) {
-// TypeSet other= (TypeSet) o;
-// if (other.isUniverse() && isUniverse())
-// return true;
-// return enumerate().equals(other.enumerate());
- } else
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.EnumeratedTypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (fUpperBounds.equals(s2))
- return s2; // xsect(subTypes(A),A) = A
- if (s2 instanceof SubTypesSet) {
- SubTypesSet st2= (SubTypesSet) s2;
-
- if (fUpperBounds.isSingleton() && st2.fUpperBounds.isSingleton()) {
- TType t1= this.fUpperBounds.anyMember();
- TType t2= st2.fUpperBounds.anyMember();
-
- if (TTypes.canAssignTo(t2, t1))
- return new SubTypesSet(st2.fUpperBounds);
- } else if (fUpperBounds instanceof SubTypesSet) {
- // xsect(subTypes(superTypes(A)), subTypes(A)) = subTypes(A)
- SubTypesSet myUpperSubTypes= (SubTypesSet) fUpperBounds;
-
- if (myUpperSubTypes.lowerBound().equals(st2.lowerBound()))
- return st2;
- }
- }
- if (s2 instanceof SubTypesOfSingleton) {
- SubTypesOfSingleton st2= (SubTypesOfSingleton) s2;
-
- if (fUpperBounds.isSingleton()) {
- TType t1= this.fUpperBounds.anyMember();
- TType t2= st2.uniqueUpperBound();
-
- if (TTypes.canAssignTo(t2, t1))
- return getTypeSetEnvironment().createSubTypesOfSingleton(t2);
- } else if (fUpperBounds instanceof SubTypesOfSingleton) {
- // xsect(subTypes(superTypes(A)), subTypes(A)) = subTypes(A)
- SubTypesOfSingleton myUpperSubTypes= (SubTypesOfSingleton) fUpperBounds;
-
- if (myUpperSubTypes.uniqueLowerBound().equals(st2.uniqueLowerBound()))
- return st2;
- }
- }
-
- if (s2 instanceof SuperTypesSet) {
- SuperTypesSet st2= (SuperTypesSet) s2;
-
- if (fUpperBounds.equals(st2.lowerBound()))
- return fUpperBounds;
-
- if (fUpperBounds instanceof TypeSetIntersection) {
- // (intersect (subTypes (intersect (superTypes A) B))
- // (superTypes A)) =>
- // (intersect (superTypes A) (subTypes B))
- TypeSetIntersection lbXSect= (TypeSetIntersection) fUpperBounds;
- TypeSet xsectLeft= lbXSect.getLHS();
- TypeSet xsectRight= lbXSect.getRHS();
-
- if (xsectLeft.equals(st2.lowerBound()))
- return new TypeSetIntersection(s2, new SubTypesSet(xsectRight));
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#subTypes()
- */
- public TypeSet subTypes() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return fUpperBounds.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- if (fEnumCache != null) return fEnumCache.contains(t);
-
- if (fUpperBounds.contains(t))
- return true;
-
- // Find the "upper frontier", i.e. the upper bound, and see whether
- // the given type is a subtype of any of those.
- Iterator ubIter= fUpperBounds.upperBound().iterator();
-
- for(; ubIter.hasNext(); ) {
- TType ub= (TType) ubIter.next();
-
- if (TTypes.canAssignTo(t, ub))
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.EnumeratedTypeSet)
- */
- public boolean containsAll(TypeSet s) {
- if (fEnumCache != null) return fEnumCache.containsAll(s);
-
- if (fUpperBounds.containsAll(s))
- return true;
-
- // Make sure all elements of s are contained in this set
- for(Iterator sIter= s.iterator(); sIter.hasNext(); ) {
- TType t= (TType) sIter.next();
- boolean found= false;
-
- // Scan the "upper frontier", i.e. the upper bound set, and see whether
- // 't' is a subtype of any of those.
- for(Iterator ubIter= fUpperBounds /*.upperBound() */.iterator(); ubIter.hasNext(); ) {
- TType ub= (TType) ubIter.next();
-
- if (TTypes.canAssignTo(t, ub)) {
- found= true;
- break;
- }
- }
- if (!found) return false;
- }
- return true;
- }
-
- /**
- * Returns the element type of the given TType, if an array type, or the
- * given TType itself, otherwise.
- */
- private TType getElementTypeOf(TType t) {
- if (t instanceof ArrayType)
- return ((ArrayType) t).getElementType();
- return t;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- if (!fUpperBounds.isSingleton())
- return false;
-
- TType t= fUpperBounds.anyMember();
-
- return getElementTypeOf(t).getSubTypes().length == 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fUpperBounds.anyMember();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return fUpperBounds; // perhaps should be unmodifiable?
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- return enumerate().lowerBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "<" + fID + ": subTypes(" + fUpperBounds + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return fUpperBounds.isSingleton();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return fUpperBounds.isSingleton() ? fUpperBounds.anyMember() : null;
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- fEnumCache= new EnumeratedTypeSet(getTypeSetEnvironment());
-
- for(Iterator iter= fUpperBounds.iterator(); iter.hasNext(); ) {
- TType ub= (TType) iter.next();
-
- if (ub instanceof ArrayType) {
- ArrayType at= (ArrayType) ub;
- int numDims= at.getDimensions();
- for(Iterator elemSubIter=TTypes.getAllSubTypesIterator(at.getElementType()); elemSubIter.hasNext(); )
- fEnumCache.add(TTypes.createArrayType((TType) elemSubIter.next(), numDims));
- } else {
- for (Iterator iterator= TTypes.getAllSubTypesIterator(ub); iterator.hasNext();) {
- fEnumCache.fMembers.add(iterator.next());
- }
- }
- fEnumCache.add(ub);
- }
-// fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesOfSingleton.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesOfSingleton.java
deleted file mode 100644
index 15e982b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesOfSingleton.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-public class SuperTypesOfSingleton extends TypeSet {
- /**
- * The "base type" defining the lower bound of this set.
- */
- private TType fLowerBound;
-
- SuperTypesOfSingleton(TType t, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- fLowerBound= t;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; //new SuperTypesOfSingleton(fLowerBound, getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet other) {
- if (other.isSingleton() && other.anyMember().equals(fLowerBound))
- return other; // xsect(superTypes(A),A) = A
-
- if (other instanceof SuperTypesOfSingleton) {
- SuperTypesOfSingleton otherSuper= (SuperTypesOfSingleton) other;
-
- if (TTypes.canAssignTo(otherSuper.fLowerBound, fLowerBound))
- return this;
- if (TTypes.canAssignTo(fLowerBound, otherSuper.fLowerBound))
- return otherSuper;
- } else if (other.hasUniqueUpperBound()) {
- TType otherUpper= other.uniqueUpperBound();
-
- if (otherUpper.equals(fLowerBound))
- return new SingletonTypeSet(fLowerBound, getTypeSetEnvironment());
- if ((otherUpper != fLowerBound && TTypes.canAssignTo(otherUpper, fLowerBound)) ||
- ! TTypes.canAssignTo(fLowerBound, otherUpper))
- return getTypeSetEnvironment().getEmptyTypeSet();
- }
-// else if (other instanceof SuperTypesSet) {
-// SuperTypesSet otherSub= (SuperTypesSet) other;
-// TypeSet otherLowers= otherSub.lowerBound();
-//
-// for(Iterator iter= otherLowers.iterator(); iter.hasNext(); ) {
-// TType t= (TType) iter.next();
-//
-// if ()
-// }
-// }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return new SingletonTypeSet(getJavaLangObject(), getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- return new SingletonTypeSet(fLowerBound, getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return fLowerBound;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return getJavaLangObject();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#superTypes()
- */
- public TypeSet superTypes() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- if (t.equals(fLowerBound))
- return true;
- if (t.equals(getJavaLangObject()))
- return true;
- return TTypes.canAssignTo(fLowerBound, t);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet other) {
- // Optimization: if other is also a SubTypeOfSingleton, just compare bounds
- if (other instanceof SuperTypesOfSingleton) {
- SuperTypesOfSingleton otherSuper= (SuperTypesOfSingleton) other;
- return TTypes.canAssignTo(fLowerBound, otherSuper.fLowerBound);
- }
- // Optimization: if other is a SubTypesSet, just compare all its bounds to mine
- if (other instanceof SuperTypesSet) {
- SuperTypesSet otherSuper= (SuperTypesSet) other;
- TypeSet otherLowerBounds= otherSuper.lowerBound();
-
- for(Iterator iter= otherLowerBounds.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
- if (! TTypes.canAssignTo(fLowerBound, t))
- return false;
- }
- return true;
- }
- if (other.isUniverse()) {
- return false;
- }
- // For now, no more tricks up my sleeve; get an iterator
- for(Iterator iter= other.iterator(); iter.hasNext(); ) {
- TType t= (TType) iter.next();
-
- if (! TTypes.canAssignTo(fLowerBound, t))
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
-// return new Iterator() {
-// // First type returned is fLowerBound, then each of the supertypes, in turn
-// //
-// // If the lower bound is an array type, return the set of array types
-// // { Array(superType(elementTypeOf(fUpperBound))) }
-// boolean isArray= (fLowerBound instanceof ArrayType);
-// private Set/*<TType>*/ superTypes= sTypeHierarchy.getAllSupertypes(getElementTypeOf(fLowerBound));
-// private Iterator/*<TType>*/ superTypeIter= superTypes.iterator();
-// private int nDims= getDimsOf(fLowerBound);
-// private int idx= (isArray ? -2 : -1);
-// public void remove() { /*do nothing*/ }
-// public boolean hasNext() { return idx < superTypes.size(); }
-// public Object next() {
-// int i=idx++;
-// if (i < -1) return sJavaLangObject;
-// if (i < 0) return fLowerBound;
-// return makePossiblyArrayTypeFor((TType) superTypeIter.next(), nDims);
-// }
-// };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- // The only thing that doesn't have at least 1 proper supertype is java.lang.Object
- return fLowerBound.equals(getJavaLangObject());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fLowerBound;
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- if (fLowerBound instanceof ArrayType) {
- ArrayType at= (ArrayType) fLowerBound;
- fEnumCache= EnumeratedTypeSet.makeArrayTypesForElements(TTypes.getAllSuperTypesIterator(at.getComponentType()), getTypeSetEnvironment());
- fEnumCache.add(getJavaLangObject());
- } else
- fEnumCache= new EnumeratedTypeSet(TTypes.getAllSuperTypesIterator(fLowerBound), getTypeSetEnvironment());
-
- fEnumCache.add(fLowerBound);
- fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof SuperTypesOfSingleton))
- return false;
- SuperTypesOfSingleton other= (SuperTypesOfSingleton) o;
-
- return other.fLowerBound.equals(fLowerBound);
- }
-
- public String toString() {
- return "<" + fID + ": superTypes(" + fLowerBound.getPrettySignature() + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesSet.java
deleted file mode 100644
index c0bbe1c5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/SuperTypesSet.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-public class SuperTypesSet extends TypeSet {
- private TypeSet fLowerBounds;
-
- SuperTypesSet(TType subType, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- fLowerBounds= new SingletonTypeSet(subType, typeSetEnvironment);
- }
-
- SuperTypesSet(TypeSet subTypes, TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment);
- fLowerBounds= subTypes;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return fLowerBounds.isUniverse();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; //new SuperTypesSet(fLowerBounds.makeClone(), getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- return new SingletonTypeSet(getTypeSetEnvironment().getJavaLangObject(), getTypeSetEnvironment());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- // Ask the operand for its lower-bound, in case it's something like an
- // EnumeratedTypeSet, which may have things in it other than the lower
- // bound...
- return fLowerBounds.lowerBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#intersectedWith(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.EnumeratedTypeSet)
- */
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (fLowerBounds.equals(s2))
- return s2; // xsect(superTypes(A),A) = A
- if (s2 instanceof SuperTypesSet) {
- SuperTypesSet st2= (SuperTypesSet) s2;
-
- if (fLowerBounds.isSingleton() && st2.fLowerBounds.isSingleton()) {
- TType t1= this.fLowerBounds.anyMember();
- TType t2= st2.fLowerBounds.anyMember();
-
- if (TTypes.canAssignTo(t1, t2))
- return new SuperTypesSet(st2.fLowerBounds, getTypeSetEnvironment());
- } else if (fLowerBounds instanceof SubTypesSet) {
- // xsect(superTypes(subTypes(A)), superTypes(A)) = superTypes(A)
- SubTypesSet myLowerSubTypes= (SubTypesSet) fLowerBounds;
-
- if (myLowerSubTypes.upperBound().equals(st2.upperBound()))
- return st2;
- }
- }
- if (s2 instanceof SuperTypesOfSingleton) {
- SuperTypesOfSingleton st2= (SuperTypesOfSingleton) s2;
-
- if (fLowerBounds.isSingleton()) {
- TType t1= this.fLowerBounds.anyMember();
- TType t2= st2.uniqueLowerBound();
-
- if (TTypes.canAssignTo(t1, t2))
- return getTypeSetEnvironment().createSuperTypesOfSingleton(t2);
- } else if (fLowerBounds instanceof SubTypesOfSingleton) {
- // xsect(superTypes(subTypes(A)), superTypes(A)) = superTypes(A)
- SubTypesOfSingleton myLowerSubTypes= (SubTypesOfSingleton) fLowerBounds;
-
- if (myLowerSubTypes.uniqueUpperBound().equals(st2.uniqueUpperBound()))
- return st2;
- }
- }
- if (s2 instanceof SubTypesSet) {
- SubTypesSet st2= (SubTypesSet) s2;
- if (fLowerBounds.equals(st2.upperBound()))
- return fLowerBounds;
-
- if (fLowerBounds instanceof TypeSetIntersection) {
- // (intersect (superTypes (intersect (subTypes A) B))
- // (subTypes A)) =>
- // (intersect (subTypes A) (superTypes B))
- TypeSetIntersection lbXSect= (TypeSetIntersection) fLowerBounds;
- TypeSet xsectLeft= lbXSect.getLHS();
- TypeSet xsectRight= lbXSect.getRHS();
-
- if (xsectLeft.equals(st2.upperBound()))
- return new TypeSetIntersection(s2, new SuperTypesSet(xsectRight, getTypeSetEnvironment()));
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#superTypes()
- */
- public TypeSet superTypes() {
- return this; // makeClone();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return fLowerBounds.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- if (fEnumCache != null) return fEnumCache.contains(t);
-
- if (t.equals(getJavaLangObject()))
- return true;
- if (fLowerBounds.contains(t))
- return true;
-
- // Find the "lower frontier", i.e. the lower bound, and see whether
- // the given type is a supertype of any of those.
- for(Iterator lbIter= fLowerBounds /*.lowerBound() */.iterator(); lbIter.hasNext(); ) {
- TType lb= (TType) lbIter.next();
-
- if (TTypes.canAssignTo(lb, t))
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.EnumeratedTypeSet)
- */
- public boolean containsAll(TypeSet s) {
- if (fEnumCache != null) return fEnumCache.containsAll(s);
-
- if (!isUniverse() && s.isUniverse()) // this is more general than just SuperTypesSet; probably belongs in TypeSet
- return false;
- if (equals(s))
- return true;
- if (fLowerBounds.containsAll(s))
- return true;
-
- // Make sure all elements of s are contained in this set
- for(Iterator sIter= s.iterator(); sIter.hasNext(); ) {
- TType t= (TType) sIter.next();
- boolean found= false;
-
- // Scan the "lower frontier", i.e. the lower bound set, and see whether
- // 't' is a supertype of any of those.
- for(Iterator lbIter= fLowerBounds /*.lowerBound()*/.iterator(); lbIter.hasNext(); ) {
- TType lb= (TType) lbIter.next();
-
- if (TTypes.canAssignTo(lb, t)) {
- found= true;
- break;
- }
- }
- if (!found) return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- if (fEnumCache != null) return fEnumCache.isSingleton();
-
- return fLowerBounds.isSingleton() && (fLowerBounds.anyMember() == getJavaLangObject());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fLowerBounds.anyMember();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- if (o instanceof SuperTypesSet) {
- SuperTypesSet other= (SuperTypesSet) o;
- return other.fLowerBounds.equals(fLowerBounds);
-// } else if (o instanceof TypeSet) {
-// TypeSet other= (TypeSet) o;
-// if (other.isUniverse() && isUniverse())
-// return true;
-// return enumerate().equals(other.enumerate());
- } else
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
- }
-
- public String toString() {
- return "<" + fID + ": superTypes(" + fLowerBounds + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return fLowerBounds.isSingleton();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return fLowerBounds.isSingleton() ? fLowerBounds.anyMember() : null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return null;
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- fEnumCache= new EnumeratedTypeSet(getTypeSetEnvironment());
- boolean anyLBIsIntfOrArray= false;
-
- for(Iterator iter= fLowerBounds.iterator(); iter.hasNext(); ) {
- TType lb= (TType) iter.next();
-
- if (lb instanceof ArrayType) {
- ArrayType at= (ArrayType) lb;
- int numDims= at.getDimensions();
- for(Iterator elemSuperIter=TTypes.getAllSuperTypesIterator(at.getElementType()); elemSuperIter.hasNext(); )
- fEnumCache.add(TTypes.createArrayType((TType) elemSuperIter.next(), numDims));
- anyLBIsIntfOrArray= true;
- } else {
- for (Iterator iterator= TTypes.getAllSuperTypesIterator(lb); iterator.hasNext(); )
- fEnumCache.fMembers.add(iterator.next());
- }
- fEnumCache.add(lb);
- }
- if (anyLBIsIntfOrArray) fEnumCache.add(getJavaLangObject());
- //fEnumCache.initComplete();
- }
- return fEnumCache;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSet.java
deleted file mode 100644
index 7d9ece8b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSet.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.ITypeSet;
-
-public abstract class TypeSet implements ITypeSet {
-
- public TType chooseSingleType() {
- return null;
- }
-
- public ITypeSet restrictedTo(ITypeSet restrictionSet) {
- throw new UnsupportedOperationException();
- }
-
- protected TType getJavaLangObject() {
- return fTypeSetEnvironment.getJavaLangObject();
- }
-
- protected TypeSetEnvironment getTypeSetEnvironment() {
- return fTypeSetEnvironment;
- }
-
- static private int sID= 0;
-
- static public int getCount() { return sID; }
- static public void resetCount() { sID= 0; }
-
- /**
- * An ID unique to this EnumeratedTypeSet instance, to aid in debugging the sharing
- * of TypeSets across ConstraintVariables in a TypeEstimateEnvironment.
- */
- protected final int fID;
- private final TypeSetEnvironment fTypeSetEnvironment;
-
- protected TypeSet(TypeSetEnvironment typeSetEnvironment) {
- fTypeSetEnvironment= typeSetEnvironment;
- fID= sID++;
- }
-
- /**
- * @return <code>true</code> iff this set represents the universe of TTypes
- */
- abstract public boolean isUniverse();
-
- abstract public TypeSet makeClone();
-
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- return null;
- }
-
- /**
- * Computes and returns a <em>new</em> TypeSet representing the intersection of the
- * receiver with s2. Does not modify the receiver or argument sets.
- * @param s2
- * @return the new TypeSet
- */
- public TypeSet intersectedWith(TypeSet s2) {
- if (s2.isUniverse())
- return makeClone();
- else if (isUniverse())
- return s2.makeClone();
- else if (isEmpty() || s2.isEmpty())
- return getTypeSetEnvironment().getEmptyTypeSet();
- else if (isSingleton()) {
- if (s2.contains(anyMember()))
- return makeClone();
- else
- return getTypeSetEnvironment().getEmptyTypeSet();
- } else if (s2.isSingleton()) {
- if (contains(s2.anyMember()))
- return s2.makeClone();
- else
- return getTypeSetEnvironment().getEmptyTypeSet();
- } else if (s2 instanceof TypeSetIntersection) {
- TypeSetIntersection x= (TypeSetIntersection) s2;
- // xsect(A,xsect(A,B)) = xsect(A,B) and
- // xsect(B,xsect(A,B)) = xsect(A,B)
- if (x.getLHS().equals(this) || x.getRHS().equals(this))
- return x;
- }
-
- TypeSet result= specialCasesIntersectedWith(s2);
-
- if (result != null)
- return result;
- else
- return new TypeSetIntersection(this, s2);
- }
-
- /**
- * Returns the TypeSet resulting from union'ing the receiver with the argument.
- * Does not modify the receiver or the argument sets.
- */
- public TypeSet addedTo(TypeSet that) {
- if (isUniverse() || that.isUniverse())
- return getTypeSetEnvironment().getUniverseTypeSet();
- if ((this instanceof EnumeratedTypeSet || this instanceof SingletonTypeSet) &&
- (that instanceof EnumeratedTypeSet || that instanceof SingletonTypeSet)) {
- EnumeratedTypeSet result= enumerate();
-
- result.addAll(that);
- return result;
- }
- return new TypeSetUnion(this, that);
- }
-
- /**
- * Returns a new TypeSet representing the set of all sub-types of the
- * types in the receiver.
- */
- public TypeSet subTypes() {
- if (isUniverse() || contains(getJavaLangObject()))
- return getTypeSetEnvironment().getUniverseTypeSet();
-
- if (isSingleton())
- return possiblyArraySubTypeSetFor(anyMember());
-
- return getTypeSetEnvironment().createSubTypesSet(this);
- }
-
- private TypeSet possiblyArraySubTypeSetFor(TType t) {
- // In Java, subTypes(x[]) == (subTypes(x))[]
-// if (t.isArrayType()) {
-// ArrayType at= (ArrayType) t;
-//
-// return new ArrayTypeSet(possiblyArraySubTypeSetFor(at.getArrayElementType()));
-// } else
-
- return getTypeSetEnvironment().createSubTypesOfSingleton(t);
- }
-
- private TypeSet possiblyArraySuperTypeSetFor(TType t) {
- // In Java, superTypes(x[]) == (superTypes(x))[] union {Object}
-// if (t.isArrayType()) {
-// ArrayType at= (ArrayType) t;
-//
-// return new ArraySuperTypeSet(possiblyArraySuperTypeSetFor(at.getArrayElementType()));
-// } else
- return getTypeSetEnvironment().createSuperTypesOfSingleton(t);
- }
-
- /**
- * Returns a new TypeSet representing the set of all super-types of the
- * types in the receiver.
- */
- public TypeSet superTypes() {
- if (isUniverse())
- return getTypeSetEnvironment().getUniverseTypeSet();
-
- if (isSingleton())
- return possiblyArraySuperTypeSetFor(anyMember());
-
- return getTypeSetEnvironment().createSuperTypesSet(this);
- }
-
- /**
- * Return true iff the type set contains no types.
- */
- abstract public boolean isEmpty();
-
- /**
- * Returns the types in the upper bound of this set.
- */
- abstract public TypeSet upperBound();
-
- /**
- * Returns the types in the lower bound of this set.
- */
- abstract public TypeSet lowerBound();
-
- /**
- * Returns true iff this TypeSet has a unique lower bound.
- */
- abstract public boolean hasUniqueLowerBound();
-
- /**
- * Returns true iff this TypeSet has a unique upper bound other than
- * java.lang.Object.
- */
- abstract public boolean hasUniqueUpperBound();
-
- /**
- * Returns the unique lower bound of this set of types, if it has one,
- * or null otherwise.
- */
- abstract public TType uniqueLowerBound();
-
- /**
- * Returns the unique upper bound of this set of types, if it has one,
- * or null otherwise.
- */
- abstract public TType uniqueUpperBound();
-
- /**
- * Returns true iff the type set contains the given type.
- */
- abstract public boolean contains(TType t);
-
- /**
- * Returns true iff the type set contains all of the types in the given TypeSet.
- */
- abstract public boolean containsAll(TypeSet s);
-
- /**
- * Returns an iterator over the types in the receiver.
- */
- abstract public Iterator iterator();
-
- /**
- * Returns a new TypeSet enumerating the receiver's contents.
- */
- abstract public EnumeratedTypeSet enumerate();
-
- /**
- * Returns true iff the given set has precisely one element
- */
- abstract public boolean isSingleton();
-
- /**
- * Returns an arbitrary member of the given Typeset.
- */
- abstract public TType anyMember();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetEnvironment.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetEnvironment.java
deleted file mode 100644
index 99cbf202..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetEnvironment.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment;
-
-
-
-public class TypeSetEnvironment {
-
- private final TypeEnvironment fTypeEnvironment;
- private final TypeUniverseSet fUniverse;
- private final EmptyTypeSet fEmptyTypeSet;
-
- private final Map/*<TType, SubTypesOfSingleton>*/ fSubtypesOfSingletons= new LinkedHashMap();//@perf
- private final Map/*<TType, SubTypesSet>*/ fSubTypesSets= new LinkedHashMap();//@perf
- private final Map/*<TType, SuperTypesOfSingleton>*/ fSuperTypesOfSingletons= new LinkedHashMap();//@perf
- private final Map/*<TType, SuperTypesSet>*/ fSuperTypesSets= new LinkedHashMap();//@perf
-
- private int fgCommonExprHits= 0;
- private int fgCommonExprMisses= 0;
-
- public TypeSetEnvironment(TypeEnvironment typeEnvironment) {
- fTypeEnvironment= typeEnvironment;
- fUniverse= new TypeUniverseSet(this);
- fEmptyTypeSet= new EmptyTypeSet(this);
- }
-
- public TType getJavaLangObject() {
- return fTypeEnvironment.getJavaLangObject();
- }
-
- public TypeUniverseSet getUniverseTypeSet() {
- return fUniverse;
- }
-
- public EmptyTypeSet getEmptyTypeSet() {
- return fEmptyTypeSet;
- }
-
- public SubTypesOfSingleton createSubTypesOfSingleton(TType superType) {
- if (superType.isJavaLangObject())
- return this.getUniverseTypeSet();
- if (fSubtypesOfSingletons.containsKey(superType)) {
- fgCommonExprHits++;
- return (SubTypesOfSingleton) fSubtypesOfSingletons.get(superType);
- } else {
- SubTypesOfSingleton s= new SubTypesOfSingleton(superType, this);
-
- fgCommonExprMisses++;
- fSubtypesOfSingletons.put(superType, s);
- return s;
- }
- }
-
- public SubTypesSet createSubTypesSet(TypeSet superTypes) {
- if (fSubTypesSets.containsKey(superTypes)) {
- fgCommonExprHits++;
- return (SubTypesSet) fSubTypesSets.get(superTypes);
- } else {
- SubTypesSet s= new SubTypesSet(superTypes);
-
- fgCommonExprMisses++;
- fSubTypesSets.put(superTypes, s);
- return s;
- }
- }
-
- public SuperTypesOfSingleton createSuperTypesOfSingleton(TType subType) {
- if (fSuperTypesOfSingletons.containsKey(subType)) {
- fgCommonExprHits++;
- return (SuperTypesOfSingleton) fSuperTypesOfSingletons.get(subType);
- } else {
- SuperTypesOfSingleton s= new SuperTypesOfSingleton(subType, this);
-
- fgCommonExprMisses++;
- fSuperTypesOfSingletons.put(subType, s);
- return s;
- }
- }
-
- public SuperTypesSet createSuperTypesSet(TType subType) {
- if (fSuperTypesSets.containsKey(subType)) {
- fgCommonExprHits++;
- return (SuperTypesSet) fSuperTypesSets.get(subType);
- } else {
- SuperTypesSet s= new SuperTypesSet(subType, this);
-
- fgCommonExprMisses++;
- fSuperTypesSets.put(subType, s);
- return s;
- }
- }
-
- public SuperTypesSet createSuperTypesSet(TypeSet subTypes) {
- if (fSuperTypesSets.containsKey(subTypes))
- return (SuperTypesSet) fSuperTypesSets.get(subTypes);
- else {
- SuperTypesSet s= new SuperTypesSet(subTypes, this);
-
- fSuperTypesSets.put(subTypes, s);
- return s;
- }
- }
-
- public void dumpStats() {
- System.out.println("Common expression hits: " + fgCommonExprHits); //$NON-NLS-1$
- System.out.println("Common expression misses: " + fgCommonExprMisses); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetIntersection.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetIntersection.java
deleted file mode 100644
index 49dce0a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetIntersection.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2.TTypes;
-
-public class TypeSetIntersection extends TypeSet {
- private TypeSet fLHS;
- private TypeSet fRHS;
-
- public TypeSetIntersection(TypeSet lhs, TypeSet rhs) {
- super(lhs.getTypeSetEnvironment());
- fLHS= lhs;
- fRHS= rhs;
- }
-
- /**
- * @return Returns the LHS.
- */
- public TypeSet getLHS() {
- return fLHS;
- }
-
- /**
- * @return Returns the RHS.
- */
- public TypeSet getRHS() {
- return fRHS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- return fLHS.isUniverse() && fRHS.isUniverse();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return this; //new TypeSetIntersection(fLHS.makeClone(), fRHS.makeClone());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- if (fLHS.isEmpty() || fRHS.isEmpty())
- return true;
- if (fLHS.isUniverse() || fRHS.isUniverse())
- return false;
- // Another quick check we can make before jumping to the expensive stuff
- if (fLHS.contains(getJavaLangObject()) && fRHS.contains(getJavaLangObject()))
- return false;
-
-// TypeSet lhsLB= fLHS.lowerBound();
-// TypeSet rhsUB= fRHS.upperBound();
-//
-// // Avoid the infinite recursion that will occur if lhsLB == fLHS && rhsUB == fRHS
-// if ((!lhsLB.equals(fLHS) || !rhsUB.equals(fRHS)) &&
-// !lhsLB.intersectedWith(rhsUB).isEmpty())
-// return false;
-//
-// if (areAllSuperTypesOf(lhsLB, rhsUB))
-// return true;
-//
-// TypeSet lhsUB= fLHS.upperBound();
-// TypeSet rhsLB= fRHS.lowerBound();
-//
-// if (!lhsUB.intersectedWith(rhsLB).isEmpty())
-// return false;
-//
-// if (areAllSuperTypesOf(rhsLB, lhsUB))
-// return true;
-
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- return fLHS.contains(t) && fRHS.contains(t);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- return fLHS.containsAll(s) && fRHS.containsAll(s);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#subTypes()
- */
- public TypeSet subTypes() {
- if (isUniverse() || contains(getJavaLangObject()))
- return getTypeSetEnvironment().getUniverseTypeSet();
- // sub(xsect(sub(a),sub(b))) == xsect(sub(a),sub(b))
- if ((fLHS instanceof SubTypesSet || fLHS instanceof SubTypesOfSingleton) &&
- (fRHS instanceof SubTypesSet || fRHS instanceof SubTypesOfSingleton))
- return this;
- return getTypeSetEnvironment().createSubTypesSet(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#superTypes()
- */
- public TypeSet superTypes() {
- // super(xsect(super(a),super(b))) == xsect(super(a),super(b))
- if ((fLHS instanceof SuperTypesSet || fLHS instanceof SuperTypesOfSingleton) &&
- (fRHS instanceof SuperTypesSet || fRHS instanceof SuperTypesOfSingleton))
- return this;
- return getTypeSetEnvironment().createSuperTypesSet(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- if (fLHS.contains(getJavaLangObject()) && fRHS.contains(getJavaLangObject()))
- return new SingletonTypeSet(getTypeSetEnvironment().getJavaLangObject(), getTypeSetEnvironment());
-
- if (fEnumCache != null) return fEnumCache.upperBound();
-
- EnumeratedTypeSet lhsSet= fLHS.enumerate();
- EnumeratedTypeSet rhsSet= fRHS.enumerate();
- TypeSet xsect= lhsSet.intersectedWith(rhsSet);
-
- return xsect.upperBound();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- if (fLHS.hasUniqueLowerBound() && fRHS.hasUniqueLowerBound()) {
- TType lhsBound= fLHS.uniqueLowerBound();
- TType rhsBound= fRHS.uniqueLowerBound();
-
- if (lhsBound.equals(rhsBound))
- return new SingletonTypeSet(lhsBound, getTypeSetEnvironment());
- else if (TTypes.canAssignTo(lhsBound, rhsBound))
- return new SingletonTypeSet(rhsBound, getTypeSetEnvironment());
- else if (TTypes.canAssignTo(rhsBound, lhsBound))
- return new SingletonTypeSet(lhsBound, getTypeSetEnvironment());
- }
- if (fEnumCache != null) return fEnumCache.lowerBound();
-
- EnumeratedTypeSet lhsSet= fLHS.enumerate();
- EnumeratedTypeSet rhsSet= fRHS.enumerate();
- TypeSet xsect= lhsSet.intersectedWith(rhsSet);
-
- return xsect.lowerBound();
- }
-
- protected TypeSet specialCasesIntersectedWith(TypeSet s2) {
- if (s2.equals(fLHS)) // xsect(s2,xsect(s2,?)) = xsect(s2,?)
- return this;
- if (s2.equals(fRHS)) // xsect(s2,xsect(?,s2)) = xsect(?,s2)
- return this;
- if (s2 instanceof TypeSetIntersection) {
- TypeSetIntersection x2= (TypeSetIntersection) s2;
- //
- // The following should use a "quick equals()" guaranteed to be constant-time
- //
- // xsect(xsect(A,B),xsect(A,C)) = xsect(xsect(A,B),C)
- if (fLHS.equals(x2.fLHS))
- return new TypeSetIntersection(this, x2.fRHS);
- // xsect(xsect(A,B),xsect(C,A)) = xsect(xsect(A,B),C)
- if (fLHS.equals(x2.fRHS))
- return new TypeSetIntersection(this, x2.fLHS);
- // xsect(xsect(A,B),xsect(B,C)) = xsect(xsect(A,B),C)
- if (fRHS.equals(x2.fLHS))
- return new TypeSetIntersection(this, x2.fRHS);
- // xsect(xsect(A,B),xsect(C,B)) = xsect(xsect(A,B),C)
- if (fRHS.equals(x2.fRHS))
- return new TypeSetIntersection(this, x2.fLHS);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- if (fEnumCache != null) return fEnumCache.isSingleton();
-
- int count= 0;
- for(Iterator lhsIter= fLHS.iterator(); lhsIter.hasNext(); ) {
- TType t= (TType) lhsIter.next();
- if (fRHS.contains(t))
- count++;
- if (count > 1)
- return false;
- }
- return (count == 1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- if (fEnumCache != null) return fEnumCache.anyMember();
-
- for(Iterator lhsIter= fLHS.iterator(); lhsIter.hasNext(); ) {
- TType t= (TType) lhsIter.next();
- if (fRHS.contains(t))
- return t;
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- return enumerate().iterator();
-
-// return new Iterator() {
-// private Iterator fLHSIter= fLHS.iterator();
-// private TType fNext= null;
-// public void remove() {
-// throw new IllegalStateException("Unimplemented");
-// }
-// private void advance() {
-// for(; fLHSIter.hasNext(); ) {
-// TType t= (TType) fLHSIter.next();
-// if (fRHS.contains(t)) {
-// fNext= t;
-// break;
-// }
-// }
-// }
-// public boolean hasNext() {
-// if (fNext == null)
-// advance();
-// return fNext != null;
-// }
-// public Object next() {
-// if (fNext == null)
-// advance();
-// if (fNext == null)
-// throw new NoSuchElementException("No more elements in TypeSetIntersection");
-// TType result= fNext;
-// fNext= null;
-// return result;
-// }
-// };
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- if (o instanceof TypeSetIntersection) {
- TypeSetIntersection other= (TypeSetIntersection) o;
- return other.fLHS.equals(fLHS) && other.fRHS.equals(fRHS);
- } else
- return false;
- }
-
- public String toString() {
- return "<" + fID + ": intersect(" + fLHS + "," + fRHS + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return null;
- }
-
- private EnumeratedTypeSet fEnumCache= null;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- if (fEnumCache == null) {
- EnumeratedTypeSet lhsSet= fLHS.enumerate();
- EnumeratedTypeSet rhsSet= fRHS.enumerate();
- fEnumCache= lhsSet.intersectedWith(rhsSet).enumerate();
- }
-
- return fEnumCache;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetUnion.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetUnion.java
deleted file mode 100644
index a31a5218..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeSetUnion.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public class TypeSetUnion extends TypeSet {
- private TypeSet fLHS;
- private TypeSet fRHS;
-
- public TypeSetUnion(TypeSet lhs, TypeSet rhs) {
- super(lhs.getTypeSetEnvironment());
- fLHS= lhs;
- fRHS= rhs;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isUniverse()
- */
- public boolean isUniverse() {
- if (fLHS.isUniverse() || fRHS.isUniverse())
- return true;
- if (fLHS.isSingleton() && fRHS.isSingleton())
- return false;
- throw new IllegalStateException("unimplemented"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#makeClone()
- */
- public TypeSet makeClone() {
- return new TypeSetUnion(fLHS.makeClone(), fRHS.makeClone());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isEmpty()
- */
- public boolean isEmpty() {
- return fLHS.isEmpty() && fRHS.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#contains(TType)
- */
- public boolean contains(TType t) {
- return fLHS.contains(t) || fRHS.contains(t);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- return fLHS.containsAll(s) || fRHS.containsAll(s);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#anyMember()
- */
- public TType anyMember() {
- return fLHS.anyMember();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- if (o instanceof TypeSetUnion) {
- TypeSetUnion other= (TypeSetUnion) o;
- return other.fLHS.equals(fLHS) && other.fRHS.equals(fRHS);
- } else
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#upperBound()
- */
- public TypeSet upperBound() {
- throw new IllegalStateException("unimplemented"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#lowerBound()
- */
- public TypeSet lowerBound() {
- throw new IllegalStateException("unimplemented"); //$NON-NLS-1$
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#iterator()
- */
- public Iterator iterator() {
- throw new IllegalStateException("unimplemented"); //$NON-NLS-1$
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#isSingleton()
- */
- public boolean isSingleton() {
- return fLHS.isSingleton() && fRHS.isSingleton() && fLHS.anyMember().equals(fRHS.anyMember());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueLowerBound()
- */
- public boolean hasUniqueLowerBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#hasUniqueUpperBound()
- */
- public boolean hasUniqueUpperBound() {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueLowerBound()
- */
- public TType uniqueLowerBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#uniqueUpperBound()
- */
- public TType uniqueUpperBound() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#enumerate()
- */
- public EnumeratedTypeSet enumerate() {
- EnumeratedTypeSet result= fLHS.enumerate();
-
- result.addAll(fRHS.enumerate());
- return result;
- }
-
- public String toString() {
- return "<" + fID + ": union(" + fLHS + "," + fRHS + ")>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeUniverseSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeUniverseSet.java
deleted file mode 100644
index 59fc5f68..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints/typesets/TypeUniverseSet.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Robert M. Fuhrer (rfuhrer@watson.ibm.com), IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public class TypeUniverseSet extends SubTypesOfSingleton {
-
- TypeUniverseSet(TypeSetEnvironment typeSetEnvironment) {
- super(typeSetEnvironment.getJavaLangObject(), typeSetEnvironment);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.SubTypesSet#contains(TType)
- */
- public boolean contains(TType t) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.SubTypesSet#containsAll(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public boolean containsAll(TypeSet s) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet#addedTo(org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.TypeSet)
- */
- public TypeSet addedTo(TypeSet that) {
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.typesets.SubTypesOfSingleton#makeClone()
- */
- public TypeSet makeClone() {
- return this; // new TypeUniverseSet();
- }
-
- public String toString() {
- return "{ " + fID + ": <universe> }"; //$NON-NLS-1$//$NON-NLS-2$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayElementVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayElementVariable2.java
deleted file mode 100644
index 49cbb8ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayElementVariable2.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-
-
-public final class ArrayElementVariable2 extends ConstraintVariable2 {
-
- private final ConstraintVariable2 fParentCv;
-
- public ArrayElementVariable2(ConstraintVariable2 parentCv) {
- super(((ArrayType) parentCv.getType()).getComponentType());
- fParentCv= parentCv;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return fParentCv.hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != ArrayElementVariable2.class)
- return false;
-
- ArrayElementVariable2 other2= (ArrayElementVariable2) other;
- return fParentCv == other2.fParentCv;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayTypeVariable2.java
deleted file mode 100644
index 989c66a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ArrayTypeVariable2.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.ArrayType;
-
-/**
- * An ArrayTypeVariable2 is a ConstraintVariable which stands for an array type.
- */
-public class ArrayTypeVariable2 extends ConstraintVariable2 {
-
- public ArrayTypeVariable2(ArrayType type) {
- super(type);
- }
-
- // hashCode() and equals(..) not necessary (unique per construction)
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CastVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CastVariable2.java
deleted file mode 100644
index 88d0bad0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CastVariable2.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public final class CastVariable2 extends ConstraintVariable2 implements ITypeConstraintVariable {
-
- private final CompilationUnitRange fRange;
- private final ConstraintVariable2 fExpressionVariable;
-
- public CastVariable2(TType type, CompilationUnitRange range, ConstraintVariable2 expressionVariable) {
- super(type);
- Assert.isNotNull(expressionVariable);
- Assert.isNotNull(range);
- fRange= range;
- fExpressionVariable= expressionVariable;
- }
-
- public CompilationUnitRange getRange() {
- return fRange;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fRange.getCompilationUnit();
- }
-
- public void setCompilationUnit(IJavaScriptUnit unit) {
- throw new UnsupportedOperationException();
- }
-
- public ConstraintVariable2 getExpressionVariable() {
- return fExpressionVariable;
- }
-
- // hashCode() and equals(..) not necessary (unique per construction)
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CollectionElementVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CollectionElementVariable2.java
deleted file mode 100644
index b7180529..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/CollectionElementVariable2.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-
-public final class CollectionElementVariable2 extends ConstraintVariable2 {
-
- public static final int NOT_DECLARED_TYPE_VARIABLE_INDEX= -1;
-
- private final ConstraintVariable2 fParentCv;
- private final String fTypeVariableKey;
- private final int fDeclarationTypeVariableIndex;
-
- //TODO: make a 'TypedCollectionElementVariable extends TypeConstraintVariable2'
- // iff Collection reference already has type parameter in source
- /**
- * @param parentCv the parent constraint variable
- * @param typeVariable the type variable for this constraint
- * @param declarationTypeVariableIndex
- */
- public CollectionElementVariable2(ConstraintVariable2 parentCv, ITypeBinding typeVariable, int declarationTypeVariableIndex) {
- super(null);
- fParentCv= parentCv;
- throw new IllegalArgumentException(typeVariable.toString());
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return fParentCv.hashCode() ^ fTypeVariableKey.hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != CollectionElementVariable2.class)
- return false;
-
- CollectionElementVariable2 other2= (CollectionElementVariable2) other;
- return fParentCv == other2.fParentCv
- && fTypeVariableKey.equals(other2.fTypeVariableKey);
- }
-
- public int getDeclarationTypeVariableIndex() {
- return fDeclarationTypeVariableIndex;
- }
-
- public ConstraintVariable2 getParentConstraintVariable() {
- return fParentCv;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- if (fParentCv instanceof ISourceConstraintVariable)
- return ((ISourceConstraintVariable) fParentCv).getCompilationUnit();
- else
- return null;
-// //TODO: assert in constructor(s)
-// return ((CollectionElementVariable2) fElementCv).getCompilationUnit();
- }
-
- public String toString() {
- return "Elem[" + fParentCv.toString() + ", " + fTypeVariableKey + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ConstraintVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ConstraintVariable2.java
deleted file mode 100644
index 9a0401e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ConstraintVariable2.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public abstract class ConstraintVariable2 {
-
- public static final String TO_STRING= "toString"; //$NON-NLS-1$
-
- private Object[] fDatas;
-
- private TypeEquivalenceSet fTypeEquivalenceSet;
-
- protected final TType fType;
-
- /**
- * @param type the type
- */
- protected ConstraintVariable2(TType type) {
- fType= type;
- }
-
- public Object getData(String name) {
- if (fDatas == null) {
- return null;
- } else {
- for (int i= 0; i < fDatas.length; i+= 2) {
- String key= (String) fDatas[i];
- if (key.equals(name))
- return fDatas[i + 1];
- }
- return null;
- }
- }
-
- public TypeEquivalenceSet getTypeEquivalenceSet() {
- return fTypeEquivalenceSet;
- }
-
- /**
- * @return the type binding, or <code>null</code> iff the type constraint variable has no type in the original source (e.g. {@link CollectionElementVariable2})
- */
- public TType getType() {
- return fType;
- }
-
- public ITypeSet getTypeEstimate() {
- Assert.isNotNull(fTypeEquivalenceSet);
- return fTypeEquivalenceSet.getTypeEstimate();
- }
-
- public void setData(String name, Object data) {
- int index= 0;
- if (fDatas != null) {
- while (index < fDatas.length) {
- if (name.equals(fDatas[index]))
- break;
- index+= 2;
- }
- }
- if (data != null) { // add
- if (fDatas != null) {
- if (index == fDatas.length) {
- Object[] newTable= new Object[fDatas.length + 2];
- System.arraycopy(fDatas, 0, newTable, 0, fDatas.length);
- fDatas= newTable;
- }
- } else {
- fDatas= new Object[2];
- }
- fDatas[index]= name;
- fDatas[index + 1]= data;
- } else { // remove
- if (fDatas != null) {
- if (index != fDatas.length) {
- int length= fDatas.length - 2;
- if (length == 0) {
- fDatas= null;
- } else {
- Object[] newTable= new Object[length];
- System.arraycopy(fDatas, 0, newTable, 0, index);
- System.arraycopy(fDatas, index + 2, newTable, index, length - index);
- fDatas= newTable;
- }
- }
- }
- }
- }
-
- public void setTypeEquivalenceSet(TypeEquivalenceSet set) {
- fTypeEquivalenceSet= set;
- }
-
- public String toString() {
- String toString= (String) getData(TO_STRING);
- if (toString != null)
- return toString;
-
- String name= getClass().getName();
- int dot= name.lastIndexOf('.');
- return name.substring(dot + 1) + ": " + fType != null ? fType.getPrettySignature() : "<NONE>"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ISourceConstraintVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ISourceConstraintVariable.java
deleted file mode 100644
index e46e06f1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ISourceConstraintVariable.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-public interface ISourceConstraintVariable {
-
- public IJavaScriptUnit getCompilationUnit();
-
- public Object getData(String name);
-
- public ITypeSet getTypeEstimate();
-
- public void setCompilationUnit(IJavaScriptUnit cu);
-
- public void setData(String name, Object data);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraint2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraint2.java
deleted file mode 100644
index e803d881..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraint2.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-public interface ITypeConstraint2 {
-
- public ConstraintVariable2 getLeft();
-
- public ConstraintVariable2 getRight();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraintVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraintVariable.java
deleted file mode 100644
index 1b767e53..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeConstraintVariable.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-
-public interface ITypeConstraintVariable extends ISourceConstraintVariable {
-
- public CompilationUnitRange getRange();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeSet.java
deleted file mode 100644
index e73c6cfb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ITypeSet.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public interface ITypeSet {
-
- public TType chooseSingleType();
-
- public ITypeSet restrictedTo(ITypeSet restrictionSet);
-
- public String toString();
-
- public boolean isEmpty();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ImmutableTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ImmutableTypeVariable2.java
deleted file mode 100644
index 0a97c66f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ImmutableTypeVariable2.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A ImmutableTypeVariable is a ConstraintVariable which stands for an
- * immutable type (without an updatable Source location)
- */
-
-public final class ImmutableTypeVariable2 extends ConstraintVariable2 {
-
- public ImmutableTypeVariable2(TType type) {
- super(type);
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getType().hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != ImmutableTypeVariable2.class)
- return false;
-
- return getType() == ((ImmutableTypeVariable2) other).getType();
- }
-
- public String toString() {
- return getType().getPrettySignature();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/IndependentTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/IndependentTypeVariable2.java
deleted file mode 100644
index 4fe96178..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/IndependentTypeVariable2.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public final class IndependentTypeVariable2 extends ConstraintVariable2 {
-
- public IndependentTypeVariable2(TType type) {
- super(type);
- }
-
- // hashCode() and equals(..) not necessary (unique per construction)
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterTypeVariable2.java
deleted file mode 100644
index d1a19e6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterTypeVariable2.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A ParameterTypeVariable is a ConstraintVariable which stands for
- * the type of a method parameter.
- */
-public final class ParameterTypeVariable2 extends ConstraintVariable2 implements ISourceConstraintVariable {
-
- private final int fParameterIndex;
- private final String fKey;
- private IJavaScriptUnit fCompilationUnit;
-
- public ParameterTypeVariable2(TType type, int index, IFunctionBinding binding) {
- super(type);
- Assert.isNotNull(binding);
- Assert.isTrue(0 <= index);
- fParameterIndex= index;
- fKey= binding.getKey();
- }
-
- public void setCompilationUnit(IJavaScriptUnit cu) {
- fCompilationUnit= cu;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- public int getParameterIndex() {
- return fParameterIndex;
- }
-
- public String getKey() {
- return fKey;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getParameterIndex() ^ getKey().hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != ParameterTypeVariable2.class)
- return false;
-
- ParameterTypeVariable2 other2= (ParameterTypeVariable2) other;
- return getParameterIndex() == other2.getParameterIndex()
- && getKey().equals(other2.getKey());
- }
-
- public String toString() {
- String toString= (String) getData(TO_STRING);
- return toString == null ? "[Parameter(" + fParameterIndex + "," + fKey + ")]" : toString; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterizedTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterizedTypeVariable2.java
deleted file mode 100644
index 1243d251..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ParameterizedTypeVariable2.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A ParameterizedTypeVariable2 is a ConstraintVariable which stands for
- * a unique parameterization of a generic type (without an updatable source location)
- */
-public final class ParameterizedTypeVariable2 extends ConstraintVariable2 {
-
- public ParameterizedTypeVariable2(TType type) {
- super(type);
- Assert.isTrue(! type.isWildcardType());
- Assert.isTrue(! type.isTypeVariable());
- }
-
- // hashCode() and equals(..) not necessary (unique per construction)
-
- public String toString() {
- return getType().getName();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ReturnTypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ReturnTypeVariable2.java
deleted file mode 100644
index 0be0a026..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/ReturnTypeVariable2.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A ReturnTypeVariable is a ConstraintVariable which stands for
- * the return type of a method.
- */
-public final class ReturnTypeVariable2 extends ConstraintVariable2 implements ISourceConstraintVariable {
-
- private final String fKey;
- private IJavaScriptUnit fCompilationUnit;
-
- public ReturnTypeVariable2(TType type, IFunctionBinding binding) {
- super(type);
- fKey= binding.getKey();
- }
-
- public String getKey() {
- return fKey;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getKey().hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != ReturnTypeVariable2.class)
- return false;
-
- ReturnTypeVariable2 other2= (ReturnTypeVariable2) other;
- return getKey().equals(other2.getKey());
- }
-
- public void setCompilationUnit(IJavaScriptUnit unit) {
- fCompilationUnit= unit;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/SubTypeConstraint2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/SubTypeConstraint2.java
deleted file mode 100644
index 37f9e775..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/SubTypeConstraint2.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-
-public final class SubTypeConstraint2 implements ITypeConstraint2 {
-
- private final ConstraintVariable2 fAncestor;
-
- private final ConstraintVariable2 fDescendant;
-
- public SubTypeConstraint2(final ConstraintVariable2 descendant, final ConstraintVariable2 ancestor) {
- Assert.isNotNull(descendant);
- Assert.isNotNull(ancestor);
- fDescendant= descendant;
- fAncestor= ancestor;
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public final boolean equals(Object other) {
- // can use object identity on ConstraintVariables, since we have the stored (or to be stored) objects
- if (other.getClass() != SubTypeConstraint2.class)
- return false;
-
- ITypeConstraint2 otherTC= (ITypeConstraint2) other;
- return fDescendant == otherTC.getLeft() && fAncestor == otherTC.getRight();
- }
-
- public final ConstraintVariable2 getLeft() {
- return fDescendant;
- }
-
- public final ConstraintVariable2 getRight() {
- return fAncestor;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public final int hashCode() {
- return fDescendant.hashCode() ^ 37 * fAncestor.hashCode();
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public final String toString() {
- return fDescendant.toString() + " <= " + fAncestor.toString(); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TTypes.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TTypes.java
deleted file mode 100644
index effc2771..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TTypes.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import java.util.Iterator;
-import java.util.Stack;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.AbstractTypeVariable;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.HierarchyType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-public class TTypes {
-
- private static class AllSupertypesIterator implements Iterator {
- private final Stack fWorklist;
-
- public AllSupertypesIterator(TType type) {
- fWorklist= new Stack();
- pushSupertypes(type);
- }
-
- public boolean hasNext() {
- return ! fWorklist.empty();
- }
-
- public Object next() {
- TType result= (TType) fWorklist.pop();
- pushSupertypes(result);
- return result;
- }
-
- private void pushSupertypes(TType type) {
- if (type.isJavaLangObject())
- return;
-
- if (type.isTypeVariable() || type.isCaptureType()) {
- TType[] bounds= ((AbstractTypeVariable) type).getBounds();
- for (int i= 0; i < bounds.length; i++)
- fWorklist.push(bounds[i].getTypeDeclaration());
-
- } else {
- TType superclass= type.getSuperclass();
- if (superclass == null) {
- if (type.isInterface())
- fWorklist.push(type.getEnvironment().getJavaLangObject());
- } else {
- fWorklist.push(superclass.getTypeDeclaration());
- }
- TType[] interfaces= type.getInterfaces();
- for (int i= 0; i < interfaces.length; i++)
- fWorklist.push(interfaces[i].getTypeDeclaration());
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-
- private static class AllSubtypesIterator implements Iterator {
- private final Stack fWorklist;
-
- public AllSubtypesIterator(TType type) {
- fWorklist= new Stack();
- fWorklist.push(type.getTypeDeclaration());
- }
-
- public boolean hasNext() {
- return ! fWorklist.empty();
- }
-
- public Object next() {
- TType result= (TType) fWorklist.pop();
- TType[] subTypes= result.getSubTypes();
- for (int i= 0; i < subTypes.length; i++)
- fWorklist.push(subTypes[i].getTypeDeclaration());
-
- return result;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-
- private TTypes() {
- // no instances
- }
-
- public static TType createArrayType(TType elementType, int dimensions) {
- return elementType.getEnvironment().createArrayType(elementType, dimensions);
- }
-
- /**
- * @return all subtypes of this type (including this type)
- */
- public static Iterator getAllSubTypesIterator(TType type) {
- return new AllSubtypesIterator(type);
- }
-
- /**
- * @return all proper supertypes of this type
- */
- public static Iterator getAllSuperTypesIterator(TType type) {
- return new AllSupertypesIterator(type);
- }
-
- /**
- * @param rhs
- * @param lhs
- * @return <code>true</code> iff an expression of type 'rhs' can be assigned to a variable of type 'lhs'.
- * Type arguments of generic / raw / parameterized types are <b>not</b> considered.
- */
- public static boolean canAssignTo(TType rhs, TType lhs) {
- if (rhs.isHierarchyType() && lhs.isHierarchyType()) {
- HierarchyType rhsGeneric= (HierarchyType) rhs.getTypeDeclaration();
- HierarchyType lhsGeneric= (HierarchyType) lhs.getTypeDeclaration();
- return lhs.isJavaLangObject() || rhsGeneric.equals(lhsGeneric) || rhsGeneric.isSubType(lhsGeneric);
-
- } else if (rhs.isTypeVariable()) {
- if (rhs.canAssignTo(lhs))
- return true;
- return lhs.isJavaLangObject();
-
- } else {
- return rhs.canAssignTo(lhs);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeEquivalenceSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeEquivalenceSet.java
deleted file mode 100644
index f987b938..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeEquivalenceSet.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.List;
-
-public class TypeEquivalenceSet {
-
- private ConstraintVariable2[] fVariables;
- private ITypeSet fTypeEstimate;
-
-
- public TypeEquivalenceSet(ConstraintVariable2 first, ConstraintVariable2 second) {
- fVariables= new ConstraintVariable2[] {first, second };
- }
-
- public TypeEquivalenceSet(ConstraintVariable2 variable) {
- fVariables= new ConstraintVariable2[] {variable};
- }
-
- public void add(ConstraintVariable2 variable) {
- for (int i= 0; i < fVariables.length; i++)
- if (fVariables[i] == variable)
- return;
-
- int length= fVariables.length;
- ConstraintVariable2[] newElements= new ConstraintVariable2[length + 1];
- System.arraycopy(fVariables, 0, newElements, 0, length);
- newElements[length]= variable;
- fVariables= newElements;
- }
-
- public ConstraintVariable2[] getContributingVariables() {
- return fVariables;
- }
-
- public void addAll(ConstraintVariable2[] variables) {
- if (fVariables.length * variables.length > 100) {
- LinkedHashSet result= new LinkedHashSet(fVariables.length + variables.length);
- result.addAll(Arrays.asList(fVariables));
- result.addAll(Arrays.asList(variables));
- fVariables= (ConstraintVariable2[]) result.toArray(new ConstraintVariable2[result.size()]);
-
- } else {
- List elements= Arrays.asList(fVariables);
- ArrayList result= new ArrayList(fVariables.length + variables.length);
- result.addAll(elements);
- for (int i= 0; i < variables.length; i++) {
- ConstraintVariable2 right= variables[i];
- if (! result.contains(right))
- result.add(right);
- }
- fVariables= (ConstraintVariable2[]) result.toArray(new ConstraintVariable2[result.size()]);
- }
-
- }
-
- public void setTypeEstimate(ITypeSet estimate) {
- fTypeEstimate= estimate;
- }
-
- public ITypeSet getTypeEstimate() {
- return fTypeEstimate;
- }
-
- public String toString() {
- StringBuffer result= new StringBuffer();
- if (fVariables.length > 0)
- result.append(fVariables[0].toString());
- for (int i= 1; i < fVariables.length; i++) {
- result.append(" =^= \n"); //$NON-NLS-1$
- result.append(fVariables[i].toString());
- }
- return result.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java
deleted file mode 100644
index 401fac57..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A TypeVariable is a ConstraintVariable which stands for a
- * single type reference (in source).
- */
-public final class TypeVariable2 extends ConstraintVariable2 implements ITypeConstraintVariable {
-
- private final CompilationUnitRange fRange;
-
- public TypeVariable2(TType type, CompilationUnitRange range) {
- super(type);
- Assert.isNotNull(range);
- fRange= range;
- }
-
- public CompilationUnitRange getRange() {
- return fRange;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return getRange().hashCode() ^ getType().hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- //TODO: unique per construction? //return this == other;
- if (this == other)
- return true;
- if (other.getClass() != TypeVariable2.class)
- return false;
-
- TypeVariable2 otherTypeVariable= (TypeVariable2) other;
- return getRange().equals(otherTypeVariable.getRange())
- && getType() == otherTypeVariable.getType();
- }
-
- public void setCompilationUnit(IJavaScriptUnit unit) {
- throw new UnsupportedOperationException();
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fRange.getCompilationUnit();
- }
-
- public String toString() {
- return super.toString() + " [" + fRange.getSourceRange().getOffset() + '+' + fRange.getSourceRange().getLength() + ']'; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/VariableVariable2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/VariableVariable2.java
deleted file mode 100644
index 440a365e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/typeconstraints2/VariableVariable2.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints2;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.typeconstraints.types.TType;
-
-/**
- * A VariableVariable is a ConstraintVariable which stands for
- * the type of a variable, namely a field or a local variable
- * Use {@link ParameterTypeVariable2} for method parameters).
- */
-public final class VariableVariable2 extends ConstraintVariable2 implements ISourceConstraintVariable {
-
- private final String fKey;
- private IJavaScriptUnit fCompilationUnit;
-
- public VariableVariable2(TType type, IVariableBinding binding) {
- super(type);
- fKey= binding.getKey();
- }
-
- public void setCompilationUnit(IJavaScriptUnit unit) {
- fCompilationUnit= unit;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- public String getKey() {
- return fKey;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return fKey.hashCode();
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (this == other)
- return true;
- if (other.getClass() != VariableVariable2.class)
- return false;
-
- return fKey.equals(((VariableVariable2) other).getKey());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java
deleted file mode 100644
index 4d4a86c9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Stack;
-
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-
-public abstract class AbstractExceptionAnalyzer extends ASTVisitor {
-
- private List fCurrentExceptions; // Elements in this list are of type TypeBinding
- private Stack fTryStack;
-
- protected AbstractExceptionAnalyzer() {
- fTryStack= new Stack();
- fCurrentExceptions= new ArrayList(1);
- fTryStack.push(fCurrentExceptions);
- }
-
- public abstract boolean visit(ThrowStatement node);
-
- public abstract boolean visit(FunctionInvocation node);
-
- public abstract boolean visit(ClassInstanceCreation node);
-
- public boolean visit(TypeDeclaration node) {
- // Don't dive into a local type.
- if (node.isLocalTypeDeclaration())
- return false;
- return true;
- }
-
-
- public boolean visit(AnonymousClassDeclaration node) {
- // Don't dive into a local type.
- return false;
- }
-
- public boolean visit(TryStatement node) {
- fCurrentExceptions= new ArrayList(1);
- fTryStack.push(fCurrentExceptions);
-
- // visit try block
- node.getBody().accept(this);
-
- // Remove those exceptions that get catch by following catch blocks
- List catchClauses= node.catchClauses();
- if (!catchClauses.isEmpty())
- handleCatchArguments(catchClauses);
- List current= (List)fTryStack.pop();
- fCurrentExceptions= (List)fTryStack.peek();
- for (Iterator iter= current.iterator(); iter.hasNext();) {
- addException((ITypeBinding)iter.next());
- }
-
- // visit catch and finally
- for (Iterator iter= catchClauses.iterator(); iter.hasNext(); ) {
- ((CatchClause)iter.next()).accept(this);
- }
- if (node.getFinally() != null)
- node.getFinally().accept(this);
-
- // return false. We have visited the body by ourselves.
- return false;
- }
-
- protected void addExceptions(ITypeBinding[] exceptions) {
- if(exceptions == null)
- return;
- for (int i= 0; i < exceptions.length;i++) {
- addException(exceptions[i]);
- }
- }
-
- protected void addException(ITypeBinding exception) {
- if (!fCurrentExceptions.contains(exception))
- fCurrentExceptions.add(exception);
- }
-
- protected List getCurrentExceptions() {
- return fCurrentExceptions;
- }
-
- private void handleCatchArguments(List catchClauses) {
- for (Iterator iter= catchClauses.iterator(); iter.hasNext(); ) {
- CatchClause clause= (CatchClause)iter.next();
- ITypeBinding catchTypeBinding= clause.getException().getType().resolveBinding();
- if (catchTypeBinding == null) // No correct type resolve.
- continue;
- for (Iterator exceptions= new ArrayList(fCurrentExceptions).iterator(); exceptions.hasNext(); ) {
- ITypeBinding throwTypeBinding= (ITypeBinding)exceptions.next();
- if (catches(catchTypeBinding, throwTypeBinding))
- fCurrentExceptions.remove(throwTypeBinding);
- }
- }
- }
-
- private boolean catches(ITypeBinding catchTypeBinding, ITypeBinding throwTypeBinding) {
- while(throwTypeBinding != null) {
- if (throwTypeBinding == catchTypeBinding)
- return true;
- throwTypeBinding= throwTypeBinding.getSuperclass();
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/Changes.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/Changes.java
deleted file mode 100644
index 580f29e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/Changes.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-
-
-public class Changes {
-
- public static IFile[] getModifiedFiles(Change[] changes) {
- List result= new ArrayList();
- getModifiedFiles(result, changes);
- return (IFile[]) result.toArray(new IFile[result.size()]);
- }
-
- private static void getModifiedFiles(List result, Change[] changes) {
- for (int i= 0; i < changes.length; i++) {
- Change change= changes[i];
- Object modifiedElement= change.getModifiedElement();
- if (modifiedElement instanceof IAdaptable) {
- IFile file= (IFile)((IAdaptable)modifiedElement).getAdapter(IFile.class);
- if (file != null)
- result.add(file);
- }
- if (change instanceof CompositeChange) {
- getModifiedFiles(result, ((CompositeChange)change).getChildren());
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CodeAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CodeAnalyzer.java
deleted file mode 100644
index b9d049c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CodeAnalyzer.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-
-public class CodeAnalyzer extends StatementAnalyzer {
-
- public CodeAnalyzer(IJavaScriptUnit cunit, Selection selection, boolean traverseSelectedNode) throws JavaScriptModelException {
- super(cunit, selection, traverseSelectedNode);
- }
-
- protected final void checkSelectedNodes() {
- super.checkSelectedNodes();
- RefactoringStatus status= getStatus();
- if (status.hasFatalError())
- return;
- ASTNode node= getFirstSelectedNode();
- if (node instanceof ArrayInitializer) {
- status.addFatalError(RefactoringCoreMessages.CodeAnalyzer_array_initializer, JavaStatusContext.create(fCUnit, node));
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CommentAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CommentAnalyzer.java
deleted file mode 100644
index 0bd420ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/CommentAnalyzer.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class CommentAnalyzer {
-
- private CommentAnalyzer() {
- }
-
- public static RefactoringStatus perform(Selection selection, IScanner scanner, int start, int length) {
- RefactoringStatus result= new RefactoringStatus();
- if (length <= 0)
- return result;
- new CommentAnalyzer().check(result, selection, scanner, start, start + length - 1);
- return result;
- }
-
- private void check(RefactoringStatus result, Selection selection, IScanner scanner, int start, int end) {
- char[] characters= scanner.getSource();
- selection= adjustSelection(characters, selection, end);
- scanner.resetTo(start, end);
-
- int token= 0;
- try {
- loop: while (token != ITerminalSymbols.TokenNameEOF) {
- token= scanner.getNextToken();
- switch(token) {
- case ITerminalSymbols.TokenNameCOMMENT_LINE:
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK:
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC:
- if (checkStart(scanner, selection.getOffset())) {
- result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_starts_inside_comment);
- break loop;
- }
- if (checkEnd(scanner, selection.getInclusiveEnd())) {
- result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_ends_inside_comment);
- break loop;
- }
- break;
- }
- }
- } catch (InvalidInputException e) {
- result.addFatalError(RefactoringCoreMessages.CommentAnalyzer_internal_error);
- }
- }
-
- private boolean checkStart(IScanner scanner, int position) {
- return scanner.getCurrentTokenStartPosition() < position && position <= scanner.getCurrentTokenEndPosition();
- }
-
- private boolean checkEnd(IScanner scanner, int position) {
- return scanner.getCurrentTokenStartPosition() <= position && position < scanner.getCurrentTokenEndPosition();
- }
-
- private Selection adjustSelection(char[] characters, Selection selection, int end) {
- int newEnd= selection.getInclusiveEnd();
- for(int i= selection.getExclusiveEnd(); i <= end; i++) {
- char ch= characters[i];
- if (ch != '\n' && ch != '\r')
- break;
- newEnd++;
- }
- return Selection.createFromStartEnd(selection.getOffset(), newEnd);
- }
-
- /**
- * Removes comments and whitespace
- * @param reference the type reference
- * @return the reference only consisting of dots and java identifier characters
- */
- public static String normalizeReference(String reference) {
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(reference.toCharArray());
- StringBuffer sb= new StringBuffer();
- try {
- int tokenType= scanner.getNextToken();
- while (tokenType != ITerminalSymbols.TokenNameEOF) {
- sb.append(scanner.getRawTokenSource());
- tokenType= scanner.getNextToken();
- }
- } catch (InvalidInputException e) {
- Assert.isTrue(false, reference);
- }
- reference= sb.toString();
- return reference;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavaElementUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavaElementUtil.java
deleted file mode 100644
index c022b636..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavaElementUtil.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-public class JavaElementUtil {
-
- //no instances
- private JavaElementUtil(){
- }
-
- public static String createMethodSignature(IFunction method){
- try {
- return Signature.toString(method.getSignature(), method.getElementName(), method.getParameterNames(), false, ! method.isConstructor());
- } catch(JavaScriptModelException e) {
- return method.getElementName(); //fallback
- }
- }
-
- public static String createFieldSignature(IField field){
- return JavaModelUtil.getFullyQualifiedName(field.getDeclaringType()) + "." + field.getElementName(); //$NON-NLS-1$
- }
-
- public static String createSignature(IMember member){
- switch (member.getElementType()){
- case IJavaScriptElement.FIELD:
- return createFieldSignature((IField)member);
- case IJavaScriptElement.TYPE:
- return JavaModelUtil.getFullyQualifiedName(((IType)member));
- case IJavaScriptElement.INITIALIZER:
- return RefactoringCoreMessages.JavaElementUtil_initializer;
- case IJavaScriptElement.METHOD:
- return createMethodSignature((IFunction)member);
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public static IJavaScriptElement[] getElementsOfType(IJavaScriptElement[] elements, int type){
- Set result= new HashSet(elements.length);
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement element= elements[i];
- if (element.getElementType() == type)
- result.add(element);
- }
- return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- public static IType getMainType(IJavaScriptUnit cu) throws JavaScriptModelException{
- IType[] types= cu.getTypes();
- for (int i = 0; i < types.length; i++) {
- if (isMainType(types[i]))
- return types[i];
- }
- return null;
- }
-
- public static boolean isMainType(IType type) throws JavaScriptModelException{
- if (! type.exists())
- return false;
-
- if (type.isBinary())
- return false;
-
- if (type.getJavaScriptUnit() == null)
- return false;
-
- if (type.getDeclaringType() != null)
- return false;
-
- return isPrimaryType(type) || isCuOnlyType(type);
- }
-
-
- private static boolean isPrimaryType(IType type){
- return type.equals(type.getJavaScriptUnit().findPrimaryType());
- }
-
-
- private static boolean isCuOnlyType(IType type) throws JavaScriptModelException{
- return type.getJavaScriptUnit().getTypes().length == 1;
- }
-
- /** see org.eclipse.wst.jsdt.internal.core.JavaElement#isAncestorOf(org.eclipse.wst.jsdt.core.IJavaScriptElement) */
- public static boolean isAncestorOf(IJavaScriptElement ancestor, IJavaScriptElement child) {
- IJavaScriptElement parent= child.getParent();
- while (parent != null && !parent.equals(ancestor)) {
- parent= parent.getParent();
- }
- return parent != null;
- }
-
- public static IFunction[] getAllConstructors(IType type) throws JavaScriptModelException {
- List result= new ArrayList();
- IFunction[] methods= type.getFunctions();
- for (int i= 0; i < methods.length; i++) {
- IFunction iMethod= methods[i];
- if (iMethod.isConstructor())
- result.add(iMethod);
- }
- return (IFunction[]) result.toArray(new IFunction[result.size()]);
- }
-
- /**
- * Returns an array of projects that have the specified root on their
- * classpaths.
- */
- public static IJavaScriptProject[] getReferencingProjects(IPackageFragmentRoot root) throws JavaScriptModelException {
- IIncludePathEntry cpe= root.getRawIncludepathEntry();
- IJavaScriptProject[] allJavaProjects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
- List result= new ArrayList(allJavaProjects.length);
- for (int i= 0; i < allJavaProjects.length; i++) {
- IJavaScriptProject project= allJavaProjects[i];
- IPackageFragmentRoot[] roots= project.findPackageFragmentRoots(cpe);
- if (roots.length > 0)
- result.add(project);
- }
- return (IJavaScriptProject[]) result.toArray(new IJavaScriptProject[result.size()]);
- }
-
- public static IMember[] merge(IMember[] a1, IMember[] a2) {
- // Don't use hash sets since ordering is important for some refactorings.
- List result= new ArrayList(a1.length + a2.length);
- for (int i= 0; i < a1.length; i++) {
- IMember member= a1[i];
- if (!result.contains(member))
- result.add(member);
- }
- for (int i= 0; i < a2.length; i++) {
- IMember member= a2[i];
- if (!result.contains(member))
- result.add(member);
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- public static boolean isDefaultPackage(Object element) {
- return (element instanceof IPackageFragment) && ((IPackageFragment)element).isDefaultPackage();
- }
-
- /**
- * @param pack a package fragment
- * @return an array containing the given package and all subpackages
- * @throws JavaScriptModelException
- */
- public static IPackageFragment[] getPackageAndSubpackages(IPackageFragment pack) throws JavaScriptModelException {
- if (pack.isDefaultPackage())
- return new IPackageFragment[] { pack };
-
- IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent();
- IJavaScriptElement[] allPackages= root.getChildren();
- ArrayList subpackages= new ArrayList();
- subpackages.add(pack);
- String prefix= pack.getElementName() + '.';
- for (int i= 0; i < allPackages.length; i++) {
- IPackageFragment currentPackage= (IPackageFragment) allPackages[i];
- if (currentPackage.getElementName().startsWith(prefix))
- subpackages.add(currentPackage);
- }
- return (IPackageFragment[]) subpackages.toArray(new IPackageFragment[subpackages.size()]);
- }
-
- /**
- * @param pack the package fragment; may not be null
- * @return the parent package fragment, or null if the given package fragment is the default package or a top level package
- */
- public static IPackageFragment getParentSubpackage(IPackageFragment pack) {
- if (pack.isDefaultPackage())
- return null;
-
- final int index= pack.getElementName().lastIndexOf('.');
- if (index == -1)
- return null;
-
- final IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent();
- final String newPackageName= pack.getElementName().substring(0, index);
- final IPackageFragment parent= root.getPackageFragment(newPackageName);
- if (parent.exists())
- return parent;
- else
- return null;
- }
-
- public static IMember[] sortByOffset(IMember[] members){
- Comparator comparator= new Comparator(){
- public int compare(Object o1, Object o2){
- try{
- return ((IMember) o1).getNameRange().getOffset() - ((IMember) o2).getNameRange().getOffset();
- } catch (JavaScriptModelException e){
- return 0;
- }
- }
- };
- Arrays.sort(members, comparator);
- return members;
- }
-
- public static boolean isSourceAvailable(ISourceReference sourceReference) {
- try {
- return SourceRange.isAvailable(sourceReference.getSourceRange());
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavadocUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavadocUtil.java
deleted file mode 100644
index c6eeb0cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/JavadocUtil.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavadocTagsSubProcessor;
-
-
-public class JavadocUtil {
-
- private JavadocUtil() {
- // static-only
- }
-
- //TODO: is a copy of ChangeSignatureRefactoring.DeclarationUpdate#createParamTag(..)
- public static TagElement createParamTag(String parameterName, AST ast, IJavaScriptProject javaProject) {
- TagElement paramNode= ast.newTagElement();
- paramNode.setTagName(TagElement.TAG_PARAM);
-
- SimpleName simpleName= ast.newSimpleName(parameterName);
- paramNode.fragments().add(simpleName);
-
- TextElement textElement= ast.newTextElement();
- String text= StubUtility.getTodoTaskTag(javaProject);
- if (text != null)
- textElement.setText(text); //TODO: use template with {@todo} ...
- paramNode.fragments().add(textElement);
-
- return paramNode;
- }
-
- /**
- * Decide whether to add a "param" javadoc tag or not.
- * @param methodDeclaration the method declaration
- * @return method has javadoc && (method had no parameter before || there is already an @param tag)
- */
- public static boolean shouldAddParamJavadoc(FunctionDeclaration methodDeclaration) {
- JSdoc javadoc= methodDeclaration.getJavadoc();
- if (javadoc == null)
- return false;
- if (methodDeclaration.parameters().size() == 0)
- return true;
- List tags= javadoc.tags();
- for (Iterator iter= tags.iterator(); iter.hasNext();) {
- TagElement element= (TagElement) iter.next();
- if (TagElement.TAG_PARAM.equals(element.getTagName()))
- return true;
- }
- return false;
- }
-
-
- /**
- * Adds a "param" javadoc tag for a new last parameter if necessary.
- * @param parameterName
- * @param methodDeclaration
- * @param astRewrite
- * @param javaProject
- * @param groupDescription
- */
- public static void addParamJavadoc(String parameterName, FunctionDeclaration methodDeclaration,
- ASTRewrite astRewrite, IJavaScriptProject javaProject, TextEditGroup groupDescription) {
- if (! shouldAddParamJavadoc(methodDeclaration))
- return;
-
- ListRewrite tagsRewrite= astRewrite.getListRewrite(methodDeclaration.getJavadoc(), JSdoc.TAGS_PROPERTY);
- HashSet leadingNames= new HashSet();
- for (Iterator iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
- SingleVariableDeclaration curr= (SingleVariableDeclaration) iter.next();
- leadingNames.add(curr.getName().getIdentifier());
- }
- TagElement parameterTag= createParamTag(parameterName, astRewrite.getAST(), javaProject);
- JavadocTagsSubProcessor.insertTag(tagsRewrite, parameterTag, leadingNames, groupDescription);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/NoCommentSourceRangeComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/NoCommentSourceRangeComputer.java
deleted file mode 100644
index 6ca21360..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/NoCommentSourceRangeComputer.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-
-public class NoCommentSourceRangeComputer extends TargetSourceRangeComputer {
- public SourceRange computeSourceRange(ASTNode node) {
- return new SourceRange(node.getStartPosition(), node.getLength());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameFinder.java
deleted file mode 100644
index 635a209d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameFinder.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.regex.Pattern;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.search.core.text.TextSearchEngine;
-import org.eclipse.search.core.text.TextSearchMatchAccess;
-import org.eclipse.search.core.text.TextSearchRequestor;
-import org.eclipse.search.core.text.TextSearchScope;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.ui.util.PatternConstructor;
-
-public class QualifiedNameFinder {
-
- private static final GroupCategorySet QUALIFIED_NAMES= new GroupCategorySet(
- new GroupCategory("org.eclipse.wst.jsdt.internal.corext.qualifiedNames", //$NON-NLS-1$
- RefactoringCoreMessages.QualifiedNameFinder_qualifiedNames_name,
- RefactoringCoreMessages.QualifiedNameFinder_qualifiedNames_description));
-
- private static class ResultCollector extends TextSearchRequestor {
-
- private String fNewValue;
- private QualifiedNameSearchResult fResult;
-
- public ResultCollector(QualifiedNameSearchResult result, String newValue) {
- fResult= result;
- fNewValue= newValue;
- }
-
- public boolean acceptFile(IFile file) throws CoreException {
- IJavaScriptElement element= JavaScriptCore.create(file);
- if ((element != null && element.exists()))
- return false;
-
- // Only touch text files (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=114153 ):
- if (! FileBuffers.getTextFileBufferManager().isTextFileLocation(file.getFullPath(), false))
- return false;
-
- IPath path= file.getProjectRelativePath();
- String segment= path.segment(0);
- if (segment != null && (segment.startsWith(".refactorings") || segment.startsWith(".deprecations"))) //$NON-NLS-1$ //$NON-NLS-2$
- return false;
-
- return true;
- }
-
- public boolean acceptPatternMatch(TextSearchMatchAccess matchAccess) throws CoreException {
- int start= matchAccess.getMatchOffset();
- int length= matchAccess.getMatchLength();
-
- // skip embedded FQNs (bug 130764):
- if (start > 0) {
- char before= matchAccess.getFileContentChar(start - 1);
- if (before == '.' || Character.isJavaIdentifierPart(before))
- return true;
- }
- int fileContentLength= matchAccess.getFileContentLength();
- int end= start + length;
- if (end < fileContentLength) {
- char after= matchAccess.getFileContentChar(end);
- if (Character.isJavaIdentifierPart(after))
- return true;
- }
-
- IFile file= matchAccess.getFile();
- TextChange change= fResult.getChange(file);
- TextChangeCompatibility.addTextEdit(
- change,
- RefactoringCoreMessages.QualifiedNameFinder_update_name,
- new ReplaceEdit(start, length, fNewValue), QUALIFIED_NAMES);
-
- return true;
- }
- }
-
- public QualifiedNameFinder() {
- }
-
- public static void process(QualifiedNameSearchResult result, String pattern, String newValue, String filePatterns, IProject root, IProgressMonitor monitor) {
- Assert.isNotNull(pattern);
- Assert.isNotNull(newValue);
- Assert.isNotNull(root);
-
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- if (filePatterns == null || filePatterns.length() == 0) {
- // Eat progress.
- monitor.beginTask("", 1); //$NON-NLS-1$
- monitor.worked(1);
- return;
- }
-
- ResultCollector collector= new ResultCollector(result, newValue);
- TextSearchEngine engine= TextSearchEngine.create();
- Pattern searchPattern= PatternConstructor.createPattern(pattern, true, false);
-
- engine.search(createScope(filePatterns, root), collector, searchPattern, monitor);
- }
-
- private static TextSearchScope createScope(String filePatterns, IProject root) {
- HashSet res= new HashSet();
- res.add(root);
- addReferencingProjects(root, res);
- IResource[] resArr= (IResource[]) res.toArray(new IResource[res.size()]);
- Pattern filePattern= getFilePattern(filePatterns);
-
- return TextSearchScope.newSearchScope(resArr, filePattern, false);
- }
-
- private static Pattern getFilePattern(String filePatterns) {
- StringTokenizer tokenizer= new StringTokenizer(filePatterns, ","); //$NON-NLS-1$
- String[] filePatternArray= new String[tokenizer.countTokens()];
- int i= 0;
- while (tokenizer.hasMoreTokens()) {
- filePatternArray[i++]= tokenizer.nextToken().trim();
- }
- return PatternConstructor.createPattern(filePatternArray, true, false);
- }
-
- private static void addReferencingProjects(IProject root, Set res) {
- IProject[] projects= root.getReferencingProjects();
- for (int i= 0; i < projects.length; i++) {
- IProject project= projects[i];
- if (res.add(project)) {
- addReferencingProjects(project, res);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameSearchResult.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameSearchResult.java
deleted file mode 100644
index 3e962bca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/QualifiedNameSearchResult.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-
-public class QualifiedNameSearchResult {
-
- private Map fChanges;
-
- public QualifiedNameSearchResult() {
- fChanges= new HashMap();
- }
-
- public TextChange getChange(IFile file) {
- TextChange result= (TextChange)fChanges.get(file);
- if (result == null) {
- result= new TextFileChange(file.getName(), file);
- fChanges.put(file, result);
- }
- return result;
- }
-
- public TextChange[] getAllChanges() {
- Collection values= fChanges.values();
- return (TextChange[])values.toArray(new TextChange[values.size()]);
- }
-
- public IFile[] getAllFiles() {
- Set keys= fChanges.keySet();
- return (IFile[])keys.toArray(new IFile[keys.size()]);
- }
-
- public Change getSingleChange(IFile[] alreadyTouchedFiles) {
- Collection values= fChanges.values();
- if (values.size() == 0)
- return null;
-
- CompositeChange result= new CompositeChange(RefactoringCoreMessages.QualifiedNameSearchResult_change_name);
- result.markAsSynthetic();
- List files= Arrays.asList(alreadyTouchedFiles);
- for (Iterator iter= values.iterator(); iter.hasNext();) {
- TextFileChange change= (TextFileChange)iter.next();
- if (!files.contains(change.getFile())) {
- result.add(change);
- }
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringASTParser.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringASTParser.java
deleted file mode 100644
index 65a09c43..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringASTParser.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-public class RefactoringASTParser {
-
- private ASTParser fParser;
-
- public RefactoringASTParser(int level) {
- fParser= ASTParser.newParser(level);
- }
-
- public JavaScriptUnit parse(ITypeRoot typeRoot, boolean resolveBindings) {
- return parse(typeRoot, resolveBindings, null);
- }
-
- public JavaScriptUnit parse(ITypeRoot typeRoot, boolean resolveBindings, IProgressMonitor pm) {
- return parse(typeRoot, null, resolveBindings, pm);
- }
-
- public JavaScriptUnit parse(ITypeRoot typeRoot, WorkingCopyOwner owner, boolean resolveBindings, IProgressMonitor pm) {
- return parse(typeRoot, owner, resolveBindings, false, false, pm);
- }
-
- public JavaScriptUnit parse(ITypeRoot typeRoot, WorkingCopyOwner owner, boolean resolveBindings, boolean statementsRecovery, boolean bindingsRecovery, IProgressMonitor pm) {
- fParser.setResolveBindings(resolveBindings);
- fParser.setStatementsRecovery(statementsRecovery);
- fParser.setBindingsRecovery(bindingsRecovery);
- fParser.setSource(typeRoot);
- if (owner != null)
- fParser.setWorkingCopyOwner(owner);
- fParser.setCompilerOptions(getCompilerOptions(typeRoot));
- JavaScriptUnit result= (JavaScriptUnit) fParser.createAST(pm);
- return result;
- }
-
- /**
- * @param newCuSource the source
- * @param originalCu the compilation unit to get the name and project from
- * @param resolveBindings whether bindings are to be resolved
- * @param statementsRecovery whether statements recovery should be enabled
- * @param pm an {@link IProgressMonitor}, or <code>null</code>
- * @return the parsed JavaScriptUnit
- */
- public JavaScriptUnit parse(String newCuSource, IJavaScriptUnit originalCu, boolean resolveBindings, boolean statementsRecovery, IProgressMonitor pm) {
- fParser.setResolveBindings(resolveBindings);
- fParser.setStatementsRecovery(statementsRecovery);
- fParser.setSource(newCuSource.toCharArray());
- fParser.setUnitName(originalCu.getElementName());
- fParser.setProject(originalCu.getJavaScriptProject());
- fParser.setCompilerOptions(getCompilerOptions(originalCu));
- JavaScriptUnit newCUNode= (JavaScriptUnit) fParser.createAST(pm);
- return newCUNode;
- }
-
- /**
- * @param newCfSource the source
- * @param originalCf the class file to get the name and project from
- * @param resolveBindings whether bindings are to be resolved
- * @param statementsRecovery whether statements recovery should be enabled
- * @param pm an {@link IProgressMonitor}, or <code>null</code>
- * @return the parsed JavaScriptUnit
- */
- public JavaScriptUnit parse(String newCfSource, IClassFile originalCf, boolean resolveBindings, boolean statementsRecovery, IProgressMonitor pm) {
- fParser.setResolveBindings(resolveBindings);
- fParser.setStatementsRecovery(statementsRecovery);
- fParser.setSource(newCfSource.toCharArray());
- String cfName= originalCf.getElementName();
- fParser.setUnitName(cfName.substring(0, cfName.length() - 6) + JavaModelUtil.DEFAULT_CU_SUFFIX);
- fParser.setProject(originalCf.getJavaScriptProject());
- fParser.setCompilerOptions(getCompilerOptions(originalCf));
- JavaScriptUnit newCUNode= (JavaScriptUnit) fParser.createAST(pm);
- return newCUNode;
- }
-
- /**
- * Tries to get the shared AST from the ASTProvider.
- * If the shared AST is not available, parses the type root with a
- * RefactoringASTParser that uses settings similar to the ASTProvider.
- *
- * @param typeRoot the type root
- * @param resolveBindings TODO
- * @param pm an {@link IProgressMonitor}, or <code>null</code>
- * @return the parsed JavaScriptUnit
- */
- public static JavaScriptUnit parseWithASTProvider(ITypeRoot typeRoot, boolean resolveBindings, IProgressMonitor pm) {
- JavaScriptUnit cuNode= ASTProvider.getASTProvider().getAST(typeRoot, ASTProvider.WAIT_ACTIVE_ONLY, pm);
- if (cuNode != null) {
- return cuNode;
- } else {
- return new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(typeRoot, null, resolveBindings, ASTProvider.SHARED_AST_STATEMENT_RECOVERY, ASTProvider.SHARED_BINDING_RECOVERY, pm);
- }
- }
-
- public static IJavaScriptUnit getCompilationUnit(ASTNode node) {
- ASTNode root= node.getRoot();
- if (root instanceof JavaScriptUnit) {
- IJavaScriptElement cu= ((JavaScriptUnit) root).getJavaElement();
- if (cu instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) cu;
- }
- return null;
- }
-
- public static Map getCompilerOptions(IJavaScriptElement element) {
- IJavaScriptProject project= element.getJavaScriptProject();
- Map options= project.getOptions(true);
- // turn all errors and warnings into ignore. The customizable set of compiler
- // options only contains additional Eclipse options. The standard JDK compiler
- // options can't be changed anyway.
- for (Iterator iter= options.keySet().iterator(); iter.hasNext();) {
- String key= (String)iter.next();
- String value= (String)options.get(key);
- if ("error".equals(value) || "warning".equals(value)) { //$NON-NLS-1$//$NON-NLS-2$
- // System.out.println("Ignoring - " + key);
- options.put(key, "ignore"); //$NON-NLS-1$
- }
- }
- options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
- return options;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringFileBuffers.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringFileBuffers.java
deleted file mode 100644
index 1be73c24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/RefactoringFileBuffers.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-/**
- * Helper methods to deal with file buffers in refactorings.
- */
-public final class RefactoringFileBuffers {
-
- /**
- * Connects to and acquires a text file buffer for the specified compilation unit.
- * <p>
- * All text file buffers acquired by a call to {@link RefactoringFileBuffers#acquire(IJavaScriptUnit)}
- * must be released using {@link RefactoringFileBuffers#release(IJavaScriptUnit)}.
- * </p>
- *
- * @param unit the compilation unit to acquire a text file buffer for
- * @return the text file buffer, or <code>null</code> if no buffer could be acquired
- * @throws CoreException if no buffer could be acquired
- */
- public static ITextFileBuffer acquire(final IJavaScriptUnit unit) throws CoreException {
- Assert.isNotNull(unit);
- final IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE) {
- final IPath path= resource.getFullPath();
- FileBuffers.getTextFileBufferManager().connect(path, LocationKind.IFILE, new NullProgressMonitor());
- return FileBuffers.getTextFileBufferManager().getTextFileBuffer(path, LocationKind.IFILE);
- }
- return null;
- }
-
- /**
- * Returns the text file buffer for the specified compilation unit.
- *
- * @param unit the compilation unit whose text file buffer to retrieve
- * @return the associated text file buffer, or <code>null</code> if no text file buffer is managed for the compilation unit
- */
- public static ITextFileBuffer getTextFileBuffer(final IJavaScriptUnit unit) {
- Assert.isNotNull(unit);
- final IResource resource= unit.getResource();
- if (resource == null || resource.getType() != IResource.FILE)
- return null;
- return FileBuffers.getTextFileBufferManager().getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE);
- }
-
- /**
- * Releases the text file buffer associated with the compilation unit.
- *
- * @param unit the compilation unit whose text file buffer has to be released
- * @throws CoreException if the buffer could not be successfully released
- */
- public static void release(final IJavaScriptUnit unit) throws CoreException {
- Assert.isNotNull(unit);
- final IResource resource= unit.getResource();
- if (resource != null && resource.getType() == IResource.FILE)
- FileBuffers.getTextFileBufferManager().disconnect(resource.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());
- }
-
- private RefactoringFileBuffers() {
- // Not for instantiation
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/ResourceUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/ResourceUtil.java
deleted file mode 100644
index b45a49c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/ResourceUtil.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IOpenable;
-
-
-public class ResourceUtil {
-
- private ResourceUtil(){
- }
-
- public static IFile[] getFiles(IJavaScriptUnit[] cus) {
- List files= new ArrayList(cus.length);
- for (int i= 0; i < cus.length; i++) {
- IResource resource= cus[i].getResource();
- if (resource != null && resource.getType() == IResource.FILE)
- files.add(resource);
- }
- return (IFile[]) files.toArray(new IFile[files.size()]);
- }
-
- public static IFile getFile(IJavaScriptUnit cu) {
- IResource resource= cu.getResource();
- if (resource != null && resource.getType() == IResource.FILE)
- return (IFile)resource;
- else
- return null;
- }
-
- //----- other ------------------------------
-
- public static IResource getResource(Object o){
- if (o instanceof IResource)
- return (IResource)o;
- if (o instanceof IJavaScriptElement)
- return getResource((IJavaScriptElement)o);
- return null;
- }
-
- private static IResource getResource(IJavaScriptElement element){
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT)
- return ((IJavaScriptUnit) element).getResource();
- else if (element instanceof IOpenable)
- return element.getResource();
- else
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/SelectionAwareSourceRangeComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/SelectionAwareSourceRangeComputer.java
deleted file mode 100644
index 31d9a11c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/SelectionAwareSourceRangeComputer.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-
-public class SelectionAwareSourceRangeComputer extends TargetSourceRangeComputer {
-
- private ASTNode[] fSelectedNodes;
- private IDocument fDocument;
- private int fSelectionStart;
- private int fSelectionLength;
-
- private Map/*<ASTNode, SourceRange>*/ fRanges;
-
- public SelectionAwareSourceRangeComputer(ASTNode[] selectedNodes, IDocument document, int selectionStart, int selectionLength) throws BadLocationException, CoreException {
- fSelectedNodes= selectedNodes;
- fDocument= document;
- fSelectionStart= selectionStart;
- fSelectionLength= selectionLength;
- }
-
- public SourceRange computeSourceRange(ASTNode node) {
- try {
- if (fRanges == null)
- initializeRanges();
- SourceRange result= (SourceRange)fRanges.get(node);
- if (result != null)
- return result;
- return super.computeSourceRange(node);
- } catch (BadLocationException e) {
- // fall back to standard implementation
- fRanges= new HashMap();
- } catch (CoreException e) {
- // fall back to standard implementation
- fRanges= new HashMap();
- }
- return super.computeSourceRange(node);
- }
-
- private void initializeRanges() throws BadLocationException, CoreException {
- fRanges= new HashMap();
- if (fSelectedNodes.length == 0)
- return;
-
- fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
- int last= fSelectedNodes.length - 1;
- fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));
-
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- String documentPortionToScan= fDocument.get(fSelectionStart, fSelectionLength);
- scanner.setSource(documentPortionToScan.toCharArray());
- TokenScanner tokenizer= new TokenScanner(scanner);
- int pos= tokenizer.getNextStartOffset(0, false);
-
- ASTNode currentNode= fSelectedNodes[0];
- int newStart= Math.min(fSelectionStart + pos, currentNode.getStartPosition());
- SourceRange range= (SourceRange)fRanges.get(currentNode);
- fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));
-
- currentNode= fSelectedNodes[last];
- int scannerStart= currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
- tokenizer.setOffset(scannerStart);
- pos= scannerStart;
- int token= -1;
- try {
- while (true) {
- token= tokenizer.readNext(false);
- pos= tokenizer.getCurrentEndOffset();
- }
- } catch (CoreException e) {
- }
- if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
- int index= pos - 1;
- while(index >= 0 && IndentManipulation.isLineDelimiterChar(documentPortionToScan.charAt(index))) {
- pos--;
- index--;
- }
- }
-
- int newEnd= Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
- range= (SourceRange)fRanges.get(currentNode);
- fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/StatementAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/StatementAnalyzer.java
deleted file mode 100644
index d2aff015..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/StatementAnalyzer.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-
-/**
- * Analyzer to check if a selection covers a valid set of statements of an abstract syntax
- * tree. The selection is valid iff
- * <ul>
- * <li>it does not start or end in the middle of a comment.</li>
- * <li>no extract characters except the empty statement ";" is included in the selection.</li>
- * </ul>
- */
-public class StatementAnalyzer extends SelectionAnalyzer {
-
- protected IJavaScriptUnit fCUnit;
- private TokenScanner fScanner;
- private RefactoringStatus fStatus;
-
- public StatementAnalyzer(IJavaScriptUnit cunit, Selection selection, boolean traverseSelectedNode) throws JavaScriptModelException {
- super(selection, traverseSelectedNode);
- Assert.isNotNull(cunit);
- fCUnit= cunit;
- fStatus= new RefactoringStatus();
- fScanner= new TokenScanner(fCUnit);
- }
-
- protected void checkSelectedNodes() {
- ASTNode[] nodes= getSelectedNodes();
- if (nodes.length == 0)
- return;
-
- ASTNode node= nodes[0];
- int selectionOffset= getSelection().getOffset();
- try {
- int pos= fScanner.getNextStartOffset(selectionOffset, true);
- if (pos == node.getStartPosition()) {
- int lastNodeEnd= ASTNodes.getExclusiveEnd(nodes[nodes.length - 1]);
-
- pos= fScanner.getNextStartOffset(lastNodeEnd, true);
- int selectionEnd= getSelection().getInclusiveEnd();
- if (pos <= selectionEnd) {
- ISourceRange range= new SourceRange(lastNodeEnd, pos - lastNodeEnd);
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_end_of_selection, JavaStatusContext.create(fCUnit, range));
- }
- return; // success
- }
- } catch (CoreException e) {
- // fall through
- }
- ISourceRange range= new SourceRange(selectionOffset, node.getStartPosition() - selectionOffset + 1);
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_beginning_of_selection, JavaStatusContext.create(fCUnit, range));
- }
-
- public RefactoringStatus getStatus() {
- return fStatus;
- }
-
- protected IJavaScriptUnit getCompilationUnit() {
- return fCUnit;
- }
-
- protected TokenScanner getTokenScanner() {
- return fScanner;
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(JavaScriptUnit node) {
- if (!hasSelectedNodes()) {
- super.endVisit(node);
- return;
- }
- ASTNode selectedNode= getFirstSelectedNode();
- Selection selection= getSelection();
- if (node != selectedNode) {
- ASTNode parent= selectedNode.getParent();
- fStatus.merge(CommentAnalyzer.perform(selection, fScanner.getScanner(), parent.getStartPosition(), parent.getLength()));
- }
- if (!fStatus.hasFatalError())
- checkSelectedNodes();
- super.endVisit(node);
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(DoStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- if (contains(selectedNodes, node.getBody()) && contains(selectedNodes, node.getExpression())) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_do_body_expression);
- }
- }
- super.endVisit(node);
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(ForStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- boolean containsExpression= contains(selectedNodes, node.getExpression());
- boolean containsUpdaters= contains(selectedNodes, node.updaters());
- if (contains(selectedNodes, node.initializers()) && containsExpression) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_initializer_expression);
- } else if (containsExpression && containsUpdaters) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_expression_updater);
- } else if (containsUpdaters && contains(selectedNodes, node.getBody())) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_updater_body);
- }
- }
- super.endVisit(node);
- }
- public void endVisit(ForInStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- boolean containsVar= contains(selectedNodes, node.getIterationVariable());
- boolean containsCollection= contains(selectedNodes, node.getCollection());
- if (containsVar && containsCollection) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_expression_updater);
- } else if (containsCollection && contains(selectedNodes, node.getBody())) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_updater_body);
- }
- }
- super.endVisit(node);
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(SwitchStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- List cases= getSwitchCases(node);
- for (int i= 0; i < selectedNodes.length; i++) {
- ASTNode topNode= selectedNodes[i];
- if (cases.contains(topNode)) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_switch_statement);
- break;
- }
- }
- }
- super.endVisit(node);
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(TryStatement node) {
- ASTNode firstSelectedNode= getFirstSelectedNode();
- if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
- if (firstSelectedNode == node.getBody() || firstSelectedNode == node.getFinally()) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_try_statement);
- } else {
- List catchClauses= node.catchClauses();
- for (Iterator iterator= catchClauses.iterator(); iterator.hasNext();) {
- CatchClause element= (CatchClause)iterator.next();
- if (element == firstSelectedNode || element.getBody() == firstSelectedNode) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_try_statement);
- } else if (element.getException() == firstSelectedNode) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_catch_argument);
- }
- }
- }
- }
- super.endVisit(node);
- }
-
- /* (non-Javadoc)
- * Method declared in ASTVisitor
- */
- public void endVisit(WhileStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- if (contains(selectedNodes, node.getExpression()) && contains(selectedNodes, node.getBody())) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_while_expression_body);
- }
- }
- super.endVisit(node);
- }
-
- public void endVisit(WithStatement node) {
- ASTNode[] selectedNodes= getSelectedNodes();
- if (doAfterValidation(node, selectedNodes)) {
- if (contains(selectedNodes, node.getExpression()) && contains(selectedNodes, node.getBody())) {
- invalidSelection(RefactoringCoreMessages.StatementAnalyzer_while_expression_body);
- }
- }
- super.endVisit(node);
- }
-
-
- private boolean doAfterValidation(ASTNode node, ASTNode[] selectedNodes) {
- return selectedNodes.length > 0 && node == selectedNodes[0].getParent() && getSelection().getEndVisitSelectionMode(node) == Selection.AFTER;
- }
-
- protected void invalidSelection(String message) {
- fStatus.addFatalError(message);
- reset();
- }
-
- protected void invalidSelection(String message, RefactoringStatusContext context) {
- fStatus.addFatalError(message, context);
- reset();
- }
-
- private static List getSwitchCases(SwitchStatement node) {
- List result= new ArrayList();
- for (Iterator iter= node.statements().iterator(); iter.hasNext(); ) {
- Object element= iter.next();
- if (element instanceof SwitchCase)
- result.add(element);
- }
- return result;
- }
-
- protected static boolean contains(ASTNode[] nodes, ASTNode node) {
- for (int i = 0; i < nodes.length; i++) {
- if (nodes[i] == node)
- return true;
- }
- return false;
- }
-
- protected static boolean contains(ASTNode[] nodes, List list) {
- for (int i = 0; i < nodes.length; i++) {
- if (list.contains(nodes[i]))
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextChangeManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextChangeManager.java
deleted file mode 100644
index a8115d44..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextChangeManager.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-
-/**
- * A <code>TextChangeManager</code> manages associations between <code>IJavaScriptUnit</code>
- * or <code>IFile</code> and <code>TextChange</code> objects.
- */
-public class TextChangeManager {
-
- private Map/*<IJavaScriptUnit, TextChange>*/ fMap= new HashMap(10);
-
- private final boolean fKeepExecutedTextEdits;
-
- public TextChangeManager() {
- this(false);
- }
-
- public TextChangeManager(boolean keepExecutedTextEdits) {
- fKeepExecutedTextEdits= keepExecutedTextEdits;
- }
-
- /**
- * Adds an association between the given compilation unit and the passed
- * change to this manager.
- *
- * @param cu the compilation unit (key)
- * @param change the change associated with the compilation unit
- */
- public void manage(IJavaScriptUnit cu, TextChange change) {
- fMap.put(cu, change);
- }
-
- /**
- * Returns the <code>TextChange</code> associated with the given compilation unit.
- * If the manager does not already manage an association it creates a one.
- *
- * @param cu the compilation unit for which the text buffer change is requested
- * @return the text change associated with the given compilation unit.
- */
- public TextChange get(IJavaScriptUnit cu) {
- TextChange result= (TextChange)fMap.get(cu);
- if (result == null) {
- result= new CompilationUnitChange(cu.getElementName(), cu);
- result.setKeepPreviewEdits(fKeepExecutedTextEdits);
- fMap.put(cu, result);
- }
- return result;
- }
-
- /**
- * Removes the <tt>TextChange</tt> managed under the given key
- * <code>unit<code>.
- *
- * @param unit the key determining the <tt>TextChange</tt> to be removed.
- * @return the removed <tt>TextChange</tt>.
- */
- public TextChange remove(IJavaScriptUnit unit) {
- return (TextChange)fMap.remove(unit);
- }
-
- /**
- * Returns all text changes managed by this instance.
- *
- * @return all text changes managed by this instance
- */
- public TextChange[] getAllChanges(){
- Set cuSet= fMap.keySet();
- IJavaScriptUnit[] cus= (IJavaScriptUnit[]) cuSet.toArray(new IJavaScriptUnit[cuSet.size()]);
- // sort by cu name:
- Arrays.sort(cus, new Comparator() {
- public int compare(Object o1, Object o2) {
- String name1= ((IJavaScriptUnit) o1).getElementName();
- String name2= ((IJavaScriptUnit) o2).getElementName();
- return name1.compareTo(name2);
- }
- });
-
- TextChange[] textChanges= new TextChange[cus.length];
- for (int i= 0; i < cus.length; i++) {
- textChanges[i]= (TextChange) fMap.get(cus[i]);
- }
- return textChanges;
- }
-
- /**
- * Returns all compilation units managed by this instance.
- *
- * @return all compilation units managed by this instance
- */
- public IJavaScriptUnit[] getAllCompilationUnits(){
- return (IJavaScriptUnit[]) fMap.keySet().toArray(new IJavaScriptUnit[fMap.keySet().size()]);
- }
-
- /**
- * Clears all associations between resources and text changes.
- */
- public void clear() {
- fMap.clear();
- }
-
- /**
- * Returns if any text changes are managed for the specified compilation unit.
- *
- * @param cu the compilation unit
- * @return <code>true</code> if any text changes are managed for the specified compilation unit and <code>false</code> otherwise
- */
- public boolean containsChangesIn(IJavaScriptUnit cu){
- return fMap.containsKey(cu);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextEditBasedChangeManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextEditBasedChangeManager.java
deleted file mode 100644
index a1eda6f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TextEditBasedChangeManager.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-
-/**
- * A <code>TextChangeManager</code> manages associations between <code>IJavaScriptUnit</code>
- * or <code>IFile</code> and <code>TextEditBasedChange</code> objects.
- */
-public class TextEditBasedChangeManager {
-
- private Map/*<IJavaScriptUnit, TextEditBasedChange>*/ fMap= new HashMap(10);
-
- private final boolean fKeepExecutedTextEdits;
-
- public TextEditBasedChangeManager() {
- this(false);
- }
-
- public TextEditBasedChangeManager(boolean keepExecutedTextEdits) {
- fKeepExecutedTextEdits= keepExecutedTextEdits;
- }
-
- /**
- * Adds an association between the given compilation unit and the passed
- * change to this manager.
- *
- * @param cu the compilation unit (key)
- * @param change the change associated with the compilation unit
- */
- public void manage(IJavaScriptUnit cu, TextEditBasedChange change) {
- fMap.put(cu, change);
- }
-
- /**
- * Returns the <code>TextEditBasedChange</code> associated with the given compilation unit.
- * If the manager does not already manage an association it creates a one.
- *
- * @param cu the compilation unit for which the text buffer change is requested
- * @return the text change associated with the given compilation unit.
- */
- public TextEditBasedChange get(IJavaScriptUnit cu) {
- TextEditBasedChange result= (TextEditBasedChange)fMap.get(cu);
- if (result == null) {
- result= new CompilationUnitChange(cu.getElementName(), cu);
- result.setKeepPreviewEdits(fKeepExecutedTextEdits);
- fMap.put(cu, result);
- }
- return result;
- }
-
- /**
- * Removes the <tt>TextEditBasedChange</tt> managed under the given key
- * <code>unit<code>.
- *
- * @param unit the key determining the <tt>TextEditBasedChange</tt> to be removed.
- * @return the removed <tt>TextEditBasedChange</tt>.
- */
- public TextEditBasedChange remove(IJavaScriptUnit unit) {
- return (TextEditBasedChange)fMap.remove(unit);
- }
-
- /**
- * Returns all text changes managed by this instance.
- *
- * @return all text changes managed by this instance
- */
- public TextEditBasedChange[] getAllChanges(){
- Set cuSet= fMap.keySet();
- IJavaScriptUnit[] cus= (IJavaScriptUnit[]) cuSet.toArray(new IJavaScriptUnit[cuSet.size()]);
- // sort by cu name:
- Arrays.sort(cus, new Comparator() {
- public int compare(Object o1, Object o2) {
- String name1= ((IJavaScriptUnit) o1).getElementName();
- String name2= ((IJavaScriptUnit) o2).getElementName();
- return name1.compareTo(name2);
- }
- });
-
- TextEditBasedChange[] textChanges= new TextEditBasedChange[cus.length];
- for (int i= 0; i < cus.length; i++) {
- textChanges[i]= (TextEditBasedChange) fMap.get(cus[i]);
- }
- return textChanges;
- }
-
- /**
- * Returns all compilation units managed by this instance.
- *
- * @return all compilation units managed by this instance
- */
- public IJavaScriptUnit[] getAllCompilationUnits(){
- return (IJavaScriptUnit[]) fMap.keySet().toArray(new IJavaScriptUnit[fMap.keySet().size()]);
- }
-
- /**
- * Clears all associations between resources and text changes.
- */
- public void clear() {
- fMap.clear();
- }
-
- /**
- * Returns if any text changes are managed for the specified compilation unit.
- *
- * @param cu the compilation unit
- * @return <code>true</code> if any text changes are managed for the specified compilation unit and <code>false</code> otherwise
- */
- public boolean containsChangesIn(IJavaScriptUnit cu){
- return fMap.containsKey(cu);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TightSourceRangeComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TightSourceRangeComputer.java
deleted file mode 100644
index cafd4c56..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/util/TightSourceRangeComputer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.refactoring.util;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.TargetSourceRangeComputer;
-
-public class TightSourceRangeComputer extends TargetSourceRangeComputer {
- private HashSet/*<ASTNode>*/ fTightSourceRangeNodes= new HashSet();
-
- public void addTightSourceNode(ASTNode reference) {
- fTightSourceRangeNodes.add(reference);
-
- List properties= reference.structuralPropertiesForType();
- for (Iterator iterator= properties.iterator(); iterator.hasNext();) {
- StructuralPropertyDescriptor descriptor= (StructuralPropertyDescriptor)iterator.next();
- if (descriptor.isChildProperty()) {
- ASTNode child= (ASTNode)reference.getStructuralProperty(descriptor);
- if (isExtending(child, reference)) {
- addTightSourceNode(child);
- }
- } else if (descriptor.isChildListProperty()) {
- List childs= (List)reference.getStructuralProperty(descriptor);
- for (Iterator iterator2= childs.iterator(); iterator2.hasNext();) {
- ASTNode child= (ASTNode)iterator2.next();
- if (isExtending(child, reference)) {
- addTightSourceNode(child);
- }
- }
- }
- }
- }
-
- public SourceRange computeSourceRange(ASTNode node) {
- if (fTightSourceRangeNodes.contains(node)) {
- return new TargetSourceRangeComputer.SourceRange(node.getStartPosition(), node.getLength());
- } else {
- return super.computeSourceRange(node); // see bug 85850
- }
- }
-
- private boolean isExtending(ASTNode child, ASTNode parent) {
- SourceRange extendedRange= super.computeSourceRange(child);
-
- int parentStart= parent.getStartPosition();
- int extendedStart= extendedRange.getStartPosition();
- if (parentStart > extendedStart)
- return true;
-
- int parentEnd= parentStart + parent.getLength();
- int extendedEnd= extendedStart + extendedRange.getLength();
- if (parentEnd < extendedEnd)
- return true;
-
- return false;
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContext.java
deleted file mode 100644
index 6028534b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContext.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateTranslator;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class CodeTemplateContext extends TemplateContext {
-
- private String fLineDelimiter;
- private IJavaScriptProject fProject;
-
- public CodeTemplateContext(String contextTypeName, IJavaScriptProject project, String lineDelim) {
- super(JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry().getContextType(contextTypeName));
- fLineDelimiter= lineDelim;
- fProject= project;
- }
-
- public IJavaScriptProject getJavaProject() {
- return fProject;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.TemplateContext#evaluate(org.eclipse.wst.jsdt.internal.corext.template.Template)
- */
- public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
- // test that all variables are defined
- Iterator iterator= getContextType().resolvers();
- while (iterator.hasNext()) {
- TemplateVariableResolver var= (TemplateVariableResolver) iterator.next();
- if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) {
- Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- if (!canEvaluate(template))
- return null;
-
- String pattern= changeLineDelimiter(template.getPattern(), fLineDelimiter);
-
- TemplateTranslator translator= new TemplateTranslator();
- TemplateBuffer buffer= translator.translate(pattern);
- getContextType().resolve(buffer, this);
- return buffer;
- }
-
- private static String changeLineDelimiter(String code, String lineDelim) {
- try {
- ILineTracker tracker= new DefaultLineTracker();
- tracker.set(code);
- int nLines= tracker.getNumberOfLines();
- if (nLines == 1) {
- return code;
- }
-
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < nLines; i++) {
- if (i != 0) {
- buf.append(lineDelim);
- }
- IRegion region = tracker.getLineInformation(i);
- String line= code.substring(region.getOffset(), region.getOffset() + region.getLength());
- buf.append(line);
- }
- return buf.toString();
- } catch (BadLocationException e) {
- // can not happen
- return code;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.template.TemplateContext#canEvaluate(org.eclipse.wst.jsdt.internal.corext.template.Template)
- */
- public boolean canEvaluate(Template template) {
- return true;
- }
-
- public void setCompilationUnitVariables(IJavaScriptUnit cu) {
- setVariable(CodeTemplateContextType.FILENAME, cu.getElementName());
- setVariable(CodeTemplateContextType.PACKAGENAME, cu.getParent().getElementName());
- setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaScriptProject().getElementName());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java
deleted file mode 100644
index 58225f15..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.ArrayList;
-
-import org.eclipse.jface.text.templates.ContextTypeRegistry;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- */
-public class CodeTemplateContextType extends TemplateContextType {
-
- /* context types */
- public static final String CATCHBLOCK_CONTEXTTYPE= "org.eclipse.jsdt.catchblock_context"; //$NON-NLS-1$
- public static final String METHODBODY_CONTEXTTYPE= "org.eclipse.jsdt.methodbody_context"; //$NON-NLS-1$
- public static final String CONSTRUCTORBODY_CONTEXTTYPE= "org.eclipse.jsdt.constructorbody_context"; //$NON-NLS-1$
- public static final String GETTERBODY_CONTEXTTYPE= "org.eclipse.jsdt.getterbody_context"; //$NON-NLS-1$
- public static final String SETTERBODY_CONTEXTTYPE= "org.eclipse.jsdt.setterbody_context"; //$NON-NLS-1$
- public static final String NEWTYPE_CONTEXTTYPE= "org.eclipse.jsdt.newtype_context"; //$NON-NLS-1$
- public static final String CLASSBODY_CONTEXTTYPE= "org.eclipse.jsdt.classbody_context"; //$NON-NLS-1$
- public static final String INTERFACEBODY_CONTEXTTYPE= "org.eclipse.jsdt.interfacebody_context"; //$NON-NLS-1$
- public static final String ENUMBODY_CONTEXTTYPE= "org.eclipse.jsdt.enumbody_context"; //$NON-NLS-1$
- public static final String ANNOTATIONBODY_CONTEXTTYPE= "org.eclipse.jsdt.annotationbody_context"; //$NON-NLS-1$
- public static final String FILECOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.filecomment_context"; //$NON-NLS-1$
- public static final String TYPECOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.typecomment_context"; //$NON-NLS-1$
- public static final String FIELDCOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.fieldcomment_context"; //$NON-NLS-1$
- public static final String METHODCOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.methodcomment_context"; //$NON-NLS-1$
- public static final String CONSTRUCTORCOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.constructorcomment_context"; //$NON-NLS-1$
- public static final String OVERRIDECOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.overridecomment_context"; //$NON-NLS-1$
- public static final String DELEGATECOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.delegatecomment_context"; //$NON-NLS-1$
- public static final String GETTERCOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.gettercomment_context"; //$NON-NLS-1$
- public static final String SETTERCOMMENT_CONTEXTTYPE= "org.eclipse.jsdt.settercomment_context"; //$NON-NLS-1$
-
- /* templates */
-
- private static final String CODETEMPLATES_PREFIX= "org.eclipse.wst.jsdt.ui.text.codetemplates."; //$NON-NLS-1$
- public static final String COMMENT_SUFFIX= "comment"; //$NON-NLS-1$
-
- public static final String CATCHBLOCK_ID= CODETEMPLATES_PREFIX + "catchblock"; //$NON-NLS-1$
- public static final String METHODSTUB_ID= CODETEMPLATES_PREFIX + "methodbody"; //$NON-NLS-1$
- public static final String NEWTYPE_ID= CODETEMPLATES_PREFIX + "newtype"; //$NON-NLS-1$
- public static final String CONSTRUCTORSTUB_ID= CODETEMPLATES_PREFIX + "constructorbody"; //$NON-NLS-1$
- public static final String GETTERSTUB_ID= CODETEMPLATES_PREFIX + "getterbody"; //$NON-NLS-1$
- public static final String SETTERSTUB_ID= CODETEMPLATES_PREFIX + "setterbody"; //$NON-NLS-1$
- public static final String FILECOMMENT_ID= CODETEMPLATES_PREFIX + "file" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String TYPECOMMENT_ID= CODETEMPLATES_PREFIX + "type" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String CLASSBODY_ID= CODETEMPLATES_PREFIX + "classbody"; //$NON-NLS-1$
- public static final String FIELDCOMMENT_ID= CODETEMPLATES_PREFIX + "field" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String METHODCOMMENT_ID= CODETEMPLATES_PREFIX + "method" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String CONSTRUCTORCOMMENT_ID= CODETEMPLATES_PREFIX + "constructor" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String OVERRIDECOMMENT_ID= CODETEMPLATES_PREFIX + "override" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String DELEGATECOMMENT_ID= CODETEMPLATES_PREFIX + "delegate" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String GETTERCOMMENT_ID= CODETEMPLATES_PREFIX + "getter" + COMMENT_SUFFIX; //$NON-NLS-1$
- public static final String SETTERCOMMENT_ID= CODETEMPLATES_PREFIX + "setter" + COMMENT_SUFFIX; //$NON-NLS-1$
-
- /* resolver types */
- public static final String EXCEPTION_TYPE= "exception_type"; //$NON-NLS-1$
- public static final String EXCEPTION_VAR= "exception_var"; //$NON-NLS-1$
- public static final String ENCLOSING_METHOD= "enclosing_method"; //$NON-NLS-1$
- public static final String ENCLOSING_TYPE= "enclosing_type"; //$NON-NLS-1$
- public static final String BODY_STATEMENT= "body_statement"; //$NON-NLS-1$
- public static final String FIELD= "field"; //$NON-NLS-1$
- public static final String FIELD_TYPE= "field_type"; //$NON-NLS-1$
- public static final String BARE_FIELD_NAME= "bare_field_name"; //$NON-NLS-1$
-
- public static final String PARAM= "param"; //$NON-NLS-1$
- public static final String RETURN_TYPE= "return_type"; //$NON-NLS-1$
- public static final String SEE_TO_OVERRIDDEN_TAG= "see_to_overridden"; //$NON-NLS-1$
- public static final String SEE_TO_TARGET_TAG= "see_to_target"; //$NON-NLS-1$
-
- public static final String TAGS= "tags"; //$NON-NLS-1$
-
- public static final String TYPENAME= "type_name"; //$NON-NLS-1$
- public static final String FILENAME= "file_name"; //$NON-NLS-1$
- public static final String PACKAGENAME= "package_name"; //$NON-NLS-1$
- public static final String PROJECTNAME= "project_name"; //$NON-NLS-1$
-
- public static final String PACKAGE_DECLARATION= "package_declaration"; //$NON-NLS-1$
- public static final String TYPE_DECLARATION= "type_declaration"; //$NON-NLS-1$
- public static final String CLASS_BODY= "classbody"; //$NON-NLS-1$
- public static final String INTERFACE_BODY= "interfacebody"; //$NON-NLS-1$
- public static final String ENUM_BODY= "enumbody"; //$NON-NLS-1$
- public static final String ANNOTATION_BODY= "annotationbody"; //$NON-NLS-1$
- public static final String TYPE_COMMENT= "typecomment"; //$NON-NLS-1$
- public static final String FILE_COMMENT= "filecomment"; //$NON-NLS-1$
-
-
- /**
- * Resolver that resolves to the variable defined in the context.
- */
- public static class CodeTemplateVariableResolver extends TemplateVariableResolver {
- public CodeTemplateVariableResolver(String type, String description) {
- super(type, description);
- }
-
- protected String resolve(TemplateContext context) {
- return context.getVariable(getType());
- }
- }
-
- /**
- * Resolver for javadoc tags.
- */
- public static class TagsVariableResolver extends TemplateVariableResolver {
- public TagsVariableResolver() {
- super(TAGS, JavaTemplateMessages.CodeTemplateContextType_variable_description_tags);
- }
-
- protected String resolve(TemplateContext context) {
- return "@"; //$NON-NLS-1$
- }
- }
-
- /**
- * Resolver for todo tags.
- */
- protected static class Todo extends TemplateVariableResolver {
-
- public Todo() {
- super("todo", JavaTemplateMessages.CodeTemplateContextType_variable_description_todo); //$NON-NLS-1$
- }
-
- protected String resolve(TemplateContext context) {
- String todoTaskTag= StubUtility.getTodoTaskTag(((CodeTemplateContext) context).getJavaProject());
- if (todoTaskTag == null)
- return "XXX"; //$NON-NLS-1$
-
- return todoTaskTag;
- }
- }
-
- private boolean fIsComment;
-
- public CodeTemplateContextType(String contextName) {
- super(contextName);
-
- fIsComment= false;
-
- // global
- addResolver(new GlobalTemplateVariables.Dollar());
- addResolver(new GlobalTemplateVariables.Date());
- addResolver(new GlobalTemplateVariables.Year());
- addResolver(new GlobalTemplateVariables.Time());
- addResolver(new GlobalTemplateVariables.User());
- addResolver(new Todo());
-
- if (CATCHBLOCK_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
-
- addResolver(new CodeTemplateVariableResolver(EXCEPTION_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_exceptiontype));
- addResolver(new CodeTemplateVariableResolver(EXCEPTION_VAR, JavaTemplateMessages.CodeTemplateContextType_variable_description_exceptionvar));
- } else if (METHODBODY_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(BODY_STATEMENT, JavaTemplateMessages.CodeTemplateContextType_variable_description_bodystatement));
- } else if (CONSTRUCTORBODY_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(BODY_STATEMENT, JavaTemplateMessages.CodeTemplateContextType_variable_description_bodystatement));
- } else if (GETTERBODY_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldname));
- } else if (SETTERBODY_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldname));
- addResolver(new CodeTemplateVariableResolver(PARAM, JavaTemplateMessages.CodeTemplateContextType_variable_description_param));
- } else if (NEWTYPE_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_typename));
- addResolver(new CodeTemplateVariableResolver(PACKAGE_DECLARATION, JavaTemplateMessages.CodeTemplateContextType_variable_description_packdeclaration));
- addResolver(new CodeTemplateVariableResolver(TYPE_DECLARATION, JavaTemplateMessages.CodeTemplateContextType_variable_description_typedeclaration));
- addResolver(new CodeTemplateVariableResolver(TYPE_COMMENT, JavaTemplateMessages.CodeTemplateContextType_variable_description_typecomment));
- addResolver(new CodeTemplateVariableResolver(FILE_COMMENT, JavaTemplateMessages.CodeTemplateContextType_variable_description_filecomment));
- addCompilationUnitVariables();
- } else if (CLASSBODY_CONTEXTTYPE.equals(contextName) ||
- INTERFACEBODY_CONTEXTTYPE.equals(contextName) ||
- ENUMBODY_CONTEXTTYPE.equals(contextName) ||
- ANNOTATIONBODY_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_typename));
- addCompilationUnitVariables();
- } else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_typename));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new TagsVariableResolver());
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (FILECOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_typename));
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (FIELDCOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_fieldtype));
- addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.CodeTemplateContextType_variable_description_fieldname));
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (METHODCOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(RETURN_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_returntype));
- addResolver(new TagsVariableResolver());
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (OVERRIDECOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(SEE_TO_OVERRIDDEN_TAG, JavaTemplateMessages.CodeTemplateContextType_variable_description_see_overridden_tag));
- addResolver(new TagsVariableResolver());
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (DELEGATECOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(SEE_TO_TARGET_TAG, JavaTemplateMessages.CodeTemplateContextType_variable_description_see_target_tag));
- addResolver(new TagsVariableResolver());
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (CONSTRUCTORCOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new TagsVariableResolver());
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (GETTERCOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldtype));
- addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldname));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(BARE_FIELD_NAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_barefieldname));
- addCompilationUnitVariables();
- fIsComment= true;
- } else if (SETTERCOMMENT_CONTEXTTYPE.equals(contextName)) {
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingtype));
- addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldtype));
- addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.CodeTemplateContextType_variable_description_getterfieldname));
- addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.CodeTemplateContextType_variable_description_enclosingmethod));
- addResolver(new CodeTemplateVariableResolver(PARAM, JavaTemplateMessages.CodeTemplateContextType_variable_description_param));
- addResolver(new CodeTemplateVariableResolver(BARE_FIELD_NAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_barefieldname));
- addCompilationUnitVariables();
- fIsComment= true;
- }
- }
-
- private void addCompilationUnitVariables() {
- addResolver(new CodeTemplateVariableResolver(FILENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_filename));
- addResolver(new CodeTemplateVariableResolver(PACKAGENAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_packagename));
- addResolver(new CodeTemplateVariableResolver(PROJECTNAME, JavaTemplateMessages.CodeTemplateContextType_variable_description_projectname));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.ContextType#validateVariables(org.eclipse.wst.jsdt.internal.corext.template.TemplateVariable[])
- */
- protected void validateVariables(TemplateVariable[] variables) throws TemplateException {
- ArrayList required= new ArrayList(5);
- String contextName= getId();
- if (NEWTYPE_CONTEXTTYPE.equals(contextName)) {
- required.add(PACKAGE_DECLARATION);
- required.add(TYPE_DECLARATION);
- }
- for (int i= 0; i < variables.length; i++) {
- String type= variables[i].getType();
- if (getResolver(type) == null) {
- throw new TemplateException(Messages.format(JavaTemplateMessages.CodeTemplateContextType_validate_unknownvariable, type));
- }
- required.remove(type);
- }
- if (!required.isEmpty()) {
- String missing= (String) required.get(0);
- throw new TemplateException(Messages.format(JavaTemplateMessages.CodeTemplateContextType_validate_missingvariable, missing));
- }
- super.validateVariables(variables);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.template.ContextType#createContext()
- */
- public TemplateContext createContext() {
- return null;
- }
-
- public static void registerContextTypes(ContextTypeRegistry registry) {
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CATCHBLOCK_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.METHODBODY_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CONSTRUCTORBODY_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.GETTERBODY_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.SETTERBODY_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.NEWTYPE_CONTEXTTYPE));
-// Comented-out next 4 lines (STP 20070430)
-// registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CLASSBODY_CONTEXTTYPE));
-// registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.INTERFACEBODY_CONTEXTTYPE));
-// registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.ENUMBODY_CONTEXTTYPE));
-// registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.ANNOTATIONBODY_CONTEXTTYPE));
-
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.FILECOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.METHODCOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CONSTRUCTORCOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.OVERRIDECOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.DELEGATECOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.GETTERCOMMENT_CONTEXTTYPE));
- registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.SETTERCOMMENT_CONTEXTTYPE));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.ContextType#validate(java.lang.String)
- */
- public void validate(String pattern) throws TemplateException {
- super.validate(pattern);
- if (fIsComment) {
- if (!isValidComment(pattern)) {
- throw new TemplateException(JavaTemplateMessages.CodeTemplateContextType_validate_invalidcomment);
- }
- }
- }
-
-
- private boolean isValidComment(String template) {
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(template.toCharArray());
- try {
- int next= scanner.getNextToken();
- while (TokenScanner.isComment(next)) {
- next= scanner.getNextToken();
- }
- return next == ITerminalSymbols.TokenNameEOF;
- } catch (InvalidInputException e) {
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplates.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplates.java
deleted file mode 100644
index cc63177f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplates.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * <code>CodeTemplates</code> gives access to the available code templates.
- *
- * @deprecated use {@link org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin#getCodeTemplateStore()} instead
- */
-public class CodeTemplates extends org.eclipse.wst.jsdt.internal.corext.template.java.TemplateSet {
-
- private static final String TEMPLATE_FILE= "codetemplates.xml"; //$NON-NLS-1$
-
- /** Singleton. */
- private static CodeTemplates fgTemplates;
-
- public static Template getCodeTemplate(String name) {
- return getInstance().getFirstTemplate(name);
- }
-
- /**
- * Returns an instance of templates.
- */
- public static CodeTemplates getInstance() {
- if (fgTemplates == null)
- fgTemplates= new CodeTemplates();
-
- return fgTemplates;
- }
-
- private CodeTemplates() {
- super("codetemplate", JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry()); //$NON-NLS-1$
- create();
- }
-
- private void create() {
-
- try {
- File templateFile= getTemplateFile();
- if (templateFile.exists()) {
- addFromFile(templateFile, false);
- }
-
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- clear();
- }
-
- }
-
- /**
- * Resets the template set.
- */
- public void reset() throws CoreException {
- }
-
- /**
- * Resets the template set with the default templates.
- */
- public void restoreDefaults() throws CoreException {
- }
-
- /**
- * Saves the template set.
- */
- public void save() throws CoreException {
- }
-
- private static File getTemplateFile() {
- IPath path= JavaScriptPlugin.getDefault().getStateLocation();
- path= path.append(TEMPLATE_FILE);
-
- return path.toFile();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java
deleted file mode 100644
index c6bc5781..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java
+++ /dev/null
@@ -1,700 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * A completion requester to collect informations on local variables.
- * This class is used for guessing variable names like arrays, collections, etc.
- */
-final class CompilationUnitCompletion extends CompletionRequestor {
-
- /**
- * Describes a local variable (including parameters) inside the method where
- * code completion was invoked. Special predicates exist to query whether
- * a variable can be iterated over.
- */
- public final class Variable {
- private static final int UNKNOWN= 0, NONE= 0;
- private static final int ARRAY= 1;
- private static final int COLLECTION= 2;
- private static final int ITERABLE= 4;
-
- /**
- * The name of the local variable.
- */
- private final String name;
-
- /**
- * The signature of the local variable's type.
- */
- private final String signature;
-
- /* lazily computed properties */
- private int fType= UNKNOWN;
- private int fChecked= NONE;
- private String[] fMemberTypes;
-
- private Variable(String name, String signature) {
- this.name= name;
- this.signature= signature;
- }
-
- /**
- * Returns the name of the variable.
- *
- * @return the name of the variable
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns <code>true</code> if the type of the local variable is an
- * array type.
- *
- * @return <code>true</code> if the receiver's type is an array,
- * <code>false</code> if not
- */
- public boolean isArray() {
- if (fType == UNKNOWN && (fChecked & ARRAY) == 0 && Signature.getTypeSignatureKind(signature) == Signature.ARRAY_TYPE_SIGNATURE)
- fType= ARRAY;
- fChecked |= ARRAY;
- return fType == ARRAY;
- }
-
- /**
- * Returns <code>true</code> if the receiver's type is a subclass of
- * <code>java.util.Collection</code>, <code>false</code> otherwise.
- *
- * @return <code>true</code> if the receiver's type is a subclass of
- * <code>java.util.Collection</code>, <code>false</code>
- * otherwise
- */
- public boolean isCollection() {
- // Collection extends Iterable
- if ((fType == UNKNOWN || fType == ITERABLE) && (fChecked & COLLECTION) == 0 && isSubtypeOf("java.util.Collection")) //$NON-NLS-1$
- fType= COLLECTION;
- fChecked |= COLLECTION;
- return fType == COLLECTION;
- }
-
- /**
- * Returns <code>true</code> if the receiver's type is a subclass of
- * <code>java.lang.Iterable</code>, <code>false</code> otherwise.
- *
- * @return <code>true</code> if the receiver's type is a subclass of
- * <code>java.lang.Iterable</code>, <code>false</code>
- * otherwise
- */
- public boolean isIterable() {
- if (fType == UNKNOWN && (fChecked & ITERABLE) == 0 && isSubtypeOf("java.lang.Iterable")) //$NON-NLS-1$
- fType= ITERABLE;
- fChecked |= ITERABLE;
- return fType == ITERABLE || fType == COLLECTION; // Collection extends Iterable
- }
-
- /**
- * Returns <code>true</code> if the receiver's type is an implementor
- * of <code>interfaceName</code>.
- *
- * @param supertype the fully qualified name of the interface
- * @return <code>true</code> if the receiver's type implements the
- * type named <code>interfaceName</code>
- */
- private boolean isSubtypeOf(String supertype) {
- String implementorName= SignatureUtil.stripSignatureToFQN(signature);
- if (implementorName.length() == 0)
- return false;
-
- boolean qualified= supertype.indexOf('.') != -1;
-
- // try cheap test first
- if (implementorName.equals(supertype) || !qualified && Signature.getSimpleName(implementorName).equals(supertype))
- return true;
-
- if (fUnit == null)
- return false;
-
- IJavaScriptProject project= fUnit.getJavaScriptProject();
-
- try {
- IType sub= project.findType(implementorName);
- if (sub == null)
- return false;
-
- if (qualified) {
- IType sup= project.findType(supertype);
- if (sup == null)
- return false;
- ITypeHierarchy hierarchy= sub.newSupertypeHierarchy(null);
- return hierarchy.contains(sup);
- } else {
- ITypeHierarchy hierarchy= sub.newSupertypeHierarchy(null);
- IType[] allTypes= hierarchy.getAllClasses();
- for (int i= 0; i < allTypes.length; i++) {
- IType type= allTypes[i];
- if (type.getElementName().equals(supertype))
- return true;
- }
- }
-
- } catch (JavaScriptModelException e) {
- // ignore and return false
- }
-
- return false;
- }
-
- private IType[] getSupertypes(String supertype) {
- IType[] empty= new IType[0];
- String implementorName= SignatureUtil.stripSignatureToFQN(signature);
- if (implementorName.length() == 0)
- return empty;
-
- boolean qualified= supertype.indexOf('.') != -1;
-
- if (fUnit == null)
- return empty;
-
- IJavaScriptProject project= fUnit.getJavaScriptProject();
-
- try {
- IType sub= project.findType(implementorName);
- if (sub == null)
- return empty;
-
- if (qualified) {
- IType sup= project.findType(supertype);
- if (sup == null)
- return empty;
- return new IType[] {sup};
- } else {
- ITypeHierarchy hierarchy= sub.newSupertypeHierarchy(null);
- IType[] allTypes= hierarchy.getAllClasses();
- List matches= new ArrayList();
- for (int i= 0; i < allTypes.length; i++) {
- IType type= allTypes[i];
- if (type.getElementName().equals(supertype))
- matches.add(type);
- }
- return (IType[]) matches.toArray(new IType[matches.size()]);
- }
-
- } catch (JavaScriptModelException e) {
- // ignore and return false
- }
-
- return empty;
- }
-
- /**
- * Returns the signature of the member type.
- *
- * @return the signature of the member type
- */
- public String getMemberTypeSignature() {
- return getMemberTypeSignatures()[0];
- }
-
- /**
- * Returns the signatures of all member type bounds.
- *
- * @return the signatures of all member type bounds
- */
- public String[] getMemberTypeSignatures() {
- if (isArray()) {
- return new String[] {Signature.createArraySignature(Signature.getElementType(signature), Signature.getArrayCount(signature) - 1)};
- } else if (fUnit != null && (isIterable() || isCollection())) {
- if (fMemberTypes == null) {
- try {
- try {
- TypeParameterResolver util= new TypeParameterResolver(this);
- fMemberTypes= util.computeBinding("java.lang.Iterable", 0); //$NON-NLS-1$
- } catch (JavaScriptModelException e) {
- try {
- TypeParameterResolver util= new TypeParameterResolver(this);
- fMemberTypes= util.computeBinding("java.util.Collection", 0); //$NON-NLS-1$
- } catch (JavaScriptModelException x) {
- fMemberTypes= new String[0];
- }
- }
- } catch (IndexOutOfBoundsException e) {
- fMemberTypes= new String[0];
- }
- }
- if (fMemberTypes.length > 0)
- return fMemberTypes;
- }
- return new String[] {Signature.createTypeSignature("java.lang.Object", true)}; //$NON-NLS-1$
- }
-
- /**
- * Returns the type names of all member type bounds, as they would be
- * appear when referenced in the current compilation unit.
- *
- * @return type names of all member type bounds
- */
- public String[] getMemberTypeNames() {
- String[] signatures= getMemberTypeSignatures();
- String[] names= new String[signatures.length];
-
- for (int i= 0; i < signatures.length; i++) {
- String sig= signatures[i];
- String local= (String) fLocalTypes.get(Signature.getElementType(sig));
- int dim= Signature.getArrayCount(sig);
- if (local != null && dim > 0) {
- StringBuffer array= new StringBuffer(local);
- for (int j= 0; j < dim; j++)
- array.append("[]"); //$NON-NLS-1$
- local= array.toString();
- }
- if (local != null)
- names[i]= local;
- else
- names[i]= Signature.getSimpleName(Signature.getSignatureSimpleName(sig));
- }
- return names;
- }
-
- /**
- * Returns the type arguments of the declared type of the variable. Returns
- * an empty array if it is not a parameterized type.
- *
- * @param type the fully qualified type name of which to match a type argument
- * @param index the index of the type parameter in the type
- * @return the type bounds for the specified type argument in this local variable
- *
- */
- public String[] getTypeArgumentBoundSignatures(String type, int index) {
- List all= new ArrayList();
- IType[] supertypes= getSupertypes(type);
- if (fUnit != null) {
- for (int i= 0; i < supertypes.length; i++) {
- try {
- TypeParameterResolver util= new TypeParameterResolver(this);
- String[] result= util.computeBinding(supertypes[i].getFullyQualifiedName(), index);
- all.addAll(Arrays.asList(result));
- } catch (JavaScriptModelException e) {
- } catch (IndexOutOfBoundsException e) {
- }
- }
- }
- if (all.isEmpty())
- return new String[] {Signature.createTypeSignature("java.lang.Object", true)}; //$NON-NLS-1$
- return (String[]) all.toArray(new String[all.size()]);
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- String type;
- switch (fType) {
- case ITERABLE:
- type= "ITERABLE"; //$NON-NLS-1$
- break;
- case COLLECTION:
- type= "COLLECTION"; //$NON-NLS-1$
- break;
- case ARRAY:
- type= "ARRAY"; //$NON-NLS-1$
- break;
- default:
- type= "UNKNOWN"; //$NON-NLS-1$
- break;
- }
- return "LocalVariable [name=\"" + name + "\" signature=\"" + signature + "\" type=\"" + type + "\" member=\"" + getMemberTypeSignature() + "\"]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
- }
-
- /**
- * Given a java type, a resolver computes the bounds of type variables
- * declared in a super type, considering any type constraints along the
- * inheritance path.
- */
- private final class TypeParameterResolver {
- private static final String OBJECT_SIGNATURE= "Ljava.lang.Object;"; //$NON-NLS-1$
-
- private final ITypeHierarchy fHierarchy;
- private final Variable fVariable;
- private final IType fType;
- private final List fBounds= new ArrayList();
-
- /**
- * Creates a new type parameter resolver to compute the bindings of type
- * parameters for the declared type of <code>variable</code>. For any
- * super type of the type of <code>variable</code>, calling
- * {@link #computeBinding(IType, int) computeBinding} will find the type
- * bounds of type variables in the super type, considering any type
- * constraints along the inheritance path.
- *
- * @param variable the local variable under investigation
- * @throws JavaScriptModelException if the type of <code>variable</code>
- * cannot be found
- */
- public TypeParameterResolver(Variable variable) throws JavaScriptModelException {
- String typeName= SignatureUtil.stripSignatureToFQN(variable.signature);
- IJavaScriptProject project= fUnit.getJavaScriptProject();
- fType= project.findType(typeName);
- fHierarchy= fType.newSupertypeHierarchy(null);
- fVariable= variable;
- }
-
- /**
- * Given a type parameter of <code>superType</code> at position
- * <code>index</code>, this method computes and returns the (lower)
- * type bound(s) of that parameter for an instance of <code>fType</code>.
- * <p>
- * <code>superType</code> must be a super type of <code>fType</code>,
- * and <code>superType</code> must have at least
- * <code>index + 1</code> type parameters.
- * </p>
- *
- * @param superType the qualified type name of the super type to compute
- * the type parameter binding for
- * @param index the index into the list of type parameters of
- * <code>superType</code>
- * @throws JavaScriptModelException if any java model operation fails
- * @throws IndexOutOfBoundsException if the index is not valid
- */
- public String[] computeBinding(String superType, int index) throws JavaScriptModelException, IndexOutOfBoundsException {
- IJavaScriptProject project= fUnit.getJavaScriptProject();
- IType type= project.findType(superType);
- if (type == null)
- throw new JavaScriptModelException(new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, "No such type", null))); //$NON-NLS-1$
- return computeBinding(type, index);
- }
-
- /**
- * Given a type parameter of <code>superType</code> at position
- * <code>index</code>, this method computes and returns the (lower)
- * type bound(s) of that parameter for an instance of <code>fType</code>.
- * <p>
- * <code>superType</code> must be a super type of <code>fType</code>,
- * and <code>superType</code> must have at least
- * <code>index + 1</code> type parameters.
- * </p>
- *
- * @param superType the super type to compute the type parameter binding
- * for
- * @param index the index into the list of type parameters of
- * <code>superType</code>
- * @throws JavaScriptModelException if any java model operation fails
- * @throws IndexOutOfBoundsException if the index is not valid
- */
- public String[] computeBinding(IType superType, int index) throws JavaScriptModelException, IndexOutOfBoundsException {
- initBounds();
- return (String[]) fBounds.toArray(new String[fBounds.size()]);
- }
-
- /**
- * Clears the collected type bounds and initializes it with
- * <code>java.lang.Object</code>.
- */
- private void initBounds() {
- fBounds.clear();
- fBounds.add(OBJECT_SIGNATURE);
- }
-
- /**
- * Returns <code>true</code> if <code>subTypeSignature</code>
- * describes a type which is a true sub type of the type described by
- * <code>superTypeSignature</code>.
- *
- * @param subTypeSignature the potential subtype's signature
- * @param superTypeSignature the potential supertype's signature
- * @return <code>true</code> if the inheritance relationship holds
- */
- private boolean isTrueSubtypeOf(String subTypeSignature, String superTypeSignature) {
- // try cheap test first
- if (subTypeSignature.equals(superTypeSignature))
- return true;
-
- if (SignatureUtil.isJavaLangObject(subTypeSignature))
- return false; // Object has no super types
-
- if (Signature.getTypeSignatureKind(subTypeSignature) != Signature.BASE_TYPE_SIGNATURE && SignatureUtil.isJavaLangObject(superTypeSignature))
- return true;
-
- IJavaScriptProject project= fUnit.getJavaScriptProject();
-
- try {
-
- if ((Signature.getTypeSignatureKind(subTypeSignature) & Signature.CLASS_TYPE_SIGNATURE) == 0)
- return false;
- IType subType= project.findType(SignatureUtil.stripSignatureToFQN(subTypeSignature));
- if (subType == null)
- return false;
-
- if ((Signature.getTypeSignatureKind(superTypeSignature) & Signature.CLASS_TYPE_SIGNATURE) == 0)
- return false;
- IType superType= project.findType(SignatureUtil.stripSignatureToFQN(superTypeSignature));
- if (superType == null)
- return false;
-
- ITypeHierarchy hierarchy= subType.newSupertypeHierarchy(null);
- IType[] types= hierarchy.getAllSuperclasses(subType);
-
- for (int i= 0; i < types.length; i++)
- if (types[i].equals(superType))
- return true;
- } catch (JavaScriptModelException e) {
- // ignore and return false
- }
-
- return false;
- }
-
- /**
- * Returns <code>true</code> if <code>signature</code> is a concrete type signature,
- * <code>false</code> if it is a type variable.
- *
- * @param signature the signature to check
- * @param context the context inside which to resolve the type
- * @throws JavaScriptModelException if finding the type fails
- */
- private boolean isConcreteType(String signature, IType context) throws JavaScriptModelException {
- // try and resolve otherwise
- if (context.isBinary()) {
- return fUnit.getJavaScriptProject().findType(SignatureUtil.stripSignatureToFQN(signature)) != null;
- } else {
- return context.resolveType(SignatureUtil.stripSignatureToFQN(signature)) != null;
- }
- }
- }
-
- private IJavaScriptUnit fUnit;
-
- private List fLocalVariables= new ArrayList();
- private List fFields= new ArrayList();
- private Map fLocalTypes= new HashMap();
-
- private boolean fError;
-
- /**
- * Creates a compilation unit completion.
- *
- * @param unit the compilation unit, may be <code>null</code>.
- */
- CompilationUnitCompletion(IJavaScriptUnit unit) {
- reset(unit);
- setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- setIgnored(CompletionProposal.KEYWORD, true);
- setIgnored(CompletionProposal.LABEL_REF, true);
- setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- setIgnored(CompletionProposal.METHOD_REF, true);
- setIgnored(CompletionProposal.PACKAGE_REF, true);
- setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- setIgnored(CompletionProposal.TYPE_REF, true);
- }
-
- /**
- * Resets the completion requester.
- *
- * @param unit the compilation unit, may be <code>null</code>.
- */
- private void reset(IJavaScriptUnit unit) {
- fUnit= unit;
- fLocalVariables.clear();
- fFields.clear();
- fLocalTypes.clear();
-
- if (fUnit != null) {
- try {
- IType[] cuTypes= fUnit.getAllTypes();
- for (int i= 0; i < cuTypes.length; i++) {
- String fqn= cuTypes[i].getFullyQualifiedName();
- String sig= Signature.createTypeSignature(fqn, true);
- fLocalTypes.put(sig, cuTypes[i].getElementName());
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- fError= false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.CompletionRequestor#accept(org.eclipse.wst.jsdt.core.CompletionProposal)
- */
- public void accept(CompletionProposal proposal) {
-
- String name= String.valueOf(proposal.getCompletion());
- String signature= String.valueOf(proposal.getSignature());
-
- switch (proposal.getKind()) {
-
- case CompletionProposal.LOCAL_VARIABLE_REF:
- // collect local variables
- fLocalVariables.add(new Variable(name, signature));
- break;
- case CompletionProposal.FIELD_REF:
- // collect local variables
- fFields.add(new Variable(name, signature));
- break;
-
- default:
- break;
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.CompletionRequestor#completionFailure(org.eclipse.wst.jsdt.core.compiler.IProblem)
- */
- public void completionFailure(IProblem problem) {
- fError= true;
- }
-
- /**
- * Tests if the code completion process produced errors.
- *
- * @return <code>true</code> if there are errors, <code>false</code>
- * otherwise
- */
- public boolean hasErrors() {
- return fError;
- }
-
- /**
- * Returns all local variable names.
- *
- * @return all local variable names
- */
- public String[] getLocalVariableNames() {
- String[] names= new String[fLocalVariables.size()];
- int i= 0;
- for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) {
- Variable localVariable= (Variable) iterator.previous();
- names[i++]= localVariable.getName();
- }
- return names;
- }
-
- /**
- * Returns all field names.
- *
- * @return all field names
- *
- */
- public String[] getFieldNames() {
- String[] names= new String[fFields.size()];
- int i= 0;
- for (ListIterator iterator= fFields.listIterator(fFields.size()); iterator.hasPrevious();) {
- Variable field= (Variable)iterator.previous();
- names[i++]= field.getName();
- }
- return names;
- }
-
- /**
- * Returns all local arrays in the order that they appear.
- *
- * @return all local arrays
- */
- public Variable[] findLocalArrays() {
- List arrays= new ArrayList();
-
- for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) {
- Variable localVariable= (Variable) iterator.previous();
-
- if (localVariable.isArray())
- arrays.add(localVariable);
- }
-
- return (Variable[]) arrays.toArray(new Variable[arrays.size()]);
- }
-
- /**
- * Returns all local variables implementing or extending
- * <code>clazz</code> in the order that they appear.
- *
- * @param clazz the fully qualified type name of the class to match
- * @return all local variables matching <code>clazz</code>
- */
- public Variable[] findLocalVariables(String clazz) {
- List matches= new ArrayList();
-
- for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) {
- Variable localVariable= (Variable) iterator.previous();
-
- if (localVariable.isSubtypeOf(clazz))
- matches.add(localVariable);
- }
-
- return (Variable[]) matches.toArray(new Variable[matches.size()]);
- }
-
- /**
- * Returns all local variables implementing or extending
- * <code>clazz</code> in the order that they appear.
- *
- * @param clazz the fully qualified type name of the class to match
- * @return all local variables matching <code>clazz</code>
- */
- public Variable[] findFieldVariables(String clazz) {
- List matches= new ArrayList();
-
- for (ListIterator iterator= fFields.listIterator(fFields.size()); iterator.hasPrevious();) {
- Variable localVariable= (Variable)iterator.previous();
-
- if (localVariable.isSubtypeOf(clazz))
- matches.add(localVariable);
- }
-
- return (Variable[]) matches.toArray(new Variable[matches.size()]);
- }
-
- /**
- * Returns all local variables implementing <code>java.lang.Iterable</code>
- * <em>and</em> all local arrays, in the order that they appear. That is,
- * the returned variables can be used within the <code>foreach</code>
- * language construct.
- *
- * @return all local <code>Iterable</code>s and arrays
- */
- public Variable[] findLocalIterables() {
- List iterables= new ArrayList();
-
- for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) {
- Variable localVariable= (Variable) iterator.previous();
-
- if (localVariable.isArray() || localVariable.isIterable())
- iterables.add(localVariable);
- }
-
- return (Variable[]) iterables.toArray(new Variable[iterables.size()]);
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContext.java
deleted file mode 100644
index 62d30861..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContext.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.templates.DocumentTemplateContext;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariableGuess;
-
-
-/**
- * A compilation unit context.
- */
-public abstract class CompilationUnitContext extends DocumentTemplateContext {
-
- /** The compilation unit, may be <code>null</code>. */
- private final IJavaScriptUnit fCompilationUnit;
- /** A flag to force evaluation in head-less mode. */
- protected boolean fForceEvaluation;
- /** A global state for proposals that change if a master proposal changes. */
- protected MultiVariableGuess fMultiVariableGuess;
- /** <code>true</code> if the context has a managed (i.e. added to the document) position, <code>false</code> otherwise. */
- protected final boolean fIsManaged;
-
- /**
- * Creates a compilation unit context.
- *
- * @param type the context type
- * @param document the document
- * @param completionOffset the completion position within the document
- * @param completionLength the completion length within the document
- * @param compilationUnit the compilation unit (may be <code>null</code>)
- */
- protected CompilationUnitContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, IJavaScriptUnit compilationUnit) {
- super(type, document, completionOffset, completionLength);
- fCompilationUnit= compilationUnit;
- fIsManaged= false;
- }
-
- /**
- * Creates a compilation unit context.
- *
- * @param type the context type
- * @param document the document
- * @param completionPosition the position defining the completion offset and length
- * @param compilationUnit the compilation unit (may be <code>null</code>)
- *
- */
- protected CompilationUnitContext(TemplateContextType type, IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit) {
- super(type, document, completionPosition);
- fCompilationUnit= compilationUnit;
- fIsManaged= true;
- }
-
- /**
- * Returns the compilation unit if one is associated with this context,
- * <code>null</code> otherwise.
- *
- * @return the compilation unit of this context or <code>null</code>
- */
- public final IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * Returns the enclosing element of a particular element type,
- * <code>null</code> if no enclosing element of that type exists.
- *
- * @param elementType the element type
- * @return the enclosing element of the given type or <code>null</code>
- */
- public IJavaScriptElement findEnclosingElement(int elementType) {
- if (fCompilationUnit == null)
- return null;
-
- try {
- IJavaScriptElement element= fCompilationUnit.getElementAt(getStart());
- if (element == null) {
- element= fCompilationUnit;
- }
-
- return element.getAncestor(elementType);
-
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
-
- /**
- * Sets whether evaluation is forced or not.
- *
- * @param evaluate <code>true</code> in order to force evaluation,
- * <code>false</code> otherwise
- */
- public void setForceEvaluation(boolean evaluate) {
- fForceEvaluation= evaluate;
- }
-
- /**
- * Returns the multi-variable guess.
- *
- * @return the multi-variable guess
- */
- public MultiVariableGuess getMultiVariableGuess() {
- return fMultiVariableGuess;
- }
-
- /**
- * @param multiVariableGuess The multiVariableGuess to set.
- */
- void setMultiVariableGuess(MultiVariableGuess multiVariableGuess) {
- fMultiVariableGuess= multiVariableGuess;
- }
-
- protected IJavaScriptProject getJavaProject() {
- IJavaScriptUnit compilationUnit= getCompilationUnit();
- IJavaScriptProject project= compilationUnit == null ? null : compilationUnit.getJavaScriptProject();
- return project;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContextType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContextType.java
deleted file mode 100644
index e09f9fab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitContextType.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-
-
-/**
- * Compilation unit context type.
- */
-public abstract class CompilationUnitContextType extends TemplateContextType {
-
- protected static class ReturnType extends TemplateVariableResolver {
- public ReturnType() {
- super("return_type", JavaTemplateMessages.CompilationUnitContextType_variable_description_return_type); //$NON-NLS-1$
- }
- protected String resolve(TemplateContext context) {
- IJavaScriptElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaScriptElement.METHOD);
- if (element == null)
- return null;
-
- try {
- return Signature.toString(((IFunction) element).getReturnType());
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
- }
-
- protected static class File extends TemplateVariableResolver {
- public File() {
- super("file", JavaTemplateMessages.CompilationUnitContextType_variable_description_file); //$NON-NLS-1$
- }
- protected String resolve(TemplateContext context) {
- IJavaScriptUnit unit= ((CompilationUnitContext) context).getCompilationUnit();
-
- return (unit == null) ? null : unit.getElementName();
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected boolean isUnambiguous(TemplateContext context) {
- return resolve(context) != null;
- }
- }
-
- protected static class PrimaryTypeName extends TemplateVariableResolver {
- public PrimaryTypeName() {
- super("primary_type_name", JavaTemplateMessages.CompilationUnitContextType_variable_description_primary_type_name); //$NON-NLS-1$
-
- }
- protected String resolve(TemplateContext context) {
- IJavaScriptUnit unit= ((CompilationUnitContext) context).getCompilationUnit();
- if (unit == null)
- return null;
- return JavaScriptCore.removeJavaScriptLikeExtension(unit.getElementName());
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected boolean isUnambiguous(TemplateContext context) {
- return resolve(context) != null;
- }
- }
-
- protected static class EnclosingJavaElement extends TemplateVariableResolver {
- protected final int fElementType;
-
- public EnclosingJavaElement(String name, String description, int elementType) {
- super(name, description);
- fElementType= elementType;
- }
- protected String resolve(TemplateContext context) {
- IJavaScriptElement element= ((CompilationUnitContext) context).findEnclosingElement(fElementType);
- return (element == null) ? null : element.getElementName();
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected boolean isUnambiguous(TemplateContext context) {
- return resolve(context) != null;
- }
- }
-
- protected static class Method extends EnclosingJavaElement {
- public Method() {
- super("enclosing_method", JavaTemplateMessages.CompilationUnitContextType_variable_description_enclosing_method, IJavaScriptElement.METHOD); //$NON-NLS-1$
- }
- }
-
- protected static class Type extends EnclosingJavaElement {
- public Type() {
- super("enclosing_type", JavaTemplateMessages.CompilationUnitContextType_variable_description_enclosing_type, IJavaScriptElement.TYPE); //$NON-NLS-1$
- }
- }
-/*
- protected static class SuperClass extends EnclosingJavaElement {
- public Type() {
- super("super_class", TemplateMessages.getString("JavaContextType.variable.description.type"), IJavaScriptElement.TYPE);
- }
- }
-*/
- protected static class Package extends EnclosingJavaElement {
- public Package() {
- super("enclosing_package", JavaTemplateMessages.CompilationUnitContextType_variable_description_enclosing_package, IJavaScriptElement.PACKAGE_FRAGMENT); //$NON-NLS-1$
- }
- }
-
- protected static class Project extends EnclosingJavaElement {
- public Project() {
- super("enclosing_project", JavaTemplateMessages.CompilationUnitContextType_variable_description_enclosing_project, IJavaScriptElement.JAVASCRIPT_PROJECT); //$NON-NLS-1$
- }
- }
-/*
- protected static class Project2 extends TemplateVariableResolver {
- public Project2() {
- super("project", TemplateMessages.getString("JavaContextType.variable.description.project"));
- }
- public String evaluate(TemplateContext context) {
- IJavaScriptUnit unit= ((JavaContext) context).getUnit();
- return (unit == null) ? null : unit.getJavaProject().getElementName();
- }
- }
-*/
- protected static class Arguments extends TemplateVariableResolver {
- public Arguments() {
- super("enclosing_method_arguments", JavaTemplateMessages.CompilationUnitContextType_variable_description_enclosing_method_arguments); //$NON-NLS-1$
- }
- protected String resolve(TemplateContext context) {
- IJavaScriptElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaScriptElement.METHOD);
- if (element == null)
- return null;
-
- IFunction method= (IFunction) element;
-
- try {
- String[] arguments= method.getParameterNames();
- StringBuffer buffer= new StringBuffer();
-
- for (int i= 0; i < arguments.length; i++) {
- if (i > 0)
- buffer.append(", "); //$NON-NLS-1$
- buffer.append(arguments[i]);
- }
-
- return buffer.toString();
-
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
- }
-
-/*
- protected static class Line extends TemplateVariableResolver {
- public Line() {
- super("line", TemplateMessages.getString("CompilationUnitContextType.variable.description.line"));
- }
- public String evaluate(TemplateContext context) {
- return ((JavaTemplateContext) context).guessLineNumber();
- }
- }
-*/
-
- /*
- * @see ContextType#ContextType(String)
- */
- public CompilationUnitContextType(String name) {
- super(name);
- }
-
- public abstract CompilationUnitContext createContext(IDocument document, int completionPosition, int length, IJavaScriptUnit compilationUnit);
- public abstract CompilationUnitContext createContext(IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit);
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.template.ContextType#validateVariables(org.eclipse.wst.jsdt.internal.corext.template.TemplateVariable[])
- */
- protected void validateVariables(TemplateVariable[] variables) throws TemplateException {
- // check for multiple cursor variables
- for (int i= 0; i < variables.length; i++) {
- TemplateVariable var= variables[i];
- if (var.getType().equals(GlobalTemplateVariables.Cursor.NAME)) {
- if (var.getOffsets().length > 1) {
- throw new TemplateException(JavaTemplateMessages.ContextType_error_multiple_cursor_variables);
- }
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java
deleted file mode 100644
index 41fef4e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-
-
-public class ElementTypeResolver extends TemplateVariableResolver {
-
- public ElementTypeResolver() {
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- *
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- if (!(variable instanceof MultiVariable)) {
- super.resolve(variable, context);
- return;
- }
- MultiVariable mv= (MultiVariable) variable;
- List params= variable.getVariableType().getParams();
- if (params.isEmpty()) {
- super.resolve(variable, context);
- return;
- }
-
- JavaContext jc= (JavaContext) context;
- String reference= (String) params.get(0);
- TemplateVariable refVar= jc.getTemplateVariable(reference);
- if (refVar instanceof JavaVariable) {
- JavaVariable jvar= (JavaVariable) refVar;
- resolve(mv, jvar, jc);
- return;
- }
-
- super.resolve(variable, context);
- }
-
- private void resolve(MultiVariable variable, JavaVariable master, JavaContext context) {
- Object[] choices= master.getChoices();
- if (choices instanceof Variable[]) {
- Variable[] variables= (Variable[]) choices;
-
- for (int i= 0; i < variables.length; i++)
- variable.setChoices(variables[i], variables[i].getMemberTypeNames());
-
- context.addDependency(master, variable);
- variable.setKey(master.getCurrentChoice());
- } else {
- super.resolve(variable, context);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java
deleted file mode 100644
index 8c5ffbd3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.Position;
-
-/**
- * Position updater that takes any changes at the borders of a position to not belong to the position.
- *
- *
- */
-final class ExclusivePositionUpdater implements IPositionUpdater {
-
- /** The position category. */
- private final String fCategory;
-
- /**
- * Creates a new updater for the given <code>category</code>.
- *
- * @param category the new category.
- */
- public ExclusivePositionUpdater(String category) {
- fCategory= category;
- }
-
- /*
- * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
- */
- public void update(DocumentEvent event) {
-
- int eventOffset= event.getOffset();
- int eventOldLength= event.getLength();
- int eventNewLength= event.getText() == null ? 0 : event.getText().length();
- int deltaLength= eventNewLength - eventOldLength;
-
- try {
- Position[] positions= event.getDocument().getPositions(fCategory);
-
- for (int i= 0; i != positions.length; i++) {
-
- Position position= positions[i];
-
- if (position.isDeleted())
- continue;
-
- int offset= position.getOffset();
- int length= position.getLength();
- int end= offset + length;
-
- if (offset >= eventOffset + eventOldLength)
- // position comes
- // after change - shift
- position.setOffset(offset + deltaLength);
- else if (end <= eventOffset) {
- // position comes way before change -
- // leave alone
- } else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
- // event completely internal to the position - adjust length
- position.setLength(length + deltaLength);
- } else if (offset < eventOffset) {
- // event extends over end of position - adjust length
- int newEnd= eventOffset;
- position.setLength(newEnd - offset);
- } else if (end > eventOffset + eventOldLength) {
- // event extends from before position into it - adjust offset
- // and length
- // offset becomes end of event, length adjusted accordingly
- int newOffset= eventOffset + eventNewLength;
- position.setOffset(newOffset);
- position.setLength(end - newOffset);
- } else {
- // event consumes the position - delete it
- position.delete();
- }
- }
- } catch (BadPositionCategoryException e) {
- // ignore and return
- }
- }
-
- /**
- * Returns the position category.
- *
- * @return the position category
- */
- public String getCategory() {
- return fCategory;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java
deleted file mode 100644
index a997cb93..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-
-/**
- * Resolves a template variable to a field that is assignment-compatible
- * with the variable instance' class parameter.
- *
- *
- */
-public class FieldResolver extends TemplateVariableResolver {
-
- private final String fDefaultType;
- private String fType;
-
- /**
- * Default constructor for instantiation by the extension point.
- */
- public FieldResolver() {
- this("java.lang.Object"); //$NON-NLS-1$
- }
-
- FieldResolver(String defaultType) {
- fDefaultType= defaultType;
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- List params= variable.getVariableType().getParams();
- if (params.size() == 0)
- fType= fDefaultType;
- else
- fType= (String) params.get(0);
-
- if (variable instanceof JavaVariable) {
- JavaContext jc= (JavaContext) context;
- JavaVariable jv= (JavaVariable) variable;
- jv.setParamType(fType);
- Variable[] fields= jc.getFields(fType);
- if (fields.length > 0) {
- jv.setChoices(fields);
- jc.markAsUsed(jv.getDefaultValue());
- } else {
- super.resolve(variable, context);
- return;
- }
- if (fields.length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
- } else
- super.resolve(variable, context);
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolveAll(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] iterables= jc.getFields(fType);
- String[] names= new String[iterables.length];
- for (int i= 0; i < iterables.length; i++)
- names[i]= iterables[i].getName();
- if (names.length > 0)
- jc.markAsUsed(names[0]);
- return names;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java
deleted file mode 100644
index 06c9a22f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java
+++ /dev/null
@@ -1,603 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateTranslator;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableType;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeNameMatchCollector;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ASTResolving;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.SimilarElementsRequestor;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariableGuess;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * A context for java source.
- */
-public class JavaContext extends CompilationUnitContext {
-
- /** A code completion requester for guessing local variable names. */
- private CompilationUnitCompletion fCompletion;
- /**
- * The list of used local names.
- *
- */
- private Set fUsedNames= new HashSet();
- private Map fVariables= new HashMap();
-
- /**
- * Creates a java template context.
- *
- * @param type the context type.
- * @param document the document.
- * @param completionOffset the completion offset within the document.
- * @param completionLength the completion length.
- * @param compilationUnit the compilation unit (may be <code>null</code>).
- */
- public JavaContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, IJavaScriptUnit compilationUnit) {
- super(type, document, completionOffset, completionLength, compilationUnit);
- }
-
- /**
- * Creates a java template context.
- *
- * @param type the context type.
- * @param document the document.
- * @param completionPosition the position defining the completion offset and length
- * @param compilationUnit the compilation unit (may be <code>null</code>).
- *
- */
- public JavaContext(TemplateContextType type, IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit) {
- super(type, document, completionPosition, compilationUnit);
- }
-
- /**
- * Returns the indentation level at the position of code completion.
- *
- * @return the indentation level at the position of the code completion
- */
- private int getIndentation() {
- int start= getStart();
- IDocument document= getDocument();
- try {
- IRegion region= document.getLineInformationOfOffset(start);
- String lineContent= document.get(region.getOffset(), region.getLength());
- IJavaScriptProject project= getJavaProject();
- return Strings.computeIndentUnits(lineContent, project);
- } catch (BadLocationException e) {
- return 0;
- }
- }
-
- /*
- * @see TemplateContext#evaluate(Template template)
- */
- public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
- clear();
-
- if (!canEvaluate(template))
- throw new TemplateException(JavaTemplateMessages.Context_error_cannot_evaluate);
-
- TemplateTranslator translator= new TemplateTranslator() {
- protected TemplateVariable createVariable(TemplateVariableType type, String name, int[] offsets) {
-// TemplateVariableResolver resolver= getContextType().getResolver(type.getName());
-// return resolver.createVariable();
-
- MultiVariable variable= new JavaVariable(type, name, offsets);
- fVariables.put(name, variable);
- return variable;
- }
- };
- TemplateBuffer buffer= translator.translate(template);
-
- getContextType().resolve(buffer, this);
-
- IPreferenceStore prefs= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
-
- IJavaScriptProject project= getJavaProject();
- JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
- formatter.format(buffer, this);
-
- clear();
-
- return buffer;
- }
-
- private void clear() {
- fUsedNames.clear();
- }
-
- /*
- * @see TemplateContext#canEvaluate(Template templates)
- */
- public boolean canEvaluate(Template template) {
- if (fForceEvaluation)
- return true;
-
- String key= getKey();
- return
- template.matches(key, getContextType().getId()) &&
- key.length() != 0 && template.getName().toLowerCase().startsWith(key.toLowerCase());
- }
-
- /*
- * @see DocumentTemplateContext#getCompletionPosition();
- */
- public int getStart() {
-
- if (fIsManaged && getCompletionLength() > 0)
- return super.getStart();
-
- try {
- IDocument document= getDocument();
-
- int start= getCompletionOffset();
- int end= getCompletionOffset() + getCompletionLength();
-
- while (start != 0 && isTempalteNamePart(document.getChar(start - 1)))
- start--;
-
- while (start != end && Character.isWhitespace(document.getChar(start)))
- start++;
-
- if (start == end)
- start= getCompletionOffset();
-
- return start;
-
- } catch (BadLocationException e) {
- return super.getStart();
- }
- }
-
- /**
- * Tells whether the given character can be part of a template name.
- *
- * @param ch the character to test
- * @return <code>true</code> if the given character can be part of a template name
- *
- */
- private boolean isTempalteNamePart(char ch) {
- return !Character.isWhitespace(ch) && ch != '(' && ch != ')' && ch != '{' && ch != '}' && ch != ';';
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.DocumentTemplateContext#getEnd()
- */
- public int getEnd() {
-
- if (fIsManaged || getCompletionLength() == 0)
- return super.getEnd();
-
- try {
- IDocument document= getDocument();
-
- int start= getCompletionOffset();
- int end= getCompletionOffset() + getCompletionLength();
-
- while (start != end && Character.isWhitespace(document.getChar(end - 1)))
- end--;
-
- return end;
-
- } catch (BadLocationException e) {
- return super.getEnd();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.DocumentTemplateContext#getKey()
- */
- public String getKey() {
-
- if (getCompletionLength() == 0)
- return super.getKey();
-
- try {
- IDocument document= getDocument();
-
- int start= getStart();
- int end= getCompletionOffset();
- return start <= end
- ? document.get(start, end - start)
- : ""; //$NON-NLS-1$
-
- } catch (BadLocationException e) {
- return super.getKey();
- }
- }
-
- /**
- * Returns the character before the start position of the completion.
- *
- * @return the character before the start position of the completion
- */
- public char getCharacterBeforeStart() {
- int start= getStart();
-
- try {
- return start == 0
- ? ' '
- : getDocument().getChar(start - 1);
-
- } catch (BadLocationException e) {
- return ' ';
- }
- }
-
- private static void handleException(Shell shell, Exception e) {
- String title= JavaTemplateMessages.JavaContext_error_title;
- if (e instanceof CoreException)
- ExceptionHandler.handle((CoreException)e, shell, title, null);
- else if (e instanceof InvocationTargetException)
- ExceptionHandler.handle((InvocationTargetException)e, shell, title, null);
- else {
- JavaScriptPlugin.log(e);
- MessageDialog.openError(shell, title, e.getMessage());
- }
- }
-
- private CompilationUnitCompletion getCompletion() {
- IJavaScriptUnit compilationUnit= getCompilationUnit();
- if (fCompletion == null) {
- fCompletion= new CompilationUnitCompletion(compilationUnit);
-
- if (compilationUnit != null) {
- try {
- compilationUnit.codeComplete(getStart(), fCompletion);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
-
- return fCompletion;
- }
-
- /**
- * Returns the names of local arrays.
- *
- * @return the names of local arrays
- */
- public Variable[] getArrays() {
- Variable[] localArrays= getCompletion().findLocalArrays();
- arrange(localArrays);
- return localArrays;
- }
-
- /**
- * Sorts already used locals behind any that are not yet used.
- *
- * @param variables the variables to sort
- *
- */
- private void arrange(Variable[] variables) {
- Arrays.sort(variables, new Comparator() {
- public int compare(Object o1, Object o2) {
- return rank((Variable) o1) - rank((Variable) o2);
- }
-
- private int rank(Variable l) {
- return fUsedNames.contains(l.getName()) ? 1 : 0;
- }
- });
- }
-
- /**
- * Returns the names of local variables matching <code>type</code>.
- *
- * @return the names of local variables matching <code>type</code>
- *
- */
- public Variable[] getLocalVariables(String type) {
- Variable[] localVariables= getCompletion().findLocalVariables(type);
- arrange(localVariables);
- return localVariables;
- }
-
- /**
- * Returns the names of all local variables.
- *
- * @return the names of all local variables
- *
- */
- public String[] getLocalVariableNames() {
- String[] localVariableNames = getCompletion().getLocalVariableNames();
- return localVariableNames;
- }
-
- /**
- * Returns the names of fields matching <code>type</code>.
- *
- * @return the names of fields matching <code>type</code>
- *
- */
- public Variable[] getFields(String type) {
- Variable[] fields= getCompletion().findFieldVariables(type);
- arrange(fields);
- return fields;
- }
-
- /**
- * Returns the names of local iterables or arrays.
- *
- * @return the names of local iterables or arrays
- */
- public Variable[] getIterables() {
- Variable[] iterables= getCompletion().findLocalIterables();
- arrange(iterables);
- return iterables;
- }
-
- public void markAsUsed(String name) {
- fUsedNames.add(name);
- }
-
- public String[] suggestVariableNames(String type) throws IllegalArgumentException {
- String[] excludes= computeExcludes();
- // TODO erasure, arrays, etc.
- String[] result= suggestVariableName(type, excludes);
- return result;
- }
-
- private String[] computeExcludes() {
- String[] excludes= getCompletion().getLocalVariableNames();
- if (!fUsedNames.isEmpty()) {
- String[] allExcludes= new String[fUsedNames.size() + excludes.length];
- System.arraycopy(excludes, 0, allExcludes, 0, excludes.length);
- System.arraycopy(fUsedNames.toArray(), 0, allExcludes, 0, fUsedNames.size());
- excludes= allExcludes;
- }
- return excludes;
- }
-
- private String[] suggestVariableName(String type, String[] excludes) throws IllegalArgumentException {
- int dim=0;
- while (type.endsWith("[]")) {//$NON-NLS-1$
- dim++;
- type= type.substring(0, type.length() - 2);
- }
-
- IJavaScriptProject project= getJavaProject();
- if (project != null)
- return StubUtility.getVariableNameSuggestions(StubUtility.LOCAL, project, type, dim, Arrays.asList(excludes), true);
-
- // fallback if we lack proper context: roll-our own lowercasing
- return new String[] {Signature.getSimpleName(type).toLowerCase()};
- }
-
- public void addImport(String type) {
- if (isReadOnly())
- return;
-
- IJavaScriptUnit cu= getCompilationUnit();
- if (cu == null)
- return;
-
- try {
- boolean qualified= type.indexOf('.') != -1;
- if (!qualified) {
- IJavaScriptSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { cu.getJavaScriptProject() });
- SimpleName nameNode= null;
- TypeNameMatch[] matches= findAllTypes(type, searchScope, nameNode, null, cu);
- if (matches.length != 1) // only add import if we have a single match
- return;
- type= matches[0].getFullyQualifiedName();
- }
-
- Position position= new Position(getCompletionOffset(), getCompletionLength());
- IDocument document= getDocument();
- final String category= "__template_position_importer" + System.currentTimeMillis(); //$NON-NLS-1$
- IPositionUpdater updater= new DefaultPositionUpdater(category);
- document.addPositionCategory(category);
- document.addPositionUpdater(updater);
- document.addPosition(position);
-
- try {
-
- ImportRewrite rewrite= StubUtility.createImportRewrite(cu, true);
- JavaScriptUnit root= getASTRoot(cu);
- ImportRewriteContext context;
- if (root == null)
- context= null;
- else
- context= new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), rewrite);
- rewrite.addImport(type, type, context);
- JavaModelUtil.applyEdit(cu, rewrite.rewriteImports(null), false, null);
-
- setCompletionOffset(position.getOffset());
- setCompletionLength(position.getLength());
-
- } catch (CoreException e) {
- handleException(null, e);
- } finally {
- document.removePosition(position);
- document.removePositionUpdater(updater);
- document.removePositionCategory(category);
- }
-
- } catch (BadLocationException e) {
- handleException(null, e);
- } catch (BadPositionCategoryException e) {
- handleException(null, e);
- } catch (JavaScriptModelException e) {
- handleException(null, e);
- }
- }
-
- private JavaScriptUnit getASTRoot(IJavaScriptUnit compilationUnit) {
- return JavaScriptPlugin.getDefault().getASTProvider().getAST(compilationUnit, ASTProvider.WAIT_NO, new NullProgressMonitor());
- }
-
- /*
- * Finds a type by the simple name. From AddImportsOperation
- */
- private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaScriptSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor, IJavaScriptUnit cu) throws JavaScriptModelException {
- boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaScriptProject());
-
- int typeKinds= SimilarElementsRequestor.ALL_TYPES;
- if (nameNode != null) {
- typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
- }
-
- ArrayList typeInfos= new ArrayList();
- TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
- new SearchEngine().searchAllTypeNames(null, 0, simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, getSearchForConstant(typeKinds), searchScope, requestor, IJavaScriptSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor);
-
- ArrayList typeRefsFound= new ArrayList(typeInfos.size());
- for (int i= 0, len= typeInfos.size(); i < len; i++) {
- TypeNameMatch curr= (TypeNameMatch) typeInfos.get(i);
- if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
- if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) {
- typeRefsFound.add(curr);
- }
- }
- }
- return (TypeNameMatch[]) typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
- }
-
- private int getSearchForConstant(int typeKinds) {
- final int CLASSES= SimilarElementsRequestor.CLASSES;
-
- switch (typeKinds & (CLASSES)) {
- case CLASSES: return IJavaScriptSearchConstants.CLASS;
- default: return IJavaScriptSearchConstants.TYPE;
- }
- }
-
- private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) {
- return (typeKinds & SimilarElementsRequestor.CLASSES) != 0;
- }
-
-
- private boolean isVisible(TypeNameMatch curr, IJavaScriptUnit cu) {
- int flags= curr.getModifiers();
- if (Flags.isPrivate(flags)) {
- return false;
- }
- if (Flags.isPublic(flags)) {
- return true;
- }
- return curr.getPackageName().equals(cu.getParent().getElementName());
- }
-
- /**
- * Evaluates a 'java' template in the context of a compilation unit
- *
- * @param template the template to be evaluated
- * @param compilationUnit the compilation unit in which to evaluate the template
- * @param position the position inside the compilation unit for which to evaluate the template
- * @return the evaluated template
- * @throws CoreException in case the template is of an unknown context type
- * @throws BadLocationException in case the position is invalid in the compilation unit
- * @throws TemplateException in case the evaluation fails
- */
- public static String evaluateTemplate(Template template, IJavaScriptUnit compilationUnit, int position) throws CoreException, BadLocationException, TemplateException {
-
- TemplateContextType contextType= JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType(JavaContextType.NAME);
- if (contextType == null)
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, JavaTemplateMessages.JavaContext_error_message, null));
-
- IDocument document= new Document();
- if (compilationUnit != null && compilationUnit.exists())
- document.set(compilationUnit.getSource());
-
- JavaContext context= new JavaContext(contextType, document, position, 0, compilationUnit);
- context.setForceEvaluation(true);
-
- TemplateBuffer buffer= context.evaluate(template);
- if (buffer == null)
- return null;
- return buffer.getString();
- }
-
- TemplateVariable getTemplateVariable(String name) {
- TemplateVariable variable= (TemplateVariable) fVariables.get(name);
- if (variable != null && !variable.isResolved())
- getContextType().resolve(variable, this);
- return variable;
- }
-
- /**
- * Adds a multi-variable guess dependency.
- *
- * @param master the master variable - <code>slave</code> needs to be updated when
- * <code>master</code> changes
- * @param slave the dependent variable
- *
- */
- public void addDependency(MultiVariable master, MultiVariable slave) {
- MultiVariableGuess guess= getMultiVariableGuess();
- if (guess == null) {
- guess= new MultiVariableGuess();
- setMultiVariableGuess(guess);
- }
-
- guess.addDependency(master, slave);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContextType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContextType.java
deleted file mode 100644
index 88b1b3d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContextType.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids: sdavids@gmx.de - see bug 25376
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-
-/**
- * A context type for java code.
- */
-public class JavaContextType extends CompilationUnitContextType {
-
- public static final String NAME= "javaScript"; //$NON-NLS-1$
-
- protected static abstract class AbstractIterable extends TemplateVariableResolver {
- public AbstractIterable(String type, String description) {
- super(type, description);
- }
-
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] iterables= getLocalVariables(jc);
- String[] names= new String[iterables.length];
- for (int i= 0; i < iterables.length; i++)
- names[i]= iterables[i].getName();
- if (names.length > 0)
- jc.markAsUsed(names[0]);
- return names;
- }
-
- abstract protected Variable[] getLocalVariables(JavaContext jc);
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- if (variable instanceof MultiVariable) {
- JavaContext jc= (JavaContext) context;
- JavaVariable jv= (JavaVariable) variable;
- Variable[] iterables= getLocalVariables(jc);
- if (iterables.length > 0) {
- jv.setChoices(iterables);
- jc.markAsUsed(iterables[0].getName());
-
- if (iterables.length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
-
- return;
- }
- }
-
- super.resolve(variable, context);
- }
- }
-
- protected static class Array extends AbstractIterable {
- public Array() {
- super("array", JavaTemplateMessages.JavaContextType_variable_description_array); //$NON-NLS-1$
- }
-
- protected Variable[] getLocalVariables(JavaContext jc) {
- return jc.getArrays();
- }
- }
-
-// protected static class Iterable extends AbstractIterable {
-// public Iterable() {
-// super("iterable", JavaTemplateMessages.JavaContextType_variable_description_iterable); //$NON-NLS-1$
-// }
-//
-// protected Variable[] getLocalVariables(JavaContext jc) {
-// return jc.getIterables();
-// }
-// }
-
- protected static abstract class AbstractIterableType extends TemplateVariableResolver {
- private String fMasterName;
-
- public AbstractIterableType(String type, String desc, String master) {
- super(type, desc);
- fMasterName= master;
- }
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] iterables= getLocalVariables(jc);
- String[] types= new String[iterables.length];
- for (int i= 0; i < iterables.length; i++)
- types[i]= iterables[i].getMemberTypeNames()[0];
- return types;
- }
-
- abstract protected Variable[] getLocalVariables(JavaContext jc);
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- if (variable instanceof MultiVariable) {
- JavaContext jc= (JavaContext) context;
- MultiVariable mv= (MultiVariable) variable;
-
- Variable[] iterables= getLocalVariables(jc);
- if (iterables.length > 0) {
-
- for (int i= 0; i < iterables.length; i++)
- mv.setChoices(iterables[i], iterables[i].getMemberTypeNames());
-
- TemplateVariable master= jc.getTemplateVariable(fMasterName);
- if (master instanceof MultiVariable) {
- final MultiVariable masterMv= (MultiVariable) master;
- jc.addDependency(masterMv, mv);
- mv.setKey(masterMv.getCurrentChoice());
- }
-
- if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
-
- return;
- }
-
- }
-
- super.resolve(variable, context);
- }
- }
-
- protected static class ArrayType extends AbstractIterableType {
- public ArrayType() {
- super("array_type", JavaTemplateMessages.JavaContextType_variable_description_array_type, "array"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- protected Variable[] getLocalVariables(JavaContext jc) {
- return jc.getArrays();
- }
- }
-
-// protected static class IterableType extends AbstractIterableType {
-// public IterableType() {
-// super("iterable_type", JavaTemplateMessages.JavaContextType_variable_description_iterable_type, "iterable"); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// protected Variable[] getLocalVariables(JavaContext jc) {
-// return jc.getIterables();
-// }
-// }
-
- protected static abstract class AbstractIterableElement extends TemplateVariableResolver {
- private String fMasterName;
-
- public AbstractIterableElement(String type, String desc, String master) {
- super(type, desc);
- fMasterName= master;
- }
-
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] iterables= getLocalVariables(jc);
- String[] elements= new String[iterables.length];
- for (int i= 0; i < iterables.length; i++) {
- elements[i]= jc.suggestVariableNames(iterables[i].getMemberTypeNames()[0])[0];
- if (i == 0)
- jc.markAsUsed(elements[0]);
- }
-
- return elements;
- }
-
- abstract protected Variable[] getLocalVariables(JavaContext jc);
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- if (variable instanceof MultiVariable) {
- JavaContext jc= (JavaContext) context;
- MultiVariable mv= (MultiVariable) variable;
-
- Variable[] iterables= getLocalVariables(jc);
- if (iterables.length > 0) {
- for (int i= 0; i < iterables.length; i++) {
- String[] elements= jc.suggestVariableNames(iterables[i].getMemberTypeNames()[0]);
- mv.setChoices(iterables[i], elements);
- }
-
-
- TemplateVariable master= jc.getTemplateVariable(fMasterName);
- if (master instanceof MultiVariable) {
- final MultiVariable masterMv= (MultiVariable) master;
- jc.addDependency(masterMv, mv);
- mv.setKey(masterMv.getCurrentChoice());
- }
- jc.markAsUsed(mv.getDefaultValue());
-
- if (iterables.length > 1 || iterables.length == 1 && mv.getChoices().length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
-
- return;
- }
-
- }
- super.resolve(variable, context);
- }
- }
-
- protected static class ArrayElement extends AbstractIterableElement {
- public ArrayElement() {
- super("array_element", JavaTemplateMessages.JavaContextType_variable_description_array_element, "array"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- protected Variable[] getLocalVariables(JavaContext jc) {
- return jc.getArrays();
- }
- }
-
-// protected static class IterableElement extends AbstractIterableElement {
-// public IterableElement() {
-// super("iterable_element", JavaTemplateMessages.JavaContextType_variable_description_iterable_element, "iterable"); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// protected Variable[] getLocalVariables(JavaContext jc) {
-// return jc.getIterables();
-// }
-// }
-
- protected static class Index extends NameResolver {
- public Index() {
- super("int"); //$NON-NLS-1$
- setType("index"); //$NON-NLS-1$
- setDescription(JavaTemplateMessages.JavaContextType_variable_description_index);
- }
- }
-
-// protected static class Collection extends LocalVarResolver {
-// public Collection() {
-// super("java.util.Collection"); //$NON-NLS-1$
-// setType("collection"); //$NON-NLS-1$
-// setDescription(JavaTemplateMessages.JavaContextType_variable_description_collection);
-// }
-// }
-//
-// protected static class Iterator extends NameResolver {
-// public Iterator() {
-// super("java.util.Iterator"); //$NON-NLS-1$
-// setType("iterator"); //$NON-NLS-1$
-// setDescription(JavaTemplateMessages.JavaContextType_variable_description_iterator);
-// }
-// }
-//
- protected static class Todo extends TemplateVariableResolver {
-
- public Todo() {
- super("todo", JavaTemplateMessages.JavaContextType_variable_description_todo); //$NON-NLS-1$
- }
- protected String resolve(TemplateContext context) {
- JavaContext javaContext= (JavaContext) context;
- IJavaScriptUnit compilationUnit= javaContext.getCompilationUnit();
- if (compilationUnit == null)
- return "XXX"; //$NON-NLS-1$
-
- IJavaScriptProject javaProject= compilationUnit.getJavaScriptProject();
- String todoTaskTag= StubUtility.getTodoTaskTag(javaProject);
- if (todoTaskTag == null)
- return "XXX"; //$NON-NLS-1$
-
- return todoTaskTag;
- }
- }
-/*
- protected static class Arguments extends SimpleVariableResolver {
- public Arguments() {
- super("arguments", TemplateMessages.getString("JavaContextType.variable.description.arguments"), "");
- }
- }
-*/
-
-
- /**
- * Creates a java context type.
- */
- public JavaContextType() {
- super(NAME);
-
- // global
- addResolver(new GlobalTemplateVariables.Cursor());
- addResolver(new GlobalTemplateVariables.WordSelection());
- addResolver(new GlobalTemplateVariables.LineSelection());
- addResolver(new GlobalTemplateVariables.Dollar());
- addResolver(new GlobalTemplateVariables.Date());
- addResolver(new GlobalTemplateVariables.Year());
- addResolver(new GlobalTemplateVariables.Time());
- addResolver(new GlobalTemplateVariables.User());
-
- // compilation unit
- addResolver(new File());
- addResolver(new PrimaryTypeName());
- addResolver(new ReturnType());
- addResolver(new Method());
- addResolver(new Type());
- addResolver(new Package());
- addResolver(new Project());
- addResolver(new Arguments());
-
- // java
- addResolver(new Array());
- addResolver(new ArrayType());
- addResolver(new ArrayElement());
- addResolver(new Index());
-// addResolver(new Iterator());
-// addResolver(new Collection());
-// addResolver(new Iterable());
-// addResolver(new IterableType());
-// addResolver(new IterableElement());
- addResolver(new Todo());
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public CompilationUnitContext createContext(IDocument document, int offset, int length, IJavaScriptUnit compilationUnit) {
- return new JavaContext(this, document, offset, length, compilationUnit);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.Position, org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public CompilationUnitContext createContext(IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit) {
- return new JavaContext(this, document, completionPosition, compilationUnit);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContext.java
deleted file mode 100644
index 444c0f3b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContext.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateTranslator;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * A context for javadoc.
- */
-public class JavaDocContext extends CompilationUnitContext {
-
- // tags
- private static final char HTML_TAG_BEGIN= '<';
- private static final char HTML_TAG_END= '>';
- private static final char JAVADOC_TAG_BEGIN= '@';
-
- /**
- * Creates a javadoc template context.
- *
- * @param type the context type.
- * @param document the document.
- * @param completionOffset the completion offset within the document.
- * @param completionLength the completion length within the document.
- * @param compilationUnit the compilation unit (may be <code>null</code>).
- */
- public JavaDocContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, IJavaScriptUnit compilationUnit) {
- super(type, document, completionOffset, completionLength, compilationUnit);
- }
-
- /**
- * Creates a javadoc template context.
- *
- * @param type the context type.
- * @param document the document.
- * @param completionPosition the position defining the completion offset and length
- * @param compilationUnit the compilation unit (may be <code>null</code>).
- *
- */
- public JavaDocContext(TemplateContextType type, IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit) {
- super(type, document, completionPosition, compilationUnit);
- }
-
- /*
- * @see TemplateContext#canEvaluate(Template templates)
- */
- public boolean canEvaluate(Template template) {
- String key= getKey();
-
- if (fForceEvaluation)
- return true;
-
- return
- template.matches(key, getContextType().getId()) &&
- (key.length() != 0) && template.getName().toLowerCase().startsWith(key.toLowerCase());
- }
-
- /*
- * @see DocumentTemplateContext#getStart()
- */
- public int getStart() {
- if (fIsManaged && getCompletionLength() > 0)
- return super.getStart();
-
- try {
- IDocument document= getDocument();
-
- if (getCompletionLength() == 0) {
- int start= getCompletionOffset();
-
- if ((start != 0) && (document.getChar(start - 1) == HTML_TAG_END))
- start--;
-
- while ((start != 0) && !Character.isWhitespace(document.getChar(start - 1)))
- start--;
-
- if ((start != 0) && !Character.isWhitespace(document.getChar(start - 1)))
- start--;
-
- // include html and javadoc tags
- if ((start != 0) && (
- (document.getChar(start - 1) == HTML_TAG_BEGIN) ||
- (document.getChar(start - 1) == JAVADOC_TAG_BEGIN)))
- {
- start--;
- }
-
- return start;
-
- }
-
- int start= getCompletionOffset();
- int end= getCompletionOffset() + getCompletionLength();
-
- while (start != 0 && !Character.isWhitespace(document.getChar(start - 1)))
- start--;
-
- while (start != end && Character.isWhitespace(document.getChar(start)))
- start++;
-
- if (start == end)
- start= getCompletionOffset();
-
- return start;
-
-
- } catch (BadLocationException e) {
- return getCompletionOffset();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.DocumentTemplateContext#getEnd()
- */
- public int getEnd() {
-
- if (fIsManaged || getCompletionLength() == 0)
- return super.getEnd();
-
- try {
- IDocument document= getDocument();
-
- int start= getCompletionOffset();
- int end= getCompletionOffset() + getCompletionLength();
-
- while (start != end && Character.isWhitespace(document.getChar(end - 1)))
- end--;
-
- return end;
-
- } catch (BadLocationException e) {
- return super.getEnd();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.DocumentTemplateContext#getKey()
- */
- public String getKey() {
-
- if (getCompletionLength() == 0)
- return super.getKey();
-
- try {
- IDocument document= getDocument();
-
- int start= getStart();
- int end= getCompletionOffset();
- return start <= end
- ? document.get(start, end - start)
- : ""; //$NON-NLS-1$
-
- } catch (BadLocationException e) {
- return super.getKey();
- }
- }
-
- /*
- * @see TemplateContext#evaluate(Template)
- */
- public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
- TemplateTranslator translator= new TemplateTranslator();
- TemplateBuffer buffer= translator.translate(template);
-
- getContextType().resolve(buffer, this);
-
- IPreferenceStore prefs= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean useCodeFormatter= prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER);
-
- IJavaScriptProject project= getJavaProject();
- JavaFormatter formatter= new JavaFormatter(TextUtilities.getDefaultLineDelimiter(getDocument()), getIndentation(), useCodeFormatter, project);
- formatter.format(buffer, this);
-
- return buffer;
- }
-
- /**
- * Returns the indentation level at the position of code completion.
- *
- * @return the indentation level at the position of the code completion
- */
- private int getIndentation() {
- int start= getStart();
- IDocument document= getDocument();
- try {
- IRegion region= document.getLineInformationOfOffset(start);
- String lineContent= document.get(region.getOffset(), region.getLength());
- IJavaScriptProject project= getJavaProject();
- return Strings.computeIndentUnits(lineContent, project);
- } catch (BadLocationException e) {
- return 0;
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContextType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContextType.java
deleted file mode 100644
index e835ba07..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaDocContextType.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-/**
- * A context type for javadoc.
- */
-public class JavaDocContextType extends CompilationUnitContextType {
-
- public static final String NAME= "jsdoc"; //$NON-NLS-1$
-
- /**
- * Creates a java context type.
- */
- public JavaDocContextType() {
- super(NAME);
-
- // global
- addResolver(new GlobalTemplateVariables.Cursor());
- addResolver(new GlobalTemplateVariables.LineSelection());
- addResolver(new GlobalTemplateVariables.WordSelection());
- addResolver(new GlobalTemplateVariables.Dollar());
- addResolver(new GlobalTemplateVariables.Date());
- addResolver(new GlobalTemplateVariables.Year());
- addResolver(new GlobalTemplateVariables.Time());
- addResolver(new GlobalTemplateVariables.User());
-
- // compilation unit
- addResolver(new File());
- addResolver(new PrimaryTypeName());
- addResolver(new Method());
- addResolver(new ReturnType());
- addResolver(new Arguments());
- addResolver(new Type());
- addResolver(new Package());
- addResolver(new Project());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public CompilationUnitContext createContext(IDocument document, int offset, int length, IJavaScriptUnit compilationUnit) {
- return new JavaDocContext(this, document, offset, length, compilationUnit);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.Position, org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public CompilationUnitContext createContext(IDocument document, Position completionPosition, IJavaScriptUnit compilationUnit) {
- return new JavaDocContext(this, document, completionPosition, compilationUnit);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaFormatter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaFormatter.java
deleted file mode 100644
index 87469519..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaFormatter.java
+++ /dev/null
@@ -1,354 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.rules.FastPartitioner;
-import org.eclipse.jface.text.source.LineRange;
-import org.eclipse.jface.text.templates.DocumentTemplateContext;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.RangeMarker;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IndentUtil;
-import org.eclipse.wst.jsdt.internal.ui.text.FastJavaPartitionScanner;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * A template editor using the Java formatter to format a template buffer.
- */
-public class JavaFormatter {
-
- private static final String COMMENT_START= "/*-"; //$NON-NLS-1$
- private static final String COMMENT_END= "*/"; //$NON-NLS-1$
-
- /** The line delimiter to use if code formatter is not used. */
- private final String fLineDelimiter;
- /** The initial indent level */
- private final int fInitialIndentLevel;
-
- /** The java partitioner */
- private boolean fUseCodeFormatter;
- private final IJavaScriptProject fProject;
-
- /**
- * Wraps a {@link TemplateBuffer} and tracks the variable offsets while changes to the buffer
- * occur. Whitespace variables are also tracked.
- */
- private static final class VariableTracker {
- private static final String CATEGORY= "__template_variables"; //$NON-NLS-1$
- private Document fDocument;
- private final TemplateBuffer fBuffer;
- private List fPositions;
-
- /**
- * Creates a new tracker.
- *
- * @param buffer the buffer to track
- * @throws MalformedTreeException
- * @throws BadLocationException
- */
- public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
- Assert.isLegal(buffer != null);
- fBuffer= buffer;
- fDocument= new Document(fBuffer.getString());
- installJavaStuff(fDocument);
- fDocument.addPositionCategory(CATEGORY);
- fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
- fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
- }
-
- /**
- * Installs a java partitioner with <code>document</code>.
- *
- * @param document the document
- */
- private static void installJavaStuff(Document document) {
- String[] types= new String[] {
- IJavaScriptPartitions.JAVA_DOC,
- IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_STRING,
- IJavaScriptPartitions.JAVA_CHARACTER,
- IDocument.DEFAULT_CONTENT_TYPE
- };
- FastPartitioner partitioner= new FastPartitioner(new FastJavaPartitionScanner(), types);
- partitioner.connect(document);
- document.setDocumentPartitioner(IJavaScriptPartitions.JAVA_PARTITIONING, partitioner);
- }
-
- /**
- * Returns the document with the buffer contents. Whitespace variables are decorated with
- * comments.
- *
- * @return the buffer document
- */
- public IDocument getDocument() {
- checkState();
- return fDocument;
- }
-
- private void checkState() {
- if (fDocument == null)
- throw new IllegalStateException();
- }
-
- /**
- * Restores any decorated regions and updates the buffer's variable offsets.
- *
- * @return the buffer.
- * @throws MalformedTreeException
- * @throws BadLocationException
- */
- public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
- checkState();
- TemplateVariable[] variables= fBuffer.getVariables();
- try {
- removeRangeMarkers(fPositions, fDocument, variables);
- } catch (BadPositionCategoryException x) {
- Assert.isTrue(false);
- }
- fBuffer.setContent(fDocument.get(), variables);
- fDocument= null;
-
- return fBuffer;
- }
-
- private List createRangeMarkers(TemplateVariable[] variables, IDocument document) throws MalformedTreeException, BadLocationException {
- Map markerToOriginal= new HashMap();
-
- MultiTextEdit root= new MultiTextEdit(0, document.getLength());
- List edits= new ArrayList();
- boolean hasModifications= false;
- for (int i= 0; i != variables.length; i++) {
- final TemplateVariable variable= variables[i];
- int[] offsets= variable.getOffsets();
-
- String value= variable.getDefaultValue();
- if (isWhitespaceVariable(value)) {
- // replace whitespace positions with unformattable comments
- String placeholder= COMMENT_START + value + COMMENT_END;
- for (int j= 0; j != offsets.length; j++) {
- ReplaceEdit replace= new ReplaceEdit(offsets[j], value.length(), placeholder);
- root.addChild(replace);
- hasModifications= true;
- markerToOriginal.put(replace, value);
- edits.add(replace);
- }
- } else {
- for (int j= 0; j != offsets.length; j++) {
- RangeMarker marker= new RangeMarker(offsets[j], value.length());
- root.addChild(marker);
- edits.add(marker);
- }
- }
- }
-
- if (hasModifications) {
- // update the document and convert the replaces to markers
- root.apply(document, TextEdit.UPDATE_REGIONS);
- }
-
- List positions= new ArrayList();
- for (Iterator it= edits.iterator(); it.hasNext();) {
- TextEdit edit= (TextEdit) it.next();
- try {
- // abuse TypedPosition to piggy back the original contents of the position
- final TypedPosition pos= new TypedPosition(edit.getOffset(), edit.getLength(), (String) markerToOriginal.get(edit));
- document.addPosition(CATEGORY, pos);
- positions.add(pos);
- } catch (BadPositionCategoryException x) {
- Assert.isTrue(false);
- }
- }
-
- return positions;
- }
-
- private boolean isWhitespaceVariable(String value) {
- int length= value.length();
- return length == 0 || Character.isWhitespace(value.charAt(0)) || Character.isWhitespace(value.charAt(length - 1));
- }
-
- private void removeRangeMarkers(List positions, IDocument document, TemplateVariable[] variables) throws MalformedTreeException, BadLocationException, BadPositionCategoryException {
-
- // revert previous changes
- for (Iterator it= positions.iterator(); it.hasNext();) {
- TypedPosition position= (TypedPosition) it.next();
- // remove and re-add in order to not confuse ExclusivePositionUpdater
- document.removePosition(CATEGORY, position);
- final String original= position.getType();
- if (original != null) {
- document.replace(position.getOffset(), position.getLength(), original);
- position.setLength(original.length());
- }
- document.addPosition(position);
- }
-
- Iterator it= positions.iterator();
- for (int i= 0; i != variables.length; i++) {
- TemplateVariable variable= variables[i];
-
- int[] offsets= new int[variable.getOffsets().length];
- for (int j= 0; j != offsets.length; j++)
- offsets[j]= ((Position) it.next()).getOffset();
-
- variable.setOffsets(offsets);
- }
-
- }
- }
-
- /**
- * Creates a JavaFormatter with the target line delimiter.
- *
- * @param lineDelimiter the line delimiter to use
- * @param initialIndentLevel the initial indentation level
- * @param useCodeFormatter <code>true</code> if the core code formatter should be used
- * @param project the java project from which to get the preferences, or <code>null</code> for workbench settings
- */
- public JavaFormatter(String lineDelimiter, int initialIndentLevel, boolean useCodeFormatter, IJavaScriptProject project) {
- fLineDelimiter= lineDelimiter;
- fUseCodeFormatter= useCodeFormatter;
- fInitialIndentLevel= initialIndentLevel;
- fProject= project;
- }
-
- /**
- * Formats the template buffer.
- * @param buffer
- * @param context
- * @throws BadLocationException
- */
- public void format(TemplateBuffer buffer, TemplateContext context) throws BadLocationException {
- try {
- VariableTracker tracker= new VariableTracker(buffer);
- IDocument document= tracker.getDocument();
-
- internalFormat(document, context);
- convertLineDelimiters(document);
- if (!isReplacedAreaEmpty(context))
- trimStart(document);
-
- tracker.updateBuffer();
- } catch (MalformedTreeException e) {
- throw new BadLocationException();
- }
- }
-
- /**
- * @param document
- * @param context
- * @throws BadLocationException
- */
- private void internalFormat(IDocument document, TemplateContext context) throws BadLocationException {
- if (fUseCodeFormatter) {
- // try to format and fall back to indenting
- try {
- format(document, (CompilationUnitContext) context);
- return;
- } catch (BadLocationException e) {
- // ignore and indent
- } catch (MalformedTreeException e) {
- // ignore and indent
- }
- }
- indent(document);
- }
-
- private void convertLineDelimiters(IDocument document) throws BadLocationException {
- int lines= document.getNumberOfLines();
- for (int line= 0; line < lines; line++) {
- IRegion region= document.getLineInformation(line);
- String lineDelimiter= document.getLineDelimiter(line);
- if (lineDelimiter != null)
- document.replace(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter);
- }
- }
-
- private void trimStart(IDocument document) throws BadLocationException {
- int i= 0;
- while ((i != document.getLength()) && Character.isWhitespace(document.getChar(i)))
- i++;
-
- document.replace(0, i, ""); //$NON-NLS-1$
- }
-
- private boolean isReplacedAreaEmpty(TemplateContext context) {
- // don't trim the buffer if the replacement area is empty
- // case: surrounding empty lines with block
- if (context instanceof DocumentTemplateContext) {
- DocumentTemplateContext dtc= (DocumentTemplateContext) context;
- if (dtc.getStart() == dtc.getCompletionOffset())
- try {
- if (dtc.getDocument().get(dtc.getStart(), dtc.getEnd() - dtc.getStart()).trim().length() == 0)
- return true;
- } catch (BadLocationException x) {
- // ignore - this may happen when the document was modified after the initial invocation, and the
- // context does not track the changes properly - don't trim in that case
- return true;
- }
- }
- return false;
- }
-
- private void format(IDocument doc, CompilationUnitContext context) throws BadLocationException {
- Map options;
- IJavaScriptProject project= context.getJavaProject();
- if (project != null)
- options= project.getOptions(true);
- else
- options= JavaScriptCore.getOptions();
-
- String contents= doc.get();
- int[] kinds= { CodeFormatter.K_EXPRESSION, CodeFormatter.K_STATEMENTS, CodeFormatter.K_UNKNOWN};
- TextEdit edit= null;
- for (int i= 0; i < kinds.length && edit == null; i++) {
- edit= CodeFormatterUtil.format2(kinds[i], contents, fInitialIndentLevel, fLineDelimiter, options);
- }
-
- if (edit == null)
- throw new BadLocationException(); // fall back to indenting
-
- edit.apply(doc, TextEdit.UPDATE_REGIONS);
- }
-
- private void indent(IDocument document) throws BadLocationException, MalformedTreeException {
- // first line
- int offset= document.getLineOffset(0);
- document.replace(offset, 0, CodeFormatterUtil.createIndentString(fInitialIndentLevel, fProject));
-
- // following lines
- int lineCount= document.getNumberOfLines();
- IndentUtil.indentLines(document, new LineRange(1, lineCount - 1), fProject, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java
deleted file mode 100644
index 8c0b1c80..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class JavaTemplateMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaTemplateMessages.class.getName();
-
- private JavaTemplateMessages() {
- // Do not instantiate
- }
-
- public static String ContextType_error_multiple_cursor_variables;
- public static String CompilationUnitContextType_variable_description_file;
- public static String CompilationUnitContextType_variable_description_primary_type_name;
- public static String CompilationUnitContextType_variable_description_enclosing_method;
- public static String CompilationUnitContextType_variable_description_enclosing_type;
- public static String CompilationUnitContextType_variable_description_enclosing_package;
- public static String CompilationUnitContextType_variable_description_enclosing_project;
- public static String CompilationUnitContextType_variable_description_enclosing_method_arguments;
- public static String CompilationUnitContextType_variable_description_return_type;
- public static String JavaContextType_variable_description_array;
- public static String JavaContextType_variable_description_array_type;
- public static String JavaContextType_variable_description_array_element;
- public static String JavaContextType_variable_description_index;
-// public static String JavaContextType_variable_description_collection;
-// public static String JavaContextType_variable_description_iterable;
-// public static String JavaContextType_variable_description_iterable_type;
-// public static String JavaContextType_variable_description_iterable_element;
-// public static String JavaContextType_variable_description_iterator;
- public static String JavaContextType_variable_description_todo;
- public static String JavaContext_error_title;
- public static String JavaContext_error_message;
- public static String CodeTemplateContextType_variable_description_todo;
- public static String CodeTemplateContextType_variable_description_packdeclaration;
- public static String CodeTemplateContextType_variable_description_typedeclaration;
- public static String CodeTemplateContextType_variable_description_getterfieldname;
- public static String CodeTemplateContextType_variable_description_getterfieldtype;
- public static String CodeTemplateContextType_variable_description_fieldname;
- public static String CodeTemplateContextType_variable_description_fieldtype;
- public static String CodeTemplateContextType_variable_description_barefieldname;
- public static String CodeTemplateContextType_variable_description_param;
- public static String CodeTemplateContextType_variable_description_typecomment;
- public static String CodeTemplateContextType_variable_description_exceptiontype;
- public static String CodeTemplateContextType_variable_description_exceptionvar;
- public static String CodeTemplateContextType_variable_description_enclosingtype;
- public static String CodeTemplateContextType_variable_description_typename;
- public static String CodeTemplateContextType_variable_description_enclosingmethod;
- public static String CodeTemplateContextType_variable_description_bodystatement;
- public static String CodeTemplateContextType_variable_description_returntype;
- public static String CodeTemplateContextType_variable_description_tags;
- public static String CodeTemplateContextType_variable_description_see_overridden_tag;
- public static String CodeTemplateContextType_variable_description_see_target_tag;
- public static String CodeTemplateContextType_variable_description_filename;
- public static String CodeTemplateContextType_variable_description_filecomment;
- public static String CodeTemplateContextType_variable_description_packagename;
- public static String CodeTemplateContextType_variable_description_projectname;
- public static String CodeTemplateContextType_validate_unknownvariable;
- public static String CodeTemplateContextType_validate_missingvariable;
- public static String CodeTemplateContextType_validate_invalidcomment;
- public static String TemplateSet_error_missing_attribute;
- public static String TemplateSet_error_read;
- public static String TemplateSet_error_write;
- public static String Context_error_cannot_evaluate;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaTemplateMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties
deleted file mode 100644
index b394c3a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties
+++ /dev/null
@@ -1,73 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-ContextType_error_multiple_cursor_variables=Template has multiple cursor variables.
-
-# Java Only stuff
-CompilationUnitContextType_variable_description_file=Filename of JavaScript file
-CompilationUnitContextType_variable_description_primary_type_name=Filename without extension
-CompilationUnitContextType_variable_description_enclosing_method=Enclosing function name
-CompilationUnitContextType_variable_description_enclosing_type=Enclosing type name
-CompilationUnitContextType_variable_description_enclosing_package=Enclosing package name
-CompilationUnitContextType_variable_description_enclosing_project=Enclosing project name
-CompilationUnitContextType_variable_description_enclosing_method_arguments=Argument names of enclosing function
-CompilationUnitContextType_variable_description_return_type=Enclosing function return type
-
-JavaContextType_variable_description_array=A proposal for an array
-JavaContextType_variable_description_array_type=A proposal for the element type of an array
-JavaContextType_variable_description_array_element=A proposal for the element name of an array
-JavaContextType_variable_description_index=A proposal for an index (int)
-#JavaContextType_variable_description_collection=A proposal for a collection (java.util.Collection)
-#JavaContextType_variable_description_iterable=A proposal for an iterable (array or java.lang.Iterable)
-#JavaContextType_variable_description_iterable_type=A proposal for the element type of an iterable (array or java.lang.Iterable)
-#JavaContextType_variable_description_iterable_element=A proposal for the element name of an iterable (array or java.lang.Iterable)
-#JavaContextType_variable_description_iterator=A proposal for an iterator (java.util.Iterator)
-JavaContextType_variable_description_todo=Todo task tag
-
-JavaContext_error_title=Template Error
-JavaContext_error_message=Template file incomplete or has errors. You can load the default templates from the template preferences page (Java>Templates).
-
-CodeTemplateContextType_variable_description_todo=Todo task tag
-CodeTemplateContextType_variable_description_packdeclaration=Package declaration of the new type
-CodeTemplateContextType_variable_description_typedeclaration=Generated type declaration
-CodeTemplateContextType_variable_description_getterfieldname=The name of field to set or get
-CodeTemplateContextType_variable_description_getterfieldtype=The type of the field to set or get
-CodeTemplateContextType_variable_description_fieldname=The name of field
-CodeTemplateContextType_variable_description_fieldtype=The type of the field
-CodeTemplateContextType_variable_description_barefieldname=The name of field to set or get without pre- or suffix
-CodeTemplateContextType_variable_description_param=The parameter passed into the setter function
-CodeTemplateContextType_variable_description_typecomment=Content of code template 'Comments > Types'
-CodeTemplateContextType_variable_description_exceptiontype=The type of the caught exception
-CodeTemplateContextType_variable_description_exceptionvar=The variable name of the caught exception
-CodeTemplateContextType_variable_description_enclosingtype=The enclosing type
-CodeTemplateContextType_variable_description_typename=Name of the current type
-CodeTemplateContextType_variable_description_enclosingmethod=The enclosing function
-CodeTemplateContextType_variable_description_bodystatement=Return statement or super call
-CodeTemplateContextType_variable_description_returntype=Return type of the enclosing function
-CodeTemplateContextType_variable_description_tags=Generated JSDoc tags (@param, @return...)
-CodeTemplateContextType_variable_description_see_overridden_tag=See tag pointing to the overridden function (@see T#m())
-CodeTemplateContextType_variable_description_see_target_tag=See tag pointing to the target function (@see T#m())
-
-CodeTemplateContextType_variable_description_filename=Name of the enclosing JavaScript file
-CodeTemplateContextType_variable_description_filecomment=Content of code template 'Comments > Files'
-CodeTemplateContextType_variable_description_packagename=Name of the enclosing package
-CodeTemplateContextType_variable_description_projectname=Name of the enclosing project
-
-CodeTemplateContextType_validate_unknownvariable=Variable ''{0}'' is unknown.
-CodeTemplateContextType_validate_missingvariable=Variable ''{0}'' is required.
-CodeTemplateContextType_validate_invalidcomment=Pattern is not a valid JavaScript comment.
-
-TemplateSet_error_missing_attribute= Cannot read template: an attribute is missing.
-TemplateSet_error_read= Cannot read template file.
-TemplateSet_error_write= Cannot write template file.
-
-Context_error_cannot_evaluate= Cannot evaluate the template.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java
deleted file mode 100644
index 9d97c150..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.jface.text.templates.TemplateVariableType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-
-
-public final class JavaVariable extends MultiVariable {
- private String fParamType;
-
- public JavaVariable(TemplateVariableType type, String name, int[] offsets) {
- super(type, name, offsets);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable#toString(java.lang.Object)
- *
- */
- public String toString(Object object) {
- if (object instanceof Variable)
- return ((Variable) object).getName();
- return super.toString(object);
- }
-
- /**
- * Returns the type given as parameter to this variable.
- *
- * @return the type given as parameter to this variable
- */
- public String getParamType() {
- return fParamType;
- }
-
- /**
- * @param paramType the paramType
- *
- */
- public void setParamType(String paramType) {
- fParamType= paramType;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java
deleted file mode 100644
index de908eac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-
-/**
- * Resolves template variables to a local variable that is assignment-compatible with the variable
- * instance' class parameter.
- *
- *
- */
-public class LocalVarResolver extends TemplateVariableResolver {
-
- private final String fDefaultType;
- private String fType;
-
- /**
- * Default ctor for instantiation by the extension point.
- */
- public LocalVarResolver() {
- this("java.lang.Object"); //$NON-NLS-1$
- }
-
- LocalVarResolver(String defaultType) {
- fDefaultType= defaultType;
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- List params= variable.getVariableType().getParams();
- if (params.size() == 0)
- fType= fDefaultType;
- else
- fType= (String) params.get(0);
-
- if (variable instanceof JavaVariable) {
- JavaContext jc= (JavaContext) context;
- JavaVariable jv= (JavaVariable) variable;
- jv.setParamType(fType);
- Variable[] variables= jc.getLocalVariables(fType);
- if (variables.length > 0) {
- jv.setChoices(variables);
- jc.markAsUsed(jv.getDefaultValue());
- } else {
- super.resolve(variable, context);
- return;
- }
- if (variables.length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
- } else
- super.resolve(variable, context);
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolveAll(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] iterables= jc.getLocalVariables(fType);
- String[] names= new String[iterables.length];
- for (int i= 0; i < iterables.length; i++)
- names[i]= iterables[i].getName();
- if (names.length > 0)
- jc.markAsUsed(names[0]);
- return names;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java
deleted file mode 100644
index f49faea6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids: sdavids@gmx.de - see bug 25376
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-
-/**
- * Resolves template variables to non-conflicting names that adhere to the naming conventions and
- * match the parameter (fully qualified name).
- *
- *
- */
-public class NameResolver extends TemplateVariableResolver {
-
- private final String fDefaultType;
-
- /**
- * Default ctor for instantiation by the extension point.
- */
- public NameResolver() {
- this("java.lang.Object"); //$NON-NLS-1$
- }
-
- NameResolver(String defaultType) {
- fDefaultType= defaultType;
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- List params= variable.getVariableType().getParams();
- String param;
- if (params.size() == 0)
- param= fDefaultType;
- else
- param= (String) params.get(0);
- JavaContext jc= (JavaContext) context;
- TemplateVariable ref= jc.getTemplateVariable(param);
- MultiVariable mv= (MultiVariable) variable;
- if (ref instanceof MultiVariable) {
- // reference is another variable
- MultiVariable refVar= (MultiVariable) ref;
- jc.addDependency(refVar, mv);
-
- refVar.getAllChoices();
- Object[] types= flatten(refVar.getAllChoices());
- for (int i= 0; i < types.length; i++) {
- String[] names= jc.suggestVariableNames(mv.toString(types[i]));
- mv.setChoices(types[i], names);
- }
-
- mv.setKey(refVar.getCurrentChoice());
- jc.markAsUsed(mv.getDefaultValue());
- } else {
- // reference is a Java type name
- jc.addImport(param);
- String[] names= jc.suggestVariableNames(param);
- mv.setChoices(names);
- jc.markAsUsed(names[0]);
- }
- }
-
- private Object[] flatten(Object[][] allValues) {
- List flattened= new ArrayList(allValues.length);
- for (int i= 0; i < allValues.length; i++) {
- flattened.addAll(Arrays.asList(allValues[i]));
- }
- return flattened.toArray(new Object[flattened.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/SignatureUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/SignatureUtil.java
deleted file mode 100644
index d20356b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/SignatureUtil.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-
-/**
- * Utilities for Signature operations.
- *
- * @see Signature
- *
- */
-public final class SignatureUtil {
-
- /**
- * The signature of <code>java.lang.Object</code> ({@value}).
- */
- private static final String OBJECT_SIGNATURE= "Ljava.lang.Object;"; //$NON-NLS-1$
-
- /**
- * The signature of <code>Boolean</code> ({@value}).
- */
- public static final String BOOLEAN_SIGNATURE= "LBoolean;"; //$NON-NLS-1$
-
- private SignatureUtil() {
- // do not instantiate
- }
-
- /**
- * Returns <code>true</code> if <code>signature</code> is the
- * signature of the <code>java.lang.Object</code> type.
- *
- * @param signature the signature
- * @return <code>true</code> if <code>signature</code> is the
- * signature of the <code>java.lang.Object</code> type,
- * <code>false</code> otherwise
- */
- public static boolean isJavaLangObject(String signature) {
- return OBJECT_SIGNATURE.equals(signature);
- }
-
- /**
- * Returns the fully qualified type name of the given signature, with any
- * type parameters and arrays erased.
- *
- * @param signature the signature
- * @return the fully qualified type name of the signature
- */
- public static String stripSignatureToFQN(String signature) throws IllegalArgumentException {
- signature= Signature.getElementType(signature);
- return Signature.toString(signature);
- }
-
- /**
- * Returns the qualified signature corresponding to
- * <code>signature</code>.
- *
- * @param signature the signature to qualify
- * @param context the type inside which an unqualified type will be
- * resolved to find the qualifier, or <code>null</code> if no
- * context is available
- * @return the qualified signature
- */
- public static String qualifySignature(final String signature, final IType context) {
- if (context == null)
- return signature;
-
- String qualifier= Signature.getSignatureQualifier(signature);
- if (qualifier.length() > 0)
- return signature;
-
- String elementType= Signature.getElementType(signature);
- String erasure= elementType;
- String simpleName= Signature.getSignatureSimpleName(erasure);
- String genericSimpleName= Signature.getSignatureSimpleName(elementType);
-
- int dim= Signature.getArrayCount(signature);
-
- try {
- String[][] strings= context.resolveType(simpleName);
- if (strings != null && strings.length > 0)
- qualifier= strings[0][0];
- } catch (JavaScriptModelException e) {
- // ignore - not found
- }
-
- if (qualifier.length() == 0)
- return signature;
-
- String qualifiedType= Signature.toQualifiedName(new String[] {qualifier, genericSimpleName});
- String qualifiedSignature= Signature.createTypeSignature(qualifiedType, true);
- String newSignature= Signature.createArraySignature(qualifiedSignature, dim);
-
- return newSignature;
- }
-
- /**
- * Takes a method signature
- * <code>[&lt; typeVariableName : formalTypeDecl &gt;] ( paramTypeSig1* ) retTypeSig</code>
- * and returns it with any parameter signatures filtered through
- * <code>getLowerBound</code> and the return type filtered through
- * <code>getUpperBound</code>. Any preceding formal type variable
- * declarations are removed.
- * <p>
- * TODO this is a temporary workaround for
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=83600
- * </p>
- *
- * @param signature the method signature to convert
- * @return the signature with no bounded types
- */
- public static char[] unboundedSignature(char[] signature) {
- if (signature == null || signature.length < 2)
- return signature;
-
- StringBuffer res= new StringBuffer("("); //$NON-NLS-1$
- char[][] parameters= Signature.getParameterTypes(signature);
- for (int i= 0; i < parameters.length; i++) {
- char[] param= parameters[i];
- res.append(param);
- }
- res.append(')');
- res.append(Signature.getReturnType(signature));
- return res.toString().toCharArray();
- }
-
- private static int typeEnd(char[] signature, int pos) {
- int depth= 0;
- while (pos < signature.length) {
- switch (signature[pos]) {
- case Signature.C_SEMICOLON:
- if (depth == 0)
- return pos + 1;
- break;
- }
- pos++;
- }
- return pos + 1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java
deleted file mode 100644
index bbd1d1b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.templates.ContextTypeRegistry;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * <code>TemplateSet</code> manages a collection of templates and makes them
- * persistent.
- *
- * @deprecated use TemplateStore instead
- *
- */
-public class TemplateSet {
-
- private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
- private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
- private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$
-
- private List fTemplates= new ArrayList();
- private String fTemplateTag;
-
- private static final int TEMPLATE_PARSE_EXCEPTION= 10002;
- private static final int TEMPLATE_IO_EXCEPTION= 10005;
- private ContextTypeRegistry fRegistry;
-
- public TemplateSet(String templateTag, ContextTypeRegistry registry) {
- fTemplateTag= templateTag;
- fRegistry= registry;
- }
-
- /**
- * Convenience method for reading templates from a file.
- *
- * @param file
- * @param allowDuplicates
- * @see #addFromStream(InputStream, boolean)
- * @throws CoreException
- */
- public void addFromFile(File file, boolean allowDuplicates) throws CoreException {
- InputStream stream= null;
-
- try {
- stream= new FileInputStream(file);
- addFromStream(stream, allowDuplicates);
-
- } catch (IOException e) {
- throwReadException(e);
-
- } finally {
- try {
- if (stream != null)
- stream.close();
- } catch (IOException e) {
- // just exit
- }
- }
- }
-
- public String getTemplateTag() {
- return fTemplateTag;
- }
-
-
- /**
- * Reads templates from a XML stream and adds them to the templates
- *
- * @param stream
- * @param allowDuplicates
- * @throws CoreException
- */
- public void addFromStream(InputStream stream, boolean allowDuplicates) throws CoreException {
- try {
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- DocumentBuilder parser= factory.newDocumentBuilder();
- Document document= parser.parse(new InputSource(stream));
-
- NodeList elements= document.getElementsByTagName(getTemplateTag());
-
- int count= elements.getLength();
- for (int i= 0; i != count; i++) {
- Node node= elements.item(i);
- NamedNodeMap attributes= node.getAttributes();
-
- if (attributes == null)
- continue;
-
- String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
- String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
- if (name == null || description == null)
- continue;
-
- String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
-
- if (name == null || description == null || context == null)
- throw new SAXException(JavaTemplateMessages.TemplateSet_error_missing_attribute);
-
- StringBuffer buffer= new StringBuffer();
- NodeList children= node.getChildNodes();
- for (int j= 0; j != children.getLength(); j++) {
- String value= children.item(j).getNodeValue();
- if (value != null)
- buffer.append(value);
- }
- String pattern= buffer.toString().trim();
-
- Template template= new Template(name, description, context, pattern);
-
- String message= validateTemplate(template);
- if (message == null) {
- if (!allowDuplicates) {
- Template[] templates= getTemplates(name);
- for (int k= 0; k < templates.length; k++) {
- remove(templates[k]);
- }
- }
- add(template);
- } else {
- throwReadException(null);
- }
- }
- } catch (ParserConfigurationException e) {
- throwReadException(e);
- } catch (IOException e) {
- throwReadException(e);
- } catch (SAXException e) {
- throwReadException(e);
- }
- }
-
- protected String validateTemplate(Template template) {
- TemplateContextType type= fRegistry.getContextType(template.getContextTypeId());
- if (type == null) {
- return "Unknown context type: " + template.getContextTypeId(); //$NON-NLS-1$
- }
- try {
- type.validate(template.getPattern());
- return null;
- } catch (TemplateException e) {
- return e.getMessage();
- }
- }
-
- private String getAttributeValue(NamedNodeMap attributes, String name) {
- Node node= attributes.getNamedItem(name);
-
- return node == null
- ? null
- : node.getNodeValue();
- }
-
- /**
- * Convenience method for saving to a file.
- *
- * @param file the file
- * @throws CoreException in case the save operation fails
- * @see #saveToStream(OutputStream)
- */
- public void saveToFile(File file) throws CoreException {
- OutputStream stream= null;
-
- try {
- stream= new FileOutputStream(file);
- saveToStream(stream);
-
- } catch (IOException e) {
- throwWriteException(e);
-
- } finally {
- try {
- if (stream != null)
- stream.close();
- } catch (IOException e) {
- // just exit
- }
- }
- }
-
- /**
- * Saves the template set as XML.
- *
- * @param stream the stream
- * @throws CoreException in case the save operation fails
- */
- public void saveToStream(OutputStream stream) throws CoreException {
- try {
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- DocumentBuilder builder= factory.newDocumentBuilder();
- Document document= builder.newDocument();
-
- Node root= document.createElement("templates"); //$NON-NLS-1$
- document.appendChild(root);
-
- for (int i= 0; i != fTemplates.size(); i++) {
- Template template= (Template) fTemplates.get(i);
-
- Node node= document.createElement(getTemplateTag());
- root.appendChild(node);
-
- NamedNodeMap attributes= node.getAttributes();
-
- Attr name= document.createAttribute(NAME_ATTRIBUTE);
- name.setValue(template.getName());
- attributes.setNamedItem(name);
-
- Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
- description.setValue(template.getDescription());
- attributes.setNamedItem(description);
-
- Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
- context.setValue(template.getContextTypeId());
- attributes.setNamedItem(context);
-
- Text pattern= document.createTextNode(template.getPattern());
- node.appendChild(pattern);
- }
-
-
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
- DOMSource source = new DOMSource(document);
- StreamResult result = new StreamResult(stream);
-
- transformer.transform(source, result);
-
- } catch (ParserConfigurationException e) {
- throwWriteException(e);
- } catch (TransformerException e) {
- throwWriteException(e);
- }
- }
-
- private static void throwReadException(Throwable t) throws CoreException {
- int code;
- if (t instanceof SAXException)
- code= TEMPLATE_PARSE_EXCEPTION;
- else
- code= TEMPLATE_IO_EXCEPTION;
-// IStatus status= JavaUIStatus.createError(code, TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$
-// throw new JavaUIException(status);
- throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", code, JavaTemplateMessages.TemplateSet_error_read, t)); //$NON-NLS-1$
- }
-
- private static void throwWriteException(Throwable t) throws CoreException {
-// IStatus status= JavaUIStatus.createError(IJavaStatusConstants.TEMPLATE_IO_EXCEPTION,
-// TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$
-// throw new JavaUIException(status);
- throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", TEMPLATE_IO_EXCEPTION, JavaTemplateMessages.TemplateSet_error_write, t)); //$NON-NLS-1$
- }
-
- /**
- * Adds a template to the set.
- *
- * @param template the template to add to the set
- */
- public void add(Template template) {
- if (exists(template))
- return; // ignore duplicate
-
- fTemplates.add(template);
- }
-
- private boolean exists(Template template) {
- for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) {
- Template anotherTemplate = (Template) iterator.next();
-
- if (template.equals(anotherTemplate))
- return true;
- }
-
- return false;
- }
-
- /**
- * Removes a template to the set.
- *
- * @param template the template to remove from the set
- */
- public void remove(Template template) {
- fTemplates.remove(template);
- }
-
- /**
- * Empties the set.
- */
- public void clear() {
- fTemplates.clear();
- }
-
- /**
- * Returns all templates.
- *
- * @return all templates
- */
- public Template[] getTemplates() {
- return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]);
- }
-
- /**
- * Returns all templates with a given name.
- *
- * @param name the template name
- * @return the templates with the given name
- */
- public Template[] getTemplates(String name) {
- ArrayList res= new ArrayList();
- for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) {
- Template curr= (Template) iterator.next();
- if (curr.getName().equals(name)) {
- res.add(curr);
- }
- }
- return (Template[]) res.toArray(new Template[res.size()]);
- }
-
- /**
- * Returns the first templates with the given name.
- *
- * @param name the template name
- * @return the first template with the given name
- */
- public Template getFirstTemplate(String name) {
- for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) {
- Template curr= (Template) iterator.next();
- if (curr.getName().equals(name)) {
- return curr;
- }
- }
- return null;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/Templates.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/Templates.java
deleted file mode 100644
index d7278d0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/Templates.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * <code>Templates</code> gives access to the available templates.
- *
- * @deprecated As of 3.0, replaced by {@link org.eclipse.jface.text.templates.persistence.TemplateStore}
- */
-public class Templates extends org.eclipse.wst.jsdt.internal.corext.template.java.TemplateSet {
-
- private static final String TEMPLATE_FILE= "templates.xml"; //$NON-NLS-1$
-
- /** Singleton. */
- private static Templates fgTemplates;
-
- /**
- * Returns an instance of templates.
- *
- * @return an instance of templates
- * @deprecated As of 3.0, replaced by
- * {@link org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin#getTemplateStore()}
- */
- public static Templates getInstance() {
- if (fgTemplates == null)
- fgTemplates= new Templates();
-
- return fgTemplates;
- }
-
- public Templates() {
- super("template", JavaScriptPlugin.getDefault().getTemplateContextRegistry()); //$NON-NLS-1$
- create();
- }
-
-
- private void create() {
-
- try {
- File templateFile= getTemplateFile();
- if (templateFile.exists()) {
- addFromFile(templateFile, false);
- }
-
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- clear();
- }
-
- }
-
- /**
- * Resets the template set.
- *
- * @throws CoreException in case the reset operation fails
- */
- public void reset() throws CoreException {
- }
-
- /**
- * Resets the template set with the default templates.
- *
- * @throws CoreException in case the restore operation fails
- */
- public void restoreDefaults() throws CoreException {
- }
-
- /**
- * Saves the template set.
- *
- * @throws CoreException in case the save operation fails
- */
- public void save() throws CoreException {
- }
-
- private static File getTemplateFile() {
- IPath path= JavaScriptPlugin.getDefault().getStateLocation();
- path= path.append(TEMPLATE_FILE);
-
- return path.toFile();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java
deleted file mode 100644
index 081f96fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.MultiVariable;
-
-/**
- * Resolves to the lower bound of a type argument of another template variable.
- *
- *
- */
-public class TypeVariableResolver extends TemplateVariableResolver {
-
- public TypeVariableResolver() {
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- *
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- if (!(variable instanceof MultiVariable)) {
- super.resolve(variable, context);
- return;
- }
- MultiVariable mv= (MultiVariable) variable;
- List params= variable.getVariableType().getParams();
- if (params.isEmpty()) {
- super.resolve(variable, context);
- return;
- }
-
- JavaContext jc= (JavaContext) context;
- String reference= (String) params.get(0);
- int index= 0;
- if (params.size() > 1) {
- String indexParam= (String) params.get(1);
- try {
- index= Integer.parseInt(indexParam);
- } catch (NumberFormatException x) {
- }
- }
- TemplateVariable refVar= jc.getTemplateVariable(reference);
- if (refVar instanceof JavaVariable) {
- JavaVariable jvar= (JavaVariable) refVar;
- resolve(mv, jvar, index, jc);
-
- return;
- }
-
-
- super.resolve(variable, context);
- }
-
- private void resolve(MultiVariable mv, JavaVariable master, int index, JavaContext context) {
- Object[] choices= master.getChoices();
- if (choices instanceof Variable[]) {
- context.addDependency(master, mv);
- Variable[] variables= (Variable[]) choices;
- String type= master.getParamType();
- for (int i= 0; i < choices.length; i++) {
- String[] bounds= variables[i].getTypeArgumentBoundSignatures(type, index);
- for (int j= 0; j < bounds.length; j++)
- bounds[j]= Signature.getSignatureSimpleName(bounds[j]);
- mv.setChoices(variables[i], bounds);
- }
- mv.setKey(master.getCurrentChoice());
- } else {
- super.resolve(mv, context);
- return;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java
deleted file mode 100644
index 41ff456f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids: sdavids@gmx.de - see bug 25376
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.template.java;
-
-import java.util.List;
-
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitCompletion.Variable;
-
-/**
- * Resolves template variables to a local variable that is assignment-compatible with the variable
- * instance' class parameter.
- *
- *
- */
-public class VarResolver extends TemplateVariableResolver {
-
- private final String fDefaultType;
- private String fType;
-
- /**
- * Default ctor for instantiation by the extension point.
- */
- public VarResolver() {
- this("java.lang.Object"); //$NON-NLS-1$
- }
-
- VarResolver(String defaultType) {
- fDefaultType= defaultType;
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
- */
- public void resolve(TemplateVariable variable, TemplateContext context) {
- List params= variable.getVariableType().getParams();
- if (params.size() == 0)
- fType= fDefaultType;
- else
- fType= (String) params.get(0);
-
- if (variable instanceof JavaVariable) {
- JavaContext jc= (JavaContext) context;
- JavaVariable jv= (JavaVariable) variable;
- jv.setParamType(fType);
- Variable[] localLariables= jc.getLocalVariables(fType);
- Variable[] fields= jc.getFields(fType);
- Variable[] variables= new Variable[localLariables.length + fields.length];
- System.arraycopy(fields, 0, variables, 0, fields.length);
- System.arraycopy(localLariables, 0, variables, fields.length, localLariables.length);
-
- if (variables.length > 0) {
- jv.setChoices(variables);
- jc.markAsUsed(jv.getDefaultValue());
- } else {
- super.resolve(variable, context);
- return;
- }
- if (variables.length > 1)
- variable.setUnambiguous(false);
- else
- variable.setUnambiguous(isUnambiguous(context));
- } else
- super.resolve(variable, context);
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolveAll(org.eclipse.jface.text.templates.TemplateContext)
- */
- protected String[] resolveAll(TemplateContext context) {
- JavaContext jc= (JavaContext) context;
- Variable[] localVariables= jc.getLocalVariables(fType);
- Variable[] fields= jc.getFields(fType);
- Variable[] variables= new Variable[localVariables.length + fields.length];
- System.arraycopy(fields, 0, variables, 0, fields.length);
- System.arraycopy(localVariables, 0, variables, fields.length, localVariables.length);
-
- String[] names= new String[variables.length];
- for (int i= 0; i < variables.length; i++)
- names[i]= variables[i].getName();
- if (names.length > 0)
- jc.markAsUsed(names[0]);
- return names;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java
deleted file mode 100644
index 39c48470..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/CodeFormatterUtil.java
+++ /dev/null
@@ -1,383 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class CodeFormatterUtil {
-
- /**
- * Creates a string that represents the given number of indentation units.
- * The returned string can contain tabs and/or spaces depending on the core
- * formatter preferences.
- *
- * @param indentationUnits the number of indentation units to generate
- * @param project the project from which to get the formatter settings,
- * <code>null</code> if the workspace default should be used
- * @return the indent string
- */
- public static String createIndentString(int indentationUnits, IJavaScriptProject project) {
- Map options= project != null ? project.getOptions(true) : JavaScriptCore.getOptions();
- return ToolFactory.createCodeFormatter(options).createIndentationString(indentationUnits);
- }
-
- /**
- * Gets the current tab width.
- *
- * @param project The project where the source is used, used for project
- * specific options or <code>null</code> if the project is unknown
- * and the workspace default should be used
- * @return The tab width
- */
- public static int getTabWidth(IJavaScriptProject project) {
- /*
- * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used
- * by the core formatter.
- * We piggy back the visual tab length setting in that preference in
- * that case.
- */
- String key;
- if (JavaScriptCore.SPACE.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
- key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
- else
- key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
-
- return getCoreOption(project, key, 4);
- }
-
- /**
- * Returns the current indent width.
- *
- * @param project the project where the source is used or <code>null</code>
- * if the project is unknown and the workspace default should be used
- * @return the indent width
- *
- */
- public static int getIndentWidth(IJavaScriptProject project) {
- String key;
- if (DefaultCodeFormatterConstants.MIXED.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
- key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
- else
- key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
-
- return getCoreOption(project, key, 4);
- }
-
- /**
- * Returns the possibly <code>project</code>-specific core preference
- * defined under <code>key</code>.
- *
- * @param project the project to get the preference from, or
- * <code>null</code> to get the global preference
- * @param key the key of the preference
- * @return the value of the preference
- *
- */
- private static String getCoreOption(IJavaScriptProject project, String key) {
- if (project == null)
- return JavaScriptCore.getOption(key);
- return project.getOption(key, true);
- }
-
- /**
- * Returns the possibly <code>project</code>-specific core preference
- * defined under <code>key</code>, or <code>def</code> if the value is
- * not a integer.
- *
- * @param project the project to get the preference from, or
- * <code>null</code> to get the global preference
- * @param key the key of the preference
- * @param def the default value
- * @return the value of the preference
- *
- */
- private static int getCoreOption(IJavaScriptProject project, String key, int def) {
- try {
- return Integer.parseInt(getCoreOption(project, key));
- } catch (NumberFormatException e) {
- return def;
- }
- }
-
- // transition code
-
- /**
- * Old API. Consider to use format2 (TextEdit)
- */
- public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) {
- return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options);
- }
-
- public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, IJavaScriptProject project) {
- Map options= project != null ? project.getOptions(true) : null;
- return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options);
- }
-
-
- /**
- * Old API. Consider to use format2 (TextEdit)
- */
- public static String format(int kind, String string, int offset, int length, int indentationLevel, int[] positions, String lineSeparator, Map options) {
- TextEdit edit= format2(kind, string, offset, length, indentationLevel, lineSeparator, options);
- if (edit == null) {
- //JavaScriptPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. kind: " + kind + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$
- return string.substring(offset, offset + length);
- }
- String formatted= getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options);
- return formatted.substring(offset, formatted.length() - (string.length() - (offset + length)));
- }
-
- /**
- * Old API. Consider to use format2 (TextEdit)
- */
- public static String format(ASTNode node, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) {
-
- TextEdit edit= format2(node, string, indentationLevel, lineSeparator, options);
- if (edit == null) {
- //JavaScriptPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. node: " + node.getNodeType() + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$
- return string;
- }
- return getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options);
- }
-
- private static String getOldAPICompatibleResult(String string, TextEdit edit, int indentationLevel, int[] positions, String lineSeparator, Map options) {
- Position[] p= null;
-
- if (positions != null) {
- p= new Position[positions.length];
- for (int i= 0; i < positions.length; i++) {
- p[i]= new Position(positions[i], 0);
- }
- }
- String res= evaluateFormatterEdit(string, edit, p);
-
- if (positions != null) {
- for (int i= 0; i < positions.length; i++) {
- Position curr= p[i];
- positions[i]= curr.getOffset();
- }
- }
- return res;
- }
-
- /**
- * Evaluates the edit on the given string.
- * @throws IllegalArgumentException If the positions are not inside the string, a
- * IllegalArgumentException is thrown.
- */
- public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) {
- try {
- Document doc= createDocument(string, positions);
- edit.apply(doc, 0);
- if (positions != null) {
- for (int i= 0; i < positions.length; i++) {
- Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$
- }
- }
- return doc.get();
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e); // bug in the formatter
- Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$
- }
- return null;
- }
-
- /**
- * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
- * @throws IllegalArgumentException If the offset and length are not inside the string, a
- * IllegalArgumentException is thrown.
- */
- public static TextEdit format2(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) {
- if (offset < 0 || length < 0 || offset + length > string.length()) {
- throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- return ToolFactory.createCodeFormatter(options).format(kind, string, offset, length, indentationLevel, lineSeparator);
- }
-
- public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) {
- return format2(kind, string, 0, string.length(), indentationLevel, lineSeparator, options);
- }
-
- public static TextEdit reformat(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) {
- if (offset < 0 || length < 0 || offset + length > string.length()) {
- throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- return ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING).format(kind, string, offset, length, indentationLevel, lineSeparator);
- }
-
- public static TextEdit reformat(int kind, String string, int indentationLevel, String lineSeparator, Map options) {
- return reformat(kind, string, 0, string.length(), indentationLevel, lineSeparator, options);
- }
-
- /**
- * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind.
- * @throws IllegalArgumentException If the offset and length are not inside the string, a
- * IllegalArgumentException is thrown.
- */
- public static TextEdit format2(ASTNode node, String str, int indentationLevel, String lineSeparator, Map options) {
- int code;
- String prefix= ""; //$NON-NLS-1$
- String suffix= ""; //$NON-NLS-1$
- if (node instanceof Statement) {
- code= CodeFormatter.K_STATEMENTS;
- if (node.getNodeType() == ASTNode.SWITCH_CASE) {
- prefix= "switch(1) {"; //$NON-NLS-1$
- suffix= "}"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- }
- } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
- code= CodeFormatter.K_EXPRESSION;
- } else if (node instanceof BodyDeclaration) {
- code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
- } else {
- switch (node.getNodeType()) {
- case ASTNode.ARRAY_TYPE:
- case ASTNode.PRIMITIVE_TYPE:
- case ASTNode.QUALIFIED_TYPE:
- case ASTNode.SIMPLE_TYPE:
- suffix= " x;"; //$NON-NLS-1$
- code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
- break;
- case ASTNode.JAVASCRIPT_UNIT:
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- prefix= "A "; //$NON-NLS-1$
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.PACKAGE_DECLARATION:
- case ASTNode.IMPORT_DECLARATION:
- suffix= "\nclass A {}"; //$NON-NLS-1$
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.JSDOC:
- suffix= "void foo();"; //$NON-NLS-1$
- code= CodeFormatter.K_CLASS_BODY_DECLARATIONS;
- break;
- case ASTNode.CATCH_CLAUSE:
- prefix= "try {}"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.ANONYMOUS_CLASS_DECLARATION:
- prefix= "new A()"; //$NON-NLS-1$
- suffix= ";"; //$NON-NLS-1$
- code= CodeFormatter.K_STATEMENTS;
- break;
- case ASTNode.MODIFIER:
- suffix= " class x {}"; //$NON-NLS-1$
- code= CodeFormatter.K_JAVASCRIPT_UNIT;
- break;
- case ASTNode.MEMBER_REF:
- case ASTNode.FUNCTION_REF:
- case ASTNode.FUNCTION_REF_PARAMETER:
- case ASTNode.TAG_ELEMENT:
- case ASTNode.TEXT_ELEMENT:
- // Javadoc formatting not yet supported:
- return null;
- default:
- //Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$
- return null;
- }
- }
-
- String concatStr= prefix + str + suffix;
- TextEdit edit= ToolFactory.createCodeFormatter(options).format(code, concatStr, prefix.length(), str.length(), indentationLevel, lineSeparator);
- if (prefix.length() > 0) {
- edit= shifEdit(edit, prefix.length());
- }
- return edit;
- }
-
- private static TextEdit shifEdit(TextEdit oldEdit, int diff) {
- TextEdit newEdit;
- if (oldEdit instanceof ReplaceEdit) {
- ReplaceEdit edit= (ReplaceEdit) oldEdit;
- newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText());
- } else if (oldEdit instanceof InsertEdit) {
- InsertEdit edit= (InsertEdit) oldEdit;
- newEdit= new InsertEdit(edit.getOffset() - diff, edit.getText());
- } else if (oldEdit instanceof DeleteEdit) {
- DeleteEdit edit= (DeleteEdit) oldEdit;
- newEdit= new DeleteEdit(edit.getOffset() - diff, edit.getLength());
- } else if (oldEdit instanceof MultiTextEdit) {
- newEdit= new MultiTextEdit();
- } else {
- return null; // not supported
- }
- TextEdit[] children= oldEdit.getChildren();
- for (int i= 0; i < children.length; i++) {
- TextEdit shifted= shifEdit(children[i], diff);
- if (shifted != null) {
- newEdit.addChild(shifted);
- }
- }
- return newEdit;
- }
-
- private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException {
- Document doc= new Document(string);
- try {
- if (positions != null) {
- final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$
-
- doc.addPositionCategory(POS_CATEGORY);
- doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) {
- protected boolean notDeleted() {
- if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) {
- fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove
- return false;
- }
- return true;
- }
- });
- for (int i= 0; i < positions.length; i++) {
- try {
- doc.addPosition(POS_CATEGORY, positions[i]);
- } catch (BadLocationException e) {
- throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- }
- }
- } catch (BadPositionCategoryException cannotHappen) {
- // can not happen: category is correctly set up
- }
- return doc;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java
deleted file mode 100644
index a8b7781c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/History.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.util.Collection;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.internal.corext.CorextMessages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIException;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * History stores a list of key, object pairs. The list is bounded at size
- * MAX_HISTORY_SIZE. If the list exceeds this size the eldest element is removed
- * from the list. An element can be added/renewed with a call to <code>accessed(Object)</code>.
- *
- * The history can be stored to/loaded from an xml file.
- */
-public abstract class History {
-
- private static final String DEFAULT_ROOT_NODE_NAME= "histroyRootNode"; //$NON-NLS-1$
- private static final String DEFAULT_INFO_NODE_NAME= "infoNode"; //$NON-NLS-1$
- private static final int MAX_HISTORY_SIZE= 60;
-
- private static JavaUIException createException(Throwable t, String message) {
- return new JavaUIException(JavaUIStatus.createError(IStatus.ERROR, message, t));
- }
-
- private final Map fHistory;
- private final Hashtable fPositions;
- private final String fFileName;
- private final String fRootNodeName;
- private final String fInfoNodeName;
-
- public History(String fileName, String rootNodeName, String infoNodeName) {
- fHistory= new LinkedHashMap(80, 0.75f, true) {
- private static final long serialVersionUID= 1L;
- protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_HISTORY_SIZE;
- }
- };
- fFileName= fileName;
- fRootNodeName= rootNodeName;
- fInfoNodeName= infoNodeName;
- fPositions= new Hashtable(MAX_HISTORY_SIZE);
- }
-
- public History(String fileName) {
- this(fileName, DEFAULT_ROOT_NODE_NAME, DEFAULT_INFO_NODE_NAME);
- }
-
- public synchronized void accessed(Object object) {
- fHistory.put(getKey(object), object);
- rebuildPositions();
- }
-
- public synchronized boolean contains(Object object) {
- return fHistory.containsKey(getKey(object));
- }
-
- public synchronized boolean containsKey(Object key) {
- return fHistory.containsKey(key);
- }
-
- public synchronized boolean isEmpty() {
- return fHistory.isEmpty();
- }
-
- public synchronized Object remove(Object object) {
- Object removed= fHistory.remove(getKey(object));
- rebuildPositions();
- return removed;
- }
-
- public synchronized Object removeKey(Object key) {
- Object removed= fHistory.remove(key);
- rebuildPositions();
- return removed;
- }
-
- /**
- * Normalized position in history of object denoted by key.
- * The position is a value between zero and one where zero
- * means not contained in history and one means newest element
- * in history. The lower the value the older the element.
- *
- * @param key The key of the object to inspect
- * @return value in [0.0, 1.0] the lower the older the element
- */
- public synchronized float getNormalizedPosition(Object key) {
- if (!containsKey(key))
- return 0.0f;
-
- int pos= ((Integer)fPositions.get(key)).intValue() + 1;
-
- //containsKey(key) implies fHistory.size()>0
- return (float)pos / (float)fHistory.size();
- }
-
- /**
- * Absolute position of object denoted by key in the
- * history or -1 if !containsKey(key). The higher the
- * newer.
- *
- * @param key The key of the object to inspect
- * @return value between 0 and MAX_HISTORY_SIZE - 1, or -1
- */
- public synchronized int getPosition(Object key) {
- if (!containsKey(key))
- return -1;
-
- return ((Integer)fPositions.get(key)).intValue();
- }
-
- public synchronized void load() {
- IPath stateLocation= JavaScriptPlugin.getDefault().getStateLocation().append(fFileName);
- File file= new File(stateLocation.toOSString());
- if (file.exists()) {
- InputStreamReader reader= null;
- try {
- reader = new InputStreamReader(new FileInputStream(file), "utf-8");//$NON-NLS-1$
- load(new InputSource(reader));
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- }
-
- public synchronized void save() {
- IPath stateLocation= JavaScriptPlugin.getDefault().getStateLocation().append(fFileName);
- File file= new File(stateLocation.toOSString());
- OutputStream out= null;
- try {
- out= new FileOutputStream(file);
- save(out);
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (TransformerFactoryConfigurationError e) {
- // The XML library can be misconficgured (e.g. via
- // -Djava.endorsed.dirs=C:\notExisting\xerces-2_7_1)
- JavaScriptPlugin.log(e);
- } finally {
- try {
- if (out != null) {
- out.close();
- }
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- protected Set getKeys() {
- return fHistory.keySet();
- }
-
- protected Collection getValues() {
- return fHistory.values();
- }
-
- /**
- * Store <code>Object</code> in <code>Element</code>
- *
- * @param object The object to store
- * @param element The Element to store to
- */
- protected abstract void setAttributes(Object object, Element element);
-
- /**
- * Return a new instance of an Object given <code>element</code>
- *
- * @param element The element containing required information to create the Object
- */
- protected abstract Object createFromElement(Element element);
-
- /**
- * Get key for object
- *
- * @param object The object to calculate a key for, not null
- * @return The key for object, not null
- */
- protected abstract Object getKey(Object object);
-
- private void rebuildPositions() {
- fPositions.clear();
- Collection values= fHistory.values();
- int pos=0;
- for (Iterator iter= values.iterator(); iter.hasNext();) {
- Object element= iter.next();
- fPositions.put(getKey(element), new Integer(pos));
- pos++;
- }
- }
-
- private void load(InputSource inputSource) throws CoreException {
- Element root;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- root = parser.parse(inputSource).getDocumentElement();
- } catch (SAXException e) {
- throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName));
- } catch (ParserConfigurationException e) {
- throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName));
- } catch (IOException e) {
- throw createException(e, Messages.format(CorextMessages.History_error_read, fFileName));
- }
-
- if (root == null) return;
- if (!root.getNodeName().equalsIgnoreCase(fRootNodeName)) {
- return;
- }
- NodeList list= root.getChildNodes();
- int length= list.getLength();
- for (int i= 0; i < length; ++i) {
- Node node= list.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element type= (Element) node;
- if (type.getNodeName().equalsIgnoreCase(fInfoNodeName)) {
- Object object= createFromElement(type);
- if (object != null) {
- fHistory.put(getKey(object), object);
- }
- }
- }
- }
- rebuildPositions();
- }
-
- private void save(OutputStream stream) throws CoreException {
- try {
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- DocumentBuilder builder= factory.newDocumentBuilder();
- Document document= builder.newDocument();
-
- Element rootElement = document.createElement(fRootNodeName);
- document.appendChild(rootElement);
-
- Iterator values= getValues().iterator();
- while (values.hasNext()) {
- Object object= values.next();
- Element element= document.createElement(fInfoNodeName);
- setAttributes(object, element);
- rootElement.appendChild(element);
- }
-
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
- DOMSource source = new DOMSource(document);
- StreamResult result = new StreamResult(stream);
-
- transformer.transform(source, result);
- } catch (TransformerException e) {
- throw createException(e, Messages.format(CorextMessages.History_error_serialize, fFileName));
- } catch (ParserConfigurationException e) {
- throw createException(e, Messages.format(CorextMessages.History_error_serialize, fFileName));
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java
deleted file mode 100644
index 1d42717f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/IOCloser.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class IOCloser {
- public static void perform(Reader reader, InputStream stream) {
- try {
- rethrows(reader, stream);
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- public static void rethrows(Reader reader, InputStream stream) throws IOException {
- if (reader != null) {
- reader.close();
- return;
- }
- if (stream != null) {
- stream.close();
- return;
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java
deleted file mode 100644
index 77118a0d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaElementResourceMapping.java
+++ /dev/null
@@ -1,398 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.mapping.RemoteResourceMappingContext;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.resources.mapping.ResourceMappingContext;
-import org.eclipse.core.resources.mapping.ResourceTraversal;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.model.JavaModelProvider;
-
-/**
- * An abstract super class to describe mappings from a Java element to a
- * set of resources. The class also provides factory methods to create
- * resource mappings.
- *
- *
- */
-public abstract class JavaElementResourceMapping extends ResourceMapping {
-
- protected JavaElementResourceMapping() {
- }
-
- public IJavaScriptElement getJavaElement() {
- Object o= getModelObject();
- if (o instanceof IJavaScriptElement)
- return (IJavaScriptElement)o;
- return null;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof JavaElementResourceMapping))
- return false;
- return getJavaElement().equals(((JavaElementResourceMapping)obj).getJavaElement());
- }
-
- public int hashCode() {
- IJavaScriptElement javaElement= getJavaElement();
- if (javaElement == null)
- return super.hashCode();
-
- return javaElement.hashCode();
- }
-
- public String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
-
- public boolean contains(ResourceMapping mapping) {
- if (mapping instanceof JavaElementResourceMapping) {
- JavaElementResourceMapping javaMapping = (JavaElementResourceMapping) mapping;
- IJavaScriptElement element = getJavaElement();
- IJavaScriptElement other = javaMapping.getJavaElement();
- if (other != null && element != null)
- return element.getPath().isPrefixOf(other.getPath());
- }
- return false;
- }
-
- //---- the factory code ---------------------------------------------------------------
-
- private static final class JavaModelResourceMapping extends JavaElementResourceMapping {
- private final IJavaScriptModel fJavaModel;
- private JavaModelResourceMapping(IJavaScriptModel model) {
- Assert.isNotNull(model);
- fJavaModel= model;
- }
- public Object getModelObject() {
- return fJavaModel;
- }
- public IProject[] getProjects() {
- IJavaScriptProject[] projects= null;
- try {
- projects= fJavaModel.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return new IProject[0];
- }
- IProject[] result= new IProject[projects.length];
- for (int i= 0; i < projects.length; i++) {
- result[i]= projects[i].getProject();
- }
- return result;
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- IJavaScriptProject[] projects= fJavaModel.getJavaScriptProjects();
- ResourceTraversal[] result= new ResourceTraversal[projects.length];
- for (int i= 0; i < projects.length; i++) {
- result[i]= new ResourceTraversal(new IResource[] {projects[i].getProject()}, IResource.DEPTH_INFINITE, 0);
- }
- return result;
- }
- }
-
- private static final class JavaProjectResourceMapping extends JavaElementResourceMapping {
- private final IJavaScriptProject fProject;
- private JavaProjectResourceMapping(IJavaScriptProject project) {
- Assert.isNotNull(project);
- fProject= project;
- }
- public Object getModelObject() {
- return fProject;
- }
- public IProject[] getProjects() {
- return new IProject[] {fProject.getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fProject.getProject()}, IResource.DEPTH_INFINITE, 0)
- };
- }
- }
-
- private static final class PackageFragementRootResourceMapping extends JavaElementResourceMapping {
- private final IPackageFragmentRoot fRoot;
- private PackageFragementRootResourceMapping(IPackageFragmentRoot root) {
- Assert.isNotNull(root);
- fRoot= root;
- }
- public Object getModelObject() {
- return fRoot;
- }
- public IProject[] getProjects() {
- return new IProject[] {fRoot.getJavaScriptProject().getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fRoot.getResource()}, IResource.DEPTH_INFINITE, 0)
- };
- }
- }
-
- private static final class LocalPackageFragementTraversal extends ResourceTraversal {
- private final IPackageFragment fPack;
- public LocalPackageFragementTraversal(IPackageFragment pack) throws CoreException {
- super(new IResource[] {pack.getResource()}, IResource.DEPTH_ONE, 0);
- fPack= pack;
- }
- public void accept(IResourceVisitor visitor) throws CoreException {
- IFile[] files= getPackageContent(fPack);
- final IResource resource= fPack.getResource();
- if (resource != null)
- visitor.visit(resource);
- for (int i= 0; i < files.length; i++) {
- visitor.visit(files[i]);
- }
- }
- }
-
- private static final class PackageFragmentResourceMapping extends JavaElementResourceMapping {
- private final IPackageFragment fPack;
- private PackageFragmentResourceMapping(IPackageFragment pack) {
- Assert.isNotNull(pack);
- fPack= pack;
- }
- public Object getModelObject() {
- return fPack;
- }
- public IProject[] getProjects() {
- return new IProject[] { fPack.getJavaScriptProject().getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- if (context instanceof RemoteResourceMappingContext) {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fPack.getResource()}, IResource.DEPTH_ONE, 0)
- };
- } else {
- return new ResourceTraversal[] { new LocalPackageFragementTraversal(fPack) };
- }
- }
- public void accept(ResourceMappingContext context, IResourceVisitor visitor, IProgressMonitor monitor) throws CoreException {
- if (context instanceof RemoteResourceMappingContext) {
- super.accept(context, visitor, monitor);
- } else {
- // We assume a local context.
- IFile[] files= getPackageContent(fPack);
- if (monitor == null)
- monitor= new NullProgressMonitor();
- monitor.beginTask("", files.length + 1); //$NON-NLS-1$
- final IResource resource= fPack.getResource();
- if (resource != null)
- visitor.visit(resource);
- monitor.worked(1);
- for (int i= 0; i < files.length; i++) {
- visitor.visit(files[i]);
- monitor.worked(1);
- }
- }
- }
- }
-
- private static IFile[] getPackageContent(IPackageFragment pack) throws CoreException {
- List result= new ArrayList();
- IContainer container= (IContainer)pack.getResource();
- if (container != null) {
- IResource[] members= container.members();
- for (int m= 0; m < members.length; m++) {
- IResource member= members[m];
- if (member instanceof IFile) {
- IFile file= (IFile)member;
- if ("class".equals(file.getFileExtension()) && file.isDerived()) //$NON-NLS-1$
- continue;
- result.add(member);
- }
- }
- }
- return (IFile[])result.toArray(new IFile[result.size()]);
- }
-
-
- private static final class CompilationUnitResourceMapping extends JavaElementResourceMapping {
- private final IJavaScriptUnit fUnit;
- private CompilationUnitResourceMapping(IJavaScriptUnit unit) {
- Assert.isNotNull(unit);
- fUnit= unit;
- }
- public Object getModelObject() {
- return fUnit;
- }
- public IProject[] getProjects() {
- return new IProject[] {fUnit.getJavaScriptProject().getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fUnit.getResource()}, IResource.DEPTH_ONE, 0)
- };
- }
- }
-
- private static final class ClassFileResourceMapping extends JavaElementResourceMapping {
- private final IClassFile fClassFile;
- private ClassFileResourceMapping(IClassFile classFile) {
- fClassFile= classFile;
- }
- public Object getModelObject() {
- return fClassFile;
- }
- public IProject[] getProjects() {
- return new IProject[] { fClassFile.getJavaScriptProject().getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fClassFile.getResource()}, IResource.DEPTH_ONE, 0)
- };
- }
- }
-
- private static final class LogicalPackageResourceMapping extends ResourceMapping {
- private final IPackageFragment[] fFragments;
- private LogicalPackageResourceMapping(IPackageFragment[] fragments) {
- fFragments= fragments;
- }
- public Object getModelObject() {
- return fFragments;
- }
- public IProject[] getProjects() {
- Set result= new HashSet();
- for (int i= 0; i < fFragments.length; i++) {
- result.add(fFragments[i].getJavaScriptProject().getProject());
- }
- return (IProject[])result.toArray(new IProject[result.size()]);
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- List result= new ArrayList();
- if (context instanceof RemoteResourceMappingContext) {
- for (int i= 0; i < fFragments.length; i++) {
- result.add(new ResourceTraversal(
- new IResource[] {fFragments[i].getResource()}, IResource.DEPTH_ONE, 0));
- }
- } else {
- for (int i= 0; i < fFragments.length; i++) {
- result.add(new LocalPackageFragementTraversal(fFragments[i]));
- }
- }
- return (ResourceTraversal[])result.toArray(new ResourceTraversal[result.size()]);
- }
-
- public String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
- }
-
- public static ResourceMapping create(IJavaScriptElement element) {
- switch (element.getElementType()) {
- case IJavaScriptElement.TYPE:
- return create((IType)element);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return create((IJavaScriptUnit)element);
- case IJavaScriptElement.CLASS_FILE:
- return create((IClassFile)element);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return create((IPackageFragment)element);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return create((IPackageFragmentRoot)element);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return create((IJavaScriptProject)element);
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return create((IJavaScriptModel)element);
- default:
- return null;
- }
-
- }
-
- public static ResourceMapping create(final IJavaScriptModel model) {
- return new JavaModelResourceMapping(model);
- }
-
- public static ResourceMapping create(final IJavaScriptProject project) {
- return new JavaProjectResourceMapping(project);
- }
-
- public static ResourceMapping create(final IPackageFragmentRoot root) {
- if (root.isExternal())
- return null;
- return new PackageFragementRootResourceMapping(root);
- }
-
- public static ResourceMapping create(final IPackageFragment pack) {
- // test if in an archive
- IPackageFragmentRoot root= (IPackageFragmentRoot)pack.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (!root.isArchive()) {
- return new PackageFragmentResourceMapping(pack);
- }
- return null;
- }
-
- public static ResourceMapping create(IJavaScriptUnit unit) {
- if (unit == null)
- return null;
- return new CompilationUnitResourceMapping(unit.getPrimary());
- }
-
- public static ResourceMapping create(IClassFile classFile) {
- // test if in a archive
- IPackageFragmentRoot root= (IPackageFragmentRoot)classFile.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (!root.isArchive()) {
- return new ClassFileResourceMapping(classFile);
- }
- return null;
- }
-
- public static ResourceMapping create(IType type) {
- // top level types behave like the CU
- IJavaScriptElement parent= type.getParent();
- if (parent instanceof IJavaScriptUnit) {
- return create((IJavaScriptUnit)parent);
- }
- return null;
- }
-
- public static ResourceMapping create(LogicalPackage logicalPackage) {
- IPackageFragment[] fragments= logicalPackage.getFragments();
- List toProcess= new ArrayList(fragments.length);
- for (int i= 0; i < fragments.length; i++) {
- // only add if not part of an archive
- IPackageFragmentRoot root= (IPackageFragmentRoot)fragments[i].getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (!root.isArchive()) {
- toProcess.add(fragments[i]);
- }
- }
- if (toProcess.size() == 0)
- return null;
- return new LogicalPackageResourceMapping((IPackageFragment[])toProcess.toArray(new IPackageFragment[toProcess.size()]));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java
deleted file mode 100644
index 0ad639fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JavaModelUtil.java
+++ /dev/null
@@ -1,947 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.RewriteSessionEditProcessor;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.internal.corext.CorextMessages;
-import org.eclipse.wst.jsdt.internal.corext.ValidateEditException;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstall2;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-
-/**
- * Utility methods for the Java Model.
- */
-public final class JavaModelUtil {
-
- /**
- * Only use this suffix for creating new .java files.
- * In general, use one of the three *JavaLike*(..) methods in JavaScriptCore or create
- * a name from an existing compilation unit with {@link #getRenamedCUName(IJavaScriptUnit, String)}
- * <p>
- * Note: Unlike {@link JavaScriptCore#getJavaScriptLikeExtensions()}, this suffix includes a leading ".".
- * </p>
- *
- * @see JavaScriptCore#getJavaScriptLikeExtensions()
- * @see JavaScriptCore#isJavaScriptLikeFileName(String)
- * @see JavaScriptCore#removeJavaScriptLikeExtension(String)
- * @see #getRenamedCUName(IJavaScriptUnit, String)
- */
- public static final String DEFAULT_CU_SUFFIX= ".js"; //$NON-NLS-1$
-
- /**
- * Finds a type by its qualified type name (dot separated).
- * @param jproject The java project to search in
- * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots))
- * @return The type found, or null if not existing
- */
- public static IType findType(IJavaScriptProject jproject, String fullyQualifiedName) throws JavaScriptModelException {
- //workaround for bug 22883
- IType type= jproject.findType(fullyQualifiedName);
- if (type != null)
- return type;
- IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- type= findType(root, fullyQualifiedName);
- if (type != null && type.exists())
- return type;
- }
- return null;
- }
-
- /**
- * Finds a type by its qualified type name (dot separated).
- * @param jproject The java project to search in
- * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots))
- * @param owner the working copy owner
- * @return The type found, or null if not existing
- */
- public static IType findType(IJavaScriptProject jproject, String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException {
- //workaround for bug 22883
- IType type= jproject.findType(fullyQualifiedName, owner);
- if (type != null)
- return type;
- IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- type= findType(root, fullyQualifiedName);
- if (type != null && type.exists())
- return type;
- }
- return null;
- }
-
-
-
- private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaScriptModelException{
- IJavaScriptElement[] children= root.getChildren();
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElement element= children[i];
- if (element.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT){
- IPackageFragment pack= (IPackageFragment)element;
- if (! fullyQualifiedName.startsWith(pack.getElementName()))
- continue;
- IType type= findType(pack, fullyQualifiedName);
- if (type != null && type.exists())
- return type;
- }
- }
- return null;
- }
-
- private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaScriptModelException{
- IJavaScriptUnit[] cus= pack.getJavaScriptUnits();
- for (int i= 0; i < cus.length; i++) {
- IJavaScriptUnit unit= cus[i];
- IType type= findType(unit, fullyQualifiedName);
- if (type != null && type.exists())
- return type;
- }
- return null;
- }
-
- private static IType findType(IJavaScriptUnit cu, String fullyQualifiedName) throws JavaScriptModelException{
- IType[] types= cu.getAllTypes();
- for (int i= 0; i < types.length; i++) {
- IType type= types[i];
- if (getFullyQualifiedName(type).equals(fullyQualifiedName))
- return type;
- }
- return null;
- }
-
- /**
- * Finds a type container by container name.
- * The returned element will be of type <code>IType</code> or a <code>IPackageFragment</code>.
- * <code>null</code> is returned if the type container could not be found.
- * @param jproject The Java project defining the context to search
- * @param typeContainerName A dot separated name of the type container
- * @see #getTypeContainerName(IType)
- */
- public static IJavaScriptElement findTypeContainer(IJavaScriptProject jproject, String typeContainerName) throws JavaScriptModelException {
- // try to find it as type
- IJavaScriptElement result= jproject.findType(typeContainerName);
- if (result == null) {
- // find it as package
- IPath path= new Path(typeContainerName.replace('.', '/'));
- result= jproject.findElement(path);
- if (!(result instanceof IPackageFragment)) {
- result= null;
- }
-
- }
- return result;
- }
-
- /**
- * Finds a type in a compilation unit. Typical usage is to find the corresponding
- * type in a working copy.
- * @param cu the compilation unit to search in
- * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots))
- * @return the type found, or null if not existing
- */
- public static IType findTypeInCompilationUnit(IJavaScriptUnit cu, String typeQualifiedName) throws JavaScriptModelException {
- IType[] types= cu.getAllTypes();
- for (int i= 0; i < types.length; i++) {
- String currName= getTypeQualifiedName(types[i]);
- if (typeQualifiedName.equals(currName)) {
- return types[i];
- }
- }
- return null;
- }
-
- /**
- * Returns the element of the given compilation unit which is "equal" to the
- * given element. Note that the given element usually has a parent different
- * from the given compilation unit.
- *
- * @param cu the cu to search in
- * @param element the element to look for
- * @return an element of the given cu "equal" to the given element
- */
- public static IJavaScriptElement findInCompilationUnit(IJavaScriptUnit cu, IJavaScriptElement element) {
- IJavaScriptElement[] elements= cu.findElements(element);
- if (elements != null && elements.length > 0) {
- return elements[0];
- }
- return null;
- }
-
- /**
- * Returns the qualified type name of the given type using '.' as separators.
- * This is a replace for IType.getTypeQualifiedName()
- * which uses '$' as separators. As '$' is also a valid character in an id
- * this is ambiguous. JavaScriptCore PR: 1GCFUNT
- */
- public static String getTypeQualifiedName(IType type) {
- try {
- if (type.isBinary() && !type.isAnonymous()) {
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- return getTypeQualifiedName(declaringType) + '.' + type.getElementName();
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return type.getTypeQualifiedName('.');
- }
-
- /**
- * Returns the fully qualified name of the given type using '.' as separators.
- * This is a replace for IType.getFullyQualifiedTypeName
- * which uses '$' as separators. As '$' is also a valid character in an id
- * this is ambiguous. JavaScriptCore PR: 1GCFUNT
- */
- public static String getFullyQualifiedName(IType type) {
- try {
- if (type.isBinary() && !type.isAnonymous()) {
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- return getFullyQualifiedName(declaringType) + '.' + type.getElementName();
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return type.getFullyQualifiedName('.');
- }
-
- /**
- * Returns the fully qualified name of a type's container. (package name or enclosing type name)
- */
- public static String getTypeContainerName(IType type) {
- IType outerType= type.getDeclaringType();
- if (outerType != null) {
- return getFullyQualifiedName(outerType);
- } else {
- return type.getPackageFragment().getElementName();
- }
- }
-
-
- /**
- * Concatenates two names. Uses a dot for separation.
- * Both strings can be empty or <code>null</code>.
- */
- public static String concatenateName(String name1, String name2) {
- StringBuffer buf= new StringBuffer();
- if (name1 != null && name1.length() > 0) {
- buf.append(name1);
- }
- if (name2 != null && name2.length() > 0) {
- if (buf.length() > 0) {
- buf.append('.');
- }
- buf.append(name2);
- }
- return buf.toString();
- }
-
- /**
- * Concatenates two names. Uses a dot for separation.
- * Both strings can be empty or <code>null</code>.
- */
- public static String concatenateName(char[] name1, char[] name2) {
- StringBuffer buf= new StringBuffer();
- if (name1 != null && name1.length > 0) {
- buf.append(name1);
- }
- if (name2 != null && name2.length > 0) {
- if (buf.length() > 0) {
- buf.append('.');
- }
- buf.append(name2);
- }
- return buf.toString();
- }
-
- /**
- * Evaluates if a member (possible from another package) is visible from
- * elements in a package.
- * @param member The member to test the visibility for
- * @param pack The package in focus
- */
- public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaScriptModelException {
-
- int type= member.getElementType();
- if (type == IJavaScriptElement.INITIALIZER || (type == IJavaScriptElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$
- return false;
- }
-
- int otherflags= member.getFlags();
- if (Flags.isPublic(otherflags)) {
- return true;
- } else if (Flags.isPrivate(otherflags)) {
- return false;
- }
-
- IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- return (pack != null && otherpack != null && isSamePackage(pack, otherpack));
- }
-
- /**
- * Evaluates if a member in the focus' element hierarchy is visible from
- * elements in a package.
- * @param member The member to test the visibility for
- * @param pack The package of the focus element focus
- */
- public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaScriptModelException {
- int type= member.getElementType();
- if (type == IJavaScriptElement.INITIALIZER || (type == IJavaScriptElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$
- return false;
- }
- return true;
-
-// int otherflags= member.getFlags();
-//
-// if (Flags.isPublic(otherflags)) {
-// return true;
-// } else if (Flags.isPrivate(otherflags)) {
-// return false;
-// }
-//
-// IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
-// return (pack != null && pack.equals(otherpack));
- }
-
-
- /**
- * Returns the package fragment root of <code>IJavaScriptElement</code>. If the given
- * element is already a package fragment root, the element itself is returned.
- */
- public static IPackageFragmentRoot getPackageFragmentRoot(IJavaScriptElement element) {
- return (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- }
-
- /**
- * Finds a method in a type.
- * This searches for a method with the same name and signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type name is done.
- * Constructors are only compared by parameters, not the name.
- * @param name The name of the method to find
- * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code>
- * @param isConstructor If the method is a constructor
- * @return The first found method or <code>null</code>, if nothing found
- */
- public static IFunction findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaScriptModelException {
- IFunction[] methods= type.getFunctions();
- for (int i= 0; i < methods.length; i++) {
- if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) {
- return methods[i];
- }
- }
- return null;
- }
-
- /**
- * Finds a method in a type and all its super types. The super class hierarchy is searched first, then the super interfaces.
- * This searches for a method with the same name and signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type name is done.
- * Constructors are only compared by parameters, not the name.
- * NOTE: For finding overridden methods or for finding the declaring method, use {@link MethodOverrideTester}
- * @param hierarchy The hierarchy containing the type
- * @param type The type to start the search from
- * @param name The name of the method to find
- * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code>
- * @param isConstructor If the method is a constructor
- * @return The first found method or <code>null</code>, if nothing found
- */
- public static IFunction findMethodInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaScriptModelException {
- IFunction method= findMethod(name, paramTypes, isConstructor, type);
- if (method != null) {
- return method;
- }
- IType superClass= hierarchy.getSuperclass(type);
- if (superClass != null) {
- IFunction res= findMethodInHierarchy(hierarchy, superClass, name, paramTypes, isConstructor);
- if (res != null) {
- return res;
- }
- }
- return method;
- }
-
-
- /**
- * Tests if a method equals to the given signature.
- * Parameter types are only compared by the simple name, no resolving for
- * the fully qualified type name is done. Constructors are only compared by
- * parameters, not the name.
- * @param name Name of the method
- * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code>
- * @param isConstructor Specifies if the method is a constructor
- * @return Returns <code>true</code> if the method has the given name and parameter types and constructor state.
- */
- public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IFunction curr) throws JavaScriptModelException {
- if (isConstructor || name.equals(curr.getElementName())) {
- if (isConstructor == curr.isConstructor()) {
- String[] currParamTypes= curr.getParameterTypes();
- if (paramTypes.length == currParamTypes.length) {
- for (int i= 0; i < paramTypes.length; i++) {
- String t1= Signature.getSimpleName(Signature.toString(paramTypes[i]));
- String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i]));
- if (!t1.equals(t2)) {
- return false;
- }
- }
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Tests if two <code>IPackageFragment</code>s represent the same logical java package.
- * @return <code>true</code> if the package fragments' names are equal.
- */
- public static boolean isSamePackage(IPackageFragment pack1, IPackageFragment pack2) {
- return pack1.getElementName().equals(pack2.getElementName());
- }
-
- /**
- * Checks if the field is boolean.
- */
- public static boolean isBoolean(IField field) throws JavaScriptModelException{
- return field.getTypeSignature().equals(SignatureUtil.BOOLEAN_SIGNATURE);
- }
-
- /**
- * Resolves a type name in the context of the declaring type.
- *
- * @param refTypeSig the type name in signature notation (for example 'QVector') this can also be an array type, but dimensions will be ignored.
- * @param declaringType the context for resolving (type where the reference was made in)
- * @return returns the fully qualified type name or build-in-type name. if a unresolved type couldn't be resolved null is returned
- */
- public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaScriptModelException {
- int arrayCount= Signature.getArrayCount(refTypeSig);
- char type= refTypeSig.charAt(arrayCount);
- if (type == Signature.C_UNRESOLVED) {
- String name= ""; //$NON-NLS-1$
- int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
- if (semi == -1) {
- throw new IllegalArgumentException();
- }
- name= refTypeSig.substring(arrayCount + 1, semi);
-
- String[][] resolvedNames= declaringType.resolveType(name);
- if (resolvedNames != null && resolvedNames.length > 0) {
- return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]);
- }
- return null;
- } else {
- return Signature.toString(refTypeSig.substring(arrayCount));
- }
- }
-
- /**
- * Returns if a CU can be edited.
- */
- public static boolean isEditable(IJavaScriptUnit cu) {
- Assert.isNotNull(cu);
- IResource resource= cu.getPrimary().getResource();
- return (resource.exists() && !resource.getResourceAttributes().isReadOnly());
- }
-
- /**
- * Returns true if a cu is a primary cu (original or shared working copy)
- */
- public static boolean isPrimary(IJavaScriptUnit cu) {
- return cu.getOwner() == null;
- }
-
- /*
- * http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- *
- * Reconciling happens in a separate thread. This can cause a situation where the
- * Java element gets disposed after an exists test has been done. So we should not
- * log not present exceptions when they happen in working copies.
- */
- public static boolean isExceptionToBeLogged(CoreException exception) {
- if (!(exception instanceof JavaScriptModelException))
- return true;
- JavaScriptModelException je= (JavaScriptModelException)exception;
- if (!je.isDoesNotExist())
- return true;
- IJavaScriptElement[] elements= je.getJavaScriptModelStatus().getElements();
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement element= elements[i];
- // if the element is already a compilation unit don't log
- // does not exist exceptions. See bug
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=75894
- // for more details
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT)
- continue;
- IJavaScriptUnit unit= (IJavaScriptUnit)element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (unit == null)
- return true;
- if (!unit.isWorkingCopy())
- return true;
- }
- return false;
- }
-
- public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) throws JavaScriptModelException {
- // workaround for 23656
- IType[] superTypes= SuperTypeHierarchyCache.getTypeHierarchy(type).getAllSuperclasses(type);
- return superTypes;
- }
-
- public static boolean isSuperType(ITypeHierarchy hierarchy, IType possibleSuperType, IType type) {
- // filed bug 112635 to add this method to ITypeHierarchy
- IType superClass= hierarchy.getSuperclass(type);
- if (superClass != null && (possibleSuperType.equals(superClass) || isSuperType(hierarchy, possibleSuperType, superClass))) {
- return true;
- }
- return false;
- }
-
- public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) {
- char[] path = resourcePath.toString().toCharArray();
- for (int i = 0, length = exclusionPatterns.length; i < length; i++) {
- char[] pattern= exclusionPatterns[i].toString().toCharArray();
- if (CharOperation.pathMatch(pattern, path, true, '/')) {
- return true;
- }
- }
- return false;
- }
-
-
- /*
- * Returns whether the given resource path matches one of the exclusion
- * patterns.
- *
- * @see IIncludePathEntry#getExclusionPatterns
- */
- public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) {
- if (exclusionPatterns == null) return false;
- char[] path = resourcePath.toString().toCharArray();
- for (int i = 0, length = exclusionPatterns.length; i < length; i++)
- if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/'))
- return true;
- return false;
- }
-
-
- /**
- * Force a reconcile of a compilation unit.
- * @param unit
- */
- public static void reconcile(IJavaScriptUnit unit) throws JavaScriptModelException {
- unit.reconcile(
- IJavaScriptUnit.NO_AST,
- false /* don't force problem detection */,
- null /* use primary owner */,
- null /* no progress monitor */);
- }
-
- /**
- * Helper method that tests if an classpath entry can be found in a
- * container. <code>null</code> is returned if the entry can not be found
- * or if the container does not allows the configuration of source
- * attachments
- * @param jproject The container's parent project
- * @param containerPath The path of the container
- * @param libPath The path of the library to be found
- * @return IIncludePathEntry A classpath entry from the container of
- * <code>null</code> if the container can not be modified.
- * @throws JavaScriptModelException thrown if accessing the container failed
- */
- public static IIncludePathEntry getClasspathEntryToEdit(IJavaScriptProject jproject, IPath containerPath, IPath libPath) throws JavaScriptModelException {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- if (container != null && initializer != null && initializer.canUpdateJsGlobalScopeContainer(containerPath, jproject)) {
- return findEntryInContainer(container, libPath);
- }
- return null; // attachment not possible
- }
-
- /**
- * Finds an entry in a container. <code>null</code> is returned if the entry can not be found
- * @param container The container
- * @param libPath The path of the library to be found
- * @return IIncludePathEntry A classpath entry from the container of
- * <code>null</code> if the container can not be modified.
- */
- public static IIncludePathEntry findEntryInContainer(IJsGlobalScopeContainer container, IPath libPath) {
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr= entries[i];
- IIncludePathEntry resolved= JavaScriptCore.getResolvedIncludepathEntry(curr);
- if (resolved != null && libPath.equals(resolved.getPath())) {
- return curr; // return the real entry
- }
- }
- return null; // attachment not possible
- }
-
- /**
- * Get all compilation units of a selection.
- * @param javaElements the selected java elements
- * @return all compilation units containing and contained in elements from javaElements
- * @throws JavaScriptModelException
- */
- public static IJavaScriptUnit[] getAllCompilationUnits(IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- HashSet result= new HashSet();
- for (int i= 0; i < javaElements.length; i++) {
- addAllCus(result, javaElements[i]);
- }
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- private static void addAllCus(HashSet/*<IJavaScriptUnit>*/ collector, IJavaScriptElement javaElement) throws JavaScriptModelException {
- switch (javaElement.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IJavaScriptProject javaProject= (IJavaScriptProject) javaElement;
- IPackageFragmentRoot[] packageFragmentRoots= javaProject.getPackageFragmentRoots();
- for (int i= 0; i < packageFragmentRoots.length; i++)
- addAllCus(collector, packageFragmentRoots[i]);
- return;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) javaElement;
- if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
- return;
- IJavaScriptElement[] packageFragments= packageFragmentRoot.getChildren();
- for (int j= 0; j < packageFragments.length; j++)
- addAllCus(collector, packageFragments[j]);
- return;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- IPackageFragment packageFragment= (IPackageFragment) javaElement;
- collector.addAll(Arrays.asList(packageFragment.getJavaScriptUnits()));
- return;
-
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- collector.add(javaElement);
- return;
-
- default:
- IJavaScriptElement cu= javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null)
- collector.add(cu);
- }
- }
-
-
- /**
- * Sets all compliance settings in the given map to 5.0
- */
- public static void set50CompilanceOptions(Map map) {
- setCompilanceOptions(map, JavaScriptCore.VERSION_1_5);
- }
-
- public static void setCompilanceOptions(Map map, String compliance) {
- if (JavaScriptCore.VERSION_1_6.equals(compliance)) {
- map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_6);
- map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_6);
- map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_6);
- map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
- } else if (JavaScriptCore.VERSION_1_5.equals(compliance)) {
- map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_5);
- map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_5);
- map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_5);
- map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
- } else if (JavaScriptCore.VERSION_1_4.equals(compliance)) {
- map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_4);
- map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3);
- map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_2);
- map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.WARNING);
- } else if (JavaScriptCore.VERSION_1_3.equals(compliance)) {
- map.put(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_3);
- map.put(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_3);
- map.put(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_1);
- map.put(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.IGNORE);
- } else {
- throw new IllegalArgumentException("Unsupported compliance: " + compliance); //$NON-NLS-1$
- }
- }
-
- public static void setDefaultClassfileOptions(Map map, String compliance) {
- map.put(JavaScriptCore.COMPILER_CODEGEN_INLINE_JSR_BYTECODE, is50OrHigher(compliance) ? JavaScriptCore.ENABLED : JavaScriptCore.DISABLED);
- map.put(JavaScriptCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaScriptCore.GENERATE);
- map.put(JavaScriptCore.COMPILER_LINE_NUMBER_ATTR, JavaScriptCore.GENERATE);
- map.put(JavaScriptCore.COMPILER_SOURCE_FILE_ATTR, JavaScriptCore.GENERATE);
- map.put(JavaScriptCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaScriptCore.PRESERVE);
- }
-
- /**
- * @return returns if version 1 is less than version 2.
- */
- public static boolean isVersionLessThan(String version1, String version2) {
- return version1.compareTo(version2) < 0;
- }
-
- public static boolean is50OrHigher(String compliance) {
- return !isVersionLessThan(compliance, JavaScriptCore.VERSION_1_5);
- }
-
- public static boolean is50OrHigher(IJavaScriptProject project) {
- return is50OrHigher(project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true));
- }
-
- public static boolean is50OrHigherJRE(IJavaScriptProject project) throws CoreException {
- IVMInstall vmInstall= JavaRuntime.getVMInstall(project);
- if (!(vmInstall instanceof IVMInstall2))
- return true; // assume 5.0.
-
- String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null);
- if (compliance == null)
- return true; // assume 5.0
- return compliance.startsWith(JavaScriptCore.VERSION_1_5) || compliance.startsWith(JavaScriptCore.VERSION_1_6);
- }
-
- public static String getCompilerCompliance(IVMInstall2 vMInstall, String defaultCompliance) {
- String version= vMInstall.getJavaVersion();
- if (version == null) {
- return defaultCompliance;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_6)) {
- return JavaScriptCore.VERSION_1_6;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_5)) {
- return JavaScriptCore.VERSION_1_5;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_4)) {
- return JavaScriptCore.VERSION_1_4;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_3)) {
- return JavaScriptCore.VERSION_1_3;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_2)) {
- return JavaScriptCore.VERSION_1_3;
- } else if (version.startsWith(JavaScriptCore.VERSION_1_1)) {
- return JavaScriptCore.VERSION_1_3;
- }
- return defaultCompliance;
- }
-
-// public static String getExecutionEnvironmentCompliance(IExecutionEnvironment executionEnvironment) {
-// String desc= executionEnvironment.getId();
-// if (desc.indexOf("1.6") != -1) { //$NON-NLS-1$
-// return JavaScriptCore.VERSION_1_6;
-// } else if (desc.indexOf("1.5") != -1) { //$NON-NLS-1$
-// return JavaScriptCore.VERSION_1_5;
-// } else if (desc.indexOf("1.4") != -1) { //$NON-NLS-1$
-// return JavaScriptCore.VERSION_1_4;
-// }
-// return JavaScriptCore.VERSION_1_3;
-// }
-
- /**
- * Compute a new name for a compilation unit, given the name of the new main type.
- * This query tries to maintain the existing extension (e.g. ".java").
- *
- * @param cu a compilation unit
- * @param newMainName the new name of the cu's main type (without extension)
- * @return the new name for the compilation unit
- */
- public static String getRenamedCUName(IJavaScriptUnit cu, String newMainName) {
- String oldName = cu.getElementName();
- int i = oldName.lastIndexOf('.');
- if (i != -1) {
- return newMainName + oldName.substring(i);
- } else {
- return newMainName;
- }
- }
-
- /**
- * Applies an text edit to a compilation unit. Filed bug 117694 against jdt.core.
- * @param cu the compilation unit to apply the edit to
- * @param edit the edit to apply
- * @param save is set, save the CU after the edit has been applied
- * @param monitor the progress monitor to use
- * @throws CoreException Thrown when the access to the CU failed
- * @throws ValidateEditException if validate edit fails
- */
- public static void applyEdit(IJavaScriptUnit cu, TextEdit edit, boolean save, IProgressMonitor monitor) throws CoreException, ValidateEditException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.beginTask(CorextMessages.JavaModelUtil_applyedit_operation, 3);
-
- try {
- IDocument document= null;
- try {
- document= aquireDocument(cu, new SubProgressMonitor(monitor, 1));
- if (save) {
- commitDocument(cu, document, edit, new SubProgressMonitor(monitor, 1));
- } else {
- new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits();
- }
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- } finally {
- releaseDocument(cu, document, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- private static IDocument aquireDocument(IJavaScriptUnit cu, IProgressMonitor monitor) throws CoreException {
- if (JavaModelUtil.isPrimary(cu)) {
- IFile file= (IFile) cu.getResource();
- if (file.exists()) {
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- IPath path= cu.getPath();
- bufferManager.connect(path, LocationKind.IFILE, monitor);
- return bufferManager.getTextFileBuffer(path, LocationKind.IFILE).getDocument();
- }
- }
- monitor.done();
- return new Document(cu.getSource());
- }
-
- private static void commitDocument(IJavaScriptUnit cu, IDocument document, TextEdit edit, IProgressMonitor monitor) throws CoreException, MalformedTreeException, BadLocationException {
- if (JavaModelUtil.isPrimary(cu)) {
- IFile file= (IFile) cu.getResource();
- if (file.exists()) {
- IStatus status= Resources.makeCommittable(file, null);
- if (!status.isOK()) {
- throw new ValidateEditException(status);
- }
- new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits(); // apply after file is commitable
-
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- bufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE).commit(monitor, true);
- return;
- }
- }
- // no commit possible, make sure changes are in
- new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits();
- }
-
-
- private static void releaseDocument(IJavaScriptUnit cu, IDocument document, IProgressMonitor monitor) throws CoreException {
- if (JavaModelUtil.isPrimary(cu)) {
- IFile file= (IFile) cu.getResource();
- if (file.exists()) {
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- bufferManager.disconnect(file.getFullPath(), LocationKind.IFILE, monitor);
- return;
- }
- }
- cu.getBuffer().setContents(document.get());
- monitor.done();
- }
-
- public static boolean isImplicitImport(String qualifier, IJavaScriptUnit cu) {
- if ("java.lang".equals(qualifier)) { //$NON-NLS-1$
- return true;
- }
- String packageName= cu.getParent().getElementName();
- if (qualifier.equals(packageName)) {
- return true;
- }
- String typeName= JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName());
- String mainTypeName= JavaModelUtil.concatenateName(packageName, typeName);
- return qualifier.equals(mainTypeName);
- }
-
- public static boolean isOpenableStorage(Object storage) {
- if (storage instanceof IJarEntryResource) {
- return ((IJarEntryResource) storage).isFile();
- } else {
- return storage instanceof IStorage;
- }
- }
-
- /**
- * Returns true iff the given local variable is a parameter of its
- * declaring method.
- *
- * TODO replace this method with new API when available:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=48420
- * @param currentLocal the local variable to test
- *
- * @return returns true if the variable is a parameter
- * @throws JavaScriptModelException
- */
- public static boolean isParameter(ILocalVariable currentLocal) throws JavaScriptModelException {
-
- final IJavaScriptElement parent= currentLocal.getParent();
- if (parent instanceof IFunction) {
- final String[] params= ((IFunction) parent).getParameterNames();
- for (int i= 0; i < params.length; i++) {
- if (params[i].equals(currentLocal.getElementName()))
- return true;
- }
- }
- return false;
- }
-
-
- public static String getFilePackage(IJavaScriptElement javaElement)
- {
- IJavaScriptElement fileAncestor = javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (fileAncestor==null)
- fileAncestor=javaElement.getAncestor(IJavaScriptElement.CLASS_FILE);
- IPath filePath= fileAncestor.getResource().getFullPath();
- IJavaScriptElement rootElement=fileAncestor.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- IPath rootPath = rootElement.getResource().getFullPath();
- String relativePath = filePath.removeFirstSegments(rootPath.segmentCount()).toPortableString();
- int index=Util.indexOfJavaLikeExtension(relativePath);
- if (index>=0)
- relativePath=relativePath.substring(0,index);
- relativePath=relativePath.replace('/', '.');
- return relativePath;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java
deleted file mode 100644
index f57932ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/JdtFlags.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-
-
-public class JdtFlags {
- private JdtFlags(){
- }
-
- public static final String VISIBILITY_STRING_PRIVATE= "private"; //$NON-NLS-1$
- public static final String VISIBILITY_STRING_PACKAGE= ""; //$NON-NLS-1$
- public static final String VISIBILITY_STRING_PROTECTED= "protected"; //$NON-NLS-1$
- public static final String VISIBILITY_STRING_PUBLIC= "public"; //$NON-NLS-1$
-
-
- public static final int VISIBILITY_CODE_INVALID= -1;
-
- public static boolean isAbstract(IMember member) throws JavaScriptModelException{
- return Flags.isAbstract(member.getFlags());
- }
-
- public static boolean isAbstract(IFunctionBinding member) {
- return Modifier.isAbstract(member.getModifiers());
- }
-
- public static boolean isDeprecated(IMember member) throws JavaScriptModelException{
- return Flags.isDeprecated(member.getFlags());
- }
-
- public static boolean isFinal(IMember member) throws JavaScriptModelException{
- if (isAnonymousType(member))
- return true;
- return false;
- }
-
- public static boolean isPackageVisible(IMember member) throws JavaScriptModelException{
- return (! isPrivate(member) && ! isPublic(member));
- }
-
- public static boolean isPackageVisible(BodyDeclaration bodyDeclaration) {
- return (! isPrivate(bodyDeclaration) && ! isProtected(bodyDeclaration) && ! isPublic(bodyDeclaration));
- }
-
- public static boolean isPackageVisible(IBinding binding) {
- return (! isPrivate(binding) && ! isProtected(binding) && ! isPublic(binding));
- }
-
- public static boolean isPrivate(IMember member) throws JavaScriptModelException{
- return Flags.isPrivate(member.getFlags());
- }
-
- public static boolean isPrivate(BodyDeclaration bodyDeclaration) {
- return Modifier.isPrivate(bodyDeclaration.getModifiers());
- }
-
- public static boolean isPrivate(IBinding binding) {
- return Modifier.isPrivate(binding.getModifiers());
- }
-
- public static boolean isProtected(BodyDeclaration bodyDeclaration) {
- return Modifier.isProtected(bodyDeclaration.getModifiers());
- }
-
- public static boolean isProtected(IBinding binding) {
- return Modifier.isProtected(binding.getModifiers());
- }
-
- public static boolean isPublic(IMember member) throws JavaScriptModelException{
- return Flags.isPublic(member.getFlags());
- }
-
- public static boolean isPublic(IBinding binding) {
- return Modifier.isPublic(binding.getModifiers());
- }
-
-
- public static boolean isPublic(BodyDeclaration bodyDeclaration) {
- return Modifier.isPublic(bodyDeclaration.getModifiers());
- }
-
- public static boolean isStatic(IMember member) throws JavaScriptModelException{
- return Flags.isStatic(member.getFlags());
- }
-
- public static boolean isStatic(IFunctionBinding methodBinding){
- return Modifier.isStatic(methodBinding.getModifiers());
- }
-
- public static boolean isStatic(IVariableBinding variableBinding){
- return Modifier.isStatic(variableBinding.getModifiers());
- }
-
- public static boolean isVarargs(IFunction method) throws JavaScriptModelException{
- return Flags.isVarargs(method.getFlags());
- }
-
- private static boolean isAnonymousType(IMember member) throws JavaScriptModelException {
- return member.getElementType() == IJavaScriptElement.TYPE &&
- ((IType)member).isAnonymous();
- }
-
- public static int getVisibilityCode(IMember member) throws JavaScriptModelException {
- if (isPublic(member))
- return Modifier.PUBLIC;
- else if (isPackageVisible(member))
- return Modifier.NONE;
- else if (isPrivate(member))
- return Modifier.PRIVATE;
- Assert.isTrue(false);
- return VISIBILITY_CODE_INVALID;
- }
-
- public static int getVisibilityCode(BodyDeclaration bodyDeclaration) {
- if (isPublic(bodyDeclaration))
- return Modifier.PUBLIC;
- else if (isProtected(bodyDeclaration))
- return Modifier.PROTECTED;
- else if (isPackageVisible(bodyDeclaration))
- return Modifier.NONE;
- else if (isPrivate(bodyDeclaration))
- return Modifier.PRIVATE;
- Assert.isTrue(false);
- return VISIBILITY_CODE_INVALID;
- }
-
- public static int getVisibilityCode(IBinding binding) {
- if (isPublic(binding))
- return Modifier.PUBLIC;
- else if (isProtected(binding))
- return Modifier.PROTECTED;
- else if (isPackageVisible(binding))
- return Modifier.NONE;
- else if (isPrivate(binding))
- return Modifier.PRIVATE;
- Assert.isTrue(false);
- return VISIBILITY_CODE_INVALID;
- }
-
-
- public static String getVisibilityString(int visibilityCode){
- if (Modifier.isPublic(visibilityCode))
- return VISIBILITY_STRING_PUBLIC;
- if (Modifier.isProtected(visibilityCode))
- return VISIBILITY_STRING_PROTECTED;
- if (Modifier.isPrivate(visibilityCode))
- return VISIBILITY_STRING_PRIVATE;
- return VISIBILITY_STRING_PACKAGE;
- }
-
- public static int getVisibilityCode(String visibilityString) {
- Assert.isNotNull(visibilityString);
- if (VISIBILITY_STRING_PACKAGE.equals(visibilityString))
- return 0;
- else if (VISIBILITY_STRING_PRIVATE.equals(visibilityString))
- return Modifier.PRIVATE;
- else if (VISIBILITY_STRING_PROTECTED.equals(visibilityString))
- return Modifier.PROTECTED;
- else if (VISIBILITY_STRING_PUBLIC.equals(visibilityString))
- return Modifier.PUBLIC;
- return VISIBILITY_CODE_INVALID;
- }
-
- public static void assertVisibility(int visibility){
- Assert.isTrue( visibility == Modifier.PUBLIC ||
- visibility == Modifier.PROTECTED ||
- visibility == Modifier.NONE ||
- visibility == Modifier.PRIVATE);
- }
-
- public static boolean isHigherVisibility(int newVisibility, int oldVisibility){
- assertVisibility(oldVisibility);
- assertVisibility(newVisibility);
- switch (oldVisibility) {
- case Modifier.PRIVATE :
- return newVisibility == Modifier.NONE
- || newVisibility == Modifier.PUBLIC
- || newVisibility == Modifier.PROTECTED;
- case Modifier.NONE :
- return newVisibility == Modifier.PUBLIC
- || newVisibility == Modifier.PROTECTED;
-
- case Modifier.PROTECTED :
- return newVisibility == Modifier.PUBLIC;
-
- case Modifier.PUBLIC :
- return false;
- default:
- Assert.isTrue(false);
- return false;
- }
- }
-
- public static int getLowerVisibility(int visibility1, int visibility2) {
- if (isHigherVisibility(visibility1, visibility2))
- return visibility2;
- else
- return visibility1;
- }
-
- public static int clearAccessModifiers(int flags) {
- return clearFlag(Modifier.PROTECTED | Modifier.PUBLIC | Modifier.PRIVATE, flags);
- }
-
- public static int clearFlag(int flag, int flags){
- return flags & ~ flag;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java
deleted file mode 100644
index ebafde9f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/LRUMap.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.LinkedHashMap;
-
-/**
- *
- */
-public class LRUMap extends LinkedHashMap {
-
- private static final long serialVersionUID= 1L;
- private final int fMaxSize;
-
- public LRUMap(int maxSize) {
- super(maxSize, 0.75f, true);
- fMaxSize= maxSize;
- }
-
- protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
- return size() > fMaxSize;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java
deleted file mode 100644
index 951eea68..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import com.ibm.icu.text.MessageFormat;
-
-/**
- * Helper class to format message strings.
- *
- *
- */
-public class Messages {
-
- public static String format(String message, Object object) {
- return MessageFormat.format(message, new Object[] { object});
- }
-
- public static String format(String message, Object[] objects) {
- return MessageFormat.format(message, objects);
- }
-
- private Messages() {
- // Not for instantiation
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java
deleted file mode 100644
index d05a9958..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/MethodOverrideTester.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-
-
-public class MethodOverrideTester {
- private static class Substitutions {
-
- public static final Substitutions EMPTY_SUBST= new Substitutions();
-
- private HashMap fMap;
-
- public Substitutions() {
- fMap= null;
- }
-
- private String[] getSubstArray(String typeVariable) {
- if (fMap != null) {
- return (String[]) fMap.get(typeVariable);
- }
- return null;
- }
-
- public String getSubstitution(String typeVariable) {
- String[] subst= getSubstArray(typeVariable);
- if (subst != null) {
- return subst[0];
- }
- return null;
- }
-
- public String getErasure(String typeVariable) {
- String[] subst= getSubstArray(typeVariable);
- if (subst != null) {
- return subst[1];
- }
- return null;
- }
- }
-
- private final IType fFocusType;
- private final ITypeHierarchy fHierarchy;
-
- private Map /* <IFunction, Substitutions> */ fMethodSubstitutions;
- private Map /* <IType, Substitutions> */ fTypeVariableSubstitutions;
-
- public MethodOverrideTester(IType focusType, ITypeHierarchy hierarchy) {
- if (focusType == null || hierarchy == null) {
- throw new IllegalArgumentException();
- }
- fFocusType= focusType;
- fHierarchy= hierarchy;
- fTypeVariableSubstitutions= null;
- fMethodSubstitutions= null;
- }
-
- public IType getFocusType() {
- return fFocusType;
- }
-
- public ITypeHierarchy getTypeHierarchy() {
- return fHierarchy;
- }
-
- /**
- * Finds the method that declares the given method. A declaring method is the 'original' method declaration that does
- * not override nor implement a method. <code>null</code> is returned it the given method does not override
- * a method. When searching, super class are examined before implemented interfaces.
- * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible.
- * @throws JavaScriptModelException
- */
- public IFunction findDeclaringMethod(IFunction overriding, boolean testVisibility) throws JavaScriptModelException {
- IFunction result= null;
- IFunction overridden= findOverriddenMethod(overriding, testVisibility);
- while (overridden != null) {
- result= overridden;
- overridden= findOverriddenMethod(result, testVisibility);
- }
- return result;
- }
-
- /**
- * Finds the method that is overridden by the given method.
- * First the super class is examined and then the implemented interfaces.
- * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible.
- * @throws JavaScriptModelException
- */
- public IFunction findOverriddenMethod(IFunction overriding, boolean testVisibility) throws JavaScriptModelException {
- int flags= overriding.getFlags();
- if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) {
- return null;
- }
-
- IType type= overriding.getDeclaringType();
- if (type==null)
- return null;
- IType superClass= fHierarchy.getSuperclass(type);
- if (superClass != null) {
- IFunction res= findOverriddenMethodInHierarchy(superClass, overriding);
- if (res != null && !Flags.isPrivate(res.getFlags())) {
- if (!testVisibility || JavaModelUtil.isVisibleInHierarchy(res, type.getPackageFragment())) {
- return res;
- }
- }
- }
- return null;
- }
-
- /**
- * Finds the directly overridden method in a type and its super types. First the super class is examined and then the implemented interfaces.
- * With generics it is possible that 2 methods in the same type are overidden at the same time. In that case, the first overridden method found is returned.
- * @param type The type to find methods in
- * @param overriding The overriding method
- * @return The first overridden method or <code>null</code> if no method is overridden
- * @throws JavaScriptModelException
- */
- public IFunction findOverriddenMethodInHierarchy(IType type, IFunction overriding) throws JavaScriptModelException {
- IFunction method= findOverriddenMethodInType(type, overriding);
- if (method != null) {
- return method;
- }
- IType superClass= fHierarchy.getSuperclass(type);
- if (superClass != null) {
- IFunction res= findOverriddenMethodInHierarchy(superClass, overriding);
- if (res != null) {
- return res;
- }
- }
- return method;
- }
-
- /**
- * Finds an overridden method in a type. WWith generics it is possible that 2 methods in the same type are overidden at the same time.
- * In that case the first overridden method found is returned.
- * @param overriddenType The type to find methods in
- * @param overriding The overriding method
- * @return The first overridden method or <code>null</code> if no method is overridden
- * @throws JavaScriptModelException
- */
- public IFunction findOverriddenMethodInType(IType overriddenType, IFunction overriding) throws JavaScriptModelException {
- IFunction[] overriddenMethods= overriddenType.getFunctions();
- for (int i= 0; i < overriddenMethods.length; i++) {
- if (isSubsignature(overriding, overriddenMethods[i])) {
- return overriddenMethods[i];
- }
- }
- return null;
- }
-
- /**
- * Finds an overriding method in a type.
- * @param overridingType The type to find methods in
- * @param overridden The overridden method
- * @return The overriding method or <code>null</code> if no method is overriding.
- * @throws JavaScriptModelException
- */
- public IFunction findOverridingMethodInType(IType overridingType, IFunction overridden) throws JavaScriptModelException {
- IFunction[] overridingMethods= overridingType.getFunctions();
- for (int i= 0; i < overridingMethods.length; i++) {
- if (isSubsignature(overridingMethods[i], overridden)) {
- return overridingMethods[i];
- }
- }
- return null;
- }
-
- /**
- * Tests if a method is a subsignature of another method.
- * @param overriding overriding method (m1)
- * @param overridden overridden method (m2)
- * @return <code>true</code> iff the method <code>m1</code> is a subsignature of the method <code>m2</code>.
- * This is one of the requirements for m1 to override m2.
- * Accessibility and return types are not taken into account.
- * Note that subsignature is <em>not</em> symmetric!
- * @throws JavaScriptModelException
- */
- public boolean isSubsignature(IFunction overriding, IFunction overridden) throws JavaScriptModelException {
- if (!overridden.getElementName().equals(overriding.getElementName())) {
- return false;
- }
- int nParameters= overridden.getNumberOfParameters();
- if (nParameters != overriding.getNumberOfParameters()) {
- return false;
- }
-
- return nParameters == 0 || hasCompatibleParameterTypes(overriding, overridden);
- }
-
- private boolean hasCompatibleParameterTypes(IFunction overriding, IFunction overridden) throws JavaScriptModelException {
- String[] overriddenParamTypes= overridden.getParameterTypes();
- String[] overridingParamTypes= overriding.getParameterTypes();
-
- String[] substitutedOverriding= new String[overridingParamTypes.length];
- boolean testErasure= false;
-
- for (int i= 0; i < overridingParamTypes.length; i++) {
- String overriddenParamSig= overriddenParamTypes[i];
- String overriddenParamName= getSubstitutedTypeName(overriddenParamSig, overridden);
- String overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding);
- substitutedOverriding[i]= overridingParamName;
- if (!overriddenParamName.equals(overridingParamName)) {
- testErasure= true;
- break;
- }
- }
- if (testErasure) {
- for (int i= 0; i < overridingParamTypes.length; i++) {
- String overriddenParamSig= overriddenParamTypes[i];
- String overriddenParamName= getErasedTypeName(overriddenParamSig, overridden);
- String overridingParamName= substitutedOverriding[i];
- if (overridingParamName == null)
- overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding);
- if (!overriddenParamName.equals(overridingParamName)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private String getVariableSubstitution(IMember context, String variableName) throws JavaScriptModelException {
- IType type;
- if (context instanceof IFunction) {
- String subst= getMethodSubstitions((IFunction) context).getSubstitution(variableName);
- if (subst != null) {
- return subst;
- }
- type= context.getDeclaringType();
- } else {
- type= (IType) context;
- }
- String subst= getTypeSubstitions(type).getSubstitution(variableName);
- if (subst != null) {
- return subst;
- }
- return variableName; // not a type variable
- }
-
- private String getVariableErasure(IMember context, String variableName) throws JavaScriptModelException {
- IType type;
- if (context instanceof IFunction) {
- String subst= getMethodSubstitions((IFunction) context).getErasure(variableName);
- if (subst != null) {
- return subst;
- }
- type= context.getDeclaringType();
- } else {
- type= (IType) context;
- }
- String subst= getTypeSubstitions(type).getErasure(variableName);
- if (subst != null) {
- return subst;
- }
- return variableName; // not a type variable
- }
-
- /*
- * Returns the substitutions for a method's type parameters
- */
- private Substitutions getMethodSubstitions(IFunction method) throws JavaScriptModelException {
- if (fMethodSubstitutions == null) {
- fMethodSubstitutions= new LRUMap(3);
- }
-
- Substitutions s= (Substitutions) fMethodSubstitutions.get(method);
- if (s == null) {
- s= Substitutions.EMPTY_SUBST;
- fMethodSubstitutions.put(method, s);
- }
- return s;
- }
-
- /*
- * Returns the substitutions for a type's type parameters
- */
- private Substitutions getTypeSubstitions(IType type) throws JavaScriptModelException {
- if (fTypeVariableSubstitutions == null) {
- fTypeVariableSubstitutions= new HashMap();
- computeSubstitutions(fFocusType, null, null);
- }
- Substitutions subst= (Substitutions) fTypeVariableSubstitutions.get(type);
- if (subst == null) {
- return Substitutions.EMPTY_SUBST;
- }
- return subst;
- }
-
- private void computeSubstitutions(IType instantiatedType, IType instantiatingType, String[] typeArguments) throws JavaScriptModelException {
- Substitutions s= new Substitutions();
- fTypeVariableSubstitutions.put(instantiatedType, s);
-
- String superclassTypeSignature= instantiatedType.getSuperclassTypeSignature();
- if (superclassTypeSignature != null) {
- IType superclass= fHierarchy.getSuperclass(instantiatedType);
- if (superclass != null && !fTypeVariableSubstitutions.containsKey(superclass)) {
- computeSubstitutions(superclass, instantiatedType, new String[0]);
- }
- }
- }
-
- /**
- * Translates the type signature to a 'normalized' type name where all variables are substituted for the given type or method context.
- * The returned name contains only simple names and can be used to compare against other substituted type names
- * @param typeSig The type signature to translate
- * @param context The context for the substitution
- * @return a type name
- * @throws JavaScriptModelException
- */
- private String getSubstitutedTypeName(String typeSig, IMember context) throws JavaScriptModelException {
- return internalGetSubstitutedTypeName(typeSig, context, false, new StringBuffer()).toString();
- }
-
- private String getErasedTypeName(String typeSig, IMember context) throws JavaScriptModelException {
- return internalGetSubstitutedTypeName(typeSig, context, true, new StringBuffer()).toString();
- }
-
- private StringBuffer internalGetSubstitutedTypeName(String typeSig, IMember context, boolean erasure, StringBuffer buf) throws JavaScriptModelException {
- int sigKind= Signature.getTypeSignatureKind(typeSig);
- switch (sigKind) {
- case Signature.BASE_TYPE_SIGNATURE:
- return buf.append(Signature.toString(typeSig));
- case Signature.ARRAY_TYPE_SIGNATURE:
- internalGetSubstitutedTypeName(Signature.getElementType(typeSig), context, erasure, buf);
- for (int i= Signature.getArrayCount(typeSig); i > 0; i--) {
- buf.append('[').append(']');
- }
- return buf;
- case Signature.CLASS_TYPE_SIGNATURE: {
- String erasureSig= typeSig;
- String erasureName= Signature.getSimpleName(Signature.toString(erasureSig));
-
- char ch= erasureSig.charAt(0);
- if (ch == Signature.C_RESOLVED) {
- buf.append(erasureName);
- } else if (ch == Signature.C_UNRESOLVED) { // could be a type variable
- if (erasure) {
- buf.append(getVariableErasure(context, erasureName));
- } else {
- buf.append(getVariableSubstitution(context, erasureName));
- }
- } else {
- Assert.isTrue(false, "Unknown class type signature"); //$NON-NLS-1$
- }
- return buf;
- }
- default:
- Assert.isTrue(false, "Unhandled type signature kind"); //$NON-NLS-1$
- return buf;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java
deleted file mode 100644
index 1a921e04..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/OpenTypeHistory.java
+++ /dev/null
@@ -1,419 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileInfo;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.CorextMessages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.w3c.dom.Element;
-
-/**
- * History for the open type dialog. Object and keys are both {@link TypeNameMatch}s.
- */
-public class OpenTypeHistory extends History {
-
- private static class TypeHistoryDeltaListener implements IElementChangedListener {
- public void elementChanged(ElementChangedEvent event) {
- if (processDelta(event.getDelta())) {
- OpenTypeHistory.getInstance().markAsInconsistent();
- }
- }
-
- /**
- * Computes whether the history needs a consistency check or not.
- *
- * @param delta the Java element delta
- *
- * @return <code>true</code> if consistency must be checked
- * <code>false</code> otherwise.
- */
- private boolean processDelta(IJavaScriptElementDelta delta) {
- IJavaScriptElement elem= delta.getElement();
-
- boolean isChanged= delta.getKind() == IJavaScriptElementDelta.CHANGED;
- boolean isRemoved= delta.getKind() == IJavaScriptElementDelta.REMOVED;
-
- switch (elem.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- if (isRemoved || (isChanged &&
- (delta.getFlags() & IJavaScriptElementDelta.F_CLOSED) != 0)) {
- return true;
- }
- return processChildrenDelta(delta);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- if (isRemoved || (isChanged && (
- (delta.getFlags() & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0 ||
- (delta.getFlags() & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0))) {
- return true;
- }
- return processChildrenDelta(delta);
- case IJavaScriptElement.TYPE:
- if (isChanged && (delta.getFlags() & IJavaScriptElementDelta.F_MODIFIERS) != 0) {
- return true;
- }
- // type children can be inner classes: fall through
- //$FALL-THROUGH$
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.CLASS_FILE:
- if (isRemoved) {
- return true;
- }
- return processChildrenDelta(delta);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- // Not the primary compilation unit. Ignore it
- if (!JavaModelUtil.isPrimary((IJavaScriptUnit) elem)) {
- return false;
- }
-
- if (isRemoved || (isChanged && isUnknownStructuralChange(delta.getFlags()))) {
- return true;
- }
- return processChildrenDelta(delta);
- default:
- // fields, methods, imports ect
- return false;
- }
- }
-
- private boolean isUnknownStructuralChange(int flags) {
- if ((flags & IJavaScriptElementDelta.F_CONTENT) == 0)
- return false;
- return (flags & IJavaScriptElementDelta.F_FINE_GRAINED) == 0;
- }
-
- /*
- private boolean isPossibleStructuralChange(int flags) {
- return (flags & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_FINE_GRAINED)) == IJavaScriptElementDelta.F_CONTENT;
- }
- */
-
- private boolean processChildrenDelta(IJavaScriptElementDelta delta) {
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- if (processDelta(children[i])) {
- return true;
- }
- }
- return false;
- }
- }
-
- private static class UpdateJob extends Job {
- public static final String FAMILY= UpdateJob.class.getName();
- public UpdateJob() {
- super(CorextMessages.TypeInfoHistory_consistency_check);
- }
- protected IStatus run(IProgressMonitor monitor) {
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- history.internalCheckConsistency(monitor);
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
- public boolean belongsTo(Object family) {
- return FAMILY.equals(family);
- }
- }
-
- // Needs to be volatile since accesses aren't synchronized.
- private volatile boolean fNeedsConsistencyCheck;
- // Map of cached time stamps
- private Map fTimestampMapping;
-
- private final IElementChangedListener fDeltaListener;
- private final UpdateJob fUpdateJob;
-
- private static final String FILENAME= "OpenTypeHistory.xml"; //$NON-NLS-1$
- private static final String NODE_ROOT= "typeInfoHistroy"; //$NON-NLS-1$
- private static final String NODE_TYPE_INFO= "typeInfo"; //$NON-NLS-1$
- private static final String NODE_HANDLE= "handle"; //$NON-NLS-1$
- private static final String NODE_MODIFIERS= "modifiers"; //$NON-NLS-1$
- private static final String NODE_TIMESTAMP= "timestamp"; //$NON-NLS-1$
-
- private static OpenTypeHistory fgInstance;
-
- public static synchronized OpenTypeHistory getInstance() {
- if (fgInstance == null)
- fgInstance= new OpenTypeHistory();
- return fgInstance;
- }
-
- public static synchronized void shutdown() {
- if (fgInstance == null)
- return;
- fgInstance.doShutdown();
- }
-
- private OpenTypeHistory() {
- super(FILENAME, NODE_ROOT, NODE_TYPE_INFO);
- fTimestampMapping= new HashMap();
- fNeedsConsistencyCheck= true;
- load();
- fDeltaListener= new TypeHistoryDeltaListener();
- JavaScriptCore.addElementChangedListener(fDeltaListener);
- fUpdateJob= new UpdateJob();
- // It is not necessary anymore that the update job has a rule since
- // markAsInconsistent isn't synchronized anymore. See bugs
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=128399 and
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=135278
- // for details.
- fUpdateJob.setPriority(Job.SHORT);
- }
-
- public void markAsInconsistent() {
- fNeedsConsistencyCheck= true;
- // cancel the old job. If no job is running this is a NOOP.
- fUpdateJob.cancel();
- fUpdateJob.schedule();
- }
-
- public boolean needConsistencyCheck() {
- return fNeedsConsistencyCheck;
- }
-
- public void checkConsistency(IProgressMonitor monitor) throws OperationCanceledException {
- if (!fNeedsConsistencyCheck)
- return;
- if (fUpdateJob.getState() == Job.RUNNING) {
- try {
- Job.getJobManager().join(UpdateJob.FAMILY, monitor);
- } catch (OperationCanceledException e) {
- // Ignore and do the consistency check without
- // waiting for the update job.
- } catch (InterruptedException e) {
- // Ignore and do the consistency check without
- // waiting for the update job.
- }
- }
- if (!fNeedsConsistencyCheck)
- return;
- internalCheckConsistency(monitor);
- }
-
- public synchronized boolean contains(TypeNameMatch type) {
- return super.contains(type);
- }
-
- public synchronized void accessed(TypeNameMatch info) {
- // Fetching the timestamp might not be cheap (remote file system
- // external Jars. So check if we alreay have one.
- if (!fTimestampMapping.containsKey(info)) {
- fTimestampMapping.put(info, new Long(getContainerTimestamp(info)));
- }
- super.accessed(info);
- }
-
- public synchronized TypeNameMatch remove(TypeNameMatch info) {
- fTimestampMapping.remove(info);
- return (TypeNameMatch)super.remove(info);
- }
-
- public synchronized void replace(TypeNameMatch old, TypeNameMatch newMatch) {
- fTimestampMapping.remove(old);
- fTimestampMapping.put(newMatch, new Long(getContainerTimestamp(newMatch)));
- super.remove(old);
- super.accessed(newMatch);
- }
-
- public synchronized TypeNameMatch[] getTypeInfos() {
- Collection values= getValues();
- int size= values.size();
- TypeNameMatch[] result= new TypeNameMatch[size];
- int i= size - 1;
- for (Iterator iter= values.iterator(); iter.hasNext();) {
- result[i]= (TypeNameMatch)iter.next();
- i--;
- }
- return result;
- }
-
- public synchronized TypeNameMatch[] getFilteredTypeInfos(TypeInfoFilter filter) {
- Collection values= getValues();
- List result= new ArrayList();
- for (Iterator iter= values.iterator(); iter.hasNext();) {
- TypeNameMatch type= (TypeNameMatch)iter.next();
- if ((filter == null || filter.matchesHistoryElement(type)) && !TypeFilter.isFiltered(type.getFullyQualifiedName()))
- result.add(type);
- }
- Collections.reverse(result);
- return (TypeNameMatch[])result.toArray(new TypeNameMatch[result.size()]);
-
- }
-
- protected Object getKey(Object object) {
- return object;
- }
-
- private synchronized void internalCheckConsistency(IProgressMonitor monitor) throws OperationCanceledException {
- // Setting fNeedsConsistencyCheck is necessary here since
- // markAsInconsistent isn't synchronized.
- fNeedsConsistencyCheck= true;
- List typesToCheck= new ArrayList(getKeys());
- monitor.beginTask(CorextMessages.TypeInfoHistory_consistency_check, typesToCheck.size());
- monitor.setTaskName(CorextMessages.TypeInfoHistory_consistency_check);
- for (Iterator iter= typesToCheck.iterator(); iter.hasNext();) {
- TypeNameMatch type= (TypeNameMatch)iter.next();
- long currentTimestamp= getContainerTimestamp(type);
- Long lastTested= (Long)fTimestampMapping.get(type);
- if (lastTested != null && currentTimestamp != IResource.NULL_STAMP && currentTimestamp == lastTested.longValue() && !isContainerDirty(type))
- continue;
- try {
- IType jType= type.getType();
- if (jType == null || !jType.exists()) {
- remove(type);
- } else {
- // copy over the modifiers since they may have changed
- int modifiers= jType.getFlags();
- if (modifiers != type.getModifiers()) {
- replace(type, SearchEngine.createTypeNameMatch(jType, modifiers));
- } else {
- fTimestampMapping.put(type, new Long(currentTimestamp));
- }
- }
- } catch (JavaScriptModelException e) {
- remove(type);
- }
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- monitor.worked(1);
- }
- monitor.done();
- fNeedsConsistencyCheck= false;
- }
-
- private long getContainerTimestamp(TypeNameMatch match) {
- try {
- IType type= match.getType();
- IResource resource= type.getResource();
- if (resource != null) {
- URI location= resource.getLocationURI();
- if (location != null) {
- IFileInfo info= EFS.getStore(location).fetchInfo();
- if (info.exists()) {
- // The element could be removed from the build path. So check
- // if the Java element still exists.
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element != null && element.exists())
- return info.getLastModified();
- }
- }
- } else { // external JAR
- IPackageFragmentRoot root= match.getPackageFragmentRoot();
- if (root.exists()) {
- IFileInfo info= EFS.getLocalFileSystem().getStore(root.getPath()).fetchInfo();
- if (info.exists()) {
- return info.getLastModified();
- }
- }
- }
- } catch (CoreException e) {
- // Fall through
- }
- return IResource.NULL_STAMP;
- }
-
-
- public boolean isContainerDirty(TypeNameMatch match) {
- IJavaScriptUnit cu= match.getType().getJavaScriptUnit();
- if (cu == null) {
- return false;
- }
- IResource resource= cu.getResource();
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- ITextFileBuffer textFileBuffer= manager.getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE);
- if (textFileBuffer != null) {
- return textFileBuffer.isDirty();
- }
- return false;
- }
-
-
- private void doShutdown() {
- JavaScriptCore.removeElementChangedListener(fDeltaListener);
- save();
- }
-
- protected Object createFromElement(Element type) {
- String handle= type.getAttribute(NODE_HANDLE);
- if (handle == null )
- return null;
-
- IJavaScriptElement element= JavaScriptCore.create(handle);
- if (!(element instanceof IType))
- return null;
-
- int modifiers= 0;
- try {
- modifiers= Integer.parseInt(type.getAttribute(NODE_MODIFIERS));
- } catch (NumberFormatException e) {
- // take zero
- }
- TypeNameMatch info= SearchEngine.createTypeNameMatch((IType) element, modifiers);
- long timestamp= IResource.NULL_STAMP;
- String timestampValue= type.getAttribute(NODE_TIMESTAMP);
- if (timestampValue != null && timestampValue.length() > 0) {
- try {
- timestamp= Long.parseLong(timestampValue);
- } catch (NumberFormatException e) {
- // take null stamp
- }
- }
- if (timestamp != IResource.NULL_STAMP) {
- fTimestampMapping.put(info, new Long(timestamp));
- }
- return info;
- }
-
- protected void setAttributes(Object object, Element typeElement) {
- TypeNameMatch type= (TypeNameMatch) object;
- String handleId= type.getType().getHandleIdentifier();
- typeElement.setAttribute(NODE_HANDLE, handleId);
- typeElement.setAttribute(NODE_MODIFIERS, Integer.toString(type.getModifiers()));
- Long timestamp= (Long) fTimestampMapping.get(type);
- if (timestamp == null) {
- typeElement.setAttribute(NODE_TIMESTAMP, Long.toString(IResource.NULL_STAMP));
- } else {
- typeElement.setAttribute(NODE_TIMESTAMP, timestamp.toString());
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java
deleted file mode 100644
index 36a2b1c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/QualifiedTypeNameHistory.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.w3c.dom.Element;
-
-public class QualifiedTypeNameHistory extends History {
-
- private static final String NODE_ROOT= "qualifiedTypeNameHistroy"; //$NON-NLS-1$
- private static final String NODE_TYPE_INFO= "fullyQualifiedTypeName"; //$NON-NLS-1$
- private static final String NODE_NAME= "name"; //$NON-NLS-1$
-
- private static QualifiedTypeNameHistory fgInstance;
-
-
- public static QualifiedTypeNameHistory getDefault() {
- if (fgInstance == null)
- fgInstance= new QualifiedTypeNameHistory("QualifiedTypeNameHistory.xml"); //$NON-NLS-1$
-
- return fgInstance;
- }
-
- public QualifiedTypeNameHistory(String fileName) {
- super(fileName, NODE_ROOT, NODE_TYPE_INFO);
- load();
- }
-
- /**
- * {@inheritDoc}
- */
- protected void setAttributes(Object object, Element element) {
- element.setAttribute(NODE_NAME, (String)object);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object createFromElement(Element element) {
- return element.getAttribute(NODE_NAME);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object getKey(Object object) {
- return object;
- }
-
- public static int getBoost(String fullyQualifiedTypeName, int min, int max) {
- float position= getDefault().getNormalizedPosition(fullyQualifiedTypeName);
- int dist= max - min;
- return Math.round(position * dist) + min;
- }
-
- public static void remember(String fullyQualifiedTypeName) {
- getDefault().accessed(fullyQualifiedTypeName);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java
deleted file mode 100644
index 49a58b8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Resources.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.io.File;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.internal.corext.CorextMessages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-
-public class Resources {
-
- private Resources() {
- }
-
- /**
- * Checks if the given resource is in sync with the underlying file system.
- *
- * @param resource the resource to be checked
- * @return IStatus status describing the check's result. If <code>status.
- * isOK()</code> returns <code>true</code> then the resource is in sync
- */
- public static IStatus checkInSync(IResource resource) {
- return checkInSync(new IResource[] {resource});
- }
-
- /**
- * Checks if the given resources are in sync with the underlying file
- * system.
- *
- * @param resources the resources to be checked
- * @return IStatus status describing the check's result. If <code>status.
- * isOK() </code> returns <code>true</code> then the resources are in sync
- */
- public static IStatus checkInSync(IResource[] resources) {
- IStatus result= null;
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) {
- result= addOutOfSync(result, resource);
- }
- }
- if (result != null)
- return result;
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- /**
- * Makes the given resource committable. Committable means that it is
- * writeable and that its content hasn't changed by calling
- * <code>validateEdit</code> for the given resource on <tt>IWorkspace</tt>.
- *
- * @param resource the resource to be checked
- * @param context the context passed to <code>validateEdit</code>
- * @return status describing the method's result. If <code>status.isOK()</code> returns <code>true</code> then the resources are committable.
- *
- * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
- */
- public static IStatus makeCommittable(IResource resource, Object context) {
- return makeCommittable(new IResource[] { resource }, context);
- }
-
- /**
- * Makes the given resources committable. Committable means that all
- * resources are writeable and that the content of the resources hasn't
- * changed by calling <code>validateEdit</code> for a given file on
- * <tt>IWorkspace</tt>.
- *
- * @param resources the resources to be checked
- * @param context the context passed to <code>validateEdit</code>
- * @return IStatus status describing the method's result. If <code>status.
- * isOK()</code> returns <code>true</code> then the add resources are
- * committable
- *
- * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
- */
- public static IStatus makeCommittable(IResource[] resources, Object context) {
- List readOnlyFiles= new ArrayList();
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource.getType() == IResource.FILE && isReadOnly(resource))
- readOnlyFiles.add(resource);
- }
- if (readOnlyFiles.size() == 0)
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
-
- Map oldTimeStamps= createModificationStampMap(readOnlyFiles);
- IStatus status= ResourcesPlugin.getWorkspace().validateEdit(
- (IFile[]) readOnlyFiles.toArray(new IFile[readOnlyFiles.size()]), context);
- if (!status.isOK())
- return status;
-
- IStatus modified= null;
- Map newTimeStamps= createModificationStampMap(readOnlyFiles);
- for (Iterator iter= oldTimeStamps.keySet().iterator(); iter.hasNext();) {
- IFile file= (IFile) iter.next();
- if (!oldTimeStamps.get(file).equals(newTimeStamps.get(file)))
- modified= addModified(modified, file);
- }
- if (modified != null)
- return modified;
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- private static Map createModificationStampMap(List files){
- Map map= new HashMap();
- for (Iterator iter= files.iterator(); iter.hasNext(); ) {
- IFile file= (IFile)iter.next();
- map.put(file, new Long(file.getModificationStamp()));
- }
- return map;
- }
-
- private static IStatus addModified(IStatus status, IFile file) {
- IStatus entry= JavaUIStatus.createError(
- IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT,
- Messages.format(CorextMessages.Resources_fileModified, file.getFullPath().toString()),
- null);
- if (status == null) {
- return entry;
- } else if (status.isMultiStatus()) {
- ((MultiStatus)status).add(entry);
- return status;
- } else {
- MultiStatus result= new MultiStatus(JavaScriptPlugin.getPluginId(),
- IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT,
- CorextMessages.Resources_modifiedResources, null);
- result.add(status);
- result.add(entry);
- return result;
- }
- }
-
- private static IStatus addOutOfSync(IStatus status, IResource resource) {
- IStatus entry= new Status(
- IStatus.ERROR,
- ResourcesPlugin.PI_RESOURCES,
- IResourceStatus.OUT_OF_SYNC_LOCAL,
- Messages.format(CorextMessages.Resources_outOfSync, resource.getFullPath().toString()),
- null);
- if (status == null) {
- return entry;
- } else if (status.isMultiStatus()) {
- ((MultiStatus)status).add(entry);
- return status;
- } else {
- MultiStatus result= new MultiStatus(
- ResourcesPlugin.PI_RESOURCES,
- IResourceStatus.OUT_OF_SYNC_LOCAL,
- CorextMessages.Resources_outOfSyncResources, null);
- result.add(status);
- result.add(entry);
- return result;
- }
- }
-
- /**
- * This method is used to generate a list of local locations to
- * be used in DnD for file transfers.
- *
- * @param resources the array of resources to get the local
- * locations for
- * @return the local locations
- */
- public static String[] getLocationOSStrings(IResource[] resources) {
- List result= new ArrayList(resources.length);
- for (int i= 0; i < resources.length; i++) {
- IPath location= resources[i].getLocation();
- if (location != null)
- result.add(location.toOSString());
- }
- return (String[]) result.toArray(new String[result.size()]);
- }
-
- /**
- * Returns the location of the given resource. For local
- * resources this is the OS path in the local file system. For
- * remote resource this is the URI.
- *
- * @param resource the resource
- * @return the location string or <code>null</code> if the
- * location URI of the resource is <code>null</code>
- */
- public static String getLocationString(IResource resource) {
- URI uri= resource.getLocationURI();
- if (uri == null)
- return null;
- return EFS.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())
- ? new File(uri).getAbsolutePath()
- : uri.toString();
- }
-
- public static boolean isReadOnly(IResource resource) {
- ResourceAttributes resourceAttributes = resource.getResourceAttributes();
- if (resourceAttributes == null) // not supported on this platform for this resource
- return false;
- return resourceAttributes.isReadOnly();
- }
-
- static void setReadOnly(IResource resource, boolean readOnly) {
- ResourceAttributes resourceAttributes = resource.getResourceAttributes();
- if (resourceAttributes == null) // not supported on this platform for this resource
- return;
-
- resourceAttributes.setReadOnly(readOnly);
- try {
- resource.setResourceAttributes(resourceAttributes);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java
deleted file mode 100644
index 916d4cc9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-
-public class SearchUtils {
-
- /**
- * @param match
- * @return the enclosing {@link IJavaScriptElement}, or null iff none
- */
- public static IJavaScriptElement getEnclosingJavaElement(SearchMatch match) {
- Object element = match.getElement();
- if (element instanceof IJavaScriptElement)
- return (IJavaScriptElement) element;
- else
- return null;
- }
-
- /**
- * @param match
- * @return the enclosing {@link IJavaScriptUnit} of the given match, or null iff none
- */
- public static IJavaScriptUnit getCompilationUnit(SearchMatch match) {
- IJavaScriptElement enclosingElement = getEnclosingJavaElement(match);
- if (enclosingElement != null){
- if (enclosingElement instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) enclosingElement;
- IJavaScriptUnit cu= (IJavaScriptUnit) enclosingElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null)
- return cu;
- }
-
- IJavaScriptElement jElement= JavaScriptCore.create(match.getResource());
- if (jElement != null && jElement.exists() && jElement.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT)
- return (IJavaScriptUnit) jElement;
- return null;
- }
-
- public static SearchParticipant[] getDefaultSearchParticipants() {
- return new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
- }
-
- /**
- * Constant for use as matchRule in {@link SearchPattern#createPattern(IJavaScriptElement, int, int)}
- * to get search behavior as of 3.1M3 (all generic instantiations are found).
- */
- public final static int GENERICS_AGNOSTIC_MATCH_RULE= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_ERASURE_MATCH;
-
- /**
- * Returns whether the given pattern is a camel case pattern or not.
- *
- * @param pattern the pattern to inspect
- * @return whether it is a camel case pattern or not
- */
- public static boolean isCamelCasePattern(String pattern) {
- return SearchPattern.validateMatchRule(
- pattern,
- SearchPattern.R_CAMELCASE_MATCH) == SearchPattern.R_CAMELCASE_MATCH;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java
deleted file mode 100644
index 37833aae..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Strings.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.LegacyActionTools;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-
-
-/**
- * Helper class to provide String manipulation functions not available in standard JDK.
- */
-public class Strings {
-
- private Strings(){}
-
- /**
- * tests if a char is lower case. Fix for 26529
- */
- public static boolean isLowerCase(char ch) {
- return Character.toLowerCase(ch) == ch;
- }
-
- public static boolean startsWithIgnoreCase(String text, String prefix) {
- int textLength= text.length();
- int prefixLength= prefix.length();
- if (textLength < prefixLength)
- return false;
- for (int i= prefixLength - 1; i >= 0; i--) {
- if (Character.toLowerCase(prefix.charAt(i)) != Character.toLowerCase(text.charAt(i)))
- return false;
- }
- return true;
- }
-
- public static String removeNewLine(String message) {
- StringBuffer result= new StringBuffer();
- int current= 0;
- int index= message.indexOf('\n', 0);
- while (index != -1) {
- result.append(message.substring(current, index));
- if (current < index && index != 0)
- result.append(' ');
- current= index + 1;
- index= message.indexOf('\n', current);
- }
- result.append(message.substring(current));
- return result.toString();
- }
-
- /**
- * Converts the given string into an array of lines. The lines
- * don't contain any line delimiter characters.
- *
- * @return the string converted into an array of strings. Returns <code>
- * null</code> if the input string can't be converted in an array of lines.
- */
- public static String[] convertIntoLines(String input) {
- try {
- ILineTracker tracker= new DefaultLineTracker();
- tracker.set(input);
- int size= tracker.getNumberOfLines();
- String result[]= new String[size];
- for (int i= 0; i < size; i++) {
- IRegion region= tracker.getLineInformation(i);
- int offset= region.getOffset();
- result[i]= input.substring(offset, offset + region.getLength());
- }
- return result;
- } catch (BadLocationException e) {
- return null;
- }
- }
-
- /**
- * Returns <code>true</code> if the given string only consists of
- * white spaces according to Java. If the string is empty, <code>true
- * </code> is returned.
- *
- * @return <code>true</code> if the string only consists of white
- * spaces; otherwise <code>false</code> is returned
- *
- * @see java.lang.Character#isWhitespace(char)
- */
- public static boolean containsOnlyWhitespaces(String s) {
- int size= s.length();
- for (int i= 0; i < size; i++) {
- if (!Character.isWhitespace(s.charAt(i)))
- return false;
- }
- return true;
- }
-
- /**
- * Removes leading tabs and spaces from the given string. If the string
- * doesn't contain any leading tabs or spaces then the string itself is
- * returned.
- */
- public static String trimLeadingTabsAndSpaces(String line) {
- int size= line.length();
- int start= size;
- for (int i= 0; i < size; i++) {
- char c= line.charAt(i);
- if (!IndentManipulation.isIndentChar(c)) {
- start= i;
- break;
- }
- }
- if (start == 0)
- return line;
- else if (start == size)
- return ""; //$NON-NLS-1$
- else
- return line.substring(start);
- }
-
- public static String trimTrailingTabsAndSpaces(String line) {
- int size= line.length();
- int end= size;
- for (int i= size - 1; i >= 0; i--) {
- char c= line.charAt(i);
- if (IndentManipulation.isIndentChar(c)) {
- end= i;
- } else {
- break;
- }
- }
- if (end == size)
- return line;
- else if (end == 0)
- return ""; //$NON-NLS-1$
- else
- return line.substring(0, end);
- }
-
- /**
- * Returns the indent of the given string in indentation units. Odd spaces
- * are not counted.
- *
- * @param line the text line
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- *
- */
- public static int computeIndentUnits(String line, IJavaScriptProject project) {
- return IndentManipulation.measureIndentUnits(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
- }
-
- /**
- * Returns the indent of the given string in indentation units. Odd spaces
- * are not counted.
- *
- * @param line the text line
- * @param tabWidth the width of the '\t' character in space equivalents
- * @param indentWidth the width of one indentation unit in space equivalents
- *
- */
- public static int computeIndentUnits(String line, int tabWidth, int indentWidth) {
- return IndentManipulation.measureIndentUnits(line, tabWidth, indentWidth);
- }
-
- /**
- * Computes the visual length of the indentation of a
- * <code>CharSequence</code>, counting a tab character as the size until
- * the next tab stop and every other whitespace character as one.
- *
- * @param line the string to measure the indent of
- * @param tabSize the visual size of a tab in space equivalents
- * @return the visual length of the indentation of <code>line</code>
- *
- */
- public static int measureIndentLength(CharSequence line, int tabSize) {
- return IndentManipulation.measureIndentInSpaces(line, tabSize);
- }
-
- /**
- * Removes the given number of indents from the line. Asserts that the given line
- * has the requested number of indents. If <code>indentsToRemove <= 0</code>
- * the line is returned.
- *
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- *
- */
- public static String trimIndent(String line, int indentsToRemove, IJavaScriptProject project) {
- return IndentManipulation.trimIndent(line, indentsToRemove, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
- }
-
- /**
- * Removes the given number of indents from the line. Asserts that the given line
- * has the requested number of indents. If <code>indentsToRemove <= 0</code>
- * the line is returned.
- *
- *
- */
- public static String trimIndent(String line, int indentsToRemove, int tabWidth, int indentWidth) {
- return IndentManipulation.trimIndent(line, indentsToRemove, tabWidth, indentWidth);
- }
-
- /**
- * Removes the common number of indents from all lines. If a line
- * only consists out of white space it is ignored.
-
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- *
- */
- public static void trimIndentation(String[] lines, IJavaScriptProject project) {
- trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), true);
- }
- /**
- * Removes the common number of indents from all lines. If a line
- * only consists out of white space it is ignored.
- *
- *
- */
- public static void trimIndentation(String[] lines, int tabWidth, int indentWidth) {
- trimIndentation(lines, tabWidth, indentWidth, true);
- }
-
- /**
- * Removes the common number of indents from all lines. If a line
- * only consists out of white space it is ignored. If <code>
- * considerFirstLine</code> is false the first line will be ignored.
- *
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- *
- */
- public static void trimIndentation(String[] lines, IJavaScriptProject project, boolean considerFirstLine) {
- trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine);
- }
-
- /**
- * Removes the common number of indents from all lines. If a line
- * only consists out of white space it is ignored. If <code>
- * considerFirstLine</code> is false the first line will be ignored.
- *
- */
- public static void trimIndentation(String[] lines, int tabWidth, int indentWidth, boolean considerFirstLine) {
- String[] toDo= new String[lines.length];
- // find indentation common to all lines
- int minIndent= Integer.MAX_VALUE; // very large
- for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) {
- String line= lines[i];
- if (containsOnlyWhitespaces(line))
- continue;
- toDo[i]= line;
- int indent= computeIndentUnits(line, tabWidth, indentWidth);
- if (indent < minIndent) {
- minIndent= indent;
- }
- }
-
- if (minIndent > 0) {
- // remove this indent from all lines
- for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) {
- String s= toDo[i];
- if (s != null)
- lines[i]= trimIndent(s, minIndent, tabWidth, indentWidth);
- else {
- String line= lines[i];
- int indent= computeIndentUnits(line, tabWidth, indentWidth);
- if (indent > minIndent)
- lines[i]= trimIndent(line, minIndent, tabWidth, indentWidth);
- else
- lines[i]= trimLeadingTabsAndSpaces(line);
- }
- }
- }
- }
-
- /**
- * Returns that part of the indentation of <code>line</code> that makes up
- * a multiple of indentation units.
- *
- * @param line the line to scan
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- * @return the indent part of <code>line</code>, but no odd spaces
- *
- */
- public static String getIndentString(String line, IJavaScriptProject project) {
- return IndentManipulation.extractIndentString(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
- }
-
- /**
- * Returns that part of the indentation of <code>line</code> that makes up
- * a multiple of indentation units.
- *
- * @param line the line to scan
- * @param tabWidth the size of one tab in space equivalents
- * @param indentWidth the size of the indent in space equivalents
- * @return the indent part of <code>line</code>, but no odd spaces
- *
- */
- public static String getIndentString(String line, int tabWidth, int indentWidth) {
- return IndentManipulation.extractIndentString(line, tabWidth, indentWidth);
- }
-
- public static String[] removeTrailingEmptyLines(String[] sourceLines) {
- int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines);
- String[] result= new String[lastNonEmpty + 1];
- for (int i= 0; i < result.length; i++) {
- result[i]= sourceLines[i];
- }
- return result;
- }
-
- private static int findLastNonEmptyLineIndex(String[] sourceLines) {
- for (int i= sourceLines.length - 1; i >= 0; i--) {
- if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$
- return i;
- }
- return -1;
- }
-
- /**
- * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added.
- * The first line of the code will not be changed. (It is considered to have no indent as it might start in
- * the middle of a line)
- *
- * @param project the java project from which to get the formatter
- * preferences, or <code>null</code> for global preferences
- *
- */
- public static String changeIndent(String code, int codeIndentLevel, IJavaScriptProject project, String newIndent, String lineDelim) {
- return IndentManipulation.changeIndent(code, codeIndentLevel, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), newIndent, lineDelim);
- }
-
- /**
- * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added.
- * The first line of the code will not be changed. (It is considered to have no indent as it might start in
- * the middle of a line)
- *
- */
- public static String changeIndent(String code, int codeIndentLevel, int tabWidth, int indentWidth, String newIndent, String lineDelim) {
- return IndentManipulation.changeIndent(code, codeIndentLevel, tabWidth, indentWidth, newIndent, lineDelim);
- }
-
- public static String trimIndentation(String source, IJavaScriptProject project, boolean considerFirstLine) {
- return trimIndentation(source, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine);
- }
-
- public static String trimIndentation(String source, int tabWidth, int indentWidth, boolean considerFirstLine) {
- try {
- ILineTracker tracker= new DefaultLineTracker();
- tracker.set(source);
- int size= tracker.getNumberOfLines();
- if (size == 1)
- return source;
- String lines[]= new String[size];
- for (int i= 0; i < size; i++) {
- IRegion region= tracker.getLineInformation(i);
- int offset= region.getOffset();
- lines[i]= source.substring(offset, offset + region.getLength());
- }
- Strings.trimIndentation(lines, tabWidth, indentWidth, considerFirstLine);
- StringBuffer result= new StringBuffer();
- int last= size - 1;
- for (int i= 0; i < size; i++) {
- result.append(lines[i]);
- if (i < last)
- result.append(tracker.getLineDelimiter(i));
- }
- return result.toString();
- } catch (BadLocationException e) {
- Assert.isTrue(false,"Can not happend"); //$NON-NLS-1$
- return null;
- }
- }
-
-
- /**
- * Concatenate the given strings into one strings using the passed line delimiter as a
- * delimiter. No delimiter is added to the last line.
- */
- public static String concatenate(String[] lines, String delimiter) {
- StringBuffer buffer= new StringBuffer();
- for (int i= 0; i < lines.length; i++) {
- if (i > 0)
- buffer.append(delimiter);
- buffer.append(lines[i]);
- }
- return buffer.toString();
- }
-
- public static boolean equals(String s, char[] c) {
- if (s.length() != c.length)
- return false;
-
- for (int i = c.length; --i >= 0;)
- if (s.charAt(i) != c[i])
- return false;
- return true;
- }
-
- public static String removeTrailingCharacters(String text, char toRemove) {
- int size= text.length();
- int end= size;
- for (int i= size - 1; i >= 0; i--) {
- char c= text.charAt(i);
- if (c == toRemove) {
- end= i;
- } else {
- break;
- }
- }
- if (end == size)
- return text;
- else if (end == 0)
- return ""; //$NON-NLS-1$
- else
- return text.substring(0, end);
- }
-
- public static String removeMnemonicIndicator(String string) {
- return LegacyActionTools.removeMnemonics(string);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java
deleted file mode 100644
index 0d80b924..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SuperTypeHierarchyCache.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeHierarchyChangedListener;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-public class SuperTypeHierarchyCache {
-
- private static class HierarchyCacheEntry implements ITypeHierarchyChangedListener {
-
- private ITypeHierarchy fTypeHierarchy;
- private long fLastAccess;
-
- public HierarchyCacheEntry(ITypeHierarchy hierarchy) {
- fTypeHierarchy= hierarchy;
- fTypeHierarchy.addTypeHierarchyChangedListener(this);
- markAsAccessed();
- }
-
- public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) {
- removeHierarchyEntryFromCache(this);
- }
-
- public ITypeHierarchy getTypeHierarchy() {
- return fTypeHierarchy;
- }
-
- public void markAsAccessed() {
- fLastAccess= System.currentTimeMillis();
- }
-
- public long getLastAccess() {
- return fLastAccess;
- }
-
- public void dispose() {
- fTypeHierarchy.removeTypeHierarchyChangedListener(this);
- fTypeHierarchy= null;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "Super hierarchy of: " + fTypeHierarchy.getType().getElementName(); //$NON-NLS-1$
- }
-
- }
-
-
- private static final int CACHE_SIZE= 8;
-
- private static ArrayList fgHierarchyCache= new ArrayList(CACHE_SIZE);
- private static Map fgMethodOverrideTesterCache= new LRUMap(CACHE_SIZE);
-
- private static int fgCacheHits= 0;
- private static int fgCacheMisses= 0;
-
- /**
- * Get a hierarchy for the given type
- */
- public static ITypeHierarchy getTypeHierarchy(IType type) throws JavaScriptModelException {
- return getTypeHierarchy(type, null);
- }
-
- public static MethodOverrideTester getMethodOverrideTester(IType type) throws JavaScriptModelException {
- MethodOverrideTester test= null;
- synchronized (fgMethodOverrideTesterCache) {
- test= (MethodOverrideTester) fgMethodOverrideTesterCache.get(type);
- }
- if (test == null) {
- ITypeHierarchy hierarchy= getTypeHierarchy(type); // don't nest the locks
- synchronized (fgMethodOverrideTesterCache) {
- test= (MethodOverrideTester) fgMethodOverrideTesterCache.get(type); // test again after waiting a long time for 'getTypeHierarchy'
- if (test == null) {
- test= new MethodOverrideTester(type, hierarchy);
- fgMethodOverrideTesterCache.put(type, test);
- }
- }
- }
- return test;
- }
-
- private static void removeMethodOverrideTester(ITypeHierarchy hierarchy) {
- synchronized (fgMethodOverrideTesterCache) {
- for (Iterator iter= fgMethodOverrideTesterCache.values().iterator(); iter.hasNext();) {
- MethodOverrideTester curr= (MethodOverrideTester) iter.next();
- if (curr.getTypeHierarchy().equals(hierarchy)) {
- iter.remove();
- }
- }
- }
- }
-
-
- /**
- * Get a hierarchy for the given type
- */
- public static ITypeHierarchy getTypeHierarchy(IType type, IProgressMonitor progressMonitor) throws JavaScriptModelException {
- ITypeHierarchy hierarchy= findTypeHierarchyInCache(type);
- if (hierarchy == null) {
- fgCacheMisses++;
- hierarchy= type.newSupertypeHierarchy(progressMonitor);
- addTypeHierarchyToCache(hierarchy);
- } else {
- fgCacheHits++;
- }
- return hierarchy;
- }
-
- private static void addTypeHierarchyToCache(ITypeHierarchy hierarchy) {
- synchronized (fgHierarchyCache) {
- int nEntries= fgHierarchyCache.size();
- if (nEntries >= CACHE_SIZE) {
- // find obsolete entries or remove entry that was least recently accessed
- HierarchyCacheEntry oldest= null;
- ArrayList obsoleteHierarchies= new ArrayList(CACHE_SIZE);
- for (int i= 0; i < nEntries; i++) {
- HierarchyCacheEntry entry= (HierarchyCacheEntry) fgHierarchyCache.get(i);
- ITypeHierarchy curr= entry.getTypeHierarchy();
- if (!curr.exists() || hierarchy.contains(curr.getType())) {
- obsoleteHierarchies.add(entry);
- } else {
- if (oldest == null || entry.getLastAccess() < oldest.getLastAccess()) {
- oldest= entry;
- }
- }
- }
- if (!obsoleteHierarchies.isEmpty()) {
- for (int i= 0; i < obsoleteHierarchies.size(); i++) {
- removeHierarchyEntryFromCache((HierarchyCacheEntry) obsoleteHierarchies.get(i));
- }
- } else if (oldest != null) {
- removeHierarchyEntryFromCache(oldest);
- }
- }
- HierarchyCacheEntry newEntry= new HierarchyCacheEntry(hierarchy);
- fgHierarchyCache.add(newEntry);
- }
- }
-
-
- /**
- * Check if the given type is in the hierarchy
- * @param type
- * @return Return <code>true</code> if a hierarchy for the given type is cached.
- */
- public static boolean hasInCache(IType type) {
- return findTypeHierarchyInCache(type) != null;
- }
-
-
- private static ITypeHierarchy findTypeHierarchyInCache(IType type) {
- synchronized (fgHierarchyCache) {
- for (int i= fgHierarchyCache.size() - 1; i>= 0; i--) {
- HierarchyCacheEntry curr= (HierarchyCacheEntry) fgHierarchyCache.get(i);
- ITypeHierarchy hierarchy= curr.getTypeHierarchy();
- if (!hierarchy.exists()) {
- removeHierarchyEntryFromCache(curr);
- } else {
- if (hierarchy.contains(type)) {
- curr.markAsAccessed();
- return hierarchy;
- }
- }
- }
- }
- return null;
- }
-
- private static void removeHierarchyEntryFromCache(HierarchyCacheEntry entry) {
- synchronized (fgHierarchyCache) {
- removeMethodOverrideTester(entry.getTypeHierarchy());
- entry.dispose();
- fgHierarchyCache.remove(entry);
- }
- }
-
-
- /**
- * Gets the number of times the hierarchy could be taken from the hierarchy.
- * @return Returns a int
- */
- public static int getCacheHits() {
- return fgCacheHits;
- }
-
- /**
- * Gets the number of times the hierarchy was build. Used for testing.
- * @return Returns a int
- */
- public static int getCacheMisses() {
- return fgCacheMisses;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java
deleted file mode 100644
index 789fac5b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeFilter.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- *
- */
-public class TypeFilter implements IPropertyChangeListener {
-
- public static TypeFilter getDefault() {
- return JavaScriptPlugin.getDefault().getTypeFilter();
- }
-
- public static boolean isFiltered(String fullTypeName) {
- return getDefault().filter(fullTypeName);
- }
-
- public static boolean isFiltered(char[] fullTypeName) {
- return getDefault().filter(new String(fullTypeName));
- }
-
- public static boolean isFiltered(char[] packageName, char[] typeName) {
- return getDefault().filter(JavaModelUtil.concatenateName(packageName, typeName));
- }
-
- public static boolean isFiltered(IType type) {
- TypeFilter typeFilter = getDefault();
- if (typeFilter.hasFilters()) {
- return typeFilter.filter(JavaModelUtil.getFullyQualifiedName(type));
- }
- return false;
- }
-
- public static boolean isFiltered(TypeNameMatch match) {
- return getDefault().filter(match.getFullyQualifiedName());
- }
-
- private StringMatcher[] fStringMatchers;
-
- /**
- *
- */
- public TypeFilter() {
- fStringMatchers= null;
- PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this);
- }
-
- private synchronized StringMatcher[] getStringMatchers() {
- if (fStringMatchers == null) {
- String str= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.TYPEFILTER_ENABLED);
- StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
- int nTokens= tok.countTokens();
-
- fStringMatchers= new StringMatcher[nTokens];
- for (int i= 0; i < nTokens; i++) {
- String curr= tok.nextToken();
- if (curr.length() > 0) {
- fStringMatchers[i]= new StringMatcher(curr, false, false);
- }
- }
- }
- return fStringMatchers;
- }
-
- public void dispose() {
- PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this);
- fStringMatchers= null;
- }
-
-
- public boolean hasFilters() {
- return getStringMatchers().length > 0;
- }
-
- public boolean filter(String fullTypeName) {
- StringMatcher[] matchers= getStringMatchers();
- for (int i= 0; i < matchers.length; i++) {
- StringMatcher curr= matchers[i];
- if (curr.match(fullTypeName)) {
- return true;
- }
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public synchronized void propertyChange(PropertyChangeEvent event) {
- if (PreferenceConstants.TYPEFILTER_ENABLED.equals(event.getProperty())) {
- fStringMatchers= null;
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java
deleted file mode 100644
index 84c6d45c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoFilter.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension;
-
-public class TypeInfoFilter {
-
- private static class PatternMatcher {
-
- private String fPattern;
- private int fMatchKind;
- private StringMatcher fStringMatcher;
-
- private static final char END_SYMBOL= '<';
- private static final char ANY_STRING= '*';
- private static final char BLANK= ' ';
-
- public PatternMatcher(String pattern, boolean ignoreCase) {
- this(pattern, SearchPattern.R_EXACT_MATCH | SearchPattern.R_PREFIX_MATCH |
- SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CAMELCASE_MATCH);
- }
-
- public PatternMatcher(String pattern, int allowedModes) {
- initializePatternAndMatchKind(pattern);
- fMatchKind= fMatchKind & allowedModes;
- if (fMatchKind == SearchPattern.R_PATTERN_MATCH) {
- fStringMatcher= new StringMatcher(fPattern, true, false);
- }
- }
-
- public String getPattern() {
- return fPattern;
- }
-
- public int getMatchKind() {
- return fMatchKind;
- }
-
- public boolean matches(String text) {
- switch (fMatchKind) {
- case SearchPattern.R_PATTERN_MATCH:
- return fStringMatcher.match(text);
- case SearchPattern.R_EXACT_MATCH:
- return fPattern.equalsIgnoreCase(text);
- case SearchPattern.R_CAMELCASE_MATCH:
- if (SearchPattern.camelCaseMatch(fPattern, text)) {
- return true;
- }
- // fall through to prefix match if camel case failed (bug 137244)
- //$FALL-THROUGH$
- default:
- return Strings.startsWithIgnoreCase(text, fPattern);
- }
- }
-
- private void initializePatternAndMatchKind(String pattern) {
- int length= pattern.length();
- if (length == 0) {
- fMatchKind= SearchPattern.R_EXACT_MATCH;
- fPattern= pattern;
- return;
- }
- char last= pattern.charAt(length - 1);
-
- if (pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1) {
- fMatchKind= SearchPattern.R_PATTERN_MATCH;
- switch (last) {
- case END_SYMBOL:
- fPattern= pattern.substring(0, length - 1);
- break;
- case BLANK:
- fPattern= pattern.trim();
- break;
- case ANY_STRING:
- fPattern= pattern;
- break;
- default:
- fPattern= pattern + ANY_STRING;
- }
- return;
- }
-
- if (last == END_SYMBOL) {
- fMatchKind= SearchPattern.R_EXACT_MATCH;
- fPattern= pattern.substring(0, length - 1);
- return;
- }
-
- if (last == BLANK) {
- fMatchKind= SearchPattern.R_EXACT_MATCH;
- fPattern= pattern.trim();
- return;
- }
-
- if (SearchUtils.isCamelCasePattern(pattern)) {
- fMatchKind= SearchPattern.R_CAMELCASE_MATCH;
- fPattern= pattern;
- return;
- }
-
- fMatchKind= SearchPattern.R_PREFIX_MATCH;
- fPattern= pattern;
- }
- }
-
- private String fText;
- private IJavaScriptSearchScope fSearchScope;
- private boolean fIsWorkspaceScope;
- private int fElementKind;
- private ITypeInfoFilterExtension fFilterExtension;
- private TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter();
-
- private PatternMatcher fPackageMatcher;
- private PatternMatcher fNameMatcher;
-
- public TypeInfoFilter(String text, IJavaScriptSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) {
- fText= text;
- fSearchScope= scope;
- fIsWorkspaceScope= fSearchScope.equals(SearchEngine.createWorkspaceScope());
- fElementKind= elementKind;
- fFilterExtension= extension;
-
- int index= text.lastIndexOf("."); //$NON-NLS-1$
- if (index == -1) {
- fNameMatcher= new PatternMatcher(text, true);
- } else {
- fPackageMatcher= new PatternMatcher(evaluatePackagePattern(text.substring(0, index)), true);
- String name= text.substring(index + 1);
- if (name.length() == 0)
- name= "*"; //$NON-NLS-1$
- fNameMatcher= new PatternMatcher(name, true);
- }
- }
-
- /*
- * Transforms o.e.j to o*.e*.j*
- */
- private String evaluatePackagePattern(String s) {
- StringBuffer buf= new StringBuffer();
- boolean hasWildCard= false;
- for (int i= 0; i < s.length(); i++) {
- char ch= s.charAt(i);
- if (ch == '.') {
- if (!hasWildCard) {
- buf.append('*');
- }
- hasWildCard= false;
- } else if (ch == '*' || ch =='?') {
- hasWildCard= true;
- }
- buf.append(ch);
- }
- if (!hasWildCard) {
- buf.append('*');
- }
- return buf.toString();
- }
-
- public String getText() {
- return fText;
- }
-
- public boolean isSubFilter(String text) {
- if (! fText.startsWith(text))
- return false;
-
- return fText.indexOf('.', text.length()) == -1;
- }
-
- public boolean isCamelCasePattern() {
- return fNameMatcher.getMatchKind() == SearchPattern.R_CAMELCASE_MATCH;
- }
-
- public String getPackagePattern() {
- if (fPackageMatcher == null)
- return null;
- return fPackageMatcher.getPattern();
- }
-
- public String getNamePattern() {
- return fNameMatcher.getPattern();
- }
-
- public int getSearchFlags() {
- return fNameMatcher.getMatchKind();
- }
-
- public int getPackageFlags() {
- if (fPackageMatcher == null)
- return SearchPattern.R_EXACT_MATCH;
-
- return fPackageMatcher.getMatchKind();
- }
-
- public boolean matchesRawNamePattern(TypeNameMatch type) {
- return Strings.startsWithIgnoreCase(type.getSimpleTypeName(), fNameMatcher.getPattern());
- }
-
- public boolean matchesCachedResult(TypeNameMatch type) {
- if (!(matchesPackage(type) && matchesFilterExtension(type)))
- return false;
- return matchesName(type);
- }
-
- public boolean matchesHistoryElement(TypeNameMatch type) {
- if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type)))
- return false;
- return matchesName(type);
- }
-
- public boolean matchesFilterExtension(TypeNameMatch type) {
- if (fFilterExtension == null)
- return true;
- fAdapter.setMatch(type);
- return fFilterExtension.select(fAdapter);
- }
-
- private boolean matchesName(TypeNameMatch type) {
- return fNameMatcher.matches(type.getSimpleTypeName());
- }
-
- private boolean matchesPackage(TypeNameMatch type) {
- if (fPackageMatcher == null)
- return true;
- return fPackageMatcher.matches(type.getTypeContainerName());
- }
-
- private boolean matchesScope(TypeNameMatch type) {
- if (fIsWorkspaceScope)
- return true;
- return fSearchScope.encloses(type.getType());
- }
-
- private boolean matchesModifiers(TypeNameMatch type) {
- if (fElementKind == IJavaScriptSearchConstants.TYPE)
- return true;
- int modifiers= type.getModifiers();
- switch (fElementKind) {
- case IJavaScriptSearchConstants.CLASS:
- return modifiers == 0;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java
deleted file mode 100644
index b3421317..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeInfoRequestorAdapter.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor;
-
-
-public class TypeInfoRequestorAdapter implements ITypeInfoRequestor {
-
- private TypeNameMatch fMatch;
-
- public void setMatch(TypeNameMatch type) {
- fMatch= type;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getEnclosingName()
- */
- public String getEnclosingName() {
- return Signature.getQualifier(fMatch.getTypeQualifiedName());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getModifiers()
- */
- public int getModifiers() {
- return fMatch.getModifiers();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getPackageName()
- */
- public String getPackageName() {
- return fMatch.getPackageName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoRequestor#getTypeName()
- */
- public String getTypeName() {
- return fMatch.getSimpleTypeName();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java
deleted file mode 100644
index 63f7bd71..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/TypeNameMatchCollector.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.corext.util;
-
-import java.util.Collection;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor;
-
-public class TypeNameMatchCollector extends TypeNameMatchRequestor {
-
- private final Collection fCollection;
-
- public TypeNameMatchCollector(Collection collection) {
- Assert.isNotNull(collection);
- fCollection= collection;
- }
-
- private boolean inScope(TypeNameMatch match) {
- return !TypeFilter.isFiltered(match);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch)
- */
- public void acceptTypeNameMatch(TypeNameMatch match) {
- if (inScope(match)) {
- fCollection.add(match);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/CompatibilityTemplateStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/CompatibilityTemplateStore.java
deleted file mode 100644
index 1416c89f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/CompatibilityTemplateStore.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.templates.ContextTypeRegistry;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.jface.text.templates.persistence.TemplateStore;
-import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
-
-
-/**
- * for compatibility only - don't use
- */
-public final class CompatibilityTemplateStore extends ContributionTemplateStore {
-
-
- private org.eclipse.wst.jsdt.internal.corext.template.java.TemplateSet fLegacySet;
-
- public CompatibilityTemplateStore(ContextTypeRegistry registry, IPreferenceStore store, String key, org.eclipse.wst.jsdt.internal.corext.template.java.TemplateSet legacySet) {
- super(registry, store, key);
- fLegacySet= legacySet;
- }
-
- public void load() throws IOException {
- super.load();
-
- if (fLegacySet != null) {
-
- List legacyTemplates= new ArrayList(Arrays.asList(fLegacySet.getTemplates()));
- fLegacySet.clear();
-
- TemplatePersistenceData[] datas= getTemplateData(true);
- for (Iterator it= legacyTemplates.listIterator(); it.hasNext();) {
- Template t= (Template) it.next();
- TemplatePersistenceData orig= findSimilarTemplate(datas, t, isCodeTemplates());
- if (orig == null) { // no contributed match for the old template found
- if (!isCodeTemplates())
- add(new TemplatePersistenceData(t, true));
- } else { // a contributed template seems to be the descendant of the non-id template t
- if (!orig.getTemplate().getPattern().equals(t.getPattern()))
- // add as modified contributed template if changed compared to the original
- orig.setTemplate(t);
- }
- }
-
- save();
- fLegacySet= null;
- }
- }
-
- private static TemplatePersistenceData findSimilarTemplate(TemplatePersistenceData[] datas, Template template, boolean isCodeTemplates) {
- for (int i= 0; i < datas.length; i++) {
- TemplatePersistenceData data= datas[i];
- Template orig= data.getTemplate();
- if (isSimilar(template, orig, isCodeTemplates))
- return data;
- }
-
- return null;
- }
-
- private static boolean isSimilar(Template t, Template orig, boolean isCodeTemplates) {
- return orig.getName().equals(t.getName()) && orig.getContextTypeId().equals(t.getContextTypeId())
- && (isCodeTemplates || orig.getDescription().equals(t.getDescription())); // only use description for templates (for, while...)
- }
-
- private boolean isCodeTemplates() {
- return fLegacySet instanceof org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplates;
- }
-
- /**
- * Removes any duplicates from a template store. Duplicate user added templates
- * are copied over their contributed siblings. If isCodeTemplates is true,
- * any user added templates are then removed.
- *
- * @param store
- * @param isCodeTemplates
- */
- public static void pruneDuplicates(TemplateStore store, boolean isCodeTemplates) {
- TemplatePersistenceData[] datas= store.getTemplateData(true);
- for (int i= datas.length - 1; i >= 0; i--) {
- TemplatePersistenceData data= datas[i];
- if (data.isUserAdded()) {
- // find a contributed template that is similar and check it
- TemplatePersistenceData similar= findSimilarTemplate(datas, data.getTemplate(), isCodeTemplates);
- if (similar != data && !similar.isUserAdded()) {
- similar.setTemplate(data.getTemplate());
- store.delete(data);
- }
- }
- }
-
- if (isCodeTemplates) {
- datas= store.getTemplateData(true);
- for (int i= datas.length - 1; i >= 0; i--) {
- if (datas[i].isUserAdded())
- store.delete(datas[i]);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/EditorInputAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/EditorInputAdapterFactory.java
deleted file mode 100644
index 5bf498df..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/EditorInputAdapterFactory.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.search.ui.ISearchPageScoreComputer;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Adapter factory to support basic UI operations for for editor inputs.
- */
-public class EditorInputAdapterFactory implements IAdapterFactory {
-
- private static Class[] PROPERTIES= new Class[] {IJavaScriptElement.class};
-
- private Object fSearchPageScoreComputer;
-
- public Class[] getAdapterList() {
- updateLazyLoadedAdapters();
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- updateLazyLoadedAdapters();
- if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key))
- return fSearchPageScoreComputer;
-
- if (IJavaScriptElement.class.equals(key) && element instanceof IEditorInput) {
- IJavaScriptElement je= JavaScriptUI.getWorkingCopyManager().getWorkingCopy((IEditorInput)element);
- if (je != null)
- return je;
- if (element instanceof IStorageEditorInput) {
- try {
- return ((IStorageEditorInput)element).getStorage().getAdapter(key);
- } catch (CoreException ex) {
- // Fall through
- }
- }
- }
- return null;
- }
-
- private void updateLazyLoadedAdapters() {
- if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
- createSearchPageScoreComputer();
- }
-
- private void createSearchPageScoreComputer() {
- fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
- PROPERTIES= new Class[] {ISearchPageScoreComputer.class, IJavaScriptElement.class};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaHelpContextIds.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaHelpContextIds.java
deleted file mode 100644
index 6503d50d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaHelpContextIds.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids <sdavids@gmx.de> bug 38692
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-/**
- * Help context ids for the Java UI.
- * <p>
- * This interface contains constants only; it is not intended to be implemented
- * or extended.
- * </p>
- *
- */
-public interface IJavaHelpContextIds {
- public static final String PREFIX= JavaScriptUI.ID_PLUGIN + '.';
-
- // Actions
- public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$
- public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$
- /* */
- public static final String GENERATE_HASHCODE_EQUALS_ACTION= PREFIX + "add_hashcode_equals_action_context"; //$NON-NLS-1$
- public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$
- public static final String CREATE_NEW_CONSTRUCTOR_ACTION= PREFIX + "create_new_constructor_action_context"; //$NON-NLS-1$
- public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$
- public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$
- public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$
- public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$
-
- public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$
- public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$
- public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$
- public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$
- public static final String FILTER_LOCALTYPES_ACTION= PREFIX + "filter_localtypes_action"; //$NON-NLS-1$
-
- public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$
- public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$
- public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$
- public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$
- public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$
- public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$
- public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$
- public static final String ADD_TO_CLASSPATH_ACTION= PREFIX + "addjtoclasspath_action_context"; //$NON-NLS-1$
- public static final String REMOVE_FROM_CLASSPATH_ACTION= PREFIX + "removefromclasspath_action_context"; //$NON-NLS-1$
-
- public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$
- public static final String TOGGLE_MARK_OCCURRENCES_ACTION= PREFIX + "toggle_mark_occurrences_action_context"; //$NON-NLS-1$
- public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$
-
- public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$
- public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$
- /** */
- public static final String OPEN_ENUM_WIZARD_ACTION= PREFIX + "open_enum_wizard_action"; //$NON-NLS-1$
- /** */
- public static final String OPEN_ANNOTATION_WIZARD_ACTION= PREFIX + "open_annotation_wizard_action"; //$NON-NLS-1$
-
- public static final String SORT_MEMBERS_ACTION= PREFIX + "sort_members_action"; //$NON-NLS-1$
-
- public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$
- public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$
- /** */
- public static final String OPEN_SOURCEFOLDER_WIZARD_ACTION= PREFIX + "open_sourcefolder_wizard_action"; //$NON-NLS-1$
-
- public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$
- public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$
- public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$
- public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$
- public static final String GOTO_TYPE_ACTION= PREFIX + "goto_type_action"; //$NON-NLS-1$
- public static final String GOTO_MATCHING_BRACKET_ACTION= PREFIX + "goto_matching_bracket_action"; //$NON-NLS-1$Object[] FORMAT_ALL= null;
-
- /**
- *
- */
- public static final String FORMAT_ALL= PREFIX + "format_all_action"; //$NON-NLS-1$
-
- public static final String GOTO_NEXT_MEMBER_ACTION= PREFIX + "goto_next_member_action"; //$NON-NLS-1$
- public static final String GOTO_PREVIOUS_MEMBER_ACTION= PREFIX + "goto_previous_member_action"; //$NON-NLS-1$
- public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$
- public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$
- public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$
- public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$
- public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$
- public static final String ADD_DELEGATE_METHODS_ACTION= PREFIX + "add_delegate_methods_action"; //$NON-NLS-1$
-
- public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$
- public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$
-
- public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$
- public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$
-
-
- /**
- *
- */
- public static final String CONFIG_CONTAINER_ACTION= PREFIX + "org.eclipse.wst.jsdt.ui.config_container_action"; //$NON-NLS-1$
-
- public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$
- public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$
- public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$
- public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$
- public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$
- public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$
- public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$
- public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$
- public static final String INTRODUCE_PARAMETER_ACTION= PREFIX + "introduce_parameter_action"; //$NON-NLS-1$
- public static final String INTRODUCE_FACTORY_ACTION= PREFIX + "introduce_factory_action"; //$NON-NLS-1$
- /**
- *
- */
- public static final String INTRODUCE_INDIRECTION_ACTION= PREFIX + "introduce_indirection_action"; //$NON-NLS-1$
-
- public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$
- public static final String CHANGE_TYPE_ACTION= PREFIX + "change_type_action"; //$NON-NLS-1$
- public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$
- public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$
- public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION= PREFIX + "find_declarations_in_workspace_action"; //$NON-NLS-1$
- public static final String FIND_DECLARATIONS_IN_PROJECT_ACTION= PREFIX + "find_declarations_in_project_action"; //$NON-NLS-1$
- public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$
- public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$
- public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION= PREFIX + "find_implementors_in_workspace_action"; //$NON-NLS-1$
- public static final String FIND_IMPLEMENTORS_IN_PROJECT_ACTION= PREFIX + "find_implementors_in_project_action"; //$NON-NLS-1$
- public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$
- public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_references_in_workspace_action"; //$NON-NLS-1$
- public static final String FIND_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_references_in_project_action"; //$NON-NLS-1$
- public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_references_in_hierarchy_action"; //$NON-NLS-1$
- public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_references_in_working_set_action"; //$NON-NLS-1$
- public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_read_references_in_workspace_action"; //$NON-NLS-1$
- public static final String FIND_READ_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_read_references_in_project_action"; //$NON-NLS-1$
- public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$
- public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$
- public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$
- public static final String FIND_WRITE_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_write_references_in_project_action"; //$NON-NLS-1$
- public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$
- public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_write_references_in_workspace_action"; //$NON-NLS-1$
- public static final String FIND_OCCURRENCES_IN_FILE_ACTION= PREFIX + "find_occurrences_in_file_action"; //$NON-NLS-1$
- public static final String FIND_EXCEPTION_OCCURRENCES= PREFIX + "find_exception_occurrences"; //$NON-NLS-1$
- public static final String FIND_IMPLEMENT_OCCURRENCES= PREFIX + "find_implement_occurrences"; //$NON-NLS-1$
- public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$
- public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$
- public static final String INLINE_ACTION= PREFIX + "inline_action"; //$NON-NLS-1$
- /**
- *
- */
- public static final String REPLACE_INVOCATIONS_ACTION= PREFIX + "replace_invocations_action"; //$NON-NLS-1$
- public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$
- public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$
- public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$
- public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$
- public static final String OPEN_INPUT_ACTION= PREFIX + "open_input_action"; //$NON-NLS-1$
- public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$
- public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$
- /**
- *
- */
- public static final String EXTRACT_SUPERTYPE_ACTION= PREFIX + "extract_supertype_action"; //$NON-NLS-1$
- public static final String PUSH_DOWN_ACTION= PREFIX + "push_down_action"; //$NON-NLS-1$
- public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$
- public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$
- public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$
- public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$
- public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$
- public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$
- public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$
- public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$
- public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$
- public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$
- public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$
- public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$
- public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$
- public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$
- public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$
- public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$
- public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$
- public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$
- public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$
- public static final String GOTO_RESOURCE_ACTION= PREFIX + "goto_resource_action"; //$NON-NLS-1$
- public static final String LINK_EDITOR_ACTION= PREFIX + "link_editor_action"; //$NON-NLS-1$
- public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION= PREFIX + "go_into_top_level_type_action"; //$NON-NLS-1$
- public static final String COMPARE_WITH_HISTORY_ACTION= PREFIX + "compare_with_history_action"; //$NON-NLS-1$
- public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION= PREFIX + "replace_with_previous_from_history_action"; //$NON-NLS-1$
- public static final String REPLACE_WITH_HISTORY_ACTION= PREFIX + "replace_with_history_action"; //$NON-NLS-1$
- public static final String ADD_FROM_HISTORY_ACTION= PREFIX + "add_from_history_action"; //$NON-NLS-1$
- public static final String LAYOUT_FLAT_ACTION= PREFIX + "layout_flat_action"; //$NON-NLS-1$
- public static final String LAYOUT_HIERARCHICAL_ACTION= PREFIX + "layout_hierarchical_action"; //$NON-NLS-1$
- // *** Don't delete this constants and the doc since it is still used in refactoring
- public static final String NEXT_CHANGE_ACTION= PREFIX + "next_change_action"; //$NON-NLS-1$
- public static final String PREVIOUS_CHANGE_ACTION= PREFIX + "previous_change_action"; //$NON-NLS-1$
- public static final String NEXT_PROBLEM_ACTION= PREFIX + "next_problem_action"; //$NON-NLS-1$
- public static final String PREVIOUS_PROBLEM_ACTION= PREFIX + "previous_problem_action"; //$NON-NLS-1$
- // *** end
- public static final String JAVA_SELECT_MARKER_RULER_ACTION= PREFIX + "java_select_marker_ruler_action"; //$NON-NLS-1$
- public static final String SHOW_QUALIFIED_NAMES_ACTION= PREFIX + "show_qualified_names_action"; //$NON-NLS-1$
- public static final String SORT_BY_DEFINING_TYPE_ACTION= PREFIX + "sort_by_defining_type_action"; //$NON-NLS-1$
- public static final String FORMAT_ACTION= PREFIX + "format_action"; //$NON-NLS-1$
- public static final String COMMENT_ACTION= PREFIX + "comment_action"; //$NON-NLS-1$
- public static final String UNCOMMENT_ACTION= PREFIX + "uncomment_action"; //$NON-NLS-1$
- /**
- *
- */
- public static final String TOGGLE_COMMENT_ACTION= PREFIX + "toggle_comment_action"; //$NON-NLS-1$
- public static final String ADD_BLOCK_COMMENT_ACTION= PREFIX + "add_block_comment_action"; //$NON-NLS-1$
- public static final String REMOVE_BLOCK_COMMENT_ACTION= PREFIX + "remove_block_comment_action"; //$NON-NLS-1$
- public static final String QUICK_FIX_ACTION= PREFIX + "quick_fix_action"; //$NON-NLS-1$
- public static final String CONTENT_ASSIST_ACTION= PREFIX + "content_assist_action"; //$NON-NLS-1$
- public static final String PARAMETER_HINTS_ACTION= PREFIX + "parameter_hints_action"; //$NON-NLS-1$
- public static final String SHOW_OUTLINE_ACTION= PREFIX + "show_outline_action"; //$NON-NLS-1$
- public static final String OPEN_STRUCTURE_ACTION= PREFIX + "open_structure_action"; //$NON-NLS-1$
- public static final String OPEN_HIERARCHY_ACTION= PREFIX + "open_hierarchy_action"; //$NON-NLS-1$
- public static final String TOGGLE_SMART_TYPING_ACTION= PREFIX + "toggle_smart_typing_action"; //$NON-NLS-1$
- public static final String INDENT_ACTION= PREFIX + "indent_action"; //$NON-NLS-1$
-
- // Dialogs
- public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$
- public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$
- public static final String TYPE_SELECTION_DIALOG2= PREFIX + "type_selection_dialog2_context"; //$NON-NLS-1$
- public static final String OPEN_PACKAGE_DIALOG= PREFIX + "open_package_dialog_context"; //$NON-NLS-1$
- public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$
- public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$
- public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$
- public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$
- public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$
- public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$
- public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$
- public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$
-
- public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$
- public static final String ADD_GETTER_SETTER_SELECTION_DIALOG= PREFIX + "add_getter_setter_selection_dialog_context"; //$NON-NLS-1$
- public static final String ADD_DELEGATE_METHODS_SELECTION_DIALOG= PREFIX + "add_delegate_methods_selection_dialog_context"; //$NON-NLS-1$
- public static final String GENERATE_HASHCODE_EQUALS_SELECTION_DIALOG= PREFIX + "hash_code_equals_tree_selection_dialog_context"; //$NON-NLS-1$
- public static final String GENERATE_CONSTRUCTOR_USING_FIELDS_SELECTION_DIALOG= PREFIX + "generate_constructor_using_fields_selection_dialog_context"; //$NON-NLS-1$
- public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_DIALOG= PREFIX + "add_unimplemented_constructors_dialog_context"; //$NON-NLS-1$
-
- public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$
- public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$
- public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$
- public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$
- public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$
- public static final String TODO_TASK_INPUT_DIALOG= PREFIX + "todo_task_input_dialog_context"; //$NON-NLS-1$
- public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$
- public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$
- public static final String EXCLUSION_PATTERN_DIALOG= PREFIX + "exclusion_pattern_dialog_context"; //$NON-NLS-1$
- public static final String ACCESS_RULES_DIALOG= PREFIX + "access_rules_dialog_context"; //$NON-NLS-1$
- public static final String OUTPUT_LOCATION_DIALOG= PREFIX + "output_location_dialog_context"; //$NON-NLS-1$
- public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$
- public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$
- public static final String NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$
- public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$
- public static final String GOTO_RESOURCE_DIALOG= PREFIX + "goto_resource_dialog"; //$NON-NLS-1$
-
- public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$
- public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG= PREFIX + "add_element_from_history_dialog_context"; //$NON-NLS-1$
- public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "compare_element_with_history_dialog_context"; //$NON-NLS-1$
- public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "replace_element_with_history_dialog_context"; //$NON-NLS-1$
-
- public static final String SORT_MEMBERS_DIALOG= PREFIX + "sort_members_dialog_context"; //$NON-NLS-1$
-
- // view parts
- public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$
- public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$
- public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$
- public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_view_context"; //$NON-NLS-1$
- public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$
- public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$
- public static final String JAVADOC_VIEW= PREFIX + "javadoc_view_context"; //$NON-NLS-1$
- public static final String SOURCE_VIEW= PREFIX + "source_view_context"; //$NON-NLS-1$
-
- // Preference/Property pages
- public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$
- public static final String SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_preference_page_context"; //$NON-NLS-1$
- public static final String TYPE_FILTER_PREFERENCE_PAGE= PREFIX + "type_filter_preference_page_context"; //$NON-NLS-1$
- public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$
- public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$
- /**
- *
- */
- public static final String CP_USERLIBRARIES_PREFERENCE_PAGE= PREFIX + "cp_userlibraries_preference_page_context"; //$NON-NLS-1$
-
- public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$
- public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$
- public static final String COMPILER_PROPERTY_PAGE= PREFIX + "compiler_property_page_context"; //$NON-NLS-1$
- public static final String JAVA_BUILD_PROPERTY_PAGE= PREFIX + "java_build_property_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_PROBLEMS_PROPERTY_PAGE= PREFIX + "javadoc_problems_property_page_context"; //$NON-NLS-1$
- public static final String PROBLEM_SEVERITIES_PROPERTY_PAGE= PREFIX + "problem_severities_property_page_context"; //$NON-NLS-1$
- public static final String TODOTASK_PROPERTY_PAGE= PREFIX + "tasktags_property_page_context"; //$NON-NLS-1$
-
- /**
- *
- */
- public static final String CODE_TEMPLATES_PREFERENCE_PAGE= PREFIX + "code_templates_preference_context"; //$NON-NLS-1$
-
- public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$
- public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$
- public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$
- public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$
- public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$
- public static final String SPELLING_CONFIGURATION_BLOCK= PREFIX + "spelling_configuration_block_context"; //$NON-NLS-1$
- public static final String PROPERTIES_FILE_EDITOR_PREFERENCE_PAGE= PREFIX + "properties_file_editor_preference_page_context"; //$NON-NLS-1$
- public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$
- public static final String JAVA_BUILD_PREFERENCE_PAGE= PREFIX + "java_build_preference_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_PROBLEMS_PREFERENCE_PAGE= PREFIX + "javadoc_problems_preference_page_context"; //$NON-NLS-1$
- public static final String PROBLEM_SEVERITIES_PREFERENCE_PAGE= PREFIX + "problem_severities_preference_page_context"; //$NON-NLS-1$
- public static final String TODOTASK_PREFERENCE_PAGE= PREFIX + "tasktags_preference_page_context"; //$NON-NLS-1$
-
- public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$
- public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "javadoc_configuration_property_page_context"; //$NON-NLS-1$
- public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_page_context"; //$NON-NLS-1$
-
- // Wizard pages
- public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$
- public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$
- public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$
- public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$
-
- // since 3.1
- public static final String NEW_ENUM_WIZARD_PAGE= PREFIX + "new_enum_wizard_page_context"; //$NON-NLS-1$
- // since 3.1
- public static final String NEW_ANNOTATION_WIZARD_PAGE= PREFIX + "new_annotation_wizard_page_context"; //$NON-NLS-1$
-
- public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$
- public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$
- // since 3.2
- public static final String JARPACKAGER_REFACTORING_DIALOG= PREFIX + "jar_packager_refactoring_dialog_context"; //$NON-NLS-1$
- // since 3.2
- public static final String JARIMPORT_WIZARD_PAGE= PREFIX + "jar_import_wizard_page_context"; //$NON-NLS-1$
- // since 3.2
- public static final String INCLUSION_EXCLUSION_WIZARD_PAGE= PREFIX + "edit_inclusion_exlusion_filter_wizard_page_context"; //$NON-NLS-1$
- public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$
- public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$
- public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$
-
- public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_page_context"; //$NON-NLS-1$
- public static final String JAVADOC_COMMAND_PAGE= PREFIX + "javadoc_command_page_context"; //$NON-NLS-1$
-
- // Same help for all refactoring error pages. Indidivual help can
- // be provided per a single refactoring status.
- // *** Don't delete this constants and the doc since it is still used in refactoring
- public static final String REFACTORING_ERROR_WIZARD_PAGE= PREFIX + "refactoring_error_wizard_page_context"; //$NON-NLS-1$
- // same help for all refactoring preview pages
- // *** Don't delete this constants and the doc since it is still used in refactoring
- public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$
-
- public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$
- public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$
- public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$
- public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$
- public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$
- public static final String EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$
- public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$
- public static final String INTRODUCE_PARAMETER_WIZARD_PAGE= PREFIX + "introduce_parameter_page_context"; //$NON-NLS-1$
- public static final String INTRODUCE_FACTORY_WIZARD_PAGE= PREFIX + "introduce_factory_wizard_page_context"; //$NON-NLS-1$
- /**
- *
- */
- public static final String INTRODUCE_INDIRECTION_WIZARD_PAGE= PREFIX + "introduce_indirection_wizard_page_context"; //$NON-NLS-1$
-
- public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$
- public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$
- public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$
- public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$
- public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$
- public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$
- /**
- *
- */
- public static final String EXTRACT_SUPERTYPE_WIZARD_PAGE= PREFIX + "extract_supertype_wizard_page_context"; //$NON-NLS-1$
- public static final String PUSH_DOWN_WIZARD_PAGE= PREFIX + "push_down_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_TYPE_PARAMETER_WIZARD_PAGE= PREFIX + "rename_type_parameter_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_LOCAL_VARIABLE_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_RESOURCE_WIZARD_PAGE= PREFIX + "rename_resource_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_JAVA_PROJECT_WIZARD_PAGE= PREFIX + "rename_java_project_wizard_page_context"; //$NON-NLS-1$
- public static final String RENAME_SOURCE_FOLDER_WIZARD_PAGE= PREFIX + "rename_source_folder_wizard_page_context"; //$NON-NLS-1$
- public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$
- public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$
- public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$
- public static final String INLINE_CONSTANT_WIZARD_PAGE= PREFIX + "inline_constant_wizard_page_context"; //$NON-NLS-1$
- public static final String SELECT_CLEAN_UPS_PAGE= PREFIX + "select_clean_ups_wizard_page_context"; //$NON-NLS-1$
-
- public static final String INFER_TYPE_ARGUMENTS_WIZARD_PAGE= PREFIX + "infer_type_arguments_wizard_page_context"; //$NON-NLS-1$
- public static final String CHANGE_TYPE_WIZARD_PAGE= PREFIX + "change_type_wizard_page_context"; //$NON-NLS-1$
- public static final String INLINE_TEMP_WIZARD_PAGE= PREFIX + "inline_temp_wizard_page_context"; //$NON-NLS-1$
-
- // reused ui-blocks
- public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$
- public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$
-
- // Custom Filters
- public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$
-
- // Call Hierarchy
- public static final String CALL_HIERARCHY_VIEW= PREFIX + "call_hierarchy_view_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_FILTERS_DIALOG= PREFIX + "call_hierarchy_filters_dialog_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION= PREFIX + "call_hierarchy_focus_on_selection_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_HISTORY_ACTION= PREFIX + "call_hierarchy_history_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION= PREFIX + "call_hierarchy_history_drop_down_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_REFRESH_ACTION= PREFIX + "call_hierarchy_refresh_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_SEARCH_SCOPE_ACTION= PREFIX + "call_hierarchy_search_scope_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_TOGGLE_JAVA_LABEL_FORMAT_ACTION= PREFIX + "call_hierarchy_toggle_java_label_format_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_COPY_ACTION= PREFIX + "call_hierarchy_copy_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_TOGGLE_IMPLEMENTORS_ACTION= PREFIX + "call_hierarchy_toggle_implementors_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_OPEN_ACTION= PREFIX + "call_hierarchy_open_action_context"; //$NON-NLS-1$
- public static final String CALL_HIERARCHY_CANCEL_SEARCH_ACTION= PREFIX + "call_hierarchy_cancel_search_action_context"; //$NON-NLS-1$
-
- /**
- *
- */
- //User library preference page
- public static final String CP_EDIT_USER_LIBRARY= PREFIX + "cp_edit_user_library"; //$NON-NLS-1$
- public static final String CP_EXPORT_USER_LIBRARY= PREFIX + "cp_export_user_library"; //$NON-NLS-1$
- public static final String CP_IMPORT_USER_LIBRARY= PREFIX + "cp_import_user_library"; //$NON-NLS-1$
- //Code style preference page
- public static final String CODE_STYLE_EDIT_PREFIX_SUFFIX= PREFIX + "code_style_edit_prefix_suffix"; //$NON-NLS-1$
- //Task tag preference page
- public static final String TASK_TAG_INPUT_DIALOG= PREFIX + "todo_task_input_dialog_context"; //$NON-NLS-1$
- //Build path
- public static final String BP_CHOOSE_EXISTING_FOLDER_TO_MAKE_SOURCE_FOLDER= PREFIX + "bp_choose_existing_folder_to_make_source_folder"; //$NON-NLS-1$
- public static final String BP_CREATE_NEW_FOLDER= PREFIX + "bp_create_new_folder_dialog"; //$NON-NLS-1$
- public static final String BP_SELECT_DEFAULT_OUTPUT_FOLDER_DIALOG= PREFIX + "bp_select_default_output_folder_dialog"; //$NON-NLS-1$
- public static final String BP_SELECT_CLASSPATH_CONTAINER= PREFIX + "bp_select_classpath_container"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java
deleted file mode 100644
index e9db530d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-/**
- * Defines status codes relevant to the Java UI plug-in. When a
- * Core exception is thrown, it contain a status object describing
- * the cause of the exception. The status objects originating from the
- * Java UI plug-in use the codes defined in this interface.
- */
-public interface IJavaStatusConstants {
-
- // Java UI status constants start at 10000 to make sure that we don't
- // collide with resource and java model constants.
-
- public static final int INTERNAL_ERROR= 10001;
-
- /**
- * Status constant indicating that an exception occurred on
- * storing or loading templates.
- */
- public static final int TEMPLATE_IO_EXCEPTION = 10002;
-
- /**
- * Status constant indicating that an validateEdit call has changed the
- * content of a file on disk.
- */
- public static final int VALIDATE_EDIT_CHANGED_CONTENT= 10003;
-
- /**
- * Status constant indicating that a <tt>ChangeAbortException</tt> has been
- * caught.
- */
- public static final int CHANGE_ABORTED= 10004;
-
- /**
- * Status constant indicating that an exception occurred while
- * parsing template file.
- */
- public static final int TEMPLATE_PARSE_EXCEPTION = 10005;
-
- /**
- * Status constant indicating that a problem occurred while notifying a post
- * save listener.
- *
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.IPostSaveListener
- *
- */
- public static final int EDITOR_POST_SAVE_NOTIFICATION= 10006;
-
- }
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaThemeConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaThemeConstants.java
deleted file mode 100644
index 5e7b7048..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaThemeConstants.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Defines the constants used in the <code>org.eclipse.ui.themes</code>
- * extension contributed by this plug-in.
- *
- *
- */
-public interface IJavaThemeConstants {
-
- String ID_PREFIX= JavaScriptUI.ID_PLUGIN + "."; //$NON-NLS-1$
-
- /**
- * Theme constant for the color used to highlight matching brackets.
- */
- public final String EDITOR_MATCHING_BRACKETS_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
-
- /**
- * Theme constant for the color used to render multi-line comments.
- */
- public final String EDITOR_MULTI_LINE_COMMENT_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR;
-
- /**
- * Theme constant for the color used to render java keywords.
- */
- public final String EDITOR_JAVA_KEYWORD_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR;
-
- /**
- * A theme constant that holds the color used to render string constants.
- */
- public final String EDITOR_STRING_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_STRING_COLOR;
-
- /**
- * A theme constant that holds the color used to render single line comments.
- */
- public final String EDITOR_SINGLE_LINE_COMMENT_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR;
-
- /**
- * A theme constant that holds the color used to render operators.
- */
- public final String EDITOR_JAVA_OPERATOR_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR;
-
- /**
- * A theme constant that holds the color used to render java default text.
- */
- public final String EDITOR_JAVA_DEFAULT_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR;
-
- /**
- * A theme constant that holds the color used to render the 'return' keyword.
- */
- public final String EDITOR_JAVA_KEYWORD_RETURN_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR;
-
- /**
- * A theme constant that holds the color used to render javadoc keywords.
- */
- public final String EDITOR_JAVADOC_KEYWORD_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR;
-
- /**
- * A theme constant that holds the color used to render javadoc tags.
- */
- public final String EDITOR_JAVADOC_TAG_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR;
-
- /**
- * A theme constant that holds the color used to render brackets.
- */
- public final String EDITOR_JAVA_BRACKET_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR;
-
- /**
- * A theme constant that holds the color used to render task tags.
- */
- public final String EDITOR_TASK_TAG_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_TASK_TAG_COLOR;
-
- /**
- * A theme constant that holds the color used to render javadoc links.
- */
- public final String EDITOR_JAVADOC_LINKS_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR;
-
- /**
- * A theme constant that holds the color used to render javadoc default text.
- */
- public final String EDITOR_JAVADOC_DEFAULT_COLOR= ID_PREFIX + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR;
-
- /**
- * A theme constant that holds the background color used in the code assist selection dialog.
- */
- public final String CODEASSIST_PROPOSALS_BACKGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND;
-
- /**
- * A theme constant that holds the foreground color used in the code assist selection dialog.
- */
- public final String CODEASSIST_PROPOSALS_FOREGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND;
-
- /**
- * A theme constant that holds the background color used for parameter hints.
- */
- public final String CODEASSIST_PARAMETERS_BACKGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND;
-
- /**
- * A theme constant that holds the foreground color used in the code assist selection dialog.
- */
- public final String CODEASSIST_PARAMETERS_FOREGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND;
-
- /**
- * Theme constant for the background color used in the code assist selection dialog to mark replaced code.
- */
- public final String CODEASSIST_REPLACEMENT_BACKGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND;
-
- /**
- * Theme constant for the foreground color used in the code
- * assist selection dialog to mark replaced code.
- */
- public final String CODEASSIST_REPLACEMENT_FOREGROUND= ID_PREFIX + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND;
-
- /**
- * Theme constant for the color used to render values in a properties file.
- */
- String PROPERTIES_FILE_COLORING_VALUE= ID_PREFIX + PreferenceConstants.PROPERTIES_FILE_COLORING_VALUE;
-
- /**
- * Theme constant for the color used to render keys in a properties file.
- */
- String PROPERTIES_FILE_COLORING_KEY= ID_PREFIX + PreferenceConstants.PROPERTIES_FILE_COLORING_KEY;
-
- /**
- * Theme constant for the color used to render arguments in a properties file.
- */
- String PROPERTIES_FILE_COLORING_ARGUMENT= ID_PREFIX + PreferenceConstants.PROPERTIES_FILE_COLORING_ARGUMENT;
-
- /**
- * Theme constant for the color used to render assignments in a properties file.
- */
- String PROPERTIES_FILE_COLORING_ASSIGNMENT= ID_PREFIX + PreferenceConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT;
-
- /**
- * Theme constant for the color used to render comments in a properties file.
- */
- String PROPERTIES_FILE_COLORING_COMMENT= ID_PREFIX + PreferenceConstants.PROPERTIES_FILE_COLORING_COMMENT;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJsGlobalScopeContainerInitializerExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJsGlobalScopeContainerInitializerExtension.java
deleted file mode 100644
index d67e6585..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJsGlobalScopeContainerInitializerExtension.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * @author childsb
- *
- */
-public interface IJsGlobalScopeContainerInitializerExtension{
- public ImageDescriptor getImage(IPath containerPath, String element, IJavaScriptProject project);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IProductConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IProductConstants.java
deleted file mode 100644
index 4288bda9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IProductConstants.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-/**
- * These constants define the set of properties that this plug-in expects to
- * be available via <code>ProductProperties#getProperty(String)</code>. The status of
- * this interface and the facilities offered is highly provisional.
- * Productization support will be reviewed and possibly modified in future
- * releases.
- *
- * @see org.eclipse.core.runtime.IProduct#getProperty(String)
- */
-
-public interface IProductConstants {
- /**
- * The "explorer" view to use when creating the JavaScript perspective
- */
- public static final String PERSPECTIVE_EXPLORER_VIEW = "idPerspectiveHierarchyView"; //$NON-NLS-1$
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IResourceLocator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IResourceLocator.java
deleted file mode 100644
index d7dc05c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IResourceLocator.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * This interface allows to locate different
- * resources which are related to an object
- */
-public interface IResourceLocator {
- /**
- * Returns the underlying finest granularity resource that contains
- * the element, or <code>null</code> if the element is not contained
- * in a resource (for example, a working copy, or an element contained
- * in an external archive).
- *
- * @param element the element for which the resource is located
- * @return the underlying resource
- * @exception JavaScriptModelException if the element does not exist or if an
- * exception occurs while accessing its underlying resource
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#getUnderlyingResource()
- */
- IResource getUnderlyingResource(Object element) throws JavaScriptModelException;
- /**
- * Returns the resource that corresponds directly to the element,
- * or <code>null</code> if there is no resource that corresponds to
- * the element.
- *
- * <p>For example, the corresponding resource for an <code>IJavaScriptUnit</code>
- * is its underlying <code>IFile</code>. The corresponding resource for
- * an <code>IPackageFragment</code> that is not contained in an archive
- * is its underlying <code>IFolder</code>. An <code>IPackageFragment</code>
- * contained in an archive has no corresponding resource. Similarly, there
- * are no corresponding resources for <code>IMethods</code>,
- * <code>IFields</code>, etc.
- *
- * @param element the element for which the resource is located
- * @return the corresponding resource
- * @exception JavaScriptModelException if the element does not exist or if an
- * exception occurs while accessing its corresponding resource
- * @see org.eclipse.wst.jsdt.core.IJavaScriptElement#getCorrespondingResource()
- */
- IResource getCorrespondingResource(Object element) throws JavaScriptModelException;
- /**
- * Returns the resource that contains the element. If the element is not
- * directly contained by a resource then a helper resource or <code>null</code>
- * is returned. Clients define the helper resource as needed.
- *
- * @param element the element for which the resource is located
- * @return the containing resource
- * @exception JavaScriptModelException if the element does not exist or if an
- * exception occurs while accessing its containing resource
- */
- IResource getContainingResource(Object element) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IUIConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IUIConstants.java
deleted file mode 100644
index 0d29b155..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IUIConstants.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public interface IUIConstants {
-
- public static final String KEY_OK= JavaScriptUI.ID_PLUGIN + ".ok.label"; //$NON-NLS-1$
- public static final String KEY_CANCEL= JavaScriptUI.ID_PLUGIN + ".cancel.label"; //$NON-NLS-1$
-
- public static final String P_ICON_NAME= JavaScriptUI.ID_PLUGIN + ".icon_name"; //$NON-NLS-1$
-
- public static final String DIALOGSTORE_LASTEXTJAR= JavaScriptUI.ID_PLUGIN + ".lastextjar"; //$NON-NLS-1$
- public static final String DIALOGSTORE_LASTJARATTACH= JavaScriptUI.ID_PLUGIN + ".lastjarattach"; //$NON-NLS-1$
- public static final String DIALOGSTORE_LASTVARIABLE= JavaScriptUI.ID_PLUGIN + ".lastvariable"; //$NON-NLS-1$
-
- public static final String DIALOGSTORE_TYPECOMMENT_DEPRECATED= JavaScriptUI.ID_PLUGIN + ".typecomment.deprecated"; //$NON-NLS-1$
-
- public static final boolean SUPPORT_REFACTORING=false;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/InitializeAfterLoadJob.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/InitializeAfterLoadJob.java
deleted file mode 100644
index f72a059b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/InitializeAfterLoadJob.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class InitializeAfterLoadJob extends UIJob {
-
- private final class RealJob extends Job {
- public RealJob(String name) {
- super(name);
- }
- protected IStatus run(IProgressMonitor monitor) {
- monitor.beginTask("", 10); //$NON-NLS-1$
- try {
- JavaScriptCore.initializeAfterLoad(new SubProgressMonitor(monitor, 6));
- JavaScriptPlugin.initializeAfterLoad(new SubProgressMonitor(monitor, 4));
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return e.getStatus();
- }
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
- public boolean belongsTo(Object family) {
- return JavaScriptUI.ID_PLUGIN.equals(family);
- }
- }
-
- public InitializeAfterLoadJob() {
- super(JavaUIMessages.InitializeAfterLoadJob_starter_job_name);
- setSystem(true);
- }
- public IStatus runInUIThread(IProgressMonitor monitor) {
- Job job = new RealJob(JavaUIMessages.JavaPlugin_initializing_ui);
- job.setPriority(Job.SHORT);
- job.schedule();
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementAdapterFactory.java
deleted file mode 100644
index ca731345..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementAdapterFactory.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.search.ui.ISearchPageScoreComputer;
-import org.eclipse.team.ui.history.IHistoryPageSource;
-import org.eclipse.ui.IContainmentAdapter;
-import org.eclipse.ui.IContributorResourceAdapter;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.ui.ide.IContributorResourceAdapter2;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.ui.views.properties.FilePropertySource;
-import org.eclipse.ui.views.properties.IPropertySource;
-import org.eclipse.ui.views.properties.ResourcePropertySource;
-import org.eclipse.ui.views.tasklist.ITaskListResourceAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.ui.compare.JavaElementHistoryPageSource;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-
-/**
- * Implements basic UI support for Java elements.
- * Implements handle to persistent support for Java elements.
- */
-public class JavaElementAdapterFactory implements IAdapterFactory, IContributorResourceAdapter, IContributorResourceAdapter2 {
-
- private static Class[] PROPERTIES= new Class[] {
- IPropertySource.class,
- IResource.class,
- IWorkbenchAdapter.class,
- IResourceLocator.class,
- IPersistableElement.class,
- IContributorResourceAdapter.class,
- IContributorResourceAdapter2.class,
- ITaskListResourceAdapter.class,
- IContainmentAdapter.class,
- IHistoryPageSource.class
- };
-
- /*
- * Do not use real type since this would cause
- * the Search plug-in to be loaded.
- */
- private Object fSearchPageScoreComputer;
- private static IResourceLocator fgResourceLocator;
- private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter;
- private static ITaskListResourceAdapter fgTaskListAdapter;
- private static JavaElementContainmentAdapter fgJavaElementContainmentAdapter;
-
- public Class[] getAdapterList() {
- updateLazyLoadedAdapters();
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- updateLazyLoadedAdapters();
- IJavaScriptElement java= getJavaElement(element);
-
- if (IPropertySource.class.equals(key)) {
- return getProperties(java);
- } if (IResource.class.equals(key)) {
- return getResource(java);
- } if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key)) {
- return fSearchPageScoreComputer;
- } if (IWorkbenchAdapter.class.equals(key)) {
- return getJavaWorkbenchAdapter();
- } if (IResourceLocator.class.equals(key)) {
- return getResourceLocator();
- } if (IPersistableElement.class.equals(key)) {
- return new PersistableJavaElementFactory(java);
- } if (IContributorResourceAdapter.class.equals(key)) {
- if (getResource(java)!=null)
- return this;
- } if (IContributorResourceAdapter2.class.equals(key)) {
- return this;
- } if (ITaskListResourceAdapter.class.equals(key)) {
- return getTaskListAdapter();
- } if (IContainmentAdapter.class.equals(key)) {
- return getJavaElementContainmentAdapter();
- } if (IHistoryPageSource.class.equals(key) && JavaElementHistoryPageSource.hasEdition(java)) {
- return JavaElementHistoryPageSource.getInstance();
- }
- return null;
- }
-
- private IResource getResource(IJavaScriptElement element) {
- // can't use IJavaScriptElement.getResource directly as we are interested in the
- // corresponding resource
- switch (element.getElementType()) {
- case IJavaScriptElement.TYPE:
- // top level types behave like the CU
- IJavaScriptElement parent= element.getParent();
- if (parent instanceof IJavaScriptUnit) {
- return ((IJavaScriptUnit) parent).getPrimary().getResource();
- }
- return null;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return ((IJavaScriptUnit) element).getPrimary().getResource();
- case IJavaScriptElement.CLASS_FILE:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- // test if in a archive
- IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (!root.isArchive()) {
- return element.getResource();
- }
- return null;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return element.getResource();
- default:
- return null;
- }
- }
-
- public IResource getAdaptedResource(IAdaptable adaptable) {
- IJavaScriptElement je= getJavaElement(adaptable);
- if (je != null)
- return getResource(je);
-
- return null;
- }
-
- public ResourceMapping getAdaptedResourceMapping(IAdaptable adaptable) {
- IJavaScriptElement je= getJavaElement(adaptable);
- if (je != null)
- return JavaElementResourceMapping.create(je);
-
- return null;
- }
-
- private IJavaScriptElement getJavaElement(Object element) {
- if (element instanceof IJavaScriptElement)
- return (IJavaScriptElement)element;
- if (element instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)element).getClassFile().getPrimaryElement();
-
- return null;
- }
-
- private IPropertySource getProperties(IJavaScriptElement element) {
- IResource resource= getResource(element);
- if (resource == null)
- return new JavaElementProperties(element);
- if (resource.getType() == IResource.FILE)
- return new FilePropertySource((IFile) resource);
- return new ResourcePropertySource(resource);
- }
-
- private void updateLazyLoadedAdapters() {
- if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
- createSearchPageScoreComputer();
- }
-
- private void createSearchPageScoreComputer() {
- fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
- PROPERTIES= new Class[] {
- IPropertySource.class,
- IResource.class,
- ISearchPageScoreComputer.class,
- IWorkbenchAdapter.class,
- IResourceLocator.class,
- IPersistableElement.class,
- IProject.class,
- IContributorResourceAdapter.class,
- IContributorResourceAdapter2.class,
- ITaskListResourceAdapter.class,
- IContainmentAdapter.class
- };
- }
-
- private static IResourceLocator getResourceLocator() {
- if (fgResourceLocator == null)
- fgResourceLocator= new ResourceLocator();
- return fgResourceLocator;
- }
-
- private static JavaWorkbenchAdapter getJavaWorkbenchAdapter() {
- if (fgJavaWorkbenchAdapter == null)
- fgJavaWorkbenchAdapter= new JavaWorkbenchAdapter();
- return fgJavaWorkbenchAdapter;
- }
-
- private static ITaskListResourceAdapter getTaskListAdapter() {
- if (fgTaskListAdapter == null)
- fgTaskListAdapter= new JavaTaskListAdapter();
- return fgTaskListAdapter;
- }
-
- private static JavaElementContainmentAdapter getJavaElementContainmentAdapter() {
- if (fgJavaElementContainmentAdapter == null)
- fgJavaElementContainmentAdapter= new JavaElementContainmentAdapter();
- return fgJavaElementContainmentAdapter;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementContainmentAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementContainmentAdapter.java
deleted file mode 100644
index b1db9c57..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementContainmentAdapter.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IContainmentAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class JavaElementContainmentAdapter implements IContainmentAdapter {
-
- private IJavaScriptModel fJavaModel= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
-
- public boolean contains(Object workingSetElement, Object element, int flags) {
- if (!(workingSetElement instanceof IJavaScriptElement) || element == null)
- return false;
-
- IJavaScriptElement workingSetJavaElement= (IJavaScriptElement)workingSetElement;
- IResource resource= null;
- IJavaScriptElement jElement= null;
- if (element instanceof IJavaScriptElement) {
- jElement= (IJavaScriptElement)element;
- resource= jElement.getResource();
- } else {
- if (element instanceof IAdaptable) {
- resource= (IResource)((IAdaptable)element).getAdapter(IResource.class);
- if (resource != null) {
- if (fJavaModel.contains(resource)) {
- jElement= JavaScriptCore.create(resource);
- if (jElement != null && !jElement.exists())
- jElement= null;
- }
- }
- }
- }
-
- if (jElement != null) {
- if (contains(workingSetJavaElement, jElement, flags))
- return true;
- if (workingSetJavaElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT &&
- resource.getType() == IResource.FOLDER && checkIfDescendant(flags))
- return isChild(workingSetJavaElement, resource);
- } else if (resource != null) {
- return contains(workingSetJavaElement, resource, flags);
- }
- return false;
- }
-
- private boolean contains(IJavaScriptElement workingSetElement, IJavaScriptElement element, int flags) {
- if (checkContext(flags) && workingSetElement.equals(element)) {
- return true;
- }
- if (checkIfChild(flags) && workingSetElement.equals(element.getParent())) {
- return true;
- }
- if (checkIfDescendant(flags) && check(workingSetElement, element)) {
- return true;
- }
- if (checkIfAncestor(flags) && check(element, workingSetElement)) {
- return true;
- }
- return false;
- }
-
- private boolean check(IJavaScriptElement ancestor, IJavaScriptElement descendent) {
- descendent= descendent.getParent();
- while (descendent != null) {
- if (ancestor.equals(descendent))
- return true;
- descendent= descendent.getParent();
- }
- return false;
- }
-
- private boolean isChild(IJavaScriptElement workingSetElement, IResource element) {
- IResource resource= workingSetElement.getResource();
- if (resource == null)
- return false;
- return check(element, resource);
- }
-
- private boolean contains(IJavaScriptElement workingSetElement, IResource element, int flags) {
- IResource workingSetResource= workingSetElement.getResource();
- if (workingSetResource == null)
- return false;
- if (checkContext(flags) && workingSetResource.equals(element)) {
- return true;
- }
- if (checkIfChild(flags) && workingSetResource.equals(element.getParent())) {
- return true;
- }
- if (checkIfDescendant(flags) && check(workingSetResource, element)) {
- return true;
- }
- if (checkIfAncestor(flags) && check(element, workingSetResource)) {
- return true;
- }
- return false;
- }
-
- private boolean check(IResource ancestor, IResource descendent) {
- descendent= descendent.getParent();
- while(descendent != null) {
- if (ancestor.equals(descendent))
- return true;
- descendent= descendent.getParent();
- }
- return false;
- }
-
- private boolean checkIfDescendant(int flags) {
- return (flags & CHECK_IF_DESCENDANT) != 0;
- }
-
- private boolean checkIfAncestor(int flags) {
- return (flags & CHECK_IF_ANCESTOR) != 0;
- }
-
- private boolean checkIfChild(int flags) {
- return (flags & CHECK_IF_CHILD) != 0;
- }
-
- private boolean checkContext(int flags) {
- return (flags & CHECK_CONTEXT) != 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementProperties.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementProperties.java
deleted file mode 100644
index 5fec3a91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaElementProperties.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import org.eclipse.jface.viewers.IBasicPropertyConstants;
-import org.eclipse.ui.views.properties.IPropertyDescriptor;
-import org.eclipse.ui.views.properties.IPropertySource;
-import org.eclipse.ui.views.properties.PropertyDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class JavaElementProperties implements IPropertySource {
-
- private IJavaScriptElement fSource;
-
- // Property Descriptors
- private static final IPropertyDescriptor[] fgPropertyDescriptors= new IPropertyDescriptor[1];
- static {
- PropertyDescriptor descriptor;
-
- // resource name
- descriptor= new PropertyDescriptor(IBasicPropertyConstants.P_TEXT, JavaUIMessages.JavaElementProperties_name);
- descriptor.setAlwaysIncompatible(true);
- fgPropertyDescriptors[0]= descriptor;
- }
-
- public JavaElementProperties(IJavaScriptElement source) {
- fSource= source;
- }
-
- public IPropertyDescriptor[] getPropertyDescriptors() {
- return fgPropertyDescriptors;
- }
-
- public Object getPropertyValue(Object name) {
- if (name.equals(IBasicPropertyConstants.P_TEXT)) {
- return fSource.getDisplayName();
- }
- return null;
- }
-
- public void setPropertyValue(Object name, Object value) {
- }
-
- public Object getEditableValue() {
- return this;
- }
-
- public boolean isPropertySet(Object property) {
- return false;
- }
-
- public void resetPropertyValue(Object property) {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java
deleted file mode 100644
index 2fc2d247..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.debug.ui.IDebugUIConstants;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.console.IConsoleConstants;
-import org.eclipse.ui.progress.IProgressConstants;
-import org.eclipse.ui.texteditor.templates.TemplatesView;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavaPerspectiveFactory implements IPerspectiveFactory {
- /**
- * Constructs a new Default layout engine.
- */
- public JavaPerspectiveFactory() {
- super();
- }
-
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
-
- IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$
-
- String explorerViewID = ProductProperties.getProperty(IProductConstants.PERSPECTIVE_EXPLORER_VIEW);
- // make sure the specified view ID is known
- if (PlatformUI.getWorkbench().getViewRegistry().find(explorerViewID) != null)
- folder.addView(explorerViewID);
- else
- folder.addView(ProductProperties.ID_PERSPECTIVE_EXPLORER_VIEW);
-
- folder.addPlaceholder(JavaScriptUI.ID_TYPE_HIERARCHY);
- folder.addPlaceholder(IPageLayout.ID_RES_NAV);
-
- IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$
- outputfolder.addView(IPageLayout.ID_PROBLEM_VIEW);
-
- outputfolder.addView(JavaScriptUI.ID_JAVADOC_VIEW);
- outputfolder.addView(JavaScriptUI.ID_SOURCE_VIEW);
- outputfolder.addPlaceholder(TemplatesView.ID);
- outputfolder.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID);
- outputfolder.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
- outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
- outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
- outputfolder.addPlaceholder(IPageLayout.ID_TASK_LIST);
- outputfolder.addPlaceholder(IPageLayout.ID_PROP_SHEET);
-
- layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
-
- layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
- layout.addActionSet(JavaScriptUI.ID_ACTION_SET);
- layout.addActionSet(JavaScriptUI.ID_ELEMENT_CREATION_ACTION_SET);
- layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
-
- // views - java
- layout.addShowViewShortcut(JavaScriptUI.ID_PACKAGES);
- layout.addShowViewShortcut(JavaScriptUI.ID_TYPE_HIERARCHY);
- layout.addShowViewShortcut(JavaScriptUI.ID_SOURCE_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_JAVADOC_VIEW);
-
- // views - search
- layout.addShowViewShortcut(NewSearchUI.SEARCH_VIEW_ID);
-
- // views - debugging
- layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
-
- // views - standard workbench
- layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
- layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
- layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
- layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
- layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
-
- // new actions - Java project creation wizard
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.JavaProjectWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.NewJSWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewEnumCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewAnnotationCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java
deleted file mode 100644
index 35bf3746..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java
+++ /dev/null
@@ -1,595 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.osgi.framework.Bundle;
-
-
-/**
- * Bundle of most images used by the Java plug-in.
- */
-public class JavaPluginImages {
-
- public static final IPath ICONS_PATH= new Path("$nl$/icons/full"); //$NON-NLS-1$
-
- private static final String NAME_PREFIX= "org.eclipse.wst.jsdt.ui."; //$NON-NLS-1$
- private static final int NAME_PREFIX_LENGTH= NAME_PREFIX.length();
-
- // The plug-in registry
- private static ImageRegistry fgImageRegistry= null;
- private static HashMap fgAvoidSWTErrorMap= null;
-
- private static final String T_OBJ= "obj16"; //$NON-NLS-1$
- private static final String T_OVR= "ovr16"; //$NON-NLS-1$
- private static final String T_WIZBAN= "wizban"; //$NON-NLS-1$
- private static final String T_ELCL= "elcl16"; //$NON-NLS-1$
- private static final String T_DLCL= "dlcl16"; //$NON-NLS-1$
- private static final String T_ETOOL= "etool16"; //$NON-NLS-1$
- private static final String T_EVIEW= "eview16"; //$NON-NLS-1$
-
- /*
- * Keys for images available from the Java-UI plug-in image registry.
- */
- public static final String IMG_MISC_PUBLIC= NAME_PREFIX + "methpub_obj.gif"; //$NON-NLS-1$
- public static final String IMG_MISC_PROTECTED= NAME_PREFIX + "methpro_obj.gif"; //$NON-NLS-1$
- public static final String IMG_MISC_PRIVATE= NAME_PREFIX + "methpri_obj.gif"; //$NON-NLS-1$
- public static final String IMG_MISC_DEFAULT= NAME_PREFIX + "methdef_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_FIELD_PUBLIC= NAME_PREFIX + "field_public_obj.gif"; //$NON-NLS-1$
- public static final String IMG_FIELD_PROTECTED= NAME_PREFIX + "field_protected_obj.gif"; //$NON-NLS-1$
- public static final String IMG_FIELD_PRIVATE= NAME_PREFIX + "field_private_obj.gif"; //$NON-NLS-1$
- public static final String IMG_FIELD_DEFAULT= NAME_PREFIX + "field_default_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_ELCL_VIEW_MENU= NAME_PREFIX + T_ELCL + "view_menu.gif"; //$NON-NLS-1$
- public static final String IMG_DLCL_VIEW_MENU= NAME_PREFIX + T_DLCL + "view_menu.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_GHOST= NAME_PREFIX + "ghost.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_SEARCH_TSK= NAME_PREFIX + "search_tsk.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_PACKDECL= NAME_PREFIX + "packd_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_IMPDECL= NAME_PREFIX + "imp_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_IMPCONT= NAME_PREFIX + "impc_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_JSEARCH= NAME_PREFIX + "jsearch_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_SEARCH_DECL= NAME_PREFIX + "search_decl_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_SEARCH_REF= NAME_PREFIX + "search_ref_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CLASS= NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CLASSALT= NAME_PREFIX + "classfo_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CLASS_DEFAULT= NAME_PREFIX + "class_default_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_INNER_CLASS_PUBLIC= NAME_PREFIX + "innerclass_public_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_CLASS_DEFAULT= NAME_PREFIX + "innerclass_default_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_CLASS_PROTECTED= NAME_PREFIX + "innerclass_protected_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_CLASS_PRIVATE= NAME_PREFIX + "innerclass_private_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_INTERFACE= NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INTERFACEALT= NAME_PREFIX + "intf_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INTERFACE_DEFAULT= NAME_PREFIX + "int_default_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_INNER_INTERFACE_PUBLIC= NAME_PREFIX + "innerinterface_public_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_INTERFACE_DEFAULT= NAME_PREFIX + "innerinterface_default_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_INTERFACE_PROTECTED= NAME_PREFIX + "innerinterface_protected_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_INNER_INTERFACE_PRIVATE= NAME_PREFIX + "innerinterface_private_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_ANNOTATION= NAME_PREFIX + "annotation_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ANNOTATION_DEFAULT= NAME_PREFIX + "annotation_default_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ANNOTATION_PROTECTED= NAME_PREFIX + "annotation_protected_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ANNOTATION_PRIVATE= NAME_PREFIX + "annotation_private_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ANNOTATION_ALT= NAME_PREFIX + "annotation_alt_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_ENUM= NAME_PREFIX + "enum_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ENUM_DEFAULT= NAME_PREFIX + "enum_default_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ENUM_PROTECTED= NAME_PREFIX + "enum_protected_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ENUM_PRIVATE= NAME_PREFIX + "enum_private_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ENUM_ALT= NAME_PREFIX + "enum_alt_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_CUNIT= NAME_PREFIX + "jcu_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CUNIT_RESOURCE= NAME_PREFIX + "jcu_resource_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CFILE= NAME_PREFIX + "classf_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CFILECLASS= NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_CFILEINT= NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_LOGICAL_PACKAGE= NAME_PREFIX + "logical_package_obj.gif";//$NON-NLS-1$
- public static final String IMG_OBJS_EMPTY_LOGICAL_PACKAGE= NAME_PREFIX + "empty_logical_package_obj.gif";//$NON-NLS-1$
- public static final String IMG_OBJS_PACKAGE= NAME_PREFIX + "package_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_EMPTY_PACK_RESOURCE= NAME_PREFIX + "empty_pack_fldr_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_EMPTY_PACKAGE= NAME_PREFIX + "empty_pack_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_PACKFRAG_ROOT= NAME_PREFIX + "packagefolder_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_JAR= NAME_PREFIX + "jar_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_EXTJAR= NAME_PREFIX + "jar_l_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_JAR_WSRC= NAME_PREFIX + "jar_src_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_EXTJAR_WSRC= NAME_PREFIX + "jar_lsrc_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ENV_VAR= NAME_PREFIX + "envvar_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_JAVA_MODEL= NAME_PREFIX + "java_model_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_UNKNOWN= NAME_PREFIX + "unknown_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_LOCAL_VARIABLE= NAME_PREFIX + "localvariable_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_PROJECT_SETTINGS= NAME_PREFIX + "settings_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_LIBRARY= NAME_PREFIX + "library_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_JAVADOCTAG= NAME_PREFIX + "jdoc_tag_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_HTMLTAG= NAME_PREFIX + "html_tag_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_TEMPLATE= NAME_PREFIX + "template_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_EXCEPTION= NAME_PREFIX + "jexception_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_ERROR= NAME_PREFIX + "jrtexception_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_BREAKPOINT_INSTALLED= NAME_PREFIX + "brkpi_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_QUICK_ASSIST= NAME_PREFIX + "quickassist_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_FIXABLE_PROBLEM= NAME_PREFIX + "quickfix_warning_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_FIXABLE_ERROR= NAME_PREFIX + "quickfix_error_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_ACCESSRULES_ATTRIB= NAME_PREFIX + "access_restriction_attrib.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_REFACTORING_FATAL= NAME_PREFIX + "fatalerror_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_REFACTORING_ERROR= NAME_PREFIX + "error_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_REFACTORING_WARNING= NAME_PREFIX + "warning_obj.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_REFACTORING_INFO= NAME_PREFIX + "info_obj.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_NLS_TRANSLATE= NAME_PREFIX + "translate.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_NLS_NEVER_TRANSLATE= NAME_PREFIX + "never_translate.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_NLS_SKIP= NAME_PREFIX + "skip.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_SEARCH_READACCESS= NAME_PREFIX + "occ_read.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_SEARCH_WRITEACCESS= NAME_PREFIX + "occ_write.gif"; //$NON-NLS-1$
- public static final String IMG_OBJS_SEARCH_OCCURRENCE= NAME_PREFIX + "occ_match.gif"; //$NON-NLS-1$
-
- public static final String IMG_OBJS_HELP= NAME_PREFIX + "help.gif"; //$NON-NLS-1$
-
- /*
- * Set of predefined Image Descriptors.
- */
- public static final ImageDescriptor DESC_VIEW_ERRORWARNING_TAB= createUnManaged(T_EVIEW, "errorwarning_tab.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_VIEW_CLASSFILEGENERATION_TAB= createUnManaged(T_EVIEW, "classfilegeneration_tab.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_VIEW_JDKCOMPLIANCE_TAB= createUnManaged(T_EVIEW, "jdkcompliance_tab.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_ELCL_FILTER= createUnManaged(T_ELCL, "filter_ps.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_FILTER= createUnManaged(T_DLCL, "filter_ps.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_ELCL_CODE_ASSIST= createUnManaged(T_ELCL, "metharg_obj.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_CODE_ASSIST= createUnManaged(T_DLCL, "metharg_obj.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_ELCL_VIEW_MENU= createManaged(T_ELCL, "view_menu.gif", IMG_ELCL_VIEW_MENU); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_VIEW_MENU= createManaged(T_DLCL, "view_menu.gif", IMG_DLCL_VIEW_MENU); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_MISC_PUBLIC= createManagedFromKey(T_OBJ, IMG_MISC_PUBLIC);
- public static final ImageDescriptor DESC_MISC_PROTECTED= createManagedFromKey(T_OBJ, IMG_MISC_PROTECTED);
- public static final ImageDescriptor DESC_MISC_PRIVATE= createManagedFromKey(T_OBJ, IMG_MISC_PRIVATE);
- public static final ImageDescriptor DESC_MISC_DEFAULT= createManagedFromKey(T_OBJ, IMG_MISC_DEFAULT);
-
- public static final ImageDescriptor DESC_FIELD_PUBLIC= createManagedFromKey(T_OBJ, IMG_FIELD_PUBLIC);
- public static final ImageDescriptor DESC_FIELD_PROTECTED= createManagedFromKey(T_OBJ, IMG_FIELD_PROTECTED);
- public static final ImageDescriptor DESC_FIELD_PRIVATE= createManagedFromKey(T_OBJ, IMG_FIELD_PRIVATE);
- public static final ImageDescriptor DESC_FIELD_DEFAULT= createManagedFromKey(T_OBJ, IMG_FIELD_DEFAULT);
-
- public static final ImageDescriptor DESC_MENU_SHIFT_RIGHT= createUnManaged(T_ETOOL, "shift_r_edit.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_MENU_SHIFT_LEFT= createUnManaged(T_ETOOL, "shift_l_edit.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OBJS_GHOST= createManagedFromKey(T_OBJ, IMG_OBJS_GHOST);
- public static final ImageDescriptor DESC_OBJS_PACKDECL= createManagedFromKey(T_OBJ, IMG_OBJS_PACKDECL);
- public static final ImageDescriptor DESC_OBJS_IMPDECL= createManagedFromKey(T_OBJ, IMG_OBJS_IMPDECL);
- public static final ImageDescriptor DESC_OBJS_IMPCONT= createManagedFromKey(T_OBJ, IMG_OBJS_IMPCONT);
- public static final ImageDescriptor DESC_OBJS_JSEARCH= createManagedFromKey(T_OBJ, IMG_OBJS_JSEARCH);
- public static final ImageDescriptor DESC_OBJS_SEARCH_DECL= createManagedFromKey(T_OBJ, IMG_OBJS_SEARCH_DECL);
- public static final ImageDescriptor DESC_OBJS_SEARCH_REF= createManagedFromKey(T_OBJ, IMG_OBJS_SEARCH_REF);
- public static final ImageDescriptor DESC_OBJS_CUNIT= createManagedFromKey(T_OBJ, IMG_OBJS_CUNIT);
- public static final ImageDescriptor DESC_OBJS_CUNIT_RESOURCE= createManagedFromKey(T_OBJ, IMG_OBJS_CUNIT_RESOURCE);
- public static final ImageDescriptor DESC_OBJS_CFILE= createManagedFromKey(T_OBJ, IMG_OBJS_CFILE);
- public static final ImageDescriptor DESC_OBJS_CFILECLASS= createManagedFromKey(T_OBJ, IMG_OBJS_CFILECLASS);
- public static final ImageDescriptor DESC_ELCL_CLEAR= createUnManaged(T_ELCL, "clear_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_CLEAR= createUnManaged(T_DLCL, "clear_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJS_CFILEINT= createManagedFromKey(T_OBJ, IMG_OBJS_CFILEINT);
- public static final ImageDescriptor DESC_OBJS_PACKAGE= createManagedFromKey(T_OBJ, IMG_OBJS_PACKAGE);
- public static final ImageDescriptor DESC_OBJS_EMPTY_LOGICAL_PACKAGE= createManagedFromKey(T_OBJ, IMG_OBJS_EMPTY_LOGICAL_PACKAGE);
- public static final ImageDescriptor DESC_OBJS_LOGICAL_PACKAGE= createManagedFromKey(T_OBJ, IMG_OBJS_LOGICAL_PACKAGE);
- public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE_RESOURCES= createManagedFromKey(T_OBJ, IMG_OBJS_EMPTY_PACK_RESOURCE);
- public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE= createManagedFromKey(T_OBJ, IMG_OBJS_EMPTY_PACKAGE);
- public static final ImageDescriptor DESC_OBJS_PACKFRAG_ROOT= createManagedFromKey(T_OBJ, IMG_OBJS_PACKFRAG_ROOT);
- public static final ImageDescriptor DESC_OBJS_PROJECT_SETTINGS= createManagedFromKey(T_OBJ, IMG_OBJS_PROJECT_SETTINGS);
-
- public static final ImageDescriptor DESC_OBJS_JAVA_MODEL= createManagedFromKey(T_OBJ, IMG_OBJS_JAVA_MODEL);
-
- public static final ImageDescriptor DESC_OBJS_CLASS= createManagedFromKey(T_OBJ, IMG_OBJS_CLASS);
- public static final ImageDescriptor DESC_OBJS_CLASS_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_CLASS_DEFAULT);
-
- public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PUBLIC= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_CLASS_PUBLIC);
- public static final ImageDescriptor DESC_OBJS_INNER_CLASS_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_CLASS_DEFAULT);
- public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PROTECTED= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_CLASS_PROTECTED);
- public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PRIVATE= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_CLASS_PRIVATE);
-
- public static final ImageDescriptor DESC_OBJS_CLASSALT= createManagedFromKey(T_OBJ, IMG_OBJS_CLASSALT);
-
- public static final ImageDescriptor DESC_OBJS_INTERFACE= createManagedFromKey(T_OBJ, IMG_OBJS_INTERFACE);
- public static final ImageDescriptor DESC_OBJS_INTERFACE_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_INTERFACE_DEFAULT);
-
- public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PUBLIC= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_INTERFACE_PUBLIC);
- public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_INTERFACE_DEFAULT);
- public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PROTECTED= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_INTERFACE_PROTECTED);
- public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PRIVATE= createManagedFromKey(T_OBJ, IMG_OBJS_INNER_INTERFACE_PRIVATE);
-
- public static final ImageDescriptor DESC_OBJS_INTERFACEALT= createManagedFromKey(T_OBJ, IMG_OBJS_INTERFACEALT);
-
- public static final ImageDescriptor DESC_OBJS_ANNOTATION= createManagedFromKey(T_OBJ, IMG_OBJS_ANNOTATION);
- public static final ImageDescriptor DESC_OBJS_ANNOTATION_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_ANNOTATION_DEFAULT);
- public static final ImageDescriptor DESC_OBJS_ANNOTATION_PROTECTED= createManagedFromKey(T_OBJ, IMG_OBJS_ANNOTATION_PROTECTED);
- public static final ImageDescriptor DESC_OBJS_ANNOTATION_PRIVATE= createManagedFromKey(T_OBJ, IMG_OBJS_ANNOTATION_PRIVATE);
- public static final ImageDescriptor DESC_OBJS_ANNOTATION_ALT= createManagedFromKey(T_OBJ, IMG_OBJS_ANNOTATION_ALT);
-
- public static final ImageDescriptor DESC_OBJS_ENUM= createManagedFromKey(T_OBJ, IMG_OBJS_ENUM);
- public static final ImageDescriptor DESC_OBJS_ENUM_DEFAULT= createManagedFromKey(T_OBJ, IMG_OBJS_ENUM_DEFAULT);
- public static final ImageDescriptor DESC_OBJS_ENUM_PROTECTED= createManagedFromKey(T_OBJ, IMG_OBJS_ENUM_PROTECTED);
- public static final ImageDescriptor DESC_OBJS_ENUM_PRIVATE= createManagedFromKey(T_OBJ, IMG_OBJS_ENUM_PRIVATE);
- public static final ImageDescriptor DESC_OBJS_ENUM_ALT= createManagedFromKey(T_OBJ, IMG_OBJS_ENUM_ALT);
-
- public static final ImageDescriptor DESC_OBJS_JAR= createManagedFromKey(T_OBJ, IMG_OBJS_JAR);
- public static final ImageDescriptor DESC_OBJS_EXTJAR= createManagedFromKey(T_OBJ, IMG_OBJS_EXTJAR);
- public static final ImageDescriptor DESC_OBJS_JAR_WSRC= createManagedFromKey(T_OBJ, IMG_OBJS_JAR_WSRC);
- public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC= createManagedFromKey(T_OBJ, IMG_OBJS_EXTJAR_WSRC);
- public static final ImageDescriptor DESC_OBJS_ENV_VAR= createManagedFromKey(T_OBJ, IMG_OBJS_ENV_VAR);
-
- public static final ImageDescriptor DESC_OBJS_LIBRARY= createManagedFromKey(T_OBJ, IMG_OBJS_LIBRARY);
-
- public static final ImageDescriptor DESC_OBJS_JAVADOCTAG= createManagedFromKey(T_OBJ, IMG_OBJS_JAVADOCTAG);
- public static final ImageDescriptor DESC_OBJS_HTMLTAG= createManagedFromKey(T_OBJ, IMG_OBJS_HTMLTAG);
-
- public static final ImageDescriptor DESC_OBJS_TEMPLATE= createManagedFromKey(T_OBJ, IMG_OBJS_TEMPLATE);
-
- public static final ImageDescriptor DESC_OBJS_EXCEPTION= createManagedFromKey(T_OBJ, IMG_OBJS_EXCEPTION);
- public static final ImageDescriptor DESC_OBJS_BREAKPOINT_INSTALLED= createManagedFromKey(T_OBJ, IMG_OBJS_BREAKPOINT_INSTALLED);
- public static final ImageDescriptor DESC_OBJS_ERROR= createManagedFromKey(T_OBJ, IMG_OBJS_ERROR);
- public static final ImageDescriptor DESC_OBJS_QUICK_ASSIST= createManagedFromKey(T_OBJ, IMG_OBJS_QUICK_ASSIST);
- public static final ImageDescriptor DESC_OBJS_FIXABLE_PROBLEM= createManagedFromKey(T_OBJ, IMG_OBJS_FIXABLE_PROBLEM);
- public static final ImageDescriptor DESC_OBJS_FIXABLE_ERROR= createManagedFromKey(T_OBJ, IMG_OBJS_FIXABLE_ERROR);
-
- // public static final ImageDescriptor DESC_OBJS_SNIPPET_EVALUATING= createManaged(T_OBJ, IMG_OBJS_SNIPPET_EVALUATING);
-
- public static final ImageDescriptor DESC_OBJS_DEFAULT_CHANGE= createUnManaged(T_OBJ, "change.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB= createUnManaged(T_OBJ, "exclusion_filter_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJS_INCLUSION_FILTER_ATTRIB= createUnManaged(T_OBJ, "inclusion_filter_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJS_OUTPUT_FOLDER_ATTRIB= createUnManaged(T_OBJ, "output_folder_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJS_SOURCE_ATTACH_ATTRIB= createUnManaged(T_OBJ, "source_attach_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJS_JAVADOC_LOCATION_ATTRIB= createUnManaged(T_OBJ, "javadoc_location_attrib.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OBJS_ACCESSRULES_ATTRIB= createManagedFromKey(T_OBJ, IMG_OBJS_ACCESSRULES_ATTRIB);
-
- public static final ImageDescriptor DESC_OBJS_REFACTORING_FATAL= createManagedFromKey(T_OBJ, IMG_OBJS_REFACTORING_FATAL);
- public static final ImageDescriptor DESC_OBJS_REFACTORING_ERROR= createManagedFromKey(T_OBJ, IMG_OBJS_REFACTORING_ERROR);
- public static final ImageDescriptor DESC_OBJS_REFACTORING_WARNING= createManagedFromKey(T_OBJ, IMG_OBJS_REFACTORING_WARNING);
- public static final ImageDescriptor DESC_OBJS_REFACTORING_INFO= createManagedFromKey(T_OBJ, IMG_OBJS_REFACTORING_INFO);
-
- public static final ImageDescriptor DESC_OBJS_NLS_TRANSLATE= createManagedFromKey(T_OBJ, IMG_OBJS_NLS_TRANSLATE);
- public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE= createManagedFromKey(T_OBJ, IMG_OBJS_NLS_NEVER_TRANSLATE);
- public static final ImageDescriptor DESC_OBJS_NLS_SKIP= createManagedFromKey(T_OBJ, IMG_OBJS_NLS_SKIP);
-
- public static final ImageDescriptor DESC_OBJS_UNKNOWN= createManagedFromKey(T_OBJ, IMG_OBJS_UNKNOWN);
-
- public static final ImageDescriptor DESC_OBJS_TYPE_SEPARATOR= createUnManaged(T_OBJ, "type_separator.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS= createManagedFromKey(T_OBJ, IMG_OBJS_SEARCH_READACCESS);
- public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS= createManagedFromKey(T_OBJ, IMG_OBJS_SEARCH_WRITEACCESS);
- public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE= createManagedFromKey(T_OBJ, IMG_OBJS_SEARCH_OCCURRENCE);
-
- public static final ImageDescriptor DESC_OBJS_LOCAL_VARIABLE= createManagedFromKey(T_OBJ, IMG_OBJS_LOCAL_VARIABLE);
-
- public static final ImageDescriptor DESC_OBJS_HELP= createManagedFromKey(T_ELCL, IMG_OBJS_HELP);
-
- public static final ImageDescriptor DESC_ELCL_ADD_TO_BP= createUnManaged(T_ELCL, "add_to_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_REMOVE_FROM_BP= createUnManaged(T_ELCL, "remove_from_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_INCLUSION= createUnManaged(T_ELCL, "inclusion_filter_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_EXCLUSION= createUnManaged(T_ELCL, "exclusion_filter_attrib.gif"); //$NON-NLS-1$
-// public static final ImageDescriptor DESC_ELCL_INCLUSION_UNDO= createUnManaged(T_ELCL, "inclusion_filter_attrib_undo.gif"); //$NON-NLS-1$
-// public static final ImageDescriptor DESC_ELCL_EXCLUSION_UNDO= createUnManaged(T_ELCL, "exclusion_filter_attrib_undo.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_ADD_TO_BP= createUnManaged(T_DLCL, "add_to_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_REMOVE_FROM_BP= createUnManaged(T_DLCL, "remove_from_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_INCLUSION= createUnManaged(T_DLCL, "inclusion_filter_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_EXCLUSION= createUnManaged(T_DLCL, "exclusion_filter_attrib.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_OUTPUT_FOLDER_ATTRIB= createUnManaged(T_DLCL, "output_folder_attrib.gif"); //$NON-NLS-1$
-// public static final ImageDescriptor DESC_DLCL_INCLUSION_UNDO= createUnManaged(T_DLCL, "inclusion_filter_attrib_undo.gif"); //$NON-NLS-1$
-// public static final ImageDescriptor DESC_DLCL_EXCLUSION_UNDO= createUnManaged(T_DLCL, "exclusion_filter_attrib_undo.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_ADD_LINKED_SOURCE_TO_BUILDPATH= createUnManaged(T_DLCL, "add_linked_source_to_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_ADD_LINKED_SOURCE_TO_BUILDPATH= createUnManaged(T_ELCL, "add_linked_source_to_buildpath.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_CONFIGURE_BUILDPATH= createUnManaged(T_DLCL, "configure_build_path.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_CONFIGURE_BUILDPATH= createUnManaged(T_ELCL, "configure_build_path.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_CONFIGURE_BUILDPATH_FILTERS= createUnManaged(T_DLCL, "configure_buildpath_filters.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_CONFIGURE_BUILDPATH_FILTERS= createUnManaged(T_ELCL, "configure_buildpath_filters.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_CONFIGURE_OUTPUT_FOLDER= createUnManaged(T_DLCL, "configure_output_folder.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_CONFIGURE_OUTPUT_FOLDER= createUnManaged(T_ELCL, "configure_output_folder.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_EXCLUDE_FROM_BUILDPATH= createUnManaged(T_DLCL, "exclude_from_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_EXCLUDE_FROM_BUILDPATH= createUnManaged(T_ELCL, "exclude_from_buildpath.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_INCLUDE_ON_BUILDPATH= createUnManaged(T_DLCL, "include_on_buildpath.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_INCLUDE_ON_BUILDPATH= createUnManaged(T_ELCL, "include_on_buildpath.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_ADD_AS_SOURCE_FOLDER= createUnManaged(T_DLCL, "add_as_source_folder.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_ADD_AS_SOURCE_FOLDER= createUnManaged(T_ELCL, "add_as_source_folder.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_REMOVE_AS_SOURCE_FOLDER= createUnManaged(T_DLCL, "remove_as_source_folder.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_REMOVE_AS_SOURCE_FOLDER= createUnManaged(T_ELCL, "remove_as_source_folder.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_DLCL_COPY_QUALIFIED_NAME= createUnManaged(T_DLCL, "cpyqual_menu.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_COPY_QUALIFIED_NAME= createUnManaged(T_ELCL, "cpyqual_menu.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OBJ_OVERRIDES= createUnManaged(T_OBJ, "over_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OBJ_IMPLEMENTS= createUnManaged(T_OBJ, "implm_co.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OVR_STATIC= createUnManagedCached(T_OVR, "static_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_FINAL= createUnManagedCached(T_OVR, "final_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_ABSTRACT= createUnManagedCached(T_OVR, "abstract_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_SYNCH= createUnManagedCached(T_OVR, "synch_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_VOLATILE= createUnManagedCached(T_OVR, "volatile_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_TRANSIENT= createUnManagedCached(T_OVR, "transient_co.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_OVR_RUN= createUnManagedCached(T_OVR, "run_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_WARNING= createUnManagedCached(T_OVR, "warning_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_ERROR= createUnManagedCached(T_OVR, "error_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_OVERRIDES= createUnManagedCached(T_OVR, "over_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_IMPLEMENTS= createUnManagedCached(T_OVR, "implm_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_SYNCH_AND_OVERRIDES= createUnManagedCached(T_OVR, "sync_over.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_SYNCH_AND_IMPLEMENTS= createUnManagedCached(T_OVR, "sync_impl.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_CONSTRUCTOR= createUnManagedCached(T_OVR, "constr_ovr.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_DEPRECATED= createUnManagedCached(T_OVR, "deprecated.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_FOCUS= createUnManagedCached(T_OVR, "focus_ovr.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_ANNOTATION= createUnManagedCached(T_OVR, "annotation_tsk.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_ENUM= createUnManagedCached(T_OVR, "enum_tsk.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_INTERFACE= createUnManagedCached(T_OVR, "interface_tsk.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_CLASS= createUnManagedCached(T_OVR, "class_tsk.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_ABSTRACT_CLASS= createUnManagedCached(T_OVR, "class_abs_tsk.gif"); //$NON-NLS-1$
-
- // Call Hierarchy
- public static final ImageDescriptor DESC_OVR_RECURSIVE= createUnManaged(T_OVR, "recursive_co.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_OVR_MAX_LEVEL= createUnManaged(T_OVR, "maxlevel_co.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_WIZBAN_NEWCLASS= createUnManaged(T_WIZBAN, "newclass_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWJSFILE= createUnManaged(T_WIZBAN, "newjscriptfile_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWINT= createUnManaged(T_WIZBAN, "newint_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWENUM= createUnManaged(T_WIZBAN, "newenum_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWANNOT= createUnManaged(T_WIZBAN, "newannotation_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ= createUnManaged(T_WIZBAN, "newjprj_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR= createUnManaged(T_WIZBAN, "newsrcfldr_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWMETH= createUnManaged(T_WIZBAN, "newmeth_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWPACK= createUnManaged(T_WIZBAN, "newpack_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_NEWSCRAPPAGE= createUnManaged(T_WIZBAN, "newsbook_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_JAVA_LAUNCH= createUnManaged(T_WIZBAN, "java_app_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_JAVA_ATTACH= createUnManaged(T_WIZBAN, "java_attach_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR= createUnManaged(T_WIZBAN, "refactor_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIELD= createUnManaged(T_WIZBAN, "fieldrefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_METHOD= createUnManaged(T_WIZBAN, "methrefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_TYPE= createUnManaged(T_WIZBAN, "typerefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PACKAGE= createUnManaged(T_WIZBAN, "packrefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CODE= createUnManaged(T_WIZBAN, "coderefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CU= createUnManaged(T_WIZBAN, "compunitrefact_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PULL_UP= createUnManaged(T_WIZBAN, "pullup_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIX_DEPRECATION= createUnManaged(T_WIZBAN, "fixdepr_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_JAR_PACKAGER= createUnManaged(T_WIZBAN, "jar_pack_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REFACTOR_EXTRACT_SUPERTYPE= createUnManaged(T_WIZBAN, "extractsupertype_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_REPLACE_JAR= createUnManaged(T_WIZBAN, "replacejar_wiz.png"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_JAVA_WORKINGSET= createUnManaged(T_WIZBAN, "java_workingset_wiz.png");//$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_EXPORT_JAVADOC= createUnManaged(T_WIZBAN, "export_javadoc_wiz.png");//$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_EXTERNALIZE_STRINGS= createUnManaged(T_WIZBAN, "extstr_wiz.png");//$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY= createUnManaged(T_WIZBAN, "addlibrary_wiz.png");//$NON-NLS-1$
- public static final ImageDescriptor DESC_WIZBAN_CLEAN_UP= createUnManaged(T_WIZBAN, "cleanup_wiz.png"); //$NON-NLS-1$
-
-
- public static final ImageDescriptor DESC_TOOL_SHOW_EMPTY_PKG= createUnManaged(T_ETOOL, "show_empty_pkg.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_SHOW_SEGMENTS= createUnManaged(T_ETOOL, "segment_edit.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_TOOL_OPENTYPE= createUnManaged(T_ETOOL, "opentype.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWPROJECT= createUnManaged(T_ETOOL, "newjprj_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWPACKAGE= createUnManaged(T_ETOOL, "newpack_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWCLASS= createUnManaged(T_ETOOL, "newclass_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWINTERFACE= createUnManaged(T_ETOOL, "newint_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWSNIPPET= createUnManaged(T_ETOOL, "newsbook_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_TOOL_NEWPACKROOT= createUnManaged(T_ETOOL, "newpackfolder_wiz.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_DLCL_NEWPACKROOT= createUnManaged(T_DLCL, "newpackfolder_wiz.gif"); //$NON-NLS-1$
-
- public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER= createUnManaged(T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$
- public static final ImageDescriptor DESC_ELCL_COLLAPSEALL= createUnManaged(T_ELCL, "collapseall.gif"); //$NON-NLS-1$
-
- // Keys for correction proposal. We have to put the image into the registry since "code assist" doesn't
- // have a life cycle. So no change to dispose icons.
-
- public static final String IMG_CORRECTION_CHANGE= NAME_PREFIX + "correction_change.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_MOVE= NAME_PREFIX + "correction_move.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_RENAME= NAME_PREFIX + "correction_rename.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_LINKED_RENAME= NAME_PREFIX + "correction_linked_rename.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_DELETE_IMPORT= NAME_PREFIX + "correction_delete_import.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_LOCAL= NAME_PREFIX + "localvariable_obj.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_REMOVE= NAME_PREFIX + "remove_correction.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_ADD= NAME_PREFIX + "add_correction.gif"; //$NON-NLS-1$
- public static final String IMG_CORRECTION_CAST= NAME_PREFIX + "correction_cast.gif"; //$NON-NLS-1$
-
- static {
- createManagedFromKey(T_OBJ, IMG_CORRECTION_CHANGE);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_MOVE);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_RENAME);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_LINKED_RENAME);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_DELETE_IMPORT);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_LOCAL);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_REMOVE);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_ADD);
- createManagedFromKey(T_OBJ, IMG_CORRECTION_CAST);
- }
-
- private static final class CachedImageDescriptor extends ImageDescriptor {
- private ImageDescriptor fDescriptor;
- private ImageData fData;
-
- public CachedImageDescriptor(ImageDescriptor descriptor) {
- fDescriptor = descriptor;
- }
-
- public ImageData getImageData() {
- if (fData == null) {
- fData= fDescriptor.getImageData();
- }
- return fData;
- }
- }
-
- /**
- * Returns the image managed under the given key in this registry.
- *
- * @param key the image's key
- * @return the image managed under the given key
- */
- public static Image get(String key) {
- return getImageRegistry().get(key);
- }
-
- /**
- * Returns the image descriptor for the given key in this registry. Might be called in a non-UI thread.
- *
- * @param key the image's key
- * @return the image descriptor for the given key
- */
- public static ImageDescriptor getDescriptor(String key) {
- if (fgImageRegistry == null) {
- return (ImageDescriptor) fgAvoidSWTErrorMap.get(key);
- }
- return getImageRegistry().getDescriptor(key);
- }
-
- /**
- * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions
- * are retrieved from the *tool16 folders.
- *
- * @param action the action
- * @param iconName the icon name
- */
- public static void setToolImageDescriptors(IAction action, String iconName) {
- setImageDescriptors(action, "tool16", iconName); //$NON-NLS-1$
- }
-
- /**
- * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions
- * are retrieved from the *lcl16 folders.
- *
- * @param action the action
- * @param iconName the icon name
- */
- public static void setLocalImageDescriptors(IAction action, String iconName) {
- setImageDescriptors(action, "lcl16", iconName); //$NON-NLS-1$
- }
-
- /*
- * Helper method to access the image registry from the JavaScriptPlugin class.
- */
- /* package */ static ImageRegistry getImageRegistry() {
- if (fgImageRegistry == null) {
- fgImageRegistry= new ImageRegistry();
- for (Iterator iter= fgAvoidSWTErrorMap.keySet().iterator(); iter.hasNext();) {
- String key= (String) iter.next();
- fgImageRegistry.put(key, (ImageDescriptor) fgAvoidSWTErrorMap.get(key));
- }
- fgAvoidSWTErrorMap= null;
- }
- return fgImageRegistry;
- }
-
- //---- Helper methods to access icons on the file system --------------------------------------
-
- private static void setImageDescriptors(IAction action, String type, String relPath) {
- ImageDescriptor id= create("d" + type, relPath, false); //$NON-NLS-1$
- if (id != null)
- action.setDisabledImageDescriptor(id);
-
- /*
- * id= create("c" + type, relPath, false); //$NON-NLS-1$
- * if (id != null)
- * action.setHoverImageDescriptor(id);
- */
-
- ImageDescriptor descriptor= create("e" + type, relPath, true); //$NON-NLS-1$
- action.setHoverImageDescriptor(descriptor);
- action.setImageDescriptor(descriptor);
- }
-
- private static ImageDescriptor createManagedFromKey(String prefix, String key) {
- return createManaged(prefix, key.substring(NAME_PREFIX_LENGTH), key);
- }
-
- private static ImageDescriptor createManaged(String prefix, String name, String key) {
- ImageDescriptor result= create(prefix, name, true);
-
- if (fgAvoidSWTErrorMap == null) {
- fgAvoidSWTErrorMap= new HashMap();
- }
- fgAvoidSWTErrorMap.put(key, result);
- if (fgImageRegistry != null) {
- JavaScriptPlugin.logErrorMessage("Image registry already defined"); //$NON-NLS-1$
- }
- return result;
- }
-
- /*
- * Creates an image descriptor for the given prefix and name in the JDT UI bundle. The path can
- * contain variables like $NL$.
- * If no image could be found, <code>useMissingImageDescriptor</code> decides if either
- * the 'missing image descriptor' is returned or <code>null</code>.
- * or <code>null</code>.
- */
- private static ImageDescriptor create(String prefix, String name, boolean useMissingImageDescriptor) {
- IPath path= ICONS_PATH.append(prefix).append(name);
- return createImageDescriptor(JavaScriptPlugin.getDefault().getBundle(), path, useMissingImageDescriptor);
- }
-
- /*
- * Creates an image descriptor for the given prefix and name in the JDT UI bundle. The path can
- * contain variables like $NL$.
- * If no image could be found, the 'missing image descriptor' is returned.
- */
- private static ImageDescriptor createUnManaged(String prefix, String name) {
- return create(prefix, name, true);
- }
-
- /*
- * Creates an image descriptor for the given prefix and name in the JDT UI bundle and let tye descriptor cache the image data.
- * If no image could be found, the 'missing image descriptor' is returned.
- */
- private static ImageDescriptor createUnManagedCached(String prefix, String name) {
- return new CachedImageDescriptor(create(prefix, name, true));
- }
-
- /*
- * Creates an image descriptor for the given path in a bundle. The path can contain variables
- * like $NL$.
- * If no image could be found, <code>useMissingImageDescriptor</code> decides if either
- * the 'missing image descriptor' is returned or <code>null</code>.
- * Added for 3.1.1.
- */
- public static ImageDescriptor createImageDescriptor(Bundle bundle, IPath path, boolean useMissingImageDescriptor) {
- URL url= FileLocator.find(bundle, path, null);
- if (url != null) {
- return ImageDescriptor.createFromURL(url);
- }
- if (useMissingImageDescriptor) {
- return ImageDescriptor.getMissingImageDescriptor();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaProjectAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaProjectAdapterFactory.java
deleted file mode 100644
index 1909d474..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaProjectAdapterFactory.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * An adapter factory for IJavaProjects.
- */
-public class JavaProjectAdapterFactory implements IAdapterFactory {
-
- private static Class[] PROPERTIES= new Class[] {
- IProject.class,
- };
-
- public Class[] getAdapterList() {
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- if (IProject.class.equals(key)) {
- IJavaScriptProject javaProject= (IJavaScriptProject)element;
- return javaProject.getProject();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java
deleted file mode 100644
index 61226fb4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java
+++ /dev/null
@@ -1,927 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import java.io.IOException;
-import java.util.LinkedHashMap;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.templates.ContextTypeRegistry;
-import org.eclipse.jface.text.templates.persistence.TemplateStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry;
-import org.eclipse.ui.editors.text.templates.ContributionTemplateStore;
-import org.eclipse.ui.forms.FormColors;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.navigator.ICommonMenuConstants;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.ui.texteditor.ConfigurationElementSorter;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.themes.IThemeManager;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.manipulation.JavaScriptManipulation;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaContextType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaDocContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ClassFileDocumentProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.DocumentAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.WorkingCopyManager;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.SaveParticipantRegistry;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.FormatterProfileStore;
-import org.eclipse.wst.jsdt.internal.ui.text.PreferencesAdapter;
-import org.eclipse.wst.jsdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistHistory;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemMarkerManager;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ClasspathAttributeConfigurationDescriptors;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-import org.osgi.framework.BundleContext;
-
-/**
- * Represents the java plug-in. It provides a series of convenience methods such as
- * access to the workbench, keeps track of elements shared by all editors and viewers
- * of the plug-in such as document providers and find-replace-dialogs.
- */
-public class JavaScriptPlugin extends AbstractUIPlugin {
-
- /**
- * The key to store customized templates.
- *
- */
- private static final String TEMPLATES_KEY= "org.eclipse.wst.jsdt.ui.text.custom_templates"; //$NON-NLS-1$
- /**
- * The key to store customized code templates.
- *
- */
- private static final String CODE_TEMPLATES_KEY= "org.eclipse.wst.jsdt.ui.text.custom_code_templates"; //$NON-NLS-1$
- /**
- * The key to store whether the legacy templates have been migrated
- *
- */
- private static final String TEMPLATES_MIGRATION_KEY= "org.eclipse.wst.jsdt.ui.text.templates_migrated"; //$NON-NLS-1$
- /**
- * The key to store whether the legacy code templates have been migrated
- *
- */
- private static final String CODE_TEMPLATES_MIGRATION_KEY= "org.eclipse.wst.jsdt.ui.text.code_templates_migrated"; //$NON-NLS-1$
-
- private static JavaScriptPlugin fgJavaPlugin;
-
- private static LinkedHashMap fgRepeatedMessages= new LinkedHashMap(20, 0.75f, true) {
- private static final long serialVersionUID= 1L;
- protected boolean removeEldestEntry(java.util.Map.Entry eldest) {
- return size() >= 20;
- }
- };
-
- /**
- * The template context type registry for the java editor.
- *
- */
- private ContextTypeRegistry fContextTypeRegistry;
- /**
- * The code template context type registry for the java editor.
- *
- */
- private ContextTypeRegistry fCodeTemplateContextTypeRegistry;
-
- /**
- * The template store for the java editor.
- *
- */
- private TemplateStore fTemplateStore;
- /**
- * The coded template store for the java editor.
- *
- */
- private TemplateStore fCodeTemplateStore;
-
- /**
- * Default instance of the appearance type filters.
- *
- */
- private TypeFilter fTypeFilter;
-
-
- private WorkingCopyManager fWorkingCopyManager;
-
- /**
- * @deprecated
- */
- private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
- private ClassFileDocumentProvider fClassFileDocumentProvider;
- private JavaScriptTextTools fJavaTextTools;
- private ProblemMarkerManager fProblemMarkerManager;
- private ImageDescriptorRegistry fImageDescriptorRegistry;
-
- private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
- private IPropertyChangeListener fFontPropertyChangeListener;
-
- /**
- * Property change listener on this plugin's preference store.
- *
- *
- */
- private IPropertyChangeListener fPropertyChangeListener;
-
- private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
-
- /**
- * The AST provider.
- *
- */
- private ASTProvider fASTProvider;
-
- /**
- * The combined preference store.
- *
- */
- private IPreferenceStore fCombinedPreferenceStore;
-
- /**
- * The extension point registry for the <code>org.eclipse.wst.jsdt.ui.javaFoldingStructureProvider</code>
- * extension point.
- *
- *
- */
- private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry;
-
- /**
- * The shared Java properties file document provider.
- *
- */
- private IDocumentProvider fPropertiesFileDocumentProvider;
-
- /**
- * Content assist history.
- *
- *
- */
- private ContentAssistHistory fContentAssistHistory;
-
- /**
- * The save participant registry.
- *
- *
- */
- private SaveParticipantRegistry fSaveParticipantRegistry;
-
- /**
- * The descriptors from the 'classpathAttributeConfiguration' extension point.
- *
- *
- */
- private ClasspathAttributeConfigurationDescriptors fClasspathAttributeConfigurationDescriptors;
-
- private FormToolkit fDialogsFormToolkit;
-
- /**
- * Theme listener.
- *
- */
- private IPropertyChangeListener fThemeListener;
-
- public static JavaScriptPlugin getDefault() {
- return fgJavaPlugin;
- }
-
- public static IWorkspace getWorkspace() {
- return ResourcesPlugin.getWorkspace();
- }
-
- public static IWorkbenchPage getActivePage() {
- return getDefault().internalGetActivePage();
- }
-
- public static IWorkbenchWindow getActiveWorkbenchWindow() {
- return getDefault().getWorkbench().getActiveWorkbenchWindow();
- }
-
- public static Shell getActiveWorkbenchShell() {
- IWorkbenchWindow window= getActiveWorkbenchWindow();
- if (window != null) {
- return window.getShell();
- }
- return null;
- }
-
- public static String getPluginId() {
- return JavaScriptUI.ID_PLUGIN;
- }
-
- public static void log(IStatus status) {
- getDefault().getLog().log(status);
- }
-
- public static void logErrorMessage(String message) {
- log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
- }
-
- public static void logErrorStatus(String message, IStatus status) {
- if (status == null) {
- logErrorMessage(message);
- return;
- }
- MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
- multi.add(status);
- log(multi);
- }
-
- public static void log(Throwable e) {
- log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.JavaPlugin_internal_error, e));
- }
-
- /**
- * Log a message that is potentially repeated after a very short time.
- * The first time this method is called with a given message, the
- * message is written to the log along with the detail message and a stack trace.
- * <p>
- * Only intended for use in debug statements.
- *
- * @param message the (generic) message
- * @param detail the detail message
- */
- public static void logRepeatedMessage(String message, String detail) {
- long now= System.currentTimeMillis();
- boolean writeToLog= true;
- if (fgRepeatedMessages.containsKey(message)) {
- long last= ((Long) fgRepeatedMessages.get(message)).longValue();
- writeToLog= now - last > 5000;
- }
- fgRepeatedMessages.put(message, new Long(now));
- if (writeToLog)
- log(new Exception(message + detail).fillInStackTrace());
- }
-
- public static boolean isDebug() {
- return getDefault().isDebugging();
- }
-
- public static ImageDescriptorRegistry getImageDescriptorRegistry() {
- return getDefault().internalGetImageDescriptorRegistry();
- }
-
- public JavaScriptPlugin() {
- super();
- fgJavaPlugin = this;
- }
-
- /* (non - Javadoc)
- * Method declared in plug-in
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
-
- WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() {
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
- IJavaScriptUnit original= workingCopy.getPrimary();
- IResource resource= original.getResource();
- if (resource instanceof IFile)
- return new DocumentAdapter(workingCopy, (IFile) resource);
- return DocumentAdapter.NULL;
- }
- });
-
- ensurePreferenceStoreBackwardsCompatibility();
-
- // Initialize AST provider
- getASTProvider();
-
- new InitializeAfterLoadJob().schedule();
-
- // make sure is loaded too for org.eclipse.wst.jsdt.core.manipulation
- // can be removed if JavaElementPropertyTester is moved down to jdt.core (bug 127085)
- JavaScriptManipulation.class.toString();
-
- fThemeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (IThemeManager.CHANGE_CURRENT_THEME.equals(event.getProperty()))
- new JavaUIPreferenceInitializer().initializeDefaultPreferences();
- }
- };
- PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(fThemeListener);
-
- }
-
- /* package */ static void initializeAfterLoad(IProgressMonitor monitor) {
- OpenTypeHistory.getInstance().checkConsistency(monitor);
- }
-
- /** @deprecated */
- private static IPreferenceStore getDeprecatedWorkbenchPreferenceStore() {
- return PlatformUI.getWorkbench().getPreferenceStore();
- }
-
- /** @deprecated */
- private static final String DEPRECATED_EDITOR_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
-
- /** @deprecated */
- private static final String DEPRECATED_REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD;
-
- /** @deprecated */
- private static final String DEPRECATED_CODEASSIST_ORDER_PROPOSALS= PreferenceConstants.CODEASSIST_ORDER_PROPOSALS;
-
- /**
- * Installs backwards compatibility for the preference store.
- */
- private void ensurePreferenceStoreBackwardsCompatibility() {
-
- IPreferenceStore store= getPreferenceStore();
-
- // must add here to guarantee that it is the first in the listener list
- fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
- fMembersOrderPreferenceCache.install(store);
-
-
- /*
- * Installs backwards compatibility: propagate the Java editor font from a
- * pre-2.1 plug-in to the Platform UI's preference store to preserve
- * the Java editor font from a pre-2.1 workspace. This is done only
- * once.
- */
- String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
- if (store.contains(JFaceResources.TEXT_FONT) && !store.isDefault(JFaceResources.TEXT_FONT)) {
- if (!store.getBoolean(fontPropagatedKey))
- PreferenceConverter.setValue(
- getDeprecatedWorkbenchPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(store, JFaceResources.TEXT_FONT));
- }
- store.setValue(fontPropagatedKey, true);
-
- /*
- * Backwards compatibility: set the Java editor font in this plug-in's
- * preference store to let older versions access it. Since 2.1 the
- * Java editor font is managed by the workbench font preference page.
- */
- PreferenceConverter.putValue(store, JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
-
- fFontPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
- PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
- }
- };
- JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
-
- /*
- * Backwards compatibility: propagate the Java editor tab width from a
- * pre-3.0 plug-in to the new preference key. This is done only once.
- */
- final String oldTabWidthKey= DEPRECATED_EDITOR_TAB_WIDTH;
- final String newTabWidthKey= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
- String tabWidthPropagatedKey= "tabWidthPropagated"; //$NON-NLS-1$
- if (store.contains(oldTabWidthKey) && !store.isDefault(oldTabWidthKey)) {
- if (!store.getBoolean(tabWidthPropagatedKey))
- store.setValue(newTabWidthKey, store.getInt(oldTabWidthKey));
- }
- store.setValue(tabWidthPropagatedKey, true);
-
- /*
- * Backwards compatibility: set the Java editor tab width in this plug-in's
- * preference store with the old key to let older versions access it.
- * Since 3.0 the tab width is managed by the extended text editor and
- * uses a new key.
- */
- store.putValue(oldTabWidthKey, store.getString(newTabWidthKey));
-
- fPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (newTabWidthKey.equals(event.getProperty())) {
- IPreferenceStore prefStore= getPreferenceStore();
- prefStore.putValue(oldTabWidthKey, prefStore.getString(newTabWidthKey));
- }
- }
- };
- store.addPropertyChangeListener(fPropertyChangeListener);
-
- /*
- * Backward compatibility for the refactoring preference key.
- */
-// store.setValue(
-// PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD,
-// RefactoringCore.getConditionCheckingFailedSeverity());
-
- // The commented call above triggers the eager loading of the LTK core plug-in
- // Since the condition checking failed severity is guaranteed to be of RefactoringStatus.SEVERITY_WARNING,
- // we directly insert the inlined value of this constant
- store.setToDefault(DEPRECATED_REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD);
-
- if (!store.getBoolean(JavaDocLocations.PREF_JAVADOCLOCATIONS_MIGRATED)) {
- JavaDocLocations.migrateToClasspathAttributes();
- }
-
- FormatterProfileStore.checkCurrentOptionsVersion();
-
- /*
- * Backward compatibility: migrate "alphabetic ordering" preference to point the sorter
- * preference to the alphabetic sorter.
- */
- String proposalOrderMigrated= "proposalOrderMigrated"; //$NON-NLS-1$
-
- if (store.contains(DEPRECATED_CODEASSIST_ORDER_PROPOSALS)) {
- if (!store.getBoolean(proposalOrderMigrated)) {
- boolean alphabetic= store.getBoolean(DEPRECATED_CODEASSIST_ORDER_PROPOSALS);
- if (alphabetic)
- store.setValue(PreferenceConstants.CODEASSIST_SORTER, "org.eclipse.wst.jsdt.ui.AlphabeticSorter"); //$NON-NLS-1$
- }
- }
- store.setValue(proposalOrderMigrated, true);
-
- }
-
- /**
- * Uninstalls backwards compatibility for the preference store.
- */
- private void uninstallPreferenceStoreBackwardsCompatibility() {
- JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
- getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- }
-
- /*
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry()
- */
- protected ImageRegistry createImageRegistry() {
- return JavaPluginImages.getImageRegistry();
- }
-
- /*
- * @see org.eclipse.core.runtime.Plugin#stop
- */
- public void stop(BundleContext context) throws Exception {
- try {
- if (fImageDescriptorRegistry != null)
- fImageDescriptorRegistry.dispose();
-
- if (fASTProvider != null) {
- fASTProvider.dispose();
- fASTProvider= null;
- }
-
- if (fWorkingCopyManager != null) {
- fWorkingCopyManager.shutdown();
- fWorkingCopyManager= null;
- }
-
- if (fCompilationUnitDocumentProvider != null) {
- fCompilationUnitDocumentProvider.shutdown();
- fCompilationUnitDocumentProvider= null;
- }
-
- if (fJavaTextTools != null) {
- fJavaTextTools.dispose();
- fJavaTextTools= null;
- }
-
- if (fTypeFilter != null) {
- fTypeFilter.dispose();
- fTypeFilter= null;
- }
-
- if (fContentAssistHistory != null) {
- ContentAssistHistory.store(fContentAssistHistory, getPluginPreferences(), PreferenceConstants.CODEASSIST_LRU_HISTORY);
- fContentAssistHistory= null;
- }
-
- uninstallPreferenceStoreBackwardsCompatibility();
-
- if (fTemplateStore != null) {
- fTemplateStore.stopListeningForPreferenceChanges();
- fTemplateStore= null;
- }
-
- if (fCodeTemplateStore != null) {
- fCodeTemplateStore.stopListeningForPreferenceChanges();
- fCodeTemplateStore= null;
- }
-
- if (fMembersOrderPreferenceCache != null) {
- fMembersOrderPreferenceCache.dispose();
- fMembersOrderPreferenceCache= null;
- }
-
- if (fSaveParticipantRegistry != null) {
- fSaveParticipantRegistry.dispose();
- fSaveParticipantRegistry= null;
- }
-
- if (fDialogsFormToolkit != null) {
- fDialogsFormToolkit.dispose();
- fDialogsFormToolkit= null;
- }
-
- if (fThemeListener != null) {
- PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(fThemeListener);
- fThemeListener= null;
- }
-
- QualifiedTypeNameHistory.getDefault().save();
-
- // must add here to guarantee that it is the first in the listener list
-
- OpenTypeHistory.shutdown();
- } finally {
- super.stop(context);
- }
- }
-
- private IWorkbenchPage internalGetActivePage() {
- IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
- if (window == null)
- return null;
- return window.getActivePage();
- }
-
- public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
- if (fCompilationUnitDocumentProvider == null)
- fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
- return fCompilationUnitDocumentProvider;
- }
-
-
-
- public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
- if (fClassFileDocumentProvider == null)
- fClassFileDocumentProvider= new ClassFileDocumentProvider();
- return fClassFileDocumentProvider;
- }
-
- public synchronized WorkingCopyManager getWorkingCopyManager() {
- if (fWorkingCopyManager == null) {
- ICompilationUnitDocumentProvider provider= getCompilationUnitDocumentProvider();
- fWorkingCopyManager= new WorkingCopyManager(provider);
- }
- return fWorkingCopyManager;
- }
-
- public synchronized ProblemMarkerManager getProblemMarkerManager() {
- if (fProblemMarkerManager == null)
- fProblemMarkerManager= new ProblemMarkerManager();
- return fProblemMarkerManager;
- }
-
- public synchronized JavaScriptTextTools getJavaTextTools() {
- if (fJavaTextTools == null)
- fJavaTextTools= new JavaScriptTextTools(getPreferenceStore(), JavaScriptCore.getPlugin().getPluginPreferences());
- return fJavaTextTools;
- }
-
- /**
- * Returns the AST provider.
- *
- * @return the AST provider
- *
- */
- public synchronized ASTProvider getASTProvider() {
- if (fASTProvider == null)
- fASTProvider= new ASTProvider();
-
- return fASTProvider;
- }
-
- public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
- // initialized on startup
- return fMembersOrderPreferenceCache;
- }
-
-
- public synchronized TypeFilter getTypeFilter() {
- if (fTypeFilter == null)
- fTypeFilter= new TypeFilter();
- return fTypeFilter;
- }
-
- public FormToolkit getDialogsFormToolkit() {
- if (fDialogsFormToolkit == null) {
- FormColors colors= new FormColors(Display.getCurrent());
- colors.setBackground(null);
- colors.setForeground(null);
- fDialogsFormToolkit= new FormToolkit(colors);
- }
- return fDialogsFormToolkit;
- }
-
- /**
- * Returns all Java editor text hovers contributed to the workbench.
- *
- * @return an array of JavaEditorTextHoverDescriptor
- *
- */
- public synchronized JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
- if (fJavaEditorTextHoverDescriptors == null) {
- fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
- ConfigurationElementSorter sorter= new ConfigurationElementSorter() {
- /*
- * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object)
- */
- public IConfigurationElement getConfigurationElement(Object object) {
- return ((JavaEditorTextHoverDescriptor)object).getConfigurationElement();
- }
- };
- sorter.sort(fJavaEditorTextHoverDescriptors);
-
- // Move Best Match hover to front
- for (int i= 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) {
- if (PreferenceConstants.ID_BESTMATCH_HOVER.equals(fJavaEditorTextHoverDescriptors[i].getId())) {
- JavaEditorTextHoverDescriptor hoverDescriptor= fJavaEditorTextHoverDescriptors[i];
- for (int j= i; j > 0; j--)
- fJavaEditorTextHoverDescriptors[j]= fJavaEditorTextHoverDescriptors[j-1];
- fJavaEditorTextHoverDescriptors[0]= hoverDescriptor;
- break;
- }
-
- }
- }
-
- return fJavaEditorTextHoverDescriptors;
- }
-
- /**
- * Resets the Java editor text hovers contributed to the workbench.
- * <p>
- * This will force a rebuild of the descriptors the next time
- * a client asks for them.
- * </p>
- *
- *
- */
- public synchronized void resetJavaEditorTextHoverDescriptors() {
- fJavaEditorTextHoverDescriptors= null;
- }
-
- /**
- * Creates the Java plug-in's standard groups for view context menus.
- *
- * @param menu the menu manager to be populated
- */
- public static void createStandardGroups(IMenuManager menu) {
- if (!menu.isEmpty())
- return;
-
- menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
- menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
- menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
- menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
- menu.add(new Separator(ICommonMenuConstants.GROUP_EDIT));
- menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
- menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
- menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
- menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
- menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
- menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
- menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
- }
-
- /**
- * Returns the template context type registry for the java plug-in.
- *
- * @return the template context type registry for the java plug-in
- *
- */
- public ContextTypeRegistry getTemplateContextRegistry() {
- if (fContextTypeRegistry == null) {
- ContributionContextTypeRegistry registry= new ContributionContextTypeRegistry();
- registry.addContextType(JavaContextType.NAME);
- registry.addContextType(JavaDocContextType.NAME);
-
- fContextTypeRegistry= registry;
- }
-
- return fContextTypeRegistry;
- }
-
- /**
- * Returns the template store for the java editor templates.
- *
- * @return the template store for the java editor templates
- *
- */
- public TemplateStore getTemplateStore() {
- if (fTemplateStore == null) {
- final IPreferenceStore store= getPreferenceStore();
- boolean alreadyMigrated= store.getBoolean(TEMPLATES_MIGRATION_KEY);
- if (alreadyMigrated)
- fTemplateStore= new ContributionTemplateStore(getTemplateContextRegistry(), store, TEMPLATES_KEY);
- else {
- fTemplateStore= new CompatibilityTemplateStore(getTemplateContextRegistry(), store, TEMPLATES_KEY, getOldTemplateStoreInstance());
- store.setValue(TEMPLATES_MIGRATION_KEY, true);
- }
-
- try {
- fTemplateStore.load();
- } catch (IOException e) {
- log(e);
- }
- fTemplateStore.startListeningForPreferenceChanges();
- }
-
- return fTemplateStore;
- }
-
- /**
- * @deprecated Indirection added to avoid deprecated warning on file
- */
- private org.eclipse.wst.jsdt.internal.corext.template.java.Templates getOldTemplateStoreInstance() {
- return org.eclipse.wst.jsdt.internal.corext.template.java.Templates.getInstance();
- }
-
- /**
- * Returns the template context type registry for the code generation
- * templates.
- *
- * @return the template context type registry for the code generation
- * templates
- *
- */
- public ContextTypeRegistry getCodeTemplateContextRegistry() {
- if (fCodeTemplateContextTypeRegistry == null) {
- fCodeTemplateContextTypeRegistry= new ContributionContextTypeRegistry();
-
- CodeTemplateContextType.registerContextTypes(fCodeTemplateContextTypeRegistry);
- }
-
- return fCodeTemplateContextTypeRegistry;
- }
-
- /**
- * Returns the template store for the code generation templates.
- *
- * @return the template store for the code generation templates
- *
- */
- public TemplateStore getCodeTemplateStore() {
- if (fCodeTemplateStore == null) {
- IPreferenceStore store= getPreferenceStore();
- boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY);
- if (alreadyMigrated)
- fCodeTemplateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY);
- else {
- fCodeTemplateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance());
- store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true);
- }
-
- try {
- fCodeTemplateStore.load();
- } catch (IOException e) {
- log(e);
- }
-
- fCodeTemplateStore.startListeningForPreferenceChanges();
-
- // compatibility / bug fixing code for duplicated templates
- // TODO remove for 3.0
- CompatibilityTemplateStore.pruneDuplicates(fCodeTemplateStore, true);
-
- }
-
- return fCodeTemplateStore;
- }
-
- /**
- * @deprecated Indirection added to avoid deprecated warning on file
- */
- private org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplates getOldCodeTemplateStoreInstance() {
- return org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplates.getInstance();
- }
-
- private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
- if (fImageDescriptorRegistry == null)
- fImageDescriptorRegistry= new ImageDescriptorRegistry();
- return fImageDescriptorRegistry;
- }
-
- /**
- * Returns a combined preference store, this store is read-only.
- *
- * @return the combined preference store
- *
- *
- */
- public IPreferenceStore getCombinedPreferenceStore() {
- if (fCombinedPreferenceStore == null) {
- IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
- fCombinedPreferenceStore= new ChainedPreferenceStore(new IPreferenceStore[] { getPreferenceStore(), new PreferencesAdapter(JavaScriptCore.getPlugin().getPluginPreferences()), generalTextStore });
- }
- return fCombinedPreferenceStore;
- }
-
- /**
- * Returns the registry of the extensions to the <code>org.eclipse.wst.jsdt.ui.javaFoldingStructureProvider</code>
- * extension point.
- *
- * @return the registry of contributed <code>IJavaFoldingStructureProvider</code>
- *
- */
- public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() {
- if (fFoldingStructureProviderRegistry == null)
- fFoldingStructureProviderRegistry= new JavaFoldingStructureProviderRegistry();
- return fFoldingStructureProviderRegistry;
- }
-
- /**
- * Returns the save participant registry.
- *
- * @return the save participant registry, not null
- *
- */
- public synchronized SaveParticipantRegistry getSaveParticipantRegistry() {
- if (fSaveParticipantRegistry == null)
- fSaveParticipantRegistry= new SaveParticipantRegistry();
- return fSaveParticipantRegistry;
- }
-
- /**
- * Returns the Java content assist history.
- *
- * @return the Java content assist history
- *
- */
- public ContentAssistHistory getContentAssistHistory() {
- if (fContentAssistHistory == null) {
- try {
- fContentAssistHistory= ContentAssistHistory.load(getPluginPreferences(), PreferenceConstants.CODEASSIST_LRU_HISTORY);
- } catch (CoreException x) {
- log(x);
- }
- if (fContentAssistHistory == null)
- fContentAssistHistory= new ContentAssistHistory();
- }
-
- return fContentAssistHistory;
- }
-
- /**
- * Returns a section in the Java plugin's dialog settings. If the section doesn't exist yet, it is created.
- *
- * @param name the name of the section
- * @return the section of the given name
- *
- */
- public IDialogSettings getDialogSettingsSection(String name) {
- IDialogSettings dialogSettings= getDialogSettings();
- IDialogSettings section= dialogSettings.getSection(name);
- if (section == null) {
- section= dialogSettings.addNewSection(name);
- }
- return section;
- }
-
- /**
- *
- */
- public ClasspathAttributeConfigurationDescriptors getClasspathAttributeConfigurationDescriptors() {
- if (fClasspathAttributeConfigurationDescriptors == null) {
- fClasspathAttributeConfigurationDescriptors= new ClasspathAttributeConfigurationDescriptors();
- }
- return fClasspathAttributeConfigurationDescriptors;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java
deleted file mode 100644
index 601c06b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.views.tasklist.ITaskListResourceAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class JavaTaskListAdapter implements ITaskListResourceAdapter {
-
- /*
- * @see ITaskListResourceAdapter#getAffectedResource(IAdaptable)
- */
- public IResource getAffectedResource(IAdaptable element) {
- IJavaScriptElement java = (IJavaScriptElement) element;
- IResource resource= java.getResource();
- if (resource != null)
- return resource;
-
- IJavaScriptUnit cu= (IJavaScriptUnit) java.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- return cu.getPrimary().getResource();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIException.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIException.java
deleted file mode 100644
index e48accdf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-
-/**
- * An exception to wrap a status. This is necessary to use the core's IRunnableWithProgress
- * support
- */
-
-public class JavaUIException extends CoreException {
-
- private static final long serialVersionUID= 1L;
-
- public JavaUIException(IStatus status) {
- super(status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java
deleted file mode 100644
index 0864494e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class JavaUIMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.JavaUIMessages";//$NON-NLS-1$
-
- private JavaUIMessages() {
- // Do not instantiate
- }
-
- public static String FilteredTypesSelectionDialog_TypeFiltersPreferencesAction_label;
- public static String JavaPlugin_internal_error;
- public static String JavaPlugin_initializing_ui;
-
- public static String JavaElementProperties_name;
- public static String JsNature_Global;
-
- public static String OpenTypeAction_description;
- public static String OpenTypeAction_tooltip;
- public static String OpenTypeAction_errorMessage;
- public static String OpenTypeAction_errorTitle;
- public static String OpenTypeAction_label;
- public static String OpenTypeAction_dialogTitle;
- public static String OpenTypeAction_dialogMessage;
-
- public static String JavaUI_defaultDialogMessage;
-
- public static String MultiElementListSelectionDialog_pageInfoMessage;
- public static String PackageSelectionDialog_progress_findEmpty;
- public static String PackageSelectionDialog_progress_search;
-
- public static String TypeSelectionDialog_dialogMessage;
- public static String TypeSelectionDialog_errorTitle;
- public static String TypeSelectionDialog_error3Message;
- public static String TypeSelectionDialog_error3Title;
- public static String TypeSelectionDialog_progress_consistency;
- public static String TypeSelectionDialog_error_type_doesnot_exist;
-
- public static String ExceptionDialog_seeErrorLogMessage;
-
- public static String MainTypeSelectionDialog_errorTitle;
- public static String MultiMainTypeSelectionDialog_errorTitle;
-
- public static String PackageSelectionDialog_error_title;
- public static String PackageSelectionDialog_error3Message;
- public static String PackageSelectionDialog_nopackages_title;
- public static String PackageSelectionDialog_nopackages_message;
-
- public static String BuildPathDialog_title;
-
- public static String OverrideMethodDialog_groupMethodsByTypes;
- public static String OverrideMethodDialog_dialog_title;
- public static String OverrideMethodDialog_dialog_description;
- public static String OverrideMethodDialog_selectioninfo_more;
- public static String OverrideMethodDialog_link_tooltip;
- public static String OverrideMethodDialog_link_message;
-
-
-
- public static String JavaElementLabels_default_package;
- public static String JavaElementLabels_anonym_type;
- public static String JavaElementLabels_anonym;
- public static String JavaElementLabels_import_container;
- public static String JavaElementLabels_initializer;
- public static String JavaElementLabels_category;
- public static String JavaElementLabels_concat_string;
- public static String JavaElementLabels_comma_string;
- public static String JavaElementLabels_declseparator_string;
- public static String JavaElementLabels_category_separator_string;
-
- public static String StatusBarUpdater_num_elements_selected;
-
- public static String OpenTypeHierarchyUtil_error_open_view;
- public static String OpenTypeHierarchyUtil_error_open_perspective;
- public static String OpenTypeHierarchyUtil_error_open_editor;
- public static String OpenTypeHierarchyUtil_selectionDialog_title;
- public static String OpenTypeHierarchyUtil_selectionDialog_message;
-
- public static String TypeInfoLabelProvider_default_package;
-
- public static String JavaUIHelp_link_label;
- public static String JavaUIHelpContext_javaHelpCategory_label;
-
- public static String ResourceTransferDragAdapter_cannot_delete_resource;
- public static String ResourceTransferDragAdapter_moving_resource;
- public static String ResourceTransferDragAdapter_cannot_delete_files;
-
- public static String Spelling_error_label;
- public static String Spelling_correct_label;
- public static String Spelling_add_info;
- public static String Spelling_add_label;
- public static String Spelling_add_askToConfigure_title;
- public static String Spelling_add_askToConfigure_question;
- public static String Spelling_add_askToConfigure_ignoreMessage;
- public static String Spelling_ignore_info;
- public static String Spelling_ignore_label;
- public static String Spelling_disable_label;
- public static String Spelling_disable_info;
- public static String Spelling_case_label;
- public static String Spelling_error_case_label;
- public static String AbstractSpellingDictionary_encodingError;
-
- public static String JavaAnnotationHover_multipleMarkersAtThisLine;
- public static String JavaEditor_codeassist_noCompletions;
-
- public static String OptionalMessageDialog_dontShowAgain;
- public static String ElementValidator_cannotPerform;
- public static String SelectionListenerWithASTManager_job_title;
-
- public static String JavaOutlineControl_statusFieldText_hideInheritedMembers;
- public static String JavaOutlineControl_statusFieldText_showInheritedMembers;
-
- public static String RenameSupport_not_available;
- public static String RenameSupport_dialog_title;
-
- public static String CoreUtility_job_title;
- public static String CoreUtility_buildall_taskname;
- public static String CoreUtility_buildproject_taskname;
-
- public static String FilteredTypesSelectionDialog_default_package;
- public static String FilteredTypesSelectionDialog_dialogMessage;
- public static String FilteredTypesSelectionDialog_error_type_doesnot_exist;
- public static String FilteredTypesSelectionDialog_library_name_format;
- public static String FilteredTypesSelectionDialog_searchJob_taskName;
- public static String FilteredTypeSelectionDialog_showContainerForDuplicatesAction;
- public static String FilteredTypeSelectionDialog_titleFormat;
-
- public static String TypeSelectionDialog2_title_format;
-
- public static String TypeSelectionComponent_label;
- public static String TypeSelectionComponent_menu;
- public static String TypeSelectionComponent_show_status_line_label;
- public static String TypeSelectionComponent_fully_qualify_duplicates_label;
-
- public static String TypeInfoViewer_job_label;
- public static String TypeInfoViewer_job_error;
- public static String TypeInfoViewer_job_cancel;
- public static String TypeInfoViewer_default_package;
- public static String TypeInfoViewer_progress_label;
- public static String TypeInfoViewer_searchJob_taskName;
- public static String TypeInfoViewer_syncJob_label;
- public static String TypeInfoViewer_syncJob_taskName;
- public static String TypeInfoViewer_progressJob_label;
- public static String TypeInfoViewer_remove_from_history;
- public static String TypeInfoViewer_separator_message;
- public static String TypeInfoViewer_library_name_format;
-
- public static String InitializeAfterLoadJob_starter_job_name;
-
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaUIMessages.class);
- }
-
- public static String HistoryListAction_remove;
- public static String HistoryListAction_max_entries_constraint;
- public static String HistoryListAction_remove_all;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties
deleted file mode 100644
index f920aab0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties
+++ /dev/null
@@ -1,179 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-JavaPlugin_internal_error=Internal Error
-JavaElementProperties_name=Name
-
-InitializeAfterLoadJob_starter_job_name=Starting JavaScript Tooling initialization
-JavaPlugin_initializing_ui=Initializing JavaScript Tooling
-
-#########
-## actions
-#########
-
-OpenTypeAction_description=Open a type in the editor
-OpenTypeAction_tooltip=Open a Type
-OpenTypeAction_errorMessage=An exception occurred while opening the type.
-OpenTypeAction_errorTitle=Open JavaScript Type
-OpenTypeAction_label=Open JavaScript Type...
-
-OpenTypeAction_dialogTitle=Open JavaScript Type
-OpenTypeAction_dialogMessage=&Enter type name prefix or pattern (*, ?, or camel case):
-
-#######
-## dialogs
-#######
-JavaUI_defaultDialogMessage=Select entries:
-
-MultiElementListSelectionDialog_pageInfoMessage=Page {0} of {1}
-
-TypeSelectionDialog_dialogMessage=Type ''{0}'' could not be found in ''{1}''. Make sure all workspace resources are refreshed.
-TypeSelectionDialog_errorTitle=Select Type
-TypeSelectionDialog_progress_consistency=Initializing search indices
-TypeSelectionDialog_error_type_doesnot_exist=Type {0} does not exist.
-TypeSelectionDialog_error3Message=Unexpected exception. See log for details.
-TypeSelectionDialog_error3Title=Exception
-
-ExceptionDialog_seeErrorLogMessage= See error log for more details.
-
-MainTypeSelectionDialog_errorTitle=Error
-MultiMainTypeSelectionDialog_errorTitle=Error
-
-PackageSelectionDialog_error3Message=Unexpected exception. See log for details.
-PackageSelectionDialog_error_title=Error
-PackageSelectionDialog_nopackages_title=Package Selection
-PackageSelectionDialog_progress_search=Searching for all packages in workspace
-PackageSelectionDialog_nopackages_message=No packages available.
-PackageSelectionDialog_progress_findEmpty=Find empty packages
-
-BuildPathDialog_title= JavaScript Include Path for {0}
-
-
-OverrideMethodDialog_groupMethodsByTypes=Group functions by types
-OverrideMethodDialog_dialog_title=Override/Implement Functions
-OverrideMethodDialog_dialog_description=Select functions to override or implement:
-OverrideMethodDialog_selectioninfo_more={0} of {1} selected.
-
-OverrideMethodDialog_link_tooltip=Show the code templates preferences.
-OverrideMethodDialog_link_message=The format of the function stubs may be configured on the <a>Code Templates</a> preference page.
-
-TypeSelectionDialog2_title_format={0} - {1}
-
-TypeSelectionComponent_label= &Matching types:
-TypeSelectionComponent_menu=Menu
-TypeSelectionComponent_fully_qualify_duplicates_label=Show &Container for Duplicates
-TypeSelectionComponent_show_status_line_label=&Show Status Line
-
-TypeInfoViewer_job_label=Searching for all types
-TypeInfoViewer_job_error=Searching for all types failed
-TypeInfoViewer_job_cancel=Operation got canceled
-TypeInfoViewer_default_package=./
-TypeInfoViewer_progress_label={0} ({1}%)
-TypeInfoViewer_progressJob_label=Progress Update Job
-TypeInfoViewer_searchJob_taskName=Searching...
-TypeInfoViewer_separator_message=Workspace matches
-TypeInfoViewer_remove_from_history=&Remove from History
-TypeInfoViewer_library_name_format=[{0}]
-TypeInfoViewer_syncJob_label=Synchronizing search tables
-TypeInfoViewer_syncJob_taskName=Refreshing indices...
-
-FilteredTypesSelectionDialog_default_package=./
-FilteredTypesSelectionDialog_dialogMessage=Type ''{0}'' could not be found in ''{1}''. Make sure all workspace resources are refreshed.
-FilteredTypesSelectionDialog_error_type_doesnot_exist=Type {0} does not exist.
-FilteredTypesSelectionDialog_TypeFiltersPreferencesAction_label=&Type Filters...
-FilteredTypesSelectionDialog_library_name_format=[{0}]
-FilteredTypesSelectionDialog_searchJob_taskName=Searching
-FilteredTypeSelectionDialog_showContainerForDuplicatesAction=Show &Container for Duplicates
-FilteredTypeSelectionDialog_titleFormat={0} - {1}
-
-###########
-## viewsupport
-###########
-JavaElementLabels_anonym_type=new {0}() '{'...}
-JavaElementLabels_anonym=new Anonymous
-JavaElementLabels_category=[{0}]
-JavaElementLabels_concat_string=\ -\
-JavaElementLabels_comma_string=,\
-JavaElementLabels_declseparator_string=\ :\
-JavaElementLabels_category_separator_string=\
-JavaElementLabels_default_package=./
-JavaElementLabels_import_container=import declarations
-JavaElementLabels_initializer={...}
-
-StatusBarUpdater_num_elements_selected={0} items selected
-
-HistoryListAction_remove=&Remove
-HistoryListAction_remove_all=Remove &All
-HistoryListAction_max_entries_constraint=Please enter a positive integer smaller than {0}.
-OpenTypeHierarchyUtil_error_open_view=Problems opening Type Hierarchy View
-OpenTypeHierarchyUtil_error_open_perspective=Problems opening Type Hierarchy Perspective
-OpenTypeHierarchyUtil_error_open_editor=Problems opening JavaScript Editor
-OpenTypeHierarchyUtil_selectionDialog_title=Open In Type Hierarchy
-OpenTypeHierarchyUtil_selectionDialog_message=&Select the type to be shown in the Type Hierarchy:
-
-TypeInfoLabelProvider_default_package=/.
-
-JavaUIHelp_link_label=JSDoc for ''{0}''
-JavaUIHelpContext_javaHelpCategory_label= JavaScript help:
-
-#########
-# DnD
-#########
-ResourceTransferDragAdapter_cannot_delete_resource=Cannot delete resources
-ResourceTransferDragAdapter_moving_resource=Moving Resources with Drag and Drop
-ResourceTransferDragAdapter_cannot_delete_files=Cannot delete the following file(s)
-
-#########
-# Spelling
-#########
-
-Spelling_error_label=The word ''{0}'' is not correctly spelled
-Spelling_correct_label=Change to ''{0}''
-Spelling_add_info=Adds the word ''{0}'' to the dictionary
-Spelling_add_label=Add ''{0}'' to dictionary
-Spelling_add_askToConfigure_title=Missing User Dictionary
-Spelling_add_askToConfigure_question=A user dictionary is needed to add words.\nDo you want to configure it now?\n
-Spelling_add_askToConfigure_ignoreMessage= &Do not show 'Add word' proposals if user dictionary is missing
-Spelling_ignore_info=Ignores ''{0}'' during the current session
-Spelling_ignore_label=Ignore ''{0}'' during the current session
-Spelling_case_label=Change to upper case
-Spelling_disable_label=Disable spell checking
-Spelling_disable_info=Disables spell checking.
-Spelling_error_case_label= The word ''{0}'' should have an initial upper case letter
-AbstractSpellingDictionary_encodingError= Could not read: ''{0}'', where the bad characters are replaced by ''{1}''. Check the encoding of the spelling dictionary ({2}).
-
-#########
-# misc
-#########
-
-JavaAnnotationHover_multipleMarkersAtThisLine=Multiple markers at this line
-JavaEditor_codeassist_noCompletions=No completions available.
-
-OptionalMessageDialog_dontShowAgain= Do not show this &message again
-
-ElementValidator_cannotPerform= The requested operation cannot be performed.
-
-SelectionListenerWithASTManager_job_title=Requesting JavaScript AST from selection
-JavaOutlineControl_statusFieldText_hideInheritedMembers= Press ''{0}'' to hide inherited members
-JavaOutlineControl_statusFieldText_showInheritedMembers= Press ''{0}'' to show inherited members
-
-##########
-# Rename support
-##########
-RenameSupport_not_available=The refactoring operation is not available
-RenameSupport_dialog_title=Rename Refactoring
-
-CoreUtility_job_title=Rebuilding
-CoreUtility_buildall_taskname=Build all...
-CoreUtility_buildproject_taskname=Build project ''{0}''...
-
-
-JsNature_Global=Global
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIPreferenceInitializer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIPreferenceInitializer.java
deleted file mode 100644
index f4db448e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIPreferenceInitializer.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class JavaUIPreferenceInitializer extends AbstractPreferenceInitializer {
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
- */
- public void initializeDefaultPreferences() {
- IPreferenceStore store = PreferenceConstants.getPreferenceStore();
-
- EditorsUI.useAnnotationsPreferencePage(store);
- EditorsUI.useQuickDiffPreferencePage(store);
- PreferenceConstants.initializeDefaultValues(store);
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIStatus.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIStatus.java
deleted file mode 100644
index 4a8a2681..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIStatus.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-/**
- * Convenience class for error exceptions thrown inside JavaScriptUI plugin.
- */
-public class JavaUIStatus extends Status {
-
- private JavaUIStatus(int severity, int code, String message, Throwable throwable) {
- super(severity, JavaScriptPlugin.getPluginId(), code, message, throwable);
- }
-
- public static IStatus createError(int code, Throwable throwable) {
- String message= throwable.getMessage();
- if (message == null) {
- message= throwable.getClass().getName();
- }
- return new JavaUIStatus(IStatus.ERROR, code, message, throwable);
- }
-
- public static IStatus createError(int code, String message, Throwable throwable) {
- return new JavaUIStatus(IStatus.ERROR, code, message, throwable);
- }
-
- public static IStatus createWarning(int code, String message, Throwable throwable) {
- return new JavaUIStatus(IStatus.WARNING, code, message, throwable);
- }
-
- public static IStatus createInfo(int code, String message, Throwable throwable) {
- return new JavaUIStatus(IStatus.INFO, code, message, throwable);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaWorkbenchAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaWorkbenchAdapter.java
deleted file mode 100644
index 0a07e56f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaWorkbenchAdapter.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * An imlementation of the IWorkbenchAdapter for IJavaElements.
- */
-public class JavaWorkbenchAdapter implements IWorkbenchAdapter {
-
- protected static final Object[] NO_CHILDREN= new Object[0];
-
- private JavaElementImageProvider fImageProvider;
-
- public JavaWorkbenchAdapter() {
- fImageProvider= new JavaElementImageProvider();
- }
-
- public Object[] getChildren(Object element) {
- IJavaScriptElement je= getJavaElement(element);
- if (je instanceof IParent) {
- try {
- return ((IParent)je).getChildren();
- } catch(JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return NO_CHILDREN;
- }
-
- public ImageDescriptor getImageDescriptor(Object element) {
- IJavaScriptElement je= getJavaElement(element);
- if (je != null)
- return fImageProvider.getJavaImageDescriptor(je, JavaElementImageProvider.OVERLAY_ICONS | JavaElementImageProvider.SMALL_ICONS);
-
- return null;
-
- }
-
- public String getLabel(Object element) {
- return JavaScriptElementLabels.getTextLabel(getJavaElement(element), JavaScriptElementLabels.ALL_DEFAULT);
- }
-
- public Object getParent(Object element) {
- IJavaScriptElement je= getJavaElement(element);
- return je != null ? je.getParent() : null;
- }
-
- private IJavaScriptElement getJavaElement(Object element) {
- if (element instanceof IJavaScriptElement)
- return (IJavaScriptElement)element;
- if (element instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)element).getClassFile().getPrimaryElement();
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java
deleted file mode 100644
index 133352f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.osgi.framework.Bundle;
-
-import com.ibm.icu.util.StringTokenizer;
-
-/**
- * Small convenience class to log messages to plugin's log file and also, if
- * desired, the console. This class should only be used by classes in this
- * plugin. Other plugins should make their own copy, with appropriate ID.
- */
-public class Logger {
- private static final String PLUGIN_ID = "org.eclipse.wst.jsdt.ui"; //$NON-NLS-1$
-
- private static final String TRACEFILTER_LOCATION = "/debug/tracefilter"; //$NON-NLS-1$
-
- public static final int OK = IStatus.OK; // 0
- public static final int INFO = IStatus.INFO; // 1
- public static final int WARNING = IStatus.WARNING; // 2
- public static final int ERROR = IStatus.ERROR; // 4
-
- public static final int OK_DEBUG = 200 + OK;
- public static final int INFO_DEBUG = 200 + INFO;
- public static final int WARNING_DEBUG = 200 + WARNING;
- public static final int ERROR_DEBUG = 200 + ERROR;
-
- /**
- * Adds message to log.
- *
- * @param level
- * severity level of the message (OK, INFO, WARNING, ERROR,
- * OK_DEBUG, INFO_DEBUG, WARNING_DEBUG, ERROR_DEBUG)
- * @param message
- * text to add to the log
- * @param exception
- * exception thrown
- */
- protected static void _log(int level, String message, Throwable exception) {
- if (level == OK_DEBUG || level == INFO_DEBUG || level == WARNING_DEBUG || level == ERROR_DEBUG) {
- if (!isDebugging())
- return;
- }
-
- int severity = IStatus.OK;
- switch (level) {
- case INFO_DEBUG :
- case INFO :
- severity = IStatus.INFO;
- break;
- case WARNING_DEBUG :
- case WARNING :
- severity = IStatus.WARNING;
- break;
- case ERROR_DEBUG :
- case ERROR :
- severity = IStatus.ERROR;
- }
- message = (message != null) ? message : "null"; //$NON-NLS-1$
- Status statusObj = new Status(severity, PLUGIN_ID, severity, message, exception);
- Bundle bundle = Platform.getBundle(PLUGIN_ID);
- if (bundle != null)
- Platform.getLog(bundle).log(statusObj);
- }
-
- /**
- * Prints message to log if category matches /debug/tracefilter option.
- *
- * @param message
- * text to print
- * @param category
- * category of the message, to be compared with
- * /debug/tracefilter
- */
- protected static void _trace(String category, String message, Throwable exception) {
- if (isTracing(category)) {
- message = (message != null) ? message : "null"; //$NON-NLS-1$
- Status statusObj = new Status(IStatus.OK, PLUGIN_ID, IStatus.OK, message, exception);
- Bundle bundle = Platform.getBundle(PLUGIN_ID);
- if (bundle != null)
- Platform.getLog(bundle).log(statusObj);
- }
- }
-
- /**
- * @return true if the platform is debugging
- */
- public static boolean isDebugging() {
- return Platform.inDebugMode();
- }
-
- /**
- * Determines if currently tracing a category
- *
- * @param category
- * @return true if tracing category, false otherwise
- */
- public static boolean isTracing(String category) {
- if (!isDebugging())
- return false;
-
- String traceFilter = Platform.getDebugOption(PLUGIN_ID + TRACEFILTER_LOCATION);
- if (traceFilter != null) {
- StringTokenizer tokenizer = new StringTokenizer(traceFilter, ","); //$NON-NLS-1$
- while (tokenizer.hasMoreTokens()) {
- String cat = tokenizer.nextToken().trim();
- if (category.equals(cat)) {
- return true;
- }
- }
- }
- return false;
- }
-
- public static void log(int level, String message) {
- _log(level, message, null);
- }
-
- public static void log(int level, String message, Throwable exception) {
- _log(level, message, exception);
- }
-
- public static void logException(String message, Throwable exception) {
- _log(ERROR, message, exception);
- }
-
- public static void logException(Throwable exception) {
- _log(ERROR, exception.getMessage(), exception);
- }
-
- public static void traceException(String category, String message, Throwable exception) {
- _trace(category, message, exception);
- }
-
- public static void traceException(String category, Throwable exception) {
- _trace(category, exception.getMessage(), exception);
- }
-
- public static void trace(String category, String message) {
- _trace(category, message, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/LogicalPackageAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/LogicalPackageAdapterFactory.java
deleted file mode 100644
index 287a917a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/LogicalPackageAdapterFactory.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.search.ui.ISearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-
-/**
- * Implements basic UI support for LogicalPackage.
- */
-public class LogicalPackageAdapterFactory implements IAdapterFactory {
-
- private static Class[] PROPERTIES= new Class[] {
- ResourceMapping.class
- };
-
- // Must be Object to allow lazy loading
- private Object fSearchPageScoreComputer;
-
- public Class[] getAdapterList() {
- updateLazyLoadedAdapters();
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- updateLazyLoadedAdapters();
-
- if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key)) {
- return fSearchPageScoreComputer;
- } else if (ResourceMapping.class.equals(key)) {
- if (!(element instanceof LogicalPackage))
- return null;
- return JavaElementResourceMapping.create((LogicalPackage)element);
- }
- return null;
- }
-
- private void updateLazyLoadedAdapters() {
- if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
- createSearchPageScoreComputer();
- }
-
- private void createSearchPageScoreComputer() {
- fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
- PROPERTIES= new Class[] {
- ISearchPageScoreComputer.class,
- ResourceMapping.class
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/MarkerAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/MarkerAdapterFactory.java
deleted file mode 100644
index 6e7ce805..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/MarkerAdapterFactory.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.search.ui.ISearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchPageScoreComputer;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-
-
-/**
- * Adapter factory to support basic UI operations for markers.
- */
-public class MarkerAdapterFactory implements IAdapterFactory {
-
- private static Class[] PROPERTIES= new Class[0];
-
-
- private Object fSearchPageScoreComputer;
-
- public Class[] getAdapterList() {
- updateLazyLoadedAdapters();
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- updateLazyLoadedAdapters();
- if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key))
- return fSearchPageScoreComputer;
- return null;
- }
-
- private void updateLazyLoadedAdapters() {
- if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
- createSearchPageScoreComputer();
- }
-
- private void createSearchPageScoreComputer() {
- fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
- PROPERTIES= new Class[] {ISearchPageScoreComputer.class};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/PersistableJavaElementFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/PersistableJavaElementFactory.java
deleted file mode 100644
index 7595ca92..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/PersistableJavaElementFactory.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IElementFactory;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-/**
- * The JavaElementFactory is used to save and recreate an IJavaScriptElement object.
- * As such, it implements the IPersistableElement interface for storage
- * and the IElementFactory interface for recreation.
- *
- * @see IMemento
- * @see IPersistableElement
- * @see IElementFactory
- */
-public class PersistableJavaElementFactory implements IElementFactory, IPersistableElement {
-
- private static final String KEY= "elementID"; //$NON-NLS-1$
- private static final String FACTORY_ID= "org.eclipse.wst.jsdt.ui.PersistableJavaElementFactory"; //$NON-NLS-1$
-
- private IJavaScriptElement fElement;
-
- /**
- * Create a JavaElementFactory.
- */
- public PersistableJavaElementFactory() {
- }
-
- /**
- * Create a JavaElementFactory. This constructor is typically used
- * for our IPersistableElement side.
- */
- public PersistableJavaElementFactory(IJavaScriptElement element) {
- fElement= element;
- }
-
- /*
- * @see IElementFactory
- */
- public IAdaptable createElement(IMemento memento) {
-
- String identifier= memento.getString(KEY);
- if (identifier != null) {
- return JavaScriptCore.create(identifier);
- }
- return null;
- }
-
- /*
- * @see IPersistableElement.
- */
- public String getFactoryId() {
- return FACTORY_ID;
- }
- /*
- * @see IPersistableElement
- */
- public void saveState(IMemento memento) {
- memento.putString(KEY, fElement.getHandleIdentifier());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java
deleted file mode 100644
index 88eafde7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.ui.IPageLayout;
-
-public class ProductProperties {
-
- /**
- * Default values for WTP level product
- */
- static final String ID_PERSPECTIVE_EXPLORER_VIEW = IPageLayout.ID_PROJECT_EXPLORER;
-
- /**
- * Return the value for the associated key from the Platform Product registry or return the
- * WTP default for the JavaScript cases.
- *
- * @param key
- * @return String value of product's property
- */
- public static String getProperty(String key) {
- if (key == null)
- return null;
- String value = null;
- if (Platform.getProduct()!=null)
- value = Platform.getProduct().getProperty(key);
- if (value == null) {
- if (key.equals(IProductConstants.PERSPECTIVE_EXPLORER_VIEW))
- return ID_PERSPECTIVE_EXPLORER_VIEW;
- }
- return value;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceAdapterFactory.java
deleted file mode 100644
index 24659de7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceAdapterFactory.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class ResourceAdapterFactory implements IAdapterFactory {
-
- private static Class[] PROPERTIES= new Class[] {
- IJavaScriptElement.class
- };
-
- public Class[] getAdapterList() {
- return PROPERTIES;
- }
-
- public Object getAdapter(Object element, Class key) {
- if (IJavaScriptElement.class.equals(key)) {
-
- // Performance optimization, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133141
- if (element instanceof IFile) {
- IJavaScriptElement je= JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(new FileEditorInput((IFile)element));
- if (je != null)
- return je;
- }
-
- return JavaScriptCore.create((IResource)element);
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceLocator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceLocator.java
deleted file mode 100644
index fbd1f699..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ResourceLocator.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * This class locates different resources
- * which are related to an object
- */
-public class ResourceLocator implements IResourceLocator {
-
- public IResource getUnderlyingResource(Object element) throws JavaScriptModelException {
- if (element instanceof IJavaScriptElement)
- return ((IJavaScriptElement) element).getUnderlyingResource();
- else
- return null;
- }
-
- public IResource getCorrespondingResource(Object element) throws JavaScriptModelException {
- if (element instanceof IJavaScriptElement)
- return ((IJavaScriptElement) element).getCorrespondingResource();
- else
- return null;
- }
-
- public IResource getContainingResource(Object element) throws JavaScriptModelException {
- IResource resource= null;
- if (element instanceof IResource)
- resource= (IResource) element;
- if (element instanceof IJavaScriptElement) {
- resource= ((IJavaScriptElement) element).getResource();
- if (resource == null)
- resource= ((IJavaScriptElement) element).getJavaScriptProject().getProject();
- }
- return resource;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SetupProjectsWizzard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SetupProjectsWizzard.java
deleted file mode 100644
index 64d9c119..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SetupProjectsWizzard.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IActionDelegate;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.wst.jsdt.ui.project.JsNature;
-
-/**
- * @author childsb
- *
- */
-public class SetupProjectsWizzard implements IObjectActionDelegate, IActionDelegate {
-
- Object[] fTarget;
-
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
-// throw new UnimplementedException("setActivePart(IAction action, IWorkbenchPart targetPart)"); //$NON-NLS-1$
- }
-
- public void run(IAction action) {
- if(fTarget==null) return;
-
- for(int i=0;i<fTarget.length;i++) {
- if(fTarget[i] instanceof IProject) {
- IProject project = (IProject)fTarget[i];
-
- if(!JsNature.hasNature(project)) {
- JsNature nature = new JsNature(project,null);
- try {
- nature.configure();
- } catch (CoreException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
- }
-
- }
- }
-
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
-
- if(selection instanceof StructuredSelection) {
- fTarget = ((StructuredSelection)selection).toArray();
- }else {
- fTarget = null;
- }
- }
-
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SharedImages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SharedImages.java
deleted file mode 100644
index 4a0fae3d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/SharedImages.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.ui.ISharedImages;
-
-/**
- * Default implementation of ISharedImages
- */
-public class SharedImages implements ISharedImages {
-
- public SharedImages() {
- }
-
- /* (Non-Javadoc)
- * Method declared in ISharedImages
- */
- public Image getImage(String key) {
- return JavaPluginImages.get(key);
- }
-
- /* (Non-Javadoc)
- * Method declared in ISharedImages
- */
- public ImageDescriptor getImageDescriptor(String key) {
- return JavaPluginImages.getDescriptor(key);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java
deleted file mode 100644
index 72dfdc57..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-
-/**
- * This is an action template for actions that toggle whether
- * it links its selection to the active editor.
- *
- *
- */
-public abstract class AbstractToggleLinkingAction extends Action {
-
- /**
- * Constructs a new action.
- */
- public AbstractToggleLinkingAction() {
- super(ActionMessages.ToggleLinkingAction_label);
- setDescription(ActionMessages.ToggleLinkingAction_description);
- setToolTipText(ActionMessages.ToggleLinkingAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "synced.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LINK_EDITOR_ACTION);
- }
-
- /**
- * Runs the action.
- */
- public abstract void run();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.java
deleted file mode 100644
index 3e10b3b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class ActionMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages";//$NON-NLS-1$
-
- private ActionMessages() {
- // Do not instantiate
- }
-
- public static String ActionUtil_warning_derived_dontShowAgain;
- public static String ActionUtil_warning_derived_message;
- public static String ActionUtil_warning_derived_title;
- public static String AddDelegateMethodsAction_not_in_source_file;
-
- public static String AddDelegateMethodsAction_template_link_message;
- public static String AddDelegateMethodsAction_template_link_tooltip;
- public static String AddGetterSetterAction_allow_setters_for_finals_description;
- public static String AddGetterSetterAction_error_not_in_source_file;
- public static String AddGetterSetterAction_template_link_description;
- public static String AddGetterSetterAction_template_link_tooltip;
- public static String AddUnimplementedConstructorsAction_template_link_message;
- public static String AddUnimplementedConstructorsAction_template_link_tooltip;
-
- public static String GenerateConstructorUsingFieldsSelectionDialog_template_link_message;
- public static String GenerateConstructorUsingFieldsSelectionDialog_template_link_tooltip;
- public static String CopyQualifiedNameAction_ActionName;
- public static String CopyQualifiedNameAction_ErrorDescription;
- public static String CopyQualifiedNameAction_ErrorTitle;
- public static String CopyQualifiedNameAction_InfoDialogTitel;
- public static String CopyQualifiedNameAction_NoElementToQualify;
- public static String CopyQualifiedNameAction_ToolTipText;
-
- public static String FindNLSProblemsAction_Description;
- public static String FindNLSProblemsAction_ErrorDialogTitle;
- public static String FindNLSProblemsAction_Name;
- public static String FindNLSProblemsAction_NoPropertieFilesFoundErrorDescription;
- public static String FindNLSProblemsAction_ToolTip;
- public static String FormatAllAction_problem_accessing;
- public static String FormatAllAction_read_only_skipped;
- public static String GenerateNewConstructorUsingFieldsAction_error_not_a_source_file;
- public static String OpenAction_error_problem_opening_editor;
- public static String OpenAction_multistatus_message;
- public static String OpenViewActionGroup_showInAction_label;
- public static String OpenWithMenu_label;
-
- public static String RefactorMenu_label;
- public static String SourceMenu_label;
- public static String BuildPath_label;
- public static String BuildAction_label;
- public static String SelectionConverter_codeResolve_failed;
- public static String OpenAction_label;
- public static String OpenAction_tooltip;
- public static String OpenAction_description;
- public static String OpenAction_declaration_label;
- public static String OpenAction_select_element;
- public static String OpenAction_error_title;
- public static String OpenAction_error_message;
- public static String OpenAction_error_messageBadSelection;
- public static String OpenSuperImplementationAction_label;
- public static String OpenSuperImplementationAction_tooltip;
- public static String OpenSuperImplementationAction_description;
- public static String OpenSuperImplementationAction_error_title;
- public static String OpenSuperImplementationAction_error_message;
- public static String OpenSuperImplementationAction_not_applicable;
- public static String OpenSuperImplementationAction_no_super_implementation;
- public static String OpenTypeHierarchyAction_label;
- public static String OpenTypeHierarchyAction_tooltip;
- public static String OpenTypeHierarchyAction_description;
- public static String OpenTypeHierarchyAction_dialog_title;
- public static String OpenTypeHierarchyAction_messages_title;
- public static String OpenTypeHierarchyAction_messages_no_java_element;
- public static String OpenTypeHierarchyAction_messages_no_java_resources;
- public static String OpenTypeHierarchyAction_messages_no_types;
- public static String OpenTypeHierarchyAction_messages_no_valid_java_element;
- public static String OpenTypeHierarchyAction_messages_unknown_import_decl;
- public static String ShowInPackageViewAction_label;
- public static String ShowInPackageViewAction_description;
- public static String ShowInPackageViewAction_tooltip;
- public static String ShowInPackageViewAction_dialog_title;
- public static String ShowInPackageViewAction_error_message;
- public static String ShowInNavigatorView_label;
- public static String ShowInNavigatorView_dialog_title;
- public static String ShowInNavigatorView_dialog_message;
- public static String ShowInNavigatorView_error_activation_failed;
- public static String OverrideMethodsAction_label;
- public static String OverrideMethodsAction_description;
- public static String OverrideMethodsAction_tooltip;
- public static String OverrideMethodsAction_error_actionfailed;
- public static String OverrideMethodsAction_error_title;
- public static String OverrideMethodsAction_error_nothing_found;
- public static String OverrideMethodsAction_not_applicable;
- public static String OverrideMethodsAction_interface_not_applicable;
- public static String OverrideMethodsAction_annotation_not_applicable;
-
- public static String CleanUpAction_label;
- public static String CleanUpAction_labelWizard;
- public static String CleanUpAction_tooltip;
- public static String CleanUpAction_description;
- public static String CleanUpAction_MultiStateErrorTitle;
- public static String CleanUpAction_UnexpectedErrorMessage;
- public static String CleanUpAction_CUNotOnBuildpathMessage;
- public static String CleanUpAction_EmptySelection_description;
- public static String CleanUpAction_actionName;
-
- public static String AddGetterSetterAction_no_primary_type_title;
- public static String AddGetterSetterAction_no_primary_type_message;
- public static String AddGetterSetterAction_label;
- public static String AddGetterSetterAction_description;
- public static String AddGetterSetterAction_tooltip;
- public static String AddGetterSetterAction_error_duplicate_methods;
- public static String AddGetterSetterAction_error_title;
- public static String AddGetterSetterAction_error_actionfailed;
- public static String AddGetterSetterAction_not_applicable;
- public static String AddGetterSetterAction_interface_not_applicable;
- public static String AddGetterSetterAction_annotation_not_applicable;
- public static String AddGetterSetterAction_QueryDialog_title;
- public static String AddGetterSetterAction_SkipExistingDialog_message;
- public static String AddGetterSetterAction_SkipExistingDialog_skip_label;
- public static String AddGetterSetterAction_SkipExistingDialog_replace_label;
- public static String AddGetterSetterAction_SkipExistingDialog_skipAll_label;
- public static String AddGetterSetterAction_dialog_label;
- public static String AddGetterSetterAction_methods_selected;
- public static String AddGettSetterAction_typeContainsNoFields_message;
-
-
- public static String GetterSetterTreeSelectionDialog_select_getters;
- public static String GetterSetterTreeSelectionDialog_select_setters;
- public static String GetterSetterTreeSelectionDialog_alpha_pair_sort;
- public static String GetterSetterTreeSelectionDialog_alpha_method_sort;
- public static String GetterSetterTreeSelectionDialog_sort_label;
- public static String SourceActionDialog_enterAt_label;
- public static String SourceActionDialog_modifier_group;
- public static String SourceActionDialog_modifier_public;
- public static String SourceActionDialog_modifier_protected;
- public static String SourceActionDialog_modifier_default;
- public static String SourceActionDialog_modifier_private;
- public static String SourceActionDialog_modifier_synchronized;
- public static String SourceActionDialog_modifier_final;
- public static String SourceActionDialog_first_method;
- public static String SourceActionDialog_last_method;
- public static String SourceActionDialog_cursor;
- public static String SourceActionDialog_after;
- public static String SourceActionDialog_createMethodComment;
- public static String SourceActionDialog_no_entries;
- public static String SourceActionDialog_createConstructorComment;
- public static String AddUnimplementedConstructorsAction_label;
- public static String AddUnimplementedConstructorsAction_description;
- public static String AddUnimplementedConstructorsAction_tooltip;
- public static String AddUnimplementedConstructorsAction_error_title;
- public static String AddUnimplementedConstructorsAction_not_applicable;
- public static String AddUnimplementedConstructorsAction_interface_not_applicable;
- public static String AddUnimplementedConstructorsAction_enum_not_applicable;
- public static String AddUnimplementedConstructorsAction_annotation_not_applicable;
- public static String AddUnimplementedConstructorsAction_methods_selected;
- public static String AddUnimplementedConstructorsAction_error_nothing_found;
- public static String AddUnimplementedConstructorsAction_dialog_title;
- public static String AddUnimplementedConstructorsAction_dialog_label;
- public static String AddUnimplementedConstructorsDialog_omit_super;
- public static String GenerateConstructorUsingFieldsAction_label;
- public static String GenerateConstructorUsingFieldsAction_description;
- public static String GenerateConstructorUsingFieldsAction_tooltip;
- public static String GenerateConstructorUsingFieldsAction_error_title;
- public static String GenerateConstructorUsingFieldsAction_not_applicable;
- public static String GenerateConstructorUsingFieldsAction_fields_selected;
- public static String GenerateConstructorUsingFieldsAction_error_duplicate_constructor;
- public static String GenerateConstructorUsingFieldsAction_error_nothing_found;
- public static String GenerateConstructorUsingFieldsAction_dialog_title;
- public static String GenerateConstructorUsingFieldsAction_dialog_label;
- public static String GenerateConstructorUsingFieldsAction_interface_not_applicable;
- public static String GenerateConstructorUsingFieldsAction_enum_not_applicable;
- public static String GenerateConstructorUsingFieldsAction_annotation_not_applicable;
- public static String GenerateConstructorUsingFieldsAction_typeContainsNoFields_message;
- public static String GenerateConstructorUsingFieldsAction_error_actionfailed;
- public static String GenerateConstructorUsingFieldsSelectionDialog_up_button;
- public static String GenerateConstructorUsingFieldsSelectionDialog_down_button;
- public static String GenerateConstructorUsingFieldsSelectionDialog_sort_constructor_choices_label;
- public static String GenerateConstructorUsingFieldsSelectionDialog_omit_super;
- public static String GenerateConstructorUsingFieldsAction_error_anonymous_class;
-
- public static String AddJavaDocStubAction_label;
- public static String AddJavaDocStubAction_description;
- public static String AddJavaDocStubAction_tooltip;
- public static String AddJavaDocStubsAction_error_dialogTitle;
- public static String AddJavaDocStubsAction_error_actionFailed;
- public static String AddJavaDocStubsAction_not_applicable;
- public static String ExternalizeStringsAction_label;
- public static String ExternalizeStringsAction_dialog_title;
- public static String ExternalizeStringsAction_dialog_message;
- public static String FindStringsToExternalizeAction_label;
- public static String FindStringsToExternalizeAction_dialog_title;
- public static String FindStringsToExternalizeAction_error_message;
- public static String FindStringsToExternalizeAction_error_cannotBeParsed;
- public static String FindStringsToExternalizeAction_foundStrings;
- public static String FindStringsToExternalizeAction_noStrings;
- public static String FindStringsToExternalizeAction_non_externalized;
- public static String FindStringsToExternalizeAction_button_label;
- public static String FindStringsToExternalizeAction_find_strings;
- public static String OpenExternalJavadocAction_label;
- public static String OpenExternalJavadocAction_description;
- public static String OpenExternalJavadocAction_tooltip;
- public static String OpenExternalJavadocAction_select_element;
- public static String OpenExternalJavadocAction_libraries_no_location;
- public static String OpenExternalJavadocAction_source_no_location;
- public static String OpenExternalJavadocAction_opening_failed;
- public static String OpenExternalJavadocAction_dialog_title;
- public static String OpenExternalJavadocAction_code_resolve_failed;
- public static String SelfEncapsulateFieldAction_label;
- public static String SelfEncapsulateFieldAction_dialog_title;
- public static String SelfEncapsulateFieldAction_dialog_unavailable;
- public static String SelfEncapsulateFieldAction_dialog_cannot_perform;
- public static String OrganizeImportsAction_label;
- public static String OrganizeImportsAction_tooltip;
- public static String OrganizeImportsAction_description;
- public static String OrganizeImportsAction_multi_error_parse;
- public static String OrganizeImportsAction_multi_error_unresolvable;
- public static String OrganizeImportsAction_selectiondialog_title;
- public static String OrganizeImportsAction_selectiondialog_message;
- public static String OrganizeImportsAction_error_title;
- public static String OrganizeImportsAction_error_message;
- public static String OrganizeImportsAction_single_error_parse;
- public static String OrganizeImportsAction_summary_added;
- public static String OrganizeImportsAction_summary_removed;
- public static String OrganizeImportsAction_EmptySelection_description;
- public static String OrganizeImportsAction_EmptySelection_title;
-
- public static String FormatAllAction_label;
- public static String FormatAllAction_tooltip;
- public static String FormatAllAction_description;
- public static String FormatAllAction_status_description;
- public static String FormatAllAction_multi_status_title;
- public static String FormatAllAction_error_title;
- public static String FormatAllAction_error_message;
- public static String FormatAllAction_operation_description;
- public static String FormatAllAction_noundo_title;
- public static String FormatAllAction_noundo_message;
- public static String FormatAllAction_EmptySelection_description;
- public static String FormatAllAction_EmptySelection_title;
-
- public static String SortMembersAction_label;
- public static String SortMembersAction_tooltip;
- public static String SortMembersAction_description;
- public static String SortMembersAction_not_applicable;
- public static String SortMembersAction_containsmarkers;
- public static String SortMembersAction_dialog_title;
- public static String MemberFilterActionGroup_hide_fields_label;
- public static String MemberFilterActionGroup_hide_fields_tooltip;
- public static String MemberFilterActionGroup_hide_fields_description;
- public static String MemberFilterActionGroup_hide_static_label;
- public static String MemberFilterActionGroup_hide_static_tooltip;
- public static String MemberFilterActionGroup_hide_static_description;
- public static String MemberFilterActionGroup_hide_nonpublic_label;
- public static String MemberFilterActionGroup_hide_nonpublic_tooltip;
- public static String MemberFilterActionGroup_hide_nonpublic_description;
- public static String MemberFilterActionGroup_hide_localtypes_label;
- public static String MemberFilterActionGroup_hide_localtypes_tooltip;
- public static String MemberFilterActionGroup_hide_localtypes_description;
- public static String NewWizardsActionGroup_new;
- public static String OpenProjectAction_dialog_title;
- public static String OpenProjectAction_dialog_message;
- public static String OpenProjectAction_error_message;
- public static String OpenJavaPerspectiveAction_dialog_title;
- public static String OpenJavaPerspectiveAction_error_open_failed;
- public static String OpenJavaBrowsingPerspectiveAction_dialog_title;
- public static String OpenJavaBrowsingPerspectiveAction_error_open_failed;
- public static String OpenTypeInHierarchyAction_label;
- public static String OpenTypeInHierarchyAction_description;
- public static String OpenTypeInHierarchyAction_tooltip;
- public static String OpenTypeInHierarchyAction_dialogMessage;
- public static String OpenTypeInHierarchyAction_dialogTitle;
- public static String RefreshAction_label;
- public static String RefreshAction_toolTip;
- public static String RefreshAction_progressMessage;
- public static String RefreshAction_error_title;
- public static String RefreshAction_error_message;
- public static String RefreshAction_locationDeleted_title;
- public static String RefreshAction_locationDeleted_message;
- public static String ModifyParameterAction_problem_title;
- public static String ModifyParameterAction_problem_message;
- public static String ActionUtil_notOnBuildPath_title;
- public static String ActionUtil_notOnBuildPath_message;
- public static String ActionUtil_notOnBuildPath_resource_message;
- public static String ActionUtil_not_possible;
- public static String ActionUtil_no_linked;
- public static String SelectAllAction_label;
- public static String SelectAllAction_tooltip;
- public static String AddToClasspathAction_label;
- public static String AddToClasspathAction_toolTip;
- public static String AddToClasspathAction_progressMessage;
- public static String AddToClasspathAction_error_title;
- public static String AddToClasspathAction_error_message;
- public static String RemoveFromClasspathAction_Remove;
- public static String RemoveFromClasspathAction_tooltip;
- public static String RemoveFromClasspathAction_Removing;
- public static String RemoveFromClasspathAction_exception_dialog_title;
- public static String RemoveFromClasspathAction_Problems_occurred;
- public static String AddDelegateMethodsAction_error_title;
- public static String AddDelegateMethodsAction_error_actionfailed;
- public static String AddDelegateMethodsAction_label;
- public static String AddDelegateMethodsAction_description;
- public static String AddDelegateMethodsAction_tooltip;
- public static String AddDelegateMethodsAction_not_applicable;
- public static String AddDelegateMethodsAction_annotation_not_applicable;
- public static String AddDelegateMethodsAction_interface_not_applicable;
- public static String AddDelegateMethodsAction_duplicate_methods;
- public static String AddDelegateMethodsAction_title;
- public static String AddDelegateMethodsAction_message;
- public static String AddDelegateMethodsAction_selectioninfo_more;
-
- public static String SurroundWithTemplateMenuAction_ConfigureTemplatesActionName;
- public static String SurroundWithTemplateMenuAction_NoneApplicable;
- public static String SurroundWithTemplateMenuAction_SurroundWithTemplateSubMenuName;
- public static String SurroundWithTemplateMenuAction_SurroundWithTryCatchActionName;
-
- public static String ToggleLinkingAction_label;
- public static String ToggleLinkingAction_tooltip;
- public static String ToggleLinkingAction_description;
- public static String ConfigureContainerAction_error_title;
- public static String ConfigureContainerAction_error_creationfailed_message;
- public static String ConfigureContainerAction_error_applyingfailed_message;
- public static String FindExceptionOccurrences_text;
- public static String FindExceptionOccurrences_toolTip;
- public static String FindImplementOccurrencesAction_text;
- public static String FindImplementOccurrencesAction_toolTip;
-
- public static String CategoryFilterActionGroup_JavaCategoryFilter_title;
- public static String CategoryFilterActionGroup_SelectAllCategories;
- public static String CategoryFilterActionGroup_DeselectAllCategories;
- public static String CategoryFilterActionGroup_SelectCategoriesDescription;
- public static String CategoryFilterActionGroup_ShowCategoriesActionDescription;
- public static String CategoryFilterActionGroup_ShowCategoriesToolTip;
- public static String CategoryFilterActionGroup_ShowCategoriesLabel;
- public static String CategoryFilterActionGroup_ShowUncategorizedMembers;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, ActionMessages.class);
- }
-
-// public static String OpenNewAnnotationWizardAction_text;
-// public static String OpenNewAnnotationWizardAction_description;
-// public static String OpenNewAnnotationWizardAction_tooltip;
- public static String OpenNewClassWizardAction_text;
- public static String OpenNewClassWizardAction_description;
- public static String OpenNewClassWizardAction_tooltip;
-// public static String OpenNewEnumWizardAction_text;
-// public static String OpenNewEnumWizardAction_description;
-// public static String OpenNewEnumWizardAction_tooltip;
- public static String OpenNewInterfaceWizardAction_text;
- public static String OpenNewInterfaceWizardAction_description;
- public static String OpenNewInterfaceWizardAction_tooltip;
- public static String OpenNewJavaProjectWizardAction_text;
- public static String OpenNewJavaProjectWizardAction_description;
- public static String OpenNewJavaProjectWizardAction_tooltip;
- public static String OpenNewPackageWizardAction_text;
- public static String OpenNewPackageWizardAction_description;
- public static String OpenNewPackageWizardAction_tooltip;
- public static String OpenNewSourceFolderWizardAction_text;
- public static String OpenNewSourceFolderWizardAction_text2;
- public static String OpenNewSourceFolderWizardAction_description;
- public static String OpenNewSourceFolderWizardAction_tooltip;
-// public static String GenerateBuildPathActionGroup_update_jar_text;
-// public static String GenerateBuildPathActionGroup_update_jar_description;
-// public static String GenerateBuildPathActionGroup_update_jar_tooltip;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties
deleted file mode 100644
index d2b90bcb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties
+++ /dev/null
@@ -1,412 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-# Sebastian Davids <sdavids@gmx.de> - Bug 114276
-###############################################################################
-
-OpenWithMenu_label=Open Wit&h
-RefactorMenu_label=Refac&tor
-SourceMenu_label=&Source
-BuildPath_label=&Build Path
-
-BuildAction_label=&Build Project
-SelectionConverter_codeResolve_failed=Could not convert text selection into a JavaScript element
-
-OpenAction_label=&Open
-OpenAction_tooltip=Open an Editor on the Selected Element
-OpenAction_description=Open an editor on the selected element
-OpenAction_declaration_label=&Open Declaration
-OpenAction_select_element=&Select or enter the element to open:
-
-OpenAction_error_title=Open
-OpenAction_error_message=Problems opening an editor.
-OpenAction_multistatus_message=See details for editors that could not be opened.
-OpenAction_error_messageBadSelection=Current text selection does not resolve to a JavaScript element
-OpenAction_error_problem_opening_editor=Problem opening editor for ''{0}'': ''{1}''
-
-OpenSuperImplementationAction_label=Open S&uper Implementation
-OpenSuperImplementationAction_tooltip=Open the Implementation in the Super Type
-OpenSuperImplementationAction_description=Open the Implementation in the Super Type
-OpenSuperImplementationAction_error_title=Open Super Implementation
-OpenSuperImplementationAction_error_message=Opening the super implementation failed. Check log for details.
-OpenSuperImplementationAction_not_applicable=The operation is not applicable to the current selection. Select an overriding function.
-OpenSuperImplementationAction_no_super_implementation=The super implementation of function ''{0}'' does not exist.
-
-OpenTypeHierarchyAction_label=Ope&n Type Hierarchy
-OpenNewClassWizardAction_text=Class
-OpenTypeHierarchyAction_tooltip=Open a Type Hierarchy on the Selected Element
-OpenTypeHierarchyAction_description=Open a type hierarchy on the selected element
-OpenTypeHierarchyAction_dialog_title=Open Type Hierarchy
-OpenTypeHierarchyAction_messages_title=Cannot create type hierarchy
-OpenTypeHierarchyAction_messages_no_java_element=A JavaScript element must be selected.
-OpenTypeHierarchyAction_messages_no_java_resources=The selected package does not contain any JavaScript resource.
-OpenTypeHierarchyAction_messages_no_types=The selected JavaScript file does not contain a type.
-#OpenNewAnnotationWizardAction_description=Opens the new annotation type wizard
-OpenNewJavaProjectWizardAction_description=Opens the new JavaScript project wizard
-OpenNewSourceFolderWizardAction_description=Opens the new JavaScript source folder wizard
-OpenNewInterfaceWizardAction_description=Opens the new interface wizard
-OpenTypeHierarchyAction_messages_no_valid_java_element=A valid JavaScript element must be selected.
-OpenTypeHierarchyAction_messages_unknown_import_decl=The selected import declaration can not be resolved.
-
-ShowInPackageViewAction_label=Show in Pac&kage Explorer
-ShowInPackageViewAction_description=Show the selected element in Script Explorer
-ShowInPackageViewAction_tooltip=Show in Script Explorer
-ShowInPackageViewAction_dialog_title=Show In Script Explorer
-ShowInPackageViewAction_error_message=An internal error occurred. Please see log for details.
-
-ShowInNavigatorView_label=Show in &Navigator View
-ShowInNavigatorView_dialog_title=Show in Navigator View
-ShowInNavigatorView_dialog_message=Select the element to be opened in the navigator view:
-ShowInNavigatorView_error_activation_failed=Cannot activate Resource Navigator
-
-OverrideMethodsAction_label=O&verride/Implement Functions...
-OverrideMethodsAction_description=Override or implement functions declared in supertypes
-OverrideMethodsAction_tooltip=Override/Implement Functions
-OverrideMethodsAction_error_actionfailed=An error occurred while creating the functions
-
-OverrideMethodsAction_error_title=Override/Implement Functions
-OverrideMethodsAction_error_nothing_found=No functions to override found for this type.
-OverrideMethodsAction_not_applicable=The operation is not applicable to the current selection. Select a type.
-OverrideMethodsAction_interface_not_applicable=The Override Functions operation is not applicable to interfaces.
-OverrideMethodsAction_annotation_not_applicable=The Override Functions operation is not applicable to annotations.
-
-AddGetterSetterAction_label=Gene&rate Getters and Setters...
-AddGetterSetterAction_description=Generate Getter and Setter functions for type's vars
-AddGetterSetterAction_tooltip=Generate Getter and Setter Functions for the Type's Vars
-
-AddGetterSetterAction_error_duplicate_methods=Possible duplicate function(s) selected
-AddGetterSetterAction_no_primary_type_title=Add Setter and Getter
-AddGetterSetterAction_no_primary_type_message=No primary type found.
-AddGetterSetterAction_error_title=Generate Getters and Setters
-AddGetterSetterAction_error_actionfailed=Generating Getters and Setters Failed.
-
-AddGetterSetterAction_not_applicable=The operation is not applicable to the current selection. Select a var which is not declared as type variable or a type that declares such vars.
-AddGetterSetterAction_interface_not_applicable=The Generate Getters and Setters operation is not applicable to interfaces.
-AddGetterSetterAction_annotation_not_applicable=The Generate Getters and Setters operation is not applicable to annotations.
-AddGetterSetterAction_error_not_in_source_file=The Generate Getters and Setters operation is only applicable to types and vars in source files.
-AddGetterSetterAction_template_link_description=The format of the getters/setters may be configured on the <a>Code Templates</a> preference page.
-AddGetterSetterAction_template_link_tooltip=Show the code templates preferences.
-
-AddGetterSetterAction_QueryDialog_title=Generate Getters and Setters
-AddGetterSetterAction_SkipExistingDialog_message=Function ''{0}'' already exists.\nSkip creation?
-AddGetterSetterAction_SkipExistingDialog_skip_label=&Skip
-AddGetterSetterAction_SkipExistingDialog_replace_label=&Replace
-AddGetterSetterAction_SkipExistingDialog_skipAll_label=Skip &All
-AddGetterSetterAction_allow_setters_for_finals_description=Allow setters for final vars (remove 'final' modifier from vars if necessary)
-
-AddGetterSetterAction_dialog_label=&Select getters and setters to create:
-AddGetterSetterAction_methods_selected={0} of {1} selected.
-AddGettSetterAction_typeContainsNoFields_message=The type contains no vars or all vars have getters/setters already.
-
-GetterSetterTreeSelectionDialog_select_getters=Select &Getters
-GetterSetterTreeSelectionDialog_select_setters=Se&lect Setters
-GetterSetterTreeSelectionDialog_alpha_pair_sort=Vars in getter/setter pairs
-GetterSetterTreeSelectionDialog_alpha_method_sort=First getters, then setters
-GetterSetterTreeSelectionDialog_sort_label=S&ort by:
-
-SourceActionDialog_enterAt_label=&Insertion point:
-SourceActionDialog_modifier_group=Access modifier
-SourceActionDialog_modifier_public=&public
-SourceActionDialog_modifier_protected=protec&ted
-SourceActionDialog_modifier_default=d&efault
-SourceActionDialog_modifier_private=pri&vate
-SourceActionDialog_modifier_synchronized=s&ynchronized
-SourceActionDialog_modifier_final=&final
-SourceActionDialog_first_method=First function
-SourceActionDialog_last_method=Last function
-SourceActionDialog_cursor=Cursor position
-SourceActionDialog_after=After ''{0}''
-SourceActionDialog_createMethodComment=Generate function &comments
-SourceActionDialog_no_entries=No functions available.
-SourceActionDialog_createConstructorComment=Generate constructor &comments
-
-AddUnimplementedConstructorsAction_label=Generate &Constructors from Superclass...
-AddUnimplementedConstructorsAction_description=Generate constructors from superclass
-AddUnimplementedConstructorsAction_tooltip=Generate Constructors from Superclass
-AddUnimplementedConstructorsAction_error_title=Generate Constructors from Superclass
-AddUnimplementedConstructorsAction_not_applicable=The operation is not applicable to the current selection. Select a class.
-AddUnimplementedConstructorsAction_interface_not_applicable=The Generate Constructors from Superclass operation is not applicable to interfaces.
-AddUnimplementedConstructorsAction_enum_not_applicable=The Generate Constructors from Superclass operation is not applicable to enums.
-AddUnimplementedConstructorsAction_annotation_not_applicable=The Generate Constructors from Superclass operation is not applicable to annotations.
-AddUnimplementedConstructorsAction_methods_selected={0} of {1} selected.
-AddUnimplementedConstructorsAction_error_nothing_found=There are no constructors from the superclass which may be added.
-AddUnimplementedConstructorsAction_dialog_title=Generate Constructors from Superclass
-AddUnimplementedConstructorsAction_dialog_label=&Select constructors to implement:
-
-AddUnimplementedConstructorsDialog_omit_super=&Omit call to default constructor super()
-
-GenerateConstructorUsingFieldsAction_label=Generate C&onstructor using Vars...
-GenerateConstructorUsingFieldsAction_description=Generate Constructor using vars
-GenerateConstructorUsingFieldsAction_tooltip=Generate Constructor Using Vars
-GenerateConstructorUsingFieldsAction_error_title=Generate Constructor using Vars
-GenerateConstructorUsingFieldsAction_not_applicable=The operation is not applicable to the current selection. Select a class.
-GenerateConstructorUsingFieldsAction_fields_selected={0} of {1} selected.
-GenerateConstructorUsingFieldsAction_error_duplicate_constructor=The constructor to be created is possibly a duplicate
-GenerateConstructorUsingFieldsAction_error_nothing_found=There are no constructors from the superclass which may be used.
-GenerateConstructorUsingFieldsAction_dialog_title=Generate Constructor using Vars
-GenerateConstructorUsingFieldsAction_dialog_label=&Select vars to initialize:
-GenerateConstructorUsingFieldsAction_interface_not_applicable=The Generate Constructor using Vars operation is not applicable to interfaces.
-GenerateConstructorUsingFieldsAction_enum_not_applicable=The Generate Constructor using Vars operation is not applicable to enums.
-GenerateConstructorUsingFieldsAction_annotation_not_applicable=The Generate Constructor using Vars operation is not applicable to annotations.
-GenerateConstructorUsingFieldsAction_typeContainsNoFields_message=The selected type contains no vars which may be initialized in a constructor.
-GenerateConstructorUsingFieldsAction_error_actionfailed=Unexpected error while creating constructors. See log for details.
-GenerateConstructorUsingFieldsAction_error_anonymous_class=Anonymous classes cannot contain explicitly declared constructors.
-GenerateNewConstructorUsingFieldsAction_error_not_a_source_file=The selected type is not in a source file
-
-GenerateConstructorUsingFieldsSelectionDialog_up_button=&Up
-GenerateConstructorUsingFieldsSelectionDialog_down_button=Do&wn
-GenerateConstructorUsingFieldsSelectionDialog_sort_constructor_choices_label=Select super constructor to invo&ke:
-GenerateConstructorUsingFieldsSelectionDialog_omit_super=&Omit call to default constructor super()
-
-AddUnimplementedConstructorsAction_template_link_tooltip=Show the code templates preferences.
-AddUnimplementedConstructorsAction_template_link_message=The format of the constructors may be configured on the <a>Code Templates</a> preference page.
-
-GenerateConstructorUsingFieldsSelectionDialog_template_link_tooltip=Show the code templates preferences.
-GenerateConstructorUsingFieldsSelectionDialog_template_link_message=The format of the constructors may be configured on the <a>Code Templates</a> preference page.
-
-AddJavaDocStubAction_label=Generate Element Commen&t
-AddJavaDocStubAction_description=Add a comment stub to the member element
-AddJavaDocStubAction_tooltip=Add a Comment Stub to the Member Element
-
-AddJavaDocStubsAction_error_dialogTitle=Generate Element Comment
-AddJavaDocStubsAction_error_actionFailed=Error while adding comment
-AddJavaDocStubsAction_not_applicable=The operation is not applicable to the current selection. Select a type or function.
-
-ExternalizeStringsAction_label= &Externalize Strings...
-ExternalizeStringsAction_dialog_title= Externalize Strings
-ExternalizeStringsAction_dialog_message=Could not open Externalize String Wizard
-
-FindStringsToExternalizeAction_label= Find Strings to Externali&ze...
-FindStringsToExternalizeAction_dialog_title= Find Strings to Externalize
-FindStringsToExternalizeAction_error_message= Unexpected Exception. See log.
-FindStringsToExternalizeAction_error_cannotBeParsed= JavaScript file ''{0}'' can not be parsed.
-FindStringsToExternalizeAction_foundStrings= {0} in {1}
-FindStringsToExternalizeAction_noStrings= No non-externalized strings found.
-FindStringsToExternalizeAction_non_externalized= {0} &non-externalized string(s) found.
-FindStringsToExternalizeAction_button_label= &Externalize...
-FindStringsToExternalizeAction_find_strings= Finding non-externalized strings...
-
-OpenExternalJavadocAction_label=Open E&xternal JSDoc
-OpenExternalJavadocAction_description=Opens the JSDoc of the selected element in an external browser
-OpenExternalJavadocAction_tooltip=Opens the JSDoc of the Selected Element in an External Browser
-OpenExternalJavadocAction_select_element=&Select or enter the element to open:
-OpenExternalJavadocAction_libraries_no_location=The documentation location for ''{0}'' has not been configured. For elements from libraries specify the JSDoc location URL on the properties page of the parent JAR (''{1}'')
-OpenExternalJavadocAction_source_no_location=The documentation location for ''{0}'' has not been configured. For elements from source specify the JSDoc location URL on the properties page of the parent project (''{1}'')
-OpenExternalJavadocAction_opening_failed=Opening JSDoc failed. See log for details
-OpenExternalJavadocAction_dialog_title=Open External JSDoc
-OpenExternalJavadocAction_code_resolve_failed=Could not convert text selection into a JavaScript element
-
-SelfEncapsulateFieldAction_label=Encap&sulate Var...
-SelfEncapsulateFieldAction_dialog_title=Encapsulate Var
-SelfEncapsulateFieldAction_dialog_unavailable=The operation is not applicable to the current selection. Select a var of a class or enum.
-SelfEncapsulateFieldAction_dialog_cannot_perform=Cannot perform refactoring. See log for more details.
-
-OrganizeImportsAction_label=Or&ganize Imports
-OrganizeImportsAction_tooltip=Evaluate All Required Imports and Replace the Current Imports
-OrganizeImportsAction_description=Evaluate all required imports and replace the current imports
-
-CleanUpAction_label=Clean &Up
-CleanUpAction_labelWizard=Clean &Up...
-CleanUpAction_tooltip=Solve Problems and Improve Code Style on Selected Resources
-CleanUpAction_description=Solve problems and improve code style on selected resources
-CleanUpAction_MultiStateErrorTitle=Problems while processing some JavaScript files. See 'Details' for more information.
-CleanUpAction_actionName=Clean Up
-CleanUpAction_UnexpectedErrorMessage={0}: Unexpected error. See log for details.
-CleanUpAction_CUNotOnBuildpathMessage={0}: JavaScript file not on include path. No changes applied.
-CleanUpAction_EmptySelection_description=The selection contains no JavaScript files.
-
-OrganizeImportsAction_EmptySelection_title=Organize Imports
-OrganizeImportsAction_multi_error_parse=Problem while Organize Imports: {0} has parse errors. No changes applied.
-OrganizeImportsAction_multi_error_unresolvable=Problem while Organize Imports: {0} contains ambiguous references. User interaction required.
-
-OrganizeImportsAction_selectiondialog_title=Organize Imports
-OrganizeImportsAction_selectiondialog_message=&Choose type to import:
-
-OrganizeImportsAction_error_title=Organize Imports
-OrganizeImportsAction_error_message=Unexpected error in organize imports. See log for details.
-
-OrganizeImportsAction_single_error_parse=JavaScript file has parse errors: ''{0}''. No changes applied.
-
-OrganizeImportsAction_summary_added={0} import(s) added.
-OrganizeImportsAction_summary_removed={0} import(s) removed.
-
-OrganizeImportsAction_EmptySelection_description=The selection contains no JavaScript files.
-
-FormatAllAction_label=Format
-FormatAllAction_tooltip=Format all selected JavaScript files
-FormatAllAction_description=Format all selected JavaScript files
-FormatAllAction_status_description=Problems while formatting some JavaScript files. See 'Details' for more information.
-FormatAllAction_multi_status_title=Format
-FormatAllAction_read_only_skipped=File ''{0}'' is read-only and has been skipped.
-FormatAllAction_problem_accessing=Problems accessing file ''{0}'': {1}
-FormatAllAction_error_title=Format
-FormatAllAction_error_message=Unexpected error while formatting. See log for details.
-
-FormatAllAction_operation_description=Formatting...
-FormatAllAction_EmptySelection_title=Format
-FormatAllAction_EmptySelection_description=The selection contains no JavaScript files.
-FormatAllAction_noundo_title=Format
-FormatAllAction_noundo_message='Undo' is not supported by this operation. Do you want to continue?
-
-
-SortMembersAction_label=Sort &Members...
-SortMembersAction_tooltip=Sorts all Members using the Member Order Preference
-SortMembersAction_description=Sorts all members using the member order preference
-SortMembersAction_dialog_title=Sort Members
-
-SortMembersAction_not_applicable=Operation not applicable to current text editor.
-SortMembersAction_containsmarkers=Markers like bookmarks, breakpoints, or user defined tasks in a reordered member will be lost. OK to continue?
-
-#OpenNewAnnotationWizardAction_text=Annotation
-OpenNewPackageWizardAction_tooltip=Opens the new JavaScript package wizard
-OpenNewClassWizardAction_tooltip=Opens the new class wizard
-OpenNewInterfaceWizardAction_text=Interface
-#OpenNewEnumWizardAction_tooltip=Opens the new enum type wizard
-OpenNewPackageWizardAction_text=Package
-
-MemberFilterActionGroup_hide_fields_label=Hide Fiel&ds
-MemberFilterActionGroup_hide_fields_tooltip=Hide Vars
-MemberFilterActionGroup_hide_fields_description=Toggles the visibility of vars
-
-MemberFilterActionGroup_hide_static_label=Hide &Static Vars and Functions
-MemberFilterActionGroup_hide_static_tooltip=Hide Static Vars and Functions
-MemberFilterActionGroup_hide_static_description=Toggles the visibility of static vars and functions
-
-MemberFilterActionGroup_hide_nonpublic_label=Hide Non-&Public Members
-MemberFilterActionGroup_hide_nonpublic_tooltip=Hide Non-Public Members
-MemberFilterActionGroup_hide_nonpublic_description=Toggles the visibility of non-public members
-
-MemberFilterActionGroup_hide_localtypes_label=Hide Local &Types
-MemberFilterActionGroup_hide_localtypes_tooltip=Hide Local Types
-MemberFilterActionGroup_hide_localtypes_description=Toggles the visibility of local types
-
-
-NewWizardsActionGroup_new=Ne&w
-
-OpenProjectAction_dialog_title=Open Project
-OpenProjectAction_dialog_message=Select &project(s) to be opened:
-OpenProjectAction_error_message=Problems while opening projects
-
-OpenJavaPerspectiveAction_dialog_title=Open JavaScript Perspective
-OpenJavaPerspectiveAction_error_open_failed=Could not open JavaScript perspective
-
-OpenJavaBrowsingPerspectiveAction_dialog_title=Open JavaScript Browsing Perspective
-OpenJavaBrowsingPerspectiveAction_error_open_failed=Could not open JavaScript browsing perspective
-
-OpenTypeInHierarchyAction_label=Open Type in Hierarchy...
-OpenTypeInHierarchyAction_description=Open a type in a type hierarchy
-
-OpenTypeInHierarchyAction_tooltip=Open a Type in a Type Hierarchy
-OpenTypeInHierarchyAction_dialogMessage=&Choose a type (? = any character, * = any string):
-OpenTypeInHierarchyAction_dialogTitle=Open Type in Hierarchy
-#OpenNewAnnotationWizardAction_tooltip=Opens the new annotation type wizard
-OpenNewJavaProjectWizardAction_tooltip=Opens the new JavaScript project wizard
-OpenNewPackageWizardAction_description=Opens the new JavaScript package wizard
-OpenViewActionGroup_showInAction_label=Sho&w In
-OpenNewSourceFolderWizardAction_tooltip=Opens the new JavaScript source folder wizard
-OpenNewClassWizardAction_description=Opens the new class wizard
-OpenNewInterfaceWizardAction_tooltip=Opens the new interface wizard
-OpenNewSourceFolderWizardAction_text=Source Folder
-OpenNewSourceFolderWizardAction_text2=New Source Folder...
-#OpenNewEnumWizardAction_description=Opens the new enum type wizard
-OpenNewJavaProjectWizardAction_text=JavaScript Project
-
-RefreshAction_label= Re&fresh
-RefreshAction_toolTip= Refresh
-RefreshAction_progressMessage= Refreshing...
-RefreshAction_error_title= Refresh Problems
-RefreshAction_error_message= Problems occurred refreshing the selected resources.
-RefreshAction_locationDeleted_title= Project location has been deleted
-RefreshAction_locationDeleted_message= The location for project {0} ({1}) has been deleted.\n Delete {0} from the workspace?
-
-ModifyParameterAction_problem_title=Refactoring
-ModifyParameterAction_problem_message=Cannot perform operation.
-
-ActionUtil_notOnBuildPath_title=Cannot Perform Operation
-ActionUtil_notOnBuildPath_message=The resource is not on the build path of a JavaScript project.
-ActionUtil_notOnBuildPath_resource_message=The resource ''{0}'' is not on the build path of a JavaScript project.
-ActionUtil_not_possible=Cannot Perform Operation
-ActionUtil_no_linked=This operation is unavailable on linked packages and package fragment roots.
-ActionUtil_warning_derived_title=Derived File Encountered
-ActionUtil_warning_derived_message=The file ''{0}'' is derived. Do you really want to edit it?
-ActionUtil_warning_derived_dontShowAgain=In the future, never warn if editing a derived file.
-
-SelectAllAction_label= Select A&ll
-SelectAllAction_tooltip= Select All
-
-AddToClasspathAction_label=Add to &Build Path
-AddToClasspathAction_toolTip=Add JAR to the JavaScript Build Path
-AddToClasspathAction_progressMessage=Adding to build path...
-AddToClasspathAction_error_title=Add to Build Path
-AddToClasspathAction_error_message=Problems occurred while adding to the build path.
-
-RemoveFromClasspathAction_Remove=Remove from &Build Path
-RemoveFromClasspathAction_tooltip=Remove Package Fragment Root from the JavaScript Build Path
-RemoveFromClasspathAction_Removing=Removing from build path...
-RemoveFromClasspathAction_exception_dialog_title=Remove From Build Path
-RemoveFromClasspathAction_Problems_occurred=Problems occurred while removing from the build path.
-
-AddDelegateMethodsAction_error_title=Generate Delegate Functions
-AddDelegateMethodsAction_error_actionfailed=Generating delegate functions failed.
-AddDelegateMethodsAction_label=Generate Delegate &Functions...
-AddDelegateMethodsAction_description=Adds delegate functions for a type's vars
-AddDelegateMethodsAction_tooltip=Adds Delegates Functions for a Type's Vars
-AddDelegateMethodsAction_not_applicable=The operation is not applicable to the current selection. Select a var which is not declared as type variable or a type that declares such fields.
-AddDelegateMethodsAction_annotation_not_applicable=The Generate Delegate Functions operation is not applicable to annotations.
-AddDelegateMethodsAction_interface_not_applicable=The Generate Delegate Functions operation is not applicable to interfaces.
-AddDelegateMethodsAction_duplicate_methods=Duplicate function(s) selected
-
-AddDelegateMethodsAction_title=Generate Delegate Functions
-AddDelegateMethodsAction_message=Select &functions to create delegates for:
-AddDelegateMethodsAction_selectioninfo_more={0} of {1} selected.
-AddDelegateMethodsAction_not_in_source_file=The Generate Delegate Functions operation is only applicable to vars and types in source files.
-AddDelegateMethodsAction_template_link_message=The format of the delegate functions may be configured on the <a>Code Templates</a> preference page.
-AddDelegateMethodsAction_template_link_tooltip=Show the code templates preferences.
-
-ToggleLinkingAction_label=Lin&k With Editor
-ToggleLinkingAction_tooltip=Link with Editor
-ToggleLinkingAction_description=Link with active editor
-
-ConfigureContainerAction_error_title=Configure Includepath Container
-ConfigureContainerAction_error_creationfailed_message=Configuration of the includepath container failed.
-ConfigureContainerAction_error_applyingfailed_message=Application of the includepath container changes failed.
-
-FindExceptionOccurrences_text= Throwing E&xception
-FindExceptionOccurrences_toolTip= Find All Occurrences Throwing this Exception
-
-FindImplementOccurrencesAction_text= I&mplementing Functions
-FindImplementOccurrencesAction_toolTip= Find All Functions Implementing or Overriding the Selected Type
-
-
-CategoryFilterActionGroup_JavaCategoryFilter_title=Visible JavaScript Categories
-CategoryFilterActionGroup_SelectAllCategories=Select &All
-CategoryFilterActionGroup_DeselectAllCategories=&Deselect All
-CategoryFilterActionGroup_SelectCategoriesDescription=Select the categories to show in the view:
-CategoryFilterActionGroup_ShowCategoriesActionDescription=Select the visible categories in the view
-CategoryFilterActionGroup_ShowCategoriesToolTip=Select Visible Categories
-CategoryFilterActionGroup_ShowUncategorizedMembers=&0 Show Uncategorized Members
-CategoryFilterActionGroup_ShowCategoriesLabel=&Visible Categories...
-
-FindNLSProblemsAction_Description=Finds undefined, duplicate, and unused NLS keys in property files
-FindNLSProblemsAction_ErrorDialogTitle=Find Broken Externalized Strings
-FindNLSProblemsAction_Name=Find Broken Ex&ternalized Strings
-FindNLSProblemsAction_NoPropertieFilesFoundErrorDescription=No NLS property files with corresponding accessor class found in selection.
-FindNLSProblemsAction_ToolTip=Finds undefined, duplicate, and unused NLS keys in property files
-
-CopyQualifiedNameAction_ToolTipText=Copy to fully qualified name to the system Clipboard
-CopyQualifiedNameAction_InfoDialogTitel=Copy Qualified Name
-CopyQualifiedNameAction_ErrorDescription=There was a problem when accessing the system clipboard. Retry?
-CopyQualifiedNameAction_ActionName=Copy Qualified Name
-CopyQualifiedNameAction_ErrorTitle=Problem Copying to Clipboard
-CopyQualifiedNameAction_NoElementToQualify=No Element to qualify found in selection.
-
-SurroundWithTemplateMenuAction_SurroundWithTemplateSubMenuName=Surround &With
-SurroundWithTemplateMenuAction_SurroundWithTryCatchActionName=Tr&y/catch Block
-SurroundWithTemplateMenuAction_ConfigureTemplatesActionName=&Configure Templates...
-SurroundWithTemplateMenuAction_NoneApplicable=(no template applicable)
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionUtil.java
deleted file mode 100644
index f7b6db76..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionUtil.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/*
- * http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
- */
-public class ActionUtil {
-
- private ActionUtil(){
- }
-
- //bug 31998 we will have to disable renaming of linked packages (and cus)
- public static boolean mustDisableJavaModelAction(Shell shell, Object element) {
- if (!(element instanceof IPackageFragment) && !(element instanceof IPackageFragmentRoot))
- return false;
-
- IResource resource= ResourceUtil.getResource(element);
- if ((resource == null) || (! (resource instanceof IFolder)) || (! resource.isLinked()))
- return false;
-
- MessageDialog.openInformation(shell, ActionMessages.ActionUtil_not_possible, ActionMessages.ActionUtil_no_linked);
- return true;
- }
-
- public static boolean isProcessable(JavaEditor editor) {
- if (editor == null)
- return true;
- Shell shell= editor.getSite().getShell();
- IJavaScriptElement input= SelectionConverter.getInput(editor);
- // if a Java editor doesn't have an input of type Java element
- // then it is for sure not on the build path
- if (input == null) {
- MessageDialog.openInformation(shell,
- ActionMessages.ActionUtil_notOnBuildPath_title,
- ActionMessages.ActionUtil_notOnBuildPath_message);
- return false;
- }
- return isProcessable(shell, input);
- }
-
- public static boolean isProcessable(Shell shell, IJavaScriptElement element) {
- if (element == null)
- return true;
- if (isOnBuildPath(element))
- return true;
- MessageDialog.openInformation(shell,
- ActionMessages.ActionUtil_notOnBuildPath_title,
- ActionMessages.ActionUtil_notOnBuildPath_message);
- return false;
- }
-
- public static boolean isOnBuildPath(IJavaScriptElement element) {
- //fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT)
- return true;
- IJavaScriptProject project= element.getJavaScriptProject();
- try {
- //if (!project.isOnClasspath(element))
- // return false;
- IProject resourceProject= project.getProject();
- if (resourceProject == null)
- return false;
- IProjectNature nature= resourceProject.getNature(JavaScriptCore.NATURE_ID);
- // We have a Java project
- if (nature != null)
- return true;
- } catch (CoreException e) {
- }
- return false;
- }
-
- public static boolean areProcessable(Shell shell, IJavaScriptElement[] elements) {
- for (int i= 0; i < elements.length; i++) {
- if (! isOnBuildPath(elements[i])) {
- MessageDialog.openInformation(shell,
- ActionMessages.ActionUtil_notOnBuildPath_title,
- Messages.format(ActionMessages.ActionUtil_notOnBuildPath_resource_message, new Object[] {elements[i].getPath()}));
- return false;
- }
- }
- return true;
- }
-
- /**
- * Check whether <code>editor</code> and <code>element</code> are
- * processable and editable. If the editor edits the element, the validation
- * is only performed once. If necessary, ask the user whether the file(s)
- * should be edited.
- *
- * @param editor an editor, or <code>null</code> iff the action was not
- * executed from an editor
- * @param shell a shell to serve as parent for a dialog
- * @param element the element to check, cannot be <code>null</code>
- * @return <code>true</code> if the element can be edited,
- * <code>false</code> otherwise
- */
- public static boolean isEditable(JavaEditor editor, Shell shell, IJavaScriptElement element) {
- if (editor != null) {
- IJavaScriptElement input= SelectionConverter.getInput(editor);
- if (input != null && input.equals(element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT)))
- return isEditable(editor);
- else
- return isEditable(editor) && isEditable(shell, element);
- }
- return isEditable(shell, element);
- }
-
- public static boolean isEditable(JavaEditor editor) {
- if (! isProcessable(editor))
- return false;
-
- return editor.validateEditorInputState();
- }
-
- public static boolean isEditable(Shell shell, IJavaScriptElement element) {
- if (! isProcessable(shell, element))
- return false;
-
- IJavaScriptElement cu= element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- IResource resource= cu.getResource();
- if (resource != null && resource.isDerived()) {
-
- // see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#validateEditorInputState()
- final String warnKey= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WARN_IF_INPUT_DERIVED;
- IPreferenceStore store= EditorsUI.getPreferenceStore();
- if (!store.getBoolean(warnKey))
- return true;
-
- MessageDialogWithToggle toggleDialog= MessageDialogWithToggle.openYesNoQuestion(
- shell,
- ActionMessages.ActionUtil_warning_derived_title,
- Messages.format(ActionMessages.ActionUtil_warning_derived_message, resource.getFullPath().toString()),
- ActionMessages.ActionUtil_warning_derived_dontShowAgain,
- false,
- null,
- null);
-
- EditorsUI.getPreferenceStore().setValue(warnKey, !toggleDialog.getToggleState());
-
- return toggleDialog.getReturnCode() == IDialogConstants.YES_ID;
- }
- }
- return true;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddBlockCommentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddBlockCommentAction.java
deleted file mode 100644
index dc87220f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddBlockCommentAction.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPartitioningException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * Action that encloses the editor's current selection with Java block comment terminators
- * (<code>&#47;&#42;</code> and <code>&#42;&#47;</code>).
- *
- *
- */
-public class AddBlockCommentAction extends BlockCommentAction {
-
- /**
- * Creates a new instance.
- *
- * @param bundle the resource bundle
- * @param prefix a prefix to be prepended to the various resource keys
- * (described in <code>ResourceAction</code> constructor), or
- * <code>null</code> if none
- * @param editor the text editor
- */
- public AddBlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
- super(bundle, prefix, editor);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.actions.BlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, org.eclipse.jface.text.IDocumentExtension3, org.eclipse.wst.jsdt.internal.ui.actions.BlockCommentAction.Edit.EditFactory)
- */
- protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException {
- int selectionOffset= selection.getOffset();
- int selectionEndOffset= selectionOffset + selection.getLength();
- List edits= new LinkedList();
- ITypedRegion partition= docExtension.getPartition(IJavaScriptPartitions.JAVA_PARTITIONING, selectionOffset, false);
-
- handleFirstPartition(partition, edits, factory, selectionOffset);
-
- while (partition.getOffset() + partition.getLength() < selectionEndOffset) {
- partition= handleInteriorPartition(partition, edits, factory, docExtension);
- }
-
- handleLastPartition(partition, edits, factory, selectionEndOffset);
-
- executeEdits(edits);
- }
-
- /**
- * Handle the partition under the start offset of the selection.
- *
- * @param partition the partition under the start of the selection
- * @param edits the list of edits to later execute
- * @param factory the factory for edits
- * @param offset the start of the selection, which must lie inside
- * <code>partition</code>
- */
- private void handleFirstPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, int offset) throws BadLocationException {
-
- int partOffset= partition.getOffset();
- String partType= partition.getType();
-
- Assert.isTrue(partOffset <= offset, "illegal partition"); //$NON-NLS-1$
-
- // first partition: mark start of comment
- if (partType == IDocument.DEFAULT_CONTENT_TYPE) {
- // Java code: right where selection starts
- edits.add(factory.createEdit(offset, 0, getCommentStart()));
- } else if (isSpecialPartition(partType)) {
- // special types: include the entire partition
- edits.add(factory.createEdit(partOffset, 0, getCommentStart()));
- } // javadoc: no mark, will only start after comment
-
- }
-
- /**
- * Handles partition boundaries within the selection. The end of the current
- * partition and the start of the next partition are examined for whether
- * they contain comment tokens that interfere with the created comment.
- * <p>
- * Comment tokens are removed from interior multi-line comments. Javadoc
- * comments are left as is; instead, multi-line comment tokens are inserted
- * before and after Javadoc partitions to ensure that the entire selected
- * area is commented.
- * </p>
- * <p>
- * The next partition is returned.
- * </p>
- *
- * @param partition the current partition
- * @param edits the list of edits to add to
- * @param factory the edit factory
- * @param docExtension the document to get the partitions from
- * @return the next partition after the current
- * @throws BadLocationException if accessing the document fails - this can
- * only happen if the document gets modified concurrently
- * @throws BadPartitioningException if the document does not have a Java
- * partitioning
- */
- private ITypedRegion handleInteriorPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, IDocumentExtension3 docExtension) throws BadPartitioningException, BadLocationException {
-
- // end of previous partition
- String partType= partition.getType();
- int partEndOffset= partition.getOffset() + partition.getLength();
- int tokenLength= getCommentStart().length();
-
- boolean wasJavadoc= false; // true if the previous partition is javadoc
-
- if (partType == IJavaScriptPartitions.JAVA_DOC) {
-
- wasJavadoc= true;
-
- } else if (partType == IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT) {
-
- // already in a comment - remove ending mark
- edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$
-
- }
-
- // advance to next partition
- partition= docExtension.getPartition(IJavaScriptPartitions.JAVA_PARTITIONING, partEndOffset, false);
- partType= partition.getType();
-
- // start of next partition
- if (wasJavadoc) {
-
- // if previous was javadoc, and the current one is not a comment,
- // then add a block comment start
- if (partType == IDocument.DEFAULT_CONTENT_TYPE
- || isSpecialPartition(partType)) {
- edits.add(factory.createEdit(partition.getOffset(), 0, getCommentStart()));
- }
-
- } else { // !wasJavadoc
-
- if (partType == IJavaScriptPartitions.JAVA_DOC) {
- // if next is javadoc, end block comment before
- edits.add(factory.createEdit(partition.getOffset(), 0, getCommentEnd()));
- } else if (partType == IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT) {
- // already in a comment - remove startToken
- edits.add(factory.createEdit(partition.getOffset(), getCommentStart().length(), "")); //$NON-NLS-1$
- }
- }
-
- return partition;
- }
-
- /**
- * Handles the partition under the end of the selection. For normal java
- * code, the comment end token is inserted at the selection end; if the
- * selection ends inside a special (i.e. string, character, line comment)
- * partition, the entire partition is included inside the comment.
- *
- * @param partition the partition under the selection end offset
- * @param edits the list of edits to add to
- * @param factory the edit factory
- * @param endOffset the end offset of the selection
- */
- private void handleLastPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, int endOffset) throws BadLocationException {
-
- String partType= partition.getType();
-
- if (partType == IDocument.DEFAULT_CONTENT_TYPE) {
- // normal java: end comment where selection ends
- edits.add(factory.createEdit(endOffset, 0, getCommentEnd()));
- } else if (isSpecialPartition(partType)) {
- // special types: consume entire partition
- edits.add(factory.createEdit(partition.getOffset() + partition.getLength(), 0, getCommentEnd()));
- }
-
- }
-
- /**
- * Returns whether <code>partType</code> is special, i.e. a Java
- * <code>String</code>,<code>Character</code>, or
- * <code>Line End Comment</code> partition.
- *
- * @param partType the partition type to check
- * @return <code>true</code> if <code>partType</code> is special,
- * <code>false</code> otherwise
- */
- private boolean isSpecialPartition(String partType) {
- return partType == IJavaScriptPartitions.JAVA_CHARACTER
- || partType == IJavaScriptPartitions.JAVA_STRING
- || partType == IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.actions.BlockCommentAction#validSelection(org.eclipse.jface.text.ITextSelection)
- */
- protected boolean isValidSelection(ITextSelection selection) {
- return selection != null && !selection.isEmpty() && selection.getLength() > 0;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddTaskAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddTaskAction.java
deleted file mode 100644
index 16a9bc7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AddTaskAction.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.views.tasklist.TaskPropertiesDialog;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class AddTaskAction extends SelectionDispatchAction {
-
- public AddTaskAction(IWorkbenchSite site) {
- super(site);
- setEnabled(false);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_TASK_ACTION);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getElement(selection) != null);
- }
-
- public void run(IStructuredSelection selection) {
- IResource resource= getElement(selection);
- if (resource == null)
- return;
-
- TaskPropertiesDialog dialog= new TaskPropertiesDialog(getShell());
- dialog.setResource(resource);
- dialog.open();
- }
-
- private IResource getElement(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
-
- Object element= selection.getFirstElement();
- if (!(element instanceof IAdaptable))
- return null;
- return (IResource)((IAdaptable)element).getAdapter(IResource.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AllCleanUpsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AllCleanUpsAction.java
deleted file mode 100644
index 7321c770..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AllCleanUpsAction.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - Bug 133277 Allow Sort Members to be performed on package and project levels
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class AllCleanUpsAction extends CleanUpAction {
-
- private IPreferenceChangeListener fPreferenceChangeListener;
-
- public AllCleanUpsAction(IWorkbenchSite site) {
- super(site);
- setToolTipText(ActionMessages.CleanUpAction_tooltip);
- setDescription(ActionMessages.CleanUpAction_description);
- installPreferenceListener();
- updateActionLabel();
-
- // PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
- }
-
- public AllCleanUpsAction(JavaEditor editor) {
- super(editor);
- setToolTipText(ActionMessages.CleanUpAction_tooltip);
- setDescription(ActionMessages.CleanUpAction_description);
- installPreferenceListener();
- updateActionLabel();
- }
-
- /**
- * {@inheritDoc}
- */
- protected ICleanUp[] createCleanUps(IJavaScriptUnit[] units) {
- return CleanUpRefactoring.createCleanUps();
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getActionName() {
- return ActionMessages.CleanUpAction_actionName;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void performRefactoring(IJavaScriptUnit[] cus, ICleanUp[] cleanUps) throws JavaScriptModelException, InvocationTargetException {
- RefactoringExecutionStarter.startCleanupRefactoring(cus, cleanUps, getShell(), showWizard(), getActionName());
- }
-
- private boolean showWizard() {
- InstanceScope instanceScope= new InstanceScope();
- IEclipsePreferences instanceNode= instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
- if (instanceNode.get(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, null) != null)
- return instanceNode.getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true);
-
- DefaultScope defaultScope= new DefaultScope();
- IEclipsePreferences defaultNode= defaultScope.getNode(JavaScriptUI.ID_PLUGIN);
- return defaultNode.getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true);
- }
-
- private void updateActionLabel() {
- if (showWizard()) {
- setText(ActionMessages.CleanUpAction_labelWizard);
- } else {
- setText(ActionMessages.CleanUpAction_label);
- }
- }
-
- private void installPreferenceListener() {
- fPreferenceChangeListener= new IPreferenceChangeListener() {
- public void preferenceChange(PreferenceChangeEvent event) {
- if (event.getKey().equals(CleanUpConstants.SHOW_CLEAN_UP_WIZARD)) {
- updateActionLabel();
- }
- }
- };
- new InstanceScope().getNode(JavaScriptUI.ID_PLUGIN).addPreferenceChangeListener(fPreferenceChangeListener);
- }
-
- public void dispose() {
- if (fPreferenceChangeListener != null) {
- new InstanceScope().getNode(JavaScriptUI.ID_PLUGIN).removePreferenceChangeListener(fPreferenceChangeListener);
- fPreferenceChangeListener= null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java
deleted file mode 100644
index 76b0bf74..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPartitioningException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension2;
-import org.eclipse.ui.texteditor.TextEditorAction;
-
-
-/**
- * Common block comment code.
- *
- *
- */
-public abstract class BlockCommentAction extends TextEditorAction {
-
- /**
- * Creates a new instance.
- * @param bundle
- * @param prefix
- * @param editor
- */
- public BlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
- super(bundle, prefix, editor);
- }
-
- /**
- * An edit is a kind of <code>DocumentEvent</code>, in this case an edit instruction, that is
- * affiliated with a <code>Position</code> on a document. The offset of the document event is
- * not stored statically, but taken from the affiliated <code>Position</code>, which gets
- * updated when other edits occur.
- */
- static class Edit extends DocumentEvent {
-
- /**
- * Factory for edits which manages the creation, installation and destruction of
- * position categories, position updaters etc. on a certain document. Once a factory has
- * been obtained, <code>Edit</code> objects can be obtained from it which will be linked to
- * the document by positions of one position category.
- * <p>Clients are required to call <code>release</code> once the <code>Edit</code>s are not
- * used any more, so the positions can be discarded.</p>
- */
- public static class EditFactory {
-
- /** The position category basename for this edits. */
- private static final String CATEGORY= "__positionalEditPositionCategory"; //$NON-NLS-1$
-
- /** The count of factories. */
- private static int fgCount= 0;
-
- /** This factory's category. */
- private final String fCategory;
- private IDocument fDocument;
- private IPositionUpdater fUpdater;
-
- /**
- * Creates a new <code>EditFactory</code> with an unambiguous position category name.
- * @param document the document that is being edited.
- */
- public EditFactory(IDocument document) {
- fCategory= CATEGORY + fgCount++;
- fDocument= document;
- }
-
- /**
- * Creates a new edition on the document of this factory.
- *
- * @param offset the offset of the edition at the point when is created.
- * @param length the length of the edition (not updated via the position update mechanism)
- * @param text the text to be replaced on the document
- * @return an <code>Edit</code> reflecting the edition on the document
- */
- public Edit createEdit(int offset, int length, String text) throws BadLocationException {
-
- if (!fDocument.containsPositionCategory(fCategory)) {
- fDocument.addPositionCategory(fCategory);
- fUpdater= new DefaultPositionUpdater(fCategory);
- fDocument.addPositionUpdater(fUpdater);
- }
-
- Position position= new Position(offset);
- try {
- fDocument.addPosition(fCategory, position);
- } catch (BadPositionCategoryException e) {
- Assert.isTrue(false);
- }
- return new Edit(fDocument, length, text, position);
- }
-
- /**
- * Releases the position category on the document and uninstalls the position updater.
- * <code>Edit</code>s managed by this factory are not updated after this call.
- */
- public void release() {
- if (fDocument != null && fDocument.containsPositionCategory(fCategory)) {
- fDocument.removePositionUpdater(fUpdater);
- try {
- fDocument.removePositionCategory(fCategory);
- } catch (BadPositionCategoryException e) {
- Assert.isTrue(false);
- }
- fDocument= null;
- fUpdater= null;
- }
- }
- }
-
- /** The position in the document where this edit be executed. */
- private Position fPosition;
-
- /**
- * Creates a new edition on <code>document</code>, taking its offset from <code>position</code>.
- *
- * @param document the document being edited
- * @param length the length of the edition
- * @param text the replacement text of the edition
- * @param position the position keeping the edition's offset
- */
- protected Edit(IDocument document, int length, String text, Position position) {
- super(document, 0, length, text);
- fPosition= position;
- }
-
- /*
- * @see org.eclipse.jface.text.DocumentEvent#getOffset()
- */
- public int getOffset() {
- return fPosition.getOffset();
- }
-
- /**
- * Executes the edition on document. The offset is taken from the position.
- *
- * @throws BadLocationException if the execution of the document fails.
- */
- public void perform() throws BadLocationException {
- getDocument().replace(getOffset(), getLength(), getText());
- }
-
- }
-
- public void run() {
- if (!isEnabled())
- return;
-
- ITextEditor editor= getTextEditor();
- if (editor == null || !ensureEditable(editor))
- return;
-
- ITextSelection selection= getCurrentSelection();
- if (!isValidSelection(selection))
- return;
-
- if (!validateEditorInputState())
- return;
-
- IDocumentProvider docProvider= editor.getDocumentProvider();
- IEditorInput input= editor.getEditorInput();
- if (docProvider == null || input == null)
- return;
-
- IDocument document= docProvider.getDocument(input);
- if (document == null)
- return;
-
- IDocumentExtension3 docExtension;
- if (document instanceof IDocumentExtension3)
- docExtension= (IDocumentExtension3) document;
- else
- return;
-
- IRewriteTarget target= (IRewriteTarget)editor.getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.beginCompoundChange();
- }
-
- Edit.EditFactory factory= new Edit.EditFactory(document);
-
- try {
- runInternal(selection, docExtension, factory);
-
- } catch (BadLocationException e) {
- // can happen on concurrent modification, deletion etc. of the document
- // -> don't complain, just bail out
- } catch (BadPartitioningException e) {
- // should not happen
- Assert.isTrue(false, "bad partitioning"); //$NON-NLS-1$
- } finally {
- factory.release();
-
- if (target != null) {
- target.endCompoundChange();
- }
- }
- }
-
- /**
- * Calls <code>perform</code> on all <code>Edit</code>s in <code>edits</code>.
- *
- * @param edits a list of <code>Edit</code>s
- * @throws BadLocationException if an <code>Edit</code> threw such an exception.
- */
- protected void executeEdits(List edits) throws BadLocationException {
- for (Iterator it= edits.iterator(); it.hasNext();) {
- Edit edit= (Edit) it.next();
- edit.perform();
- }
- }
-
- /**
- * Ensures that the editor is modifyable. If the editor is an instance of
- * <code>ITextEditorExtension2</code>, its <code>validateEditorInputState</code> method
- * is called, otherwise, the result of <code>isEditable</code> is returned.
- *
- * @param editor the editor to be checked
- * @return <code>true</code> if the editor is editable, <code>false</code> otherwise
- */
- protected boolean ensureEditable(ITextEditor editor) {
- Assert.isNotNull(editor);
-
- if (editor instanceof ITextEditorExtension2) {
- ITextEditorExtension2 ext= (ITextEditorExtension2) editor;
- return ext.validateEditorInputState();
- }
-
- return editor.isEditable();
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- super.update();
-
- if (isEnabled()) {
- if (!canModifyEditor() || !isValidSelection(getCurrentSelection()))
- setEnabled(false);
- }
- }
-
- /**
- * Returns the editor's selection, or <code>null</code> if no selection can be obtained or the
- * editor is <code>null</code>.
- *
- * @return the selection of the action's editor, or <code>null</code>
- */
- protected ITextSelection getCurrentSelection() {
- ITextEditor editor= getTextEditor();
- if (editor != null) {
- ISelectionProvider provider= editor.getSelectionProvider();
- if (provider != null) {
- ISelection selection= provider.getSelection();
- if (selection instanceof ITextSelection)
- return (ITextSelection) selection;
- }
- }
- return null;
- }
-
- /**
- * Runs the real command once all the editor, document, and selection checks have succeeded.
- *
- * @param selection the current selection we are being called for
- * @param docExtension the document extension where we get the partitioning from
- * @param factory the edit factory we can use to create <code>Edit</code>s
- * @throws BadLocationException if an edition fails
- * @throws BadPartitioningException if a partitioning call fails
- */
- protected abstract void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException;
-
- /**
- * Checks whether <code>selection</code> is valid.
- *
- * @param selection the selection to check
- * @return <code>true</code> if the selection is valid, <code>false</code> otherwise
- */
- protected abstract boolean isValidSelection(ITextSelection selection);
-
- /**
- * Returns the text to be inserted at the selection start.
- *
- * @return the text to be inserted at the selection start
- */
- protected String getCommentStart() {
- // for now: no space story
- return "/*"; //$NON-NLS-1$
- }
-
- /**
- * Returns the text to be inserted at the selection end.
- *
- * @return the text to be inserted at the selection end
- */
- protected String getCommentEnd() {
- // for now: no space story
- return "*/"; //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CategoryFilterActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CategoryFilterActionGroup.java
deleted file mode 100644
index 1df1501b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CategoryFilterActionGroup.java
+++ /dev/null
@@ -1,530 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-
-import com.ibm.icu.text.Collator;
-
-public class CategoryFilterActionGroup extends ActionGroup {
-
- private class CategoryFilter extends ViewerFilter {
-
- /**
- * {@inheritDoc}
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IMember) {
- IMember member= (IMember)element;
- try {
- String[] categories= member.getCategories();
- if (categories.length == 0)
- return !fFilterUncategorizedMembers;
-
- for (int i= 0; i < categories.length; i++) {
- if (!fFilteredCategories.contains(categories[i]))
- return true;
- }
- return false;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return true;
- }
-
- }
-
- private class CategoryFilterSelectionDialog extends SelectionStatusDialog implements IListAdapter {
-
- private static final int SELECT_ALL= 0;
- private static final int DESELECT_ALL= 1;
-
- private final CheckedListDialogField fCategoryList;
-
- public CategoryFilterSelectionDialog(Shell parent, List categories, List selectedCategories) {
- super(parent);
-
- setTitle(ActionMessages.CategoryFilterActionGroup_JavaCategoryFilter_title);
-
- String[] buttons= {
- ActionMessages.CategoryFilterActionGroup_SelectAllCategories,
- ActionMessages.CategoryFilterActionGroup_DeselectAllCategories
- };
-
- fCategoryList= new CheckedListDialogField(this, buttons, new ILabelProvider() {
- public Image getImage(Object element) {return null;}
- public String getText(Object element) {return (String)element;}
- public void addListener(ILabelProviderListener listener) {}
- public void dispose() {}
- public boolean isLabelProperty(Object element, String property) {return false;}
- public void removeListener(ILabelProviderListener listener) {}
- });
- fCategoryList.addElements(categories);
- fCategoryList.setViewerComparator(new ViewerComparator());
- fCategoryList.setLabelText(ActionMessages.CategoryFilterActionGroup_SelectCategoriesDescription);
- fCategoryList.checkAll(true);
- for (Iterator iter= selectedCategories.iterator(); iter.hasNext();) {
- String selected= (String)iter.next();
- fCategoryList.setChecked(selected, false);
- }
- if (categories.size() == 0) {
- fCategoryList.setEnabled(false);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setLayout(new GridLayout(1, true));
- composite.setFont(parent.getFont());
-
- Composite list= new Composite(composite, SWT.NONE);
- list.setFont(composite.getFont());
- LayoutUtil.doDefaultLayout(list, new DialogField[] { fCategoryList }, true);
- LayoutUtil.setHorizontalGrabbing(fCategoryList.getListControl(null));
- Dialog.applyDialogFont(composite);
-
- setHelpAvailable(false);
-
- return composite;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void computeResult() {
- setResult(fCategoryList.getCheckedElements());
- }
-
- /**
- * {@inheritDoc}
- */
- public void customButtonPressed(ListDialogField field, int index) {
- if (index == SELECT_ALL) {
- fCategoryList.checkAll(true);
- fCategoryList.refresh();
- } else if (index == DESELECT_ALL) {
- fCategoryList.checkAll(false);
- fCategoryList.refresh();
- }
- }
-
- public void doubleClicked(ListDialogField field) {
- List selectedElements= field.getSelectedElements();
- if (selectedElements.size() == 1) {
- Object selected= selectedElements.get(0);
- fCategoryList.setChecked(selected, !fCategoryList.isChecked(selected));
- }
- }
- public void selectionChanged(ListDialogField field) {}
- }
-
- private class CategoryFilterMenuAction extends Action {
-
- public CategoryFilterMenuAction() {
- setDescription(ActionMessages.CategoryFilterActionGroup_ShowCategoriesActionDescription);
- setToolTipText(ActionMessages.CategoryFilterActionGroup_ShowCategoriesToolTip);
- setText(ActionMessages.CategoryFilterActionGroup_ShowCategoriesLabel);
- JavaPluginImages.setLocalImageDescriptors(this, "category_menu.gif"); //$NON-NLS-1$
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- showCategorySelectionDialog(fInputElement);
- }
-
- }
-
- private class CategoryFilterAction extends Action {
-
- private final String fCategory;
-
- public CategoryFilterAction(String category, int count) {
- fCategory= category;
- StringBuffer buf = new StringBuffer();
- buf.append('&').append(count).append(' ').append(fCategory);
- setText(buf.toString());
- setChecked(!fFilteredCategories.contains(fCategory));
- setId(FILTER_CATEGORY_ACTION_ID);
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- super.run();
- if (fFilteredCategories.contains(fCategory)) {
- fFilteredCategories.remove(fCategory);
- } else {
- fFilteredCategories.add(fCategory);
- }
- fLRUList.put(fCategory, fCategory);
- storeSettings();
- fireSelectionChange();
- }
-
- }
-
- private class FilterUncategorizedMembersAction extends Action {
-
- public FilterUncategorizedMembersAction() {
- setText(ActionMessages.CategoryFilterActionGroup_ShowUncategorizedMembers);
- setChecked(!fFilterUncategorizedMembers);
- setId(FILTER_CATEGORY_ACTION_ID);
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- fFilterUncategorizedMembers= !fFilterUncategorizedMembers;
- storeSettings();
- fireSelectionChange();
- }
- }
-
- private interface IResultCollector {
- public boolean accept(String[] category);
- }
-
- private static int COUNTER= 0;//WORKAROUND for Bug 132669 https://bugs.eclipse.org/bugs/show_bug.cgi?id=132669
-
- private static final String FILTER_CATEGORY_ACTION_ID= "FilterCategoryActionId"; //$NON-NLS-1$
- private final String CATEGORY_MENU_GROUP_NAME= "CategoryMenuGroup" + (COUNTER++); //$NON-NLS-1$
- private static final int MAX_NUMBER_OF_CATEGORIES_IN_MENU= 5;
-
- private final StructuredViewer fViewer;
- private final String fViewerId;
- private final CategoryFilter fFilter;
- private final HashSet fFilteredCategories;
- private IJavaScriptElement[] fInputElement;
- private final CategoryFilterMenuAction fMenuAction;
- private IMenuManager fMenuManager;
- private IMenuListener fMenuListener;
- private final LinkedHashMap fLRUList;
- private boolean fFilterUncategorizedMembers;
-
- public CategoryFilterActionGroup(final StructuredViewer viewer, final String viewerId, IJavaScriptElement[] input) {
- Assert.isLegal(viewer != null);
- Assert.isLegal(viewerId != null);
- Assert.isLegal(input != null);
-
- fLRUList= new LinkedHashMap(MAX_NUMBER_OF_CATEGORIES_IN_MENU * 2, 0.75f, true) {
- private static final long serialVersionUID= 1L;
- protected boolean removeEldestEntry(Map.Entry eldest) {
- return size() > MAX_NUMBER_OF_CATEGORIES_IN_MENU;
- }
- };
- fViewer= viewer;
- fViewerId= viewerId;
- fInputElement= input;
-
- fFilter= new CategoryFilter();
-
- fFilteredCategories= new HashSet();
- loadSettings();
-
- fMenuAction= new CategoryFilterMenuAction();
-
- fViewer.addFilter(fFilter);
- }
-
- public void setInput(IJavaScriptElement[] input) {
- Assert.isLegal(input != null);
- fInputElement= input;
- }
-
- private void loadSettings() {
- fFilteredCategories.clear();
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- String string= store.getString(getPreferenceKey());
- if (string != null && string.length() > 0) {
- String[] categories= string.split(";"); //$NON-NLS-1$
- for (int i= 0; i < categories.length; i++) {
- fFilteredCategories.add(categories[i]);
- }
- }
- string= store.getString(getPreferenceKey()+".LRU"); //$NON-NLS-1$
- if (string != null && string.length() > 0) {
- String[] categories= string.split(";"); //$NON-NLS-1$
- for (int i= categories.length - 1; i >= 0; i--) {
- fLRUList.put(categories[i], categories[i]);
- }
- }
- fFilterUncategorizedMembers= store.getBoolean(getPreferenceKey()+".FilterUncategorized"); //$NON-NLS-1$
- }
-
- private void storeSettings() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- if (fFilteredCategories.size() == 0) {
- store.setValue(getPreferenceKey(), ""); //$NON-NLS-1$
- } else {
- StringBuffer buf= new StringBuffer();
- Iterator iter= fFilteredCategories.iterator();
- String element= (String)iter.next();
- buf.append(element);
- while (iter.hasNext()) {
- element= (String)iter.next();
- buf.append(';');
- buf.append(element);
- }
- store.setValue(getPreferenceKey(), buf.toString());
- buf= new StringBuffer();
- iter= fLRUList.values().iterator();
- element= (String)iter.next();
- buf.append(element);
- while (iter.hasNext()) {
- element= (String)iter.next();
- buf.append(';');
- buf.append(element);
- }
- store.setValue(getPreferenceKey()+".LRU", buf.toString()); //$NON-NLS-1$
- store.setValue(getPreferenceKey()+".FilterUncategorized", fFilterUncategorizedMembers); //$NON-NLS-1$
- }
- }
-
- public void contributeToViewMenu(IMenuManager menuManager) {
- menuManager.add(new Separator(CATEGORY_MENU_GROUP_NAME));
- menuManager.appendToGroup(CATEGORY_MENU_GROUP_NAME, fMenuAction);
- fMenuListener= new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- if (!manager.isVisible())
- return;
- updateMenu(manager);
- }
- };
- menuManager.addMenuListener(fMenuListener);
- fMenuManager= menuManager;
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- super.dispose();
- if (fMenuManager != null) {
- fMenuManager.removeMenuListener(fMenuListener);
- fMenuManager= null;
- fMenuListener= null;
- }
- }
-
- private void updateMenu(IMenuManager manager) {
- IContributionItem[] items= manager.getItems();
- if (items != null) {
- for (int i= 0; i < items.length; i++) {
- IContributionItem item= items[i];
- if (item != null && item.getId() != null && item.getId().equals(FILTER_CATEGORY_ACTION_ID)) {
- IContributionItem removed= manager.remove(item);
- if (removed != null) {
- item.dispose();
- }
- }
- }
- }
- List menuEntries= new ArrayList();
- boolean hasUncategorizedMembers= getMenuCategories(menuEntries);
- Collections.sort(menuEntries, Collator.getInstance());
-
- if (menuEntries.size() > 0 && hasUncategorizedMembers)
- manager.appendToGroup(CATEGORY_MENU_GROUP_NAME, new FilterUncategorizedMembersAction());
-
- int count= 0;
- for (Iterator iter= menuEntries.iterator(); iter.hasNext();) {
- String category= (String)iter.next();
- manager.appendToGroup(CATEGORY_MENU_GROUP_NAME, new CategoryFilterAction(category, count + 1));
- count++;
- }
- }
-
- private boolean getMenuCategories(List result) {
- final HashSet/*<String>*/ categories= new HashSet();
- final HashSet/*<String>*/ foundLRUCategories= new HashSet();
- final boolean hasUncategorizedMember[]= new boolean[] {false};
- for (int i= 0; i < fInputElement.length && !(hasUncategorizedMember[0] && foundLRUCategories.size() >= MAX_NUMBER_OF_CATEGORIES_IN_MENU); i++) {
- collectCategories(fInputElement[i], new IResultCollector() {
- public boolean accept(String[] cats) {
- if (cats.length > 0) {
- for (int j= 0; j < cats.length; j++) {
- String category= cats[j];
- categories.add(category);
- if (fLRUList.containsKey(category)) {
- foundLRUCategories.add(category);
- }
- }
- } else {
- hasUncategorizedMember[0]= true;
- }
- return hasUncategorizedMember[0] && foundLRUCategories.size() >= MAX_NUMBER_OF_CATEGORIES_IN_MENU;
- }
- });
- }
- int count= 0;
- for (Iterator iter= foundLRUCategories.iterator(); iter.hasNext();) {
- String element= (String)iter.next();
- result.add(element);
- count++;
- }
- if (count < MAX_NUMBER_OF_CATEGORIES_IN_MENU) {
- List sortedCategories= new ArrayList(categories);
- Collections.sort(sortedCategories, Collator.getInstance());
- for (Iterator iter= sortedCategories.iterator(); iter.hasNext() && count < MAX_NUMBER_OF_CATEGORIES_IN_MENU;) {
- String element= (String)iter.next();
- if (!foundLRUCategories.contains(element)) {
- result.add(element);
- count++;
- }
- }
- }
- return hasUncategorizedMember[0];
- }
-
- private boolean collectCategories(IJavaScriptElement element, IResultCollector collector) {//HashSet result, int max, LinkedHashMap lruList) {
- try {
- if (element instanceof IMember) {
- IMember member= (IMember)element;
- collector.accept(member.getCategories());
- return processChildren(member.getChildren(), collector);
- } else if (element instanceof IJavaScriptUnit) {
- return processChildren(((IJavaScriptUnit)element).getChildren(), collector);
- } else if (element instanceof IClassFile) {
- return processChildren(((IClassFile)element).getChildren(), collector);
- } else if (element instanceof IJavaScriptModel) {
- return processChildren(((IJavaScriptModel)element).getChildren(), collector);
- } else if (element instanceof IJavaScriptProject) {
- return processChildren(((IJavaScriptProject)element).getChildren(), collector);
- } else if (element instanceof IPackageFragment) {
- return processChildren(((IPackageFragment)element).getChildren(), collector);
- } else if (element instanceof IPackageFragmentRoot) {
- return processChildren(((IPackageFragmentRoot)element).getChildren(), collector);
- }
- return false;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return true;
- }
- }
-
- private boolean processChildren(IJavaScriptElement[] children, IResultCollector collector) {
- for (int i= 0; i < children.length; i++) {
- if (collectCategories(children[i], collector))
- return true;
- }
- return false;
- }
-
- private void fireSelectionChange() {
- fViewer.getControl().setRedraw(false);
- BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fViewer.refresh();
- }
- });
- fViewer.getControl().setRedraw(true);
- }
-
- private String getPreferenceKey() {
- return "CategoryFilterActionGroup." + fViewerId; //$NON-NLS-1$
- }
-
- private void showCategorySelectionDialog(IJavaScriptElement[] input) {
- final HashSet/*<String>*/ categories= new HashSet();
- for (int i= 0; i < input.length; i++) {
- collectCategories(input[i], new IResultCollector() {
- public boolean accept(String[] cats) {
- for (int j= 0; j < cats.length; j++) {
- categories.add(cats[j]);
- }
- return false;
- }
- });
- }
- CategoryFilterSelectionDialog dialog= new CategoryFilterSelectionDialog(fViewer.getControl().getShell(), new ArrayList(categories), new ArrayList(fFilteredCategories));
- if (dialog.open() == Window.OK) {
- Object[] selected= dialog.getResult();
- for (Iterator iter= categories.iterator(); iter.hasNext();) {
- String category= (String)iter.next();
- if (contains(selected, category)) {
- if (fFilteredCategories.remove(category))
- fLRUList.put(category, category);
- } else {
- if (fFilteredCategories.add(category))
- fLRUList.put(category, category);
- }
- }
- storeSettings();
- fireSelectionChange();
- }
- }
-
- private boolean contains(Object[] selected, String category) {
- for (int i= 0; i < selected.length; i++) {
- if (selected[i].equals(category))
- return true;
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CleanUpAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CleanUpAction.java
deleted file mode 100644
index 498b493b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CleanUpAction.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public abstract class CleanUpAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- public CleanUpAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- *
- * @param editor
- * the Java editor
- */
- public CleanUpAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(getCompilationUnit(fEditor) != null);
- }
-
- /**
- * @return the name of this action, not <b>null</b>
- */
- protected abstract String getActionName();
-
- /**
- * @param units
- * the units to clean up
- * @return the clean ups to be performed or <b>null</b> if none to be
- * performed
- */
- protected abstract ICleanUp[] createCleanUps(IJavaScriptUnit[] units);
-
- /**
- * @param units
- * to clean up
- * @param cleanUps
- * clean ups to execute on units
- *
- * @throws JavaScriptModelException
- * @throws InvocationTargetException
- */
- protected void performRefactoring(IJavaScriptUnit[] units, ICleanUp[] cleanUps) throws JavaScriptModelException, InvocationTargetException {
- RefactoringExecutionStarter.startCleanupRefactoring(units, cleanUps, getShell(), false, getActionName());
- }
-
- public void run(ITextSelection selection) {
- IJavaScriptUnit cu= getCompilationUnit(fEditor);
- if (cu != null) {
- run(cu);
- }
- }
-
- public void run(IStructuredSelection selection) {
- IJavaScriptUnit[] cus= getCompilationUnits(selection);
- if (cus.length == 0) {
- MessageDialog.openInformation(getShell(), getActionName(), ActionMessages.CleanUpAction_EmptySelection_description);
- } else if (cus.length == 1) {
- run(cus[0]);
- } else {
- runOnMultiple(cus);
- }
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(getCompilationUnit(fEditor) != null);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(isEnabled(selection));
- }
-
- private boolean isEnabled(IStructuredSelection selection) {
- Object[] selected= selection.toArray();
- for (int i= 0; i < selected.length; i++) {
- try {
- if (selected[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement)selected[i];
- if (elem.exists()) {
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- return elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT; // for browsing perspective
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return true;
- case IJavaScriptElement.IMPORT_CONTAINER:
- return true;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot root= (IPackageFragmentRoot)elem.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
- return true;
- }
- }
- } else if (selected[i] instanceof LogicalPackage) {
- return true;
- }
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return false;
- }
-
- private void run(IJavaScriptUnit cu) {
- if (!ActionUtil.isEditable(fEditor, getShell(), cu))
- return;
-
- ICleanUp[] cleanUps= createCleanUps(new IJavaScriptUnit[] {
- cu
- });
- if (cleanUps == null)
- return;
-
- if (!ElementValidator.check(cu, getShell(), getActionName(), fEditor != null))
- return;
-
- try {
- performRefactoring(new IJavaScriptUnit[] {
- cu
- }, cleanUps);
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- if (e.getCause() instanceof CoreException)
- showUnexpectedError((CoreException)e.getCause());
- } catch (JavaScriptModelException e) {
- showUnexpectedError(e);
- }
- }
-
- private void runOnMultiple(final IJavaScriptUnit[] cus) {
- ICleanUp[] cleanUps= createCleanUps(cus);
- if (cleanUps == null)
- return;
-
- MultiStatus status= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, ActionMessages.CleanUpAction_MultiStateErrorTitle, null);
- for (int i= 0; i < cus.length; i++) {
- IJavaScriptUnit cu= cus[i];
-
- if (!ActionUtil.isOnBuildPath(cu)) {
- String cuLocation= cu.getPath().makeRelative().toString();
- String message= Messages.format(ActionMessages.CleanUpAction_CUNotOnBuildpathMessage, cuLocation);
- status.add(new Status(IStatus.INFO, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message, null));
- }
- }
- if (!status.isOK()) {
- ErrorDialog.openError(getShell(), getActionName(), null, status);
- return;
- }
-
- try {
- performRefactoring(cus, cleanUps);
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- if (e.getCause() instanceof CoreException)
- showUnexpectedError((CoreException)e.getCause());
- } catch (JavaScriptModelException e) {
- showUnexpectedError(e);
- }
- }
-
- private void showUnexpectedError(CoreException e) {
- String message2= Messages.format(ActionMessages.CleanUpAction_UnexpectedErrorMessage, e.getStatus().getMessage());
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message2, null);
- ErrorDialog.openError(getShell(), getActionName(), null, status);
- }
-
- public IJavaScriptUnit[] getCompilationUnits(IStructuredSelection selection) {
- HashSet result= new HashSet();
- Object[] selected= selection.toArray();
- for (int i= 0; i < selected.length; i++) {
- try {
- if (selected[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement)selected[i];
- if (elem.exists()) {
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- if (elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- result.add(elem.getParent());
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- result.add(elem);
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- result.add(elem.getParent());
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- collectCompilationUnits((IPackageFragment)elem, result);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- collectCompilationUnits((IPackageFragmentRoot)elem, result);
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IPackageFragmentRoot[] roots= ((IJavaScriptProject)elem).getPackageFragmentRoots();
- for (int k= 0; k < roots.length; k++) {
- collectCompilationUnits(roots[k], result);
- }
- break;
- }
- }
- } else if (selected[i] instanceof LogicalPackage) {
- IPackageFragment[] packageFragments= ((LogicalPackage)selected[i]).getFragments();
- for (int k= 0; k < packageFragments.length; k++) {
- IPackageFragment pack= packageFragments[k];
- if (pack.exists()) {
- collectCompilationUnits(pack, result);
- }
- }
- }
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- }
- return (IJavaScriptUnit[])result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaScriptModelException {
- result.addAll(Arrays.asList(pack.getJavaScriptUnits()));
- }
-
- private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaScriptModelException {
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IJavaScriptElement[] children= root.getChildren();
- for (int i= 0; i < children.length; i++) {
- collectCompilationUnits((IPackageFragment)children[i], result);
- }
- }
- }
-
- private static IJavaScriptUnit getCompilationUnit(JavaEditor editor) {
- IJavaScriptElement element= JavaScriptUI.getEditorInputJavaElement(editor.getEditorInput());
- if (!(element instanceof IJavaScriptUnit))
- return null;
-
- return (IJavaScriptUnit)element;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CompositeActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CompositeActionGroup.java
deleted file mode 100644
index e6fb04c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CompositeActionGroup.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-
-public class CompositeActionGroup extends ActionGroup {
-
- private ActionGroup[] fGroups;
-
- public CompositeActionGroup() {
- }
-
- public CompositeActionGroup(ActionGroup[] groups) {
- setGroups(groups);
- }
-
- protected void setGroups(ActionGroup[] groups) {
- Assert.isTrue(fGroups == null);
- Assert.isNotNull(groups);
- fGroups= groups;
- }
-
- public ActionGroup get(int index) {
- if (fGroups == null)
- return null;
- return fGroups[index];
- }
-
- public void addGroup(ActionGroup group) {
- if (fGroups == null) {
- fGroups= new ActionGroup[] { group };
- } else {
- ActionGroup[] newGroups= new ActionGroup[fGroups.length + 1];
- System.arraycopy(fGroups, 0, newGroups, 0, fGroups.length);
- newGroups[fGroups.length]= group;
- fGroups= newGroups;
- }
- }
-
- public void dispose() {
- super.dispose();
- if (fGroups == null)
- return;
- for (int i= 0; i < fGroups.length; i++) {
- fGroups[i].dispose();
- }
- }
-
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- if (fGroups == null)
- return;
- for (int i= 0; i < fGroups.length; i++) {
- fGroups[i].fillActionBars(actionBars);
- }
- }
-
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- if (fGroups == null)
- return;
- for (int i= 0; i < fGroups.length; i++) {
- fGroups[i].fillContextMenu(menu);
- }
- }
-
- public void setContext(ActionContext context) {
- super.setContext(context);
- if (fGroups == null)
- return;
- for (int i= 0; i < fGroups.length; i++) {
- fGroups[i].setContext(context);
- }
- }
-
- public void updateActionBars() {
- super.updateActionBars();
- if (fGroups == null)
- return;
- for (int i= 0; i < fGroups.length; i++) {
- fGroups[i].updateActionBars();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java
deleted file mode 100644
index 6321cb9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-/**
- * Action to open a dialog to configure classpath containers. Added as a <code>objectContribution</code>
- * to {@link JsGlobalScopeContainer}.
- */
-public class ConfigureContainerAction implements IObjectActionDelegate {
-
- private ISelection fCurrentSelection;
- private IWorkbenchPart fPart;
-
- /*
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- fPart= targetPart;
- }
-
- /*
- * @see IActionDelegate#run(IAction)
- */
- public void run(IAction action) {
- if (fCurrentSelection instanceof IStructuredSelection) {
- JsGlobalScopeContainer container= (JsGlobalScopeContainer) ((IStructuredSelection) fCurrentSelection).getFirstElement();
- openWizard(container.getClasspathEntry(), container.getLabel(), container.getJavaProject());
- }
- }
-
- private void openWizard(IIncludePathEntry entry, String label, final IJavaScriptProject project) {
- Shell shell= fPart.getSite().getShell();
- try {
- IIncludePathEntry[] entries= project.getRawIncludepath();
-
- IIncludePathEntry result= BuildPathDialogAccess.configureContainerEntry(shell, entry, project, entries);
- if (result == null || result.equals(entry)) {
- return; // user cancelled or no changes
- }
-
- int idx= indexInClasspath(entries, entry);
- if (idx == -1) {
- return;
- }
-
- final IIncludePathEntry[] newEntries= new IIncludePathEntry[entries.length];
- System.arraycopy(entries, 0, newEntries, 0, entries.length);
- newEntries[idx]= result;
-
- IRunnableContext context= fPart.getSite().getWorkbenchWindow();
- if (context == null) {
- context= PlatformUI.getWorkbench().getProgressService();
- }
- context.run(true, true, new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- project.setRawIncludepath(newEntries, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- });
- } catch (JavaScriptModelException e) {
- String title= ActionMessages.ConfigureContainerAction_error_title;
- String message= ActionMessages.ConfigureContainerAction_error_creationfailed_message;
- ExceptionHandler.handle(e, shell, title, message);
- } catch (InvocationTargetException e) {
- String title= ActionMessages.ConfigureContainerAction_error_title;
- String message= ActionMessages.ConfigureContainerAction_error_applyingfailed_message;
- ExceptionHandler.handle(e, shell, title, message);
- } catch (InterruptedException e) {
- // user cancelled
- }
- }
-
- protected static int indexInClasspath(IIncludePathEntry[] entries, IIncludePathEntry entry) {
- for (int i= 0; i < entries.length; i++) {
- if (entries[i] == entry) {
- return i;
- }
- }
- return -1;
- }
-
- /*
- * @see IActionDelegate#selectionChanged(IAction, ISelection)
- */
- public void selectionChanged(IAction action, ISelection selection) {
- fCurrentSelection= selection;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CopyQualifiedNameAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CopyQualifiedNameAction.java
deleted file mode 100644
index d3e5d296..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/CopyQualifiedNameAction.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.MemberRef;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class CopyQualifiedNameAction extends SelectionDispatchAction {
-
- private static final long LABEL_FLAGS= new Long(JavaScriptElementLabels.F_FULLY_QUALIFIED | JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.I_FULLY_QUALIFIED | JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.USE_RESOLVED | JavaScriptElementLabels.T_TYPE_PARAMETERS | JavaScriptElementLabels.CU_QUALIFIED | JavaScriptElementLabels.CF_QUALIFIED).longValue();
-
- //TODO: Make API
- public static final String ACTION_DEFINITION_ID= "org.eclipse.wst.jsdt.ui.edit.text.java.copy.qualified.name"; //$NON-NLS-1$
-
- //TODO: Make API
- public static final String ACTION_HANDLER_ID= "org.eclipse.wst.jsdt.ui.actions.CopyQualifiedName"; //$NON-NLS-1$
-
- private JavaEditor fEditor;
-
- public CopyQualifiedNameAction(JavaEditor editor) {
- this(editor.getSite());
- fEditor= editor;
- setEnabled(true);
- }
-
- public CopyQualifiedNameAction(IWorkbenchSite site) {
- super(site);
-
- setText(ActionMessages.CopyQualifiedNameAction_ActionName);
- setToolTipText(ActionMessages.CopyQualifiedNameAction_ToolTipText);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_COPY_QUALIFIED_NAME);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_COPY_QUALIFIED_NAME);
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(canEnable(selection.toArray()));
- }
-
- public void selectionChanged(ITextSelection selection) {
- //Must not create an AST
- }
-
- private boolean canEnable(Object[] objects) {
- for (int i= 0; i < objects.length; i++) {
- Object element= objects[i];
- if (isValideElement(element))
- return true;
- }
-
- return false;
- }
-
- private boolean isValideElement(Object element) {
- if (element instanceof IMember)
- return true;
-
- if (element instanceof IClassFile)
- return true;
-
- if (element instanceof IJavaScriptUnit)
- return true;
-
- if (element instanceof IImportDeclaration)
- return true;
-
- if (element instanceof IPackageFragment)
- return true;
-
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
-
- try {
- IJavaScriptElement[] elements= getSelectedElements();
- if (elements == null) {
- MessageDialog.openInformation(getShell(), ActionMessages.CopyQualifiedNameAction_InfoDialogTitel, ActionMessages.CopyQualifiedNameAction_NoElementToQualify);
- return;
- }
-
- Object[] data= null;
- Transfer[] dataTypes= null;
-
- if (elements.length == 1) {
- String qualifiedName= JavaScriptElementLabels.getElementLabel(elements[0], LABEL_FLAGS);
- IResource resource= elements[0].getCorrespondingResource();
-
- if (resource != null) {
- IPath location= resource.getLocation();
- if (location != null) {
- data= new Object[] {qualifiedName, resource, new String[] {location.toOSString()}};
- dataTypes= new Transfer[] {TextTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance()};
- } else {
- data= new Object[] {qualifiedName, resource};
- dataTypes= new Transfer[] {TextTransfer.getInstance(), ResourceTransfer.getInstance()};
- }
- } else {
- data= new Object[] {qualifiedName};
- dataTypes= new Transfer[] {TextTransfer.getInstance()};
- }
- } else {
- StringBuffer buf= new StringBuffer();
- buf.append(JavaScriptElementLabels.getElementLabel(elements[0], LABEL_FLAGS));
- for (int i= 1; i < elements.length; i++) {
- IJavaScriptElement element= elements[i];
-
- String qualifiedName= JavaScriptElementLabels.getElementLabel(element, LABEL_FLAGS);
- buf.append('\r').append('\n').append(qualifiedName);
- }
- data= new Object[] {buf.toString()};
- dataTypes= new Transfer[] {TextTransfer.getInstance()};
- }
-
- Clipboard clipboard= new Clipboard(getShell().getDisplay());
- try {
- clipboard.setContents(data, dataTypes);
- } catch (SWTError e) {
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) {
- throw e;
- }
- if (MessageDialog.openQuestion(getShell(), ActionMessages.CopyQualifiedNameAction_ErrorTitle, ActionMessages.CopyQualifiedNameAction_ErrorDescription)) {
- clipboard.setContents(data, dataTypes);
- }
- } finally {
- clipboard.dispose();
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private IJavaScriptElement[] getSelectedElements() throws JavaScriptModelException {
- if (fEditor != null) {
- IJavaScriptElement element= getSelectedElement(fEditor);
- if (element == null)
- return null;
-
- return new IJavaScriptElement[] {element};
- }
-
- ISelection selection= getSelection();
- if (!(selection instanceof IStructuredSelection))
- return null;
-
- List result= new ArrayList();
- for (Iterator iter= ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (isValideElement(element))
- result.add(element);
- }
- if (result.isEmpty())
- return null;
-
- return (IJavaScriptElement[])result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- private IJavaScriptElement getSelectedElement(JavaEditor editor) {
- ISourceViewer viewer= editor.getViewer();
- if (viewer == null)
- return null;
-
- Point selectedRange= viewer.getSelectedRange();
- int length= selectedRange.y;
- int offset= selectedRange.x;
-
- IJavaScriptElement element= JavaScriptUI.getEditorInputJavaElement(editor.getEditorInput());
- JavaScriptUnit ast= ASTProvider.getASTProvider().getAST(element, ASTProvider.WAIT_YES, null);
- if (ast == null)
- return null;
-
- NodeFinder finder= new NodeFinder(offset, length);
- ast.accept(finder);
- ASTNode node= finder.getCoveringNode();
-
- IBinding binding= null;
- if (node instanceof Name) {
- binding= ((Name)node).resolveBinding();
- } else if (node instanceof FunctionInvocation) {
- binding= ((FunctionInvocation)node).resolveMethodBinding();
- } else if (node instanceof FunctionDeclaration) {
- binding= ((FunctionDeclaration)node).resolveBinding();
- } else if (node instanceof Type) {
- binding= ((Type)node).resolveBinding();
- } else if (node instanceof AnonymousClassDeclaration) {
- binding= ((AnonymousClassDeclaration)node).resolveBinding();
- } else if (node instanceof TypeDeclaration) {
- binding= ((TypeDeclaration)node).resolveBinding();
- } else if (node instanceof JavaScriptUnit) {
- return ((JavaScriptUnit)node).getJavaElement();
- } else if (node instanceof Expression) {
- binding= ((Expression)node).resolveTypeBinding();
- } else if (node instanceof ImportDeclaration) {
- binding= ((ImportDeclaration)node).resolveBinding();
- } else if (node instanceof MemberRef) {
- binding= ((MemberRef)node).resolveBinding();
- } else if (node instanceof PackageDeclaration) {
- binding= ((PackageDeclaration)node).resolveBinding();
- } else if (node instanceof VariableDeclaration) {
- binding= ((VariableDeclaration)node).resolveBinding();
- }
-
- if (binding != null)
- return binding.getJavaElement();
-
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ExtractSuperClassAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ExtractSuperClassAction.java
deleted file mode 100644
index 716d285e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ExtractSuperClassAction.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.io.CharConversionException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-/**
- * Action to extract a supertype from a class.
- * <p>
- * Action is applicable to selections containing elements of type
- * <code>IType</code> (top-level types only), <code>IField</code> and
- * <code>IFunction</code>.
- * </p>
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- */
-public class ExtractSuperClassAction extends SelectionDispatchAction {
-
- /**
- * Action definition ID of the refactor -> extract supertype action (value
- * <code>"org.eclipse.wst.jsdt.ui.edit.text.java.extract.superclass"</code>).
- *
- *
- */
- public static final String EXTRACT_SUPERTYPE= "org.eclipse.wst.jsdt.ui.edit.text.java.extract.superclass"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Extract Supertype global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.ExtractSuperclass"</code>).
- *
- *
- */
- public static final String EXTRACT_SUPERTYPES= "org.eclipse.wst.jsdt.ui.actions.ExtractSuperclass"; //$NON-NLS-1$
-
- private static IMember[] getSelectedMembers(final IStructuredSelection selection) {
- if (selection.isEmpty())
- return null;
- if (selection.size() == 1) {
- try {
- final IType type= RefactoringAvailabilityTester.getSingleSelectedType(selection);
- if (type != null)
- return new IType[] {type};
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- for (final Iterator iterator= selection.iterator(); iterator.hasNext();) {
- if (!(iterator.next() instanceof IMember))
- return null;
- }
- final Set set= new HashSet();
- set.addAll(Arrays.asList(selection.toArray()));
- return (IMember[]) set.toArray(new IMember[set.size()]);
- }
-
- /** The java editor */
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- *
- * @param editor
- * the java editor
- */
- public ExtractSuperClassAction(final JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new extract super type action. The action requires that the
- * selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site
- * the workbench site
- */
- public ExtractSuperClassAction(final IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.ExtractSuperTypeAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTRACT_SUPERTYPE_ACTION);
- }
-
- private IMember getSelectedMemberFromEditor() throws JavaScriptModelException {
- final IJavaScriptElement element= SelectionConverter.resolveEnclosingElement(fEditor, (ITextSelection) fEditor.getSelectionProvider().getSelection());
- if (element == null || !(element instanceof IMember))
- return null;
- return (IMember) element;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(final IStructuredSelection selection) {
- try {
- final IMember[] members= getSelectedMembers(selection);
- if (RefactoringAvailabilityTester.isExtractSupertypeAvailable(members) && ActionUtil.isEditable(getShell(), members[0]))
- RefactoringExecutionStarter.startExtractSupertypeRefactoring(members, getShell());
- } catch (final JavaScriptModelException exception) {
- ExceptionHandler.handle(exception, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(final ITextSelection selection) {
- try {
- if (! ActionUtil.isEditable(fEditor))
- return;
- final IMember member= getSelectedMemberFromEditor();
- final IMember[] array= new IMember[] { member};
- if (member != null && RefactoringAvailabilityTester.isExtractSupertypeAvailable(array)) {
- RefactoringExecutionStarter.startExtractSupertypeRefactoring(array, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.ExtractSuperTypeAction_unavailable);
- }
- } catch (JavaScriptModelException exception) {
- ExceptionHandler.handle(exception, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isExtractSupertypeAvailable(selection));
- } catch (JavaScriptModelException exception) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (!(exception.getException() instanceof CharConversionException) && JavaModelUtil.isExceptionToBeLogged(exception))
- JavaScriptPlugin.log(exception);
- setEnabled(false);//no UI - happens on selection changes
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isExtractSupertypeAvailable(selection));
- } catch (JavaScriptModelException event) {
- setEnabled(false);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FindBrokenNLSKeysAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FindBrokenNLSKeysAction.java
deleted file mode 100644
index b423495b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FindBrokenNLSKeysAction.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSHintHelper;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search.SearchBrokenNLSKeysUtil;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class FindBrokenNLSKeysAction extends SelectionDispatchAction {
-
- private static class SearchPatternData {
-
- private final IType fAccessorType;
- private final IFile fPropertyFile;
-
- public SearchPatternData(IType accessorType, IFile propertyFile) {
- fAccessorType= accessorType;
- fPropertyFile= propertyFile;
- }
-
- public IFile getPropertyFile() {
- return fPropertyFile;
- }
-
- public IType getWrapperClass() {
- return fAccessorType;
- }
-
- }
-
- //TODO: Add to API: IJavaEditorActionDefinitionIds
- public static final String FIND_BROKEN_NLS_KEYS_ACTION_ID= "org.eclipse.wst.jsdt.ui.edit.text.java.find.broken.nls.keys"; //$NON-NLS-1$
-
- //TODO: Add to API: JdtActionConstants
- public static final String ACTION_HANDLER_ID= "org.eclipse.wst.jsdt.ui.actions.FindNLSProblems"; //$NON-NLS-1$
-
- private JavaEditor fEditor;
-
- public FindBrokenNLSKeysAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.FindNLSProblemsAction_Name);
- setToolTipText(ActionMessages.FindNLSProblemsAction_ToolTip);
- setDescription(ActionMessages.FindNLSProblemsAction_Description);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the Java editor
- */
- public FindBrokenNLSKeysAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(getCompilationUnit(editor) != null);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- ISelectionProvider selectionProvider= fEditor.getSelectionProvider();
- if (selectionProvider == null)
- return;
-
- run(new StructuredSelection(selectionProvider.getSelection()));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (selection.size() == 1) {
- Object firstElement= selection.getFirstElement();
- if (firstElement instanceof IJavaScriptElement) {
- IJavaScriptElement javaElement= (IJavaScriptElement) firstElement;
- if (!ActionUtil.isProcessable(getShell(), javaElement)) {
- return;
- }
- }
- }
-
- SearchPatternData[] data= getNLSFiles(selection);
- if (data == null || data.length == 0) {
- MessageDialog.openInformation(getShell(), ActionMessages.FindNLSProblemsAction_ErrorDialogTitle, ActionMessages.FindNLSProblemsAction_NoPropertieFilesFoundErrorDescription);
- return;
- }
-
- String scope= "workspace"; //$NON-NLS-1$
- if (selection.size() == 1) {
- Object firstElement= selection.getFirstElement();
- if (firstElement instanceof IJavaScriptElement) {
- scope= ((IJavaScriptElement)firstElement).getElementName();
- } else if (firstElement instanceof IFile) {
- scope= ((IFile)firstElement).getName();
- } else if (firstElement instanceof IFolder) {
- scope= ((IFolder)firstElement).getName();
- }
- }
- run(data, scope);
- }
-
- private void run(SearchPatternData[] data, String scope) {
- List wrappers= new ArrayList();
- List properties= new ArrayList();
- for (int i= 0; i < data.length; i++) {
- SearchPatternData current= data[i];
- if (current.getWrapperClass() != null || current.getPropertyFile() != null) {
- wrappers.add(current.getWrapperClass());
- properties.add(current.getPropertyFile());
- }
- }
- IType[] accessorClasses= (IType[])wrappers.toArray(new IType[wrappers.size()]);
- IFile[] propertieFiles= (IFile[])properties.toArray(new IFile[properties.size()]);
- SearchBrokenNLSKeysUtil.search(scope, accessorClasses, propertieFiles);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- ISelectionProvider selectionProvider= fEditor.getSelectionProvider();
- if (selectionProvider == null) {
- setEnabled(false);
- } else {
- selectionChanged(new StructuredSelection(selectionProvider.getSelection()));
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(canEnable(selection));
- }
-
- private SearchPatternData[] getNLSFiles(IStructuredSelection selection) {
- Object[] selectedElements= selection.toArray();
- List result= new ArrayList();
- collectNLSFiles(selectedElements, result);
- return (SearchPatternData[])result.toArray(new SearchPatternData[result.size()]);
- }
-
- private boolean canEnable(IStructuredSelection selection) {
- Object[] selected= selection.toArray();
- for (int i= 0; i < selected.length; i++) {
- try {
- if (selected[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) selected[i];
- if (elem.exists()) {
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- if (elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- return true;
- }
- return false;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return true;
- case IJavaScriptElement.IMPORT_CONTAINER:
- return false;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return true;
- }
- }
- } else if (selected[i] instanceof LogicalPackage) {
- return true;
- } else if (selected[i] instanceof IFile) {
- IFile file= (IFile)selected[i];
- if ("properties".equalsIgnoreCase(file.getFileExtension())) //$NON-NLS-1$
- return true;
- }
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return false;
- }
-
- private void collectNLSFiles(Object[] objects, List result) {
- try {
- for (int i= 0; i < objects.length; i++) {
- if (objects[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) objects[i];
- if (elem.exists()) {
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- if (elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- SearchPatternData data= tryIfPropertyCuSelected((IJavaScriptUnit)elem.getParent());
- if (data != null) {
- result.add(data);
- }
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- SearchPatternData data= tryIfPropertyCuSelected((IJavaScriptUnit)elem);
- if (data != null) {
- result.add(data);
- }
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- IPackageFragment fragment= (IPackageFragment)elem;
- if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE)
- collectNLSFiles(new Object[] {fragment.getCorrespondingResource()}, result);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- {
- IPackageFragmentRoot root= (IPackageFragmentRoot) elem;
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE)
- collectNLSFiles(new Object[] {root.getCorrespondingResource()}, result);
- break;
- }
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- {
- IJavaScriptProject javaProject= (IJavaScriptProject)elem;
- IPackageFragmentRoot[] allPackageFragmentRoots= javaProject.getAllPackageFragmentRoots();
- for (int j= 0; j < allPackageFragmentRoots.length; j++) {
- IPackageFragmentRoot root= allPackageFragmentRoots[j];
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- if (javaProject.equals(root.getJavaScriptProject())) {
- collectNLSFiles(new Object[] {root.getCorrespondingResource()}, result);
- }
- }
- }
- break;
- }
- }
- }
- } else if (objects[i] instanceof LogicalPackage) {
- LogicalPackage logicalPackage= (LogicalPackage)objects[i];
- collectNLSFiles(new Object[] {logicalPackage.getJavaProject()}, result);
- } else if (objects[i] instanceof IFolder) {
- collectNLSFiles(((IFolder)objects[i]).members(), result);
- } else if (objects[i] instanceof IFile) {
- SearchPatternData data= tryIfPropertyFileSelected((IFile)objects[i]);
- if (data != null) {
- result.add(data);
- }
- }
- }
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- JavaScriptPlugin.log(e);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private SearchPatternData tryIfPropertyCuSelected(IJavaScriptUnit compilationUnit) throws JavaScriptModelException {
- if (compilationUnit == null)
- return null;
-
- if (!ActionUtil.isOnBuildPath(compilationUnit))
- return null;
-
- IType[] types= compilationUnit.getTypes();
- if (types.length > 1)
- return null;
-
- IStorage bundle= NLSHintHelper.getResourceBundle(compilationUnit);
- if (!(bundle instanceof IFile))
- return null;
-
- return new SearchPatternData(types[0], (IFile)bundle);
- }
-
- private SearchPatternData tryIfPropertyFileSelected(IFile file) throws JavaScriptModelException {
- if (!"properties".equalsIgnoreCase(file.getFileExtension())) //$NON-NLS-1$
- return null;
-
- IPath propertyFullPath= file.getFullPath();
- // Try to find a corresponding CU
- String[] javaExtensions= JavaScriptCore.getJavaScriptLikeExtensions();
- for (int i= 0; i < javaExtensions.length; i++) {
- String extension= javaExtensions[i];
- IPath cuPath= propertyFullPath.removeFileExtension().addFileExtension(extension);
- IFile cuFile= (IFile)JavaScriptPlugin.getWorkspace().getRoot().findMember(cuPath);
-
- if (cuFile == null) { //try with uppercase first char
- String filename= cuPath.removeFileExtension().lastSegment();
- if (filename != null && filename.length() > 0) {
- filename= Character.toUpperCase(filename.charAt(0)) + filename.substring(1);
- IPath dirPath= propertyFullPath.removeLastSegments(1).addTrailingSeparator();
- cuPath= dirPath.append(filename).addFileExtension(extension);
- cuFile= (IFile)JavaScriptPlugin.getWorkspace().getRoot().findMember(cuPath);
- }
- }
-
- if (cuFile != null && cuFile.exists()) {
- IJavaScriptElement element= JavaScriptCore.create(cuFile);
- if (element != null && element.exists() && element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT && ActionUtil.isOnBuildPath(element)) {
- IJavaScriptUnit compilationUnit= (IJavaScriptUnit)element;
- IType type= (compilationUnit).findPrimaryType();
- if (type != null) {
- String resourceBundleName= NLSHintHelper.getResourceBundleName(compilationUnit);
- if (resourceBundleName != null) {
- String resourceName= resourceBundleName + NLSRefactoring.PROPERTY_FILE_EXT;
- String name= file.getName();
- if (resourceName.endsWith(name)) {
- return new SearchPatternData(type, file);
- }
- }
- }
- }
- }
- }
-
- return null;
- }
-
- private static IJavaScriptUnit getCompilationUnit(JavaEditor editor) {
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- IJavaScriptUnit cu= manager.getWorkingCopy(editor.getEditorInput());
- return cu;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingActionGroup.java
deleted file mode 100644
index ffb1c91e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingActionGroup.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.source.projection.IProjectionListener;
-import org.eclipse.jface.text.source.projection.ProjectionViewer;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.editors.text.IFoldingCommandIds;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.texteditor.ResourceAction;
-import org.eclipse.ui.texteditor.TextOperationAction;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-
-/**
- * Groups the JDT folding actions.
- *
- *
- */
-public class FoldingActionGroup extends ActionGroup {
- private static abstract class PreferenceAction extends ResourceAction implements IUpdate {
- PreferenceAction(ResourceBundle bundle, String prefix, int style) {
- super(bundle, prefix, style);
- }
- }
-
- /**
- *
- */
- private class FoldingAction extends PreferenceAction {
-
- FoldingAction(ResourceBundle bundle, String prefix) {
- super(bundle, prefix, IAction.AS_PUSH_BUTTON);
- }
-
- public void update() {
- setEnabled(FoldingActionGroup.this.isEnabled() && fViewer.isProjectionMode());
- }
-
- }
-
- private ProjectionViewer fViewer;
-
- private final PreferenceAction fToggle;
- private final TextOperationAction fExpand;
- private final TextOperationAction fCollapse;
- private final TextOperationAction fExpandAll;
- private final IProjectionListener fProjectionListener;
-
- /* since 3.2 */
- private final PreferenceAction fRestoreDefaults;
- private final FoldingAction fCollapseMembers;
- private final FoldingAction fCollapseComments;
- private final TextOperationAction fCollapseAll;
-
-
- /**
- * Creates a new projection action group for <code>editor</code>. If the
- * supplied viewer is not an instance of <code>ProjectionViewer</code>, the
- * action group is disabled.
- *
- * @param editor the text editor to operate on
- * @param viewer the viewer of the editor
- */
- public FoldingActionGroup(final ITextEditor editor, ITextViewer viewer) {
- if (!(viewer instanceof ProjectionViewer)) {
- fToggle= null;
- fExpand= null;
- fCollapse= null;
- fExpandAll= null;
- fCollapseAll= null;
- fRestoreDefaults= null;
- fCollapseMembers= null;
- fCollapseComments= null;
- fProjectionListener= null;
- return;
- }
-
- fViewer= (ProjectionViewer) viewer;
-
- fProjectionListener= new IProjectionListener() {
-
- public void projectionEnabled() {
- update();
- }
-
- public void projectionDisabled() {
- update();
- }
- };
-
- fViewer.addProjectionListener(fProjectionListener);
-
- fToggle= new PreferenceAction(FoldingMessages.getResourceBundle(), "Projection.Toggle.", IAction.AS_CHECK_BOX) { //$NON-NLS-1$
- public void run() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean current= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
- store.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, !current);
- }
-
- public void update() {
- ITextOperationTarget target= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
-
- boolean isEnabled= (target != null && target.canDoOperation(ProjectionViewer.TOGGLE));
- setEnabled(isEnabled);
- }
- };
- fToggle.setChecked(true);
- fToggle.setActionDefinitionId(IFoldingCommandIds.FOLDING_TOGGLE);
- editor.setAction("FoldingToggle", fToggle); //$NON-NLS-1$
-
- fExpandAll= new TextOperationAction(FoldingMessages.getResourceBundle(), "Projection.ExpandAll.", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$
- fExpandAll.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND_ALL);
- editor.setAction("FoldingExpandAll", fExpandAll); //$NON-NLS-1$
-
- fCollapseAll= new TextOperationAction(FoldingMessages.getResourceBundle(), "Projection.CollapseAll.", editor, ProjectionViewer.COLLAPSE_ALL, true); //$NON-NLS-1$
- fCollapseAll.setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE_ALL);
- editor.setAction("FoldingCollapseAll", fCollapseAll); //$NON-NLS-1$
-
- fExpand= new TextOperationAction(FoldingMessages.getResourceBundle(), "Projection.Expand.", editor, ProjectionViewer.EXPAND, true); //$NON-NLS-1$
- fExpand.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND);
- editor.setAction("FoldingExpand", fExpand); //$NON-NLS-1$
-
- fCollapse= new TextOperationAction(FoldingMessages.getResourceBundle(), "Projection.Collapse.", editor, ProjectionViewer.COLLAPSE, true); //$NON-NLS-1$
- fCollapse.setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE);
- editor.setAction("FoldingCollapse", fCollapse); //$NON-NLS-1$
-
- fRestoreDefaults= new FoldingAction(FoldingMessages.getResourceBundle(), "Projection.Restore.") { //$NON-NLS-1$
- public void run() {
- if (editor instanceof JavaEditor) {
- JavaEditor javaEditor= (JavaEditor) editor;
- javaEditor.resetProjection();
- }
- }
- };
- fRestoreDefaults.setActionDefinitionId(IFoldingCommandIds.FOLDING_RESTORE);
- editor.setAction("FoldingRestore", fRestoreDefaults); //$NON-NLS-1$
-
- fCollapseMembers= new FoldingAction(FoldingMessages.getResourceBundle(), "Projection.CollapseMembers.") { //$NON-NLS-1$
- public void run() {
- if (editor instanceof JavaEditor) {
- JavaEditor javaEditor= (JavaEditor) editor;
- javaEditor.collapseMembers();
- }
- }
- };
- fCollapseMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.FOLDING_COLLAPSE_MEMBERS);
- editor.setAction("FoldingCollapseMembers", fCollapseMembers); //$NON-NLS-1$
-
- fCollapseComments= new FoldingAction(FoldingMessages.getResourceBundle(), "Projection.CollapseComments.") { //$NON-NLS-1$
- public void run() {
- if (editor instanceof JavaEditor) {
- JavaEditor javaEditor= (JavaEditor) editor;
- javaEditor.collapseComments();
- }
- }
- };
- fCollapseComments.setActionDefinitionId(IJavaEditorActionDefinitionIds.FOLDING_COLLAPSE_COMMENTS);
- editor.setAction("FoldingCollapseComments", fCollapseComments); //$NON-NLS-1$
- }
-
- /**
- * Returns <code>true</code> if the group is enabled.
- * <pre>
- * Invariant: isEnabled() <=> fViewer and all actions are != null.
- * </pre>
- *
- * @return <code>true</code> if the group is enabled
- */
- protected boolean isEnabled() {
- return fViewer != null;
- }
-
- /*
- * @see org.eclipse.ui.actions.ActionGroup#dispose()
- */
- public void dispose() {
- if (isEnabled()) {
- fViewer.removeProjectionListener(fProjectionListener);
- fViewer= null;
- }
- super.dispose();
- }
-
- /**
- * Updates the actions.
- */
- protected void update() {
- if (isEnabled()) {
- fToggle.update();
- fToggle.setChecked(fViewer.isProjectionMode());
- fExpand.update();
- fExpandAll.update();
- fCollapse.update();
- fCollapseAll.update();
- fRestoreDefaults.update();
- fCollapseMembers.update();
- fCollapseComments.update();
- }
- }
-
- /**
- * Fills the menu with all folding actions.
- *
- * @param manager the menu manager for the folding submenu
- */
- public void fillMenu(IMenuManager manager) {
- if (isEnabled()) {
- update();
- manager.add(fToggle);
- manager.add(fExpandAll);
- manager.add(fExpand);
- manager.add(fCollapse);
- manager.add(fCollapseAll);
- manager.add(fRestoreDefaults);
- manager.add(fCollapseMembers);
- manager.add(fCollapseComments);
- }
- }
-
- /*
- * @see org.eclipse.ui.actions.ActionGroup#updateActionBars()
- */
- public void updateActionBars() {
- update();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java
deleted file mode 100644
index c4ad9d9d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-import com.ibm.icu.text.MessageFormat;
-
-/**
- * Class that gives access to the folding messages resource bundle.
- */
-public class FoldingMessages {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.actions.FoldingMessages"; //$NON-NLS-1$
-
- private static final ResourceBundle RESOURCE_BUNDLE= ResourceBundle.getBundle(BUNDLE_NAME);
-
- private FoldingMessages() {
- // no instance
- }
-
- /**
- * Returns the resource string associated with the given key in the resource bundle. If there isn't
- * any value under the given key, the key is returned.
- *
- * @param key the resource key
- * @return the string
- */
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
-
- /**
- * Returns the resource bundle managed by the receiver.
- *
- * @return the resource bundle
- *
- */
- public static ResourceBundle getResourceBundle() {
- return RESOURCE_BUNDLE;
- }
-
- /**
- * Returns the formatted resource string associated with the given key in the resource bundle.
- * <code>MessageFormat</code> is used to format the message. If there isn't any value
- * under the given key, the key is returned.
- *
- * @param key the resource key
- * @param arg the message argument
- * @return the string
- */
- public static String getFormattedString(String key, Object arg) {
- return getFormattedString(key, new Object[] { arg });
- }
-
- /**
- * Returns the formatted resource string associated with the given key in the resource bundle.
- * <code>MessageFormat</code> is used to format the message. If there isn't any value
- * under the given key, the key is returned.
- *
- * @param key the resource key
- * @param args the message arguments
- * @return the string
- */
- public static String getFormattedString(String key, Object[] args) {
- return MessageFormat.format(getString(key), args);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties
deleted file mode 100644
index b801ed91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties
+++ /dev/null
@@ -1,49 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-Projection.Toggle.label= &Enable Folding
-Projection.Toggle.tooltip= Toggles Folding
-Projection.Toggle.description= Toggles folding for the current editor
-Projection.Toggle.image=
-
-Projection.ExpandAll.label= Expand &All
-Projection.ExpandAll.tooltip= Expands All Collapsed Regions
-Projection.ExpandAll.description= Expands any collapsed regions in the current editor
-Projection.ExpandAll.image=
-
-Projection.Expand.label= E&xpand
-Projection.Expand.tooltip= Expands the Current Collapsed Region
-Projection.Expand.description= Expands the collapsed region at the current selection
-Projection.Expand.image=
-
-Projection.CollapseAll.label= Collapse A&ll
-Projection.CollapseAll.tooltip= Collapses All Expanded Regions
-Projection.CollapseAll.description= Collapse any expanded regions in the current editor
-Projection.CollapseAll.image=
-
-Projection.Collapse.label= Colla&pse
-Projection.Collapse.tooltip= Collapses the Current Region
-Projection.Collapse.description= Collapses the Current Region
-Projection.Collapse.image=
-
-Projection.Restore.label= &Reset Structure
-Projection.Restore.tooltip= Restore the Original Folding Structure
-Projection.Restore.description= Restores the original folding structure
-Projection.Restore.image=
-
-Projection.CollapseComments.label= Collapse &Comments
-Projection.CollapseComments.tooltip= Collapses All Comments
-Projection.CollapseComments.description= Collapses all comments
-Projection.CollapseComments.image=
-
-Projection.CollapseMembers.label= Collapse &Members
-Projection.CollapseMembers.tooltip= Collapses All Members
-Projection.CollapseMembers.description= Collapses all members
-Projection.CollapseMembers.image=
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsContentProvider.java
deleted file mode 100644
index 7d7cb95b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsContentProvider.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-
-public class GenerateConstructorUsingFieldsContentProvider implements ITreeContentProvider {
-
- private static final Object[] EMPTY= new Object[0];
-
- private List fFields= new ArrayList();
-
- private List fSelected= new ArrayList();
-
- private ITypeBinding fType= null;
-
- private final JavaScriptUnit fUnit;
-
- public GenerateConstructorUsingFieldsContentProvider(IType type, List fields, List selected) throws JavaScriptModelException {
- RefactoringASTParser parser= new RefactoringASTParser(AST.JLS3);
- fUnit= parser.parse(type.getJavaScriptUnit(), true);
- fType= ASTNodes.getTypeBinding(fUnit, type);
- if (fType != null) {
- IField field= null;
- for (Iterator iterator= fields.iterator(); iterator.hasNext();) {
- field= (IField) iterator.next();
- VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, fUnit);
- if (fragment != null) {
- IVariableBinding binding= fragment.resolveBinding();
- if (binding != null)
- fFields.add(binding);
- }
- }
- for (Iterator iterator= selected.iterator(); iterator.hasNext();) {
- field= (IField) iterator.next();
- VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, fUnit);
- if (fragment != null) {
- IVariableBinding binding= fragment.resolveBinding();
- if (binding != null)
- fSelected.add(binding);
- }
- }
- }
- }
-
- public JavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- public boolean canMoveDown(List selectedElements) {
- int nSelected= selectedElements.size();
- for (int index= fFields.size() - 1; index >= 0 && nSelected > 0; index--) {
- if (!selectedElements.contains(fFields.get(index))) {
- return true;
- }
- nSelected--;
- }
- return false;
- }
-
- public boolean canMoveUp(List selected) {
- int nSelected= selected.size();
- for (int index= 0; index < fFields.size() && nSelected > 0; index++) {
- if (!selected.contains(fFields.get(index))) {
- return true;
- }
- nSelected--;
- }
- return false;
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- public void down(List checked, CheckboxTreeViewer tree) {
- if (checked.size() > 0) {
- setElements(reverse(moveUp(reverse(fFields), checked)), tree);
- tree.reveal(checked.get(checked.size() - 1));
- }
- tree.setSelection(new StructuredSelection(checked));
- }
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- return EMPTY;
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- return fFields.toArray();
- }
-
- public List getFieldsList() {
- return fFields;
- }
-
- public Object[] getInitiallySelectedElements() {
- if (fSelected.isEmpty())
- return getElements(null);
- return fSelected.toArray();
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- return null;
- }
-
- public ITypeBinding getType() {
- return fType;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- private List moveUp(List elements, List move) {
- List result= new ArrayList(elements.size());
- Object floating= null;
- for (int index= 0; index < elements.size(); index++) {
- Object current= elements.get(index);
- if (move.contains(current)) {
- result.add(current);
- } else {
- if (floating != null) {
- result.add(floating);
- }
- floating= current;
- }
- }
- if (floating != null) {
- result.add(floating);
- }
- return result;
- }
-
- private List reverse(List list) {
- List reverse= new ArrayList(list.size());
- for (int index= list.size() - 1; index >= 0; index--) {
- reverse.add(list.get(index));
- }
- return reverse;
- }
-
- public void setElements(List elements, CheckboxTreeViewer tree) {
- fFields= new ArrayList(elements);
- if (tree != null)
- tree.refresh();
- }
-
- public void up(List checked, CheckboxTreeViewer tree) {
- if (checked.size() > 0) {
- setElements(moveUp(fFields, checked), tree);
- tree.reveal(checked.get(0));
- }
- tree.setSelection(new StructuredSelection(checked));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsSelectionDialog.java
deleted file mode 100644
index 3040eb38..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsSelectionDialog.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IVisibilityChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-
-public class GenerateConstructorUsingFieldsSelectionDialog extends SourceActionDialog {
-
- class GenerateConstructorUsingFieldsTreeViewerAdapter implements ISelectionChangedListener, IDoubleClickListener {
-
- public void doubleClick(DoubleClickEvent event) {
- // Do nothing
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection selection= (IStructuredSelection) getTreeViewer().getSelection();
-
- List selectedList= selection.toList();
- GenerateConstructorUsingFieldsContentProvider cp= (GenerateConstructorUsingFieldsContentProvider) getContentProvider();
-
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.UP_INDEX].setEnabled(cp.canMoveUp(selectedList));
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.DOWN_INDEX].setEnabled(cp.canMoveDown(selectedList));
- }
- }
-
- private static final int DOWN_BUTTON= IDialogConstants.CLIENT_ID + 2;
-
- private static final int UP_BUTTON= IDialogConstants.CLIENT_ID + 1;
-
- protected Button[] fButtonControls;
-
- boolean[] fButtonsEnabled;
-
- IDialogSettings fGenConstructorSettings;
-
- int fHeight= 18;
-
- boolean fOmitSuper;
-
- Button fOmitSuperButton;
-
- IFunctionBinding[] fSuperConstructors;
-
- int fSuperIndex;
-
- GenerateConstructorUsingFieldsTreeViewerAdapter fTreeViewerAdapter;
-
- int fWidth= 60;
-
- final String OMIT_SUPER= "OmitCallToSuper"; //$NON-NLS-1$
-
- final String SETTINGS_SECTION= "GenerateConstructorUsingFieldsSelectionDialog"; //$NON-NLS-1$
-
- private static final int DOWN_INDEX= 1;
-
- private static final int UP_INDEX= 0;
-
- public GenerateConstructorUsingFieldsSelectionDialog(Shell parent, ILabelProvider labelProvider, GenerateConstructorUsingFieldsContentProvider contentProvider, CompilationUnitEditor editor, IType type, IFunctionBinding[] superConstructors) throws JavaScriptModelException {
- super(parent, labelProvider, contentProvider, editor, type, true);
- fTreeViewerAdapter= new GenerateConstructorUsingFieldsTreeViewerAdapter();
-
- fSuperConstructors= superConstructors;
-
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fGenConstructorSettings= dialogSettings.getSection(SETTINGS_SECTION);
- if (fGenConstructorSettings == null) {
- fGenConstructorSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
- fGenConstructorSettings.put(OMIT_SUPER, false);
- }
-
- fOmitSuper= fGenConstructorSettings.getBoolean(OMIT_SUPER);
- }
-
- Composite addSuperClassConstructorChoices(Composite composite) {
- Label label= new Label(composite, SWT.NONE);
- label.setText(ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_sort_constructor_choices_label);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- label.setLayoutData(gd);
-
- BindingLabelProvider provider= new BindingLabelProvider();
- final Combo combo= new Combo(composite, SWT.READ_ONLY);
- for (int i= 0; i < fSuperConstructors.length; i++) {
- combo.add(provider.getText(fSuperConstructors[i]));
- }
-
- // TODO: Can we be a little more intelligent about guessing the super() ?
- combo.setText(combo.getItem(0));
- combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- combo.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- fSuperIndex= combo.getSelectionIndex();
- // Disable omit super checkbox unless default constructor
- fOmitSuperButton.setEnabled(getSuperConstructorChoice().getParameterTypes().length == 0);
- updateOKStatus();
- }
- });
-
- return composite;
- }
-
- protected void buttonPressed(int buttonId) {
- super.buttonPressed(buttonId);
- switch (buttonId) {
- case UP_BUTTON: {
- GenerateConstructorUsingFieldsContentProvider contentProvider= (GenerateConstructorUsingFieldsContentProvider) getTreeViewer().getContentProvider();
- contentProvider.up(getElementList(), getTreeViewer());
- updateOKStatus();
- break;
- }
- case DOWN_BUTTON: {
- GenerateConstructorUsingFieldsContentProvider contentProvider= (GenerateConstructorUsingFieldsContentProvider) getTreeViewer().getContentProvider();
- contentProvider.down(getElementList(), getTreeViewer());
- updateOKStatus();
- break;
- }
- }
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.GENERATE_CONSTRUCTOR_USING_FIELDS_SELECTION_DIALOG);
- }
-
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- GridData gd= null;
-
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
-
- Composite classConstructorComposite= addSuperClassConstructorChoices(composite);
- gd= new GridData(GridData.FILL_BOTH);
- classConstructorComposite.setLayoutData(gd);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout innerLayout= new GridLayout();
- innerLayout.numColumns= 2;
- innerLayout.marginHeight= 0;
- innerLayout.marginWidth= 0;
- inner.setLayout(innerLayout);
-
- Label messageLabel= createMessageArea(inner);
- if (messageLabel != null) {
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- messageLabel.setLayoutData(gd);
- }
-
- CheckboxTreeViewer treeViewer= createTreeViewer(inner);
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(fWidth);
- gd.heightHint= convertHeightInCharsToPixels(fHeight);
- treeViewer.getControl().setLayoutData(gd);
- treeViewer.addSelectionChangedListener(fTreeViewerAdapter);
-
- Composite buttonComposite= createSelectionButtons(inner);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
- buttonComposite.setLayoutData(gd);
-
- gd= new GridData(GridData.FILL_BOTH);
- inner.setLayoutData(gd);
-
- Composite entryComposite= createInsertPositionCombo(composite);
- entryComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite commentComposite= createCommentSelection(composite);
- commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite overrideSuperComposite= createOmitSuper(composite);
- overrideSuperComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Control linkControl= createLinkControl(composite);
- if (linkControl != null)
- linkControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
-
- applyDialogFont(composite);
-
- return composite;
- }
-
- protected Composite createInsertPositionCombo(Composite composite) {
- Composite entryComposite= super.createInsertPositionCombo(composite);
- addVisibilityAndModifiersChoices(entryComposite);
- return entryComposite;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog#createLinkControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP);
- link.setText(ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_template_link_message);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID);
- }
- });
- link.setToolTipText(ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_template_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
- link.setLayoutData(gridData);
- return link;
- }
-
- protected Composite createOmitSuper(Composite composite) {
- Composite omitSuperComposite= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- omitSuperComposite.setLayout(layout);
-
- fOmitSuperButton= new Button(omitSuperComposite, SWT.CHECK);
- fOmitSuperButton.setText(ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_omit_super);
- fOmitSuperButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- fOmitSuperButton.addSelectionListener(new SelectionListener() {
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
-
- public void widgetSelected(SelectionEvent e) {
- boolean isSelected= (((Button) e.widget).getSelection());
- setOmitSuper(isSelected);
- }
- });
- fOmitSuperButton.setSelection(isOmitSuper());
-
- // Disable omit super checkbox unless default constructor and enum
- final boolean hasContructor= getSuperConstructorChoice().getParameterTypes().length == 0;
- fOmitSuperButton.setEnabled(hasContructor);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- fOmitSuperButton.setLayoutData(gd);
-
- return omitSuperComposite;
- }
-
- protected Composite createSelectionButtons(Composite composite) {
- Composite buttonComposite= super.createSelectionButtons(composite);
-
- GridLayout layout= new GridLayout();
- buttonComposite.setLayout(layout);
-
- createUpDownButtons(buttonComposite);
-
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
-
- return buttonComposite;
- }
-
- void createUpDownButtons(Composite buttonComposite) {
- int numButtons= 2; // up, down
- fButtonControls= new Button[numButtons];
- fButtonsEnabled= new boolean[numButtons];
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.UP_INDEX]= createButton(buttonComposite, UP_BUTTON, ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_up_button, false);
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.DOWN_INDEX]= createButton(buttonComposite, DOWN_BUTTON, ActionMessages.GenerateConstructorUsingFieldsSelectionDialog_down_button, false);
- boolean defaultState= false;
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.UP_INDEX].setEnabled(defaultState);
- fButtonControls[GenerateConstructorUsingFieldsSelectionDialog.DOWN_INDEX].setEnabled(defaultState);
- fButtonsEnabled[GenerateConstructorUsingFieldsSelectionDialog.UP_INDEX]= defaultState;
- fButtonsEnabled[GenerateConstructorUsingFieldsSelectionDialog.DOWN_INDEX]= defaultState;
- }
-
- protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
- int[] visibilities= availableVisibilities;
- return createVisibilityControl(parent, visibilityChangeListener, visibilities, correctVisibility);
- }
-
- List getElementList() {
- IStructuredSelection selection= (IStructuredSelection) getTreeViewer().getSelection();
- List elements= selection.toList();
- ArrayList elementList= new ArrayList();
-
- for (int i= 0; i < elements.size(); i++) {
- elementList.add(elements.get(i));
- }
- return elementList;
- }
-
- public IFunctionBinding getSuperConstructorChoice() {
- return fSuperConstructors[fSuperIndex];
- }
-
- public boolean isOmitSuper() {
- return fOmitSuper;
- }
-
- public void setOmitSuper(boolean omitSuper) {
- if (fOmitSuper != omitSuper) {
- fOmitSuper= omitSuper;
- fGenConstructorSettings.put(OMIT_SUPER, omitSuper);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsValidator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsValidator.java
deleted file mode 100644
index 2f6e2432..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateConstructorUsingFieldsValidator.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-public class GenerateConstructorUsingFieldsValidator implements ISelectionStatusValidator {
-
- private GenerateConstructorUsingFieldsSelectionDialog fDialog;
-
- private final int fEntries;
-
- private List fSignatures;
-
- private ITypeBinding fType= null;
-
- public GenerateConstructorUsingFieldsValidator(GenerateConstructorUsingFieldsSelectionDialog dialog, ITypeBinding type, int entries) {
- fEntries= entries;
- fDialog= dialog;
- fType= type;
- fSignatures= getExistingConstructorSignatures();
- }
-
- public GenerateConstructorUsingFieldsValidator(int entries) {
- fEntries= entries;
- fType= null;
- }
-
- private int countSelectedFields(Object[] selection) {
- int count= 0;
- for (int index= 0; index < selection.length; index++) {
- if (selection[index] instanceof IVariableBinding)
- count++;
- }
- return count;
- }
-
- private void createSignature(final IFunctionBinding constructor, StringBuffer buffer, Object[] selection) {
- ITypeBinding types[]= constructor.getParameterTypes();
- for (int index= 0; index < types.length; index++)
- buffer.append(types[index].getName());
- if (selection != null) {
- for (int index= 0; index < selection.length; index++)
- if (selection[index] instanceof IVariableBinding)
- buffer.append(((IVariableBinding) selection[index]).getType().getErasure().getName());
- }
- }
-
- private List getExistingConstructorSignatures() {
- List existing= new ArrayList();
- IFunctionBinding[] methods= fType.getDeclaredMethods();
- for (int index= 0; index < methods.length; index++) {
- if (methods[index].isConstructor()) {
- StringBuffer buffer= new StringBuffer();
- createSignature(methods[index], buffer, null);
- existing.add(buffer.toString());
- }
- }
- return existing;
- }
-
- public IStatus validate(Object[] selection) {
- StringBuffer buffer= new StringBuffer();
- final IFunctionBinding constructor= fDialog.getSuperConstructorChoice();
- createSignature(constructor, buffer, selection);
- if (fSignatures.contains(buffer.toString()))
- return new StatusInfo(IStatus.WARNING, ActionMessages.GenerateConstructorUsingFieldsAction_error_duplicate_constructor);
- return new StatusInfo(IStatus.INFO, Messages.format(ActionMessages.GenerateConstructorUsingFieldsAction_fields_selected, new Object[] { String.valueOf(countSelectedFields(selection)), String.valueOf(fEntries)}));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateJavadocAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateJavadocAction.java
deleted file mode 100644
index 54b9e272..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/GenerateJavadocAction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.wst.jsdt.internal.ui.javadocexport.JavadocWizard;
-
-public class GenerateJavadocAction implements IWorkbenchWindowActionDelegate {
-
- private ISelection fSelection;
- private Shell fCurrentShell;
-
- public void dispose() {
- }
-
- public void init(IWorkbenchWindow window) {
- fCurrentShell= window.getShell();
- }
-
- public void run(IAction action) {
- JavadocWizard wizard= new JavadocWizard();
- IStructuredSelection selection= null;
- if (fSelection instanceof IStructuredSelection) {
- selection= (IStructuredSelection)fSelection;
- } else {
- selection= new StructuredSelection();
- }
- JavadocWizard.openJavadocWizard(wizard, fCurrentShell, selection);
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- fSelection= selection;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/IndentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/IndentAction.java
deleted file mode 100644
index a5e9bedd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/IndentAction.java
+++ /dev/null
@@ -1,570 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Tom Eicher (Avaloq Evolution AG) - block selection mode
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaIndenter;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * Indents a line or range of lines in a Java document to its correct position. No 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.wst.jsdt.internal.ui.text.JavaHeuristicScanner
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaIndenter
- *
- */
-public class IndentAction extends TextEditorAction {
-
- /** The caret offset after an indent operation. */
- private int fCaretOffset;
-
- /**
- * Whether this is the action invoked by TAB. When <code>true</code>, indentation behaves
- * differently to accommodate normal TAB operation.
- */
- private final boolean fIsTabAction;
-
- /**
- * Creates a new instance.
- *
- * @param bundle the resource bundle
- * @param prefix the prefix to use for keys in <code>bundle</code>
- * @param editor the text editor
- * @param isTabAction whether the action should insert tabs if over the indentation
- */
- public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) {
- super(bundle, prefix, editor);
- fIsTabAction= isTabAction;
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- // update has been called by the framework
- if (!isEnabled() || !validateEditorInputState())
- return;
-
- ITextSelection selection= getSelection();
- final IDocument document= getDocument();
-
- 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 {
- document.addPosition(end);
- firstLine= selection.getStartLine();
- nLines= selection.getEndLine() - firstLine + 1;
- } catch (BadLocationException e) {
- // will only happen on concurrent modification
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$
- return;
- }
-
- Runnable runnable= new Runnable() {
- public void run() {
- IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class);
- if (target != null)
- target.beginCompoundChange();
-
- try {
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- JavaIndenter indenter= new JavaIndenter(document, scanner, getJavaProject());
- 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(newOffset, newLength);
-
- document.removePosition(end);
- } catch (BadLocationException e) {
- // will only happen on concurrent modification
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
-
- } finally {
- if (target != null)
- target.endCompoundChange();
- }
- }
- };
-
- if (nLines > 50) {
- Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay();
- BusyIndicator.showWhile(display, runnable);
- } else
- runnable.run();
-
- }
- }
-
- /**
- * Selects the given range on the editor.
- *
- * @param newOffset the selection offset
- * @param newLength the selection range
- */
- private void selectAndReveal(int newOffset, int newLength) {
- Assert.isTrue(newOffset >= 0);
- Assert.isTrue(newLength >= 0);
- ITextEditor editor= getTextEditor();
- if (editor instanceof JavaEditor) {
- ISourceViewer viewer= ((JavaEditor)editor).getViewer();
- if (viewer != null)
- viewer.setSelectedRange(newOffset, newLength);
- } else
- // this is too intrusive, but will never get called anyway
- getTextEditor().selectAndReveal(newOffset, newLength);
-
- }
-
- /**
- * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are
- * indented as specified by the <code>JavaDocAutoIndentStrategy</code>.
- *
- * @param document the document
- * @param line the line to be indented
- * @param caret the caret position
- * @param indenter the java 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, JavaIndenter indenter, JavaHeuristicScanner 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, IJavaScriptPartitions.JAVA_PARTITIONING, offset, true);
- ITypedRegion startingPartition= TextUtilities.getPartition(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, false);
- String type= partition.getType();
- if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT)) {
- indent= computeJavadocIndent(document, line, scanner, startingPartition);
- } else if (!fIsTabAction && startingPartition.getOffset() == offset && startingPartition.getType().equals(IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT)) {
-
- // line comment starting at position 0 -> indent inside
- 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;
-
- StringBuffer computed= indenter.computeIndentation(offset);
- if (computed == null)
- computed= new StringBuffer(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 java indentation
- if (indent == null) {
- StringBuffer 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 == JavaHeuristicScanner.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);
-
- // if we are right before the text start / line end, and already after the insertion point
- // then just insert a tab.
- if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) {
- String tab= getTabEquivalent();
- document.replace(caret, 0, tab);
- fCaretOffset= caret + tab.length();
- return true;
- }
-
- // 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;
- } else
- return false;
- }
-
- /**
- * Computes and returns the indentation for a javadoc line. The line
- * must be inside a javadoc comment.
- *
- * @param document the document
- * @param line the line in document
- * @param scanner the scanner
- * @param partition the javadoc partition
- * @return the indent, or <code>null</code> if not computable
- * @throws BadLocationException
- *
- */
- private String computeJavadocIndent(IDocument document, int line, JavaHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
- if (line == 0) // impossible - the first line is never inside a javadoc 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 == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
- if (nonWS == JavaHeuristicScanner.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;
-
- StringBuffer buf= new StringBuffer();
- int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- if (previousLineNonWS == JavaHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
- // align with the comment start if the previous line is not an asterisked line
- previousLine= document.getLineInformationOfOffset(partition.getOffset());
- previousLineStart= previousLine.getOffset();
- previousLineLength= previousLine.getLength();
- previousLineEnd= previousLineStart + previousLineLength;
- previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- if (previousLineNonWS == JavaHeuristicScanner.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();
- }
-
- /**
- * Returns the size in characters of a string. All characters count one, tabs count the editor's
- * preference for the tab display
- *
- * @param indent the string to be measured.
- * @return the size in characters of a string
- */
- private int whiteSpaceLength(String indent) {
- if (indent == null)
- return 0;
- else {
- int size= 0;
- int l= indent.length();
- int tabSize= getTabSize();
-
- for (int i= 0; i < l; i++)
- size += indent.charAt(i) == '\t' ? tabSize : 1;
- return size;
- }
- }
-
- /**
- * Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and
- * formatter preferences.
- *
- * @return a string representing one tab in the editor, never <code>null</code>
- */
- private String getTabEquivalent() {
- String tab;
- if (JavaScriptCore.SPACE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) {
- int size= getTabSize();
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i< size; i++)
- buf.append(' ');
- tab= buf.toString();
- } else
- tab= "\t"; //$NON-NLS-1$
-
- return tab;
- }
-
- /**
- * Returns the tab size used by the java editor, which is deduced from the
- * formatter preferences.
- *
- * @return the tab size as defined in the current formatter preferences
- */
- private int getTabSize() {
- return getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4);
- }
-
- /**
- * Returns <code>true</code> if empty lines should be indented, false otherwise.
- *
- * @return <code>true</code> if empty lines should be indented, false otherwise
- *
- */
- private boolean indentEmptyLines() {
- return DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES));
- }
-
- /**
- * 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) {
- IJavaScriptProject project= getJavaProject();
- if (project == null)
- return JavaScriptCore.getOption(key);
- return project.getOption(key, true);
- }
-
- /**
- * 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>IJavaScriptProject</code> of the current editor input, or
- * <code>null</code> if it cannot be found.
- *
- * @return the <code>IJavaScriptProject</code> of the current editor input, or
- * <code>null</code> if it cannot be found
- *
- */
- private IJavaScriptProject getJavaProject() {
- ITextEditor editor= getTextEditor();
- if (editor == null)
- return null;
-
- IJavaScriptUnit cu= JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
- if (cu == null)
- return null;
- return cu.getJavaScriptProject();
- }
-
- /**
- * Returns the editor's selection provider.
- *
- * @return the editor's selection provider or <code>null</code>
- */
- private ISelectionProvider getSelectionProvider() {
- ITextEditor editor= getTextEditor();
- if (editor != null) {
- return editor.getSelectionProvider();
- }
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- super.update();
-
- if (isEnabled())
- if (fIsTabAction)
- setEnabled(canModifyEditor() && isSmartMode() && isValidSelection());
- else
- setEnabled(canModifyEditor() && !getSelection().isEmpty());
- }
-
- /**
- * Returns if the current selection is valid, i.e. whether it is empty and the caret in the
- * whitespace at the start of a line, or covers multiple lines.
- *
- * @return <code>true</code> if the selection is valid for an indent operation
- */
- private boolean isValidSelection() {
- ITextSelection selection= getSelection();
- if (selection.isEmpty())
- return false;
-
- int offset= selection.getOffset();
- int length= selection.getLength();
-
- IDocument document= getDocument();
- if (document == null)
- return false;
-
- try {
- IRegion firstLine= document.getLineInformationOfOffset(offset);
- int lineOffset= firstLine.getOffset();
-
- // either the selection has to be empty and the caret in the WS at the line start
- // or the selection has to extend over multiple lines
- if (length == 0)
- return document.get(lineOffset, offset - lineOffset).trim().length() == 0;
- else
-// return lineOffset + firstLine.getLength() < offset + length;
- return false; // only enable for empty selections for now
-
- } catch (BadLocationException e) {
- }
-
- return false;
- }
-
- /**
- * Returns the smart preference state.
- *
- * @return <code>true</code> if smart mode is on, <code>false</code> otherwise
- */
- private boolean isSmartMode() {
- ITextEditor editor= getTextEditor();
-
- if (editor instanceof ITextEditorExtension3)
- return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT;
-
- return false;
- }
-
- /**
- * 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= getTextEditor();
- 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() {
- ISelectionProvider provider= getSelectionProvider();
- if (provider != null) {
-
- ISelection selection= provider.getSelection();
- if (selection instanceof ITextSelection)
- return (ITextSelection) selection;
- }
-
- // null object
- return TextSelection.emptySelection();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/JDTQuickMenuAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/JDTQuickMenuAction.java
deleted file mode 100644
index 570c9ac6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/JDTQuickMenuAction.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-
-
-public abstract class JDTQuickMenuAction extends QuickMenuAction {
-
- private JavaEditor fEditor;
-
- public JDTQuickMenuAction(String commandId) {
- super(commandId);
- }
-
- public JDTQuickMenuAction(JavaEditor editor, String commandId) {
- super(commandId);
- fEditor= editor;
- }
-
- protected Point computeMenuLocation(StyledText text) {
- if (fEditor == null || text != fEditor.getViewer().getTextWidget())
- return null;
- return computeWordStart();
- }
-
- private Point computeWordStart() {
- ITextSelection selection= (ITextSelection)fEditor.getSelectionProvider().getSelection();
- IRegion textRegion= JavaWordFinder.findWord(fEditor.getViewer().getDocument(), selection.getOffset());
- if (textRegion == null)
- return null;
-
- IRegion widgetRegion= modelRange2WidgetRange(textRegion);
- if (widgetRegion == null)
- return null;
-
- int start= widgetRegion.getOffset();
-
- StyledText styledText= fEditor.getViewer().getTextWidget();
- Point result= styledText.getLocationAtOffset(start);
- result.y+= styledText.getLineHeight(start);
-
- if (!styledText.getClientArea().contains(result))
- return null;
- return result;
- }
-
- private IRegion modelRange2WidgetRange(IRegion region) {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5)viewer;
- return extension.modelRange2WidgetRange(region);
- }
-
- IRegion visibleRegion= viewer.getVisibleRegion();
- int start= region.getOffset() - visibleRegion.getOffset();
- int end= start + region.getLength();
- if (end > visibleRegion.getLength())
- end= visibleRegion.getLength();
-
- return new Region(start, end - start);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/LexicalSortingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/LexicalSortingAction.java
deleted file mode 100644
index 7ddd0d13..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/LexicalSortingAction.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingMessages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SourcePositionComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-
-/*
- * XXX: This class should become part of the MemberFilterActionGroup
- * which should be renamed to MemberActionsGroup
- */
-public class LexicalSortingAction extends Action {
- private JavaScriptElementComparator fComparator= new JavaScriptElementComparator();
- private SourcePositionComparator fSourcePositonComparator= new SourcePositionComparator();
- private StructuredViewer fViewer;
- private String fPreferenceKey;
-
- public LexicalSortingAction(StructuredViewer viewer, String id) {
- super();
- fViewer= viewer;
- fPreferenceKey= "LexicalSortingAction." + id + ".isChecked"; //$NON-NLS-1$ //$NON-NLS-2$
- setText(JavaBrowsingMessages.LexicalSortingAction_label);
- JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
- setToolTipText(JavaBrowsingMessages.LexicalSortingAction_tooltip);
- setDescription(JavaBrowsingMessages.LexicalSortingAction_description);
- boolean checked= JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean(fPreferenceKey);
- valueChanged(checked, false);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_BROWSING_ACTION);
- }
-
- public void run() {
- valueChanged(isChecked(), true);
- }
-
- private void valueChanged(final boolean on, boolean store) {
- setChecked(on);
- BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- if (on)
- fViewer.setComparator(fComparator);
- else
- fViewer.setComparator(fSourcePositonComparator);
- }
- });
-
- if (store)
- JavaScriptPlugin.getDefault().getPreferenceStore().setValue(fPreferenceKey, on);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiActionGroup.java
deleted file mode 100644
index dbb31db3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiActionGroup.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * A MultiActionGroup will display a list of IActions in a menu by transforming them
- * into MenuItems. The list of labels given will be what is displayed in the ViewMenu for
- * the corresponding action (the action at the same position in the action array).
- * The actions are currently implemented as state based
- * so that after an action is executed the label will have a selection check.
- *
- *
- */
-public class MultiActionGroup extends ActionGroup {
-
- public IAction[] NO_ACTIONS = new IAction[0];
-
- private IAction[] fActions;
-
- private int fCurrentSelection;
- private MenuItem[] fItems;
-
- /**
- * Creates a new action group with a given set of actions.
- *
- * @param actions the actions for this multi group
- * @param currentSelection decides which action is selected in the menu on start up.
- * Denotes the location in the actions array of the current
- * selected state. It cannot be null.
- */
- public MultiActionGroup(IAction[] actions, int currentSelection) {
- super();
- setActions(actions, currentSelection);
- }
-
- /**
- * Creates a new action group. Clients using this constructor must set the actions
- * immediately after creating the multi action group by calling {@link #setActions(IAction[], int)}.
- */
- protected MultiActionGroup() {
- super();
- }
-
- /**
- * Sets the given actions.
- *
- * @param actions the actions for this multi group, at least one
- * @param currentSelection decides which action is selected in the menu on start up.
- * Denotes the location in the actions array of the current
- * selected state. It cannot be null.
- */
- protected final void setActions(IAction[] actions, int currentSelection) {
- fCurrentSelection= currentSelection;
- fActions = actions;
- }
-
- /**
- * Adds the actions to the given menu manager.
- */
- protected void addActions(IMenuManager viewMenu) {
-
- viewMenu.add(new Separator());
- fItems= new MenuItem[fActions.length];
-
- for (int i= 0; i < fActions.length; i++) {
- final int j= i;
-
- viewMenu.add(new ContributionItem() {
-
- public void fill(Menu menu, int index) {
-
- int style= SWT.CHECK;
- if ((fActions[j].getStyle() & IAction.AS_RADIO_BUTTON) != 0)
- style= SWT.RADIO;
-
- MenuItem mi= new MenuItem(menu, style, index);
- ImageDescriptor d= fActions[j].getImageDescriptor();
- mi.setImage(JavaScriptPlugin.getImageDescriptorRegistry().get(d));
- fItems[j]= mi;
- mi.setText(fActions[j].getText());
- mi.setSelection(fCurrentSelection == j);
- mi.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- if (fCurrentSelection == j) {
- fItems[fCurrentSelection].setSelection(true);
- return;
- }
- fActions[j].run();
-
- // Update checked state
- fItems[fCurrentSelection].setSelection(false);
- fCurrentSelection= j;
- fItems[fCurrentSelection].setSelection(true);
- }
-
- });
- }
- public boolean isDynamic() {
- return false;
- }
- });
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiOrganizeImportAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiOrganizeImportAction.java
deleted file mode 100644
index 21c9cf61..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiOrganizeImportAction.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.Hashtable;
-import java.util.Map;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ImportsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class MultiOrganizeImportAction extends CleanUpAction {
-
- public MultiOrganizeImportAction(IWorkbenchSite site) {
- super(site);
-
- setText(ActionMessages.OrganizeImportsAction_label);
- setToolTipText(ActionMessages.OrganizeImportsAction_tooltip);
- setDescription(ActionMessages.OrganizeImportsAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
- }
-
- public MultiOrganizeImportAction(JavaEditor editor) {
- super(editor);
-
- setText(ActionMessages.OrganizeImportsAction_label);
- setToolTipText(ActionMessages.OrganizeImportsAction_tooltip);
- setDescription(ActionMessages.OrganizeImportsAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
- }
-
- protected ICleanUp[] createCleanUps(IJavaScriptUnit[] units) {
- Map settings= new Hashtable();
- settings.put(CleanUpConstants.ORGANIZE_IMPORTS, CleanUpConstants.TRUE);
- ImportsCleanUp importsCleanUp= new ImportsCleanUp(settings);
-
- return new ICleanUp[] {
- importsCleanUp
- };
- }
-
- protected String getActionName() {
- return ActionMessages.OrganizeImportsAction_error_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiSortMembersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiSortMembersAction.java
deleted file mode 100644
index 6ae20588..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/MultiSortMembersAction.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - Bug 133277 Allow Sort Members to be performed on package and project levels
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.Hashtable;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SortMembersMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.SortMembersCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class MultiSortMembersAction extends CleanUpAction {
-
- public MultiSortMembersAction(IWorkbenchSite site) {
- super(site);
-
- setText(ActionMessages.SortMembersAction_label);
- setDescription(ActionMessages.SortMembersAction_description);
- setToolTipText(ActionMessages.SortMembersAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION);
- }
-
- public MultiSortMembersAction(JavaEditor editor) {
- super(editor);
-
- setText(ActionMessages.SortMembersAction_label);
- setDescription(ActionMessages.SortMembersAction_description);
- setToolTipText(ActionMessages.SortMembersAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION);
- }
-
- /**
- * {@inheritDoc}
- */
- protected ICleanUp[] createCleanUps(IJavaScriptUnit[] units) {
- try {
- if (!hasMembersToSort(units))
- return null;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
-
- SortMembersMessageDialog dialog= new SortMembersMessageDialog(getShell());
- if (dialog.open() != Window.OK)
- return null;
-
- Hashtable settings= new Hashtable();
- settings.put(CleanUpConstants.SORT_MEMBERS, CleanUpConstants.TRUE);
- settings.put(CleanUpConstants.SORT_MEMBERS_ALL, !dialog.isNotSortingFieldsEnabled() ? CleanUpConstants.TRUE : CleanUpConstants.FALSE);
-
- return new ICleanUp[] {
- new SortMembersCleanUp(settings)
- };
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getActionName() {
- return ActionMessages.SortMembersAction_dialog_title;
- }
-
- private boolean hasMembersToSort(IJavaScriptUnit[] units) throws JavaScriptModelException {
- for (int i= 0; i < units.length; i++) {
- if (hasMembersToSort(units[i].getChildren()))
- return true;
- }
-
- return false;
- }
-
- private boolean hasMembersToSort(IJavaScriptElement[] members) throws JavaScriptModelException {
- if (members.length > 1)
- return true;
-
- if (members.length == 0)
- return false;
-
- IJavaScriptElement elem= members[0];
- if (!(elem instanceof IParent))
- return false;
-
- return hasMembersToSort(((IParent)elem).getChildren());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/NewWizardsActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/NewWizardsActionGroup.java
deleted file mode 100644
index 3e26a215..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/NewWizardsActionGroup.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.NewWizardMenu;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-
-/**
- * Action group that adds the 'new' menu to a context menu.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- */
-public class NewWizardsActionGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
-
- /**
- * Creates a new <code>NewWizardsActionGroup</code>. The group requires
- * that the selection provided by the part's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public NewWizardsActionGroup(IWorkbenchSite site) {
- fSite= site;
- }
-
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
-
- ISelection selection= getContext().getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection sel= (IStructuredSelection) selection;
- if (sel.size() <= 1 && isNewTarget(sel.getFirstElement())) {
- MenuManager newMenu = new MenuManager(ActionMessages.NewWizardsActionGroup_new);
- menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
- newMenu.add(new NewWizardMenu(fSite.getWorkbenchWindow()));
- }
- }
-
- }
-
- private boolean isNewTarget(Object element) {
- if (element == null)
- return true;
- if (element instanceof IResource) {
- return true;
- }
- if (element instanceof IJavaScriptElement) {
- int type= ((IJavaScriptElement)element).getElementType();
- return type == IJavaScriptElement.JAVASCRIPT_PROJECT ||
- type == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT ||
- type == IJavaScriptElement.PACKAGE_FRAGMENT ||
- type == IJavaScriptElement.JAVASCRIPT_UNIT ||
- type == IJavaScriptElement.TYPE;
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OccurrencesSearchMenuAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OccurrencesSearchMenuAction.java
deleted file mode 100644
index b4b515c3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OccurrencesSearchMenuAction.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IPartService;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2;
-import org.eclipse.ui.actions.RetargetAction;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
-
-/**
- * <p>
- * This is required because of
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=79162
- * and
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=137679
- * </p>
- */
-public class OccurrencesSearchMenuAction implements IWorkbenchWindowPulldownDelegate2 {
-
- private static Action NO_ACTION_AVAILABLE= new Action(SearchMessages.group_occurrences_quickMenu_noEntriesAvailable) {
- public boolean isEnabled() {
- return false;
- }
- };
-
- private Menu fMenu;
-
- private IPartService fPartService;
- private RetargetAction[] fRetargetActions;
-
- /**
- * {@inheritDoc}
- */
- public Menu getMenu(Menu parent) {
- setMenu(new Menu(parent));
- fillMenu(fMenu);
- return fMenu;
- }
-
- /**
- * {@inheritDoc}
- */
- public Menu getMenu(Control parent) {
- setMenu(new Menu(parent));
- fillMenu(fMenu);
- return fMenu;
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- setMenu(null);
- disposeSubmenuActions();
- }
-
- private RetargetAction createSubmenuAction(IPartService partService, String actionID, String text, String actionDefinitionId) {
- RetargetAction action= new RetargetAction(actionID, text);
- action.setActionDefinitionId(actionDefinitionId);
-
- partService.addPartListener(action);
- IWorkbenchPart activePart = partService.getActivePart();
- if (activePart != null) {
- action.partActivated(activePart);
- }
- return action;
- }
-
- private void disposeSubmenuActions() {
- if (fPartService != null && fRetargetActions != null) {
- for (int i= 0; i < fRetargetActions.length; i++) {
- fPartService.removePartListener(fRetargetActions[i]);
- fRetargetActions[i].dispose();
- }
- }
- fRetargetActions= null;
- fPartService= null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void init(IWorkbenchWindow window) {
- disposeSubmenuActions(); // paranoia code: double initialization should not happen
- if (window != null) {
- fPartService= window.getPartService();
- if (fPartService != null) {
- fRetargetActions= new RetargetAction[] {
- createSubmenuAction(fPartService, JdtActionConstants.FIND_OCCURRENCES_IN_FILE, SearchMessages.Search_FindOccurrencesInFile_shortLabel, IJavaEditorActionDefinitionIds.SEARCH_OCCURRENCES_IN_FILE),
-// createSubmenuAction(fPartService, JdtActionConstants.FIND_IMPLEMENT_OCCURRENCES, ActionMessages.FindImplementOccurrencesAction_text, IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENT_OCCURRENCES_IN_FILE),
-// createSubmenuAction(fPartService, JdtActionConstants.FIND_EXCEPTION_OCCURRENCES, ActionMessages.FindExceptionOccurrences_text, IJavaEditorActionDefinitionIds.SEARCH_EXCEPTION_OCCURRENCES_IN_FILE),
- };
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(IAction action) {
- JavaEditor editor= null;
- IWorkbenchPart activePart= JavaScriptPlugin.getActivePage().getActivePart();
- if (activePart instanceof JavaEditor)
- editor= (JavaEditor) activePart;
-
- (new JDTQuickMenuAction(editor, IJavaEditorActionDefinitionIds.SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU) {
- protected void fillMenu(IMenuManager menu) {
- fillQuickMenu(menu);
- }
- }).run();
-
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(IAction action, ISelection selection) {
- }
-
- private void fillQuickMenu(IMenuManager manager) {
- IAction[] actions= fRetargetActions;
- if (actions != null) {
- boolean hasAction= false;
- for (int i= 0; i < actions.length; i++) {
- IAction action= actions[i];
- if (action.isEnabled()) {
- hasAction= true;
- manager.add(action);
- }
- }
- if (!hasAction) {
- manager.add(NO_ACTION_AVAILABLE);
- }
- } else {
- manager.add(NO_ACTION_AVAILABLE);
- }
- }
-
- /**
- * The menu to show in the workbench menu
- */
- private void fillMenu(Menu menu) {
- if (fRetargetActions != null) {
- for (int i= 0; i < fRetargetActions.length; i++) {
- ActionContributionItem item= new ActionContributionItem(fRetargetActions[i]);
- item.fill(menu, -1);
- }
- } else {
- // can only happen if 'init' was not called: programming error
- ActionContributionItem item= new ActionContributionItem(NO_ACTION_AVAILABLE);
- item.fill(menu, -1);
- }
- }
-
- private void setMenu(Menu menu) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- fMenu = menu;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenBrowserUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenBrowserUtil.java
deleted file mode 100644
index 4c34e5b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenBrowserUtil.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.net.URL;
-
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-public class OpenBrowserUtil {
-
- public static void open(final URL url, Display display, final String dialogTitle) {
- display.syncExec(new Runnable() {
- public void run() {
- internalOpen(url, dialogTitle);
- }
- });
- }
-
- private static void internalOpen(final URL url, String title) {
- BusyIndicator.showWhile(null, new Runnable() {
- public void run() {
- PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(url.toExternalForm() + "?noframes=true"); //$NON-NLS-1$
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeAction.java
deleted file mode 100644
index 80437a76..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeAction.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionDelegate2;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OpenTypeSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class OpenTypeAction extends Action implements IWorkbenchWindowActionDelegate, IActionDelegate2 {
-
- public OpenTypeAction() {
- super();
- setText(JavaUIMessages.OpenTypeAction_label);
- setDescription(JavaUIMessages.OpenTypeAction_description);
- setToolTipText(JavaUIMessages.OpenTypeAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_TOOL_OPENTYPE);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_TYPE_ACTION);
- }
-
- public void run() {
- runWithEvent(null);
- }
-
- public void runWithEvent(Event e) {
- Shell parent= JavaScriptPlugin.getActiveWorkbenchShell();
- SelectionDialog dialog;
- if (e != null && e.stateMask == SWT.MOD1) {
- // use old open type dialog when MOD1 (but no other modifier) is down:
- dialog= createOpenTypeSelectionDialog2(parent);
- } else {
- dialog= new OpenTypeSelectionDialog(parent, true, PlatformUI.getWorkbench().getProgressService(), null, IJavaScriptSearchConstants.TYPE);
- }
- dialog.setTitle(JavaUIMessages.OpenTypeAction_dialogTitle);
- dialog.setMessage(JavaUIMessages.OpenTypeAction_dialogMessage);
-
- int result= dialog.open();
- if (result != IDialogConstants.OK_ID)
- return;
-
- Object[] types= dialog.getResult();
- if (types != null && types.length > 0) {
- IType type= null;
- for (int i= 0; i < types.length; i++) {
- type= (IType) types[i];
- try {
- JavaScriptUI.openInEditor(type, true, true);
- } catch (CoreException x) {
- ExceptionHandler.handle(x, JavaUIMessages.OpenTypeAction_errorTitle, JavaUIMessages.OpenTypeAction_errorMessage);
- }
- }
- }
- }
-
- /**
- * @deprecated
- * @param parent
- * @return the dialog
- */
- private SelectionDialog createOpenTypeSelectionDialog2(Shell parent) {
- return new org.eclipse.wst.jsdt.internal.ui.dialogs.OpenTypeSelectionDialog2(parent, false, PlatformUI.getWorkbench().getProgressService(), null, IJavaScriptSearchConstants.TYPE);
- }
-
- // ---- IWorkbenchWindowActionDelegate
- // ------------------------------------------------
-
- public void run(IAction action) {
- run();
- }
-
- public void dispose() {
- // do nothing.
- }
-
- public void init(IWorkbenchWindow window) {
- // do nothing.
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- // do nothing. Action doesn't depend on selection.
- }
-
- // ---- IActionDelegate2
- // ------------------------------------------------
-
- public void runWithEvent(IAction action, Event event) {
- runWithEvent(event);
- }
-
- public void init(IAction action) {
- // do nothing.
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeInHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeInHierarchyAction.java
deleted file mode 100644
index f2f1485f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/OpenTypeInHierarchyAction.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OpenTypeSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.util.OpenTypeHierarchyUtil;
-
-public class OpenTypeInHierarchyAction extends Action implements IWorkbenchWindowActionDelegate {
-
- private IWorkbenchWindow fWindow;
-
- public OpenTypeInHierarchyAction() {
- super();
- setText(ActionMessages.OpenTypeInHierarchyAction_label);
- setDescription(ActionMessages.OpenTypeInHierarchyAction_description);
- setToolTipText(ActionMessages.OpenTypeInHierarchyAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_TYPE_IN_HIERARCHY_ACTION);
- }
-
- public void run() {
- Shell parent= JavaScriptPlugin.getActiveWorkbenchShell();
- OpenTypeSelectionDialog dialog= new OpenTypeSelectionDialog(parent, false,
- PlatformUI.getWorkbench().getProgressService(),
- SearchEngine.createWorkspaceScope(), IJavaScriptSearchConstants.TYPE);
-
- dialog.setTitle(ActionMessages.OpenTypeInHierarchyAction_dialogTitle);
- dialog.setMessage(ActionMessages.OpenTypeInHierarchyAction_dialogMessage);
- int result= dialog.open();
- if (result != IDialogConstants.OK_ID)
- return;
-
- Object[] types= dialog.getResult();
- if (types != null && types.length > 0) {
- IType type= (IType)types[0];
- OpenTypeHierarchyUtil.open(new IType[] { type }, fWindow);
- }
- }
-
- //---- IWorkbenchWindowActionDelegate ------------------------------------------------
-
- public void run(IAction action) {
- run();
- }
-
- public void dispose() {
- fWindow= null;
- }
-
- public void init(IWorkbenchWindow window) {
- fWindow= window;
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- // do nothing. Action doesn't depend on selection.
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java
deleted file mode 100644
index c21fe3bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.keys.IBindingService;
-
-/**
- * A quick menu actions provides support to assign short cuts
- * to sub menus.
- *
- *
- */
-public abstract class QuickMenuAction extends Action {
-
- private static final int CHAR_INDENT= 3;
-
- /**
- * Creates a new quick menu action with the given command id.
- *
- * @param commandId the command id of the short cut used to open
- * the sub menu
- */
- public QuickMenuAction(String commandId) {
- setActionDefinitionId(commandId);
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- Display display= Display.getCurrent();
- if (display == null)
- return;
- Control focus= display.getFocusControl();
- if (focus == null || focus.isDisposed())
- return;
-
- MenuManager menu= new MenuManager();
- fillMenu(menu);
- final Menu widget= menu.createContextMenu(focus.getShell());
- Point location= computeMenuLocation(focus, widget);
- if (location == null)
- return;
- widget.setLocation(location);
- widget.setVisible(true);
- while (!widget.isDisposed() && widget.isVisible()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- if (!widget.isDisposed()) {
- widget.dispose();
- }
- }
-
- /**
- * Hook to fill a menu manager with the items of the sub menu.
- *
- * @param menu the sub menu to fill
- */
- protected abstract void fillMenu(IMenuManager menu);
-
- /**
- * Adds the shortcut to the given menu text and returns it.
- *
- * @param menuText the menu text
- * @return the menu text with the shortcut
- *
- */
- public String addShortcut(String menuText) {
- String shortcut= getShortcutString();
- if (menuText == null || shortcut == null)
- return menuText;
-
- return menuText + '\t' + shortcut;
- }
-
- /**
- * Returns the shortcut assigned to the sub menu or <code>null</code> if
- * no short cut is assigned.
- *
- * @return the shortcut as a human readable string or <code>null</code>
- */
- private String getShortcutString() {
- IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService == null)
- return null;
- return bindingService.getBestActiveBindingFormattedFor(getActionDefinitionId());
- }
-
- private Point computeMenuLocation(Control focus, Menu menu) {
- Point cursorLocation= focus.getDisplay().getCursorLocation();
- Rectangle clientArea= null;
- Point result= null;
- if (focus instanceof StyledText) {
- StyledText styledText= (StyledText)focus;
- clientArea= styledText.getClientArea();
- result= computeMenuLocation(styledText);
- } else if (focus instanceof Tree) {
- Tree tree= (Tree)focus;
- clientArea= tree.getClientArea();
- result= computeMenuLocation(tree);
- } else if (focus instanceof Table) {
- Table table= (Table)focus;
- clientArea= table.getClientArea();
- result= computeMenuLocation(table);
- }
- if (result == null) {
- result= focus.toControl(cursorLocation);
- }
- if (clientArea != null && !clientArea.contains(result)) {
- result= new Point(
- clientArea.x + clientArea.width / 2,
- clientArea.y + clientArea.height / 2);
- }
- Rectangle shellArea= focus.getShell().getClientArea();
- if (!shellArea.contains(focus.getShell().toControl(focus.toDisplay(result)))) {
- result= new Point(
- shellArea.x + shellArea.width / 2,
- shellArea.y + shellArea.height / 2);
- }
- return focus.toDisplay(result);
- }
-
- /**
- * Hook to compute the menu location if the focus widget is
- * a styled text widget.
- *
- * @param text the styled text widget that has the focus
- *
- * @return a widget relative position of the menu to pop up or
- * <code>null</code> if now position inside the widget can
- * be computed
- */
- protected Point computeMenuLocation(StyledText text) {
- int offset= text.getCaretOffset();
- Point result= text.getLocationAtOffset(offset);
- result.y+= text.getLineHeight(offset);
- if (!text.getClientArea().contains(result))
- return null;
- return result;
- }
-
- /**
- * Hook to compute the menu location if the focus widget is
- * a tree widget.
- *
- * @param tree the tree widget that has the focus
- *
- * @return a widget relative position of the menu to pop up or
- * <code>null</code> if now position inside the widget can
- * be computed
- */
- protected Point computeMenuLocation(Tree tree) {
- TreeItem[] items= tree.getSelection();
- Rectangle clientArea= tree.getClientArea();
- switch (items.length) {
- case 0:
- return null;
- case 1:
- Rectangle bounds= items[0].getBounds();
- Rectangle intersect= clientArea.intersection(bounds);
- if (intersect != null && intersect.height == bounds.height) {
- return new Point(
- Math.max(0, bounds.x + getAvarageCharWith(tree) * CHAR_INDENT),
- bounds.y + bounds.height);
- } else {
- return null;
- }
- default:
- Rectangle[] rectangles= new Rectangle[items.length];
- for (int i= 0; i < rectangles.length; i++) {
- rectangles[i]= items[i].getBounds();
- }
- Point cursorLocation= tree.getDisplay().getCursorLocation();
- Point result= findBestLocation(getIncludedPositions(rectangles, clientArea),
- tree.toControl(cursorLocation));
- if (result != null)
- result.x= result.x + getAvarageCharWith(tree) * CHAR_INDENT;
- return result;
- }
- }
-
- /**
- * Hook to compute the menu location if the focus widget is
- * a table widget.
- *
- * @param table the table widget that has the focus
- *
- * @return a widget relative position of the menu to pop up or
- * <code>null</code> if now position inside the widget can
- * be computed
- */
- protected Point computeMenuLocation(Table table) {
- TableItem[] items= table.getSelection();
- Rectangle clientArea= table.getClientArea();
- switch (items.length) {
- case 0: {
- return null;
- } case 1: {
- Rectangle bounds= items[0].getBounds(0);
- Rectangle iBounds= items[0].getImageBounds(0);
- Rectangle intersect= clientArea.intersection(bounds);
- if (intersect != null && intersect.height == bounds.height) {
- return new Point(
- Math.max(0, bounds.x + iBounds.width + getAvarageCharWith(table) * CHAR_INDENT),
- bounds.y + bounds.height);
- } else {
- return null;
- }
- } default: {
- Rectangle[] rectangles= new Rectangle[items.length];
- for (int i= 0; i < rectangles.length; i++) {
- rectangles[i]= items[i].getBounds(0);
- }
- Rectangle iBounds= items[0].getImageBounds(0);
- Point cursorLocation= table.getDisplay().getCursorLocation();
- Point result= findBestLocation(getIncludedPositions(rectangles, clientArea),
- table.toControl(cursorLocation));
- if (result != null)
- result.x= result.x + iBounds.width + getAvarageCharWith(table) * CHAR_INDENT;
- return result;
- }
- }
- }
-
- private Point[] getIncludedPositions(Rectangle[] rectangles, Rectangle widgetBounds) {
- List result= new ArrayList();
- for (int i= 0; i < rectangles.length; i++) {
- Rectangle rectangle= rectangles[i];
- Rectangle intersect= widgetBounds.intersection(rectangle);
- if (intersect != null && intersect.height == rectangle.height) {
- result.add(new Point(intersect.x, intersect.y + intersect.height));
- }
- }
- return (Point[]) result.toArray(new Point[result.size()]);
- }
-
- private Point findBestLocation(Point[] points, Point relativeCursor) {
- Point result= null;
- double bestDist= Double.MAX_VALUE;
- for (int i= 0; i < points.length; i++) {
- Point point= points[i];
- int a= 0;
- int b= 0;
- if (point.x > relativeCursor.x) {
- a= point.x - relativeCursor.x;
- } else {
- a= relativeCursor.x - point.x;
- }
- if (point.y > relativeCursor.y) {
- b= point.y - relativeCursor.y;
- } else {
- b= relativeCursor.y - point.y;
- }
- double dist= Math.sqrt(a * a + b * b);
- if (dist < bestDist) {
- result= point;
- bestDist= dist;
- }
- }
- return result;
- }
-
- private int getAvarageCharWith(Control control) {
- GC gc= null;
- try {
- gc= new GC(control);
- return gc.getFontMetrics().getAverageCharWidth();
- } finally {
- if (gc != null)
- gc.dispose();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/RemoveBlockCommentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/RemoveBlockCommentAction.java
deleted file mode 100644
index 0cdddeed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/RemoveBlockCommentAction.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPartitioningException;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * Action that removes the enclosing comment marks from a Java block comment.
- *
- *
- */
-public class RemoveBlockCommentAction extends BlockCommentAction {
-
- /**
- * Creates a new instance.
- *
- * @param bundle the resource bundle
- * @param prefix a prefix to be prepended to the various resource keys
- * (described in <code>ResourceAction</code> constructor), or
- * <code>null</code> if none
- * @param editor the text editor
- */
- public RemoveBlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
- super(bundle, prefix, editor);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.actions.AddBlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, org.eclipse.jface.text.IDocumentExtension3, org.eclipse.wst.jsdt.internal.ui.actions.AddBlockCommentAction.Edit.EditFactory)
- */
- protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadPartitioningException, BadLocationException {
- List edits= new LinkedList();
- int tokenLength= getCommentStart().length();
-
- int offset= selection.getOffset();
- int endOffset= offset + selection.getLength();
-
- ITypedRegion partition= docExtension.getPartition(IJavaScriptPartitions.JAVA_PARTITIONING, offset, false);
- int partOffset= partition.getOffset();
- int partEndOffset= partOffset + partition.getLength();
-
- while (partEndOffset < endOffset) {
-
- if (partition.getType() == IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT) {
- edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$
- edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$
- }
-
- partition= docExtension.getPartition(IJavaScriptPartitions.JAVA_PARTITIONING, partEndOffset, false);
- partOffset= partition.getOffset();
- partEndOffset= partOffset + partition.getLength();
- }
-
- if (partition.getType() == IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT) {
- edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$
- edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$
- }
-
- executeEdits(edits);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.actions.AddBlockCommentAction#validSelection(org.eclipse.jface.text.ITextSelection)
- */
- protected boolean isValidSelection(ITextSelection selection) {
- return selection != null && !selection.isEmpty();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectAllAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectAllAction.java
deleted file mode 100644
index 77bdfa35..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectAllAction.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-/**
- * This action selects all entries currently showing in view.
- */
-public class SelectAllAction extends Action {
-
- private StructuredViewer fViewer;
-
- /**
- * Creates the action for a TreeViewer
- */
- public SelectAllAction(TreeViewer viewer) {
- this((StructuredViewer) viewer);
- }
-
- /**
- * Creates the action for a TableViewer
- */
- public SelectAllAction(TableViewer viewer) {
- this((StructuredViewer) viewer);
- }
-
- private SelectAllAction(StructuredViewer viewer) {
- super("selectAll"); //$NON-NLS-1$
- setText(ActionMessages.SelectAllAction_label);
- setToolTipText(ActionMessages.SelectAllAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SELECT_ALL_ACTION);
- Assert.isNotNull(viewer);
- fViewer= viewer;
- }
-
- private void collectExpandedAndVisible(TreeItem[] items, List result) {
- for (int i= 0; i < items.length; i++) {
- TreeItem item= items[i];
- if (item.getData() != null) {
- result.add(item);
- if (item.getExpanded()) {
- collectExpandedAndVisible(item.getItems(), result);
- }
- }
- }
- }
-
- /**
- * Selects all resources in the view.
- */
- public void run() {
- if (fViewer instanceof TreeViewer) {
- ArrayList allVisible= new ArrayList();
- Tree tree= ((TreeViewer) fViewer).getTree();
- collectExpandedAndVisible(tree.getItems(), allVisible);
- tree.setSelection((TreeItem[]) allVisible.toArray(new TreeItem[allVisible.size()]));
- fViewer.setSelection(fViewer.getSelection());
- } else if (fViewer instanceof TableViewer) {
- ((TableViewer) fViewer).getTable().selectAll();
- // force viewer selection change
- fViewer.setSelection(fViewer.getSelection());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java
deleted file mode 100644
index 96342955..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.ICodeAssist;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class SelectionConverter {
-
- private static final IJavaScriptElement[] EMPTY_RESULT= new IJavaScriptElement[0];
-
- private SelectionConverter() {
- // no instance
- }
-
- /**
- * Converts the selection provided by the given part into a structured selection.
- * The following conversion rules are used:
- * <ul>
- * <li><code>part instanceof JavaEditor</code>: returns a structured selection
- * using code resolve to convert the editor's text selection.</li>
- * <li><code>part instanceof IWorkbenchPart</code>: returns the part's selection
- * if it is a structured selection.</li>
- * <li><code>default</code>: returns an empty structured selection.</li>
- * </ul>
- */
- public static IStructuredSelection getStructuredSelection(IWorkbenchPart part) throws JavaScriptModelException {
- if (part instanceof JavaEditor)
- return new StructuredSelection(codeResolve((JavaEditor)part));
- ISelectionProvider provider= part.getSite().getSelectionProvider();
- if (provider != null) {
- ISelection selection= provider.getSelection();
- if (selection instanceof IStructuredSelection)
- return (IStructuredSelection)selection;
- }
- return StructuredSelection.EMPTY;
- }
-
-
- /**
- * Converts the given structured selection into an array of Java elements.
- * An empty array is returned if one of the elements stored in the structured
- * selection is not of type <code>IJavaScriptElement</code>
- */
- public static IJavaScriptElement[] getElements(IStructuredSelection selection) {
- if (!selection.isEmpty()) {
- IJavaScriptElement[] result= new IJavaScriptElement[selection.size()];
- int i= 0;
- for (Iterator iter= selection.iterator(); iter.hasNext(); i++) {
- Object element= iter.next();
- if (!(element instanceof IJavaScriptElement))
- return EMPTY_RESULT;
- result[i]= (IJavaScriptElement)element;
- }
- return result;
- }
- return EMPTY_RESULT;
- }
-
- public static boolean canOperateOn(JavaEditor editor) {
- if (editor == null)
- return false;
- return getInput(editor) != null;
-
- }
-
- public static IJavaScriptElement[] codeResolveOrInputForked(JavaEditor editor) throws InvocationTargetException, InterruptedException {
- IJavaScriptElement input= getInput(editor);
- ITextSelection selection= (ITextSelection)editor.getSelectionProvider().getSelection();
- IJavaScriptElement[] result= performForkedCodeResolve(input, selection);
- if (result.length == 0) {
- result= new IJavaScriptElement[] {input};
- }
- return result;
- }
-
- public static IJavaScriptElement[] codeResolve(JavaEditor editor) throws JavaScriptModelException {
- return codeResolve(editor, true);
- }
-
- /**
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- *
- */
- public static IJavaScriptElement[] codeResolve(JavaEditor editor, boolean primaryOnly) throws JavaScriptModelException {
- return codeResolve(getInput(editor, primaryOnly), (ITextSelection)editor.getSelectionProvider().getSelection());
- }
-
- /**
- * Perform a code resolve in a separate thread.
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- * @throws InterruptedException
- * @throws InvocationTargetException
- *
- */
- public static IJavaScriptElement[] codeResolveForked(JavaEditor editor, boolean primaryOnly) throws InvocationTargetException, InterruptedException {
- return performForkedCodeResolve(getInput(editor, primaryOnly), (ITextSelection)editor.getSelectionProvider().getSelection());
- }
-
- public static IJavaScriptElement getElementAtOffset(JavaEditor editor) throws JavaScriptModelException {
- return getElementAtOffset(editor, true);
- }
-
- /**
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- *
- */
- private static IJavaScriptElement getElementAtOffset(JavaEditor editor, boolean primaryOnly) throws JavaScriptModelException {
- return getElementAtOffset(getInput(editor, primaryOnly), (ITextSelection)editor.getSelectionProvider().getSelection());
- }
-
- public static IType getTypeAtOffset(JavaEditor editor) throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(editor);
- IType type= (IType)element.getAncestor(IJavaScriptElement.TYPE);
- if (type == null) {
- IJavaScriptUnit unit= SelectionConverter.getInputAsCompilationUnit(editor);
- if (unit != null)
- type= unit.findPrimaryType();
- }
- return type;
- }
-
- public static IJavaScriptElement getInput(JavaEditor editor) {
- return getInput(editor, true);
- }
-
- /**
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- *
- */
- private static IJavaScriptElement getInput(JavaEditor editor, boolean primaryOnly) {
- if (editor == null)
- return null;
- return EditorUtility.getEditorInputJavaElement(editor, primaryOnly);
- }
-
- public static ITypeRoot getInputAsTypeRoot(JavaEditor editor) {
- Object editorInput= SelectionConverter.getInput(editor);
- if (editorInput instanceof ITypeRoot)
- return (ITypeRoot)editorInput;
- return null;
- }
-
- public static IJavaScriptUnit getInputAsCompilationUnit(JavaEditor editor) {
- Object editorInput= SelectionConverter.getInput(editor);
- if (editorInput instanceof IJavaScriptUnit)
- return (IJavaScriptUnit)editorInput;
- return null;
- }
-
- public static IClassFile getInputAsClassFile(JavaEditor editor) {
- Object editorInput= SelectionConverter.getInput(editor);
- if (editorInput instanceof IClassFile)
- return (IClassFile)editorInput;
- return null;
- }
-
- private static IJavaScriptElement[] performForkedCodeResolve(final IJavaScriptElement input, final ITextSelection selection) throws InvocationTargetException, InterruptedException {
- final class CodeResolveRunnable implements IRunnableWithProgress {
- IJavaScriptElement[] result;
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- result= codeResolve(input, selection);
- } catch (JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- }
- }
- }
- CodeResolveRunnable runnable= new CodeResolveRunnable();
- PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
- return runnable.result;
- }
-
- public static IJavaScriptElement[] codeResolve(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
- if (input instanceof ICodeAssist) {
- if (input instanceof IJavaScriptUnit) {
- JavaModelUtil.reconcile((IJavaScriptUnit) input);
- }
- IJavaScriptElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset() + selection.getLength(), 0);
- if (elements.length > 0) {
- return elements;
- }
- }
- return EMPTY_RESULT;
- }
-
- public static IJavaScriptElement getElementAtOffset(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
- if (input instanceof IJavaScriptUnit) {
- IJavaScriptUnit cunit= (IJavaScriptUnit) input;
- JavaModelUtil.reconcile(cunit);
- IJavaScriptElement ref= cunit.getElementAt(selection.getOffset());
- if (ref == null)
- return input;
- else
- return ref;
- } else if (input instanceof IClassFile) {
- IJavaScriptElement ref= ((IClassFile)input).getElementAt(selection.getOffset());
- if (ref == null)
- return input;
- else
- return ref;
- }
- return null;
- }
-
-// public static IJavaScriptElement[] resolveSelectedElements(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
-// IJavaScriptElement enclosing= resolveEnclosingElement(input, selection);
-// if (enclosing == null)
-// return EMPTY_RESULT;
-// if (!(enclosing instanceof ISourceReference))
-// return EMPTY_RESULT;
-// ISourceRange sr= ((ISourceReference)enclosing).getSourceRange();
-// if (selection.getOffset() == sr.getOffset() && selection.getLength() == sr.getLength())
-// return new IJavaScriptElement[] {enclosing};
-// }
-
- public static IJavaScriptElement resolveEnclosingElement(JavaEditor editor, ITextSelection selection) throws JavaScriptModelException {
- return resolveEnclosingElement(getInput(editor), selection);
- }
-
- public static IJavaScriptElement resolveEnclosingElement(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement atOffset= null;
- if (input instanceof IJavaScriptUnit) {
- IJavaScriptUnit cunit= (IJavaScriptUnit)input;
- JavaModelUtil.reconcile(cunit);
- atOffset= cunit.getElementAt(selection.getOffset());
- } else if (input instanceof IClassFile) {
- IClassFile cfile= (IClassFile)input;
- atOffset= cfile.getElementAt(selection.getOffset());
- } else {
- return null;
- }
- if (atOffset == null) {
- return input;
- } else {
- int selectionEnd= selection.getOffset() + selection.getLength();
- IJavaScriptElement result= atOffset;
- if (atOffset instanceof ISourceReference) {
- ISourceRange range= ((ISourceReference)atOffset).getSourceRange();
- while (range.getOffset() + range.getLength() < selectionEnd) {
- result= result.getParent();
- if (! (result instanceof ISourceReference)) {
- result= input;
- break;
- }
- range= ((ISourceReference)result).getSourceRange();
- }
- }
- return result;
- }
- }
-
- /**
- * Shows a dialog for resolving an ambiguous java element.
- * Utility method that can be called by subclasses.
- */
- public static IJavaScriptElement selectJavaElement(IJavaScriptElement[] elements, Shell shell, String title, String message) {
- int nResults= elements.length;
- if (nResults == 0)
- return null;
- if (nResults == 1)
- return elements[0];
-
- int flags= JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_QUALIFIED | JavaScriptElementLabelProvider.SHOW_ROOT;
-
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaScriptElementLabelProvider(flags));
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.setElements(elements);
-
- if (dialog.open() == Window.OK) {
- return (IJavaScriptElement) dialog.getFirstResult();
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithActionGroup.java
deleted file mode 100644
index 4ae8d0f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithActionGroup.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-
-public class SurroundWithActionGroup extends ActionGroup {
-
- private CompilationUnitEditor fEditor;
-// private SurroundWithTryCatchAction fSurroundWithTryCatchAction;
- private final String fGroup;
-
- public SurroundWithActionGroup(CompilationUnitEditor editor, String group) {
- fEditor= editor;
- fGroup= group;
-// fSurroundWithTryCatchAction= createSurroundWithTryCatchAction(fEditor);
- }
-
- public void fillActionBars(IActionBars actionBar) {
-// actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatchAction);
- }
-
- /**
- * The Menu to show when right click on the editor
- * {@inheritDoc}
- */
- public void fillContextMenu(IMenuManager menu) {
- ISelectionProvider selectionProvider= fEditor.getSelectionProvider();
- if (selectionProvider == null)
- return;
-
- ISelection selection= selectionProvider.getSelection();
- if (!(selection instanceof ITextSelection))
- return;
-
- ITextSelection textSelection= (ITextSelection)selection;
- if (textSelection.getLength() == 0)
- return;
-
- String menuText= ActionMessages.SurroundWithTemplateMenuAction_SurroundWithTemplateSubMenuName;
-
- String shortcutString= getShortcutString();
- if (shortcutString != null) {
- menuText= menuText + '\t' + shortcutString;
- }
-
- MenuManager subMenu = new MenuManager(menuText, SurroundWithTemplateMenuAction.SURROUND_WITH_QUICK_MENU_ACTION_ID);
- menu.appendToGroup(fGroup, subMenu);
- subMenu.add(new Action() {});
- subMenu.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- manager.removeAll();
- SurroundWithTemplateMenuAction.fillMenu(manager, fEditor);
- }
- });
- }
-
- private String getShortcutString() {
- IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService == null)
- return null;
- return bindingService.getBestActiveBindingFormattedFor(SurroundWithTemplateMenuAction.SURROUND_WITH_QUICK_MENU_ACTION_ID);
- }
-
-// private static SurroundWithTryCatchAction createSurroundWithTryCatchAction(CompilationUnitEditor editor) {
-// SurroundWithTryCatchAction result= new SurroundWithTryCatchAction(editor);
-// result.setText(ActionMessages.SurroundWithTemplateMenuAction_SurroundWithTryCatchActionName);
-// result.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH);
-// editor.setAction("SurroundWithTryCatch", result); //$NON-NLS-1$
-// return result;
-// }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithTemplateMenuAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithTemplateMenuAction.java
deleted file mode 100644
index 809ebc0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SurroundWithTemplateMenuAction.java
+++ /dev/null
@@ -1,412 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IEditingSupport;
-import org.eclipse.jface.text.IEditingSupportRegistry;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IPartService;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.AssistContext;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.QuickTemplateProcessor;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.ui.actions.SurroundWithTryCatchAction;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-public class SurroundWithTemplateMenuAction implements IWorkbenchWindowPulldownDelegate2 {
-
- //TODO make api
- public static final String SURROUND_WITH_QUICK_MENU_ACTION_ID= "org.eclipse.wst.jsdt.ui.edit.text.java.surround.with.quickMenu"; //$NON-NLS-1$
-
- private static final String JAVA_TEMPLATE_PREFERENCE_PAGE_ID= "org.eclipse.wst.jsdt.ui.preferences.JavaTemplatePreferencePage"; //$NON-NLS-1$
-
- private static final String TEMPLATE_GROUP= "templateGroup"; //$NON-NLS-1$
-
- private static final String CONFIG_GROUP= "configGroup"; //$NON-NLS-1$
-
- private static class ConfigureTemplatesAction extends Action {
-
- public ConfigureTemplatesAction() {
- super(ActionMessages.SurroundWithTemplateMenuAction_ConfigureTemplatesActionName);
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- PreferencesUtil.createPreferenceDialogOn(getShell(), JAVA_TEMPLATE_PREFERENCE_PAGE_ID, new String[] {JAVA_TEMPLATE_PREFERENCE_PAGE_ID}, null).open();
- }
-
- private Shell getShell() {
- return JavaScriptPlugin.getActiveWorkbenchWindow().getShell();
- }
- }
-
- private static Action NONE_APPLICABLE_ACTION= new Action(ActionMessages.SurroundWithTemplateMenuAction_NoneApplicable) {
- public void run() {
- //Do nothing
- }
- public boolean isEnabled() {
- return false;
- }
- };
-
- private Menu fMenu;
- private IPartService fPartService;
- private IPartListener fPartListener= new IPartListener() {
-
- public void partActivated(IWorkbenchPart part) {
- }
-
- public void partBroughtToTop(IWorkbenchPart part) {
- }
-
- public void partClosed(IWorkbenchPart part) {
- }
-
- public void partDeactivated(IWorkbenchPart part) {
- disposeMenuItems();
- }
-
- public void partOpened(IWorkbenchPart part) {
- }
-
- };
-
- protected void disposeMenuItems() {
- if (fMenu == null || fMenu.isDisposed()) {
- return;
- }
- MenuItem[] items = fMenu.getItems();
- for (int i=0; i < items.length; i++) {
- MenuItem menuItem= items[i];
- if (!menuItem.isDisposed()) {
- menuItem.dispose();
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Menu getMenu(Menu parent) {
- setMenu(new Menu(parent));
- fillMenu(fMenu);
- initMenu();
- return fMenu;
- }
-
- /**
- * {@inheritDoc}
- */
- public Menu getMenu(Control parent) {
- setMenu(new Menu(parent));
- fillMenu(fMenu);
- initMenu();
- return fMenu;
- }
-
- public static void fillMenu(IMenuManager menu, CompilationUnitEditor editor) {
- IAction[] actions= getTemplateActions(editor);
-// surroundWithTryCatchAction.update(editor.getSelectionProvider().getSelection());
-
- if (actions == null /* && !surroundWithTryCatchAction.isEnabled()*/) {
- menu.add(NONE_APPLICABLE_ACTION);
- } else {
-// menu.add(surroundWithTryCatchAction);
- menu.add(new Separator(TEMPLATE_GROUP));
-
- if (actions == null) {
- menu.add(NONE_APPLICABLE_ACTION);
- } else {
- for (int i= 0; i < actions.length; i++) {
- menu.add(actions[i]);
- }
- }
- }
-
- menu.add(new Separator(CONFIG_GROUP));
- menu.add(new ConfigureTemplatesAction());
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- if (fPartService != null) {
- fPartService.removePartListener(fPartListener);
- fPartService= null;
- }
- setMenu(null);
- }
-
- /**
- * {@inheritDoc}
- */
- public void init(IWorkbenchWindow window) {
- if (fPartService != null) {
- fPartService.removePartListener(fPartListener);
- fPartService= null;
- }
-
- if (window != null) {
- IPartService partService= window.getPartService();
- if (partService != null) {
- fPartService= partService;
- partService.addPartListener(fPartListener);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(IAction action) {
- IWorkbenchPart activePart= JavaScriptPlugin.getActivePage().getActivePart();
- if (!(activePart instanceof CompilationUnitEditor))
- return;
-
- final CompilationUnitEditor editor= (CompilationUnitEditor)activePart;
-
- (new JDTQuickMenuAction(editor, SURROUND_WITH_QUICK_MENU_ACTION_ID) {
- protected void fillMenu(IMenuManager menu) {
-// SurroundWithTryCatchAction surroundWithTryCatch= createSurroundWithTryCatchAction(editor);
- SurroundWithTemplateMenuAction.fillMenu(menu, editor);
- }
- }).run();
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(IAction action, ISelection selection) {
- // Default do nothing
- }
-
- /**
- * The menu to show in the workbench menu
- */
- protected void fillMenu(Menu menu) {
-
- IWorkbenchPart activePart= JavaScriptPlugin.getActivePage().getActivePart();
- if (!(activePart instanceof CompilationUnitEditor)) {
- ActionContributionItem item= new ActionContributionItem(NONE_APPLICABLE_ACTION);
- item.fill(menu, -1);
- return;
- }
-
- CompilationUnitEditor editor= (CompilationUnitEditor)activePart;
-
- IAction[] actions= getTemplateActions(editor);
-
- SurroundWithTryCatchAction surroundAction= createSurroundWithTryCatchAction(editor);
- ActionContributionItem surroundItem= new ActionContributionItem(surroundAction);
- surroundItem.fill(menu, -1);
-
- Separator templateGroup= new Separator(TEMPLATE_GROUP);
- templateGroup.fill(menu, -1);
-
- if (actions == null || actions.length == 0) {
- ActionContributionItem item= new ActionContributionItem(NONE_APPLICABLE_ACTION);
- item.fill(menu, -1);
- } else {
- for (int i= 0; i < actions.length; i++) {
- ActionContributionItem item= new ActionContributionItem(actions[i]);
- item.fill(menu, -1);
- }
- }
-
- Separator configGroup= new Separator(CONFIG_GROUP);
- configGroup.fill(menu, -1);
-
- ActionContributionItem configAction= new ActionContributionItem(new ConfigureTemplatesAction());
- configAction.fill(menu, -1);
-
- }
-
- private static SurroundWithTryCatchAction createSurroundWithTryCatchAction(CompilationUnitEditor editor) {
- SurroundWithTryCatchAction result= new SurroundWithTryCatchAction(editor);
- result.setText(ActionMessages.SurroundWithTemplateMenuAction_SurroundWithTryCatchActionName);
- result.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH);
- editor.setAction("SurroundWithTryCatch", result); //$NON-NLS-1$
- return result;
- }
-
- protected void initMenu() {
- fMenu.addMenuListener(new MenuAdapter() {
- public void menuShown(MenuEvent e) {
- Menu m = (Menu)e.widget;
- MenuItem[] items = m.getItems();
- for (int i=0; i < items.length; i++) {
- items[i].dispose();
- }
- fillMenu(m);
- }
- });
- }
-
- private void setMenu(Menu menu) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- fMenu = menu;
- }
-
- private static IAction[] getTemplateActions(JavaEditor editor) {
- ISelectionProvider selectionProvider= editor.getSelectionProvider();
- if (selectionProvider == null)
- return null;
-
- ISelection selection= selectionProvider.getSelection();
- if (!(selection instanceof ITextSelection))
- return null;
-
- ITextSelection textSelection= (ITextSelection)selection;
- if (textSelection.getLength() == 0)
- return null;
-
- IJavaScriptUnit cu= JavaScriptUI.getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
- if (cu == null)
- return null;
-
- QuickTemplateProcessor quickTemplateProcessor= new QuickTemplateProcessor();
- IInvocationContext context= new AssistContext(cu, textSelection.getOffset(), textSelection.getLength());
-
- try {
- IJavaCompletionProposal[] proposals= quickTemplateProcessor.getAssists(context, null);
- if (proposals == null || proposals.length == 0)
- return null;
-
- return getActionsFromProposals(proposals, context.getSelectionOffset(), editor.getViewer());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- private static IAction[] getActionsFromProposals(IJavaCompletionProposal[] proposals, final int offset, final ITextViewer viewer) {
- List result= new ArrayList();
-
- for (int i= 0, j= 1; i < proposals.length; i++) {
- if (proposals[i] instanceof ICompletionProposalExtension2) {
- final IJavaCompletionProposal proposal= proposals[i];
-
- StringBuffer actionName= new StringBuffer();
- if (j<10) {
- actionName.append('&').append(j).append(' ');
- }
- actionName.append(proposals[i].getDisplayString());
-
- Action action= new Action(actionName.toString()) {
- /**
- * {@inheritDoc}
- */
- public void run() {
- applyProposal(proposal, viewer, (char)0, 0, offset);
- }
- };
-
- result.add(action);
- j++;
- }
- }
- if (result.size() == 0)
- return null;
-
- return (IAction[])result.toArray(new IAction[result.size()]);
- }
-
- private static void applyProposal(ICompletionProposal proposal, ITextViewer viewer, char trigger, int stateMask, final int offset) {
- Assert.isTrue(proposal instanceof ICompletionProposalExtension2);
-
- IRewriteTarget target= null;
- IEditingSupportRegistry registry= null;
- IEditingSupport helper= new IEditingSupport() {
-
- public boolean isOriginator(DocumentEvent event, IRegion focus) {
- return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset;
- }
-
- public boolean ownsFocusShell() {
- return false;
- }
-
- };
-
- try {
- IDocument document= viewer.getDocument();
-
- if (viewer instanceof ITextViewerExtension) {
- ITextViewerExtension extension= (ITextViewerExtension) viewer;
- target= extension.getRewriteTarget();
- }
-
- if (target != null)
- target.beginCompoundChange();
-
- if (viewer instanceof IEditingSupportRegistry) {
- registry= (IEditingSupportRegistry) viewer;
- registry.register(helper);
- }
-
- ((ICompletionProposalExtension2)proposal).apply(viewer, trigger, stateMask, offset);
-
- Point selection= proposal.getSelection(document);
- if (selection != null) {
- viewer.setSelectedRange(selection.x, selection.y);
- viewer.revealRange(selection.x, selection.y);
- }
- } finally {
- if (target != null)
- target.endCompoundChange();
-
- if (registry != null)
- registry.unregister(helper);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/WorkbenchRunnableAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/WorkbenchRunnableAdapter.java
deleted file mode 100644
index a75bda34..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/WorkbenchRunnableAdapter.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.operation.IThreadListener;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-
-/**
- * An <code>IRunnableWithProgress</code> that adapts and <code>IWorkspaceRunnable</code>
- * so that is can be executed inside <code>IRunnableContext</code>. <code>OperationCanceledException</code>
- * thrown by the adapted runnable are caught and re-thrown as a <code>InterruptedException</code>.
- */
-public class WorkbenchRunnableAdapter implements IRunnableWithProgress, IThreadListener {
-
- private boolean fTransfer= false;
- private IWorkspaceRunnable fWorkspaceRunnable;
- private ISchedulingRule fRule;
-
- /**
- * Runs a workspace runnable with the workspace lock.
- */
- public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable) {
- this(runnable, ResourcesPlugin.getWorkspace().getRoot());
- }
-
- /**
- * Runs a workspace runnable with the given lock or <code>null</code> to run with no lock at all.
- */
- public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable, ISchedulingRule rule) {
- fWorkspaceRunnable= runnable;
- fRule= rule;
- }
-
- /**
- * Runs a workspace runnable with the given lock or <code>null</code> to run with no lock at all.
- * @param transfer <code>true</code> if the rule is to be transfered
- * to the model context thread. Otherwise <code>false</code>
- */
- public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable, ISchedulingRule rule, boolean transfer) {
- fWorkspaceRunnable= runnable;
- fRule= rule;
- fTransfer= transfer;
- }
-
- public ISchedulingRule getSchedulingRule() {
- return fRule;
- }
-
- /**
- * {@inheritDoc}
- */
- public void threadChange(Thread thread) {
- if (fTransfer)
- Job.getJobManager().transferRule(fRule, thread);
- }
-
- /*
- * @see IRunnableWithProgress#run(IProgressMonitor)
- */
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- JavaScriptCore.run(fWorkspaceRunnable, fRule, monitor);
- } catch (OperationCanceledException e) {
- throw new InterruptedException(e.getMessage());
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
-
- public void runAsUserJob(String name, final Object jobFamiliy) {
- Job buildJob = new Job(name){
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IStatus run(IProgressMonitor monitor) {
- try {
- WorkbenchRunnableAdapter.this.run(monitor);
- } catch (InvocationTargetException e) {
- Throwable cause= e.getCause();
- if (cause instanceof CoreException) {
- return ((CoreException) cause).getStatus();
- } else {
- return JavaUIStatus.createError(IStatus.ERROR, cause);
- }
- } catch (InterruptedException e) {
- return Status.CANCEL_STATUS;
- } finally {
- monitor.done();
- }
- return Status.OK_STATUS;
- }
- public boolean belongsTo(Object family) {
- return jobFamiliy == family;
- }
- };
- buildJob.setRule(fRule);
- buildJob.setUser(true);
- buildJob.schedule();
-
- // TODO: should block until user pressed 'to background'
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java
deleted file mode 100644
index 656da368..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.List;
-
-import org.eclipse.swt.widgets.Widget;
-
-/**
- * Allows accessing the PackagesViewTableViewer and the
- * PackagesViewTreeViewer with identical API.
- *
- *
- */
-interface IPackagesViewViewer {
-
- public void mapElement(Object element, Widget item);
-
- public void unmapElement(Object element, Widget item);
-
- public Widget doFindInputItem(Object element);
-
- public Widget doFindItem(Object element);
-
- public void doUpdateItem(Widget item, Object element, boolean fullMap);
-
- public List getSelectionFromWidget();
-
- public void internalRefresh(Object element);
-
- public void setSelectionToWidget(List l, boolean reveal);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingContentProvider.java
deleted file mode 100644
index 84ec80bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingContentProvider.java
+++ /dev/null
@@ -1,537 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.IBasicPropertyConstants;
-import org.eclipse.jface.viewers.ListViewer;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-class JavaBrowsingContentProvider extends StandardJavaScriptElementContentProvider implements IElementChangedListener {
-
- private StructuredViewer fViewer;
- private Object fInput;
- private JavaBrowsingPart fBrowsingPart;
- private int fReadsInDisplayThread;
-
-
- public JavaBrowsingContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
- super(provideMembers);
- fBrowsingPart= browsingPart;
- fViewer= fBrowsingPart.getViewer();
- JavaScriptCore.addElementChangedListener(this);
- }
-
- public boolean hasChildren(Object element) {
- startReadInDisplayThread();
- try{
- return super.hasChildren(element);
- } finally {
- finishedReadInDisplayThread();
- }
- }
-
- public Object[] getChildren(Object element) {
- if (!exists(element))
- return NO_CHILDREN;
-
- startReadInDisplayThread();
- try {
- if (element instanceof Collection) {
- Collection elements= (Collection)element;
- if (elements.isEmpty())
- return NO_CHILDREN;
- Object[] result= new Object[0];
- Iterator iter= ((Collection)element).iterator();
- while (iter.hasNext()) {
- Object[] children= getChildren(iter.next());
- if (children != NO_CHILDREN)
- result= concatenate(result, children);
- }
- return result;
- }
- if (element instanceof IPackageFragment)
- return getPackageContents((IPackageFragment)element);
- if (fProvideMembers && element instanceof IType)
- return getChildren((IType)element);
- if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent)
- return removeImportAndPackageDeclarations(super.getChildren(element));
- if (element instanceof IJavaScriptProject)
- return getPackageFragmentRoots((IJavaScriptProject)element);
- return super.getChildren(element);
- } catch (JavaScriptModelException e) {
- return NO_CHILDREN;
- } finally {
- finishedReadInDisplayThread();
- }
- }
-
- private Object[] getPackageContents(IPackageFragment fragment) throws JavaScriptModelException {
- ISourceReference[] sourceRefs;
- if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
- sourceRefs= fragment.getJavaScriptUnits();
- }
- else {
- IClassFile[] classFiles= fragment.getClassFiles();
- List topLevelClassFile= new ArrayList();
- for (int i= 0; i < classFiles.length; i++) {
- IType type= classFiles[i].getType();
- if (type != null && type.getDeclaringType() == null && !type.isAnonymous() && !type.isLocal())
- topLevelClassFile.add(classFiles[i]);
- }
- sourceRefs= (ISourceReference[])topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
- }
-
- Object[] result= new Object[0];
- for (int i= 0; i < sourceRefs.length; i++)
- result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
- return concatenate(result, fragment.getNonJavaScriptResources());
- }
-
- private Object[] removeImportAndPackageDeclarations(Object[] members) {
- ArrayList tempResult= new ArrayList(members.length);
- for (int i= 0; i < members.length; i++)
- if (!(members[i] instanceof IImportContainer))
- tempResult.add(members[i]);
- return tempResult.toArray();
- }
-
- private Object[] getChildren(IType type) throws JavaScriptModelException{
- IParent parent;
- if (type.isBinary())
- parent= type.getClassFile();
- else {
- parent= type.getJavaScriptUnit();
- }
- if (type.getDeclaringType() != null)
- return type.getChildren();
-
- // Add import declarations
- IJavaScriptElement[] members= parent.getChildren();
- ArrayList tempResult= new ArrayList(members.length);
- for (int i= 0; i < members.length; i++)
- if ((members[i] instanceof IImportContainer))
- tempResult.add(members[i]);
- tempResult.addAll(Arrays.asList(type.getChildren()));
- return tempResult.toArray();
- }
-
- protected Object[] getPackageFragmentRoots(IJavaScriptProject project) throws JavaScriptModelException {
- if (!project.getProject().isOpen())
- return NO_CHILDREN;
-
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- List list= new ArrayList(roots.length);
- // filter out package fragments that correspond to projects and
- // replace them with the package fragments directly
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (!root.isExternal()) {
- Object[] children= root.getChildren();
- for (int k= 0; k < children.length; k++)
- list.add(children[k]);
- }
- else if (hasChildren(root)) {
- list.add(root);
- }
- }
- return concatenate(list.toArray(), project.getNonJavaScriptResources());
- }
-
- // ---------------- Element change handling
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- super.inputChanged(viewer, oldInput, newInput);
-
- if (newInput instanceof Collection) {
- // Get a template object from the collection
- Collection col= (Collection)newInput;
- if (!col.isEmpty())
- newInput= col.iterator().next();
- else
- newInput= null;
- }
- fInput= newInput;
- }
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void dispose() {
- super.dispose();
- JavaScriptCore.removeElementChangedListener(this);
- }
-
- /* (non-Javadoc)
- * Method declared on IElementChangedListener.
- */
- public void elementChanged(final ElementChangedEvent event) {
- try {
- processDelta(event.getDelta());
- } catch(JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus());
- }
- }
-
-
- /**
- * Processes a delta recursively. When more than two children are affected the
- * tree is fully refreshed starting at this node. The delta is processed in the
- * current thread but the viewer updates are posted to the UI thread.
- */
- protected void processDelta(IJavaScriptElementDelta delta) throws JavaScriptModelException {
- int kind= delta.getKind();
- int flags= delta.getFlags();
- final IJavaScriptElement element= delta.getElement();
- final boolean isElementValidForView= fBrowsingPart.isValidElement(element);
-
- if (!getProvideWorkingCopy() && element instanceof IJavaScriptUnit && ((IJavaScriptUnit)element).isWorkingCopy())
- return;
-
- if (element != null && element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT && !isOnClassPath((IJavaScriptUnit)element))
- return;
-
- // handle open and closing of a solution or project
- if (((flags & IJavaScriptElementDelta.F_CLOSED) != 0) || ((flags & IJavaScriptElementDelta.F_OPENED) != 0)) {
- postRefresh(null);
- return;
- }
-
- if (kind == IJavaScriptElementDelta.REMOVED) {
- Object parent= internalGetParent(element);
- if (isElementValidForView) {
- if (element instanceof IClassFile) {
- postRemove(((IClassFile)element).getType());
- } else if (element instanceof IJavaScriptUnit && !((IJavaScriptUnit)element).isWorkingCopy()) {
- postRefresh(null);
- } else if (element instanceof IJavaScriptUnit && ((IJavaScriptUnit)element).isWorkingCopy()) {
- if (getProvideWorkingCopy())
- postRefresh(null);
- } else if (parent instanceof IJavaScriptUnit && getProvideWorkingCopy() && !((IJavaScriptUnit)parent).isWorkingCopy()) {
- if (element instanceof IJavaScriptUnit&& ((IJavaScriptUnit)element).isWorkingCopy()) {
- // working copy removed from system - refresh
- postRefresh(null);
- }
- } else if (element instanceof IJavaScriptUnit && ((IJavaScriptUnit)element).isWorkingCopy() && parent != null && parent.equals(fInput))
- // closed editor - removing working copy
- postRefresh(null);
- else
- postRemove(element);
- }
-
- if (fBrowsingPart.isAncestorOf(element, fInput)) {
- if (element instanceof IJavaScriptUnit && ((IJavaScriptUnit)element).isWorkingCopy()) {
- postAdjustInputAndSetSelection(((IJavaScriptElement) fInput).getPrimaryElement());
- } else
- postAdjustInputAndSetSelection(null);
- }
-
- if (fInput != null && fInput.equals(element))
- postRefresh(null);
-
- if (parent instanceof IPackageFragment && fBrowsingPart.isValidElement(parent)) {
- // refresh if package gets empty (might be filtered)
- if (isPackageFragmentEmpty((IPackageFragment)parent) && fViewer.testFindItem(parent) != null)
- postRefresh(null);
- }
-
- return;
- }
- if (kind == IJavaScriptElementDelta.ADDED && delta.getMovedFromElement() != null && element instanceof IJavaScriptUnit)
- return;
-
- if (kind == IJavaScriptElementDelta.ADDED) {
- if (isElementValidForView) {
- Object parent= internalGetParent(element);
- if (element instanceof IClassFile) {
- postAdd(parent, ((IClassFile)element).getType());
- } else if (element instanceof IJavaScriptUnit && !((IJavaScriptUnit)element).isWorkingCopy()) {
- postAdd(parent, ((IJavaScriptUnit)element).getTypes());
- } else if (parent instanceof IJavaScriptUnit && getProvideWorkingCopy() && !((IJavaScriptUnit)parent).isWorkingCopy()) {
- // do nothing
- } else if (element instanceof IJavaScriptUnit && ((IJavaScriptUnit)element).isWorkingCopy()) {
- // new working copy comes to live
- postRefresh(null);
- } else
- postAdd(parent, element);
- } else if (fInput == null) {
- IJavaScriptElement newInput= fBrowsingPart.findInputForJavaElement(element);
- if (newInput != null)
- postAdjustInputAndSetSelection(element);
- } else if (element instanceof IType && fBrowsingPart.isValidInput(element)) {
- IJavaScriptElement cu1= element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- IJavaScriptElement cu2= ((IJavaScriptElement)fInput).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu1 != null && cu2 != null && cu1.equals(cu2))
- postAdjustInputAndSetSelection(element);
- }
- return;
- }
-
- if (kind == IJavaScriptElementDelta.CHANGED) {
- if (fInput != null && fInput.equals(element) && (flags & IJavaScriptElementDelta.F_CHILDREN) != 0 && (flags & IJavaScriptElementDelta.F_FINE_GRAINED) != 0) {
- postRefresh(null, true);
- return;
- }
- if (isElementValidForView && (flags & IJavaScriptElementDelta.F_MODIFIERS) != 0) {
- postUpdateIcon(element);
- }
- }
-
- if (isClassPathChange(delta))
- // throw the towel and do a full refresh
- postRefresh(null);
-
- if ((flags & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0 && fInput instanceof IJavaScriptElement) {
- IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)element;
- IJavaScriptElement inputsParent= ((IJavaScriptElement)fInput).getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (pkgRoot.equals(inputsParent))
- postRefresh(null);
- }
-
- // the source attachment of a JAR has changed
- if (element instanceof IPackageFragmentRoot && (((flags & IJavaScriptElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaScriptElementDelta.F_SOURCEDETACHED)) != 0)))
- postUpdateIcon(element);
-
- IJavaScriptElementDelta[] affectedChildren= delta.getAffectedChildren();
- if (affectedChildren.length > 1) {
- // a package fragment might become non empty refresh from the parent
- if (element instanceof IPackageFragment) {
- IJavaScriptElement parent= (IJavaScriptElement)internalGetParent(element);
- // avoid posting a refresh to an invisible parent
- if (element.equals(fInput)) {
- postRefresh(element);
- } else {
- postRefresh(parent);
- }
- }
- // more than one child changed, refresh from here downwards
- if (element instanceof IPackageFragmentRoot && isElementValidForView) {
- postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
- return;
- }
- }
- for (int i= 0; i < affectedChildren.length; i++) {
- processDelta(affectedChildren[i]);
- }
- }
-
- private boolean isOnClassPath(IJavaScriptUnit element) throws JavaScriptModelException {
- IJavaScriptProject project= element.getJavaScriptProject();
- if (project == null || !project.exists())
- return false;
- return project.isOnIncludepath(element);
- }
-
- /**
- * Updates the package icon
- */
- private void postUpdateIcon(final IJavaScriptElement element) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed())
- fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
- }
- });
- }
-
- private void postRefresh(final Object root, final boolean updateLabels) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed())
- fViewer.refresh(root, updateLabels);
- }
- });
- }
-
- private void postRefresh(final Object root) {
- postRefresh(root, false);
- }
-
- private void postAdd(final Object parent, final Object element) {
- postAdd(parent, new Object[] {element});
- }
-
- private void postAdd(final Object parent, final Object[] elements) {
- if (elements == null || elements.length <= 0)
- return;
-
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- Object[] newElements= getNewElements(elements);
- if (fViewer instanceof AbstractTreeViewer) {
- if (fViewer.testFindItem(parent) == null) {
- Object root= ((AbstractTreeViewer)fViewer).getInput();
- if (root != null)
- ((AbstractTreeViewer)fViewer).add(root, newElements);
- }
- else
- ((AbstractTreeViewer)fViewer).add(parent, newElements);
- }
- else if (fViewer instanceof ListViewer)
- ((ListViewer)fViewer).add(newElements);
- else if (fViewer instanceof TableViewer)
- ((TableViewer)fViewer).add(newElements);
- if (fViewer.testFindItem(elements[0]) != null)
- fBrowsingPart.adjustInputAndSetSelection(elements[0]);
- }
- }
- });
- }
-
- private Object[] getNewElements(Object[] elements) {
- int elementsLength= elements.length;
- ArrayList result= new ArrayList(elementsLength);
- for (int i= 0; i < elementsLength; i++) {
- Object element= elements[i];
- if (fViewer.testFindItem(element) == null)
- result.add(element);
- }
- return result.toArray();
- }
-
- private void postRemove(final Object element) {
- postRemove(new Object[] {element});
- }
-
- private void postRemove(final Object[] elements) {
- if (elements.length <= 0)
- return;
-
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- if (fViewer instanceof AbstractTreeViewer)
- ((AbstractTreeViewer)fViewer).remove(elements);
- else if (fViewer instanceof ListViewer)
- ((ListViewer)fViewer).remove(elements);
- else if (fViewer instanceof TableViewer)
- ((TableViewer)fViewer).remove(elements);
- }
- }
- });
- }
-
- private void postAdjustInputAndSetSelection(final Object element) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ctrl.setRedraw(false);
- fBrowsingPart.adjustInputAndSetSelection(element);
- ctrl.setRedraw(true);
- }
- }
- });
- }
-
- protected void startReadInDisplayThread() {
- if (isDisplayThread())
- fReadsInDisplayThread++;
- }
-
- protected void finishedReadInDisplayThread() {
- if (isDisplayThread())
- fReadsInDisplayThread--;
- }
-
- private boolean isDisplayThread() {
- Control ctrl= fViewer.getControl();
- if (ctrl == null)
- return false;
-
- Display currentDisplay= Display.getCurrent();
- return currentDisplay != null && currentDisplay.equals(ctrl.getDisplay());
- }
-
- private void postRunnable(final Runnable r) {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- fBrowsingPart.setProcessSelectionEvents(false);
- try {
- if (isDisplayThread() && fReadsInDisplayThread == 0)
- ctrl.getDisplay().syncExec(r);
- else
- ctrl.getDisplay().asyncExec(r);
- } finally {
- fBrowsingPart.setProcessSelectionEvents(true);
- }
- }
- }
-
- /**
- * Returns the parent for the element.
- * <p>
- * Note: This method will return a working copy if the
- * parent is a working copy. The super class implementation
- * returns the original element instead.
- * </p>
- */
- protected Object internalGetParent(Object element) {
- if (element instanceof IJavaScriptProject) {
- return ((IJavaScriptProject)element).getJavaScriptModel();
- }
- // try to map resources to the containing package fragment
- if (element instanceof IResource) {
- IResource parent= ((IResource)element).getParent();
- Object jParent= JavaScriptCore.create(parent);
- if (jParent != null)
- return jParent;
- return parent;
- }
-
- // for package fragments that are contained in a project package fragment
- // we have to skip the package fragment root as the parent.
- if (element instanceof IPackageFragment) {
- IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent();
- return skipProjectPackageFragmentRoot(parent);
- }
- if (element instanceof IJavaScriptElement)
- return ((IJavaScriptElement)element).getParent();
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.java
deleted file mode 100644
index 55a5bf60..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-public final class JavaBrowsingMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaBrowsingMessages.class.getName();
-
- private JavaBrowsingMessages() {
- // Do not instantiate
- }
-
- public static String JavaBrowsingPart_toolTip;
- public static String JavaBrowsingPart_toolTip2;
- public static String LexicalSortingAction_label;
- public static String LexicalSortingAction_tooltip;
- public static String LexicalSortingAction_description;
- public static String PackagesView_flatLayoutAction_label;
- public static String PackagesView_HierarchicalLayoutAction_label;
- public static String PackagesView_LayoutActionGroup_layout_label;
- public static String StatusBar_concat;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaBrowsingMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties
deleted file mode 100644
index dfbd8d91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties
+++ /dev/null
@@ -1,24 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-JavaBrowsingPart_toolTip= Working Set: {0}
-JavaBrowsingPart_toolTip2= {0} - Working Set: {1}
-
-LexicalSortingAction_label= Sort
-LexicalSortingAction_tooltip= Sort
-LexicalSortingAction_description= Enable Sorting
-
-PackagesView_flatLayoutAction_label= &Flat
-PackagesView_HierarchicalLayoutAction_label= &Hierarchical
-PackagesView_LayoutActionGroup_layout_label= &Package Presentation
-
-# the first argument is the string to which the second one is appended
-StatusBar_concat= {0}, {1}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPart.java
deleted file mode 100644
index 55212d8c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPart.java
+++ /dev/null
@@ -1,1315 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.search.ui.ISearchResultViewPart;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.NewWizardsActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.dnd.DelegatingDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.ResourceTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTableViewer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.BuildActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.CustomFiltersActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.ImportActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-
-abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider {
-
- private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$
- private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$
- private static final String TAG_LOGICAL_PACKAGE= "logicalPackage"; //$NON-NLS-1$
- private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$
-
- private JavaUILabelProvider fLabelProvider;
- private ILabelProvider fTitleProvider;
- private StructuredViewer fViewer;
- private IMemento fMemento;
- private JavaElementTypeComparator fTypeComparator;
-
- // Actions
- private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
- private boolean fHasWorkingSetFilter= true;
- private boolean fHasCustomFilter= true;
- private OpenEditorActionGroup fOpenEditorGroup;
- private CCPActionGroup fCCPActionGroup;
- private BuildActionGroup fBuildActionGroup;
- private ToggleLinkingAction fToggleLinkingAction;
- protected CompositeActionGroup fActionGroups;
-
-
- // Filters
- private CustomFiltersActionGroup fCustomFiltersActionGroup;
-
- protected IWorkbenchPart fPreviousSelectionProvider;
- protected Object fPreviousSelectedElement;
-
- // Linking
- private boolean fLinkingEnabled;
-
- /*
- * Ensure selection changed events being processed only if
- * initiated by user interaction with this part.
- */
- private boolean fProcessSelectionEvents= true;
-
- private IPartListener2 fPartListener= new IPartListener2() {
- public void partActivated(IWorkbenchPartReference ref) {
- }
- public void partBroughtToTop(IWorkbenchPartReference ref) {
- }
- public void partInputChanged(IWorkbenchPartReference ref) {
- }
- public void partClosed(IWorkbenchPartReference ref) {
- }
- public void partDeactivated(IWorkbenchPartReference ref) {
- }
- public void partOpened(IWorkbenchPartReference ref) {
- }
- public void partVisible(IWorkbenchPartReference ref) {
- if (ref != null && ref.getId() == getSite().getId()){
- fProcessSelectionEvents= true;
- IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage();
- if (page != null)
- selectionChanged(page.getActivePart(), page.getSelection());
- }
- }
- public void partHidden(IWorkbenchPartReference ref) {
- if (ref != null && ref.getId() == getSite().getId())
- fProcessSelectionEvents= false;
- }
- };
-
- public JavaBrowsingPart() {
- super();
- initLinkingEnabled();
- }
-
- /*
- * Implements method from IViewPart.
- */
- public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
- fMemento= memento;
- }
-
- /*
- * Implements method from IViewPart.
- */
- public void saveState(IMemento memento) {
- if (fViewer == null) {
- // part has not been created
- if (fMemento != null) //Keep the old state;
- memento.putMemento(fMemento);
- return;
- }
- if (fHasWorkingSetFilter)
- fWorkingSetFilterActionGroup.saveState(memento);
- if (fHasCustomFilter)
- fCustomFiltersActionGroup.saveState(memento);
- saveSelectionState(memento);
- saveLinkingEnabled(memento);
- }
-
- private void saveLinkingEnabled(IMemento memento) {
- memento.putInteger(getLinkToEditorKey(), fLinkingEnabled ? 1 : 0);
- }
-
- private void saveSelectionState(IMemento memento) {
- Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
- if (elements.length > 0) {
- IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS);
- for (int i= 0; i < elements.length; i++) {
- IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT);
- Object o= elements[i];
- if (o instanceof IJavaScriptElement)
- elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((IJavaScriptElement) elements[i]).getHandleIdentifier());
- else if (o instanceof LogicalPackage) {
- IPackageFragment[] packages=((LogicalPackage)o).getFragments();
- for (int j= 0; j < packages.length; j++) {
- IMemento packageMem= elementMem.createChild(TAG_LOGICAL_PACKAGE);
- packageMem.putString(TAG_SELECTED_ELEMENT_PATH, packages[j].getHandleIdentifier());
- }
- }
- }
- }
- }
-
- protected void restoreState(IMemento memento) {
- if (fHasWorkingSetFilter)
- fWorkingSetFilterActionGroup.restoreState(memento);
- if (fHasCustomFilter)
- fCustomFiltersActionGroup.restoreState(memento);
-
- if (fHasCustomFilter || fHasWorkingSetFilter) {
- fViewer.getControl().setRedraw(false);
- fViewer.refresh();
- fViewer.getControl().setRedraw(true);
- }
- }
-
- private ISelection restoreSelectionState(IMemento memento) {
- if (memento == null)
- return null;
-
- IMemento childMem;
- childMem= memento.getChild(TAG_SELECTED_ELEMENTS);
- if (childMem != null) {
- ArrayList list= new ArrayList();
- IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT);
- for (int i= 0; i < elementMem.length; i++) {
- String javaElementHandle= elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
- if (javaElementHandle == null) {
- // logical package
- IMemento[] packagesMem= elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
- LogicalPackage lp= null;
- for (int j= 0; j < packagesMem.length; j++) {
- javaElementHandle= packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
- Object pack= JavaScriptCore.create(javaElementHandle);
- if (pack instanceof IPackageFragment && ((IPackageFragment)pack).exists()) {
- if (lp == null)
- lp= new LogicalPackage((IPackageFragment)pack);
- else
- lp.add((IPackageFragment)pack);
- }
- }
- if (lp != null)
- list.add(lp);
- } else {
- IJavaScriptElement element= JavaScriptCore.create(javaElementHandle);
- if (element != null && element.exists())
- list.add(element);
- }
- }
- return new StructuredSelection(list);
- }
- return null;
- }
-
- private void restoreLinkingEnabled(IMemento memento) {
- Integer val= memento.getInteger(getLinkToEditorKey());
- if (val != null) {
- fLinkingEnabled= val.intValue() != 0;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- public void createPartControl(Composite parent) {
- Assert.isTrue(fViewer == null);
-
-
- fTypeComparator= new JavaElementTypeComparator();
-
- // Setup viewer
- fViewer= createViewer(parent);
-
- initDragAndDrop();
-
- fLabelProvider= createLabelProvider();
- fViewer.setLabelProvider(createDecoratingLabelProvider(fLabelProvider));
-
- fViewer.setComparator(createJavaElementComparator());
- fViewer.setUseHashlookup(true);
- fTitleProvider= createTitleProvider();
-
- createContextMenu();
- getSite().setSelectionProvider(fViewer);
-
- if (fMemento != null) { // initialize linking state before creating the actions
- restoreLinkingEnabled(fMemento);
- }
-
- createActions(); // call before registering for selection changes
- addKeyListener();
-
- if (fMemento != null)
- restoreState(fMemento);
-
- getSite().setSelectionProvider(fViewer);
-
- // Status line
- IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
- fViewer.addSelectionChangedListener(createStatusBarUpdater(slManager));
-
-
- hookViewerListeners();
-
- // Filters
- addFilters();
-
- // Initialize viewer input
- fViewer.setContentProvider(createContentProvider());
- setInitialInput();
-
- // Initialize selection
- setInitialSelection();
- fMemento= null;
-
- // Listen to page changes
- getViewSite().getPage().addPostSelectionListener(this);
- getViewSite().getPage().addPartListener(fPartListener);
-
- fillActionBars(getViewSite().getActionBars());
-
- setHelp();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInSource.class) {
- return getShowInSource();
- }
- if (key == IContextProvider.class)
- return JavaUIHelp.getHelpContextProvider(this, getHelpContextId());
-
- return super.getAdapter(key);
- }
-
- /**
- * Returns the <code>IShowInSource</code> for this view.
- * @return returns the <code>IShowInSource</code>
- */
- protected IShowInSource getShowInSource() {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- return new ShowInContext(
- null,
- getSite().getSelectionProvider().getSelection());
- }
- };
- }
-
- protected DecoratingJavaLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
-// XXX: Work in progress for problem decorator being a workbench decorator//
-// return new ExcludingDecoratingLabelProvider(provider, decorationMgr, "org.eclipse.wst.jsdt.ui.problem.decorator"); //$NON-NLS-1$
- return new DecoratingJavaLabelProvider(provider);
- }
-
- protected JavaScriptElementComparator createJavaElementComparator() {
- return new JavaScriptElementComparator();
- }
-
- protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
- return new StatusBarUpdater(slManager);
- }
-
- protected void createContextMenu() {
- MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuManager.setRemoveAllWhenShown(true);
- menuManager.addMenuListener(this);
- Menu contextMenu= menuManager.createContextMenu(fViewer.getControl());
- fViewer.getControl().setMenu(contextMenu);
- getSite().registerContextMenu(menuManager, fViewer);
- }
-
- protected void initDragAndDrop() {
- int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
- // drop
- Transfer[] dropTransfers= new Transfer[] {
- LocalSelectionTransfer.getInstance()
- };
- TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
- new SelectionTransferDropAdapter(fViewer)
- };
- fViewer.addDropSupport(ops | DND.DROP_DEFAULT, dropTransfers, new DelegatingDropAdapter(dropListeners));
-
- // Drag
- Transfer[] dragTransfers= new Transfer[] {
- LocalSelectionTransfer.getInstance(),
- ResourceTransfer.getInstance()};
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(fViewer),
- new ResourceTransferDragAdapter(fViewer)
- };
- fViewer.addDragSupport(ops, dragTransfers, new JdtViewerDragAdapter(fViewer, dragListeners));
- }
-
- protected void fillActionBars(IActionBars actionBars) {
- IToolBarManager toolBar= actionBars.getToolBarManager();
- fillToolBar(toolBar);
-
-
- if (fHasWorkingSetFilter)
- fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars());
-
- actionBars.updateActionBars();
-
- fActionGroups.fillActionBars(actionBars);
-
- if (fHasCustomFilter)
- fCustomFiltersActionGroup.fillActionBars(actionBars);
-
- IMenuManager menu= actionBars.getMenuManager();
- menu.add(fToggleLinkingAction);
- }
-
- //---- IWorkbenchPart ------------------------------------------------------
-
-
- public void setFocus() {
- fViewer.getControl().setFocus();
- }
-
- public void dispose() {
- if (fViewer != null) {
- getViewSite().getPage().removePostSelectionListener(this);
- getViewSite().getPage().removePartListener(fPartListener);
- fViewer= null;
- }
- if (fActionGroups != null)
- fActionGroups.dispose();
-
- if (fWorkingSetFilterActionGroup != null) {
- fWorkingSetFilterActionGroup.dispose();
- }
-
- super.dispose();
- }
-
- /**
- * Adds the KeyListener
- */
- protected void addKeyListener() {
- fViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- handleKeyReleased(event);
- }
- });
- }
-
- protected void handleKeyReleased(KeyEvent event) {
- if (event.stateMask != 0)
- return;
-
- int key= event.keyCode;
- if (key == SWT.F5) {
- IAction action= fBuildActionGroup.getRefreshAction();
- if (action.isEnabled())
- action.run();
- }
- }
-
- //---- Adding Action to Toolbar -------------------------------------------
-
- protected void fillToolBar(IToolBarManager tbm) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
- */
- public void menuAboutToShow(IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
-
- IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
- int size= selection.size();
- Object element= selection.getFirstElement();
-
- if (size == 1)
- addOpenNewWindowAction(menu, element);
- fActionGroups.setContext(new ActionContext(selection));
- fActionGroups.fillContextMenu(menu);
- fActionGroups.setContext(null);
- }
-
- private void addOpenNewWindowAction(IMenuManager menu, Object element) {
- if (element instanceof IJavaScriptElement) {
- element= ((IJavaScriptElement)element).getResource();
- }
- if (!(element instanceof IContainer))
- return;
- menu.appendToGroup(
- IContextMenuConstants.GROUP_OPEN,
- new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element));
- }
-
- protected void createActions() {
- fActionGroups= new CompositeActionGroup(new ActionGroup[] {
- new NewWizardsActionGroup(this.getSite()),
- fOpenEditorGroup= new OpenEditorActionGroup(this),
- new OpenViewActionGroup(this),
- fCCPActionGroup= new CCPActionGroup(this),
- new GenerateActionGroup(this),
- new RefactorActionGroup(this),
- new ImportActionGroup(this),
- fBuildActionGroup= new BuildActionGroup(this),
- new JavaSearchActionGroup(this)});
-
-
- if (fHasWorkingSetFilter) {
- String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$
- Assert.isNotNull(viewId);
- IPropertyChangeListener workingSetListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doWorkingSetChanged(event);
- }
- };
- fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(getSite(), workingSetListener);
- fViewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter());
- }
-
- // Custom filter group
- if (fHasCustomFilter)
- fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer);
-
- fToggleLinkingAction= new ToggleLinkingAction(this);
- }
-
- private void doWorkingSetChanged(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property))
- updateTitle();
- else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- updateTitle();
- fViewer.getControl().setRedraw(false);
- fViewer.refresh();
- fViewer.getControl().setRedraw(true);
- }
-
- }
-
-
- /**
- * Returns the shell to use for opening dialogs.
- * Used in this class, and in the actions.
- * @return returns the shell
- */
- Shell getShell() {
- return fViewer.getControl().getShell();
- }
-
- protected final Display getDisplay() {
- return fViewer.getControl().getDisplay();
- }
-
- /**
- * Returns the selection provider.
- * @return the selection provider
- */
- ISelectionProvider getSelectionProvider() {
- return fViewer;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * input for this part.
- *
- * @param element the object to test
- * @return <code>true</code> if the given element is a valid input
- */
- abstract protected boolean isValidInput(Object element);
-
- /**
- * Answers if the given <code>element</code> is a valid
- * element for this part.
- *
- * @param element the object to test
- * @return <code>true</code> if the given element is a valid element
- */
- protected boolean isValidElement(Object element) {
- if (!(element instanceof IJavaScriptElement)) {
- return false;
- }
- Object input= getViewer().getInput();
- if (input == null)
- return false;
- if (input instanceof Collection)
- return ((Collection)input).contains(element);
- else
- return input.equals(element);
-
- }
-
- private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) {
- if (newInput == null)
- return part == fPreviousSelectionProvider;
-
- if (input instanceof IJavaScriptElement && newInput instanceof IJavaScriptElement)
- return getTypeComparator().compare(newInput, input) > 0;
-
- if((newInput instanceof List) && (part instanceof PackagesView))
- return true;
-
- else
- return false;
- }
-
- private boolean isInputResetBy(IWorkbenchPart part) {
- if (!(part instanceof JavaBrowsingPart))
- return true;
- Object thisInput= getViewer().getInput();
- Object partInput= ((JavaBrowsingPart)part).getViewer().getInput();
-
- if(thisInput instanceof Collection)
- thisInput= ((Collection)thisInput).iterator().next();
-
- if(partInput instanceof Collection)
- partInput= ((Collection)partInput).iterator().next();
-
- if (thisInput instanceof IJavaScriptElement && partInput instanceof IJavaScriptElement)
- return getTypeComparator().compare(partInput, thisInput) > 0;
- else
- return true;
- }
-
- protected boolean isAncestorOf(Object ancestor, Object element) {
- if (element instanceof IJavaScriptElement && ancestor instanceof IJavaScriptElement)
- return !element.equals(ancestor) && internalIsAncestorOf((IJavaScriptElement)ancestor, (IJavaScriptElement)element);
- return false;
- }
-
- private boolean internalIsAncestorOf(IJavaScriptElement ancestor, IJavaScriptElement element) {
- if (element != null)
- return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
- else
- return false;
- }
-
- private boolean isSearchResultView(IWorkbenchPart part) {
- return SearchUtil.isSearchPlugInActivated() && part instanceof ISearchResultViewPart;
- }
-
- protected boolean needsToProcessSelectionChanged(IWorkbenchPart part, ISelection selection) {
- if (!fProcessSelectionEvents || part == this || isSearchResultView(part) || part instanceof AbstractInfoView){
- if (part == this)
- fPreviousSelectionProvider= part;
- return false;
- }
- return true;
- }
-
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (!needsToProcessSelectionChanged(part, selection))
- return;
-
- if (fToggleLinkingAction.isChecked() && (part instanceof ITextEditor)) {
- setSelectionFromEditor(part, selection);
- return;
- }
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- // Set selection
- Object selectedElement= getSingleElementFromSelection(selection);
-
- if (selectedElement != null && (part == null || part.equals(fPreviousSelectionProvider)) && selectedElement.equals(fPreviousSelectedElement))
- return;
-
- fPreviousSelectedElement= selectedElement;
-
- Object currentInput= getViewer().getInput();
- if (selectedElement != null && selectedElement.equals(currentInput)) {
- IJavaScriptElement elementToSelect= findElementToSelect(selectedElement);
- if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0)
- setSelection(new StructuredSelection(elementToSelect), true);
- else if (elementToSelect == null && (this instanceof MembersView)) {
- setSelection(StructuredSelection.EMPTY, true);
- fPreviousSelectedElement= StructuredSelection.EMPTY;
- }
- fPreviousSelectionProvider= part;
- return;
- }
-
- // Clear input if needed
- if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) {
- if (!isAncestorOf(selectedElement, currentInput))
- setInput(null);
- fPreviousSelectionProvider= part;
- return;
- } else if (selection.isEmpty() && !isInputResetBy(part)) {
- fPreviousSelectionProvider= part;
- return;
- } else if (selectedElement == null && part == fPreviousSelectionProvider) {
- setInput(null);
- fPreviousSelectionProvider= part;
- return;
- }
- fPreviousSelectionProvider= part;
-
- // Adjust input and set selection and
- adjustInputAndSetSelection(selectedElement);
- }
-
-
- void setHasWorkingSetFilter(boolean state) {
- fHasWorkingSetFilter= state;
- }
-
- void setHasCustomSetFilter(boolean state) {
- fHasCustomFilter= state;
- }
-
- protected Object getInput() {
- return fViewer.getInput();
- }
-
- protected void setInput(Object input) {
- setViewerInput(input);
- updateTitle();
- }
-
- boolean isLinkingEnabled() {
- return fLinkingEnabled;
- }
-
- private void initLinkingEnabled() {
- fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(getLinkToEditorKey());
- }
-
- private void setViewerInput(Object input) {
- fProcessSelectionEvents= false;
- fViewer.setInput(input);
- fProcessSelectionEvents= true;
- }
-
- void updateTitle() {
- setTitleToolTip(getToolTipText(fViewer.getInput()));
- }
-
- /**
- * Returns the tool tip text for the given element.
- * @param element the element
- * @return the tooltip for the element
- */
- String getToolTipText(Object element) {
- String result;
- if (!(element instanceof IResource)) {
- result= JavaScriptElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
- } else {
- IPath path= ((IResource) element).getFullPath();
- if (path.isRoot()) {
- result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
- } else {
- result= path.makeRelative().toString();
- }
- }
-
- if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null)
- return result;
-
- IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet();
- String wsstr= Messages.format(JavaBrowsingMessages.JavaBrowsingPart_toolTip, new String[] { ws.getLabel() });
- if (result.length() == 0)
- return wsstr;
- return Messages.format(JavaBrowsingMessages.JavaBrowsingPart_toolTip2, new String[] { result, ws.getLabel() });
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#getTitleToolTip()
- */
- public String getTitleToolTip() {
- if (fViewer == null)
- return super.getTitleToolTip();
- return getToolTipText(fViewer.getInput());
- }
-
- protected final StructuredViewer getViewer() {
- return fViewer;
- }
-
- protected final void setViewer(StructuredViewer viewer){
- fViewer= viewer;
- }
-
- protected JavaUILabelProvider createLabelProvider() {
- return new AppearanceAwareLabelProvider(
- AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS
- );
- }
-
- protected ILabelProvider createTitleProvider() {
- return new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_BASICS | JavaScriptElementLabelProvider.SHOW_SMALL_ICONS);
- }
-
- protected final ILabelProvider getLabelProvider() {
- return fLabelProvider;
- }
-
- protected final ILabelProvider getTitleProvider() {
- return fTitleProvider;
- }
-
- /**
- * Creates the viewer of this part.
- *
- * @param parent the parent for the viewer
- * @return the created viewer
- */
- protected StructuredViewer createViewer(Composite parent) {
- return new ProblemTableViewer(parent, SWT.MULTI);
- }
-
- protected int getLabelProviderFlags() {
- return JavaScriptElementLabelProvider.SHOW_BASICS | JavaScriptElementLabelProvider.SHOW_OVERLAY_ICONS |
- JavaScriptElementLabelProvider.SHOW_SMALL_ICONS | JavaScriptElementLabelProvider.SHOW_VARIABLE | JavaScriptElementLabelProvider.SHOW_PARAMETERS;
- }
-
- /**
- * Adds filters the viewer of this part.
- */
- protected void addFilters() {
- // default is to have no filters
- }
-
- /**
- * Creates the content provider of this part.
- * @return the content provider
- */
- protected IContentProvider createContentProvider() {
- return new JavaBrowsingContentProvider(true, this);
- }
-
- protected void setInitialInput() {
- // Use the selection, if any
- ISelection selection= getSite().getPage().getSelection();
- Object input= getSingleElementFromSelection(selection);
- if (!(input instanceof IJavaScriptElement)) {
- // Use the input of the page
- input= getSite().getPage().getInput();
- if (!(input instanceof IJavaScriptElement) && input instanceof IAdaptable)
- input= ((IAdaptable)input).getAdapter(IJavaScriptElement.class);
- }
- setInput(findInputForJavaElement((IJavaScriptElement)input));
- }
-
- protected void setInitialSelection() {
- // Use the selection, if any
- Object input;
- IWorkbenchPage page= getSite().getPage();
- ISelection selection= null;
- if (page != null)
- selection= page.getSelection();
- if (selection instanceof ITextSelection) {
- Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
- if (part instanceof IEditorPart) {
- setSelectionFromEditor((IEditorPart)part);
- if (fViewer.getSelection() != null)
- return;
- }
- }
-
- // Use saved selection from memento
- if (selection == null || selection.isEmpty())
- selection= restoreSelectionState(fMemento);
-
- if (selection == null || selection.isEmpty()) {
- // Use the input of the page
- input= getSite().getPage().getInput();
- if (!(input instanceof IJavaScriptElement)) {
- if (input instanceof IAdaptable)
- input= ((IAdaptable)input).getAdapter(IJavaScriptElement.class);
- else
- return;
- }
- selection= new StructuredSelection(input);
- }
- selectionChanged(null, selection);
- }
-
- protected final void setHelp() {
- JavaUIHelp.setHelp(fViewer, getHelpContextId());
- }
-
- /**
- * Returns the context ID for the Help system
- *
- * @return the string used as ID for the Help context
- */
- abstract protected String getHelpContextId();
-
- /**
- * Returns the preference key for the link to editor setting.
- *
- * @return the string used as key into the preference store
- */
- abstract protected String getLinkToEditorKey();
-
- /**
- * Adds additional listeners to this view.
- * This method can be overridden but should
- * call super.
- */
- protected void hookViewerListeners() {
- fViewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if (!fProcessSelectionEvents)
- return;
-
- fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection());
-
- IWorkbenchPage page= getSite().getPage();
- if (page == null)
- return;
-
- if (page.equals(JavaScriptPlugin.getActivePage()) && JavaBrowsingPart.this.equals(page.getActivePart())) {
- linkToEditor((IStructuredSelection)event.getSelection());
- }
- }
- });
-
- fViewer.addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- IAction open= fOpenEditorGroup.getOpenAction();
- if (open.isEnabled()) {
- open.run();
- restoreSelection();
- }
- }
- });
- }
-
- void restoreSelection() {
- // Default is to do nothing
- }
-
- void adjustInputAndSetSelection(Object o) {
- if (!(o instanceof IJavaScriptElement)) {
- if (o == null)
- setInput(null);
- setSelection(StructuredSelection.EMPTY, true);
- return;
- }
-
- IJavaScriptElement je= (IJavaScriptElement)o;
- IJavaScriptElement elementToSelect= findElementToSelect(je);
- IJavaScriptElement newInput= findInputForJavaElement(je);
- IJavaScriptElement oldInput= null;
- if (getInput() instanceof IJavaScriptElement)
- oldInput= (IJavaScriptElement)getInput();
-
- if (elementToSelect == null && !isValidInput(newInput) && (newInput == null && !isAncestorOf(je, oldInput)))
- // Clear input
- setInput(null);
- else if (mustSetNewInput(elementToSelect, oldInput, newInput)) {
- // Adjust input to selection
- setInput(newInput);
- }
-
- if (elementToSelect != null && elementToSelect.exists())
- setSelection(new StructuredSelection(elementToSelect), true);
- else
- setSelection(StructuredSelection.EMPTY, true);
- }
-
- /**
- * Compute if a new input must be set.
- *
- * @param elementToSelect the element to select
- * @param oldInput old input
- * @param newInput new input
- * @return <code>true</code> if the input has to be set
- *
- */
- private boolean mustSetNewInput(IJavaScriptElement elementToSelect, IJavaScriptElement oldInput, IJavaScriptElement newInput) {
- return (newInput == null || !newInput.equals(oldInput))
- && (elementToSelect == null
- || oldInput == null);
- }
-
- /**
- * Finds the closest Java element which can be used as input for
- * this part and has the given Java element as child
- *
- * @param je the Java element for which to search the closest input
- * @return the closest Java element used as input for this part
- */
- protected IJavaScriptElement findInputForJavaElement(IJavaScriptElement je) {
- if (je == null || !je.exists())
- return null;
- if (isValidInput(je))
- return je;
- return findInputForJavaElement(je.getParent());
- }
-
- protected final IJavaScriptElement findElementToSelect(Object obj) {
- if (obj instanceof IJavaScriptElement)
- return findElementToSelect((IJavaScriptElement)obj);
- return null;
- }
-
- /**
- * Finds the element which has to be selected in this part.
- *
- * @param je the Java element which has the focus
- * @return returns the element to select
- */
- abstract protected IJavaScriptElement findElementToSelect(IJavaScriptElement je);
-
-
- protected final Object getSingleElementFromSelection(ISelection selection) {
- if (!(selection instanceof IStructuredSelection) || selection.isEmpty())
- return null;
-
- Iterator iter= ((IStructuredSelection)selection).iterator();
- Object firstElement= iter.next();
- if (!(firstElement instanceof IJavaScriptElement)) {
- if (firstElement instanceof IMarker)
- firstElement= ((IMarker)firstElement).getResource();
- if (firstElement instanceof IAdaptable) {
- IJavaScriptElement je= (IJavaScriptElement)((IAdaptable)firstElement).getAdapter(IJavaScriptElement.class);
- if (je == null && firstElement instanceof IFile) {
- IContainer parent= ((IFile)firstElement).getParent();
- if (parent != null)
- return parent.getAdapter(IJavaScriptElement.class);
- else return null;
- } else
- return je;
-
- } else
- return firstElement;
- }
- Object currentInput= getViewer().getInput();
- if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaScriptElement)firstElement)))
- if (iter.hasNext())
- // multi-selection and view is empty
- return null;
- else
- // OK: single selection and view is empty
- return firstElement;
-
- // be nice to multi-selection
- while (iter.hasNext()) {
- Object element= iter.next();
- if (!(element instanceof IJavaScriptElement))
- return null;
- if (!currentInput.equals(findInputForJavaElement((IJavaScriptElement)element)))
- return null;
- }
- return firstElement;
- }
-
- /**
- * Gets the typeComparator.
- * @return Returns a JavaElementTypeComparator
- */
- protected Comparator getTypeComparator() {
- return fTypeComparator;
- }
-
- /**
- * Links to editor (if option enabled)
- * @param selection the selection
- */
- private void linkToEditor(IStructuredSelection selection) {
- Object obj= selection.getFirstElement();
-
- if (selection.size() == 1) {
- IEditorPart part= EditorUtility.isOpenInEditor(obj);
- if (part != null) {
- IWorkbenchPage page= getSite().getPage();
- page.bringToTop(part);
- if (obj instanceof IJavaScriptElement)
- EditorUtility.revealInEditor(part, (IJavaScriptElement) obj);
- }
- }
- }
-
- void setSelectionFromEditor(IWorkbenchPart part) {
- if (!fProcessSelectionEvents || !linkBrowsingViewSelectionToEditor() || !(part instanceof IEditorPart))
- return;
-
- IWorkbenchPartSite site= part.getSite();
- if (site == null)
- return;
- ISelectionProvider provider= site.getSelectionProvider();
- if (provider != null)
- setSelectionFromEditor(part, provider.getSelection());
- }
-
- private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) {
- if (part instanceof IEditorPart) {
- IJavaScriptElement element= null;
- if (selection instanceof IStructuredSelection) {
- Object obj= getSingleElementFromSelection(selection);
- if (obj instanceof IJavaScriptElement)
- element= (IJavaScriptElement)obj;
- }
- IEditorInput ei= ((IEditorPart)part).getEditorInput();
- if (selection instanceof ITextSelection) {
- int offset= ((ITextSelection)selection).getOffset();
- element= getElementAt(ei, offset);
- }
- if (element != null) {
- adjustInputAndSetSelection(element);
- return;
- }
- if (ei instanceof IFileEditorInput) {
- IFile file= ((IFileEditorInput)ei).getFile();
- IJavaScriptElement je= (IJavaScriptElement)file.getAdapter(IJavaScriptElement.class);
- if (je == null) {
- IContainer container= ((IFileEditorInput)ei).getFile().getParent();
- if (container != null)
- je= (IJavaScriptElement)container.getAdapter(IJavaScriptElement.class);
- }
- if (je == null) {
- setSelection(null, false);
- return;
- }
- adjustInputAndSetSelection(je);
- } else if (ei instanceof IClassFileEditorInput) {
- IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
- adjustInputAndSetSelection(cf);
- }
- }
- }
-
- /**
- * Returns the element contained in the EditorInput
- * @param input the editor input
- * @return the input element
- */
- Object getElementOfInput(IEditorInput input) {
- if (input instanceof IFileEditorInput)
- return ((IFileEditorInput)input).getFile();
- if (input != null)
- return JavaScriptUI.getEditorInputJavaElement(input);
- return null;
- }
-
- void setSelection(ISelection selection, boolean reveal) {
- if (selection != null && selection.equals(fViewer.getSelection()))
- return;
- fProcessSelectionEvents= false;
- fViewer.setSelection(selection, reveal);
- fProcessSelectionEvents= true;
- }
-
- /**
- * @param input the editor input
- * @param offset the offset in the file
- * @return the element at the given offset
- */
- protected IJavaScriptElement getElementAt(IEditorInput input, int offset) {
- if (input instanceof IClassFileEditorInput) {
- try {
- return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset);
- } catch (JavaScriptModelException ex) {
- return null;
- }
- }
-
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- IJavaScriptUnit unit= manager.getWorkingCopy(input);
- if (unit != null)
- try {
- if (unit.isConsistent())
- return unit.getElementAt(offset);
- else {
- /*
- * XXX: We should set the selection later when the
- * CU is reconciled.
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51290
- */
- }
- } catch (JavaScriptModelException ex) {
- // fall through
- }
- return null;
- }
-
- protected IType getTypeForCU(IJavaScriptUnit cu) {
- // Use primary type if possible
- IType primaryType= cu.findPrimaryType();
- if (primaryType != null)
- return primaryType;
-
- // Use first top-level type
- try {
- IType[] types= cu.getTypes();
- if (types.length > 0)
- return types[0];
- else
- return null;
- } catch (JavaScriptModelException ex) {
- return null;
- }
- }
-
- void setProcessSelectionEvents(boolean state) {
- fProcessSelectionEvents= state;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
- */
- public Object getViewPartInput() {
- if (fViewer != null) {
- return fViewer.getInput();
- }
- return null;
- }
-
- protected void setActionGroups(CompositeActionGroup actionGroups) {
- fActionGroups= actionGroups;
- }
-
- protected void setBuildActionGroup(BuildActionGroup actionGroup) {
- fBuildActionGroup= actionGroup;
- }
-
- protected void setCCPActionGroup(CCPActionGroup actionGroup) {
- fCCPActionGroup= actionGroup;
- }
-
- protected void setCustomFiltersActionGroup(CustomFiltersActionGroup customFiltersActionGroup) {
- fCustomFiltersActionGroup= customFiltersActionGroup;
- }
-
- protected boolean hasCustomFilter() {
- return fHasCustomFilter;
- }
-
- protected boolean hasWorkingSetFilter() {
- return fHasWorkingSetFilter;
- }
-
- protected void setOpenEditorGroup(OpenEditorActionGroup openEditorGroup) {
- fOpenEditorGroup= openEditorGroup;
- }
-
- protected OpenEditorActionGroup getOpenEditorGroup() {
- return fOpenEditorGroup;
- }
-
- protected BuildActionGroup getBuildActionGroup() {
- return fBuildActionGroup;
- }
-
- protected CCPActionGroup getCCPActionGroup() {
- return fCCPActionGroup;
- }
-
- private boolean linkBrowsingViewSelectionToEditor() {
- return isLinkingEnabled();
- }
-
- public void setLinkingEnabled(boolean enabled) {
- fLinkingEnabled= enabled;
- PreferenceConstants.getPreferenceStore().setValue(getLinkToEditorKey(), enabled);
- if (enabled) {
- IEditorPart editor = getSite().getPage().getActiveEditor();
- if (editor != null) {
- setSelectionFromEditor(editor);
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java
deleted file mode 100644
index 55c89f30..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.debug.ui.IDebugUIConstants;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-import org.eclipse.ui.IPlaceholderFolderLayout;
-import org.eclipse.ui.console.IConsoleConstants;
-import org.eclipse.ui.progress.IProgressConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-public class JavaBrowsingPerspectiveFactory implements IPerspectiveFactory {
-
- /*
- * XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
- */
- static IJavaScriptElement fgJavaElementFromAction;
-
- /**
- * Constructs a new Default layout engine.
- */
- public JavaBrowsingPerspectiveFactory() {
- super();
- }
-
- public void createInitialLayout(IPageLayout layout) {
- if (stackBrowsingViewsVertically())
- createVerticalLayout(layout);
- else
- createHorizontalLayout(layout);
-
- // action sets
- layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
- layout.addActionSet(JavaScriptUI.ID_ACTION_SET);
- layout.addActionSet(JavaScriptUI.ID_ELEMENT_CREATION_ACTION_SET);
- layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
-
- // views - java
- layout.addShowViewShortcut(JavaScriptUI.ID_TYPE_HIERARCHY);
- layout.addShowViewShortcut(JavaScriptUI.ID_PACKAGES);
- layout.addShowViewShortcut(JavaScriptUI.ID_PROJECTS_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_PACKAGES_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_TYPES_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_MEMBERS_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_SOURCE_VIEW);
- layout.addShowViewShortcut(JavaScriptUI.ID_JAVADOC_VIEW);
-
- // views - search
- layout.addShowViewShortcut(NewSearchUI.SEARCH_VIEW_ID);
-
- // views - debugging
- layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
-
- // views - standard workbench
- layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
- layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
- layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
- layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
- layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
-
- // new actions - Java project creation wizard
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.JavaProjectWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewEnumCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewAnnotationCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
- layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
- }
-
- private void createVerticalLayout(IPageLayout layout) {
- String relativePartId= IPageLayout.ID_EDITOR_AREA;
- int relativePos= IPageLayout.LEFT;
-
- IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
- placeHolderLeft.addPlaceholder(JavaScriptUI.ID_TYPE_HIERARCHY);
- placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
- placeHolderLeft.addPlaceholder(JavaScriptUI.ID_PACKAGES);
- placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
-
- if (shouldShowProjectsView()) {
- layout.addView(JavaScriptUI.ID_PROJECTS_VIEW, IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA);
- relativePartId= JavaScriptUI.ID_PROJECTS_VIEW;
- relativePos= IPageLayout.BOTTOM;
- }
- if (shouldShowPackagesView()) {
- layout.addView(JavaScriptUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
- relativePartId= JavaScriptUI.ID_PACKAGES_VIEW;
- relativePos= IPageLayout.BOTTOM;
- }
- layout.addView(JavaScriptUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
- layout.addView(JavaScriptUI.ID_MEMBERS_VIEW, IPageLayout.BOTTOM, (float)0.50, JavaScriptUI.ID_TYPES_VIEW);
-
- IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
- placeHolderBottom.addPlaceholder(IPageLayout.ID_PROBLEM_VIEW);
- placeHolderBottom.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID);
- placeHolderBottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
- placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
- placeHolderBottom.addPlaceholder(JavaScriptUI.ID_SOURCE_VIEW);
- placeHolderBottom.addPlaceholder(JavaScriptUI.ID_JAVADOC_VIEW);
- placeHolderBottom.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
- }
-
- private void createHorizontalLayout(IPageLayout layout) {
- String relativePartId= IPageLayout.ID_EDITOR_AREA;
- int relativePos= IPageLayout.TOP;
-
- if (shouldShowProjectsView()) {
- layout.addView(JavaScriptUI.ID_PROJECTS_VIEW, IPageLayout.TOP, (float)0.25, IPageLayout.ID_EDITOR_AREA);
- relativePartId= JavaScriptUI.ID_PROJECTS_VIEW;
- relativePos= IPageLayout.RIGHT;
- }
- if (shouldShowPackagesView()) {
- layout.addView(JavaScriptUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
- relativePartId= JavaScriptUI.ID_PACKAGES_VIEW;
- relativePos= IPageLayout.RIGHT;
- }
- layout.addView(JavaScriptUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
- layout.addView(JavaScriptUI.ID_MEMBERS_VIEW, IPageLayout.RIGHT, (float)0.50, JavaScriptUI.ID_TYPES_VIEW);
-
- IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
- placeHolderLeft.addPlaceholder(JavaScriptUI.ID_TYPE_HIERARCHY);
- placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
- placeHolderLeft.addPlaceholder(JavaScriptUI.ID_PACKAGES);
- placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
-
-
- IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
- placeHolderBottom.addPlaceholder(IPageLayout.ID_PROBLEM_VIEW);
- placeHolderBottom.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID);
- placeHolderBottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW);
- placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
- placeHolderBottom.addPlaceholder(JavaScriptUI.ID_SOURCE_VIEW);
- placeHolderBottom.addPlaceholder(JavaScriptUI.ID_JAVADOC_VIEW);
- placeHolderBottom.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
- }
-
- private boolean shouldShowProjectsView() {
- return fgJavaElementFromAction == null || fgJavaElementFromAction.getElementType() == IJavaScriptElement.JAVASCRIPT_MODEL;
- }
-
- private boolean shouldShowPackagesView() {
- if (fgJavaElementFromAction == null)
- return true;
- int type= fgJavaElementFromAction.getElementType();
- return type == IJavaScriptElement.JAVASCRIPT_MODEL || type == IJavaScriptElement.JAVASCRIPT_PROJECT || type == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT;
- }
-
- private boolean stackBrowsingViewsVertically() {
- return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.BROWSING_STACK_VERTICALLY);
- }
-
- /*
- * XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
- */
- static void setInputFromAction(IAdaptable input) {
- if (input instanceof IJavaScriptElement)
- fgJavaElementFromAction= (IJavaScriptElement)input;
- else
- fgJavaElementFromAction= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaElementTypeComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaElementTypeComparator.java
deleted file mode 100644
index 88bde5b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaElementTypeComparator.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.Comparator;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class JavaElementTypeComparator implements Comparator {
-
-
- /**
- * Compares two Java element types. A type is considered to be
- * greater if it may contain the other.
- *
- * @return an int less than 0 if object1 is less than object2,
- * 0 if they are equal, and > 0 if object1 is greater
- *
- * @see Comparator#compare(Object, Object)
- */
- public int compare(Object o1, Object o2) {
- if (!(o1 instanceof IJavaScriptElement) || !(o2 instanceof IJavaScriptElement))
- throw new ClassCastException();
- return getIdForJavaElement((IJavaScriptElement)o1) - getIdForJavaElement((IJavaScriptElement)o2);
- }
-
- /**
- * Compares two Java element types. A type is considered to be
- * greater if it may contain the other.
- *
- * @return an int < 0 if object1 is less than object2,
- * 0 if they are equal, and > 0 if object1 is greater
- *
- * @see Comparator#compare(Object, Object)
- */
- public int compare(Object o1, int elementType) {
- if (!(o1 instanceof IJavaScriptElement))
- throw new ClassCastException();
- return getIdForJavaElement((IJavaScriptElement)o1) - getIdForJavaElementType(elementType);
- }
-
- int getIdForJavaElement(IJavaScriptElement element) {
- return getIdForJavaElementType(element.getElementType());
- }
-
- int getIdForJavaElementType(int elementType) {
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return 130;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return 120;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return 110;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return 100;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return 90;
- case IJavaScriptElement.CLASS_FILE:
- return 80;
- case IJavaScriptElement.TYPE:
- return 70;
- case IJavaScriptElement.FIELD:
- return 60;
- case IJavaScriptElement.METHOD:
- return 50;
- case IJavaScriptElement.INITIALIZER:
- return 40;
- case IJavaScriptElement.IMPORT_CONTAINER:
- return 20;
- case IJavaScriptElement.IMPORT_DECLARATION:
- return 10;
- default :
- return 1;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackage.java
deleted file mode 100644
index 03c3d19a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackage.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.PlatformObject;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Contains a list of package fragments with the same name
- * but residing in different source folders of a unique Java project.
- */
-public class LogicalPackage extends PlatformObject {
-
- private Set fPackages;
- private String fName;
- private IJavaScriptProject fJavaProject;
-
- public LogicalPackage(IPackageFragment fragment){
- Assert.isNotNull(fragment);
- fPackages= new HashSet();
- fJavaProject= fragment.getJavaScriptProject();
- Assert.isNotNull(fJavaProject);
- add(fragment);
- fName= fragment.getElementName();
- }
-
- public IJavaScriptProject getJavaProject(){
- return fJavaProject;
- }
-
- public IPackageFragment[] getFragments(){
- return (IPackageFragment[]) fPackages.toArray(new IPackageFragment[fPackages.size()]);
- }
-
- public void add(IPackageFragment fragment){
- Assert.isTrue(fragment != null && fJavaProject.equals(fragment.getJavaScriptProject()));
- fPackages.add(fragment);
- }
-
- public void remove(IPackageFragment fragment){
- fPackages.remove(fragment);
- }
-
- public boolean contains(IPackageFragment fragment){
- return fPackages.contains(fragment);
- }
-
- public String getElementName(){
- return fName;
- }
-
- public int size(){
- return fPackages.size();
- }
-
- /**
- * Returns true if the given fragment has the same name and
- * resides inside the same project as the other fragments in
- * the LogicalPackage.
- *
- * @param fragment
- * @return boolean
- */
- public boolean belongs(IPackageFragment fragment) {
-
- if(fragment==null)
- return false;
-
- if(fJavaProject.equals(fragment.getJavaScriptProject())){
- return fName.equals(fragment.getElementName());
- }
-
- return false;
- }
-
- public boolean hasSubpackages() throws JavaScriptModelException {
- for (Iterator iter= fPackages.iterator(); iter.hasNext();) {
- IPackageFragment pack= (IPackageFragment) iter.next();
- if (pack.hasSubpackages()) {
- return true;
- }
- }
- return false;
- }
-
- public boolean isDefaultPackage() {
- return fName.length() == 0;
- }
-
- public boolean equals(Object o){
- if (!(o instanceof LogicalPackage))
- return false;
-
- LogicalPackage lp= (LogicalPackage)o;
- if (!fJavaProject.equals(lp.getJavaProject()))
- return false;
-
- IPackageFragment[] fragments= lp.getFragments();
-
- if (fragments.length != getFragments().length)
- return false;
-
- //this works because a LogicalPackage cannot contain the same IPackageFragment twice
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- if(!fPackages.contains(fragment))
- return false;
- }
-
- return true;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- IPackageFragment[] fragments= getFragments();
- return fJavaProject.hashCode() + getHash(fragments, fragments.length-1);
- }
-
- private int getHash(IPackageFragment[] fragments, int index) {
- if (index <= 0)
- return fragments[0].hashCode() * 17;
- else return fragments[index].hashCode() * 17 + getHash(fragments, index-1);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackagesProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackagesProvider.java
deleted file mode 100644
index 5b298f0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/LogicalPackagesProvider.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-abstract class LogicalPackagesProvider implements IPropertyChangeListener, IElementChangedListener {
-
- protected static final Object[] NO_CHILDREN= new Object[0];
-
- protected Map fMapToLogicalPackage;
- protected Map fMapToPackageFragments;
- protected boolean fCompoundState;
- protected StructuredViewer fViewer;
- protected boolean fInputIsProject;
-
- public LogicalPackagesProvider(StructuredViewer viewer){
- fViewer= viewer;
- fCompoundState= isInCompoundState();
- fInputIsProject= true;
- fMapToLogicalPackage= new HashMap();
- fMapToPackageFragments= new HashMap();
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
- }
-
- /**
- * Adds the given fragments to the internal map.
- * Existing fragments will be replaced by the new ones.
- *
- * @param packageFragments the package fragments to add
- */
- protected void addFragmentsToMap(IPackageFragment[] packageFragments) {
- for (int i= 0; i < packageFragments.length; i++) {
- IPackageFragment fragment= packageFragments[i];
- String key= getKey(fragment);
- fMapToPackageFragments.put(key, fragment);
- }
- }
-
- protected String getKey(IPackageFragment fragment) {
- return fragment.getElementName() + fragment.getJavaScriptProject().getElementName();
- }
-
- /**
- * Returns the logical package for the given package fragment
- * or <code>null</code> if it is not grouped by logical package.
- *
- * @param fragment the package fragment
- * @return the logical package
- */
- public LogicalPackage findLogicalPackage(IPackageFragment fragment) {
- Assert.isNotNull(fragment);
- if (isInCompoundState())
- return (LogicalPackage)fMapToLogicalPackage.get(getKey(fragment));
- else
- return null;
- }
-
- /**
- * Combines packages with same names into a logical package which will
- * be added to the resulting array. If a package is not yet in this content
- * provider then the package fragment is added to the resulting array.
- *
- * @param packageFragments the package fragments to combine
- * @return an array with combined (logical) packages and package fragments
- */
- protected Object[] combineSamePackagesIntoLogialPackages(IPackageFragment[] packageFragments) {
-
- if (!fCompoundState)
- return packageFragments;
-
- List newChildren= new ArrayList();
-
- for (int i= 0; i < packageFragments.length; i++) {
- IPackageFragment fragment= packageFragments[i];
-
- if (fragment == null)
- continue;
-
- LogicalPackage lp= findLogicalPackage(fragment);
-
- if (lp != null) {
- if (lp.belongs(fragment)) {
- lp.add(fragment);
- }
- if(!newChildren.contains(lp))
- newChildren.add(lp);
-
- } else {
- String key= getKey(fragment);
- IPackageFragment frag= (IPackageFragment)fMapToPackageFragments.get(key);
- if (frag != null && !fragment.equals(frag)) {
- lp= new LogicalPackage(frag);
- lp.add(fragment);
- newChildren.remove(frag);
- newChildren.add(lp);
- fMapToLogicalPackage.put(key, lp);
- fMapToPackageFragments.remove(frag);
- } else {
- fMapToPackageFragments.put(key, fragment);
- newChildren.add(fragment);
- }
- }
- }
- return newChildren.toArray();
- }
-
- /**
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (fCompoundState == isInCompoundState())
- return;
- else
- fCompoundState= isInCompoundState();
-
- if (!isInCompoundState()) {
- fMapToLogicalPackage.clear();
- fMapToPackageFragments.clear();
- }
-
- if(fViewer instanceof TreeViewer){
- TreeViewer viewer= (TreeViewer) fViewer;
- Object[] expandedObjects= viewer.getExpandedElements();
- viewer.refresh();
- viewer.setExpandedElements(expandedObjects);
- } else
- fViewer.refresh();
- }
-
- protected boolean isInCompoundState() {
- // XXX: for now we don't offer a preference might become a view menu entry
- // return AppearancePreferencePage.logicalPackagesInPackagesView();
- return true;
- }
-
- public void dispose(){
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
- fMapToLogicalPackage= null;
- fMapToPackageFragments= null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput != null) {
- JavaScriptCore.addElementChangedListener(this);
- } else {
- JavaScriptCore.removeElementChangedListener(this);
- }
- fInputIsProject= (newInput instanceof IJavaScriptProject);
-
- if(viewer instanceof StructuredViewer)
- fViewer= (StructuredViewer)viewer;
- }
-
- abstract protected void processDelta(IJavaScriptElementDelta delta) throws JavaScriptModelException;
-
- /*
- *
- */
- protected boolean isClassPathChange(IJavaScriptElementDelta delta) {
-
- // need to test the flags only for package fragment roots
- if (delta.getElement().getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- return false;
-
- int flags= delta.getFlags();
- return (delta.getKind() == IJavaScriptElementDelta.CHANGED &&
- ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) != 0) ||
- ((flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) ||
- ((flags & IJavaScriptElementDelta.F_REORDER) != 0));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.IElementChangedListener#elementChanged(org.eclipse.wst.jsdt.core.ElementChangedEvent)
- */
- public void elementChanged(ElementChangedEvent event) {
- try {
- processDelta(event.getDelta());
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/MembersView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/MembersView.java
deleted file mode 100644
index 0ad561e8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/MembersView.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.CategoryFilterActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.LexicalSortingAction;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.MemberFilterActionGroup;
-
-public class MembersView extends JavaBrowsingPart implements IPropertyChangeListener {
-
- private MemberFilterActionGroup fMemberFilterActionGroup;
- /**
- * Category filter action group.
- *
- */
- private CategoryFilterActionGroup fCategoryFilterActionGroup;
-
-
- public MembersView() {
- setHasWorkingSetFilter(false);
- setHasCustomSetFilter(true);
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES };
- }
-
- };
- }
- return super.getAdapter(key);
- }
-
- /**
- * Creates and returns the label provider for this part.
- *
- * @return the label provider
- * @see org.eclipse.jface.viewers.ILabelProvider
- */
- protected JavaUILabelProvider createLabelProvider() {
- return new AppearanceAwareLabelProvider(
- AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.ALL_CATEGORY,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
- );
- }
-
- /**
- * Returns the context ID for the Help system
- *
- * @return the string used as ID for the Help context
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.MEMBERS_VIEW;
- }
-
- protected String getLinkToEditorKey() {
- return PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createViewer(org.eclipse.swt.widgets.Composite)
- */
- protected StructuredViewer createViewer(Composite parent) {
- ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI);
- ColoredViewersManager.install(viewer);
- fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaScriptUI.ID_MEMBERS_VIEW);
- return viewer;
- }
-
- protected void fillToolBar(IToolBarManager tbm) {
- tbm.add(new LexicalSortingAction(getViewer(), JavaScriptUI.ID_MEMBERS_VIEW));
- fMemberFilterActionGroup.contributeToToolBar(tbm);
- super.fillToolBar(tbm);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#fillActionBars(org.eclipse.ui.IActionBars)
- *
- */
- protected void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- fCategoryFilterActionGroup= new CategoryFilterActionGroup(getViewer(), getViewSite().getId(), getCategoryFilterActionGroupInput());
- fCategoryFilterActionGroup.contributeToViewMenu(actionBars.getMenuManager());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#setInput(java.lang.Object)
- *
- */
- protected void setInput(Object input) {
- super.setInput(input);
- if (fCategoryFilterActionGroup != null)
- fCategoryFilterActionGroup.setInput(getCategoryFilterActionGroupInput());
- }
-
- private IJavaScriptElement[] getCategoryFilterActionGroupInput() {
- Object input= getInput();
- if (input instanceof IJavaScriptElement)
- return new IJavaScriptElement[] { (IJavaScriptElement)input };
- return new IJavaScriptElement[0];
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * input for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid input
- */
- protected boolean isValidInput(Object element) {
- if (element instanceof IType) {
- IType type= (IType)element;
- return type.isBinary() || type.getDeclaringType() == null;
- }
- return false;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * element for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid element
- */
- protected boolean isValidElement(Object element) {
- if (element instanceof IMember)
- return super.isValidElement(((IMember)element).getDeclaringType());
- else if (element instanceof IImportDeclaration)
- return isValidElement(((IJavaScriptElement)element).getParent());
- else if (element instanceof IImportContainer) {
- Object input= getViewer().getInput();
- if (input instanceof IJavaScriptElement) {
- IJavaScriptUnit cu= (IJavaScriptUnit)((IJavaScriptElement)input).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- IJavaScriptUnit importContainerCu= (IJavaScriptUnit)((IJavaScriptElement)element).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- return cu.equals(importContainerCu);
- } else {
- IClassFile cf= (IClassFile)((IJavaScriptElement)input).getAncestor(IJavaScriptElement.CLASS_FILE);
- IClassFile importContainerCf= (IClassFile)((IJavaScriptElement)element).getAncestor(IJavaScriptElement.CLASS_FILE);
- return cf != null && cf.equals(importContainerCf);
- }
- }
- }
- return false;
- }
-
- /**
- * Finds the element which has to be selected in this part.
- *
- * @param je the Java element which has the focus
- * @return the element to select
- */
- protected IJavaScriptElement findElementToSelect(IJavaScriptElement je) {
- if (je == null)
- return null;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.TYPE:
- if (((IType)je).getDeclaringType() == null)
- return null;
- return je;
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.IMPORT_CONTAINER:
- return je;
- case IJavaScriptElement.IMPORT_DECLARATION:
- IJavaScriptUnit cu= (IJavaScriptUnit)je.getParent().getParent();
- try {
- if (cu.getImports()[0].equals(je)) {
- Object selectedElement= getSingleElementFromSelection(getViewer().getSelection());
- if (selectedElement instanceof IImportContainer)
- return (IImportContainer)selectedElement;
- }
- } catch (JavaScriptModelException ex) {
- // return je;
- }
- return je;
- }
- return null;
- }
-
- /**
- * Finds the closest Java element which can be used as input for
- * this part and has the given Java element as child.
- *
- * @param je the Java element for which to search the closest input
- * @return the closest Java element used as input for this part, or <code>null</code>
- */
- protected IJavaScriptElement findInputForJavaElement(IJavaScriptElement je) {
- if (je == null || !je.exists() || (je.getJavaScriptProject() != null && !je.getJavaScriptProject().isOnIncludepath(je)))
- return null;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.TYPE:
- IType type= ((IType)je).getDeclaringType();
- if (type == null)
- return je;
- else
- return findInputForJavaElement(type);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return getTypeForCU((IJavaScriptUnit)je);
- case IJavaScriptElement.CLASS_FILE:
- return findInputForJavaElement(((IClassFile)je).getType());
- case IJavaScriptElement.IMPORT_DECLARATION:
- return findInputForJavaElement(je.getParent());
- case IJavaScriptElement.IMPORT_CONTAINER:
- IJavaScriptElement parent= je.getParent();
- if (parent instanceof IJavaScriptUnit) {
- return getTypeForCU((IJavaScriptUnit)parent);
- }
- else if (parent instanceof IClassFile)
- return findInputForJavaElement(parent);
- return null;
- default:
- if (je instanceof IMember)
- return findInputForJavaElement(((IMember)je).getDeclaringType());
- }
- return null;
- }
-
- /*
- * Implements method from IViewPart.
- */
- public void saveState(IMemento memento) {
- super.saveState(memento);
- fMemberFilterActionGroup.saveState(memento);
- }
-
- protected void restoreState(IMemento memento) {
- super.restoreState(memento);
- fMemberFilterActionGroup.restoreState(memento);
- getViewer().getControl().setRedraw(false);
- getViewer().refresh();
- getViewer().getControl().setRedraw(true);
- }
-
- protected void hookViewerListeners() {
- super.hookViewerListeners();
- getViewer().addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- TreeViewer viewer= (TreeViewer)getViewer();
- Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
- if (viewer.isExpandable(element))
- viewer.setExpandedState(element, !viewer.getExpandedState(element));
- }
- });
- }
-
- boolean isInputAWorkingCopy() {
- Object input= getViewer().getInput();
- if (input instanceof IJavaScriptElement) {
- IJavaScriptUnit cu= (IJavaScriptUnit)((IJavaScriptElement)input).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null)
- return cu.isWorkingCopy();
- }
- return false;
- }
-
- protected void restoreSelection() {
- IEditorPart editor= getViewSite().getPage().getActiveEditor();
- if (editor != null)
- setSelectionFromEditor(editor);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
- getViewer().refresh();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#dispose()
- */
- public void dispose() {
- if (fMemberFilterActionGroup != null) {
- fMemberFilterActionGroup.dispose();
- fMemberFilterActionGroup= null;
- }
- if (fCategoryFilterActionGroup != null) {
- fCategoryFilterActionGroup.dispose();
- fCategoryFilterActionGroup= null;
- }
- super.dispose();
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackageViewerWrapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackageViewerWrapper.java
deleted file mode 100644
index 7e810c3b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackageViewerWrapper.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.events.HelpListener;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-
-/**
- * Wrapper who transfers listeners and filters and to which clients
- * can refer.
- *
- * @deprecated needs to be replaced by a manager who handles transfer of listeners and filters
- */
-class PackageViewerWrapper extends StructuredViewer {
-
- private StructuredViewer fViewer;
- private ListenerList fListenerList;
- private ListenerList fSelectionChangedListenerList;
- private ListenerList fPostSelectionChangedListenerList;
-
- public PackageViewerWrapper() {
- fListenerList= new ListenerList(ListenerList.IDENTITY);
- fPostSelectionChangedListenerList= new ListenerList(ListenerList.IDENTITY);
- fSelectionChangedListenerList= new ListenerList(ListenerList.IDENTITY);
- }
-
- public void setViewer(StructuredViewer viewer) {
- Assert.isNotNull(viewer);
-
- StructuredViewer oldViewer= fViewer;
- fViewer= viewer;
-
- if (fViewer.getContentProvider() != null)
- super.setContentProvider(fViewer.getContentProvider());
- transferFilters(oldViewer);
- transferListeners();
- }
-
- StructuredViewer getViewer(){
- return fViewer;
- }
-
- private void transferFilters(StructuredViewer oldViewer) {
- //set filters
- if (oldViewer != null) {
- ViewerFilter[] filters= oldViewer.getFilters();
- for (int i= 0; i < filters.length; i++) {
- ViewerFilter filter= filters[i];
- fViewer.addFilter(filter);
- }
- }
- }
-
- private void transferListeners() {
-
- Object[] listeners= fPostSelectionChangedListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- Object object= listeners[i];
- ISelectionChangedListener listener= (ISelectionChangedListener)object;
- fViewer.addPostSelectionChangedListener(listener);
- }
-
- listeners= fSelectionChangedListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- Object object= listeners[i];
- ISelectionChangedListener listener= (ISelectionChangedListener)object;
- fViewer.addSelectionChangedListener(listener);
- }
-
- // Add all other listeners
- listeners= fListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- Object object= listeners[i];
-
- if (object instanceof IOpenListener) {
- IOpenListener listener= (IOpenListener) object;
- addOpenListener(listener);
- } else if (object instanceof HelpListener) {
- HelpListener listener= (HelpListener) object;
- addHelpListener(listener);
- } else if (object instanceof IDoubleClickListener) {
- IDoubleClickListener listener= (IDoubleClickListener) object;
- addDoubleClickListener(listener);
- }
- }
- }
-
- public void setSelection(ISelection selection, boolean reveal) {
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection sel= (IStructuredSelection) selection;
-
- //try and give the two a common super class
- IContentProvider provider= getContentProvider();
- if (provider instanceof LogicalPackagesProvider) {
- LogicalPackagesProvider fprovider= (LogicalPackagesProvider) provider;
-
- Object object= sel.getFirstElement();
- if (object instanceof IPackageFragment) {
- IPackageFragment pkgFragment= (IPackageFragment)object;
- LogicalPackage logicalPkg= fprovider.findLogicalPackage(pkgFragment);
- if (logicalPkg != null)
- object= logicalPkg;
- else
- object= pkgFragment;
- }
- if (object != null)
- fViewer.setSelection(new StructuredSelection(object), reveal);
- else
- fViewer.setSelection(StructuredSelection.EMPTY, reveal);
- }
- } else
- fViewer.setSelection(selection, reveal);
- }
-
- public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
- fPostSelectionChangedListenerList.add(listener);
- fViewer.addPostSelectionChangedListener(listener);
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- fSelectionChangedListenerList.add(listener);
- fViewer.addSelectionChangedListener(listener);
- }
-
- public void addDoubleClickListener(IDoubleClickListener listener) {
- fViewer.addDoubleClickListener(listener);
- fListenerList.add(listener);
- }
-
- public void addOpenListener(IOpenListener listener) {
- fViewer.addOpenListener(listener);
- fListenerList.add(listener);
- }
-
- public void addHelpListener(HelpListener listener) {
- fViewer.addHelpListener(listener);
- fListenerList.add(listener);
- }
-
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- fViewer.removeSelectionChangedListener(listener);
- fSelectionChangedListenerList.remove(listener);
- }
-
- public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
- fViewer.removePostSelectionChangedListener(listener);
- fPostSelectionChangedListenerList.remove(listener);
- }
-
- public void removeHelpListener(HelpListener listener) {
- fListenerList.remove(listener);
- fViewer.removeHelpListener(listener);
- }
-
- public void removeDoubleClickListener(IDoubleClickListener listener) {
- fViewer.removeDoubleClickListener(listener);
- fListenerList.remove(listener);
- }
-
- public void removeOpenListener(IOpenListener listener) {
- fViewer.removeOpenListener(listener);
- fListenerList.remove(listener);
- }
-
- // --------- simply delegate to wrapped viewer ---------
- public Control getControl() {
- return fViewer.getControl();
- }
-
- public void addFilter(ViewerFilter filter) {
- fViewer.addFilter(filter);
- }
-
- public void setFilters(ViewerFilter[] filters) {
- fViewer.setFilters(filters);
- }
-
- public void refresh() {
- fViewer.refresh();
- }
-
- public void removeFilter(ViewerFilter filter) {
- fViewer.removeFilter(filter);
- }
-
- public ISelection getSelection() {
- return fViewer.getSelection();
- }
-
- public void refresh(boolean updateLabels) {
- fViewer.refresh(updateLabels);
- }
-
- public void refresh(Object element, boolean updateLabels) {
- fViewer.refresh(element, updateLabels);
- }
-
- public void refresh(Object element) {
- fViewer.refresh(element);
- }
-
- public void resetFilters() {
- fViewer.resetFilters();
- }
-
- public void reveal(Object element) {
- fViewer.reveal(element);
- }
-
- public void setContentProvider(IContentProvider contentProvider) {
- fViewer.setContentProvider(contentProvider);
- }
-
- public void setSorter(ViewerSorter sorter) {
- fViewer.setSorter(sorter);
- }
-
- public void setComparator(ViewerComparator comparator) {
- fViewer.setComparator(comparator);
- }
-
- public void setUseHashlookup(boolean enable) {
- fViewer.setUseHashlookup(enable);
- }
-
- public Widget testFindItem(Object element) {
- return fViewer.testFindItem(element);
- }
-
- public void update(Object element, String[] properties) {
- fViewer.update(element, properties);
- }
-
- public void update(Object[] elements, String[] properties) {
- fViewer.update(elements, properties);
- }
-
- public IContentProvider getContentProvider() {
- return fViewer.getContentProvider();
- }
-
- public Object getInput() {
- return fViewer.getInput();
- }
-
- public IBaseLabelProvider getLabelProvider() {
- return fViewer.getLabelProvider();
- }
-
- public void setLabelProvider(IBaseLabelProvider labelProvider) {
- fViewer.setLabelProvider(labelProvider);
- }
-
- public Object getData(String key) {
- return fViewer.getData(key);
- }
-
- public Item scrollDown(int x, int y) {
- return fViewer.scrollDown(x, y);
- }
-
- public Item scrollUp(int x, int y) {
- return fViewer.scrollUp(x, y);
- }
-
- public void setData(String key, Object value) {
- fViewer.setData(key, value);
- }
-
- public void setSelection(ISelection selection) {
- fViewer.setSelection(selection);
- }
-
- public boolean equals(Object obj) {
- return fViewer.equals(obj);
- }
-
- public int hashCode() {
- return fViewer.hashCode();
- }
-
- public String toString() {
- return fViewer.toString();
- }
-
- public void setViewerInput(Object input){
- fViewer.setInput(input);
- }
-
- // need to provide implementation for abstract methods
- protected Widget doFindInputItem(Object element) {
- return ((IPackagesViewViewer)fViewer).doFindInputItem(element);
- }
-
- protected Widget doFindItem(Object element) {
- return ((IPackagesViewViewer)fViewer).doFindItem(element);
- }
-
- protected void doUpdateItem(Widget item, Object element, boolean fullMap) {
- ((IPackagesViewViewer)fViewer).doUpdateItem(item, element, fullMap);
- }
-
- protected List getSelectionFromWidget() {
- return ((IPackagesViewViewer)fViewer).getSelectionFromWidget();
- }
-
- protected void internalRefresh(Object element) {
- ((IPackagesViewViewer)fViewer).internalRefresh(element);
- }
-
- protected void setSelectionToWidget(List l, boolean reveal) {
- ((IPackagesViewViewer)fViewer).setSelectionToWidget(l, reveal);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesView.java
deleted file mode 100644
index 498c0d62..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesView.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.MultiActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectAllAction;
-import org.eclipse.wst.jsdt.internal.ui.filters.NonJavaElementFilter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.LibraryFilter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTableViewer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-public class PackagesView extends JavaBrowsingPart{
-
- private static final String TAG_VIEW_STATE= ".viewState"; //$NON-NLS-1$
- private static final int LIST_VIEW_STATE= 0;
- private static final int TREE_VIEW_STATE= 1;
-
-
- private static class StatusBarUpdater4LogicalPackage extends StatusBarUpdater {
-
- private StatusBarUpdater4LogicalPackage(IStatusLineManager statusLineManager) {
- super(statusLineManager);
- }
-
- protected String formatMessage(ISelection sel) {
- if (sel instanceof IStructuredSelection) {
- IStructuredSelection selection= (IStructuredSelection)sel;
- int nElements= selection.size();
- Object elem= selection.getFirstElement();
- if (nElements == 1 && (elem instanceof LogicalPackage))
- return formatLogicalPackageMessage((LogicalPackage) elem);
- }
- return super.formatMessage(sel);
- }
-
- private String formatLogicalPackageMessage(LogicalPackage logicalPackage) {
- IPackageFragment[] fragments= logicalPackage.getFragments();
- StringBuffer buf= new StringBuffer(logicalPackage.getElementName());
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- String message= ""; //$NON-NLS-1$
- boolean firstTime= true;
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- IJavaScriptElement element= fragment.getParent();
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) element;
- String label= JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.DEFAULT_QUALIFIED | JavaScriptElementLabels.ROOT_QUALIFIED);
- if (firstTime) {
- buf.append(label);
- firstTime= false;
- }
- else
- message= Messages.format(JavaBrowsingMessages.StatusBar_concat, new String[] {message, label});
- }
- }
- buf.append(message);
- return buf.toString();
- }
- }
-
-
- private SelectAllAction fSelectAllAction;
-
- private int fCurrViewState;
-
- private PackageViewerWrapper fWrappedViewer;
-
- private MultiActionGroup fSwitchActionGroup;
- private boolean fLastInputWasProject;
-
- /**
- * Adds filters the viewer of this part.
- */
- protected void addFilters() {
- super.addFilters();
- getViewer().addFilter(createNonJavaElementFilter());
- getViewer().addFilter(new LibraryFilter());
- }
-
-
- /**
- * Creates new NonJavaElementFilter and overrides method select to allow for
- * LogicalPackages.
- * @return NonJavaElementFilter
- */
- protected NonJavaElementFilter createNonJavaElementFilter() {
- return new NonJavaElementFilter(){
- public boolean select(Viewer viewer, Object parent, Object element){
- return ((element instanceof IJavaScriptElement) || (element instanceof LogicalPackage) || (element instanceof IFolder));
- }
- };
- }
-
- public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
- //this must be created before all actions and filters
- fWrappedViewer= new PackageViewerWrapper();
- restoreLayoutState(memento);
- }
-
- private void restoreLayoutState(IMemento memento) {
- if (memento == null) {
- //read state from the preference store
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- fCurrViewState= store.getInt(this.getViewSite().getId() + TAG_VIEW_STATE);
- } else {
- //restore from memento
- Integer integer= memento.getInteger(this.getViewSite().getId() + TAG_VIEW_STATE);
- if ((integer == null) || !isValidState(integer.intValue())) {
- fCurrViewState= LIST_VIEW_STATE;
- } else fCurrViewState= integer.intValue();
- }
- }
-
- private boolean isValidState(int state) {
- return (state==LIST_VIEW_STATE) || (state==TREE_VIEW_STATE);
- }
-
-
-
- /*
- * @see org.eclipse.ui.IViewPart#saveState(org.eclipse.ui.IMemento)
- */
- public void saveState(IMemento memento) {
- super.saveState(memento);
- memento.putInteger(this.getViewSite().getId()+TAG_VIEW_STATE,fCurrViewState);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createViewer(org.eclipse.swt.widgets.Composite)
- */
- protected StructuredViewer createViewer(Composite parent) {
- //Creates the viewer of this part dependent on the current layout.
- StructuredViewer viewer;
- if(isInListState())
- viewer= createTableViewer(parent);
- else
- viewer= createTreeViewer(parent);
-
- fWrappedViewer.setViewer(viewer);
- return fWrappedViewer;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
- }
- };
- }
- return super.getAdapter(key);
- }
-
- protected boolean isInListState() {
- return fCurrViewState== LIST_VIEW_STATE;
- }
-
- private ProblemTableViewer createTableViewer(Composite parent) {
- return new PackagesViewTableViewer(parent, SWT.MULTI);
- }
-
- private ProblemTreeViewer createTreeViewer(Composite parent) {
- return new PackagesViewTreeViewer(parent, SWT.MULTI);
- }
-
- /**
- * Overrides the createContentProvider from JavaBrowsingPart
- * Creates the content provider of this part.
- */
- protected IContentProvider createContentProvider() {
- if(isInListState())
- return new PackagesViewFlatContentProvider(fWrappedViewer.getViewer());
- else return new PackagesViewHierarchicalContentProvider(fWrappedViewer.getViewer());
- }
-
- protected JavaUILabelProvider createLabelProvider() {
- if(isInListState())
- return createListLabelProvider();
- else return createTreeLabelProvider();
- }
-
- private JavaUILabelProvider createTreeLabelProvider() {
- return new PackagesViewLabelProvider(PackagesViewLabelProvider.HIERARCHICAL_VIEW_STATE);
- }
-
- private JavaUILabelProvider createListLabelProvider() {
- return new PackagesViewLabelProvider(PackagesViewLabelProvider.FLAT_VIEW_STATE);
- }
-
- /**
- * Returns the context ID for the Help system
- *
- * @return the string used as ID for the Help context
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.PACKAGES_BROWSING_VIEW;
- }
-
- protected String getLinkToEditorKey() {
- return PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * input for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid input
- */
- protected boolean isValidInput(Object element) {
- if (element instanceof IJavaScriptProject || (element instanceof IPackageFragmentRoot && ((IJavaScriptElement)element).getElementName() != IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
- try {
- IJavaScriptProject jProject= ((IJavaScriptElement)element).getJavaScriptProject();
- if (jProject != null)
- return jProject.getProject().hasNature(JavaScriptCore.NATURE_ID);
- } catch (CoreException ex) {
- return false;
- }
- return false;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * element for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid element
- */
- protected boolean isValidElement(Object element) {
- if (element instanceof IPackageFragment) {
- IJavaScriptElement parent= ((IPackageFragment)element).getParent();
- if (parent != null)
- return super.isValidElement(parent) || super.isValidElement(parent.getJavaScriptProject());
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#findElementToSelect(org.eclipse.wst.jsdt.core.IJavaScriptElement)
- */
- protected IJavaScriptElement findElementToSelect(IJavaScriptElement je) {
- if (je == null)
- return null;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return je;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return ((IJavaScriptUnit)je).getParent();
- case IJavaScriptElement.CLASS_FILE:
- return ((IClassFile)je).getParent();
- case IJavaScriptElement.TYPE:
- return ((IType)je).getPackageFragment();
- default:
- return findElementToSelect(je.getParent());
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#setInput(java.lang.Object)
- */
- protected void setInput(Object input) {
- setViewerWrapperInput(input);
- super.updateTitle();
- }
-
- private void setViewerWrapperInput(Object input) {
- fWrappedViewer.setViewerInput(input);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#fillActionBars(org.eclipse.ui.IActionBars)
- */
- protected void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- fSwitchActionGroup.fillActionBars(actionBars);
- }
-
-
-
- private void setUpViewer(StructuredViewer viewer){
- Assert.isTrue(viewer != null);
-
- JavaUILabelProvider labelProvider= createLabelProvider();
- viewer.setLabelProvider(createDecoratingLabelProvider(labelProvider));
-
- viewer.setComparator(createJavaElementComparator());
- viewer.setUseHashlookup(true);
-
- createContextMenu();
-
- //disapears when control disposed
- addKeyListener();
-
- //this methods only adds listeners to the viewer,
- //these listenters disapear when the viewer is disposed
- hookViewerListeners();
-
- // Set content provider
- viewer.setContentProvider(createContentProvider());
- //Disposed when viewer's Control is disposed
- initDragAndDrop();
-
- }
-
- //alter sorter to include LogicalPackages
- protected JavaScriptElementComparator createJavaElementComparator() {
- return new JavaScriptElementComparator(){
- public int category(Object element) {
- if (element instanceof LogicalPackage) {
- LogicalPackage cp= (LogicalPackage) element;
- return super.category(cp.getFragments()[0]);
- } else return super.category(element);
- }
- public int compare(Viewer viewer, Object e1, Object e2){
- if (e1 instanceof LogicalPackage) {
- LogicalPackage cp= (LogicalPackage) e1;
- e1= cp.getFragments()[0];
- }
- if (e2 instanceof LogicalPackage) {
- LogicalPackage cp= (LogicalPackage) e2;
- e2= cp.getFragments()[0];
- }
- return super.compare(viewer, e1, e2);
- }
- };
- }
-
- protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
- return new StatusBarUpdater4LogicalPackage(slManager);
- }
-
- protected void setSiteSelectionProvider(){
- getSite().setSelectionProvider(fWrappedViewer);
- }
-
- void adjustInputAndSetSelection(Object o) {
- if (!(o instanceof LogicalPackage)) {
- super.adjustInputAndSetSelection(o);
- return;
- }
-
- LogicalPackage lp= (LogicalPackage)o;
- if (!lp.getJavaProject().equals(getInput()))
- setInput(lp.getJavaProject());
-
- setSelection(new StructuredSelection(lp), true);
- }
-
- //do the same thing as the JavaBrowsingPart but with wrapper
- protected void createActions() {
- super.createActions();
-
- createSelectAllAction();
-
- //create the switch action group
- fSwitchActionGroup= createSwitchActionGroup();
- }
-
- private MultiActionGroup createSwitchActionGroup(){
-
- LayoutAction switchToFlatViewAction= new LayoutAction(JavaBrowsingMessages.PackagesView_flatLayoutAction_label,LIST_VIEW_STATE);
- LayoutAction switchToHierarchicalViewAction= new LayoutAction(JavaBrowsingMessages.PackagesView_HierarchicalLayoutAction_label, TREE_VIEW_STATE);
- JavaPluginImages.setLocalImageDescriptors(switchToFlatViewAction, "flatLayout.gif"); //$NON-NLS-1$
- JavaPluginImages.setLocalImageDescriptors(switchToHierarchicalViewAction, "hierarchicalLayout.gif"); //$NON-NLS-1$
-
- return new LayoutActionGroup(new IAction[]{switchToFlatViewAction,switchToHierarchicalViewAction}, fCurrViewState);
- }
-
- private static class LayoutActionGroup extends MultiActionGroup {
-
- LayoutActionGroup(IAction[] actions, int index) {
- super(actions, index);
- }
-
- public void fillActionBars(IActionBars actionBars) {
- //create new layout group
- IMenuManager manager= actionBars.getMenuManager();
- final IContributionItem groupMarker= new GroupMarker("layout"); //$NON-NLS-1$
- manager.add(groupMarker);
- IMenuManager newManager= new MenuManager(JavaBrowsingMessages.PackagesView_LayoutActionGroup_layout_label);
- manager.appendToGroup("layout", newManager); //$NON-NLS-1$
- super.addActions(newManager);
- }
- }
-
-
- /**
- * Switches between flat and hierarchical state.
- */
- private class LayoutAction extends Action {
-
- private int fState;
-
- public LayoutAction(String text, int state) {
- super(text, IAction.AS_RADIO_BUTTON);
- fState= state;
- if (state == PackagesView.LIST_VIEW_STATE)
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_FLAT_ACTION);
- else
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_HIERARCHICAL_ACTION);
- }
-
- public int getState() {
- return fState;
- }
-
- public void setRunnable(Runnable runnable) {
- Assert.isNotNull(runnable);
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- switchViewer(fState);
- }
- }
-
- private void switchViewer(int state) {
- //Indicate which viewer is to be used
- if (fCurrViewState == state)
- return;
- else {
- fCurrViewState= state;
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- store.setValue(getViewSite().getId() + TAG_VIEW_STATE, state);
- }
-
- //get the information from the existing viewer
- StructuredViewer viewer= fWrappedViewer.getViewer();
- Object object= viewer.getInput();
- ISelection selection= viewer.getSelection();
-
- // create and set up the new viewer
- Control control= createViewer(fWrappedViewer.getControl().getParent()).getControl();
-
- setUpViewer(fWrappedViewer);
-
- createSelectAllAction();
-
- // add the selection information from old viewer
- fWrappedViewer.setViewerInput(object);
- fWrappedViewer.getControl().setFocus();
- fWrappedViewer.setSelection(selection, true);
-
- // dispose old viewer
- viewer.getContentProvider().dispose();
- viewer.getControl().dispose();
-
- // layout the new viewer
- if (control != null && !control.isDisposed()) {
- control.setVisible(true);
- control.getParent().layout(true);
- }
- }
-
- private void createSelectAllAction() {
- IActionBars actionBars= getViewSite().getActionBars();
- if (isInListState()) {
- fSelectAllAction= new SelectAllAction((TableViewer)fWrappedViewer.getViewer());
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
- } else {
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
- fSelectAllAction= null;
- }
- actionBars.updateActionBars();
- }
-
- protected IJavaScriptElement findInputForJavaElement(IJavaScriptElement je) {
- // null check has to take place here as well (not only in
- // findInputForJavaElement(IJavaScriptElement, boolean) since we
- // are accessing the Java element
- if (je == null)
- return null;
- if(je.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT || je.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT)
- return findInputForJavaElement(je, true);
- else
- return findInputForJavaElement(je, false);
-
- }
-
- protected IJavaScriptElement findInputForJavaElement(IJavaScriptElement je, boolean canChangeInputType) {
- if (je == null || !je.exists())
- return null;
-
- if (isValidInput(je)) {
-
- //don't update if input must be project (i.e. project is used as source folder)
- if (canChangeInputType)
- fLastInputWasProject= je.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT;
- return je;
- } else if (fLastInputWasProject) {
- IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot)je.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (!packageFragmentRoot.isExternal())
- return je.getJavaScriptProject();
- }
-
- return findInputForJavaElement(je.getParent(), canChangeInputType);
- }
-
- /**
- * Override the getText and getImage methods for the DecoratingLabelProvider
- * to handel the decoration of logical packages.
- *
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createDecoratingLabelProvider(JavaUILabelProvider)
- */
- protected DecoratingJavaLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
- return new DecoratingJavaLabelProvider(provider, false, isInListState()) {
-
- public String getText(Object element){
- if (element instanceof LogicalPackage) {
- LogicalPackage el= (LogicalPackage) element;
- return super.getText(el.getFragments()[0]);
- } else return super.getText(element);
- }
-
- public Image getImage(Object element) {
- if(element instanceof LogicalPackage){
- LogicalPackage el= (LogicalPackage) element;
- ILabelDecorator decorator= getLabelDecorator();
- IPackageFragment[] fragments= el.getFragments();
-
- Image image= super.getImage(el);
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- Image decoratedImage= decorator.decorateImage(image, fragment);
- if(decoratedImage != null)
- image= decoratedImage;
- }
- return image;
- } else return super.getImage(element);
- }
-
- };
- }
-
- /*
- * Overridden from JavaBrowsingPart to handel LogicalPackages and tree
- * structure.
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#adjustInputAndSetSelection(org.eclipse.wst.jsdt.core.IJavaScriptElement)
- */
- void adjustInputAndSetSelection(IJavaScriptElement je) {
-
- IJavaScriptElement jElementToSelect= findElementToSelect(je);
- LogicalPackagesProvider p= (LogicalPackagesProvider) fWrappedViewer.getContentProvider();
-
- Object elementToSelect= jElementToSelect;
- if (jElementToSelect != null && jElementToSelect.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
- IPackageFragment pkgFragment= (IPackageFragment)jElementToSelect;
- elementToSelect= p.findLogicalPackage(pkgFragment);
- if (elementToSelect == null)
- elementToSelect= pkgFragment;
- }
-
- IJavaScriptElement newInput= findInputForJavaElement(je);
- if (elementToSelect == null && !isValidInput(newInput))
- setInput(null);
- else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) {
-
- //optimization, if you are in the same project but expansion hasn't happened
- Object input= getViewer().getInput();
- if (elementToSelect != null && newInput != null) {
- if (newInput.equals(input)) {
- getViewer().reveal(elementToSelect);
- // Adjust input to selection
- } else {
- setInput(newInput);
- getViewer().reveal(elementToSelect);
- }
- } else
- setInput(newInput);
-
- if (elementToSelect instanceof IPackageFragment) {
- IPackageFragment pkgFragment= (IPackageFragment)elementToSelect;
- elementToSelect= p.findLogicalPackage(pkgFragment);
- if (elementToSelect == null)
- elementToSelect= pkgFragment;
- }
- }
-
- ISelection selection;
- if (elementToSelect != null)
- selection= new StructuredSelection(elementToSelect);
- else
- selection= StructuredSelection.EMPTY;
- setSelection(selection, true);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewFlatContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewFlatContentProvider.java
deleted file mode 100644
index 1ff94b3b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewFlatContentProvider.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Table content provider for the hierarchical layout in the packages view.
- * <p>
- * XXX: The standard Java browsing part content provider needs and calls
- * the browsing part/view. This class currently doesn't need to do so
- * but might be required to later.
- * </p>
- */
-class PackagesViewFlatContentProvider extends LogicalPackagesProvider implements IStructuredContentProvider {
- PackagesViewFlatContentProvider(StructuredViewer viewer) {
- super(viewer);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
- */
- public Object[] getChildren(Object parentElement) {
-
- if(parentElement instanceof IJavaScriptElement){
- IJavaScriptElement element= (IJavaScriptElement) parentElement;
-
- int type= element.getElementType();
-
- try {
- switch (type) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- IJavaScriptProject project= (IJavaScriptProject) element;
- IPackageFragment[] children= getPackageFragments(project.getPackageFragments());
- if(isInCompoundState()) {
- fMapToLogicalPackage.clear();
- fMapToPackageFragments.clear();
- return combineSamePackagesIntoLogialPackages(children);
- } else
- return children;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- fMapToLogicalPackage.clear();
- fMapToPackageFragments.clear();
- IPackageFragmentRoot root= (IPackageFragmentRoot) element;
- return root.getChildren();
-
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- //no children in flat view
- break;
-
- default :
- //do nothing, empty array returned
- }
- } catch (JavaScriptModelException e) {
- return NO_CHILDREN;
- }
-
- }
- return NO_CHILDREN;
- }
-
- /*
- * Weeds out packageFragments from external jars
- */
- private IPackageFragment[] getPackageFragments(IPackageFragment[] iPackageFragments) {
- List list= new ArrayList();
- for (int i= 0; i < iPackageFragments.length; i++) {
- IPackageFragment fragment= iPackageFragments[i];
- IJavaScriptElement el= fragment.getParent();
- if (el instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) el;
- if(root.isArchive() && root.isExternal())
- continue;
- }
- list.add(fragment);
- }
- return (IPackageFragment[]) list.toArray(new IPackageFragment[list.size()]);
- }
-
- /*
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- protected void processDelta(IJavaScriptElementDelta delta) throws JavaScriptModelException {
-
- int kind= delta.getKind();
- final IJavaScriptElement element= delta.getElement();
-
- if (isClassPathChange(delta)) {
- Object input= fViewer.getInput();
- if (input != null) {
- if (fInputIsProject && input.equals(element.getJavaScriptProject())) {
- postRefresh(input);
- return;
- } else if (!fInputIsProject && input.equals(element)) {
- if (element.exists())
- postRefresh(input);
- else
- postRemove(input);
- return;
- }
- }
- }
-
- if (kind == IJavaScriptElementDelta.REMOVED) {
- Object input= fViewer.getInput();
- if (input != null && input.equals(element)) {
- postRemove(input);
- return;
- }
- }
-
- if (element instanceof IPackageFragment) {
- final IPackageFragment frag= (IPackageFragment) element;
-
- if (kind == IJavaScriptElementDelta.REMOVED) {
- removeElement(frag);
-
- } else if (kind == IJavaScriptElementDelta.ADDED) {
- addElement(frag);
-
- } else if (kind == IJavaScriptElementDelta.CHANGED) {
- //just refresh
- Object toBeRefreshed= element;
-
- IPackageFragment pkgFragment= (IPackageFragment) element;
- LogicalPackage logicalPkg= findLogicalPackage(pkgFragment);
- //deal with packages that have been filtered and are now visible
- if (logicalPkg != null)
- toBeRefreshed= findElementToRefresh(logicalPkg);
- else
- toBeRefreshed= findElementToRefresh(pkgFragment);
-
- postRefresh(toBeRefreshed);
- }
- //in this view there will be no children of PackageFragment to refresh
- return;
- }
- processAffectedChildren(delta);
- }
-
- //test to see if element to be refreshed is being filtered out
- //and if so refresh the viewers input element (JavaProject or PackageFragmentRoot)
- private Object findElementToRefresh(IPackageFragment fragment) {
- if (fViewer.testFindItem(fragment) == null) {
- if(fInputIsProject)
- return fragment.getJavaScriptProject();
- else return fragment.getParent();
- }
- return fragment;
- }
-
- //test to see if element to be refreshed is being filtered out
- //and if so refresh the viewers input element (JavaProject or PackageFragmentRoot)
- private Object findElementToRefresh(LogicalPackage logicalPackage) {
- if (fViewer.testFindItem(logicalPackage) == null) {
- IPackageFragment fragment= logicalPackage.getFragments()[0];
- return fragment.getJavaScriptProject();
- }
- return logicalPackage;
- }
-
-
- private void processAffectedChildren(IJavaScriptElementDelta delta) throws JavaScriptModelException {
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElementDelta elementDelta= children[i];
- processDelta(elementDelta);
- }
- }
-
- private void postAdd(final Object child) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl = fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ((TableViewer)fViewer).add(child);
- }
- }
- });
- }
-
-
- private void postRemove(final Object object) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl = fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ((TableViewer)fViewer).remove(object);
- }
- }
- });
- }
-
- private void postRunnable(final Runnable r) {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- // fBrowsingPart.setProcessSelectionEvents(false);
- try {
- Display currentDisplay= Display.getCurrent();
- if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
- ctrl.getDisplay().syncExec(r);
- else
- ctrl.getDisplay().asyncExec(r);
- } finally {
- // fBrowsingPart.setProcessSelectionEvents(true);
- }
- }
- }
-
- private void removeElement(IPackageFragment frag) {
- String key= getKey(frag);
- LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
-
- if(lp != null){
- lp.remove(frag);
- //if you need to change the LogicalPackage to a PackageFragment
- if(lp.getFragments().length == 1){
- IPackageFragment fragment= lp.getFragments()[0];
- fMapToLogicalPackage.remove(key);
- fMapToPackageFragments.put(key,fragment);
-
- //@Improve: Should I replace this with a refresh of the parent?
- postRemove(lp);
- postAdd(fragment);
- } return;
- } else {
- fMapToPackageFragments.remove(key);
- postRemove(frag);
- }
- }
-
-
- private void postRefresh(final Object element) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- fViewer.refresh(element);
- }
- }
- });
- }
-
- private void addElement(IPackageFragment frag) {
- String key= getKey(frag);
- LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
-
- if(lp != null && lp.belongs(frag)){
- lp.add(frag);
- return;
- }
-
- IPackageFragment fragment= (IPackageFragment)fMapToPackageFragments.get(key);
- if(fragment != null){
- //must create a new LogicalPackage
- if(!fragment.equals(frag)){
- lp= new LogicalPackage(fragment);
- lp.add(frag);
- fMapToLogicalPackage.put(key, lp);
-
- //@Improve: should I replace this with a refresh?
- postRemove(fragment);
- postAdd(lp);
-
- return;
- }
- }
-
- else {
- fMapToPackageFragments.put(key, frag);
- postAdd(frag);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewHierarchicalContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewHierarchicalContentProvider.java
deleted file mode 100644
index 570dbc6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewHierarchicalContentProvider.java
+++ /dev/null
@@ -1,646 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Tree content provider for the hierarchical layout in the packages view.
- * <p>
- * XXX: The standard Java browsing part content provider needs and calls
- * the browsing part/view. This class currently doesn't need to do so
- * but might be required to later.
- * </p>
- */
-class PackagesViewHierarchicalContentProvider extends LogicalPackagesProvider implements ITreeContentProvider {
-
- public PackagesViewHierarchicalContentProvider(StructuredViewer viewer){
- super(viewer);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- try {
- if (parentElement instanceof IJavaScriptElement) {
- IJavaScriptElement iJavaElement= (IJavaScriptElement) parentElement;
- int type= iJavaElement.getElementType();
-
- switch (type) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- {
-
- //create new element mapping
- fMapToLogicalPackage.clear();
- fMapToPackageFragments.clear();
- IJavaScriptProject project= (IJavaScriptProject) parentElement;
-
- IPackageFragment[] topLevelChildren= getTopLevelChildrenByElementName(project.getPackageFragments());
- List list= new ArrayList();
- for (int i= 0; i < topLevelChildren.length; i++) {
- IPackageFragment fragment= topLevelChildren[i];
-
- IJavaScriptElement el= fragment.getParent();
- if (el instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) el;
- if (!root.isArchive() || !root.isExternal())
- list.add(fragment);
- }
- }
-
- IPackageFragmentRoot[] packageFragmentRoots= project.getPackageFragmentRoots();
- List folders= new ArrayList();
- for (int i= 0; i < packageFragmentRoots.length; i++) {
- IPackageFragmentRoot root= packageFragmentRoots[i];
- IResource resource= root.getUnderlyingResource();
- if (resource != null && resource instanceof IFolder) {
- folders.addAll(getFolders(((IFolder)resource).members()));
- }
- }
-
- Object[] logicalPackages= combineSamePackagesIntoLogialPackages((IPackageFragment[]) list.toArray(new IPackageFragment[list.size()]));
- if (folders.size() > 0) {
- if (logicalPackages.length > 0)
- folders.addAll(Arrays.asList(logicalPackages));
- return folders.toArray();
- } else {
- return logicalPackages;
- }
- }
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- {
- IPackageFragmentRoot root= (IPackageFragmentRoot) parentElement;
-
- //create new element mapping
- fMapToLogicalPackage.clear();
- fMapToPackageFragments.clear();
- IResource resource= root.getUnderlyingResource();
- if (root.isArchive()) {
- IPackageFragment[] fragments= new IPackageFragment[0];
- IJavaScriptElement[] els= root.getChildren();
- fragments= getTopLevelChildrenByElementName(els);
- addFragmentsToMap(fragments);
- return fragments;
-
- } else if (resource != null && resource instanceof IFolder) {
- List children= getFoldersAndElements(((IFolder)resource).members());
-
- IPackageFragment defaultPackage= root.getPackageFragment(""); //$NON-NLS-1$
- if(defaultPackage.exists())
- children.add(defaultPackage);
-
- addFragmentsToMap(children);
- return children.toArray();
- } else {
- return NO_CHILDREN;
- }
- }
-
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- {
- IPackageFragment packageFragment= (IPackageFragment) parentElement;
- if (packageFragment.isDefaultPackage())
- return NO_CHILDREN;
-
- IPackageFragmentRoot parent= (IPackageFragmentRoot) packageFragment.getParent();
- IPackageFragment[] fragments= findNextLevelChildrenByElementName(parent, packageFragment);
-
- addFragmentsToMap(fragments);
-
- Object[] nonJavaResources= packageFragment.getNonJavaScriptResources();
- if (nonJavaResources.length == 0) {
- return fragments;
- }
- ArrayList combined= new ArrayList();
- combined.addAll(Arrays.asList(fragments));
- for (int i= 0; i < nonJavaResources.length; i++) {
- Object curr= nonJavaResources[i];
- if (curr instanceof IFolder) {
- combined.add(curr);
- }
- }
- return combined.toArray();
- }
- }
-
- //@Improve: rewrite using concatenate
- } else if (parentElement instanceof LogicalPackage) {
-
- List children= new ArrayList();
- LogicalPackage logicalPackage= (LogicalPackage) parentElement;
- IPackageFragment[] elements= logicalPackage.getFragments();
- for (int i= 0; i < elements.length; i++) {
- IPackageFragment fragment= elements[i];
- IPackageFragment[] objects= findNextLevelChildrenByElementName((IPackageFragmentRoot) fragment.getParent(), fragment);
- children.addAll(Arrays.asList(objects));
- }
- return combineSamePackagesIntoLogialPackages((IPackageFragment[]) children.toArray(new IPackageFragment[children.size()]));
- } else if (parentElement instanceof IFolder) {
- IFolder folder= (IFolder)parentElement;
- IResource[] resources= folder.members();
- List children = getFoldersAndElements(resources);
- addFragmentsToMap(children);
- return children.toArray();
- }
-
- } catch (JavaScriptModelException e) {
- return NO_CHILDREN;
- } catch (CoreException e) {
- return NO_CHILDREN;
- }
- return NO_CHILDREN;
- }
-
- private void addFragmentsToMap(List elements) {
- List packageFragments= new ArrayList();
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object elem= iter.next();
- if (elem instanceof IPackageFragment)
- packageFragments.add(elem);
- }
- addFragmentsToMap((IPackageFragment[])packageFragments.toArray(new IPackageFragment[packageFragments.size()]));
- }
-
- private List getFoldersAndElements(IResource[] resources) throws CoreException {
- List list= new ArrayList();
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
-
- if (resource instanceof IFolder) {
- IFolder folder= (IFolder) resource;
- IJavaScriptElement element= JavaScriptCore.create(folder);
-
- if (element instanceof IPackageFragment) {
- list.add(element);
- } else {
- list.add(folder);
- }
- }
- }
- return list;
- }
-
- private List getFolders(IResource[] resources) throws CoreException {
- List list= new ArrayList();
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
-
- if (resource instanceof IFolder) {
- IFolder folder= (IFolder) resource;
- IJavaScriptElement element= JavaScriptCore.create(folder);
-
- if (element == null) {
- list.add(folder);
- }
- }
- }
- return list;
- }
-
- private IPackageFragment[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) {
- List list= new ArrayList();
- try {
-
- IJavaScriptElement[] children= parent.getChildren();
- String fragmentname= fragment.getElementName();
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElement element= children[i];
- if (element instanceof IPackageFragment) {
- IPackageFragment frag= (IPackageFragment) element;
-
- String name= element.getElementName();
- if (name.length() > fragmentname.length() && name.charAt(fragmentname.length()) == '.' && frag.exists() && !IPackageFragment.DEFAULT_PACKAGE_NAME.equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) {
- String tail= name.substring(fragmentname.length() + 1);
- if (!IPackageFragment.DEFAULT_PACKAGE_NAME.equals(tail) && tail.indexOf('.') == -1) {
- list.add(frag);
- }
- }
- }
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return (IPackageFragment[]) list.toArray(new IPackageFragment[list.size()]);
- }
-
- private IPackageFragment[] getTopLevelChildrenByElementName(IJavaScriptElement[] elements){
- List topLevelElements= new ArrayList();
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement iJavaElement= elements[i];
- //if the name of the PackageFragment is the top level package it will contain no "." separators
- if (iJavaElement instanceof IPackageFragment && iJavaElement.getElementName().indexOf('.')==-1){
- topLevelElements.add(iJavaElement);
- }
- }
- return (IPackageFragment[]) topLevelElements.toArray(new IPackageFragment[topLevelElements.size()]);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
-
- try {
- if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment) element;
- if(!fragment.exists())
- return null;
- Object parent= getHierarchicalParent(fragment);
- if(parent instanceof IPackageFragment) {
- IPackageFragment pkgFragment= (IPackageFragment)parent;
- LogicalPackage logicalPkg= findLogicalPackage(pkgFragment);
- if (logicalPkg != null)
- return logicalPkg;
- else {
- LogicalPackage lp= createLogicalPackage(pkgFragment);
- if(lp == null)
- return pkgFragment;
- else return lp;
- }
- }
- return parent;
-
- } else if(element instanceof LogicalPackage){
- LogicalPackage el= (LogicalPackage) element;
- IPackageFragment fragment= el.getFragments()[0];
- Object parent= getHierarchicalParent(fragment);
-
- if(parent instanceof IPackageFragment){
- IPackageFragment pkgFragment= (IPackageFragment) parent;
- LogicalPackage logicalPkg= findLogicalPackage(pkgFragment);
- if (logicalPkg != null)
- return logicalPkg;
- else {
- LogicalPackage lp= createLogicalPackage(pkgFragment);
- if(lp == null)
- return pkgFragment;
- else return lp;
- }
- } else
- return fragment.getJavaScriptProject();
- } else if (element instanceof IFolder) {
- IFolder folder = (IFolder) element;
- IResource res = folder.getParent();
-
- IJavaScriptElement el = JavaScriptCore.create(res);
- if (el != null) {
- return el;
- } else {
- return res;
- }
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- /*
- * Check if the given IPackageFragment should be the member of a
- * LogicalPackage and if so creates the LogicalPackage and adds it to the
- * map.
- */
- private LogicalPackage createLogicalPackage(IPackageFragment pkgFragment) {
- if(!fInputIsProject)
- return null;
-
- List fragments= new ArrayList();
- try {
- IPackageFragmentRoot[] roots= pkgFragment.getJavaScriptProject().getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- IPackageFragment fragment= root.getPackageFragment(pkgFragment.getElementName());
- if(fragment.exists() && !fragment.equals(pkgFragment))
- fragments.add(fragment);
- }
- if(!fragments.isEmpty()) {
- LogicalPackage logicalPackage= new LogicalPackage(pkgFragment);
- fMapToLogicalPackage.put(getKey(pkgFragment), logicalPackage);
- Iterator iter= fragments.iterator();
- while(iter.hasNext()){
- IPackageFragment f= (IPackageFragment)iter.next();
- if(logicalPackage.belongs(f)){
- logicalPackage.add(f);
- fMapToLogicalPackage.put(getKey(f), logicalPackage);
- }
- }
-
- return logicalPackage;
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- return null;
- }
-
- private Object getHierarchicalParent(IPackageFragment fragment) throws JavaScriptModelException {
- IJavaScriptElement parent= fragment.getParent();
-
- if ((parent instanceof IPackageFragmentRoot) && parent.exists()) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
- if (root.isArchive() || !fragment.exists()) {
- return findNextLevelParentByElementName(fragment);
- } else {
- IResource resource= fragment.getUnderlyingResource();
- if ((resource != null) && (resource instanceof IFolder)) {
- IFolder folder= (IFolder) resource;
- IResource res= folder.getParent();
-
- IJavaScriptElement el= JavaScriptCore.create(res);
- if (el != null) {
- return el;
- } else {
- return res;
- }
- }
- }
- }
- return parent;
- }
-
- private Object findNextLevelParentByElementName(IPackageFragment child) {
- String name= child.getElementName();
-
- int index= name.lastIndexOf('.');
- if (index != -1) {
- String realParentName= name.substring(0, index);
- IPackageFragment element= ((IPackageFragmentRoot) child.getParent()).getPackageFragment(realParentName);
- if (element.exists()) {
- return element;
- }
- }
- return child.getParent();
- }
-
-
- /*
- * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
-
- if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment) element;
- if(fragment.isDefaultPackage() || !fragment.exists())
- return false;
- }
- return getChildren(element).length > 0;
- }
-
- /*
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- protected void processDelta(IJavaScriptElementDelta delta) throws JavaScriptModelException {
-
- int kind = delta.getKind();
- final IJavaScriptElement element = delta.getElement();
-
- if (isClassPathChange(delta)) {
- Object input= fViewer.getInput();
- if (input != null) {
- if (fInputIsProject && input.equals(element.getJavaScriptProject())) {
- postRefresh(input);
- return;
- } else if (!fInputIsProject && input.equals(element)) {
- if (element.exists())
- postRefresh(input);
- else
- postRemove(input);
- return;
- }
- }
- }
-
- if (kind == IJavaScriptElementDelta.REMOVED) {
- Object input= fViewer.getInput();
- if (input != null && input.equals(element)) {
- postRemove(input);
- return;
- }
- }
-
- if (element instanceof IPackageFragment) {
- final IPackageFragment frag = (IPackageFragment) element;
-
- //if fragment was in LogicalPackage refresh,
- //otherwise just remove
- if (kind == IJavaScriptElementDelta.REMOVED) {
- removeElement(frag);
- return;
-
- } else if (kind == IJavaScriptElementDelta.ADDED) {
-
- Object parent= getParent(frag);
- addElement(frag, parent);
- return;
-
- } else if (kind == IJavaScriptElementDelta.CHANGED) {
- //just refresh
- LogicalPackage logicalPkg= findLogicalPackage(frag);
- //in case changed object is filtered out
- if (logicalPkg != null)
- postRefresh(findElementToRefresh(logicalPkg));
- else
- postRefresh(findElementToRefresh(frag));
- return;
- }
- }
-
- processAffectedChildren(delta);
- }
-
- private Object findElementToRefresh(Object object) {
- Object toBeRefreshed= object;
- if (fViewer.testFindItem(object) == null) {
- Object parent= getParent(object);
- if(parent instanceof IPackageFragmentRoot && fInputIsProject)
- parent= ((IPackageFragmentRoot)parent).getJavaScriptProject();
-
- if(parent != null)
- toBeRefreshed= parent;
- }
- return toBeRefreshed;
- }
-
- private void processAffectedChildren(IJavaScriptElementDelta delta) throws JavaScriptModelException {
- IJavaScriptElementDelta[] affectedChildren = delta.getAffectedChildren();
- for (int i = 0; i < affectedChildren.length; i++) {
- if (!(affectedChildren[i] instanceof IJavaScriptUnit)) {
- processDelta(affectedChildren[i]);
- }
- }
- }
-
- private void postAdd(final Object child, final Object parent) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl = fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ((TreeViewer)fViewer).add(parent, child);
- }
- }
- });
- }
-
- private void postRemove(final Object object) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl = fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ((TreeViewer)fViewer).remove(object);
- }
- }
- });
- }
-
- private void postRefresh(final Object object) {
- postRunnable(new Runnable() {
- public void run() {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ((TreeViewer) fViewer).refresh(object);
- }
- }
- });
- }
-
- private void postRunnable(final Runnable r) {
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- // fBrowsingPart.setProcessSelectionEvents(false);
- try {
- Display currentDisplay= Display.getCurrent();
- if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
- ctrl.getDisplay().syncExec(r);
- else
- ctrl.getDisplay().asyncExec(r);
- } finally {
- // fBrowsingPart.setProcessSelectionEvents(true);
- }
- }
- }
-
- private void addElement(IPackageFragment frag, Object parent) {
-
- String key= getKey(frag);
- LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
-
- //if fragment must be added to an existing LogicalPackage
- if (lp != null && lp.belongs(frag)){
- lp.add(frag);
- return;
- }
-
- //if a new LogicalPackage must be created
- IPackageFragment iPackageFragment= (IPackageFragment)fMapToPackageFragments.get(key);
- if (iPackageFragment!= null && !iPackageFragment.equals(frag)){
- lp= new LogicalPackage(iPackageFragment);
- lp.add(frag);
- //add new LogicalPackage to LogicalPackages map
- fMapToLogicalPackage.put(key, lp);
-
- //determine who to refresh
- if (parent instanceof IPackageFragmentRoot){
- IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
- if (fInputIsProject){
- postRefresh(root.getJavaScriptProject());
- } else {
- postRefresh(root);
- }
- } else {
- //@Improve: Should this be replaced by a refresh?
- postAdd(lp, parent);
- postRemove(iPackageFragment);
- }
-
- }
- //if this is a new Package Fragment
- else {
- fMapToPackageFragments.put(key, frag);
-
- //determine who to refresh
- if (parent instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
- if (fInputIsProject) {
- postAdd(frag, root.getJavaScriptProject());
- } else
- postAdd(frag, root);
- } else {
- postAdd(frag, parent);
- }
- }
- }
-
- private void removeElement(IPackageFragment frag) {
-
- String key= getKey(frag);
- LogicalPackage lp= (LogicalPackage)fMapToLogicalPackage.get(key);
-
- if(lp != null){
- lp.remove(frag);
- //if the LogicalPackage needs to revert back to a PackageFragment
- //remove it from the LogicalPackages map and add the PackageFragment
- //to the PackageFragment map
- if (lp.getFragments().length == 1) {
- IPackageFragment fragment= lp.getFragments()[0];
- fMapToPackageFragments.put(key, fragment);
- fMapToLogicalPackage.remove(key);
-
- //remove the LogicalPackage from viewer
- postRemove(lp);
-
- Object parent= getParent(fragment);
- if (parent instanceof IPackageFragmentRoot) {
- parent= ((IPackageFragmentRoot)parent).getJavaScriptProject();
- }
- postAdd(fragment, parent);
- }
-
- } else {
- //remove the fragment from the fragment map and viewer
- IPackageFragment fragment= (IPackageFragment) fMapToPackageFragments.get(key);
- if (fragment!= null && fragment.equals(frag)) {
- fMapToPackageFragments.remove(key);
- postRemove(frag);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewLabelProvider.java
deleted file mode 100644
index baef2409..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewLabelProvider.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.TreeHierarchyLayoutProblemsDecorator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Label provider for the Packages view.
- */
-class PackagesViewLabelProvider extends AppearanceAwareLabelProvider {
-
- static final int HIERARCHICAL_VIEW_STATE= 0;
- static final int FLAT_VIEW_STATE= 1;
-
- private int fViewState;
-
- private ImageDescriptorRegistry fRegistry;
- private TreeHierarchyLayoutProblemsDecorator fDecorator;
-
- PackagesViewLabelProvider(int state) {
- this(state, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS);
- }
-
- PackagesViewLabelProvider(int state, long textFlags, int imageFlags) {
- super(textFlags, imageFlags);
-
- Assert.isTrue(isValidState(state));
- fViewState= state;
- fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
-
- fDecorator= new TreeHierarchyLayoutProblemsDecorator(isFlatView());
- addLabelDecorator(fDecorator);
- }
-
- private boolean isValidState(int state) {
- return state == FLAT_VIEW_STATE || state == HIERARCHICAL_VIEW_STATE;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- if (element instanceof LogicalPackage) {
- LogicalPackage cp= (LogicalPackage) element;
- return getLogicalPackageImage(cp);
- }
- return super.getImage(element);
- }
-
- /*
- * Decoration is only concerned with error ticks
- */
- private Image getLogicalPackageImage(LogicalPackage cp) {
- IPackageFragment[] fragments= cp.getFragments();
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- if(!isEmpty(fragment)) {
- return decorateCompoundElement(JavaPluginImages.DESC_OBJS_LOGICAL_PACKAGE, cp);
- }
- }
- return decorateCompoundElement(JavaPluginImages.DESC_OBJS_EMPTY_LOGICAL_PACKAGE, cp);
- }
-
-
- private Image decorateCompoundElement(ImageDescriptor imageDescriptor, LogicalPackage cp) {
- Image image= fRegistry.get(imageDescriptor);
- return decorateImage(image, cp);
- }
-
- private boolean isEmpty(IPackageFragment fragment) {
- try {
- return (fragment.getJavaScriptUnits().length == 0) && (fragment.getClassFiles().length == 0);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (element instanceof IPackageFragment)
- return getText((IPackageFragment)element);
- else if (element instanceof LogicalPackage)
- return getText((LogicalPackage)element);
- else
- return super.getText(element);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- if (element instanceof IPackageFragment || element instanceof LogicalPackage)
- return new ColoredString(getText(element));
- return super.getRichTextLabel(element);
- }
-
-
- private String getText(IPackageFragment fragment) {
- if (isFlatView())
- return getFlatText(fragment);
- else
- return getHierarchicalText(fragment);
- }
-
- private String getText(LogicalPackage logicalPackage) {
- IPackageFragment[] fragments= logicalPackage.getFragments();
- return getText(fragments[0]);
- }
-
- private String getFlatText(IPackageFragment fragment) {
- return super.getText(fragment);
- }
-
- private boolean isFlatView() {
- return fViewState==FLAT_VIEW_STATE;
- }
-
- private String getHierarchicalText(IPackageFragment fragment) {
- if (fragment.isDefaultPackage()) {
- return super.getText(fragment);
- }
- IResource res= fragment.getResource();
- if(res != null && !(res.getType() == IResource.FILE))
- return decorateText(res.getName(), fragment);
- else
- return decorateText(calculateName(fragment), fragment);
- }
-
- private String calculateName(IPackageFragment fragment) {
-
- String name= fragment.getElementName();
- if (name.indexOf(".") != -1) //$NON-NLS-1$
- name= name.substring(name.lastIndexOf(".") + 1); //$NON-NLS-1$
- return name;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTableViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTableViewer.java
deleted file mode 100644
index 48ce472a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTableViewer.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTableViewer;
-
-/**
- * Special problem table viewer to handle logical packages.
- */
-class PackagesViewTableViewer extends ProblemTableViewer implements IPackagesViewViewer {
-
- public PackagesViewTableViewer(Composite parent, int style) {
- super(parent, style);
- ColoredViewersManager.install(this);
- }
-
- public void mapElement(Object element, Widget item) {
- if (element instanceof LogicalPackage && item instanceof Item) {
- LogicalPackage cp= (LogicalPackage) element;
- IPackageFragment[] fragments= cp.getFragments();
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- fResourceToItemsMapper.addToMap(fragment, (Item)item);
- }
- }
- super.mapElement(element, item);
- }
-
- public void unmapElement(Object element, Widget item) {
- if (element instanceof LogicalPackage && item instanceof Item) {
- LogicalPackage cp= (LogicalPackage) element;
- IPackageFragment[] fragments= cp.getFragments();
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- fResourceToItemsMapper.removeFromMap(fragment, (Item)item);
- }
- }
- super.unmapElement(element, item);
- }
-
- /*
- * @see org.eclipse.jface.viewers.StructuredViewer#getFilteredChildren(java.
- * lang.Object)
- */
- protected Object[] getFilteredChildren(Object parent) {
-
- Object[] result= getRawChildren(parent);
- List list= new ArrayList();
- if (result != null) {
- Object[] toBeFiltered= new Object[1];
- for (int i= 0; i < result.length; i++) {
- Object object= result[i];
- if(object instanceof LogicalPackage) {
- if(selectLogicalPackage((LogicalPackage)object))
- list.add(object);
- } else {
- toBeFiltered[0]= object;
- if (filter(toBeFiltered).length == 1)
- list.add(object);
- }
- }
- }
- return list.toArray();
- }
-
- private boolean selectLogicalPackage(LogicalPackage logicalPackage) {
- return filter(logicalPackage.getFragments()).length > 0;
- }
-
- // --------- see: IPackagesViewViewer ----------
-
- public Widget doFindItem(Object element){
- return super.doFindItem(element);
- }
-
- public Widget doFindInputItem(Object element){
- return super.doFindInputItem(element);
- }
-
- public List getSelectionFromWidget(){
- return super.getSelectionFromWidget();
- }
-
- public void doUpdateItem(Widget item, Object element, boolean fullMap){
- super.doUpdateItem(item, element, fullMap);
- }
-
- public void internalRefresh(Object element){
- super.internalRefresh(element);
- }
-
- public void setSelectionToWidget(List l, boolean reveal){
- super.setSelectionToWidget(l, reveal);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTreeViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTreeViewer.java
deleted file mode 100644
index 78e49e9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PackagesViewTreeViewer.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.List;
-
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-
-/**
- * Special problem tree viewer to handle logical packages.
- */
-public class PackagesViewTreeViewer extends ProblemTreeViewer implements IPackagesViewViewer{
-
- public PackagesViewTreeViewer(Composite parent, int style) {
- super(parent, style);
- ColoredViewersManager.install(this);
- }
-
- /*
- * @see org.eclipse.jface.viewers.StructuredViewer#mapElement(java.lang.Object, org.eclipse.swt.widgets.Widget)
- */
- public void mapElement(Object element, Widget item) {
- if (element instanceof LogicalPackage && item instanceof Item) {
- LogicalPackage cp= (LogicalPackage) element;
- IPackageFragment[] fragments= cp.getFragments();
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- fResourceToItemsMapper.addToMap(fragment, (Item) item);
- }
- }
- super.mapElement(element, item);
- }
-
- /*
- * @see org.eclipse.jface.viewers.StructuredViewer#unmapElement(java.lang.Object, org.eclipse.swt.widgets.Widget)
- */
- public void unmapElement(Object element, Widget item) {
-
- if (element instanceof LogicalPackage && item instanceof Item) {
- LogicalPackage cp= (LogicalPackage) element;
- IPackageFragment[] fragments= cp.getFragments();
- for (int i= 0; i < fragments.length; i++) {
- IPackageFragment fragment= fragments[i];
- fResourceToItemsMapper.removeFromMap((Object)fragment, (Item)item);
- }
- }
- super.unmapElement(element, item);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer#isFiltered(java.lang.Object, java.lang.Object, org.eclipse.jface.viewers.ViewerFilter[])
- */
- protected boolean isFiltered(Object object, Object parent, ViewerFilter[] filters) {
- boolean res= super.isFiltered(object, parent, filters);
- if (res && isEssential(object)) {
- return false;
- }
- return res;
- }
-
- private boolean isEssential(Object object) {
- try {
- if (object instanceof IPackageFragment) {
- IPackageFragment fragment = (IPackageFragment) object;
- if (!fragment.isDefaultPackage() && fragment.hasSubpackages()) {
- return hasFilteredChildren(fragment);
- }
- } else if (object instanceof LogicalPackage) {
- LogicalPackage logicalPackage= (LogicalPackage) object;
- if (!logicalPackage.isDefaultPackage() && logicalPackage.hasSubpackages()) {
- return !hasFilteredChildren(object);
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-
- // --------- see: IPackagesViewViewer ----------
-
- public Widget doFindItem(Object element) {
- return super.doFindItem(element);
- }
-
- public Widget doFindInputItem(Object element) {
- return super.doFindInputItem(element);
- }
-
- public List getSelectionFromWidget() {
- return super.getSelectionFromWidget();
- }
-
- public void doUpdateItem(Widget item, Object element, boolean fullMap){
- super.doUpdateItem(item, element, fullMap);
- }
-
- public void internalRefresh(Object element){
- super.internalRefresh(element);
- }
-
- public void setSelectionToWidget(List l, boolean reveal){
- super.setSelectionToWidget(l, reveal);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PatchedOpenInNewWindowAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PatchedOpenInNewWindowAction.java
deleted file mode 100644
index 3d120a31..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/PatchedOpenInNewWindowAction.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.OpenInNewWindowAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-/*
- * XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
- * This class can be removed once the bug is fixed.
- *
- *
- */
-public class PatchedOpenInNewWindowAction extends OpenInNewWindowAction {
-
- private IWorkbenchWindow fWorkbenchWindow;
-
- public PatchedOpenInNewWindowAction(IWorkbenchWindow window, IAdaptable input) {
- super(window, input);
- fWorkbenchWindow= window;
- }
-
- public void run() {
- JavaBrowsingPerspectiveFactory.setInputFromAction(getSelectedJavaElement());
- try {
- super.run();
- } finally {
- JavaBrowsingPerspectiveFactory.setInputFromAction(null);
- }
- }
-
- private IJavaScriptElement getSelectedJavaElement() {
- if (fWorkbenchWindow.getActivePage() != null) {
- ISelection selection= fWorkbenchWindow.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
- Object selectedElement= ((IStructuredSelection)selection).getFirstElement();
- if (selectedElement instanceof IJavaScriptElement)
- return (IJavaScriptElement)selectedElement;
- if (!(selectedElement instanceof IJavaScriptElement) && selectedElement instanceof IAdaptable)
- return (IJavaScriptElement)((IAdaptable)selectedElement).getAdapter(IJavaScriptElement.class);
- else if (selectedElement instanceof IWorkspace)
- return JavaScriptCore.create(((IWorkspace)selectedElement).getRoot());
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectAndSourceFolderContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectAndSourceFolderContentProvider.java
deleted file mode 100644
index 6bf6417f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectAndSourceFolderContentProvider.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-class ProjectAndSourceFolderContentProvider extends JavaBrowsingContentProvider {
-
- ProjectAndSourceFolderContentProvider(JavaBrowsingPart browsingPart) {
- super(false, browsingPart);
- }
-
- /* (non-Javadoc)
- * Method declared on ITreeContentProvider.
- */
- public Object[] getChildren(Object element) {
- if (!exists(element))
- return NO_CHILDREN;
-
- try {
- startReadInDisplayThread();
- if (element instanceof IStructuredSelection) {
- Assert.isLegal(false);
- Object[] result= new Object[0];
- Class clazz= null;
- Iterator iter= ((IStructuredSelection)element).iterator();
- while (iter.hasNext()) {
- Object item= iter.next();
- if (clazz == null)
- clazz= item.getClass();
- if (clazz == item.getClass())
- result= concatenate(result, getChildren(item));
- else
- return NO_CHILDREN;
- }
- return result;
- }
- if (element instanceof IStructuredSelection) {
- Assert.isLegal(false);
- Object[] result= new Object[0];
- Iterator iter= ((IStructuredSelection)element).iterator();
- while (iter.hasNext())
- result= concatenate(result, getChildren(iter.next()));
- return result;
- }
- if (element instanceof IJavaScriptProject)
- return getPackageFragmentRoots((IJavaScriptProject)element);
- if (element instanceof IPackageFragmentRoot)
- return NO_CHILDREN;
-
- return super.getChildren(element);
-
- } catch (JavaScriptModelException e) {
- return NO_CHILDREN;
- } finally {
- finishedReadInDisplayThread();
- }
- }
-
- protected Object[] getPackageFragmentRoots(IJavaScriptProject project) throws JavaScriptModelException {
- if (!project.getProject().isOpen())
- return NO_CHILDREN;
-
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- List list= new ArrayList(roots.length);
- // filter out package fragments that correspond to projects and
- // replace them with the package fragments directly
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (!isProjectPackageFragmentRoot(root))
- list.add(root);
- }
- return list.toArray();
- }
-
- /*
- *
- * @see ITreeContentProvider
- */
- public boolean hasChildren(Object element) {
- return element instanceof IJavaScriptProject && super.hasChildren(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectsView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectsView.java
deleted file mode 100644
index f7b4d960..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ProjectsView.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.Iterator;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.FilterUpdater;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.ProjectActionGroup;
-
-public class ProjectsView extends JavaBrowsingPart {
-
- private FilterUpdater fFilterUpdater;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createViewer(org.eclipse.swt.widgets.Composite)
- */
- protected StructuredViewer createViewer(Composite parent) {
- ProblemTreeViewer result= new ProblemTreeViewer(parent, SWT.MULTI);
- ColoredViewersManager.install(result);
- fFilterUpdater= new FilterUpdater(result);
- ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater);
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#dispose()
- */
- public void dispose() {
- if (fFilterUpdater != null)
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater);
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
- }
-
- };
- }
- return super.getAdapter(key);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createContentProvider()
- */
- protected IContentProvider createContentProvider() {
- return new ProjectAndSourceFolderContentProvider(this);
- }
-
- /**
- * Returns the context ID for the Help system.
- *
- * @return the string used as ID for the Help context
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.PROJECTS_VIEW;
- }
-
- protected String getLinkToEditorKey() {
- return PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR;
- }
-
-
- /**
- * Adds additional listeners to this view.
- */
- protected void hookViewerListeners() {
- super.hookViewerListeners();
- getViewer().addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- TreeViewer viewer= (TreeViewer)getViewer();
- Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
- if (viewer.isExpandable(element))
- viewer.setExpandedState(element, !viewer.getExpandedState(element));
- }
- });
- }
-
- protected void setInitialInput() {
- IJavaScriptElement root= JavaScriptCore.create(JavaScriptPlugin.getWorkspace().getRoot());
- getViewer().setInput(root);
- updateTitle();
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * input for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid input
- */
- protected boolean isValidInput(Object element) {
- return element instanceof IJavaScriptModel;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * element for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid element
- */
- protected boolean isValidElement(Object element) {
- return element instanceof IJavaScriptProject || element instanceof IPackageFragmentRoot;
- }
-
- /**
- * Finds the element which has to be selected in this part.
- *
- * @param je the Java element which has the focus
- * @return the element to select
- */
- protected IJavaScriptElement findElementToSelect(IJavaScriptElement je) {
- if (je == null)
- return null;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- return null;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return je;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- if (je.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH))
- return je.getParent();
- else
- return je;
- default :
- return findElementToSelect(je.getParent());
- }
- }
-
- /*
- * @see JavaBrowsingPart#setInput(Object)
- */
- protected void setInput(Object input) {
- // Don't allow to clear input for this view
- if (input != null)
- super.setInput(input);
- else
- getViewer().setSelection(null);
- }
-
- protected void createActions() {
- super.createActions();
- fActionGroups.addGroup(new ProjectActionGroup(this));
- }
-
- /**
- * Handles selection of LogicalPackage in Packages view.
- *
- * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
- *
- */
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (!needsToProcessSelectionChanged(part, selection))
- return;
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection sel= (IStructuredSelection)selection;
- Iterator iter= sel.iterator();
- while (iter.hasNext()) {
- Object selectedElement= iter.next();
- if (selectedElement instanceof LogicalPackage) {
- selection= new StructuredSelection(((LogicalPackage)selectedElement).getJavaProject());
- break;
- }
- }
- }
- super.selectionChanged(part, selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java
deleted file mode 100644
index 61f385b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.wst.jsdt.internal.ui.actions.AbstractToggleLinkingAction;
-
-
-/**
- * This action toggles whether this package explorer links its selection to the active
- * editor.
- *
- *
- */
-public class ToggleLinkingAction extends AbstractToggleLinkingAction {
-
- JavaBrowsingPart fJavaBrowsingPart;
-
- /**
- * Constructs a new action.
- */
- public ToggleLinkingAction(JavaBrowsingPart part) {
- setChecked(part.isLinkingEnabled());
- fJavaBrowsingPart= part;
- }
-
- /**
- * Runs the action.
- */
- public void run() {
- fJavaBrowsingPart.setLinkingEnabled(isChecked());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java
deleted file mode 100644
index f7011b75..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-
-/**
- * Decorates top-level types with problem markers that
- * are above the first type.
- */
-class TopLevelTypeProblemsLabelDecorator extends ProblemsLabelDecorator {
-
- public TopLevelTypeProblemsLabelDecorator(ImageDescriptorRegistry registry) {
- super(registry);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator#isInside(int, ISourceReference)
- */
- protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
-// XXX: Work in progress for problem decorator being a workbench decorator
-// IDecoratorManager decoratorMgr= PlatformUI.getWorkbench().getDecoratorManager();
-// if (!decoratorMgr.getEnabled("org.eclipse.wst.jsdt.ui.problem.decorator")) //$NON-NLS-1$
-// return false;
-
- if (!(sourceElement instanceof IType) || ((IType)sourceElement).getDeclaringType() != null)
- return false;
-
- IJavaScriptUnit cu= ((IType)sourceElement).getJavaScriptUnit();
- if (cu == null)
- return false;
- IType[] types= cu.getTypes();
- if (types.length < 1)
- return false;
-
- int firstTypeStartOffset= -1;
- ISourceRange range= types[0].getSourceRange();
- if (range != null)
- firstTypeStartOffset= range.getOffset();
-
- int lastTypeEndOffset= -1;
- range= types[types.length-1].getSourceRange();
- if (range != null)
- lastTypeEndOffset= range.getOffset() + range.getLength() - 1;
-
- return pos < firstTypeStartOffset || pos > lastTypeEndOffset || isInside(pos, sourceElement.getSourceRange());
- }
-
- private boolean isInside(int pos, ISourceRange range) {
- if (range == null)
- return false;
- int offset= range.getOffset();
- return offset <= pos && pos < offset + range.getLength();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TypesView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TypesView.java
deleted file mode 100644
index d113b10c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/TypesView.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.browsing;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectAllAction;
-import org.eclipse.wst.jsdt.internal.ui.filters.NonJavaElementFilter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class TypesView extends JavaBrowsingPart {
-
- private SelectAllAction fSelectAllAction;
-
- /**
- * Creates and returns the label provider for this part.
- *
- * @return the label provider
- * @see org.eclipse.jface.viewers.ILabelProvider
- */
- protected JavaUILabelProvider createLabelProvider() {
- return new AppearanceAwareLabelProvider(
- AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.T_CATEGORY,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS);
- }
-
- protected StructuredViewer createViewer(Composite parent) {
- StructuredViewer viewer= super.createViewer(parent);
- ColoredViewersManager.install(viewer);
- return viewer;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
- }
-
- };
- }
- return super.getAdapter(key);
- }
-
- /**
- * Adds filters the viewer of this part.
- */
- protected void addFilters() {
- super.addFilters();
- getViewer().addFilter(new NonJavaElementFilter());
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * input for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid input
- */
- protected boolean isValidInput(Object element) {
- return element instanceof IPackageFragment;
- }
-
- /**
- * Answers if the given <code>element</code> is a valid
- * element for this part.
- *
- * @param element the object to test
- * @return <true> if the given element is a valid element
- */
- protected boolean isValidElement(Object element) {
- if (element instanceof IJavaScriptUnit)
- return super.isValidElement(((IJavaScriptUnit)element).getParent());
- else if (element instanceof IType) {
- IType type= (IType)element;
- return type.getDeclaringType() == null && isValidElement(type.getJavaScriptUnit());
- }
- return false;
- }
-
- /**
- * Finds the element which has to be selected in this part.
- *
- * @param je the Java element which has the focus
- * @return the element to select
- */
- protected IJavaScriptElement findElementToSelect(IJavaScriptElement je) {
- if (je == null)
- return null;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.TYPE:
- IType type= ((IType)je).getDeclaringType();
- if (type == null)
- type= (IType)je;
- return type;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return getTypeForCU((IJavaScriptUnit)je);
- case IJavaScriptElement.CLASS_FILE:
- return findElementToSelect(((IClassFile)je).getType());
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- return findElementToSelect(je.getParent());
- default:
- if (je instanceof IMember)
- return findElementToSelect(((IMember)je).getDeclaringType());
- return null;
-
- }
- }
-
- /**
- * Returns the context ID for the Help system
- *
- * @return the string used as ID for the Help context
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.TYPES_VIEW;
- }
-
- protected String getLinkToEditorKey() {
- return PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR;
- }
-
- protected void createActions() {
- super.createActions();
- fSelectAllAction= new SelectAllAction((TableViewer)getViewer());
- }
-
- protected void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
-
- // Add selectAll action handlers.
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
- }
-
- /**
- * Handles selection of LogicalPackage in Packages view.
- *
- * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
- *
- */
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (!needsToProcessSelectionChanged(part, selection))
- return;
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection sel= (IStructuredSelection) selection;
- Object selectedElement= sel.getFirstElement();
- if (sel.size() == 1 && (selectedElement instanceof LogicalPackage)) {
- IPackageFragment[] fragments= ((LogicalPackage)selectedElement).getFragments();
- List selectedElements= Arrays.asList(fragments);
- if (selectedElements.size() > 1) {
- adjustInput(part, selectedElements);
- fPreviousSelectedElement= selectedElements;
- fPreviousSelectionProvider= part;
- } else if (selectedElements.size() == 1)
- super.selectionChanged(part, new StructuredSelection(selectedElements.get(0)));
- else
- Assert.isLegal(false);
- return;
- }
- }
- super.selectionChanged(part, selection);
- }
-
- private void adjustInput(IWorkbenchPart part, List selectedElements) {
- Object currentInput= getViewer().getInput();
- if (!selectedElements.equals(currentInput))
- setInput(selectedElements);
- }
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.browsing.JavaBrowsingPart#createDecoratingLabelProvider(org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider)
- */
- protected DecoratingJavaLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
- DecoratingJavaLabelProvider decoratingLabelProvider= super.createDecoratingLabelProvider(provider);
- provider.addLabelDecorator(new TopLevelTypeProblemsLabelDecorator(null));
- return decoratingLabelProvider;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyContentProvider.java
deleted file mode 100644
index c53470a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyContentProvider.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.progress.DeferredTreeContentManager;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-public class CallHierarchyContentProvider implements ITreeContentProvider {
- private final static Object[] EMPTY_ARRAY = new Object[0];
-
- private DeferredTreeContentManager fManager;
- private CallHierarchyViewPart fPart;
-
- private class MethodWrapperRunnable implements IRunnableWithProgress {
- private MethodWrapper fMethodWrapper;
- private MethodWrapper[] fCalls= null;
-
- MethodWrapperRunnable(MethodWrapper methodWrapper) {
- fMethodWrapper= methodWrapper;
- }
-
- public void run(IProgressMonitor pm) {
- fCalls= fMethodWrapper.getCalls(pm);
- }
-
- MethodWrapper[] getCalls() {
- if (fCalls != null) {
- return fCalls;
- }
- return new MethodWrapper[0];
- }
- }
-
- public CallHierarchyContentProvider(CallHierarchyViewPart part) {
- super();
- fPart= part;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
- */
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof TreeRoot) {
- TreeRoot dummyRoot = (TreeRoot) parentElement;
-
- return new Object[] { dummyRoot.getRoot() };
- } else if (parentElement instanceof MethodWrapper) {
- MethodWrapper methodWrapper = ((MethodWrapper) parentElement);
-
- if (shouldStopTraversion(methodWrapper)) {
- return EMPTY_ARRAY;
- } else {
- if (fManager != null) {
- Object[] children = fManager.getChildren(new DeferredMethodWrapper(this, methodWrapper));
- if (children != null)
- return children;
- }
- return fetchChildren(methodWrapper);
- }
- }
-
- return EMPTY_ARRAY;
- }
-
- protected Object[] fetchChildren(MethodWrapper methodWrapper) {
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- MethodWrapperRunnable runnable= new MethodWrapperRunnable(methodWrapper);
- try {
- context.run(true, true, runnable);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, CallHierarchyMessages.CallHierarchyContentProvider_searchError_title, CallHierarchyMessages.CallHierarchyContentProvider_searchError_message);
- return EMPTY_ARRAY;
- } catch (InterruptedException e) {
- return new Object[] { TreeTermination.SEARCH_CANCELED };
- }
-
- return runnable.getCalls();
- }
-
- private boolean shouldStopTraversion(MethodWrapper methodWrapper) {
- return (methodWrapper.getLevel() > CallHierarchyUI.getDefault().getMaxCallDepth()) || methodWrapper.isRecursive();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
- */
- public Object getParent(Object element) {
- if (element instanceof MethodWrapper) {
- return ((MethodWrapper) element).getParent();
- }
-
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {
- // Nothing to dispose
- }
-
- /**
- * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
- */
- public boolean hasChildren(Object element) {
- if (element == TreeRoot.EMPTY_ROOT || element == TreeTermination.SEARCH_CANCELED) {
- return false;
- }
-
- // Only methods can have subelements, so there's no need to fool the
- // user into believing that there is more
- if (element instanceof MethodWrapper) {
- MethodWrapper methodWrapper= (MethodWrapper) element;
- if (methodWrapper.getMember().getElementType() != IJavaScriptElement.METHOD) {
- return false;
- }
- if (shouldStopTraversion(methodWrapper)) {
- return false;
- }
- return true;
- } else if (element instanceof TreeRoot) {
- return true;
- } else if (element instanceof DeferredMethodWrapper) {
- // Err on the safe side by returning true even though
- // we don't know for sure that there are children.
- return true;
- }
-
- return false; // the "Update ..." placeholder has no children
- }
-
- /**
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (oldInput instanceof TreeRoot) {
- Object root = ((TreeRoot) oldInput).getRoot();
- if (root instanceof MethodWrapper) {
- cancelJobs((MethodWrapper) root);
- }
- }
- if (viewer instanceof AbstractTreeViewer) {
- fManager = new DeferredTreeContentManager(this, (AbstractTreeViewer) viewer, fPart.getSite());
- }
- }
-
- /**
- * Cancel all current jobs.
- */
- void cancelJobs(MethodWrapper wrapper) {
- if (fManager != null && wrapper != null) {
- fManager.cancel(wrapper);
- if (fPart != null) {
- fPart.setCancelEnabled(false);
- }
- }
- }
-
- /**
- *
- */
- public void doneFetching() {
- if (fPart != null) {
- fPart.setCancelEnabled(false);
- }
- }
-
- /**
- *
- */
- public void startFetching() {
- if (fPart != null) {
- fPart.setCancelEnabled(true);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyFiltersActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyFiltersActionGroup.java
deleted file mode 100644
index 4808ef7b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyFiltersActionGroup.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Action group to add the filter action to a view part's toolbar
- * menu.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- */
-public class CallHierarchyFiltersActionGroup extends ActionGroup {
-
- class ShowFilterDialogAction extends Action {
- ShowFilterDialogAction() {
- setText(CallHierarchyMessages.ShowFilterDialogAction_text);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_FILTER);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_FILTER);
- }
-
- public void run() {
- openDialog();
- }
- }
-
- private IViewPart fPart;
-
- /**
- * Creates a new <code>CustomFiltersActionGroup</code>.
- *
- * @param part the view part that owns this action group
- * @param viewer the viewer to be filtered
- */
- public CallHierarchyFiltersActionGroup(IViewPart part, StructuredViewer viewer) {
- Assert.isNotNull(part);
- Assert.isNotNull(viewer);
- fPart= part;
- }
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- fillViewMenu(actionBars.getMenuManager());
- }
-
- private void fillViewMenu(IMenuManager viewMenu) {
- viewMenu.add(new Separator("filters")); //$NON-NLS-1$
- viewMenu.add(new ShowFilterDialogAction());
- }
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void dispose() {
- super.dispose();
- }
-
- // ---------- dialog related code ----------
-
- private void openDialog() {
- FiltersDialog dialog= new FiltersDialog(
- fPart.getViewSite().getShell());
-
- dialog.open();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyImageDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyImageDescriptor.java
deleted file mode 100644
index b0b37122..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyImageDescriptor.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-
-public class CallHierarchyImageDescriptor extends CompositeImageDescriptor {
-
- /** Flag to render the recursive adornment */
- public final static int RECURSIVE= 0x001;
-
- /** Flag to render the callee adornment */
- public final static int MAX_LEVEL= 0x002;
-
- private ImageDescriptor fBaseImage;
- private int fFlags;
- private Point fSize;
-
- /**
- * Creates a new CallHierarchyImageDescriptor.
- *
- * @param baseImage an image descriptor used as the base image
- * @param flags flags indicating which adornments are to be rendered. See <code>setAdornments</code>
- * for valid values.
- * @param size the size of the resulting image
- * @see #setAdornments(int)
- */
- public CallHierarchyImageDescriptor(ImageDescriptor baseImage, int flags, Point size) {
- fBaseImage= baseImage;
- Assert.isNotNull(fBaseImage);
- fFlags= flags;
- Assert.isTrue(fFlags >= 0);
- fSize= size;
- Assert.isNotNull(fSize);
- }
-
- /**
- * Sets the descriptors adornments. Valid values are: <code>RECURSIVE</code>, <code>CALLER</code>,
- * <code>CALLEE</code>, <code>MAX_LEVEL</code>, or any combination of those.
- *
- * @param adornments the image descritpors adornments
- */
- public void setAdornments(int adornments) {
- Assert.isTrue(adornments >= 0);
- fFlags= adornments;
- }
-
- /**
- * Returns the current adornments.
- *
- * @return the current adornments
- */
- public int getAdronments() {
- return fFlags;
- }
-
- /**
- * Sets the size of the image created by calling <code>createImage()</code>.
- *
- * @param size the size of the image returned from calling <code>createImage()</code>
- * @see ImageDescriptor#createImage()
- */
- public void setImageSize(Point size) {
- Assert.isNotNull(size);
- Assert.isTrue(size.x >= 0 && size.y >= 0);
- fSize= size;
- }
-
- /**
- * Returns the size of the image created by calling <code>createImage()</code>.
- *
- * @return the size of the image created by calling <code>createImage()</code>
- * @see ImageDescriptor#createImage()
- */
- public Point getImageSize() {
- return new Point(fSize.x, fSize.y);
- }
-
- /* (non-Javadoc)
- * Method declared in CompositeImageDescriptor
- */
- protected Point getSize() {
- return fSize;
- }
-
- /* (non-Javadoc)
- * Method declared on Object.
- */
- public boolean equals(Object object) {
- if (object == null || !CallHierarchyImageDescriptor.class.equals(object.getClass()))
- return false;
-
- CallHierarchyImageDescriptor other= (CallHierarchyImageDescriptor)object;
- return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize.equals(other.fSize));
- }
-
- /* (non-Javadoc)
- * Method declared on Object.
- */
- public int hashCode() {
- return fBaseImage.hashCode() | fFlags | fSize.hashCode();
- }
-
- /* (non-Javadoc)
- * Method declared in CompositeImageDescriptor
- */
- protected void drawCompositeImage(int width, int height) {
- ImageData bg= getImageData(fBaseImage);
-
- drawImage(bg, 0, 0);
- drawBottomLeft();
- }
-
- private ImageData getImageData(ImageDescriptor descriptor) {
- ImageData data= descriptor.getImageData(); // see bug 51965: getImageData can return null
- if (data == null) {
- data= DEFAULT_IMAGE_DATA;
- JavaScriptPlugin.logErrorMessage("Image data not available: " + descriptor.toString()); //$NON-NLS-1$
- }
- return data;
- }
-
- private void drawBottomLeft() {
- Point size= getSize();
- int x= 0;
- ImageData data= null;
- if ((fFlags & RECURSIVE) != 0) {
- data= getImageData(JavaPluginImages.DESC_OVR_RECURSIVE);
- drawImage(data, x, size.y - data.height);
- x+= data.width;
- }
- if ((fFlags & MAX_LEVEL) != 0) {
- data= getImageData(JavaPluginImages.DESC_OVR_MAX_LEVEL);
- drawImage(data, x, size.y - data.height);
- x+= data.width;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelDecorator.java
deleted file mode 100644
index 54a2181b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelDecorator.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageImageDescriptor;
-
-/**
- * LabelDecorator that decorates an method's image with recursion overlays.
- * The viewer using this decorator is responsible for updating the images on element changes.
- */
-public class CallHierarchyLabelDecorator implements ILabelDecorator {
-
- /**
- * Creates a decorator. The decorator creates an own image registry to cache
- * images.
- */
- public CallHierarchyLabelDecorator() {
- // Do nothing
- }
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateText(String, Object)
- */
- public String decorateText(String text, Object element) {
- return text;
- }
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateImage(Image, Object)
- */
- public Image decorateImage(Image image, Object element) {
- int adornmentFlags= computeAdornmentFlags(element);
- if (adornmentFlags != 0) {
- ImageDescriptor baseImage= new ImageImageDescriptor(image);
- Rectangle bounds= image.getBounds();
- return JavaScriptPlugin.getImageDescriptorRegistry().get(new CallHierarchyImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
- }
- return image;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- private int computeAdornmentFlags(Object element) {
- int flags= 0;
- if (element instanceof MethodWrapper) {
- MethodWrapper methodWrapper= (MethodWrapper) element;
- if (methodWrapper.isRecursive()) {
- flags= CallHierarchyImageDescriptor.RECURSIVE;
- }
- if (isMaxCallDepthExceeded(methodWrapper)) {
- flags|= CallHierarchyImageDescriptor.MAX_LEVEL;
- }
- }
- return flags;
- }
-
- private boolean isMaxCallDepthExceeded(MethodWrapper methodWrapper) {
- return methodWrapper.getLevel() > CallHierarchyUI.getDefault().getMaxCallDepth();
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#addListener(ILabelProviderListener)
- */
- public void addListener(ILabelProviderListener listener) {
- // Do nothing
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#dispose()
- */
- public void dispose() {
- // Nothing to dispose
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#isLabelProperty(Object, String)
- */
- public boolean isLabelProperty(Object element, String property) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
- */
- public void removeListener(ILabelProviderListener listener) {
- // Do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelProvider.java
deleted file mode 100644
index 75772572..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyLabelProvider.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.Collection;
-
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-class CallHierarchyLabelProvider extends AppearanceAwareLabelProvider {
- private static final long TEXTFLAGS= DEFAULT_TEXTFLAGS | JavaScriptElementLabels.ALL_POST_QUALIFIED | JavaScriptElementLabels.P_COMPRESSED;
- private static final int IMAGEFLAGS= DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS;
-
- private ILabelDecorator fDecorator;
-
- CallHierarchyLabelProvider() {
- super(TEXTFLAGS, IMAGEFLAGS);
- fDecorator= new CallHierarchyLabelDecorator();
- }
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- Image result= null;
- if (element instanceof MethodWrapper) {
- MethodWrapper methodWrapper = (MethodWrapper) element;
-
- if (methodWrapper.getMember() != null) {
- result= fDecorator.decorateImage(super.getImage(methodWrapper.getMember()), methodWrapper);
- }
- } else if (isPendingUpdate(element)) {
- return null;
- } else {
- result= super.getImage(element);
- }
-
- return result;
- }
-
- /*
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- if (element instanceof MethodWrapper && ((MethodWrapper) element).getMember() != null) {
- return getElementLabel((MethodWrapper) element);
- }
- return getSpecialLabel(element);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- if (element instanceof MethodWrapper && ((MethodWrapper) element).getMember() != null) {
- MethodWrapper wrapper= (MethodWrapper) element;
- String decorated= getElementLabel(wrapper);
- ColoredString text= super.getRichTextLabel(wrapper.getMember());
- return ColoredJavaElementLabels.decorateColoredString(text, decorated, ColoredJavaElementLabels.COUNTER_STYLE);
- }
- return new ColoredString(getSpecialLabel(element));
- }
-
- private String getSpecialLabel(Object element) {
- if (element instanceof MethodWrapper) {
- return CallHierarchyMessages.CallHierarchyLabelProvider_root;
- } else if (element == TreeTermination.SEARCH_CANCELED) {
- return CallHierarchyMessages.CallHierarchyLabelProvider_searchCanceled;
- } else if (isPendingUpdate(element)) {
- return CallHierarchyMessages.CallHierarchyLabelProvider_updatePending;
- }
- return CallHierarchyMessages.CallHierarchyLabelProvider_noMethodSelected;
- }
-
- private boolean isPendingUpdate(Object element) {
- return element instanceof IWorkbenchAdapter;
- }
-
- private String getElementLabel(MethodWrapper methodWrapper) {
- String label = super.getText(methodWrapper.getMember());
-
- Collection callLocations = methodWrapper.getMethodCall().getCallLocations();
-
- if ((callLocations != null) && (callLocations.size() > 1)) {
- return Messages.format(CallHierarchyMessages.CallHierarchyLabelProvider_matches, new String[]{label, String.valueOf(callLocations.size())});
- }
-
- return label;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.java
deleted file mode 100644
index c1bb1589..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class CallHierarchyMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.callhierarchy.CallHierarchyMessages";//$NON-NLS-1$
-
- private CallHierarchyMessages() {
- // Do not instantiate
- }
-
- public static String HistoryDropDownAction_clearhistory_label;
- public static String LocationCopyAction_copy;
- public static String ToggleCallModeAction_callers_label;
- public static String ToggleCallModeAction_callers_tooltip;
- public static String ToggleCallModeAction_callers_description;
- public static String ToggleCallModeAction_callees_label;
- public static String ToggleCallModeAction_callees_tooltip;
- public static String ToggleCallModeAction_callees_description;
- public static String HistoryDropDownAction_tooltip;
- public static String HistoryAction_description;
- public static String HistoryAction_tooltip;
- public static String HistoryListDialog_title;
- public static String HistoryListDialog_label;
- public static String HistoryListDialog_remove_button;
- public static String HistoryListAction_label;
- public static String ToggleOrientationAction_vertical_label;
- public static String ToggleOrientationAction_vertical_description;
- public static String ToggleOrientationAction_vertical_tooltip;
- public static String ToggleOrientationAction_horizontal_label;
- public static String ToggleOrientationAction_horizontal_tooltip;
- public static String ToggleOrientationAction_horizontal_description;
- public static String ToggleOrientationAction_automatic_label;
- public static String ToggleOrientationAction_automatic_tooltip;
- public static String ToggleOrientationAction_automatic_description;
- public static String ToggleOrientationAction_single_label;
- public static String ToggleOrientationAction_single_tooltip;
- public static String ToggleOrientationAction_single_description;
- public static String ShowFilterDialogAction_text;
- public static String FiltersDialog_filter;
- public static String FiltersDialog_filterOnNames;
- public static String FiltersDialog_filterOnNamesSubCaption;
- public static String FiltersDialog_maxCallDepth;
- public static String FiltersDialog_messageMaxCallDepthInvalid;
- public static String CallHierarchyContentProvider_searchError_title;
- public static String CallHierarchyContentProvider_searchError_message;
- public static String CallHierarchyLabelProvider_root;
- public static String CallHierarchyLabelProvider_searchCanceled;
- public static String CallHierarchyLabelProvider_noMethodSelected;
- public static String CallHierarchyLabelProvider_updatePending;
- public static String CallHierarchyLabelProvider_matches;
- public static String CallHierarchyViewPart_empty;
- public static String CallHierarchyViewPart_callsToMethod;
- public static String CallHierarchyViewPart_callsFromMethod;
- public static String FocusOnSelectionAction_focusOnSelection_text;
- public static String FocusOnSelectionAction_focusOnSelection_description;
- public static String FocusOnSelectionAction_focusOnSelection_tooltip;
- public static String FocusOnSelectionAction_focusOn_text;
- public static String RefreshAction_text;
- public static String RefreshAction_tooltip;
- public static String SearchScopeActionGroup_searchScope;
- public static String SearchScopeActionGroup_hierarchy_text;
- public static String SearchScopeActionGroup_hierarchy_tooltip;
- public static String SearchScopeActionGroup_project_text;
- public static String SearchScopeActionGroup_project_tooltip;
- public static String SearchScopeActionGroup_workingset_tooltip;
- public static String SearchScopeActionGroup_workspace_text;
- public static String SearchScopeActionGroup_workspace_tooltip;
- public static String SearchScopeActionGroup_workingset_select_text;
- public static String SearchScopeActionGroup_workingset_select_tooltip;
- public static String WorkingSetScope;
- public static String SearchUtil_workingSetConcatenation;
- public static String SelectWorkingSetAction_error_title;
- public static String SelectWorkingSetAction_error_message;
- public static String OpenLocationAction_error_title;
- public static String CallHierarchyUI_open_in_editor_error_message;
- public static String CallHierarchyUI_open_in_editor_error_messageArgs;
- public static String CallHierarchyUI_error_open_view;
- public static String CopyCallHierarchyAction_label;
- public static String CopyCallHierarchyAction_problem;
- public static String CopyCallHierarchyAction_clipboard_busy;
- public static String OpenCallHierarchyAction_label;
- public static String OpenCallHierarchyAction_tooltip;
- public static String OpenCallHierarchyAction_description;
- public static String OpenCallHierarchyAction_messages_no_java_element;
- public static String OpenCallHierarchyAction_messages_no_valid_java_element;
- public static String OpenCallHierarchyAction_messages_title;
- public static String OpenCallHierarchyAction_dialog_title;
- public static String CancelSearchAction_label;
- public static String CancelSearchAction_tooltip;
- public static String CallHierarchyUI_selectionDialog_title;
- public static String CallHierarchyUI_selectionDialog_message;
- public static String OpenLocationAction_label;
- public static String OpenLocationAction_tooltip;
- public static String LocationViewer_ColumnIcon_header;
- public static String LocationViewer_ColumnLine_header;
- public static String LocationViewer_ColumnInfo_header;
- public static String LocationLabelProvider_unknown;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CallHierarchyMessages.class);
- }
-
- public static String CallHierarchyViewPart_layout_menu;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties
deleted file mode 100644
index 27a9c25b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties
+++ /dev/null
@@ -1,116 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
-# (report 36180: Callers/Callees view)
-# Michael Fraenkel (fraenkel@us.ibm.com) - patch
-# (report 60714: Call Hierarchy: display search scope in view title)
-###############################################################################
-
-ToggleCallModeAction_callers_label=&Caller Hierarchy
-ToggleCallModeAction_callers_tooltip=Show Caller Hierarchy
-ToggleCallModeAction_callers_description=Show the Caller Hierarchy
-ToggleCallModeAction_callees_label=C&allee Hierarchy
-ToggleCallModeAction_callees_tooltip=Show Callee Hierarchy
-ToggleCallModeAction_callees_description=Show the Callee Hierarchy
-
-HistoryDropDownAction_tooltip=Show History List
-HistoryDropDownAction_clearhistory_label=Clear History
-HistoryAction_description=Open ''{0}'' in Hierarchy
-HistoryAction_tooltip=Open ''{0}'' in Hierarchy
-
-HistoryListDialog_title=Call Hierarchy History
-HistoryListDialog_label=&Select the element to open in the call hierarchy:
-HistoryListDialog_remove_button=&Remove
-
-HistoryListAction_label=History...
-
-ToggleOrientationAction_vertical_label=&Vertical View Orientation
-ToggleOrientationAction_vertical_description=Vertical View Orientation
-ToggleOrientationAction_vertical_tooltip=Vertical View Orientation
-ToggleOrientationAction_horizontal_label=&Horizontal View Orientation
-ToggleOrientationAction_horizontal_tooltip=Horizontal View Orientation
-ToggleOrientationAction_horizontal_description=Horizontal View Orientation
-ToggleOrientationAction_automatic_label=&Automatic View Orientation
-ToggleOrientationAction_automatic_tooltip=Automatic View Orientation
-ToggleOrientationAction_automatic_description=Automatic View Orientation
-ToggleOrientationAction_single_label=Hierarchy View &Only
-ToggleOrientationAction_single_tooltip=Hierarchy View Only
-ToggleOrientationAction_single_description=Hierarchy View Only
-
-ShowFilterDialogAction_text= &Filters...
-FiltersDialog_filter= Filter Calls
-FiltersDialog_filterOnNames= &Name filter patterns (matching names will be hidden):
-FiltersDialog_filterOnNamesSubCaption= Patterns are separated by commas (* = any string, ? = any character)
-FiltersDialog_maxCallDepth= &Max call depth:
-FiltersDialog_messageMaxCallDepthInvalid= The max call depth must be in range [1..99]
-CallHierarchyContentProvider_searchError_title=Exception
-CallHierarchyContentProvider_searchError_message=Unexpected exception.
-CallHierarchyLabelProvider_root=Root
-CallHierarchyLabelProvider_searchCanceled=The search was cancelled
-CallHierarchyLabelProvider_noMethodSelected=- no function selected -
-CallHierarchyLabelProvider_updatePending=...
-CallHierarchyLabelProvider_matches={0} ({1} matches)
-CallHierarchyViewPart_empty=To display the call hierarchy, select a function (for example in the outline view or in the editor), and select the \'Open Call Hierarchy\' menu option. Alternatively, you can drag and drop a function onto this view.
-CallHierarchyViewPart_callsToMethod=Members calling ''{0}'' - in {1}
-CallHierarchyViewPart_layout_menu=Layout
-CallHierarchyViewPart_callsFromMethod=Calls from method ''{0}'' - in {1}
-FocusOnSelectionAction_focusOnSelection_text=Fo&cus On Selection
-FocusOnSelectionAction_focusOnSelection_description=Focus On Selection
-FocusOnSelectionAction_focusOnSelection_tooltip=Focus On Selection
-FocusOnSelectionAction_focusOn_text=Fo&cus On ''{0}''
-
-RefreshAction_text=Re&fresh
-RefreshAction_tooltip=Refresh
-SearchScopeActionGroup_searchScope=&Search Scope
-SearchScopeActionGroup_hierarchy_text=&Hierarchy
-SearchScopeActionGroup_hierarchy_tooltip=Search for Calls in Hierarchy
-SearchScopeActionGroup_project_text=&Project
-SearchScopeActionGroup_project_tooltip=Search for Calls in Project
-SearchScopeActionGroup_workingset_tooltip=Search for Calls in Working Set
-SearchScopeActionGroup_workspace_text=&Workspace
-SearchScopeActionGroup_workspace_tooltip=Search for Calls in Workspace
-SearchScopeActionGroup_workingset_select_text=Working &Set...
-SearchScopeActionGroup_workingset_select_tooltip=Select Working Set
-WorkingSetScope= Working Set - {0}
-
-SearchUtil_workingSetConcatenation= {0}, {1}
-
-SelectWorkingSetAction_error_title=Select Working Sets Error
-SelectWorkingSetAction_error_message=An error occurred while selecting the working sets.
-OpenLocationAction_error_title=Show Call Location
-CallHierarchyUI_open_in_editor_error_message=An error occurred while opening the editor.
-CallHierarchyUI_open_in_editor_error_messageArgs=An error occurred while opening the editor for ''{0}'': ''{1}''.
-CallHierarchyUI_error_open_view=An error occurred while opening the call hierarchy view.
-
-CopyCallHierarchyAction_label=Copy E&xpanded Hierarchy
-CopyCallHierarchyAction_problem=Problem Copying Hierarchy to Clipboard
-CopyCallHierarchyAction_clipboard_busy=There was a problem when accessing the system clipboard. Retry?
-OpenCallHierarchyAction_label=Open Call &Hierarchy
-OpenCallHierarchyAction_tooltip=Open a Call Hierarchy on the Selected Element
-OpenCallHierarchyAction_description=Open a call hierarchy on the selected element
-OpenCallHierarchyAction_messages_no_java_element=A JavaScript element must be selected.
-OpenCallHierarchyAction_messages_no_valid_java_element=A function must be selected.
-OpenCallHierarchyAction_messages_title= Cannot create call hierarchy
-OpenCallHierarchyAction_dialog_title=Open Call Hierarchy
-
-CancelSearchAction_label=Cancel
-CancelSearchAction_tooltip=Cancel Current Search
-
-CallHierarchyUI_selectionDialog_title=Open In Call Hierarchy
-CallHierarchyUI_selectionDialog_message=&Select the method to be shown in the Call Hierarchy:
-
-OpenLocationAction_label=&Open
-OpenLocationAction_tooltip=Open Location
-
-LocationViewer_ColumnIcon_header=
-LocationViewer_ColumnLine_header=Line
-LocationViewer_ColumnInfo_header=Call
-
-LocationLabelProvider_unknown=?
-LocationCopyAction_copy=&Copy
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyTransferDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyTransferDropAdapter.java
deleted file mode 100644
index 8abad4f8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyTransferDropAdapter.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-
-class CallHierarchyTransferDropAdapter extends SelectionTransferDropAdapter {
-
- private static final int OPERATION = DND.DROP_LINK;
- private CallHierarchyViewPart fCallHierarchyViewPart;
-
- public CallHierarchyTransferDropAdapter(CallHierarchyViewPart viewPart, StructuredViewer viewer) {
- super(viewer);
- setFullWidthMatchesItem(false);
- fCallHierarchyViewPart= viewPart;
- }
-
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- event.detail= DND.DROP_NONE;
- initializeSelection();
- if (target != null){
- super.validateDrop(target, event, operation);
- return;
- }
- if (getInputElement(getSelection()) != null)
- event.detail= OPERATION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter#isEnabled(org.eclipse.swt.dnd.DropTargetEvent)
- */
- public boolean isEnabled(DropTargetEvent event) {
- return true;
- }
-
- public void drop(Object target, DropTargetEvent event) {
- if (target != null || event.detail != OPERATION){
- super.drop(target, event);
- return;
- }
- IFunction input= getInputElement(getSelection());
- fCallHierarchyViewPart.setMethod(input);
- }
-
- private static IFunction getInputElement(ISelection selection) {
- Object single= SelectionUtil.getSingleElement(selection);
- if (single == null)
- return null;
- return getCandidate(single);
- }
-
- /**
- * Converts the input to a possible input candidates
- */
- public static IFunction getCandidate(Object input) {
- if (!(input instanceof IFunction)) {
- return null;
- }
- return (IFunction) input;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyUI.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyUI.java
deleted file mode 100644
index 569e72d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyUI.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.OpenStrategy;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallHierarchy;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallLocation;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CallHierarchyUI {
- private static final int DEFAULT_MAX_CALL_DEPTH= 10;
- private static final String PREF_MAX_CALL_DEPTH = "PREF_MAX_CALL_DEPTH"; //$NON-NLS-1$
-
- private static CallHierarchyUI fgInstance;
-
- private CallHierarchyUI() {
- // Do nothing
- }
-
- public static CallHierarchyUI getDefault() {
- if (fgInstance == null) {
- fgInstance = new CallHierarchyUI();
- }
-
- return fgInstance;
- }
-
- /**
- * Returns the maximum tree level allowed
- * @return int
- */
- public int getMaxCallDepth() {
- int maxCallDepth;
-
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
- maxCallDepth = settings.getInt(PREF_MAX_CALL_DEPTH);
- if (maxCallDepth < 1 || maxCallDepth > 99) {
- maxCallDepth= DEFAULT_MAX_CALL_DEPTH;
- }
-
- return maxCallDepth;
- }
-
- public void setMaxCallDepth(int maxCallDepth) {
- IPreferenceStore settings = JavaScriptPlugin.getDefault().getPreferenceStore();
- settings.setValue(PREF_MAX_CALL_DEPTH, maxCallDepth);
- }
-
- public static void jumpToMember(IJavaScriptElement element) {
- if (element != null) {
- try {
- JavaScriptUI.openInEditor(element, true, true);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- public static void jumpToLocation(CallLocation callLocation) {
- try {
- IEditorPart methodEditor = JavaScriptUI.openInEditor(callLocation.getMember(), false, false);
- if (methodEditor instanceof ITextEditor) {
- ITextEditor editor = (ITextEditor) methodEditor;
- editor.selectAndReveal(callLocation.getStart(),
- (callLocation.getEnd() - callLocation.getStart()));
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * @return <code>true</code> iff no error occurred while trying to
- * open the editor, <code>false</code> iff an error dialog was raised.
- */
- public static boolean openInEditor(Object element, Shell shell, String title) {
- CallLocation callLocation= CallHierarchy.getCallLocation(element);
-
- try {
- IMember enclosingMember;
- int selectionStart;
- int selectionLength;
-
- if (callLocation != null) {
- enclosingMember= callLocation.getMember();
- selectionStart= callLocation.getStart();
- selectionLength= callLocation.getEnd() - selectionStart;
- } else if (element instanceof MethodWrapper) {
- enclosingMember= ((MethodWrapper) element).getMember();
- if(enclosingMember.isVirtual()) {
- selectionStart = 0;
- selectionLength = 0;
-
- }else {
- ISourceRange selectionRange= enclosingMember.getNameRange();
- if (selectionRange == null)
- selectionRange= enclosingMember.getSourceRange();
- if (selectionRange == null)
- return true;
- selectionStart= selectionRange.getOffset();
- selectionLength= selectionRange.getLength();
- }
- } else {
- return true;
- }
-
- boolean activateOnOpen = OpenStrategy.activateOnOpen();
-
- IEditorPart methodEditor = JavaScriptUI.openInEditor(enclosingMember, activateOnOpen, false);
- if (methodEditor instanceof ITextEditor) {
- ITextEditor editor = (ITextEditor) methodEditor;
- editor.selectAndReveal(selectionStart, selectionLength);
- }
- return true;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(),
- IJavaStatusConstants.INTERNAL_ERROR,
- CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message, e));
-
- ErrorDialog.openError(shell, title,
- CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message,
- e.getStatus());
- return false;
- } catch (PartInitException x) {
- String name;
- if (callLocation != null)
- name= callLocation.getCalledMember().getElementName();
- else if (element instanceof MethodWrapper)
- name= ((MethodWrapper) element).getName();
- else
- name= ""; //$NON-NLS-1$
- MessageDialog.openError(shell, title,
- Messages.format(
- CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_messageArgs,
- new String[] { name, x.getMessage() }));
- return false;
- }
- }
-
- public static IEditorPart isOpenInEditor(Object elem) {
- IJavaScriptElement javaElement= null;
- if (elem instanceof MethodWrapper) {
- javaElement= ((MethodWrapper) elem).getMember();
- } else if (elem instanceof CallLocation) {
- javaElement= ((CallLocation) elem).getCalledMember();
- }
- if (javaElement != null) {
- return EditorUtility.isOpenInEditor(javaElement);
- }
- return null;
- }
-
- /**
- * Converts the input to a possible input candidates
- */
- public static IJavaScriptElement[] getCandidates(Object input) {
- if (!(input instanceof IJavaScriptElement)) {
- return null;
- }
- IJavaScriptElement elem= (IJavaScriptElement) input;
- if (elem.getElementType() == IJavaScriptElement.METHOD) {
- return new IJavaScriptElement[] { elem };
- }
- return null;
- }
-
- public static CallHierarchyViewPart open(IJavaScriptElement[] candidates, IWorkbenchWindow window) {
- Assert.isTrue(candidates != null && candidates.length != 0);
-
- IJavaScriptElement input= null;
- if (candidates.length > 1) {
- String title= CallHierarchyMessages.CallHierarchyUI_selectionDialog_title;
- String message= CallHierarchyMessages.CallHierarchyUI_selectionDialog_message;
- input= SelectionConverter.selectJavaElement(candidates, window.getShell(), title, message);
- } else {
- input= candidates[0];
- }
- if (input == null)
- return null;
-
- return openInViewPart(window, input);
- }
-
- private static CallHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaScriptElement input) {
- IWorkbenchPage page= window.getActivePage();
- try {
- CallHierarchyViewPart result= (CallHierarchyViewPart)page.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
- result.setMethod((IFunction)input);
- return result;
- } catch (CoreException e) {
- ExceptionHandler.handle(e, window.getShell(),
- CallHierarchyMessages.CallHierarchyUI_error_open_view, e.getMessage());
- }
- return null;
- }
-
- /**
- * Converts an ISelection (containing MethodWrapper instances) to an ISelection
- * with the MethodWrapper's replaced by their corresponding IMembers. If the selection
- * contains elements which are not MethodWrapper instances or not already IMember instances
- * they are discarded.
- * @param selection The selection to convert.
- * @return An ISelection containing IMember's in place of MethodWrapper instances.
- */
- static ISelection convertSelection(ISelection selection) {
- if (selection.isEmpty()) {
- return selection;
- }
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection= (IStructuredSelection) selection;
- List javaElements= new ArrayList();
- for (Iterator iter= structuredSelection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof MethodWrapper) {
- IMember member= ((MethodWrapper)element).getMember();
- if (member != null) {
- javaElements.add(member);
- }
- } else if (element instanceof IMember) {
- javaElements.add(element);
- } else if (element instanceof CallLocation) {
- IMember member = ((CallLocation) element).getMember();
- javaElements.add(member);
- }
- }
- return new StructuredSelection(javaElements);
- }
- return StructuredSelection.EMPTY;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewPart.java
deleted file mode 100644
index eeb7cfa4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewPart.java
+++ /dev/null
@@ -1,948 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.PageBook;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallHierarchy;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallLocation;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.dnd.DelegatingDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.ResourceTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SelectionProviderMediator;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-/**
- * This is the main view for the callers plugin. It builds a tree of callers/callees
- * and allows the user to double click an entry to go to the selected method.
- *
- */
-public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart,
- ISelectionChangedListener {
-
- private class CallHierarchySelectionProvider extends SelectionProviderMediator {
-
- public CallHierarchySelectionProvider(StructuredViewer[] viewers) {
- super(viewers, null);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.SelectionProviderMediator#getSelection()
- */
- public ISelection getSelection() {
- ISelection selection= super.getSelection();
- if (!selection.isEmpty()) {
- return CallHierarchyUI.convertSelection(selection);
- }
- return selection;
- }
- }
-
- private static final String DIALOGSTORE_VIEWORIENTATION = "CallHierarchyViewPart.orientation"; //$NON-NLS-1$
- private static final String DIALOGSTORE_CALL_MODE = "CallHierarchyViewPart.call_mode"; //$NON-NLS-1$
- /**
- * The key to be used is <code>DIALOGSTORE_RATIO + fCurrentOrientation</code>.
- */
- private static final String DIALOGSTORE_RATIO= "CallHierarchyViewPart.ratio"; //$NON-NLS-1$
-
- static final int VIEW_ORIENTATION_VERTICAL = 0;
- static final int VIEW_ORIENTATION_HORIZONTAL = 1;
- static final int VIEW_ORIENTATION_SINGLE = 2;
- static final int VIEW_ORIENTATION_AUTOMATIC = 3;
- static final int CALL_MODE_CALLERS = 0;
- static final int CALL_MODE_CALLEES = 1;
- static final String GROUP_SEARCH_SCOPE = "MENU_SEARCH_SCOPE"; //$NON-NLS-1$
- static final String ID_CALL_HIERARCHY = "org.eclipse.wst.jsdt.callhierarchy.view"; //$NON-NLS-1$
- private static final String GROUP_FOCUS = "group.focus"; //$NON-NLS-1$
- private static final int PAGE_EMPTY = 0;
- private static final int PAGE_VIEWER = 1;
- private Label fNoHierarchyShownLabel;
- private PageBook fPagebook;
- private IDialogSettings fDialogSettings;
- private int fCurrentOrientation;
- int fOrientation= VIEW_ORIENTATION_AUTOMATIC;
- private int fCurrentCallMode;
- private MethodWrapper fCalleeRoot;
- private MethodWrapper fCallerRoot;
- private IMemento fMemento;
- private IFunction fShownMethod;
- private CallHierarchySelectionProvider fSelectionProviderMediator;
- private List fMethodHistory;
- private LocationViewer fLocationViewer;
- private SashForm fHierarchyLocationSplitter;
- private Clipboard fClipboard;
- private SearchScopeActionGroup fSearchScopeActions;
- private ToggleOrientationAction[] fToggleOrientationActions;
- private ToggleCallModeAction[] fToggleCallModeActions;
- private CallHierarchyFiltersActionGroup fFiltersActionGroup;
- private HistoryDropDownAction fHistoryDropDownAction;
- private RefreshAction fRefreshAction;
- private OpenLocationAction fOpenLocationAction;
- private LocationCopyAction fLocationCopyAction;
- private FocusOnSelectionAction fFocusOnSelectionAction;
- private CopyCallHierarchyAction fCopyAction;
- private CancelSearchAction fCancelSearchAction;
- private CompositeActionGroup fActionGroups;
- private CallHierarchyViewer fCallHierarchyViewer;
- private boolean fShowCallDetails;
- protected Composite fParent;
- private IPartListener2 fPartListener;
-
- public CallHierarchyViewPart() {
- super();
-
- fDialogSettings = JavaScriptPlugin.getDefault().getDialogSettings();
-
- fMethodHistory = new ArrayList();
- }
-
- public void setFocus() {
- fPagebook.setFocus();
- }
-
- /**
- * Sets the history entries
- */
- public void setHistoryEntries(IFunction[] elems) {
- fMethodHistory.clear();
-
- for (int i = 0; i < elems.length; i++) {
- fMethodHistory.add(elems[i]);
- }
-
- updateHistoryEntries();
- }
-
- /**
- * Gets all history entries.
- */
- public IFunction[] getHistoryEntries() {
- if (fMethodHistory.size() > 0) {
- updateHistoryEntries();
- }
-
- return (IFunction[]) fMethodHistory.toArray(new IFunction[fMethodHistory.size()]);
- }
-
- /**
- * Method setMethod.
- * @param method
- */
- public void setMethod(IFunction method) {
- if (method == null) {
- showPage(PAGE_EMPTY);
-
- return;
- }
- if (! method.equals(fShownMethod)) {
- addHistoryEntry(method);
- }
-
- this.fShownMethod = method;
-
- refresh();
- }
-
- public IFunction getMethod() {
- return fShownMethod;
- }
-
- public MethodWrapper getCurrentMethodWrapper() {
- if (fCurrentCallMode == CALL_MODE_CALLERS) {
- return fCallerRoot;
- } else {
- return fCalleeRoot;
- }
- }
-
- /**
- * called from ToggleOrientationAction.
- * @param orientation VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
- */
- void setOrientation(int orientation) {
- if (fCurrentOrientation != orientation) {
- if ((fLocationViewer != null) && !fLocationViewer.getControl().isDisposed() &&
- (fHierarchyLocationSplitter != null) &&
- !fHierarchyLocationSplitter.isDisposed()) {
- if (orientation == VIEW_ORIENTATION_SINGLE) {
- setShowCallDetails(false);
- } else {
- if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
- setShowCallDetails(true);
- }
-
- boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
- fHierarchyLocationSplitter.setOrientation(horizontal ? SWT.HORIZONTAL
- : SWT.VERTICAL);
- }
-
- fHierarchyLocationSplitter.layout();
- }
-
- updateCheckedState();
-
- fCurrentOrientation = orientation;
-
- restoreSplitterRatio();
- }
- }
-
- private void updateCheckedState() {
- for (int i= 0; i < fToggleOrientationActions.length; i++) {
- fToggleOrientationActions[i].setChecked(fOrientation == fToggleOrientationActions[i].getOrientation());
- }
- }
-
- /**
- * called from ToggleCallModeAction.
- * @param mode CALL_MODE_CALLERS or CALL_MODE_CALLEES
- */
- void setCallMode(int mode) {
- if (fCurrentCallMode != mode) {
- for (int i = 0; i < fToggleCallModeActions.length; i++) {
- fToggleCallModeActions[i].setChecked(mode == fToggleCallModeActions[i].getMode());
- }
-
- fCurrentCallMode = mode;
- fDialogSettings.put(DIALOGSTORE_CALL_MODE, mode);
-
- updateView();
- }
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- return fSearchScopeActions.getSearchScope();
- }
-
- public void setShowCallDetails(boolean show) {
- fShowCallDetails = show;
- showOrHideCallDetailsView();
- }
-
- private void initDragAndDrop() {
- addDragAdapters(fCallHierarchyViewer);
- addDropAdapters(fCallHierarchyViewer);
- addDropAdapters(fLocationViewer);
-
- //dnd on empty hierarchy
- DropTarget dropTarget = new DropTarget(fPagebook, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT);
- dropTarget.setTransfer(new Transfer[] { LocalSelectionTransfer.getInstance() });
- dropTarget.addDropListener(new CallHierarchyTransferDropAdapter(this, fCallHierarchyViewer));
- }
-
- private void addDropAdapters(StructuredViewer viewer) {
- Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
- int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT;
-
- TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
- new CallHierarchyTransferDropAdapter(this, viewer)
- };
- viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
- }
-
- private void addDragAdapters(StructuredViewer viewer) {
- int ops= DND.DROP_COPY | DND.DROP_LINK;
- Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance()};
-
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(viewer),
- new ResourceTransferDragAdapter(viewer)
- };
- viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
- }
-
- public void createPartControl(Composite parent) {
- fParent= parent;
- addResizeListener(parent);
- fPagebook = new PageBook(parent, SWT.NONE);
-
- // Page 1: Viewers
- createHierarchyLocationSplitter(fPagebook);
- createCallHierarchyViewer(fHierarchyLocationSplitter);
- createLocationViewer(fHierarchyLocationSplitter);
-
- // Page 2: Nothing selected
- fNoHierarchyShownLabel = new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
- fNoHierarchyShownLabel.setText(CallHierarchyMessages.CallHierarchyViewPart_empty); //
-
- initDragAndDrop();
-
- showPage(PAGE_EMPTY);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fPagebook, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
-
- fSelectionProviderMediator = new CallHierarchySelectionProvider(new StructuredViewer[] {
- fCallHierarchyViewer, fLocationViewer
- });
-
- IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
- fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
- getSite().setSelectionProvider(fSelectionProviderMediator);
-
- fCallHierarchyViewer.initContextMenu(
- new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillCallHierarchyViewerContextMenu(menu);
- }
- }, getSite(), fSelectionProviderMediator);
-
-
- fClipboard= new Clipboard(parent.getDisplay());
-
- makeActions();
- fillViewMenu();
- fillActionBars();
-
- initOrientation();
- initCallMode();
-
- if (fMemento != null) {
- restoreState(fMemento);
- }
- restoreSplitterRatio();
- addPartListener();
- }
-
- private void restoreSplitterRatio() {
- String ratio= fDialogSettings.get(DIALOGSTORE_RATIO + fCurrentOrientation);
- if (ratio == null)
- return;
- int intRatio= Integer.parseInt(ratio);
- fHierarchyLocationSplitter.setWeights(new int[] {intRatio, 1000 - intRatio});
- }
-
- private void saveSplitterRatio() {
- if (fHierarchyLocationSplitter != null && ! fHierarchyLocationSplitter.isDisposed()) {
- int[] weigths = fHierarchyLocationSplitter.getWeights();
- int ratio = (weigths[0] * 1000) / (weigths[0] + weigths[1]);
- String key= DIALOGSTORE_RATIO + fCurrentOrientation;
- fDialogSettings.put(key, ratio);
- }
- }
-
- private void addPartListener() {
- fPartListener= new IPartListener2() {
- public void partActivated(IWorkbenchPartReference partRef) { }
- public void partBroughtToTop(IWorkbenchPartReference partRef) { }
- public void partClosed(IWorkbenchPartReference partRef) {
- if (ID_CALL_HIERARCHY.equals(partRef.getId()))
- saveViewSettings();
- }
- public void partDeactivated(IWorkbenchPartReference partRef) {
- if (ID_CALL_HIERARCHY.equals(partRef.getId()))
- saveViewSettings();
- }
- public void partOpened(IWorkbenchPartReference partRef) { }
- public void partHidden(IWorkbenchPartReference partRef) { }
- public void partVisible(IWorkbenchPartReference partRef) { }
- public void partInputChanged(IWorkbenchPartReference partRef) { }
- };
- getViewSite().getPage().addPartListener(fPartListener);
- }
-
- protected void saveViewSettings() {
- saveSplitterRatio();
- fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, fOrientation);
- }
-
- private void addResizeListener(Composite parent) {
- parent.addControlListener(new ControlListener() {
- public void controlMoved(ControlEvent e) {
- }
- public void controlResized(ControlEvent e) {
- computeOrientation();
- }
- });
- }
-
- void computeOrientation() {
- saveSplitterRatio();
- fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, fOrientation);
- if (fOrientation != VIEW_ORIENTATION_AUTOMATIC) {
- setOrientation(fOrientation);
- }
- else {
- if (fOrientation == VIEW_ORIENTATION_SINGLE)
- return;
- Point size= fParent.getSize();
- if (size.x != 0 && size.y != 0) {
- if (size.x > size.y)
- setOrientation(VIEW_ORIENTATION_HORIZONTAL);
- else
- setOrientation(VIEW_ORIENTATION_VERTICAL);
- }
- }
- }
-
- private void showPage(int page) {
- if (page == PAGE_EMPTY) {
- fPagebook.showPage(fNoHierarchyShownLabel);
- } else {
- fPagebook.showPage(fHierarchyLocationSplitter);
- }
- }
-
- /**
- * Restores the type hierarchy settings from a memento.
- */
- private void restoreState(IMemento memento) {
- fSearchScopeActions.restoreState(memento);
- }
-
- private void initCallMode() {
- int mode;
-
- try {
- mode = fDialogSettings.getInt(DIALOGSTORE_CALL_MODE);
-
- if ((mode < 0) || (mode > 1)) {
- mode = CALL_MODE_CALLERS;
- }
- } catch (NumberFormatException e) {
- mode = CALL_MODE_CALLERS;
- }
-
- // force the update
- fCurrentCallMode = -1;
-
- // will fill the main tool bar
- setCallMode(mode);
- }
-
- private void initOrientation() {
-
- try {
- fOrientation = fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
-
- if ((fOrientation < 0) || (fOrientation > 3)) {
- fOrientation = VIEW_ORIENTATION_AUTOMATIC;
- }
- } catch (NumberFormatException e) {
- fOrientation = VIEW_ORIENTATION_AUTOMATIC;
- }
-
- // force the update
- fCurrentOrientation = -1;
- setOrientation(fOrientation);
- }
-
- private void fillViewMenu() {
- IActionBars actionBars = getViewSite().getActionBars();
- IMenuManager viewMenu = actionBars.getMenuManager();
- viewMenu.add(new Separator());
-
- for (int i = 0; i < fToggleCallModeActions.length; i++) {
- viewMenu.add(fToggleCallModeActions[i]);
- }
-
- viewMenu.add(new Separator());
-
- MenuManager layoutSubMenu= new MenuManager(CallHierarchyMessages.CallHierarchyViewPart_layout_menu);
- for (int i = 0; i < fToggleOrientationActions.length; i++) {
- layoutSubMenu.add(fToggleOrientationActions[i]);
- }
- viewMenu.add(layoutSubMenu);
- }
-
- /**
- *
- */
- public void dispose() {
- if (fActionGroups != null)
- fActionGroups.dispose();
-
- if (fClipboard != null)
- fClipboard.dispose();
-
- if (fPartListener != null) {
- getViewSite().getPage().removePartListener(fPartListener);
- fPartListener= null;
- }
-
- super.dispose();
- }
-
- /**
- * Goes to the selected entry, without updating the order of history entries.
- */
- public void gotoHistoryEntry(IFunction entry) {
- if (fMethodHistory.contains(entry)) {
- setMethod(entry);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on IViewPart.
- */
- public void init(IViewSite site, IMemento memento)
- throws PartInitException {
- super.init(site, memento);
- fMemento = memento;
- }
-
- /**
- *
- */
- public void refresh() {
- setCalleeRoot(null);
- setCallerRoot(null);
-
- updateView();
- }
-
- public void saveState(IMemento memento) {
- if (fPagebook == null) {
- // part has not been created
- if (fMemento != null) { //Keep the old state;
- memento.putMemento(fMemento);
- }
-
- return;
- }
-
- fSearchScopeActions.saveState(memento);
- }
-
- public void selectionChanged(SelectionChangedEvent e) {
- if (e.getSelectionProvider() == fCallHierarchyViewer) {
- methodSelectionChanged(e.getSelection());
- }
- }
-
- /**
- * @param selection
- */
- private void methodSelectionChanged(ISelection selection) {
- if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1) {
- Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
-
- if (selectedElement instanceof MethodWrapper) {
- MethodWrapper methodWrapper = (MethodWrapper) selectedElement;
-
- revealElementInEditor(methodWrapper, fCallHierarchyViewer);
- updateLocationsView(methodWrapper);
- } else {
- updateLocationsView(null);
- }
- } else {
- updateLocationsView(null);
- }
- }
-
- private void revealElementInEditor(Object elem, Viewer originViewer) {
- // only allow revealing when the type hierarchy is the active pagae
- // no revealing after selection events due to model changes
- if (getSite().getPage().getActivePart() != this) {
- return;
- }
-
- if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
- return;
- }
-
- if (elem instanceof MethodWrapper) {
- CallLocation callLocation = CallHierarchy.getCallLocation(elem);
-
- if (callLocation != null) {
- IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(callLocation);
-
- if (editorPart != null) {
- getSite().getPage().bringToTop(editorPart);
-
- if (editorPart instanceof ITextEditor) {
- ITextEditor editor = (ITextEditor) editorPart;
- editor.selectAndReveal(callLocation.getStart(),
- (callLocation.getEnd() - callLocation.getStart()));
- }
- }
- } else {
- IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(elem);
- getSite().getPage().bringToTop(editorPart);
- EditorUtility.revealInEditor(editorPart,
- ((MethodWrapper) elem).getMember());
- }
- } else if (elem instanceof IJavaScriptElement) {
- IEditorPart editorPart = EditorUtility.isOpenInEditor(elem);
-
- if (editorPart != null) {
- // getSite().getPage().removePartListener(fPartListener);
- getSite().getPage().bringToTop(editorPart);
- EditorUtility.revealInEditor(editorPart, (IJavaScriptElement) elem);
-
- // getSite().getPage().addPartListener(fPartListener);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getAdapter(Class adapter) {
- if (adapter == IContextProvider.class) {
- return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
- }
- if (adapter == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
- }
- };
- }
- return super.getAdapter(adapter);
- }
-
- /**
- * Returns the current selection.
- */
- protected ISelection getSelection() {
- StructuredViewer viewerInFocus= fSelectionProviderMediator.getViewerInFocus();
- if (viewerInFocus != null) {
- return viewerInFocus.getSelection();
- }
- return StructuredSelection.EMPTY;
- }
-
- protected void fillLocationViewerContextMenu(IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
-
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fOpenLocationAction);
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
- menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fLocationCopyAction);
- }
-
- protected void handleKeyEvent(KeyEvent event) {
- if (event.stateMask == 0) {
- if (event.keyCode == SWT.F5) {
- if ((fRefreshAction != null) && fRefreshAction.isEnabled()) {
- fRefreshAction.run();
-
- return;
- }
- }
- }
- }
-
- private IActionBars getActionBars() {
- return getViewSite().getActionBars();
- }
-
- private void setCalleeRoot(MethodWrapper calleeRoot) {
- this.fCalleeRoot = calleeRoot;
- }
-
- private MethodWrapper getCalleeRoot() {
- if (fCalleeRoot == null) {
- fCalleeRoot = CallHierarchy.getDefault().getCalleeRoot(fShownMethod);
- }
-
- return fCalleeRoot;
- }
-
- private void setCallerRoot(MethodWrapper callerRoot) {
- this.fCallerRoot = callerRoot;
- }
-
- private MethodWrapper getCallerRoot() {
- if (fCallerRoot == null) {
- fCallerRoot = CallHierarchy.getDefault().getCallerRoot(fShownMethod);
- }
-
- return fCallerRoot;
- }
-
- /**
- * Adds the entry if new. Inserted at the beginning of the history entries list.
- */
- private void addHistoryEntry(IJavaScriptElement entry) {
- if (fMethodHistory.contains(entry)) {
- fMethodHistory.remove(entry);
- }
-
- fMethodHistory.add(0, entry);
- fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
- }
-
- /**
- * @param parent
- */
- private void createLocationViewer(Composite parent) {
- fLocationViewer= new LocationViewer(parent);
-
- fLocationViewer.getControl().addKeyListener(createKeyListener());
-
- fLocationViewer.initContextMenu(new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillLocationViewerContextMenu(menu);
- }
- }, ID_CALL_HIERARCHY, getSite());
- }
-
- private void createHierarchyLocationSplitter(Composite parent) {
- fHierarchyLocationSplitter = new SashForm(parent, SWT.NONE);
-
- fHierarchyLocationSplitter.addKeyListener(createKeyListener());
- }
-
- private void createCallHierarchyViewer(Composite parent) {
- fCallHierarchyViewer = new CallHierarchyViewer(parent, this);
-
- fCallHierarchyViewer.addKeyListener(createKeyListener());
- fCallHierarchyViewer.addSelectionChangedListener(this);
- }
-
- /**
- * @param menu
- */
- protected void fillCallHierarchyViewerContextMenu(IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
-
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
-
- if (fFocusOnSelectionAction.canActionBeAdded()) {
- menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
- }
- if (fCopyAction.canActionBeAdded()) {
- menu.appendToGroup(GROUP_FOCUS, fCopyAction);
- }
-
- fActionGroups.setContext(new ActionContext(getSelection()));
- fActionGroups.fillContextMenu(menu);
- fActionGroups.setContext(null);
- }
-
- private void fillActionBars() {
- IActionBars actionBars = getActionBars();
- IToolBarManager toolBar = actionBars.getToolBarManager();
-
- fActionGroups.fillActionBars(actionBars);
-
- toolBar.add(fCancelSearchAction);
- for (int i = 0; i < fToggleCallModeActions.length; i++) {
- toolBar.add(fToggleCallModeActions[i]);
- }
- toolBar.add(fHistoryDropDownAction);
- }
-
- private KeyListener createKeyListener() {
- KeyListener keyListener = new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- handleKeyEvent(event);
- }
- };
-
- return keyListener;
- }
-
- /**
- *
- */
- private void makeActions() {
- fRefreshAction = new RefreshAction(this);
-
- fOpenLocationAction = new OpenLocationAction(this, getSite());
- fLocationViewer.addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- fOpenLocationAction.run();
- }
- });
-
- fLocationCopyAction= fLocationViewer.initCopyAction(getViewSite(), fClipboard);
-
- fFocusOnSelectionAction = new FocusOnSelectionAction(this);
- fCopyAction= new CopyCallHierarchyAction(this, fClipboard, fCallHierarchyViewer);
- fSearchScopeActions = new SearchScopeActionGroup(this, fDialogSettings);
- fFiltersActionGroup = new CallHierarchyFiltersActionGroup(this,
- fCallHierarchyViewer);
- fHistoryDropDownAction = new HistoryDropDownAction(this);
- fHistoryDropDownAction.setEnabled(false);
- fCancelSearchAction = new CancelSearchAction(this);
- setCancelEnabled(false);
- fToggleOrientationActions = new ToggleOrientationAction[] {
- new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
- new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
- new ToggleOrientationAction(this, VIEW_ORIENTATION_AUTOMATIC),
- new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
- };
- fToggleCallModeActions = new ToggleCallModeAction[] {
- new ToggleCallModeAction(this, CALL_MODE_CALLERS),
- new ToggleCallModeAction(this, CALL_MODE_CALLEES)
- };
- fActionGroups = new CompositeActionGroup(new ActionGroup[] {
- new OpenEditorActionGroup(this),
- new OpenViewActionGroup(this),
- new CCPActionGroup(this),
- new GenerateActionGroup(this),
- new RefactorActionGroup(this),
- new JavaSearchActionGroup(this),
- fSearchScopeActions, fFiltersActionGroup
- });
- }
-
- private void showOrHideCallDetailsView() {
- if (fShowCallDetails) {
- fHierarchyLocationSplitter.setMaximizedControl(null);
- } else {
- fHierarchyLocationSplitter.setMaximizedControl(fCallHierarchyViewer.getControl());
- }
- }
-
- private void updateLocationsView(MethodWrapper methodWrapper) {
- if (methodWrapper != null && methodWrapper.getMethodCall().hasCallLocations()) {
- fLocationViewer.setInput(methodWrapper.getMethodCall().getCallLocations());
- } else {
- fLocationViewer.clearViewer();
- }
- }
-
- private void updateHistoryEntries() {
- for (int i = fMethodHistory.size() - 1; i >= 0; i--) {
- IFunction method = (IFunction) fMethodHistory.get(i);
-
- if (!method.exists()) {
- fMethodHistory.remove(i);
- }
- }
-
- fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
- }
-
- /**
- * Method updateView.
- */
- private void updateView() {
- if ( (fShownMethod != null)) {
- showPage(PAGE_VIEWER);
-
- CallHierarchy.getDefault().setSearchScope(getSearchScope());
-
- String elementName= JavaScriptElementLabels.getElementLabel(fShownMethod, JavaScriptElementLabels.ALL_DEFAULT);
- String scopeDescription= fSearchScopeActions.getFullDescription();
- String[] args= new String[] { elementName, scopeDescription };
- // set input to null so that setSorter does not cause a refresh on the old contents:
- fCallHierarchyViewer.setInput(null);
- if (fCurrentCallMode == CALL_MODE_CALLERS) {
- setContentDescription(Messages.format(CallHierarchyMessages.CallHierarchyViewPart_callsToMethod, args));
- fCallHierarchyViewer.setComparator(new ViewerComparator()); // bug 111423: sort caller hierarchy alphabetically
- fCallHierarchyViewer.setMethodWrapper(getCallerRoot());
- } else {
- setContentDescription(Messages.format(CallHierarchyMessages.CallHierarchyViewPart_callsFromMethod, args));
- fCallHierarchyViewer.setComparator(null);
- fCallHierarchyViewer.setMethodWrapper(getCalleeRoot());
- }
- }
- }
-
- static CallHierarchyViewPart findAndShowCallersView(IWorkbenchPartSite site) {
- IWorkbenchPage workbenchPage = site.getPage();
- CallHierarchyViewPart callersView = null;
-
- try {
- callersView = (CallHierarchyViewPart) workbenchPage.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- }
-
- return callersView;
- }
-
- /**
- * Cancels the caller/callee search jobs that are currently running.
- */
- void cancelJobs() {
- fCallHierarchyViewer.cancelJobs();
- }
-
- /**
- * Sets the enablement state of the cancel button.
- * @param enabled
- */
- void setCancelEnabled(boolean enabled) {
- fCancelSearchAction.setEnabled(enabled);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewer.java
deleted file mode 100644
index 9769dbdc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyViewer.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-
-class CallHierarchyViewer extends TreeViewer {
- private CallHierarchyViewPart fPart;
-
- private OpenLocationAction fOpen;
-
- private CallHierarchyContentProvider fContentProvider;
-
- /**
- * @param parent the parent composite
- * @param part the call hierarchy view part
- */
- CallHierarchyViewer(Composite parent, CallHierarchyViewPart part) {
- super(new Tree(parent, SWT.MULTI));
-
- fPart = part;
-
- getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
- setUseHashlookup(true);
- setAutoExpandLevel(2);
- fContentProvider = new CallHierarchyContentProvider(fPart);
- setContentProvider(fContentProvider);
- setLabelProvider(new CallHierarchyLabelProvider());
-
- fOpen= new OpenLocationAction(part, part.getSite());
- addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- fOpen.run();
- }
- });
-
- ColoredViewersManager.install(this);
-
- clearViewer();
- }
-
- /**
- * @param wrapper
- */
- void setMethodWrapper(MethodWrapper wrapper) {
- setInput(getTreeRoot(wrapper));
-
- setFocus();
- setSelection(new StructuredSelection(wrapper), true);
- }
-
- CallHierarchyViewPart getPart() {
- return fPart;
- }
-
- /**
- *
- */
- void setFocus() {
- getControl().setFocus();
- }
-
- boolean isInFocus() {
- return getControl().isFocusControl();
- }
-
- /**
- * @param keyListener
- */
- void addKeyListener(KeyListener keyListener) {
- getControl().addKeyListener(keyListener);
- }
-
- /**
- * Wraps the root of a MethodWrapper tree in a dummy root in order to show
- * it in the tree.
- *
- * @param root The root of the MethodWrapper tree.
- * @return A new MethodWrapper which is a dummy root above the specified root.
- */
- private TreeRoot getTreeRoot(MethodWrapper root) {
- TreeRoot dummyRoot = new TreeRoot(root);
-
- return dummyRoot;
- }
-
- /**
- * Attaches a contextmenu listener to the tree
- * @param menuListener the menu listener
- * @param viewSite the view site
- * @param selectionProvider the selection provider
- */
- void initContextMenu(IMenuListener menuListener, IWorkbenchPartSite viewSite, ISelectionProvider selectionProvider) {
- MenuManager menuMgr= new MenuManager();
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(menuListener);
- Menu menu= menuMgr.createContextMenu(getTree());
- getTree().setMenu(menu);
- viewSite.registerContextMenu(menuMgr, selectionProvider);
- }
-
- /**
- *
- */
- void clearViewer() {
- setInput(TreeRoot.EMPTY_ROOT);
- }
-
- void cancelJobs() {
- if (fPart == null)
- return;
- fContentProvider.cancelJobs(fPart.getCurrentMethodWrapper());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CancelSearchAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CancelSearchAction.java
deleted file mode 100644
index 7fda702d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CancelSearchAction.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * This class is copied from the org.eclipse.search2.internal.ui.CancelSearchAction class.
- */
-public class CancelSearchAction extends Action {
-
- private CallHierarchyViewPart fView;
-
- public CancelSearchAction(CallHierarchyViewPart view) {
- super(CallHierarchyMessages.CancelSearchAction_label);
- fView= view;
- setToolTipText(CallHierarchyMessages.CancelSearchAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "ch_cancel.gif"); //$NON-NLS-1$
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_CANCEL_SEARCH_ACTION);
-}
-
- public void run() {
- fView.cancelJobs();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CopyCallHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CopyCallHierarchyAction.java
deleted file mode 100644
index b2dd2eec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CopyCallHierarchyAction.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-
-class CopyCallHierarchyAction extends Action {
- private static final char INDENTATION= '\t';
-
- private CallHierarchyViewPart fView;
- private CallHierarchyViewer fViewer;
-
- private final Clipboard fClipboard;
-
- public CopyCallHierarchyAction(CallHierarchyViewPart view, Clipboard clipboard, CallHierarchyViewer viewer) {
- super(CallHierarchyMessages.CopyCallHierarchyAction_label);
- Assert.isNotNull(clipboard);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_COPY_ACTION);
- fView= view;
- fClipboard= clipboard;
- fViewer= viewer;
- }
-
- public boolean canActionBeAdded() {
- Object element = SelectionUtil.getSingleElement(getSelection());
- return element != null;
- }
-
- private ISelection getSelection() {
- ISelectionProvider provider = fView.getSite().getSelectionProvider();
-
- if (provider != null) {
- return provider.getSelection();
- }
-
- return null;
- }
-
- /*
- * @see IAction#run()
- */
- public void run() {
- StringBuffer buf= new StringBuffer();
- addCalls(fViewer.getTree().getSelection()[0], 0, buf);
-
- TextTransfer plainTextTransfer = TextTransfer.getInstance();
- try{
- fClipboard.setContents(
- new String[]{ convertLineTerminators(buf.toString()) },
- new Transfer[]{ plainTextTransfer });
- } catch (SWTError e){
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD)
- throw e;
- if (MessageDialog.openQuestion(fView.getViewSite().getShell(), CallHierarchyMessages.CopyCallHierarchyAction_problem, CallHierarchyMessages.CopyCallHierarchyAction_clipboard_busy))
- run();
- }
- }
-
- /**
- * Adds the specified TreeItem's text to the StringBuffer
- *
- * @param item
- * @param buf
- */
- private void addCalls(TreeItem item, int indent, StringBuffer buf) {
- for (int i= 0; i < indent; i++) {
- buf.append(INDENTATION);
- }
-
- buf.append(item.getText());
- buf.append('\n');
-
- if (item.getExpanded()) {
- TreeItem[] items= item.getItems();
- for (int i= 0; i < items.length; i++) {
- addCalls(items[i], indent + 1, buf);
- }
- }
- }
-
- static String convertLineTerminators(String in) {
- StringWriter stringWriter= new StringWriter();
- PrintWriter printWriter= new PrintWriter(stringWriter);
- StringReader stringReader= new StringReader(in);
- BufferedReader bufferedReader= new BufferedReader(stringReader);
- try {
- String line= bufferedReader.readLine();
- while (line != null) {
- printWriter.print(line);
- line= bufferedReader.readLine();
- if (line != null && line.length() != 0)
- printWriter.println();
-
- }
- } catch (IOException e) {
- return in; // return the call hierarchy unfiltered
- }
- return stringWriter.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/DeferredMethodWrapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/DeferredMethodWrapper.java
deleted file mode 100644
index 0b8cc4a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/DeferredMethodWrapper.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.ui.progress.IDeferredWorkbenchAdapter;
-import org.eclipse.ui.progress.IElementCollector;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class DeferredMethodWrapper extends MethodWrapperWorkbenchAdapter implements IDeferredWorkbenchAdapter {
- private final CallHierarchyContentProvider fProvider;
-
- /**
- * A simple job scheduling rule for serializing jobs that shouldn't be run
- * concurrently.
- */
- private class BatchSimilarSchedulingRule implements ISchedulingRule {
- public String id;
-
- public BatchSimilarSchedulingRule(String id) {
- this.id = id;
- }
-
- /*
- * @see org.eclipse.core.runtime.jobs.ISchedulingRule#isConflicting(org.eclipse.core.runtime.jobs.ISchedulingRule)
- */
- public boolean isConflicting(ISchedulingRule rule) {
- if (rule instanceof BatchSimilarSchedulingRule) {
- return ((BatchSimilarSchedulingRule) rule).id.equals(id);
- }
- return false;
- }
-
- /*
- * @see org.eclipse.core.runtime.jobs.ISchedulingRule#contains(org.eclipse.core.runtime.jobs.ISchedulingRule)
- */
- public boolean contains(ISchedulingRule rule) {
- return this == rule;
- }
- }
-
- DeferredMethodWrapper(CallHierarchyContentProvider provider, MethodWrapper methodWrapper) {
- super(methodWrapper);
- this.fProvider = provider;
- }
-
- private Object getCalls(IProgressMonitor monitor) {
- return getMethodWrapper().getCalls(monitor);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.progress.IDeferredWorkbenchAdapter#fetchDeferredChildren(java.lang.Object,
- * org.eclipse.jface.progress.IElementCollector,
- * org.eclipse.core.runtime.IProgressMonitor)
- */
- public void fetchDeferredChildren(Object object, IElementCollector collector, IProgressMonitor monitor) {
- try {
- fProvider.startFetching();
- DeferredMethodWrapper methodWrapper = (DeferredMethodWrapper) object;
- collector.add((Object[]) methodWrapper.getCalls(monitor), monitor);
- collector.done();
- } catch (OperationCanceledException e) {
- collector.add(new Object[] { TreeTermination.SEARCH_CANCELED }, monitor);
- } catch (Exception e) {
- JavaScriptPlugin.log(e);
- } finally {
- fProvider.doneFetching();
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.progress.IDeferredWorkbenchAdapter#isContainer()
- */
- public boolean isContainer() {
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.progress.IDeferredWorkbenchAdapter#getRule()
- */
- public ISchedulingRule getRule(Object o) {
- return new BatchSimilarSchedulingRule("org.eclipse.wst.jsdt.ui.callhierarchy.methodwrapper"); //$NON-NLS-1$
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object)
- */
- public Object[] getChildren(Object o) {
- return this.fProvider.fetchChildren(((DeferredMethodWrapper) o).getMethodWrapper());
- }
-
- /**
- * Returns an object which is an instance of the given class associated
- * with this object. Returns <code>null</code> if no such object can be
- * found.
- */
- public Object getAdapter(Class adapter) {
- if (adapter == IDeferredWorkbenchAdapter.class)
- return this;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FiltersDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FiltersDialog.java
deleted file mode 100644
index f09c94ec..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FiltersDialog.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallHierarchy;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-class FiltersDialog extends StatusDialog {
- private Label fNamesHelpText;
- private Button fFilterOnNames;
- private Text fNames;
- private Text fMaxCallDepth;
-
- /**
- * @param parentShell
- */
- protected FiltersDialog(Shell parentShell) {
- super(parentShell);
- }
-
- /* (non-Javadoc)
- * Method declared on Window.
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText(CallHierarchyMessages.FiltersDialog_filter);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.CALL_HIERARCHY_FILTERS_DIALOG);
- }
-
- /* (non-Javadoc)
- * Method declared on Dialog.
- */
- protected Control createDialogArea(Composite parent) {
- Composite superComposite = (Composite) super.createDialogArea(parent);
-
- Composite composite = new Composite(superComposite, SWT.NONE);
- composite.setFont(superComposite.getFont());
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- GridLayout layout = new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
-
- createNamesArea(composite);
- new Label(composite, SWT.NONE); // Filler
- createMaxCallDepthArea(composite);
-
- updateUIFromFilter();
-
- return composite;
- }
-
- private void createMaxCallDepthArea(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- composite.setLayout(layout);
-
- Label label= new Label(composite, SWT.NONE);
- label.setFont(composite.getFont());
- label.setText(CallHierarchyMessages.FiltersDialog_maxCallDepth);
-
- fMaxCallDepth = new Text(composite, SWT.SINGLE | SWT.BORDER);
- fMaxCallDepth.setFont(composite.getFont());
- fMaxCallDepth.setTextLimit(6);
- fMaxCallDepth.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- });
-
- GridData gridData = new GridData();
- gridData.widthHint = convertWidthInCharsToPixels(10);
- fMaxCallDepth.setLayoutData(gridData);
- }
-
- private void createNamesArea(Composite parent) {
- fFilterOnNames = createCheckbox(parent,
- CallHierarchyMessages.FiltersDialog_filterOnNames, true);
-
- fNames= new Text(parent, SWT.SINGLE | SWT.BORDER);
- fNames.setFont(parent.getFont());
- fNames.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- });
-
- GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
- gridData.widthHint = convertWidthInCharsToPixels(60);
- fNames.setLayoutData(gridData);
-
- fNamesHelpText= new Label(parent, SWT.LEFT);
- fNamesHelpText.setFont(parent.getFont());
- fNamesHelpText.setText(CallHierarchyMessages.FiltersDialog_filterOnNamesSubCaption);
- }
-
- /**
- * Creates a check box button with the given parent and text.
- *
- * @param parent the parent composite
- * @param text the text for the check box
- * @param grabRow <code>true</code>to grab the remaining horizontal space,
- * <code>false</code> otherwise
- *
- * @return the check box button
- */
- private Button createCheckbox(Composite parent, String text, boolean grabRow) {
- Button button = new Button(parent, SWT.CHECK);
- button.setFont(parent.getFont());
-
- if (grabRow) {
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
- button.setLayoutData(gridData);
- }
-
- button.setText(text);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- validateInput();
- updateEnabledState();
- }
- });
-
- return button;
- }
-
- /**
- * Updates the enabled state of the widgetry.
- */
- private void updateEnabledState() {
- fNames.setEnabled(fFilterOnNames.getSelection());
- fNamesHelpText.setEnabled(fFilterOnNames.getSelection());
- }
-
- /**
- * Updates the given filter from the UI state.
- */
- private void updateFilterFromUI() {
- int maxCallDepth = Integer.parseInt(this.fMaxCallDepth.getText());
-
- CallHierarchyUI.getDefault().setMaxCallDepth(maxCallDepth);
- CallHierarchy.getDefault().setFilters(fNames.getText());
- CallHierarchy.getDefault().setFilterEnabled(fFilterOnNames.getSelection());
- }
-
- /**
- * Updates the UI state from the given filter.
- */
- private void updateUIFromFilter() {
- fMaxCallDepth.setText(String.valueOf(CallHierarchyUI.getDefault().getMaxCallDepth()));
- fNames.setText(CallHierarchy.getDefault().getFilters());
- fFilterOnNames.setSelection(CallHierarchy.getDefault().isFilterEnabled());
- updateEnabledState();
- }
-
- /**
- * Updates the filter from the UI state.
- * Must be done here rather than by extending open()
- * because after super.open() is called, the widgetry is disposed.
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- if (!isMaxCallDepthValid()) {
- if (fMaxCallDepth.forceFocus()) {
- fMaxCallDepth.setSelection(0, fMaxCallDepth.getCharCount());
- fMaxCallDepth.showSelection();
- }
- }
-
- updateFilterFromUI();
- super.okPressed();
- }
-
- private boolean isMaxCallDepthValid() {
- String text= fMaxCallDepth.getText();
- if (text.length() == 0)
- return false;
-
- try {
- int maxCallDepth= Integer.parseInt(text);
-
- return (maxCallDepth >= 1 && maxCallDepth <= 99);
- } catch (NumberFormatException e) {
- return false;
- }
- }
-
- private void validateInput() {
- StatusInfo status= new StatusInfo();
- if (!isMaxCallDepthValid()) {
- status.setError(CallHierarchyMessages.FiltersDialog_messageMaxCallDepthInvalid);
- }
- updateStatus(status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FocusOnSelectionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FocusOnSelectionAction.java
deleted file mode 100644
index 84873d3c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/FocusOnSelectionAction.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-
-class FocusOnSelectionAction extends Action {
- private CallHierarchyViewPart fPart;
-
- public FocusOnSelectionAction(CallHierarchyViewPart part) {
- super(CallHierarchyMessages.FocusOnSelectionAction_focusOnSelection_text);
- fPart= part;
- setDescription(CallHierarchyMessages.FocusOnSelectionAction_focusOnSelection_description);
- setToolTipText(CallHierarchyMessages.FocusOnSelectionAction_focusOnSelection_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION);
- }
-
- public boolean canActionBeAdded() {
- Object element = SelectionUtil.getSingleElement(getSelection());
-
- IFunction method = getSelectedMethod(element);
-
- if (method != null) {
- setText(Messages.format(CallHierarchyMessages.FocusOnSelectionAction_focusOn_text, method.getElementName()));
-
- return true;
- }
-
- return false;
- }
-
- private IFunction getSelectedMethod(Object element) {
- IFunction method = null;
-
- if (element instanceof IFunction) {
- method= (IFunction) element;
- } else if (element instanceof MethodWrapper) {
- IMember member= ((MethodWrapper) element).getMember();
- if (member.getElementType() == IJavaScriptElement.METHOD) {
- method= (IFunction) member;
- }
- }
- return method;
- }
-
- /*
- * @see Action#run
- */
- public void run() {
- Object element = SelectionUtil.getSingleElement(getSelection());
-
- IFunction method= getSelectedMethod(element);
- if (method != null) {
- fPart.setMethod(method);
- }
- }
-
- private ISelection getSelection() {
- ISelectionProvider provider = fPart.getSite().getSelectionProvider();
-
- if (provider != null) {
- return provider.getSelection();
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryAction.java
deleted file mode 100644
index a68a1958..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryAction.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * Action used for the type hierarchy forward / backward buttons
- */
-class HistoryAction extends Action {
- private static JavaScriptElementLabelProvider fLabelProvider = new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_POST_QUALIFIED |
- JavaScriptElementLabelProvider.SHOW_PARAMETERS |
- JavaScriptElementLabelProvider.SHOW_RETURN_TYPE);
- private CallHierarchyViewPart fView;
- private IFunction fMethod;
-
- public HistoryAction(CallHierarchyViewPart viewPart, IFunction element) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- fView = viewPart;
- fMethod = element;
-
- String elementName = getElementLabel(element);
- setText(elementName);
- setImageDescriptor(getImageDescriptor(element));
-
- setDescription(Messages.format(CallHierarchyMessages.HistoryAction_description, elementName));
- setToolTipText(Messages.format(CallHierarchyMessages.HistoryAction_tooltip, elementName));
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_HISTORY_ACTION);
- }
-
- private ImageDescriptor getImageDescriptor(IJavaScriptElement elem) {
- JavaElementImageProvider imageProvider = new JavaElementImageProvider();
- ImageDescriptor desc = imageProvider.getBaseImageDescriptor(elem, 0);
- imageProvider.dispose();
-
- return desc;
- }
-
- /*
- * @see Action#run()
- */
- public void run() {
- fView.gotoHistoryEntry(fMethod);
- }
-
- /**
- * @param element
- * @return String
- */
- private String getElementLabel(IJavaScriptElement element) {
- Assert.isNotNull(element);
- return fLabelProvider.getText(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryDropDownAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryDropDownAction.java
deleted file mode 100644
index cb995d91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryDropDownAction.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-
-class HistoryDropDownAction extends Action implements IMenuCreator {
-
- private static class ClearHistoryAction extends Action {
-
- private CallHierarchyViewPart fView;
-
- public ClearHistoryAction(CallHierarchyViewPart view) {
- super(CallHierarchyMessages.HistoryDropDownAction_clearhistory_label);
- fView= view;
- }
-
- public void run() {
- fView.setHistoryEntries(new IFunction[0]);
- fView.setMethod(null);
- }
- }
-
- public static final int RESULTS_IN_DROP_DOWN = 10;
- private CallHierarchyViewPart fView;
- private Menu fMenu;
-
- public HistoryDropDownAction(CallHierarchyViewPart view) {
- fView = view;
- fMenu = null;
- setToolTipText(CallHierarchyMessages.HistoryDropDownAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION);
-
- setMenuCreator(this);
- }
-
- public Menu getMenu(Menu parent) {
- return null;
- }
-
- public Menu getMenu(Control parent) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- fMenu= new Menu(parent);
- IFunction[] elements= fView.getHistoryEntries();
- addEntries(fMenu, elements);
- new MenuItem(fMenu, SWT.SEPARATOR);
- addActionToMenu(fMenu, new HistoryListAction(fView));
- addActionToMenu(fMenu, new ClearHistoryAction(fView));
- return fMenu;
- }
-
- public void dispose() {
- fView = null;
-
- if (fMenu != null) {
- fMenu.dispose();
- fMenu = null;
- }
- }
-
- protected void addActionToMenu(Menu parent, Action action) {
- ActionContributionItem item = new ActionContributionItem(action);
- item.fill(parent, -1);
- }
-
- private boolean addEntries(Menu menu, IFunction[] elements) {
- boolean checked = false;
-
- int min = Math.min(elements.length, RESULTS_IN_DROP_DOWN);
-
- for (int i = 0; i < min; i++) {
- HistoryAction action = new HistoryAction(fView, elements[i]);
- action.setChecked(elements[i].equals(fView.getMethod()));
- checked = checked || action.isChecked();
- addActionToMenu(menu, action);
- }
-
- return checked;
- }
-
- public void run() {
- (new HistoryListAction(fView)).run();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryListAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryListAction.java
deleted file mode 100644
index 44d25cc9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/HistoryListAction.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class HistoryListAction extends Action {
-
- private class HistoryListDialog extends StatusDialog {
-
- private ListDialogField fHistoryList;
- private IStatus fHistoryStatus;
- private IFunction fResult;
-
- private HistoryListDialog(Shell shell, IFunction[] elements) {
- super(shell);
- setTitle(CallHierarchyMessages.HistoryListDialog_title);
-
- String[] buttonLabels= new String[] {
- CallHierarchyMessages.HistoryListDialog_remove_button,
- };
-
- IListAdapter adapter= new IListAdapter() {
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed();
- }
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged();
- }
-
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked();
- }
- };
-
- JavaScriptElementLabelProvider labelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_QUALIFIED | JavaScriptElementLabelProvider.SHOW_ROOT);
-
- fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider);
- fHistoryList.setLabelText(CallHierarchyMessages.HistoryListDialog_label);
- fHistoryList.setElements(Arrays.asList(elements));
-
- ISelection sel;
- if (elements.length > 0) {
- sel= new StructuredSelection(elements[0]);
- } else {
- sel= new StructuredSelection();
- }
-
- fHistoryList.selectElements(sel);
- }
-
-
- /*
- * @see Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- inner.setFont(composite.getFont());
-
- LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0);
- LayoutUtil.setHeightHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12));
- LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null));
-
- applyDialogFont(composite);
- return composite;
- }
-
- /**
- * Method doCustomButtonPressed.
- */
- private void doCustomButtonPressed() {
- fHistoryList.removeElements(fHistoryList.getSelectedElements());
- }
-
- private void doDoubleClicked() {
- if (fHistoryStatus.isOK()) {
- okPressed();
- }
- }
-
-
- private void doSelectionChanged() {
- StatusInfo status= new StatusInfo();
- List selected= fHistoryList.getSelectedElements();
- if (selected.size() != 1) {
- status.setError(""); //$NON-NLS-1$
- fResult= null;
- } else {
- fResult= (IFunction) selected.get(0);
- }
- fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size() && selected.size() != 0);
- fHistoryStatus= status;
- updateStatus(status);
- }
-
- public IFunction getResult() {
- return fResult;
- }
-
- public IFunction[] getRemaining() {
- List elems= fHistoryList.getElements();
- return (IFunction[]) elems.toArray(new IFunction[elems.size()]);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#create()
- */
- public void create() {
- setShellStyle(getShellStyle() | SWT.RESIZE);
- super.create();
- }
-
- }
-
- private CallHierarchyViewPart fView;
-
- public HistoryListAction(CallHierarchyViewPart view) {
- fView= view;
- setText(CallHierarchyMessages.HistoryListAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION);
- }
-
- /*
- * @see IAction#run()
- */
- public void run() {
- IFunction[] historyEntries= fView.getHistoryEntries();
- HistoryListDialog dialog= new HistoryListDialog(JavaScriptPlugin.getActiveWorkbenchShell(), historyEntries);
- if (dialog.open() == Window.OK) {
- fView.setHistoryEntries(dialog.getRemaining());
- fView.setMethod(dialog.getResult());
- }
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ICallHierarchyViewPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ICallHierarchyViewPart.java
deleted file mode 100644
index f4b7bff0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ICallHierarchyViewPart.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-/**
- * Marker interface for the call hierarchy view to be used outside.
- */
-public interface ICallHierarchyViewPart {
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationCopyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationCopyAction.java
deleted file mode 100644
index 0d57bc40..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationCopyAction.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.Iterator;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallLocation;
-
-/**
- * Copies the selection from the location viewer.
- */
-class LocationCopyAction extends Action {
- private final Clipboard fClipboard;
- private final IViewSite fViewSite;
- private final LocationViewer fLocationViewer;
-
- LocationCopyAction(IViewSite viewSite, Clipboard clipboard, LocationViewer locationViewer) {
- fClipboard= clipboard;
- fViewSite= viewSite;
- fLocationViewer= locationViewer;
-
- setText(CallHierarchyMessages.LocationCopyAction_copy);
- setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
-
- locationViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- setEnabled(! event.getSelection().isEmpty());
- }
- });
- }
-
- public void run() {
- IStructuredSelection selection= (IStructuredSelection) fLocationViewer.getSelection();
- StringBuffer buf= new StringBuffer();
- for (Iterator iterator= selection.iterator(); iterator.hasNext();) {
- CallLocation location= (CallLocation) iterator.next();
- buf.append(location.getLineNumber()).append('\t').append(location.getCallText());
- buf.append('\n');
- }
- TextTransfer plainTextTransfer = TextTransfer.getInstance();
- try {
- fClipboard.setContents(
- new String[]{ CopyCallHierarchyAction.convertLineTerminators(buf.toString()) },
- new Transfer[]{ plainTextTransfer });
- } catch (SWTError e){
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD)
- throw e;
- if (MessageDialog.openQuestion(fViewSite.getShell(), CallHierarchyMessages.CopyCallHierarchyAction_problem, CallHierarchyMessages.CopyCallHierarchyAction_clipboard_busy))
- run();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationLabelProvider.java
deleted file mode 100644
index ded7b84f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationLabelProvider.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallLocation;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-class LocationLabelProvider extends LabelProvider implements ITableLabelProvider {
- private static final int COLUMN_ICON= 0;
- private static final int COLUMN_LINE= 1;
- private static final int COLUMN_INFO= 2;
-
- LocationLabelProvider() {
- // Do nothing
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- return getColumnText(element, COLUMN_INFO);
- }
-
- public Image getImage(Object element) {
- return getColumnImage(element, COLUMN_ICON);
- }
-
- private String removeWhitespaceOutsideStringLiterals(CallLocation callLocation) {
- StringBuffer buf = new StringBuffer();
- boolean withinString = false;
-
- String s= callLocation.getCallText();
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
-
- if (ch == '"') {
- withinString = !withinString;
- }
-
- if (withinString) {
- buf.append(ch);
- } else if (Character.isWhitespace(ch)) {
- if ((buf.length() == 0) ||
- !Character.isWhitespace(buf.charAt(buf.length() - 1))) {
- if (ch != ' ') {
- ch = ' ';
- }
-
- buf.append(ch);
- }
- } else {
- buf.append(ch);
- }
- }
-
- return buf.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == COLUMN_ICON) {
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_OCCURRENCE);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- if (element instanceof CallLocation) {
- CallLocation callLocation= (CallLocation) element;
-
- switch (columnIndex) {
- case COLUMN_LINE:
- int lineNumber= callLocation.getLineNumber();
- if (lineNumber == CallLocation.UNKNOWN_LINE_NUMBER) {
- return CallHierarchyMessages.LocationLabelProvider_unknown;
- } else {
- return String.valueOf(lineNumber);
- }
- case COLUMN_INFO:
- return removeWhitespaceOutsideStringLiterals(callLocation);
- }
- }
-
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationViewer.java
deleted file mode 100644
index f6660a37..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/LocationViewer.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.ArrayList;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnPixelData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.actions.ActionFactory;
-
-
-
-class LocationViewer extends TableViewer {
- private final String columnHeaders[] = {
- CallHierarchyMessages.LocationViewer_ColumnIcon_header,
- CallHierarchyMessages.LocationViewer_ColumnLine_header,
- CallHierarchyMessages.LocationViewer_ColumnInfo_header};
-
- private ColumnLayoutData columnLayouts[] = {
- new ColumnPixelData(18, false, true),
- new ColumnWeightData(60),
- new ColumnWeightData(300)};
-
-
- LocationViewer(Composite parent) {
- super(createTable(parent));
-
- setContentProvider(new ArrayContentProvider());
- setLabelProvider(new LocationLabelProvider());
- setInput(new ArrayList());
-
- createColumns();
- }
-
- /**
- * Creates the table control.
- */
- private static Table createTable(Composite parent) {
- return new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
- }
-
- private void createColumns() {
- TableLayout layout = new TableLayout();
- getTable().setLayout(layout);
- getTable().setHeaderVisible(true);
- for (int i = 0; i < columnHeaders.length; i++) {
- layout.addColumnData(columnLayouts[i]);
- TableColumn tc = new TableColumn(getTable(), SWT.NONE,i);
- tc.setResizable(columnLayouts[i].resizable);
- tc.setText(columnHeaders[i]);
- }
- }
-
- /**
- * Attaches a contextmenu listener to the tree
- */
- void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
- MenuManager menuMgr= new MenuManager();
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(menuListener);
- Menu menu= menuMgr.createContextMenu(getControl());
- getControl().setMenu(menu);
- viewSite.registerContextMenu(popupId, menuMgr, this);
- }
-
- /**
- * Initializes and returns the Copy action for the location viewer.
- */
- LocationCopyAction initCopyAction(final IViewSite viewSite, final Clipboard clipboard) {
- final LocationCopyAction copyAction= new LocationCopyAction(viewSite, clipboard, this);
-
- getTable().addFocusListener(new FocusListener() {
- IAction fViewCopyHandler;
- public void focusLost(FocusEvent e) {
- if (fViewCopyHandler != null) {
- IActionBars actionBars= viewSite.getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), fViewCopyHandler);
- actionBars.updateActionBars();
- fViewCopyHandler= null;
- }
- }
-
- public void focusGained(FocusEvent e) {
- IActionBars actionBars= viewSite.getActionBars();
- fViewCopyHandler= actionBars.getGlobalActionHandler(ActionFactory.COPY.getId());
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction);
- actionBars.updateActionBars();
- }
- });
-
- return copyAction;
- }
-
- /**
- *
- */
- void clearViewer() {
- setInput(""); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/MethodWrapperWorkbenchAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/MethodWrapperWorkbenchAdapter.java
deleted file mode 100644
index 2c2a90cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/MethodWrapperWorkbenchAdapter.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-
-public class MethodWrapperWorkbenchAdapter implements IWorkbenchAdapter {
-
- private final MethodWrapper fMethodWrapper;
-
- public MethodWrapperWorkbenchAdapter(MethodWrapper methodWrapper) {
- Assert.isNotNull(methodWrapper);
- fMethodWrapper= methodWrapper;
- }
-
- public MethodWrapper getMethodWrapper() {
- return fMethodWrapper;
- }
-
- public Object[] getChildren(Object o) { //should not be called
- return new Object[0];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getImageDescriptor(java.lang.Object)
- */
- public ImageDescriptor getImageDescriptor(Object object) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object)
- */
- public String getLabel(Object o) {
- return fMethodWrapper.getMember().getElementName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getParent(java.lang.Object)
- */
- public Object getParent(Object o) {
- return fMethodWrapper.getParent();
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- //Note: A MethodWrapperWorkbenchAdapter is equal to its MethodWrapper and vice versa (bug 101677).
- return fMethodWrapper.equals(obj);
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- //Note: A MethodWrapperWorkbenchAdapter is equal to its MethodWrapper and vice versa (bug 101677).
- return fMethodWrapper.hashCode();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenCallHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenCallHierarchyAction.java
deleted file mode 100644
index e072511b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenCallHierarchyAction.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-/**
- * This action opens a call hierarchy on the selected method.
- * <p>
- * The action is applicable to selections containing elements of type
- * <code>IFunction</code>.
- */
-public class OpenCallHierarchyAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>OpenCallHierarchyAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OpenCallHierarchyAction(IWorkbenchSite site) {
- super(site);
- setText(CallHierarchyMessages.OpenCallHierarchyAction_label);
- setToolTipText(CallHierarchyMessages.OpenCallHierarchyAction_tooltip);
- setDescription(CallHierarchyMessages.OpenCallHierarchyAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_OPEN_ACTION);
-
- }
-
- /**
- * Creates a new <code>OpenCallHierarchyAction</code>. The action requires
- * that the selection provided by the given selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param provider a special selection provider which is used instead
- * of the site's selection provider or <code>null</code> to use the site's
- * selection provider
- *
- *
- * @deprecated Use {@link #setSpecialSelectionProvider(ISelectionProvider)} instead. This API will be
- * removed after 3.2 M5.
- */
- public OpenCallHierarchyAction(IWorkbenchSite site, ISelectionProvider provider) {
- this(site);
- setSpecialSelectionProvider(provider);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- */
- public OpenCallHierarchyAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- // Do nothing
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(isEnabled(selection));
- }
-
- private boolean isEnabled(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
- Object input= selection.getFirstElement();
- if (!(input instanceof IJavaScriptElement))
- return false;
- switch (((IJavaScriptElement)input).getElementType()) {
- case IJavaScriptElement.METHOD:
- return true;
- default:
- return false;
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptElement input= SelectionConverter.getInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
-
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveOrInputForked(fEditor);
- if (elements == null)
- return;
- List candidates= new ArrayList(elements.length);
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement[] resolvedElements= CallHierarchyUI.getCandidates(elements[i]);
- if (resolvedElements != null)
- candidates.addAll(Arrays.asList(resolvedElements));
- }
- if (candidates.isEmpty()) {
- IJavaScriptElement enclosingMethod= getEnclosingMethod(input, selection);
- if (enclosingMethod != null) {
- candidates.add(enclosingMethod);
- }
- }
- run((IJavaScriptElement[])candidates.toArray(new IJavaScriptElement[candidates.size()]));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), getErrorDialogTitle(), ActionMessages.SelectionConverter_codeResolve_failed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- private IJavaScriptElement getEnclosingMethod(IJavaScriptElement input, ITextSelection selection) {
- IJavaScriptElement enclosingElement= null;
- try {
- switch (input.getElementType()) {
- case IJavaScriptElement.CLASS_FILE :
- IClassFile classFile= (IClassFile) input.getAncestor(IJavaScriptElement.CLASS_FILE);
- if (classFile != null) {
- enclosingElement= classFile.getElementAt(selection.getOffset());
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- IJavaScriptUnit cu= (IJavaScriptUnit) input.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- enclosingElement= cu.getElementAt(selection.getOffset());
- }
- break;
- }
- if (enclosingElement != null && enclosingElement.getElementType() == IJavaScriptElement.METHOD) {
- return enclosingElement;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- return null;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (selection.size() != 1)
- return;
- Object input= selection.getFirstElement();
-
- if (!(input instanceof IJavaScriptElement)) {
- IStatus status= createStatus(CallHierarchyMessages.OpenCallHierarchyAction_messages_no_java_element);
- openErrorDialog(status);
- return;
- }
- IJavaScriptElement element= (IJavaScriptElement) input;
- if (!ActionUtil.isProcessable(getShell(), element))
- return;
-
- List result= new ArrayList(1);
- IStatus status= compileCandidates(result, element);
- if (status.isOK()) {
- run((IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]));
- } else {
- openErrorDialog(status);
- }
- }
-
- private int openErrorDialog(IStatus status) {
- String message= CallHierarchyMessages.OpenCallHierarchyAction_messages_title;
- String dialogTitle= getErrorDialogTitle();
- return ErrorDialog.openError(getShell(), dialogTitle, message, status);
- }
-
- private static String getErrorDialogTitle() {
- return CallHierarchyMessages.OpenCallHierarchyAction_dialog_title;
- }
-
- public void run(IJavaScriptElement[] elements) {
- if (elements.length == 0) {
- getShell().getDisplay().beep();
- return;
- }
- CallHierarchyUI.open(elements, getSite().getWorkbenchWindow());
- }
-
- private static IStatus compileCandidates(List result, IJavaScriptElement elem) {
- IStatus ok= new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
- switch (elem.getElementType()) {
- case IJavaScriptElement.METHOD:
- result.add(elem);
- return ok;
- }
- return createStatus(CallHierarchyMessages.OpenCallHierarchyAction_messages_no_valid_java_element);
- }
-
- private static IStatus createStatus(String message) {
- return new Status(IStatus.INFO, JavaScriptPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenDeclarationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenDeclarationAction.java
deleted file mode 100644
index b93a94f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenDeclarationAction.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-
-/**
- * This class is used for opening the declaration of an element from the call hierarchy view.
- */
-class OpenDeclarationAction extends OpenAction {
- public OpenDeclarationAction(IWorkbenchSite site) {
- super(site);
- }
-
- public boolean canActionBeAdded() {
- // It is safe to cast to IMember since the selection has already been converted
- IMember member = (IMember) SelectionUtil.getSingleElement(getSelection());
-
- if (member != null) {
- return true;
- }
-
- return false;
- }
-
- public ISelection getSelection() {
- return CallHierarchyUI.convertSelection(getSelectionProvider().getSelection());
- }
-
- public Object getElementToOpen(Object object) {
- if (object instanceof MethodWrapper) {
- return ((MethodWrapper) object).getMember();
- }
- return object;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenLocationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenLocationAction.java
deleted file mode 100644
index 11d5c28c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/OpenLocationAction.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.Iterator;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.CallLocation;
-import org.eclipse.wst.jsdt.internal.corext.callhierarchy.MethodWrapper;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-class OpenLocationAction extends SelectionDispatchAction {
- private CallHierarchyViewPart fPart;
-
- public OpenLocationAction(CallHierarchyViewPart part, IWorkbenchSite site) {
- super(site);
- fPart= part;
- setText(CallHierarchyMessages.OpenLocationAction_label);
- setToolTipText(CallHierarchyMessages.OpenLocationAction_tooltip);
- }
-
- private boolean checkEnabled(IStructuredSelection selection) {
- if (selection.isEmpty()) {
- return false;
- }
-
- for (Iterator iter = selection.iterator(); iter.hasNext();) {
- Object element = iter.next();
-
- if (element instanceof MethodWrapper) {
- continue;
- } else if (element instanceof CallLocation) {
- continue;
- }
-
- return false;
- }
-
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#getSelection()
- */
- public ISelection getSelection() {
- return fPart.getSelection();
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (!checkEnabled(selection)) {
- return;
- }
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- boolean noError= CallHierarchyUI.openInEditor(iter.next(), getShell(), getDialogTitle());
- if (! noError)
- return;
- }
- }
-
- private String getDialogTitle() {
- return CallHierarchyMessages.OpenLocationAction_error_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/RefreshAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/RefreshAction.java
deleted file mode 100644
index 728129d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/RefreshAction.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-class RefreshAction extends Action {
- private CallHierarchyViewPart fPart;
-
- public RefreshAction(CallHierarchyViewPart part) {
- fPart= part;
- setText(CallHierarchyMessages.RefreshAction_text);
- setToolTipText(CallHierarchyMessages.RefreshAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "refresh_nav.gif");//$NON-NLS-1$
- setActionDefinitionId("org.eclipse.ui.file.refresh"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_REFRESH_ACTION);
- }
-
- /**
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- fPart.refresh();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeAction.java
deleted file mode 100644
index b3fa2312..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeAction.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-
-
-abstract class SearchScopeAction extends Action {
- private final SearchScopeActionGroup fGroup;
-
- public SearchScopeAction(SearchScopeActionGroup group, String text) {
- super(text, AS_RADIO_BUTTON);
- this.fGroup = group;
- }
-
- public abstract IJavaScriptSearchScope getSearchScope();
-
- public abstract int getSearchScopeType();
-
- public void run() {
- this.fGroup.setSelected(this, true);
- }
-
- public abstract String getFullDescription();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeActionGroup.java
deleted file mode 100644
index aae31fc0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeActionGroup.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-class SearchScopeActionGroup extends ActionGroup {
- private static final String TAG_SEARCH_SCOPE_TYPE= "search_scope_type"; //$NON-NLS-1$
- private static final String TAG_SELECTED_WORKING_SET= "working_set"; //$NON-NLS-1$
- private static final String TAG_WORKING_SET_COUNT = "working_set_count"; //$NON-NLS-1$
-
- private static final String DIALOGSTORE_SCOPE_TYPE= "SearchScopeActionGroup.search_scope_type"; //$NON-NLS-1$
- private static final String DIALOGSTORE_SELECTED_WORKING_SET= "SearchScopeActionGroup.working_set"; //$NON-NLS-1$
-
- static final int SEARCH_SCOPE_TYPE_WORKSPACE= 1;
- static final int SEARCH_SCOPE_TYPE_PROJECT= 2;
- static final int SEARCH_SCOPE_TYPE_HIERARCHY= 3;
- static final int SEARCH_SCOPE_TYPE_WORKING_SET= 4;
-
- private SearchScopeAction fSelectedAction = null;
- private String[] fSelectedWorkingSetNames = null;
- private CallHierarchyViewPart fView;
- private IDialogSettings fDialogSettings;
- private SearchScopeHierarchyAction fSearchScopeHierarchyAction;
- private SearchScopeProjectAction fSearchScopeProjectAction;
- private SearchScopeWorkspaceAction fSearchScopeWorkspaceAction;
- private SelectWorkingSetAction fSelectWorkingSetAction;
-
- public SearchScopeActionGroup(CallHierarchyViewPart view, IDialogSettings dialogSettings) {
- this.fView= view;
- this.fDialogSettings= dialogSettings;
- createActions();
- }
-
- /**
- * @return IJavaScriptSearchScope
- */
- public IJavaScriptSearchScope getSearchScope() {
- if (fSelectedAction != null) {
- return fSelectedAction.getSearchScope();
- }
-
- return null;
- }
-
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- fillContextMenu(actionBars.getMenuManager());
- }
-
- protected void setActiveWorkingSets(IWorkingSet[] sets) {
- if (sets != null) {
- fSelectedWorkingSetNames = getWorkingSetNames(sets);
- fSelectedAction = new SearchScopeWorkingSetAction(this, sets, getScopeDescription(sets));
- } else {
- fSelectedWorkingSetNames = null;
- fSelectedAction = null;
- }
- }
-
- private String[] getWorkingSetNames(IWorkingSet[] sets) {
- String[] result= new String[sets.length];
- for (int i = 0; i < sets.length; i++) {
- result[i]= sets[i].getName();
- }
- return result;
- }
-
- protected IWorkingSet[] getActiveWorkingSets() {
- if (fSelectedWorkingSetNames != null) {
- return getWorkingSets(fSelectedWorkingSetNames);
- }
-
- return null;
- }
-
- private IWorkingSet[] getWorkingSets(String[] workingSetNames) {
- if (workingSetNames == null) {
- return null;
- }
- Set workingSets= new HashSet(2);
- for (int j= 0; j < workingSetNames.length; j++) {
- IWorkingSet workingSet= getWorkingSetManager().getWorkingSet(workingSetNames[j]);
- if (workingSet != null) {
- workingSets.add(workingSet);
- }
- }
-
- return (IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]);
- }
-
- /**
- * Sets the new search scope type.
- *
- * @param newSelection New action which should be the checked one
- * @param ignoreUnchecked Ignores actions which are unchecked (necessary since both the old and the new action fires).
- */
- protected void setSelected(SearchScopeAction newSelection, boolean ignoreUnchecked) {
- if (!ignoreUnchecked || newSelection.isChecked()) {
- if (newSelection instanceof SearchScopeWorkingSetAction) {
- fSelectedWorkingSetNames = getWorkingSetNames(((SearchScopeWorkingSetAction) newSelection).getWorkingSets());
- } else {
- fSelectedWorkingSetNames = null;
- }
-
- if (newSelection != null) {
- fSelectedAction= newSelection;
- } else {
- fSelectedAction= fSearchScopeWorkspaceAction;
- }
-
- fDialogSettings.put(DIALOGSTORE_SCOPE_TYPE, getSearchScopeType());
- fDialogSettings.put(DIALOGSTORE_SELECTED_WORKING_SET, fSelectedWorkingSetNames);
- }
- }
-
- protected CallHierarchyViewPart getView() {
- return fView;
- }
-
- protected IWorkingSetManager getWorkingSetManager() {
- IWorkingSetManager workingSetManager = PlatformUI.getWorkbench()
- .getWorkingSetManager();
-
- return workingSetManager;
- }
-
- protected void fillSearchActions(IMenuManager javaSearchMM) {
- Action[] actions = getActions();
-
- for (int i = 0; i < actions.length; i++) {
- Action action = actions[i];
-
- if (action.isEnabled()) {
- javaSearchMM.add(action);
- }
- }
-
- javaSearchMM.setVisible(!javaSearchMM.isEmpty());
- }
-
- public void fillContextMenu(IMenuManager menu) {
- menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
-
- MenuManager javaSearchMM = new MenuManager(CallHierarchyMessages.SearchScopeActionGroup_searchScope,
- IContextMenuConstants.GROUP_SEARCH);
- javaSearchMM.setRemoveAllWhenShown(true);
-
- javaSearchMM.addMenuListener(new IMenuListener() {
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
- */
- public void menuAboutToShow(IMenuManager manager) {
- fillSearchActions(manager);
- }
- });
-
- fillSearchActions(javaSearchMM);
- menu.appendToGroup(IContextMenuConstants.GROUP_SEARCH, javaSearchMM);
- }
-
- private Action[] getActions() {
- List actions = new ArrayList(SearchUtil.LRU_WORKINGSET_LIST_SIZE + 4);
- addAction(actions, fSearchScopeWorkspaceAction);
- addAction(actions, fSearchScopeProjectAction);
- addAction(actions, fSearchScopeHierarchyAction);
- addAction(actions, fSelectWorkingSetAction);
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- IWorkingSet[] workingSets= (IWorkingSet[])iter.next();
- String description = SearchUtil.toString(workingSets);
- SearchScopeWorkingSetAction workingSetAction = new SearchScopeWorkingSetAction(this, workingSets, description);
-
- if (isSelectedWorkingSet(workingSets)) {
- workingSetAction.setChecked(true);
- }
-
- actions.add(workingSetAction);
- }
-
- Action[] result = (Action[]) actions.toArray(new Action[actions.size()]);
-
- ensureExactlyOneCheckedAction(result);
- return result;
- }
-
- private void ensureExactlyOneCheckedAction(Action[] result) {
- int checked = getCheckedActionCount(result);
- if (checked != 1) {
- if (checked > 1) {
- for (int i = 0; i < result.length; i++) {
- Action action = result[i];
- action.setChecked(false);
- }
- }
- fSearchScopeWorkspaceAction.setChecked(true);
- }
- }
-
- private int getCheckedActionCount(Action[] result) {
- // Ensure that exactly one action is selected
- int checked= 0;
- for (int i = 0; i < result.length; i++) {
- Action action = result[i];
- if (action.isChecked()) {
- checked++;
- }
- }
- return checked;
- }
-
- private void addAction(List actions, Action action) {
- if (action == fSelectedAction) {
- action.setChecked(true);
- } else {
- action.setChecked(false);
- }
-
- actions.add(action);
- }
-
- private void createActions() {
- fSearchScopeWorkspaceAction = new SearchScopeWorkspaceAction(this);
- fSelectWorkingSetAction = new SelectWorkingSetAction(this);
- fSearchScopeHierarchyAction = new SearchScopeHierarchyAction(this);
- fSearchScopeProjectAction = new SearchScopeProjectAction(this);
-
- int searchScopeType;
- try {
- searchScopeType= fDialogSettings.getInt(DIALOGSTORE_SCOPE_TYPE);
- } catch (NumberFormatException e) {
- searchScopeType= SEARCH_SCOPE_TYPE_WORKSPACE;
- }
- String[] workingSetNames= fDialogSettings.getArray(DIALOGSTORE_SELECTED_WORKING_SET);
- setSelected(getSearchScopeAction(searchScopeType, workingSetNames), false);
- }
-
- public void saveState(IMemento memento) {
- int type= getSearchScopeType();
- memento.putInteger(TAG_SEARCH_SCOPE_TYPE, type);
- if (type == SEARCH_SCOPE_TYPE_WORKING_SET) {
- memento.putInteger(TAG_WORKING_SET_COUNT, fSelectedWorkingSetNames.length);
- for (int i = 0; i < fSelectedWorkingSetNames.length; i++) {
- String workingSetName = fSelectedWorkingSetNames[i];
- memento.putString(TAG_SELECTED_WORKING_SET+i, workingSetName);
- }
- }
- }
-
- public void restoreState(IMemento memento) {
- String[] workingSetNames= null;
- Integer scopeType= memento.getInteger(TAG_SEARCH_SCOPE_TYPE);
- if (scopeType != null) {
- if (scopeType.intValue() == SEARCH_SCOPE_TYPE_WORKING_SET) {
- Integer workingSetCount= memento.getInteger(TAG_WORKING_SET_COUNT);
- if (workingSetCount != null) {
- workingSetNames = new String[workingSetCount.intValue()];
- for (int i = 0; i < workingSetCount.intValue(); i++) {
- workingSetNames[i]= memento.getString(TAG_SELECTED_WORKING_SET+i);
- }
- }
- }
- setSelected(getSearchScopeAction(scopeType.intValue(), workingSetNames), false);
- }
- }
-
- private SearchScopeAction getSearchScopeAction(int searchScopeType, String[] workingSetNames) {
- switch (searchScopeType) {
- case SEARCH_SCOPE_TYPE_WORKSPACE:
- return fSearchScopeWorkspaceAction;
- case SEARCH_SCOPE_TYPE_PROJECT:
- return fSearchScopeProjectAction;
- case SEARCH_SCOPE_TYPE_HIERARCHY:
- return fSearchScopeHierarchyAction;
- case SEARCH_SCOPE_TYPE_WORKING_SET:
- IWorkingSet[] workingSets= getWorkingSets(workingSetNames);
- if (workingSets != null && workingSets.length > 0) {
- return new SearchScopeWorkingSetAction(this, workingSets, getScopeDescription(workingSets));
- }
- return null;
- }
- return null;
- }
-
- private int getSearchScopeType() {
- if (fSelectedAction != null) {
- return fSelectedAction.getSearchScopeType();
- }
- return 0;
- }
-
- private String getScopeDescription(IWorkingSet[] workingSets) {
- return Messages.format(CallHierarchyMessages.WorkingSetScope, new String[] {SearchUtil.toString(workingSets)});
- }
-
- /**
- * Determines whether the specified working sets correspond to the currently selected working sets.
- * @param workingSets
- * @return Returns true if the specified working sets correspond to the currently selected working sets
- */
- private boolean isSelectedWorkingSet(IWorkingSet[] workingSets) {
- if (fSelectedWorkingSetNames != null && fSelectedWorkingSetNames.length == workingSets.length) {
- Set workingSetNames= new HashSet(workingSets.length);
- for (int i = 0; i < workingSets.length; i++) {
- workingSetNames.add(workingSets[i].getName());
- }
- for (int i = 0; i < fSelectedWorkingSetNames.length; i++) {
- if (!workingSetNames.contains(fSelectedWorkingSetNames[i])) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- public String getFullDescription() {
- if (fSelectedAction != null)
- return fSelectedAction.getFullDescription();
- return null;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeHierarchyAction.java
deleted file mode 100644
index 4130eda6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeHierarchyAction.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-
-
-class SearchScopeHierarchyAction extends SearchScopeAction {
- private final SearchScopeActionGroup fGroup;
-
- public SearchScopeHierarchyAction(SearchScopeActionGroup group) {
- super(group, CallHierarchyMessages.SearchScopeActionGroup_hierarchy_text);
- this.fGroup = group;
- setToolTipText(CallHierarchyMessages.SearchScopeActionGroup_hierarchy_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- try {
- IFunction method = this.fGroup.getView().getMethod();
-
- if (method != null) {
- return SearchEngine.createHierarchyScope(method.getDeclaringType());
- } else {
- return null;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeActionGroup.SearchScopeAction#getSearchScopeType()
- */
- public int getSearchScopeType() {
- return SearchScopeActionGroup.SEARCH_SCOPE_TYPE_HIERARCHY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeAction#getFullDescription()
- */
- public String getFullDescription() {
- IFunction method = this.fGroup.getView().getMethod();
- return JavaSearchScopeFactory.getInstance().getHierarchyScopeDescription(method.getDeclaringType());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeProjectAction.java
deleted file mode 100644
index 25bdc72d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeProjectAction.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-
-
-class SearchScopeProjectAction extends SearchScopeAction {
- private final SearchScopeActionGroup fGroup;
-
- public SearchScopeProjectAction(SearchScopeActionGroup group) {
- super(group, CallHierarchyMessages.SearchScopeActionGroup_project_text);
- this.fGroup = group;
- setToolTipText(CallHierarchyMessages.SearchScopeActionGroup_project_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- IFunction method = this.fGroup.getView().getMethod();
- if (method == null) {
- return null;
- }
-
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- return factory.createJavaProjectSearchScope(method.getJavaScriptProject(), true);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeActionGroup.SearchScopeAction#getSearchScopeType()
- */
- public int getSearchScopeType() {
- return SearchScopeActionGroup.SEARCH_SCOPE_TYPE_PROJECT;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeAction#getFullDescription()
- */
- public String getFullDescription() {
- IFunction method = this.fGroup.getView().getMethod();
- if (method != null) {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- return factory.getProjectScopeDescription(method.getJavaScriptProject(), true);
- }
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkingSetAction.java
deleted file mode 100644
index 334b2ad2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkingSetAction.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-
-
-class SearchScopeWorkingSetAction extends SearchScopeAction {
- private IWorkingSet[] fWorkingSets;
-
- public SearchScopeWorkingSetAction(SearchScopeActionGroup group, IWorkingSet[] workingSets, String name) {
- super(group, name);
- setToolTipText(CallHierarchyMessages.SearchScopeActionGroup_workingset_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
-
- this.fWorkingSets = workingSets;
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- return JavaSearchScopeFactory.getInstance().createJavaSearchScope(fWorkingSets, true);
- }
-
- /**
- *
- */
- public IWorkingSet[] getWorkingSets() {
- return fWorkingSets;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeActionGroup.SearchScopeAction#getSearchScopeType()
- */
- public int getSearchScopeType() {
- return SearchScopeActionGroup.SEARCH_SCOPE_TYPE_WORKING_SET;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeAction#getFullDescription()
- */
- public String getFullDescription() {
- return JavaSearchScopeFactory.getInstance().getWorkingSetScopeDescription(fWorkingSets, true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkspaceAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkspaceAction.java
deleted file mode 100644
index 97db3004..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchScopeWorkspaceAction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- * Michael Fraenkel (fraenkel@us.ibm.com) - patch
- * (report 60714: Call Hierarchy: display search scope in view title)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-
-
-class SearchScopeWorkspaceAction extends SearchScopeAction {
- public SearchScopeWorkspaceAction(SearchScopeActionGroup group) {
- super(group, CallHierarchyMessages.SearchScopeActionGroup_workspace_text);
- setToolTipText(CallHierarchyMessages.SearchScopeActionGroup_workspace_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- return SearchEngine.createWorkspaceScope();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeActionGroup.SearchScopeAction#getSearchScopeType()
- */
- public int getSearchScopeType() {
- return SearchScopeActionGroup.SEARCH_SCOPE_TYPE_WORKSPACE;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.callhierarchy.SearchScopeAction#getFullDescription()
- */
- public String getFullDescription() {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- return factory.getWorkspaceScopeDescription(true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchUtil.java
deleted file mode 100644
index 44d020e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SearchUtil.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.search.LRUWorkingSetsList;
-import org.eclipse.wst.jsdt.internal.ui.search.WorkingSetComparator;
-
-public class SearchUtil {
-
- // LRU working sets
- public static int LRU_WORKINGSET_LIST_SIZE= 3;
- private static LRUWorkingSetsList fgLRUWorkingSets;
- // Settings store
- private static final String DIALOG_SETTINGS_KEY= "CallHierarchySearchScope"; //$NON-NLS-1$
- private static final String STORE_LRU_WORKING_SET_NAMES= "lastUsedWorkingSetNames"; //$NON-NLS-1$
- private static IDialogSettings fgSettingsStore;
-
- /**
- * Updates the LRU list of working sets.
- *
- * @param workingSets the workings sets to be added to the LRU list
- */
- public static void updateLRUWorkingSets(IWorkingSet[] workingSets) {
- if (workingSets == null || workingSets.length < 1)
- return;
-
- SearchUtil.getLRUWorkingSets().add(workingSets);
- SearchUtil.saveState();
- }
-
- private static void saveState() {
- IWorkingSet[] workingSets;
- Iterator iter= SearchUtil.fgLRUWorkingSets.iterator();
- int i= 0;
- while (iter.hasNext()) {
- workingSets= (IWorkingSet[])iter.next();
- String[] names= new String[workingSets.length];
- for (int j= 0; j < workingSets.length; j++)
- names[j]= workingSets[j].getName();
- SearchUtil.fgSettingsStore.put(SearchUtil.STORE_LRU_WORKING_SET_NAMES + i, names);
- i++;
- }
- }
-
- public static LRUWorkingSetsList getLRUWorkingSets() {
- if (SearchUtil.fgLRUWorkingSets == null) {
- restoreState();
- }
- return SearchUtil.fgLRUWorkingSets;
- }
-
- static void restoreState() {
- SearchUtil.fgLRUWorkingSets= new LRUWorkingSetsList(SearchUtil.LRU_WORKINGSET_LIST_SIZE);
- SearchUtil.fgSettingsStore= JavaScriptPlugin.getDefault().getDialogSettings().getSection(SearchUtil.DIALOG_SETTINGS_KEY);
- if (SearchUtil.fgSettingsStore == null)
- SearchUtil.fgSettingsStore= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(SearchUtil.DIALOG_SETTINGS_KEY);
-
- boolean foundLRU= false;
- for (int i= SearchUtil.LRU_WORKINGSET_LIST_SIZE - 1; i >= 0; i--) {
- String[] lruWorkingSetNames= SearchUtil.fgSettingsStore.getArray(SearchUtil.STORE_LRU_WORKING_SET_NAMES + i);
- if (lruWorkingSetNames != null) {
- Set workingSets= new HashSet(2);
- for (int j= 0; j < lruWorkingSetNames.length; j++) {
- IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[j]);
- if (workingSet != null) {
- workingSets.add(workingSet);
- }
- }
- foundLRU= true;
- if (!workingSets.isEmpty())
- SearchUtil.fgLRUWorkingSets.add((IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]));
- }
- }
- if (!foundLRU)
- // try old preference format
- restoreFromOldFormat();
- }
-
- private static void restoreFromOldFormat() {
- SearchUtil.fgLRUWorkingSets= new LRUWorkingSetsList(SearchUtil.LRU_WORKINGSET_LIST_SIZE);
- SearchUtil.fgSettingsStore= JavaScriptPlugin.getDefault().getDialogSettings().getSection(SearchUtil.DIALOG_SETTINGS_KEY);
- if (SearchUtil.fgSettingsStore == null)
- SearchUtil.fgSettingsStore= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(SearchUtil.DIALOG_SETTINGS_KEY);
-
- boolean foundLRU= false;
- String[] lruWorkingSetNames= SearchUtil.fgSettingsStore.getArray(SearchUtil.STORE_LRU_WORKING_SET_NAMES);
- if (lruWorkingSetNames != null) {
- for (int i= lruWorkingSetNames.length - 1; i >= 0; i--) {
- IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[i]);
- if (workingSet != null) {
- foundLRU= true;
- SearchUtil.fgLRUWorkingSets.add(new IWorkingSet[]{workingSet});
- }
- }
- }
- if (foundLRU)
- // save in new format
- saveState();
- }
-
- public static String toString(IWorkingSet[] workingSets) {
- Arrays.sort(workingSets, new WorkingSetComparator());
- String result= ""; //$NON-NLS-1$
- if (workingSets != null && workingSets.length > 0) {
- boolean firstFound= false;
- for (int i= 0; i < workingSets.length; i++) {
- String workingSetName= workingSets[i].getLabel();
- if (firstFound)
- result= Messages.format(CallHierarchyMessages.SearchUtil_workingSetConcatenation, new String[] {result, workingSetName});
- else {
- result= workingSetName;
- firstFound= true;
- }
- }
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SelectWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SelectWorkingSetAction.java
deleted file mode 100644
index aa6b1061..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/SelectWorkingSetAction.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-class SelectWorkingSetAction extends Action {
- private final SearchScopeActionGroup fGroup;
-
- public SelectWorkingSetAction(SearchScopeActionGroup group) {
- super(CallHierarchyMessages.SearchScopeActionGroup_workingset_select_text);
- this.fGroup = group;
- setToolTipText(CallHierarchyMessages.SearchScopeActionGroup_workingset_select_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_SEARCH_SCOPE_ACTION);
- }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- try {
- IWorkingSet[] workingSets;
- workingSets = JavaSearchScopeFactory.getInstance().queryWorkingSets();
- if (workingSets != null) {
- this.fGroup.setActiveWorkingSets(workingSets);
- SearchUtil.updateLRUWorkingSets(workingSets);
- } else {
- this.fGroup.setActiveWorkingSets(null);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, JavaScriptPlugin.getActiveWorkbenchShell(),
- CallHierarchyMessages.SelectWorkingSetAction_error_title,
- CallHierarchyMessages.SelectWorkingSetAction_error_message);
- } catch (InterruptedException e) {
- // cancel pressed
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleCallModeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleCallModeAction.java
deleted file mode 100644
index 7c9ffd50..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleCallModeAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Toggles the call direction of the call hierarchy (i.e. toggles between showing callers and callees.)
- */
-class ToggleCallModeAction extends Action {
-
- private CallHierarchyViewPart fView;
- private int fMode;
-
- public ToggleCallModeAction(CallHierarchyViewPart v, int mode) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- if (mode == CallHierarchyViewPart.CALL_MODE_CALLERS) {
- setText(CallHierarchyMessages.ToggleCallModeAction_callers_label);
- setDescription(CallHierarchyMessages.ToggleCallModeAction_callers_description);
- setToolTipText(CallHierarchyMessages.ToggleCallModeAction_callers_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "ch_callers.gif"); //$NON-NLS-1$
- } else if (mode == CallHierarchyViewPart.CALL_MODE_CALLEES) {
- setText(CallHierarchyMessages.ToggleCallModeAction_callees_label);
- setDescription(CallHierarchyMessages.ToggleCallModeAction_callees_description);
- setToolTipText(CallHierarchyMessages.ToggleCallModeAction_callees_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "ch_callees.gif"); //$NON-NLS-1$
- } else {
- Assert.isTrue(false);
- }
- fView= v;
- fMode= mode;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION);
- }
-
- public int getMode() {
- return fMode;
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- fView.setCallMode(fMode); // will toggle the checked state
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleOrientationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleOrientationAction.java
deleted file mode 100644
index 43ee5083..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/ToggleOrientationAction.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Toggles the orientationof the layout of the call hierarchy
- */
-class ToggleOrientationAction extends Action {
-
- private CallHierarchyViewPart fView;
- private int fActionOrientation;
-
- public ToggleOrientationAction(CallHierarchyViewPart v, int orientation) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_HORIZONTAL) {
- setText(CallHierarchyMessages.ToggleOrientationAction_horizontal_label);
- setDescription(CallHierarchyMessages.ToggleOrientationAction_horizontal_description);
- setToolTipText(CallHierarchyMessages.ToggleOrientationAction_horizontal_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_horizontal.gif"); //$NON-NLS-1$
- } else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_VERTICAL) {
- setText(CallHierarchyMessages.ToggleOrientationAction_vertical_label);
- setDescription(CallHierarchyMessages.ToggleOrientationAction_vertical_description);
- setToolTipText(CallHierarchyMessages.ToggleOrientationAction_vertical_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_vertical.gif"); //$NON-NLS-1$
- } else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_AUTOMATIC) {
- setText(CallHierarchyMessages.ToggleOrientationAction_automatic_label);
- setDescription(CallHierarchyMessages.ToggleOrientationAction_automatic_description);
- setToolTipText(CallHierarchyMessages.ToggleOrientationAction_automatic_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_automatic.gif"); //$NON-NLS-1$
- } else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_SINGLE) {
- setText(CallHierarchyMessages.ToggleOrientationAction_single_label);
- setDescription(CallHierarchyMessages.ToggleOrientationAction_single_description);
- setToolTipText(CallHierarchyMessages.ToggleOrientationAction_single_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_single.gif"); //$NON-NLS-1$
- } else {
- Assert.isTrue(false);
- }
- fView= v;
- fActionOrientation= orientation;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION);
- }
-
- public int getOrientation() {
- return fActionOrientation;
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- if (isChecked()) {
- fView.fOrientation= fActionOrientation;
- fView.computeOrientation();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeRoot.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeRoot.java
deleted file mode 100644
index 7daa0f08..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeRoot.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-public class TreeRoot {
- public static final Object EMPTY_ROOT = new Object();
- private Object fRoot;
-
- /**
- * Constructor for TreeRoot.
- */
- public TreeRoot(Object root) {
- this.fRoot = root;
- }
-
- Object getRoot() {
- return fRoot;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeTermination.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeTermination.java
deleted file mode 100644
index 1e77217a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/TreeTermination.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.callhierarchy;
-
-
-final class TreeTermination {
- public static final Object SEARCH_CANCELED = new Object();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/JavaElementReferenceConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/JavaElementReferenceConverter.java
deleted file mode 100644
index e6f8190c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/JavaElementReferenceConverter.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.commands;
-
-import org.eclipse.core.commands.AbstractParameterValueConverter;
-import org.eclipse.core.commands.ParameterValueConversionException;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-
-/**
- * A command parameter value converter to convert between Java elements and
- * String references that identify them.
- * <p>
- * References can be made to Java types, methods and fields. The reference
- * identifies the project to use as a search scope as well as the java element
- * information. Note that non-source elements may be referenced (such as
- * java.lang.Object), but they must be resolved within the scope of some
- * project.
- * </p>
- * <p>
- * References take the form:
- *
- * <pre>
- * elementRef := typeRef | fieldRef | methodRef
- * typeRef := projectName '/' fullyQualifiedTypeName
- * fieldRef := typeRef '#' fieldName
- * methodRef := typeRef '#' methodName '(' parameterSignatures ')'
- * </pre>
- *
- * where <code>parameterSignatures</code> uses the signature format documented
- * in the {@link org.eclipse.wst.jsdt.core.Signature Signature} class.
- * </p>
- *
- *
- */
-public class JavaElementReferenceConverter extends AbstractParameterValueConverter {
-
- private static final char PROJECT_END_CHAR= '/';
-
- private static final char TYPE_END_CHAR= '#';
-
- private static final char PARAM_START_CHAR= Signature.C_PARAM_START;
-
- private static final char PARAM_END_CHAR= Signature.C_PARAM_END;
-
- public Object convertToObject(String parameterValue) throws ParameterValueConversionException {
-
- assertWellFormed(parameterValue != null);
-
- final int projectEndPosition= parameterValue.indexOf(PROJECT_END_CHAR);
- assertWellFormed(projectEndPosition != -1);
-
- String projectName= parameterValue.substring(0, projectEndPosition);
- String javaElementRef= parameterValue.substring(projectEndPosition + 1);
-
- IJavaScriptModel javaModel= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- assertExists(javaModel);
-
- IJavaScriptProject javaProject= javaModel.getJavaScriptProject(projectName);
- assertExists(javaProject);
-
- final int typeEndPosition= javaElementRef.indexOf(TYPE_END_CHAR);
- String typeName;
- if (typeEndPosition == -1) {
- typeName= javaElementRef;
- } else {
- typeName= javaElementRef.substring(0, typeEndPosition);
- }
-
- if (Util.isJavaLikeFileName(typeName))
- {
- ITypeRoot typeRoot=null;
- try {
- typeRoot=javaProject.findTypeRoot(typeName);
- } catch (JavaScriptModelException e) { }
- assertExists(typeRoot);
- if (typeEndPosition == -1) {
- return typeRoot;
- }
- String memberRef= javaElementRef.substring(typeEndPosition + 1);
-
- final int paramStartPosition= memberRef.indexOf(PARAM_START_CHAR);
- if (paramStartPosition == -1) {
- IField field= typeRoot.getField(memberRef);
- assertExists(field);
- return field;
- }
- String methodName= memberRef.substring(0, paramStartPosition);
- String signature= memberRef.substring(paramStartPosition);
- String[] parameterTypes= null;
- try {
- parameterTypes= Signature.getParameterTypes(signature);
- } catch (IllegalArgumentException ex) {
- // parameterTypes == null
- }
- assertWellFormed(parameterTypes != null);
- IFunction method= typeRoot.getFunction(methodName, parameterTypes);
- assertExists(method);
- return method;
- }
-
- IType type= null;
- try {
- type= javaProject.findType(typeName);
- } catch (JavaScriptModelException ex) {
- // type == null
- }
- assertExists(type);
-
- if (typeEndPosition == -1) {
- return type;
- }
-
- String memberRef= javaElementRef.substring(typeEndPosition + 1);
-
- final int paramStartPosition= memberRef.indexOf(PARAM_START_CHAR);
- if (paramStartPosition == -1) {
- IField field= type.getField(memberRef);
- assertExists(field);
- return field;
- }
- String methodName= memberRef.substring(0, paramStartPosition);
- String signature= memberRef.substring(paramStartPosition);
- String[] parameterTypes= null;
- try {
- parameterTypes= Signature.getParameterTypes(signature);
- } catch (IllegalArgumentException ex) {
- // parameterTypes == null
- }
- assertWellFormed(parameterTypes != null);
- IFunction method= type.getFunction(methodName, parameterTypes);
- assertExists(method);
- return method;
- }
-
- /**
- * Throws a <code>ParameterValueConversionException</code> if the java
- * element reference string does not meet some well-formedness condition.
- *
- * @param assertion
- * a boolean check for well-formedness
- * @throws ParameterValueConversionException
- */
- private void assertWellFormed(boolean assertion) throws ParameterValueConversionException {
- if (!assertion) {
- throw new ParameterValueConversionException("Malformed parameterValue"); //$NON-NLS-1$
- }
- }
-
- /**
- * Throws a <code>ParameterValueConversionException</code> if the java
- * element reference string identifies an element that does not exist.
- *
- * @param javaElement
- * an element to check for existence
- * @throws ParameterValueConversionException
- */
- private void assertExists(IJavaScriptElement javaElement) throws ParameterValueConversionException {
- if ((javaElement == null) || (!javaElement.exists())) {
- throw new ParameterValueConversionException("parameterValue must reference an existing IJavaScriptElement"); //$NON-NLS-1$
- }
- }
-
- public String convertToString(Object parameterValue) throws ParameterValueConversionException {
-
- if (!(parameterValue instanceof IJavaScriptElement)) {
- throw new ParameterValueConversionException("parameterValue must be an IJavaScriptElement"); //$NON-NLS-1$
- }
-
- IJavaScriptElement javaElement= (IJavaScriptElement) parameterValue;
-
- IJavaScriptProject javaProject= javaElement.getJavaScriptProject();
- if (javaProject == null) {
- throw new ParameterValueConversionException("Could not get IJavaScriptProject for element"); //$NON-NLS-1$
- }
-
- StringBuffer buffer;
-
- if (javaElement instanceof IType) {
- IType type= (IType) javaElement;
- buffer= composeTypeReference(type);
- } else
- if (javaElement instanceof IFunction) {
- IFunction method= (IFunction) javaElement;
- buffer= composeTypeReference(method.getDeclaringType());
- buffer.append(TYPE_END_CHAR);
- buffer.append(method.getElementName());
- String[] parameterTypes= method.getParameterTypes();
- buffer.append(PARAM_START_CHAR);
- for (int i= 0; i < parameterTypes.length; i++) {
- buffer.append(parameterTypes[i]);
- }
- buffer.append(PARAM_END_CHAR);
- } else
- if (javaElement instanceof IField) {
- IField field= (IField) javaElement;
- buffer= composeTypeReference(field.getDeclaringType());
- buffer.append(TYPE_END_CHAR);
- buffer.append(field.getElementName());
- } else {
- throw new ParameterValueConversionException("Unsupported IJavaScriptElement type"); //$NON-NLS-1$
- }
-
- return buffer.toString();
- }
-
- private StringBuffer composeTypeReference(IType type) {
- StringBuffer buffer= new StringBuffer();
- buffer.append(type.getJavaScriptProject().getElementName());
- buffer.append(PROJECT_END_CHAR);
- buffer.append(type.getFullyQualifiedName());
- return buffer;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/OpenElementInEditorHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/OpenElementInEditorHandler.java
deleted file mode 100644
index 2f236210..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/OpenElementInEditorHandler.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.commands;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * A command handler to open a java element in its editor.
- *
- *
- */
-public class OpenElementInEditorHandler extends AbstractHandler {
-
- private static final String PARAM_ID_ELEMENT_REF= "elementRef"; //$NON-NLS-1$
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- IJavaScriptElement javaElement= (IJavaScriptElement) event.getObjectParameterForExecution(PARAM_ID_ELEMENT_REF);
-
- try {
- IEditorPart editorPart= JavaScriptUI.openInEditor(javaElement);
- JavaScriptUI.revealInEditor(editorPart, javaElement);
- } catch (JavaScriptModelException ex) {
- throw new ExecutionException("Error opening java element in editor", ex); //$NON-NLS-1$
- } catch (PartInitException ex) {
- throw new ExecutionException("Error opening java element in editor", ex); //$NON-NLS-1$
- }
-
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInPackageViewHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInPackageViewHandler.java
deleted file mode 100644
index fa060ea5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInPackageViewHandler.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.commands;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerPart;
-
-/**
- * A command handler to show a java element in the package view.
- *
- *
- */
-public class ShowElementInPackageViewHandler extends AbstractHandler {
-
- private static final String PARAM_ID_ELEMENT_REF= "elementRef"; //$NON-NLS-1$
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- IJavaScriptElement javaElement= (IJavaScriptElement) event.getObjectParameterForExecution(PARAM_ID_ELEMENT_REF);
-
- PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
- view.tryToReveal(javaElement);
-
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInTypeHierarchyViewHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInTypeHierarchyViewHandler.java
deleted file mode 100644
index 3d8bf18a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/commands/ShowElementInTypeHierarchyViewHandler.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.commands;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.OpenTypeHierarchyUtil;
-
-/**
- * A command handler to show a java element in the type hierarchy view.
- *
- *
- */
-public class ShowElementInTypeHierarchyViewHandler extends AbstractHandler {
-
- private static final String PARAM_ID_ELEMENT_REF= "elementRef"; //$NON-NLS-1$
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (window == null)
- return null;
-
- IJavaScriptElement javaElement= (IJavaScriptElement) event.getObjectParameterForExecution(PARAM_ID_ELEMENT_REF);
-
- OpenTypeHierarchyUtil.open(javaElement, window);
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties
deleted file mode 100644
index c555bb96..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties
+++ /dev/null
@@ -1,33 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-title= Restore JavaScript Element from Local History
-width= 800
-height= 600
-
-treeTitleFormat= Local History of ''{0}''
-
-treeFormat= {0}
-workspaceTreeFormat= {0} (Workspace File)
-
-editionLabel= Local History ({0})
-workspaceEditionLabel= Workspace File
-
-targetLabel= Editor Buffer
-
-todayFormat= Today ({0})
-yesterdayFormat= Yesterday ({0})
-dayFormat= {0}
-
-buttonLabel= Restore
-
-memberPaneTitle= Available JavaScript Elements
-noAdditionalMembersMessage= No additional members found in local history.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties
deleted file mode 100644
index 24ca1da8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties
+++ /dev/null
@@ -1,20 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-title= Compare JavaScript Elements
-width= 800
-height= 600
-
-buttonLabel= Close
-
-errorTitle= Compare JavaScript Element Error
-errorFormat= Cannot locate source for ''{0}''.
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareDialog.java
deleted file mode 100644
index 8143e1eb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareDialog.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.CompareUI;
-import org.eclipse.compare.CompareViewerSwitchingPane;
-import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-class CompareDialog extends ResizableDialog {
-
- class ViewerSwitchingPane extends CompareViewerSwitchingPane {
-
- ViewerSwitchingPane(Composite parent, int style) {
- super(parent, style, false);
- }
-
- protected Viewer getViewer(Viewer oldViewer, Object input) {
- if (input instanceof ICompareInput)
- return CompareUI.findContentViewer(oldViewer, (ICompareInput)input, this, fCompareConfiguration);
- return null;
- }
-
- public void setImage(Image image) {
- // don't show icon
- }
- }
-
- private CompareViewerSwitchingPane fContentPane;
- private CompareConfiguration fCompareConfiguration;
- private ICompareInput fInput;
-
-
- CompareDialog(Shell parent, ResourceBundle bundle) {
- super(parent, bundle);
-
- fCompareConfiguration= new CompareConfiguration();
- fCompareConfiguration.setLeftEditable(false);
- fCompareConfiguration.setRightEditable(false);
- }
-
- void compare(ICompareInput input) {
-
- fInput= input;
-
- fCompareConfiguration.setLeftLabel(fInput.getLeft().getName());
- fCompareConfiguration.setLeftImage(fInput.getLeft().getImage());
-
- fCompareConfiguration.setRightLabel(fInput.getRight().getName());
- fCompareConfiguration.setRightImage(fInput.getRight().getImage());
-
- if (fContentPane != null)
- fContentPane.setInput(fInput);
-
- open();
- }
-
- /* (non Javadoc)
- * Creates SWT control tree.
- */
- protected synchronized Control createDialogArea(Composite parent2) {
-
- Composite parent= (Composite) super.createDialogArea(parent2);
-
- getShell().setText(JavaCompareUtilities.getString(fBundle, "title")); //$NON-NLS-1$
-
- fContentPane= new ViewerSwitchingPane(parent, SWT.BORDER | SWT.FLAT);
- fContentPane.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL
- | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL));
-
- if (fInput != null)
- fContentPane.setInput(fInput);
-
- applyDialogFont(parent);
- return parent;
- }
-
- /* (non-Javadoc)
- * Method declared on Dialog.
- */
- protected void createButtonsForButtonBar(Composite parent) {
- String buttonLabel= JavaCompareUtilities.getString(fBundle, "buttonLabel", IDialogConstants.OK_LABEL); //$NON-NLS-1$
- createButton(parent, IDialogConstants.CANCEL_ID, buttonLabel, false);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.COMPARE_DIALOG);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java
deleted file mode 100644
index 2991f498..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class CompareMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.compare.CompareMessages";//$NON-NLS-1$
-
- private CompareMessages() {
- // Do not instantiate
- }
-
- public static String JavaCompareWithEditionActionImpl_0;
- public static String JavaMergeViewer_title;
- public static String JavaReplaceWithEditionActionImpl_0;
- public static String PropertiesFileMergeViewer_title;
- public static String JavaStructureViewer_title;
- public static String JavaNode_compilationUnit;
- public static String JavaNode_importDeclarations;
- public static String JavaNode_initializer;
- public static String JavaNode_packageDeclaration;
- public static String PropertiesStructureCreator_error_occurred;
- public static String PropertyCompareViewer_title;
- public static String PropertyCompareViewer_malformedEncoding;
- public static String CompareWithHistory_title;
- public static String CompareWithHistory_internalErrorMessage;
- public static String CompareWithHistory_invalidSelectionMessage;
- public static String ReplaceFromHistory_title;
- public static String ReplaceFromHistory_internalErrorMessage;
- public static String ReplaceFromHistory_invalidSelectionMessage;
- public static String ReplaceFromHistory_parsingErrorMessage;
- public static String AddFromHistory_title;
- public static String AddFromHistory_internalErrorMessage;
- public static String AddFromHistory_invalidSelectionMessage;
- public static String Editor_Buffer;
- public static String Workspace_File;
- public static String LocalHistoryActionGroup_menu_local_history;
- public static String LocalHistoryActionGroup_action_compare_with;
- public static String LocalHistoryActionGroup_action_compare_with_title;
- public static String LocalHistoryActionGroup_action_compare_with_message;
- public static String LocalHistoryActionGroup_action_replace_with_previous;
- public static String LocalHistoryActionGroup_action_replace_with_previous_title;
- public static String LocalHistoryActionGroup_action_replace_with_previous_message;
- public static String LocalHistoryActionGroup_action_replace_with;
- public static String LocalHistoryActionGroup_action_replace_with_title;
- public static String LocalHistoryActionGroup_action_replace_with_message;
- public static String LocalHistoryActionGroup_action_add;
- public static String LocalHistoryActionGroup_action_add_title;
- public static String LocalHistoryActionGroup_action_add_message;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CompareMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties
deleted file mode 100644
index 71cd7b80..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties
+++ /dev/null
@@ -1,89 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-#
-# Title of Java source compare viewer
-#
-JavaMergeViewer_title= JavaScript Source Compare
-
-#
-# Title of Java properties file compare viewer
-#
-PropertiesFileMergeViewer_title= JavaScript Properties Compare
-
-#
-# Title of Java structure ceator (shown in diff structure viewer)
-#
-JavaStructureViewer_title= JavaScript Structure Compare
-JavaNode_compilationUnit= JavaScript file
-JavaNode_importDeclarations= Import Declarations
-JavaNode_initializer= {...}
-JavaNode_packageDeclaration= Package Declaration
-
-#
-# Property file compare viewer
-#
-PropertyCompareViewer_title= Property Compare
-PropertyCompareViewer_malformedEncoding=Malformed encoding.
-PropertiesStructureCreator_error_occurred=An error occurred while creating the input structure.
-
-#
-# Compare with Local History action
-#
-CompareWithHistory_title= Compare with Local History
-CompareWithHistory_internalErrorMessage= Internal error.
-CompareWithHistory_invalidSelectionMessage= Selection is no longer valid.
-
-#
-# Replace from Local History action
-#
-ReplaceFromHistory_title= Replace from Local History
-ReplaceFromHistory_internalErrorMessage= Internal error.
-ReplaceFromHistory_invalidSelectionMessage= Selection is no longer valid.
-ReplaceFromHistory_parsingErrorMessage= Could not parse previous entry in local history.\nUse \'Replace with Element from Local History\'.
-
-#
-# Restore from Local History action
-#
-AddFromHistory_title= Restore from Local History
-AddFromHistory_internalErrorMessage= Internal error.
-AddFromHistory_invalidSelectionMessage= Selection is no longer valid.
-
-#
-# Title of left pane in Compare/Replace/Restore from local History dialog
-#
-Editor_Buffer= Editor Buffer
-Workspace_File= Workspace File
-
-#
-# Local history action group for compilation unit editor
-#
-LocalHistoryActionGroup_menu_local_history=Local &History
-
-LocalHistoryActionGroup_action_compare_with=Comp&are With...
-LocalHistoryActionGroup_action_compare_with_title=Compare With
-LocalHistoryActionGroup_action_compare_with_message=Operation not applicable to current text selection. Please select a type, method or field.
-
-LocalHistoryActionGroup_action_replace_with_previous=Replace with &Previous
-LocalHistoryActionGroup_action_replace_with_previous_title=Replace with Previous
-LocalHistoryActionGroup_action_replace_with_previous_message=Operation not applicable to current text selection. Please select a type, function or field.
-
-LocalHistoryActionGroup_action_replace_with=Replace &With...
-LocalHistoryActionGroup_action_replace_with_title=Replace With
-LocalHistoryActionGroup_action_replace_with_message=Operation not applicable to current text selection. Please select a type, function or field.
-
-LocalHistoryActionGroup_action_add=&Restore From...
-LocalHistoryActionGroup_action_add_title=Restore From
-LocalHistoryActionGroup_action_add_message=Operation not applicable to current text selection. Please select a type, function or field.
-
-JavaCompareWithEditionActionImpl_0=Compare JavaScript Element with Local History
-JavaReplaceWithEditionActionImpl_0=Replace with JavaScript Element from Local History
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties
deleted file mode 100644
index 884cdaeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties
+++ /dev/null
@@ -1,33 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-title= Compare JavaScript Element with Local History
-width= 800
-height= 600
-
-treeTitleFormat= Local History of ''{0}''
-
-treeFormat= {0}
-workspaceTreeFormat= {0} (Workspace File)
-parseErrorFormat= {0} (Parsing Error; No Structured Compare Available)
-
-editionLabel= Local History ({0})
-workspaceEditionLabel= Workspace File
-
-targetLabel= {0}
-
-todayFormat= Today ({0})
-yesterdayFormat= Yesterday ({0})
-dayFormat= {0}
-
-buttonLabel= Close
-
-notFoundInLocalHistoryMessage= No differing versions of selected JavaScript element found in local history.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java
deleted file mode 100644
index a74b060c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java
+++ /dev/null
@@ -1,317 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.widgets.Display;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- * Adapts an options {@link IEclipsePreferences} to {@link org.eclipse.jface.preference.IPreferenceStore}.
- * <p>
- * This preference store is read-only i.e. write access
- * throws an {@link java.lang.UnsupportedOperationException}.
- * </p>
- *
- *
- */
-class EclipsePreferencesAdapter implements IPreferenceStore {
-
- /**
- * Preference change listener. Listens for events preferences
- * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
- * on this adapter with arguments from the received event.
- */
- private class PreferenceChangeListener implements IEclipsePreferences.IPreferenceChangeListener {
-
- /**
- * {@inheritDoc}
- */
- public void preferenceChange(final IEclipsePreferences.PreferenceChangeEvent event) {
- if (Display.getCurrent() == null) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- firePropertyChangeEvent(event.getKey(), event.getOldValue(), event.getNewValue());
- }
- });
- } else {
- firePropertyChangeEvent(event.getKey(), event.getOldValue(), event.getNewValue());
- }
- }
- }
-
- /** Listeners on on this adapter */
- private ListenerList fListeners= new ListenerList(ListenerList.IDENTITY);
-
- /** Listener on the node */
- private IEclipsePreferences.IPreferenceChangeListener fListener= new PreferenceChangeListener();
-
- /** wrapped node */
- private final IScopeContext fContext;
- private final String fQualifier;
-
- /**
- * Initialize with the node to wrap
- *
- * @param context The context to access
- */
- public EclipsePreferencesAdapter(IScopeContext context, String qualifier) {
- fContext= context;
- fQualifier= qualifier;
- }
-
- private IEclipsePreferences getNode() {
- return fContext.getNode(fQualifier);
- }
-
- /**
- * {@inheritDoc}
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- if (fListeners.size() == 0)
- getNode().addPreferenceChangeListener(fListener);
- fListeners.add(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.remove(listener);
- if (fListeners.size() == 0) {
- getNode().removePreferenceChangeListener(fListener);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(String name) {
- return getNode().get(name, null) != null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
- PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++)
- ((IPropertyChangeListener) listeners[i]).propertyChange(event);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getBoolean(String name) {
- return getNode().getBoolean(name, BOOLEAN_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getDefaultBoolean(String name) {
- return BOOLEAN_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDefaultDouble(String name) {
- return DOUBLE_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public float getDefaultFloat(String name) {
- return FLOAT_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getDefaultInt(String name) {
- return INT_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getDefaultLong(String name) {
- return LONG_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultString(String name) {
- return STRING_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDouble(String name) {
- return getNode().getDouble(name, DOUBLE_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public float getFloat(String name) {
- return getNode().getFloat(name, FLOAT_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInt(String name) {
- return getNode().getInt(name, INT_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public long getLong(String name) {
- return getNode().getLong(name, LONG_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getString(String name) {
- return getNode().get(name, STRING_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isDefault(String name) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsSaving() {
- try {
- return getNode().keys().length > 0;
- } catch (BackingStoreException e) {
- // ignore
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public void putValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, String defaultObject) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setToDefault(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistory.java
deleted file mode 100644
index cae3a0c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistory.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-
-public class JavaAddElementFromHistory extends JavaHistoryAction {
-
- public JavaAddElementFromHistory() {
- }
-
- protected JavaHistoryActionImpl createDelegate() {
- return new JavaAddElementFromHistoryImpl();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistoryImpl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistoryImpl.java
deleted file mode 100644
index 02143327..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaAddElementFromHistoryImpl.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-import java.util.Map;
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.EditionSelectionDialog;
-import org.eclipse.compare.IStreamContentAccessor;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-
-
-class JavaAddElementFromHistoryImpl extends JavaHistoryActionImpl {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.compare.AddFromHistoryAction"; //$NON-NLS-1$
-
- JavaAddElementFromHistoryImpl() {
- super(true);
- }
-
- public void run(ISelection selection) {
-
- String errorTitle= CompareMessages.AddFromHistory_title;
- String errorMessage= CompareMessages.AddFromHistory_internalErrorMessage;
- Shell shell= getShell();
-
- IJavaScriptUnit cu= null;
- IParent parent= null;
- IMember input= null;
-
- // analyze selection
- if (selection.isEmpty()) {
- // no selection: we try to use the editor's input
- JavaEditor editor= getEditor();
- if (editor != null) {
- IEditorInput editorInput= editor.getEditorInput();
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- if (manager != null) {
- cu= manager.getWorkingCopy(editorInput);
- parent= cu;
- }
- }
- } else {
- input= getEditionElement(selection);
- if (input != null) {
- cu= input.getJavaScriptUnit();
- parent= input;
- input= null;
-
- } else {
- if (selection instanceof IStructuredSelection) {
- Object o= ((IStructuredSelection)selection).getFirstElement();
- if (o instanceof IJavaScriptUnit) {
- cu= (IJavaScriptUnit) o;
- parent= cu;
- }
- }
- }
- }
-
- if (parent == null || cu == null) {
- String invalidSelectionMessage= CompareMessages.AddFromHistory_invalidSelectionMessage;
- MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
- return;
- }
-
- IFile file= getFile(parent);
- if (file == null) {
- MessageDialog.openError(shell, errorTitle, errorMessage);
- return;
- }
-
- boolean inEditor= beingEdited(file);
-
- IStatus status= Resources.makeCommittable(file, shell);
- if (!status.isOK()) {
- return;
- }
-
- // get the document where to insert the text
- IPath path= file.getFullPath();
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- ITextFileBuffer textFileBuffer= null;
- try {
- bufferManager.connect(path, LocationKind.IFILE, null);
- textFileBuffer= bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
- IDocument document= textFileBuffer.getDocument();
-
- // configure EditionSelectionDialog and let user select an edition
- ITypedElement target= new JavaTextBufferNode(file, document, inEditor);
- ITypedElement[] editions= buildEditions(target, file);
-
- ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
- EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle);
- d.setAddMode(true);
- d.setHelpContextId(IJavaHelpContextIds.ADD_ELEMENT_FROM_HISTORY_DIALOG);
- ITypedElement selected= d.selectEdition(target, editions, parent);
- if (selected == null)
- return; // user cancel
-
- IJavaScriptUnit cu2= cu;
- if (parent instanceof IMember)
- cu2= ((IMember)parent).getJavaScriptUnit();
-
- JavaScriptUnit root= parsePartialCompilationUnit(cu2);
- ASTRewrite rewriter= ASTRewrite.create(root.getAST());
-
- ITypedElement[] results= d.getSelection();
- for (int i= 0; i < results.length; i++) {
-
- // create an AST node
- ASTNode newNode= createASTNode(rewriter, results[i], TextUtilities.getDefaultLineDelimiter(document), cu.getJavaScriptProject());
- if (newNode == null) {
- MessageDialog.openError(shell, errorTitle, errorMessage);
- return;
- }
-
- // now determine where to put the new node
- if (newNode instanceof PackageDeclaration) {
- rewriter.set(root, JavaScriptUnit.PACKAGE_PROPERTY, newNode, null);
-
- } else if (newNode instanceof ImportDeclaration) {
- ListRewrite lw= rewriter.getListRewrite(root, JavaScriptUnit.IMPORTS_PROPERTY);
- lw.insertFirst(newNode, null);
-
- } else { // class, interface, enum, annotation, method, field
-
- if (parent instanceof IJavaScriptUnit) { // top level
- ListRewrite lw= rewriter.getListRewrite(root, JavaScriptUnit.TYPES_PROPERTY);
- int index= ASTNodes.getInsertionIndex((BodyDeclaration)newNode, root.types());
- lw.insertAt(newNode, index, null);
-
- } else if (parent instanceof IType) {
- ASTNode declaration= getBodyContainer(root, (IType)parent);
- if (declaration instanceof TypeDeclaration) {
- List container= ASTNodes.getBodyDeclarations(declaration);
- int index= ASTNodes.getInsertionIndex((BodyDeclaration)newNode, container);
- ListRewrite lw= rewriter.getListRewrite(declaration, ASTNodes.getBodyDeclarationsProperty(declaration));
- lw.insertAt(newNode, index, null);
- }
- } else {
- JavaScriptPlugin.logErrorMessage("JavaAddElementFromHistoryImpl: unknown container " + parent); //$NON-NLS-1$
- }
-
- }
- }
-
- Map options= null;
- IJavaScriptProject javaProject= cu2.getJavaScriptProject();
- if (javaProject != null)
- options= javaProject.getOptions(true);
- applyChanges(rewriter, document, textFileBuffer, shell, inEditor, options);
-
- } catch(InvocationTargetException ex) {
- ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
-
- } catch(InterruptedException ex) {
- // shouldn't be called because is not cancelable
- Assert.isTrue(false);
-
- } catch(CoreException ex) {
- ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
-
- } finally {
- try {
- if (textFileBuffer != null)
- bufferManager.disconnect(path, LocationKind.IFILE, null);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /**
- * Creates a place holder ASTNode for the given element.
- * @param rewriter
- * @param element
- * @param delimiter the line delimiter
- * @param project
- * @return a ASTNode or null
- * @throws CoreException
- */
- private ASTNode createASTNode(ASTRewrite rewriter, ITypedElement element, String delimiter, IJavaScriptProject project) throws CoreException {
- if (element instanceof IStreamContentAccessor) {
- String content= JavaCompareUtilities.readString((IStreamContentAccessor)element);
- if (content != null) {
- content= trimTextBlock(content, delimiter, project);
- if (content != null) {
- int type= getPlaceHolderType(element);
- if (type != -1)
- return rewriter.createStringPlaceholder(content, type);
- }
- }
- }
- return null;
- }
-
- /**
- * Returns the corresponding place holder type for the given element.
- * @return a place holder type (see ASTRewrite) or -1 if there is no corresponding placeholder
- */
- private int getPlaceHolderType(ITypedElement element) {
-
- if (element instanceof DocumentRangeNode) {
- JavaNode jn= (JavaNode) element;
- switch (jn.getTypeCode()) {
-
- case JavaNode.PACKAGE:
- return ASTNode.PACKAGE_DECLARATION;
-
- case JavaNode.CLASS:
- case JavaNode.INTERFACE:
- return ASTNode.TYPE_DECLARATION;
-
- case JavaNode.CONSTRUCTOR:
- case JavaNode.METHOD:
- return ASTNode.FUNCTION_DECLARATION;
-
- case JavaNode.FIELD:
- return ASTNode.FIELD_DECLARATION;
-
- case JavaNode.INIT:
- return ASTNode.INITIALIZER;
-
- case JavaNode.IMPORT:
- case JavaNode.IMPORT_CONTAINER:
- return ASTNode.IMPORT_DECLARATION;
-
- case JavaNode.CU:
- return ASTNode.JAVASCRIPT_UNIT;
- }
- }
- return -1;
- }
-
- protected boolean isEnabled(ISelection selection) {
-
- if (selection.isEmpty()) {
- JavaEditor editor= getEditor();
- if (editor != null) {
- // we check whether editor shows JavaScriptUnit
- IEditorInput editorInput= editor.getEditorInput();
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- return manager.getWorkingCopy(editorInput) != null;
- }
- return false;
- }
-
- if (selection instanceof IStructuredSelection) {
- Object o= ((IStructuredSelection)selection).getFirstElement();
- if (o instanceof IJavaScriptUnit)
- return true;
- }
-
- return super.isEnabled(selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareAction.java
deleted file mode 100644
index 0d58f8b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareAction.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.IEncodedStreamContentAccessor;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.structuremergeviewer.DiffNode;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionDelegate;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class JavaCompareAction implements IActionDelegate {
-
- class TypedElement implements ITypedElement, IEncodedStreamContentAccessor {
-
- private ISourceReference fSource;
- private String fContents;
-
- TypedElement(ISourceReference s, String contents) {
- fSource= s;
- fContents= contents;
- }
-
- public String getName() {
- return fJavaElementLabelProvider.getText(fSource);
- }
-
- public String getType() {
- return "JAVA"; //$NON-NLS-1$
- }
-
- public Image getImage() {
- return fJavaElementLabelProvider.getImage(fSource);
- }
-
- public InputStream getContents() throws CoreException {
- byte[] bytes;
- try {
- bytes= fContents.getBytes("UTF-16"); //$NON-NLS-1$
- } catch (UnsupportedEncodingException e) {
- bytes= fContents.getBytes();
- }
- return new ByteArrayInputStream(bytes);
- }
-
- public String getCharset() {
- return "UTF-16"; //$NON-NLS-1$
- }
- }
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.compare.CompareAction"; //$NON-NLS-1$
-
- private ISourceReference fLeft;
- private ISourceReference fRight;
-
- private JavaScriptElementLabelProvider fJavaElementLabelProvider;
-
-
- public void selectionChanged(IAction action, ISelection selection) {
- action.setEnabled(isEnabled(selection));
- }
-
- public void run(IAction action) {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
- CompareDialog d= new CompareDialog(shell, bundle);
-
-
- String left= null;
- String right= null;
-
- try {
- left= getExtendedSource(fLeft);
- } catch (JavaScriptModelException ex) {
- JavaScriptPlugin.log(ex);
- }
-
- try {
- right= getExtendedSource(fRight);
- } catch (JavaScriptModelException ex) {
- JavaScriptPlugin.log(ex);
- }
-
- fJavaElementLabelProvider= new JavaScriptElementLabelProvider(
- JavaScriptElementLabelProvider.SHOW_PARAMETERS |
- JavaScriptElementLabelProvider.SHOW_OVERLAY_ICONS |
- JavaScriptElementLabelProvider.SHOW_ROOT);
-
- if (left == null || right == null) {
- String errorTitle= JavaCompareUtilities.getString(bundle, "errorTitle"); //$NON-NLS-1$
- String errorFormat= JavaCompareUtilities.getString(bundle, "errorFormat"); //$NON-NLS-1$
-
- Object element= null;
- if (left == null)
- element= fLeft;
- else
- element= fRight;
-
- String message= Messages.format(errorFormat, new String[] { fJavaElementLabelProvider.getText(element) } );
-
- MessageDialog.openError(shell, errorTitle, message);
- return;
- }
-
- d.compare(new DiffNode(new TypedElement(fLeft, left), new TypedElement(fRight, right)));
-
- fJavaElementLabelProvider.dispose();
- fJavaElementLabelProvider= null;
- }
-
- protected boolean isEnabled(ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- Object[] sel= ((IStructuredSelection) selection).toArray();
- if (sel.length == 2) {
- for (int i= 0; i < 2; i++) {
- Object o= sel[i];
- if (!(o instanceof ISourceReference))
- return false;
- }
- fLeft= (ISourceReference) sel[0];
- fRight= (ISourceReference) sel[1];
- return true;
- }
- }
- return false;
- }
-
- private String getExtendedSource(ISourceReference ref) throws JavaScriptModelException {
-
- // get parent
- if (ref instanceof IJavaScriptElement) {
- IJavaScriptElement parent= ((IJavaScriptElement) ref).getParent();
- if (parent instanceof ISourceReference) {
- ISourceReference sr= (ISourceReference) parent;
- String parentContent= sr.getSource();
- if (parentContent != null) {
- ISourceRange parentRange= sr.getSourceRange();
- ISourceRange childRange= ref.getSourceRange();
-
- int start= childRange.getOffset() - parentRange.getOffset();
- int end= start + childRange.getLength();
-
- // search backwards for beginning of line
- while (start > 0) {
- char c= parentContent.charAt(start-1);
- if (c == '\n' || c == '\r')
- break;
- start--;
- }
-
- return parentContent.substring(start, end);
- }
- }
- }
-
- return ref.getSource();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareUtilities.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareUtilities.java
deleted file mode 100644
index 743bee37..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareUtilities.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IEncodedStreamContentAccessor;
-import org.eclipse.compare.IStreamContentAccessor;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentPartitioner;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-class JavaCompareUtilities {
-
- private static final char PACKAGEDECLARATION= '%';
- private static final char IMPORTDECLARATION= '#';
- private static final char IMPORT_CONTAINER= '<';
- private static final char FIELD= '^';
- private static final char METHOD= '~';
- private static final char INITIALIZER= '|';
- private static final char COMPILATIONUNIT= '{';
- private static final char TYPE= '[';
-
- static String getString(ResourceBundle bundle, String key, String dfltValue) {
-
- if (bundle != null) {
- try {
- return bundle.getString(key);
- } catch (MissingResourceException x) {
- // NeedWork
- }
- }
- return dfltValue;
- }
-
- static String getString(ResourceBundle bundle, String key) {
- return getString(bundle, key, key);
- }
-
- static int getInteger(ResourceBundle bundle, String key, int dfltValue) {
-
- if (bundle != null) {
- try {
- String s= bundle.getString(key);
- if (s != null)
- return Integer.parseInt(s);
- } catch (NumberFormatException x) {
- // NeedWork
- } catch (MissingResourceException x) {
- // NeedWork
- }
- }
- return dfltValue;
- }
-
- static ImageDescriptor getImageDescriptor(int type) {
- switch (type) {
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- return getImageDescriptor("obj16/compare_method.gif"); //$NON-NLS-1$
- case IJavaScriptElement.FIELD:
- return getImageDescriptor("obj16/compare_field.gif"); //$NON-NLS-1$
- case IJavaScriptElement.IMPORT_DECLARATION:
- return JavaPluginImages.DESC_OBJS_IMPDECL;
- case IJavaScriptElement.IMPORT_CONTAINER:
- return JavaPluginImages.DESC_OBJS_IMPCONT;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return JavaPluginImages.DESC_OBJS_CUNIT;
- }
- return ImageDescriptor.getMissingImageDescriptor();
- }
-
- static ImageDescriptor getTypeImageDescriptor(boolean isClass) {
- if (isClass)
- return JavaPluginImages.DESC_OBJS_CLASS;
- return JavaPluginImages.DESC_OBJS_INTERFACE;
- }
-
- static ImageDescriptor getEnumImageDescriptor() {
- return JavaPluginImages.DESC_OBJS_ENUM;
- }
-
- static ImageDescriptor getAnnotationImageDescriptor() {
- return JavaPluginImages.DESC_OBJS_ANNOTATION;
- }
-
- static ImageDescriptor getImageDescriptor(IMember element) {
- int t= element.getElementType();
- if (t == IJavaScriptElement.TYPE) {
- IType type= (IType) element;
- try {
- return getTypeImageDescriptor(type.isClass());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return JavaPluginImages.DESC_OBJS_GHOST;
- }
- }
- return getImageDescriptor(t);
- }
-
- /**
- * Returns a name for the given Java element that uses the same conventions
- * as the JavaNode name of a corresponding element.
- */
- static String getJavaElementID(IJavaScriptElement je) {
-
- if (je instanceof IMember && ((IMember)je).isBinary())
- return null;
-
- StringBuffer sb= new StringBuffer();
-
- switch (je.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- sb.append(COMPILATIONUNIT);
- break;
- case IJavaScriptElement.TYPE:
- sb.append(TYPE);
- sb.append(je.getElementName());
- break;
- case IJavaScriptElement.FIELD:
- sb.append(FIELD);
- sb.append(je.getElementName());
- break;
- case IJavaScriptElement.METHOD:
- sb.append(METHOD);
- sb.append(JavaScriptElementLabels.getElementLabel(je, JavaScriptElementLabels.M_PARAMETER_TYPES));
- break;
- case IJavaScriptElement.INITIALIZER:
- String id= je.getHandleIdentifier();
- int pos= id.lastIndexOf(INITIALIZER);
- if (pos >= 0)
- sb.append(id.substring(pos));
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- sb.append(IMPORT_CONTAINER);
- break;
- case IJavaScriptElement.IMPORT_DECLARATION:
- sb.append(IMPORTDECLARATION);
- sb.append(je.getElementName());
- break;
- default:
- return null;
- }
- return sb.toString();
- }
-
- /**
- * Returns a name which identifies the given typed name.
- * The type is encoded as a single character at the beginning of the string.
- */
- static String buildID(int type, String name) {
- StringBuffer sb= new StringBuffer();
- switch (type) {
- case JavaNode.CU:
- sb.append(COMPILATIONUNIT);
- break;
- case JavaNode.CLASS:
- case JavaNode.INTERFACE:
- case JavaNode.ENUM:
- case JavaNode.ANNOTATION:
- sb.append(TYPE);
- sb.append(name);
- break;
- case JavaNode.FIELD:
- sb.append(FIELD);
- sb.append(name);
- break;
- case JavaNode.CONSTRUCTOR:
- case JavaNode.METHOD:
- sb.append(METHOD);
- sb.append(name);
- break;
- case JavaNode.INIT:
- sb.append(INITIALIZER);
- sb.append(name);
- break;
- case JavaNode.PACKAGE:
- sb.append(PACKAGEDECLARATION);
- break;
- case JavaNode.IMPORT:
- sb.append(IMPORTDECLARATION);
- sb.append(name);
- break;
- case JavaNode.IMPORT_CONTAINER:
- sb.append(IMPORT_CONTAINER);
- break;
- default:
- Assert.isTrue(false);
- break;
- }
- return sb.toString();
- }
-
- static ImageDescriptor getImageDescriptor(String relativePath) {
- IPath path= JavaPluginImages.ICONS_PATH.append(relativePath);
- return JavaPluginImages.createImageDescriptor(JavaScriptPlugin.getDefault().getBundle(), path, true);
- }
-
- static boolean getBoolean(CompareConfiguration cc, String key, boolean dflt) {
- if (cc != null) {
- Object value= cc.getProperty(key);
- if (value instanceof Boolean)
- return ((Boolean) value).booleanValue();
- }
- return dflt;
- }
-
- static Image getImage(IMember member) {
- ImageDescriptor id= getImageDescriptor(member);
- return id.createImage();
- }
-
- static JavaScriptTextTools getJavaTextTools() {
- JavaScriptPlugin plugin= JavaScriptPlugin.getDefault();
- if (plugin != null)
- return plugin.getJavaTextTools();
- return null;
- }
-
- static IDocumentPartitioner createJavaPartitioner() {
- JavaScriptTextTools tools= getJavaTextTools();
- if (tools != null)
- return tools.createDocumentPartitioner();
- return null;
- }
-
- static void setupDocument(IDocument document) {
- JavaScriptTextTools tools= getJavaTextTools();
- if (tools != null)
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- }
-//
-// static void setupPropertiesFileDocument(IDocument document) {
-// PropertiesFileDocumentSetupParticipant.setupDocument(document);
-// }
-
- /**
- * Reads the contents of the given input stream into a string.
- * The function assumes that the input stream uses the platform's default encoding
- * (<code>ResourcesPlugin.getEncoding()</code>).
- * Returns null if an error occurred.
- */
- 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
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException ex) {
- // silently ignored
- }
- }
- }
- return null;
- }
-
- public static String readString(IStreamContentAccessor sa) throws CoreException {
- InputStream is= sa.getContents();
- if (is != null) {
- String encoding= null;
- if (sa instanceof IEncodedStreamContentAccessor) {
- try {
- encoding= ((IEncodedStreamContentAccessor) sa).getCharset();
- } catch (Exception e) {
- }
- }
- if (encoding == null)
- encoding= ResourcesPlugin.getEncoding();
- return readString(is, encoding);
- }
- return null;
- }
-
- /**
- * Returns the contents of the given string as an array of bytes
- * in the platform's default encoding.
- */
- static byte[] getBytes(String s, String encoding) {
- try {
- return s.getBytes(encoding);
- } catch (UnsupportedEncodingException e) {
- return s.getBytes();
- }
- }
-
- /**
- * Breaks the contents of the given input stream into an array of strings.
- * The function assumes that the input stream uses the platform's default encoding
- * (<code>ResourcesPlugin.getEncoding()</code>).
- * Returns null if an error occurred.
- */
- static String[] readLines(InputStream is2, String encoding) {
-
- BufferedReader reader= null;
- try {
- reader= new BufferedReader(new InputStreamReader(is2, encoding));
- StringBuffer sb= new StringBuffer();
- List list= new ArrayList();
- while (true) {
- int c= reader.read();
- if (c == -1)
- break;
- sb.append((char)c);
- if (c == '\r') { // single CR or a CR followed by LF
- c= reader.read();
- if (c == -1)
- break;
- sb.append((char)c);
- if (c == '\n') {
- list.add(sb.toString());
- sb= new StringBuffer();
- }
- } else if (c == '\n') { // a single LF
- list.add(sb.toString());
- sb= new StringBuffer();
- }
- }
- if (sb.length() > 0)
- list.add(sb.toString());
- return (String[]) list.toArray(new String[list.size()]);
-
- } catch (IOException ex) {
- return null;
-
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException ex) {
- // silently ignored
- }
- }
- }
- }
-
- /*
- * Initialize the given Action from a ResourceBundle.
- */
- static void initAction(IAction a, ResourceBundle bundle, String prefix) {
-
- String labelKey= "label"; //$NON-NLS-1$
- String tooltipKey= "tooltip"; //$NON-NLS-1$
- String imageKey= "image"; //$NON-NLS-1$
- String descriptionKey= "description"; //$NON-NLS-1$
-
- if (prefix != null && prefix.length() > 0) {
- labelKey= prefix + labelKey;
- tooltipKey= prefix + tooltipKey;
- imageKey= prefix + imageKey;
- descriptionKey= prefix + descriptionKey;
- }
-
- a.setText(getString(bundle, labelKey, labelKey));
- a.setToolTipText(getString(bundle, tooltipKey, null));
- a.setDescription(getString(bundle, descriptionKey, null));
-
- String relPath= getString(bundle, imageKey, null);
- if (relPath != null && relPath.trim().length() > 0) {
-
- String dPath;
- String ePath;
-
- if (relPath.indexOf("/") >= 0) { //$NON-NLS-1$
- String path= relPath.substring(1);
- dPath= 'd' + path;
- ePath= 'e' + path;
- } else {
- dPath= "dlcl16/" + relPath; //$NON-NLS-1$
- ePath= "elcl16/" + relPath; //$NON-NLS-1$
- }
-
- ImageDescriptor id= JavaCompareUtilities.getImageDescriptor(dPath); // we set the disabled image first (see PR 1GDDE87)
- if (id != null)
- a.setDisabledImageDescriptor(id);
- id= JavaCompareUtilities.getImageDescriptor(ePath);
- if (id != null) {
- a.setImageDescriptor(id);
- a.setHoverImageDescriptor(id);
- }
- }
- }
-
- static void initToggleAction(IAction a, ResourceBundle bundle, String prefix, boolean checked) {
-
- String tooltip= null;
- if (checked)
- tooltip= getString(bundle, prefix + "tooltip.checked", null); //$NON-NLS-1$
- else
- tooltip= getString(bundle, prefix + "tooltip.unchecked", null); //$NON-NLS-1$
- if (tooltip == null)
- tooltip= getString(bundle, prefix + "tooltip", null); //$NON-NLS-1$
-
- if (tooltip != null)
- a.setToolTipText(tooltip);
-
- String description= null;
- if (checked)
- description= getString(bundle, prefix + "description.checked", null); //$NON-NLS-1$
- else
- description= getString(bundle, prefix + "description.unchecked", null); //$NON-NLS-1$
- if (description == null)
- description= getString(bundle, prefix + "description", null); //$NON-NLS-1$
-
- if (description != null)
- a.setDescription(description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionAction.java
deleted file mode 100644
index 5bc68c14..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionAction.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-/**
- * Provides "Replace from local history" for Java elements.
- */
-public class JavaCompareWithEditionAction extends JavaHistoryAction {
-
- public JavaCompareWithEditionAction() {
- }
-
- protected JavaHistoryActionImpl createDelegate() {
- return new JavaCompareWithEditionActionImpl();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionActionImpl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionActionImpl.java
deleted file mode 100644
index 4f3d1866..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaCompareWithEditionActionImpl.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.CompareUI;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.team.ui.TeamUI;
-import org.eclipse.team.ui.history.HistoryPageCompareEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-/**
- * Provides "Replace from local history" for Java elements.
- */
-class JavaCompareWithEditionActionImpl extends JavaHistoryActionImpl {
-
- private static boolean USE_MODAL_COMPARE = false;
-
- JavaCompareWithEditionActionImpl() {
- super(false);
- }
-
- public void run(ISelection selection) {
-
- IMember input= getEditionElement(selection);
- if (input == null) {
- MessageDialog.openInformation(getShell(), CompareMessages.CompareWithHistory_title, CompareMessages.CompareWithHistory_invalidSelectionMessage);
- return;
- }
-
- JavaElementHistoryPageSource pageSource = JavaElementHistoryPageSource.getInstance();
- final IFile file= pageSource.getFile(input);
- if (file == null) {
- MessageDialog.openError(getShell(), CompareMessages.CompareWithHistory_title, CompareMessages.CompareWithHistory_internalErrorMessage);
- return;
- }
-
- if (USE_MODAL_COMPARE) {
- CompareConfiguration cc = new CompareConfiguration();
- cc.setLeftEditable(false);
- cc.setRightEditable(false);
- HistoryPageCompareEditorInput ci = new HistoryPageCompareEditorInput(cc, pageSource, input);
- ci.setTitle(CompareMessages.JavaCompareWithEditionActionImpl_0);
- ci.setHelpContextId(IJavaHelpContextIds.COMPARE_ELEMENT_WITH_HISTORY_DIALOG);
- CompareUI.openCompareDialog(ci);
- } else {
- TeamUI.showHistoryFor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), input, pageSource);
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaContentViewerCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaContentViewerCreator.java
deleted file mode 100644
index 30275f66..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaContentViewerCreator.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IViewerCreator;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-
-
-/**
- * Required when creating a JavaMergeViewer from the plugin.xml file.
- */
-public class JavaContentViewerCreator implements IViewerCreator {
-
- public Viewer createViewer(Composite parent, CompareConfiguration mp) {
- return new JavaMergeViewer(parent, SWT.NULL, mp);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaElementHistoryPageSource.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaElementHistoryPageSource.java
deleted file mode 100644
index 0c9a6ef5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaElementHistoryPageSource.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.team.ui.history.ElementLocalHistoryPageSource;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-
-public class JavaElementHistoryPageSource extends ElementLocalHistoryPageSource {
-
- private static JavaElementHistoryPageSource instance;
-
- public static JavaElementHistoryPageSource getInstance() {
- if (instance == null)
- instance = new JavaElementHistoryPageSource();
- return instance;
- }
-
- /**
- * Returns true if the given IJavaScriptElement maps to a JavaNode.
- * The JavaHistoryAction uses this function to determine whether
- * a selected Java element can be replaced by some piece of
- * code from the local history.
- */
- public static boolean hasEdition(IJavaScriptElement je) {
-
- if (je instanceof IMember && ((IMember)je).isBinary())
- return false;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.team.ui.history.ElementLocalHistoryPageSource#getFile(java.lang.Object)
- */
- public IFile getFile(Object input) {
- // extract CU from input
- IJavaScriptUnit cu= null;
- if (input instanceof IJavaScriptUnit)
- cu= (IJavaScriptUnit) input;
- else if (input instanceof IMember)
- cu= ((IMember)input).getJavaScriptUnit();
-
- if (cu == null || !cu.exists())
- return null;
-
- // get to original CU
- cu= cu.getPrimary();
-
- // find underlying file
- IFile file= (IFile) cu.getResource();
- if (file != null && file.exists())
- return file;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryAction.java
deleted file mode 100644
index 62a89d2a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryAction.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IActionDelegate;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/**
- * A delegate for JavaHistoryActionImpls.
- */
-public abstract class JavaHistoryAction extends Action implements IActionDelegate {
-
- private JavaHistoryActionImpl fDelegate;
- private JavaEditor fEditor;
- private String fTitle;
- private String fMessage;
-
- JavaHistoryAction() {
- }
-
- private JavaHistoryActionImpl getDelegate() {
- if (fDelegate == null) {
- fDelegate= createDelegate();
- if (fEditor != null && fTitle != null && fMessage != null)
- fDelegate.init(fEditor, fTitle, fMessage);
- }
- return fDelegate;
- }
-
- protected abstract JavaHistoryActionImpl createDelegate();
-
- final void init(JavaEditor editor, String text, String title, String message) {
- Assert.isNotNull(editor);
- Assert.isNotNull(title);
- Assert.isNotNull(message);
- fEditor= editor;
- fTitle= title;
- fMessage= message;
- //getDelegate().init(editor, text, title, message);
- setText(text);
- //setEnabled(getDelegate().checkEnabled());
- }
-
- /**
- * Executes this action with the given selection.
- */
- public final void run(ISelection selection) {
- getDelegate().run(selection);
- }
-
- public final void run() {
- getDelegate().runFromEditor(this);
- }
-
- final void update() {
- getDelegate().update(this);
- }
-
- //---- IActionDelegate
-
- public final void selectionChanged(IAction uiProxy, ISelection selection) {
- getDelegate().selectionChanged(uiProxy, selection);
- }
-
- public final void run(IAction action) {
- getDelegate().run(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryActionImpl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryActionImpl.java
deleted file mode 100644
index 2d35a42f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaHistoryActionImpl.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Map;
-
-import org.eclipse.compare.HistoryItem;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.ResourceNode;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFileState;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.RewriteSessionEditProcessor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/**
- * Base class for the "Replace with local history"
- * and "Add from local history" actions.
- */
-abstract class JavaHistoryActionImpl /* extends Action implements IActionDelegate*/ {
-
- private boolean fModifiesFile;
- private ISelection fSelection;
-
- JavaHistoryActionImpl(boolean modifiesFile) {
- fModifiesFile= modifiesFile;
- }
-
- ISelection getSelection() {
- return fSelection;
- }
-
- final IFile getFile(Object input) {
- return JavaElementHistoryPageSource.getInstance().getFile(input);
- }
-
- final ITypedElement[] buildEditions(ITypedElement target, IFile file) {
-
- // setup array of editions
- IFileState[] states= null;
- // add available editions
- try {
- states= file.getHistory(null);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- }
-
- int count= 1;
- if (states != null)
- count+= states.length;
-
- ITypedElement[] editions= new ITypedElement[count];
- editions[0]= new ResourceNode(file);
- if (states != null)
- for (int i= 0; i < states.length; i++)
- editions[i+1]= new HistoryItem(target, states[i]);
- return editions;
- }
-
- final Shell getShell() {
- if (fEditor != null)
- return fEditor.getEditorSite().getShell();
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- /**
- * Tries to find the given element in a working copy.
- */
- final IJavaScriptElement getWorkingCopy(IJavaScriptElement input) {
- // TODO: With new working copy story: original == working copy.
- // Note that the previous code could result in a reconcile as side effect. Should check if that
- // is still required.
- return input;
- }
-
- final ASTNode getBodyContainer(JavaScriptUnit root, IMember parent) throws JavaScriptModelException {
- ISourceRange sourceRange= parent.getNameRange();
- ASTNode parentNode= NodeFinder.perform(root, sourceRange);
- do {
- if (parentNode instanceof TypeDeclaration )
- return parentNode;
- parentNode= parentNode.getParent();
- } while (parentNode != null);
- return null;
- }
-
- /**
- * Returns true if the given file is open in an editor.
- */
- final boolean beingEdited(IFile file) {
- IDocumentProvider dp= JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider();
- FileEditorInput input= new FileEditorInput(file);
- return dp.getDocument(input) != null;
- }
-
- /**
- * Returns an IMember or null.
- */
- final IMember getEditionElement(ISelection selection) {
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection ss= (IStructuredSelection) selection;
- if (ss.size() == 1) {
- Object o= ss.getFirstElement();
- if (o instanceof IMember) {
- IMember m= (IMember) o;
- if (m.exists() && !m.isBinary() && JavaStructureCreator.hasEdition(m))
- return m;
- }
- }
- }
- return null;
- }
-
- final boolean isEnabled(IFile file) {
- if (file == null || ! file.exists())
- return false;
- if (fModifiesFile) {
- // without validate/edit we would do this:
- // return !file.isReadOnly();
- // with validate/edit we have to return true
- return true;
- }
- return true;
- }
-
- boolean isEnabled(ISelection selection) {
- IMember m= getEditionElement(selection);
- if (m == null)
- return false;
- IFile file= getFile(m);
- if (!isEnabled(file))
- return false;
- return true;
- }
-
- void applyChanges(ASTRewrite rewriter, final IDocument document, final ITextFileBuffer textFileBuffer, Shell shell, boolean inEditor, Map options)
- throws CoreException, InvocationTargetException, InterruptedException {
-
-
- MultiTextEdit edit= new MultiTextEdit();
- try {
- TextEdit res= rewriter.rewriteAST(document, options);
- edit.addChildren(res.removeChildren());
- } catch (IllegalArgumentException e) {
- JavaScriptPlugin.log(e);
- }
-
- try {
- new RewriteSessionEditProcessor(document, edit, TextEdit.UPDATE_REGIONS).performEdits();
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
-
- IRunnableWithProgress r= new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) throws InvocationTargetException {
- try {
- textFileBuffer.commit(pm, false);
- } catch (CoreException ex) {
- throw new InvocationTargetException(ex);
- }
- }
- };
-
- if (inEditor) {
- // we don't show progress
- r.run(new NullProgressMonitor());
- } else {
- PlatformUI.getWorkbench().getProgressService().run(true, false, r);
- }
- }
-
- static String trimTextBlock(String content, String delimiter, IJavaScriptProject currentProject) {
- if (content != null) {
- String[] lines= Strings.convertIntoLines(content);
- if (lines != null) {
- Strings.trimIndentation(lines, currentProject);
- return Strings.concatenate(lines, delimiter);
- }
- }
- return null;
- }
-
- final JavaEditor getEditor(IFile file) {
- FileEditorInput fei= new FileEditorInput(file);
- IWorkbench workbench= JavaScriptPlugin.getDefault().getWorkbench();
- IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
- for (int i= 0; i < windows.length; i++) {
- IWorkbenchPage[] pages= windows[i].getPages();
- for (int x= 0; x < pages.length; x++) {
- IEditorPart[] editors= pages[x].getDirtyEditors();
- for (int z= 0; z < editors.length; z++) {
- IEditorPart ep= editors[z];
- if (ep instanceof JavaEditor) {
- JavaEditor je= (JavaEditor) ep;
- if (fei.equals(je.getEditorInput()))
- return (JavaEditor) ep;
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Executes this action with the given selection.
- */
- public abstract void run(ISelection selection);
-
- //---- Action
-
- private JavaEditor fEditor;
- private String fTitle;
- private String fMessage;
-
- void init(JavaEditor editor, String title, String message) {
- fEditor= editor;
- fTitle= title;
- fMessage= message;
- }
-
- final JavaEditor getEditor() {
- return fEditor;
- }
-
- final public void runFromEditor(IAction uiProxy) {
-
- // this run is called from Editor
- IJavaScriptElement element= null;
- try {
- element= SelectionConverter.getElementAtOffset(fEditor);
- } catch (JavaScriptModelException e) {
- // ignored
- }
-
- fSelection= element != null
- ? new StructuredSelection(element)
- : StructuredSelection.EMPTY;
- boolean isEnabled= isEnabled(fSelection);
- uiProxy.setEnabled(isEnabled);
-
- if (!isEnabled) {
- MessageDialog.openInformation(getShell(), fTitle, fMessage);
- return;
- }
- run(fSelection);
- }
-
- boolean checkEnabled() {
- IJavaScriptUnit unit= SelectionConverter.getInputAsCompilationUnit(fEditor);
- IFile file= getFile(unit);
- return isEnabled(file);
- }
-
- final public void update(IAction uiProxy) {
- uiProxy.setEnabled(checkEnabled());
- }
-
- //---- IActionDelegate
-
- final public void selectionChanged(IAction uiProxy, ISelection selection) {
- fSelection= selection;
- uiProxy.setEnabled(isEnabled(selection));
- }
-
- final public void run(IAction action) {
- run(fSelection);
- }
-
- static JavaScriptUnit parsePartialCompilationUnit(IJavaScriptUnit unit) {
-
- if (unit == null) {
- throw new IllegalArgumentException();
- }
- try {
- ASTParser c= ASTParser.newParser(AST.JLS3);
- c.setSource(unit);
- c.setFocalPosition(0);
- c.setResolveBindings(false);
- c.setWorkingCopyOwner(null);
- ASTNode result= c.createAST(null);
- return (JavaScriptUnit) result;
- } catch (IllegalStateException e) {
- // convert ASTParser's complaints into old form
- throw new IllegalArgumentException();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaMergeViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaMergeViewer.java
deleted file mode 100644
index d148a62a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaMergeViewer.java
+++ /dev/null
@@ -1,423 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IResourceProvider;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.contentmergeviewer.ITokenComparator;
-import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
-import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.compare.structuremergeviewer.IDiffContainer;
-import org.eclipse.compare.structuremergeviewer.IDiffElement;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentPartitioner;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextViewer;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.AbstractTextEditor;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.compare.JavaTokenComparator.ITokenComparatorFactory;
-import org.eclipse.wst.jsdt.internal.ui.text.PreferencesAdapter;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class JavaMergeViewer extends TextMergeViewer {
-
- private IPropertyChangeListener fPreferenceChangeListener;
- private IPreferenceStore fPreferenceStore;
- private boolean fUseSystemColors;
- private JavaScriptSourceViewerConfiguration fSourceViewerConfiguration;
- private ArrayList fSourceViewer;
-
-
- public JavaMergeViewer(Composite parent, int styles, CompareConfiguration mp) {
- super(parent, styles | SWT.LEFT_TO_RIGHT, mp);
-
- getPreferenceStore();
-
- fUseSystemColors= fPreferenceStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT);
- if (! fUseSystemColors) {
- RGB bg= createColor(fPreferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND);
- setBackgroundColor(bg);
- RGB fg= createColor(fPreferenceStore, IJavaScriptColorConstants.JAVA_DEFAULT);
- setForegroundColor(fg);
- }
- }
-
- private IPreferenceStore getPreferenceStore() {
- if (fPreferenceStore == null)
- setPreferenceStore(createChainedPreferenceStore(null));
- return fPreferenceStore;
- }
-
- protected void handleDispose(DisposeEvent event) {
- setPreferenceStore(null);
- fSourceViewer= null;
- super.handleDispose(event);
- }
-
- public IJavaScriptProject getJavaProject(ICompareInput input) {
-
- if (input == null)
- return null;
-
- IResourceProvider rp= null;
- ITypedElement te= input.getLeft();
- if (te instanceof IResourceProvider)
- rp= (IResourceProvider) te;
- if (rp == null) {
- te= input.getRight();
- if (te instanceof IResourceProvider)
- rp= (IResourceProvider) te;
- }
- if (rp == null) {
- te= input.getAncestor();
- if (te instanceof IResourceProvider)
- rp= (IResourceProvider) te;
- }
- if (rp != null) {
- IResource resource= rp.getResource();
- if (resource != null) {
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element != null)
- return element.getJavaScriptProject();
- }
- }
- return null;
- }
-
- public void setInput(Object input) {
-
- if (input instanceof ICompareInput) {
- IJavaScriptProject project= getJavaProject((ICompareInput)input);
- if (project != null) {
- setPreferenceStore(createChainedPreferenceStore(project));
- if (fSourceViewer != null) {
- Iterator iterator= fSourceViewer.iterator();
- while (iterator.hasNext()) {
- SourceViewer sourceViewer= (SourceViewer) iterator.next();
- sourceViewer.unconfigure();
- sourceViewer.configure(getSourceViewerConfiguration());
- }
- }
- }
- }
-
- super.setInput(input);
- }
-
- private ChainedPreferenceStore createChainedPreferenceStore(IJavaScriptProject project) {
- ArrayList stores= new ArrayList(4);
- if (project != null)
- stores.add(new EclipsePreferencesAdapter(new ProjectScope(project.getProject()), JavaScriptCore.PLUGIN_ID));
- stores.add(JavaScriptPlugin.getDefault().getPreferenceStore());
- stores.add(new PreferencesAdapter(JavaScriptCore.getPlugin().getPluginPreferences()));
- stores.add(EditorsUI.getPreferenceStore());
- return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
- }
-
- private void handlePropertyChange(PropertyChangeEvent event) {
-
- String key= event.getProperty();
-
- if (key.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND)) {
-
- if (!fUseSystemColors) {
- RGB bg= createColor(fPreferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND);
- setBackgroundColor(bg);
- }
-
- } else if (key.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
-
- fUseSystemColors= fPreferenceStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT);
- if (fUseSystemColors) {
- setBackgroundColor(null);
- setForegroundColor(null);
- } else {
- RGB bg= createColor(fPreferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND);
- setBackgroundColor(bg);
- RGB fg= createColor(fPreferenceStore, IJavaScriptColorConstants.JAVA_DEFAULT);
- setForegroundColor(fg);
- }
- } else if (key.equals(IJavaScriptColorConstants.JAVA_DEFAULT)) {
-
- if (!fUseSystemColors) {
- RGB fg= createColor(fPreferenceStore, IJavaScriptColorConstants.JAVA_DEFAULT);
- setForegroundColor(fg);
- }
- }
-
- if (fSourceViewerConfiguration != null && fSourceViewerConfiguration.affectsTextPresentation(event)) {
- fSourceViewerConfiguration.handlePropertyChangeEvent(event);
- invalidateTextPresentation();
- }
- }
-
- /**
- * Creates a color from the information stored in the given preference store.
- * Returns <code>null</code> if there is no such information available.
- * @param store preference store
- * @param key preference key
- * @return the color or <code>null</code>
- */
- private static RGB createColor(IPreferenceStore store, String key) {
- if (!store.contains(key))
- return null;
- if (store.isDefault(key))
- return PreferenceConverter.getDefaultColor(store, key);
- return PreferenceConverter.getColor(store, key);
- }
-
- public String getTitle() {
- return CompareMessages.JavaMergeViewer_title;
- }
-
- public ITokenComparator createTokenComparator(String s) {
- return new JavaTokenComparator(s, new ITokenComparatorFactory() {
- public ITokenComparator createTokenComparator(String text) {
- return JavaMergeViewer.super.createTokenComparator(text);
- }
- });
- }
-
- protected IDocumentPartitioner getDocumentPartitioner() {
- return JavaCompareUtilities.createJavaPartitioner();
- }
-
- protected String getDocumentPartitioning() {
- return IJavaScriptPartitions.JAVA_PARTITIONING;
- }
-
- protected void configureTextViewer(TextViewer textViewer) {
- if (textViewer instanceof SourceViewer) {
- if (fSourceViewer == null)
- fSourceViewer= new ArrayList();
- fSourceViewer.add(textViewer);
- JavaScriptTextTools tools= JavaCompareUtilities.getJavaTextTools();
- if (tools != null)
- ((SourceViewer)textViewer).configure(getSourceViewerConfiguration());
- }
- }
-
- private JavaScriptSourceViewerConfiguration getSourceViewerConfiguration() {
- if (fSourceViewerConfiguration == null)
- getPreferenceStore();
- return fSourceViewerConfiguration;
- }
-
- protected int findInsertionPosition(char type, ICompareInput input) {
-
- int pos= super.findInsertionPosition(type, input);
- if (pos != 0)
- return pos;
-
- if (input instanceof IDiffElement) {
-
- // find the other (not deleted) element
- JavaNode otherJavaElement= null;
- ITypedElement otherElement= null;
- switch (type) {
- case 'L':
- otherElement= input.getRight();
- break;
- case 'R':
- otherElement= input.getLeft();
- break;
- }
- if (otherElement instanceof JavaNode)
- otherJavaElement= (JavaNode) otherElement;
-
- // find the parent of the deleted elements
- JavaNode javaContainer= null;
- IDiffElement diffElement= (IDiffElement) input;
- IDiffContainer container= diffElement.getParent();
- if (container instanceof ICompareInput) {
-
- ICompareInput parent= (ICompareInput) container;
- ITypedElement element= null;
-
- switch (type) {
- case 'L':
- element= parent.getLeft();
- break;
- case 'R':
- element= parent.getRight();
- break;
- }
-
- if (element instanceof JavaNode)
- javaContainer= (JavaNode) element;
- }
-
- if (otherJavaElement != null && javaContainer != null) {
-
- Object[] children;
- Position p;
-
- switch (otherJavaElement.getTypeCode()) {
-
- case JavaNode.PACKAGE:
- return 0;
-
- case JavaNode.IMPORT_CONTAINER:
- // we have to find the place after the package declaration
- children= javaContainer.getChildren();
- if (children.length > 0) {
- JavaNode packageDecl= null;
- for (int i= 0; i < children.length; i++) {
- JavaNode child= (JavaNode) children[i];
- switch (child.getTypeCode()) {
- case JavaNode.PACKAGE:
- packageDecl= child;
- break;
- case JavaNode.CLASS:
- return child.getRange().getOffset();
- }
- }
- if (packageDecl != null) {
- p= packageDecl.getRange();
- return p.getOffset() + p.getLength();
- }
- }
- return javaContainer.getRange().getOffset();
-
- case JavaNode.IMPORT:
- // append after last import
- p= javaContainer.getRange();
- return p.getOffset() + p.getLength();
-
- case JavaNode.CLASS:
- // append after last class
- children= javaContainer.getChildren();
- if (children.length > 0) {
- for (int i= children.length-1; i >= 0; i--) {
- JavaNode child= (JavaNode) children[i];
- switch (child.getTypeCode()) {
- case JavaNode.CLASS:
- case JavaNode.IMPORT_CONTAINER:
- case JavaNode.PACKAGE:
- case JavaNode.FIELD:
- p= child.getRange();
- return p.getOffset() + p.getLength();
- }
- }
- }
- return javaContainer.getAppendPosition().getOffset();
-
- case JavaNode.METHOD:
- // append in next line after last child
- children= javaContainer.getChildren();
- if (children.length > 0) {
- JavaNode child= (JavaNode) children[children.length-1];
- p= child.getRange();
- return findEndOfLine(javaContainer, p.getOffset() + p.getLength());
- }
- // otherwise use position from parser
- return javaContainer.getAppendPosition().getOffset();
-
- case JavaNode.FIELD:
- // append after last field
- children= javaContainer.getChildren();
- if (children.length > 0) {
- JavaNode method= null;
- for (int i= children.length-1; i >= 0; i--) {
- JavaNode child= (JavaNode) children[i];
- switch (child.getTypeCode()) {
- case JavaNode.METHOD:
- method= child;
- break;
- case JavaNode.FIELD:
- p= child.getRange();
- return p.getOffset() + p.getLength();
- }
- }
- if (method != null)
- return method.getRange().getOffset();
- }
- return javaContainer.getAppendPosition().getOffset();
- }
- }
-
- if (javaContainer != null) {
- // return end of container
- Position p= javaContainer.getRange();
- return p.getOffset() + p.getLength();
- }
- }
-
- // we give up
- return 0;
- }
-
- private int findEndOfLine(JavaNode container, int pos) {
- int line;
- IDocument doc= container.getDocument();
- try {
- line= doc.getLineOfOffset(pos);
- pos= doc.getLineOffset(line+1);
- } catch (BadLocationException ex) {
- // silently ignored
- }
-
- // ensure that position is within container range
- Position containerRange= container.getRange();
- int start= containerRange.getOffset();
- int end= containerRange.getOffset() + containerRange.getLength();
- if (pos < start)
- return start;
- if (pos >= end)
- return end-1;
-
- return pos;
- }
-
- private void setPreferenceStore(IPreferenceStore ps) {
- if (fPreferenceChangeListener != null) {
- if (fPreferenceStore != null)
- fPreferenceStore.removePropertyChangeListener(fPreferenceChangeListener);
- fPreferenceChangeListener= null;
- }
- fPreferenceStore= ps;
- if (fPreferenceStore != null) {
- JavaScriptTextTools tools= JavaCompareUtilities.getJavaTextTools();
- fSourceViewerConfiguration= new JavaScriptSourceViewerConfiguration(tools.getColorManager(), fPreferenceStore, null, getDocumentPartitioning());
- fPreferenceChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- handlePropertyChange(event);
- }
- };
- fPreferenceStore.addPropertyChangeListener(fPreferenceChangeListener);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaNode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaNode.java
deleted file mode 100644
index 0c3ebdc0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaNode.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Comparable Java elements are represented as JavaNodes.
- * Extends the DocumentRangeNode with method signature information.
- */
-public class JavaNode extends DocumentRangeNode implements ITypedElement {
-
- public static final int CU= 0;
- public static final int PACKAGE= 1;
- public static final int IMPORT_CONTAINER= 2;
- public static final int IMPORT= 3;
- public static final int INTERFACE= 4;
- public static final int CLASS= 5;
- public static final int ENUM= 6;
- public static final int ANNOTATION= 7;
- public static final int FIELD= 8;
- public static final int INIT= 9;
- public static final int CONSTRUCTOR= 10;
- public static final int METHOD= 11;
-
- private int fInitializerCount= 1;
-
- /**
- * Creates a JavaNode under the given parent.
- * @param parent the parent node
- * @param type the Java elements type. Legal values are from the range CU to METHOD of this class.
- * @param name the name of the Java element
- * @param start the starting position of the java element in the underlying document
- * @param length the number of characters of the java element in the underlying document
- */
- public JavaNode(JavaNode parent, int type, String name, int start, int length) {
- super(parent, type, JavaCompareUtilities.buildID(type, name), parent.getDocument(), start, length);
- parent.addChild(this);
- }
-
- /**
- * Creates a JavaNode for a CU. It represents the root of a
- * JavaNode tree, so its parent is null.
- * @param document the document which contains the Java element
- */
- public JavaNode(IDocument document) {
- super(CU, JavaCompareUtilities.buildID(CU, "root"), document, 0, document.getLength()); //$NON-NLS-1$
- }
-
- public String getInitializerCount() {
- return Integer.toString(fInitializerCount++);
- }
-
- /**
- * Extracts the method name from the signature.
- * Used for smart matching.
- */
- public String extractMethodName() {
- String id= getId();
- int pos= id.indexOf('(');
- if (pos > 0)
- return id.substring(1, pos);
- return id.substring(1);
- }
-
- /**
- * Extracts the method's arguments name the signature.
- * Used for smart matching.
- */
- public String extractArgumentList() {
- String id= getId();
- int pos= id.indexOf('(');
- if (pos >= 0)
- return id.substring(pos+1);
- return id.substring(1);
- }
-
- /**
- * Returns a name which is presented in the UI.
- * @see ITypedElement#getName()
- */
- public String getName() {
-
- switch (getTypeCode()) {
- case INIT:
- return CompareMessages.JavaNode_initializer;
- case IMPORT_CONTAINER:
- return CompareMessages.JavaNode_importDeclarations;
- case CU:
- return CompareMessages.JavaNode_compilationUnit;
- case PACKAGE:
- return CompareMessages.JavaNode_packageDeclaration;
- }
- return getId().substring(1); // we strip away the type character
- }
-
- /*
- * @see ITypedElement#getType()
- */
- public String getType() {
- return "java2"; //$NON-NLS-1$
- }
-
- /**
- * Returns a shared image for this Java element.
- *
- * see ITypedInput.getImage
- */
- public Image getImage() {
-
- ImageDescriptor id= null;
-
- switch (getTypeCode()) {
- case CU:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.JAVASCRIPT_UNIT);
- break;
- case IMPORT:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.IMPORT_DECLARATION);
- break;
- case IMPORT_CONTAINER:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.IMPORT_CONTAINER);
- break;
- case CLASS:
- id= JavaCompareUtilities.getTypeImageDescriptor(true);
- break;
- case INTERFACE:
- id= JavaCompareUtilities.getTypeImageDescriptor(false);
- break;
- case INIT:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.INITIALIZER);
- break;
- case CONSTRUCTOR:
- case METHOD:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.METHOD);
- break;
- case FIELD:
- id= JavaCompareUtilities.getImageDescriptor(IJavaScriptElement.FIELD);
- break;
- case ENUM:
- id= JavaCompareUtilities.getEnumImageDescriptor();
- break;
- case ANNOTATION:
- id= JavaCompareUtilities.getAnnotationImageDescriptor();
- break;
- }
- return JavaScriptPlugin.getImageDescriptorRegistry().get(id);
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return getType() + ": " + getName() //$NON-NLS-1$
- + "[" + getRange().offset + "+" + getRange().length + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaParseTreeBuilder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaParseTreeBuilder.java
deleted file mode 100644
index 2719e1f2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaParseTreeBuilder.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.Iterator;
-import java.util.Stack;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-
-
-class JavaParseTreeBuilder extends ASTVisitor {
-
- private char[] fBuffer;
- private Stack fStack= new Stack();
- private JavaNode fImportContainer;
- private boolean fShowCU;
-
- /*
- * Parsing is performed on the given buffer and the resulting tree (if any)
- * hangs below the given root.
- */
- JavaParseTreeBuilder(JavaNode root, char[] buffer, boolean showCU) {
- fBuffer= buffer;
- fShowCU= showCU;
- fStack.clear();
- fStack.push(root);
- }
-
- public boolean visit(PackageDeclaration node) {
- new JavaNode(getCurrentContainer(), JavaNode.PACKAGE, null, node.getStartPosition(), node.getLength());
- return false;
- }
-
- public boolean visit(JavaScriptUnit node) {
- if (fShowCU)
- push(JavaNode.CU, null, node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(JavaScriptUnit node) {
- if (fShowCU)
- pop();
- }
-
- public boolean visit(TypeDeclaration node) {
- push(JavaNode.CLASS, node.getName().toString(), node.getStartPosition(), node.getLength());
- return true;
- }
-
- public void endVisit(TypeDeclaration node) {
- pop();
- }
-
-
-
-
-
- public boolean visit(FunctionDeclaration node) {
- String signature= getSignature(node);
- push(node.isConstructor() ? JavaNode.CONSTRUCTOR : JavaNode.METHOD, signature, node.getStartPosition(), node.getLength());
- return false;
- }
-
- public void endVisit(FunctionDeclaration node) {
- pop();
- }
-
- public boolean visit(Initializer node) {
- push(JavaNode.INIT, getCurrentContainer().getInitializerCount(), node.getStartPosition(), node.getLength());
- return false;
- }
-
- public void endVisit(Initializer node) {
- pop();
- }
-
- public boolean visit(ImportDeclaration node) {
- int s= node.getStartPosition();
- int l= node.getLength();
- int declarationEnd= s + l;
- if (fImportContainer == null)
- fImportContainer= new JavaNode(getCurrentContainer(), JavaNode.IMPORT_CONTAINER, null, s, l);
- String nm= node.getName().toString();
- if (node.isOnDemand())
- nm+= ".*"; //$NON-NLS-1$
- new JavaNode(fImportContainer, JavaNode.IMPORT, nm, s, l);
- fImportContainer.setLength(declarationEnd - fImportContainer.getRange().getOffset() + 1);
- fImportContainer.setAppendPosition(declarationEnd + 2); // FIXME
- return false;
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- String name= getFieldName(node);
- ASTNode parent= node.getParent();
- push(JavaNode.FIELD, name, parent.getStartPosition(), parent.getLength());
- return false;
- }
-
- public void endVisit(VariableDeclarationFragment node) {
- pop();
- }
-
- // private stuff
-
- /**
- * Adds a new JavaNode with the given type and name to the current
- * container.
- */
- private void push(int type, String name, int declarationStart, int length) {
-
- while (declarationStart > 0) {
- char c= fBuffer[declarationStart - 1];
- if (c != ' ' && c != '\t')
- break;
- declarationStart--;
- length++;
- }
-
- JavaNode node= new JavaNode(getCurrentContainer(), type, name, declarationStart, length);
- if (type == JavaNode.CU)
- node.setAppendPosition(declarationStart + length + 1);
- else
- node.setAppendPosition(declarationStart + length);
-
- fStack.push(node);
- }
-
- /**
- * Closes the current Java node by setting its end position and pops it off
- * the stack.
- */
- private void pop() {
- fStack.pop();
- }
-
- private JavaNode getCurrentContainer() {
- return (JavaNode) fStack.peek();
- }
-
- private String getFieldName(VariableDeclarationFragment node) {
- StringBuffer buffer= new StringBuffer();
- buffer.append(node.getName().toString());
- ASTNode parent= node.getParent();
- if (parent instanceof FieldDeclaration) {
- FieldDeclaration fd= (FieldDeclaration) parent;
- buffer.append(" : "); //$NON-NLS-1$
- buffer.append(getType(fd.getType()));
- }
- return buffer.toString();
- }
-
- private String getSignature(FunctionDeclaration node) {
- StringBuffer buffer= new StringBuffer();
- SimpleName name = node.getName();
- if (name!=null)
- buffer.append(name.toString());
-
- buffer.append('(');
- boolean first= true;
- Iterator iterator= node.parameters().iterator();
- while (iterator.hasNext()) {
- Object parameterDecl= iterator.next();
- if (parameterDecl instanceof SingleVariableDeclaration) {
- SingleVariableDeclaration svd= (SingleVariableDeclaration) parameterDecl;
- if (!first)
- buffer.append(", "); //$NON-NLS-1$
- buffer.append(getType(svd.getType()));
- if (svd.isVarargs())
- buffer.append("..."); //$NON-NLS-1$
- first= false;
- }
- }
- buffer.append(')');
- return buffer.toString();
- }
-
-
- private String getType(Type type) {
- String name= type.toString();
- int pos= name.lastIndexOf('.');
- if (pos >= 0)
- name= name.substring(pos + 1);
- return name;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionAction.java
deleted file mode 100644
index ad083b55..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionAction.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-/**
- * Provides "Replace from local history" for Java elements.
- */
-public class JavaReplaceWithEditionAction extends JavaHistoryAction {
-
- public JavaReplaceWithEditionAction() {
- }
-
- protected JavaHistoryActionImpl createDelegate() {
- return new JavaReplaceWithEditionActionImpl(false);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionActionImpl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionActionImpl.java
deleted file mode 100644
index 74c56050..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithEditionActionImpl.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Map;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.CompareUI;
-import org.eclipse.compare.IStreamContentAccessor;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.team.core.TeamException;
-import org.eclipse.team.ui.history.ElementLocalHistoryPageSource;
-import org.eclipse.team.ui.history.HistoryPageCompareEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-
-/**
- * Provides "Replace from local history" for Java elements.
- */
-class JavaReplaceWithEditionActionImpl extends JavaHistoryActionImpl {
-
- protected boolean fPrevious= false;
-
- JavaReplaceWithEditionActionImpl(boolean previous) {
- super(true);
- fPrevious= previous;
- }
-
- public void run(ISelection selection) {
-
- Shell shell= getShell();
-
- final IMember input= getEditionElement(selection);
- if (input == null) {
- MessageDialog.openInformation(shell, CompareMessages.ReplaceFromHistory_title, CompareMessages.ReplaceFromHistory_invalidSelectionMessage);
- return;
- }
-
- final IFile file= getFile(input);
- if (file == null) {
- showError();
- return;
- }
-
- IStatus status= Resources.makeCommittable(file, shell);
- if (!status.isOK()) {
- return;
- }
-
- if (fPrevious) {
- String errorTitle= CompareMessages.ReplaceFromHistory_title;
- String errorMessage= CompareMessages.ReplaceFromHistory_internalErrorMessage;
- try {
- ITypedElement ti = ElementLocalHistoryPageSource.getPreviousEdition(file, input);
- if (ti == null) {
- MessageDialog.openInformation(shell, errorTitle, CompareMessages.ReplaceFromHistory_parsingErrorMessage);
- return;
- }
- replace(input, file, ti);
- } catch (TeamException e) {
- ExceptionHandler.handle(e, shell, errorTitle, errorMessage);
- }
- } else {
- JavaElementHistoryPageSource pageSource = JavaElementHistoryPageSource.getInstance();
- CompareConfiguration cc = new CompareConfiguration();
- cc.setLeftEditable(false);
- cc.setRightEditable(false);
- HistoryPageCompareEditorInput ci = new HistoryPageCompareEditorInput(cc, pageSource, input) {
- protected void performReplace(Object selectedElement) {
- if (selectedElement instanceof ITypedElement) {
- JavaReplaceWithEditionActionImpl.this.replace(input, file, (ITypedElement)selectedElement);
- }
- }
- };
- ci.setReplace(true);
- ci.setTitle(CompareMessages.JavaReplaceWithEditionActionImpl_0);
- ci.setHelpContextId(IJavaHelpContextIds.REPLACE_ELEMENT_WITH_HISTORY_DIALOG);
- CompareUI.openCompareDialog(ci);
- }
- }
-
- public void replace(IMember input, IFile file, ITypedElement element) {
-
- Shell shell= getShell();
-
- String errorTitle= CompareMessages.ReplaceFromHistory_title;
- String errorMessage= CompareMessages.ReplaceFromHistory_internalErrorMessage;
-
- // get the document where to insert the text
- IPath path= file.getFullPath();
- ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager();
- ITextFileBuffer textFileBuffer= null;
- try {
- bufferManager.connect(path, LocationKind.IFILE, null);
- textFileBuffer= bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
- IDocument document= textFileBuffer.getDocument();
- performReplace(input, file, textFileBuffer, document, element);
- } catch(InvocationTargetException ex) {
- ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
-
- } catch(InterruptedException ex) {
- // shouldn't be called because is not cancelable
- Assert.isTrue(false);
-
- } catch(CoreException ex) {
- ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
-
- } finally {
- try {
- if (textFileBuffer != null)
- bufferManager.disconnect(path, LocationKind.IFILE, null);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- private void performReplace(IMember input, IFile file,
- ITextFileBuffer textFileBuffer, IDocument document, ITypedElement ti)
- throws CoreException, JavaScriptModelException,
- InvocationTargetException, InterruptedException {
-
- if (ti instanceof IStreamContentAccessor) {
-
- boolean inEditor= beingEdited(file);
-
- String content= JavaCompareUtilities.readString((IStreamContentAccessor)ti);
- String newContent= trimTextBlock(content, TextUtilities.getDefaultLineDelimiter(document), input.getJavaScriptProject());
- if (newContent == null) {
- showError();
- return;
- }
-
- IJavaScriptUnit compilationUnit= input.getJavaScriptUnit();
- JavaScriptUnit root= parsePartialCompilationUnit(compilationUnit);
-
-
- final ISourceRange nameRange= input.getNameRange();
- // workaround for bug in getNameRange(): for AnnotationMembers length is negative
- int length= nameRange.getLength();
- if (length < 0)
- length= 1;
- ASTNode node2= NodeFinder.perform(root, new SourceRange(nameRange.getOffset(), length));
- ASTNode node= ASTNodes.getParent(node2, BodyDeclaration.class);
-
- //ASTNode node= getBodyContainer(root, input);
- if (node == null) {
- showError();
- return;
- }
-
- ASTRewrite rewriter= ASTRewrite.create(root.getAST());
- rewriter.replace(node, rewriter.createStringPlaceholder(newContent, node.getNodeType()), null);
-
- if (inEditor) {
- JavaEditor je= getEditor(file);
- if (je != null)
- je.setFocus();
- }
-
- Map options= null;
- IJavaScriptProject javaProject= compilationUnit.getJavaScriptProject();
- if (javaProject != null)
- options= javaProject.getOptions(true);
- applyChanges(rewriter, document, textFileBuffer, getShell(), inEditor, options);
-
- }
- }
-
- private void showError() {
- MessageDialog.openError(getShell(), CompareMessages.ReplaceFromHistory_title, CompareMessages.ReplaceFromHistory_internalErrorMessage);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithPreviousEditionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithPreviousEditionAction.java
deleted file mode 100644
index e11639a0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaReplaceWithPreviousEditionAction.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-/**
- * Provides "Replace from local history" for Java elements.
- */
-public class JavaReplaceWithPreviousEditionAction extends JavaHistoryAction {
-
- public JavaReplaceWithPreviousEditionAction() {
- }
-
- protected JavaHistoryActionImpl createDelegate() {
- return new JavaReplaceWithEditionActionImpl(true);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureCreator.java
deleted file mode 100644
index 0bd482dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureCreator.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.compare.CompareUI;
-import org.eclipse.compare.IEditableContent;
-import org.eclipse.compare.IEditableContentExtension;
-import org.eclipse.compare.IResourceProvider;
-import org.eclipse.compare.ISharedDocumentAdapter;
-import org.eclipse.compare.IStreamContentAccessor;
-import org.eclipse.compare.structuremergeviewer.DiffNode;
-import org.eclipse.compare.structuremergeviewer.Differencer;
-import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
-import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.compare.structuremergeviewer.IDiffContainer;
-import org.eclipse.compare.structuremergeviewer.IDiffElement;
-import org.eclipse.compare.structuremergeviewer.IStructureComparator;
-import org.eclipse.compare.structuremergeviewer.StructureCreator;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentPartitioner;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.services.IDisposable;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-public class JavaStructureCreator extends StructureCreator {
-
- private Map fDefaultCompilerOptions;
-
- /**
- * A root node for the structure. It is similar to {@link org.eclipse.compare.structuremergeviewer.StructureRootNode} but needed
- * to be a subclass of {@link JavaNode} because of the code used to build the structure.
- */
- private final class RootJavaNode extends JavaNode implements IDisposable {
-
- private final Object fInput;
- private final boolean fEditable;
- private final ISharedDocumentAdapter fAdapter;
-
- private RootJavaNode(IDocument document, boolean editable, Object input, ISharedDocumentAdapter adapter) {
- super(document);
- this.fEditable = editable;
- fInput= input;
- fAdapter= adapter;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.DocumentRangeNode#isEditable()
- */
- public boolean isEditable() {
- return fEditable;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.DocumentRangeNode#nodeChanged(org.eclipse.compare.structuremergeviewer.DocumentRangeNode)
- */
- protected void nodeChanged(DocumentRangeNode node) {
- save(this, fInput);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.services.IDisposable#dispose()
- */
- public void dispose() {
- if (fAdapter != null) {
- fAdapter.disconnect(fInput);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.DocumentRangeNode#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class adapter) {
- if (adapter == ISharedDocumentAdapter.class) {
- return fAdapter;
- }
- return super.getAdapter(adapter);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.DocumentRangeNode#isReadOnly()
- */
- public boolean isReadOnly() {
- if (fInput instanceof IEditableContentExtension) {
- IEditableContentExtension ext = (IEditableContentExtension) fInput;
- return ext.isReadOnly();
- }
- return super.isReadOnly();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.DocumentRangeNode#validateEdit(org.eclipse.swt.widgets.Shell)
- */
- public IStatus validateEdit(Shell shell) {
- if (fInput instanceof IEditableContentExtension) {
- IEditableContentExtension ext = (IEditableContentExtension) fInput;
- return ext.validateEdit(shell);
- }
- return super.validateEdit(shell);
- }
- }
-
- /**
- * RewriteInfos are used temporarily when rewriting the diff tree
- * in order to combine similar diff nodes ("smart folding").
- */
- static class RewriteInfo {
-
- boolean fIsOut= false;
-
- JavaNode fAncestor= null;
- JavaNode fLeft= null;
- JavaNode fRight= null;
-
- ArrayList fChildren= new ArrayList();
-
- void add(IDiffElement diff) {
- fChildren.add(diff);
- }
-
- void setDiff(ICompareInput diff) {
- if (fIsOut)
- return;
-
- fIsOut= true;
-
- JavaNode a= (JavaNode) diff.getAncestor();
- JavaNode y= (JavaNode) diff.getLeft();
- JavaNode m= (JavaNode) diff.getRight();
-
- if (a != null) {
- if (fAncestor != null)
- return;
- fAncestor= a;
- }
- if (y != null) {
- if (fLeft != null)
- return;
- fLeft= y;
- }
- if (m != null) {
- if (fRight != null)
- return;
- fRight= m;
- }
-
- fIsOut= false;
- }
-
- /**
- * @return true if some nodes could be successfully combined into one
- */
- boolean matches() {
- return !fIsOut && fAncestor != null && fLeft != null && fRight != null;
- }
- }
-
- public JavaStructureCreator() {
- }
-
- void setDefaultCompilerOptions(Map compilerSettings) {
- fDefaultCompilerOptions= compilerSettings;
- }
-
- /**
- * @return the name that appears in the enclosing pane title bar
- */
- public String getName() {
- return CompareMessages.JavaStructureViewer_title;
- }
-
- /**
- * @param input implement the IStreamContentAccessor interface
- * @return a tree of JavaNodes for the given input.
- * In case of error null is returned.
- */
- public IStructureComparator getStructure(final Object input) {
- String contents= null;
- char[] buffer= null;
- IDocument doc= CompareUI.getDocument(input);
- if (doc == null) {
- if (input instanceof IStreamContentAccessor) {
- IStreamContentAccessor sca= (IStreamContentAccessor) input;
- try {
- contents= JavaCompareUtilities.readString(sca);
- } catch (CoreException ex) {
- // return null indicates the error.
- return null;
- }
- }
-
- if (contents != null) {
- int n= contents.length();
- buffer= new char[n];
- contents.getChars(0, n, buffer, 0);
-
- doc= new Document(contents);
- setupDocument(doc);
- }
- }
-
- return createStructureComparator(input, buffer, doc, null, null);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.StructureCreator#createStructureComparator(java.lang.Object, org.eclipse.jface.text.IDocument, org.eclipse.compare.ISharedDocumentAdapter, org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IStructureComparator createStructureComparator(Object element,
- IDocument document, ISharedDocumentAdapter sharedDocumentAdapter,
- IProgressMonitor monitor) throws CoreException {
- return createStructureComparator(element, null, document, sharedDocumentAdapter, monitor);
- }
-
- private IStructureComparator createStructureComparator(final Object input, char[] buffer, IDocument doc, ISharedDocumentAdapter adapter, IProgressMonitor monitor) {
- String contents;
- Map compilerOptions= null;
-
- if (input instanceof IResourceProvider) {
- IResource resource= ((IResourceProvider) input).getResource();
- if (resource != null) {
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element != null) {
- IJavaScriptProject javaProject= element.getJavaScriptProject();
- if (javaProject != null)
- compilerOptions= javaProject.getOptions(true);
- }
- }
- }
- if (compilerOptions == null)
- compilerOptions= fDefaultCompilerOptions;
-
- if (doc != null) {
- boolean isEditable= false;
- if (input instanceof IEditableContent)
- isEditable= ((IEditableContent) input).isEditable();
-
- // we hook into the root node to intercept all node changes
- JavaNode root= new RootJavaNode(doc, isEditable, input, adapter);
-
- if (buffer == null) {
- contents= doc.get();
- int n= contents.length();
- buffer= new char[n];
- contents.getChars(0, n, buffer, 0);
- }
-
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- if (compilerOptions != null)
- parser.setCompilerOptions(compilerOptions);
- parser.setSource(buffer);
- parser.setFocalPosition(0);
- JavaScriptUnit cu= (JavaScriptUnit) parser.createAST(monitor);
- cu.accept(new JavaParseTreeBuilder(root, buffer, true));
-
- return root;
- }
- return null;
- }
-
- /**
- * Returns the contents of the given node as a string.
- * This string is used to test the content of a Java element
- * for equality. Is is never shown in the UI, so any string representing
- * the content will do.
- * @param node must implement the IStreamContentAccessor interface
- * @param ignoreWhiteSpace if true all Java white space (including comments) is removed from the contents.
- * @return contents for equality test
- */
- public String getContents(Object node, boolean ignoreWhiteSpace) {
-
- if (! (node instanceof IStreamContentAccessor))
- return null;
-
- IStreamContentAccessor sca= (IStreamContentAccessor) node;
- String content= null;
- try {
- content= JavaCompareUtilities.readString(sca);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- return null;
- }
-
- if (ignoreWhiteSpace) { // we return everything but Java whitespace
-
- // replace comments and whitespace by a single blank
- StringBuffer buf= new StringBuffer();
- char[] b= content.toCharArray();
-
- // to avoid the trouble when dealing with Unicode
- // we use the Java scanner to extract non-whitespace and non-comment tokens
- IScanner scanner= ToolFactory.createScanner(true, true, false, false); // however we request Whitespace and Comments
- scanner.setSource(b);
- try {
- int token;
- while ((token= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) {
- switch (token) {
- case ITerminalSymbols.TokenNameWHITESPACE:
- int l= buf.length();
- if (l > 0 && buf.charAt(l-1) != ' ')
- buf.append(' ');
- break;
- default:
- buf.append(scanner.getCurrentTokenSource());
- buf.append(' ');
- break;
- }
- }
- content= buf.toString(); // success!
- } catch (InvalidInputException ex) {
- // NeedWork
- }
- }
- return content;
- }
-
- /**
- * @return true since this IStructureCreator can rewrite the diff tree
- * in order to fold certain combinations of additions and deletions.
- */
- public boolean canRewriteTree() {
- return true;
- }
-
- /**
- * Tries to detect certain combinations of additions and deletions
- * as renames or signature changes and folders them into a single node.
- * @param differencer
- * @param root
- */
- public void rewriteTree(Differencer differencer, IDiffContainer root) {
-
- HashMap map= new HashMap(10);
-
- Object[] children= root.getChildren();
- for (int i= 0; i < children.length; i++) {
- DiffNode diff= (DiffNode) children[i];
- JavaNode jn= (JavaNode) diff.getId();
-
- if (jn == null)
- continue;
- int type= jn.getTypeCode();
-
- // we can only combine methods or constructors
- if (type == JavaNode.METHOD || type == JavaNode.CONSTRUCTOR) {
-
- // find or create a RewriteInfo for all methods with the same name
- String name= jn.extractMethodName();
- RewriteInfo nameInfo= (RewriteInfo) map.get(name);
- if (nameInfo == null) {
- nameInfo= new RewriteInfo();
- map.put(name, nameInfo);
- }
- nameInfo.add(diff);
-
- // find or create a RewriteInfo for all methods with the same
- // (non-empty) argument list
- String argList= jn.extractArgumentList();
- RewriteInfo argInfo= null;
- if (argList != null && !argList.equals("()")) { //$NON-NLS-1$
- argInfo= (RewriteInfo) map.get(argList);
- if (argInfo == null) {
- argInfo= new RewriteInfo();
- map.put(argList, argInfo);
- }
- argInfo.add(diff);
- }
-
- switch (diff.getKind() & Differencer.CHANGE_TYPE_MASK) {
- case Differencer.ADDITION:
- case Differencer.DELETION:
- // we only consider addition and deletions
- // since a rename or argument list change looks
- // like a pair of addition and deletions
- if (type != JavaNode.CONSTRUCTOR)
- nameInfo.setDiff(diff);
-
- if (argInfo != null)
- argInfo.setDiff(diff);
- break;
- default:
- break;
- }
- }
-
- // recurse
- rewriteTree(differencer, diff);
- }
-
- // now we have to rebuild the diff tree according to the combined
- // changes
- Iterator it= map.keySet().iterator();
- while (it.hasNext()) {
- String name= (String) it.next();
- RewriteInfo i= (RewriteInfo) map.get(name);
- if (i.matches()) { // we found a RewriteInfo that could be successfully combined
-
- // we have to find the differences of the newly combined node
- // (because in the first pass we only got a deletion and an addition)
- DiffNode d= (DiffNode) differencer.findDifferences(true, null, root, i.fAncestor, i.fLeft, i.fRight);
- if (d != null) {// there better should be a difference
- d.setDontExpand(true);
- Iterator it2= i.fChildren.iterator();
- while (it2.hasNext()) {
- IDiffElement rd= (IDiffElement) it2.next();
- root.removeToRoot(rd);
- d.add(rd);
- }
- }
- }
- }
- }
-
- /**
- * The JavaHistoryAction uses this function to determine whether
- * a selected Java element can be replaced by some piece of
- * code from the local history.
- * @param je Java element
- * @return true if the given IJavaScriptElement maps to a JavaNode
- */
- static boolean hasEdition(IJavaScriptElement je) {
- return JavaElementHistoryPageSource.hasEdition(je);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.StructureCreator#getDocumentPartitioner()
- */
- protected IDocumentPartitioner getDocumentPartitioner() {
- return JavaCompareUtilities.createJavaPartitioner();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.StructureCreator#getDocumentPartitioning()
- */
- protected String getDocumentPartitioning() {
- return IJavaScriptPartitions.JAVA_PARTITIONING;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.compare.structuremergeviewer.StructureCreator#getPath(java.lang.Object, java.lang.Object)
- */
- protected String[] getPath(Object element, Object input) {
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement je = (IJavaScriptElement) element;
- // build a path starting at the given Java element and walk
- // up the parent chain until we reach a IWorkingCopy or IJavaScriptUnit
- List args= new ArrayList();
- while (je != null) {
- // each path component has a name that uses the same
- // conventions as a JavaNode name
- String name= JavaCompareUtilities.getJavaElementID(je);
- if (name == null)
- return null;
- args.add(name);
- if (je instanceof IJavaScriptUnit)
- break;
- je= je.getParent();
- }
-
- // revert the path
- int n= args.size();
- String[] path= new String[n];
- for (int i= 0; i < n; i++)
- path[i]= (String) args.get(n-1-i);
-
- return path;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewer.java
deleted file mode 100644
index 00c3aa12..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewer.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.Map;
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.CompareViewerPane;
-import org.eclipse.compare.IResourceProvider;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.structuremergeviewer.DiffNode;
-import org.eclipse.compare.structuremergeviewer.Differencer;
-import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.compare.structuremergeviewer.IDiffContainer;
-import org.eclipse.compare.structuremergeviewer.StructureDiffViewer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-class JavaStructureDiffViewer extends StructureDiffViewer {
-
- /**
- * Toggles a boolean property of an <code>CompareConfiguration</code>.
- */
- static class ChangePropertyAction extends Action {
-
- private CompareConfiguration fCompareConfiguration;
- private String fPropertyKey;
- private ResourceBundle fBundle;
- private String fPrefix;
-
-
- public ChangePropertyAction(ResourceBundle bundle, CompareConfiguration cc, String rkey, String pkey) {
- fPropertyKey= pkey;
- fBundle= bundle;
- fPrefix= rkey;
- JavaCompareUtilities.initAction(this, fBundle, fPrefix);
- setCompareConfiguration(cc);
- }
-
- public void run() {
- boolean b= !JavaCompareUtilities.getBoolean(fCompareConfiguration, fPropertyKey, false);
- setChecked(b);
- if (fCompareConfiguration != null)
- fCompareConfiguration.setProperty(fPropertyKey, new Boolean(b));
- }
-
- public void setChecked(boolean state) {
- super.setChecked(state);
- JavaCompareUtilities.initToggleAction(this, fBundle, fPrefix, state);
- }
-
- public void setCompareConfiguration(CompareConfiguration cc) {
- fCompareConfiguration= cc;
- setChecked(JavaCompareUtilities.getBoolean(fCompareConfiguration, fPropertyKey, false));
- }
- }
-
- private static final String SMART= "SMART"; //$NON-NLS-1$
-
- private ActionContributionItem fSmartActionItem;
- private JavaStructureCreator fStructureCreator;
- private boolean fThreeWay;
-
- public JavaStructureDiffViewer(Composite parent, CompareConfiguration configuration) {
- super(parent, configuration);
- fStructureCreator= new JavaStructureCreator();
- setStructureCreator(fStructureCreator);
- }
-
- /**
- * Overridden to find and expand the first class.
- */
- protected void initialSelection() {
- Object firstClass= null;
- Object o= getRoot();
- if (o != null) {
- Object[] children= getSortedChildren(o);
- if (children != null && children.length > 0) {
- for (int i= 0; i < children.length; i++) {
- o= children[i];
- Object[] sortedChildren= getSortedChildren(o);
- if (sortedChildren != null && sortedChildren.length > 0) {
- for (int j= 0; j < sortedChildren.length; j++) {
- o= sortedChildren[j];
- if (o instanceof DiffNode) {
- DiffNode dn= (DiffNode) o;
- ITypedElement e= dn.getId();
- if (e instanceof JavaNode) {
- JavaNode jn= (JavaNode) e;
- int tc= jn.getTypeCode();
- if (tc == JavaNode.CLASS || tc == JavaNode.INTERFACE) {
- firstClass= dn;
- }
- }
- }
- }
- }
- }
- }
- }
- if (firstClass != null)
- expandToLevel(firstClass, 1);
- else
- expandToLevel(2);
- }
-
- protected void compareInputChanged(ICompareInput input) {
-
- fThreeWay= input != null ? input.getAncestor() != null
- : false;
- setSmartButtonVisible(fThreeWay);
-
- if (input != null) {
- Map compilerOptions= getCompilerOptions(input.getAncestor());
- if (compilerOptions == null)
- compilerOptions= getCompilerOptions(input.getLeft());
- if (compilerOptions == null)
- compilerOptions= getCompilerOptions(input.getRight());
- if (compilerOptions != null)
- fStructureCreator.setDefaultCompilerOptions(compilerOptions);
- }
-
- super.compareInputChanged(input);
- }
-
- private Map getCompilerOptions(ITypedElement input) {
- if (input instanceof IResourceProvider) {
- IResource resource= ((IResourceProvider) input).getResource();
- if (resource != null) {
- IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element != null) {
- IJavaScriptProject javaProject= element.getJavaScriptProject();
- if (javaProject != null)
- return javaProject.getOptions(true);
- }
- }
- }
- return null;
- }
-
- /**
- * Overriden to create a "smart" button in the viewer's pane control bar.
- * <p>
- * Clients can override this method and are free to decide whether they want to call
- * the inherited method.
- *
- * @param toolBarManager the toolbar manager for which to add the buttons
- */
- protected void createToolItems(ToolBarManager toolBarManager) {
-
- super.createToolItems(toolBarManager);
-
- IAction a= new ChangePropertyAction(getBundle(), getCompareConfiguration(), "action.Smart.", SMART); //$NON-NLS-1$
- fSmartActionItem= new ActionContributionItem(a);
- fSmartActionItem.setVisible(fThreeWay);
- toolBarManager.appendToGroup("modes", fSmartActionItem); //$NON-NLS-1$
- }
-
- protected void postDiffHook(Differencer differencer, IDiffContainer root, IProgressMonitor monitor) {
- if (fStructureCreator.canRewriteTree()) {
- boolean smart= JavaCompareUtilities.getBoolean(getCompareConfiguration(), SMART, false);
- if (smart && root != null)
- fStructureCreator.rewriteTree(differencer, root);
- }
- }
-
- /**
- * Tracks property changes of the configuration object.
- * Clients may override to track their own property changes.
- * In this case they must call the inherited method.
- */
- protected void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(SMART))
- diff();
- else
- super.propertyChange(event);
- }
-
- private void setSmartButtonVisible(boolean visible) {
- if (fSmartActionItem == null)
- return;
- Control c= getControl();
- if (c == null || c.isDisposed())
- return;
-
- fSmartActionItem.setVisible(visible);
- ToolBarManager tbm= CompareViewerPane.getToolBarManager(c.getParent());
- if (tbm != null) {
- tbm.update(true);
- ToolBar tb= tbm.getControl();
- if (!tb.isDisposed())
- tb.getParent().layout(true);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewerCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewerCreator.java
deleted file mode 100644
index bf367eda..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaStructureDiffViewerCreator.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IViewerCreator;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * A factory object for the <code>JavaStructureDiffViewer</code>.
- * This indirection is necessary because only objects with a default
- * constructor can be created via an extension point
- * (this precludes Viewers).
- */
-public class JavaStructureDiffViewerCreator implements IViewerCreator {
-
- public Viewer createViewer(Composite parent, CompareConfiguration cc) {
- return new JavaStructureDiffViewer(parent, cc);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextBufferNode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextBufferNode.java
deleted file mode 100644
index 8c107528..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextBufferNode.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-import org.eclipse.compare.HistoryItem;
-import org.eclipse.compare.IEncodedStreamContentAccessor;
-import org.eclipse.compare.IResourceProvider;
-import org.eclipse.compare.ITypedElement;
-import org.eclipse.compare.ResourceNode;
-import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFileState;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Implements the IStreamContentAccessor and ITypedElement protocols
- * for a TextBuffer.
- */
-class JavaTextBufferNode implements ITypedElement, IEncodedStreamContentAccessor, IResourceProvider {
-
- private IFile fFile;
- private IDocument fDocument;
- private boolean fInEditor;
-
- JavaTextBufferNode(IFile file, IDocument document, boolean inEditor) {
- fFile= file;
- fDocument= document;
- fInEditor= inEditor;
- }
-
- public String getName() {
- if (fInEditor)
- return CompareMessages.Editor_Buffer;
- return CompareMessages.Workspace_File;
- }
-
- public String getType() {
- return "java"; //$NON-NLS-1$
- }
-
- public Image getImage() {
- return null;
- }
-
- public InputStream getContents() {
- return new ByteArrayInputStream(JavaCompareUtilities.getBytes(fDocument.get(), "UTF-16")); //$NON-NLS-1$
- }
-
- public String getCharset() {
- return "UTF-16"; //$NON-NLS-1$
- }
-
- public IResource getResource() {
- return fFile;
- }
-
- static final ITypedElement[] buildEditions(ITypedElement target, IFile file) {
-
- // setup array of editions
- IFileState[] states= null;
- // add available editions
- try {
- states= file.getHistory(null);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- }
-
- int count= 1;
- if (states != null)
- count+= states.length;
-
- ITypedElement[] editions= new ITypedElement[count];
- editions[0]= new ResourceNode(file);
- if (states != null)
- for (int i= 0; i < states.length; i++)
- editions[i+1]= new HistoryItem(target, states[i]);
- return editions;
- }
-
- /**
- * Returns the corresponding place holder type for the given element.
- * @return a place holder type (see ASTRewrite) or -1 if there is no corresponding placeholder
- */
- static final int getPlaceHolderType(ITypedElement element) {
-
- if (element instanceof DocumentRangeNode) {
- JavaNode jn= (JavaNode) element;
- switch (jn.getTypeCode()) {
-
- case JavaNode.PACKAGE:
- return ASTNode.PACKAGE_DECLARATION;
-
- case JavaNode.CLASS:
- case JavaNode.INTERFACE:
- return ASTNode.TYPE_DECLARATION;
-
-
- case JavaNode.CONSTRUCTOR:
- case JavaNode.METHOD:
- return ASTNode.FUNCTION_DECLARATION;
-
- case JavaNode.FIELD:
- return ASTNode.FIELD_DECLARATION;
-
- case JavaNode.INIT:
- return ASTNode.INITIALIZER;
-
- case JavaNode.IMPORT:
- case JavaNode.IMPORT_CONTAINER:
- return ASTNode.IMPORT_DECLARATION;
-
- case JavaNode.CU:
- return ASTNode.JAVASCRIPT_UNIT;
- }
- }
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewer.java
deleted file mode 100644
index 29e26579..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewer.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.IStreamContentAccessor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class JavaTextViewer extends Viewer {
-
- private SourceViewer fSourceViewer;
- private Object fInput;
-
-
- JavaTextViewer(Composite parent) {
- fSourceViewer= new SourceViewer(parent, null, SWT.LEFT_TO_RIGHT | SWT.H_SCROLL | SWT.V_SCROLL);
- JavaScriptTextTools tools= JavaCompareUtilities.getJavaTextTools();
- if (tools != null) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSourceViewer.configure(new JavaScriptSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING));
- }
-
- fSourceViewer.setEditable(false);
-
- String symbolicFontName= JavaMergeViewer.class.getName();
- Font font= JFaceResources.getFont(symbolicFontName);
- if (font != null)
- fSourceViewer.getTextWidget().setFont(font);
-
- }
-
- public Control getControl() {
- return fSourceViewer.getControl();
- }
-
- public void setInput(Object input) {
- if (input instanceof IStreamContentAccessor) {
- Document document= new Document(getString(input));
- JavaCompareUtilities.setupDocument(document);
- fSourceViewer.setDocument(document);
- }
- fInput= input;
- }
-
- public Object getInput() {
- return fInput;
- }
-
- public ISelection getSelection() {
- return null;
- }
-
- public void setSelection(ISelection s, boolean reveal) {
- }
-
- public void refresh() {
- }
-
- /**
- * A helper method to retrieve the contents of the given object
- * if it implements the IStreamContentAccessor interface.
- */
- private static String getString(Object input) {
-
- if (input instanceof IStreamContentAccessor) {
- IStreamContentAccessor sca= (IStreamContentAccessor) input;
- try {
- return JavaCompareUtilities.readString(sca);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewerCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewerCreator.java
deleted file mode 100644
index 2f2b98a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTextViewerCreator.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IViewerCreator;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Composite;
-
-
-/**
- * A factory object for the <code>JavaTextViewer</code>.
- * This indirection is necessary because only objects with a default
- * constructor can be created via an extension point
- * (this precludes Viewers).
- */
-public class JavaTextViewerCreator implements IViewerCreator {
-
- public Viewer createViewer(Composite parent, CompareConfiguration mp) {
- return new JavaTextViewer(parent);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java
deleted file mode 100644
index 340fb536..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.contentmergeviewer.ITokenComparator;
-import org.eclipse.compare.rangedifferencer.IRangeComparator;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-
-
-/**
- * A comparator for Java tokens.
- */
-public class JavaTokenComparator implements ITokenComparator {
-
- /**
- * Factory to create text token comparators.
- * This is a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=183224 .
- */
- public static interface ITokenComparatorFactory {
- /**
- * @param text text to be tokenized
- * @return a token comparator
- */
- public ITokenComparator createTokenComparator(String text);
- }
-
- private static final boolean DEBUG= false;
-
- private final String fText;
- private final ITokenComparatorFactory fTextTokenComparatorFactory;
- private int fCount;
- private int[] fStarts;
- private int[] fLengths;
-
- /**
- * Creates a token comparator for the given string.
- *
- * @param text the text to be tokenized
- */
- public JavaTokenComparator(String text) {
- this(text, null);
- }
-
- /**
- * Creates a token comparator for the given string.
- *
- * @param text the text to be tokenized
- * @param textTokenComparatorFactory a factory to create text token comparators
- */
- public JavaTokenComparator(String text, ITokenComparatorFactory textTokenComparatorFactory) {
-
- fTextTokenComparatorFactory= textTokenComparatorFactory;
- Assert.isLegal(text != null);
-
- fText= text;
-
- int length= fText.length();
- fStarts= new int[length];
- fLengths= new int[length];
- fCount= 0;
-
- IScanner scanner= ToolFactory.createScanner(true, true, false, false); // returns comments & whitespace
- scanner.setSource(fText.toCharArray());
- int endPos= 0;
- try {
- int tokenType;
- while ((tokenType= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) {
- int start= scanner.getCurrentTokenStartPosition();
- int end= scanner.getCurrentTokenEndPosition()+1;
- // Comments are treated as a single token (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=78063)
- if (TokenScanner.isComment(tokenType) || tokenType == ITerminalSymbols.TokenNameStringLiteral) {
- int dl= fTextTokenComparatorFactory == null ? getCommentStartTokenLength(tokenType) : 0;
- recordTokenRange(start, dl);
- parseText(start + dl, text.substring(start + dl, end));
- } else {
- recordTokenRange(start, end - start);
- }
- endPos= end;
- }
- } catch (InvalidInputException ex) {
- // We couldn't parse part of the input. Fall through and make the rest a single token
- }
- // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=13907
- if (endPos < length) {
- recordTokenRange(endPos, length - endPos);
- }
- }
-
- /**
- * Records the given token range.
- *
- * @param start of the token
- * @param length length of the token
- *
- */
- private void recordTokenRange(int start, int length) {
- fStarts[fCount]= start;
- fLengths[fCount]= length;
- fCount++;
- if (DEBUG)
- System.out.println(fText.substring(start, start + length));
- }
-
- private void parseText(int start, String text) {
- ITokenComparator subTokenizer= fTextTokenComparatorFactory == null
- ? new JavaTokenComparator(text)
- : fTextTokenComparatorFactory.createTokenComparator(text);
- int count= subTokenizer.getRangeCount();
- for (int i= 0; i < count; i++) {
- int subStart= subTokenizer.getTokenStart(i);
- int subLength= subTokenizer.getTokenLength(i);
- recordTokenRange(start + subStart, subLength);
- }
- }
-
- /**
- * Returns the length of the token that
- * initiates the given comment type.
- *
- * @param tokenType
- * @return the length of the token that start a comment
- *
- */
- private static int getCommentStartTokenLength(int tokenType) {
- if (tokenType == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) {
- return 3;
- } else if (tokenType == ITerminalSymbols.TokenNameStringLiteral) {
- return 1;
- } else {
- return 2;
- }
- }
-
- /**
- * Returns the number of tokens in the string.
- *
- * @return number of token in the string
- */
- public int getRangeCount() {
- return fCount;
- }
-
- /* (non Javadoc)
- * see ITokenComparator.getTokenStart
- */
- public int getTokenStart(int index) {
- if (index >= 0 && index < fCount)
- return fStarts[index];
- if (fCount > 0)
- return fStarts[fCount-1] + fLengths[fCount-1];
- return 0;
- }
-
- /* (non Javadoc)
- * see ITokenComparator.getTokenLength
- */
- public int getTokenLength(int index) {
- if (index < fCount)
- return fLengths[index];
- return 0;
- }
-
- /**
- * Returns <code>true</code> if a token given by the first index
- * matches a token specified by the other <code>IRangeComparator</code> and index.
- *
- * @param thisIndex the number of the token within this range comparator
- * @param other the range comparator to compare this with
- * @param otherIndex the number of the token within the other comparator
- * @return <code>true</code> if the token are equal
- */
- public boolean rangesEqual(int thisIndex, IRangeComparator other, int otherIndex) {
- if (other != null && getClass() == other.getClass()) {
- JavaTokenComparator tc= (JavaTokenComparator) other; // safe cast
- int thisLen= getTokenLength(thisIndex);
- int otherLen= tc.getTokenLength(otherIndex);
- if (thisLen == otherLen)
- return fText.regionMatches(false, getTokenStart(thisIndex), tc.fText, tc.getTokenStart(otherIndex), thisLen);
- }
- return false;
- }
-
- /**
- * Aborts the comparison if the number of tokens is too large.
- *
- * @param length a number on which to base the decision whether to return
- * <code>true</code> or <code>false</code>
- * @param maxLength another number on which to base the decision whether to return
- * <code>true</code> or <code>false</code>
- * @param other the other <code>IRangeComparator</code> to compare with
- * @return <code>true</code> to abort a token comparison
- */
- public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) {
-
- if (getRangeCount() < 50 || other.getRangeCount() < 50)
- return false;
-
- if (maxLength < 100)
- return false;
-
- if (length < 100)
- return false;
-
- if (maxLength > 800)
- return true;
-
- if (length < maxLength / 4)
- return false;
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/LocalHistoryActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/LocalHistoryActionGroup.java
deleted file mode 100644
index a6463736..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/LocalHistoryActionGroup.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-
-public class LocalHistoryActionGroup extends ActionGroup {
-
- private String fGroupName;
-
- private JavaHistoryAction fCompareWith;
- private JavaHistoryAction fReplaceWithPrevious;
- private JavaHistoryAction fReplaceWith;
- private JavaHistoryAction fAddFrom;
-
- public LocalHistoryActionGroup(CompilationUnitEditor editor, String groupName) {
- Assert.isNotNull(groupName);
- fGroupName= groupName;
- fCompareWith= new JavaCompareWithEditionAction();
- fCompareWith.init(editor,
- CompareMessages.LocalHistoryActionGroup_action_compare_with,
- CompareMessages.LocalHistoryActionGroup_action_compare_with_title,
- CompareMessages.LocalHistoryActionGroup_action_compare_with_message);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fCompareWith, IJavaHelpContextIds.COMPARE_WITH_HISTORY_ACTION);
-
- fReplaceWithPrevious= new JavaReplaceWithPreviousEditionAction();
- fReplaceWithPrevious.init(editor,
- CompareMessages.LocalHistoryActionGroup_action_replace_with_previous,
- CompareMessages.LocalHistoryActionGroup_action_replace_with_previous_title,
- CompareMessages.LocalHistoryActionGroup_action_replace_with_previous_message);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fReplaceWithPrevious, IJavaHelpContextIds.REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION);
-
- fReplaceWith= new JavaReplaceWithEditionAction();
- fReplaceWith.init(editor,
- CompareMessages.LocalHistoryActionGroup_action_replace_with,
- CompareMessages.LocalHistoryActionGroup_action_replace_with_title,
- CompareMessages.LocalHistoryActionGroup_action_replace_with_message);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fReplaceWith, IJavaHelpContextIds.REPLACE_WITH_HISTORY_ACTION);
-
- fAddFrom= new JavaAddElementFromHistory();
- fAddFrom.init(editor,
- CompareMessages.LocalHistoryActionGroup_action_add,
- CompareMessages.LocalHistoryActionGroup_action_add_title,
- CompareMessages.LocalHistoryActionGroup_action_add_message);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fAddFrom, IJavaHelpContextIds.ADD_FROM_HISTORY_ACTION);
- }
-
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- IMenuManager localMenu= new MenuManager(CompareMessages.LocalHistoryActionGroup_menu_local_history);
- int added= 0;
- added+= addAction(localMenu, fCompareWith);
- added+= addAction(localMenu, fReplaceWithPrevious);
- added+= addAction(localMenu, fReplaceWith);
- added+= addAction(localMenu, fAddFrom);
- if (added > 0)
- menu.appendToGroup(fGroupName, localMenu);
- }
-
- private int addAction(IMenuManager menu, JavaHistoryAction action) {
- action.update();
- if (action.isEnabled()) {
- menu.add(action);
- return 1;
- }
- return 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties
deleted file mode 100644
index 911b6d20..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties
+++ /dev/null
@@ -1,33 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-title= Replace JavaScript Element from Local History
-width= 800
-height= 600
-
-treeTitleFormat= Local History of ''{0}''
-
-treeFormat= {0}
-workspaceTreeFormat= {0} (Workspace File)
-parseErrorFormat= {0} (Parsing Error; No Structured Replace Available)
-
-editionLabel= Local History ({0})
-workspaceEditionLabel= Workspace File
-
-targetLabel= {0}
-
-todayFormat= Today ({0})
-yesterdayFormat= Yesterday ({0})
-dayFormat= {0}
-
-buttonLabel= Replace
-
-notFoundInLocalHistoryMessage= No differing versions of selected JavaScript element found in local history.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ResizableDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ResizableDialog.java
deleted file mode 100644
index 2bb0bb69..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ResizableDialog.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.compare.CompareUI;
-import org.eclipse.jface.dialogs.DialogSettings;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.TrayDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Shell;
-
-/**
- * Base class for resizable Dialogs with persistent window bounds.
- */
-public abstract class ResizableDialog extends TrayDialog {
-
- // dialog store id constants
- private final static String DIALOG_BOUNDS_KEY= "ResizableDialogBounds"; //$NON-NLS-1$
- private static final String X= "x"; //$NON-NLS-1$
- private static final String Y= "y"; //$NON-NLS-1$
- private static final String WIDTH= "width"; //$NON-NLS-1$
- private static final String HEIGHT= "height"; //$NON-NLS-1$
-
- protected ResourceBundle fBundle;
- private Rectangle fNewBounds;
- private IDialogSettings fSettings;
-
- public ResizableDialog(Shell parent, ResourceBundle bundle) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX);
-
- fBundle= bundle;
-
- fSettings= CompareUI.getPlugin().getDialogSettings();
- }
-
- protected Point getInitialSize() {
-
- int width= 0;
- int height= 0;
-
- final Shell s= getShell();
- if (s != null) {
- s.addControlListener(
- new ControlListener() {
- public void controlMoved(ControlEvent arg0) {
- fNewBounds= s.getBounds();
- }
- public void controlResized(ControlEvent arg0) {
- fNewBounds= s.getBounds();
- }
- }
- );
- }
-
- IDialogSettings bounds= fSettings.getSection(DIALOG_BOUNDS_KEY);
- if (bounds == null) {
- if (fBundle != null) {
- width= JavaCompareUtilities.getInteger(fBundle, WIDTH, 0);
- height= JavaCompareUtilities.getInteger(fBundle, HEIGHT, 0);
- Shell shell= getParentShell();
- if (shell != null) {
- Point parentSize= shell.getSize();
- if (width <= 0)
- width= parentSize.x-300;
- if (height <= 0)
- height= parentSize.y-200;
- }
- } else {
- Shell shell= getParentShell();
- if (shell != null) {
- Point parentSize= shell.getSize();
- width= parentSize.x-100;
- height= parentSize.y-100;
- }
- }
- if (width < 700)
- width= 700;
- if (height < 500)
- height= 500;
- } else {
- try {
- width= bounds.getInt(WIDTH);
- } catch (NumberFormatException e) {
- width= 700;
- }
- try {
- height= bounds.getInt(HEIGHT);
- } catch (NumberFormatException e) {
- height= 500;
- }
- }
-
- return new Point(width, height);
- }
-
- protected Point getInitialLocation(Point initialSize) {
- Point loc= super.getInitialLocation(initialSize);
-
- IDialogSettings bounds= fSettings.getSection(DIALOG_BOUNDS_KEY);
- if (bounds != null) {
- try {
- loc.x= bounds.getInt(X);
- } catch (NumberFormatException e) {
- // silently ignored
- }
- try {
- loc.y= bounds.getInt(Y);
- } catch (NumberFormatException e) {
- // silently ignored
- }
- }
- return loc;
- }
-
- public boolean close() {
- boolean closed= super.close();
- if (closed && fNewBounds != null)
- saveBounds(fNewBounds);
- return closed;
- }
-
- private void saveBounds(Rectangle bounds) {
- IDialogSettings dialogBounds= fSettings.getSection(DIALOG_BOUNDS_KEY);
- if (dialogBounds == null) {
- dialogBounds= new DialogSettings(DIALOG_BOUNDS_KEY);
- fSettings.addSection(dialogBounds);
- }
- dialogBounds.put(X, bounds.x);
- dialogBounds.put(Y, bounds.y);
- dialogBounds.put(WIDTH, bounds.width);
- dialogBounds.put(HEIGHT, bounds.height);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/TextMergeViewerCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/TextMergeViewerCreator.java
deleted file mode 100644
index bd3bebf7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/TextMergeViewerCreator.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.compare;
-
-import org.eclipse.compare.CompareConfiguration;
-import org.eclipse.compare.IViewerCreator;
-import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * A factory object for the <code>TextMergeViewer</code>.
- * This indirection is necessary because only objects with a default
- * constructor can be created via an extension point
- * (this precludes Viewers).
- */
-public class TextMergeViewerCreator implements IViewerCreator {
-
- public Viewer createViewer(Composite parent, CompareConfiguration mp) {
- return new TextMergeViewer(parent, mp);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.java
deleted file mode 100644
index abf8ae66..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- *
- */
-public class DialogsMessages extends NLS {
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.dialogs.DialogsMessages"; //$NON-NLS-1$
- private DialogsMessages() {
- }
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, DialogsMessages.class);
- }
- public static String SortMembersMessageDialog_dialog_title;
- public static String SortMembersMessageDialog_description;
- public static String SortMembersMessageDialog_link_tooltip;
- public static String SortMembersMessageDialog_do_not_sort_fields_label;
- public static String SortMembersMessageDialog_sort_all_label;
- public static String SortMembersMessageDialog_sort_warning_label;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties
deleted file mode 100644
index 8684258e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties
+++ /dev/null
@@ -1,18 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-# Sebastian Davids <sdavids@gmx.de> - Bug 114276
-###############################################################################
-
-SortMembersMessageDialog_dialog_title=Sort Members
-SortMembersMessageDialog_description=The order of the sort may be configured on the <a>Members Sort Order</a> preference page.
-SortMembersMessageDialog_link_tooltip=Show the members sort order preferences.
-SortMembersMessageDialog_do_not_sort_fields_label=Do not sort vars and initializers
-SortMembersMessageDialog_sort_all_label=&Sort all members
-SortMembersMessageDialog_sort_warning_label=Reordering of vars and initializers can result in semantic and runtime changes due to different initialization and persistence order.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java
deleted file mode 100644
index ebc14a0d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java
+++ /dev/null
@@ -1,1650 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.IJobManager;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.XMLMemento;
-import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.dialogs.SearchPattern;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor;
-import org.eclipse.wst.jsdt.core.search.TypeNameRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeInfoRequestorAdapter;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.TypeFilterPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.OwnerDrawSupport;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstallType;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.launching.LibraryLocation;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoImageProvider;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-
-/**
- * Shows a list of Java types to the user with a text entry field for a string
- * pattern used to filter the list of types.
- *
- *
- */
-public class FilteredTypesSelectionDialog extends FilteredItemsSelectionDialog implements ITypeSelectionComponent {
-
- /**
- * Disabled "Show Container for Duplicates because of
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=184693 .
- */
- private static final boolean BUG_184693= true;
-
- private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog"; //$NON-NLS-1$
-
- private static final String SHOW_CONTAINER_FOR_DUPLICATES= "ShowContainerForDuplicates"; //$NON-NLS-1$
-
- private static final String WORKINGS_SET_SETTINGS= "WorkingSet"; //$NON-NLS-1$
-
- private WorkingSetFilterActionGroup fFilterActionGroup;
-
- private final TypeItemLabelProvider fTypeInfoLabelProvider;
-
- private String fTitle;
-
- private ShowContainerForDuplicatesAction fShowContainerForDuplicatesAction;
-
- private IJavaScriptSearchScope fSearchScope;
-
- private boolean fAllowScopeSwitching;
-
- private final int fElementKinds;
-
- private final ITypeInfoFilterExtension fFilterExtension;
-
- private final TypeSelectionExtension fExtension;
-
- private ISelectionStatusValidator fValidator;
-
- private final TypeInfoUtil fTypeInfoUtil;
-
- private static boolean fgFirstTime= true;
-
- private final TypeItemsComparator fTypeItemsComparator;
-
- private int fTypeFilterVersion= 0;
-
- /**
- * Creates new FilteredTypesSelectionDialog instance
- *
- * @param parent
- * shell to parent the dialog on
- * @param multi
- * <code>true</code> if multiple selection is allowed
- * @param context
- * context used to execute long-running operations associated
- * with this dialog
- * @param scope
- * scope used when searching for types
- * @param elementKinds
- * flags defining nature of searched elements; the only valid
- * values are: <code>IJavaScriptSearchConstants.TYPE</code>
- * <code>IJavaScriptSearchConstants.ANNOTATION_TYPE</code>
- * <code>IJavaScriptSearchConstants.INTERFACE</code>
- * <code>IJavaScriptSearchConstants.ENUM</code>
- * <code>IJavaScriptSearchConstants.CLASS_AND_INTERFACE</code>
- * <code>IJavaScriptSearchConstants.CLASS_AND_ENUM</code>.
- * Please note that the bitwise OR combination of the elementary
- * constants is not supported.
- */
- public FilteredTypesSelectionDialog(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds) {
- this(parent, multi, context, scope, elementKinds, null);
- }
-
- /**
- * Creates new FilteredTypesSelectionDialog instance.
- *
- * @param shell
- * shell to parent the dialog on
- * @param multi
- * <code>true</code> if multiple selection is allowed
- * @param context
- * context used to execute long-running operations associated
- * with this dialog
- * @param scope
- * scope used when searching for types. If the scope is <code>null</code>,
- * then workspace is scope is used as default, and the user can
- * choose a working set as scope.
- * @param elementKinds
- * flags defining nature of searched elements; the only valid
- * values are: <code>IJavaScriptSearchConstants.TYPE</code>
- * <code>IJavaScriptSearchConstants.ANNOTATION_TYPE</code>
- * <code>IJavaScriptSearchConstants.INTERFACE</code>
- * <code>IJavaScriptSearchConstants.ENUM</code>
- * <code>IJavaScriptSearchConstants.CLASS_AND_INTERFACE</code>
- * <code>IJavaScriptSearchConstants.CLASS_AND_ENUM</code>.
- * Please note that the bitwise OR combination of the elementary
- * constants is not supported.
- * @param extension
- * an extension of the standard type selection dialog; See
- * {@link TypeSelectionExtension}
- */
- public FilteredTypesSelectionDialog(Shell shell, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
- super(shell, multi);
-
- setSelectionHistory(new TypeSelectionHistory());
-
- if (scope == null) {
- fAllowScopeSwitching= true;
- scope= SearchEngine.createWorkspaceScope();
- }
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.TYPE_SELECTION_DIALOG2);
-
- fElementKinds= elementKinds;
- fExtension= extension;
- fFilterExtension= (extension == null) ? null : extension.getFilterExtension();
- fSearchScope= scope;
-
- if (extension != null) {
- fValidator= extension.getSelectionValidator();
- }
-
- fTypeInfoUtil= new TypeInfoUtil(extension != null ? extension.getImageProvider() : null);
-
- fTypeInfoLabelProvider= new TypeItemLabelProvider();
-
- setListLabelProvider(fTypeInfoLabelProvider);
- setListSelectionLabelDecorator(fTypeInfoLabelProvider);
- setDetailsLabelProvider(new TypeItemDetailsLabelProvider(fTypeInfoUtil));
-
- fTypeItemsComparator= new TypeItemsComparator();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SelectionDialog#setTitle(java.lang.String)
- */
- public void setTitle(String title) {
- super.setTitle(title);
- fTitle= title;
- }
-
- /**
- * Adds or replaces subtitle of the dialog
- *
- * @param text
- * the new subtitle for this dialog
- */
- private void setSubtitle(String text) {
- if (text == null || text.length() == 0) {
- getShell().setText(fTitle);
- } else {
- getShell().setText(Messages.format(JavaUIMessages.FilteredTypeSelectionDialog_titleFormat, new String[] { fTitle, text }));
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.AbstractSearchDialog#getDialogSettings()
- */
- protected IDialogSettings getDialogSettings() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS);
-
- if (settings == null) {
- settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS);
- }
-
- return settings;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.AbstractSearchDialog#storeDialog(org.eclipse.jface.dialogs.IDialogSettings)
- */
- protected void storeDialog(IDialogSettings settings) {
- super.storeDialog(settings);
-
- if (! BUG_184693) {
- settings.put(SHOW_CONTAINER_FOR_DUPLICATES, fShowContainerForDuplicatesAction.isChecked());
- }
-
- if (fFilterActionGroup != null) {
- XMLMemento memento= XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$
- fFilterActionGroup.saveState(memento);
- fFilterActionGroup.dispose();
- StringWriter writer= new StringWriter();
- try {
- memento.save(writer);
- settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString());
- } catch (IOException e) {
- // don't do anything. Simply don't store the settings
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.AbstractSearchDialog#restoreDialog(org.eclipse.jface.dialogs.IDialogSettings)
- */
- protected void restoreDialog(IDialogSettings settings) {
- super.restoreDialog(settings);
-
- if (! BUG_184693) {
- boolean showContainer= settings.getBoolean(SHOW_CONTAINER_FOR_DUPLICATES);
- fShowContainerForDuplicatesAction.setChecked(showContainer);
- fTypeInfoLabelProvider.setContainerInfo(showContainer);
- } else {
- fTypeInfoLabelProvider.setContainerInfo(true);
- }
-
- if (fAllowScopeSwitching) {
- String setting= settings.get(WORKINGS_SET_SETTINGS);
- if (setting != null) {
- try {
- IMemento memento= XMLMemento.createReadRoot(new StringReader(setting));
- fFilterActionGroup.restoreState(memento);
- } catch (WorkbenchException e) {
- // don't do anything. Simply don't restore the settings
- JavaScriptPlugin.log(e);
- }
- }
- IWorkingSet ws= fFilterActionGroup.getWorkingSet();
- if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
- setSearchScope(SearchEngine.createWorkspaceScope());
- setSubtitle(null);
- } else {
- setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true));
- setSubtitle(ws.getLabel());
- }
- }
-
- // TypeNameMatch[] types = OpenTypeHistory.getInstance().getTypeInfos();
- //
- // for (int i = 0; i < types.length; i++) {
- // TypeNameMatch type = types[i];
- // accessedHistoryItem(type);
- // }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.AbstractSearchDialog#fillViewMenu(org.eclipse.jface.action.IMenuManager)
- */
- protected void fillViewMenu(IMenuManager menuManager) {
- super.fillViewMenu(menuManager);
-
- if (! BUG_184693) {
- fShowContainerForDuplicatesAction= new ShowContainerForDuplicatesAction();
- menuManager.add(fShowContainerForDuplicatesAction);
- }
- if (fAllowScopeSwitching) {
- fFilterActionGroup= new WorkingSetFilterActionGroup(getShell(), JavaScriptPlugin.getActivePage(), new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- IWorkingSet ws= (IWorkingSet) event.getNewValue();
- if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
- setSearchScope(SearchEngine.createWorkspaceScope());
- setSubtitle(null);
- } else {
- setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true));
- setSubtitle(ws.getLabel());
- }
-
- applyFilter();
- }
- });
- fFilterActionGroup.fillViewMenu(menuManager);
- }
-
- menuManager.add(new Separator());
- menuManager.add(new TypeFiltersPreferencesAction());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createExtendedContentArea(Composite parent) {
- Control addition= null;
-
- if (fExtension != null) {
-
- addition= fExtension.createContentArea(parent);
- if (addition != null) {
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- addition.setLayoutData(gd);
-
- }
-
- fExtension.initialize(this);
- }
-
- return addition;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SelectionDialog#setResult(java.util.List)
- */
- protected void setResult(List newResult) {
-
- List resultToReturn= new ArrayList();
-
- for (int i= 0; i < newResult.size(); i++) {
- if (newResult.get(i) instanceof TypeNameMatch) {
- IType type= ((TypeNameMatch) newResult.get(i)).getType();
- if (type.exists()) {
- // items are added to history in the
- // org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#computeResult()
- // method
- resultToReturn.add(type);
- } else {
- TypeNameMatch typeInfo= (TypeNameMatch) newResult.get(i);
- IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot();
- String containerName= JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED);
- String message= Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName });
- MessageDialog.openError(getShell(), fTitle, message);
- getSelectionHistory().remove(typeInfo);
- }
- }
- }
-
- super.setResult(resultToReturn);
- }
-
- /*
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#create()
- */
- public void create() {
- super.create();
- Control patternControl= getPatternControl();
- if (patternControl instanceof Text) {
- TextFieldNavigationHandler.install((Text) patternControl);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.window.Window#open()
- */
- public int open() {
- if (getInitialPattern() == null) {
- IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (window != null) {
- ISelection selection= window.getSelectionService().getSelection();
- if (selection instanceof ITextSelection) {
- String text= ((ITextSelection) selection).getText();
- if (text != null) {
- text= text.trim();
- if (text.length() > 0 && JavaScriptConventions.validateJavaScriptTypeName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3).isOK()) {
- setInitialPattern(text, FULL_SELECTION);
- }
- }
- }
- }
- }
- return super.open();
- }
-
- /**
- * Sets a new validator.
- *
- * @param validator
- * the new validator
- */
- public void setValidator(ISelectionStatusValidator validator) {
- fValidator= validator;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter()
- */
- protected ItemsFilter createFilter() {
- return new TypeItemsFilter(fSearchScope, fElementKinds, fFilterExtension);
- }
-
- protected Control createContents(Composite parent) {
- Control contents= super.createContents(parent);
- if (ColoredViewersManager.showColoredLabels()) {
- if (contents instanceof Composite) {
- Table listControl= findTableControl((Composite) contents);
- if (listControl != null) {
- installOwnerDraw(listControl);
- }
- }
- }
- return contents;
- }
-
- private void installOwnerDraw(Table tableControl) {
- new OwnerDrawSupport(tableControl) { // installs the owner draw listeners
- public ColoredString getColoredLabel(Item item) {
- String text= item.getText();
- ColoredString str= new ColoredString(text);
- int index= text.indexOf('-');
- if (index != -1) {
- str.colorize(index, str.length() - index, ColoredJavaElementLabels.QUALIFIER_STYLE);
- }
- return str;
- }
-
- public Color getColor(String foregroundColorName, Display display) {
- return PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry().get(foregroundColorName);
- }
- };
- }
-
- private Table findTableControl(Composite composite) {
- Control[] children= composite.getChildren();
- for (int i= 0; i < children.length; i++) {
- Control curr= children[i];
- if (curr instanceof Table) {
- return (Table) curr;
- } else if (curr instanceof Composite) {
- Table res= findTableControl((Composite) curr);
- if (res != null) {
- return res;
- }
- }
- }
- return null;
- }
-
-
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider,
- * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter,
- * org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void fillContentProvider(AbstractContentProvider provider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException {
- TypeItemsFilter typeSearchFilter= (TypeItemsFilter) itemsFilter;
- TypeSearchRequestor requestor= new TypeSearchRequestor(provider, typeSearchFilter);
- SearchEngine engine= new SearchEngine((WorkingCopyOwner) null);
- String packPattern= typeSearchFilter.getPackagePattern();
- progressMonitor.setTaskName(JavaUIMessages.FilteredTypesSelectionDialog_searchJob_taskName);
-
- /*
- * Setting the filter into match everything mode avoids filtering twice
- * by the same pattern (the search engine only provides filtered
- * matches). For the case when the pattern is a camel case pattern with
- * a terminator, the filter is not set to match everything mode because
- * jdt.core's SearchPattern does not support that case.
- */
- String typePattern= itemsFilter.getPattern();
- int matchRule= typeSearchFilter.getMatchRule();
- if (matchRule == SearchPattern.RULE_CAMELCASE_MATCH) {
- // If the pattern is empty, the RULE_BLANK_MATCH will be chosen, so we don't have to check the pattern length
- char lastChar= typePattern.charAt(typePattern.length() - 1);
-
- if (lastChar == '<' || lastChar == ' ') {
- typePattern= typePattern.substring(0, typePattern.length() - 1);
- } else {
- typeSearchFilter.setMatchEverythingMode(true);
- }
- } else {
- typeSearchFilter.setMatchEverythingMode(true);
- }
-
- try {
- engine.searchAllTypeNames(packPattern == null ? null : packPattern.toCharArray(),
- typeSearchFilter.getPackageFlags(), //TODO: https://bugs.eclipse.org/bugs/show_bug.cgi?id=176017
- typePattern.toCharArray(),
- matchRule, //TODO: https://bugs.eclipse.org/bugs/show_bug.cgi?id=176017
- typeSearchFilter.getElementKind(),
- typeSearchFilter.getSearchScope(),
- requestor,
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- progressMonitor);
- } finally {
- typeSearchFilter.setMatchEverythingMode(false);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator()
- */
- protected Comparator getItemsComparator() {
- return fTypeItemsComparator;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java.lang.Object)
- */
- public String getElementName(Object item) {
- TypeNameMatch type= (TypeNameMatch) item;
- return fTypeInfoUtil.getText(type);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java.lang.Object)
- */
- protected IStatus validateItem(Object item) {
-
- if (item == null)
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, "", null); //$NON-NLS-1$
-
- if (fValidator != null) {
- IType type= ((TypeNameMatch) item).getType();
- if (!type.exists())
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_error_type_doesnot_exist, ((TypeNameMatch) item).getFullyQualifiedName()), null);
- Object[] elements= { type };
- return fValidator.validate(elements);
- } else
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- /**
- * Sets search scope used when searching for types.
- *
- * @param scope
- * the new scope
- */
- private void setSearchScope(IJavaScriptSearchScope scope) {
- fSearchScope= scope;
- }
-
- /*
- * We only have to ensure history consistency here since the search engine
- * takes care of working copies.
- */
- private static class ConsistencyRunnable implements IRunnableWithProgress {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- if (fgFirstTime) {
- // Join the initialize after load job.
- IJobManager manager= Job.getJobManager();
- manager.join(JavaScriptUI.ID_PLUGIN, monitor);
- }
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- if (fgFirstTime || history.isEmpty()) {
- if (history.needConsistencyCheck()) {
- monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100);
- refreshSearchIndices(new SubProgressMonitor(monitor, 90));
- history.checkConsistency(new SubProgressMonitor(monitor, 10));
- } else {
- refreshSearchIndices(monitor);
- }
- monitor.done();
- fgFirstTime= false;
- } else {
- history.checkConsistency(monitor);
- }
- }
- public static boolean needsExecution() {
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- return fgFirstTime || history.isEmpty() || history.needConsistencyCheck();
- }
- private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- new SearchEngine().searchAllTypeNames(
- null,
- 0,
- // make sure we search a concrete name. This is faster according to Kent
- "_______________".toCharArray(), //$NON-NLS-1$
- SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_CASE_SENSITIVE,
- IJavaScriptSearchConstants.ENUM,
- SearchEngine.createWorkspaceScope(),
- new TypeNameRequestor() {},
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- monitor);
- } catch (JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- }
- }
- }
-
- /*
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#reloadCache(boolean, org.eclipse.core.runtime.IProgressMonitor)
- */
- public void reloadCache(boolean checkDuplicates, IProgressMonitor monitor) {
- IProgressMonitor remainingMonitor;
- if (ConsistencyRunnable.needsExecution()) {
- monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 10);
- try {
- ConsistencyRunnable runnable= new ConsistencyRunnable();
- runnable.run(new SubProgressMonitor(monitor, 1));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, JavaUIMessages.TypeSelectionDialog_error3Title, JavaUIMessages.TypeSelectionDialog_error3Message);
- close();
- return;
- } catch (InterruptedException e) {
- // cancelled by user
- close();
- return;
- }
- remainingMonitor= new SubProgressMonitor(monitor, 9);
- } else {
- remainingMonitor= monitor;
- }
- super.reloadCache(checkDuplicates, remainingMonitor);
- monitor.done();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent#triggerSearch()
- */
- public void triggerSearch() {
- fTypeFilterVersion++;
- applyFilter();
- }
-
- /**
- * The <code>ShowContainerForDuplicatesAction</code> provides means to
- * show/hide container information for duplicate elements.
- */
- private class ShowContainerForDuplicatesAction extends Action {
-
- /**
- * Creates a new instance of the class
- */
- public ShowContainerForDuplicatesAction() {
- super(JavaUIMessages.FilteredTypeSelectionDialog_showContainerForDuplicatesAction, IAction.AS_CHECK_BOX);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- fTypeInfoLabelProvider.setContainerInfo(isChecked());
- }
- }
-
- private class TypeFiltersPreferencesAction extends Action {
-
- public TypeFiltersPreferencesAction() {
- super(JavaUIMessages.FilteredTypesSelectionDialog_TypeFiltersPreferencesAction_label);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- String typeFilterID= TypeFilterPreferencePage.TYPE_FILTER_PREF_PAGE_ID;
- PreferencesUtil.createPreferenceDialogOn(getShell(), typeFilterID, new String[] { typeFilterID }, null).open();
- triggerSearch();
- }
- }
-
- /**
- * A <code>LabelProvider</code> for (the table of) types.
- */
- private class TypeItemLabelProvider extends LabelProvider implements ILabelDecorator {
-
- private boolean fContainerInfo;
-
-
- /**
- * Construct a new <code>TypeItemLabelProvider</code>. F
- */
- public TypeItemLabelProvider() {
-
- }
-
- public void setContainerInfo(boolean containerInfo) {
- fContainerInfo= containerInfo;
- fireLabelProviderChanged(new LabelProviderChangedEvent(this));
- }
-
- private boolean isInnerType(TypeNameMatch match) {
- return match.getTypeQualifiedName().indexOf('.') != -1;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- if (!(element instanceof TypeNameMatch)) {
- return super.getImage(element);
- }
-
- TypeNameMatch type= (TypeNameMatch) element;
-
- ImageDescriptor iD= JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false);
-
- return JavaScriptPlugin.getImageDescriptorRegistry().get(iD);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (!(element instanceof TypeNameMatch)) {
- return super.getText(element);
- }
-
- if (fContainerInfo && isDuplicateElement(element)) {
- return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element);
- }
-
- if (!fContainerInfo && isDuplicateElement(element)) {
- return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element);
- }
-
- return fTypeInfoUtil.getText(element);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.ILabelDecorator#decorateImage(org.eclipse.swt.graphics.Image,
- * java.lang.Object)
- */
- public Image decorateImage(Image image, Object element) {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.ILabelDecorator#decorateText(java.lang.String,
- * java.lang.Object)
- */
- public String decorateText(String text, Object element) {
- if (!(element instanceof TypeNameMatch)) {
- return null;
- }
-
- if (fContainerInfo && isDuplicateElement(element)) {
- return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element);
- }
-
- return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element);
- }
-
- }
-
- /**
- * A <code>LabelProvider</code> for the label showing type details.
- */
- private static class TypeItemDetailsLabelProvider extends LabelProvider {
-
- private final TypeNameMatchLabelProvider fLabelProvider= new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeNameMatchLabelProvider.SHOW_ROOT_POSTFIX);
-
- private final TypeInfoUtil fTypeInfoUtil;
-
- public TypeItemDetailsLabelProvider(TypeInfoUtil typeInfoUtil) {
- fTypeInfoUtil= typeInfoUtil;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- if (element instanceof TypeNameMatch) {
- return fLabelProvider.getImage((element));
- }
-
- return super.getImage(element);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (element instanceof TypeNameMatch) {
- return fTypeInfoUtil.getQualificationText((TypeNameMatch) element);
- }
-
- return super.getText(element);
- }
- }
-
- private static class TypeInfoUtil {
-
- private final ITypeInfoImageProvider fProviderExtension;
-
- private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter();
-
- private final Map fLib2Name= new HashMap();
-
- private final String[] fInstallLocations;
-
- private final String[] fVMNames;
-
- private boolean fFullyQualifyDuplicates;
-
- public TypeInfoUtil(ITypeInfoImageProvider extension) {
- fProviderExtension= extension;
- List locations= new ArrayList();
- List labels= new ArrayList();
- IVMInstallType[] installs= JavaRuntime.getVMInstallTypes();
- for (int i= 0; i < installs.length; i++) {
- processVMInstallType(installs[i], locations, labels);
- }
- fInstallLocations= (String[]) locations.toArray(new String[locations.size()]);
- fVMNames= (String[]) labels.toArray(new String[labels.size()]);
-
- }
-
- public void setFullyQualifyDuplicates(boolean value) {
- fFullyQualifyDuplicates= value;
- }
-
- private void processVMInstallType(IVMInstallType installType, List locations, List labels) {
- if (installType != null) {
- IVMInstall[] installs= installType.getVMInstalls();
- boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS());
- final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$
- for (int i= 0; i < installs.length; i++) {
- String label= getFormattedLabel(installs[i].getName());
- LibraryLocation[] libLocations= installs[i].getLibraryLocations();
- if (libLocations != null) {
- processLibraryLocation(libLocations, label);
- } else {
- String filePath= installs[i].getInstallLocation().getAbsolutePath();
- // on MacOS X install locations end in an additional
- // "/Home" segment; remove it
- if (isMac && filePath.endsWith(HOME_SUFFIX))
- filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1);
- locations.add(filePath);
- labels.add(label);
- }
- }
- }
- }
-
- private void processLibraryLocation(LibraryLocation[] libLocations, String label) {
- for (int l= 0; l < libLocations.length; l++) {
- LibraryLocation location= libLocations[l];
- fLib2Name.put(location.getSystemLibraryPath().toOSString(), label);
- }
- }
-
- private String getFormattedLabel(String name) {
- return Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, name);
- }
-
- public String getText(Object element) {
-
- return ((TypeNameMatch) element).getQualifiedName();
- }
-
- public String getQualifiedText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- result.append(type.getQualifiedName());
- String containerName= type.getTypeContainerName();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- if (containerName.length() > 0) {
- result.append(containerName);
- } else {
- result.append(JavaUIMessages.FilteredTypesSelectionDialog_default_package);
- }
- return result.toString();
- }
-
- public String getFullyQualifiedText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- result.append(type.getSimpleTypeName());
- String containerName= type.getTypeContainerName();
- if (containerName.length() > 0) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(containerName);
- }
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(type));
- return result.toString();
- }
-
- public String getText(TypeNameMatch last, TypeNameMatch current, TypeNameMatch next) {
- StringBuffer result= new StringBuffer();
- int qualifications= 0;
- String currentTN= current.getSimpleTypeName();
- result.append(currentTN);
- String currentTCN= getTypeContainerName(current);
- if (last != null) {
- String lastTN= last.getSimpleTypeName();
- String lastTCN= getTypeContainerName(last);
- if (currentTCN.equals(lastTCN)) {
- if (currentTN.equals(lastTN)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- return result.toString();
- }
- } else if (currentTN.equals(lastTN)) {
- qualifications= 1;
- }
- }
- if (next != null) {
- String nextTN= next.getSimpleTypeName();
- String nextTCN= getTypeContainerName(next);
- if (currentTCN.equals(nextTCN)) {
- if (currentTN.equals(nextTN)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- return result.toString();
- }
- } else if (currentTN.equals(nextTN)) {
- qualifications= 1;
- }
- }
- if (qualifications > 0) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- if (fFullyQualifyDuplicates) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- }
- }
- return result.toString();
- }
-
- public String getQualificationText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- String containerName= type.getTypeContainerName();
- if (containerName.length() > 0) {
- result.append(containerName);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- }
- result.append(getContainerName(type));
- return result.toString();
- }
-
- private boolean isInnerType(TypeNameMatch match) {
- return match.getTypeQualifiedName().indexOf('.') != -1;
- }
-
- public ImageDescriptor getImageDescriptor(Object element) {
- TypeNameMatch type= (TypeNameMatch) element;
- if (fProviderExtension != null) {
- fAdapter.setMatch(type);
- ImageDescriptor descriptor= fProviderExtension.getImageDescriptor(fAdapter);
- if (descriptor != null)
- return descriptor;
- }
- return JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false);
- }
-
- private String getTypeContainerName(TypeNameMatch info) {
- String result= info.getTypeContainerName();
- if (result.length() > 0)
- return result;
- return JavaUIMessages.FilteredTypesSelectionDialog_default_package;
- }
-
- private String getContainerName(TypeNameMatch type) {
- IPackageFragmentRoot root= type.getPackageFragmentRoot();
- if (root.isExternal()) {
- String name= root.getPath().toOSString();
- for (int i= 0; i < fInstallLocations.length; i++) {
- if (name.startsWith(fInstallLocations[i])) {
- return fVMNames[i];
- }
- }
- String lib= (String) fLib2Name.get(name);
- if (lib != null)
- return lib;
- }
- StringBuffer buf= new StringBuffer();
- JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf);
- return buf.toString();
- }
- }
-
- /**
- * Filters types using pattern, scope, element kind and filter extension.
- */
- private class TypeItemsFilter extends ItemsFilter {
-
- private final IJavaScriptSearchScope fScope;
-
- private final boolean fIsWorkspaceScope;
-
- private final int fElemKind;
-
- private final ITypeInfoFilterExtension fFilterExt;
-
- private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter();
-
- private SearchPattern fPackageMatcher;
-
- private boolean fMatchEverything= false;
-
- private final int fMyTypeFilterVersion= fTypeFilterVersion;
-
- /**
- * Creates instance of TypeItemsFilter
- *
- * @param scope
- * @param elementKind
- * @param extension
- */
- public TypeItemsFilter(IJavaScriptSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) {
- super(new TypeSearchPattern());
- fScope= scope;
- fIsWorkspaceScope= scope == null ? false : scope.equals(SearchEngine.createWorkspaceScope());
- fElemKind= elementKind;
- fFilterExt= extension;
- String stringPackage= ((TypeSearchPattern) patternMatcher).getPackagePattern();
- if (stringPackage != null) {
- fPackageMatcher= new SearchPattern();
- fPackageMatcher.setPattern(stringPackage);
- } else {
- fPackageMatcher= null;
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isSubFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter)
- */
- public boolean isSubFilter(ItemsFilter filter) {
- if (!super.isSubFilter(filter))
- return false;
- TypeItemsFilter typeItemsFilter= (TypeItemsFilter) filter;
- if (fScope != typeItemsFilter.getSearchScope())
- return false;
- if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion())
- return false;
- return getPattern().indexOf('.', filter.getPattern().length()) == -1;
- }
-
- public boolean equalsFilter(ItemsFilter iFilter) {
- if (!super.equalsFilter(iFilter))
- return false;
- if (!(iFilter instanceof TypeItemsFilter))
- return false;
- TypeItemsFilter typeItemsFilter= (TypeItemsFilter) iFilter;
- if (fScope != typeItemsFilter.getSearchScope())
- return false;
- if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion())
- return false;
- return true;
- }
-
- public int getElementKind() {
- return fElemKind;
- }
-
- public ITypeInfoFilterExtension getFilterExtension() {
- return fFilterExt;
- }
-
- public IJavaScriptSearchScope getSearchScope() {
- return fScope;
- }
-
- public int getMyTypeFilterVersion() {
- return fMyTypeFilterVersion;
- }
-
- public String getPackagePattern() {
- if (fPackageMatcher == null)
- return null;
- return fPackageMatcher.getPattern();
- }
-
- public int getPackageFlags() {
- if (fPackageMatcher == null)
- return SearchPattern.RULE_PREFIX_MATCH;
-
- return fPackageMatcher.getMatchRule();
- }
-
- public boolean matchesRawNamePattern(TypeNameMatch type) {
- return Strings.startsWithIgnoreCase(type.getSimpleTypeName(), getPattern());
- }
-
- public boolean matchesCachedResult(TypeNameMatch type) {
- if (!(matchesPackage(type) && matchesFilterExtension(type)))
- return false;
- return matchesName(type);
- }
-
- public boolean matchesHistoryElement(TypeNameMatch type) {
- if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type)))
- return false;
- return matchesName(type);
- }
-
- public boolean matchesFilterExtension(TypeNameMatch type) {
- if (fFilterExt == null)
- return true;
- fAdapter.setMatch(type);
- return fFilterExt.select(fAdapter);
- }
-
- private boolean matchesName(TypeNameMatch type) {
- return matches(type.getSimpleTypeName());
- }
-
- private boolean matchesPackage(TypeNameMatch type) {
- if (fPackageMatcher == null)
- return true;
- return fPackageMatcher.matches(type.getPackageName());
- }
-
- private boolean matchesScope(TypeNameMatch type) {
- if (fIsWorkspaceScope)
- return true;
- return fScope.encloses(type.getType());
-
- }
-
- private boolean matchesModifiers(TypeNameMatch type) {
- if (fElemKind == IJavaScriptSearchConstants.TYPE)
- return true;
- int modifiers= type.getModifiers();
- switch (fElemKind) {
- case IJavaScriptSearchConstants.CLASS:
- return modifiers == 0;
- }
- return false;
- }
-
- /**
- * Set filter to "match everything" mode.
- *
- * @param matchEverything if <code>true</code>, {@link #matchItem(Object)} always returns true.
- * If <code>false</code>, the filter is enabled.
- */
- public void setMatchEverythingMode(boolean matchEverything) {
- this.fMatchEverything= matchEverything;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isConsistentItem(java.lang.Object)
- */
- public boolean isConsistentItem(Object item) {
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchItem(java.lang.Object)
- */
- public boolean matchItem(Object item) {
-
- if (fMatchEverything)
- return true;
-
- TypeNameMatch type= (TypeNameMatch) item;
- if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type)))
- return false;
- return matchesName(type);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchesRawNamePattern(java.lang.Object)
- */
- public boolean matchesRawNamePattern(Object item) {
- TypeNameMatch type= (TypeNameMatch) item;
- return matchesRawNamePattern(type);
- }
-
- }
-
- /**
- * Extends functionality of SearchPatterns
- */
- private static class TypeSearchPattern extends SearchPattern {
-
- private String packagePattern;
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SearchPattern#setPattern(java.lang.String)
- */
- public void setPattern(String stringPattern) {
- String pattern= stringPattern;
- String packPattern= null;
- int index= stringPattern.lastIndexOf("."); //$NON-NLS-1$
- if (index != -1) {
- packPattern= evaluatePackagePattern(stringPattern.substring(0, index));
- pattern= stringPattern.substring(index + 1);
- if (pattern.length() == 0)
- pattern= "**"; //$NON-NLS-1$
- }
- super.setPattern(pattern);
- packagePattern= packPattern;
- }
-
- /*
- * Transforms o.e.j to o*.e*.j*
- */
- private String evaluatePackagePattern(String s) {
- StringBuffer buf= new StringBuffer();
- boolean hasWildCard= false;
- for (int i= 0; i < s.length(); i++) {
- char ch= s.charAt(i);
- if (ch == '.') {
- if (!hasWildCard) {
- buf.append('*');
- }
- hasWildCard= false;
- } else if (ch == '*' || ch == '?') {
- hasWildCard= true;
- }
- buf.append(ch);
- }
- if (!hasWildCard) {
- buf.append('*');
- }
- return buf.toString();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SearchPattern#isNameCharAllowed(char)
- */
- protected boolean isNameCharAllowed(char nameChar) {
- return super.isNameCharAllowed(nameChar);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SearchPattern#isPatternCharAllowed(char)
- */
- protected boolean isPatternCharAllowed(char patternChar) {
- return super.isPatternCharAllowed(patternChar);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SearchPattern#isValidCamelCaseChar(char)
- */
- protected boolean isValidCamelCaseChar(char ch) {
- return super.isValidCamelCaseChar(ch);
- }
-
- /**
- * @return the packagePattern
- */
- public String getPackagePattern() {
- return packagePattern;
- }
-
- }
-
- /**
- * A <code>TypeSearchRequestor</code> collects matches filtered using
- * <code>TypeItemsFilter</code>. The attached content provider is filled
- * on the basis of the collected entries (instances of
- * <code>TypeNameMatch</code>).
- */
- private static class TypeSearchRequestor extends TypeNameMatchRequestor {
- private volatile boolean fStop;
-
- private final AbstractContentProvider fContentProvider;
-
- private final TypeItemsFilter fTypeItemsFilter;
-
- public TypeSearchRequestor(AbstractContentProvider contentProvider, TypeItemsFilter typeItemsFilter) {
- super();
- fContentProvider= contentProvider;
- fTypeItemsFilter= typeItemsFilter;
- }
-
- public void cancel() {
- fStop= true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch)
- */
- public void acceptTypeNameMatch(TypeNameMatch match) {
- if (fStop)
- return;
- if (TypeFilter.isFiltered(match))
- return;
- if (fTypeItemsFilter.matchesFilterExtension(match))
- fContentProvider.add(match, fTypeItemsFilter);
- }
-
- }
-
- /**
- * Compares TypeItems is used during sorting
- */
- private static class TypeItemsComparator implements Comparator {
-
- private final Map fLib2Name= new HashMap();
-
- private final String[] fInstallLocations;
-
- private final String[] fVMNames;
-
- /**
- * Creates new instance of TypeItemsComparator
- */
- public TypeItemsComparator() {
- List locations= new ArrayList();
- List labels= new ArrayList();
- IVMInstallType[] installs= JavaRuntime.getVMInstallTypes();
- for (int i= 0; i < installs.length; i++) {
- processVMInstallType(installs[i], locations, labels);
- }
- fInstallLocations= (String[]) locations.toArray(new String[locations.size()]);
- fVMNames= (String[]) labels.toArray(new String[labels.size()]);
- }
-
- private void processVMInstallType(IVMInstallType installType, List locations, List labels) {
- if (installType != null) {
- IVMInstall[] installs= installType.getVMInstalls();
- boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS());
- final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$
- for (int i= 0; i < installs.length; i++) {
- String label= getFormattedLabel(installs[i].getName());
- LibraryLocation[] libLocations= installs[i].getLibraryLocations();
- if (libLocations != null) {
- processLibraryLocation(libLocations, label);
- } else {
- String filePath= installs[i].getInstallLocation().getAbsolutePath();
- // on MacOS X install locations end in an additional
- // "/Home" segment; remove it
- if (isMac && filePath.endsWith(HOME_SUFFIX))
- filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1);
- locations.add(filePath);
- labels.add(label);
- }
- }
- }
- }
-
- private void processLibraryLocation(LibraryLocation[] libLocations, String label) {
- for (int l= 0; l < libLocations.length; l++) {
- LibraryLocation location= libLocations[l];
- fLib2Name.put(location.getSystemLibraryPath().toString(), label);
- }
- }
-
- private String getFormattedLabel(String name) {
- return MessageFormat.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, new Object[] { name });
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- */
- public int compare(Object left, Object right) {
-
- TypeNameMatch leftInfo= (TypeNameMatch) left;
- TypeNameMatch rightInfo= (TypeNameMatch) right;
-
- int result= compareName(leftInfo.getSimpleTypeName(), rightInfo.getSimpleTypeName());
- if (result != 0)
- return result;
- result= compareTypeContainerName(leftInfo.getTypeContainerName(), rightInfo.getTypeContainerName());
- if (result != 0)
- return result;
-
- int leftCategory= getElementTypeCategory(leftInfo);
- int rightCategory= getElementTypeCategory(rightInfo);
- if (leftCategory < rightCategory)
- return -1;
- if (leftCategory > rightCategory)
- return +1;
- return compareContainerName(leftInfo, rightInfo);
- }
-
- private int compareName(String leftString, String rightString) {
- int result= leftString.compareToIgnoreCase(rightString);
- if (result != 0 || rightString.length() == 0) {
- return result;
- } else if (Strings.isLowerCase(leftString.charAt(0)) && !Strings.isLowerCase(rightString.charAt(0))) {
- return +1;
- } else if (Strings.isLowerCase(rightString.charAt(0)) && !Strings.isLowerCase(leftString.charAt(0))) {
- return -1;
- } else {
- return leftString.compareTo(rightString);
- }
- }
-
- private int compareTypeContainerName(String leftString, String rightString) {
- int leftLength= leftString.length();
- int rightLength= rightString.length();
- if (leftLength == 0 && rightLength > 0)
- return -1;
- if (leftLength == 0 && rightLength == 0)
- return 0;
- if (leftLength > 0 && rightLength == 0)
- return +1;
- return compareName(leftString, rightString);
- }
-
- private int compareContainerName(TypeNameMatch leftType, TypeNameMatch rightType) {
- return getContainerName(leftType).compareTo(getContainerName(rightType));
- }
-
- private String getContainerName(TypeNameMatch type) {
- IPackageFragmentRoot root= type.getPackageFragmentRoot();
- if (root.isExternal()) {
- String name= root.getPath().toOSString();
- for (int i= 0; i < fInstallLocations.length; i++) {
- if (name.startsWith(fInstallLocations[i])) {
- return fVMNames[i];
- }
- }
- String lib= (String) fLib2Name.get(name);
- if (lib != null)
- return lib;
- }
- StringBuffer buf= new StringBuffer();
- JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf);
- return buf.toString();
- }
-
- private int getElementTypeCategory(TypeNameMatch type) {
- try {
- if (type.getPackageFragmentRoot().getKind() == IPackageFragmentRoot.K_SOURCE)
- return 0;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return 1;
- }
- }
-
- /**
- * Extends the <code>SelectionHistory</code>, providing support for
- * <code>OpenTypeHistory</code>.
- */
- protected class TypeSelectionHistory extends SelectionHistory {
-
- /**
- * Creates new instance of TypeSelectionHistory
- */
-
- public TypeSelectionHistory() {
- super();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#accessed(java.lang.Object)
- */
- public synchronized void accessed(Object object) {
- super.accessed(object);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#remove(java.lang.Object)
- */
- public synchronized boolean remove(Object element) {
- OpenTypeHistory.getInstance().remove((TypeNameMatch) element);
- return super.remove(element);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#load(org.eclipse.ui.IMemento)
- */
- public void load(IMemento memento) {
- TypeNameMatch[] types= OpenTypeHistory.getInstance().getTypeInfos();
-
- for (int i= 0; i < types.length; i++) {
- TypeNameMatch type= types[i];
- accessed(type);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#save(org.eclipse.ui.IMemento)
- */
- public void save(IMemento memento) {
- persistHistory();
- }
-
- /**
- * Stores contents of the local history into persistent history
- * container.
- */
- private synchronized void persistHistory() {
- if (getReturnCode() == OK) {
- Object[] items= getHistoryItems();
- for (int i= 0; i < items.length; i++) {
- OpenTypeHistory.getInstance().accessed((TypeNameMatch) items[i]);
- }
- }
- }
-
- protected Object restoreItemFromMemento(IMemento element) {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#storeItemToMemento(java.lang.Object,
- * org.eclipse.ui.IMemento)
- */
- protected void storeItemToMemento(Object item, IMemento element) {
-
- }
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/ListDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/ListDialog.java
deleted file mode 100644
index f36cba88..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/ListDialog.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.dialogs.SelectionDialog;
-
-public class ListDialog extends SelectionDialog {
-
- private IStructuredContentProvider fContentProvider;
- private ILabelProvider fLabelProvider;
- private Object fInput;
- private TableViewer fTableViewer;
- private boolean fAddCancelButton;
- private final int fShellStyle;
-
- public ListDialog(Shell parent, int shellStyle) {
- super(parent);
- fAddCancelButton= false;
- fShellStyle= shellStyle;
- }
-
- public void setInput(Object input) {
- fInput= input;
- }
-
- public void setContentProvider(IStructuredContentProvider sp){
- fContentProvider= sp;
- }
-
- public void setLabelProvider(ILabelProvider lp){
- fLabelProvider= lp;
- }
-
- public void setAddCancelButton(boolean addCancelButton) {
- fAddCancelButton= addCancelButton;
- }
-
- public TableViewer getTableViewer(){
- return fTableViewer;
- }
-
- public boolean hasFilters(){
- return fTableViewer.getFilters() != null && fTableViewer.getFilters().length != 0;
- }
-
- public void create() {
- setShellStyle(fShellStyle);
- super.create();
- }
-
- protected Label createMessageArea(Composite composite) {
- Label label = new Label(composite,SWT.WRAP);
- label.setText(getMessage());
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(55);
- label.setLayoutData(gd);
- applyDialogFont(label);
- return label;
- }
-
- protected Control createDialogArea(Composite container) {
- Composite parent= (Composite) super.createDialogArea(container);
- createMessageArea(parent);
- fTableViewer= new TableViewer(parent, getTableStyle());
- fTableViewer.setContentProvider(fContentProvider);
- Table table= fTableViewer.getTable();
- fTableViewer.setLabelProvider(fLabelProvider);
- fTableViewer.setInput(fInput);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(55);
- gd.heightHint= convertHeightInCharsToPixels(15);
- table.setLayoutData(gd);
- applyDialogFont(parent);
- return parent;
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- if (! fAddCancelButton)
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- else
- super.createButtonsForButtonBar(parent);
- }
-
- protected int getTableStyle() {
- return SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/MultiElementListSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/MultiElementListSelectionDialog.java
deleted file mode 100644
index 68d8870d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/MultiElementListSelectionDialog.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog;
-import org.eclipse.ui.dialogs.FilteredList;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-
-/**
- * A class to select elements out of a list of elements, organized on multiple
- * pages.
- */
-public class MultiElementListSelectionDialog extends AbstractElementListSelectionDialog {
-
- private static class Page {
- private Object[] elements;
- public String filter;
- public boolean okState= false;
-
- public Page(Object[] elements) {
- this.elements= elements;
- }
- }
-
- private Page[] fPages;
- private int fCurrentPage;
- private int fNumberOfPages;
-
- private Button fFinishButton;
- private Button fBackButton;
- private Button fNextButton;
-
- private Label fPageInfoLabel;
- private String fPageInfoMessage= JavaUIMessages.MultiElementListSelectionDialog_pageInfoMessage;
- private Comparator fComparator;
-
- /**
- * Constructs a multi-page list selection dialog.
- * @param parent The parent shell
- * @param renderer the label renderer.
- */
- public MultiElementListSelectionDialog(Shell parent, ILabelProvider renderer) {
- super(parent, renderer);
- }
-
- /**
- * Sets message shown in the right top corner. Use {0} and {1} as placeholders
- * for the current and the total number of pages.
- * @param message the message.
- */
- public void setPageInfoMessage(String message) {
- fPageInfoMessage= message;
- }
-
- /**
- * Sets the elements to be displayed in the dialog.
- * @param elements an array of pages holding arrays of elements
- */
- public void setElements(Object[][] elements) {
- fNumberOfPages= elements.length;
- fPages= new Page[fNumberOfPages];
- for (int i= 0; i != fNumberOfPages; i++)
- fPages[i]= new Page(elements[i]);
-
- initializeResult(fNumberOfPages);
- }
-
- /*
- * @see Window#open()
- */
- public int open() {
- List selection= getInitialElementSelections();
- if (selection == null || selection.size() != fNumberOfPages) {
- setInitialSelections(new Object[fNumberOfPages]);
- selection= getInitialElementSelections();
- }
-
- Assert.isTrue(selection.size() == fNumberOfPages);
-
- return super.open();
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite contents= (Composite) super.createDialogArea(parent);
-
- createMessageArea(contents);
- createFilterText(contents);
- createFilteredList(contents);
-
- fCurrentPage= 0;
- setPageData();
-
- applyDialogFont(contents);
- return contents;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(Composite)
- */
- protected void createButtonsForButtonBar(Composite parent) {
- fBackButton= createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, false);
- fNextButton= createButton(parent, IDialogConstants.NEXT_ID, IDialogConstants.NEXT_LABEL, true);
- fFinishButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.FINISH_LABEL, false);
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
- }
-
- /*
- * @see org.eclipse.ui.dialogs.SelectionDialog#createMessageArea(Composite)
- */
- protected Label createMessageArea(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.horizontalSpacing= 5;
- layout.numColumns= 2;
- composite.setLayout(layout);
-
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- composite.setLayoutData(data);
-
- Label messageLabel= super.createMessageArea(composite);
-
- fPageInfoLabel= new Label(composite, SWT.NULL);
- fPageInfoLabel.setText(getPageInfoMessage());
-
- data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- data.horizontalAlignment= GridData.END;
- fPageInfoLabel.setLayoutData(data);
- applyDialogFont(messageLabel);
- return messageLabel;
- }
-
- /*
- * @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult()
- */
- protected void computeResult() {
- setResult(fCurrentPage, getSelectedElements());
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
- */
- protected void buttonPressed(int buttonId) {
- if (buttonId == IDialogConstants.BACK_ID) {
- turnPage(false);
- } else if (buttonId == IDialogConstants.NEXT_ID) {
- turnPage(true);
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- /**
- * @see AbstractElementListSelectionDialog#handleDefaultSelected()
- */
- protected void handleDefaultSelected() {
- if (validateCurrentSelection()) {
- if (fCurrentPage == fNumberOfPages - 1) {
- buttonPressed(IDialogConstants.OK_ID);
- } else {
- buttonPressed(IDialogConstants.NEXT_ID);
- }
- }
- }
-
- /**
- * @see AbstractElementListSelectionDialog#updateButtonsEnableState(IStatus)
- */
- protected void updateButtonsEnableState(IStatus status) {
- boolean isOK= !status.matches(IStatus.ERROR);
- fPages[fCurrentPage].okState= isOK;
-
- boolean isAllOK= isOK;
- for (int i= 0; i != fNumberOfPages; i++)
- isAllOK = isAllOK && fPages[i].okState;
-
- fFinishButton.setEnabled(isAllOK);
-
- boolean nextButtonEnabled= isOK && (fCurrentPage < fNumberOfPages - 1);
-
- fNextButton.setEnabled(nextButtonEnabled);
- fBackButton.setEnabled(fCurrentPage != 0);
-
- if (nextButtonEnabled) {
- getShell().setDefaultButton(fNextButton);
- } else if (isAllOK) {
- getShell().setDefaultButton(fFinishButton);
- }
- }
-
- private void turnPage(boolean toNextPage) {
- Page page= fPages[fCurrentPage];
-
- // store filter
- String filter= getFilter();
- if (filter == null)
- filter= ""; //$NON-NLS-1$
- page.filter= filter;
-
- // store selection
- Object[] selectedElements= getSelectedElements();
- List list= getInitialElementSelections();
- list.set(fCurrentPage, selectedElements);
-
- // store result
- setResult(fCurrentPage, getSelectedElements());
-
- if (toNextPage) {
- if (fCurrentPage + 1 >= fNumberOfPages)
- return;
-
- fCurrentPage++;
- } else {
- if (fCurrentPage - 1 < 0)
- return;
-
- fCurrentPage--;
- }
-
- if (fPageInfoLabel != null && !fPageInfoLabel.isDisposed())
- fPageInfoLabel.setText(getPageInfoMessage());
-
- setPageData();
-
- validateCurrentSelection();
- }
-
- private void setPageData() {
- Page page= fPages[fCurrentPage];
-
- // 1. set elements
- setListElements(page.elements);
-
- // 2. apply filter
- String filter= page.filter;
- if (filter == null)
- filter= ""; //$NON-NLS-1$
- setFilter(filter);
-
- // 3. select elements
- Object[] selectedElements= (Object[]) getInitialElementSelections().get(fCurrentPage);
- setSelection(selectedElements);
- fFilteredList.setFocus();
- }
-
- private String getPageInfoMessage() {
- if (fPageInfoMessage == null)
- return ""; //$NON-NLS-1$
-
- String[] args= new String[] { Integer.toString(fCurrentPage + 1), Integer.toString(fNumberOfPages) };
- return Messages.format(fPageInfoMessage, args);
- }
-
- private void initializeResult(int length) {
- List result= new ArrayList(length);
- for (int i= 0; i != length; i++)
- result.add(null);
-
- setResult(result);
- }
-
- /**
- * Gets the current Page.
- * @return Returns a int
- */
- public int getCurrentPage() {
- return fCurrentPage;
- }
-
- /**
- * Set the <code>Comparator</code> used to sort
- * the elements in the List.
- *
- * @param comparator the comparator to use, not null.
- */
- public void setComparator(Comparator comparator) {
- fComparator= comparator;
- if (fFilteredList != null)
- fFilteredList.setComparator(fComparator);
- }
-
- /**
- * {@inheritDoc}
- */
- protected FilteredList createFilteredList(Composite parent) {
- FilteredList filteredList= super.createFilteredList(parent);
- if (fComparator != null) {
- filteredList.setComparator(fComparator);
- }
- return filteredList;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog.java
deleted file mode 100644
index 7a849eed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-
-/**
- * A type selection dialog used for opening types.
- */
-public class OpenTypeSelectionDialog extends FilteredTypesSelectionDialog {
-
- private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.OpenTypeSelectionDialog2"; //$NON-NLS-1$
-
- public OpenTypeSelectionDialog(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds) {
- this(parent, multi, context, scope, elementKinds, null);
- }
-
- public OpenTypeSelectionDialog(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
- super(parent, multi, context, scope, elementKinds, extension);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.SelectionStatusDialog#configureShell(org.eclipse.swt.widgets.Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.OPEN_TYPE_DIALOG);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog#getDialogSettings()
- */
- protected IDialogSettings getDialogSettings() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS);
-
- if (settings == null) {
- settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS);
- }
-
- return settings;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog2.java
deleted file mode 100644
index 53af66f1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OpenTypeSelectionDialog2.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.DialogSettings;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-
-/**
- * @deprecated use {@link OpenTypeSelectionDialog}
- */
-public class OpenTypeSelectionDialog2 extends TypeSelectionDialog2 {
-
- private IDialogSettings fSettings;
- private Point fLocation;
- private Point fSize;
-
- private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.OpenTypeSelectionDialog2"; //$NON-NLS-1$
- private static final String WIDTH= "width"; //$NON-NLS-1$
- private static final String HEIGHT= "height"; //$NON-NLS-1$
-
- public OpenTypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds) {
- this(parent, multi, context, scope, elementKinds, null);
- }
-
- public OpenTypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context,
- IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
- super(parent, multi, context, scope, elementKinds, extension);
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- fSettings= settings.getSection(DIALOG_SETTINGS);
- if (fSettings == null) {
- fSettings= new DialogSettings(DIALOG_SETTINGS);
- settings.addSection(fSettings);
- fSettings.put(WIDTH, 480);
- fSettings.put(HEIGHT, 320);
- }
- }
-
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.OPEN_TYPE_DIALOG);
- }
-
- protected Point getInitialSize() {
- Point result= super.getInitialSize();
- if (fSize != null) {
- result.x= Math.max(result.x, fSize.x);
- result.y= Math.max(result.y, fSize.y);
- Rectangle display= getShell().getDisplay().getClientArea();
- result.x= Math.min(result.x, display.width);
- result.y= Math.min(result.y, display.height);
- }
- return result;
- }
-
- protected Point getInitialLocation(Point initialSize) {
- Point result= super.getInitialLocation(initialSize);
- if (fLocation != null) {
- result.x= fLocation.x;
- result.y= fLocation.y;
- Rectangle display= getShell().getDisplay().getClientArea();
- int xe= result.x + initialSize.x;
- if (xe > display.width) {
- result.x-= xe - display.width;
- }
- int ye= result.y + initialSize.y;
- if (ye > display.height) {
- result.y-= ye - display.height;
- }
- }
- return result;
- }
-
- protected Control createDialogArea(Composite parent) {
- readSettings();
- return super.createDialogArea(parent);
- }
-
- public boolean close() {
- writeSettings();
- return super.close();
- }
-
- /**
- * Initializes itself from the dialog settings with the same state
- * as at the previous invocation.
- */
- private void readSettings() {
- try {
- int x= fSettings.getInt("x"); //$NON-NLS-1$
- int y= fSettings.getInt("y"); //$NON-NLS-1$
- fLocation= new Point(x, y);
- } catch (NumberFormatException e) {
- fLocation= null;
- }
- try {
- int width= fSettings.getInt("width"); //$NON-NLS-1$
- int height= fSettings.getInt("height"); //$NON-NLS-1$
- fSize= new Point(width, height);
-
- } catch (NumberFormatException e) {
- fSize= null;
- }
- }
-
- /**
- * Stores it current configuration in the dialog store.
- */
- private void writeSettings() {
- Point location= getShell().getLocation();
- fSettings.put("x", location.x); //$NON-NLS-1$
- fSettings.put("y", location.y); //$NON-NLS-1$
-
- Point size= getShell().getSize();
- fSettings.put("width", size.x); //$NON-NLS-1$
- fSettings.put("height", size.y); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OptionalMessageDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OptionalMessageDialog.java
deleted file mode 100644
index 4feb5a04..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OptionalMessageDialog.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-
-/**
- * This is a <code>MessageDialog</code> which allows the user
- * to choose that the dialog isn't shown again the next time.
- */
-public class OptionalMessageDialog extends MessageDialog {
-
- // String constants for widgets
- private static final String CHECKBOX_TEXT= JavaUIMessages.OptionalMessageDialog_dontShowAgain;
-
- // Dialog store id constants
- private static final String STORE_ID= "OptionalMessageDialog.hide."; //$NON-NLS-1$
-
- public static final int NOT_SHOWN= IDialogConstants.CLIENT_ID + 1;
-
- private Button fHideDialogCheckBox;
- private String fId;
-
- /**
- * Opens the dialog but only if the user hasn't choosen to hide it.
- * Returns <code>NOT_SHOWN</code> if the dialog was not shown.
- */
- public static int open(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex) {
- if (!isDialogEnabled(id))
- return OptionalMessageDialog.NOT_SHOWN;
-
- MessageDialog dialog= new OptionalMessageDialog(id, parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex);
- return dialog.open();
- }
-
- protected OptionalMessageDialog(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex) {
- super(parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex);
- fId= id;
- }
-
- protected Control createCustomArea(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- fHideDialogCheckBox= new Button(composite, SWT.CHECK | SWT.LEFT);
- fHideDialogCheckBox.setText(CHECKBOX_TEXT);
- fHideDialogCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setDialogEnabled(fId, !((Button)e.widget).getSelection());
- }
- });
- applyDialogFont(fHideDialogCheckBox);
- return fHideDialogCheckBox;
- }
-
- //--------------- Configuration handling --------------
-
- /**
- * Returns this dialog
- *
- * @return the settings to be used
- */
- private static IDialogSettings getDialogSettings() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- settings= settings.getSection(STORE_ID);
- if (settings == null)
- settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(STORE_ID);
- return settings;
- }
-
- /**
- * Answers whether the optional dialog is enabled and should be shown.
- */
- public static boolean isDialogEnabled(String key) {
- IDialogSettings settings= getDialogSettings();
- return !settings.getBoolean(key);
- }
-
- /**
- * Sets whether the optional dialog is enabled and should be shown.
- */
- public static void setDialogEnabled(String key, boolean isEnabled) {
- IDialogSettings settings= getDialogSettings();
- settings.put(key, !isEnabled);
- }
-
- /**
- * Clears all remembered information about hidden dialogs
- */
- public static void clearAllRememberedStates() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- settings.addNewSection(STORE_ID);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java
deleted file mode 100644
index e4ba5e8b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ViewerPane;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-
-public class OverrideMethodDialog extends SourceActionDialog {
-
- private static final boolean SHOW_ONLY_SUPER = true;
-
-
- private class OverrideFlatTreeAction extends Action {
-
- private boolean fToggle;
-
-
- public OverrideFlatTreeAction() {
- setToolTipText(JavaUIMessages.OverrideMethodDialog_groupMethodsByTypes);
-
- JavaPluginImages.setLocalImageDescriptors(this, "impl_co.gif"); //$NON-NLS-1$
-
- fToggle= getOverrideContentProvider().isShowTypes();
- setChecked(fToggle);
- }
-
- private OverrideMethodContentProvider getOverrideContentProvider() {
- return (OverrideMethodContentProvider) getContentProvider();
- }
-
- public void run() {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=39264
- Object[] elementList= getOverrideContentProvider().getViewer().getCheckedElements();
- fToggle= !fToggle;
- setChecked(fToggle);
- getOverrideContentProvider().setShowTypes(fToggle);
- getOverrideContentProvider().getViewer().setCheckedElements(elementList);
- }
-
- }
-
- private static class OverrideMethodContentProvider implements ITreeContentProvider {
-
- private final Object[] fEmpty= new Object[0];
-
- private IFunction[] fMethods;
-
- private IDialogSettings fSettings;
-
- private boolean fShowTypes;
-
- // private Object[] fTypes;
-
- private ContainerCheckedTreeViewer fViewer;
-
- private final String SETTINGS_SECTION= "OverrideMethodDialog"; //$NON-NLS-1$
-
- private final String SETTINGS_SHOWTYPES= "showtypes"; //$NON-NLS-1$
-
- /**
- * Constructor for OverrideMethodContentProvider.
- */
- public OverrideMethodContentProvider() {
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fSettings= dialogSettings.getSection(SETTINGS_SECTION);
- if (fSettings == null) {
- fSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
- fSettings.put(SETTINGS_SHOWTYPES, true);
- }
- fShowTypes= fSettings.getBoolean(SETTINGS_SHOWTYPES);
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof IJavaScriptUnit) {
- ArrayList result= new ArrayList(fMethods.length);
- for (int index= 0; index < fMethods.length; index++) {
- if (fMethods[index].getJavaScriptUnit() == parentElement)
- result.add(fMethods[index]);
- }
- return result.toArray();
- }
- return fEmpty;
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- return fMethods;
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- if (element instanceof IFunction) {
- return ((IFunction) element).getJavaScriptUnit();
- }
- return null;
- }
-
- public ContainerCheckedTreeViewer getViewer() {
- return fViewer;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- public void init(IFunction[] methods) {
- fMethods= methods;
- //fTypes= types;
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- fViewer= (ContainerCheckedTreeViewer) viewer;
- }
-
- public boolean isShowTypes() {
- return fShowTypes;
- }
-
- public void setShowTypes(boolean showTypes) {
- if (fShowTypes != showTypes) {
- fShowTypes= showTypes;
- fSettings.put(SETTINGS_SHOWTYPES, showTypes);
- if (fViewer != null)
- fViewer.refresh();
- }
- }
- }
-
- private static class OverrideMethodComparator extends ViewerComparator {
-
- private ITypeBinding[] fAllTypes= new ITypeBinding[0];
-
- public OverrideMethodComparator(ITypeBinding curr) {
- if (curr != null) {
- ITypeBinding[] superTypes= Bindings.getAllSuperTypes(curr);
- fAllTypes= new ITypeBinding[superTypes.length + 1];
- fAllTypes[0]= curr;
- System.arraycopy(superTypes, 0, fAllTypes, 1, superTypes.length);
- }
- }
-
- /*
- * @see ViewerSorter#compare(Viewer, Object, Object)
- */
- public int compare(Viewer viewer, Object first, Object second) {
- if (first instanceof ITypeBinding && second instanceof ITypeBinding) {
- final ITypeBinding left= (ITypeBinding) first;
- final ITypeBinding right= (ITypeBinding) second;
- if (right.getQualifiedName().equals("java.lang.Object")) //$NON-NLS-1$
- return -1;
- if (left.isEqualTo(right))
- return 0;
- if (Bindings.isSuperType(left, right))
- return +1;
- else if (Bindings.isSuperType(right, left))
- return -1;
- return 0;
- } else
- return super.compare(viewer, first, second);
- }
- }
-
- private static class OverrideMethodValidator implements ISelectionStatusValidator {
-
- private static int fNumMethods;
-
- public OverrideMethodValidator(int entries) {
- fNumMethods= entries;
- }
-
- /*
- * @see ISelectionValidator#validate(Object[])
- */
- public IStatus validate(Object[] selection) {
- int count= 0;
- for (int index= 0; index < selection.length; index++) {
- if (selection[index] instanceof IFunction)
- count++;
- }
- if (count == 0)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- return new StatusInfo(IStatus.INFO, Messages.format(JavaUIMessages.OverrideMethodDialog_selectioninfo_more, new String[] { String.valueOf(count), String.valueOf(fNumMethods)}));
- }
- }
-
- private static ITypeBinding getSuperType(final ITypeBinding binding, final String name) {
-
- if (binding.isArray() || binding.isPrimitive())
- return null;
-
- if (binding.getQualifiedName().startsWith(name))
- return binding;
-
- final ITypeBinding type= binding.getSuperclass();
- if (type != null) {
- final ITypeBinding result= getSuperType(type, name);
- if (result != null)
- return result;
- }
- return null;
- }
-
- private JavaScriptUnit fUnit= null;
-
- public OverrideMethodDialog(Shell shell, CompilationUnitEditor editor, IType type, boolean isSubType) throws JavaScriptModelException {
- super(shell, new BindingLabelProvider(), new OverrideMethodContentProvider(), editor, type, false);
-
-// IMethod[] methods = type.getMethods();
- String parentName = type.getSuperclassName();
- IType superType = type.getJavaScriptProject().findType(parentName);
- IFunction pMethods[] = superType.getFunctions();
- IFunction tMethods[] = type.getFunctions();
-
- IFunction parentMethods[] = new IFunction[0];
-
- if(OverrideMethodDialog.SHOW_ONLY_SUPER){
-
- ArrayList show = new ArrayList();
- start: for(int i = 0;pMethods!=null && i<pMethods.length;i++){
- for(int k=0;k<tMethods.length;k++){
- if(tMethods[k].getElementName().equals(pMethods[i].getElementName())){
- continue start;
- }
- }
- show.add(pMethods[i]);
-
-
- }
- parentMethods = (IFunction[]) show.toArray(new IFunction[show.size()]);
-
- }
-
-
-
- //IMethodBinding[] toImplementArray= (IMethodBinding[]) toImplement.toArray(new IMethodBinding[toImplement.size()]);
- setInitialSelections(parentMethods);
-
- HashSet expanded= new HashSet(parentMethods.length);
- for (int i= 0; i < parentMethods.length; i++) {
- expanded.add(parentMethods[i]);
- }
-
- HashSet types= new HashSet(parentMethods.length);
- for (int i= 0; i < parentMethods.length; i++) {
- types.add(parentMethods[i]);
- }
-
- IFunction[] typesArrays= (IFunction[]) types.toArray(new IFunction[types.size()]);
- OverrideMethodComparator comparator= null;//new OverrideMethodComparator(binding);
- if (expanded.isEmpty() && typesArrays.length > 0) {
- comparator.sort(null, typesArrays);
- expanded.add(typesArrays[0]);
- }
- setExpandedElements(expanded.toArray());
-
- ((OverrideMethodContentProvider) getContentProvider()).init(parentMethods);
-
- setTitle(JavaUIMessages.OverrideMethodDialog_dialog_title);
- setMessage(null);
- setValidator(new OverrideMethodValidator(parentMethods.length));
- setComparator(comparator);
- setContainerMode(true);
- setSize(60, 18);
- setInput(new Object());
- }
-
- public JavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.OVERRIDE_TREE_SELECTION_DIALOG);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog#createLinkControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP);
- link.setText(JavaUIMessages.OverrideMethodDialog_link_message);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.OVERRIDECOMMENT_ID);
- }
- });
- link.setToolTipText(JavaUIMessages.OverrideMethodDialog_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
- link.setLayoutData(gridData);
- return link;
- }
-
- /*
- * @see CheckedTreeSelectionDialog#createTreeViewer(Composite)
- */
- protected CheckboxTreeViewer createTreeViewer(Composite composite) {
- initializeDialogUnits(composite);
- ViewerPane pane= new ViewerPane(composite, SWT.BORDER | SWT.FLAT);
- pane.setText(JavaUIMessages.OverrideMethodDialog_dialog_description);
- CheckboxTreeViewer treeViewer= super.createTreeViewer(pane);
- pane.setContent(treeViewer.getControl());
- GridLayout paneLayout= new GridLayout();
- paneLayout.marginHeight= 0;
- paneLayout.marginWidth= 0;
- paneLayout.numColumns= 1;
- pane.setLayout(paneLayout);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(55);
- gd.heightHint= convertHeightInCharsToPixels(15);
- pane.setLayoutData(gd);
- ToolBarManager manager= pane.getToolBarManager();
- manager.add(new OverrideFlatTreeAction()); // create after tree is created
- manager.update(true);
- treeViewer.getTree().setFocus();
- return treeViewer;
- }
-
- public boolean hasMethodsToOverride() {
- return getContentProvider().getElements(null).length > 0;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/PackageSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/PackageSelectionDialog.java
deleted file mode 100644
index 2eeaa58f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/PackageSelectionDialog.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * Dialog to browse for package fragments.
- */
-public class PackageSelectionDialog extends ElementListSelectionDialog {
-
- public static final int F_REMOVE_DUPLICATES= 1;
- public static final int F_SHOW_PARENTS= 2;
- public static final int F_HIDE_DEFAULT_PACKAGE= 4;
- public static final int F_HIDE_EMPTY_INNER= 8;
-
-
- /** The dialog location. */
- private Point fLocation;
- /** The dialog size. */
- private Point fSize;
-
- private IRunnableContext fContext;
- private IJavaScriptSearchScope fScope;
- private int fFlags;
-
- /**
- * Creates a package selection dialog.
- * @param parent the parent shell
- * @param context the runnable context to run the search in
- * @param flags a combination of <code>F_REMOVE_DUPLICATES</code>, <code>F_SHOW_PARENTS</code>,
- * <code>F_HIDE_DEFAULT_PACKAGE</code> and <code>F_HIDE_EMPTY_INNER</code>
- * @param scope the scope defining the available packages.
- */
- public PackageSelectionDialog(Shell parent, IRunnableContext context, int flags, IJavaScriptSearchScope scope) {
- super(parent, createLabelProvider(flags));
- fFlags= flags;
- fScope= scope;
- fContext= context;
- }
-
- private static ILabelProvider createLabelProvider(int dialogFlags) {
- int flags= JavaScriptElementLabelProvider.SHOW_DEFAULT;
- if ((dialogFlags & F_REMOVE_DUPLICATES) == 0) {
- flags= flags | JavaScriptElementLabelProvider.SHOW_ROOT;
- }
- return new JavaScriptElementLabelProvider(flags);
- }
-
-
- /*
- * @see org.eclipse.jface.window.Window#open()
- */
- public int open() {
- final ArrayList packageList= new ArrayList();
-
- IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- boolean hideEmpty= (fFlags & F_HIDE_EMPTY_INNER) != 0;
- monitor.beginTask(JavaUIMessages.PackageSelectionDialog_progress_search, hideEmpty ? 2 : 1);
- try {
- SearchRequestor requestor= new SearchRequestor() {
- private HashSet fSet= new HashSet();
- private final boolean fAddDefault= (fFlags & F_HIDE_DEFAULT_PACKAGE) == 0;
- private final boolean fDuplicates= (fFlags & F_REMOVE_DUPLICATES) == 0;
- private final boolean fIncludeParents= (fFlags & F_SHOW_PARENTS) != 0;
-
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- IJavaScriptElement enclosingElement= (IJavaScriptElement) match.getElement();
- String name= enclosingElement.getElementName();
- if (fAddDefault || name.length() > 0) {
- if (fDuplicates || fSet.add(name)) {
- packageList.add(enclosingElement);
- if (fIncludeParents) {
- addParentPackages(enclosingElement, name);
- }
- }
- }
- }
-
- private void addParentPackages(IJavaScriptElement enclosingElement, String name) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) enclosingElement.getParent();
- int idx= name.lastIndexOf('.');
- while (idx != -1) {
- name= name.substring(0, idx);
- if (fDuplicates || fSet.add(name)) {
- packageList.add(root.getPackageFragment(name));
- }
- idx= name.lastIndexOf('.');
- }
- }
- };
- SearchPattern pattern= SearchPattern.createPattern("*", //$NON-NLS-1$
- IJavaScriptSearchConstants.PACKAGE, IJavaScriptSearchConstants.DECLARATIONS,
- SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);
- new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), fScope, requestor, new SubProgressMonitor(monitor, 1));
-
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
-
- if (hideEmpty) {
- removeEmptyPackages(new SubProgressMonitor(monitor, 1));
- }
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- } finally {
- monitor.done();
- }
- }
-
- private void removeEmptyPackages(IProgressMonitor monitor) throws JavaScriptModelException, InterruptedException {
- monitor.beginTask(JavaUIMessages.PackageSelectionDialog_progress_findEmpty, packageList.size());
- try {
- ArrayList res= new ArrayList(packageList.size());
- for (int i= 0; i < packageList.size(); i++) {
- IPackageFragment pkg= (IPackageFragment) packageList.get(i);
- if (pkg.hasChildren() || !pkg.hasSubpackages()) {
- res.add(pkg);
- }
- monitor.worked(1);
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
- }
- packageList.clear();
- packageList.addAll(res);
- } finally{
- monitor.done();
- }
- }
- };
-
- try {
- fContext.run(true, true, runnable);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, JavaUIMessages.PackageSelectionDialog_error_title, JavaUIMessages.PackageSelectionDialog_error3Message);
- return CANCEL;
- } catch (InterruptedException e) {
- // cancelled by user
- return CANCEL;
- }
-
- if (packageList.isEmpty()) {
- String title= JavaUIMessages.PackageSelectionDialog_nopackages_title;
- String message= JavaUIMessages.PackageSelectionDialog_nopackages_message;
- MessageDialog.openInformation(getShell(), title, message);
- return CANCEL;
- }
-
- setElements(packageList.toArray());
-
- return super.open();
- }
-
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.OPEN_PACKAGE_DIALOG);
- }
-
- /*
- * @see Window#close()
- */
- public boolean close() {
- writeSettings();
- return super.close();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- Control control= super.createContents(parent);
- readSettings();
- return control;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#getInitialSize()
- */
- protected Point getInitialSize() {
- Point result= super.getInitialSize();
- if (fSize != null) {
- result.x= Math.max(result.x, fSize.x);
- result.y= Math.max(result.y, fSize.y);
- Rectangle display= getShell().getDisplay().getClientArea();
- result.x= Math.min(result.x, display.width);
- result.y= Math.min(result.y, display.height);
- }
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point)
- */
- protected Point getInitialLocation(Point initialSize) {
- Point result= super.getInitialLocation(initialSize);
- if (fLocation != null) {
- result.x= fLocation.x;
- result.y= fLocation.y;
- Rectangle display= getShell().getDisplay().getClientArea();
- int xe= result.x + initialSize.x;
- if (xe > display.width) {
- result.x-= xe - display.width;
- }
- int ye= result.y + initialSize.y;
- if (ye > display.height) {
- result.y-= ye - display.height;
- }
- }
- return result;
- }
-
-
-
- /**
- * Initializes itself from the dialog settings with the same state
- * as at the previous invocation.
- */
- private void readSettings() {
- IDialogSettings s= getDialogSettings();
- try {
- int x= s.getInt("x"); //$NON-NLS-1$
- int y= s.getInt("y"); //$NON-NLS-1$
- fLocation= new Point(x, y);
- int width= s.getInt("width"); //$NON-NLS-1$
- int height= s.getInt("height"); //$NON-NLS-1$
- fSize= new Point(width, height);
-
- } catch (NumberFormatException e) {
- fLocation= null;
- fSize= null;
- }
- }
-
- /**
- * Stores it current configuration in the dialog store.
- */
- private void writeSettings() {
- IDialogSettings s= getDialogSettings();
-
- Point location= getShell().getLocation();
- s.put("x", location.x); //$NON-NLS-1$
- s.put("y", location.y); //$NON-NLS-1$
-
- Point size= getShell().getSize();
- s.put("width", size.x); //$NON-NLS-1$
- s.put("height", size.y); //$NON-NLS-1$
- }
-
- /**
- * Returns the dialog settings object used to share state
- * between several find/replace dialogs.
- *
- * @return the dialog settings to be used
- */
- private IDialogSettings getDialogSettings() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- String sectionName= getClass().getName();
- IDialogSettings subSettings= settings.getSection(sectionName);
- if (subSettings == null)
- subSettings= settings.addNewSection(sectionName);
- return subSettings;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SortMembersMessageDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SortMembersMessageDialog.java
deleted file mode 100644
index 8948b613..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SortMembersMessageDialog.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-
-public class SortMembersMessageDialog extends OptionalMessageDialog {
-
- private final static String OPTIONAL_ID= "SortMembersMessageDialog.optionalDialog.id"; //$NON-NLS-1$
-
- private final static String DIALOG_SETTINGS_SORT_ALL= "SortMembers.sort_all"; //$NON-NLS-1$
-
- private SelectionButtonDialogField fNotSortAllRadio;
- private SelectionButtonDialogField fSortAllRadio;
-
- private final IDialogSettings fDialogSettings;
-
- public SortMembersMessageDialog(Shell parentShell) {
- super(OPTIONAL_ID, parentShell, DialogsMessages.SortMembersMessageDialog_dialog_title, null, new String(), INFORMATION, new String[] {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
-
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- boolean isSortAll= fDialogSettings.getBoolean(DIALOG_SETTINGS_SORT_ALL);
-
- fNotSortAllRadio= new SelectionButtonDialogField(SWT.RADIO);
- fNotSortAllRadio.setLabelText(DialogsMessages.SortMembersMessageDialog_do_not_sort_fields_label);
- fNotSortAllRadio.setSelection(!isSortAll);
-
- fSortAllRadio= new SelectionButtonDialogField(SWT.RADIO);
- fSortAllRadio.setLabelText(DialogsMessages.SortMembersMessageDialog_sort_all_label);
- fSortAllRadio.setSelection(isSortAll);
- }
-
- private Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP | SWT.RIGHT);
- link.setText(DialogsMessages.SortMembersMessageDialog_description);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID);
- }
- });
- link.setToolTipText(DialogsMessages.SortMembersMessageDialog_link_tooltip);
- GridData gridData= new GridData(GridData.FILL, GridData.CENTER, true, false);
- gridData.widthHint= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);//convertWidthInCharsToPixels(60);
- link.setLayoutData(gridData);
- link.setFont(composite.getFont());
-
- return link;
- }
-
- protected void openCodeTempatePage(String id) {
- PreferencesUtil.createPreferenceDialogOn(getShell(), MembersOrderPreferencePage.PREF_ID, null, null).open();
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IconAndMessageDialog#createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- Control contents= super.createContents(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.SORT_MEMBERS_DIALOG);
- return contents;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IconAndMessageDialog#createMessageArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createMessageArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite messageComposite= new Composite(parent, SWT.NONE);
- messageComposite.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- messageComposite.setLayout(layout);
- messageComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- createLinkControl(messageComposite);
-
- int indent= convertWidthInCharsToPixels(3);
-
- fNotSortAllRadio.doFillIntoGrid(messageComposite, 1);
- LayoutUtil.setHorizontalIndent(fNotSortAllRadio.getSelectionButton(null), indent);
-
- fSortAllRadio.doFillIntoGrid(messageComposite, 1);
- LayoutUtil.setHorizontalIndent(fSortAllRadio.getSelectionButton(null), indent);
-
- final Composite warningComposite= new Composite(messageComposite, SWT.NONE);
- layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- warningComposite.setLayout(layout);
- warningComposite.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
- warningComposite.setFont(messageComposite.getFont());
-
- Image image= Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING);
- final Label imageLabel1= new Label(warningComposite, SWT.LEFT | SWT.WRAP);
- imageLabel1.setImage(image);
- imageLabel1.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label label= new Label(warningComposite, SWT.WRAP);
- label.setText(DialogsMessages.SortMembersMessageDialog_sort_warning_label);
- GridData gridData= new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- gridData.widthHint= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
- label.setLayoutData(gridData);
- label.setFont(warningComposite.getFont());
-
- fNotSortAllRadio.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- imageLabel1.setEnabled(!fNotSortAllRadio.isSelected());
- label.setEnabled(!fNotSortAllRadio.isSelected());
- }
- });
- imageLabel1.setEnabled(!fNotSortAllRadio.isSelected());
- label.setEnabled(!fNotSortAllRadio.isSelected());
-
- return messageComposite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#open()
- */
- public int open() {
- if (isDialogEnabled(OPTIONAL_ID)) {
- int res= super.open();
- if (res != Window.OK) {
- setDialogEnabled(OPTIONAL_ID, true); // don't save state on cancel
- }
- return res;
- }
- return Window.OK;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#close()
- */
- public boolean close() {
- fDialogSettings.put(DIALOG_SETTINGS_SORT_ALL, fSortAllRadio.isSelected());
- return super.close();
- }
-
-
- public boolean isNotSortingFieldsEnabled() {
- return fNotSortAllRadio.isSelected();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SourceActionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SourceActionDialog.java
deleted file mode 100644
index b4d59d5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/SourceActionDialog.java
+++ /dev/null
@@ -1,655 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.resource.StringConverter;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.CodeTemplatePreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IVisibilityChangeListener;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * An advanced version of CheckedTreeSelectionDialog with right-side button layout and
- * extra buttons and composites.
- */
-public class SourceActionDialog extends CheckedTreeSelectionDialog {
-
- protected List fInsertPositions;
- protected List fLabels;
- protected int fCurrentPositionIndex;
-
- protected IDialogSettings fSettings;
- protected CompilationUnitEditor fEditor;
- protected ITreeContentProvider fContentProvider;
- protected boolean fGenerateComment;
- protected IType fType;
- protected int fWidth, fHeight;
- protected String fCommentString;
- protected boolean fEnableInsertPosition= true;
-
- protected int fVisibilityModifier;
- protected boolean fFinal;
- protected boolean fSynchronized;
-
- protected final String SETTINGS_SECTION_METHODS= "SourceActionDialog.methods"; //$NON-NLS-1$
- protected final String SETTINGS_SECTION_CONSTRUCTORS= "SourceActionDialog.constructors"; //$NON-NLS-1$
-
- protected final String SETTINGS_INSERTPOSITION= "InsertPosition"; //$NON-NLS-1$
- protected final String SETTINGS_VISIBILITY_MODIFIER= "VisibilityModifier"; //$NON-NLS-1$
- protected final String SETTINGS_FINAL_MODIFIER= "FinalModifier"; //$NON-NLS-1$
- protected final String SETTINGS_SYNCHRONIZED_MODIFIER= "SynchronizedModifier"; //$NON-NLS-1$
- protected final String SETTINGS_COMMENTS= "Comments"; //$NON-NLS-1$
- protected Composite fInsertPositionComposite;
-
- public SourceActionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type, boolean isConstructor) throws JavaScriptModelException {
- super(parent, labelProvider, contentProvider);
- fEditor= editor;
- fContentProvider= contentProvider;
- fType= type;
- fCommentString= ActionMessages.SourceActionDialog_createMethodComment;
- setEmptyListMessage(ActionMessages.SourceActionDialog_no_entries);
-
- fWidth= 60;
- fHeight= 18;
-
- int insertionDefault= isConstructor ? 0 : 1;
- boolean generateCommentsDefault= JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject()).createComments;
-
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- String sectionId= isConstructor ? SETTINGS_SECTION_CONSTRUCTORS : SETTINGS_SECTION_METHODS;
- fSettings= dialogSettings.getSection(sectionId);
- if (fSettings == null) {
- fSettings= dialogSettings.addNewSection(sectionId);
- }
-
- fVisibilityModifier= asInt(fSettings.get(SETTINGS_VISIBILITY_MODIFIER), Modifier.PUBLIC);
- fFinal= asBoolean(fSettings.get(SETTINGS_FINAL_MODIFIER), false);
- fSynchronized= asBoolean(fSettings.get(SETTINGS_SYNCHRONIZED_MODIFIER), false);
- fCurrentPositionIndex= asInt(fSettings.get(SETTINGS_INSERTPOSITION), insertionDefault);
- fGenerateComment= asBoolean(fSettings.get(SETTINGS_COMMENTS), generateCommentsDefault);
- setupInsertPostions();
- }
-
- public void setupInsertPostions(){
- fInsertPositions= new ArrayList();
- fLabels= new ArrayList();
-
- IJavaScriptElement[] members = new IJavaScriptElement[0];
- IFunction[] methods = new IFunction[0];
- try {
- members = fType.getChildren();
- methods= fType.getFunctions();
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- fInsertPositions.add(methods.length > 0 ? methods[0]: null); // first
- fInsertPositions.add(null); // last
-
- fLabels.add(ActionMessages.SourceActionDialog_first_method);
- fLabels.add(ActionMessages.SourceActionDialog_last_method);
-
- try {
- if (hasCursorPositionElement(fEditor, members, fInsertPositions)) {
- fLabels.add(ActionMessages.SourceActionDialog_cursor);
- fCurrentPositionIndex= 2;
- } else {
- // code is needed to deal with bogus values already present in the dialog store.
- fCurrentPositionIndex= Math.max(fCurrentPositionIndex, 0);
- fCurrentPositionIndex= Math.min(fCurrentPositionIndex, 1);
- }
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- for (int i = 0; i < methods.length; i++) {
- IFunction curr= methods[i];
- String methodLabel= JavaScriptElementLabels.getElementLabel(curr, JavaScriptElementLabels.M_PARAMETER_TYPES);
- fLabels.add(Messages.format(ActionMessages.SourceActionDialog_after, methodLabel));
- try {
- fInsertPositions.add(findSibling(curr, members));
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- fInsertPositions.add(null);
- }
-
- protected IType getType() {
- return fType;
- }
-
- protected boolean asBoolean(String string, boolean defaultValue) {
- if (string != null) {
- return StringConverter.asBoolean(string, defaultValue);
- }
- return defaultValue;
- }
-
- protected int asInt(String string, int defaultValue) {
- if (string != null) {
- return StringConverter.asInt(string, defaultValue);
- }
- return defaultValue;
- }
-
- private IJavaScriptElement findSibling(IFunction curr, IJavaScriptElement[] members) throws JavaScriptModelException {
- IJavaScriptElement res= null;
- int methodStart= curr.getSourceRange().getOffset();
- for (int i= members.length-1; i >= 0; i--) {
- IMember member= (IMember) members[i];
- if (methodStart >= member.getSourceRange().getOffset()) {
- return res;
- }
- res= member;
- }
- return null;
- }
-
- protected boolean hasCursorPositionElement(CompilationUnitEditor editor, IJavaScriptElement[] members, List insertPositions) throws JavaScriptModelException {
- if (editor == null) {
- return false;
- }
- int offset= ((ITextSelection) editor.getSelectionProvider().getSelection()).getOffset();
-
- for (int i= 0; i < members.length; i++) {
- IMember curr= (IMember) members[i];
- ISourceRange range= curr.getSourceRange();
- if (offset < range.getOffset()) {
- insertPositions.add(curr);
- return true;
- } else if (offset < range.getOffset() + range.getLength()) {
- return false; // in the middle of a member
- }
- }
- insertPositions.add(null);
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#close()
- */
- public boolean close() {
- fSettings.put(SETTINGS_VISIBILITY_MODIFIER, StringConverter.asString(fVisibilityModifier));
- fSettings.put(SETTINGS_FINAL_MODIFIER, StringConverter.asString(fFinal));
- fSettings.put(SETTINGS_SYNCHRONIZED_MODIFIER, StringConverter.asString(fSynchronized));
-
- if (fCurrentPositionIndex == 0 || fCurrentPositionIndex == 1) {
- fSettings.put(SETTINGS_INSERTPOSITION, StringConverter.asString(fCurrentPositionIndex));
- }
- fSettings.put(SETTINGS_COMMENTS, fGenerateComment);
- return super.close();
- }
-
- /**
- * Sets the size of the tree in unit of characters.
- * @param width the width of the tree.
- * @param height the height of the tree.
- */
- public void setSize(int width, int height) {
- fWidth = width;
- fHeight = height;
- }
-
-
- /***
- * Set insert position valid input is 0 for the first position, 1 for the last position, > 1 for all else.
- */
- private void setInsertPosition(int insert) {
- fCurrentPositionIndex= insert;
- }
-
- public void setCommentString(String string) {
- fCommentString= string;
- }
-
- protected ITreeContentProvider getContentProvider() {
- return fContentProvider;
- }
-
- public boolean getGenerateComment() {
- return fGenerateComment;
- }
-
- public int getVisibilityModifier() {
- return fVisibilityModifier;
- }
-
- public void setGenerateComment(boolean comment) {
- fGenerateComment= comment;
- }
-
- protected void setVisibility(int visibility) {
- fVisibilityModifier= visibility;
- }
-
- private void setFinal(boolean value) {
- fFinal= value;
- }
-
- private void setSynchronized(boolean value) {
- fSynchronized= value;
- }
-
- protected Composite createSelectionButtons(Composite composite) {
- Composite buttonComposite= super.createSelectionButtons(composite);
-
- GridLayout layout = new GridLayout();
- buttonComposite.setLayout(layout);
-
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
-
- return buttonComposite;
- }
-
- protected void buttonPressed(int buttonId) {
- switch (buttonId) {
- case IDialogConstants.OK_ID: {
- okPressed();
- break;
- }
- case IDialogConstants.CANCEL_ID: {
- cancelPressed();
- break;
- }
- }
- }
-
- /**
- * Returns a composite containing the label created at the top of the dialog. Returns null if there is the
- * message for the label is null.
- */
- protected Label createMessageArea(Composite composite) {
- if (getMessage() != null) {
- Label label = new Label(composite,SWT.NONE);
- label.setText(getMessage());
- label.setFont(composite.getFont());
- return label;
- }
- return null;
- }
-
- /*
- * @see Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- GridData gd= null;
-
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
-
- Label messageLabel = createMessageArea(composite);
- if (messageLabel != null) {
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- messageLabel.setLayoutData(gd);
- }
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout innerLayout = new GridLayout();
- innerLayout.numColumns= 2;
- innerLayout.marginHeight= 0;
- innerLayout.marginWidth= 0;
- inner.setLayout(innerLayout);
- inner.setFont(parent.getFont());
-
- CheckboxTreeViewer treeViewer= createTreeViewer(inner);
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint = convertWidthInCharsToPixels(fWidth);
- gd.heightHint = convertHeightInCharsToPixels(fHeight);
- treeViewer.getControl().setLayoutData(gd);
-
- Composite buttonComposite= createSelectionButtons(inner);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
- buttonComposite.setLayoutData(gd);
-
- gd= new GridData(GridData.FILL_BOTH);
- inner.setLayoutData(gd);
-
- fInsertPositionComposite= createInsertPositionCombo(composite);
- fInsertPositionComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite commentComposite= createCommentSelection(composite);
- commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Control linkControl= createLinkControl(composite);
- if (linkControl != null)
- linkControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
-
- applyDialogFont(composite);
-
- return composite;
- }
-
- protected Control createLinkControl(Composite composite) {
- return null; // No link as default
- }
-
- protected void openCodeTempatePage(String id) {
- HashMap arg= new HashMap();
- arg.put(CodeTemplatePreferencePage.DATA_SELECT_TEMPLATE, id);
- PreferencesUtil.createPropertyDialogOn(getShell(), fType.getJavaScriptProject().getProject(), CodeTemplatePreferencePage.PROP_ID, null, arg).open();
- }
-
-
- protected Composite createCommentSelection(Composite composite) {
- Composite commentComposite = new Composite(composite, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- commentComposite.setLayout(layout);
- commentComposite.setFont(composite.getFont());
-
- Button commentButton= new Button(commentComposite, SWT.CHECK);
- commentButton.setText(fCommentString);
-
- commentButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- boolean isSelected= (((Button) e.widget).getSelection());
- setGenerateComment(isSelected);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
- commentButton.setSelection(getGenerateComment());
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- commentButton.setLayoutData(gd);
-
- return commentComposite;
- }
-
- protected Composite addVisibilityAndModifiersChoices(Composite buttonComposite) {
- // Add visibility and modifiers buttons: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870
- // Add persistence of options: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
- IVisibilityChangeListener visibilityChangeListener= new IVisibilityChangeListener(){
- public void visibilityChanged(int newVisibility) {
- setVisibility(newVisibility);
- }
- public void modifierChanged(int modifier, boolean isChecked) {
- switch (modifier) {
- case Modifier.FINAL: {
- setFinal(isChecked);
- return;
- }
- case Modifier.SYNCHRONIZED: {
- setSynchronized(isChecked);
- return;
- }
- default: return;
- }
- }
- };
-
- int initialVisibility= getVisibilityModifier();
- int[] availableVisibilities= new int[]{Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE, Modifier.NONE};
-
- Composite visibilityComposite= createVisibilityControlAndModifiers(buttonComposite, visibilityChangeListener, availableVisibilities, initialVisibility);
- return visibilityComposite;
- }
-
- private List convertToIntegerList(int[] array) {
- List result= new ArrayList(array.length);
- for (int i= 0; i < array.length; i++) {
- result.add(new Integer(array[i]));
- }
- return result;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.dialogs.CheckedTreeSelectionDialog#create()
- */
- public void create() {
- super.create();
-
- // select the first checked element, or if none are checked, the first element
- CheckboxTreeViewer treeViewer= getTreeViewer();
- TreeItem[] items= treeViewer.getTree().getItems();
- if (items.length > 0) {
- Object revealedElement= items[0];
-
- for (int i= 0; i < items.length; i++) {
- if (items[i].getChecked()) {
- revealedElement= items[i].getData();
- break;
- }
- }
- treeViewer.setSelection(new StructuredSelection(revealedElement));
- treeViewer.reveal(revealedElement);
- }
- }
-
- protected Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
- List allowedVisibilities= convertToIntegerList(availableVisibilities);
- if (allowedVisibilities.size() == 1)
- return null;
-
- Group group= new Group(parent, SWT.NONE);
- group.setText(ActionMessages.SourceActionDialog_modifier_group);
- GridData gd= new GridData(GridData.FILL_BOTH);
- group.setLayoutData(gd);
- GridLayout layout= new GridLayout();
- layout.makeColumnsEqualWidth= true;
- layout.numColumns= 4;
- group.setLayout(layout);
-
- String[] labels= new String[] {
- ActionMessages.SourceActionDialog_modifier_public,
- ActionMessages.SourceActionDialog_modifier_protected,
- ActionMessages.SourceActionDialog_modifier_default,
- ActionMessages.SourceActionDialog_modifier_private,
- };
- Integer[] data= new Integer[] {
- new Integer(Modifier.PUBLIC),
- new Integer(Modifier.PROTECTED),
- new Integer(Modifier.NONE),
- new Integer(Modifier.PRIVATE)};
- Integer initialVisibility= new Integer(correctVisibility);
- for (int i= 0; i < labels.length; i++) {
- Button radio= new Button(group, SWT.RADIO);
- Integer visibilityCode= data[i];
- radio.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
- radio.setText(labels[i]);
- radio.setData(visibilityCode);
- radio.setSelection(visibilityCode.equals(initialVisibility));
- radio.setEnabled(allowedVisibilities.contains(visibilityCode));
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- visibilityChangeListener.visibilityChanged(((Integer)event.widget.getData()).intValue());
- }
- });
- }
- return group;
- }
-
- protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
- Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility);
-
- Button finalCheckboxButton= new Button(visibilityComposite, SWT.CHECK);
- finalCheckboxButton.setText(ActionMessages.SourceActionDialog_modifier_final);
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- finalCheckboxButton.setLayoutData(gd);
- finalCheckboxButton.setData(new Integer(Modifier.FINAL));
- finalCheckboxButton.setEnabled(true);
- finalCheckboxButton.setSelection(isFinal());
- finalCheckboxButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent event) {
- visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection());
- }
-
- public void widgetDefaultSelected(SelectionEvent event) {
- widgetSelected(event);
- }
- });
-
- Button syncCheckboxButton= new Button(visibilityComposite, SWT.CHECK);
- syncCheckboxButton.setText(ActionMessages.SourceActionDialog_modifier_synchronized);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- syncCheckboxButton.setLayoutData(gd);
- syncCheckboxButton.setData(new Integer(Modifier.SYNCHRONIZED));
- syncCheckboxButton.setEnabled(true);
- syncCheckboxButton.setSelection(isSynchronized());
- syncCheckboxButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent event) {
- visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection());
- }
-
- public void widgetDefaultSelected(SelectionEvent event) {
- widgetSelected(event);
- }
- });
- return visibilityComposite;
- }
-
- protected Composite createInsertPositionCombo(Composite composite) {
- Composite selectionComposite = new Composite(composite, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- selectionComposite.setLayout(layout);
-
- addOrderEntryChoices(selectionComposite);
-
- return selectionComposite;
- }
-
- private Composite addOrderEntryChoices(Composite buttonComposite) {
- Label enterLabel= new Label(buttonComposite, SWT.NONE);
- enterLabel.setText(ActionMessages.SourceActionDialog_enterAt_label);
- if (!fEnableInsertPosition)
- enterLabel.setEnabled(false);
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- enterLabel.setLayoutData(gd);
-
- final Combo enterCombo= new Combo(buttonComposite, SWT.READ_ONLY);
- if (!fEnableInsertPosition)
- enterCombo.setEnabled(false);
- fillWithPossibleInsertPositions(enterCombo);
-
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(fWidth);
- enterCombo.setLayoutData(gd);
- enterCombo.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- int index= enterCombo.getSelectionIndex();
- // Add persistence only if first or last method: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
- setInsertPosition(index);
- }
- });
-
- return buttonComposite;
- }
-
- private void fillWithPossibleInsertPositions(Combo combo) {
- combo.setItems((String[]) fLabels.toArray(new String[fLabels.size()]));
- combo.select(fCurrentPositionIndex);
- }
-
- public boolean getFinal() {
- return fFinal;
- }
-
- public boolean getSynchronized() {
- return fSynchronized;
- }
-
- public boolean isFinal() {
- return fFinal;
- }
-
- public boolean isSynchronized() {
- return fSynchronized;
- }
-
- public void setElementPositionEnabled(boolean enabled) {
- fEnableInsertPosition= enabled;
- }
-
- public boolean isElementPositionEnabled() {
- return fEnableInsertPosition;
- }
-
- /*
- * Determine where in the file to enter the newly created methods.
- */
- public IJavaScriptElement getElementPosition() {
- return (IJavaScriptElement) fInsertPositions.get(fCurrentPositionIndex);
- }
-
- public int getInsertOffset() throws JavaScriptModelException {
- IJavaScriptElement elementPosition= getElementPosition();
- if (elementPosition instanceof ISourceReference) {
- return ((ISourceReference) elementPosition).getSourceRange().getOffset();
- }
- return -1;
- }
-
- protected IDialogSettings getDialogSettings() {
- return fSettings;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusInfo.java
deleted file mode 100644
index e08a624d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusInfo.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * A settable IStatus.
- * Can be an error, warning, info or ok. For error, info and warning states,
- * a message describes the problem.
- */
-public class StatusInfo implements IStatus {
-
- public static final IStatus OK_STATUS= new StatusInfo();
-
- private String fStatusMessage;
- private int fSeverity;
-
- /**
- * Creates a status set to OK (no message)
- */
- public StatusInfo() {
- this(OK, null);
- }
-
- /**
- * Creates a status .
- * @param severity The status severity: ERROR, WARNING, INFO and OK.
- * @param message The message of the status. Applies only for ERROR,
- * WARNING and INFO.
- */
- public StatusInfo(int severity, String message) {
- fStatusMessage= message;
- fSeverity= severity;
- }
-
- /**
- * Returns if the status' severity is OK.
- */
- public boolean isOK() {
- return fSeverity == IStatus.OK;
- }
-
- /**
- * Returns if the status' severity is WARNING.
- */
- public boolean isWarning() {
- return fSeverity == IStatus.WARNING;
- }
-
- /**
- * Returns if the status' severity is INFO.
- */
- public boolean isInfo() {
- return fSeverity == IStatus.INFO;
- }
-
- /**
- * Returns if the status' severity is ERROR.
- */
- public boolean isError() {
- return fSeverity == IStatus.ERROR;
- }
-
- /**
- * @see IStatus#getMessage
- */
- public String getMessage() {
- return fStatusMessage;
- }
-
- /**
- * Sets the status to ERROR.
- * @param errorMessage The error message (can be empty, but not null)
- */
- public void setError(String errorMessage) {
- Assert.isNotNull(errorMessage);
- fStatusMessage= errorMessage;
- fSeverity= IStatus.ERROR;
- }
-
- /**
- * Sets the status to WARNING.
- * @param warningMessage The warning message (can be empty, but not null)
- */
- public void setWarning(String warningMessage) {
- Assert.isNotNull(warningMessage);
- fStatusMessage= warningMessage;
- fSeverity= IStatus.WARNING;
- }
-
- /**
- * Sets the status to INFO.
- * @param infoMessage The info message (can be empty, but not null)
- */
- public void setInfo(String infoMessage) {
- Assert.isNotNull(infoMessage);
- fStatusMessage= infoMessage;
- fSeverity= IStatus.INFO;
- }
-
- /**
- * Sets the status to OK.
- */
- public void setOK() {
- fStatusMessage= null;
- fSeverity= IStatus.OK;
- }
-
- /*
- * @see IStatus#matches(int)
- */
- public boolean matches(int severityMask) {
- return (fSeverity & severityMask) != 0;
- }
-
- /**
- * Returns always <code>false</code>.
- * @see IStatus#isMultiStatus()
- */
- public boolean isMultiStatus() {
- return false;
- }
-
- /*
- * @see IStatus#getSeverity()
- */
- public int getSeverity() {
- return fSeverity;
- }
-
- /*
- * @see IStatus#getPlugin()
- */
- public String getPlugin() {
- return JavaScriptUI.ID_PLUGIN;
- }
-
- /**
- * Returns always <code>null</code>.
- * @see IStatus#getException()
- */
- public Throwable getException() {
- return null;
- }
-
- /**
- * Returns always the error severity.
- * @see IStatus#getCode()
- */
- public int getCode() {
- return fSeverity;
- }
-
- /**
- * Returns always an empty array.
- * @see IStatus#getChildren()
- */
- public IStatus[] getChildren() {
- return new IStatus[0];
- }
-
- /**
- * Returns a string representation of the status, suitable
- * for debugging purposes only.
- */
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("StatusInfo "); //$NON-NLS-1$
- if (fSeverity == OK) {
- buf.append("OK"); //$NON-NLS-1$
- } else if (fSeverity == ERROR) {
- buf.append("ERROR"); //$NON-NLS-1$
- } else if (fSeverity == WARNING) {
- buf.append("WARNING"); //$NON-NLS-1$
- } else if (fSeverity == INFO) {
- buf.append("INFO"); //$NON-NLS-1$
- } else {
- buf.append("severity="); //$NON-NLS-1$
- buf.append(fSeverity);
- }
- buf.append(": "); //$NON-NLS-1$
- buf.append(fStatusMessage);
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusUtil.java
deleted file mode 100644
index 82554149..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/StatusUtil.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.dialogs.IMessageProvider;
-
-/**
- * A utility class to work with IStatus.
- */
-public class StatusUtil {
-
- /**
- * Compares two instances of <code>IStatus</code>. The more severe is returned:
- * An error is more severe than a warning, and a warning is more severe
- * than ok. If the two stati have the same severity, the second is returned.
- */
- public static IStatus getMoreSevere(IStatus s1, IStatus s2) {
- if (s1.getSeverity() > s2.getSeverity()) {
- return s1;
- } else {
- return s2;
- }
- }
-
- /**
- * Finds the most severe status from a array of stati.
- * An error is more severe than a warning, and a warning is more severe
- * than ok.
- */
- public static IStatus getMostSevere(IStatus[] status) {
- IStatus max= null;
- for (int i= 0; i < status.length; i++) {
- IStatus curr= status[i];
- if (curr.matches(IStatus.ERROR)) {
- return curr;
- }
- if (max == null || curr.getSeverity() > max.getSeverity()) {
- max= curr;
- }
- }
- return max;
- }
-
- /**
- * Applies the status to the status line of a dialog page.
- */
- public static void applyToStatusLine(DialogPage page, IStatus status) {
- String message= status.getMessage();
- switch (status.getSeverity()) {
- case IStatus.OK:
- page.setMessage(message, IMessageProvider.NONE);
- page.setErrorMessage(null);
- break;
- case IStatus.WARNING:
- page.setMessage(message, IMessageProvider.WARNING);
- page.setErrorMessage(null);
- break;
- case IStatus.INFO:
- page.setMessage(message, IMessageProvider.INFORMATION);
- page.setErrorMessage(null);
- break;
- default:
- if (message.length() == 0) {
- message= null;
- }
- page.setMessage(null);
- page.setErrorMessage(message);
- break;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TableTextCellEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TableTextCellEditor.java
deleted file mode 100644
index ab4eeace..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TableTextCellEditor.java
+++ /dev/null
@@ -1,437 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * <code>TableTextCellEditor</code> is a copy of TextCellEditor, with the
- * following changes:
- *
- * <ul>
- * <li> modify events are sent out as the text is changed, and not only after
- * editing is done </li>
- *
- * <li>a content assistant is supported</li>
- *
- * <li>the <code>Control</code> from <code>getControl(Composite)</code>
- * does not notify registered FocusListeners. This is a workaround for bug
- * 58777. </li>
- *
- * <li>the user can go to the next/previous row with up and down keys</li>
- * </ul>
- */
-public class TableTextCellEditor extends CellEditor {
- public interface IActivationListener {
- public void activate();
- }
-
- private final TableViewer fTableViewer;
- private final int fColumn;
- private final String fProperty;
- /**
- * The editor's value on activation. This value is reset to the
- * cell when the editor is left via ESC key.
- */
- String fOriginalValue;
- SubjectControlContentAssistant fContentAssistant;
- private IActivationListener fActivationListener;
-
- protected Text text;
-
- private boolean isSelection = false;
- private boolean isDeleteable = false;
- private boolean isSelectable = false;
-
- private static final int defaultStyle = SWT.SINGLE;
- private ModifyListener fModifyListener;
-
- public TableTextCellEditor(TableViewer tableViewer, int column) {
- super(tableViewer.getTable(), defaultStyle);
- fTableViewer= tableViewer;
- fColumn= column;
- fProperty= (String) tableViewer.getColumnProperties()[column];
- }
-
- public void activate() {
- super.activate();
- if (fActivationListener != null)
- fActivationListener.activate();
- fOriginalValue= text.getText();
- }
-
- private void fireModifyEvent(Object newValue) {
- fTableViewer.getCellModifier().modify(
- ((IStructuredSelection) fTableViewer.getSelection()).getFirstElement(),
- fProperty, newValue);
- }
-
- protected void focusLost() {
- if (fContentAssistant != null && fContentAssistant.hasProposalPopupFocus()) {
- // skip focus lost if it went to the content assist popup
- } else {
- super.focusLost();
- }
- }
-
- public void setContentAssistant(SubjectControlContentAssistant assistant) {
- fContentAssistant= assistant;
- }
-
- public void setActivationListener(IActivationListener listener) {
- fActivationListener= listener;
- }
-
- public Text getText() {
- return text;
- }
-
- protected void checkDeleteable() {
- boolean oldIsDeleteable = isDeleteable;
- isDeleteable = isDeleteEnabled();
- if (oldIsDeleteable != isDeleteable) {
- fireEnablementChanged(DELETE);
- }
- }
-
- protected void checkSelectable() {
- boolean oldIsSelectable = isSelectable;
- isSelectable = isSelectAllEnabled();
- if (oldIsSelectable != isSelectable) {
- fireEnablementChanged(SELECT_ALL);
- }
- }
-
- protected void checkSelection() {
- boolean oldIsSelection = isSelection;
- isSelection = text.getSelectionCount() > 0;
- if (oldIsSelection != isSelection) {
- fireEnablementChanged(COPY);
- fireEnablementChanged(CUT);
- }
- }
-
- private ModifyListener getModifyListener() {
- if (fModifyListener == null) {
- fModifyListener = new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- editOccured(e);
- }
- };
- }
- return fModifyListener;
- }
-
- /* (non-Javadoc)
- * Method declared on CellEditor.
- */
- protected Control createControl(Composite parent) {
- //workaround for bug 58777: don't accept focus listeners on the text control
- final Control[] textControl= new Control[1];
- Composite result= new Composite(parent, SWT.NONE) {
- public void addListener(int eventType, final Listener listener) {
- if (eventType != SWT.FocusIn && eventType != SWT.FocusOut) {
- textControl[0].addListener(eventType, listener);
- }
- }
- };
- result.setFont(parent.getFont());
- result.setBackground(parent.getBackground());
- result.setLayout(new FillLayout());
-
- text = new Text(result, getStyle());
- textControl[0]= text;
- text.addSelectionListener(new SelectionAdapter() {
- public void widgetDefaultSelected(SelectionEvent e) {
- handleDefaultSelection(e);
- }
- });
- text.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- // support switching rows while editing:
- if (e.stateMask == SWT.MOD1 || e.stateMask == SWT.MOD2) {
- if (e.keyCode == SWT.ARROW_UP || e.keyCode == SWT.ARROW_DOWN) {
- // allow starting multi-selection even if in edit mode
- deactivate();
- e.doit= false;
- return;
- }
- }
-
- if (e.stateMask != SWT.NONE)
- return;
-
- switch (e.keyCode) {
- case SWT.ARROW_DOWN :
- e.doit= false;
- int nextRow= fTableViewer.getTable().getSelectionIndex() + 1;
- if (nextRow >= fTableViewer.getTable().getItemCount())
- break;
- editRow(nextRow);
- break;
-
- case SWT.ARROW_UP :
- e.doit= false;
- int prevRow= fTableViewer.getTable().getSelectionIndex() - 1;
- if (prevRow < 0)
- break;
- editRow(prevRow);
- break;
-
- case SWT.F2 :
- e.doit= false;
- deactivate();
- break;
- }
- }
-
- private void editRow(int row) {
- fTableViewer.getTable().setSelection(row);
- IStructuredSelection newSelection= (IStructuredSelection) fTableViewer.getSelection();
- if (newSelection.size() == 1)
- fTableViewer.editElement(newSelection.getFirstElement(), fColumn);
- }
- });
- text.addKeyListener(new KeyAdapter() {
- // hook key pressed - see PR 14201
- public void keyPressed(KeyEvent e) {
- keyReleaseOccured(e);
-
- // as a result of processing the above call, clients may have
- // disposed this cell editor
- if ((getControl() == null) || getControl().isDisposed())
- return;
- checkSelection(); // see explaination below
- checkDeleteable();
- checkSelectable();
- }
- });
- text.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_ESCAPE
- || e.detail == SWT.TRAVERSE_RETURN) {
- e.doit = false;
- }
- }
- });
- // We really want a selection listener but it is not supported so we
- // use a key listener and a mouse listener to know when selection changes
- // may have occured
- text.addMouseListener(new MouseAdapter() {
- public void mouseUp(MouseEvent e) {
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
- });
- text.addFocusListener(new FocusAdapter() {
- public void focusLost(FocusEvent e) {
- TableTextCellEditor.this.focusLost();
- }
- });
- text.setFont(parent.getFont());
- text.setBackground(parent.getBackground());
- text.setText("");//$NON-NLS-1$
- text.addModifyListener(getModifyListener());
-
- return result;
- }
-
- protected void fireCancelEditor() {
- /* bug 58540: change signature refactoring interaction: validate as you type [refactoring] */
- text.setText(fOriginalValue);
- super.fireApplyEditorValue();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of
- * this <code>CellEditor</code> framework method returns
- * the text string.
- *
- * @return the text string
- */
- protected Object doGetValue() {
- return text.getText();
- }
-
- protected void doSetFocus() {
- if (text != null) {
- text.selectAll();
- text.setFocus();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
- }
-
- /**
- * The <code>TextCellEditor2</code> implementation of
- * this <code>CellEditor</code> framework method accepts
- * a text string (type <code>String</code>).
- *
- * @param value a text string (type <code>String</code>)
- */
- protected void doSetValue(Object value) {
- Assert.isTrue(text != null && (value instanceof String));
- text.removeModifyListener(getModifyListener());
- text.setText((String) value);
- text.addModifyListener(getModifyListener());
- }
-
- /**
- * Processes a modify event that occurred in this text cell editor.
- * This framework method performs validation and sets the error message
- * accordingly, and then reports a change via <code>fireEditorValueChanged</code>.
- * Subclasses should call this method at appropriate times. Subclasses
- * may extend or reimplement.
- *
- * @param e the SWT modify event
- */
- protected void editOccured(ModifyEvent e) {
- String value = text.getText();
- boolean oldValidState = isValueValid();
- boolean newValidState = isCorrect(value);
- if (!newValidState) {
- // try to insert the current value into the error message.
- setErrorMessage(Messages.format(getErrorMessage(),
- new Object[] { value }));
- }
- valueChanged(oldValidState, newValidState);
- fireModifyEvent(text.getText()); // update model on-the-fly
- }
-
- public LayoutData getLayoutData() {
- return new LayoutData();
- }
-
- protected void handleDefaultSelection(SelectionEvent event) {
- // same with enter-key handling code in keyReleaseOccured(e);
- fireApplyEditorValue();
- deactivate();
- }
-
- public boolean isCopyEnabled() {
- if (text == null || text.isDisposed())
- return false;
- return text.getSelectionCount() > 0;
- }
-
- public boolean isCutEnabled() {
- if (text == null || text.isDisposed())
- return false;
- return text.getSelectionCount() > 0;
- }
-
- public boolean isDeleteEnabled() {
- if (text == null || text.isDisposed())
- return false;
- return text.getSelectionCount() > 0
- || text.getCaretPosition() < text.getCharCount();
- }
-
- public boolean isPasteEnabled() {
- if (text == null || text.isDisposed())
- return false;
- return true;
- }
-
- public boolean isSelectAllEnabled() {
- if (text == null || text.isDisposed())
- return false;
- return text.getCharCount() > 0;
- }
-
- protected void keyReleaseOccured(KeyEvent keyEvent) {
- if (keyEvent.character == '\r') { // Return key
- // Enter is handled in handleDefaultSelection.
- // Do not apply the editor value in response to an Enter key event
- // since this can be received from the IME when the intent is -not-
- // to apply the value.
- // See bug 39074 [CellEditors] [DBCS] canna input mode fires bogus event from Text Control
- //
- // An exception is made for Ctrl+Enter for multi-line texts, since
- // a default selection event is not sent in this case.
- if (text != null && !text.isDisposed()
- && (text.getStyle() & SWT.MULTI) != 0) {
- if ((keyEvent.stateMask & SWT.CTRL) != 0) {
- super.keyReleaseOccured(keyEvent);
- }
- }
- return;
- }
- super.keyReleaseOccured(keyEvent);
- }
-
- public void performCopy() {
- text.copy();
- }
-
- public void performCut() {
- text.cut();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- public void performDelete() {
- if (text.getSelectionCount() > 0)
- // remove the contents of the current selection
- text.insert(""); //$NON-NLS-1$
- else {
- // remove the next character
- int pos = text.getCaretPosition();
- if (pos < text.getCharCount()) {
- text.setSelection(pos, pos + 1);
- text.insert(""); //$NON-NLS-1$
- }
- }
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- public void performPaste() {
- text.paste();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- public void performSelectAll() {
- text.selectAll();
- checkSelection();
- checkDeleteable();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TextFieldNavigationHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TextFieldNavigationHandler.java
deleted file mode 100644
index 6e9c1b8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TextFieldNavigationHandler.java
+++ /dev/null
@@ -1,505 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.CommandManager;
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.core.commands.common.NotDefinedException;
-import org.eclipse.core.commands.contexts.ContextManager;
-import org.eclipse.jface.bindings.BindingManager;
-import org.eclipse.jface.bindings.Scheme;
-import org.eclipse.jface.bindings.TriggerSequence;
-import org.eclipse.jface.bindings.keys.KeySequence;
-import org.eclipse.jface.bindings.keys.SWTKeySupport;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordIterator;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-import com.ibm.icu.text.BreakIterator;
-
-/**
- * Support for camelCase-aware sub-word navigation in dialog fields.
- */
-public class TextFieldNavigationHandler {
-
- public static void install(Text text) {
- if (isSubWordNavigationEnabled())
- new FocusHandler(new TextNavigable(text));
- }
-
- public static void install(StyledText styledText) {
- if (isSubWordNavigationEnabled())
- new FocusHandler(new StyledTextNavigable(styledText));
- }
-
- public static void install(Combo combo) {
- if (isSubWordNavigationEnabled())
- new FocusHandler(new ComboNavigable(combo));
- }
-
- private static boolean isSubWordNavigationEnabled() {
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- return preferenceStore.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION);
- }
-
- private abstract static class WorkaroundNavigable extends Navigable {
- /* workarounds for:
- * - bug 103630: Add API: Combo#getCaretPosition()
- * - bug 106024: Text#setSelection(int, int) does not handle start > end with SWT.SINGLE
- */
- Point fLastSelection;
- int fCaretPosition;
-
- void selectionChanged() {
- Point selection= getSelection();
- if (selection.equals(fLastSelection)) {
- // leave caret position
- } else if (selection.x == selection.y) { //empty range
- fCaretPosition= selection.x;
- } else if (fLastSelection.y == selection.y) {
- fCaretPosition= selection.x; //same end -> assume caret at start
- } else {
- fCaretPosition= selection.y;
- }
- fLastSelection= selection;
- }
- }
-
- private abstract static class Navigable {
- public abstract Control getControl();
-
- public abstract String getText();
-
- public abstract void setText(String text);
-
- public abstract Point getSelection();
-
- public abstract void setSelection(int start, int end);
-
- public abstract int getCaretPosition();
- }
-
- private static class TextNavigable extends WorkaroundNavigable {
- static final boolean BUG_106024_TEXT_SELECTION=
- "win32".equals(SWT.getPlatform()) //$NON-NLS-1$
- // on carbon, getCaretPosition() always returns getSelection().x
- || "carbon".equals(SWT.getPlatform()); //$NON-NLS-1$
-
- private final Text fText;
-
- public TextNavigable(Text text) {
- fText= text;
- // workaround for bug 106024:
- if (BUG_106024_TEXT_SELECTION) {
- fLastSelection= getSelection();
- fCaretPosition= fLastSelection.y;
- fText.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- selectionChanged();
- }
- });
- fText.addMouseListener(new MouseAdapter() {
- public void mouseUp(MouseEvent e) {
- selectionChanged();
- }
- });
- }
- }
-
- public Control getControl() {
- return fText;
- }
-
- public String getText() {
- return fText.getText();
- }
-
- public void setText(String text) {
- fText.setText(text);
- }
-
- public Point getSelection() {
- return fText.getSelection();
- }
-
- public int getCaretPosition() {
- if (BUG_106024_TEXT_SELECTION) {
- selectionChanged();
- return fCaretPosition;
- } else {
- return fText.getCaretPosition();
- }
- }
-
- public void setSelection(int start, int end) {
- fText.setSelection(start, end);
- }
- }
-
- private static class StyledTextNavigable extends Navigable {
- private final StyledText fStyledText;
-
- public StyledTextNavigable(StyledText styledText) {
- fStyledText= styledText;
- }
-
- public Control getControl() {
- return fStyledText;
- }
-
- public String getText() {
- return fStyledText.getText();
- }
-
- public void setText(String text) {
- fStyledText.setText(text);
- }
-
- public Point getSelection() {
- return fStyledText.getSelection();
- }
-
- public int getCaretPosition() {
- return fStyledText.getCaretOffset();
- }
-
- public void setSelection(int start, int end) {
- fStyledText.setSelection(start, end);
- }
- }
-
- private static class ComboNavigable extends WorkaroundNavigable {
- private final Combo fCombo;
-
- public ComboNavigable(Combo combo) {
- fCombo= combo;
- // workaround for bug 103630:
- fLastSelection= getSelection();
- fCaretPosition= fLastSelection.y;
- fCombo.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- selectionChanged();
- }
- });
- fCombo.addMouseListener(new MouseAdapter() {
- public void mouseUp(MouseEvent e) {
- selectionChanged();
- }
- });
- }
-
- public Control getControl() {
- return fCombo;
- }
-
- public String getText() {
- return fCombo.getText();
- }
-
- public void setText(String text) {
- fCombo.setText(text);
- }
-
- public Point getSelection() {
- return fCombo.getSelection();
- }
-
- public int getCaretPosition() {
- selectionChanged();
- return fCaretPosition;
-// return fCombo.getCaretPosition(); // not available: bug 103630
- }
-
- public void setSelection(int start, int end) {
- fCombo.setSelection(new Point(start, end));
- }
- }
-
- private static class FocusHandler implements FocusListener {
-
- private static final String EMPTY_TEXT= ""; //$NON-NLS-1$
-
- private final JavaWordIterator fIterator;
- private final Navigable fNavigable;
- private KeyAdapter fKeyListener;
-
- private FocusHandler(Navigable navigable) {
- fIterator= new JavaWordIterator();
- fNavigable= navigable;
-
- Control control= navigable.getControl();
- control.addFocusListener(this);
- if (control.isFocusControl())
- activate();
- control.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- deactivate();
- }
- });
- }
-
- public void focusGained(FocusEvent e) {
- activate();
- }
-
- public void focusLost(FocusEvent e) {
- deactivate();
- }
-
- private void activate() {
- fNavigable.getControl().addKeyListener(getKeyListener());
- }
-
- private void deactivate() {
- if (fKeyListener != null) {
- Control control= fNavigable.getControl();
- if (! control.isDisposed())
- control.removeKeyListener(fKeyListener);
- fKeyListener= null;
- }
- }
-
- private KeyAdapter getKeyListener() {
- if (fKeyListener == null) {
- fKeyListener= new KeyAdapter() {
- private final boolean IS_WORKAROUND= (fNavigable instanceof ComboNavigable)
- || (fNavigable instanceof TextNavigable && TextNavigable.BUG_106024_TEXT_SELECTION);
- private List/*<Submission>*/ fSubmissions;
-
- public void keyPressed(KeyEvent e) {
- if (IS_WORKAROUND) {
- if (e.keyCode == SWT.ARROW_LEFT && e.stateMask == SWT.MOD2) {
- int caretPosition= fNavigable.getCaretPosition();
- if (caretPosition != 0) {
- Point selection= fNavigable.getSelection();
- if (caretPosition == selection.x)
- fNavigable.setSelection(selection.y, caretPosition - 1);
- else
- fNavigable.setSelection(selection.x, caretPosition - 1);
- }
- e.doit= false;
- return;
-
- } else if (e.keyCode == SWT.ARROW_RIGHT && e.stateMask == SWT.MOD2) {
- String text= fNavigable.getText();
- int caretPosition= fNavigable.getCaretPosition();
- if (caretPosition != text.length()) {
- Point selection= fNavigable.getSelection();
- if (caretPosition == selection.y)
- fNavigable.setSelection(selection.x, caretPosition + 1);
- else
- fNavigable.setSelection(selection.y, caretPosition + 1);
- }
- e.doit= false;
- return;
- }
- }
- int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
- KeySequence keySequence = KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator));
- getSubmissions();
- for (Iterator iter= getSubmissions().iterator(); iter.hasNext();) {
- Submission submission= (Submission) iter.next();
- TriggerSequence[] triggerSequences= submission.getTriggerSequences();
- for (int i= 0; i < triggerSequences.length; i++) {
- if (triggerSequences[i].equals(keySequence)) { // XXX does not work for multi-stroke bindings
- e.doit= false;
- submission.execute();
- return;
- }
- }
- }
- }
-
- private List/*<Submission>*/ getSubmissions() {
- if (fSubmissions != null)
- return fSubmissions;
-
- fSubmissions= new ArrayList();
-
- ICommandService commandService= (ICommandService) PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- IBindingService bindingService= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (commandService == null || bindingService == null)
- return fSubmissions;
-
- // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=184502 ,
- // similar to CodeAssistAdvancedConfigurationBlock.getKeyboardShortcut(..):
- BindingManager localBindingManager= new BindingManager(new ContextManager(), new CommandManager());
- final Scheme[] definedSchemes= bindingService.getDefinedSchemes();
- if (definedSchemes != null) {
- try {
- for (int i = 0; i < definedSchemes.length; i++) {
- Scheme scheme= definedSchemes[i];
- Scheme localSchemeCopy= localBindingManager.getScheme(scheme.getId());
- localSchemeCopy.define(scheme.getName(), scheme.getDescription(), scheme.getParentId());
- }
- } catch (final NotDefinedException e) {
- JavaScriptPlugin.log(e);
- }
- }
- localBindingManager.setLocale(bindingService.getLocale());
- localBindingManager.setPlatform(bindingService.getPlatform());
-
- localBindingManager.setBindings(bindingService.getBindings());
- try {
- Scheme activeScheme= bindingService.getActiveScheme();
- if (activeScheme != null)
- localBindingManager.setActiveScheme(activeScheme);
- } catch (NotDefinedException e) {
- JavaScriptPlugin.log(e);
- }
-
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.SELECT_WORD_NEXT)) {
- public void execute() {
- fIterator.setText(fNavigable.getText());
- int caretPosition= fNavigable.getCaretPosition();
- int newCaret= fIterator.following(caretPosition);
- if (newCaret != BreakIterator.DONE) {
- Point selection= fNavigable.getSelection();
- if (caretPosition == selection.y)
- fNavigable.setSelection(selection.x, newCaret);
- else
- fNavigable.setSelection(selection.y, newCaret);
- }
- fIterator.setText(EMPTY_TEXT);
- }
- });
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS)) {
- public void execute() {
- fIterator.setText(fNavigable.getText());
- int caretPosition= fNavigable.getCaretPosition();
- int newCaret= fIterator.preceding(caretPosition);
- if (newCaret != BreakIterator.DONE) {
- Point selection= fNavigable.getSelection();
- if (caretPosition == selection.x)
- fNavigable.setSelection(selection.y, newCaret);
- else
- fNavigable.setSelection(selection.x, newCaret);
- }
- fIterator.setText(EMPTY_TEXT);
- }
- });
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.WORD_NEXT)) {
- public void execute() {
- fIterator.setText(fNavigable.getText());
- int caretPosition= fNavigable.getCaretPosition();
- int newCaret= fIterator.following(caretPosition);
- if (newCaret != BreakIterator.DONE)
- fNavigable.setSelection(newCaret, newCaret);
- fIterator.setText(EMPTY_TEXT);
- }
- });
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.WORD_PREVIOUS)) {
- public void execute() {
- fIterator.setText(fNavigable.getText());
- int caretPosition= fNavigable.getCaretPosition();
- int newCaret= fIterator.preceding(caretPosition);
- if (newCaret != BreakIterator.DONE)
- fNavigable.setSelection(newCaret, newCaret);
- fIterator.setText(EMPTY_TEXT);
- }
- });
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.DELETE_NEXT_WORD)) {
- public void execute() {
- Point selection= fNavigable.getSelection();
- String text= fNavigable.getText();
- int start;
- int end;
- if (selection.x != selection.y) {
- start= selection.x;
- end= selection.y;
- } else {
- fIterator.setText(text);
- start= fNavigable.getCaretPosition();
- end= fIterator.following(start);
- fIterator.setText(EMPTY_TEXT);
- if (end == BreakIterator.DONE)
- return;
- }
- fNavigable.setText(text.substring(0, start) + text.substring(end));
- fNavigable.setSelection(start, start);
- }
- });
- fSubmissions.add(new Submission(getKeyBindings(localBindingManager, commandService, ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD)) {
- public void execute() {
- Point selection= fNavigable.getSelection();
- String text= fNavigable.getText();
- int start;
- int end;
- if (selection.x != selection.y) {
- start= selection.x;
- end= selection.y;
- } else {
- fIterator.setText(text);
- end= fNavigable.getCaretPosition();
- start= fIterator.preceding(end);
- fIterator.setText(EMPTY_TEXT);
- if (start == BreakIterator.DONE)
- return;
- }
- fNavigable.setText(text.substring(0, start) + text.substring(end));
- fNavigable.setSelection(start, start);
- }
- });
-
- return fSubmissions;
- }
-
- private TriggerSequence[] getKeyBindings(BindingManager localBindingManager, ICommandService commandService, String commandID) {
- Command command= commandService.getCommand(commandID);
- ParameterizedCommand pCmd= new ParameterizedCommand(command, null);
- return localBindingManager.getActiveBindingsDisregardingContextFor(pCmd);
- }
-
- };
- }
- return fKeyListener;
- }
- }
-
- private abstract static class Submission {
- private TriggerSequence[] fTriggerSequences;
-
- public Submission(TriggerSequence[] triggerSequences) {
- fTriggerSequences= triggerSequences;
- }
-
- public TriggerSequence[] getTriggerSequences() {
- return fTriggerSequences;
- }
-
- public abstract void execute();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java
deleted file mode 100644
index 2dce2d78..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java
+++ /dev/null
@@ -1,1583 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.ProgressMonitorWrapper;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor;
-import org.eclipse.wst.jsdt.core.search.TypeNameRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeInfoFilter;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeInfoRequestorAdapter;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstallType;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.launching.LibraryLocation;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoImageProvider;
-
-/**
- * A viewer to present type queried form the type history and form the
- * search engine. All viewer updating takes place in the UI thread.
- * Therefore no synchronization of the methods is necessary.
- *
- *
- */
-public class TypeInfoViewer {
-
- private static class SearchRequestor extends TypeNameMatchRequestor {
- private volatile boolean fStop;
-
- private Set fHistory;
-
- private TypeInfoFilter fFilter;
- private List fResult;
-
- public SearchRequestor(TypeInfoFilter filter) {
- super();
- fResult= new ArrayList(2048);
- fFilter= filter;
- }
- public TypeNameMatch[] getResult() {
- return (TypeNameMatch[])fResult.toArray(new TypeNameMatch[fResult.size()]);
- }
- public void cancel() {
- fStop= true;
- }
- public void setHistory(Set history) {
- fHistory= history;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch)
- */
- public void acceptTypeNameMatch(TypeNameMatch match) {
- if (fStop)
- return;
- if (TypeFilter.isFiltered(match))
- return;
- if (fHistory.contains(match))
- return;
- if (fFilter.matchesFilterExtension(match))
- fResult.add(match);
- }
- }
-
- protected static class TypeInfoComparator implements Comparator {
- private TypeInfoLabelProvider fLabelProvider;
- private TypeInfoFilter fFilter;
- public TypeInfoComparator(TypeInfoLabelProvider labelProvider, TypeInfoFilter filter) {
- fLabelProvider= labelProvider;
- fFilter= filter;
- }
- public int compare(Object left, Object right) {
- TypeNameMatch leftInfo= (TypeNameMatch)left;
- TypeNameMatch rightInfo= (TypeNameMatch)right;
- int leftCategory= getCamelCaseCategory(leftInfo);
- int rightCategory= getCamelCaseCategory(rightInfo);
- if (leftCategory < rightCategory)
- return -1;
- if (leftCategory > rightCategory)
- return +1;
- int result= compareName(leftInfo.getSimpleTypeName(), rightInfo.getSimpleTypeName());
- if (result != 0)
- return result;
- result= compareTypeContainerName(leftInfo.getTypeContainerName(), rightInfo.getTypeContainerName());
- if (result != 0)
- return result;
-
- leftCategory= getElementTypeCategory(leftInfo);
- rightCategory= getElementTypeCategory(rightInfo);
- if (leftCategory < rightCategory)
- return -1;
- if (leftCategory > rightCategory)
- return +1;
- return compareContainerName(leftInfo, rightInfo);
- }
- private int compareName(String leftString, String rightString) {
- int result= leftString.compareToIgnoreCase(rightString);
- if (result != 0 || rightString.length() == 0) {
- return result;
- } else if (Strings.isLowerCase(leftString.charAt(0)) &&
- !Strings.isLowerCase(rightString.charAt(0))) {
- return +1;
- } else if (Strings.isLowerCase(rightString.charAt(0)) &&
- !Strings.isLowerCase(leftString.charAt(0))) {
- return -1;
- } else {
- return leftString.compareTo(rightString);
- }
- }
- private int compareTypeContainerName(String leftString, String rightString) {
- int leftLength= leftString.length();
- int rightLength= rightString.length();
- if (leftLength == 0 && rightLength > 0)
- return -1;
- if (leftLength == 0 && rightLength == 0)
- return 0;
- if (leftLength > 0 && rightLength == 0)
- return +1;
- return compareName(leftString, rightString);
- }
- private int compareContainerName(TypeNameMatch leftType, TypeNameMatch rightType) {
- return fLabelProvider.getContainerName(leftType).compareTo(
- fLabelProvider.getContainerName(rightType));
- }
- private int getCamelCaseCategory(TypeNameMatch type) {
- if (fFilter == null)
- return 0;
- if (!fFilter.isCamelCasePattern())
- return 0;
- return fFilter.matchesRawNamePattern(type) ? 0 : 1;
- }
- private int getElementTypeCategory(TypeNameMatch type) {
- try {
- if (type.getPackageFragmentRoot().getKind() == IPackageFragmentRoot.K_SOURCE)
- return 0;
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return 1;
- }
- }
-
- protected static class TypeInfoLabelProvider {
-
- private ITypeInfoImageProvider fProviderExtension;
- private TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter();
-
- private Map fLib2Name= new HashMap();
- private String[] fInstallLocations;
- private String[] fVMNames;
-
- private boolean fFullyQualifyDuplicates;
-
- public TypeInfoLabelProvider(ITypeInfoImageProvider extension) {
- fProviderExtension= extension;
- List locations= new ArrayList();
- List labels= new ArrayList();
- IVMInstallType[] installs= JavaRuntime.getVMInstallTypes();
- for (int i= 0; i < installs.length; i++) {
- processVMInstallType(installs[i], locations, labels);
- }
- fInstallLocations= (String[])locations.toArray(new String[locations.size()]);
- fVMNames= (String[])labels.toArray(new String[labels.size()]);
-
- }
- public void setFullyQualifyDuplicates(boolean value) {
- fFullyQualifyDuplicates= value;
- }
- private void processVMInstallType(IVMInstallType installType, List locations, List labels) {
- if (installType != null) {
- IVMInstall[] installs= installType.getVMInstalls();
- boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS());
- final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$
- for (int i= 0; i < installs.length; i++) {
- String label= getFormattedLabel(installs[i].getName());
- LibraryLocation[] libLocations= installs[i].getLibraryLocations();
- if (libLocations != null) {
- processLibraryLocation(libLocations, label);
- } else {
- String filePath= installs[i].getInstallLocation().getAbsolutePath();
- // on MacOS X install locations end in an additional "/Home" segment; remove it
- if (isMac && filePath.endsWith(HOME_SUFFIX))
- filePath= filePath.substring(0, filePath.length()- HOME_SUFFIX.length() + 1);
- locations.add(filePath);
- labels.add(label);
- }
- }
- }
- }
- private void processLibraryLocation(LibraryLocation[] libLocations, String label) {
- for (int l= 0; l < libLocations.length; l++) {
- LibraryLocation location= libLocations[l];
- fLib2Name.put(location.getSystemLibraryPath().toString(), label);
- }
- }
- private String getFormattedLabel(String name) {
- return Messages.format(JavaUIMessages.TypeInfoViewer_library_name_format, name);
- }
- public String getText(Object element) {
- return ((TypeNameMatch)element).getSimpleTypeName();
- }
- public String getQualifiedText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- result.append(type.getSimpleTypeName());
- String containerName= type.getTypeContainerName();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- if (containerName.length() > 0) {
- result.append(containerName);
- } else {
- result.append(JavaUIMessages.TypeInfoViewer_default_package);
- }
- return result.toString();
- }
- public String getFullyQualifiedText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- result.append(type.getSimpleTypeName());
- String containerName= type.getTypeContainerName();
- if (containerName.length() > 0) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(containerName);
- }
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(type));
- return result.toString();
- }
- public String getText(TypeNameMatch last, TypeNameMatch current, TypeNameMatch next) {
- StringBuffer result= new StringBuffer();
- int qualifications= 0;
- String currentTN= current.getSimpleTypeName();
- result.append(currentTN);
- String currentTCN= getTypeContainerName(current);
- if (last != null) {
- String lastTN= last.getSimpleTypeName();
- String lastTCN= getTypeContainerName(last);
- if (currentTCN.equals(lastTCN)) {
- if (currentTN.equals(lastTN)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- return result.toString();
- }
- } else if (currentTN.equals(lastTN)) {
- qualifications= 1;
- }
- }
- if (next != null) {
- String nextTN= next.getSimpleTypeName();
- String nextTCN= getTypeContainerName(next);
- if (currentTCN.equals(nextTCN)) {
- if (currentTN.equals(nextTN)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- return result.toString();
- }
- } else if (currentTN.equals(nextTN)) {
- qualifications= 1;
- }
- }
- if (qualifications > 0) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(currentTCN);
- if (fFullyQualifyDuplicates) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getContainerName(current));
- }
- }
- return result.toString();
- }
- public String getQualificationText(TypeNameMatch type) {
- StringBuffer result= new StringBuffer();
- String containerName= type.getTypeContainerName();
- if (containerName.length() > 0) {
- result.append(containerName);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- }
- result.append(getContainerName(type));
- return result.toString();
- }
-
- private boolean isInnerType(TypeNameMatch match) {
- return match.getTypeQualifiedName().indexOf('.') != -1;
- }
-
- public ImageDescriptor getImageDescriptor(Object element) {
- TypeNameMatch type= (TypeNameMatch)element;
- if (fProviderExtension != null) {
- fAdapter.setMatch(type);
- ImageDescriptor descriptor= fProviderExtension.getImageDescriptor(fAdapter);
- if (descriptor != null)
- return descriptor;
- }
- return JavaElementImageProvider.getTypeImageDescriptor(
- isInnerType(type), false, type.getModifiers(), false);
- }
-
- private String getTypeContainerName(TypeNameMatch info) {
- String result= info.getTypeContainerName();
- if (result.length() > 0)
- return result;
- return JavaUIMessages.TypeInfoViewer_default_package;
- }
-
- private String getContainerName(TypeNameMatch type) {
- IPackageFragmentRoot root= type.getPackageFragmentRoot();
- if (root.isExternal()) {
- String name= root.getPath().toOSString();
- for (int i= 0; i < fInstallLocations.length; i++) {
- if (name.startsWith(fInstallLocations[i])) {
- return fVMNames[i];
- }
- }
- String lib= (String)fLib2Name.get(name);
- if (lib != null)
- return lib;
- }
- StringBuffer buf= new StringBuffer();
- JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf);
- return buf.toString();
- }
- }
-
- private static class ProgressUpdateJob extends UIJob {
- private TypeInfoViewer fViewer;
- private boolean fStopped;
- public ProgressUpdateJob(Display display, TypeInfoViewer viewer) {
- super(display, JavaUIMessages.TypeInfoViewer_progressJob_label);
- fViewer= viewer;
- }
- public void stop() {
- fStopped= true;
- cancel();
- }
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (stopped())
- return new Status(IStatus.CANCEL, JavaScriptPlugin.getPluginId(), IStatus.CANCEL, "", null); //$NON-NLS-1$
- fViewer.updateProgressMessage();
- if (!stopped())
- schedule(300);
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
- private boolean stopped() {
- return fStopped || fViewer.getTable().isDisposed();
- }
- }
-
- private static class ProgressMonitor extends ProgressMonitorWrapper {
- private TypeInfoViewer fViewer;
- private String fName;
- private int fTotalWork;
- private double fWorked;
- private boolean fDone;
-
- public ProgressMonitor(IProgressMonitor monitor, TypeInfoViewer viewer) {
- super(monitor);
- fViewer= viewer;
- }
- public void setTaskName(String name) {
- super.setTaskName(name);
- fName= name;
- }
- public void beginTask(String name, int totalWork) {
- super.beginTask(name, totalWork);
- if (fName == null)
- fName= name;
- fTotalWork= totalWork;
- }
- public void worked(int work) {
- super.worked(work);
- internalWorked(work);
- }
- public void done() {
- fDone= true;
- fViewer.setProgressMessage(""); //$NON-NLS-1$
- super.done();
- }
- public void internalWorked(double work) {
- fWorked= fWorked + work;
- fViewer.setProgressMessage(getMessage());
- }
- private String getMessage() {
- if (fDone) {
- return ""; //$NON-NLS-1$
- } else if (fTotalWork == 0) {
- return fName;
- } else {
- return Messages.format(
- JavaUIMessages.TypeInfoViewer_progress_label,
- new Object[] { fName, new Integer((int)((fWorked * 100) / fTotalWork)) });
- }
- }
- }
-
- private static abstract class AbstractJob extends Job {
- protected TypeInfoViewer fViewer;
- protected AbstractJob(String name, TypeInfoViewer viewer) {
- super(name);
- fViewer= viewer;
- setSystem(true);
- }
- protected final IStatus run(IProgressMonitor parent) {
- ProgressMonitor monitor= new ProgressMonitor(parent, fViewer);
- try {
- fViewer.scheduleProgressUpdateJob();
- return doRun(monitor);
- } finally {
- fViewer.stopProgressUpdateJob();
- }
- }
- protected abstract IStatus doRun(ProgressMonitor monitor);
- }
-
- private static abstract class AbstractSearchJob extends AbstractJob {
- private int fMode;
-
- protected int fTicket;
- protected TypeInfoLabelProvider fLabelProvider;
-
- protected TypeInfoFilter fFilter;
- protected OpenTypeHistory fHistory;
-
- protected AbstractSearchJob(int ticket, TypeInfoViewer viewer, TypeInfoFilter filter, OpenTypeHistory history, int numberOfVisibleItems, int mode) {
- super(JavaUIMessages.TypeInfoViewer_job_label, viewer);
- fMode= mode;
- fTicket= ticket;
- fViewer= viewer;
- fLabelProvider= fViewer.getLabelProvider();
- fFilter= filter;
- fHistory= history;
- }
- public void stop() {
- cancel();
- }
- protected IStatus doRun(ProgressMonitor monitor) {
- try {
- if (VIRTUAL) {
- internalRunVirtual(monitor);
- } else {
- internalRun(monitor);
- }
- } catch (CoreException e) {
- fViewer.searchJobFailed(fTicket, e);
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, JavaUIMessages.TypeInfoViewer_job_error, e);
- } catch (InterruptedException e) {
- return canceled(e, true);
- } catch (OperationCanceledException e) {
- return canceled(e, false);
- }
- fViewer.searchJobDone(fTicket);
- return ok();
- }
- protected abstract TypeNameMatch[] getSearchResult(Set matchIdsInHistory, ProgressMonitor monitor) throws CoreException;
-
- private void internalRun(ProgressMonitor monitor) throws CoreException, InterruptedException {
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- fViewer.clear(fTicket);
-
- // local vars to speed up rendering
- TypeNameMatch last= null;
- TypeNameMatch type= null;
- TypeNameMatch next= null;
- List elements= new ArrayList();
- List imageDescriptors= new ArrayList();
- List labels= new ArrayList();
- Set filteredMatches= new HashSet();
-
- TypeNameMatch[] matchingTypes= fHistory.getFilteredTypeInfos(fFilter);
- if (matchingTypes.length > 0) {
- Arrays.sort(matchingTypes, new TypeInfoComparator(fLabelProvider, fFilter));
- type= matchingTypes[0];
- int i= 1;
- while(type != null) {
- next= (i == matchingTypes.length) ? null : matchingTypes[i];
- elements.add(type);
- filteredMatches.add(type);
- imageDescriptors.add(fLabelProvider.getImageDescriptor(type));
- labels.add(fLabelProvider.getText(last, type, next));
- last= type;
- type= next;
- i++;
- }
- }
- matchingTypes= null;
- fViewer.fExpectedItemCount= elements.size();
- fViewer.addHistory(fTicket, elements, imageDescriptors, labels);
-
- if ((fMode & INDEX) == 0) {
- return;
- }
- TypeNameMatch[] result= getSearchResult(filteredMatches, monitor);
- fViewer.fExpectedItemCount+= result.length;
- if (result.length == 0) {
- return;
- }
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- int processed= 0;
- int nextIndex= 1;
- type= result[0];
- if (!filteredMatches.isEmpty()) {
- fViewer.addDashLineAndUpdateLastHistoryEntry(fTicket, type);
- }
- while (true) {
- long startTime= System.currentTimeMillis();
- elements.clear();
- imageDescriptors.clear();
- labels.clear();
- int delta = Math.min(nextIndex == 1 ? fViewer.getNumberOfVisibleItems() : 10, result.length - processed);
- if (delta == 0)
- break;
- processed= processed + delta;
- while(delta > 0) {
- next= (nextIndex == result.length) ? null : result[nextIndex];
- elements.add(type);
- labels.add(fLabelProvider.getText(last, type, next));
- imageDescriptors.add(fLabelProvider.getImageDescriptor(type));
- last= type;
- type= next;
- nextIndex++;
- delta--;
- }
- fViewer.addAll(fTicket, elements, imageDescriptors, labels);
- long sleep= 100 - (System.currentTimeMillis() - startTime);
- if (false)
- System.out.println("Sleeping for: " + sleep); //$NON-NLS-1$
-
- if (sleep > 0)
- Thread.sleep(sleep);
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- }
- }
- private void internalRunVirtual(ProgressMonitor monitor) throws CoreException, InterruptedException {
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- fViewer.clear(fTicket);
-
- TypeNameMatch[] matchingTypes= fHistory.getFilteredTypeInfos(fFilter);
- fViewer.setHistoryResult(fTicket, matchingTypes);
- if ((fMode & INDEX) == 0)
- return;
-
- Set filteredMatches= new HashSet(matchingTypes.length * 2);
- for (int i= 0; i < matchingTypes.length; i++) {
- filteredMatches.add(matchingTypes[i]);
- }
-
- TypeNameMatch[] result= getSearchResult(filteredMatches, monitor);
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- fViewer.setSearchResult(fTicket, result);
- }
- private IStatus canceled(Exception e, boolean removePendingItems) {
- fViewer.searchJobCanceled(fTicket, removePendingItems);
- return new Status(IStatus.CANCEL, JavaScriptPlugin.getPluginId(), IStatus.CANCEL, JavaUIMessages.TypeInfoViewer_job_cancel, e);
- }
- private IStatus ok() {
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
- }
-
- private static class SearchEngineJob extends AbstractSearchJob {
- private IJavaScriptSearchScope fScope;
- private int fElementKind;
- private SearchRequestor fReqestor;
-
- public SearchEngineJob(int ticket, TypeInfoViewer viewer, TypeInfoFilter filter, OpenTypeHistory history, int numberOfVisibleItems, int mode,
- IJavaScriptSearchScope scope, int elementKind) {
- super(ticket, viewer, filter, history, numberOfVisibleItems, mode);
- fScope= scope;
- fElementKind= elementKind;
- fReqestor= new SearchRequestor(filter);
- }
- public void stop() {
- fReqestor.cancel();
- super.stop();
- }
- protected TypeNameMatch[] getSearchResult(Set matchIdsInHistory, ProgressMonitor monitor) throws CoreException {
- long start= System.currentTimeMillis();
- fReqestor.setHistory(matchIdsInHistory);
- // consider primary working copies during searching
- SearchEngine engine= new SearchEngine((WorkingCopyOwner)null);
- String packPattern= fFilter.getPackagePattern();
- monitor.setTaskName(JavaUIMessages.TypeInfoViewer_searchJob_taskName);
- engine.searchAllTypeNames(
- packPattern == null ? null : packPattern.toCharArray(),
- fFilter.getPackageFlags(),
- fFilter.getNamePattern().toCharArray(),
- fFilter.getSearchFlags(),
- fElementKind,
- fScope,
- fReqestor,
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- monitor);
- if (DEBUG)
- System.out.println("Time needed until search has finished: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
- TypeNameMatch[] result= fReqestor.getResult();
- Arrays.sort(result, new TypeInfoComparator(fLabelProvider, fFilter));
- if (DEBUG)
- System.out.println("Time needed until sort has finished: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
- fViewer.rememberResult(fTicket, result);
- return result;
- }
- }
-
- private static class CachedResultJob extends AbstractSearchJob {
- private TypeNameMatch[] fLastResult;
- public CachedResultJob(int ticket, TypeNameMatch[] lastResult, TypeInfoViewer viewer, TypeInfoFilter filter, OpenTypeHistory history, int numberOfVisibleItems, int mode) {
- super(ticket, viewer, filter, history, numberOfVisibleItems, mode);
- fLastResult= lastResult;
- }
- protected TypeNameMatch[] getSearchResult(Set filteredHistory, ProgressMonitor monitor) throws CoreException {
- List result= new ArrayList(2048);
- for (int i= 0; i < fLastResult.length; i++) {
- TypeNameMatch type= fLastResult[i];
- if (filteredHistory.contains(type))
- continue;
- if (fFilter.matchesCachedResult(type))
- result.add(type);
- }
- // we have to sort if the filter is a camel case filter.
- TypeNameMatch[] types= (TypeNameMatch[])result.toArray(new TypeNameMatch[result.size()]);
- if (fFilter.isCamelCasePattern()) {
- Arrays.sort(types, new TypeInfoComparator(fLabelProvider, fFilter));
- }
- return types;
- }
- }
-
- private static class SyncJob extends AbstractJob {
- public SyncJob(TypeInfoViewer viewer) {
- super(JavaUIMessages.TypeInfoViewer_syncJob_label, viewer);
- }
- public void stop() {
- cancel();
- }
- protected IStatus doRun(ProgressMonitor monitor) {
- try {
- monitor.setTaskName(JavaUIMessages.TypeInfoViewer_syncJob_taskName);
- new SearchEngine().searchAllTypeNames(
- null,
- 0,
- // make sure we search a concrete name. This is faster according to Kent
- "_______________".toCharArray(), //$NON-NLS-1$
- SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
- IJavaScriptSearchConstants.ENUM,
- SearchEngine.createWorkspaceScope(),
- new TypeNameRequestor() {},
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- monitor);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, JavaUIMessages.TypeInfoViewer_job_error, e);
- } catch (OperationCanceledException e) {
- return new Status(IStatus.CANCEL, JavaScriptPlugin.getPluginId(), IStatus.CANCEL, JavaUIMessages.TypeInfoViewer_job_cancel, e);
- } finally {
- fViewer.syncJobDone();
- }
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
- }
-
- private static class DashLine {
- private int fSeparatorWidth;
- private String fMessage;
- private int fMessageLength;
- public String getText(int width) {
- StringBuffer dashes= new StringBuffer();
- int chars= (((width - fMessageLength) / fSeparatorWidth) / 2) -2;
- for (int i= 0; i < chars; i++) {
- dashes.append(SEPARATOR);
- }
- StringBuffer result= new StringBuffer();
- result.append(dashes);
- result.append(fMessage);
- result.append(dashes);
- return result.toString();
- }
- public void initialize(GC gc) {
- fSeparatorWidth= gc.getAdvanceWidth(SEPARATOR);
- fMessage= " " + JavaUIMessages.TypeInfoViewer_separator_message + " "; //$NON-NLS-1$ //$NON-NLS-2$
- fMessageLength= gc.textExtent(fMessage).x;
- }
- }
-
- private static class ImageManager {
- private Map fImages= new HashMap(20);
-
- public Image get(ImageDescriptor descriptor) {
- if (descriptor == null)
- descriptor= ImageDescriptor.getMissingImageDescriptor();
-
- Image result= (Image)fImages.get(descriptor);
- if (result != null)
- return result;
- result= descriptor.createImage();
- if (result != null)
- fImages.put(descriptor, result);
- return result;
- }
-
- public void dispose() {
- for (Iterator iter= fImages.values().iterator(); iter.hasNext(); ) {
- Image image= (Image)iter.next();
- image.dispose();
- }
- fImages.clear();
- }
- }
-
- private Display fDisplay;
-
- private String fProgressMessage;
- private Label fProgressLabel;
- private int fProgressCounter;
- private ProgressUpdateJob fProgressUpdateJob;
-
- private OpenTypeHistory fHistory;
-
- /* non virtual table */
- private int fNextElement;
- private List fItems;
-
- /* virtual table */
- private TypeNameMatch[] fHistoryMatches;
- private TypeNameMatch[] fSearchMatches;
-
- private int fNumberOfVisibleItems;
- private int fExpectedItemCount;
- private Color fDashLineColor;
- private int fScrollbarWidth;
- private int fTableWidthDelta;
- private int fDashLineIndex= -1;
- private Image fSeparatorIcon;
- private DashLine fDashLine= new DashLine();
-
- private boolean fFullyQualifySelection;
- /* remembers the last selection to restore unqualified labels */
- private TableItem[] fLastSelection;
- private String[] fLastLabels;
-
- private TypeInfoLabelProvider fLabelProvider;
- private ImageManager fImageManager;
-
- private Table fTable;
-
- private SyncJob fSyncJob;
-
- private TypeInfoFilter fTypeInfoFilter;
- private ITypeInfoFilterExtension fFilterExtension;
- private TypeNameMatch[] fLastCompletedResult;
- private TypeInfoFilter fLastCompletedFilter;
-
- private int fSearchJobTicket;
- protected int fElementKind;
- protected IJavaScriptSearchScope fSearchScope;
-
- private AbstractSearchJob fSearchJob;
-
- private static final int HISTORY= 1;
- private static final int INDEX= 2;
- private static final int FULL= HISTORY | INDEX;
-
- private static final char SEPARATOR= '-';
-
- private static final boolean DEBUG= false;
- private static final boolean VIRTUAL= false;
-
- private static final TypeNameMatch[] EMTPY_TYPE_INFO_ARRAY= new TypeNameMatch[0];
- // only needed when in virtual table mode
-
- private static final TypeNameMatch DASH_LINE= SearchEngine.createTypeNameMatch(null, 0);
-
-
- public TypeInfoViewer(Composite parent, int flags, Label progressLabel,
- IJavaScriptSearchScope scope, int elementKind, String initialFilter,
- ITypeInfoFilterExtension filterExtension, ITypeInfoImageProvider imageExtension) {
- Assert.isNotNull(scope);
- fDisplay= parent.getDisplay();
- fProgressLabel= progressLabel;
- fSearchScope= scope;
- fElementKind= elementKind;
- fFilterExtension= filterExtension;
- fFullyQualifySelection= (flags & SWT.MULTI) != 0;
- fTable= new Table(parent, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.FLAT | flags | (VIRTUAL ? SWT.VIRTUAL : SWT.NONE));
- fTable.setFont(parent.getFont());
- fLabelProvider= new TypeInfoLabelProvider(imageExtension);
- fItems= new ArrayList(500);
- fTable.setHeaderVisible(false);
- addPopupMenu();
- fTable.addControlListener(new ControlAdapter() {
- public void controlResized(ControlEvent event) {
- int itemHeight= fTable.getItemHeight();
- Rectangle clientArea= fTable.getClientArea();
- fNumberOfVisibleItems= (clientArea.height / itemHeight) + 1;
- }
- });
- fTable.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == SWT.DEL) {
- deleteHistoryEntry();
- } else if (e.keyCode == SWT.ARROW_DOWN) {
- int index= fTable.getSelectionIndex();
- if (index == fDashLineIndex - 1) {
- e.doit= false;
- setTableSelection(index + 2);
- }
- } else if (e.keyCode == SWT.ARROW_UP) {
- int index= fTable.getSelectionIndex();
- if (fDashLineIndex != -1 && index == fDashLineIndex + 1) {
- e.doit= false;
- setTableSelection(index - 2);
- }
- }
- }
- });
- fTable.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (fLastSelection != null) {
- for (int i= 0; i < fLastSelection.length; i++) {
- TableItem item= fLastSelection[i];
- // could be disposed by deleting element from
- // type info history
- if (!item.isDisposed())
- item.setText(fLastLabels[i]);
- }
- }
- TableItem[] items= fTable.getSelection();
- fLastSelection= new TableItem[items.length];
- fLastLabels= new String[items.length];
- for (int i= 0; i < items.length; i++) {
- TableItem item= items[i];
- fLastSelection[i]= item;
- fLastLabels[i]= item.getText();
- Object data= item.getData();
- if (data instanceof TypeNameMatch) {
- String qualifiedText= getQualifiedText((TypeNameMatch)data);
- if (qualifiedText.length() > fLastLabels[i].length())
- item.setText(qualifiedText);
- }
- }
- }
- });
- fTable.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- stop(true, true);
- fDashLineColor.dispose();
- fSeparatorIcon.dispose();
- fImageManager.dispose();
- if (fProgressUpdateJob != null) {
- fProgressUpdateJob.stop();
- fProgressUpdateJob= null;
- }
- }
- });
- if (VIRTUAL) {
- fHistoryMatches= EMTPY_TYPE_INFO_ARRAY;
- fSearchMatches= EMTPY_TYPE_INFO_ARRAY;
- fTable.addListener(SWT.SetData, new Listener() {
- public void handleEvent(Event event) {
- TableItem item= (TableItem)event.item;
- setData(item);
- }
- });
- }
-
- fDashLineColor= computeDashLineColor();
- fScrollbarWidth= computeScrollBarWidth();
- fTableWidthDelta= fTable.computeTrim(0, 0, 0, 0).width - fScrollbarWidth;
- fSeparatorIcon= JavaPluginImages.DESC_OBJS_TYPE_SEPARATOR.createImage(fTable.getDisplay());
- // Use a new image manager since an extension can provide its own
- // image descriptors. To avoid thread problems with SWT the registry
- // must be created in the UI thread.
- fImageManager= new ImageManager();
-
- fHistory= OpenTypeHistory.getInstance();
- if (initialFilter != null && initialFilter.length() > 0)
- fTypeInfoFilter= createTypeInfoFilter(initialFilter);
- GC gc= null;
- try {
- gc= new GC(fTable);
- gc.setFont(fTable.getFont());
- fDashLine.initialize(gc);
- } finally {
- gc.dispose();
- }
- // If we do have a type info filter then we are
- // scheduling a search job in startup. So no
- // need to sync the search indices.
- if (fTypeInfoFilter == null) {
- scheduleSyncJob();
- }
- }
-
- /* package */ void startup() {
- if (fTypeInfoFilter == null) {
- reset();
- } else {
- scheduleSearchJob(FULL);
- }
- }
-
- public Table getTable() {
- return fTable;
- }
-
- /* package */ TypeInfoLabelProvider getLabelProvider() {
- return fLabelProvider;
- }
-
- private int getNumberOfVisibleItems() {
- return fNumberOfVisibleItems;
- }
-
- public void setFocus() {
- fTable.setFocus();
- }
-
-
- public void setQualificationStyle(boolean value) {
- if (fFullyQualifySelection == value)
- return;
- fFullyQualifySelection= value;
- if (fLastSelection != null) {
- for (int i= 0; i < fLastSelection.length; i++) {
- TableItem item= fLastSelection[i];
- Object data= item.getData();
- if (data instanceof TypeNameMatch) {
- item.setText(getQualifiedText((TypeNameMatch)data));
- }
- }
- }
- }
-
- public TypeNameMatch[] getSelection() {
- TableItem[] items= fTable.getSelection();
- List result= new ArrayList(items.length);
- for (int i= 0; i < items.length; i++) {
- Object data= items[i].getData();
- if (data instanceof TypeNameMatch) {
- result.add(data);
- }
- }
- return (TypeNameMatch[])result.toArray(new TypeNameMatch[result.size()]);
- }
-
- public void stop() {
- stop(true, false);
- }
-
- public void stop(boolean stopSyncJob, boolean dispose) {
- if (fSyncJob != null && stopSyncJob) {
- fSyncJob.stop();
- fSyncJob= null;
- }
- if (fSearchJob != null) {
- fSearchJob.stop();
- fSearchJob= null;
- }
- }
-
- public void forceSearch() {
- stop(false, false);
- if (fTypeInfoFilter == null) {
- reset();
- } else {
- // clear last results
- fLastCompletedFilter= null;
- fLastCompletedResult= null;
- scheduleSearchJob(isSyncJobRunning() ? HISTORY : FULL);
- }
- }
-
- public void setSearchPattern(String text) {
- stop(false, false);
- if (text.length() == 0 || "*".equals(text)) { //$NON-NLS-1$
- fTypeInfoFilter= null;
- reset();
- } else {
- fTypeInfoFilter= createTypeInfoFilter(text);
- scheduleSearchJob(isSyncJobRunning() ? HISTORY : FULL);
- }
- }
-
- public void setSearchScope(IJavaScriptSearchScope scope, boolean refresh) {
- fSearchScope= scope;
- if (!refresh)
- return;
- stop(false, false);
- fLastCompletedFilter= null;
- fLastCompletedResult= null;
- if (fTypeInfoFilter == null) {
- reset();
- } else {
- scheduleSearchJob(isSyncJobRunning() ? HISTORY : FULL);
- }
- }
-
- public void setFullyQualifyDuplicates(boolean value, boolean refresh) {
- fLabelProvider.setFullyQualifyDuplicates(value);
- if (!refresh)
- return;
- stop(false, false);
- if (fTypeInfoFilter == null) {
- reset();
- } else {
- scheduleSearchJob(isSyncJobRunning() ? HISTORY : FULL);
- }
- }
-
- public void reset() {
- fLastSelection= null;
- fLastLabels= null;
- fExpectedItemCount= 0;
- fDashLineIndex= -1;
- TypeInfoFilter filter= (fTypeInfoFilter != null)
- ? fTypeInfoFilter
- : new TypeInfoFilter("*", fSearchScope, fElementKind, fFilterExtension); //$NON-NLS-1$
- if (VIRTUAL) {
- fHistoryMatches= fHistory.getFilteredTypeInfos(filter);
- fExpectedItemCount= fHistoryMatches.length;
- fTable.setItemCount(fHistoryMatches.length);
- // bug under windows.
- if (fHistoryMatches.length == 0) {
- fTable.redraw();
- }
- fTable.clear(0, fHistoryMatches.length - 1);
- } else {
- fNextElement= 0;
- TypeNameMatch[] historyItems= fHistory.getFilteredTypeInfos(filter);
- if (historyItems.length == 0) {
- shortenTable();
- return;
- }
- fExpectedItemCount= historyItems.length;
- int lastIndex= historyItems.length - 1;
- TypeNameMatch last= null;
- TypeNameMatch type= historyItems[0];
- for (int i= 0; i < historyItems.length; i++) {
- TypeNameMatch next= i == lastIndex ? null : historyItems[i + 1];
- addSingleElement(type,
- fLabelProvider.getImageDescriptor(type),
- fLabelProvider.getText(last, type, next));
- last= type;
- type= next;
- }
- shortenTable();
- }
- }
-
- protected TypeInfoFilter createTypeInfoFilter(String text) {
- if ("**".equals(text)) //$NON-NLS-1$
- text= "*"; //$NON-NLS-1$
- return new TypeInfoFilter(text, fSearchScope, fElementKind, fFilterExtension);
- }
-
- private void addPopupMenu() {
- Menu menu= new Menu(fTable.getShell(), SWT.POP_UP);
- fTable.setMenu(menu);
- final MenuItem remove= new MenuItem(menu, SWT.NONE);
- remove.setText(JavaUIMessages.TypeInfoViewer_remove_from_history);
- menu.addMenuListener(new MenuAdapter() {
- public void menuShown(MenuEvent e) {
- TableItem[] selection= fTable.getSelection();
- remove.setEnabled(canEnable(selection));
- }
- });
- remove.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- deleteHistoryEntry();
- }
- });
- }
-
- private boolean canEnable(TableItem[] selection) {
- if (selection.length == 0)
- return false;
- for (int i= 0; i < selection.length; i++) {
- TableItem item= selection[i];
- Object data= item.getData();
- if (!(data instanceof TypeNameMatch))
- return false;
- if (!(fHistory.contains((TypeNameMatch)data)))
- return false;
- }
- return true;
- }
-
- //---- History management -------------------------------------------------------
-
- private void deleteHistoryEntry() {
- int index= fTable.getSelectionIndex();
- if (index == -1)
- return;
- TableItem item= fTable.getItem(index);
- Object element= item.getData();
- if (!(element instanceof TypeNameMatch))
- return;
- if (fHistory.remove(element) != null) {
- item.dispose();
- fItems.remove(index);
- int count= fTable.getItemCount();
- if (count > 0) {
- item= fTable.getItem(0);
- if (item.getData() instanceof DashLine) {
- item.dispose();
- fItems.remove(0);
- fDashLineIndex= -1;
- if (count > 1) {
- setTableSelection(0);
- }
- } else {
- if (index >= count) {
- index= count - 1;
- }
- setTableSelection(index);
- }
- } else {
- // send dummy selection
- fTable.notifyListeners(SWT.Selection, new Event());
- }
- }
- }
-
- //-- Search result updating ----------------------------------------------------
-
- private void clear(int ticket) {
- syncExec(ticket, new Runnable() {
- public void run() {
- fNextElement= 0;
- fDashLineIndex= -1;
- fLastSelection= null;
- fLastLabels= null;
- fExpectedItemCount= 0;
- }
- });
- }
-
- private void rememberResult(int ticket, final TypeNameMatch[] result) {
- syncExec(ticket, new Runnable() {
- public void run() {
- if (fLastCompletedResult == null) {
- fLastCompletedFilter= fTypeInfoFilter;
- fLastCompletedResult= result;
- }
- }
- });
- }
-
- private void addHistory(int ticket, final List elements, final List imageDescriptors, final List labels) {
- addAll(ticket, elements, imageDescriptors, labels);
- }
-
- private void addAll(int ticket, final List elements, final List imageDescriptors, final List labels) {
- syncExec(ticket, new Runnable() {
- public void run() {
- int size= elements.size();
- for(int i= 0; i < size; i++) {
- addSingleElement(elements.get(i),
- (ImageDescriptor)imageDescriptors.get(i),
- (String)labels.get(i));
- }
- }
- });
- }
-
- private void addDashLineAndUpdateLastHistoryEntry(int ticket, final TypeNameMatch next) {
- syncExec(ticket, new Runnable() {
- public void run() {
- if (fNextElement > 0) {
- TableItem item= fTable.getItem(fNextElement - 1);
- String label= item.getText();
- String newLabel= fLabelProvider.getText(null, (TypeNameMatch)item.getData(), next);
- if (newLabel.length() != label.length())
- item.setText(newLabel);
- if (fLastSelection != null && fLastSelection.length > 0) {
- TableItem last= fLastSelection[fLastSelection.length - 1];
- if (last == item) {
- fLastLabels[fLastLabels.length - 1]= newLabel;
- }
- }
- }
- fDashLineIndex= fNextElement;
- addDashLine();
- }
- });
- }
-
- private void addDashLine() {
- TableItem item= null;
- if (fItems.size() > fNextElement) {
- item= (TableItem)fItems.get(fNextElement);
- } else {
- item= new TableItem(fTable, SWT.NONE);
- fItems.add(item);
- }
- fillDashLine(item);
- fNextElement++;
- }
-
- private void addSingleElement(Object element, ImageDescriptor imageDescriptor, String label) {
- TableItem item= null;
- Object old= null;
- if (fItems.size() > fNextElement) {
- item= (TableItem)fItems.get(fNextElement);
- old= item.getData();
- item.setForeground(null);
- } else {
- item= new TableItem(fTable, SWT.NONE);
- fItems.add(item);
- }
- item.setData(element);
- item.setImage(fImageManager.get(imageDescriptor));
- if (fNextElement == 0) {
- if (needsSelectionChange(old, element) || fLastSelection != null) {
- item.setText(label);
- fTable.setSelection(0);
- fTable.notifyListeners(SWT.Selection, new Event());
- } else {
- fLastSelection= new TableItem[] { item };
- fLastLabels= new String[] { label };
- }
- } else {
- item.setText(label);
- }
- fNextElement++;
- }
-
- private boolean needsSelectionChange(Object oldElement, Object newElement) {
- int[] selected= fTable.getSelectionIndices();
- if (selected.length != 1)
- return true;
- if (selected[0] != 0)
- return true;
- if (oldElement == null)
- return true;
- return !oldElement.equals(newElement);
- }
-
- private void scheduleSearchJob(int mode) {
- fSearchJobTicket++;
- if (fLastCompletedFilter != null && fTypeInfoFilter.isSubFilter(fLastCompletedFilter.getText())) {
- fSearchJob= new CachedResultJob(fSearchJobTicket, fLastCompletedResult, this, fTypeInfoFilter,
- fHistory, fNumberOfVisibleItems,
- mode);
- } else {
- fLastCompletedFilter= null;
- fLastCompletedResult= null;
- fSearchJob= new SearchEngineJob(fSearchJobTicket, this, fTypeInfoFilter,
- fHistory, fNumberOfVisibleItems,
- mode, fSearchScope, fElementKind);
- }
- fSearchJob.schedule();
- }
-
- private void searchJobDone(int ticket) {
- syncExec(ticket, new Runnable() {
- public void run() {
- shortenTable();
- checkEmptyList();
- fSearchJob= null;
- }
- });
- }
-
- private void searchJobCanceled(int ticket, final boolean removePendingItems) {
- syncExec(ticket, new Runnable() {
- public void run() {
- if (removePendingItems) {
- shortenTable();
- checkEmptyList();
- }
- fSearchJob= null;
- }
- });
- }
-
- private synchronized void searchJobFailed(int ticket, CoreException e) {
- searchJobDone(ticket);
- JavaScriptPlugin.log(e);
- }
-
- //-- virtual table support -------------------------------------------------------
-
- private void setHistoryResult(int ticket, final TypeNameMatch[] types) {
- syncExec(ticket, new Runnable() {
- public void run() {
- fExpectedItemCount= types.length;
- int lastHistoryLength= fHistoryMatches.length;
- fHistoryMatches= types;
- int length= fHistoryMatches.length + fSearchMatches.length;
- int dash= (fHistoryMatches.length > 0 && fSearchMatches.length > 0) ? 1 : 0;
- fTable.setItemCount(length + dash);
- if (length == 0) {
- // bug under windows.
- fTable.redraw();
- return;
- }
- int update= Math.max(lastHistoryLength, fHistoryMatches.length);
- if (update > 0) {
- fTable.clear(0, update + dash - 1);
- }
- }
- });
- }
-
- private void setSearchResult(int ticket, final TypeNameMatch[] types) {
- syncExec(ticket, new Runnable() {
- public void run() {
- fExpectedItemCount+= types.length;
- fSearchMatches= types;
- int length= fHistoryMatches.length + fSearchMatches.length;
- int dash= (fHistoryMatches.length > 0 && fSearchMatches.length > 0) ? 1 : 0;
- fTable.setItemCount(length + dash);
- if (length == 0) {
- // bug under windows.
- fTable.redraw();
- return;
- }
- if (fHistoryMatches.length == 0) {
- fTable.clear(0, length + dash - 1);
- } else {
- fTable.clear(fHistoryMatches.length - 1, length + dash - 1);
- }
- }
- });
- }
-
- private void setData(TableItem item) {
- int index= fTable.indexOf(item);
- TypeNameMatch type= getTypeInfo(index);
- if (type == DASH_LINE) {
- item.setData(fDashLine);
- fillDashLine(item);
- } else {
- item.setData(type);
- item.setImage(fImageManager.get(fLabelProvider.getImageDescriptor(type)));
- item.setText(fLabelProvider.getText(
- getTypeInfo(index - 1),
- type,
- getTypeInfo(index + 1)));
- item.setForeground(null);
- }
- }
-
- private TypeNameMatch getTypeInfo(int index) {
- if (index < 0)
- return null;
- if (index < fHistoryMatches.length) {
- return fHistoryMatches[index];
- }
- int dash= (fHistoryMatches.length > 0 && fSearchMatches.length > 0) ? 1 : 0;
- if (index == fHistoryMatches.length && dash == 1) {
- return DASH_LINE;
- }
- index= index - fHistoryMatches.length - dash;
- if (index >= fSearchMatches.length)
- return null;
- return fSearchMatches[index];
- }
-
- //-- Sync Job updates ------------------------------------------------------------
-
- private void scheduleSyncJob() {
- fSyncJob= new SyncJob(this);
- fSyncJob.schedule();
- }
-
- private void syncJobDone() {
- syncExec(new Runnable() {
- public void run() {
- fSyncJob= null;
- if (fTypeInfoFilter != null) {
- scheduleSearchJob(FULL);
- }
- }
- });
- }
-
- private boolean isSyncJobRunning() {
- return fSyncJob != null;
- }
-
- //-- progress monitor updates -----------------------------------------------------
-
- private void scheduleProgressUpdateJob() {
- syncExec(new Runnable() {
- public void run() {
- if (fProgressCounter == 0) {
- clearProgressMessage();
- fProgressUpdateJob= new ProgressUpdateJob(fDisplay, TypeInfoViewer.this);
- fProgressUpdateJob.schedule(300);
- }
- fProgressCounter++;
- }
- });
- }
-
- private void stopProgressUpdateJob() {
- syncExec(new Runnable() {
- public void run() {
- fProgressCounter--;
- if (fProgressCounter == 0 && fProgressUpdateJob != null) {
- fProgressUpdateJob.stop();
- fProgressUpdateJob= null;
- clearProgressMessage();
- }
- }
- });
- }
-
- private void setProgressMessage(String message) {
- fProgressMessage= message;
- }
-
- private void clearProgressMessage() {
- fProgressMessage= ""; //$NON-NLS-1$
- fProgressLabel.setText(fProgressMessage);
- }
-
- private void updateProgressMessage() {
- fProgressLabel.setText(fProgressMessage);
- }
-
- //-- Helper methods --------------------------------------------------------------
-
- private void syncExec(final Runnable runnable) {
- if (fDisplay.isDisposed())
- return;
- fDisplay.syncExec(new Runnable() {
- public void run() {
- if (fTable.isDisposed())
- return;
- runnable.run();
- }
- });
- }
-
- private void syncExec(final int ticket, final Runnable runnable) {
- if (fDisplay.isDisposed())
- return;
- fDisplay.syncExec(new Runnable() {
- public void run() {
- if (fTable.isDisposed() || ticket != fSearchJobTicket)
- return;
- runnable.run();
- }
- });
- }
-
- private void fillDashLine(TableItem item) {
- Rectangle bounds= item.getImageBounds(0);
- Rectangle area= fTable.getBounds();
- boolean willHaveScrollBar= fExpectedItemCount + 1 > fNumberOfVisibleItems;
- item.setText(fDashLine.getText(area.width - bounds.x - bounds.width - fTableWidthDelta -
- (willHaveScrollBar ? fScrollbarWidth : 0)));
- item.setImage(fSeparatorIcon);
- item.setForeground(fDashLineColor);
- item.setData(fDashLine);
- }
-
- private void shortenTable() {
- if (VIRTUAL)
- return;
- if (fNextElement < fItems.size()) {
- fTable.setRedraw(false);
- fTable.remove(fNextElement, fItems.size() - 1);
- fTable.setRedraw(true);
- }
- for (int i= fItems.size() - 1; i >= fNextElement; i--) {
- fItems.remove(i);
- }
- }
-
- private void checkEmptyList() {
- if (fTable.getItemCount() == 0) {
- fTable.notifyListeners(SWT.Selection, new Event());
- }
- }
-
- private void setTableSelection(int index) {
- fTable.setSelection(index);
- fTable.notifyListeners(SWT.Selection, new Event());
- }
-
- private Color computeDashLineColor() {
- Color fg= fTable.getForeground();
- int fGray= (int)(0.3*fg.getRed() + 0.59*fg.getGreen() + 0.11*fg.getBlue());
- Color bg= fTable.getBackground();
- int bGray= (int)(0.3*bg.getRed() + 0.59*bg.getGreen() + 0.11*bg.getBlue());
- int gray= (int)((fGray + bGray) * 0.66);
- return new Color(fDisplay, gray, gray, gray);
- }
-
- private int computeScrollBarWidth() {
- Composite t= new Composite(fTable.getShell(), SWT.V_SCROLL);
- int result= t.computeTrim(0, 0, 0, 0).width;
- t.dispose();
- return result;
- }
-
- private String getQualifiedText(TypeNameMatch type) {
- return fFullyQualifySelection
- ? fLabelProvider.getFullyQualifiedText(type)
- : fLabelProvider.getQualifiedText(type);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionComponent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionComponent.java
deleted file mode 100644
index 5b794ce2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionComponent.java
+++ /dev/null
@@ -1,437 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.dialogs.DialogSettings;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.accessibility.AccessibleAdapter;
-import org.eclipse.swt.accessibility.AccessibleEvent;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.custom.ViewForm;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.XMLMemento;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
-import org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-
-/**
- * @deprecated use {@link FilteredTypesSelectionDialog}
- */
-public class TypeSelectionComponent extends Composite implements ITypeSelectionComponent {
-
- private IDialogSettings fSettings;
- private boolean fMultipleSelection;
- private ITitleLabel fTitleLabel;
-
- private ToolBar fToolBar;
- private ToolItem fToolItem;
- private MenuManager fMenuManager;
- private WorkingSetFilterActionGroup fFilterActionGroup;
-
- private TypeSelectionExtension fTypeSelectionExtension;
- private Text fFilter;
- private String fInitialFilterText;
- private IJavaScriptSearchScope fScope;
- private TypeInfoViewer fViewer;
- private ViewForm fForm;
- private CLabel fLabel;
-
- public static final int NONE= 0;
- public static final int CARET_BEGINNING= 1;
- public static final int FULL_SELECTION= 2;
-
- private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.TypeSelectionComponent"; //$NON-NLS-1$
- private static final String SHOW_STATUS_LINE= "show_status_line"; //$NON-NLS-1$
- private static final String FULLY_QUALIFY_DUPLICATES= "fully_qualify_duplicates"; //$NON-NLS-1$
- private static final String WORKINGS_SET_SETTINGS= "workingset_settings"; //$NON-NLS-1$
-
- private class ToggleStatusLineAction extends Action {
- public ToggleStatusLineAction() {
- super(JavaUIMessages.TypeSelectionComponent_show_status_line_label, IAction.AS_CHECK_BOX);
- }
- public void run() {
- if (fForm == null)
- return;
- GridData gd= (GridData)fForm.getLayoutData();
- boolean checked= isChecked();
- gd.exclude= !checked;
- fForm.setVisible(checked);
- fSettings.put(SHOW_STATUS_LINE, checked);
- TypeSelectionComponent.this.layout();
- }
- }
-
- private class FullyQualifyDuplicatesAction extends Action {
- public FullyQualifyDuplicatesAction() {
- super(JavaUIMessages.TypeSelectionComponent_fully_qualify_duplicates_label, IAction.AS_CHECK_BOX);
- }
- public void run() {
- boolean checked= isChecked();
- fViewer.setFullyQualifyDuplicates(checked, true);
- fSettings.put(FULLY_QUALIFY_DUPLICATES, checked);
- }
- }
-
- /**
- * Special interface to access a title lable in
- * a generic fashion.
- */
- public interface ITitleLabel {
- /**
- * Sets the title to the given text
- *
- * @param text the title text
- */
- public void setText(String text);
- }
-
- public TypeSelectionComponent(Composite parent, int style, String message, boolean multi,
- IJavaScriptSearchScope scope, int elementKind, String initialFilter, ITitleLabel titleLabel,
- TypeSelectionExtension extension) {
- super(parent, style);
- setFont(parent.getFont());
- fMultipleSelection= multi;
- fScope= scope;
- fInitialFilterText= initialFilter;
- fTitleLabel= titleLabel;
- fTypeSelectionExtension= extension;
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- fSettings= settings.getSection(DIALOG_SETTINGS);
- if (fSettings == null) {
- fSettings= new DialogSettings(DIALOG_SETTINGS);
- settings.addSection(fSettings);
- }
- if (fSettings.get(SHOW_STATUS_LINE) == null) {
- fSettings.put(SHOW_STATUS_LINE, true);
- }
- createContent(message, elementKind);
- }
-
- public void triggerSearch() {
- fViewer.forceSearch();
- }
-
- public TypeNameMatch[] getSelection() {
- return fViewer.getSelection();
- }
-
- public IJavaScriptSearchScope getScope() {
- return fScope;
- }
-
- private void createContent(final String message, int elementKind) {
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0; layout.marginHeight= 0;
- setLayout(layout);
- Font font= getFont();
-
- Control header= createHeader(this, font, message);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- header.setLayoutData(gd);
-
- fFilter= new Text(this, SWT.BORDER | SWT.FLAT);
- fFilter.setFont(font);
- if (fInitialFilterText != null) {
- fFilter.setText(fInitialFilterText);
- }
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- fFilter.setLayoutData(gd);
- fFilter.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- patternChanged((Text)e.widget);
- }
- });
- fFilter.addKeyListener(new KeyListener() {
- public void keyReleased(KeyEvent e) {
- }
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == SWT.ARROW_DOWN) {
- fViewer.setFocus();
- }
- }
- });
- fFilter.getAccessible().addAccessibleListener(new AccessibleAdapter() {
- public void getName(AccessibleEvent e) {
- e.result= Strings.removeMnemonicIndicator(message);
- }
- });
- TextFieldNavigationHandler.install(fFilter);
-
- Label label= new Label(this, SWT.NONE);
- label.setFont(font);
- label.setText(JavaUIMessages.TypeSelectionComponent_label);
- label.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_MNEMONIC && e.doit) {
- e.detail= SWT.TRAVERSE_NONE;
- fViewer.setFocus();
- }
- }
- });
- label= new Label(this, SWT.RIGHT);
- label.setFont(font);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- label.setLayoutData(gd);
- fViewer= new TypeInfoViewer(this, fMultipleSelection ? SWT.MULTI : SWT.NONE, label,
- fScope, elementKind, fInitialFilterText,
- fTypeSelectionExtension != null ? fTypeSelectionExtension.getFilterExtension() : null,
- fTypeSelectionExtension != null ? fTypeSelectionExtension.getImageProvider() : null);
- gd= new GridData(GridData.FILL_BOTH);
- final Table table= fViewer.getTable();
- PixelConverter converter= new PixelConverter(table);
- gd.widthHint= converter.convertWidthInCharsToPixels(70);
- gd.heightHint= SWTUtil.getTableHeightHint(table, 10);
- gd.horizontalSpan= 2;
- table.setLayoutData(gd);
- table.getAccessible().addAccessibleListener(new AccessibleAdapter() {
- public void getName(AccessibleEvent e) {
- if (table.getSelectionCount() == 0) {
- e.result= Strings.removeMnemonicIndicator(JavaUIMessages.TypeSelectionComponent_label);
- }
- }
- });
- fViewer.setFullyQualifyDuplicates(fSettings.getBoolean(FULLY_QUALIFY_DUPLICATES), false);
- if (fTypeSelectionExtension != null) {
- Control addition= fTypeSelectionExtension.createContentArea(this);
- if (addition != null) {
- addition.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
- }
- if (!fMultipleSelection) {
- fForm= new ViewForm(this, SWT.BORDER | SWT.FLAT);
- fForm.setFont(font);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- boolean showStatusLine= fSettings.getBoolean(SHOW_STATUS_LINE);
- gd.exclude= !showStatusLine;
- fForm.setVisible(showStatusLine);
- fForm.setLayoutData(gd);
- fLabel= new CLabel(fForm, SWT.FLAT);
- fLabel.setFont(fForm.getFont());
- fForm.setContent(fLabel);
- table.addSelectionListener(new SelectionAdapter() {
- private TypeNameMatchLabelProvider fLabelProvider= new TypeNameMatchLabelProvider(
- TypeNameMatchLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeNameMatchLabelProvider.SHOW_ROOT_POSTFIX);
- public void widgetSelected(SelectionEvent event) {
- TypeNameMatch[] selection= fViewer.getSelection();
- if (selection.length != 1) {
- fLabel.setText(""); //$NON-NLS-1$
- fLabel.setImage(null);
- } else {
- TypeNameMatch type= selection[0];
- fLabel.setText(fViewer.getLabelProvider().getQualificationText(type));
- fLabel.setImage(fLabelProvider.getImage(type));
- }
- }
- });
- }
- addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent event) {
- disposeComponent();
- }
- });
- if (fTypeSelectionExtension != null) {
- fTypeSelectionExtension.initialize(this);
- }
- }
-
- public void addSelectionListener(SelectionListener listener) {
- fViewer.getTable().addSelectionListener(listener);
- }
-
- public void populate(int selectionMode) {
- if (fInitialFilterText != null) {
- switch(selectionMode) {
- case CARET_BEGINNING:
- fFilter.setSelection(0, 0);
- break;
- case FULL_SELECTION:
- fFilter.setSelection(0, fInitialFilterText.length());
- break;
- }
- }
- fFilter.setFocus();
- fViewer.startup();
- }
-
- private void patternChanged(Text text) {
- fViewer.setSearchPattern(text.getText());
- }
-
- private Control createHeader(Composite parent, Font font, String message) {
- Composite header= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0; layout.marginHeight= 0;
- header.setLayout(layout);
- header.setFont(font);
- Label label= new Label(header, SWT.NONE);
- label.setText(message);
- label.setFont(font);
- label.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_MNEMONIC && e.doit) {
- e.detail= SWT.TRAVERSE_NONE;
- fFilter.setFocus();
- }
- }
- });
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- label.setLayoutData(gd);
-
- createViewMenu(header);
- return header;
- }
-
- private void createViewMenu(Composite parent) {
- fToolBar= new ToolBar(parent, SWT.FLAT);
- fToolItem= new ToolItem(fToolBar, SWT.PUSH, 0);
-
- GridData data= new GridData();
- data.horizontalAlignment= GridData.END;
- fToolBar.setLayoutData(data);
-
- fToolItem.setImage(JavaPluginImages.get(JavaPluginImages.IMG_ELCL_VIEW_MENU));
- fToolItem.setDisabledImage(JavaPluginImages.get(JavaPluginImages.IMG_DLCL_VIEW_MENU));
- fToolItem.setToolTipText(JavaUIMessages.TypeSelectionComponent_menu);
- fToolItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- showViewMenu();
- }
- });
-
- fMenuManager= new MenuManager();
- fillViewMenu(fMenuManager);
-
- // ICommandService commandService= (ICommandService)PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- // IHandlerService handlerService= (IHandlerService)PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
- }
-
- private void showViewMenu() {
- Menu menu = fMenuManager.createContextMenu(getShell());
- Rectangle bounds = fToolItem.getBounds();
- Point topLeft = new Point(bounds.x, bounds.y + bounds.height);
- topLeft = fToolBar.toDisplay(topLeft);
- menu.setLocation(topLeft.x, topLeft.y);
- menu.setVisible(true);
- }
-
- private void fillViewMenu(IMenuManager viewMenu) {
- if (!fMultipleSelection) {
- ToggleStatusLineAction showStatusLineAction= new ToggleStatusLineAction();
- showStatusLineAction.setChecked(fSettings.getBoolean(SHOW_STATUS_LINE));
- viewMenu.add(showStatusLineAction);
- }
- FullyQualifyDuplicatesAction fullyQualifyDuplicatesAction= new FullyQualifyDuplicatesAction();
- fullyQualifyDuplicatesAction.setChecked(fSettings.getBoolean(FULLY_QUALIFY_DUPLICATES));
- viewMenu.add(fullyQualifyDuplicatesAction);
- if (fScope == null) {
- fFilterActionGroup= new WorkingSetFilterActionGroup(getShell(),
- JavaScriptPlugin.getActivePage(),
- new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- IWorkingSet ws= (IWorkingSet)event.getNewValue();
- if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
- fScope= SearchEngine.createWorkspaceScope();
- fTitleLabel.setText(null);
- } else {
- fScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true);
- fTitleLabel.setText(ws.getLabel());
- }
- fViewer.setSearchScope(fScope, true);
- }
- });
- String setting= fSettings.get(WORKINGS_SET_SETTINGS);
- if (setting != null) {
- try {
- IMemento memento= XMLMemento.createReadRoot(new StringReader(setting));
- fFilterActionGroup.restoreState(memento);
- } catch (WorkbenchException e) {
- }
- }
- IWorkingSet ws= fFilterActionGroup.getWorkingSet();
- if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
- fScope= SearchEngine.createWorkspaceScope();
- fTitleLabel.setText(null);
- } else {
- fScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true);
- fTitleLabel.setText(ws.getLabel());
- }
- fFilterActionGroup.fillViewMenu(viewMenu);
- }
- }
-
- private void disposeComponent() {
- if (fFilterActionGroup != null) {
- XMLMemento memento= XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$
- fFilterActionGroup.saveState(memento);
- fFilterActionGroup.dispose();
- StringWriter writer= new StringWriter();
- try {
- memento.save(writer);
- fSettings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString());
- } catch (IOException e) {
- // don't do anything. Simply don't store the settings
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java
deleted file mode 100644
index b77d0505..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui.dialogs;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.IJobManager;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.core.search.TypeNameRequestor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-
-/**
- * @deprecated use {@link FilteredTypesSelectionDialog}
- */
-public class TypeSelectionDialog2 extends SelectionStatusDialog {
-
- private String fTitle;
-
- private boolean fMultipleSelection;
- private IRunnableContext fRunnableContext;
- private IJavaScriptSearchScope fScope;
- private int fElementKind;
-
- private String fInitialFilter;
- private int fSelectionMode;
- private ISelectionStatusValidator fValidator;
- private TypeSelectionComponent fContent;
- private TypeSelectionExtension fExtension;
-
- public static final int NONE= TypeSelectionComponent.NONE;
- public static final int CARET_BEGINNING= TypeSelectionComponent.CARET_BEGINNING;
- public static final int FULL_SELECTION= TypeSelectionComponent.FULL_SELECTION;
-
- private static boolean fgFirstTime= true;
-
- private class TitleLabel implements TypeSelectionComponent.ITitleLabel {
- public void setText(String text) {
- if (text == null || text.length() == 0) {
- getShell().setText(fTitle);
- } else {
- getShell().setText(Messages.format(
- JavaUIMessages.TypeSelectionDialog2_title_format,
- new String[] { fTitle, text}));
- }
- }
- }
-
- public TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context,
- IJavaScriptSearchScope scope, int elementKinds) {
- this(parent, multi, context, scope, elementKinds, null);
- }
-
- public TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context,
- IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
- fMultipleSelection= multi;
- fRunnableContext= context;
- fScope= scope;
- fElementKind= elementKinds;
- fSelectionMode= NONE;
- fExtension= extension;
- if (fExtension != null) {
- fValidator= fExtension.getSelectionValidator();
- }
- }
-
- public void setFilter(String filter) {
- setFilter(filter, FULL_SELECTION);
- }
-
- public void setFilter(String filter, int selectionMode) {
- fInitialFilter= filter;
- fSelectionMode= selectionMode;
- }
-
- public void setValidator(ISelectionStatusValidator validator) {
- fValidator= validator;
- }
-
- protected TypeNameMatch[] getSelectedTypes() {
- if (fContent == null || fContent.isDisposed())
- return null;
- return fContent.getSelection();
- }
-
- public void create() {
- super.create();
- fContent.populate(fSelectionMode);
- getOkButton().setEnabled(fContent.getSelection().length > 0);
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.TYPE_SELECTION_DIALOG2);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite area= (Composite)super.createDialogArea(parent);
- fContent= new TypeSelectionComponent(area, SWT.NONE, getMessage(),
- fMultipleSelection, fScope, fElementKind, fInitialFilter,
- new TitleLabel(), fExtension);
- GridData gd= new GridData(GridData.FILL_BOTH);
- fContent.setLayoutData(gd);
- fContent.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- handleDefaultSelected(fContent.getSelection());
- }
- public void widgetSelected(SelectionEvent e) {
- handleWidgetSelected(fContent.getSelection());
- }
- });
- return area;
- }
-
- protected void handleDefaultSelected(TypeNameMatch[] selection) {
- if (selection.length == 0)
- return;
- okPressed();
- }
-
- protected void handleWidgetSelected(TypeNameMatch[] selection) {
- IStatus status= null;
- if (selection.length == 0) {
- status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, "",null); //$NON-NLS-1$
- } else {
- if (fValidator != null) {
- List jElements= new ArrayList();
- for (int i= 0; i < selection.length; i++) {
- IType type= selection[i].getType();
- if (type != null) {
- jElements.add(type);
- } else {
- status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- Messages.format(JavaUIMessages.TypeSelectionDialog_error_type_doesnot_exist, selection[i].getFullyQualifiedName()),
- null);
- break;
- }
- }
- if (status == null) {
- status= fValidator.validate(jElements.toArray());
- }
- } else {
- status= new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "",null); //$NON-NLS-1$
- }
- }
- updateStatus(status);
- }
-
- public int open() {
- try {
- ensureConsistency();
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, JavaUIMessages.TypeSelectionDialog_error3Title, JavaUIMessages.TypeSelectionDialog_error3Message);
- return CANCEL;
- } catch (InterruptedException e) {
- // cancelled by user
- return CANCEL;
- }
- if (fInitialFilter == null) {
- IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (window != null) {
- ISelection selection= window.getSelectionService().getSelection();
- if (selection instanceof ITextSelection) {
- String text= ((ITextSelection)selection).getText();
- if (text != null) {
- text= text.trim();
- if (text.length() > 0 && JavaScriptConventions.validateJavaScriptTypeName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3).isOK()) {
- fInitialFilter= text;
- fSelectionMode= FULL_SELECTION;
- }
- }
- }
- }
- }
- return super.open();
- }
-
- public boolean close() {
- boolean result;
- try {
- if (getReturnCode() == OK) {
- OpenTypeHistory.getInstance().save();
- }
- } finally {
- result= super.close();
- }
- return result;
- }
-
- public void setTitle(String title) {
- super.setTitle(title);
- fTitle= title;
- }
-
- protected void computeResult() {
- TypeNameMatch[] selected= fContent.getSelection();
- if (selected == null || selected.length == 0) {
- setResult(null);
- return;
- }
-
- // If the scope is null then it got computed by the type selection component.
- if (fScope == null) {
- fScope= fContent.getScope();
- }
-
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- List result= new ArrayList(selected.length);
- for (int i= 0; i < selected.length; i++) {
- TypeNameMatch typeInfo= selected[i];
- IType type= typeInfo.getType();
- if (!type.exists()) {
- String title= JavaUIMessages.TypeSelectionDialog_errorTitle;
- IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot();
- String containerName= JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED);
- String message= Messages.format(JavaUIMessages.TypeSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName });
- MessageDialog.openError(getShell(), title, message);
- history.remove(typeInfo);
- setResult(null);
- } else {
- history.accessed(typeInfo);
- result.add(type);
- }
- }
- setResult(result);
- }
-
- private void ensureConsistency() throws InvocationTargetException, InterruptedException {
- // we only have to ensure history consistency here since the search engine
- // takes care of working copies.
- class ConsistencyRunnable implements IRunnableWithProgress {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- if (fgFirstTime) {
- // Join the initialize after load job.
- IJobManager manager= Job.getJobManager();
- manager.join(JavaScriptUI.ID_PLUGIN, monitor);
- }
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- if (fgFirstTime || history.isEmpty()) {
- monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100);
- if (history.needConsistencyCheck()) {
- refreshSearchIndices(new SubProgressMonitor(monitor, 90));
- history.checkConsistency(new SubProgressMonitor(monitor, 10));
- } else {
- refreshSearchIndices(monitor);
- }
- monitor.done();
- fgFirstTime= false;
- } else {
- history.checkConsistency(monitor);
- }
- }
- public boolean needsExecution() {
- OpenTypeHistory history= OpenTypeHistory.getInstance();
- return fgFirstTime || history.isEmpty() || history.needConsistencyCheck();
- }
- private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- new SearchEngine().searchAllTypeNames(
- null,
- 0,
- // make sure we search a concrete name. This is faster according to Kent
- "_______________".toCharArray(), //$NON-NLS-1$
- SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
- IJavaScriptSearchConstants.ENUM,
- SearchEngine.createWorkspaceScope(),
- new TypeNameRequestor() {},
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- monitor);
- } catch (JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- }
- }
- }
- ConsistencyRunnable runnable= new ConsistencyRunnable();
- if (!runnable.needsExecution())
- return;
- IRunnableContext context= fRunnableContext != null
- ? fRunnableContext
- : PlatformUI.getWorkbench().getProgressService();
- context.run(true, true, runnable);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java
deleted file mode 100644
index 3a5f1280..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceAdapter;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-
-public class BasicSelectionTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener {
-
- private ISelectionProvider fProvider;
-
- public BasicSelectionTransferDragAdapter(ISelectionProvider provider) {
- Assert.isNotNull(provider);
- fProvider= provider;
- }
-
- /**
- * @see TransferDragSourceListener#getTransfer
- */
- public Transfer getTransfer() {
- return LocalSelectionTransfer.getInstance();
- }
-
- /* non Java-doc
- * @see org.eclipse.swt.dnd.DragSourceListener#dragStart
- */
- public void dragStart(DragSourceEvent event) {
- ISelection selection= fProvider.getSelection();
- LocalSelectionTransfer.getInstance().setSelection(selection);
- LocalSelectionTransfer.getInstance().setSelectionSetTime(event.time & 0xFFFFFFFFL);
- event.doit= isDragable(selection);
- }
-
- /**
- * Checks if the elements contained in the given selection can
- * be dragged.
- * <p>
- * Subclasses may override.
- *
- * @param selection containing the elements to be dragged
- */
- protected boolean isDragable(ISelection selection) {
- return true;
- }
-
-
- /* non Java-doc
- * @see org.eclipse.swt.dnd.DragSourceListener#dragSetData
- */
- public void dragSetData(DragSourceEvent event) {
- // For consistency set the data to the selection even though
- // the selection is provided by the LocalSelectionTransfer
- // to the drop target adapter.
- event.data= LocalSelectionTransfer.getInstance().getSelection();
- }
-
-
- /* non Java-doc
- * @see org.eclipse.swt.dnd.DragSourceListener#dragFinished
- */
- public void dragFinished(DragSourceEvent event) {
- // Make sure we don't have to do any remaining work
- Assert.isTrue(event.detail != DND.DROP_MOVE);
- LocalSelectionTransfer.getInstance().setSelection(null);
- LocalSelectionTransfer.getInstance().setSelectionSetTime(0);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDragAdapter.java
deleted file mode 100644
index 013fc004..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDragAdapter.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-
-/**
- * A delegating drag adapter negotiates between a set of <code>TransferDragSourceListener</code>s
- * On <code>dragStart</code> the adapter determines the listener to be used for any further
- * <code>drag*</code> callback.
- */
-public class DelegatingDragAdapter implements DragSourceListener {
-
- private TransferDragSourceListener[] fPossibleListeners;
- private List fActiveListeners;
- private TransferDragSourceListener fFinishListener;
-
- public DelegatingDragAdapter(TransferDragSourceListener[] listeners) {
- setPossibleListeners(listeners);
- }
-
- protected void setPossibleListeners(TransferDragSourceListener[] listeners) {
- Assert.isNotNull(listeners);
- Assert.isTrue(fActiveListeners == null, "Can only set possible listeners before drag operation has started"); //$NON-NLS-1$
- fPossibleListeners= listeners;
- }
-
- /* non Java-doc
- * @see DragSourceListener
- */
- public void dragStart(DragSourceEvent event) {
- fFinishListener= null;
- boolean saveDoit= event.doit;
- Object saveData= event.data;
- boolean doIt= false;
- List transfers= new ArrayList(fPossibleListeners.length);
- fActiveListeners= new ArrayList(fPossibleListeners.length);
-
- for (int i= 0; i < fPossibleListeners.length; i++) {
- TransferDragSourceListener listener= fPossibleListeners[i];
- event.doit= saveDoit;
- listener.dragStart(event);
- if (event.doit) {
- transfers.add(listener.getTransfer());
- fActiveListeners.add(listener);
- }
- doIt= doIt || event.doit;
- }
- if (doIt) {
- ((DragSource)event.widget).setTransfer((Transfer[])transfers.toArray(new Transfer[transfers.size()]));
- }
- event.data= saveData;
- event.doit= doIt;
- }
-
- /* non Java-doc
- * @see DragSourceListener
- */
- public void dragSetData(DragSourceEvent event) {
- fFinishListener= getListener(event.dataType);
- if (fFinishListener != null)
- fFinishListener.dragSetData(event);
- }
-
- /* non Java-doc
- * @see DragSourceListener
- */
- public void dragFinished(DragSourceEvent event) {
- try{
- if (fFinishListener != null) {
- fFinishListener.dragFinished(event);
- } else {
- // If the user presses Escape then we get a dragFinished without
- // getting a dragSetData before.
- fFinishListener= getListener(event.dataType);
- if (fFinishListener != null)
- fFinishListener.dragFinished(event);
- }
- } finally{
- fFinishListener= null;
- fActiveListeners= null;
- }
- }
-
- private TransferDragSourceListener getListener(TransferData type) {
- if (type == null)
- return null;
-
- for (Iterator iter= fActiveListeners.iterator(); iter.hasNext();) {
- TransferDragSourceListener listener= (TransferDragSourceListener)iter.next();
- if (listener.getTransfer().isSupportedType(type)) {
- return listener;
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDropAdapter.java
deleted file mode 100644
index ab1b8c82..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/DelegatingDropAdapter.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.DropTargetListener;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-
-/**
- * A delegating drop adapter negotiates between a set of
- * <code>TransferDropTargetListener</code> s On <code>dragEnter</code> the
- * adapter determines the listener to be used for any further <code>drag*</code>
- * callback.
- */
-public class DelegatingDropAdapter implements DropTargetListener {
-
- private TransferDropTargetListener[] fListeners;
- private TransferDropTargetListener fCurrentListener;
- private int fOriginalDropType;
-
- /**
- * Creates a new delegating drop adapter.
- *
- * @param listeners an array of potential listeners
- */
- public DelegatingDropAdapter(TransferDropTargetListener[] listeners) {
- Assert.isNotNull(listeners);
- fListeners= listeners;
- }
-
- /**
- * The cursor has entered the drop target boundaries. The current listener
- * is updated, and <code>#dragEnter()</code> is forwarded to the current
- * listener.
- *
- * @param event the drop target event
- * @see DropTargetListener#dragEnter(DropTargetEvent)
- */
- public void dragEnter(DropTargetEvent event) {
- fOriginalDropType= event.detail;
- updateCurrentListener(event);
- }
-
- /**
- * The cursor has left the drop target boundaries. The event is forwarded to
- * the current listener.
- *
- * @param event the drop target event
- * @see DropTargetListener#dragLeave(DropTargetEvent)
- */
- public void dragLeave(final DropTargetEvent event) {
- setCurrentListener(null, event);
- }
-
- /**
- * The operation being performed has changed (usually due to the user
- * changing a drag modifier key while dragging). Updates the current
- * listener and forwards this event to that listener.
- *
- * @param event the drop target event
- * @see DropTargetListener#dragOperationChanged(DropTargetEvent)
- */
- public void dragOperationChanged(final DropTargetEvent event) {
- fOriginalDropType= event.detail;
- TransferDropTargetListener oldListener= getCurrentListener();
- updateCurrentListener(event);
- final TransferDropTargetListener newListener= getCurrentListener();
- // only notify the current listener if it hasn't changed based on the
- // operation change. otherwise the new listener would get a dragEnter
- // followed by a dragOperationChanged with the exact same event.
- if (newListener != null && newListener == oldListener) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- newListener.dragOperationChanged(event);
- }
- });
- }
- }
-
- /**
- * The cursor is moving over the drop target. Updates the current listener
- * and forwards this event to that listener. If no listener can handle the
- * drag operation the <code>event.detail</code> field is set to
- * <code>DND.DROP_NONE</code> to indicate an invalid drop.
- *
- * @param event the drop target event
- * @see DropTargetListener#dragOver(DropTargetEvent)
- */
- public void dragOver(final DropTargetEvent event) {
- TransferDropTargetListener oldListener= getCurrentListener();
- updateCurrentListener(event);
- final TransferDropTargetListener newListener= getCurrentListener();
-
- // only notify the current listener if it hasn't changed based on the
- // drag over. otherwise the new listener would get a dragEnter
- // followed by a dragOver with the exact same event.
- if (newListener != null && newListener == oldListener) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- newListener.dragOver(event);
- }
- });
- }
- }
-
- /**
- * Forwards this event to the current listener, if there is one. Sets the
- * current listener to <code>null</code> afterwards.
- *
- * @param event the drop target event
- * @see DropTargetListener#drop(DropTargetEvent)
- */
- public void drop(final DropTargetEvent event) {
- updateCurrentListener(event);
- if (getCurrentListener() != null) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- getCurrentListener().drop(event);
- }
- });
- }
- setCurrentListener(null, event);
- }
-
- /**
- * Forwards this event to the current listener if there is one.
- *
- * @param event the drop target event
- * @see DropTargetListener#dropAccept(DropTargetEvent)
- */
- public void dropAccept(final DropTargetEvent event) {
- if (getCurrentListener() != null) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- getCurrentListener().dropAccept(event);
- }
- });
- }
- }
-
- /**
- * Returns the listener which currently handles drop events.
- *
- * @return the <code>TransferDropTargetListener</code> which currently
- * handles drop events.
- */
- private TransferDropTargetListener getCurrentListener() {
- return fCurrentListener;
- }
-
- /**
- * Returns the transfer data type supported by the given listener. Returns
- * <code>null</code> if the listener does not support any of the specified
- * data types.
- *
- * @param dataTypes available data types
- * @param listener <code>TransferDropTargetListener</code> to use for
- * testing supported data types.
- * @return the transfer data type supported by the given listener or
- * <code>null</code>.
- */
- private TransferData getSupportedTransferType(TransferData[] dataTypes, TransferDropTargetListener listener) {
- for (int i= 0; i < dataTypes.length; i++) {
- if (listener.getTransfer().isSupportedType(dataTypes[i])) {
- return dataTypes[i];
- }
- }
- return null;
- }
-
- /**
- * Returns the combined set of <code>Transfer</code> types of all
- * <code>TransferDropTargetListeners</code>.
- *
- * @return the combined set of <code>Transfer</code> types
- */
- public Transfer[] getTransfers() {
- Transfer[] types= new Transfer[fListeners.length];
- for (int i= 0; i < fListeners.length; i++) {
- types[i]= fListeners[i].getTransfer();
- }
- return types;
- }
-
- /**
- * Sets the current listener to <code>listener</code>. Sends the given
- * <code>DropTargetEvent</code> if the current listener changes.
- *
- * @return <code>true</code> if the new listener is different than the
- * previous <code>false</code> otherwise
- */
- private boolean setCurrentListener(TransferDropTargetListener listener, final DropTargetEvent event) {
- if (fCurrentListener == listener)
- return false;
- if (fCurrentListener != null) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- fCurrentListener.dragLeave(event);
- }
- });
- }
- fCurrentListener= listener;
- if (fCurrentListener != null) {
- SafeRunner.run(new SafeRunnable() {
- public void run() throws Exception {
- fCurrentListener.dragEnter(event);
- }
- });
- }
- return true;
- }
-
- /**
- * Updates the current listener to one that can handle the drop. There can
- * be many listeners and each listener may be able to handle many
- * <code>TransferData</code> types. The first listener found that can
- * handle a drop of one of the given <code>TransferData</code> types will
- * be selected. If no listener can handle the drag operation the
- * <code>event.detail</code> field is set to <code>DND.DROP_NONE</code>
- * to indicate an invalid drop.
- *
- * @param event the drop target event
- */
- private void updateCurrentListener(DropTargetEvent event) {
- int originalDetail= event.detail;
- // Revert the detail to the "original" drop type that the User
- // indicated. This is necessary because the previous listener
- // may have changed the detail to something other than what the
- // user indicated.
- event.detail= fOriginalDropType;
-
- for (int i= 0; i < fListeners.length; i++) {
- TransferDropTargetListener listener= fListeners[i];
- TransferData dataType= getSupportedTransferType(event.dataTypes, listener);
- if (dataType != null) {
- TransferData originalDataType= event.currentDataType;
- // set the data type supported by the drop listener
- event.currentDataType= dataType;
- if (listener.isEnabled(event)) {
- // if the listener stays the same, set its previously
- // determined
- // event detail
- if (!setCurrentListener(listener, event))
- event.detail= originalDetail;
- return;
- } else {
- event.currentDataType= originalDataType;
- }
- }
- }
- setCurrentListener(null, event);
- event.detail= DND.DROP_NONE;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDragAdapter.java
deleted file mode 100644
index d54ef0dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDragAdapter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-
-public class JdtViewerDragAdapter extends DelegatingDragAdapter {
-
- private StructuredViewer fViewer;
-
- public JdtViewerDragAdapter(StructuredViewer viewer, TransferDragSourceListener[] listeners) {
- super(listeners);
- Assert.isNotNull(viewer);
- fViewer= viewer;
- }
-
- public void dragStart(DragSourceEvent event) {
- IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection();
- if (selection.isEmpty()) {
- event.doit= false;
- return;
- }
- super.dragStart(event);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDropAdapter.java
deleted file mode 100644
index 4cde5d71..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/JdtViewerDropAdapter.java
+++ /dev/null
@@ -1,295 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.DropTargetListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.TreeItem;
-
-/**
- * A drag and drop adapter to be used together with structured viewers.
- * The adapater delegates the <code>dragEnter</code>, <code>dragOperationChanged
- * </code>, <code>dragOver</code> and <code>dropAccept</code> method to the
- * <code>validateDrop</code> method. Furthermore it adds location feedback.
- */
-public class JdtViewerDropAdapter implements DropTargetListener {
-
- /**
- * Constant describing the position of the mouse cursor relative
- * to the target object. This means the mouse is not positioned
- * over or near any valid target.
- */
- public static final int LOCATION_NONE= DND.FEEDBACK_NONE;
-
- /**
- * Constant describing the position of the mouse cursor relative
- * to the target object. This means the mouse is positioned
- * directly on the target.
- */
- public static final int LOCATION_ON= DND.FEEDBACK_SELECT;
-
- /**
- * Constant describing the position of the mouse cursor relative
- * to the target object. This means the mouse is positioned
- * slightly before the target.
- */
- public static final int LOCATION_BEFORE= DND.FEEDBACK_INSERT_BEFORE;
-
- /**
- * Constant describing the position of the mouse cursor relative
- * to the target object. This means the mouse is positioned
- * slightly after the target.
- */
- public static final int LOCATION_AFTER= DND.FEEDBACK_INSERT_AFTER;
-
- /**
- * The threshold used to determine if the mouse is before or after
- * an item.
- */
- private static final int LOCATION_EPSILON= 5;
-
-
- private static final int ITEM_MARGIN_LEFT= 40;
- private static final int ITEM_MARGIN_RIGTH= 10;
-
- /**
- * Style to enable location feedback.
- */
- public static final int INSERTION_FEEDBACK= 1 << 1;
-
- private StructuredViewer fViewer;
- private int fFeedback;
- private boolean fShowInsertionFeedback;
- private boolean fFullWidthMatchesItem;
- private int fRequestedOperation;
- private int fLastOperation;
- protected int fLocation;
- protected Object fTarget;
-
-
-
- public JdtViewerDropAdapter(StructuredViewer viewer, int feedback) {
- Assert.isNotNull(viewer);
- fViewer= viewer;
- fFeedback= feedback;
- fLastOperation= -1;
- fFullWidthMatchesItem= true;
- }
-
- /**
- * Controls whether the drop adapter shows insertion feedback or not.
- *
- * @param showInsertionFeedback <code>true</code> if the drop adapter is supposed
- * to show insertion feedback. Otherwise <code>false</code>
- */
- public void showInsertionFeedback(boolean showInsertionFeedback) {
- fShowInsertionFeedback= showInsertionFeedback;
- }
-
- /**
- * Controls whether the drop adapter matches an tree or table item on the full width of the viewer.
- *
- * @param enable <code>true</code> if the drop adapter is supposed
- * to test the horizontal distance
- */
- protected void setFullWidthMatchesItem(boolean enable) {
- fFullWidthMatchesItem= enable;
- }
-
- /**
- * Returns the viewer this adapter is working on.
- */
- protected StructuredViewer getViewer() {
- return fViewer;
- }
-
- //---- Hooks to override -----------------------------------------------------
-
- /**
- * The actual drop has occurred. Calls <code>drop(Object target, DropTargetEvent event)
- * </code>.
- * @see DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent)
- */
- public void drop(DropTargetEvent event) {
- drop(fTarget, event);
- }
-
- /**
- * The actual drop has occurred.
- * @param target the drop target in form of a domain element.
- * @param event the drop traget event
- */
- public void drop(Object target, DropTargetEvent event) {
- }
-
- /**
- * Checks if the drop is valid. The method calls <code>validateDrop
- * (Object target, DropTargetEvent event). Implementors can alter the
- * <code>currentDataType</code> field and the <code>detail</code> field
- * to give feedback about drop acceptence.
- */
- public void validateDrop(DropTargetEvent event) {
- validateDrop(fTarget, event, fRequestedOperation);
- }
-
- /**
- * Checks if the drop on the current target is valid. The method
- * can alter the <code>currentDataType</code> field and the <code>
- * detail</code> field to give feedback about drop acceptence.
- * @param target the drop target in form of a domain element.
- * @param event the drop traget event
- * @param operation the operation requested by the user.
- */
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- }
-
- public void dragEnter(DropTargetEvent event) {
- dragOperationChanged(event);
- }
-
- public void dragLeave(DropTargetEvent event) {
- fTarget= null;
- fLocation= LOCATION_NONE;
- }
-
- public void dragOperationChanged(DropTargetEvent event) {
- fRequestedOperation= event.detail;
- fTarget= computeTarget(event);
- fLocation= computeLocation(event);
- validateDrop(event);
- fLastOperation= event.detail;
- computeFeedback(event);
- }
-
- public void dragOver(DropTargetEvent event) {
- Object oldTarget= fTarget;
- fTarget= computeTarget(event);
-
- //set the location feedback
- int oldLocation= fLocation;
- fLocation= computeLocation(event);
- if (oldLocation != fLocation || oldTarget != fTarget || fLastOperation != event.detail) {
- validateDrop(event);
- fLastOperation= event.detail;
- } else {
- event.detail= fLastOperation;
- }
- computeFeedback(event);
- }
-
- public void dropAccept(DropTargetEvent event) {
- fTarget= computeTarget(event);
- validateDrop(event);
- fLastOperation= event.detail;
- }
-
- /**
- * Returns the data held by <code>event.item</code>. Inside a viewer
- * this corresponds to the items data model element.
- */
- protected Object computeTarget(DropTargetEvent event) {
- if (event.item == null) {
- return null;
- }
- if (!fFullWidthMatchesItem) {
- Point coordinates= fViewer.getControl().toControl(new Point(event.x, event.y));
- Rectangle bounds= getBounds((Item) event.item);
- if (coordinates.x < bounds.x - ITEM_MARGIN_LEFT || coordinates.x >= bounds.x + bounds.width + ITEM_MARGIN_RIGTH) {
- event.item= null; // too far away
- return null;
- }
- }
- return event.item.getData();
- }
-
- /**
- * Returns the position of the given coordinates relative to the given target.
- * The position is determined to be before, after, or on the item, based on
- * some threshold value. The return value is one of the LOCATION_* constants
- * defined in this class.
- */
- protected int computeLocation(DropTargetEvent event) {
- if (!(event.item instanceof Item))
- return LOCATION_NONE;
-
- Item item= (Item) event.item;
- Point coordinates= fViewer.getControl().toControl(new Point(event.x, event.y));
- Rectangle bounds= getBounds(item);
- if (bounds == null) {
- return LOCATION_NONE;
- }
- if ((coordinates.y - bounds.y) < LOCATION_EPSILON) {
- return LOCATION_BEFORE;
- }
- if ((bounds.y + bounds.height - coordinates.y) < LOCATION_EPSILON) {
- return LOCATION_AFTER;
- }
- return LOCATION_ON;
- }
-
- /**
- * Returns the bounds of the given item, or <code>null</code> if it is not a
- * valid type of item.
- */
- private Rectangle getBounds(Item item) {
- if (item instanceof TreeItem)
- return ((TreeItem) item).getBounds();
-
- if (item instanceof TableItem)
- return ((TableItem) item).getBounds(0);
-
- return null;
- }
-
- /**
- * Sets the drag under feedback corresponding to the value of <code>fLocation</code>
- * and the <code>INSERTION_FEEDBACK</code> style bit.
- */
- protected void computeFeedback(DropTargetEvent event) {
- if (!fShowInsertionFeedback && fLocation != LOCATION_NONE) {
- event.feedback= DND.FEEDBACK_SELECT;
- } else {
- event.feedback= fLocation;
- }
- event.feedback|= fFeedback;
- }
-
- /**
- * Sets the drop operation to </code>DROP_NODE<code>.
- */
- protected void clearDropOperation(DropTargetEvent event) {
- event.detail= DND.DROP_NONE;
- }
-
- /**
- * Returns the requested drop operation.
- */
- protected int getRequestedOperation() {
- return fRequestedOperation;
- }
-
- protected void setDefaultFeedback(int feedback) {
- fFeedback= feedback;
- }
-
- //---- helper methods to test DnD
-
- public void internalTestSetLocation(int location) {
- fLocation= location;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/ResourceTransferDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/ResourceTransferDragAdapter.java
deleted file mode 100644
index 49d0e4e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dnd/ResourceTransferDragAdapter.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.dnd;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceAdapter;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * A drag adapter that transfers the current selection as </code>
- * IResource</code>. Only those elements in the selection are part
- * of the transfer which can be converted into an <code>IResource
- * </code>.
- */
-public class ResourceTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener {
-
- private ISelectionProvider fProvider;
-
- private static final List EMPTY_LIST= new ArrayList(0);
-
- /**
- * Creates a new ResourceTransferDragAdapter for the given selection
- * provider.
- *
- * @param provider the selection provider to access the viewer's selection
- */
- public ResourceTransferDragAdapter(ISelectionProvider provider) {
- fProvider= provider;
- Assert.isNotNull(fProvider);
- }
-
- public Transfer getTransfer() {
- return ResourceTransfer.getInstance();
- }
-
- public void dragStart(DragSourceEvent event) {
- event.doit= convertSelection().size() > 0;
- }
-
- public void dragSetData(DragSourceEvent event) {
- List resources= convertSelection();
- event.data= resources.toArray(new IResource[resources.size()]);
- }
-
- public void dragFinished(DragSourceEvent event) {
- if (!event.doit)
- return;
-
- if (event.detail == DND.DROP_MOVE) {
- handleFinishedDropMove(event);
- }
- }
-
- private List convertSelection() {
- ISelection s= fProvider.getSelection();
- if (!(s instanceof IStructuredSelection))
- return EMPTY_LIST;
- IStructuredSelection selection= (IStructuredSelection)s;
- List result= new ArrayList(selection.size());
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- IResource resource= null;
- if (element instanceof IJavaScriptElement) {
- // don't use IAdaptable as for members only the top level type adapts
- resource= ((IJavaScriptElement) element).getResource();
- } else if (element instanceof IAdaptable) {
- resource= (IResource) ((IAdaptable) element).getAdapter(IResource.class);
- }
- if (resource != null)
- result.add(resource);
- }
- return result;
- }
-
- private void handleFinishedDropMove(DragSourceEvent event) {
- MultiStatus status= new MultiStatus(
- JavaScriptPlugin.getPluginId(),
- IJavaStatusConstants.INTERNAL_ERROR,
- JavaUIMessages.ResourceTransferDragAdapter_cannot_delete_resource,
- null);
- List resources= convertSelection();
- for (Iterator iter= resources.iterator(); iter.hasNext();) {
- IResource resource= (IResource) iter.next();
- try {
- resource.delete(true, null);
- } catch (CoreException e) {
- status.add(e.getStatus());
- }
- }
- if (status.getChildren().length > 0) {
- Shell parent= SWTUtil.getShell(event.widget);
- ErrorDialog error= new ErrorDialog(parent,
- JavaUIMessages.ResourceTransferDragAdapter_moving_resource,
- JavaUIMessages.ResourceTransferDragAdapter_cannot_delete_files,
- status, IStatus.ERROR);
- error.open();
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClassFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClassFilter.java
deleted file mode 100644
index e3fa957f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClassFilter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IType;
-
-
-/**
- * Filters classes
- */
-public class ClassFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IType) {
- return false;
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClosedProjectFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClosedProjectFilter.java
deleted file mode 100644
index 5ac7af05..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ClosedProjectFilter.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * Filters closed projects
- */
-public class ClosedProjectFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IJavaScriptElement)
- return ((IJavaScriptElement)element).getJavaScriptProject().getProject().isOpen();
- if (element instanceof IResource)
- return ((IResource)element).getProject().isOpen();
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ContainedLibraryFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ContainedLibraryFilter.java
deleted file mode 100644
index 98030848..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ContainedLibraryFilter.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-
-/**
- * The LibraryFilter is a filter used to determine whether
- * a Java internal library is shown
- */
-public class ContainedLibraryFilter extends ViewerFilter {
-
- /* (non-Javadoc)
- * Method declared on ViewerFilter.
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- if (root.isArchive()) {
- // don't filter out JARs contained in the project itself
- IResource resource= root.getResource();
- if (resource != null) {
- IProject jarProject= resource.getProject();
- IProject container= root.getJavaScriptProject().getProject();
- return !container.equals(jarProject);
- }
- }
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java
deleted file mode 100644
index 16d0e709..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.Stack;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-public class CustomFiltersDialog extends SelectionDialog {
-
- private static final String SEPARATOR= ","; //$NON-NLS-1$
-
- private String fViewId;
- private boolean fEnablePatterns;
- private String[] fPatterns;
- private String[] fEnabledFilterIds;
-
- private FilterDescriptor[] fBuiltInFilters;
-
- private CheckboxTableViewer fCheckBoxList;
- private Button fEnableUserDefinedPatterns;
- private Text fUserDefinedPatterns;
-
- private Stack fFilterDescriptorChangeHistory;
-
-
- /**
- * Creates a dialog to customize Java element filters.
- *
- * @param shell the parent shell
- * @param viewId the id of the view
- * @param enablePatterns <code>true</code> if pattern filters are enabled
- * @param patterns the filter patterns
- * @param enabledFilterIds the Ids of the enabled filters
- */
- public CustomFiltersDialog(
- Shell shell,
- String viewId,
- boolean enablePatterns,
- String[] patterns,
- String[] enabledFilterIds) {
-
- super(shell);
- Assert.isNotNull(viewId);
- Assert.isNotNull(patterns);
- Assert.isNotNull(enabledFilterIds);
-
- fViewId= viewId;
- fPatterns= patterns;
- fEnablePatterns= enablePatterns;
- fEnabledFilterIds= enabledFilterIds;
-
- fBuiltInFilters= FilterDescriptor.getFilterDescriptors(fViewId);
- fFilterDescriptorChangeHistory= new Stack();
- setShellStyle(getShellStyle() | SWT.RESIZE);
- }
-
- protected void configureShell(Shell shell) {
- setTitle(FilterMessages.CustomFiltersDialog_title);
- setMessage(FilterMessages.CustomFiltersDialog_filterList_label);
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.CUSTOM_FILTERS_DIALOG);
- }
-
- /**
- * Overrides method in Dialog
- *
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
- // create a composite with standard margins and spacing
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- composite.setFont(parent.getFont());
- Composite group= composite;
-
- // Checkbox
- fEnableUserDefinedPatterns= new Button(group, SWT.CHECK);
- fEnableUserDefinedPatterns.setFocus();
- fEnableUserDefinedPatterns.setText(FilterMessages.CustomFiltersDialog_enableUserDefinedPattern);
-
- // Pattern field
- fUserDefinedPatterns= new Text(group, SWT.SINGLE | SWT.BORDER);
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
- data.widthHint= convertWidthInCharsToPixels(59);
- fUserDefinedPatterns.setLayoutData(data);
- String patterns= convertToString(fPatterns, SEPARATOR);
- fUserDefinedPatterns.setText(patterns);
-
- // Info text
- final Label info= new Label(group, SWT.LEFT);
- info.setText(FilterMessages.CustomFiltersDialog_patternInfo);
-
- // Enabling / disabling of pattern group
- fEnableUserDefinedPatterns.setSelection(fEnablePatterns);
- fUserDefinedPatterns.setEnabled(fEnablePatterns);
- info.setEnabled(fEnablePatterns);
- fEnableUserDefinedPatterns.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- boolean state= fEnableUserDefinedPatterns.getSelection();
- fUserDefinedPatterns.setEnabled(state);
- info.setEnabled(fEnableUserDefinedPatterns.getSelection());
- if (state)
- fUserDefinedPatterns.setFocus();
- }
- });
-
- // Filters provided by extension point
- if (fBuiltInFilters.length > 0)
- createCheckBoxList(group);
-
- applyDialogFont(parent);
- return parent;
- }
-
- private void createCheckBoxList(Composite parent) {
- // Filler
- new Label(parent, SWT.NONE);
-
- Label info= new Label(parent, SWT.LEFT);
- info.setText(FilterMessages.CustomFiltersDialog_filterList_label);
-
- fCheckBoxList= CheckboxTableViewer.newCheckList(parent, SWT.BORDER);
- GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= fCheckBoxList.getTable().getItemHeight() * 10;
- fCheckBoxList.getTable().setLayoutData(data);
-
- fCheckBoxList.setLabelProvider(createLabelPrivder());
- fCheckBoxList.setContentProvider(new ArrayContentProvider());
- Arrays.sort(fBuiltInFilters);
- fCheckBoxList.setInput(fBuiltInFilters);
- setInitialSelections(getEnabledFilterDescriptors());
-
- List initialSelection= getInitialElementSelections();
- if (initialSelection != null && !initialSelection.isEmpty())
- checkInitialSelections();
-
- // Description
- info= new Label(parent, SWT.LEFT);
- info.setText(FilterMessages.CustomFiltersDialog_description_label);
- final Text description= new Text(parent, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL);
- data = new GridData(GridData.FILL_HORIZONTAL);
- data.heightHint= convertHeightInCharsToPixels(3);
- description.setLayoutData(data);
- fCheckBoxList.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection= event.getSelection();
- if (selection instanceof IStructuredSelection) {
- Object selectedElement= ((IStructuredSelection)selection).getFirstElement();
- if (selectedElement instanceof FilterDescriptor)
- description.setText(((FilterDescriptor)selectedElement).getDescription());
- }
- }
- });
- fCheckBoxList.addCheckStateListener(new ICheckStateListener() {
- /*
- * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent)
- */
- public void checkStateChanged(CheckStateChangedEvent event) {
- Object element= event.getElement();
- if (element instanceof FilterDescriptor) {
- // renew if already touched
- if (fFilterDescriptorChangeHistory.contains(element))
- fFilterDescriptorChangeHistory.remove(element);
- fFilterDescriptorChangeHistory.push(element);
- }
- }});
-
- addSelectionButtons(parent);
- }
-
- private void addSelectionButtons(Composite composite) {
- Composite buttonComposite= new Composite(composite, SWT.RIGHT);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- buttonComposite.setLayout(layout);
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL);
- data.grabExcessHorizontalSpace= true;
- composite.setData(data);
-
- // Select All button
- String label= FilterMessages.CustomFiltersDialog_SelectAllButton_label;
- Button selectButton= createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, label, false);
- SWTUtil.setButtonDimensionHint(selectButton);
- SelectionListener listener= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fCheckBoxList.setAllChecked(true);
- fFilterDescriptorChangeHistory.clear();
- for (int i= 0; i < fBuiltInFilters.length; i++)
- fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]);
- }
- };
- selectButton.addSelectionListener(listener);
-
- // De-select All button
- label= FilterMessages.CustomFiltersDialog_DeselectAllButton_label;
- Button deselectButton= createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, label, false);
- SWTUtil.setButtonDimensionHint(deselectButton);
- listener= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fCheckBoxList.setAllChecked(false);
- fFilterDescriptorChangeHistory.clear();
- for (int i= 0; i < fBuiltInFilters.length; i++)
- fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]);
- }
- };
- deselectButton.addSelectionListener(listener);
- }
-
- private void checkInitialSelections() {
- Iterator itemsToCheck= getInitialElementSelections().iterator();
- while (itemsToCheck.hasNext())
- fCheckBoxList.setChecked(itemsToCheck.next(),true);
- }
-
- protected void okPressed() {
- if (fBuiltInFilters != null) {
- ArrayList result= new ArrayList();
- for (int i= 0; i < fBuiltInFilters.length; ++i) {
- if (fCheckBoxList.getChecked(fBuiltInFilters[i]))
- result.add(fBuiltInFilters[i]);
- }
- setResult(result);
- }
- super.okPressed();
- }
-
- private ILabelProvider createLabelPrivder() {
- return
- new LabelProvider() {
- public Image getImage(Object element) {
- return null;
- }
- public String getText(Object element) {
- if (element instanceof FilterDescriptor)
- return ((FilterDescriptor)element).getName();
- else
- return null;
- }
- };
- }
-
- // ---------- result handling ----------
-
- protected void setResult(List newResult) {
- super.setResult(newResult);
- if (fUserDefinedPatterns.getText().length() > 0) {
- fEnablePatterns= fEnableUserDefinedPatterns.getSelection();
- fPatterns= convertFromString(fUserDefinedPatterns.getText(), SEPARATOR);
- } else {
- fEnablePatterns= false;
- fPatterns= new String[0];
- }
- }
-
-
- /**
- * @return the patterns which have been entered by the user
- */
- public String[] getUserDefinedPatterns() {
- return fPatterns;
- }
-
- /**
- * @return the Ids of the enabled built-in filters
- */
- public String[] getEnabledFilterIds() {
- Object[] result= getResult();
- Set enabledIds= new HashSet(result.length);
- for (int i= 0; i < result.length; i++)
- enabledIds.add(((FilterDescriptor)result[i]).getId());
- return (String[]) enabledIds.toArray(new String[enabledIds.size()]);
- }
-
- /**
- * @return <code>true</code> if the user-defined patterns are disabled
- */
- public boolean areUserDefinedPatternsEnabled() {
- return fEnablePatterns;
- }
-
- /**
- * @return a stack with the filter descriptor check history
- *
- */
- public Stack getFilterDescriptorChangeHistory() {
- return fFilterDescriptorChangeHistory;
- }
-
- private FilterDescriptor[] getEnabledFilterDescriptors() {
- FilterDescriptor[] filterDescs= fBuiltInFilters;
- List result= new ArrayList(filterDescs.length);
- List enabledFilterIds= Arrays.asList(fEnabledFilterIds);
- for (int i= 0; i < filterDescs.length; i++) {
- String id= filterDescs[i].getId();
- if (enabledFilterIds.contains(id))
- result.add(filterDescs[i]);
- }
- return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
- }
-
-
- public static String[] convertFromString(String patterns, String separator) {
- StringTokenizer tokenizer= new StringTokenizer(patterns, separator, true);
- int tokenCount= tokenizer.countTokens();
- List result= new ArrayList(tokenCount);
- boolean escape= false;
- boolean append= false;
- while (tokenizer.hasMoreTokens()) {
- String token= tokenizer.nextToken().trim();
- if (separator.equals(token)) {
- if (!escape)
- escape= true;
- else {
- addPattern(result, separator);
- append= true;
- }
- } else {
- if (!append)
- result.add(token);
- else
- addPattern(result, token);
- append= false;
- escape= false;
- }
- }
- return (String[])result.toArray(new String[result.size()]);
- }
-
- private static void addPattern(List list, String pattern) {
- if (list.isEmpty())
- list.add(pattern);
- else {
- int index= list.size() - 1;
- list.set(index, ((String)list.get(index)) + pattern);
- }
- }
-
- public static String convertToString(String[] patterns, String separator) {
- int length= patterns.length;
- StringBuffer strBuf= new StringBuffer();
- if (length > 0)
- strBuf.append(escapeSeparator(patterns[0], separator));
- else
- return ""; //$NON-NLS-1$
- int i= 1;
- while (i < length) {
- strBuf.append(separator);
- strBuf.append(" "); //$NON-NLS-1$
- strBuf.append(escapeSeparator(patterns[i++], separator));
- }
- return strBuf.toString();
- }
-
- private static String escapeSeparator(String pattern, String separator) {
- int length= pattern.length();
- StringBuffer buf= new StringBuffer(length);
- for (int i= 0; i < length; i++) {
- char ch= pattern.charAt(i);
- if (separator.equals(String.valueOf(ch)))
- buf.append(ch);
- buf.append(ch);
- }
- return buf.toString();
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyInnerPackageFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyInnerPackageFilter.java
deleted file mode 100644
index 5d686abf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyInnerPackageFilter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-/**
- * Filters empty non-leaf package fragments
- */
-public class EmptyInnerPackageFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragment) {
- IPackageFragment pkg= (IPackageFragment)element;
- try {
- if (pkg.isDefaultPackage())
- return true;//pkg.hasChildren();
- return !pkg.hasSubpackages() || pkg.hasChildren() || (pkg.getNonJavaScriptResources().length > 0);
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyPackageFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyPackageFilter.java
deleted file mode 100644
index edf0b362..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/EmptyPackageFilter.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-/**
- * filters out all empty package fragments.
- */
-public class EmptyPackageFilter extends ViewerFilter {
-
- /**
- * Returns the result of this filter, when applied to the
- * given inputs.
- *
- * @return Returns true if element should be included in filtered set
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragment) {
- IPackageFragment pkg= (IPackageFragment)element;
- try {
- return pkg.hasChildren();
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
- return true;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java
deleted file mode 100644
index 74eedbf7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-
-/**
- * Fields filter.
- *
- *
- */
-public class FieldsFilter extends MemberFilter {
- public FieldsFilter() {
- addFilter(MemberFilter.FILTER_FIELDS);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterDescriptor.java
deleted file mode 100644
index 8e6ef9f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterDescriptor.java
+++ /dev/null
@@ -1,277 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.IPluginContribution;
-import org.eclipse.ui.activities.WorkbenchActivityHelper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-import com.ibm.icu.text.Collator;
-
-/**
- * Represents a custom filter which is provided by the
- * "org.eclipse.wst.jsdt.ui.javaElementFilters" extension point.
- *
- * since 2.0
- */
-public class FilterDescriptor implements Comparable, IPluginContribution {
-
- private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$
-
-
- private static final String EXTENSION_POINT_NAME= "javaElementFilters"; //$NON-NLS-1$
-
- private static final String FILTER_TAG= "filter"; //$NON-NLS-1$
-
- private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$
- private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
- /**
- * @deprecated as of 3.0 use {@link FilterDescriptor#TARGET_ID_ATTRIBUTE}
- */
- private static final String VIEW_ID_ATTRIBUTE= "viewId"; //$NON-NLS-1$
- private static final String TARGET_ID_ATTRIBUTE= "targetId"; //$NON-NLS-1$
- private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$
- private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$
- private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$
- private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
- /**
- * @deprecated use "enabled" instead
- */
- private static final String SELECTED_ATTRIBUTE= "selected"; //$NON-NLS-1$
-
- private static FilterDescriptor[] fgFilterDescriptors;
-
-
- private IConfigurationElement fElement;
-
- /**
- * Returns all contributed Java element filters.
- */
- public static FilterDescriptor[] getFilterDescriptors() {
- if (fgFilterDescriptors == null) {
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaScriptUI.ID_PLUGIN, EXTENSION_POINT_NAME);
- fgFilterDescriptors= createFilterDescriptors(elements);
- }
- return fgFilterDescriptors;
- }
- /**
- * Returns all Java element filters which
- * are contributed to the given view.
- */
- public static FilterDescriptor[] getFilterDescriptors(String targetId) {
- FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors();
- List result= new ArrayList(filterDescs.length);
- for (int i= 0; i < filterDescs.length; i++) {
- String tid= filterDescs[i].getTargetId();
- if (WorkbenchActivityHelper.filterItem(filterDescs[i]))
- continue;
- if (tid == null || tid.equals(targetId))
- result.add(filterDescs[i]);
- }
- return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
- }
-
- /**
- * Creates a new filter descriptor for the given configuration element.
- */
- private FilterDescriptor(IConfigurationElement element) {
- fElement= element;
- // it is either a pattern filter or a custom filter
- Assert.isTrue(isPatternFilter() ^ isCustomFilter(), "An extension for extension-point org.eclipse.wst.jsdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$
- Assert.isNotNull(getId(), "An extension for extension-point org.eclipse.wst.jsdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$
- Assert.isNotNull(getName(), "An extension for extension-point org.eclipse.wst.jsdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$
- }
-
- /**
- * Creates a new <code>ViewerFilter</code>.
- * This method is only valid for viewer filters.
- */
- public ViewerFilter createViewerFilter() {
- if (!isCustomFilter())
- return null;
-
- final ViewerFilter[] result= new ViewerFilter[1];
- String message= Messages.format(FilterMessages.FilterDescriptor_filterCreationError_message, getId());
- ISafeRunnable code= new SafeRunnable(message) {
- /*
- * @see org.eclipse.core.runtime.ISafeRunnable#run()
- */
- public void run() throws Exception {
- result[0]= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE);
- }
-
- };
- SafeRunner.run(code);
- return result[0];
- }
-
- //---- XML Attribute accessors ---------------------------------------------
-
- /**
- * Returns the filter's id.
- * <p>
- * This attribute is mandatory for custom filters.
- * The ID for pattern filters is
- * PATTERN_FILTER_ID_PREFIX plus the pattern itself.
- * </p>
- */
- public String getId() {
- if (isPatternFilter()) {
- String targetId= getTargetId();
- if (targetId == null)
- return PATTERN_FILTER_ID_PREFIX + getPattern();
- else
- return targetId + PATTERN_FILTER_ID_PREFIX + getPattern();
- } else
- return fElement.getAttribute(ID_ATTRIBUTE);
- }
-
- /**
- * Returns the filter's name.
- * <p>
- * If the name of a pattern filter is missing
- * then the pattern is used as its name.
- * </p>
- */
- public String getName() {
- String name= fElement.getAttribute(NAME_ATTRIBUTE);
- if (name == null && isPatternFilter())
- name= getPattern();
- return name;
- }
-
- /**
- * Returns the filter's pattern.
- *
- * @return the pattern string or <code>null</code> if it's not a pattern filter
- */
- public String getPattern() {
- return fElement.getAttribute(PATTERN_ATTRIBUTE);
- }
-
- /**
- * Returns the filter's viewId.
- *
- * @return the view ID or <code>null</code> if the filter is for all views
- *
- */
- public String getTargetId() {
- String tid= fElement.getAttribute(TARGET_ID_ATTRIBUTE);
-
- if (tid != null)
- return tid;
-
- // Backwards compatibility code
- return fElement.getAttribute(VIEW_ID_ATTRIBUTE);
-
- }
-
- /**
- * Returns the filter's description.
- *
- * @return the description or <code>null</code> if no description is provided
- */
- public String getDescription() {
- String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE);
- if (description == null)
- description= ""; //$NON-NLS-1$
- return description;
- }
-
- /**
- * @return <code>true</code> if this filter is a custom filter.
- */
- public boolean isPatternFilter() {
- return getPattern() != null;
- }
-
- /**
- * @return <code>true</code> if this filter is a pattern filter.
- */
- public boolean isCustomFilter() {
- return fElement.getAttribute(CLASS_ATTRIBUTE) != null;
- }
-
- /**
- * Returns <code>true</code> if the filter
- * is initially enabled.
- *
- * This attribute is optional and defaults to <code>true</code>.
- */
- public boolean isEnabled() {
- String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE);
- if (strVal == null)
- // backward compatibility
- strVal= fElement.getAttribute(SELECTED_ATTRIBUTE);
- return strVal == null || Boolean.valueOf(strVal).booleanValue();
- }
-
- /*
- * Implements a method from IComparable
- */
- public int compareTo(Object o) {
- if (o instanceof FilterDescriptor)
- return Collator.getInstance().compare(getName(), ((FilterDescriptor)o).getName());
- else
- return Integer.MIN_VALUE;
- }
-
- //---- initialization ---------------------------------------------------
-
- /**
- * Creates the filter descriptors.
- */
- private static FilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) {
- List result= new ArrayList(5);
- Set descIds= new HashSet(5);
- for (int i= 0; i < elements.length; i++) {
- final IConfigurationElement element= elements[i];
- if (FILTER_TAG.equals(element.getName())) {
-
- final FilterDescriptor[] desc= new FilterDescriptor[1];
- SafeRunner.run(new SafeRunnable(FilterMessages.FilterDescriptor_filterDescriptionCreationError_message) {
- public void run() throws Exception {
- desc[0]= new FilterDescriptor(element);
- }
- });
-
- if (desc[0] != null && !descIds.contains(desc[0].getId())) {
- result.add(desc[0]);
- descIds.add(desc[0].getId());
- }
- }
- }
- return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]);
- }
-
- public String getLocalId() {
- return fElement.getAttribute(ID_ATTRIBUTE);
- }
-
- public String getPluginId() {
- return fElement.getContributor().getName();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.java
deleted file mode 100644
index f9f6eaef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class FilterMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.filters.FilterMessages";//$NON-NLS-1$
-
- private FilterMessages() {
- // Do not instantiate
- }
-
- public static String CustomFiltersDialog_title;
- public static String CustomFiltersDialog_patternInfo;
- public static String CustomFiltersDialog_enableUserDefinedPattern;
- public static String CustomFiltersDialog_filterList_label;
- public static String CustomFiltersDialog_description_label;
- public static String CustomFiltersDialog_SelectAllButton_label;
- public static String CustomFiltersDialog_DeselectAllButton_label;
- public static String OpenCustomFiltersDialogAction_text;
- public static String FilterDescriptor_filterDescriptionCreationError_message;
- public static String FilterDescriptor_filterCreationError_message;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, FilterMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties
deleted file mode 100644
index 87b3dbe8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties
+++ /dev/null
@@ -1,23 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-CustomFiltersDialog_title= JavaScript Element Filters
-CustomFiltersDialog_patternInfo= The patterns are separated by comma, where\n* = any string, ? = any character, ,, = ,
-CustomFiltersDialog_enableUserDefinedPattern= &Name filter patterns (matching names will be hidden):
-CustomFiltersDialog_filterList_label= S&elect the elements to exclude from the view:
-CustomFiltersDialog_description_label= Filter description:
-CustomFiltersDialog_SelectAllButton_label= &Select All
-CustomFiltersDialog_DeselectAllButton_label= &Deselect All
-
-OpenCustomFiltersDialogAction_text= &Filters...
-
-FilterDescriptor_filterDescriptionCreationError_message= One of the extensions for extension-point org.eclipse.wst.jsdt.ui.javaElementFilters is incorrect.
-FilterDescriptor_filterCreationError_message= The org.eclipse.wst.jsdt.ui.javaElementFilters plug-in extension "{0}" specifies a viewer filter class which does not exist.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ImportDeclarationFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ImportDeclarationFilter.java
deleted file mode 100644
index 3277b19d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/ImportDeclarationFilter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-
-
-/**
- * Filters import declarations
- */
-public class ImportDeclarationFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- return !((element instanceof IImportContainer) || (element instanceof IImportDeclaration));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/JavaFileFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/JavaFileFilter.java
deleted file mode 100644
index 48dc2e86..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/JavaFileFilter.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-/**
- * Filters out all compilation units and class files elements.
- */
-public class JavaFileFilter extends ViewerFilter {
-
- /**
- * Returns the result of this filter, when applied to the
- * given inputs.
- *
- * @return Returns true if element should be included in filtered set
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IJavaScriptUnit)
- return false;
- if (element instanceof IClassFile)
- return false;
-
- if (element instanceof IPackageFragment)
- try {
- return ((IPackageFragment)element).getNonJavaScriptResources().length > 0;
- } catch (JavaScriptModelException ex) {
- return true;
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java
deleted file mode 100644
index b37951f2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.ui.ProjectLibraryRoot;
-
-
-/**
- * The LibraryFilter is a filter used to determine whether
- * the JavaScript Resources node is shown. This node contains libraries.
- */
-public class LibraryFilter extends ViewerFilter {
-
- /* (non-Javadoc)
- * Method declared on ViewerFilter.
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof ProjectLibraryRoot) {
- return false;
- } else if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) {
- return false;
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LocalTypesFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LocalTypesFilter.java
deleted file mode 100644
index 02977d42..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LocalTypesFilter.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-
-
-/**
- * Filters local types
- */
-public class LocalTypesFilter extends MemberFilter {
- public LocalTypesFilter() {
- addFilter(MemberFilter.FILTER_LOCALTYPES);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NamePatternFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NamePatternFilter.java
deleted file mode 100644
index ae098e96..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NamePatternFilter.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-
-/**
- * The NamePatternFilter selects the elements which
- * match the given string patterns.
- * <p>
- * The following characters have special meaning:
- * ? => any character
- * * => any string
- * </p>
- *
- *
- */
-public class NamePatternFilter extends ViewerFilter {
- private String[] fPatterns;
- private StringMatcher[] fMatchers;
-
- /**
- * Return the currently configured StringMatchers.
- * @return returns the matchers
- */
- private StringMatcher[] getMatchers() {
- return fMatchers;
- }
-
- /**
- * Gets the patterns for the receiver.
- * @return returns the patterns to be filtered for
- */
- public String[] getPatterns() {
- return fPatterns;
- }
-
-
- /* (non-Javadoc)
- * Method declared on ViewerFilter.
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (fMatchers.length == 0) {
- return true;
- }
- String matchName= null;
- if (element instanceof IJavaScriptElement) {
- matchName= ((IJavaScriptElement) element).getElementName();
- } else if (element instanceof IResource) {
- matchName= ((IResource) element).getName();
- }else if (element instanceof IStorage) {
- matchName= ((IStorage) element).getName();
- } else if (element instanceof IWorkingSet) {
- matchName= ((IWorkingSet) element).getLabel();
- } else if (element instanceof IAdaptable) {
- IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)element).getAdapter(IWorkbenchAdapter.class);
- if (wbadapter != null) {
- matchName= wbadapter.getLabel(element);
- }
- }
- if (matchName != null && matchName.length() > 0) {
- StringMatcher[] testMatchers= getMatchers();
- for (int i = 0; i < testMatchers.length; i++) {
- if (testMatchers[i].match(matchName))
- return false;
- }
- return true;
- }
- return true;
- }
-
- /**
- * Sets the patterns to filter out for the receiver.
- * <p>
- * The following characters have special meaning:
- * ? => any character
- * * => any string
- * </p>
- * @param newPatterns the new patterns
- */
- public void setPatterns(String[] newPatterns) {
- fPatterns = newPatterns;
- fMatchers = new StringMatcher[newPatterns.length];
- for (int i = 0; i < newPatterns.length; i++) {
- //Reset the matchers to prevent constructor overhead
- fMatchers[i]= new StringMatcher(newPatterns[i], true, false);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NoPackageContainingFoldersFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NoPackageContainingFoldersFilter.java
deleted file mode 100644
index 7a10d2da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NoPackageContainingFoldersFilter.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class NoPackageContainingFoldersFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IFolder) {
- try {
- if (containsPackage((IFolder)element))
- return true;
- else
- return false;
- } catch (CoreException e) {
- return true;
- }
- }
-
- return true;
- }
-
- private boolean containsPackage(IFolder folder) throws CoreException {
- IJavaScriptElement element= JavaScriptCore.create(folder);
- if (element instanceof IPackageFragment)
- return true;
- IResource[] resources= folder.members();
- for (int i= 0; i < resources.length; i++) {
- if (resources[i] instanceof IFolder && containsPackage((IFolder)resources[i]))
- return true;
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonJavaElementFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonJavaElementFilter.java
deleted file mode 100644
index f7429694..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonJavaElementFilter.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-
-/**
- * Filters out all non-Java elements.
- */
-public class NonJavaElementFilter extends ViewerFilter {
-
- /**
- * Returns the result of this filter, when applied to the
- * given inputs.
- *
- * @return Returns true if element should be included in filtered set
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IJavaScriptElement)
- return true;
-
- if (element instanceof IResource) {
- IProject project= ((IResource)element).getProject();
- return project == null || !project.isOpen();
- }
-
- // Exclude all IStorage elements which are neither Java elements nor resources
- if (element instanceof IStorage)
- return false;
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java
deleted file mode 100644
index 22a96ac8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-
-/**
- * Non-public member filter.
- *
- *
- */
-public class NonPublicFilter extends MemberFilter {
- public NonPublicFilter() {
- addFilter(MemberFilter.FILTER_NONPUBLIC);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicTypeFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicTypeFilter.java
deleted file mode 100644
index 51965d97..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicTypeFilter.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-/**
- * Filters non-public types
- */
-public class NonPublicTypeFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IType) {
- IType type= (IType)element;
- try {
- return Flags.isPublic(type.getFlags());
- } catch (JavaScriptModelException ex) {
- return true;
- }
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonSharedProjectFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonSharedProjectFilter.java
deleted file mode 100644
index 1fa62d41..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonSharedProjectFilter.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.team.core.RepositoryProvider;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * Filters non-shared projects and Java projects. Non-shared projects are
- * projects that are not controlled by a team provider.
- *
- *
- */
-public class NonSharedProjectFilter extends ViewerFilter {
-
- /*
- * @see ViewerFilter
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IProject)
- return isSharedProject((IProject)element);
-
- if (element instanceof IJavaScriptProject)
- return isSharedProject(((IJavaScriptProject)element).getProject());
-
- return true;
- }
-
- private boolean isSharedProject(IProject project) {
- return !project.isAccessible() || RepositoryProvider.isShared(project);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java
deleted file mode 100644
index 43128d09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.filters;
-
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-
-/**
- * Statics filter.
- *
- *
- */
-public class StaticsFilter extends MemberFilter {
- public StaticsFilter() {
- addFilter(MemberFilter.FILTER_STATIC);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/AbstractCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/AbstractCleanUp.java
deleted file mode 100644
index a02b98f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/AbstractCleanUp.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-
-public abstract class AbstractCleanUp implements ICleanUp {
-
- private Map fOptions;
- private final boolean fCanReinitialize;
-
- public AbstractCleanUp() {
- this(null);
- }
-
- public AbstractCleanUp(Map options) {
- fOptions= options;
- fCanReinitialize= options == null;
- }
-
- protected int getNumberOfProblems(IProblem[] problems, int problemId) {
- int result= 0;
- for (int i= 0; i < problems.length; i++) {
- if (problems[i].getID() == problemId)
- result++;
- }
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkPreConditions(IJavaScriptProject project, IJavaScriptUnit[] compilationUnits, IProgressMonitor monitor) throws CoreException {
- if (monitor != null)
- monitor.done();
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkPostConditions(IProgressMonitor monitor) throws CoreException {
- if (monitor != null)
- monitor.done();
- //Default do nothing
- return new RefactoringStatus();
- }
-
- /**
- * {@inheritDoc}
- */
- public void initialize(Map settings) throws CoreException {
- if (fCanReinitialize)
- fOptions= settings;
- }
-
- protected boolean isEnabled(String key) {
- Assert.isNotNull(key);
-
- Object value= fOptions.get(key);
- return CleanUpConstants.TRUE == value || CleanUpConstants.TRUE.equals(value);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsFreshAST(JavaScriptUnit compilationUnit) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(IJavaScriptUnit unit) throws CoreException {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpRefactoringWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpRefactoringWizard.java
deleted file mode 100644
index bbb3152a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpRefactoringWizard.java
+++ /dev/null
@@ -1,494 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpPreferenceUtil;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BulletListBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.CleanUpPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CodeFormatingTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CodeStyleTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.UnnecessaryCodeTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileStore;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage.IModificationListener;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.xml.sax.InputSource;
-
-public class CleanUpRefactoringWizard extends RefactoringWizard {
-
- private static final String USE_CUSTOM_PROFILE_KEY= "org.eclipse.wst.jsdt.ui.cleanup.use_dialog_profile"; //$NON-NLS-1$
- private static final String CUSTOM_PROFILE_KEY= "org.eclipse.wst.jsdt.ui.cleanup.custom_profile"; //$NON-NLS-1$
-
- private static class ProjectProfileLableProvider extends LabelProvider implements ITableLabelProvider {
-
- private Hashtable fProfileIdsTable;
-
- /**
- * {@inheritDoc}
- */
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getColumnText(Object element, int columnIndex) {
- if (columnIndex == 0) {
- return ((IJavaScriptProject)element).getProject().getName();
- } else if (columnIndex == 1) {
-
- if (fProfileIdsTable == null)
- fProfileIdsTable= loadProfiles();
-
- InstanceScope instanceScope= new InstanceScope();
- IEclipsePreferences instancePreferences= instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
-
- final String workbenchProfileId;
- if (instancePreferences.get(CleanUpConstants.CLEANUP_PROFILE, null) != null) {
- workbenchProfileId= instancePreferences.get(CleanUpConstants.CLEANUP_PROFILE, null);
- } else {
- workbenchProfileId= CleanUpConstants.DEFAULT_PROFILE;
- }
-
- return getProjectProfileName((IJavaScriptProject)element, fProfileIdsTable, workbenchProfileId);
- }
- return null;
- }
-
- private Hashtable loadProfiles() {
- List list= CleanUpPreferenceUtil.loadProfiles(new InstanceScope());
-
- Hashtable profileIdsTable= new Hashtable();
- for (Iterator iterator= list.iterator(); iterator.hasNext();) {
- Profile profile= (Profile)iterator.next();
- profileIdsTable.put(profile.getID(), profile);
- }
-
- return profileIdsTable;
- }
-
- private String getProjectProfileName(final IJavaScriptProject project, Hashtable profileIdsTable, String workbenchProfileId) {
- ProjectScope projectScope= new ProjectScope(project.getProject());
- IEclipsePreferences node= projectScope.getNode(JavaScriptUI.ID_PLUGIN);
- String id= node.get(CleanUpConstants.CLEANUP_PROFILE, null);
- if (id == null) {
- Profile profile= (Profile)profileIdsTable.get(workbenchProfileId);
- if (profile != null) {
- return profile.getName();
- } else {
- return MultiFixMessages.CleanUpRefactoringWizard_unknownProfile_Name;
- }
- } else {
- Profile profile= (Profile)profileIdsTable.get(id);
- if (profile != null) {
- return profile.getName();
- } else {
- return Messages.format(MultiFixMessages.CleanUpRefactoringWizard_UnmanagedProfileWithName_Name, id.substring(ProfileManager.ID_PREFIX.length()));
- }
- }
- }
-
- public void reset() {
- fProfileIdsTable= null;
- }
- }
-
- private static class CleanUpConfigurationPage extends UserInputWizardPage implements IModificationListener {
-
- private static final class ProfileTableAdapter implements IListAdapter {
- private final ProjectProfileLableProvider fProvider;
- private final Shell fShell;
-
- private ProfileTableAdapter(ProjectProfileLableProvider provider, Shell shell) {
- fProvider= provider;
- fShell= shell;
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- openPropertyDialog(field);
- }
-
- public void doubleClicked(ListDialogField field) {
- openPropertyDialog(field);
- }
-
- private void openPropertyDialog(ListDialogField field) {
- IJavaScriptProject project= (IJavaScriptProject)field.getSelectedElements().get(0);
- PreferencesUtil.createPropertyDialogOn(fShell, project, CleanUpPreferencePage.PROP_ID, null, null).open();
- List selectedElements= field.getSelectedElements();
- fProvider.reset();
- field.refresh();
- field.selectElements(new StructuredSelection(selectedElements));
- }
-
- public void selectionChanged(ListDialogField field) {
- if (field.getSelectedElements().size() != 1) {
- field.enableButton(0, false);
- } else {
- field.enableButton(0, true);
- }
- }
- }
-
- private static final String ENCODING= "UTF-8"; //$NON-NLS-1$
-
- private final CleanUpRefactoring fCleanUpRefactoring;
- private Map fCustomSettings;
- private SelectionButtonDialogField fUseCustomField;
-
- private ControlEnableState fEnableState;
-
- public CleanUpConfigurationPage(CleanUpRefactoring refactoring) {
- super(MultiFixMessages.CleanUpRefactoringWizard_CleanUpConfigurationPage_title);
- fCleanUpRefactoring= refactoring;
- IJavaScriptUnit[] cus= fCleanUpRefactoring.getCompilationUnits();
- IJavaScriptProject[] projects= fCleanUpRefactoring.getProjects();
- if (cus.length == 1) {
- setMessage(MultiFixMessages.CleanUpRefactoringWizard_CleaningUp11_Title);
- } else if (projects.length == 1) {
- setMessage(Messages.format(MultiFixMessages.CleanUpRefactoringWizard_CleaningUpN1_Title, new Integer(cus.length)));
- } else {
- setMessage(Messages.format(MultiFixMessages.CleanUpRefactoringWizard_CleaningUpNN_Title, new Object[] {new Integer(cus.length), new Integer(projects.length)}));
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- boolean isCustom= getDialogSettings().getBoolean(USE_CUSTOM_PROFILE_KEY);
-
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setFont(parent.getFont());
-
- SelectionButtonDialogField useProfile= new SelectionButtonDialogField(SWT.RADIO);
- useProfile.setLabelText(MultiFixMessages.CleanUpRefactoringWizard_use_configured_radio);
- useProfile.setSelection(!isCustom);
- useProfile.doFillIntoGrid(composite, 2);
-
- ProjectProfileLableProvider tableLabelProvider= new ProjectProfileLableProvider();
- IListAdapter listAdapter= new ProfileTableAdapter(tableLabelProvider, getShell());
- String[] buttons= new String[] {
- MultiFixMessages.CleanUpRefactoringWizard_Configure_Button
- };
- final ListDialogField settingsField= new ListDialogField(listAdapter, buttons, tableLabelProvider);
-
- String[] headerNames= new String[] {
- MultiFixMessages.CleanUpRefactoringWizard_Project_TableHeader,
- MultiFixMessages.CleanUpRefactoringWizard_Profile_TableHeader
- };
- ColumnLayoutData[] columns = new ColumnLayoutData[] {
- new ColumnWeightData(1, 100, true),
- new ColumnWeightData(2, 20, true)
- };
- settingsField.setTableColumns(new ListDialogField.ColumnsDescription(columns , headerNames, true));
- settingsField.setViewerComparator(new ViewerComparator());
-
- settingsField.doFillIntoGrid(composite, 3);
-
- Table table= settingsField.getTableViewer().getTable();
- GridData data= (GridData)settingsField.getListControl(null).getLayoutData();
- data.horizontalIndent= 15;
- data.grabExcessVerticalSpace= false;
- data.heightHint= SWTUtil.getTableHeightHint(table, Math.min(5, fCleanUpRefactoring.getProjects().length + 1));
- data.grabExcessHorizontalSpace= true;
- data.verticalAlignment= GridData.BEGINNING;
-
- data= (GridData)settingsField.getButtonBox(null).getLayoutData();
- data.grabExcessVerticalSpace= false;
- data.verticalAlignment= GridData.BEGINNING;
-
- data= (GridData)settingsField.getLabelControl(null).getLayoutData();
- data.exclude= true;
-
- settingsField.setElements(Arrays.asList(fCleanUpRefactoring.getProjects()));
- settingsField.selectFirstElement();
-
- fUseCustomField= new SelectionButtonDialogField(SWT.RADIO);
- fUseCustomField.setLabelText(MultiFixMessages.CleanUpRefactoringWizard_use_custom_radio);
- fUseCustomField.setSelection(isCustom);
- fUseCustomField.doFillIntoGrid(composite, 2);
-
- String settings= getDialogSettings().get(CUSTOM_PROFILE_KEY);
- if (settings == null) {
- fCustomSettings= CleanUpConstants.getEclipseDefaultSettings();
- } else {
- try {
- fCustomSettings= decodeSettings(settings);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- fCustomSettings= CleanUpConstants.getEclipseDefaultSettings();
- }
- }
-
- final BulletListBlock bulletListBlock= new BulletListBlock();
- Control bulletList= bulletListBlock.createControl(composite);
- GridData layoutData= (GridData)bulletList.getLayoutData();
- (layoutData).horizontalIndent= 15;
- layoutData.grabExcessVerticalSpace= true;
-
- final Button configure= new Button(composite, SWT.NONE);
- configure.setText(MultiFixMessages.CleanUpRefactoringWizard_ConfigureCustomProfile_button);
-
- data= new GridData(SWT.TOP, SWT.LEAD, false, false);
- data.widthHint= SWTUtil.getButtonWidthHint(configure);
- configure.setLayoutData(data);
-
- showCustomSettings(bulletListBlock);
- configure.addSelectionListener(new SelectionAdapter() {
- /**
- * {@inheritDoc}
- */
- public void widgetSelected(SelectionEvent e) {
- CleanUpSaveParticipantConfigurationModifyDialog dialog= new CleanUpSaveParticipantConfigurationModifyDialog(getShell(), fCustomSettings, MultiFixMessages.CleanUpRefactoringWizard_CustomCleanUpsDialog_title) {
- protected CleanUpTabPage[] createTabPages(Map workingValues) {
- CleanUpTabPage[] result= new CleanUpTabPage[3];
- result[0]= new CodeStyleTabPage(this, workingValues, false);
-// result[1]= new MemberAccessesTabPage(this, workingValues, false);
- result[1]= new UnnecessaryCodeTabPage(this, workingValues, false);
-// result[3]= new MissingCodeTabPage(this, workingValues, false);
- result[2]= new CodeFormatingTabPage(this, workingValues, false);
-
- addTabPage(MultiFixMessages.CleanUpRefactoringWizard_code_style_tab, result[0]);
-// addTabPage(MultiFixMessages.CleanUpRefactoringWizard_member_accesses_tab, result[1]);
- addTabPage(MultiFixMessages.CleanUpRefactoringWizard_unnecessary_code_tab, result[1]);
-// addTabPage(MultiFixMessages.CleanUpRefactoringWizard_missing_code_tab, result[3]);
- addTabPage(MultiFixMessages.CleanUpRefactoringWizard_code_organizing_tab, result[2]);
-
- return result;
- }
- };
- dialog.open();
- showCustomSettings(bulletListBlock);
- }
- });
-
- updateEnableState(isCustom, settingsField, configure, bulletListBlock);
-
- fUseCustomField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- updateEnableState(fUseCustomField.isSelected(), settingsField, configure, bulletListBlock);
- }
- });
-
- Link preferencePageLink= new Link(composite, SWT.WRAP);
- preferencePageLink.setText(MultiFixMessages.CleanUpRefactoringWizard_HideWizard_Link);
- preferencePageLink.setFont(parent.getFont());
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(300);
- gridData.horizontalSpan= 2;
- preferencePageLink.setLayoutData(gridData);
- preferencePageLink.addSelectionListener(new SelectionAdapter() {
- /**
- * {@inheritDoc}
- */
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(composite.getShell(), CleanUpPreferencePage.PREF_ID, null, null).open();
- }
- });
-
- setControl(composite);
-
- Dialog.applyDialogFont(composite);
- }
-
- private void updateEnableState(boolean isCustom, final ListDialogField settingsField, Button configureCustom, BulletListBlock bulletListBlock) {
- settingsField.getListControl(null).setEnabled(!isCustom);
- if (isCustom) {
- fEnableState= ControlEnableState.disable(settingsField.getButtonBox(null));
- } else if (fEnableState != null) {
- fEnableState.restore();
- fEnableState= null;
- }
- bulletListBlock.setEnabled(isCustom);
- configureCustom.setEnabled(isCustom);
- }
-
- private void showCustomSettings(BulletListBlock bulletListBlock) {
- StringBuffer buf= new StringBuffer();
-
- final ICleanUp[] cleanUps= CleanUpRefactoring.createCleanUps(fCustomSettings);
- for (int i= 0; i < cleanUps.length; i++) {
- String[] descriptions= cleanUps[i].getDescriptions();
- if (descriptions != null) {
- for (int j= 0; j < descriptions.length; j++) {
- if (buf.length() > 0) {
- buf.append('\n');
- }
- buf.append(descriptions[j]);
- }
- }
- }
- bulletListBlock.setText(buf.toString());
- }
-
- protected boolean performFinish() {
- initializeRefactoring();
- storeSettings();
- return super.performFinish();
- }
-
- public IWizardPage getNextPage() {
- initializeRefactoring();
- storeSettings();
- return super.getNextPage();
- }
-
- private void storeSettings() {
- getDialogSettings().put(USE_CUSTOM_PROFILE_KEY, fUseCustomField.isSelected());
- try {
- getDialogSettings().put(CUSTOM_PROFILE_KEY, encodeSettings(fCustomSettings));
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private void initializeRefactoring() {
- ICleanUp[] cleanups;
- if (fUseCustomField.isSelected()) {
- cleanups= CleanUpRefactoring.createCleanUps(fCustomSettings);
- } else {
- cleanups= CleanUpRefactoring.createCleanUps();
- }
-
- CleanUpRefactoring refactoring= (CleanUpRefactoring)getRefactoring();
- refactoring.clearCleanUps();
- for (int i= 0; i < cleanups.length; i++) {
- refactoring.addCleanUp(cleanups[i]);
- }
- }
-
- public String encodeSettings(Map settings) throws CoreException {
- ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
- try {
- CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
- CustomProfile profile= new ProfileManager.CustomProfile("custom", settings, versioner.getCurrentVersion(), versioner.getProfileKind()); //$NON-NLS-1$
- ArrayList profiles= new ArrayList();
- profiles.add(profile);
- ProfileStore.writeProfilesToStream(profiles, stream, ENCODING, versioner);
- try {
- return stream.toString(ENCODING);
- } catch (UnsupportedEncodingException e) {
- return stream.toString();
- }
- } finally {
- try { stream.close(); } catch (IOException e) { /* ignore */ }
- }
- }
-
- public Map decodeSettings(String settings) throws CoreException {
- byte[] bytes;
- try {
- bytes= settings.getBytes(ENCODING);
- } catch (UnsupportedEncodingException e) {
- bytes= settings.getBytes();
- }
- InputStream is= new ByteArrayInputStream(bytes);
- try {
- List res= ProfileStore.readProfilesFromStream(new InputSource(is));
- if (res == null || res.size() == 0)
- return CleanUpConstants.getEclipseDefaultSettings();
-
- CustomProfile profile= (CustomProfile)res.get(0);
- new CleanUpProfileVersioner().update(profile);
- return profile.getSettings();
- } finally {
- try { is.close(); } catch (IOException e) { /* ignore */ }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void updateStatus(IStatus status) {}
-
- /**
- * {@inheritDoc}
- */
- public void valuesModified() {}
- }
-
- public CleanUpRefactoringWizard(CleanUpRefactoring refactoring, int flags) {
- super(refactoring, flags);
- setDefaultPageTitle(MultiFixMessages.CleanUpRefactoringWizard_PageTitle);
- setWindowTitle(MultiFixMessages.CleanUpRefactoringWizard_WindowTitle);
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_CLEAN_UP);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- addPage(new CleanUpConfigurationPage((CleanUpRefactoring)getRefactoring()));
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantConfigurationModifyDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantConfigurationModifyDialog.java
deleted file mode 100644
index 50a0c43a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantConfigurationModifyDialog.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CodeFormatingTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CodeStyleTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.UnnecessaryCodeTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage.IModificationListener;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CleanUpSaveParticipantConfigurationModifyDialog extends StatusDialog implements IModificationListener {
-
- private static final String DS_KEY_PREFERRED_WIDTH= "clean_up_save_particpant_modify_dialog.preferred_width"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_HEIGHT= "clean_up_save_particpant_modify_dialog.preferred_height"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_X= "clean_up_save_particpant_modify_dialog.preferred_x"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_Y= "clean_up_save_particpant_modify_dialog.preferred_y"; //$NON-NLS-1$
- private static final String DS_KEY_LAST_FOCUS= "clean_up_save_particpant_modify_dialog.last_focus"; //$NON-NLS-1$
-
- private static final int APPLY_BUTTON_ID= IDialogConstants.CLIENT_ID;
-
- private final Map fWorkingValues;
- private Map fOrginalValues;
- private final List fTabPages;
- private final IDialogSettings fDialogSettings;
- private TabFolder fTabFolder;
- private Button fApplyButton;
- private CleanUpTabPage[] fPages;
- private Label fCountLabel;
-
- public CleanUpSaveParticipantConfigurationModifyDialog(Shell parentShell, Map settings, String title) {
- super(parentShell);
-
- setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX);
-
- setTitle(title);
- fWorkingValues= settings;
- fOrginalValues= new HashMap(settings);
- setStatusLineAboveButtons(false);
- fTabPages= new ArrayList();
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- }
-
- public void create() {
- super.create();
- int lastFocusNr= 0;
- try {
- lastFocusNr= fDialogSettings.getInt(DS_KEY_LAST_FOCUS);
- if (lastFocusNr < 0)
- lastFocusNr= 0;
- if (lastFocusNr > fTabPages.size() - 1)
- lastFocusNr= fTabPages.size() - 1;
- } catch (NumberFormatException x) {
- lastFocusNr= 0;
- }
-
- fTabFolder.setSelection(lastFocusNr);
- ((ModifyDialogTabPage)fTabFolder.getSelection()[0].getData()).setInitialFocus();
- }
-
- protected Control createDialogArea(Composite parent) {
- final Composite composite= (Composite)super.createDialogArea(parent);
-
- fTabFolder= new TabFolder(composite, SWT.NONE);
- fTabFolder.setFont(composite.getFont());
- fTabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- fPages= createTabPages(fWorkingValues);
-
- fCountLabel= new Label(composite, SWT.NONE);
- fCountLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- updateCountLabel();
-
- applyDialogFont(composite);
-
- fTabFolder.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {}
-
- public void widgetSelected(SelectionEvent e) {
- final TabItem tabItem= (TabItem)e.item;
- final ModifyDialogTabPage page= (ModifyDialogTabPage)tabItem.getData();
- fDialogSettings.put(DS_KEY_LAST_FOCUS, fTabPages.indexOf(page));
- page.makeVisible();
- }
- });
-
- updateStatus(StatusInfo.OK_STATUS);
-
- return composite;
- }
-
- protected CleanUpTabPage[] createTabPages(Map workingValues) {
- CleanUpTabPage[] result= new CleanUpTabPage[3];
- result[0]= new CodeStyleTabPage(this, workingValues, true);
-// result[1]= new MemberAccessesTabPage(this, workingValues, true);
- result[1]= new UnnecessaryCodeTabPage(this, workingValues, true);
-// result[3]= new MissingCodeTabPage(this, workingValues, true);
- result[2]= new CodeFormatingTabPage(this, workingValues, true);
-
- addTabPage(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_CodeStyle_TabPage, result[0]);
-// addTabPage(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_MemberAccesses_TabPage, result[1]);
- addTabPage(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_UnnecessaryCode_TabPage, result[1]);
-// addTabPage(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_MissingCode_TabPage, result[3]);
- addTabPage(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_CodeOrganizing_TabPage, result[2]);
-
- return result;
- }
-
- public void updateStatus(IStatus status) {
- int count= 0;
- for (int i= 0; i < fPages.length; i++) {
- count+= fPages[i].getSelectedCleanUpCount();
- }
- if (count == 0) {
- super.updateStatus(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_SelectAnAction_Error));
- } else {
- if (status == null) {
- super.updateStatus(StatusInfo.OK_STATUS);
- } else {
- super.updateStatus(status);
- }
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.window.Window#getInitialSize()
- */
- protected Point getInitialSize() {
- Point initialSize= super.getInitialSize();
- try {
- int lastWidth= fDialogSettings.getInt(DS_KEY_PREFERRED_WIDTH);
- if (initialSize.x > lastWidth)
- lastWidth= initialSize.x;
- int lastHeight= fDialogSettings.getInt(DS_KEY_PREFERRED_HEIGHT);
- if (initialSize.y > lastHeight)
- lastHeight= initialSize.x;
- return new Point(lastWidth, lastHeight);
- } catch (NumberFormatException ex) {
- }
- return initialSize;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point)
- */
- protected Point getInitialLocation(Point initialSize) {
- try {
- return new Point(fDialogSettings.getInt(DS_KEY_PREFERRED_X), fDialogSettings.getInt(DS_KEY_PREFERRED_Y));
- } catch (NumberFormatException ex) {
- return super.getInitialLocation(initialSize);
- }
- }
-
- public boolean close() {
- final Rectangle shell= getShell().getBounds();
-
- fDialogSettings.put(DS_KEY_PREFERRED_WIDTH, shell.width);
- fDialogSettings.put(DS_KEY_PREFERRED_HEIGHT, shell.height);
- fDialogSettings.put(DS_KEY_PREFERRED_X, shell.x);
- fDialogSettings.put(DS_KEY_PREFERRED_Y, shell.y);
-
- return super.close();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- applyPressed();
- super.okPressed();
- }
-
- protected void buttonPressed(int buttonId) {
- if (buttonId == APPLY_BUTTON_ID) {
- applyPressed();
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- private void applyPressed() {
- fOrginalValues= new HashMap(fWorkingValues);
- updateStatus(StatusInfo.OK_STATUS);
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- fApplyButton= createButton(parent, APPLY_BUTTON_ID, SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_Apply_Button, false);
- fApplyButton.setEnabled(false);
-
- GridLayout layout= (GridLayout)parent.getLayout();
- layout.numColumns++;
- layout.makeColumnsEqualWidth= false;
- Label label= new Label(parent, SWT.NONE);
- GridData data= new GridData();
- data.widthHint= layout.horizontalSpacing;
- label.setLayoutData(data);
- super.createButtonsForButtonBar(parent);
- }
-
- protected final void addTabPage(String title, ModifyDialogTabPage tabPage) {
- final TabItem tabItem= new TabItem(fTabFolder, SWT.NONE);
- applyDialogFont(tabItem.getControl());
- tabItem.setText(title);
- tabItem.setData(tabPage);
- tabItem.setControl(tabPage.createContents(fTabFolder));
- fTabPages.add(tabPage);
- }
-
- protected void updateButtonsEnableState(IStatus status) {
- super.updateButtonsEnableState(status);
- if (fApplyButton != null && !fApplyButton.isDisposed()) {
- fApplyButton.setEnabled(hasChanges() && !status.matches(IStatus.ERROR));
- }
- }
-
- private boolean hasChanges() {
- for (Iterator iterator= fWorkingValues.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- if (!fWorkingValues.get(key).equals(fOrginalValues.get(key)))
- return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public void valuesModified() {
- updateCountLabel();
- updateStatus(StatusInfo.OK_STATUS);
- }
-
- private void updateCountLabel() {
- int size= 0, count= 0;
- for (int i= 0; i < fPages.length; i++) {
- size+= fPages[i].getCleanUpCount();
- count+= fPages[i].getSelectedCleanUpCount();
- }
-
- fCountLabel.setText(Messages.format(SaveParticipantMessages.CleanUpSaveParticipantConfigurationModifyDialog_XofYSelected_Label, new Object[] {new Integer(count), new Integer(size)}));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantPreferenceConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantPreferenceConfiguration.java
deleted file mode 100644
index 726a10a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CleanUpSaveParticipantPreferenceConfiguration.java
+++ /dev/null
@@ -1,345 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpPostSaveListener;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpPreferenceUtil;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.AbstractSaveParticipantPreferenceConfiguration;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BulletListBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.CodeFormatterPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Preference configuration UI for the clean up save participant.
- *
- *
- */
-public class CleanUpSaveParticipantPreferenceConfiguration extends AbstractSaveParticipantPreferenceConfiguration {
-
- private static final int INDENT= 10;
-
- private IScopeContext fContext;
- private Map fSettings;
- private BulletListBlock fSelectedActionsText;
- private Button fFormatCodeButton;
-// private Button fOrganizeImportsButton;
- private Shell fShell;
- private Link fFormatConfigLink;
-// private Link fOrganizeImportsConfigLink;
- private IPreferencePageContainer fContainer;
- private Button fAdditionalActionButton;
- private Button fConfigureButton;
-
- /**
- * {@inheritDoc}
- */
- public Control createConfigControl(final Composite parent, IPreferencePageContainer container) {
- fContainer= container;
- fShell= parent.getShell();
-
- final Composite composite= new Composite(parent, SWT.NONE);
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.horizontalIndent= INDENT;
- composite.setLayoutData(gridData);
- GridLayout gridLayout= new GridLayout(1, false);
- gridLayout.marginHeight= 0;
- gridLayout.marginWidth= 0;
- composite.setLayout(gridLayout);
-
- fFormatCodeButton= new Button(composite, SWT.CHECK);
- fFormatCodeButton.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_FormatSource_Checkbox);
- fFormatCodeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- fFormatCodeButton.addSelectionListener(new SelectionAdapter() {
- /**
- * {@inheritDoc}
- */
- public void widgetSelected(SelectionEvent e) {
- changeSettingsValue(CleanUpConstants.FORMAT_SOURCE_CODE, fFormatCodeButton.getSelection());
- }
- });
-
- PixelConverter pixelConverter= new PixelConverter(parent);
- int heightOneHalf= (int)Math.round(pixelConverter.convertHeightInCharsToPixels(1) * 1.5);
-
- fFormatConfigLink= new Link(composite, SWT.NONE);
- fFormatConfigLink.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_ConfigureFormatter_Link);
- GridData gridData2= new GridData(SWT.LEFT, SWT.TOP, false, true);
- gridData2.horizontalIndent= 20;
- gridData2.minimumHeight= heightOneHalf;
- fFormatConfigLink.setLayoutData(gridData2);
-
-// fOrganizeImportsButton= new Button(composite, SWT.CHECK);
-// fOrganizeImportsButton.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_OrganizeImports_Checkbox);
-// fOrganizeImportsButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-// fOrganizeImportsButton.addSelectionListener(new SelectionAdapter() {
-// /**
-// * {@inheritDoc}
-// */
-// public void widgetSelected(SelectionEvent e) {
-// changeSettingsValue(CleanUpConstants.ORGANIZE_IMPORTS, fOrganizeImportsButton.getSelection());
-// }
-// });
-
-// fOrganizeImportsConfigLink= new Link(composite, SWT.NONE);
-// fOrganizeImportsConfigLink.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_ConfigureImports_Link);
-// GridData gridData3= new GridData(SWT.LEFT, SWT.TOP, false, true);
-// gridData3.horizontalIndent= 20;
-// gridData3.minimumHeight= heightOneHalf;
-// fOrganizeImportsConfigLink.setLayoutData(gridData3);
-
- fAdditionalActionButton= new Button(composite, SWT.CHECK);
- fAdditionalActionButton.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_AdditionalActions_Checkbox);
-
- createAdvancedComposite(composite);
- fAdditionalActionButton.addSelectionListener(new SelectionAdapter() {
- /**
- * {@inheritDoc}
- */
- public void widgetSelected(SelectionEvent e) {
- changeSettingsValue(CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS, fAdditionalActionButton.getSelection());
- }
- });
-
- return composite;
- }
-
- private Composite createAdvancedComposite(final Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.horizontalIndent= INDENT;
- composite.setLayoutData(gridData);
- GridLayout layout= new GridLayout(2, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- fSelectedActionsText= new BulletListBlock();
- final GridData data= (GridData)fSelectedActionsText.createControl(composite).getLayoutData();
- data.heightHint= new PixelConverter(composite).convertHeightInCharsToPixels(8);
-
- fConfigureButton= new Button(composite, SWT.NONE);
- fConfigureButton.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_Configure_Button);
- fConfigureButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
- fConfigureButton.addSelectionListener(new SelectionAdapter() {
- /**
- * {@inheritDoc}
- */
- public void widgetSelected(SelectionEvent e) {
- new CleanUpSaveParticipantConfigurationModifyDialog(parent.getShell(), fSettings, SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_CleanUpSaveParticipantConfiguration_Title).open();
- settingsChanged();
- }
-
- });
-
- return composite;
- }
-
- /**
- * {@inheritDoc}
- */
- public void initialize(final IScopeContext context, IAdaptable element) {
- fContext= context;
- fSettings= CleanUpPreferenceUtil.loadSaveParticipantOptions(context);
-
- settingsChanged();
-
- IJavaScriptProject javaProject= null;
- if (element != null) {
- IProject project= (IProject)element.getAdapter(IProject.class);
- if (project != null) {
- IJavaScriptProject jProject= JavaScriptCore.create(project);
- if (jProject != null && jProject.exists()) {
- javaProject= jProject;
- }
- }
- }
-
- configurePreferenceLink(fFormatConfigLink, javaProject, CodeFormatterPreferencePage.PREF_ID, CodeFormatterPreferencePage.PROP_ID);
-// configurePreferenceLink(fOrganizeImportsConfigLink, javaProject, ImportOrganizePreferencePage.PREF_ID, ImportOrganizePreferencePage.PROP_ID);
-
- super.initialize(context, element);
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- super.dispose();
- }
-
- /**
- * {@inheritDoc}
- */
- public void performDefaults() {
- fSettings= CleanUpPreferenceUtil.loadSaveParticipantOptions(new InstanceScope());
- settingsChanged();
- }
-
- /**
- * {@inheritDoc}
- */
- public void performOk() {
- super.performOk();
-
- if (!ProjectScope.SCOPE.equals(fContext.getName()) || hasSettingsInScope(fContext))
- CleanUpPreferenceUtil.saveSaveParticipantOptions(fContext, fSettings);
- }
-
- /**
- * {@inheritDoc}
- */
- public void enableProjectSettings() {
- super.enableProjectSettings();
-
- CleanUpPreferenceUtil.saveSaveParticipantOptions(fContext, fSettings);
-
- updateAdvancedEnableState();
- }
-
- /**
- * {@inheritDoc}
- */
- public void disableProjectSettings() {
- super.disableProjectSettings();
-
- IEclipsePreferences node= fContext.getNode(JavaScriptUI.ID_PLUGIN);
-
- Map settings= CleanUpConstants.getSaveParticipantSettings();
- for (Iterator iterator= settings.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- node.remove(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + key);
- }
-
- updateAdvancedEnableState();
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getPostSaveListenerId() {
- return CleanUpPostSaveListener.POSTSAVELISTENER_ID;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getPostSaveListenerName() {
- return SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_CleanUpActionsTopNodeName_Checkbox;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void enableConfigControl(boolean isEnabled) {
- super.enableConfigControl(isEnabled);
-
- updateAdvancedEnableState();
- }
-
- private void settingsChanged() {
- fFormatCodeButton.setSelection(CleanUpConstants.TRUE.equals(fSettings.get(CleanUpConstants.FORMAT_SOURCE_CODE)));
-// fOrganizeImportsButton.setSelection(CleanUpConstants.TRUE.equals(fSettings.get(CleanUpConstants.ORGANIZE_IMPORTS)));
- fAdditionalActionButton.setSelection(CleanUpConstants.TRUE.equals(fSettings.get(CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS)));
-
- updateAdvancedEnableState();
-
- Map settings= new HashMap(fSettings);
- settings.put(CleanUpConstants.FORMAT_SOURCE_CODE, CleanUpConstants.FALSE);
- settings.put(CleanUpConstants.ORGANIZE_IMPORTS, CleanUpConstants.FALSE);
-
- final ICleanUp[] cleanUps= CleanUpRefactoring.createCleanUps(settings);
-
- if (cleanUps.length == 0) {
- fSelectedActionsText.setText(SaveParticipantMessages.CleanUpSaveParticipantPreferenceConfiguration_NoActionEnabled_Info);
- } else {
- StringBuffer buf= new StringBuffer();
-
- boolean first= true;
- for (int i= 0; i < cleanUps.length; i++) {
- String[] descriptions= cleanUps[i].getDescriptions();
- if (descriptions != null) {
- for (int j= 0; j < descriptions.length; j++) {
- if (first) {
- first= false;
- } else {
- buf.append('\n');
- }
- buf.append(descriptions[j]);
- }
- }
- }
- fSelectedActionsText.setText(buf.toString());
- }
- }
-
- private void updateAdvancedEnableState() {
- boolean additionalOptionEnabled= isEnabled(fContext) && CleanUpConstants.TRUE.equals(fSettings.get(CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS));
- boolean additionalEnabled= additionalOptionEnabled && (!ProjectScope.SCOPE.equals(fContext.getName()) || hasSettingsInScope(fContext));
- fSelectedActionsText.setEnabled(additionalEnabled);
- fConfigureButton.setEnabled(additionalEnabled);
- }
-
- private void configurePreferenceLink(Link link, final IJavaScriptProject javaProject, final String preferenceId, final String propertyId) {
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (fContainer instanceof IWorkbenchPreferenceContainer) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer)fContainer;
- if (javaProject != null) {
- container.openPage(propertyId, null);
- } else {
- container.openPage(preferenceId, null);
- }
- } else {
- PreferencesUtil.createPreferenceDialogOn(fShell, preferenceId, null, null);
- }
- }
- });
- }
-
- private void changeSettingsValue(String key, boolean enabled) {
- String value;
- if (enabled) {
- value= CleanUpConstants.TRUE;
- } else {
- value= CleanUpConstants.FALSE;
- }
- fSettings.put(key, value);
- settingsChanged();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatCleanUp.java
deleted file mode 100644
index f7cd581c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatCleanUp.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class CodeFormatCleanUp extends AbstractCleanUp {
-
- public CodeFormatCleanUp() {
- super();
- }
-
- public CodeFormatCleanUp(Map options) {
- super(options);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return false;
- }
-
- public IFix createFix(IJavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean removeWhitespaces= isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES);
- return CodeFormatFix.createCleanUp(compilationUnit, isEnabled(CleanUpConstants.FORMAT_SOURCE_CODE), removeWhitespaces && isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_ALL), removeWhitespaces && isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return null;
- }
-
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- ArrayList result= new ArrayList();
- if (isEnabled(CleanUpConstants.FORMAT_SOURCE_CODE))
- result.add(MultiFixMessages.CodeFormatCleanUp_description);
-
- if (isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES)) {
- if (isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_ALL)) {
- result.add(MultiFixMessages.CodeFormatCleanUp_RemoveTrailingAll_description);
- } else if (isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY)) {
- result.add(MultiFixMessages.CodeFormatCleanUp_RemoveTrailingNoEmpty_description);
- }
- }
-
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
- buf.append(" function start() {}\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES) && isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_ALL)) {
- buf.append("\n"); //$NON-NLS-1$
- } else {
- buf.append(" \n"); //$NON-NLS-1$
- }
- if (isEnabled(CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES)) {
- buf.append(" function\n"); //$NON-NLS-1$
- } else {
- buf.append(" function \n"); //$NON-NLS-1$
- }
- buf.append(" stop() {\n"); //$NON-NLS-1$
- buf.append(" }\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatFix.java
deleted file mode 100644
index c68a955e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeFormatFix.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-public class CodeFormatFix implements IFix {
-
- public static IFix createCleanUp(IJavaScriptUnit cu, boolean format, boolean removeTrailingWhitespacesAll, boolean removeTrailingWhitespacesIgnorEmpty) throws CoreException {
- if (!format && !removeTrailingWhitespacesAll && !removeTrailingWhitespacesIgnorEmpty)
- return null;
-
- if (format) {
- Map fomatterSettings= new HashMap(cu.getJavaScriptProject().getOptions(true));
-
- String content= cu.getBuffer().getContents();
- Document document= new Document(content);
-
- TextEdit edit= CodeFormatterUtil.reformat(CodeFormatter.K_JAVASCRIPT_UNIT, content, 0, TextUtilities.getDefaultLineDelimiter(document), fomatterSettings);
- if (edit == null || !edit.hasChildren())
- return null;
-
- String label= MultiFixMessages.CodeFormatFix_description;
- TextChange change= new CompilationUnitChange(label, cu);
- change.setEdit(edit);
-
- CategorizedTextEditGroup group= new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
- group.addTextEdit(edit);
- change.addTextEditGroup(group);
-
- return new CodeFormatFix(change, cu);
- } else if (removeTrailingWhitespacesAll || removeTrailingWhitespacesIgnorEmpty) {
- try {
- MultiTextEdit multiEdit= new MultiTextEdit();
- Document document= new Document(cu.getBuffer().getContents());
-
- int lineCount= document.getNumberOfLines();
- for (int i= 0; i < lineCount; i++) {
-
- IRegion region= document.getLineInformation(i);
- if (region.getLength() == 0)
- continue;
-
- int lineStart= region.getOffset();
- int lineExclusiveEnd= lineStart + region.getLength();
- int j= getIndexOfRightMostNoneWhitspaceCharacter(lineStart, lineExclusiveEnd - 1, document);
-
- if (removeTrailingWhitespacesAll) {
- j++;
- if (j < lineExclusiveEnd)
- multiEdit.addChild(new DeleteEdit(j, lineExclusiveEnd - j));
- } else if (removeTrailingWhitespacesIgnorEmpty) {
- if (j >= lineStart) {
- if (document.getChar(j) == '*' && getIndexOfRightMostNoneWhitspaceCharacter(lineStart, j - 1, document) < lineStart) {
- j++;
- }
- j++;
- if (j < lineExclusiveEnd)
- multiEdit.addChild(new DeleteEdit(j, lineExclusiveEnd - j));
- }
- }
- }
-
- if (multiEdit.getChildrenSize() == 0)
- return null;
-
- String label= MultiFixMessages.CodeFormatFix_RemoveTrailingWhitespace_changeDescription;
- CompilationUnitChange change= new CompilationUnitChange(label, cu);
- change.setEdit(multiEdit);
-
- CategorizedTextEditGroup group= new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
- group.addTextEdit(multiEdit);
- change.addTextEditGroup(group);
-
- return new CodeFormatFix(change, cu);
- } catch (BadLocationException x) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, "", x)); //$NON-NLS-1$
- }
- }
-
- return null;
- }
-
- /**
- * Returns the index in document of a none whitespace character
- * between start (inclusive) and end (inclusive) such that if
- * more then one such character the index returned is the largest
- * possible (closest to end). Returns start - 1 if no such character.
- *
- * @param start
- * @param end
- * @param document
- * @return the position or start - 1
- * @throws BadLocationException
- */
- private static int getIndexOfRightMostNoneWhitspaceCharacter(int start, int end, Document document) throws BadLocationException {
- int position= end;
- while (position >= start && Character.isWhitespace(document.getChar(position)))
- position--;
-
- return position;
- }
-
- private final IJavaScriptUnit fCompilationUnit;
- private final TextChange fChange;
-
- public CodeFormatFix(TextChange change, IJavaScriptUnit compilationUnit) {
- fChange= change;
- fCompilationUnit= compilationUnit;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#createChange()
- */
- public TextChange createChange() throws CoreException {
- return fChange;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getCompilationUnit()
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getDescription()
- */
- public String getDescription() {
- return MultiFixMessages.CodeFormatFix_description;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.IFix#getStatus()
- */
- public IStatus getStatus() {
- return StatusInfo.OK_STATUS;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeStyleCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeStyleCleanUp.java
deleted file mode 100644
index bc6791a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CodeStyleCleanUp.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CodeStyleFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * Creates fixes which can resolve code style issues
- * @see org.eclipse.wst.jsdt.internal.corext.fix.CodeStyleFix
- */
-public class CodeStyleCleanUp extends AbstractCleanUp {
-
- public CodeStyleCleanUp() {
- this(null);
- }
-
- public CodeStyleCleanUp(Map options) {
- super(options);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- boolean nonStaticFields= isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS);
- boolean nonStaticMethods= isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS);
- boolean qualifyStatic= isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS);
-
- return nonStaticFields && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS) ||
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS) ||
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD) ||
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS) ||
- nonStaticMethods && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS) ||
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD) ||
- nonStaticFields && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY) ||
- nonStaticMethods && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean nonStaticFields= isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS);
- boolean nonStaticMethods= isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS);
- boolean qualifyStatic= isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS);
-
- return CodeStyleFix.createCleanUp(compilationUnit,
- nonStaticFields && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS),
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS),
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD),
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS),
- nonStaticMethods && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS),
- qualifyStatic && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD),
- nonStaticFields && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY),
- nonStaticMethods && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY)
- );
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return CodeStyleFix.createCleanUp(compilationUnit, problems,
- isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS),
- isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS),
- isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS));
- }
-
- public Map getRequiredOptions() {
- Map options= new Hashtable();
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS))
- options.put(JavaScriptCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaScriptCore.WARNING);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS))
- options.put(JavaScriptCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaScriptCore.WARNING);
- return options;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS))
- result.add(MultiFixMessages.CodeStyleMultiFix_AddThisQualifier_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS))
- result.add(MultiFixMessages.CodeStyleCleanUp_QualifyNonStaticMethod_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY))
- result.add(MultiFixMessages.CodeStyleCleanUp_removeFieldThis_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY))
- result.add(MultiFixMessages.CodeStyleCleanUp_removeMethodThis_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD))
- result.add(MultiFixMessages.CodeStyleMultiFix_QualifyAccessToStaticField);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD))
- result.add(MultiFixMessages.CodeStyleCleanUp_QualifyStaticMethod_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS))
- result.add(MultiFixMessages.CodeStyleMultiFix_ChangeNonStaticAccess_description);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS))
- result.add(MultiFixMessages.CodeStyleMultiFix_ChangeIndirectAccessToStaticToDirect);
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- buf.append("private int value;\n"); //$NON-NLS-1$
- buf.append("public int get() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS)) {
- buf.append(" return this.value + this.value;\n"); //$NON-NLS-1$
- } else if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_IF_NECESSARY)) {
- buf.append(" return value + value;\n"); //$NON-NLS-1$
- } else {
- buf.append(" return this.value + value;\n"); //$NON-NLS-1$
- }
- buf.append("}\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- buf.append("public int getZero() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_ALWAYS)) {
- buf.append(" return this.get() - this.get();\n"); //$NON-NLS-1$
- } else if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_METHOD_USE_THIS_IF_NECESSARY)) {
- buf.append(" return get() - get();\n"); //$NON-NLS-1$
- } else {
- buf.append(" return this.get() - get();\n"); //$NON-NLS-1$
- }
- buf.append("}\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- buf.append("class E {\n"); //$NON-NLS-1$
- buf.append(" public static int NUMBER;\n"); //$NON-NLS-1$
- buf.append(" public static void set(int i) {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_FIELD)) {
- buf.append(" E.NUMBER= i;\n"); //$NON-NLS-1$
- } else {
- buf.append(" NUMBER= i;\n"); //$NON-NLS-1$
- }
- buf.append(" }\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- buf.append(" public void reset() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_METHOD)) {
- buf.append(" E.set(0);\n"); //$NON-NLS-1$
- } else {
- buf.append(" set(0);\n"); //$NON-NLS-1$
- }
- buf.append(" }\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- buf.append("class ESub extends E {\n"); //$NON-NLS-1$
- buf.append(" public void reset() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS)) {
- buf.append(" E.NUMBER= 0;\n"); //$NON-NLS-1$
- } else {
- buf.append(" ESub.NUMBER= 0;\n"); //$NON-NLS-1$
- }
- buf.append(" }\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- buf.append("public void dec() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS)) {
- buf.append(" E.NUMBER--;\n"); //$NON-NLS-1$
- } else {
- buf.append(" (new E()).NUMBER--;\n"); //$NON-NLS-1$
- }
- buf.append("}\n"); //$NON-NLS-1$
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
-// if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS)) {
-// CodeStyleFix fix= CodeStyleFix.createAddFieldQualifierFix(compilationUnit, problem);
-// if (fix != null)
-// return true;
-// }
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS)) {
- CodeStyleFix fix= CodeStyleFix.createIndirectAccessToStaticFix(compilationUnit, problem);
- if (fix != null)
- return true;
- }
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS)) {
- CodeStyleFix[] fixes= CodeStyleFix.createNonStaticAccessFixes(compilationUnit, problem);
- if (fixes != null && fixes.length > 0)
- return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- int result= 0;
- IProblem[] problems= compilationUnit.getProblems();
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS))
- result+= getNumberOfProblems(problems, IProblem.UnqualifiedFieldAccess);
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS)) {
- for (int i=0;i<problems.length;i++) {
- int id= problems[i].getID();
- if (id == IProblem.IndirectAccessToStaticField || id == IProblem.IndirectAccessToStaticMethod)
- result++;
- }
- }
- if (isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS)) {
- for (int i=0;i<problems.length;i++) {
- int id= problems[i].getID();
- if (id == IProblem.NonStaticAccessToStaticField || id == IProblem.NonStaticAccessToStaticMethod)
- result++;
- }
- }
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatCleanUp.java
deleted file mode 100644
index bdb724fc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatCleanUp.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class CommentFormatCleanUp extends AbstractCleanUp {
-
- public CommentFormatCleanUp(Map options) {
- super(options);
- }
-
- public CommentFormatCleanUp() {
- super();
- }
-
- public IFix createFix(IJavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- if (!isEnabled(CleanUpConstants.FORMAT_SOURCE_CODE))
- return null;
-
- HashMap preferences= new HashMap(compilationUnit.getJavaScriptProject().getOptions(true));
-
- boolean singleLineComment= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT));
- boolean blockComment= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT));
- boolean javaDoc= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT));
-
- return CommentFormatFix.createCleanUp(compilationUnit, singleLineComment, blockComment, javaDoc, preferences);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return null;
- }
-
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- return null;
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
- buf.append("/**\n"); //$NON-NLS-1$
- buf.append(" *A JSDoc comment\n"); //$NON-NLS-1$
- buf.append("* \n"); //$NON-NLS-1$
- buf.append(" */\n"); //$NON-NLS-1$
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatFix.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatFix.java
deleted file mode 100644
index 3f6c018a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/CommentFormatFix.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup;
-import org.eclipse.ltk.core.refactoring.GroupCategory;
-import org.eclipse.ltk.core.refactoring.GroupCategorySet;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingStrategy;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-public class CommentFormatFix implements IFix {
-
- public static IFix createCleanUp(IJavaScriptUnit unit, boolean singleLine, boolean multiLine, boolean javaDoc, HashMap preferences) throws CoreException {
- if (!singleLine && !multiLine && !javaDoc)
- return null;
-
- String content= unit.getBuffer().getContents();
- Document document= new Document(content);
-
- final List edits= format(document, singleLine, multiLine, javaDoc, preferences);
-
- if (edits.size() == 0)
- return null;
-
- MultiTextEdit resultEdit= new MultiTextEdit();
- resultEdit.addChildren((TextEdit[])edits.toArray(new TextEdit[edits.size()]));
-
- TextChange change= new CompilationUnitChange(MultiFixMessages.CommentFormatFix_description, unit);
- change.setEdit(resultEdit);
-
- String label= MultiFixMessages.CommentFormatFix_description;
- CategorizedTextEditGroup group= new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label)));
- group.addTextEdit(resultEdit);
- change.addTextEditGroup(group);
-
- return new CommentFormatFix(change, unit);
- }
-
- static String format(String input, boolean singleLine, boolean multiLine, boolean javaDoc) {
- if (!singleLine && !multiLine && !javaDoc)
- return input;
-
- HashMap preferences= new HashMap(JavaScriptCore.getOptions());
- Document document= new Document(input);
- List edits= format(document, singleLine, multiLine, javaDoc, preferences);
-
- if (edits.size() == 0)
- return input;
-
- MultiTextEdit resultEdit= new MultiTextEdit();
- resultEdit.addChildren((TextEdit[])edits.toArray(new TextEdit[edits.size()]));
-
- try {
- resultEdit.apply(document);
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- return document.get();
- }
-
- private static List format(IDocument document, boolean singleLine, boolean multiLine, boolean javaDoc, HashMap preferences) {
- final List edits= new ArrayList();
-
- JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
-
- String content= document.get();
-
- CommentFormattingStrategy formattingStrategy= new CommentFormattingStrategy();
-
- IFormattingContext context= new CommentFormattingContext();
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE);
- context.setProperty(FormattingContextProperties.CONTEXT_MEDIUM, document);
-
- try {
- ITypedRegion[] regions= TextUtilities.computePartitioning(document, IJavaScriptPartitions.JAVA_PARTITIONING, 0, document.getLength(), false);
- for (int i= 0; i < regions.length; i++) {
- ITypedRegion region= regions[i];
- if (singleLine && region.getType().equals(IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT)) {
- TextEdit edit= format(region, context, formattingStrategy, content);
- if (edit != null)
- edits.add(edit);
- } else if (multiLine && region.getType().equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT)) {
- TextEdit edit= format(region, context, formattingStrategy, content);
- if (edit != null)
- edits.add(edit);
- } else if (javaDoc && region.getType().equals(IJavaScriptPartitions.JAVA_DOC)) {
- TextEdit edit= format(region, context, formattingStrategy, content);
- if (edit != null)
- edits.add(edit);
- }
- }
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } finally {
- context.dispose();
- }
-
- return edits;
- }
-
- private static TextEdit format(ITypedRegion region, IFormattingContext context, CommentFormattingStrategy formattingStrategy, String content) {
- TypedPosition typedPosition= new TypedPosition(region.getOffset(), region.getLength(), region.getType());
- context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, typedPosition);
- formattingStrategy.formatterStarts(context);
- TextEdit edit= formattingStrategy.calculateTextEdit();
- formattingStrategy.formatterStops();
- if (edit == null)
- return null;
-
- if (!edit.hasChildren())
- return null;
-
- // Filter out noops
- TextEdit[] children= edit.getChildren();
- for (int i= 0; i < children.length; i++) {
- if (!(children[i] instanceof ReplaceEdit))
- return edit;
- }
-
- IDocument doc= new Document(content);
- try {
- edit.copy().apply(doc, TextEdit.NONE);
- if (content.equals(doc.get()))
- return null;
- } catch (MalformedTreeException e) {
- } catch (BadLocationException e) {
- }
-
- return edit;
- }
-
- private final IJavaScriptUnit fCompilationUnit;
- private final TextChange fChange;
-
- public CommentFormatFix(TextChange change, IJavaScriptUnit compilationUnit) {
- fChange= change;
- fCompilationUnit= compilationUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- public TextChange createChange() throws CoreException {
- return fChange;
- }
-
- /**
- * {@inheritDoc}
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDescription() {
- return MultiFixMessages.CommentFormatFix_description;
- }
-
- /**
- * {@inheritDoc}
- */
- public IStatus getStatus() {
- return StatusInfo.OK_STATUS;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ControlStatementsCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ControlStatementsCleanUp.java
deleted file mode 100644
index ec13994e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ControlStatementsCleanUp.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.ControlStatementsFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class ControlStatementsCleanUp extends AbstractCleanUp {
-
- public ControlStatementsCleanUp(Map options) {
- super(options);
- }
-
- public ControlStatementsCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- boolean useBlocks= isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS);
-
- if (!useBlocks)
- return false;
-
- return isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS) ||
- isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER) ||
- isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean useBlocks= isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS);
- if (!useBlocks)
- return null;
-
- return ControlStatementsFix.createCleanUp(compilationUnit,
- isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS),
- isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER),
- isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- //No warnings generated by the compiler
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS))
- result.add(MultiFixMessages.CodeStyleMultiFix_ConvertSingleStatementInControlBodeyToBlock_description);
- if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER))
- result.add(MultiFixMessages.ControlStatementsCleanUp_RemoveUnnecessaryBlocks_description);
- if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW))
- result.add(MultiFixMessages.ControlStatementsCleanUp_RemoveUnnecessaryBlocksWithReturnOrThrow_description);
-
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS)) {
- buf.append("if (obj == null) {\n"); //$NON-NLS-1$
- buf.append(" throw ('some exception');\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
-
- buf.append("if (ids.length > 0) {\n"); //$NON-NLS-1$
- buf.append(" alert(ids[0]);\n"); //$NON-NLS-1$
- buf.append("} else {\n"); //$NON-NLS-1$
- buf.append(" return;\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
- } else if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER)){
- buf.append("if (obj == null)\n"); //$NON-NLS-1$
- buf.append(" throw ('some exception');\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
-
- buf.append("if (ids.length > 0)\n"); //$NON-NLS-1$
- buf.append(" alert(ids[0]);\n"); //$NON-NLS-1$
- buf.append("else\n"); //$NON-NLS-1$
- buf.append(" return;\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- } else if (isEnabled(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS) && isEnabled(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW)) {
- buf.append("if (obj == null)\n"); //$NON-NLS-1$
- buf.append(" throw ('some exception');\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
-
- buf.append("if (ids.length > 0) {\n"); //$NON-NLS-1$
- buf.append(" alert(ids[0]);\n"); //$NON-NLS-1$
- buf.append("} else \n"); //$NON-NLS-1$
- buf.append(" return;\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- } else {
- buf.append("if (obj == null) {\n"); //$NON-NLS-1$
- buf.append(" throw ('some exception');\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
-
- buf.append("if (ids.length > 0) {\n"); //$NON-NLS-1$
- buf.append(" alert(ids[0]);\n"); //$NON-NLS-1$
- buf.append("} else \n"); //$NON-NLS-1$
- buf.append(" return;\n"); //$NON-NLS-1$
- buf.append("\n"); //$NON-NLS-1$
- }
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ConvertLoopCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ConvertLoopCleanUp.java
deleted file mode 100644
index 9a36dd9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ConvertLoopCleanUp.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.ConvertLoopFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class ConvertLoopCleanUp extends AbstractCleanUp {
-
- public ConvertLoopCleanUp(Map options) {
- super(options);
- }
-
- public ConvertLoopCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return isEnabled(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean convertForLoops= isEnabled(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED);
-
- return ConvertLoopFix.createCleanUp(compilationUnit,
- convertForLoops, convertForLoops,
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- //No warnings generated by the compiler
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
-
- if (isEnabled(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED))
- result.add(MultiFixMessages.Java50CleanUp_ConvertToEnhancedForLoop_description);
-
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- if (isEnabled(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED)) {
- buf.append("for (var element in ids) {\n"); //$NON-NLS-1$
- buf.append(" var value= element / 2; \n"); //$NON-NLS-1$
- buf.append(" alert(value);\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
- } else {
- buf.append("for (var i = 0; i < ids.length; i++) {\n"); //$NON-NLS-1$
- buf.append(" var value= ids[i] / 2; \n"); //$NON-NLS-1$
- buf.append(" alert(value);\n"); //$NON-NLS-1$
- buf.append("}\n"); //$NON-NLS-1$
- }
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ExpressionsCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ExpressionsCleanUp.java
deleted file mode 100644
index 7137437a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ExpressionsCleanUp.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.ExpressionsFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class ExpressionsCleanUp extends AbstractCleanUp {
-
- public ExpressionsCleanUp(Map options) {
- super(options);
- }
-
- public ExpressionsCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- boolean usePrentheses= isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES);
- if (!usePrentheses)
- return false;
-
- return isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS) ||
- isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean usePrentheses= isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES);
- if (!usePrentheses)
- return null;
-
- return ExpressionsFix.createCleanUp(compilationUnit,
- isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS),
- isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- return createFix(compilationUnit);
- }
-
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS))
- result.add(MultiFixMessages.ExpressionsCleanUp_addParanoiac_description);
-
- if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER))
- result.add(MultiFixMessages.ExpressionsCleanUp_removeUnnecessary_description);
-
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS)) {
- buf.append("var b= (((i > 0) && (i < 10)) || (i == 50));\n"); //$NON-NLS-1$
- } else if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER)) {
- buf.append("var b= i > 0 && i < 10 || i == 50;\n"); //$NON-NLS-1$
- } else {
- buf.append("var b= (i > 0 && i < 10 || i == 50);\n"); //$NON-NLS-1$
- }
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS)) {
- IFix fix= ExpressionsFix.createAddParanoidalParenthesisFix(compilationUnit, new ASTNode[] {problem.getCoveredNode(compilationUnit)});
- if (fix != null)
- return true;
- }
- if (isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES) && isEnabled(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER)) {
- IFix fix= ExpressionsFix.createRemoveUnnecessaryParenthesisFix(compilationUnit, new ASTNode[] {problem.getCoveredNode(compilationUnit)});
- if (fix != null)
- return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ICleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ICleanUp.java
deleted file mode 100644
index 9f400b46..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ICleanUp.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * A clean up can solve several different problems in a given
- * <code>JavaScriptUnit</code>. The <code>JavaScriptUnit</code> is
- * compiled by using the compiler options returned by
- * <code>getRequiredOptions</code>.
- *
- *
- */
-public interface ICleanUp {
-
- /**
- * Does this clean up require an AST for the given <code>unit</code>. If
- * true is returned an AST for unit is created by the clean up
- * infrastructure and {@link #createFix(JavaScriptUnit)} is executed,
- * otherwise {@link #createFix(IJavaScriptUnit)} is executed. The source
- * from which the AST is created may be differ from the source of
- * <code>unit</code>.
- * <p>
- * Implementors should return false whenever possible because creating an
- * AST is expensive.
- *
- * @param unit
- * the unit to create an ast for
- * @return true if {@link #createFix(JavaScriptUnit)} must be executed,
- * false if {@link #createFix(IJavaScriptUnit)} must be executed
- */
- public abstract boolean requireAST(IJavaScriptUnit unit) throws CoreException;
-
- /**
- * Create an <code>IFix</code> which fixes all problems in
- * <code>unit</code> or <code>null</code> if nothing to fix.
- * <p>
- * This is called iff {@link #requireAST(IJavaScriptUnit)} returns
- * <code>false</code>.
- *
- * @param unit
- * the IJavaScriptUnit to fix, not null
- * @return the fix for the problems or <code>null</code> if nothing to fix
- */
- public abstract IFix createFix(IJavaScriptUnit unit) throws CoreException;
-
- /**
- * Create an <code>IFix</code> which fixes all problems in
- * <code>compilationUnit</code> or <code>null</code> if nothing to fix.
- * <p>
- * This is called iff {@link #requireAST(IJavaScriptUnit)} returns
- * <code>true</code>.
- *
- * @param compilationUnit
- * The compilation unit to fix, may be null
- * @return The fix or null if no fixes possible
- * @throws CoreException
- */
- public abstract IFix createFix(JavaScriptUnit compilationUnit) throws CoreException;
-
- /**
- * Create a <code>IFix</code> which fixes all <code>problems</code> in
- * <code>JavaScriptUnit</code>
- *
- * @param compilationUnit
- * The compilation unit to fix, may be null
- * @param problems
- * The locations of the problems to fix
- * @return The fix or null if no fixes possible
- * @throws CoreException
- */
- public abstract IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException;
-
- /**
- * Required compiler options to allow <code>createFix</code> to work
- * correct.
- *
- * @return The options as map or null
- */
- public abstract Map getRequiredOptions();
-
- /**
- * If true a fresh AST, containing all the changes from previous clean ups,
- * will be created and passed to createFix.
- *
- * @param compilationUnit
- * The current available AST
- * @return true if the caller needs an up to date AST
- */
- public abstract boolean needsFreshAST(JavaScriptUnit compilationUnit);
-
- /**
- * Description for each operation this clean up will execute
- *
- * @return descriptions or null
- */
- public String[] getDescriptions();
-
- public void initialize(Map settings) throws CoreException;
-
- /**
- * After call to checkPreConditions clients will start creating fixes for
- * <code>compilationUnits</code> int <code>project</code> unless the
- * result of checkPreConditions contains a fatal error
- *
- * @param project
- * The project to clean up
- * @param compilationUnits
- * The compilation Units to clean up, all member of project
- * @param monitor
- * the monitor to show progress
- * @return the result of the precondition check, not null
- */
- public abstract RefactoringStatus checkPreConditions(IJavaScriptProject project, IJavaScriptUnit[] compilationUnits, IProgressMonitor monitor) throws CoreException;
-
- /**
- * Called when done cleaning up.
- *
- * @param monitor
- * the monitor to show progress
- * @return the result of the postcondition check, not null
- */
- public abstract RefactoringStatus checkPostConditions(IProgressMonitor monitor) throws CoreException;
-
- /**
- * True if <code>problem</code> in <code>JavaScriptUnit</code> can be
- * fixed by this CleanUp. If true
- * <code>createFix(compilationUnit, new IProblemLocation[] {problem})</code>
- * does not return null.
- *
- * @param compilationUnit
- * The compilation unit to fix not null
- * @param problem
- * The location of the problem to fix
- * @return True if problem can be fixed
- * @throws CoreException
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException;
-
- /**
- * Maximal number of problems this clean up will fix in compilation unit.
- * There may be less then the returned number but never more.
- *
- * @param compilationUnit
- * The compilation unit to fix, not null
- * @return The maximal number of fixes or -1 if unknown.
- */
- public abstract int maximalNumberOfFixes(JavaScriptUnit compilationUnit);
-
- /**
- * A code snippet which complies to the current settings.
- *
- * @return A code snippet, not null.
- */
- public abstract String getPreview();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ImportsCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ImportsCleanUp.java
deleted file mode 100644
index ef637a88..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/ImportsCleanUp.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.ImportsFix;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class ImportsCleanUp extends AbstractCleanUp {
-
- private CodeGenerationSettings fCodeGeneratorSettings;
- private RefactoringStatus fStatus;
-
- public ImportsCleanUp(Map options) {
- super(options);
- }
-
- public ImportsCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return isEnabled(CleanUpConstants.ORGANIZE_IMPORTS);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(final JavaScriptUnit compilationUnit) throws CoreException {
- return ImportsFix.createCleanUp(compilationUnit, fCodeGeneratorSettings,
- isEnabled(CleanUpConstants.ORGANIZE_IMPORTS), fStatus);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkPreConditions(IJavaScriptProject project, IJavaScriptUnit[] compilationUnits, IProgressMonitor monitor) throws CoreException {
- RefactoringStatus result= super.checkPreConditions(project, compilationUnits, monitor);
-
- if (isEnabled(CleanUpConstants.ORGANIZE_IMPORTS)) {
- fCodeGeneratorSettings= JavaPreferencesSettings.getCodeGenerationSettings(project);
- fStatus= new RefactoringStatus();
- }
-
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public RefactoringStatus checkPostConditions(IProgressMonitor monitor) throws CoreException {
- fCodeGeneratorSettings= null;
- if (fStatus == null || fStatus.isOK()) {
- return super.checkPostConditions(monitor);
- } else {
- return fStatus;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- if (isEnabled(CleanUpConstants.ORGANIZE_IMPORTS))
- return new String[] {MultiFixMessages.ImportsCleanUp_OrganizeImports_Description};
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
-// if (isEnabled(CleanUpConstants.ORGANIZE_IMPORTS)) {
-// buf.append("import org.model.Engine;\n"); //$NON-NLS-1$
-// } else {
-// buf.append("import org.model.*;\n"); //$NON-NLS-1$
-// }
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsFreshAST(JavaScriptUnit compilationUnit) {
- if (isEnabled(CleanUpConstants.ORGANIZE_IMPORTS))
- return true;
-
- return super.needsFreshAST(compilationUnit);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.java
deleted file mode 100644
index aba88911..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import org.eclipse.osgi.util.NLS;
-
-public class MultiFixMessages extends NLS {
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.fix.MultiFixMessages"; //$NON-NLS-1$
-
- private MultiFixMessages() {
- }
-
- public static String CleanUpRefactoringWizard_CleaningUp11_Title;
- public static String CleanUpRefactoringWizard_CleaningUpN1_Title;
- public static String CleanUpRefactoringWizard_CleaningUpNN_Title;
- public static String CleanUpRefactoringWizard_CleanUpConfigurationPage_title;
- public static String CleanUpRefactoringWizard_code_organizing_tab;
- public static String CleanUpRefactoringWizard_code_style_tab;
- public static String CleanUpRefactoringWizard_Configure_Button;
- public static String CleanUpRefactoringWizard_ConfigureCustomProfile_button;
- public static String CleanUpRefactoringWizard_CustomCleanUpsDialog_title;
- public static String CleanUpRefactoringWizard_HideWizard_Link;
- public static String CleanUpRefactoringWizard_Profile_TableHeader;
- public static String CleanUpRefactoringWizard_Project_TableHeader;
- public static String CleanUpRefactoringWizard_unknownProfile_Name;
- public static String CleanUpRefactoringWizard_UnmanagedProfileWithName_Name;
- public static String CleanUpRefactoringWizard_unnecessary_code_tab;
- public static String CleanUpRefactoringWizard_use_configured_radio;
- public static String CleanUpRefactoringWizard_use_custom_radio;
- public static String CodeFormatCleanUp_RemoveTrailingAll_description;
- public static String CodeFormatCleanUp_RemoveTrailingNoEmpty_description;
- public static String CodeFormatFix_RemoveTrailingWhitespace_changeDescription;
- public static String ImportsCleanUp_OrganizeImports_Description;
- public static String SortMembersCleanUp_AllMembers_description;
- public static String SortMembersCleanUp_Excluding_description;
- public static String SortMembersCleanUp_RemoveMarkersWarning0;
- public static String StringMultiFix_AddMissingNonNls_description;
- public static String StringMultiFix_RemoveUnnecessaryNonNls_description;
-
- public static String UnusedCodeMultiFix_RemoveUnusedVariable_description;
- public static String UnusedCodeMultiFix_RemoveUnusedField_description;
- public static String UnusedCodeMultiFix_RemoveUnusedMethod_description;
- public static String UnusedCodeCleanUp_RemoveUnusedCasts_description;
-
- public static String CodeStyleMultiFix_ChangeNonStaticAccess_description;
- public static String CodeStyleMultiFix_AddThisQualifier_description;
- public static String CodeStyleMultiFix_QualifyAccessToStaticField;
- public static String CodeStyleMultiFix_ChangeIndirectAccessToStaticToDirect;
- public static String CodeStyleMultiFix_ConvertSingleStatementInControlBodeyToBlock_description;
- public static String CodeStyleCleanUp_QualifyNonStaticMethod_description;
- public static String CodeStyleCleanUp_QualifyStaticMethod_description;
- public static String CodeStyleCleanUp_removeFieldThis_description;
- public static String CodeStyleCleanUp_removeMethodThis_description;
-
- public static String Java50MultiFix_AddMissingDeprecated_description;
- public static String Java50MultiFix_AddMissingOverride_description;
- public static String Java50CleanUp_ConvertToEnhancedForLoop_description;
- public static String Java50CleanUp_AddTypeParameters_description;
-
- public static String CleanUpRefactoringWizard_WindowTitle;
- public static String CleanUpRefactoringWizard_PageTitle;
- public static String CleanUpRefactoringWizard_formatterException_errorMessage;
-
- public static String ControlStatementsCleanUp_RemoveUnnecessaryBlocks_description;
- public static String ControlStatementsCleanUp_RemoveUnnecessaryBlocksWithReturnOrThrow_description;
-
- public static String ExpressionsCleanUp_addParanoiac_description;
- public static String ExpressionsCleanUp_removeUnnecessary_description;
-
- public static String VariableDeclarationCleanUp_AddFinalField_description;
- public static String VariableDeclarationCleanUp_AddFinalParameters_description;
- public static String VariableDeclarationCleanUp_AddFinalLocals_description;
-
- public static String CodeFormatCleanUp_description;
- public static String CodeFormatFix_description;
-
- public static String CommentFormatFix_description;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, MultiFixMessages.class);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties
deleted file mode 100644
index 42328a3c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties
+++ /dev/null
@@ -1,73 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-StringMultiFix_AddMissingNonNls_description=Add missing '$NON-NLS$' tags
-StringMultiFix_RemoveUnnecessaryNonNls_description=Remove unnecessary '$NON-NLS$' tags
-
-UnusedCodeMultiFix_RemoveUnusedVariable_description=Remove unused local variables
-UnusedCodeMultiFix_RemoveUnusedField_description=Remove unused private vars
-UnusedCodeCleanUp_RemoveUnusedCasts_description=Remove unnecessary casts
-UnusedCodeMultiFix_RemoveUnusedMethod_description=Remove unused private functions
-
-CodeStyleMultiFix_ChangeNonStaticAccess_description=Change non static accesses to static members using declaring type
-ControlStatementsCleanUp_RemoveUnnecessaryBlocks_description=Remove unnecessary blocks
-ControlStatementsCleanUp_RemoveUnnecessaryBlocksWithReturnOrThrow_description=Remove blocks containing a single return or throw statement
-CodeStyleMultiFix_ChangeIndirectAccessToStaticToDirect=Change indirect accesses to static members to direct accesses (accesses through subtypes)
-CodeFormatFix_RemoveTrailingWhitespace_changeDescription=Remove trailing whitespace
-CodeFormatCleanUp_RemoveTrailingNoEmpty_description=Remove trailing whitespaces on non empty lines
-CodeStyleCleanUp_QualifyNonStaticMethod_description=Add 'this' qualifier to unqualified function accesses
-CodeStyleCleanUp_QualifyStaticMethod_description=Qualify accesses to static functions with declaring class
-CodeStyleMultiFix_AddThisQualifier_description=Add 'this' qualifier to unqualified field accesses
-CodeFormatCleanUp_RemoveTrailingAll_description=Remove trailing whitespaces on all lines
-CodeStyleMultiFix_QualifyAccessToStaticField=Qualify accesses to static fields with declaring class
-CodeStyleCleanUp_removeFieldThis_description=Remove 'this' qualifier for non static var accesses
-CodeStyleCleanUp_removeMethodThis_description=Remove 'this' qualifier for non static var accesses
-CodeStyleMultiFix_ConvertSingleStatementInControlBodeyToBlock_description=Convert control statement bodies to block
-
-Java50MultiFix_AddMissingDeprecated_description=Add missing '@Deprecated' annotations
-Java50CleanUp_ConvertToEnhancedForLoop_description=Convert for loops to enhanced for loops
-Java50CleanUp_AddTypeParameters_description=Add type parameters to raw type references
-Java50MultiFix_AddMissingOverride_description=Add missing '@Override' annotations
-
-CleanUpRefactoringWizard_unknownProfile_Name=Unknown
-CleanUpRefactoringWizard_use_configured_radio=&Use configured profiles
-CleanUpRefactoringWizard_unnecessary_code_tab=U&nnecessary Code
-CleanUpRefactoringWizard_Project_TableHeader=Project
-CleanUpRefactoringWizard_Profile_TableHeader=Profile
-CleanUpRefactoringWizard_code_organizing_tab=Code &Organizing
-CleanUpRefactoringWizard_Configure_Button=Confi&gure...
-CleanUpRefactoringWizard_use_custom_radio=Use custom &profile
-CleanUpRefactoringWizard_code_style_tab=&Code Style
-CleanUpRefactoringWizard_HideWizard_Link=Go to the <a>Clean Up</a> preference page to hide this wizard in the future
-CleanUpRefactoringWizard_CleaningUp11_Title=Cleaning up 1 file in 1 project
-CleanUpRefactoringWizard_CleaningUpN1_Title=Cleaning up {0} files in 1 project
-CleanUpRefactoringWizard_CleaningUpNN_Title=Cleaning up {0} files in {1} projects
-CleanUpRefactoringWizard_formatterException_errorMessage=The formatter threw an unhandled exception while formatting the preview.
-CleanUpRefactoringWizard_WindowTitle=Clean Up
-CleanUpRefactoringWizard_PageTitle=Clean Up
-ExpressionsCleanUp_addParanoiac_description=Add paranoiac parentheses
-ExpressionsCleanUp_removeUnnecessary_description=Remove unnecessary parentheses
-VariableDeclarationCleanUp_AddFinalField_description=Add final modifier to private vars
-VariableDeclarationCleanUp_AddFinalParameters_description=Add final modifier to function parameters
-VariableDeclarationCleanUp_AddFinalLocals_description=Add final modifier to local variables
-
-CleanUpRefactoringWizard_CleanUpConfigurationPage_title=Clean Up Configuration
-CleanUpRefactoringWizard_UnmanagedProfileWithName_Name=Unmanaged profile ''{0}''
-CleanUpRefactoringWizard_ConfigureCustomProfile_button=Confi&gure...
-CleanUpRefactoringWizard_CustomCleanUpsDialog_title=Custom Clean Ups
-
-CommentFormatFix_description=Format comment
-
-CodeFormatFix_description=Format code
-CodeFormatCleanUp_description=Format source code
-ImportsCleanUp_OrganizeImports_Description=Organize imports
-SortMembersCleanUp_AllMembers_description=Sort all members
-SortMembersCleanUp_Excluding_description=Sort members excluding vars, enum constants, and initializers
-SortMembersCleanUp_RemoveMarkersWarning0=The file ''{0}'' in project ''{1}'' contains markers which may be removed by Sort Members
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.java
deleted file mode 100644
index 3453cfa8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import org.eclipse.osgi.util.NLS;
-
-public class SaveParticipantMessages extends NLS {
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.fix.SaveParticipantMessages"; //$NON-NLS-1$
-
- public static String CleanUpSaveParticipantConfigurationModifyDialog_Apply_Button;
- public static String CleanUpSaveParticipantConfigurationModifyDialog_CodeOrganizing_TabPage;
- public static String CleanUpSaveParticipantConfigurationModifyDialog_CodeStyle_TabPage;
-
- public static String CleanUpSaveParticipantConfigurationModifyDialog_SelectAnAction_Error;
- public static String CleanUpSaveParticipantConfigurationModifyDialog_UnnecessaryCode_TabPage;
-
- public static String CleanUpSaveParticipantConfigurationModifyDialog_XofYSelected_Label;
-
- public static String CleanUpSaveParticipantPreferenceConfiguration_AdditionalActions_Checkbox;
- public static String CleanUpSaveParticipantPreferenceConfiguration_CleanUpActionsTopNodeName_Checkbox;
- public static String CleanUpSaveParticipantPreferenceConfiguration_CleanUpSaveParticipantConfiguration_Title;
- public static String CleanUpSaveParticipantPreferenceConfiguration_Configure_Button;
- public static String CleanUpSaveParticipantPreferenceConfiguration_ConfigureFormatter_Link;
-// public static String CleanUpSaveParticipantPreferenceConfiguration_ConfigureImports_Link;
- public static String CleanUpSaveParticipantPreferenceConfiguration_NoActionEnabled_Info;
- public static String CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_FormatSource_Checkbox;
-// public static String CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_OrganizeImports_Checkbox;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, SaveParticipantMessages.class);
- }
-
- private SaveParticipantMessages() {}
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties
deleted file mode 100644
index 906d9ad8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties
+++ /dev/null
@@ -1,25 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_FormatSource_Checkbox=Format &source code
-CleanUpSaveParticipantPreferenceConfiguration_CleanUpActionsTopNodeName_Checkbox=Per&form the selected actions on save
-CleanUpSaveParticipantPreferenceConfiguration_AdditionalActions_Checkbox=Addi&tional actions
-CleanUpSaveParticipantPreferenceConfiguration_Configure_Button=Co&nfigure...
-CleanUpSaveParticipantPreferenceConfiguration_ConfigureFormatter_Link=Configure the formatter settings on the <a>Formatter</a> page.
-#CleanUpSaveParticipantPreferenceConfiguration_ConfigureImports_Link=Configure the organize imports settings on the <a>Organize Imports</a> page.
-CleanUpSaveParticipantPreferenceConfiguration_NoActionEnabled_Info=No action enabled.\n\nSelect 'Configure...' to enable some actions.
-CleanUpSaveParticipantConfigurationModifyDialog_CodeStyle_TabPage=&Code Style
-CleanUpSaveParticipantConfigurationModifyDialog_UnnecessaryCode_TabPage=&Unnecessary Code
-CleanUpSaveParticipantConfigurationModifyDialog_SelectAnAction_Error=Select at least one save action.
-CleanUpSaveParticipantConfigurationModifyDialog_XofYSelected_Label={0} of {1} save actions activated
-CleanUpSaveParticipantConfigurationModifyDialog_CodeOrganizing_TabPage=Code &Organizing
-CleanUpSaveParticipantConfigurationModifyDialog_Apply_Button=&Apply
-CleanUpSaveParticipantPreferenceConfiguration_CleanUpSaveParticipantConfiguration_Title=Additional Save Actions
-#CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_OrganizeImports_Checkbox=Organize &imports
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SortMembersCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SortMembersCleanUp.java
deleted file mode 100644
index ee21098d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SortMembersCleanUp.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - https://bugs.eclipse.org/bugs/show_bug.cgi?id=168954
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.debug.core.model.IBreakpoint;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.SortMembersFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-import com.ibm.icu.text.MessageFormat;
-
-public class SortMembersCleanUp extends AbstractCleanUp {
-
- private HashSet fTouchedFiles;
-
- public SortMembersCleanUp() {
- super();
- }
-
- public SortMembersCleanUp(Map options) {
- super(options);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean sortMembers= isEnabled(CleanUpConstants.SORT_MEMBERS);
- IFix fix= SortMembersFix.createCleanUp(compilationUnit, sortMembers, sortMembers && isEnabled(CleanUpConstants.SORT_MEMBERS_ALL));
- if (fix != null) {
- if (fTouchedFiles == null) {
- fTouchedFiles= new HashSet();
- }
- fTouchedFiles.add(((IJavaScriptUnit)compilationUnit.getJavaElement()).getResource());
- }
- return fix;
- }
-
- public RefactoringStatus checkPostConditions(IProgressMonitor monitor) throws CoreException {
- if (fTouchedFiles == null) {
- return super.checkPostConditions(monitor);
- } else {
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- monitor.beginTask("", fTouchedFiles.size()); //$NON-NLS-1$
-
- try {
- RefactoringStatus result= new RefactoringStatus();
- for (Iterator iterator= fTouchedFiles.iterator(); iterator.hasNext();) {
- IFile file= (IFile)iterator.next();
- if (containsRelevantMarkers(file)) {
- String fileLocation= file.getProjectRelativePath().toOSString();
- String projectName= file.getProject().getName();
- result.addWarning(MessageFormat.format(MultiFixMessages.SortMembersCleanUp_RemoveMarkersWarning0, new Object[] {fileLocation, projectName}));
- }
-
- monitor.worked(1);
- }
-
- return result;
- } finally {
- monitor.done();
- fTouchedFiles= null;
- }
-
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- return null;
- }
-
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- if (isEnabled(CleanUpConstants.SORT_MEMBERS)) {
- if (isEnabled(CleanUpConstants.SORT_MEMBERS_ALL)) {
- return new String[] {MultiFixMessages.SortMembersCleanUp_AllMembers_description};
- } else {
- return new String[] {MultiFixMessages.SortMembersCleanUp_Excluding_description};
- }
- }
- return null;
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- buf.append("class SortExample {\n"); //$NON-NLS-1$
-
- if ((isEnabled(CleanUpConstants.SORT_MEMBERS) && isEnabled(CleanUpConstants.SORT_MEMBERS_ALL))) {
- buf.append(" private String bar;\n"); //$NON-NLS-1$
- buf.append(" private String foo;\n"); //$NON-NLS-1$
- } else {
- buf.append(" private String foo;\n"); //$NON-NLS-1$
- buf.append(" private String bar;\n"); //$NON-NLS-1$
- }
-
- if (isEnabled(CleanUpConstants.SORT_MEMBERS)) {
- buf.append(" private void bar() {}\n"); //$NON-NLS-1$
- buf.append(" private void foo() {}\n"); //$NON-NLS-1$
- } else {
- buf.append(" private void foo() {}\n"); //$NON-NLS-1$
- buf.append(" private void bar() {}\n"); //$NON-NLS-1$
- }
-
- buf.append("}\n"); //$NON-NLS-1$
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return isEnabled(CleanUpConstants.SORT_MEMBERS);
- }
-
- private static boolean containsRelevantMarkers(IFile file) throws CoreException {
- IMarker[] bookmarks= file.findMarkers(IMarker.BOOKMARK, true, IResource.DEPTH_INFINITE);
- if (bookmarks.length != 0)
- return true;
-
- IMarker[] tasks= file.findMarkers(IMarker.TASK, true, IResource.DEPTH_INFINITE);
- if (tasks.length != 0)
- return true;
-
- IMarker[] breakpoints= file.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
- if (breakpoints.length != 0)
- return true;
-
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/StringCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/StringCleanUp.java
deleted file mode 100644
index 17c9cbde..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/StringCleanUp.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.StringFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * Create fixes which can solve problems in connection with Strings
- * @see org.eclipse.wst.jsdt.internal.corext.fix.StringFix
- *
- */
-public class StringCleanUp extends AbstractCleanUp {
-
- public StringCleanUp(Map options) {
- super(options);
- }
-
- public StringCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS) ||
- isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return StringFix.createCleanUp(compilationUnit,
- isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS),
- isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return StringFix.createCleanUp(compilationUnit, problems,
- isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS),
- isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS));
- }
-
- public Map getRequiredOptions() {
- Map result= new Hashtable();
-
- if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS) || isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
- result.put(JavaScriptCore.COMPILER_PB_NON_NLS_STRING_LITERAL, JavaScriptCore.WARNING);
-
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS))
- result.add(MultiFixMessages.StringMultiFix_AddMissingNonNls_description);
- if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
- result.add(MultiFixMessages.StringMultiFix_RemoveUnnecessaryNonNls_description);
- return (String[])result.toArray(new String[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
- if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS)) {
- buf.append("var s=\"\";"); //$NON-NLS-1$
- } else {
- buf.append("var s=\"\"; //$NON-NLS-1$"); //$NON-NLS-1$
- }
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- * @throws CoreException
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return StringFix.createFix(compilationUnit, problem, isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS), isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS)) != null;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- int result= 0;
- IProblem[] problems= compilationUnit.getProblems();
- if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS))
- result+= getNumberOfProblems(problems, IProblem.NonExternalizedStringLiteral);
-
- if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
- result+= getNumberOfProblems(problems, IProblem.UnnecessaryNLSTag);
-
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnnecessaryCodeCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnnecessaryCodeCleanUp.java
deleted file mode 100644
index df7fadc1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnnecessaryCodeCleanUp.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.UnusedCodeFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class UnnecessaryCodeCleanUp extends AbstractCleanUp {
-
- public UnnecessaryCodeCleanUp(Map options) {
- super(options);
- }
-
- public UnnecessaryCodeCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- return isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return UnusedCodeFix.createCleanUp(compilationUnit,
- false,
- false,
- false,
- false,
- false,
- false,
- isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS));
- }
-
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- return UnusedCodeFix.createCleanUp(compilationUnit, problems,
- false,
- false,
- false,
- false,
- false,
- false,
- isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS));
- }
-
- public Map getRequiredOptions() {
- Map options= new Hashtable();
-
- if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS))
- options.put(JavaScriptCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaScriptCore.WARNING);
-
- return options;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS))
- result.add(MultiFixMessages.UnusedCodeCleanUp_RemoveUnusedCasts_description);
- return (String[])result.toArray(new String[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
-// if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_CASTS)) {
-// buf.append("Boolean b= Boolean.TRUE;\n"); //$NON-NLS-1$
-// } else {
-// buf.append("Boolean b= (Boolean) Boolean.TRUE;\n"); //$NON-NLS-1$
-// }
-//
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- int result= 0;
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java
deleted file mode 100644
index 7db3af3b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.UnusedCodeFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- * Create fixes which can remove unused code
- * @see org.eclipse.wst.jsdt.internal.corext.fix.UnusedCodeFix
- *
- */
-public class UnusedCodeCleanUp extends AbstractCleanUp {
-
- public UnusedCodeCleanUp(Map options) {
- super(options);
- }
-
- public UnusedCodeCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- boolean removeUnuseMembers= isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS);
-
- return removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS) ||
-// removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS) ||
- removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS) ||
-// removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES) ;
-// isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS);
- }
-
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean removeUnuseMembers= isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS);
-
- return UnusedCodeFix.createCleanUp(compilationUnit,
- removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS),
- removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS),
- removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS),
- removeUnuseMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES),
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES),
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS),
- false);
- }
-
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean removeMembers= isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS);
- return UnusedCodeFix.createCleanUp(compilationUnit, problems,
- removeMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS),
- removeMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS),
- removeMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS),
- removeMembers && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES),
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES),
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS),
- false);
- }
-
- public Map getRequiredOptions() {
- Map options= new Hashtable();
-
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS))
- options.put(JavaScriptCore.COMPILER_PB_UNUSED_IMPORT, JavaScriptCore.WARNING);
-
- boolean removeMembers= isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS);
- if (removeMembers && (
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES)))
- options.put(JavaScriptCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaScriptCore.WARNING);
-
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES))
- options.put(JavaScriptCore.COMPILER_PB_UNUSED_LOCAL, JavaScriptCore.WARNING);
-
- return options;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
-// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS))
-// result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedImport_description);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS))
- result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedMethod_description);
-// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS))
-// result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedConstructor_description);
-// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES))
-// result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedType_description);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS))
- result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedField_description);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES))
- result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedVariable_description);
- return (String[])result.toArray(new String[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-
-//// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS)) {
-//// } else {
-//// buf.append("import pack.Bar;\n"); //$NON-NLS-1$
-//// }
-//// buf.append("class Example {\n"); //$NON-NLS-1$
-// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES)) {
-// } else {
-// buf.append(" private class Sub {}\n"); //$NON-NLS-1$
-// }
-// if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS)) {
-// } else {
-// buf.append(" function Example() {}\n"); //$NON-NLS-1$
-// }
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS)) {
- } else {
- buf.append(" var fField;\n"); //$NON-NLS-1$
- }
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS)) {
- } else {
- buf.append(" function foo() {}\n"); //$NON-NLS-1$
- }
- buf.append(" function bar() {\n"); //$NON-NLS-1$
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES)) {
- } else {
- buf.append(" var i= 10;\n"); //$NON-NLS-1$
- }
- buf.append(" }\n"); //$NON-NLS-1$
-// buf.append("}\n"); //$NON-NLS-1$
-
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS)) {
- UnusedCodeFix fix= UnusedCodeFix.createRemoveUnusedImportFix(compilationUnit, problem);
- if (fix != null)
- return true;
- }
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS) ||
- isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES))
- {
- UnusedCodeFix fix= UnusedCodeFix.createUnusedMemberFix(compilationUnit, problem, false);
- if (fix != null)
- return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- int result= 0;
- IProblem[] problems= compilationUnit.getProblems();
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS)) {
- for (int i=0;i<problems.length;i++) {
- int id= problems[i].getID();
- if (id == IProblem.DuplicateImport || id == IProblem.ConflictingImport ||
- id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound)
- result++;
- }
- }
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS))
- result+= getNumberOfProblems(problems, IProblem.UnusedPrivateMethod);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS))
- result+= getNumberOfProblems(problems, IProblem.UnusedPrivateConstructor);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES))
- result+= getNumberOfProblems(problems, IProblem.UnusedPrivateType);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS))
- result+= getNumberOfProblems(problems, IProblem.UnusedPrivateField);
- if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES))
- result+= getNumberOfProblems(problems, IProblem.LocalVariableIsNeverUsed);
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/VariableDeclarationCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/VariableDeclarationCleanUp.java
deleted file mode 100644
index fdf4b4cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/VariableDeclarationCleanUp.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.fix;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.VariableDeclarationFix;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class VariableDeclarationCleanUp extends AbstractCleanUp {
-
- public VariableDeclarationCleanUp(Map options) {
- super(options);
- }
-
- public VariableDeclarationCleanUp() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean requireAST(IJavaScriptUnit unit) throws CoreException {
- boolean addFinal= isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL);
- if (!addFinal)
- return false;
-
- return isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS) ||
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS) ||
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES);
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit) throws CoreException {
- if (compilationUnit == null)
- return null;
-
- boolean addFinal= isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL);
- if (!addFinal)
- return null;
-
- return VariableDeclarationFix.createCleanUp(compilationUnit,
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS),
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS),
- isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES));
- }
-
- /**
- * {@inheritDoc}
- */
- public IFix createFix(JavaScriptUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
- //No warnings generated by the compiler
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map getRequiredOptions() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public String[] getDescriptions() {
- List result= new ArrayList();
- if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS))
- result.add(MultiFixMessages.VariableDeclarationCleanUp_AddFinalField_description);
- if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS))
- result.add(MultiFixMessages.VariableDeclarationCleanUp_AddFinalParameters_description);
- if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES))
- result.add(MultiFixMessages.VariableDeclarationCleanUp_AddFinalLocals_description);
-
- return (String[])result.toArray(new String[result.size()]);
- }
-
- public String getPreview() {
- StringBuffer buf= new StringBuffer();
-//
-// if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS)) {
-// buf.append("private final int i= 0;\n"); //$NON-NLS-1$
-// } else {
-// buf.append("private int i= 0;\n"); //$NON-NLS-1$
-// }
-// if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS)) {
-// buf.append("public void foo(final int j) {\n"); //$NON-NLS-1$
-// } else {
-// buf.append("public void foo(int j) {\n"); //$NON-NLS-1$
-// }
-// if (isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL) && isEnabled(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES)) {
-// buf.append(" final int k;\n"); //$NON-NLS-1$
-// buf.append(" int h;\n"); //$NON-NLS-1$
-// buf.append(" h= 0;\n"); //$NON-NLS-1$
-// } else {
-// buf.append(" int k, h;\n"); //$NON-NLS-1$
-// buf.append(" h= 0;\n"); //$NON-NLS-1$
-// }
-// buf.append("}\n"); //$NON-NLS-1$
-//
- return buf.toString();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean canFix(JavaScriptUnit compilationUnit, IProblemLocation problem) throws CoreException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int maximalNumberOfFixes(JavaScriptUnit compilationUnit) {
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java
deleted file mode 100644
index 715f68b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java
+++ /dev/null
@@ -1,572 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.resource.ColorRegistry;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.JSdocContentAccess;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-/**
- * Abstract class for views which show information for a given element.
- *
- *
- */
-public abstract class AbstractInfoView extends ViewPart implements ISelectionListener, IMenuListener, IPropertyChangeListener {
-
-
- /** JavaScriptElementLabels flags used for the title */
- private final long TITLE_FLAGS= JavaScriptElementLabels.ALL_FULLY_QUALIFIED
- | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_EXCEPTIONS
- | JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE | JavaScriptElementLabels.M_PRE_TYPE_PARAMETERS | JavaScriptElementLabels.T_TYPE_PARAMETERS
- | JavaScriptElementLabels.USE_RESOLVED;
- private final long LOCAL_VARIABLE_TITLE_FLAGS= TITLE_FLAGS & ~JavaScriptElementLabels.F_FULLY_QUALIFIED | JavaScriptElementLabels.F_POST_QUALIFIED;
-
- /** JavaScriptElementLabels flags used for the tool tip text */
- private static final long TOOLTIP_LABEL_FLAGS= JavaScriptElementLabels.DEFAULT_QUALIFIED | JavaScriptElementLabels.ROOT_POST_QUALIFIED | JavaScriptElementLabels.APPEND_ROOT_PATH |
- JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_APP_RETURNTYPE | JavaScriptElementLabels.M_EXCEPTIONS |
- JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.T_TYPE_PARAMETERS;
-
-
- /*
- * @see IPartListener2
- */
- private IPartListener2 fPartListener= new IPartListener2() {
- public void partVisible(IWorkbenchPartReference ref) {
- if (ref.getId().equals(getSite().getId())) {
- IWorkbenchPart activePart= ref.getPage().getActivePart();
- if (activePart != null)
- selectionChanged(activePart, ref.getPage().getSelection());
- startListeningForSelectionChanges();
- }
- }
- public void partHidden(IWorkbenchPartReference ref) {
- if (ref.getId().equals(getSite().getId()))
- stopListeningForSelectionChanges();
- }
- public void partInputChanged(IWorkbenchPartReference ref) {
- if (!ref.getId().equals(getSite().getId()))
- computeAndSetInput(ref.getPart(false));
- }
- public void partActivated(IWorkbenchPartReference ref) {
- }
- public void partBroughtToTop(IWorkbenchPartReference ref) {
- }
- public void partClosed(IWorkbenchPartReference ref) {
- }
- public void partDeactivated(IWorkbenchPartReference ref) {
- }
- public void partOpened(IWorkbenchPartReference ref) {
- }
- };
-
-
- /** The current input. */
- protected IJavaScriptElement fCurrentViewInput;
- /** The copy to clipboard action. */
- private SelectionDispatchAction fCopyToClipboardAction;
- /** The goto input action. */
- private GotoInputAction fGotoInputAction;
- /** Counts the number of background computation requests. */
- private volatile int fComputeCount;
-
- /**
- * Background color.
- *
- */
- private Color fBackgroundColor;
- private RGB fBackgroundColorRGB;
-
-
- /**
- * Set the input of this view.
- *
- * @param input the input object
- */
- abstract protected void setInput(Object input);
-
- /**
- * Computes the input for this view based on the given element.
- *
- * @param element the element from which to compute the input
- * @return the input or <code>null</code> if the input was not computed successfully
- */
- abstract protected Object computeInput(Object element);
-
- /**
- * Create the part control.
- *
- * @param parent the parent control
- * @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- abstract protected void internalCreatePartControl(Composite parent);
-
- /**
- * Set the view's foreground color.
- *
- * @param color the SWT color
- */
- abstract protected void setForeground(Color color);
-
- /**
- * Set the view's background color.
- *
- * @param color the SWT color
- */
- abstract protected void setBackground(Color color);
-
- /**
- * Returns the view's primary control.
- *
- * @return the primary control
- */
- abstract Control getControl();
-
- /**
- * Returns the context ID for the Help system
- *
- * @return the string used as ID for the Help context
- *
- */
- abstract protected String getHelpContextId();
-
- /*
- * @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- public final void createPartControl(Composite parent) {
- internalCreatePartControl(parent);
- inititalizeColors();
- getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener);
- createContextMenu();
- createActions();
- fillActionBars(getViewSite().getActionBars());
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), getHelpContextId());
- }
-
- /**
- * Creates the actions and action groups for this view.
- */
- protected void createActions() {
- fGotoInputAction= new GotoInputAction(this);
- fGotoInputAction.setEnabled(false);
- fCopyToClipboardAction= new CopyToClipboardAction(getViewSite());
-
- ISelectionProvider provider= getSelectionProvider();
- if (provider != null)
- provider.addSelectionChangedListener(fCopyToClipboardAction);
- }
-
- /**
- * Creates the context menu for this view.
- */
- protected void createContextMenu() {
- MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuManager.setRemoveAllWhenShown(true);
- menuManager.addMenuListener(this);
- Menu contextMenu= menuManager.createContextMenu(getControl());
- getControl().setMenu(contextMenu);
- getSite().registerContextMenu(menuManager, getSelectionProvider());
- }
-
- /*
- * @see IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
- */
- public void menuAboutToShow(IMenuManager menu) {
- menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
- menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
- menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
-
- IAction action;
-
- action= getCopyToClipboardAction();
- if (action != null)
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, action);
-
- action= getSelectAllAction();
- if (action != null)
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, action);
-
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fGotoInputAction);
- }
-
- protected IAction getSelectAllAction() {
- return null;
- }
-
- protected IAction getCopyToClipboardAction() {
- return fCopyToClipboardAction;
- }
-
- /**
- * Returns the input of this view.
- *
- * @return input the input object or <code>null</code> if not input is set
- */
- protected IJavaScriptElement getInput() {
- return fCurrentViewInput;
- }
-
- // Helper method
- ISelectionProvider getSelectionProvider() {
- return getViewSite().getSelectionProvider();
- }
-
- /**
- * Fills the actions bars.
- * <p>
- * Subclasses may extend.
- *
- * @param actionBars the action bars
- */
- protected void fillActionBars(IActionBars actionBars) {
- IToolBarManager toolBar= actionBars.getToolBarManager();
- fillToolBar(toolBar);
-
- IAction action;
-
- action= getCopyToClipboardAction();
- if (action != null)
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), action);
-
- action= getSelectAllAction();
- if (action != null)
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), action);
- }
-
- /**
- * Fills the tool bar.
- * <p>
- * Default is to do nothing.</p>
- *
- * @param tbm the tool bar manager
- */
- protected void fillToolBar(IToolBarManager tbm) {
- tbm.add(fGotoInputAction);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#inititalizeColors()
- *
- */
- private void inititalizeColors() {
- if (getSite().getShell().isDisposed())
- return;
-
- Display display= getSite().getShell().getDisplay();
- if (display == null || display.isDisposed())
- return;
-
- setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
-
- ColorRegistry registry= JFaceResources.getColorRegistry();
- registry.addListener(this);
-
- fBackgroundColorRGB= registry.getRGB(getBackgroundColorKey());
- Color bgColor;
- if (fBackgroundColorRGB == null) {
- bgColor= display.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- fBackgroundColorRGB= bgColor.getRGB();
- } else {
- bgColor= new Color(display, fBackgroundColorRGB);
- fBackgroundColor= bgColor;
- }
-
- setBackground(bgColor);
- }
-
- /**
- * The preference key for the background color.
- *
- * @return the background color key
- *
- */
- abstract protected String getBackgroundColorKey();
-
- public void propertyChange(PropertyChangeEvent event) {
- if (getBackgroundColorKey().equals(event.getProperty()))
- inititalizeColors();
- }
-
- /**
- * Start to listen for selection changes.
- */
- protected void startListeningForSelectionChanges() {
- getSite().getPage().addPostSelectionListener(this);
- }
-
- /**
- * Stop to listen for selection changes.
- */
- protected void stopListeningForSelectionChanges() {
- getSite().getPage().removePostSelectionListener(this);
- }
-
- /*
- * @see ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
- */
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (part.equals(this))
- return;
-
- computeAndSetInput(part);
- }
-
- /**
- * Tells whether the new input should be ignored
- * if the current input is the same.
- *
- * @param je the new input
- * @param selection the current selection from the part that provides the input
- * @return <code>true</code> if the new input should be ignored
- */
- protected boolean isIgnoringNewInput(IJavaScriptElement je, IWorkbenchPart part, ISelection selection) {
- return fCurrentViewInput != null && fCurrentViewInput.equals(je) && je != null;
- }
-
- /**
- * Finds and returns the Java element selected in the given part.
- *
- * @param part the workbench part for which to find the selected Java element
- * @param selection the selection
- * @return the selected Java element
- */
- protected IJavaScriptElement findSelectedJavaElement(IWorkbenchPart part, ISelection selection) {
- Object element = null;
- try {
- if (part instanceof JavaEditor && selection instanceof ITextSelection) {
- IJavaScriptElement[] elements= TextSelectionConverter.codeResolve((JavaEditor)part, (ITextSelection)selection);
- if (elements != null) {
- if (elements.length > 1) {
- for (int i = 0; i < elements.length; i++) {
- if (elements[i] == null)
- continue;
- int elementType = elements[i].getElementType();
- if ((elementType == IJavaScriptElement.METHOD || elementType == IJavaScriptElement.FIELD || elementType == IJavaScriptElement.TYPE || elementType == IJavaScriptElement.INITIALIZER) && JSdocContentAccess.getContentReader((IMember) elements[i], true) != null) {
- return elements[i];
- }
- if (elementType == IJavaScriptElement.LOCAL_VARIABLE && JSdocContentAccess.getContentReader((ILocalVariable) elements[i], true) != null) {
- return elements[i];
- }
- }
- }
- else if (elements.length > 0) {
- return elements[0];
- }
- }
- else {
- return null;
- }
- } else if (selection instanceof IStructuredSelection) {
- element= SelectionUtil.getSingleElement(selection);
- } else {
- return null;
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
-
- return findJavaElement(element);
- }
-
- /**
- * Tries to get a Java element out of the given element.
- *
- * @param element an object
- * @return the Java element represented by the given element or <code>null</code>
- */
- private IJavaScriptElement findJavaElement(Object element) {
-
- if (element == null)
- return null;
-
- IJavaScriptElement je= null;
- if (element instanceof IAdaptable)
- je= (IJavaScriptElement)((IAdaptable)element).getAdapter(IJavaScriptElement.class);
-
- return je;
- }
-
- /**
- * Finds and returns the type for the given CU.
- *
- * @param cu the compilation unit
- * @return the type with same name as the given CU or the first type in the CU
- */
- protected IType getTypeForCU(IJavaScriptUnit cu) {
-
- if (cu == null || !cu.exists())
- return null;
-
- // Use primary type if possible
- IType primaryType= cu.findPrimaryType();
- if (primaryType != null)
- return primaryType;
-
- // Use first top-level type
- try {
- IType[] types= cu.getTypes();
- if (types.length > 0)
- return types[0];
- else
- return null;
- } catch (JavaScriptModelException ex) {
- return null;
- }
- }
-
- /*
- * @see IWorkbenchPart#dispose()
- */
- final public void dispose() {
- // cancel possible running computation
- fComputeCount++;
-
- getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener);
-
- ISelectionProvider provider= getSelectionProvider();
- if (provider != null)
- provider.removeSelectionChangedListener(fCopyToClipboardAction);
-
- JFaceResources.getColorRegistry().removeListener(this);
- fBackgroundColorRGB= null;
- if (fBackgroundColor != null) {
- fBackgroundColor.dispose();
- fBackgroundColor= null;
- }
-
- internalDispose();
-
- }
-
- /*
- * @see IWorkbenchPart#dispose()
- */
- abstract protected void internalDispose();
-
- /**
- * Determines all necessary details and delegates the computation into
- * a background thread.
- *
- * @param part the workbench part
- */
- private void computeAndSetInput(final IWorkbenchPart part) {
-
- final int currentCount= ++fComputeCount;
-
- ISelectionProvider provider= part.getSite().getSelectionProvider();
- if (provider == null)
- return;
-
- final ISelection selection= provider.getSelection();
- if (selection == null || selection.isEmpty())
- return;
-
- Thread thread= new Thread("Info view input computer") { //$NON-NLS-1$
- public void run() {
- if (currentCount != fComputeCount)
- return;
-
- final IJavaScriptElement je= findSelectedJavaElement(part, selection);
-
- if (isIgnoringNewInput(je, part, selection))
- return;
-
- // The actual computation
- final Object input= computeInput(je);
- if (input == null)
- return;
-
- Shell shell= getSite().getShell();
- if (shell.isDisposed())
- return;
-
- Display display= shell.getDisplay();
- if (display.isDisposed())
- return;
-
- display.asyncExec(new Runnable() {
- /*
- * @see java.lang.Runnable#run()
- */
- public void run() {
-
- if (fComputeCount != currentCount || getViewSite().getShell().isDisposed())
- return;
-
- fCurrentViewInput= je;
- doSetInput(input);
- }
- });
- }
- };
-
- thread.setDaemon(true);
- thread.setPriority(Thread.MIN_PRIORITY);
- thread.start();
- }
-
- private void doSetInput(Object input) {
- setInput(input);
-
- fGotoInputAction.setEnabled(true);
-
- IJavaScriptElement inputElement= getInput();
-
- long flags;
- if (inputElement instanceof ILocalVariable)
- flags= LOCAL_VARIABLE_TITLE_FLAGS;
- else
- flags= TITLE_FLAGS;
-
- setContentDescription(JavaScriptElementLabels.getElementLabel(inputElement, flags));
- setTitleToolTip(JavaScriptElementLabels.getElementLabel(inputElement, TOOLTIP_LABEL_FLAGS));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/CopyToClipboardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/CopyToClipboardAction.java
deleted file mode 100644
index d3232d1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/CopyToClipboardAction.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-class CopyToClipboardAction extends SelectionDispatchAction{
-
- private final static int MAX_REPEAT_COUNT= 10;
-
- private Clipboard fClipboard;
-
- public CopyToClipboardAction(IWorkbenchSite site) {
- super(site);
-
- setText(InfoViewMessages.CopyAction_label);
- setToolTipText(InfoViewMessages.CopyAction_tooltip);
- setDescription(InfoViewMessages.CopyAction_description);
-
- ISharedImages workbenchImages= PlatformUI.getWorkbench().getSharedImages();
- setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
- setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
- setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IAbstractTextEditorHelpContextIds.COPY_ACTION);
-
- update(getSelection());
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(selection != null && selection.getLength() > 0);
- }
-
- public void run(ITextSelection selection) {
- fClipboard= new Clipboard(getShell().getDisplay());
- try {
- copyToClipboard(selection, 0);
- } finally {
- fClipboard.dispose();
- }
- }
-
- private void copyToClipboard(ITextSelection selection, int repeatCount) {
- try{
- fClipboard.setContents(new String[] { selection.getText() }, new Transfer[] { TextTransfer.getInstance() });
- } catch (SWTError e) {
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD || repeatCount >= MAX_REPEAT_COUNT)
- throw e;
-
- if (MessageDialog.openQuestion(getShell(), InfoViewMessages.CopyToClipboard_error_title, InfoViewMessages.CopyToClipboard_error_message))
- copyToClipboard(selection, repeatCount + 1);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/GotoInputAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/GotoInputAction.java
deleted file mode 100644
index 504ea9b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/GotoInputAction.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-
-class GotoInputAction extends Action {
-
- private AbstractInfoView fInfoView;
-
- public GotoInputAction(AbstractInfoView infoView) {
- Assert.isNotNull(infoView);
- fInfoView= infoView;
-
- JavaPluginImages.setLocalImageDescriptors(this, "goto_input.gif"); //$NON-NLS-1$
- setText(InfoViewMessages.GotoInputAction_label);
- setToolTipText(InfoViewMessages.GotoInputAction_tooltip);
- setDescription(InfoViewMessages.GotoInputAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_INPUT_ACTION);
- }
-
- public void run() {
- IJavaScriptElement inputElement= fInfoView.getInput();
- new OpenAction(fInfoView.getViewSite()).run(new Object[] { inputElement });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.java
deleted file mode 100644
index a1dc4049..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class InfoViewMessages extends NLS {
-
- private static final String BUNDLE_NAME= InfoViewMessages.class.getName();
-
- private InfoViewMessages() {
- // Do not instantiate
- }
-
- public static String CopyAction_label;
- public static String CopyAction_tooltip;
- public static String CopyAction_description;
- public static String SelectAllAction_label;
- public static String SelectAllAction_tooltip;
- public static String SelectAllAction_description;
- public static String GotoInputAction_label;
- public static String GotoInputAction_tooltip;
- public static String GotoInputAction_description;
- public static String CopyToClipboard_error_title;
- public static String CopyToClipboard_error_message;
- public static String JavadocView_error_noBrowser_title;
- public static String JavadocView_error_noBrowser_message;
- public static String JavadocView_error_noBrowser_doNotWarn;
- public static String JavadocView_noAttachments;
- public static String JavadocView_noAttachedSource;
- public static String JavadocView_noAttachedJavadoc;
- public static String JavadocView_noInformation;
- public static String JavadocView_error_gettingJavadoc;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, InfoViewMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties
deleted file mode 100644
index 34477793..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties
+++ /dev/null
@@ -1,35 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-CopyAction_label= &Copy
-CopyAction_tooltip= Copy the Selected Text to the Clipboard
-CopyAction_description= Copy
-
-SelectAllAction_label= Select &All
-SelectAllAction_tooltip= Select All
-SelectAllAction_description= Select All
-
-GotoInputAction_label= Open &Input
-GotoInputAction_tooltip= Open Input
-GotoInputAction_description= Open Input
-
-CopyToClipboard_error_title= Problem Copying to Clipboard
-CopyToClipboard_error_message= There was a problem when accessing the system clipboard. Retry?
-
-JavadocView_error_noBrowser_title= JSDoc view
-JavadocView_error_noBrowser_message= The HTML Browser widget could not be created. The standard text widget will be used instead.
-JavadocView_error_noBrowser_doNotWarn= Do not show this message again.
-JavadocView_noAttachments= <em>Note: This element neither has attached source nor attached JSDoc and hence no JSDoc could be found.</em>
-JavadocView_noAttachedSource= <em>Note: This element has no attached source and the JSDoc could not be found in the attached JSDoc.</em>
-JavadocView_noAttachedJavadoc= <em>Note: This element has no attached Jdoc and the Jdoc could not be found in the attached source.</em>
-JavadocView_noInformation= <em>Note: The JSDoc for this element could neither be found in the attached source nor the attached JSDoc.</em>
-JavadocView_error_gettingJavadoc= <em>Note: An exception occurred while getting the JSDoc. See log for details.</em>
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java
deleted file mode 100644
index ac0aa806..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java
+++ /dev/null
@@ -1,703 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringReader;
-import java.net.URL;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPartitioningException;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.browser.Browser;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JSdocContentAccess;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.osgi.framework.Bundle;
-
-/**
- * View which shows Javadoc for a given Java element.
- *
- * FIXME: As of 3.0 selectAll() and getSelection() is not working
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
- *
- *
- */
-public class JavadocView extends AbstractInfoView {
-
- /**
- * Preference key for the preference whether to show a dialog
- * when the SWT Browser widget is not available.
- *
- */
- private static final String DO_NOT_WARN_PREFERENCE_KEY= "JavadocView.error.doNotWarn"; //$NON-NLS-1$
-
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=73558
- private static final boolean WARNING_DIALOG_ENABLED= false;
-
- /** Flags used to render a label in the text widget. */
- private static final long LABEL_FLAGS= JavaScriptElementLabels.ALL_FULLY_QUALIFIED
- | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_EXCEPTIONS
- | JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE | JavaScriptElementLabels.T_TYPE_PARAMETERS;
-
-
- /** The HTML widget. */
- private Browser fBrowser;
- /** The text widget. */
- private StyledText fText;
- /** The information presenter. */
- private DefaultInformationControl.IInformationPresenter fPresenter;
- /** The text presentation. */
- private TextPresentation fPresentation= new TextPresentation();
- /** The select all action */
- private SelectAllAction fSelectAllAction;
- /** The style sheet (css) */
- private static String fgStyleSheet;
- /**
- * <code>true</code> once the style sheet has been loaded.
- *
- */
- private static boolean fgStyleSheetLoaded= false;
-
- /** The Browser widget */
- private boolean fIsUsingBrowserWidget;
-
- private RGB fBackgroundColorRGB;
- /**
- * The font listener.
- *
- */
- private IPropertyChangeListener fFontListener;
-
-
- /**
- * The Javadoc view's select all action.
- */
- private class SelectAllAction extends Action {
-
- /** The control. */
- private Control fControl;
- /** The selection provider. */
- private SelectionProvider fSelectionProvider;
-
- /**
- * Creates the action.
- *
- * @param control the widget
- * @param selectionProvider the selection provider
- */
- public SelectAllAction(Control control, SelectionProvider selectionProvider) {
- super("selectAll"); //$NON-NLS-1$
-
- Assert.isNotNull(control);
- Assert.isNotNull(selectionProvider);
- fControl= control;
- fSelectionProvider= selectionProvider;
-
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
- setEnabled(!fIsUsingBrowserWidget);
-
- setText(InfoViewMessages.SelectAllAction_label);
- setToolTipText(InfoViewMessages.SelectAllAction_tooltip);
- setDescription(InfoViewMessages.SelectAllAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION);
- }
-
- /**
- * Selects all in the view.
- */
- public void run() {
- if (fControl instanceof StyledText)
- ((StyledText)fControl).selectAll();
- else {
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
-// ((Browser)fControl).selectAll();
- if (fSelectionProvider != null)
- fSelectionProvider.fireSelectionChanged();
- }
- }
- }
-
- /**
- * The Javadoc view's selection provider.
- */
- private static class SelectionProvider implements ISelectionProvider {
-
- /** The selection changed listeners. */
- private ListenerList fListeners= new ListenerList(ListenerList.IDENTITY);
- /** The widget. */
- private Control fControl;
-
- /**
- * Creates a new selection provider.
- *
- * @param control the widget
- */
- public SelectionProvider(Control control) {
- Assert.isNotNull(control);
- fControl= control;
- if (fControl instanceof StyledText) {
- ((StyledText)fControl).addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fireSelectionChanged();
- }
- });
- } else {
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
-// ((Browser)fControl).addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent e) {
-// fireSelectionChanged();
-// }
-// });
- }
- }
-
- /**
- * Sends a selection changed event to all listeners.
- */
- public void fireSelectionChanged() {
- ISelection selection= getSelection();
- SelectionChangedEvent event= new SelectionChangedEvent(this, selection);
- Object[] selectionChangedListeners= fListeners.getListeners();
- for (int i= 0; i < selectionChangedListeners.length; i++)
- ((ISelectionChangedListener)selectionChangedListeners[i]).selectionChanged(event);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- fListeners.add(listener);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
- */
- public ISelection getSelection() {
- if (fControl instanceof StyledText) {
- IDocument document= new Document(((StyledText)fControl).getSelectionText());
- return new TextSelection(document, 0, document.getLength());
- } else {
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
- return StructuredSelection.EMPTY;
- }
- }
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- fListeners.remove(listener);
- }
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
- */
- public void setSelection(ISelection selection) {
- // not supported
- }
- }
-
- /*
- * @see AbstractInfoView#internalCreatePartControl(Composite)
- */
- protected void internalCreatePartControl(Composite parent) {
- try {
- fBrowser= new Browser(parent, SWT.NONE);
- fIsUsingBrowserWidget= true;
-
- } catch (SWTError er) {
-
- /* The Browser widget throws an SWTError if it fails to
- * instantiate properly. Application code should catch
- * this SWTError and disable any feature requiring the
- * Browser widget.
- * Platform requirements for the SWT Browser widget are available
- * from the SWT FAQ web site.
- */
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean doNotWarn= store.getBoolean(DO_NOT_WARN_PREFERENCE_KEY);
- if (WARNING_DIALOG_ENABLED && !doNotWarn) {
- String title= InfoViewMessages.JavadocView_error_noBrowser_title;
- String message= InfoViewMessages.JavadocView_error_noBrowser_message;
- String toggleMessage= InfoViewMessages.JavadocView_error_noBrowser_doNotWarn;
- MessageDialogWithToggle dialog= MessageDialogWithToggle.openError(parent.getShell(), title, message, toggleMessage, false, null, null);
- if (dialog.getReturnCode() == Window.OK)
- store.setValue(DO_NOT_WARN_PREFERENCE_KEY, dialog.getToggleState());
- }
-
- fIsUsingBrowserWidget= false;
- }
-
- if (!fIsUsingBrowserWidget) {
- fText= new StyledText(parent, SWT.V_SCROLL | SWT.H_SCROLL);
- fText.setEditable(false);
- fPresenter= new HTMLTextPresenter(false);
-
- fText.addControlListener(new ControlAdapter() {
- /*
- * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent)
- */
- public void controlResized(ControlEvent e) {
- setInput(fText.getText());
- }
- });
- }
-
- initStyleSheet();
- listenForFontChanges();
- getViewSite().setSelectionProvider(new SelectionProvider(getControl()));
- }
-
- /**
- * Registers a listener for the Java editor font.
- *
- *
- */
- private void listenForFontChanges() {
- fFontListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (PreferenceConstants.APPEARANCE_JAVADOC_FONT.equals(event.getProperty())) {
- fgStyleSheetLoaded= false;
- // trigger reloading, but make sure other listeners have already run, so that
- // the style sheet gets reloaded only once.
- final Display display= getSite().getPage().getWorkbenchWindow().getWorkbench().getDisplay();
- if (!display.isDisposed()) {
- display.asyncExec(new Runnable() {
- public void run() {
- if (!display.isDisposed()) {
- initStyleSheet();
- refresh();
- }
- }
- });
- }
- }
- }
- };
- JFaceResources.getFontRegistry().addListener(fFontListener);
- }
-
- private static void initStyleSheet() {
- if (fgStyleSheetLoaded)
- return;
- fgStyleSheetLoaded= true;
- fgStyleSheet= loadStyleSheet();
- }
-
- private static String loadStyleSheet() {
- Bundle bundle= Platform.getBundle(JavaScriptPlugin.getPluginId());
- URL styleSheetURL= bundle.getEntry("/JavadocViewStyleSheet.css"); //$NON-NLS-1$
- if (styleSheetURL == null)
- return null;
-
- try {
- styleSheetURL= FileLocator.toFileURL(styleSheetURL);
- BufferedReader reader= new BufferedReader(new InputStreamReader(styleSheetURL.openStream()));
- StringBuffer buffer= new StringBuffer(200);
- String line= reader.readLine();
- while (line != null) {
- buffer.append(line);
- buffer.append('\n');
- line= reader.readLine();
- }
-
- FontData fontData= JFaceResources.getFontRegistry().getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
- return HTMLPrinter.convertTopLevelFont(buffer.toString(), fontData);
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- return null;
- }
- }
-
- /*
- * @see AbstractInfoView#createActions()
- */
- protected void createActions() {
- super.createActions();
- fSelectAllAction= new SelectAllAction(getControl(), (SelectionProvider)getSelectionProvider());
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getSelectAllAction()
- *
- */
- protected IAction getSelectAllAction() {
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
- if (fIsUsingBrowserWidget)
- return null;
-
- return fSelectAllAction;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getCopyToClipboardAction()
- *
- */
- protected IAction getCopyToClipboardAction() {
- // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63022
- if (fIsUsingBrowserWidget)
- return null;
-
- return super.getCopyToClipboardAction();
- }
-
- /*
- * @see AbstractInfoView#setForeground(Color)
- */
- protected void setForeground(Color color) {
- getControl().setForeground(color);
- }
-
- /*
- * @see AbstractInfoView#setBackground(Color)
- */
- protected void setBackground(Color color) {
- getControl().setBackground(color);
- fBackgroundColorRGB= color.getRGB();
- refresh();
- }
-
- /**
- * Refreshes the view.
- *
- *
- */
- private void refresh() {
- IJavaScriptElement input= getInput();
- if (input == null) {
- StringBuffer buffer= new StringBuffer(""); //$NON-NLS-1$
- HTMLPrinter.insertPageProlog(buffer, 0, fBackgroundColorRGB, fgStyleSheet);
- setInput(buffer.toString());
- } else {
- setInput(computeInput(input));
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getBackgroundColorKey()
- *
- */
- protected String getBackgroundColorKey() {
- return "org.eclipse.wst.jsdt.ui.JavadocView.backgroundColor"; //$NON-NLS-1$
- }
-
- /*
- * @see AbstractInfoView#internalDispose()
- */
- protected void internalDispose() {
- fText= null;
- fBrowser= null;
- if (fFontListener != null) {
- JFaceResources.getFontRegistry().removeListener(fFontListener);
- fFontListener= null;
- }
- }
-
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
- */
- public void setFocus() {
- getControl().setFocus();
- }
-
- /*
- * @see AbstractInfoView#computeInput(Object)
- */
- protected Object computeInput(Object input) {
- if (getControl() == null || ! (input instanceof IJavaScriptElement))
- return null;
-
- IJavaScriptElement je= (IJavaScriptElement)input;
- String javadocHtml;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- try {
- javadocHtml= getJavadocHtml(((IJavaScriptUnit)je).getTypes());
- } catch (JavaScriptModelException ex) {
- javadocHtml= null;
- }
- break;
- case IJavaScriptElement.CLASS_FILE:
- javadocHtml= getJavadocHtml(new IJavaScriptElement[] {((IClassFile)je).getType()});
- break;
- default:
- javadocHtml= getJavadocHtml(new IJavaScriptElement[] { je });
- }
-
- if (javadocHtml == null)
- return ""; //$NON-NLS-1$
-
- return javadocHtml;
- }
-
- /*
- * @see AbstractInfoView#setInput(Object)
- */
- protected void setInput(Object input) {
- String javadocHtml= (String)input;
-
- if (fIsUsingBrowserWidget) {
- if (javadocHtml != null && javadocHtml.length() > 0) {
- boolean RTL= (getSite().getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0;
- if (RTL) {
- StringBuffer buffer= new StringBuffer(javadocHtml);
- HTMLPrinter.insertStyles(buffer, new String[] { "direction:rtl" } ); //$NON-NLS-1$
- javadocHtml= buffer.toString();
- }
- }
- fBrowser.setText(javadocHtml);
- } else {
- fPresentation.clear();
- Rectangle size= fText.getClientArea();
-
- try {
- javadocHtml= ((DefaultInformationControl.IInformationPresenterExtension)fPresenter).updatePresentation(getSite().getShell(), javadocHtml, fPresentation, size.width, size.height);
- } catch (IllegalArgumentException ex) {
- // the javadoc might no longer be valid
- return;
- }
- fText.setText(javadocHtml);
- TextPresentation.applyTextPresentation(fPresentation, fText);
- }
- }
-
- /**
- * Returns the Javadoc in HTML format.
- *
- * @param result the Java elements for which to get the Javadoc
- * @return a string with the Javadoc in HTML format.
- */
- private String getJavadocHtml(IJavaScriptElement[] result) {
- StringBuffer buffer= new StringBuffer();
- int nResults= result.length;
-
- if (nResults == 0)
- return null;
-
- if (nResults > 1) {
-
- for (int i= 0; i < result.length; i++) {
- HTMLPrinter.startBulletList(buffer);
- IJavaScriptElement curr= result[i];
- if (curr instanceof IMember)
- HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr));
- HTMLPrinter.endBulletList(buffer);
- }
-
- } else {
-
- IJavaScriptElement curr= result[0];
- if (curr instanceof IMember) {
- IMember member= (IMember) curr;
-// HTMLPrinter.addSmallHeader(buffer, getInfoText(member));
- Reader reader;
- try {
- reader= JSdocContentAccess.getHTMLContentReader(member, true, true);
-
- // Provide hint why there's no Javadoc
- if (reader == null && member.isBinary()) {
- boolean hasAttachedJavadoc= JavaDocLocations.getJavadocBaseLocation(member) != null;
- IPackageFragmentRoot root= (IPackageFragmentRoot)member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- boolean hasAttachedSource= root != null && root.getSourceAttachmentPath() != null;
- IOpenable openable= member.getOpenable();
- boolean hasSource= openable.getBuffer() != null;
-
- if (!hasAttachedSource && !hasAttachedJavadoc)
- reader= new StringReader(InfoViewMessages.JavadocView_noAttachments);
- else if (!hasAttachedJavadoc && !hasSource)
- reader= new StringReader(InfoViewMessages.JavadocView_noAttachedJavadoc);
- else if (!hasAttachedSource)
- reader= new StringReader(InfoViewMessages.JavadocView_noAttachedSource);
- else if (!hasSource)
- reader= new StringReader(InfoViewMessages.JavadocView_noInformation);
- }
-
- } catch (JavaScriptModelException ex) {
- reader= new StringReader(InfoViewMessages.JavadocView_error_gettingJavadoc);
- JavaScriptPlugin.log(ex.getStatus());
- }
- if (reader != null) {
- HTMLPrinter.addParagraph(buffer, reader);
- }
- }
- }
-
- boolean flushContent= true;
- if (buffer.length() > 0 || flushContent) {
- HTMLPrinter.insertPageProlog(buffer, 0, fBackgroundColorRGB, fgStyleSheet);
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-
- return null;
- }
-
- /**
- * Gets the label for the given member.
- *
- * @param member the Java member
- * @return a string containing the member's label
- */
- private String getInfoText(IMember member) {
- return JavaScriptElementLabels.getElementLabel(member, LABEL_FLAGS);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#isIgnoringNewInput(org.eclipse.wst.jsdt.core.IJavaScriptElement, org.eclipse.jface.viewers.ISelection)
- *
- */
- protected boolean isIgnoringNewInput(IJavaScriptElement je, IWorkbenchPart part, ISelection selection) {
- if (super.isIgnoringNewInput(je, part, selection)
- && part instanceof ITextEditor
- && selection instanceof ITextSelection) {
-
- ITextEditor editor= (ITextEditor)part;
- IDocumentProvider docProvider= editor.getDocumentProvider();
- if (docProvider == null)
- return false;
-
- IDocument document= docProvider.getDocument(editor.getEditorInput());
- if (!(document instanceof IDocumentExtension3))
- return false;
-
- try {
- int offset= ((ITextSelection)selection).getOffset();
- String partition= ((IDocumentExtension3)document).getContentType(IJavaScriptPartitions.JAVA_PARTITIONING, offset, false);
- return partition != IJavaScriptPartitions.JAVA_DOC;
- } catch (BadPartitioningException ex) {
- return false;
- } catch (BadLocationException ex) {
- return false;
- }
-
- }
- return false;
- }
-
- /*
- * @see AbstractInfoView#findSelectedJavaElement(IWorkbenchPart)
- */
- protected IJavaScriptElement findSelectedJavaElement(IWorkbenchPart part, ISelection selection) {
- IJavaScriptElement element;
- try {
- element= super.findSelectedJavaElement(part, selection);
-
- if (element == null && part instanceof JavaEditor && selection instanceof ITextSelection) {
-
- JavaEditor editor= (JavaEditor)part;
- ITextSelection textSelection= (ITextSelection)selection;
-
- IDocumentProvider documentProvider= editor.getDocumentProvider();
- if (documentProvider == null)
- return null;
-
- IDocument document= documentProvider.getDocument(editor.getEditorInput());
- if (document == null)
- return null;
-
- ITypedRegion typedRegion= TextUtilities.getPartition(document, IJavaScriptPartitions.JAVA_PARTITIONING, textSelection.getOffset(), false);
- if (IJavaScriptPartitions.JAVA_DOC.equals(typedRegion.getType()))
- return TextSelectionConverter.getElementAtOffset((JavaEditor)part, textSelection);
- else
- return null;
- } else
- return element;
- } catch (JavaScriptModelException e) {
- return null;
- } catch (BadLocationException e) {
- return null;
- }
- }
-
- /*
- * @see AbstractInfoView#getControl()
- */
- protected Control getControl() {
- if (fIsUsingBrowserWidget)
- return fBrowser;
- else
- return fText;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getHelpContextId()
- *
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.JAVADOC_VIEW;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/SourceView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/SourceView.java
deleted file mode 100644
index 5321dc16..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/SourceView.java
+++ /dev/null
@@ -1,518 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import java.io.IOException;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextViewer;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
-import org.eclipse.wst.jsdt.core.ICodeAssist;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCodeReader;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-/**
- * View which shows source for a given Java element.
- *
- *
- */
-public class SourceView extends AbstractInfoView implements IMenuListener {
-
- /** Symbolic Java editor font name. */
- private static final String SYMBOLIC_FONT_NAME= "org.eclipse.wst.jsdt.ui.editors.textfont"; //$NON-NLS-1$
-
- /**
- * Internal property change listener for handling changes in the editor's preferences.
- *
- *
- */
- class PropertyChangeListener implements IPropertyChangeListener {
- /*
- * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (fViewer == null)
- return;
-
- if (fViewerConfiguration.affectsTextPresentation(event)) {
- fViewerConfiguration.handlePropertyChangeEvent(event);
- fViewer.invalidateTextPresentation();
- }
- }
- }
-
- /**
- * Internal property change listener for handling workbench font changes.
- */
- class FontPropertyChangeListener implements IPropertyChangeListener {
- /*
- * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (fViewer == null)
- return;
-
- String property= event.getProperty();
-
- if (SYMBOLIC_FONT_NAME.equals(property))
- setViewerFont();
- }
- }
-
- /**
- * The Javadoc view's select all action.
- */
- private static class SelectAllAction extends Action {
-
- private TextViewer fTextViewer;
-
- /**
- * Creates the action.
- *
- * @param textViewer the text viewer
- */
- public SelectAllAction(TextViewer textViewer) {
- super("selectAll"); //$NON-NLS-1$
-
- Assert.isNotNull(textViewer);
- fTextViewer= textViewer;
-
- setText(InfoViewMessages.SelectAllAction_label);
- setToolTipText(InfoViewMessages.SelectAllAction_tooltip);
- setDescription(InfoViewMessages.SelectAllAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION);
- }
-
- /**
- * Selects all in the viewer.
- */
- public void run() {
- fTextViewer.doOperation(ITextOperationTarget.SELECT_ALL);
- }
- }
-
- /** This view's source viewer */
- private SourceViewer fViewer;
- /** The viewers configuration */
- private JavaScriptSourceViewerConfiguration fViewerConfiguration;
- /** The viewer's font properties change listener. */
- private IPropertyChangeListener fFontPropertyChangeListener= new FontPropertyChangeListener();
- /**
- * The editor's property change listener.
- *
- */
- private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
- /** The open action */
- private OpenAction fOpen;
- /** The number of removed leading comment lines. */
- private int fCommentLineCount;
- /** The select all action. */
- private SelectAllAction fSelectAllAction;
- /** Element opened by the open action. */
- private IJavaScriptElement fLastOpenedElement;
-
-
- /*
- * @see AbstractInfoView#internalCreatePartControl(Composite)
- */
- protected void internalCreatePartControl(Composite parent) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL, store);
- fViewerConfiguration= new SimpleJavaSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
- fViewer.configure(fViewerConfiguration);
- fViewer.setEditable(false);
-
- setViewerFont();
- JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
-
- store.addPropertyChangeListener(fPropertyChangeListener);
-
- getViewSite().setSelectionProvider(fViewer);
- }
-
- /*
- * @see AbstractInfoView#internalCreatePartControl(Composite)
- */
- protected void createActions() {
- super.createActions();
- fSelectAllAction= new SelectAllAction(fViewer);
-
- // Setup OpenAction
- fOpen= new OpenAction(getViewSite()) {
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#getSelection()
- */
- public ISelection getSelection() {
- return convertToJavaElementSelection(fViewer.getSelection());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.OpenAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- if (selection.isEmpty()) {
- getShell().getDisplay().beep();
- return;
- }
- super.run(selection);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.OpenAction#getElementToOpen(Object)
- */
- public Object getElementToOpen(Object object) throws JavaScriptModelException {
- if (object instanceof IJavaScriptElement)
- fLastOpenedElement= (IJavaScriptElement)object;
- else
- fLastOpenedElement= null;
- return super.getElementToOpen(object);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.OpenAction#run(Object[])
- */
- public void run(Object[] elements) {
- stopListeningForSelectionChanges();
- super.run(elements);
- startListeningForSelectionChanges();
- }
- };
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getSelectAllAction()
- *
- */
- protected IAction getSelectAllAction() {
- return fSelectAllAction;
- }
-
- /*
- * @see AbstractInfoView#fillActionBars(IActionBars)
- */
- protected void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN, fOpen);
- fOpen.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EDITOR);
- }
-
- /*
- * @see AbstractInfoView#getControl()
- */
- protected Control getControl() {
- return fViewer.getControl();
- }
-
- /*
- * @see AbstractInfoView#menuAboutToShow(IMenuManager)
- */
- public void menuAboutToShow(IMenuManager menu) {
- super.menuAboutToShow(menu);
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
- }
-
- /*
- * @see AbstractInfoView#setForeground(Color)
- */
- protected void setForeground(Color color) {
- fViewer.getTextWidget().setForeground(color);
- }
-
- /*
- * @see AbstractInfoView#setBackground(Color)
- */
- protected void setBackground(Color color) {
- fViewer.getTextWidget().setBackground(color);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getBackgroundColorKey()
- *
- */
- protected String getBackgroundColorKey() {
- return "org.eclipse.wst.jsdt.ui.DeclarationView.backgroundColor"; //$NON-NLS-1$
- }
-
- /**
- * Converts the given selection to a structured selection
- * containing Java elements.
- *
- * @param selection the selection
- * @return a structured selection with Java elements
- */
- private IStructuredSelection convertToJavaElementSelection(ISelection selection) {
-
- if (!(selection instanceof ITextSelection && fCurrentViewInput instanceof ISourceReference))
- return StructuredSelection.EMPTY;
-
- ITextSelection textSelection= (ITextSelection)selection;
-
- Object codeAssist= fCurrentViewInput.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (codeAssist == null)
- codeAssist= fCurrentViewInput.getAncestor(IJavaScriptElement.CLASS_FILE);
-
- if (codeAssist instanceof ICodeAssist) {
- IJavaScriptElement[] elements= null;
- try {
- ISourceRange range= ((ISourceReference)fCurrentViewInput).getSourceRange();
- elements= ((ICodeAssist)codeAssist).codeSelect(range.getOffset() + getOffsetInUnclippedDocument(textSelection), textSelection.getLength());
- } catch (JavaScriptModelException e) {
- return StructuredSelection.EMPTY;
- }
- if (elements != null && elements.length > 0) {
- return new StructuredSelection(elements[0]);
- } else
- return StructuredSelection.EMPTY;
- }
-
- return StructuredSelection.EMPTY;
- }
-
- /**
- * Computes and returns the offset in the unclipped document
- * based on the given text selection from the clipped
- * document.
- *
- * @param textSelection
- * @return the offest in the unclipped document or <code>-1</code> if the offset cannot be computed
- */
- private int getOffsetInUnclippedDocument(ITextSelection textSelection) {
- IDocument unclippedDocument= null;
- try {
- unclippedDocument= new Document(((ISourceReference)fCurrentViewInput).getSource());
- } catch (JavaScriptModelException e) {
- return -1;
- }
- IDocument clippedDoc= (IDocument)fViewer.getInput();
- try {
- IRegion unclippedLineInfo= unclippedDocument.getLineInformation(fCommentLineCount + textSelection.getStartLine());
- IRegion clippedLineInfo= clippedDoc.getLineInformation(textSelection.getStartLine());
- int removedIndentation= unclippedLineInfo.getLength() - clippedLineInfo.getLength();
- int relativeLineOffset= textSelection.getOffset() - clippedLineInfo.getOffset();
- return unclippedLineInfo.getOffset() + removedIndentation + relativeLineOffset ;
- } catch (BadLocationException ex) {
- return -1;
- }
- }
-
- /*
- * @see AbstractInfoView#internalDispose()
- */
- protected void internalDispose() {
- fViewer= null;
- fViewerConfiguration= null;
- JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
- JavaScriptPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- }
-
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
- */
- public void setFocus() {
- fViewer.getTextWidget().setFocus();
- }
-
- /*
- * @see AbstractInfoView#computeInput(Object)
- */
- protected Object computeInput(Object input) {
-
- if (fViewer == null || !(input instanceof ISourceReference))
- return null;
-
- ISourceReference sourceRef= (ISourceReference)input;
-
- if (fLastOpenedElement != null && input instanceof IJavaScriptElement && ((IJavaScriptElement)input).getHandleIdentifier().equals(fLastOpenedElement.getHandleIdentifier())) {
- fLastOpenedElement= null;
- return null;
- } else {
- fLastOpenedElement= null;
- }
-
- String source;
- try {
- source= sourceRef.getSource();
- } catch (JavaScriptModelException ex) {
- return ""; //$NON-NLS-1$
- }
-
- if (source == null)
- return ""; //$NON-NLS-1$
-
- source= removeLeadingComments(source);
- String delim= StubUtility.getLineDelimiterUsed((IJavaScriptElement) input);
-
- String[] sourceLines= Strings.convertIntoLines(source);
- if (sourceLines == null || sourceLines.length == 0)
- return ""; //$NON-NLS-1$
-
- String firstLine= sourceLines[0];
- boolean firstCharNotWhitespace= firstLine != null && firstLine.length() > 0 && !Character.isWhitespace(firstLine.charAt(0));
- if (firstCharNotWhitespace)
- sourceLines[0]= ""; //$NON-NLS-1$
- IJavaScriptProject project;
- if (input instanceof IJavaScriptElement)
- project= ((IJavaScriptElement) input).getJavaScriptProject();
- else
- project= null;
- Strings.trimIndentation(sourceLines, project);
-
- if (firstCharNotWhitespace)
- sourceLines[0]= firstLine;
-
- return Strings.concatenate(sourceLines, delim);
- }
-
- /*
- * @see AbstractInfoView#setInput(Object)
- */
- protected void setInput(Object input) {
- if (input instanceof IDocument)
- fViewer.setInput(input);
- else if (input == null)
- fViewer.setInput(new Document("")); //$NON-NLS-1$
- else {
- IDocument document= new Document(input.toString());
- JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- fViewer.setInput(document);
- }
- }
-
- /**
- * Removes the leading comments from the given source.
- *
- * @param source the string with the source
- * @return the source without leading comments
- */
- private String removeLeadingComments(String source) {
- JavaCodeReader reader= new JavaCodeReader();
- IDocument document= new Document(source);
- int i;
- try {
- reader.configureForwardReader(document, 0, document.getLength(), true, false);
- int c= reader.read();
- while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) {
- c= reader.read();
- }
- i= reader.getOffset();
- reader.close();
- } catch (IOException ex) {
- i= 0;
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
-
- try {
- fCommentLineCount= document.getLineOfOffset(i);
- } catch (BadLocationException e) {
- fCommentLineCount= 0;
- }
-
- if (i < 0)
- return source;
-
- return source.substring(i);
- }
-
- /**
- * Sets the font for this viewer sustaining selection and scroll position.
- */
- private void setViewerFont() {
- Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME);
-
- if (fViewer.getDocument() != null) {
-
- Point selection= fViewer.getSelectedRange();
- int topIndex= fViewer.getTopIndex();
-
- StyledText styledText= fViewer.getTextWidget();
- Control parent= fViewer.getControl();
-
- parent.setRedraw(false);
-
- styledText.setFont(font);
-
- fViewer.setSelectedRange(selection.x , selection.y);
- fViewer.setTopIndex(topIndex);
-
- if (parent instanceof Composite) {
- Composite composite= (Composite) parent;
- composite.layout(true);
- }
-
- parent.setRedraw(true);
-
-
- } else {
- StyledText styledText= fViewer.getTextWidget();
- styledText.setFont(font);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.infoviews.AbstractInfoView#getHelpContextId()
- *
- */
- protected String getHelpContextId() {
- return IJavaHelpContextIds.SOURCE_VIEW;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/TextSelectionConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/TextSelectionConverter.java
deleted file mode 100644
index 89edb07e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/TextSelectionConverter.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.infoviews;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.ICodeAssist;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-
-/**
- * Helper class to convert text selections to Java elements.
- *
- *
- */
-class TextSelectionConverter {
-
- /** Empty result. */
- private static final IJavaScriptElement[] EMPTY_RESULT= new IJavaScriptElement[0];
-
- /** Prevent instance creation. */
- private TextSelectionConverter() {
- }
-
- /**
- * Finds and returns the Java elements for the given editor selection.
- *
- * @param editor the Java editor
- * @param selection the text selection
- * @return the Java elements for the given editor selection
- * @throws JavaScriptModelException
- */
- public static IJavaScriptElement[] codeResolve(JavaEditor editor, ITextSelection selection) throws JavaScriptModelException {
- return codeResolve(getInput(editor), selection);
- }
-
- /**
- * Finds and returns the Java element that contains the
- * text selection in the given editor.
- *
- * @param editor the Java editor
- * @param selection the text selection
- * @return the Java elements for the given editor selection
- * @throws JavaScriptModelException
- */
- public static IJavaScriptElement getElementAtOffset(JavaEditor editor, ITextSelection selection) throws JavaScriptModelException {
- return getElementAtOffset(getInput(editor), selection);
- }
-
- //-------------------- Helper methods --------------------
-
- private static IJavaScriptElement getInput(JavaEditor editor) {
- if (editor == null)
- return null;
- IEditorInput input= editor.getEditorInput();
- if (input instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)input).getClassFile();
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- return manager.getWorkingCopy(input);
- }
-
- private static IJavaScriptElement[] codeResolve(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
- if (input instanceof ICodeAssist) {
- if (input instanceof IJavaScriptUnit) {
- IJavaScriptUnit cunit= (IJavaScriptUnit)input;
- if (cunit.isWorkingCopy())
- JavaModelUtil.reconcile(cunit);
- }
- IJavaScriptElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
- if (elements != null && elements.length > 0)
- return elements;
- }
- return EMPTY_RESULT;
- }
-
- private static IJavaScriptElement getElementAtOffset(IJavaScriptElement input, ITextSelection selection) throws JavaScriptModelException {
- if (input instanceof IJavaScriptUnit) {
- IJavaScriptUnit cunit= (IJavaScriptUnit)input;
- if (cunit.isWorkingCopy())
- JavaModelUtil.reconcile(cunit);
- IJavaScriptElement ref= cunit.getElementAt(selection.getOffset());
- if (ref == null)
- return input;
- else
- return ref;
- } else if (input instanceof IClassFile) {
- IJavaScriptElement ref= ((IClassFile)input).getElementAt(selection.getOffset());
- if (ref == null)
- return input;
- else
- return ref;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CheckboxTreeAndListGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CheckboxTreeAndListGroup.java
deleted file mode 100644
index 17e43b56..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CheckboxTreeAndListGroup.java
+++ /dev/null
@@ -1,804 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ITreeViewerListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeExpansionEvent;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Tree;
-
-/**
- * Combines a CheckboxTreeViewer and CheckboxListViewer.
- * All viewer selection-driven interactions are handled within this viewer
- */
-public class CheckboxTreeAndListGroup implements ICheckStateListener, ISelectionChangedListener, ITreeViewerListener {
-
- private Object fRoot;
- private Object fCurrentTreeSelection;
- private List fExpandedTreeNodes= new ArrayList();
- private Map fCheckedStateStore= new HashMap(9);
- private List fWhiteCheckedTreeItems= new ArrayList();
- private List fListeners= new ArrayList();
-
- private ITreeContentProvider fTreeContentProvider;
- private IStructuredContentProvider fListContentProvider;
- private ILabelProvider fTreeLabelProvider;
- private ILabelProvider fListLabelProvider;
-
- // widgets
- private CheckboxTreeViewer fTreeViewer;
- private CheckboxTableViewer fListViewer;
-
- /**
- * Creates an instance of this class. Use this constructor if you wish to specify
- * the width and/or height of the combined widget (to only hardcode one of the
- * sizing dimensions, specify the other dimension's value as -1)
- */
- public CheckboxTreeAndListGroup(
- Composite parent,
- Object rootObject,
- ITreeContentProvider treeContentProvider,
- ILabelProvider treeLabelProvider,
- IStructuredContentProvider listContentProvider,
- ILabelProvider listLabelProvider,
- int style,
- int width,
- int height) {
- fRoot= rootObject;
- fTreeContentProvider= treeContentProvider;
- fListContentProvider= listContentProvider;
- fTreeLabelProvider= treeLabelProvider;
- fListLabelProvider= listLabelProvider;
- createContents(parent, width, height, style);
- }
- /**
- * This method must be called just before this window becomes visible.
- */
- public void aboutToOpen() {
- determineWhiteCheckedDescendents(fRoot);
- checkNewTreeElements(getTreeChildren(fRoot));
- fCurrentTreeSelection= null;
-
- //select the first element in the list
- Object[] elements= getTreeChildren(fRoot);
- Object primary= elements.length > 0 ? elements[0] : null;
- if (primary != null) {
- fTreeViewer.setSelection(new StructuredSelection(primary));
- }
- fTreeViewer.getControl().setFocus();
- }
- /**
- * Adds the passed listener to self's collection of clients
- * that listen for changes to element checked states
- *
- * @param listener ICheckStateListener
- */
- public void addCheckStateListener(ICheckStateListener listener) {
- fListeners.add(listener);
- }
- /**
- * Adds the receiver and all of it's ancestors to the checkedStateStore if they
- * are not already there.
- */
- private void addToHierarchyToCheckedStore(Object treeElement) {
-
- // if this tree element is already gray then its ancestors all are as well
- if (!fCheckedStateStore.containsKey(treeElement))
- fCheckedStateStore.put(treeElement, new ArrayList());
-
- Object parent= fTreeContentProvider.getParent(treeElement);
- if (parent != null)
- addToHierarchyToCheckedStore(parent);
- }
- /**
- * Returns a boolean indicating whether all children of the passed tree element
- * are currently white-checked
- *
- * @return boolean
- * @param treeElement java.lang.Object
- */
- protected boolean areAllChildrenWhiteChecked(Object treeElement) {
- Object[] children= getTreeChildren(treeElement);
- for (int i= 0; i < children.length; ++i) {
- if (!fWhiteCheckedTreeItems.contains(children[i]))
- return false;
- }
-
- return true;
- }
- /**
- * Returns a boolean indicating whether all list elements associated with
- * the passed tree element are currently checked
- *
- * @return boolean
- * @param treeElement java.lang.Object
- */
- protected boolean areAllElementsChecked(Object treeElement) {
- List checkedElements= (List)fCheckedStateStore.get(treeElement);
- if (checkedElements == null) // ie.- tree item not even gray-checked
- return false;
-
- return getListItemsSize(treeElement) == checkedElements.size();
- }
- /**
- * Iterates through the passed elements which are being realized for the first
- * time and check each one in the tree viewer as appropriate
- */
- protected void checkNewTreeElements(Object[] elements) {
- for (int i= 0; i < elements.length; ++i) {
- Object currentElement= elements[i];
- boolean checked= fCheckedStateStore.containsKey(currentElement);
- fTreeViewer.setChecked(currentElement, checked);
- fTreeViewer.setGrayed(
- currentElement,
- checked && !fWhiteCheckedTreeItems.contains(currentElement));
- }
- }
- /**
- * An item was checked in one of self's two views. Determine which
- * view this occurred in and delegate appropriately
- *
- * @param event CheckStateChangedEvent
- */
- public void checkStateChanged(final CheckStateChangedEvent event) {
-
- //Potentially long operation - show a busy cursor
- BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- if (event.getCheckable().equals(fTreeViewer))
- treeItemChecked(event.getElement(), event.getChecked());
- else
- listItemChecked(event.getElement(), event.getChecked(), true);
-
- notifyCheckStateChangeListeners(event);
- }
- });
- }
- /**
- * Lay out and initialize self's visual components.
- *
- * @param parent org.eclipse.swt.widgets.Composite
- * @param width int
- * @param height int
- */
- protected void createContents(
- Composite parent,
- int width,
- int height,
- int style) {
- // group pane
- Composite composite= new Composite(parent, style);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.makeColumnsEqualWidth= true;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createTreeViewer(composite, width / 2, height);
- createListViewer(composite, width / 2, height);
-
- initialize();
- }
- /**
- * Creates this group's list viewer.
- */
- protected void createListViewer(Composite parent, int width, int height) {
- fListViewer= CheckboxTableViewer.newCheckList(parent, SWT.BORDER);
- fListViewer.setUseHashlookup(true);
- GridData data= new GridData(GridData.FILL_BOTH);
- data.widthHint= width;
- data.heightHint= height;
- fListViewer.getTable().setLayoutData(data);
- fListViewer.setContentProvider(fListContentProvider);
- fListViewer.setLabelProvider(fListLabelProvider);
- fListViewer.addCheckStateListener(this);
- }
- /**
- * Creates this group's tree viewer.
- */
- protected void createTreeViewer(Composite parent, int width, int height) {
- Tree tree= new Tree(parent, SWT.CHECK | SWT.BORDER);
- GridData data= new GridData(GridData.FILL_BOTH);
- data.widthHint= width;
- data.heightHint= height;
- tree.setLayoutData(data);
-
- fTreeViewer= new CheckboxTreeViewer(tree);
- fTreeViewer.setUseHashlookup(true);
- fTreeViewer.setContentProvider(fTreeContentProvider);
- fTreeViewer.setLabelProvider(fTreeLabelProvider);
- fTreeViewer.addTreeListener(this);
- fTreeViewer.addCheckStateListener(this);
- fTreeViewer.addSelectionChangedListener(this);
- }
- /**
- * Returns a boolean indicating whether the passed tree element should be
- * at LEAST gray-checked. Note that this method does not consider whether
- * it should be white-checked, so a specified tree item which should be
- * white-checked will result in a <code>true</code> answer from this method.
- * To determine whether a tree item should be white-checked use method
- * #determineShouldBeWhiteChecked(Object).
- *
- * @param treeElement java.lang.Object
- * @return boolean
- * @see #determineShouldBeWhiteChecked(java.lang.Object)
- */
- protected boolean determineShouldBeAtLeastGrayChecked(Object treeElement) {
- // if any list items associated with treeElement are checked then it
- // retains its gray-checked status regardless of its children
- List checked= (List) fCheckedStateStore.get(treeElement);
- if (checked != null && (!checked.isEmpty()))
- return true;
-
- // if any children of treeElement are still gray-checked then treeElement
- // must remain gray-checked as well
- Object[] children= getTreeChildren(treeElement);
- for (int i= 0; i < children.length; ++i) {
- if (fCheckedStateStore.containsKey(children[i]))
- return true;
- }
-
- return false;
- }
- /**
- * Returns a boolean indicating whether the passed tree item should be
- * white-checked.
- *
- * @return boolean
- * @param treeElement java.lang.Object
- */
- protected boolean determineShouldBeWhiteChecked(Object treeElement) {
- return areAllChildrenWhiteChecked(treeElement)
- && areAllElementsChecked(treeElement);
- }
- /**
- * Recursively adds appropriate tree elements to the collection of
- * known white-checked tree elements.
- *
- * @param treeElement java.lang.Object
- */
- protected void determineWhiteCheckedDescendents(Object treeElement) {
- // always go through all children first since their white-checked
- // statuses will be needed to determine the white-checked status for
- // this tree element
- Object[] children= getTreeChildren(treeElement);
- for (int i= 0; i < children.length; ++i)
- determineWhiteCheckedDescendents(children[i]);
-
- // now determine the white-checked status for this tree element
- if (determineShouldBeWhiteChecked(treeElement))
- setWhiteChecked(treeElement, true);
- }
- /**
- * Causes the tree viewer to expand all its items
- */
- public void expandAll() {
- fTreeViewer.expandAll();
- }
- /**
- * Answers a flat collection of all of the checked elements in the
- * list portion of self
- *
- * @return java.util.Vector
- */
- public Iterator getAllCheckedListItems() {
- Set result= new HashSet();
- Iterator listCollectionsEnum= fCheckedStateStore.values().iterator();
- while (listCollectionsEnum.hasNext())
- result.addAll((List)listCollectionsEnum.next());
- return result.iterator();
- }
- /**
- * Answer a collection of all of the checked elements in the tree portion
- * of self
- *
- * @return java.util.Vector
- */
- public Set getAllCheckedTreeItems() {
- return new HashSet(fCheckedStateStore.keySet());
- }
- /**
- * Answers the number of elements that have been checked by the
- * user.
- *
- * @return int
- */
- public int getCheckedElementCount() {
- return fCheckedStateStore.size();
- }
- /**
- * Returns a count of the number of list items associated with a
- * given tree item.
- *
- * @return int
- * @param treeElement java.lang.Object
- */
- protected int getListItemsSize(Object treeElement) {
- Object[] elements= getListElements(treeElement);
- return elements.length;
- }
- /**
- * Gets the table that displays the folder content
- *
- * @return the table used to show the list
- */
- public Table getTable() {
- return fListViewer.getTable();
- }
- /**
- * Gets the tree that displays the list for a folder
- *
- * @return the tree used to show the folders
- */
- public Tree getTree() {
- return fTreeViewer.getTree();
- }
- /**
- * Adds the given filter to the tree viewer and
- * triggers refiltering and resorting of the elements.
- *
- * @param filter a viewer filter
- */
- public void addTreeFilter(ViewerFilter filter) {
- fTreeViewer.addFilter(filter);
- }
- /**
- * Adds the given filter to the list viewer and
- * triggers refiltering and resorting of the elements.
- *
- * @param filter a viewer filter
- */
- public void addListFilter(ViewerFilter filter) {
- fListViewer.addFilter(filter);
- }
- /**
- * Logically gray-check all ancestors of treeItem by ensuring that they
- * appear in the checked table
- */
- protected void grayCheckHierarchy(Object treeElement) {
-
- // if this tree element is already gray then its ancestors all are as well
- if (fCheckedStateStore.containsKey(treeElement))
- return; // no need to proceed upwards from here
-
- fCheckedStateStore.put(treeElement, new ArrayList());
- if (determineShouldBeWhiteChecked(treeElement)) {
- setWhiteChecked(treeElement, true);
- }
- Object parent= fTreeContentProvider.getParent(treeElement);
- if (parent != null)
- grayCheckHierarchy(parent);
- }
- /**
- * Sets the initial checked state of the passed list element to true.
- */
- public void initialCheckListItem(Object element) {
- Object parent= fTreeContentProvider.getParent(element);
- fCurrentTreeSelection= parent;
- //As this is not done from the UI then set the box for updating from the selection to false
- listItemChecked(element, true, false);
- updateHierarchy(parent);
- }
- /**
- * Sets the initial checked state of the passed element to true,
- * as well as to all of its children and associated list elements
- */
- public void initialCheckTreeItem(Object element) {
- treeItemChecked(element, true);
- }
- /**
- * Initializes this group's viewers after they have been laid out.
- */
- protected void initialize() {
- fTreeViewer.setInput(fRoot);
- }
- /**
- * Callback that's invoked when the checked status of an item in the list
- * is changed by the user. Do not try and update the hierarchy if we are building the
- * initial list.
- */
- protected void listItemChecked(
- Object listElement,
- boolean state,
- boolean updatingFromSelection) {
- List checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
-
- if (state) {
- if (checkedListItems == null) {
- // since the associated tree item has gone from 0 -> 1 checked
- // list items, tree checking may need to be updated
- grayCheckHierarchy(fCurrentTreeSelection);
- checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
- }
- checkedListItems.add(listElement);
- } else {
- checkedListItems.remove(listElement);
- if (checkedListItems.isEmpty()) {
- // since the associated tree item has gone from 1 -> 0 checked
- // list items, tree checking may need to be updated
- ungrayCheckHierarchy(fCurrentTreeSelection);
- }
- }
-
- if (updatingFromSelection)
- updateHierarchy(fCurrentTreeSelection);
- }
- /**
- * Notifies all checked state listeners that the passed element has had
- * its checked state changed to the passed state
- */
- protected void notifyCheckStateChangeListeners(CheckStateChangedEvent event) {
- Iterator listenersEnum= fListeners.iterator();
- while (listenersEnum.hasNext())
- ((ICheckStateListener) listenersEnum.next()).checkStateChanged(event);
- }
- /**
- *Sets the contents of the list viewer based upon the specified selected
- *tree element. This also includes checking the appropriate list items.
- *
- *@param treeElement java.lang.Object
- */
- protected void populateListViewer(final Object treeElement) {
- if (treeElement == fCurrentTreeSelection)
- return;
- fCurrentTreeSelection= treeElement;
- fListViewer.setInput(treeElement);
- List listItemsToCheck= (List) fCheckedStateStore.get(treeElement);
-
- if (listItemsToCheck != null) {
- Iterator listItemsEnum= listItemsToCheck.iterator();
- while (listItemsEnum.hasNext())
- fListViewer.setChecked(listItemsEnum.next(), true);
- }
- }
- /**
- * Removes the passed listener from self's collection of clients
- * that listen for changes to element checked states
- *
- * @param listener ICheckStateListener
- */
- public void removeCheckStateListener(ICheckStateListener listener) {
- fListeners.remove(listener);
- }
- /**
- * Handles the selection of an item in the tree viewer
- *
- * @param event ISelection
- */
- public void selectionChanged(final SelectionChangedEvent event) {
- BusyIndicator.showWhile(getTable().getShell().getDisplay(), new Runnable() {
- public void run() {
- IStructuredSelection selection= (IStructuredSelection) event.getSelection();
- Object selectedElement= selection.getFirstElement();
- if (selectedElement == null) {
- fCurrentTreeSelection= null;
- fListViewer.setInput(fCurrentTreeSelection);
- return;
- }
- populateListViewer(selectedElement);
- }
- });
- }
-
- /**
- * Selects or deselect all of the elements in the tree depending on the value of the selection
- * boolean. Be sure to update the displayed files as well.
- */
- public void setAllSelections(final boolean selection) {
-
- //Potentially long operation - show a busy cursor
- BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- setTreeChecked(fRoot, selection);
- fListViewer.setAllChecked(selection);
- }
- });
- }
-
- /**
- * Sets the list viewer's providers to those passed
- *
- * @param contentProvider ITreeContentProvider
- * @param labelProvider ILabelProvider
- */
- public void setListProviders(
- IStructuredContentProvider contentProvider,
- ILabelProvider labelProvider) {
- fListViewer.setContentProvider(contentProvider);
- fListViewer.setLabelProvider(labelProvider);
- }
- /**
- * Sets the sorter that is to be applied to self's list viewer
- */
- public void setListComparator(ViewerComparator comparator) {
- fListViewer.setComparator(comparator);
- }
- /**
- * Sets the root of the widget to be new Root. Regenerate all of the tables and lists from this
- * value.
- *
- * @param newRoot
- */
- public void setRoot(Object newRoot) {
- this.fRoot= newRoot;
- initialize();
- }
- /**
- * Sets the checked state of the passed tree element appropriately, and
- * do so recursively to all of its child tree elements as well
- */
- protected void setTreeChecked(Object treeElement, boolean state) {
-
- if (treeElement.equals(fCurrentTreeSelection)) {
- fListViewer.setAllChecked(state);
- }
-
- if (state) {
- Object[] listItems= getListElements(treeElement);
- List listItemsChecked= new ArrayList();
- for (int i= 0; i < listItems.length; ++i)
- listItemsChecked.add(listItems[i]);
-
- fCheckedStateStore.put(treeElement, listItemsChecked);
- } else
- fCheckedStateStore.remove(treeElement);
-
- setWhiteChecked(treeElement, state);
- fTreeViewer.setChecked(treeElement, state);
- fTreeViewer.setGrayed(treeElement, false);
-
- // now logically check/uncheck all children as well
- Object[] children= getTreeChildren(treeElement);
- for (int i= 0; i < children.length; ++i) {
- setTreeChecked(children[i], state);
- }
- }
- /**
- * Sets the tree viewer's providers to those passed
- *
- * @param contentProvider ITreeContentProvider
- * @param labelProvider ILabelProvider
- */
- public void setTreeProviders(
- ITreeContentProvider contentProvider,
- ILabelProvider labelProvider) {
- fTreeViewer.setContentProvider(contentProvider);
- fTreeViewer.setLabelProvider(labelProvider);
- }
- /**
- * Sets the sorter that is to be applied to self's tree viewer
- */
- public void setTreeComparator(ViewerComparator sorter) {
- fTreeViewer.setComparator(sorter);
- }
- /**
- * Adjusts the collection of references to white-checked tree elements appropriately.
- *
- * @param treeElement java.lang.Object
- * @param isWhiteChecked boolean
- */
- protected void setWhiteChecked(Object treeElement, boolean isWhiteChecked) {
- if (isWhiteChecked) {
- if (!fWhiteCheckedTreeItems.contains(treeElement))
- fWhiteCheckedTreeItems.add(treeElement);
- } else
- fWhiteCheckedTreeItems.remove(treeElement);
- }
- /**
- * Handle the collapsing of an element in a tree viewer
- */
- public void treeCollapsed(TreeExpansionEvent event) {
- // We don't need to do anything with this
- }
-
- /**
- * Handles the expansionsion of an element in a tree viewer
- */
- public void treeExpanded(TreeExpansionEvent event) {
-
- Object item= event.getElement();
-
- // First see if the children need to be given their checked state at all. If they've
- // already been realized then this won't be necessary
- if (!fExpandedTreeNodes.contains(item)) {
- fExpandedTreeNodes.add(item);
- checkNewTreeElements(getTreeChildren(item));
- }
- }
-
- /**
- * Callback that's invoked when the checked status of an item in the tree
- * is changed by the user.
- */
- protected void treeItemChecked(Object treeElement, boolean state) {
-
- // recursively adjust all child tree elements appropriately
- setTreeChecked(treeElement, state);
-
- Object parent= fTreeContentProvider.getParent(treeElement);
- if (parent == null)
- return;
-
- // now update upwards in the tree hierarchy
- if (state)
- grayCheckHierarchy(parent);
- else
- ungrayCheckHierarchy(parent);
-
- updateHierarchy(treeElement);
- }
- /**
- * Logically un-gray-check all ancestors of treeItem iff appropriate.
- */
- protected void ungrayCheckHierarchy(Object treeElement) {
- if (!determineShouldBeAtLeastGrayChecked(treeElement))
- fCheckedStateStore.remove(treeElement);
-
- Object parent= fTreeContentProvider.getParent(treeElement);
- if (parent != null)
- ungrayCheckHierarchy(parent);
- }
- /**
- * Sets the checked state of self and all ancestors appropriately
- */
- protected void updateHierarchy(Object treeElement) {
-
- boolean whiteChecked= determineShouldBeWhiteChecked(treeElement);
- boolean shouldBeAtLeastGray= determineShouldBeAtLeastGrayChecked(treeElement);
-
- fTreeViewer.setChecked(treeElement, whiteChecked || shouldBeAtLeastGray);
- setWhiteChecked(treeElement, whiteChecked);
- if (whiteChecked)
- fTreeViewer.setGrayed(treeElement, false);
- else
- fTreeViewer.setGrayed(treeElement, shouldBeAtLeastGray);
-
- // proceed up the tree element hierarchy
- Object parent= fTreeContentProvider.getParent(treeElement);
- if (parent != null) {
- updateHierarchy(parent);
- }
- }
- /**
- * Update the selections of the tree elements in items to reflect the new
- * selections provided.
- *
- * @param items with keys of Object (the tree element) and values of List (the selected
- * list elements).
- */
- public void updateSelections(final Map items) {
-
- //Potentially long operation - show a busy cursor
- BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- handleUpdateSelection(items);
- }
- });
- }
- /**
- * Returns the result of running the given elements through the filters.
- *
- * @param elements the elements to filter
- * @return only the elements which all filters accept
- */
- protected Object[] filter(ViewerFilter[] filters, Object[] elements) {
- if (filters != null) {
- ArrayList filtered = new ArrayList(elements.length);
- for (int i = 0; i < elements.length; i++) {
- boolean add = true;
- for (int j = 0; j < filters.length; j++) {
- add = filters[j].select(null, null, elements[i]);
- if (!add)
- break;
- }
- if (add)
- filtered.add(elements[i]);
- }
- return filtered.toArray();
- }
- return elements;
- }
-
- private Object[] getTreeChildren(Object element) {
- return filter(fTreeViewer.getFilters(), fTreeContentProvider.getChildren(element));
- }
-
- private Object[] getListElements(Object element) {
- return filter(fListViewer.getFilters(), fListContentProvider.getElements(element));
- }
-
- public Set getWhiteCheckedTreeItems() {
- return new HashSet(fWhiteCheckedTreeItems);
- }
-
- private void handleUpdateSelection(Map items) {
- Iterator keyIterator= items.keySet().iterator();
-
- //Update the store before the hierarchy to prevent updating parents before all of the children are done
- while (keyIterator.hasNext()) {
- Object key= keyIterator.next();
- //Replace the items in the checked state store with those from the supplied items
- List selections= (List) items.get(key);
- if (selections.size() == 0)
- //If it is empty remove it from the list
- fCheckedStateStore.remove(key);
- else {
- fCheckedStateStore.put(key, selections);
- // proceed up the tree element hierarchy
- Object parent= fTreeContentProvider.getParent(key);
- if (parent != null) {
- addToHierarchyToCheckedStore(parent);
- }
- }
- }
-
- //Now update hierarchies
- keyIterator= items.keySet().iterator();
-
- while (keyIterator.hasNext()) {
- Object key= keyIterator.next();
- updateHierarchy(key);
- if (fCurrentTreeSelection != null && fCurrentTreeSelection.equals(key)) {
- fListViewer.setAllChecked(false);
- fListViewer.setCheckedElements(((List) items.get(key)).toArray());
- }
- }
- }
-
- /**
- * Checks if an element is grey checked.
- */
- public boolean isTreeItemGreyChecked(Object object) {
- return fTreeViewer.getGrayed(object);
- }
-
- /**
- * For a given element, expand its chidren to a level.
- */
- public void expandTreeToLevel(Object object, int level) {
- fTreeViewer.expandToLevel(object, level);
- }
- /**
- * @param selection
- */
- public void setTreeSelection(ISelection selection) {
- fTreeViewer.setSelection(selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CreateJavadocActionDelegate.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CreateJavadocActionDelegate.java
deleted file mode 100644
index b7e51f8e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/CreateJavadocActionDelegate.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-
-public class CreateJavadocActionDelegate implements IObjectActionDelegate {
-
- private ISelection fCurrentSelection;
- private Shell fCurrentShell;
-
- /*
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- fCurrentShell= targetPart.getSite().getShell();
- }
-
- /*
- * @see IActionDelegate#run(IAction)
- */
- public void run(IAction action) {
- if (fCurrentSelection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection= (IStructuredSelection) fCurrentSelection;
- Object first= structuredSelection.getFirstElement();
- if (first instanceof IFile) {
- JavadocWizard wizard= new JavadocWizard((IFile) first);
- JavadocWizard.openJavadocWizard(wizard, fCurrentShell, structuredSelection);
- }
- }
- }
-
- /*
- * @see IActionDelegate#selectionChanged(IAction, ISelection)
- */
- public void selectionChanged(IAction action, ISelection selection) {
- fCurrentSelection= selection;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocConsoleLineTracker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocConsoleLineTracker.java
deleted file mode 100644
index 13d1ebdc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocConsoleLineTracker.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.debug.ui.console.IConsole;
-import org.eclipse.debug.ui.console.IConsoleLineTracker;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.console.IHyperlink;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavadocConsoleLineTracker implements IConsoleLineTracker {
-
- private static class JavadocConsoleHyperLink implements IHyperlink {
-
- private IPath fExternalPath;
- private int fLineNumber;
-
- public JavadocConsoleHyperLink(IPath externalPath, int lineNumber) {
- fExternalPath= externalPath;
- fLineNumber= lineNumber;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkEntered()
- */
- public void linkEntered() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkExited()
- */
- public void linkExited() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkActivated()
- */
- public void linkActivated() {
- try {
- IFile[] files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(fExternalPath);
- if (files.length > 0) {
- for (int i = 0; i < files.length; i++) {
- IFile curr= files[0];
- IJavaScriptElement element= JavaScriptCore.create(curr);
- if (element != null && element.exists()) {
- IEditorPart part= JavaScriptUI.openInEditor(element, true, false);
- if (part instanceof ITextEditor) {
- revealLine((ITextEditor) part, fLineNumber);
- }
- return;
- }
- }
- }
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private void revealLine(ITextEditor editor, int lineNumber) throws BadLocationException {
- IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
- IRegion region= document.getLineInformation(lineNumber - 1);
- editor.selectAndReveal(region.getOffset(), 0);
- }
-
- }
-
-
- private IConsole fConsole;
-
- /**
- *
- */
- public JavadocConsoleLineTracker() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleLineTracker#init(org.eclipse.debug.ui.console.IConsole)
- */
- public void init(IConsole console) {
- fConsole= console;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleLineTracker#lineAppended(org.eclipse.jface.text.IRegion)
- */
- public void lineAppended(IRegion line) {
- try {
- int offset = line.getOffset();
- int length = line.getLength();
- String text = fConsole.getDocument().get(offset, length);
-
- int index1= text.indexOf(':');
- if (index1 == -1) {
- return;
- }
-
- int lineNumber= -1;
- IPath path= null;
- int index2= text.indexOf(':', index1 + 1);
- while ((index2 != -1) && (path == null)) {
- if (index1 < index2) {
- try {
- String substr= text.substring(index1 + 1, index2);
- lineNumber= Integer.parseInt(substr);
- path= Path.fromOSString(text.substring(0, index1));
- } catch (NumberFormatException e) {
- // ignore
- }
- }
- index1= index2;
- index2= text.indexOf(':', index1 + 1);
- }
-
- if (lineNumber != -1) {
- JavadocConsoleHyperLink link= new JavadocConsoleHyperLink(path, lineNumber);
- fConsole.addLink(link, line.getOffset(), index1);
-
- }
- } catch (BadLocationException e) {
- // ignore
- }
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.console.IConsoleLineTracker#dispose()
- */
- public void dispose() {
- fConsole = null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java
deleted file mode 100644
index 9ff6e643..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class JavadocExportMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.javadocexport.JavadocExportMessages";//$NON-NLS-1$
-
- private JavadocExportMessages() {
- // Do not instantiate
- }
-
- public static String JavadocSpecificsWizardPage_description;
- public static String JavadocSpecificsWizardPage_stylesheetbrowsedialog_title;
- public static String JavadocSpecificsWizardPage_overviewbutton_label;
- public static String JavadocSpecificsWizardPage_overviewbrowse_label;
- public static String JavadocSpecificsWizardPage_extraoptionsfield_label;
- public static String JavadocSpecificsWizardPage_vmoptionsfield_label;
- public static String JavadocSpecificsWizardPage_overviewbrowsedialog_title;
- public static String JavadocSpecificsWizardPage_antscriptbutton_label;
- public static String JavadocSpecificsWizardPage_antscripttext_label;
- public static String JavadocSpecificsWizardPage_antscriptbrowse_label;
- public static String JavadocSpecificsWizardPage_openbrowserbutton_label;
- public static String JavadocSpecificsWizardPage_antscriptbrowsedialog_title;
- public static String JavadocSpecificsWizardPage_antscriptbrowsedialog_label;
-// public static String JavadocSpecificsWizardPage_sourcecompatibility_label;
- public static String JavadocSpecificsWizardPage_overviewnotfound_error;
- public static String JavadocSpecificsWizardPage_overviewincorrect_error;
- public static String JavadocSpecificsWizardPage_antfileincorrect_error;
- public static String JavadocSpecificsWizardPage_antfileoverwrite_warning;
- public static String JavadocTreeWizardPage_javadoctreewizardpage_description;
- public static String JavadocTreeWizardPage_checkboxtreeandlistgroup_label;
- public static String JavadocTreeWizardPage_visibilitygroup_label;
- public static String JavadocTreeWizardPage_privatebutton_label;
- public static String JavadocTreeWizardPage_packagebutton_label;
- public static String JavadocTreeWizardPage_protectedbutton_label;
- public static String JavadocTreeWizardPage_publicbutton_label;
- public static String JavadocTreeWizardPage_standarddocletbutton_label;
- public static String JavadocTreeWizardPage_destinationfield_label;
- public static String JavadocTreeWizardPage_destinationbrowse_label;
- public static String JavadocTreeWizardPage_customdocletbutton_label;
- public static String JavadocTreeWizardPage_docletnamefield_label;
- public static String JavadocTreeWizardPage_docletpathfield_label;
- public static String JavadocTreeWizardPage_destinationbrowsedialog_title;
- public static String JavadocTreeWizardPage_destinationbrowsedialog_label;
- public static String JavadocTreeWizardPage_nodocletname_error;
- public static String JavadocTreeWizardPage_invaliddocletname_error;
- public static String JavadocTreeWizardPage_invaliddocletpath_error;
- public static String JavadocTreeWizardPage_nodestination_error;
- public static String JavadocTreeWizardPage_invaliddestination_error;
- public static String JavadocTreeWizardPage_invalidtreeselection_error;
- public static String JavadocTreeWizardPage_javadoccmd_dialog_title;
- public static String JavadocTreeWizardPage_javadoccmd_error_enterpath;
- public static String JavadocTreeWizardPage_javadoccmd_error_notexists;
- public static String JavadocWizardPage_javadocwizardpage_description;
- public static String JavadocWizard_javadocwizard_title;
- public static String JavadocWizard_updatejavadoclocation_message;
- public static String JavadocWizard_updatejavadocdialog_label;
- public static String JavadocWizard_javadocprocess_label;
- public static String JavadocWizard_launchconfig_name;
- public static String JavadocWizard_error_title;
- public static String JavadocWizard_launch_error_message;
- public static String JavadocWizard_exec_error_message;
- public static String JavadocWizard_error_writeANT_title;
- public static String JavadocWizard_error_writeANT_message;
- public static String JavadocOptionsManager_antfileincorrectCE_warning;
- public static String JavadocOptionsManager_antfileincorrectIOE_warning;
- public static String JavadocOptionsManager_antfileincorrectSAXE_warning;
- public static String JavadocOptionsManager_createXM_error;
- public static String JavadocStandardWizardPage_description;
- public static String JavadocStandardWizardPage_titlebutton_label;
- public static String JavadocStandardWizardPage_basicgroup_label;
- public static String JavadocStandardWizardPage_usebutton_label;
- public static String JavadocStandardWizardPage_hierarchybutton_label;
- public static String JavadocStandardWizardPage_navigartorbutton_label;
- public static String JavadocStandardWizardPage_indexbutton_label;
- public static String JavadocStandardWizardPage_seperateindexbutton_label;
- public static String JavadocStandardWizardPage_tagsgroup_label;
- public static String JavadocStandardWizardPage_authorbutton_label;
- public static String JavadocStandardWizardPage_nojarlinkref_error;
- public static String JavadocStandardWizardPage_versionbutton_label;
- public static String JavadocStandardWizardPage_deprecatedbutton_label;
- public static String JavadocStandardWizardPage_deprecatedlistbutton_label;
- public static String JavadocStandardWizardPage_stylesheettext_label;
- public static String JavadocStandardWizardPage_selectallbutton_label;
- public static String JavadocStandardWizardPage_clearallbutton_label;
- public static String JavadocStandardWizardPage_referencedclasses_label;
- public static String JavadocStandardWizardPage_stylesheetnopath_error;
- public static String JavadocStandardWizardPage_stylesheetnotcss_error;
- public static String JavadocStandardWizardPage_stylesheetbrowsebutton_label;
- public static String JavadocStandardWizardPage_configurebutton_label;
- public static String JavadocStandardWizardPage_configurecontainer_error_title;
- public static String JavadocStandardWizardPage_configurecontainer_error_message;
- public static String JavadocStandardWizardPage_javadocpropertydialog_title;
- public static String JavadocStandardWizardPage_nolinkref_error;
- public static String JavadocLinkDialogLabelProvider_configuredentry;
- public static String JavadocLinkDialogLabelProvider_notconfiguredentry;
- public static String JavadocTreeWizardPage_privatevisibilitydescription_label;
- public static String JavadocTreeWizardPage_warning_mayoverwritefiles;
- public static String JavadocTreeWizardPage_packagevisibledescription_label;
- public static String JavadocTreeWizardPage_protectedvisibilitydescription_label;
- public static String JavadocTreeWizardPage_publicvisibilitydescription_label;
- public static String JavadocWizard_antInformationDialog_title;
- public static String JavadocWizard_antInformationDialog_message;
- public static String JavadocTreeWizardPage_javadoccommand_label;
- public static String JavadocTreeWizardPage_javadoccommand_button_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavadocExportMessages.class);
- }
-
- public static String JavadocOptionsManager_status_title;
- public static String JavadocOptionsManager_status_non_local;
- public static String JavadocWizard_warning_starting_message;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties
deleted file mode 100644
index 5bfa5d27..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties
+++ /dev/null
@@ -1,119 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-JavadocSpecificsWizardPage_description=Configure JSDoc arguments.
-
-JavadocSpecificsWizardPage_stylesheetbrowsedialog_title=Style sheet Selection
-JavadocSpecificsWizardPage_overviewbutton_label=&Overview:
-JavadocSpecificsWizardPage_overviewbrowse_label=Bro&wse...
-JavadocSpecificsWizardPage_extraoptionsfield_label=E&xtra JSDoc options (path names with white spaces must be enclosed in quotes):
-JavadocSpecificsWizardPage_vmoptionsfield_label=&VM options (prefixed with '-J', e.g. -J-Xmx180m for larger heap space):
-JavadocSpecificsWizardPage_overviewbrowsedialog_title=Select overview page
-JavadocSpecificsWizardPage_antscriptbutton_label=&Save the settings of this JSDoc export as an Ant script:
-JavadocSpecificsWizardPage_antscripttext_label=&Ant Script:
-JavadocSpecificsWizardPage_antscriptbrowse_label=Brows&e...
-JavadocSpecificsWizardPage_openbrowserbutton_label=O&pen generated index file in browser
-JavadocSpecificsWizardPage_antscriptbrowsedialog_title=Destination Selection
-JavadocSpecificsWizardPage_antscriptbrowsedialog_label=Select destination folder for ANT script:
-
-#JavadocSpecificsWizardPage_sourcecompatibility_label=&JRE source compatibility:
-JavadocSpecificsWizardPage_overviewnotfound_error=Overview path not found.
-JavadocSpecificsWizardPage_overviewincorrect_error=Overview must be an html document.
-JavadocSpecificsWizardPage_antfileincorrect_error=Not a valid Ant file name.
-JavadocSpecificsWizardPage_antfileoverwrite_warning=The generated ant file will overwrite the existing ant file.
-JavadocTreeWizardPage_javadoctreewizardpage_description=Select types for JSDoc generation.
-JavadocTreeWizardPage_checkboxtreeandlistgroup_label=Select &types for which JSDoc will be generated:
-JavadocTreeWizardPage_visibilitygroup_label=Create JSDoc for members with visibility:
-JavadocTreeWizardPage_privatebutton_label=Pr&ivate
-JavadocTreeWizardPage_packagebutton_label=P&ackage
-JavadocTreeWizardPage_protectedbutton_label=Pr&otected
-JavadocTreeWizardPage_publicbutton_label=P&ublic
-JavadocTreeWizardPage_standarddocletbutton_label=Use &Standard Doclet
-JavadocTreeWizardPage_destinationfield_label=&Destination:
-JavadocTreeWizardPage_destinationbrowse_label=Bro&wse...
-JavadocTreeWizardPage_customdocletbutton_label=Use &Custom Doclet
-JavadocTreeWizardPage_docletnamefield_label=Doc&let name:
-JavadocTreeWizardPage_docletpathfield_label=Doclet class &path:
-JavadocTreeWizardPage_destinationbrowsedialog_title=Destination Selection
-JavadocTreeWizardPage_destinationbrowsedialog_label=Select the JSDoc destination folder:
-JavadocTreeWizardPage_nodocletname_error=Enter a doclet name.
-JavadocTreeWizardPage_invaliddocletname_error=Invalid doclet name.
-JavadocTreeWizardPage_invaliddocletpath_error=Not a valid doclet class path.
-JavadocTreeWizardPage_nodestination_error=Enter the destination folder.
-JavadocTreeWizardPage_invaliddestination_error=Not a valid folder.
-JavadocTreeWizardPage_invalidtreeselection_error=Selection does not contain any JavaScript files
-JavadocTreeWizardPage_javadoccmd_dialog_title=JSDoc Command Selection
-JavadocTreeWizardPage_javadoccmd_error_enterpath=Specify the JSDoc command.
-JavadocTreeWizardPage_javadoccmd_error_notexists=The JSDoc command does not exist.
-
-
-JavadocWizardPage_javadocwizardpage_description=JSDoc Generation
-JavadocWizard_warning_starting_message=Problems while starting the JSDoc command.
-JavadocWizard_javadocwizard_title=Generate JSDoc
-JavadocWizard_updatejavadoclocation_message=Do you want to update the JSDoc location for ''{0}'' with the chosen destination folder ''{1}''?
-JavadocWizard_updatejavadocdialog_label=Update JSDoc Location
-JavadocWizard_javadocprocess_label=JSDoc Generation
-JavadocWizard_launchconfig_name=JSDoc
-
-JavadocWizard_error_title=Generate JSDoc
-JavadocWizard_launch_error_message=Could not launch JSDoc command. See log for details.
-JavadocWizard_exec_error_message=Could not launch JSDoc command. See log for details.
-
-JavadocWizard_error_writeANT_title=Create ANT file
-JavadocWizard_error_writeANT_message=Create ANT file failed.
-
-JavadocOptionsManager_antfileincorrectCE_warning=Unable to run wizard from Ant file, loading previous settings.
-JavadocOptionsManager_antfileincorrectIOE_warning=Error reading Ant file, loading previous settings.
-JavadocOptionsManager_antfileincorrectSAXE_warning=Error reading Ant file, loading previous settings.
-
-JavadocOptionsManager_createXM_error=Error writing the Ant file. No file created.
-JavadocOptionsManager_status_title=Non-local files selected.
-JavadocOptionsManager_status_non_local=File ''{0}'' has been skipped as it is not local and can not be processed by the JSDoc tool.
-
-JavadocStandardWizardPage_description=Configure JSDoc arguments for standard doclet.
-JavadocStandardWizardPage_titlebutton_label=Document &title:
-JavadocStandardWizardPage_basicgroup_label=Basic Options
-JavadocStandardWizardPage_usebutton_label=Generate &use page
-JavadocStandardWizardPage_hierarchybutton_label=Generate &hierarchy tree
-JavadocStandardWizardPage_navigartorbutton_label=Generate navi&gator bar
-JavadocStandardWizardPage_indexbutton_label=Generate &index
-JavadocStandardWizardPage_seperateindexbutton_label=Separate index &per letter
-JavadocStandardWizardPage_tagsgroup_label=Document these tags
-JavadocStandardWizardPage_authorbutton_label=@&author
-JavadocStandardWizardPage_nojarlinkref_error=Archive references are not supported by the JSDoc tool.
-JavadocStandardWizardPage_versionbutton_label=@&version
-JavadocStandardWizardPage_deprecatedbutton_label=@&deprecated
-JavadocStandardWizardPage_deprecatedlistbutton_label=deprecated &list
-JavadocStandardWizardPage_stylesheettext_label=St&yle sheet:
-JavadocStandardWizardPage_selectallbutton_label=&Select All
-JavadocStandardWizardPage_clearallbutton_label=&Clear All
-JavadocStandardWizardPage_referencedclasses_label=Select &referenced archives and projects to which links should be generated:
-JavadocStandardWizardPage_stylesheetnopath_error=Style sheet path not found.
-JavadocStandardWizardPage_stylesheetnotcss_error=Style sheet must be a css document.
-JavadocStandardWizardPage_stylesheetbrowsebutton_label=Bro&wse...
-JavadocStandardWizardPage_configurebutton_label=B&rowse...
-JavadocStandardWizardPage_configurecontainer_error_title=Configure JSDoc Location
-JavadocStandardWizardPage_configurecontainer_error_message=Unexpected problem while updating the JSDoc location.
-JavadocStandardWizardPage_javadocpropertydialog_title=Configure JSDoc Location
-
-JavadocStandardWizardPage_nolinkref_error=JSDoc location is not configured for a selected reference.
-
-JavadocLinkDialogLabelProvider_configuredentry={0} - {1}
-JavadocLinkDialogLabelProvider_notconfiguredentry={0} - not configured
-JavadocTreeWizardPage_privatevisibilitydescription_label=Private: Generate JSDoc for all classes and members.
-JavadocTreeWizardPage_warning_mayoverwritefiles=JSDoc generation may overwrite existing files
-JavadocTreeWizardPage_packagevisibledescription_label=Package: Generate JSDoc for all but private classes and members.
-JavadocTreeWizardPage_protectedvisibilitydescription_label=Protected: Generate JSDoc for protected and public classes and members.
-JavadocTreeWizardPage_publicvisibilitydescription_label=Public: Generate JSDoc for public classes and members.
-JavadocWizard_antInformationDialog_title=JSDoc Generation with Ant Scripts
-JavadocWizard_antInformationDialog_message=Ant file will be created.\nTo run the generated ant script, the operating system PATH must contain the JSDoc command.
-JavadocTreeWizardPage_javadoccommand_label=J&SDoc command:
-JavadocTreeWizardPage_javadoccommand_button_label=Confi&gure...
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkDialogLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkDialogLabelProvider.java
deleted file mode 100644
index 1b5cbaab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkDialogLabelProvider.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.net.URL;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.ISharedImages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public class JavadocLinkDialogLabelProvider extends LabelProvider {
-
- public String getText(Object element) {
- if (element instanceof JavadocLinkRef) {
- JavadocLinkRef ref= (JavadocLinkRef) element;
- URL url= ref.getURL();
- String text= ref.getFullPath().lastSegment();
- if (url != null) {
- Object[] args= new Object[] { text, url.toExternalForm() };
- return Messages.format(JavadocExportMessages.JavadocLinkDialogLabelProvider_configuredentry, args);
- } else {
- return Messages.format(JavadocExportMessages.JavadocLinkDialogLabelProvider_notconfiguredentry, text);
- }
- }
- return super.getText(element);
- }
-
- public Image getImage(Object element) {
- if (element instanceof JavadocLinkRef) {
- JavadocLinkRef ref= (JavadocLinkRef) element;
- ImageDescriptor desc;
- if (ref.isProjectRef()) {
- desc= PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT);
- } else {
- desc= JavaScriptUI.getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJS_JAR);
- }
- if (ref.getURL() == null) {
- return JavaScriptPlugin.getImageDescriptorRegistry().get(new JavaScriptElementImageDescriptor(desc, JavaScriptElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE));
- }
- return JavaScriptPlugin.getImageDescriptorRegistry().get(desc);
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkRef.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkRef.java
deleted file mode 100644
index 3796a961..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocLinkRef.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.net.URL;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathSupport;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public class JavadocLinkRef {
- private final IJavaScriptProject fProject;
- private final IPath fContainerPath;
- private IIncludePathEntry fClasspathEntry;
-
- public JavadocLinkRef(IPath containerPath, IIncludePathEntry classpathEntry, IJavaScriptProject project) {
- fContainerPath= containerPath;
- fProject= project;
- fClasspathEntry= classpathEntry;
- }
-
- public JavadocLinkRef(IJavaScriptProject project) {
- this(null, null, project);
- }
-
- public boolean isProjectRef() {
- return fClasspathEntry == null;
- }
-
- public IPath getFullPath() {
- return isProjectRef() ? fProject.getPath() : fClasspathEntry.getPath();
- }
-
- public URL getURL() {
- if (isProjectRef()) {
- return JavaScriptUI.getProjectJSdocLocation(fProject);
- } else {
- return JavaScriptUI.getLibraryJSdocLocation(fClasspathEntry);
- }
- }
-
- public void setURL(URL url, IProgressMonitor monitor) throws CoreException {
- if (isProjectRef()) {
- JavaScriptUI.setProjectJSdocLocation(fProject, url);
- } else {
- CPListElement element= CPListElement.createFromExisting(fClasspathEntry, fProject);
- String location= url != null ? url.toExternalForm() : null;
- element.setAttribute(CPListElement.JAVADOC, location);
- String[] changedAttributes= { CPListElement.JAVADOC };
- BuildPathSupport.modifyClasspathEntry(null, element.getClasspathEntry(), changedAttributes, fProject, fContainerPath, monitor);
- fClasspathEntry= element.getClasspathEntry();
- }
- }
-
- public boolean equals(Object obj) {
- if (obj != null && obj.getClass().equals(getClass())) {
- JavadocLinkRef other= (JavadocLinkRef) obj;
- if (!fProject.equals(other.fProject) || isProjectRef() != other.isProjectRef()) {
- return false;
- }
- if (!isProjectRef()) {
- return !fClasspathEntry.equals(other.fClasspathEntry);
- }
- }
- return false;
- }
-
- public int hashCode() {
- if (isProjectRef()) {
- return fProject.hashCode();
- } else {
- return fProject.hashCode() + fClasspathEntry.hashCode();
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocMemberContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocMemberContentProvider.java
deleted file mode 100644
index d9989219..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocMemberContentProvider.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class JavadocMemberContentProvider implements ITreeContentProvider {
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- return new Object[0];
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- //@test
- //System.out.println(element.getClass().toString());
- if (element instanceof IPackageFragment)
- return ((IPackageFragment) element).getParent();
- return null;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- try {
- if (element instanceof IPackageFragment) {
- IPackageFragment iPackageFragment= (IPackageFragment) element;
- return (iPackageFragment.getChildren().length > 0);
- }
- } catch (JavaScriptModelException e) {
- }
- return false;
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- try {
- if (inputElement instanceof IPackageFragment) {
- IJavaScriptUnit[] cu= ((IPackageFragment) inputElement).getJavaScriptUnits();
- return cu;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return new Object[0];
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocOptionsManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocOptionsManager.java
deleted file mode 100644
index 0adb68f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocOptionsManager.java
+++ /dev/null
@@ -1,1158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids, sdavids@gmx.de, - bug 38692
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerException;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.launching.ExecutionArguments;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstallType;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-public class JavadocOptionsManager {
-
- private IFile fXmlfile;
-
- private StatusInfo fWizardStatus;
-
- private String[] fJavadocCommandHistory;
-
-
- private IJavaScriptElement[] fSelectedElements;
- private IJavaScriptElement[] fInitialElements;
-
- private String fAccess;
- private String fDocletpath;
- private String fDocletname;
- private boolean fFromStandard;
- private String fStylesheet;
- private String fAdditionalParams;
- private String fVMParams;
- private String fOverview;
- private String fTitle;
-
- private String[] fHRefs;
-
- private IPath[] fSourcepath;
- private IPath[] fClasspath;
-
- private boolean fNotree;
- private boolean fNoindex;
- private boolean fSplitindex;
- private boolean fNonavbar;
- private boolean fNodeprecated;
- private boolean fNoDeprecatedlist;
- private boolean fAuthor;
- private boolean fVersion;
- private boolean fUse;
-
- private String fSource;
-
- private boolean fOpenInBrowser;
-
- private RecentSettingsStore fRecentSettings;
-
- //add-on for multi-project version
- private String fDestination;
- private String fAntpath;
-
- public final String PRIVATE= "private"; //$NON-NLS-1$
- public final String PROTECTED= "protected"; //$NON-NLS-1$
- public final String PACKAGE= "package"; //$NON-NLS-1$
- public final String PUBLIC= "public"; //$NON-NLS-1$
-
- public final String USE= "use"; //$NON-NLS-1$
- public final String NOTREE= "notree"; //$NON-NLS-1$
- public final String NOINDEX= "noindex"; //$NON-NLS-1$
- public final String NONAVBAR= "nonavbar"; //$NON-NLS-1$
- public final String NODEPRECATED= "nodeprecated"; //$NON-NLS-1$
- public final String NODEPRECATEDLIST= "nodeprecatedlist"; //$NON-NLS-1$
- public final String VERSION= "version"; //$NON-NLS-1$
- public final String AUTHOR= "author"; //$NON-NLS-1$
- public final String SPLITINDEX= "splitindex"; //$NON-NLS-1$
- public final String STYLESHEETFILE= "stylesheetfile"; //$NON-NLS-1$
- public final String OVERVIEW= "overview"; //$NON-NLS-1$
- public final String DOCLETNAME= "docletname"; //$NON-NLS-1$
- public final String DOCLETPATH= "docletpath"; //$NON-NLS-1$
- public final String SOURCEPATH= "sourcepath"; //$NON-NLS-1$
- public final String CLASSPATH= "classpath"; //$NON-NLS-1$
- public final String DESTINATION= "destdir"; //$NON-NLS-1$
- public final String OPENINBROWSER= "openinbrowser"; //$NON-NLS-1$
-
- public final String VISIBILITY= "access"; //$NON-NLS-1$
- public final String PACKAGENAMES= "packagenames"; //$NON-NLS-1$
- public final String SOURCEFILES= "sourcefiles"; //$NON-NLS-1$
- public final String EXTRAOPTIONS= "additionalparam"; //$NON-NLS-1$
- public final String VMOPTIONS= "vmparam"; //$NON-NLS-1$
- //public final String JAVADOCCOMMAND= "javadoccommand"; //$NON-NLS-1$
- public final String TITLE= "doctitle"; //$NON-NLS-1$
- public final String HREF= "href"; //$NON-NLS-1$
-
- public final String NAME= "name"; //$NON-NLS-1$
- public final String PATH= "path"; //$NON-NLS-1$
- public final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$
- public final String ANTPATH= "antpath"; //$NON-NLS-1$
- public final String SOURCE= "source"; //$NON-NLS-1$
-
- private final String SECTION_JAVADOC= "javadoc"; //$NON-NLS-1$
-
- private static final String JAVADOC_COMMAND_HISTORY= "javadoc_command_history"; //$NON-NLS-1$
-
- public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings dialogSettings, List currSelection) {
- fXmlfile= xmlJavadocFile;
- fWizardStatus= new StatusInfo();
-
- IDialogSettings javadocSection= dialogSettings.getSection(SECTION_JAVADOC);
-
- String commandHistory= null;
- if (javadocSection != null) {
- commandHistory= javadocSection.get(JAVADOC_COMMAND_HISTORY);
- }
- if (commandHistory == null || commandHistory.length() == 0) {
- commandHistory= initJavadocCommandDefault();
- }
- fJavadocCommandHistory= arrayFromFlatString(commandHistory);
-
- fRecentSettings= new RecentSettingsStore(javadocSection);
-
- if (xmlJavadocFile != null) {
- try {
- JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents());
- Element element= reader.readXML();
- if (element != null) {
- loadFromXML(element);
- return;
- }
- fWizardStatus.setWarning(JavadocExportMessages.JavadocOptionsManager_antfileincorrectCE_warning);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- fWizardStatus.setWarning(JavadocExportMessages.JavadocOptionsManager_antfileincorrectCE_warning);
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- fWizardStatus.setWarning(JavadocExportMessages.JavadocOptionsManager_antfileincorrectIOE_warning);
- } catch (SAXException e) {
- fWizardStatus.setWarning(JavadocExportMessages.JavadocOptionsManager_antfileincorrectSAXE_warning);
- }
- }
- if (javadocSection != null) {
- loadFromDialogStore(javadocSection, currSelection);
- } else {
- loadDefaults(currSelection);
- }
- }
-
-
- /*
- * Returns the Java project that is parent top all selected elements or null if
- * the elements are from several projects.
- */
- private IJavaScriptProject getSingleProjectFromInitialSelection() {
- IJavaScriptProject res= null;
- for (int i= 0; i < fInitialElements.length; i++) {
- IJavaScriptProject curr= fInitialElements[i].getJavaScriptProject();
- if (res == null) {
- res= curr;
- } else if (!res.equals(curr)) {
- return null;
- }
- }
- if (res != null && res.isOpen()) {
- return res;
- }
- return null;
- }
-
-
- private void loadFromDialogStore(IDialogSettings settings, List sel) {
- fInitialElements= getInitialElementsFromSelection(sel);
-
- IJavaScriptProject project= getSingleProjectFromInitialSelection();
-
- fAccess= settings.get(VISIBILITY);
- if (fAccess == null)
- fAccess= PROTECTED;
-
- //this is defaulted to false.
- fFromStandard= settings.getBoolean(FROMSTANDARD);
-
- //doclet is loaded even if the standard doclet is being used
- fDocletpath= settings.get(DOCLETPATH);
- fDocletname= settings.get(DOCLETNAME);
- if (fDocletpath == null || fDocletname == null) {
- fFromStandard= true;
- fDocletpath= ""; //$NON-NLS-1$
- fDocletname= ""; //$NON-NLS-1$
- }
-
-
- if (project != null) {
- fAntpath= getRecentSettings().getAntpath(project);
- } else {
- fAntpath= settings.get(ANTPATH);
- if (fAntpath == null) {
- fAntpath= ""; //$NON-NLS-1$
- }
- }
-
-
- if (project != null) {
- fDestination= getRecentSettings().getDestination(project);
- } else {
- fDestination= settings.get(DESTINATION);
- if (fDestination == null) {
- fDestination= ""; //$NON-NLS-1$
- }
- }
-
- fTitle= settings.get(TITLE);
- if (fTitle == null)
- fTitle= ""; //$NON-NLS-1$
-
- fStylesheet= settings.get(STYLESHEETFILE);
- if (fStylesheet == null)
- fStylesheet= ""; //$NON-NLS-1$
-
- fVMParams= settings.get(VMOPTIONS);
- if (fVMParams == null)
- fVMParams= ""; //$NON-NLS-1$
-
- fAdditionalParams= settings.get(EXTRAOPTIONS);
- if (fAdditionalParams == null)
- fAdditionalParams= ""; //$NON-NLS-1$
-
- fOverview= settings.get(OVERVIEW);
- if (fOverview == null)
- fOverview= ""; //$NON-NLS-1$
-
- fUse= loadBoolean(settings.get(USE));
- fAuthor= loadBoolean(settings.get(AUTHOR));
- fVersion= loadBoolean(settings.get(VERSION));
- fNodeprecated= loadBoolean(settings.get(NODEPRECATED));
- fNoDeprecatedlist= loadBoolean(settings.get(NODEPRECATEDLIST));
- fNonavbar= loadBoolean(settings.get(NONAVBAR));
- fNoindex= loadBoolean(settings.get(NOINDEX));
- fNotree= loadBoolean(settings.get(NOTREE));
- fSplitindex= loadBoolean(settings.get(SPLITINDEX));
- fOpenInBrowser= loadBoolean(settings.get(OPENINBROWSER));
-
- fSource= settings.get(SOURCE);
- if (project != null) {
- fSource= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- }
-
- if (project != null) {
- fHRefs= getRecentSettings().getHRefs(project);
- } else {
- fHRefs= new String[0];
- }
- }
-
-
- //loads defaults for wizard (nothing is stored)
- private void loadDefaults(List sel) {
- fInitialElements= getInitialElementsFromSelection(sel);
-
- IJavaScriptProject project= getSingleProjectFromInitialSelection();
-
- if (project != null) {
- fAntpath= getRecentSettings().getAntpath(project);
- fDestination= getRecentSettings().getDestination(project);
- fHRefs= getRecentSettings().getHRefs(project);
- } else {
- fAntpath= ""; //$NON-NLS-1$
- fDestination= ""; //$NON-NLS-1$
- fHRefs= new String[0];
- }
-
- fAccess= PUBLIC;
-
- fDocletname= ""; //$NON-NLS-1$
- fDocletpath= ""; //$NON-NLS-1$
- fTitle= ""; //$NON-NLS-1$
- fStylesheet= ""; //$NON-NLS-1$
- fVMParams= ""; //$NON-NLS-1$
- fAdditionalParams= ""; //$NON-NLS-1$
- fOverview= ""; //$NON-NLS-1$
-
- fUse= true;
- fAuthor= true;
- fVersion= true;
- fNodeprecated= false;
- fNoDeprecatedlist= false;
- fNonavbar= false;
- fNoindex= false;
- fNotree= false;
- fSplitindex= true;
- fOpenInBrowser= false;
- fSource= "1.3"; //$NON-NLS-1$
- if (project != null) {
- fSource= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- }
-
- //by default it is empty all project map to the empty string
- fFromStandard= true;
- }
-
- private void loadFromXML(Element element) {
-
- fAccess= element.getAttribute(VISIBILITY);
- if (fAccess.length() == 0)
- fAccess= PROTECTED;
-
- //Since the selected packages are stored we must locate the project
- String destination= element.getAttribute(DESTINATION);
- fDestination= makeAbsolutePathFromRelative(new Path(destination)).toOSString();
- fFromStandard= true;
- fDocletname= ""; //$NON-NLS-1$
- fDocletpath= ""; //$NON-NLS-1$
-
- if (destination.length() == 0) {
- NodeList list= element.getChildNodes();
- for (int i= 0; i < list.getLength(); i++) {
- Node child= list.item(i);
- if (child.getNodeName().equals("doclet")) { //$NON-NLS-1$
- fDocletpath= ((Element) child).getAttribute(PATH);
- fDocletname= ((Element) child).getAttribute(NAME);
- if (fDocletpath.length() != 0 || fDocletname.length() != 0) {
- fFromStandard= false;
- } else {
- fDocletname= ""; //$NON-NLS-1$
- fDocletpath= ""; //$NON-NLS-1$
- }
- break;
- }
- }
- }
-
- fInitialElements= getSelectedElementsFromAnt(element);
-
-
- //find all the links stored in the ant script
- NodeList children= element.getChildNodes();
- fHRefs= new String[children.getLength()];
- for (int i= 0; i < fHRefs.length; i++) {
- Node child= children.item(i);
- if (child.getNodeName().equals("link")) { //$NON-NLS-1$
- fHRefs[i]= ((Element) child).getAttribute(HREF);
- }
- }
-
- // The ant file for generating the Javadoc is always local.
- IPath p= fXmlfile.getLocation();
- if (p != null)
- fAntpath= p.toOSString();
- else
- fAntpath= ""; //$NON-NLS-1$
-
- fStylesheet= element.getAttribute(STYLESHEETFILE);
- fTitle= element.getAttribute(TITLE);
-
-
- StringBuffer additionals= new StringBuffer();
- StringBuffer vmargs= new StringBuffer();
- String extraOptions= element.getAttribute(EXTRAOPTIONS);
- if (extraOptions.length() > 0) {
- ExecutionArguments tokens= new ExecutionArguments("", extraOptions); //$NON-NLS-1$
- String[] args= tokens.getProgramArgumentsArray();
-
- boolean vmarg= false;
- for (int i= 0; i < args.length; i++) {
- String curr= args[i];
- if (curr.length() > 0 && curr.charAt(0) == '-') {
- // an command
- vmarg=(curr.length() > 1 && curr.charAt(1) == 'J');
- }
- if (vmarg) {
- vmargs.append(curr).append(' ');
- } else {
- additionals.append(curr).append(' ');
- }
- }
- }
-
- fAdditionalParams= additionals.toString();
- fVMParams= vmargs.toString();
- fOverview= element.getAttribute(OVERVIEW);
-
- fUse= loadBoolean(element.getAttribute(USE));
- fAuthor= loadBoolean(element.getAttribute(AUTHOR));
- fVersion= loadBoolean(element.getAttribute(VERSION));
- fNodeprecated= loadBoolean(element.getAttribute(NODEPRECATED));
- fNoDeprecatedlist= loadBoolean(element.getAttribute(NODEPRECATEDLIST));
- fNonavbar= loadBoolean(element.getAttribute(NONAVBAR));
- fNoindex= loadBoolean(element.getAttribute(NOINDEX));
- fNotree= loadBoolean(element.getAttribute(NOTREE));
- fSplitindex= loadBoolean(element.getAttribute(SPLITINDEX));
-
- fSource= element.getAttribute(SOURCE);
- }
-
- /*
- * Method creates an absolute path to the project. If the path is already
- * absolute it returns the path. If it encounters any difficulties in
- * creating the absolute path, the method returns null.
- *
- * @param path
- * @return IPath
- */
- private IPath makeAbsolutePathFromRelative(IPath path) {
- if (!path.isAbsolute()) {
- if (fXmlfile == null) {
- return null;
- }
- // The XML file is always local. So ok to use getLocation here
- IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location
- if (basePath == null) {
- return null;
- }
- return basePath.append(path);
- }
- return path;
- }
-
- private IContainer[] getSourceContainers(Element element) {
- String sourcePaths= element.getAttribute(SOURCEPATH);
-
- if (sourcePaths.endsWith(File.pathSeparator)) {
- sourcePaths += '.';
- }
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
-
- ArrayList res= new ArrayList();
-
- String[] strings= sourcePaths.split(File.pathSeparator);
- for (int i= 0; i < strings.length; i++) {
- IPath path= makeAbsolutePathFromRelative(new Path(strings[i].trim()));
- if (path != null) {
- IContainer[] containers= root.findContainersForLocation(path);
- for (int k= 0; k < containers.length; k++) {
- res.add(containers[k]);
- }
- }
-
- }
- return (IContainer[]) res.toArray(new IContainer[res.size()]);
- }
-
- private IJavaScriptElement[] getSelectedElementsFromAnt(Element element) {
- List res= new ArrayList();
-
- // get all the packages listed in the ANT file
- String packagenames= element.getAttribute(PACKAGENAMES);
- if (packagenames != null) {
- IContainer[] containers= getSourceContainers(element);
-
- StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$
- while (tokenizer.hasMoreTokens()) {
- IPath relPackagePath= new Path(tokenizer.nextToken().trim().replace('.', '/'));
- for (int i= 0; i < containers.length; i++) {
- IContainer curr= containers[i];
- IResource resource= curr.findMember(relPackagePath);
- if (resource != null) {
- IJavaScriptElement javaElem= JavaScriptCore.create(resource);
- if (javaElem instanceof IPackageFragment) {
- res.add(javaElem);
- }
- }
- }
- }
- }
-
- //get all CompilationUnites listed in the ANT file
- String sourcefiles= element.getAttribute(SOURCEFILES);
- if (sourcefiles != null) {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
-
- StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$
- while (tokenizer.hasMoreTokens()) {
- String name= tokenizer.nextToken().trim();
- if (JavaScriptCore.isJavaScriptLikeFileName(name)) {
- IPath path= makeAbsolutePathFromRelative(new Path(name));
- //if unable to create an absolute path to the resource skip it
- if (path != null) {
- IFile[] files= root.findFilesForLocation(path);
- for (int i= 0; i < files.length; i++) {
- IJavaScriptElement el= JavaScriptCore.createCompilationUnitFrom(files[i]);
- if (el != null) {
- res.add(el);
- }
- }
- }
- }
- }
- }
- return (IJavaScriptElement[]) res.toArray(new IJavaScriptElement[res.size()]);
- }
-
- /**
- * @return Returns the javadocCommandHistory.
- */
- public String[] getJavadocCommandHistory() {
- return fJavadocCommandHistory;
- }
-
-
- //it is possible that the package list is empty
- public StatusInfo getWizardStatus() {
- return fWizardStatus;
- }
-
- public IJavaScriptElement[] getInitialElements() {
- return fInitialElements;
- }
-
- public IJavaScriptElement[] getSourceElements() {
- return fSelectedElements;
- }
-
- public String getAccess() {
- return fAccess;
- }
-
- public String getAntpath() {
- return fAntpath;
- }
-
- public boolean isFromStandard() {
- return fFromStandard;
- }
-
- public String getDestination() {
- return fDestination;
- }
-
- public String getDocletPath() {
- return fDocletpath;
- }
-
- public String getDocletName() {
- return fDocletname;
- }
-
- public String getStyleSheet() {
- return fStylesheet;
- }
-
- public String getOverview() {
- return fOverview;
- }
-
- public String getAdditionalParams() {
- return fAdditionalParams;
- }
-
- public String getVMParams() {
- return fVMParams;
- }
-
- public IPath[] getClasspath() {
- return fClasspath;
- }
-
- public IPath[] getSourcepath() {
- return fSourcepath;
- }
-
- public String getTitle() {
- return fTitle;
- }
-
- public boolean doOpenInBrowser() {
- return fOpenInBrowser;
- }
-
- public String[] getHRefs() {
- return fHRefs;
- }
-
- public boolean getBoolean(String flag) {
-
- if (flag.equals(AUTHOR))
- return fAuthor;
- else if (flag.equals(VERSION))
- return fVersion;
- else if (flag.equals(USE))
- return fUse;
- else if (flag.equals(NODEPRECATED))
- return fNodeprecated;
- else if (flag.equals(NODEPRECATEDLIST))
- return fNoDeprecatedlist;
- else if (flag.equals(NOINDEX))
- return fNoindex;
- else if (flag.equals(NOTREE))
- return fNotree;
- else if (flag.equals(SPLITINDEX))
- return fSplitindex;
- else if (flag.equals(NONAVBAR))
- return fNonavbar;
- else
- return false;
- }
-
- private boolean loadBoolean(String value) {
-
- if (value == null || value.length() == 0)
- return false;
- else {
- if (value.equals("true")) //$NON-NLS-1$
- return true;
- else
- return false;
- }
- }
-
- private String flatPathList(IPath[] paths) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < paths.length; i++) {
- if (i > 0) {
- buf.append(File.pathSeparatorChar);
- }
- buf.append(paths[i].toOSString());
- }
- return buf.toString();
- }
-
- private String flatStringList(String[] paths) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < paths.length; i++) {
- if (i > 0) {
- buf.append(File.pathSeparatorChar);
- }
- buf.append(paths[i]);
- }
- return buf.toString();
- }
-
- private String[] arrayFromFlatString(String str) {
- StringTokenizer tok= new StringTokenizer(str, File.pathSeparator);
- String[] res= new String[tok.countTokens()];
- for (int i= 0; i < res.length; i++) {
- res[i]= tok.nextToken();
- }
- return res;
- }
-
-
- public IStatus getArgumentArray(List vmArgs, List toolArgs) {
- MultiStatus status= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, JavadocExportMessages.JavadocOptionsManager_status_title, null);
-
- //bug 38692
- vmArgs.add(getJavadocCommandHistory()[0]);
-
- if (fFromStandard) {
- toolArgs.add("-d"); //$NON-NLS-1$
- toolArgs.add(fDestination);
- } else {
- toolArgs.add("-doclet"); //$NON-NLS-1$
- toolArgs.add(fDocletname);
- toolArgs.add("-docletpath"); //$NON-NLS-1$
- toolArgs.add(fDocletpath);
- }
-
- if (fSourcepath.length > 0) {
- toolArgs.add("-sourcepath"); //$NON-NLS-1$
- toolArgs.add(flatPathList(fSourcepath));
- }
-
- if (fClasspath.length > 0) {
- toolArgs.add("-classpath"); //$NON-NLS-1$
- toolArgs.add(flatPathList(fClasspath));
- }
- toolArgs.add("-" + fAccess); //$NON-NLS-1$
-
- if (fFromStandard) {
- if (fSource.length() > 0 && !fSource.equals("-")) { //$NON-NLS-1$
- toolArgs.add("-source"); //$NON-NLS-1$
- toolArgs.add(fSource);
- }
-
- if (fUse)
- toolArgs.add("-use"); //$NON-NLS-1$
- if (fVersion)
- toolArgs.add("-version"); //$NON-NLS-1$
- if (fAuthor)
- toolArgs.add("-author"); //$NON-NLS-1$
- if (fNonavbar)
- toolArgs.add("-nonavbar"); //$NON-NLS-1$
- if (fNoindex)
- toolArgs.add("-noindex"); //$NON-NLS-1$
- if (fNotree)
- toolArgs.add("-notree"); //$NON-NLS-1$
- if (fNodeprecated)
- toolArgs.add("-nodeprecated"); //$NON-NLS-1$
- if (fNoDeprecatedlist)
- toolArgs.add("-nodeprecatedlist"); //$NON-NLS-1$
- if (fSplitindex)
- toolArgs.add("-splitindex"); //$NON-NLS-1$
-
- if (fTitle.length() != 0) {
- toolArgs.add("-doctitle"); //$NON-NLS-1$
- toolArgs.add(fTitle);
- }
-
-
- if (fStylesheet.length() != 0) {
- toolArgs.add("-stylesheetfile"); //$NON-NLS-1$
- toolArgs.add(fStylesheet);
- }
-
- for (int i= 0; i < fHRefs.length; i++) {
- toolArgs.add("-link"); //$NON-NLS-1$
- toolArgs.add(fHRefs[i]);
- }
-
- } //end standard options
-
- if (fAdditionalParams.length() + fVMParams.length() != 0) {
- ExecutionArguments tokens= new ExecutionArguments(fVMParams, fAdditionalParams);
- String[] vmArgsArray= tokens.getVMArgumentsArray();
- for (int i= 0; i < vmArgsArray.length; i++) {
- vmArgs.add(vmArgsArray[i]);
- }
- String[] argsArray= tokens.getProgramArgumentsArray();
- for (int i= 0; i < argsArray.length; i++) {
- toolArgs.add(argsArray[i]);
- }
- }
- addProxyOptions(vmArgs);
-
- if (fOverview.length() != 0) {
- toolArgs.add("-overview"); //$NON-NLS-1$
- toolArgs.add(fOverview);
- }
-
- for (int i= 0; i < fSelectedElements.length; i++) {
- IJavaScriptElement curr= fSelectedElements[i];
- if (curr instanceof IPackageFragment) {
- toolArgs.add(curr.getElementName());
- } else if (curr instanceof IJavaScriptUnit) {
- // Since the Javadoc tool is running locally we can only create
- // Javadoc for local resources. So using the location is fine here.
- IPath p= curr.getResource().getLocation();
- if (p != null) {
- toolArgs.add(p.toOSString());
- } else {
- String message= JavadocExportMessages.JavadocOptionsManager_status_non_local;
- status.add(new StatusInfo(IStatus.WARNING, Messages.format(message, curr.getPath().makeRelative().toString())));
- }
- }
- }
- return status;
- }
-
- private void addProxyOptions(List vmOptions) {
- // bug 74132
- String hostPrefix= "-J-Dhttp.proxyHost="; //$NON-NLS-1$
- String portPrefix= "-J-Dhttp.proxyPort="; //$NON-NLS-1$
- for (int i= 0; i < vmOptions.size(); i++) {
- String curr= (String) vmOptions.get(i);
- if (curr.startsWith(hostPrefix) || curr.startsWith(portPrefix)) {
- return;
- }
- }
- String proxyHost= System.getProperty("http.proxyHost"); //$NON-NLS-1$
- if (proxyHost != null) {
- vmOptions.add(hostPrefix + proxyHost);
- }
-
- String proxyPort= System.getProperty("http.proxyPort"); //$NON-NLS-1$
- if (proxyPort != null) {
- vmOptions.add(portPrefix + proxyPort);
- }
- }
-
-
- public File createXML(IJavaScriptProject[] projects) throws CoreException {
- FileOutputStream objectStreamOutput= null;
- //@change
- //for now only writing ant files for single project selection
- try {
- if (fAntpath.length() > 0) {
- File file= new File(fAntpath);
-
- String encoding= "UTF-8"; //$NON-NLS-1$
- IContentType type= Platform.getContentTypeManager().getContentType("org.eclipse.ant.core.antBuildFile"); //$NON-NLS-1$
- if (type != null)
- encoding= type.getDefaultCharset();
- IPath filePath= Path.fromOSString(fAntpath);
- IPath directoryPath= filePath.removeLastSegments(1);
-
- IPath basePath= null;
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- if (root.findFilesForLocation(filePath).length > 0) {
- basePath= directoryPath; // only do relative path if ant file is stored in the workspace
- }
-
- directoryPath.toFile().mkdirs();
-
- objectStreamOutput= new FileOutputStream(file);
- JavadocWriter writer= new JavadocWriter(objectStreamOutput, encoding, basePath, projects);
- writer.writeXML(this);
- return file;
- }
- } catch (IOException e) {
- String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
- } catch (ParserConfigurationException e) {
- String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
- } catch (TransformerException e) {
- String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
- } finally {
- if (objectStreamOutput != null) {
- try {
- objectStreamOutput.close();
- } catch (IOException e) {
- }
- }
- }
- return null;
- }
-
- public void updateDialogSettings(IDialogSettings dialogSettings, IJavaScriptProject[] checkedProjects) {
- IDialogSettings settings= dialogSettings.addNewSection(SECTION_JAVADOC);
-
- settings.put(JAVADOC_COMMAND_HISTORY, flatStringList(fJavadocCommandHistory));
- if (fJavadocCommandHistory.length > 0) {
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- store.setValue(PreferenceConstants.JAVADOC_COMMAND, fJavadocCommandHistory[0]);
- }
-
-
- settings.put(FROMSTANDARD, fFromStandard);
-
- settings.put(DOCLETNAME, fDocletname);
- settings.put(DOCLETPATH, fDocletpath);
-
- settings.put(VISIBILITY, fAccess);
-
- settings.put(USE, fUse);
- settings.put(AUTHOR, fAuthor);
- settings.put(VERSION, fVersion);
- settings.put(NODEPRECATED, fNodeprecated);
- settings.put(NODEPRECATEDLIST, fNoDeprecatedlist);
- settings.put(SPLITINDEX, fSplitindex);
- settings.put(NOINDEX, fNoindex);
- settings.put(NOTREE, fNotree);
- settings.put(NONAVBAR, fNonavbar);
- settings.put(OPENINBROWSER, fOpenInBrowser);
- settings.put(SOURCE, fSource);
-
- if (fAntpath.length() != 0)
- settings.put(ANTPATH, fAntpath);
- if (fDestination.length() != 0)
- settings.put(DESTINATION, fDestination);
- if (fAdditionalParams.length() != 0)
- settings.put(EXTRAOPTIONS, fAdditionalParams);
- if (fVMParams.length() != 0)
- settings.put(VMOPTIONS, fVMParams);
- if (fOverview.length() != 0)
- settings.put(OVERVIEW, fOverview);
- if (fStylesheet.length() != 0)
- settings.put(STYLESHEETFILE, fStylesheet);
- if (fTitle.length() != 0)
- settings.put(TITLE, fTitle);
-
- if (checkedProjects.length == 1) {
- updateRecentSettings(checkedProjects[0]);
- }
- getRecentSettings().store(settings);
- }
-
- public void setJavadocCommandHistory(String[] javadocCommandHistory) {
- fJavadocCommandHistory= javadocCommandHistory;
- }
-
- public void setAccess(String access) {
- fAccess= access;
- }
- public void setDestination(String destination) {
- fDestination= destination;
- }
-
- public void setDocletPath(String docletpath) {
- fDocletpath= docletpath;
- }
-
- public void setDocletName(String docletname) {
- fDocletname= docletname;
- }
-
- public void setStyleSheet(String stylesheet) {
- fStylesheet= stylesheet;
- }
-
- public void setOverview(String overview) {
- fOverview= overview;
- }
-
- public void setAdditionalParams(String params) {
- fAdditionalParams= params;
- }
-
- public void setVMParams(String params) {
- fVMParams= params;
- }
-
- public void setGeneralAntpath(String antpath) {
- fAntpath= antpath;
- }
- public void setClasspath(IPath[] classpath) {
- fClasspath= classpath;
- }
-
- public void setSourcepath(IPath[] sourcepath) {
- fSourcepath= sourcepath;
- }
-
- public void setSelectedElements(IJavaScriptElement[] elements) {
- fSelectedElements= elements;
- }
-
- public void setFromStandard(boolean fromStandard) {
- fFromStandard= fromStandard;
- }
-
- public void setTitle(String title) {
- fTitle= title;
- }
-
- public void setOpenInBrowser(boolean openInBrowser) {
- fOpenInBrowser= openInBrowser;
- }
-
- public void setHRefs(String[] hrefs) {
- fHRefs= hrefs;
- }
-
- public void setBoolean(String flag, boolean value) {
-
- if (flag.equals(AUTHOR))
- fAuthor= value;
- else if (flag.equals(USE))
- fUse= value;
- else if (flag.equals(VERSION))
- fVersion= value;
- else if (flag.equals(NODEPRECATED))
- fNodeprecated= value;
- else if (flag.equals(NODEPRECATEDLIST))
- fNoDeprecatedlist= value;
- else if (flag.equals(NOINDEX))
- fNoindex= value;
- else if (flag.equals(NOTREE))
- fNotree= value;
- else if (flag.equals(SPLITINDEX))
- fSplitindex= value;
- else if (flag.equals(NONAVBAR))
- fNonavbar= value;
- }
-
- public void setSource(String source) {
- fSource= source;
- }
-
- public String getSource() {
- return fSource;
- }
-
- private IJavaScriptElement[] getInitialElementsFromSelection(List candidates) {
- ArrayList res= new ArrayList();
- for (int i= 0; i < candidates.size(); i++) {
- try {
- IJavaScriptElement elem= getSelectableJavaElement(candidates.get(i));
- if (elem != null) {
- res.add(elem);
- }
- } catch (JavaScriptModelException ignore) {
- // ignore this
- }
- }
- return (IJavaScriptElement[]) res.toArray(new IJavaScriptElement[res.size()]);
- }
-
- private IJavaScriptElement getSelectableJavaElement(Object obj) throws JavaScriptModelException {
- IJavaScriptElement je= null;
- if (obj instanceof IAdaptable) {
- je= (IJavaScriptElement) ((IAdaptable) obj).getAdapter(IJavaScriptElement.class);
- }
-
- if (je != null) {
- switch (je.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_MODEL :
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- case IJavaScriptElement.CLASS_FILE :
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- if (containsCompilationUnits((IPackageFragmentRoot) je)) {
- return je;
- }
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- if (containsCompilationUnits((IPackageFragment) je)) {
- return je;
- }
- break;
- default :
- IJavaScriptUnit cu= (IJavaScriptUnit) je.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- return cu;
- }
- }
- IJavaScriptProject project= je.getJavaScriptProject();
- if (isValidProject(project))
- return project;
- }
-
- return null;
- }
-
- private boolean isValidProject(IJavaScriptProject project) throws JavaScriptModelException {
- if (project != null && project.exists() && project.isOpen()) {
- return true;
- }
- return false;
- }
-
- private boolean containsCompilationUnits(IPackageFragmentRoot root) throws JavaScriptModelException {
- if (root.getKind() != IPackageFragmentRoot.K_SOURCE) {
- return false;
- }
-
- IJavaScriptElement[] elements= root.getChildren();
- for (int i= 0; i < elements.length; i++) {
- if (elements[i] instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment) elements[i];
- if (containsCompilationUnits(fragment)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean containsCompilationUnits(IPackageFragment pack) throws JavaScriptModelException {
- return pack.getJavaScriptUnits().length > 0;
- }
-
- public RecentSettingsStore getRecentSettings() {
- return fRecentSettings;
- }
-
- /**
- * @param project
- */
- public void updateRecentSettings(IJavaScriptProject project) {
- fRecentSettings.setProjectSettings(project, fDestination, fAntpath, fHRefs);
- }
-
-
- private static String initJavadocCommandDefault() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- String cmd= store.getString(PreferenceConstants.JAVADOC_COMMAND); // old location
- if (cmd != null && cmd.length() > 0) {
- store.setToDefault(PreferenceConstants.JAVADOC_COMMAND);
- return cmd;
- }
-
- File file= findJavaDocCommand();
- if (file != null) {
- return file.getPath();
- }
- return ""; //$NON-NLS-1$
- }
-
-
- private static File findJavaDocCommand() {
- IVMInstall install= JavaRuntime.getDefaultVMInstall();
- if (install != null) {
- File res= getCommand(install);
- if (res != null) {
- return res;
- }
- }
-
- IVMInstallType[] jreTypes= JavaRuntime.getVMInstallTypes();
- for (int i= 0; i < jreTypes.length; i++) {
- IVMInstallType jreType= jreTypes[i];
- IVMInstall[] installs= jreType.getVMInstalls();
- for (int k= 0; k < installs.length; k++) {
- File res= getCommand(installs[k]);
- if (res != null) {
- return res;
- }
- }
- }
- return null;
- }
-
- private static File getCommand(IVMInstall install) {
- File installLocation= install.getInstallLocation();
- if (installLocation != null) {
- File javaDocCommand= new File(installLocation, "bin/javadoc"); //$NON-NLS-1$
- if (javaDocCommand.isFile()) {
- return javaDocCommand;
- }
- javaDocCommand= new File(installLocation, "bin/javadoc.exe"); //$NON-NLS-1$
- if (javaDocCommand.isFile()) {
- return javaDocCommand;
- }
- }
- return null;
- }
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocProjectContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocProjectContentProvider.java
deleted file mode 100644
index 3e996b0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocProjectContentProvider.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class JavadocProjectContentProvider implements ITreeContentProvider {
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- try {
- if (parentElement instanceof IJavaScriptProject) {
- IJavaScriptProject project= (IJavaScriptProject) parentElement;
- return getPackageFragmentRoots(project);
- } else if (parentElement instanceof IPackageFragmentRoot) {
- return getPackageFragments((IPackageFragmentRoot) parentElement);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return new Object[0];
- }
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- try {
- return JavaScriptCore.create(root).getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return new Object[0];
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
-
- IJavaScriptElement parent= ((IJavaScriptElement)element).getParent();
- if (parent instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
- if (root.getPath().equals(root.getJavaScriptProject().getProject().getFullPath())) {
- return root.getJavaScriptProject();
- }
- }
- return parent;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return (getChildren(element).length > 0);
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- private Object[] getPackageFragmentRoots(IJavaScriptProject project) throws JavaScriptModelException {
- ArrayList result= new ArrayList();
-
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- if (root.getPath().equals(root.getJavaScriptProject().getPath())) {
- Object[] packageFragments= getPackageFragments(root);
- for (int k= 0; k < packageFragments.length; k++) {
- result.add(packageFragments[k]);
- }
- } else {
- result.add(root);
- }
- }
- }
- return result.toArray();
- }
-
- private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaScriptModelException {
- ArrayList packageFragments= new ArrayList();
-
- IJavaScriptElement[] children= root.getChildren();
- for (int i= 0; i < children.length; i++) {
- if (((IPackageFragment) children[i]).containsJavaResources())
- packageFragments.add(children[i]);
- }
- return packageFragments.toArray();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocReader.java
deleted file mode 100644
index 180bc2b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocReader.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.eclipse.core.runtime.Assert;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-
-/**
- * Reads data from an InputStream and returns a JarPackage
- */
-public class JavadocReader extends Object {
-
- private InputStream fInputStream;
-
- /**
- * Reads a Javadoc Ant Script from the underlying stream.
- * It is the client's responsibility to close the stream.
- */
- public JavadocReader(InputStream inputStream) {
- Assert.isNotNull(inputStream);
- fInputStream= new BufferedInputStream(inputStream);
- }
-
- /**
- * Closes this stream.
- * It is the clients responsibility to close the stream.
- *
- * @exception IOException
- */
- public void close() throws IOException {
- if (fInputStream != null)
- fInputStream.close();
- }
-
- public Element readXML() throws IOException, SAXException {
-
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- DocumentBuilder parser= null;
- try {
- parser= factory.newDocumentBuilder();
- } catch (ParserConfigurationException ex) {
- throw new IOException(ex.getMessage());
- } finally {
- // Note: Above code is OK since clients are responsible to close the stream
- }
-
- //find the project associated with the ant script
- Element xmlJavadocDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
-
- NodeList targets= xmlJavadocDesc.getChildNodes();
-
- for (int i= 0; i < targets.getLength(); i++) {
- Node target= targets.item(i);
-
- //look through the XML file for the javadoc task
- if (target.getNodeName().equals("target")) { //$NON-NLS-1$
- NodeList children= target.getChildNodes();
- for (int j= 0; j < children.getLength(); j++) {
- Node child= children.item(j);
- if (child.getNodeName().equals("javadoc") && (child.getNodeType() == Node.ELEMENT_NODE)) { //$NON-NLS-1$
- return (Element) child;
- }
- }
- }
-
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java
deleted file mode 100644
index 83e5fa8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-public class JavadocSpecificsWizardPage extends JavadocWizardPage {
-
- private Button fAntBrowseButton;
- private Button fCheckbrowser;
- private Text fAntText;
- private Button fOverViewButton;
- private Button fOverViewBrowseButton;
- private Button fAntButton;
-// private Combo fSourceCombo;
-
- private Composite fLowerComposite;
- private Text fOverViewText;
- private Text fExtraOptionsText;
- private Text fVMOptionsText;
-
- private StatusInfo fOverviewStatus;
- private StatusInfo fAntStatus;
-
- private JavadocTreeWizardPage fFirstPage;
-
- private JavadocOptionsManager fStore;
-
- private final int OVERVIEWSTATUS= 1;
- private final int ANTSTATUS= 2;
-
- protected JavadocSpecificsWizardPage(String pageName, JavadocTreeWizardPage firstPage, JavadocOptionsManager store) {
- super(pageName);
- setDescription(JavadocExportMessages.JavadocSpecificsWizardPage_description);
-
- fStore= store;
-
- fOverviewStatus= new StatusInfo();
- fAntStatus= new StatusInfo();
- fFirstPage= firstPage;
- }
-
- /*
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- fLowerComposite= new Composite(parent, SWT.NONE);
- fLowerComposite.setLayoutData(createGridData(GridData.FILL_BOTH, 1, 0));
-
- GridLayout layout= createGridLayout(3);
- layout.marginHeight= 0;
- fLowerComposite.setLayout(layout);
-
- createExtraOptionsGroup(fLowerComposite);
- createAntGroup(fLowerComposite);
-
- setControl(fLowerComposite);
- Dialog.applyDialogFont(fLowerComposite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fLowerComposite, IJavaHelpContextIds.JAVADOC_SPECIFICS_PAGE);
-
- } //end method createControl
-
- private void createExtraOptionsGroup(Composite composite) {
- Composite c= new Composite(composite, SWT.NONE);
- c.setLayout(createGridLayout(3));
- c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0));
- ((GridLayout) c.getLayout()).marginWidth= 0;
-
- fOverViewButton= createButton(c, SWT.CHECK, JavadocExportMessages.JavadocSpecificsWizardPage_overviewbutton_label, createGridData(1));
- fOverViewText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- //there really aught to be a way to specify this
- ((GridData) fOverViewText.getLayoutData()).widthHint= 200;
- fOverViewBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.JavadocSpecificsWizardPage_overviewbrowse_label, createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0));
- SWTUtil.setButtonDimensionHint(fOverViewBrowseButton);
-
- String str= fStore.getOverview();
- if (str.length() == 0) {
- //default
- fOverViewText.setEnabled(false);
- fOverViewBrowseButton.setEnabled(false);
- } else {
- fOverViewButton.setSelection(true);
- fOverViewText.setText(str);
- }
-
- createLabel(composite, SWT.NONE, JavadocExportMessages.JavadocSpecificsWizardPage_vmoptionsfield_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 3, 0));
- fVMOptionsText= createText(composite, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 3, 0));
- fVMOptionsText.setText(fStore.getVMParams());
-
-
- createLabel(composite, SWT.NONE, JavadocExportMessages.JavadocSpecificsWizardPage_extraoptionsfield_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 3, 0));
- fExtraOptionsText= createText(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL, 3, 0));
- //fExtraOptionsText.setSize(convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10));
-
- fExtraOptionsText.setText(fStore.getAdditionalParams());
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false, 3, 1));
- GridLayout layout= new GridLayout(2, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- inner.setLayout(layout);
-
-// createLabel(inner, SWT.NONE, JavadocExportMessages.JavadocSpecificsWizardPage_sourcecompatibility_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, 0));
-//
-// fSourceCombo= createCombo(inner, SWT.NONE, fStore.getSource(), createGridData(1));
-// String[] versions= { "-", "1.3", "1.4", "1.5" };//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$
-// fSourceCombo.setItems(versions);
-// fSourceCombo.setText(fStore.getSource());
-
-
- //Listeners
- fOverViewButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fOverViewBrowseButton, fOverViewText }) {
- public void validate() {
- doValidation(OVERVIEWSTATUS);
- }
- });
-
- fOverViewText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(OVERVIEWSTATUS);
- }
- });
-
- fOverViewBrowseButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- handleFileBrowseButtonPressed(fOverViewText, new String[] { "*.html" }, JavadocExportMessages.JavadocSpecificsWizardPage_overviewbrowsedialog_title); //$NON-NLS-1$
- }
- });
-
- }
-
- private void createAntGroup(Composite composite) {
- Composite c= new Composite(composite, SWT.NONE);
- c.setLayout(createGridLayout(3));
- c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0));
- ((GridLayout) c.getLayout()).marginWidth= 0;
-
- fAntButton= createButton(c, SWT.CHECK, JavadocExportMessages.JavadocSpecificsWizardPage_antscriptbutton_label, createGridData(3));
- createLabel(c, SWT.NONE, JavadocExportMessages.JavadocSpecificsWizardPage_antscripttext_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, 0));
- fAntText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- //there really aught to be a way to specify this
- ((GridData) fAntText.getLayoutData()).widthHint= 200;
-
- fAntText.setText(fStore.getAntpath());
-
- fAntBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.JavadocSpecificsWizardPage_antscriptbrowse_label, createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0));
- SWTUtil.setButtonDimensionHint(fAntBrowseButton);
- fAntText.setEnabled(false);
- fAntBrowseButton.setEnabled(false);
-
- fCheckbrowser= createButton(c, SWT.CHECK, JavadocExportMessages.JavadocSpecificsWizardPage_openbrowserbutton_label, createGridData(3));
- fCheckbrowser.setSelection(fStore.doOpenInBrowser());
-
- fAntButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fAntText, fAntBrowseButton }) {
- public void validate() {
- doValidation(ANTSTATUS);
- }
- });
-
- fAntText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(ANTSTATUS);
- }
- });
-
- fAntBrowseButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- String temp= fAntText.getText();
- IPath path= Path.fromOSString(temp);
- String file= path.lastSegment();
- if (file == null)
- file= "javadoc.xml";//$NON-NLS-1$
- path= path.removeLastSegments(1);
-
- String selected= handleFolderBrowseButtonPressed(path.toOSString(), JavadocExportMessages.JavadocSpecificsWizardPage_antscriptbrowsedialog_title, JavadocExportMessages.JavadocSpecificsWizardPage_antscriptbrowsedialog_label);
-
- path= Path.fromOSString(selected).append(file);
- fAntText.setText(path.toOSString());
-
- }
- });
- } //end method createExtraOptionsGroup
-
- private void doValidation(int val) {
- switch (val) {
-
- case OVERVIEWSTATUS :
- fOverviewStatus= new StatusInfo();
- if (fOverViewButton.getSelection()) {
- String filename= fOverViewText.getText();
- if (filename.length() == 0) {
- fOverviewStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_overviewnotfound_error);
- } else {
- File file= new File(filename);
- String ext= filename.substring(filename.lastIndexOf('.') + 1);
- if (!file.isFile()) {
- fOverviewStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_overviewnotfound_error);
- } else if (!ext.equalsIgnoreCase("html")) { //$NON-NLS-1$
- fOverviewStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_overviewincorrect_error);
- }
- }
- }
- break;
- case ANTSTATUS :
- fAntStatus= new StatusInfo();
- if (fAntButton.getSelection()) {
- String filename= fAntText.getText();
- if (filename.length() == 0) {
- fOverviewStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_antfileincorrect_error);
- } else {
- File file= new File(filename);
- String ext= filename.substring(filename.lastIndexOf('.') + 1);
- if (file.isDirectory() || !(ext.equalsIgnoreCase("xml"))) //$NON-NLS-1$
- fAntStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_antfileincorrect_error);
- else if (file.exists())
- fAntStatus.setWarning(JavadocExportMessages.JavadocSpecificsWizardPage_antfileoverwrite_warning);
- }
- }
- break;
- }
-
- updateStatus(findMostSevereStatus());
-
- }
-
- /*
- * @see JavadocWizardPage#onFinish()
- */
-
- protected void updateStore() {
-
- fStore.setVMParams(fVMOptionsText.getText());
- fStore.setAdditionalParams(fExtraOptionsText.getText());
-
- if (fOverViewText.getEnabled())
- fStore.setOverview(fOverViewText.getText());
- else
- fStore.setOverview(""); //$NON-NLS-1$
-
- //for now if there are multiple then the ant file is not stored for specific projects
- if (fAntText.getEnabled()) {
- fStore.setGeneralAntpath(fAntText.getText());
- }
- fStore.setOpenInBrowser(fCheckbrowser.getSelection());
-// fStore.setSource(fSourceCombo.getText());
-
- }
-
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- doValidation(OVERVIEWSTATUS);
- doValidation(ANTSTATUS);
- fCheckbrowser.setVisible(!fFirstPage.getCustom());
- }
- }
-
- public void init() {
- updateStatus(new StatusInfo());
- }
-
- private IStatus findMostSevereStatus() {
- return StatusUtil.getMostSevere(new IStatus[] { fAntStatus, fOverviewStatus });
- }
-
- public boolean generateAnt() {
- return fAntButton.getSelection();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocStandardWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocStandardWizardPage.java
deleted file mode 100644
index 7f60afc6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocStandardWizardPage.java
+++ /dev/null
@@ -1,573 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavadocConfigurationBlock;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.launching.IRuntimeClasspathEntry;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-
-public class JavadocStandardWizardPage extends JavadocWizardPage {
-
-
- private final int STYLESHEETSTATUS= 1;
- private final int LINK_REFERENCES= 2;
-
- private JavadocOptionsManager fStore;
- private Composite fUpperComposite;
-
- private Group fBasicOptionsGroup;
- private Group fTagsGroup;
-
- private Button fTitleButton;
- private Text fTitleText;
- private Text fStyleSheetText;
- private FlaggedButton fDeprecatedList;
- private FlaggedButton fDeprecatedCheck;
- private FlaggedButton fIndexCheck;
- private FlaggedButton fSeperatedIndexCheck;
- private Button fStyleSheetBrowseButton;
- private Button fStyleSheetButton;
-
- private CheckedListDialogField fListDialogField;
-
- private StatusInfo fStyleSheetStatus;
- private StatusInfo fLinkRefStatus;
-
- private ArrayList fButtonsList;
- private JavadocTreeWizardPage fFirstPage;
-
-
- public JavadocStandardWizardPage(String pageName, JavadocTreeWizardPage firstPage, JavadocOptionsManager store) {
- super(pageName);
- fFirstPage= firstPage;
- setDescription(JavadocExportMessages.JavadocStandardWizardPage_description);
-
- fStore= store;
- fButtonsList= new ArrayList();
- fStyleSheetStatus= new StatusInfo();
- fLinkRefStatus= new StatusInfo();
- }
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
-
- initializeDialogUnits(parent);
-
- fUpperComposite= new Composite(parent, SWT.NONE);
- fUpperComposite.setFont(parent.getFont());
- fUpperComposite.setLayoutData(createGridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL, 1, 0));
-
- GridLayout layout= createGridLayout(4);
- layout.marginHeight= 0;
- fUpperComposite.setLayout(layout);
-
- createBasicOptionsGroup(fUpperComposite);
- createTagOptionsGroup(fUpperComposite);
- createListDialogField(fUpperComposite);
- createStyleSheetGroup(fUpperComposite);
-
- setControl(fUpperComposite);
- Dialog.applyDialogFont(fUpperComposite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fUpperComposite, IJavaHelpContextIds.JAVADOC_STANDARD_PAGE);
- }
- private void createBasicOptionsGroup(Composite composite) {
-
- fTitleButton= createButton(composite, SWT.CHECK, JavadocExportMessages.JavadocStandardWizardPage_titlebutton_label, createGridData(1));
- fTitleText= createText(composite, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 3, 0));
- String text= fStore.getTitle();
- if (!text.equals("")) { //$NON-NLS-1$
- fTitleText.setText(text);
- fTitleButton.setSelection(true);
- } else
- fTitleText.setEnabled(false);
-
- fBasicOptionsGroup= new Group(composite, SWT.SHADOW_ETCHED_IN);
- fBasicOptionsGroup.setLayout(createGridLayout(1));
- fBasicOptionsGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 2, 0));
- fBasicOptionsGroup.setText(JavadocExportMessages.JavadocStandardWizardPage_basicgroup_label);
-
- new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.JavadocStandardWizardPage_usebutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.USE, true);
- new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.JavadocStandardWizardPage_hierarchybutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.NOTREE, false);
- new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.JavadocStandardWizardPage_navigartorbutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.NONAVBAR, false);
-
- fIndexCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.JavadocStandardWizardPage_indexbutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.NOINDEX, false);
-
- fSeperatedIndexCheck= new FlaggedButton(fBasicOptionsGroup, JavadocExportMessages.JavadocStandardWizardPage_seperateindexbutton_label, createGridData(GridData.GRAB_HORIZONTAL, 1, convertWidthInCharsToPixels(3)), fStore.SPLITINDEX, true);
- fSeperatedIndexCheck.getButton().setEnabled(fIndexCheck.getButton().getSelection());
-
- fIndexCheck.getButton().addSelectionListener(new ToggleSelectionAdapter(new Control[] { fSeperatedIndexCheck.getButton()}));
- fTitleButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fTitleText }));
-
- }
-
- private void createTagOptionsGroup(Composite composite) {
- fTagsGroup= new Group(composite, SWT.SHADOW_ETCHED_IN);
- fTagsGroup.setLayout(createGridLayout(1));
- fTagsGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 2, 0));
- fTagsGroup.setText(JavadocExportMessages.JavadocStandardWizardPage_tagsgroup_label);
-
- new FlaggedButton(fTagsGroup, JavadocExportMessages.JavadocStandardWizardPage_authorbutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.AUTHOR, true);
- new FlaggedButton(fTagsGroup, JavadocExportMessages.JavadocStandardWizardPage_versionbutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.VERSION, true);
- fDeprecatedCheck= new FlaggedButton(fTagsGroup, JavadocExportMessages.JavadocStandardWizardPage_deprecatedbutton_label, new GridData(GridData.FILL_HORIZONTAL), fStore.NODEPRECATED, false);
- fDeprecatedList= new FlaggedButton(fTagsGroup, JavadocExportMessages.JavadocStandardWizardPage_deprecatedlistbutton_label, createGridData(GridData.FILL_HORIZONTAL, 1, convertWidthInCharsToPixels(3)), fStore.NODEPRECATEDLIST, false);
- fDeprecatedList.getButton().setEnabled(fDeprecatedCheck.getButton().getSelection());
-
- fDeprecatedCheck.getButton().addSelectionListener(new ToggleSelectionAdapter(new Control[] { fDeprecatedList.getButton()}));
- } //end createTagOptionsGroup
-
- private void createStyleSheetGroup(Composite composite) {
- Composite c= new Composite(composite, SWT.NONE);
- c.setLayout(createGridLayout(3));
- c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 4, 0));
- ((GridLayout) c.getLayout()).marginWidth= 0;
-
- fStyleSheetButton= createButton(c, SWT.CHECK, JavadocExportMessages.JavadocStandardWizardPage_stylesheettext_label, createGridData(1));
- fStyleSheetText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- //there really aught to be a way to specify this
- ((GridData) fStyleSheetText.getLayoutData()).widthHint= 200;
- fStyleSheetBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.JavadocStandardWizardPage_stylesheetbrowsebutton_label, createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0));
- SWTUtil.setButtonDimensionHint(fStyleSheetBrowseButton);
-
- String str= fStore.getStyleSheet();
- if (str.equals("")) { //$NON-NLS-1$
- //default
- fStyleSheetText.setEnabled(false);
- fStyleSheetBrowseButton.setEnabled(false);
- } else {
- fStyleSheetButton.setSelection(true);
- fStyleSheetText.setText(str);
- }
-
- //Listeners
- fStyleSheetButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fStyleSheetText, fStyleSheetBrowseButton }) {
- public void validate() {
- doValidation(STYLESHEETSTATUS);
- }
- });
-
- fStyleSheetText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(STYLESHEETSTATUS);
- }
- });
-
- fStyleSheetBrowseButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- handleFileBrowseButtonPressed(fStyleSheetText, new String[] { "*.css" }, JavadocExportMessages.JavadocSpecificsWizardPage_stylesheetbrowsedialog_title); //$NON-NLS-1$
- }
- });
-
- }
-
- private void createListDialogField(Composite composite) {
- Composite c= new Composite(composite, SWT.NONE);
- c.setFont(composite.getFont());
- c.setLayout(createGridLayout(3));
- c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, 4, 0));
- ((GridLayout) c.getLayout()).marginWidth= 0;
-
- String[] buttonlabels= new String[] { JavadocExportMessages.JavadocStandardWizardPage_selectallbutton_label, JavadocExportMessages.JavadocStandardWizardPage_clearallbutton_label, JavadocExportMessages.JavadocStandardWizardPage_configurebutton_label};
-
- JavadocLinkDialogLabelProvider labelProvider= new JavadocLinkDialogLabelProvider();
-
- ListAdapter adapter= new ListAdapter();
-
- fListDialogField= new CheckedListDialogField(adapter, buttonlabels, labelProvider);
- fListDialogField.setDialogFieldListener(adapter);
- fListDialogField.setCheckAllButtonIndex(0);
- fListDialogField.setUncheckAllButtonIndex(1);
- fListDialogField.setViewerComparator(new ViewerComparator());
-
- createLabel(c, SWT.NONE, JavadocExportMessages.JavadocStandardWizardPage_referencedclasses_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 4, 0));
- fListDialogField.doFillIntoGrid(c, 3);
-
- LayoutUtil.setHorizontalGrabbing(fListDialogField.getListControl(null));
-
- fListDialogField.enableButton(2, false);
- }
-
- private List getCheckedReferences(JavadocLinkRef[] referencesClasses) {
- List checkedElements= new ArrayList();
-
- String hrefs[]= fStore.getHRefs();
- if (hrefs.length > 0) {
- HashSet set= new HashSet();
- for (int i= 0; i < hrefs.length; i++) {
- set.add(hrefs[i]);
- }
- for (int i = 0; i < referencesClasses.length; i++) {
- JavadocLinkRef curr= referencesClasses[i];
- URL url= curr.getURL();
- if (url != null && set.contains(url.toExternalForm())) {
- checkedElements.add(curr);
- }
- }
- }
- return checkedElements;
- }
-
-
-
- /**
- * Returns IJavaProjects and IPaths that will be on the classpath
- */
- private JavadocLinkRef[] getReferencedElements(IJavaScriptProject[] checkedProjects) {
- HashSet result= new HashSet();
- for (int i= 0; i < checkedProjects.length; i++) {
- IJavaScriptProject project= checkedProjects[i];
- try {
- collectReferencedElements(project, result);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- // ignore
- }
- }
- return (JavadocLinkRef[]) result.toArray(new JavadocLinkRef[result.size()]);
- }
-
- private void collectReferencedElements(IJavaScriptProject project, HashSet result) throws CoreException {
- IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(project);
- for (int i= 0; i < unresolved.length; i++) {
- IRuntimeClasspathEntry curr= unresolved[i];
- if (curr.getType() == IRuntimeClasspathEntry.PROJECT) {
- result.add(new JavadocLinkRef(JavaScriptCore.create((IProject) curr.getResource())));
- } else {
- IRuntimeClasspathEntry[] entries= JavaRuntime.resolveRuntimeClasspathEntry(curr, project);
- for (int k = 0; k < entries.length; k++) {
- IRuntimeClasspathEntry entry= entries[k];
- if (entry.getType() == IRuntimeClasspathEntry.PROJECT) {
- result.add(new JavadocLinkRef(JavaScriptCore.create((IProject) entry.getResource())));
- } else if (entry.getType() == IRuntimeClasspathEntry.ARCHIVE) {
- IIncludePathEntry classpathEntry= entry.getClasspathEntry();
- if (classpathEntry != null) {
- IPath containerPath= null;
- if (curr.getType() == IRuntimeClasspathEntry.CONTAINER) {
- containerPath= curr.getPath();
- }
- result.add(new JavadocLinkRef(containerPath, classpathEntry, project));
- }
- }
- }
- }
- }
- }
-
- final void doValidation(int VALIDATE) {
- switch (VALIDATE) {
- case STYLESHEETSTATUS :
- fStyleSheetStatus= new StatusInfo();
- if (fStyleSheetButton.getSelection()) {
- String filename= fStyleSheetText.getText();
- if (filename.length() == 0) {
- fStyleSheetStatus.setError(JavadocExportMessages.JavadocSpecificsWizardPage_overviewnotfound_error);
- } else {
- File file= new File(filename);
- String ext= filename.substring(filename.lastIndexOf('.') + 1);
- if (!file.isFile()) {
- fStyleSheetStatus.setError(JavadocExportMessages.JavadocStandardWizardPage_stylesheetnopath_error);
- } else if (!ext.equalsIgnoreCase("css")) { //$NON-NLS-1$
- fStyleSheetStatus.setError(JavadocExportMessages.JavadocStandardWizardPage_stylesheetnotcss_error);
- }
- }
- }
- break;
- case LINK_REFERENCES:
- fLinkRefStatus= new StatusInfo();
- List list= fListDialogField.getCheckedElements();
- for (int i= 0; i < list.size(); i++) {
- JavadocLinkRef curr= (JavadocLinkRef) list.get(i);
- URL url= curr.getURL();
- if (url == null) {
- fLinkRefStatus.setWarning(JavadocExportMessages.JavadocStandardWizardPage_nolinkref_error);
- break;
- } else if ("jar".equals(url.getProtocol())) { //$NON-NLS-1$
- fLinkRefStatus.setWarning(JavadocExportMessages.JavadocStandardWizardPage_nojarlinkref_error);
- break;
- }
- }
- break;
- }
-
- updateStatus(findMostSevereStatus());
-
- }
-
- private IStatus findMostSevereStatus() {
- return StatusUtil.getMostSevere(new IStatus[] { fStyleSheetStatus, fLinkRefStatus });
- }
-
- public void updateStore() {
-
- if (fTitleButton.getSelection())
- fStore.setTitle(fTitleText.getText());
- else
- fStore.setTitle(""); //$NON-NLS-1$
-
- //don't store the buttons if they are not enabled
- //this will change when there is a single page aimed at the standard doclet
- if (true) {
- Object[] buttons= fButtonsList.toArray();
- for (int i= 0; i < buttons.length; i++) {
- FlaggedButton button= (FlaggedButton) buttons[i];
- if (button.getButton().getEnabled())
- fStore.setBoolean(button.getFlag(), !(button.getButton().getSelection() ^ button.show()));
- else
- fStore.setBoolean(button.getFlag(), false == button.show());
- }
- }
-
- if (fStyleSheetText.getEnabled())
- fStore.setStyleSheet(fStyleSheetText.getText());
- else
- fStore.setStyleSheet(""); //$NON-NLS-1$
-
- fStore.setHRefs(getHRefs());
- }
-
- private String[] getHRefs() {
- HashSet res= new HashSet();
- List checked= fListDialogField.getCheckedElements();
- for (Iterator iterator= checked.iterator(); iterator.hasNext();) {
- JavadocLinkRef element= (JavadocLinkRef) iterator.next();
- URL url= element.getURL();
- if (url != null) {
- res.add(url.toExternalForm());
- }
- }
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- //get the links
-
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- doValidation(STYLESHEETSTATUS);
- updateHRefList(fFirstPage.getCheckedProjects());
- } else {
- fStore.setHRefs(getHRefs());
- }
- }
-
- /**
- * Method will refresh the list of referenced libraries and projects
- * depended on the projects or elements of projects selected in the
- * TreeViewer on the JavadocTreeWizardPage.
- */
- private void updateHRefList(IJavaScriptProject[] checkedProjects) {
- JavadocLinkRef[] res= getReferencedElements(checkedProjects);
- fListDialogField.setElements(Arrays.asList(res));
-
- List checked= getCheckedReferences(res);
- fListDialogField.setCheckedElements(checked);
- }
-
- public void init() {
- updateStatus(new StatusInfo());
- }
-
- protected class FlaggedButton {
-
- private Button fButton;
- private String fFlag;
- private boolean fShowFlag;
-
- public FlaggedButton(Composite composite, String message, GridData gridData, String flag, boolean show) {
- fFlag= flag;
- fShowFlag= show;
- fButton= createButton(composite, SWT.CHECK, message, gridData);
- fButtonsList.add(this);
- setButtonSettings();
- }
-
- public Button getButton() {
- return fButton;
- }
-
- public String getFlag() {
- return fFlag;
- }
- public boolean show() {
- return fShowFlag;
- }
-
- private void setButtonSettings() {
-
- fButton.setSelection(!(fStore.getBoolean(fFlag) ^ fShowFlag));
- }
-
- } //end class FlaggesButton
-
- private class ListAdapter implements IListAdapter, IDialogFieldListener {
-
- /**
- * @see IListAdapter#customButtonPressed(ListDialogField, int)
- */
- public void customButtonPressed(ListDialogField field, int index) {
- if (index == 2)
- doEditButtonPressed();
- }
-
- /**
- * @see IListAdapter#selectionChanged(ListDialogField)
- */
- public void selectionChanged(ListDialogField field) {
- List selection= fListDialogField.getSelectedElements();
- if (selection.size() != 1) {
- fListDialogField.enableButton(2, false);
- } else {
- fListDialogField.enableButton(2, true);
- }
- }
-
- public void doubleClicked(ListDialogField field) {
- doEditButtonPressed();
- }
-
- public void dialogFieldChanged(DialogField field) {
- doValidation(LINK_REFERENCES);
- }
-
- }
-
- /**
- * Method doEditButtonPressed.
- */
- private void doEditButtonPressed() {
-
- List selected= fListDialogField.getSelectedElements();
- if (selected.isEmpty()) {
- return;
- }
- JavadocLinkRef obj= (JavadocLinkRef) selected.get(0);
- if (obj != null) {
- JavadocPropertyDialog jdialog= new JavadocPropertyDialog(getShell(), obj);
- if (jdialog.open() == Window.OK) {
- fListDialogField.refresh();
- }
- }
-
- }
-
- private class JavadocPropertyDialog extends StatusDialog implements IStatusChangeListener {
-
- private JavadocConfigurationBlock fJavadocConfigurationBlock;
- private JavadocLinkRef fElement;
-
- public JavadocPropertyDialog(Shell parent, JavadocLinkRef selection) {
- super(parent);
- setTitle(JavadocExportMessages.JavadocStandardWizardPage_javadocpropertydialog_title);
-
- fElement= selection;
- URL initialLocation= selection.getURL();
- fJavadocConfigurationBlock= new JavadocConfigurationBlock(parent, this, initialLocation, selection.isProjectRef());
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- Control inner= fJavadocConfigurationBlock.createContents(composite);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- applyDialogFont(composite);
- return composite;
- }
-
- public void statusChanged(IStatus status) {
- updateStatus(status);
-
- }
-
- /**
- * @see Dialog#okPressed()
- */
- protected void okPressed() {
- try {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- URL javadocLocation= fJavadocConfigurationBlock.getJavadocLocation();
- fElement.setURL(javadocLocation, monitor);
- }
- };
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(runnable));
-
- } catch (InvocationTargetException e) {
- String title= JavadocExportMessages.JavadocStandardWizardPage_configurecontainer_error_title;
- String message= JavadocExportMessages.JavadocStandardWizardPage_configurecontainer_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- } catch (InterruptedException e) {
- // user cancelled
- }
-
- fListDialogField.refresh();
- doValidation(LINK_REFERENCES);
- super.okPressed();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocTreeWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocTreeWizardPage.java
deleted file mode 100644
index a2bbfe04..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocTreeWizardPage.java
+++ /dev/null
@@ -1,706 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class JavadocTreeWizardPage extends JavadocWizardPage {
-
- private CheckboxTreeAndListGroup fInputGroup;
-
- private Text fDestinationText;
- private Combo fJavadocCommandText;
- private Text fDocletText;
- private Text fDocletTypeText;
- private Button fStandardButton;
- private Button fDestinationBrowserButton;
- private Button fCustomButton;
- private Button fPrivateVisibility;
- private Button fProtectedVisibility;
- private Button fPackageVisibility;
- private Button fPublicVisibility;
- private Label fDocletLabel;
- private Label fDocletTypeLabel;
- private Label fDestinationLabel;
- private CLabel fDescriptionLabel;
-
- private String fVisibilitySelection;
-
- private JavadocOptionsManager fStore;
-
- private StatusInfo fJavadocStatus;
- private StatusInfo fDestinationStatus;
- private StatusInfo fDocletStatus;
- private StatusInfo fTreeStatus;
- private StatusInfo fPreferenceStatus;
- private StatusInfo fWizardStatus;
-
- private final int PREFERENCESTATUS= 0;
- private final int CUSTOMSTATUS= 1;
- private final int STANDARDSTATUS= 2;
- private final int TREESTATUS= 3;
- private final int JAVADOCSTATUS= 4;
-
- /**
- * Constructor for JavadocTreeWizardPage.
- * @param pageName
- */
- protected JavadocTreeWizardPage(String pageName, JavadocOptionsManager store) {
- super(pageName);
- setDescription(JavadocExportMessages.JavadocTreeWizardPage_javadoctreewizardpage_description);
-
- fStore= store;
-
- // Status variables
- fJavadocStatus= new StatusInfo();
- fDestinationStatus= new StatusInfo();
- fDocletStatus= new StatusInfo();
- fTreeStatus= new StatusInfo();
- fPreferenceStatus= new StatusInfo();
- fWizardStatus= store.getWizardStatus();
- }
-
- /*
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- final Composite composite= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 6;
- composite.setLayout(layout);
-
- createJavadocCommandSet(composite);
- createInputGroup(composite);
- createVisibilitySet(composite);
- createOptionsSet(composite);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.JAVADOC_TREE_PAGE);
- }
-
- protected void createJavadocCommandSet(Composite composite) {
-
- final int numColumns= 2;
-
- GridLayout layout= createGridLayout(numColumns);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- Composite group = new Composite(composite, SWT.NONE);
- group.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
- group.setLayout(layout);
-
- createLabel(group, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_javadoccommand_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, numColumns, 0));
- fJavadocCommandText= createCombo(group, SWT.NONE, null, createGridData(GridData.FILL_HORIZONTAL, numColumns - 1, 0));
-
- fJavadocCommandText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(JAVADOCSTATUS);
- }
- });
-
- final Button javadocCommandBrowserButton= createButton(group, SWT.PUSH, JavadocExportMessages.JavadocTreeWizardPage_javadoccommand_button_label, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, 0));
- SWTUtil.setButtonDimensionHint(javadocCommandBrowserButton);
-
- javadocCommandBrowserButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- browseForJavadocCommand();
- }
- });
- }
-
-
-
-
- protected void createInputGroup(Composite composite) {
-
- createLabel(composite, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_checkboxtreeandlistgroup_label, createGridData(6));
- Composite c= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- layout.makeColumnsEqualWidth= true;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- c.setLayout(layout);
- c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
-
- ITreeContentProvider treeContentProvider= new JavadocProjectContentProvider();
- ITreeContentProvider listContentProvider= new JavadocMemberContentProvider();
- fInputGroup= new CheckboxTreeAndListGroup(c, this, treeContentProvider, new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT), listContentProvider, new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT), SWT.NONE, convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10));
-
- fInputGroup.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent e) {
- doValidation(TREESTATUS);
- }
- });
- fInputGroup.setTreeComparator(new JavaScriptElementComparator());
-
- IJavaScriptElement[] elements= fStore.getInitialElements();
- setTreeChecked(elements);
- if (elements.length > 0) {
- fInputGroup.setTreeSelection(new StructuredSelection(elements[0].getJavaScriptProject()));
- }
-
- fInputGroup.aboutToOpen();
- }
-
- private void createVisibilitySet(Composite composite) {
-
- GridLayout visibilityLayout= createGridLayout(4);
- visibilityLayout.marginHeight= 0;
- visibilityLayout.marginWidth= 0;
- Composite visibilityGroup= new Composite(composite, SWT.NONE);
- visibilityGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
- visibilityGroup.setLayout(visibilityLayout);
-
- createLabel(visibilityGroup, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_visibilitygroup_label, createGridData(GridData.FILL_HORIZONTAL, 4, 0));
- fPrivateVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_privatebutton_label, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- fPackageVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_packagebutton_label, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- fProtectedVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_protectedbutton_label, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
- fPublicVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_publicbutton_label, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
-
- fDescriptionLabel= new CLabel(visibilityGroup, SWT.LEFT);
- fDescriptionLabel.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 4, convertWidthInCharsToPixels(3) - 3)); // INDENT of CLabel
-
- fPrivateVisibility.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (((Button) e.widget).getSelection()) {
- fVisibilitySelection= fStore.PRIVATE;
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_privatevisibilitydescription_label);
- }
- }
- });
- fPackageVisibility.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (((Button) e.widget).getSelection()) {
- fVisibilitySelection= fStore.PACKAGE;
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_packagevisibledescription_label);
- }
- }
- });
- fProtectedVisibility.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (((Button) e.widget).getSelection()) {
- fVisibilitySelection= fStore.PROTECTED;
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_protectedvisibilitydescription_label);
- }
- }
- });
-
- fPublicVisibility.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (((Button) e.widget).getSelection()) {
- fVisibilitySelection= fStore.PUBLIC;
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_publicvisibilitydescription_label);
- }
- }
- });
-
- setVisibilitySettings();
-
- }
-
- protected void setVisibilitySettings() {
- fVisibilitySelection= fStore.getAccess();
- fPrivateVisibility.setSelection(fVisibilitySelection.equals(fStore.PRIVATE));
- if (fPrivateVisibility.getSelection())
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_privatevisibilitydescription_label);
-
- fProtectedVisibility.setSelection(fVisibilitySelection.equals(fStore.PROTECTED));
- if (fProtectedVisibility.getSelection())
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_protectedvisibilitydescription_label);
-
- fPackageVisibility.setSelection(fVisibilitySelection.equals(fStore.PACKAGE));
- if (fPackageVisibility.getSelection())
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_packagevisibledescription_label);
-
- fPublicVisibility.setSelection(fVisibilitySelection.equals(fStore.PUBLIC));
- if (fPublicVisibility.getSelection())
- fDescriptionLabel.setText(JavadocExportMessages.JavadocTreeWizardPage_publicvisibilitydescription_label);
- }
-
- private void createOptionsSet(Composite composite) {
-
- final int numColumns= 4;
-
- final GridLayout layout= createGridLayout(numColumns);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- Composite group= new Composite(composite, SWT.NONE);
- group.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
- group.setLayout(layout);
-
- fStandardButton= createButton(group, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_standarddocletbutton_label, createGridData(GridData.HORIZONTAL_ALIGN_FILL, numColumns, 0));
-
- fDestinationLabel= createLabel(group, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_destinationfield_label, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3)));
- fDestinationText= createText(group, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, numColumns - 2, 0));
- ((GridData) fDestinationText.getLayoutData()).widthHint= 0;
- fDestinationText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(STANDARDSTATUS);
- }
- });
-
- fDestinationBrowserButton= createButton(group, SWT.PUSH, JavadocExportMessages.JavadocTreeWizardPage_destinationbrowse_label, createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0));
- SWTUtil.setButtonDimensionHint(fDestinationBrowserButton);
-
- //Option to use custom doclet
- fCustomButton= createButton(group, SWT.RADIO, JavadocExportMessages.JavadocTreeWizardPage_customdocletbutton_label, createGridData(GridData.HORIZONTAL_ALIGN_FILL, numColumns, 0));
-
- //For Entering location of custom doclet
- fDocletTypeLabel= createLabel(group, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_docletnamefield_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, convertWidthInCharsToPixels(3)));
- fDocletTypeText= createText(group, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, numColumns - 1, 0));
- ((GridData) fDocletTypeText.getLayoutData()).widthHint= 0;
-
-
- fDocletTypeText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(CUSTOMSTATUS);
- }
- });
-
- fDocletLabel= createLabel(group, SWT.NONE, JavadocExportMessages.JavadocTreeWizardPage_docletpathfield_label, createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, convertWidthInCharsToPixels(3)));
- fDocletText= createText(group, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, numColumns - 1, 0));
- ((GridData) fDocletText.getLayoutData()).widthHint= 0;
-
- fDocletText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation(CUSTOMSTATUS);
- }
-
- });
-
- //Add Listeners
- fCustomButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }, new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }));
- fCustomButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- doValidation(CUSTOMSTATUS);
- }
- });
- fStandardButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }, new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }));
- fStandardButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- doValidation(STANDARDSTATUS);
- }
- });
- fDestinationBrowserButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- String text= handleFolderBrowseButtonPressed(fDestinationText.getText(), JavadocExportMessages.JavadocTreeWizardPage_destinationbrowsedialog_title,
- JavadocExportMessages.JavadocTreeWizardPage_destinationbrowsedialog_label);
- fDestinationText.setText(text);
- }
- });
-
- setOptionSetSettings();
- }
-
- public boolean getCustom() {
- return fCustomButton.getSelection();
- }
-
- private void setOptionSetSettings() {
-
- if (!fStore.isFromStandard()) {
- fCustomButton.setSelection(true);
- fDocletText.setText(fStore.getDocletPath());
- fDocletTypeText.setText(fStore.getDocletName());
- fDestinationText.setText(fStore.getDestination());
- fDestinationText.setEnabled(false);
- fDestinationBrowserButton.setEnabled(false);
- fDestinationLabel.setEnabled(false);
-
- } else {
- fStandardButton.setSelection(true);
- fDestinationText.setText(fStore.getDestination());
- fDocletText.setText(fStore.getDocletPath());
- fDocletTypeText.setText(fStore.getDocletName());
- fDocletText.setEnabled(false);
- fDocletLabel.setEnabled(false);
- fDocletTypeText.setEnabled(false);
- fDocletTypeLabel.setEnabled(false);
- }
-
- fJavadocCommandText.setItems(fStore.getJavadocCommandHistory());
- fJavadocCommandText.select(0);
- }
-
- /**
- * Receives of list of elements selected by the user and passes them
- * to the CheckedTree. List can contain multiple projects and elements from
- * different projects. If the list of seletected elements is empty a default
- * project is selected.
- */
- private void setTreeChecked(IJavaScriptElement[] sourceElements) {
- for (int i= 0; i < sourceElements.length; i++) {
- IJavaScriptElement curr= sourceElements[i];
- if (curr instanceof IJavaScriptUnit) {
- fInputGroup.initialCheckListItem(curr);
- } else if (curr instanceof IPackageFragment) {
- fInputGroup.initialCheckTreeItem(curr);
- } else if (curr instanceof IJavaScriptProject) {
- fInputGroup.initialCheckTreeItem(curr);
- } else if (curr instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) curr;
- if (!root.isArchive())
- fInputGroup.initialCheckTreeItem(curr);
- }
- }
- }
-
- private IPath[] getSourcePath(IJavaScriptProject[] projects) {
- HashSet res= new HashSet();
- //loops through all projects and gets a list if of their source paths
- for (int k= 0; k < projects.length; k++) {
- IJavaScriptProject iJavaProject= projects[k];
-
- try {
- IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot curr= roots[i];
- if (curr.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IResource resource= curr.getResource();
- if (resource != null) {
- // Using get location is OK here. If the source folder
- // isn't local we can't create Javadoc for it.
- IPath p= resource.getLocation();
- if (p != null) {
- res.add(p);
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return (IPath[]) res.toArray(new IPath[res.size()]);
- }
-
- private IPath[] getClassPath(IJavaScriptProject[] javaProjects) {
- HashSet res= new HashSet();
-
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int j= 0; j < javaProjects.length; j++) {
- IJavaScriptProject curr= javaProjects[j];
- try {
- IPath outputLocation= null;
-
- // Not really clear yet what to do here for EFS. See bug
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=113233.
-
- String[] classPath= JavaRuntime.computeDefaultRuntimeClassPath(curr);
- for (int i= 0; i < classPath.length; i++) {
- IPath path= Path.fromOSString(classPath[i]);
- if (!path.equals(outputLocation)) {
- res.add(path);
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return (IPath[]) res.toArray(new IPath[res.size()]);
- }
-
- /**
- * Gets a list of elements to generated javadoc for from each project.
- * Javadoc can be generated for either a IPackageFragment or a IJavaScriptUnit.
- */
- private IJavaScriptElement[] getSourceElements(IJavaScriptProject[] projects) {
- ArrayList res= new ArrayList();
- try {
- Set allChecked= fInputGroup.getAllCheckedTreeItems();
-
- Set incompletePackages= new HashSet();
- for (int h= 0; h < projects.length; h++) {
- IJavaScriptProject iJavaProject= projects[h];
-
- IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IPath rootLocation= root.getResource().getLocation();
- IJavaScriptElement[] packs= root.getChildren();
- for (int k= 0; k < packs.length; k++) {
- IJavaScriptElement curr= packs[k];
- if (curr.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
- // default packages are always incomplete
- if (curr.getElementName().length() == 0 || !allChecked.contains(curr)
- || fInputGroup.isTreeItemGreyChecked(curr) || !isAccessibleLocation(curr.getResource().getLocation(), rootLocation)) {
- incompletePackages.add(curr.getElementName());
- }
- }
- }
- }
- }
- }
-
- Iterator checkedElements= fInputGroup.getAllCheckedListItems();
- while (checkedElements.hasNext()) {
- Object element= checkedElements.next();
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit) element;
- if (incompletePackages.contains(unit.getParent().getElementName())) {
- res.add(unit);
- }
- }
- }
-
- Set addedPackages= new HashSet();
-
- checkedElements= allChecked.iterator();
- while (checkedElements.hasNext()) {
- Object element= checkedElements.next();
- if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment) element;
- String name= fragment.getElementName();
- if (!incompletePackages.contains(name) && !addedPackages.contains(name)) {
- res.add(fragment);
- addedPackages.add(name);
- }
- }
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return (IJavaScriptElement[]) res.toArray(new IJavaScriptElement[res.size()]);
- }
-
- private boolean isAccessibleLocation(IPath packageLocation, IPath rootLocation) {
- return rootLocation != null && packageLocation != null && rootLocation.isPrefixOf(packageLocation);
- }
-
- protected void updateStore(IJavaScriptProject[] checkedProjects) {
-
- if (fCustomButton.getSelection()) {
- fStore.setDocletName(fDocletTypeText.getText());
- fStore.setDocletPath(fDocletText.getText());
- fStore.setFromStandard(false);
- }
- if (fStandardButton.getSelection()) {
- fStore.setFromStandard(true);
- //the destination used in javadoc generation
- fStore.setDestination(fDestinationText.getText());
- }
-
- fStore.setSourcepath(getSourcePath(checkedProjects));
- fStore.setClasspath(getClassPath(checkedProjects));
- fStore.setAccess(fVisibilitySelection);
- fStore.setSelectedElements(getSourceElements(checkedProjects));
-
- ArrayList commands= new ArrayList();
- commands.add(fJavadocCommandText.getText()); // must be first
- String[] items= fJavadocCommandText.getItems();
- for (int i= 0; i < items.length; i++) {
- String curr= items[i];
- if (!commands.contains(curr)) {
- commands.add(curr);
- }
- }
- fStore.setJavadocCommandHistory((String[]) commands.toArray(new String[commands.size()]));
- }
-
- public IJavaScriptProject[] getCheckedProjects() {
- ArrayList res= new ArrayList();
- TreeItem[] treeItems= fInputGroup.getTree().getItems();
- for (int i= 0; i < treeItems.length; i++) {
- if (treeItems[i].getChecked()) {
- Object curr= treeItems[i].getData();
- if (curr instanceof IJavaScriptProject) {
- res.add(curr);
- }
- }
- }
- return (IJavaScriptProject[]) res.toArray(new IJavaScriptProject[res.size()]);
- }
-
- protected void doValidation(int validate) {
-
-
- switch (validate) {
- case PREFERENCESTATUS :
- fPreferenceStatus= new StatusInfo();
- fDocletStatus= new StatusInfo();
- updateStatus(findMostSevereStatus());
- break;
- case CUSTOMSTATUS :
-
- if (fCustomButton.getSelection()) {
- fDestinationStatus= new StatusInfo();
- fDocletStatus= new StatusInfo();
- String doclet= fDocletTypeText.getText();
- String docletPath= fDocletText.getText();
- if (doclet.length() == 0) {
- fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_nodocletname_error);
-
- } else if (JavaScriptConventions.validateJavaScriptTypeName(doclet).matches(IStatus.ERROR)) {
- fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invaliddocletname_error);
- } else if ((docletPath.length() == 0) || !validDocletPath(docletPath)) {
- fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invaliddocletpath_error);
- }
- updateStatus(findMostSevereStatus());
- }
- break;
-
- case STANDARDSTATUS :
- if (fStandardButton.getSelection()) {
- fDestinationStatus= new StatusInfo();
- fDocletStatus= new StatusInfo();
- String dest= fDestinationText.getText();
- if (dest.length() == 0) {
- fDestinationStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_nodestination_error);
- }
- File file= new File(dest);
- if (!Path.ROOT.isValidPath(dest) || file.isFile()) {
- fDestinationStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invaliddestination_error);
- }
- if (new File(dest, "package-list").exists() || new File(dest, "index.html").exists()) //$NON-NLS-1$//$NON-NLS-2$
- fDestinationStatus.setWarning(JavadocExportMessages.JavadocTreeWizardPage_warning_mayoverwritefiles);
- updateStatus(findMostSevereStatus());
- }
- break;
-
- case TREESTATUS :
-
- fTreeStatus= new StatusInfo();
-
- if (!fInputGroup.getAllCheckedListItems().hasNext())
- fTreeStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invalidtreeselection_error);
- updateStatus(findMostSevereStatus());
-
- break;
-
- case JAVADOCSTATUS:
- fJavadocStatus= new StatusInfo();
- String text= fJavadocCommandText.getText();
- if (text.length() == 0) {
- fJavadocStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_javadoccmd_error_enterpath);
- } else {
- File file= new File(text);
- if (!file.isFile()) {
- fJavadocStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_javadoccmd_error_notexists);
- }
- }
- updateStatus(findMostSevereStatus());
- break;
- } //end switch
-
-
- }
-
- protected void browseForJavadocCommand() {
- FileDialog dialog= new FileDialog(getShell());
- dialog.setText(JavadocExportMessages.JavadocTreeWizardPage_javadoccmd_dialog_title);
- String dirName= fJavadocCommandText.getText();
- dialog.setFileName(dirName);
- String selectedDirectory= dialog.open();
- if (selectedDirectory != null) {
- ArrayList newItems= new ArrayList();
- String[] items= fJavadocCommandText.getItems();
- newItems.add(selectedDirectory);
- for (int i= 0; i < items.length && newItems.size() < 5; i++) { // only keep the last 5 entries
- String curr= items[i];
- if (!newItems.contains(curr)) {
- newItems.add(curr);
- }
- }
- fJavadocCommandText.setItems((String[]) newItems.toArray(new String[newItems.size()]));
- fJavadocCommandText.select(0);
- }
- }
-
-
- private boolean validDocletPath(String docletPath) {
- StringTokenizer tokens= new StringTokenizer(docletPath, ";"); //$NON-NLS-1$
- while (tokens.hasMoreTokens()) {
- File file= new File(tokens.nextToken());
- if (!file.exists())
- return false;
- }
- return true;
- }
-
- /**
- * Finds the most severe error (if there is one)
- */
- private IStatus findMostSevereStatus() {
- return StatusUtil.getMostSevere(new IStatus[] { fJavadocStatus, fPreferenceStatus, fDestinationStatus, fDocletStatus, fTreeStatus, fWizardStatus });
- }
-
- public void init() {
- updateStatus(new StatusInfo());
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- doValidation(STANDARDSTATUS);
- doValidation(CUSTOMSTATUS);
- doValidation(TREESTATUS);
- doValidation(PREFERENCESTATUS);
- doValidation(JAVADOCSTATUS);
- }
- super.setVisible(visible);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizard.java
deleted file mode 100644
index 397a780a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizard.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids <sdavids@gmx.de> bug 38692
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.debug.core.DebugEvent;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.IDebugEventSetListener;
-import org.eclipse.debug.core.ILaunch;
-import org.eclipse.debug.core.ILaunchConfigurationType;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.core.Launch;
-import org.eclipse.debug.core.model.IProcess;
-import org.eclipse.debug.ui.IDebugUIConstants;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IExportWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.OpenBrowserUtil;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavadocWizard extends Wizard implements IExportWizard {
-
- private JavadocTreeWizardPage fJTWPage;
- private JavadocSpecificsWizardPage fJSWPage;
- private JavadocStandardWizardPage fJSpWPage;
-
- private IPath fDestination;
-
- private boolean fWriteCustom;
- private boolean fOpenInBrowser;
-
- private final String TREE_PAGE_DESC= "JavadocTreePage"; //$NON-NLS-1$
- private final String SPECIFICS_PAGE_DESC= "JavadocSpecificsPage"; //$NON-NLS-1$
- private final String STANDARD_PAGE_DESC= "JavadocStandardPage"; //$NON-NLS-1$
-
- private final int YES= 0;
- private final int YES_TO_ALL= 1;
- private final int NO= 2;
- private final int NO_TO_ALL= 3;
- private final String JAVADOC_ANT_INFORMATION_DIALOG= "javadocAntInformationDialog";//$NON-NLS-1$
-
-
- private JavadocOptionsManager fStore;
- private IWorkspaceRoot fRoot;
-
- private IFile fXmlJavadocFile;
-
- private static final String ID_JAVADOC_PROCESS_TYPE= "org.eclipse.wst.jsdt.ui.javadocProcess"; //$NON-NLS-1$
-
- public static void openJavadocWizard(JavadocWizard wizard, Shell shell, IStructuredSelection selection ) {
- wizard.init(PlatformUI.getWorkbench(), selection);
-
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(100), converter.convertHeightInCharsToPixels(20));
- dialog.open();
- }
-
-
- public JavadocWizard() {
- this(null);
- }
-
- public JavadocWizard(IFile xmlJavadocFile) {
- super();
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXPORT_JAVADOC);
- setWindowTitle(JavadocExportMessages.JavadocWizard_javadocwizard_title);
-
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
-
- fRoot= ResourcesPlugin.getWorkspace().getRoot();
- fXmlJavadocFile= xmlJavadocFile;
-
- fWriteCustom= false;
- }
-
- /*
- * @see IWizard#performFinish()
- */
- public boolean performFinish() {
-
- IJavaScriptProject[] checkedProjects= fJTWPage.getCheckedProjects();
- updateStore(checkedProjects);
-
- fStore.updateDialogSettings(getDialogSettings(), checkedProjects);
-
- // Wizard should not run with dirty editors
- if (!new RefactoringSaveHelper(RefactoringSaveHelper.SAVE_ALL_ALWAYS_ASK).saveEditors(getShell())) {
- return false;
- }
-
- fDestination= Path.fromOSString(fStore.getDestination());
- fDestination.toFile().mkdirs();
-
- fOpenInBrowser= fStore.doOpenInBrowser();
-
- //Ask if you wish to set the javadoc location for the projects (all) to
- //the location of the newly generated javadoc
- if (fStore.isFromStandard()) {
- try {
-
- URL newURL= fDestination.toFile().toURL();
- List projs= new ArrayList();
- //get javadoc locations for all projects
- for (int i= 0; i < checkedProjects.length; i++) {
- IJavaScriptProject curr= checkedProjects[i];
- URL currURL= JavaScriptUI.getProjectJSdocLocation(curr);
- if (!newURL.equals(currURL)) { // currURL can be null
- //if not all projects have the same javadoc location ask if you want to change
- //them to have the same javadoc location
- projs.add(curr);
- }
- }
- if (!projs.isEmpty()) {
- setAllJavadocLocations((IJavaScriptProject[]) projs.toArray(new IJavaScriptProject[projs.size()]), newURL);
- }
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- if (fJSWPage.generateAnt()) {
- //@Improve: make a better message
- OptionalMessageDialog.open(JAVADOC_ANT_INFORMATION_DIALOG, getShell(), JavadocExportMessages.JavadocWizard_antInformationDialog_title, null, JavadocExportMessages.JavadocWizard_antInformationDialog_message, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0);
- try {
- File file= fStore.createXML(checkedProjects);
- if (file != null) {
- IFile[] files= fRoot.findFilesForLocation(Path.fromOSString(file.getPath()));
- if (files != null) {
- for (int i= 0; i < files.length; i++) {
- files[i].refreshLocal(IResource.DEPTH_ONE, null);
- }
- }
- }
-
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(),JavadocExportMessages.JavadocWizard_error_writeANT_title, JavadocExportMessages.JavadocWizard_error_writeANT_message);
- }
- }
-
- if (!executeJavadocGeneration())
- return false;
-
- return true;
- }
-
- private void updateStore(IJavaScriptProject[] checkedProjects) {
- //writes the new settings to store
- fJTWPage.updateStore(checkedProjects);
- if (!fJTWPage.getCustom())
- fJSpWPage.updateStore();
- fJSWPage.updateStore();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.IWizard#performCancel()
- */
- public boolean performCancel() {
-
- IJavaScriptProject[] checkedProjects= fJTWPage.getCheckedProjects();
- updateStore(checkedProjects);
-
- //If the wizard was not launched from an ant file store the settings
- if (fXmlJavadocFile == null) {
- fStore.updateDialogSettings(getDialogSettings(), checkedProjects);
- }
- return super.performCancel();
- }
-
- private void setAllJavadocLocations(IJavaScriptProject[] projects, URL newURL) {
- Shell shell= getShell();
- String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL };
-
- for (int j= 0; j < projects.length; j++) {
- IJavaScriptProject iJavaProject= projects[j];
- String message= Messages.format(JavadocExportMessages.JavadocWizard_updatejavadoclocation_message, new String[] { iJavaProject.getElementName(), fDestination.toOSString()});
- MessageDialog dialog= new MessageDialog(shell, JavadocExportMessages.JavadocWizard_updatejavadocdialog_label, null, message, MessageDialog.QUESTION, buttonlabels, 1);
-
- switch (dialog.open()) {
- case YES :
- JavaScriptUI.setProjectJSdocLocation(iJavaProject, newURL);
- break;
- case YES_TO_ALL :
- for (int i= j; i < projects.length; i++) {
- iJavaProject= projects[i];
- JavaScriptUI.setProjectJSdocLocation(iJavaProject, newURL);
- j++;
- }
- break;
- case NO_TO_ALL :
- j= projects.length;
- break;
- case NO :
- default :
- break;
- }
- }
- }
-
- private boolean executeJavadocGeneration() {
- Process process= null;
- try {
- ArrayList vmArgs= new ArrayList();
- ArrayList progArgs= new ArrayList();
-
- IStatus status= fStore.getArgumentArray(vmArgs, progArgs);
- if (!status.isOK()) {
- ErrorDialog.openError(getShell(), JavadocExportMessages.JavadocWizard_error_title, JavadocExportMessages.JavadocWizard_warning_starting_message, status);
- }
-
- File file= File.createTempFile("javadoc-arguments", ".tmp"); //$NON-NLS-1$//$NON-NLS-2$
- vmArgs.add('@' + file.getAbsolutePath());
-
- FileWriter writer= new FileWriter(file);
- try {
- for (int i= 0; i < progArgs.size(); i++) {
- String curr= (String) progArgs.get(i);
- curr= checkForSpaces(curr);
-
- writer.write(curr);
- writer.write(' ');
- }
- } finally {
- writer.close();
- }
-
- String[] args= (String[]) vmArgs.toArray(new String[vmArgs.size()]);
- process= Runtime.getRuntime().exec(args);
- if (process != null) {
- // construct a formatted command line for the process properties
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < args.length; i++) {
- buf.append(args[i]);
- buf.append(' ');
- }
-
- IDebugEventSetListener listener= new JavadocDebugEventListener(getShell().getDisplay(), file);
- DebugPlugin.getDefault().addDebugEventListener(listener);
-
- ILaunchConfigurationWorkingCopy wc= null;
- try {
- ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
- String name= JavadocExportMessages.JavadocWizard_launchconfig_name;
- wc= lcType.newInstance(null, name);
- wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
-
- ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null);
- IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.JavadocWizard_javadocprocess_label);
- iprocess.setAttribute(IProcess.ATTR_CMDLINE, buf.toString());
- iprocess.setAttribute(IProcess.ATTR_PROCESS_TYPE, ID_JAVADOC_PROCESS_TYPE);
-
- DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch);
-
- } catch (CoreException e) {
- String title= JavadocExportMessages.JavadocWizard_error_title;
- String message= JavadocExportMessages.JavadocWizard_launch_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
-
- return true;
-
- }
- } catch (IOException e) {
- String title= JavadocExportMessages.JavadocWizard_error_title;
- String message= JavadocExportMessages.JavadocWizard_exec_error_message;
-
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, e.getMessage(), e);
- ExceptionHandler.handle(new CoreException(status), getShell(), title, message);
- return false;
- }
- return false;
-
- }
-
- private String checkForSpaces(String curr) {
- if (curr.indexOf(' ') == -1) {
- return curr;
- }
- StringBuffer buf= new StringBuffer();
- buf.append('\'');
- for (int i= 0; i < curr.length(); i++) {
- char ch= curr.charAt(i);
- if (ch == '\\' || ch == '\'') {
- buf.append('\\');
- }
- buf.append(ch);
- }
- buf.append('\'');
- return buf.toString();
- }
-
- /*
- * @see IWizard#addPages()
- */
- public void addPages() {
-
- fJTWPage= new JavadocTreeWizardPage(TREE_PAGE_DESC, fStore);
- fJSWPage= new JavadocSpecificsWizardPage(SPECIFICS_PAGE_DESC, fJTWPage, fStore);
- fJSpWPage= new JavadocStandardWizardPage(STANDARD_PAGE_DESC, fJTWPage, fStore);
-
- super.addPage(fJTWPage);
- super.addPage(fJSpWPage);
- super.addPage(fJSWPage);
-
- fJTWPage.init();
- fJSpWPage.init();
- fJSWPage.init();
-
- }
-
- public void init(IWorkbench workbench, IStructuredSelection structuredSelection) {
- IWorkbenchWindow window= workbench.getActiveWorkbenchWindow();
- List selected= Collections.EMPTY_LIST;
- if (window != null) {
- ISelection selection= window.getSelectionService().getSelection();
- if (selection instanceof IStructuredSelection) {
- selected= ((IStructuredSelection) selection).toList();
- } else {
- IJavaScriptElement element= EditorUtility.getActiveEditorJavaInput();
- if (element != null) {
- selected= new ArrayList();
- selected.add(element);
- }
- }
- }
- fStore= new JavadocOptionsManager(fXmlJavadocFile, getDialogSettings(), selected);
- }
-
- private void refresh(IPath path) {
- if (fRoot.findContainersForLocation(path).length > 0) {
- try {
- fRoot.refreshLocal(IResource.DEPTH_INFINITE, null);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- private void spawnInBrowser(Display display) {
- if (fOpenInBrowser) {
- try {
- IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$
- URL url= indexFile.toFile().toURL();
- OpenBrowserUtil.open(url, display, getWindowTitle());
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- private class JavadocDebugEventListener implements IDebugEventSetListener {
- private Display fDisplay;
- private File fFile;
-
- public JavadocDebugEventListener(Display display, File file) {
- fDisplay= display;
- fFile= file;
- }
-
- public void handleDebugEvents(DebugEvent[] events) {
- for (int i= 0; i < events.length; i++) {
- if (events[i].getKind() == DebugEvent.TERMINATE) {
- try {
- if (!fWriteCustom) {
- fFile.delete();
- refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace
- spawnInBrowser(fDisplay);
- }
- } finally {
- DebugPlugin.getDefault().removeDebugEventListener(this);
- }
- return;
- }
- }
- }
- }
-
- public IWizardPage getNextPage(IWizardPage page) {
- if (page instanceof JavadocTreeWizardPage) {
- if (!fJTWPage.getCustom()) {
- return fJSpWPage;
- }
- return fJSWPage;
- } else if (page instanceof JavadocSpecificsWizardPage) {
- return null;
- } else if (page instanceof JavadocStandardWizardPage)
- return fJSWPage;
- else
- return null;
- }
-
- public IWizardPage getPreviousPage(IWizardPage page) {
- if (page instanceof JavadocSpecificsWizardPage) {
- if (!fJTWPage.getCustom()) {
- return fJSpWPage;
- }
- return fJSWPage;
- } else if (page instanceof JavadocTreeWizardPage) {
- return null;
- } else if (page instanceof JavadocStandardWizardPage)
- return fJTWPage;
- else
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizardPage.java
deleted file mode 100644
index 361991b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWizardPage.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-public abstract class JavadocWizardPage extends NewElementWizardPage {
-
- protected JavadocWizardPage(String pageName) {
- super(pageName);
- setTitle(JavadocExportMessages.JavadocWizardPage_javadocwizardpage_description);
- }
-
- protected Button createButton(Composite composite, int style, String message, GridData gd) {
- Button button= new Button(composite, style);
- button.setText(message);
- button.setLayoutData(gd);
- return button;
- }
-
- protected GridLayout createGridLayout(int columns) {
- return new GridLayout(columns, false);
-
- }
-
- protected GridData createGridData(int flag, int hspan, int vspan, int indent) {
- GridData gd= new GridData(flag);
- gd.horizontalIndent= indent;
- gd.horizontalSpan= hspan;
- gd.verticalSpan= vspan;
- return gd;
- }
-
- protected GridData createGridData(int flag, int hspan, int indent) {
- GridData gd= new GridData(flag);
- gd.horizontalIndent= indent;
- gd.horizontalSpan= hspan;
- return gd;
- }
-
- protected GridData createGridData(int hspan) {
- GridData gd= new GridData();
- gd.horizontalSpan= hspan;
- return gd;
- }
-
- protected Label createLabel(Composite composite, int style, String message, GridData gd) {
- Label label= new Label(composite, style);
- label.setText(message);
- label.setLayoutData(gd);
- return label;
- }
-
- protected Text createText(Composite composite, int style, String message, GridData gd) {
- Text text= new Text(composite, style);
- if (message != null)
- text.setText(message);
- text.setLayoutData(gd);
- return text;
- }
-
- protected Combo createCombo(Composite composite, int style, String message, GridData gd) {
- Combo combo= new Combo(composite, style);
- if (message != null)
- combo.setText(message);
- combo.setLayoutData(gd);
- return combo;
- }
-
- protected void handleFileBrowseButtonPressed(Text text, String[] extensions, String title) {
- FileDialog dialog= new FileDialog(text.getShell());
- dialog.setText(title);
- dialog.setFilterExtensions(extensions);
- String dirName= text.getText();
- if (!dirName.equals("")) { //$NON-NLS-1$
- File path= new File(dirName);
- if (path.exists())
- dialog.setFilterPath(dirName);
-
- }
- String selectedDirectory= dialog.open();
- if (selectedDirectory != null)
- text.setText(selectedDirectory);
- }
-
- protected String handleFolderBrowseButtonPressed(String dir, String title, String message) {
- DirectoryDialog dialog= new DirectoryDialog(getShell());
- dialog.setFilterPath(dir);
- dialog.setText(title);
- dialog.setMessage(message);
- String res= dialog.open();
- if (res != null) {
- File file= new File(res);
- if (file.isDirectory())
- return res;
- }
- return dir;
- }
-
- protected static class EnableSelectionAdapter extends SelectionAdapter {
- private Control[] fEnable;
- private Control[] fDisable;
-
- protected EnableSelectionAdapter(Control[] enable, Control[] disable) {
- super();
- fEnable= enable;
- fDisable= disable;
- }
-
- public void widgetSelected(SelectionEvent e) {
- for (int i= 0; i < fEnable.length; i++) {
- fEnable[i].setEnabled(true);
- }
- for (int i= 0; i < fDisable.length; i++) {
- fDisable[i].setEnabled(false);
- }
- validate();
- }
- //copied from WizardNewProjectCreationPage
- public void validate() {
- }
-
- } //end class EnableSelectionAdapter
-
- protected static class ToggleSelectionAdapter extends SelectionAdapter {
- Control[] controls;
-
- protected ToggleSelectionAdapter(Control[] controls) {
- this.controls= controls;
- }
-
- public void widgetSelected(SelectionEvent e) {
-
- for (int i= 0; i < controls.length; i++) {
- Control control= controls[i];
- control.setEnabled(!control.getEnabled());
- }
- validate();
- }
-
- public void validate() {
- }
-
- } //end class ToggleSelection Adapter
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWriter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWriter.java
deleted file mode 100644
index 39e082a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocWriter.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class JavadocWriter {
-
- private static final char PATH_SEPARATOR= '/'; // use forward slash for all platforms
-
- private final OutputStream fOutputStream;
- private final IJavaScriptProject[] fJavaProjects;
- private final IPath fBasePath;
- private final String fEncoding;
-
- /**
- * Create a JavadocWriter on the given output stream.
- * It is the client's responsibility to close the output stream.
- * @param basePath The base path to which all path will be made relative (if
- * possible). If <code>null</code>, paths are not made relative.
- */
- public JavadocWriter(OutputStream outputStream, String encoding, IPath basePath, IJavaScriptProject[] projects) {
- Assert.isNotNull(outputStream);
- Assert.isNotNull(encoding);
- fOutputStream= new BufferedOutputStream(outputStream);
- fEncoding= encoding;
- fBasePath= basePath;
- fJavaProjects= projects;
- }
-
- public void writeXML(JavadocOptionsManager store) throws ParserConfigurationException, TransformerException {
-
- DocumentBuilder docBuilder= null;
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- docBuilder= factory.newDocumentBuilder();
- Document document= docBuilder.newDocument();
-
- // Create the document
- Element project= document.createElement("project"); //$NON-NLS-1$
- document.appendChild(project);
-
- project.setAttribute("default", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
-
- Element javadocTarget= document.createElement("target"); //$NON-NLS-1$
- project.appendChild(javadocTarget);
- javadocTarget.setAttribute("name", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
-
- Element xmlJavadocDesc= document.createElement("javadoc"); //$NON-NLS-1$
- javadocTarget.appendChild(xmlJavadocDesc);
-
- if (!store.isFromStandard())
- xmlWriteDoclet(store, document, xmlJavadocDesc);
- else
- xmlWriteJavadocStandardParams(store, document, xmlJavadocDesc);
-
-
- // Write the document to the stream
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, fEncoding);
- transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
- DOMSource source = new DOMSource(document);
- StreamResult result = new StreamResult(fOutputStream);
- transformer.transform(source, result);
-
- }
-
- //writes ant file, for now only worry about one project
- private void xmlWriteJavadocStandardParams(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException {
-
- String destination= getPathString(Path.fromOSString(store.getDestination()));
-
- xmlJavadocDesc.setAttribute(store.DESTINATION, destination);
- xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
- String source= store.getSource();
- if (source.length() > 0 && !source.equals("-")) { //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.SOURCE, store.getSource());
- }
- xmlJavadocDesc.setAttribute(store.USE, booleanToString(store.getBoolean("use"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.NOTREE, booleanToString(store.getBoolean("notree"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.NONAVBAR, booleanToString(store.getBoolean("nonavbar"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.NOINDEX, booleanToString(store.getBoolean("noindex"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.SPLITINDEX, booleanToString(store.getBoolean("splitindex"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.AUTHOR, booleanToString(store.getBoolean("author"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.VERSION, booleanToString(store.getBoolean("version"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.NODEPRECATEDLIST, booleanToString(store.getBoolean("nodeprecatedlist"))); //$NON-NLS-1$
- xmlJavadocDesc.setAttribute(store.NODEPRECATED, booleanToString(store.getBoolean("nodeprecated"))); //$NON-NLS-1$
-
-
- //set the packages and source files
- List packages= new ArrayList();
- List sourcefiles= new ArrayList();
- sortSourceElement(store.getSourceElements(), sourcefiles, packages);
- if (!packages.isEmpty())
- xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
-
- if (!sourcefiles.isEmpty())
- xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
-
- xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
- xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
-
- String overview= store.getOverview();
- if (overview.length() > 0)
- xmlJavadocDesc.setAttribute(store.OVERVIEW, overview);
-
- String styleSheet= store.getStyleSheet();
- if (styleSheet.length() > 0)
- xmlJavadocDesc.setAttribute(store.STYLESHEETFILE, styleSheet);
-
- String title= store.getTitle();
- if (title.length() > 0)
- xmlJavadocDesc.setAttribute(store.TITLE, title);
-
-
- String vmArgs= store.getVMParams();
- String additionalArgs= store.getAdditionalParams();
- if (vmArgs.length() + additionalArgs.length() > 0) {
- String str= vmArgs + ' ' + additionalArgs;
- xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
- }
-
- String[] hrefs= store.getHRefs();
- for (int i= 0; i < hrefs.length; i++) {
- Element links= document.createElement("link"); //$NON-NLS-1$
- xmlJavadocDesc.appendChild(links);
- links.setAttribute(store.HREF, hrefs[i]);
- }
- }
-
- private void sortSourceElement(IJavaScriptElement[] iJavaElements, List sourcefiles, List packages) {
- for (int i= 0; i < iJavaElements.length; i++) {
- IJavaScriptElement element= iJavaElements[i];
- IPath p= element.getResource().getLocation();
- if (p == null)
- continue;
-
- if (element instanceof IJavaScriptUnit) {
- String relative= getPathString(p);
- sourcefiles.add(relative);
- } else if (element instanceof IPackageFragment) {
- packages.add(element.getElementName());
- }
- }
- }
-
- private String getPathString(IPath[] paths) {
- StringBuffer buf= new StringBuffer();
-
- for (int i= 0; i < paths.length; i++) {
- if (buf.length() != 0) {
- buf.append(File.pathSeparatorChar);
- }
- buf.append(getPathString(paths[i]));
- }
-
- if (buf.length() == 0) {
- buf.append('.');
- }
- return buf.toString();
- }
-
- private boolean hasSameDevice(IPath p1, IPath p2) {
- String dev= p1.getDevice();
- if (dev == null) {
- return p2.getDevice() == null;
- }
- return dev.equals(p2.getDevice());
- }
-
- //make the path relative to the base path
- private String getPathString(IPath fullPath) {
- if (fBasePath == null || !hasSameDevice(fullPath, fBasePath)) {
- return fullPath.toOSString();
- }
- int matchingSegments= fBasePath.matchingFirstSegments(fullPath);
- if (fBasePath.segmentCount() == matchingSegments) {
- return getRelativePath(fullPath, matchingSegments);
- }
- for (int i= 0; i < fJavaProjects.length; i++) {
- IProject proj= fJavaProjects[i].getProject();
- IPath projLoc= proj.getLocation();
- if (projLoc != null && projLoc.segmentCount() <= matchingSegments && projLoc.isPrefixOf(fullPath)) {
- return getRelativePath(fullPath, matchingSegments);
- }
- }
- IPath workspaceLoc= ResourcesPlugin.getWorkspace().getRoot().getLocation();
- if (workspaceLoc.segmentCount() <= matchingSegments && workspaceLoc.isPrefixOf(fullPath)) {
- return getRelativePath(fullPath, matchingSegments);
- }
- return fullPath.toOSString();
- }
-
- private String getRelativePath(IPath fullPath, int matchingSegments) {
- StringBuffer res= new StringBuffer();
- int backSegments= fBasePath.segmentCount() - matchingSegments;
- while (backSegments > 0) {
- res.append(".."); //$NON-NLS-1$
- res.append(PATH_SEPARATOR);
- backSegments--;
- }
- int segCount= fullPath.segmentCount();
- for (int i= matchingSegments; i < segCount; i++) {
- if (i > matchingSegments) {
- res.append(PATH_SEPARATOR);
- }
- res.append(fullPath.segment(i));
- }
- return res.toString();
- }
-
- private void xmlWriteDoclet(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException {
-
- //set the packages and source files
- List packages= new ArrayList();
- List sourcefiles= new ArrayList();
- sortSourceElement(store.getSourceElements(), sourcefiles, packages);
- if (!packages.isEmpty())
- xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
-
- if (!sourcefiles.isEmpty())
- xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
-
- xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
- xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
- xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
-
- Element doclet= document.createElement("doclet"); //$NON-NLS-1$
- xmlJavadocDesc.appendChild(doclet);
- doclet.setAttribute(store.NAME, store.getDocletName());
- doclet.setAttribute(store.PATH, store.getDocletPath());
-
- String str= store.getOverview();
- if (str.length() > 0)
- xmlJavadocDesc.setAttribute(store.OVERVIEW, str);
-
- str= store.getAdditionalParams();
- if (str.length() > 0)
- xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
-
- }
-
- private String toSeparatedList(List packages) {
- StringBuffer buf= new StringBuffer();
- Iterator iter= packages.iterator();
- int nAdded= 0;
- while (iter.hasNext()) {
- if (nAdded > 0) {
- buf.append(',');
- }
- nAdded++;
- String curr= (String) iter.next();
- buf.append(curr);
- }
- return buf.toString();
- }
-
- private String booleanToString(boolean bool) {
- if (bool)
- return "true"; //$NON-NLS-1$
- else
- return "false"; //$NON-NLS-1$
- }
-
- public void close() throws IOException {
- if (fOutputStream != null) {
- fOutputStream.close();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/RecentSettingsStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/RecentSettingsStore.java
deleted file mode 100644
index df4d89a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/RecentSettingsStore.java
+++ /dev/null
@@ -1,277 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javadocexport;
-
-import java.io.File;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class RecentSettingsStore {
-
- private final String HREF= "href"; //$NON-NLS-1$
- private final String DESTINATION= "destdir"; //$NON-NLS-1$
- private final String ANTPATH= "antpath"; //$NON-NLS-1$
-
- private final String SECTION_PROJECTS= "projects"; //$NON-NLS-1$
-
- private final static char REF_SEPARATOR= ';';
-
-
- //list of hrefs in string format
- private Map fPerProjectSettings;
-
- /**
- *
- */
- public RecentSettingsStore(IDialogSettings settings) {
- fPerProjectSettings= new HashMap();
- if (settings != null) {
- load(settings);
- }
- }
-
- /**
- * Method creates a list of data structes that contain
- * The destination, antfile location and the list of library/project references for every
- * project in the workspace.Defaults are created for new project.
- */
- private void load(IDialogSettings settings) {
-
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
-
- IDialogSettings projectsSection= settings.getSection(SECTION_PROJECTS);
- if (projectsSection != null) {
- IDialogSettings[] sections= projectsSection.getSections();
- for (int i= 0; i < sections.length; i++) {
- IDialogSettings curr= sections[i];
- String projectName= curr.getName();
- IProject project= root.getProject(projectName);
- //make sure project has not been removed
- if (project.isAccessible()) {
- IJavaScriptProject javaProject= JavaScriptCore.create(project);
- if (!fPerProjectSettings.containsKey(javaProject)) {
- String hrefs= curr.get(HREF);
- if (hrefs == null) {
- hrefs= ""; //$NON-NLS-1$
- }
- String destdir= curr.get(DESTINATION);
- if (destdir == null || destdir.length() == 0) {
- destdir= getDefaultDestination(javaProject);
- }
- String antpath= curr.get(ANTPATH);
- if (antpath == null || antpath.length() == 0) {
- antpath= getDefaultAntPath(javaProject);
- }
- ProjectData data= new ProjectData();
- data.setDestination(destdir);
- data.setAntpath(antpath);
- data.setHRefs(hrefs);
- if (!fPerProjectSettings.containsValue(javaProject))
- fPerProjectSettings.put(javaProject, data);
- }
- }
- }
- }
- //finds projects in the workspace that have been added since the
- //last time the wizard was run
- IProject[] projects= root.getProjects();
- for (int i= 0; i < projects.length; i++) {
- IProject project= projects[i];
- if (project.isAccessible()) {
- IJavaScriptProject curr= JavaScriptCore.create(project);
- if (!fPerProjectSettings.containsKey(curr)) {
- ProjectData data= new ProjectData();
- data.setDestination(getDefaultDestination(curr));
- data.setAntpath(getDefaultAntPath(curr));
- data.setHRefs(""); //$NON-NLS-1$
- fPerProjectSettings.put(curr, data);
- }
- }
- }
- }
-
- public void store(IDialogSettings settings) {
-
- IDialogSettings projectsSection= settings.addNewSection(SECTION_PROJECTS);
-
- //Write all project information to DialogSettings.
- Set keys= fPerProjectSettings.keySet();
- for (Iterator iter= keys.iterator(); iter.hasNext();) {
-
- IJavaScriptProject curr= (IJavaScriptProject) iter.next();
-
- IDialogSettings proj= projectsSection.addNewSection(curr.getElementName());
- if (!keys.contains(curr)) {
- proj.put(HREF, ""); //$NON-NLS-1$
- proj.put(DESTINATION, ""); //$NON-NLS-1$
- proj.put(ANTPATH, ""); //$NON-NLS-1$
- } else {
- ProjectData data= (ProjectData) fPerProjectSettings.get(curr);
- proj.put(HREF, data.getHRefs());
- proj.put(DESTINATION, data.getDestination());
- proj.put(ANTPATH, data.getAntPath());
- }
- projectsSection.addSection(proj);
- }
- }
-
- public void setProjectSettings(IJavaScriptProject project, String destination, String antpath, String[] hrefs) {
- ProjectData data= (ProjectData) fPerProjectSettings.get(project);
- if (data == null) {
- data= new ProjectData();
- }
- data.setDestination(destination);
- data.setAntpath(antpath);
-
- StringBuffer refs= new StringBuffer();
- for (int i= 0; i < hrefs.length; i++) {
- if (i > 0) {
- refs.append(REF_SEPARATOR);
- }
- refs.append(hrefs[i]);
-
- }
- data.setHRefs(refs.toString());
- }
-
- public static String[] getRefTokens(String refs) {
- StringTokenizer tok= new StringTokenizer(refs, String.valueOf(REF_SEPARATOR));
- String[] res= new String[tok.countTokens()];
- for (int i= 0; i < res.length; i++) {
- res[i]= tok.nextToken();
- }
- return res;
- }
-
-
-
- public String[] getHRefs(IJavaScriptProject project) {
- ProjectData data= (ProjectData) fPerProjectSettings.get(project);
- if (data != null) {
- String refs= data.getHRefs();
- return getRefTokens(refs);
- }
- return new String[0];
- }
-
- //for now if multiple projects are selected the destination
- //feild will be empty,
- public String getDestination(IJavaScriptProject project) {
-
- ProjectData data= (ProjectData) fPerProjectSettings.get(project);
- if (data != null)
- return data.getDestination();
- else
- return getDefaultDestination(project);
- }
-
- public String getAntpath(IJavaScriptProject project) {
- ProjectData data= (ProjectData) fPerProjectSettings.get(project);
- if (data != null)
- return data.getAntPath();
- else
- return getDefaultAntPath(project);
- }
-
- /// internal
-
-
- private String getDefaultAntPath(IJavaScriptProject project) {
- if (project != null) {
- // The Javadoc.xml file can only be stored locally. So if
- // the project isn't local then we can't provide a good
- // default location.
- IPath path= project.getProject().getLocation();
- if (path != null)
- return path.append("javadoc.xml").toOSString(); //$NON-NLS-1$
- }
-
- return ""; //$NON-NLS-1$
- }
-
- private String getDefaultDestination(IJavaScriptProject project) {
- if (project != null) {
- URL url= JavaScriptUI.getProjectJSdocLocation(project);
- //uses default if source is has http protocol
- if (url == null || !url.getProtocol().equals("file")) { //$NON-NLS-1$
- // Since Javadoc.exe is a local tool its output is local.
- // So if the project isn't local then the default location
- // can't be local to a project. So use #getLocation() to
- // test this is fine here.
- IPath path= project.getProject().getLocation();
- if (path != null)
- return path.append("doc").toOSString(); //$NON-NLS-1$
- } else {
- //must do this to remove leading "/"
- return (new File(url.getFile())).getPath();
- }
- }
-
- return ""; //$NON-NLS-1$
-
- }
-
- private static class ProjectData {
-
- private String fHrefs;
- private String fDestinationDir;
- private String fAntPath;
-
- public void setHRefs(String hrefs) {
- if (hrefs == null)
- fHrefs= ""; //$NON-NLS-1$
- else
- fHrefs= hrefs;
- }
-
- public void setDestination(String destination) {
- if (destination == null)
- fDestinationDir= ""; //$NON-NLS-1$
- else
- fDestinationDir= destination;
- }
-
- public void setAntpath(String antpath) {
- if (antpath == null)
- fAntPath= ""; //$NON-NLS-1$
- else
- fAntPath= antpath;
- }
-
- public String getHRefs() {
- return fHrefs;
- }
-
- public String getDestination() {
- return fDestinationDir;
- }
-
- public String getAntPath() {
- return fAntPath;
- }
-
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java
deleted file mode 100644
index 96b061fe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java
+++ /dev/null
@@ -1,672 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IWindowListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-/**
- * Provides a shared AST for clients. The shared AST is
- * the AST of the active Java editor's input element.
- *
- *
- */
-public final class ASTProvider {
-
- /**
- * Wait flag.
- *
- *
- */
- public static final class WAIT_FLAG {
-
- String fName;
-
- private WAIT_FLAG(String name) {
- fName= name;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fName;
- }
- }
-
- /**
- * Wait flag indicating that a client requesting an AST
- * wants to wait until an AST is ready.
- * <p>
- * An AST will be created by this AST provider if the shared
- * AST is not for the given java element.
- * </p>
- *
- *
- */
- public static final WAIT_FLAG WAIT_YES= new WAIT_FLAG("wait yes"); //$NON-NLS-1$
-
- /**
- * Wait flag indicating that a client requesting an AST
- * only wants to wait for the shared AST of the active editor.
- * <p>
- * No AST will be created by the AST provider.
- * </p>
- *
- *
- */
- public static final WAIT_FLAG WAIT_ACTIVE_ONLY= new WAIT_FLAG("wait active only"); //$NON-NLS-1$
-
- /**
- * Wait flag indicating that a client requesting an AST
- * only wants the already available shared AST.
- * <p>
- * No AST will be created by the AST provider.
- * </p>
- *
- *
- */
- public static final WAIT_FLAG WAIT_NO= new WAIT_FLAG("don't wait"); //$NON-NLS-1$
-
-
- /**
- * Tells whether this class is in debug mode.
- *
- */
- private static final boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ASTProvider")); //$NON-NLS-1$//$NON-NLS-2$
-
-
- /**
- * Internal activation listener.
- *
- *
- */
- private class ActivationListener implements IPartListener2, IWindowListener {
-
-
- /*
- * @see org.eclipse.ui.IPartListener2#partActivated(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partActivated(IWorkbenchPartReference ref) {
- if (isJavaEditor(ref) && !isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partBroughtToTop(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partBroughtToTop(IWorkbenchPartReference ref) {
- if (isJavaEditor(ref) && !isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partClosed(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partClosed(IWorkbenchPartReference ref) {
- if (isActiveEditor(ref)) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "closed active editor: " + ref.getTitle()); //$NON-NLS-1$ //$NON-NLS-2$
-
- activeJavaEditorChanged(null);
- }
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partDeactivated(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partDeactivated(IWorkbenchPartReference ref) {
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partOpened(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partOpened(IWorkbenchPartReference ref) {
- if (isJavaEditor(ref) && !isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partHidden(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partHidden(IWorkbenchPartReference ref) {
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partVisible(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partVisible(IWorkbenchPartReference ref) {
- if (isJavaEditor(ref) && !isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partInputChanged(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partInputChanged(IWorkbenchPartReference ref) {
- if (isJavaEditor(ref) && isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow)
- */
- public void windowActivated(IWorkbenchWindow window) {
- IWorkbenchPartReference ref= window.getPartService().getActivePartReference();
- if (isJavaEditor(ref) && !isActiveEditor(ref))
- activeJavaEditorChanged(ref.getPart(true));
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow)
- */
- public void windowDeactivated(IWorkbenchWindow window) {
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow)
- */
- public void windowClosed(IWorkbenchWindow window) {
- if (fActiveEditor != null && fActiveEditor.getSite() != null && window == fActiveEditor.getSite().getWorkbenchWindow()) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "closed active editor: " + fActiveEditor.getTitle()); //$NON-NLS-1$ //$NON-NLS-2$
-
- activeJavaEditorChanged(null);
- }
- window.getPartService().removePartListener(this);
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow)
- */
- public void windowOpened(IWorkbenchWindow window) {
- window.getPartService().addPartListener(this);
- }
-
- private boolean isActiveEditor(IWorkbenchPartReference ref) {
- return ref != null && isActiveEditor(ref.getPart(false));
- }
-
- private boolean isActiveEditor(IWorkbenchPart part) {
- return part != null && (part == fActiveEditor);
- }
-
- private boolean isJavaEditor(IWorkbenchPartReference ref) {
- if (ref == null)
- return false;
-
- String id= ref.getId();
-
- // The instanceof check is not need but helps clients, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84862
- return JavaScriptUI.ID_CF_EDITOR.equals(id) || JavaScriptUI.ID_CU_EDITOR.equals(id) || ref.getPart(false) instanceof JavaEditor;
- }
- }
-
- public static final int SHARED_AST_LEVEL= AST.JLS3;
- public static final boolean SHARED_AST_STATEMENT_RECOVERY= true;
- public static final boolean SHARED_BINDING_RECOVERY= true;
-
- private static final String DEBUG_PREFIX= "ASTProvider > "; //$NON-NLS-1$
-
-
- private IJavaScriptElement fReconcilingJavaElement;
- private IJavaScriptElement fActiveJavaElement;
- private JavaScriptUnit fAST;
- private ActivationListener fActivationListener;
- private Object fReconcileLock= new Object();
- private Object fWaitLock= new Object();
- private boolean fIsReconciling;
- private IWorkbenchPart fActiveEditor;
-
-
- /**
- * Returns the Java plug-in's AST provider.
- *
- * @return the AST provider
- *
- */
- public static ASTProvider getASTProvider() {
- return JavaScriptPlugin.getDefault().getASTProvider();
- }
-
- /**
- * Creates a new AST provider.
- */
- public ASTProvider() {
- install();
- }
-
- /**
- * Installs this AST provider.
- */
- void install() {
- // Create and register activation listener
- fActivationListener= new ActivationListener();
- PlatformUI.getWorkbench().addWindowListener(fActivationListener);
-
- // Ensure existing windows get connected
- IWorkbenchWindow[] windows= PlatformUI.getWorkbench().getWorkbenchWindows();
- for (int i= 0, length= windows.length; i < length; i++)
- windows[i].getPartService().addPartListener(fActivationListener);
- }
-
- private void activeJavaEditorChanged(IWorkbenchPart editor) {
-
- IJavaScriptElement javaElement= null;
- if (editor instanceof JavaEditor)
- javaElement= ((JavaEditor)editor).getInputJavaElement();
-
- synchronized (this) {
- fActiveEditor= editor;
- fActiveJavaElement= javaElement;
- cache(null, javaElement);
- }
-
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "active editor is: " + toString(javaElement)); //$NON-NLS-1$ //$NON-NLS-2$
-
- synchronized (fReconcileLock) {
- if (fIsReconciling && (fReconcilingJavaElement == null || !fReconcilingJavaElement.equals(javaElement))) {
- fIsReconciling= false;
- fReconcilingJavaElement= null;
- } else if (javaElement == null) {
- fIsReconciling= false;
- fReconcilingJavaElement= null;
- }
- }
- }
-
- /**
- * Returns whether the given compilation unit AST is
- * cached by this AST provided.
- *
- * @param ast the compilation unit AST
- * @return <code>true</code> if the given AST is the cached one
- */
- public boolean isCached(JavaScriptUnit ast) {
- return ast != null && fAST == ast;
- }
-
- /**
- * Returns whether this AST provider is active on the given
- * compilation unit.
- *
- * @param cu the compilation unit
- * @return <code>true</code> if the given compilation unit is the active one
- *
- */
- public boolean isActive(IJavaScriptUnit cu) {
- return cu != null && cu.equals(fActiveJavaElement);
- }
-
- /**
- * Informs that reconciling for the given element is about to be started.
- *
- * @param javaElement the Java element
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
- */
- void aboutToBeReconciled(IJavaScriptElement javaElement) {
-
- if (javaElement == null)
- return;
-
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "about to reconcile: " + toString(javaElement)); //$NON-NLS-1$ //$NON-NLS-2$
-
- synchronized (fReconcileLock) {
- fIsReconciling= true;
- fReconcilingJavaElement= javaElement;
- }
- cache(null, javaElement);
- }
-
- /**
- * Disposes the cached AST.
- */
- private synchronized void disposeAST() {
-
- if (fAST == null)
- return;
-
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "disposing AST: " + toString(fAST) + " for: " + toString(fActiveJavaElement)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- fAST= null;
-
- cache(null, null);
- }
-
- /**
- * Returns a string for the given Java element used for debugging.
- *
- * @param javaElement the compilation unit AST
- * @return a string used for debugging
- */
- private String toString(IJavaScriptElement javaElement) {
- if (javaElement == null)
- return "null"; //$NON-NLS-1$
- else
- return javaElement.getElementName();
-
- }
-
- /**
- * Returns a string for the given AST used for debugging.
- *
- * @param ast the compilation unit AST
- * @return a string used for debugging
- */
- private String toString(JavaScriptUnit ast) {
- if (ast == null)
- return "null"; //$NON-NLS-1$
-
- List types= ast.types();
- if (types != null && types.size() > 0)
- return ((AbstractTypeDeclaration)types.get(0)).getName().getIdentifier();
- else
- return "AST without any type"; //$NON-NLS-1$
- }
-
- /**
- * Caches the given compilation unit AST for the given Java element.
- *
- * @param ast
- * @param javaElement
- */
- private synchronized void cache(JavaScriptUnit ast, IJavaScriptElement javaElement) {
-
- if (fActiveJavaElement != null && !fActiveJavaElement.equals(javaElement)) {
- if (DEBUG && javaElement != null) // don't report call from disposeAST()
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "don't cache AST for inactive: " + toString(javaElement)); //$NON-NLS-1$ //$NON-NLS-2$
- return;
- }
-
- if (DEBUG && (javaElement != null || ast != null)) // don't report call from disposeAST()
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "caching AST: " + toString(ast) + " for: " + toString(javaElement)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- if (fAST != null)
- disposeAST();
-
- fAST= ast;
-
- // Signal AST change
- synchronized (fWaitLock) {
- fWaitLock.notifyAll();
- }
- }
-
- /**
- * Returns a shared compilation unit AST for the given
- * Java element.
- * <p>
- * Clients are not allowed to modify the AST and must
- * synchronize all access to its nodes.
- * </p>
- *
- * @param je the Java element
- * @param waitFlag {@link #WAIT_YES}, {@link #WAIT_NO} or {@link #WAIT_ACTIVE_ONLY}
- * @param progressMonitor the progress monitor or <code>null</code>
- * @return the AST or <code>null</code> if the AST is not available
- */
- public JavaScriptUnit getAST(IJavaScriptElement je, WAIT_FLAG waitFlag, IProgressMonitor progressMonitor) {
- if (je == null)
- return null;
-
- Assert.isTrue(je.getElementType() == IJavaScriptElement.CLASS_FILE || je.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT);
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- return null;
-
- boolean isActiveElement;
- synchronized (this) {
- isActiveElement= je.equals(fActiveJavaElement);
- if (isActiveElement) {
- if (fAST != null) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "returning cached AST:" + toString(fAST) + " for: " + je.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- return fAST;
- }
- if (waitFlag == WAIT_NO) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "returning null (WAIT_NO) for: " + je.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
-
- return null;
-
- }
- }
- }
- if (isActiveElement && isReconciling(je)) {
- try {
- final IJavaScriptElement activeElement= fReconcilingJavaElement;
-
- // Wait for AST
- synchronized (fWaitLock) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "waiting for AST for: " + je.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
-
- fWaitLock.wait();
- }
-
- // Check whether active element is still valid
- synchronized (this) {
- if (activeElement == fActiveJavaElement && fAST != null) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "...got AST for: " + je.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
-
- return fAST;
- }
- }
- return getAST(je, waitFlag, progressMonitor);
- } catch (InterruptedException e) {
- return null; // thread has been interrupted don't compute AST
- }
- } else if (waitFlag == WAIT_NO || (waitFlag == WAIT_ACTIVE_ONLY && !(isActiveElement && fAST == null)))
- return null;
-
- if (isActiveElement)
- aboutToBeReconciled(je);
-
- JavaScriptUnit ast= null;
- try {
- ast= createAST(je, progressMonitor);
- if (progressMonitor != null && progressMonitor.isCanceled()) {
- ast= null;
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "Ignore created AST for: " + je.getElementName() + " - operation has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- } finally {
- if (isActiveElement) {
- if (fAST != null) {
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "Ignore created AST for " + je.getElementName() + " - AST from reconciler is newer"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- reconciled(fAST, je, null);
- } else
- reconciled(ast, je, null);
- }
- }
-
- return ast;
- }
-
- /**
- * Tells whether the given Java element is the one
- * reported as currently being reconciled.
- *
- * @param javaElement the Java element
- * @return <code>true</code> if reported as currently being reconciled
- */
- private boolean isReconciling(IJavaScriptElement javaElement) {
- synchronized (fReconcileLock) {
- return javaElement != null && javaElement.equals(fReconcilingJavaElement) && fIsReconciling;
- }
- }
-
- /**
- * Creates a new compilation unit AST.
- *
- * @param je the Java element for which to create the AST
- * @param progressMonitor the progress monitor
- * @return AST
- */
- private JavaScriptUnit createAST(final IJavaScriptElement je, final IProgressMonitor progressMonitor) {
- if (!hasSource(je))
- return null;
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- return null;
-
- final ASTParser parser = ASTParser.newParser(SHARED_AST_LEVEL);
- parser.setResolveBindings(true);
- parser.setStatementsRecovery(SHARED_AST_STATEMENT_RECOVERY);
- parser.setBindingsRecovery(SHARED_BINDING_RECOVERY);
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- return null;
-
- if (je.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT)
- parser.setSource((IJavaScriptUnit)je);
- else if (je.getElementType() == IJavaScriptElement.CLASS_FILE)
- parser.setSource((IClassFile)je);
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- return null;
-
- final JavaScriptUnit root[]= new JavaScriptUnit[1];
-
- SafeRunner.run(new ISafeRunnable() {
- public void run() {
- try {
- if (progressMonitor != null && progressMonitor.isCanceled())
- return;
- if (DEBUG)
- System.err.println(getThreadName() + " - " + DEBUG_PREFIX + "creating AST for: " + je.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
- root[0]= (JavaScriptUnit)parser.createAST(progressMonitor);
- } catch (OperationCanceledException ex) {
- return;
- }
- }
- public void handleException(Throwable ex) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, "Error in JSDT Core during AST creation", ex); //$NON-NLS-1$
- JavaScriptPlugin.getDefault().getLog().log(status);
- }
- });
-
- // mark as unmodifiable
- if (root[0] != null)
- ASTNodes.setFlagsToAST(root[0], ASTNode.PROTECT);
-
- return root[0];
- }
-
- /**
- * Checks whether the given Java element has accessible source.
- *
- * @param je the Java element to test
- * @return <code>true</code> if the element has source
- *
- */
- private boolean hasSource(IJavaScriptElement je) {
- if (je == null || !je.exists())
- return false;
-
- try {
- return je instanceof ITypeRoot && ((ITypeRoot)je).getBuffer() != null;
- } catch (JavaScriptModelException ex) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, "Error in JSDT Core during AST creation", ex); //$NON-NLS-1$
- JavaScriptPlugin.getDefault().getLog().log(status);
- }
- return false;
- }
-
- /**
- * Disposes this AST provider.
- */
- public void dispose() {
-
- // Dispose activation listener
- PlatformUI.getWorkbench().removeWindowListener(fActivationListener);
- fActivationListener= null;
-
- disposeAST();
-
- synchronized (fWaitLock) {
- fWaitLock.notifyAll();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit)
- */
- void reconciled(JavaScriptUnit ast, IJavaScriptElement javaElement, IProgressMonitor progressMonitor) {
-
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "reconciled: " + toString(javaElement) + ", AST: " + toString(ast)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- synchronized (fReconcileLock) {
-
- fIsReconciling= progressMonitor != null && progressMonitor.isCanceled();
- if (javaElement == null || !javaElement.equals(fReconcilingJavaElement)) {
-
- if (DEBUG)
- System.out.println(getThreadName() + " - " + DEBUG_PREFIX + " ignoring AST of out-dated editor"); //$NON-NLS-1$ //$NON-NLS-2$
-
- // Signal - threads might wait for wrong element
- synchronized (fWaitLock) {
- fWaitLock.notifyAll();
- }
-
- return;
- }
-
- cache(ast, javaElement);
- }
- }
-
- private String getThreadName() {
- String name= Thread.currentThread().getName();
- if (name != null)
- return name;
- else
- return Thread.currentThread().toString();
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddClassFileMarkerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddClassFileMarkerAction.java
deleted file mode 100644
index 4c41a102..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddClassFileMarkerAction.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.texteditor.AddMarkerAction;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IResourceLocator;
-
-
-
-class AddClassFileMarkerAction extends AddMarkerAction {
-
-
- /**
- * Creates a marker action.
- */
- public AddClassFileMarkerAction(String prefix, ITextEditor textEditor, String markerType, boolean askForLabel) {
- super(JavaEditorMessages.getBundleForConstructedKeys(), prefix, textEditor, markerType, askForLabel);
- }
-
- /**
- * @see AddMarkerAction#getResource()
- */
- protected IResource getResource() {
-
- IResource resource= null;
-
- IEditorInput input= getTextEditor().getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- IClassFile c= ((IClassFileEditorInput) input).getClassFile();
- IResourceLocator locator= (IResourceLocator) c.getAdapter(IResourceLocator.class);
- if (locator != null) {
- try {
- resource= locator.getContainingResource(c);
- } catch (JavaScriptModelException x) {
- // ignore but should inform
- }
- }
- }
-
- return resource;
- }
-
- /**
- * @see AddMarkerAction#getInitialAttributes()
- */
- protected Map getInitialAttributes() {
-
- Map attributes= super.getInitialAttributes();
-
- IEditorInput input= getTextEditor().getEditorInput();
- if (input instanceof IClassFileEditorInput) {
-
- IClassFile classFile= ((IClassFileEditorInput) input).getClassFile();
- JavaScriptCore.addJavaScriptElementMarkerAttributes(attributes, classFile);
- }
-
- return attributes;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddImportOnSelectionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
deleted file mode 100644
index c0881b67..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Comparator;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IEditingSupport;
-import org.eclipse.jface.text.IEditingSupportRegistry;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.dialogs.FilteredList;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddImportsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddImportsOperation.IChooseImportQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.History;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-
-import com.ibm.icu.text.Collator;
-
-
-public class AddImportOnSelectionAction extends Action implements IUpdate {
-
- private static final AddImportComparator ADD_IMPORT_COMPARATOR= new AddImportComparator();
-
- private static final class AddImportComparator implements Comparator {
-
- public int compare(Object o1, Object o2) {
- if (((String)o1).equals(o2))
- return 0;
-
- History history= QualifiedTypeNameHistory.getDefault();
-
- int pos1= history.getPosition(o1);
- int pos2= history.getPosition(o2);
-
- if (pos1 == pos2)
- return Collator.getInstance().compare(o1, o2);
-
- if (pos1 > pos2) {
- return -1;
- } else {
- return 1;
- }
- }
-
- }
-
- private CompilationUnitEditor fEditor;
-
- public AddImportOnSelectionAction(CompilationUnitEditor editor) {
- super(JavaEditorMessages.AddImportOnSelection_label);
- setToolTipText(JavaEditorMessages.AddImportOnSelection_tooltip);
- setDescription(JavaEditorMessages.AddImportOnSelection_description);
- fEditor= editor;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
- setEnabled(getCompilationUnit() != null);
- }
-
- public void update() {
- setEnabled(fEditor != null && getCompilationUnit() != null);
- }
-
- private IJavaScriptUnit getCompilationUnit () {
- if (fEditor == null) {
- return null;
- }
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- return manager.getWorkingCopy(fEditor.getEditorInput());
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- final IJavaScriptUnit cu= getCompilationUnit();
- if (cu == null || fEditor == null)
- return;
- if (!ElementValidator.checkValidateEdit(cu, getShell(), JavaEditorMessages.AddImportOnSelection_error_title))
- return;
- if (!ActionUtil.isEditable(fEditor))
- return;
-
- ISelection selection= fEditor.getSelectionProvider().getSelection();
- if (selection instanceof ITextSelection) {
- final ITextSelection textSelection= (ITextSelection) selection;
- AddImportOnSelectionAction.SelectTypeQuery query= new SelectTypeQuery(getShell());
- AddImportsOperation op= new AddImportsOperation(cu, textSelection.getOffset(), textSelection.getLength(), query, false);
- IEditingSupport helper= createViewerHelper(textSelection, query);
- try {
- registerHelper(helper);
- IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
- progressService.runInUI(fEditor.getSite().getWorkbenchWindow(), new WorkbenchRunnableAdapter(op, op.getScheduleRule()), op.getScheduleRule());
- IStatus status= op.getStatus();
- if (!status.isOK()) {
- IStatusLineManager manager= getStatusLineManager();
- if (manager != null) {
- manager.setMessage(status.getMessage());
- }
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), JavaEditorMessages.AddImportOnSelection_error_title, null);
- } catch (InterruptedException e) {
- // Do nothing. Operation has been canceled.
- } finally {
- deregisterHelper(helper);
- }
- }
- }
-
- private IEditingSupport createViewerHelper(final ITextSelection selection, final SelectTypeQuery query) {
- return new IEditingSupport() {
-
- public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) {
- return subjectRegion.getOffset() <= selection.getOffset() + selection.getLength() && selection.getOffset() <= subjectRegion.getOffset() + subjectRegion.getLength();
- }
-
- public boolean ownsFocusShell() {
- return query.isShowing();
- }
-
- };
- }
-
- private void registerHelper(IEditingSupport helper) {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.register(helper);
- }
- }
-
- private void deregisterHelper(IEditingSupport helper) {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.unregister(helper);
- }
- }
-
- private Shell getShell() {
- return fEditor.getSite().getShell();
- }
-
- private static class SelectTypeQuery implements IChooseImportQuery {
-
- private final Shell fShell;
- private boolean fIsShowing;
-
- public SelectTypeQuery(Shell shell) {
- fShell= shell;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddImportsOperation.IChooseImportQuery#chooseImport(org.eclipse.wst.jsdt.internal.corext.util.TypeInfo[], java.lang.String)
- */
- public TypeNameMatch chooseImport(TypeNameMatch[] results, String containerName) {
- int nResults= results.length;
-
- if (nResults == 0) {
- return null;
- } else if (nResults == 1) {
- return results[0];
- }
-
- if (containerName.length() != 0) {
- for (int i= 0; i < nResults; i++) {
- TypeNameMatch curr= results[i];
- if (containerName.equals(curr.getTypeContainerName())) {
- return curr;
- }
- }
- }
- fIsShowing= true;
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(fShell, new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED)) {
- protected FilteredList createFilteredList(Composite parent) {
- FilteredList filteredList= super.createFilteredList(parent);
- filteredList.setComparator(ADD_IMPORT_COMPARATOR);
- return filteredList;
- }
- };
- dialog.setTitle(JavaEditorMessages.AddImportOnSelection_dialog_title);
- dialog.setMessage(JavaEditorMessages.AddImportOnSelection_dialog_message);
- dialog.setElements(results);
- if (dialog.open() == Window.OK) {
- fIsShowing= false;
- TypeNameMatch result= (TypeNameMatch) dialog.getFirstResult();
- QualifiedTypeNameHistory.remember(result.getFullyQualifiedName());
- return result;
- }
- fIsShowing= false;
- return null;
- }
-
- boolean isShowing() {
- return fIsShowing;
- }
- }
-
- private IStatusLineManager getStatusLineManager() {
- return fEditor.getEditorSite().getActionBars().getStatusLineManager();
- }
-
- /**
- * @return Returns the scheduling rule for this operation
- */
- public ISchedulingRule getScheduleRule() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java
deleted file mode 100644
index a28ce11e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.actions.RetargetAction;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.RetargetTextEditorAction;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalCategory;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalComputerRegistry;
-import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
-
-
-public class BasicCompilationUnitEditorActionContributor extends BasicJavaEditorActionContributor {
-
- /**
- * A menu listener that can remove itself from the menu it listens to.
- *
- */
- private final class MenuListener implements IMenuListener {
- private final IMenuManager fMenu;
-
- public MenuListener(IMenuManager menu) {
- fMenu= menu;
- }
-
- public void menuAboutToShow(IMenuManager manager) {
- for (int i= 0; i < fSpecificAssistActions.length; i++) {
- fSpecificAssistActions[i].update();
- }
- }
-
- public void dispose() {
- fMenu.removeMenuListener(this);
- }
- }
-
- protected RetargetAction fRetargetContentAssist;
- protected RetargetTextEditorAction fContentAssist;
- protected RetargetTextEditorAction fContextInformation;
- protected RetargetTextEditorAction fQuickAssistAction;
- protected RetargetTextEditorAction fChangeEncodingAction;
-
- /* */
- protected SpecificContentAssistAction[] fSpecificAssistActions;
- /* */
- private MenuListener fContentAssistMenuListener;
-
-
- public BasicCompilationUnitEditorActionContributor() {
-
- fRetargetContentAssist= new RetargetAction(JdtActionConstants.CONTENT_ASSIST, JavaEditorMessages.ContentAssistProposal_label);
- fRetargetContentAssist.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- fRetargetContentAssist.setImageDescriptor(JavaPluginImages.DESC_ELCL_CODE_ASSIST);
- fRetargetContentAssist.setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_CODE_ASSIST);
- markAsPartListener(fRetargetContentAssist);
-
- fContentAssist= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "ContentAssistProposal."); //$NON-NLS-1$
- fContentAssist.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- fContentAssist.setImageDescriptor(JavaPluginImages.DESC_ELCL_CODE_ASSIST);
- fContentAssist.setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_CODE_ASSIST);
-
- fContextInformation= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "ContentAssistContextInformation."); //$NON-NLS-1$
- fContextInformation.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
-
- fQuickAssistAction= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "CorrectionAssistProposal."); //$NON-NLS-1$
- fQuickAssistAction.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICK_ASSIST);
-
- fChangeEncodingAction= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.ChangeEncodingAction."); //$NON-NLS-1$
- }
-
- /*
- * @see EditorActionBarContributor#contributeToMenu(IMenuManager)
- */
- public void contributeToMenu(IMenuManager menu) {
-
- super.contributeToMenu(menu);
- if (fContentAssistMenuListener != null)
- fContentAssistMenuListener.dispose();
-
- IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
- if (editMenu != null) {
- editMenu.add(fChangeEncodingAction);
- IMenuManager caMenu= new MenuManager(JavaEditorMessages.BasicEditorActionContributor_specific_content_assist_menu, "specific_content_assist"); //$NON-NLS-1$
- editMenu.insertAfter(ITextEditorActionConstants.GROUP_ASSIST, caMenu);
-
- caMenu.add(fRetargetContentAssist);
- Collection descriptors= CompletionProposalComputerRegistry.getDefault().getProposalCategories();
- List specificAssistActions= new ArrayList(descriptors.size());
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- final CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- if (cat.hasComputers()) {
- IAction caAction= new SpecificContentAssistAction(cat);
- caMenu.add(caAction);
- specificAssistActions.add(caAction);
- }
- }
- fSpecificAssistActions= (SpecificContentAssistAction[]) specificAssistActions.toArray(new SpecificContentAssistAction[specificAssistActions.size()]);
- if (fSpecificAssistActions.length > 0) {
- fContentAssistMenuListener= new MenuListener(caMenu);
- caMenu.addMenuListener(fContentAssistMenuListener);
- }
- caMenu.add(new Separator("context_info")); //$NON-NLS-1$
- caMenu.add(fContextInformation);
-
- editMenu.appendToGroup(ITextEditorActionConstants.GROUP_ASSIST, fQuickAssistAction);
- }
- }
-
- /*
- * @see IEditorActionBarContributor#setActiveEditor(IEditorPart)
- */
- public void setActiveEditor(IEditorPart part) {
- super.setActiveEditor(part);
-
- ITextEditor textEditor= null;
- if (part instanceof ITextEditor)
- textEditor= (ITextEditor) part;
-
- fContentAssist.setAction(getAction(textEditor, "ContentAssistProposal")); //$NON-NLS-1$
- fContextInformation.setAction(getAction(textEditor, "ContentAssistContextInformation")); //$NON-NLS-1$
- fQuickAssistAction.setAction(getAction(textEditor, ITextEditorActionConstants.QUICK_ASSIST));
-
- if (fSpecificAssistActions != null) {
- for (int i= 0; i < fSpecificAssistActions.length; i++) {
- SpecificContentAssistAction assistAction= fSpecificAssistActions[i];
- assistAction.setActiveEditor(part);
- }
- }
-
- fChangeEncodingAction.setAction(getAction(textEditor, ITextEditorActionConstants.CHANGE_ENCODING));
-
- IActionBars actionBars= getActionBars();
- actionBars.setGlobalActionHandler(JdtActionConstants.SHIFT_RIGHT, getAction(textEditor, "ShiftRight")); //$NON-NLS-1$
- actionBars.setGlobalActionHandler(JdtActionConstants.SHIFT_LEFT, getAction(textEditor, "ShiftLeft")); //$NON-NLS-1$
-
- actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), getAction(textEditor, IDEActionFactory.ADD_TASK.getId()));
- actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), getAction(textEditor, IDEActionFactory.BOOKMARK.getId()));
- }
-
- /*
- * @see IEditorActionBarContributor#init(IActionBars, IWorkbenchPage)
- */
- public void init(IActionBars bars, IWorkbenchPage page) {
- super.init(bars, page);
- // register actions that have a dynamic editor.
- bars.setGlobalActionHandler(JdtActionConstants.CONTENT_ASSIST, fContentAssist);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.BasicJavaEditorActionContributor#dispose()
- *
- */
- public void dispose() {
- if (fRetargetContentAssist != null) {
- fRetargetContentAssist.dispose();
- fRetargetContentAssist= null;
- }
- if (fContentAssistMenuListener != null) {
- fContentAssistMenuListener.dispose();
- fContentAssistMenuListener= null;
- }
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicJavaEditorActionContributor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicJavaEditorActionContributor.java
deleted file mode 100644
index 52554114..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicJavaEditorActionContributor.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.actions.RetargetAction;
-import org.eclipse.ui.texteditor.BasicTextEditorActionContributor;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.RetargetTextEditorAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.CopyQualifiedNameAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.FoldingActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-/**
- * Common base class for action contributors for Java editors.
- */
-public class BasicJavaEditorActionContributor extends BasicTextEditorActionContributor {
-
- private List fPartListeners= new ArrayList();
-
- private TogglePresentationAction fTogglePresentation;
- private ToggleMarkOccurrencesAction fToggleMarkOccurrencesAction;
-
- private RetargetTextEditorAction fGotoMatchingBracket;
- private RetargetTextEditorAction fShowOutline;
- private RetargetTextEditorAction fOpenStructure;
- private RetargetTextEditorAction fOpenHierarchy;
-
- private RetargetTextEditorAction fRetargetShowInformationAction;
-
- private RetargetTextEditorAction fStructureSelectEnclosingAction;
- private RetargetTextEditorAction fStructureSelectNextAction;
- private RetargetTextEditorAction fStructureSelectPreviousAction;
- private RetargetTextEditorAction fStructureSelectHistoryAction;
-
- private RetargetTextEditorAction fGotoNextMemberAction;
- private RetargetTextEditorAction fGotoPreviousMemberAction;
-
- private RetargetTextEditorAction fRemoveOccurrenceAnnotationsAction;
-
- public BasicJavaEditorActionContributor() {
- super();
-
- ResourceBundle b= JavaEditorMessages.getBundleForConstructedKeys();
-
- fRetargetShowInformationAction= new RetargetTextEditorAction(b, "Editor.ShowInformation."); //$NON-NLS-1$
- fRetargetShowInformationAction.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_INFORMATION);
-
- // actions that are "contributed" to editors, they are considered belonging to the active editor
- fTogglePresentation= new TogglePresentationAction();
-
- fToggleMarkOccurrencesAction= new ToggleMarkOccurrencesAction();
-
- fGotoMatchingBracket= new RetargetTextEditorAction(b, "GotoMatchingBracket."); //$NON-NLS-1$
- fGotoMatchingBracket.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
-
- fShowOutline= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "ShowOutline."); //$NON-NLS-1$
- fShowOutline.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
-
- fOpenHierarchy= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "OpenHierarchy."); //$NON-NLS-1$
- fOpenHierarchy.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
-
- fOpenStructure= new RetargetTextEditorAction(JavaEditorMessages.getBundleForConstructedKeys(), "OpenStructure."); //$NON-NLS-1$
- fOpenStructure.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
-
- fStructureSelectEnclosingAction= new RetargetTextEditorAction(b, "StructureSelectEnclosing."); //$NON-NLS-1$
- fStructureSelectEnclosingAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
- fStructureSelectNextAction= new RetargetTextEditorAction(b, "StructureSelectNext."); //$NON-NLS-1$
- fStructureSelectNextAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
- fStructureSelectPreviousAction= new RetargetTextEditorAction(b, "StructureSelectPrevious."); //$NON-NLS-1$
- fStructureSelectPreviousAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
- fStructureSelectHistoryAction= new RetargetTextEditorAction(b, "StructureSelectHistory."); //$NON-NLS-1$
- fStructureSelectHistoryAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
-
- fGotoNextMemberAction= new RetargetTextEditorAction(b, "GotoNextMember."); //$NON-NLS-1$
- fGotoNextMemberAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
- fGotoPreviousMemberAction= new RetargetTextEditorAction(b, "GotoPreviousMember."); //$NON-NLS-1$
- fGotoPreviousMemberAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
-
- fRemoveOccurrenceAnnotationsAction= new RetargetTextEditorAction(b, "RemoveOccurrenceAnnotations."); //$NON-NLS-1$
- fRemoveOccurrenceAnnotationsAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
- }
-
- protected final void markAsPartListener(RetargetAction action) {
- fPartListeners.add(action);
- }
-
- /*
- * @see IEditorActionBarContributor#init(IActionBars, IWorkbenchPage)
- */
- public void init(IActionBars bars, IWorkbenchPage page) {
- Iterator e= fPartListeners.iterator();
- while (e.hasNext())
- page.addPartListener((RetargetAction) e.next());
-
- super.init(bars, page);
-
- bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation);
- bars.setGlobalActionHandler(IJavaEditorActionDefinitionIds.TOGGLE_MARK_OCCURRENCES, fToggleMarkOccurrencesAction);
-
- }
-
- /*
- * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
- */
- public void contributeToMenu(IMenuManager menu) {
-
- super.contributeToMenu(menu);
-
- IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
- if (editMenu != null) {
-
- MenuManager structureSelection= new MenuManager(JavaEditorMessages.ExpandSelectionMenu_label, "expandSelection"); //$NON-NLS-1$
- editMenu.insertAfter(ITextEditorActionConstants.SELECT_ALL, structureSelection);
- structureSelection.add(fStructureSelectEnclosingAction);
- structureSelection.add(fStructureSelectNextAction);
- structureSelection.add(fStructureSelectPreviousAction);
- structureSelection.add(fStructureSelectHistoryAction);
-
- editMenu.appendToGroup(ITextEditorActionConstants.GROUP_INFORMATION, fRetargetShowInformationAction);
- }
-
- IMenuManager navigateMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE);
- if (navigateMenu != null) {
- navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, fShowOutline);
- navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, fOpenHierarchy);
- }
-
- IMenuManager gotoMenu= menu.findMenuUsingPath("navigate/goTo"); //$NON-NLS-1$
- if (gotoMenu != null) {
- gotoMenu.add(new Separator("additions2")); //$NON-NLS-1$
- gotoMenu.appendToGroup("additions2", fGotoPreviousMemberAction); //$NON-NLS-1$
- gotoMenu.appendToGroup("additions2", fGotoNextMemberAction); //$NON-NLS-1$
- gotoMenu.appendToGroup("additions2", fGotoMatchingBracket); //$NON-NLS-1$
- }
- }
-
- /*
- * @see EditorActionBarContributor#setActiveEditor(IEditorPart)
- */
- public void setActiveEditor(IEditorPart part) {
-
- super.setActiveEditor(part);
-
- ITextEditor textEditor= null;
- if (part instanceof ITextEditor)
- textEditor= (ITextEditor)part;
-
- fTogglePresentation.setEditor(textEditor);
- fToggleMarkOccurrencesAction.setEditor(textEditor);
-
- fGotoMatchingBracket.setAction(getAction(textEditor, GotoMatchingBracketAction.GOTO_MATCHING_BRACKET));
- fShowOutline.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.SHOW_OUTLINE));
- fOpenHierarchy.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.OPEN_HIERARCHY));
- fOpenStructure.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE));
-
- fStructureSelectEnclosingAction.setAction(getAction(textEditor, StructureSelectionAction.ENCLOSING));
- fStructureSelectNextAction.setAction(getAction(textEditor, StructureSelectionAction.NEXT));
- fStructureSelectPreviousAction.setAction(getAction(textEditor, StructureSelectionAction.PREVIOUS));
- fStructureSelectHistoryAction.setAction(getAction(textEditor, StructureSelectionAction.HISTORY));
-
- fGotoNextMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.NEXT_MEMBER));
- fGotoPreviousMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.PREVIOUS_MEMBER));
-
- fRemoveOccurrenceAnnotationsAction.setAction(getAction(textEditor, "RemoveOccurrenceAnnotations")); //$NON-NLS-1$
- fRetargetShowInformationAction.setAction(getAction(textEditor, ITextEditorActionConstants.SHOW_INFORMATION));
-
- if (part instanceof JavaEditor) {
- JavaEditor javaEditor= (JavaEditor) part;
- javaEditor.getActionGroup().fillActionBars(getActionBars());
- FoldingActionGroup foldingActions= javaEditor.getFoldingActionGroup();
- if (foldingActions != null)
- foldingActions.updateActionBars();
- }
-
- IActionBars actionBars= getActionBars();
- IStatusLineManager manager= actionBars.getStatusLineManager();
- manager.setMessage(null);
- manager.setErrorMessage(null);
-
- /** The global actions to be connected with editor actions */
- IAction action= getAction(textEditor, ITextEditorActionConstants.NEXT);
- actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, action);
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, action);
- action= getAction(textEditor, ITextEditorActionConstants.PREVIOUS);
- actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, action);
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, action);
- action= getAction(textEditor, IJavaEditorActionConstants.COPY_QUALIFIED_NAME);
- actionBars.setGlobalActionHandler(CopyQualifiedNameAction.ACTION_HANDLER_ID, action);
- }
-
- /*
- * @see IEditorActionBarContributor#dispose()
- */
- public void dispose() {
-
- Iterator e= fPartListeners.iterator();
- while (e.hasNext())
- getPage().removePartListener((RetargetAction) e.next());
- fPartListeners.clear();
-
- setActiveEditor(null);
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileDocumentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileDocumentProvider.java
deleted file mode 100644
index cf9274b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileDocumentProvider.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ISynchronizable;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.editors.text.FileDocumentProvider;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IResourceLocator;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-/**
- * A document provider for class files. Class files can be either inside
- */
-public class ClassFileDocumentProvider extends FileDocumentProvider {
-
- /**
- * An input change listener to request the editor to reread the input.
- */
- public interface InputChangeListener {
- void inputChanged(IClassFileEditorInput input);
- }
-
- /**
- * Synchronizes the document with external resource changes.
- */
- protected class ClassFileSynchronizer implements IElementChangedListener {
-
- protected IClassFileEditorInput fInput;
- protected IPackageFragmentRoot fPackageFragmentRoot;
-
- /**
- * Default constructor.
- */
- public ClassFileSynchronizer(IClassFileEditorInput input) {
-
- fInput= input;
-
- IJavaScriptElement parent= fInput.getClassFile().getParent();
- while (parent != null && !(parent instanceof IPackageFragmentRoot)) {
- parent= parent.getParent();
- }
- fPackageFragmentRoot= (IPackageFragmentRoot) parent;
- }
-
- /**
- * Installs the synchronizer.
- */
- public void install() {
- JavaScriptCore.addElementChangedListener(this);
- }
-
- /**
- * Uninstalls the synchronizer.
- */
- public void uninstall() {
- JavaScriptCore.removeElementChangedListener(this);
- }
-
- /*
- * @see IElementChangedListener#elementChanged
- */
- public void elementChanged(ElementChangedEvent e) {
- check(fPackageFragmentRoot, e.getDelta());
- }
-
- /**
- * Recursively check whether the class file has been deleted.
- * Returns true if delta processing can be stopped.
- */
- protected boolean check(IPackageFragmentRoot input, IJavaScriptElementDelta delta) {
- IJavaScriptElement element= delta.getElement();
-
- if ((delta.getKind() & IJavaScriptElementDelta.REMOVED) != 0 || (delta.getFlags() & IJavaScriptElementDelta.F_CLOSED) != 0) {
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=19023
- if (element.equals(input.getJavaScriptProject()) || element.equals(input)) {
- handleDeleted(fInput);
- return true;
- }
- }
-
- if (((delta.getFlags() & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) && input.equals(element)) {
- handleDeleted(fInput);
- return true;
- }
-
- if (((delta.getFlags() & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) && input.equals(element)) {
- handleDeleted(fInput);
- return true;
- }
-
- IJavaScriptElementDelta[] subdeltas= delta.getAffectedChildren();
- for (int i= 0; i < subdeltas.length; i++) {
- if (check(input, subdeltas[i]))
- return true;
- }
-
- if ((delta.getFlags() & IJavaScriptElementDelta.F_SOURCEDETACHED) != 0 ||
- (delta.getFlags() & IJavaScriptElementDelta.F_SOURCEATTACHED) != 0)
- {
- IClassFile file= fInput != null ? fInput.getClassFile() : null;
- IJavaScriptProject project= input != null ? input.getJavaScriptProject() : null;
-
- boolean isOnClasspath= false;
- if (file != null && project != null)
- isOnClasspath= project.isOnIncludepath(file);
-
- if (isOnClasspath) {
- fireInputChanged(fInput);
- return false;
- } else {
- handleDeleted(fInput);
- return true;
- }
- }
-
- return false;
- }
- }
-
- /**
- * Correcting the visibility of <code>FileSynchronizer</code>.
- */
- protected class _FileSynchronizer extends FileSynchronizer {
- public _FileSynchronizer(IFileEditorInput fileEditorInput) {
- super(fileEditorInput);
- }
- }
-
- /**
- * Bundle of all required informations.
- */
- protected class ClassFileInfo extends FileInfo {
-
- ClassFileSynchronizer fClassFileSynchronizer= null;
-
- ClassFileInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer) {
- super(document, model, fileSynchronizer);
- }
-
- ClassFileInfo(IDocument document, IAnnotationModel model, ClassFileSynchronizer classFileSynchronizer) {
- super(document, model, null);
- fClassFileSynchronizer= classFileSynchronizer;
- }
- }
-
- /** Input change listeners. */
- private List fInputListeners= new ArrayList();
-
- /**
- * Creates a new document provider.
- */
- public ClassFileDocumentProvider() {
- super();
- }
-
- /*
- * @see StorageDocumentProvider#setDocumentContent(IDocument, IEditorInput)
- */
- protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
- if (editorInput instanceof IClassFileEditorInput) {
- IClassFile classFile= ((IClassFileEditorInput) editorInput).getClassFile();
- String source= classFile.getSource();
- if (source == null)
- source= ""; //$NON-NLS-1$
- classFile.makeConsistent(getProgressMonitor());
- document.set(source);
- return true;
- }
- return super.setDocumentContent(document, editorInput, encoding);
- }
-
- /**
- * Creates an annotation model derived from the given class file editor input.
- *
- * @param classFileEditorInput the editor input from which to query the annotations
- * @return the created annotation model
- * @exception CoreException if the editor input could not be accessed
- */
- protected IAnnotationModel createClassFileAnnotationModel(IClassFileEditorInput classFileEditorInput) throws CoreException {
- IResource resource= null;
- IClassFile classFile= classFileEditorInput.getClassFile();
-
- IResourceLocator locator= (IResourceLocator) classFile.getAdapter(IResourceLocator.class);
- if (locator != null)
- resource= locator.getContainingResource(classFile);
-
- if (resource != null) {
- ClassFileMarkerAnnotationModel model= new ClassFileMarkerAnnotationModel(resource);
- model.setClassFile(classFile);
- return model;
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.ui.editors.text.StorageDocumentProvider#createEmptyDocument()
- *
- */
- protected IDocument createEmptyDocument() {
- IDocument document= FileBuffers.getTextFileBufferManager().createEmptyDocument(null, LocationKind.IFILE);
- if (document instanceof ISynchronizable)
- ((ISynchronizable)document).setLockObject(new Object());
- return document;
- }
-
- /*
- * @see AbstractDocumentProvider#createDocument(Object)
- */
- protected IDocument createDocument(Object element) throws CoreException {
- IDocument document= super.createDocument(element);
- if (document != null) {
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- }
- return document;
- }
-
- public String getEncoding(Object element) {
- if (element instanceof IStorageEditorInput) {
- StorageInfo info= (StorageInfo) getElementInfo(element);
- if (info != null)
- return info.fEncoding;
- return getPersistedEncoding(element);
- }
- if(element instanceof InternalClassFileEditorInput){
- InternalClassFileEditorInput input = (InternalClassFileEditorInput)element;
- IClassFile file = input.getClassFile();
- if(file!=null){
- String fileEncoding = null;
- try {
- IResource resource =( file.getResource());
- fileEncoding = (resource==null|| !(resource instanceof IFile))?null:((IFile)resource).getCharset();
- } catch (CoreException e) {
- // resource not in workspace, use default encoding.
- }
- return fileEncoding;
- }
- }
- return null;
- }
-
- /*
- * @see AbstractDocumentProvider#createElementInfo(Object)
- */
- protected ElementInfo createElementInfo(Object element) throws CoreException {
-
- if (element instanceof IClassFileEditorInput) {
-
- IClassFileEditorInput input = (IClassFileEditorInput) element;
- ExternalClassFileEditorInput external= null;
- if (input instanceof ExternalClassFileEditorInput)
- external= (ExternalClassFileEditorInput) input;
-
- if (external != null) {
- try {
- refreshFile(external.getFile());
- } catch (CoreException x) {
- handleCoreException(x, JavaEditorMessages.ClassFileDocumentProvider_error_createElementInfo);
- }
- }
-
- IDocument d= createDocument(input);
- IAnnotationModel m= createClassFileAnnotationModel(input);
-
- if (external != null) {
- ClassFileInfo info= new ClassFileInfo(d, m, (_FileSynchronizer) null);
- info.fModificationStamp= computeModificationStamp(external.getFile());
- info.fEncoding= getPersistedEncoding(element);
- return info;
- } else if (input instanceof InternalClassFileEditorInput) {
- ClassFileSynchronizer s= new ClassFileSynchronizer(input);
- s.install();
- ClassFileInfo info= new ClassFileInfo(d, m, s);
- info.fEncoding= getPersistedEncoding(element);
- return info;
- }
- }
-
- return null;
- }
-
- /*
- * @see FileDocumentProvider#disposeElementInfo(Object, ElementInfo)
- */
- protected void disposeElementInfo(Object element, ElementInfo info) {
- ClassFileInfo classFileInfo= (ClassFileInfo) info;
- if (classFileInfo.fClassFileSynchronizer != null) {
- classFileInfo.fClassFileSynchronizer.uninstall();
- classFileInfo.fClassFileSynchronizer= null;
- }
-
- super.disposeElementInfo(element, info);
- }
-
- /*
- * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument)
- */
- protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document) throws CoreException {
- }
-
-
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProviderExtension3#isSynchronized(java.lang.Object)
- *
- */
- public boolean isSynchronized(Object element) {
- Object elementInfo= getElementInfo(element);
- if (elementInfo instanceof ClassFileInfo) {
- IClassFileEditorInput input= (IClassFileEditorInput)element;
- IResource resource;
- try {
- resource= input.getClassFile().getUnderlyingResource();
- } catch (JavaScriptModelException e) {
- return true;
- }
- return resource == null || resource.isSynchronized(IResource.DEPTH_ZERO);
- }
- return false;
- }
-
- /**
- * Handles the deletion of the element underlying the given class file editor input.
- * @param input the editor input
- */
- protected void handleDeleted(IClassFileEditorInput input) {
- fireElementDeleted(input);
- }
-
- /**
- * Fires input changes to input change listeners.
- */
- protected void fireInputChanged(IClassFileEditorInput input) {
- List list= new ArrayList(fInputListeners);
- for (Iterator i = list.iterator(); i.hasNext();)
- ((InputChangeListener) i.next()).inputChanged(input);
- }
-
- /**
- * Adds an input change listener.
- */
- public void addInputChangeListener(InputChangeListener listener) {
- fInputListeners.add(listener);
- }
-
- /**
- * Removes an input change listener.
- */
- public void removeInputChangeListener(InputChangeListener listener) {
- fInputListeners.remove(listener);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditor.java
deleted file mode 100644
index 72ab8c56..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditor.java
+++ /dev/null
@@ -1,871 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.IWidgetTokenKeeper;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StackLayout;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-/**
- * Java specific text editor.
- */
-public class ClassFileEditor extends JavaEditor implements ClassFileDocumentProvider.InputChangeListener {
-
-
- /**
- * A form to attach source to a class file.
- */
- private class SourceAttachmentForm implements IPropertyChangeListener {
-
- private final IClassFile fFile;
- private Composite fComposite;
- private Color fBackgroundColor;
- private Color fForegroundColor;
- private Color fSeparatorColor;
- private List fBannerLabels= new ArrayList();
- private List fHeaderLabels= new ArrayList();
- private Font fFont;
-
- /**
- * Creates a source attachment form for a class file.
- *
- * @param file the class file
- */
- public SourceAttachmentForm(IClassFile file) {
- fFile= file;
- }
-
- /**
- * Returns the package fragment root of this file.
- *
- * @param file the class file
- * @return the package fragment root of the given class file
- */
- private IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) {
-
- IJavaScriptElement element= file.getParent();
- while (element != null && element.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- element= element.getParent();
-
- return (IPackageFragmentRoot) element;
- }
-
- /**
- * Creates the control of the source attachment form.
- *
- * @param parent the parent composite
- * @return the creates source attachment form
- */
- public Control createControl(Composite parent) {
-
- Display display= parent.getDisplay();
- fBackgroundColor= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
- fForegroundColor= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
- fSeparatorColor= new Color(display, 152, 170, 203);
-
- JFaceResources.getFontRegistry().addListener(this);
-
- fComposite= createComposite(parent);
- fComposite.setLayout(new GridLayout());
- fComposite.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- JFaceResources.getFontRegistry().removeListener(SourceAttachmentForm.this);
- fComposite= null;
- fSeparatorColor.dispose();
- fSeparatorColor= null;
- fBannerLabels.clear();
- fHeaderLabels.clear();
- if (fFont != null) {
- fFont.dispose();
- fFont= null;
- }
- }
- });
-
- createTitleLabel(fComposite, JavaEditorMessages.SourceAttachmentForm_title);
- createLabel(fComposite, null);
- createLabel(fComposite, null);
-
- createHeadingLabel(fComposite, JavaEditorMessages.SourceAttachmentForm_heading);
-
- Composite separator= createCompositeSeparator(fComposite);
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.heightHint= 2;
- separator.setLayoutData(data);
-
-// try {
-// IPackageFragmentRoot root= getPackageFragmentRoot(fFile);
-// if (root != null) {
-// createSourceAttachmentControls(fComposite, root);
-// }
-// } catch (JavaScriptModelException e) {
-// String title= JavaEditorMessages.SourceAttachmentForm_error_title;
-// String message= JavaEditorMessages.SourceAttachmentForm_error_message;
-// ExceptionHandler.handle(e, fComposite.getShell(), title, message);
-// }
-
- separator= createCompositeSeparator(fComposite);
- data= new GridData(GridData.FILL_HORIZONTAL);
- data.heightHint= 2;
- separator.setLayoutData(data);
-
- fNoSourceTextWidget= createCodeView(fComposite);
- data= new GridData(GridData.FILL_BOTH);
- fNoSourceTextWidget.setLayoutData(data);
-
-// updateCodeView(fNoSourceTextWidget, fFile);
-
- return fComposite;
- }
-
-// private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaScriptModelException {
-// IIncludePathEntry entry;
-// try {
-// entry= root.getRawIncludepathEntry();
-// } catch (JavaScriptModelException ex) {
-// if (ex.isDoesNotExist())
-// entry= null;
-// else
-// throw ex;
-// }
-// IPath containerPath= null;
-//
-// if (entry == null || root.getKind() != IPackageFragmentRoot.K_BINARY) {
-// createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSource, fFile.getDisplayName()));
-// return;
-// }
-//
-// IJavaScriptProject jproject= root.getJavaScriptProject();
-// if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
-// containerPath= entry.getPath();
-// JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
-// IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
-// if (initializer == null || container == null) {
-// createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_cannotconfigure, containerPath.toString()));
-// return;
-// }
-// String containerName= container.getDescription();
-// IStatus status= initializer.getSourceAttachmentStatus(containerPath, jproject);
-// if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
-// createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_notsupported, containerName));
-// return;
-// }
-// if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_READ_ONLY) {
-// createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_readonly, containerName));
-// return;
-// }
-// entry= JavaModelUtil.findEntryInContainer(container, root.getPath());
-// Assert.isNotNull(entry);
-// }
-//
-//
-// Button button;
-//
-// IPath path= entry.getSourceAttachmentPath();
-// if (path == null || path.isEmpty()) {
-// createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSourceAttachment, root.getElementName()));
-// createLabel(composite, JavaEditorMessages.SourceAttachmentForm_message_pressButtonToAttach);
-// createLabel(composite, null);
-//
-// button= createButton(composite, JavaEditorMessages.SourceAttachmentForm_button_attachSource);
-//
-// } else {
-// createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSourceInAttachment, fFile.getDisplayName()));
-// createLabel(composite, JavaEditorMessages.SourceAttachmentForm_message_pressButtonToChange);
-// createLabel(composite, null);
-//
-// button= createButton(composite, JavaEditorMessages.SourceAttachmentForm_button_changeAttachedSource);
-// }
-//
-// button.addSelectionListener(getButtonListener(entry, containerPath, jproject));
-// }
-//
-// private SelectionListener getButtonListener(final IIncludePathEntry entry, final IPath containerPath, final IJavaScriptProject jproject) {
-// return new SelectionListener() {
-// public void widgetSelected(SelectionEvent event) {
-// Shell shell= getSite().getShell();
-// try {
-// IIncludePathEntry result= BuildPathDialogAccess.configureSourceAttachment(shell, entry);
-// if (result != null) {
-// applySourceAttachment(shell, result, jproject, containerPath);
-// verifyInput(getEditorInput());
-// }
-// } catch (CoreException e) {
-// String title= JavaEditorMessages.SourceAttachmentForm_error_title;
-// String message= JavaEditorMessages.SourceAttachmentForm_error_message;
-// ExceptionHandler.handle(e, shell, title, message);
-// }
-// }
-//
-// public void widgetDefaultSelected(SelectionEvent e) {}
-// };
-// }
-
- protected void applySourceAttachment(Shell shell, IIncludePathEntry newEntry, IJavaScriptProject project, IPath containerPath) {
- try {
- IRunnableWithProgress runnable= SourceAttachmentBlock.getRunnable(shell, newEntry, project, containerPath);
- PlatformUI.getWorkbench().getProgressService().run(true, true, runnable);
-
- } catch (InvocationTargetException e) {
- String title= JavaEditorMessages.SourceAttachmentForm_attach_error_title;
- String message= JavaEditorMessages.SourceAttachmentForm_attach_error_message;
- ExceptionHandler.handle(e, shell, title, message);
-
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
-
- for (Iterator iterator = fBannerLabels.iterator(); iterator.hasNext();) {
- Label label = (Label) iterator.next();
- label.setFont(JFaceResources.getBannerFont());
- }
-
- for (Iterator iterator = fHeaderLabels.iterator(); iterator.hasNext();) {
- Label label = (Label) iterator.next();
- label.setFont(JFaceResources.getHeaderFont());
- }
-
- fComposite.layout(true);
- fComposite.redraw();
- }
-
- // --- copied from org.eclipse.update.ui.forms.internal.FormWidgetFactory
-
- private Composite createComposite(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setBackground(fBackgroundColor);
- // composite.addMouseListener(new MouseAdapter() {
- // public void mousePressed(MouseEvent e) {
- // ((Control) e.widget).setFocus();
- // }
- // });
- return composite;
- }
-
- private Composite createCompositeSeparator(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setBackground(fSeparatorColor);
- return composite;
- }
-
- private StyledText createCodeView(Composite parent) {
- int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION;
- StyledText styledText= new StyledText(parent, styles);
- styledText.setBackground(fBackgroundColor);
- styledText.setForeground(fForegroundColor);
- styledText.setEditable(false);
- return styledText;
- }
-
- private Label createLabel(Composite parent, String text) {
- Label label= new Label(parent, SWT.WRAP);
- if (text != null)
- label.setText(text);
- label.setBackground(fBackgroundColor);
- label.setForeground(fForegroundColor);
- GridData gd= new GridData();
- gd.widthHint= new PixelConverter(label).convertWidthInCharsToPixels(80);
- label.setLayoutData(gd);
- return label;
- }
-
- private Label createTitleLabel(Composite parent, String text) {
- Label label = new Label(parent, SWT.NONE);
- if (text != null)
- label.setText(text);
- label.setBackground(fBackgroundColor);
- label.setForeground(fForegroundColor);
- label.setFont(JFaceResources.getHeaderFont());
- fHeaderLabels.add(label);
- return label;
- }
-
- private Label createHeadingLabel(Composite parent, String text) {
- Label label = new Label(parent, SWT.NONE);
- if (text != null)
- label.setText(text);
- label.setBackground(fBackgroundColor);
- label.setForeground(fForegroundColor);
- label.setFont(JFaceResources.getBannerFont());
- fBannerLabels.add(label);
- return label;
- }
-
- private Button createButton(Composite parent, String text) {
- Button button = new Button(parent, SWT.FLAT);
- button.setBackground(fBackgroundColor);
- button.setForeground(fForegroundColor);
- if (text != null)
- button.setText(text);
- return button;
- }
-
-// private void updateCodeView(StyledText styledText, IClassFile classFile) {
-// String content= null;
-// ClassFileBytesDisassembler disassembler= ToolFactory.createDefaultClassFileBytesDisassembler();
-// try {
-// content= disassembler.disassemble(classFile.getBytes(), "\n", ClassFileBytesDisassembler.DETAILED); //$NON-NLS-1$
-// } catch (JavaScriptModelException ex) {
-// JavaScriptPlugin.log(ex.getStatus());
-// } catch (ClassFormatException ex) {
-// JavaScriptPlugin.log(ex);
-// }
-// styledText.setText(content == null ? "" : content); //$NON-NLS-1$
-// }
- }
-
- /**
- * Updater that takes care of minimizing changes of the editor input.
- */
- private class InputUpdater implements Runnable {
-
- /** Has the runnable already been posted? */
- private boolean fPosted= false;
- /** Editor input */
- private IClassFileEditorInput fClassFileEditorInput;
-
-
- public InputUpdater() {
- }
-
- /*
- * @see Runnable#run()
- */
- public void run() {
-
- IClassFileEditorInput input;
- synchronized (this) {
- input= fClassFileEditorInput;
- }
-
- try {
-
- if (getSourceViewer() != null)
- setInput(input);
-
- } finally {
- synchronized (this) {
- fPosted= false;
- }
- }
- }
-
- /**
- * Posts this runnable into the event queue if not already there.
- *
- * @param input the input to be set when executed
- */
- public void post(IClassFileEditorInput input) {
-
- synchronized(this) {
- if (fPosted) {
- if (input != null && input.equals(fClassFileEditorInput))
- fClassFileEditorInput= input;
- return;
- }
- }
-
- if (input != null && input.equals(getEditorInput())) {
- ISourceViewer viewer= getSourceViewer();
- if (viewer != null) {
- StyledText textWidget= viewer.getTextWidget();
- if (textWidget != null && !textWidget.isDisposed()) {
- synchronized (this) {
- fPosted= true;
- fClassFileEditorInput= input;
- }
- textWidget.getDisplay().asyncExec(this);
- }
- }
- }
- }
- }
-
-
- private StackLayout fStackLayout;
- private Composite fParent;
-
- private Composite fViewerComposite;
- private Control fSourceAttachmentForm;
-
- private CompositeActionGroup fContextMenuGroup;
-
- private InputUpdater fInputUpdater= new InputUpdater();
-
- /**
- * The copy action used when there's attached source.
- *
- */
- private IAction fSourceCopyAction;
- /**
- * The Select All action used when there's attached source.
- *
- */
- private IAction fSelectAllAction;
-
- /**
- * StyledText widget used to show the disassembled code.
- * if there's no source.
- *
- *
- */
- private StyledText fNoSourceTextWidget;
-
-
- /**
- * Default constructor.
- */
- public ClassFileEditor() {
- super();
- setDocumentProvider(JavaScriptPlugin.getDefault().getClassFileDocumentProvider());
- setEditorContextMenuId("#ClassFileEditorContext"); //$NON-NLS-1$
- setRulerContextMenuId("#ReadOnlyJavaScriptRulerContext"); //$NON-NLS-1$
- setOutlinerContextMenuId("#ClassFileOutlinerContext"); //$NON-NLS-1$
- // don't set help contextId, we install our own help context
- }
-
- /*
- * @see AbstractTextEditor#createActions()
- */
- protected void createActions() {
- super.createActions();
-
- setAction(ITextEditorActionConstants.SAVE, null);
- setAction(ITextEditorActionConstants.REVERT_TO_SAVED, null);
-
- fSourceCopyAction= getAction(ITextEditorActionConstants.COPY);
- fSelectAllAction= getAction(ITextEditorActionConstants.SELECT_ALL);
-
- final ActionGroup group= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT, true);
- fActionGroups.addGroup(group);
- fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {group});
-
- /*
- * 1GF82PL: ITPJUI:ALL - Need to be able to add bookmark to class file
- *
- * // replace default action with class file specific ones
- *
- * setAction(ITextEditorActionConstants.BOOKMARK, new AddClassFileMarkerAction("AddBookmark.", this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
- * setAction(ITextEditorActionConstants.ADD_TASK, new AddClassFileMarkerAction("AddTask.", this, IMarker.TASK, false)); //$NON-NLS-1$
- * setAction(ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS, new ClassFileMarkerRulerAction("ManageBookmarks.", getVerticalRuler(), this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
- * setAction(ITextEditorActionConstants.RULER_MANAGE_TASKS, new ClassFileMarkerRulerAction("ManageTasks.", getVerticalRuler(), this, IMarker.TASK, true)); //$NON-NLS-1$
- */
- }
-
- /*
- * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
- */
- public void editorContextMenuAboutToShow(IMenuManager menu) {
- super.editorContextMenuAboutToShow(menu);
-
- ActionContext context= new ActionContext(getSelectionProvider().getSelection());
- fContextMenuGroup.setContext(context);
- fContextMenuGroup.fillContextMenu(menu);
- fContextMenuGroup.setContext(null);
- }
-
- /*
- * @see JavaEditor#getElementAt(int)
- */
- protected IJavaScriptElement getElementAt(int offset) {
- if (getEditorInput() instanceof IClassFileEditorInput) {
- try {
- IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
- return input.getClassFile().getElementAt(offset);
- } catch (JavaScriptModelException x) {
- }
- }
- return null;
- }
-
- /*
- * @see JavaEditor#getCorrespondingElement(IJavaScriptElement)
- */
- protected IJavaScriptElement getCorrespondingElement(IJavaScriptElement element) {
- if (getEditorInput() instanceof IClassFileEditorInput) {
- IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
- IJavaScriptElement parent= element.getAncestor(IJavaScriptElement.CLASS_FILE);
- if (input.getClassFile().equals(parent))
- return element;
- }
- return null;
- }
-
- /*
- * 1GEPKT5: ITPJUI:Linux - Source in editor for external classes is editable
- * Removed methods isSaveOnClosedNeeded and isDirty.
- * Added method isEditable.
- */
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditable()
- */
- public boolean isEditable() {
- return false;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditorInputReadOnly()
- *
- */
- public boolean isEditorInputReadOnly() {
- return true;
- }
-
- /**
- * Translates the given editor input into an <code>ExternalClassFileEditorInput</code>
- * if it is a file editor input representing an external class file.
- *
- * @param input the editor input to be transformed if necessary
- * @return the transformed editor input
- */
- protected IEditorInput transformEditorInput(IEditorInput input) {
-
- if (input instanceof IFileEditorInput) {
- IFile file= ((IFileEditorInput) input).getFile();
- IClassFileEditorInput classFileInput= new ExternalClassFileEditorInput(file);
- if (classFileInput.getClassFile() != null)
- input= classFileInput;
- }
-
- return input;
- }
-
- /*
- * @see AbstractTextEditor#doSetInput(IEditorInput)
- */
- protected void doSetInput(IEditorInput input) throws CoreException {
- uninstallOccurrencesFinder();
-
- input= transformEditorInput(input);
- if (!(input instanceof IClassFileEditorInput))
- throw new CoreException(JavaUIStatus.createError(
- IJavaScriptModelStatusConstants.INVALID_RESOURCE_TYPE,
- JavaEditorMessages.ClassFileEditor_error_invalid_input_message,
- null));
-
- JavaScriptModelException e= probeInputForSource(input);
- if (e != null) {
- IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
- IClassFile file= classFileEditorInput.getClassFile();
- IJavaScriptProject javaProject= file.getJavaScriptProject();
- if (!javaProject.exists() || !javaProject.isOnIncludepath(file)) {
- throw new CoreException(JavaUIStatus.createError(
- IJavaScriptModelStatusConstants.INVALID_RESOURCE,
- JavaEditorMessages.ClassFileEditor_error_classfile_not_on_classpath,
- null));
- } else {
- throw e;
- }
- }
-
- IDocumentProvider documentProvider= getDocumentProvider();
- if (documentProvider instanceof ClassFileDocumentProvider)
- ((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
-
- super.doSetInput(input);
-
- documentProvider= getDocumentProvider();
- if (documentProvider instanceof ClassFileDocumentProvider)
- ((ClassFileDocumentProvider) documentProvider).addInputChangeListener(this);
-
- verifyInput(getEditorInput());
-
- final IJavaScriptElement inputElement= getInputJavaElement();
-
- Job job= new Job(JavaEditorMessages.OverrideIndicatorManager_intallJob) {
- /*
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
- *
- */
- protected IStatus run(IProgressMonitor monitor) {
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(inputElement, ASTProvider.WAIT_YES, null);
- if (fOverrideIndicatorManager != null)
- fOverrideIndicatorManager.reconciled(ast, true, monitor);
- if (fSemanticManager != null) {
- SemanticHighlightingReconciler reconciler= fSemanticManager.getReconciler();
- if (reconciler != null)
- reconciler.reconciled(ast, false, monitor);
- }
- if (isMarkingOccurrences())
- installOccurrencesFinder(false);
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.DECORATE);
- job.setSystem(true);
- job.schedule();
-
- }
-
- /*
- * @see IWorkbenchPart#createPartControl(Composite)
- */
- public void createPartControl(Composite parent) {
-
- fParent= new Composite(parent, SWT.NONE);
- fStackLayout= new StackLayout();
- fParent.setLayout(fStackLayout);
-
- fViewerComposite= new Composite(fParent, SWT.NONE);
- fViewerComposite.setLayout(new FillLayout());
-
- super.createPartControl(fViewerComposite);
-
- fStackLayout.topControl= fViewerComposite;
- fParent.layout();
-
- try {
- verifyInput(getEditorInput());
- } catch (CoreException e) {
- String title= JavaEditorMessages.ClassFileEditor_error_title;
- String message= JavaEditorMessages.ClassFileEditor_error_message;
- ExceptionHandler.handle(e, fParent.getShell(), title, message);
- }
- }
-
- private JavaScriptModelException probeInputForSource(IEditorInput input) {
- if (input == null)
- return null;
-
- IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
- IClassFile file= classFileEditorInput.getClassFile();
-
- try {
- file.getSourceRange();
- } catch (JavaScriptModelException e) {
- return e;
- }
-
- return null;
- }
-
- /**
- * Checks if the class file input has no source attached. If so, a source attachment form is shown.
- *
- * @param input the editor input
- * @throws JavaScriptModelException if an exception occurs while accessing its corresponding resource
- */
- private void verifyInput(IEditorInput input) throws JavaScriptModelException {
-
- if (fParent == null || input == null)
- return;
-
- IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
- IClassFile file= classFileEditorInput.getClassFile();
-
- IAction copyQualifiedName= getAction(IJavaEditorActionConstants.COPY_QUALIFIED_NAME);
-
- boolean wasUsingSourceCopyAction= fSourceCopyAction == getAction(ITextEditorActionConstants.COPY);
-
- // show source attachment form if no source found
- if (file.getSourceRange() == null) {
-
- // dispose old source attachment form
- if (fSourceAttachmentForm != null)
- fSourceAttachmentForm.dispose();
-
- SourceAttachmentForm form= new SourceAttachmentForm(file);
- fSourceAttachmentForm= form.createControl(fParent);
-
- fStackLayout.topControl= fSourceAttachmentForm;
- fParent.layout();
-
- if (fNoSourceTextWidget != null) {
- // Copy action for the no attached source case
- final IAction copyAction= new Action() {
- public void run() {
- fNoSourceTextWidget.copy();
- }
- };
- copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
- setAction(ITextEditorActionConstants.COPY, copyAction);
- copyAction.setEnabled(fNoSourceTextWidget.getSelectionText().length() > 0);
- fNoSourceTextWidget.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- copyAction.setEnabled(fNoSourceTextWidget.getSelectionText().length() > 0);
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- // Select All action for the no attached source case
- final IAction selectAllAction= new Action() {
- public void run() {
- fNoSourceTextWidget.selectAll();
- copyAction.setEnabled(true);
- }
- };
- selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL);
- setAction(ITextEditorActionConstants.SELECT_ALL, selectAllAction);
- copyAction.setEnabled(fNoSourceTextWidget.getSelectionText().length() > 0);
- copyQualifiedName.setEnabled(false);
-
-
- }
-
- } else { // show source viewer
-
- if (fSourceAttachmentForm != null) {
- fSourceAttachmentForm.dispose();
- fSourceAttachmentForm= null;
-
- fStackLayout.topControl= fViewerComposite;
- fParent.layout();
- }
-
- setAction(ITextEditorActionConstants.COPY, fSourceCopyAction);
- setAction(ITextEditorActionConstants.SELECT_ALL, fSelectAllAction);
- copyQualifiedName.setEnabled(true);
-
- }
-
- IAction currentCopyAction= getAction(ITextEditorActionConstants.COPY);
- boolean isUsingSourceCopyAction= fSourceCopyAction == currentCopyAction;
- if (wasUsingSourceCopyAction != isUsingSourceCopyAction) {
- IActionBars actionBars= getEditorSite().getActionBars();
-
- if (isUsingSourceCopyAction) {
- createNavigationActions();
- } else {
- for (int i= 0; i < ACTION_MAP.length; i++) {
- IdMapEntry entry= ACTION_MAP[i];
- actionBars.setGlobalActionHandler(entry.getActionId(), null);
- setAction(entry.getActionId(), null);
- }
- }
-
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, currentCopyAction);
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.SELECT_ALL, getAction(ITextEditorActionConstants.SELECT_ALL));
- actionBars.updateActionBars();
- }
-
- }
-
- /*
- * @see ClassFileDocumentProvider.InputChangeListener#inputChanged(IClassFileEditorInput)
- */
- public void inputChanged(IClassFileEditorInput input) {
- fInputUpdater.post(input);
- }
-
- /*
- * @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
- */
- protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles, IPreferenceStore store) {
- return new JavaSourceViewer(parent, ruler, null, false, styles, store) {
-
- public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
- if (PlatformUI.getWorkbench().getHelpSystem().isContextHelpDisplayed())
- return false;
- return super.requestWidgetToken(requester);
- }
-
- public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
- if (PlatformUI.getWorkbench().getHelpSystem().isContextHelpDisplayed())
- return false;
- return super.requestWidgetToken(requester, priority);
- }
- };
- }
-
- /*
- * @see org.eclipse.ui.IWorkbenchPart#dispose()
- */
- public void dispose() {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18510
- IDocumentProvider documentProvider= getDocumentProvider();
- if (documentProvider instanceof ClassFileDocumentProvider)
- ((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
- super.dispose();
- }
-
- /*
- * @see org.eclipse.ui.IWorkbenchPart#setFocus()
- */
- public void setFocus() {
- super.setFocus();
-
- if (fSourceAttachmentForm != null && !fSourceAttachmentForm.isDisposed())
- fSourceAttachmentForm.setFocus();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorActionContributor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorActionContributor.java
deleted file mode 100644
index f10f3c70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorActionContributor.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-public class ClassFileEditorActionContributor extends BasicJavaEditorActionContributor {
-
- public ClassFileEditorActionContributor() {
- super();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorInputFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorInputFactory.java
deleted file mode 100644
index 7eb84270..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileEditorInputFactory.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IElementFactory;
-import org.eclipse.ui.IMemento;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-
-/**
- * The factory which is capable of recreating class file editor
- * inputs stored in a memento.
- */
-public class ClassFileEditorInputFactory implements IElementFactory {
-
- public final static String ID= "org.eclipse.wst.jsdt.ui.ClassFileEditorInputFactory"; //$NON-NLS-1$
- public final static String KEY= "org.eclipse.wst.jsdt.ui.ClassFileIdentifier"; //$NON-NLS-1$
-
- public ClassFileEditorInputFactory() {
- }
-
- /**
- * @see IElementFactory#createElement
- */
- public IAdaptable createElement(IMemento memento) {
- String identifier= memento.getString(KEY);
- if (identifier == null)
- return null;
-
- IJavaScriptElement element= JavaScriptCore.create(identifier);
- try {
- if (!element.exists() && element instanceof IClassFile) {
- /*
- * Let's try to find the class file,
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83221
- */
- IClassFile cf= (IClassFile)element;
- IType type= cf.getType(); // this will work, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=154667
- IJavaScriptProject project= element.getJavaScriptProject();
- if (project != null) {
- type= JavaModelUtil.findType(project, type.getFullyQualifiedName());
- if (type == null)
- return null;
- element= type.getParent();
- }
- }
- return EditorUtility.getEditorInput(element);
- } catch (JavaScriptModelException x) {
- // Don't report but simply return null
- return null;
- }
- }
-
- public static void saveState(IMemento memento, InternalClassFileEditorInput input) {
- IClassFile c= input.getClassFile();
- memento.putString(KEY, c.getHandleIdentifier());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerAnnotationModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerAnnotationModel.java
deleted file mode 100644
index b1626588..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerAnnotationModel.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-/**
- *
- */
-public class ClassFileMarkerAnnotationModel extends AbstractMarkerAnnotationModel implements IResourceChangeListener {
-
- protected IClassFile fClassFile;
- protected IWorkspace fWorkspace;
- protected IResource fMarkerResource;
- protected boolean fChangesApplied;
-
-
- public ClassFileMarkerAnnotationModel(IResource markerResource) {
- super();
- fMarkerResource= markerResource;
- fWorkspace= fMarkerResource.getWorkspace();
- }
-
- public void setClassFile(IClassFile classFile) {
- fClassFile= classFile;
- }
-
- /**
- * @see AbstractMarkerAnnotationModel#isAcceptable
- */
- protected boolean isAcceptable(IMarker marker) {
- try {
- return JavaScriptCore.isReferencedBy(fClassFile, marker);
- } catch (CoreException x) {
- handleCoreException(x, JavaEditorMessages.ClassFileMarkerAnnotationModel_error_isAcceptable);
- return false;
- }
- }
-
- protected boolean isAffected(IMarkerDelta markerDelta) {
- try {
- return JavaScriptCore.isReferencedBy(fClassFile, markerDelta);
- } catch (CoreException x) {
- handleCoreException(x, JavaEditorMessages.ClassFileMarkerAnnotationModel_error_isAffected);
- return false;
- }
- }
-
- /**
- * @see AbstractMarkerAnnotationModel#createMarkerAnnotation(IMarker)
- */
- protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
- return new JavaMarkerAnnotation(marker);
- }
-
- /**
- * @see AbstractMarkerAnnotationModel#listenToMarkerChanges(boolean)
- */
- protected void listenToMarkerChanges(boolean listen) {
- if (listen)
- fWorkspace.addResourceChangeListener(this);
- else
- fWorkspace.removeResourceChangeListener(this);
- }
-
- /**
- * @see AbstractMarkerAnnotationModel#deleteMarkers(IMarker[])
- */
- protected void deleteMarkers(IMarker[] markers) throws CoreException {
- // empty as class files are read only
- }
-
- /**
- * @see AbstractMarkerAnnotationModel#retrieveMarkers()
- */
- protected IMarker[] retrieveMarkers() throws CoreException {
- if (fMarkerResource != null) {
- IMarker[] workspaceMarkers= fWorkspace.getRoot().findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
- IMarker[] resourceMarkers= fMarkerResource.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
- int workspaceMarkersLength= workspaceMarkers.length;
- if (workspaceMarkersLength == 0)
- return resourceMarkers;
-
- int resourceMarkersLength= resourceMarkers.length;
- if (resourceMarkersLength == 0)
- return workspaceMarkers;
-
- IMarker[] result= new IMarker[resourceMarkersLength + workspaceMarkersLength];
- System.arraycopy(resourceMarkers, 0, result, 0, resourceMarkersLength);
- System.arraycopy(workspaceMarkers, 0, result, resourceMarkersLength, workspaceMarkersLength);
- return result;
- }
- return null;
- }
-
- private void checkDeltas(IMarkerDelta[] markerDeltas) throws CoreException {
- for (int i= 0; i < markerDeltas.length; i++) {
- if (isAffected(markerDeltas[i])) {
- IMarker marker= markerDeltas[i].getMarker();
- switch (markerDeltas[i].getKind()) {
- case IResourceDelta.ADDED :
- addMarkerAnnotation(marker);
- fChangesApplied= true;
- break;
- case IResourceDelta.REMOVED :
- removeMarkerAnnotation(marker);
- fChangesApplied= true;
- break;
- case IResourceDelta.CHANGED:
- modifyMarkerAnnotation(marker);
- fChangesApplied= true;
- break;
- }
- }
- }
- }
-
- /**
- * @see IResourceChangeListener#resourceChanged
- */
- public void resourceChanged(IResourceChangeEvent e) {
- try {
- IMarkerDelta[] deltas= e.findMarkerDeltas(null, true);
- if (deltas != null) {
- fChangesApplied= false;
- checkDeltas(deltas);
- if (fChangesApplied)
- fireModelChanged();
- }
- } catch (CoreException x) {
- handleCoreException(x, JavaEditorMessages.ClassFileMarkerAnnotationModel_error_resourceChanged);
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerRulerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerRulerAction.java
deleted file mode 100644
index 9fa42e4d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClassFileMarkerRulerAction.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.Map;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.MarkerRulerAction;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IResourceLocator;
-
-
-
-class ClassFileMarkerRulerAction extends MarkerRulerAction {
-
-
- public ClassFileMarkerRulerAction(String prefix, IVerticalRuler ruler, ITextEditor editor, String markerType, boolean askForLabel) {
- super(JavaEditorMessages.getBundleForConstructedKeys(), prefix, editor, ruler, markerType, askForLabel);
- }
-
- /**
- * @see MarkerRulerAction#getResource()
- */
- protected IResource getResource() {
-
- IResource resource= null;
-
- IEditorInput input= getTextEditor().getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- IClassFile c= ((IClassFileEditorInput) input).getClassFile();
- IResourceLocator locator= (IResourceLocator) c.getAdapter(IResourceLocator.class);
- if (locator != null) {
- try {
- resource= locator.getContainingResource(c);
- } catch (JavaScriptModelException x) {
- // ignore but should inform
- }
- }
- }
-
- return resource;
- }
-
- /**
- * @see MarkerRulerAction#getInitialAttributes()
- */
- protected Map getInitialAttributes() {
-
- Map attributes= super.getInitialAttributes();
-
- IEditorInput input= getTextEditor().getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- IClassFile classFile= ((IClassFileEditorInput) input).getClassFile();
- JavaScriptCore.addJavaScriptElementMarkerAttributes(attributes, classFile);
- }
-
- return attributes;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClipboardOperationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClipboardOperationAction.java
deleted file mode 100644
index a52c5f50..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ClipboardOperationAction.java
+++ /dev/null
@@ -1,507 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.RTFTransfer;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ImportReferencesCollector;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * Action for cut/copy and paste with support for adding imports on paste.
- */
-public final class ClipboardOperationAction extends TextEditorAction {
-
- public static class ClipboardData {
- private String fOriginHandle;
- private String[] fTypeImports;
- private String[] fStaticImports;
-
- public ClipboardData(IJavaScriptElement origin, String[] typeImports, String[] staticImports) {
- Assert.isNotNull(origin);
- Assert.isNotNull(typeImports);
- Assert.isNotNull(staticImports);
-
- fTypeImports= typeImports;
- fStaticImports= staticImports;
- fOriginHandle= origin.getHandleIdentifier();
- }
-
- public ClipboardData(byte[] bytes) throws IOException {
- DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes));
- try {
- fOriginHandle= dataIn.readUTF();
- fTypeImports= readArray(dataIn);
- fStaticImports= readArray(dataIn);
- } finally {
- dataIn.close();
- }
- }
-
- private static String[] readArray(DataInputStream dataIn) throws IOException {
- int count= dataIn.readInt();
-
- String[] array= new String[count];
- for (int i = 0; i < count; i++) {
- array[i]= dataIn.readUTF();
- }
- return array;
- }
-
- private static void writeArray(DataOutputStream dataOut, String[] array) throws IOException {
- dataOut.writeInt(array.length);
- for (int i = 0; i < array.length; i++) {
- dataOut.writeUTF(array[i]);
- }
- }
-
- public String[] getTypeImports() {
- return fTypeImports;
- }
-
- public String[] getStaticImports() {
- return fStaticImports;
- }
-
- public boolean isFromSame(IJavaScriptElement elem) {
- return fOriginHandle.equals(elem.getHandleIdentifier());
- }
-
- public byte[] serialize() throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- DataOutputStream dataOut = new DataOutputStream(out);
- try {
- dataOut.writeUTF(fOriginHandle);
- writeArray(dataOut, fTypeImports);
- writeArray(dataOut, fStaticImports);
- } finally {
- dataOut.close();
- out.close();
- }
-
- return out.toByteArray();
- }
- }
-
-
- private static class ClipboardTransfer extends ByteArrayTransfer {
-
- private static final String TYPE_NAME = "source-with-imports-transfer-format" + System.currentTimeMillis(); //$NON-NLS-1$
-
- private static final int TYPEID = registerType(TYPE_NAME);
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
- */
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.dnd.Transfer#getTypeNames()
- */
- protected String[] getTypeNames() {
- return new String[] { TYPE_NAME };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.dnd.Transfer#javaToNative(java.lang.Object, org.eclipse.swt.dnd.TransferData)
- */
- protected void javaToNative(Object data, TransferData transferData) {
- if (data instanceof ClipboardData) {
- try {
- super.javaToNative(((ClipboardData) data).serialize(), transferData);
- } catch (IOException e) {
- //it's best to send nothing if there were problems
- }
- }
- }
-
- /* (non-Javadoc)
- * Method declared on Transfer.
- */
- protected Object nativeToJava(TransferData transferData) {
- byte[] bytes = (byte[]) super.nativeToJava(transferData);
- if (bytes != null) {
- try {
- return new ClipboardData(bytes);
- } catch (IOException e) {
- }
- }
- return null;
- }
-
- }
-
- private static final ClipboardTransfer fgTransferInstance = new ClipboardTransfer();
-
- /** The text operation code */
- private int fOperationCode= -1;
- /** The text operation target */
- private ITextOperationTarget fOperationTarget;
-
-
- /**
- * Creates the action.
- */
- public ClipboardOperationAction(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) {
- super(bundle, prefix, editor);
- fOperationCode= operationCode;
-
- if (operationCode == ITextOperationTarget.CUT) {
- setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION);
- setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT);
- } else if (operationCode == ITextOperationTarget.COPY) {
- setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION);
- setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
- } else if (operationCode == ITextOperationTarget.PASTE) {
- setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION);
- setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
- } else {
- Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$
- }
- update();
- }
-
- private boolean isReadOnlyOperation() {
- return fOperationCode == ITextOperationTarget.COPY;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- if (fOperationCode == -1 || fOperationTarget == null)
- return;
-
- ITextEditor editor= getTextEditor();
- if (editor == null)
- return;
-
- if (!isReadOnlyOperation() && !validateEditorInputState())
- return;
-
- BusyIndicator.showWhile(getDisplay(), new Runnable() {
- public void run() {
- internalDoOperation();
- }
- });
- }
-
- private Shell getShell() {
- ITextEditor editor= getTextEditor();
- if (editor != null) {
- IWorkbenchPartSite site= editor.getSite();
- Shell shell= site.getShell();
- if (shell != null && !shell.isDisposed()) {
- return shell;
- }
- }
- return null;
- }
-
- private Display getDisplay() {
- Shell shell= getShell();
- if (shell != null) {
- return shell.getDisplay();
- }
- return null;
- }
-
-
- protected final void internalDoOperation() {
- if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_IMPORTS_ON_PASTE)) {
- if (fOperationCode == ITextOperationTarget.PASTE) {
- doPasteWithImportsOperation();
- } else {
- doCutCopyWithImportsOperation();
- }
- } else {
- fOperationTarget.doOperation(fOperationCode);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- super.update();
-
- if (!isReadOnlyOperation() && !canModifyEditor()) {
- setEnabled(false);
- return;
- }
-
- ITextEditor editor= getTextEditor();
- if (fOperationTarget == null && editor!= null && fOperationCode != -1)
- fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
-
- boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
- setEnabled(isEnabled);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.texteditor.TextEditorAction#setEditor(org.eclipse.ui.texteditor.ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
- super.setEditor(editor);
- fOperationTarget= null;
- }
-
-
- private void doCutCopyWithImportsOperation() {
- ITextEditor editor= getTextEditor();
- IJavaScriptElement inputElement= (IJavaScriptElement) editor.getEditorInput().getAdapter(IJavaScriptElement.class);
- ISelection selection= editor.getSelectionProvider().getSelection();
-
- Object clipboardData= null;
- if (inputElement != null && selection instanceof ITextSelection && !selection.isEmpty()) {
- ITextSelection textSelection= (ITextSelection) selection;
- if (isNonTrivialSelection(textSelection)) {
- clipboardData= getClipboardData(inputElement, textSelection.getOffset(), textSelection.getLength());
- }
- }
-
- fOperationTarget.doOperation(fOperationCode);
-
- if (clipboardData != null) {
- Clipboard clipboard= new Clipboard(getDisplay());
- try {
- /*
- * We currently make assumptions about what the styled text widget sets,
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=61876
- */
- Object textData= clipboard.getContents(TextTransfer.getInstance());
- Object rtfData= clipboard.getContents(RTFTransfer.getInstance());
-
- ArrayList datas= new ArrayList(3);
- ArrayList transfers= new ArrayList(3);
- if (textData != null) {
- datas.add(textData);
- transfers.add(TextTransfer.getInstance());
- }
- if (rtfData != null) {
- datas.add(rtfData);
- transfers.add(RTFTransfer.getInstance());
- }
-
- /*
- * Don't add if we didn't get any data from the clipboard
- * see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=70077
- */
- if (datas.isEmpty())
- return;
-
- datas.add(clipboardData);
- transfers.add(fgTransferInstance);
-
- Transfer[] dataTypes= (Transfer[]) transfers.toArray(new Transfer[transfers.size()]);
- Object[] data= datas.toArray();
- setClipboardContents(clipboard, data, dataTypes);
- } finally {
- clipboard.dispose();
- }
- }
- }
-
- private void setClipboardContents(Clipboard clipboard, Object[] datas, Transfer[] transfers) {
- try {
- clipboard.setContents(datas, transfers);
- } catch (SWTError e) {
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) {
- throw e;
- }
- // silently fail. see e.g. https://bugs.eclipse.org/bugs/show_bug.cgi?id=65975
- }
- }
-
- private boolean isNonTrivialSelection(ITextSelection selection) {
- if (selection.getLength() < 30) {
- String text= selection.getText();
- if (text != null) {
- for (int i= 0; i < text.length(); i++) {
- if (!Character.isJavaIdentifierPart(text.charAt(i))) {
- return true;
- }
- }
- }
- return false;
- }
- return true;
- }
-
-
- private ClipboardData getClipboardData(IJavaScriptElement inputElement, int offset, int length) {
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(inputElement, ASTProvider.WAIT_ACTIVE_ONLY, null);
- if (astRoot == null) {
- return null;
- }
-
- // do process import if selection spans over import declaration or package
- List list= astRoot.imports();
- if (!list.isEmpty()) {
- if (offset < ((ASTNode) list.get(list.size() - 1)).getStartPosition()) {
- return null;
- }
- } else if (astRoot.getPackage() != null) {
- if (offset < ((ASTNode) astRoot.getPackage()).getStartPosition()) {
- return null;
- }
- }
-
- ArrayList typeImportsRefs= new ArrayList();
- ArrayList staticImportsRefs= new ArrayList();
-
- ImportReferencesCollector.collect(astRoot, inputElement.getJavaScriptProject(), new Region(offset, length), typeImportsRefs, staticImportsRefs);
-
- if (typeImportsRefs.isEmpty() && staticImportsRefs.isEmpty()) {
- return null;
- }
-
- HashSet namesToImport= new HashSet(typeImportsRefs.size());
- for (int i= 0; i < typeImportsRefs.size(); i++) {
- Name curr= (Name) typeImportsRefs.get(i);
- IBinding binding= curr.resolveBinding();
- if (binding != null && binding.getKind() == IBinding.TYPE) {
- ITypeBinding typeBinding= (ITypeBinding) binding;
- if (typeBinding.isArray()) {
- typeBinding= typeBinding.getElementType();
- }
-
- if (typeBinding.isMember() || typeBinding.isTopLevel()) {
- String name= Bindings.getRawQualifiedName(typeBinding);
- if (name.length() > 0) {
- namesToImport.add(name);
- }
- }
- }
- }
-
- HashSet staticsToImport= new HashSet(staticImportsRefs.size());
- for (int i= 0; i < staticImportsRefs.size(); i++) {
- Name curr= (Name) staticImportsRefs.get(i);
- IBinding binding= curr.resolveBinding();
- if (binding != null) {
- StringBuffer buf= new StringBuffer(Bindings.getImportName(binding));
- if (binding.getKind() == IBinding.METHOD) {
- buf.append("()"); //$NON-NLS-1$
- }
- staticsToImport.add(buf.toString());
- }
- }
-
-
- if (namesToImport.isEmpty() && staticsToImport.isEmpty()) {
- return null;
- }
-
- String[] typeImports= (String[]) namesToImport.toArray(new String[namesToImport.size()]);
- String[] staticImports= (String[]) staticsToImport.toArray(new String[staticsToImport.size()]);
- return new ClipboardData(inputElement, typeImports, staticImports);
- }
-
-
- private void doPasteWithImportsOperation() {
- ITextEditor editor= getTextEditor();
- IJavaScriptElement inputElement= (IJavaScriptElement) editor.getEditorInput().getAdapter(IJavaScriptElement.class);
-
- Clipboard clipboard= new Clipboard(getDisplay());
- ClipboardData importsData= (ClipboardData) clipboard.getContents(fgTransferInstance);
- if (importsData != null && inputElement instanceof IJavaScriptUnit && !importsData.isFromSame(inputElement)) {
- // combine operation and adding of imports
- IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
- if (target != null) {
- target.beginCompoundChange();
- }
- try {
- fOperationTarget.doOperation(fOperationCode);
- addImports((IJavaScriptUnit) inputElement, importsData);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } finally {
- if (target != null) {
- target.endCompoundChange();
- }
- }
- } else {
- fOperationTarget.doOperation(fOperationCode);
- }
- }
-
-
- private void addImports(IJavaScriptUnit unit, ClipboardData data) throws CoreException {
- ImportRewrite rewrite= StubUtility.createImportRewrite(unit, true);
- String[] imports= data.getTypeImports();
- for (int i= 0; i < imports.length; i++) {
- rewrite.addImport(imports[i]);
- }
- String[] staticImports= data.getStaticImports();
- for (int i= 0; i < staticImports.length; i++) {
- String name= Signature.getSimpleName(staticImports[i]);
- boolean isField= !name.endsWith("()"); //$NON-NLS-1$
- if (!isField) {
- name= name.substring(0, name.length() - 2);
- }
- String qualifier= Signature.getQualifier(staticImports[i]);
- rewrite.addStaticImport(qualifier, name, isField);
- }
-
- JavaModelUtil.applyEdit(unit, rewrite.rewriteImports(null), false, null);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitAnnotationModelEvent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitAnnotationModelEvent.java
deleted file mode 100644
index ced261d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitAnnotationModelEvent.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.AnnotationModelEvent;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Event sent out by changes of the compilation unit annotation model.
- */
-public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent {
-
- private boolean fIncludesProblemMarkerAnnotations;
- private IResource fUnderlyingResource;
-
- /**
- * Constructor for CompilationUnitAnnotationModelEvent.
- * @param model
- * @param underlyingResource The annotation model's underlying resource
- */
- public CompilationUnitAnnotationModelEvent(IAnnotationModel model, IResource underlyingResource) {
- super(model);
- fUnderlyingResource= underlyingResource;
- fIncludesProblemMarkerAnnotations= false;
- }
-
- private void testIfProblemMarker(Annotation annotation) {
- if (fIncludesProblemMarkerAnnotations) {
- return;
- }
- if (annotation instanceof JavaMarkerAnnotation) {
- fIncludesProblemMarkerAnnotations= ((JavaMarkerAnnotation) annotation).isProblem();
- } else if (annotation instanceof MarkerAnnotation) {
- try {
- IMarker marker= ((MarkerAnnotation) annotation).getMarker();
- if (!marker.exists() || marker.isSubtypeOf(IMarker.PROBLEM)) {
- fIncludesProblemMarkerAnnotations= true;
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationAdded(org.eclipse.jface.text.source.Annotation)
- */
- public void annotationAdded(Annotation annotation) {
- super.annotationAdded(annotation);
- testIfProblemMarker(annotation);
- }
-
-
- /*
- * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation)
- */
- public void annotationRemoved(Annotation annotation) {
- super.annotationRemoved(annotation);
- testIfProblemMarker(annotation);
- }
-
- /*
- * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation, org.eclipse.jface.text.Position)
- */
- public void annotationRemoved(Annotation annotation, Position position) {
- super.annotationRemoved(annotation, position);
- testIfProblemMarker(annotation);
- }
-
- /*
- * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationChanged(org.eclipse.jface.text.source.Annotation)
- */
- public void annotationChanged(Annotation annotation) {
- testIfProblemMarker(annotation);
- super.annotationChanged(annotation);
- }
-
- /**
- * Returns whether the change included problem marker annotations.
- *
- * @return <code>true</code> if the change included marker annotations
- */
- public boolean includesProblemMarkerAnnotationChanges() {
- return fIncludesProblemMarkerAnnotations;
- }
-
- /**
- * Returns the annotation model's underlying resource
- */
- public IResource getUnderlyingResource() {
- return fUnderlyingResource;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java
deleted file mode 100644
index fa33556c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java
+++ /dev/null
@@ -1,1566 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IEncodedStorage;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFileState;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.AnnotationModel;
-import org.eclipse.jface.text.source.AnnotationModelEvent;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationModelListener;
-import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
-import org.eclipse.jface.text.source.IAnnotationPresentation;
-import org.eclipse.jface.text.source.ImageUtilities;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.editors.text.ForwardingDocumentProvider;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.ui.texteditor.MarkerUtilities;
-import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IProblemRequestor;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.IPostSaveListener;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.IProblemRequestorExtension;
-import org.eclipse.wst.jsdt.internal.ui.text.spelling.JavaSpellingReconcileStrategy;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-public class CompilationUnitDocumentProvider extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider {
-
- /**
- * Bundle of all required informations to allow working copy management.
- */
- static protected class CompilationUnitInfo extends FileInfo {
- public IJavaScriptUnit fCopy;
- }
-
- /**
- * Annotation representing an <code>IProblem</code>.
- */
- static public class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationPresentation, IQuickFixableAnnotation {
-
- public static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling"; //$NON-NLS-1$
-
- //XXX: To be fully correct these constants should be non-static
- /**
- * The layer in which task problem annotations are located.
- */
- private static final int TASK_LAYER;
- /**
- * The layer in which info problem annotations are located.
- */
- private static final int INFO_LAYER;
- /**
- * The layer in which warning problem annotations representing are located.
- */
- private static final int WARNING_LAYER;
- /**
- * The layer in which error problem annotations representing are located.
- */
- private static final int ERROR_LAYER;
-
- static {
- AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup();
- TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$
- INFO_LAYER= computeLayer("org.eclipse.wst.jsdt.ui.info", lookup); //$NON-NLS-1$
- WARNING_LAYER= computeLayer("org.eclipse.wst.jsdt.ui.warning", lookup); //$NON-NLS-1$
- ERROR_LAYER= computeLayer("org.eclipse.wst.jsdt.ui.error", lookup); //$NON-NLS-1$
- }
-
- private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) {
- Annotation annotation= new Annotation(annotationType, false, null);
- AnnotationPreference preference= lookup.getAnnotationPreference(annotation);
- if (preference != null)
- return preference.getPresentationLayer() + 1;
- else
- return IAnnotationAccessExtension.DEFAULT_LAYER + 1;
- }
-
- private static Image fgQuickFixImage;
- private static Image fgQuickFixErrorImage;
- private static boolean fgQuickFixImagesInitialized= false;
-
- private IJavaScriptUnit fCompilationUnit;
- private List fOverlaids;
- private IProblem fProblem;
- private Image fImage;
- private boolean fQuickFixImagesInitialized= false;
- private int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
- private boolean fIsQuickFixable;
- private boolean fIsQuickFixableStateSet= false;
-
-
- public ProblemAnnotation(IProblem problem, IJavaScriptUnit cu) {
-
- fProblem= problem;
- fCompilationUnit= cu;
-
- if (JavaSpellingReconcileStrategy.SPELLING_PROBLEM_ID == fProblem.getID()) {
- setType(SPELLING_ANNOTATION_TYPE);
- fLayer= WARNING_LAYER;
- } else if (IProblem.Task == fProblem.getID()) {
- setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
- fLayer= TASK_LAYER;
- } else if (fProblem.isWarning()) {
- setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
- fLayer= WARNING_LAYER;
- } else if (fProblem.isError()) {
- setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
- fLayer= ERROR_LAYER;
- } else {
- setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
- fLayer= INFO_LAYER;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
- */
- public int getLayer() {
- return fLayer;
- }
-
- private void initializeImages() {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
- if (!fQuickFixImagesInitialized) {
- if (!isQuickFixableStateSet())
- setQuickFixable(isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)); // no light bulb for tasks
- if (isQuickFixable()) {
- if (!fgQuickFixImagesInitialized) {
- fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
- fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
- fgQuickFixImagesInitialized= true;
- }
- if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
- fImage= fgQuickFixErrorImage;
- else
- fImage= fgQuickFixImage;
- }
- fQuickFixImagesInitialized= true;
- }
- }
-
- private boolean indicateQuixFixableProblems() {
- return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
- }
-
- /*
- * @see Annotation#paint
- */
- public void paint(GC gc, Canvas canvas, Rectangle r) {
- initializeImages();
- if (fImage != null)
- ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
- }
-
- /*
- * @see IJavaAnnotation#getImage(Display)
- */
- public Image getImage(Display display) {
- initializeImages();
- return fImage;
- }
-
- /*
- * @see IJavaAnnotation#getMessage()
- */
- public String getText() {
- return fProblem.getMessage();
- }
-
- /*
- * @see IJavaAnnotation#getArguments()
- */
- public String[] getArguments() {
- return isProblem() ? fProblem.getArguments() : null;
- }
-
- /*
- * @see IJavaAnnotation#getId()
- */
- public int getId() {
- return fProblem.getID();
- }
-
- /*
- * @see IJavaAnnotation#isProblem()
- */
- public boolean isProblem() {
- String type= getType();
- return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) ||
- JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) ||
- SPELLING_ANNOTATION_TYPE.equals(type);
- }
-
- /*
- * @see IJavaAnnotation#hasOverlay()
- */
- public boolean hasOverlay() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
- */
- public IJavaAnnotation getOverlay() {
- return null;
- }
-
- /*
- * @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
- */
- public void addOverlaid(IJavaAnnotation annotation) {
- if (fOverlaids == null)
- fOverlaids= new ArrayList(1);
- fOverlaids.add(annotation);
- }
-
- /*
- * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
- */
- public void removeOverlaid(IJavaAnnotation annotation) {
- if (fOverlaids != null) {
- fOverlaids.remove(annotation);
- if (fOverlaids.size() == 0)
- fOverlaids= null;
- }
- }
-
- /*
- * @see IJavaAnnotation#getOverlaidIterator()
- */
- public Iterator getOverlaidIterator() {
- if (fOverlaids != null)
- return fOverlaids.iterator();
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getMarkerType()
- */
- public String getMarkerType() {
- if (fProblem instanceof CategorizedProblem)
- return ((CategorizedProblem) fProblem).getMarkerType();
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.IQuickFixableAnnotation#setQuickFixable(boolean)
- *
- */
- public void setQuickFixable(boolean state) {
- fIsQuickFixable= state;
- fIsQuickFixableStateSet= true;
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.IQuickFixableAnnotation#isQuickFixableStateSet()
- *
- */
- public boolean isQuickFixableStateSet() {
- return fIsQuickFixableStateSet;
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.IQuickFixableAnnotation#isQuickFixable()
- *
- */
- public boolean isQuickFixable() {
- Assert.isTrue(isQuickFixableStateSet());
- return fIsQuickFixable;
- }
- }
-
- /**
- * Internal structure for mapping positions to some value.
- * The reason for this specific structure is that positions can
- * change over time. Thus a lookup is based on value and not
- * on hash value.
- */
- protected static class ReverseMap {
-
- static class Entry {
- Position fPosition;
- Object fValue;
- }
-
- private List fList= new ArrayList(2);
- private int fAnchor= 0;
-
- public ReverseMap() {
- }
-
- public Object get(Position position) {
-
- Entry entry;
-
- // behind anchor
- int length= fList.size();
- for (int i= fAnchor; i < length; i++) {
- entry= (Entry) fList.get(i);
- if (entry.fPosition.equals(position)) {
- fAnchor= i;
- return entry.fValue;
- }
- }
-
- // before anchor
- for (int i= 0; i < fAnchor; i++) {
- entry= (Entry) fList.get(i);
- if (entry.fPosition.equals(position)) {
- fAnchor= i;
- return entry.fValue;
- }
- }
-
- return null;
- }
-
- private int getIndex(Position position) {
- Entry entry;
- int length= fList.size();
- for (int i= 0; i < length; i++) {
- entry= (Entry) fList.get(i);
- if (entry.fPosition.equals(position))
- return i;
- }
- return -1;
- }
-
- public void put(Position position, Object value) {
- int index= getIndex(position);
- if (index == -1) {
- Entry entry= new Entry();
- entry.fPosition= position;
- entry.fValue= value;
- fList.add(entry);
- } else {
- Entry entry= (Entry) fList.get(index);
- entry.fValue= value;
- }
- }
-
- public void remove(Position position) {
- int index= getIndex(position);
- if (index > -1)
- fList.remove(index);
- }
-
- public void clear() {
- fList.clear();
- }
- }
-
- /**
- * Annotation model dealing with java marker annotations and temporary problems.
- * Also acts as problem requester for its compilation unit. Initially inactive. Must explicitly be
- * activated.
- */
- protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
-
- private static class ProblemRequestorState {
- boolean fInsideReportingSequence= false;
- List fReportedProblems;
- }
-
- private ThreadLocal fProblemRequestorState= new ThreadLocal();
- private int fStateCount= 0;
-
- private IJavaScriptUnit fCompilationUnit;
- private List fGeneratedAnnotations= new ArrayList();
- private IProgressMonitor fProgressMonitor;
- private boolean fIsActive= false;
- private boolean fIsHandlingTemporaryProblems;
-
- private ReverseMap fReverseMap= new ReverseMap();
- private List fPreviouslyOverlaid= null;
- private List fCurrentlyOverlaid= new ArrayList();
- private Thread fActiveThread;
-
-
- public CompilationUnitAnnotationModel(IResource resource) {
- super(resource);
- }
-
- public void setCompilationUnit(IJavaScriptUnit unit) {
- fCompilationUnit= unit;
- }
-
- protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
- String markerType= MarkerUtilities.getMarkerType(marker);
- if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
- return new JavaMarkerAnnotation(marker);
- return super.createMarkerAnnotation(marker);
- }
-
- /*
- * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
- */
- protected AnnotationModelEvent createAnnotationModelEvent() {
- return new CompilationUnitAnnotationModelEvent(this, getResource());
- }
-
- protected Position createPositionFromProblem(IProblem problem) {
- int start= problem.getSourceStart();
- if (start < 0)
- return null;
-
- int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
- if (length < 0)
- return null;
-
- return new Position(start, length);
- }
-
- /*
- * @see IProblemRequestor#beginReporting()
- */
- public void beginReporting() {
- ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
- if (state == null)
- internalBeginReporting(false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
- */
- public void beginReportingSequence() {
- ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
- if (state == null)
- internalBeginReporting(true);
- }
-
- /**
- * Sets up the infrastructure necessary for problem reporting.
- *
- * @param insideReportingSequence <code>true</code> if this method
- * call is issued from inside a reporting sequence
- */
- private void internalBeginReporting(boolean insideReportingSequence) {
- if (fCompilationUnit != null /*&& fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)*/) {
- ProblemRequestorState state= new ProblemRequestorState();
- state.fInsideReportingSequence= insideReportingSequence;
- state.fReportedProblems= new ArrayList();
- synchronized (getLockObject()) {
- fProblemRequestorState.set(state);
- ++fStateCount;
- }
- }
- }
-
- /*
- * @see IProblemRequestor#acceptProblem(IProblem)
- */
- public void acceptProblem(IProblem problem) {
- if (fIsHandlingTemporaryProblems || problem.getID() == JavaSpellingReconcileStrategy.SPELLING_PROBLEM_ID) {
- ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
- if (state != null)
- state.fReportedProblems.add(problem);
- }
- }
-
- /*
- * @see IProblemRequestor#endReporting()
- */
- public void endReporting() {
- ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
- if (state != null && !state.fInsideReportingSequence)
- internalEndReporting(state);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
- */
- public void endReportingSequence() {
- ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
- if (state != null && state.fInsideReportingSequence)
- internalEndReporting(state);
- }
-
- private void internalEndReporting(ProblemRequestorState state) {
- int stateCount= 0;
- synchronized(getLockObject()) {
- -- fStateCount;
- stateCount= fStateCount;
- fProblemRequestorState.set(null);
- }
-
- if (stateCount == 0)
- reportProblems(state.fReportedProblems);
- }
-
- /**
- * Signals the end of problem reporting.
- *
- * @param reportedProblems the problems to report
- */
- private void reportProblems(List reportedProblems) {
- if (fProgressMonitor != null && fProgressMonitor.isCanceled())
- return;
-
- boolean temporaryProblemsChanged= false;
-
- synchronized (getLockObject()) {
-
- boolean isCanceled= false;
-
- fPreviouslyOverlaid= fCurrentlyOverlaid;
- fCurrentlyOverlaid= new ArrayList();
-
- if (fGeneratedAnnotations.size() > 0) {
- temporaryProblemsChanged= true;
- removeAnnotations(fGeneratedAnnotations, false, true);
- fGeneratedAnnotations.clear();
- }
-
- if (reportedProblems != null && reportedProblems.size() > 0) {
-
- Iterator e= reportedProblems.iterator();
- while (e.hasNext()) {
-
- if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
- isCanceled= true;
- break;
- }
-
- IProblem problem= (IProblem) e.next();
- Position position= createPositionFromProblem(problem);
- if (position != null) {
-
- try {
- ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit);
- overlayMarkers(position, annotation);
- addAnnotation(annotation, position, false);
- fGeneratedAnnotations.add(annotation);
-
- temporaryProblemsChanged= true;
- } catch (BadLocationException x) {
- // ignore invalid position
- }
- }
- }
- }
-
- removeMarkerOverlays(isCanceled);
- fPreviouslyOverlaid= null;
- }
-
- if (temporaryProblemsChanged)
- fireModelChanged();
- }
-
- private void removeMarkerOverlays(boolean isCanceled) {
- if (isCanceled) {
- fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
- } else if (fPreviouslyOverlaid != null) {
- Iterator e= fPreviouslyOverlaid.iterator();
- while (e.hasNext()) {
- JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
- annotation.setOverlay(null);
- }
- }
- }
-
- /**
- * Overlays value with problem annotation.
- *
- * @param value the value
- * @param problemAnnotation
- */
- private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
- if (value instanceof JavaMarkerAnnotation) {
- JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
- if (annotation.isProblem()) {
- annotation.setOverlay(problemAnnotation);
- fPreviouslyOverlaid.remove(annotation);
- fCurrentlyOverlaid.add(annotation);
- }
- } else {
- }
- }
-
- private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
- Object value= getAnnotations(position);
- if (value instanceof List) {
- List list= (List) value;
- for (Iterator e = list.iterator(); e.hasNext();)
- setOverlay(e.next(), problemAnnotation);
- } else {
- setOverlay(value, problemAnnotation);
- }
- }
-
- /**
- * Tells this annotation model to collect temporary problems from now on.
- */
- private void startCollectingProblems() {
- fGeneratedAnnotations.clear();
- }
-
- /**
- * Tells this annotation model to no longer collect temporary problems.
- */
- private void stopCollectingProblems() {
- if (fGeneratedAnnotations != null)
- removeAnnotations(fGeneratedAnnotations, true, true);
- fGeneratedAnnotations.clear();
- }
-
- /*
- * @see IProblemRequestor#isActive()
- */
- public synchronized boolean isActive() {
- return fIsActive && fActiveThread == Thread.currentThread();
- }
-
- /*
- * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
- */
- public void setProgressMonitor(IProgressMonitor monitor) {
- fProgressMonitor= monitor;
- }
-
- /*
- * @see IProblemRequestorExtension#setIsActive(boolean)
- */
- public synchronized void setIsActive(boolean isActive) {
- Assert.isLegal(!isActive || Display.getCurrent() == null); // must not be enabled from UI threads
- fIsActive= isActive;
- if (fIsActive)
- fActiveThread= Thread.currentThread();
- else
- fActiveThread= null;
- }
-
- /*
- * @see IProblemRequestorExtension#setIsHandlingTemporaryProblems(boolean)
- *
- */
- public void setIsHandlingTemporaryProblems(boolean enable) {
- if (fIsHandlingTemporaryProblems != enable) {
- fIsHandlingTemporaryProblems= enable;
- if (fIsHandlingTemporaryProblems)
- startCollectingProblems();
- else
- stopCollectingProblems();
- }
-
- }
-
- private Object getAnnotations(Position position) {
- synchronized (getLockObject()) {
- return fReverseMap.get(position);
- }
- }
-
- /*
- * @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
- */
- protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
- super.addAnnotation(annotation, position, fireModelChanged);
-
- synchronized (getLockObject()) {
- Object cached= fReverseMap.get(position);
- if (cached == null)
- fReverseMap.put(position, annotation);
- else if (cached instanceof List) {
- List list= (List) cached;
- list.add(annotation);
- } else if (cached instanceof Annotation) {
- List list= new ArrayList(2);
- list.add(cached);
- list.add(annotation);
- fReverseMap.put(position, list);
- }
- }
- }
-
- /*
- * @see AnnotationModel#removeAllAnnotations(boolean)
- */
- protected void removeAllAnnotations(boolean fireModelChanged) {
- super.removeAllAnnotations(fireModelChanged);
- synchronized (getLockObject()) {
- fReverseMap.clear();
- }
- }
-
- /*
- * @see AnnotationModel#removeAnnotation(Annotation, boolean)
- */
- protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
- Position position= getPosition(annotation);
- synchronized (getLockObject()) {
- Object cached= fReverseMap.get(position);
- if (cached instanceof List) {
- List list= (List) cached;
- list.remove(annotation);
- if (list.size() == 1) {
- fReverseMap.put(position, list.get(0));
- list.clear();
- }
- } else if (cached instanceof Annotation) {
- fReverseMap.remove(position);
- }
- }
- super.removeAnnotation(annotation, fireModelChanged);
- }
- }
-
-
- protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
-
- private ListenerList fListenerList;
-
- public GlobalAnnotationModelListener() {
- fListenerList= new ListenerList(ListenerList.IDENTITY);
- }
-
- /**
- * @see IAnnotationModelListener#modelChanged(IAnnotationModel)
- */
- public void modelChanged(IAnnotationModel model) {
- Object[] listeners= fListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ((IAnnotationModelListener) listeners[i]).modelChanged(model);
- }
- }
-
- /**
- * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
- */
- public void modelChanged(AnnotationModelEvent event) {
- Object[] listeners= fListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- Object curr= listeners[i];
- if (curr instanceof IAnnotationModelListenerExtension) {
- ((IAnnotationModelListenerExtension) curr).modelChanged(event);
- }
- }
- }
-
- public void addListener(IAnnotationModelListener listener) {
- fListenerList.add(listener);
- }
-
- public void removeListener(IAnnotationModelListener listener) {
- fListenerList.remove(listener);
- }
- }
-
- /** Preference key for temporary problems */
- private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
-
-
- /** Indicates whether the save has been initialized by this provider */
- private boolean fIsAboutToSave= false;
- /** The save policy used by this provider */
- private ISavePolicy fSavePolicy;
- /** Internal property changed listener */
- private IPropertyChangeListener fPropertyListener;
- /** Annotation model listener added to all created CU annotation models */
- private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
- /**
- * Element information of all connected elements with a fake CU but no file info.
- *
- */
- private final Map fFakeCUMapForMissingInfo= new HashMap();
-
-
- /**
- * Constructor
- */
- public CompilationUnitDocumentProvider() {
-
- IDocumentProvider provider= new TextFileDocumentProvider();
- provider= new ForwardingDocumentProvider(IJavaScriptPartitions.JAVA_PARTITIONING, new JavaDocumentSetupParticipant(), provider);
- setParentDocumentProvider(provider);
-
- fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
- fPropertyListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
- enableHandlingTemporaryProblems();
- }
- };
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
- }
-
- /**
- * Creates a compilation unit from the given file.
- *
- * @param file the file from which to create the compilation unit
- * @return the fake compilation unit
- */
- protected IJavaScriptUnit createCompilationUnit(IFile file) {
- Object element= JavaScriptCore.create(file);
- if (element instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) element;
- return null;
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
- */
- protected FileInfo createEmptyFileInfo() {
- return new CompilationUnitInfo();
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
- */
- protected IAnnotationModel createAnnotationModel(IFile file) {
- return new CompilationUnitAnnotationModel(file);
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
- */
- protected FileInfo createFileInfo(Object element) throws CoreException {
- IJavaScriptUnit original= null;
- if (element instanceof IFileEditorInput) {
- IFileEditorInput input= (IFileEditorInput) element;
- original= createCompilationUnit(input.getFile());
- if (original == null)
- return null;
- }
-
- FileInfo info= super.createFileInfo(element);
- if (!(info instanceof CompilationUnitInfo))
- return null;
-
- if (original == null)
- original= createFakeCompiltationUnit(element, false);
- if (original == null)
- return null;
-
- CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
- setUpSynchronization(cuInfo);
-
- IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
- if (requestor instanceof IProblemRequestorExtension) {
- IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
- extension.setIsActive(false);
- extension.setIsHandlingTemporaryProblems(isHandlingTemporaryProblems());
- }
-
- /*
- * Use the deprecated method to ensure that our problem requestor is
- * used; it is the only way to have as-you-type IProblems from
- * reconciling appear in the annotation model.
- */
- if (JavaModelUtil.isPrimary(original))
- original.becomeWorkingCopy(requestor, getProgressMonitor());
- cuInfo.fCopy= original;
-
- if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) {
- CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
- model.setCompilationUnit(cuInfo.fCopy);
- }
-
- if (cuInfo.fModel != null)
- cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
-
- return cuInfo;
- }
-
- /**
- * Creates a fake compilation unit.
- *
- * @param element the element
- * @param setContents tells whether to read and set the contents to the new CU
- * @return the fake compilation unit
- *
- */
- private IJavaScriptUnit createFakeCompiltationUnit(Object element, boolean setContents) {
- if (element instanceof IStorageEditorInput)
- return createFakeCompiltationUnit((IStorageEditorInput)element, setContents);
- else if (element instanceof IURIEditorInput)
- return createFakeCompiltationUnit((IURIEditorInput)element);
- return null;
- }
-
- /**
- * Creates a fake compilation unit.
- *
- * @param editorInput the storage editor input
- * @param setContents tells whether to read and set the contents to the new CU
- * @return the fake compilation unit
- *
- */
- private IJavaScriptUnit createFakeCompiltationUnit(IStorageEditorInput editorInput, boolean setContents) {
- try {
- final IStorage storage= editorInput.getStorage();
- final IPath storagePath= storage.getFullPath();
- if (storage.getName() == null || storagePath == null)
- return null;
-
- final IPath documentPath;
- if (storage instanceof IFileState)
- documentPath= storagePath.append(Long.toString(((IFileState)storage).getModificationTime()));
- else
- documentPath= storagePath;
-
- WorkingCopyOwner woc= new WorkingCopyOwner() {
- /*
- * @see org.eclipse.wst.jsdt.core.WorkingCopyOwner#createBuffer(org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- *
- */
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
- return new DocumentAdapter(workingCopy, documentPath);
- }
- };
-
- IIncludePathEntry[] cpEntries= null;
- IJavaScriptProject jp= findJavaProject(storagePath);
- if (jp != null)
- cpEntries= jp.getResolvedIncludepath(true);
-
- if (cpEntries == null || cpEntries.length == 0)
- cpEntries= new IIncludePathEntry[] { JavaRuntime.getDefaultJREContainerEntry() };
-
- final IJavaScriptUnit cu= woc.newWorkingCopy(storage.getName(), cpEntries, getProgressMonitor());
- if (setContents) {
- int READER_CHUNK_SIZE= 2048;
- int BUFFER_SIZE= 8 * READER_CHUNK_SIZE;
-
- String charsetName= null;
- if (storage instanceof IEncodedStorage)
- charsetName= ((IEncodedStorage)storage).getCharset();
- if (charsetName == null)
- charsetName= getDefaultEncoding();
-
- Reader in= null;
- InputStream contents= storage.getContents();
- try {
- in= new BufferedReader(new InputStreamReader(contents, charsetName));
- StringBuffer buffer= new StringBuffer(BUFFER_SIZE);
- char[] readBuffer= new char[READER_CHUNK_SIZE];
- int n;
- n= in.read(readBuffer);
- while (n > 0) {
- buffer.append(readBuffer, 0, n);
- n= in.read(readBuffer);
- }
- cu.getBuffer().setContents(buffer.toString());
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- return null;
- } finally {
- try {
- if (in != null)
- in.close();
- else
- contents.close();
- } catch (IOException x) {
- }
- }
- }
-
- if (!isModifiable(editorInput))
- JavaModelUtil.reconcile(cu);
-
- return cu;
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex.getStatus());
- return null;
- }
- }
-
- /**
- * Creates a fake compilation unit.
- *
- * @param editorInput the URI editor input
- * @return the fake compilation unit
- *
- */
- private IJavaScriptUnit createFakeCompiltationUnit(IURIEditorInput editorInput) {
- try {
- final URI uri= editorInput.getURI();
- final IFileStore fileStore= EFS.getStore(uri);
- final IPath path= URIUtil.toPath(uri);
- if (fileStore.getName() == null || path == null)
- return null;
-
- WorkingCopyOwner woc= new WorkingCopyOwner() {
- /*
- * @see org.eclipse.wst.jsdt.core.WorkingCopyOwner#createBuffer(org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- *
- */
- public IBuffer createBuffer(IJavaScriptUnit workingCopy) {
- return new DocumentAdapter(workingCopy, path);
- }
- };
-
- IIncludePathEntry[] cpEntries= null;
- IJavaScriptProject jp= findJavaProject(path);
- if (jp != null)
- cpEntries= jp.getResolvedIncludepath(true);
-
- if (cpEntries == null || cpEntries.length == 0)
- cpEntries= new IIncludePathEntry[] { JavaRuntime.getDefaultJREContainerEntry() };
-
- final IJavaScriptUnit cu= woc.newWorkingCopy(fileStore.getName(), cpEntries, getProgressMonitor());
-
- if (!isModifiable(editorInput))
- JavaModelUtil.reconcile(cu);
-
- return cu;
- } catch (CoreException ex) {
- return null;
- }
- }
-
- /**
- * Fuzzy search for Java project in the workspace that matches
- * the given path.
- *
- * @param path the path to match
- * @return the matching Java project or <code>null</code>
- *
- */
- private IJavaScriptProject findJavaProject(IPath path) {
- if (path == null)
- return null;
-
- String[] pathSegments= path.segments();
- IJavaScriptModel model= JavaScriptCore.create(JavaScriptPlugin.getWorkspace().getRoot());
- IJavaScriptProject[] projects;
- try {
- projects= model.getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- return null; // ignore - use default JRE
- }
- for (int i= 0; i < projects.length; i++) {
- IPath projectPath= projects[i].getProject().getFullPath();
- String projectSegment= projectPath.segments()[0];
- for (int j= 0; j < pathSegments.length; j++)
- if (projectSegment.equals(pathSegments[j]))
- return projects[i];
- }
- return null;
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
- */
- protected void disposeFileInfo(Object element, FileInfo info) {
- if (info instanceof CompilationUnitInfo) {
- CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
-
- try {
- cuInfo.fCopy.discardWorkingCopy();
- } catch (JavaScriptModelException x) {
- handleCoreException(x, x.getMessage());
- }
-
- if (cuInfo.fModel != null)
- cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
- }
- super.disposeFileInfo(element, info);
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#connect(java.lang.Object)
- *
- */
- public void connect(Object element) throws CoreException {
- super.connect(element);
- if (getFileInfo(element) != null)
- return;
-
- CompilationUnitInfo info= (CompilationUnitInfo)fFakeCUMapForMissingInfo.get(element);
- if (info == null) {
- IJavaScriptUnit cu= createFakeCompiltationUnit(element, true);
- if (cu == null)
- return;
- info= new CompilationUnitInfo();
- info.fCopy= cu;
- info.fElement= element;
- if (element instanceof IStorageEditorInput)
- {
- IStorage storage = ((IStorageEditorInput)element).getStorage();
- info.fModel=new StorageMarkerAnnotationModel(ResourcesPlugin.getWorkspace().getRoot(),storage.getName());
- }
- else
- info.fModel= new AnnotationModel();
- fFakeCUMapForMissingInfo.put(element, info);
- }
- info.fCount++;
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#getAnnotationModel(java.lang.Object)
- *
- */
- public IAnnotationModel getAnnotationModel(Object element) {
- IAnnotationModel model= super.getAnnotationModel(element);
- if (model != null)
- return model;
-
- FileInfo info= (FileInfo)fFakeCUMapForMissingInfo.get(element);
- if (info != null) {
- if (info.fModel != null)
- return info.fModel;
- if (info.fTextFileBuffer != null)
- return info.fTextFileBuffer.getAnnotationModel();
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disconnect(java.lang.Object)
- *
- */
- public void disconnect(Object element) {
- CompilationUnitInfo info= (CompilationUnitInfo)fFakeCUMapForMissingInfo.get(element);
- if (info != null) {
- if (info.fCount == 1) {
- fFakeCUMapForMissingInfo.remove(element);
- info.fModel= null;
- // Destroy and unregister fake working copy
- try {
- info.fCopy.discardWorkingCopy();
- } catch (JavaScriptModelException ex) {
- handleCoreException(ex, ex.getMessage());
- }
- } else
- info.fCount--;
- }
- super.disconnect(element);
- }
-
-
- /**
- * Creates and returns a new sub-progress monitor for the
- * given parent monitor.
- *
- * @param monitor the parent progress monitor
- * @param ticks the number of work ticks allocated from the parent monitor
- * @return the new sub-progress monitor
- */
- private IProgressMonitor getSubProgressMonitor(IProgressMonitor monitor, int ticks) {
- if (monitor != null)
- return new SubProgressMonitor(monitor, ticks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
-
- return new NullProgressMonitor();
- }
-
- protected void commitWorkingCopy(IProgressMonitor monitor, Object element, final CompilationUnitInfo info, boolean overwrite) throws CoreException {
-
- if (monitor == null)
- monitor= new NullProgressMonitor();
-
- monitor.beginTask("", 120); //$NON-NLS-1$
-
- try {
- final IProgressMonitor subMonitor1= getSubProgressMonitor(monitor, 50);
-
- try {
- SafeRunner.run(new ISafeRunnable() {
- public void run() {
- try {
- info.fCopy.reconcile(IJavaScriptUnit.NO_AST, false, null, subMonitor1);
- } catch (JavaScriptModelException ex) {
- handleException(ex);
- } catch (OperationCanceledException ex) {
- // do not log this
- }
- }
- public void handleException(Throwable ex) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, "Error in JSDT Core during reconcile while saving", ex); //$NON-NLS-1$
- JavaScriptPlugin.getDefault().getLog().log(status);
- }
- });
- } finally {
- subMonitor1.done();
- }
-
- IDocument document= info.fTextFileBuffer.getDocument();
- IResource resource= info.fCopy.getResource();
-
- Assert.isTrue(resource instanceof IFile);
-
- boolean isSynchronized= resource.isSynchronized(IResource.DEPTH_ZERO);
-
- /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=98327
- * Make sure file gets save in commit() if the underlying file has been deleted */
- if (!isSynchronized && isDeleted(element))
- info.fTextFileBuffer.setDirty(true);
-
- if (!resource.exists()) {
- // underlying resource has been deleted, just recreate file, ignore the rest
- IProgressMonitor subMonitor2= getSubProgressMonitor(monitor, 70);
- try {
- createFileFromDocument(subMonitor2, (IFile) resource, document);
- } finally {
- subMonitor2.done();
- }
- return;
- }
-
- if (fSavePolicy != null)
- fSavePolicy.preSave(info.fCopy);
-
- IProgressMonitor subMonitor3= getSubProgressMonitor(monitor, 50);
- try {
- fIsAboutToSave= true;
- info.fCopy.commitWorkingCopy(isSynchronized || overwrite, subMonitor3);
- notifyPostSaveListeners(info.fCopy, info, getSubProgressMonitor(monitor, 20));
- } catch (CoreException x) {
- // inform about the failure
- fireElementStateChangeFailed(element);
- throw x;
- } catch (RuntimeException x) {
- // inform about the failure
- fireElementStateChangeFailed(element);
- throw x;
- } finally {
- fIsAboutToSave= false;
- subMonitor3.done();
- }
-
- // If here, the dirty state of the editor will change to "not dirty".
- // Thus, the state changing flag will be reset.
- if (info.fModel instanceof AbstractMarkerAnnotationModel) {
- AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
- model.updateMarkers(document);
- }
-
- if (fSavePolicy != null) {
- IJavaScriptUnit unit= fSavePolicy.postSave(info.fCopy);
- if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) {
- IResource r= unit.getResource();
- IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
- if (markers != null && markers.length > 0) {
- AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
- for (int i= 0; i < markers.length; i++)
- model.updateMarker(document, markers[i], null);
- }
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
- */
- protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
- final FileInfo info= getFileInfo(element);
- if (info instanceof CompilationUnitInfo) {
-
- // Delegate handling of non-primary CUs
- IJavaScriptUnit cu= ((CompilationUnitInfo)info).fCopy;
- if (cu != null && !JavaModelUtil.isPrimary(cu))
- return super.createSaveOperation(element, document, overwrite);
-
- if (info.fTextFileBuffer.getDocument() != document) {
- // the info exists, but not for the given document
- // -> saveAs was executed with a target that is already open
- // in another editor
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=85519
- Status status= new Status(IStatus.WARNING, EditorsUI.PLUGIN_ID, IStatus.ERROR, JavaEditorMessages.CompilationUnitDocumentProvider_saveAsTargetOpenInEditor, null);
- throw new CoreException(status);
- }
-
- return new DocumentProviderOperation() {
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void execute(IProgressMonitor monitor) throws CoreException {
- commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
- }
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
- */
- public ISchedulingRule getSchedulingRule() {
- if (info.fElement instanceof IFileEditorInput) {
- IFile file= ((IFileEditorInput) info.fElement).getFile();
- return computeSchedulingRule(file);
- } else
- return null;
- }
- };
- }
-
- return null;
- }
-
- /**
- * Returns the preference whether handling temporary problems is enabled.
- *
- * @return <code>true</code> if temporary problems are handled
- */
- protected boolean isHandlingTemporaryProblems() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
- }
-
- /**
- * Switches the state of problem acceptance according to the value in the preference store.
- */
- protected void enableHandlingTemporaryProblems() {
- boolean enable= isHandlingTemporaryProblems();
- for (Iterator iter= getFileInfosIterator(); iter.hasNext();) {
- FileInfo info= (FileInfo) iter.next();
- if (info.fModel instanceof IProblemRequestorExtension) {
- IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
- extension.setIsHandlingTemporaryProblems(enable);
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.wst.jsdt.internal.ui.javaeditor.ISavePolicy)
- */
- public void setSavePolicy(ISavePolicy savePolicy) {
- fSavePolicy= savePolicy;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#addGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
- */
- public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
- fGlobalAnnotationModelListener.addListener(listener);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#removeGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
- */
- public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
- fGlobalAnnotationModelListener.removeListener(listener);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
- */
- public IJavaScriptUnit getWorkingCopy(Object element) {
- FileInfo fileInfo= getFileInfo(element);
- if (fileInfo instanceof CompilationUnitInfo) {
- CompilationUnitInfo info= (CompilationUnitInfo)fileInfo;
- return info.fCopy;
- }
- CompilationUnitInfo cuInfo= (CompilationUnitInfo)fFakeCUMapForMissingInfo.get(element);
- if (cuInfo != null)
- return cuInfo.fCopy;
-
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
- */
- public void shutdown() {
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
- Iterator e= getConnectedElementsIterator();
- while (e.hasNext())
- disconnect(e.next());
- fFakeCUMapForMissingInfo.clear();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#saveDocumentContent(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
- */
- public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
- if (!fIsAboutToSave)
- return;
- super.saveDocument(monitor, element, document, overwrite);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object)
- */
- public ILineTracker createLineTracker(Object element) {
- return new DefaultLineTracker();
- }
-
- /**
- * Notify post save listeners.
- * <p>
- * <strong>Note:</strong> Post save listeners are not
- * allowed to save the file and they must not assumed to be
- * called in the UI thread i.e. if they open a dialog they
- * must ensure it ends up in the UI thread.
- * </p>
- *
- * @param unit the compilation unit
- * @param info compilation unit info
- * @param monitor the progress monitor
- * @throws CoreException
- * @see IPostSaveListener
- *
- */
- protected void notifyPostSaveListeners(final IJavaScriptUnit unit, final CompilationUnitInfo info, final IProgressMonitor monitor) throws CoreException {
- final IBuffer buffer= unit.getBuffer();
- IPostSaveListener[] listeners= JavaScriptPlugin.getDefault().getSaveParticipantRegistry().getEnabledPostSaveListeners(unit.getJavaScriptProject().getProject());
-
- String message= JavaEditorMessages.CompilationUnitDocumentProvider_error_saveParticipantProblem;
- final MultiStatus errorStatus= new MultiStatus(JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION, message, null);
-
- monitor.beginTask(JavaEditorMessages.CompilationUnitDocumentProvider_progressNotifyingSaveParticipants, listeners.length * 5);
- try {
- for (int i= 0; i < listeners.length; i++) {
- final IPostSaveListener listener= listeners[i];
- final String participantName= listener.getName();
- SafeRunner.run(new ISafeRunnable() {
- public void run() {
- try {
- long stamp= unit.getResource().getModificationStamp();
-
- listener.saved(unit, getSubProgressMonitor(monitor, 4));
-
- if (stamp != unit.getResource().getModificationStamp()) {
- String msg= Messages.format(JavaEditorMessages.CompilationUnitDocumentProvider_error_saveParticipantSavedFile, participantName);
- errorStatus.add(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION, msg, null));
- }
-
- if (buffer.hasUnsavedChanges())
- buffer.save(getSubProgressMonitor(monitor, 1), true);
-
- } catch (CoreException ex) {
- handleException(ex);
- } finally {
- monitor.worked(1);
- }
- }
-
- public void handleException(Throwable ex) {
- String msg= Messages.format("The save participant ''{0}'' caused an exception: {1}", new String[] { listener.getId(), ex.toString()}); //$NON-NLS-1$
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION, msg, null));
-
- msg= Messages.format(JavaEditorMessages.CompilationUnitDocumentProvider_error_saveParticipantFailed, new String[] { participantName, ex.toString()});
- errorStatus.add(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION, msg, null));
-
- // Revert the changes
- if (info != null && buffer.hasUnsavedChanges()) {
- try {
- info.fTextFileBuffer.revert(getSubProgressMonitor(monitor, 1));
- } catch (CoreException e) {
- msg= Messages.format("Error on revert after failure of save participant ''{0}''.", participantName); //$NON-NLS-1$
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION, msg, ex);
- JavaScriptPlugin.getDefault().getLog().log(status);
- }
-
- if (info.fModel instanceof AbstractMarkerAnnotationModel) {
- AbstractMarkerAnnotationModel markerModel= (AbstractMarkerAnnotationModel)info.fModel;
- markerModel.resetMarkers();
- }
- }
-
- // XXX: Work in progress 'Save As' case
-// else if (buffer.hasUnsavedChanges()) {
-// try {
-// buffer.save(getSubProgressMonitor(monitor, 1), true);
-// } catch (JavaScriptModelException e) {
-// message= Messages.format("Error reverting changes after failure of save participant ''{0}''.", participantName); //$NON-NLS-1$
-// IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, message, ex);
-// JavaScriptPlugin.getDefault().getLog().log(status);
-// }
-// }
- }
- });
- }
- } finally {
- monitor.done();
- if (!errorStatus.isOK())
- throw new CoreException(errorStatus);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java
deleted file mode 100644
index f3c21c6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java
+++ /dev/null
@@ -1,1739 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Stack;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.jface.text.ITextViewerExtension7;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.IWidgetTokenKeeper;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TabsToSpacesConverter;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContentAssistant;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
-import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.source.IOverviewRuler;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.custom.VerifyKeyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.texteditor.ContentAssistAction;
-import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.IStatusField;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.ResourceAction;
-import org.eclipse.ui.texteditor.TextOperationAction;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.AddBlockCommentAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.IndentAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.RemoveBlockCommentAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.SurroundWithActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.compare.LocalHistoryActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.text.ContentAssistPreference;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.SmartBackspaceManager;
-import org.eclipse.wst.jsdt.internal.ui.text.Symbols;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.CorrectionCommandInstaller;
-import org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-
-/**
- * Java specific text editor.
- */
-public class CompilationUnitEditor extends JavaEditor implements IJavaReconcilingListener {
- private static final boolean CODE_ASSIST_DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ResultCollector")); //$NON-NLS-1$//$NON-NLS-2$
-
- /**
- * Text operation code for requesting common prefix completion.
- */
- public static final int CONTENTASSIST_COMPLETE_PREFIX= 60;
-
-
- interface ITextConverter {
- void customizeDocumentCommand(IDocument document, DocumentCommand command);
- }
-
- class AdaptedSourceViewer extends JavaSourceViewer {
-
- public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IPreferenceStore store) {
- super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles, store);
- }
-
- public IContentAssistant getContentAssistant() {
- return fContentAssistant;
- }
-
- /*
- * @see ITextOperationTarget#doOperation(int)
- */
- public void doOperation(int operation) {
-
- if (getTextWidget() == null || !isEditorInputModifiable())
- return;
-
- switch (operation) {
- case CONTENTASSIST_PROPOSALS:
- long time= CODE_ASSIST_DEBUG ? System.currentTimeMillis() : 0;
- String msg= fContentAssistant.showPossibleCompletions();
- if (CODE_ASSIST_DEBUG) {
- long delta= System.currentTimeMillis() - time;
- System.err.println("Code Assist (total): " + delta); //$NON-NLS-1$
- }
- setStatusLineErrorMessage(msg);
- return;
- case QUICK_ASSIST:
- /*
- * XXX: We can get rid of this once the SourceViewer has a way to update the status line
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=133787
- */
- msg= fQuickAssistAssistant.showPossibleQuickAssists();
- setStatusLineErrorMessage(msg);
- return;
- }
-
- super.doOperation(operation);
- }
-
- /*
- * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
- */
- public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
- if (PlatformUI.getWorkbench().getHelpSystem().isContextHelpDisplayed())
- return false;
- return super.requestWidgetToken(requester);
- }
-
- /*
- * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int)
- *
- */
- public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
- if (PlatformUI.getWorkbench().getHelpSystem().isContextHelpDisplayed())
- return false;
- return super.requestWidgetToken(requester, priority);
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
- *
- */
- public IFormattingContext createFormattingContext() {
- IFormattingContext context= new CommentFormattingContext();
-
- Map preferences;
- IJavaScriptElement inputJavaElement= getInputJavaElement();
- IJavaScriptProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaScriptProject() : null;
- if (javaProject == null)
- preferences= new HashMap(JavaScriptCore.getOptions());
- else
- preferences= new HashMap(javaProject.getOptions(true));
-
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);
-
- return context;
- }
- }
-
-
- private class ExitPolicy implements IExitPolicy {
-
- final char fExitCharacter;
- final char fEscapeCharacter;
- final Stack fStack;
- final int fSize;
-
- public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) {
- fExitCharacter= exitCharacter;
- fEscapeCharacter= escapeCharacter;
- fStack= stack;
- fSize= fStack.size();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.wst.jsdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
- */
- public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) {
-
- if (fSize == fStack.size() && !isMasked(offset)) {
- if (event.character == fExitCharacter) {
- BracketLevel level= (BracketLevel) fStack.peek();
- if (level.fFirstPosition.offset > offset || level.fSecondPosition.offset < offset)
- return null;
- if (level.fSecondPosition.offset == offset && length == 0)
- // don't enter the character if if its the closing peer
- return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false);
- }
- // when entering an anonymous class between the parenthesis', we don't want
- // to jump after the closing parenthesis when return is pressed
- if (event.character == SWT.CR && offset > 0) {
- IDocument document= getSourceViewer().getDocument();
- try {
- if (document.getChar(offset - 1) == '{')
- return new ExitFlags(ILinkedModeListener.EXIT_ALL, true);
- } catch (BadLocationException e) {
- }
- }
- }
- return null;
- }
-
- private boolean isMasked(int offset) {
- IDocument document= getSourceViewer().getDocument();
- try {
- return fEscapeCharacter == document.getChar(offset - 1);
- } catch (BadLocationException e) {
- }
- return false;
- }
- }
-
- private static class BracketLevel {
- int fOffset;
- int fLength;
- LinkedModeUI fUI;
- Position fFirstPosition;
- Position fSecondPosition;
- }
-
- /**
- * Position updater that takes any changes at the borders of a position to not belong to the position.
- *
- *
- */
- private static class ExclusivePositionUpdater implements IPositionUpdater {
-
- /** The position category. */
- private final String fCategory;
-
- /**
- * Creates a new updater for the given <code>category</code>.
- *
- * @param category the new category.
- */
- public ExclusivePositionUpdater(String category) {
- fCategory= category;
- }
-
- /*
- * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
- */
- public void update(DocumentEvent event) {
-
- int eventOffset= event.getOffset();
- int eventOldLength= event.getLength();
- int eventNewLength= event.getText() == null ? 0 : event.getText().length();
- int deltaLength= eventNewLength - eventOldLength;
-
- try {
- Position[] positions= event.getDocument().getPositions(fCategory);
-
- for (int i= 0; i != positions.length; i++) {
-
- Position position= positions[i];
-
- if (position.isDeleted())
- continue;
-
- int offset= position.getOffset();
- int length= position.getLength();
- int end= offset + length;
-
- if (offset >= eventOffset + eventOldLength)
- // position comes
- // after change - shift
- position.setOffset(offset + deltaLength);
- else if (end <= eventOffset) {
- // position comes way before change -
- // leave alone
- } else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
- // event completely internal to the position - adjust length
- position.setLength(length + deltaLength);
- } else if (offset < eventOffset) {
- // event extends over end of position - adjust length
- int newEnd= eventOffset;
- position.setLength(newEnd - offset);
- } else if (end > eventOffset + eventOldLength) {
- // event extends from before position into it - adjust offset
- // and length
- // offset becomes end of event, length adjusted accordingly
- int newOffset= eventOffset + eventNewLength;
- position.setOffset(newOffset);
- position.setLength(end - newOffset);
- } else {
- // event consumes the position - delete it
- position.delete();
- }
- }
- } catch (BadPositionCategoryException e) {
- // ignore and return
- }
- }
-
- /**
- * Returns the position category.
- *
- * @return the position category
- */
- public String getCategory() {
- return fCategory;
- }
-
- }
-
- private class BracketInserter implements VerifyKeyListener, ILinkedModeListener {
-
- private boolean fCloseBrackets= true;
- private boolean fCloseStrings= true;
- private boolean fCloseAngularBrackets= true;
- private final String CATEGORY= toString();
- private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY);
- private Stack fBracketLevelStack= new Stack();
-
- public void setCloseBracketsEnabled(boolean enabled) {
- fCloseBrackets= enabled;
- }
-
- public void setCloseStringsEnabled(boolean enabled) {
- fCloseStrings= enabled;
- }
-
- public void setCloseAngularBracketsEnabled(boolean enabled) {
- fCloseAngularBrackets= enabled;
- }
-
- private boolean isAngularIntroducer(String identifier) {
- return identifier.length() > 0
- && (Character.isUpperCase(identifier.charAt(0))
- || identifier.startsWith("final") //$NON-NLS-1$
- || identifier.startsWith("public") //$NON-NLS-1$
- || identifier.startsWith("public") //$NON-NLS-1$
- || identifier.startsWith("protected") //$NON-NLS-1$
- || identifier.startsWith("private")); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
- */
- public void verifyKey(VerifyEvent event) {
-
- // early pruning to slow down normal typing as little as possible
- if (!event.doit || getInsertMode() != SMART_INSERT)
- return;
- switch (event.character) {
- case '(':
- case '<':
- case '[':
- case '\'':
- case '\"':
- case '{':
- break;
- default:
- return;
- }
-
- final ISourceViewer sourceViewer= getSourceViewer();
- IDocument document= sourceViewer.getDocument();
-
- final Point selection= sourceViewer.getSelectedRange();
- final int offset= selection.x;
- final int length= selection.y;
-
- try {
- IRegion startLine= document.getLineInformationOfOffset(offset);
- IRegion endLine= document.getLineInformationOfOffset(offset + length);
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- int nextToken= scanner.nextToken(offset + length, endLine.getOffset() + endLine.getLength());
- String next= nextToken == Symbols.TokenEOF ? null : document.get(offset, scanner.getPosition() - offset).trim();
- int prevToken= scanner.previousToken(offset - 1, startLine.getOffset());
- int prevTokenOffset= scanner.getPosition() + 1;
- String previous= prevToken == Symbols.TokenEOF ? null : document.get(prevTokenOffset, offset - prevTokenOffset).trim();
-
- switch (event.character) {
- case '(':
- if (!fCloseBrackets
- || nextToken == Symbols.TokenLPAREN
- || nextToken == Symbols.TokenIDENT
- || next != null && next.length() > 1)
- return;
- break;
-
- case '<':
- if (!(fCloseAngularBrackets && fCloseBrackets)
- || nextToken == Symbols.TokenLESSTHAN
- || prevToken != Symbols.TokenLBRACE
- && prevToken != Symbols.TokenRBRACE
- && prevToken != Symbols.TokenSEMICOLON
- && prevToken != Symbols.TokenSYNCHRONIZED
- && prevToken != Symbols.TokenSTATIC
- && (prevToken != Symbols.TokenIDENT || !isAngularIntroducer(previous))
- && prevToken != Symbols.TokenEOF)
- return;
- break;
-
- case '{':
- case '[':
- if (!fCloseBrackets
- || nextToken == Symbols.TokenIDENT
- || next != null && next.length() > 1)
- return;
- break;
-
- case '\'':
- case '"':
- if (!fCloseStrings
- || nextToken == Symbols.TokenIDENT
- || prevToken == Symbols.TokenIDENT
- || next != null && next.length() > 1
- || previous != null && previous.length() > 1)
- return;
- break;
-
- default:
- return;
- }
-
- ITypedRegion partition= TextUtilities.getPartition(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, true);
- if (!IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()))
- return;
-
- if (!validateEditorInputState())
- return;
-
- final char character= event.character;
- final char closingCharacter= getPeerCharacter(character);
- final StringBuffer buffer= new StringBuffer();
- buffer.append(character);
- buffer.append(closingCharacter);
-
- document.replace(offset, length, buffer.toString());
-
-
- BracketLevel level= new BracketLevel();
- fBracketLevelStack.push(level);
-
- LinkedPositionGroup group= new LinkedPositionGroup();
- group.addPosition(new LinkedPosition(document, offset + 1, 0, LinkedPositionGroup.NO_STOP));
-
- LinkedModeModel model= new LinkedModeModel();
- model.addLinkingListener(this);
- model.addGroup(group);
- model.forceInstall();
-
- level.fOffset= offset;
- level.fLength= 2;
-
- // set up position tracking for our magic peers
- if (fBracketLevelStack.size() == 1) {
- document.addPositionCategory(CATEGORY);
- document.addPositionUpdater(fUpdater);
- }
- level.fFirstPosition= new Position(offset, 1);
- level.fSecondPosition= new Position(offset + 1, 1);
- document.addPosition(CATEGORY, level.fFirstPosition);
- document.addPosition(CATEGORY, level.fSecondPosition);
-
- level.fUI= new EditorLinkedModeUI(model, sourceViewer);
- level.fUI.setSimpleMode(true);
- level.fUI.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack));
- level.fUI.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE);
- level.fUI.setCyclingMode(LinkedModeUI.CYCLE_NEVER);
- level.fUI.enter();
-
-
- IRegion newSelection= level.fUI.getSelectedRegion();
- sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
-
- event.doit= false;
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } catch (BadPositionCategoryException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void left(LinkedModeModel environment, int flags) {
-
- final BracketLevel level= (BracketLevel) fBracketLevelStack.pop();
-
- if (flags != ILinkedModeListener.EXTERNAL_MODIFICATION)
- return;
-
- // remove brackets
- final ISourceViewer sourceViewer= getSourceViewer();
- final IDocument document= sourceViewer.getDocument();
- if (document instanceof IDocumentExtension) {
- IDocumentExtension extension= (IDocumentExtension) document;
- extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() {
-
- public void perform(IDocument d, IDocumentListener owner) {
- if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0)
- && !level.fSecondPosition.isDeleted
- && level.fSecondPosition.offset == level.fFirstPosition.offset)
- {
- try {
- document.replace(level.fSecondPosition.offset,
- level.fSecondPosition.length,
- ""); //$NON-NLS-1$
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- if (fBracketLevelStack.size() == 0) {
- document.removePositionUpdater(fUpdater);
- try {
- document.removePositionCategory(CATEGORY);
- } catch (BadPositionCategoryException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- });
- }
-
-
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#suspend(org.eclipse.jface.text.link.LinkedModeModel)
- */
- public void suspend(LinkedModeModel environment) {
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#resume(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void resume(LinkedModeModel environment, int flags) {
- }
- }
-
- /**
- * Remembers data related to the current selection to be able to
- * restore it later.
- *
- *
- */
- private class RememberedSelection {
- /** The remembered selection start. */
- private RememberedOffset fStartOffset= new RememberedOffset();
- /** The remembered selection end. */
- private RememberedOffset fEndOffset= new RememberedOffset();
-
- /**
- * Remember current selection.
- */
- public void remember() {
- /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
- * This method may be called inside an asynchronous call posted
- * to the UI thread, so protect against intermediate disposal
- * of the editor.
- */
- ISourceViewer viewer= getSourceViewer();
- if (viewer != null) {
- Point selection= viewer.getSelectedRange();
- int startOffset= selection.x;
- int endOffset= startOffset + selection.y;
-
- fStartOffset.setOffset(startOffset);
- fEndOffset.setOffset(endOffset);
- }
- }
-
- /**
- * Restore remembered selection.
- */
- public void restore() {
- /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
- * This method may be called inside an asynchronous call posted
- * to the UI thread, so protect against intermediate disposal
- * of the editor.
- */
- if (getSourceViewer() == null)
- return;
-
- try {
-
- int startOffset, endOffset;
- int revealStartOffset, revealEndOffset;
- if (showsHighlightRangeOnly()) {
- IJavaScriptElement newStartElement= fStartOffset.getElement();
- startOffset= fStartOffset.getRememberedOffset(newStartElement);
- revealStartOffset= fStartOffset.getRevealOffset(newStartElement, startOffset);
- if (revealStartOffset == -1)
- startOffset= -1;
-
- IJavaScriptElement newEndElement= fEndOffset.getElement();
- endOffset= fEndOffset.getRememberedOffset(newEndElement);
- revealEndOffset= fEndOffset.getRevealOffset(newEndElement, endOffset);
- if (revealEndOffset == -1)
- endOffset= -1;
- } else {
- startOffset= fStartOffset.getOffset();
- revealStartOffset= startOffset;
- endOffset= fEndOffset.getOffset();
- revealEndOffset= endOffset;
- }
-
- if (startOffset == -1) {
- startOffset= endOffset; // fallback to caret offset
- revealStartOffset= revealEndOffset;
- }
-
- if (endOffset == -1) {
- endOffset= startOffset; // fallback to other offset
- revealEndOffset= revealStartOffset;
- }
-
- IJavaScriptElement element;
- if (endOffset == -1) {
- // fallback to element selection
- element= fEndOffset.getElement();
- if (element == null)
- element= fStartOffset.getElement();
- if (element != null)
- setSelection(element);
- return;
- }
-
- if (isValidSelection(revealStartOffset, revealEndOffset - revealStartOffset) && isValidSelection(startOffset, endOffset - startOffset))
- selectAndReveal(startOffset, endOffset - startOffset, revealStartOffset, revealEndOffset - revealStartOffset);
- } finally {
- fStartOffset.clear();
- fEndOffset.clear();
- }
- }
-
- private boolean isValidSelection(int offset, int length) {
- IDocumentProvider provider= getDocumentProvider();
- if (provider != null) {
- IDocument document= provider.getDocument(getEditorInput());
- if (document != null) {
- int end= offset + length;
- int documentLength= document.getLength();
- return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength && length >= 0;
- }
- }
- return false;
- }
-
- }
-
- /**
- * Remembers additional data for a given
- * offset to be able restore it later.
- *
- *
- */
- private class RememberedOffset {
- /** Remembered line for the given offset */
- private int fLine;
- /** Remembered column for the given offset*/
- private int fColumn;
- /** Remembered Java element for the given offset*/
- private IJavaScriptElement fElement;
- /** Remembered Java element line for the given offset*/
- private int fElementLine;
-
- /**
- * Store visual properties of the given offset.
- *
- * @param offset Offset in the document
- */
- public void setOffset(int offset) {
- try {
- IDocument document= getSourceViewer().getDocument();
- fLine= document.getLineOfOffset(offset);
- fColumn= offset - document.getLineOffset(fLine);
- fElement= getElementAt(offset, true);
- fElementLine= getElementLine(document, fElement);
- } catch (BadLocationException e) {
- // should not happen
- JavaScriptPlugin.log(e);
- clear();
- } catch (JavaScriptModelException e) {
- // should not happen
- JavaScriptPlugin.log(e.getStatus());
- clear();
- }
- }
-
- /**
- * Computes the element line of a java element (the start of the element, or the line with
- * the element's name range).
- *
- * @param document the displayed document for line information
- * @param element the java element, may be <code>null</code>
- * @return the element's start line, or -1
- * @throws BadLocationException
- * @throws JavaScriptModelException
- *
- */
- private int getElementLine(IDocument document, IJavaScriptElement element) throws BadLocationException, JavaScriptModelException {
- if (element instanceof IMember) {
- ISourceRange range= ((IMember) element).getNameRange();
- if (range != null)
- return document.getLineOfOffset(range.getOffset());
- }
- int elementOffset= getOffset(element);
- if (elementOffset != -1)
- return document.getLineOfOffset(elementOffset);
- return -1;
- }
-
- /**
- * Return offset recomputed from stored visual properties.
- *
- * @return Offset in the document
- */
- public int getOffset() {
- IJavaScriptElement newElement= getElement();
-
- int offset= getRememberedOffset(newElement);
-
- if (offset == -1 || newElement != null && !containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1)))
- return -1;
-
- return offset;
- }
-
- /**
- * Return offset recomputed from stored visual properties.
- *
- * @param newElement Enclosing element
- * @return Offset in the document
- */
- public int getRememberedOffset(IJavaScriptElement newElement) {
- try {
- IDocument document= getSourceViewer().getDocument();
- int newElementLine= getElementLine(document, newElement);
- int newLine= fLine;
- if (newElementLine != -1 && fElementLine != -1)
- newLine += newElementLine - fElementLine;
-
- if (newLine < 0 || newLine >= document.getNumberOfLines())
- return -1;
- int maxColumn= document.getLineLength(newLine);
- String lineDelimiter= document.getLineDelimiter(newLine);
- if (lineDelimiter != null)
- maxColumn= maxColumn - lineDelimiter.length();
- int offset;
- if (fColumn > maxColumn)
- offset= document.getLineOffset(newLine) + maxColumn;
- else
- offset= document.getLineOffset(newLine) + fColumn;
-
- return offset;
- } catch (BadLocationException e) {
- // should not happen
- JavaScriptPlugin.log(e);
- return -1;
- } catch (JavaScriptModelException e) {
- // should not happen
- JavaScriptPlugin.log(e.getStatus());
- return -1;
- }
- }
-
- /**
- * Returns the offset used to reveal the given element based on the given selection offset.
- * @param element the element
- * @param offset the selection offset
- * @return the offset to reveal the given element based on the given selection offset
- */
- public int getRevealOffset(IJavaScriptElement element, int offset) {
- if (element == null || offset == -1)
- return -1;
-
- if (containsOffset(element, offset)) {
- if (offset > 0) {
- IJavaScriptElement alternateElement= getElementAt(offset, false);
- if (element.getHandleIdentifier().equals(alternateElement.getParent().getHandleIdentifier()))
- return offset - 1; // Solves test case 2 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
- }
- return offset;
- } else if (offset > 0 && containsOffset(element, offset - 1))
- return offset - 1; // Solves test case 1 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
-
- return -1;
- }
-
- /**
- * Return Java element recomputed from stored visual properties.
- *
- * @return Java element
- */
- public IJavaScriptElement getElement() {
- if (fElement == null)
- return null;
-
- return findElement(fElement);
- }
-
- /**
- * Clears the stored position
- */
- public void clear() {
- fLine= -1;
- fColumn= -1;
- fElement= null;
- fElementLine= -1;
- }
-
- /**
- * Does the given Java element contain the given offset?
- * @param element Java element
- * @param offset Offset
- * @return <code>true</code> iff the Java element contains the offset
- */
- private boolean containsOffset(IJavaScriptElement element, int offset) {
- int elementOffset= getOffset(element);
- int elementLength= getLength(element);
- return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false;
- }
- /**
- * Returns the offset of the given Java element.
- *
- * @param element Java element
- * @return Offset of the given Java element
- */
- private int getOffset(IJavaScriptElement element) {
- if (element instanceof ISourceReference) {
- ISourceReference sr= (ISourceReference) element;
- try {
- ISourceRange srcRange= sr.getSourceRange();
- if (srcRange != null)
- return srcRange.getOffset();
- } catch (JavaScriptModelException e) {
- }
- }
- return -1;
- }
-
- /**
- * Returns the length of the given Java element.
- *
- * @param element Java element
- * @return Length of the given Java element
- */
- private int getLength(IJavaScriptElement element) {
- if (element instanceof ISourceReference) {
- ISourceReference sr= (ISourceReference) element;
- try {
- ISourceRange srcRange= sr.getSourceRange();
- if (srcRange != null)
- return srcRange.getLength();
- } catch (JavaScriptModelException e) {
- }
- }
- return -1;
- }
-
- /**
- * Returns the updated java element for the old java element.
- *
- * @param element Old Java element
- * @return Updated Java element
- */
- private IJavaScriptElement findElement(IJavaScriptElement element) {
-
- if (element == null)
- return null;
-
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- IJavaScriptUnit unit= manager.getWorkingCopy(getEditorInput());
-
- if (unit != null) {
- try {
- JavaModelUtil.reconcile(unit);
- IJavaScriptElement[] findings= unit.findElements(element);
- if (findings != null && findings.length > 0)
- return findings[0];
-
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x.getStatus());
- // nothing found, be tolerant and go on
- }
- }
-
- return null;
- }
-
- }
-
- /** Preference key for code formatter tab size */
- private final static String CODE_FORMATTER_TAB_SIZE= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
- /** Preference key for inserting spaces rather than tabs */
- private final static String SPACES_FOR_TABS= DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR;
- /** Preference key for automatically closing strings */
- private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
- /** Preference key for automatically closing brackets and parenthesis */
- private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
-
-
- /** The editor's save policy */
- protected ISavePolicy fSavePolicy;
- /** Listener to annotation model changes that updates the error tick in the tab image */
- private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
- /**
- * The remembered selection.
- *
- */
- private RememberedSelection fRememberedSelection= new RememberedSelection();
- /** The bracket inserter. */
- private BracketInserter fBracketInserter= new BracketInserter();
-
- /** The standard action groups added to the menu */
- private GenerateActionGroup fGenerateActionGroup;
- private CompositeActionGroup fContextMenuGroup;
-
- private CorrectionCommandInstaller fCorrectionCommands;
-
- /**
- * Reconciling listeners.
- *
- */
- private ListenerList fReconcilingListeners= new ListenerList(ListenerList.IDENTITY);
-
- /**
- * Mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898
- * for a description of the problem.
- * <p>
- * XXX remove once the underlying problem (https://bugs.eclipse.org/bugs/show_bug.cgi?id=66176) is solved.
- * </p>
- */
- private final Object fReconcilerLock= new Object();
-
-
-
-
-
- /**
- * Creates a new compilation unit editor.
- */
- public CompilationUnitEditor() {
- super();
- setDocumentProvider(JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider());
- setEditorContextMenuId("#JavaScriptEditorContext"); //$NON-NLS-1$
- setRulerContextMenuId("#JavaScriptRulerContext"); //$NON-NLS-1$
- setOutlinerContextMenuId("#JavaScriptOutlinerContext"); //$NON-NLS-1$
- // don't set help contextId, we install our own help context
- fSavePolicy= null;
-
- fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
- fCorrectionCommands= null;
- }
-
- /*
- * @see AbstractTextEditor#createActions()
- */
- protected void createActions() {
-
- super.createActions();
-
- IAction action= new ContentAssistAction(JavaEditorMessages.getBundleForConstructedKeys(), "ContentAssistProposal.", this); //$NON-NLS-1$
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- setAction("ContentAssistProposal", action); //$NON-NLS-1$
- markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
- setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
- markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
- setAction("Comment", action); //$NON-NLS-1$
- markAsStateDependentAction("Comment", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
- setAction("Uncomment", action); //$NON-NLS-1$
- markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
-
- action= new ToggleCommentAction(JavaEditorMessages.getBundleForConstructedKeys(), "ToggleComment.", this); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_COMMENT);
- setAction("ToggleComment", action); //$NON-NLS-1$
- markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
- configureToggleCommentAction();
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
- setAction("Format", action); //$NON-NLS-1$
- markAsStateDependentAction("Format", true); //$NON-NLS-1$
- markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
-
- action= new AddBlockCommentAction(JavaEditorMessages.getBundleForConstructedKeys(), "AddBlockComment.", this); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
- setAction("AddBlockComment", action); //$NON-NLS-1$
- markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
- markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
-
- action= new RemoveBlockCommentAction(JavaEditorMessages.getBundleForConstructedKeys(), "RemoveBlockComment.", this); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
- setAction("RemoveBlockComment", action); //$NON-NLS-1$
- markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
- markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
-
- action= new IndentAction(JavaEditorMessages.getBundleForConstructedKeys(), "Indent.", this, false); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT);
- setAction("Indent", action); //$NON-NLS-1$
- markAsStateDependentAction("Indent", true); //$NON-NLS-1$
- markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
-
- action= new IndentAction(JavaEditorMessages.getBundleForConstructedKeys(), "Indent.", this, true); //$NON-NLS-1$
- setAction("IndentOnTab", action); //$NON-NLS-1$
- markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
- markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
-
- // override the text editor actions with indenting move line actions
- JavaMoveLinesAction[] moveLinesActions= JavaMoveLinesAction.createMoveCopyActionSet(JavaEditorMessages.getBundleForConstructedKeys(), this);
- ResourceAction rAction= moveLinesActions[0];
- rAction.setHelpContextId(IAbstractTextEditorHelpContextIds.MOVE_LINES_ACTION);
- rAction.setActionDefinitionId(ITextEditorActionDefinitionIds.MOVE_LINES_UP);
- setAction(ITextEditorActionConstants.MOVE_LINE_UP, rAction);
-
- rAction= moveLinesActions[1];
- rAction.setHelpContextId(IAbstractTextEditorHelpContextIds.MOVE_LINES_ACTION);
- rAction.setActionDefinitionId(ITextEditorActionDefinitionIds.MOVE_LINES_DOWN);
- setAction(ITextEditorActionConstants.MOVE_LINE_DOWN, rAction);
-
- rAction= moveLinesActions[2];
- rAction.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_LINES_ACTION);
- rAction.setActionDefinitionId(ITextEditorActionDefinitionIds.COPY_LINES_UP);
- setAction(ITextEditorActionConstants.COPY_LINE_UP, rAction);
-
- rAction= moveLinesActions[3];
- rAction.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_LINES_ACTION);
- rAction.setActionDefinitionId(ITextEditorActionDefinitionIds.COPY_LINES_DOWN);
- setAction(ITextEditorActionConstants.COPY_LINE_DOWN, rAction);
-
- if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
- // don't replace Shift Right - have to make sure their enablement is mutually exclusive
-// removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
- setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
- }
-
- fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
- ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT, false);
- ActionGroup surroundWith= new SurroundWithActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
-
- fActionGroups.addGroup(surroundWith);
- fActionGroups.addGroup(rg);
- fActionGroups.addGroup(fGenerateActionGroup);
-
- // We have to keep the context menu group separate to have better control over positioning
- fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {
- fGenerateActionGroup,
- rg,
- surroundWith,
- new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
-
- fCorrectionCommands= new CorrectionCommandInstaller(); // allow shortcuts for quick fix/assist
- fCorrectionCommands.registerCommands(this);
- }
-
- /*
- * @see JavaEditor#getElementAt(int)
- */
- protected IJavaScriptElement getElementAt(int offset) {
- return getElementAt(offset, true);
- }
-
- /**
- * Returns the most narrow element including the given offset. If <code>reconcile</code>
- * is <code>true</code> the editor's input element is reconciled in advance. If it is
- * <code>false</code> this method only returns a result if the editor's input element
- * does not need to be reconciled.
- *
- * @param offset the offset included by the retrieved element
- * @param reconcile <code>true</code> if working copy should be reconciled
- * @return the most narrow element which includes the given offset
- */
- protected IJavaScriptElement getElementAt(int offset, boolean reconcile) {
- IJavaScriptUnit unit= (IJavaScriptUnit)getInputJavaElement();
-
- if (unit != null) {
- try {
- if (reconcile) {
- JavaModelUtil.reconcile(unit);
- return unit.getElementAt(offset);
- } else if (unit.isConsistent())
- return unit.getElementAt(offset);
-
- } catch (JavaScriptModelException x) {
- if (!x.isDoesNotExist())
- JavaScriptPlugin.log(x.getStatus());
- // nothing found, be tolerant and go on
- }
- }
-
- return null;
- }
-
- /*
- * @see JavaEditor#getCorrespondingElement(IJavaScriptElement)
- */
- protected IJavaScriptElement getCorrespondingElement(IJavaScriptElement element) {
- // XXX: With new working copy story: original == working copy.
- // Note that the previous code could result in a reconcile as side effect. Should check if that
- // is still required.
- return element;
- }
-
- /*
- * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
- */
- public void editorContextMenuAboutToShow(IMenuManager menu) {
- super.editorContextMenuAboutToShow(menu);
-
- ActionContext context= new ActionContext(getSelectionProvider().getSelection());
- fContextMenuGroup.setContext(context);
- fContextMenuGroup.fillContextMenu(menu);
- fContextMenuGroup.setContext(null);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
- IDocumentProvider p= getDocumentProvider();
- if (p instanceof ICompilationUnitDocumentProvider) {
- ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
- cp.setSavePolicy(fSavePolicy);
- }
- try {
- super.performSave(overwrite, progressMonitor);
- } finally {
- if (p instanceof ICompilationUnitDocumentProvider) {
- ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
- cp.setSavePolicy(null);
- }
- }
- }
-
- /*
- * @see AbstractTextEditor#doSave(IProgressMonitor)
- */
- public void doSave(IProgressMonitor progressMonitor) {
-
- IDocumentProvider p= getDocumentProvider();
- if (p == null) {
- // editor has been closed
- return;
- }
-
- if (p.isDeleted(getEditorInput())) {
-
- if (isSaveAsAllowed()) {
-
- /*
- * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
- * Changed Behavior to make sure that if called inside a regular save (because
- * of deletion of input element) there is a way to report back to the caller.
- */
- performSaveAs(progressMonitor);
-
- } else {
-
- /*
- * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
- * Missing resources.
- */
- Shell shell= getSite().getShell();
- MessageDialog.openError(shell, JavaEditorMessages.CompilationUnitEditor_error_saving_title1, JavaEditorMessages.CompilationUnitEditor_error_saving_message1);
- }
-
- } else {
-
- setStatusLineErrorMessage(null);
-
- updateState(getEditorInput());
- validateState(getEditorInput());
-
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- IJavaScriptUnit unit= manager.getWorkingCopy(getEditorInput());
-
- if (unit != null) {
- synchronized (unit) {
- performSave(false, progressMonitor);
- }
- } else
- performSave(false, progressMonitor);
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#openSaveErrorDialog(java.lang.String, java.lang.String, org.eclipse.core.runtime.CoreException)
- *
- */
- protected void openSaveErrorDialog(String title, String message, CoreException exception) {
- IStatus status= exception.getStatus();
- if (JavaScriptUI.ID_PLUGIN.equals(status.getPlugin()) && status.getCode() == IJavaStatusConstants.EDITOR_POST_SAVE_NOTIFICATION) {
- int mask= IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR;
- ErrorDialog dialog = new ErrorDialog(getSite().getShell(), title, message, status, mask) {
- protected Control createDialogArea(Composite parent) {
- parent= (Composite)super.createDialogArea(parent);
- Link link= new Link(parent, SWT.NONE);
- link.setText(JavaEditorMessages.CompilationUnitEditor_error_saving_saveParticipant);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.wst.jsdt.ui.preferences.SaveParticipantPreferencePage", null, null).open(); //$NON-NLS-1$
- }
- });
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- link.setLayoutData(gridData);
- return parent;
- }
- };
- dialog.open();
- } else
- super.openSaveErrorDialog(title, message, exception);
- }
-
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- /*
- * @see AbstractTextEditor#doSetInput(IEditorInput)
- */
- protected void doSetInput(IEditorInput input) throws CoreException {
- super.doSetInput(input);
- configureToggleCommentAction();
- if (fJavaEditorErrorTickUpdater != null)
- fJavaEditorErrorTickUpdater.updateEditorImage(getInputJavaElement());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
- *
- */
- protected void installOverrideIndicator(boolean provideAST) {
- super.installOverrideIndicator(provideAST);
-
- if (fOverrideIndicatorManager == null)
- return;
-
- addReconcileListener(fOverrideIndicatorManager);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
- *
- */
- protected void uninstallOverrideIndicator() {
- if (fOverrideIndicatorManager != null)
- removeReconcileListener(fOverrideIndicatorManager);
- super.uninstallOverrideIndicator();
- }
-
- /**
- * Configures the toggle comment action
- *
- *
- */
- private void configureToggleCommentAction() {
- IAction action= getAction("ToggleComment"); //$NON-NLS-1$
- if (action instanceof ToggleCommentAction) {
- ISourceViewer sourceViewer= getSourceViewer();
- SourceViewerConfiguration configuration= getSourceViewerConfiguration();
- ((ToggleCommentAction)action).configure(sourceViewer, configuration);
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#installTabsToSpacesConverter()
- *
- */
- protected void installTabsToSpacesConverter() {
- ISourceViewer sourceViewer= getSourceViewer();
- SourceViewerConfiguration config= getSourceViewerConfiguration();
- if (config != null && sourceViewer instanceof ITextViewerExtension7) {
- int tabWidth= config.getTabWidth(sourceViewer);
- TabsToSpacesConverter tabToSpacesConverter= new TabsToSpacesConverter();
- tabToSpacesConverter.setNumberOfSpacesPerTab(tabWidth);
- IDocumentProvider provider= getDocumentProvider();
- if (provider instanceof ICompilationUnitDocumentProvider) {
- ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider;
- tabToSpacesConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
- } else
- tabToSpacesConverter.setLineTracker(new DefaultLineTracker());
- ((ITextViewerExtension7)sourceViewer).setTabsToSpacesConverter(tabToSpacesConverter);
- updateIndentPrefixes();
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isTabsToSpacesConversionEnabled()
- *
- */
- protected boolean isTabsToSpacesConversionEnabled() {
- IJavaScriptElement element= getInputJavaElement();
- IJavaScriptProject project= element == null ? null : element.getJavaScriptProject();
- String option;
- if (project == null)
- option= JavaScriptCore.getOption(SPACES_FOR_TABS);
- else
- option= project.getOption(SPACES_FOR_TABS, true);
- return JavaScriptCore.SPACE.equals(option);
- }
-
- public void dispose() {
-
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
-
- if (fJavaEditorErrorTickUpdater != null) {
- fJavaEditorErrorTickUpdater.dispose();
- fJavaEditorErrorTickUpdater= null;
- }
-
- if (fCorrectionCommands != null) {
- fCorrectionCommands.deregisterCommands();
- fCorrectionCommands= null;
- }
-
- super.dispose();
- }
-
- /*
- * @see AbstractTextEditor#createPartControl(Composite)
- */
- public void createPartControl(Composite parent) {
-
- super.createPartControl(parent);
-
- IPreferenceStore preferenceStore= getPreferenceStore();
- boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS);
- boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS);
- boolean closeAngularBrackets= JavaScriptCore.VERSION_1_5.compareTo(preferenceStore.getString(JavaScriptCore.COMPILER_SOURCE)) <= 0;
-
- fBracketInserter.setCloseBracketsEnabled(closeBrackets);
- fBracketInserter.setCloseStringsEnabled(closeStrings);
- fBracketInserter.setCloseAngularBracketsEnabled(closeAngularBrackets);
-
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
-
- if (isMarkingOccurrences())
- installOccurrencesFinder(false);
- }
-
- private static char getEscapeCharacter(char character) {
- switch (character) {
- case '"':
- case '\'':
- return '\\';
- default:
- return 0;
- }
- }
-
- private static char getPeerCharacter(char character) {
- switch (character) {
- case '(':
- return ')';
-
- case ')':
- return '(';
-
- case '<':
- return '>';
-
- case '>':
- return '<';
-
- case '[':
- return ']';
-
- case ']':
- return '[';
-
- case '{':
- return '}';
-
- case '}':
- return '{';
-
- case '"':
- return character;
-
- case '\'':
- return character;
-
- default:
- throw new IllegalArgumentException();
- }
- }
-
- /*
- * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
- */
- protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
-
- try {
-
- AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
- if (asv != null) {
-
- String p= event.getProperty();
-
- if (CLOSE_BRACKETS.equals(p)) {
- fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p));
- return;
- }
-
- if (CLOSE_STRINGS.equals(p)) {
- fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p));
- return;
- }
-
- if (JavaScriptCore.COMPILER_SOURCE.equals(p)) {
- boolean closeAngularBrackets= JavaScriptCore.VERSION_1_5.compareTo(getPreferenceStore().getString(p)) <= 0;
- fBracketInserter.setCloseAngularBracketsEnabled(closeAngularBrackets);
- }
-
- if (SPACES_FOR_TABS.equals(p)) {
- if (isTabsToSpacesConversionEnabled())
- installTabsToSpacesConverter();
- else
- uninstallTabsToSpacesConverter();
- return;
- }
-
- if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) {
- if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
- setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
- } else {
- removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$
- }
- }
-
- IContentAssistant c= asv.getContentAssistant();
- if (c instanceof ContentAssistant)
- ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event);
-
- if (CODE_FORMATTER_TAB_SIZE.equals(p) && isTabsToSpacesConversionEnabled()) {
- uninstallTabsToSpacesConverter();
- installTabsToSpacesConverter();
- }
- }
-
- } finally {
- super.handlePreferenceStoreChanged(event);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
- */
- protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
- return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles, store);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
- *
- */
- public void aboutToBeReconciled() {
-
- // Notify AST provider
- JavaScriptPlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
-
- // Notify listeners
- Object[] listeners = fReconcilingListeners.getListeners();
- for (int i = 0, length= listeners.length; i < length; ++i)
- ((IJavaReconcilingListener)listeners[i]).aboutToBeReconciled();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(JavaScriptUnit, boolean, IProgressMonitor)
- *
- */
- public void reconciled(JavaScriptUnit ast, boolean forced, IProgressMonitor progressMonitor) {
-
- // see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=58245
- JavaScriptPlugin javaPlugin= JavaScriptPlugin.getDefault();
- if (javaPlugin == null)
- return;
-
- // Always notify AST provider
- javaPlugin.getASTProvider().reconciled(ast, getInputJavaElement(), progressMonitor);
-
- // Notify listeners
- Object[] listeners = fReconcilingListeners.getListeners();
- for (int i = 0, length= listeners.length; i < length; ++i)
- ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, progressMonitor);
-
- // Update Java Outline page selection
- if (!forced && !progressMonitor.isCanceled()) {
- Shell shell= getSite().getShell();
- if (shell != null && !shell.isDisposed()) {
- shell.getDisplay().asyncExec(new Runnable() {
- public void run() {
- selectionChanged();
- }
- });
- }
- }
- }
-
- /**
- * Tells whether this is the active editor in the active page.
- *
- * @return <code>true</code> if this is the active editor in the active page
- * @see IWorkbenchPage#getActiveEditor
- */
- protected final boolean isActiveEditor() {
- IWorkbenchWindow window= getSite().getWorkbenchWindow();
- IWorkbenchPage page= window.getActivePage();
- if (page == null)
- return false;
- IEditorPart activeEditor= page.getActiveEditor();
- return activeEditor != null && activeEditor.equals(this);
- }
-
- /**
- * Adds the given listener.
- * Has no effect if an identical listener was not already registered.
- *
- * @param listener The reconcile listener to be added
- *
- */
- final void addReconcileListener(IJavaReconcilingListener listener) {
- synchronized (fReconcilingListeners) {
- fReconcilingListeners.add(listener);
- }
- }
-
- /**
- * Removes the given listener.
- * Has no effect if an identical listener was not already registered.
- *
- * @param listener the reconcile listener to be removed
- *
- */
- final void removeReconcileListener(IJavaReconcilingListener listener) {
- synchronized (fReconcilingListeners) {
- fReconcilingListeners.remove(listener);
- }
- }
-
- protected void updateStateDependentActions() {
- super.updateStateDependentActions();
- fGenerateActionGroup.editorStateChanged();
- }
-
- /*
- * @see AbstractTextEditor#rememberSelection()
- */
- protected void rememberSelection() {
- fRememberedSelection.remember();
- }
-
- /*
- * @see AbstractTextEditor#restoreSelection()
- */
- protected void restoreSelection() {
- fRememberedSelection.restore();
- }
-
- /*
- * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
- */
- protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
-
- String oldExtension= ""; //$NON-NLS-1$
- if (originalElement instanceof IFileEditorInput) {
- IFile file= ((IFileEditorInput) originalElement).getFile();
- if (file != null) {
- String ext= file.getFileExtension();
- if (ext != null)
- oldExtension= ext;
- }
- }
-
- String newExtension= ""; //$NON-NLS-1$
- if (movedElement instanceof IFileEditorInput) {
- IFile file= ((IFileEditorInput) movedElement).getFile();
- if (file != null)
- newExtension= file.getFileExtension();
- }
-
- return oldExtension.equals(newExtension);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class required) {
- if (SmartBackspaceManager.class.equals(required)) {
- if (getSourceViewer() instanceof JavaSourceViewer) {
- return ((JavaSourceViewer) getSourceViewer()).getBackspaceManager();
- }
- }
-
- return super.getAdapter(required);
- }
-
- /**
- * Returns the mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898
- * for a description of the problem.
- * <p>
- * XXX remove once the underlying problem (https://bugs.eclipse.org/bugs/show_bug.cgi?id=66176) is solved.
- * </p>
- * @return the lock reconcilers may use to synchronize on
- */
- public Object getReconcilerLock() {
- return fReconcilerLock;
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor#createNavigationActions()
- */
- protected void createNavigationActions() {
- super.createNavigationActions();
-
- final StyledText textWidget= getSourceViewer().getTextWidget();
-
- IAction action= new DeletePreviousSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
- setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
- markAsStateDependentAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, true);
-
- action= new DeleteNextSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
- setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
- markAsStateDependentAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, true);
- }
-
- protected void updateStatusField(String category) {
- super.updateStatusField(category);
-
- if (ITextEditorActionConstants.STATUS_CATEGORY_INPUT_POSITION.equals(category)) {
- IStatusField field = getStatusField(IJavaEditorActionConstants.STATUS_CATEGORY_OFFSET);
- if (field != null) {
- ISourceViewer sourceViewer = getSourceViewer();
- Point selection = sourceViewer.getTextWidget().getSelection();
- int offset1 = widgetOffset2ModelOffset(sourceViewer, selection.x);
- int offset2 = widgetOffset2ModelOffset(sourceViewer, selection.y);
- String text = null;
- if (offset1 != offset2)
- text = "[" + offset1 + "-" + offset2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- else
- text = "[ " + offset1 + " ]"; //$NON-NLS-1$ //$NON-NLS-2$
- field.setText(text);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditorActionContributor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditorActionContributor.java
deleted file mode 100644
index 58fd8ec1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditorActionContributor.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.ui.texteditor.RetargetTextEditorAction;
-import org.eclipse.ui.texteditor.StatusLineContributionItem;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
-
-public class CompilationUnitEditorActionContributor extends BasicCompilationUnitEditorActionContributor {
- private static final boolean _showOffset = Boolean.valueOf((Platform.getDebugOption("org.eclipse.wst.jsdt.ui/statusbar/offset"))).booleanValue() || Platform.inDebugMode() || Platform.inDevelopmentMode(); //$NON-NLS-1$
-
- private RetargetTextEditorAction fToggleInsertModeAction;
-
- private StatusLineContributionItem fOffsetStatusField = null;
-
- public CompilationUnitEditorActionContributor() {
- super();
-
- ResourceBundle b= JavaEditorMessages.getBundleForConstructedKeys();
-
- fToggleInsertModeAction= new RetargetTextEditorAction(b, "CompilationUnitEditorActionContributor.ToggleInsertMode.", IAction.AS_CHECK_BOX); //$NON-NLS-1$
- fToggleInsertModeAction.setActionDefinitionId(ITextEditorActionDefinitionIds.TOGGLE_INSERT_MODE);
-
- if (_showOffset) {
- fOffsetStatusField = new StatusLineContributionItem(IJavaEditorActionConstants.STATUS_CATEGORY_OFFSET, true, 10);
- }
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.BasicEditorActionContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
- */
- public void contributeToMenu(IMenuManager menu) {
- super.contributeToMenu(menu);
-
- IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
- if (editMenu != null) {
- editMenu.appendToGroup(IContextMenuConstants.GROUP_ADDITIONS, fToggleInsertModeAction);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToStatusLine(org.eclipse.jface.action.IStatusLineManager)
- */
- public void contributeToStatusLine(IStatusLineManager manager) {
- super.contributeToStatusLine(manager);
- if (_showOffset) {
- manager.add(fOffsetStatusField);
- }
- }
-
- /*
- * @see IEditorActionBarContributor#setActiveEditor(IEditorPart)
- */
- public void setActiveEditor(IEditorPart part) {
- super.setActiveEditor(part);
-
- ITextEditor textEditor= null;
- ITextEditorExtension textEditorExtension= null;
- if (part instanceof ITextEditor)
- textEditor= (ITextEditor) part;
- if (part instanceof ITextEditorExtension)
- textEditorExtension= (ITextEditorExtension) part;
-
- if(_showOffset && textEditorExtension !=null) {
- textEditorExtension.setStatusField(null, IJavaEditorActionConstants.STATUS_CATEGORY_OFFSET);
- }
-
- // Source menu.
- IActionBars bars= getActionBars();
- bars.setGlobalActionHandler(JdtActionConstants.COMMENT, getAction(textEditor, "Comment")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.UNCOMMENT, getAction(textEditor, "Uncomment")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.TOGGLE_COMMENT, getAction(textEditor, "ToggleComment")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.FORMAT, getAction(textEditor, "Format")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.FORMAT_ELEMENT, getAction(textEditor, "QuickFormat")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.ADD_BLOCK_COMMENT, getAction(textEditor, "AddBlockComment")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.REMOVE_BLOCK_COMMENT, getAction(textEditor, "RemoveBlockComment")); //$NON-NLS-1$
- bars.setGlobalActionHandler(JdtActionConstants.INDENT, getAction(textEditor, "Indent")); //$NON-NLS-1$
-
- IAction action= getAction(textEditor, ActionFactory.REFRESH.getId());
- bars.setGlobalActionHandler(ActionFactory.REFRESH.getId(), action);
-
- fToggleInsertModeAction.setAction(getAction(textEditor, ITextEditorActionConstants.TOGGLE_INSERT_MODE));
-
- if(_showOffset && textEditorExtension !=null) {
- textEditorExtension.setStatusField(fOffsetStatusField, IJavaEditorActionConstants.STATUS_CATEGORY_OFFSET);
- // fOffsetStatusField.setActionHandler(action);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompoundEditExitStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompoundEditExitStrategy.java
deleted file mode 100644
index 583ac955..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompoundEditExitStrategy.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.IExecutionListener;
-import org.eclipse.core.commands.NotHandledException;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.custom.VerifyKeyListener;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Exit strategy for commands that want to fold repeated execution into one compound edit. See
- * {@link org.eclipse.jface.text.IRewriteTarget#endCompoundChange() IRewriteTarget.endCompoundChange}.
- * As long as a strategy is installed on an {@link ITextViewer}, it will detect the end of a
- * compound operation when any of the following conditions becomes true:
- * <ul>
- * <li>the viewer's text widget loses the keyboard focus</li>
- * <li>the mouse is clicked or double clicked inside the viewer's widget</li>
- * <li>a command other than the ones specified is executed</li>
- * <li>the viewer receives any key events that are not modifier combinations</li>
- * </ul>
- * <p>
- * If the end of a compound edit is detected, any registered {@link ICompoundEditListener}s are
- * notified and the strategy is disarmed (spring-loaded).
- * </p>
- *
- *
- */
-public final class CompoundEditExitStrategy {
- /**
- * Listens for events that may trigger the end of a compound edit.
- */
- private final class EventListener implements MouseListener, FocusListener, VerifyKeyListener, IExecutionListener {
-
- /*
- * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseDoubleClick(MouseEvent e) {
- // mouse actions end the compound change
- fireEndCompoundEdit();
- }
-
- /*
- * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseDown(MouseEvent e) {
- // mouse actions end the compound change
- fireEndCompoundEdit();
- }
-
- public void mouseUp(MouseEvent e) {}
-
- public void focusGained(FocusEvent e) {}
-
- /*
- * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
- */
- public void focusLost(FocusEvent e) {
- // losing focus ends the change
- fireEndCompoundEdit();
- }
-
- public void notHandled(String commandId, NotHandledException exception) {}
-
- public void postExecuteFailure(String commandId, ExecutionException exception) {}
-
- public void postExecuteSuccess(String commandId, Object returnValue) {}
-
- /*
- * @see org.eclipse.core.commands.IExecutionListener#preExecute(java.lang.String, org.eclipse.core.commands.ExecutionEvent)
- */
- public void preExecute(String commandId, ExecutionEvent event) {
- // any command other than the known ones end the compound change
- for (int i= 0; i < fCommandIds.length; i++) {
- if (commandId.equals(fCommandIds[i]))
- return;
- }
- fireEndCompoundEdit();
- }
-
- /*
- * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
- */
- public void verifyKey(VerifyEvent event) {
- // any key press that is not a modifier combo ends the compound change
- final int maskWithoutShift= SWT.MODIFIER_MASK & ~SWT.SHIFT;
- if ((event.keyCode & SWT.MODIFIER_MASK) == 0 && (event.stateMask & maskWithoutShift) == 0)
- fireEndCompoundEdit();
- }
-
- }
-
- private final String[] fCommandIds;
- private final EventListener fEventListener= new EventListener();
- private final ListenerList fListenerList= new ListenerList(ListenerList.IDENTITY);
-
- private ITextViewer fViewer;
- private StyledText fWidgetEventSource;
-
- /**
- * Creates a new strategy, equivalent to calling
- * {@linkplain #CompoundEditExitStrategy(String[]) CompoundEditExitStrategy(new String[] &#x7b; commandId &#x7d;)}.
- *
- * @param commandId the command id of the repeatable command
- */
- public CompoundEditExitStrategy(String commandId) {
- if (commandId == null)
- throw new NullPointerException("commandId"); //$NON-NLS-1$
- fCommandIds= new String[] {commandId};
- }
-
- /**
- * Creates a new strategy, ending upon execution of any command other than the ones
- * specified.
- *
- * @param commandIds the ids of the repeatable commands
- */
- public CompoundEditExitStrategy(String[] commandIds) {
- for (int i= 0; i < commandIds.length; i++) {
- if (commandIds[i] == null)
- throw new NullPointerException("commandIds[" + i + "]"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- fCommandIds= new String[commandIds.length];
- System.arraycopy(commandIds, 0, fCommandIds, 0, commandIds.length);
- }
-
- /**
- * Installs the receiver on <code>viewer</code> and arms it. After this call returns, any
- * registered listeners will be notified if a compound edit ends.
- *
- * @param viewer the viewer to install on
- */
- public void arm(ITextViewer viewer) {
- disarm();
- if (viewer == null)
- throw new NullPointerException("editor"); //$NON-NLS-1$
- fViewer= viewer;
- addListeners(fViewer);
- }
-
- /**
- * Disarms the receiver. After this call returns, any registered listeners will be not be
- * notified any more until <code>install</code> is called again. Note that the listeners are
- * not removed.
- * <p>
- * Note that the receiver is automatically disarmed when the end of a compound edit has
- * been detected and before the listeners are notified.
- * </p>
- */
- public void disarm() {
- if (isInstalled()) {
- removeListeners(fViewer);
- fViewer= null;
- }
- }
-
- private void addListeners(ITextViewer viewer) {
- fWidgetEventSource= viewer.getTextWidget();
- if (fWidgetEventSource != null) {
- fWidgetEventSource.addVerifyKeyListener(fEventListener);
- fWidgetEventSource.addMouseListener(fEventListener);
- fWidgetEventSource.addFocusListener(fEventListener);
- }
-
- ICommandService commandService= (ICommandService)PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- if (commandService != null)
- commandService.addExecutionListener(fEventListener);
- }
-
- private void removeListeners(ITextViewer editor) {
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- if (commandService != null)
- commandService.removeExecutionListener(fEventListener);
-
- if (fWidgetEventSource != null) {
- fWidgetEventSource.removeFocusListener(fEventListener);
- fWidgetEventSource.removeMouseListener(fEventListener);
- fWidgetEventSource.removeVerifyKeyListener(fEventListener);
- fWidgetEventSource= null;
- }
- }
-
- private boolean isInstalled() {
- return fViewer != null;
- }
-
- private void fireEndCompoundEdit() {
- disarm();
- Object[] listeners= fListenerList.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ICompoundEditListener listener= (ICompoundEditListener) listeners[i];
- try {
- listener.endCompoundEdit();
- } catch (Exception e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /**
- * Adds a compound edit listener. Multiple registration is possible. Note that the receiver is
- * automatically disarmed before the listeners are notified.
- *
- * @param listener the new listener
- */
- public void addCompoundListener(ICompoundEditListener listener) {
- fListenerList.add(listener);
- }
-
- /**
- * Removes a compound edit listener. If <code>listener</code> is registered multiple times, an
- * arbitrary instance is removed. If <code>listener</code> is not currently registered,
- * nothing happens.
- *
- * @param listener the listener to be removed.
- */
- public void removeCompoundListener(ICompoundEditListener listener) {
- fListenerList.remove(listener);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties
deleted file mode 100644
index 05df3b1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties
+++ /dev/null
@@ -1,218 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-CompilationUnitEditorActionContributor.ToggleInsertMode.label=Sma&rt Insert Mode
-CompilationUnitEditorActionContributor.ToggleInsertMode.tooltip=Toggle Smart Insert Mode
-CompilationUnitEditorActionContributor.ToggleInsertMode.image=
-CompilationUnitEditorActionContributor.ToggleInsertMode.description= Toggles smart insert mode
-
-JavaOutlinePage.ContextMenu.refactoring.label=&Refactor
-JavaOutlinePage.HideFields.description.checked=Shows Vars
-JavaOutlinePage.HideFields.description.unchecked=Hides Vars
-JavaOutlinePage.HideFields.label=Hide Vars
-JavaOutlinePage.HideFields.tooltip.checked=Show Vars
-JavaOutlinePage.HideFields.tooltip.unchecked=Hide Vars
-JavaOutlinePage.HideNonePublicMembers.description.checked=Shows non-public members
-JavaOutlinePage.HideNonePublicMembers.description.unchecked=Hides non-public members
-JavaOutlinePage.HideNonePublicMembers.label=Show Public Members Only
-JavaOutlinePage.HideNonePublicMembers.tooltip.checked=Show Non-Public Members
-JavaOutlinePage.HideNonePublicMembers.tooltip.unchecked=Hide Non-Public Members
-JavaOutlinePage.HideStaticMembers.description.checked=Shows static members
-JavaOutlinePage.HideStaticMembers.description.unchecked=Hides static members
-JavaOutlinePage.HideStaticMembers.label=Hide Static Members
-JavaOutlinePage.HideStaticMembers.tooltip.checked=Show Static Members
-JavaOutlinePage.HideStaticMembers.tooltip.unchecked=Hide Static Members
-
-OpenHierarchy.label=Quick Type &Hierarchy
-OpenHierarchy.dialog.message=&Select the type to open:
-OpenHierarchy.dialog.title=Open Type Hierarchy
-OpenHierarchy.tooltip=Show the Quick Type Hierarchy of the Selected Element
-OpenHierarchy.description=Show the quick type hierarchy of the selected element
-
-OpenOnSelection.label=&Open on Selection
-OpenOnSelection.description=Open an editor on the selected element
-OpenOnSelection.dialog.message=&Select or enter the element to open:
-OpenOnSelection.dialog.title=Open On Selection
-OpenOnSelection.tooltip=Open an Editor on the Selected Element
-
-TogglePresentation.label=Show Source of Selected Element Only
-TogglePresentation.tooltip=Show Source of Selected Element Only
-
-ToggleMarkOccurrencesAction.label= Toggle Mark Occurrences
-ToggleMarkOccurrencesAction.tooltip= Toggle Mark Occurrences
-
-ToggleTextHover.label=Show Text Hover
-ToggleTextHover.tooltip=Show Text Hover
-
-ContentAssistProposal.label=&Default
-ContentAssistProposal.tooltip=Default Content Assist
-ContentAssistProposal.description=Default Content Assist
-
-ContentAssistContextInformation.label=Parameter &Hints
-ContentAssistContextInformation.tooltip=Show Parameter Hints
-ContentAssistContextInformation.description=Show Function Parameter Hints
-
-CorrectionAssistProposal.label=&Quick Fix
-CorrectionAssistProposal.tooltip=Quick Fix
-CorrectionAssistProposal.description=Quick Fix
-
-ShowOutline.label= Quick Out&line
-ShowOutline.tooltip= Shows the Quick Outline of Editor Input
-ShowOutline.description= Shows the quick outline for the editor input
-
-OpenStructure.label= Open Stru&cture
-OpenStructure.tooltip= Opens Structure of Selected Element
-OpenStructure.description= Opens the structure of the selected element
-
-OpenExternalJavadoc.label=Open External JSDoc
-OpenExternalJavadoc.tooltip=Opens JSDoc in an External Browser for the Element at the Cursor Position
-OpenExternalJavadoc.description=Opens JSDoc in an external browser for the element at the cursor position
-
-Comment.label=Co&mment
-Comment.tooltip=Comment the Selected Lines
-Comment.description=Turn the selected lines into JavaScript comments
-
-Uncomment.label=&Uncomment
-Uncomment.tooltip=Uncomment the Selected JavaScript Comment Lines
-Uncomment.description=Uncomment the selected JavaScript comment lines
-
-ToggleComment.label=Togg&le Comment
-ToggleComment.tooltip=Toggle Comment For the Selected Lines
-ToggleComment.description=Toggle comment for the selected lines
-
-AddBlockComment.label=Add &Block Comment
-AddBlockComment.tooltip=Enclose the Selection in a Block Comment
-AddBlockComment.description=Encloses the selection with block comment markers
-
-RemoveBlockComment.label=Remove Bloc&k Comment
-RemoveBlockComment.tooltip=Remove Block Comment Markers Enclosing the Caret
-RemoveBlockComment.description=Removes any block comment markers enclosing the caret
-
-Format.label=&Format
-Format.tooltip=Format the Selected Text
-Format.description=Format the selected text
-
-ShiftRight.label=&Shift Right
-ShiftRight.tooltip=Shift Right
-ShiftRight.description=Shift the selected text to the right
-
-ShiftLeft.label=S&hift Left
-ShiftLeft.tooltip=Shift Left
-ShiftLeft.description=Shift the selected text to the left
-
-Editor.Cut.label=Cu&t
-Editor.Cut.tooltip=Cut
-Editor.Cut.image=
-Editor.Cut.description=Cut
-
-Editor.Copy.label=&Copy
-Editor.Copy.tooltip=Copy
-Editor.Copy.image=
-Editor.Copy.description=Copy
-
-Editor.Paste.label=&Paste
-Editor.Paste.tooltip=Paste
-Editor.Paste.image=
-Editor.Paste.description=Paste
-
-StructureSelectNext.label=&Next Element
-StructureSelectNext.tooltip=Expand Selection to Include Next Sibling
-StructureSelectNext.description=Expand selection to include next sibling
-
-StructureSelectPrevious.label=&Previous Element
-StructureSelectPrevious.tooltip=Expand Selection to Include Previous Sibling
-StructureSelectPrevious.description=Expand selection to include previous sibling
-
-StructureSelectEnclosing.label=&Enclosing Element
-StructureSelectEnclosing.tooltip=Expand Selection to Include Enclosing Element
-StructureSelectEnclosing.description=Expand selection to include enclosing element
-
-StructureSelectHistory.label=&Restore Last Selection
-StructureSelectHistory.tooltip=Restore Last Selection
-StructureSelectHistory.description=Restore last selection
-
-GotoNextMember.label= N&ext Member
-GotoNextMember.tooltip=Move the Caret to the Next Member of the JavaScript file
-GotoNextMember.description=Move the caret to the next member of the JavaScript file
-
-GotoPreviousMember.label= Previ&ous Member
-GotoPreviousMember.tooltip=Move the Caret to the Previous Member of the JavaScript file
-GotoPreviousMember.description=Move the caret to the previous member of the JavaScript file
-
-GotoMatchingBracket.label= Matching &Bracket
-GotoMatchingBracket.tooltip=Go to Matching Bracket
-GotoMatchingBracket.description=Go to Matching Bracket
-
-SourceAttachmentDialog.title=Attachments For ''{0}''
-SourceAttachmentDialog.error.title=Error Attaching Source
-SourceAttachmentDialog.error.message=An error occurred while associating the source
-
-JavaSelectAnnotationRulerAction.QuickFix.label= &Quick Fix
-JavaSelectAnnotationRulerAction.QuickFix.tooltip= Quick Fix
-JavaSelectAnnotationRulerAction.QuickFix.description= Runs Quick Fix on the annotation's line
-JavaSelectAnnotationRulerAction.QuickFix.image=
-
-JavaSelectAnnotationRulerAction.QuickAssist.label= Quick &Assist
-JavaSelectAnnotationRulerAction.QuickAssist.tooltip= Quick Assist
-JavaSelectAnnotationRulerAction.QuickAssist.description= Runs Quick Assist on the annotation's line
-JavaSelectAnnotationRulerAction.QuickAssist.image=
-
-JavaSelectAnnotationRulerAction.GotoAnnotation.label= &Go to Annotation
-JavaSelectAnnotationRulerAction.GotoAnnotation.tooltip= Go to Annotation
-JavaSelectAnnotationRulerAction.GotoAnnotation.description= Selects the annotation in the editor
-JavaSelectAnnotationRulerAction.GotoAnnotation.image=
-
-JavaSelectAnnotationRulerAction.OpenSuperImplementation.label= &Open Super Implementation
-JavaSelectAnnotationRulerAction.OpenSuperImplementation.tooltip= Open Super Implementation
-JavaSelectAnnotationRulerAction.OpenSuperImplementation.description= Opens the super implementation
-JavaSelectAnnotationRulerAction.OpenSuperImplementation.image=
-
-Editor.ChangeEncodingAction.label= Set Encodin&g...
-Editor.ChangeEncodingAction.tooltip= Set Encoding
-Editor.ChangeEncodingAction.image=
-Editor.ChangeEncodingAction.description= Set Encoding
-Editor.ChangeEncodingAction.dialog.title= Set Encoding
-
-Editor.ConvertLineDelimiters.label=C&onvert Line Delimiters To
-
-Editor.ConvertToWindows.label=&Windows
-Editor.ConvertToWindows.tooltip=Converts Line Delimiters to Windows
-Editor.ConvertToWindows.image=
-Editor.ConvertToWindows.description=Converts line delimiters to Windows
-
-Editor.ConvertToUNIX.label=&UNIX
-Editor.ConvertToUNIX.tooltip=Converts Line Delimiters to UNIX
-Editor.ConvertToUNIX.image=
-Editor.ConvertToUNIX.description=Converts line delimiters to UNIX
-
-Editor.ConvertToMac.label=&Mac
-Editor.ConvertToMac.tooltip=Converts line delimiters to Mac
-Editor.ConvertToMac.image=
-Editor.ConvertToMac.description=Converts line delimiters to Mac
-
-Indent.label=Correct &Indentation
-Indent.tooltip=&Indent Current Line to Correct Indentation
-Indent.description=&Indents the current line or selection depending on surrounding source code
-
-Editor.MoveLinesUp.label=Move Lines Up
-Editor.MoveLinesUp.tooltip=Move the Selected Lines Up
-Editor.MoveLinesUp.image=
-Editor.MoveLinesUp.description=Moves the selected lines up
-
-Editor.MoveLinesDown.label=Move Lines Down
-Editor.MoveLinesDown.tooltip=Move the Selected Lines Down
-Editor.MoveLinesDown.image=
-Editor.MoveLinesDown.description=Moves the selected lines down
-
-Editor.ShowInformation.label= Show T&ooltip Description
-Editor.ShowInformation.tooltip= Shows the Tooltip Description
-Editor.ShowInformation.image=
-Editor.ShowInformation.description= Displays information for the current caret location in a sticky hover
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/DocumentAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/DocumentAdapter.java
deleted file mode 100644
index ca0695d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/DocumentAdapter.java
+++ /dev/null
@@ -1,524 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultLineTracker;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.ISynchronizable;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.core.BufferChangedEvent;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IBufferChangedListener;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-/**
- * Adapts <code>IDocument</code> to <code>IBuffer</code>. Uses the
- * same algorithm as the text widget to determine the buffer's line delimiter.
- * All text inserted into the buffer is converted to this line delimiter.
- * This class is <code>public</code> for test purposes only.
- */
-public class DocumentAdapter implements IBuffer, IDocumentListener {
-
- /**
- * Internal implementation of a NULL instanceof IBuffer.
- */
- static private class NullBuffer implements IBuffer {
- public void addBufferChangedListener(IBufferChangedListener listener) {}
- public void append(char[] text) {}
- public void append(String text) {}
- public void close() {}
- public char getChar(int position) { return 0; }
- public char[] getCharacters() { return null; }
- public String getContents() { return null; }
- public int getLength() { return 0; }
- public IOpenable getOwner() { return null; }
- public String getText(int offset, int length) { return null; }
- public IResource getUnderlyingResource() { return null; }
- public boolean hasUnsavedChanges() { return false; }
- public boolean isClosed() { return false; }
- public boolean isReadOnly() { return true; }
- public void removeBufferChangedListener(IBufferChangedListener listener) {}
- public void replace(int position, int length, char[] text) {}
- public void replace(int position, int length, String text) {}
- public void save(IProgressMonitor progress, boolean force) throws JavaScriptModelException {}
- public void setContents(char[] contents) {}
- public void setContents(String contents) {}
- }
-
-
- /** NULL implementing <code>IBuffer</code> */
- public final static IBuffer NULL= new NullBuffer();
-
-
- /**
- * Run the given runnable in the UI thread.
- *
- * @param runnable the runnable
- *
- */
- private static final void run(Runnable runnable) {
- Display currentDisplay= Display.getCurrent();
- if (currentDisplay != null)
- runnable.run();
- else
- Display.getDefault().syncExec(runnable);
- }
-
-
- /**
- * Executes a document set content call in the UI thread.
- */
- protected class DocumentSetCommand implements Runnable {
-
- private String fContents;
-
- public void run() {
- if (!isClosed())
- fDocument.set(fContents);
- }
-
- public void set(String contents) {
- fContents= contents;
- DocumentAdapter.run(this);
- }
- }
-
-
- /**
- * Executes a document replace call in the UI thread.
- */
- protected class DocumentReplaceCommand implements Runnable {
-
- private int fOffset;
- private int fLength;
- private String fText;
-
- public void run() {
- try {
- if (!isClosed())
- fDocument.replace(fOffset, fLength, fText);
- } catch (BadLocationException x) {
- // ignore
- }
- }
-
- public void replace(int offset, int length, String text) {
- fOffset= offset;
- fLength= length;
- fText= text;
- DocumentAdapter.run(this);
- }
- }
-
-
- private static final boolean DEBUG_LINE_DELIMITERS= true;
-
- private IOpenable fOwner;
- private IFile fFile;
- private ITextFileBuffer fTextFileBuffer;
- private IDocument fDocument;
-
- private DocumentSetCommand fSetCmd= new DocumentSetCommand();
- private DocumentReplaceCommand fReplaceCmd= new DocumentReplaceCommand();
-
- private Set fLegalLineDelimiters;
-
- private List fBufferListeners= new ArrayList(3);
- private IStatus fStatus;
-
- /*
- *
- */
- private IPath fPath;
-
- /*
- *
- */
- private LocationKind fLocationKind;
-
-
- /**
- * Constructs a new document adapter.
- *
- * @param owner the owner of this buffer
- * @param path the path of the file that backs the buffer
- *
- */
- public DocumentAdapter(IOpenable owner, IPath path) {
- Assert.isLegal(path != null);
-
- fOwner= owner;
- fPath= path;
- fLocationKind= LocationKind.NORMALIZE;
-
- initialize();
- }
-
- /**
- * Constructs a new document adapter.
- *
- * @param owner the owner of this buffer
- * @param file the <code>IFile</code> that backs the buffer
- */
- public DocumentAdapter(IOpenable owner, IFile file) {
-
- fOwner= owner;
- fFile= file;
- fPath= fFile.getFullPath();
- fLocationKind= LocationKind.IFILE;
-
- initialize();
- }
-
- private void initialize() {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- manager.connect(fPath, fLocationKind, new NullProgressMonitor());
- fTextFileBuffer= manager.getTextFileBuffer(fPath, fLocationKind);
- fDocument= fTextFileBuffer.getDocument();
- } catch (CoreException x) {
- fStatus= x.getStatus();
- fDocument= manager.createEmptyDocument(fPath, fLocationKind);
- if (fDocument instanceof ISynchronizable)
- ((ISynchronizable)fDocument).setLockObject(new Object());
- }
- fDocument.addPrenotifiedDocumentListener(this);
- }
-
- /**
- * Returns the status of this document adapter.
- *
- * @return the status
- */
- public IStatus getStatus() {
- if (fStatus != null)
- return fStatus;
- if (fTextFileBuffer != null)
- return fTextFileBuffer.getStatus();
- return null;
- }
-
- /**
- * Returns the adapted document.
- *
- * @return the adapted document
- */
- public IDocument getDocument() {
- return fDocument;
- }
-
- /*
- * @see IBuffer#addBufferChangedListener(IBufferChangedListener)
- */
- public void addBufferChangedListener(IBufferChangedListener listener) {
- Assert.isNotNull(listener);
- if (!fBufferListeners.contains(listener))
- fBufferListeners.add(listener);
- }
-
- /*
- * @see IBuffer#removeBufferChangedListener(IBufferChangedListener)
- */
- public void removeBufferChangedListener(IBufferChangedListener listener) {
- Assert.isNotNull(listener);
- fBufferListeners.remove(listener);
- }
-
- /*
- * @see IBuffer#append(char[])
- */
- public void append(char[] text) {
- append(new String(text));
- }
-
- /*
- * @see IBuffer#append(String)
- */
- public void append(String text) {
- if (DEBUG_LINE_DELIMITERS) {
- validateLineDelimiters(text);
- }
- fReplaceCmd.replace(fDocument.getLength(), 0, text);
- }
-
- /*
- * @see IBuffer#close()
- */
- public void close() {
-
- if (isClosed())
- return;
-
- IDocument d= fDocument;
- fDocument= null;
- d.removePrenotifiedDocumentListener(this);
-
- if (fTextFileBuffer != null) {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- manager.disconnect(fPath, fLocationKind, new NullProgressMonitor());
- } catch (CoreException x) {
- // ignore
- }
- fTextFileBuffer= null;
- }
-
- fireBufferChanged(new BufferChangedEvent(this, 0, 0, null));
- fBufferListeners.clear();
- }
-
- /*
- * @see IBuffer#getChar(int)
- */
- public char getChar(int position) {
- try {
- return fDocument.getChar(position);
- } catch (BadLocationException x) {
- throw new ArrayIndexOutOfBoundsException();
- }
- }
-
- /*
- * @see IBuffer#getCharacters()
- */
- public char[] getCharacters() {
- String content= getContents();
- return content == null ? null : content.toCharArray();
- }
-
- /*
- * @see IBuffer#getContents()
- */
- public String getContents() {
- return fDocument.get();
- }
-
- /*
- * @see IBuffer#getLength()
- */
- public int getLength() {
- return fDocument.getLength();
- }
-
- /*
- * @see IBuffer#getOwner()
- */
- public IOpenable getOwner() {
- return fOwner;
- }
-
- /*
- * @see IBuffer#getText(int, int)
- */
- public String getText(int offset, int length) {
- try {
- return fDocument.get(offset, length);
- } catch (BadLocationException x) {
- throw new ArrayIndexOutOfBoundsException();
- }
- }
-
- /*
- * @see IBuffer#getUnderlyingResource()
- */
- public IResource getUnderlyingResource() {
- return fFile;
- }
-
- /*
- * @see IBuffer#hasUnsavedChanges()
- */
- public boolean hasUnsavedChanges() {
- return fTextFileBuffer != null ? fTextFileBuffer.isDirty() : false;
- }
-
- /*
- * @see IBuffer#isClosed()
- */
- public boolean isClosed() {
- return fDocument == null;
- }
-
- /*
- * @see IBuffer#isReadOnly()
- */
- public boolean isReadOnly() {
- if (fTextFileBuffer != null)
- return !fTextFileBuffer.isCommitable();
-
- IResource resource= getUnderlyingResource();
- if (resource == null)
- return true;
-
- final ResourceAttributes attributes= resource.getResourceAttributes();
- return attributes == null ? false : attributes.isReadOnly();
- }
-
- /*
- * @see IBuffer#replace(int, int, char[])
- */
- public void replace(int position, int length, char[] text) {
- replace(position, length, new String(text));
- }
-
- /*
- * @see IBuffer#replace(int, int, String)
- */
- public void replace(int position, int length, String text) {
- if (DEBUG_LINE_DELIMITERS) {
- validateLineDelimiters(text);
- }
- fReplaceCmd.replace(position, length, text);
- }
-
- /*
- * @see IBuffer#save(IProgressMonitor, boolean)
- */
- public void save(IProgressMonitor progress, boolean force) throws JavaScriptModelException {
- try {
- if (fTextFileBuffer != null)
- fTextFileBuffer.commit(progress, force);
- } catch (CoreException e) {
- throw new JavaScriptModelException(e);
- }
- }
-
- /*
- * @see IBuffer#setContents(char[])
- */
- public void setContents(char[] contents) {
- setContents(new String(contents));
- }
-
- /*
- * @see IBuffer#setContents(String)
- */
- public void setContents(String contents) {
- int oldLength= fDocument.getLength();
-
- if (contents == null) {
-
- if (oldLength != 0)
- fSetCmd.set(""); //$NON-NLS-1$
-
- } else {
-
- // set only if different
- if (DEBUG_LINE_DELIMITERS) {
- validateLineDelimiters(contents);
- }
-
- if (!contents.equals(fDocument.get()))
- fSetCmd.set(contents);
- }
- }
-
-
- private void validateLineDelimiters(String contents) {
-
- if (fLegalLineDelimiters == null) {
- // collect all line delimiters in the document
- HashSet existingDelimiters= new HashSet();
-
- for (int i= fDocument.getNumberOfLines() - 1; i >= 0; i-- ) {
- try {
- String curr= fDocument.getLineDelimiter(i);
- if (curr != null) {
- existingDelimiters.add(curr);
- }
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
- if (existingDelimiters.isEmpty()) {
- return; // first insertion of a line delimiter: no test
- }
- fLegalLineDelimiters= existingDelimiters;
-
- }
-
- DefaultLineTracker tracker= new DefaultLineTracker();
- tracker.set(contents);
-
- int lines= tracker.getNumberOfLines();
- if (lines <= 1)
- return;
-
- for (int i= 0; i < lines; i++) {
- try {
- String curr= tracker.getLineDelimiter(i);
- if (curr != null && !fLegalLineDelimiters.contains(curr)) {
- StringBuffer buf= new StringBuffer("WARNING: javaeditor.DocumentAdapter added new line delimiter to code: "); //$NON-NLS-1$
- for (int k= 0; k < curr.length(); k++) {
- if (k > 0)
- buf.append(' ');
- buf.append((int)curr.charAt(k));
- }
- IStatus status= new Status(IStatus.WARNING, JavaScriptUI.ID_PLUGIN, IStatus.OK, buf.toString(), new Throwable());
- JavaScriptPlugin.log(status);
- }
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /*
- * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
- */
- public void documentAboutToBeChanged(DocumentEvent event) {
- // there is nothing to do here
- }
-
- /*
- * @see IDocumentListener#documentChanged(DocumentEvent)
- */
- public void documentChanged(DocumentEvent event) {
- fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event.getLength(), event.getText()));
- }
-
- private void fireBufferChanged(BufferChangedEvent event) {
- if (fBufferListeners != null && fBufferListeners.size() > 0) {
- Iterator e= new ArrayList(fBufferListeners).iterator();
- while (e.hasNext())
- ((IBufferChangedListener) e.next()).bufferChanged(event);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java
deleted file mode 100644
index 4a28e35e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-
-
-/**
- * Turns off occurrences highlighting on a java editor until linked mode is
- * left.
- *
- *
- */
-public class EditorHighlightingSynchronizer implements ILinkedModeListener {
-
- private final JavaEditor fEditor;
- private final boolean fWasOccurrencesOn;
-
- /**
- * Creates a new synchronizer.
- *
- * @param editor the java editor the occurrences markers of which will be
- * synchronized with the linked mode
- *
- */
- public EditorHighlightingSynchronizer(JavaEditor editor) {
- Assert.isLegal(editor != null);
- fEditor= editor;
- fWasOccurrencesOn= fEditor.isMarkingOccurrences();
-
- if (fWasOccurrencesOn && !isEditorDisposed())
- fEditor.uninstallOccurrencesFinder();
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void left(LinkedModeModel environment, int flags) {
- if (fWasOccurrencesOn && !isEditorDisposed())
- fEditor.installOccurrencesFinder(true);
- }
-
- /*
- *
- */
- private boolean isEditorDisposed() {
- return fEditor == null || fEditor.getSelectionProvider() == null;
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#suspend(org.eclipse.jface.text.link.LinkedModeModel)
- */
- public void suspend(LinkedModeModel environment) {
- }
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#resume(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void resume(LinkedModeModel environment, int flags) {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java
deleted file mode 100644
index 819f808a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java
+++ /dev/null
@@ -1,633 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IEditorDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.WorkspaceModifyOperation;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.ide.IGotoMarker;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.util.Util;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * A number of routines for working with JavaElements in editors.
- *
- * Use 'isOpenInEditor' to test if an element is already open in a editor
- * Use 'openInEditor' to force opening an element in a editor
- * With 'getWorkingCopy' you get the working copy (element in the editor) of an element
- */
-public class EditorUtility {
-
-
- /**
- * Tests if a CU is currently shown in an editor
- *
- * @return the IEditorPart if shown, null if element is not open in an editor
- */
- public static IEditorPart isOpenInEditor(Object inputElement) {
- IEditorInput input= null;
-
- try {
- input= getEditorInput(inputElement);
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x.getStatus());
- }
-
- if (input != null) {
- IWorkbenchPage p= JavaScriptPlugin.getActivePage();
- if (p != null) {
- return p.findEditor(input);
- }
- }
-
- return null;
- }
-
- /**
- * Opens a Java editor for an element such as <code>IJavaScriptElement</code>, <code>IFile</code>, or <code>IStorage</code>.
- * The editor is activated by default.
- *
- * @return an open editor or <code>null</code> if an external editor was opened
- * @throws PartInitException if the editor could not be opened or the input element is not valid
- */
- public static IEditorPart openInEditor(Object inputElement) throws JavaScriptModelException, PartInitException {
- return openInEditor(inputElement, true);
- }
-
- /**
- * Opens the editor currently associated with the given element (IJavaScriptElement, IFile, IStorage...)
- *
- * @return an open editor or <code>null</code> if an external editor was opened
- * @throws PartInitException if the editor could not be opened or the input element is not valid
- */
- public static IEditorPart openInEditor(Object inputElement, boolean activate) throws JavaScriptModelException, PartInitException {
-
- if (inputElement instanceof IFile)
- return openInEditor((IFile) inputElement, activate);
-
- if(inputElement instanceof IJavaScriptElement && ((IJavaScriptElement)inputElement).isVirtual()) {
-
- URI hostElementPath = ((IJavaScriptElement)inputElement).getHostPath();
-
- if(hostElementPath!=null) {
- /* See if we can resolve the URI on the workspace */
- IResource realFile = ((IJavaScriptElement)inputElement).getJavaScriptProject().getProject().getWorkspace().getRoot().getFileForLocation(new Path(hostElementPath.getPath()));
- if(realFile==null || !realFile.exists()) {
- realFile = ((IJavaScriptElement)inputElement).getJavaScriptProject().getProject().getWorkspace().getRoot().findMember(hostElementPath.getPath());
- }
- if(realFile!=null) return openInEditor((IFile)realFile, activate);
- return openInEditor(hostElementPath, activate);
- }
-
- }
-
- /*
- * Support to navigate inside non-primary working copy.
- * For now we only support to navigate inside the currently
- * active editor.
- *
- * XXX: once we have FileStoreEditorInput as API,
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=111887
- * we can fix this code by creating the correct editor input
- * in getEditorInput(Object)
- */
- if (inputElement instanceof IJavaScriptElement) {
- IJavaScriptUnit cu= (IJavaScriptUnit)((IJavaScriptElement)inputElement).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null && !JavaModelUtil.isPrimary(cu)) {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IEditorPart editor= page.getActiveEditor();
- if (editor != null) {
- IJavaScriptElement editorCU= EditorUtility.getEditorInputJavaElement(editor, false);
- if (cu.equals(editorCU)) {
- if (activate && page.getActivePart() != editor)
- page.activate(editor);
- return editor;
- }
- }
- }
- }
- }
-
- IEditorInput input= getEditorInput(inputElement);
- if (input == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_no_editorInput);
-
- return openInEditor(input, getEditorID(input), activate);
- }
-
- /**
- * Selects a Java Element in an editor
- */
- public static void revealInEditor(IEditorPart part, IJavaScriptElement element) {
- if (element == null)
- return;
-
- if (part instanceof JavaEditor) {
- ((JavaEditor) part).setSelection(element);
- return;
- }
-
- // Support for non-Java editor
- try {
- ISourceRange range= null;
- if (element instanceof IJavaScriptUnit)
- range= null;
- else if (element instanceof IClassFile)
- range= null;
- else if (element instanceof ILocalVariable)
- range= ((ILocalVariable)element).getNameRange();
- else if (element instanceof IMember)
- range= ((IMember)element).getNameRange();
- else if (element instanceof ISourceReference)
- range= ((ISourceReference)element).getSourceRange();
-
- if (range != null)
- revealInEditor(part, range.getOffset(), range.getLength());
- } catch (JavaScriptModelException e) {
- // don't reveal
- }
- }
-
- /**
- * Selects and reveals the given region in the given editor part.
- */
- public static void revealInEditor(IEditorPart part, IRegion region) {
- if (part != null && region != null)
- revealInEditor(part, region.getOffset(), region.getLength());
- }
-
- /**
- * Selects and reveals the given offset and length in the given editor part.
- */
- public static void revealInEditor(IEditorPart editor, final int offset, final int length) {
- if (editor instanceof ITextEditor) {
- ((ITextEditor)editor).selectAndReveal(offset, length);
- return;
- }
-
- // Support for non-text editor - try IGotoMarker interface
- if (editor instanceof IGotoMarker) {
- final IEditorInput input= editor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- final IGotoMarker gotoMarkerTarget= (IGotoMarker)editor;
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- protected void execute(IProgressMonitor monitor) throws CoreException {
- IMarker marker= null;
- try {
- marker= ((IFileEditorInput)input).getFile().createMarker(IMarker.TEXT);
- marker.setAttribute(IMarker.CHAR_START, offset);
- marker.setAttribute(IMarker.CHAR_END, offset + length);
-
- gotoMarkerTarget.gotoMarker(marker);
-
- } finally {
- if (marker != null)
- marker.delete();
- }
- }
- };
-
- try {
- op.run(null);
- } catch (InvocationTargetException ex) {
- // reveal failed
- } catch (InterruptedException e) {
- Assert.isTrue(false, "this operation can not be canceled"); //$NON-NLS-1$
- }
- }
- return;
- }
-
- /*
- * Workaround: send out a text selection
- * XXX: Needs to be improved, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=32214
- */
- if (editor != null && editor.getEditorSite().getSelectionProvider() != null) {
- IEditorSite site= editor.getEditorSite();
- if (site == null)
- return;
-
- ISelectionProvider provider= editor.getEditorSite().getSelectionProvider();
- if (provider == null)
- return;
-
- provider.setSelection(new TextSelection(offset, length));
- }
- }
-
- private static IEditorPart openInEditor(IFile file, boolean activate) throws PartInitException {
- if (file == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_file_must_not_be_null);
-
- IWorkbenchPage p= JavaScriptPlugin.getActivePage();
- if (p == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_no_active_WorkbenchPage);
-
- IEditorPart editorPart= IDE.openEditor(p, file, activate);
- initializeHighlightRange(editorPart);
- return editorPart;
- }
-
- private static IEditorPart openInEditor(URI file, boolean activate) throws PartInitException{
- if (file == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_file_must_not_be_null);
-
- IWorkbenchPage p= JavaScriptPlugin.getActivePage();
- if (p == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_no_active_WorkbenchPage);
-
- IEditorDescriptor desc = PlatformUI.getWorkbench().
- getEditorRegistry().getDefaultEditor(file.getPath());
- if(desc==null) {
- throwPartInitException(JavaEditorMessages.EditorUtility_cantFindEditor + file.toString());
- }
- IEditorPart editorPart= IDE.openEditor(p, file, desc.getId(), activate);
- initializeHighlightRange(editorPart);
- return editorPart;
- }
-
- private static IEditorPart openInEditor(IEditorInput input, String editorID, boolean activate) throws PartInitException {
- Assert.isNotNull(input);
- Assert.isNotNull(editorID);
-
- IWorkbenchPage p= JavaScriptPlugin.getActivePage();
- if (p == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_no_active_WorkbenchPage);
-
- IEditorPart editorPart= p.openEditor(input, editorID, activate);
- initializeHighlightRange(editorPart);
- return editorPart;
- }
-
- private static void throwPartInitException(String message) throws PartInitException {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, message, null);
- throw new PartInitException(status);
- }
-
- private static void initializeHighlightRange(IEditorPart editorPart) {
- if (editorPart instanceof ITextEditor) {
- IAction toggleAction= editorPart.getEditorSite().getActionBars().getGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY);
- boolean enable= toggleAction != null;
- if (enable && editorPart instanceof JavaEditor)
- enable= JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS);
- else
- enable= enable && toggleAction.isEnabled() && toggleAction.isChecked();
- if (enable) {
- if (toggleAction instanceof TextEditorAction) {
- // Reset the action
- ((TextEditorAction)toggleAction).setEditor(null);
- // Restore the action
- ((TextEditorAction)toggleAction).setEditor((ITextEditor)editorPart);
- } else {
- // Uncheck
- toggleAction.run();
- // Check
- toggleAction.run();
- }
- }
- }
- }
-
- private static String getEditorID(IEditorInput input) throws PartInitException {
- Assert.isNotNull(input);
- IEditorDescriptor editorDescriptor;
- if (input instanceof IFileEditorInput)
- editorDescriptor= IDE.getEditorDescriptor(((IFileEditorInput)input).getFile());
- else if (input instanceof InternalClassFileEditorInput )
- return JavaScriptUI.ID_CF_EDITOR;
- else {
- String name= input.getName();
- if (name == null)
- throwPartInitException(JavaEditorMessages.EditorUtility_could_not_find_editorId);
- editorDescriptor= IDE.getEditorDescriptor(name);
- }
- return editorDescriptor.getId();
- }
-
- /**
- * Returns the given editor's input as Java element.
- *
- * @param editor the editor
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- * @return the given editor's input as Java element or <code>null</code> if none
- *
- */
- public static IJavaScriptElement getEditorInputJavaElement(IEditorPart editor, boolean primaryOnly) {
- Assert.isNotNull(editor);
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput == null)
- return null;
-
- IJavaScriptElement je= JavaScriptUI.getEditorInputJavaElement(editorInput);
- if (je != null || primaryOnly)
- return je;
-
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput, false);
- }
-
- private static IEditorInput getEditorInput(IJavaScriptElement element) throws JavaScriptModelException {
- while (element != null) {
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= ((IJavaScriptUnit) element).getPrimary();
- IResource resource= unit.getResource();
- if (resource instanceof IFile)
- return new FileEditorInput((IFile) resource);
- }
-
- if (element instanceof IClassFile)
- {
- String elementName = element.getElementName();
- if (Util.isMetadataFileName(elementName))
- {
- IResource resource=element.getResource();
- if (resource instanceof IFile)
- return new FileEditorInput((IFile) resource);
-
- }
- return new InternalClassFileEditorInput((IClassFile) element);
- }
-
- element= element.getParent();
- }
-
- return null;
- }
-
- public static IEditorInput getEditorInput(Object input) throws JavaScriptModelException {
- if (input instanceof IJavaScriptElement)
- return getEditorInput((IJavaScriptElement) input);
-
- if (input instanceof IFile)
- return new FileEditorInput((IFile) input);
-
- if (JavaModelUtil.isOpenableStorage(input))
- return new JarEntryEditorInput((IStorage)input);
-
- return null;
- }
-
- /**
- * If the current active editor edits a java element return it, else
- * return null
- */
- public static IJavaScriptElement getActiveEditorJavaInput() {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IEditorPart part= page.getActiveEditor();
- if (part != null) {
- IEditorInput editorInput= part.getEditorInput();
- if (editorInput != null) {
- return JavaScriptUI.getEditorInputJavaElement(editorInput);
- }
- }
- }
- return null;
- }
-
- /**
- * Maps the localized modifier name to a code in the same
- * manner as #findModifier.
- *
- * @param modifierName the modifier name
- * @return the SWT modifier bit, or <code>0</code> if no match was found
- *
- */
- public static int findLocalizedModifier(String modifierName) {
- if (modifierName == null)
- return 0;
-
- if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.CTRL)))
- return SWT.CTRL;
- if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT)))
- return SWT.SHIFT;
- if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.ALT)))
- return SWT.ALT;
- if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.COMMAND)))
- return SWT.COMMAND;
-
- return 0;
- }
-
- /**
- * Returns the modifier string for the given SWT modifier
- * modifier bits.
- *
- * @param stateMask the SWT modifier bits
- * @return the modifier string
- *
- */
- public static String getModifierString(int stateMask) {
- String modifierString= ""; //$NON-NLS-1$
- if ((stateMask & SWT.CTRL) == SWT.CTRL)
- modifierString= appendModifierString(modifierString, SWT.CTRL);
- if ((stateMask & SWT.ALT) == SWT.ALT)
- modifierString= appendModifierString(modifierString, SWT.ALT);
- if ((stateMask & SWT.SHIFT) == SWT.SHIFT)
- modifierString= appendModifierString(modifierString, SWT.SHIFT);
- if ((stateMask & SWT.COMMAND) == SWT.COMMAND)
- modifierString= appendModifierString(modifierString, SWT.COMMAND);
-
- return modifierString;
- }
-
- /**
- * Appends to modifier string of the given SWT modifier bit
- * to the given modifierString.
- *
- * @param modifierString the modifier string
- * @param modifier an int with SWT modifier bit
- * @return the concatenated modifier string
- *
- */
- private static String appendModifierString(String modifierString, int modifier) {
- if (modifierString == null)
- modifierString= ""; //$NON-NLS-1$
- String newModifierString= Action.findModifierString(modifier);
- if (modifierString.length() == 0)
- return newModifierString;
- return Messages.format(JavaEditorMessages.EditorUtility_concatModifierStrings, new String[] {modifierString, newModifierString});
- }
-
- /**
- * Returns the Java project for a given editor input or <code>null</code> if no corresponding
- * Java project exists.
- *
- * @param input the editor input
- * @return the corresponding Java project
- *
- *
- */
- public static IJavaScriptProject getJavaProject(IEditorInput input) {
- IJavaScriptProject jProject= null;
- if (input instanceof IFileEditorInput) {
- IProject project= ((IFileEditorInput)input).getFile().getProject();
- if (project != null) {
- jProject= JavaScriptCore.create(project);
- if (!jProject.exists())
- jProject= null;
- }
- } else if (input instanceof IClassFileEditorInput) {
- jProject= ((IClassFileEditorInput)input).getClassFile().getJavaScriptProject();
- }
- return jProject;
- }
-
- /**
- * Returns an array of all editors that have an unsaved content. If the identical content is
- * presented in more than one editor, only one of those editor parts is part of the result.
- *
- * @return an array of all dirty editor parts.
- *
- */
- public static IEditorPart[] getDirtyEditors() {
- Set inputs= new HashSet();
- List result= new ArrayList(0);
- IWorkbench workbench= PlatformUI.getWorkbench();
- IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
- for (int i= 0; i < windows.length; i++) {
- IWorkbenchPage[] pages= windows[i].getPages();
- for (int x= 0; x < pages.length; x++) {
- IEditorPart[] editors= pages[x].getDirtyEditors();
- for (int z= 0; z < editors.length; z++) {
- IEditorPart ep= editors[z];
- IEditorInput input= ep.getEditorInput();
- if (inputs.add(input))
- result.add(ep);
- }
- }
- }
- return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
- }
-
- /**
- * Returns the editors to save before performing global Java-related
- * operations.
- *
- * @param saveUnknownEditors <code>true</code> iff editors with unknown buffer management should also be saved
- * @return the editors to save
- *
- */
- public static IEditorPart[] getDirtyEditorsToSave(boolean saveUnknownEditors) {
- Set inputs= new HashSet();
- List result= new ArrayList(0);
- IWorkbench workbench= PlatformUI.getWorkbench();
- IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
- for (int i= 0; i < windows.length; i++) {
- IWorkbenchPage[] pages= windows[i].getPages();
- for (int x= 0; x < pages.length; x++) {
- IEditorPart[] editors= pages[x].getDirtyEditors();
- for (int z= 0; z < editors.length; z++) {
- IEditorPart ep= editors[z];
- IEditorInput input= ep.getEditorInput();
- if (!mustSaveDirtyEditor(ep, input, saveUnknownEditors))
- continue;
-
- if (inputs.add(input))
- result.add(ep);
- }
- }
- }
- return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
- }
-
- /**
- *
- */
- private static boolean mustSaveDirtyEditor(IEditorPart ep, IEditorInput input, boolean saveUnknownEditors) {
- /*
- * Goal: save all editors that could interfere with refactoring operations.
- *
- * If <code>saveUnknownEditors</code> is <code>false</code>, save all editors
- * for compilation units that are not working copies.
- *
- * If <code>saveUnknownEditors</code> is <code>true</code>, save all editors
- * whose implementation is probably not based on file buffers.
- */
- IResource resource= (IResource) input.getAdapter(IResource.class);
- if (resource == null)
- return saveUnknownEditors;
-
- IJavaScriptElement javaElement= JavaScriptCore.create(resource);
- if (javaElement instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit) javaElement;
- if (!cu.isWorkingCopy()) {
- return true;
- }
- }
-
- if (! (ep instanceof ITextEditor))
- return saveUnknownEditors;
-
- ITextEditor textEditor= (ITextEditor) ep;
- IDocumentProvider documentProvider= textEditor.getDocumentProvider();
- if (! (documentProvider instanceof TextFileDocumentProvider))
- return saveUnknownEditors;
-
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ExternalClassFileEditorInput.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ExternalClassFileEditorInput.java
deleted file mode 100644
index 757e6561..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ExternalClassFileEditorInput.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-/**
- * Editor input for .class files on the file system.
- */
-public class ExternalClassFileEditorInput extends FileEditorInput implements IClassFileEditorInput {
-
- private IClassFile fClassFile;
-
- ExternalClassFileEditorInput(IFile file) {
- super(file);
- refresh();
- }
-
- /*
- * @see IClassFileEditorInput#getClassFile()
- */
- public IClassFile getClassFile() {
- return fClassFile;
- }
-
- /**
- * Refreshes this input element. Workaround for non-updating class file elements.
- */
- public void refresh() {
- Object element= JavaScriptCore.create(getFile());
- if (element instanceof IClassFile)
- fClassFile= (IClassFile) element;
- }
-
- /*
- * @see IAdaptable#getAdapter(Class)
- */
- public Object getAdapter(Class adapter) {
- if (adapter == IClassFile.class)
- return fClassFile;
- return fClassFile.getAdapter(adapter);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/GotoMatchingBracketAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/GotoMatchingBracketAction.java
deleted file mode 100644
index f23a9345..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/GotoMatchingBracketAction.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-public class GotoMatchingBracketAction extends Action {
-
- public final static String GOTO_MATCHING_BRACKET= "GotoMatchingBracket"; //$NON-NLS-1$
-
- private final JavaEditor fEditor;
-
- public GotoMatchingBracketAction(JavaEditor editor) {
- super(JavaEditorMessages.GotoMatchingBracket_label);
- Assert.isNotNull(editor);
- fEditor= editor;
- setEnabled(true);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_MATCHING_BRACKET_ACTION);
- }
-
- public void run() {
- fEditor.gotoMatchingBracket();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IClassFileEditorInput.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IClassFileEditorInput.java
deleted file mode 100644
index f3d4502a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IClassFileEditorInput.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IClassFile;
-
-
-/**
- * Editor input for class files.
- */
-public interface IClassFileEditorInput extends IEditorInput {
-
- /**
- * Returns the class file acting as input.
- */
- public IClassFile getClassFile();
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompilationUnitDocumentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompilationUnitDocumentProvider.java
deleted file mode 100644
index 9eb57b57..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompilationUnitDocumentProvider.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.source.IAnnotationModelListener;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.IDocumentProviderExtension2;
-import org.eclipse.ui.texteditor.IDocumentProviderExtension3;
-import org.eclipse.ui.texteditor.IDocumentProviderExtension5;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- *
- */
-public interface ICompilationUnitDocumentProvider extends IDocumentProvider, IDocumentProviderExtension2, IDocumentProviderExtension3, IDocumentProviderExtension5 {
-
- /**
- * Shuts down this provider.
- */
- void shutdown();
-
- /**
- * Returns the working copy for the given element.
- *
- * @param element the element
- * @return the working copy for the given element
- */
- IJavaScriptUnit getWorkingCopy(Object element);
-
- /**
- * Saves the content of the given document to the given element. This method has
- * only an effect if it is called when directly or indirectly inside <code>saveDocument</code>.
- *
- * @param monitor the progress monitor
- * @param element the element to which to save
- * @param document the document to save
- * @param overwrite <code>true</code> if the save should be enforced
- */
- void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException;
-
- /**
- * Creates a line tracker for the given element. It is of the same kind as the one that would be
- * used for a newly created document for the given element.
- *
- * @param element the element
- * @return a line tracker for the given element
- */
- ILineTracker createLineTracker(Object element);
-
- /**
- * Sets the document provider's save policy.
- *
- * @param savePolicy the save policy
- */
- void setSavePolicy(ISavePolicy savePolicy);
-
- /**
- * Adds a listener that reports changes from all compilation unit annotation models.
- *
- * @param listener the listener
- */
- void addGlobalAnnotationModelListener(IAnnotationModelListener listener);
-
- /**
- * Removes the listener.
- *
- * @param listener the listener
- */
- void removeGlobalAnnotationModelListener(IAnnotationModelListener listener);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java
deleted file mode 100644
index 816b647d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-/**
- * <code>ICompoundEditListener</code>s can be registered with a
- * {@link CompoundEditExitStrategy} to be notified if a compound edit session is ended.
- *
- *
- */
-public interface ICompoundEditListener {
- /**
- * Notifies the receiver that the sending <code>CompoundEditExitStrategy</code> has
- * detected the end of a compound operation.
- */
- void endCompoundEdit();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaAnnotation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaAnnotation.java
deleted file mode 100644
index ae12d980..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaAnnotation.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-/**
- * Interface of annotations representing markers
- * and problems.
- *
- * @see org.eclipse.core.resources.IMarker
- * @see org.eclipse.wst.jsdt.core.compiler.IProblem
- */
-public interface IJavaAnnotation {
-
- /**
- * @see org.eclipse.jface.text.source.Annotation#getType()
- */
- String getType();
-
- /**
- * @see org.eclipse.jface.text.source.Annotation#isPersistent()
- */
- boolean isPersistent();
-
- /**
- * @see org.eclipse.jface.text.source.Annotation#isMarkedDeleted()
- */
- boolean isMarkedDeleted();
-
- /**
- * @see org.eclipse.jface.text.source.Annotation#getText()
- */
- String getText();
-
- /**
- * Returns whether this annotation is overlaid.
- *
- * @return <code>true</code> if overlaid
- */
- boolean hasOverlay();
-
- /**
- * Returns the overlay of this annotation.
- *
- * @return the annotation's overlay
- *
- */
- IJavaAnnotation getOverlay();
-
- /**
- * Returns an iterator for iterating over the
- * annotation which are overlaid by this annotation.
- *
- * @return an iterator over the overlaid annotations
- */
- Iterator getOverlaidIterator();
-
- /**
- * Adds the given annotation to the list of
- * annotations which are overlaid by this annotations.
- *
- * @param annotation the problem annotation
- */
- void addOverlaid(IJavaAnnotation annotation);
-
- /**
- * Removes the given annotation from the list of
- * annotations which are overlaid by this annotation.
- *
- * @param annotation the problem annotation
- */
- void removeOverlaid(IJavaAnnotation annotation);
-
- /**
- * Tells whether this annotation is a problem
- * annotation.
- *
- * @return <code>true</code> if it is a problem annotation
- */
- boolean isProblem();
-
- /**
- * Returns the compilation unit corresponding to the document on which the annotation is set
- * or <code>null</code> if no corresponding compilation unit exists.
- */
- IJavaScriptUnit getCompilationUnit();
-
- /**
- * Returns the problem arguments or <code>null</code> if no problem arguments can be evaluated.
- *
- * @return returns the problem arguments or <code>null</code> if no problem
- * arguments can be evaluated.
- */
- String[] getArguments();
-
- /**
- * Returns the problem id or <code>-1</code> if no problem id can be evaluated.
- *
- * @return returns the problem id or <code>-1</code>
- */
- int getId();
-
- /**
- * Returns the marker type associated to this problem or <code>null<code> if no marker type
- * can be evaluated. See also {@link org.eclipse.wst.jsdt.core.compiler.CategorizedProblem#getMarkerType()}.
- *
- * @return the type of the marker which would be associated to the problem or
- * <code>null<code> if no marker type can be evaluated.
- */
- String getMarkerType();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaEditorActionConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaEditorActionConstants.java
deleted file mode 100644
index 517c9737..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IJavaEditorActionConstants.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-/**
- * Defines action IDs for private JavaEditor actions.
- */
-public interface IJavaEditorActionConstants {
-
- /**
- * ID of the action to toggle smart typing.
- * Value: <code>"smartTyping"</code>
- *
- */
- public static final String TOGGLE_SMART_TYPING= "smartTyping"; //$NON-NLS-1$
-
- /**
- * ID of the smart typing status item
- * Value: <code>"SmartTyping"</code>
- *
- */
- public static final String STATUS_CATEGORY_SMART_TYPING= "SmartTyping"; //$NON-NLS-1$
-
- /**
- * ID of the action to toggle the style of the presentation.
- */
- public static final String TOGGLE_PRESENTATION= "togglePresentation"; //$NON-NLS-1$
-
- /**
- * ID of the action to copy the qualified name.
- *
- */
- public static final String COPY_QUALIFIED_NAME= "copyQualifiedName"; //$NON-NLS-1$
-
- /**
- * ID of the action to show debugging information
- *
- */
- public static final String STATUS_CATEGORY_OFFSET = "showOffset"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ISavePolicy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ISavePolicy.java
deleted file mode 100644
index 1caa1295..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ISavePolicy.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-public interface ISavePolicy {
-
- /**
- *
- */
- void preSave(IJavaScriptUnit unit);
-
- /**
- * Returns the compilation unit in which the argument
- * has been changed. If the argument is not changed, the
- * returned result is <code>null</code>.
- */
- IJavaScriptUnit postSave(IJavaScriptUnit unit);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IndentUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IndentUtil.java
deleted file mode 100644
index 81cad8e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/IndentUtil.java
+++ /dev/null
@@ -1,476 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ILineRange;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaIndenter;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * Utility that indents a number of lines in a document.
- *
- *
- */
-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, IJavaScriptProject, 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 boolean hasChanged;
- private int leftmostLine= -1;
- /**
- * Returns <code>true</code> if the indentation operation changed the
- * document, <code>false</code> if not.
- * @return <code>true</code> if the document was changed
- */
- public boolean hasChanged() {
- return hasChanged;
- }
- }
-
- private IndentUtil() {
- // do not instantiate
- }
-
- /**
- * Indents the line range specified by <code>lines</code> in
- * <code>document</code>. The passed Java 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 Java 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, IJavaScriptProject project, IndentResult result) throws BadLocationException {
- int numberOfLines= lines.getNumberOfLines();
-
- if (numberOfLines < 1)
- return new IndentResult(null);
-
- result= reuseOrCreateToken(result, numberOfLines);
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- JavaIndenter indenter= new JavaIndenter(document, scanner, project);
- boolean changed= false;
- int tabSize= CodeFormatterUtil.getTabWidth(project);
- for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) {
- changed |= indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, tabSize);
- }
- result.hasChanged= changed;
-
- return result;
- }
-
- /**
- * Shifts the line range specified by <code>lines</code> in
- * <code>document</code>. The amount that the lines get shifted
- * are determined by the first line in the range, all subsequent
- * lines are adjusted accordingly. The passed Java 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 shifted
- * @param project the Java 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>shiftLines</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 shiftLines(IDocument document, ILineRange lines, IJavaScriptProject project, IndentResult result) throws BadLocationException {
- int numberOfLines= lines.getNumberOfLines();
-
- if (numberOfLines < 1)
- return new IndentResult(null);
-
- result= reuseOrCreateToken(result, numberOfLines);
- result.hasChanged= false;
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- JavaIndenter indenter= new JavaIndenter(document, scanner, project);
-
- String current= getCurrentIndent(document, lines.getStartLine());
- StringBuffer correct= indenter.computeIndentation(document.getLineOffset(lines.getStartLine()));
- if (correct == null)
- return result; // bail out
-
- int tabSize= CodeFormatterUtil.getTabWidth(project);
- StringBuffer addition= new StringBuffer();
- int difference= subtractIndent(correct, current, addition, tabSize);
-
- if (difference == 0)
- return result;
-
- if (result.leftmostLine == -1)
- result.leftmostLine= getLeftMostLine(document, lines, tabSize);
-
- int maxReduction= computeVisualLength(getCurrentIndent(document, result.leftmostLine + lines.getStartLine()), tabSize);
-
- if (difference > 0) {
- for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++)
- addIndent(document, line, addition, result.commentLinesAtColumnZero, i++);
- } else {
- int reduction= Math.min(-difference, maxReduction);
- for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++)
- cutIndent(document, line, reduction, tabSize, result.commentLinesAtColumnZero, i++);
- }
-
- result.hasChanged= true;
-
- return result;
-
- }
-
- /**
- * 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 commentlines
- * @throws BadLocationException on concurrent document modification
- */
- private static void addIndent(IDocument document, int line, CharSequence indent, boolean[] commentlines, int relative) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int insert= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // go behind line comments
- if (!commentlines[relative]) {
- while (insert < endOffset - 2 && document.get(insert, 2).equals(SLASHES))
- 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.
- * @throws BadLocationException on concurrent document modification
- */
- private static void cutIndent(IDocument document, int line, int toDelete, int tabSize, boolean[] commentLines, int relative) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // go behind line comments
- while (from < endOffset - 2 && document.get(from, 2).equals(SLASHES))
- from += 2;
-
- int to= from;
- while (toDelete > 0 && to < endOffset) {
- char ch= document.getChar(to);
- if (!Character.isWhitespace(ch))
- break;
- toDelete -= computeVisualLength(ch, tabSize);
- if (toDelete >= 0)
- to++;
- else
- break;
- }
-
- if (endOffset > to + 1 && document.get(to, 2).equals(SLASHES))
- commentLines[relative]= true;
-
- document.replace(from, to - from, null);
- }
-
- /**
- * 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 static int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference, int tabSize) {
- int c1= computeVisualLength(correct, tabSize);
- int c2= computeVisualLength(current, tabSize);
- 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, tabSize);
- }
-
-
- return diff;
- }
-
- private static int computeVisualLength(char ch, int tabSize) {
- if (ch == '\t')
- return tabSize;
- else
- return 1;
- }
-
- /**
- * 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 static int computeVisualLength(CharSequence seq, int tablen) {
- int size= 0;
-
- 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 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. The space before the asterix in a javadoc-like
- * comment is not considered part of the indentation.
- *
- * @param document the document
- * @param line the line
- * @return the indentation of <code>line</code> in <code>document</code>
- * @throws BadLocationException if the document is changed concurrently
- */
- private static String getCurrentIndent(IDocument document, int line) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // go behind line comments
- int to= from;
- 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++;
- }
-
- // don't count the space before javadoc like, asterix-style comment lines
- if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
- String type= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, to, true);
- if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT))
- to--;
- }
-
- return document.get(from, to - from);
- }
-
- private static int getLeftMostLine(IDocument document, ILineRange lines, int tabSize) throws BadLocationException {
- int numberOfLines= lines.getNumberOfLines();
- int first= lines.getStartLine();
- int minLine= -1;
- int minIndent= Integer.MAX_VALUE;
- for (int line= 0; line < numberOfLines; line++) {
- int length= computeVisualLength(getCurrentIndent(document, line + first), tabSize);
- if (length < minIndent) {
- minIndent= length;
- minLine= line;
- }
- }
- return minLine;
- }
-
- 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 java heuristic scanner. Javadoc and multi
- * line comments are indented as specified by the
- * <code>JavaDocAutoIndentStrategy</code>.
- *
- * @param document the document
- * @param line the line to be indented
- * @param indenter the java indenter
- * @param scanner the heuristic scanner
- * @param commentLines the indent token comment booleans
- * @param lineIndex the zero-based line index
- * @return <code>true</code> if the document was modified,
- * <code>false</code> if not
- * @throws BadLocationException if the document got changed concurrently
- */
- private static boolean indentLine(IDocument document, int line, JavaIndenter indenter, JavaHeuristicScanner scanner, boolean[] commentLines, int lineIndex, int tabSize) 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, IJavaScriptPartitions.JAVA_PARTITIONING, offset, true);
- ITypedRegion startingPartition= TextUtilities.getPartition(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, false);
- String type= partition.getType();
- if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT)) {
- indent= computeJavadocIndent(document, line, scanner, startingPartition);
- } else if (!commentLines[lineIndex] && startingPartition.getOffset() == offset && startingPartition.getType().equals(IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT)) {
- return false;
- }
- }
-
- // standard java indentation
- if (indent == null) {
- StringBuffer computed= indenter.computeIndentation(offset);
- if (computed != null)
- indent= computed.toString();
- else
- indent= new String();
- }
-
- // change document:
- // get current white space
- int lineLength= currentLine.getLength();
- int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
- if (end == JavaHeuristicScanner.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 (length > 0) {
- ITypedRegion partition= TextUtilities.getPartition(document, IJavaScriptPartitions.JAVA_PARTITIONING, end, false);
- if (partition.getOffset() == end && IJavaScriptPartitions.JAVA_SINGLE_LINE_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);
- return true;
- }
-
- return false;
- }
-
- /**
- * Computes and returns the indentation for a javadoc line. The line
- * must be inside a javadoc comment.
- *
- * @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 static String computeJavadocIndent(IDocument document, int line, JavaHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
- if (line == 0) // impossible - the first line is never inside a javadoc 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 == JavaHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
- if (nonWS == JavaHeuristicScanner.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;
-
- StringBuffer buf= new StringBuffer();
- int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- if (previousLineNonWS == JavaHeuristicScanner.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 == JavaHeuristicScanner.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();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java
deleted file mode 100644
index 712b8026..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-
-/**
- * Class file considered as editor input.
- */
-public class InternalClassFileEditorInput implements IClassFileEditorInput, IPersistableElement {
-
- private IClassFile fClassFile;
-
- public InternalClassFileEditorInput(IClassFile classFile) {
- fClassFile= classFile;
- }
-
- /*
- * @see Object#equals(Object)
- */
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!(obj instanceof InternalClassFileEditorInput))
- return false;
- InternalClassFileEditorInput other= (InternalClassFileEditorInput) obj;
- return fClassFile.equals(other.fClassFile);
- }
-
- /*
- * @see Object#hashCode
- */
- public int hashCode() {
- return fClassFile.hashCode();
- }
-
- /*
- * @see IClassFileEditorInput#getClassFile()
- */
- public IClassFile getClassFile() {
- return fClassFile;
- }
-
- /*
- * @see IEditorInput#getPersistable()
- */
- public IPersistableElement getPersistable() {
- return this;
- }
-
- /*
- * @see IEditorInput#getName()
- */
- public String getName() {
- return fClassFile.getDisplayName();
- }
-
- /*
- * @see IEditorInput#getToolTipText()
- */
- public String getToolTipText() {
- return fClassFile.getType().getFullyQualifiedName();
- }
-
- /*
- * @see IEditorInput#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- try {
- if (fClassFile.isClass())
- return JavaPluginImages.DESC_OBJS_CFILECLASS;
- return JavaPluginImages.DESC_OBJS_CFILEINT;
- } catch (JavaScriptModelException e) {
- // fall through
- }
- return JavaPluginImages.DESC_OBJS_CFILE;
- }
-
- /*
- * @see IEditorInput#exists()
- */
- public boolean exists() {
- return fClassFile.exists();
- }
-
- /*
- * @see IAdaptable#getAdapter(Class)
- */
- public Object getAdapter(Class adapter) {
- if (adapter == IClassFile.class)
- return fClassFile;
- else if(adapter == IJavaScriptElement.class)
- return fClassFile;
- return null;
- }
-
- /*
- * @see IPersistableElement#saveState(IMemento)
- */
- public void saveState(IMemento memento) {
- ClassFileEditorInputFactory.saveState(memento, this);
- }
-
- /*
- * @see IPersistableElement#getFactoryId()
- */
- public String getFactoryId() {
- return ClassFileEditorInputFactory.ID;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JarEntryEditorInput.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JarEntryEditorInput.java
deleted file mode 100644
index 4093e790..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JarEntryEditorInput.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorRegistry;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-
-/**
- * An EditorInput for a JarEntryFile.
- */
-public class JarEntryEditorInput implements IStorageEditorInput {
-
- private IStorage fJarEntryFile;
-
- public JarEntryEditorInput(IStorage jarEntryFile) {
- fJarEntryFile= jarEntryFile;
- }
-
- /*
- */
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!(obj instanceof JarEntryEditorInput))
- return false;
- JarEntryEditorInput other= (JarEntryEditorInput) obj;
- return fJarEntryFile.equals(other.fJarEntryFile);
- }
-
- /*
- * @see IEditorInput#getPersistable()
- */
- public IPersistableElement getPersistable() {
- return null;
- }
-
- /*
- * @see IEditorInput#getName()
- */
- public String getName() {
- return fJarEntryFile.getName();
- }
-
- /*
- * @see IEditorInput#getContentType()
- */
- public String getContentType() {
- return fJarEntryFile.getFullPath().getFileExtension();
- }
-
- /*
- * @see IEditorInput#getToolTipText()
- */
- public String getToolTipText() {
- if (fJarEntryFile instanceof IJarEntryResource) {
- IJarEntryResource jarEntry= (IJarEntryResource)fJarEntryFile;
- IPackageFragmentRoot root= jarEntry.getPackageFragmentRoot();
- IPath fullPath= root.getPath().append(fJarEntryFile.getFullPath());
- if (root.isExternal())
- return fullPath.toOSString();
- return fullPath.toString();
-
- }
-
- IPath fullPath= fJarEntryFile.getFullPath();
- if (fullPath == null)
- return null;
- return fullPath.toString();
- }
-
- /*
- * @see IEditorInput#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry();
- return registry.getImageDescriptor(getContentType());
- }
-
- /*
- * @see IEditorInput#exists()
- */
- public boolean exists() {
- // JAR entries can't be deleted
- return true;
- }
-
- /*
- * @see IAdaptable#getAdapter(Class)
- */
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- /*
- * see IStorageEditorInput#getStorage()
- */
- public IStorage getStorage() {
- return fJarEntryFile;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java
deleted file mode 100644
index 5315ff0a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IAnnotationImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Image provider for annotations based on Java problem markers.
- *
- *
- */
-public class JavaAnnotationImageProvider implements IAnnotationImageProvider {
-
- private final static int NO_IMAGE= 0;
- private final static int GRAY_IMAGE= 1;
- private final static int OVERLAY_IMAGE= 2;
- private final static int QUICKFIX_IMAGE= 3;
- private final static int QUICKFIX_ERROR_IMAGE= 4;
-
-
- private static Image fgQuickFixImage;
- private static Image fgQuickFixErrorImage;
- private static ImageRegistry fgImageRegistry;
-
- private boolean fShowQuickFixIcon;
- private int fCachedImageType;
- private Image fCachedImage;
-
-
- public JavaAnnotationImageProvider() {
- fShowQuickFixIcon= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationImageProvider#getManagedImage(org.eclipse.jface.text.source.Annotation)
- */
- public Image getManagedImage(Annotation annotation) {
- if (annotation instanceof IJavaAnnotation) {
- IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
- int imageType= getImageType(javaAnnotation);
- return getImage(javaAnnotation, imageType, Display.getCurrent());
- }
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationImageProvider#getImageDescriptorId(org.eclipse.jface.text.source.Annotation)
- */
- public String getImageDescriptorId(Annotation annotation) {
- // unmanaged images are not supported
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationImageProvider#getImageDescriptor(java.lang.String)
- */
- public ImageDescriptor getImageDescriptor(String symbolicName) {
- // unmanaged images are not supported
- return null;
- }
-
-
- private boolean showQuickFix(IJavaAnnotation annotation) {
- return fShowQuickFixIcon && annotation.isProblem() && JavaCorrectionProcessor.hasCorrections((Annotation) annotation);
- }
-
- private Image getQuickFixImage() {
- if (fgQuickFixImage == null)
- fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
- return fgQuickFixImage;
- }
-
- private Image getQuickFixErrorImage() {
- if (fgQuickFixErrorImage == null)
- fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
- return fgQuickFixErrorImage;
- }
-
- private ImageRegistry getImageRegistry(Display display) {
- if (fgImageRegistry == null)
- fgImageRegistry= new ImageRegistry(display);
- return fgImageRegistry;
- }
-
- private int getImageType(IJavaAnnotation annotation) {
- int imageType= NO_IMAGE;
- if (annotation.hasOverlay())
- imageType= OVERLAY_IMAGE;
- else if (!annotation.isMarkedDeleted()) {
- if (showQuickFix(annotation))
- imageType= JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(annotation.getType()) ? QUICKFIX_ERROR_IMAGE : QUICKFIX_IMAGE;
- } else {
- imageType= GRAY_IMAGE;
- }
- return imageType;
- }
-
- private Image getImage(IJavaAnnotation annotation, int imageType, Display display) {
- if ((imageType == QUICKFIX_IMAGE || imageType == QUICKFIX_ERROR_IMAGE) && fCachedImageType == imageType)
- return fCachedImage;
-
- Image image= null;
- switch (imageType) {
- case OVERLAY_IMAGE:
- IJavaAnnotation overlay= annotation.getOverlay();
- image= getManagedImage((Annotation) overlay);
- fCachedImageType= -1;
- break;
- case QUICKFIX_IMAGE:
- image= getQuickFixImage();
- fCachedImageType= imageType;
- fCachedImage= image;
- break;
- case QUICKFIX_ERROR_IMAGE:
- image= getQuickFixErrorImage();
- fCachedImageType= imageType;
- fCachedImage= image;
- break;
- case GRAY_IMAGE: {
- ISharedImages sharedImages= PlatformUI.getWorkbench().getSharedImages();
- String annotationType= annotation.getType();
- if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(annotationType)) {
- image= sharedImages.getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
- } else if (JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(annotationType)) {
- image= sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK);
- } else if (JavaMarkerAnnotation.INFO_ANNOTATION_TYPE.equals(annotationType)) {
- image= sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK);
- }
- if (image != null) {
- ImageRegistry registry= getImageRegistry(display);
- String key= Integer.toString(image.hashCode());
- Image grayImage= registry.get(key);
- if (grayImage == null) {
- grayImage= new Image(display, image, SWT.IMAGE_GRAY);
- registry.put(key, grayImage);
- }
- image= grayImage;
- }
- fCachedImageType= -1;
- break;
- }
- }
-
- return image;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java
deleted file mode 100644
index 24b0144c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.Collections;
-import java.util.Iterator;
-
-import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-
-
-/**
- * Filters problems based on their types.
- */
-public class JavaAnnotationIterator implements Iterator {
-
- private Iterator fIterator;
- private Annotation fNext;
- private boolean fSkipIrrelevants;
- private boolean fReturnAllAnnotations;
-
- /**
- * Equivalent to <code>JavaAnnotationIterator(model, skipIrrelevants, false)</code>.
- */
- public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) {
- this(model, skipIrrelevants, false);
- }
-
- /**
- * Returns a new JavaAnnotationIterator.
- * @param model the annotation model
- * @param skipIrrelevants whether to skip irrelevant annotations
- * @param returnAllAnnotations Whether to return non IJavaAnnotations as well
- */
- public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants, boolean returnAllAnnotations) {
- fReturnAllAnnotations= returnAllAnnotations;
- if (model != null)
- fIterator= model.getAnnotationIterator();
- else
- fIterator= Collections.EMPTY_LIST.iterator();
- fSkipIrrelevants= skipIrrelevants;
- skip();
- }
-
- private void skip() {
- while (fIterator.hasNext()) {
- Annotation next= (Annotation) fIterator.next();
- if (next instanceof IJavaAnnotation || next instanceof IQuickFixableAnnotation) {
- if (fSkipIrrelevants) {
- if (!next.isMarkedDeleted()) {
- fNext= next;
- return;
- }
- } else {
- fNext= next;
- return;
- }
- } else if (fReturnAllAnnotations) {
- fNext= next;
- return;
- }
- }
- fNext= null;
- }
-
- /*
- * @see Iterator#hasNext()
- */
- public boolean hasNext() {
- return fNext != null;
- }
-
- /*
- * @see Iterator#next()
- */
- public Object next() {
- try {
- return fNext;
- } finally {
- skip();
- }
- }
-
- /*
- * @see Iterator#remove()
- */
- public void remove() {
- throw new UnsupportedOperationException();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaDocumentSetupParticipant.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaDocumentSetupParticipant.java
deleted file mode 100644
index 5a147033..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaDocumentSetupParticipant.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-/**
- * The document setup participant for JDT.
- */
-public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant {
-
- public JavaDocumentSetupParticipant() {
- }
-
- /*
- * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument)
- */
- public void setup(IDocument document) {
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java
deleted file mode 100644
index 8ca44a24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java
+++ /dev/null
@@ -1,3630 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Tom Eicher (Avaloq Evolution AG) - block selection mode
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.text.CharacterIterator;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.commands.operations.IOperationApprover;
-import org.eclipse.core.commands.operations.IUndoContext;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension4;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ISelectionValidator;
-import org.eclipse.jface.text.ISynchronizable;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextInputListener;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension2;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.reconciler.IReconciler;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.AnnotationRulerColumn;
-import org.eclipse.jface.text.source.CompositeRuler;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationModelExtension;
-import org.eclipse.jface.text.source.ICharacterPairMatcher;
-import org.eclipse.jface.text.source.IOverviewRuler;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.ISourceViewerExtension2;
-import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.jface.text.source.IVerticalRulerColumn;
-import org.eclipse.jface.text.source.LineChangeHover;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.jface.text.source.projection.ProjectionSupport;
-import org.eclipse.jface.text.source.projection.ProjectionViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IPostSelectionProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ST;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IPartService;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWindowListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.editors.text.DefaultEncodingSupport;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.editors.text.IEncodingSupport;
-import org.eclipse.ui.operations.NonLocalUndoUserApprover;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
-import org.eclipse.ui.texteditor.TextNavigationAction;
-import org.eclipse.ui.texteditor.TextOperationAction;
-import org.eclipse.ui.views.contentoutline.ContentOutline;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.core.util.IModifierConstants;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.CopyQualifiedNameAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.FoldingActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
-import org.eclipse.wst.jsdt.internal.ui.search.BreakContinueTargetFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.ExceptionOccurrencesFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.ImplementOccurrencesFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.MethodExitsFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.OccurrencesFinder;
-import org.eclipse.wst.jsdt.internal.ui.text.DocumentCharacterIterator;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaChangeHover;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaPairMatcher;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordIterator;
-import org.eclipse.wst.jsdt.internal.ui.text.PreferencesAdapter;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaExpandHover;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.SourceViewerInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ISelectionListenerWithAST;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.ShowInPackageViewAction;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProvider;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProviderExtension;
-import org.osgi.service.prefs.BackingStoreException;
-
-import com.ibm.icu.text.BreakIterator;
-
-/**
- * Java specific text editor.
- */
-public abstract class JavaEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
-
- /**
- * Internal implementation class for a change listener.
- *
- */
- protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
-
- /**
- * Installs this selection changed listener with the given selection provider. If
- * the selection provider is a post selection provider, post selection changed
- * events are the preferred choice, otherwise normal selection changed events
- * are requested.
- *
- * @param selectionProvider
- */
- public void install(ISelectionProvider selectionProvider) {
- if (selectionProvider == null)
- return;
-
- if (selectionProvider instanceof IPostSelectionProvider) {
- IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
- provider.addPostSelectionChangedListener(this);
- } else {
- selectionProvider.addSelectionChangedListener(this);
- }
- }
-
- /**
- * Removes this selection changed listener from the given selection provider.
- *
- * @param selectionProvider the selection provider
- */
- public void uninstall(ISelectionProvider selectionProvider) {
- if (selectionProvider == null)
- return;
-
- if (selectionProvider instanceof IPostSelectionProvider) {
- IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
- provider.removePostSelectionChangedListener(this);
- } else {
- selectionProvider.removeSelectionChangedListener(this);
- }
- }
- }
-
- /**
- * Updates the Java outline page selection and this editor's range indicator.
- *
- *
- */
- private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
- */
- public void selectionChanged(SelectionChangedEvent event) {
- // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
- JavaEditor.this.selectionChanged();
- }
- }
-
- /**
- * Updates the selection in the editor's widget with the selection of the outline page.
- */
- class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
- public void selectionChanged(SelectionChangedEvent event) {
- doSelectionChanged(event);
- }
- }
-
-
- /**
- * Adapts an options {@link IEclipsePreferences} to {@link org.eclipse.jface.preference.IPreferenceStore}.
- * <p>
- * This preference store is read-only i.e. write access
- * throws an {@link java.lang.UnsupportedOperationException}.
- * </p>
- *
- *
- */
- private static class EclipsePreferencesAdapter implements IPreferenceStore {
-
- /**
- * Preference change listener. Listens for events preferences
- * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
- * on this adapter with arguments from the received event.
- */
- private class PreferenceChangeListener implements IEclipsePreferences.IPreferenceChangeListener {
-
- /**
- * {@inheritDoc}
- */
- public void preferenceChange(final IEclipsePreferences.PreferenceChangeEvent event) {
- if (Display.getCurrent() == null) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- firePropertyChangeEvent(event.getKey(), event.getOldValue(), event.getNewValue());
- }
- });
- } else {
- firePropertyChangeEvent(event.getKey(), event.getOldValue(), event.getNewValue());
- }
- }
- }
-
- /** Listeners on on this adapter */
- private ListenerList fListeners= new ListenerList(ListenerList.IDENTITY);
-
- /** Listener on the node */
- private IEclipsePreferences.IPreferenceChangeListener fListener= new PreferenceChangeListener();
-
- /** wrapped node */
- private final IScopeContext fContext;
- private final String fQualifier;
-
- /**
- * Initialize with the node to wrap
- *
- * @param context the context to access
- * @param qualifier the qualifier
- */
- public EclipsePreferencesAdapter(IScopeContext context, String qualifier) {
- fContext= context;
- fQualifier= qualifier;
- }
-
- private IEclipsePreferences getNode() {
- return fContext.getNode(fQualifier);
- }
-
- /**
- * {@inheritDoc}
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- if (fListeners.size() == 0)
- getNode().addPreferenceChangeListener(fListener);
- fListeners.add(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.remove(listener);
- if (fListeners.size() == 0) {
- getNode().removePreferenceChangeListener(fListener);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(String name) {
- return getNode().get(name, null) != null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
- PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++)
- ((IPropertyChangeListener) listeners[i]).propertyChange(event);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getBoolean(String name) {
- return getNode().getBoolean(name, BOOLEAN_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getDefaultBoolean(String name) {
- return BOOLEAN_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDefaultDouble(String name) {
- return DOUBLE_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public float getDefaultFloat(String name) {
- return FLOAT_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getDefaultInt(String name) {
- return INT_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getDefaultLong(String name) {
- return LONG_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultString(String name) {
- return STRING_DEFAULT_DEFAULT;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDouble(String name) {
- return getNode().getDouble(name, DOUBLE_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public float getFloat(String name) {
- return getNode().getFloat(name, FLOAT_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInt(String name) {
- return getNode().getInt(name, INT_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public long getLong(String name) {
- return getNode().getLong(name, LONG_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getString(String name) {
- return getNode().get(name, STRING_DEFAULT_DEFAULT);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isDefault(String name) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsSaving() {
- try {
- return getNode().keys().length > 0;
- } catch (BackingStoreException e) {
- // ignore
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public void putValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, String defaultObject) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setToDefault(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
- }
-
-
- /**
- * Cancels the occurrences finder job upon document changes.
- *
- *
- */
- class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
-
- public void install() {
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer == null)
- return;
-
- StyledText text= sourceViewer.getTextWidget();
- if (text == null || text.isDisposed())
- return;
-
- sourceViewer.addTextInputListener(this);
-
- IDocument document= sourceViewer.getDocument();
- if (document != null)
- document.addDocumentListener(this);
- }
-
- public void uninstall() {
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer != null)
- sourceViewer.removeTextInputListener(this);
-
- IDocumentProvider documentProvider= getDocumentProvider();
- if (documentProvider != null) {
- IDocument document= documentProvider.getDocument(getEditorInput());
- if (document != null)
- document.removeDocumentListener(this);
- }
- }
-
-
- /*
- * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
- */
- public void documentAboutToBeChanged(DocumentEvent event) {
- if (fOccurrencesFinderJob != null)
- fOccurrencesFinderJob.doCancel();
- }
-
- /*
- * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
- */
- public void documentChanged(DocumentEvent event) {
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
- if (oldInput == null)
- return;
-
- oldInput.removeDocumentListener(this);
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
- if (newInput == null)
- return;
- newInput.addDocumentListener(this);
- }
- }
-
- /**
- * This action implements smart home.
- *
- * Instead of going to the start of a line it does the following:
- *
- * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
- * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
- * - if the caret is at the beginning of the line see first case.
- *
- *
- */
- protected class SmartLineStartAction extends LineStartAction {
-
- /**
- * Creates a new smart line start action
- *
- * @param textWidget the styled text widget
- * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
- */
- public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
- super(textWidget, doSelect);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
- */
- protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
-
- String type= IDocument.DEFAULT_CONTENT_TYPE;
- try {
- type= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, true);
- } catch (BadLocationException exception) {
- // Should not happen
- }
-
- int index= super.getLineStartPosition(document, line, length, offset);
- if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT)) {
- if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
- do {
- ++index;
- } while (index < length && Character.isWhitespace(line.charAt(index)));
- }
- } else {
- if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
- index++;
- do {
- ++index;
- } while (index < length && Character.isWhitespace(line.charAt(index)));
- }
- }
- return index;
- }
- }
-
- /**
- * Text navigation action to navigate to the next sub-word.
- *
- *
- */
- protected abstract class NextSubWordAction extends TextNavigationAction {
-
- protected JavaWordIterator fIterator= new JavaWordIterator();
-
- /**
- * Creates a new next sub-word action.
- *
- * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
- */
- protected NextSubWordAction(int code) {
- super(getSourceViewer().getTextWidget(), code);
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- // Check whether we are in a java code partition and the preference is enabled
- final IPreferenceStore store= getPreferenceStore();
- if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
- super.run();
- return;
- }
-
- final ISourceViewer viewer= getSourceViewer();
- final IDocument document= viewer.getDocument();
- fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
- int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
- if (position == -1)
- return;
-
- int next= findNextPosition(position);
- try {
- if (isBlockSelectionModeEnabled() && document.getLineOfOffset(next) != document.getLineOfOffset(position)) {
- super.run(); // may navigate into virtual white space
- } else if (next != BreakIterator.DONE) {
- setCaretPosition(next);
- getTextWidget().showSelection();
- fireSelectionChanged();
- }
- } catch (BadLocationException x) {
- // ignore
- }
- }
-
- /**
- * Finds the next position after the given position.
- *
- * @param position the current position
- * @return the next position
- */
- protected int findNextPosition(int position) {
- ISourceViewer viewer= getSourceViewer();
- int widget= -1;
- int next= position;
- while (next != BreakIterator.DONE && widget == -1) { // TODO: optimize
- next= fIterator.following(next);
- if (next != BreakIterator.DONE)
- widget= modelOffset2WidgetOffset(viewer, next);
- }
-
- IDocument document= viewer.getDocument();
- LinkedModeModel model= LinkedModeModel.getModel(document, position);
- if (model != null) {
- LinkedPosition linkedPosition= model.findPosition(new LinkedPosition(document, position, 0));
- if (linkedPosition != null) {
- int linkedPositionEnd= linkedPosition.getOffset() + linkedPosition.getLength();
- if (position != linkedPositionEnd && linkedPositionEnd < next)
- next= linkedPositionEnd;
- } else {
- LinkedPosition nextLinkedPosition= model.findPosition(new LinkedPosition(document, next, 0));
- if (nextLinkedPosition != null) {
- int nextLinkedPositionOffset= nextLinkedPosition.getOffset();
- if (position != nextLinkedPositionOffset && nextLinkedPositionOffset < next)
- next= nextLinkedPositionOffset;
- }
- }
- }
-
- return next;
- }
-
- /**
- * Sets the caret position to the sub-word boundary given with <code>position</code>.
- *
- * @param position Position where the action should move the caret
- */
- protected abstract void setCaretPosition(int position);
- }
-
- /**
- * Text navigation action to navigate to the next sub-word.
- *
- *
- */
- protected class NavigateNextSubWordAction extends NextSubWordAction {
-
- /**
- * Creates a new navigate next sub-word action.
- */
- public NavigateNextSubWordAction() {
- super(ST.WORD_NEXT);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(final int position) {
- getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
- }
- }
-
- /**
- * Text operation action to delete the next sub-word.
- *
- *
- */
- protected class DeleteNextSubWordAction extends NextSubWordAction implements IUpdate {
-
- /**
- * Creates a new delete next sub-word action.
- */
- public DeleteNextSubWordAction() {
- super(ST.DELETE_WORD_NEXT);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(final int position) {
- if (!validateEditorInputState())
- return;
-
- final ISourceViewer viewer= getSourceViewer();
- StyledText text= viewer.getTextWidget();
- Point widgetSelection= text.getSelection();
- if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
- final int caret= text.getCaretOffset();
- final int offset= modelOffset2WidgetOffset(viewer, position);
-
- if (caret == widgetSelection.x)
- text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
- else
- text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
- text.invokeAction(ST.DELETE_NEXT);
- } else {
- Point selection= viewer.getSelectedRange();
- final int caret, length;
- if (selection.y != 0) {
- caret= selection.x;
- length= selection.y;
- } else {
- caret= widgetOffset2ModelOffset(viewer, text.getCaretOffset());
- length= position - caret;
- }
-
- try {
- viewer.getDocument().replace(caret, length, ""); //$NON-NLS-1$
- } catch (BadLocationException exception) {
- // Should not happen
- }
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- setEnabled(isEditorInputModifiable());
- }
- }
-
- /**
- * Text operation action to select the next sub-word.
- *
- *
- */
- protected class SelectNextSubWordAction extends NextSubWordAction {
-
- /**
- * Creates a new select next sub-word action.
- */
- public SelectNextSubWordAction() {
- super(ST.SELECT_WORD_NEXT);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(final int position) {
- final ISourceViewer viewer= getSourceViewer();
-
- final StyledText text= viewer.getTextWidget();
- if (text != null && !text.isDisposed()) {
-
- final Point selection= text.getSelection();
- final int caret= text.getCaretOffset();
- final int offset= modelOffset2WidgetOffset(viewer, position);
-
- if (caret == selection.x)
- text.setSelectionRange(selection.y, offset - selection.y);
- else
- text.setSelectionRange(selection.x, offset - selection.x);
- }
- }
- }
-
- /**
- * Text navigation action to navigate to the previous sub-word.
- *
- *
- */
- protected abstract class PreviousSubWordAction extends TextNavigationAction {
-
- protected JavaWordIterator fIterator= new JavaWordIterator();
-
- /**
- * Creates a new previous sub-word action.
- *
- * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
- */
- protected PreviousSubWordAction(final int code) {
- super(getSourceViewer().getTextWidget(), code);
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- // Check whether we are in a java code partition and the preference is enabled
- final IPreferenceStore store= getPreferenceStore();
- if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
- super.run();
- return;
- }
-
- final ISourceViewer viewer= getSourceViewer();
- final IDocument document= viewer.getDocument();
- fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
- int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
- if (position == -1)
- return;
-
- int previous= findPreviousPosition(position);
- try {
- if (isBlockSelectionModeEnabled() && document.getLineOfOffset(previous) != document.getLineOfOffset(position)) {
- super.run(); // may navigate into virtual white space
- } else if (previous != BreakIterator.DONE) {
- setCaretPosition(previous);
- getTextWidget().showSelection();
- fireSelectionChanged();
- }
- } catch (BadLocationException x) {
- // ignore - getLineOfOffset failed
- }
-
- }
-
- /**
- * Finds the previous position before the given position.
- *
- * @param position the current position
- * @return the previous position
- */
- protected int findPreviousPosition(int position) {
- ISourceViewer viewer= getSourceViewer();
- int widget= -1;
- int previous= position;
- while (previous != BreakIterator.DONE && widget == -1) { // TODO: optimize
- previous= fIterator.preceding(previous);
- if (previous != BreakIterator.DONE)
- widget= modelOffset2WidgetOffset(viewer, previous);
- }
-
- IDocument document= viewer.getDocument();
- LinkedModeModel model= LinkedModeModel.getModel(document, position);
- if (model != null) {
- LinkedPosition linkedPosition= model.findPosition(new LinkedPosition(document, position, 0));
- if (linkedPosition != null) {
- int linkedPositionOffset= linkedPosition.getOffset();
- if (position != linkedPositionOffset && previous < linkedPositionOffset)
- previous= linkedPositionOffset;
- } else {
- LinkedPosition previousLinkedPosition= model.findPosition(new LinkedPosition(document, previous, 0));
- if (previousLinkedPosition != null) {
- int previousLinkedPositionEnd= previousLinkedPosition.getOffset() + previousLinkedPosition.getLength();
- if (position != previousLinkedPositionEnd && previous < previousLinkedPositionEnd)
- previous= previousLinkedPositionEnd;
- }
- }
- }
-
- return previous;
- }
-
- /**
- * Sets the caret position to the sub-word boundary given with <code>position</code>.
- *
- * @param position Position where the action should move the caret
- */
- protected abstract void setCaretPosition(int position);
- }
-
- /**
- * Text navigation action to navigate to the previous sub-word.
- *
- *
- */
- protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
-
- /**
- * Creates a new navigate previous sub-word action.
- */
- public NavigatePreviousSubWordAction() {
- super(ST.WORD_PREVIOUS);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(final int position) {
- getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
- }
- }
-
- /**
- * Text operation action to delete the previous sub-word.
- *
- *
- */
- protected class DeletePreviousSubWordAction extends PreviousSubWordAction implements IUpdate {
-
- /**
- * Creates a new delete previous sub-word action.
- */
- public DeletePreviousSubWordAction() {
- super(ST.DELETE_WORD_PREVIOUS);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(int position) {
- if (!validateEditorInputState())
- return;
-
- final int length;
- final ISourceViewer viewer= getSourceViewer();
- StyledText text= viewer.getTextWidget();
- Point widgetSelection= text.getSelection();
- if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
- final int caret= text.getCaretOffset();
- final int offset= modelOffset2WidgetOffset(viewer, position);
-
- if (caret == widgetSelection.x)
- text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
- else
- text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
- text.invokeAction(ST.DELETE_PREVIOUS);
- } else {
- Point selection= viewer.getSelectedRange();
- if (selection.y != 0) {
- position= selection.x;
- length= selection.y;
- } else {
- length= widgetOffset2ModelOffset(viewer, text.getCaretOffset()) - position;
- }
-
- try {
- viewer.getDocument().replace(position, length, ""); //$NON-NLS-1$
- } catch (BadLocationException exception) {
- // Should not happen
- }
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- setEnabled(isEditorInputModifiable());
- }
- }
-
- /**
- * Text operation action to select the previous sub-word.
- *
- *
- */
- protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
-
- /**
- * Creates a new select previous sub-word action.
- */
- public SelectPreviousSubWordAction() {
- super(ST.SELECT_WORD_PREVIOUS);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
- */
- protected void setCaretPosition(final int position) {
- final ISourceViewer viewer= getSourceViewer();
-
- final StyledText text= viewer.getTextWidget();
- if (text != null && !text.isDisposed()) {
-
- final Point selection= text.getSelection();
- final int caret= text.getCaretOffset();
- final int offset= modelOffset2WidgetOffset(viewer, position);
-
- if (caret == selection.x)
- text.setSelectionRange(selection.y, offset - selection.y);
- else
- text.setSelectionRange(selection.x, offset - selection.x);
- }
- }
- }
-
- /**
- * Format element action to format the enclosing java element.
- * <p>
- * The format element action works as follows:
- * <ul>
- * <li>If there is no selection and the caret is positioned on a Java element,
- * only this element is formatted. If the element has some accompanying comment,
- * then the comment is formatted as well.</li>
- * <li>If the selection spans one or more partitions of the document, then all
- * partitions covered by the selection are entirely formatted.</li>
- * <p>
- * Partitions at the end of the selection are not completed, except for comments.
- *
- *
- */
- protected class FormatElementAction extends Action implements IUpdate {
-
- /*
- *
- */
- FormatElementAction() {
- setEnabled(isEditorInputModifiable());
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
-
- final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
- if (viewer.isEditable()) {
-
- final Point selection= viewer.rememberSelection();
- try {
- viewer.setRedraw(false);
-
- final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaScriptPartitions.JAVA_PARTITIONING, selection.x, true);
- if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
-
- try {
- final IJavaScriptElement element= getElementAt(selection.x, true);
- if (element != null && element.exists()) {
-
- final int kind= element.getElementType();
- if (kind == IJavaScriptElement.TYPE || kind == IJavaScriptElement.METHOD || kind == IJavaScriptElement.INITIALIZER) {
-
- final ISourceReference reference= (ISourceReference)element;
- final ISourceRange range= reference.getSourceRange();
-
- if (range != null) {
- viewer.setSelectedRange(range.getOffset(), range.getLength());
- viewer.doOperation(ISourceViewer.FORMAT);
- }
- }
- }
- } catch (JavaScriptModelException exception) {
- // Should not happen
- }
- } else {
- viewer.setSelectedRange(selection.x, 1);
- viewer.doOperation(ISourceViewer.FORMAT);
- }
- } catch (BadLocationException exception) {
- // Can not happen
- } finally {
-
- viewer.setRedraw(true);
- viewer.restoreSelection();
- }
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- *
- */
- public void update() {
- setEnabled(isEditorInputModifiable());
- }
- }
-
- /**
- * Internal activation listener.
- *
- */
- private class ActivationListener implements IWindowListener {
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow)
- *
- */
- public void windowActivated(IWorkbenchWindow window) {
- if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) {
- fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
- updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, JavaScriptPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO, getProgressMonitor()));
- }
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow)
- *
- */
- public void windowDeactivated(IWorkbenchWindow window) {
- if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart())
- removeOccurrenceAnnotations();
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow)
- *
- */
- public void windowClosed(IWorkbenchWindow window) {
- }
-
- /*
- * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow)
- *
- */
- public void windowOpened(IWorkbenchWindow window) {
- }
- }
-
- /**
- * Runner that will toggle folding either instantly (if the editor is
- * visible) or the next time it becomes visible. If a runner is started when
- * there is already one registered, the registered one is canceled as
- * toggling folding twice is a no-op.
- * <p>
- * The access to the fFoldingRunner field is not thread-safe, it is assumed
- * that <code>runWhenNextVisible</code> is only called from the UI thread.
- * </p>
- *
- *
- */
- private final class ToggleFoldingRunner implements IPartListener2 {
- /**
- * The workbench page we registered the part listener with, or
- * <code>null</code>.
- */
- private IWorkbenchPage fPage;
-
- /**
- * Does the actual toggling of projection.
- */
- private void toggleFolding() {
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer instanceof ProjectionViewer) {
- ProjectionViewer pv= (ProjectionViewer) sourceViewer;
- if (pv.isProjectionMode() != isFoldingEnabled()) {
- if (pv.canDoOperation(ProjectionViewer.TOGGLE))
- pv.doOperation(ProjectionViewer.TOGGLE);
- }
- }
- }
-
- /**
- * Makes sure that the editor's folding state is correct the next time
- * it becomes visible. If it already is visible, it toggles the folding
- * state. If not, it either registers a part listener to toggle folding
- * when the editor becomes visible, or cancels an already registered
- * runner.
- */
- public void runWhenNextVisible() {
- // if there is one already: toggling twice is the identity
- if (fFoldingRunner != null) {
- fFoldingRunner.cancel();
- return;
- }
- IWorkbenchPartSite site= getSite();
- if (site != null) {
- IWorkbenchPage page= site.getPage();
- if (!page.isPartVisible(JavaEditor.this)) {
- // if we're not visible - defer until visible
- fPage= page;
- fFoldingRunner= this;
- page.addPartListener(this);
- return;
- }
- }
- // we're visible - run now
- toggleFolding();
- }
-
- /**
- * Remove the listener and clear the field.
- */
- private void cancel() {
- if (fPage != null) {
- fPage.removePartListener(this);
- fPage= null;
- }
- if (fFoldingRunner == this)
- fFoldingRunner= null;
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partVisible(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partVisible(IWorkbenchPartReference partRef) {
- if (JavaEditor.this.equals(partRef.getPart(false))) {
- cancel();
- toggleFolding();
- }
- }
-
- /*
- * @see org.eclipse.ui.IPartListener2#partClosed(org.eclipse.ui.IWorkbenchPartReference)
- */
- public void partClosed(IWorkbenchPartReference partRef) {
- if (JavaEditor.this.equals(partRef.getPart(false))) {
- cancel();
- }
- }
-
- public void partActivated(IWorkbenchPartReference partRef) {}
- public void partBroughtToTop(IWorkbenchPartReference partRef) {}
- public void partDeactivated(IWorkbenchPartReference partRef) {}
- public void partOpened(IWorkbenchPartReference partRef) {}
- public void partHidden(IWorkbenchPartReference partRef) {}
- public void partInputChanged(IWorkbenchPartReference partRef) {}
- }
-
- /** Preference key for matching brackets */
- protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
- /** Preference key for matching brackets color */
- protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
-
- protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']', '<', '>' };
-
- /** The outline page */
- protected JavaOutlinePage fOutlinePage;
- /** Outliner context menu Id */
- protected String fOutlinerContextMenuId;
- /**
- * The editor selection changed listener.
- *
- *
- */
- private EditorSelectionChangedListener fEditorSelectionChangedListener;
- /** The selection changed listener */
- protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
- /** The editor's bracket matcher */
- protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
- /** This editor's encoding support */
- private DefaultEncodingSupport fEncodingSupport;
- /** History for structure select action */
- private SelectionHistory fSelectionHistory;
- protected CompositeActionGroup fActionGroups;
-
- /**
- * The action group for folding.
- *
- *
- */
- private FoldingActionGroup fFoldingGroup;
-
- private CompositeActionGroup fContextMenuGroup;
- /**
- * Holds the current occurrence annotations.
- *
- */
- private Annotation[] fOccurrenceAnnotations= null;
- /**
- * Tells whether all occurrences of the element at the
- * current caret location are automatically marked in
- * this editor.
- *
- */
- private boolean fMarkOccurrenceAnnotations;
- /**
- * Tells whether the occurrence annotations are sticky
- * i.e. whether they stay even if there's no valid Java
- * element at the current caret position.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fStickyOccurrenceAnnotations;
- /**
- * Tells whether to mark type occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkTypeOccurrences;
- /**
- * Tells whether to mark method occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkMethodOccurrences;
- /**
- * Tells whether to mark constant occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkConstantOccurrences;
- /**
- * Tells whether to mark field occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkFieldOccurrences;
- /**
- * Tells whether to mark local variable occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkLocalVariableypeOccurrences;
- /**
- * Tells whether to mark exception occurrences in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkExceptions;
- /**
- * Tells whether to mark method exits in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkMethodExitPoints;
-
- /**
- * Tells whether to mark targets of <code>break</code> and <code>continue</code> statements in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkBreakContinueTargets;
-
- /**
- * Tells whether to mark implementors in this editor.
- * Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
- *
- */
- private boolean fMarkImplementors;
- /**
- * The selection used when forcing occurrence marking
- * through code.
- *
- */
- private ISelection fForcedMarkOccurrencesSelection;
- /**
- * The document modification stamp at the time when the last
- * occurrence marking took place.
- *
- */
- private long fMarkOccurrenceModificationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
- /**
- * The region of the word under the caret used to when
- * computing the current occurrence markings.
- *
- */
- private IRegion fMarkOccurrenceTargetRegion;
-
- /**
- * The internal shell activation listener for updating occurrences.
- *
- */
- private ActivationListener fActivationListener= new ActivationListener();
- private ISelectionListenerWithAST fPostSelectionListenerWithAST;
- private OccurrencesFinderJob fOccurrencesFinderJob;
- /** The occurrences finder job canceler */
- private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
- /**
- * This editor's projection support
- *
- */
- private ProjectionSupport fProjectionSupport;
- /**
- * This editor's projection model updater
- *
- */
- private IJavaFoldingStructureProvider fProjectionModelUpdater;
- /**
- * The override and implements indicator manager for this editor.
- *
- */
- protected OverrideIndicatorManager fOverrideIndicatorManager;
- /**
- * Semantic highlighting manager
- * , protected as of 3.3
- */
- protected SemanticHighlightingManager fSemanticManager;
- /**
- * The folding runner.
- *
- */
- private ToggleFoldingRunner fFoldingRunner;
-
- /**
- * Tells whether the selection changed event is caused
- * by a call to {@link #gotoAnnotation(boolean)}.
- *
- *
- */
- private boolean fSelectionChangedViaGotoAnnotation;
- /**
- * The cached selected range.
- *
- * @see ITextViewer#getSelectedRange()
- *
- */
- private Point fCachedSelectedRange;
-
-
- /**
- * Returns the most narrow java element including the given offset.
- *
- * @param offset the offset inside of the requested element
- * @return the most narrow java element
- */
- abstract protected IJavaScriptElement getElementAt(int offset);
-
- /**
- * Returns the java element of this editor's input corresponding to the given IJavaScriptElement.
- *
- * @param element the java element
- * @return the corresponding Java element
- */
- abstract protected IJavaScriptElement getCorrespondingElement(IJavaScriptElement element);
-
- /**
- * Default constructor.
- */
- public JavaEditor() {
- super();
- }
-
- /**
- * Sets the input of the editor's outline page.
- *
- * @param page the Java outline page
- * @param input the editor input
- */
- protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
- if (page == null)
- return;
-
- IJavaScriptElement je= getInputJavaElement();
- if (je != null && je.exists())
- page.setInput(je);
- else
- page.setInput(null);
-
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
- */
- protected void initializeKeyBindingScopes() {
- setKeyBindingScopes(new String[] { "org.eclipse.wst.jsdt.ui.javascriptViewScope" }); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
- */
- protected void initializeEditor() {
- IPreferenceStore store= createCombinedPreferenceStore(null);
- setPreferenceStore(store);
- setSourceViewerConfiguration(createJavaSourceViewerConfiguration());
- fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
- fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
- fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
- fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
- fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
- fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
- fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
- fMarkExceptions= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
- fMarkImplementors= store.getBoolean(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS);
- fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
- fMarkBreakContinueTargets= store.getBoolean(PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS);
- }
-
- /**
- * Returns a new Java source viewer configuration.
- *
- * @return a new <code>JavaScriptSourceViewerConfiguration</code>
- *
- */
- protected JavaScriptSourceViewerConfiguration createJavaSourceViewerConfiguration() {
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- return new JavaScriptSourceViewerConfiguration(textTools.getColorManager(), getPreferenceStore(), this, IJavaScriptPartitions.JAVA_PARTITIONING);
- }
-
- /*
- * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
- */
- protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
-
- IPreferenceStore store= getPreferenceStore();
- ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
-
- JavaUIHelp.setHelp(this, viewer.getTextWidget(), IJavaHelpContextIds.JAVA_EDITOR);
-
- JavaSourceViewer javaSourceViewer= null;
- if (viewer instanceof JavaSourceViewer)
- javaSourceViewer= (JavaSourceViewer)viewer;
-
- /*
- * This is a performance optimization to reduce the computation of
- * the text presentation triggered by {@link #setVisibleDocument(IDocument)}
- */
- if (javaSourceViewer != null && isFoldingEnabled() && (store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
- javaSourceViewer.prepareDelayedProjection();
-
- ProjectionViewer projectionViewer= (ProjectionViewer)viewer;
- fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
- fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
- fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
- fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell shell) {
- return new SourceViewerInformationControl(shell, SWT.TOOL | SWT.NO_TRIM | getOrientation(), SWT.NONE, EditorsUI.getTooltipAffordanceString());
- }
- });
- fProjectionSupport.setInformationPresenterControlCreator(new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell shell) {
- int shellStyle= SWT.RESIZE | SWT.TOOL | getOrientation();
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- return new SourceViewerInformationControl(shell, shellStyle, style);
- }
- });
- fProjectionSupport.install();
-
- fProjectionModelUpdater= JavaScriptPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
- if (fProjectionModelUpdater != null)
- fProjectionModelUpdater.install(this, projectionViewer);
-
- // ensure source viewer decoration support has been created and configured
- getSourceViewerDecorationSupport(viewer);
-
- return viewer;
- }
-
- public final ISourceViewer getViewer() {
- return getSourceViewer();
- }
-
- /*
- * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
- */
- protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
- return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
- }
-
- /*
- * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
- */
- protected boolean affectsTextPresentation(PropertyChangeEvent event) {
- return ((JavaScriptSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
- }
-
- /**
- * Creates and returns the preference store for this Java editor with the given input.
- *
- * @param input The editor input for which to create the preference store
- * @return the preference store for this editor
- *
- *
- */
- private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
- List stores= new ArrayList(3);
-
- IJavaScriptProject project= EditorUtility.getJavaProject(input);
- if (project != null) {
- stores.add(new EclipsePreferencesAdapter(new ProjectScope(project.getProject()), JavaScriptCore.PLUGIN_ID));
- }
-
- stores.add(JavaScriptPlugin.getDefault().getPreferenceStore());
- stores.add(new PreferencesAdapter(JavaScriptCore.getPlugin().getPluginPreferences()));
- stores.add(EditorsUI.getPreferenceStore());
-
- return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
- }
-
- /**
- * Sets the outliner's context menu ID.
- *
- * @param menuId the menu ID
- */
- protected void setOutlinerContextMenuId(String menuId) {
- fOutlinerContextMenuId= menuId;
- }
-
- /**
- * Returns the standard action group of this editor.
- *
- * @return returns this editor's standard action group
- */
- protected ActionGroup getActionGroup() {
- return fActionGroups;
- }
-
- /*
- * @see AbstractTextEditor#editorContextMenuAboutToShow
- */
- public void editorContextMenuAboutToShow(IMenuManager menu) {
-
- super.editorContextMenuAboutToShow(menu);
- menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
-
- ActionContext context= new ActionContext(getSelectionProvider().getSelection());
- fContextMenuGroup.setContext(context);
- fContextMenuGroup.fillContextMenu(menu);
- fContextMenuGroup.setContext(null);
-
- // Quick views
- IAction action= getAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
- action= getAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
-
- }
-
- /**
- * Creates the outline page used with this editor.
- *
- * @return the created Java outline page
- */
- protected JavaOutlinePage createOutlinePage() {
- JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
- fOutlineSelectionChangedListener.install(page);
- setOutlinePageInput(page, getEditorInput());
- return page;
- }
-
- /**
- * Informs the editor that its outliner has been closed.
- */
- public void outlinePageClosed() {
- if (fOutlinePage != null) {
- fOutlineSelectionChangedListener.uninstall(fOutlinePage);
- fOutlinePage= null;
- resetHighlightRange();
- }
- }
-
- /**
- * Synchronizes the outliner selection with the given element
- * position in the editor.
- *
- * @param element the java element to select
- */
- protected void synchronizeOutlinePage(ISourceReference element) {
- synchronizeOutlinePage(element, true);
- }
-
- /**
- * Synchronizes the outliner selection with the given element
- * position in the editor.
- *
- * @param element the java element to select
- * @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
- */
- protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
- if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
- fOutlineSelectionChangedListener.uninstall(fOutlinePage);
- fOutlinePage.select(element);
- fOutlineSelectionChangedListener.install(fOutlinePage);
- }
- }
-
- /**
- * Synchronizes the outliner selection with the actual cursor
- * position in the editor.
- */
- public void synchronizeOutlinePageSelection() {
- synchronizeOutlinePage(computeHighlightRangeSourceReference());
- }
-
- /*
- * @see AbstractTextEditor#getAdapter(Class)
- */
- public Object getAdapter(Class required) {
-
- if (IContentOutlinePage.class.equals(required)) {
- if (fOutlinePage == null)
- fOutlinePage= createOutlinePage();
- return fOutlinePage;
- }
-
- if (IEncodingSupport.class.equals(required))
- return fEncodingSupport;
-
- if (required == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
- }
-
- };
- }
-
- if (required == IShowInSource.class) {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- return new ShowInContext(getEditorInput(), null) {
- /*
- * @see org.eclipse.ui.part.ShowInContext#getSelection()
- *
- */
- public ISelection getSelection() {
- IJavaScriptElement je= null;
- try {
- je= SelectionConverter.getElementAtOffset(JavaEditor.this);
- if (je==null)
- return null;
- return new StructuredSelection(je);
- } catch (JavaScriptModelException ex) {
- return null;
- }
- }
- };
- }
- };
- }
-
- if (required == IJavaFoldingStructureProvider.class)
- return fProjectionModelUpdater;
-
- if (fProjectionSupport != null) {
- Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
- if (adapter != null)
- return adapter;
- }
-
- if (required == IContextProvider.class)
- return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.JAVA_EDITOR);
-
- return super.getAdapter(required);
- }
-
- /**
- * React to changed selection.
- *
- *
- */
- protected void selectionChanged() {
- if (getSelectionProvider() == null)
- return;
- ISourceReference element= computeHighlightRangeSourceReference();
- if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
- synchronizeOutlinePage(element);
- setSelection(element, false);
- if (!fSelectionChangedViaGotoAnnotation)
- updateStatusLine();
- fSelectionChangedViaGotoAnnotation= false;
- }
-
- protected void setSelection(ISourceReference reference, boolean moveCursor) {
- if (getSelectionProvider() == null)
- return;
-
- ISelection selection= getSelectionProvider().getSelection();
- if (selection instanceof ITextSelection) {
- ITextSelection textSelection= (ITextSelection) selection;
- // PR 39995: [navigation] Forward history cleared after going back in navigation history:
- // mark only in navigation history if the cursor is being moved (which it isn't if
- // this is called from a PostSelectionEvent that should only update the magnet)
- if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
- markInNavigationHistory();
- }
-
- if (reference != null) {
-
- StyledText textWidget= null;
-
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer != null)
- textWidget= sourceViewer.getTextWidget();
-
- if (textWidget == null)
- return;
-
- try {
- ISourceRange range= null;
- if (reference instanceof ILocalVariable) {
- IJavaScriptElement je= ((ILocalVariable)reference).getParent();
- if (je instanceof ISourceReference)
- range= ((ISourceReference)je).getSourceRange();
- } else
- range= reference.getSourceRange();
-
- if (range == null)
- return;
-
- int offset= range.getOffset();
- int length= range.getLength();
-
- if (offset < 0 || length < 0)
- return;
-
- setHighlightRange(offset, length, moveCursor);
-
- if (!moveCursor)
- return;
-
- offset= -1;
- length= -1;
-
- if (reference instanceof IMember) {
- range= ((IMember) reference).getNameRange();
- if (range != null) {
- offset= range.getOffset();
- length= range.getLength();
- }
- } else if (reference instanceof ILocalVariable) {
- range= ((ILocalVariable)reference).getNameRange();
- if (range != null) {
- offset= range.getOffset();
- length= range.getLength();
- }
- } else if (reference instanceof IImportDeclaration) {
- String content= reference.getSource();
- if (content != null) {
- int start= content.indexOf("import") + 6; //$NON-NLS-1$
- while (start < content.length() && content.charAt(start) == ' ')
- start++;
-
- int end= content.indexOf(';');
- do {
- end--;
- } while (end >= 0 && content.charAt(end) == ' ');
-
- offset= range.getOffset() + start;
- length= end - start + 1;
- } else {
- // fallback
- offset= range.getOffset();
- length= range.getLength();
- }
- }
-
- if (offset > -1 && length > 0) {
-
- try {
- textWidget.setRedraw(false);
- sourceViewer.revealRange(offset, length);
- sourceViewer.setSelectedRange(offset, length);
- } finally {
- textWidget.setRedraw(true);
- }
-
- markInNavigationHistory();
- }
-
- } catch (JavaScriptModelException x) {
- } catch (IllegalArgumentException x) {
- }
-
- } else if (moveCursor) {
- resetHighlightRange();
- markInNavigationHistory();
- }
- }
-
- public void setSelection(IJavaScriptElement element) {
-
- if (element == null || element instanceof IJavaScriptUnit || element instanceof IClassFile) {
- /*
- * If the element is an IJavaScriptUnit this unit is either the input
- * of this editor or not being displayed. In both cases, nothing should
- * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
- */
- return;
- }
-
- IJavaScriptElement corresponding= getCorrespondingElement(element);
- if (corresponding instanceof ISourceReference) {
- ISourceReference reference= (ISourceReference) corresponding;
- // set highlight range
- setSelection(reference, true);
- // set outliner selection
- if (fOutlinePage != null) {
- fOutlineSelectionChangedListener.uninstall(fOutlinePage);
- fOutlinePage.select(reference);
- fOutlineSelectionChangedListener.install(fOutlinePage);
- }
- }
- }
-
- protected void doSelectionChanged(SelectionChangedEvent event) {
-
- ISourceReference reference= null;
-
- ISelection selection= event.getSelection();
- Iterator iter= ((IStructuredSelection) selection).iterator();
- while (iter.hasNext()) {
- Object o= iter.next();
- if (o instanceof ISourceReference) {
- reference= (ISourceReference) o;
- break;
- }
- }
- if (!isActivePart() && JavaScriptPlugin.getActivePage() != null)
- JavaScriptPlugin.getActivePage().bringToTop(this);
-
- setSelection(reference, !isActivePart());
-
- ISelectionProvider selectionProvider= getSelectionProvider();
- if (selectionProvider == null )
- return;
-
- ISelection textSelection= selectionProvider.getSelection();
- if (!(textSelection instanceof ITextSelection))
- return;
-
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
- if (ast != null) {
- fForcedMarkOccurrencesSelection= textSelection;
- updateOccurrenceAnnotations((ITextSelection)textSelection, ast);
- }
-
- }
-
- /*
- * @see AbstractTextEditor#adjustHighlightRange(int, int)
- */
- protected void adjustHighlightRange(int offset, int length) {
-
- try {
-
- IJavaScriptElement element= getElementAt(offset, false);
- while (element instanceof ISourceReference) {
- ISourceRange range= ((ISourceReference) element).getSourceRange();
- if (range != null && offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
-
- ISourceViewer viewer= getSourceViewer();
- if (viewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
- extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
- }
-
- setHighlightRange(range.getOffset(), range.getLength(), true);
- if (fOutlinePage != null) {
- fOutlineSelectionChangedListener.uninstall(fOutlinePage);
- fOutlinePage.select((ISourceReference) element);
- fOutlineSelectionChangedListener.install(fOutlinePage);
- }
-
- return;
- }
- element= element.getParent();
- }
-
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x.getStatus());
- }
-
- ISourceViewer viewer= getSourceViewer();
- if (viewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
- extension.exposeModelRange(new Region(offset, length));
- } else {
- resetHighlightRange();
- }
-
- }
-
- protected boolean isActivePart() {
- IWorkbenchPart part= getActivePart();
- return part != null && part.equals(this);
- }
-
- private boolean isJavaOutlinePageActive() {
- IWorkbenchPart part= getActivePart();
- return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
- }
-
- private IWorkbenchPart getActivePart() {
- IWorkbenchWindow window= getSite().getWorkbenchWindow();
- IPartService service= window.getPartService();
- IWorkbenchPart part= service.getActivePart();
- return part;
- }
-
- /*
- * @see StatusTextEditor#getStatusHeader(IStatus)
- */
- protected String getStatusHeader(IStatus status) {
- if (fEncodingSupport != null) {
- String message= fEncodingSupport.getStatusHeader(status);
- if (message != null)
- return message;
- }
- return super.getStatusHeader(status);
- }
-
- /*
- * @see StatusTextEditor#getStatusBanner(IStatus)
- */
- protected String getStatusBanner(IStatus status) {
- if (fEncodingSupport != null) {
- String message= fEncodingSupport.getStatusBanner(status);
- if (message != null)
- return message;
- }
- return super.getStatusBanner(status);
- }
-
- /*
- * @see StatusTextEditor#getStatusMessage(IStatus)
- */
- protected String getStatusMessage(IStatus status) {
- if (fEncodingSupport != null) {
- String message= fEncodingSupport.getStatusMessage(status);
- if (message != null)
- return message;
- }
- return super.getStatusMessage(status);
- }
-
- /*
- * @see AbstractTextEditor#doSetInput
- */
- protected void doSetInput(IEditorInput input) throws CoreException {
- ISourceViewer sourceViewer= getSourceViewer();
- if (!(sourceViewer instanceof ISourceViewerExtension2)) {
- setPreferenceStore(createCombinedPreferenceStore(input));
- internalDoSetInput(input);
- return;
- }
-
- // uninstall & unregister preference store listener
- getSourceViewerDecorationSupport(sourceViewer).uninstall();
- ((ISourceViewerExtension2)sourceViewer).unconfigure();
-
- setPreferenceStore(createCombinedPreferenceStore(input));
-
- // install & register preference store listener
- sourceViewer.configure(getSourceViewerConfiguration());
- getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
-
- internalDoSetInput(input);
- }
-
- private void internalDoSetInput(IEditorInput input) throws CoreException {
- ISourceViewer sourceViewer= getSourceViewer();
- JavaSourceViewer javaSourceViewer= null;
- if (sourceViewer instanceof JavaSourceViewer)
- javaSourceViewer= (JavaSourceViewer)sourceViewer;
-
- IPreferenceStore store= getPreferenceStore();
- if (javaSourceViewer != null && isFoldingEnabled() &&(store == null || !store.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS)))
- javaSourceViewer.prepareDelayedProjection();
-
- super.doSetInput(input);
-
- if (javaSourceViewer != null && javaSourceViewer.getReconciler() == null) {
- IReconciler reconciler= getSourceViewerConfiguration().getReconciler(javaSourceViewer);
- if (reconciler != null) {
- reconciler.install(javaSourceViewer);
- javaSourceViewer.setReconciler(reconciler);
- }
- }
-
- if (fEncodingSupport != null)
- fEncodingSupport.reset();
-
- setOutlinePageInput(fOutlinePage, input);
-
- if (isShowingOverrideIndicators())
- installOverrideIndicator(false);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
- *
- */
- protected void setPreferenceStore(IPreferenceStore store) {
- super.setPreferenceStore(store);
- if (getSourceViewerConfiguration() instanceof JavaScriptSourceViewerConfiguration) {
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- setSourceViewerConfiguration(new JavaScriptSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaScriptPartitions.JAVA_PARTITIONING));
- }
- if (getSourceViewer() instanceof JavaSourceViewer)
- ((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
- }
-
- /*
- * @see IWorkbenchPart#dispose()
- */
- public void dispose() {
-
- if (fProjectionModelUpdater != null) {
- fProjectionModelUpdater.uninstall();
- fProjectionModelUpdater= null;
- }
-
- if (fProjectionSupport != null) {
- fProjectionSupport.dispose();
- fProjectionSupport= null;
- }
-
- // cancel possible running computation
- fMarkOccurrenceAnnotations= false;
- uninstallOccurrencesFinder();
-
- uninstallOverrideIndicator();
-
- uninstallSemanticHighlighting();
-
- if (fActivationListener != null) {
- PlatformUI.getWorkbench().removeWindowListener(fActivationListener);
- fActivationListener= null;
- }
-
- if (fEncodingSupport != null) {
- fEncodingSupport.dispose();
- fEncodingSupport= null;
- }
-
- if (fBracketMatcher != null) {
- fBracketMatcher.dispose();
- fBracketMatcher= null;
- }
-
- if (fSelectionHistory != null) {
- fSelectionHistory.dispose();
- fSelectionHistory= null;
- }
-
- if (fEditorSelectionChangedListener != null) {
- fEditorSelectionChangedListener.uninstall(getSelectionProvider());
- fEditorSelectionChangedListener= null;
- }
-
- if (fActionGroups != null) {
- fActionGroups.dispose();
- fActionGroups= null;
- }
-
- super.dispose();
- }
-
- protected void createActions() {
- installEncodingSupport();
-
- super.createActions();
-
- ActionGroup oeg, ovg, jsg;
- fActionGroups= new CompositeActionGroup(new ActionGroup[] {
- oeg= new OpenEditorActionGroup(this),
- ovg= new OpenViewActionGroup(this),
- jsg= new JavaSearchActionGroup(this)
- });
- fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, jsg});
-
- fFoldingGroup= new FoldingActionGroup(this, getViewer());
-
- Action action= new GotoMatchingBracketAction(this);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
- setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
- setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
- setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
-
- action= new TextOperationAction(JavaEditorMessages.getBundleForConstructedKeys(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
- setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
-
- fSelectionHistory= new SelectionHistory(this);
-
- action= new StructureSelectEnclosingAction(this, fSelectionHistory);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
- setAction(StructureSelectionAction.ENCLOSING, action);
-
- action= new StructureSelectNextAction(this, fSelectionHistory);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
- setAction(StructureSelectionAction.NEXT, action);
-
- action= new StructureSelectPreviousAction(this, fSelectionHistory);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
- setAction(StructureSelectionAction.PREVIOUS, action);
-
- StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
- historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
- setAction(StructureSelectionAction.HISTORY, historyAction);
- fSelectionHistory.setHistoryAction(historyAction);
-
- action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
- setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
-
- action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
- setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
-
- action= new FormatElementAction();
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
- setAction("QuickFormat", action); //$NON-NLS-1$
- markAsStateDependentAction("QuickFormat", true); //$NON-NLS-1$
-
- action= new RemoveOccurrenceAnnotations(this);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
- setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
-
- // add annotation actions for roll-over expand hover
- action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
- setAction("AnnotationAction", action); //$NON-NLS-1$
-
- action= new ShowInPackageViewAction(this);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
- setAction("ShowInPackageView", action); //$NON-NLS-1$
-
-
- // replace cut/copy paste actions with a version that implement 'add imports on paste'
-
- action= new ClipboardOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
- setAction(ITextEditorActionConstants.CUT, action);
-
- action= new ClipboardOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.Copy.", this, ITextOperationTarget.COPY); //$NON-NLS-1$
- setAction(ITextEditorActionConstants.COPY, action);
-
- action= new ClipboardOperationAction(JavaEditorMessages.getBundleForConstructedKeys(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
- setAction(ITextEditorActionConstants.PASTE, action);
-
- action= new CopyQualifiedNameAction(this);
- setAction(IJavaEditorActionConstants.COPY_QUALIFIED_NAME, action);
- }
-
- /**
- * Installs the encoding support on the given text editor.
- * <p>
- * Subclasses may override to install their own encoding
- * support or to disable the default encoding support.
- * </p>
- *
- */
- protected void installEncodingSupport() {
- fEncodingSupport= new DefaultEncodingSupport();
- fEncodingSupport.initialize(this);
- }
-
-
- public void updatedTitleImage(Image image) {
- setTitleImage(image);
- }
-
- /*
- * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
- */
- protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
-
- String property= event.getProperty();
-
- if (AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
- /*
- * Ignore tab setting since we rely on the formatter preferences.
- * We do this outside the try-finally block to avoid that EDITOR_TAB_WIDTH
- * is handled by the sub-class (AbstractDecoratedTextEditor).
- */
- return;
- }
-
- try {
-
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer == null)
- return;
-
- if (isJavaEditorHoverProperty(property))
- updateHoverBehavior();
-
- boolean newBooleanValue= false;
- Object newValue= event.getNewValue();
- if (newValue != null)
- newBooleanValue= Boolean.valueOf(newValue.toString()).booleanValue();
-
- if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
- if (newBooleanValue)
- selectionChanged();
- return;
- }
-
- if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
- if (newBooleanValue != fMarkOccurrenceAnnotations) {
- fMarkOccurrenceAnnotations= newBooleanValue;
- if (!fMarkOccurrenceAnnotations)
- uninstallOccurrencesFinder();
- else
- installOccurrencesFinder(true);
- }
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES.equals(property)) {
- fMarkTypeOccurrences= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES.equals(property)) {
- fMarkMethodOccurrences= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES.equals(property)) {
- fMarkConstantOccurrences= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES.equals(property)) {
- fMarkFieldOccurrences= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES.equals(property)) {
- fMarkLocalVariableypeOccurrences= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES.equals(property)) {
- fMarkExceptions= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS.equals(property)) {
- fMarkMethodExitPoints= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS.equals(property)) {
- fMarkBreakContinueTargets= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_MARK_IMPLEMENTORS.equals(property)) {
- fMarkImplementors= newBooleanValue;
- return;
- }
- if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
- fStickyOccurrenceAnnotations= newBooleanValue;
- return;
- }
- if (SemanticHighlightings.affectsEnablement(getPreferenceStore(), event)) {
- if (isSemanticHighlightingEnabled())
- installSemanticHighlighting();
- else
- uninstallSemanticHighlighting();
- return;
- }
-
- if (JavaScriptCore.COMPILER_SOURCE.equals(property)) {
- if (event.getNewValue() instanceof String)
- fBracketMatcher.setSourceVersion((String) event.getNewValue());
- // fall through as others are interested in source change as well.
- }
-
- ((JavaScriptSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
-
- if (affectsOverrideIndicatorAnnotations(event)) {
- if (isShowingOverrideIndicators()) {
- if (fOverrideIndicatorManager == null)
- installOverrideIndicator(true);
- } else {
- if (fOverrideIndicatorManager != null)
- uninstallOverrideIndicator();
- }
- return;
- }
-
- if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
- if (sourceViewer instanceof ProjectionViewer) {
- ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
- if (fProjectionModelUpdater != null)
- fProjectionModelUpdater.uninstall();
- // either freshly enabled or provider changed
- fProjectionModelUpdater= JavaScriptPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
- if (fProjectionModelUpdater != null) {
- fProjectionModelUpdater.install(this, projectionViewer);
- }
- }
- return;
- }
-
- if (DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE.equals(property)
- || DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE.equals(property)
- || DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR.equals(property)) {
- StyledText textWidget= sourceViewer.getTextWidget();
- int tabWidth= getSourceViewerConfiguration().getTabWidth(sourceViewer);
- if (textWidget.getTabs() != tabWidth)
- textWidget.setTabs(tabWidth);
- return;
- }
-
- if (PreferenceConstants.EDITOR_FOLDING_ENABLED.equals(property)) {
- if (sourceViewer instanceof ProjectionViewer) {
- new ToggleFoldingRunner().runWhenNextVisible();
- }
- return;
- }
-
- } finally {
- super.handlePreferenceStoreChanged(event);
- }
-
- if (AbstractDecoratedTextEditorPreferenceConstants.SHOW_RANGE_INDICATOR.equals(property)) {
- // superclass already installed the range indicator
- Object newValue= event.getNewValue();
- ISourceViewer viewer= getSourceViewer();
- if (newValue != null && viewer != null) {
- if (Boolean.valueOf(newValue.toString()).booleanValue()) {
- // adjust the highlightrange in order to get the magnet right after changing the selection
- Point selection= viewer.getSelectedRange();
- adjustHighlightRange(selection.x, selection.y);
- }
- }
-
- }
- }
-
- /**
- * Initializes the given viewer's colors.
- *
- * @param viewer the viewer to be initialized
- *
- */
- protected void initializeViewerColors(ISourceViewer viewer) {
- // is handled by JavaSourceViewer
- }
-
- private boolean isJavaEditorHoverProperty(String property) {
- return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
- */
- protected void updatePropertyDependentActions() {
- super.updatePropertyDependentActions();
- if (fEncodingSupport != null)
- fEncodingSupport.reset();
- }
-
- /*
- * Update the hovering behavior depending on the preferences.
- */
- private void updateHoverBehavior() {
- SourceViewerConfiguration configuration= getSourceViewerConfiguration();
- String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
-
- for (int i= 0; i < types.length; i++) {
-
- String t= types[i];
-
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer instanceof ITextViewerExtension2) {
- // Remove existing hovers
- ((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
-
- int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
-
- if (stateMasks != null) {
- for (int j= 0; j < stateMasks.length; j++) {
- int stateMask= stateMasks[j];
- ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
- ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
- }
- } else {
- ITextHover textHover= configuration.getTextHover(sourceViewer, t);
- ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
- }
- } else
- sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
- */
- public Object getViewPartInput() {
- return getEditorInput().getAdapter(IJavaScriptElement.class);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
- */
- protected void doSetSelection(ISelection selection) {
- super.doSetSelection(selection);
- synchronizeOutlinePageSelection();
- }
-
- boolean isFoldingEnabled() {
- return JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
- }
-
- /*
- * @see org.eclipse.ui.part.WorkbenchPart#getOrientation()
- *
- */
- public int getOrientation() {
- return SWT.LEFT_TO_RIGHT; //Java editors are always left to right by default
- }
-
- /*
- * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
-
- fEditorSelectionChangedListener= new EditorSelectionChangedListener();
- fEditorSelectionChangedListener.install(getSelectionProvider());
-
- if (isSemanticHighlightingEnabled())
- installSemanticHighlighting();
-
- PlatformUI.getWorkbench().addWindowListener(fActivationListener);
- }
-
- protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
-
- fBracketMatcher.setSourceVersion(getPreferenceStore().getString(JavaScriptCore.COMPILER_SOURCE));
- support.setCharacterPairMatcher(fBracketMatcher);
- support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
-
- super.configureSourceViewerDecorationSupport(support);
- }
-
- /**
- * Returns the lock object for the given annotation model.
- *
- * @param annotationModel the annotation model
- * @return the annotation model's lock object
- *
- */
- private Object getLockObject(IAnnotationModel annotationModel) {
- if (annotationModel instanceof ISynchronizable) {
- Object lock= ((ISynchronizable)annotationModel).getLockObject();
- if (lock != null)
- return lock;
- }
- return annotationModel;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#updateMarkerViews(org.eclipse.jface.text.source.Annotation)
- *
- */
- protected void updateMarkerViews(Annotation annotation) {
- if (annotation instanceof IJavaAnnotation) {
- Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
- if (e != null) {
- while (e.hasNext()) {
- Object o= e.next();
- if (o instanceof MarkerAnnotation) {
- super.updateMarkerViews((MarkerAnnotation)o);
- return;
- }
- }
- }
- return;
- }
- super.updateMarkerViews(annotation);
- }
-
- /**
- * Finds and marks occurrence annotations.
- *
- *
- */
- class OccurrencesFinderJob extends Job {
-
- private IDocument fDocument;
- private ISelection fSelection;
- private ISelectionValidator fPostSelectionValidator;
- private boolean fCanceled= false;
- private IProgressMonitor fProgressMonitor;
- private Position[] fPositions;
-
- public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
- super(JavaEditorMessages.JavaEditor_markOccurrences_job_name);
- fDocument= document;
- fSelection= selection;
- fPositions= positions;
-
- if (getSelectionProvider() instanceof ISelectionValidator)
- fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
- }
-
- // cannot use cancel() because it is declared final
- void doCancel() {
- fCanceled= true;
- cancel();
- }
-
- private boolean isCanceled() {
- return fCanceled || fProgressMonitor.isCanceled()
- || fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
- || LinkedModeModel.hasInstalledModel(fDocument);
- }
-
- /*
- * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public IStatus run(IProgressMonitor progressMonitor) {
-
- fProgressMonitor= progressMonitor;
-
- if (isCanceled())
- return Status.CANCEL_STATUS;
-
- ITextViewer textViewer= getViewer();
- if (textViewer == null)
- return Status.CANCEL_STATUS;
-
- IDocument document= textViewer.getDocument();
- if (document == null)
- return Status.CANCEL_STATUS;
-
- IDocumentProvider documentProvider= getDocumentProvider();
- if (documentProvider == null)
- return Status.CANCEL_STATUS;
-
- IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
- if (annotationModel == null)
- return Status.CANCEL_STATUS;
-
- // Add occurrence annotations
- int length= fPositions.length;
- Map annotationMap= new HashMap(length);
- for (int i= 0; i < length; i++) {
-
- if (isCanceled())
- return Status.CANCEL_STATUS;
-
- String message;
- Position position= fPositions[i];
-
- // Create & add annotation
- try {
- message= document.get(position.offset, position.length);
- } catch (BadLocationException ex) {
- // Skip this match
- continue;
- }
- annotationMap.put(
- new Annotation("org.eclipse.wst.jsdt.ui.occurrences", false, message), //$NON-NLS-1$
- position);
- }
-
- if (isCanceled())
- return Status.CANCEL_STATUS;
-
- synchronized (getLockObject(annotationModel)) {
- if (annotationModel instanceof IAnnotationModelExtension) {
- ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
- } else {
- removeOccurrenceAnnotations();
- Iterator iter= annotationMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry mapEntry= (Map.Entry)iter.next();
- annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
- }
- }
- fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
- }
-
- return Status.OK_STATUS;
- }
- }
-
- /**
- * Updates the occurrences annotations based
- * on the current selection.
- *
- * @param selection the text selection
- * @param astRoot the compilation unit AST
- *
- */
- protected void updateOccurrenceAnnotations(ITextSelection selection, JavaScriptUnit astRoot) {
-
- if (fOccurrencesFinderJob != null)
- fOccurrencesFinderJob.cancel();
-
- if (!fMarkOccurrenceAnnotations)
- return;
-
- if (astRoot == null || selection == null)
- return;
-
- IDocument document= getSourceViewer().getDocument();
- if (document == null)
- return;
-
- if (document instanceof IDocumentExtension4) {
- int offset= selection.getOffset();
- long currentModificationStamp= ((IDocumentExtension4)document).getModificationStamp();
- IRegion markOccurrenceTargetRegion= fMarkOccurrenceTargetRegion;
- if (markOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp) {
- if (markOccurrenceTargetRegion.getOffset() <= offset && offset <= markOccurrenceTargetRegion.getOffset() + markOccurrenceTargetRegion.getLength())
- return;
- }
- fMarkOccurrenceTargetRegion= JavaWordFinder.findWord(document, offset);
- fMarkOccurrenceModificationStamp= currentModificationStamp;
- }
-
- List matches= null;
-
- ASTNode selectedNode= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
-
- if (fMarkExceptions || fMarkTypeOccurrences) {
- ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
- String message= exceptionFinder.initialize(astRoot, selectedNode);
- if (message == null) {
- matches= exceptionFinder.perform();
- if (!fMarkExceptions && !matches.isEmpty())
- matches.clear();
- }
- }
-
- if ((matches == null || matches.isEmpty()) && (fMarkMethodExitPoints || fMarkTypeOccurrences)) {
- MethodExitsFinder finder= new MethodExitsFinder();
- String message= finder.initialize(astRoot, selectedNode);
- if (message == null) {
- matches= finder.perform();
- if (!fMarkMethodExitPoints && !matches.isEmpty())
- matches.clear();
- }
- }
-
- if ((matches == null || matches.isEmpty()) && (fMarkBreakContinueTargets || fMarkTypeOccurrences)) {
- BreakContinueTargetFinder finder= new BreakContinueTargetFinder();
- String message= finder.initialize(astRoot, selectedNode);
- if (message == null) {
- matches= finder.perform();
- if (!fMarkBreakContinueTargets && !matches.isEmpty())
- matches.clear();
- }
- }
-
- if ((matches == null || matches.isEmpty()) && (fMarkImplementors || fMarkTypeOccurrences)) {
- ImplementOccurrencesFinder finder= new ImplementOccurrencesFinder();
- String message= finder.initialize(astRoot, selectedNode);
- if (message == null) {
- matches= finder.perform();
- if (!fMarkImplementors && !matches.isEmpty())
- matches.clear();
- }
- }
-
- if (matches == null) {
- IBinding binding= null;
- if (selectedNode instanceof Name)
- binding= ((Name)selectedNode).resolveBinding();
-
- if (binding != null && markOccurrencesOfType(binding)) {
- // Find the matches && extract positions so we can forget the AST
- OccurrencesFinder finder = new OccurrencesFinder(binding);
- String message= finder.initialize(astRoot, selectedNode);
- if (message == null)
- matches= finder.perform();
- }
- }
-
- if (matches == null || matches.size() == 0) {
- if (!fStickyOccurrenceAnnotations)
- removeOccurrenceAnnotations();
- return;
- }
-
- Position[] positions= new Position[matches.size()];
- int i= 0;
- for (Iterator each= matches.iterator(); each.hasNext();) {
- ASTNode currentNode= (ASTNode)each.next();
- positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
- }
-
- fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
- //fOccurrencesFinderJob.setPriority(Job.DECORATE);
- //fOccurrencesFinderJob.setSystem(true);
- //fOccurrencesFinderJob.schedule();
- fOccurrencesFinderJob.run(new NullProgressMonitor());
- }
-
- protected void installOccurrencesFinder(boolean forceUpdate) {
- fMarkOccurrenceAnnotations= true;
-
- fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
- public void selectionChanged(IEditorPart part, ITextSelection selection, JavaScriptUnit astRoot) {
- updateOccurrenceAnnotations(selection, astRoot);
- }
- };
- SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
- if (forceUpdate && getSelectionProvider() != null) {
- fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
- updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, JavaScriptPlugin.getDefault().getASTProvider().getAST(getInputJavaElement(), ASTProvider.WAIT_NO, getProgressMonitor()));
- }
-
- if (fOccurrencesFinderJobCanceler == null) {
- fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
- fOccurrencesFinderJobCanceler.install();
- }
- }
-
- protected void uninstallOccurrencesFinder() {
- fMarkOccurrenceAnnotations= false;
-
- if (fOccurrencesFinderJob != null) {
- fOccurrencesFinderJob.cancel();
- fOccurrencesFinderJob= null;
- }
-
- if (fOccurrencesFinderJobCanceler != null) {
- fOccurrencesFinderJobCanceler.uninstall();
- fOccurrencesFinderJobCanceler= null;
- }
-
- if (fPostSelectionListenerWithAST != null) {
- SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
- fPostSelectionListenerWithAST= null;
- }
-
- removeOccurrenceAnnotations();
- }
-
- protected boolean isMarkingOccurrences() {
- IPreferenceStore store= getPreferenceStore();
- return store != null && store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
- }
-
- boolean markOccurrencesOfType(IBinding binding) {
-
- if (binding == null)
- return false;
-
- int kind= binding.getKind();
-
- if (fMarkTypeOccurrences && kind == IBinding.TYPE)
- return true;
-
- if (fMarkMethodOccurrences && kind == IBinding.METHOD)
- return true;
-
- if (kind == IBinding.VARIABLE) {
- IVariableBinding variableBinding= (IVariableBinding)binding;
- if (variableBinding.isField()) {
- int constantModifier= IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL;
- boolean isConstant= (variableBinding.getModifiers() & constantModifier) == constantModifier;
- if (isConstant)
- return fMarkConstantOccurrences;
- else
- return fMarkFieldOccurrences;
- }
-
- return fMarkLocalVariableypeOccurrences;
- }
-
- return false;
- }
-
- void removeOccurrenceAnnotations() {
- fMarkOccurrenceModificationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
- fMarkOccurrenceTargetRegion= null;
-
- IDocumentProvider documentProvider= getDocumentProvider();
- if (documentProvider == null)
- return;
-
- IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
- if (annotationModel == null || fOccurrenceAnnotations == null)
- return;
-
- synchronized (getLockObject(annotationModel)) {
- if (annotationModel instanceof IAnnotationModelExtension) {
- ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
- } else {
- for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
- annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
- }
- fOccurrenceAnnotations= null;
- }
- }
-
- protected void uninstallOverrideIndicator() {
- if (fOverrideIndicatorManager != null) {
- fOverrideIndicatorManager.removeAnnotations();
- fOverrideIndicatorManager= null;
- }
- }
-
- protected void installOverrideIndicator(boolean provideAST) {
- uninstallOverrideIndicator();
- IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
- final IJavaScriptElement inputElement= getInputJavaElement();
-
- if (model == null || inputElement == null)
- return;
-
- fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
-
- if (provideAST) {
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(inputElement, ASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
- fOverrideIndicatorManager.reconciled(ast, true, getProgressMonitor());
- }
- }
-
- /**
- * Tells whether override indicators are shown.
- *
- * @return <code>true</code> if the override indicators are shown
- *
- */
- protected boolean isShowingOverrideIndicators() {
- AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
- IPreferenceStore store= getPreferenceStore();
- return getBoolean(store, preference.getHighlightPreferenceKey())
- || getBoolean(store, preference.getVerticalRulerPreferenceKey())
- || getBoolean(store, preference.getOverviewRulerPreferenceKey())
- || getBoolean(store, preference.getTextPreferenceKey());
- }
-
- /**
- * Returns the boolean preference for the given key.
- *
- * @param store the preference store
- * @param key the preference key
- * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
- *
- */
- private boolean getBoolean(IPreferenceStore store, String key) {
- return key != null && store.getBoolean(key);
- }
-
- /**
- * Determines whether the preference change encoded by the given event
- * changes the override indication.
- *
- * @param event the event to be investigated
- * @return <code>true</code> if event causes a change
- *
- */
- protected boolean affectsOverrideIndicatorAnnotations(PropertyChangeEvent event) {
- String key= event.getProperty();
- AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
- if (key == null || preference == null)
- return false;
-
- return key.equals(preference.getHighlightPreferenceKey())
- || key.equals(preference.getVerticalRulerPreferenceKey())
- || key.equals(preference.getOverviewRulerPreferenceKey())
- || key.equals(preference.getTextPreferenceKey());
- }
-
- /**
- * @return <code>true</code> if Semantic Highlighting is enabled.
- *
- *
- */
- private boolean isSemanticHighlightingEnabled() {
- return SemanticHighlightings.isEnabled(getPreferenceStore());
- }
-
- /**
- * Install Semantic Highlighting.
- *
- *
- */
- private void installSemanticHighlighting() {
- if (fSemanticManager == null) {
- fSemanticManager= new SemanticHighlightingManager();
- fSemanticManager.install(this, (JavaSourceViewer) getSourceViewer(), JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), getPreferenceStore());
- }
- }
-
- /**
- * Uninstall Semantic Highlighting.
- *
- *
- */
- private void uninstallSemanticHighlighting() {
- if (fSemanticManager != null) {
- fSemanticManager.uninstall();
- fSemanticManager= null;
- }
- }
-
- /**
- * Returns the Java element wrapped by this editors input.
- *
- * @return the Java element wrapped by this editors input.
- *
- */
- protected IJavaScriptElement getInputJavaElement() {
- return EditorUtility.getEditorInputJavaElement(this, false);
- }
-
- protected void updateStatusLine() {
- ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
- Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
- setStatusLineErrorMessage(null);
- setStatusLineMessage(null);
- if (annotation != null) {
- updateMarkerViews(annotation);
- if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
- setStatusLineMessage(annotation.getText());
- }
- }
-
- /**
- * Jumps to the matching bracket.
- */
- public void gotoMatchingBracket() {
-
- ISourceViewer sourceViewer= getSourceViewer();
- IDocument document= sourceViewer.getDocument();
- if (document == null)
- return;
-
- IRegion selection= getSignedSelection(sourceViewer);
-
- int selectionLength= Math.abs(selection.getLength());
- if (selectionLength > 1) {
- setStatusLineErrorMessage(JavaEditorMessages.GotoMatchingBracket_error_invalidSelection);
- sourceViewer.getTextWidget().getDisplay().beep();
- return;
- }
-
- // #26314
- int sourceCaretOffset= selection.getOffset() + selection.getLength();
- if (isSurroundedByBrackets(document, sourceCaretOffset))
- sourceCaretOffset -= selection.getLength();
-
- IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
- if (region == null) {
- setStatusLineErrorMessage(JavaEditorMessages.GotoMatchingBracket_error_noMatchingBracket);
- sourceViewer.getTextWidget().getDisplay().beep();
- return;
- }
-
- int offset= region.getOffset();
- int length= region.getLength();
-
- if (length < 1)
- return;
-
- int anchor= fBracketMatcher.getAnchor();
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
- int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
-
- boolean visible= false;
- if (sourceViewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
- visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
- } else {
- IRegion visibleRegion= sourceViewer.getVisibleRegion();
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
- visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
- }
-
- if (!visible) {
- setStatusLineErrorMessage(JavaEditorMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement);
- sourceViewer.getTextWidget().getDisplay().beep();
- return;
- }
-
- if (selection.getLength() < 0)
- targetOffset -= selection.getLength();
-
- sourceViewer.setSelectedRange(targetOffset, selection.getLength());
- sourceViewer.revealRange(targetOffset, selection.getLength());
- }
-
- /**
- * Returns the signed current selection.
- * The length will be negative if the resulting selection
- * is right-to-left (RtoL).
- * <p>
- * The selection offset is model based.
- * </p>
- *
- * @param sourceViewer the source viewer
- * @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0
- */
- protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
- StyledText text= sourceViewer.getTextWidget();
- Point selection= text.getSelectionRange();
-
- if (text.getCaretOffset() == selection.x) {
- selection.x= selection.x + selection.y;
- selection.y= -selection.y;
- }
-
- selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
-
- return new Region(selection.x, selection.y);
- }
-
- /**
- * Returns the cached selected range, which allows
- * to query it from a non-UI thread.
- * <p>
- * The result might be outdated if queried from a non-UI thread.</em></p>
- *
- * @return the caret offset in the master document
- * @see ITextViewer#getSelectedRange()
- *
- */
- public Point getCachedSelectedRange() {
- return fCachedSelectedRange;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleCursorPositionChanged()
- *
- */
- protected void handleCursorPositionChanged() {
- super.handleCursorPositionChanged();
- fCachedSelectedRange= getViewer().getSelectedRange();
- }
-
- private static boolean isBracket(char character) {
- for (int i= 0; i != BRACKETS.length; ++i)
- if (character == BRACKETS[i])
- return true;
- return false;
- }
-
- private static boolean isSurroundedByBrackets(IDocument document, int offset) {
- if (offset == 0 || offset == document.getLength())
- return false;
-
- try {
- return
- isBracket(document.getChar(offset - 1)) &&
- isBracket(document.getChar(offset));
-
- } catch (BadLocationException e) {
- return false;
- }
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Overrides the default implementation to handle {@link IJavaAnnotation}.
- * </p>
- *
- * @param offset the region offset
- * @param length the region length
- * @param forward <code>true</code> for forwards, <code>false</code> for backward
- * @param annotationPosition the position of the found annotation
- * @return the found annotation
- *
- */
- protected Annotation findAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
-
- Annotation nextAnnotation= null;
- Position nextAnnotationPosition= null;
- Annotation containingAnnotation= null;
- Position containingAnnotationPosition= null;
- boolean currentAnnotation= false;
-
- IDocument document= getDocumentProvider().getDocument(getEditorInput());
- int endOfDocument= document.getLength();
- int distance= Integer.MAX_VALUE;
-
- IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
- Iterator e= new JavaAnnotationIterator(model, true, true);
- while (e.hasNext()) {
- Annotation a= (Annotation) e.next();
- if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
- continue;
-
- Position p= model.getPosition(a);
- if (p == null)
- continue;
-
- if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
- if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
- containingAnnotation= a;
- containingAnnotationPosition= p;
- currentAnnotation= p.length == length;
- }
- } else {
- int currentDistance= 0;
-
- if (forward) {
- currentDistance= p.getOffset() - offset;
- if (currentDistance < 0)
- currentDistance= endOfDocument + currentDistance;
-
- if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
- distance= currentDistance;
- nextAnnotation= a;
- nextAnnotationPosition= p;
- }
- } else {
- currentDistance= offset + length - (p.getOffset() + p.length);
- if (currentDistance < 0)
- currentDistance= endOfDocument + currentDistance;
-
- if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
- distance= currentDistance;
- nextAnnotation= a;
- nextAnnotationPosition= p;
- }
- }
- }
- }
- if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
- annotationPosition.setOffset(containingAnnotationPosition.getOffset());
- annotationPosition.setLength(containingAnnotationPosition.getLength());
- return containingAnnotation;
- }
- if (nextAnnotationPosition != null) {
- annotationPosition.setOffset(nextAnnotationPosition.getOffset());
- annotationPosition.setLength(nextAnnotationPosition.getLength());
- }
-
- return nextAnnotation;
- }
-
- /**
- * Returns the annotation overlapping with the given range or <code>null</code>.
- *
- * @param offset the region offset
- * @param length the region length
- * @return the found annotation or <code>null</code>
- *
- */
- private Annotation getAnnotation(int offset, int length) {
- IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
- Iterator e= new JavaAnnotationIterator(model, true, false);
- while (e.hasNext()) {
- Annotation a= (Annotation) e.next();
- Position p= model.getPosition(a);
- if (p != null && p.overlapsWith(offset, length))
- return a;
- }
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#gotoAnnotation(boolean)
- *
- */
- public Annotation gotoAnnotation(boolean forward) {
- fSelectionChangedViaGotoAnnotation= true;
- return super.gotoAnnotation(forward);
- }
-
- /**
- * Computes and returns the source reference that includes the caret and
- * serves as provider for the outline page selection and the editor range
- * indication.
- *
- * @return the computed source reference
- *
- */
- protected ISourceReference computeHighlightRangeSourceReference() {
- ISourceViewer sourceViewer= getSourceViewer();
- if (sourceViewer == null)
- return null;
-
- StyledText styledText= sourceViewer.getTextWidget();
- if (styledText == null)
- return null;
-
- int caret= 0;
- if (sourceViewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
- caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
- } else {
- int offset= sourceViewer.getVisibleRegion().getOffset();
- caret= offset + styledText.getCaretOffset();
- }
-
- IJavaScriptElement element= getElementAt(caret, false);
-
- if ( !(element instanceof ISourceReference))
- return null;
-
- if (element.getElementType() == IJavaScriptElement.IMPORT_DECLARATION) {
-
- IImportDeclaration declaration= (IImportDeclaration) element;
- IImportContainer container= (IImportContainer) declaration.getParent();
- ISourceRange srcRange= null;
-
- try {
- srcRange= container.getSourceRange();
- } catch (JavaScriptModelException e) {
- }
-
- if (srcRange != null && srcRange.getOffset() == caret)
- return container;
- }
-
- return (ISourceReference) element;
- }
-
- /**
- * Returns the most narrow java element including the given offset.
- *
- * @param offset the offset inside of the requested element
- * @param reconcile <code>true</code> if editor input should be reconciled in advance
- * @return the most narrow java element
- *
- */
- protected IJavaScriptElement getElementAt(int offset, boolean reconcile) {
- return getElementAt(offset);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createChangeHover()
- */
- protected LineChangeHover createChangeHover() {
- return new JavaChangeHover(IJavaScriptPartitions.JAVA_PARTITIONING, getOrientation());
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
- */
- protected void createNavigationActions() {
- super.createNavigationActions();
-
- final StyledText textWidget= getSourceViewer().getTextWidget();
-
- IAction action= new SmartLineStartAction(textWidget, false);
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
- setAction(ITextEditorActionDefinitionIds.LINE_START, action);
-
- action= new SmartLineStartAction(textWidget, true);
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
- setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
-
- action= new NavigatePreviousSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
- setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
-
- action= new NavigateNextSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
- setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
-
- action= new SelectPreviousSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
- setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
-
- action= new SelectNextSubWordAction();
- action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
- setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
- textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler)
- *
- */
- protected IVerticalRulerColumn createAnnotationRulerColumn(CompositeRuler ruler) {
- if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
- return super.createAnnotationRulerColumn(ruler);
-
- AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
- column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
-
- public void doubleClick(DoubleClickEvent event) {
- // for now: just invoke ruler double click action
- triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
- }
-
- private void triggerAction(String actionID) {
- IAction action= getAction(actionID);
- if (action != null) {
- if (action instanceof IUpdate)
- ((IUpdate) action).update();
- // hack to propagate line change
- if (action instanceof ISelectionListener) {
- ((ISelectionListener)action).selectionChanged(null, null);
- }
- if (action.isEnabled())
- action.run();
- }
- }
-
- }));
-
- return column;
- }
-
- /**
- * Returns the folding action group, or <code>null</code> if there is none.
- *
- * @return the folding action group, or <code>null</code> if there is none
- *
- */
- protected FoldingActionGroup getFoldingActionGroup() {
- return fFoldingGroup;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert()
- */
- protected void performRevert() {
- ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
- projectionViewer.setRedraw(false);
- try {
-
- boolean projectionMode= projectionViewer.isProjectionMode();
- if (projectionMode) {
- projectionViewer.disableProjection();
- if (fProjectionModelUpdater != null)
- fProjectionModelUpdater.uninstall();
- }
-
- super.performRevert();
-
- if (projectionMode) {
- if (fProjectionModelUpdater != null)
- fProjectionModelUpdater.install(this, projectionViewer);
- projectionViewer.enableProjection();
- }
-
- } finally {
- projectionViewer.setRedraw(true);
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#rulerContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
- */
- protected void rulerContextMenuAboutToShow(IMenuManager menu) {
- super.rulerContextMenuAboutToShow(menu);
- IMenuManager foldingMenu= new MenuManager(JavaEditorMessages.Editor_FoldingMenu_name, "projection"); //$NON-NLS-1$
- menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, foldingMenu);
-
- IAction action= getAction("FoldingToggle"); //$NON-NLS-1$
- foldingMenu.add(action);
- action= getAction("FoldingExpandAll"); //$NON-NLS-1$
- foldingMenu.add(action);
- action= getAction("FoldingCollapseAll"); //$NON-NLS-1$
- foldingMenu.add(action);
- action= getAction("FoldingRestore"); //$NON-NLS-1$
- foldingMenu.add(action);
- action= getAction("FoldingCollapseMembers"); //$NON-NLS-1$
- foldingMenu.add(action);
- action= getAction("FoldingCollapseComments"); //$NON-NLS-1$
- foldingMenu.add(action);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages()
- *
- */
- protected String[] collectContextMenuPreferencePages() {
- String[] inheritedPages= super.collectContextMenuPreferencePages();
- int length= 10;
- String[] result= new String[inheritedPages.length + length];
- result[0]= "org.eclipse.wst.jsdt.ui.preferences.JavaEditorPreferencePage"; //$NON-NLS-1$
- result[1]= "org.eclipse.wst.jsdt.ui.preferences.JavaTemplatePreferencePage"; //$NON-NLS-1$
- result[2]= "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferencePage"; //$NON-NLS-1$
- result[3]= "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced"; //$NON-NLS-1$
- result[4]= "org.eclipse.wst.jsdt.ui.preferences.JavaEditorHoverPreferencePage"; //$NON-NLS-1$
- result[5]= "org.eclipse.wst.jsdt.ui.preferences.JavaEditorColoringPreferencePage"; //$NON-NLS-1$
- result[6]= "org.eclipse.wst.jsdt.ui.preferences.FoldingPreferencePage"; //$NON-NLS-1$
- result[7]= "org.eclipse.wst.jsdt.ui.preferences.MarkOccurrencesPreferencePage"; //$NON-NLS-1$
- result[8]= "org.eclipse.wst.jsdt.ui.preferences.SmartTypingPreferencePage"; //$NON-NLS-1$
- result[9]= "org.eclipse.wst.jsdt.ui.preferences.SaveParticipantPreferencePage"; //$NON-NLS-1$
- System.arraycopy(inheritedPages, 0, result, length, inheritedPages.length);
- return result;
- }
-
- /*
- * @see AbstractTextEditor#getUndoRedoOperationApprover(IUndoContext)
- *
- */
- protected IOperationApprover getUndoRedoOperationApprover(IUndoContext undoContext) {
- // since IResource is a more general way to compare java elements, we
- // use this as the preferred class for comparing objects.
- return new NonLocalUndoUserApprover(undoContext, this, new Object [] { getInputJavaElement() }, IResource.class);
- }
-
- /**
- * Resets the foldings structure according to the folding
- * preferences.
- *
- *
- */
- public void resetProjection() {
- if (fProjectionModelUpdater != null) {
- fProjectionModelUpdater.initialize();
- }
- }
-
- /**
- * Collapses all foldable members if supported by the folding
- * structure provider.
- *
- *
- */
- public void collapseMembers() {
- if (fProjectionModelUpdater instanceof IJavaFoldingStructureProviderExtension) {
- IJavaFoldingStructureProviderExtension extension= (IJavaFoldingStructureProviderExtension) fProjectionModelUpdater;
- extension.collapseMembers();
- }
- }
-
- /**
- * Collapses all foldable comments if supported by the folding
- * structure provider.
- *
- *
- */
- public void collapseComments() {
- if (fProjectionModelUpdater instanceof IJavaFoldingStructureProviderExtension) {
- IJavaFoldingStructureProviderExtension extension= (IJavaFoldingStructureProviderExtension) fProjectionModelUpdater;
- extension.collapseComments();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorErrorTickUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorErrorTickUpdater.java
deleted file mode 100644
index feb21c73..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorErrorTickUpdater.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IProblemChangedListener;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-
-/**
- * The <code>JavaEditorErrorTickUpdater</code> will register as a IProblemChangedListener
- * to listen on problem changes of the editor's input. It updates the title images when the annotation
- * model changed.
- */
-public class JavaEditorErrorTickUpdater implements IProblemChangedListener {
-
- private JavaEditor fJavaEditor;
- private JavaUILabelProvider fLabelProvider;
-
- public JavaEditorErrorTickUpdater(JavaEditor editor) {
- Assert.isNotNull(editor);
- fJavaEditor= editor;
- fLabelProvider= new JavaUILabelProvider(0, JavaElementImageProvider.SMALL_ICONS);
- fLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
- JavaScriptPlugin.getDefault().getProblemMarkerManager().addListener(this);
- }
-
- /* (non-Javadoc)
- * @see IProblemChangedListener#problemsChanged(IResource[], boolean)
- */
- public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
- if (!isMarkerChange)
- return;
-
- IEditorInput input= fJavaEditor.getEditorInput();
- if (input != null) { // might run async, tests needed
- IJavaScriptElement jelement= (IJavaScriptElement) input.getAdapter(IJavaScriptElement.class);
- if (jelement != null) {
- IResource resource= jelement.getResource();
- for (int i = 0; i < changedResources.length; i++) {
- if (changedResources[i].equals(resource)) {
- updateEditorImage(jelement);
- }
- }
- }
- }
- }
-
- public void updateEditorImage(IJavaScriptElement jelement) {
- Image titleImage= fJavaEditor.getTitleImage();
- if (titleImage == null) {
- return;
- }
- Image newImage;
- if (jelement instanceof IJavaScriptUnit && !jelement.getJavaScriptProject().isOnIncludepath(jelement))
- newImage= fLabelProvider.getImage(jelement.getResource());
- else
- newImage= fLabelProvider.getImage(jelement);
- if (titleImage != newImage) {
- postImageChange(newImage);
- }
- }
-
- private void postImageChange(final Image newImage) {
- Shell shell= fJavaEditor.getEditorSite().getShell();
- if (shell != null && !shell.isDisposed()) {
- shell.getDisplay().syncExec(new Runnable() {
- public void run() {
- fJavaEditor.updatedTitleImage(newImage);
- }
- });
- }
- }
-
- public void dispose() {
- fLabelProvider.dispose();
- JavaScriptPlugin.getDefault().getProblemMarkerManager().removeListener(this);
- }
-
-
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java
deleted file mode 100644
index f1b0741a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class JavaEditorMessages extends NLS {
-
- private static final String BUNDLE_FOR_CONSTRUCTED_KEYS= "org.eclipse.wst.jsdt.internal.ui.javaeditor.ConstructedJavaEditorMessages";//$NON-NLS-1$
- private static ResourceBundle fgBundleForConstructedKeys= ResourceBundle.getBundle(BUNDLE_FOR_CONSTRUCTED_KEYS);
-
- /**
- * Returns the message bundle which contains constructed keys.
- *
- *
- * @return the message bundle
- */
- public static ResourceBundle getBundleForConstructedKeys() {
- return fgBundleForConstructedKeys;
- }
-
- private static final String BUNDLE_NAME= JavaEditorMessages.class.getName();
-
-
- private JavaEditorMessages() {
- // Do not instantiate
- }
-
- public static String AddImportOnSelection_label;
- public static String AddImportOnSelection_tooltip;
- public static String AddImportOnSelection_description;
- public static String AddImportOnSelection_error_title;
- public static String AddImportOnSelection_dialog_title;
- public static String AddImportOnSelection_dialog_message;
- public static String ClassFileEditor_error_classfile_not_on_classpath;
- public static String ClassFileEditor_error_invalid_input_message;
- public static String ClassFileEditor_error_title;
- public static String ClassFileEditor_error_message;
-// public static String ClassFileEditor_SourceAttachmentForm_cannotconfigure;
-// public static String ClassFileEditor_SourceAttachmentForm_notsupported;
-// public static String ClassFileEditor_SourceAttachmentForm_readonly;
- public static String ClassFileMarkerAnnotationModel_error_isAcceptable;
- public static String ClassFileMarkerAnnotationModel_error_isAffected;
- public static String ClassFileMarkerAnnotationModel_error_resourceChanged;
- public static String CompilationUnitDocumentProvider_progressNotifyingSaveParticipants;
- public static String CompilationUnitDocumentProvider_error_saveParticipantProblem;
- public static String CompilationUnitDocumentProvider_error_saveParticipantSavedFile;
- public static String CompilationUnitDocumentProvider_error_saveParticipantFailed;
- public static String CompilationUnitEditor_error_saving_message1;
- public static String CompilationUnitEditor_error_saving_title1;
- public static String CompilationUnitEditor_error_saving_saveParticipant;
- public static String EditorUtility_cantFindEditor;
- public static String EditorUtility_could_not_find_editorId;
- public static String EditorUtility_file_must_not_be_null;
- public static String EditorUtility_no_active_WorkbenchPage;
- public static String EditorUtility_no_editorInput;
- public static String JavaOutlinePage_Sort_label;
- public static String JavaOutlinePage_Sort_tooltip;
- public static String JavaOutlinePage_Sort_description;
- public static String JavaOutlinePage_GoIntoTopLevelType_label;
- public static String JavaOutlinePage_GoIntoTopLevelType_tooltip;
- public static String JavaOutlinePage_GoIntoTopLevelType_description;
- public static String JavaOutlinePage_error_NoTopLevelType;
- public static String ToggleComment_error_title;
- public static String ToggleComment_error_message;
- public static String ContentAssistProposal_label;
- public static String Editor_FoldingMenu_name;
- public static String CompilationUnitDocumentProvider_saveAsTargetOpenInEditor;
- public static String ClassFileDocumentProvider_error_createElementInfo;
- public static String ExpandSelectionMenu_label;
- public static String GotoMatchingBracket_label;
- public static String GotoMatchingBracket_error_invalidSelection;
- public static String GotoMatchingBracket_error_noMatchingBracket;
- public static String GotoMatchingBracket_error_bracketOutsideSelectedElement;
- public static String SourceAttachmentForm_title;
- public static String SourceAttachmentForm_heading;
- public static String SourceAttachmentForm_message_noSource;
-// public static String SourceAttachmentForm_message_noSourceAttachment;
-// public static String SourceAttachmentForm_message_pressButtonToAttach;
-// public static String SourceAttachmentForm_message_noSourceInAttachment;
-// public static String SourceAttachmentForm_message_pressButtonToChange;
-// public static String SourceAttachmentForm_button_attachSource;
-// public static String SourceAttachmentForm_button_changeAttachedSource;
-// public static String SourceAttachmentForm_error_title;
-// public static String SourceAttachmentForm_error_message;
- public static String SourceAttachmentForm_attach_error_title;
- public static String SourceAttachmentForm_attach_error_message;
- public static String EditorUtility_concatModifierStrings;
- public static String OverrideIndicatorManager_implements;
- public static String OverrideIndicatorManager_intallJob;
- public static String OverrideIndicatorManager_overrides;
- public static String OverrideIndicatorManager_open_error_title;
- public static String OverrideIndicatorManager_open_error_message;
- public static String OverrideIndicatorManager_open_error_messageHasLogEntry;
- public static String SemanticHighlighting_job;
- public static String SemanticHighlighting_methodDeclaration;
- public static String SemanticHighlighting_localVariableDeclaration;
- public static String SemanticHighlighting_localVariable;
- public static String SemanticHighlighting_parameterVariable;
- public static String SemanticHighlighting_deprecatedMember;
- public static String SemanticHighlighting_method;
- public static String SemanticHighlighting_objectInitializer;
- public static String JavaEditor_markOccurrences_job_name;
- public static String Editor_OpenPropertiesFile_error_keyNotFound;
- public static String Editor_OpenPropertiesFile_error_fileNotFound_dialogMessage;
- public static String Editor_OpenPropertiesFile_error_openEditor_dialogMessage;
- public static String Editor_MoveLines_IllegalMove_status;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaEditorMessages.class);
- }
-
- public static String BasicEditorActionContributor_specific_content_assist_menu;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties
deleted file mode 100644
index f391e4e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties
+++ /dev/null
@@ -1,115 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-AddImportOnSelection_label=A&dd Import
-AddImportOnSelection_tooltip=Create Import Statement on Selection
-AddImportOnSelection_description=Create import statement on selection
-
-AddImportOnSelection_error_title=Add Import
-
-AddImportOnSelection_dialog_title=Add Import
-AddImportOnSelection_dialog_message=&Choose element to generate an import statement for:
-
-ClassFileEditor_error_classfile_not_on_classpath=The class file is not on the classpath
-#ClassFileEditor_SourceAttachmentForm_cannotconfigure=The JAR of this javaScript file belongs to container ''{0}'' can not be configured.
-#ClassFileEditor_SourceAttachmentForm_notsupported=The JAR of this javaScript file belongs to container ''{0}'' which does not support the attachment of sources to its entries.
-ClassFileEditor_error_invalid_input_message=The Class File Viewer cannot handle the given input.
-#ClassFileEditor_SourceAttachmentForm_readonly=The JAR of this javaScript file belongs to container ''{0}'' which does not allow modifications to source attachments on its entries.
-ClassFileEditor_error_title=Error Creating Editor
-ClassFileEditor_error_message=An error occurred while creating the class file editor.
-
-ClassFileMarkerAnnotationModel_error_isAcceptable=ClassFileMarkerAnnotationModel.isAcceptable
-ClassFileMarkerAnnotationModel_error_isAffected=ClassFileMarkerAnnotationModel.isAffected
-ClassFileMarkerAnnotationModel_error_resourceChanged=ClassFileMarkerAnnotationModel.resourceChanged
-
-CompilationUnitEditor_error_saving_message1=File has been deleted or is not accessible.
-CompilationUnitEditor_error_saving_title1=Cannot Save
-CompilationUnitEditor_error_saving_saveParticipant=To avoid this, disable the corresponding participants on the <a>Save Actions</a> preference page.
-
-JavaOutlinePage_Sort_label=Sort
-JavaOutlinePage_Sort_tooltip=Sort
-JavaOutlinePage_Sort_description=Enable Sorting
-JavaOutlinePage_GoIntoTopLevelType_label=Go Into Top Level Type
-JavaOutlinePage_GoIntoTopLevelType_tooltip=Go Into Top Level Type
-JavaOutlinePage_GoIntoTopLevelType_description=Show children of top level type only
-JavaOutlinePage_error_NoTopLevelType=Top level type not defined
-
-ToggleComment_error_title=Toggle Comment
-ToggleComment_error_message=An error occurred while toggling comments.
-
-ContentAssistProposal_label=&Default
-BasicEditorActionContributor_specific_content_assist_menu=Co&ntent Assist
-
-Editor_FoldingMenu_name=F&olding
-
-CompilationUnitDocumentProvider_saveAsTargetOpenInEditor=Target file is already open in another editor.
-CompilationUnitDocumentProvider_progressNotifyingSaveParticipants=Notifying save participants
-CompilationUnitDocumentProvider_error_saveParticipantProblem=A save participant caused problems.
-CompilationUnitDocumentProvider_error_saveParticipantSavedFile=The save participant ''{0}'' spuriously saved the file.
-CompilationUnitDocumentProvider_error_saveParticipantFailed=The save participant ''{0}'' caused an exception: {1}. See the error Log for details.
-
-ClassFileDocumentProvider_error_createElementInfo=ClassFileDocumentProvider.createElementInfo
-
-
-
-
-ExpandSelectionMenu_label=E&xpand Selection To
-
-
-GotoMatchingBracket_label= Matching &Bracket
-GotoMatchingBracket_error_invalidSelection=No bracket selected
-GotoMatchingBracket_error_noMatchingBracket=No matching bracket found
-GotoMatchingBracket_error_bracketOutsideSelectedElement=Matching bracket is outside the selected element
-
-SourceAttachmentForm_title=Class File Editor
-SourceAttachmentForm_heading=Source not found
-SourceAttachmentForm_message_noSource=There is no source file attached to the javascript file {0}.
-#SourceAttachmentForm_message_noSourceAttachment=The jar file {0} has no source attachment.
-#SourceAttachmentForm_message_pressButtonToAttach=You can attach the source by clicking Attach Source below:
-#SourceAttachmentForm_message_noSourceInAttachment=The source attachment does not contain the source for the file {0}.
-#SourceAttachmentForm_message_pressButtonToChange=You can change the source attachment by clicking Change Attached Source below:
-#SourceAttachmentForm_button_attachSource=&Attach Source...
-#SourceAttachmentForm_button_changeAttachedSource=&Change Attached Source...
-#SourceAttachmentForm_error_title=Error Opening Source Attachment Form
-#SourceAttachmentForm_error_message=An error occurred while opening the source attachment form
-SourceAttachmentForm_attach_error_title=Error Attaching Source
-SourceAttachmentForm_attach_error_message=An error occurred while applying the source attachment
-
-EditorUtility_concatModifierStrings= {0} + {1}
-EditorUtility_no_editorInput=Could not get an editor input for the given element
-EditorUtility_cantFindEditor=Can't find Editor for file:
-EditorUtility_file_must_not_be_null=File must not be null
-EditorUtility_no_active_WorkbenchPage=No active workbench page
-EditorUtility_could_not_find_editorId=Cannot find an editor ID for the given editor input
-
-OverrideIndicatorManager_implements= implements {0}
-OverrideIndicatorManager_intallJob= Override indicator installation job
-OverrideIndicatorManager_overrides= overrides {0}
-OverrideIndicatorManager_open_error_title= Open Declaring Function
-OverrideIndicatorManager_open_error_message= Could not open the super implementation.
-OverrideIndicatorManager_open_error_messageHasLogEntry= Could not open the super implementation.\nSee the error log for details.
-
-SemanticHighlighting_job= Semantic Highlighting Job
-SemanticHighlighting_methodDeclaration= Function declarations
-SemanticHighlighting_localVariableDeclaration= Local variable declarations
-SemanticHighlighting_localVariable= Local variable references
-SemanticHighlighting_parameterVariable= Parameter variables
-SemanticHighlighting_deprecatedMember= Deprecated members
-SemanticHighlighting_method= Functions
-SemanticHighlighting_objectInitializer = Object initializer
-
-JavaEditor_markOccurrences_job_name= Occurrences Marker
-
-Editor_OpenPropertiesFile_error_keyNotFound= The key "{0}" is not defined in this properties file
-Editor_OpenPropertiesFile_error_fileNotFound_dialogMessage= Could not determine properties file
-Editor_OpenPropertiesFile_error_openEditor_dialogMessage= Could not open the properties file editor for: {0}
-
-Editor_MoveLines_IllegalMove_status= Move not possible - Uncheck "Show Source of Selected Element Only" to see the entire document
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java
deleted file mode 100644
index f3743bb9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-
-
-/**
- * Java element hyperlink.
- *
- *
- */
-public class JavaElementHyperlink implements IHyperlink {
-
- private final IRegion fRegion;
- private final IAction fOpenAction;
-
-
- /**
- * Creates a new Java element hyperlink.
- */
- public JavaElementHyperlink(IRegion region, IAction openAction) {
- Assert.isNotNull(openAction);
- Assert.isNotNull(region);
-
- fRegion= region;
- fOpenAction= openAction;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getHyperlinkRegion()
- *
- */
- public IRegion getHyperlinkRegion() {
- return fRegion;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#open()
- *
- */
- public void open() {
- fOpenAction.run();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getTypeLabel()
- *
- */
- public String getTypeLabel() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getHyperlinkText()
- *
- */
- public String getHyperlinkText() {
- return fOpenAction.getToolTipText();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java
deleted file mode 100644
index 1e9e5f09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.ICodeAssist;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-
-
-/**
- * Java element hyperlink detector.
- *
- *
- */
-public class JavaElementHyperlinkDetector extends AbstractHyperlinkDetector {
-
- /*
- * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
- */
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
- ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
- if (region == null || !(textEditor instanceof JavaEditor))
- return null;
-
- IAction openAction= textEditor.getAction("OpenEditor"); //$NON-NLS-1$
- if (openAction == null)
- return null;
-
- int offset= region.getOffset();
-
- IJavaScriptElement input= EditorUtility.getEditorInputJavaElement(textEditor, false);
- if (input == null)
- return null;
-
- try {
- IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
- IRegion wordRegion= JavaWordFinder.findWord(document, offset);
- if (wordRegion == null)
- return null;
-
- IJavaScriptElement[] elements= null;
- elements= ((ICodeAssist) input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
- if (elements != null && elements.length > 0)
- return new IHyperlink[] {new JavaElementHyperlink(wordRegion, openAction)};
- } catch (JavaScriptModelException e) {
- return null;
- }
-
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMarkerAnnotation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMarkerAnnotation.java
deleted file mode 100644
index 967e66bf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMarkerAnnotation.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.ui.texteditor.MarkerUtilities;
-import org.eclipse.wst.jsdt.core.CorrectionEngine;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-
-public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnotation {
-
- public static final String JAVA_MARKER_TYPE_PREFIX= "org.eclipse.wst.jsdt"; //$NON-NLS-1$
- public static final String ERROR_ANNOTATION_TYPE= "org.eclipse.wst.jsdt.ui.error"; //$NON-NLS-1$
- public static final String WARNING_ANNOTATION_TYPE= "org.eclipse.wst.jsdt.ui.warning"; //$NON-NLS-1$
- public static final String INFO_ANNOTATION_TYPE= "org.eclipse.wst.jsdt.ui.info"; //$NON-NLS-1$
- public static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$
-
- private IJavaAnnotation fOverlay;
-
-
- public JavaMarkerAnnotation(IMarker marker) {
- super(marker);
- }
-
- /*
- * @see IJavaAnnotation#getArguments()
- */
- public String[] getArguments() {
- IMarker marker= getMarker();
- if (marker != null && marker.exists() && isProblem())
- return CorrectionEngine.getProblemArguments(marker);
- return null;
- }
-
- /*
- * @see IJavaAnnotation#getId()
- */
- public int getId() {
- IMarker marker= getMarker();
- if (marker == null || !marker.exists())
- return -1;
-
- if (isProblem())
- return marker.getAttribute(IJavaScriptModelMarker.ID, -1);
-
-// if (TASK_ANNOTATION_TYPE.equals(getAnnotationType())) {
-// try {
-// if (marker.isSubtypeOf(IJavaScriptModelMarker.TASK_MARKER)) {
-// return IProblem.Task;
-// }
-// } catch (CoreException e) {
-// JavaScriptPlugin.log(e); // should no happen, we test for marker.exists
-// }
-// }
-
- return -1;
- }
-
- /*
- * @see IJavaAnnotation#isProblem()
- */
- public boolean isProblem() {
- String type= getType();
- return WARNING_ANNOTATION_TYPE.equals(type) || ERROR_ANNOTATION_TYPE.equals(type);
- }
-
- /**
- * Overlays this annotation with the given javaAnnotation.
- *
- * @param javaAnnotation annotation that is overlaid by this annotation
- */
- public void setOverlay(IJavaAnnotation javaAnnotation) {
- if (fOverlay != null)
- fOverlay.removeOverlaid(this);
-
- fOverlay= javaAnnotation;
- if (!isMarkedDeleted())
- markDeleted(fOverlay != null);
-
- if (fOverlay != null)
- fOverlay.addOverlaid(this);
- }
-
- /*
- * @see IJavaAnnotation#hasOverlay()
- */
- public boolean hasOverlay() {
- return fOverlay != null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
- */
- public IJavaAnnotation getOverlay() {
- return fOverlay;
- }
-
- /*
- * @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
- */
- public void addOverlaid(IJavaAnnotation annotation) {
- // not supported
- }
-
- /*
- * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
- */
- public void removeOverlaid(IJavaAnnotation annotation) {
- // not supported
- }
-
- /*
- * @see IJavaAnnotation#getOverlaidIterator()
- */
- public Iterator getOverlaidIterator() {
- // not supported
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
- */
- public IJavaScriptUnit getCompilationUnit() {
- IJavaScriptElement element= JavaScriptCore.create(getMarker().getResource());
- if (element instanceof IJavaScriptUnit) {
- return (IJavaScriptUnit)element;
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation#getMarkerType()
- */
- public String getMarkerType() {
- IMarker marker= getMarker();
- if (marker == null || !marker.exists())
- return null;
-
- return MarkerUtilities.getMarkerType(getMarker());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMoveLinesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMoveLinesAction.java
deleted file mode 100644
index 5564e9de..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaMoveLinesAction.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Tom Eicher (Avaloq Evolution AG) - block selection mode
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ILineRange;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.LineRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IndentUtil.IndentResult;
-
-/**
- * Action for moving selected lines in a Java editor.
- *
- */
-public class JavaMoveLinesAction extends TextEditorAction {
-
- /**
- * State shared by the Move / Copy lines action quadruple.
- *
- */
- private static final class SharedState {
- /** The compilation unit editor that all four actions operate on. */
- public CompilationUnitEditor fEditor;
- /**
- * The indent token shared by all four actions.
- */
- public IndentResult fResult= null;
- /**
- * Set to true before modifying the document, to false after.
- */
- boolean fIsChanging= false;
-
- /** <code>true</code> if a compound move / copy is going on. */
- private boolean fEditInProgress= false;
- /** The exit strategy that will detect the ending of a compound edit */
- private final CompoundEditExitStrategy fExitStrategy;
-
- public SharedState(CompilationUnitEditor editor) {
- fEditor= editor;
- fExitStrategy= new CompoundEditExitStrategy(new String[] {ITextEditorActionDefinitionIds.MOVE_LINES_UP, ITextEditorActionDefinitionIds.MOVE_LINES_DOWN, ITextEditorActionDefinitionIds.COPY_LINES_UP, ITextEditorActionDefinitionIds.COPY_LINES_DOWN});
- fExitStrategy.addCompoundListener(new ICompoundEditListener() {
- public void endCompoundEdit() {
- SharedState.this.endCompoundEdit();
- }
- });
- }
-
- /**
- * Ends the compound change.
- */
- public void beginCompoundEdit() {
- if (fEditInProgress || fEditor == null)
- return;
-
- fEditInProgress= true;
-
- fExitStrategy.arm(fEditor.getViewer());
-
- IRewriteTarget target= (IRewriteTarget)fEditor.getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.beginCompoundChange();
- }
- }
- /**
- * Ends the compound change.
- */
- public void endCompoundEdit() {
- if (!fEditInProgress || fEditor == null)
- return;
-
- fExitStrategy.disarm();
-
- IRewriteTarget target= (IRewriteTarget)fEditor.getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.endCompoundChange();
- }
-
- fResult= null;
- fEditInProgress= false;
- }
- }
-
- /* keys */
-
- /** Key for status message upon illegal move. <p>Value {@value}</p> */
-
- /* state variables - define what this action does */
-
- /** <code>true</code> if lines are shifted upwards, <code>false</code> otherwise. */
- private final boolean fUpwards;
- /** <code>true</code> if lines are to be copied instead of moved. */
- private final boolean fCopy;
- /** The shared state of the move/copy action quadruple. */
- private final SharedState fSharedState;
-
- /**
- * Creates the quadruple of move and copy actions. The returned array contains
- * the actions in the following order:
- * [0] move up
- * [1] move down
- * [2] copy up (duplicate)
- * [3] copy down (duplicate & select)
- * @param bundle the resource bundle
- * @param editor the editor
- * @return the quadruple of actions
- */
- public static JavaMoveLinesAction[] createMoveCopyActionSet(ResourceBundle bundle, CompilationUnitEditor editor) {
- SharedState state= new SharedState(editor);
- JavaMoveLinesAction[] actions= new JavaMoveLinesAction[4];
- actions[0]= new JavaMoveLinesAction(bundle, "Editor.MoveLinesUp.", true, false, state); //$NON-NLS-1$
- actions[1]= new JavaMoveLinesAction(bundle, "Editor.MoveLinesDown.", false, false, state); //$NON-NLS-1$
- actions[2]= new JavaMoveLinesAction(bundle, "Editor.CopyLineUp.", true, true, state); //$NON-NLS-1$
- actions[3]= new JavaMoveLinesAction(bundle, "Editor.CopyLineDown.", false, true, state); //$NON-NLS-1$
- return actions;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.TextEditorAction#setEditor(org.eclipse.ui.texteditor.ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
- Assert.isTrue(editor instanceof CompilationUnitEditor);
- super.setEditor(editor);
- if (fSharedState != null)
- fSharedState.fEditor= (CompilationUnitEditor) editor;
- }
-
- /**
- * Creates and initializes the action for the given text editor.
- * The action configures its visual representation from the given resource
- * bundle.
- *
- * @param bundle the resource bundle
- * @param prefix a prefix to be prepended to the various resource keys
- * (described in <code>ResourceAction</code> constructor), or <code>null</code> if none
- * @param upwards <code>true</code>if the selected lines should be moved upwards,
- * <code>false</code> if downwards
- * @param copy if <code>true</code>, the action will copy lines instead of moving them
- * @param state the shared state
- * @see TextEditorAction#TextEditorAction(ResourceBundle, String, ITextEditor)
- */
- private JavaMoveLinesAction(ResourceBundle bundle, String prefix, boolean upwards, boolean copy, SharedState state) {
- super(bundle, prefix, state.fEditor);
- fUpwards= upwards;
- fCopy= copy;
- fSharedState= state;
- update();
- }
-
- /**
- * Checks if <code>selection</code> is contained by the visible region of <code>viewer</code>.
- * As a special case, a selection is considered contained even if it extends over the visible
- * region, but the extension stays on a partially contained line and contains only white space.
- *
- * @param selection the selection to be checked
- * @param viewer the viewer displaying a visible region of <code>selection</code>'s document.
- * @return <code>true</code>, if <code>selection</code> is contained, <code>false</code> otherwise.
- */
- private boolean containedByVisibleRegion(ITextSelection selection, ISourceViewer viewer) {
- int min= selection.getOffset();
- int max= min + selection.getLength();
- IDocument document= viewer.getDocument();
-
- IRegion visible;
- if (viewer instanceof ITextViewerExtension5)
- visible= ((ITextViewerExtension5) viewer).getModelCoverage();
- else
- visible= viewer.getVisibleRegion();
-
- int visOffset= visible.getOffset();
- try {
- if (visOffset > min) {
- if (document.getLineOfOffset(visOffset) != selection.getStartLine())
- return false;
- if (!isWhitespace(document.get(min, visOffset - min))) {
- showStatus();
- return false;
- }
- }
- int visEnd= visOffset + visible.getLength();
- if (visEnd < max) {
- if (document.getLineOfOffset(visEnd) != selection.getEndLine())
- return false;
- if (!isWhitespace(document.get(visEnd, max - visEnd))) {
- showStatus();
- return false;
- }
- }
- return true;
- } catch (BadLocationException e) {
- }
- return false;
- }
-
- /**
- * Given a selection on a document, computes the lines fully or partially covered by
- * <code>selection</code>. A line in the document is considered covered if
- * <code>selection</code> comprises any characters on it, including the terminating delimiter.
- * <p>Note that the last line in a selection is not considered covered if the selection only
- * comprises the line delimiter at its beginning (that is considered part of the second last
- * line).
- * As a special case, if the selection is empty, a line is considered covered if the caret is
- * at any position in the line, including between the delimiter and the start of the line. The
- * line containing the delimiter is not considered covered in that case.
- * </p>
- *
- * @param document the document <code>selection</code> refers to
- * @param selection a selection on <code>document</code>
- * @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
- * @return a selection describing the range of lines (partially) covered by
- * <code>selection</code>, without any terminating line delimiters
- * @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
- */
- private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ISourceViewer viewer) throws BadLocationException {
- int low= document.getLineOffset(selection.getStartLine());
- int endLine= selection.getEndLine();
- int high= document.getLineOffset(endLine) + document.getLineLength(endLine);
-
- // get everything up to last line without its delimiter
- String delim= document.getLineDelimiter(endLine);
- if (delim != null)
- high -= delim.length();
-
- return new TextSelection(document, low, high - low);
- }
-
- /**
- * Computes the region of the skipped line given the text block to be moved. If
- * <code>fUpwards</code> is <code>true</code>, the line above <code>selection</code>
- * is selected, otherwise the line below.
- *
- * @param document the document <code>selection</code> refers to
- * @param selection the selection on <code>document</code> that will be moved.
- * @return the region comprising the line that <code>selection</code> will be moved over, without its terminating delimiter.
- */
- private ITextSelection getSkippedLine(IDocument document, ITextSelection selection) {
- int skippedLineN= (fUpwards ? selection.getStartLine() - 1 : selection.getEndLine() + 1);
- if (skippedLineN > document.getNumberOfLines() || (!fCopy && (skippedLineN < 0 || skippedLineN == document.getNumberOfLines())))
- return null;
- try {
- if (fCopy && skippedLineN == -1)
- skippedLineN= 0;
- IRegion line= document.getLineInformation(skippedLineN);
- return new TextSelection(document, line.getOffset(), line.getLength());
- } catch (BadLocationException e) {
- // only happens on concurrent modifications
- return null;
- }
- }
-
- /**
- * Checks for white space in a string.
- *
- * @param string the string to be checked or <code>null</code>
- * @return <code>true</code> if <code>string</code> contains only white space or is
- * <code>null</code>, <code>false</code> otherwise
- */
- private boolean isWhitespace(String string) {
- return string == null ? true : string.trim().length() == 0;
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void runWithEvent(Event event) {
-
- // get involved objects
- if (fSharedState.fEditor == null)
- return;
-
- if (!validateEditorInputState())
- return;
-
- ISourceViewer viewer= fSharedState.fEditor.getViewer();
- if (viewer == null)
- return;
-
- IDocument document= viewer.getDocument();
- if (document == null)
- return;
-
- StyledText widget= viewer.getTextWidget();
- if (widget == null)
- return;
-
- // get selection
- ITextSelection sel= (ITextSelection) viewer.getSelectionProvider().getSelection();
- if (sel.isEmpty())
- return;
-
- ITextSelection skippedLine= getSkippedLine(document, sel);
- if (skippedLine == null)
- return;
-
- try {
-
- ITextSelection movingArea= getMovingSelection(document, sel, viewer);
-
- // if either the skipped line or the moving lines are outside the widget's
- // visible area, bail out
- if (!containedByVisibleRegion(movingArea, viewer) || !containedByVisibleRegion(skippedLine, viewer))
- return;
-
- // get the content to be moved around: the moving (selected) area and the skipped line
- String moving= movingArea.getText();
- String skipped= skippedLine.getText();
- if (moving == null || skipped == null || document.getLength() == 0)
- return;
-
- String delim;
- String insertion;
- int offset;
- if (fUpwards) {
- delim= document.getLineDelimiter(skippedLine.getEndLine());
- if (fCopy) {
- delim= TextUtilities.getDefaultLineDelimiter(document);
- insertion= moving + delim;
- offset= movingArea.getOffset();
- } else {
- Assert.isNotNull(delim);
- insertion= moving + delim + skipped;
- offset= skippedLine.getOffset();
- }
- } else {
- delim= document.getLineDelimiter(movingArea.getEndLine());
- if (fCopy) {
- if (delim == null) {
- delim= TextUtilities.getDefaultLineDelimiter(document);
- insertion= delim + moving;
- } else
- insertion= moving + delim;
- offset= skippedLine.getOffset();
- } else {
- Assert.isNotNull(delim);
- insertion= skipped + delim + moving;
- offset= movingArea.getOffset();
- }
- }
- int lenght= fCopy ? 0 : insertion.length();
-
- // modify the document
- ILineRange selectionBefore= getLineRange(document, movingArea);
-
- if (fCopy)
- fSharedState.endCompoundEdit();
- fSharedState.beginCompoundEdit();
- fSharedState.fIsChanging= true;
-
- document.replace(offset, lenght, insertion);
-
- ILineRange selectionAfter;
- if (fUpwards && fCopy)
- selectionAfter= selectionBefore;
- else if (fUpwards)
- selectionAfter= new LineRange(selectionBefore.getStartLine() - 1, selectionBefore.getNumberOfLines());
- else if (fCopy)
- selectionAfter= new LineRange(selectionBefore.getStartLine() + selectionBefore.getNumberOfLines(), selectionBefore.getNumberOfLines());
- else
- selectionAfter= new LineRange(selectionBefore.getStartLine() + 1, selectionBefore.getNumberOfLines());
-
- fSharedState.fResult= IndentUtil.indentLines(document, selectionAfter, getProject(), fSharedState.fResult);
-
- // move the selection along
- IRegion region= getRegion(document, selectionAfter);
- selectAndReveal(viewer, region.getOffset(), region.getLength());
-
- } catch (BadLocationException x) {
- // won't happen without concurrent modification - bail out
- return;
- } finally {
- fSharedState.fIsChanging= false;
- if (fCopy)
- fSharedState.endCompoundEdit();
- }
- }
-
- private IJavaScriptProject getProject() {
- IEditorInput editorInput= fSharedState.fEditor.getEditorInput();
- IJavaScriptUnit unit= JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput);
- if (unit != null)
- return unit.getJavaScriptProject();
- return null;
- }
-
- private ILineRange getLineRange(IDocument document, ITextSelection selection) throws BadLocationException {
- final int offset= selection.getOffset();
- int startLine= document.getLineOfOffset(offset);
- int endOffset= offset + selection.getLength();
- int endLine= document.getLineOfOffset(endOffset);
- final int nLines= endLine - startLine + 1;
- return new LineRange(startLine, nLines);
- }
-
- private IRegion getRegion(IDocument document, ILineRange lineRange) throws BadLocationException {
- final int startLine= lineRange.getStartLine();
- int offset= document.getLineOffset(startLine);
- final int numberOfLines= lineRange.getNumberOfLines();
- if (numberOfLines < 1)
- return new Region(offset, 0);
- int endLine = startLine + numberOfLines - 1;
- int endOffset;
- if (fSharedState.fEditor.isBlockSelectionModeEnabled()) {
- // in column mode, don't select the last delimiter as we count an
- // empty selected line
- IRegion endLineInfo = document.getLineInformation(endLine);
- endOffset = endLineInfo.getOffset() + endLineInfo.getLength();
- }
- else {
- endOffset = document.getLineOffset(endLine) + document.getLineLength(endLine);
- }
- return new Region(offset, endOffset - offset);
- }
-
- /**
- * Performs similar to AbstractTextEditor.selectAndReveal, but does not update
- * the viewers highlight area.
- *
- * @param viewer the viewer that we want to select on
- * @param offset the offset of the selection
- * @param length the length of the selection
- */
- private void selectAndReveal(ITextViewer viewer, int offset, int length) {
- // invert selection to avoid jumping to the end of the selection in st.showSelection()
- viewer.setSelectedRange(offset + length, -length);
- //viewer.revealRange(offset, length); // will trigger jumping
- StyledText st= viewer.getTextWidget();
- if (st != null)
- st.showSelection(); // only minimal scrolling
- }
-
- /**
- * Displays information in the status line why a line move is not possible
- */
- private void showStatus() {
- IEditorStatusLine status= (IEditorStatusLine) fSharedState.fEditor.getAdapter(IEditorStatusLine.class);
- if (status == null)
- return;
- status.setMessage(false, JavaEditorMessages.Editor_MoveLines_IllegalMove_status, null);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- super.update();
-
- if (isEnabled())
- setEnabled(canModifyEditor());
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java
deleted file mode 100644
index affa1c73..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java
+++ /dev/null
@@ -1,1401 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Vector;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.IPostSelectionProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.ui.model.WorkbenchAdapter;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.IShowInTarget;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.AbstractToggleLinkingAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.CategoryFilterActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.dnd.DelegatingDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SourcePositionComparator;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.CustomFiltersActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.MemberFilterActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-
-/**
- * The content outline page of the Java editor. The viewer implements a proprietary
- * update mechanism based on Java model deltas. It does not react on domain changes.
- * It is specified to show the content of ICompilationUnits and IClassFiles.
- * Publishes its context menu under <code>JavaScriptPlugin.getDefault().getPluginId() + ".outline"</code>.
- */
-public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
-
- static Object[] NO_CHILDREN= new Object[0];
-
- /**
- * The element change listener of the java outline viewer.
- * @see IElementChangedListener
- */
- protected class ElementChangedListener implements IElementChangedListener {
-
- public void elementChanged(final ElementChangedEvent e) {
-
- if (getControl() == null)
- return;
-
- Display d= getControl().getDisplay();
- if (d != null) {
- d.asyncExec(new Runnable() {
- public void run() {
- IJavaScriptUnit cu= (IJavaScriptUnit) fInput;
- IJavaScriptElement base= cu;
- if (fTopLevelTypeOnly) {
- base= cu.findPrimaryType();
- if (base == null) {
- if (fOutlineViewer != null)
- fOutlineViewer.refresh(true);
- return;
- }
- }
- IJavaScriptElementDelta delta= findElement(base, e.getDelta());
- if (delta != null && fOutlineViewer != null) {
- fOutlineViewer.reconcile(delta);
- }
- }
- });
- }
- }
-
- private boolean isPossibleStructuralChange(IJavaScriptElementDelta cuDelta) {
- if (cuDelta.getKind() != IJavaScriptElementDelta.CHANGED) {
- return true; // add or remove
- }
- int flags= cuDelta.getFlags();
- if ((flags & IJavaScriptElementDelta.F_CHILDREN) != 0) {
- return true;
- }
- return (flags & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_FINE_GRAINED)) == IJavaScriptElementDelta.F_CONTENT;
- }
-
- protected IJavaScriptElementDelta findElement(IJavaScriptElement unit, IJavaScriptElementDelta delta) {
-
- if (delta == null || unit == null)
- return null;
-
- IJavaScriptElement element= delta.getElement();
-
- if (unit.equals(element)) {
- if (isPossibleStructuralChange(delta)) {
- return delta;
- }
- return null;
- }
-
-
- if (element.getElementType() > IJavaScriptElement.CLASS_FILE)
- return null;
-
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- if (children == null || children.length == 0)
- return null;
-
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElementDelta d= findElement(unit, children[i]);
- if (d != null)
- return d;
- }
-
- return null;
- }
- }
-
- static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return JavaEditorMessages.JavaOutlinePage_error_NoTopLevelType;
- }
-
- /*
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
- */
- public Object getAdapter(Class clas) {
- if (clas == IWorkbenchAdapter.class)
- return this;
- return null;
- }
- }
-
- /**
- * Content provider for the children of an IJavaScriptUnit or
- * an IClassFile
- * @see ITreeContentProvider
- */
- protected class ChildrenProvider implements ITreeContentProvider {
-
- private Object[] NO_CLASS= new Object[] {new NoClassElement()};
- private ElementChangedListener fListener;
-
- protected boolean matches(IJavaScriptElement element) {
- if (element.getElementType() == IJavaScriptElement.METHOD) {
- String name= element.getElementName();
- return (name != null && name.indexOf('<') >= 0);
- }
-
- //@GINO: Anonymous Filter top level anonymous
- if (element.getElementType() == IJavaScriptElement.TYPE && element.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT ) {
-
- IType type = (IType)element;
- try {
- return type.isAnonymous();
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return false;
- }
-
- protected IJavaScriptElement[] filter(IJavaScriptElement[] children) {
- boolean initializers= false;
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i])) {
- initializers= true;
- break;
- }
- }
-
- if (!initializers)
- return children;
-
- Vector v= new Vector();
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i]))
- continue;
- v.addElement(children[i]);
- }
-
- IJavaScriptElement[] result= new IJavaScriptElement[v.size()];
- v.copyInto(result);
- return result;
- }
-
- public Object[] getChildren(Object parent) {
- if (parent instanceof IParent) {
- IParent c= (IParent) parent;
- try {
- return filter(c.getChildren());
- } catch (JavaScriptModelException x) {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341
- // don't log NotExist exceptions as this is a valid case
- // since we might have been posted and the element
- // removed in the meantime.
- if (JavaScriptPlugin.isDebug() || !x.isDoesNotExist())
- JavaScriptPlugin.log(x);
- }
- }
- return NO_CHILDREN;
- }
-
- public Object[] getElements(Object parent) {
- if (fTopLevelTypeOnly) {
- if (parent instanceof ITypeRoot) {
- try {
- IType type= ((ITypeRoot) parent).findPrimaryType();
- return type != null ? type.getChildren() : NO_CLASS;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return getChildren(parent);
- }
-
- public Object getParent(Object child) {
- if (child instanceof IJavaScriptElement) {
- IJavaScriptElement e= (IJavaScriptElement) child;
- return e.getParent();
- }
- return null;
- }
-
- public boolean hasChildren(Object parent) {
- if (parent instanceof IParent) {
- IParent c= (IParent) parent;
- try {
- IJavaScriptElement[] children= filter(c.getChildren());
- return (children != null && children.length > 0);
- } catch (JavaScriptModelException x) {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341
- // don't log NotExist exceptions as this is a valid case
- // since we might have been posted and the element
- // removed in the meantime.
- if (JavaScriptPlugin.isDebug() || !x.isDoesNotExist())
- JavaScriptPlugin.log(x);
- }
- }
- return false;
- }
-
- public boolean isDeleted(Object o) {
- return false;
- }
-
- public void dispose() {
- if (fListener != null) {
- JavaScriptCore.removeElementChangedListener(fListener);
- fListener= null;
- }
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- boolean isCU= (newInput instanceof IJavaScriptUnit);
-
- if (isCU && fListener == null) {
- fListener= new ElementChangedListener();
- JavaScriptCore.addElementChangedListener(fListener);
- } else if (!isCU && fListener != null) {
- JavaScriptCore.removeElementChangedListener(fListener);
- fListener= null;
- }
- }
- }
-
- /**
- * The tree viewer used for displaying the outline.
- *
- * @see TreeViewer
- */
- protected class JavaOutlineViewer extends TreeViewer {
-
- /**
- * Indicates an item which has been reused. At the point of
- * its reuse it has been expanded. This field is used to
- * communicate between <code>internalExpandToLevel</code> and
- * <code>reuseTreeItem</code>.
- */
- private Item fReusedExpandedItem;
- private boolean fReorderedMembers;
- private boolean fForceFireSelectionChanged;
-
- public JavaOutlineViewer(Tree tree) {
- super(tree);
- setAutoExpandLevel(ALL_LEVELS);
- setUseHashlookup(true);
- }
-
- /**
- * Investigates the given element change event and if affected
- * incrementally updates the Java outline.
- *
- * @param delta the Java element delta used to reconcile the Java outline
- */
- public void reconcile(IJavaScriptElementDelta delta) {
- fReorderedMembers= false;
- fForceFireSelectionChanged= false;
- if (getComparator() == null) {
- if (fTopLevelTypeOnly
- && delta.getElement() instanceof IType
- && (delta.getKind() & IJavaScriptElementDelta.ADDED) != 0)
- {
- refresh(true);
-
- } else {
- Widget w= findItem(fInput);
- if (w != null && !w.isDisposed())
- update(w, delta);
- if (fForceFireSelectionChanged)
- fireSelectionChanged(new SelectionChangedEvent(getSite().getSelectionProvider(), this.getSelection()));
- if (fReorderedMembers) {
- refresh(false);
- fReorderedMembers= false;
- }
- }
- } else {
- // just for now
- refresh(true);
- }
- }
-
- /*
- * @see TreeViewer#internalExpandToLevel
- */
- protected void internalExpandToLevel(Widget node, int level) {
- if (node instanceof Item) {
- Item i= (Item) node;
- if (i.getData() instanceof IJavaScriptElement) {
- IJavaScriptElement je= (IJavaScriptElement) i.getData();
- if (je.getElementType() == IJavaScriptElement.IMPORT_CONTAINER || isInnerType(je)) {
- if (i != fReusedExpandedItem) {
- setExpanded(i, false);
- return;
- }
- }
- }
- }
- super.internalExpandToLevel(node, level);
- }
-
- protected void reuseTreeItem(Item item, Object element) {
-
- // remove children
- Item[] c= getChildren(item);
- if (c != null && c.length > 0) {
-
- if (getExpanded(item))
- fReusedExpandedItem= item;
-
- for (int k= 0; k < c.length; k++) {
- if (c[k].getData() != null)
- disassociate(c[k]);
- c[k].dispose();
- }
- }
-
- updateItem(item, element);
- updatePlus(item, element);
- internalExpandToLevel(item, ALL_LEVELS);
-
- fReusedExpandedItem= null;
- fForceFireSelectionChanged= true;
- }
-
- protected boolean mustUpdateParent(IJavaScriptElementDelta delta, IJavaScriptElement element) {
- if (element instanceof IFunction) {
- if ((delta.getKind() & IJavaScriptElementDelta.ADDED) != 0) {
- return false;
- }
- return "main".equals(element.getElementName()); //$NON-NLS-1$
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object)
- */
- public boolean isExpandable(Object element) {
- if (hasFilters()) {
- return getFilteredChildren(element).length > 0;
- }
- return super.isExpandable(element);
- }
-
- protected ISourceRange getSourceRange(IJavaScriptElement element) throws JavaScriptModelException {
- if (element instanceof ISourceReference)
- return ((ISourceReference) element).getSourceRange();
- if (element instanceof IMember && !(element instanceof IInitializer))
- return ((IMember) element).getNameRange();
- return null;
- }
-
- protected boolean overlaps(ISourceRange range, int start, int end) {
- return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
- }
-
- protected boolean filtered(IJavaScriptElement parent, IJavaScriptElement child) {
-
- Object[] result= new Object[] { child };
- ViewerFilter[] filters= getFilters();
- for (int i= 0; i < filters.length; i++) {
- result= filters[i].filter(this, parent, result);
- if (result.length == 0)
- return true;
- }
-
- return false;
- }
-
- protected void update(Widget w, IJavaScriptElementDelta delta) {
-
- Item item;
-
- IJavaScriptElement parent= delta.getElement();
- IJavaScriptElementDelta[] affected= delta.getAffectedChildren();
- Item[] children= getChildren(w);
-
- boolean doUpdateParent= false;
- boolean doUpdateParentsPlus= false;
-
- Vector deletions= new Vector();
- Vector additions= new Vector();
-
- for (int i= 0; i < affected.length; i++) {
- IJavaScriptElementDelta affectedDelta= affected[i];
- IJavaScriptElement affectedElement= affectedDelta.getElement();
- int status= affected[i].getKind();
-
- // find tree item with affected element
- int j;
- for (j= 0; j < children.length; j++)
- if (affectedElement.equals(children[j].getData()))
- break;
-
- if (j == children.length) {
- // remove from collapsed parent
- if ((status & IJavaScriptElementDelta.REMOVED) != 0) {
- doUpdateParentsPlus= true;
- continue;
- }
- // addition
- if ((status & IJavaScriptElementDelta.CHANGED) != 0 &&
- (affectedDelta.getFlags() & IJavaScriptElementDelta.F_MODIFIERS) != 0 &&
- !filtered(parent, affectedElement))
- {
- additions.addElement(affectedDelta);
- }
- continue;
- }
-
- item= children[j];
-
- // removed
- if ((status & IJavaScriptElementDelta.REMOVED) != 0) {
- deletions.addElement(item);
- doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
-
- // changed
- } else if ((status & IJavaScriptElementDelta.CHANGED) != 0) {
- int change= affectedDelta.getFlags();
- doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
-
- if ((change & IJavaScriptElementDelta.F_MODIFIERS) != 0) {
- if (filtered(parent, affectedElement))
- deletions.addElement(item);
- else
- updateItem(item, affectedElement);
- }
-
- if ((change & IJavaScriptElementDelta.F_CONTENT) != 0)
- updateItem(item, affectedElement);
-
- if ((change & IJavaScriptElementDelta.F_CATEGORIES) != 0)
- updateItem(item, affectedElement);
-
- if ((change & IJavaScriptElementDelta.F_CHILDREN) != 0)
- update(item, affectedDelta);
-
- if ((change & IJavaScriptElementDelta.F_REORDER) != 0)
- fReorderedMembers= true;
- }
- }
-
- // find all elements to add
- IJavaScriptElementDelta[] add= delta.getAddedChildren();
- if (additions.size() > 0) {
- IJavaScriptElementDelta[] tmp= new IJavaScriptElementDelta[add.length + additions.size()];
- System.arraycopy(add, 0, tmp, 0, add.length);
- for (int i= 0; i < additions.size(); i++)
- tmp[i + add.length]= (IJavaScriptElementDelta) additions.elementAt(i);
- add= tmp;
- }
-
- // add at the right position
- go2: for (int i= 0; i < add.length; i++) {
-
- try {
-
- IJavaScriptElement e= add[i].getElement();
- if (filtered(parent, e))
- continue go2;
-
- doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
- ISourceRange rng= getSourceRange(e);
- int start= rng.getOffset();
- int end= start + rng.getLength() - 1;
- int nameOffset= Integer.MAX_VALUE;
- if (e instanceof IField) {
- ISourceRange nameRange= ((IField) e).getNameRange();
- if (nameRange != null)
- nameOffset= nameRange.getOffset();
- }
-
- Item last= null;
- item= null;
- children= getChildren(w);
-
- for (int j= 0; j < children.length; j++) {
- item= children[j];
- IJavaScriptElement r= (IJavaScriptElement) item.getData();
-
- if (r == null) {
- // parent node collapsed and not be opened before -> do nothing
- continue go2;
- }
-
-
- try {
- rng= getSourceRange(r);
-
- // multi-field declarations always start at
- // the same offset. They also have the same
- // end offset if the field sequence is terminated
- // with a semicolon. If not, the source range
- // ends behind the identifier / initializer
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51851
- boolean multiFieldDeclaration=
- r.getElementType() == IJavaScriptElement.FIELD
- && e.getElementType() == IJavaScriptElement.FIELD
- && rng.getOffset() == start;
-
- // elements are inserted by occurrence
- // however, multi-field declarations have
- // equal source ranges offsets, therefore we
- // compare name-range offsets.
- boolean multiFieldOrderBefore= false;
- if (multiFieldDeclaration) {
- if (r instanceof IField) {
- ISourceRange nameRange= ((IField) r).getNameRange();
- if (nameRange != null) {
- if (nameRange.getOffset() > nameOffset)
- multiFieldOrderBefore= true;
- }
- }
- }
-
- if (!multiFieldDeclaration && overlaps(rng, start, end)) {
-
- // be tolerant if the delta is not correct, or if
- // the tree has been updated other than by a delta
- reuseTreeItem(item, e);
- continue go2;
-
- } else if (multiFieldOrderBefore || rng.getOffset() > start) {
-
- if (last != null && deletions.contains(last)) {
- // reuse item
- deletions.removeElement(last);
- reuseTreeItem(last, e);
- } else {
- // nothing to reuse
- createTreeItem(w, e, j);
- }
- continue go2;
- }
-
- } catch (JavaScriptModelException x) {
- // stumbled over deleted element
- }
-
- last= item;
- }
-
- // add at the end of the list
- if (last != null && deletions.contains(last)) {
- // reuse item
- deletions.removeElement(last);
- reuseTreeItem(last, e);
- } else {
- // nothing to reuse
- createTreeItem(w, e, -1);
- }
-
- } catch (JavaScriptModelException x) {
- // the element to be added is not present -> don't add it
- }
- }
-
-
- // remove items which haven't been reused
- Enumeration e= deletions.elements();
- while (e.hasMoreElements()) {
- item= (Item) e.nextElement();
- disassociate(item);
- item.dispose();
- }
-
- if (doUpdateParent)
- updateItem(w, delta.getElement());
- if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item)
- updatePlus((Item)w, delta.getElement());
- }
-
-
-
- /*
- * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
- */
- protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
- Object input= getInput();
- if (event instanceof ProblemsLabelChangedEvent) {
- ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
- if (e.isMarkerChange() && input instanceof IJavaScriptUnit) {
- return; // marker changes can be ignored
- }
- }
- // look if the underlying resource changed
- Object[] changed= event.getElements();
- if (changed != null) {
- IResource resource= getUnderlyingResource();
- if (resource != null) {
- for (int i= 0; i < changed.length; i++) {
- if (changed[i] != null && changed[i].equals(resource)) {
- // change event to a full refresh
- event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
- break;
- }
- }
- }
- }
- super.handleLabelProviderChanged(event);
- }
-
- private IResource getUnderlyingResource() {
- Object input= getInput();
- if (input instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit) input;
- cu= cu.getPrimary();
- return cu.getResource();
- } else if (input instanceof IClassFile) {
- return ((IClassFile) input).getResource();
- }
- return null;
- }
-
-
- }
-
- class LexicalSortingAction extends Action {
-
- private JavaScriptElementComparator fComparator= new JavaScriptElementComparator();
- private SourcePositionComparator fSourcePositonComparator= new SourcePositionComparator();
-
- public LexicalSortingAction() {
- super();
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
- setText(JavaEditorMessages.JavaOutlinePage_Sort_label);
- JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
- setToolTipText(JavaEditorMessages.JavaOutlinePage_Sort_tooltip);
- setDescription(JavaEditorMessages.JavaOutlinePage_Sort_description);
-
- boolean checked= JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
- valueChanged(checked, false);
- }
-
- public void run() {
- valueChanged(isChecked(), true);
- }
-
- private void valueChanged(final boolean on, boolean store) {
- setChecked(on);
- BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- if (on)
- fOutlineViewer.setComparator(fComparator);
- else
- fOutlineViewer.setComparator(fSourcePositonComparator);
- }
- });
-
- if (store)
- JavaScriptPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
- }
- }
-
- class ClassOnlyAction extends Action {
-
- public ClassOnlyAction() {
- super();
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
- setText(JavaEditorMessages.JavaOutlinePage_GoIntoTopLevelType_label);
- setToolTipText(JavaEditorMessages.JavaOutlinePage_GoIntoTopLevelType_tooltip);
- setDescription(JavaEditorMessages.JavaOutlinePage_GoIntoTopLevelType_description);
- JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
- setTopLevelTypeOnly(showclass);
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- setTopLevelTypeOnly(!fTopLevelTypeOnly);
- }
-
- private void setTopLevelTypeOnly(boolean show) {
- fTopLevelTypeOnly= show;
- setChecked(show);
- fOutlineViewer.refresh(false);
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
- }
- }
-
- private class CollapseAllAction extends Action {
- JavaOutlineViewer fJavaOutlineViewer;
- CollapseAllAction(JavaOutlineViewer viewer) {
- super(PackagesMessages.CollapseAllAction_label);
- setDescription(PackagesMessages.CollapseAllAction_description);
- setToolTipText(PackagesMessages.CollapseAllAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "collapseall.gif"); //$NON-NLS-1$
-
- fJavaOutlineViewer= viewer;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.COLLAPSE_ALL_ACTION);
- }
-
- public void run() {
- fJavaOutlineViewer.collapseAll();
- }
- }
-
-
- /**
- * This action toggles whether this Java Outline page links
- * its selection to the active editor.
- *
- *
- */
- public class ToggleLinkingAction extends AbstractToggleLinkingAction {
-
- JavaOutlinePage fJavaOutlinePage;
-
- /**
- * Constructs a new action.
- *
- * @param outlinePage the Java outline page
- */
- public ToggleLinkingAction(JavaOutlinePage outlinePage) {
- boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
- setChecked(isLinkingEnabled);
- fJavaOutlinePage= outlinePage;
- }
-
- /**
- * Runs the action.
- */
- public void run() {
- PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
- if (isChecked() && fEditor != null)
- fEditor.synchronizeOutlinePage(fEditor.computeHighlightRangeSourceReference(), false);
- }
-
- }
-
- /**
- * Empty selection provider.
- *
- *
- */
- private static final class EmptySelectionProvider implements ISelectionProvider {
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- }
- public ISelection getSelection() {
- return StructuredSelection.EMPTY;
- }
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- }
- public void setSelection(ISelection selection) {
- }
- }
-
-
- /** A flag to show contents of top level type only */
- private boolean fTopLevelTypeOnly;
-
- private IJavaScriptElement fInput;
- private String fContextMenuID;
- private Menu fMenu;
- private JavaOutlineViewer fOutlineViewer;
- private JavaEditor fEditor;
-
- private MemberFilterActionGroup fMemberFilterActionGroup;
-
- private ListenerList fSelectionChangedListeners= new ListenerList(ListenerList.IDENTITY);
- private ListenerList fPostSelectionChangedListeners= new ListenerList(ListenerList.IDENTITY);
- private Hashtable fActions= new Hashtable();
-
- private TogglePresentationAction fTogglePresentation;
-
- private ToggleLinkingAction fToggleLinkingAction;
-
- private CompositeActionGroup fActionGroups;
-
- private IPropertyChangeListener fPropertyChangeListener;
- /**
- * Custom filter action group.
- *
- */
- private CustomFiltersActionGroup fCustomFiltersActionGroup;
- /**
- * Category filter action group.
- *
- */
- private CategoryFilterActionGroup fCategoryFilterActionGroup;
-
- public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
- super();
-
- Assert.isNotNull(editor);
-
- fContextMenuID= contextMenuID;
- fEditor= editor;
-
- fTogglePresentation= new TogglePresentationAction();
- fTogglePresentation.setEditor(editor);
-
- fPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doPropertyChange(event);
- }
- };
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
- }
-
- /* (non-Javadoc)
- * Method declared on Page
- */
- public void init(IPageSite pageSite) {
- super.init(pageSite);
- }
-
- private void doPropertyChange(PropertyChangeEvent event) {
- if (fOutlineViewer != null) {
- if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
- fOutlineViewer.refresh(false);
- }
- }
- }
-
- /*
- * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
- */
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- if (fOutlineViewer != null)
- fOutlineViewer.addSelectionChangedListener(listener);
- else
- fSelectionChangedListeners.add(listener);
- }
-
- /*
- * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
- */
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- if (fOutlineViewer != null)
- fOutlineViewer.removeSelectionChangedListener(listener);
- else
- fSelectionChangedListeners.remove(listener);
- }
-
- /*
- * @see ISelectionProvider#setSelection(ISelection)
- */
- public void setSelection(ISelection selection) {
- if (fOutlineViewer != null)
- fOutlineViewer.setSelection(selection);
- }
-
- /*
- * @see ISelectionProvider#getSelection()
- */
- public ISelection getSelection() {
- if (fOutlineViewer == null)
- return StructuredSelection.EMPTY;
- return fOutlineViewer.getSelection();
- }
-
- /*
- * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
- if (fOutlineViewer != null)
- fOutlineViewer.addPostSelectionChangedListener(listener);
- else
- fPostSelectionChangedListeners.add(listener);
- }
-
- /*
- * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
- if (fOutlineViewer != null)
- fOutlineViewer.removePostSelectionChangedListener(listener);
- else
- fPostSelectionChangedListeners.remove(listener);
- }
-
- private void registerToolbarActions(IActionBars actionBars) {
- IToolBarManager toolBarManager= actionBars.getToolBarManager();
- toolBarManager.add(new LexicalSortingAction());
-
- fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "org.eclipse.wst.jsdt.ui.JavaOutlinePage"); //$NON-NLS-1$
- fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
-
- fCustomFiltersActionGroup.fillActionBars(actionBars);
-
- IMenuManager viewMenuManager= actionBars.getMenuManager();
- viewMenuManager.add(new Separator("EndFilterGroup")); //$NON-NLS-1$
-
- fToggleLinkingAction= new ToggleLinkingAction(this);
- // viewMenuManager.add(new ClassOnlyAction());
- viewMenuManager.add(fToggleLinkingAction);
- toolBarManager.add(new CollapseAllAction(getOutlineViewer()));
-
- fCategoryFilterActionGroup= new CategoryFilterActionGroup(fOutlineViewer, "org.eclipse.wst.jsdt.ui.JavaOutlinePage", new IJavaScriptElement[] {fInput}); //$NON-NLS-1$
- fCategoryFilterActionGroup.contributeToViewMenu(viewMenuManager);
- }
-
- /*
- * @see IPage#createControl
- */
- public void createControl(Composite parent) {
-
- Tree tree= new Tree(parent, SWT.MULTI);
-
- AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
- AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.ALL_CATEGORY,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
- );
-
- fOutlineViewer= new JavaOutlineViewer(tree);
- ColoredViewersManager.install(fOutlineViewer);
- initDragAndDrop();
- fOutlineViewer.setContentProvider(new ChildrenProvider());
- fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
-
- Object[] listeners= fSelectionChangedListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- fSelectionChangedListeners.remove(listeners[i]);
- fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
- }
-
- listeners= fPostSelectionChangedListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- fPostSelectionChangedListeners.remove(listeners[i]);
- fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
- }
-
- MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
- manager.setRemoveAllWhenShown(true);
- manager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager m) {
- contextMenuAboutToShow(m);
- }
- });
- fMenu= manager.createContextMenu(tree);
- tree.setMenu(fMenu);
-
- IPageSite site= getSite();
- site.registerContextMenu(JavaScriptPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
-
- updateSelectionProvider(site);
-
- // we must create the groups after we have set the selection provider to the site
- fActionGroups= new CompositeActionGroup(new ActionGroup[] {
- new OpenViewActionGroup(this),
- new CCPActionGroup(this),
- new GenerateActionGroup(this),
- new RefactorActionGroup(this),
- new JavaSearchActionGroup(this)});
-
- // register global actions
- IActionBars actionBars= site.getActionBars();
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fEditor.getAction(ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fEditor.getAction(ITextEditorActionConstants.REDO));
-
- IAction action= fEditor.getAction(ITextEditorActionConstants.NEXT);
- actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, action);
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, action);
- action= fEditor.getAction(ITextEditorActionConstants.PREVIOUS);
- actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, action);
- actionBars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, action);
-
- actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation);
-
- fActionGroups.fillActionBars(actionBars);
-
- IStatusLineManager statusLineManager= actionBars.getStatusLineManager();
- if (statusLineManager != null) {
- StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
- fOutlineViewer.addPostSelectionChangedListener(updater);
- }
- // Custom filter group
- fCustomFiltersActionGroup= new CustomFiltersActionGroup("org.eclipse.wst.jsdt.ui.JavaOutlinePage", fOutlineViewer); //$NON-NLS-1$
-
- registerToolbarActions(actionBars);
-
- fOutlineViewer.setInput(fInput);
- }
-
- /*
- *
- */
- private void updateSelectionProvider(IPageSite site) {
- ISelectionProvider provider= fOutlineViewer;
- if (fInput != null) {
- IJavaScriptUnit cu= (IJavaScriptUnit)fInput.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null && !JavaModelUtil.isPrimary(cu))
- provider= new EmptySelectionProvider();
- }
- site.setSelectionProvider(provider);
- }
-
- public void dispose() {
-
- if (fEditor == null)
- return;
-
- if (fMemberFilterActionGroup != null) {
- fMemberFilterActionGroup.dispose();
- fMemberFilterActionGroup= null;
- }
-
- if (fCategoryFilterActionGroup != null) {
- fCategoryFilterActionGroup.dispose();
- fCategoryFilterActionGroup= null;
- }
-
- if (fCustomFiltersActionGroup != null) {
- fCustomFiltersActionGroup.dispose();
- fCustomFiltersActionGroup= null;
- }
-
-
- fEditor.outlinePageClosed();
- fEditor= null;
-
- fSelectionChangedListeners.clear();
- fSelectionChangedListeners= null;
-
- fPostSelectionChangedListeners.clear();
- fPostSelectionChangedListeners= null;
-
- if (fPropertyChangeListener != null) {
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- fPropertyChangeListener= null;
- }
-
- if (fMenu != null && !fMenu.isDisposed()) {
- fMenu.dispose();
- fMenu= null;
- }
-
- if (fActionGroups != null)
- fActionGroups.dispose();
-
- fTogglePresentation.setEditor(null);
-
- fOutlineViewer= null;
-
- super.dispose();
- }
-
- public Control getControl() {
- if (fOutlineViewer != null)
- return fOutlineViewer.getControl();
- return null;
- }
-
- public void setInput(IJavaScriptElement inputElement) {
- fInput= inputElement;
- if (fOutlineViewer != null) {
- fOutlineViewer.setInput(fInput);
- updateSelectionProvider(getSite());
- }
- if (fCategoryFilterActionGroup != null)
- fCategoryFilterActionGroup.setInput(new IJavaScriptElement[] {fInput});
- }
-
- public void select(ISourceReference reference) {
- if (fOutlineViewer != null) {
-
- ISelection s= fOutlineViewer.getSelection();
- if (s instanceof IStructuredSelection) {
- IStructuredSelection ss= (IStructuredSelection) s;
- List elements= ss.toList();
- if (!elements.contains(reference)) {
- s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
- fOutlineViewer.setSelection(s, true);
- }
- }
- }
- }
-
- public void setAction(String actionID, IAction action) {
- Assert.isNotNull(actionID);
- if (action == null)
- fActions.remove(actionID);
- else
- fActions.put(actionID, action);
- }
-
- public IAction getAction(String actionID) {
- Assert.isNotNull(actionID);
- return (IAction) fActions.get(actionID);
- }
-
- /*
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInSource.class) {
- return getShowInSource();
- }
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES };
- }
-
- };
- }
- if (key == IShowInTarget.class) {
- return getShowInTarget();
- }
-
- return null;
- }
-
- /**
- * Convenience method to add the action installed under the given actionID to the
- * specified group of the menu.
- *
- * @param menu the menu manager
- * @param group the group to which to add the action
- * @param actionID the ID of the new action
- */
- protected void addAction(IMenuManager menu, String group, String actionID) {
- IAction action= getAction(actionID);
- if (action != null) {
- if (action instanceof IUpdate)
- ((IUpdate) action).update();
-
- if (action.isEnabled()) {
- IMenuManager subMenu= menu.findMenuUsingPath(group);
- if (subMenu != null)
- subMenu.add(action);
- else
- menu.appendToGroup(group, action);
- }
- }
- }
-
- protected void contextMenuAboutToShow(IMenuManager menu) {
-
- JavaScriptPlugin.createStandardGroups(menu);
-
- IStructuredSelection selection= (IStructuredSelection)getSelection();
- fActionGroups.setContext(new ActionContext(selection));
- fActionGroups.fillContextMenu(menu);
- }
-
- /*
- * @see Page#setFocus()
- */
- public void setFocus() {
- if (fOutlineViewer != null)
- fOutlineViewer.getControl().setFocus();
- }
-
- /**
- * Checks whether a given Java element is an inner type.
- *
- * @param element the java element
- * @return <code>true</code> iff the given element is an inner type
- */
- private boolean isInnerType(IJavaScriptElement element) {
-
- if (element != null && element.getElementType() == IJavaScriptElement.TYPE) {
- IType type= (IType)element;
- try {
- return type.isMember();
- } catch (JavaScriptModelException e) {
- IJavaScriptElement parent= type.getParent();
- if (parent != null) {
- int parentElementType= parent.getElementType();
- return (parentElementType != IJavaScriptElement.JAVASCRIPT_UNIT && parentElementType != IJavaScriptElement.CLASS_FILE);
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns the <code>IShowInSource</code> for this view.
- *
- * @return the {@link IShowInSource}
- */
- protected IShowInSource getShowInSource() {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- return new ShowInContext(
- null,
- getSite().getSelectionProvider().getSelection());
- }
- };
- }
-
- /**
- * Returns the <code>IShowInTarget</code> for this view.
- *
- * @return the {@link IShowInTarget}
- */
- protected IShowInTarget getShowInTarget() {
- return new IShowInTarget() {
- public boolean show(ShowInContext context) {
- ISelection sel= context.getSelection();
- if (sel instanceof ITextSelection) {
- ITextSelection tsel= (ITextSelection) sel;
- int offset= tsel.getOffset();
- IJavaScriptElement element= fEditor.getElementAt(offset);
- if (element != null) {
- setSelection(new StructuredSelection(element));
- return true;
- }
- } else if (sel instanceof IStructuredSelection) {
- setSelection(sel);
- return true;
- }
- return false;
- }
- };
- }
-
- private void initDragAndDrop() {
- int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
- Transfer[] transfers= new Transfer[] {
- LocalSelectionTransfer.getInstance()
- };
-
- // Drop Adapter
- TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
- new SelectionTransferDropAdapter(fOutlineViewer)
- };
- fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
-
- // Drag Adapter
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(fOutlineViewer)
- };
- fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
- }
-
- /**
- * Returns whether only the contents of the top level type is to be shown.
- *
- * @return <code>true</code> if only the contents of the top level type is to be shown.
- *
- */
- protected final boolean isTopLevelTypeOnly() {
- return fTopLevelTypeOnly;
- }
-
- /**
- * Returns the <code>JavaOutlineViewer</code> of this view.
- *
- * @return the {@link JavaOutlineViewer}
- *
- */
- protected final JavaOutlineViewer getOutlineViewer() {
- return fOutlineViewer;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectAnnotationRulerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectAnnotationRulerAction.java
deleted file mode 100644
index e702726b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectAnnotationRulerAction.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.Iterator;
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.IVerticalRulerInfo;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.ui.texteditor.SelectMarkerRulerAction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.AssistAnnotation;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Action which gets triggered when selecting (annotations) in the vertical ruler.
- *
- * <p>
- * Was originally called >code>JavaSelectMarkerRulerAction</code>.
- * </p>
- */
-public class JavaSelectAnnotationRulerAction extends SelectMarkerRulerAction {
-
- private ITextEditor fTextEditor;
- private Position fPosition;
- private Annotation fAnnotation;
- private AnnotationPreferenceLookup fAnnotationPreferenceLookup;
- private IPreferenceStore fStore;
- private boolean fHasCorrection;
- private ResourceBundle fBundle;
-
- public JavaSelectAnnotationRulerAction(ResourceBundle bundle, String prefix, ITextEditor editor, IVerticalRulerInfo ruler) {
- super(bundle, prefix, editor, ruler);
- fBundle= bundle;
- fTextEditor= editor;
-
- fAnnotationPreferenceLookup= EditorsUI.getAnnotationPreferenceLookup();
- fStore= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION);
- }
-
- public void run() {
- if (fStore.getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
- return;
-
- runWithEvent(null);
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#runWithEvent(org.eclipse.swt.widgets.Event)
- *
- */
- public void runWithEvent(Event event) {
- if (fAnnotation instanceof OverrideIndicatorManager.OverrideIndicator) {
- ((OverrideIndicatorManager.OverrideIndicator)fAnnotation).open();
- return;
- }
-
- if (fHasCorrection) {
- ITextOperationTarget operation= (ITextOperationTarget) fTextEditor.getAdapter(ITextOperationTarget.class);
- final int opCode= ISourceViewer.QUICK_ASSIST;
- if (operation != null && operation.canDoOperation(opCode)) {
- fTextEditor.selectAndReveal(fPosition.getOffset(), fPosition.getLength());
- operation.doOperation(opCode);
- }
- return;
- }
-
- super.run();
- }
-
- public void update() {
- findJavaAnnotation();
- setEnabled(true); // super.update() might change this later
-
- if (fAnnotation instanceof OverrideIndicatorManager.OverrideIndicator) {
- initialize(fBundle, "JavaSelectAnnotationRulerAction.OpenSuperImplementation."); //$NON-NLS-1$
- return;
- }
- if (fHasCorrection) {
- if (fAnnotation instanceof AssistAnnotation)
- initialize(fBundle, "JavaSelectAnnotationRulerAction.QuickAssist."); //$NON-NLS-1$
- else
- initialize(fBundle, "JavaSelectAnnotationRulerAction.QuickFix."); //$NON-NLS-1$
- return;
- }
-
- initialize(fBundle, "JavaSelectAnnotationRulerAction.GotoAnnotation."); //$NON-NLS-1$;
- super.update();
- }
-
- private void findJavaAnnotation() {
- fPosition= null;
- fAnnotation= null;
- fHasCorrection= false;
-
- AbstractMarkerAnnotationModel model= getAnnotationModel();
- IAnnotationAccessExtension annotationAccess= getAnnotationAccessExtension();
-
- IDocument document= getDocument();
- if (model == null)
- return ;
-
- boolean hasAssistLightbulb= fStore.getBoolean(PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB);
-
- Iterator iter= model.getAnnotationIterator();
- int layer= Integer.MIN_VALUE;
-
- while (iter.hasNext()) {
- Annotation annotation= (Annotation) iter.next();
- if (annotation.isMarkedDeleted())
- continue;
-
- int annotationLayer= layer;
- if (annotationAccess != null) {
- annotationLayer= annotationAccess.getLayer(annotation);
- if (annotationLayer < layer)
- continue;
- }
-
- Position position= model.getPosition(annotation);
- if (!includesRulerLine(position, document))
- continue;
-
- boolean isReadOnly= fTextEditor instanceof ITextEditorExtension && ((ITextEditorExtension)fTextEditor).isEditorInputReadOnly();
- if (!isReadOnly
- && (
- ((hasAssistLightbulb && annotation instanceof AssistAnnotation)
- || JavaCorrectionProcessor.hasCorrections(annotation)))) {
- fPosition= position;
- fAnnotation= annotation;
- fHasCorrection= true;
- layer= annotationLayer;
- continue;
- } else {
- AnnotationPreference preference= fAnnotationPreferenceLookup.getAnnotationPreference(annotation);
- if (preference == null)
- continue;
-
- String key= preference.getVerticalRulerPreferenceKey();
- if (key == null)
- continue;
-
- if (fStore.getBoolean(key)) {
- fPosition= position;
- fAnnotation= annotation;
- fHasCorrection= false;
- layer= annotationLayer;
- }
- }
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectMarkerRulerAction2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectMarkerRulerAction2.java
deleted file mode 100644
index fd6cd759..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectMarkerRulerAction2.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.VerticalRulerEvent;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.texteditor.SelectAnnotationRulerAction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.AssistAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaExpandHover;
-
-/**
- * A special select marker ruler action which activates quick fix if clicked on a quick fixable problem.
- */
-public class JavaSelectMarkerRulerAction2 extends SelectAnnotationRulerAction {
-
- public JavaSelectMarkerRulerAction2(ResourceBundle bundle, String prefix, ITextEditor editor) {
- super(bundle, prefix, editor);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IVerticalRulerListener#annotationDefaultSelected(org.eclipse.ui.texteditor.VerticalRulerEvent)
- */
- public void annotationDefaultSelected(VerticalRulerEvent event) {
- Annotation annotation= event.getSelectedAnnotation();
- IAnnotationModel model= getAnnotationModel();
-
- if (isOverrideIndicator(annotation)) {
- ((OverrideIndicatorManager.OverrideIndicator)annotation).open();
- return;
- }
-
- if (isBreakpoint(annotation))
- triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
-
- Position position= model.getPosition(annotation);
- if (position == null)
- return;
-
- if (isQuickFixTarget(annotation)) {
- ITextOperationTarget operation= (ITextOperationTarget) getTextEditor().getAdapter(ITextOperationTarget.class);
- final int opCode= ISourceViewer.QUICK_ASSIST;
- if (operation != null && operation.canDoOperation(opCode)) {
- getTextEditor().selectAndReveal(position.getOffset(), position.getLength());
- operation.doOperation(opCode);
- return;
- }
- }
-
- // default:
- super.annotationDefaultSelected(event);
- }
-
- /**
- * Tells whether the given annotation is an override annotation.
- *
- * @param annotation the annotation
- * @return <code>true</code> iff the annotation is an override annotation
- */
- private boolean isOverrideIndicator(Annotation annotation) {
- return annotation instanceof OverrideIndicatorManager.OverrideIndicator;
- }
-
- /**
- * Checks whether the given annotation is a breakpoint annotation.
- *
- * @param annotation
- * @return <code>true</code> if the annotation is a breakpoint annotation
- */
- private boolean isBreakpoint(Annotation annotation) {
- return annotation.getType().equals("org.eclipse.debug.core.breakpoint") || annotation.getType().equals(JavaExpandHover.NO_BREAKPOINT_ANNOTATION); //$NON-NLS-1$
- }
-
- private boolean isQuickFixTarget(Annotation a) {
- return JavaCorrectionProcessor.hasCorrections(a) || a instanceof AssistAnnotation;
- }
-
- private void triggerAction(String actionID) {
- IAction action= getTextEditor().getAction(actionID);
- if (action != null) {
- if (action instanceof IUpdate)
- ((IUpdate) action).update();
- // hack to propagate line change
- if (action instanceof ISelectionListener) {
- ((ISelectionListener)action).selectionChanged(null, null);
- }
- if (action.isEnabled())
- action.run();
- }
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectRulerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectRulerAction.java
deleted file mode 100644
index c7affd4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSelectRulerAction.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.source.IVerticalRulerInfo;
-import org.eclipse.ui.texteditor.AbstractRulerActionDelegate;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-public class JavaSelectRulerAction extends AbstractRulerActionDelegate {
-
- /*
- * @see AbstractRulerActionDelegate#createAction(ITextEditor, IVerticalRulerInfo)
- */
- protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) {
- return new JavaSelectAnnotationRulerAction(JavaEditorMessages.getBundleForConstructedKeys(), "JavaSelectAnnotationRulerAction.", editor, rulerInfo); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSourceViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSourceViewer.java
deleted file mode 100644
index 09085a15..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaSourceViewer.java
+++ /dev/null
@@ -1,630 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextPresentationListener;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.jface.text.information.IInformationPresenter;
-import org.eclipse.jface.text.reconciler.IReconciler;
-import org.eclipse.jface.text.source.IOverviewRuler;
-import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.jface.text.source.projection.ProjectionViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BidiSegmentEvent;
-import org.eclipse.swt.custom.BidiSegmentListener;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.ui.texteditor.AbstractTextEditor;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.text.SmartBackspaceManager;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-
-
-public class JavaSourceViewer extends ProjectionViewer implements IPropertyChangeListener {
-
- /**
- * Text operation code for requesting the outline for the current input.
- */
- public static final int SHOW_OUTLINE= 51;
-
- /**
- * Text operation code for requesting the outline for the element at the current position.
- */
- public static final int OPEN_STRUCTURE= 52;
-
- /**
- * Text operation code for requesting the hierarchy for the current input.
- */
- public static final int SHOW_HIERARCHY= 53;
-
- private IInformationPresenter fOutlinePresenter;
- private IInformationPresenter fStructurePresenter;
- private IInformationPresenter fHierarchyPresenter;
-
- /**
- * This viewer's foreground color.
- *
- */
- private Color fForegroundColor;
- /**
- * The viewer's background color.
- *
- */
- private Color fBackgroundColor;
- /**
- * This viewer's selection foreground color.
- *
- */
- private Color fSelectionForegroundColor;
- /**
- * The viewer's selection background color.
- *
- */
- private Color fSelectionBackgroundColor;
- /**
- * The preference store.
- *
- *
- */
- private IPreferenceStore fPreferenceStore;
- /**
- * Is this source viewer configured?
- *
- *
- */
- private boolean fIsConfigured;
- /**
- * The backspace manager of this viewer.
- *
- *
- */
- private SmartBackspaceManager fBackspaceManager;
-
- /**
- * Whether to delay setting the visual document until the projection has been computed.
- * <p>
- * Added for performance optimization.
- * </p>
- * @see #prepareDelayedProjection()
- *
- */
- private boolean fIsSetVisibleDocumentDelayed= false;
-
- public JavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IPreferenceStore store) {
- super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
- setPreferenceStore(store);
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
- *
- */
- public IFormattingContext createFormattingContext() {
-
- // it's ok to use instance preferences here as subclasses replace
- // with project dependent versions (see CompilationUnitEditor.AdaptedSourceViewer)
- IFormattingContext context= new CommentFormattingContext();
- Map map= new HashMap(JavaScriptCore.getOptions());
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, map);
-
- return context;
- }
-
- /*
- * @see ITextOperationTarget#doOperation(int)
- */
- public void doOperation(int operation) {
- if (getTextWidget() == null)
- return;
-
- switch (operation) {
- case SHOW_OUTLINE:
- if (fOutlinePresenter != null)
- fOutlinePresenter.showInformation();
- return;
- case OPEN_STRUCTURE:
- if (fStructurePresenter != null)
- fStructurePresenter.showInformation();
- return;
- case SHOW_HIERARCHY:
- if (fHierarchyPresenter != null)
- fHierarchyPresenter.showInformation();
- return;
- }
-
- super.doOperation(operation);
- }
-
- /*
- * @see ITextOperationTarget#canDoOperation(int)
- */
- public boolean canDoOperation(int operation) {
- if (operation == SHOW_OUTLINE)
- return fOutlinePresenter != null;
- if (operation == OPEN_STRUCTURE)
- return fStructurePresenter != null;
- if (operation == SHOW_HIERARCHY)
- return fHierarchyPresenter != null;
-
- return super.canDoOperation(operation);
- }
-
- /*
- * @see ISourceViewer#configure(SourceViewerConfiguration)
- */
- public void configure(SourceViewerConfiguration configuration) {
-
- /*
- * Prevent access to colors disposed in unconfigure(), see:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=53641
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=86177
- */
- StyledText textWidget= getTextWidget();
- if (textWidget != null && !textWidget.isDisposed()) {
- Color foregroundColor= textWidget.getForeground();
- if (foregroundColor != null && foregroundColor.isDisposed())
- textWidget.setForeground(null);
- Color backgroundColor= textWidget.getBackground();
- if (backgroundColor != null && backgroundColor.isDisposed())
- textWidget.setBackground(null);
- }
-
- super.configure(configuration);
- if (configuration instanceof JavaScriptSourceViewerConfiguration) {
- JavaScriptSourceViewerConfiguration javaSVCconfiguration= (JavaScriptSourceViewerConfiguration)configuration;
- fOutlinePresenter= javaSVCconfiguration.getOutlinePresenter(this, false);
- if (fOutlinePresenter != null)
- fOutlinePresenter.install(this);
-
- fStructurePresenter= javaSVCconfiguration.getOutlinePresenter(this, true);
- if (fStructurePresenter != null)
- fStructurePresenter.install(this);
-
- fHierarchyPresenter= javaSVCconfiguration.getHierarchyPresenter(this, true);
- if (fHierarchyPresenter != null)
- fHierarchyPresenter.install(this);
-
- }
-
- if (fPreferenceStore != null) {
- fPreferenceStore.addPropertyChangeListener(this);
- initializeViewerColors();
- }
-
- fIsConfigured= true;
- }
-
-
- protected void initializeViewerColors() {
- if (fPreferenceStore != null) {
-
- StyledText styledText= getTextWidget();
-
- // ----------- foreground color --------------------
- Color color= fPreferenceStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT)
- ? null
- : createColor(fPreferenceStore, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, styledText.getDisplay());
- styledText.setForeground(color);
-
- if (fForegroundColor != null)
- fForegroundColor.dispose();
-
- fForegroundColor= color;
-
- // ---------- background color ----------------------
- color= fPreferenceStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)
- ? null
- : createColor(fPreferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay());
- styledText.setBackground(color);
-
- if (fBackgroundColor != null)
- fBackgroundColor.dispose();
-
- fBackgroundColor= color;
-
- // ----------- selection foreground color --------------------
- color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR)
- ? null
- : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, styledText.getDisplay());
- styledText.setSelectionForeground(color);
-
- if (fSelectionForegroundColor != null)
- fSelectionForegroundColor.dispose();
-
- fSelectionForegroundColor= color;
-
- // ---------- selection background color ----------------------
- color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR)
- ? null
- : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, styledText.getDisplay());
- styledText.setSelectionBackground(color);
-
- if (fSelectionBackgroundColor != null)
- fSelectionBackgroundColor.dispose();
-
- fSelectionBackgroundColor= color;
- }
- }
-
- /**
- * Creates a color from the information stored in the given preference store.
- * Returns <code>null</code> if there is no such information available.
- *
- * @param store the store to read from
- * @param key the key used for the lookup in the preference store
- * @param display the display used create the color
- * @return the created color according to the specification in the preference store
- *
- */
- private Color createColor(IPreferenceStore store, String key, Display display) {
-
- RGB rgb= null;
-
- if (store.contains(key)) {
-
- if (store.isDefault(key))
- rgb= PreferenceConverter.getDefaultColor(store, key);
- else
- rgb= PreferenceConverter.getColor(store, key);
-
- if (rgb != null)
- return new Color(display, rgb);
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
- *
- */
- public void unconfigure() {
- if (fOutlinePresenter != null) {
- fOutlinePresenter.uninstall();
- fOutlinePresenter= null;
- }
- if (fStructurePresenter != null) {
- fStructurePresenter.uninstall();
- fStructurePresenter= null;
- }
- if (fHierarchyPresenter != null) {
- fHierarchyPresenter.uninstall();
- fHierarchyPresenter= null;
- }
- if (fForegroundColor != null) {
- fForegroundColor.dispose();
- fForegroundColor= null;
- }
- if (fBackgroundColor != null) {
- fBackgroundColor.dispose();
- fBackgroundColor= null;
- }
-
- if (fPreferenceStore != null)
- fPreferenceStore.removePropertyChangeListener(this);
-
- super.unconfigure();
-
- fIsConfigured= false;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#rememberSelection()
- */
- public Point rememberSelection() {
- return super.rememberSelection();
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#restoreSelection()
- */
- public void restoreSelection() {
- super.restoreSelection();
- }
-
- /*
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- String property = event.getProperty();
- if (AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND.equals(property)
- || AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT.equals(property)
- || AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND.equals(property)
- || AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
- || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR.equals(property)
- || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR.equals(property)
- || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR.equals(property)
- || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR.equals(property))
- {
- initializeViewerColors();
- }
- }
-
- /**
- * Sets the preference store on this viewer.
- *
- * @param store the preference store
- *
- *
- */
- public void setPreferenceStore(IPreferenceStore store) {
- if (fIsConfigured && fPreferenceStore != null)
- fPreferenceStore.removePropertyChangeListener(this);
-
- fPreferenceStore= store;
-
- if (fIsConfigured && fPreferenceStore != null) {
- fPreferenceStore.addPropertyChangeListener(this);
- initializeViewerColors();
- }
- }
-
- /*
- * @see org.eclipse.jface.text.ITextViewer#resetVisibleRegion()
- *
- */
- public void resetVisibleRegion() {
- super.resetVisibleRegion();
- // re-enable folding if ProjectionViewer failed to due so
- if (fPreferenceStore != null && fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED) && !isProjectionMode())
- enableProjection();
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#createControl(org.eclipse.swt.widgets.Composite, int)
- */
- protected void createControl(Composite parent, int styles) {
-
- // Use LEFT_TO_RIGHT unless otherwise specified.
- if ((styles & SWT.RIGHT_TO_LEFT) == 0 && (styles & SWT.LEFT_TO_RIGHT) == 0)
- styles |= SWT.LEFT_TO_RIGHT;
-
- super.createControl(parent, styles);
-
- fBackspaceManager= new SmartBackspaceManager();
- fBackspaceManager.install(this);
-
- StyledText text= getTextWidget();
- text.addBidiSegmentListener(new BidiSegmentListener() {
- public void lineGetSegments(BidiSegmentEvent event) {
- if (redraws())
- event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
- }
- });
- }
-
- /**
- * Returns the backspace manager for this viewer.
- *
- * @return the backspace manager for this viewer, or <code>null</code> if
- * there is none
- *
- */
- public SmartBackspaceManager getBackspaceManager() {
- return fBackspaceManager;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewer#handleDispose()
- */
- protected void handleDispose() {
- if (fBackspaceManager != null) {
- fBackspaceManager.uninstall();
- fBackspaceManager= null;
- }
-
- super.handleDispose();
- }
-
- /**
- * Prepends the text presentation listener at the beginning of the viewer's
- * list of text presentation listeners. If the listener is already registered
- * with the viewer this call moves the listener to the beginning of
- * the list.
- *
- * @param listener the text presentation listener
- *
- */
- public void prependTextPresentationListener(ITextPresentationListener listener) {
-
- Assert.isNotNull(listener);
-
- if (fTextPresentationListeners == null)
- fTextPresentationListeners= new ArrayList();
-
- fTextPresentationListeners.remove(listener);
- fTextPresentationListeners.add(0, listener);
- }
-
- /**
- * Sets the given reconciler.
- *
- * @param reconciler the reconciler
- *
- */
- void setReconciler(IReconciler reconciler) {
- fReconciler= reconciler;
- }
-
- /**
- * Returns the reconciler.
- *
- * @return the reconciler or <code>null</code> if not set
- *
- */
- IReconciler getReconciler() {
- return fReconciler;
- }
-
- /**
- * Returns a segmentation of the given line appropriate for BIDI rendering. The default
- * implementation returns only the string literals of a java code line as segments.
- *
- * @param widgetLineOffset the offset of the line
- * @param line the content of the line
- * @return the line's BIDI segmentation
- */
- protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
- if (line != null && line.length() > 0) {
- int lineOffset= widgetOffset2ModelOffset(widgetLineOffset);
- try {
- return getBidiLineSegments(getDocument(), lineOffset);
- } catch (BadLocationException x) {
- return null; // don't segment line in this case
- }
- }
- return null;
- }
-
- /**
- * Returns a segmentation of the line of the given document appropriate for
- * BIDI rendering. The default implementation returns only the string literals of a java code
- * line as segments.
- *
- * @param document the document
- * @param lineOffset the offset of the line
- * @return the line's BIDI segmentation
- * @throws BadLocationException in case lineOffset is not valid in document
- */
- protected static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
-
- if (document == null)
- return null;
-
- IRegion line= document.getLineInformationOfOffset(lineOffset);
- ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaScriptPartitions.JAVA_PARTITIONING, lineOffset, line.getLength(), false);
-
- List segmentation= new ArrayList();
- for (int i= 0; i < linePartitioning.length; i++) {
- if (IJavaScriptPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
- segmentation.add(linePartitioning[i]);
- }
-
-
- if (segmentation.size() == 0)
- return null;
-
- int size= segmentation.size();
- int[] segments= new int[size * 2 + 1];
-
- int j= 0;
- for (int i= 0; i < size; i++) {
- ITypedRegion segment= (ITypedRegion) segmentation.get(i);
-
- if (i == 0)
- segments[j++]= 0;
-
- int offset= segment.getOffset() - lineOffset;
- if (offset > segments[j - 1])
- segments[j++]= offset;
-
- if (offset + segment.getLength() >= line.getLength())
- break;
-
- segments[j++]= offset + segment.getLength();
- }
-
- if (j < segments.length) {
- int[] result= new int[j];
- System.arraycopy(segments, 0, result, 0, j);
- segments= result;
- }
-
- return segments;
- }
-
- /**
- * Delays setting the visual document until after the projection has been computed.
- * This method must only be called before the document is set on the viewer.
- * <p>
- * This is a performance optimization to reduce the computation of
- * the text presentation triggered by <code>setVisibleDocument(IDocument)</code>.
- * </p>
- *
- * @see #setVisibleDocument(IDocument)
- *
- */
- void prepareDelayedProjection() {
- Assert.isTrue(!fIsSetVisibleDocumentDelayed);
- fIsSetVisibleDocumentDelayed= true;
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * This is a performance optimization to reduce the computation of
- * the text presentation triggered by {@link #setVisibleDocument(IDocument)}
- * </p>
- * @see #prepareDelayedProjection()
- *
- */
- protected void setVisibleDocument(IDocument document) {
- if (fIsSetVisibleDocumentDelayed) {
- fIsSetVisibleDocumentDelayed= false;
- IDocument previous= getVisibleDocument();
- enableProjection(); // will set the visible document if anything is folded
- IDocument current= getVisibleDocument();
- // if the visible document was not replaced, continue as usual
- if (current != null && current != previous)
- return;
- }
-
- super.setVisibleDocument(document);
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Performance optimization: since we know at this place
- * that none of the clients expects the given range to be
- * untouched we reuse the given range as return value.
- * </p>
- */
- protected StyleRange modelStyleRange2WidgetStyleRange(StyleRange range) {
- IRegion region= modelRange2WidgetRange(new Region(range.start, range.length));
- if (region != null) {
- // don't clone the style range, but simply reuse it.
- range.start= region.getOffset();
- range.length= region.getLength();
- return range;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaTextSelection.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaTextSelection.java
deleted file mode 100644
index ed1f305b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaTextSelection.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-
-/**
- * A special text selection that gives access to the resolved and
- * enclosing element.
- */
-public class JavaTextSelection extends TextSelection {
-
- private IJavaScriptElement fElement;
- private IJavaScriptElement[] fResolvedElements;
-
- private boolean fEnclosingElementRequested;
- private IJavaScriptElement fEnclosingElement;
-
- private boolean fPartialASTRequested;
- private JavaScriptUnit fPartialAST;
-
- private boolean fNodesRequested;
- private ASTNode[] fSelectedNodes;
- private ASTNode fCoveringNode;
-
- private boolean fInMethodBodyRequested;
- private boolean fInMethodBody;
-
- private boolean fInClassInitializerRequested;
- private boolean fInClassInitializer;
-
- private boolean fInVariableInitializerRequested;
- private boolean fInVariableInitializer;
-
- /**
- * Creates a new text selection at the given offset and length.
- */
- public JavaTextSelection(IJavaScriptElement element, IDocument document, int offset, int length) {
- super(document, offset, length);
- fElement= element;
- }
-
- /**
- * Resolves the <code>IJavaScriptElement</code>s at the current offset. Returns
- * an empty array if the string under the offset doesn't resolve to a
- * <code>IJavaScriptElement</code>.
- *
- * @return the resolved java elements at the current offset
- * @throws JavaScriptModelException passed from the underlying code resolve API
- */
- public IJavaScriptElement[] resolveElementAtOffset() throws JavaScriptModelException {
- if (fResolvedElements != null)
- return fResolvedElements;
- // long start= System.currentTimeMillis();
- fResolvedElements= SelectionConverter.codeResolve(fElement, this);
- // System.out.println("Time resolving element: " + (System.currentTimeMillis() - start));
- return fResolvedElements;
- }
-
- public IJavaScriptElement resolveEnclosingElement() throws JavaScriptModelException {
- if (fEnclosingElementRequested)
- return fEnclosingElement;
- fEnclosingElementRequested= true;
- fEnclosingElement= SelectionConverter.resolveEnclosingElement(fElement, this);
- return fEnclosingElement;
- }
-
- public JavaScriptUnit resolvePartialAstAtOffset() {
- if (fPartialASTRequested)
- return fPartialAST;
- fPartialASTRequested= true;
- if (! (fElement instanceof IJavaScriptUnit))
- return null;
- // long start= System.currentTimeMillis();
- fPartialAST= JavaScriptPlugin.getDefault().getASTProvider().getAST(fElement, ASTProvider.WAIT_YES, null);
- // System.out.println("Time requesting partial AST: " + (System.currentTimeMillis() - start));
- return fPartialAST;
- }
-
- public ASTNode[] resolveSelectedNodes() {
- if (fNodesRequested)
- return fSelectedNodes;
- fNodesRequested= true;
- JavaScriptUnit root= resolvePartialAstAtOffset();
- if (root == null)
- return null;
- Selection ds= Selection.createFromStartLength(getOffset(), getLength());
- SelectionAnalyzer analyzer= new SelectionAnalyzer(ds, false);
- root.accept(analyzer);
- fSelectedNodes= analyzer.getSelectedNodes();
- fCoveringNode= analyzer.getLastCoveringNode();
- return fSelectedNodes;
- }
-
- public ASTNode resolveCoveringNode() {
- if (fNodesRequested)
- return fCoveringNode;
- resolveSelectedNodes();
- return fCoveringNode;
- }
-
- public boolean resolveInMethodBody() {
- if (fInMethodBodyRequested)
- return fInMethodBody;
- fInMethodBodyRequested= true;
- resolveSelectedNodes();
- ASTNode node= getStartNode();
- if (node == null) {
- fInMethodBody= true;
- } else {
- while (node != null) {
- int nodeType= node.getNodeType();
- if (nodeType == ASTNode.BLOCK && node.getParent() instanceof BodyDeclaration) {
- fInMethodBody= node.getParent().getNodeType() == ASTNode.FUNCTION_DECLARATION;
- break;
- } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
- fInMethodBody= false;
- break;
- }
- node= node.getParent();
- }
- }
- return fInMethodBody;
- }
-
- public boolean resolveInClassInitializer() {
- if (fInClassInitializerRequested)
- return fInClassInitializer;
- fInClassInitializerRequested= true;
- resolveSelectedNodes();
- ASTNode node= getStartNode();
- if (node == null) {
- fInClassInitializer= true;
- } else {
- while (node != null) {
- int nodeType= node.getNodeType();
- if (node instanceof AbstractTypeDeclaration) {
- fInClassInitializer= false;
- break;
- } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
- fInClassInitializer= false;
- break;
- } else if (nodeType == ASTNode.INITIALIZER) {
- fInClassInitializer= true;
- break;
- }
- node= node.getParent();
- }
- }
- return fInClassInitializer;
- }
-
- public boolean resolveInVariableInitializer() {
- if (fInVariableInitializerRequested)
- return fInVariableInitializer;
- fInVariableInitializerRequested= true;
- resolveSelectedNodes();
- ASTNode node= getStartNode();
- ASTNode last= null;
- while (node != null) {
- int nodeType= node.getNodeType();
- if (node instanceof AbstractTypeDeclaration) {
- fInVariableInitializer= false;
- break;
- } else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
- fInVariableInitializer= false;
- break;
- } else if (nodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT &&
- ((VariableDeclarationFragment)node).getInitializer() == last) {
- fInVariableInitializer= true;
- break;
- } else if (nodeType == ASTNode.SINGLE_VARIABLE_DECLARATION &&
- ((SingleVariableDeclaration)node).getInitializer() == last) {
- fInVariableInitializer= true;
- break;
- }
- last= node;
- node= node.getParent();
- }
- return fInVariableInitializer;
- }
-
- private ASTNode getStartNode() {
- if (fSelectedNodes != null && fSelectedNodes.length > 0)
- return fSelectedNodes[0];
- else
- return fCoveringNode;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlink.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlink.java
deleted file mode 100644
index d4c785b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlink.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.AccessorClassReference;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSHintHelper;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-
-/**
- * NLS key hyperlink.
- *
- *
- */
-public class NLSKeyHyperlink implements IHyperlink {
-
- private IRegion fRegion;
- private AccessorClassReference fAccessorClassReference;
- private IEditorPart fEditor;
- private final String fKeyName;
-
-
- /**
- * Creates a new NLS key hyperlink.
- *
- * @param region
- * @param keyName
- * @param ref
- * @param editor the editor which contains the hyperlink
- */
- public NLSKeyHyperlink(IRegion region, String keyName, AccessorClassReference ref, IEditorPart editor) {
- Assert.isNotNull(region);
- Assert.isNotNull(keyName);
- Assert.isNotNull(ref);
- Assert.isNotNull(editor);
-
- fRegion= region;
- fKeyName= keyName;
- fAccessorClassReference= ref;
- fEditor= editor;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getHyperlinkRegion()
- */
- public IRegion getHyperlinkRegion() {
- return fRegion;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#open()
- */
- public void open() {
- IStorage propertiesFile= null;
- try {
- ITypeBinding typeBinding= fAccessorClassReference.getBinding();
- propertiesFile= NLSHintHelper.getResourceBundle(typeBinding.getJavaElement().getJavaScriptProject(), fAccessorClassReference);
- } catch (JavaScriptModelException e) {
- // Don't open the file
- }
- if (propertiesFile == null) {
- showErrorInStatusLine(fEditor, JavaEditorMessages.Editor_OpenPropertiesFile_error_fileNotFound_dialogMessage);
- return;
- }
-
- IEditorPart editor;
- try {
- editor= EditorUtility.openInEditor(propertiesFile, true);
- } catch (PartInitException e) {
- handleOpenPropertiesFileFailed(propertiesFile);
- return;
- } catch (JavaScriptModelException e) {
- handleOpenPropertiesFileFailed(propertiesFile);
- return;
- }
-
-// // Reveal the key in the properties file
-// if (editor instanceof ITextEditor) {
-// IRegion region= null;
-// boolean found= false;
-//
-// // Find key in document
-// IEditorInput editorInput= editor.getEditorInput();
-// IDocument document= ((ITextEditor)editor).getDocumentProvider().getDocument(editorInput);
-// if (document != null) {
-// FindReplaceDocumentAdapter finder= new FindReplaceDocumentAdapter(document);
-// PropertyKeyHyperlinkDetector detector= new PropertyKeyHyperlinkDetector();
-// detector.setContext(editor);
-// String key= PropertyFileDocumentModel.unwindEscapeChars(fKeyName);
-// int offset= document.getLength() - 1;
-// try {
-// while (!found && offset >= 0) {
-// region= finder.find(offset, key, false, true, false, false);
-// if (region == null)
-// offset= -1;
-// else {
-// // test whether it's the key
-// IHyperlink[] hyperlinks= detector.detectHyperlinks(null, region, false);
-// if (hyperlinks != null) {
-// for (int i= 0; i < hyperlinks.length; i++) {
-// IRegion hyperlinkRegion= hyperlinks[i].getHyperlinkRegion();
-// found= key.equals(document.get(hyperlinkRegion.getOffset(), hyperlinkRegion.getLength()));
-// }
-// } else if (document instanceof IDocumentExtension3) {
-// // Fall back: test using properties file partitioning
-// ITypedRegion partition= null;
-// partition= ((IDocumentExtension3)document).getPartition(IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, region.getOffset(), false);
-// found= IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
-// && key.equals(document.get(partition.getOffset(), partition.getLength()).trim());
-// }
-// // Prevent endless loop (panic code, shouldn't be needed)
-// if (offset == region.getOffset())
-// offset= -1;
-// else
-// offset= region.getOffset();
-// }
-// }
-// } catch (BadLocationException ex) {
-// found= false;
-// } catch (BadPartitioningException e1) {
-// found= false;
-// }
-// }
-// if (found)
-// EditorUtility.revealInEditor(editor, region);
-// else {
-// EditorUtility.revealInEditor(editor, 0, 0);
-// showErrorInStatusLine(editor, Messages.format(JavaEditorMessages.Editor_OpenPropertiesFile_error_keyNotFound, fKeyName));
-// }
-// }
- }
-
- private void showErrorInStatusLine(IEditorPart editor, final String message) {
- final Display display= fEditor.getSite().getShell().getDisplay();
- display.beep();
- final IEditorStatusLine statusLine= (IEditorStatusLine)editor.getAdapter(IEditorStatusLine.class);
- if (statusLine != null) {
- display.asyncExec(new Runnable() {
- /*
- * @see java.lang.Runnable#run()
- */
- public void run() {
- statusLine.setMessage(true, message, null);
- }
- });
- }
- }
-
- private void handleOpenPropertiesFileFailed(IStorage propertiesFile) {
- showErrorInStatusLine(fEditor, Messages.format(JavaEditorMessages.Editor_OpenPropertiesFile_error_openEditor_dialogMessage, propertiesFile.getFullPath().toOSString()));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getTypeLabel()
- */
- public String getTypeLabel() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IHyperlink#getHyperlinkText()
- */
- public String getHyperlinkText() {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlinkDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlinkDetector.java
deleted file mode 100644
index 7d942ec5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/NLSKeyHyperlinkDetector.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.AccessorClassReference;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSHintHelper;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-/**
- * NLS hyperlink detector.
- *
- *
- */
-public class NLSKeyHyperlinkDetector extends AbstractHyperlinkDetector {
-
-
- /*
- * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
- */
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
- ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
- if (region == null || textEditor == null || canShowMultipleHyperlinks)
- return null;
-
- IEditorSite site= textEditor.getEditorSite();
- if (site == null)
- return null;
-
- IJavaScriptElement javaElement= getInputJavaElement(textEditor);
- if (javaElement == null)
- return null;
-
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null);
- if (ast == null)
- return null;
-
- ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
- if (!(node instanceof StringLiteral) && !(node instanceof SimpleName))
- return null;
-
- if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
- return null;
-
- IRegion nlsKeyRegion= new Region(node.getStartPosition(), node.getLength());
- AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, nlsKeyRegion);
- if (ref == null)
- return null;
- String keyName= null;
- if (node instanceof StringLiteral) {
- keyName= ((StringLiteral)node).getLiteralValue();
- } else {
- keyName= ((SimpleName)node).getIdentifier();
- }
- if (keyName != null)
- return new IHyperlink[] {new NLSKeyHyperlink(nlsKeyRegion, keyName, ref, textEditor)};
-
- return null;
- }
-
- private IJavaScriptElement getInputJavaElement(ITextEditor editor) {
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)editorInput).getClassFile();
-
- if (editor instanceof CompilationUnitEditor)
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput);
-
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java
deleted file mode 100644
index 3fb2f17d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.texteditor.IAnnotationImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Image provider for {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.OverrideIndicatorManager.OverrideIndicator} annotations.
- *
- *
- */
-public class OverrideIndicatorImageProvider implements IAnnotationImageProvider {
-
- /*
- * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getManagedImage(org.eclipse.jface.text.source.Annotation)
- */
- private static final String OVERRIDE_IMG_DESC_ID= "JavaPluginImages.DESC_OBJ_OVERRIDES"; //$NON-NLS-1$
- private static final String OVERWRITE_IMG_DESC_ID= "JavaPluginImages.DESC_OBJ_IMPLEMENTS"; //$NON-NLS-1$
- public Image getManagedImage(Annotation annotation) {
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getImageDescriptorId(org.eclipse.jface.text.source.Annotation)
- */
- public String getImageDescriptorId(Annotation annotation) {
- if (!isImageProviderFor(annotation))
- return null;
-
- if (isOverwriting(annotation))
- return OVERWRITE_IMG_DESC_ID;
- else
- return OVERRIDE_IMG_DESC_ID;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getImageDescriptor(java.lang.String)
- */
- public ImageDescriptor getImageDescriptor(String imageDescritporId) {
- if (OVERWRITE_IMG_DESC_ID.equals(imageDescritporId))
- return JavaPluginImages.DESC_OBJ_IMPLEMENTS;
- else if (OVERRIDE_IMG_DESC_ID.equals(imageDescritporId))
- return JavaPluginImages.DESC_OBJ_OVERRIDES;
-
- return null;
- }
-
- private boolean isImageProviderFor(Annotation annotation) {
- return annotation != null && OverrideIndicatorManager.ANNOTATION_TYPE.equals(annotation.getType());
- }
-
- private boolean isOverwriting(Annotation annotation) {
- return ((OverrideIndicatorManager.OverrideIndicator)annotation).isOverwriteIndicator();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorManager.java
deleted file mode 100644
index 2f36a80a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorManager.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ISynchronizable;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationModelExtension;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Manages the override and overwrite indicators for
- * the given Java element and annotation model.
- *
- *
- */
-class OverrideIndicatorManager implements IJavaReconcilingListener {
-
- /**
- * Overwrite and override indicator annotation.
- *
- *
- */
- class OverrideIndicator extends Annotation {
-
- private boolean fIsOverwriteIndicator;
- private String fAstNodeKey;
-
- /**
- * Creates a new override annotation.
- *
- * @param isOverwriteIndicator <code>true</code> if this annotation is
- * an overwrite indicator, <code>false</code> otherwise
- * @param text the text associated with this annotation
- * @param key the method binding key
- *
- */
- OverrideIndicator(boolean isOverwriteIndicator, String text, String key) {
- super(ANNOTATION_TYPE, false, text);
- fIsOverwriteIndicator= isOverwriteIndicator;
- fAstNodeKey= key;
- }
-
- /**
- * Tells whether this is an overwrite or an override indicator.
- *
- * @return <code>true</code> if this is an overwrite indicator
- */
- public boolean isOverwriteIndicator() {
- return fIsOverwriteIndicator;
- }
-
- /**
- * Opens and reveals the defining method.
- */
- public void open() {
- JavaScriptUnit ast= ASTProvider.getASTProvider().getAST(fJavaElement, ASTProvider.WAIT_ACTIVE_ONLY, null);
- if (ast != null) {
- ASTNode node= ast.findDeclaringNode(fAstNodeKey);
- if (node instanceof FunctionDeclaration) {
- try {
- IFunctionBinding methodBinding= ((FunctionDeclaration)node).resolveBinding();
- IFunctionBinding definingMethodBinding= Bindings.findOverriddenMethod(methodBinding, true);
- if (definingMethodBinding != null) {
- IJavaScriptElement definingMethod= definingMethodBinding.getJavaElement();
- if (definingMethod != null) {
- JavaScriptUI.openInEditor(definingMethod, true, true);
- return;
- }
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, JavaEditorMessages.OverrideIndicatorManager_open_error_title, JavaEditorMessages.OverrideIndicatorManager_open_error_messageHasLogEntry);
- return;
- }
- }
- }
- String title= JavaEditorMessages.OverrideIndicatorManager_open_error_title;
- String message= JavaEditorMessages.OverrideIndicatorManager_open_error_message;
- MessageDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), title, message);
- }
- }
-
- static final String ANNOTATION_TYPE= "org.eclipse.wst.jsdt.ui.overrideIndicator"; //$NON-NLS-1$
-
- private IAnnotationModel fAnnotationModel;
- private Object fAnnotationModelLockObject;
- private Annotation[] fOverrideAnnotations;
- private IJavaScriptElement fJavaElement;
-
-
- public OverrideIndicatorManager(IAnnotationModel annotationModel, IJavaScriptElement javaElement, JavaScriptUnit ast) {
- Assert.isNotNull(annotationModel);
- Assert.isNotNull(javaElement);
-
- fJavaElement= javaElement;
- fAnnotationModel=annotationModel;
- fAnnotationModelLockObject= getLockObject(fAnnotationModel);
-
- updateAnnotations(ast, new NullProgressMonitor());
- }
-
- /**
- * Returns the lock object for the given annotation model.
- *
- * @param annotationModel the annotation model
- * @return the annotation model's lock object
- *
- */
- private Object getLockObject(IAnnotationModel annotationModel) {
- if (annotationModel instanceof ISynchronizable) {
- Object lock= ((ISynchronizable)annotationModel).getLockObject();
- if (lock != null)
- return lock;
- }
- return annotationModel;
- }
-
- /**
- * Updates the override and implements annotations based
- * on the given AST.
- *
- * @param ast the compilation unit AST
- * @param progressMonitor the progress monitor
- *
- */
- protected void updateAnnotations(JavaScriptUnit ast, IProgressMonitor progressMonitor) {
-
- if (ast == null || progressMonitor.isCanceled())
- return;
-
- final Map annotationMap= new HashMap(50);
-
- ast.accept(new ASTVisitor(false) {
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- IFunctionBinding binding= node.resolveBinding();
- if (binding != null) {
- IFunctionBinding definingMethod= Bindings.findOverriddenMethod(binding, true);
- if (definingMethod != null) {
-
- ITypeBinding definingType= definingMethod.getDeclaringClass();
- String qualifiedMethodName= definingType.getQualifiedName() + "." + binding.getName(); //$NON-NLS-1$
-
- boolean isImplements= JdtFlags.isAbstract(definingMethod);
- String text;
- if (isImplements)
- text= Messages.format(JavaEditorMessages.OverrideIndicatorManager_implements, qualifiedMethodName);
- else
- text= Messages.format(JavaEditorMessages.OverrideIndicatorManager_overrides, qualifiedMethodName);
-
- SimpleName name= node.getName();
- Position position= new Position(name.getStartPosition(), name.getLength());
-
- annotationMap.put(
- new OverrideIndicator(isImplements, text, binding.getKey()),
- position);
-
- }
- }
- return true;
- }
- });
-
- if (progressMonitor.isCanceled())
- return;
-
- synchronized (fAnnotationModelLockObject) {
- if (fAnnotationModel instanceof IAnnotationModelExtension) {
- ((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, annotationMap);
- } else {
- removeAnnotations();
- Iterator iter= annotationMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry mapEntry= (Map.Entry)iter.next();
- fAnnotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
- }
- }
- fOverrideAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
- }
- }
-
- /**
- * Removes all override indicators from this manager's annotation model.
- */
- void removeAnnotations() {
- if (fOverrideAnnotations == null)
- return;
-
- synchronized (fAnnotationModelLockObject) {
- if (fAnnotationModel instanceof IAnnotationModelExtension) {
- ((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, null);
- } else {
- for (int i= 0, length= fOverrideAnnotations.length; i < length; i++)
- fAnnotationModel.removeAnnotation(fOverrideAnnotations[i]);
- }
- fOverrideAnnotations= null;
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
- */
- public void aboutToBeReconciled() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(JavaScriptUnit, boolean, IProgressMonitor)
- */
- public void reconciled(JavaScriptUnit ast, boolean forced, IProgressMonitor progressMonitor) {
- updateAnnotations(ast, progressMonitor);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java
deleted file mode 100644
index 39beaa7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.action.Action;
-
-/**
- * Remove occurrence annotations action.
- *
- *
- */
-class RemoveOccurrenceAnnotations extends Action {
-
- /** The Java editor to which this actions belongs. */
- private final JavaEditor fEditor;
-
- /**
- * Creates this action.
- *
- * @param editor the Java editor for which to remove the occurrence annotations
- */
- RemoveOccurrenceAnnotations(JavaEditor editor) {
- fEditor = editor;
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- fEditor.removeOccurrenceAnnotations();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlighting.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlighting.java
deleted file mode 100644
index deb1e381..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlighting.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.resource.ColorRegistry;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Semantic highlighting
- */
-public abstract class SemanticHighlighting {
-
- /**
- * @return the preference key, will be augmented by a prefix and a suffix for each preference
- */
- public abstract String getPreferenceKey();
-
- /**
- * @return the default default text color
- *
- */
- public abstract RGB getDefaultDefaultTextColor();
-
- /**
- * @return the default default text color
- */
- public RGB getDefaultTextColor() {
- return findRGB(PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry(),
- getThemeColorKey(),
- getDefaultDefaultTextColor());
- }
-
- /**
- * @return <code>true</code> if the text attribute bold is set by default
- */
- public abstract boolean isBoldByDefault();
-
- /**
- * @return <code>true</code> if the text attribute italic is set by default
- */
- public abstract boolean isItalicByDefault();
-
- /**
- * @return <code>true</code> if the text attribute strikethrough is set by default
- *
- */
- public boolean isStrikethroughByDefault() {
- return false;
- }
-
- /**
- * @return <code>true</code> if the text attribute underline is set by default
- *
- */
- public boolean isUnderlineByDefault() {
- return false;
- }
-
- /**
- * @return <code>true</code> if the text attribute italic is enabled by default
- */
- public abstract boolean isEnabledByDefault();
-
- /**
- * @return the display name
- */
- public abstract String getDisplayName();
-
- /**
- * Returns <code>true</code> iff the semantic highlighting consumes the semantic token.
- * <p>
- * NOTE: Implementors are not allowed to keep a reference on the token or on any object
- * retrieved from the token.
- * </p>
- *
- * @param token the semantic token for a {@link org.eclipse.wst.jsdt.core.dom.SimpleName}
- * @return <code>true</code> iff the semantic highlighting consumes the semantic token
- */
- public abstract boolean consumes(SemanticToken token);
-
- /**
- * Returns <code>true</code> iff the semantic highlighting consumes the
- * semantic token.
- * <p>
- * NOTE: Implementors are not allowed to keep a reference on the token or on
- * any object retrieved from the token.
- * </p>
- * @param token the semantic token for a
- * {@link org.eclipse.wst.jsdt.core.dom.NumberLiteral},
- * {@link org.eclipse.wst.jsdt.core.dom.BooleanLiteral} or
- * {@link org.eclipse.wst.jsdt.core.dom.CharacterLiteral}
- * @return <code>true</code> iff the semantic highlighting consumes the
- * semantic token
- */
- public boolean consumesLiteral(SemanticToken token) {
- return false;
- }
-
- private String getThemeColorKey() {
- return JavaScriptUI.ID_PLUGIN + "." + getPreferenceKey() + "Highlighting"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- /**
- * Returns the RGB for the given key in the given color registry.
- *
- * @param registry the color registry
- * @param key the key for the constant in the registry
- * @param defaultRGB the default RGB if no entry is found
- * @return RGB the RGB
- *
- */
- private static RGB findRGB(ColorRegistry registry, String key, RGB defaultRGB) {
- RGB rgb= registry.getRGB(key);
- if (rgb != null)
- return rgb;
- return defaultRGB;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingManager.java
deleted file mode 100644
index 187537cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingManager.java
+++ /dev/null
@@ -1,627 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.StringConverter;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextAttribute;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaPresentationReconciler;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IColorManagerExtension;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-/**
- * Semantic highlighting manager
- *
- *
- */
-public class SemanticHighlightingManager implements IPropertyChangeListener {
-
- /**
- * Highlighting.
- */
- static class Highlighting { // TODO: rename to HighlightingStyle
-
- /** Text attribute */
- private TextAttribute fTextAttribute;
- /** Enabled state */
- private boolean fIsEnabled;
-
- /**
- * Initialize with the given text attribute.
- * @param textAttribute The text attribute
- * @param isEnabled the enabled state
- */
- public Highlighting(TextAttribute textAttribute, boolean isEnabled) {
- setTextAttribute(textAttribute);
- setEnabled(isEnabled);
- }
-
- /**
- * @return Returns the text attribute.
- */
- public TextAttribute getTextAttribute() {
- return fTextAttribute;
- }
-
- /**
- * @param textAttribute The background to set.
- */
- public void setTextAttribute(TextAttribute textAttribute) {
- fTextAttribute= textAttribute;
- }
-
- /**
- * @return the enabled state
- */
- public boolean isEnabled() {
- return fIsEnabled;
- }
-
- /**
- * @param isEnabled the new enabled state
- */
- public void setEnabled(boolean isEnabled) {
- fIsEnabled= isEnabled;
- }
- }
-
- /**
- * Highlighted Positions.
- */
- static class HighlightedPosition extends Position {
-
- /** Highlighting of the position */
- private Highlighting fStyle;
-
- /** Lock object */
- private Object fLock;
-
- /**
- * Initialize the styled positions with the given offset, length and foreground color.
- *
- * @param offset The position offset
- * @param length The position length
- * @param highlighting The position's highlighting
- * @param lock The lock object
- */
- public HighlightedPosition(int offset, int length, Highlighting highlighting, Object lock) {
- super(offset, length);
- fStyle= highlighting;
- fLock= lock;
- }
-
- /**
- * @return Returns a corresponding style range.
- */
- public StyleRange createStyleRange() {
- int len= 0;
- if (fStyle.isEnabled())
- len= getLength();
-
- TextAttribute textAttribute= fStyle.getTextAttribute();
- int style= textAttribute.getStyle();
- int fontStyle= style & (SWT.ITALIC | SWT.BOLD | SWT.NORMAL);
- StyleRange styleRange= new StyleRange(getOffset(), len, textAttribute.getForeground(), textAttribute.getBackground(), fontStyle);
- styleRange.strikeout= (style & TextAttribute.STRIKETHROUGH) != 0;
- styleRange.underline= (style & TextAttribute.UNDERLINE) != 0;
-
- return styleRange;
- }
-
- /**
- * Uses reference equality for the highlighting.
- *
- * @param off The offset
- * @param len The length
- * @param highlighting The highlighting
- * @return <code>true</code> iff the given offset, length and highlighting are equal to the internal ones.
- */
- public boolean isEqual(int off, int len, Highlighting highlighting) {
- synchronized (fLock) {
- return !isDeleted() && getOffset() == off && getLength() == len && fStyle == highlighting;
- }
- }
-
- /**
- * Is this position contained in the given range (inclusive)? Synchronizes on position updater.
- *
- * @param off The range offset
- * @param len The range length
- * @return <code>true</code> iff this position is not delete and contained in the given range.
- */
- public boolean isContained(int off, int len) {
- synchronized (fLock) {
- return !isDeleted() && off <= getOffset() && off + len >= getOffset() + getLength();
- }
- }
-
- public void update(int off, int len) {
- synchronized (fLock) {
- super.setOffset(off);
- super.setLength(len);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.Position#setLength(int)
- */
- public void setLength(int length) {
- synchronized (fLock) {
- super.setLength(length);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.Position#setOffset(int)
- */
- public void setOffset(int offset) {
- synchronized (fLock) {
- super.setOffset(offset);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.Position#delete()
- */
- public void delete() {
- synchronized (fLock) {
- super.delete();
- }
- }
-
- /*
- * @see org.eclipse.jface.text.Position#undelete()
- */
- public void undelete() {
- synchronized (fLock) {
- super.undelete();
- }
- }
-
- /**
- * @return Returns the highlighting.
- */
- public Highlighting getHighlighting() {
- return fStyle;
- }
- }
-
- /**
- * Highlighted ranges.
- */
- public static class HighlightedRange extends Region {
- /** The highlighting key as returned by {@link SemanticHighlighting#getPreferenceKey()}. */
- private String fKey;
-
- /**
- * Initialize with the given offset, length and highlighting key.
- *
- * @param offset
- * @param length
- * @param key the highlighting key as returned by {@link SemanticHighlighting#getPreferenceKey()}
- */
- public HighlightedRange(int offset, int length, String key) {
- super(offset, length);
- fKey= key;
- }
-
- /**
- * @return the highlighting key as returned by {@link SemanticHighlighting#getPreferenceKey()}
- */
- public String getKey() {
- return fKey;
- }
-
- /*
- * @see org.eclipse.jface.text.Region#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- return super.equals(o) && o instanceof HighlightedRange && fKey.equals(((HighlightedRange)o).getKey());
- }
-
- /*
- * @see org.eclipse.jface.text.Region#hashCode()
- */
- public int hashCode() {
- return super.hashCode() | fKey.hashCode();
- }
- }
-
- /** Semantic highlighting presenter */
- private SemanticHighlightingPresenter fPresenter;
- /** Semantic highlighting reconciler */
- private SemanticHighlightingReconciler fReconciler;
-
- /** Semantic highlightings */
- private SemanticHighlighting[] fSemanticHighlightings;
- /** Highlightings */
- private Highlighting[] fHighlightings;
-
- /** The editor */
- private JavaEditor fEditor;
- /** The source viewer */
- private JavaSourceViewer fSourceViewer;
- /** The color manager */
- private IColorManager fColorManager;
- /** The preference store */
- private IPreferenceStore fPreferenceStore;
- /** The source viewer configuration */
- private JavaScriptSourceViewerConfiguration fConfiguration;
- /** The presentation reconciler */
- private JavaPresentationReconciler fPresentationReconciler;
-
- /** The hard-coded ranges */
- private HighlightedRange[][] fHardcodedRanges;
-
- /**
- * Install the semantic highlighting on the given editor infrastructure
- *
- * @param editor The Java editor
- * @param sourceViewer The source viewer
- * @param colorManager The color manager
- * @param preferenceStore The preference store
- */
- public void install(JavaEditor editor, JavaSourceViewer sourceViewer, IColorManager colorManager, IPreferenceStore preferenceStore) {
- fEditor= editor;
- fSourceViewer= sourceViewer;
- fColorManager= colorManager;
- fPreferenceStore= preferenceStore;
- if (fEditor != null) {
- fConfiguration= editor.createJavaSourceViewerConfiguration();
- fPresentationReconciler= (JavaPresentationReconciler) fConfiguration.getPresentationReconciler(sourceViewer);
- } else {
- fConfiguration= null;
- fPresentationReconciler= null;
- }
-
- fPreferenceStore.addPropertyChangeListener(this);
-
- if (isEnabled())
- enable();
- }
-
- /**
- * Install the semantic highlighting on the given source viewer infrastructure. No reconciliation will be performed.
- *
- * @param sourceViewer the source viewer
- * @param colorManager the color manager
- * @param preferenceStore the preference store
- * @param hardcodedRanges the hard-coded ranges to be highlighted
- */
- public void install(JavaSourceViewer sourceViewer, IColorManager colorManager, IPreferenceStore preferenceStore, HighlightedRange[][] hardcodedRanges) {
- fHardcodedRanges= hardcodedRanges;
- install(null, sourceViewer, colorManager, preferenceStore);
- }
-
- /**
- * Enable semantic highlighting.
- */
- private void enable() {
- initializeHighlightings();
-
- fPresenter= new SemanticHighlightingPresenter();
- fPresenter.install(fSourceViewer, fPresentationReconciler);
-
- if (fEditor != null) {
- fReconciler= new SemanticHighlightingReconciler();
- fReconciler.install(fEditor, fSourceViewer, fPresenter, fSemanticHighlightings, fHighlightings);
- } else {
- fPresenter.updatePresentation(null, createHardcodedPositions(), new HighlightedPosition[0]);
- }
- }
-
- /**
- * Computes the hard-coded positions from the hard-coded ranges
- *
- * @return the hard-coded positions
- */
- private HighlightedPosition[] createHardcodedPositions() {
- List positions= new ArrayList();
- for (int i= 0; i < fHardcodedRanges.length; i++) {
- HighlightedRange range= null;
- Highlighting hl= null;
- for (int j= 0; j < fHardcodedRanges[i].length; j++ ) {
- hl= getHighlighting(fHardcodedRanges[i][j].getKey());
- if (hl.isEnabled()) {
- range= fHardcodedRanges[i][j];
- break;
- }
- }
-
- if (range != null)
- positions.add(fPresenter.createHighlightedPosition(range.getOffset(), range.getLength(), hl));
- }
- return (HighlightedPosition[]) positions.toArray(new HighlightedPosition[positions.size()]);
- }
-
- /**
- * Returns the highlighting corresponding to the given key.
- *
- * @param key the highlighting key as returned by {@link SemanticHighlighting#getPreferenceKey()}
- * @return the corresponding highlighting
- */
- private Highlighting getHighlighting(String key) {
- for (int i= 0; i < fSemanticHighlightings.length; i++) {
- SemanticHighlighting semanticHighlighting= fSemanticHighlightings[i];
- if (key.equals(semanticHighlighting.getPreferenceKey()))
- return fHighlightings[i];
- }
- return null;
- }
-
- /**
- * Uninstall the semantic highlighting
- */
- public void uninstall() {
- disable();
-
- if (fPreferenceStore != null) {
- fPreferenceStore.removePropertyChangeListener(this);
- fPreferenceStore= null;
- }
-
- fEditor= null;
- fSourceViewer= null;
- fColorManager= null;
- fConfiguration= null;
- fPresentationReconciler= null;
- fHardcodedRanges= null;
- }
-
- /**
- * Disable semantic highlighting.
- */
- private void disable() {
- if (fReconciler != null) {
- fReconciler.uninstall();
- fReconciler= null;
- }
-
- if (fPresenter != null) {
- fPresenter.uninstall();
- fPresenter= null;
- }
-
- if (fSemanticHighlightings != null)
- disposeHighlightings();
- }
-
- /**
- * @return <code>true</code> iff semantic highlighting is enabled in the preferences
- */
- private boolean isEnabled() {
- return SemanticHighlightings.isEnabled(fPreferenceStore);
- }
-
- /**
- * Initialize semantic highlightings.
- */
- private void initializeHighlightings() {
- fSemanticHighlightings= SemanticHighlightings.getSemanticHighlightings();
- fHighlightings= new Highlighting[fSemanticHighlightings.length];
-
- for (int i= 0, n= fSemanticHighlightings.length; i < n; i++) {
- SemanticHighlighting semanticHighlighting= fSemanticHighlightings[i];
- String colorKey= SemanticHighlightings.getColorPreferenceKey(semanticHighlighting);
- addColor(colorKey);
-
- String boldKey= SemanticHighlightings.getBoldPreferenceKey(semanticHighlighting);
- int style= fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL;
-
- String italicKey= SemanticHighlightings.getItalicPreferenceKey(semanticHighlighting);
- if (fPreferenceStore.getBoolean(italicKey))
- style |= SWT.ITALIC;
-
- String strikethroughKey= SemanticHighlightings.getStrikethroughPreferenceKey(semanticHighlighting);
- if (fPreferenceStore.getBoolean(strikethroughKey))
- style |= TextAttribute.STRIKETHROUGH;
-
- String underlineKey= SemanticHighlightings.getUnderlinePreferenceKey(semanticHighlighting);
- if (fPreferenceStore.getBoolean(underlineKey))
- style |= TextAttribute.UNDERLINE;
-
- boolean isEnabled= fPreferenceStore.getBoolean(SemanticHighlightings.getEnabledPreferenceKey(semanticHighlighting));
-
- fHighlightings[i]= new Highlighting(new TextAttribute(fColorManager.getColor(PreferenceConverter.getColor(fPreferenceStore, colorKey)), null, style), isEnabled);
- }
- }
-
- /**
- * Dispose the semantic highlightings.
- */
- private void disposeHighlightings() {
- for (int i= 0, n= fSemanticHighlightings.length; i < n; i++)
- removeColor(SemanticHighlightings.getColorPreferenceKey(fSemanticHighlightings[i]));
-
- fSemanticHighlightings= null;
- fHighlightings= null;
- }
-
- /*
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- handlePropertyChangeEvent(event);
- }
-
- /**
- * Handle the given property change event
- *
- * @param event The event
- */
- private void handlePropertyChangeEvent(PropertyChangeEvent event) {
- if (fPreferenceStore == null)
- return; // Uninstalled during event notification
-
- if (fConfiguration != null)
- fConfiguration.handlePropertyChangeEvent(event);
-
- if (SemanticHighlightings.affectsEnablement(fPreferenceStore, event)) {
- if (isEnabled())
- enable();
- else
- disable();
- }
-
- if (!isEnabled())
- return;
-
- boolean refreshNeeded= false;
-
- for (int i= 0, n= fSemanticHighlightings.length; i < n; i++) {
- SemanticHighlighting semanticHighlighting= fSemanticHighlightings[i];
-
- String colorKey= SemanticHighlightings.getColorPreferenceKey(semanticHighlighting);
- if (colorKey.equals(event.getProperty())) {
- adaptToTextForegroundChange(fHighlightings[i], event);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
-
- String boldKey= SemanticHighlightings.getBoldPreferenceKey(semanticHighlighting);
- if (boldKey.equals(event.getProperty())) {
- adaptToTextStyleChange(fHighlightings[i], event, SWT.BOLD);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
-
- String italicKey= SemanticHighlightings.getItalicPreferenceKey(semanticHighlighting);
- if (italicKey.equals(event.getProperty())) {
- adaptToTextStyleChange(fHighlightings[i], event, SWT.ITALIC);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
-
- String strikethroughKey= SemanticHighlightings.getStrikethroughPreferenceKey(semanticHighlighting);
- if (strikethroughKey.equals(event.getProperty())) {
- adaptToTextStyleChange(fHighlightings[i], event, TextAttribute.STRIKETHROUGH);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
-
- String underlineKey= SemanticHighlightings.getUnderlinePreferenceKey(semanticHighlighting);
- if (underlineKey.equals(event.getProperty())) {
- adaptToTextStyleChange(fHighlightings[i], event, TextAttribute.UNDERLINE);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
-
- String enabledKey= SemanticHighlightings.getEnabledPreferenceKey(semanticHighlighting);
- if (enabledKey.equals(event.getProperty())) {
- adaptToEnablementChange(fHighlightings[i], event);
- fPresenter.highlightingStyleChanged(fHighlightings[i]);
- refreshNeeded= true;
- continue;
- }
- }
-
- if (refreshNeeded && fReconciler != null)
- fReconciler.refresh();
- }
-
- private void adaptToEnablementChange(Highlighting highlighting, PropertyChangeEvent event) {
- Object value= event.getNewValue();
- boolean eventValue;
- if (value instanceof Boolean)
- eventValue= ((Boolean) value).booleanValue();
- else if (IPreferenceStore.TRUE.equals(value))
- eventValue= true;
- else
- eventValue= false;
- highlighting.setEnabled(eventValue);
- }
-
- private void adaptToTextForegroundChange(Highlighting highlighting, PropertyChangeEvent event) {
- RGB rgb= null;
-
- Object value= event.getNewValue();
- if (value instanceof RGB)
- rgb= (RGB) value;
- else if (value instanceof String)
- rgb= StringConverter.asRGB((String) value);
-
- if (rgb != null) {
-
- String property= event.getProperty();
- Color color= fColorManager.getColor(property);
-
- if ((color == null || !rgb.equals(color.getRGB())) && fColorManager instanceof IColorManagerExtension) {
- IColorManagerExtension ext= (IColorManagerExtension) fColorManager;
- ext.unbindColor(property);
- ext.bindColor(property, rgb);
- color= fColorManager.getColor(property);
- }
-
- TextAttribute oldAttr= highlighting.getTextAttribute();
- highlighting.setTextAttribute(new TextAttribute(color, oldAttr.getBackground(), oldAttr.getStyle()));
- }
- }
-
- private void adaptToTextStyleChange(Highlighting highlighting, PropertyChangeEvent event, int styleAttribute) {
- boolean eventValue= false;
- Object value= event.getNewValue();
- if (value instanceof Boolean)
- eventValue= ((Boolean) value).booleanValue();
- else if (IPreferenceStore.TRUE.equals(value))
- eventValue= true;
-
- TextAttribute oldAttr= highlighting.getTextAttribute();
- boolean activeValue= (oldAttr.getStyle() & styleAttribute) == styleAttribute;
-
- if (activeValue != eventValue)
- highlighting.setTextAttribute(new TextAttribute(oldAttr.getForeground(), oldAttr.getBackground(), eventValue ? oldAttr.getStyle() | styleAttribute : oldAttr.getStyle() & ~styleAttribute));
- }
-
- private void addColor(String colorKey) {
- if (fColorManager != null && colorKey != null && fColorManager.getColor(colorKey) == null) {
- RGB rgb= PreferenceConverter.getColor(fPreferenceStore, colorKey);
- if (fColorManager instanceof IColorManagerExtension) {
- IColorManagerExtension ext= (IColorManagerExtension) fColorManager;
- ext.unbindColor(colorKey);
- ext.bindColor(colorKey, rgb);
- }
- }
- }
-
- private void removeColor(String colorKey) {
- if (fColorManager instanceof IColorManagerExtension)
- ((IColorManagerExtension) fColorManager).unbindColor(colorKey);
- }
-
- /**
- * Returns this hightlighter's reconciler.
- *
- * @return the semantic highlighter reconciler or <code>null</code> if none
- *
- */
- public SemanticHighlightingReconciler getReconciler() {
- return fReconciler;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingPresenter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingPresenter.java
deleted file mode 100644
index b0054bc5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingPresenter.java
+++ /dev/null
@@ -1,772 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ISynchronizable;
-import org.eclipse.jface.text.ITextInputListener;
-import org.eclipse.jface.text.ITextPresentationListener;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedPosition;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager.Highlighting;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaPresentationReconciler;
-
-
-/**
- * Semantic highlighting presenter - UI thread implementation.
- *
- *
- */
-public class SemanticHighlightingPresenter implements ITextPresentationListener, ITextInputListener, IDocumentListener {
-
- /**
- * Semantic highlighting position updater.
- */
- private class HighlightingPositionUpdater implements IPositionUpdater {
-
- /** The position category. */
- private final String fCategory;
-
- /**
- * Creates a new updater for the given <code>category</code>.
- *
- * @param category the new category.
- */
- public HighlightingPositionUpdater(String category) {
- fCategory= category;
- }
-
- /*
- * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
- */
- public void update(DocumentEvent event) {
-
- int eventOffset= event.getOffset();
- int eventOldLength= event.getLength();
- int eventEnd= eventOffset + eventOldLength;
-
- try {
- Position[] positions= event.getDocument().getPositions(fCategory);
-
- for (int i= 0; i != positions.length; i++) {
-
- HighlightedPosition position= (HighlightedPosition) positions[i];
-
- // Also update deleted positions because they get deleted by the background thread and removed/invalidated only in the UI runnable
-// if (position.isDeleted())
-// continue;
-
- int offset= position.getOffset();
- int length= position.getLength();
- int end= offset + length;
-
- if (offset > eventEnd)
- updateWithPrecedingEvent(position, event);
- else if (end < eventOffset)
- updateWithSucceedingEvent(position, event);
- else if (offset <= eventOffset && end >= eventEnd)
- updateWithIncludedEvent(position, event);
- else if (offset <= eventOffset)
- updateWithOverEndEvent(position, event);
- else if (end >= eventEnd)
- updateWithOverStartEvent(position, event);
- else
- updateWithIncludingEvent(position, event);
- }
- } catch (BadPositionCategoryException e) {
- // ignore and return
- }
- }
-
- /**
- * Update the given position with the given event. The event precedes the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithPrecedingEvent(HighlightedPosition position, DocumentEvent event) {
- String newText= event.getText();
- int eventNewLength= newText != null ? newText.length() : 0;
- int deltaLength= eventNewLength - event.getLength();
-
- position.setOffset(position.getOffset() + deltaLength);
- }
-
- /**
- * Update the given position with the given event. The event succeeds the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithSucceedingEvent(HighlightedPosition position, DocumentEvent event) {
- }
-
- /**
- * Update the given position with the given event. The event is included by the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithIncludedEvent(HighlightedPosition position, DocumentEvent event) {
- int eventOffset= event.getOffset();
- String newText= event.getText();
- if (newText == null)
- newText= ""; //$NON-NLS-1$
- int eventNewLength= newText.length();
-
- int deltaLength= eventNewLength - event.getLength();
-
- int offset= position.getOffset();
- int length= position.getLength();
- int end= offset + length;
-
- int includedLength= 0;
- while (includedLength < eventNewLength && Character.isJavaIdentifierPart(newText.charAt(includedLength)))
- includedLength++;
- if (includedLength == eventNewLength)
- position.setLength(length + deltaLength);
- else {
- int newLeftLength= eventOffset - offset + includedLength;
-
- int excludedLength= eventNewLength;
- while (excludedLength > 0 && Character.isJavaIdentifierPart(newText.charAt(excludedLength - 1)))
- excludedLength--;
- int newRightOffset= eventOffset + excludedLength;
- int newRightLength= end + deltaLength - newRightOffset;
-
- if (newRightLength == 0) {
- position.setLength(newLeftLength);
- } else {
- if (newLeftLength == 0) {
- position.update(newRightOffset, newRightLength);
- } else {
- position.setLength(newLeftLength);
- addPositionFromUI(newRightOffset, newRightLength, position.getHighlighting());
- }
- }
- }
- }
-
- /**
- * Update the given position with the given event. The event overlaps with the end of the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithOverEndEvent(HighlightedPosition position, DocumentEvent event) {
- String newText= event.getText();
- if (newText == null)
- newText= ""; //$NON-NLS-1$
- int eventNewLength= newText.length();
-
- int includedLength= 0;
- while (includedLength < eventNewLength && Character.isJavaIdentifierPart(newText.charAt(includedLength)))
- includedLength++;
- position.setLength(event.getOffset() - position.getOffset() + includedLength);
- }
-
- /**
- * Update the given position with the given event. The event overlaps with the start of the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithOverStartEvent(HighlightedPosition position, DocumentEvent event) {
- int eventOffset= event.getOffset();
- int eventEnd= eventOffset + event.getLength();
-
- String newText= event.getText();
- if (newText == null)
- newText= ""; //$NON-NLS-1$
- int eventNewLength= newText.length();
-
- int excludedLength= eventNewLength;
- while (excludedLength > 0 && Character.isJavaIdentifierPart(newText.charAt(excludedLength - 1)))
- excludedLength--;
- int deleted= eventEnd - position.getOffset();
- int inserted= eventNewLength - excludedLength;
- position.update(eventOffset + excludedLength, position.getLength() - deleted + inserted);
- }
-
- /**
- * Update the given position with the given event. The event includes the position.
- *
- * @param position The position
- * @param event The event
- */
- private void updateWithIncludingEvent(HighlightedPosition position, DocumentEvent event) {
- position.delete();
- position.update(event.getOffset(), 0);
- }
- }
-
- /** Position updater */
- private IPositionUpdater fPositionUpdater= new HighlightingPositionUpdater(getPositionCategory());
-
- /** The source viewer this semantic highlighting reconciler is installed on */
- private JavaSourceViewer fSourceViewer;
- /** The background presentation reconciler */
- private JavaPresentationReconciler fPresentationReconciler;
-
- /** UI's current highlighted positions - can contain <code>null</code> elements */
- private List fPositions= new ArrayList();
- /** UI position lock */
- private Object fPositionLock= new Object();
-
- /** <code>true</code> iff the current reconcile is canceled. */
- private boolean fIsCanceled= false;
-
- /**
- * Creates and returns a new highlighted position with the given offset, length and highlighting.
- * <p>
- * NOTE: Also called from background thread.
- * </p>
- *
- * @param offset The offset
- * @param length The length
- * @param highlighting The highlighting
- * @return The new highlighted position
- */
- public HighlightedPosition createHighlightedPosition(int offset, int length, Highlighting highlighting) {
- // TODO: reuse deleted positions
- return new HighlightedPosition(offset, length, highlighting, fPositionUpdater);
- }
-
- /**
- * Adds all current positions to the given list.
- * <p>
- * NOTE: Called from background thread.
- * </p>
- *
- * @param list The list
- */
- public void addAllPositions(List list) {
- synchronized (fPositionLock) {
- list.addAll(fPositions);
- }
- }
-
- /**
- * Create a text presentation in the background.
- * <p>
- * NOTE: Called from background thread.
- * </p>
- *
- * @param addedPositions the added positions
- * @param removedPositions the removed positions
- * @return the text presentation or <code>null</code>, if reconciliation should be canceled
- */
- public TextPresentation createPresentation(List addedPositions, List removedPositions) {
- JavaSourceViewer sourceViewer= fSourceViewer;
- JavaPresentationReconciler presentationReconciler= fPresentationReconciler;
- if (sourceViewer == null || presentationReconciler == null)
- return null;
-
- if (isCanceled())
- return null;
-
- IDocument document= sourceViewer.getDocument();
- if (document == null)
- return null;
-
- int minStart= Integer.MAX_VALUE;
- int maxEnd= Integer.MIN_VALUE;
- for (int i= 0, n= removedPositions.size(); i < n; i++) {
- Position position= (Position) removedPositions.get(i);
- int offset= position.getOffset();
- minStart= Math.min(minStart, offset);
- maxEnd= Math.max(maxEnd, offset + position.getLength());
- }
- for (int i= 0, n= addedPositions.size(); i < n; i++) {
- Position position= (Position) addedPositions.get(i);
- int offset= position.getOffset();
- minStart= Math.min(minStart, offset);
- maxEnd= Math.max(maxEnd, offset + position.getLength());
- }
-
- if (minStart < maxEnd)
- try {
- return presentationReconciler.createRepairDescription(new Region(minStart, maxEnd - minStart), document);
- } catch (RuntimeException e) {
- // Assume concurrent modification from UI thread
- }
-
- return null;
- }
-
- /**
- * Create a runnable for updating the presentation.
- * <p>
- * NOTE: Called from background thread.
- * </p>
- * @param textPresentation the text presentation
- * @param addedPositions the added positions
- * @param removedPositions the removed positions
- * @return the runnable or <code>null</code>, if reconciliation should be canceled
- */
- public Runnable createUpdateRunnable(final TextPresentation textPresentation, List addedPositions, List removedPositions) {
- if (fSourceViewer == null || textPresentation == null)
- return null;
-
- // TODO: do clustering of positions and post multiple fast runnables
- final HighlightedPosition[] added= new SemanticHighlightingManager.HighlightedPosition[addedPositions.size()];
- addedPositions.toArray(added);
- final SemanticHighlightingManager.HighlightedPosition[] removed= new SemanticHighlightingManager.HighlightedPosition[removedPositions.size()];
- removedPositions.toArray(removed);
-
- if (isCanceled())
- return null;
-
- Runnable runnable= new Runnable() {
- public void run() {
- updatePresentation(textPresentation, added, removed);
- }
- };
- return runnable;
- }
-
- /**
- * Invalidate the presentation of the positions based on the given added positions and the existing deleted positions.
- * Also unregisters the deleted positions from the document and patches the positions of this presenter.
- * <p>
- * NOTE: Indirectly called from background thread by UI runnable.
- * </p>
- * @param textPresentation the text presentation or <code>null</code>, if the presentation should computed in the UI thread
- * @param addedPositions the added positions
- * @param removedPositions the removed positions
- */
- public void updatePresentation(TextPresentation textPresentation, HighlightedPosition[] addedPositions, HighlightedPosition[] removedPositions) {
- if (fSourceViewer == null)
- return;
-
-// checkOrdering("added positions: ", Arrays.asList(addedPositions)); //$NON-NLS-1$
-// checkOrdering("removed positions: ", Arrays.asList(removedPositions)); //$NON-NLS-1$
-// checkOrdering("old positions: ", fPositions); //$NON-NLS-1$
-
- // TODO: double-check consistency with document.getPositions(...)
- // TODO: reuse removed positions
- if (isCanceled())
- return;
-
- IDocument document= fSourceViewer.getDocument();
- if (document == null)
- return;
-
- String positionCategory= getPositionCategory();
-
- List removedPositionsList= Arrays.asList(removedPositions);
-
- try {
- synchronized (fPositionLock) {
- List oldPositions= fPositions;
- int newSize= Math.max(fPositions.size() + addedPositions.length - removedPositions.length, 10);
-
- /*
- * The following loop is a kind of merge sort: it merges two List<Position>, each
- * sorted by position.offset, into one new list. The first of the two is the
- * previous list of positions (oldPositions), from which any deleted positions get
- * removed on the fly. The second of two is the list of added positions. The result
- * is stored in newPositions.
- */
- List newPositions= new ArrayList(newSize);
- Position position= null;
- Position addedPosition= null;
- for (int i= 0, j= 0, n= oldPositions.size(), m= addedPositions.length; i < n || position != null || j < m || addedPosition != null;) {
- // loop variant: i + j < old(i + j)
-
- // a) find the next non-deleted Position from the old list
- while (position == null && i < n) {
- position= (Position) oldPositions.get(i++);
- if (position.isDeleted() || contain(removedPositionsList, position)) {
- document.removePosition(positionCategory, position);
- position= null;
- }
- }
-
- // b) find the next Position from the added list
- if (addedPosition == null && j < m) {
- addedPosition= addedPositions[j++];
- document.addPosition(positionCategory, addedPosition);
- }
-
- // c) merge: add the next of position/addedPosition with the lower offset
- if (position != null) {
- if (addedPosition != null)
- if (position.getOffset() <= addedPosition.getOffset()) {
- newPositions.add(position);
- position= null;
- } else {
- newPositions.add(addedPosition);
- addedPosition= null;
- }
- else {
- newPositions.add(position);
- position= null;
- }
- } else if (addedPosition != null) {
- newPositions.add(addedPosition);
- addedPosition= null;
- }
- }
- fPositions= newPositions;
- }
- } catch (BadPositionCategoryException e) {
- // Should not happen
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- // Should not happen
- JavaScriptPlugin.log(e);
- }
-// checkOrdering("new positions: ", fPositions); //$NON-NLS-1$
-
- if (textPresentation != null)
- fSourceViewer.changeTextPresentation(textPresentation, false);
- else
- fSourceViewer.invalidateTextPresentation();
- }
-
-// private void checkOrdering(String s, List positions) {
-// Position previous= null;
-// for (int i= 0, n= positions.size(); i < n; i++) {
-// Position current= (Position) positions.get(i);
-// if (previous != null && previous.getOffset() + previous.getLength() > current.getOffset())
-// return;
-// }
-// }
-
- /**
- * Returns <code>true</code> iff the positions contain the position.
- * @param positions the positions, must be ordered by offset but may overlap
- * @param position the position
- * @return <code>true</code> iff the positions contain the position
- */
- private boolean contain(List positions, Position position) {
- return indexOf(positions, position) != -1;
- }
-
- /**
- * Returns index of the position in the positions, <code>-1</code> if not found.
- * @param positions the positions, must be ordered by offset but may overlap
- * @param position the position
- * @return the index
- */
- private int indexOf(List positions, Position position) {
- int index= computeIndexAtOffset(positions, position.getOffset());
- int size= positions.size();
- while (index < size) {
- if (positions.get(index) == position)
- return index;
- index++;
- }
- return -1;
- }
-
- /**
- * Insert the given position in <code>fPositions</code>, s.t. the offsets remain in linear order.
- *
- * @param position The position for insertion
- */
- private void insertPosition(Position position) {
- int i= computeIndexAfterOffset(fPositions, position.getOffset());
- fPositions.add(i, position);
- }
-
- /**
- * Returns the index of the first position with an offset greater than the given offset.
- *
- * @param positions the positions, must be ordered by offset and must not overlap
- * @param offset the offset
- * @return the index of the last position with an offset greater than the given offset
- */
- private int computeIndexAfterOffset(List positions, int offset) {
- int i= -1;
- int j= positions.size();
- while (j - i > 1) {
- int k= (i + j) >> 1;
- Position position= (Position) positions.get(k);
- if (position.getOffset() > offset)
- j= k;
- else
- i= k;
- }
- return j;
- }
-
- /**
- * Returns the index of the first position with an offset equal or greater than the given offset.
- *
- * @param positions the positions, must be ordered by offset and must not overlap
- * @param offset the offset
- * @return the index of the last position with an offset equal or greater than the given offset
- */
- private int computeIndexAtOffset(List positions, int offset) {
- int i= -1;
- int j= positions.size();
- while (j - i > 1) {
- int k= (i + j) >> 1;
- Position position= (Position) positions.get(k);
- if (position.getOffset() >= offset)
- j= k;
- else
- i= k;
- }
- return j;
- }
-
- /*
- * @see org.eclipse.jface.text.ITextPresentationListener#applyTextPresentation(org.eclipse.jface.text.TextPresentation)
- */
- public void applyTextPresentation(TextPresentation textPresentation) {
- IRegion region= textPresentation.getExtent();
- int i= computeIndexAtOffset(fPositions, region.getOffset()), n= computeIndexAtOffset(fPositions, region.getOffset() + region.getLength());
- if (n - i > 2) {
- List ranges= new ArrayList(n - i);
- for (; i < n; i++) {
- HighlightedPosition position= (HighlightedPosition) fPositions.get(i);
- if (!position.isDeleted())
- ranges.add(position.createStyleRange());
- }
- StyleRange[] array= new StyleRange[ranges.size()];
- array= (StyleRange[]) ranges.toArray(array);
- textPresentation.replaceStyleRanges(array);
- } else {
- for (; i < n; i++) {
- HighlightedPosition position= (HighlightedPosition) fPositions.get(i);
- if (!position.isDeleted())
- textPresentation.replaceStyleRange(position.createStyleRange());
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
- setCanceled(true);
- releaseDocument(oldInput);
- resetState();
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
- manageDocument(newInput);
- }
-
- /*
- * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
- */
- public void documentAboutToBeChanged(DocumentEvent event) {
- setCanceled(true);
- }
-
- /*
- * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
- */
- public void documentChanged(DocumentEvent event) {
- }
-
- /**
- * @return Returns <code>true</code> iff the current reconcile is canceled.
- * <p>
- * NOTE: Also called from background thread.
- * </p>
- */
- public boolean isCanceled() {
- IDocument document= fSourceViewer != null ? fSourceViewer.getDocument() : null;
- if (document == null)
- return fIsCanceled;
-
- synchronized (getLockObject(document)) {
- return fIsCanceled;
- }
- }
-
- /**
- * Set whether or not the current reconcile is canceled.
- *
- * @param isCanceled <code>true</code> iff the current reconcile is canceled
- */
- public void setCanceled(boolean isCanceled) {
- IDocument document= fSourceViewer != null ? fSourceViewer.getDocument() : null;
- if (document == null) {
- fIsCanceled= isCanceled;
- return;
- }
-
- synchronized (getLockObject(document)) {
- fIsCanceled= isCanceled;
- }
- }
-
- /**
- * @param document the document
- * @return the document's lock object
- */
- private Object getLockObject(IDocument document) {
- if (document instanceof ISynchronizable) {
- Object lock= ((ISynchronizable)document).getLockObject();
- if (lock != null)
- return lock;
- }
- return document;
- }
-
- /**
- * Install this presenter on the given source viewer and background presentation
- * reconciler.
- *
- * @param sourceViewer the source viewer
- * @param backgroundPresentationReconciler the background presentation reconciler,
- * can be <code>null</code>, in that case {@link SemanticHighlightingPresenter#createPresentation(List, List)}
- * should not be called
- */
- public void install(JavaSourceViewer sourceViewer, JavaPresentationReconciler backgroundPresentationReconciler) {
- fSourceViewer= sourceViewer;
- fPresentationReconciler= backgroundPresentationReconciler;
-
- fSourceViewer.prependTextPresentationListener(this);
- fSourceViewer.addTextInputListener(this);
- manageDocument(fSourceViewer.getDocument());
- }
-
- /**
- * Uninstall this presenter.
- */
- public void uninstall() {
- setCanceled(true);
-
- if (fSourceViewer != null) {
- fSourceViewer.removeTextPresentationListener(this);
- releaseDocument(fSourceViewer.getDocument());
- invalidateTextPresentation();
- resetState();
-
- fSourceViewer.removeTextInputListener(this);
- fSourceViewer= null;
- }
- }
-
- /**
- * Invalidate text presentation of positions with the given highlighting.
- *
- * @param highlighting The highlighting
- */
- public void highlightingStyleChanged(Highlighting highlighting) {
- for (int i= 0, n= fPositions.size(); i < n; i++) {
- HighlightedPosition position= (HighlightedPosition) fPositions.get(i);
- if (position.getHighlighting() == highlighting)
- fSourceViewer.invalidateTextPresentation(position.getOffset(), position.getLength());
- }
- }
-
- /**
- * Invalidate text presentation of all positions.
- */
- private void invalidateTextPresentation() {
- for (int i= 0, n= fPositions.size(); i < n; i++) {
- Position position= (Position) fPositions.get(i);
- fSourceViewer.invalidateTextPresentation(position.getOffset(), position.getLength());
- }
- }
-
- /**
- * Add a position with the given range and highlighting unconditionally, only from UI thread.
- * The position will also be registered on the document. The text presentation is not invalidated.
- *
- * @param offset The range offset
- * @param length The range length
- * @param highlighting
- */
- private void addPositionFromUI(int offset, int length, Highlighting highlighting) {
- Position position= createHighlightedPosition(offset, length, highlighting);
- synchronized (fPositionLock) {
- insertPosition(position);
- }
-
- IDocument document= fSourceViewer.getDocument();
- if (document == null)
- return;
- String positionCategory= getPositionCategory();
- try {
- document.addPosition(positionCategory, position);
- } catch (BadLocationException e) {
- // Should not happen
- JavaScriptPlugin.log(e);
- } catch (BadPositionCategoryException e) {
- // Should not happen
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * Reset to initial state.
- */
- private void resetState() {
- synchronized (fPositionLock) {
- fPositions.clear();
- }
- }
-
- /**
- * Start managing the given document.
- *
- * @param document The document
- */
- private void manageDocument(IDocument document) {
- if (document != null) {
- document.addPositionCategory(getPositionCategory());
- document.addPositionUpdater(fPositionUpdater);
- document.addDocumentListener(this);
- }
- }
-
- /**
- * Stop managing the given document.
- *
- * @param document The document
- */
- private void releaseDocument(IDocument document) {
- if (document != null) {
- document.removeDocumentListener(this);
- document.removePositionUpdater(fPositionUpdater);
- try {
- document.removePositionCategory(getPositionCategory());
- } catch (BadPositionCategoryException e) {
- // Should not happen
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /**
- * @return The semantic reconciler position's category.
- */
- private String getPositionCategory() {
- return toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java
deleted file mode 100644
index 860f2e69..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextInputListener;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.CharacterLiteral;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.RegularExpressionLiteral;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedPosition;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager.Highlighting;
-import org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener;
-
-
-/**
- * Semantic highlighting reconciler - Background thread implementation.
- *
- *
- */
-public class SemanticHighlightingReconciler implements IJavaReconcilingListener, ITextInputListener {
-
- /**
- * Collects positions from the AST.
- */
- private class PositionCollector extends GenericVisitor {
-
- /** The semantic token */
- private SemanticToken fToken= new SemanticToken();
-
- /*
- * @see org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor#visitNode(org.eclipse.wst.jsdt.core.dom.ASTNode)
- */
- protected boolean visitNode(ASTNode node) {
- if ((node.getFlags() & ASTNode.MALFORMED) == ASTNode.MALFORMED) {
- retainPositions(node.getStartPosition(), node.getLength());
- return false;
- }
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.BooleanLiteral)
- */
- public boolean visit(BooleanLiteral node) {
- return visitLiteral(node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.CharacterLiteral)
- */
- public boolean visit(CharacterLiteral node) {
- return visitLiteral(node);
- }
-
- public boolean visit(RegularExpressionLiteral node) {
- return visitLiteral(node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.NumberLiteral)
- */
- public boolean visit(NumberLiteral node) {
- return visitLiteral(node);
- }
-
- private boolean visitLiteral(Expression node) {
- fToken.update(node);
- for (int i= 0, n= fJobSemanticHighlightings.length; i < n; i++) {
- SemanticHighlighting semanticHighlighting= fJobSemanticHighlightings[i];
- if (fJobHighlightings[i].isEnabled() && semanticHighlighting.consumesLiteral(fToken)) {
- int offset= node.getStartPosition();
- int length= node.getLength();
- if (offset > -1 && length > 0)
- addPosition(offset, length, fJobHighlightings[i]);
- break;
- }
- }
- fToken.clear();
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.SimpleName)
- */
- public boolean visit(SimpleName node) {
- fToken.update(node);
- for (int i= 0, n= fJobSemanticHighlightings.length; i < n; i++) {
- SemanticHighlighting semanticHighlighting= fJobSemanticHighlightings[i];
- if (fJobHighlightings[i].isEnabled() && semanticHighlighting.consumes(fToken)) {
- int offset= node.getStartPosition();
- int length= node.getLength();
- if (offset > -1 && length > 0)
- addPosition(offset, length, fJobHighlightings[i]);
- break;
- }
- }
- fToken.clear();
- return false;
- }
-
- /**
- * Add a position with the given range and highlighting iff it does not exist already.
- * @param offset The range offset
- * @param length The range length
- * @param highlighting The highlighting
- */
- private void addPosition(int offset, int length, Highlighting highlighting) {
- boolean isExisting= false;
- // TODO: use binary search
- for (int i= 0, n= fRemovedPositions.size(); i < n; i++) {
- HighlightedPosition position= (HighlightedPosition) fRemovedPositions.get(i);
- if (position == null)
- continue;
- if (position.isEqual(offset, length, highlighting)) {
- isExisting= true;
- fRemovedPositions.set(i, null);
- fNOfRemovedPositions--;
- break;
- }
- }
-
- if (!isExisting) {
- Position position= fJobPresenter.createHighlightedPosition(offset, length, highlighting);
- fAddedPositions.add(position);
- }
- }
-
- /**
- * Retain the positions completely contained in the given range.
- * @param offset The range offset
- * @param length The range length
- */
- private void retainPositions(int offset, int length) {
- // TODO: use binary search
- for (int i= 0, n= fRemovedPositions.size(); i < n; i++) {
- HighlightedPosition position= (HighlightedPosition) fRemovedPositions.get(i);
- if (position != null && position.isContained(offset, length)) {
- fRemovedPositions.set(i, null);
- fNOfRemovedPositions--;
- }
- }
- }
- }
-
- /** Position collector */
- private PositionCollector fCollector= new PositionCollector();
-
- /** The Java editor this semantic highlighting reconciler is installed on */
- private JavaEditor fEditor;
- /** The source viewer this semantic highlighting reconciler is installed on */
- private ISourceViewer fSourceViewer;
- /** The semantic highlighting presenter */
- private SemanticHighlightingPresenter fPresenter;
- /** Semantic highlightings */
- private SemanticHighlighting[] fSemanticHighlightings;
- /** Highlightings */
- private Highlighting[] fHighlightings;
-
- /** Background job's added highlighted positions */
- private List fAddedPositions= new ArrayList();
- /** Background job's removed highlighted positions */
- private List fRemovedPositions= new ArrayList();
- /** Number of removed positions */
- private int fNOfRemovedPositions;
-
- /** Background job */
- private Job fJob;
- /** Background job lock */
- private final Object fJobLock= new Object();
- /**
- * Reconcile operation lock.
- *
- */
- private final Object fReconcileLock= new Object();
- /**
- * <code>true</code> if any thread is executing
- * <code>reconcile</code>, <code>false</code> otherwise.
- *
- */
- private boolean fIsReconciling= false;
-
- /** The semantic highlighting presenter - cache for background thread, only valid during {@link #reconciled(JavaScriptUnit, boolean, IProgressMonitor)} */
- private SemanticHighlightingPresenter fJobPresenter;
- /** Semantic highlightings - cache for background thread, only valid during {@link #reconciled(JavaScriptUnit, boolean, IProgressMonitor)} */
- private SemanticHighlighting[] fJobSemanticHighlightings;
- /** Highlightings - cache for background thread, only valid during {@link #reconciled(JavaScriptUnit, boolean, IProgressMonitor)} */
- private Highlighting[] fJobHighlightings;
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
- */
- public void aboutToBeReconciled() {
- // Do nothing
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(JavaScriptUnit, boolean, IProgressMonitor)
- */
- public void reconciled(JavaScriptUnit ast, boolean forced, IProgressMonitor progressMonitor) {
- // ensure at most one thread can be reconciling at any time
- synchronized (fReconcileLock) {
- if (fIsReconciling)
- return;
- else
- fIsReconciling= true;
- }
- fJobPresenter= fPresenter;
- fJobSemanticHighlightings= fSemanticHighlightings;
- fJobHighlightings= fHighlightings;
-
- try {
- if (fJobPresenter == null || fJobSemanticHighlightings == null || fJobHighlightings == null)
- return;
-
- fJobPresenter.setCanceled(progressMonitor.isCanceled());
-
- if (ast == null || fJobPresenter.isCanceled())
- return;
-
- ASTNode[] subtrees= getAffectedSubtrees(ast);
- if (subtrees.length == 0)
- return;
-
- startReconcilingPositions();
-
- if (!fJobPresenter.isCanceled())
- reconcilePositions(subtrees);
-
- TextPresentation textPresentation= null;
- if (!fJobPresenter.isCanceled())
- textPresentation= fJobPresenter.createPresentation(fAddedPositions, fRemovedPositions);
-
- if (!fJobPresenter.isCanceled())
- updatePresentation(textPresentation, fAddedPositions, fRemovedPositions);
-
- stopReconcilingPositions();
- } finally {
- fJobPresenter= null;
- fJobSemanticHighlightings= null;
- fJobHighlightings= null;
- synchronized (fReconcileLock) {
- fIsReconciling= false;
- }
- }
- }
-
- /**
- * @param node Root node
- * @return Array of subtrees that may be affected by past document changes
- */
- private ASTNode[] getAffectedSubtrees(ASTNode node) {
- // TODO: only return nodes which are affected by document changes - would require an 'anchor' concept for taking distant effects into account
- return new ASTNode[] { node };
- }
-
- /**
- * Start reconciling positions.
- */
- private void startReconcilingPositions() {
- fJobPresenter.addAllPositions(fRemovedPositions);
- fNOfRemovedPositions= fRemovedPositions.size();
- }
-
- /**
- * Reconcile positions based on the AST subtrees
- *
- * @param subtrees the AST subtrees
- */
- private void reconcilePositions(ASTNode[] subtrees) {
- // FIXME: remove positions not covered by subtrees
- for (int i= 0, n= subtrees.length; i < n; i++)
- subtrees[i].accept(fCollector);
- List oldPositions= fRemovedPositions;
- List newPositions= new ArrayList(fNOfRemovedPositions);
- for (int i= 0, n= oldPositions.size(); i < n; i ++) {
- Object current= oldPositions.get(i);
- if (current != null)
- newPositions.add(current);
- }
- fRemovedPositions= newPositions;
- }
-
- /**
- * Update the presentation.
- *
- * @param textPresentation the text presentation
- * @param addedPositions the added positions
- * @param removedPositions the removed positions
- */
- private void updatePresentation(TextPresentation textPresentation, List addedPositions, List removedPositions) {
- Runnable runnable= fJobPresenter.createUpdateRunnable(textPresentation, addedPositions, removedPositions);
- if (runnable == null)
- return;
-
- JavaEditor editor= fEditor;
- if (editor == null)
- return;
-
- IWorkbenchPartSite site= editor.getSite();
- if (site == null)
- return;
-
- Shell shell= site.getShell();
- if (shell == null || shell.isDisposed())
- return;
-
- Display display= shell.getDisplay();
- if (display == null || display.isDisposed())
- return;
-
- display.asyncExec(runnable);
- }
-
- /**
- * Stop reconciling positions.
- */
- private void stopReconcilingPositions() {
- fRemovedPositions.clear();
- fNOfRemovedPositions= 0;
- fAddedPositions.clear();
- }
-
- /**
- * Install this reconciler on the given editor, presenter and highlightings.
- * @param editor the editor
- * @param sourceViewer the source viewer
- * @param presenter the semantic highlighting presenter
- * @param semanticHighlightings the semantic highlightings
- * @param highlightings the highlightings
- */
- public void install(JavaEditor editor, ISourceViewer sourceViewer, SemanticHighlightingPresenter presenter, SemanticHighlighting[] semanticHighlightings, Highlighting[] highlightings) {
- fPresenter= presenter;
- fSemanticHighlightings= semanticHighlightings;
- fHighlightings= highlightings;
-
- fEditor= editor;
- fSourceViewer= sourceViewer;
-
- if (fEditor instanceof CompilationUnitEditor) {
- ((CompilationUnitEditor)fEditor).addReconcileListener(this);
- } else if (fEditor == null) {
- fSourceViewer.addTextInputListener(this);
- scheduleJob();
- }
- }
-
- /**
- * Uninstall this reconciler from the editor
- */
- public void uninstall() {
- if (fPresenter != null)
- fPresenter.setCanceled(true);
-
- if (fEditor != null) {
- if (fEditor instanceof CompilationUnitEditor)
- ((CompilationUnitEditor)fEditor).removeReconcileListener(this);
- else
- fSourceViewer.removeTextInputListener(this);
- fEditor= null;
- }
-
- fSourceViewer= null;
- fSemanticHighlightings= null;
- fHighlightings= null;
- fPresenter= null;
- }
-
- /**
- * Schedule a background job for retrieving the AST and reconciling the Semantic Highlighting model.
- */
- private void scheduleJob() {
- final IJavaScriptElement element= fEditor.getInputJavaElement();
-
- synchronized (fJobLock) {
- final Job oldJob= fJob;
- if (fJob != null) {
- fJob.cancel();
- fJob= null;
- }
-
- if (element != null) {
- fJob= new Job(JavaEditorMessages.SemanticHighlighting_job) {
- protected IStatus run(IProgressMonitor monitor) {
- if (oldJob != null) {
- try {
- oldJob.join();
- } catch (InterruptedException e) {
- JavaScriptPlugin.log(e);
- return Status.CANCEL_STATUS;
- }
- }
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(element, ASTProvider.WAIT_YES, monitor);
- reconciled(ast, false, monitor);
- synchronized (fJobLock) {
- // allow the job to be gc'ed
- if (fJob == this)
- fJob= null;
- }
- return Status.OK_STATUS;
- }
- };
- fJob.setSystem(true);
- fJob.setPriority(Job.DECORATE);
- fJob.schedule();
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
- synchronized (fJobLock) {
- if (fJob != null) {
- fJob.cancel();
- fJob= null;
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
- */
- public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
- if (newInput != null)
- scheduleJob();
- }
-
- /**
- * Refreshes the highlighting.
- *
- *
- */
- public void refresh() {
- scheduleJob();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightings.java
deleted file mode 100644
index 2964e61b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticHighlightings.java
+++ /dev/null
@@ -1,1665 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteral;
-import org.eclipse.wst.jsdt.core.dom.ObjectLiteralField;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * Semantic highlightings
- *
- *
- */
-public class SemanticHighlightings {
-
- /**
- * A named preference part that controls the highlighting of static final fields.
- */
- public static final String STATIC_FINAL_FIELD="staticFinalField"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of static fields.
- */
- public static final String STATIC_FIELD="staticField"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of fields.
- */
- public static final String FIELD="field"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of method declarations.
- */
- public static final String METHOD_DECLARATION="methodDeclarationName"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of static method invocations.
- */
- public static final String STATIC_METHOD_INVOCATION="staticMethodInvocation"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of inherited method invocations.
- */
- public static final String INHERITED_METHOD_INVOCATION="inheritedMethodInvocation"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of annotation element references.
- *
- */
- public static final String ANNOTATION_ELEMENT_REFERENCE="annotationElementReference"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of abstract method invocations.
- */
- public static final String ABSTRACT_METHOD_INVOCATION="abstractMethodInvocation"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of local variables.
- */
- public static final String LOCAL_VARIABLE_DECLARATION="localVariableDeclaration"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of local variables.
- */
- public static final String LOCAL_VARIABLE="localVariable"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of parameter variables.
- */
- public static final String PARAMETER_VARIABLE="parameterVariable"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of deprecated members.
- */
- public static final String DEPRECATED_MEMBER="deprecatedMember"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of type parameters.
- *
- */
- public static final String TYPE_VARIABLE="typeParameter"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of type parameters.
- *
- * @author STP
- */
- public static final String OBJECT_INITIALIZER="objectInitializer"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of methods
- * (invocations and declarations).
- *
- *
- */
- public static final String METHOD="method"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of auto(un)boxed
- * expressions.
- *
- *
- */
- public static final String AUTOBOXING="autoboxing"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of classes.
- *
- *
- */
- public static final String CLASS="class"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of enums.
- *
- *
- */
- public static final String ENUM="enum"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of interfaces.
- *
- *
- */
- public static final String INTERFACE="interface"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of annotations.
- *
- *
- */
- public static final String ANNOTATION="annotation"; //$NON-NLS-1$
-
- /**
- * A named preference part that controls the highlighting of type arguments.
- *
- *
- */
- public static final String TYPE_ARGUMENT="typeArgument"; //$NON-NLS-1$
-
- /**
- * Semantic highlightings
- */
- private static SemanticHighlighting[] fgSemanticHighlightings;
-
- /**
- * Semantic highlighting for static final fields.
- */
-/*
- private static final class StaticFinalFieldHighlighting extends SemanticHighlighting {
- @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return STATIC_FINAL_FIELD;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- public RGB getDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_staticFinalField;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
- IBinding binding= token.getBinding();
- return binding != null && binding.getKind() == IBinding.VARIABLE && ((IVariableBinding)binding).isField() && (binding.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) == (Modifier.FINAL | Modifier.STATIC);
- }
-}
-*/
-
- /**
- * Semantic highlighting for static fields.
- */
-/*
- private static final class StaticFieldHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return STATIC_FIELD;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- public RGB getDefaultTextColor() {
- return new RGB(0, 0, 192);
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_staticField;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
- IBinding binding= token.getBinding();
- return binding != null && binding.getKind() == IBinding.VARIABLE && ((IVariableBinding)binding).isField() && (binding.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
- }
- }
-*/
-
- /**
- * Semantic highlighting for fields.
- */
-/*
- private static final class FieldHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return FIELD;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- public RGB getDefaultTextColor() {
- return new RGB(0, 0, 192);
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_field;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
- IBinding binding= token.getBinding();
- return binding != null && binding.getKind() == IBinding.VARIABLE && ((IVariableBinding)binding).isField();
- }
- }
-*/
- /**
- * Semantic highlighting for fields.
- * @author STP
- */
- private static final class ObjectInitializerHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return OBJECT_INITIALIZER;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_objectInitializer;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- */
-
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- StructuralPropertyDescriptor location= node.getLocationInParent();
- if (location == ObjectLiteralField.FIELD_NAME_PROPERTY ) {
- ASTNode parent= node.getParent();
- return (parent != null && parent instanceof ObjectLiteral);
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for auto(un)boxed expressions.
- */
-/*
- private static final class AutoboxHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return AUTOBOXING;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(171, 48, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_autoboxing;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumesLiteral(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumesLiteral(SemanticToken token) {
- return isAutoUnBoxing(token.getLiteral());
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
- return isAutoUnBoxing(token.getNode());
- }
-
- private boolean isAutoUnBoxing(Expression node) {
- if (isAutoUnBoxingExpression(node))
- return true;
- // special cases: the autoboxing conversions happens at a
- // location that is not mapped directly to a simple name
- // or a literal, but can still be mapped somehow
- // A) expressions
- StructuralPropertyDescriptor desc= node.getLocationInParent();
- if (desc == ArrayAccess.ARRAY_PROPERTY
- || desc == InfixExpression.LEFT_OPERAND_PROPERTY
- || desc == InfixExpression.RIGHT_OPERAND_PROPERTY
- || desc == ConditionalExpression.THEN_EXPRESSION_PROPERTY
- || desc == PrefixExpression.OPERAND_PROPERTY
- || desc == CastExpression.EXPRESSION_PROPERTY
- || desc == ConditionalExpression.ELSE_EXPRESSION_PROPERTY) {
- ASTNode parent= node.getParent();
- if (parent instanceof Expression)
- return isAutoUnBoxingExpression((Expression) parent);
- }
- // B) constructor invocations
- if (desc == SimpleType.NAME_PROPERTY || desc == QualifiedType.NAME_PROPERTY) {
- ASTNode parent= node.getParent();
- if (parent != null && parent.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
- parent= parent.getParent();
- if (parent instanceof Expression)
- return isAutoUnBoxingExpression((Expression) parent);
- }
- }
- return false;
- }
-
- private boolean isAutoUnBoxingExpression(Expression expression) {
- return expression.resolveBoxing() || expression.resolveUnboxing();
- }
- }
-*/
- /**
- * Semantic highlighting for method declarations.
- */
- private static final class MethodDeclarationHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return METHOD_DECLARATION;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_methodDeclaration;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- */
- public boolean consumes(SemanticToken token) {
- StructuralPropertyDescriptor location= token.getNode().getLocationInParent();
- return location == FunctionDeclaration.NAME_PROPERTY ;
- }
- }
-
- /**
- * Semantic highlighting for static method invocations.
- */
-/*
- private static final class StaticMethodInvocationHighlighting extends SemanticHighlighting {
- public String getPreferenceKey() {
- return STATIC_METHOD_INVOCATION;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_staticMethodInvocation;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- if (node.isDeclaration())
- return false;
-
- IBinding binding= token.getBinding();
- return binding != null && binding.getKind() == IBinding.METHOD && (binding.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
- }
- }
-*/
-
- /**
- * Semantic highlighting for annotation element references.
- *
- */
-/*
- private static final class AnnotationElementReferenceHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return ANNOTATION_ELEMENT_REFERENCE;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_annotationElementReference;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- if (node.getParent() instanceof MemberValuePair) {
- IBinding binding= token.getBinding();
- boolean isAnnotationElement= binding != null && binding.getKind() == IBinding.METHOD;
-
- return isAnnotationElement;
- }
-
- return false;
- }
- }
-*/
-
- /**
- * Semantic highlighting for abstract method invocations.
- */
-/*
- private static final class AbstractMethodInvocationHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return ABSTRACT_METHOD_INVOCATION;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_abstractMethodInvocation;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- if (node.isDeclaration())
- return false;
-
- IBinding binding= token.getBinding();
- boolean isAbstractMethod= binding != null && binding.getKind() == IBinding.METHOD && (binding.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT;
- if (!isAbstractMethod)
- return false;
-
- // filter out annotation value references
- if (binding != null) {
- ITypeBinding declaringType= ((IFunctionBinding)binding).getDeclaringClass();
- if (declaringType.isAnnotation())
- return false;
- }
-
- return true;
- }
- }
-*/
-
- /**
- * Semantic highlighting for inherited method invocations.
- */
-/*
- private static final class InheritedMethodInvocationHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return INHERITED_METHOD_INVOCATION;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_inheritedMethodInvocation;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- if (node.isDeclaration())
- return false;
-
- IBinding binding= token.getBinding();
- if (binding == null || binding.getKind() != IBinding.METHOD)
- return false;
-
- ITypeBinding currentType= Bindings.getBindingOfParentType(node);
- ITypeBinding declaringType= ((IFunctionBinding) binding).getDeclaringClass();
- if (currentType == declaringType || currentType == null)
- return false;
-
- return Bindings.isSuperType(declaringType, currentType);
- }
- }
-*/
-
- /**
- * Semantic highlighting for inherited method invocations.
- */
- private static final class MethodHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return METHOD;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_method;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#isMatched(org.eclipse.wst.jsdt.core.dom.ASTNode)
- */
- public boolean consumes(SemanticToken token) {
- IBinding binding= getMethodBinding(token);
- return binding != null && binding.getKind() == IBinding.METHOD;
- }
-
- /**
- * Extracts the method binding from the token's simple name. The method
- * binding is either the token's binding (if the parent of token is a
- * method call or declaration) or the constructor binding of a class
- * instance creation if the node is the type name of a class instance
- * creation.
- *
- * @param token the token to extract the method binding from
- * @return the corresponding method binding, or <code>null</code>
- */
- private IBinding getMethodBinding(SemanticToken token) {
- IBinding binding= null;
- // work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605
- ASTNode node= token.getNode();
- ASTNode parent= node.getParent();
- while (isTypePath(node, parent)) {
- node= parent;
- parent= parent.getParent();
- }
-
- if (parent != null && node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
- binding= ((ClassInstanceCreation) parent).resolveConstructorBinding();
- else
- binding= token.getBinding();
- return binding;
- }
-
- /**
- * Returns <code>true</code> if the given child/parent nodes are valid
- * sub nodes of a <code>Type</code> ASTNode.
- * @param child the child node
- * @param parent the parent node
- * @return <code>true</code> if the nodes may be the sub nodes of a type node, false otherwise
- */
- private boolean isTypePath(ASTNode child, ASTNode parent) {
- if (parent instanceof Type) {
- StructuralPropertyDescriptor location= child.getLocationInParent();
- return location == SimpleType.NAME_PROPERTY;
- } else if (parent instanceof QualifiedName) {
- StructuralPropertyDescriptor location= child.getLocationInParent();
- return location == QualifiedName.NAME_PROPERTY;
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for local variable declarations.
- */
- private static final class LocalVariableDeclarationHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return LOCAL_VARIABLE_DECLARATION;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_localVariableDeclaration;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- */
- public boolean consumes(SemanticToken token) {
- SimpleName node= token.getNode();
- StructuralPropertyDescriptor location= node.getLocationInParent();
- if (location == VariableDeclarationFragment.NAME_PROPERTY || location == SingleVariableDeclaration.NAME_PROPERTY) {
- ASTNode parent= node.getParent();
- if (parent instanceof VariableDeclaration) {
- parent= parent.getParent();
- return parent == null || !(parent instanceof FieldDeclaration);
- }
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for local variables.
- */
- private static final class LocalVariableHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return LOCAL_VARIABLE;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_localVariable;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- */
- public boolean consumes(SemanticToken token) {
- IBinding binding= token.getBinding();
- if (binding != null && binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) {
- ASTNode decl= token.getRoot().findDeclaringNode(binding);
- return decl instanceof VariableDeclaration;
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for parameter variables.
- */
- private static final class ParameterVariableHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return PARAMETER_VARIABLE;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_parameterVariable;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- */
- public boolean consumes(SemanticToken token) {
- IBinding binding= token.getBinding();
- if (binding != null && binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) {
- ASTNode decl= token.getRoot().findDeclaringNode(binding);
- return decl != null && decl.getLocationInParent() == FunctionDeclaration.PARAMETERS_PROPERTY;
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for deprecated members.
- */
- private static final class DeprecatedMemberHighlighting extends SemanticHighlighting {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- */
- public String getPreferenceKey() {
- return DEPRECATED_MEMBER;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 0, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- */
- public boolean isBoldByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- */
- public boolean isItalicByDefault() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isStrikethroughByDefault()
- *
- */
- public boolean isStrikethroughByDefault() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- */
- public boolean isEnabledByDefault() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- */
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_deprecatedMember;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- */
- public boolean consumes(SemanticToken token) {
- IBinding binding= getMethodBinding(token);
- return binding != null ? binding.isDeprecated() : false;
- }
-
- /**
- * Extracts the method binding from the token's simple name. The method
- * binding is either the token's binding (if the parent of token is a
- * method call or declaration) or the constructor binding of a class
- * instance creation if the node is the type name of a class instance
- * creation.
- *
- * @param token the token to extract the method binding from
- * @return the corresponding method binding, or <code>null</code>
- */
- private IBinding getMethodBinding(SemanticToken token) {
- IBinding binding= null;
- // work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605
- ASTNode node= token.getNode();
- ASTNode parent= node.getParent();
- while (isTypePath(node, parent)) {
- node= parent;
- parent= parent.getParent();
- }
-
- if (parent != null && node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
- binding= ((ClassInstanceCreation) parent).resolveConstructorBinding();
- else
- binding= token.getBinding();
- return binding;
- }
-
- /**
- * Returns <code>true</code> if the given child/parent nodes are valid
- * sub nodes of a <code>Type</code> ASTNode.
- * @param child the child node
- * @param parent the parent node
- * @return <code>true</code> if the nodes may be the sub nodes of a type node, false otherwise
- */
- private boolean isTypePath(ASTNode child, ASTNode parent) {
- if (parent instanceof Type) {
- StructuralPropertyDescriptor location= child.getLocationInParent();
- return location == SimpleType.NAME_PROPERTY;
- } else if (parent instanceof QualifiedName) {
- StructuralPropertyDescriptor location= child.getLocationInParent();
- return location == QualifiedName.NAME_PROPERTY;
- }
- return false;
- }
- }
-
- /**
- * Semantic highlighting for type variables.
- *
- */
-/*
- private static final class TypeVariableHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return TYPE_VARIABLE;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(100, 70, 50);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return true;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_typeVariables;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types in type parameter lists
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- if (node.getNodeType() != ASTNode.SIMPLE_TYPE && node.getNodeType() != ASTNode.TYPE_PARAMETER)
- return false;
-
- // 2: match generic type variable references
- IBinding binding= token.getBinding();
- return binding instanceof ITypeBinding && ((ITypeBinding) binding).isTypeVariable();
- }
- }
-*/
-
- /**
- * Semantic highlighting for classes.
- *
- */
-/*
- private static final class ClassHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return CLASS;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(0, 80, 50);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_classes;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- int nodeType= node.getNodeType();
- if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.THIS_EXPRESSION && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION)
- return false;
- while (nodeType == ASTNode.QUALIFIED_NAME) {
- node= node.getParent();
- nodeType= node.getNodeType();
- if (nodeType == ASTNode.IMPORT_DECLARATION)
- return false;
- }
-
- // 2: match classes
- IBinding binding= token.getBinding();
- return binding instanceof ITypeBinding && ((ITypeBinding) binding).isClass();
- }
- }
-*/
-/*
- private static final class EnumHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return ENUM;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(100, 70, 50);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_enums;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- int nodeType= node.getNodeType();
- if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.ENUM_DECLARATION)
- return false;
- while (nodeType == ASTNode.QUALIFIED_NAME) {
- node= node.getParent();
- nodeType= node.getNodeType();
- if (nodeType == ASTNode.IMPORT_DECLARATION)
- return false;
- }
-
- // 2: match enums
- IBinding binding= token.getBinding();
- return binding instanceof ITypeBinding && ((ITypeBinding) binding).isEnum();
- }
- }
-*/
-
- /**
- * Semantic highlighting for interfaces.
- *
- */
-/*
- private static final class InterfaceHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return INTERFACE;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(50, 63, 112);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_interfaces;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- int nodeType= node.getNodeType();
- if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION)
- return false;
- while (nodeType == ASTNode.QUALIFIED_NAME) {
- node= node.getParent();
- nodeType= node.getNodeType();
- if (nodeType == ASTNode.IMPORT_DECLARATION)
- return false;
- }
-
- // 2: match interfaces
- IBinding binding= token.getBinding();
- return binding instanceof ITypeBinding && ((ITypeBinding) binding).isInterface();
- }
- }
-*/
-
- /**
- * Semantic highlighting for annotation types.
- *
- */
-/*
- private static final class AnnotationHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return ANNOTATION;
- }
- public RGB getDefaultDefaultTextColor() {
- return new RGB(100, 100, 100);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return true; // as it replaces the syntax based highlighting which is always enabled
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_annotations;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- int nodeType= node.getNodeType();
- if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.ANNOTATION_TYPE_DECLARATION
- && nodeType != ASTNode.MARKER_ANNOTATION && nodeType != ASTNode.NORMAL_ANNOTATION && nodeType != ASTNode.SINGLE_MEMBER_ANNOTATION)
- return false;
- while (nodeType == ASTNode.QUALIFIED_NAME) {
- node= node.getParent();
- nodeType= node.getNodeType();
- if (nodeType == ASTNode.IMPORT_DECLARATION)
- return false;
- }
-
- // 2: match annotations
- IBinding binding= token.getBinding();
- return binding instanceof ITypeBinding && ((ITypeBinding) binding).isAnnotation();
- }
- }
-*/
-
- /**
- * Semantic highlighting for annotation types.
- *
- */
-/*
- private static final class TypeArgumentHighlighting extends SemanticHighlighting {
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#getPreferenceKey()
- public String getPreferenceKey() {
- return TYPE_ARGUMENT;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextColor()
- */
- public RGB getDefaultDefaultTextColor() {
- return new RGB(13, 100, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDefaultTextStyleBold()
- public boolean isBoldByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isItalicByDefault()
- public boolean isItalicByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#isEnabledByDefault()
- public boolean isEnabledByDefault() {
- return false;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.ISemanticHighlighting#getDisplayName()
- public String getDisplayName() {
- return JavaEditorMessages.SemanticHighlighting_typeArguments;
- }
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting#consumes(org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticToken)
- public boolean consumes(SemanticToken token) {
-
- // 1: match types
- SimpleName name= token.getNode();
- ASTNode node= name.getParent();
- int nodeType= node.getNodeType();
- if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE)
- return false;
-
- // 2: match type arguments
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent == ParameterizedType.TYPE_ARGUMENTS_PROPERTY)
- return true;
-
- return false;
- }
- }
-*/
-
- /**
- * A named preference that controls the given semantic highlighting's color.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the color preference key
- */
- public static String getColorPreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX;
- }
-
- /**
- * A named preference that controls if the given semantic highlighting has the text attribute bold.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the bold preference key
- */
- public static String getBoldPreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX;
- }
-
- /**
- * A named preference that controls if the given semantic highlighting has the text attribute italic.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the italic preference key
- */
- public static String getItalicPreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX;
- }
-
- /**
- * A named preference that controls if the given semantic highlighting has the text attribute strikethrough.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the strikethrough preference key
- *
- */
- public static String getStrikethroughPreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX;
- }
-
- /**
- * A named preference that controls if the given semantic highlighting has the text attribute underline.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the underline preference key
- *
- */
- public static String getUnderlinePreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX;
- }
-
- /**
- * A named preference that controls if the given semantic highlighting is enabled.
- *
- * @param semanticHighlighting the semantic highlighting
- * @return the enabled preference key
- */
- public static String getEnabledPreferenceKey(SemanticHighlighting semanticHighlighting) {
- return PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + semanticHighlighting.getPreferenceKey() + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX;
- }
-
- /**
- * @return The semantic highlightings, the order defines the precedence of matches, the first match wins.
- */
- public static SemanticHighlighting[] getSemanticHighlightings() {
- if (fgSemanticHighlightings == null)
- fgSemanticHighlightings= new SemanticHighlighting[] {
-// STP
-new ObjectInitializerHighlighting(),
- new DeprecatedMemberHighlighting(),
-// new AutoboxHighlighting(),
-// new StaticFinalFieldHighlighting(),
-// new StaticFieldHighlighting(),
-// new FieldHighlighting(),
- new MethodDeclarationHighlighting(),
-// new StaticMethodInvocationHighlighting(),
-// new AbstractMethodInvocationHighlighting(),
-// new AnnotationElementReferenceHighlighting(),
-// new InheritedMethodInvocationHighlighting(),
- new ParameterVariableHighlighting(),
- new LocalVariableDeclarationHighlighting(),
- new LocalVariableHighlighting(),
-// new TypeVariableHighlighting(), // before type arguments!
- new MethodHighlighting(), // before types to get ctors
-// new TypeArgumentHighlighting(), // before other types
-// new ClassHighlighting(),
-// new EnumHighlighting(),
-// new AnnotationHighlighting(), // before interfaces
-// new InterfaceHighlighting(),
- };
- return fgSemanticHighlightings;
- }
-
- /**
- * Initialize default preferences in the given preference store.
- * @param store The preference store
- */
- public static void initDefaults(IPreferenceStore store) {
- SemanticHighlighting[] semanticHighlightings= getSemanticHighlightings();
- for (int i= 0, n= semanticHighlightings.length; i < n; i++) {
- SemanticHighlighting semanticHighlighting= semanticHighlightings[i];
- setDefaultAndFireEvent(store, SemanticHighlightings.getColorPreferenceKey(semanticHighlighting), semanticHighlighting.getDefaultTextColor());
- store.setDefault(SemanticHighlightings.getBoldPreferenceKey(semanticHighlighting), semanticHighlighting.isBoldByDefault());
- store.setDefault(SemanticHighlightings.getItalicPreferenceKey(semanticHighlighting), semanticHighlighting.isItalicByDefault());
- store.setDefault(SemanticHighlightings.getStrikethroughPreferenceKey(semanticHighlighting), semanticHighlighting.isStrikethroughByDefault());
- store.setDefault(SemanticHighlightings.getUnderlinePreferenceKey(semanticHighlighting), semanticHighlighting.isUnderlineByDefault());
- store.setDefault(SemanticHighlightings.getEnabledPreferenceKey(semanticHighlighting), semanticHighlighting.isEnabledByDefault());
- }
-
- convertMethodHighlightingPreferences(store);
- convertAnnotationHighlightingPreferences(store);
- }
-
- /**
- * Tests whether <code>event</code> in <code>store</code> affects the
- * enablement of semantic highlighting.
- *
- * @param store the preference store where <code>event</code> was observed
- * @param event the property change under examination
- * @return <code>true</code> if <code>event</code> changed semantic
- * highlighting enablement, <code>false</code> if it did not
- *
- */
- public static boolean affectsEnablement(IPreferenceStore store, PropertyChangeEvent event) {
- String relevantKey= null;
- SemanticHighlighting[] highlightings= getSemanticHighlightings();
- for (int i= 0; i < highlightings.length; i++) {
- if (event.getProperty().equals(getEnabledPreferenceKey(highlightings[i]))) {
- relevantKey= event.getProperty();
- break;
- }
- }
- if (relevantKey == null)
- return false;
-
- for (int i= 0; i < highlightings.length; i++) {
- String key= getEnabledPreferenceKey(highlightings[i]);
- if (key.equals(relevantKey))
- continue;
- if (store.getBoolean(key))
- return false; // another is still enabled or was enabled before
- }
-
- // all others are disabled, so toggling relevantKey affects the enablement
- return true;
- }
-
- /**
- * Tests whether semantic highlighting is currently enabled.
- *
- * @param store the preference store to consult
- * @return <code>true</code> if semantic highlighting is enabled,
- * <code>false</code> if it is not
- *
- */
- public static boolean isEnabled(IPreferenceStore store) {
- SemanticHighlighting[] highlightings= getSemanticHighlightings();
- boolean enable= false;
- for (int i= 0; i < highlightings.length; i++) {
- String enabledKey= getEnabledPreferenceKey(highlightings[i]);
- if (store.getBoolean(enabledKey)) {
- enable= true;
- break;
- }
- }
-
- return enable;
- }
-
- /**
- * In 3.0, methods were highlighted by a rule-based word matcher that
- * matched any identifier that was followed by possibly white space and a
- * left parenthesis.
- * <p>
- * With generics, this does not work any longer for constructors of generic
- * types, and the highlighting has been moved to be a semantic highlighting.
- * Because different preference key naming schemes are used, we have to
- * migrate the old settings to the new ones, which is done here. Nothing
- * needs to be done if the old settings were set to the default values.
- * </p>
- *
- * @param store the preference store to migrate
- *
- */
- private static void convertMethodHighlightingPreferences(IPreferenceStore store) {
- String colorkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX;
- String boldkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX;
- String italickey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX;
- String enabledkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX;
-
- String oldColorkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR;
- String oldBoldkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD;
- String oldItalickey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC;
-
- if (conditionalReset(store, oldColorkey, colorkey)
- || conditionalReset(store, oldBoldkey, boldkey)
- || conditionalReset(store, oldItalickey, italickey)) {
- store.setValue(enabledkey, true);
- }
-
- }
-
- /**
- * In 3.1, annotations were highlighted by a rule-based word matcher that matched any identifier
- * preceded by an '@' sign and possibly white space.
- * <p>
- * This does not work when there is a comment between the '@' and the annotation, results in
- * stale highlighting if there is a new line between the '@' and the annotation, and does not
- * work for highlighting annotation declarations. Because different preference key naming
- * schemes are used, we have to migrate the old settings to the new ones, which is done here.
- * Nothing needs to be done if the old settings were set to the default values.
- * </p>
- *
- * @param store the preference store to migrate
- *
- */
- private static void convertAnnotationHighlightingPreferences(IPreferenceStore store) {
- String colorkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX;
- String boldkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX;
- String italickey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX;
- String strikethroughKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX;
- String underlineKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX;
- String enabledkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX;
-
- String oldColorkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_COLOR;
- String oldBoldkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_BOLD;
- String oldItalickey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_ITALIC;
- String oldStrikethroughKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_STRIKETHROUGH;
- String oldUnderlineKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_UNDERLINE;
-
- if (conditionalReset(store, oldColorkey, colorkey)
- || conditionalReset(store, oldBoldkey, boldkey)
- || conditionalReset(store, oldItalickey, italickey)
- || conditionalReset(store, oldStrikethroughKey, strikethroughKey)
- || conditionalReset(store, oldUnderlineKey, underlineKey)) {
- store.setValue(enabledkey, true);
- }
-
- }
-
- /**
- * If the setting pointed to by <code>oldKey</code> is not the default
- * setting, store that setting under <code>newKey</code> and reset
- * <code>oldKey</code> to its default setting.
- * <p>
- * Returns <code>true</code> if any changes were made.
- * </p>
- *
- * @param store the preference store to read from and write to
- * @param oldKey the old preference key
- * @param newKey the new preference key
- * @return <code>true</code> if <code>store</code> was modified,
- * <code>false</code> if not
- *
- */
- private static boolean conditionalReset(IPreferenceStore store, String oldKey, String newKey) {
- if (!store.isDefault(oldKey)) {
- if (store.isDefault(newKey))
- store.setValue(newKey, store.getString(oldKey));
- store.setToDefault(oldKey);
- return true;
- }
- return false;
- }
-
- /**
- * Sets the default value and fires a property
- * change event if necessary.
- *
- * @param store the preference store
- * @param key the preference key
- * @param newValue the new value
- *
- */
- private static void setDefaultAndFireEvent(IPreferenceStore store, String key, RGB newValue) {
- RGB oldValue= null;
- if (store.isDefault(key))
- oldValue= PreferenceConverter.getDefaultColor(store, key);
-
- PreferenceConverter.setDefault(store, key, newValue);
-
- if (oldValue != null && !oldValue.equals(newValue))
- store.firePropertyChangeEvent(key, oldValue, newValue);
- }
-
- /**
- * Do not instantiate
- */
- private SemanticHighlightings() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticToken.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticToken.java
deleted file mode 100644
index 05c6941d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SemanticToken.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-
-/**
- * Semantic token
- */
-public final class SemanticToken {
-
- /** AST node */
- private SimpleName fNode;
- private Expression fLiteral;
-
- /** Binding */
- private IBinding fBinding;
- /** Is the binding resolved? */
- private boolean fIsBindingResolved= false;
-
- /** AST root */
- private JavaScriptUnit fRoot;
- private boolean fIsRootResolved= false;
-
- /**
- * @return Returns the binding, can be <code>null</code>.
- */
- public IBinding getBinding() {
- if (!fIsBindingResolved) {
- fIsBindingResolved= true;
- if (fNode != null)
- fBinding= fNode.resolveBinding();
- }
-
- return fBinding;
- }
-
- /**
- * @return the AST node (a {@link SimpleName})
- */
- public SimpleName getNode() {
- return fNode;
- }
-
- /**
- * @return the AST node (a <code>Boolean-, Character- or NumberLiteral</code>)
- */
- public Expression getLiteral() {
- return fLiteral;
- }
-
- /**
- * @return the AST root
- */
- public JavaScriptUnit getRoot() {
- if (!fIsRootResolved) {
- fIsRootResolved= true;
- fRoot= (JavaScriptUnit) (fNode != null ? fNode : fLiteral).getRoot();
- }
-
- return fRoot;
- }
-
- /**
- * Update this token with the given AST node.
- * <p>
- * NOTE: Allowed to be used by {@link SemanticHighlightingReconciler} only.
- * </p>
- *
- * @param node the AST simple name
- */
- void update(SimpleName node) {
- clear();
- fNode= node;
- }
-
- /**
- * Update this token with the given AST node.
- * <p>
- * NOTE: Allowed to be used by {@link SemanticHighlightingReconciler} only.
- * </p>
- *
- * @param literal the AST literal
- */
- void update(Expression literal) {
- clear();
- fLiteral= literal;
- }
-
- /**
- * Clears this token.
- * <p>
- * NOTE: Allowed to be used by {@link SemanticHighlightingReconciler} only.
- * </p>
- */
- void clear() {
- fNode= null;
- fLiteral= null;
- fBinding= null;
- fIsBindingResolved= false;
- fRoot= null;
- fIsRootResolved= false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistAction.java
deleted file mode 100644
index f216b315..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistAction.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalCategory;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalComputerRegistry;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Action to run content assist on a specific proposal category.
- *
- *
- */
-final class SpecificContentAssistAction extends Action implements IUpdate {
- /**
- * The category represented by this action.
- */
- private final CompletionProposalCategory fCategory;
- /**
- * The content assist executor.
- */
- private final SpecificContentAssistExecutor fExecutor= new SpecificContentAssistExecutor(CompletionProposalComputerRegistry.getDefault());
- /**
- * The editor.
- */
- private JavaEditor fEditor;
-
- /**
- * Creates a new action for a certain proposal category.
- *
- * @param category
- */
- public SpecificContentAssistAction(CompletionProposalCategory category) {
- fCategory= category;
- setText(category.getName());
- setImageDescriptor(category.getImageDescriptor());
- setActionDefinitionId("org.eclipse.wst.jsdt.ui.specific_content_assist.command"); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- ITextEditor editor= getActiveEditor();
- if (editor == null)
- return;
-
- fExecutor.invokeContentAssist(editor, fCategory.getId());
-
- return;
- }
-
- private ITextEditor getActiveEditor() {
- return fEditor;
- }
-
- /**
- * Sets the active editor part.
- *
- * @param part the editor, possibly <code>null</code>
- */
- public void setActiveEditor(IEditorPart part) {
- JavaEditor editor;
- if (part instanceof JavaEditor)
- editor= (JavaEditor) part;
- else
- editor= null;
- fEditor= editor;
- setEnabled(computeEnablement(fEditor));
- }
-
- private boolean computeEnablement(ITextEditor editor) {
- if (editor == null)
- return false;
- ITextOperationTarget target= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
- boolean hasContentAssist= target != null && target.canDoOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
- if (!hasContentAssist)
- return false;
-
- ISelection selection= editor.getSelectionProvider().getSelection();
- return isValidSelection(selection);
- }
-
- /**
- * Computes the partition type at the selection start and checks whether the proposal category
- * has any computers for this partition.
- *
- * @param selection the selection
- * @return <code>true</code> if there are any computers for the selection
- */
- private boolean isValidSelection(ISelection selection) {
- if (!(selection instanceof ITextSelection))
- return false;
- int offset= ((ITextSelection) selection).getOffset();
-
- IDocument document= getDocument();
- if (document == null)
- return false;
-
- String contentType;
- try {
- contentType= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, true);
- } catch (BadLocationException x) {
- return false;
- }
-
- return fCategory.hasComputers(contentType);
- }
-
- private IDocument getDocument() {
- Assert.isTrue(fEditor != null);
- IDocumentProvider provider= fEditor.getDocumentProvider();
- if (provider == null)
- return null;
-
- IDocument document= provider.getDocument(fEditor.getEditorInput());
- return document;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
- public void update() {
- setEnabled(computeEnablement(fEditor));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java
deleted file mode 100644
index ad669cb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalCategory;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalComputerRegistry;
-
-/**
- * A content assist executor can invoke content assist for a specific proposal category on an editor.
- *
- *
- */
-public final class SpecificContentAssistExecutor {
-
- private final CompletionProposalComputerRegistry fRegistry;
-
- /**
- * Creates a new executor.
- *
- * @param registry the computer registry to use for the enablement of proposal categories
- */
- public SpecificContentAssistExecutor(CompletionProposalComputerRegistry registry) {
- Assert.isNotNull(registry);
- fRegistry= registry;
- }
-
- /**
- * Invokes content assist on <code>editor</code>, showing only proposals computed by the
- * <code>CompletionProposalCategory</code> with the given <code>categoryId</code>.
- *
- * @param editor the editor to invoke code assist on
- * @param categoryId the id of the proposal category to show proposals for
- */
- public void invokeContentAssist(final ITextEditor editor, String categoryId) {
- Collection categories= fRegistry.getProposalCategories();
- boolean[] inclusionState= new boolean[categories.size()];
- boolean[] separateState= new boolean[categories.size()];
- int i= 0;
- for (Iterator it= categories.iterator(); it.hasNext(); i++) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- inclusionState[i]= cat.isIncluded();
- cat.setIncluded(cat.getId().equals(categoryId));
- separateState[i]= cat.isSeparateCommand();
- cat.setSeparateCommand(false);
- }
-
- try {
- ITextOperationTarget target= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
- if (target != null && target.canDoOperation(ISourceViewer.CONTENTASSIST_PROPOSALS))
- target.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
- } finally {
- i= 0;
- for (Iterator it= categories.iterator(); it.hasNext(); i++) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- cat.setIncluded(inclusionState[i]);
- cat.setSeparateCommand(separateState[i]);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/StorageMarkerAnnotationModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/StorageMarkerAnnotationModel.java
deleted file mode 100644
index 59f4dab2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/StorageMarkerAnnotationModel.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.Position;
-import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
-
-
-/**
- * Source editor resource marker annotation model implementation
- */
-public class StorageMarkerAnnotationModel extends ResourceMarkerAnnotationModel {
- public final static String SECONDARY_ID_KEY = "org.eclipse.wst.sse.ui.extensions.breakpoint.path"; //$NON-NLS-1$
- protected IResource fMarkerResource;
- protected String fSecondaryMarkerAttributeValue;
-
- /**
- * Constructor
- *
- * @param resource
- */
- public StorageMarkerAnnotationModel(IResource resource) {
- super(resource);
- fMarkerResource = resource;
- }
-
- public StorageMarkerAnnotationModel(IResource resource, String secondaryID) {
- super(resource);
- fMarkerResource = resource;
- fSecondaryMarkerAttributeValue = secondaryID;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#createMarkerAnnotation(org.eclipse.core.resources.IMarker)
- */
-// protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
-// /*
-// * We need to do some special processing if marker is a validation
-// * (aka problem) marker or if marker is a breakpoint marker so create
-// * a special marker annotation for those markers. Otherwise, use
-// * default.
-// */
-// if (MarkerUtilities.isMarkerType(marker, IMarker.PROBLEM)) {
-// return new StructuredMarkerAnnotation(marker);
-// }
-// return super.createMarkerAnnotation(marker);
-// }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#getMarkerPosition(org.eclipse.core.resources.IMarker)
- */
- public Position getMarkerPosition(IMarker marker) {
- Position pos = super.getMarkerPosition(marker);
-
- // if ((pos == null || pos.getLength() == 0) && marker.getType() ==
- // IInternalDebugUIConstants.ANN_INSTR_POINTER_CURRENT) {
- if (pos == null || pos.getLength() == 0) {
- // We probably should create position from marker if marker
- // attributes specify a valid position
- pos = createPositionFromMarker(marker);
- }
-
- return pos;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#isAcceptable(org.eclipse.core.resources.IMarker)
- */
- protected boolean isAcceptable(IMarker marker) {
-// try {
-// Object attr = marker.getAttribute(IBreakpointConstants.ATTR_HIDDEN);
-// if (attr != null && ((Boolean) attr).equals(Boolean.TRUE))
-// return false;
-// }
-// catch (CoreException e) {
-// // ignore
-// }
-
- if (fSecondaryMarkerAttributeValue == null)
- return super.isAcceptable(marker);
- String markerSecondaryMarkerAttributeValue = marker.getAttribute(SECONDARY_ID_KEY, ""); //$NON-NLS-1$
- boolean isSameFile = fSecondaryMarkerAttributeValue.equalsIgnoreCase(markerSecondaryMarkerAttributeValue);
- return super.isAcceptable(marker) && isSameFile;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleCommentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleCommentAction.java
deleted file mode 100644
index a5fc7545..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleCommentAction.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ResourceBundle;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-/**
- * An action which toggles comment prefixes on the selected lines.
- *
- *
- */
-public final class ToggleCommentAction extends TextEditorAction {
-
- /** The text operation target */
- private ITextOperationTarget fOperationTarget;
- /** The document partitioning */
- private String fDocumentPartitioning;
- /** The comment prefixes */
- private Map fPrefixesMap;
-
- /**
- * Creates and initializes the action for the given text editor. The action
- * configures its visual representation from the given resource bundle.
- *
- * @param bundle the resource bundle
- * @param prefix a prefix to be prepended to the various resource keys
- * (described in <code>ResourceAction</code> constructor), or
- * <code>null</code> if none
- * @param editor the text editor
- * @see org.eclipse.ui.texteditor.ResourceAction#ResourceAction(ResourceBundle, String, int)
- */
- public ToggleCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
- super(bundle, prefix, editor);
- }
-
- /**
- * Implementation of the <code>IAction</code> prototype. Checks if the selected
- * lines are all commented or not and uncomments/comments them respectively.
- */
- public void run() {
- if (fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null)
- return;
-
- ITextEditor editor= getTextEditor();
- if (editor == null)
- return;
-
- if (!validateEditorInputState())
- return;
-
- final int operationCode;
- if (isSelectionCommented(editor.getSelectionProvider().getSelection()))
- operationCode= ITextOperationTarget.STRIP_PREFIX;
- else
- operationCode= ITextOperationTarget.PREFIX;
-
- Shell shell= editor.getSite().getShell();
- if (!fOperationTarget.canDoOperation(operationCode)) {
- if (shell != null)
- MessageDialog.openError(shell, JavaEditorMessages.ToggleComment_error_title, JavaEditorMessages.ToggleComment_error_message);
- return;
- }
-
- Display display= null;
- if (shell != null && !shell.isDisposed())
- display= shell.getDisplay();
-
- BusyIndicator.showWhile(display, new Runnable() {
- public void run() {
- fOperationTarget.doOperation(operationCode);
- }
- });
- }
-
- /**
- * Is the given selection single-line commented?
- *
- * @param selection Selection to check
- * @return <code>true</code> iff all selected lines are commented
- */
- private boolean isSelectionCommented(ISelection selection) {
- if (!(selection instanceof ITextSelection))
- return false;
-
- ITextSelection textSelection= (ITextSelection) selection;
- if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0)
- return false;
-
- IDocument document= getTextEditor().getDocumentProvider().getDocument(getTextEditor().getEditorInput());
-
- try {
-
- IRegion block= getTextBlockFromSelection(textSelection, document);
- ITypedRegion[] regions= TextUtilities.computePartitioning(document, fDocumentPartitioning, block.getOffset(), block.getLength(), false);
-
- int lineCount= 0;
- int[] lines= new int[regions.length * 2]; // [startline, endline, startline, endline, ...]
- 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--;
- lines[j + 1]= (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));
- lineCount += lines[j + 1] - lines[j] + 1;
- }
-
- // Perform the check
- for (int i= 0, j= 0; i < regions.length; i++, j += 2) {
- String[] prefixes= (String[]) fPrefixesMap.get(regions[i].getType());
- if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0)
- if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document))
- return false;
- }
-
- return true;
-
- } catch (BadLocationException x) {
- // should not happen
- JavaScriptPlugin.log(x);
- }
-
- return false;
- }
-
- /**
- * Creates a region describing the text block (something that starts at
- * the beginning of a line) completely containing the current selection.
- *
- * @param selection The selection to use
- * @param document The document
- * @return the region describing the text block comprising the given selection
- */
- private IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) {
-
- try {
- IRegion line= document.getLineInformationOfOffset(selection.getOffset());
- int length= selection.getLength() == 0 ? line.getLength() : selection.getLength() + (selection.getOffset() - line.getOffset());
- return new Region(line.getOffset(), length);
-
- } catch (BadLocationException x) {
- // should not happen
- JavaScriptPlugin.log(x);
- }
-
- return null;
- }
-
- /**
- * 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
- */
- private 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 x) {
- // should not happen
- JavaScriptPlugin.log(x);
- }
-
- return -1;
- }
-
- /**
- * Determines whether each line is prefixed by one of the prefixes.
- *
- * @param startLine Start line in document
- * @param endLine End line in document
- * @param prefixes Possible comment prefixes
- * @param document The document
- * @return <code>true</code> iff each line from <code>startLine</code>
- * to and including <code>endLine</code> is prepended by one
- * of the <code>prefixes</code>, ignoring whitespace at the
- * begin of line
- */
- private boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) {
-
- try {
-
- // check for occurrences of prefixes in the given lines
- for (int i= startLine; i <= endLine; i++) {
-
- IRegion line= document.getLineInformation(i);
- String text= document.get(line.getOffset(), line.getLength());
-
- int[] found= TextUtilities.indexOf(prefixes, text, 0);
-
- if (found[0] == -1)
- // found a line which is not commented
- return false;
-
- String s= document.get(line.getOffset(), found[0]);
- s= s.trim();
- if (s.length() != 0)
- // found a line which is not commented
- return false;
-
- }
-
- return true;
-
- } catch (BadLocationException x) {
- // should not happen
- JavaScriptPlugin.log(x);
- }
-
- return false;
- }
-
- /**
- * Implementation of the <code>IUpdate</code> prototype method discovers
- * the operation through the current editor's
- * <code>ITextOperationTarget</code> adapter, and sets the enabled state
- * accordingly.
- */
- public void update() {
- super.update();
-
- if (!canModifyEditor()) {
- setEnabled(false);
- return;
- }
-
- ITextEditor editor= getTextEditor();
- if (fOperationTarget == null && editor != null)
- fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
-
- boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(ITextOperationTarget.PREFIX) && fOperationTarget.canDoOperation(ITextOperationTarget.STRIP_PREFIX));
- setEnabled(isEnabled);
- }
-
- /*
- * @see TextEditorAction#setEditor(ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
- super.setEditor(editor);
- fOperationTarget= null;
- }
-
- public void configure(ISourceViewer sourceViewer, SourceViewerConfiguration configuration) {
- fPrefixesMap= null;
-
- String[] types= configuration.getConfiguredContentTypes(sourceViewer);
- Map prefixesMap= new HashMap(types.length);
- for (int i= 0; i < types.length; i++) {
- String type= types[i];
- String[] prefixes= configuration.getDefaultPrefixes(sourceViewer, type);
- if (prefixes != null && prefixes.length > 0) {
- int emptyPrefixes= 0;
- for (int j= 0; j < prefixes.length; j++)
- if (prefixes[j].length() == 0)
- emptyPrefixes++;
-
- if (emptyPrefixes > 0) {
- String[] nonemptyPrefixes= new String[prefixes.length - emptyPrefixes];
- for (int j= 0, k= 0; j < prefixes.length; j++) {
- String prefix= prefixes[j];
- if (prefix.length() != 0) {
- nonemptyPrefixes[k]= prefix;
- k++;
- }
- }
- prefixes= nonemptyPrefixes;
- }
-
- prefixesMap.put(type, prefixes);
- }
- }
- fDocumentPartitioning= configuration.getConfiguredDocumentPartitioning(sourceViewer);
- fPrefixesMap= prefixesMap;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleMarkOccurrencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleMarkOccurrencesAction.java
deleted file mode 100644
index cb4bd0a8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleMarkOccurrencesAction.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * A toolbar action which toggles the {@linkplain org.eclipse.wst.jsdt.ui.PreferenceConstants#EDITOR_MARK_OCCURRENCES mark occurrences preference}.
- *
- *
- */
-public class ToggleMarkOccurrencesAction extends TextEditorAction implements IPropertyChangeListener {
-
- private IPreferenceStore fStore;
-
- /**
- * Constructs and updates the action.
- */
- public ToggleMarkOccurrencesAction() {
- super(JavaEditorMessages.getBundleForConstructedKeys(), "ToggleMarkOccurrencesAction.", null, IAction.AS_CHECK_BOX); //$NON-NLS-1$
- JavaPluginImages.setToolImageDescriptors(this, "mark_occurrences.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.TOGGLE_MARK_OCCURRENCES_ACTION);
- update();
- }
-
- /*
- * @see IAction#actionPerformed
- */
- public void run() {
- fStore.setValue(PreferenceConstants.EDITOR_MARK_OCCURRENCES, isChecked());
- }
-
- /*
- * @see TextEditorAction#update
- */
- public void update() {
- ITextEditor editor= getTextEditor();
-
- boolean checked= false;
- if (editor instanceof JavaEditor)
- checked= ((JavaEditor)editor).isMarkingOccurrences();
-
- setChecked(checked);
- setEnabled(editor != null);
- }
-
- /*
- * @see TextEditorAction#setEditor(ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
-
- super.setEditor(editor);
-
- if (editor != null) {
-
- if (fStore == null) {
- fStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- fStore.addPropertyChangeListener(this);
- }
-
- } else if (fStore != null) {
- fStore.removePropertyChangeListener(this);
- fStore= null;
- }
-
- update();
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(PreferenceConstants.EDITOR_MARK_OCCURRENCES))
- setChecked(Boolean.valueOf(event.getNewValue().toString()).booleanValue());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/TogglePresentationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/TogglePresentationAction.java
deleted file mode 100644
index f73cf59b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/TogglePresentationAction.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * A tool bar action which toggles the presentation model of the
- * connected text editor. The editor shows either the highlight range
- * only or always the whole document.
- */
-public class TogglePresentationAction extends TextEditorAction implements IPropertyChangeListener {
-
- private IPreferenceStore fStore;
-
- /**
- * Constructs and updates the action.
- */
- public TogglePresentationAction() {
- super(JavaEditorMessages.getBundleForConstructedKeys(), "TogglePresentation.", null, IAction.AS_CHECK_BOX); //$NON-NLS-1$
- JavaPluginImages.setToolImageDescriptors(this, "segment_edit.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.TOGGLE_PRESENTATION_ACTION);
- update();
- }
-
- /*
- * @see IAction#actionPerformed
- */
- public void run() {
-
- ITextEditor editor= getTextEditor();
- if (editor == null)
- return;
-
- IRegion remembered= editor.getHighlightRange();
- editor.resetHighlightRange();
-
- boolean showAll= !editor.showsHighlightRangeOnly();
- setChecked(showAll);
-
- editor.showHighlightRangeOnly(showAll);
- if (remembered != null)
- editor.setHighlightRange(remembered.getOffset(), remembered.getLength(), true);
-
- fStore.removePropertyChangeListener(this);
- fStore.setValue(PreferenceConstants.EDITOR_SHOW_SEGMENTS, showAll);
- fStore.addPropertyChangeListener(this);
- }
-
- /*
- * @see TextEditorAction#update
- */
- public void update() {
- ITextEditor editor= getTextEditor();
- boolean checked= (editor != null && editor.showsHighlightRangeOnly());
- setChecked(checked);
- if (editor instanceof CompilationUnitEditor) {
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- setEnabled(manager.getWorkingCopy(editor.getEditorInput()) != null);
- } else if (editor instanceof ClassFileEditor) {
- IEditorInput input= editor.getEditorInput();
- IClassFile cf= null;
- if (input instanceof IClassFileEditorInput) {
- IClassFileEditorInput cfi= (IClassFileEditorInput)input;
- cf= cfi.getClassFile();
- }
- setEnabled(cf != null && cf.exists());
- } else
- setEnabled(editor != null);
- }
-
- /*
- * @see TextEditorAction#setEditor(ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
-
- super.setEditor(editor);
-
- if (editor != null) {
-
- if (fStore == null) {
- fStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- fStore.addPropertyChangeListener(this);
- }
- synchronizeWithPreference(editor);
-
- } else if (fStore != null) {
- fStore.removePropertyChangeListener(this);
- fStore= null;
- }
-
- update();
- }
-
- /**
- * Synchronizes the appearance of the editor with what the preference store tells him.
- *
- * @param editor the text editor
- */
- private void synchronizeWithPreference(ITextEditor editor) {
-
- if (editor == null)
- return;
-
- boolean showSegments= fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS);
- setChecked(showSegments);
-
- if (editor.showsHighlightRangeOnly() != showSegments) {
- IRegion remembered= editor.getHighlightRange();
- editor.resetHighlightRange();
- editor.showHighlightRangeOnly(showSegments);
- if (remembered != null)
- editor.setHighlightRange(remembered.getOffset(), remembered.getLength(), true);
- }
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(PreferenceConstants.EDITOR_SHOW_SEGMENTS))
- synchronizeWithPreference(getTextEditor());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleTextHoverAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleTextHoverAction.java
deleted file mode 100644
index ce48c36d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ToggleTextHoverAction.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.TextEditorAction;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-
-/**
- * A toolbar action which toggles the enabling state of the
- * editor's text hover.
- */
-public class ToggleTextHoverAction extends TextEditorAction implements IPropertyChangeListener {
-
-
- private IPreferenceStore fStore;
-
- /**
- * Constructs and updates the action.
- */
- public ToggleTextHoverAction() {
- super(JavaEditorMessages.getBundleForConstructedKeys(), "ToggleTextHover.", null); //$NON-NLS-1$
- JavaPluginImages.setToolImageDescriptors(this, "jdoc_hover_edit.gif"); //$NON-NLS-1$
- setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_TEXT_HOVER);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.TOGGLE_TEXTHOVER_ACTION);
- update();
- }
-
- /*
- * @see IAction#actionPerformed
- */
- public void run() {
- ITextEditor editor= getTextEditor();
- if (editor == null)
- return;
-
- boolean showHover= !fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_HOVER);
- setChecked(showHover);
-
- fStore.removePropertyChangeListener(this);
- fStore.setValue(PreferenceConstants.EDITOR_SHOW_HOVER, showHover);
- fStore.addPropertyChangeListener(this);
- }
-
- /*
- * @see TextEditorAction#update
- */
- public void update() {
- boolean showHover= fStore != null && fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_HOVER);
- setChecked(showHover);
- setEnabled(getTextEditor() != null);
- }
-
- /*
- * @see TextEditorAction#setEditor(ITextEditor)
- */
- public void setEditor(ITextEditor editor) {
- super.setEditor(editor);
- if (editor != null) {
- if (fStore == null) {
- fStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- fStore.addPropertyChangeListener(this);
- }
- } else if (fStore != null) {
- fStore.removePropertyChangeListener(this);
- fStore= null;
- }
- update();
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(PreferenceConstants.EDITOR_SHOW_HOVER))
- update();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/WorkingCopyManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/WorkingCopyManager.java
deleted file mode 100644
index 556d47a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/WorkingCopyManager.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.javaeditor;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManagerExtension;
-
-
-/**
- * This working copy manager works together with a given compilation unit document provider and
- * additionally offers to "overwrite" the working copy provided by this document provider.
- */
-public class WorkingCopyManager implements IWorkingCopyManager, IWorkingCopyManagerExtension {
-
- private ICompilationUnitDocumentProvider fDocumentProvider;
- private Map fMap;
- private boolean fIsShuttingDown;
-
- /**
- * Creates a new working copy manager that co-operates with the given
- * compilation unit document provider.
- *
- * @param provider the provider
- */
- public WorkingCopyManager(ICompilationUnitDocumentProvider provider) {
- Assert.isNotNull(provider);
- fDocumentProvider= provider;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.IWorkingCopyManager#connect(org.eclipse.ui.IEditorInput)
- */
- public void connect(IEditorInput input) throws CoreException {
- fDocumentProvider.connect(input);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.IWorkingCopyManager#disconnect(org.eclipse.ui.IEditorInput)
- */
- public void disconnect(IEditorInput input) {
- fDocumentProvider.disconnect(input);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.IWorkingCopyManager#shutdown()
- */
- public void shutdown() {
- if (!fIsShuttingDown) {
- fIsShuttingDown= true;
- try {
- if (fMap != null) {
- fMap.clear();
- fMap= null;
- }
- fDocumentProvider.shutdown();
- } finally {
- fIsShuttingDown= false;
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.IWorkingCopyManager#getWorkingCopy(org.eclipse.ui.IEditorInput)
- */
- public IJavaScriptUnit getWorkingCopy(IEditorInput input) {
- return getWorkingCopy(input, true);
- }
-
- /**
- * Returns the working copy remembered for the compilation unit encoded in the
- * given editor input.
- * <p>
- * Note: This method must not be part of the public {@link IWorkingCopyManager} API.
- * </p>
- *
- * @param input the editor input
- * @param primaryOnly if <code>true</code> only primary working copies will be returned
- * @return the working copy of the compilation unit, or <code>null</code> if the
- * input does not encode an editor input, or if there is no remembered working
- * copy for this compilation unit
- *
- */
- public IJavaScriptUnit getWorkingCopy(IEditorInput input, boolean primaryOnly) {
- IJavaScriptUnit unit= fMap == null ? null : (IJavaScriptUnit) fMap.get(input);
- if (unit == null)
- unit= fDocumentProvider.getWorkingCopy(input);
- if (unit != null && (!primaryOnly || JavaModelUtil.isPrimary(unit)))
- return unit;
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#setWorkingCopy(org.eclipse.ui.IEditorInput, org.eclipse.wst.jsdt.core.IJavaScriptUnit)
- */
- public void setWorkingCopy(IEditorInput input, IJavaScriptUnit workingCopy) {
- if (fDocumentProvider.getDocument(input) != null) {
- if (fMap == null)
- fMap= new HashMap();
- fMap.put(input, workingCopy);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#removeWorkingCopy(org.eclipse.ui.IEditorInput)
- */
- public void removeWorkingCopy(IEditorInput input) {
- fMap.remove(input);
- if (fMap.isEmpty())
- fMap= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/AbstractSaveParticipantPreferenceConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/AbstractSaveParticipantPreferenceConfiguration.java
deleted file mode 100644
index c847d102..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/AbstractSaveParticipantPreferenceConfiguration.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public abstract class AbstractSaveParticipantPreferenceConfiguration implements ISaveParticipantPreferenceConfiguration {
-
- /**
- * Preference prefix that is appended to the id of {@link SaveParticipantDescriptor save participants}.
- *
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @see SaveParticipantDescriptor
- *
- */
- private static final String EDITOR_SAVE_PARTICIPANT_PREFIX= "editor_save_participant_"; //$NON-NLS-1$
-
- private SelectionButtonDialogField fEnableField;
- private Control fConfigControl;
- private IScopeContext fContext;
- private ControlEnableState fConfigControlEnabledState;
-
- /**
- * The id of the post save listener managed by this configuration block, not null
- */
- protected abstract String getPostSaveListenerId();
-
- /**
- * The name of the post save listener managed by this configuration block, not null
- */
- protected abstract String getPostSaveListenerName();
-
- protected Control createConfigControl(Composite composite, IPreferencePageContainer container) {
- //Default has no specific controls
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Control createControl(Composite parent, IPreferencePageContainer container) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridData gridData= new GridData(SWT.FILL, SWT.TOP, true, false);
- composite.setLayoutData(gridData);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- fEnableField= new SelectionButtonDialogField(SWT.CHECK);
- fEnableField.setLabelText(getPostSaveListenerName());
- fEnableField.doFillIntoGrid(composite, 1);
-
- fConfigControl= createConfigControl(composite, container);
-
- return composite;
- }
-
- /**
- * {@inheritDoc}
- */
- public void initialize(final IScopeContext context, IAdaptable element) {
- boolean enabled= isEnabled(context);
- fEnableField.setSelection(enabled);
-
- if (fConfigControl != null && !enabled) {
- fConfigControlEnabledState= ControlEnableState.disable(fConfigControl);
- }
-
- fEnableField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- enableConfigControl(fEnableField.isSelected());
- }
- });
-
- fContext= context;
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {}
-
- /**
- * {@inheritDoc}
- */
- public void performDefaults() {
- String key= getPreferenceKey();
- boolean defaultEnabled= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).getBoolean(key, false);
- fContext.getNode(JavaScriptUI.ID_PLUGIN).putBoolean(key, defaultEnabled);
- fEnableField.setSelection(defaultEnabled);
- }
-
- /**
- * {@inheritDoc}
- */
- public void performOk() {}
-
- /**
- * {@inheritDoc}
- */
- public void enableProjectSettings() {
- fContext.getNode(JavaScriptUI.ID_PLUGIN).putBoolean(getPreferenceKey(), fEnableField.isSelected());
- }
-
- /**
- * {@inheritDoc}
- */
- public void disableProjectSettings() {
- fContext.getNode(JavaScriptUI.ID_PLUGIN).remove(getPreferenceKey());
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasSettingsInScope(IScopeContext context) {
- return context.getNode(JavaScriptUI.ID_PLUGIN).get(getPreferenceKey(), null) != null;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isEnabled(IScopeContext context) {
- IEclipsePreferences node;
- if (hasSettingsInScope(context)) {
- node= context.getNode(JavaScriptUI.ID_PLUGIN);
- } else {
- node= new InstanceScope().getNode(JavaScriptUI.ID_PLUGIN);
- }
- IEclipsePreferences defaultNode= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN);
-
- String key= getPreferenceKey();
- return node.getBoolean(key, defaultNode.getBoolean(key, false));
- }
-
- protected void enableConfigControl(boolean isEnabled) {
- fContext.getNode(JavaScriptUI.ID_PLUGIN).putBoolean(getPreferenceKey(), isEnabled);
- if (fConfigControl != null) {
- if (fConfigControlEnabledState != null) {
- fConfigControlEnabledState.restore();
- fConfigControlEnabledState= null;
- } else {
- fConfigControlEnabledState= ControlEnableState.disable(fConfigControl);
- }
- }
- }
-
- private String getPreferenceKey() {
- return EDITOR_SAVE_PARTICIPANT_PREFIX + getPostSaveListenerId();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/IPostSaveListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/IPostSaveListener.java
deleted file mode 100644
index e3c6da08..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/IPostSaveListener.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- * This <code>IPostSaveListener</code> is informed when
- * a compilation unit is saved through the {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider}.
- * <p>
- * In oder to get notified the listener must be registered with the {@link SaveParticipantRegistry}
- * and be enabled on the save participant preference page.</p>
- * <p>
- * The notification order of post save listeners is unspecified.</p>
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * @see SaveParticipantDescriptor
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider
- *
- */
-public interface IPostSaveListener {
-
- /**
- * A human readable name of this listener.
- *
- * @return the name
- */
- String getName();
-
- /**
- * The unique id of this listener.
- *
- * @return a non-empty id
- */
- String getId();
-
- /**
- * Informs this post save listener that the given <code>compilationUnit</code>
- * has been saved by the {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider}. The listener
- * is allowed to modify the given compilation unit and to open a dialog.
- * <p>
- * <em>Every implementor of this method must strictly obey these rules:</em>
- * <ul>
- * <li>not touch any file other than the given <code>compilationUnit</code>
- * which is already locked by a scheduling rule </li>
- * <li>changing the scheduling rule or posting a new job is not allowed</li>
- * <li>it is not allowed to save the given <code>compilationUnit</code></li>
- * <li>it must be able to deal with unsaved resources and with compilation units which are not on the Java build path</li>
- * <li>must not assume to be called in the UI thread</li>
- * <li>should be as fast as possible since this code is executed every time the <code>compilationUnit</code> is saved</li>
- * </ul>
- * The compilation unit document provider can disable a listener that violates any of the above rules.</p>
- *
- * @param compilationUnit the compilation unit which was saved
- * @param monitor the progress monitor for reporting progress
- * @see org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider
- */
- void saved(IJavaScriptUnit compilationUnit, IProgressMonitor monitor) throws CoreException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java
deleted file mode 100644
index 113fbdce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-/**
- * Preference UI to configure details of a save participant on the the
- * Java &gt; Editor &gt; Save Participants preference page.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- */
-public interface ISaveParticipantPreferenceConfiguration {
-
- /**
- * Creates a control that will be displayed on the Java &gt; Editor &gt; Save Participants
- * preference page to edit the details of a save participant.
- *
- * @param parent the parent composite to which to add the preferences control
- * @param container the container in which this preference configuration is displayed
- * @return the control that was added to the <code>parent</code>
- */
- Control createControl(Composite parent, IPreferencePageContainer container);
-
- /**
- * Called after creating the control.
- * <p>
- * Implementations should load the preferences values and update the controls accordingly.
- * </p>
- * @param context the context from which to load the preference values from
- * @param element the element to configure, or null if this configures the workspace settings
- */
- void initialize(IScopeContext context, IAdaptable element);
-
- /**
- * Called when the <code>OK</code> button is pressed on the preference
- * page.
- * <p>
- * Implementations should commit the configured preference settings
- * into their form of preference storage.</p>
- */
- void performOk();
-
- /**
- * Called when the <code>Defaults</code> button is pressed on the
- * preference page.
- * <p>
- * Implementation should reset any preference settings to
- * their default values and adjust the controls accordingly.</p>
- */
- void performDefaults();
-
- /**
- * Called when the preference page is being disposed.
- * <p>
- * Implementations should free any resources they are holding on to.</p>
- */
- void dispose();
-
- /**
- * Called when project specific settings have been enabled
- */
- void enableProjectSettings();
-
- /**
- * Called when project specific settings have been disabled
- */
- void disableProjectSettings();
-
- /**
- * Called when a compilation unit is saved.
- * <p>
- * @param context the context in which the compilation unit is saved
- * @return true if the corresponding {@link IPostSaveListener} needs to be informed
- */
- boolean isEnabled(IScopeContext context);
-
- /**
- * Called when the property page is opened to check whether this has enabled settings
- * in the given context.
- *
- * @param context the context to check
- * @return true if this has settings in context
- */
- boolean hasSettingsInScope(IScopeContext context);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java
deleted file mode 100644
index a6d37b4e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import org.eclipse.core.runtime.Assert;
-
-/**
- * Describes a save participant contribution.
- *
- *
- */
-public class SaveParticipantDescriptor {
-
- /** The listener */
- private final IPostSaveListener fPostSaveListener;
- /** The preference configuration block, if any */
- private ISaveParticipantPreferenceConfiguration fPreferenceConfiguration;
-
- /**
- * Creates a new descriptor which connects a {@link IPostSaveListener}
- * with an {@link ISaveParticipantPreferenceConfiguration}.
- *
- * @param listener the listener
- */
- SaveParticipantDescriptor(IPostSaveListener listener) {
- Assert.isNotNull(listener);
-
- fPostSaveListener= listener;
- }
-
- /**
- * Returns the post save listener of the described
- * save participant
- *
- * @return the listener
- */
- public IPostSaveListener getPostSaveListener() {
- return fPostSaveListener;
- }
-
- /**
- * Creates a new preference configuration of the described
- * save participant.
- *
- * @return the preference configuration
- */
- public ISaveParticipantPreferenceConfiguration createPreferenceConfiguration() {
- return new AbstractSaveParticipantPreferenceConfiguration() {
-
- protected String getPostSaveListenerId() {
- return fPostSaveListener.getId();
- }
-
- protected String getPostSaveListenerName() {
- return fPostSaveListener.getName();
- }
- };
- }
-
- /**
- * Returns the preference configuration of the described
- * save participant.
- *
- * @return the preference configuration
- */
- public ISaveParticipantPreferenceConfiguration getPreferenceConfiguration() {
- if (fPreferenceConfiguration == null)
- fPreferenceConfiguration= createPreferenceConfiguration();
-
- return fPreferenceConfiguration;
- }
-
- /**
- * Returns the identifier of the described save participant.
- *
- * @return the non-empty id of this descriptor
- */
- public String getId() {
- return fPostSaveListener.getId();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java
deleted file mode 100644
index 3244d71c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- *
- *
- */
-final class SaveParticipantMessages extends NLS {
-
- private static final String BUNDLE_NAME= SaveParticipantMessages.class.getName();
-
- private SaveParticipantMessages() {
- // Do not instantiate
- }
-
- public static String SaveParticipantRegistry_participantNotFound;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, SaveParticipantMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties
deleted file mode 100644
index 3dcc0868..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2006, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-SaveParticipantRegistry_participantNotFound= The ''{0}'' save participant could not be found and will be disabled.
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantRegistry.java
deleted file mode 100644
index 3c36260b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantRegistry.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpPostSaveListener;
-import org.eclipse.wst.jsdt.internal.ui.fix.CleanUpSaveParticipantPreferenceConfiguration;
-
-/**
- * A registry for save participants. This registry manages
- * {@link SaveParticipantDescriptor}s and keeps track of enabled save
- * participants.
- * <p>
- * Save participants can be enabled and disabled on the Java &gt; Editor &gt;
- * Save Participants preference page. Enabled save participants are notified
- * through a call to
- * {@link IPostSaveListener#saved(org.eclipse.wst.jsdt.core.IJavaScriptUnit, org.eclipse.core.runtime.IProgressMonitor)}
- * whenever the {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider} saves a compilation unit
- * that is in the workspace.</p>
- * <p>
- * An instance of this registry can be received through a call to {@link org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin#getSaveParticipantRegistry()}.</p>
- *
- *
- */
-public final class SaveParticipantRegistry {
-
- private static final IPostSaveListener[] EMPTY_ARRAY= new IPostSaveListener[0];
-
- /** The map of descriptors, indexed by their identifiers. */
- private Map fDescriptors;
-
- /**
- * Creates a new instance.
- */
- public SaveParticipantRegistry() {
- }
-
- /**
- * Returns an array of <code>SaveParticipantDescriptor</code> describing
- * all registered save participants.
- *
- * @return the array of registered save participant descriptors
- */
- public synchronized SaveParticipantDescriptor[] getSaveParticipantDescriptors() {
- ensureRegistered();
- return (SaveParticipantDescriptor[]) fDescriptors.values().toArray(new SaveParticipantDescriptor[fDescriptors.size()]);
- }
-
- /**
- * Returns the save participant descriptor for the given <code>id</code> or
- * <code>null</code> if no such listener is registered.
- *
- * @param id the identifier of the requested save participant
- * @return the corresponding descriptor, or <code>null</code> if none can be found
- */
- public synchronized SaveParticipantDescriptor getSaveParticipantDescriptor(String id) {
- ensureRegistered();
- return (SaveParticipantDescriptor) fDescriptors.get(id);
- }
-
- /**
- * Ensures that all descriptors are created and stored in
- * <code>fDescriptors</code>.
- */
- private void ensureRegistered() {
- if (fDescriptors == null)
- reloadDescriptors();
- }
-
- /**
- * Loads the save participants.
- * <p>
- * This method can be called more than once in
- * order to reload from a changed extension registry.
- * </p>
- */
- private void reloadDescriptors() {
- Map map= new HashMap();
- SaveParticipantDescriptor desc= new SaveParticipantDescriptor(new CleanUpPostSaveListener()) {
- /**
- * {@inheritDoc}
- */
- public ISaveParticipantPreferenceConfiguration createPreferenceConfiguration() {
- return new CleanUpSaveParticipantPreferenceConfiguration();
- }
- };
- map.put(desc.getId(), desc);
-
- fDescriptors= map;
- }
-
- public void dispose() {
- }
-
- /**
- * Checks weather there are enabled or disabled post save listener in the given context.
- *
- * @param context to context to check, not null
- * @return true if there are settings in context
- */
- public synchronized boolean hasSettingsInScope(IScopeContext context) {
- ensureRegistered();
-
- for (Iterator iterator= fDescriptors.values().iterator(); iterator.hasNext();) {
- SaveParticipantDescriptor descriptor= (SaveParticipantDescriptor)iterator.next();
- if (descriptor.getPreferenceConfiguration().hasSettingsInScope(context))
- return true;
- }
-
- return false;
- }
-
- public IPostSaveListener[] getEnabledPostSaveListeners(IProject project) {
- return getEnabledPostSaveListeners(new ProjectScope(project));
- }
-
- /**
- * Returns an array of <code>IPostSaveListener</code> which are
- * enabled in the given context.
- *
- * @param context the context from which to retrive the settings from, not null
- * @return the current enabled post save listeners according to the preferences
- */
- public synchronized IPostSaveListener[] getEnabledPostSaveListeners(IScopeContext context) {
- ensureRegistered();
-
- ArrayList result= null;
- for (Iterator iterator= fDescriptors.values().iterator(); iterator.hasNext();) {
- SaveParticipantDescriptor descriptor= (SaveParticipantDescriptor)iterator.next();
- if (descriptor.getPreferenceConfiguration().isEnabled(context)) {
- if (result == null) {
- result= new ArrayList();
- }
- result.add(descriptor.getPostSaveListener());
- }
- }
-
- if (result == null) {
- return EMPTY_ARRAY;
- } else {
- return (IPostSaveListener[])result.toArray(new IPostSaveListener[result.size()]);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/GoToNextPreviousMemberAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/GoToNextPreviousMemberAction.java
deleted file mode 100644
index 6bd51299..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/GoToNextPreviousMemberAction.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class GoToNextPreviousMemberAction extends Action implements IUpdate {
-
- public static final String NEXT_MEMBER= "GoToNextMember"; //$NON-NLS-1$
- public static final String PREVIOUS_MEMBER= "GoToPreviousMember"; //$NON-NLS-1$
- private JavaEditor fEditor;
- private boolean fIsGotoNext;
-
- public static GoToNextPreviousMemberAction newGoToNextMemberAction(JavaEditor editor) {
- String text= SelectionActionMessages.GotoNextMember_label;
- return new GoToNextPreviousMemberAction(editor, text, true);
- }
-
- public static GoToNextPreviousMemberAction newGoToPreviousMemberAction(JavaEditor editor) {
- String text= SelectionActionMessages.GotoPreviousMember_label;
- return new GoToNextPreviousMemberAction(editor, text, false);
- }
-
- private GoToNextPreviousMemberAction(JavaEditor editor, String text, boolean isGotoNext) {
- super(text);
- Assert.isNotNull(editor);
- fEditor= editor;
- fIsGotoNext= isGotoNext;
- update();
- if (isGotoNext)
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_NEXT_MEMBER_ACTION);
- else
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_PREVIOUS_MEMBER_ACTION);
- }
-
- /*
- * This constructor is for testing purpose only.
- */
- public GoToNextPreviousMemberAction(boolean isSelectNext) {
- super(""); //$NON-NLS-1$
- fIsGotoNext= isSelectNext;
- }
-
- public void update() {
- boolean enabled= false;
- ISourceReference ref= getSourceReference();
- if (ref != null) {
- ISourceRange range;
- try {
- range= ref.getSourceRange();
- enabled= range != null && range.getLength() > 0;
- } catch (JavaScriptModelException e) {
- // enabled= false;
- }
- }
- setEnabled(enabled);
- }
-
- /* (non-JavaDoc)
- * Method declared in IAction.
- */
- public final void run() {
- ITextSelection selection= getTextSelection();
- ISourceRange newRange= getNewSelectionRange(createSourceRange(selection), null);
- // Check if new selection differs from current selection
- if (selection.getOffset() == newRange.getOffset() && selection.getLength() == newRange.getLength())
- return;
- fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
- }
-
- private IType[] getTypes() throws JavaScriptModelException {
- IEditorInput input= fEditor.getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- return new IType[] { ((IClassFileEditorInput)input).getClassFile().getType() };
- } else {
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input).getAllTypes();
- }
- }
-
- private ISourceReference getSourceReference() {
- IEditorInput input= fEditor.getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- return ((IClassFileEditorInput)input).getClassFile();
- } else {
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input);
- }
- }
-
- private ITextSelection getTextSelection() {
- return (ITextSelection)fEditor.getSelectionProvider().getSelection();
- }
-
- public ISourceRange getNewSelectionRange(ISourceRange oldSourceRange, IType[] types) {
- try{
- if (types == null)
- types= getTypes();
- Integer[] offsetArray= createOffsetArray(types);
- if (offsetArray.length == 0)
- return oldSourceRange;
- Arrays.sort(offsetArray);
- Integer oldOffset= new Integer(oldSourceRange.getOffset());
- int index= Arrays.binarySearch(offsetArray, oldOffset);
-
- if (fIsGotoNext)
- return createNewSourceRange(getNextOffset(index, offsetArray, oldOffset));
- else
- return createNewSourceRange(getPreviousOffset(index, offsetArray, oldOffset));
-
- } catch (JavaScriptModelException e){
- JavaScriptPlugin.log(e); //dialog would be too heavy here
- return oldSourceRange;
- }
- }
-
- private static Integer getPreviousOffset(int index, Integer[] offsetArray, Integer oldOffset) {
- if (index == -1)
- return oldOffset;
- if (index == 0)
- return offsetArray[0];
- if (index > 0)
- return offsetArray[index - 1];
- Assert.isTrue(index < -1);
- int absIndex= Math.abs(index);
- return offsetArray[absIndex - 2];
- }
-
- private static Integer getNextOffset(int index, Integer[] offsetArray, Integer oldOffset) {
- if (index == -1)
- return offsetArray[0];
-
- if (index == 0){
- if (offsetArray.length != 1)
- return offsetArray[1];
- else
- return offsetArray[0];
- }
- if (index > 0){
- if (index == offsetArray.length - 1)
- return oldOffset;
- return offsetArray[index + 1];
- }
- Assert.isTrue(index < -1);
- int absIndex= Math.abs(index);
- if (absIndex > offsetArray.length)
- return oldOffset;
- else
- return offsetArray[absIndex - 1];
- }
-
- private static ISourceRange createNewSourceRange(Integer offset){
- return new SourceRange(offset.intValue(), 0);
- }
-
- private static Integer[] createOffsetArray(IType[] types) throws JavaScriptModelException {
- List result= new ArrayList();
- for (int i= 0; i < types.length; i++) {
- IType iType= types[i];
- addOffset(result, iType.getNameRange().getOffset());
- addOffset(result, iType.getSourceRange().getOffset() + iType.getSourceRange().getLength());
- addMemberOffsetList(result, iType.getFunctions());
- addMemberOffsetList(result, iType.getFields());
- addMemberOffsetList(result, iType.getInitializers());
- }
- return (Integer[]) result.toArray(new Integer[result.size()]);
- }
-
- private static void addMemberOffsetList(List result, IMember[] members) throws JavaScriptModelException {
- for (int i= 0; i < members.length; i++) {
- addOffset(result, getOffset(members[i]));
- }
- }
-
- private static int getOffset(IMember iMember) throws JavaScriptModelException {
- //special case
- if (iMember.getElementType() == IJavaScriptElement.INITIALIZER)
- return firstOpeningBraceOffset((IInitializer)iMember);
-
- if (iMember.getNameRange() != null && iMember.getNameRange().getOffset() >= 0)
- return iMember.getNameRange().getOffset();
- return iMember.getSourceRange().getOffset();
- }
-
- private static int firstOpeningBraceOffset(IInitializer iInitializer) throws JavaScriptModelException {
- try {
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(iInitializer.getSource().toCharArray());
- int token= scanner.getNextToken();
- while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLBRACE)
- token= scanner.getNextToken();
- if (token == ITerminalSymbols.TokenNameLBRACE)
- return iInitializer.getSourceRange().getOffset() + scanner.getCurrentTokenStartPosition() + scanner.getRawTokenSource().length;
- return iInitializer.getSourceRange().getOffset();
- } catch (InvalidInputException e) {
- return iInitializer.getSourceRange().getOffset();
- }
- }
-
- //-- private helper methods
-
- private static ISourceRange createSourceRange(ITextSelection ts) {
- return new SourceRange(ts.getOffset(), ts.getLength());
- }
-
- private static void addOffset(List result, int offset) {
- if (offset >= 0)
- result.add(new Integer(offset));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java
deleted file mode 100644
index 0eb50fcb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- *
- *
- */
-final class SelectionActionMessages extends NLS {
-
- private static final String BUNDLE_NAME= SelectionActionMessages.class.getName();
-
- private SelectionActionMessages() {
- // Do not instantiate
- }
-
- public static String StructureSelect_error_title;
- public static String StructureSelect_error_message;
- public static String StructureSelectNext_label;
- public static String StructureSelectNext_tooltip;
- public static String StructureSelectNext_description;
- public static String StructureSelectPrevious_label;
- public static String StructureSelectPrevious_tooltip;
- public static String StructureSelectPrevious_description;
- public static String StructureSelectEnclosing_label;
- public static String StructureSelectEnclosing_tooltip;
- public static String StructureSelectEnclosing_description;
- public static String StructureSelectHistory_label;
- public static String StructureSelectHistory_tooltip;
- public static String StructureSelectHistory_description;
-
- public static String GotoNextMember_label;
- public static String GotoPreviousMember_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, SelectionActionMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties
deleted file mode 100644
index 3d3cce90..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties
+++ /dev/null
@@ -1,32 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-StructureSelect_error_title= Expand Selection To
-StructureSelect_error_message= No source code attached to class file. To perform this operation you will need to attach source.
-
-StructureSelectNext_label=&Next Element
-StructureSelectNext_tooltip=Expand Selection to Include Next Sibling
-StructureSelectNext_description=Expand selection to include next sibling
-
-StructureSelectPrevious_label=&Previous Element
-StructureSelectPrevious_tooltip=Expand Selection to Include Previous Sibling
-StructureSelectPrevious_description=Expand selection to include previous sibling
-
-StructureSelectEnclosing_label=&Enclosing Element
-StructureSelectEnclosing_tooltip=Expand Selection to Include Enclosing Element
-StructureSelectEnclosing_description=Expand selection to include enclosing element
-
-StructureSelectHistory_label=&Restore Last Selection
-StructureSelectHistory_tooltip=Restore Last Selection
-StructureSelectHistory_description=Restore last selection
-
-GotoNextMember_label= N&ext Member
-GotoPreviousMember_label= Previ&ous Member
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionHistory.java
deleted file mode 100644
index a1a125d2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionHistory.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class SelectionHistory {
-
- private List fHistory;
- private JavaEditor fEditor;
- private ISelectionChangedListener fSelectionListener;
- private int fSelectionChangeListenerCounter;
- private StructureSelectHistoryAction fHistoryAction;
-
- public SelectionHistory(JavaEditor editor) {
- Assert.isNotNull(editor);
- fEditor= editor;
- fHistory= new ArrayList(3);
- fSelectionListener= new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if (fSelectionChangeListenerCounter == 0)
- flush();
- }
- };
- fEditor.getSelectionProvider().addSelectionChangedListener(fSelectionListener);
- }
-
- public void setHistoryAction(StructureSelectHistoryAction action) {
- Assert.isNotNull(action);
- fHistoryAction= action;
- }
-
- public boolean isEmpty() {
- return fHistory.isEmpty();
- }
-
- public void remember(ISourceRange range) {
- fHistory.add(range);
- fHistoryAction.update();
- }
-
- public ISourceRange getLast() {
- if (isEmpty())
- return null;
- int size= fHistory.size();
- ISourceRange result= (ISourceRange)fHistory.remove(size - 1);
- fHistoryAction.update();
- return result;
- }
-
- public void flush() {
- if (fHistory.isEmpty())
- return;
- fHistory.clear();
- fHistoryAction.update();
- }
-
- public void ignoreSelectionChanges() {
- fSelectionChangeListenerCounter++;
- }
-
- public void listenToSelectionChanges() {
- fSelectionChangeListenerCounter--;
- }
-
- public void dispose() {
- fEditor.getSelectionProvider().removeSelectionChangedListener(fSelectionListener);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectEnclosingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectEnclosingAction.java
deleted file mode 100644
index 8a152b8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectEnclosingAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class StructureSelectEnclosingAction extends StructureSelectionAction {
-
- public StructureSelectEnclosingAction(JavaEditor editor, SelectionHistory history) {
- super(SelectionActionMessages.StructureSelectEnclosing_label, editor, history);
- setToolTipText(SelectionActionMessages.StructureSelectEnclosing_tooltip);
- setDescription(SelectionActionMessages.StructureSelectEnclosing_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.STRUCTURED_SELECT_ENCLOSING_ACTION);
- }
-
- /*
- * This constructor is for testing purpose only.
- */
- public StructureSelectEnclosingAction() {
- }
-
- /*
- * @see StructureSelectionAction#internalGetNewSelectionRange(ISourceRange, IJavaScriptUnit, SelectionAnalyzer)
- */
- ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaScriptModelException{
- ASTNode first= selAnalyzer.getFirstSelectedNode();
- if (first == null || first.getParent() == null)
- return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);
-
- return getSelectedNodeSourceRange(sr, first.getParent());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectHistoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectHistoryAction.java
deleted file mode 100644
index 6091e878..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectHistoryAction.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class StructureSelectHistoryAction extends Action implements IUpdate {
- private JavaEditor fEditor;
- private SelectionHistory fHistory;
-
- public StructureSelectHistoryAction(JavaEditor editor, SelectionHistory history) {
- super(SelectionActionMessages.StructureSelectHistory_label);
- setToolTipText(SelectionActionMessages.StructureSelectHistory_tooltip);
- setDescription(SelectionActionMessages.StructureSelectHistory_description);
- Assert.isNotNull(history);
- Assert.isNotNull(editor);
- fHistory= history;
- fEditor= editor;
- update();
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.STRUCTURED_SELECTION_HISTORY_ACTION);
- }
-
- public void update() {
- setEnabled(!fHistory.isEmpty());
- }
-
- public void run() {
- ISourceRange old= fHistory.getLast();
- if (old != null) {
- try {
- fHistory.ignoreSelectionChanges();
- fEditor.selectAndReveal(old.getOffset(), old.getLength());
- } finally {
- fHistory.listenToSelectionChanges();
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectNextAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectNextAction.java
deleted file mode 100644
index 1d7b551c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectNextAction.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class StructureSelectNextAction extends StructureSelectionAction{
-
- private static class NextNodeAnalyzer extends GenericVisitor {
- private final int fOffset;
- private ASTNode fNextNode;
- private NextNodeAnalyzer(int offset) {
- super(true);
- fOffset= offset;
- }
- public static ASTNode perform(int offset, ASTNode lastCoveringNode) {
- NextNodeAnalyzer analyzer= new NextNodeAnalyzer(offset);
- lastCoveringNode.accept(analyzer);
- return analyzer.fNextNode;
- }
- protected boolean visitNode(ASTNode node) {
- int start= node.getStartPosition();
- int end= start + node.getLength();
- if (start == fOffset) {
- fNextNode= node;
- return true;
- } else {
- return (start < fOffset && fOffset < end);
- }
- }
- }
-
- public StructureSelectNextAction(JavaEditor editor, SelectionHistory history) {
- super(SelectionActionMessages.StructureSelectNext_label, editor, history);
- setToolTipText(SelectionActionMessages.StructureSelectNext_tooltip);
- setDescription(SelectionActionMessages.StructureSelectNext_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.STRUCTURED_SELECT_NEXT_ACTION);
- }
-
- /*
- * This constructor is for testing purpose only.
- */
- public StructureSelectNextAction() {
- }
-
- /* non java doc
- * @see StructureSelectionAction#internalGetNewSelectionRange(ISourceRange, IJavaScriptUnit, SelectionAnalyzer)
- */
- ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaScriptModelException{
- if (oldSourceRange.getLength() == 0 && selAnalyzer.getLastCoveringNode() != null) {
- ASTNode previousNode= NextNodeAnalyzer.perform(oldSourceRange.getOffset(), selAnalyzer.getLastCoveringNode());
- if (previousNode != null)
- return getSelectedNodeSourceRange(sr, previousNode);
- }
- ASTNode first= selAnalyzer.getFirstSelectedNode();
- if (first == null)
- return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);
-
- ASTNode parent= first.getParent();
- if (parent == null)
- return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);
-
- ASTNode lastSelectedNode= selAnalyzer.getSelectedNodes()[selAnalyzer.getSelectedNodes().length - 1];
- ASTNode nextNode= getNextNode(parent, lastSelectedNode);
- if (nextNode == parent)
- return getSelectedNodeSourceRange(sr, first.getParent());
- int offset= oldSourceRange.getOffset();
- int end= Math.min(sr.getSourceRange().getLength(), nextNode.getStartPosition() + nextNode.getLength() - 1);
- return StructureSelectionAction.createSourceRange(offset, end);
- }
-
- private static ASTNode getNextNode(ASTNode parent, ASTNode node){
- ASTNode[] siblingNodes= StructureSelectionAction.getSiblingNodes(node);
- if (siblingNodes == null || siblingNodes.length == 0)
- return parent;
- if (node == siblingNodes[siblingNodes.length -1 ])
- return parent;
- else
- return siblingNodes[StructureSelectionAction.findIndex(siblingNodes, node) + 1];
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectPreviousAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectPreviousAction.java
deleted file mode 100644
index 1f7fcfc2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectPreviousAction.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class StructureSelectPreviousAction extends StructureSelectionAction {
-
- private static class PreviousNodeAnalyzer extends GenericVisitor {
- private final int fOffset;
- private ASTNode fPreviousNode;
- private PreviousNodeAnalyzer(int offset) {
- super(true);
- fOffset= offset;
- }
- public static ASTNode perform(int offset, ASTNode lastCoveringNode) {
- PreviousNodeAnalyzer analyzer= new PreviousNodeAnalyzer(offset);
- lastCoveringNode.accept(analyzer);
- return analyzer.fPreviousNode;
- }
- protected boolean visitNode(ASTNode node) {
- int start= node.getStartPosition();
- int end= start + node.getLength();
- if (end == fOffset) {
- fPreviousNode= node;
- return true;
- } else {
- return (start < fOffset && fOffset < end);
- }
- }
- }
-
- public StructureSelectPreviousAction(JavaEditor editor, SelectionHistory history) {
- super(SelectionActionMessages.StructureSelectPrevious_label, editor, history);
- setToolTipText(SelectionActionMessages.StructureSelectPrevious_tooltip);
- setDescription(SelectionActionMessages.StructureSelectPrevious_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.STRUCTURED_SELECT_PREVIOUS_ACTION);
- }
-
- /*
- * This constructor is for testing purpose only.
- */
- public StructureSelectPreviousAction() {
- }
-
- /* non java doc
- * @see StructureSelectionAction#internalGetNewSelectionRange(ISourceRange, IJavaScriptUnit, SelectionAnalyzer)
- */
- ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaScriptModelException{
- if (oldSourceRange.getLength() == 0 && selAnalyzer.getLastCoveringNode() != null) {
- ASTNode previousNode= PreviousNodeAnalyzer.perform(oldSourceRange.getOffset(), selAnalyzer.getLastCoveringNode());
- if (previousNode != null)
- return getSelectedNodeSourceRange(sr, previousNode);
- }
- ASTNode first= selAnalyzer.getFirstSelectedNode();
- if (first == null)
- return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);
-
- ASTNode parent= first.getParent();
- if (parent == null)
- return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);
-
- ASTNode previousNode= getPreviousNode(parent, selAnalyzer.getSelectedNodes()[0]);
- if (previousNode == parent)
- return getSelectedNodeSourceRange(sr, parent);
-
- int offset= previousNode.getStartPosition();
- int end= oldSourceRange.getOffset() + oldSourceRange.getLength() - 1;
- return StructureSelectionAction.createSourceRange(offset, end);
- }
-
- private static ASTNode getPreviousNode(ASTNode parent, ASTNode node){
- ASTNode[] siblingNodes= StructureSelectionAction.getSiblingNodes(node);
- if (siblingNodes == null || siblingNodes.length == 0)
- return parent;
- if (node == siblingNodes[0]) {
- return parent;
- } else {
- int index= StructureSelectionAction.findIndex(siblingNodes, node);
- if (index < 1)
- return parent;
- return siblingNodes[index - 1];
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectionAction.java
deleted file mode 100644
index 46b76645..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/StructureSelectionAction.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.javaeditor.selectionactions;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public abstract class StructureSelectionAction extends Action {
-
- public static final String NEXT= "SelectNextElement"; //$NON-NLS-1$
- public static final String PREVIOUS= "SelectPreviousElement"; //$NON-NLS-1$
- public static final String ENCLOSING= "SelectEnclosingElement"; //$NON-NLS-1$
- public static final String HISTORY= "RestoreLastSelection"; //$NON-NLS-1$
-
- private JavaEditor fEditor;
- private SelectionHistory fSelectionHistory;
-
- protected StructureSelectionAction(String text, JavaEditor editor, SelectionHistory history) {
- super(text);
- Assert.isNotNull(editor);
- Assert.isNotNull(history);
- fEditor= editor;
- fSelectionHistory= history;
- }
-
- /*
- * This constructor is for testing purpose only.
- */
- protected StructureSelectionAction() {
- super(""); //$NON-NLS-1$
- }
-
- /*
- * Method declared in IAction.
- */
- public final void run() {
- IJavaScriptElement inputElement= EditorUtility.getEditorInputJavaElement(fEditor, false);
- if (!(inputElement instanceof ISourceReference && inputElement.exists()))
- return;
-
- ISourceReference source= (ISourceReference)inputElement;
- ISourceRange sourceRange;
- try {
- sourceRange= source.getSourceRange();
- if (sourceRange == null || sourceRange.getLength() == 0) {
- MessageDialog.openInformation(fEditor.getEditorSite().getShell(),
- SelectionActionMessages.StructureSelect_error_title,
- SelectionActionMessages.StructureSelect_error_message);
- return;
- }
- } catch (JavaScriptModelException e) {
- }
- ITextSelection selection= getTextSelection();
- ISourceRange newRange= getNewSelectionRange(createSourceRange(selection), source);
- // Check if new selection differs from current selection
- if (selection.getOffset() == newRange.getOffset() && selection.getLength() == newRange.getLength())
- return;
- fSelectionHistory.remember(new SourceRange(selection.getOffset(), selection.getLength()));
- try {
- fSelectionHistory.ignoreSelectionChanges();
- fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
- } finally {
- fSelectionHistory.listenToSelectionChanges();
- }
- }
-
- public final ISourceRange getNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr) {
- try{
- JavaScriptUnit root= getAST(sr);
- if (root == null)
- return oldSourceRange;
- Selection selection= Selection.createFromStartLength(oldSourceRange.getOffset(), oldSourceRange.getLength());
- SelectionAnalyzer selAnalyzer= new SelectionAnalyzer(selection, true);
- root.accept(selAnalyzer);
- return internalGetNewSelectionRange(oldSourceRange, sr, selAnalyzer);
- } catch (JavaScriptModelException e){
- JavaScriptPlugin.log(e); //dialog would be too heavy here
- return new SourceRange(oldSourceRange.getOffset(), oldSourceRange.getLength());
- }
- }
-
- /**
- * Subclasses determine the actual new selection.
- */
- abstract ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaScriptModelException;
-
- protected final ITextSelection getTextSelection() {
- return (ITextSelection)fEditor.getSelectionProvider().getSelection();
- }
-
- // -- helper methods for subclasses to fit a node range into the source range
-
- protected static ISourceRange getLastCoveringNodeRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaScriptModelException {
- if (selAnalyzer.getLastCoveringNode() == null)
- return oldSourceRange;
- else
- return getSelectedNodeSourceRange(sr, selAnalyzer.getLastCoveringNode());
- }
-
- protected static ISourceRange getSelectedNodeSourceRange(ISourceReference sr, ASTNode nodeToSelect) throws JavaScriptModelException {
- int offset= nodeToSelect.getStartPosition();
- int end= Math.min(sr.getSourceRange().getLength(), nodeToSelect.getStartPosition() + nodeToSelect.getLength() - 1);
- return createSourceRange(offset, end);
- }
-
- //-- private helper methods
-
- private static ISourceRange createSourceRange(ITextSelection ts){
- return new SourceRange(ts.getOffset(), ts.getLength());
- }
-
- private static JavaScriptUnit getAST(ISourceReference sr) {
- return ASTProvider.getASTProvider().getAST((IJavaScriptElement) sr, ASTProvider.WAIT_YES, null);
- }
-
- //-- helper methods for this class and subclasses
-
- static ISourceRange createSourceRange(int offset, int end){
- int length= end - offset + 1;
- if (length == 0) //to allow 0-length selection
- length= 1;
- return new SourceRange(Math.max(0, offset), length);
- }
-
- static ASTNode[] getSiblingNodes(ASTNode node) {
- ASTNode parent= node.getParent();
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent.isChildListProperty()) {
- List siblings= (List) parent.getStructuralProperty(locationInParent);
- return (ASTNode[]) siblings.toArray(new ASTNode[siblings.size()]);
- }
- return null;
- }
-
- static int findIndex(Object[] array, Object o){
- for (int i= 0; i < array.length; i++) {
- Object object= array[i];
- if (object == o)
- return i;
- }
- return -1;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java
deleted file mode 100644
index 0ab5850e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ModelProvider;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.team.core.mapping.IResourceMappingMerger;
-import org.eclipse.team.ui.mapping.ISynchronizationCompareAdapter;
-
-/**
- * Adaptor factory for model support.
- *
- *
- */
-public final class JavaModelAdapterFactory implements IAdapterFactory {
-
- /**
- * {@inheritDoc}
- */
- public Object getAdapter(final Object adaptable, final Class adapter) {
- if (adaptable instanceof JavaModelProvider) {
- if (adapter == IResourceMappingMerger.class)
- return new JavaModelMerger((ModelProvider) adaptable);
- else if (adapter == ISynchronizationCompareAdapter.class)
- return new JavaSynchronizationCompareAdapter();
- } else if (adaptable instanceof RefactoringHistory) {
- if (adapter == ResourceMapping.class)
- return new JavaRefactoringHistoryResourceMapping((RefactoringHistory) adaptable);
- else if (adapter == IResource.class)
- return new JavaRefactoringHistoryResourceMapping((RefactoringHistory) adaptable).getResource();
- } else if (adaptable instanceof RefactoringDescriptorProxy) {
- if (adapter == ResourceMapping.class)
- return new JavaRefactoringDescriptorResourceMapping((RefactoringDescriptorProxy) adaptable);
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Class[] getAdapterList() {
- return new Class[] { ResourceMapping.class, ISynchronizationCompareAdapter.class, IResource.class};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelContentProvider.java
deleted file mode 100644
index 7fd72d91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelContentProvider.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-/**
- * Content provider for Java models.
- *
- *
- */
-public final class JavaModelContentProvider extends StandardJavaScriptElementContentProvider {
-
- /** The name of the settings folder */
- private static final String NAME_SETTINGS_FOLDER= ".settings"; //$NON-NLS-1$
-
- /**
- * Creates a new java model content provider.
- */
- public JavaModelContentProvider() {
- super(true);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getChildren(final Object element) {
- if (element instanceof IJavaScriptUnit)
- return NO_CHILDREN;
- else if (element instanceof RefactoringHistory)
- return ((RefactoringHistory) element).getDescriptors();
- else if (element instanceof IJavaScriptProject) {
- final List elements= new ArrayList();
- elements.add(((IJavaScriptProject) element).getProject().getFolder(NAME_SETTINGS_FOLDER));
- final Object[] children= super.getChildren(element);
- for (int index= 0; index < children.length; index++) {
- if (!elements.contains(children[index]))
- elements.add(children[index]);
- }
- return elements.toArray();
- } else if (element instanceof IFolder) {
- final IFolder folder= (IFolder) element;
- try {
- return folder.members();
- } catch (CoreException exception) {
- // Do nothing
- }
- }
- return super.getChildren(element);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasChildren(final Object element) {
- if (element instanceof IJavaScriptUnit)
- return false;
- else if (element instanceof RefactoringHistory)
- return true;
- else if (element instanceof RefactoringDescriptorProxy)
- return false;
- else if (element instanceof IFolder)
- return true;
- return super.hasChildren(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelLabelProvider.java
deleted file mode 100644
index 93cf515c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelLabelProvider.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryControlConfiguration;
-import org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryLabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Label provider for Java models.
- *
- *
- */
-public final class JavaModelLabelProvider extends AppearanceAwareLabelProvider {
-
- /** The name of the settings folder */
- private static final String NAME_SETTINGS_FOLDER= ".settings"; //$NON-NLS-1$
-
- /** The refactoring history label provider */
- private final RefactoringHistoryLabelProvider fHistoryLabelProvider= new RefactoringHistoryLabelProvider(new RefactoringHistoryControlConfiguration(null, false, false));
-
- /** The project preferences label */
- private final String fPreferencesLabel;
-
- /** The pending refactorings label */
- private final String fRefactoringsLabel;
-
- /** The project settings image, or <code>null</code> */
- private Image fSettingsImage= null;
-
- /**
- * Creates a new java model label provider.
- */
- public JavaModelLabelProvider() {
- this(ModelMessages.JavaModelLabelProvider_project_preferences_label, ModelMessages.JavaModelLabelProvider_refactorings_label);
- }
-
- /**
- * Creates a new java model label provider.
- *
- * @param preferences
- * the preferences label
- * @param refactorings
- * the refactorings label
- */
- public JavaModelLabelProvider(final String preferences, final String refactorings) {
- super(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS);
- Assert.isNotNull(preferences);
- Assert.isNotNull(refactorings);
- fPreferencesLabel= preferences;
- fRefactoringsLabel= refactorings;
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- super.dispose();
- fHistoryLabelProvider.dispose();
- if (fSettingsImage != null && !fSettingsImage.isDisposed()) {
- fSettingsImage.dispose();
- fSettingsImage= null;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Image getImage(final Object element) {
- if (element instanceof IFolder) {
- final IFolder folder= (IFolder) element;
- if (folder.getName().equals(NAME_SETTINGS_FOLDER)) {
- if (fSettingsImage == null || fSettingsImage.isDisposed())
- fSettingsImage= JavaPluginImages.DESC_OBJS_PROJECT_SETTINGS.createImage();
- return decorateImage(fSettingsImage, element);
- }
- }
- Image image= super.getImage(element);
- if (image == null) {
- if (element instanceof RefactoringHistory)
- image= fHistoryLabelProvider.getImage(element);
- else if (element instanceof RefactoringDescriptorProxy)
- image= fHistoryLabelProvider.getImage(element);
- return decorateImage(image, element);
- }
- return image;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getText(final Object element) {
- if (element instanceof IFolder) {
- final IFolder folder= (IFolder) element;
- if (folder.getName().equals(NAME_SETTINGS_FOLDER))
- return decorateText(fPreferencesLabel, element);
- }
- String text= super.getText(element);
- if (text == null || "".equals(text)) { //$NON-NLS-1$
- if (element instanceof RefactoringHistory)
- text= fRefactoringsLabel;
- else if (element instanceof RefactoringDescriptorProxy)
- text= fHistoryLabelProvider.getText(element);
- return decorateText(text, element);
- }
- return text;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelMerger.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelMerger.java
deleted file mode 100644
index 6a0b57e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelMerger.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.resources.mapping.ModelProvider;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.ui.refactoring.model.AbstractResourceMappingMerger;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Java-aware refactoring model merger.
- *
- *
- */
-public final class JavaModelMerger extends AbstractResourceMappingMerger {
-
- /**
- * Creates a new java model merger.
- *
- * @param provider
- * the model provider
- */
- public JavaModelMerger(final ModelProvider provider) {
- super(provider);
- }
-
- /**
- * {@inheritDoc}
- */
- protected IProject[] getDependencies(final IProject[] projects) {
- Assert.isNotNull(projects);
- final Set set= new HashSet();
- for (int index= 0; index < projects.length; index++)
- getDependentProjects(set, projects[index]);
- final IProject[] result= new IProject[set.size()];
- set.toArray(result);
- return result;
- }
-
- /**
- * Returns the dependent projects of the specified project.
- *
- * @param set
- * the project set
- * @param project
- * the project to get its dependent projects
- */
- private void getDependentProjects(final Set set, final IProject project) {
- Assert.isNotNull(set);
- Assert.isNotNull(project);
- final IJavaScriptModel model= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- if (model != null) {
- try {
- final String name= project.getName();
- final IJavaScriptProject[] projects= model.getJavaScriptProjects();
- for (int index= 0; index < projects.length; index++) {
- final String[] names= projects[index].getRequiredProjectNames();
- for (int offset= 0; offset < names.length; offset++) {
- if (name.equals(names[offset]))
- set.add(projects[index].getProject());
- }
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelProvider.java
deleted file mode 100644
index 8e1ca22b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelProvider.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ModelProvider;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.resources.mapping.ResourceMappingContext;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-/**
- * Java-aware model provider.
- *
- *
- */
-public final class JavaModelProvider extends ModelProvider {
-
- /** The model provider id */
- public static final String JAVA_MODEL_PROVIDER_ID= "org.eclipse.wst.jsdt.ui.modelProvider"; //$NON-NLS-1$
-
- /**
- * Returns the resource associated with the corresponding model element.
- *
- * @param element
- * the model element
- * @return the associated resource, or <code>null</code>
- */
- public static IResource getResource(final Object element) {
- IResource resource= null;
- if (element instanceof IJavaScriptElement) {
- resource= ((IJavaScriptElement) element).getResource();
- } else if (element instanceof IResource) {
- resource= (IResource) element;
- } else if (element instanceof IAdaptable) {
- final IAdaptable adaptable= (IAdaptable) element;
- final Object adapted= adaptable.getAdapter(IResource.class);
- if (adapted instanceof IResource)
- resource= (IResource) adapted;
- } else {
- final Object adapted= Platform.getAdapterManager().getAdapter(element, IResource.class);
- if (adapted instanceof IResource)
- resource= (IResource) adapted;
- }
- return resource;
- }
-
- /**
- * Creates a new java model provider.
- */
- public JavaModelProvider() {
- // Used by the runtime
- }
-
- /**
- * {@inheritDoc}
- */
- public ResourceMapping[] getMappings(final IResource resource, final ResourceMappingContext context, final IProgressMonitor monitor) throws CoreException {
- final IJavaScriptElement element= JavaScriptCore.create(resource);
- if (element != null)
- return new ResourceMapping[] { JavaElementResourceMapping.create(element)};
- final Object adapted= resource.getAdapter(ResourceMapping.class);
- if (adapted instanceof ResourceMapping)
- return new ResourceMapping[] { ((ResourceMapping) adapted)};
- return new ResourceMapping[] { new JavaResourceMapping(resource)};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java
deleted file mode 100644
index 18f878ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.model.AbstractRefactoringDescriptorResourceMapping;
-
-/**
- * Refactoring descriptor resource mapping for the Java model provider.
- *
- *
- */
-public final class JavaRefactoringDescriptorResourceMapping extends AbstractRefactoringDescriptorResourceMapping {
-
- /**
- * Creates a new java refactoring descriptor resource mapping.
- *
- * @param descriptor
- * the refactoring descriptor
- */
- public JavaRefactoringDescriptorResourceMapping(final RefactoringDescriptorProxy descriptor) {
- super(descriptor);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java
deleted file mode 100644
index 2afeb2e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.ltk.core.refactoring.model.AbstractRefactoringHistoryResourceMapping;
-
-/**
- * Refactoring history resource mapping for the Java model provider.
- *
- *
- */
-public final class JavaRefactoringHistoryResourceMapping extends AbstractRefactoringHistoryResourceMapping {
-
- /**
- * Creates a new refactoring history resource mapping.
- *
- * @param history
- * the refactoring history
- */
- public JavaRefactoringHistoryResourceMapping(final RefactoringHistory history) {
- super(history);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java
deleted file mode 100644
index 1b4f06b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.resources.mapping.ResourceMappingContext;
-import org.eclipse.core.resources.mapping.ResourceTraversal;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Resource mapping for the java model provider.
- *
- *
- */
-public final class JavaResourceMapping extends ResourceMapping {
-
- /** The resource to map */
- private final IResource fResource;
-
- /**
- * Creates a new java resource mapping.
- *
- * @param resource
- * the resource to map
- */
- public JavaResourceMapping(final IResource resource) {
- Assert.isNotNull(resource);
- fResource= resource;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getModelObject() {
- return fResource;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
-
- /**
- * {@inheritDoc}
- */
- public IProject[] getProjects() {
- return new IProject[] { fResource.getProject() };
- }
-
- /**
- * {@inheritDoc}
- */
- public ResourceTraversal[] getTraversals(final ResourceMappingContext context, final IProgressMonitor monitor) {
- return new ResourceTraversal[] { new ResourceTraversal(new IResource[] { fResource }, IResource.DEPTH_INFINITE, IResource.NONE) };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationCompareAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationCompareAdapter.java
deleted file mode 100644
index 18043245..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationCompareAdapter.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.resources.mapping.IModelProviderDescriptor;
-import org.eclipse.core.resources.mapping.ModelProvider;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.ui.refactoring.model.AbstractSynchronizationCompareAdapter;
-import org.eclipse.team.core.mapping.ISynchronizationContext;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Java-aware synchronization compare adapter.
- *
- *
- */
-public final class JavaSynchronizationCompareAdapter extends AbstractSynchronizationCompareAdapter {
-
- /** The modelProviderId name */
- private static final String MODEL_PROVIDER_ID= "modelProviderId"; //$NON-NLS-1$
-
- /** The modelProviders name */
- private static final String MODEL_PROVIDERS= "modelProviders"; //$NON-NLS-1$
-
- /** The resourcePath name */
- private static final String RESOURCE_PATH= "resourcePath"; //$NON-NLS-1$
-
- /** The resourceType name */
- private static final String RESOURCE_TYPE= "resourceType"; //$NON-NLS-1$
-
- /** The resources name */
- private static final String RESOURCES= "resources"; //$NON-NLS-1$
-
- /** The workingSetName name */
- private static final String WORKING_SET_NAME= "workingSetName"; //$NON-NLS-1$
-
- /** The workingSets name */
- private static final String WORKING_SETS= "workingSets"; //$NON-NLS-1$
-
- /**
- * {@inheritDoc}
- */
- public ICompareInput asCompareInput(final ISynchronizationContext context, final Object element) {
- if (element instanceof RefactoringDescriptorProxy)
- return super.asCompareInput(context, element);
- final IResource resource= JavaModelProvider.getResource(element);
- if (resource != null)
- return super.asCompareInput(context, resource);
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public ResourceMapping[] restore(final IMemento memento) {
- IMemento[] children= memento.getChildren(RESOURCES);
- final List result= new ArrayList();
- for (int index= 0; index < children.length; index++) {
- final Integer typeInt= children[index].getInteger(RESOURCE_TYPE);
- if (typeInt == null)
- continue;
- final String pathString= children[index].getString(RESOURCE_PATH);
- if (pathString == null)
- continue;
- IResource resource= null;
- final IPath path= new Path(pathString);
- final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- switch (typeInt.intValue()) {
- case IResource.ROOT:
- resource= root;
- break;
- case IResource.PROJECT:
- resource= root.getProject(path.lastSegment());
- break;
- case IResource.FILE:
- resource= root.getFile(path);
- break;
- case IResource.FOLDER:
- resource= root.getFolder(path);
- break;
- }
- if (resource != null) {
- final ResourceMapping mapping= JavaSynchronizationContentProvider.getResourceMapping(resource);
- if (mapping != null)
- result.add(mapping);
- }
- }
- children= memento.getChildren(WORKING_SETS);
- for (int index= 0; index < children.length; index++) {
- final String name= children[index].getString(WORKING_SET_NAME);
- if (name == null)
- continue;
- final IWorkingSet set= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(name);
- if (set != null) {
- final ResourceMapping mapping= JavaSynchronizationContentProvider.getResourceMapping(set);
- if (mapping != null)
- result.add(mapping);
- }
- }
- children= memento.getChildren(MODEL_PROVIDERS);
- for (int index= 0; index < children.length; index++) {
- final String id= children[index].getString(MODEL_PROVIDER_ID);
- if (id == null)
- continue;
- final IModelProviderDescriptor descriptor= ModelProvider.getModelProviderDescriptor(id);
- if (descriptor == null)
- continue;
- try {
- final ModelProvider provider= descriptor.getModelProvider();
- if (provider != null) {
- final ResourceMapping mapping= JavaSynchronizationContentProvider.getResourceMapping(provider);
- if (mapping != null)
- result.add(mapping);
- }
- } catch (CoreException event) {
- JavaScriptPlugin.log(event);
- }
- }
- return (ResourceMapping[]) result.toArray(new ResourceMapping[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public void save(final ResourceMapping[] mappings, final IMemento memento) {
- for (int index= 0; index < mappings.length; index++) {
- final Object object= mappings[index].getModelObject();
- if (object instanceof IJavaScriptElement) {
- final IJavaScriptElement element= (IJavaScriptElement) object;
- final IResource resource= (IResource) element.getAdapter(IResource.class);
- if (resource != null) {
- final IMemento child= memento.createChild(RESOURCES);
- child.putInteger(RESOURCE_TYPE, resource.getType());
- child.putString(RESOURCE_PATH, resource.getFullPath().toString());
- }
- }
- if (object instanceof IResource) {
- final IResource resource= (IResource) object;
- final IMemento child= memento.createChild(RESOURCES);
- child.putInteger(RESOURCE_TYPE, resource.getType());
- child.putString(RESOURCE_PATH, resource.getFullPath().toString());
- } else if (object instanceof IWorkingSet)
- memento.createChild(WORKING_SETS).putString(WORKING_SET_NAME, ((IWorkingSet) object).getName());
- else if (object instanceof ModelProvider)
- memento.createChild(MODEL_PROVIDERS).putString(MODEL_PROVIDER_ID, ((ModelProvider) object).getId());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationContentProvider.java
deleted file mode 100644
index f767ddb7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationContentProvider.java
+++ /dev/null
@@ -1,808 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.resources.mapping.ResourceMapping;
-import org.eclipse.core.resources.mapping.ResourceMappingContext;
-import org.eclipse.core.resources.mapping.ResourceTraversal;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.ltk.ui.refactoring.model.AbstractSynchronizationContentProvider;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.team.core.diff.FastDiffFilter;
-import org.eclipse.team.core.diff.IDiff;
-import org.eclipse.team.core.diff.IDiffChangeEvent;
-import org.eclipse.team.core.diff.IDiffTree;
-import org.eclipse.team.core.diff.IDiffVisitor;
-import org.eclipse.team.core.mapping.IResourceDiffTree;
-import org.eclipse.team.core.mapping.ISynchronizationContext;
-import org.eclipse.team.core.mapping.ISynchronizationScope;
-import org.eclipse.team.core.mapping.provider.ResourceDiffTree;
-import org.eclipse.ui.navigator.IPipelinedTreeContentProvider;
-import org.eclipse.ui.navigator.PipelinedShapeModification;
-import org.eclipse.ui.navigator.PipelinedViewerUpdate;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Java-aware synchronization content provider.
- *
- *
- */
-public final class JavaSynchronizationContentProvider extends AbstractSynchronizationContentProvider implements IPipelinedTreeContentProvider {
-
- /** The refactorings folder */
-// private static final String NAME_REFACTORING_FOLDER= ".refactorings"; //$NON-NLS-1$
-
- /**
- * Returns the diffs associated with the element.
- *
- * @param context
- * the synchronization context
- * @param element
- * the element
- * @return an array of diffs
- */
- static IDiff[] getDiffs(final ISynchronizationContext context, final Object element) {
- return context.getDiffTree().getDiffs(getResourceTraversals(element));
- }
-
- /**
- * Returns the resource mapping for the element.
- *
- * @param element
- * the element to get the resource mapping
- * @return the resource mapping
- */
- static ResourceMapping getResourceMapping(final Object element) {
- if (element instanceof IJavaScriptElement)
- return JavaElementResourceMapping.create((IJavaScriptElement) element);
- if (element instanceof IAdaptable) {
- final IAdaptable adaptable= (IAdaptable) element;
- final Object adapted= adaptable.getAdapter(ResourceMapping.class);
- if (adapted instanceof ResourceMapping)
- return (ResourceMapping) adapted;
- }
- return null;
- }
-
- /**
- * Returns the resource traversals for the element.
- *
- * @param element
- * the element to get the resource traversals
- * @return the resource traversals
- */
- static ResourceTraversal[] getResourceTraversals(final Object element) {
- final ResourceMapping mapping= getResourceMapping(element);
- if (mapping != null)
- try {
- return mapping.getTraversals(ResourceMappingContext.LOCAL_CONTEXT, new NullProgressMonitor());
- } catch (final CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- return new ResourceTraversal[0];
- }
-
- /** The content provider, or <code>null</code> */
- private ITreeContentProvider fContentProvider= null;
-
- /** The model root, or <code>null</code> */
- private Object fModelRoot= null;
-
- /**
- * Returns the java element associated with the project.
- *
- * @param project
- * the project
- * @return the associated java element, or <code>null</code> if the
- * project is not a java project
- */
- private IJavaScriptProject asJavaProject(final IProject project) {
- try {
- if (project.getDescription().hasNature(JavaScriptCore.NATURE_ID))
- return JavaScriptCore.create(project);
- } catch (final CoreException exception) {
- // Only log the error for projects that are accessible (i.e. exist and are open)
- if (project.isAccessible())
- JavaScriptPlugin.log(exception);
- }
- return null;
- }
-
- /**
- * Converts the shape modification to use java elements.
- *
- * @param modification
- * the shape modification to convert
- */
- private void convertToJavaElements(final PipelinedShapeModification modification) {
- final Object parent= modification.getParent();
- if (parent instanceof IResource) {
- final IJavaScriptElement project= asJavaProject(((IResource) parent).getProject());
- if (project != null) {
- modification.getChildren().clear();
- return;
- }
- }
- if (parent instanceof ISynchronizationContext) {
- final Set result= new HashSet();
- for (final Iterator iterator= modification.getChildren().iterator(); iterator.hasNext();) {
- final Object element= iterator.next();
- if (element instanceof IProject) {
- final IJavaScriptElement project= asJavaProject((IProject) element);
- if (project != null) {
- iterator.remove();
- result.add(project);
- }
- }
- }
- modification.getChildren().addAll(result);
- }
- }
-
- /**
- * Converts the viewer update to use java elements.
- *
- * @param update
- * the viewer update to convert
- * @return <code>true</code> if any elements have been converted,
- * <code>false</code> otherwise
- */
- private boolean convertToJavaElements(final PipelinedViewerUpdate update) {
- final Set result= new HashSet();
- for (final Iterator iterator= update.getRefreshTargets().iterator(); iterator.hasNext();) {
- final Object element= iterator.next();
- if (element instanceof IProject) {
- final IJavaScriptElement project= asJavaProject((IProject) element);
- if (project != null) {
- iterator.remove();
- result.add(project);
- }
- }
- }
- update.getRefreshTargets().addAll(result);
- return !result.isEmpty();
- }
-
- /**
- * {@inheritDoc}
- */
- public void diffsChanged(final IDiffChangeEvent event, final IProgressMonitor monitor) {
- syncExec(new Runnable() {
-
- public void run() {
- handleChange(event);
- }
- }, getViewer().getControl());
- }
-
- /**
- * Returns all the existing projects that contain additions,
- * removals or deletions.
- *
- * @param event
- * the event
- * @return the projects that contain changes
- */
- private IJavaScriptProject[] getChangedProjects(final IDiffChangeEvent event) {
- final Set result= new HashSet();
- final IDiff[] changes= event.getChanges();
- for (int index= 0; index < changes.length; index++) {
- final IResource resource= ResourceDiffTree.getResourceFor(changes[index]);
- if (resource != null) {
- final IJavaScriptProject project= asJavaProject(resource.getProject());
- if (project != null)
- result.add(project);
- }
- }
- final IDiff[] additions= event.getAdditions();
- for (int index= 0; index < additions.length; index++) {
- final IResource resource= ResourceDiffTree.getResourceFor(additions[index]);
- if (resource != null) {
- final IJavaScriptProject project= asJavaProject(resource.getProject());
- if (project != null)
- result.add(project);
- }
- }
- final IPath[] removals = event.getRemovals();
- for (int i = 0; i < removals.length; i++) {
- IPath path = removals[i];
- if (path.segmentCount() > 0) {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
- // Only consider projects that still exist
- if (project.exists()) {
- final IJavaScriptProject javaProject= asJavaProject(project.getProject());
- if (javaProject != null)
- result.add(javaProject);
- }
- }
- }
- return (IJavaScriptProject[]) result.toArray(new IJavaScriptProject[result.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object[] getChildrenInContext(final ISynchronizationContext context, final Object parent, final Object[] children) {
- final Object[] elements= super.getChildrenInContext(context, parent, children);
- if (parent instanceof IPackageFragment)
- return getPackageFragmentChildren(context, parent, elements);
- else if (parent instanceof IPackageFragmentRoot)
- return getPackageFragmentRootChildren(context, parent, elements);
- else if (parent instanceof IJavaScriptProject)
- return getJavaProjectChildren(context, parent, elements);
- else if (parent instanceof RefactoringHistory)
- return ((RefactoringHistory) parent).getDescriptors();
- // It may be the case that the elements are folders that have a corresponding
- // source folder in which case they should be filtered out
- return getFilteredElements(parent, elements);
- }
-
- /**
- * Returns the filtered elements.
- *
- * @param parent
- * the parent element
- * @param children
- * the child elements
- * @return the filtered elements
- */
- private Object[] getFilteredElements(final Object parent, final Object[] children) {
- final List result= new ArrayList(children.length);
- for (int index= 0; index < children.length; index++) {
- if (children[index] instanceof IFolder) {
- if (!(JavaScriptCore.create((IFolder) children[index]) instanceof IPackageFragmentRoot))
- result.add(children[index]);
- } else
- result.add(children[index]);
- }
- return result.toArray();
- }
-
- /**
- * {@inheritDoc}
- */
- protected ITreeContentProvider getDelegateContentProvider() {
- if (fContentProvider == null)
- fContentProvider= new JavaModelContentProvider();
- return fContentProvider;
- }
-
- /**
- * Returns the projects that used to have changes in the diff tree
- * but have been deleted from the workspace.
- *
- * @param event
- * the event
- * @return the deleted projects
- */
- private Set getDeletedProjects(final IDiffChangeEvent event) {
- final Set result= new HashSet();
- final IPath[] deletions= event.getRemovals();
- for (int index= 0; index < deletions.length; index++) {
- final IPath path= deletions[index];
- if (path.segmentCount() > 0) {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
- if (!project.isAccessible())
- result.add(project);
- }
- }
- return result;
- }
-
- /**
- * Since the this content provider overrides the resource content provider,
- * this method is only invoked when the resource content provider is
- * disabled. In this case, we still want the Java projects to appear at the
- * root of the view.
- *
- * {@inheritDoc}
- */
- public Object[] getElements(Object parent) {
- if (parent instanceof ISynchronizationContext)
- // Put the resource projects directly under the context
- parent= getModelRoot();
- return super.getElements(parent);
- }
-
- /**
- * Returns the java project children in the current scope.
- *
- * @param context
- * the synchronization context
- * @param parent
- * the parent element
- * @param children
- * the child elements
- * @return the java project children
- */
- private Object[] getJavaProjectChildren(final ISynchronizationContext context, final Object parent, final Object[] children) {
- final LinkedList list= new LinkedList();
- for (int index= 0; index < children.length; index++) {
- if (children[index] instanceof IPackageFragment) {
- final IPackageFragment fragment= (IPackageFragment) children[index];
- if (getChildren(fragment).length == 0)
- continue;
- }
- // We need to check whether a folder has non-fragment children (bug 138767)
- if (children[index] instanceof IFolder) {
- IFolder folder = (IFolder) children[index];
- if (getChildren(folder).length == 0)
- continue;
- }
- list.add(children[index]);
- }
-
- final IResource resource= JavaModelProvider.getResource(parent);
- if (resource != null) {
- final IResourceDiffTree tree= context.getDiffTree();
- final IResource[] members= tree.members(resource);
- for (int index= 0; index < members.length; index++) {
- IResource child = members[index];
- if (isVisible(context, child)) {
- if (hasPhantomFolder(tree, child)) {
- // Add any phantom resources that are visible
- list.add(child);
- }
-
-
-// if (members[index] instanceof IFolder) {
-// final IFolder folder= (IFolder) members[index];
-// if (folder.getName().equals(NAME_REFACTORING_FOLDER)) {
-// final RefactoringHistory history= getRefactorings(context, (IProject) resource, null);
-// if (!history.isEmpty()) {
-// list.remove(folder);
-// list.addFirst(history);
-// }
-// }
-// }
- }
- }
-
- }
- return list.toArray(new Object[list.size()]);
- }
-
- private boolean hasPhantomFolder(IResourceDiffTree tree, IResource child) {
- if (!child.exists())
- return true;
- final boolean[] found = new boolean[] { false };
- tree.accept(child.getFullPath(), new IDiffVisitor() {
- public boolean visit(IDiff delta){
- IResource treeResource = ResourceDiffTree.getResourceFor(delta);
- if (treeResource.getType()==IResource.FILE && !treeResource.getParent().exists()){
- found[0] = true;
- return false;
- }
-
- return true;
- }}, IResource.DEPTH_INFINITE);
- return found[0];
- }
-
-
- /**
- * {@inheritDoc}
- */
- protected String getModelProviderId() {
- return JavaModelProvider.JAVA_MODEL_PROVIDER_ID;
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object getModelRoot() {
- if (fModelRoot == null)
- fModelRoot= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- return fModelRoot;
- }
-
- /**
- * Returns the package fragment children in the current scope.
- *
- * @param context
- * the synchronization context
- * @param parent
- * the parent element
- * @param children
- * the child elements
- * @return the package fragment children
- */
- private Object[] getPackageFragmentChildren(final ISynchronizationContext context, final Object parent, final Object[] children) {
- final Set set= new HashSet();
- for (int index= 0; index < children.length; index++)
- set.add(children[index]);
- final IResource resource= ((IPackageFragment) parent).getResource();
- if (resource != null) {
- final IResourceDiffTree tree= context.getDiffTree();
- final IResource[] members= tree.members(resource);
- for (int index= 0; index < members.length; index++) {
- final int type= members[index].getType();
- if (type == IResource.FILE) {
- final IDiff diff= tree.getDiff(members[index]);
- if (diff != null && isVisible(diff))
- if (isInScope(context.getScope(), parent, members[index])) {
- final IJavaScriptElement element= JavaScriptCore.create(members[index]);
- if (element == null) {
- set.add(members[index]);
- } else {
- set.add(element);
- }
- }
- }
- }
- }
- return set.toArray(new Object[set.size()]);
- }
-
- /**
- * Returns the package fragment root children in the current scope.
- *
- * @param context
- * the synchronization context
- * @param parent
- * the parent element
- * @param children
- * the child elements
- * @return the package fragment root children
- */
- private Object[] getPackageFragmentRootChildren(final ISynchronizationContext context, final Object parent, final Object[] children) {
- final Set set= new HashSet();
- for (int index= 0; index < children.length; index++) {
- if (children[index] instanceof IPackageFragment) {
- IPackageFragment fragment = (IPackageFragment) children[index];
- if (fragment.isOpen() && getChildren(fragment).length == 0)
- // Don't add the default package unless it has children
- continue;
- }
- set.add(children[index]);
- }
- final IResource resource= JavaModelProvider.getResource(parent);
- if (resource != null) {
- final IResourceDiffTree tree= context.getDiffTree();
- final IResource[] members= tree.members(resource);
- for (int index= 0; index < members.length; index++) {
- final int type= members[index].getType();
- final boolean contained= isInScope(context.getScope(), parent, members[index]);
- final boolean visible= isVisible(context, members[index]);
- if (type == IResource.FILE && contained && visible) {
- // If the file is not a compilation unit add it.
- // (compilation units are always children of packages so they
- // don't need to be added here)
- final IJavaScriptElement element= JavaScriptCore.create((IFile) members[index]);
- if (element == null)
- set.add(members[index]);
- } else if (type == IResource.FOLDER && contained && visible && tree.getDiff(members[index]) != null) {
- // If the folder is out-of-sync, add it
- final IJavaScriptElement element= JavaScriptCore.create(members[index]);
- if (element != null)
- set.add(element);
- }
- if (type == IResource.FOLDER) {
- // If the folder contains java elements, add it
- final IFolder folder= (IFolder) members[index];
- tree.accept(folder.getFullPath(), new IDiffVisitor() {
-
- public final boolean visit(final IDiff diff) {
- if (isVisible(diff)) {
- final IResource current= tree.getResource(diff);
- if (current != null) {
- final int kind= current.getType();
- if (kind == IResource.FILE) {
- final IJavaScriptElement element= JavaScriptCore.create(current.getParent());
- if (element != null)
- set.add(element);
- } else {
- final IJavaScriptElement element= JavaScriptCore.create(current);
- if (element != null)
- set.add(element);
- }
- }
- }
- return true;
- }
- }, IResource.DEPTH_INFINITE);
- }
- }
- return set.toArray(new Object[set.size()]);
- }
- return children;
- }
-
- /**
- * {@inheritDoc}
- */
- public void getPipelinedChildren(final Object parent, final Set children) {
- if (parent instanceof ISynchronizationContext) {
- // When a context is the root, the resource content provider returns
- // projects as direct children. We should replace any projects that
- // are Java projects with an IJavaScriptProject
- final Set result= new HashSet(children.size());
- for (final Iterator iterator= children.iterator(); iterator.hasNext();) {
- final Object element= iterator.next();
- if (element instanceof IProject) {
- final IJavaScriptElement java= asJavaProject((IProject) element);
- if (java != null) {
- iterator.remove();
- result.add(java);
- }
- }
- if (element instanceof IFolder) {
- IFolder folder = (IFolder) element;
- IJavaScriptElement javaElement = JavaScriptCore.create(folder);
- // If the folder is also a package, don't show it
- // as a folder since it will be shown as a package
- if (javaElement instanceof IPackageFragmentRoot) {
- iterator.remove();
- }
- }
- }
- children.addAll(result);
- } else if (parent instanceof ISynchronizationScope) {
- // When the root is a scope, we should return the
- // Java model provider so all model providers appear
- // at the root of the viewer.
- children.add(getModelProvider());
- } else if (parent instanceof IFolder) {
- // Remove any children that are also source folders so they
- // don't appear twice
- for (final Iterator iterator= children.iterator(); iterator.hasNext();) {
- final Object element= iterator.next();
- if (element instanceof IFolder) {
- IFolder folder = (IFolder) element;
- IJavaScriptElement javaElement = JavaScriptCore.create(folder);
- if (javaElement instanceof IPackageFragmentRoot) {
- iterator.remove();
- }
- }
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void getPipelinedElements(final Object element, final Set elements) {
- getPipelinedChildren(element, elements);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getPipelinedParent(final Object element, final Object parent) {
- if (element instanceof IJavaScriptElement)
- return getParent(element);
- return parent;
- }
-
- /**
- * {@inheritDoc}
- */
- protected ResourceTraversal[] getTraversals(final ISynchronizationContext context, final Object object) {
- return getResourceTraversals(object);
- }
-
- /**
- * Returns the visible projects.
- *
- * @return the visible projects
- */
- private Set getVisibleProjects() {
- final TreeItem[] children= ((TreeViewer) getViewer()).getTree().getItems();
- final Set result= new HashSet();
- for (int index= 0; index < children.length; index++) {
- final Object data= children[index].getData();
- if (data instanceof IJavaScriptProject)
- result.add(data);
- }
- return result;
- }
-
- /**
- * Handles a diff change event.
- *
- * @param event
- * the event
- */
- private void handleChange(final IDiffChangeEvent event) {
- final Set existing= getVisibleProjects();
- // Get all existing and open projects that contain changes
- // and determine what needs to be done to the project
- // (i.e. add, remove or refresh)
- final IJavaScriptProject[] changed= getChangedProjects(event);
- final List refreshes= new ArrayList(changed.length);
- final List additions= new ArrayList(changed.length);
- final List removals= new ArrayList(changed.length);
- for (int index= 0; index < changed.length; index++) {
- final IJavaScriptProject project= changed[index];
- if (hasVisibleChanges(event.getTree(), project)) {
- if (existing.contains(project))
- refreshes.add(project);
- else
- additions.add(project);
- } else
- removals.add(project);
- }
- // Remove any java projects that correspond to deleted or closed projects
- final Set removed= getDeletedProjects(event);
- for (final Iterator iterator= existing.iterator(); iterator.hasNext();) {
- final IJavaScriptProject element= (IJavaScriptProject) iterator.next();
- if (removed.contains(element.getResource()))
- removals.add(element);
- }
-
- if (!removals.isEmpty() || !additions.isEmpty() || !refreshes.isEmpty()) {
- final TreeViewer viewer= (TreeViewer) getViewer();
- final Tree tree= viewer.getTree();
- try {
- tree.setRedraw(false);
- if (!additions.isEmpty())
- viewer.add(viewer.getInput(), additions.toArray());
- if (!removals.isEmpty())
- viewer.remove(viewer.getInput(), removals.toArray());
- if (!refreshes.isEmpty()) {
- for (final Iterator iter= refreshes.iterator(); iter.hasNext();)
- viewer.refresh(iter.next());
- }
- } finally {
- tree.setRedraw(true);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasChildren(final Object element) {
- if (element instanceof IJavaScriptUnit || element instanceof IFile || element instanceof RefactoringDescriptorProxy || element instanceof RefactoringDescriptor)
- return false;
- return super.hasChildren(element);
- }
-
- /**
- * Returns whether the element has some children in the current scope.
- *
- * @param scope
- * the synchronization scope
- * @param element
- * the element
- * @param resource
- * the resource
- * @return <code>true</code> if it has some children, <code>false</code>
- * otherwise
- */
- private boolean hasChildrenInScope(final ISynchronizationScope scope, final Object element, final IResource resource) {
- final IResource[] roots= scope.getRoots();
- final IPath path= resource.getFullPath();
- if (element instanceof IPackageFragment) {
- for (int index= 0; index < roots.length; index++)
- if (path.equals(roots[index].getFullPath().removeLastSegments(1)))
- return true;
- return false;
- }
- for (int index= 0; index < roots.length; index++)
- if (path.isPrefixOf(roots[index].getFullPath()))
- return true;
- return false;
- }
-
- /**
- * Has the java project visible changes?
- *
- * @param tree
- * the diff tree
- * @param project
- * the java project
- * @return <code>true</code> if it has visible changes, <code>false</code>
- * otherwise
- */
- private boolean hasVisibleChanges(final IDiffTree tree, final IJavaScriptProject project) {
- return tree.hasMatchingDiffs(project.getResource().getFullPath(), new FastDiffFilter() {
-
- public boolean select(final IDiff diff) {
- return isVisible(diff);
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- public PipelinedShapeModification interceptAdd(final PipelinedShapeModification modification) {
- convertToJavaElements(modification);
- return modification;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean interceptRefresh(final PipelinedViewerUpdate update) {
- return convertToJavaElements(update);
- }
-
- /**
- * {@inheritDoc}
- */
- public PipelinedShapeModification interceptRemove(final PipelinedShapeModification modification) {
- convertToJavaElements(modification);
- return modification;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean interceptUpdate(final PipelinedViewerUpdate anUpdateSynchronization) {
- return convertToJavaElements(anUpdateSynchronization);
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean isInScope(final ISynchronizationScope scope, final Object parent, final Object element) {
- final IResource resource= JavaModelProvider.getResource(element);
- if (resource == null)
- return false;
- if (scope.contains(resource))
- return true;
- if (hasChildrenInScope(scope, element, resource))
- return true;
- return false;
- }
-
- /**
- * Executes the given runnable.
- *
- * @param runnable
- * the runnable
- * @param control
- * the control
- */
- private void syncExec(final Runnable runnable, final Control control) {
- if (control != null && !control.isDisposed())
- control.getDisplay().syncExec(new Runnable() {
-
- public void run() {
- if (!control.isDisposed())
- BusyIndicator.showWhile(control.getDisplay(), runnable);
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationLabelProvider.java
deleted file mode 100644
index d9c84bd0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaSynchronizationLabelProvider.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.viewers.DecoratingLabelProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreePathLabelProvider;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.ViewerLabel;
-import org.eclipse.ltk.ui.refactoring.model.AbstractSynchronizationLabelProvider;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.team.core.diff.IDiff;
-import org.eclipse.team.core.diff.IDiffTree;
-import org.eclipse.team.core.mapping.ISynchronizationContext;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-
-/**
- * Java-aware synchronization label provider.
- *
- *
- */
-public final class JavaSynchronizationLabelProvider extends AbstractSynchronizationLabelProvider implements ITreePathLabelProvider{
-
- /** The delegate label provider, or <code>null</code> */
- private ILabelProvider fLabelProvider= null;
-
- /** The model root, or <code>null</code> */
- private Object fModelRoot= null;
-
- /** The package image, or <code>null</code> */
- private Image fPackageImage= null;
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- if (fPackageImage != null && !fPackageImage.isDisposed())
- fPackageImage.dispose();
- if (fLabelProvider != null)
- fLabelProvider.dispose();
- super.dispose();
- }
-
- /**
- * {@inheritDoc}
- */
- public Image getDelegateImage(final Object element) {
- if (element instanceof IPackageFragment) {
- final IPackageFragment fragment= (IPackageFragment) element;
- final IResource resource= fragment.getResource();
- if (resource == null || !resource.exists()) {
- if (fPackageImage == null)
- fPackageImage= JavaPluginImages.DESC_OBJS_PACKAGE.createImage();
- return fPackageImage;
- }
- }
- return super.getDelegateImage(element);
- }
-
- /**
- * {@inheritDoc}
- */
- protected ILabelProvider getDelegateLabelProvider() {
- if (fLabelProvider == null)
- fLabelProvider= new DecoratingLabelProvider(new JavaModelLabelProvider(ModelMessages.JavaModelLabelProvider_project_preferences_label, ModelMessages.JavaModelLabelProvider_refactorings_label), new ProblemsLabelDecorator(null));
- return fLabelProvider;
- }
-
- /**
- * {@inheritDoc}
- */
- protected IDiff getDiff(final Object element) {
- final ISynchronizationContext context= getContext();
- final IResource resource= JavaModelProvider.getResource(element);
- if (context != null && resource != null) {
- final IDiff[] diff= JavaSynchronizationContentProvider.getDiffs(context, element);
- for (int index= 0; index < diff.length; index++) {
- if (context.getDiffTree().getResource(diff[index]).equals(resource))
- return diff[index];
- }
- }
- return super.getDiff(element);
- }
-
- /**
- * {@inheritDoc}
- */
- protected int getMarkerSeverity(final Object element) {
- // Decoration label provider is handling this
- return -1;
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object getModelRoot() {
- if (fModelRoot == null)
- fModelRoot= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- return fModelRoot;
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean hasDecendantConflicts(final Object element) {
- final ISynchronizationContext context= getContext();
- final IResource resource= JavaModelProvider.getResource(element);
- if (context != null && resource != null)
- return context.getDiffTree().getProperty(resource.getFullPath(), IDiffTree.P_HAS_DESCENDANT_CONFLICTS);
- return super.hasDecendantConflicts(element);
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean isBusy(final Object element) {
- final ISynchronizationContext context= getContext();
- final IResource resource= JavaModelProvider.getResource(element);
- if (context != null && resource != null)
- return context.getDiffTree().getProperty(resource.getFullPath(), IDiffTree.P_BUSY_HINT);
- return super.isBusy(element);
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean isIncludeOverlays() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreePathLabelProvider#updateLabel(org.eclipse.jface.viewers.ViewerLabel, org.eclipse.jface.viewers.TreePath)
- */
- public void updateLabel(ViewerLabel label, TreePath elementPath) {
- Object firstSegment = elementPath.getFirstSegment();
- if (firstSegment instanceof IProject && elementPath.getSegmentCount() == 2) {
- IProject project = (IProject) firstSegment;
- Object lastSegment = elementPath.getLastSegment();
- if (lastSegment instanceof IFolder) {
- IFolder folder = (IFolder) lastSegment;
- if (!folder.getParent().equals(project)) {
- // This means that a folder that is not a direct child of the project
- // is a child in the tree. Therefore, the resource content provider
- // must be active and in compress folder mode so we will leave
- // it to the resource provider to provide the proper label.
- // We need to do this because of bug 153912
- return;
- }
- }
- }
- label.setImage(getImage(elementPath.getLastSegment()));
- label.setText(getText(elementPath.getLastSegment()));
- Font f = getFont(elementPath.getLastSegment());
- if (f != null)
- label.setFont(f);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.java
deleted file mode 100644
index 5577a35d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.model;
-
-import org.eclipse.osgi.util.NLS;
-
-public class ModelMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.model.ModelMessages"; //$NON-NLS-1$
-
- public static String JavaModelLabelProvider_project_preferences_label;
-
- public static String JavaModelLabelProvider_refactorings_label;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, ModelMessages.class);
- }
-
- private ModelMessages() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties
deleted file mode 100644
index 620d4136..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-JavaModelLabelProvider_project_preferences_label=Settings
-JavaModelLabelProvider_refactorings_label=Refactorings
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java
deleted file mode 100644
index cd874359..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.navigator.IExtensionStateModel;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.MultiActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.navigator.IExtensionStateConstants.Values;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages;
-
-/**
- * Adds view menus to switch between flat and hierarchical layout.
- *
- *
- */
-public class CommonLayoutActionGroup extends MultiActionGroup {
-
- public static final String LAYOUT_GROUP_NAME = "layout"; //$NON-NLS-1$
-
- private IExtensionStateModel fStateModel;
- private StructuredViewer fStructuredViewer;
-
- private boolean fHasContributedToViewMenu = false;
- private IAction fHierarchicalLayout = null;
- private IAction fFlatLayoutAction = null;
- private IAction[] fActions;
-
- private IMenuManager fLayoutSubMenu;
-
- private class CommonLayoutAction extends Action implements IAction {
-
- private final boolean fIsFlatLayout;
-
- public CommonLayoutAction(boolean flat) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- fIsFlatLayout = flat;
- if (fIsFlatLayout) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_FLAT_ACTION);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_HIERARCHICAL_ACTION);
- }
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- if (fStateModel.getBooleanProperty(Values.IS_LAYOUT_FLAT) != fIsFlatLayout) {
- fStateModel.setBooleanProperty(Values.IS_LAYOUT_FLAT, fIsFlatLayout);
-
- fStructuredViewer.getControl().setRedraw(false);
- try {
- fStructuredViewer.refresh();
- } finally {
- fStructuredViewer.getControl().setRedraw(true);
- }
- }
- }
- }
-
- public CommonLayoutActionGroup(StructuredViewer structuredViewer,
- IExtensionStateModel stateModel) {
- super();
- fStateModel = stateModel;
- fStructuredViewer = structuredViewer;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see ActionGroup#fillActionBars(IActionBars)
- */
- public void fillActionBars(IActionBars actionBars) {
- if (!fHasContributedToViewMenu) {
-
- IMenuManager viewMenu = actionBars.getMenuManager();
- // Create layout sub menu
- if (fLayoutSubMenu == null) {
- fLayoutSubMenu = new MenuManager(PackagesMessages.LayoutActionGroup_label);
- addActions(fLayoutSubMenu);
-
- viewMenu.insertAfter(IWorkbenchActionConstants.MB_ADDITIONS, new Separator(LAYOUT_GROUP_NAME));
- }
-
- viewMenu.appendToGroup(LAYOUT_GROUP_NAME, fLayoutSubMenu);
-
- fHasContributedToViewMenu = true;
- }
- }
-
- public void unfillActionBars(IActionBars actionBars) {
- if (fHasContributedToViewMenu) {
- // Create layout sub menu
- if (fLayoutSubMenu != null) {
- actionBars.getMenuManager().remove(fLayoutSubMenu);
- fLayoutSubMenu.dispose();
- fLayoutSubMenu= null;
- }
-
- fHasContributedToViewMenu = false;
- }
- }
-
- private IAction[] createActions() {
-
- fFlatLayoutAction = new CommonLayoutAction(true);
- fFlatLayoutAction.setText(PackagesMessages.LayoutActionGroup_flatLayoutAction_label);
- JavaPluginImages.setLocalImageDescriptors(fFlatLayoutAction, "flatLayout.gif"); //$NON-NLS-1$
-
- fHierarchicalLayout = new CommonLayoutAction(false);
- fHierarchicalLayout.setText(PackagesMessages.LayoutActionGroup_hierarchicalLayoutAction_label);
- JavaPluginImages.setLocalImageDescriptors(fHierarchicalLayout, "hierarchicalLayout.gif"); //$NON-NLS-1$
-
- return new IAction[] { fFlatLayoutAction, fHierarchicalLayout };
- }
-
- public void setFlatLayout(boolean flatLayout) {
- if (fActions == null) {
- fActions = createActions();
-
- // indicates check the flat action
- setActions(fActions, flatLayout ? 0 : 1);
- }
- fHierarchicalLayout.setChecked(!flatLayout);
- fFlatLayoutAction.setChecked(flatLayout);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/ContainerFolder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/ContainerFolder.java
deleted file mode 100644
index 07b659ce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/ContainerFolder.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-
-/**
- * @author childsb
- *
- */
-public class ContainerFolder {
-
-
-
-
- Object parent;
- String name;
- public ContainerFolder(String fullPath, Object parent){
-
- this.parent = parent;
- name = fullPath;
- }
-
- public Object getParentObject() {
- return parent;
- }
-
- public String getName() {
- return name;
-
- }
- public String toString() { return name;}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/IExtensionStateConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/IExtensionStateConstants.java
deleted file mode 100644
index 4b5908cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/IExtensionStateConstants.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-
-public interface IExtensionStateConstants {
-
- String ROOT_MODE= "rootMode"; //$NON-NLS-1$
-
- interface Values {
-
- String IS_LAYOUT_FLAT= "isLayoutFlat"; //$NON-NLS-1$
-
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaDropAdapterAssistant.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaDropAdapterAssistant.java
deleted file mode 100644
index 6f5773bf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaDropAdapterAssistant.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
-import org.eclipse.ui.navigator.CommonDropAdapter;
-import org.eclipse.ui.navigator.CommonDropAdapterAssistant;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgCopyStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgMoveStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-public class JavaDropAdapterAssistant extends CommonDropAdapterAssistant {
-
- private List fElements;
- private JavaMoveProcessor fMoveProcessor;
- private int fCanMoveElements;
- private JavaCopyProcessor fCopyProcessor;
- private int fCanCopyElements;
-
- public IStatus handleDrop(CommonDropAdapter dropAdapter, DropTargetEvent dropTargetEvent, Object target) {
- if (LocalSelectionTransfer.getInstance().isSupportedType(dropAdapter.getCurrentTransfer())) {
- try {
-
- switch (dropAdapter.getCurrentOperation()) {
- case DND.DROP_MOVE :
- handleDropMove(target);
- break;
- case DND.DROP_COPY :
- handleDropCopy(target);
- break;
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, PackagesMessages.SelectionTransferDropAdapter_error_title, PackagesMessages.SelectionTransferDropAdapter_error_message);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- } catch (InterruptedException e) {
- //ok
- } finally {
- // The drag source listener must not perform any operation
- // since this drop adapter did the remove of the source even
- // if we moved something.
- //event.detail= DND.DROP_NONE;
- }
- clear();
- return Status.OK_STATUS;
- } else if (FileTransfer.getInstance().isSupportedType(dropAdapter.getCurrentTransfer())) {
- try {
-
- final Object data = FileTransfer.getInstance().nativeToJava(dropAdapter.getCurrentTransfer());
- if (!(data instanceof String[]))
- return Status.CANCEL_STATUS;
-
- final IContainer targetContainer = getActualTarget(target);
- if (targetContainer == null)
- return Status.CANCEL_STATUS;
-
-
- getShell().forceActive();
- new CopyFilesAndFoldersOperation(getShell()).copyFiles((String[]) data, targetContainer);
- } catch (JavaScriptModelException e) {
- String title = PackagesMessages.DropAdapter_errorTitle;
- String message = PackagesMessages.DropAdapter_errorMessage;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
- return Status.OK_STATUS;
- }
- return Status.CANCEL_STATUS;
- }
-
- public IStatus validateDrop(Object target, int operation, TransferData transferType) {
- IStatus result = Status.OK_STATUS;
- if (LocalSelectionTransfer.getInstance().isSupportedType(transferType)) {
- initializeSelection();
- try {
- switch (operation) {
- case DND.DROP_DEFAULT :
- if (handleValidateDefault(target) != DND.DROP_NONE) {
- result = Status.OK_STATUS;
- } else {
- result = Status.CANCEL_STATUS;
- }
- break;
- case DND.DROP_COPY :
- if (handleValidateCopy(target) != DND.DROP_NONE) {
- result = Status.OK_STATUS;
- } else {
- result = Status.CANCEL_STATUS;
- }
- break;
- case DND.DROP_MOVE :
- if (handleValidateMove(target) != DND.DROP_NONE) {
- result = Status.OK_STATUS;
- } else {
- result = Status.CANCEL_STATUS;
- }
- break;
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, PackagesMessages.SelectionTransferDropAdapter_error_title, PackagesMessages.SelectionTransferDropAdapter_error_message);
- //event.detail= DND.DROP_NONE;
- result = Status.CANCEL_STATUS;
- }
- }
- return result;
- }
-
- public boolean isSupportedType(TransferData transferType) {
- return super.isSupportedType(transferType) || FileTransfer.getInstance().isSupportedType(transferType);
- }
-
- private IContainer getActualTarget(Object dropTarget) throws JavaScriptModelException {
- if (dropTarget instanceof IContainer)
- return (IContainer) dropTarget;
- else if (dropTarget instanceof IJavaScriptElement)
- return getActualTarget(((IJavaScriptElement) dropTarget).getCorrespondingResource());
- return null;
- }
-
- protected void initializeSelection() {
- if (fElements != null)
- return;
- ISelection s = LocalSelectionTransfer.getInstance().getSelection();
- if (!(s instanceof IStructuredSelection))
- return;
- fElements = ((IStructuredSelection) s).toList();
- }
-
- private void handleDropMove(final Object target) throws JavaScriptModelException, InvocationTargetException, InterruptedException {
- IJavaScriptElement[] javaElements = ReorgUtils.getJavaElements(fElements);
- IResource[] resources = ReorgUtils.getResources(fElements);
- ReorgMoveStarter starter = null;
- if (target instanceof IResource)
- starter = ReorgMoveStarter.create(javaElements, resources, (IResource) target);
- else if (target instanceof IJavaScriptElement)
- starter = ReorgMoveStarter.create(javaElements, resources, (IJavaScriptElement) target);
- if (starter != null)
- starter.run(getShell());
- }
-
- private void handleDropCopy(final Object target) throws JavaScriptModelException, InvocationTargetException, InterruptedException {
- IJavaScriptElement[] javaElements = ReorgUtils.getJavaElements(fElements);
- IResource[] resources = ReorgUtils.getResources(fElements);
- ReorgCopyStarter starter = null;
- if (target instanceof IResource)
- starter = ReorgCopyStarter.create(javaElements, resources, (IResource) target);
- else if (target instanceof IJavaScriptElement)
- starter = ReorgCopyStarter.create(javaElements, resources, (IJavaScriptElement) target);
- if (starter != null)
- starter.run(getShell());
- }
-
- private int handleValidateCopy(Object target) throws JavaScriptModelException {
-
- final ICopyPolicy policy= ReorgPolicyFactory.createCopyPolicy(ReorgUtils.getResources(fElements), ReorgUtils.getJavaElements(fElements));
- fCopyProcessor= policy.canEnable() ? new JavaCopyProcessor(policy) : null;
-
- if (!canCopyElements())
- return DND.DROP_NONE;
-
- if (target instanceof IResource && fCopyProcessor != null && fCopyProcessor.setDestination((IResource)target).isOK())
- return DND.DROP_COPY;
- else if (target instanceof IJavaScriptElement && fCopyProcessor != null && fCopyProcessor.setDestination((IJavaScriptElement)target).isOK())
- return DND.DROP_COPY;
- else
- return DND.DROP_NONE;
- }
-
- private int handleValidateDefault(Object target) throws JavaScriptModelException {
- if (target == null)
- return DND.DROP_NONE;
-
- return handleValidateMove(target);
- }
-
- private int handleValidateMove(Object target) throws JavaScriptModelException {
- if (target == null)
- return DND.DROP_NONE;
-
- IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(ReorgUtils.getResources(fElements), ReorgUtils.getJavaElements(fElements));
- fMoveProcessor= (policy.canEnable()) ? new JavaMoveProcessor(policy) : null;
-
- if (!canMoveElements())
- return DND.DROP_NONE;
-
- if (target instanceof IResource && fMoveProcessor != null && fMoveProcessor.setDestination((IResource)target).isOK())
- return DND.DROP_MOVE;
- else if (target instanceof IJavaScriptElement && fMoveProcessor != null && fMoveProcessor.setDestination((IJavaScriptElement)target).isOK())
- return DND.DROP_MOVE;
- else
- return DND.DROP_NONE;
- }
-
-
- private boolean canMoveElements() {
- if (fCanMoveElements == 0) {
- fCanMoveElements = 2;
- if (fMoveProcessor == null)
- fCanMoveElements = 1;
- }
- return fCanMoveElements == 2;
- }
-
-
- private boolean canCopyElements() {
- if (fCanCopyElements == 0) {
- fCanCopyElements = 2;
- if (fCopyProcessor == null)
- fCanCopyElements = 1;
- }
- return fCanCopyElements == 2;
- }
-
- private void clear() {
- fElements = null;
- fMoveProcessor = null;
- fCanMoveElements = 0;
- fCopyProcessor = null;
- fCanCopyElements = 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaFileLinkHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaFileLinkHelper.java
deleted file mode 100644
index abc26b6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaFileLinkHelper.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.ide.ResourceUtil;
-import org.eclipse.ui.navigator.ILinkHelper;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavaFileLinkHelper implements ILinkHelper {
-
- public void activateEditor(IWorkbenchPage page, IStructuredSelection selection) {
- if (selection == null || selection.isEmpty())
- return;
- Object element= selection.getFirstElement();
- IEditorPart part= EditorUtility.isOpenInEditor(element);
- if (part != null) {
- page.bringToTop(part);
- if (element instanceof IJavaScriptElement)
- EditorUtility.revealInEditor(part, (IJavaScriptElement) element);
- }
-
- }
-
- public IStructuredSelection findSelection(IEditorInput input) {
- IJavaScriptElement element= JavaScriptUI.getEditorInputJavaElement(input);
- if (element == null) {
- IFile file = ResourceUtil.getFile(input);
- if (file != null) {
- element= JavaScriptCore.create(file);
- }
- }
- return (element != null) ? new StructuredSelection(element) : StructuredSelection.EMPTY;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorActionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorActionProvider.java
deleted file mode 100644
index 42025f00..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorActionProvider.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-
-/**
- * Contributes the following actions to the menu on behalf of the JDT content
- * extension.
- *
- * <ul>
- * <li>{@link OpenViewActionGroup}. Contributes the Open View actions (type
- * hierarchy, call hierarchy, etc).</li>
- * <li>{@link CCPActionGroup}. Contributes the Cut/Copy/Paste/Delete.</li>
- * <li>{@link JavaSearchActionGroup}. Contributes the search functionality (find in workspace, project, etc).</li>
- * <li>{@link GenerateActionGroup}. Contributes the "Source>" and "Generate>" submenu .</li>
- * </ul>
- */
-public class JavaNavigatorActionProvider extends CommonActionProvider {
-
- private OpenViewActionGroup fOpenViewGroup;
-
- private CCPActionGroup fCCPGroup;
-
- private JavaSearchActionGroup fSearchGroup;
-
- //private GenerateBuildPathActionGroup fBuildPathGroup;
-
- private GenerateActionGroup fGenerateGroup;
-
- private boolean fInViewPart= false;
-
- public void fillActionBars(IActionBars actionBars) {
- if (fInViewPart) {
- fOpenViewGroup.fillActionBars(actionBars);
- fCCPGroup.fillActionBars(actionBars);
- // fBuildPathGroup.fillActionBars(actionBars);
- fGenerateGroup.fillActionBars(actionBars);
- fSearchGroup.fillActionBars(actionBars);
- }
- }
-
- public void fillContextMenu(IMenuManager menu) {
- if (fInViewPart) {
- ISelection selection = (this.getContext()!=null) ? this.getContext().getSelection() : null;
- boolean isEmpty = (selection!=null)? selection.isEmpty() : false;
- fOpenViewGroup.containsShowInMenu(!isEmpty);
- fOpenViewGroup.fillContextMenu(menu);
- fCCPGroup.setShowLimited(isEmpty);
- fCCPGroup.fillContextMenu(menu);
- // fBuildPathGroup.fillContextMenu(menu);
- fGenerateGroup.fillContextMenu(menu);
- fSearchGroup.fillContextMenu(menu);
- }
- }
-
- public void init(ICommonActionExtensionSite site) {
-
- ICommonViewerWorkbenchSite workbenchSite= null;
- if (site.getViewSite() instanceof ICommonViewerWorkbenchSite)
- workbenchSite= (ICommonViewerWorkbenchSite) site.getViewSite();
-
- if (workbenchSite != null) {
- if (workbenchSite.getPart() != null && workbenchSite.getPart() instanceof IViewPart) {
- IViewPart viewPart= (IViewPart) workbenchSite.getPart();
-
- fOpenViewGroup= new OpenViewActionGroup(viewPart, site.getStructuredViewer());
- fOpenViewGroup.containsOpenPropertiesAction(false);
- fCCPGroup= new CCPActionGroup(viewPart);
- fGenerateGroup= new GenerateActionGroup(viewPart);
- fSearchGroup= new JavaSearchActionGroup(viewPart);
- //fBuildPathGroup= new GenerateBuildPathActionGroup(viewPart);
-
- fInViewPart= true;
- }
- }
- }
-
- public void setContext(ActionContext context) {
- super.setContext(context);
- if (fInViewPart) {
- fOpenViewGroup.setContext(context);
- fCCPGroup.setContext(context);
- fGenerateGroup.setContext(context);
- fSearchGroup.setContext(context);
- //fBuildPathGroup.setContext(context);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java
deleted file mode 100644
index baf064ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.navigator.ICommonContentExtensionSite;
-import org.eclipse.ui.navigator.IExtensionStateModel;
-import org.eclipse.ui.navigator.IPipelinedTreeContentProvider;
-import org.eclipse.ui.navigator.PipelinedShapeModification;
-import org.eclipse.ui.navigator.PipelinedViewerUpdate;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.navigator.IExtensionStateConstants.Values;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerContentProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class JavaNavigatorContentProvider extends
- PackageExplorerContentProvider implements IPipelinedTreeContentProvider {
-
- public JavaNavigatorContentProvider() {
- super(false);
- }
-
- public JavaNavigatorContentProvider(boolean provideMembers) {
- super(provideMembers);
- }
-
- public static final String JSDT_EXTENSION_ID = "org.eclipse.wst.jsdt.ui.javaContent"; //$NON-NLS-1$
- /**
- * @deprecated
- */
- public static final String JDT_EXTENSION_ID = JSDT_EXTENSION_ID;
-
- private IExtensionStateModel fStateModel;
-
- private Object fRealInput;
-
- private IPropertyChangeListener fLayoutPropertyListener;
-
- public void init(ICommonContentExtensionSite commonContentExtensionSite) {
- IExtensionStateModel stateModel = commonContentExtensionSite
- .getExtensionStateModel();
- IMemento memento = commonContentExtensionSite.getMemento();
-
- fStateModel = stateModel;
- restoreState(memento);
- fLayoutPropertyListener = new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (Values.IS_LAYOUT_FLAT.equals(event.getProperty())) {
- if (event.getNewValue() != null) {
- boolean newValue = ((Boolean) event.getNewValue())
- .booleanValue() ? true : false;
- setIsFlatLayout(newValue);
- }
- }
-
- }
- };
- fStateModel.addPropertyChangeListener(fLayoutPropertyListener);
-
- IPreferenceStore store = PreferenceConstants.getPreferenceStore();
- boolean showCUChildren = store
- .getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
- setProvideMembers(showCUChildren);
- }
-
- public void dispose() {
- super.dispose();
- fStateModel.removePropertyChangeListener(fLayoutPropertyListener);
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- fRealInput = newInput;
- super.inputChanged(viewer, oldInput, findInputElement(newInput));
- }
-
- public Object getParent(Object element) {
- Object parent= super.getParent(element);
- if (parent instanceof IJavaScriptModel) {
- return parent.equals(getViewerInput()) ? fRealInput : parent;
- }
- if (parent instanceof IJavaScriptProject) {
- return ((IJavaScriptProject)parent).getProject();
- }
- return parent;
- }
-
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof IWorkspaceRoot) {
- IWorkspaceRoot root = (IWorkspaceRoot) inputElement;
- return root.getProjects();
- } else if (inputElement instanceof IJavaScriptModel) {
- return ((IJavaScriptModel)inputElement).getWorkspace().getRoot().getProjects();
- }
- if (inputElement instanceof IProject) {
- return super.getElements(JavaScriptCore.create((IProject)inputElement));
- }
- return super.getElements(inputElement);
- }
-
- public boolean hasChildren(Object element) {
- if (element instanceof IProject) {
- return ((IProject) element).isAccessible();
- }
- if (getProvideMembers() && element instanceof IFile && JavaScriptCore.isJavaScriptLikeFileName(((IFile) element).getName())) {
- /*
- * TODO: gives false positives for .js files not on an Include
- * Path
- */
- return JavaScriptCore.create((IFile) element) != null;
- }
- return super.hasChildren(element);
- }
-
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof IWorkspaceRoot) {
- IWorkspaceRoot root = (IWorkspaceRoot) parentElement;
- return root.getProjects();
- }
- if (parentElement instanceof IProject) {
- return super.getChildren(JavaScriptCore.create((IProject) parentElement));
- }
- if (getProvideMembers() && parentElement instanceof IFile && JavaScriptCore.isJavaScriptLikeFileName(((IFile) parentElement).getName())) {
- return super.getChildren(JavaScriptCore.create((IFile) parentElement));
- }
- return super.getChildren(parentElement);
- }
-
- private Object findInputElement(Object newInput) {
- if (newInput instanceof IWorkspaceRoot) {
- return JavaScriptCore.create((IWorkspaceRoot) newInput);
- }
- return newInput;
- }
-
- public void restoreState(IMemento memento) {
-
- }
-
- public void saveState(IMemento memento) {
-
- }
-
- private void customizeChildren(Object parent, Set currentChildren) {
- if(!getProvideMembers())
- return;
-
- // Append CU's children to Files
- if(parent instanceof IFile && JavaScriptCore.isJavaScriptLikeFileName(((IFile)parent).getName())) {
- Object[] children = getChildren(parent);
- for (int i = 0; i < children.length; i++) {
- currentChildren.add(children[i]);
- }
- }
-
- // append JS Model children as children of IProjects
- if (parent instanceof IProject) {
- Object[] projectChildren = super.getChildren(JavaScriptCore.create((IProject) parent));
- for (int i = 0; i < projectChildren.length; i++) {
- currentChildren.add(projectChildren[i]);
- }
- }
- }
-
- public void getPipelinedChildren(Object parent, Set currentChildren) {
- customizeChildren(parent, currentChildren);
- }
- public void getPipelinedElements(Object input, Set currentElements) {
- customizeChildren(input, currentElements);
- }
-
- public Object getPipelinedParent(Object object, Object suggestedParent) {
- if (object instanceof IJavaScriptElement && ((IJavaScriptElement) object).getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- try {
- IResource underlyingResource = ((IJavaScriptUnit) object).getUnderlyingResource();
- if (underlyingResource != null && underlyingResource.getType() < IResource.PROJECT) {
- return underlyingResource.getParent();
- }
- }
- catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return suggestedParent;
- }
-
- public PipelinedShapeModification interceptAdd(PipelinedShapeModification addModification) {
-//
-// Object parent= addModification.getParent();
-//
-// if (parent instanceof IJavaScriptProject) {
-// addModification.setParent(((IJavaScriptProject)parent).getProject());
-// }
-//
-// if (parent instanceof IWorkspaceRoot) {
-// deconvertJavaProjects(addModification);
-// }
-//
-// convertToJavaElements(addModification);
- return addModification;
- }
-
- public PipelinedShapeModification interceptRemove(
- PipelinedShapeModification removeModification) {
-// deconvertJavaProjects(removeModification);
-// convertToJavaElements(removeModification.getChildren());
- return removeModification;
- }
-
- private void deconvertJavaProjects(PipelinedShapeModification modification) {
- Set convertedChildren = new LinkedHashSet();
- for (Iterator iterator = modification.getChildren().iterator(); iterator.hasNext();) {
- Object added = iterator.next();
- if(added instanceof IJavaScriptProject) {
- iterator.remove();
- convertedChildren.add(((IJavaScriptProject)added).getProject());
- }
- }
- modification.getChildren().addAll(convertedChildren);
- }
-
- /**
- * Converts the shape modification to use Java elements.
- *
- *
- * @param modification
- * the shape modification to convert
- * @return returns true if the conversion took place
- */
- private boolean convertToJavaElements(PipelinedShapeModification modification) {
- Object parent = modification.getParent();
- // As of 3.3, we no longer re-parent additions to IProject.
- if (parent instanceof IContainer) {
- IJavaScriptElement element = JavaScriptCore.create((IContainer) parent);
- if (element != null && element.exists()) {
- // we don't convert the root
- if( !(element instanceof IJavaScriptModel) && !(element instanceof IJavaScriptProject))
- modification.setParent(element);
- return convertToJavaElements(modification.getChildren());
-
- }
- }
- return false;
- }
-
- /**
- * Converts the shape modification to use Java elements.
- *
- *
- * @param currentChildren
- * The set of current children that would be contributed or refreshed in the viewer.
- * @return returns true if the conversion took place
- */
- private boolean convertToJavaElements(Set currentChildren) {
-
- LinkedHashSet convertedChildren = new LinkedHashSet();
- IJavaScriptElement newChild;
- for (Iterator childrenItr = currentChildren.iterator(); childrenItr
- .hasNext();) {
- Object child = childrenItr.next();
- // only convert IFolders and IFiles
- if (child instanceof IFolder || child instanceof IFile) {
- if ((newChild = JavaScriptCore.create((IResource) child)) != null
- && newChild.exists()) {
- childrenItr.remove();
- convertedChildren.add(newChild);
- }
- } else if (child instanceof IJavaScriptProject) {
- childrenItr.remove();
- convertedChildren.add( ((IJavaScriptProject)child).getProject());
- }
- }
- if (!convertedChildren.isEmpty()) {
- currentChildren.addAll(convertedChildren);
- return true;
- }
- return false;
-
- }
-
- public boolean interceptRefresh(PipelinedViewerUpdate refreshSynchronization) {
- return false;
-// return convertToJavaElements(refreshSynchronization.getRefreshTargets());
-
- }
-
- public boolean interceptUpdate(PipelinedViewerUpdate updateSynchronization) {
- return false;
-// return convertToJavaElements(updateSynchronization.getRefreshTargets());
- }
-
-// protected void postAdd(final Object parent, final Object element, Collection runnables) {
-// if (parent instanceof IJavaScriptModel)
-// super.postAdd(((IJavaScriptModel) parent).getWorkspace(), element, runnables);
-// else if (parent instanceof IJavaScriptProject)
-// super.postAdd( ((IJavaScriptProject)parent).getProject(), element, runnables);
-// else
-// super.postAdd(parent, element, runnables);
-// }
-
-
- protected void postRefresh(final List toRefresh, final boolean updateLabels, Collection runnables) {
- for (Iterator iter = toRefresh.iterator(); iter.hasNext();) {
- Object element = iter.next();
- if (element instanceof IJavaScriptModel) {
- iter.remove();
- toRefresh.add(element.equals(getViewerInput()) ? fRealInput : element);
- super.postRefresh(toRefresh, updateLabels, runnables);
- return;
- }
- }
- super.postRefresh(toRefresh, updateLabels, runnables);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java
deleted file mode 100644
index ff3c1adf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.navigator.ICommonContentExtensionSite;
-import org.eclipse.ui.navigator.ICommonLabelProvider;
-import org.eclipse.ui.navigator.IExtensionStateModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.navigator.IExtensionStateConstants.Values;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerContentProvider;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Provides the labels for the Project Explorer.
- * <p>
- * It provides labels for the packages in hierarchical layout and in all other
- * cases delegates it to its super class.
- * </p>
- *
- *
- */
-public class JavaNavigatorLabelProvider implements ICommonLabelProvider {
-
- private final long LABEL_FLAGS = JavaScriptElementLabels.DEFAULT_QUALIFIED
- | JavaScriptElementLabels.ROOT_POST_QUALIFIED
- | JavaScriptElementLabels.APPEND_ROOT_PATH
- | JavaScriptElementLabels.M_PARAMETER_TYPES
- | JavaScriptElementLabels.M_PARAMETER_NAMES
- | JavaScriptElementLabels.M_APP_RETURNTYPE
- | JavaScriptElementLabels.M_EXCEPTIONS
- | JavaScriptElementLabels.F_APP_TYPE_SIGNATURE
- | JavaScriptElementLabels.T_TYPE_PARAMETERS;
-
- private PackageExplorerLabelProvider delegeteLabelProvider;
-
- private PackageExplorerContentProvider fContentProvider;
-
- private IExtensionStateModel fStateModel;
-
- private IPropertyChangeListener fLayoutPropertyListener;
-
- public JavaNavigatorLabelProvider() {
-
- }
- public void init(ICommonContentExtensionSite commonContentExtensionSite) {
- fStateModel = commonContentExtensionSite.getExtensionStateModel();
- fContentProvider = (PackageExplorerContentProvider) commonContentExtensionSite.getExtension().getContentProvider();
- delegeteLabelProvider = createLabelProvider();
-
- delegeteLabelProvider.setIsFlatLayout(fStateModel
- .getBooleanProperty(Values.IS_LAYOUT_FLAT));
- fLayoutPropertyListener = new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (Values.IS_LAYOUT_FLAT.equals(event.getProperty())) {
- if (event.getNewValue() != null) {
- boolean newValue = ((Boolean) event.getNewValue())
- .booleanValue() ? true : false;
- delegeteLabelProvider.setIsFlatLayout(newValue);
- }
- }
-
- }
- };
- fStateModel.addPropertyChangeListener(fLayoutPropertyListener);
- }
-
- public String getDescription(Object element) {
- return formatMessage(element);
- }
-
- private PackageExplorerLabelProvider createLabelProvider() {
- return new PackageExplorerLabelProvider(fContentProvider);
- }
-
- public void dispose() {
- delegeteLabelProvider.dispose();
- fStateModel.removePropertyChangeListener(fLayoutPropertyListener);
- }
-
- public void propertyChange(PropertyChangeEvent event) {
- delegeteLabelProvider.propertyChange(event);
- }
-
- public void addLabelDecorator(ILabelDecorator decorator) {
- delegeteLabelProvider.addLabelDecorator(decorator);
- }
-
- public void addListener(ILabelProviderListener listener) {
- delegeteLabelProvider.addListener(listener);
- }
-
- public Color getBackground(Object element) {
- return delegeteLabelProvider.getBackground(element);
- }
-
- public Color getForeground(Object element) {
- return delegeteLabelProvider.getForeground(element);
- }
-
- public Image getImage(Object element) {
- return delegeteLabelProvider.getImage(element);
- }
-
- public boolean isLabelProperty(Object element, String property) {
- return delegeteLabelProvider.isLabelProperty(element, property);
- }
-
- public void removeListener(ILabelProviderListener listener) {
- delegeteLabelProvider.removeListener(listener);
- }
-
- public boolean equals(Object obj) {
- return delegeteLabelProvider.equals(obj);
- }
-
- public int hashCode() {
- return delegeteLabelProvider.hashCode();
- }
-
- public String toString() {
- return delegeteLabelProvider.toString();
- }
-
- public String getText(Object element) {
- if (!delegeteLabelProvider.isFlatLayout() && element instanceof IJavaScriptElement) {
- switch (((IJavaScriptElement) element).getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.LOCAL_VARIABLE :
- case IJavaScriptElement.INITIALIZER : {
- String text = delegeteLabelProvider.getText(element);
- int groupEnd = text.lastIndexOf('.');
- if (groupEnd > 0 && groupEnd < text.length() - 1) {
- text = text.substring(groupEnd + 1);
- }
- return text;
- }
- }
- }
-
- return delegeteLabelProvider.getText(element);
- }
-
- public void setIsFlatLayout(boolean state) {
- delegeteLabelProvider.setIsFlatLayout(state);
- }
-
- // Taken from StatusBarUpdater
-
- private String formatMessage(Object element) {
- if (element instanceof IJavaScriptElement) {
- return formatJavaElementMessage((IJavaScriptElement) element);
- } else if (element instanceof IResource) {
- return formatResourceMessage((IResource) element);
- }
- return ""; //$NON-NLS-1$
- }
-
- private String formatJavaElementMessage(IJavaScriptElement element) {
- return JavaScriptElementLabels.getElementLabel(element, LABEL_FLAGS);
- }
-
- private String formatResourceMessage(IResource element) {
- IContainer parent = element.getParent();
- if (parent != null && parent.getType() != IResource.ROOT)
- return element.getName() + JavaScriptElementLabels.CONCAT_STRING
- + parent.getFullPath().makeRelative().toString();
- else
- return element.getName();
- }
-
- public void restoreState(IMemento memento) {
-
- }
-
- public void saveState(IMemento memento) {
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorRefactorActionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorRefactorActionProvider.java
deleted file mode 100644
index 32a86b6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorRefactorActionProvider.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-/**
- * Contributes the following actions to the menu on behalf of the JDT content
- * extension.
- *
- * <ul>
- * <li>{@link RefactorActionGroup}. Contributes the "Refactor>" and "Source>" submenus to the context menu.</li>
- * </ul>
- */
-public class JavaNavigatorRefactorActionProvider extends CommonActionProvider {
-
- private RefactorActionGroup fRefactorGroup;
-
- public void fillActionBars(IActionBars actionBars) {
- if (fRefactorGroup != null) {
- fRefactorGroup.fillActionBars(actionBars);
- fRefactorGroup.retargetFileMenuActions(actionBars);
- }
- }
-
- public void fillContextMenu(IMenuManager menu) {
- if (fRefactorGroup != null) {
- fRefactorGroup.fillContextMenu(menu);
- }
- }
-
- public void init(ICommonActionExtensionSite site) {
- ICommonViewerWorkbenchSite workbenchSite= null;
- if (site.getViewSite() instanceof ICommonViewerWorkbenchSite)
- workbenchSite= (ICommonViewerWorkbenchSite) site.getViewSite();
-
- // we only initialize the refactor group when in a view part
- // (required for the constructor)
- if (workbenchSite != null) {
- if (workbenchSite.getPart() != null && workbenchSite.getPart() instanceof IViewPart) {
- IViewPart viewPart= (IViewPart) workbenchSite.getPart();
-
- fRefactorGroup= new RefactorActionGroup(viewPart);
- }
- }
- }
-
- public void setContext(ActionContext context) {
- if (fRefactorGroup != null) {
- fRefactorGroup.setContext(context);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorViewActionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorViewActionProvider.java
deleted file mode 100644
index b1df68d2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorViewActionProvider.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import java.util.Arrays;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-import org.eclipse.ui.navigator.IExtensionActivationListener;
-import org.eclipse.ui.navigator.IExtensionStateModel;
-import org.eclipse.ui.navigator.INavigatorActivationService;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.navigator.IExtensionStateConstants.Values;
-
-/**
- * Contributes the following actions to the menu on behalf of the JDT content
- * extension.
- *
- * <ul>
- * <li>{@link CommonLayoutActionGroup}. Contributes the "Package Presentation>" submenu in the View's drop down menu (not right-click).</li>
- * </ul>
- */
-public class JavaNavigatorViewActionProvider extends CommonActionProvider {
-
- private static final int HIERARCHICAL_LAYOUT= 0x1;
-
- private static final int FLAT_LAYOUT= 0x2;
-
- private static final String TAG_LAYOUT= "org.eclipse.wst.jsdt.internal.ui.navigator.layout"; //$NON-NLS-1$
-
- private IExtensionStateModel fStateModel;
-
- private CommonLayoutActionGroup fLayoutActionGroup;
-
- private ICommonActionExtensionSite fExtensionSite;
-
- private String fExtensionId;
-
- private IActionBars fActionBars;
-
- private boolean fEnabled= false;
-
- private IExtensionActivationListener fMenuUpdater= new IExtensionActivationListener() {
-
- public void onExtensionActivation(String viewerId, String[] theNavigatorExtensionIds, boolean isCurrentlyActive) {
-
- if (fExtensionSite != null && fActionBars != null) {
-
- int search= Arrays.binarySearch(theNavigatorExtensionIds, fExtensionId);
- if (search > -1) {
- if (isMyViewer(viewerId)) {
- if (wasEnabled(isCurrentlyActive))
- fLayoutActionGroup.fillActionBars(fActionBars);
-
- else
- if (wasDisabled(isCurrentlyActive))
- fLayoutActionGroup.unfillActionBars(fActionBars);
- // else no change
- }
- fEnabled= isCurrentlyActive;
- }
- }
-
- }
-
- private boolean isMyViewer(String viewerId) {
- String myViewerId= fExtensionSite.getViewSite().getId();
- return myViewerId != null && myViewerId.equals(viewerId);
- }
-
- private boolean wasDisabled(boolean isActive) {
- return fEnabled && !isActive;
- }
-
- private boolean wasEnabled(boolean isActive) {
- return !fEnabled && isActive;
- }
- };
-
-
- public void fillActionBars(IActionBars actionBars) {
- fActionBars= actionBars;
- fLayoutActionGroup.fillActionBars(actionBars);
- }
-
- public void init(ICommonActionExtensionSite site) {
-
- fExtensionSite= site;
-
- fStateModel= fExtensionSite.getExtensionStateModel();
- fLayoutActionGroup= new CommonLayoutActionGroup(fExtensionSite.getStructuredViewer(), fStateModel);
-
- INavigatorActivationService activationService= fExtensionSite.getContentService().getActivationService();
- activationService.addExtensionActivationListener(fMenuUpdater);
-
- fExtensionId= fExtensionSite.getExtensionId();
-
- fEnabled= true;
-
- }
-
- public void dispose() {
- super.dispose();
- fExtensionSite.getContentService().getActivationService().removeExtensionActivationListener(fMenuUpdater);
- }
-
- public void setContext(ActionContext context) {
- super.setContext(context);
- }
-
- public void restoreState(IMemento memento) {
- boolean isCurrentLayoutFlat= false;
- Integer state= null;
- if (memento != null)
- state= memento.getInteger(TAG_LAYOUT);
-
- // If no memento try an restore from preference store
- if (state == null) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- state= new Integer(store.getInt(TAG_LAYOUT));
- }
-
- if (state.intValue() == FLAT_LAYOUT)
- isCurrentLayoutFlat= true;
- else
- if (state.intValue() == HIERARCHICAL_LAYOUT)
- isCurrentLayoutFlat= false;
-
- fStateModel.setBooleanProperty(Values.IS_LAYOUT_FLAT, isCurrentLayoutFlat);
- fLayoutActionGroup.setFlatLayout(isCurrentLayoutFlat);
- }
-
- public void saveState(IMemento aMemento) {
- super.saveState(aMemento);
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- if (fStateModel.getBooleanProperty(Values.IS_LAYOUT_FLAT))
- store.setValue(TAG_LAYOUT, FLAT_LAYOUT);
- else
- store.setValue(TAG_LAYOUT, HIERARCHICAL_LAYOUT);
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialElementsFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialElementsFilter.java
deleted file mode 100644
index 21aa6067..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialElementsFilter.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipse.ui.navigator.IExtensionStateModel;
-import org.eclipse.ui.navigator.INavigatorContentService;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- *
- * This filter is only applicable to instances of the Common Navigator.
- *
- * This filter will not allow essential elements to be blocked.
- */
-public abstract class NonEssentialElementsFilter extends ViewerFilter {
-
- private static final String JAVA_EXTENSION_ID = "org.eclipse.wst.jsdt.java.ui.javaContent"; //$NON-NLS-1$
-
- private boolean isStateModelInitialized = false;
- private IExtensionStateModel fStateModel = null;
-
- private INavigatorContentService fContentService;
-
- private ViewerFilter fDelegateFilter;
-
- protected NonEssentialElementsFilter(ViewerFilter delegateFilter) {
- fDelegateFilter = delegateFilter;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (!isStateModelInitialized) {
- initStateModel(viewer);
- }
- if (fContentService == null || fStateModel == null) {
- return true;
- } else if (element instanceof IPackageFragment) {
- if (isApplicable() && viewer instanceof StructuredViewer) {
- boolean isHierarchicalLayout= !fStateModel.getBooleanProperty(IExtensionStateConstants.Values.IS_LAYOUT_FLAT);
- try {
- IPackageFragment fragment = (IPackageFragment) element;
- if (isHierarchicalLayout && !fragment.isDefaultPackage() && fragment.hasSubpackages()) {
- return hasFilteredChildren((StructuredViewer) viewer, fragment);
- }
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
- }
- return doSelect(viewer, parent, element);
- }
-
- private boolean hasFilteredChildren(StructuredViewer viewer, IPackageFragment fragment) {
- Object[] children= getRawChildren(viewer, fragment);
- ViewerFilter[] filters= viewer.getFilters();
- for (int i= 0; i < filters.length; i++) {
- children= filters[i].filter(viewer, fragment, children);
- if (children.length == 0)
- return false;
- }
- return true;
- }
-
- private Object[] getRawChildren(StructuredViewer viewer, IPackageFragment fragment) {
- IStructuredContentProvider provider = (IStructuredContentProvider) viewer.getContentProvider();
- if (provider instanceof ITreeContentProvider) {
- return ((ITreeContentProvider)provider).getChildren(fragment);
- }
- return provider.getElements(fragment);
- }
-
- protected boolean doSelect(Viewer viewer, Object parent, Object element) {
- return fDelegateFilter.select(viewer, parent, element);
- }
-
- private boolean isApplicable() {
- return fContentService != null && fContentService.isVisible(JAVA_EXTENSION_ID) && fContentService.isActive(JAVA_EXTENSION_ID);
- }
-
- private synchronized void initStateModel(Viewer viewer) {
- if (!isStateModelInitialized) {
- if (viewer instanceof CommonViewer) {
-
- CommonViewer commonViewer = (CommonViewer) viewer;
- fContentService = commonViewer.getNavigatorContentService();
- fStateModel = fContentService.findStateModel(JAVA_EXTENSION_ID);
-
- isStateModelInitialized = true;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyInnerPackageFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyInnerPackageFilter.java
deleted file mode 100644
index 8df5b0dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyInnerPackageFilter.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/***************************************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others. 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: IBM Corporation - initial API and implementation
- **************************************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.wst.jsdt.internal.ui.filters.EmptyInnerPackageFilter;
-
-
-public class NonEssentialEmptyInnerPackageFilter extends NonEssentialElementsFilter {
-
-
- public NonEssentialEmptyInnerPackageFilter() {
- super(new EmptyInnerPackageFilter());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyPackageFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyPackageFilter.java
deleted file mode 100644
index 2ff84c6f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/NonEssentialEmptyPackageFilter.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/***************************************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others. 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: IBM Corporation - initial API and implementation
- **************************************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.wst.jsdt.internal.ui.filters.EmptyPackageFilter;
-
-
-
-
-/**
- * Filters out all empty package fragments unless the mode of the viewer is set to hierarchical
- * layout.
- *
- * This filter is only applicable to instances of the Common Navigator.
- */
-public class NonEssentialEmptyPackageFilter extends NonEssentialElementsFilter {
-
- public NonEssentialEmptyPackageFilter() {
- super(new EmptyPackageFilter());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/OpenAndExpand.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/OpenAndExpand.java
deleted file mode 100644
index f5b2e7fd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/OpenAndExpand.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.events.HelpListener;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class OpenAndExpand extends SelectionDispatchAction implements IAction {
-
- private OpenAction fOpenAction;
- private TreeViewer fViewer;
-
- public OpenAndExpand(IWorkbenchSite site, OpenAction openAction, TreeViewer viewer) {
- super(site);
- fOpenAction = openAction;
- fViewer = viewer;
- }
-
- public void run() {
- fOpenAction.run();
- if(getSelection() != null && getSelection() instanceof IStructuredSelection)
- expand(((IStructuredSelection)getSelection()).getFirstElement());
-
- }
-
- public void run(ISelection selection) {
- fOpenAction.run(selection);
- if(selection != null && selection instanceof IStructuredSelection)
- expand(((IStructuredSelection)selection).getFirstElement());
- }
-
- public void run(IStructuredSelection selection) {
- fOpenAction.run(selection);
- if(selection != null)
- expand(selection.getFirstElement());
- }
-
- public void run(ITextSelection selection) {
- fOpenAction.run(selection);
- }
-
- public void run(JavaTextSelection selection) {
- fOpenAction.run(selection);
- }
-
- public void run(Object[] elements) {
- fOpenAction.run(elements);
- }
-
- public void runWithEvent(Event event) {
- fOpenAction.runWithEvent(event);
- }
-
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- fOpenAction.addPropertyChangeListener(listener);
- }
-
- public boolean equals(Object obj) {
- return fOpenAction.equals(obj);
- }
-
- public int getAccelerator() {
- return fOpenAction.getAccelerator();
- }
-
- public String getActionDefinitionId() {
- return fOpenAction.getActionDefinitionId();
- }
-
- public String getDescription() {
- return fOpenAction.getDescription();
- }
-
- public ImageDescriptor getDisabledImageDescriptor() {
- return fOpenAction.getDisabledImageDescriptor();
- }
-
- public Object getElementToOpen(Object object) throws JavaScriptModelException {
- return fOpenAction.getElementToOpen(object);
- }
-
- public HelpListener getHelpListener() {
- return fOpenAction.getHelpListener();
- }
-
- public ImageDescriptor getHoverImageDescriptor() {
- return fOpenAction.getHoverImageDescriptor();
- }
-
- public String getId() {
- return fOpenAction.getId();
- }
-
- public ImageDescriptor getImageDescriptor() {
- return fOpenAction.getImageDescriptor();
- }
-
- public IMenuCreator getMenuCreator() {
- return fOpenAction.getMenuCreator();
- }
-
- public ISelection getSelection() {
- return fOpenAction.getSelection();
- }
-
- public ISelectionProvider getSelectionProvider() {
- return fOpenAction.getSelectionProvider();
- }
-
- public Shell getShell() {
- return fOpenAction.getShell();
- }
-
- public IWorkbenchSite getSite() {
- return fOpenAction.getSite();
- }
-
- public int getStyle() {
- return fOpenAction.getStyle();
- }
-
- public String getText() {
- return fOpenAction.getText();
- }
-
- public String getToolTipText() {
- return fOpenAction.getToolTipText();
- }
-
- public int hashCode() {
- return fOpenAction.hashCode();
- }
-
- public boolean isChecked() {
- return fOpenAction.isChecked();
- }
-
- public boolean isEnabled() {
- return fOpenAction.isEnabled();
- }
-
- public boolean isHandled() {
- return fOpenAction.isHandled();
- }
-
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fOpenAction.removePropertyChangeListener(listener);
- }
-
- public void selectionChanged(ISelection selection) {
- fOpenAction.selectionChanged(selection);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- fOpenAction.selectionChanged(selection);
- }
-
- public void selectionChanged(ITextSelection selection) {
- fOpenAction.selectionChanged(selection);
- }
-
- public void selectionChanged(JavaTextSelection selection) {
- fOpenAction.selectionChanged(selection);
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- fOpenAction.selectionChanged(event);
- }
-
- public void setAccelerator(int keycode) {
- fOpenAction.setAccelerator(keycode);
- }
-
- public void setActionDefinitionId(String id) {
- fOpenAction.setActionDefinitionId(id);
- }
-
- public void setChecked(boolean checked) {
- fOpenAction.setChecked(checked);
- }
-
- public void setDescription(String text) {
- fOpenAction.setDescription(text);
- }
-
- public void setDisabledImageDescriptor(ImageDescriptor newImage) {
- fOpenAction.setDisabledImageDescriptor(newImage);
- }
-
- public void setEnabled(boolean enabled) {
- fOpenAction.setEnabled(enabled);
- }
-
- public void setHelpListener(HelpListener listener) {
- fOpenAction.setHelpListener(listener);
- }
-
- public void setHoverImageDescriptor(ImageDescriptor newImage) {
- fOpenAction.setHoverImageDescriptor(newImage);
- }
-
- public void setId(String id) {
- fOpenAction.setId(id);
- }
-
- public void setImageDescriptor(ImageDescriptor newImage) {
- fOpenAction.setImageDescriptor(newImage);
- }
-
- public void setMenuCreator(IMenuCreator creator) {
- fOpenAction.setMenuCreator(creator);
- }
-
- public void setSpecialSelectionProvider(ISelectionProvider provider) {
- fOpenAction.setSpecialSelectionProvider(provider);
- }
-
- public void setText(String text) {
- fOpenAction.setText(text);
- }
-
- public void setToolTipText(String toolTipText) {
- fOpenAction.setToolTipText(toolTipText);
- }
-
- public String toString() {
- return fOpenAction.toString();
- }
-
- public void update(ISelection selection) {
- fOpenAction.update(selection);
- }
-
- private void expand(Object target) {
- if (! fOpenAction.isEnabled())
- fViewer.setExpandedState(target, !fViewer.getExpandedState(target));
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java
deleted file mode 100644
index c9b3d2b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.navigator;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionConstants;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-
-
-public class PackageExplorerOpenActionProvider extends CommonActionProvider {
-
-
- private IAction fOpenAndExpand;
- private OpenEditorActionGroup fOpenGroup;
-
- private boolean fInViewPart = false;
-
- public void fillActionBars(IActionBars actionBars) {
- if (fInViewPart) {
- fOpenGroup.fillActionBars(actionBars);
-
- if (fOpenAndExpand == null && fOpenGroup.getOpenAction().isEnabled()) // TODO: is not updated!
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, fOpenGroup.getOpenAction());
- else if (fOpenAndExpand != null && fOpenAndExpand.isEnabled())
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, fOpenAndExpand);
- }
-
- }
-
- public void fillContextMenu(IMenuManager menu) {
-
- if (fInViewPart) {
- if (fOpenGroup.getOpenAction().isEnabled()) {
- fOpenGroup.fillContextMenu(menu);
- }
- }
- }
-
- public void init(ICommonActionExtensionSite site) {
-
- ICommonViewerWorkbenchSite workbenchSite = null;
- if (site.getViewSite() instanceof ICommonViewerWorkbenchSite)
- workbenchSite = (ICommonViewerWorkbenchSite) site.getViewSite();
-
- if (workbenchSite != null) {
- if (workbenchSite.getPart() != null && workbenchSite.getPart() instanceof IViewPart) {
- IViewPart viewPart = (IViewPart) workbenchSite.getPart();
-
- fOpenGroup = new OpenEditorActionGroup(viewPart);
-
- if (site.getStructuredViewer() instanceof TreeViewer)
- fOpenAndExpand = new OpenAndExpand(workbenchSite.getSite(), (OpenAction) fOpenGroup.getOpenAction(), (TreeViewer) site.getStructuredViewer());
- fInViewPart = true;
- }
- }
- }
-
- public void setContext(ActionContext context) {
- super.setContext(context);
- if (fInViewPart) {
- fOpenGroup.setContext(context);
- }
- }
-
- /*
- * @see org.eclipse.ui.actions.ActionGroup#dispose()
- * @since 3.5
- */
- public void dispose() {
- if (fOpenGroup != null)
- fOpenGroup.dispose();
- super.dispose();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CollapseAllAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CollapseAllAction.java
deleted file mode 100644
index 45db3c7c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CollapseAllAction.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Collapse all nodes.
- */
-class CollapseAllAction extends Action {
-
- private PackageExplorerPart fPackageExplorer;
-
- CollapseAllAction(PackageExplorerPart part) {
- super(PackagesMessages.CollapseAllAction_label);
- setDescription(PackagesMessages.CollapseAllAction_description);
- setToolTipText(PackagesMessages.CollapseAllAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "collapseall.gif"); //$NON-NLS-1$
-
- fPackageExplorer= part;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.COLLAPSE_ALL_ACTION);
- }
-
- public void run() {
- fPackageExplorer.collapseAll();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CustomHashtable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CustomHashtable.java
deleted file mode 100644
index 87eda51a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/CustomHashtable.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Peter Shipton - original hashtable implementation
- * Nick Edgar - added element comparer support
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-import org.eclipse.jface.viewers.IElementComparer;
-
-/**
- * CustomHashtable associates keys with values. Keys and values cannot be null.
- * The size of the Hashtable is the number of key/value pairs it contains.
- * The capacity is the number of key/value pairs the Hashtable can hold.
- * The load factor is a float value which determines how full the Hashtable
- * gets before expanding the capacity. If the load factor of the Hashtable
- * is exceeded, the capacity is doubled.
- * <p>
- * CustomHashtable allows a custom comparator and hash code provider.
- */
-/* package */final class CustomHashtable {
-
- /**
- * HashMapEntry is an internal class which is used to hold the entries of a Hashtable.
- */
- private static class HashMapEntry {
- Object key, value;
-
- HashMapEntry next;
-
- HashMapEntry(Object theKey, Object theValue) {
- key = theKey;
- value = theValue;
- }
- }
-
- private static final class EmptyEnumerator implements Enumeration {
- public boolean hasMoreElements() {
- return false;
- }
-
- public Object nextElement() {
- throw new NoSuchElementException();
- }
- }
-
- private class HashEnumerator implements Enumeration {
- boolean key;
-
- int start;
-
- HashMapEntry entry;
-
- HashEnumerator(boolean isKey) {
- key = isKey;
- start = firstSlot;
- }
-
- public boolean hasMoreElements() {
- if (entry != null)
- return true;
- while (start <= lastSlot)
- if (elementData[start++] != null) {
- entry = elementData[start - 1];
- return true;
- }
- return false;
- }
-
- public Object nextElement() {
- if (hasMoreElements()) {
- Object result = key ? entry.key : entry.value;
- entry = entry.next;
- return result;
- } else
- throw new NoSuchElementException();
- }
- }
-
- transient int elementCount;
-
- transient HashMapEntry[] elementData;
-
- private float loadFactor;
-
- private int threshold;
-
- transient int firstSlot = 0;
-
- transient int lastSlot = -1;
-
- transient private IElementComparer comparer;
-
- private static final EmptyEnumerator emptyEnumerator = new EmptyEnumerator();
-
- /**
- * The default capacity used when not specified in the constructor.
- */
- public static final int DEFAULT_CAPACITY = 13;
-
- /**
- * Constructs a new Hashtable using the default capacity
- * and load factor.
- */
- public CustomHashtable() {
- this(13);
- }
-
- /**
- * Constructs a new Hashtable using the specified capacity
- * and the default load factor.
- *
- * @param capacity the initial capacity
- */
- public CustomHashtable(int capacity) {
- this(capacity, null);
- }
-
- /**
- * Constructs a new hash table with the default capacity and the given
- * element comparer.
- *
- * @param comparer the element comparer to use to compare keys and obtain
- * hash codes for keys, or <code>null</code> to use the normal
- * <code>equals</code> and <code>hashCode</code> methods
- */
- public CustomHashtable(IElementComparer comparer) {
- this(DEFAULT_CAPACITY, comparer);
- }
-
- /**
- * Constructs a new hash table with the given capacity and the given
- * element comparer.
- *
- * @param capacity the maximum number of elements that can be added without
- * rehashing
- * @param comparer the element comparer to use to compare keys and obtain
- * hash codes for keys, or <code>null</code> to use the normal
- * <code>equals</code> and <code>hashCode</code> methods
- */
- public CustomHashtable(int capacity, IElementComparer comparer) {
- if (capacity >= 0) {
- elementCount = 0;
- elementData = new HashMapEntry[capacity == 0 ? 1 : capacity];
- firstSlot = elementData.length;
- loadFactor = 0.75f;
- computeMaxSize();
- } else
- throw new IllegalArgumentException();
- this.comparer = comparer;
- }
-
- /**
- * Constructs a new hash table with enough capacity to hold all keys in the
- * given hash table, then adds all key/value pairs in the given hash table
- * to the new one, using the given element comparer.
- *
- * @param table the hash table to add from
- * @param comparer the element comparer to use to compare keys and obtain
- * hash codes for keys, or <code>null</code> to use the normal
- * <code>equals</code> and <code>hashCode</code> methods
- */
- public CustomHashtable(CustomHashtable table, IElementComparer comparer) {
- this(table.size() * 2, comparer);
- for (int i = table.elementData.length; --i >= 0;) {
- HashMapEntry entry = table.elementData[i];
- while (entry != null) {
- put(entry.key, entry.value);
- entry = entry.next;
- }
- }
- }
-
- private void computeMaxSize() {
- threshold = (int) (elementData.length * loadFactor);
- }
-
- /**
- * Answers if this Hashtable contains the specified object as a key
- * of one of the key/value pairs.
- *
- * @param key the object to look for as a key in this Hashtable
- * @return true if object is a key in this Hashtable, false otherwise
- */
- public boolean containsKey(Object key) {
- return getEntry(key) != null;
- }
-
- /**
- * Answers an Enumeration on the values of this Hashtable. The
- * results of the Enumeration may be affected if the contents
- * of this Hashtable are modified.
- *
- * @return an Enumeration of the values of this Hashtable
- */
- public Enumeration elements() {
- if (elementCount == 0)
- return emptyEnumerator;
- return new HashEnumerator(false);
- }
-
- /**
- * Answers the value associated with the specified key in
- * this Hashtable.
- *
- * @param key the key of the value returned
- * @return the value associated with the specified key, null if the specified key
- * does not exist
- */
- public Object get(Object key) {
- int index = (hashCode(key) & 0x7FFFFFFF) % elementData.length;
- HashMapEntry entry = elementData[index];
- while (entry != null) {
- if (keyEquals(key, entry.key))
- return entry.value;
- entry = entry.next;
- }
- return null;
- }
-
- private HashMapEntry getEntry(Object key) {
- int index = (hashCode(key) & 0x7FFFFFFF) % elementData.length;
- HashMapEntry entry = elementData[index];
- while (entry != null) {
- if (keyEquals(key, entry.key))
- return entry;
- entry = entry.next;
- }
- return null;
- }
-
- /**
- * Answers the hash code for the given key.
- */
- private int hashCode(Object key) {
- if (comparer == null)
- return key.hashCode();
- else
- return comparer.hashCode(key);
- }
-
- /**
- * Compares two keys for equality.
- */
- private boolean keyEquals(Object a, Object b) {
- if (comparer == null)
- return a.equals(b);
- else
- return comparer.equals(a, b);
- }
-
- /**
- * Answers an Enumeration on the keys of this Hashtable. The
- * results of the Enumeration may be affected if the contents
- * of this Hashtable are modified.
- *
- * @return an Enumeration of the keys of this Hashtable
- */
- public Enumeration keys() {
- if (elementCount == 0)
- return emptyEnumerator;
- return new HashEnumerator(true);
- }
-
- /**
- * Associate the specified value with the specified key in this Hashtable.
- * If the key already exists, the old value is replaced. The key and value
- * cannot be null.
- *
- * @param key the key to add
- * @param value the value to add
- * @return the old value associated with the specified key, null if the key did
- * not exist
- */
- public Object put(Object key, Object value) {
- if (key != null && value != null) {
- int index = (hashCode(key) & 0x7FFFFFFF) % elementData.length;
- HashMapEntry entry = elementData[index];
- while (entry != null && !keyEquals(key, entry.key))
- entry = entry.next;
- if (entry == null) {
- if (++elementCount > threshold) {
- rehash();
- index = (hashCode(key) & 0x7FFFFFFF) % elementData.length;
- }
- if (index < firstSlot)
- firstSlot = index;
- if (index > lastSlot)
- lastSlot = index;
- entry = new HashMapEntry(key, value);
- entry.next = elementData[index];
- elementData[index] = entry;
- return null;
- }
- Object result = entry.value;
- entry.key = key; // important to avoid hanging onto keys that are equal but "old" -- see bug 30607
- entry.value = value;
- return result;
- } else
- throw new NullPointerException();
- }
-
- /**
- * Increases the capacity of this Hashtable. This method is sent when
- * the size of this Hashtable exceeds the load factor.
- */
- private void rehash() {
- int length = elementData.length << 1;
- if (length == 0)
- length = 1;
- firstSlot = length;
- lastSlot = -1;
- HashMapEntry[] newData = new HashMapEntry[length];
- for (int i = elementData.length; --i >= 0;) {
- HashMapEntry entry = elementData[i];
- while (entry != null) {
- int index = (hashCode(entry.key) & 0x7FFFFFFF) % length;
- if (index < firstSlot)
- firstSlot = index;
- if (index > lastSlot)
- lastSlot = index;
- HashMapEntry next = entry.next;
- entry.next = newData[index];
- newData[index] = entry;
- entry = next;
- }
- }
- elementData = newData;
- computeMaxSize();
- }
-
- /**
- * Remove the key/value pair with the specified key from this Hashtable.
- *
- * @param key the key to remove
- * @return the value associated with the specified key, null if the specified key
- * did not exist
- */
- public Object remove(Object key) {
- HashMapEntry last = null;
- int index = (hashCode(key) & 0x7FFFFFFF) % elementData.length;
- HashMapEntry entry = elementData[index];
- while (entry != null && !keyEquals(key, entry.key)) {
- last = entry;
- entry = entry.next;
- }
- if (entry != null) {
- if (last == null)
- elementData[index] = entry.next;
- else
- last.next = entry.next;
- elementCount--;
- return entry.value;
- }
- return null;
- }
-
- /**
- * Answers the number of key/value pairs in this Hashtable.
- *
- * @return the number of key/value pairs in this Hashtable
- */
- public int size() {
- return elementCount;
- }
-
- /**
- * Answers the string representation of this Hashtable.
- *
- * @return the string representation of this Hashtable
- */
- public String toString() {
- if (size() == 0)
- return "{}"; //$NON-NLS-1$
-
- StringBuffer buffer = new StringBuffer();
- buffer.append('{');
- for (int i = elementData.length; --i >= 0;) {
- HashMapEntry entry = elementData[i];
- while (entry != null) {
- buffer.append(entry.key);
- buffer.append('=');
- buffer.append(entry.value);
- buffer.append(", "); //$NON-NLS-1$
- entry = entry.next;
- }
- }
- // Remove the last ", "
- if (elementCount > 0)
- buffer.setLength(buffer.length() - 2);
- buffer.append('}');
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/DefaultElementComparer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/DefaultElementComparer.java
deleted file mode 100644
index 04b01e4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/DefaultElementComparer.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.viewers.IElementComparer;
-
-public class DefaultElementComparer implements IElementComparer {
-
- public static final DefaultElementComparer INSTANCE= new DefaultElementComparer();
-
- public boolean equals(Object a, Object b) {
- return a.equals(b);
- }
- public int hashCode(Object element) {
- return element.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDragAdapter.java
deleted file mode 100644
index 07f93e6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDragAdapter.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceAdapter;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.actions.WorkspaceModifyOperation;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Drag support class to allow dragging of files and folder from
- * the packages view to another application.
- */
-class FileTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener {
-
- private ISelectionProvider fProvider;
-
- FileTransferDragAdapter(ISelectionProvider provider) {
- fProvider= provider;
- Assert.isNotNull(fProvider);
- }
-
- public Transfer getTransfer() {
- return FileTransfer.getInstance();
- }
-
- public void dragStart(DragSourceEvent event) {
- event.doit= isDragable(fProvider.getSelection());
- }
-
- private boolean isDragable(ISelection s) {
- if (!(s instanceof IStructuredSelection))
- return false;
- IStructuredSelection selection= (IStructuredSelection)s;
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement jElement= (IJavaScriptElement)element;
- int type= jElement.getElementType();
- // valid elements are: roots, units and types. Don't allow dragging
- // projects outside of eclipse
- if (type != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT &&
- type != IJavaScriptElement.JAVASCRIPT_UNIT && type != IJavaScriptElement.TYPE)
- return false;
- IPackageFragmentRoot root= (IPackageFragmentRoot)jElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null && root.isArchive())
- return false;
- }
- }
- List resources= convertIntoResources(selection);
- return resources.size() == selection.size();
- }
-
- public void dragSetData(DragSourceEvent event){
- List elements= getResources();
- if (elements == null || elements.size() == 0) {
- event.data= null;
- return;
- }
-
- event.data= getResourceLocations(elements);
- }
-
- private static String[] getResourceLocations(List resources) {
- return Resources.getLocationOSStrings((IResource[]) resources.toArray(new IResource[resources.size()]));
- }
-
- public void dragFinished(DragSourceEvent event) {
- if (!event.doit)
- return;
-
- if (event.detail == DND.DROP_MOVE) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=30543
- // handleDropMove(event);
- } else if (event.detail == DND.DROP_NONE || event.detail == DND.DROP_TARGET_MOVE) {
- handleRefresh(event);
- }
- }
-
- /* package */ void handleDropMove(DragSourceEvent event) {
- final List elements= getResources();
- if (elements == null || elements.size() == 0)
- return;
-
- WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
- public void execute(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(PackagesMessages.DragAdapter_deleting, elements.size());
- MultiStatus status= createMultiStatus();
- Iterator iter= elements.iterator();
- while(iter.hasNext()) {
- IResource resource= (IResource)iter.next();
- try {
- monitor.subTask(resource.getFullPath().toOSString());
- resource.delete(true, null);
-
- } catch (CoreException e) {
- status.add(e.getStatus());
- } finally {
- monitor.worked(1);
- }
- }
- if (!status.isOK()) {
- throw new CoreException(status);
- }
- } finally {
- monitor.done();
- }
- }
- };
- runOperation(op, true, false);
- }
-
- private void handleRefresh(DragSourceEvent event) {
- final Set roots= collectRoots(getResources());
-
- WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
- public void execute(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(PackagesMessages.DragAdapter_refreshing, roots.size());
- MultiStatus status= createMultiStatus();
- Iterator iter= roots.iterator();
- while (iter.hasNext()) {
- IResource r= (IResource)iter.next();
- try {
- r.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 1));
- } catch (CoreException e) {
- status.add(e.getStatus());
- }
- }
- if (!status.isOK()) {
- throw new CoreException(status);
- }
- } finally {
- monitor.done();
- }
- }
- };
-
- runOperation(op, true, false);
- }
-
- protected Set collectRoots(final List elements) {
- final Set roots= new HashSet(10);
-
- Iterator iter= elements.iterator();
- while (iter.hasNext()) {
- IResource resource= (IResource)iter.next();
- IResource parent= resource.getParent();
- if (parent == null) {
- roots.add(resource);
- } else {
- roots.add(parent);
- }
- }
- return roots;
- }
-
- private List getResources() {
- ISelection s= fProvider.getSelection();
- if (!(s instanceof IStructuredSelection))
- return null;
-
- return convertIntoResources((IStructuredSelection)s);
- }
-
- private List convertIntoResources(IStructuredSelection selection) {
- List result= new ArrayList(selection.size());
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object o= iter.next();
- IResource r= null;
- if (o instanceof IResource) {
- r= (IResource)o;
- } else if (o instanceof IAdaptable) {
- r= (IResource)((IAdaptable)o).getAdapter(IResource.class);
- }
- // Only add resource for which we have a location
- // in the local file system.
- if (r != null && r.getLocation() != null) {
- result.add(r);
- }
- }
- return result;
- }
-
- private MultiStatus createMultiStatus() {
- return new MultiStatus(JavaScriptPlugin.getPluginId(),
- IStatus.OK, PackagesMessages.DragAdapter_problem, null);
- }
-
- private void runOperation(IRunnableWithProgress op, boolean fork, boolean cancelable) {
- try {
- Shell parent= JavaScriptPlugin.getActiveWorkbenchShell();
- new ProgressMonitorDialog(parent).run(fork, cancelable, op);
- } catch (InvocationTargetException e) {
- String message= PackagesMessages.DragAdapter_problem;
- String title= PackagesMessages.DragAdapter_problemTitle;
- ExceptionHandler.handle(e, title, message);
- } catch (InterruptedException e) {
- // Do nothing. Operation has been canceled by user.
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDropAdapter.java
deleted file mode 100644
index c289e058..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/FileTransferDropAdapter.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Adapter to handle file drop from other applications.
- */
-class FileTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
-
- FileTransferDropAdapter(AbstractTreeViewer viewer) {
- super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
- }
-
- //---- TransferDropTargetListener interface ---------------------------------------
-
- public Transfer getTransfer() {
- return FileTransfer.getInstance();
- }
-
- public boolean isEnabled(DropTargetEvent event) {
- Object target= event.item != null ? event.item.getData() : null;
- if (target == null)
- return false;
- return target instanceof IJavaScriptElement || target instanceof IResource;
- }
-
- //---- Actual DND -----------------------------------------------------------------
-
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- event.detail= DND.DROP_NONE;
-
- boolean isPackageFragment= target instanceof IPackageFragment;
- boolean isJavaProject= target instanceof IJavaScriptProject;
- boolean isPackageFragmentRoot= target instanceof IPackageFragmentRoot;
- boolean isContainer= target instanceof IContainer;
-
- if (!(isPackageFragment || isJavaProject || isPackageFragmentRoot || isContainer))
- return;
-
- if (isContainer) {
- IContainer container= (IContainer)target;
- if (container.isAccessible() && !Resources.isReadOnly(container))
- event.detail= DND.DROP_COPY;
- } else {
- IJavaScriptElement element= (IJavaScriptElement)target;
- if (!element.isReadOnly())
- event.detail= DND.DROP_COPY;
- }
-
- return;
- }
-
- public void drop(Object dropTarget, final DropTargetEvent event) {
- try {
- int operation= event.detail;
-
- event.detail= DND.DROP_NONE;
- final Object data= event.data;
- if (data == null || !(data instanceof String[]) || operation != DND.DROP_COPY)
- return;
-
- final IContainer target= getActualTarget(dropTarget);
- if (target == null)
- return;
-
- // Run the import operation asynchronously.
- // Otherwise the drag source (e.g., Windows Explorer) will be blocked
- // while the operation executes. Fixes bug 35796.
- Display.getCurrent().asyncExec(new Runnable() {
- public void run() {
- getShell().forceActive();
- new CopyFilesAndFoldersOperation(getShell()).copyFiles((String[]) data, target);
- // Import always performs a copy.
- event.detail= DND.DROP_COPY;
- }
- });
- } catch (JavaScriptModelException e) {
- String title= PackagesMessages.DropAdapter_errorTitle;
- String message= PackagesMessages.DropAdapter_errorMessage;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
- }
-
- private IContainer getActualTarget(Object dropTarget) throws JavaScriptModelException{
- if (dropTarget instanceof IContainer)
- return (IContainer)dropTarget;
- else if (dropTarget instanceof IJavaScriptElement)
- return getActualTarget(((IJavaScriptElement)dropTarget).getCorrespondingResource());
- return null;
- }
-
- private Shell getShell() {
- return getViewer().getControl().getShell();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoPackageAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoPackageAction.java
deleted file mode 100644
index 9fa726b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoPackageAction.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.PackageSelectionDialog;
-
-class GotoPackageAction extends Action {
-
- private PackageExplorerPart fPackageExplorer;
-
- GotoPackageAction(PackageExplorerPart part) {
- super(PackagesMessages.GotoPackage_action_label);
- setDescription(PackagesMessages.GotoPackage_action_description);
- fPackageExplorer= part;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_PACKAGE_ACTION);
- }
-
- public void run() {
- try {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- SelectionDialog dialog= createAllPackagesDialog(shell);
- dialog.setTitle(getDialogTitle());
- dialog.setMessage(PackagesMessages.GotoPackage_dialog_message);
- dialog.open();
- Object[] res= dialog.getResult();
- if (res != null && res.length == 1)
- gotoPackage((IPackageFragment)res[0]);
- } catch (JavaScriptModelException e) {
- }
- }
-
- private SelectionDialog createAllPackagesDialog(Shell shell) throws JavaScriptModelException{
- IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- int flag= PackageSelectionDialog.F_HIDE_EMPTY_INNER;
- PackageSelectionDialog dialog= new PackageSelectionDialog(shell, progressService, flag, scope);
- dialog.setFilter(""); //$NON-NLS-1$
- dialog.setIgnoreCase(false);
- dialog.setMultipleSelection(false);
- return dialog;
- }
-
- private void gotoPackage(IPackageFragment p) {
- fPackageExplorer.selectReveal(new StructuredSelection(p));
- if (!p.equals(getSelectedElement())) {
- MessageDialog.openInformation(fPackageExplorer.getSite().getShell(),
- getDialogTitle(),
- Messages.format(PackagesMessages.PackageExplorer_element_not_present, p.getElementName()));
- }
- }
-
- private Object getSelectedElement() {
- return ((IStructuredSelection)fPackageExplorer.getSite().getSelectionProvider().getSelection()).getFirstElement();
- }
-
- private String getDialogTitle() {
- return PackagesMessages.GotoPackage_dialog_title;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java
deleted file mode 100644
index 0bdf843a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.IStructuredSelection;
-
-/**
- * Goto to the referenced required project
- */
-class GotoRequiredProjectAction extends Action {
-
- private PackageExplorerPart fPackageExplorer;
-
- GotoRequiredProjectAction(PackageExplorerPart part) {
- super(PackagesMessages.GotoRequiredProjectAction_label);
- setDescription(PackagesMessages.GotoRequiredProjectAction_description);
- setToolTipText(PackagesMessages.GotoRequiredProjectAction_tooltip);
- fPackageExplorer= part;
- }
-
- public void run() {
- IStructuredSelection selection= (IStructuredSelection)fPackageExplorer.getSite().getSelectionProvider().getSelection();
- Object element= selection.getFirstElement();
- if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) {
- JsGlobalScopeContainer.RequiredProjectWrapper wrapper= (JsGlobalScopeContainer.RequiredProjectWrapper) element;
- fPackageExplorer.tryToReveal(wrapper.getProject());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoResourceAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoResourceAction.java
deleted file mode 100644
index a7e2edb9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoResourceAction.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-public class GotoResourceAction extends Action {
-
- private PackageExplorerPart fPackageExplorer;
-
- private static class GotoResourceDialog extends FilteredResourcesSelectionDialog {
- private IJavaScriptModel fJavaModel;
- public GotoResourceDialog(Shell parentShell, IContainer container, StructuredViewer viewer) {
- super(parentShell, false, container, IResource.FILE | IResource.FOLDER | IResource.PROJECT);
- fJavaModel= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- setTitle(PackagesMessages.GotoResource_dialog_title);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell, IJavaHelpContextIds.GOTO_RESOURCE_DIALOG);
- }
-
- protected ItemsFilter createFilter() {
- return new GotoResourceFilter();
- }
-
- private class GotoResourceFilter extends ResourceFilter {
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#matchItem(java.lang.Object)
- */
- public boolean matchItem(Object item) {
- IResource resource = (IResource) item;
- return super.matchItem(item) && select(resource);
- }
-
- /**
- * This is the orignal <code>select</code> method. Since
- * <code>GotoResourceDialog</code> needs to extend
- * <code>FilteredResourcesSelectionDialog</code> result of this
- * method must be combined with the <code>matchItem</code> method
- * from super class (<code>ResourceFilter</code>).
- *
- * @param resource
- * A resource
- * @return <code>true</code> if item matches against given
- * conditions <code>false</code> otherwise
- */
- private boolean select(IResource resource) {
- IProject project= resource.getProject();
- try {
- if (project.getNature(JavaScriptCore.NATURE_ID) != null)
- return fJavaModel.contains(resource);
- } catch (CoreException e) {
- // do nothing. Consider resource;
- }
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#equalsFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter)
- */
- public boolean equalsFilter(ItemsFilter filter) {
- if (!super.equalsFilter(filter)) {
- return false;
- }
- if (!(filter instanceof GotoResourceFilter)) {
- return false;
- }
- return true;
- }
- }
-
- }
-
- public GotoResourceAction(PackageExplorerPart explorer) {
- setText(PackagesMessages.GotoResource_action_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_RESOURCE_ACTION);
- fPackageExplorer= explorer;
- }
-
- public void run() {
- TreeViewer viewer= fPackageExplorer.getTreeViewer();
- GotoResourceDialog dialog= new GotoResourceDialog(fPackageExplorer.getSite().getShell(),
- ResourcesPlugin.getWorkspace().getRoot(), viewer);
- dialog.open();
- Object[] result = dialog.getResult();
- if (result == null || result.length == 0 || !(result[0] instanceof IResource))
- return;
- StructuredSelection selection= null;
- IJavaScriptElement element = JavaScriptCore.create((IResource)result[0]);
- if (element != null && element.exists())
- selection= new StructuredSelection(element);
- else
- selection= new StructuredSelection(result[0]);
- viewer.setSelection(selection, true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoTypeAction.java
deleted file mode 100644
index 11651377..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoTypeAction.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.IJavaScriptElementSearchConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-class GotoTypeAction extends Action {
-
- private PackageExplorerPart fPackageExplorer;
-
- GotoTypeAction(PackageExplorerPart part) {
- super();
- setText(PackagesMessages.GotoType_action_label);
- setDescription(PackagesMessages.GotoType_action_description);
- fPackageExplorer= part;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_TYPE_ACTION);
- }
-
- public void run() {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- SelectionDialog dialog= null;
- try {
- dialog= JavaScriptUI.createTypeDialog(shell, new ProgressMonitorDialog(shell),
- SearchEngine.createWorkspaceScope(), IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES, false);
- } catch (JavaScriptModelException e) {
- String title= getDialogTitle();
- String message= PackagesMessages.GotoType_error_message;
- ExceptionHandler.handle(e, title, message);
- return;
- }
-
- dialog.setTitle(getDialogTitle());
- dialog.setMessage(PackagesMessages.GotoType_dialog_message);
- if (dialog.open() == IDialogConstants.CANCEL_ID) {
- return;
- }
-
- Object[] types= dialog.getResult();
- if (types != null && types.length > 0) {
- gotoType((IType) types[0]);
- }
- }
-
- private void gotoType(IType type) {
- IJavaScriptUnit cu= (IJavaScriptUnit) type.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- IJavaScriptElement element= null;
- if (cu != null) {
- element= cu.getPrimary();
- }
- else {
- element= type.getAncestor(IJavaScriptElement.CLASS_FILE);
- }
- if (element != null) {
- PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
- if (view != null) {
- view.selectReveal(new StructuredSelection(element));
- if (!element.equals(getSelectedElement(view))) {
- MessageDialog.openInformation(fPackageExplorer.getSite().getShell(),
- getDialogTitle(),
- Messages.format(PackagesMessages.PackageExplorer_element_not_present, element.getElementName()));
- }
- }
- }
- }
-
- private Object getSelectedElement(PackageExplorerPart view) {
- return ((IStructuredSelection)view.getSite().getSelectionProvider().getSelection()).getFirstElement();
- }
-
- private String getDialogTitle() {
- return PackagesMessages.GotoType_dialog_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/HierarchicalDecorationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/HierarchicalDecorationContext.java
deleted file mode 100644
index 70390b8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/HierarchicalDecorationContext.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.mapping.ResourceMappingContext;
-import org.eclipse.core.resources.mapping.ResourceTraversal;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.viewers.IDecorationContext;
-import org.eclipse.team.ui.mapping.SynchronizationStateTester;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaElementResourceMapping;
-
-public class HierarchicalDecorationContext implements IDecorationContext {
-
- private HierarchicalSynchronizationStateTester fStateTester;
- public static final HierarchicalDecorationContext CONTEXT= new HierarchicalDecorationContext();
-
- private HierarchicalDecorationContext() {
- fStateTester= new HierarchicalSynchronizationStateTester();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IDecorationContext#getProperties()
- */
- public String[] getProperties() {
- return new String[] { SynchronizationStateTester.PROP_TESTER };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IDecorationContext#getProperty(java.lang.String)
- */
- public Object getProperty(String property) {
- if (property == SynchronizationStateTester.PROP_TESTER) {
- return fStateTester;
- }
- return null;
- }
-
- private static final class HierarchicalSynchronizationStateTester extends SynchronizationStateTester {
-
- public HierarchicalSynchronizationStateTester() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.team.ui.mapping.SynchronizationStateTester#getState(java.lang.Object, int, org.eclipse.core.runtime.IProgressMonitor)
- */
- public int getState(Object element, int stateMask, IProgressMonitor monitor) throws CoreException {
- if (element instanceof JavaElementResourceMapping) {
- JavaElementResourceMapping mapping= (JavaElementResourceMapping) element;
- IJavaScriptElement javaElement= mapping.getJavaElement();
- if (javaElement instanceof IPackageFragment) {
- IPackageFragment packageFragment= (IPackageFragment) javaElement;
- if (!packageFragment.isDefaultPackage()) {
- element= new HierarchicalPackageFragementResourceMapping(packageFragment);
- }
- }
- }
- return super.getState(element, stateMask, monitor);
- }
- }
-
- private static final class HierarchicalPackageFragementResourceMapping extends JavaElementResourceMapping {
- private final IPackageFragment fPack;
- private HierarchicalPackageFragementResourceMapping(IPackageFragment fragment) {
- Assert.isNotNull(fragment);
- fPack= fragment;
- }
- public Object getModelObject() {
- return fPack;
- }
- public IProject[] getProjects() {
- return new IProject[] {fPack.getJavaScriptProject().getProject() };
- }
- public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException {
- return new ResourceTraversal[] {
- new ResourceTraversal(new IResource[] {fPack.getResource()}, IResource.DEPTH_INFINITE, 0)
- };
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/IMultiElementTreeContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/IMultiElementTreeContentProvider.java
deleted file mode 100644
index f768d158..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/IMultiElementTreeContentProvider.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreePath;
-
-public interface IMultiElementTreeContentProvider extends ITreeContentProvider {
- public TreePath[] getTreePaths(Object element);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/JsGlobalScopeContainer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/JsGlobalScopeContainer.java
deleted file mode 100644
index a0f5ebc3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/JsGlobalScopeContainer.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJsGlobalScopeContainerInitializerExtension;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.JSDScopeUiUtil;
-
-/**
- * Representation of class path containers in Java UI.
- */
-public class JsGlobalScopeContainer extends PackageFragmentRootContainer {
-
- private IIncludePathEntry fClassPathEntry;
- private IJsGlobalScopeContainer fContainer;
-
- public static class RequiredProjectWrapper implements IAdaptable, IWorkbenchAdapter {
-
- private final JsGlobalScopeContainer fParent;
- private final IJavaScriptProject fProject;
-
- public RequiredProjectWrapper(JsGlobalScopeContainer parent, IJavaScriptProject project) {
- fParent= parent;
- fProject= project;
- }
-
- public IJavaScriptProject getProject() {
- return fProject;
- }
-
- public JsGlobalScopeContainer getParentJsGlobalScopeContainer() {
- return fParent;
- }
-
- public Object getAdapter(Class adapter) {
- if (adapter == IWorkbenchAdapter.class)
- return this;
- return null;
- }
-
- public Object[] getChildren(Object o) {
- return new Object[0];
- }
-
- public ImageDescriptor getImageDescriptor(Object object) {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT);
- }
-
- public String getLabel(Object o) {
- return fProject.getElementName();
- }
-
- public Object getParent(Object o) {
- return fParent;
- }
- }
-
- public JsGlobalScopeContainer(IJavaScriptProject parent, IIncludePathEntry entry) {
- super(parent);
- fClassPathEntry= entry;
- try {
- fContainer= JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), parent);
- } catch (JavaScriptModelException e) {
- fContainer= null;
- }
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof JsGlobalScopeContainer) {
- JsGlobalScopeContainer other = (JsGlobalScopeContainer)obj;
- if (getJavaProject().equals(other.getJavaProject()) &&
- fClassPathEntry.equals(other.fClassPathEntry)) {
- return true;
- }
-
- }
- return false;
- }
-
- public int hashCode() {
- return getJavaProject().hashCode()*17+fClassPathEntry.hashCode();
- }
-
- public IPackageFragmentRoot[] getPackageFragmentRoots() {
- return getJavaProject().findPackageFragmentRoots(fClassPathEntry);
- }
-
- public IAdaptable[] getChildren() {
- List list= new ArrayList();
- IPackageFragmentRoot[] roots= getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- list.add(roots[i]);
- }
- if (fContainer != null) {
- IIncludePathEntry[] classpathEntries= fContainer.getIncludepathEntries();
- if (classpathEntries == null) {
- // invalid implementation of a classpath container
- JavaScriptPlugin.log(new IllegalArgumentException("Invalid classpath container implementation: getClasspathEntries() returns null. " + fContainer.getPath())); //$NON-NLS-1$
- } else {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int i= 0; i < classpathEntries.length; i++) {
- IIncludePathEntry entry= classpathEntries[i];
- if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- IResource resource= root.findMember(entry.getPath());
- if (resource instanceof IProject)
- list.add(new RequiredProjectWrapper(this, JavaScriptCore.create((IProject) resource)));
- }
- }
- }
- }
- return (IAdaptable[]) list.toArray(new IAdaptable[list.size()]);
- }
-
- public ImageDescriptor getImageDescriptor() {
- IJsGlobalScopeContainerInitializerExtension init = JSDScopeUiUtil.getContainerUiInitializer(fClassPathEntry.getPath());
- if(init!=null ) {
- IPath entPath = fClassPathEntry.getPath();
- ImageDescriptor image = init.getImage(entPath, fClassPathEntry.toString(), super.getJavaProject());
- if(image!=null) return image;
- }
- return JavaPluginImages.DESC_OBJS_LIBRARY;
- }
-
- public String getLabel() {
- if (fContainer != null)
- return fContainer.getDescription();
-
- IPath path= fClassPathEntry.getPath();
- String containerId= path.segment(0);
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerId);
- if (initializer != null) {
- String description= initializer.getDescription(path, getJavaProject());
- return Messages.format(PackagesMessages.JsGlobalScopeContainer_unbound_label, description);
- }
- return Messages.format(PackagesMessages.JsGlobalScopeContainer_unknown_label, path.toString());
- }
-
- public IIncludePathEntry getClasspathEntry() {
- return fClassPathEntry;
- }
-
- static boolean contains(IJavaScriptProject project, IIncludePathEntry entry, IPackageFragmentRoot root) {
- IPackageFragmentRoot[] roots= project.findPackageFragmentRoots(entry);
- for (int i= 0; i < roots.length; i++) {
- if (roots[i].equals(root))
- return true;
- }
- return false;
- }
-
- public String toString() {
- return fClassPathEntry.toString();
- }
-
- public boolean hasChildren() {
- return getPackageFragmentRoots().length > 0;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java
deleted file mode 100644
index e66818e8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Adds view menus to switch between flat and hierarchical layout.
- *
- *
- */
-class LayoutActionGroup extends ActionGroup {
-
- public static final String VIEWMENU_LAYOUT_GROUP= "layout"; //$NON-NLS-1$
-
- private IAction fFlatLayoutAction;
- private IAction fHierarchicalLayoutAction;
- private IAction fShowLibrariesNode;
-
- LayoutActionGroup(PackageExplorerPart packageExplorer) {
- fFlatLayoutAction= new LayoutAction(packageExplorer, true);
- fHierarchicalLayoutAction= new LayoutAction(packageExplorer, false);
- fShowLibrariesNode= new ShowLibrariesNodeAction(packageExplorer);
- }
-
- /* (non-Javadoc)
- * @see ActionGroup#fillActionBars(IActionBars)
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- contributeToViewMenu(actionBars.getMenuManager());
- }
-
- private void contributeToViewMenu(IMenuManager viewMenu) {
- viewMenu.add(new Separator(VIEWMENU_LAYOUT_GROUP));
-
- // Create layout sub menu
-
- IMenuManager layoutSubMenu= new MenuManager(PackagesMessages.LayoutActionGroup_label);
- layoutSubMenu.add(fFlatLayoutAction);
- layoutSubMenu.add(fHierarchicalLayoutAction);
-
- viewMenu.add(layoutSubMenu);
- viewMenu.add(fShowLibrariesNode);
- }
-}
-
-class LayoutAction extends Action implements IAction {
-
- private boolean fIsFlatLayout;
- private PackageExplorerPart fPackageExplorer;
-
- public LayoutAction(PackageExplorerPart packageExplorer, boolean flat) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
-
- fIsFlatLayout= flat;
- fPackageExplorer= packageExplorer;
- if (fIsFlatLayout) {
- setText(PackagesMessages.LayoutActionGroup_flatLayoutAction_label);
- JavaPluginImages.setLocalImageDescriptors(this, "flatLayout.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_FLAT_ACTION);
- } else {
- setText(PackagesMessages.LayoutActionGroup_hierarchicalLayoutAction_label);
- JavaPluginImages.setLocalImageDescriptors(this, "hierarchicalLayout.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LAYOUT_HIERARCHICAL_ACTION);
- }
- setChecked(packageExplorer.isFlatLayout() == fIsFlatLayout);
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- if (fPackageExplorer.isFlatLayout() != fIsFlatLayout)
- fPackageExplorer.setFlatLayout(fIsFlatLayout);
- }
-}
-
-class ShowLibrariesNodeAction extends Action implements IAction {
-
- private PackageExplorerPart fPackageExplorer;
-
- public ShowLibrariesNodeAction(PackageExplorerPart packageExplorer) {
- super(PackagesMessages.LayoutActionGroup_show_libraries_in_group, AS_CHECK_BOX);
- fPackageExplorer= packageExplorer;
- setChecked(packageExplorer.isLibrariesNodeShown());
- }
-
- /*
- * @see org.eclipse.jface.action.IAction#run()
- */
- public void run() {
- fPackageExplorer.setShowLibrariesNode(isChecked());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java
deleted file mode 100644
index 59548f7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class LibraryContainer extends PackageFragmentRootContainer {
-
- public LibraryContainer(IJavaScriptProject project) {
- super(project);
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof LibraryContainer) {
- LibraryContainer other = (LibraryContainer)obj;
- return getJavaProject().equals(other.getJavaProject());
- }
- return false;
- }
-
- public int hashCode() {
- return getJavaProject().hashCode();
- }
-
- public IAdaptable[] getChildren() {
- return getPackageFragmentRoots();
- }
-
-
- public ImageDescriptor getImageDescriptor() {
- return JavaPluginImages.DESC_OBJS_LIBRARY;
- }
-
- public String getLabel() {
- return PackagesMessages.LibraryContainer_name;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer#getPackageFragmentRoots()
- */
- public IPackageFragmentRoot[] getPackageFragmentRoots() {
- List list= new ArrayList();
- try {
- IPackageFragmentRoot[] roots= getJavaProject().getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- int classpathEntryKind= root.getRawIncludepathEntry().getEntryKind();
- if (classpathEntryKind == IIncludePathEntry.CPE_LIBRARY || classpathEntryKind == IIncludePathEntry.CPE_VARIABLE) {
- list.add(root);
- }
- }
- } catch (JavaScriptModelException e) {
- // fall through
- }
- return (IPackageFragmentRoot[]) list.toArray(new IPackageFragmentRoot[list.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/NamespaceGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/NamespaceGroup.java
deleted file mode 100644
index a92ca948..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/NamespaceGroup.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class NamespaceGroup implements IAdaptable {
- String fNamePrefix;
- int fNamePrefixLength;
- private IPackageFragmentRoot fPackageFragmentRoot;
- private PackageFragmentRootContainer fPackageFragmentRootContainer;
- private IJavaScriptUnit fJavaScriptUnit;
-
- public static final class WorkBenchAdapter implements IWorkbenchAdapter {
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object
- * )
- */
- public Object[] getChildren(Object o) {
- if (o instanceof NamespaceGroup)
- return ((NamespaceGroup) o).getChildren();
- return new Object[0];
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.model.IWorkbenchAdapter#getImageDescriptor(java.
- * lang.Object)
- */
- public ImageDescriptor getImageDescriptor(Object object) {
- return JavaPluginImages.DESC_OBJS_LOGICAL_PACKAGE;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object)
- */
- public String getLabel(Object o) {
- if (o instanceof NamespaceGroup) {
- return ((NamespaceGroup) o).fNamePrefix;
- }
- return EMPTY_STRING;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.model.IWorkbenchAdapter#getParent(java.lang.Object)
- */
- public Object getParent(Object o) {
- // TODO Auto-generated method stub
- System.out.println("Unimplemented method:WorkBenchAdapter.getParent"); //$NON-NLS-1$
- return null;
- }
-
- }
-
- /**
- * <p>Create a {@link NamespaceGroup} with a {@link IPackageFragmentRoot} as the parent</p>
- *
- * @param root parent of this group
- * @param prefix the prefix of this group
- */
- public NamespaceGroup(IPackageFragmentRoot root, String prefix) {
- fPackageFragmentRoot = root;
- fNamePrefix = prefix;
- fNamePrefixLength = fNamePrefix.length();
- this.fJavaScriptUnit = null;
- }
-
- /**
- * <p>Create a {@link NamespaceGroup} with a {@link PackageFragmentRootContainer} as the parent</p>
- *
- * @param root parent of this group
- * @param prefix the prefix of this group
- */
- public NamespaceGroup(PackageFragmentRootContainer root, String prefix) {
- fPackageFragmentRootContainer = root;
- fNamePrefix = prefix;
- fNamePrefixLength = fNamePrefix.length();
- this.fJavaScriptUnit = null;
- }
-
- /**
- * <p>Create a {@link NamespaceGroup} with a {@link IJavaScriptUnit} as the parent</p>
- *
- * @param unit parent of this group
- * @param prefix the prefix of this group
- */
- public NamespaceGroup(IJavaScriptUnit unit, String prefix) {
- fNamePrefix = prefix;
- fNamePrefixLength = fNamePrefix.length();
- this.fJavaScriptUnit = unit;
- }
-
- /**
- * @return If this group has a {@link IPackageFragmentRoot} as its parent then
- * returns that parent, else returns <code>null</code>
- */
- public IPackageFragmentRoot getPackageFragmentRoot() {
- return fPackageFragmentRoot;
- }
-
- /**
- * @return If this group has a {@link PackageFragmentRootContainer} as its parent then
- * returns that parent, else returns <code>null</code>
- */
- public PackageFragmentRootContainer getPackageFragmentRootContainer() {
- return fPackageFragmentRootContainer;
- }
-
- /**
- * @return If this group has a {@link IJavaScriptUnit} as its parent then
- * returns that parent, else returns <code>null</code>
- */
- public IJavaScriptUnit getJavaScriptUnit() {
- return this.fJavaScriptUnit;
- }
-
- Object getParent() {
- if (fPackageFragmentRoot != null)
- return fPackageFragmentRoot;
- if (fPackageFragmentRootContainer != null)
- return fPackageFragmentRootContainer;
- if(fJavaScriptUnit != null) {
- return this.fJavaScriptUnit;
- }
- return null;
- }
-
- private int computeParentHash() {
- if (fPackageFragmentRoot != null)
- return fPackageFragmentRoot.hashCode();
- if (fPackageFragmentRootContainer != null)
- return fPackageFragmentRootContainer.hashCode();
- return 0;
- }
-
- public String getText() {
- return fNamePrefix;
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof NamespaceGroup && getParent() != null) {
- return fNamePrefix.equals(((NamespaceGroup) obj).fNamePrefix) && getParent().equals(((NamespaceGroup) obj).getParent());
- }
- return super.equals(obj);
- }
-
- public int hashCode() {
- return computeParentHash() + super.hashCode();
- }
-
- /*
- * Copied from org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider
- */
- protected IJavaScriptElement[] filter(IJavaScriptElement[] children) {
- boolean initializers= false;
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i])) {
- initializers= true;
- break;
- }
- }
-
- if (!initializers)
- return children;
-
- List v= new ArrayList();
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i]))
- continue;
- v.add(children[i]);
- }
-
- IJavaScriptElement[] result = (IJavaScriptElement[]) v.toArray(new IJavaScriptElement[v.size()]);
- return result;
- }
-
- /*
- * Copied from org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider
- */
- protected boolean matches(IJavaScriptElement element) {
- if (element.getElementType() == IJavaScriptElement.TYPE && (element.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT || element.getParent().getElementType() == IJavaScriptElement.CLASS_FILE)) {
- IType type = (IType) element;
- try {
- return type.isAnonymous();
- }
- catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return false;
- }
-
- public Object[] getChildren() {
- Object[] children = null;
- try {
- children = ((IParent)this.getParent()).getChildren();
- }
- catch (JavaScriptModelException ex1) {
- // TODO Auto-generated catch block
- ex1.printStackTrace();
- }
- if (children == null)
- return null;
- List allChildren = new ArrayList();
-
- boolean unique = false;
- try {
- while (!unique && children != null && children.length > 0) {
- for (int i = 0; i < children.length; i++) {
- String display1 = ((IJavaScriptElement) children[0]).getDisplayName();
- String display2 = ((IJavaScriptElement) children[i]).getDisplayName();
- if (!((display1 == display2) || (display1 != null && display1.compareTo(display2) == 0))) {
- allChildren.addAll(Arrays.asList(children));
- unique = true;
- break;
- }
- }
- List more = new ArrayList();
- for (int i = 0; !unique && i < children.length; i++) {
- if (children[i] instanceof IPackageFragment) {
- more.addAll(Arrays.asList(((IPackageFragment) children[i]).getChildren()));
- }
- else if (children[i] instanceof IPackageFragmentRoot) {
- more.addAll(Arrays.asList(((IPackageFragmentRoot) children[i]).getChildren()));
- }
- else if (children[i] instanceof IClassFile) {
- more.addAll(Arrays.asList(filter(((IClassFile) children[i]).getChildren())));
- }
- else if (children[i] instanceof IJavaScriptUnit) {
- more.addAll(Arrays.asList(filter(((IJavaScriptUnit) children[i]).getChildren())));
- }
- else {
- /* bottomed out, now at javaElement level */
- unique = true;
- break;
- }
-
- }
- if (!unique)
- children = more.toArray();
- }
- }
- catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
-
-
- return allChildren.toArray();
- }
-
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class adapter) {
- if (adapter == IWorkbenchAdapter.class) {
- return new WorkBenchAdapter();
- }
-// else if (adapter == IProject.class) {
-// return getParent().getProject().getProject();
-// }
-
- return Platform.getAdapterManager().getAdapter(this, adapter);
- }
-
- public String toString() {
- return "Namespacegroup: " + fNamePrefix; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerActionGroup.java
deleted file mode 100644
index eb27f5ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerActionGroup.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.OpenStrategy;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.OpenInNewWindowAction;
-import org.eclipse.ui.views.framelist.BackAction;
-import org.eclipse.ui.views.framelist.ForwardAction;
-import org.eclipse.ui.views.framelist.Frame;
-import org.eclipse.ui.views.framelist.FrameAction;
-import org.eclipse.ui.views.framelist.FrameList;
-import org.eclipse.ui.views.framelist.GoIntoAction;
-import org.eclipse.ui.views.framelist.TreeFrame;
-import org.eclipse.ui.views.framelist.UpAction;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.NewWizardsActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectAllAction;
-//import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage.GenerateBuildPathActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.ViewActionGroup;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.BuildActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.CustomFiltersActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.ImportActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JdtActionConstants;
-import org.eclipse.wst.jsdt.ui.actions.NavigateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenProjectAction;
-import org.eclipse.wst.jsdt.ui.actions.ProjectActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-class PackageExplorerActionGroup extends CompositeActionGroup {
-
- private PackageExplorerPart fPart;
-
- private FrameList fFrameList;
- private GoIntoAction fZoomInAction;
- private BackAction fBackAction;
- private ForwardAction fForwardAction;
- private UpAction fUpAction;
- private GotoTypeAction fGotoTypeAction;
- private GotoPackageAction fGotoPackageAction;
- private GotoResourceAction fGotoResourceAction;
- private CollapseAllAction fCollapseAllAction;
- private SelectAllAction fSelectAllAction;
-
-
- private ToggleLinkingAction fToggleLinkingAction;
-
- private RefactorActionGroup fRefactorActionGroup;
- private NavigateActionGroup fNavigateActionGroup;
- private ViewActionGroup fViewActionGroup;
-
- private CustomFiltersActionGroup fCustomFiltersActionGroup;
-
- private IAction fGotoRequiredProjectAction;
-
- private ProjectActionGroup fProjectActionGroup;
-
- public PackageExplorerActionGroup(PackageExplorerPart part) {
- super();
- fPart= part;
- TreeViewer viewer= part.getTreeViewer();
-
- IPropertyChangeListener workingSetListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doWorkingSetChanged(event);
- }
- };
-
- IWorkbenchPartSite site = fPart.getSite();
- setGroups(new ActionGroup[] {
- new NewWizardsActionGroup(site),
- fNavigateActionGroup= new NavigateActionGroup(fPart),
- new CCPActionGroup(fPart),
- /*new GenerateBuildPathActionGroup(fPart),*/
- new GenerateActionGroup(fPart),
- fRefactorActionGroup= new RefactorActionGroup(fPart),
- new ImportActionGroup(fPart),
- new BuildActionGroup(fPart),
- new JavaSearchActionGroup(fPart),
- fProjectActionGroup= new ProjectActionGroup(fPart),
- fViewActionGroup= new ViewActionGroup(fPart.getRootMode(), workingSetListener, site),
- fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer),
- new LayoutActionGroup(fPart)
- });
-
-
- fViewActionGroup.fillFilters(viewer);
-
- PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
- fFrameList= new FrameList(frameSource);
- frameSource.connectTo(fFrameList);
-
- fZoomInAction= new GoIntoAction(fFrameList);
- fBackAction= new BackAction(fFrameList);
- fForwardAction= new ForwardAction(fFrameList);
- fUpAction= new UpAction(fFrameList);
-
- fGotoTypeAction= new GotoTypeAction(fPart);
- fGotoPackageAction= new GotoPackageAction(fPart);
- fGotoResourceAction= new GotoResourceAction(fPart);
- fCollapseAllAction= new CollapseAllAction(fPart);
- fToggleLinkingAction = new ToggleLinkingAction(fPart);
- fGotoRequiredProjectAction= new GotoRequiredProjectAction(fPart);
- fSelectAllAction= new SelectAllAction(fPart.getTreeViewer());
- }
-
- public void dispose() {
- super.dispose();
- }
-
-
- //---- Persistent state -----------------------------------------------------------------------
-
- /* package */ void restoreFilterAndSorterState(IMemento memento) {
- fViewActionGroup.restoreState(memento);
- fCustomFiltersActionGroup.restoreState(memento);
- }
-
- /* package */ void saveFilterAndSorterState(IMemento memento) {
- fViewActionGroup.saveState(memento);
- fCustomFiltersActionGroup.saveState(memento);
- }
-
- //---- Action Bars ----------------------------------------------------------------------------
-
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- setGlobalActionHandlers(actionBars);
- fillToolBar(actionBars.getToolBarManager());
- fillViewMenu(actionBars.getMenuManager());
- }
-
- /* package */ void updateActionBars(IActionBars actionBars) {
- actionBars.getToolBarManager().removeAll();
- actionBars.getMenuManager().removeAll();
- fillActionBars(actionBars);
- actionBars.updateActionBars();
- fZoomInAction.setEnabled(true);
- }
-
- private void setGlobalActionHandlers(IActionBars actionBars) {
- // Navigate Go Into and Go To actions.
- actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
- actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction);
- actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction);
- actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
- actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
-
- fRefactorActionGroup.retargetFileMenuActions(actionBars);
- }
-
- /* package */ void fillToolBar(IToolBarManager toolBar) {
- toolBar.add(fBackAction);
- toolBar.add(fForwardAction);
- toolBar.add(fUpAction);
-
- toolBar.add(new Separator());
- toolBar.add(fCollapseAllAction);
- toolBar.add(fToggleLinkingAction);
-
- }
-
- /* package */ void fillViewMenu(IMenuManager menu) {
- menu.add(new Separator());
- menu.add(fToggleLinkingAction);
- menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
- menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
- }
-
- //---- Context menu -------------------------------------------------------------------------
-
- public void fillContextMenu(IMenuManager menu) {
- IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
- int size= selection.size();
- Object element= selection.getFirstElement();
-
- if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper)
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fGotoRequiredProjectAction);
-
- addGotoMenu(menu, element, size);
-
- addOpenNewWindowAction(menu, element);
-
- super.fillContextMenu(menu);
- }
-
- private void addGotoMenu(IMenuManager menu, Object element, int size) {
- boolean enabled= size == 1 && fPart.getTreeViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer);
- fZoomInAction.setEnabled(enabled);
- if (enabled)
- menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
- }
-
- private boolean isGoIntoTarget(Object element) {
- if (element == null)
- return false;
- if (element instanceof IJavaScriptElement) {
- int type= ((IJavaScriptElement)element).getElementType();
- return type == IJavaScriptElement.JAVASCRIPT_PROJECT ||
- type == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT ||
- type == IJavaScriptElement.PACKAGE_FRAGMENT;
- }
- if (element instanceof IWorkingSet) {
- return true;
- }
- return false;
- }
-
- private void addOpenNewWindowAction(IMenuManager menu, Object element) {
- if (element instanceof IJavaScriptElement) {
- element= ((IJavaScriptElement)element).getResource();
-
- }
- // fix for 64890 Package explorer out of sync when open/closing projects [package explorer] 64890
- if (element instanceof IProject && !((IProject)element).isOpen())
- return;
-
- if (!(element instanceof IContainer))
- return;
- menu.appendToGroup(
- IContextMenuConstants.GROUP_OPEN,
- new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
- }
-
- //---- Key board and mouse handling ------------------------------------------------------------
-
- /* package*/ void handleDoubleClick(DoubleClickEvent event) {
- TreeViewer viewer= fPart.getTreeViewer();
- IStructuredSelection selection= (IStructuredSelection)event.getSelection();
- Object element= selection.getFirstElement();
- if (viewer.isExpandable(element)) {
- if (doubleClickGoesInto()) {
- // don't zoom into compilation units and class files
- if (element instanceof IJavaScriptUnit || element instanceof IClassFile)
- return;
- if (element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet) {
- fZoomInAction.run();
- }
- } else {
- IAction openAction= fNavigateActionGroup.getOpenAction();
- if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
- return;
- if (selection instanceof ITreeSelection) {
- TreePath[] paths= ((ITreeSelection)selection).getPathsFor(element);
- for (int i= 0; i < paths.length; i++) {
- viewer.setExpandedState(paths[i], !viewer.getExpandedState(paths[i]));
- }
- } else {
- viewer.setExpandedState(element, !viewer.getExpandedState(element));
- }
- }
- } else if (element instanceof IProject && !((IProject) element).isOpen()) {
- OpenProjectAction openProjectAction= fProjectActionGroup.getOpenProjectAction();
- if (openProjectAction.isEnabled()) {
- openProjectAction.run();
- }
- }
- }
-
- /* package */ void handleOpen(OpenEvent event) {
- IAction openAction= fNavigateActionGroup.getOpenAction();
- if (openAction != null && openAction.isEnabled()) {
- openAction.run();
- return;
- }
- }
-
- /* package */ void handleKeyEvent(KeyEvent event) {
- if (event.stateMask != 0)
- return;
-
- if (event.keyCode == SWT.BS) {
- if (fUpAction != null && fUpAction.isEnabled()) {
- fUpAction.run();
- event.doit= false;
- }
- }
- }
-
- private void doWorkingSetChanged(PropertyChangeEvent event) {
- if (ViewActionGroup.MODE_CHANGED.equals(event.getProperty())) {
- fPart.rootModeChanged(((Integer)event.getNewValue()).intValue());
- Object oldInput= null;
- Object newInput= null;
- if (fPart.showProjects()) {
- oldInput= fPart.getWorkingSetModel();
- newInput= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- } else if (fPart.showWorkingSets()) {
- oldInput= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- newInput= fPart.getWorkingSetModel();
- }
- if (oldInput != null && newInput != null) {
- Frame frame;
- for (int i= 0; (frame= fFrameList.getFrame(i)) != null; i++) {
- if (frame instanceof TreeFrame) {
- TreeFrame treeFrame= (TreeFrame)frame;
- if (oldInput.equals(treeFrame.getInput()))
- treeFrame.setInput(newInput);
- }
- }
- }
- } else {
- IWorkingSet workingSet= (IWorkingSet) event.getNewValue();
-
- String workingSetLabel= null;
- if (workingSet != null)
- workingSetLabel= workingSet.getLabel();
- fPart.setWorkingSetLabel(workingSetLabel);
- fPart.updateTitle();
-
- String property= event.getProperty();
- if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- TreeViewer viewer= fPart.getTreeViewer();
- viewer.getControl().setRedraw(false);
- viewer.refresh();
- viewer.getControl().setRedraw(true);
- }
- }
- }
-
- private boolean doubleClickGoesInto() {
- return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
- }
-
- public FrameAction getUpAction() {
- return fUpAction;
- }
-
- public FrameAction getBackAction() {
- return fBackAction;
- }
- public FrameAction getForwardAction() {
- return fForwardAction;
- }
-
- public ViewActionGroup getWorkingSetActionGroup() {
- return fViewActionGroup;
- }
-
- public CustomFiltersActionGroup getCustomFilterActionGroup() {
- return fCustomFiltersActionGroup;
- }
-
- public FrameList getFrameList() {
- return fFrameList;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java
deleted file mode 100644
index 9b40640e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java
+++ /dev/null
@@ -1,1533 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.IBasicPropertyConstants;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.navigator.ContainerFolder;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.ProjectLibraryRoot;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-/**
- * Content provider for the PackageExplorer.
- *
- * <p>
- * Since 2.1 this content provider can provide the children for flat or hierarchical
- * layout.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider
- */
-public class PackageExplorerContentProvider extends StandardJavaScriptElementContentProvider implements ITreeContentProvider, IElementChangedListener, IPropertyChangeListener {
-
- protected static final int ORIGINAL= 0;
- protected static final int PARENT= 1 << 0;
- protected static final int GRANT_PARENT= 1 << 1;
- protected static final int PROJECT= 1 << 2;
-
- private TreeViewer fViewer;
- private Object fInput;
- private boolean fIsFlatLayout;
- private boolean fShowLibrariesNode;
- private boolean fFoldPackages;
-
- private Collection fPendingUpdates;
-
- private UIJob fUpdateJob;
-
- /**
- * Creates a new content provider for Java elements.
- * @param provideMembers if set, members of compilation units and class files are shown
- */
- public PackageExplorerContentProvider(boolean provideMembers) {
- super(provideMembers);
- fShowLibrariesNode= false;
- fIsFlatLayout= false;
- fFoldPackages= arePackagesFoldedInHierarchicalLayout();
- fPendingUpdates= null;
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
-
- fUpdateJob= null;
- }
-
- private boolean arePackagesFoldedInHierarchicalLayout(){
- return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER);
- }
-
- protected Object getViewerInput() {
- return fInput;
- }
-
- /* (non-Javadoc)
- * Method declared on IElementChangedListener.
- */
- public void elementChanged(final ElementChangedEvent event) {
- final ArrayList runnables= new ArrayList();
- try {
- // 58952 delete project does not update Package Explorer [package explorer]
- // if the input to the viewer is deleted then refresh to avoid the display of stale elements
- if (inputDeleted(runnables))
- return;
-
- processDelta(event.getDelta(), runnables);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- } finally {
- executeRunnables(runnables);
- }
- }
-
- protected final void executeRunnables(final Collection runnables) {
-
- // now post all collected runnables
- final Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- //Are we in the UIThread? If so spin it until we are done
- if ((ctrl.getDisplay().getThread() == Thread.currentThread()) && !fViewer.isBusy()) {
- runUpdates(runnables);
- } else {
- synchronized (this) {
- if (fPendingUpdates == null) {
- fPendingUpdates= runnables;
- } else {
- fPendingUpdates.addAll(runnables);
- }
- }
- postAsyncUpdate(ctrl.getDisplay());
- }
- }
- }
-
- private void postAsyncUpdate(final Display display) {
- if (fUpdateJob == null) {
- fUpdateJob= new UIJob(display, PackagesMessages.PackageExplorerContentProvider_update_job_description) {
- public IStatus runInUIThread(IProgressMonitor monitor) {
- TreeViewer viewer= fViewer;
- if (viewer != null && viewer.isBusy()) {
- schedule(100); // reschedule when viewer is busy: bug 184991
- } else {
- runPendingUpdates();
- }
- return Status.OK_STATUS;
- }
- };
- fUpdateJob.setSystem(true);
- }
- fUpdateJob.schedule();
- }
-
- /**
- * Run all of the runnables that are the widget updates. Must be called in the display thread.
- */
- public void runPendingUpdates() {
- Collection pendingUpdates;
- synchronized (this) {
- pendingUpdates= fPendingUpdates;
- fPendingUpdates= null;
- }
- if (pendingUpdates != null && fViewer != null) {
- Control control = fViewer.getControl();
- if (control != null && !control.isDisposed()) {
- runUpdates(pendingUpdates);
- }
- }
- }
-
- private void runUpdates(Collection runnables) {
- Iterator runnableIterator = runnables.iterator();
- while (runnableIterator.hasNext()){
- ((Runnable) runnableIterator.next()).run();
- }
- }
-
-
- private boolean inputDeleted(Collection runnables) {
- if (fInput == null)
- return false;
- if ((fInput instanceof IJavaScriptElement) && ((IJavaScriptElement) fInput).exists())
- return false;
- if ((fInput instanceof IResource) && ((IResource) fInput).exists())
- return false;
- if (fInput instanceof WorkingSetModel)
- return false;
- if (fInput instanceof IWorkingSet) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156239
- return false;
- postRefresh(fInput, ORIGINAL, fInput, runnables);
- return true;
- }
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void dispose() {
- super.dispose();
- JavaScriptCore.removeElementChangedListener(this);
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider#getPackageFragmentRootContent(org.eclipse.wst.jsdt.core.IPackageFragmentRoot)
- */
- protected Object[] getPackageFragmentRootContent(IPackageFragmentRoot root) throws JavaScriptModelException {
- if (fIsFlatLayout) {
- return super.getPackageFragmentRootContent(root);
- }
-
- // hierarchical package mode
- ArrayList result= new ArrayList();
- getHierarchicalPackageChildren(root, null, result);
- if (!isProjectPackageFragmentRoot(root)) {
- Object[] nonJavaResources= root.getNonJavaScriptResources();
- for (int i= 0; i < nonJavaResources.length; i++) {
- result.add(nonJavaResources[i]);
- }
- }
- return result.toArray();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider#getPackageContent(org.eclipse.wst.jsdt.core.IPackageFragment)
- */
- protected Object[] getPackageContent(IPackageFragment fragment) throws JavaScriptModelException {
- if (fIsFlatLayout) {
- return super.getPackageContent(fragment);
- }
-
- // hierarchical package mode
- ArrayList result= new ArrayList();
-
- getHierarchicalPackageChildren((IPackageFragmentRoot) fragment.getParent(), fragment, result);
- Object[] nonPackages= super.getPackageContent(fragment);
- if (result.isEmpty())
- return nonPackages;
- for (int i= 0; i < nonPackages.length; i++) {
- result.add(nonPackages[i]);
- }
- return result.toArray();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider#getFolderContent(org.eclipse.core.resources.IFolder)
- */
- protected Object[] getFolderContent(IFolder folder) throws CoreException {
- if (fIsFlatLayout) {
- return super.getFolderContent(folder);
- }
-
- // hierarchical package mode
- ArrayList result= new ArrayList();
-
- getHierarchicalPackagesInFolder(folder, result);
- Object[] others= super.getFolderContent(folder);
- if (result.isEmpty())
- return others;
- for (int i= 0; i < others.length; i++) {
- result.add(others[i]);
- }
- return result.toArray();
- }
-
-
- public Object[] getChildren(Object parentElement) {
- try {
- if (parentElement instanceof IJavaScriptModel)
- return concatenate(getJavaProjects((IJavaScriptModel)parentElement), getNonJavaProjects((IJavaScriptModel)parentElement));
-
- if(parentElement instanceof ContainerFolder) {
- return getContainerPackageFragmentRoots((PackageFragmentRootContainer)((ContainerFolder)parentElement).getParentObject());
- }
- if (parentElement instanceof PackageFragmentRootContainer)
- return getContainerPackageFragmentRoots((PackageFragmentRootContainer)parentElement, fIsFlatLayout, null);
- else if (parentElement instanceof NamespaceGroup && ((NamespaceGroup) parentElement).getPackageFragmentRootContainer() != null) {
- return getContainerPackageFragmentRoots(((NamespaceGroup) parentElement).getPackageFragmentRootContainer(), true, ((NamespaceGroup) parentElement));
- }
-
- if(parentElement instanceof ProjectLibraryRoot) {
-// return ((ProjectLibraryRoot)parentElement).getChildren();
- // Include source folders (and also scour their model contents)
- Object[] children1 = ((ProjectLibraryRoot) parentElement).getChildren();
- List sourceRoots = new ArrayList();
- try {
- IPackageFragmentRoot[] packageFragmentRoots = ((ProjectLibraryRoot) parentElement).getProject().getPackageFragmentRoots();
- for (int i = 0; i < packageFragmentRoots.length; i++) {
- IIncludePathEntry entry = packageFragmentRoots[i].getRawIncludepathEntry();
- if (IIncludePathEntry.CPE_SOURCE == entry.getEntryKind()) {
- boolean hidden = false;
- IIncludePathAttribute[] attribs = entry.getExtraAttributes();
- for (int k = 0; !hidden && attribs != null && k < attribs.length; k++) {
- hidden |= (attribs[k] == IIncludePathAttribute.HIDE);
- }
- if (!hidden) {
- sourceRoots.add(packageFragmentRoots[i]);
- }
- }
- }
- }
- catch (JavaScriptModelException e) {
- e.printStackTrace();
- }
- Object[] combined = new Object[children1.length + sourceRoots.size()];
- System.arraycopy(children1, 0, combined, 0, children1.length);
- if (!sourceRoots.isEmpty()) {
- System.arraycopy(sourceRoots.toArray(), 0, combined, children1.length, sourceRoots.size());
- }
- return combined;
- }
-// if (parentElement instanceof IPackageFragmentRoot) {
-// Object[] children = super.getChildren(parentElement);
-// for (int i = 0; i < children.length; i++) {
-// // replace the "default package" with its contents
-// if (children[i] instanceof IPackageFragment && ((IPackageFragment) children[i]).isDefaultPackage()) {
-// List combined = new ArrayList(children.length);
-// for (int j = 0; j < children.length; j++) {
-// if (j != i) {
-// combined.add(children[j]);
-// }
-// else {
-// Object[] defaultChildren = super.getChildren(children[j]);
-// for (int k = 0; k < defaultChildren.length; k++) {
-// combined.add(defaultChildren[k]);
-// }
-// }
-// }
-// return combined.toArray();
-// }
-// }
-// return children;
-// }
- if (parentElement instanceof IProject) {
- IProject project= (IProject) parentElement;
- if (project.isAccessible())
- return project.members();
- return NO_CHILDREN;
- }
- if (parentElement instanceof IPackageFragmentRoot && ((IPackageFragmentRoot)parentElement).isVirtual()) {
- return getLibraryChildren((IPackageFragmentRoot)parentElement, fIsFlatLayout, null);
- }
- else if (parentElement instanceof NamespaceGroup && ((NamespaceGroup) parentElement).getPackageFragmentRoot() != null && ((NamespaceGroup) parentElement).getPackageFragmentRoot().isVirtual()) {
- return getLibraryChildren(((NamespaceGroup) parentElement).getPackageFragmentRoot(), true, ((NamespaceGroup) parentElement));
- }
- else if(parentElement instanceof IPackageFragmentRoot && IIncludePathEntry.CPE_SOURCE == ((IPackageFragmentRoot) parentElement).getRawIncludepathEntry().getEntryKind()) {
- return getSourceChildren(parentElement, fIsFlatLayout, null);
- }
- else if (parentElement instanceof NamespaceGroup && ((NamespaceGroup) parentElement).getPackageFragmentRoot() != null && IIncludePathEntry.CPE_SOURCE == ((NamespaceGroup) parentElement).getPackageFragmentRoot().getRawIncludepathEntry().getEntryKind()) {
- return getSourceChildren(((NamespaceGroup) parentElement).getPackageFragmentRoot(), true, ((NamespaceGroup) parentElement));
- }
- // if script unit
- else if (parentElement instanceof IJavaScriptUnit) {
- return getSourceChildren(parentElement, fIsFlatLayout, null);
- }
- // if group with script unit as parent
- else if(parentElement instanceof NamespaceGroup && ((NamespaceGroup) parentElement).getJavaScriptUnit() != null) {
- return getSourceChildren(((NamespaceGroup) parentElement).getJavaScriptUnit(), true, ((NamespaceGroup) parentElement));
- }
- return super.getChildren(parentElement);
- } catch (JavaScriptModelException e) {
- //ignore, caused by trying to get children of files in libraries
- return NO_CHILDREN;
- } catch (CoreException e) {
- e.printStackTrace();
- return NO_CHILDREN;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider#hasChildren(java.lang.Object)
- */
- public boolean hasChildren(Object element) {
- if (element instanceof JsGlobalScopeContainer) {
- return ((JsGlobalScopeContainer) element).hasChildren();
- }
- if (element instanceof ProjectLibraryRoot) {
- return ((ProjectLibraryRoot) element).hasChildren();
- }
- return super.hasChildren(element);
- }
-
- private Object[] getSourceChildren(Object parentElement, boolean neverGroup, NamespaceGroup onlyGroup) throws JavaScriptModelException {
- /* if the parent is a fragment root use its children
- * else if parent element is a script unit, use it as the child
- */
- Object[] rawChildren = new Object[0];
- if(parentElement instanceof IPackageFragmentRoot) {
- rawChildren = ((IParent) parentElement).getChildren();
- } else if(parentElement instanceof IJavaScriptUnit) {
- rawChildren = new Object[] { parentElement };
- }
-
- if (rawChildren == null)
- return new Object[0];
-
- ArrayList allChildren = new ArrayList();
- ArrayList expanded = new ArrayList();
- expanded.addAll(Arrays.asList(rawChildren));
-
- if (expanded.isEmpty())
- return new Object[0];
-
- Object next = expanded.remove(0);
- Map groups = new HashMap();
-
- while (next != null) {
- if (next instanceof IPackageFragment) {
- expanded.addAll(Arrays.asList(((IPackageFragment) next).getChildren()));
- }
- else if (next instanceof IPackageFragmentRoot) {
- expanded.addAll(Arrays.asList(((IPackageFragmentRoot) next).getChildren()));
- }
- else if (next instanceof IClassFile || next instanceof IJavaScriptUnit) {
- IJavaScriptElement[] filtered = filter(((IParent) next).getChildren());
- List newChildren = Arrays.asList(filtered);
- allChildren.removeAll(newChildren);
- if (fIsFlatLayout || neverGroup) {
- if (onlyGroup == null) {
- allChildren.addAll(newChildren);
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupNamesEnd = displayName.lastIndexOf('.');
- if (groupNamesEnd == onlyGroup.fNamePrefixLength && displayName.startsWith(onlyGroup.fNamePrefix)) {
- allChildren.add(filtered[j]);
- }
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupEnd = displayName.lastIndexOf('.');
- if (groupEnd > 0) {
- String groupName = displayName.substring(0, groupEnd);
- if (!groups.containsKey(groupName)) {
- // create the group based on the parent type
- NamespaceGroup group = null;
- if(parentElement instanceof IPackageFragmentRoot) {
- group = new NamespaceGroup((IPackageFragmentRoot) parentElement, groupName);
- } else if(parentElement instanceof IJavaScriptUnit) {
- group = new NamespaceGroup((IJavaScriptUnit) parentElement, groupName);
- }
-
- if(group != null) {
- groups.put(groupName, group);
- allChildren.add(group);
- }
- }
- }
- else {
- allChildren.add(filtered[j]);
- }
-
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
-
- if (expanded.size() > 0)
- next = expanded.remove(0);
- else
- next = null;
-
- }
-
- return allChildren.toArray();
- }
-
-
- private Object[] getLibraryChildren(IPackageFragmentRoot container, boolean neverGroup, NamespaceGroup onlyGroup) {
- Object[] children=null;
- try {
- children = container.getChildren();
- } catch (JavaScriptModelException ex1) {
- ex1.printStackTrace();
- }
- if(children==null) return null;
- ArrayList allChildren = new ArrayList();
-
- Map groups = null;
- if (!fIsFlatLayout) {
- groups = new HashMap();
- }
-
- boolean unique = false;
- try {
- while(!unique && children!=null && children.length>0) {
- for(int i = 0;i<children.length;i++) {
- String display1 = ((IJavaScriptElement)children[0]).getDisplayName();
- String display2 = ((IJavaScriptElement)children[i]).getDisplayName();
- if(!( (display1==display2) || (display1!=null && display1.compareTo(display2)==0))){
- allChildren.addAll(Arrays.asList(children));
- unique=true;
- break;
- }
- }
- List more = new ArrayList();
- for(int i = 0;!unique && i<children.length;i++) {
- if(children[i] instanceof IPackageFragment) {
- more.addAll(Arrays.asList(((IPackageFragment)children[i]).getChildren()));
- }else if(children[i] instanceof IPackageFragmentRoot) {
- more.addAll(Arrays.asList(((IPackageFragmentRoot)children[i]).getChildren()));
- }else if(children[i] instanceof IClassFile || children[i] instanceof IJavaScriptUnit) {
- IJavaScriptElement[] filtered = filter(((IParent) children[i]).getChildren());
- List newChildren = Arrays.asList(filtered);
- allChildren.removeAll(newChildren);
- if (fIsFlatLayout || neverGroup) {
- if (onlyGroup == null) {
- allChildren.addAll(newChildren);
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupNamesEnd = displayName.lastIndexOf('.');
- if (groupNamesEnd == onlyGroup.fNamePrefixLength && displayName.startsWith(onlyGroup.fNamePrefix)) {
- allChildren.add(filtered[j]);
- }
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupEnd = displayName.lastIndexOf('.');
- if (groupEnd > 0) {
- String groupName = displayName.substring(0, groupEnd);
- if (!groups.containsKey(groupName)) {
- NamespaceGroup group = new NamespaceGroup(container, groupName);
- groups.put(groupName, group);
- allChildren.add(group);
- }
- }
- else {
- allChildren.add(filtered[j]);
- }
-
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
- else {
- /* bottomed out, now at javaScriptElement level */
- unique=true;
- break;
- }
-
- }
- if(!unique) children = more.toArray();
- }
- } catch (JavaScriptModelException ex) {
- ex.printStackTrace();
- }
-
- return allChildren.toArray();
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider#getPackageFragmentRoots(org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- protected Object[] getPackageFragmentRoots(IJavaScriptProject project) throws JavaScriptModelException {
- if (!project.getProject().isOpen())
- return NO_CHILDREN;
-
- List result= new ArrayList();
-
- boolean addJARContainer= false;
- ArrayList projectPackageFragmentRoots = new ArrayList();
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- IIncludePathEntry classpathEntry= root.getRawIncludepathEntry();
-
- IIncludePathAttribute[] attribs = classpathEntry.getExtraAttributes();
- boolean shouldHide = false;
- for(int p = 0;p<attribs.length;p++){
- if(attribs[p]==IIncludePathAttribute.HIDE) shouldHide = true;
- }
-
- int entryKind= classpathEntry.getEntryKind();
- if (entryKind == IIncludePathEntry.CPE_CONTAINER) {
- // all JsGlobalScopeContainers are added later
- } else if (fShowLibrariesNode && (entryKind != IIncludePathEntry.CPE_SOURCE) && entryKind!=IIncludePathEntry.CPE_CONTAINER) {
- addJARContainer= true;
- projectPackageFragmentRoots.add(root);
- } else {
- if (isProjectPackageFragmentRoot(root)) {
- // filter out package fragments that correspond to projects and
- // replace them with the package fragments directly
-// Object[] fragments= getPackageFragmentRootContent(root);
-// for (int j= 0; j < fragments.length; j++) {
-// result.add(fragments[j]);
-// }
- } /*else if(!shouldHide){
- result.add(root);
- }*/
- }
- }
-
- if (addJARContainer) {
- projectPackageFragmentRoots.add(new LibraryContainer(project));
- }
-
- // separate loop to make sure all containers are on the classpath
- IIncludePathEntry[] rawClasspath= project.getRawIncludepath();
- for (int i= 0; i < rawClasspath.length; i++) {
- IIncludePathEntry classpathEntry= rawClasspath[i];
- if (classpathEntry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- projectPackageFragmentRoots.add(new JsGlobalScopeContainer(project, classpathEntry));
- }
- }
-// Object[] resources= project.getNonJavaScriptResources();
-// for (int i= 0; i < resources.length; i++) {
-// result.add(resources[i]);
-// }
- ProjectLibraryRoot projectLibs = new ProjectLibraryRoot(project);
- result.add(0,projectLibs);
- return result.toArray();
- }
-
- public Object getParent(Object element) {
- if (element instanceof NamespaceGroup) {
- return ((NamespaceGroup)element).getParent();
- }
- if (element instanceof IPackageFragmentRoot) {
- IJavaScriptProject project = (IJavaScriptProject) ((IPackageFragmentRoot) element).getAncestor(IJavaScriptElement.JAVASCRIPT_PROJECT);
- if (project != null) {
- return new ProjectLibraryRoot(project);
- }
- }
- return super.getParent(element);
- }
-
-// private Object[] getContainerPackageFragmentRoots3(PackageFragmentRootContainer container) {
-// Object[] children = container.getChildren();
-// if(children==null) return null;
-// ArrayList allChildren = new ArrayList();
-// for(int i=0;i<children.length;i++) {
-// try {
-// allChildren.addAll(Arrays.asList(((IPackageFragmentRoot)children[i]).getChildren()));
-// } catch (JavaScriptModelException ex) {
-//
-// }
-// }
-// return allChildren.toArray();
-// }
-//
- private Object[] getContainerPackageFragmentRoots(PackageFragmentRootContainer container) {
- return getContainerPackageFragmentRoots(container, false, null);
- }
- private Object[] getContainerPackageFragmentRoots(PackageFragmentRootContainer container, boolean neverGroup, NamespaceGroup onlyGroup) {
-
- Object[] children = container.getChildren();
- if(children==null) return new Object[0];
-
- ArrayList allChildren = new ArrayList();
- ArrayList expanded = new ArrayList();
- expanded.addAll(Arrays.asList(children));
-
-
- if(expanded.isEmpty()) return new Object[0];
-
- Map groups = null;
- if (!fIsFlatLayout) {
- groups = new HashMap();
- }
-
- Object next = expanded.remove(0);
-
- while(next!=null) {
- try {
- if(next instanceof IPackageFragment) {
- expanded.addAll(Arrays.asList(((IPackageFragment)next).getChildren()));
- }else if(next instanceof IPackageFragmentRoot) {
- expanded.addAll(Arrays.asList(((IPackageFragmentRoot)next).getChildren()));
- }else if(next instanceof IClassFile || next instanceof IJavaScriptUnit) {
- IJavaScriptElement[] filtered = filter(((IParent) next).getChildren());
- List newChildren = Arrays.asList(filtered);
- allChildren.removeAll(newChildren);
- if (fIsFlatLayout || neverGroup) {
- if (onlyGroup == null) {
- allChildren.addAll(newChildren);
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupNamesEnd = displayName.lastIndexOf('.');
- if (groupNamesEnd == onlyGroup.fNamePrefixLength && displayName.startsWith(onlyGroup.fNamePrefix)) {
- allChildren.add(filtered[j]);
- }
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
- else {
- for (int j = 0; j < filtered.length; j++) {
- switch(filtered[j].getElementType()) {
- case IJavaScriptElement.TYPE :
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.METHOD :
- case IJavaScriptElement.INITIALIZER :
- case IJavaScriptElement.LOCAL_VARIABLE : {
- String displayName = filtered[j].getDisplayName();
- int groupEnd = displayName.lastIndexOf('.');
- if (groupEnd > 0) {
- String groupName = displayName.substring(0, groupEnd);
- if (!groups.containsKey(groupName)) {
- NamespaceGroup group = new NamespaceGroup(container, groupName);
- groups.put(groupName, group);
- allChildren.add(group);
- }
- }
- else {
- allChildren.add(filtered[j]);
- }
-
- break;
- }
- default : {
- allChildren.add(filtered[j]);
- }
- }
- }
- }
- }
- else {
- allChildren.add(next);
- }
- } catch (JavaScriptModelException ex) {
- ex.printStackTrace();
- }
-
- if(expanded.size()>0)
- next = expanded.remove(0);
- else
- next = null;
-
- }
-
- return allChildren.toArray();
-
-
-
- }
- private Object[] getContainerPackageFragmentRootsDeprc(PackageFragmentRootContainer container, boolean createFolder) {
-
-
- if(container!=null) {
-
- Object[] children = container.getChildren();
- if(children==null) return null;
- ArrayList allChildren = new ArrayList();
-
- boolean unique = false;
-
- while(!unique && children!=null && children.length>0) {
- String display1=null;
- for(int i = 0;i<children.length;i++) {
- display1 = ((IJavaScriptElement)children[0]).getDisplayName();
- String display2 = ((IJavaScriptElement)children[i]).getDisplayName();
- if(!( (display1==display2) || (display1!=null && display1.compareTo(display2)==0))){
- allChildren.addAll(Arrays.asList(children));
- unique=true;
- break;
- }
- }
- if(!unique && createFolder) {
- ContainerFolder folder = new ContainerFolder(display1, container);
- return new Object[] {folder};
- }
- ArrayList more = new ArrayList();
- for(int i = 0;!unique && i<children.length;i++) {
-
- try {
- if(children[i] instanceof IPackageFragment) {
- more.addAll(Arrays.asList(((IPackageFragment)children[i]).getChildren()));
- }else if(children[i] instanceof IPackageFragmentRoot) {
- more.addAll(Arrays.asList(((IPackageFragmentRoot)children[i]).getChildren()));
- }else if(children[i] instanceof IClassFile) {
- more.addAll(Arrays.asList( filter(((IClassFile)children[i]).getChildren())) );
- }else if(children[i] instanceof IJavaScriptUnit) {
- more.addAll(Arrays.asList( filter(((IJavaScriptUnit)children[i]).getChildren())) );
- }else {
- /* bottomed out, now at javaElement level */
- unique=true;
- break;
- }
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- ex.printStackTrace();
- }
-
- }
- if(!unique) children = more.toArray();
- }
-
-
-
- return allChildren.toArray();
- }else {
-
-
- Object[] children = container.getChildren();
- if(children==null) return null;
- ArrayList allChildren = new ArrayList();
- for(int i=0;i<children.length;i++) {
- try {
- allChildren.addAll(Arrays.asList(((IPackageFragmentRoot)children[i]).getChildren()));
- } catch (JavaScriptModelException ex) {
-
- }
- }
- return allChildren.toArray();
- }
- }
-
- private Object[] getNonJavaProjects(IJavaScriptModel model) throws JavaScriptModelException {
- return model.getNonJavaScriptResources();
- }
-
- protected Object internalGetParent(Object element) {
- if (!fIsFlatLayout && element instanceof IPackageFragment) {
- return getHierarchicalPackageParent((IPackageFragment) element);
- } else if (element instanceof IPackageFragmentRoot) {
- // since we insert logical package containers we have to fix
- // up the parent for package fragment roots so that they refer
- // to the container and containers refer to the project
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
-
- try {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- int entryKind= entry.getEntryKind();
- if (entryKind == IIncludePathEntry.CPE_CONTAINER) {
- return new JsGlobalScopeContainer(root.getJavaScriptProject(), entry);
- } else if (fShowLibrariesNode && (entryKind == IIncludePathEntry.CPE_LIBRARY || entryKind == IIncludePathEntry.CPE_VARIABLE)) {
- return new LibraryContainer(root.getJavaScriptProject());
- }
- } catch (JavaScriptModelException e) {
- // fall through
- }
- } else if (element instanceof PackageFragmentRootContainer) {
- return ((PackageFragmentRootContainer)element).getJavaProject();
- }
- return super.internalGetParent(element);
- }
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- super.inputChanged(viewer, oldInput, newInput);
- fViewer= (TreeViewer)viewer;
- if (oldInput == null && newInput != null) {
- JavaScriptCore.addElementChangedListener(this);
- } else if (oldInput != null && newInput == null) {
- JavaScriptCore.removeElementChangedListener(this);
- }
- fInput= newInput;
- }
-
- // hierarchical packages
- /**
- * Returns the hierarchical packages inside a given fragment or root.
- * @param parent The parent package fragment root
- * @param fragment The package to get the children for or 'null' to get the children of the root.
- * @param result Collection where the resulting elements are added
- * @throws JavaScriptModelException
- */
- private void getHierarchicalPackageChildren(IPackageFragmentRoot parent, IPackageFragment fragment, Collection result) throws JavaScriptModelException {
- IJavaScriptElement[] children= parent.getChildren();
- String prefix= fragment != null ? fragment.getElementName() + '/' : ""; //$NON-NLS-1$
- if (prefix.length()==1)
- prefix=""; //$NON-NLS-1$
- int prefixLen= prefix.length();
- for (int i= 0; i < children.length; i++) {
- IPackageFragment curr= (IPackageFragment) children[i];
- if (fragment==null)
- {
- if (curr.isDefaultPackage())
- result.add(curr);
- }
- else
- {
- String name= curr.getElementName();
- if (name.startsWith(prefix) && name.length() > prefixLen && name.indexOf('/', prefixLen) == -1) {
- if (fFoldPackages) {
- curr= getFolded(children, curr);
- }
- result.add(curr);
- }
- }
-
- }
- }
-
- /**
- * Returns the hierarchical packages inside a given folder.
- * @param folder The parent folder
- * @param result Collection where the resulting elements are added
- * @throws CoreException thrown when elements could not be accessed
- */
- private void getHierarchicalPackagesInFolder(IFolder folder, Collection result) throws CoreException {
- IResource[] resources= folder.members();
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (resource instanceof IFolder) {
- IFolder curr= (IFolder) resource;
- IJavaScriptElement element= JavaScriptCore.create(curr);
- if (element instanceof IPackageFragment) {
- if (element.exists()) {
- if (fFoldPackages) {
- IPackageFragment fragment= (IPackageFragment) element;
- IPackageFragmentRoot root= (IPackageFragmentRoot) fragment.getParent();
- element= getFolded(root.getChildren(), fragment);
- }
- result.add(element);
- }
- }
- }
- }
- }
-
- public Object getHierarchicalPackageParent(IPackageFragment child) {
- String name= child.getElementName();
- IPackageFragmentRoot parent= (IPackageFragmentRoot) child.getParent();
- int index= name.lastIndexOf('/');
- if (index != -1) {
- String realParentName= name.substring(0, index);
- IPackageFragment element= parent.getPackageFragment(realParentName);
- if (element.exists()) {
- try {
- if (fFoldPackages && isEmpty(element) && findSinglePackageChild(element, parent.getChildren()) != null) {
- return getHierarchicalPackageParent(element);
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return element;
- } else { // bug 65240
- IResource resource= element.getResource();
- if (resource != null) {
- return resource;
- }
- }
- }
- if (parent.getResource() instanceof IProject) {
- return parent.getJavaScriptProject();
- }
- return parent;
- }
-
- private static IPackageFragment getFolded(IJavaScriptElement[] children, IPackageFragment pack) throws JavaScriptModelException {
- while (isEmpty(pack)) {
- IPackageFragment collapsed= findSinglePackageChild(pack, children);
- if (collapsed == null) {
- return pack;
- }
- pack= collapsed;
- }
- return pack;
- }
-
- private static boolean isEmpty(IPackageFragment fragment) throws JavaScriptModelException {
- return !fragment.containsJavaResources() && fragment.getNonJavaScriptResources().length == 0;
- }
-
- private static IPackageFragment findSinglePackageChild(IPackageFragment fragment, IJavaScriptElement[] children) {
- String prefix= fragment.getElementName() + '/';
- int prefixLen= prefix.length();
- IPackageFragment found= null;
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElement element= children[i];
- String name= element.getElementName();
- if (name.startsWith(prefix) && name.length() > prefixLen && name.indexOf('/', prefixLen) == -1) {
- if (found == null) {
- found= (IPackageFragment) element;
- } else {
- return null;
- }
- }
- }
- return found;
- }
-
- // ------ delta processing ------
-
- /**
- * Processes a delta recursively. When more than two children are affected the
- * tree is fully refreshed starting at this node.
- *
- * @param delta the delta to process
- * @param runnables the resulting view changes as runnables (type {@link Runnable})
- * @return true is returned if the conclusion is to refresh a parent of an element. In that case no siblings need
- * to be processed
- * @throws JavaScriptModelException thrown when the access to an element failed
- */
- private boolean processDelta(IJavaScriptElementDelta delta, Collection runnables) throws JavaScriptModelException {
-
- int kind= delta.getKind();
- int flags= delta.getFlags();
- IJavaScriptElement element= delta.getElement();
- int elementType= element.getElementType();
-
-
- if (elementType != IJavaScriptElement.JAVASCRIPT_MODEL && elementType != IJavaScriptElement.JAVASCRIPT_PROJECT) {
- IJavaScriptProject proj= element.getJavaScriptProject();
- if (proj == null || !proj.getProject().isOpen()) // TODO: Not needed if parent already did the 'open' check!
- return false;
- }
-
- if (!fIsFlatLayout && elementType == IJavaScriptElement.PACKAGE_FRAGMENT) {
- if (kind == IJavaScriptElementDelta.REMOVED) {
- final Object parent = getHierarchicalPackageParent((IPackageFragment) element);
- if (parent instanceof IPackageFragmentRoot) {
- postRemove(element, runnables);
- return false;
- } else {
- postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
- return true;
- }
- } else if (kind == IJavaScriptElementDelta.ADDED) {
- final Object parent = getHierarchicalPackageParent((IPackageFragment) element);
- if (parent instanceof IPackageFragmentRoot) {
- //postAdd(parent, element, runnables);
- return false;
- } else {
- postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
- return true;
- }
- }
- handleAffectedChildren(delta, element, runnables);
- return false;
- }
-
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- IJavaScriptUnit cu= (IJavaScriptUnit) element;
- if (!JavaModelUtil.isPrimary(cu)) {
- return false;
- }
-
- if (!getProvideMembers() && cu.isWorkingCopy() && kind == IJavaScriptElementDelta.CHANGED) {
- return false;
- }
-
- if ((kind == IJavaScriptElementDelta.CHANGED) /* && !isStructuralCUChange(flags)*/) {
- // XXX: Remove structure change optimization until ASTConvertor is ready
- if ((flags & IJavaScriptElementDelta.F_CONTENT) == 1)
- return false; // test moved ahead
- }
-
- if (!isOnClassPath(cu)) { // TODO: isOnClassPath expensive! Should be put after all cheap tests
- return false;
- }
-
- }
-
- if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- // handle open and closing of a project
- if ((flags & (IJavaScriptElementDelta.F_CLOSED | IJavaScriptElementDelta.F_OPENED)) != 0) {
- postRefresh(element, ORIGINAL, element, runnables);
- return false;
- }
- // if the raw class path has changed we refresh the entire project
- if ((flags & IJavaScriptElementDelta.F_INCLUDEPATH_CHANGED) != 0) {
- postRefresh(element, ORIGINAL, element, runnables);
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- postRefresh(((IJavaScriptProject)element).getProject(), ORIGINAL, ((IJavaScriptProject)element).getProject(), runnables);
- }
- return false;
- }
- // if added it could be that the corresponding IProject is already shown. Remove it first.
- // bug 184296
- if (kind == IJavaScriptElementDelta.ADDED) {
- //postRemove(element.getResource(), runnables);
- //postAdd(element.getParent(), element, runnables);
- return false;
- }
- }
-
- if (kind == IJavaScriptElementDelta.REMOVED) {
- Object parent= internalGetParent(element);
- if (element instanceof IPackageFragment) {
- // refresh package fragment root to allow filtering empty (parent) packages: bug 72923
- if (fViewer.testFindItem(parent) != null)
- postRefresh(parent, PARENT, element, runnables);
- return true;
- }
-
- postRemove(element, runnables);
- if (parent instanceof IPackageFragment)
- postUpdateIcon((IPackageFragment)parent, runnables);
- // we are filtering out empty subpackages, so we
- // a package becomes empty we remove it from the viewer.
- if (isPackageFragmentEmpty(element.getParent())) {
- if (fViewer.testFindItem(parent) != null)
- postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
- return true;
- }
- return false;
- }
-
- if (kind == IJavaScriptElementDelta.ADDED) {
- Object parent= internalGetParent(element);
- // we are filtering out empty subpackages, so we
- // have to handle additions to them specially.
- if (parent instanceof IPackageFragment) {
- Object grandparent= internalGetParent(parent);
- // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
- // avoid posting a refresh to an invisible parent
- if (parent.equals(fInput)) {
- postRefresh(parent, PARENT, element, runnables);
- } else {
- // refresh from grandparent if parent isn't visible yet
- if (fViewer.testFindItem(parent) == null)
- postRefresh(grandparent, GRANT_PARENT, element, runnables);
- else {
- postRefresh(parent, PARENT, element, runnables);
- }
- }
- return true;
- } else {
- //postAdd(parent, element, runnables);
- }
- }
-
- if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- if (kind == IJavaScriptElementDelta.CHANGED) {
- // isStructuralCUChange already performed above
- postRefresh(element, ORIGINAL, element, runnables);
- IResource underlyingResource = ((IJavaScriptUnit)element).getUnderlyingResource();
- if(underlyingResource != null) {
- postRefresh(underlyingResource, ORIGINAL, element, runnables);
- }
- if ((flags & IJavaScriptElementDelta.F_PRIMARY_RESOURCE) != 0) {
- IJavaScriptElement parent2 = element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (parent2 != null) {
- postRefresh(parent2, ORIGINAL, element, runnables);
- }
- }
- updateSelection(delta, runnables);
- }
- return false;
- }
- // no changes possible in class files
- if (elementType == IJavaScriptElement.CLASS_FILE)
- return false;
-
-
- if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT) {
- // the contents of an external JAR has changed
- if ((flags & IJavaScriptElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) {
- postRefresh(element, ORIGINAL, element, runnables);
- return false;
- }
- // the source attachment of a JAR has changed
- if ((flags & (IJavaScriptElementDelta.F_SOURCEATTACHED | IJavaScriptElementDelta.F_SOURCEDETACHED)) != 0)
- postUpdateIcon(element, runnables);
-
- if (isClassPathChange(delta)) {
- // throw the towel and do a full refresh of the affected java project.
- postRefresh(element.getJavaScriptProject(), PROJECT, element, runnables);
- return true;
- }
- }
- handleAffectedChildren(delta, element, runnables);
- return false;
- }
-
- private static boolean isStructuralCUChange(int flags) {
- // No refresh on working copy creation (F_PRIMARY_WORKING_COPY)
- return ((flags & IJavaScriptElementDelta.F_CHILDREN) != 0) || ((flags & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_FINE_GRAINED)) == IJavaScriptElementDelta.F_CONTENT);
- }
-
- /* package */ void handleAffectedChildren(IJavaScriptElementDelta delta, IJavaScriptElement element, Collection runnables) throws JavaScriptModelException {
- int count= 0;
-
- IResourceDelta[] resourceDeltas= delta.getResourceDeltas();
- if (resourceDeltas != null) {
- for (int i= 0; i < resourceDeltas.length; i++) {
- int kind= resourceDeltas[i].getKind();
- if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) {
- count++;
- }
- }
- }
- IJavaScriptElementDelta[] affectedChildren= delta.getAffectedChildren();
- for (int i= 0; i < affectedChildren.length; i++) {
- int kind= affectedChildren[i].getKind();
- if (kind == IJavaScriptElementDelta.ADDED || kind == IJavaScriptElementDelta.REMOVED) {
- count++;
- }
- }
-
- if (count > 1) {
- // more than one child changed, refresh from here downwards
- if (element instanceof IPackageFragment) {
- // a package fragment might become non empty refresh from the parent
- IJavaScriptElement parent= (IJavaScriptElement) internalGetParent(element);
- // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
- // avoid posting a refresh to an invisible parent
- if (element.equals(fInput)) {
- postRefresh(element, ORIGINAL, element, runnables);
- } else {
- postRefresh(parent, PARENT, element, runnables);
- }
- } else if (element instanceof IPackageFragmentRoot) {
- Object toRefresh= internalGetParent(element);
- postRefresh(toRefresh, ORIGINAL, toRefresh, runnables);
- } else {
- postRefresh(element, ORIGINAL, element, runnables);
- }
- return;
- }
- if (resourceDeltas != null) {
- for (int i= 0; i < resourceDeltas.length; i++) {
- if (processResourceDelta(resourceDeltas[i], element, runnables)) {
- return; // early return, element got refreshed
- }
- }
- }
- for (int i= 0; i < affectedChildren.length; i++) {
- if (processDelta(affectedChildren[i], runnables)) {
- return; // early return, element got refreshed
- }
- }
- }
-
- protected void processAffectedChildren(IJavaScriptElementDelta[] affectedChildren, Collection runnables) throws JavaScriptModelException {
- for (int i= 0; i < affectedChildren.length; i++) {
- processDelta(affectedChildren[i], runnables);
- }
- }
-
- private boolean isOnClassPath(IJavaScriptUnit element) {
- IJavaScriptProject project= element.getJavaScriptProject();
- if (project == null || !project.exists())
- return false;
- return project.isOnIncludepath(element);
- }
-
- /**
- * Updates the selection. It finds newly added elements
- * and selects them.
- * @param delta the delta to process
- * @param runnables the resulting view changes as runnables (type {@link Runnable})
- */
- private void updateSelection(IJavaScriptElementDelta delta, Collection runnables) {
- final IJavaScriptElement addedElement= findAddedElement(delta);
- if (addedElement != null) {
- final StructuredSelection selection= new StructuredSelection(addedElement);
- runnables.add(new Runnable() {
- public void run() {
- // 19431
- // if the item is already visible then select it
- if (fViewer.testFindItem(addedElement) != null)
- fViewer.setSelection(selection);
- }
- });
- }
- }
-
- private IJavaScriptElement findAddedElement(IJavaScriptElementDelta delta) {
- if (delta.getKind() == IJavaScriptElementDelta.ADDED)
- return delta.getElement();
-
- IJavaScriptElementDelta[] affectedChildren= delta.getAffectedChildren();
- for (int i= 0; i < affectedChildren.length; i++)
- return findAddedElement(affectedChildren[i]);
-
- return null;
- }
-
- /**
- * Updates the package icon
- * @param element the element to update
- * @param runnables the resulting view changes as runnables (type {@link Runnable})
- */
- private void postUpdateIcon(final IJavaScriptElement element, Collection runnables) {
- runnables.add(new Runnable() {
- public void run() {
- // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
- fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
- }
- });
- }
-
- /**
- * Process a resource delta.
- *
- * @param delta the delta to process
- * @param parent the parent
- * @param runnables the resulting view changes as runnables (type {@link Runnable})
- * @return true if the parent got refreshed
- */
- private boolean processResourceDelta(IResourceDelta delta, Object parent, Collection runnables) {
- int status= delta.getKind();
- int flags= delta.getFlags();
-
- IResource resource= delta.getResource();
- // filter out changes affecting the output folder
- if (resource == null)
- return false;
-
- // this could be optimized by handling all the added children in the parent
- if ((status & IResourceDelta.REMOVED) != 0) {
- if (parent instanceof IPackageFragment) {
- // refresh one level above to deal with empty package filtering properly
- postRefresh(internalGetParent(parent), PARENT, parent, runnables);
- return true;
- } else {
- postRemove(resource, runnables);
- return false;
- }
- }
- if ((status & IResourceDelta.ADDED) != 0) {
- if (parent instanceof IPackageFragment) {
- // refresh one level above to deal with empty package filtering properly
- postRefresh(internalGetParent(parent), PARENT, parent, runnables);
- return true;
- } else
- {
- //postAdd(parent, resource, runnables);
- return false;
- }
- }
- if ((status & IResourceDelta.CHANGED) != 0) {
- if ((flags & IResourceDelta.TYPE) != 0) {
- postRefresh(parent, PARENT, resource, runnables);
- return true;
- }
- }
- // open/close state change of a project
- if ((flags & IResourceDelta.OPEN) != 0) {
- postProjectStateChanged(internalGetParent(parent), runnables);
- return true;
- }
- IResourceDelta[] resourceDeltas= delta.getAffectedChildren();
-
- int count= 0;
- for (int i= 0; i < resourceDeltas.length; i++) {
- int kind= resourceDeltas[i].getKind();
- if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) {
- count++;
- if (count > 1) {
- postRefresh(parent, PARENT, resource, runnables);
- return true;
- }
- }
- }
- for (int i= 0; i < resourceDeltas.length; i++) {
- if (processResourceDelta(resourceDeltas[i], resource, runnables)) {
- return false; // early return, element got refreshed
- }
- }
- return false;
- }
-
- public void setIsFlatLayout(boolean state) {
- fIsFlatLayout= state;
- }
-
- public void setShowLibrariesNode(boolean state) {
- fShowLibrariesNode= state;
- }
-
- private void postRefresh(Object root, int relation, Object affectedElement, Collection runnables) {
- // JFace doesn't refresh when object isn't part of the viewer
- // Therefore move the refresh start down to the viewer's input
- if (isParent(root, fInput))
- root= fInput;
- List toRefresh= new ArrayList(1);
- toRefresh.add(root);
- augmentElementToRefresh(toRefresh, relation, affectedElement);
- postRefresh(toRefresh, true, runnables);
- }
-
- /**
- * Can be implemented by subclasses to add additional elements to refresh
- *
- * @param toRefresh the elements to refresh
- * @param relation the relation to the affected element ({@link #GRANT_PARENT}, {@link #PARENT}, {@link #ORIGINAL}, {@link #PROJECT})
- * @param affectedElement the affected element
- */
- protected void augmentElementToRefresh(List toRefresh, int relation, Object affectedElement) {
- }
-
- private boolean isParent(Object root, Object child) {
- Object parent= getParent(child);
- if (parent == null)
- return false;
- if (parent.equals(root))
- return true;
- return isParent(root, parent);
- }
-
- protected void postRefresh(final List toRefresh, final boolean updateLabels, Collection runnables) {
- runnables.add(new Runnable() {
- public void run() {
- for (Iterator iter= toRefresh.iterator(); iter.hasNext();) {
- fViewer.refresh(iter.next(), updateLabels);
- }
- }
- });
- }
-
-// protected void postAdd(final Object parent, final Object element, Collection runnables) {
-// runnables.add(new Runnable() {
-// public void run() {
-// Widget[] items= fViewer.testFindItems(element);
-// for (int i= 0; i < items.length; i++) {
-// Widget item= items[i];
-// if (item instanceof TreeItem && !item.isDisposed()) {
-// TreeItem parentItem= ((TreeItem) item).getParentItem();
-// if (parentItem != null && !parentItem.isDisposed() && parent.equals(parentItem.getData())) {
-// return; // no add, element already added (most likely by a refresh)
-// }
-// }
-// }
-// fViewer.add(parent, element);
-// }
-// });
-// }
-
- protected void postRemove(final Object element, Collection runnables) {
- runnables.add(new Runnable() {
- public void run() {
- fViewer.remove(element);
- }
- });
- }
-
- protected void postProjectStateChanged(final Object root, Collection runnables) {
- runnables.add(new Runnable() {
- public void run() {
- fViewer.refresh(root, true);
- // trigger a synthetic selection change so that action refresh their
- // enable state.
- fViewer.setSelection(fViewer.getSelection());
- }
- });
- }
-
-
- /*
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (arePackagesFoldedInHierarchicalLayout() != fFoldPackages){
- fFoldPackages= arePackagesFoldedInHierarchicalLayout();
- if (fViewer != null && !fViewer.getControl().isDisposed()) {
- fViewer.getControl().setRedraw(false);
- Object[] expandedObjects= fViewer.getExpandedElements();
- fViewer.refresh();
- fViewer.setExpandedElements(expandedObjects);
- fViewer.getControl().setRedraw(true);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java
deleted file mode 100644
index 9aeefebe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.ui.navigator.ContainerFolder;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Provides the labels for the Package Explorer.
- * <p>
- * It provides labels for the packages in hierarchical layout and in all
- * other cases delegates it to its super class.
- * </p>
- *
- */
-public class PackageExplorerLabelProvider extends AppearanceAwareLabelProvider {
-
- private PackageExplorerContentProvider fContentProvider;
- private Map fWorkingSetImages;
-
- private boolean fIsFlatLayout;
- private PackageExplorerProblemsDecorator fProblemDecorator;
-
- public PackageExplorerLabelProvider(PackageExplorerContentProvider cp) {
- super(DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED | JavaScriptElementLabels.ALL_CATEGORY, DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS);
-
- fProblemDecorator= new PackageExplorerProblemsDecorator();
- addLabelDecorator(fProblemDecorator);
- Assert.isNotNull(cp);
- fContentProvider= cp;
- fWorkingSetImages= null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- String text= getSpecificText(element);
- if (text != null) {
- return new ColoredString(decorateText(text, element));
- }
- return super.getRichTextLabel(element);
- }
-
- private String getSpecificText(Object element) {
- if (!fIsFlatLayout && element instanceof IPackageFragment) {
- IPackageFragment fragment = (IPackageFragment) element;
- Object parent= fContentProvider.getHierarchicalPackageParent(fragment);
- if (parent instanceof IPackageFragment) {
- return getNameDelta((IPackageFragment) parent, fragment);
- } else if (parent instanceof IFolder) { // bug 152735
- return getNameDelta((IFolder) parent, fragment);
- }
- } else if (element instanceof IWorkingSet) {
- return ((IWorkingSet) element).getLabel();
- }
- return null;
- }
-
- public String getText(Object element) {
- if(element instanceof ContainerFolder) {
- return ((ContainerFolder)element).toString();
- }
- String text= getSpecificText(element);
- if (text != null) {
- return decorateText(text, element);
- }
- text = super.getText(element);
- if(element instanceof IClassFile) {
- text = ((IClassFile)element).getPath().lastSegment();
- }else if (element instanceof IJavaScriptUnit) {
- text = ((IJavaScriptUnit)element).getPath().lastSegment();
- }
-
- return text;
-
- }
-
- private String getNameDelta(IPackageFragment parent, IPackageFragment fragment) {
- String prefix= parent.getElementName() + '/';
- String fullName= fragment.getElementName();
- if (fullName.startsWith(prefix)) {
- return fullName.substring(prefix.length());
- }
- return fullName;
- }
-
- public boolean isFlatLayout() {
- return fIsFlatLayout;
- }
-
- private String getNameDelta(IFolder parent, IPackageFragment fragment) {
- IPath prefix= parent.getFullPath();
- IPath fullPath= fragment.getPath();
- if (prefix.isPrefixOf(fullPath)) {
- StringBuffer buf= new StringBuffer();
- for (int i= prefix.segmentCount(); i < fullPath.segmentCount(); i++) {
- if (buf.length() > 0)
- buf.append('.');
- buf.append(fullPath.segment(i));
- }
- return buf.toString();
- }
- return fragment.getElementName();
- }
-
- public Image getImage(Object element) {
-
- if(element instanceof ContainerFolder) {
- return super.getImage(((ContainerFolder)element).getParentObject());
- }
-
- if (element instanceof IWorkingSet) {
- ImageDescriptor image= ((IWorkingSet)element).getImageDescriptor();
- if (fWorkingSetImages == null) {
- fWorkingSetImages= new HashMap();
- }
-
- Image result= (Image) fWorkingSetImages.get(image);
- if (result == null) {
- result= image.createImage();
- fWorkingSetImages.put(image, result);
- }
- return decorateImage(result, element);
- }
- return super.getImage(element);
- }
-
- public void setIsFlatLayout(boolean state) {
- fIsFlatLayout= state;
- fProblemDecorator.setIsFlatLayout(state);
- }
-
- public void dispose() {
- if (fWorkingSetImages != null) {
- for (Iterator iter= fWorkingSetImages.values().iterator(); iter.hasNext();) {
- ((Image)iter.next()).dispose();
- }
- }
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java
deleted file mode 100644
index 9f17153d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java
+++ /dev/null
@@ -1,1604 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.ITreeViewerListener;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeExpansionEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.XMLMemento;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.IShowInTarget;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.views.framelist.Frame;
-import org.eclipse.ui.views.framelist.FrameAction;
-import org.eclipse.ui.views.framelist.FrameList;
-import org.eclipse.ui.views.framelist.IFrameSource;
-import org.eclipse.ui.views.framelist.TreeFrame;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dnd.DelegatingDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.ResourceTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.FilterUpdater;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.ConfigureWorkingSetAction;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.ViewActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel;
-import org.eclipse.wst.jsdt.ui.IPackagesViewPart;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-import org.eclipse.wst.jsdt.ui.actions.CustomFiltersActionGroup;
-
-/**
- * The ViewPart for the ProjectExplorer. It listens to part activation events.
- * When selection linking with the editor is enabled the view selection tracks
- * the active editor page. Similarly when a resource is selected in the packages
- * view the corresponding editor is activated.
- */
-
-public class PackageExplorerPart extends ViewPart
- implements ISetSelectionTarget, IMenuListener,
- IShowInTarget,
- IPackagesViewPart, IPropertyChangeListener,
- IViewPartInputProvider {
-
- private static final String PERF_CREATE_PART_CONTROL= "org.eclipse.wst.jsdt.ui/perf/explorer/createPartControl"; //$NON-NLS-1$
- private static final String PERF_MAKE_ACTIONS= "org.eclipse.wst.jsdt.ui/perf/explorer/makeActions"; //$NON-NLS-1$
-
- private static final int HIERARCHICAL_LAYOUT= 0x1;
- private static final int FLAT_LAYOUT= 0x2;
-
- private final static String VIEW_ID= JavaScriptUI.ID_PACKAGES;
-
- // Persistence tags.
- private static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
- private static final String TAG_GROUP_LIBRARIES= "group_libraries"; //$NON-NLS-1$
- private static final String TAG_ROOT_MODE= "rootMode"; //$NON-NLS-1$
- private static final String TAG_LINK_EDITOR= "linkWithEditor"; //$NON-NLS-1$
- private static final String TAG_MEMENTO= "memento"; //$NON-NLS-1$
-
- private boolean fIsCurrentLayoutFlat = false; // true means flat, false means hierarchical
- private boolean fShowLibrariesNode;
- private boolean fLinkingEnabled;
-
- private int fRootMode;
- private WorkingSetModel fWorkingSetModel;
-
- private PackageExplorerLabelProvider fLabelProvider;
- private DecoratingJavaLabelProvider fDecoratingLabelProvider;
- private PackageExplorerContentProvider fContentProvider;
- private FilterUpdater fFilterUpdater;
-
- private PackageExplorerActionGroup fActionSet;
- private ProblemTreeViewer fViewer;
- private Menu fContextMenu;
-
- private IMemento fMemento;
-
- private ISelection fLastOpenSelection;
- private final ISelectionChangedListener fPostSelectionListener;
-
- private String fWorkingSetLabel;
- private IDialogSettings fDialogSettings;
-
-
- private IPartListener2 fLinkWithEditorListener= new IPartListener2() {
- public void partVisible(IWorkbenchPartReference partRef) {}
- public void partBroughtToTop(IWorkbenchPartReference partRef) {}
- public void partClosed(IWorkbenchPartReference partRef) {}
- public void partDeactivated(IWorkbenchPartReference partRef) {}
- public void partHidden(IWorkbenchPartReference partRef) {}
- public void partOpened(IWorkbenchPartReference partRef) {}
- public void partInputChanged(IWorkbenchPartReference partRef) {
- if (partRef instanceof IEditorReference) {
- editorActivated(((IEditorReference) partRef).getEditor(true));
- }
- }
-
- public void partActivated(IWorkbenchPartReference partRef) {
- if (partRef instanceof IEditorReference) {
- editorActivated(((IEditorReference) partRef).getEditor(true));
- }
- }
-
- };
-
- private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
- public void treeCollapsed(TreeExpansionEvent event) {
- }
-
- public void treeExpanded(TreeExpansionEvent event) {
- Object element= event.getElement();
- if (element instanceof IJavaScriptUnit ||
- element instanceof IClassFile)
- expandMainType(element);
- }
- };
-
- private class PackageExplorerProblemTreeViewer extends ProblemTreeViewer {
- // fix for 64372 Projects showing up in Package Explorer twice [package explorer]
- private List fPendingRefreshes;
-
- public PackageExplorerProblemTreeViewer(Composite parent, int style) {
- super(parent, style);
- fPendingRefreshes= Collections.synchronizedList(new ArrayList());
- ColoredViewersManager.install(this);
- }
- public void add(Object parentElement, Object[] childElements) {
- if (fPendingRefreshes.contains(parentElement)) {
- return;
- }
- super.add(parentElement, childElements);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.AbstractTreeViewer#internalRefresh(java.lang.Object, boolean)
- */
- protected void internalRefresh(Object element, boolean updateLabels) {
- try {
- fPendingRefreshes.add(element);
- super.internalRefresh(element, updateLabels);
- } finally {
- fPendingRefreshes.remove(element);
- }
- }
-
- protected boolean evaluateExpandableWithFilters(Object parent) {
- if (parent instanceof IJavaScriptProject
- || parent instanceof IJavaScriptUnit || parent instanceof IClassFile
- || parent instanceof JsGlobalScopeContainer) {
- return false;
- }
- if (parent instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) parent).isArchive()) {
- return false;
- }
- return true;
- }
-
- protected boolean isFiltered(Object object, Object parent, ViewerFilter[] filters) {
- if (object instanceof PackageFragmentRootContainer) {
- return !hasFilteredChildren(object);
- }
-
- boolean res= super.isFiltered(object, parent, filters);
- if (res && isEssential(object)) {
- return false;
- }
- return res;
- }
-
- /* Checks if a filtered object in essential (i.e. is a parent that
- * should not be removed).
- */
- private boolean isEssential(Object object) {
- try {
- if (!isFlatLayout() && object instanceof IPackageFragment) {
- IPackageFragment fragment = (IPackageFragment) object;
- if (!fragment.isDefaultPackage() && fragment.hasSubpackages()) {
- return hasFilteredChildren(fragment);
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-
- protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
- IStructuredSelection is= (IStructuredSelection)invalidSelection;
- List ns= null;
- if (newSelection instanceof IStructuredSelection) {
- ns= new ArrayList(((IStructuredSelection)newSelection).toList());
- } else {
- ns= new ArrayList();
- }
- boolean changed= false;
- for (Iterator iter= is.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptProject) {
- IProject project= ((IJavaScriptProject)element).getProject();
- if (!project.isOpen() && project.exists()) {
- ns.add(project);
- changed= true;
- }
- } else if (element instanceof IProject) {
- IProject project= (IProject)element;
- if (project.isOpen()) {
- IJavaScriptProject jProject= JavaScriptCore.create(project);
- if (jProject != null && jProject.exists())
- ns.add(jProject);
- changed= true;
- }
- }
- }
- if (changed) {
- newSelection= new StructuredSelection(ns);
- setSelection(newSelection);
- }
- super.handleInvalidSelection(invalidSelection, newSelection);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object[] addAditionalProblemParents(Object[] elements) {
- if (showWorkingSets() && elements != null) {
- return fWorkingSetModel.addWorkingSets(elements);
- }
- return elements;
- }
-
- //---- special handling to preserve the selection correctly
- private boolean fInPreserveSelection;
- protected void preservingSelection(Runnable updateCode) {
- try {
- fInPreserveSelection= true;
- super.preservingSelection(updateCode);
- } finally {
- fInPreserveSelection= false;
- }
- }
- protected void setSelectionToWidget(ISelection selection, boolean reveal) {
- if (true) {
- super.setSelectionToWidget(selection, reveal);
- return;
- }
- if (!fInPreserveSelection || !(selection instanceof ITreeSelection)) {
- super.setSelectionToWidget(selection, reveal);
- return;
- }
- IContentProvider cp= getContentProvider();
- if (!(cp instanceof IMultiElementTreeContentProvider)) {
- super.setSelectionToWidget(selection, reveal);
- return;
- }
- IMultiElementTreeContentProvider contentProvider= (IMultiElementTreeContentProvider)cp;
- ITreeSelection toRestore= (ITreeSelection)selection;
- List pathsToSelect= new ArrayList();
- for (Iterator iter= toRestore.iterator(); iter.hasNext();) {
- Object element= iter.next();
- TreePath[] pathsToRestore= toRestore.getPathsFor(element);
- CustomHashtable currentParents= createRootAccessedMap(contentProvider.getTreePaths(element));
- for (int i= 0; i < pathsToRestore.length; i++) {
- TreePath path= pathsToRestore[i];
- Object root= path.getFirstSegment();
- if (root != null && path.equals((TreePath)currentParents.get(root), getComparer())) {
- pathsToSelect.add(path);
- }
- }
- }
- List toSelect= new ArrayList();
- for (Iterator iter= pathsToSelect.iterator(); iter.hasNext();) {
- TreePath path= (TreePath)iter.next();
- int size= path.getSegmentCount();
- if (size == 0)
- continue;
- Widget current= getTree();
- int last= size - 1;
- Object segment;
- for (int i= 0; i < size && current != null && (segment= path.getSegment(i)) != null; i++) {
- internalExpandToLevel(current, 1);
- current= internalFindChild(current, segment);
- if (i == last && current != null)
- toSelect.add(current);
- }
- }
- getTree().setSelection((TreeItem[])toSelect.toArray(new TreeItem[toSelect.size()]));
- }
- private Widget internalFindChild(Widget parent, Object element) {
- Item[] items = getChildren(parent);
- for (int i = 0; i < items.length; i++) {
- Item item = items[i];
- Object data = item.getData();
- if (data != null && equals(data, element))
- return item;
- }
- return null;
- }
- private CustomHashtable createRootAccessedMap(TreePath[] paths) {
- CustomHashtable result= new CustomHashtable(getComparer());
- for (int i= 0; i < paths.length; i++) {
- TreePath path= paths[i];
- Object root= path.getFirstSegment();
- if (root != null) {
- result.put(root, path);
- }
- }
- return result;
- }
- }
-
- public PackageExplorerPart() {
- fPostSelectionListener= new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- handlePostSelectionChanged(event);
- }
- };
-
- // exception: initialize from preference
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettingsSection(getClass().getName());
-
- // on by default
- fShowLibrariesNode= fDialogSettings.get(TAG_GROUP_LIBRARIES) == null || fDialogSettings.getBoolean(TAG_GROUP_LIBRARIES);
-
- fLinkingEnabled= fDialogSettings.getBoolean(TAG_LINK_EDITOR);
-
- try {
- fIsCurrentLayoutFlat= fDialogSettings.getInt(TAG_LAYOUT) == FLAT_LAYOUT;
- } catch (NumberFormatException e) {
- fIsCurrentLayoutFlat= false;
- }
-
- try {
- fRootMode= fDialogSettings.getInt(TAG_ROOT_MODE);
- } catch (NumberFormatException e) {
- fRootMode= ViewActionGroup.SHOW_PROJECTS;
- }
-
- }
-
- public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
- if (memento == null) {
- String persistedMemento= fDialogSettings.get(TAG_MEMENTO);
- if (persistedMemento != null) {
- try {
- memento= XMLMemento.createReadRoot(new StringReader(persistedMemento));
- } catch (WorkbenchException e) {
- // don't do anything. Simply don't restore the settings
- }
- }
- }
- fMemento= memento;
- if (memento != null) {
- restoreLayoutState(memento);
- restoreLinkingEnabled(memento);
- restoreRootMode(memento);
- }
- if (showWorkingSets()) {
- createWorkingSetModel();
- }
- }
-
- private void restoreRootMode(IMemento memento) {
- Integer value= memento.getInteger(TAG_ROOT_MODE);
- fRootMode= value == null ? ViewActionGroup.SHOW_PROJECTS : value.intValue();
- if (fRootMode != ViewActionGroup.SHOW_PROJECTS && fRootMode != ViewActionGroup.SHOW_WORKING_SETS)
- fRootMode= ViewActionGroup.SHOW_PROJECTS;
- }
-
- private void restoreLayoutState(IMemento memento) {
- Integer layoutState= memento.getInteger(TAG_LAYOUT);
- fIsCurrentLayoutFlat= layoutState == null || layoutState.intValue() == FLAT_LAYOUT;
-
- // on by default
- Integer groupLibraries= memento.getInteger(TAG_GROUP_LIBRARIES);
- fShowLibrariesNode= groupLibraries == null || groupLibraries.intValue() != 0;
- }
-
- /**
- * Returns the package explorer part of the active perspective. If
- * there isn't any package explorer part <code>null</code> is returned.
- * @return the package explorer from the active perspective
- */
- public static PackageExplorerPart getFromActivePerspective() {
- IWorkbenchPage activePage= JavaScriptPlugin.getActivePage();
- if (activePage == null)
- return null;
- IViewPart view= activePage.findView(VIEW_ID);
- if (view instanceof PackageExplorerPart)
- return (PackageExplorerPart)view;
- return null;
- }
-
- /**
- * Makes the package explorer part visible in the active perspective. If there
- * isn't a package explorer part registered <code>null</code> is returned.
- * Otherwise the opened view part is returned.
- * @return the opened package explorer
- */
- public static PackageExplorerPart openInActivePerspective() {
- try {
- return (PackageExplorerPart)JavaScriptPlugin.getActivePage().showView(VIEW_ID);
- } catch(PartInitException pe) {
- return null;
- }
- }
-
- public void dispose() {
- XMLMemento memento= XMLMemento.createWriteRoot("packageExplorer"); //$NON-NLS-1$
- saveState(memento);
- StringWriter writer= new StringWriter();
- try {
- memento.save(writer);
- fDialogSettings.put(TAG_MEMENTO, writer.getBuffer().toString());
- } catch (IOException e) {
- // don't do anything. Simply don't store the settings
- }
-
- if (fContextMenu != null && !fContextMenu.isDisposed())
- fContextMenu.dispose();
-
- getSite().getPage().removePartListener(fLinkWithEditorListener); // always remove even if we didn't register
-
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
- if (fViewer != null) {
- fViewer.removeTreeListener(fExpansionListener);
- }
-
- if (fActionSet != null)
- fActionSet.dispose();
- if (fFilterUpdater != null)
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater);
- if (fWorkingSetModel != null)
- fWorkingSetModel.dispose();
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- public void createPartControl(Composite parent) {
-
- final PerformanceStats stats= PerformanceStats.getStats(PERF_CREATE_PART_CONTROL, this);
- stats.startRun();
-
- fViewer= createViewer(parent);
- fViewer.setUseHashlookup(true);
-
- initDragAndDrop();
-
- setProviders();
-
- JavaScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
-
-
- MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(this);
- fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
- fViewer.getTree().setMenu(fContextMenu);
-
- // Register viewer with site. This must be done before making the actions.
- IWorkbenchPartSite site= getSite();
- site.registerContextMenu(menuMgr, fViewer);
- site.setSelectionProvider(fViewer);
-
- makeActions(); // call before registering for selection changes
-
- // Set input after filter and sorter has been set. This avoids resorting and refiltering.
- restoreFilterAndSorter();
- fViewer.setInput(findInputElement());
- initFrameActions();
- initKeyListener();
-
-
- fViewer.addPostSelectionChangedListener(fPostSelectionListener);
-
- fViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- fActionSet.handleDoubleClick(event);
- }
- });
-
- fViewer.addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- fActionSet.handleOpen(event);
- fLastOpenSelection= event.getSelection();
- }
- });
-
- IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
- fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
- fViewer.addTreeListener(fExpansionListener);
-
- // Set help for the view
- JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
-
- fillActionBars();
-
- updateTitle();
-
- fFilterUpdater= new FilterUpdater(fViewer);
- ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater);
-
- // Sync'ing the package explorer has to be done here. It can't be done
- // when restoring the link state since the package explorers input isn't
- // set yet.
- setLinkingEnabled(isLinkingEnabled());
-
- stats.endRun();
- }
-
- private void initFrameActions() {
- fActionSet.getUpAction().update();
- fActionSet.getBackAction().update();
- fActionSet.getForwardAction().update();
- }
-
- private ProblemTreeViewer createViewer(Composite composite) {
- return new PackageExplorerProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- }
-
- /**
- * Answers whether this part shows the packages flat or hierarchical.
- * @return <true> if flat layout is selected
- *
- *
- */
- public boolean isFlatLayout() {
- return fIsCurrentLayoutFlat;
- }
-
- private void setProviders() {
- //content provider must be set before the label provider
- fContentProvider= createContentProvider();
- fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
- fContentProvider.setShowLibrariesNode(fShowLibrariesNode);
- fViewer.setContentProvider(fContentProvider);
-
- fViewer.setComparer(createElementComparer());
-
- fLabelProvider= createLabelProvider();
- fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
- fDecoratingLabelProvider= new DecoratingJavaLabelProvider(fLabelProvider, false, fIsCurrentLayoutFlat);
- fViewer.setLabelProvider(fDecoratingLabelProvider);
- // problem decoration provided by PackageLabelProvider
- }
-
- public void setShowLibrariesNode(boolean enabled) {
- fShowLibrariesNode= enabled;
- saveDialogSettings();
-
- fContentProvider.setShowLibrariesNode(enabled);
- fViewer.getControl().setRedraw(false);
- fViewer.refresh();
- fViewer.getControl().setRedraw(true);
- }
-
- boolean isLibrariesNodeShown() {
- return fShowLibrariesNode;
- }
-
-
- public void setFlatLayout(boolean enable) {
- // Update current state and inform content and label providers
- fIsCurrentLayoutFlat= enable;
- saveDialogSettings();
-
- if (fViewer != null) {
- fContentProvider.setIsFlatLayout(isFlatLayout());
- fLabelProvider.setIsFlatLayout(isFlatLayout());
- fDecoratingLabelProvider.setFlatPackageMode(isFlatLayout());
-
- fViewer.getControl().setRedraw(false);
- fViewer.refresh();
- fViewer.getControl().setRedraw(true);
- }
- }
-
- /**
- * This method should only be called inside this class
- * and from test cases.
- * @return the created content provider
- */
- public PackageExplorerContentProvider createContentProvider() {
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
- if (showProjects())
- return new PackageExplorerContentProvider(showCUChildren);
- else
- return new WorkingSetAwareContentProvider(showCUChildren, fWorkingSetModel);
- }
-
- private PackageExplorerLabelProvider createLabelProvider() {
- return new PackageExplorerLabelProvider(fContentProvider);
- }
-
- private IElementComparer createElementComparer() {
- if (showProjects())
- return null;
- else
- return WorkingSetModel.COMPARER;
- }
-
- private void fillActionBars() {
- IActionBars actionBars= getViewSite().getActionBars();
- fActionSet.fillActionBars(actionBars);
- }
-
- private Object findInputElement() {
- if (showWorkingSets()) {
- return fWorkingSetModel;
- } else {
- Object input= getSite().getPage().getInput();
- if (input instanceof IWorkspace) {
- return JavaScriptCore.create(((IWorkspace)input).getRoot());
- } else if (input instanceof IContainer) {
- IJavaScriptElement element= JavaScriptCore.create((IContainer)input);
- if (element != null && element.exists())
- return element;
- return input;
- }
- //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
- // we can't handle the input
- // fall back to show the workspace
- return JavaScriptCore.create(JavaScriptPlugin.getWorkspace().getRoot());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key.equals(ISelectionProvider.class))
- return fViewer;
- if (key == IShowInSource.class) {
- return getShowInSource();
- }
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { IPageLayout.ID_RES_NAV };
- }
-
- };
- }
- if (key == IContextProvider.class) {
- return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.PACKAGES_VIEW);
- }
- return super.getAdapter(key);
- }
-
- /**
- * Returns the tool tip text for the given element.
- * @param element the element
- * @return the tooltip
- */
- String getToolTipText(Object element) {
- String result;
- if (!(element instanceof IResource)) {
- if (element instanceof IJavaScriptModel) {
- result= PackagesMessages.PackageExplorerPart_workspace;
- } else if (element instanceof IJavaScriptElement){
- result= JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- } else if (element instanceof IWorkingSet) {
- result= ((IWorkingSet)element).getLabel();
- } else if (element instanceof WorkingSetModel) {
- result= PackagesMessages.PackageExplorerPart_workingSetModel;
- } else {
- result= fLabelProvider.getText(element);
- }
- } else {
- IPath path= ((IResource) element).getFullPath();
- if (path.isRoot()) {
- result= PackagesMessages.PackageExplorer_title;
- } else {
- result= path.makeRelative().toString();
- }
- }
-
- if (fRootMode == ViewActionGroup.SHOW_PROJECTS) {
- if (fWorkingSetLabel == null)
- return result;
- if (result.length() == 0)
- return Messages.format(PackagesMessages.PackageExplorer_toolTip, new String[] { fWorkingSetLabel });
- return Messages.format(PackagesMessages.PackageExplorer_toolTip2, new String[] { result, fWorkingSetLabel });
- } else { // Working set mode. During initialization element and action set can be null.
- if (element != null && !(element instanceof IWorkingSet) && !(element instanceof WorkingSetModel) && fActionSet != null) {
- FrameList frameList= fActionSet.getFrameList();
- int index= frameList.getCurrentIndex();
- IWorkingSet ws= null;
- while(index >= 0) {
- Frame frame= frameList.getFrame(index);
- if (frame instanceof TreeFrame) {
- Object input= ((TreeFrame)frame).getInput();
- if (input instanceof IWorkingSet) {
- ws= (IWorkingSet) input;
- break;
- }
- }
- index--;
- }
- if (ws != null) {
- return Messages.format(PackagesMessages.PackageExplorer_toolTip3, new String[] {ws.getLabel() , result});
- } else {
- return result;
- }
- } else {
- return result;
- }
- }
- }
-
- public String getTitleToolTip() {
- if (fViewer == null)
- return super.getTitleToolTip();
- return getToolTipText(fViewer.getInput());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
- */
- public void setFocus() {
- fViewer.getTree().setFocus();
- }
-
- private ISelection getSelection() {
- return fViewer.getSelection();
- }
-
- //---- Action handling ----------------------------------------------------------
-
- /* (non-Javadoc)
- * @see IMenuListener#menuAboutToShow(IMenuManager)
- */
- public void menuAboutToShow(IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
-
- fActionSet.setContext(new ActionContext(getSelection()));
- fActionSet.fillContextMenu(menu);
- fActionSet.setContext(null);
- }
-
- private void makeActions() {
-
- final PerformanceStats stats= PerformanceStats.getStats(PERF_MAKE_ACTIONS, this);
- stats.startRun();
-
- fActionSet= new PackageExplorerActionGroup(this);
- if (fWorkingSetModel != null)
- fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel);
-
- stats.endRun();
- }
-
- // ---- Event handling ----------------------------------------------------------
-
- private void initDragAndDrop() {
- initDrag();
- initDrop();
- }
-
- private void initDrag() {
- int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
- Transfer[] transfers= new Transfer[] {
- LocalSelectionTransfer.getInstance(),
- ResourceTransfer.getInstance(),
- FileTransfer.getInstance()};
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(fViewer),
- new ResourceTransferDragAdapter(fViewer),
- new FileTransferDragAdapter(fViewer)
- };
- fViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fViewer, dragListeners));
- }
-
- private void initDrop() {
- int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT;
- Transfer[] transfers= new Transfer[] {
- LocalSelectionTransfer.getInstance(),
- FileTransfer.getInstance()};
- TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
- new SelectionTransferDropAdapter(fViewer),
- new FileTransferDropAdapter(fViewer),
- new WorkingSetDropAdapter(this)
- };
- fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
- }
-
- /**
- * Handles post selection changed in viewer.
- *
- * Links to editor (if option enabled).
- * @param event the selection eveny
- */
- private void handlePostSelectionChanged(SelectionChangedEvent event) {
- ISelection selection= event.getSelection();
- // If the selection is the same as the one that triggered the last
- // open event then do nothing. The editor already got revealed.
- if (isLinkingEnabled() && !selection.equals(fLastOpenSelection)) {
- linkToEditor((IStructuredSelection)selection);
- }
- fLastOpenSelection= null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.ISetSelectionTarget#selectReveal(org.eclipse.jface.viewers.ISelection)
- */
- public void selectReveal(final ISelection selection) {
- Control ctrl= getTreeViewer().getControl();
- if (ctrl == null || ctrl.isDisposed())
- return;
-
- fContentProvider.runPendingUpdates();
- fViewer.setSelection(convertSelection(selection), true);
- }
-
- public ISelection convertSelection(ISelection s) {
- if (!(s instanceof IStructuredSelection))
- return s;
-
- Object[] elements= ((IStructuredSelection)s).toArray();
-
- boolean changed= false;
- for (int i= 0; i < elements.length; i++) {
- Object convertedElement= convertElement(elements[i]);
- changed= changed || convertedElement != elements[i];
- elements[i]= convertedElement;
- }
- if (changed)
- return new StructuredSelection(elements);
- else
- return s;
- }
-
- private Object convertElement(Object original) {
- if (original instanceof IJavaScriptElement) {
- if (original instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit) original;
- IJavaScriptProject javaProject= cu.getJavaScriptProject();
- if (javaProject != null && javaProject.exists() && ! javaProject.isOnIncludepath(cu)) {
- // could be a working copy of a .java file that is not on classpath
- IResource resource= cu.getResource();
- if (resource != null)
- return resource;
- }
-
- }
- return original;
-
- } else if (original instanceof IResource) {
- IJavaScriptElement je= JavaScriptCore.create((IResource)original);
- if (je != null && je.exists()) {
- IJavaScriptProject javaProject= je.getJavaScriptProject();
- if (javaProject != null && javaProject.exists()) {
- return je;
- }
- }
- } else if (original instanceof IAdaptable) {
- IAdaptable adaptable= (IAdaptable)original;
- IJavaScriptElement je= (IJavaScriptElement) adaptable.getAdapter(IJavaScriptElement.class);
- if (je != null && je.exists())
- return je;
-
- IResource r= (IResource) adaptable.getAdapter(IResource.class);
- if (r != null) {
- je= JavaScriptCore.create(r);
- if (je != null && je.exists())
- return je;
- else
- return r;
- }
- }
- return original;
- }
-
- public void selectAndReveal(Object element) {
- selectReveal(new StructuredSelection(element));
- }
-
- public boolean isLinkingEnabled() {
- return fLinkingEnabled;
- }
-
- /**
- * Links to editor (if option enabled)
- * @param selection the selection
- */
- private void linkToEditor(IStructuredSelection selection) {
- // ignore selection changes if the package explorer is not the active part.
- // In this case the selection change isn't triggered by a user.
- if (!isActivePart())
- return;
- Object obj= selection.getFirstElement();
-
- if (selection.size() == 1) {
- IEditorPart part= EditorUtility.isOpenInEditor(obj);
- if (part != null) {
- IWorkbenchPage page= getSite().getPage();
- page.bringToTop(part);
- if (obj instanceof IJavaScriptElement)
- EditorUtility.revealInEditor(part, (IJavaScriptElement)obj);
- }
- }
- }
-
- private boolean isActivePart() {
- return this == getSite().getPage().getActivePart();
- }
-
- public void saveState(IMemento memento) {
- if (fViewer == null && fMemento != null) {
- // part has not been created -> keep the old state
- memento.putMemento(fMemento);
- return;
- }
-
- memento.putInteger(TAG_ROOT_MODE, fRootMode);
- if (fWorkingSetModel != null)
- fWorkingSetModel.saveState(memento);
-
- saveLayoutState(memento);
- saveLinkingEnabled(memento);
-
- if (fActionSet != null) {
- fActionSet.saveFilterAndSorterState(memento);
- }
- }
-
- private void saveLinkingEnabled(IMemento memento) {
- memento.putInteger(TAG_LINK_EDITOR, fLinkingEnabled ? 1 : 0);
- }
-
- private void saveLayoutState(IMemento memento) {
- if (memento != null) {
- memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
- memento.putInteger(TAG_GROUP_LIBRARIES, fShowLibrariesNode ? 1 : 0);
- }
- }
-
- private void saveDialogSettings() {
- fDialogSettings.put(TAG_GROUP_LIBRARIES, fShowLibrariesNode);
- fDialogSettings.put(TAG_LAYOUT, getLayoutAsInt());
- fDialogSettings.put(TAG_ROOT_MODE, fRootMode);
- fDialogSettings.put(TAG_LINK_EDITOR, fLinkingEnabled);
- }
-
- private int getLayoutAsInt() {
- if (fIsCurrentLayoutFlat)
- return FLAT_LAYOUT;
- else
- return HIERARCHICAL_LAYOUT;
- }
-
- private void restoreFilterAndSorter() {
- setComparator();
- if (fMemento != null)
- fActionSet.restoreFilterAndSorterState(fMemento);
- }
-
- private void restoreLinkingEnabled(IMemento memento) {
- Integer val= memento.getInteger(TAG_LINK_EDITOR);
- fLinkingEnabled= val != null && val.intValue() != 0;
- }
-
- /**
- * Create the KeyListener for doing the refresh on the viewer.
- */
- private void initKeyListener() {
- fViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- fActionSet.handleKeyEvent(event);
- }
- });
- }
-
- /**
- * An editor has been activated. Set the selection in this Packages Viewer
- * to be the editor's input, if linking is enabled.
- * @param editor the activated editor
- */
- void editorActivated(IEditorPart editor) {
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput == null)
- return;
- Object input= getInputFromEditor(editorInput);
- if (input == null)
- return;
- if (!inputIsSelected(editorInput))
- showInput(input);
- else
- getTreeViewer().getTree().showSelection();
- }
-
- private Object getInputFromEditor(IEditorInput editorInput) {
- Object input= JavaScriptUI.getEditorInputJavaElement(editorInput);
- if (input == null) {
- input= editorInput.getAdapter(IFile.class);
- }
- if (input == null && editorInput instanceof IStorageEditorInput) {
- try {
- input= ((IStorageEditorInput) editorInput).getStorage();
- } catch (CoreException e) {
- // ignore
- }
- }
- return input;
- }
-
-
- private boolean inputIsSelected(IEditorInput input) {
- IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection();
- if (selection.size() != 1)
- return false;
- IEditorInput selectionAsInput= null;
- try {
- selectionAsInput= EditorUtility.getEditorInput(selection.getFirstElement());
- } catch (JavaScriptModelException e1) {
- return false;
- }
- return input.equals(selectionAsInput);
- }
-
- boolean showInput(Object input) {
- Object element= null;
-
- if (input instanceof IFile && isOnClassPath((IFile)input)) {
- element= JavaScriptCore.create((IFile)input);
- }
-
- if (element == null) // try a non Java resource
- element= input;
-
- if (element != null) {
- ISelection newSelection= new StructuredSelection(element);
- if (fViewer.getSelection().equals(newSelection)) {
- fViewer.reveal(element);
- } else {
- try {
- fViewer.removePostSelectionChangedListener(fPostSelectionListener);
- fViewer.setSelection(newSelection, true);
-
- while (element != null && fViewer.getSelection().isEmpty()) {
- // Try to select parent in case element is filtered
- element= getParent(element);
- if (element != null) {
- newSelection= new StructuredSelection(element);
- fViewer.setSelection(newSelection, true);
- }
- }
- } finally {
- fViewer.addPostSelectionChangedListener(fPostSelectionListener);
- }
- }
- return true;
- }
- return false;
- }
-
- private boolean isOnClassPath(IFile file) {
- IJavaScriptProject jproject= JavaScriptCore.create(file.getProject());
- return jproject.isOnIncludepath(file);
- }
-
- /**
- * Returns the element's parent.
- * @param element the element
- *
- * @return the parent or <code>null</code> if there's no parent
- */
- private Object getParent(Object element) {
- if (element instanceof IJavaScriptElement)
- return ((IJavaScriptElement)element).getParent();
- else if (element instanceof IResource)
- return ((IResource)element).getParent();
- else if (element instanceof IJarEntryResource) {
- return ((IJarEntryResource)element).getParent();
- }
- return null;
- }
-
- /**
- * A compilation unit or class was expanded, expand
- * the main type.
- * @param element the element
- */
- void expandMainType(Object element) {
- try {
- IType type= null;
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit)element;
- IType[] types= cu.getTypes();
- if (types.length > 0)
- type= types[0];
- }
- else if (element instanceof IClassFile) {
- IClassFile cf= (IClassFile)element;
- type= cf.getType();
- }
- if (type != null) {
- final IType type2= type;
- Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- ctrl.getDisplay().asyncExec(new Runnable() {
- public void run() {
- Control ctrl2= fViewer.getControl();
- if (ctrl2 != null && !ctrl2.isDisposed())
- fViewer.expandToLevel(type2, 1);
- }
- });
- }
- }
- } catch(JavaScriptModelException e) {
- // no reveal
- }
- }
-
- /**
- * Returns the TreeViewer.
- * @return the tree viewer
- */
- public TreeViewer getTreeViewer() {
- return fViewer;
- }
-
- boolean isExpandable(Object element) {
- if (fViewer == null)
- return false;
- return fViewer.isExpandable(element);
- }
-
- void setWorkingSetLabel(String workingSetName) {
- fWorkingSetLabel= workingSetName;
- setTitleToolTip(getTitleToolTip());
- }
-
- /**
- * Updates the title text and title tool tip.
- * Called whenever the input of the viewer changes.
- */
- void updateTitle() {
- Object input= fViewer.getInput();
- if (input == null
- || (input instanceof IJavaScriptModel)) {
- setContentDescription(""); //$NON-NLS-1$
- setTitleToolTip(""); //$NON-NLS-1$
- } else {
- String inputText= JavaScriptElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
- setContentDescription(inputText);
- setTitleToolTip(getToolTipText(input));
- }
- }
-
- /**
- * Sets the decorator for the package explorer.
- *
- * @param decorator a label decorator or <code>null</code> for no decorations.
- * @deprecated To be removed
- */
- public void setLabelDecorator(ILabelDecorator decorator) {
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (fViewer == null)
- return;
-
- boolean refreshViewer= false;
-
- if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
- fActionSet.updateActionBars(getViewSite().getActionBars());
-
- boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
- ((StandardJavaScriptElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
-
- refreshViewer= true;
- } else if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
- refreshViewer= true;
- }
-
- if (refreshViewer)
- fViewer.refresh();
- }
-
- /* (non-Javadoc)
- * @see IViewPartInputProvider#getViewPartInput()
- */
- public Object getViewPartInput() {
- if (fViewer != null) {
- return fViewer.getInput();
- }
- return null;
- }
-
- public void collapseAll() {
- try {
- fViewer.getControl().setRedraw(false);
- fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS);
- } finally {
- fViewer.getControl().setRedraw(true);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.IShowInTarget#show(org.eclipse.ui.part.ShowInContext)
- */
- public boolean show(ShowInContext context) {
- ISelection selection= context.getSelection();
- if (selection instanceof IStructuredSelection) {
- // fix for 64634 Navigate/Show in/Package Explorer doesn't work
- IStructuredSelection structuredSelection= ((IStructuredSelection) selection);
- if (structuredSelection.size() == 1) {
- int res= tryToReveal(structuredSelection.getFirstElement());
- if (res == IStatus.OK)
- return true;
- if (res == IStatus.CANCEL)
- return false;
- } else if (structuredSelection.size() > 1) {
- selectReveal(structuredSelection);
- return true;
- }
- }
-
- Object input= context.getInput();
- if (input instanceof IEditorInput) {
- Object elementOfInput= getInputFromEditor((IEditorInput) input);
- return elementOfInput != null && (tryToReveal(elementOfInput) == IStatus.OK);
- }
-
- return false;
- }
-
- /**
- * Returns the <code>IShowInSource</code> for this view.
- * @return the <code>IShowInSource</code>
- */
- protected IShowInSource getShowInSource() {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- return new ShowInContext(
- getTreeViewer().getInput(),
- getTreeViewer().getSelection());
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.IPackagesViewPart#setLinkingEnabled(boolean)
- */
- public void setLinkingEnabled(boolean enabled) {
- fLinkingEnabled= enabled;
- saveDialogSettings();
-
- IWorkbenchPage page= getSite().getPage();
- if (enabled) {
- page.addPartListener(fLinkWithEditorListener);
-
- IEditorPart editor = page.getActiveEditor();
- if (editor != null) {
- editorActivated(editor);
- }
- } else {
- page.removePartListener(fLinkWithEditorListener);
- }
- }
-
- /**
- * Returns the name for the given element.
- * Used as the name for the current frame.
- * @param element the elemeny
- * @return the name of the frame
- */
- String getFrameName(Object element) {
- if (element instanceof IJavaScriptElement) {
- return ((IJavaScriptElement) element).getElementName();
- } else if (element instanceof WorkingSetModel) {
- return ""; //$NON-NLS-1$
- } else {
- return fLabelProvider.getText(element);
- }
- }
-
- public int tryToReveal(Object element) {
- if (revealElementOrParent(element))
- return IStatus.OK;
-
- WorkingSetFilterActionGroup workingSetGroup= fActionSet.getWorkingSetActionGroup().getFilterGroup();
- if (workingSetGroup != null) {
- IWorkingSet workingSet= workingSetGroup.getWorkingSet();
- if (workingSetGroup.isFiltered(getVisibleParent(element), element)) {
- String message;
- if (element instanceof IJavaScriptElement) {
- String elementLabel= JavaScriptElementLabels.getElementLabel((IJavaScriptElement)element, JavaScriptElementLabels.ALL_DEFAULT);
- message= Messages.format(PackagesMessages.PackageExplorerPart_notFoundSepcific, new String[] {elementLabel, workingSet.getLabel()});
- } else {
- message= Messages.format(PackagesMessages.PackageExplorer_notFound, workingSet.getLabel());
- }
- if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) {
- workingSetGroup.setWorkingSet(null, true);
- if (revealElementOrParent(element))
- return IStatus.OK;
- } else {
- return IStatus.CANCEL;
- }
- }
- }
- // try to remove filters
- CustomFiltersActionGroup filterGroup= fActionSet.getCustomFilterActionGroup();
- String[] currentFilters= filterGroup.internalGetEnabledFilterIds();
- String[] newFilters= filterGroup.removeFiltersFor(getVisibleParent(element), element, getTreeViewer().getContentProvider());
- if (currentFilters.length > newFilters.length) {
- String message;
- if (element instanceof IJavaScriptElement) {
- String elementLabel= JavaScriptElementLabels.getElementLabel((IJavaScriptElement)element, JavaScriptElementLabels.ALL_DEFAULT);
- message= Messages.format(PackagesMessages.PackageExplorerPart_removeFiltersSpecific, elementLabel);
- } else {
- message= PackagesMessages.PackageExplorer_removeFilters;
- }
- if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) {
- filterGroup.setFilters(newFilters);
- if (revealElementOrParent(element))
- return IStatus.OK;
- } else {
- return IStatus.CANCEL;
- }
- }
- FrameAction action= fActionSet.getUpAction();
- while (action.getFrameList().getCurrentIndex() > 0) {
- // only try to go up if there is a parent frame
- // fix for bug# 63769 Endless loop after Show in Package Explorer
- if (action.getFrameList().getSource().getFrame(IFrameSource.PARENT_FRAME, 0) == null)
- break;
- action.run();
- if (revealElementOrParent(element))
- return IStatus.OK;
- }
- return IStatus.ERROR;
- }
-
- private boolean revealElementOrParent(Object element) {
- if (revealAndVerify(element))
- return true;
- element= getVisibleParent(element);
- if (element != null) {
- if (revealAndVerify(element))
- return true;
- if (element instanceof IJavaScriptElement) {
- IResource resource= ((IJavaScriptElement)element).getResource();
- if (resource != null) {
- if (revealAndVerify(resource))
- return true;
- }
- }
- }
- return false;
- }
-
- private Object getVisibleParent(Object object) {
- // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
- if (object == null)
- return null;
- if (!(object instanceof IJavaScriptElement))
- return object;
- IJavaScriptElement element2= (IJavaScriptElement) object;
- switch (element2.getElementType()) {
- case IJavaScriptElement.IMPORT_DECLARATION:
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.INITIALIZER:
- // select parent cu/classfile
- element2= (IJavaScriptElement)element2.getOpenable();
- break;
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- element2= null;
- break;
- }
- return element2;
- }
-
- private boolean revealAndVerify(Object element) {
- if (element == null)
- return false;
- selectReveal(new StructuredSelection(element));
- return ! getSite().getSelectionProvider().getSelection().isEmpty();
- }
-
- public void rootModeChanged(int newMode) {
- fRootMode= newMode;
- saveDialogSettings();
-
- if (showWorkingSets() && fWorkingSetModel == null) {
- createWorkingSetModel();
- if (fActionSet != null) {
- fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel);
- }
- }
- IStructuredSelection selection= new StructuredSelection(((IStructuredSelection) fViewer.getSelection()).toArray());
- Object input= fViewer.getInput();
- boolean isRootInputChange= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).equals(input)
- || (fWorkingSetModel != null && fWorkingSetModel.equals(input))
- || input instanceof IWorkingSet;
- try {
- fViewer.getControl().setRedraw(false);
- if (isRootInputChange) {
- fViewer.setInput(null);
- }
- setProviders();
- setComparator();
- fActionSet.getWorkingSetActionGroup().fillFilters(fViewer);
- if (isRootInputChange) {
- fViewer.setInput(findInputElement());
- }
- fViewer.setSelection(selection, true);
- } finally {
- fViewer.getControl().setRedraw(true);
- }
- if (isRootInputChange && showWorkingSets() && fWorkingSetModel.needsConfiguration()) {
- ConfigureWorkingSetAction action= new ConfigureWorkingSetAction(getSite());
- action.setWorkingSetModel(fWorkingSetModel);
- action.run();
- fWorkingSetModel.configured();
- }
- setTitleToolTip(getTitleToolTip());
- }
-
- private void createWorkingSetModel() {
- SafeRunner.run(new ISafeRunnable() {
- public void run() throws Exception {
- fWorkingSetModel= new WorkingSetModel(fMemento);
- }
- public void handleException(Throwable exception) {
- fWorkingSetModel= new WorkingSetModel(null);
- }
- });
- }
-
-
- /**
- * @return the selected working set to filter if in root mode {@link ViewActionGroup#SHOW_PROJECTS}
- */
- public IWorkingSet getFilterWorkingSet() {
- if (!showProjects())
- return null;
-
- if (fActionSet == null)
- return null;
-
- return fActionSet.getWorkingSetActionGroup().getFilterGroup().getWorkingSet();
- }
-
- public WorkingSetModel getWorkingSetModel() {
- return fWorkingSetModel;
- }
-
- public int getRootMode() {
- return fRootMode;
- }
-
- /* package */ boolean showProjects() {
- return fRootMode == ViewActionGroup.SHOW_PROJECTS;
- }
-
- /* package */ boolean showWorkingSets() {
- return fRootMode == ViewActionGroup.SHOW_WORKING_SETS;
- }
-
- private void setComparator() {
- if (showWorkingSets()) {
- fViewer.setComparator(new WorkingSetAwareJavaElementSorter());
- } else {
- fViewer.setComparator(new JavaScriptElementComparator());
- }
- }
-
- //---- test methods for working set mode -------------------------------
-
- public void internalTestShowWorkingSets(IWorkingSet[] workingSets) {
- if (fWorkingSetModel == null)
- createWorkingSetModel();
- fWorkingSetModel.setActiveWorkingSets(workingSets);
- fWorkingSetModel.configured();
- rootModeChanged(ViewActionGroup.SHOW_WORKING_SETS);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerProblemsDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerProblemsDecorator.java
deleted file mode 100644
index 5a2d8866..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerProblemsDecorator.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.TreeHierarchyLayoutProblemsDecorator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-
-public class PackageExplorerProblemsDecorator extends TreeHierarchyLayoutProblemsDecorator {
-
- public PackageExplorerProblemsDecorator() {
- super();
- }
-
- public PackageExplorerProblemsDecorator(boolean isFlatLayout) {
- super(isFlatLayout);
- }
-
- protected int computeAdornmentFlags(Object obj) {
- if (!(obj instanceof IWorkingSet))
- return super.computeAdornmentFlags(obj);
-
- IWorkingSet workingSet= (IWorkingSet)obj;
- IAdaptable[] elements= workingSet.getElements();
- int result= 0;
- for (int i= 0; i < elements.length; i++) {
- IAdaptable element= elements[i];
- int flags= super.computeAdornmentFlags(element);
- if ((flags & JavaScriptElementImageDescriptor.ERROR) != 0)
- return JavaScriptElementImageDescriptor.ERROR;
- if ((flags & JavaScriptElementImageDescriptor.WARNING) != 0)
- result= JavaScriptElementImageDescriptor.WARNING;
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageFragmentRootContainer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageFragmentRootContainer.java
deleted file mode 100644
index 6b4c723c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageFragmentRootContainer.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-public abstract class PackageFragmentRootContainer implements IAdaptable {
-
- private static WorkbenchAdapterImpl fgAdapterInstance= new WorkbenchAdapterImpl();
-
- private static class WorkbenchAdapterImpl implements IWorkbenchAdapter {
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object)
- */
- public Object[] getChildren(Object o) {
- if (o instanceof PackageFragmentRootContainer)
- return ((PackageFragmentRootContainer) o).getChildren();
- return new Object[0];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getImageDescriptor(java.lang.Object)
- */
- public ImageDescriptor getImageDescriptor(Object o) {
- if (o instanceof PackageFragmentRootContainer)
- return ((PackageFragmentRootContainer) o).getImageDescriptor();
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object)
- */
- public String getLabel(Object o) {
- if (o instanceof PackageFragmentRootContainer)
- return ((PackageFragmentRootContainer) o).getLabel();
- return new String();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getParent(java.lang.Object)
- */
- public Object getParent(Object o) {
- if (o instanceof PackageFragmentRootContainer)
- return ((PackageFragmentRootContainer) o).getJavaProject();
- return null;
- }
- }
-
- private IJavaScriptProject fProject;
-
- public PackageFragmentRootContainer(IJavaScriptProject project) {
- Assert.isNotNull(project);
- fProject= project;
- }
-
- public Object getAdapter(Class adapter) {
- if (adapter == IWorkbenchAdapter.class)
- return fgAdapterInstance;
- return null;
- }
-
- public abstract IAdaptable[] getChildren();
-
- public abstract IPackageFragmentRoot[] getPackageFragmentRoots();
-
- public abstract String getLabel();
-
- public abstract ImageDescriptor getImageDescriptor();
-
- public IJavaScriptProject getJavaProject() {
- return fProject;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesFrameSource.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesFrameSource.java
deleted file mode 100644
index e726f0d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesFrameSource.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.ui.views.framelist.TreeFrame;
-import org.eclipse.ui.views.framelist.TreeViewerFrameSource;
-
-class PackagesFrameSource extends TreeViewerFrameSource {
- private PackageExplorerPart fPackagesExplorer;
-
- PackagesFrameSource(PackageExplorerPart explorer) {
- super(explorer.getTreeViewer());
- fPackagesExplorer= explorer;
- }
-
- protected TreeFrame createFrame(Object input) {
- TreeFrame frame = super.createFrame(input);
- frame.setName(fPackagesExplorer.getFrameName(input));
- frame.setToolTipText(fPackagesExplorer.getToolTipText(input));
- return frame;
- }
-
- /**
- * Also updates the title of the packages explorer
- * @param frame the frame that changed
- */
- protected void frameChanged(TreeFrame frame) {
- super.frameChanged(frame);
- fPackagesExplorer.updateTitle();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java
deleted file mode 100644
index 7212f2b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class PackagesMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages";//$NON-NLS-1$
-
- private PackagesMessages() {
- // Do not instantiate
- }
-
- public static String DragAdapter_deleting;
- public static String DragAdapter_problem;
- public static String DragAdapter_problemTitle;
- public static String DragAdapter_refreshing;
- public static String DropAdapter_errorTitle;
- public static String DropAdapter_errorMessage;
- public static String GotoPackage_action_label;
- public static String GotoPackage_dialog_message;
- public static String GotoPackage_dialog_title;
- public static String GotoPackage_action_description;
- public static String GotoRequiredProjectAction_label;
- public static String GotoRequiredProjectAction_description;
- public static String GotoRequiredProjectAction_tooltip;
- public static String GotoType_action_label;
- public static String GotoType_action_description;
- public static String GotoType_dialog_message;
- public static String GotoType_dialog_title;
- public static String GotoType_error_message;
- public static String GotoResource_action_label;
- public static String GotoResource_dialog_title;
- public static String LayoutActionGroup_show_libraries_in_group;
- public static String LibraryContainer_name;
- public static String PackageExplorerPart_notFoundSepcific;
- public static String PackageExplorerPart_removeFiltersSpecific;
- public static String PackageExplorer_title;
- public static String PackageExplorer_toolTip;
- public static String PackageExplorer_toolTip2;
- public static String PackageExplorer_toolTip3;
- public static String PackageExplorer_element_not_present;
- public static String PackageExplorer_filteredDialog_title;
- public static String PackageExplorer_notFound;
- public static String PackageExplorer_removeFilters;
- public static String SelectionTransferDropAdapter_error_title;
- public static String SelectionTransferDropAdapter_error_message;
- public static String CollapseAllAction_label;
- public static String CollapseAllAction_tooltip;
- public static String CollapseAllAction_description;
- public static String LayoutActionGroup_label;
- public static String LayoutActionGroup_flatLayoutAction_label;
- public static String LayoutActionGroup_hierarchicalLayoutAction_label;
- public static String JsGlobalScopeContainer_unbound_label;
- public static String JsGlobalScopeContainer_unknown_label;
- public static String PackageExplorerPart_workspace;
- public static String PackageExplorerPart_workingSetModel;
- public static String PackageExplorerContentProvider_update_job_description;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, PackagesMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties
deleted file mode 100644
index 1283b4f4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties
+++ /dev/null
@@ -1,71 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-DragAdapter_deleting=Deleting ...
-DragAdapter_problem=Problem while moving or copying files.
-DragAdapter_problemTitle=Drag & Drop
-DragAdapter_refreshing=Refreshing...
-
-DropAdapter_errorTitle=Drag & Drop
-DropAdapter_errorMessage=Error while moving or copying files.
-
-
-GotoPackage_action_label=&Package...
-GotoPackage_dialog_message=&Choose a package (? = any character, * = any string):
-GotoPackage_dialog_title=Go to Package
-GotoPackage_action_description=Searches for and selects the package entered.
-
-GotoRequiredProjectAction_label=Go to Project
-GotoRequiredProjectAction_description=Go to Project
-GotoRequiredProjectAction_tooltip=Go to Project
-
-GotoType_action_label=&Type...
-GotoType_action_description=Searches for and selects the type entered.
-GotoType_dialog_message=&Choose a type (? = any character, * = any string):
-GotoType_dialog_title=Go to Type
-GotoType_error_message=An exception occurred while searching for types
-
-GotoResource_action_label=&Resource...
-GotoResource_dialog_title= Go to Resource
-
-PackageExplorer_title=JavaScript Explorer
-PackageExplorer_toolTip= Working Set: {0}
-PackageExplorer_toolTip2= {0} - Working Set: {1}
-PackageExplorer_toolTip3= {0}/{1}
-
-PackageExplorer_element_not_present=Cannot reveal {0} in Script Explorer. The element may be hidden by a filter or an active working set.
-
-PackageExplorer_filteredDialog_title=Show In JavaScript Explorer
-PackageExplorer_notFound=Cannot reveal the selected element. Do you want to deselect the current working set ''{0}''?
-PackageExplorer_removeFilters=Cannot reveal the selected element. Do you want to remove some filters to reveal the element?
-PackageExplorerContentProvider_update_job_description=Update script explorer
-
-PackageExplorerPart_workspace=Workspace
-PackageExplorerPart_workingSetModel=Working Sets
-PackageExplorerPart_notFoundSepcific=Cannot reveal ''{0}''. Do you want to deselect the current working set ''{1}''?
-PackageExplorerPart_removeFiltersSpecific=Cannot reveal ''{0}''. Do you want to remove some filters to reveal the element?
-
-SelectionTransferDropAdapter_error_title=Drag and drop
-SelectionTransferDropAdapter_error_message=Unexpected exception. See log for details
-
-CollapseAllAction_label=Collapse All
-CollapseAllAction_tooltip=Collapse All
-CollapseAllAction_description=Collapse All
-
-LayoutActionGroup_label= Folder &Presentation
-LayoutActionGroup_flatLayoutAction_label= &Flat
-LayoutActionGroup_show_libraries_in_group=Show 'Referenced Libraries' Node
-LayoutActionGroup_hierarchicalLayoutAction_label= &Grouped
-
-JsGlobalScopeContainer_unbound_label={0} (unbound)
-JsGlobalScopeContainer_unknown_label={0} (unknown)
-LibraryContainer_name=Referenced Libraries
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDragAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDragAdapter.java
deleted file mode 100644
index 5ad5ebca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDragAdapter.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.wst.jsdt.internal.ui.dnd.BasicSelectionTransferDragAdapter;
-
-public class SelectionTransferDragAdapter extends BasicSelectionTransferDragAdapter {
-
- public SelectionTransferDragAdapter(ISelectionProvider provider) {
- super(provider);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDropAdapter.java
deleted file mode 100644
index bd421314..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/SelectionTransferDropAdapter.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgCopyStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgMoveStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-public class SelectionTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
-
- private List fElements;
- private JavaMoveProcessor fMoveProcessor;
- private int fCanMoveElements;
- private JavaCopyProcessor fCopyProcessor;
- private int fCanCopyElements;
- private ISelection fSelection;
-
- private static final long DROP_TIME_DIFF_TRESHOLD= 150;
-
- public SelectionTransferDropAdapter(StructuredViewer viewer) {
- super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
- }
-
- //---- TransferDropTargetListener interface ---------------------------------------
-
- public Transfer getTransfer() {
- return LocalSelectionTransfer.getInstance();
- }
-
- public boolean isEnabled(DropTargetEvent event) {
- Object target= event.item != null ? event.item.getData() : null;
- if (target == null)
- return false;
- return target instanceof IJavaScriptElement || target instanceof IResource;
- }
-
- //---- Actual DND -----------------------------------------------------------------
-
- public void dragEnter(DropTargetEvent event) {
- clear();
- super.dragEnter(event);
- }
-
- public void dragLeave(DropTargetEvent event) {
- clear();
- super.dragLeave(event);
- }
-
- private void clear() {
- fElements= null;
- fSelection= null;
- fMoveProcessor= null;
- fCanMoveElements= 0;
- fCopyProcessor= null;
- fCanCopyElements= 0;
- }
-
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- event.detail= DND.DROP_NONE;
-
- if (tooFast(event))
- return;
-
- initializeSelection();
-
- try {
- switch(operation) {
- case DND.DROP_DEFAULT: event.detail= handleValidateDefault(target, event); break;
- case DND.DROP_COPY: event.detail= handleValidateCopy(target, event); break;
- case DND.DROP_MOVE: event.detail= handleValidateMove(target, event); break;
- }
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, PackagesMessages.SelectionTransferDropAdapter_error_title, PackagesMessages.SelectionTransferDropAdapter_error_message);
- event.detail= DND.DROP_NONE;
- }
- }
-
- protected void initializeSelection(){
- if (fElements != null)
- return;
- ISelection s= LocalSelectionTransfer.getInstance().getSelection();
- if (!(s instanceof IStructuredSelection))
- return;
- fSelection= s;
- fElements= ((IStructuredSelection)s).toList();
- }
-
- protected ISelection getSelection(){
- return fSelection;
- }
-
- private boolean tooFast(DropTargetEvent event) {
- return Math.abs(LocalSelectionTransfer.getInstance().getSelectionSetTime() - (event.time & 0xFFFFFFFFL)) < DROP_TIME_DIFF_TRESHOLD;
- }
-
- public void drop(Object target, DropTargetEvent event) {
- try{
- switch(event.detail) {
- case DND.DROP_MOVE: handleDropMove(target, event); break;
- case DND.DROP_COPY: handleDropCopy(target, event); break;
- }
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, PackagesMessages.SelectionTransferDropAdapter_error_title, PackagesMessages.SelectionTransferDropAdapter_error_message);
- } catch(InvocationTargetException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- } catch (InterruptedException e) {
- //ok
- } finally {
- // The drag source listener must not perform any operation
- // since this drop adapter did the remove of the source even
- // if we moved something.
- event.detail= DND.DROP_NONE;
- }
- }
-
- private int handleValidateDefault(Object target, DropTargetEvent event) throws JavaScriptModelException{
- if (target == null)
- return DND.DROP_NONE;
-
- if ((event.operations & DND.DROP_MOVE) != 0) {
- return handleValidateMove(target, event);
- }
- if ((event.operations & DND.DROP_COPY) != 0) {
- return handleValidateCopy(target, event);
- }
- return DND.DROP_NONE;
- }
-
- private int handleValidateMove(Object target, DropTargetEvent event) throws JavaScriptModelException{
- if (target == null)
- return DND.DROP_NONE;
-
- if (fMoveProcessor == null) {
- IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(ReorgUtils.getResources(fElements), ReorgUtils.getJavaElements(fElements));
- if (policy.canEnable())
- fMoveProcessor= new JavaMoveProcessor(policy);
- }
-
- if (!canMoveElements())
- return DND.DROP_NONE;
-
- if (target instanceof IResource && fMoveProcessor != null && fMoveProcessor.setDestination((IResource)target).isOK())
- return DND.DROP_MOVE;
- else if (target instanceof IJavaScriptElement && fMoveProcessor != null && fMoveProcessor.setDestination((IJavaScriptElement)target).isOK())
- return DND.DROP_MOVE;
- else
- return DND.DROP_NONE;
- }
-
- private boolean canMoveElements() {
- if (fCanMoveElements == 0) {
- fCanMoveElements= 2;
- if (fMoveProcessor == null)
- fCanMoveElements= 1;
- }
- return fCanMoveElements == 2;
- }
-
- private void handleDropMove(final Object target, DropTargetEvent event) throws JavaScriptModelException, InvocationTargetException, InterruptedException{
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(fElements);
- IResource[] resources= ReorgUtils.getResources(fElements);
- ReorgMoveStarter starter= null;
- if (target instanceof IResource)
- starter= ReorgMoveStarter.create(javaElements, resources, (IResource)target);
- else if (target instanceof IJavaScriptElement)
- starter= ReorgMoveStarter.create(javaElements, resources, (IJavaScriptElement)target);
- if (starter != null)
- starter.run(getShell());
- }
-
- private int handleValidateCopy(Object target, DropTargetEvent event) throws JavaScriptModelException{
-
- if (fCopyProcessor == null) {
- final ICopyPolicy policy= ReorgPolicyFactory.createCopyPolicy(ReorgUtils.getResources(fElements), ReorgUtils.getJavaElements(fElements));
- fCopyProcessor= policy.canEnable() ? new JavaCopyProcessor(policy) : null;
- }
-
- if (!canCopyElements())
- return DND.DROP_NONE;
-
- if (target instanceof IResource && fCopyProcessor != null && fCopyProcessor.setDestination((IResource)target).isOK())
- return DND.DROP_COPY;
- else if (target instanceof IJavaScriptElement && fCopyProcessor != null && fCopyProcessor.setDestination((IJavaScriptElement)target).isOK())
- return DND.DROP_COPY;
- else
- return DND.DROP_NONE;
- }
-
- private boolean canCopyElements() {
- if (fCanCopyElements == 0) {
- fCanCopyElements= 2;
- if (fCopyProcessor == null)
- fCanCopyElements= 1;
- }
- return fCanCopyElements == 2;
- }
-
- private void handleDropCopy(final Object target, DropTargetEvent event) throws JavaScriptModelException, InvocationTargetException, InterruptedException{
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(fElements);
- IResource[] resources= ReorgUtils.getResources(fElements);
- ReorgCopyStarter starter= null;
- if (target instanceof IResource)
- starter= ReorgCopyStarter.create(javaElements, resources, (IResource)target);
- else if (target instanceof IJavaScriptElement)
- starter= ReorgCopyStarter.create(javaElements, resources, (IJavaScriptElement)target);
- if (starter != null)
- starter.run(getShell());
- }
-
- private Shell getShell() {
- return getViewer().getControl().getShell();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java
deleted file mode 100644
index fd7b20bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.wst.jsdt.internal.ui.actions.AbstractToggleLinkingAction;
-import org.eclipse.wst.jsdt.ui.IPackagesViewPart;
-
-
-/**
- * This action toggles whether this package explorer links its selection to the active
- * editor.
- *
- *
- */
-public class ToggleLinkingAction extends AbstractToggleLinkingAction {
-
- private IPackagesViewPart fPackageExplorerPart;
-
- /**
- * Constructs a new action.
- */
- public ToggleLinkingAction(IPackagesViewPart explorer) {
- setChecked(explorer.isLinkingEnabled());
- fPackageExplorerPart= explorer;
- }
-
- /**
- * Runs the action.
- */
- public void run() {
- fPackageExplorerPart.setLinkingEnabled(isChecked());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java
deleted file mode 100644
index 8d44d7ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel;
-
-public class WorkingSetAwareContentProvider extends PackageExplorerContentProvider implements IMultiElementTreeContentProvider {
-
- private WorkingSetModel fWorkingSetModel;
- private IPropertyChangeListener fListener;
-
- public WorkingSetAwareContentProvider(boolean provideMembers, WorkingSetModel model) {
- super(provideMembers);
- fWorkingSetModel= model;
- fListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- workingSetModelChanged(event);
- }
- };
- fWorkingSetModel.addPropertyChangeListener(fListener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- fWorkingSetModel.removePropertyChangeListener(fListener);
- super.dispose();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasChildren(Object element) {
- if (element instanceof IWorkingSet)
- return true;
- return super.hasChildren(element);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getChildren(Object element) {
- Object[] children;
- if (element instanceof WorkingSetModel) {
- Assert.isTrue(fWorkingSetModel == element);
- return fWorkingSetModel.getActiveWorkingSets();
- } else if (element instanceof IWorkingSet) {
- children= getWorkingSetChildren((IWorkingSet)element);
- } else {
- children= super.getChildren(element);
- }
- return children;
- }
-
- private Object[] getWorkingSetChildren(IWorkingSet set) {
- IAdaptable[] elements= fWorkingSetModel.getChildren(set);
- Set result= new HashSet(elements.length);
- for (int i= 0; i < elements.length; i++) {
- IAdaptable element= elements[i];
- if (element instanceof IProject) {
- processResource((IProject) element, result); // also add closed projects
- } else if (element instanceof IResource) {
- IProject project= ((IResource) element).getProject();
- if (project.isOpen()) {
- processResource((IResource) element, result);
- }
- } else if (element instanceof IJavaScriptProject) {
- result.add(element); // also add closed projects
- } else if (element instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) element;
- IProject project= getProject(elem);
- if (project != null && project.isOpen()) {
- result.add(elem);
- }
- } else {
- IProject project= (IProject) element.getAdapter(IProject.class);
- if (project != null) {
- processResource(project, result);
- }
- }
- }
- return result.toArray();
- }
-
- private void processResource(IResource resource, Collection result) {
- IJavaScriptElement elem= JavaScriptCore.create(resource);
- if (elem != null && elem.exists()) {
- result.add(elem);
- } else {
- result.add(resource);
- }
- }
-
- private IProject getProject(IJavaScriptElement element) {
- IJavaScriptProject project= element.getJavaScriptProject();
- if (project == null)
- return null;
- return project.getProject();
- }
-
- /**
- * {@inheritDoc}
- */
- public TreePath[] getTreePaths(Object element) {
- if (element instanceof IWorkingSet) {
- TreePath path= new TreePath(new Object[] {element});
- return new TreePath[] {path};
- }
- List modelParents= getModelPath(element);
- List result= new ArrayList();
- for (int i= 0; i < modelParents.size(); i++) {
- result.addAll(getTreePaths(modelParents, i));
- }
- return (TreePath[])result.toArray(new TreePath[result.size()]);
- }
-
- private List getModelPath(Object element) {
- List result= new ArrayList();
- result.add(element);
- Object parent= super.getParent(element);
- Object input= getViewerInput();
- // stop at input or on JavaModel. We never visualize it anyway.
- while (parent != null && !parent.equals(input) && !(parent instanceof IJavaScriptModel)) {
- result.add(parent);
- parent= super.getParent(parent);
- }
- Collections.reverse(result);
- return result;
- }
-
- private List/*<TreePath>*/ getTreePaths(List modelParents, int index) {
- List result= new ArrayList();
- Object input= getViewerInput();
- Object element= modelParents.get(index);
- Object[] parents= fWorkingSetModel.getAllParents(element);
- for (int i= 0; i < parents.length; i++) {
- List chain= new ArrayList();
- if (!parents[i].equals(input))
- chain.add(parents[i]);
- for (int m= index; m < modelParents.size(); m++) {
- chain.add(modelParents.get(m));
- }
- result.add(new TreePath(chain.toArray()));
- }
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getParent(Object child) {
- Object[] parents= fWorkingSetModel.getAllParents(child);
- if(parents.length == 0)
- return super.getParent(child);
- Object first= parents[0];
- return first;
- }
-
- protected void augmentElementToRefresh(List toRefresh, int relation, Object affectedElement) {
- // we are refreshing the JavaModel and are in working set mode.
- if (JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).equals(affectedElement)) {
- toRefresh.remove(affectedElement);
- toRefresh.add(fWorkingSetModel);
- } else if (relation == GRANT_PARENT) {
- Object parent= internalGetParent(affectedElement);
- if (parent != null) {
- toRefresh.addAll(Arrays.asList(fWorkingSetModel.getAllParents(parent)));
- }
- }
- List nonProjetTopLevelElemens= fWorkingSetModel.getNonProjectTopLevelElements();
- if (nonProjetTopLevelElemens.isEmpty())
- return;
- List toAdd= new ArrayList();
- for (Iterator iter= nonProjetTopLevelElemens.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (isChildOf(element, toRefresh))
- toAdd.add(element);
- }
- toRefresh.addAll(toAdd);
- }
-
- private void workingSetModelChanged(PropertyChangeEvent event) {
- String property= event.getProperty();
- Object newValue= event.getNewValue();
- List toRefresh= new ArrayList(1);
- if (WorkingSetModel.CHANGE_WORKING_SET_MODEL_CONTENT.equals(property)) {
- toRefresh.add(fWorkingSetModel);
- } else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- toRefresh.add(newValue);
- } else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
- toRefresh.add(newValue);
- }
- ArrayList runnables= new ArrayList();
- postRefresh(toRefresh, true, runnables);
- executeRunnables(runnables);
- }
-
- private boolean isChildOf(Object element, List potentialParents) {
- // Calling super get parent to bypass working set mapping
- Object parent= super.getParent(element);
- if (parent == null)
- return false;
- for (Iterator iter= potentialParents.iterator(); iter.hasNext();) {
- Object potentialParent= iter.next();
- while(parent != null) {
- if (parent.equals(potentialParent))
- return true;
- parent= super.getParent(parent);
- }
-
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareJavaElementSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareJavaElementSorter.java
deleted file mode 100644
index 150dd494..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareJavaElementSorter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-
-public class WorkingSetAwareJavaElementSorter extends JavaScriptElementComparator {
-
- public int compare(Viewer viewer, Object e1, Object e2) {
- if (e1 instanceof IWorkingSet || e2 instanceof IWorkingSet)
- return 0;
-
- return super.compare(viewer, e1, e2);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetDropAdapter.java
deleted file mode 100644
index 1f730816..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetDropAdapter.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.packageview;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.OthersWorkingSetUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel;
-
-public class WorkingSetDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
-
- private PackageExplorerPart fPackageExplorer;
-
- private IStructuredSelection fSelection;
- private Object[] fElementsToAdds;
- private Set fCurrentElements;
- private IWorkingSet fWorkingSet;
-
- public WorkingSetDropAdapter(PackageExplorerPart part) {
- super(part.getTreeViewer(), DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
- fPackageExplorer= part;
- }
-
- //---- TransferDropTargetListener interface ---------------------------------------
-
- public Transfer getTransfer() {
- return LocalSelectionTransfer.getInstance();
- }
-
- public boolean isEnabled(DropTargetEvent event) {
- Object target= event.item != null ? event.item.getData() : null;
- if (target == null)
- return false;
- ISelection selection= LocalSelectionTransfer.getInstance().getSelection();
- if (!isValidSelection(selection)) {
- return false;
- }
- if (!isValidTarget(target))
- return false;
-
- initializeState(target, selection);
- return true;
- }
-
- //---- Actual DND -----------------------------------------------------------------
-
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- event.detail= DND.DROP_NONE;
- switch(operation) {
- case DND.DROP_DEFAULT:
- case DND.DROP_COPY:
- case DND.DROP_MOVE:
- event.detail= validateTarget(target, operation);
- break;
- case DND.DROP_LINK:
- event.detail= DND.DROP_NONE;
- break;
- }
- }
-
- private int validateTarget(Object target, int operation) {
- showInsertionFeedback(false);
- setDefaultFeedback(DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
- if (!isValidTarget(target))
- return DND.DROP_NONE;
- ISelection s= LocalSelectionTransfer.getInstance().getSelection();
- if (!isValidSelection(s)) {
- return DND.DROP_NONE;
- }
-
- initializeState(target, s);
-
- if (isWorkingSetSelection()) {
- setDefaultFeedback(DND.FEEDBACK_SCROLL);
- if (fLocation == LOCATION_BEFORE || fLocation == LOCATION_AFTER) {
- showInsertionFeedback(true);
- return DND.DROP_MOVE;
- }
- return DND.DROP_NONE;
- } else {
- if (isOthersWorkingSet(fWorkingSet) && operation == DND.DROP_COPY)
- return DND.DROP_NONE;
-
- List realJavaElements= new ArrayList();
- List realResource= new ArrayList();
- ReorgUtils.splitIntoJavaElementsAndResources(fElementsToAdds, realJavaElements, realResource);
- if (fElementsToAdds.length != realJavaElements.size() + realResource.size())
- return DND.DROP_NONE;
- for (Iterator iter= realJavaElements.iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement)iter.next();
- if (ReorgUtils.containsElementOrParent(fCurrentElements, element))
- return DND.DROP_NONE;
- }
- for (Iterator iter= realResource.iterator(); iter.hasNext();) {
- IResource element= (IResource)iter.next();
- if (ReorgUtils.containsElementOrParent(fCurrentElements, element))
- return DND.DROP_NONE;
- }
- if (!(fSelection instanceof ITreeSelection)) {
- return DND.DROP_COPY;
- }
- ITreeSelection treeSelection= (ITreeSelection)fSelection;
- TreePath[] paths= treeSelection.getPaths();
- for (int i= 0; i < paths.length; i++) {
- TreePath path= paths[i];
- if (path.getSegmentCount() != 2)
- return DND.DROP_COPY;
- if (!(path.getSegment(0) instanceof IWorkingSet))
- return DND.DROP_COPY;
- if (paths.length == 1) {
- IWorkingSet ws= (IWorkingSet)path.getSegment(0);
- if (OthersWorkingSetUpdater.ID.equals(ws.getId()))
- return DND.DROP_MOVE;
- }
- }
- }
- if (operation == DND.DROP_DEFAULT)
- return DND.DROP_MOVE;
- return operation;
- }
-
- private boolean isValidTarget(Object target) {
- return target instanceof IWorkingSet;
- }
-
- private boolean isValidSelection(ISelection selection) {
- return selection instanceof IStructuredSelection;
- }
-
- private boolean isOthersWorkingSet(IWorkingSet ws) {
- return OthersWorkingSetUpdater.ID.equals(ws.getId());
- }
-
- private void initializeState(Object target, ISelection s) {
- fWorkingSet= (IWorkingSet)target;
- fSelection= (IStructuredSelection)s;
- fElementsToAdds= fSelection.toArray();
- fCurrentElements= new HashSet(Arrays.asList(fWorkingSet.getElements()));
- }
-
- private boolean isWorkingSetSelection() {
- for (int i= 0; i < fElementsToAdds.length; i++) {
- if (!(fElementsToAdds[i] instanceof IWorkingSet))
- return false;
- }
- return true;
- }
-
- public void drop(Object target, final DropTargetEvent event) {
- if (isWorkingSetSelection()) {
- performWorkingSetReordering();
- } else {
- performElementRearrange(event.detail);
- }
- // drag adapter has nothing to do, even on move.
- event.detail= DND.DROP_NONE;
- }
-
- private void performWorkingSetReordering() {
- WorkingSetModel model= fPackageExplorer.getWorkingSetModel();
- List activeWorkingSets= new ArrayList(Arrays.asList(model.getActiveWorkingSets()));
- int index= activeWorkingSets.indexOf(fWorkingSet);
- if (index != -1) {
- if (fLocation == LOCATION_AFTER)
- index++;
- List result= new ArrayList(activeWorkingSets.size());
- List selected= new ArrayList(Arrays.asList(fElementsToAdds));
- for (int i= 0; i < activeWorkingSets.size(); i++) {
- if (i == index) {
- result.addAll(selected);
- }
- Object element= activeWorkingSets.get(i);
- if (!selected.contains(element)) {
- result.add(element);
- }
- }
- if (index == activeWorkingSets.size())
- result.addAll(selected);
- model.setActiveWorkingSets((IWorkingSet[])result.toArray(new IWorkingSet[result.size()]));
- }
- }
-
- private void performElementRearrange(int eventDetail) {
- // only move if target isn't the other working set. If this is the case
- // the move will happenn automatically by refreshing the other working set
- if (!isOthersWorkingSet(fWorkingSet)) {
- List elements= new ArrayList(Arrays.asList(fWorkingSet.getElements()));
- elements.addAll(Arrays.asList(fElementsToAdds));
- fWorkingSet.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- }
- if (eventDetail == DND.DROP_MOVE) {
- ITreeSelection treeSelection= (ITreeSelection)fSelection;
- Map workingSets= groupByWorkingSets(treeSelection.getPaths());
- for (Iterator iter= workingSets.keySet().iterator(); iter.hasNext();) {
- IWorkingSet ws= (IWorkingSet)iter.next();
- List toRemove= (List)workingSets.get(ws);
- List currentElements= new ArrayList(Arrays.asList(ws.getElements()));
- currentElements.removeAll(toRemove);
- ws.setElements((IAdaptable[])currentElements.toArray(new IAdaptable[currentElements.size()]));
- }
- }
- }
-
- private Map/*<List<IWorkingSet>>*/ groupByWorkingSets(TreePath[] paths) {
- Map result= new HashMap();
- for (int i= 0; i < paths.length; i++) {
- TreePath path= paths[i];
- IWorkingSet ws= (IWorkingSet)path.getSegment(0);
- List l= (List)result.get(ws);
- if (l == null) {
- l= new ArrayList();
- result.put(ws, l);
- }
- l.add(path.getSegment(1));
- }
- return result;
- }
-
- //---- test methods for JUnit test since DnD is hard to simulate
-
- public int internalTestValidateTarget(Object target, int operation) {
- return validateTarget(target, operation);
- }
-
- public void internalTestDrop(Object target, int eventDetail) {
- if (isWorkingSetSelection()) {
- performWorkingSetReordering();
- } else {
- performElementRearrange(eventDetail);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java
deleted file mode 100644
index ce0a9253..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.events.ExpansionAdapter;
-import org.eclipse.ui.forms.events.ExpansionEvent;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-
-/**
- * Configures Java Editor typing preferences.
- *
- *
- */
-abstract class AbstractConfigurationBlock implements IPreferenceConfigurationBlock {
-
- /**
- * Use as follows:
- *
- * <pre>
- * SectionManager manager= new SectionManager();
- * Composite composite= manager.createSectionComposite(parent);
- *
- * Composite xSection= manager.createSection("section X"));
- * xSection.setLayout(new FillLayout());
- * new Button(xSection, SWT.PUSH); // add controls to section..
- *
- * [...]
- *
- * return composite; // return main composite
- * </pre>
- */
- protected final class SectionManager {
- /** The preference setting for keeping no section open. */
- private static final String __NONE= "__none"; //$NON-NLS-1$
- private Set fSections= new HashSet();
- private boolean fIsBeingManaged= false;
- private ExpansionAdapter fListener= new ExpansionAdapter() {
- public void expansionStateChanged(ExpansionEvent e) {
- ExpandableComposite source= (ExpandableComposite) e.getSource();
- updateSectionStyle(source);
- if (fIsBeingManaged)
- return;
- if (e.getState()) {
- try {
- fIsBeingManaged= true;
- for (Iterator iter= fSections.iterator(); iter.hasNext();) {
- ExpandableComposite composite= (ExpandableComposite) iter.next();
- if (composite != source)
- composite.setExpanded(false);
- }
- } finally {
- fIsBeingManaged= false;
- }
- if (fLastOpenKey != null && fDialogSettingsStore != null)
- fDialogSettingsStore.setValue(fLastOpenKey, source.getText());
- } else {
- if (!fIsBeingManaged && fLastOpenKey != null && fDialogSettingsStore != null)
- fDialogSettingsStore.setValue(fLastOpenKey, __NONE);
- }
- ExpandableComposite exComp= getParentExpandableComposite(source);
- if (exComp != null)
- exComp.layout(true, true);
- ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(source);
- if (parentScrolledComposite != null) {
- parentScrolledComposite.reflow(true);
- }
- }
- };
- private Composite fBody;
- private final String fLastOpenKey;
- private final IPreferenceStore fDialogSettingsStore;
- private ExpandableComposite fFirstChild= null;
- /**
- * Creates a new section manager.
- */
- public SectionManager() {
- this(null, null);
- }
- /**
- * Creates a new section manager.
- */
- public SectionManager(IPreferenceStore dialogSettingsStore, String lastOpenKey) {
- fDialogSettingsStore= dialogSettingsStore;
- fLastOpenKey= lastOpenKey;
- }
- private void manage(ExpandableComposite section) {
- if (section == null)
- throw new NullPointerException();
- if (fSections.add(section))
- section.addExpansionListener(fListener);
- makeScrollableCompositeAware(section);
- }
-
- /**
- * Creates a new composite that can contain a set of expandable
- * sections. A <code>ScrolledPageComposite</code> is created and a new
- * composite within that, to ensure that expanding the sections will
- * always have enough space, unless there already is a
- * <code>ScrolledComposite</code> along the parent chain of
- * <code>parent</code>, in which case a normal <code>Composite</code>
- * is created.
- * <p>
- * The receiver keeps a reference to the inner body composite, so that
- * new sections can be added via <code>createSection</code>.
- * </p>
- *
- * @param parent the parent composite
- * @return the newly created composite
- */
- public Composite createSectionComposite(Composite parent) {
- Assert.isTrue(fBody == null);
- boolean isNested= isNestedInScrolledComposite(parent);
- Composite composite;
- if (isNested) {
- composite= new Composite(parent, SWT.NONE);
- fBody= composite;
- } else {
- composite= new ScrolledPageContent(parent);
- fBody= ((ScrolledPageContent) composite).getBody();
- }
-
- fBody.setLayout(new GridLayout());
-
- return composite;
- }
-
- /**
- * Creates an expandable section within the parent created previously by
- * calling <code>createSectionComposite</code>. Controls can be added
- * directly to the returned composite, which has no layout initially.
- *
- * @param label the display name of the section
- * @return a composite within the expandable section
- */
- public Composite createSection(String label) {
- Assert.isNotNull(fBody);
- final ExpandableComposite excomposite= new ExpandableComposite(fBody, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.COMPACT);
- if (fFirstChild == null)
- fFirstChild= excomposite;
- excomposite.setText(label);
- String last= null;
- if (fLastOpenKey != null && fDialogSettingsStore != null)
- last= fDialogSettingsStore.getString(fLastOpenKey);
-
- if (fFirstChild == excomposite && !__NONE.equals(last) || label.equals(last)) {
- excomposite.setExpanded(true);
- if (fFirstChild != excomposite)
- fFirstChild.setExpanded(false);
- } else {
- excomposite.setExpanded(false);
- }
- excomposite.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
-
- updateSectionStyle(excomposite);
- manage(excomposite);
-
- Composite contents= new Composite(excomposite, SWT.NONE);
- excomposite.setClient(contents);
-
- return contents;
- }
- }
-
- protected static final int INDENT= 20;
- private OverlayPreferenceStore fStore;
-
- private Map fCheckBoxes= new HashMap();
- private SelectionListener fCheckBoxListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- public void widgetSelected(SelectionEvent e) {
- Button button= (Button) e.widget;
- fStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
- }
- };
-
-
- private Map fTextFields= new HashMap();
- private ModifyListener fTextFieldListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- Text text= (Text) e.widget;
- fStore.setValue((String) fTextFields.get(text), text.getText());
- }
- };
-
- private ArrayList fNumberFields= new ArrayList();
- private ModifyListener fNumberFieldListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- numberFieldChanged((Text) e.widget);
- }
- };
-
- /**
- * List of master/slave listeners when there's a dependency.
- *
- * @see #createDependency(Button, Control)
- *
- */
- private ArrayList fMasterSlaveListeners= new ArrayList();
-
- private StatusInfo fStatus;
- private final PreferencePage fMainPage;
-
- public AbstractConfigurationBlock(OverlayPreferenceStore store) {
- Assert.isNotNull(store);
- fStore= store;
- fMainPage= null;
- }
-
- public AbstractConfigurationBlock(OverlayPreferenceStore store, PreferencePage mainPreferencePage) {
- Assert.isNotNull(store);
- Assert.isNotNull(mainPreferencePage);
- fStore= store;
- fMainPage= mainPreferencePage;
- }
-
- protected final ScrolledPageContent getParentScrolledComposite(Control control) {
- Control parent= control.getParent();
- while (!(parent instanceof ScrolledPageContent) && parent != null) {
- parent= parent.getParent();
- }
- if (parent instanceof ScrolledPageContent) {
- return (ScrolledPageContent) parent;
- }
- return null;
- }
-
- private final ExpandableComposite getParentExpandableComposite(Control control) {
- Control parent= control.getParent();
- while (!(parent instanceof ExpandableComposite) && parent != null) {
- parent= parent.getParent();
- }
- if (parent instanceof ExpandableComposite) {
- return (ExpandableComposite) parent;
- }
- return null;
- }
-
- protected void updateSectionStyle(ExpandableComposite excomposite) {
- excomposite.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
- }
-
- private void makeScrollableCompositeAware(Control control) {
- ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(control);
- if (parentScrolledComposite != null) {
- parentScrolledComposite.adaptChild(control);
- }
- }
-
- private boolean isNestedInScrolledComposite(Composite parent) {
- return getParentScrolledComposite(parent) != null;
- }
-
- protected Button addCheckBox(Composite parent, String label, String key, int indentation) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(label);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indentation;
- gd.horizontalSpan= 2;
- checkBox.setLayoutData(gd);
- checkBox.addSelectionListener(fCheckBoxListener);
- makeScrollableCompositeAware(checkBox);
-
- fCheckBoxes.put(checkBox, key);
-
- return checkBox;
- }
-
- /**
- * Returns an array of size 2:
- * - first element is of type <code>Label</code>
- * - second element is of type <code>Text</code>
- * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls.
- *
- * @param composite the parent composite
- * @param label the text field's label
- * @param key the preference key
- * @param textLimit the text limit
- * @param indentation the field's indentation
- * @param isNumber <code>true</code> iff this text field is used to e4dit a number
- * @return the controls added
- */
- protected Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) {
-
- PixelConverter pixelConverter= new PixelConverter(composite);
-
- Label labelControl= new Label(composite, SWT.NONE);
- labelControl.setText(label);
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indentation;
- labelControl.setLayoutData(gd);
-
- Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.widthHint= pixelConverter.convertWidthInCharsToPixels(textLimit + 1);
- textControl.setLayoutData(gd);
- textControl.setTextLimit(textLimit);
- fTextFields.put(textControl, key);
- if (isNumber) {
- fNumberFields.add(textControl);
- textControl.addModifyListener(fNumberFieldListener);
- } else {
- textControl.addModifyListener(fTextFieldListener);
- }
-
- return new Control[]{labelControl, textControl};
- }
-
- protected void createDependency(final Button master, final Control slave) {
- createDependency(master, new Control[] {slave});
- }
-
- protected void createDependency(final Button master, final Control[] slaves) {
- Assert.isTrue(slaves.length > 0);
- indent(slaves[0]);
- SelectionListener listener= new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- boolean state= master.getSelection();
- for (int i= 0; i < slaves.length; i++) {
- slaves[i].setEnabled(state);
- }
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {}
- };
- master.addSelectionListener(listener);
- fMasterSlaveListeners.add(listener);
- }
-
- protected static void indent(Control control) {
- ((GridData) control.getLayoutData()).horizontalIndent+= INDENT;
- }
-
- public void initialize() {
- initializeFields();
- }
-
- private void initializeFields() {
-
- Iterator iter= fCheckBoxes.keySet().iterator();
- while (iter.hasNext()) {
- Button b= (Button) iter.next();
- String key= (String) fCheckBoxes.get(b);
- b.setSelection(fStore.getBoolean(key));
- }
-
- iter= fTextFields.keySet().iterator();
- while (iter.hasNext()) {
- Text t= (Text) iter.next();
- String key= (String) fTextFields.get(t);
- t.setText(fStore.getString(key));
- }
-
- // Update slaves
- iter= fMasterSlaveListeners.iterator();
- while (iter.hasNext()) {
- SelectionListener listener= (SelectionListener)iter.next();
- listener.widgetSelected(null);
- }
-
- updateStatus(new StatusInfo());
- }
-
- public void performOk() {
- }
-
- public void performDefaults() {
- initializeFields();
- }
-
- IStatus getStatus() {
- if (fStatus == null)
- fStatus= new StatusInfo();
- return fStatus;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#dispose()
- *
- */
- public void dispose() {
- }
-
- private void numberFieldChanged(Text textControl) {
- String number= textControl.getText();
- IStatus status= validatePositiveNumber(number);
- if (!status.matches(IStatus.ERROR))
- fStore.setValue((String) fTextFields.get(textControl), number);
- updateStatus(status);
- }
-
- private IStatus validatePositiveNumber(String number) {
- StatusInfo status= new StatusInfo();
- if (number.length() == 0) {
- status.setError(PreferencesMessages.JavaEditorPreferencePage_empty_input);
- } else {
- try {
- int value= Integer.parseInt(number);
- if (value < 0)
- status.setError(Messages.format(PreferencesMessages.JavaEditorPreferencePage_invalid_input, number));
- } catch (NumberFormatException e) {
- status.setError(Messages.format(PreferencesMessages.JavaEditorPreferencePage_invalid_input, number));
- }
- }
- return status;
- }
-
- protected void updateStatus(IStatus status) {
- if (fMainPage == null)
- return;
- fMainPage.setValid(status.isOK());
- StatusUtil.applyToStatusLine(fMainPage, status);
- }
-
- protected final OverlayPreferenceStore getPreferenceStore() {
- return fStore;
- }
-
- protected Composite createSubsection(Composite parent, SectionManager manager, String label) {
- if (manager != null) {
- return manager.createSection(label);
- } else {
- Group group= new Group(parent, SWT.SHADOW_NONE);
- group.setText(label);
- GridData data= new GridData(SWT.FILL, SWT.CENTER, true, false);
- group.setLayoutData(data);
- return group;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferenceAndPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferenceAndPropertyPage.java
deleted file mode 100644
index 503f7c5c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferenceAndPropertyPage.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.ui.preferences.IWorkingCopyManager;
-import org.eclipse.ui.preferences.WorkingCopyManager;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- * Abstract preference and property page which is used to wrap a
- * {@link org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceAndPropertyConfigurationBlock}.
- *
- *
- */
-public abstract class AbstractConfigurationBlockPreferenceAndPropertyPage extends PropertyAndPreferencePage {
-
- private IPreferenceAndPropertyConfigurationBlock fConfigurationBlock;
- private PreferencesAccess fAccess;
-
- public AbstractConfigurationBlockPreferenceAndPropertyPage() {
- }
-
- /**
- * Create a configuration block which does modify settings in <code>context</code>.
- *
- * @param context the context to modify
- * @return the preference block, not null
- */
- protected abstract IPreferenceAndPropertyConfigurationBlock createConfigurationBlock(IScopeContext context);
-
- protected abstract String getHelpId();
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), getHelpId());
- }
-
- /**
- * {@inheritDoc}
- */
- protected Control createPreferenceContent(Composite parent) {
-
- IPreferencePageContainer container= getContainer();
- IWorkingCopyManager manager;
- if (container instanceof IWorkbenchPreferenceContainer) {
- manager= ((IWorkbenchPreferenceContainer)container).getWorkingCopyManager();
- } else {
- manager= new WorkingCopyManager(); // non shared
- }
- fAccess= PreferencesAccess.getWorkingCopyPreferences(manager);
- IProject project= getProject();
- IScopeContext context;
- if (project != null) {
- context= fAccess.getProjectScope(project);
- } else {
- context= fAccess.getInstanceScope();
- }
-
- fConfigurationBlock= createConfigurationBlock(context);
-
- Control content= fConfigurationBlock.createControl(parent);
-
- fConfigurationBlock.initialize();
-
- Dialog.applyDialogFont(content);
- return content;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean performOk() {
- fConfigurationBlock.performOk();
-
- try {
- fAccess.applyChanges();
- } catch (BackingStoreException e) {
- JavaScriptPlugin.log(e);
- }
-
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public void performDefaults() {
- fConfigurationBlock.performDefaults();
- super.performDefaults();
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- fConfigurationBlock.dispose();
- super.dispose();
- }
-
- /**
- * {@inheritDoc}
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (useProjectSpecificSettings) {
- fConfigurationBlock.enableProjectSettings();
- } else {
- fConfigurationBlock.disableProjectSettings();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java
deleted file mode 100644
index 2657ec0f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Abstract preference page which is used to wrap a
- * {@link org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock}.
- *
- *
- */
-public abstract class AbstractConfigurationBlockPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
-
- private IPreferenceConfigurationBlock fConfigurationBlock;
- private OverlayPreferenceStore fOverlayStore;
-
-
- /**
- * Creates a new preference page.
- */
- public AbstractConfigurationBlockPreferencePage() {
- setDescription();
- setPreferenceStore();
- fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), new OverlayPreferenceStore.OverlayKey[] {});
- fConfigurationBlock= createConfigurationBlock(fOverlayStore);
- }
-
- protected abstract IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore);
- protected abstract String getHelpId();
- protected abstract void setDescription();
- protected abstract void setPreferenceStore();
-
- /*
- * @see IWorkbenchPreferencePage#init()
- */
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), getHelpId());
- }
-
- /*
- * @see PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
-
- fOverlayStore.load();
- fOverlayStore.start();
-
- Control content= fConfigurationBlock.createControl(parent);
-
- initialize();
-
- Dialog.applyDialogFont(content);
- return content;
- }
-
- private void initialize() {
- fConfigurationBlock.initialize();
- }
-
- /*
- * @see PreferencePage#performOk()
- */
- public boolean performOk() {
-
- fConfigurationBlock.performOk();
-
- fOverlayStore.propagate();
-
- JavaScriptPlugin.getDefault().savePluginPreferences();
-
- return true;
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- public void performDefaults() {
-
- fOverlayStore.loadDefaults();
- fConfigurationBlock.performDefaults();
-
- super.performDefaults();
- }
-
- /*
- * @see DialogPage#dispose()
- */
- public void dispose() {
-
- fConfigurationBlock.dispose();
-
- if (fOverlayStore != null) {
- fOverlayStore.stop();
- fOverlayStore= null;
- }
-
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java
deleted file mode 100644
index e8f24133..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class AppearancePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- private static final String SHOW_CU_CHILDREN= PreferenceConstants.SHOW_CU_CHILDREN;
- private static final String PREF_METHOD_RETURNTYPE= PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE;
-// private static final String PREF_METHOD_TYPEPARAMETERS= PreferenceConstants.APPEARANCE_METHOD_TYPEPARAMETERS;
-// private static final String PREF_COMPRESS_PACKAGE_NAMES= PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES;
-// private static final String PREF_PKG_NAME_PATTERN_FOR_PKG_VIEW= PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW;
-// private static final String STACK_BROWSING_VIEWS_VERTICALLY= PreferenceConstants.BROWSING_STACK_VERTICALLY;
- private static final String PREF_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER;
- private static final String PREF_CATEGORY= PreferenceConstants.APPEARANCE_CATEGORY;
-
- public static final String PREF_COLORED_LABELS= "colored_labels_in_views"; //$NON-NLS-1$
-
- private SelectionButtonDialogField fShowMethodReturnType;
- private SelectionButtonDialogField fShowCategory;
-// private SelectionButtonDialogField fCompressPackageNames;
-// private SelectionButtonDialogField fStackBrowsingViewsVertically;
- private SelectionButtonDialogField fShowMembersInPackageView;
-// private StringDialogField fPackageNamePattern;
- private SelectionButtonDialogField fFoldPackagesInPackageExplorer;
-// private SelectionButtonDialogField fShowMethodTypeParameters;
- private SelectionButtonDialogField fShowColoredLabels;
-
- public AppearancePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setDescription(PreferencesMessages.AppearancePreferencePage_description);
-
- IDialogFieldListener listener= new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
- };
-
- fShowMethodReturnType= new SelectionButtonDialogField(SWT.CHECK);
- fShowMethodReturnType.setDialogFieldListener(listener);
-// fShowMethodReturnType.setLabelText(PreferencesMessages.AppearancePreferencePage_methodreturntype_label);
- fShowMethodReturnType.setLabelText(PreferencesMessages.AppearancePreferencePage_inferredmethodreturntype_label);
-
-// fShowMethodTypeParameters= new SelectionButtonDialogField(SWT.CHECK);
-// fShowMethodTypeParameters.setDialogFieldListener(listener);
-// fShowMethodTypeParameters.setLabelText(PreferencesMessages.AppearancePreferencePage_methodtypeparams_label);
-
- fShowCategory= new SelectionButtonDialogField(SWT.CHECK);
- fShowCategory.setDialogFieldListener(listener);
- fShowCategory.setLabelText(PreferencesMessages.AppearancePreferencePage_showCategory_label);
-
- fShowMembersInPackageView= new SelectionButtonDialogField(SWT.CHECK);
- fShowMembersInPackageView.setDialogFieldListener(listener);
- fShowMembersInPackageView.setLabelText(PreferencesMessages.AppearancePreferencePage_showMembersInPackagesView);
-
-// fStackBrowsingViewsVertically= new SelectionButtonDialogField(SWT.CHECK);
-// fStackBrowsingViewsVertically.setDialogFieldListener(listener);
-// fStackBrowsingViewsVertically.setLabelText(PreferencesMessages.AppearancePreferencePage_stackViewsVerticallyInTheJavaBrowsingPerspective);
-
- fFoldPackagesInPackageExplorer= new SelectionButtonDialogField(SWT.CHECK);
- fFoldPackagesInPackageExplorer.setDialogFieldListener(listener);
-// fFoldPackagesInPackageExplorer.setLabelText(PreferencesMessages.AppearancePreferencePage_foldEmptyPackages);
- fFoldPackagesInPackageExplorer.setLabelText(PreferencesMessages.AppearancePreferencePage_foldEmptySourceFolders);
-
-// fCompressPackageNames= new SelectionButtonDialogField(SWT.CHECK);
-// fCompressPackageNames.setDialogFieldListener(listener);
-// fCompressPackageNames.setLabelText(PreferencesMessages.AppearancePreferencePage_pkgNamePatternEnable_label);
-
-// fPackageNamePattern= new StringDialogField();
-// fPackageNamePattern.setDialogFieldListener(listener);
-// fPackageNamePattern.setLabelText(PreferencesMessages.AppearancePreferencePage_pkgNamePattern_label);
-
- fShowColoredLabels= new SelectionButtonDialogField(SWT.CHECK);
- fShowColoredLabels.setDialogFieldListener(listener);
- fShowColoredLabels.setLabelText(PreferencesMessages.AppearancePreferencePage_coloredlabels_label);
- }
-
- private void initFields() {
- IPreferenceStore prefs= getPreferenceStore();
- fShowMethodReturnType.setSelection(prefs.getBoolean(PREF_METHOD_RETURNTYPE));
-// fShowMethodTypeParameters.setSelection(prefs.getBoolean(PREF_METHOD_TYPEPARAMETERS));
- fShowMembersInPackageView.setSelection(prefs.getBoolean(SHOW_CU_CHILDREN));
- fShowCategory.setSelection(prefs.getBoolean(PREF_CATEGORY));
-// fStackBrowsingViewsVertically.setSelection(prefs.getBoolean(STACK_BROWSING_VIEWS_VERTICALLY));
-// fPackageNamePattern.setText(prefs.getString(PREF_PKG_NAME_PATTERN_FOR_PKG_VIEW));
-// fCompressPackageNames.setSelection(prefs.getBoolean(PREF_COMPRESS_PACKAGE_NAMES));
-// fPackageNamePattern.setEnabled(fCompressPackageNames.isSelected());
- fFoldPackagesInPackageExplorer.setSelection(prefs.getBoolean(PREF_FOLD_PACKAGES_IN_PACKAGE_EXPLORER));
-
- fShowColoredLabels.setSelection(prefs.getBoolean(PREF_COLORED_LABELS));
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.APPEARANCE_PREFERENCE_PAGE);
- }
-
- /*
- * @see PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- initializeDialogUnits(parent);
- int nColumns= 1;
-
- Composite result= new Composite(parent, SWT.NONE);
- result.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= 0;
- layout.numColumns= nColumns;
- result.setLayout(layout);
-
- fShowMethodReturnType.doFillIntoGrid(result, nColumns);
-// fShowMethodTypeParameters.doFillIntoGrid(result, nColumns);
- fShowCategory.doFillIntoGrid(result, nColumns);
- fShowMembersInPackageView.doFillIntoGrid(result, nColumns);
- fShowColoredLabels.doFillIntoGrid(result, nColumns);
- fFoldPackagesInPackageExplorer.doFillIntoGrid(result, nColumns);
-
-// new Separator().doFillIntoGrid(result, nColumns);
-
-// fCompressPackageNames.doFillIntoGrid(result, nColumns);
-// fPackageNamePattern.doFillIntoGrid(result, 2);
-// LayoutUtil.setHorizontalGrabbing(fPackageNamePattern.getTextControl(null));
-// LayoutUtil.setWidthHint(fPackageNamePattern.getLabelControl(null), convertWidthInCharsToPixels(65));
-
-// new Separator().doFillIntoGrid(result, nColumns);
-// fStackBrowsingViewsVertically.doFillIntoGrid(result, nColumns);
-
-// String noteTitle= PreferencesMessages.AppearancePreferencePage_note;
-// String noteMessage= PreferencesMessages.AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives;
-// Composite noteControl= createNoteComposite(JFaceResources.getDialogFont(), result, noteTitle, noteMessage);
-// GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
-// gd.horizontalSpan= 2;
-// noteControl.setLayoutData(gd);
-
- initFields();
-
- Dialog.applyDialogFont(result);
- return result;
- }
-
- private void doDialogFieldChanged(DialogField field) {
-// if (field == fCompressPackageNames)
-// fPackageNamePattern.setEnabled(fCompressPackageNames.isSelected());
-
- updateStatus(getValidationStatus());
- }
-
- private IStatus getValidationStatus(){
-// if (fCompressPackageNames.isSelected() && fPackageNamePattern.getText().equals("")) //$NON-NLS-1$
-// return new StatusInfo(IStatus.ERROR, PreferencesMessages.AppearancePreferencePage_packageNameCompressionPattern_error_isEmpty);
-// else
- return new StatusInfo();
- }
-
- private void updateStatus(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
- /*
- * @see IWorkbenchPreferencePage#init(IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore prefs= getPreferenceStore();
- prefs.setValue(PREF_METHOD_RETURNTYPE, fShowMethodReturnType.isSelected());
-// prefs.setValue(PREF_METHOD_TYPEPARAMETERS, fShowMethodTypeParameters.isSelected());
- prefs.setValue(PREF_CATEGORY, fShowCategory.isSelected());
- prefs.setValue(SHOW_CU_CHILDREN, fShowMembersInPackageView.isSelected());
-// prefs.setValue(STACK_BROWSING_VIEWS_VERTICALLY, fStackBrowsingViewsVertically.isSelected());
-// prefs.setValue(PREF_PKG_NAME_PATTERN_FOR_PKG_VIEW, fPackageNamePattern.getText());
-// prefs.setValue(PREF_COMPRESS_PACKAGE_NAMES, fCompressPackageNames.isSelected());
- prefs.setValue(PREF_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, fFoldPackagesInPackageExplorer.isSelected());
- prefs.setValue(PREF_COLORED_LABELS, fShowColoredLabels.isSelected());
- JavaScriptPlugin.getDefault().savePluginPreferences();
- return super.performOk();
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore prefs= getPreferenceStore();
- fShowMethodReturnType.setSelection(prefs.getDefaultBoolean(PREF_METHOD_RETURNTYPE));
-// fShowMethodTypeParameters.setSelection(prefs.getDefaultBoolean(PREF_METHOD_TYPEPARAMETERS));
- fShowCategory.setSelection(prefs.getDefaultBoolean(PREF_CATEGORY));
- fShowMembersInPackageView.setSelection(prefs.getDefaultBoolean(SHOW_CU_CHILDREN));
-// fStackBrowsingViewsVertically.setSelection(prefs.getDefaultBoolean(STACK_BROWSING_VIEWS_VERTICALLY));
-// fPackageNamePattern.setText(prefs.getDefaultString(PREF_PKG_NAME_PATTERN_FOR_PKG_VIEW));
-// fCompressPackageNames.setSelection(prefs.getDefaultBoolean(PREF_COMPRESS_PACKAGE_NAMES));
- fFoldPackagesInPackageExplorer.setSelection(prefs.getDefaultBoolean(PREF_FOLD_PACKAGES_IN_PACKAGE_EXPLORER));
- fShowColoredLabels.setSelection(false);
- super.performDefaults();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java
deleted file mode 100644
index 8d92e0cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-
-/**
- * Property page for configuring the Java build path
- */
-public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener {
-
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.BuildPathsPropertyPage"; //$NON-NLS-1$
-
- private static final String PAGE_SETTINGS= "BuildPathsPropertyPage"; //$NON-NLS-1$
- private static final String INDEX= "pageIndex"; //$NON-NLS-1$
-
- public static final Object DATA_ADD_ENTRY= "add_classpath_entry"; //$NON-NLS-1$
-
- public static final Object DATA_REVEAL_ENTRY= "select_classpath_entry"; //$NON-NLS-1$
- public static final Object DATA_REVEAL_ATTRIBUTE_KEY= "select_classpath_attribute_key"; //$NON-NLS-1$
- public static final String DATA_PAGE_INDEX= "pageIndex"; //$NON-NLS-1$
-
- public static final Object DATA_BLOCK= "block_until_buildpath_applied"; //$NON-NLS-1$
-
- private BuildPathsBlock fBuildPathsBlock;
- private boolean fBlockOnApply= false;
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- protected Control createContents(Composite parent) {
- // ensure the page has no special buttons
- noDefaultAndApplyButton();
-
- IProject project= getProject();
- Control result;
- if (project == null || !isJavaProject(project)) {
- result= createWithoutJava(parent);
- } else if (!project.isOpen()) {
- result= createForClosedProject(parent);
- } else {
- result= createWithJava(parent, project);
- }
- Dialog.applyDialogFont(result);
- return result;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.BUILD_PATH_PROPERTY_PAGE);
- }
-
- private IDialogSettings getSettings() {
- IDialogSettings javaSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- IDialogSettings pageSettings= javaSettings.getSection(PAGE_SETTINGS);
- if (pageSettings == null) {
- pageSettings= javaSettings.addNewSection(PAGE_SETTINGS);
- pageSettings.put(INDEX, 0);
- }
- return pageSettings;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- if (fBuildPathsBlock != null) {
- if (!visible) {
- fBuildPathsBlock.aboutToDispose();
- if (fBuildPathsBlock.hasChangesInDialog()) {
- String title= PreferencesMessages.BuildPathsPropertyPage_unsavedchanges_title;
- String message= PreferencesMessages.BuildPathsPropertyPage_unsavedchanges_message;
- String[] buttonLabels= new String[] {
- PreferencesMessages.BuildPathsPropertyPage_unsavedchanges_button_save,
- PreferencesMessages.BuildPathsPropertyPage_unsavedchanges_button_discard,
- PreferencesMessages.BuildPathsPropertyPage_unsavedchanges_button_ignore
- };
- MessageDialog dialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
- int res= dialog.open();
- if (res == 0) {
- performOk();
- } else if (res == 1) {
- fBuildPathsBlock.init(JavaScriptCore.create(getProject()), null);
- } else {
- // keep unsaved
- }
- }
- } else {
- fBuildPathsBlock.aboutToShow();
- if (!fBuildPathsBlock.hasChangesInDialog() && fBuildPathsBlock.hasChangesInClasspathFile()) {
- fBuildPathsBlock.init(JavaScriptCore.create(getProject()), null);
- }
- }
- }
- super.setVisible(visible);
- }
-
-
- /*
- * Content for valid projects.
- */
- private Control createWithJava(Composite parent, IProject project) {
- IWorkbenchPreferenceContainer pageContainer= null;
- IPreferencePageContainer container= getContainer();
- if (container instanceof IWorkbenchPreferenceContainer) {
- pageContainer= (IWorkbenchPreferenceContainer) container;
- }
-
- fBuildPathsBlock= new BuildPathsBlock(new BusyIndicatorRunnableContext(), this, getSettings().getInt(INDEX), false, pageContainer);
- fBuildPathsBlock.init(JavaScriptCore.create(project), null);
- return fBuildPathsBlock.createControl(parent);
- }
-
- /*
- * Content for non-Java projects.
- */
- private Control createWithoutJava(Composite parent) {
- Label label= new Label(parent, SWT.LEFT);
- label.setText(PreferencesMessages.BuildPathsPropertyPage_no_java_project_message);
-
- fBuildPathsBlock= null;
- setValid(true);
- return label;
- }
-
- /*
- * Content for closed projects.
- */
- private Control createForClosedProject(Composite parent) {
- Label label= new Label(parent, SWT.LEFT);
- label.setText(PreferencesMessages.BuildPathsPropertyPage_closed_project_message);
-
- fBuildPathsBlock= null;
- setValid(true);
- return label;
- }
-
- private IProject getProject() {
- IAdaptable adaptable= getElement();
- if (adaptable != null) {
- IProject elem= (IProject) adaptable.getAdapter(IProject.class);
- if(elem!=null) return elem;
- }
- return null;
- }
-
- private boolean isJavaProject(IProject proj) {
- try {
- return proj.hasNature(JavaScriptCore.NATURE_ID);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-
- /*
- * @see IPreferencePage#performOk
- */
- public boolean performOk() {
- if (fBuildPathsBlock != null) {
- fBuildPathsBlock.aboutToDispose();
- getSettings().put(INDEX, fBuildPathsBlock.getPageIndex());
- if (fBuildPathsBlock.hasChangesInDialog() || fBuildPathsBlock.isClassfileMissing() || fBuildPathsBlock.hasChangesInSuper()) {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- fBuildPathsBlock.configureJavaProject(monitor);
- }
- };
- WorkbenchRunnableAdapter op= new WorkbenchRunnableAdapter(runnable);
- if (fBlockOnApply) {
- try {
- new ProgressMonitorDialog(getShell()).run(true, true, op);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), PreferencesMessages.BuildPathsPropertyPage_error_title, PreferencesMessages.BuildPathsPropertyPage_error_message);
- return false;
- } catch (InterruptedException e) {
- return false;
- }
- } else {
- op.runAsUserJob(PreferencesMessages.BuildPathsPropertyPage_job_title, null);
- }
- }
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see IStatusChangeListener#statusChanged
- */
- public void statusChanged(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
- */
- public void applyData(Object data) {
- if (data instanceof Map) {
- Map map= (Map) data;
- Object selectedLibrary= map.get(DATA_REVEAL_ENTRY);
- if (selectedLibrary instanceof IIncludePathEntry) {
- IIncludePathEntry entry= (IIncludePathEntry) selectedLibrary;
- Object attr= map.get(DATA_REVEAL_ATTRIBUTE_KEY);
- String attributeKey= attr instanceof String ? (String) attr : null;
- if (fBuildPathsBlock != null) {
- fBuildPathsBlock.setElementToReveal(entry, attributeKey);
- }
- }
- Object entryToAdd= map.get(DATA_ADD_ENTRY);
- if (entryToAdd instanceof IIncludePathEntry) {
- if (fBuildPathsBlock != null) {
- fBuildPathsBlock.addElement((IIncludePathEntry) entryToAdd);
- }
- }
-
- Object pageIndex = map.get(DATA_PAGE_INDEX);
-
- if(pageIndex instanceof Integer) {
- fBuildPathsBlock.showPage(((Integer)pageIndex).intValue());
- }
-
- fBlockOnApply= Boolean.TRUE.equals(map.get(DATA_BLOCK));
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BulletListBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BulletListBlock.java
deleted file mode 100644
index b868c1a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BulletListBlock.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.Bullet;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GlyphMetrics;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * Each line of the given text is preceded by a bullet.
- */
-public class BulletListBlock {
-
- private StyledText fStyledText;
- private boolean fEnabled;
- private String fText;
-
- public BulletListBlock() {
- fEnabled= true;
- fText= ""; //$NON-NLS-1$
- }
-
- public Control createControl(Composite parent) {
- fStyledText= new StyledText(parent, SWT.FLAT | SWT.BORDER | SWT.READ_ONLY);
-
- final GridData data= new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
- fStyledText.setLayoutData(data);
- configureStyledText(fText, fEnabled);
-
- return fStyledText;
- }
-
- public void setText(String text) {
- fText= text;
- configureStyledText(fText, fEnabled);
- }
-
- public void setEnabled(boolean enabled) {
- fEnabled= enabled;
- configureStyledText(fText, fEnabled);
- }
-
- private void configureStyledText(String text, boolean enabled) {
- if (fStyledText == null)
- return;
-
- fStyledText.setText(text);
- int count= fStyledText.getCharCount();
- if (count == 0)
- return;
-
- Color foreground= enabled ? null : Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY);
-
- fStyledText.setStyleRange(new StyleRange(0, count, foreground, null));
-
- StyleRange styleRange= new StyleRange(0, count, foreground, null);
- styleRange.metrics= new GlyphMetrics(0, 0, 20);
- fStyledText.setLineBullet(0, fStyledText.getLineCount(), new Bullet(styleRange));
-
- fStyledText.setEnabled(enabled);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CleanUpPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CleanUpPreferencePage.java
deleted file mode 100644
index 8ee7ce9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CleanUpPreferencePage.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpConfigurationBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileConfigurationBlock;
-
-/*
- * The page to configure the clean up options.
- */
-public class CleanUpPreferencePage extends ProfilePreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CleanUpPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CleanUpPreferencePage"; //$NON-NLS-1$
-
- public CleanUpPreferencePage() {
- // only used when page is shown programmatically
- setTitle(PreferencesMessages.CleanUpPreferencePage_Title );
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.ProfilePreferencePage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
-// PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
- }
-
- protected ProfileConfigurationBlock createConfigurationBlock(PreferencesAccess access) {
- return new CleanUpConfigurationBlock(getProject(), access);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedConfigurationBlock.java
deleted file mode 100644
index 7a276fd9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedConfigurationBlock.java
+++ /dev/null
@@ -1,768 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.CommandManager;
-import org.eclipse.core.commands.IParameter;
-import org.eclipse.core.commands.Parameterization;
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.core.commands.common.NotDefinedException;
-import org.eclipse.core.commands.contexts.ContextManager;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.bindings.BindingManager;
-import org.eclipse.jface.bindings.Scheme;
-import org.eclipse.jface.bindings.TriggerSequence;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalCategory;
-import org.eclipse.wst.jsdt.internal.ui.text.java.CompletionProposalComputerRegistry;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- *
- *
- */
-final class CodeAssistAdvancedConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final Key PREF_EXCLUDED_CATEGORIES= getJDTUIKey(PreferenceConstants.CODEASSIST_EXCLUDED_CATEGORIES);
- private static final Key PREF_CATEGORY_ORDER= getJDTUIKey(PreferenceConstants.CODEASSIST_CATEGORY_ORDER);
- private static final Key PREF_CODEASSIST_TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC= getJDTCoreKey(JavaScriptCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC);
-
- private static Key[] getAllKeys() {
- return new Key[] {
- PREF_EXCLUDED_CATEGORIES,
- PREF_CATEGORY_ORDER,
- PREF_CODEASSIST_TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC
- };
- }
-
- private final class DefaultTableLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0)
- return ((ModelElement) element).getImage();
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- switch (columnIndex) {
- case 0:
- return ((ModelElement) element).getName();
- case 1:
- return ((ModelElement) element).getKeybindingAsString();
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- return getColumnText(element, 0); // needed to make the sorter work
- }
- }
-
- private final class SeparateTableLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0)
- return ((ModelElement) element).getImage();
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- switch (columnIndex) {
- case 0:
- return ((ModelElement) element).getName();
- default:
- Assert.isTrue(false);
- return null;
- }
- }
- }
-
- private final Comparator fCategoryComparator= new Comparator() {
- private int getRank(Object o) {
- return ((ModelElement) o).getRank();
- }
-
- public int compare(Object o1, Object o2) {
- return getRank(o1) - getRank(o2);
- }
- };
-
- private final class PreferenceModel {
- private static final int LIMIT= 0xffff;
- private static final String COLON= ":"; //$NON-NLS-1$
- private static final String SEPARATOR= "\0"; //$NON-NLS-1$
-
- private final List fElements;
- /**
- * The read-only list of elements.
- */
- final List elements;
-
- public PreferenceModel(CompletionProposalComputerRegistry registry) {
- List categories= registry.getProposalCategories();
- fElements= new ArrayList();
- for (Iterator it= categories.iterator(); it.hasNext();) {
- CompletionProposalCategory category= (CompletionProposalCategory) it.next();
- if (category.hasComputers()) {
- fElements.add(new ModelElement(category, this));
- }
- }
- Collections.sort(fElements, fCategoryComparator);
- elements= Collections.unmodifiableList(fElements);
- }
-
- public void moveUp(ModelElement category) {
- int index= fElements.indexOf(category);
- if (index > 0) {
- Object item= fElements.remove(index);
- fElements.add(index - 1, item);
- writeOrderPreference(null, false);
- }
- }
-
- public void moveDown(ModelElement category) {
- int index= fElements.indexOf(category);
- if (index < fElements.size() - 1) {
- Object item= fElements.remove(index);
- fElements.add(index + 1, item);
- writeOrderPreference(null, false);
- }
- }
-
- private void writeInclusionPreference(ModelElement changed, boolean isInDefaultCategory) {
- StringBuffer buf= new StringBuffer();
- for (Iterator it= fElements.iterator(); it.hasNext();) {
- ModelElement item= (ModelElement) it.next();
- boolean included= changed == item ? isInDefaultCategory : item.isInDefaultCategory();
- if (!included)
- buf.append(item.getId() + SEPARATOR);
- }
-
- String newValue= buf.toString();
- String oldValue= setValue(PREF_EXCLUDED_CATEGORIES, newValue);
- validateSettings(PREF_EXCLUDED_CATEGORIES, oldValue, newValue);
- }
-
- private void writeOrderPreference(ModelElement changed, boolean isSeparate) {
- StringBuffer buf= new StringBuffer();
- int i= 0;
- for (Iterator it= fElements.iterator(); it.hasNext(); i++) {
- ModelElement item= (ModelElement) it.next();
- boolean separate= changed == item ? isSeparate : item.isSeparateCommand();
- int rank= separate ? i : i + LIMIT;
- buf.append(item.getId() + COLON + rank + SEPARATOR);
- }
-
- String newValue= buf.toString();
- String oldValue= setValue(PREF_CATEGORY_ORDER, newValue);
- validateSettings(PREF_CATEGORY_ORDER, oldValue, newValue);
- }
-
-
- private boolean readInclusionPreference(CompletionProposalCategory cat) {
- String[] ids= getTokens(getValue(PREF_EXCLUDED_CATEGORIES), SEPARATOR);
- for (int i= 0; i < ids.length; i++) {
- if (ids[i].equals(cat.getId()))
- return false;
- }
- return true;
- }
-
- private int readOrderPreference(CompletionProposalCategory cat) {
- String[] sortOrderIds= getTokens(getValue(PREF_CATEGORY_ORDER), SEPARATOR);
- for (int i= 0; i < sortOrderIds.length; i++) {
- String[] idAndRank= getTokens(sortOrderIds[i], COLON);
- if (idAndRank[0].equals(cat.getId()))
- return Integer.parseInt(idAndRank[1]);
- }
- return LIMIT + 1;
- }
-
- public void update() {
- Collections.sort(fElements, fCategoryComparator);
- }
- }
-
- private final class ModelElement {
- private final CompletionProposalCategory fCategory;
- private final Command fCommand;
- private final IParameter fParam;
- private final PreferenceModel fPreferenceModel;
-
- ModelElement(CompletionProposalCategory category, PreferenceModel model) {
- fCategory= category;
- ICommandService commandSvc= (ICommandService) PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- fCommand= commandSvc.getCommand("org.eclipse.wst.jsdt.ui.specific_content_assist.command"); //$NON-NLS-1$
- IParameter type;
- try {
- type= fCommand.getParameters()[0];
- } catch (NotDefinedException x) {
- Assert.isTrue(false);
- type= null;
- }
- fParam= type;
- fPreferenceModel= model;
- }
- Image getImage() {
- return CodeAssistAdvancedConfigurationBlock.this.getImage(fCategory.getImageDescriptor());
- }
- String getName() {
- return fCategory.getDisplayName();
- }
- String getKeybindingAsString() {
- final Parameterization[] params= { new Parameterization(fParam, fCategory.getId()) };
- final ParameterizedCommand pCmd= new ParameterizedCommand(fCommand, params);
- String key= getKeyboardShortcut(pCmd);
- return key;
- }
- boolean isInDefaultCategory() {
- return fPreferenceModel.readInclusionPreference(fCategory);
- }
- void setInDefaultCategory(boolean included) {
- if (included != isInDefaultCategory())
- fPreferenceModel.writeInclusionPreference(this, included);
- }
- String getId() {
- return fCategory.getId();
- }
- int getRank() {
- int rank= getInternalRank();
- if (rank > PreferenceModel.LIMIT)
- return rank - PreferenceModel.LIMIT;
- return rank;
- }
- void moveUp() {
- fPreferenceModel.moveUp(this);
- }
- void moveDown() {
- fPreferenceModel.moveDown(this);
- }
- private int getInternalRank() {
- return fPreferenceModel.readOrderPreference(fCategory);
- }
- boolean isSeparateCommand() {
- return getInternalRank() < PreferenceModel.LIMIT;
- }
-
- void setSeparateCommand(boolean separate) {
- if (separate != isSeparateCommand())
- fPreferenceModel.writeOrderPreference(this, separate);
- }
-
- void update() {
- fCategory.setIncluded(isInDefaultCategory());
- int rank= getInternalRank();
- fCategory.setSortOrder(rank);
- fCategory.setSeparateCommand(rank < PreferenceModel.LIMIT);
- }
- }
-
- /** element type: {@link ModelElement}. */
- private final PreferenceModel fModel;
- private final Map fImages= new HashMap();
-
- private CheckboxTableViewer fDefaultViewer;
- private CheckboxTableViewer fSeparateViewer;
- private Button fUpButton;
- private Button fDownButton;
-
- CodeAssistAdvancedConfigurationBlock(IStatusChangeListener statusListener, IWorkbenchPreferenceContainer container) {
- super(statusListener, null, getAllKeys(), container);
- fModel= new PreferenceModel(CompletionProposalComputerRegistry.getDefault());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
-
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
-
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Composite composite= new Composite(scrolled, SWT.NONE);
- int columns= 2;
- GridLayout layout= new GridLayout(columns, false);
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
-
- createDefaultLabel(composite, columns);
- createDefaultViewer(composite, columns);
- createKeysLink(composite, columns);
-
- createFiller(composite, columns);
-
- createSeparateLabel(composite, columns);
- createSeparateSection(composite);
-
- createFiller(composite, columns);
-
- createParameterTimeoutControl(composite, columns);
-
- updateControls();
- if (fModel.elements.size() > 0) {
- fDefaultViewer.getTable().select(0);
- fSeparateViewer.getTable().select(0);
- handleTableSelection();
- }
-
- scrolled.setContent(composite);
- scrolled.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- return scrolled;
- }
-
- private void createDefaultLabel(Composite composite, int h_span) {
- final ICommandService commandSvc= (ICommandService) PlatformUI.getWorkbench().getAdapter(ICommandService.class);
- final Command command= commandSvc.getCommand(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- ParameterizedCommand pCmd= new ParameterizedCommand(command, null);
- String key= getKeyboardShortcut(pCmd);
- if (key == null)
- key= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_no_shortcut;
-
- PixelConverter pixelConverter= new PixelConverter(composite);
- int width= pixelConverter.convertWidthInCharsToPixels(40);
-
- Label label= new Label(composite, SWT.NONE | SWT.WRAP);
- label.setText(Messages.format(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_page_description, new Object[] { key }));
- GridData gd= new GridData(GridData.FILL, GridData.FILL, true, false, h_span, 1);
- gd.widthHint= width;
- label.setLayoutData(gd);
-
- createFiller(composite, h_span);
-
- label= new Label(composite, SWT.NONE | SWT.WRAP);
- label.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_default_table_description);
- gd= new GridData(GridData.FILL, GridData.FILL, true, false, h_span, 1);
- gd.widthHint= width;
- label.setLayoutData(gd);
- }
-
- private void createDefaultViewer(Composite composite, int h_span) {
- fDefaultViewer= CheckboxTableViewer.newCheckList(composite, SWT.SINGLE | SWT.BORDER);
- Table table= fDefaultViewer.getTable();
- table.setHeaderVisible(true);
- table.setLinesVisible(false);
- table.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false, h_span, 1));
-
- TableColumn nameColumn= new TableColumn(table, SWT.NONE);
- nameColumn.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_default_table_category_column_title);
- nameColumn.setResizable(false);
- TableColumn keyColumn= new TableColumn(table, SWT.NONE);
- keyColumn.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title);
- keyColumn.setResizable(false);
-
- fDefaultViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- boolean checked= event.getChecked();
- ModelElement element= (ModelElement) event.getElement();
- element.setInDefaultCategory(checked);
- }
- });
-
- fDefaultViewer.setContentProvider(new ArrayContentProvider());
-
- DefaultTableLabelProvider labelProvider= new DefaultTableLabelProvider();
- fDefaultViewer.setLabelProvider(labelProvider);
- fDefaultViewer.setInput(fModel.elements);
- fDefaultViewer.setComparator(new ViewerComparator()); // sort alphabetically
-
- final int ICON_AND_CHECKBOX_WITH= 50;
- final int HEADER_MARGIN= 20;
- int minNameWidth= computeWidth(table, nameColumn.getText()) + HEADER_MARGIN;
- int minKeyWidth= computeWidth(table, keyColumn.getText()) + HEADER_MARGIN;
- for (int i= 0; i < fModel.elements.size(); i++) {
- minNameWidth= Math.max(minNameWidth, computeWidth(table, labelProvider.getColumnText(fModel.elements.get(i), 0)) + ICON_AND_CHECKBOX_WITH);
- minKeyWidth= Math.max(minKeyWidth, computeWidth(table, labelProvider.getColumnText(fModel.elements.get(i), 1)));
- }
-
- nameColumn.setWidth(minNameWidth);
- keyColumn.setWidth(minKeyWidth);
- }
-
- private void createKeysLink(Composite composite, int h_span) {
- Link link= new Link(composite, SWT.NONE | SWT.WRAP);
- link.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_key_binding_hint);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(getShell(), e.text, null, null);
- }
- });
-
- PixelConverter pixelConverter= new PixelConverter(composite);
- int width= pixelConverter.convertWidthInCharsToPixels(40);
-
- // limit the size of the Link as it would take all it can get
- GridData gd= new GridData(GridData.FILL, GridData.FILL, false, false, h_span, 1);
- gd.widthHint= width;
- link.setLayoutData(gd);
- }
-
- private void createFiller(Composite composite, int h_span) {
- Label filler= new Label(composite, SWT.NONE);
- filler.setVisible(false);
- filler.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, h_span, 1));
- }
-
- private void createSeparateLabel(Composite composite, int h_span) {
- PixelConverter pixelConverter= new PixelConverter(composite);
- int width= pixelConverter.convertWidthInCharsToPixels(40);
-
- Label label= new Label(composite, SWT.NONE | SWT.WRAP);
- label.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_separate_table_description);
- GridData gd= new GridData(GridData.FILL, GridData.FILL, false, false, h_span, 1);
- gd.widthHint= width;
- label.setLayoutData(gd);
- }
-
- private void createSeparateSection(Composite composite) {
- createSeparateViewer(composite);
- createButtonList(composite);
- }
-
- private void createSeparateViewer(Composite composite) {
- fSeparateViewer= CheckboxTableViewer.newCheckList(composite, SWT.SINGLE | SWT.BORDER);
- Table table= fSeparateViewer.getTable();
- table.setHeaderVisible(false);
- table.setLinesVisible(false);
- table.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false, 1, 1));
-
- TableColumn nameColumn= new TableColumn(table, SWT.NONE);
- nameColumn.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title);
- nameColumn.setResizable(false);
-
- fSeparateViewer.setContentProvider(new ArrayContentProvider());
-
- ITableLabelProvider labelProvider= new SeparateTableLabelProvider();
- fSeparateViewer.setLabelProvider(labelProvider);
- fSeparateViewer.setInput(fModel.elements);
-
- final int ICON_AND_CHECKBOX_WITH= 50;
- final int HEADER_MARGIN= 20;
- int minNameWidth= computeWidth(table, nameColumn.getText()) + HEADER_MARGIN;
- for (int i= 0; i < fModel.elements.size(); i++) {
- minNameWidth= Math.max(minNameWidth, computeWidth(table, labelProvider.getColumnText(fModel.elements.get(i), 0)) + ICON_AND_CHECKBOX_WITH);
- }
-
- nameColumn.setWidth(minNameWidth);
-
- fSeparateViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- boolean checked= event.getChecked();
- ModelElement element= (ModelElement) event.getElement();
- element.setSeparateCommand(checked);
- }
- });
-
- table.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleTableSelection();
- }
- });
-
- }
-
- private void createButtonList(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- fUpButton= new Button(composite, SWT.PUSH | SWT.CENTER);
- fUpButton.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_Up);
- fUpButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int index= getSelectionIndex();
- if (index != -1) {
- ((ModelElement) fModel.elements.get(index)).moveUp();
- fSeparateViewer.refresh();
- handleTableSelection();
- }
- }
- });
- fUpButton.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(fUpButton);
-
- fDownButton= new Button(composite, SWT.PUSH | SWT.CENTER);
- fDownButton.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_Down);
- fDownButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int index= getSelectionIndex();
- if (index != -1) {
- ((ModelElement) fModel.elements.get(index)).moveDown();
- fSeparateViewer.refresh();
- handleTableSelection();
- }
- }
- });
- fDownButton.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(fDownButton);
- }
-
- private void createParameterTimeoutControl(Composite composite, int h_span) {
- Composite timeoutComposite= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout(4, false);
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- timeoutComposite.setLayout(layout);
- GridData gd= new GridData(GridData.FILL, GridData.FILL, true, false, h_span, 1);
- timeoutComposite.setLayoutData(gd);
-
- PixelConverter pixelConverter= new PixelConverter(composite);
- String str= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout;
- addTextField(timeoutComposite, str, PREF_CODEASSIST_TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, 0, pixelConverter.convertWidthInCharsToPixels(7));
-
- Label ms= new Label(timeoutComposite, SWT.NONE);
- gd= new GridData();
- ms.setLayoutData(gd);
- ms.setText(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_ms);
-
- }
-
- private void handleTableSelection() {
- ModelElement item= getSelectedItem();
- if (item != null) {
- int index= getSelectionIndex();
- fUpButton.setEnabled(index > 0);
- fDownButton.setEnabled(index < fModel.elements.size() - 1);
- } else {
- fUpButton.setEnabled(false);
- fDownButton.setEnabled(false);
- }
- }
-
- private ModelElement getSelectedItem() {
- return (ModelElement) ((IStructuredSelection) fSeparateViewer.getSelection()).getFirstElement();
- }
-
- private int getSelectionIndex() {
- return fSeparateViewer.getTable().getSelectionIndex();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
- */
- protected void updateControls() {
- super.updateControls();
-
- fModel.update();
- updateCheckedState();
- fDefaultViewer.refresh();
- fSeparateViewer.refresh();
- handleTableSelection();
- }
-
- private void updateCheckedState() {
- final int size= fModel.elements.size();
- List defaultChecked= new ArrayList(size);
- List separateChecked= new ArrayList(size);
-
- for (Iterator it= fModel.elements.iterator(); it.hasNext();) {
- ModelElement element= (ModelElement) it.next();
- if (element.isInDefaultCategory())
- defaultChecked.add(element);
- if (element.isSeparateCommand())
- separateChecked.add(element);
- }
-
- fDefaultViewer.setCheckedElements(defaultChecked.toArray(new Object[defaultChecked.size()]));
- fSeparateViewer.setCheckedElements(separateChecked.toArray(new Object[separateChecked.size()]));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#processChanges(org.eclipse.ui.preferences.IWorkbenchPreferenceContainer)
- */
- protected boolean processChanges(IWorkbenchPreferenceContainer container) {
- for (Iterator it= fModel.elements.iterator(); it.hasNext();) {
- ModelElement item= (ModelElement) it.next();
- item.update();
- }
-
- return super.processChanges(container);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock.Key, java.lang.String, java.lang.String)
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (changedKey == PREF_CODEASSIST_TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC) {
- final StatusInfo status= new StatusInfo();
- if (newValue.length() == 0)
- status.setError(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_emptyInput);
- else {
- try {
- int number= Integer.parseInt(newValue);
- int min= 0;
- int max= 5000;
- if (number < min || number > max) {
- String msgFormat= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidRange;
- String msg= Messages.format(msgFormat, new Object[] {new Integer(min), new Integer(max)});
- status.setError(msg);
- }
- } catch (NumberFormatException ex) {
- String msgFormat= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidInput;
- String msg= Messages.format(msgFormat, newValue);
- status.setError(msg);
- }
- }
- fContext.statusChanged(status);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
- */
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- // no builds triggered by our settings
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#dispose()
- */
- public void dispose() {
- for (Iterator it= fImages.values().iterator(); it.hasNext();) {
- Image image= (Image) it.next();
- image.dispose();
- }
-
- super.dispose();
- }
-
- private int computeWidth(Control control, String name) {
- if (name == null)
- return 0;
- GC gc= new GC(control);
- try {
- gc.setFont(JFaceResources.getDialogFont());
- return gc.stringExtent(name).x + 10;
- } finally {
- gc.dispose();
- }
- }
-
- private static BindingManager fgLocalBindingManager;
- static {
- fgLocalBindingManager= new BindingManager(new ContextManager(), new CommandManager());
- final IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getService(IBindingService.class);
- final Scheme[] definedSchemes= bindingService.getDefinedSchemes();
- if (definedSchemes != null) {
- try {
- for (int i = 0; i < definedSchemes.length; i++) {
- final Scheme scheme= definedSchemes[i];
- final Scheme copy= fgLocalBindingManager.getScheme(scheme.getId());
- copy.define(scheme.getName(), scheme.getDescription(), scheme.getParentId());
- }
- } catch (final NotDefinedException e) {
- JavaScriptPlugin.log(e);
- }
- }
- fgLocalBindingManager.setLocale(bindingService.getLocale());
- fgLocalBindingManager.setPlatform(bindingService.getPlatform());
- }
-
- private static String getKeyboardShortcut(ParameterizedCommand command) {
- IBindingService bindingService= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- fgLocalBindingManager.setBindings(bindingService.getBindings());
- try {
- Scheme activeScheme= bindingService.getActiveScheme();
- if (activeScheme != null)
- fgLocalBindingManager.setActiveScheme(activeScheme);
- } catch (NotDefinedException e) {
- JavaScriptPlugin.log(e);
- }
-
- TriggerSequence[] bindings= fgLocalBindingManager.getActiveBindingsDisregardingContextFor(command);
- if (bindings.length > 0)
- return bindings[0].format();
- return null;
- }
-
- private Image getImage(ImageDescriptor imgDesc) {
- if (imgDesc == null)
- return null;
-
- Image img= (Image) fImages.get(imgDesc);
- if (img == null) {
- img= imgDesc.createImage(false);
- fImages.put(imgDesc, img);
- }
- return img;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedPreferencePage.java
deleted file mode 100644
index 66173071..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistAdvancedPreferencePage.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-public final class CodeAssistAdvancedPreferencePage extends PropertyAndPreferencePage {
-
- private CodeAssistAdvancedConfigurationBlock fConfigurationBlock;
-
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new CodeAssistAdvancedConfigurationBlock(getNewStatusChangedListener(), container);
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return false;
- }
-
- protected String getPreferencePageID() {
- return "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced"; //$NON-NLS-1$
- }
-
- protected String getPropertyPageID() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistConfigurationBlock.java
deleted file mode 100644
index 85636133..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistConfigurationBlock.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ProposalSorterHandle;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ProposalSorterRegistry;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Configures the content assist preferences.
- *
- *
- */
-class CodeAssistConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final Key PREF_CODEASSIST_AUTOACTIVATION= getJDTUIKey(PreferenceConstants.CODEASSIST_AUTOACTIVATION);
- private static final Key PREF_CODEASSIST_AUTOACTIVATION_DELAY= getJDTUIKey(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY);
- private static final Key PREF_CODEASSIST_AUTOINSERT= getJDTUIKey(PreferenceConstants.CODEASSIST_AUTOINSERT);
- private static final Key PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= getJDTUIKey(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
- private static final Key PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= getJDTUIKey(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC);
- private static final Key PREF_CODEASSIST_SHOW_VISIBLE_PROPOSALS= getJDTUIKey(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS);
- private static final Key PREF_CODEASSIST_SORTER= getJDTUIKey(PreferenceConstants.CODEASSIST_SORTER);
- private static final Key PREF_CODEASSIST_CASE_SENSITIVITY= getJDTUIKey(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY);
- private static final Key PREF_CODEASSIST_ADDIMPORT= getJDTUIKey(PreferenceConstants.CODEASSIST_ADDIMPORT);
- private static final Key PREF_CODEASSIST_SUGGEST_STATIC_IMPORTS= getJDTCoreKey(JavaScriptCore.CODEASSIST_SUGGEST_STATIC_IMPORTS);
- private static final Key PREF_CODEASSIST_INSERT_COMPLETION= getJDTUIKey(PreferenceConstants.CODEASSIST_INSERT_COMPLETION);
- private static final Key PREF_CODEASSIST_FILL_ARGUMENT_NAMES= getJDTUIKey(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES);
- private static final Key PREF_CODEASSIST_GUESS_METHOD_ARGUMENTS= getJDTUIKey(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS);
- private static final Key PREF_CODEASSIST_PREFIX_COMPLETION= getJDTUIKey(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION);
- private static final Key PREF_CODEASSIST_FORBIDDEN_REFERENCE_CHECK= getJDTCoreKey(JavaScriptCore.CODEASSIST_FORBIDDEN_REFERENCE_CHECK);
- private static final Key PREF_CODEASSIST_DISCOURAGED_REFERENCE_CHECK= getJDTCoreKey(JavaScriptCore.CODEASSIST_DISCOURAGED_REFERENCE_CHECK);
- private static final Key PREF_CODEASSIST_DEPRECATION_CHECK= getJDTCoreKey(JavaScriptCore.CODEASSIST_DEPRECATION_CHECK);
- private static final Key PREF_CODEASSIST_CAMEL_CASE_MATCH= getJDTCoreKey(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH);
-
- private static Key[] getAllKeys() {
- return new Key[] {
- PREF_CODEASSIST_AUTOACTIVATION,
- PREF_CODEASSIST_AUTOACTIVATION_DELAY,
- PREF_CODEASSIST_AUTOINSERT,
- PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA,
- PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC,
- PREF_CODEASSIST_SHOW_VISIBLE_PROPOSALS,
- PREF_CODEASSIST_SORTER,
- PREF_CODEASSIST_CASE_SENSITIVITY,
- PREF_CODEASSIST_ADDIMPORT,
- PREF_CODEASSIST_SUGGEST_STATIC_IMPORTS,
- PREF_CODEASSIST_INSERT_COMPLETION,
- PREF_CODEASSIST_FILL_ARGUMENT_NAMES,
- PREF_CODEASSIST_GUESS_METHOD_ARGUMENTS,
- PREF_CODEASSIST_PREFIX_COMPLETION,
- PREF_CODEASSIST_FORBIDDEN_REFERENCE_CHECK,
- PREF_CODEASSIST_DISCOURAGED_REFERENCE_CHECK,
- PREF_CODEASSIST_DEPRECATION_CHECK,
- PREF_CODEASSIST_CAMEL_CASE_MATCH,
- };
- }
-
- private static final String[] trueFalse= new String[] { IPreferenceStore.TRUE, IPreferenceStore.FALSE };
- private static final String[] enabledDisabled= new String[] { JavaScriptCore.ENABLED, JavaScriptCore.DISABLED };
-
- private Button fCompletionInsertsRadioButton;
- private Button fCompletionOverwritesRadioButton;
-
- public CodeAssistConfigurationBlock(IStatusChangeListener statusListener, IWorkbenchPreferenceContainer workbenchcontainer) {
- super(statusListener, null, getAllKeys(), workbenchcontainer);
- }
-
- protected Control createContents(Composite parent) {
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Composite control= new Composite(scrolled, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- control.setLayout(layout);
-
- Composite composite;
-
- composite= createSubsection(control, PreferencesMessages.CodeAssistConfigurationBlock_insertionSection_title);
- addInsertionSection(composite);
-
- composite= createSubsection(control, PreferencesMessages.CodeAssistConfigurationBlock_sortingSection_title);
- addSortingSection(composite);
-
- composite= createSubsection(control, PreferencesMessages.CodeAssistConfigurationBlock_autoactivationSection_title);
- addAutoActivationSection(composite);
-
- initialize();
-
- scrolled.setContent(control);
- final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
- return scrolled;
- }
-
- protected Composite createSubsection(Composite parent, String label) {
- Group group= new Group(parent, SWT.SHADOW_NONE);
- group.setText(label);
- GridData data= new GridData(SWT.FILL, SWT.CENTER, true, false);
- group.setLayoutData(data);
- GridLayout layout= new GridLayout();
- layout.numColumns= 3;
- group.setLayout(layout);
-
- return group;
- }
-
- private void addInsertionSection(Composite composite) {
- addCompletionRadioButtons(composite);
-
- String label;
- label= PreferencesMessages.JavaEditorPreferencePage_insertSingleProposalsAutomatically;
- addCheckBox(composite, label, PREF_CODEASSIST_AUTOINSERT, trueFalse, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_completePrefixes;
- addCheckBox(composite, label, PREF_CODEASSIST_PREFIX_COMPLETION, trueFalse, 0);
-
-// label= PreferencesMessages.JavaEditorPreferencePage_automaticallyAddImportInsteadOfQualifiedName;
-// Button master= addCheckBox(composite, label, PREF_CODEASSIST_ADDIMPORT, trueFalse, 0);
-
-// label= PreferencesMessages.JavaEditorPreferencePage_suggestStaticImports;
-// Button slave= addCheckBox(composite, label, PREF_CODEASSIST_SUGGEST_STATIC_IMPORTS, enabledDisabled, 20);
-// createSelectionDependency(master, slave);
-
-
- label= PreferencesMessages.JavaEditorPreferencePage_fillArgumentNamesOnMethodCompletion;
- Button master= addCheckBox(composite, label, PREF_CODEASSIST_FILL_ARGUMENT_NAMES, trueFalse, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_guessArgumentNamesOnMethodCompletion;
- Button slave= addCheckBox(composite, label, PREF_CODEASSIST_GUESS_METHOD_ARGUMENTS, trueFalse, 20);
- createSelectionDependency(master, slave);
- }
-
- /**
- * Creates a selection dependency between a master and a slave control.
- *
- * @param master
- * The master button that controls the state of the slave
- * @param slave
- * The slave control that is enabled only if the master is
- * selected
- */
- protected static void createSelectionDependency(final Button master, final Control slave) {
-
- master.addSelectionListener(new SelectionListener() {
-
- public void widgetDefaultSelected(SelectionEvent event) {
- // Do nothing
- }
-
- public void widgetSelected(SelectionEvent event) {
- slave.setEnabled(master.getSelection());
- }
- });
- slave.setEnabled(master.getSelection());
- }
-
- private void addSortingSection(Composite composite) {
- String label;
- label= PreferencesMessages.JavaEditorPreferencePage_presentProposalsInAlphabeticalOrder;
- ProposalSorterHandle[] sorters= ProposalSorterRegistry.getDefault().getSorters();
- String[] labels= new String[sorters.length];
- String[] values= new String[sorters.length];
- for (int i= 0; i < sorters.length; i++) {
- ProposalSorterHandle handle= sorters[i];
- labels[i]= handle.getName();
- values[i]= handle.getId();
- }
-
- addComboBox(composite, label, PREF_CODEASSIST_SORTER, values, labels, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_showOnlyProposalsVisibleInTheInvocationContext;
- addCheckBox(composite, label, PREF_CODEASSIST_SHOW_VISIBLE_PROPOSALS, trueFalse, 0);
-
- label= PreferencesMessages.CodeAssistConfigurationBlock_matchCamelCase_label;
- addCheckBox(composite, label, PREF_CODEASSIST_CAMEL_CASE_MATCH, enabledDisabled, 0);
-
- label= PreferencesMessages.CodeAssistConfigurationBlock_restricted_link;
- Map targetInfo= new java.util.HashMap(2);
- targetInfo.put(ProblemSeveritiesPreferencePage.DATA_SELECT_OPTION_KEY, JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE);
- targetInfo.put(ProblemSeveritiesPreferencePage.DATA_SELECT_OPTION_QUALIFIER, JavaScriptCore.PLUGIN_ID);
- createPreferencePageLink(composite, label, targetInfo);
-
-
- label= PreferencesMessages.CodeAssistConfigurationBlock_hideForbidden_label;
- addCheckBox(composite, label, PREF_CODEASSIST_FORBIDDEN_REFERENCE_CHECK, enabledDisabled, 0);
-
- label= PreferencesMessages.CodeAssistConfigurationBlock_hideDiscouraged_label;
- addCheckBox(composite, label, PREF_CODEASSIST_DISCOURAGED_REFERENCE_CHECK, enabledDisabled, 0);
-
- label= PreferencesMessages.CodeAssistConfigurationBlock_hideDeprecated_label;
- addCheckBox(composite, label, PREF_CODEASSIST_DEPRECATION_CHECK, enabledDisabled, 0);
- }
-
- private void createPreferencePageLink(Composite composite, String label, final Map targetInfo) {
- final Link link= new Link(composite, SWT.NONE);
- link.setText(label);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(link.getShell(), e.text, null, targetInfo);
- }
- });
- }
-
- private void addAutoActivationSection(Composite composite) {
- String label;
- label= PreferencesMessages.JavaEditorPreferencePage_enableAutoActivation;
- final Button autoactivation= addCheckBox(composite, label, PREF_CODEASSIST_AUTOACTIVATION, trueFalse, 0);
- autoactivation.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- updateAutoactivationControls();
- }
- });
-
- label= PreferencesMessages.JavaEditorPreferencePage_autoActivationDelay;
- addLabelledTextField(composite, label, PREF_CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true);
-
- label= PreferencesMessages.JavaEditorPreferencePage_autoActivationTriggersForJava;
- addLabelledTextField(composite, label, PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false);
-
- label= PreferencesMessages.JavaEditorPreferencePage_autoActivationTriggersForJavaDoc;
- addLabelledTextField(composite, label, PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false);
- }
-
- protected Text addLabelledTextField(Composite parent, String label, Key key, int textlimit, int indent, boolean dummy) {
- PixelConverter pixelConverter= new PixelConverter(parent);
-
- Label labelControl= new Label(parent, SWT.WRAP);
- labelControl.setText(label);
- labelControl.setLayoutData(new GridData());
-
- Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
- textBox.setData(key);
- textBox.setLayoutData(new GridData());
-
- fLabels.put(textBox, labelControl);
-
- String currValue= getValue(key);
- if (currValue != null) {
- textBox.setText(currValue);
- }
- textBox.addModifyListener(getTextModifyListener());
-
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- if (textlimit != 0) {
- textBox.setTextLimit(textlimit);
- data.widthHint= pixelConverter.convertWidthInCharsToPixels(textlimit + 1);
- }
- data.horizontalIndent= indent;
- data.horizontalSpan= 2;
- textBox.setLayoutData(data);
-
- fTextBoxes.add(textBox);
- return textBox;
- }
-
- private void addCompletionRadioButtons(Composite contentAssistComposite) {
- Composite completionComposite= new Composite(contentAssistComposite, SWT.NONE);
- GridData ccgd= new GridData();
- ccgd.horizontalSpan= 2;
- completionComposite.setLayoutData(ccgd);
- GridLayout ccgl= new GridLayout();
- ccgl.marginWidth= 0;
- ccgl.numColumns= 2;
- completionComposite.setLayout(ccgl);
-
- SelectionListener completionSelectionListener= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- boolean insert= fCompletionInsertsRadioButton.getSelection();
- setValue(PREF_CODEASSIST_INSERT_COMPLETION, insert);
- }
- };
-
- fCompletionInsertsRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT);
- fCompletionInsertsRadioButton.setText(PreferencesMessages.JavaEditorPreferencePage_completionInserts);
- fCompletionInsertsRadioButton.setLayoutData(new GridData());
- fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener);
-
- fCompletionOverwritesRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT);
- fCompletionOverwritesRadioButton.setText(PreferencesMessages.JavaEditorPreferencePage_completionOverwrites);
- fCompletionOverwritesRadioButton.setLayoutData(new GridData());
- fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener);
-
- Label label= new Label(completionComposite, SWT.NONE);
- label.setText(PreferencesMessages.JavaEditorPreferencePage_completionToggleHint);
- GridData gd= new GridData();
- gd.horizontalIndent= 20;
- gd.horizontalSpan= 2;
- label.setLayoutData(gd);
- }
-
- public void initialize() {
- initializeFields();
- }
-
- private void initializeFields() {
- boolean completionInserts= getBooleanValue(PREF_CODEASSIST_INSERT_COMPLETION);
- fCompletionInsertsRadioButton.setSelection(completionInserts);
- fCompletionOverwritesRadioButton.setSelection(!completionInserts);
-
- updateAutoactivationControls();
- }
-
- private void updateAutoactivationControls() {
- boolean autoactivation= getBooleanValue(PREF_CODEASSIST_AUTOACTIVATION);
- setControlEnabled(PREF_CODEASSIST_AUTOACTIVATION_DELAY, autoactivation);
- setControlEnabled(PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, autoactivation);
- setControlEnabled(PREF_CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, autoactivation);
- setControlEnabled(PREF_CODEASSIST_GUESS_METHOD_ARGUMENTS, getBooleanValue(PREF_CODEASSIST_FILL_ARGUMENT_NAMES));
- }
-
-
- public void performDefaults() {
- super.performDefaults();
- initializeFields();
- }
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- return null;
- }
-
- /**
- * Validates that the specified number is positive.
- *
- * @param number
- * The number to validate
- * @return The status of the validation
- */
- protected static IStatus validatePositiveNumber(final String number) {
-
- final StatusInfo status= new StatusInfo();
- if (number.length() == 0) {
- status.setError(PreferencesMessages.SpellingPreferencePage_empty_threshold);
- } else {
- try {
- final int value= Integer.parseInt(number);
- if (value < 0) {
- status.setError(Messages.format(PreferencesMessages.SpellingPreferencePage_invalid_threshold, number));
- }
- } catch (NumberFormatException exception) {
- status.setError(Messages.format(PreferencesMessages.SpellingPreferencePage_invalid_threshold, number));
- }
- }
- return status;
- }
-
- protected void validateSettings(Key key, String oldValue, String newValue) {
- if (key == null || PREF_CODEASSIST_AUTOACTIVATION_DELAY.equals(key))
- fContext.statusChanged(validatePositiveNumber(getValue(PREF_CODEASSIST_AUTOACTIVATION_DELAY)));
- }
-
- protected void setControlEnabled(Key key, boolean enabled) {
- Control control= getControl(key);
- control.setEnabled(enabled);
- Label label= (Label) fLabels.get(control);
- if (label != null)
- label.setEnabled(enabled);
- }
-
- private Control getControl(Key key) {
- for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fComboBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fCheckBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fTextBoxes.get(i);
- Key currKey= (Key) curr.getData();
- if (key.equals(currKey)) {
- return curr;
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java
deleted file mode 100644
index e5b1f64b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.ui.IJavaScriptElementSearchConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * Configures the Content Assist > Static Members preference page.
- *
- *
- */
-class CodeAssistFavoritesConfigurationBlock extends OptionsConfigurationBlock {
-
-
- private static class FavoriteStaticMemberInputDialog extends StatusDialog {
-
- private class StringButtonAdapter implements IDialogFieldListener, IStringButtonAdapter {
- /*
- * @see IDialogFieldListener#dialogFieldChanged(DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
-
- /*
- * @see IStringButtonAdapter#changeControlPressed(DialogField)
- */
- public void changeControlPressed(DialogField field) {
- doBrowseTypes();
- }
- }
-
- private StringButtonDialogField fNameDialogField;
- private List fExistingEntries;
- private final boolean fIsEditingMember;
-
- public FavoriteStaticMemberInputDialog(Shell parent, List existingEntries, boolean isEditingMember) {
- super(parent);
- fIsEditingMember= isEditingMember;
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fExistingEntries= existingEntries;
-
- String label, title;
- if (isEditingMember) {
- title= PreferencesMessages.FavoriteStaticMemberInputDialog_member_title;
- label= PreferencesMessages.FavoriteStaticMemberInputDialog_member_labelText;
- } else {
- title= PreferencesMessages.FavoriteStaticMemberInputDialog_type_title;
- label= PreferencesMessages.FavoriteStaticMemberInputDialog_type_labelText;
- }
- setTitle(title);
-
- StringButtonAdapter adapter= new StringButtonAdapter();
-
- fNameDialogField= new StringButtonDialogField(adapter);
- fNameDialogField.setLabelText(label);
- fNameDialogField.setButtonLabel(PreferencesMessages.FavoriteStaticMemberInputDialog_browse_button);
- fNameDialogField.setDialogFieldListener(adapter);
- fNameDialogField.setText(""); //$NON-NLS-1$
- }
-
- public void setInitialSelection(String editedEntry) {
- Assert.isNotNull(editedEntry);
- if (editedEntry.length() == 0)
- fNameDialogField.setText(""); //$NON-NLS-1$
- else
- fNameDialogField.setText(editedEntry);
- }
-
- public String getResult() {
- String val= fNameDialogField.getText();
- if (!fIsEditingMember)
- val= val + WILDCARD;
- return val;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- initializeDialogUnits(parent);
-
- GridLayout layout= (GridLayout) composite.getLayout();
- layout.numColumns= 2;
-
- fNameDialogField.doFillIntoGrid(composite, 3);
-
- fNameDialogField.getChangeControl(null).setVisible(!fIsEditingMember);
-
- LayoutUtil.setHorizontalSpan(fNameDialogField.getLabelControl(null), 2);
-
- int fieldWidthHint= convertWidthInCharsToPixels(60);
- Text text= fNameDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, fieldWidthHint);
- LayoutUtil.setHorizontalGrabbing(text);
- LayoutUtil.setHorizontalSpan(text, fIsEditingMember ? 2 : 1);
- TextFieldNavigationHandler.install(text);
-
- DialogField.createEmptySpace(composite, 1);
-
- fNameDialogField.postSetFocusOnDialogField(parent.getDisplay());
-
-
- applyDialogFont(composite);
- return composite;
- }
-
- private void doBrowseTypes() {
- IRunnableContext context= new BusyIndicatorRunnableContext();
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- int style= IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES;
- try {
- SelectionDialog dialog= JavaScriptUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
- dialog.setTitle(PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title);
- dialog.setMessage(PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_description);
- if (dialog.open() == Window.OK) {
- IType res= (IType) dialog.getResult()[0];
- fNameDialogField.setText(res.getFullyQualifiedName('.'));
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title, PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message);
- }
- }
-
- void doDialogFieldChanged(DialogField field) {
- doValidation();
- }
-
- private void doValidation() {
- StatusInfo status= new StatusInfo();
- String newText= fNameDialogField.getText();
- if (newText.length() == 0) {
- status.setError(""); //$NON-NLS-1$
- } else {
- IStatus val= JavaScriptConventions.validateJavaScriptTypeName(newText, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3);
- if (val.matches(IStatus.ERROR)) {
- if (fIsEditingMember)
- status.setError(PreferencesMessages.FavoriteStaticMemberInputDialog_error_invalidMemberName);
- else
- status.setError(PreferencesMessages.FavoriteStaticMemberInputDialog_error_invalidTypeName);
- } else {
- if (doesExist(newText, fIsEditingMember)) {
- status.setError(PreferencesMessages.FavoriteStaticMemberInputDialog_error_entryExists);
- }
- }
- }
- updateStatus(status);
- }
-
- private boolean doesExist(String name, boolean isStatic) {
- for (int i= 0; i < fExistingEntries.size(); i++) {
- String entry= (String) fExistingEntries.get(i);
- if (name.equals(entry)) {
- return true;
- }
- }
- return false;
- }
-
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
- }
-
- }
-
-
- private static class ListLabelProvider extends LabelProvider {
-
- public final Image MEMBER_ICON;
- private final Image CLASS_ICON;
-
- public ListLabelProvider() {
- MEMBER_ICON= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, 0, JavaElementImageProvider.SMALL_SIZE);
- CLASS_ICON= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.SMALL_SIZE);
- }
-
- public Image getImage(Object element) {
- return ((String)element).endsWith(WILDCARD) ? CLASS_ICON : MEMBER_ICON;
- }
-
- public String getText(Object element) {
- return (String)element;
- }
- }
-
-
- private class ListAdapter implements IListAdapter, IDialogFieldListener {
-
- private boolean canEdit(ListDialogField field) {
- List selected= field.getSelectedElements();
- return selected.size() == 1;
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doButtonPressed(index);
- }
-
- public void selectionChanged(ListDialogField field) {
- fList.enableButton(IDX_EDIT, canEdit(field));
- }
-
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
-
- public void doubleClicked(ListDialogField field) {
- if (canEdit(field)) {
- doButtonPressed(IDX_EDIT);
- }
- }
- }
-
-
- private static final Key PREF_CODEASSIST_FAVORITE_STATIC_MEMBERS= getJDTUIKey(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS);
-
- private static final String WILDCARD= ".*"; //$NON-NLS-1$
-
- private static final int IDX_NEW_TYPE= 0;
- private static final int IDX_NEW_MEMBER= 1;
- private static final int IDX_EDIT= 2;
- private static final int IDX_REMOVE= 3;
-
- private ListDialogField fList;
-
-
- private static Key[] getAllKeys() {
- return new Key[] {
- PREF_CODEASSIST_FAVORITE_STATIC_MEMBERS
- };
- }
-
-
- public CodeAssistFavoritesConfigurationBlock(IStatusChangeListener statusListener, IWorkbenchPreferenceContainer workbenchcontainer) {
- super(statusListener, null, getAllKeys(), workbenchcontainer);
- }
-
- protected Control createContents(Composite parent) {
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Composite control= new Composite(scrolled, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- control.setLayout(layout);
-
- createFavoriteList(control);
-
- initialize();
-
- scrolled.setContent(control);
- final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
-
- Dialog.applyDialogFont(scrolled);
-
- return scrolled;
- }
-
- private void createFavoriteList(Composite parent) {
- String[] buttonLabels= new String[] {
- PreferencesMessages.CodeAssistStaticMembersConfigurationBlock_newType_button,
- PreferencesMessages.CodeAssistStaticMembersConfigurationBlock_newMember_button,
- PreferencesMessages.CodeAssistStaticMembersConfigurationBlock_edit_button,
- PreferencesMessages.CodeAssistStaticMembersConfigurationBlock_remove_button
- };
-
- ListAdapter adapter= new ListAdapter();
-
- fList= new ListDialogField(adapter, buttonLabels, new ListLabelProvider());
- fList.setDialogFieldListener(adapter);
- fList.setLabelText(PreferencesMessages.CodeAssistStaticMembersConfigurationBlock_description);
- fList.setRemoveButtonIndex(IDX_REMOVE);
- fList.enableButton(IDX_EDIT, false);
- fList.setViewerComparator(new ViewerComparator());
-
- PixelConverter pixelConverter= new PixelConverter(parent);
-
- fList.doFillIntoGrid(parent, 3);
- LayoutUtil.setHorizontalSpan(fList.getLabelControl(null), 2);
- LayoutUtil.setWidthHint(fList.getLabelControl(null), pixelConverter.convertWidthInCharsToPixels(60));
- LayoutUtil.setHorizontalGrabbing(fList.getListControl(null));
-
- Control listControl= fList.getListControl(null);
- GridData gd= (GridData)listControl.getLayoutData();
- gd.verticalAlignment= GridData.BEGINNING;
- gd.heightHint= pixelConverter.convertHeightInCharsToPixels(7);
- }
-
- public void initialize() {
- initializeFields();
- }
-
- private void initializeFields() {
- fList.setElements(Arrays.asList(getFavoriteStaticMembersPreference()));
- }
-
- public void performDefaults() {
- super.performDefaults();
- initializeFields();
- }
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- return null;
- }
-
- protected void validateSettings(Key key, String oldValue, String newValue) {
- // no validation
- }
-
- protected void setControlEnabled(Key key, boolean enabled) {
- Control control= getControl(key);
- control.setEnabled(enabled);
- Label label= (Label) fLabels.get(control);
- if (label != null)
- label.setEnabled(enabled);
- }
-
- private Control getControl(Key key) {
- for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fComboBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fCheckBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
- Control curr= (Control) fTextBoxes.get(i);
- Key currKey= (Key) curr.getData();
- if (key.equals(currKey)) {
- return curr;
- }
- }
- return null;
- }
-
- private void doButtonPressed(int index) {
- if (index == IDX_NEW_TYPE || index == IDX_NEW_MEMBER) { // add new
- List existing= fList.getElements();
- FavoriteStaticMemberInputDialog dialog= new FavoriteStaticMemberInputDialog(getShell(), existing, index == IDX_NEW_MEMBER);
- if (dialog.open() == Window.OK) {
- fList.addElement(dialog.getResult());
- }
- } else if (index == IDX_EDIT) { // edit
- List selected= fList.getSelectedElements();
- if (selected.isEmpty())
- return;
-
- String editedEntry= (String)selected.get(0);
-
- List existing= fList.getElements();
- existing.remove(editedEntry);
- boolean isType= editedEntry.endsWith(WILDCARD);
- FavoriteStaticMemberInputDialog dialog= new FavoriteStaticMemberInputDialog(getShell(), existing, !isType);
- if (isType)
- dialog.setInitialSelection(editedEntry.substring(0, editedEntry.length() - 2));
- else
- dialog.setInitialSelection(editedEntry);
-
- if (dialog.open() == Window.OK) {
- fList.replaceElement(editedEntry, dialog.getResult());
- }
- }
- }
-
- protected final void doDialogFieldChanged(DialogField field) {
- // set values in working copy
- if (field == fList)
- setValue(PREF_CODEASSIST_FAVORITE_STATIC_MEMBERS, serializeFavorites(fList.getElements()));
- }
-
- private String[] getFavoriteStaticMembersPreference() {
- String str= getValue(PREF_CODEASSIST_FAVORITE_STATIC_MEMBERS);
- if (str != null && str.length() > 0)
- return deserializeFavorites(str);
- return new String[0];
- }
-
- private static String[] deserializeFavorites(String str) {
- return str.split(";"); //$NON-NLS-1$
- }
-
- private static String serializeFavorites(List favorites) {
- int size= favorites.size();
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < size; i++) {
- buf.append((String)favorites.get(i));
- if (i < size -1)
- buf.append(';');
- }
- return buf.toString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java
deleted file mode 100644
index 253cde45..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-/**
- * Content Assist > Static Members preference page.
- * <p>
- * Note: Must be public since it is referenced from plugin.xml
- * </p>
- *
- *
- */
-public class CodeAssistFavoritesPreferencePage extends PropertyAndPreferencePage implements IWorkbenchPreferencePage {
-
- private CodeAssistFavoritesConfigurationBlock fConfigurationBlock;
-
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new CodeAssistFavoritesConfigurationBlock(getNewStatusChangedListener(), container);
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return false;
- }
-
- protected String getPreferencePageID() {
- return "org.eclipse.wst.jsdt.ui.preferences.CodeAssistStaticMembersPreferencePage"; //$NON-NLS-1$
- }
-
- protected String getPropertyPageID() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java
deleted file mode 100644
index 0dc0260d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-/**
- * Content Assist preference page.
- * <p>
- * Note: Must be public since it is referenced from plugin.xml
- * </p>
- *
- *
- */
-public class CodeAssistPreferencePage extends PropertyAndPreferencePage implements IWorkbenchPreferencePage {
-
- private CodeAssistConfigurationBlock fConfigurationBlock;
-
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new CodeAssistConfigurationBlock(getNewStatusChangedListener(), container);
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return false;
- }
-
- protected String getPreferencePageID() {
- return "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferencePage"; //$NON-NLS-1$
- }
-
- protected String getPropertyPageID() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java
deleted file mode 100644
index b249db55..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.CodeFormatterConfigurationBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileConfigurationBlock;
-
-/*
- * The page to configure the code formatter options.
- */
-public class CodeFormatterPreferencePage extends ProfilePreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CodeFormatterPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CodeFormatterPreferencePage"; //$NON-NLS-1$
-
- public CodeFormatterPreferencePage() {
- // only used when page is shown programatically
- setTitle(PreferencesMessages.CodeFormatterPreferencePage_title);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.ProfilePreferencePage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
- }
-
- protected ProfileConfigurationBlock createConfigurationBlock(PreferencesAccess access) {
- return new CodeFormatterConfigurationBlock(getProject(), access);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreviewCode.txt b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreviewCode.txt
deleted file mode 100644
index bbe7fe29..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreviewCode.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * This header comment may be left unformatted.
- */
-
-package org.eclipse.formatter.example;
-
-/**
- * Example class displaying the effects of various code formatting preferences.
- * <p> See also {@link org.eclipse.editor.syntax}. </p>
- *
- * The blank line above may be cleared.
- * @version 3.0
- */
-public class Example extends Object {
- /* This comment may be wrapped to multiple lines depending on the maximal line length. */
- private int integer= 0;
- // This single-line comment may be wrapped too...
- private String string= "zero";
-
- /**
- * This comment shows the formatting of code snippets.
- * <pre>
- * while ((size = foo(size, max)) > 0) { System.out.println("bar"); }
- * </pre>
- * After this comment a blank line may be inserted.
- * @param size The size
- * @param max The maximum
- */
- public int foo(int size, int max) {
-
- if (size < max) {
- try {
- size=(long)stream.available();
- } catch (IOException e) {
-
- }
- } else if (size == max) {
- ++size;
- } else {
- --size;
- }
- return size;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeStylePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeStylePreferencePage.java
deleted file mode 100644
index d413a353..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeStylePreferencePage.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/*
- * The page to configure the naming style options.
- */
-public class CodeStylePreferencePage extends PropertyAndPreferencePage implements IWorkbenchPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CodeStylePreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CodeStylePreferencePage"; //$NON-NLS-1$
-
- private NameConventionConfigurationBlock fConfigurationBlock;
-
- public CodeStylePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.getString("CodeStylePreferencePage.description")); //$NON-NLS-1$
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.CodeStylePreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new NameConventionConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
-
-}
-
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateBlock.java
deleted file mode 100644
index 83733a0f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateBlock.java
+++ /dev/null
@@ -1,580 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProjectTemplateStore;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.TreeListDialogField;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-/**
- */
-public class CodeTemplateBlock {
-
- private class CodeTemplateAdapter extends ViewerComparator implements ITreeListAdapter, IDialogFieldListener {
-
- private final Object[] NO_CHILDREN= new Object[0];
-
- public void customButtonPressed(TreeListDialogField field, int index) {
- doButtonPressed(index, field.getSelectedElements());
- }
-
- public void selectionChanged(TreeListDialogField field) {
- List selected= field.getSelectedElements();
- field.enableButton(IDX_EDIT, canEdit(selected));
- field.enableButton(IDX_EXPORT, !selected.isEmpty());
-
- updateSourceViewerInput(selected);
- }
-
- public void doubleClicked(TreeListDialogField field) {
- List selected= field.getSelectedElements();
- if (canEdit(selected)) {
- doButtonPressed(IDX_EDIT, selected);
- }
- }
-
- public Object[] getChildren(TreeListDialogField field, Object element) {
- if (element == COMMENT_NODE || element == CODE_NODE) {
- return getTemplateOfCategory(element == COMMENT_NODE);
- }
- return NO_CHILDREN;
- }
-
- public Object getParent(TreeListDialogField field, Object element) {
- if (element instanceof TemplatePersistenceData) {
- TemplatePersistenceData data= (TemplatePersistenceData) element;
- if (data.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) {
- return COMMENT_NODE;
- }
- return CODE_NODE;
- }
- return null;
- }
-
- public boolean hasChildren(TreeListDialogField field, Object element) {
- return (element == COMMENT_NODE || element == CODE_NODE);
- }
-
- public void dialogFieldChanged(DialogField field) {
- }
-
- public void keyPressed(TreeListDialogField field, KeyEvent event) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
- */
- public int category(Object element) {
- if (element == COMMENT_NODE) {
- return 1;
- } else if (element == CODE_NODE) {
- return 2;
- }
-
- TemplatePersistenceData data= (TemplatePersistenceData) element;
- String id= data.getId();
-
- if (CodeTemplateContextType.NEWTYPE_ID.equals(id)) {
- return 101;
- } else if (CodeTemplateContextType.CLASSBODY_ID.equals(id)) {
- return 102;
- } else if (CodeTemplateContextType.METHODSTUB_ID.equals(id)) {
- return 106;
- } else if (CodeTemplateContextType.CONSTRUCTORSTUB_ID.equals(id)) {
- return 107;
- } else if (CodeTemplateContextType.GETTERSTUB_ID.equals(id)) {
- return 108;
- } else if (CodeTemplateContextType.SETTERSTUB_ID.equals(id)) {
- return 109;
- } else if (CodeTemplateContextType.CATCHBLOCK_ID.equals(id)) {
- return 110;
- } else if (CodeTemplateContextType.FILECOMMENT_ID.equals(id)) {
- return 1;
- } else if (CodeTemplateContextType.TYPECOMMENT_ID.equals(id)) {
- return 2;
- } else if (CodeTemplateContextType.FIELDCOMMENT_ID.equals(id)) {
- return 3;
- } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT_ID.equals(id)) {
- return 4;
- } else if (CodeTemplateContextType.METHODCOMMENT_ID.equals(id)) {
- return 5;
- } else if (CodeTemplateContextType.OVERRIDECOMMENT_ID.equals(id)) {
- return 6;
- } else if (CodeTemplateContextType.DELEGATECOMMENT_ID.equals(id)) {
- return 7;
- } else if (CodeTemplateContextType.GETTERCOMMENT_ID.equals(id)) {
- return 8;
- } else if (CodeTemplateContextType.SETTERCOMMENT_ID.equals(id)) {
- return 9;
- }
- return 1000;
- }
- }
-
- private static class CodeTemplateLabelProvider extends LabelProvider {
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- return null;
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (element == COMMENT_NODE || element == CODE_NODE) {
- return (String) element;
- }
- TemplatePersistenceData data= (TemplatePersistenceData) element;
- String id=data.getId();
- if (CodeTemplateContextType.CATCHBLOCK_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_catchblock_label;
- } else if (CodeTemplateContextType.METHODSTUB_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_methodstub_label;
- } else if (CodeTemplateContextType.CONSTRUCTORSTUB_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_constructorstub_label;
- } else if (CodeTemplateContextType.GETTERSTUB_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_getterstub_label;
- } else if (CodeTemplateContextType.SETTERSTUB_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_setterstub_label;
- } else if (CodeTemplateContextType.NEWTYPE_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_newtype_label;
- } else if (CodeTemplateContextType.CLASSBODY_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_classbody_label;
- } else if (CodeTemplateContextType.FILECOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_filecomment_label;
- } else if (CodeTemplateContextType.TYPECOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_typecomment_label;
- } else if (CodeTemplateContextType.FIELDCOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_fieldcomment_label;
- } else if (CodeTemplateContextType.METHODCOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_methodcomment_label;
- } else if (CodeTemplateContextType.OVERRIDECOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_overridecomment_label;
- } else if (CodeTemplateContextType.DELEGATECOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_delegatecomment_label;
- } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_constructorcomment_label;
- } else if (CodeTemplateContextType.GETTERCOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_gettercomment_label;
- } else if (CodeTemplateContextType.SETTERCOMMENT_ID.equals(id)) {
- return PreferencesMessages.CodeTemplateBlock_settercomment_label;
- }
- return data.getTemplate().getDescription();
- }
- }
-
- private final static int IDX_EDIT= 0;
- private final static int IDX_IMPORT= 2;
- private final static int IDX_EXPORT= 3;
- private final static int IDX_EXPORTALL= 4;
-
- protected final static Object COMMENT_NODE= PreferencesMessages.CodeTemplateBlock_templates_comment_node;
- protected final static Object CODE_NODE= PreferencesMessages.CodeTemplateBlock_templates_code_node;
-
- private TreeListDialogField fCodeTemplateTree;
-
- protected ProjectTemplateStore fTemplateStore;
-
- private PixelConverter fPixelConverter;
- private SourceViewer fPatternViewer;
- private Control fSWTWidget;
- private TemplateVariableProcessor fTemplateProcessor;
-
- private final IProject fProject;
-
- public CodeTemplateBlock(IProject project) {
-
- fProject= project;
-
- fTemplateStore= new ProjectTemplateStore(project);
- try {
- fTemplateStore.load();
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
-
- fTemplateProcessor= new TemplateVariableProcessor();
-
- CodeTemplateAdapter adapter= new CodeTemplateAdapter();
-
- String[] buttonLabels= new String[] {
- PreferencesMessages.CodeTemplateBlock_templates_edit_button,
- /* */ null,
- PreferencesMessages.CodeTemplateBlock_templates_import_button,
- PreferencesMessages.CodeTemplateBlock_templates_export_button,
- PreferencesMessages.CodeTemplateBlock_templates_exportall_button
-
- };
- fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider());
- fCodeTemplateTree.setDialogFieldListener(adapter);
- fCodeTemplateTree.setLabelText(PreferencesMessages.CodeTemplateBlock_templates_label);
- fCodeTemplateTree.setViewerComparator(adapter);
-
- fCodeTemplateTree.enableButton(IDX_EXPORT, false);
- fCodeTemplateTree.enableButton(IDX_EDIT, false);
-
- fCodeTemplateTree.addElement(COMMENT_NODE);
- fCodeTemplateTree.addElement(CODE_NODE);
-
- fCodeTemplateTree.selectFirstElement();
- }
-
- public void postSetSelection(Object element) {
- fCodeTemplateTree.postSetSelection(new StructuredSelection(element));
- }
-
- public boolean hasProjectSpecificOptions(IProject project) {
- if (project != null) {
- return ProjectTemplateStore.hasProjectSpecificTempates(project);
- }
- return false;
- }
-
- protected Control createContents(Composite parent) {
- fPixelConverter= new PixelConverter(parent);
- fSWTWidget= parent;
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- composite.setLayout(layout);
-
- fCodeTemplateTree.doFillIntoGrid(composite, 3);
- LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2);
- LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null));
-
- fPatternViewer= createViewer(composite, 2);
-
- return composite;
- }
-
- private Shell getShell() {
- if (fSWTWidget != null) {
- return fSWTWidget.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- private SourceViewer createViewer(Composite parent, int nColumns) {
- Label label= new Label(parent, SWT.NONE);
- label.setText(PreferencesMessages.CodeTemplateBlock_preview);
- GridData data= new GridData();
- data.horizontalSpan= nColumns;
- label.setLayoutData(data);
-
- IDocument document= new Document();
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
- CodeTemplateSourceViewerConfiguration configuration= new CodeTemplateSourceViewerConfiguration(tools.getColorManager(), store, null, fTemplateProcessor);
- viewer.configure(configuration);
- viewer.setEditable(false);
- viewer.setDocument(document);
-
- Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- viewer.getTextWidget().setFont(font);
- new JavaSourcePreviewerUpdater(viewer, configuration, store);
-
- Control control= viewer.getControl();
- data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
- data.horizontalSpan= nColumns;
- data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5);
- control.setLayoutData(data);
-
- return viewer;
- }
-
- protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) {
- ArrayList res= new ArrayList();
- TemplatePersistenceData[] templates= fTemplateStore.getTemplateData();
- for (int i= 0; i < templates.length; i++) {
- TemplatePersistenceData curr= templates[i];
- if (isComment == curr.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) {
- res.add(curr);
- }
- }
- return (TemplatePersistenceData[]) res.toArray(new TemplatePersistenceData[res.size()]);
- }
-
- protected static boolean canEdit(List selected) {
- return selected.size() == 1 && (selected.get(0) instanceof TemplatePersistenceData);
- }
-
- protected void updateSourceViewerInput(List selection) {
- if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) {
- return;
- }
- if (selection.size() == 1 && selection.get(0) instanceof TemplatePersistenceData) {
- TemplatePersistenceData data= (TemplatePersistenceData) selection.get(0);
- Template template= data.getTemplate();
- TemplateContextType type= JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry().getContextType(template.getContextTypeId());
- fTemplateProcessor.setContextType(type);
- fPatternViewer.getDocument().set(template.getPattern());
- } else {
- fPatternViewer.getDocument().set(""); //$NON-NLS-1$
- }
- }
-
- protected void doButtonPressed(int buttonIndex, List selected) {
- if (buttonIndex == IDX_EDIT) {
- edit((TemplatePersistenceData) selected.get(0));
- } else if (buttonIndex == IDX_EXPORT) {
- export(selected);
- } else if (buttonIndex == IDX_EXPORTALL) {
- exportAll();
- } else if (buttonIndex == IDX_IMPORT) {
- import_();
- }
- }
-
- private void edit(TemplatePersistenceData data) {
- Template newTemplate= new Template(data.getTemplate());
- EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, JavaScriptPlugin.getDefault().getCodeTemplateContextRegistry());
- if (dialog.open() == Window.OK) {
- // changed
- data.setTemplate(dialog.getTemplate());
- fCodeTemplateTree.refresh(data);
- fCodeTemplateTree.selectElements(new StructuredSelection(data));
- }
- }
-
- private void import_() {
- FileDialog dialog= new FileDialog(getShell());
- dialog.setText(PreferencesMessages.CodeTemplateBlock_import_title);
- dialog.setFilterExtensions(new String[] {PreferencesMessages.CodeTemplateBlock_import_extension});
- String path= dialog.open();
-
- if (path == null)
- return;
-
- try {
- TemplateReaderWriter reader= new TemplateReaderWriter();
- File file= new File(path);
- if (file.exists()) {
- InputStream input= new BufferedInputStream(new FileInputStream(file));
- try {
- TemplatePersistenceData[] datas= reader.read(input, null);
- for (int i= 0; i < datas.length; i++) {
- updateTemplate(datas[i]);
- }
- } finally {
- try {
- input.close();
- } catch (IOException x) {
- }
- }
- }
-
- fCodeTemplateTree.refresh();
- updateSourceViewerInput(fCodeTemplateTree.getSelectedElements());
-
- } catch (FileNotFoundException e) {
- openReadErrorDialog(e);
- } catch (IOException e) {
- openReadErrorDialog(e);
- }
-
- }
-
- private void updateTemplate(TemplatePersistenceData data) {
- TemplatePersistenceData[] datas= fTemplateStore.getTemplateData();
- for (int i= 0; i < datas.length; i++) {
- String id= datas[i].getId();
- if (id != null && id.equals(data.getId())) {
- datas[i].setTemplate(data.getTemplate());
- break;
- }
- }
- }
-
- private void exportAll() {
- export(fTemplateStore.getTemplateData());
- }
-
- private void export(List selected) {
- Set datas= new HashSet();
- for (int i= 0; i < selected.size(); i++) {
- Object curr= selected.get(i);
- if (curr instanceof TemplatePersistenceData) {
- datas.add(curr);
- } else {
- TemplatePersistenceData[] cat= getTemplateOfCategory(curr == COMMENT_NODE);
- datas.addAll(Arrays.asList(cat));
- }
- }
- export((TemplatePersistenceData[]) datas.toArray(new TemplatePersistenceData[datas.size()]));
- }
-
- private void export(TemplatePersistenceData[] templates) {
- FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
- dialog.setText(Messages.format(PreferencesMessages.CodeTemplateBlock_export_title, String.valueOf(templates.length)));
- dialog.setFilterExtensions(new String[] {PreferencesMessages.CodeTemplateBlock_export_extension});
- dialog.setFileName(PreferencesMessages.CodeTemplateBlock_export_filename);
- String path= dialog.open();
-
- if (path == null)
- return;
-
- File file= new File(path);
-
- if (file.isHidden()) {
- String title= PreferencesMessages.CodeTemplateBlock_export_error_title;
- String message= Messages.format(PreferencesMessages.CodeTemplateBlock_export_error_hidden, file.getAbsolutePath());
- MessageDialog.openError(getShell(), title, message);
- return;
- }
-
- if (file.exists() && !file.canWrite()) {
- String title= PreferencesMessages.CodeTemplateBlock_export_error_title;
- String message= Messages.format(PreferencesMessages.CodeTemplateBlock_export_error_canNotWrite, file.getAbsolutePath());
- MessageDialog.openError(getShell(), title, message);
- return;
- }
-
- if (!file.exists() || confirmOverwrite(file)) {
- OutputStream output= null;
- try {
- output= new BufferedOutputStream(new FileOutputStream(file));
- TemplateReaderWriter writer= new TemplateReaderWriter();
- writer.save(templates, output);
- output.close();
- } catch (IOException e) {
- if (output != null) {
- try {
- output.close();
- } catch (IOException e2) {
- // ignore
- }
- }
- openWriteErrorDialog(e);
- }
- }
-
- }
-
- private boolean confirmOverwrite(File file) {
- return MessageDialog.openQuestion(getShell(),
- PreferencesMessages.CodeTemplateBlock_export_exists_title,
- Messages.format(PreferencesMessages.CodeTemplateBlock_export_exists_message, file.getAbsolutePath()));
- }
-
- public void performDefaults() {
- fTemplateStore.restoreDefaults();
-
- // refresh
- fCodeTemplateTree.refresh();
- updateSourceViewerInput(fCodeTemplateTree.getSelectedElements());
- }
-
- public boolean performOk(boolean enabled) {
- if (fProject != null) {
- TemplatePersistenceData[] templateData= fTemplateStore.getTemplateData();
- for (int i= 0; i < templateData.length; i++) {
- fTemplateStore.setProjectSpecific(templateData[i].getId(), enabled);
- }
- }
- try {
- fTemplateStore.save();
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- openWriteErrorDialog(e);
- }
- return true;
- }
-
- public void performCancel() {
- try {
- fTemplateStore.revertChanges();
- } catch (IOException e) {
- openReadErrorDialog(e);
- }
- }
-
- private void openReadErrorDialog(Exception e) {
- String title= PreferencesMessages.CodeTemplateBlock_error_read_title;
-
- String message= e.getLocalizedMessage();
- if (message != null)
- message= Messages.format(PreferencesMessages.CodeTemplateBlock_error_parse_message, message);
- else
- message= PreferencesMessages.CodeTemplateBlock_error_read_message;
- MessageDialog.openError(getShell(), title, message);
- }
-
- private void openWriteErrorDialog(Exception e) {
- String title= PreferencesMessages.CodeTemplateBlock_error_write_title;
- String message= PreferencesMessages.CodeTemplateBlock_error_write_message;
- MessageDialog.openError(getShell(), title, message);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplatePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplatePreferencePage.java
deleted file mode 100644
index c9ba93b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplatePreferencePage.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-
-/*
- * The page to configure the code templates.
- */
-public class CodeTemplatePreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CodeTemplatePreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CodeTemplatePreferencePage"; //$NON-NLS-1$
-
- public static final String DATA_SELECT_TEMPLATE= "CodeTemplatePreferencePage.select_template"; //$NON-NLS-1$
-
- private CodeTemplateBlock fCodeTemplateConfigurationBlock;
-
- public CodeTemplatePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); //$NON-NLS-1$
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.CodeTemplatesPreferencePage_title);
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- fCodeTemplateConfigurationBlock= new CodeTemplateBlock(getProject());
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CODE_TEMPLATES_PREFERENCE_PAGE);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#createPreferenceContent(org.eclipse.swt.widgets.Composite)
- */
- protected Control createPreferenceContent(Composite composite) {
- return fCodeTemplateConfigurationBlock.createContents(composite);
- }
-
- /*
- * @see IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fCodeTemplateConfigurationBlock != null) {
- return fCodeTemplateConfigurationBlock.performOk(useProjectSettings());
- }
- return true;
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fCodeTemplateConfigurationBlock != null) {
- fCodeTemplateConfigurationBlock.performDefaults();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus)
- */
- public void statusChanged(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.IPreferencePage#performCancel()
- */
- public boolean performCancel() {
- if (fCodeTemplateConfigurationBlock != null) {
- fCodeTemplateConfigurationBlock.performCancel();
- }
- return super.performCancel();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#hasProjectSpecificOptions(org.eclipse.core.resources.IProject)
- */
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fCodeTemplateConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
- */
- public void applyData(Object data) {
- if (data instanceof Map) {
- Object id= ((Map) data).get(DATA_SELECT_TEMPLATE);
- if (id instanceof String) {
- final TemplatePersistenceData[] templates= fCodeTemplateConfigurationBlock.fTemplateStore.getTemplateData();
- TemplatePersistenceData template= null;
- for (int index= 0; index < templates.length; index++) {
- template= templates[index];
- if (template.getId().equals(id)) {
- fCodeTemplateConfigurationBlock.postSetSelection(template);
- break;
- }
- }
- }
- }
- super.applyData(data);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateSourceViewerConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateSourceViewerConfiguration.java
deleted file mode 100644
index b7f6db39..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeTemplateSourceViewerConfiguration.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Iterator;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContentAssistant;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class CodeTemplateSourceViewerConfiguration extends SimpleJavaSourceViewerConfiguration {
-
- private static class TemplateVariableTextHover implements ITextHover {
-
- private TemplateVariableProcessor fProcessor;
-
- /**
- * @param processor the template variable processor
- */
- public TemplateVariableTextHover(TemplateVariableProcessor processor) {
- fProcessor= processor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion subject) {
- try {
- IDocument doc= textViewer.getDocument();
- int offset= subject.getOffset();
- if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$
- String varName= doc.get(offset, subject.getLength());
- TemplateContextType contextType= fProcessor.getContextType();
- if (contextType != null) {
- Iterator iter= contextType.resolvers();
- while (iter.hasNext()) {
- TemplateVariableResolver var= (TemplateVariableResolver) iter.next();
- if (varName.equals(var.getType())) {
- return var.getDescription();
- }
- }
- }
- }
- } catch (BadLocationException e) {
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int)
- */
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (textViewer != null) {
- return JavaWordFinder.findWord(textViewer.getDocument(), offset);
- }
- return null;
- }
-
- }
-
- private final TemplateVariableProcessor fProcessor;
-
- public CodeTemplateSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore store, ITextEditor editor, TemplateVariableProcessor processor) {
- super(colorManager, store, editor, IJavaScriptPartitions.JAVA_PARTITIONING, false);
- fProcessor= processor;
- }
-
- /*
- * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
- */
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- IColorManager manager= textTools.getColorManager();
-
-
- ContentAssistant assistant= new ContentAssistant();
- assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE);
- // Register the same processor for strings and single line comments to get code completion at the start of those partitions.
- assistant.setContentAssistProcessor(fProcessor, IJavaScriptPartitions.JAVA_STRING);
- assistant.setContentAssistProcessor(fProcessor, IJavaScriptPartitions.JAVA_CHARACTER);
- assistant.setContentAssistProcessor(fProcessor, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- assistant.setContentAssistProcessor(fProcessor, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- assistant.setContentAssistProcessor(fProcessor, IJavaScriptPartitions.JAVA_DOC);
-
- assistant.enableAutoInsert(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT));
- assistant.enableAutoActivation(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION));
- assistant.setAutoActivationDelay(store.getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY));
- assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
- assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
- assistant.setInformationControlCreator(new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
- }
- });
-
- Color background= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager);
- assistant.setContextInformationPopupBackground(background);
- assistant.setContextSelectorBackground(background);
- assistant.setProposalSelectorBackground(background);
-
- Color foreground= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager);
- assistant.setContextInformationPopupForeground(foreground);
- assistant.setContextSelectorForeground(foreground);
- assistant.setProposalSelectorForeground(foreground);
-
- return assistant;
- }
-
- private Color getColor(IPreferenceStore store, String key, IColorManager manager) {
- RGB rgb= PreferenceConverter.getColor(store, key);
- return manager.getColor(rgb);
- }
-
- /*
- * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
- *
- */
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
- return new TemplateVariableTextHover(fProcessor);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt
deleted file mode 100644
index 1af303f2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * This is about <code>Example.js</code>.
- * {@link com.yourCompany.aPackage.aFile}
- * @author author
- * @deprecated use <code>BetterExample.js</code>
- */
-var index = 0;
-var arr = [];
-
-function foo() {
- /* This comment may span multiple lines. */
- var var1 = new Object();
- var obj = [ make: "Toyota", model: "Celica", year: 2000 ];
- var s = "abc123";
- clear(var1);
-}
-
-function pop() {
- return arr[index--];
-}
-
-function push(elem) {
- // This comment may span only this line
- arr[index++] = elem;
-}
-
-function isEmpty() {
- // TASK: refactor
- return index == 0;
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ComplianceConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ComplianceConfigurationBlock.java
deleted file mode 100644
index e9f5ff0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ComplianceConfigurationBlock.java
+++ /dev/null
@@ -1,617 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathSupport;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstall2;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-
-/**
- */
-public class ComplianceConfigurationBlock extends OptionsConfigurationBlock {
-
- // Preference store keys, see JavaScriptCore.getOptions
- private static final Key PREF_LOCAL_VARIABLE_ATTR= getJDTCoreKey(JavaScriptCore.COMPILER_LOCAL_VARIABLE_ATTR);
- private static final Key PREF_LINE_NUMBER_ATTR= getJDTCoreKey(JavaScriptCore.COMPILER_LINE_NUMBER_ATTR);
- private static final Key PREF_SOURCE_FILE_ATTR= getJDTCoreKey(JavaScriptCore.COMPILER_SOURCE_FILE_ATTR);
- private static final Key PREF_CODEGEN_UNUSED_LOCAL= getJDTCoreKey(JavaScriptCore.COMPILER_CODEGEN_UNUSED_LOCAL);
- private static final Key PREF_CODEGEN_TARGET_PLATFORM= getJDTCoreKey(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM);
- private static final Key PREF_CODEGEN_INLINE_JSR_BYTECODE= getJDTCoreKey(JavaScriptCore.COMPILER_CODEGEN_INLINE_JSR_BYTECODE);
-
- private static final Key PREF_SOURCE_COMPATIBILITY= getJDTCoreKey(JavaScriptCore.COMPILER_SOURCE);
- private static final Key PREF_COMPLIANCE= getJDTCoreKey(JavaScriptCore.COMPILER_COMPLIANCE);
- private static final Key PREF_PB_ASSERT_AS_IDENTIFIER= getJDTCoreKey(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER);
-
- private static final Key INTR_DEFAULT_COMPLIANCE= getJDTUIKey("internal.default.compliance"); //$NON-NLS-1$
-
- // values
-// private static final String GENERATE= JavaScriptCore.GENERATE;
-// private static final String DO_NOT_GENERATE= JavaScriptCore.DO_NOT_GENERATE;
-//
-// private static final String PRESERVE= JavaScriptCore.PRESERVE;
-// private static final String OPTIMIZE_OUT= JavaScriptCore.OPTIMIZE_OUT;
-
- private static final String VERSION_1_1= JavaScriptCore.VERSION_1_1;
- private static final String VERSION_1_2= JavaScriptCore.VERSION_1_2;
- private static final String VERSION_1_3= JavaScriptCore.VERSION_1_3;
- private static final String VERSION_1_4= JavaScriptCore.VERSION_1_4;
- private static final String VERSION_1_5= JavaScriptCore.VERSION_1_5;
- private static final String VERSION_1_6= JavaScriptCore.VERSION_1_6;
-
- private static final String ERROR= JavaScriptCore.ERROR;
- private static final String WARNING= JavaScriptCore.WARNING;
- private static final String IGNORE= JavaScriptCore.IGNORE;
-
- private static final String ENABLED= JavaScriptCore.ENABLED;
-// private static final String DISABLED= JavaScriptCore.DISABLED;
-
-
- private static final String DEFAULT_CONF= "default"; //$NON-NLS-1$
- private static final String USER_CONF= "user"; //$NON-NLS-1$
-
- private ArrayList fComplianceControls;
-// private PixelConverter fPixelConverter;
-
- private String[] fRememberedUserCompliance;
-
- private static final int IDX_ASSERT_AS_IDENTIFIER= 0;
- private static final int IDX_ENUM_AS_IDENTIFIER= 1;
- private static final int IDX_SOURCE_COMPATIBILITY= 2;
- private static final int IDX_CODEGEN_TARGET_PLATFORM= 3;
- private static final int IDX_COMPLIANCE= 4;
- private static final int IDX_INLINE_JSR_BYTECODE= 5;
-
- private IStatus fComplianceStatus;
-
- private Link fJRE50InfoText;
- private Composite fControlsComposite;
- private ControlEnableState fBlockEnableState;
-
- public ComplianceConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getKeys(), container);
-
- fBlockEnableState= null;
- fComplianceControls= new ArrayList();
-
- fComplianceStatus= new StatusInfo();
-
- fRememberedUserCompliance= new String[] { // caution: order depends on IDX_* constants
- getValue(PREF_PB_ASSERT_AS_IDENTIFIER),
- getValue(PREF_SOURCE_COMPATIBILITY),
- getValue(PREF_CODEGEN_TARGET_PLATFORM),
- getValue(PREF_COMPLIANCE),
- getValue(PREF_CODEGEN_INLINE_JSR_BYTECODE),
- };
- }
-
- private static Key[] getKeys() {
- return new Key[] {
- PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
- PREF_CODEGEN_INLINE_JSR_BYTECODE,
- PREF_COMPLIANCE, PREF_SOURCE_COMPATIBILITY,
- PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_ASSERT_AS_IDENTIFIER
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#settingsUpdated()
- */
- protected void settingsUpdated() {
- setValue(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
- super.settingsUpdated();
- }
-
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
-// fPixelConverter= new PixelConverter(parent);
- setShell(parent.getShell());
-
- Composite complianceComposite= createComplianceTabContent(parent);
-
- validateSettings(null, null, null);
-
- return complianceComposite;
- }
-
- public void enablePreferenceContent(boolean enable) {
- if (fControlsComposite != null && !fControlsComposite.isDisposed()) {
- if (enable) {
- if (fBlockEnableState != null) {
- fBlockEnableState.restore();
- fBlockEnableState= null;
- }
- } else {
- if (fBlockEnableState == null) {
- fBlockEnableState= ControlEnableState.disable(fControlsComposite);
- }
- }
- }
- }
-
- private Composite createComplianceTabContent(Composite folder) {
-
-
- String[] values3456= new String[] { VERSION_1_4, VERSION_1_5};
- String[] values3456Labels= new String[] {
-// PreferencesMessages.ComplianceConfigurationBlock_version13,
- PreferencesMessages.ComplianceConfigurationBlock_version14,
- PreferencesMessages.ComplianceConfigurationBlock_version15
-// PreferencesMessages.ComplianceConfigurationBlock_version16
- };
-
- final ScrolledPageContent sc1 = new ScrolledPageContent(folder);
- Composite composite= sc1.getBody();
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- fControlsComposite= new Composite(composite, SWT.NONE);
- fControlsComposite.setFont(composite.getFont());
- fControlsComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
-
- layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
- fControlsComposite.setLayout(layout);
-
- int nColumns= 3;
-
- layout= new GridLayout();
- layout.numColumns= nColumns;
-
- Group group= new Group(fControlsComposite, SWT.NONE);
- group.setFont(fControlsComposite.getFont());
- group.setText(PreferencesMessages.ComplianceConfigurationBlock_compliance_group_label);
- group.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
- group.setLayout(layout);
-
- String label= PreferencesMessages.ComplianceConfigurationBlock_compiler_compliance_label;
- Combo combo = addComboBox(group, label, PREF_COMPLIANCE, values3456, values3456Labels, 0);
- combo.setEnabled(false);
-
-// label= PreferencesMessages.ComplianceConfigurationBlock_default_settings_label;
-// addCheckBox(group, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT_CONF, USER_CONF }, 0);
-//
-// int indent= fPixelConverter.convertWidthInCharsToPixels(2);
-// Control[] otherChildren= group.getChildren();
-//
-// String[] versions= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4, VERSION_1_5, VERSION_1_6 };
-// String[] versionsLabels= new String[] {
-// PreferencesMessages.ComplianceConfigurationBlock_version11,
-// PreferencesMessages.ComplianceConfigurationBlock_version12,
-// PreferencesMessages.ComplianceConfigurationBlock_version13,
-// PreferencesMessages.ComplianceConfigurationBlock_version14,
-// PreferencesMessages.ComplianceConfigurationBlock_version15,
-// PreferencesMessages.ComplianceConfigurationBlock_version16
-// };
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_codegen_targetplatform_label;
-// addComboBox(group, label, PREF_CODEGEN_TARGET_PLATFORM, versions, versionsLabels, indent);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_source_compatibility_label;
-// addComboBox(group, label, PREF_SOURCE_COMPATIBILITY, values3456, values3456Labels, indent);
-//
-// String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
-//
-// String[] errorWarningIgnoreLabels= new String[] {
-// PreferencesMessages.ComplianceConfigurationBlock_error,
-// PreferencesMessages.ComplianceConfigurationBlock_warning,
-// PreferencesMessages.ComplianceConfigurationBlock_ignore
-// };
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_pb_assert_as_identifier_label;
-// addComboBox(group, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_pb_enum_as_identifier_label;
-// addComboBox(group, label, PREF_PB_ENUM_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
-//
-//
-// Control[] allChildren= group.getChildren();
-// fComplianceControls.addAll(Arrays.asList(allChildren));
-// fComplianceControls.removeAll(Arrays.asList(otherChildren));
-//
-// layout= new GridLayout();
-// layout.numColumns= nColumns;
-//
-// group= new Group(fControlsComposite, SWT.NONE);
-// group.setFont(fControlsComposite.getFont());
-// group.setText(PreferencesMessages.ComplianceConfigurationBlock_classfiles_group_label);
-// group.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
-// group.setLayout(layout);
-//
-// String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
-// String[] enableDisableValues= new String[] { ENABLED, DISABLED };
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_variable_attr_label;
-// addCheckBox(group, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_line_number_attr_label;
-// addCheckBox(group, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_source_file_attr_label;
-// addCheckBox(group, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_codegen_unused_local_label;
-// addCheckBox(group, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
-//
-// label= PreferencesMessages.ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label;
-// addCheckBox(group, label, PREF_CODEGEN_INLINE_JSR_BYTECODE, enableDisableValues, 0);
-//
-// fJRE50InfoText= new Link(composite, SWT.WRAP);
-// fJRE50InfoText.setFont(composite.getFont());
-// // set a text: not the real one, just for layouting
-// fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info_project, new String[] { VERSION_1_3, VERSION_1_3 }));
-// fJRE50InfoText.setVisible(false);
-// fJRE50InfoText.addSelectionListener(new SelectionListener() {
-// public void widgetDefaultSelected(SelectionEvent e) {
-// if ("1".equals(e.text)) { //$NON-NLS-1$
-// openJREInstallPreferencePage();
-// } else {
-// openBuildPathPropertyPage();
-// }
-// }
-// public void widgetSelected(SelectionEvent e) {
-// widgetDefaultSelected(e);
-// }
-// });
-// GridData gd= new GridData(GridData.FILL, GridData.FILL, true, true);
-// gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
-// fJRE50InfoText.setLayoutData(gd);
-// validateJRE50Status();
-
- return sc1;
- }
-
- protected final void openBuildPathPropertyPage() {
- if (getPreferenceContainer() != null) {
- Map data= new HashMap();
- data.put(BuildPathsPropertyPage.DATA_REVEAL_ENTRY, JavaRuntime.getDefaultJREContainerEntry());
- getPreferenceContainer().openPage(BuildPathsPropertyPage.PROP_ID, data);
- }
- validateJRE50Status();
- }
-
- protected final void openJREInstallPreferencePage() {
- String jreID= BuildPathSupport.JRE_PREF_PAGE_ID;
- if (fProject == null && getPreferenceContainer() != null) {
- getPreferenceContainer().openPage(jreID, null);
- } else {
- PreferencesUtil.createPreferenceDialogOn(getShell(), jreID, new String[] { jreID }, null).open();
- }
- validateJRE50Status();
- }
-
- /* (non-javadoc)
- * Update fields and validate.
- * @param changedKey Key that changed, or null, if all changed.
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (!areSettingsEnabled()) {
- return;
- }
- if (changedKey != null) {
- if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
- updateComplianceEnableState();
- updateComplianceDefaultSettings(true, null);
- fComplianceStatus= validateCompliance();
- } else if (PREF_COMPLIANCE.equals(changedKey)) {
- // set compliance settings to default
-// Object oldDefault= setValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF);
- updateComplianceEnableState();
-// updateComplianceDefaultSettings(USER_CONF.equals(oldDefault), oldValue);
- fComplianceStatus= validateCompliance();
- validateJRE50Status();
- } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey)) {
- updateAssertEnumAsIdentifierEnableState();
- fComplianceStatus= validateCompliance();
- } else if (PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey)) {
- updateInlineJSREnableState();
- fComplianceStatus= validateCompliance();
- } else {
- return;
- }
- } else {
-// updateComplianceEnableState();
-// updateAssertEnumAsIdentifierEnableState();
-// updateInlineJSREnableState();
- fComplianceStatus= validateCompliance();
-// validateJRE50Status();
- }
- fContext.statusChanged(fComplianceStatus);
- }
-
- private void validateJRE50Status() {
- if (fJRE50InfoText != null && !fJRE50InfoText.isDisposed()) {
- boolean isVisible= false;
- String compliance= getStoredValue(PREF_COMPLIANCE); // get actual value
- IVMInstall install= null;
- if (fProject != null) { // project specific settings: only test if a 50 JRE is installed
- try {
- install= JavaRuntime.getVMInstall(JavaScriptCore.create(fProject));
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- } else {
- install= JavaRuntime.getDefaultVMInstall();
- }
- if (install instanceof IVMInstall2) {
- String compilerCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, compliance);
- if (JavaModelUtil.isVersionLessThan(compilerCompliance, compliance)) { // Discourage using compiler with version less than compliance
- String[] args= { getVersionLabel(compliance), getVersionLabel(compilerCompliance) };
- if (fProject == null) {
- fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info, args));
- } else {
- fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info_project, args));
- }
- isVisible= true;
- }
- }
- fJRE50InfoText.setVisible(isVisible);
- }
- }
-
- private String getVersionLabel(String version) {
- if (JavaModelUtil.isVersionLessThan(version, VERSION_1_5)) {
- return version; // for version <= 1.4, we can use the version as is
- }
- if (VERSION_1_5.equals(version))
- return PreferencesMessages.ComplianceConfigurationBlock_version15;
- return PreferencesMessages.ComplianceConfigurationBlock_version16;
- }
-
-
- private IStatus validateCompliance() {
- StatusInfo status= new StatusInfo();
- String compliance= getValue(PREF_COMPLIANCE);
- String source= getValue(PREF_SOURCE_COMPATIBILITY);
- String target= getValue(PREF_CODEGEN_TARGET_PLATFORM);
-
- // compliance must not be smaller than source or target
- if (JavaModelUtil.isVersionLessThan(compliance, source)) {
- status.setError(PreferencesMessages.ComplianceConfigurationBlock_src_greater_compliance);
- return status;
- }
-
- if (JavaModelUtil.isVersionLessThan(compliance, target)) {
- status.setError(PreferencesMessages.ComplianceConfigurationBlock_classfile_greater_compliance);
- return status;
- }
-
- // target must not be smaller than source
- if (!VERSION_1_3.equals(source) && JavaModelUtil.isVersionLessThan(target, source)) {
- status.setError(PreferencesMessages.ComplianceConfigurationBlock_classfile_greater_source);
- return status;
- }
-
- return status;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#useProjectSpecificSettings(boolean)
- */
- public void useProjectSpecificSettings(boolean enable) {
- super.useProjectSpecificSettings(enable);
- validateJRE50Status();
- }
-
- /*
- * Update the compliance controls' enable state
- */
- private void updateComplianceEnableState() {
- boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER_CONF);
- for (int i= fComplianceControls.size() - 1; i >= 0; i--) {
- Control curr= (Control) fComplianceControls.get(i);
- curr.setEnabled(enabled);
- }
- }
-
- private void updateAssertEnumAsIdentifierEnableState() {
- if (checkValue(INTR_DEFAULT_COMPLIANCE, USER_CONF)) {
- String compatibility= getValue(PREF_SOURCE_COMPATIBILITY);
-
- boolean isLessThan14= VERSION_1_3.equals(compatibility);
- updateRememberedComplianceOption(PREF_PB_ASSERT_AS_IDENTIFIER, IDX_ASSERT_AS_IDENTIFIER, isLessThan14);
- }
- }
-
- private void updateRememberedComplianceOption(Key prefKey, int idx, boolean enabled) {
- Combo combo= getComboBox(prefKey);
- combo.setEnabled(enabled);
-
- if (!enabled) {
- String val= getValue(prefKey);
- if (!ERROR.equals(val)) {
- setValue(prefKey, ERROR);
- updateCombo(combo);
- fRememberedUserCompliance[idx]= val;
- }
- } else {
- String val= fRememberedUserCompliance[idx];
- if (!ERROR.equals(val)) {
- setValue(prefKey, val);
- updateCombo(combo);
- }
- }
- }
-
- private void updateInlineJSREnableState() {
- String target= getValue(PREF_CODEGEN_TARGET_PLATFORM);
-
- boolean enabled= JavaModelUtil.isVersionLessThan(target, VERSION_1_5);
- Button checkBox= getCheckBox(PREF_CODEGEN_INLINE_JSR_BYTECODE);
- checkBox.setEnabled(enabled);
-
- if (!enabled) {
- String val= getValue(PREF_CODEGEN_INLINE_JSR_BYTECODE);
- fRememberedUserCompliance[IDX_INLINE_JSR_BYTECODE]= val;
-
- if (!ENABLED.equals(val)) {
- setValue(PREF_CODEGEN_INLINE_JSR_BYTECODE, ENABLED);
- updateCheckBox(checkBox);
- }
- } else {
- String val= fRememberedUserCompliance[IDX_INLINE_JSR_BYTECODE];
- if (!ENABLED.equals(val)) {
- setValue(PREF_CODEGEN_INLINE_JSR_BYTECODE, val);
- updateCheckBox(checkBox);
- }
- }
- }
-
- /*
- * Set the default compliance values derived from the chosen level
- */
- private void updateComplianceDefaultSettings(boolean rememberOld, String oldComplianceLevel) {
- String assertAsId, enumAsId, source, target;
- boolean isDefault= checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF);
- String complianceLevel= getValue(PREF_COMPLIANCE);
-
- if (isDefault) {
- if (rememberOld) {
- if (oldComplianceLevel == null) {
- oldComplianceLevel= complianceLevel;
- }
-
- fRememberedUserCompliance[IDX_ASSERT_AS_IDENTIFIER]= getValue(PREF_PB_ASSERT_AS_IDENTIFIER);
- fRememberedUserCompliance[IDX_SOURCE_COMPATIBILITY]= getValue(PREF_SOURCE_COMPATIBILITY);
- fRememberedUserCompliance[IDX_CODEGEN_TARGET_PLATFORM]= getValue(PREF_CODEGEN_TARGET_PLATFORM);
- fRememberedUserCompliance[IDX_COMPLIANCE]= oldComplianceLevel;
- }
-
- if (VERSION_1_4.equals(complianceLevel)) {
- assertAsId= WARNING;
- enumAsId= WARNING;
- source= VERSION_1_3;
- target= VERSION_1_2;
- } else if (VERSION_1_5.equals(complianceLevel)) {
- assertAsId= ERROR;
- enumAsId= ERROR;
- source= VERSION_1_5;
- target= VERSION_1_5;
- } else if (VERSION_1_6.equals(complianceLevel)) {
- assertAsId= ERROR;
- enumAsId= ERROR;
- source= VERSION_1_6;
- target= VERSION_1_6;
- } else {
- assertAsId= IGNORE;
- enumAsId= IGNORE;
- source= VERSION_1_3;
- target= VERSION_1_1;
- }
- } else {
- if (rememberOld && complianceLevel.equals(fRememberedUserCompliance[IDX_COMPLIANCE])) {
- assertAsId= fRememberedUserCompliance[IDX_ASSERT_AS_IDENTIFIER];
- source= fRememberedUserCompliance[IDX_SOURCE_COMPATIBILITY];
- target= fRememberedUserCompliance[IDX_CODEGEN_TARGET_PLATFORM];
- } else {
- updateInlineJSREnableState();
- updateAssertEnumAsIdentifierEnableState();
- return;
- }
- }
- setValue(PREF_PB_ASSERT_AS_IDENTIFIER, assertAsId);
- setValue(PREF_SOURCE_COMPATIBILITY, source);
- setValue(PREF_CODEGEN_TARGET_PLATFORM, target);
- updateControls();
- updateInlineJSREnableState();
- updateAssertEnumAsIdentifierEnableState();
- }
-
- /*
- * Evaluate if the current compliance setting correspond to a default setting
- */
- private String getCurrentCompliance() {
- Object complianceLevel= getValue(PREF_COMPLIANCE);
- if ((VERSION_1_3.equals(complianceLevel)
- && IGNORE.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER))
- && VERSION_1_3.equals(getValue(PREF_SOURCE_COMPATIBILITY))
- && VERSION_1_1.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))
- || (VERSION_1_4.equals(complianceLevel)
- && WARNING.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER))
- && VERSION_1_3.equals(getValue(PREF_SOURCE_COMPATIBILITY))
- && VERSION_1_2.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))
- || (VERSION_1_5.equals(complianceLevel)
- && ERROR.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER))
- && VERSION_1_5.equals(getValue(PREF_SOURCE_COMPATIBILITY))
- && VERSION_1_5.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))
- || (VERSION_1_6.equals(complianceLevel)
- && ERROR.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER))
- && VERSION_1_6.equals(getValue(PREF_SOURCE_COMPATIBILITY))
- && VERSION_1_6.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))) {
- return DEFAULT_CONF;
- }
- return USER_CONF;
- }
-
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- String title= PreferencesMessages.ComplianceConfigurationBlock_needsbuild_title;
- String message;
- if (workspaceSettings) {
- message= PreferencesMessages.ComplianceConfigurationBlock_needsfullbuild_message;
- } else {
- message= PreferencesMessages.ComplianceConfigurationBlock_needsprojectbuild_message;
- }
- return new String[] { title, message };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#performOk()
- */
- public boolean performOk() {
- setValue(INTR_DEFAULT_COMPLIANCE, null);
- return super.performOk();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#performApply()
- */
- public boolean performApply() {
- setValue(INTR_DEFAULT_COMPLIANCE, null);
- boolean result= super.performApply();
- setValue(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CompliancePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CompliancePreferencePage.java
deleted file mode 100644
index db3c85c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CompliancePreferencePage.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-
-/**
- * Page used to configure both workspace and project specific compiler settings
- */
-public class CompliancePreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CompliancePreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CompliancePreferencePage"; //$NON-NLS-1$
-
- private ComplianceConfigurationBlock fConfigurationBlock;
-
- public CompliancePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.CompliancePreferencePage_description);
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.CompliancePreferencePage_title);
-
- JavaRuntime.getDefaultVMInstall(); // make sure the default JRE is detected (bug 152384)
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new ComplianceConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- if (isProjectPreferencePage()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.COMPILER_PROPERTY_PAGE);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE);
- }
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enablePreferenceContent(boolean)
- */
- protected void enablePreferenceContent(boolean enable) {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.enablePreferenceContent(enable);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/EditTemplateDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/EditTemplateDialog.java
deleted file mode 100644
index e8b621bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/EditTemplateDialog.java
+++ /dev/null
@@ -1,608 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextListener;
-import org.eclipse.jface.text.ITextOperationTarget;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextEvent;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.text.templates.ContextTypeRegistry;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.custom.VerifyKeyListener;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-/**
- * Dialog to edit a template.
- */
-class EditTemplateDialog extends StatusDialog {
-
- private static class TextViewerAction extends Action implements IUpdate {
-
- private int fOperationCode= -1;
- private ITextOperationTarget fOperationTarget;
-
- /**
- * Creates a new action.
- *
- * @param viewer the viewer
- * @param operationCode the opcode
- */
- public TextViewerAction(ITextViewer viewer, int operationCode) {
- fOperationCode= operationCode;
- fOperationTarget= viewer.getTextOperationTarget();
- update();
- }
-
- /**
- * Updates the enabled state of the action.
- * Fires a property change if the enabled state changes.
- *
- * @see Action#firePropertyChange(String, Object, Object)
- */
- public void update() {
-
- boolean wasEnabled= isEnabled();
- boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
- setEnabled(isEnabled);
-
- if (wasEnabled != isEnabled) {
- firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
- }
- }
-
- /**
- * @see Action#run()
- */
- public void run() {
- if (fOperationCode != -1 && fOperationTarget != null) {
- fOperationTarget.doOperation(fOperationCode);
- }
- }
- }
-
- private Template fTemplate;
-
- private Text fNameText;
- private Text fDescriptionText;
- private Combo fContextCombo;
- private SourceViewer fPatternEditor;
- private Button fInsertVariableButton;
- private Button fAutoInsertCheckbox;
- private boolean fIsNameModifiable;
-
- private StatusInfo fValidationStatus;
- private boolean fSuppressError= true; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=4354
- private Map fGlobalActions= new HashMap(10);
- private List fSelectionActions = new ArrayList(3);
- private String[][] fContextTypes;
-
- private ContextTypeRegistry fContextTypeRegistry;
-
- private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor();
-
- /**
- * Creates a new dialog.
- *
- * @param parent the shell parent of the dialog
- * @param template the template to edit
- * @param edit whether this is a new template or an existing being edited
- * @param isNameModifiable whether the name of the template may be modified
- * @param registry the context type registry to use
- */
- public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, ContextTypeRegistry registry) {
- super(parent);
-
- setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
-
- String title= edit
- ? PreferencesMessages.EditTemplateDialog_title_edit
- : PreferencesMessages.EditTemplateDialog_title_new;
- setTitle(title);
-
- fTemplate= template;
- fIsNameModifiable= isNameModifiable;
-
- String delim= new Document().getLegalLineDelimiters()[0];
-
- List contexts= new ArrayList();
- for (Iterator it= registry.contextTypes(); it.hasNext();) {
- TemplateContextType type= (TemplateContextType) it.next();
- if (type.getId().equals("javadoc")) //$NON-NLS-1$
- contexts.add(new String[] { type.getId(), type.getName(), "/**" + delim }); //$NON-NLS-1$
- else
- contexts.add(0, new String[] { type.getId(), type.getName(), "" }); //$NON-NLS-1$
- }
- fContextTypes= (String[][]) contexts.toArray(new String[contexts.size()][]);
-
- fValidationStatus= new StatusInfo();
-
- fContextTypeRegistry= registry;
-
- TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId());
- fTemplateProcessor.setContextType(type);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.StatusDialog#create()
- */
- public void create() {
- super.create();
- updateStatusAndButtons();
- boolean isEmpty= fNameText != null && fNameText.getText().length() == 0;
- getButton(IDialogConstants.OK_ID).setEnabled(!isEmpty);
- }
-
- /*
- * @see Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite ancestor) {
- Composite parent= new Composite(ancestor, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- parent.setLayout(layout);
- parent.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- ModifyListener listener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doTextWidgetChanged(e.widget);
- }
- };
-
- if (fIsNameModifiable) {
- createLabel(parent, PreferencesMessages.EditTemplateDialog_name);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout= new GridLayout();
- layout.numColumns= 4;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- fNameText= createText(composite);
- fNameText.addFocusListener(new FocusListener() {
-
- public void focusGained(FocusEvent e) {
- }
-
- public void focusLost(FocusEvent e) {
- if (fSuppressError) {
- fSuppressError= false;
- updateStatusAndButtons();
- }
- }
- });
-
- createLabel(composite, PreferencesMessages.EditTemplateDialog_context);
- fContextCombo= new Combo(composite, SWT.READ_ONLY);
-
- for (int i= 0; i < fContextTypes.length; i++) {
- fContextCombo.add(fContextTypes[i][1]);
- }
-
- fContextCombo.addModifyListener(listener);
-
- fAutoInsertCheckbox= createCheckbox(composite, PreferencesMessages.EditTemplateDialog_autoinsert);
- fAutoInsertCheckbox.setSelection(fTemplate.isAutoInsertable());
- }
-
- createLabel(parent, PreferencesMessages.EditTemplateDialog_description);
-
- int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY;
- fDescriptionText= new Text(parent, descFlags );
- fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- fDescriptionText.addModifyListener(listener);
-
- Label patternLabel= createLabel(parent, PreferencesMessages.EditTemplateDialog_pattern);
- patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
- fPatternEditor= createEditor(parent);
-
- Label filler= new Label(parent, SWT.NONE);
- filler.setLayoutData(new GridData());
-
- Composite composite= new Composite(parent, SWT.NONE);
- layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData());
-
- fInsertVariableButton= new Button(composite, SWT.NONE);
- fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
- fInsertVariableButton.setText(PreferencesMessages.EditTemplateDialog_insert_variable);
- fInsertVariableButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fPatternEditor.getTextWidget().setFocus();
- fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {}
- });
-
- fDescriptionText.setText(fTemplate.getDescription());
- if (fIsNameModifiable) {
- fNameText.setText(fTemplate.getName());
- fNameText.addModifyListener(listener);
- fContextCombo.select(getIndex(fTemplate.getContextTypeId()));
- } else {
- fPatternEditor.getControl().setFocus();
- }
- initializeActions();
-
- applyDialogFont(parent);
- return composite;
- }
-
- protected void doTextWidgetChanged(Widget w) {
- if (w == fNameText) {
- fSuppressError= false;
- updateStatusAndButtons();
- } else if (w == fContextCombo) {
- String contextId= getContextId();
- fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId));
- IDocument document= fPatternEditor.getDocument();
- String prefix= getPrefix();
- document.set(prefix + getPattern());
- fPatternEditor.setVisibleRegion(prefix.length(), document.getLength() - prefix.length());
- } else if (w == fDescriptionText) {
- // nothing
- }
- }
-
- private String getContextId() {
- if (fContextCombo != null && !fContextCombo.isDisposed()) {
- String name= fContextCombo.getText();
- for (int i= 0; i < fContextTypes.length; i++) {
- if (name.equals(fContextTypes[i][1])) {
- return fContextTypes[i][0];
- }
- }
- }
-
- return fTemplate.getContextTypeId();
- }
-
- protected void doSourceChanged(IDocument document) {
- String text= document.get();
- fValidationStatus.setOK();
- TemplateContextType contextType= fContextTypeRegistry.getContextType(getContextId());
- if (contextType != null) {
- try {
- contextType.validate(text);
- } catch (TemplateException e) {
- fValidationStatus.setError(e.getLocalizedMessage());
- }
- }
-
- updateUndoAction();
- updateStatusAndButtons();
- }
-
- private static GridData getButtonGridData(Button button) {
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- return data;
- }
-
- private static Label createLabel(Composite parent, String name) {
- Label label= new Label(parent, SWT.NULL);
- label.setText(name);
- label.setLayoutData(new GridData());
-
- return label;
- }
-
- private static Button createCheckbox(Composite parent, String name) {
- Button button= new Button(parent, SWT.CHECK);
- button.setText(name);
- button.setLayoutData(new GridData());
-
- return button;
- }
-
- private static Text createText(Composite parent) {
- Text text= new Text(parent, SWT.BORDER);
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- return text;
- }
-
- private SourceViewer createEditor(Composite parent) {
- String prefix= getPrefix();
- IDocument document= new Document(prefix + fTemplate.getPattern());
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
- CodeTemplateSourceViewerConfiguration configuration= new CodeTemplateSourceViewerConfiguration(tools.getColorManager(), store, null, fTemplateProcessor);
- viewer.configure(configuration);
- viewer.setEditable(true);
- viewer.setDocument(document, prefix.length(), document.getLength() - prefix.length());
-
- Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- viewer.getTextWidget().setFont(font);
- new JavaSourcePreviewerUpdater(viewer, configuration, store);
-
- int nLines= document.getNumberOfLines();
- if (nLines < 5) {
- nLines= 5;
- } else if (nLines > 12) {
- nLines= 12;
- }
-
- Control control= viewer.getControl();
- GridData data= new GridData(GridData.FILL_BOTH);
- data.widthHint= convertWidthInCharsToPixels(80);
- data.heightHint= convertHeightInCharsToPixels(nLines);
- control.setLayoutData(data);
-
- viewer.addTextListener(new ITextListener() {
- public void textChanged(TextEvent event) {
- if (event .getDocumentEvent() != null)
- doSourceChanged(event.getDocumentEvent().getDocument());
- }
- });
-
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- updateSelectionDependentActions();
- }
- });
-
- viewer.prependVerifyKeyListener(new VerifyKeyListener() {
- public void verifyKey(VerifyEvent event) {
- handleVerifyKeyPressed(event);
- }
- });
-
- return viewer;
- }
-
- private String getPrefix() {
- String id= getContextId();
- int idx= getIndex(id);
- if (idx != -1)
- return fContextTypes[idx][2];
- else
- return ""; //$NON-NLS-1$
- }
-
- private void handleVerifyKeyPressed(VerifyEvent event) {
- if (!event.doit)
- return;
-
- if (event.stateMask != SWT.MOD1)
- return;
-
- switch (event.character) {
- case ' ':
- fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
- event.doit= false;
- break;
-
- // CTRL-Z
- case 'z' - 'a' + 1:
- fPatternEditor.doOperation(ITextOperationTarget.UNDO);
- event.doit= false;
- break;
- }
- }
-
- private void initializeActions() {
- TextViewerAction action= new TextViewerAction(fPatternEditor, ITextOperationTarget.UNDO);
- action.setText(PreferencesMessages.EditTemplateDialog_undo);
- fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
-
- action= new TextViewerAction(fPatternEditor, ITextOperationTarget.CUT);
- action.setText(PreferencesMessages.EditTemplateDialog_cut);
- fGlobalActions.put(ITextEditorActionConstants.CUT, action);
-
- action= new TextViewerAction(fPatternEditor, ITextOperationTarget.COPY);
- action.setText(PreferencesMessages.EditTemplateDialog_copy);
- fGlobalActions.put(ITextEditorActionConstants.COPY, action);
-
- action= new TextViewerAction(fPatternEditor, ITextOperationTarget.PASTE);
- action.setText(PreferencesMessages.EditTemplateDialog_paste);
- fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
-
- action= new TextViewerAction(fPatternEditor, ITextOperationTarget.SELECT_ALL);
- action.setText(PreferencesMessages.EditTemplateDialog_select_all);
- fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
-
- action= new TextViewerAction(fPatternEditor, ISourceViewer.CONTENTASSIST_PROPOSALS);
- action.setText(PreferencesMessages.EditTemplateDialog_content_assist);
- fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
-
- fSelectionActions.add(ITextEditorActionConstants.CUT);
- fSelectionActions.add(ITextEditorActionConstants.COPY);
- fSelectionActions.add(ITextEditorActionConstants.PASTE);
-
- // create context menu
- MenuManager manager= new MenuManager(null, null);
- manager.setRemoveAllWhenShown(true);
- manager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager mgr) {
- fillContextMenu(mgr);
- }
- });
-
- StyledText text= fPatternEditor.getTextWidget();
- Menu menu= manager.createContextMenu(text);
- text.setMenu(menu);
- }
-
- private void fillContextMenu(IMenuManager menu) {
- menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
- menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
-
- menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
- menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
-
- menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
- menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$
- }
-
- protected void updateSelectionDependentActions() {
- Iterator iterator= fSelectionActions.iterator();
- while (iterator.hasNext())
- updateAction((String)iterator.next());
- }
-
- protected void updateUndoAction() {
- IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
- if (action instanceof IUpdate)
- ((IUpdate) action).update();
- }
-
- protected void updateAction(String actionId) {
- IAction action= (IAction) fGlobalActions.get(actionId);
- if (action instanceof IUpdate)
- ((IUpdate) action).update();
- }
-
- private int getIndex(String contextid) {
-
- if (contextid == null)
- return -1;
-
- for (int i= 0; i < fContextTypes.length; i++) {
- if (contextid.equals(fContextTypes[i][0])) {
- return i;
- }
- }
- return -1;
- }
-
- protected void okPressed() {
- String name= fNameText == null ? fTemplate.getName() : fNameText.getText();
- boolean isAutoInsertable= fAutoInsertCheckbox != null && fAutoInsertCheckbox.getSelection();
- fTemplate= new Template(name, fDescriptionText.getText(), getContextId(), getPattern(), isAutoInsertable);
- super.okPressed();
- }
-
- private void updateStatusAndButtons() {
- StatusInfo status= fValidationStatus;
- boolean isEmpty= fNameText != null && fNameText.getText().length() == 0;
- if (!fSuppressError && isEmpty) {
- status= new StatusInfo();
- status.setError(PreferencesMessages.EditTemplateDialog_error_noname);
- } else if (fNameText != null && fNameText.getText().indexOf(' ') > -1) {
- status= new StatusInfo();
- status.setError(PreferencesMessages.EditTemplateDialog_error_spaces);
- }
- updateStatus(status);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG);
- }
-
- /**
- * Returns the created template.
- *
- * @return the created template
- *
- */
- public Template getTemplate() {
- return fTemplate;
- }
-
- private String getPattern() {
- IDocument doc= fPatternEditor.getDocument();
- IRegion visible= fPatternEditor.getVisibleRegion();
- try {
- return doc.get(visible.getOffset(), doc.getLength() - visible.getOffset());
- } catch (BadLocationException e) {
- return ""; //$NON-NLS-1$
- }
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
- *
- */
- protected IDialogSettings getDialogBoundsSettings() {
- String sectionName= getClass().getName() + "_dialogBounds"; //$NON-NLS-1$
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- IDialogSettings section= settings.getSection(sectionName);
- if (section == null)
- section= settings.addNewSection(sectionName);
- return section;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingConfigurationBlock.java
deleted file mode 100644
index 83bbd78b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingConfigurationBlock.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StackLayout;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.folding.JavaFoldingStructureProviderDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingPreferenceBlock;
-
-/**
- * Configures Java Editor folding preferences.
- *
- *
- */
-class FoldingConfigurationBlock implements IPreferenceConfigurationBlock {
-
- private static class ErrorPreferences implements IJavaFoldingPreferenceBlock {
- private String fMessage;
-
- protected ErrorPreferences(String message) {
- fMessage= message;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
- */
- public Control createControl(Composite composite) {
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setLayout(new FillLayout(SWT.VERTICAL));
-
- Label label= new Label(inner, SWT.CENTER);
- label.setText(fMessage);
-
- return inner;
- }
-
- public void initialize() {
- }
-
- public void performOk() {
- }
-
- public void performDefaults() {
- }
-
- public void dispose() {
- }
-
- }
-
- /** The overlay preference store. */
- private final OverlayPreferenceStore fStore;
-
- /* The controls */
- private Combo fProviderCombo;
- private Button fFoldingCheckbox;
- private ComboViewer fProviderViewer;
- private Composite fGroup;
- private StackLayout fStackLayout;
-
- /* the model */
- private final Map fProviderDescriptors;
- private final Map fProviderPreferences;
- private final Map fProviderControls;
-
-
- public FoldingConfigurationBlock(OverlayPreferenceStore store) {
- Assert.isNotNull(store);
- fStore= store;
- fStore.addKeys(createOverlayStoreKeys());
- fProviderDescriptors= createListModel();
- fProviderPreferences= new HashMap();
- fProviderControls= new HashMap();
- }
-
- private Map createListModel() {
- JavaFoldingStructureProviderRegistry reg= JavaScriptPlugin.getDefault().getFoldingStructureProviderRegistry();
- reg.reloadExtensions();
- JavaFoldingStructureProviderDescriptor[] descs= reg.getFoldingProviderDescriptors();
- Map map= new HashMap();
- for (int i= 0; i < descs.length; i++) {
- map.put(descs[i].getId(), descs[i]);
- }
- return map;
- }
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- ArrayList overlayKeys= new ArrayList();
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_ENABLED));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOLDING_PROVIDER));
-
- OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
- overlayKeys.toArray(keys);
- return keys;
- }
-
- /**
- * Creates page for folding preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(Composite parent) {
-
- Composite composite= new Composite(parent, SWT.NULL);
- // assume parent page uses griddata
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_FILL);
- composite.setLayoutData(gd);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- PixelConverter pc= new PixelConverter(composite);
- layout.verticalSpacing= pc.convertHeightInCharsToPixels(1) / 2;
- composite.setLayout(layout);
-
-
- /* check box for new editors */
- fFoldingCheckbox= new Button(composite, SWT.CHECK);
- fFoldingCheckbox.setText(PreferencesMessages.FoldingConfigurationBlock_enable);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
- fFoldingCheckbox.setLayoutData(gd);
- fFoldingCheckbox.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- boolean enabled= fFoldingCheckbox.getSelection();
- fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, enabled);
- updateCheckboxDependencies();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- Label label= new Label(composite, SWT.CENTER);
- gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
- label.setLayoutData(gd);
-
- if (fProviderDescriptors.size() > 1) {
- /* list */
- Composite comboComp= new Composite(composite, SWT.NONE);
- gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
- GridLayout gridLayout= new GridLayout(2, false);
- gridLayout.marginWidth= 0;
- comboComp.setLayout(gridLayout);
-
- Label comboLabel= new Label(comboComp, SWT.CENTER);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER);
- comboLabel.setLayoutData(gd);
- comboLabel.setText(PreferencesMessages.FoldingConfigurationBlock_combo_caption);
-
- label= new Label(composite, SWT.CENTER);
- gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
- label.setLayoutData(gd);
-
- fProviderCombo= new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_CENTER);
- fProviderCombo.setLayoutData(gd);
-
- fProviderViewer= createProviderViewer();
- }
-
- Composite groupComp= new Composite(composite, SWT.NONE);
- gd= new GridData(GridData.FILL_BOTH);
- gd.horizontalSpan= 2;
- groupComp.setLayoutData(gd);
- GridLayout gridLayout= new GridLayout(1, false);
- gridLayout.marginWidth= 0;
- groupComp.setLayout(gridLayout);
-
- /* contributed provider preferences. */
- fGroup= new Composite(groupComp, SWT.NONE);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
- fGroup.setLayoutData(gd);
- fStackLayout= new StackLayout();
- fGroup.setLayout(fStackLayout);
-
- return composite;
- }
-
- private ComboViewer createProviderViewer() {
- /* list viewer */
- ComboViewer viewer= new ComboViewer(fProviderCombo);
- viewer.setContentProvider(new IStructuredContentProvider() {
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer v, Object oldInput, Object newInput) {
- }
-
- /*
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- return fProviderDescriptors.values().toArray();
- }
- });
- viewer.setLabelProvider(new LabelProvider() {
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- return ((JavaFoldingStructureProviderDescriptor) element).getName();
- }
- });
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection sel= (IStructuredSelection) event.getSelection();
- if (!sel.isEmpty()) {
- fStore.setValue(PreferenceConstants.EDITOR_FOLDING_PROVIDER, ((JavaFoldingStructureProviderDescriptor) sel.getFirstElement()).getId());
- updateListDependencies();
- }
- }
- });
- viewer.setInput(fProviderDescriptors);
- viewer.refresh();
-
- return viewer;
- }
-
- private void updateCheckboxDependencies() {
- }
-
- void updateListDependencies() {
- String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
- JavaFoldingStructureProviderDescriptor desc= (JavaFoldingStructureProviderDescriptor) fProviderDescriptors.get(id);
- IJavaFoldingPreferenceBlock prefs;
-
- if (desc == null) {
- // safety in case there is no such descriptor
- String message= Messages.format(PreferencesMessages.FoldingConfigurationBlock_error_not_exist, id);
- JavaScriptPlugin.log(new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null));
- prefs= new ErrorPreferences(message);
- } else {
- prefs= (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id);
- if (prefs == null) {
- try {
- prefs= desc.createPreferences();
- fProviderPreferences.put(id, prefs);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- prefs= new ErrorPreferences(e.getLocalizedMessage());
- }
- }
- }
-
- Control control= (Control) fProviderControls.get(id);
- if (control == null) {
- control= prefs.createControl(fGroup);
- if (control == null) {
- String message= PreferencesMessages.FoldingConfigurationBlock_info_no_preferences;
- control= new ErrorPreferences(message).createControl(fGroup);
- } else {
- fProviderControls.put(id, control);
- }
- }
- Dialog.applyDialogFont(control);
- fStackLayout.topControl= control;
- control.pack();
- fGroup.layout();
- fGroup.getParent().layout();
-
- prefs.initialize();
- }
-
- public void initialize() {
- restoreFromPreferences();
- }
-
- public void performOk() {
- for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
- IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
- prefs.performOk();
- }
- }
-
- public void performDefaults() {
- restoreFromPreferences();
- for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
- IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
- prefs.performDefaults();
- }
- }
-
- public void dispose() {
- for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
- IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
- prefs.dispose();
- }
- }
-
- private void restoreFromPreferences() {
- boolean enabled= fStore.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
- fFoldingCheckbox.setSelection(enabled);
- updateCheckboxDependencies();
-
- String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
- Object provider= fProviderDescriptors.get(id);
-
- // Fallback to default
- if (provider == null) {
- String message= Messages.format(PreferencesMessages.FoldingConfigurationBlock_warning_providerNotFound_resetToDefault, id);
- JavaScriptPlugin.log(new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null));
-
- id= JavaScriptPlugin.getDefault().getPreferenceStore().getDefaultString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
-
- provider= fProviderDescriptors.get(id);
- Assert.isNotNull(provider);
-
- fStore.setToDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
- }
-
- if (fProviderViewer == null)
- updateListDependencies();
- else
- fProviderViewer.setSelection(new StructuredSelection(provider), true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingPreferencePage.java
deleted file mode 100644
index 7c9b5750..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/FoldingPreferencePage.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * The page for setting the editor options.
- */
-public final class FoldingPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.JavaEditorPreferencePage_folding_title;
- setDescription(description);
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null; // no description for new look.
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new FoldingConfigurationBlock(overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java
deleted file mode 100644
index d4333af3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-/**
- * Interface for preference and property configuration blocks which can either be
- * wrapped by a {@link org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigurationBlockPreferenceAndPropertyPage}
- * or be included some preference page.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- */
-public interface IPreferenceAndPropertyConfigurationBlock extends IPreferenceConfigurationBlock {
-
- /**
- * Disable project specific settings for the settings configured by this block.
- */
- public abstract void disableProjectSettings();
-
- /**
- * Enabled project specific settings for the settings configured by this block.
- */
- public abstract void enableProjectSettings();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java
deleted file mode 100644
index b3f92b85..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-
-/**
- * Interface for preference configuration blocks which can either be
- * wrapped by a {@link org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage}
- * or be included some preference page.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- */
-public interface IPreferenceConfigurationBlock {
-
- /**
- * Creates the preference control.
- *
- * @param parent the parent composite to which to add the preferences control
- * @return the control that was added to <code>parent</code>
- */
- Control createControl(Composite parent);
-
- /**
- * Called after creating the control. Implementations should load the
- * preferences values and update the controls accordingly.
- */
- void initialize();
-
- /**
- * Called when the <code>OK</code> button is pressed on the preference
- * page. Implementations should commit the configured preference settings
- * into their form of preference storage.
- */
- void performOk();
-
- /**
- * Called when the <code>Defaults</code> button is pressed on the
- * preference page. Implementation should reset any preference settings to
- * their default values and adjust the controls accordingly.
- */
- void performDefaults();
-
- /**
- * Called when the preference page is being disposed. Implementations should
- * free any resources they are holding on to.
- */
- void dispose();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java
deleted file mode 100644
index 72b540d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java
+++ /dev/null
@@ -1,508 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/*
- * The page for setting the organize import settings
- */
-public class ImportOrganizeConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final Key PREF_IMPORTORDER= getJDTUIKey(PreferenceConstants.ORGIMPORTS_IMPORTORDER);
- private static final Key PREF_ONDEMANDTHRESHOLD= getJDTUIKey(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD);
- private static final Key PREF_IGNORELOWERCASE= getJDTUIKey(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
- private static final Key PREF_STATICONDEMANDTHRESHOLD= getJDTUIKey(PreferenceConstants.ORGIMPORTS_STATIC_ONDEMANDTHRESHOLD);
-
- private static final String DIALOGSETTING_LASTLOADPATH= JavaScriptUI.ID_PLUGIN + ".importorder.loadpath"; //$NON-NLS-1$
- private static final String DIALOGSETTING_LASTSAVEPATH= JavaScriptUI.ID_PLUGIN + ".importorder.savepath"; //$NON-NLS-1$
-
- private static Key[] getAllKeys() {
- return new Key[] {
- PREF_IMPORTORDER, PREF_ONDEMANDTHRESHOLD, PREF_STATICONDEMANDTHRESHOLD, PREF_IGNORELOWERCASE
- };
- }
-
- public static class ImportOrderEntry {
-
- public final String name;
- public final boolean isStatic;
-
- public ImportOrderEntry(String name, boolean isStatic) {
- this.name= name;
- this.isStatic= isStatic;
- }
-
- public String serialize() {
- return isStatic ? '#' + name : name;
- }
-
- public static ImportOrderEntry fromSerialized(String str) {
- if (str.length() > 0 && str.charAt(0) == '#') {
- return new ImportOrderEntry(str.substring(1), true);
- }
- return new ImportOrderEntry(str, false);
- }
-
- }
-
-
- private static class ImportOrganizeLabelProvider extends LabelProvider {
-
- private final Image PCK_ICON;
- private final Image STATIC_CLASS_ICON;
-
- public ImportOrganizeLabelProvider() {
- PCK_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE);
- STATIC_CLASS_ICON= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaScriptElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
- }
-
- public Image getImage(Object element) {
- return ((ImportOrderEntry) element).isStatic ? STATIC_CLASS_ICON : PCK_ICON;
- }
-
- public String getText(Object element) {
- ImportOrderEntry entry= (ImportOrderEntry) element;
- String name= entry.name;
- if (name.length() > 0) {
- return name;
- }
- if (entry.isStatic) {
- return PreferencesMessages.ImportOrganizeConfigurationBlock_other_static;
- }
- return PreferencesMessages.ImportOrganizeConfigurationBlock_other_normal;
- }
- }
-
- private class ImportOrganizeAdapter implements IListAdapter, IDialogFieldListener {
-
- private boolean canEdit(ListDialogField field) {
- List selected= field.getSelectedElements();
- return selected.size() == 1;
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doButtonPressed(index);
- }
-
- public void selectionChanged(ListDialogField field) {
- fOrderListField.enableButton(IDX_EDIT, canEdit(field));
- }
-
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
-
- public void doubleClicked(ListDialogField field) {
- if (canEdit(field)) {
- doButtonPressed(IDX_EDIT);
- }
- }
- }
-
- private static final int IDX_ADD= 0;
- private static final int IDX_ADD_STATIC= 1;
- private static final int IDX_EDIT= 2;
- private static final int IDX_REMOVE= 3;
- private static final int IDX_UP= 5;
- private static final int IDX_DOWN= 6;
-
- private ListDialogField fOrderListField;
- private StringDialogField fThresholdField;
- private StringDialogField fStaticThresholdField;
- private SelectionButtonDialogField fIgnoreLowerCaseTypesField;
- private SelectionButtonDialogField fExportButton;
- private SelectionButtonDialogField fImportButton;
-
- private PixelConverter fPixelConverter;
-
- public ImportOrganizeConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getAllKeys(), container);
-
- String[] buttonLabels= new String[] {
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_add_button,
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_add_static_button,
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_edit_button,
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_remove_button,
- /* 4 */ null,
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_up_button,
- PreferencesMessages.ImportOrganizeConfigurationBlock_order_down_button,
- };
-
- ImportOrganizeAdapter adapter= new ImportOrganizeAdapter();
-
- fOrderListField= new ListDialogField(adapter, buttonLabels, new ImportOrganizeLabelProvider());
- fOrderListField.setDialogFieldListener(adapter);
- fOrderListField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_label);
- fOrderListField.setUpButtonIndex(IDX_UP);
- fOrderListField.setDownButtonIndex(IDX_DOWN);
- fOrderListField.setRemoveButtonIndex(IDX_REMOVE);
-
- fOrderListField.enableButton(IDX_EDIT, false);
-
- fImportButton= new SelectionButtonDialogField(SWT.PUSH);
- fImportButton.setDialogFieldListener(adapter);
- fImportButton.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_load_button);
-
- fExportButton= new SelectionButtonDialogField(SWT.PUSH);
- fExportButton.setDialogFieldListener(adapter);
- fExportButton.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_order_save_button);
-
- fThresholdField= new StringDialogField();
- fThresholdField.setDialogFieldListener(adapter);
- fThresholdField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_threshold_label);
-
- fStaticThresholdField= new StringDialogField();
- fStaticThresholdField.setDialogFieldListener(adapter);
- fStaticThresholdField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_staticthreshold_label);
-
- fIgnoreLowerCaseTypesField= new SelectionButtonDialogField(SWT.CHECK);
- fIgnoreLowerCaseTypesField.setDialogFieldListener(adapter);
- fIgnoreLowerCaseTypesField.setLabelText(PreferencesMessages.ImportOrganizeConfigurationBlock_ignoreLowerCase_label);
-
- updateControls();
- }
-
- protected Control createContents(Composite parent) {
- setShell(parent.getShell());
-
- fPixelConverter= new PixelConverter(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
-
- composite.setLayout(layout);
-
- fOrderListField.doFillIntoGrid(composite, 3);
- LayoutUtil.setHorizontalSpan(fOrderListField.getLabelControl(null), 2);
- LayoutUtil.setWidthHint(fOrderListField.getLabelControl(null), fPixelConverter.convertWidthInCharsToPixels(60));
- LayoutUtil.setHorizontalGrabbing(fOrderListField.getListControl(null));
-
- Composite importExportComp= new Composite(composite, SWT.NONE);
- importExportComp.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
- layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
-
- importExportComp.setLayout(layout);
-
- fImportButton.doFillIntoGrid(importExportComp, 1);
- fExportButton.doFillIntoGrid(importExportComp, 1);
-
- fThresholdField.doFillIntoGrid(composite, 2);
- ((GridData) fThresholdField.getTextControl(null).getLayoutData()).grabExcessHorizontalSpace= false;
- fStaticThresholdField.doFillIntoGrid(composite, 2);
- fIgnoreLowerCaseTypesField.doFillIntoGrid(composite, 2);
-
- Dialog.applyDialogFont(composite);
-
- return composite;
- }
-
- private boolean doThresholdChanged(String thresholdString) {
- StatusInfo status= new StatusInfo();
- try {
- int threshold= Integer.parseInt(thresholdString);
- if (threshold < 0) {
- status.setError(PreferencesMessages.ImportOrganizeConfigurationBlock_error_invalidthreshold);
- }
- } catch (NumberFormatException e) {
- status.setError(PreferencesMessages.ImportOrganizeConfigurationBlock_error_invalidthreshold);
- }
- updateStatus(status);
- return status.isOK();
- }
-
- private void doButtonPressed(int index) {
- if (index == IDX_ADD || index == IDX_ADD_STATIC) { // add new
- List existing= fOrderListField.getElements();
- ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing, index == IDX_ADD_STATIC);
- if (dialog.open() == Window.OK) {
- List selectedElements= fOrderListField.getSelectedElements();
- if (selectedElements.size() == 1) {
- int insertionIndex= fOrderListField.getIndexOfElement(selectedElements.get(0)) + 1;
- fOrderListField.addElement(dialog.getResult(), insertionIndex);
- } else {
- fOrderListField.addElement(dialog.getResult());
- }
- }
- } else if (index == IDX_EDIT) { // edit
- List selected= fOrderListField.getSelectedElements();
- if (selected.isEmpty()) {
- return;
- }
- ImportOrderEntry editedEntry= (ImportOrderEntry) selected.get(0);
-
- List existing= fOrderListField.getElements();
- existing.remove(editedEntry);
-
- ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing, editedEntry.isStatic);
- dialog.setInitialSelection(editedEntry);
- if (dialog.open() == Window.OK) {
- fOrderListField.replaceElement(editedEntry, dialog.getResult());
- }
- }
- }
-
-
- /*
- * The import order file is a property file. The keys are
- * "0", "1" ... last entry. The values must be valid package names.
- */
- private List loadFromProperties(Properties properties) {
- ArrayList res= new ArrayList();
- int nEntries= properties.size();
- for (int i= 0 ; i < nEntries; i++) {
- String curr= properties.getProperty(String.valueOf(i));
- if (curr != null) {
- ImportOrderEntry entry= ImportOrderEntry.fromSerialized(curr);
- if (!JavaScriptConventions.validatePackageName(entry.name, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_5).matches(IStatus.ERROR)) {
- res.add(entry);
- } else {
- return null;
- }
- } else {
- return res;
- }
- }
- return res;
- }
-
- private List loadImportOrder() {
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- FileDialog dialog= new FileDialog(getShell(), SWT.OPEN);
- dialog.setText(PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_title);
- dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
- String lastPath= dialogSettings.get(DIALOGSETTING_LASTLOADPATH);
- if (lastPath != null) {
- dialog.setFilterPath(lastPath);
- }
- String fileName= dialog.open();
- if (fileName != null) {
- dialogSettings.put(DIALOGSETTING_LASTLOADPATH, dialog.getFilterPath());
-
- Properties properties= new Properties();
- FileInputStream fis= null;
- try {
- fis= new FileInputStream(fileName);
- properties.load(fis);
- List res= loadFromProperties(properties);
- if (res != null) {
- return res;
- }
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- } finally {
- if (fis != null) {
- try { fis.close(); } catch (IOException e) {}
- }
- }
- String title= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_title;
- String message= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_message;
- MessageDialog.openError(getShell(), title, message);
- }
- return null;
- }
-
- private void saveImportOrder(List elements) {
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
- dialog.setText(PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_title);
- dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
- dialog.setFileName("example.importorder"); //$NON-NLS-1$
- String lastPath= dialogSettings.get(DIALOGSETTING_LASTSAVEPATH);
- if (lastPath != null) {
- dialog.setFilterPath(lastPath);
- }
- String fileName= dialog.open();
- if (fileName != null) {
- dialogSettings.put(DIALOGSETTING_LASTSAVEPATH, dialog.getFilterPath());
-
- Properties properties= new Properties();
- for (int i= 0; i < elements.size(); i++) {
- ImportOrderEntry entry= (ImportOrderEntry) elements.get(i);
- properties.setProperty(String.valueOf(i), entry.serialize());
- }
- FileOutputStream fos= null;
- try {
- fos= new FileOutputStream(fileName);
- properties.store(fos, "Organize Import Order"); //$NON-NLS-1$
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- String title= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_title;
- String message= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_message;
- MessageDialog.openError(getShell(), title, message);
- } finally {
- if (fos != null) {
- try { fos.close(); } catch (IOException e) {}
- }
- }
- }
- }
-
- private void updateStatus(IStatus status) {
- fContext.statusChanged(status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String)
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- // no validation
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
- */
- protected void updateControls() {
- ImportOrderEntry[] importOrder= getImportOrderPreference();
- int threshold= getImportNumberThreshold(PREF_ONDEMANDTHRESHOLD);
- int staticThreshold= getImportNumberThreshold(PREF_STATICONDEMANDTHRESHOLD);
- boolean ignoreLowerCase= Boolean.valueOf(getValue(PREF_IGNORELOWERCASE)).booleanValue();
-
- fOrderListField.removeAllElements();
- for (int i= 0; i < importOrder.length; i++) {
- fOrderListField.addElement(importOrder[i]);
- }
- fThresholdField.setText(String.valueOf(threshold));
- fStaticThresholdField.setText(String.valueOf(staticThreshold));
- fIgnoreLowerCaseTypesField.setSelection(ignoreLowerCase);
- }
-
-
- protected final void doDialogFieldChanged(DialogField field) {
- // set values in working copy
- if (field == fOrderListField) {
- setValue(PREF_IMPORTORDER, packOrderList(fOrderListField.getElements()));
- } else if (field == fThresholdField) {
- if (doThresholdChanged(fThresholdField.getText())) {
- setValue(PREF_ONDEMANDTHRESHOLD, fThresholdField.getText());
- }
- } else if (field == fStaticThresholdField) {
- if (doThresholdChanged(fStaticThresholdField.getText())) {
- setValue(PREF_STATICONDEMANDTHRESHOLD, fStaticThresholdField.getText());
- }
- } else if (field == fIgnoreLowerCaseTypesField) {
- setValue(PREF_IGNORELOWERCASE, fIgnoreLowerCaseTypesField.isSelected());
- } else if (field == fImportButton) {
- List order= loadImportOrder();
- if (order != null) {
- fOrderListField.setElements(order);
- }
- } else if (field == fExportButton) {
- saveImportOrder(fOrderListField.getElements());
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
- */
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- return null; // no build required
- }
-
- private static ImportOrderEntry[] unpackOrderList(String str) {
- ArrayList res= new ArrayList();
- int start= 0;
- do {
- int end= str.indexOf(';', start);
- if (end == -1) {
- end= str.length();
- }
- res.add(ImportOrderEntry.fromSerialized(str.substring(start, end)));
- start= end + 1;
- } while (start < str.length());
-
- return (ImportOrderEntry[]) res.toArray(new ImportOrderEntry[res.size()]);
- }
-
- private static String packOrderList(List orderList) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < orderList.size(); i++) {
- ImportOrderEntry entry= (ImportOrderEntry) orderList.get(i);
- buf.append(entry.serialize());
- buf.append(';');
- }
- return buf.toString();
- }
-
- private ImportOrderEntry[] getImportOrderPreference() {
- String str= getValue(PREF_IMPORTORDER);
- if (str != null) {
- return unpackOrderList(str);
- }
- return new ImportOrderEntry[0];
- }
-
- private int getImportNumberThreshold(Key key) {
- String thresholdStr= getValue(key);
- try {
- int threshold= Integer.parseInt(thresholdStr);
- if (threshold < 0) {
- threshold= Integer.MAX_VALUE;
- }
- return threshold;
- } catch (NumberFormatException e) {
- return Integer.MAX_VALUE;
- }
- }
-
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeInputDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeInputDialog.java
deleted file mode 100644
index 346c3cfa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizeInputDialog.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.PackageSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.preferences.ImportOrganizeConfigurationBlock.ImportOrderEntry;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.ui.IJavaScriptElementSearchConstants;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Dialog to enter a new package entry in the organize import preference page.
- */
-public class ImportOrganizeInputDialog extends StatusDialog {
-
- private class ImportOrganizeInputAdapter implements IDialogFieldListener, IStringButtonAdapter {
- /**
- * @see IDialogFieldListener#dialogFieldChanged(DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
-
- /**
- * @see IStringButtonAdapter#changeControlPressed(DialogField)
- */
- public void changeControlPressed(DialogField field) {
- doBrowsePackages();
- }
- }
-
- private StringButtonDialogField fNameDialogField;
- private SelectionButtonDialogField fBrowseTypeButton;
- private List fExistingEntries;
- private final boolean fIsStatic;
-
- public ImportOrganizeInputDialog(Shell parent, List/*<ImportOrderEntry>*/ existingEntries, boolean isStatic) {
- super(parent);
- fIsStatic= isStatic;
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fExistingEntries= existingEntries;
-
- String label, title;
- if (isStatic) {
- title= PreferencesMessages.ImportOrganizeInputDialog_title_static;
- label= PreferencesMessages.ImportOrganizeInputDialog_name_group_static_label;
- } else {
- title= PreferencesMessages.ImportOrganizeInputDialog_title;
- label= PreferencesMessages.ImportOrganizeInputDialog_name_group_label;
- }
- setTitle(title);
-
- ImportOrganizeInputAdapter adapter= new ImportOrganizeInputAdapter();
-
- fNameDialogField= new StringButtonDialogField(adapter);
- fNameDialogField.setLabelText(label);
- fNameDialogField.setButtonLabel(PreferencesMessages.ImportOrganizeInputDialog_browse_packages_button);
- fNameDialogField.setDialogFieldListener(adapter);
- fNameDialogField.setText(""); //$NON-NLS-1$
-
- fBrowseTypeButton= new SelectionButtonDialogField(SWT.PUSH);
- fBrowseTypeButton.setLabelText(PreferencesMessages.ImportOrganizeInputDialog_browse_types_label);
- fBrowseTypeButton.setDialogFieldListener(adapter);
- }
-
- public void setInitialSelection(ImportOrderEntry editedEntry) {
- Assert.isNotNull(editedEntry);
- if (editedEntry.name.length() == 0) {
- fNameDialogField.setText(""); //$NON-NLS-1$
- } else {
- fNameDialogField.setText(editedEntry.name);
- }
- }
-
- public ImportOrderEntry getResult() {
- String val= fNameDialogField.getText();
- if ("*".equals(val)) { //$NON-NLS-1$
- return new ImportOrderEntry("", fIsStatic); //$NON-NLS-1$
- } else {
- return new ImportOrderEntry(val, fIsStatic);
- }
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- initializeDialogUnits(parent);
-
- GridLayout layout= (GridLayout) composite.getLayout();
- layout.numColumns= 2;
-
- fNameDialogField.doFillIntoGrid(composite, 3);
-
- LayoutUtil.setHorizontalSpan(fNameDialogField.getLabelControl(null), 2);
-
- int fieldWidthHint= convertWidthInCharsToPixels(60);
- Text text= fNameDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, fieldWidthHint);
- LayoutUtil.setHorizontalGrabbing(text);
- TextFieldNavigationHandler.install(text);
-
- DialogField.createEmptySpace(composite, 1);
- fBrowseTypeButton.doFillIntoGrid(composite, 1);
-
- fNameDialogField.postSetFocusOnDialogField(parent.getDisplay());
-
- applyDialogFont(composite);
- return composite;
- }
-
- final void doBrowsePackages() {
- IRunnableContext context= new BusyIndicatorRunnableContext();
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- int style= PackageSelectionDialog.F_REMOVE_DUPLICATES | PackageSelectionDialog.F_SHOW_PARENTS | PackageSelectionDialog.F_HIDE_DEFAULT_PACKAGE;
- PackageSelectionDialog dialog= new PackageSelectionDialog(getShell(), context, style, scope);
- dialog.setFilter(fNameDialogField.getText());
- dialog.setIgnoreCase(false);
- dialog.setTitle(PreferencesMessages.ImportOrganizeInputDialog_ChoosePackageDialog_title);
- dialog.setMessage(PreferencesMessages.ImportOrganizeInputDialog_ChoosePackageDialog_description);
- dialog.setEmptyListMessage(PreferencesMessages.ImportOrganizeInputDialog_ChoosePackageDialog_empty);
- if (dialog.open() == Window.OK) {
- IPackageFragment res= (IPackageFragment) dialog.getFirstResult();
- fNameDialogField.setText(res.getElementName());
- }
- }
-
- private void doBrowseTypes() {
- IRunnableContext context= new BusyIndicatorRunnableContext();
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- int style= IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES;
- try {
- SelectionDialog dialog= JavaScriptUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
- dialog.setTitle(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title);
- dialog.setMessage(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_description);
- if (dialog.open() == Window.OK) {
- IType res= (IType) dialog.getResult()[0];
- fNameDialogField.setText(res.getFullyQualifiedName('.'));
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title, PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_error_message);
- }
- }
-
- /**
- * @param field
- */
- final void doDialogFieldChanged(DialogField field) {
- if (field == fBrowseTypeButton) {
- doBrowseTypes();
- } else {
- doValidation();
- }
- }
-
-
- private void doValidation() {
- StatusInfo status= new StatusInfo();
- String newText= fNameDialogField.getText();
- if (newText.length() == 0) {
- status.setError(""); //$NON-NLS-1$
- } else {
- if (newText.equals("*")) { //$NON-NLS-1$
- if (doesExist("", fIsStatic)) { //$NON-NLS-1$
- status.setError(PreferencesMessages.ImportOrganizeInputDialog_error_entryExists);
- }
- } else {
- IStatus val= JavaScriptConventions.validateJavaScriptTypeName(newText, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3);
- if (val.matches(IStatus.ERROR)) {
- status.setError(PreferencesMessages.ImportOrganizeInputDialog_error_invalidName);
- } else {
- if (doesExist(newText, fIsStatic)) {
- status.setError(PreferencesMessages.ImportOrganizeInputDialog_error_entryExists);
- }
- }
- }
- }
- updateStatus(status);
- }
-
- private boolean doesExist(String name, boolean isStatic) {
- for (int i= 0; i < fExistingEntries.size(); i++) {
- ImportOrderEntry entry= (ImportOrderEntry) fExistingEntries.get(i);
- if (name.equals(entry.name) && isStatic == entry.isStatic) {
- return true;
- }
- }
- return false;
- }
-
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizePreferencePage.java
deleted file mode 100644
index f4922a3f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ImportOrganizePreferencePage.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/*
- * The page to configure the naming style options.
- */
-public class ImportOrganizePreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.ImportOrganizePreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.ImportOrganizePreferencePage"; //$NON-NLS-1$
-
-
- private ImportOrganizeConfigurationBlock fConfigurationBlock;
-
- public ImportOrganizePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.ImportOrganizePreferencePage_description);
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.ImportOrganizePreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new ImportOrganizeConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.ORGANIZE_IMPORTS_PREFERENCE_PAGE);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-
-}
-
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBasePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBasePreferencePage.java
deleted file mode 100644
index dc440c39..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBasePreferencePage.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSavePreferences;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/*
- * The page for setting general java plugin preferences.
- * See PreferenceConstants to access or change these values through public API.
- */
-public class JavaBasePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- public static final String JAVA_BASE_PREF_PAGE_ID= "org.eclipse.wst.jsdt.ui.preferences.JavaBasePreferencePage"; //$NON-NLS-1$
-
- private static final String DOUBLE_CLICK= PreferenceConstants.DOUBLE_CLICK;
- private static final String DOUBLE_CLICK_GOES_INTO= PreferenceConstants.DOUBLE_CLICK_GOES_INTO;
- private static final String DOUBLE_CLICK_EXPANDS= PreferenceConstants.DOUBLE_CLICK_EXPANDS;
-
- private ArrayList fCheckBoxes;
- private ArrayList fRadioButtons;
-
- public JavaBasePreferencePage() {
- super();
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setDescription(PreferencesMessages.JavaBasePreferencePage_description);
-
- fRadioButtons= new ArrayList();
- fCheckBoxes= new ArrayList();
- }
-
- /*
- * @see IWorkbenchPreferencePage#init(IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_BASE_PREFERENCE_PAGE);
- }
-
- private Button addRadioButton(Composite parent, String label, String key, String value) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
-
- Button button= new Button(parent, SWT.RADIO);
- button.setText(label);
- button.setData(new String[] { key, value });
- button.setLayoutData(gd);
-
- button.setSelection(value.equals(getPreferenceStore().getString(key)));
-
- fRadioButtons.add(button);
- return button;
- }
-
- private Button addCheckBox(Composite parent, String label, String key) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
-
- Button button= new Button(parent, SWT.CHECK);
- button.setText(label);
- button.setData(key);
- button.setLayoutData(gd);
-
- button.setSelection(getPreferenceStore().getBoolean(key));
-
- fCheckBoxes.add(button);
- return button;
- }
-
- protected Control createContents(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite result= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= 0;
- layout.verticalSpacing= convertVerticalDLUsToPixels(10);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- result.setLayout(layout);
-
- Group doubleClickGroup= new Group(result, SWT.NONE);
- doubleClickGroup.setLayout(new GridLayout());
- doubleClickGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- doubleClickGroup.setText(PreferencesMessages.JavaBasePreferencePage_doubleclick_action);
- addRadioButton(doubleClickGroup, PreferencesMessages.JavaBasePreferencePage_doubleclick_gointo, DOUBLE_CLICK, DOUBLE_CLICK_GOES_INTO);
- addRadioButton(doubleClickGroup, PreferencesMessages.JavaBasePreferencePage_doubleclick_expand, DOUBLE_CLICK, DOUBLE_CLICK_EXPANDS);
-
- if ( IUIConstants.SUPPORT_REFACTORING ) {
- Group refactoringGroup= new Group(result, SWT.NONE);
- refactoringGroup.setLayout(new GridLayout());
- refactoringGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- refactoringGroup.setText(PreferencesMessages.JavaBasePreferencePage_refactoring_title);
- addCheckBox(refactoringGroup,
- PreferencesMessages.JavaBasePreferencePage_refactoring_auto_save,
- RefactoringSavePreferences.PREF_SAVE_ALL_EDITORS);
- addCheckBox(refactoringGroup,
- PreferencesMessages.JavaBasePreferencePage_refactoring_lightweight,
- PreferenceConstants.REFACTOR_LIGHTWEIGHT);
- }
-
- Group group= new Group(result, SWT.NONE);
- group.setLayout(new GridLayout());
- group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- group.setText(PreferencesMessages.JavaBasePreferencePage_search);
-
- addCheckBox(group, PreferencesMessages.JavaBasePreferencePage_search_small_menu, PreferenceConstants.SEARCH_USE_REDUCED_MENU);
-
-
- layout= new GridLayout();
- layout.numColumns= 2;
-
- Group dontAskGroup= new Group(result, SWT.NONE);
- dontAskGroup.setLayout(layout);
- dontAskGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- dontAskGroup.setText(PreferencesMessages.JavaBasePreferencePage_dialogs);
-
- Label label= new Label(dontAskGroup, SWT.WRAP);
- label.setText(PreferencesMessages.JavaBasePreferencePage_do_not_hide_description);
- GridData data= new GridData(GridData.FILL, GridData.CENTER, true, false);
- data.widthHint= convertVerticalDLUsToPixels(50);
- label.setLayoutData(data);
-
- Button clearButton= new Button(dontAskGroup, SWT.PUSH);
- clearButton.setText(PreferencesMessages.JavaBasePreferencePage_do_not_hide_button);
- clearButton.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
- clearButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- unhideAllDialogs();
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- unhideAllDialogs();
- }
- });
-
-
- SWTUtil.setButtonDimensionHint(clearButton);
- Dialog.applyDialogFont(result);
- return result;
- }
-
- protected final void unhideAllDialogs() {
- OptionalMessageDialog.clearAllRememberedStates();
- MessageDialog.openInformation(getShell(), PreferencesMessages.JavaBasePreferencePage_do_not_hide_dialog_title, PreferencesMessages.JavaBasePreferencePage_do_not_hide_dialog_message);
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- button.setSelection(store.getDefaultBoolean(key));
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- String[] info= (String[]) button.getData();
- button.setSelection(info[1].equals(store.getDefaultString(info[0])));
- }
- super.performDefaults();
- }
-
- /*
- * @see IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- store.setValue(key, button.getSelection());
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- if (button.getSelection()) {
- String[] info= (String[]) button.getData();
- store.setValue(info[0], info[1]);
- }
- }
-
- JavaScriptPlugin.getDefault().savePluginPreferences();
- return super.performOk();
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java
deleted file mode 100644
index 78e29f06..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-
-/**
- */
-public class JavaBuildConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final String SETTINGS_SECTION_NAME= "JavaBuildConfigurationBlock"; //$NON-NLS-1$
-
- private static final Key PREF_PB_MAX_PER_UNIT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MAX_PER_UNIT);
-
- private static final Key PREF_RESOURCE_FILTER= getJDTCoreKey(JavaScriptCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER);
- private static final Key PREF_BUILD_INVALID_CLASSPATH= getJDTCoreKey(JavaScriptCore.CORE_JAVA_BUILD_INVALID_CLASSPATH);
- private static final Key PREF_BUILD_CLEAN_OUTPUT_FOLDER= getJDTCoreKey(JavaScriptCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER);
- private static final Key PREF_ENABLE_EXCLUSION_PATTERNS= getJDTCoreKey(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS);
- private static final Key PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= getJDTCoreKey(JavaScriptCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS);
-
- private static final Key PREF_PB_INCOMPLETE_BUILDPATH= getJDTCoreKey(JavaScriptCore.CORE_INCOMPLETE_CLASSPATH);
- private static final Key PREF_PB_CIRCULAR_BUILDPATH= getJDTCoreKey(JavaScriptCore.CORE_CIRCULAR_CLASSPATH);
- private static final Key PREF_PB_INCOMPATIBLE_JDK_LEVEL= getJDTCoreKey(JavaScriptCore.CORE_INCOMPATIBLE_JDK_LEVEL);
- private static final Key PREF_PB_DUPLICATE_RESOURCE= getJDTCoreKey(JavaScriptCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE);
- private static final Key PREF_RECREATE_MODIFIED_CLASS_FILES= getJDTCoreKey(JavaScriptCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER);
-
-
- // values
- private static final String ERROR= JavaScriptCore.ERROR;
- private static final String WARNING= JavaScriptCore.WARNING;
- private static final String IGNORE= JavaScriptCore.IGNORE;
-
- private static final String ABORT= JavaScriptCore.ABORT;
- private static final String CLEAN= JavaScriptCore.CLEAN;
-
- private static final String ENABLED= JavaScriptCore.ENABLED;
- private static final String DISABLED= JavaScriptCore.DISABLED;
-
- private PixelConverter fPixelConverter;
-
- private IStatus fMaxNumberProblemsStatus, fResourceFilterStatus;
-
- public JavaBuildConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getKeys(), container);
- fMaxNumberProblemsStatus= new StatusInfo();
- fResourceFilterStatus= new StatusInfo();
- }
-
- private static Key[] getKeys() {
- Key[] keys= new Key[] {
- PREF_PB_MAX_PER_UNIT, PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_INCOMPLETE_BUILDPATH, PREF_PB_CIRCULAR_BUILDPATH,
- PREF_BUILD_CLEAN_OUTPUT_FOLDER, PREF_PB_DUPLICATE_RESOURCE,
- PREF_PB_INCOMPATIBLE_JDK_LEVEL, PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, PREF_RECREATE_MODIFIED_CLASS_FILES,
- };
- return keys;
- }
-
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- fPixelConverter= new PixelConverter(parent);
- setShell(parent.getShell());
-
- Composite mainComp= new Composite(parent, SWT.NONE);
- mainComp.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- mainComp.setLayout(layout);
-
- Composite othersComposite= createBuildPathTabContent(mainComp);
- GridData gridData= new GridData(GridData.FILL, GridData.FILL, true, true);
- gridData.heightHint= fPixelConverter.convertHeightInCharsToPixels(20);
- othersComposite.setLayoutData(gridData);
-
- validateSettings(null, null, null);
-
- return mainComp;
- }
-
-
- private Composite createBuildPathTabContent(Composite parent) {
- String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
- String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE };
- String[] enableDisableValues= new String[] { ENABLED, DISABLED };
- String[] enableIgnoreValues= new String[] { ENABLED, IGNORE };
-
- String[] errorWarning= new String[] { ERROR, WARNING };
-
- String[] errorWarningLabels= new String[] {
- PreferencesMessages.JavaBuildConfigurationBlock_error,
- PreferencesMessages.JavaBuildConfigurationBlock_warning
- };
-
- String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
- String[] errorWarningIgnoreLabels= new String[] {
- PreferencesMessages.JavaBuildConfigurationBlock_error,
- PreferencesMessages.JavaBuildConfigurationBlock_warning,
- PreferencesMessages.JavaBuildConfigurationBlock_ignore
- };
-
- int nColumns= 3;
-
- final ScrolledPageContent pageContent = new ScrolledPageContent(parent);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= nColumns;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
-
- Composite composite= pageContent.getBody();
- composite.setLayout(layout);
-
- String label= PreferencesMessages.JavaBuildConfigurationBlock_section_general;
- ExpandableComposite excomposite= createStyleSection(composite, label, nColumns);
-
- Composite othersComposite= new Composite(excomposite, SWT.NONE);
- excomposite.setClient(othersComposite);
- othersComposite.setLayout(new GridLayout(nColumns, false));
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_pb_max_per_unit_label;
- Text text= addTextField(othersComposite, label, PREF_PB_MAX_PER_UNIT, 0, 0);
- GridData gd= (GridData) text.getLayoutData();
- gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(8);
- gd.horizontalAlignment= GridData.END;
- text.setTextLimit(6);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_enable_exclusion_patterns_label;
- addCheckBox(othersComposite, label, PREF_ENABLE_EXCLUSION_PATTERNS, enableDisableValues, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_enable_multiple_outputlocations_label;
- addCheckBox(othersComposite, label, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, enableDisableValues, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_section_include_path_problems;
- excomposite= createStyleSection(composite, label, nColumns);
-
- othersComposite= new Composite(excomposite, SWT.NONE);
- excomposite.setClient(othersComposite);
- othersComposite.setLayout(new GridLayout(nColumns, false));
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_build_invalid_classpath_label;
- addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_pb_incomplete_build_path_label;
- addComboBox(othersComposite, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_pb_build_path_cycles_label;
- addComboBox(othersComposite, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_pb_check_prereq_binary_level_label;
- addComboBox(othersComposite, label, PREF_PB_INCOMPATIBLE_JDK_LEVEL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_section_output_folder;
- excomposite= createStyleSection(composite, label, nColumns);
-
- othersComposite= new Composite(excomposite, SWT.NONE);
- excomposite.setClient(othersComposite);
- othersComposite.setLayout(new GridLayout(nColumns, false));
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_pb_duplicate_resources_label;
- addComboBox(othersComposite, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_build_clean_outputfolder_label;
- addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_build_recreate_modified;
- addCheckBox(othersComposite, label, PREF_RECREATE_MODIFIED_CLASS_FILES, enableIgnoreValues, 0);
-
- label= PreferencesMessages.JavaBuildConfigurationBlock_resource_filter_label;
- text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER, 0, 0);
- gd= (GridData) text.getLayoutData();
- gd.grabExcessHorizontalSpace= true;
- gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
-
- Label description= new Label(othersComposite, SWT.WRAP);
- description.setText(PreferencesMessages.JavaBuildConfigurationBlock_resource_filter_description);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= nColumns;
- gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
- description.setLayoutData(gd);
-
- IDialogSettings section= JavaScriptPlugin.getDefault().getDialogSettings().getSection(SETTINGS_SECTION_NAME);
- restoreSectionExpansionStates(section);
-
- return pageContent;
- }
-
- /* (non-javadoc)
- * Update fields and validate.
- * @param changedKey Key that changed, or null, if all changed.
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (!areSettingsEnabled()) {
- return;
- }
-
- if (changedKey != null) {
- if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) {
- fMaxNumberProblemsStatus= validateMaxNumberProblems();
- } else if (PREF_RESOURCE_FILTER.equals(changedKey)) {
- fResourceFilterStatus= validateResourceFilters();
- } else {
- return;
- }
- } else {
- updateEnableStates();
- fMaxNumberProblemsStatus= validateMaxNumberProblems();
- fResourceFilterStatus= validateResourceFilters();
- }
- IStatus status= StatusUtil.getMostSevere(new IStatus[] { fMaxNumberProblemsStatus, fResourceFilterStatus });
- fContext.statusChanged(status);
- }
-
- private void updateEnableStates() {
- }
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- String title= PreferencesMessages.JavaBuildConfigurationBlock_needsbuild_title;
- String message;
- if (workspaceSettings) {
- message= PreferencesMessages.JavaBuildConfigurationBlock_needsfullbuild_message;
- } else {
- message= PreferencesMessages.JavaBuildConfigurationBlock_needsprojectbuild_message;
- }
- return new String[] { title, message };
- }
-
- private IStatus validateMaxNumberProblems() {
- String number= getValue(PREF_PB_MAX_PER_UNIT);
- StatusInfo status= new StatusInfo();
- if (number.length() == 0) {
- status.setError(PreferencesMessages.JavaBuildConfigurationBlock_empty_input);
- } else {
- try {
- int value= Integer.parseInt(number);
- if (value <= 0) {
- status.setError(Messages.format(PreferencesMessages.JavaBuildConfigurationBlock_invalid_input, number));
- }
- } catch (NumberFormatException e) {
- status.setError(Messages.format(PreferencesMessages.JavaBuildConfigurationBlock_invalid_input, number));
- }
- }
- return status;
- }
-
- private IStatus validateResourceFilters() {
- String text= getValue(PREF_RESOURCE_FILTER);
-
- IWorkspace workspace= ResourcesPlugin.getWorkspace();
-
- String[] filters= getTokens(text, ","); //$NON-NLS-1$
- for (int i= 0; i < filters.length; i++) {
- String fileName= filters[i].replace('*', 'x');
- int resourceType= IResource.FILE;
- int lastCharacter= fileName.length() - 1;
- if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') {
- fileName= fileName.substring(0, lastCharacter);
- resourceType= IResource.FOLDER;
- }
- IStatus status= workspace.validateName(fileName, resourceType);
- if (status.matches(IStatus.ERROR)) {
- String message= Messages.format(PreferencesMessages.JavaBuildConfigurationBlock_filter_invalidsegment_error, status.getMessage());
- return new StatusInfo(IStatus.ERROR, message);
- }
- }
- return new StatusInfo();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#dispose()
- */
- public void dispose() {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(SETTINGS_SECTION_NAME);
- storeSectionExpansionStates(settings);
- super.dispose();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildPreferencePage.java
deleted file mode 100644
index 61f4802d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildPreferencePage.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Page used to configure both workspace and project specific compiler settings
- */
-public class JavaBuildPreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.JavaBuildPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.JavaBuildPreferencePage"; //$NON-NLS-1$
-
- private JavaBuildConfigurationBlock fConfigurationBlock;
-
- public JavaBuildPreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.JavaBuildPreferencePage_description);
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.JavaBuildPreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new JavaBuildConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- if (isProjectPreferencePage()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_BUILD_PROPERTY_PAGE);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_BUILD_PREFERENCE_PAGE);
- }
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaCategoryPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaCategoryPropertyPage.java
deleted file mode 100644
index 0e9ec501..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaCategoryPropertyPage.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-/**
- * Top level node for Java property pages
- */
-public class JavaCategoryPropertyPage extends PropertyPage {
-
- private IProject fProject;
-
- private final static String HREF_BUILDPATH= BuildPathsPropertyPage.PROP_ID;
- private final static String HREF_COMPILER= CompliancePreferencePage.PROP_ID;
- private final static String HREF_CODESTYLE= CodeStylePreferencePage.PROP_ID;
- private final static String HREF_JLOC= JavadocConfigurationPropertyPage.PROP_ID;
- private final static String HREF_TODO= TodoTaskPreferencePage.PROP_ID;
- private final static String HREF_PSEVERITIES= ProblemSeveritiesPreferencePage.PROP_ID;
- private final static String HREF_JAVADOC= JavadocProblemsPreferencePage.PROP_ID;
- private final static String HREF_FORMATTER= CodeFormatterPreferencePage.PROP_ID;
- private final static String HREF_TEMPLATES= ""; // Code //$NON-NLS-1$
- private final static String HREF_IMPORTORDER= ImportOrganizePreferencePage.PROP_ID;
- private final static String HREF_BUILDING= JavaBuildPreferencePage.PROP_ID;
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- protected Control createContents(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new TableWrapLayout());
-
- FormToolkit toolkit= new FormToolkit(parent.getDisplay());
- try {
- String[] args= {
- fProject.getName(), HREF_BUILDPATH, HREF_COMPILER, HREF_TODO, HREF_PSEVERITIES, HREF_JAVADOC, HREF_BUILDING,
- HREF_CODESTYLE, HREF_FORMATTER, HREF_TEMPLATES, HREF_IMPORTORDER, HREF_JLOC
- };
- String msg= Messages.format(PreferencesMessages.JavaCategoryPropertyPage_text, args);
-
- FormText formText = toolkit.createFormText(composite, true);
- try {
- formText.setText(msg, true, false);
- } catch (SWTException e) {
- formText.setText(e.getMessage(), false, false);
- }
-
- formText.setBackground(null);
- formText.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
- formText.addHyperlinkListener(new HyperlinkAdapter() {
- public void linkActivated(HyperlinkEvent e) {
- doLinkActivated(e.data.toString());
- }
- });
- } finally {
- toolkit.dispose();
- }
-
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- protected void doLinkActivated(String string) {
- if (string.length() > 0) {
- IPreferencePageContainer container= getContainer();
- if (container instanceof PreferenceDialog) {
- //see bug 80689: ((PreferenceDialog) container).setCurrentPageId(string);
- }
- }
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement()
- */
- public IAdaptable getElement() {
- return fProject;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- fProject= (IProject) element.getAdapter(IResource.class);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java
deleted file mode 100644
index 2438a0c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.ColorSelector;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.FontMetrics;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.List;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Configures Java Editor hover preferences.
- *
- *
- */
-class JavaEditorAppearanceConfigurationBlock extends AbstractConfigurationBlock {
-
- private final String[][] fAppearanceColorListModel= new String[][] {
- {PreferencesMessages.JavaEditorPreferencePage_matchingBracketsHighlightColor2, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, null},
- {PreferencesMessages.JavaEditorPreferencePage_backgroundForCompletionProposals, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_foregroundForCompletionProposals, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_backgroundForMethodParameters, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_foregroundForMethodParameters, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_backgroundForCompletionReplacement, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_foregroundForCompletionReplacement, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, null },
- {PreferencesMessages.JavaEditorPreferencePage_sourceHoverBackgroundColor, PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR, PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT},
-
- };
-
- private List fAppearanceColorList;
- private ColorSelector fAppearanceColorEditor;
- private Button fAppearanceColorDefault;
-
- private FontMetrics fFontMetrics;
-
- public JavaEditorAppearanceConfigurationBlock(PreferencePage mainPreferencePage, OverlayPreferenceStore store) {
- super(store, mainPreferencePage);
- getPreferenceStore().addKeys(createOverlayStoreKeys());
- }
-
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- ArrayList overlayKeys= new ArrayList();
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SHOW_SEGMENTS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT));
-
- OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
- overlayKeys.toArray(keys);
- return keys;
- }
-
- /**
- * Creates page for appearance preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
-
- Composite composite= new Composite(scrolled, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- createHeader(composite);
- createAppearancePage(composite);
-
- scrolled.setContent(composite);
- final Point size= composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
- return scrolled;
-
- }
-
- private void createHeader(Composite contents) {
- final Shell shell= contents.getShell();
- String text= PreferencesMessages.JavaEditorPreferencePage_link;
- Link link= new Link(contents, SWT.NONE);
- link.setText(text);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(shell, "org.eclipse.ui.preferencePages.GeneralTextEditor", null, null); //$NON-NLS-1$
- }
- });
- // TODO replace by link-specific tooltips when
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88866 gets fixed
- link.setToolTipText(PreferencesMessages.JavaEditorPreferencePage_link_tooltip);
-
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= 150; // only expand further if anyone else requires it
- link.setLayoutData(gridData);
-
- addFiller(contents);
- }
-
- private void addFiller(Composite composite) {
- PixelConverter pixelConverter= new PixelConverter(composite);
-
- Label filler= new Label(composite, SWT.LEFT );
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 2;
- filler.setLayoutData(gd);
- }
-
- /**
- * Returns the number of pixels corresponding to the width of the given
- * number of characters.
- * <p>
- * This method may only be called after <code>initializeDialogUnits</code>
- * has been called.
- * </p>
- * <p>
- * Clients may call this framework method, but should not override it.
- * </p>
- *
- * @param chars
- * the number of characters
- * @return the number of pixels
- */
- protected int convertWidthInCharsToPixels(int chars) {
- // test for failure to initialize for backward compatibility
- if (fFontMetrics == null)
- return 0;
- return Dialog.convertWidthInCharsToPixels(fFontMetrics, chars);
- }
-
- /**
- * Returns the number of pixels corresponding to the height of the given
- * number of characters.
- * <p>
- * This method may only be called after <code>initializeDialogUnits</code>
- * has been called.
- * </p>
- * <p>
- * Clients may call this framework method, but should not override it.
- * </p>
- *
- * @param chars
- * the number of characters
- * @return the number of pixels
- */
- protected int convertHeightInCharsToPixels(int chars) {
- // test for failure to initialize for backward compatibility
- if (fFontMetrics == null)
- return 0;
- return Dialog.convertHeightInCharsToPixels(fFontMetrics, chars);
- }
-
- private Control createAppearancePage(Composite parent) {
-
- Composite appearanceComposite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- appearanceComposite.setLayout(layout);
-
- String label;
-
- label= PreferencesMessages.JavaEditorPreferencePage_subWordNavigation;
- addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_analyseAnnotationsWhileTyping;
- addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
-
- String text= PreferencesMessages.SmartTypingConfigurationBlock_annotationReporting_link;
- addLink(appearanceComposite, text, INDENT);
-
- Label spacer= new Label(appearanceComposite, SWT.LEFT );
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.heightHint= convertHeightInCharsToPixels(1) / 2;
- spacer.setLayoutData(gd);
-
- label= PreferencesMessages.JavaEditorPreferencePage_highlightMatchingBrackets;
- addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_quickassist_lightbulb;
- addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_showJavaElementOnly;
- addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_SHOW_SEGMENTS, 0);
-
- Label l= new Label(appearanceComposite, SWT.LEFT );
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.heightHint= convertHeightInCharsToPixels(1) / 2;
- l.setLayoutData(gd);
-
- l= new Label(appearanceComposite, SWT.LEFT);
- l.setText(PreferencesMessages.JavaEditorPreferencePage_appearanceOptions);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- l.setLayoutData(gd);
-
- Composite editorComposite= new Composite(appearanceComposite, SWT.NONE);
- layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- editorComposite.setLayout(layout);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
- gd.horizontalSpan= 2;
- editorComposite.setLayoutData(gd);
-
- fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
- gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
- gd.heightHint= convertHeightInCharsToPixels(12);
- fAppearanceColorList.setLayoutData(gd);
-
- Composite stylesComposite= new Composite(editorComposite, SWT.NONE);
- layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- stylesComposite.setLayout(layout);
- stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- l= new Label(stylesComposite, SWT.LEFT);
- l.setText(PreferencesMessages.JavaEditorPreferencePage_color);
- gd= new GridData();
- gd.horizontalAlignment= GridData.BEGINNING;
- l.setLayoutData(gd);
-
- fAppearanceColorEditor= new ColorSelector(stylesComposite);
- Button foregroundColorButton= fAppearanceColorEditor.getButton();
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment= GridData.BEGINNING;
- foregroundColorButton.setLayoutData(gd);
-
- SelectionListener colorDefaultSelectionListener= new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- boolean systemDefault= fAppearanceColorDefault.getSelection();
- fAppearanceColorEditor.getButton().setEnabled(!systemDefault);
-
- int i= fAppearanceColorList.getSelectionIndex();
- if (i == -1)
- return;
-
- String key= fAppearanceColorListModel[i][2];
- if (key != null)
- getPreferenceStore().setValue(key, systemDefault);
- }
- public void widgetDefaultSelected(SelectionEvent e) {}
- };
-
- fAppearanceColorDefault= new Button(stylesComposite, SWT.CHECK);
- fAppearanceColorDefault.setText(PreferencesMessages.JavaEditorPreferencePage_systemDefault);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment= GridData.BEGINNING;
- gd.horizontalSpan= 2;
- fAppearanceColorDefault.setLayoutData(gd);
- fAppearanceColorDefault.setVisible(false);
- fAppearanceColorDefault.addSelectionListener(colorDefaultSelectionListener);
-
- fAppearanceColorList.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- handleAppearanceColorListSelection();
- }
- });
- foregroundColorButton.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i= fAppearanceColorList.getSelectionIndex();
- if (i == -1)
- return;
-
- String key= fAppearanceColorListModel[i][1];
- PreferenceConverter.setValue(getPreferenceStore(), key, fAppearanceColorEditor.getColorValue());
- }
- });
- return appearanceComposite;
- }
-
-
- private void addLink(Composite composite, String text, int indent) {
- GridData gd;
- final Link link= new Link(composite, SWT.NONE);
- link.setText(text);
- gd= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gd.widthHint= 300; // don't get wider initially
- gd.horizontalSpan= 2;
- gd.horizontalIndent= indent;
- link.setLayoutData(gd);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(link.getShell(), e.text, null, null);
- }
- });
- }
-
- private void handleAppearanceColorListSelection() {
- int i= fAppearanceColorList.getSelectionIndex();
- if (i == -1)
- return;
- String key= fAppearanceColorListModel[i][1];
- RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key);
- fAppearanceColorEditor.setColorValue(rgb);
- updateAppearanceColorWidgets(fAppearanceColorListModel[i][2]);
- }
-
- private void updateAppearanceColorWidgets(String systemDefaultKey) {
- if (systemDefaultKey == null) {
- fAppearanceColorDefault.setSelection(false);
- fAppearanceColorDefault.setVisible(false);
- fAppearanceColorEditor.getButton().setEnabled(true);
- } else {
- boolean systemDefault= getPreferenceStore().getBoolean(systemDefaultKey);
- fAppearanceColorDefault.setSelection(systemDefault);
- fAppearanceColorDefault.setVisible(true);
- fAppearanceColorEditor.getButton().setEnabled(!systemDefault);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#initialize()
- */
- public void initialize() {
- super.initialize();
- initializeDefaultColors();
-
- for (int i= 0; i < fAppearanceColorListModel.length; i++)
- fAppearanceColorList.add(fAppearanceColorListModel[i][0]);
-
- fAppearanceColorList.getDisplay().asyncExec(new Runnable() {
- public void run() {
- if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) {
- fAppearanceColorList.select(0);
- handleAppearanceColorListSelection();
- }
- }
- });
-
- }
-
- /**
- * Initializes the default colors.
- *
- *
- */
- private void initializeDefaultColors() {
- if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT)) {
- RGB rgb= fAppearanceColorList.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND).getRGB();
- PreferenceConverter.setValue(getPreferenceStore(), PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR, rgb);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#performDefaults()
- */
- public void performDefaults() {
- super.performDefaults();
- initializeDefaultColors();
- handleAppearanceColorListSelection();
- }
-
- /**
- * Initializes the computation of horizontal and vertical dialog units based
- * on the size of current font.
- * <p>
- * This method must be called before any of the dialog unit based conversion
- * methods are called.
- * </p>
- *
- * @param testControl
- * a control from which to obtain the current font
- */
- protected void initializeDialogUnits(Control testControl) {
- // Compute and store a font metric
- GC gc = new GC(testControl);
- gc.setFont(JFaceResources.getDialogFont());
- fFontMetrics = gc.getFontMetrics();
- gc.dispose();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java
deleted file mode 100644
index 830a6bba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java
+++ /dev/null
@@ -1,960 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.ColorSelector;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontMetrics;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Scrollable;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlighting;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedRange;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaColorManager;
-import org.eclipse.wst.jsdt.internal.ui.text.PreferencesAdapter;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Configures Java Editor hover preferences.
- *
- *
- */
-class JavaEditorColoringConfigurationBlock extends AbstractConfigurationBlock {
-
- /**
- * Item in the highlighting color list.
- *
- *
- */
- private static class HighlightingColorListItem {
- /** Display name */
- private String fDisplayName;
- /** Color preference key */
- private String fColorKey;
- /** Bold preference key */
- private String fBoldKey;
- /** Italic preference key */
- private String fItalicKey;
- /**
- * Strikethrough preference key.
- *
- */
- private String fStrikethroughKey;
- /** Underline preference key.
- *
- */
- private String fUnderlineKey;
-
- /**
- * Initialize the item with the given values.
- * @param displayName the display name
- * @param colorKey the color preference key
- * @param boldKey the bold preference key
- * @param italicKey the italic preference key
- * @param strikethroughKey the strikethrough preference key
- * @param underlineKey the underline preference key
- */
- public HighlightingColorListItem(String displayName, String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) {
- fDisplayName= displayName;
- fColorKey= colorKey;
- fBoldKey= boldKey;
- fItalicKey= italicKey;
- fStrikethroughKey= strikethroughKey;
- fUnderlineKey= underlineKey;
- }
-
- /**
- * @return the bold preference key
- */
- public String getBoldKey() {
- return fBoldKey;
- }
-
- /**
- * @return the bold preference key
- */
- public String getItalicKey() {
- return fItalicKey;
- }
-
- /**
- * @return the strikethrough preference key
- *
- */
- public String getStrikethroughKey() {
- return fStrikethroughKey;
- }
-
- /**
- * @return the underline preference key
- *
- */
- public String getUnderlineKey() {
- return fUnderlineKey;
- }
-
- /**
- * @return the color preference key
- */
- public String getColorKey() {
- return fColorKey;
- }
-
- /**
- * @return the display name
- */
- public String getDisplayName() {
- return fDisplayName;
- }
- }
-
- private static class SemanticHighlightingColorListItem extends HighlightingColorListItem {
-
- /** Enablement preference key */
- private final String fEnableKey;
-
- /**
- * Initialize the item with the given values.
- * @param displayName the display name
- * @param colorKey the color preference key
- * @param boldKey the bold preference key
- * @param italicKey the italic preference key
- * @param strikethroughKey the strikethroughKey preference key
- * @param underlineKey the underlineKey preference key
- * @param enableKey the enable preference key
- */
- public SemanticHighlightingColorListItem(String displayName, String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey, String enableKey) {
- super(displayName, colorKey, boldKey, italicKey, strikethroughKey, underlineKey);
- fEnableKey= enableKey;
- }
-
- /**
- * @return the enablement preference key
- */
- public String getEnableKey() {
- return fEnableKey;
- }
- }
-
- /**
- * Color list label provider.
- *
- *
- */
- private class ColorListLabelProvider extends LabelProvider {
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (element instanceof String)
- return (String) element;
- return ((HighlightingColorListItem)element).getDisplayName();
- }
- }
-
- /**
- * Color list content provider.
- *
- *
- */
- private class ColorListContentProvider implements ITreeContentProvider {
-
- /*
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- return new String[] {fJavaCategory, fJavadocCategory, fCommentsCategory};
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof String) {
- String entry= (String) parentElement;
- if (fJavaCategory.equals(entry))
- return fListModel.subList(7, fListModel.size()).toArray();
- if (fJavadocCategory.equals(entry))
- return fListModel.subList(0, 4).toArray();
- if (fCommentsCategory.equals(entry))
- return fListModel.subList(4, 7).toArray();
- }
- return new Object[0];
- }
-
- public Object getParent(Object element) {
- if (element instanceof String)
- return null;
- int index= fListModel.indexOf(element);
- if (index < 4)
- return fJavadocCategory;
- if (index >= 7)
- return fJavaCategory;
- return fCommentsCategory;
- }
-
- public boolean hasChildren(Object element) {
- return element instanceof String;
- }
- }
-
- private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX;
- /**
- * Preference key suffix for italic preferences.
- *
- */
- private static final String ITALIC= PreferenceConstants.EDITOR_ITALIC_SUFFIX;
- /**
- * Preference key suffix for strikethrough preferences.
- *
- */
- private static final String STRIKETHROUGH= PreferenceConstants.EDITOR_STRIKETHROUGH_SUFFIX;
- /**
- * Preference key suffix for underline preferences.
- *
- */
- private static final String UNDERLINE= PreferenceConstants.EDITOR_UNDERLINE_SUFFIX;
-
- private static final String COMPILER_TASK_TAGS= JavaScriptCore.COMPILER_TASK_TAGS;
- /**
- * The keys of the overlay store.
- */
- private final String[][] fSyntaxColorListModel= new String[][] {
- { PreferencesMessages.JavaEditorPreferencePage_javaDocKeywords, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_javaDocHtmlTags, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_javaDocLinks, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_javaDocOthers, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_multiLineComment, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_singleLineComment, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_javaCommentTaskTags, PreferenceConstants.EDITOR_TASK_TAG_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_keywords, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_returnKeyword, PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_operators, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_brackets, PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_strings, PreferenceConstants.EDITOR_STRING_COLOR },
- { PreferencesMessages.JavaEditorPreferencePage_others, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR },
- };
-
- private final String fJavaCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_java;
- private final String fJavadocCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_javadoc;
- private final String fCommentsCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_comments;
-
- private ColorSelector fSyntaxForegroundColorEditor;
- private Label fColorEditorLabel;
- private Button fBoldCheckBox;
- private Button fEnableCheckbox;
- /**
- * Check box for italic preference.
- *
- */
- private Button fItalicCheckBox;
- /**
- * Check box for strikethrough preference.
- *
- */
- private Button fStrikethroughCheckBox;
- /**
- * Check box for underline preference.
- *
- */
- private Button fUnderlineCheckBox;
- /**
- * Highlighting color list
- *
- */
- private final java.util.List fListModel= new ArrayList();
- /**
- * Highlighting color list viewer
- *
- */
- private StructuredViewer fListViewer;
- /**
- * Semantic highlighting manager
- *
- */
- private SemanticHighlightingManager fSemanticHighlightingManager;
- /**
- * The previewer.
- *
- */
- private JavaSourceViewer fPreviewViewer;
- /**
- * The color manager.
- *
- */
- private IColorManager fColorManager;
- /**
- * The font metrics.
- *
- */
- private FontMetrics fFontMetrics;
-
- public JavaEditorColoringConfigurationBlock(OverlayPreferenceStore store) {
- super(store);
-
- fColorManager= new JavaColorManager(false);
-
- for (int i= 0, n= fSyntaxColorListModel.length; i < n; i++)
- fListModel.add(new HighlightingColorListItem (fSyntaxColorListModel[i][0],
- fSyntaxColorListModel[i][1],
- fSyntaxColorListModel[i][1] + BOLD,
- fSyntaxColorListModel[i][1] + ITALIC,
- fSyntaxColorListModel[i][1] + STRIKETHROUGH,
- fSyntaxColorListModel[i][1] + UNDERLINE));
-
- SemanticHighlighting[] semanticHighlightings= SemanticHighlightings.getSemanticHighlightings();
- for (int i= 0, n= semanticHighlightings.length; i < n; i++)
- fListModel.add(
- new SemanticHighlightingColorListItem(
- semanticHighlightings[i].getDisplayName(),
- SemanticHighlightings.getColorPreferenceKey(semanticHighlightings[i]),
- SemanticHighlightings.getBoldPreferenceKey(semanticHighlightings[i]),
- SemanticHighlightings.getItalicPreferenceKey(semanticHighlightings[i]),
- SemanticHighlightings.getStrikethroughPreferenceKey(semanticHighlightings[i]),
- SemanticHighlightings.getUnderlinePreferenceKey(semanticHighlightings[i]),
- SemanticHighlightings.getEnabledPreferenceKey(semanticHighlightings[i])
- ));
-
- store.addKeys(createOverlayStoreKeys());
- }
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- ArrayList overlayKeys= new ArrayList();
-
- for (int i= 0, n= fListModel.size(); i < n; i++) {
- HighlightingColorListItem item= (HighlightingColorListItem) fListModel.get(i);
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, item.getColorKey()));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getBoldKey()));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getItalicKey()));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getStrikethroughKey()));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getUnderlineKey()));
-
- if (item instanceof SemanticHighlightingColorListItem)
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ((SemanticHighlightingColorListItem) item).getEnableKey()));
- }
-
- OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
- overlayKeys.toArray(keys);
- return keys;
- }
-
- /**
- * Creates page for hover preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Control control= createSyntaxPage(scrolled);
-
- scrolled.setContent(control);
- final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
-
- return scrolled;
- }
-
- /**
- * Returns the number of pixels corresponding to the width of the given
- * number of characters.
- * <p>
- * This method may only be called after <code>initializeDialogUnits</code>
- * has been called.
- * </p>
- * <p>
- * Clients may call this framework method, but should not override it.
- * </p>
- *
- * @param chars
- * the number of characters
- * @return the number of pixels
- */
- private int convertWidthInCharsToPixels(int chars) {
- // test for failure to initialize for backward compatibility
- if (fFontMetrics == null)
- return 0;
- return Dialog.convertWidthInCharsToPixels(fFontMetrics, chars);
- }
-
- /**
- * Returns the number of pixels corresponding to the height of the given
- * number of characters.
- * <p>
- * This method may only be called after <code>initializeDialogUnits</code>
- * has been called.
- * </p>
- * <p>
- * Clients may call this framework method, but should not override it.
- * </p>
- *
- * @param chars
- * the number of characters
- * @return the number of pixels
- */
- private int convertHeightInCharsToPixels(int chars) {
- // test for failure to initialize for backward compatibility
- if (fFontMetrics == null)
- return 0;
- return Dialog.convertHeightInCharsToPixels(fFontMetrics, chars);
- }
-
- public void initialize() {
- super.initialize();
-
- fListViewer.setInput(fListModel);
- fListViewer.setSelection(new StructuredSelection(fJavaCategory));
- }
-
- public void performDefaults() {
- super.performDefaults();
-
- handleSyntaxColorListSelection();
-
- uninstallSemanticHighlighting();
- installSemanticHighlighting();
-
- fPreviewViewer.invalidateTextPresentation();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#dispose()
- */
- public void dispose() {
- uninstallSemanticHighlighting();
- fColorManager.dispose();
-
- super.dispose();
- }
-
- private void handleSyntaxColorListSelection() {
- HighlightingColorListItem item= getHighlightingColorListItem();
- if (item == null) {
- fEnableCheckbox.setEnabled(false);
- fSyntaxForegroundColorEditor.getButton().setEnabled(false);
- fColorEditorLabel.setEnabled(false);
- fBoldCheckBox.setEnabled(false);
- fItalicCheckBox.setEnabled(false);
- fStrikethroughCheckBox.setEnabled(false);
- fUnderlineCheckBox.setEnabled(false);
- return;
- }
- RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), item.getColorKey());
- fSyntaxForegroundColorEditor.setColorValue(rgb);
- fBoldCheckBox.setSelection(getPreferenceStore().getBoolean(item.getBoldKey()));
- fItalicCheckBox.setSelection(getPreferenceStore().getBoolean(item.getItalicKey()));
- fStrikethroughCheckBox.setSelection(getPreferenceStore().getBoolean(item.getStrikethroughKey()));
- fUnderlineCheckBox.setSelection(getPreferenceStore().getBoolean(item.getUnderlineKey()));
- if (item instanceof SemanticHighlightingColorListItem) {
- fEnableCheckbox.setEnabled(true);
- boolean enable= getPreferenceStore().getBoolean(((SemanticHighlightingColorListItem) item).getEnableKey());
- fEnableCheckbox.setSelection(enable);
- fSyntaxForegroundColorEditor.getButton().setEnabled(enable);
- fColorEditorLabel.setEnabled(enable);
- fBoldCheckBox.setEnabled(enable);
- fItalicCheckBox.setEnabled(enable);
- fStrikethroughCheckBox.setEnabled(enable);
- fUnderlineCheckBox.setEnabled(enable);
- } else {
- fSyntaxForegroundColorEditor.getButton().setEnabled(true);
- fColorEditorLabel.setEnabled(true);
- fBoldCheckBox.setEnabled(true);
- fItalicCheckBox.setEnabled(true);
- fStrikethroughCheckBox.setEnabled(true);
- fUnderlineCheckBox.setEnabled(true);
- fEnableCheckbox.setEnabled(false);
- fEnableCheckbox.setSelection(true);
- }
- }
-
- private Control createSyntaxPage(final Composite parent) {
-
- Composite colorComposite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- colorComposite.setLayout(layout);
-
- Link link= new Link(colorComposite, SWT.NONE);
- link.setText(PreferencesMessages.JavaEditorColoringConfigurationBlock_link);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(parent.getShell(), e.text, null, null);
- }
- });
- // TODO replace by link-specific tooltips when
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88866 gets fixed
-// link.setToolTipText(PreferencesMessages.JavaEditorColoringConfigurationBlock_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= 150; // only expand further if anyone else requires it
- gridData.horizontalSpan= 2;
- link.setLayoutData(gridData);
-
- addFiller(colorComposite, 1);
-
- Label label;
- label= new Label(colorComposite, SWT.LEFT);
- label.setText(PreferencesMessages.JavaEditorPreferencePage_coloring_element);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite editorComposite= new Composite(colorComposite, SWT.NONE);
- layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- editorComposite.setLayout(layout);
- GridData gd= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- editorComposite.setLayoutData(gd);
-
- fListViewer= new TreeViewer(editorComposite, SWT.SINGLE | SWT.BORDER);
- fListViewer.setLabelProvider(new ColorListLabelProvider());
- fListViewer.setContentProvider(new ColorListContentProvider());
- fListViewer.setComparator(new ViewerComparator() {
- public int category(Object element) {
- // don't sort the top level categories
- if (fJavaCategory.equals(element))
- return 0;
- if (fJavadocCategory.equals(element))
- return 1;
- if (fCommentsCategory.equals(element))
- return 2;
- // to sort semantic settings after partition based ones:
-// if (element instanceof SemanticHighlightingColorListItem)
-// return 1;
- return 0;
- }
- });
- gd= new GridData(SWT.BEGINNING, SWT.BEGINNING, false, true);
- gd.heightHint= convertHeightInCharsToPixels(9);
- int maxWidth= 0;
- for (Iterator it= fListModel.iterator(); it.hasNext();) {
- HighlightingColorListItem item= (HighlightingColorListItem) it.next();
- maxWidth= Math.max(maxWidth, convertWidthInCharsToPixels(item.getDisplayName().length()));
- }
- ScrollBar vBar= ((Scrollable) fListViewer.getControl()).getVerticalBar();
- if (vBar != null)
- maxWidth += vBar.getSize().x * 3; // scrollbars and tree indentation guess
- gd.widthHint= maxWidth;
-
- fListViewer.getControl().setLayoutData(gd);
-
- Composite stylesComposite= new Composite(editorComposite, SWT.NONE);
- layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- stylesComposite.setLayout(layout);
- stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- fEnableCheckbox= new Button(stylesComposite, SWT.CHECK);
- fEnableCheckbox.setText(PreferencesMessages.JavaEditorPreferencePage_enable);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment= GridData.BEGINNING;
- gd.horizontalSpan= 2;
- fEnableCheckbox.setLayoutData(gd);
-
- fColorEditorLabel= new Label(stylesComposite, SWT.LEFT);
- fColorEditorLabel.setText(PreferencesMessages.JavaEditorPreferencePage_color);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= 20;
- fColorEditorLabel.setLayoutData(gd);
-
- fSyntaxForegroundColorEditor= new ColorSelector(stylesComposite);
- Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton();
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- foregroundColorButton.setLayoutData(gd);
-
- fBoldCheckBox= new Button(stylesComposite, SWT.CHECK);
- fBoldCheckBox.setText(PreferencesMessages.JavaEditorPreferencePage_bold);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= 20;
- gd.horizontalSpan= 2;
- fBoldCheckBox.setLayoutData(gd);
-
- fItalicCheckBox= new Button(stylesComposite, SWT.CHECK);
- fItalicCheckBox.setText(PreferencesMessages.JavaEditorPreferencePage_italic);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= 20;
- gd.horizontalSpan= 2;
- fItalicCheckBox.setLayoutData(gd);
-
- fStrikethroughCheckBox= new Button(stylesComposite, SWT.CHECK);
- fStrikethroughCheckBox.setText(PreferencesMessages.JavaEditorPreferencePage_strikethrough);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= 20;
- gd.horizontalSpan= 2;
- fStrikethroughCheckBox.setLayoutData(gd);
-
- fUnderlineCheckBox= new Button(stylesComposite, SWT.CHECK);
- fUnderlineCheckBox.setText(PreferencesMessages.JavaEditorPreferencePage_underline);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= 20;
- gd.horizontalSpan= 2;
- fUnderlineCheckBox.setLayoutData(gd);
-
- label= new Label(colorComposite, SWT.LEFT);
- label.setText(PreferencesMessages.JavaEditorPreferencePage_preview);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Control previewer= createPreviewer(colorComposite);
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(20);
- gd.heightHint= convertHeightInCharsToPixels(5);
- previewer.setLayoutData(gd);
-
- fListViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- handleSyntaxColorListSelection();
- }
- });
-
- foregroundColorButton.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- PreferenceConverter.setValue(getPreferenceStore(), item.getColorKey(), fSyntaxForegroundColorEditor.getColorValue());
- }
- });
-
- fBoldCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- getPreferenceStore().setValue(item.getBoldKey(), fBoldCheckBox.getSelection());
- }
- });
-
- fItalicCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- getPreferenceStore().setValue(item.getItalicKey(), fItalicCheckBox.getSelection());
- }
- });
- fStrikethroughCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- getPreferenceStore().setValue(item.getStrikethroughKey(), fStrikethroughCheckBox.getSelection());
- }
- });
-
- fUnderlineCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- getPreferenceStore().setValue(item.getUnderlineKey(), fUnderlineCheckBox.getSelection());
- }
- });
-
- fEnableCheckbox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- HighlightingColorListItem item= getHighlightingColorListItem();
- if (item instanceof SemanticHighlightingColorListItem) {
- boolean enable= fEnableCheckbox.getSelection();
- getPreferenceStore().setValue(((SemanticHighlightingColorListItem) item).getEnableKey(), enable);
- fEnableCheckbox.setSelection(enable);
- fSyntaxForegroundColorEditor.getButton().setEnabled(enable);
- fColorEditorLabel.setEnabled(enable);
- fBoldCheckBox.setEnabled(enable);
- fItalicCheckBox.setEnabled(enable);
- fStrikethroughCheckBox.setEnabled(enable);
- fUnderlineCheckBox.setEnabled(enable);
- uninstallSemanticHighlighting();
- installSemanticHighlighting();
- }
- }
- });
-
- colorComposite.layout(false);
-
- return colorComposite;
- }
-
- private void addFiller(Composite composite, int horizontalSpan) {
- PixelConverter pixelConverter= new PixelConverter(composite);
- Label filler= new Label(composite, SWT.LEFT );
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= horizontalSpan;
- gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 2;
- filler.setLayoutData(gd);
- }
-
- private Control createPreviewer(Composite parent) {
-
- IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
- IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { getPreferenceStore(), new PreferencesAdapter(createTemporaryCorePreferenceStore()), generalTextStore });
- fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store);
- SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(fColorManager, store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
- fPreviewViewer.configure(configuration);
- // fake 1.5 source to get 1.5 features right.
- configuration.handlePropertyChangeEvent(new PropertyChangeEvent(this, JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_4, JavaScriptCore.VERSION_1_5));
- Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- fPreviewViewer.getTextWidget().setFont(font);
- new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store);
- fPreviewViewer.setEditable(false);
-
- String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
- IDocument document= new Document(content);
- JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- fPreviewViewer.setDocument(document);
-
- installSemanticHighlighting();
-
- return fPreviewViewer.getControl();
- }
-
-
- private Preferences createTemporaryCorePreferenceStore() {
- Preferences result= new Preferences();
-
- result.setValue(COMPILER_TASK_TAGS, "TASK,TODO"); //$NON-NLS-1$
-
- return result;
- }
-
-
- private String loadPreviewContentFromFile(String filename) {
- String line;
- String separator= System.getProperty("line.separator"); //$NON-NLS-1$
- StringBuffer buffer= new StringBuffer(512);
- BufferedReader reader= null;
- try {
- reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
- while ((line= reader.readLine()) != null) {
- buffer.append(line);
- buffer.append(separator);
- }
- } catch (IOException io) {
- JavaScriptPlugin.log(io);
- } finally {
- if (reader != null) {
- try { reader.close(); } catch (IOException e) {}
- }
- }
- return buffer.toString();
- }
-
-
- /**
- * Install Semantic Highlighting on the previewer
- *
- *
- */
- private void installSemanticHighlighting() {
- if (fSemanticHighlightingManager == null) {
- fSemanticHighlightingManager= new SemanticHighlightingManager();
- fSemanticHighlightingManager.install(fPreviewViewer, fColorManager, getPreferenceStore(), createPreviewerRanges());
- }
- }
-
-
- /**
- * Uninstall Semantic Highlighting from the previewer
- *
- *
- */
- private void uninstallSemanticHighlighting() {
- if (fSemanticHighlightingManager != null) {
- fSemanticHighlightingManager.uninstall();
- fSemanticHighlightingManager= null;
- }
- }
-
-
- /**
- * Create the hard coded previewer ranges
- *
- * @return the hard coded previewer ranges
- *
- */
- private SemanticHighlightingManager.HighlightedRange[][] createPreviewerRanges() {
- return new SemanticHighlightingManager.HighlightedRange[][] {
- // Function Declaration
- { createHighlightedRange( 9, 9, 3,SemanticHighlightings.METHOD_DECLARATION) },
- { createHighlightedRange(17, 9, 3,SemanticHighlightings.METHOD_DECLARATION) },
- { createHighlightedRange(21, 9, 4,SemanticHighlightings.METHOD_DECLARATION) },
- { createHighlightedRange(26, 9, 7,SemanticHighlightings.METHOD_DECLARATION) },
- // Function
- { createHighlightedRange(11,19, 6,SemanticHighlightings.METHOD) },
- { createHighlightedRange(14, 4, 5,SemanticHighlightings.METHOD) },
- // Local Variable Declaration
- { createHighlightedRange(11, 8, 4,SemanticHighlightings.LOCAL_VARIABLE_DECLARATION) },
- { createHighlightedRange(12, 8, 3,SemanticHighlightings.LOCAL_VARIABLE_DECLARATION) },
- { createHighlightedRange(13, 8, 1,SemanticHighlightings.LOCAL_VARIABLE_DECLARATION) },
- // Local Variable
- { createHighlightedRange(14,10, 4,SemanticHighlightings.LOCAL_VARIABLE) },
- // Object Initializer
- { createHighlightedRange(12,14,47,SemanticHighlightings.OBJECT_INITIALIZER) },
- // Parameter Variable
- { createHighlightedRange(20,16, 4,SemanticHighlightings.PARAMETER_VARIABLE) },
-// { createHighlightedRange( 6, 13, 9, SemanticHighlightings.DEPRECATED_MEMBER), createHighlightedRange( 6, 13, 9, SemanticHighlightings.CLASS), },
-// { createHighlightedRange( 6, 23, 1, SemanticHighlightings.TYPE_VARIABLE), createHighlightedRange( 6, 23, 1, SemanticHighlightings.TYPE_ARGUMENT), },
-// { createHighlightedRange( 6, 37, 9, SemanticHighlightings.INTERFACE) },
-// { createHighlightedRange( 6, 47, 6, SemanticHighlightings.TYPE_ARGUMENT), createHighlightedRange( 6, 47, 6, SemanticHighlightings.CLASS) },
-// { createHighlightedRange( 7, 6, 5, SemanticHighlightings.ENUM), },
-// {/* createHighlightedRange( 7, 14, 3, SemanticHighlightings.STATIC_FINAL_FIELD), createHighlightedRange(7, 14, 3, SemanticHighlightings.STATIC_FIELD), */createHighlightedRange(7, 14, 3, SemanticHighlightings.FIELD) },
-// { createHighlightedRange( 7, 19, 5, SemanticHighlightings.STATIC_FINAL_FIELD), createHighlightedRange(7, 19, 5, SemanticHighlightings.STATIC_FIELD), createHighlightedRange(7, 19, 5, SemanticHighlightings.FIELD) },
-// { createHighlightedRange( 7, 26, 4, SemanticHighlightings.STATIC_FINAL_FIELD), createHighlightedRange(7, 26, 4, SemanticHighlightings.STATIC_FIELD), createHighlightedRange(7, 26, 4, SemanticHighlightings.FIELD) },
-// { createHighlightedRange( 9, 8, 6, SemanticHighlightings.CLASS), },
-// { createHighlightedRange( 9, 15, 11, SemanticHighlightings.STATIC_FIELD), createHighlightedRange(9, 15, 11, SemanticHighlightings.FIELD) },
-// { createHighlightedRange(11, 9, 1, SemanticHighlightings.TYPE_VARIABLE) },
-// { createHighlightedRange(11, 11, 5, SemanticHighlightings.FIELD) },
-// { createHighlightedRange(13, 2, 16, SemanticHighlightings.ANNOTATION) },
-// { createHighlightedRange(13, 19, 5, SemanticHighlightings.ANNOTATION_ELEMENT_REFERENCE) },
-// { createHighlightedRange(14, 12, 3, SemanticHighlightings.METHOD_DECLARATION), createHighlightedRange(14, 12, 3, SemanticHighlightings.METHOD) },
-// { createHighlightedRange(14, 24, 9, SemanticHighlightings.PARAMETER_VARIABLE) },
-// { createHighlightedRange(15, 2, 14, SemanticHighlightings.ABSTRACT_METHOD_INVOCATION), createHighlightedRange(15, 2, 14, SemanticHighlightings.METHOD) },
-// { createHighlightedRange(16, 6, 5, SemanticHighlightings.LOCAL_VARIABLE_DECLARATION) },
-// { createHighlightedRange(16, 16, 8, SemanticHighlightings.INHERITED_METHOD_INVOCATION), createHighlightedRange(16, 16, 8, SemanticHighlightings.METHOD) },
-// { createHighlightedRange(17, 2, 12, SemanticHighlightings.STATIC_METHOD_INVOCATION), createHighlightedRange(17, 2, 12, SemanticHighlightings.METHOD) },
-// { createHighlightedRange(18, 9, 3, SemanticHighlightings.METHOD) },
-// { createHighlightedRange(18, 13, 5, SemanticHighlightings.LOCAL_VARIABLE) },
-// { createHighlightedRange(18, 22, 9, SemanticHighlightings.AUTOBOXING) },
- };
- }
-
-
- /**
- * Create a highlighted range on the previewers document with the given line, column, length and key.
- *
- * @param line the line
- * @param column the column
- * @param length the length
- * @param key the key
- * @return the highlighted range
- *
- */
- private HighlightedRange createHighlightedRange(int line, int column, int length, String key) {
- try {
- IDocument document= fPreviewViewer.getDocument();
- int offset= document.getLineOffset(line) + column;
- return new HighlightedRange(offset, length, key);
- } catch (BadLocationException x) {
- JavaScriptPlugin.log(x);
- }
- return null;
- }
-
-
- /**
- * Returns the current highlighting color list item.
- *
- * @return the current highlighting color list item
- *
- */
- private HighlightingColorListItem getHighlightingColorListItem() {
- IStructuredSelection selection= (IStructuredSelection) fListViewer.getSelection();
- Object element= selection.getFirstElement();
- if (element instanceof String)
- return null;
- return (HighlightingColorListItem) element;
- }
-
- /**
- * Initializes the computation of horizontal and vertical dialog units based
- * on the size of current font.
- * <p>
- * This method must be called before any of the dialog unit based conversion
- * methods are called.
- * </p>
- *
- * @param testControl
- * a control from which to obtain the current font
- */
- private void initializeDialogUnits(Control testControl) {
- // Compute and store a font metric
- GC gc = new GC(testControl);
- gc.setFont(JFaceResources.getDialogFont());
- fFontMetrics = gc.getFontMetrics();
- gc.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringPreferencePage.java
deleted file mode 100644
index 35970670..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorColoringPreferencePage.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-/**
- * Quick Diff preference page.
- * <p>
- * Note: Must be public since it is referenced from plugin.xml
- * </p>
- *
- *
- */
-public class JavaEditorColoringPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.JavaEditorPreferencePage_colors;
- setDescription(description);
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null;
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new JavaEditorColoringConfigurationBlock(overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java
deleted file mode 100644
index 3aa8ad4c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java
+++ /dev/null
@@ -1,580 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Configures Java Editor hover preferences.
- *
- *
- */
-class JavaEditorHoverConfigurationBlock implements IPreferenceConfigurationBlock {
-
- private static final String DELIMITER= PreferencesMessages.JavaEditorHoverConfigurationBlock_delimiter;
-
- private static final int ENABLED_PROP= 0;
- private static final int MODIFIER_PROP= 1;
-
- // Data structure to hold the values which are edited by the user
- private static class HoverConfig {
-
- private String fModifierString;
- private boolean fIsEnabled;
- private int fStateMask;
-
- private HoverConfig(String modifier, int stateMask, boolean enabled) {
- fModifierString= modifier;
- fIsEnabled= enabled;
- fStateMask= stateMask;
- }
- }
-
-
- private class JavaEditorTextHoverDescriptorLabelProvider implements ITableLabelProvider {
-
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex) {
- switch (columnIndex) {
- case ENABLED_PROP:
- return ((JavaEditorTextHoverDescriptor)element).getLabel();
-
- case MODIFIER_PROP:
- TableItem item= (TableItem)fHoverTableViewer.testFindItem(element);
- int index= fHoverTable.indexOf(item);
- return fHoverConfigs[index].fModifierString;
-
- default:
- break;
- }
-
- return null;
- }
-
- public void addListener(ILabelProviderListener listener) {
- }
-
- public void dispose() {
- }
-
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- public void removeListener(ILabelProviderListener listener) {
- }
- }
-
-
- private class JavaEditorTextHoverDescriptorContentProvider implements IStructuredContentProvider {
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // Do nothing since the viewer listens to resource deltas
- }
-
- public void dispose() {
- }
-
- public boolean isDeleted(Object element) {
- return false;
- }
-
- public Object[] getElements(Object element) {
- return (Object[])element;
- }
- }
-
-
- private OverlayPreferenceStore fStore;
- private HoverConfig[] fHoverConfigs;
- private Text fModifierEditor;
- private Table fHoverTable;
- private TableViewer fHoverTableViewer;
- private TableColumn fNameColumn;
- private TableColumn fModifierColumn;
- private Text fDescription;
-
- private PreferencePage fMainPreferencePage;
-
- private StatusInfo fStatus;
-
- private Map fCheckBoxes= new HashMap();
- private SelectionListener fCheckBoxListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- Button button= (Button) e.widget;
- fStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
- }
- public void widgetSelected(SelectionEvent e) {
- Button button= (Button) e.widget;
- fStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
- }
- };
-
-
- public JavaEditorHoverConfigurationBlock(PreferencePage mainPreferencePage, OverlayPreferenceStore store) {
- Assert.isNotNull(mainPreferencePage);
- Assert.isNotNull(store);
- fMainPreferencePage= mainPreferencePage;
- fStore= store;
- fStore.addKeys(createOverlayStoreKeys());
- }
-
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- ArrayList overlayKeys= new ArrayList();
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER));
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS));
-
- OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
- overlayKeys.toArray(keys);
- return keys;
- }
-
- /**
- * Creates page for hover preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(Composite parent) {
-
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
-
- Composite hoverComposite= new Composite(scrolled, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- hoverComposite.setLayout(layout);
-
- String rollOverLabel= PreferencesMessages.JavaEditorHoverConfigurationBlock_annotationRollover;
- addCheckBox(hoverComposite, rollOverLabel, PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER, 0);
-
- addFiller(hoverComposite);
-
- Label label= new Label(hoverComposite, SWT.NONE);
- label.setText(PreferencesMessages.JavaEditorHoverConfigurationBlock_hoverPreferences);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment= GridData.BEGINNING;
- gd.horizontalSpan= 2;
- label.setLayoutData(gd);
-
- TableLayoutComposite layouter= new TableLayoutComposite(hoverComposite, SWT.NONE);
- addColumnLayoutData(layouter);
-
- // Hover table
- fHoverTable= new Table(layouter, SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
- fHoverTable.setHeaderVisible(true);
- fHoverTable.setLinesVisible(true);
-
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint= SWTUtil.getTableHeightHint(fHoverTable, 10);
- gd.horizontalSpan= 2;
- gd.widthHint= new PixelConverter(parent).convertWidthInCharsToPixels(30);
- layouter.setLayoutData(gd);
-
- fHoverTable.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- handleHoverListSelection();
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- TableLayout tableLayout= new TableLayout();
- fHoverTable.setLayout(tableLayout);
-
- fNameColumn= new TableColumn(fHoverTable, SWT.NONE);
- fNameColumn.setText(PreferencesMessages.JavaEditorHoverConfigurationBlock_nameColumnTitle);
- fNameColumn.setResizable(true);
-
- fModifierColumn= new TableColumn(fHoverTable, SWT.NONE);
- fModifierColumn.setText(PreferencesMessages.JavaEditorHoverConfigurationBlock_modifierColumnTitle);
- fModifierColumn.setResizable(true);
-
- fHoverTableViewer= new CheckboxTableViewer(fHoverTable);
- fHoverTableViewer.setUseHashlookup(true);
- fHoverTableViewer.setContentProvider(new JavaEditorTextHoverDescriptorContentProvider());
- fHoverTableViewer.setLabelProvider(new JavaEditorTextHoverDescriptorLabelProvider());
-
- ((CheckboxTableViewer)fHoverTableViewer).addCheckStateListener(new ICheckStateListener() {
- /*
- * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent)
- */
- public void checkStateChanged(CheckStateChangedEvent event) {
- String id= ((JavaEditorTextHoverDescriptor)event.getElement()).getId();
- if (id == null)
- return;
- JavaEditorTextHoverDescriptor[] descriptors= getContributedHovers();
- HoverConfig hoverConfig= null;
- int i= 0, length= fHoverConfigs.length;
- while (i < length) {
- if (id.equals(descriptors[i].getId())) {
- hoverConfig= fHoverConfigs[i];
- hoverConfig.fIsEnabled= event.getChecked();
- fModifierEditor.setEnabled(event.getChecked());
- fHoverTableViewer.setSelection(new StructuredSelection(descriptors[i]));
- }
- i++;
- }
- handleHoverListSelection();
- updateStatus(hoverConfig);
- }
- });
-
- // Text field for modifier string
- label= new Label(hoverComposite, SWT.LEFT);
- label.setText(PreferencesMessages.JavaEditorHoverConfigurationBlock_keyModifier);
- fModifierEditor= new Text(hoverComposite, SWT.BORDER);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- fModifierEditor.setLayoutData(gd);
-
- fModifierEditor.addKeyListener(new KeyListener() {
- private boolean isModifierCandidate;
- public void keyPressed(KeyEvent e) {
- isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0;
- }
-
- public void keyReleased(KeyEvent e) {
- if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) {
- String text= fModifierEditor.getText();
- Point selection= fModifierEditor.getSelection();
- int i= selection.x - 1;
- while (i > -1 && Character.isWhitespace(text.charAt(i))) {
- i--;
- }
- boolean needsPrefixDelimiter= i > -1 && !String.valueOf(text.charAt(i)).equals(DELIMITER);
-
- i= selection.y;
- while (i < text.length() && Character.isWhitespace(text.charAt(i))) {
- i++;
- }
- boolean needsPostfixDelimiter= i < text.length() && !String.valueOf(text.charAt(i)).equals(DELIMITER);
-
- String insertString;
-
- if (needsPrefixDelimiter && needsPostfixDelimiter)
- insertString= Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_insertDelimiterAndModifierAndDelimiter, new String[] {Action.findModifierString(e.stateMask)});
- else if (needsPrefixDelimiter)
- insertString= Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_insertDelimiterAndModifier, new String[] {Action.findModifierString(e.stateMask)});
- else if (needsPostfixDelimiter)
- insertString= Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_insertModifierAndDelimiter, new String[] {Action.findModifierString(e.stateMask)});
- else
- insertString= Action.findModifierString(e.stateMask);
-
- if (insertString != null)
- fModifierEditor.insert(insertString);
- }
- }
- });
-
- fModifierEditor.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- handleModifierModified();
- }
- });
-
- // Description
- Label descriptionLabel= new Label(hoverComposite, SWT.LEFT);
- descriptionLabel.setText(PreferencesMessages.JavaEditorHoverConfigurationBlock_description);
- gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
- gd.horizontalSpan= 2;
- descriptionLabel.setLayoutData(gd);
- fDescription= new Text(hoverComposite, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER);
- gd= new GridData(GridData.FILL_BOTH);
- gd.horizontalSpan= 2;
- fDescription.setLayoutData(gd);
-
- initialize();
-
- scrolled.setContent(hoverComposite);
- final Point size= hoverComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
-
- Dialog.applyDialogFont(scrolled);
-
- return scrolled;
-
- }
-
- private void addColumnLayoutData(TableLayoutComposite layouter) {
- layouter.addColumnData(new ColumnWeightData(40, true));
- layouter.addColumnData(new ColumnWeightData(60, true));
- }
-
- private JavaEditorTextHoverDescriptor[] getContributedHovers() {
- return JavaScriptPlugin.getDefault().getJavaEditorTextHoverDescriptors();
- }
-
- public void initialize() {
- JavaEditorTextHoverDescriptor[] hoverDescs= getContributedHovers();
- fHoverConfigs= new HoverConfig[hoverDescs.length];
- for (int i= 0; i < hoverDescs.length; i++)
- fHoverConfigs[i]= new HoverConfig(hoverDescs[i].getModifierString(), hoverDescs[i].getStateMask(), hoverDescs[i].isEnabled());
-
- fHoverTableViewer.setInput(hoverDescs);
-
- initializeFields();
- }
-
- void initializeFields() {
- fModifierEditor.setEnabled(false);
-
- Iterator e= fCheckBoxes.keySet().iterator();
- while (e.hasNext()) {
- Button b= (Button) e.next();
- String key= (String) fCheckBoxes.get(b);
- b.setSelection(fStore.getBoolean(key));
- }
-
- for (int i= 0; i < fHoverConfigs.length; i++)
- fHoverTable.getItem(i).setChecked(fHoverConfigs[i].fIsEnabled);
- fHoverTableViewer.refresh();
- }
-
- public void performOk() {
- StringBuffer buf= new StringBuffer();
- StringBuffer maskBuf= new StringBuffer();
- for (int i= 0; i < fHoverConfigs.length; i++) {
- buf.append(getContributedHovers()[i].getId());
- buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
- if (!fHoverConfigs[i].fIsEnabled)
- buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG);
- String modifier= fHoverConfigs[i].fModifierString;
- if (modifier == null || modifier.length() == 0)
- modifier= JavaEditorTextHoverDescriptor.NO_MODIFIER;
- buf.append(modifier);
- buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
-
- maskBuf.append(getContributedHovers()[i].getId());
- maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
- maskBuf.append(fHoverConfigs[i].fStateMask);
- maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
- }
- fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf.toString());
- fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, maskBuf.toString());
-
- JavaScriptPlugin.getDefault().resetJavaEditorTextHoverDescriptors();
- }
-
- public void performDefaults() {
- restoreFromPreferences();
- initializeFields();
- updateStatus(null);
- }
-
- private void restoreFromPreferences() {
- String compiledTextHoverModifiers= fStore.getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS);
-
- StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
- HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2);
-
- while (tokenizer.hasMoreTokens()) {
- String id= tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- idToModifier.put(id, tokenizer.nextToken());
- }
-
- String compiledTextHoverModifierMasks= JavaScriptPlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS);
-
- tokenizer= new StringTokenizer(compiledTextHoverModifierMasks, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
- HashMap idToModifierMask= new HashMap(tokenizer.countTokens() / 2);
-
- while (tokenizer.hasMoreTokens()) {
- String id= tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- idToModifierMask.put(id, tokenizer.nextToken());
- }
-
- for (int i= 0; i < fHoverConfigs.length; i++) {
- String modifierString= (String)idToModifier.get(getContributedHovers()[i].getId());
- boolean enabled= true;
- if (modifierString == null)
- modifierString= JavaEditorTextHoverDescriptor.DISABLED_TAG;
-
- if (modifierString.startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) {
- enabled= false;
- modifierString= modifierString.substring(1);
- }
-
- if (modifierString.equals(JavaEditorTextHoverDescriptor.NO_MODIFIER))
- modifierString= ""; //$NON-NLS-1$
-
- fHoverConfigs[i].fModifierString= modifierString;
- fHoverConfigs[i].fIsEnabled= enabled;
- fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifierString);
-
- if (fHoverConfigs[i].fStateMask == -1) {
- try {
- fHoverConfigs[i].fStateMask= Integer.parseInt((String)idToModifierMask.get(getContributedHovers()[i].getId()));
- } catch (NumberFormatException ex) {
- fHoverConfigs[i].fStateMask= -1;
- }
- }
- }
- }
-
- private void handleModifierModified() {
- int i= fHoverTable.getSelectionIndex();
- if (i == -1)
- return;
-
- String modifiers= fModifierEditor.getText();
- fHoverConfigs[i].fModifierString= modifiers;
- fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifiers);
-
- // update table
- fHoverTableViewer.refresh(getContributedHovers()[i]);
-
- updateStatus(fHoverConfigs[i]);
- }
-
- private void handleHoverListSelection() {
- int i= fHoverTable.getSelectionIndex();
-
- if (i == -1) {
- if (fHoverTable.getSelectionCount() == 0)
- fModifierEditor.setEnabled(false);
- return;
- }
-
- boolean enabled= fHoverConfigs[i].fIsEnabled;
- fModifierEditor.setEnabled(enabled);
- fModifierEditor.setText(fHoverConfigs[i].fModifierString);
- String description= getContributedHovers()[i].getDescription();
- if (description == null)
- description= ""; //$NON-NLS-1$
- fDescription.setText(description);
- }
-
- IStatus getStatus() {
- if (fStatus == null)
- fStatus= new StatusInfo();
- return fStatus;
- }
-
- private void updateStatus(HoverConfig hoverConfig) {
- if (hoverConfig != null && hoverConfig.fIsEnabled && hoverConfig.fStateMask == -1)
- fStatus= new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_modifierIsNotValid, hoverConfig.fModifierString));
- else
- fStatus= new StatusInfo();
-
- int i= 0;
- HashMap stateMasks= new HashMap(fHoverConfigs.length);
- while (fStatus.isOK() && i < fHoverConfigs.length) {
- if (fHoverConfigs[i].fIsEnabled) {
- String label= getContributedHovers()[i].getLabel();
- Integer stateMask= new Integer(fHoverConfigs[i].fStateMask);
- if (fHoverConfigs[i].fStateMask == -1)
- fStatus= new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_modifierIsNotValidForHover, new String[] {fHoverConfigs[i].fModifierString, label}));
- else if (stateMasks.containsKey(stateMask))
- fStatus= new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.JavaEditorHoverConfigurationBlock_duplicateModifier, new String[] {label, (String)stateMasks.get(stateMask)}));
- else
- stateMasks.put(stateMask, label);
- }
- i++;
- }
-
- fMainPreferencePage.setValid(fStatus.isOK());
- StatusUtil.applyToStatusLine(fMainPreferencePage, fStatus);
- }
-
- private Button addCheckBox(Composite parent, String label, String key, int indentation) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(label);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indentation;
- gd.horizontalSpan= 2;
- checkBox.setLayoutData(gd);
- checkBox.addSelectionListener(fCheckBoxListener);
-
- fCheckBoxes.put(checkBox, key);
-
- return checkBox;
- }
-
- private void addFiller(Composite composite) {
- PixelConverter pixelConverter= new PixelConverter(composite);
- Label filler= new Label(composite, SWT.LEFT );
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 2;
- filler.setLayoutData(gd);
- }
-
- /*
- * @see DialogPage#dispose()
- */
- public void dispose() {
- // nothing to dispose
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverPreferencePage.java
deleted file mode 100644
index d3cd23b6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorHoverPreferencePage.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-/**
- * Quick Diff preference page.
- * <p>
- * Note: Must be public since it is referenced from plugin.xml
- * </p>
- *
- *
- */
-public class JavaEditorHoverPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.JavaEditorPreferencePage_hoverTab_title;
- setDescription(description);
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null; // no description for new look.
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new JavaEditorHoverConfigurationBlock(this, overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPreferencePage.java
deleted file mode 100644
index e877be8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPreferencePage.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * The page for setting the editor options.
- */
-public final class JavaEditorPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.JavaEditorPreferencePage_general;
- setDescription(description);
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null; // no description for new look.
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new JavaEditorAppearanceConfigurationBlock(this, overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPropertyPage.java
deleted file mode 100644
index 266d9be5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorPropertyPage.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbenchPropertyPage;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-
-public class JavaEditorPropertyPage extends PropertyPage implements IWorkbenchPropertyPage {
-
- public JavaEditorPropertyPage() {}
-
- protected Control createContents(Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setLayout(new GridLayout());
-
- Link link= new Link(composite, SWT.WRAP);
- GridData data= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- data.widthHint= 300;
- link.setLayoutData(data);
- link.setText(PreferencesMessages.JavaEditorPropertyPage_SaveActionLink_Text);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer)getContainer();
- container.openPage(SaveParticipantPreferencePage.PROPERTY_PAGE_ID, null);
- }
- });
-
- return composite;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaElementInfoPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaElementInfoPage.java
deleted file mode 100644
index fd972a3f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaElementInfoPage.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-
-/**
- * This is a dummy PropertyPage for JavaElements.
- * Copied from the ResourceInfoPage
- */
-public class JavaElementInfoPage extends PropertyPage {
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_ELEMENT_INFO_PAGE);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- // ensure the page has no special buttons
- noDefaultAndApplyButton();
-
- IJavaScriptElement element= (IJavaScriptElement)getElement();
-
- IResource resource= element.getResource();
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
-
- Label nameLabel= new Label(composite, SWT.NONE);
- nameLabel.setText(PreferencesMessages.JavaElementInfoPage_nameLabel);
-
- Label nameValueLabel= new Label(composite, SWT.NONE);
- nameValueLabel.setText(element.getElementName());
-
- if (resource != null) {
- // path label
- Label pathLabel= new Label(composite, SWT.NONE);
- pathLabel.setText(PreferencesMessages.JavaElementInfoPage_resource_path);
-
- // path value label
- Label pathValueLabel= new Label(composite, SWT.NONE);
- pathValueLabel.setText(resource.getFullPath().toString());
- }
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit)element;
- Label packageLabel= new Label(composite, SWT.NONE);
- packageLabel.setText(PreferencesMessages.JavaElementInfoPage_package);
- Label packageName= new Label(composite, SWT.NONE);
- packageName.setText(unit.getParent().getElementName());
-
- } else if (element instanceof IPackageFragment) {
- IPackageFragment packageFragment= (IPackageFragment)element;
- Label packageContents= new Label(composite, SWT.NONE);
- packageContents.setText(PreferencesMessages.JavaElementInfoPage_package_contents);
- Label packageContentsType= new Label(composite, SWT.NONE);
- try {
- if (packageFragment.getKind() == IPackageFragmentRoot.K_SOURCE)
- packageContentsType.setText(PreferencesMessages.JavaElementInfoPage_source);
- else
- packageContentsType.setText(PreferencesMessages.JavaElementInfoPage_binary);
- } catch (JavaScriptModelException e) {
- packageContentsType.setText(PreferencesMessages.JavaElementInfoPage_not_present);
- }
- } else if (element instanceof IPackageFragmentRoot) {
- Label rootContents= new Label(composite, SWT.NONE);
- rootContents.setText(PreferencesMessages.JavaElementInfoPage_classpath_entry_kind);
- Label rootContentsType= new Label(composite, SWT.NONE);
- try {
- IIncludePathEntry entry= ((IPackageFragmentRoot)element).getRawIncludepathEntry();
- if (entry != null) {
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_source); break;
- case IIncludePathEntry.CPE_PROJECT:
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_project); break;
- case IIncludePathEntry.CPE_LIBRARY:
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_library); break;
- case IIncludePathEntry.CPE_VARIABLE:
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_variable);
- Label varPath= new Label(composite, SWT.NONE);
- varPath.setText(PreferencesMessages.JavaElementInfoPage_variable_path);
- Label varPathVar= new Label(composite, SWT.NONE);
- varPathVar.setText(entry.getPath().makeRelative().toString());
- break;
- }
- } else {
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_not_present);
- }
- } catch (JavaScriptModelException e) {
- rootContentsType.setText(PreferencesMessages.JavaElementInfoPage_not_present);
- }
- } else if (element instanceof IJavaScriptProject) {
- Label packageLabel= new Label(composite, SWT.NONE);
- packageLabel.setText(PreferencesMessages.JavaElementInfoPage_location);
- String location= Resources.getLocationString(((IJavaScriptProject)element).getProject());
- if (location != null) {
- Label packageName= new Label(composite, SWT.NONE);
- packageName.setText(location);
- }
- }
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaPreferencesSettings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaPreferencesSettings.java
deleted file mode 100644
index 5305c85e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaPreferencesSettings.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class JavaPreferencesSettings {
-
-
- public static CodeGenerationSettings getCodeGenerationSettings(IJavaScriptProject project) {
- CodeGenerationSettings res= new CodeGenerationSettings();
- res.createComments= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, project)).booleanValue();
- res.useKeywordThis= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_KEYWORD_THIS, project)).booleanValue();
- res.overrideAnnotation= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_USE_OVERRIDE_ANNOTATION, project)).booleanValue();
- res.importOrder= getImportOrderPreference(project);
- res.importThreshold= getImportNumberThreshold(project);
- res.staticImportThreshold= getStaticImportNumberThreshold(project);
- res.importIgnoreLowercase= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, project)).booleanValue();
- res.tabWidth= CodeFormatterUtil.getTabWidth(project);
- res.indentWidth= CodeFormatterUtil.getIndentWidth(project);
- return res;
- }
-
- /**
- * @deprecated Use getCodeGenerationSettings(IJavaScriptProject) instead
- */
- public static CodeGenerationSettings getCodeGenerationSettings() {
- return getCodeGenerationSettings(null);
- }
-
- public static int getImportNumberThreshold(IJavaScriptProject project) {
- String thresholdStr= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, project);
- try {
- int threshold= Integer.parseInt(thresholdStr);
- if (threshold < 0) {
- threshold= Integer.MAX_VALUE;
- }
- return threshold;
- } catch (NumberFormatException e) {
- return Integer.MAX_VALUE;
- }
- }
-
- public static int getStaticImportNumberThreshold(IJavaScriptProject project) {
- String thresholdStr= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, project);
- try {
- int threshold= Integer.parseInt(thresholdStr);
- if (threshold < 0) {
- threshold= Integer.MAX_VALUE;
- }
- return threshold;
- } catch (NumberFormatException e) {
- return Integer.MAX_VALUE;
- }
- }
-
- public static String[] getImportOrderPreference(IJavaScriptProject project) {
- String str= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_IMPORTORDER, project);
- if (str != null) {
- return unpackList(str, ";"); //$NON-NLS-1$
- }
- return new String[0];
- }
-
- /**
- * @deprecated Use getImportNumberThreshold(IJavaScriptProject) instead
- */
- public static int getImportNumberThreshold(IPreferenceStore prefs) {
- int threshold= prefs.getInt(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD);
- if (threshold < 0) {
- threshold= Integer.MAX_VALUE;
- }
- return threshold;
- }
-
- /**
- * @deprecated Use getImportOrderPreference(IJavaScriptProject) instead
- */
- public static String[] getImportOrderPreference(IPreferenceStore prefs) {
- String str= prefs.getString(PreferenceConstants.ORGIMPORTS_IMPORTORDER);
- if (str != null) {
- return unpackList(str, ";"); //$NON-NLS-1$
- }
- return new String[0];
- }
-
- private static String[] unpackList(String str, String separator) {
- StringTokenizer tok= new StringTokenizer(str, separator);
- int nTokens= tok.countTokens();
- String[] res= new String[nTokens];
- for (int i= 0; i < nTokens; i++) {
- res[i]= tok.nextToken().trim();
- }
- return res;
- }
-
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaScriptMainPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaScriptMainPage.java
deleted file mode 100644
index 17d289d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaScriptMainPage.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.SWT;
-//import org.eclipse.swt.events.SelectionAdapter;
-//import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-//import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbenchPropertyPage;
-import org.eclipse.ui.dialogs.PropertyPage;
-//import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-
-/**
- * @author childsb
- *
-
- */
-
-
-public class JavaScriptMainPage extends PropertyPage implements IWorkbenchPropertyPage{
-
- public static final String PROP_ID= "org.eclipse.wst.jsdt.internal.ui.preferences.JavaScriptMainPage"; //$NON-NLS-1$
-
- public JavaScriptMainPage() {}
-
- protected Control createContents(Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setLayout(new GridLayout());
-
-// Link link= new Link(composite, SWT.WRAP);
-// GridData data= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
-// data.widthHint= 300;
-// link.setLayoutData(data);
-// link.setText(PreferencesMessages.JavaEditorPropertyPage_SaveActionLink_Text);
-// link.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent e) {
-// IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer)getContainer();
-// container.openPage(SaveParticipantPreferencePage.PROPERTY_PAGE_ID, null);
-// }
-// });
-
- return composite;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java
deleted file mode 100644
index 44e6d4ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-/**
- * Handles Java editor font changes for Java source preview viewers.
- *
- *
- */
-class JavaSourcePreviewerUpdater {
-
- /**
- * Creates a Java source preview updater for the given viewer, configuration and preference store.
- *
- * @param viewer the viewer
- * @param configuration the configuration
- * @param preferenceStore the preference store
- */
- JavaSourcePreviewerUpdater(final SourceViewer viewer, final JavaScriptSourceViewerConfiguration configuration, final IPreferenceStore preferenceStore) {
- Assert.isNotNull(viewer);
- Assert.isNotNull(configuration);
- Assert.isNotNull(preferenceStore);
- final IPropertyChangeListener fontChangeListener= new IPropertyChangeListener() {
- /*
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(PreferenceConstants.EDITOR_TEXT_FONT)) {
- Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- viewer.getTextWidget().setFont(font);
- }
- }
- };
- final IPropertyChangeListener propertyChangeListener= new IPropertyChangeListener() {
- /*
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (configuration.affectsTextPresentation(event)) {
- configuration.handlePropertyChangeEvent(event);
- viewer.invalidateTextPresentation();
- }
- }
- };
- viewer.getTextWidget().addDisposeListener(new DisposeListener() {
- /*
- * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
- */
- public void widgetDisposed(DisposeEvent e) {
- preferenceStore.removePropertyChangeListener(propertyChangeListener);
- JFaceResources.getFontRegistry().removeListener(fontChangeListener);
- }
- });
- JFaceResources.getFontRegistry().addListener(fontChangeListener);
- preferenceStore.addPropertyChangeListener(propertyChangeListener);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaTemplatePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaTemplatePreferencePage.java
deleted file mode 100644
index 62bdcb9c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaTemplatePreferencePage.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.templates.TemplatePreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-public class JavaTemplatePreferencePage extends TemplatePreferencePage implements IWorkbenchPreferencePage {
-
- private TemplateVariableProcessor fTemplateProcessor;
-
- public JavaTemplatePreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setTemplateStore(JavaScriptPlugin.getDefault().getTemplateStore());
- setContextTypeRegistry(JavaScriptPlugin.getDefault().getTemplateContextRegistry());
- fTemplateProcessor= new TemplateVariableProcessor();
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createContents(org.eclipse.swt.widgets.Composite)
- *
- */
- protected Control createContents(Composite ancestor) {
- ScrolledPageContent scrolled= new ScrolledPageContent(ancestor, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Control control= super.createContents(scrolled);
-
- scrolled.setContent(control);
- final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
-
- return scrolled;
- }
-
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- boolean ok= super.performOk();
-
- JavaScriptPlugin.getDefault().savePluginPreferences();
-
- return ok;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#getFormatterPreferenceKey()
- */
- protected String getFormatterPreferenceKey() {
- return PreferenceConstants.TEMPLATES_USE_CODEFORMATTER;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createTemplateEditDialog2(org.eclipse.jface.text.templates.Template, boolean, boolean)
- */
- protected Template editTemplate(Template template, boolean edit, boolean isNameModifiable) {
- org.eclipse.wst.jsdt.internal.ui.preferences.EditTemplateDialog dialog= new org.eclipse.wst.jsdt.internal.ui.preferences.EditTemplateDialog(getShell(), template, edit, isNameModifiable, getContextTypeRegistry());
- if (dialog.open() == Window.OK) {
- return dialog.getTemplate();
- }
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createViewer(org.eclipse.swt.widgets.Composite)
- */
- protected SourceViewer createViewer(Composite parent) {
- IDocument document= new Document();
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- tools.setupJavaDocumentPartitioner(document, IJavaScriptPartitions.JAVA_PARTITIONING);
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
- SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false);
- viewer.configure(configuration);
- viewer.setEditable(false);
- viewer.setDocument(document);
-
- Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- viewer.getTextWidget().setFont(font);
- new JavaSourcePreviewerUpdater(viewer, configuration, store);
-
- Control control= viewer.getControl();
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
- control.setLayoutData(data);
-
- return viewer;
- }
-
-
- /*
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#updateViewerInput()
- */
- protected void updateViewerInput() {
- IStructuredSelection selection= (IStructuredSelection) getTableViewer().getSelection();
- SourceViewer viewer= getViewer();
-
- if (selection.size() == 1 && selection.getFirstElement() instanceof TemplatePersistenceData) {
- TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
- Template template= data.getTemplate();
- String contextId= template.getContextTypeId();
- TemplateContextType type= JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType(contextId);
- fTemplateProcessor.setContextType(type);
-
- IDocument doc= viewer.getDocument();
-
- String start= null;
- if ("javadoc".equals(contextId)) { //$NON-NLS-1$
- start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
- } else
- start= ""; //$NON-NLS-1$
-
- doc.set(start + template.getPattern());
- int startLen= start.length();
- viewer.setDocument(doc, startLen, doc.getLength() - startLen);
-
- } else {
- viewer.getDocument().set(""); //$NON-NLS-1$
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java
deleted file mode 100644
index 8d1eb392..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java
+++ /dev/null
@@ -1,920 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.zip.ZipFile;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.OpenBrowserUtil;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ArchiveFileFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavadocConfigurationBlock {
- private static final String FILE_IMPORT_MASK= "*.jar;*.zip"; //$NON-NLS-1$
- private static final String ERROR_DIALOG_TITLE= "Error Dialog"; //$NON-NLS-1$
-
- private StringDialogField fURLField;
- private StringDialogField fArchiveField;
- private StringDialogField fArchivePathField;
- private URL fInitialURL;
- private SelectionButtonDialogField fValidateURLButton;
- private SelectionButtonDialogField fValidateArchiveButton;
- private SelectionButtonDialogField fBrowseFolder;
- private SelectionButtonDialogField fURLRadioButton;
- private SelectionButtonDialogField fArchiveRadioButton;
- private SelectionButtonDialogField fBrowseArchive;
- private SelectionButtonDialogField fExternalRadio, fWorkspaceRadio;
- private SelectionButtonDialogField fBrowseArchivePath;
- private Shell fShell;
- private IStatusChangeListener fContext;
-
- private IStatus fURLStatus;
- private IStatus fArchiveStatus;
- private IStatus fArchivePathStatus;
-
- private URL fURLResult;
- private URL fArchiveURLResult;
-
- boolean fIsForSource;
-
-
- public JavadocConfigurationBlock(Shell shell, IStatusChangeListener context, URL initURL, boolean forSource) {
- fShell= shell;
- fContext= context;
- fInitialURL= initURL;
- fIsForSource= forSource;
-
- JDocConfigurationAdapter adapter= new JDocConfigurationAdapter();
-
- if (!forSource) {
- fURLRadioButton= new SelectionButtonDialogField(SWT.RADIO);
- fURLRadioButton.setDialogFieldListener(adapter);
- fURLRadioButton.setLabelText(PreferencesMessages.JavadocConfigurationBlock_location_type_path_label);
- }
-
- fURLField= new StringDialogField();
- fURLField.setDialogFieldListener(adapter);
- fURLField.setLabelText(PreferencesMessages.JavadocConfigurationBlock_location_path_label);
-
- fBrowseFolder= new SelectionButtonDialogField(SWT.PUSH);
- fBrowseFolder.setDialogFieldListener(adapter);
- fBrowseFolder.setLabelText(PreferencesMessages.JavadocConfigurationBlock_browse_folder_button);
-
- fValidateURLButton= new SelectionButtonDialogField(SWT.PUSH);
- fValidateURLButton.setDialogFieldListener(adapter);
- fValidateURLButton.setLabelText(PreferencesMessages.JavadocConfigurationBlock_validate_button);
-
- if (!forSource) {
- fArchiveRadioButton= new SelectionButtonDialogField(SWT.RADIO);
- fArchiveRadioButton.setDialogFieldListener(adapter);
- fArchiveRadioButton.setLabelText(PreferencesMessages.JavadocConfigurationBlock_location_type_jar_label);
-
- fExternalRadio= new SelectionButtonDialogField(SWT.RADIO);
- fExternalRadio.setDialogFieldListener(adapter);
- fExternalRadio.setLabelText(PreferencesMessages.JavadocConfigurationBlock_external_radio);
-
- fWorkspaceRadio= new SelectionButtonDialogField(SWT.RADIO);
- fWorkspaceRadio.setDialogFieldListener(adapter);
- fWorkspaceRadio.setLabelText(PreferencesMessages.JavadocConfigurationBlock_workspace_radio);
-
- fArchiveField= new StringDialogField();
- fArchiveField.setDialogFieldListener(adapter);
- fArchiveField.setLabelText(PreferencesMessages.JavadocConfigurationBlock_location_jar_label);
-
- fBrowseArchive= new SelectionButtonDialogField(SWT.PUSH);
- fBrowseArchive.setDialogFieldListener(adapter);
- fBrowseArchive.setLabelText(PreferencesMessages.JavadocConfigurationBlock_browse_archive_button);
-
- fArchivePathField= new StringDialogField();
- fArchivePathField.setDialogFieldListener(adapter);
- fArchivePathField.setLabelText(PreferencesMessages.JavadocConfigurationBlock_jar_path_label);
-
- fBrowseArchivePath= new SelectionButtonDialogField(SWT.PUSH);
- fBrowseArchivePath.setDialogFieldListener(adapter);
- fBrowseArchivePath.setLabelText(PreferencesMessages.JavadocConfigurationBlock_browse_archive_path_button);
-
- fValidateArchiveButton= new SelectionButtonDialogField(SWT.PUSH);
- fValidateArchiveButton.setDialogFieldListener(adapter);
- fValidateArchiveButton.setLabelText(PreferencesMessages.JavadocConfigurationBlock_validate_button);
- }
-
- fURLStatus= new StatusInfo();
- fArchiveStatus= new StatusInfo();
- fArchivePathStatus= new StatusInfo();
-
- initializeSelections();
- }
-
- public Control createContents(Composite parent) {
- fShell= parent.getShell();
-
- PixelConverter converter= new PixelConverter(parent);
- Composite topComp= new Composite(parent, SWT.NONE);
- GridLayout topLayout= new GridLayout();
- topLayout.numColumns= 3;
- topLayout.marginWidth= 0;
- topLayout.marginHeight= 0;
- topComp.setLayout(topLayout);
-
- // Add the first radio button for the path
- if (!fIsForSource) {
- fURLRadioButton.doFillIntoGrid(topComp, 3);
- }
-
- fURLField.doFillIntoGrid(topComp, 2);
- LayoutUtil.setWidthHint(fURLField.getTextControl(null), converter.convertWidthInCharsToPixels(43));
- LayoutUtil.setHorizontalGrabbing(fURLField.getTextControl(null));
-
- fBrowseFolder.doFillIntoGrid(topComp, 1);
-
- DialogField.createEmptySpace(topComp, 2);
- fValidateURLButton.doFillIntoGrid(topComp, 1);
-
- //DialogField.createEmptySpace(topComp, 3);
-
- if (!fIsForSource) {
- // Add the second radio button for the jar/zip
- fArchiveRadioButton.doFillIntoGrid(topComp, 3);
-
-
- // external - workspace selection
- DialogField.createEmptySpace(topComp, 1);
- Composite radioComposite= new Composite(topComp, SWT.NONE);
- radioComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
- GridLayout layout= new GridLayout(2, true);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- radioComposite.setLayout(layout);
- fExternalRadio.doFillIntoGrid(radioComposite, 1);
- fWorkspaceRadio.doFillIntoGrid(radioComposite, 1);
- DialogField.createEmptySpace(topComp, 1);
-
- // Add the jar/zip field
- fArchiveField.doFillIntoGrid(topComp, 2);
- LayoutUtil.setWidthHint(fArchiveField.getTextControl(null), converter.convertWidthInCharsToPixels(43));
- LayoutUtil.setHorizontalGrabbing(fArchiveField.getTextControl(null));
-
- fBrowseArchive.doFillIntoGrid(topComp, 1);
-
- // Add the path chooser for the jar/zip
- fArchivePathField.doFillIntoGrid(topComp, 2);
- LayoutUtil.setWidthHint(fArchivePathField.getTextControl(null), converter.convertWidthInCharsToPixels(43));
- LayoutUtil.setHorizontalGrabbing(fArchivePathField.getTextControl(null));
-
- fBrowseArchivePath.doFillIntoGrid(topComp, 1);
-
- DialogField.createEmptySpace(topComp, 2);
- fValidateArchiveButton.doFillIntoGrid(topComp, 1);
-
- int indent= converter.convertWidthInCharsToPixels(2);
- LayoutUtil.setHorizontalIndent(fArchiveField.getLabelControl(null), indent);
- LayoutUtil.setHorizontalIndent(fArchivePathField.getLabelControl(null), indent);
- LayoutUtil.setHorizontalIndent(fURLField.getLabelControl(null), indent);
-
- fURLRadioButton.attachDialogFields(new DialogField[] {fURLField, fBrowseFolder, fValidateURLButton });
- fArchiveRadioButton.attachDialogFields(new DialogField[] {fArchiveField, fBrowseArchive, fExternalRadio, fWorkspaceRadio, fArchivePathField, fBrowseArchivePath, fValidateArchiveButton });
- }
-
-
- return topComp;
- }
-
- private void initializeSelections() {
- String initialValue = fInitialURL != null ? fInitialURL.toExternalForm() : ""; //$NON-NLS-1$
-
- if (fIsForSource) {
- fURLField.setText(initialValue);
- return;
- }
- String prefix= JavaDocLocations.ARCHIVE_PREFIX;
- boolean isArchive= initialValue.startsWith(prefix);
-
- boolean isWorkspaceArchive= false;
-
- fURLRadioButton.setSelection(!isArchive);
- fArchiveRadioButton.setSelection(isArchive);
-
- if (isArchive) {
- String jarPathStr;
- String insidePath= ""; //$NON-NLS-1$
- int excIndex= initialValue.indexOf("!/"); //$NON-NLS-1$
- if (excIndex == -1) {
- jarPathStr= initialValue.substring(prefix.length());
- } else {
- jarPathStr= initialValue.substring(prefix.length(), excIndex);
- insidePath= initialValue.substring(excIndex + 2);
- }
-
- final String fileProtocol= "file:/"; //$NON-NLS-1$
- final String resourceProtocol= "platform:/resource/"; //$NON-NLS-1$
-
- if (jarPathStr.startsWith(fileProtocol)) {
- jarPathStr= jarPathStr.substring(fileProtocol.length());
- } else if (jarPathStr.startsWith(resourceProtocol)) {
- jarPathStr= jarPathStr.substring(resourceProtocol.length());
- isWorkspaceArchive= true;
- } else {
- fURLField.setText(initialValue);
- return;
- }
- IPath jarPath= new Path(decodeExclamationMarks(jarPathStr));
- fArchivePathField.setText(decodeExclamationMarks(insidePath));
- if (isWorkspaceArchive) {
- fArchiveField.setText(jarPath.makeRelative().toString());
- } else {
- fArchiveField.setText(jarPath.makeAbsolute().toOSString());
- }
- } else {
- fURLField.setText(initialValue);
- }
- fExternalRadio.setSelection(!isWorkspaceArchive);
- fWorkspaceRadio.setSelection(isWorkspaceArchive);
-
- }
-
- public void setFocus() {
- fURLField.postSetFocusOnDialogField(fShell.getDisplay());
- }
-
- public void performDefaults() {
- initializeSelections();
- }
-
- public URL getJavadocLocation() {
- if (fIsForSource || fURLRadioButton.isSelected()) {
- return fURLResult;
- }
- return fArchiveURLResult;
- }
-
- private class EntryValidator implements Runnable {
-
- private String fInvalidMessage= PreferencesMessages.JavadocConfigurationBlock_InvalidLocation_message;
- private String fValidMessage= PreferencesMessages.JavadocConfigurationBlock_ValidLocation_message;
- private String fTitle= PreferencesMessages.JavadocConfigurationBlock_MessageDialog_title;
- private String fUnable= PreferencesMessages.JavadocConfigurationBlock_UnableToValidateLocation_message;
- public void run() {
-
- URL location= getJavadocLocation();
- if (location == null) {
- MessageDialog.openWarning(fShell, fTitle, fInvalidMessage);
- return;
- }
-
- try {
- String protocol = location.getProtocol();
- if (protocol.startsWith("http") || protocol.equals("jar")) { //$NON-NLS-1$ //$NON-NLS-2$
- validateURL(location);
- } else if (protocol.equals("file")) { //$NON-NLS-1$
- validateFile(location);
- } else {
- MessageDialog.openWarning(fShell, fTitle, fUnable);
- }
- } catch (MalformedURLException e) {
- MessageDialog.openWarning(fShell, fTitle, fUnable);
- }
-
- }
-
- public void spawnInBrowser(URL url) {
- OpenBrowserUtil.open(url, fShell.getDisplay(), fTitle);
- }
-
- private void validateFile(URL location) throws MalformedURLException {
- File folder = new File(location.getFile());
- if (folder.isDirectory()) {
- File indexFile= new File(folder, "index.html"); //$NON-NLS-1$
- if (indexFile.isFile()) {
- File packageList= new File(folder, "package-list"); //$NON-NLS-1$
- if (packageList.exists()) {
- if (MessageDialog.openConfirm(fShell, fTitle, fValidMessage)) {
- spawnInBrowser(indexFile.toURL());
- }
- return;
- }
- }
- }
- MessageDialog.openWarning(fShell, fTitle, fInvalidMessage);
- }
-
- private void validateURL(URL location) throws MalformedURLException {
- IPath path= new Path(location.toExternalForm());
- IPath index = path.append("index.html"); //$NON-NLS-1$
- IPath packagelist = path.append("package-list"); //$NON-NLS-1$
- URL indexURL = new URL(index.toString());
- URL packagelistURL = new URL(packagelist.toString());
-
- boolean suc= checkURLConnection(indexURL) && checkURLConnection(packagelistURL);
- if (suc) {
- if (MessageDialog.openConfirm(fShell, fTitle, fValidMessage))
- spawnInBrowser(indexURL);
- } else {
- MessageDialog.openWarning(fShell, fTitle, fInvalidMessage);
- }
- }
- }
-
- private boolean checkURLConnection(URL url) {
- int res= 0;
- URLConnection connection= null;
- try {
- connection= url.openConnection();
- if (connection instanceof HttpURLConnection) {
- connection.connect();
- res= ((HttpURLConnection) connection).getResponseCode();
- }
- InputStream is= null;
- try {
- is= connection.getInputStream();
- byte[] buffer= new byte[256];
- while (is.read(buffer) != -1) {
- }
- } finally {
- if (is != null)
- is.close();
- }
- } catch (IllegalArgumentException e) {
- return false; // bug 91072
- } catch (IOException e) {
- return false;
- }
- return res < 400;
- }
-
-
- private class JDocConfigurationAdapter implements IDialogFieldListener {
-
- // ---------- IDialogFieldListener --------
- public void dialogFieldChanged(DialogField field) {
- jdocDialogFieldChanged(field);
- }
- }
-
-
- private void jdocDialogFieldChanged(DialogField field) {
- if (field == fURLField) {
- fURLStatus= updateURLStatus();
- statusChanged();
- } else if (field == fArchiveField) {
- fArchiveStatus= updateArchiveStatus();
- statusChanged();
- } else if (field == fArchivePathField) {
- fArchivePathStatus= updateArchivePathStatus();
- statusChanged();
- } else if (field == fValidateURLButton || field == fValidateArchiveButton) {
- EntryValidator validator= new EntryValidator();
- BusyIndicator.showWhile(fShell.getDisplay(), validator);
- } else if (field == fBrowseFolder) {
- String url= chooseJavaDocFolder();
- if (url != null) {
- fURLField.setText(url);
- }
- } else if (field == fBrowseArchive) {
- String jarPath= chooseArchive();
- if (jarPath != null) {
- fArchiveField.setText(jarPath);
- }
- } else if (field == fExternalRadio || field == fWorkspaceRadio) {
- fArchiveStatus= updateArchiveStatus();
- statusChanged();
- } else if (field == fBrowseArchivePath) {
- String archivePath= chooseArchivePath();
- if (archivePath != null) {
- fArchivePathField.setText(archivePath);
- }
- } else if (field == fURLRadioButton || field == fArchiveRadioButton) {
- statusChanged();
- }
- }
-
- private void statusChanged() {
- IStatus status;
- boolean isURL= fIsForSource || fURLRadioButton.isSelected();
- if (isURL) {
- status= fURLStatus;
- } else {
- status= StatusUtil.getMoreSevere(fArchiveStatus, fArchivePathStatus);
- }
- if (!fIsForSource) {
- boolean canBrowseArchivePath= !isURL && fArchiveStatus.isOK() && fArchiveField.getText().length() > 0;
- if (canBrowseArchivePath && fWorkspaceRadio.isSelected()) {
- IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(fArchiveField.getText()));
- canBrowseArchivePath= resource != null && resource.getLocation() != null;
- }
- fBrowseArchivePath.setEnabled(canBrowseArchivePath);
- }
- fContext.statusChanged(status);
- }
-
-
- private String chooseArchivePath() {
- final String[] res= new String[] { null };
- BusyIndicator.showWhile(fShell.getDisplay(), new Runnable() {
- public void run() {
- res[0]= internalChooseArchivePath();
- }
- });
- return res[0];
- }
-
- private String encodeExclamationMarks(String str) {
- StringBuffer buf= new StringBuffer(str.length());
- for (int i= 0; i < str.length(); i++) {
- char ch= str.charAt(i);
- if (ch == '!') {
- buf.append("%21"); //$NON-NLS-1$
- } else {
- buf.append(ch);
- }
- }
- return buf.toString();
- }
-
- private String decodeExclamationMarks(String str) {
- StringBuffer buf= new StringBuffer(str.length());
- int length= str.length();
- for (int i= 0; i < length; i++) {
- char ch= str.charAt(i);
- if (ch == '%' && (i < length - 2) && str.charAt(i + 1) == '2' && str.charAt(i + 2) == '1') {
- buf.append('!');
- i+= 2;
- } else {
- buf.append(ch);
- }
- }
- return buf.toString();
- }
-
-
-
- private String internalChooseArchivePath() {
- ZipFile zipFile= null;
- try {
- if (fWorkspaceRadio.isSelected()) {
- IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(fArchiveField.getText()));
- if (resource != null) {
- IPath location= resource.getLocation();
- if (location != null) {
- zipFile= new ZipFile(location.toOSString());
- }
- }
- } else {
- zipFile= new ZipFile(fArchiveField.getText());
- }
- if (zipFile == null) {
- return null;
- }
-
- ZipFileStructureProvider provider= new ZipFileStructureProvider(zipFile);
-
- ILabelProvider lp= new ZipDialogLabelProvider(provider);
- ZipDialogContentProvider cp= new ZipDialogContentProvider(provider);
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(fShell, lp, cp);
- dialog.setAllowMultiple(false);
- dialog.setValidator(new ZipDialogValidator());
- dialog.setTitle(PreferencesMessages.JavadocConfigurationBlock_browse_jarorzip_path_title);
- dialog.setMessage(PreferencesMessages.JavadocConfigurationBlock_location_in_jarorzip_message);
- dialog.setComparator(new ViewerComparator());
-
- String init= fArchivePathField.getText();
- if (init.length() == 0) {
- init= "docs/api"; //$NON-NLS-1$
- }
- dialog.setInitialSelection(cp.findElement(new Path(init)));
-
- dialog.setInput(this);
- if (dialog.open() == Window.OK) {
- String name= provider.getFullPath(dialog.getFirstResult());
- return new Path(name).removeTrailingSeparator().toString();
- }
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- } finally {
- if (zipFile != null) {
- try {
- zipFile.close();
- } catch (IOException e1) {
- // ignore
- }
- }
- }
- return null;
- }
-
- private String chooseArchive() {
- if (fWorkspaceRadio.isSelected()) {
- return chooseWorkspaceArchive();
- }
-
- IPath currPath= new Path(fArchiveField.getText());
- if (ArchiveFileFilter.isArchivePath(currPath)) {
- currPath= currPath.removeLastSegments(1);
- }
-
- FileDialog dialog= new FileDialog(fShell, SWT.OPEN);
- dialog.setFilterExtensions(new String[] { FILE_IMPORT_MASK });
- dialog.setText(PreferencesMessages.JavadocConfigurationBlock_zipImportSource_title);
- dialog.setFilterPath(currPath.toOSString());
-
- return dialog.open();
- }
-
- private String chooseWorkspaceArchive() {
- String initSelection= fArchiveField.getText();
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new WorkbenchContentProvider();
- Class[] acceptedClasses= new Class[] { IFile.class };
- TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
-
- IResource initSel= null;
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- if (initSelection.length() > 0) {
- initSel= root.findMember(new Path(initSelection));
- }
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(fShell, lp, cp);
- dialog.addFilter(new ArchiveFileFilter((List) null, true));
- dialog.setAllowMultiple(false);
- dialog.setValidator(validator);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- dialog.setTitle(PreferencesMessages.JavadocConfigurationBlock_workspace_archive_selection_dialog_title);
- dialog.setMessage(PreferencesMessages.JavadocConfigurationBlock_workspace_archive_selection_dialog_description);
- dialog.setInput(root);
- dialog.setInitialSelection(initSel);
- dialog.setHelpAvailable(false);
- if (dialog.open() == Window.OK) {
- IResource res= (IResource) dialog.getFirstResult();
- return res.getFullPath().makeRelative().toString();
- }
- return null;
- }
-
- /**
- * Display an error dialog with the specified message.
- *
- * @param message the error message
- */
- protected void displayErrorDialog(String message) {
- MessageDialog.openError(fShell, ERROR_DIALOG_TITLE, message);
- }
-
- private String chooseJavaDocFolder() {
- String initPath= ""; //$NON-NLS-1$
- if (fURLResult != null && "file".equals(fURLResult.getProtocol())) { //$NON-NLS-1$
- initPath= (new File(fURLResult.getFile())).getPath();
- }
- DirectoryDialog dialog= new DirectoryDialog(fShell);
- dialog.setText(PreferencesMessages.JavadocConfigurationBlock_javadocFolderDialog_label);
- dialog.setMessage(PreferencesMessages.JavadocConfigurationBlock_javadocFolderDialog_message);
- dialog.setFilterPath(initPath);
- String result= dialog.open();
- if (result != null) {
- try {
- URL url= new File(result).toURL();
- return url.toExternalForm();
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return null;
- }
-
- private IStatus updateURLStatus() {
- StatusInfo status= new StatusInfo();
- fURLResult= null;
- try {
- String jdocLocation= fURLField.getText();
- if (jdocLocation.length() == 0) {
- return status;
- }
- URL url= new URL(jdocLocation);
- if ("file".equals(url.getProtocol())) { //$NON-NLS-1$
- if (url.getFile() == null) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_notafolder);
- return status;
- }
- }
- fURLResult= url;
- } catch (MalformedURLException e) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_MalformedURL_error);
- return status;
- }
-
- return status;
- }
-
- private IStatus updateArchiveStatus() {
- try {
- fArchiveURLResult= null;
-
- StatusInfo status= new StatusInfo();
- String jdocLocation= fArchiveField.getText();
- if (jdocLocation.length() > 0) {
- if (!Path.ROOT.isValidPath(jdocLocation)) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_invalidarchivepath);
- return status;
- }
- if (fWorkspaceRadio.isSelected()) {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IResource res= root.findMember(new Path(jdocLocation));
- if (res != null) {
- if (!(res instanceof IFile)) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_archive_not_found_in_workspace);
- return status;
- }
- } else {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_archive_not_found_in_workspace);
- return status;
- }
- } else {
- IPath path= Path.fromOSString(jdocLocation);
- if (!path.isAbsolute()) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_archivepathnotabsolute);
- return status;
- }
- File jarFile= new File(jdocLocation);
- if (jarFile.isDirectory()) {
- status.setError(PreferencesMessages.JavadocConfigurationBlock_error_notafile);
- return status;
- }
- if (!jarFile.exists()) {
- status.setWarning(PreferencesMessages.JavadocConfigurationBlock_error_notafile);
- }
- }
- fArchiveURLResult= getArchiveURL();
- }
- return status;
- } catch (MalformedURLException e) {
- StatusInfo status= new StatusInfo();
- status.setError(e.getMessage());
- return status;
- }
- }
-
- private IStatus updateArchivePathStatus() {
- // no validation yet
- try {
- fArchiveURLResult= getArchiveURL();
- } catch (MalformedURLException e) {
- fArchiveURLResult= null;
- StatusInfo status= new StatusInfo();
- status.setError(e.getMessage());
- //status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.MalformedURL.error")); //$NON-NLS-1$
- return status;
- }
- return new StatusInfo();
-
- }
-
-
- private URL getArchiveURL() throws MalformedURLException {
- String jarLoc= fArchiveField.getText();
- String innerPath= fArchivePathField.getText().trim();
-
- StringBuffer buf= new StringBuffer();
- buf.append("jar:"); //$NON-NLS-1$
-
- if (fWorkspaceRadio.isSelected()) {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IResource res= root.findMember(new Path(jarLoc));
- if (res != null) {
- buf.append("platform:/resource").append(encodeExclamationMarks(res.getFullPath().toString())); //$NON-NLS-1$
- }
- } else {
- buf.append(encodeExclamationMarks(new File(jarLoc).toURL().toExternalForm()));
- }
- buf.append('!');
- if (innerPath.length() > 0) {
- if (innerPath.charAt(0) != '/') {
- buf.append('/');
- }
- buf.append(innerPath);
- } else {
- buf.append('/');
- }
- return new URL(buf.toString());
- }
-
-
- /**
- * An adapter for presenting a zip file in a tree viewer.
- */
- private static class ZipDialogContentProvider implements ITreeContentProvider {
-
- private ZipFileStructureProvider fProvider;
-
- public ZipDialogContentProvider(ZipFileStructureProvider provider) {
- fProvider= provider;
- }
-
- public Object findElement(IPath path) {
- String[] segments= path.segments();
-
- Object elem= fProvider.getRoot();
- for (int i= 0; i < segments.length && elem != null; i++) {
- List list= fProvider.getChildren(elem);
- String name= segments[i];
- elem= null;
- for (int k= 0; k < list.size(); k++) {
- Object curr= list.get(k);
- if (fProvider.isFolder(curr) && name.equals(fProvider.getLabel(curr))) {
- elem= curr;
- break;
- }
- }
- }
- return elem;
- }
-
- private Object recursiveFind(Object element, String name) {
- if (name.equals(fProvider.getLabel(element))) {
- return element;
- }
- List list= fProvider.getChildren(element);
- if (list != null) {
- for (int k= 0; k < list.size(); k++) {
- Object res= recursiveFind(list.get(k), name);
- if (res != null) {
- return res;
- }
- }
- }
- return null;
- }
-
- public Object findFileByName(String name) {
- return recursiveFind(fProvider.getRoot(), name);
- }
-
- /* non java-doc
- * @see ITreeContentProvider#inputChanged
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- /* non java-doc
- * @see ITreeContentProvider#getParent
- */
- public Object getParent(Object element) {
- if (element.equals(fProvider.getRoot())) {
- return null;
- }
- IPath path= new Path(fProvider.getFullPath(element));
- if (path.segmentCount() > 0) {
- return findElement(path.removeLastSegments(1));
- }
- return fProvider.getRoot();
- }
-
- /* non java-doc
- * @see ITreeContentProvider#hasChildren
- */
- public boolean hasChildren(Object element) {
- List list= fProvider.getChildren(element);
- if (list != null) {
- for (int i= 0; i < list.size(); i++) {
- if (fProvider.isFolder(list.get(i))) {
- return true;
- }
- }
- }
- return false;
- }
-
- /* non java-doc
- * @see ITreeContentProvider#getChildren
- */
- public Object[] getChildren(Object element) {
- List list= fProvider.getChildren(element);
- ArrayList res= new ArrayList();
- if (list != null) {
- for (int i= 0; i < list.size(); i++) {
- Object curr= list.get(i);
- if (fProvider.isFolder(curr)) {
- res.add(curr);
- }
- }
- }
- return res.toArray();
- }
-
- /* non java-doc
- * @see ITreeContentProvider#getElements
- */
- public Object[] getElements(Object element) {
- return new Object[] {fProvider.getRoot() };
- }
-
- /* non java-doc
- * @see IContentProvider#dispose
- */
- public void dispose() {
- }
- }
-
- private static class ZipDialogLabelProvider extends LabelProvider {
-
- private final Image IMG_JAR=
- JavaScriptUI.getSharedImages().getImage(org.eclipse.wst.jsdt.ui.ISharedImages.IMG_OBJS_JAR);
- private final Image IMG_FOLDER=
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
-
- private ZipFileStructureProvider fProvider;
-
- public ZipDialogLabelProvider(ZipFileStructureProvider provider) {
- fProvider= provider;
- }
-
- public Image getImage(Object element) {
- if (element == fProvider.getRoot()) {
- return IMG_JAR;
- } else {
- return IMG_FOLDER;
- }
- }
-
- public String getText(Object element) {
- if (element == fProvider.getRoot()) {
- return fProvider.getZipFile().getName();
- }
- return fProvider.getLabel(element);
- }
- }
-
- private static class ZipDialogValidator implements ISelectionStatusValidator {
- public ZipDialogValidator() {
- super();
- }
-
- /*
- * @see ISelectionValidator#validate(Object[])
- */
- public IStatus validate(Object[] selection) {
- String message= ""; //$NON-NLS-1$
- return new StatusInfo(IStatus.INFO, message);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java
deleted file mode 100644
index 60f315e8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ArchiveFileFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathSupport;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Property page used to set the project's Javadoc location for sources
- */
-public class JavadocConfigurationPropertyPage extends PropertyPage implements IStatusChangeListener {
-
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.JavadocConfigurationPropertyPage"; //$NON-NLS-1$
-
- private JavadocConfigurationBlock fJavadocConfigurationBlock;
- private boolean fIsValidElement;
-
- private IPath fContainerPath;
- private IIncludePathEntry fEntry;
- private URL fInitalLocation;
-
- public JavadocConfigurationPropertyPage() {
- }
-
- /**
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IJavaScriptElement elem= getJavaElement();
- try {
- if (elem instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) elem).getKind() == IPackageFragmentRoot.K_BINARY) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) elem;
-
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null) {
- fIsValidElement= false;
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsIncorrectElement_description);
- } else {
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- fContainerPath= entry.getPath();
- fEntry= handleContainerEntry(fContainerPath, elem.getJavaScriptProject(), root.getPath());
- fIsValidElement= fEntry != null;
- } else {
- fContainerPath= null;
- fEntry= entry;
- fIsValidElement= true;
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description);
- }
- }
-
- } else if (elem instanceof IJavaScriptProject) {
- fIsValidElement= true;
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsJavaProject_description);
- } else {
- fIsValidElement= false;
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsIncorrectElement_description);
- }
- } catch (JavaScriptModelException e) {
- fIsValidElement= false;
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsIncorrectElement_description);
- }
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVADOC_CONFIGURATION_PROPERTY_PAGE);
- }
-
- private IIncludePathEntry handleContainerEntry(IPath containerPath, IJavaScriptProject jproject, IPath jarPath) throws JavaScriptModelException {
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- if (initializer == null || container == null) {
- setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_invalid_container, containerPath.toString()));
- return null;
- }
- String containerName= container.getDescription();
- IStatus status= initializer.getAttributeStatus(containerPath, jproject, IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME);
- if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
- setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_not_supported, containerName));
- return null;
- }
- if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_READ_ONLY) {
- setDescription(Messages.format(PreferencesMessages.JavadocConfigurationPropertyPage_read_only, containerName));
- return null;
- }
- IIncludePathEntry entry= JavaModelUtil.findEntryInContainer(container, jarPath);
- Assert.isNotNull(entry);
- setDescription(PreferencesMessages.JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description);
- return entry;
- }
-
- /*
- * @see PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- if (!fIsValidElement) {
- return new Composite(parent, SWT.NONE);
- }
-
- IJavaScriptElement elem= getJavaElement();
- fInitalLocation= null;
- if (elem != null) {
- try {
- fInitalLocation= JavaScriptUI.getJSdocBaseLocation(elem);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- boolean isProject= (elem instanceof IJavaScriptProject);
- fJavadocConfigurationBlock= new JavadocConfigurationBlock(getShell(), this, fInitalLocation, isProject);
- Control control= fJavadocConfigurationBlock.createContents(parent);
- control.setVisible(elem != null);
-
- Dialog.applyDialogFont(control);
- return control;
- }
-
- private IJavaScriptElement getJavaElement() {
- IAdaptable adaptable= getElement();
- IJavaScriptElement elem= (IJavaScriptElement) adaptable.getAdapter(IJavaScriptElement.class);
- if (elem == null) {
-
- IResource resource= (IResource) adaptable.getAdapter(IResource.class);
- //special case when the .jar is a file
- try {
- if (resource instanceof IFile && ArchiveFileFilter.isArchivePath(resource.getFullPath())) {
- IProject proj= resource.getProject();
- if (proj.hasNature(JavaScriptCore.NATURE_ID)) {
- IJavaScriptProject jproject= JavaScriptCore.create(proj);
- elem= jproject.getPackageFragmentRoot(resource); // create a handle
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return elem;
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- if (fJavadocConfigurationBlock != null) {
- fJavadocConfigurationBlock.performDefaults();
- }
- super.performDefaults();
- }
-
- /**
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fJavadocConfigurationBlock != null) {
- URL javadocLocation= fJavadocConfigurationBlock.getJavadocLocation();
- if (javadocLocation == null && fInitalLocation == null || javadocLocation != null && javadocLocation.equals(fInitalLocation)) {
- return true; // no change
- }
-
-
- IJavaScriptElement elem= getJavaElement();
- try {
- IRunnableWithProgress runnable= getRunnable(getShell(), elem, javadocLocation, fEntry, fContainerPath);
- PlatformUI.getWorkbench().getProgressService().run(true, true, runnable);
- } catch (InvocationTargetException e) {
- String title= PreferencesMessages.SourceAttachmentPropertyPage_error_title;
- String message= PreferencesMessages.SourceAttachmentPropertyPage_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- return false;
- } catch (InterruptedException e) {
- // cancelled
- return false;
- }
- }
- return true;
- }
-
-
- private static IRunnableWithProgress getRunnable(final Shell shell, final IJavaScriptElement elem, final URL javadocLocation, final IIncludePathEntry entry, final IPath containerPath) {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- IJavaScriptProject project= elem.getJavaScriptProject();
- if (elem instanceof IPackageFragmentRoot) {
- CPListElement cpElem= CPListElement.createFromExisting(entry, project);
- String loc= javadocLocation != null ? javadocLocation.toExternalForm() : null;
- cpElem.setAttribute(CPListElement.JAVADOC, loc);
- IIncludePathEntry newEntry= cpElem.getClasspathEntry();
- String[] changedAttributes= { CPListElement.JAVADOC };
- BuildPathSupport.modifyClasspathEntry(shell, newEntry, changedAttributes, project, containerPath, monitor);
- } else {
- JavaScriptUI.setProjectJSdocLocation(project, javadocLocation);
- }
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- }
-
-
- /**
- * @see IStatusChangeListener#statusChanged(IStatus)
- */
- public void statusChanged(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java
deleted file mode 100644
index f5fce56b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java
+++ /dev/null
@@ -1,266 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-
-/**
- */
-public class JavadocProblemsConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final Key PREF_JAVADOC_SUPPORT= getJDTCoreKey(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT);
-
- private static final Key PREF_PB_INVALID_JAVADOC= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC);
- private static final Key PREF_PB_INVALID_JAVADOC_TAGS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC_TAGS);
- private static final Key PREF_PB_INVALID_JAVADOC_TAGS_NOT_VISIBLE_REF= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC_TAGS__NOT_VISIBLE_REF);
- private static final Key PREF_PB_INVALID_JAVADOC_TAGS_DEPRECATED_REF= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC_TAGS__DEPRECATED_REF);
- private static final Key PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY);
-
- private static final Key PREF_PB_MISSING_JAVADOC_TAGS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_TAGS);
- private static final Key PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY);
- private static final Key PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING);
-
- private static final Key PREF_PB_MISSING_JAVADOC_COMMENTS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS);
- private static final Key PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY);
- private static final Key PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING);
-
-
- // values
- private static final String ERROR= JavaScriptCore.ERROR;
- private static final String WARNING= JavaScriptCore.WARNING;
- private static final String IGNORE= JavaScriptCore.IGNORE;
-
- private static final String ENABLED= JavaScriptCore.ENABLED;
- private static final String DISABLED= JavaScriptCore.DISABLED;
-
- private static final String PUBLIC= JavaScriptCore.PUBLIC;
- private static final String PROTECTED= JavaScriptCore.PROTECTED;
- private static final String DEFAULT= JavaScriptCore.DEFAULT;
- private static final String PRIVATE= JavaScriptCore.PRIVATE;
-
- private PixelConverter fPixelConverter;
- private Composite fJavadocComposite;
-
- private ControlEnableState fBlockEnableState;
-
-
- public JavadocProblemsConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getKeys(), container);
- fBlockEnableState= null;
- }
-
- private static Key[] getKeys() {
- Key[] keys= new Key[] {
- PREF_JAVADOC_SUPPORT,
- PREF_PB_INVALID_JAVADOC, PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, PREF_PB_INVALID_JAVADOC_TAGS,
- PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY,
- PREF_PB_INVALID_JAVADOC_TAGS_NOT_VISIBLE_REF, PREF_PB_INVALID_JAVADOC_TAGS_DEPRECATED_REF,
- PREF_PB_MISSING_JAVADOC_TAGS, PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING,
- PREF_PB_MISSING_JAVADOC_COMMENTS, PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING,
- };
- return keys;
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- fPixelConverter= new PixelConverter(parent);
- setShell(parent.getShell());
-
- Composite javadocComposite= createJavadocTabContent(parent);
-
- validateSettings(null, null, null);
-
- return javadocComposite;
- }
-
-
- private Composite createJavadocTabContent(Composite folder) {
- String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
-
- String[] errorWarningIgnoreLabels= new String[] {
- PreferencesMessages.JavadocProblemsConfigurationBlock_error,
- PreferencesMessages.JavadocProblemsConfigurationBlock_warning,
- PreferencesMessages.JavadocProblemsConfigurationBlock_ignore
- };
-
- String[] enabledDisabled= new String[] { ENABLED, DISABLED };
-
- String[] visibilities= new String[] { PUBLIC, PROTECTED, DEFAULT, PRIVATE };
-
- String[] visibilitiesLabels= new String[] {
- PreferencesMessages.JavadocProblemsConfigurationBlock_public,
- PreferencesMessages.JavadocProblemsConfigurationBlock_protected,
- PreferencesMessages.JavadocProblemsConfigurationBlock_default,
- PreferencesMessages.JavadocProblemsConfigurationBlock_private
- };
- int nColumns= 3;
-
-
- final ScrolledPageContent sc1 = new ScrolledPageContent(folder);
-
- Composite outer= sc1.getBody();
-
- GridLayout layout = new GridLayout();
- layout.numColumns= nColumns;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- outer.setLayout(layout);
-
- String label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_javadoc_support_label;
- addCheckBox(outer, label, PREF_JAVADOC_SUPPORT, enabledDisabled, 0);
-
- layout = new GridLayout();
- layout.numColumns= nColumns;
- layout.marginHeight= 0;
- //layout.marginWidth= 0;
-
- Composite composite= new Composite(outer, SWT.NONE);
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, true));
-
- fJavadocComposite= composite;
-
- Label description= new Label(composite, SWT.WRAP);
- description.setText(PreferencesMessages.JavadocProblemsConfigurationBlock_javadoc_description);
- GridData gd= new GridData();
- gd.horizontalSpan= nColumns;
- //gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
- description.setLayoutData(gd);
-
- int indent= fPixelConverter.convertWidthInCharsToPixels(2);
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_invalid_javadoc_label;
- addComboBox(composite, label, PREF_PB_INVALID_JAVADOC, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_visibility_label;
- addComboBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, visibilities, visibilitiesLabels, indent);
-
- label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_label;
- addCheckBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS, enabledDisabled, indent);
-
- label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_not_visible_ref_label;
- addCheckBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS_NOT_VISIBLE_REF, enabledDisabled, indent);
-
- label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_deprecated_label;
- addCheckBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS_DEPRECATED_REF, enabledDisabled, indent);
-
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= nColumns;
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_javadoc_label;
- addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_visibility_label;
- addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, visibilities, visibilitiesLabels, indent);
-
- label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_overriding_label;
- addCheckBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING, enabledDisabled, indent);
-
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= nColumns;
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_comments_label;
- addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
- label = PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_comments_visibility_label;
- addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, visibilities, visibilitiesLabels, indent);
-
- label= PreferencesMessages.JavadocProblemsConfigurationBlock_pb_missing_comments_overriding_label;
- addCheckBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING, enabledDisabled, indent);
-
- return sc1;
- }
-
- /* (non-javadoc)
- * Update fields and validate.
- * @param changedKey Key that changed, or null, if all changed.
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (!areSettingsEnabled()) {
- return;
- }
-
- if (changedKey != null) {
- if (PREF_PB_INVALID_JAVADOC.equals(changedKey) ||
- PREF_PB_MISSING_JAVADOC_TAGS.equals(changedKey) ||
- PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) ||
- PREF_JAVADOC_SUPPORT.equals(changedKey)) {
- updateEnableStates();
- } else {
- return;
- }
- } else {
- updateEnableStates();
- }
- fContext.statusChanged(new StatusInfo());
- }
-
- private void updateEnableStates() {
- boolean enableJavadoc= checkValue(PREF_JAVADOC_SUPPORT, ENABLED);
- enableConfigControls(enableJavadoc);
-
- if (enableJavadoc) {
- boolean enableInvalidTagsErrors= !checkValue(PREF_PB_INVALID_JAVADOC, IGNORE);
- getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS).setEnabled(enableInvalidTagsErrors);
- getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS_NOT_VISIBLE_REF).setEnabled(enableInvalidTagsErrors);
- getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS_DEPRECATED_REF).setEnabled(enableInvalidTagsErrors);
- setComboEnabled(PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, enableInvalidTagsErrors);
-
- boolean enableMissingTagsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_TAGS, IGNORE);
- getCheckBox(PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING).setEnabled(enableMissingTagsErrors);
- setComboEnabled(PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, enableMissingTagsErrors);
-
- boolean enableMissingCommentsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_COMMENTS, IGNORE);
- getCheckBox(PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING).setEnabled(enableMissingCommentsErrors);
- setComboEnabled(PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, enableMissingCommentsErrors);
- }
- }
-
- protected void enableConfigControls(boolean enable) {
- if (enable) {
- if (fBlockEnableState != null) {
- fBlockEnableState.restore();
- fBlockEnableState= null;
- }
- } else {
- if (fBlockEnableState == null) {
- fBlockEnableState= ControlEnableState.disable(fJavadocComposite);
- }
- }
- }
-
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- String title= PreferencesMessages.JavadocProblemsConfigurationBlock_needsbuild_title;
- String message;
- if (workspaceSettings) {
- message= PreferencesMessages.JavadocProblemsConfigurationBlock_needsfullbuild_message;
- } else {
- message= PreferencesMessages.JavadocProblemsConfigurationBlock_needsprojectbuild_message;
- }
- return new String[] { title, message };
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsPreferencePage.java
deleted file mode 100644
index 70f51833..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsPreferencePage.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Page used to configure both workspace and project specific compiler settings
- */
-public class JavadocProblemsPreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.JavadocProblemsPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.JavadocProblemsPreferencePage"; //$NON-NLS-1$
-
- private JavadocProblemsConfigurationBlock fConfigurationBlock;
-
- public JavadocProblemsPreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.getString("JavadocProblemsPreferencePage.description")); //$NON-NLS-1$
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.JavadocProblemsPreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new JavadocProblemsConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- if (isProjectPreferencePage()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVADOC_PROBLEMS_PROPERTY_PAGE);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVADOC_PROBLEMS_PREFERENCE_PAGE);
- }
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java
deleted file mode 100644
index 46fb9947..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Configures Java Editor hover preferences.
- *
- *
- */
-class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock {
-
- private OverlayPreferenceStore fStore;
-
-
- private Map fCheckBoxes= new HashMap();
- private SelectionListener fCheckBoxListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- public void widgetSelected(SelectionEvent e) {
- Button button= (Button) e.widget;
- fStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
- }
- };
-
- /**
- * List of master/slave listeners when there's a dependency.
- *
- * @see #createDependency(Button, String, Control)
- *
- */
- private ArrayList fMasterSlaveListeners= new ArrayList();
-
- private StatusInfo fStatus;
-
- public MarkOccurrencesConfigurationBlock(OverlayPreferenceStore store) {
- Assert.isNotNull(store);
- fStore= store;
-
- fStore.addKeys(createOverlayStoreKeys());
- }
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- ArrayList overlayKeys= new ArrayList();
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STICKY_OCCURRENCES));
-
- OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
- overlayKeys.toArray(keys);
- return keys;
- }
-
- /**
- * Creates page for mark occurrences preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(final Composite parent) {
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- Link link= new Link(composite, SWT.NONE);
- link.setText(PreferencesMessages.MarkOccurrencesConfigurationBlock_link);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(parent.getShell(), e.text, null, null);
- }
- });
- // TODO replace by link-specific tooltips when
- // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88866 gets fixed
- link.setToolTipText(PreferencesMessages.MarkOccurrencesConfigurationBlock_link_tooltip);
-
- addFiller(composite);
-
- String label;
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markOccurrences;
- Button master= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0);
-
- addFiller(composite);
-
-// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markTypeOccurrences;
-// Button slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, 0);
-// createDependency(master, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, slave);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodOccurrences;
- Button slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, 0);
- createDependency(master, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, slave);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markConstantOccurrences;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, 0);
- createDependency(master, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, slave);
-
-// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markFieldOccurrences;
-// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, 0);
-// createDependency(master, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, slave);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, 0);
- createDependency(master, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, slave);
-
-// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markExceptionOccurrences;
-// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, 0);
-// createDependency(master, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, slave);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodExitPoints;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, 0);
- createDependency(master, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, slave);
-
-// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markImplementors;
-// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, 0);
-// createDependency(master, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, slave);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markBreakContinueTargets;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS, 0);
- createDependency(master, PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS, slave);
-
- addFiller(composite);
-
- label= PreferencesMessages.MarkOccurrencesConfigurationBlock_stickyOccurrences;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0);
- createDependency(master, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, slave);
-
- return composite;
- }
-
- private void addFiller(Composite composite) {
- PixelConverter pixelConverter= new PixelConverter(composite);
-
- Label filler= new Label(composite, SWT.LEFT );
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 2;
- filler.setLayoutData(gd);
- }
-
- private Button addCheckBox(Composite parent, String label, String key, int indentation) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(label);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indentation;
- gd.horizontalSpan= 2;
- checkBox.setLayoutData(gd);
- checkBox.addSelectionListener(fCheckBoxListener);
-
- fCheckBoxes.put(checkBox, key);
-
- return checkBox;
- }
-
- private void createDependency(final Button master, String masterKey, final Control slave) {
- indent(slave);
- boolean masterState= fStore.getBoolean(masterKey);
- slave.setEnabled(masterState);
- SelectionListener listener= new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- slave.setEnabled(master.getSelection());
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {}
- };
- master.addSelectionListener(listener);
- fMasterSlaveListeners.add(listener);
- }
-
- private static void indent(Control control) {
- GridData gridData= new GridData();
- gridData.horizontalIndent= 10;
- control.setLayoutData(gridData);
- }
-
- public void initialize() {
- initializeFields();
- }
-
- void initializeFields() {
-
- Iterator iter= fCheckBoxes.keySet().iterator();
- while (iter.hasNext()) {
- Button b= (Button) iter.next();
- String key= (String) fCheckBoxes.get(b);
- b.setSelection(fStore.getBoolean(key));
- }
-
- // Update slaves
- iter= fMasterSlaveListeners.iterator();
- while (iter.hasNext()) {
- SelectionListener listener= (SelectionListener)iter.next();
- listener.widgetSelected(null);
- }
-
- }
-
- public void performOk() {
- }
-
- public void performDefaults() {
- restoreFromPreferences();
- initializeFields();
- }
-
- private void restoreFromPreferences() {
-
- }
-
- IStatus getStatus() {
- if (fStatus == null)
- fStatus= new StatusInfo();
- return fStatus;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#dispose()
- *
- */
- public void dispose() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java
deleted file mode 100644
index 14c8c198..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * The page for setting the editor options.
- */
-public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.MarkOccurrencesConfigurationBlock_title;
- setDescription(description);
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null; // no description for new look.
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new MarkOccurrencesConfigurationBlock(overlayPreferenceStore);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferenceCache.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferenceCache.java
deleted file mode 100644
index 0538484b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferenceCache.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.StringTokenizer;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- */
-public class MembersOrderPreferenceCache implements IPropertyChangeListener {
-
- public static final int TYPE_INDEX= 0;
- public static final int CONSTRUCTORS_INDEX= 1;
- public static final int METHOD_INDEX= 2;
- public static final int FIELDS_INDEX= 3;
- public static final int INIT_INDEX= 4;
- public static final int STATIC_FIELDS_INDEX= 5;
- public static final int STATIC_INIT_INDEX= 6;
- public static final int STATIC_METHODS_INDEX= 7;
- public static final int ENUM_CONSTANTS_INDEX= 8;
- public static final int N_CATEGORIES= ENUM_CONSTANTS_INDEX + 1;
-
- private static final int PUBLIC_INDEX= 0;
- private static final int PRIVATE_INDEX= 1;
- private static final int PROTECTED_INDEX= 2;
- private static final int DEFAULT_INDEX= 3;
- private static final int N_VISIBILITIES= DEFAULT_INDEX + 1;
-
- private int[] fCategoryOffsets= null;
-
- private boolean fSortByVisibility;
- private int[] fVisibilityOffsets= null;
-
- private IPreferenceStore fPreferenceStore;
-
- public MembersOrderPreferenceCache() {
- fPreferenceStore= null;
- fCategoryOffsets= null;
- fSortByVisibility= false;
- fVisibilityOffsets= null;
- }
-
- public void install(IPreferenceStore store) {
- fPreferenceStore= store;
- store.addPropertyChangeListener(this);
- fSortByVisibility= store.getBoolean(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER);
- }
-
- public void dispose() {
- fPreferenceStore.removePropertyChangeListener(this);
- fPreferenceStore= null;
- }
-
- public static boolean isMemberOrderProperty(String property) {
- return PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(property)
- || PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER.equals(property)
- || PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER.equals(property);
- }
-
- public void propertyChange(PropertyChangeEvent event) {
- String property= event.getProperty();
-
- if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(property)) {
- fCategoryOffsets= null;
- } else if (PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER.equals(property)) {
- fVisibilityOffsets= null;
- } else if (PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER.equals(property)) {
- fSortByVisibility= fPreferenceStore.getBoolean(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER);
- }
- }
-
- public int getCategoryIndex(int kind) {
- if (fCategoryOffsets == null) {
- fCategoryOffsets= getCategoryOffsets();
- }
- return fCategoryOffsets[kind];
- }
-
- private int[] getCategoryOffsets() {
- int[] offsets= new int[N_CATEGORIES];
- IPreferenceStore store= fPreferenceStore;
- String key= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
- boolean success= fillCategoryOffsetsFromPreferenceString(store.getString(key), offsets);
- if (!success) {
- store.setToDefault(key);
- fillCategoryOffsetsFromPreferenceString(store.getDefaultString(key), offsets);
- }
- return offsets;
- }
-
- private boolean fillCategoryOffsetsFromPreferenceString(String str, int[] offsets) {
- StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$
- int i= 0;
- offsets[ENUM_CONSTANTS_INDEX]= i++; // enum constants always on top
-
- while (tokenizer.hasMoreTokens()) {
- String token= tokenizer.nextToken().trim();
- if ("T".equals(token)) { //$NON-NLS-1$
- offsets[TYPE_INDEX]= i++;
- } else if ("M".equals(token)) { //$NON-NLS-1$
- offsets[METHOD_INDEX]= i++;
- } else if ("F".equals(token)) { //$NON-NLS-1$
- offsets[FIELDS_INDEX]= i++;
- } else if ("I".equals(token)) { //$NON-NLS-1$
- offsets[INIT_INDEX]= i++;
- } else if ("SF".equals(token)) { //$NON-NLS-1$
- offsets[STATIC_FIELDS_INDEX]= i++;
- } else if ("SI".equals(token)) { //$NON-NLS-1$
- offsets[STATIC_INIT_INDEX]= i++;
- } else if ("SM".equals(token)) { //$NON-NLS-1$
- offsets[STATIC_METHODS_INDEX]= i++;
- } else if ("C".equals(token)) { //$NON-NLS-1$
- offsets[CONSTRUCTORS_INDEX]= i++;
- }
- }
- return i == N_CATEGORIES;
- }
-
- public boolean isSortByVisibility() {
- return fSortByVisibility;
- }
-
- public int getVisibilityIndex(int modifierFlags) {
- if (fVisibilityOffsets == null) {
- fVisibilityOffsets= getVisibilityOffsets();
- }
- int kind= DEFAULT_INDEX;
- if (Flags.isPublic(modifierFlags)) {
- kind= PUBLIC_INDEX;
- } else if (Flags.isPrivate(modifierFlags)) {
- kind= PRIVATE_INDEX;
- }
-
- return fVisibilityOffsets[kind];
- }
-
- private int[] getVisibilityOffsets() {
- int[] offsets= new int[N_VISIBILITIES];
- IPreferenceStore store= fPreferenceStore;
- String key= PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER;
- boolean success= fillVisibilityOffsetsFromPreferenceString(store.getString(key), offsets);
- if (!success) {
- store.setToDefault(key);
- fillVisibilityOffsetsFromPreferenceString(store.getDefaultString(key), offsets);
- }
- return offsets;
- }
-
- private boolean fillVisibilityOffsetsFromPreferenceString(String str, int[] offsets) {
- StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$
- int i= 0;
- while (tokenizer.hasMoreTokens()) {
- String token= tokenizer.nextToken().trim();
- if ("B".equals(token)) { //$NON-NLS-1$
- offsets[PUBLIC_INDEX]= i++;
- } else if ("V".equals(token)) { //$NON-NLS-1$
- offsets[PRIVATE_INDEX]= i++;
- } else if ("R".equals(token)) { //$NON-NLS-1$
- offsets[PROTECTED_INDEX]= i++;
- } else if ("D".equals(token)) { //$NON-NLS-1$
- offsets[DEFAULT_INDEX]= i++;
- }
- }
- return i == N_VISIBILITIES;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferencePage.java
deleted file mode 100644
index cc7d46cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MembersOrderPreferencePage.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*******************************************************************************
- * All rights reserved. This program and the accompanying materials
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.MembersOrderPreferencePage"; //$NON-NLS-1$
-
-// private static final String ALL_SORTMEMBER_ENTRIES= "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$
- private static final String ALL_SORTMEMBER_ENTRIES= "T,I,F,C,M"; //$NON-NLS-1$
- private static final String ALL_VISIBILITY_ENTRIES= "B,V,R,D"; //$NON-NLS-1$
- private static final String PREF_OUTLINE_SORT_OPTION= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
- private static final String PREF_VISIBILITY_SORT_OPTION= PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER;
- private static final String PREF_USE_VISIBILITY_SORT_OPTION= PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER;
-
- public static final String CONSTRUCTORS= "C"; //$NON-NLS-1$
-// public static final String FIELDS= "F"; //$NON-NLS-1$
- public static final String VARS= "F"; //$NON-NLS-1$
- public static final String METHODS= "M"; //$NON-NLS-1$
-// public static final String STATIC_METHODS= "SM"; //$NON-NLS-1$
-// public static final String STATIC_FIELDS= "SF"; //$NON-NLS-1$
- public static final String INIT= "I"; //$NON-NLS-1$
-// public static final String STATIC_INIT= "SI"; //$NON-NLS-1$
- public static final String TYPES= "T"; //$NON-NLS-1$
-
- public static final String PUBLIC= "B"; //$NON-NLS-1$
- public static final String PRIVATE= "V"; //$NON-NLS-1$
- public static final String PROTECTED= "R"; //$NON-NLS-1$
- public static final String DEFAULT= "D"; //$NON-NLS-1$
-
- private boolean fUseVisibilitySort;
- private ListDialogField fSortOrderList;
- private ListDialogField fVisibilityOrderList;
- private SelectionButtonDialogField fUseVisibilitySortField;
-
- private static boolean isValidEntries(List entries, String entryString) {
- StringTokenizer tokenizer= new StringTokenizer(entryString, ","); //$NON-NLS-1$
- int i= 0;
- for (; tokenizer.hasMoreTokens(); i++) {
- String token= tokenizer.nextToken();
- if (!entries.contains(token))
- return false;
- }
- return i == entries.size();
- }
-
- public MembersOrderPreferencePage() {
- //set the preference store
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
-
- setDescription(PreferencesMessages.MembersOrderPreferencePage_label_description);
-
-// String memberSortString= getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION);
- String memberSortString = ALL_SORTMEMBER_ENTRIES;
-
- String upLabel= PreferencesMessages.MembersOrderPreferencePage_category_button_up;
- String downLabel= PreferencesMessages.MembersOrderPreferencePage_category_button_down;
-
- // category sort
-
- fSortOrderList= new ListDialogField(null, new String[] { upLabel, downLabel }, new MemberSortLabelProvider());
- fSortOrderList.setDownButtonIndex(1);
- fSortOrderList.setUpButtonIndex(0);
-
- //validate entries stored in store, false get defaults
- List entries= parseList(memberSortString);
- if (!isValidEntries(entries, ALL_SORTMEMBER_ENTRIES)) {
- memberSortString= getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
- entries= parseList(memberSortString);
- }
-
- fSortOrderList.setElements(entries);
-
- // visibility sort
-
- fUseVisibilitySort= getPreferenceStore().getBoolean(PREF_USE_VISIBILITY_SORT_OPTION);
-
- String visibilitySortString= getPreferenceStore().getString(PREF_VISIBILITY_SORT_OPTION);
-
- upLabel= PreferencesMessages.MembersOrderPreferencePage_visibility_button_up;
- downLabel= PreferencesMessages.MembersOrderPreferencePage_visibility_button_down;
-
- fVisibilityOrderList= new ListDialogField(null, new String[] { upLabel, downLabel }, new VisibilitySortLabelProvider());
- fVisibilityOrderList.setDownButtonIndex(1);
- fVisibilityOrderList.setUpButtonIndex(0);
-
- //validate entries stored in store, false get defaults
- entries= parseList(visibilitySortString);
- if (!isValidEntries(entries, ALL_VISIBILITY_ENTRIES)) {
- visibilitySortString= getPreferenceStore().getDefaultString(PREF_VISIBILITY_SORT_OPTION);
- entries= parseList(visibilitySortString);
- }
- fVisibilityOrderList.setElements(entries);
- }
-
- private static List parseList(String string) {
- StringTokenizer tokenizer= new StringTokenizer(string, ","); //$NON-NLS-1$
- List entries= new ArrayList();
- for (int i= 0; tokenizer.hasMoreTokens(); i++) {
- String token= tokenizer.nextToken();
- entries.add(token);
- }
- return entries;
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE);
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- // Create both the dialog lists
- Composite sortComposite= new Composite(parent, SWT.NONE);
- sortComposite.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- sortComposite.setLayout(layout);
-
- GridData gd= new GridData();
- gd.verticalAlignment= GridData.FILL;
- gd.horizontalAlignment= GridData.FILL_HORIZONTAL;
- sortComposite.setLayoutData(gd);
-
- createListDialogField(sortComposite, fSortOrderList);
-
- fUseVisibilitySortField= new SelectionButtonDialogField(SWT.CHECK);
- fUseVisibilitySortField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- fVisibilityOrderList.setEnabled(fUseVisibilitySortField.isSelected());
- }
- });
- fUseVisibilitySortField.setLabelText(PreferencesMessages.MembersOrderPreferencePage_usevisibilitysort_label);
- fUseVisibilitySortField.doFillIntoGrid(sortComposite, 2);
- fUseVisibilitySortField.setSelection(fUseVisibilitySort);
-
- createListDialogField(sortComposite, fVisibilityOrderList);
- fVisibilityOrderList.setEnabled(fUseVisibilitySortField.isSelected());
-
- Dialog.applyDialogFont(sortComposite);
-
- // XXX: workaround until implemented
- fUseVisibilitySortField.setEnabled(false);
- fVisibilityOrderList.setEnabled(false);
-
- return sortComposite;
- }
-
-
- private void createListDialogField(Composite composite, ListDialogField dialogField) {
- Control list= dialogField.getListControl(composite);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= true;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
- gd.widthHint= convertWidthInCharsToPixels(50);
-
- list.setLayoutData(gd);
-
- Composite buttons= dialogField.getButtonBox(composite);
- gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
-
- buttons.setLayoutData(gd);
- }
-
- /*
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore prefs= JavaScriptPlugin.getDefault().getPreferenceStore();
- String str= prefs.getDefaultString(PREF_OUTLINE_SORT_OPTION);
- if (str != null)
- fSortOrderList.setElements(parseList(str));
- else
- fSortOrderList.setElements(parseList(ALL_SORTMEMBER_ENTRIES));
-
- str= prefs.getDefaultString(PREF_VISIBILITY_SORT_OPTION);
- if (str != null)
- fVisibilityOrderList.setElements(parseList(str));
- else
- fVisibilityOrderList.setElements(parseList(ALL_VISIBILITY_ENTRIES));
-
- fUseVisibilitySortField.setSelection(prefs.getDefaultBoolean(PREF_USE_VISIBILITY_SORT_OPTION));
-
- super.performDefaults();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- //reorders elements in the Outline based on selection
- public boolean performOk() {
-
- //save preferences for both dialog lists
- IPreferenceStore store= getPreferenceStore();
- updateList(store, fSortOrderList, PREF_OUTLINE_SORT_OPTION);
- updateList(store, fVisibilityOrderList, PREF_VISIBILITY_SORT_OPTION);
-
- //update the button setting
- store.setValue(PREF_USE_VISIBILITY_SORT_OPTION, fUseVisibilitySortField.isSelected());
- JavaScriptPlugin.getDefault().savePluginPreferences();
-
- return true;
- }
-
- private void updateList(IPreferenceStore store, ListDialogField list, String str) {
- StringBuffer buf= new StringBuffer();
- List curr= list.getElements();
- for (Iterator iter= curr.iterator(); iter.hasNext();) {
- String s= (String) iter.next();
- buf.append(s);
- buf.append(',');
- }
- store.setValue(str, buf.toString());
- }
-
- private class MemberSortLabelProvider extends LabelProvider {
-
- public MemberSortLabelProvider() {
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- //access to image registry
- ImageDescriptorRegistry registry= JavaScriptPlugin.getImageDescriptorRegistry();
- ImageDescriptor descriptor= null;
-
- if (element instanceof String) {
- int visibility= Flags.AccPublic;
- String s= (String) element;
-// if (s.equals(FIELDS)) {
- if (s.equals(VARS)) {
- //0 will give the default field image
- descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility);
- } else if (s.equals(CONSTRUCTORS)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
- //add a constructor adornment to the image descriptor
- descriptor= new JavaScriptElementImageDescriptor(descriptor, JavaScriptElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
- } else if (s.equals(METHODS)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
-// } else if (s.equals(STATIC_FIELDS)) {
-// descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility);
- //add a static fields adornment to the image descriptor
-// descriptor= new JavaScriptElementImageDescriptor(descriptor, JavaScriptElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
-// } else if (s.equals(STATIC_METHODS)) {
-// descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
- //add a static methods adornment to the image descriptor
-// descriptor= new JavaScriptElementImageDescriptor(descriptor, JavaScriptElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
- } else if (s.equals(INIT)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
-// } else if (s.equals(STATIC_INIT)) {
-// descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
-// descriptor= new JavaScriptElementImageDescriptor(descriptor, JavaScriptElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
- } else if (s.equals(TYPES)) {
- descriptor= JavaElementImageProvider.getTypeImageDescriptor(true, false, Flags.AccPublic, false);
- } else {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
- }
- return registry.get(descriptor);
- }
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
-
- if (element instanceof String) {
- String s= (String) element;
-// if (s.equals(FIELDS)) {
- if (s.equals(VARS)) {
-// return PreferencesMessages.MembersOrderPreferencePage_fields_label;
- return PreferencesMessages.MembersOrderPreferencePage_vars_label;
- } else if (s.equals(METHODS)) {
- return PreferencesMessages.MembersOrderPreferencePage_methods_label;
-// } else if (s.equals(STATIC_FIELDS)) {
-// return PreferencesMessages.MembersOrderPreferencePage_staticfields_label;
-// } else if (s.equals(STATIC_METHODS)) {
-// return PreferencesMessages.MembersOrderPreferencePage_staticmethods_label;
- } else if (s.equals(CONSTRUCTORS)) {
- return PreferencesMessages.MembersOrderPreferencePage_constructors_label;
- } else if (s.equals(INIT)) {
- return PreferencesMessages.MembersOrderPreferencePage_initialisers_label;
-// } else if (s.equals(STATIC_INIT)) {
-// return PreferencesMessages.MembersOrderPreferencePage_staticinitialisers_label;
- } else if (s.equals(TYPES)) {
- return PreferencesMessages.MembersOrderPreferencePage_types_label;
- }
- }
- return ""; //$NON-NLS-1$
- }
- }
-
-
- private class VisibilitySortLabelProvider extends LabelProvider {
-
- public VisibilitySortLabelProvider() {
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- //access to image registry
- ImageDescriptorRegistry registry= JavaScriptPlugin.getImageDescriptorRegistry();
- ImageDescriptor descriptor= null;
-
- if (element instanceof String) {
- String s= (String) element;
- if (s.equals(PUBLIC)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
- } else if (s.equals(PROTECTED)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccProtected);
- } else if (s.equals(PRIVATE)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPrivate);
- } else if (s.equals(DEFAULT)) {
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccDefault);
- }
- return registry.get(descriptor);
- }
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- if (element instanceof String) {
- String s= (String) element;
-
- if (s.equals(PUBLIC)) {
- return PreferencesMessages.MembersOrderPreferencePage_public_label;
- } else if (s.equals(PRIVATE)) {
- return PreferencesMessages.MembersOrderPreferencePage_private_label;
- } else if (s.equals(PROTECTED)) {
- return PreferencesMessages.MembersOrderPreferencePage_protected_label;
- } else if (s.equals(DEFAULT)) {
- return PreferencesMessages.MembersOrderPreferencePage_default_label;
- }
- }
- return ""; //$NON-NLS-1$
- }
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java
deleted file mode 100644
index 7c95f882..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-
-/**
- * Mockup preference store, for registering listeners and firing events,
- * without being an actual store.
- * <p>
- * All methods except firing, adding and removing listeners throw
- * an {@link java.lang.UnsupportedOperationException}.
- * </p>
- *
- *
- */
-public class MockupPreferenceStore implements IPreferenceStore {
-
- /** Listeners on this store */
- private ListenerList fListeners= new ListenerList(ListenerList.IDENTITY);
-
- /**
- * {@inheritDoc}
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.add(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.remove(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
- firePropertyChangeEvent(this, name, oldValue, newValue);
- }
-
- /**
- * Fires a property change event with the given source, property name, old and new value. Used
- * when the event source should be different from this mockup preference store.
- * @param source The event source
- * @param name The property name
- * @param oldValue The property's old value
- * @param newValue The property's new value
- */
- public void firePropertyChangeEvent(Object source, String name, Object oldValue, Object newValue) {
- PropertyChangeEvent event= new PropertyChangeEvent(source, name, oldValue, newValue);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++)
- ((IPropertyChangeListener) listeners[i]).propertyChange(event);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getBoolean(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getDefaultBoolean(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDefaultDouble(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public float getDefaultFloat(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public int getDefaultInt(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public long getDefaultLong(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultString(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDouble(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public float getFloat(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInt(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public long getLong(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getString(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isDefault(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsSaving() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void putValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, String defaultObject) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setToDefault(String name) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, double value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, float value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, int value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, long value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, String value) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, boolean value) {
- throw new UnsupportedOperationException();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NameConventionConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NameConventionConfigurationBlock.java
deleted file mode 100644
index a2ccf839..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NameConventionConfigurationBlock.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/*
- * The page to configure name conventions
- */
-public class NameConventionConfigurationBlock extends OptionsConfigurationBlock {
-
- private final static int FIELD= 1;
- private final static int STATIC= 2;
- private final static int ARGUMENT= 3;
- private final static int LOCAL= 4;
-
- // Preference store keys
- private static final Key PREF_FIELD_PREFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_FIELD_PREFIXES);
- private static final Key PREF_FIELD_SUFFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_FIELD_SUFFIXES);
- private static final Key PREF_STATIC_FIELD_PREFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_STATIC_FIELD_PREFIXES);
- private static final Key PREF_STATIC_FIELD_SUFFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_STATIC_FIELD_SUFFIXES);
- private static final Key PREF_ARGUMENT_PREFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_ARGUMENT_PREFIXES);
- private static final Key PREF_ARGUMENT_SUFFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_ARGUMENT_SUFFIXES);
- private static final Key PREF_LOCAL_PREFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_LOCAL_PREFIXES);
- private static final Key PREF_LOCAL_SUFFIXES= getJDTCoreKey(JavaScriptCore.CODEASSIST_LOCAL_SUFFIXES);
-
- private static final Key PREF_KEYWORD_THIS= getJDTUIKey(PreferenceConstants.CODEGEN_KEYWORD_THIS);
- private static final Key PREF_IS_FOR_GETTERS= getJDTUIKey(PreferenceConstants.CODEGEN_IS_FOR_GETTERS);
- private static final Key PREF_EXCEPTION_NAME= getJDTUIKey(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME);
-
- private static final Key PREF_USE_OVERRIDE_ANNOT= getJDTUIKey(PreferenceConstants.CODEGEN_USE_OVERRIDE_ANNOTATION);
- private static final Key PREF_GENERATE_COMMENTS= getJDTUIKey(PreferenceConstants.CODEGEN_ADD_COMMENTS);
-
- private static class NameConventionEntry {
- public int kind;
- public String prefix;
- public String suffix;
- public Key prefixkey;
- public Key suffixkey;
- }
-
- private class NameConventionInputDialog extends StatusDialog implements IDialogFieldListener {
-
- private StringDialogField fPrefixField;
- private StringDialogField fSuffixField;
- private NameConventionEntry fEntry;
- private DialogField fMessageField;
-
- public NameConventionInputDialog(Shell parent, String title, String message, NameConventionEntry entry) {
- super(parent);
- fEntry= entry;
-
- setTitle(title);
-
- fMessageField= new DialogField();
- fMessageField.setLabelText(message);
-
- fPrefixField= new StringDialogField();
- fPrefixField.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_dialog_prefix);
- fPrefixField.setDialogFieldListener(this);
-
- fSuffixField= new StringDialogField();
- fSuffixField.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_dialog_suffix);
- fSuffixField.setDialogFieldListener(this);
-
- fPrefixField.setText(entry.prefix);
- fSuffixField.setText(entry.suffix);
- }
-
- public NameConventionEntry getResult() {
- NameConventionEntry res= new NameConventionEntry();
- res.prefix= Strings.removeTrailingCharacters(fPrefixField.getText(), ',');
- res.suffix= Strings.removeTrailingCharacters(fSuffixField.getText(), ',');
- res.prefixkey= fEntry.prefixkey;
- res.suffixkey= fEntry.suffixkey;
- res.kind= fEntry.kind;
- return res;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(composite.getFont());
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
-
- fMessageField.doFillIntoGrid(inner, 2);
- fPrefixField.doFillIntoGrid(inner, 2);
- fSuffixField.doFillIntoGrid(inner, 2);
-
- LayoutUtil.setHorizontalGrabbing(fPrefixField.getTextControl(null));
- LayoutUtil.setWidthHint(fPrefixField.getTextControl(null), convertWidthInCharsToPixels(45));
- LayoutUtil.setWidthHint(fSuffixField.getTextControl(null), convertWidthInCharsToPixels(45));
-
- fPrefixField.postSetFocusOnDialogField(parent.getDisplay());
-
- applyDialogFont(composite);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.CODE_STYLE_EDIT_PREFIX_SUFFIX);
-
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- // validate
- IStatus prefixStatus= validateIdentifiers(getTokens(fPrefixField.getText(), ","), true); //$NON-NLS-1$
- IStatus suffixStatus= validateIdentifiers(getTokens(fSuffixField.getText(), ","), false); //$NON-NLS-1$
-
- updateStatus(StatusUtil.getMoreSevere(suffixStatus, prefixStatus));
- }
-
- private IStatus validateIdentifiers(String[] values, boolean prefix) {
- for (int i= 0; i < values.length; i++) {
- String val= values[i];
- if (val.length() == 0) {
- if (prefix) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.NameConventionConfigurationBlock_error_emptyprefix);
- } else {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.NameConventionConfigurationBlock_error_emptysuffix);
- }
- }
- String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$
- IStatus status= JavaScriptConventions.validateFieldName(name);
- if (status.matches(IStatus.ERROR)) {
- if (prefix) {
- return new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.NameConventionConfigurationBlock_error_invalidprefix, val));
- } else {
- return new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.NameConventionConfigurationBlock_error_invalidsuffix, val));
- }
- }
- }
- return new StatusInfo();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- //PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG);
- }
- }
-
- private static class NameConventionLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- return getColumnImage(element, 0);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- return getColumnText(element, 0);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex != 0) {
- return null;
- }
-
- NameConventionEntry entry= (NameConventionEntry) element;
- ImageDescriptorRegistry registry= JavaScriptPlugin.getImageDescriptorRegistry();
- switch (entry.kind) {
- case FIELD:
- return registry.get(JavaPluginImages.DESC_FIELD_PUBLIC);
- case STATIC:
- return registry.get(new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_FIELD_PUBLIC, JavaScriptElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE));
- case ARGUMENT:
- return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE);
- default:
- return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE);
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- NameConventionEntry entry= (NameConventionEntry) element;
- if (columnIndex == 0) {
- switch (entry.kind) {
- case FIELD:
- return PreferencesMessages.NameConventionConfigurationBlock_field_label;
- case STATIC:
- return PreferencesMessages.NameConventionConfigurationBlock_static_label;
- case ARGUMENT:
- return PreferencesMessages.NameConventionConfigurationBlock_arg_label;
- default:
- return PreferencesMessages.NameConventionConfigurationBlock_local_label;
- }
- } else if (columnIndex == 1) {
- return entry.prefix;
- } else {
- return entry.suffix;
- }
- }
- }
-
- private class NameConventionAdapter implements IListAdapter, IDialogFieldListener {
-
- private boolean canEdit(ListDialogField field) {
- return field.getSelectedElements().size() == 1;
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doEditButtonPressed();
- }
-
- public void selectionChanged(ListDialogField field) {
- field.enableButton(0, canEdit(field));
- }
-
- public void doubleClicked(ListDialogField field) {
- if (canEdit(field)) {
- doEditButtonPressed();
- }
- }
-
- public void dialogFieldChanged(DialogField field) {
- updateModel(field);
- }
- }
-
- private ListDialogField fNameConventionList;
-// private SelectionButtonDialogField fUseKeywordThisBox;
- private SelectionButtonDialogField fUseIsForBooleanGettersBox;
-
- private StringDialogField fExceptionName;
-// Commented out next 1 line (STP 20070430)
-// private SelectionButtonDialogField fUseOverrideAnnotation;
- private SelectionButtonDialogField fGenerateComments;
-
-
- public NameConventionConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getAllKeys(), container);
-
- NameConventionAdapter adapter= new NameConventionAdapter();
- String[] buttons= new String[] {
- PreferencesMessages.NameConventionConfigurationBlock_list_edit_button
- };
- fNameConventionList= new ListDialogField(adapter, buttons, new NameConventionLabelProvider());
- fNameConventionList.setDialogFieldListener(adapter);
- fNameConventionList.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_list_label);
-
- String[] columnsHeaders= new String[] {
- PreferencesMessages.NameConventionConfigurationBlock_list_name_column,
- PreferencesMessages.NameConventionConfigurationBlock_list_prefix_column,
- PreferencesMessages.NameConventionConfigurationBlock_list_suffix_column,
- };
- ColumnLayoutData[] data= new ColumnLayoutData[] {
- new ColumnWeightData(3),
- new ColumnWeightData(2),
- new ColumnWeightData(2)
- };
-
- fNameConventionList.setTableColumns(new ListDialogField.ColumnsDescription(data, columnsHeaders, true));
-
- if (fNameConventionList.getSize() > 0) {
- fNameConventionList.selectFirstElement();
- } else {
- fNameConventionList.enableButton(0, false);
- }
-
- fExceptionName= new StringDialogField();
- fExceptionName.setDialogFieldListener(adapter);
- fExceptionName.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_exceptionname_label);
-
-// fUseKeywordThisBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP);
-// fUseKeywordThisBox.setDialogFieldListener(adapter);
-// fUseKeywordThisBox.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_keywordthis_label);
-
- fUseIsForBooleanGettersBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP);
- fUseIsForBooleanGettersBox.setDialogFieldListener(adapter);
- fUseIsForBooleanGettersBox.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_isforbooleangetters_label);
-
-// Commented out next 3 lines (STP 20070430)
-// fUseOverrideAnnotation= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP);
-// fUseOverrideAnnotation.setDialogFieldListener(adapter);
-// fUseOverrideAnnotation.setLabelText(PreferencesMessages.NameConventionConfigurationBlock_use_override_annotation_label);
-
- fGenerateComments= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP);
- fGenerateComments.setDialogFieldListener(adapter);
- fGenerateComments.setLabelText(PreferencesMessages.CodeTemplateBlock_createcomment_label);
-
- updateControls();
- }
-
- private static Key[] getAllKeys() {
- return new Key[] {
- PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES,
- PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES,
- PREF_EXCEPTION_NAME, PREF_KEYWORD_THIS, PREF_IS_FOR_GETTERS, PREF_USE_OVERRIDE_ANNOT, PREF_GENERATE_COMMENTS
- };
- }
-
- protected Control createContents(Composite parent) {
- setShell(parent.getShell());
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 3;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- composite.setLayout(layout);
-
- fNameConventionList.doFillIntoGrid(composite, 4);
- LayoutUtil.setHorizontalSpan(fNameConventionList.getLabelControl(null), 2);
- Table table= fNameConventionList.getTableViewer().getTable();
- GridData data= (GridData)fNameConventionList.getListControl(null).getLayoutData();
- data.heightHint= SWTUtil.getTableHeightHint(table, 5);
- data.grabExcessHorizontalSpace= true;
- data.verticalAlignment= GridData.BEGINNING;
- data.grabExcessVerticalSpace= false;
-
- data= (GridData)fNameConventionList.getButtonBox(null).getLayoutData();
- data.grabExcessVerticalSpace= false;
- data.verticalAlignment= GridData.BEGINNING;
-
-// fUseKeywordThisBox.doFillIntoGrid(composite, 3);
- fUseIsForBooleanGettersBox.doFillIntoGrid(composite, 3);
- DialogField.createEmptySpace(composite, 3);
-
- fGenerateComments.doFillIntoGrid(composite, 3);
-// Commented out next 1 line (STP 20070430)
-// fUseOverrideAnnotation.doFillIntoGrid(composite, 3);
- DialogField.createEmptySpace(composite, 3);
-
- fExceptionName.doFillIntoGrid(composite, 2);
-
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String)
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- // no validation here
- }
-
- protected final void updateModel(DialogField field) {
- if (field == fNameConventionList) {
- for (int i= 0; i < fNameConventionList.getSize(); i++) {
- NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getElement(i);
- setValue(entry.suffixkey, entry.suffix);
- setValue(entry.prefixkey, entry.prefix);
- }
- } else if (field == fExceptionName) {
- String name= fExceptionName.getText();
-
- setValue(PREF_EXCEPTION_NAME, name);
-
- // validation
- IStatus status = JavaScriptConventions.validateIdentifier(name);
- if (!status.isOK()) {
- fContext.statusChanged(status);
- } else {
- fContext.statusChanged(new StatusInfo());
- }
-// } else if (field == fUseKeywordThisBox) {
-// setValue(PREF_KEYWORD_THIS, fUseKeywordThisBox.isSelected());
- } else if (field == fUseIsForBooleanGettersBox) {
- setValue(PREF_IS_FOR_GETTERS, fUseIsForBooleanGettersBox.isSelected());
-// Commented out next 2 lines (STP 20070430)
-// } else if (field == fUseOverrideAnnotation) {
-// setValue(PREF_USE_OVERRIDE_ANNOT, fUseOverrideAnnotation.isSelected());
- } else if (field == fGenerateComments) {
- setValue(PREF_GENERATE_COMMENTS, fGenerateComments.isSelected());
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
- */
- protected void updateControls() {
-// Added next 1 line (STP 20070430)
- ArrayList list= new ArrayList(2);
-// Commented out next 3 lines (STP 20070430)
-// ArrayList list= new ArrayList(4);
-// createEntry(list, PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, FIELD);
-// createEntry(list, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, STATIC);
- createEntry(list, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, ARGUMENT);
- createEntry(list, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES, LOCAL);
- fNameConventionList.setElements(list);
-
- fExceptionName.setText(getValue(PREF_EXCEPTION_NAME));
-// fUseKeywordThisBox.setSelection(getBooleanValue(PREF_KEYWORD_THIS));
- fUseIsForBooleanGettersBox.setSelection(getBooleanValue(PREF_IS_FOR_GETTERS));
-// Commented out next 1 line (STP 20070430)
-// fUseOverrideAnnotation.setSelection(getBooleanValue(PREF_USE_OVERRIDE_ANNOT));
- fGenerateComments.setSelection(getBooleanValue(PREF_GENERATE_COMMENTS));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
- */
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- return null; // no build required
- }
-
- private void createEntry(List list, Key prefixKey, Key suffixKey, int kind) {
- NameConventionEntry entry= new NameConventionEntry();
- entry.kind= kind;
- entry.suffixkey= suffixKey;
- entry.prefixkey= prefixKey;
- entry.suffix= getPreferenceValue(suffixKey);
- entry.prefix= getPreferenceValue(prefixKey);
- list.add(entry);
- }
-
- private String getPreferenceValue(Key key) {
- String value= getValue(key);
- if (value == null) {
- value= ""; //$NON-NLS-1$
- JavaScriptPlugin.logErrorMessage("JavaScriptCore preference is null. Key:" + key); //$NON-NLS-1$
- }
- return value;
- }
-
- private void doEditButtonPressed() {
- NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getSelectedElements().get(0);
-
- String title;
- String message;
- switch (entry.kind) {
- case FIELD:
- title= PreferencesMessages.NameConventionConfigurationBlock_field_dialog_title;
- message= PreferencesMessages.NameConventionConfigurationBlock_field_dialog_message;
- break;
- case STATIC:
- title= PreferencesMessages.NameConventionConfigurationBlock_static_dialog_title;
- message= PreferencesMessages.NameConventionConfigurationBlock_static_dialog_message;
- break;
- case ARGUMENT:
- title= PreferencesMessages.NameConventionConfigurationBlock_arg_dialog_title;
- message= PreferencesMessages.NameConventionConfigurationBlock_arg_dialog_message;
- break;
- default:
- title= PreferencesMessages.NameConventionConfigurationBlock_local_dialog_title;
- message= PreferencesMessages.NameConventionConfigurationBlock_local_dialog_message;
- }
-
- NameConventionInputDialog dialog= new NameConventionInputDialog(getShell(), title, message, entry);
- if (dialog.open() == Window.OK) {
- fNameConventionList.replaceElement(entry, dialog.getResult());
- updateModel(fNameConventionList);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NewJavaProjectPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NewJavaProjectPreferencePage.java
deleted file mode 100644
index a82c89e5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/NewJavaProjectPreferencePage.java
+++ /dev/null
@@ -1,519 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-// AW
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.NoSuchElementException;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/*
- * The page for defaults for classpath entries in new java projects.
- * See PreferenceConstants to access or change these values through public API.
- */
-public class NewJavaProjectPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- public static final String ID= "org.eclipse.wst.jsdt.ui.preferences.BuildPathPreferencePage"; //$NON-NLS-1$
-
- private static final String SRCBIN_FOLDERS_IN_NEWPROJ= PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ;
- private static final String SRCBIN_SRCNAME= PreferenceConstants.SRCBIN_SRCNAME;
- private static final String SRCBIN_BINNAME= PreferenceConstants.SRCBIN_BINNAME;
-
- private static final String CLASSPATH_JRELIBRARY_INDEX= PreferenceConstants.NEWPROJECT_JRELIBRARY_INDEX;
- private static final String CLASSPATH_JRELIBRARY_LIST= PreferenceConstants.NEWPROJECT_JRELIBRARY_LIST;
-
-
- private static String fgDefaultEncoding= System.getProperty("file.encoding"); //$NON-NLS-1$
-
- public static IIncludePathEntry[] getDefaultJRELibrary() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- String str= store.getString(CLASSPATH_JRELIBRARY_LIST);
- int index= store.getInt(CLASSPATH_JRELIBRARY_INDEX);
-
- StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
- while (tok.hasMoreTokens() && index > 0) {
- tok.nextToken();
- index--;
- }
-
- if (tok.hasMoreTokens()) {
- IIncludePathEntry[] res= decodeJRELibraryClasspathEntries(tok.nextToken());
- if (res.length > 0) {
- return res;
- }
- }
- return new IIncludePathEntry[] { getJREContainerEntry() };
- }
-
- // JRE Entry
-
- public static String decodeJRELibraryDescription(String encoded) {
- int end= encoded.indexOf(' ');
- if (end != -1) {
- return decode(encoded.substring(0, end));
- }
- return ""; //$NON-NLS-1$
- }
-
- private static String decode(String str) {
- try {
- return URLDecoder.decode(str, fgDefaultEncoding);
- } catch (UnsupportedEncodingException e) {
- JavaScriptPlugin.log(e);
- }
- return ""; //$NON-NLS-1$
- }
-
- private static String encode(String str) {
- try {
- return URLEncoder.encode(str, fgDefaultEncoding);
- } catch (UnsupportedEncodingException e) {
- JavaScriptPlugin.log(e);
- }
- return ""; //$NON-NLS-1$
- }
-
- public static IIncludePathEntry[] decodeJRELibraryClasspathEntries(String encoded) {
- StringTokenizer tok= new StringTokenizer(encoded, " "); //$NON-NLS-1$
- ArrayList res= new ArrayList();
- while (tok.hasMoreTokens()) {
- try {
- tok.nextToken(); // desc: ignore
- int kind= Integer.parseInt(tok.nextToken());
- IPath path= decodePath(tok.nextToken());
- IPath attachPath= decodePath(tok.nextToken());
- IPath attachRoot= decodePath(tok.nextToken());
- boolean isExported= Boolean.valueOf(tok.nextToken()).booleanValue();
- switch (kind) {
- case IIncludePathEntry.CPE_SOURCE:
- res.add(JavaScriptCore.newSourceEntry(path));
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- res.add(JavaScriptCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
- break;
- case IIncludePathEntry.CPE_VARIABLE:
- res.add(JavaScriptCore.newVariableEntry(path, attachPath, attachRoot, isExported));
- break;
- case IIncludePathEntry.CPE_PROJECT:
- res.add(JavaScriptCore.newProjectEntry(path, isExported));
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- res.add(JavaScriptCore.newContainerEntry(path, isExported));
- break;
- }
- } catch (NumberFormatException e) {
- String message= PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message, e));
- } catch (NoSuchElementException e) {
- String message= PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message, e));
- }
- }
- return (IIncludePathEntry[]) res.toArray(new IIncludePathEntry[res.size()]);
- }
-
-
- public static String encodeJRELibrary(String desc, IIncludePathEntry[] cpentries) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < cpentries.length; i++) {
- IIncludePathEntry entry= cpentries[i];
- buf.append(encode(desc));
- buf.append(' ');
- buf.append(entry.getEntryKind());
- buf.append(' ');
- buf.append(encodePath(entry.getPath()));
- buf.append(' ');
- buf.append(encodePath(entry.getSourceAttachmentPath()));
- buf.append(' ');
- buf.append(encodePath(entry.getSourceAttachmentRootPath()));
- buf.append(' ');
- buf.append(entry.isExported());
- buf.append(' ');
- }
- return buf.toString();
- }
-
- private static String encodePath(IPath path) {
- if (path == null) {
- return "#"; //$NON-NLS-1$
- } else if (path.isEmpty()) {
- return "&"; //$NON-NLS-1$
- } else {
- return encode(path.toPortableString());
- }
- }
-
- private static IPath decodePath(String str) {
- if ("#".equals(str)) { //$NON-NLS-1$
- return null;
- } else if ("&".equals(str)) { //$NON-NLS-1$
- return Path.EMPTY;
- } else {
- return Path.fromPortableString(decode(str));
- }
- }
-
-
- private ArrayList fCheckBoxes;
- private ArrayList fRadioButtons;
- private ArrayList fTextControls;
-
- private SelectionListener fSelectionListener;
- private ModifyListener fModifyListener;
-
- //private Text fBinFolderNameText;
- private Text fSrcFolderNameText;
-
- private Combo fJRECombo;
-
- private Button fProjectAsSourceFolder;
- private Button fFoldersAsSourceFolder;
-
- private Label fSrcFolderNameLabel;
- //private Label fBinFolderNameLabel;
-
- public NewJavaProjectPreferencePage() {
- super();
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setDescription(PreferencesMessages.NewJavaProjectPreferencePage_description);
-
- // title used when opened programatically
- setTitle(PreferencesMessages.NewJavaProjectPreferencePage_title);
-
- fRadioButtons= new ArrayList();
- fCheckBoxes= new ArrayList();
- fTextControls= new ArrayList();
-
- fSelectionListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {}
-
- public void widgetSelected(SelectionEvent e) {
- controlChanged(e.widget);
- }
- };
-
- fModifyListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- controlModified(e.widget);
- }
- };
-
- }
-
- public static void initDefaults(IPreferenceStore store) {
- store.setDefault(SRCBIN_FOLDERS_IN_NEWPROJ, false);
- store.setDefault(SRCBIN_SRCNAME, "script"); //$NON-NLS-1$
- store.setDefault(SRCBIN_BINNAME, ""); //$NON-NLS-1$
-
-// store.setDefault(CLASSPATH_JRELIBRARY_LIST, getDefaultJRELibraries());
- store.setDefault(CLASSPATH_JRELIBRARY_INDEX, 0);
- }
-
-// private static String getDefaultJRELibraries() {
-// StringBuffer buf= new StringBuffer();
-// IIncludePathEntry cntentry= getJREContainerEntry();
-// buf.append(encodeJRELibrary(PreferencesMessages.NewJavaProjectPreferencePage_jre_container_description, new IIncludePathEntry[] { cntentry} ));
-// buf.append(';');
-// IIncludePathEntry varentry= getJREVariableEntry();
-// buf.append(encodeJRELibrary(PreferencesMessages.NewJavaProjectPreferencePage_jre_variable_description, new IIncludePathEntry[] { varentry }));
-// buf.append(';');
-// return buf.toString();
-// }
-
- private static IIncludePathEntry getJREContainerEntry() {
- return JavaScriptCore.newContainerEntry(new Path("org.eclipse.wst.jsdt.launching.JRE_CONTAINER")); //$NON-NLS-1$
- }
-
- private static IIncludePathEntry getJREVariableEntry() {
- return JavaScriptCore.newVariableEntry(new Path("JRE_LIB"), new Path("JRE_SRC"), new Path("JRE_SRCROOT")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /*
- * @see IWorkbenchPreferencePage#init(IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /**
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.NEW_JAVA_PROJECT_PREFERENCE_PAGE);
- }
-
-
- private Button addRadioButton(Composite parent, String label, String key, String value, int indent) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- gd.horizontalIndent= indent;
-
- Button button= new Button(parent, SWT.RADIO);
- button.setText(label);
- button.setData(new String[] { key, value });
- button.setLayoutData(gd);
-
- button.setSelection(value.equals(getPreferenceStore().getString(key)));
-
- fRadioButtons.add(button);
- return button;
- }
-
- private Text addTextControl(Composite parent, Label labelControl, String key, int indent) {
- GridData gd= new GridData();
- gd.horizontalIndent= indent;
-
- labelControl.setLayoutData(gd);
-
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint= convertWidthInCharsToPixels(30);
-
- Text text= new Text(parent, SWT.SINGLE | SWT.BORDER);
- text.setText(getPreferenceStore().getString(key));
- text.setData(key);
- text.setLayoutData(gd);
-
- fTextControls.add(text);
- return text;
- }
-
-
- protected Control createContents(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite result= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= 0;
- layout.verticalSpacing= convertVerticalDLUsToPixels(10);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- layout.numColumns= 2;
- result.setLayout(layout);
-
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
-
- Group sourceFolderGroup= new Group(result, SWT.NONE);
- layout= new GridLayout();
- layout.numColumns= 2;
- sourceFolderGroup.setLayout(layout);
- sourceFolderGroup.setLayoutData(gd);
- sourceFolderGroup.setText(PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_label);
-
- int indent= 0;
-
- fProjectAsSourceFolder= addRadioButton(sourceFolderGroup, PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_project, SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.FALSE, indent);
- fProjectAsSourceFolder.addSelectionListener(fSelectionListener);
-
- fFoldersAsSourceFolder= addRadioButton(sourceFolderGroup, PreferencesMessages.NewJavaProjectPreferencePage_sourcefolder_folder, SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.TRUE, indent);
- fFoldersAsSourceFolder.addSelectionListener(fSelectionListener);
-
- indent= convertWidthInCharsToPixels(4);
-
- fSrcFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
- fSrcFolderNameLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_folders_src);
- fSrcFolderNameText= addTextControl(sourceFolderGroup, fSrcFolderNameLabel, SRCBIN_SRCNAME, indent);
- fSrcFolderNameText.addModifyListener(fModifyListener);
-
- //fBinFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
- //fBinFolderNameLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_folders_bin);
- //fBinFolderNameText= addTextControl(sourceFolderGroup, fBinFolderNameLabel, SRCBIN_BINNAME, indent);
- //fBinFolderNameText.addModifyListener(fModifyListener);
-
-// String[] jreNames= getJRENames();
-// if (jreNames.length > 0) {
-// Label jreSelectionLabel= new Label(result, SWT.NONE);
-// jreSelectionLabel.setText(PreferencesMessages.NewJavaProjectPreferencePage_jrelibrary_label);
-// jreSelectionLabel.setLayoutData(new GridData());
-//
-// int index= getPreferenceStore().getInt(CLASSPATH_JRELIBRARY_INDEX);
-// fJRECombo= new Combo(result, SWT.READ_ONLY);
-// fJRECombo.setItems(jreNames);
-// fJRECombo.select(index);
-// fJRECombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-// }
-
- validateFolders();
-
- Dialog.applyDialogFont(result);
- return result;
- }
-
- private void validateFolders() {
- boolean useFolders= fFoldersAsSourceFolder.getSelection();
-
- fSrcFolderNameText.setEnabled(useFolders);
- //fBinFolderNameText.setEnabled(useFolders);
- fSrcFolderNameLabel.setEnabled(useFolders);
- //fBinFolderNameLabel.setEnabled(useFolders);
- if (useFolders) {
- String srcName= fSrcFolderNameText.getText();
- if (srcName.length() == 0) {
- updateStatus(new StatusInfo(IStatus.ERROR, PreferencesMessages.NewJavaProjectPreferencePage_folders_error_namesempty));
- return;
- }
- IWorkspace workspace= JavaScriptPlugin.getWorkspace();
- IProject dmy= workspace.getRoot().getProject("project"); //$NON-NLS-1$
-
- IStatus status;
- IPath srcPath= dmy.getFullPath().append(srcName);
- if (srcName.length() != 0) {
- status= workspace.validatePath(srcPath.toString(), IResource.FOLDER);
- if (!status.isOK()) {
- String message= Messages.format(PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidsrcname, status.getMessage());
- updateStatus(new StatusInfo(IStatus.ERROR, message));
- return;
- }
- }
- IIncludePathEntry entry= JavaScriptCore.newSourceEntry(srcPath);
- status= JavaScriptConventions.validateClasspath(JavaScriptCore.create(dmy), new IIncludePathEntry[] { entry });
- if (!status.isOK()) {
- String message= PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidcp;
- updateStatus(new StatusInfo(IStatus.ERROR, message));
- return;
- }
- }
- updateStatus(new StatusInfo()); // set to OK
- }
-
- private void updateStatus(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
- private void controlChanged(Widget widget) {
- if (widget == fFoldersAsSourceFolder || widget == fProjectAsSourceFolder) {
- validateFolders();
- }
- }
-
- private void controlModified(Widget widget) {
- if (widget == fSrcFolderNameText ) {
- validateFolders();
- }
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- button.setSelection(store.getDefaultBoolean(key));
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- String[] info= (String[]) button.getData();
- button.setSelection(info[1].equals(store.getDefaultString(info[0])));
- }
- for (int i= 0; i < fTextControls.size(); i++) {
- Text text= (Text) fTextControls.get(i);
- String key= (String) text.getData();
- text.setText(store.getDefaultString(key));
- }
- if (fJRECombo != null) {
- fJRECombo.select(store.getDefaultInt(CLASSPATH_JRELIBRARY_INDEX));
- }
-
- validateFolders();
- super.performDefaults();
- }
-
- /*
- * @see IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- store.setValue(key, button.getSelection());
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- if (button.getSelection()) {
- String[] info= (String[]) button.getData();
- store.setValue(info[0], info[1]);
- }
- }
- for (int i= 0; i < fTextControls.size(); i++) {
- Text text= (Text) fTextControls.get(i);
- String key= (String) text.getData();
- store.setValue(key, text.getText());
- }
-
- if (fJRECombo != null) {
- store.setValue(CLASSPATH_JRELIBRARY_INDEX, fJRECombo.getSelectionIndex());
- }
-
- JavaScriptPlugin.getDefault().savePluginPreferences();
- return super.performOk();
- }
-
-// private String[] getJRENames() {
-// String prefString= getPreferenceStore().getString(CLASSPATH_JRELIBRARY_LIST);
-// ArrayList list= new ArrayList();
-// StringTokenizer tok= new StringTokenizer(prefString, ";"); //$NON-NLS-1$
-// while (tok.hasMoreTokens()) {
-// list.add(decodeJRELibraryDescription(tok.nextToken()));
-// }
-// return (String[]) list.toArray(new String[list.size()]);
-// }
-
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OccurrencesPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OccurrencesPreferencePage.java
deleted file mode 100644
index 7059604a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OccurrencesPreferencePage.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-/**
- * Occurrences preference page.
- * <p>
- * Note: Must be public since it is referenced from plugin.xml
- * </p>
- *
- *
- */
-public class OccurrencesPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- // This page has no description
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.wst.jsdt.internal.ui.preferences.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new MarkOccurrencesConfigurationBlock(overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OptionsConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OptionsConfigurationBlock.java
deleted file mode 100644
index 010eee9c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OptionsConfigurationBlock.java
+++ /dev/null
@@ -1,881 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.forms.events.ExpansionAdapter;
-import org.eclipse.ui.forms.events.ExpansionEvent;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.ui.preferences.IWorkingCopyManager;
-import org.eclipse.ui.preferences.WorkingCopyManager;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- * Abstract options configuration block providing a general implementation for setting up
- * an options configuration page.
- *
- *
- */
-public abstract class OptionsConfigurationBlock {
-
- public static final class Key {
-
- private String fQualifier;
- private String fKey;
-
- public Key(String qualifier, String key) {
- fQualifier= qualifier;
- fKey= key;
- }
-
- public String getName() {
- return fKey;
- }
-
- private IEclipsePreferences getNode(IScopeContext context, IWorkingCopyManager manager) {
- IEclipsePreferences node= context.getNode(fQualifier);
- if (manager != null) {
- return manager.getWorkingCopy(node);
- }
- return node;
- }
-
- public String getStoredValue(IScopeContext context, IWorkingCopyManager manager) {
- return getNode(context, manager).get(fKey, null);
- }
-
- public String getStoredValue(IScopeContext[] lookupOrder, boolean ignoreTopScope, IWorkingCopyManager manager) {
- for (int i= ignoreTopScope ? 1 : 0; i < lookupOrder.length; i++) {
- String value= getStoredValue(lookupOrder[i], manager);
- if (value != null) {
- return value;
- }
- }
- return null;
- }
-
- public void setStoredValue(IScopeContext context, String value, IWorkingCopyManager manager) {
- if (value != null) {
- getNode(context, manager).put(fKey, value);
- } else {
- getNode(context, manager).remove(fKey);
- }
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fQualifier + '/' + fKey;
- }
-
- public String getQualifier() {
- return fQualifier;
- }
-
- }
-
-
- protected static class ControlData {
- private Key fKey;
- private String[] fValues;
-
- public ControlData(Key key, String[] values) {
- fKey= key;
- fValues= values;
- }
-
- public Key getKey() {
- return fKey;
- }
-
- public String getValue(boolean selection) {
- int index= selection ? 0 : 1;
- return fValues[index];
- }
-
- public String getValue(int index) {
- return fValues[index];
- }
-
- public int getSelection(String value) {
- if (value != null) {
- for (int i= 0; i < fValues.length; i++) {
- if (value.equals(fValues[i])) {
- return i;
- }
- }
- }
- return fValues.length -1; // assume the last option is the least severe
- }
- }
-
- private static final String REBUILD_COUNT_KEY= "preferences_build_requested"; //$NON-NLS-1$
-
- private static final String SETTINGS_EXPANDED= "expanded"; //$NON-NLS-1$
-
- protected final ArrayList fCheckBoxes;
- protected final ArrayList fComboBoxes;
- protected final ArrayList fTextBoxes;
- protected final HashMap fLabels;
- protected final ArrayList fExpandedComposites;
-
- private SelectionListener fSelectionListener;
- private ModifyListener fTextModifyListener;
-
- protected IStatusChangeListener fContext;
- protected final IProject fProject; // project or null
- protected final Key[] fAllKeys;
-
- private IScopeContext[] fLookupOrder;
-
- private Shell fShell;
-
- private final IWorkingCopyManager fManager;
- private IWorkbenchPreferenceContainer fContainer;
-
- private Map fDisabledProjectSettings; // null when project specific settings are turned off
-
- private int fRebuildCount; /// used to prevent multiple dialogs that ask for a rebuild
-
- public OptionsConfigurationBlock(IStatusChangeListener context, IProject project, Key[] allKeys, IWorkbenchPreferenceContainer container) {
- fContext= context;
- fProject= project;
- fAllKeys= allKeys;
- fContainer= container;
- if (container == null) {
- fManager= new WorkingCopyManager();
- } else {
- fManager= container.getWorkingCopyManager();
- }
-
- if (fProject != null) {
- fLookupOrder= new IScopeContext[] {
- new ProjectScope(fProject),
- new InstanceScope(),
- new DefaultScope()
- };
- } else {
- fLookupOrder= new IScopeContext[] {
- new InstanceScope(),
- new DefaultScope()
- };
- }
-
- testIfOptionsComplete(allKeys);
- if (fProject == null || hasProjectSpecificOptions(fProject)) {
- fDisabledProjectSettings= null;
- } else {
- fDisabledProjectSettings= new IdentityHashMap();
- for (int i= 0; i < allKeys.length; i++) {
- Key curr= allKeys[i];
- fDisabledProjectSettings.put(curr, curr.getStoredValue(fLookupOrder, false, fManager));
- }
- }
-
- settingsUpdated();
-
- fCheckBoxes= new ArrayList();
- fComboBoxes= new ArrayList();
- fTextBoxes= new ArrayList(2);
- fLabels= new HashMap();
- fExpandedComposites= new ArrayList();
-
- fRebuildCount= getRebuildCount();
- }
-
- protected final IWorkbenchPreferenceContainer getPreferenceContainer() {
- return fContainer;
- }
-
- protected static Key getKey(String plugin, String key) {
- return new Key(plugin, key);
- }
-
- protected final static Key getJDTCoreKey(String key) {
- return getKey(JavaScriptCore.PLUGIN_ID, key);
- }
-
- protected final static Key getJDTUIKey(String key) {
- return getKey(JavaScriptUI.ID_PLUGIN, key);
- }
-
-
- private void testIfOptionsComplete(Key[] allKeys) {
- for (int i= 0; i < allKeys.length; i++) {
- if (allKeys[i].getStoredValue(fLookupOrder, false, fManager) == null) {
- JavaScriptPlugin.logErrorMessage("preference option missing: " + allKeys[i] + " (" + this.getClass().getName() +')'); //$NON-NLS-1$//$NON-NLS-2$
- }
- }
- }
-
- private int getRebuildCount() {
- return fManager.getWorkingCopy(new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN)).getInt(REBUILD_COUNT_KEY, 0);
- }
-
- private void incrementRebuildCount() {
- fRebuildCount++;
- fManager.getWorkingCopy(new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN)).putInt(REBUILD_COUNT_KEY, fRebuildCount);
- }
-
-
- protected void settingsUpdated() {
- }
-
-
- public void selectOption(String key, String qualifier) {
- for (int i= 0; i < fAllKeys.length; i++) {
- Key curr= fAllKeys[i];
- if (curr.getName().equals(key) && curr.getQualifier().equals(qualifier)) {
- selectOption(curr);
- }
- }
- }
-
- public void selectOption(Key key) {
- Control control= findControl(key);
- if (control != null) {
- if (!fExpandedComposites.isEmpty()) {
- ExpandableComposite expandable= getParentExpandableComposite(control);
- if (expandable != null) {
- for (int i= 0; i < fExpandedComposites.size(); i++) {
- ExpandableComposite curr= (ExpandableComposite) fExpandedComposites.get(i);
- curr.setExpanded(curr == expandable);
- }
- expandedStateChanged(expandable);
- }
- }
- control.setFocus();
- }
- }
-
-
- public final boolean hasProjectSpecificOptions(IProject project) {
- if (project != null) {
- IScopeContext projectContext= new ProjectScope(project);
- Key[] allKeys= fAllKeys;
- for (int i= 0; i < allKeys.length; i++) {
- if (allKeys[i].getStoredValue(projectContext, fManager) != null) {
- return true;
- }
- }
- }
- return false;
- }
-
- protected Shell getShell() {
- return fShell;
- }
-
- protected void setShell(Shell shell) {
- fShell= shell;
- }
-
- protected abstract Control createContents(Composite parent);
-
- protected Button addCheckBox(Composite parent, String label, Key key, String[] values, int indent) {
- ControlData data= new ControlData(key, values);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 3;
- gd.horizontalIndent= indent;
-
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setFont(JFaceResources.getDialogFont());
- checkBox.setText(label);
- checkBox.setData(data);
- checkBox.setLayoutData(gd);
- checkBox.addSelectionListener(getSelectionListener());
-
- makeScrollableCompositeAware(checkBox);
-
- String currValue= getValue(key);
- checkBox.setSelection(data.getSelection(currValue) == 0);
-
- fCheckBoxes.add(checkBox);
-
- return checkBox;
- }
-
- protected Button addCheckBoxWithLink(Composite parent, String label, Key key, String[] values, int indent, int widthHint, SelectionListener listener) {
- ControlData data= new ControlData(key, values);
-
- GridData gd= new GridData(GridData.FILL, GridData.FILL, true, false);
- gd.horizontalSpan= 3;
- gd.horizontalIndent= indent;
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- composite.setLayout(layout);
- composite.setLayoutData(gd);
-
- Button checkBox= new Button(composite, SWT.CHECK);
- checkBox.setFont(JFaceResources.getDialogFont());
- checkBox.setData(data);
- checkBox.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
- checkBox.addSelectionListener(getSelectionListener());
-
- gd= new GridData(GridData.FILL, GridData.CENTER, true, false);
- gd.widthHint= widthHint;
-
- Link link= new Link(composite, SWT.NONE);
- link.setText(label);
- link.setLayoutData(gd);
- if (listener != null) {
- link.addSelectionListener(listener);
- }
-
- makeScrollableCompositeAware(link);
- makeScrollableCompositeAware(checkBox);
-
- String currValue= getValue(key);
- checkBox.setSelection(data.getSelection(currValue) == 0);
-
- fCheckBoxes.add(checkBox);
-
- return checkBox;
- }
-
- protected Combo addComboBox(Composite parent, String label, Key key, String[] values, String[] valueLabels, int indent) {
- GridData gd= new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1);
- gd.horizontalIndent= indent;
-
- Label labelControl= new Label(parent, SWT.LEFT);
- labelControl.setFont(JFaceResources.getDialogFont());
- labelControl.setText(label);
- labelControl.setLayoutData(gd);
-
- Combo comboBox= newComboControl(parent, key, values, valueLabels);
- comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- fLabels.put(comboBox, labelControl);
-
- return comboBox;
- }
-
- protected Combo addInversedComboBox(Composite parent, String label, Key key, String[] values, String[] valueLabels, int indent) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indent;
- gd.horizontalSpan= 3;
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- composite.setLayout(layout);
- composite.setLayoutData(gd);
-
- Combo comboBox= newComboControl(composite, key, values, valueLabels);
- comboBox.setFont(JFaceResources.getDialogFont());
- comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- Label labelControl= new Label(composite, SWT.LEFT | SWT.WRAP);
- labelControl.setText(label);
- labelControl.setLayoutData(new GridData());
-
- fLabels.put(comboBox, labelControl);
- return comboBox;
- }
-
- protected Combo newComboControl(Composite composite, Key key, String[] values, String[] valueLabels) {
- ControlData data= new ControlData(key, values);
-
- Combo comboBox= new Combo(composite, SWT.READ_ONLY);
- comboBox.setItems(valueLabels);
- comboBox.setData(data);
- comboBox.addSelectionListener(getSelectionListener());
- comboBox.setFont(JFaceResources.getDialogFont());
-
- makeScrollableCompositeAware(comboBox);
-
- String currValue= getValue(key);
- comboBox.select(data.getSelection(currValue));
-
- fComboBoxes.add(comboBox);
- return comboBox;
- }
-
- protected Text addTextField(Composite parent, String label, Key key, int indent, int widthHint) {
- Label labelControl= new Label(parent, SWT.WRAP);
- labelControl.setText(label);
- labelControl.setFont(JFaceResources.getDialogFont());
- labelControl.setLayoutData(new GridData());
-
- Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
- textBox.setData(key);
- textBox.setLayoutData(new GridData());
-
- makeScrollableCompositeAware(textBox);
-
- fLabels.put(textBox, labelControl);
-
- String currValue= getValue(key);
- if (currValue != null) {
- textBox.setText(currValue);
- }
- textBox.addModifyListener(getTextModifyListener());
-
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- if (widthHint != 0) {
- data.widthHint= widthHint;
- }
- data.horizontalIndent= indent;
- data.horizontalSpan= 2;
- textBox.setLayoutData(data);
-
- fTextBoxes.add(textBox);
- return textBox;
- }
-
- protected ScrolledPageContent getParentScrolledComposite(Control control) {
- Control parent= control.getParent();
- while (!(parent instanceof ScrolledPageContent) && parent != null) {
- parent= parent.getParent();
- }
- if (parent instanceof ScrolledPageContent) {
- return (ScrolledPageContent) parent;
- }
- return null;
- }
-
- protected ExpandableComposite getParentExpandableComposite(Control control) {
- Control parent= control.getParent();
- while (!(parent instanceof ExpandableComposite) && parent != null) {
- parent= parent.getParent();
- }
- if (parent instanceof ExpandableComposite) {
- return (ExpandableComposite) parent;
- }
- return null;
- }
-
- private void makeScrollableCompositeAware(Control control) {
- ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(control);
- if (parentScrolledComposite != null) {
- parentScrolledComposite.adaptChild(control);
- }
- }
-
- protected ExpandableComposite createStyleSection(Composite parent, String label, int nColumns) {
- ExpandableComposite excomposite= new ExpandableComposite(parent, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT);
- excomposite.setText(label);
- excomposite.setExpanded(false);
- excomposite.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
- excomposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, nColumns, 1));
- excomposite.addExpansionListener(new ExpansionAdapter() {
- public void expansionStateChanged(ExpansionEvent e) {
- expandedStateChanged((ExpandableComposite) e.getSource());
- }
- });
- fExpandedComposites.add(excomposite);
- makeScrollableCompositeAware(excomposite);
- return excomposite;
- }
-
- protected final void expandedStateChanged(ExpandableComposite expandable) {
- ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(expandable);
- if (parentScrolledComposite != null) {
- parentScrolledComposite.reflow(true);
- }
- }
-
- protected void restoreSectionExpansionStates(IDialogSettings settings) {
- for (int i= 0; i < fExpandedComposites.size(); i++) {
- ExpandableComposite excomposite= (ExpandableComposite) fExpandedComposites.get(i);
- if (settings == null) {
- excomposite.setExpanded(i == 0); // only expand the first node by default
- } else {
- excomposite.setExpanded(settings.getBoolean(SETTINGS_EXPANDED + String.valueOf(i)));
- }
- }
- }
-
- protected void storeSectionExpansionStates(IDialogSettings settings) {
- for (int i= 0; i < fExpandedComposites.size(); i++) {
- ExpandableComposite curr= (ExpandableComposite) fExpandedComposites.get(i);
- settings.put(SETTINGS_EXPANDED + String.valueOf(i), curr.isExpanded());
- }
- }
-
- protected SelectionListener getSelectionListener() {
- if (fSelectionListener == null) {
- fSelectionListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {}
-
- public void widgetSelected(SelectionEvent e) {
- controlChanged(e.widget);
- }
- };
- }
- return fSelectionListener;
- }
-
- protected ModifyListener getTextModifyListener() {
- if (fTextModifyListener == null) {
- fTextModifyListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- textChanged((Text) e.widget);
- }
- };
- }
- return fTextModifyListener;
- }
-
- protected void controlChanged(Widget widget) {
- ControlData data= (ControlData) widget.getData();
- String newValue= null;
- if (widget instanceof Button) {
- newValue= data.getValue(((Button)widget).getSelection());
- } else if (widget instanceof Combo) {
- newValue= data.getValue(((Combo)widget).getSelectionIndex());
- } else {
- return;
- }
- String oldValue= setValue(data.getKey(), newValue);
- validateSettings(data.getKey(), oldValue, newValue);
- }
-
- protected void textChanged(Text textControl) {
- Key key= (Key) textControl.getData();
- String number= textControl.getText();
- String oldValue= setValue(key, number);
- validateSettings(key, oldValue, number);
- }
-
- protected boolean checkValue(Key key, String value) {
- return value.equals(getValue(key));
- }
-
- protected String getValue(Key key) {
- if (fDisabledProjectSettings != null) {
- return (String) fDisabledProjectSettings.get(key);
- }
- return key.getStoredValue(fLookupOrder, false, fManager);
- }
-
-
- protected boolean getBooleanValue(Key key) {
- return Boolean.valueOf(getValue(key)).booleanValue();
- }
-
- protected String setValue(Key key, String value) {
- if (fDisabledProjectSettings != null) {
- return (String) fDisabledProjectSettings.put(key, value);
- }
- String oldValue= getValue(key);
- key.setStoredValue(fLookupOrder[0], value, fManager);
- return oldValue;
- }
-
- protected String setValue(Key key, boolean value) {
- return setValue(key, String.valueOf(value));
- }
-
- /**
- * Returns the value as actually stored in the preference store.
- * @param key
- * @return the value as actually stored in the preference store.
- */
- protected String getStoredValue(Key key) {
- return key.getStoredValue(fLookupOrder, false, fManager);
- }
-
- /* (non-javadoc)
- * Update fields and validate.
- * @param changedKey Key that changed, or null, if all changed.
- */
- protected abstract void validateSettings(Key changedKey, String oldValue, String newValue);
-
-
- protected String[] getTokens(String text, String separator) {
- StringTokenizer tok= new StringTokenizer(text, separator);
- int nTokens= tok.countTokens();
- String[] res= new String[nTokens];
- for (int i= 0; i < res.length; i++) {
- res[i]= tok.nextToken().trim();
- }
- return res;
- }
-
- private boolean getChanges(IScopeContext currContext, List changedSettings) {
- boolean needsBuild= false;
- for (int i= 0; i < fAllKeys.length; i++) {
- Key key= fAllKeys[i];
- String oldVal= key.getStoredValue(currContext, null);
- String val= key.getStoredValue(currContext, fManager);
- if (val == null) {
- if (oldVal != null) {
- changedSettings.add(key);
- needsBuild |= !oldVal.equals(key.getStoredValue(fLookupOrder, true, fManager));
- }
- } else if (!val.equals(oldVal)) {
- changedSettings.add(key);
- needsBuild |= oldVal != null || !val.equals(key.getStoredValue(fLookupOrder, true, fManager));
- }
- }
- return needsBuild;
- }
-
- public void useProjectSpecificSettings(boolean enable) {
- boolean hasProjectSpecificOption= fDisabledProjectSettings == null;
- if (enable != hasProjectSpecificOption && fProject != null) {
- if (enable) {
- for (int i= 0; i < fAllKeys.length; i++) {
- Key curr= fAllKeys[i];
- String val= (String) fDisabledProjectSettings.get(curr);
- curr.setStoredValue(fLookupOrder[0], val, fManager);
- }
- fDisabledProjectSettings= null;
- updateControls();
- validateSettings(null, null, null);
- } else {
- fDisabledProjectSettings= new IdentityHashMap();
- for (int i= 0; i < fAllKeys.length; i++) {
- Key curr= fAllKeys[i];
- String oldSetting= curr.getStoredValue(fLookupOrder, false, fManager);
- fDisabledProjectSettings.put(curr, oldSetting);
- curr.setStoredValue(fLookupOrder[0], null, fManager); // clear project settings
- }
- }
- }
- }
-
- public boolean areSettingsEnabled() {
- return fDisabledProjectSettings == null || fProject == null;
- }
-
-
- public boolean performOk() {
- return processChanges(fContainer);
- }
-
- public boolean performApply() {
- return processChanges(null); // apply directly
- }
-
- protected boolean processChanges(IWorkbenchPreferenceContainer container) {
- IScopeContext currContext= fLookupOrder[0];
-
- List /* <Key>*/ changedOptions= new ArrayList();
- boolean needsBuild= getChanges(currContext, changedOptions);
- if (changedOptions.isEmpty()) {
- return true;
- }
- if (needsBuild) {
- int count= getRebuildCount();
- if (count > fRebuildCount) {
- needsBuild= false; // build already requested
- fRebuildCount= count;
- }
- }
-
- boolean doBuild= false;
- if (needsBuild) {
- String[] strings= getFullBuildDialogStrings(fProject == null);
- if (strings != null) {
- MessageDialog dialog= new MessageDialog(getShell(), strings[0], null, strings[1], MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
- int res= dialog.open();
- if (res == 0) {
- doBuild= true;
- } else if (res != 1) {
- return false; // cancel pressed
- }
- }
- }
- if (container != null) {
- // no need to apply the changes to the original store: will be done by the page container
- if (doBuild) { // post build
- incrementRebuildCount();
- container.registerUpdateJob(CoreUtility.getBuildJob(fProject));
- }
- } else {
- // apply changes right away
- try {
- fManager.applyChanges();
- } catch (BackingStoreException e) {
- JavaScriptPlugin.log(e);
- return false;
- }
- if (doBuild) {
- CoreUtility.getBuildJob(fProject).schedule();
- }
-
- }
- return true;
- }
-
- protected abstract String[] getFullBuildDialogStrings(boolean workspaceSettings);
-
-
- public void performDefaults() {
- for (int i= 0; i < fAllKeys.length; i++) {
- Key curr= fAllKeys[i];
- String defValue= curr.getStoredValue(fLookupOrder, true, fManager);
- setValue(curr, defValue);
- }
-
- settingsUpdated();
- updateControls();
- validateSettings(null, null, null);
- }
-
- /**
- *
- */
- public void performRevert() {
- for (int i= 0; i < fAllKeys.length; i++) {
- Key curr= fAllKeys[i];
- String origValue= curr.getStoredValue(fLookupOrder, false, null);
- setValue(curr, origValue);
- }
-
- settingsUpdated();
- updateControls();
- validateSettings(null, null, null);
- }
-
- public void dispose() {
- }
-
- protected void updateControls() {
- // update the UI
- for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
- updateCheckBox((Button) fCheckBoxes.get(i));
- }
- for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
- updateCombo((Combo) fComboBoxes.get(i));
- }
- for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
- updateText((Text) fTextBoxes.get(i));
- }
- }
-
- protected void updateCombo(Combo curr) {
- ControlData data= (ControlData) curr.getData();
-
- String currValue= getValue(data.getKey());
- curr.select(data.getSelection(currValue));
- }
-
- protected void updateCheckBox(Button curr) {
- ControlData data= (ControlData) curr.getData();
-
- String currValue= getValue(data.getKey());
- curr.setSelection(data.getSelection(currValue) == 0);
- }
-
- protected void updateText(Text curr) {
- Key key= (Key) curr.getData();
-
- String currValue= getValue(key);
- if (currValue != null) {
- curr.setText(currValue);
- }
- }
-
- protected Button getCheckBox(Key key) {
- for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
- Button curr= (Button) fCheckBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- return null;
- }
-
- protected Combo getComboBox(Key key) {
- for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
- Combo curr= (Combo) fComboBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- return null;
- }
-
- protected Text getTextControl(Key key) {
- for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
- Text curr= (Text) fTextBoxes.get(i);
- ControlData data= (ControlData) curr.getData();
- if (key.equals(data.getKey())) {
- return curr;
- }
- }
- return null;
- }
-
- protected Control findControl(Key key) {
- Combo comboBox= getComboBox(key);
- if (comboBox != null) {
- return comboBox;
- }
- Button checkBox= getCheckBox(key);
- if (checkBox != null) {
- return checkBox;
- }
- Text text= getTextControl(key);
- if (text != null) {
- return text;
- }
- return null;
- }
-
- protected void setComboEnabled(Key key, boolean enabled) {
- Combo combo= getComboBox(key);
- Label label= (Label) fLabels.get(combo);
- combo.setEnabled(enabled);
- label.setEnabled(enabled);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java
deleted file mode 100644
index 3446cddb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java
+++ /dev/null
@@ -1,486 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-
-
-/**
- * An overlaying preference store.
- */
-public class OverlayPreferenceStore implements IPreferenceStore {
-
-
- public static final class TypeDescriptor {
- private TypeDescriptor() {
- }
- }
-
- public static final TypeDescriptor BOOLEAN= new TypeDescriptor();
- public static final TypeDescriptor DOUBLE= new TypeDescriptor();
- public static final TypeDescriptor FLOAT= new TypeDescriptor();
- public static final TypeDescriptor INT= new TypeDescriptor();
- public static final TypeDescriptor LONG= new TypeDescriptor();
- public static final TypeDescriptor STRING= new TypeDescriptor();
-
- public static class OverlayKey {
-
- TypeDescriptor fDescriptor;
- String fKey;
-
- public OverlayKey(TypeDescriptor descriptor, String key) {
- fDescriptor= descriptor;
- fKey= key;
- }
- }
-
- private class PropertyListener implements IPropertyChangeListener {
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- OverlayKey key= findOverlayKey(event.getProperty());
- if (key != null)
- propagateProperty(fParent, key, fStore);
- }
- }
-
-
- private IPreferenceStore fParent;
- private IPreferenceStore fStore;
- private OverlayKey[] fOverlayKeys;
-
- private PropertyListener fPropertyListener;
- private boolean fLoaded;
-
-
- public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) {
- fParent= parent;
- fOverlayKeys= overlayKeys;
- fStore= new PreferenceStore();
- }
-
- private OverlayKey findOverlayKey(String key) {
- for (int i= 0; i < fOverlayKeys.length; i++) {
- if (fOverlayKeys[i].fKey.equals(key))
- return fOverlayKeys[i];
- }
- return null;
- }
-
- private boolean covers(String key) {
- return (findOverlayKey(key) != null);
- }
-
- private void propagateProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target) {
-
- if (orgin.isDefault(key.fKey)) {
- if (!target.isDefault(key.fKey))
- target.setToDefault(key.fKey);
- return;
- }
-
- TypeDescriptor d= key.fDescriptor;
- if (BOOLEAN == d) {
-
- boolean originValue= orgin.getBoolean(key.fKey);
- boolean targetValue= target.getBoolean(key.fKey);
- if (targetValue != originValue)
- target.setValue(key.fKey, originValue);
-
- } else if (DOUBLE == d) {
-
- double originValue= orgin.getDouble(key.fKey);
- double targetValue= target.getDouble(key.fKey);
- if (targetValue != originValue)
- target.setValue(key.fKey, originValue);
-
- } else if (FLOAT == d) {
-
- float originValue= orgin.getFloat(key.fKey);
- float targetValue= target.getFloat(key.fKey);
- if (targetValue != originValue)
- target.setValue(key.fKey, originValue);
-
- } else if (INT == d) {
-
- int originValue= orgin.getInt(key.fKey);
- int targetValue= target.getInt(key.fKey);
- if (targetValue != originValue)
- target.setValue(key.fKey, originValue);
-
- } else if (LONG == d) {
-
- long originValue= orgin.getLong(key.fKey);
- long targetValue= target.getLong(key.fKey);
- if (targetValue != originValue)
- target.setValue(key.fKey, originValue);
-
- } else if (STRING == d) {
-
- String originValue= orgin.getString(key.fKey);
- String targetValue= target.getString(key.fKey);
- if (targetValue != null && originValue != null && !targetValue.equals(originValue))
- target.setValue(key.fKey, originValue);
-
- }
- }
-
- public void propagate() {
- for (int i= 0; i < fOverlayKeys.length; i++)
- propagateProperty(fStore, fOverlayKeys[i], fParent);
- }
-
- private void loadProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target, boolean forceInitialization) {
- TypeDescriptor d= key.fDescriptor;
- if (BOOLEAN == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, true);
- target.setValue(key.fKey, orgin.getBoolean(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey));
-
- } else if (DOUBLE == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, 1.0D);
- target.setValue(key.fKey, orgin.getDouble(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey));
-
- } else if (FLOAT == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, 1.0F);
- target.setValue(key.fKey, orgin.getFloat(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey));
-
- } else if (INT == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, 1);
- target.setValue(key.fKey, orgin.getInt(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey));
-
- } else if (LONG == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, 1L);
- target.setValue(key.fKey, orgin.getLong(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey));
-
- } else if (STRING == d) {
-
- if (forceInitialization)
- target.setValue(key.fKey, "1"); //$NON-NLS-1$
- target.setValue(key.fKey, orgin.getString(key.fKey));
- target.setDefault(key.fKey, orgin.getDefaultString(key.fKey));
-
- }
- }
-
- public void load() {
- for (int i= 0; i < fOverlayKeys.length; i++)
- loadProperty(fParent, fOverlayKeys[i], fStore, true);
-
- fLoaded= true;
-
- }
-
- public void loadDefaults() {
- for (int i= 0; i < fOverlayKeys.length; i++)
- setToDefault(fOverlayKeys[i].fKey);
- }
-
- public void start() {
- if (fPropertyListener == null) {
- fPropertyListener= new PropertyListener();
- fParent.addPropertyChangeListener(fPropertyListener);
- }
- }
-
- public void stop() {
- if (fPropertyListener != null) {
- fParent.removePropertyChangeListener(fPropertyListener);
- fPropertyListener= null;
- }
- }
-
- /*
- * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener)
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- fStore.addPropertyChangeListener(listener);
- }
-
- /*
- * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener)
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fStore.removePropertyChangeListener(listener);
- }
-
- /*
- * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object)
- */
- public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
- fStore.firePropertyChangeEvent(name, oldValue, newValue);
- }
-
- /*
- * @see IPreferenceStore#contains(String)
- */
- public boolean contains(String name) {
- return fStore.contains(name);
- }
-
- /*
- * @see IPreferenceStore#getBoolean(String)
- */
- public boolean getBoolean(String name) {
- return fStore.getBoolean(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultBoolean(String)
- */
- public boolean getDefaultBoolean(String name) {
- return fStore.getDefaultBoolean(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultDouble(String)
- */
- public double getDefaultDouble(String name) {
- return fStore.getDefaultDouble(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultFloat(String)
- */
- public float getDefaultFloat(String name) {
- return fStore.getDefaultFloat(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultInt(String)
- */
- public int getDefaultInt(String name) {
- return fStore.getDefaultInt(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultLong(String)
- */
- public long getDefaultLong(String name) {
- return fStore.getDefaultLong(name);
- }
-
- /*
- * @see IPreferenceStore#getDefaultString(String)
- */
- public String getDefaultString(String name) {
- return fStore.getDefaultString(name);
- }
-
- /*
- * @see IPreferenceStore#getDouble(String)
- */
- public double getDouble(String name) {
- return fStore.getDouble(name);
- }
-
- /*
- * @see IPreferenceStore#getFloat(String)
- */
- public float getFloat(String name) {
- return fStore.getFloat(name);
- }
-
- /*
- * @see IPreferenceStore#getInt(String)
- */
- public int getInt(String name) {
- return fStore.getInt(name);
- }
-
- /*
- * @see IPreferenceStore#getLong(String)
- */
- public long getLong(String name) {
- return fStore.getLong(name);
- }
-
- /*
- * @see IPreferenceStore#getString(String)
- */
- public String getString(String name) {
- return fStore.getString(name);
- }
-
- /*
- * @see IPreferenceStore#isDefault(String)
- */
- public boolean isDefault(String name) {
- return fStore.isDefault(name);
- }
-
- /*
- * @see IPreferenceStore#needsSaving()
- */
- public boolean needsSaving() {
- return fStore.needsSaving();
- }
-
- /*
- * @see IPreferenceStore#putValue(String, String)
- */
- public void putValue(String name, String value) {
- if (covers(name))
- fStore.putValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, double)
- */
- public void setDefault(String name, double value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, float)
- */
- public void setDefault(String name, float value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, int)
- */
- public void setDefault(String name, int value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, long)
- */
- public void setDefault(String name, long value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, String)
- */
- public void setDefault(String name, String value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setDefault(String, boolean)
- */
- public void setDefault(String name, boolean value) {
- if (covers(name))
- fStore.setDefault(name, value);
- }
-
- /*
- * @see IPreferenceStore#setToDefault(String)
- */
- public void setToDefault(String name) {
- fStore.setToDefault(name);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, double)
- */
- public void setValue(String name, double value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, float)
- */
- public void setValue(String name, float value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, int)
- */
- public void setValue(String name, int value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, long)
- */
- public void setValue(String name, long value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, String)
- */
- public void setValue(String name, String value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /*
- * @see IPreferenceStore#setValue(String, boolean)
- */
- public void setValue(String name, boolean value) {
- if (covers(name))
- fStore.setValue(name, value);
- }
-
- /**
- * The keys to add to the list of overlay keys.
- * <p>
- * Note: This method must be called before {@link #load()} is called.
- * </p>
- *
- * @param keys
- *
- */
- public void addKeys(OverlayKey[] keys) {
- Assert.isTrue(!fLoaded);
- Assert.isNotNull(keys);
-
- int overlayKeysLength= fOverlayKeys.length;
- OverlayKey[] result= new OverlayKey[keys.length + overlayKeysLength];
-
- for (int i= 0, length= overlayKeysLength; i < length; i++)
- result[i]= fOverlayKeys[i];
-
- for (int i= 0, length= keys.length; i < length; i++)
- result[overlayKeysLength + i]= keys[i];
-
- fOverlayKeys= result;
-
- if (fLoaded)
- load();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesAccess.java
deleted file mode 100644
index f41fbcac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesAccess.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.ui.preferences.IWorkingCopyManager;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- *
- */
-public class PreferencesAccess {
-
- public static PreferencesAccess getOriginalPreferences() {
- return new PreferencesAccess();
- }
-
- public static PreferencesAccess getWorkingCopyPreferences(IWorkingCopyManager workingCopyManager) {
- return new WorkingCopyPreferencesAccess(workingCopyManager);
- }
-
- private PreferencesAccess() {
- // can only extends in this file
- }
-
- public IScopeContext getDefaultScope() {
- return new DefaultScope();
- }
-
- public IScopeContext getInstanceScope() {
- return new InstanceScope();
- }
-
- public IScopeContext getProjectScope(IProject project) {
- return new ProjectScope(project);
- }
-
- public void applyChanges() throws BackingStoreException {
- }
-
-
- private static class WorkingCopyPreferencesAccess extends PreferencesAccess {
-
- private final IWorkingCopyManager fWorkingCopyManager;
-
- private WorkingCopyPreferencesAccess(IWorkingCopyManager workingCopyManager) {
- fWorkingCopyManager= workingCopyManager;
- }
-
- private final IScopeContext getWorkingCopyScopeContext(IScopeContext original) {
- return new WorkingCopyScopeContext(fWorkingCopyManager, original);
- }
-
- public IScopeContext getDefaultScope() {
- return getWorkingCopyScopeContext(super.getDefaultScope());
- }
-
- public IScopeContext getInstanceScope() {
- return getWorkingCopyScopeContext(super.getInstanceScope());
- }
-
- public IScopeContext getProjectScope(IProject project) {
- return getWorkingCopyScopeContext(super.getProjectScope(project));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess#applyChanges()
- */
- public void applyChanges() throws BackingStoreException {
- fWorkingCopyManager.applyChanges();
- }
- }
-
-
- private static class WorkingCopyScopeContext implements IScopeContext {
-
- private final IWorkingCopyManager fWorkingCopyManager;
- private final IScopeContext fOriginal;
-
- public WorkingCopyScopeContext(IWorkingCopyManager workingCopyManager, IScopeContext original) {
- fWorkingCopyManager= workingCopyManager;
- fOriginal= original;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.IScopeContext#getName()
- */
- public String getName() {
- return fOriginal.getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.IScopeContext#getNode(java.lang.String)
- */
- public IEclipsePreferences getNode(String qualifier) {
- return fWorkingCopyManager.getWorkingCopy(fOriginal.getNode(qualifier));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.IScopeContext#getLocation()
- */
- public IPath getLocation() {
- return fOriginal.getLocation();
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.java
deleted file mode 100644
index 3076f819..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.java
+++ /dev/null
@@ -1,780 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- * Sebastian Davids, sdavids@gmx.de - 187316 [preferences] Mark Occurences Pref Page; Link to
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class PreferencesMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesMessages";//$NON-NLS-1$
-
- private PreferencesMessages() {
- // Do not instantiate
- }
-
- public static String AppearancePreferencePage_coloredlabels_label;
- public static String BuildPathsPropertyPage_error_message;
- public static String BuildPathsPropertyPage_error_title;
- public static String BuildPathsPropertyPage_job_title;
- public static String BuildPathsPropertyPage_no_java_project_message;
- public static String BuildPathsPropertyPage_closed_project_message;
- public static String BuildPathsPropertyPage_unsavedchanges_title;
- public static String BuildPathsPropertyPage_unsavedchanges_message;
- public static String BuildPathsPropertyPage_unsavedchanges_button_save;
- public static String BuildPathsPropertyPage_unsavedchanges_button_discard;
- public static String BuildPathsPropertyPage_unsavedchanges_button_ignore;
- public static String ClasspathVariablesPreferencePage_title;
- public static String ClasspathVariablesPreferencePage_description;
- public static String ClasspathVariablesPreferencePage_savechanges_title;
- public static String ClasspathVariablesPreferencePage_savechanges_message;
- public static String CleanUpPreferencePage_Description;
- public static String CleanUpPreferencePage_Title;
- public static String CodeAssistAdvancedConfigurationBlock_default_table_category_column_title;
- public static String CodeAssistAdvancedConfigurationBlock_default_table_description;
- public static String CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title;
- public static String CodeAssistAdvancedConfigurationBlock_key_binding_hint;
- public static String CodeAssistAdvancedConfigurationBlock_page_description;
- public static String CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title;
- public static String CodeAssistAdvancedConfigurationBlock_separate_table_description;
- public static String CodeAssistAdvancedConfigurationBlock_no_shortcut;
- public static String CodeAssistAdvancedConfigurationBlock_Up;
- public static String CodeAssistAdvancedConfigurationBlock_Down;
- public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout;
- public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_ms;
- public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_emptyInput;
- public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidInput;
- public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidRange;
- public static String ImportOrganizeConfigurationBlock_emptylines_between_groups_label;
- public static String ImportOrganizeConfigurationBlock_error_invalidnumberofemptylines;
- public static String ImportOrganizePreferencePage_description;
- public static String ImportOrganizePreferencePage_title;
- public static String ImportOrganizeConfigurationBlock_order_label;
- public static String ImportOrganizeConfigurationBlock_other_static;
- public static String ImportOrganizeConfigurationBlock_other_normal;
- public static String ImportOrganizeConfigurationBlock_other_normal_label;
- public static String ImportOrganizeConfigurationBlock_order_add_button;
- public static String ImportOrganizeConfigurationBlock_order_edit_button;
- public static String ImportOrganizeConfigurationBlock_order_up_button;
- public static String ImportOrganizeConfigurationBlock_order_down_button;
- public static String ImportOrganizeConfigurationBlock_order_remove_button;
- public static String ImportOrganizeConfigurationBlock_order_add_static_button;
- public static String ImportOrganizeConfigurationBlock_order_load_button;
- public static String ImportOrganizeConfigurationBlock_order_save_button;
- public static String ImportOrganizeConfigurationBlock_other_description;
- public static String ImportOrganizeConfigurationBlock_ignoreLowerCase_label;
- public static String ImportOrganizeConfigurationBlock_threshold_label;
- public static String ImportOrganizeConfigurationBlock_error_invalidthreshold;
- public static String ImportOrganizeConfigurationBlock_loadDialog_title;
- public static String ImportOrganizeConfigurationBlock_loadDialog_error_title;
- public static String ImportOrganizeConfigurationBlock_loadDialog_error_message;
- public static String ImportOrganizeConfigurationBlock_saveDialog_title;
- public static String ImportOrganizeConfigurationBlock_saveDialog_error_title;
- public static String ImportOrganizeConfigurationBlock_staticthreshold_label;
- public static String ImportOrganizeConfigurationBlock_saveDialog_error_message;
- public static String ImportOrganizeInputDialog_title;
- public static String ImportOrganizeInputDialog_browse_packages_button;
- public static String ImportOrganizeInputDialog_browse_types_label;
- public static String ImportOrganizeInputDialog_title_static;
- public static String ImportOrganizeInputDialog_ChoosePackageDialog_title;
- public static String ImportOrganizeInputDialog_ChoosePackageDialog_description;
- public static String ImportOrganizeInputDialog_ChoosePackageDialog_empty;
- public static String ImportOrganizeInputDialog_ChooseTypeDialog_title;
- public static String ImportOrganizeInputDialog_ChooseTypeDialog_description;
- public static String ImportOrganizeInputDialog_ChooseTypeDialog_error_message;
- public static String ImportOrganizeInputDialog_error_enterName;
- public static String ImportOrganizeInputDialog_error_invalidName;
- public static String ImportOrganizeInputDialog_error_entryExists;
- public static String ImportOrganizeInputDialog_name_group_label;
- public static String ImportOrganizeInputDialog_name_group_static_label;
- public static String JavaBasePreferencePage_description;
- public static String JavaBasePreferencePage_doubleclick_action;
- public static String JavaBasePreferencePage_doubleclick_gointo;
- public static String JavaBasePreferencePage_doubleclick_expand;
- public static String JavaBasePreferencePage_refactoring_lightweight;
- public static String JavaBasePreferencePage_refactoring_title;
- public static String JavaBasePreferencePage_refactoring_auto_save;
- public static String JavaBasePreferencePage_search;
- public static String JavaBasePreferencePage_search_small_menu;
- public static String JavaBuildConfigurationBlock_build_recreate_modified;
- public static String JavadocConfigurationBlock_error_archive_not_found_in_workspace;
- public static String JavadocConfigurationBlock_external_radio;
- public static String JavadocConfigurationBlock_workspace_archive_selection_dialog_description;
- public static String JavadocConfigurationBlock_workspace_archive_selection_dialog_title;
- public static String JavadocConfigurationBlock_workspace_radio;
- public static String JavadocConfigurationPropertyPage_invalid_container;
- public static String JavadocConfigurationPropertyPage_not_supported;
- public static String JavadocConfigurationPropertyPage_read_only;
- public static String JavaEditorPropertyPage_SaveActionLink_Text;
- public static String NewJavaProjectPreferencePage_title;
- public static String NewJavaProjectPreferencePage_description;
- public static String NewJavaProjectPreferencePage_sourcefolder_label;
- public static String NewJavaProjectPreferencePage_sourcefolder_project;
- public static String NewJavaProjectPreferencePage_sourcefolder_folder;
- public static String NewJavaProjectPreferencePage_folders_src;
- public static String NewJavaProjectPreferencePage_folders_error_namesempty;
- public static String NewJavaProjectPreferencePage_folders_error_invalidsrcname;
- public static String NewJavaProjectPreferencePage_folders_error_invalidcp;
- public static String NewJavaProjectPreferencePage_error_decode;
- public static String JavaEditorPreferencePage_showQuickFixables;
- public static String JavaEditorPreferencePage_analyseAnnotationsWhileTyping;
- public static String JavaEditorPreferencePage_multiLineComment;
- public static String JavaEditorPreferencePage_singleLineComment;
- public static String JavaEditorPreferencePage_returnKeyword;
- public static String JavaEditorPreferencePage_keywords;
- public static String JavaEditorPreferencePage_strings;
- public static String JavaEditorPreferencePage_others;
- public static String JavaEditorPreferencePage_operators;
- public static String JavaEditorPreferencePage_brackets;
- public static String JavaEditorPreferencePage_javaCommentTaskTags;
- public static String JavaEditorPreferencePage_javaDocKeywords;
- public static String JavaEditorPreferencePage_javaDocHtmlTags;
- public static String JavaEditorPreferencePage_javaDocLinks;
- public static String JavaEditorPreferencePage_javaDocOthers;
- public static String JavaEditorPreferencePage_backgroundColor;
- public static String JavaEditorPreferencePage_systemDefault;
- public static String JavaEditorPreferencePage_custom;
- public static String JavaEditorPreferencePage_semanticHighlighting_option;
- public static String JavaEditorPreferencePage_foreground;
- public static String JavaEditorPreferencePage_color;
- public static String JavaEditorPreferencePage_bold;
- public static String JavaEditorPreferencePage_italic;
- public static String JavaEditorPreferencePage_strikethrough;
- public static String JavaEditorPreferencePage_underline;
- public static String JavaEditorPreferencePage_enable;
- public static String JavaEditorPreferencePage_preview;
- public static String JavaEditorPreferencePage_displayedTabWidth;
- public static String JavaEditorPreferencePage_insertSpaceForTabs;
- public static String JavaEditorPreferencePage_showOverviewRuler;
- public static String JavaEditorPreferencePage_highlightMatchingBrackets;
- public static String JavaEditorPreferencePage_highlightCurrentLine;
- public static String JavaEditorPreferencePage_showPrintMargin;
- public static String JavaEditorPreferencePage_printMarginColumn;
- public static String JavaEditorPreferencePage_insertSingleProposalsAutomatically;
- public static String JavaEditorPreferencePage_showOnlyProposalsVisibleInTheInvocationContext;
- public static String JavaEditorPreferencePage_presentProposalsInAlphabeticalOrder;
- public static String JavaEditorPreferencePage_coloring_element;
- public static String JavaEditorPreferencePage_enableAutoActivation;
-// public static String JavaEditorPreferencePage_automaticallyAddImportInsteadOfQualifiedName;
-// public static String JavaEditorPreferencePage_suggestStaticImports;
- public static String JavaEditorPreferencePage_completionInserts;
- public static String JavaEditorPreferencePage_completionOverwrites;
- public static String JavaEditorPreferencePage_completionToggleHint;
- public static String JavaEditorPreferencePage_fillArgumentNamesOnMethodCompletion;
- public static String JavaEditorPreferencePage_guessArgumentNamesOnMethodCompletion;
- public static String JavaEditorPreferencePage_autoActivationDelay;
- public static String JavaEditorPreferencePage_autoActivationTriggersForJava;
- public static String JavaEditorPreferencePage_autoActivationTriggersForJavaDoc;
- public static String JavaEditorPreferencePage_completePrefixes;
- public static String JavaEditorPreferencePage_backgroundForCompletionProposals;
- public static String JavaEditorPreferencePage_foregroundForCompletionProposals;
- public static String JavaEditorPreferencePage_backgroundForMethodParameters;
- public static String JavaEditorPreferencePage_foregroundForMethodParameters;
- public static String JavaEditorPreferencePage_backgroundForCompletionReplacement;
- public static String JavaEditorPreferencePage_foregroundForCompletionReplacement;
- public static String JavaEditorPreferencePage_sourceHoverBackgroundColor;
- public static String JavaEditorPreferencePage_general;
- public static String JavaEditorPreferencePage_colors;
- public static String JavaEditorPreferencePage_empty_input;
- public static String JavaEditorPreferencePage_invalid_input;
- public static String JavaEditorPreferencePage_showLineNumbers;
- public static String JavaEditorPreferencePage_lineNumberForegroundColor;
- public static String JavaEditorPreferencePage_matchingBracketsHighlightColor2;
- public static String JavaEditorPreferencePage_currentLineHighlighColor;
- public static String JavaEditorPreferencePage_printMarginColor2;
- public static String JavaEditorPreferencePage_appearanceOptions;
- public static String JavaEditorPreferencePage_typing_tabTitle;
- public static String JavaEditorPreferencePage_typing_description;
- public static String JavaEditorPreferencePage_closeStrings;
- public static String JavaEditorPreferencePage_closeBrackets;
- public static String JavaEditorPreferencePage_closeBraces;
- public static String JavaEditorPreferencePage_closeJavaDocs;
- public static String JavaEditorPreferencePage_wrapStrings;
- public static String JavaEditorPreferencePage_escapeStrings;
- public static String JavaEditorPreferencePage_addJavaDocTags;
- public static String JavaEditorPreferencePage_smartPaste;
- public static String JavaEditorPreferencePage_link;
- public static String JavaEditorPreferencePage_link_tooltip;
- public static String JavaEditorPreferencePage_importsOnPaste;
- public static String JavaEditorPreferencePage_subWordNavigation;
- public static String JavaEditorPreferencePage_typing_smartSemicolon;
- public static String JavaEditorPreferencePage_typing_smartOpeningBrace;
- public static String JavaEditorPreferencePage_typing_smartTab;
- public static String JavaEditorPreferencePage_hoverTab_title;
- public static String JavaEditorColoringConfigurationBlock_link;
- public static String JavaEditorPreferencePage_quickassist_lightbulb;
- public static String JavaEditorPreferencePage_showJavaElementOnly;
- public static String JavaEditorPreferencePage_accessibility_disableCustomCarets;
- public static String JavaEditorPreferencePage_accessibility_wideCaret;
- public static String JavaEditorHoverConfigurationBlock_annotationRollover;
- public static String JavaEditorHoverConfigurationBlock_hoverPreferences;
- public static String JavaEditorHoverConfigurationBlock_enabled;
- public static String JavaEditorHoverConfigurationBlock_keyModifier;
- public static String JavaEditorHoverConfigurationBlock_description;
- public static String JavaEditorHoverConfigurationBlock_modifierIsNotValid;
- public static String JavaEditorHoverConfigurationBlock_modifierIsNotValidForHover;
- public static String JavaEditorHoverConfigurationBlock_duplicateModifier;
- public static String JavaEditorHoverConfigurationBlock_nameColumnTitle;
- public static String JavaEditorHoverConfigurationBlock_modifierColumnTitle;
- public static String JavaEditorHoverConfigurationBlock_delimiter;
- public static String JavaEditorHoverConfigurationBlock_insertDelimiterAndModifierAndDelimiter;
- public static String JavaEditorHoverConfigurationBlock_insertModifierAndDelimiter;
- public static String JavaEditorHoverConfigurationBlock_insertDelimiterAndModifier;
- public static String MarkOccurrencesConfigurationBlock_title;
- public static String MarkOccurrencesConfigurationBlock_link;
- public static String MarkOccurrencesConfigurationBlock_link_tooltip;
- public static String MarkOccurrencesConfigurationBlock_markOccurrences;
-// public static String MarkOccurrencesConfigurationBlock_markTypeOccurrences;
- public static String MarkOccurrencesConfigurationBlock_markMethodOccurrences;
- public static String MarkOccurrencesConfigurationBlock_markConstantOccurrences;
-// public static String MarkOccurrencesConfigurationBlock_markFieldOccurrences;
- public static String MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences;
-// public static String MarkOccurrencesConfigurationBlock_markExceptionOccurrences;
- public static String MarkOccurrencesConfigurationBlock_markMethodExitPoints;
-// public static String MarkOccurrencesConfigurationBlock_markImplementors;
- public static String MarkOccurrencesConfigurationBlock_markBreakContinueTargets;
- public static String MarkOccurrencesConfigurationBlock_stickyOccurrences;
- public static String JavaElementInfoPage_binary;
- public static String JavaElementInfoPage_classpath_entry_kind;
- public static String JavaElementInfoPage_library;
- public static String JavaElementInfoPage_nameLabel;
- public static String JavaElementInfoPage_not_present;
- public static String JavaElementInfoPage_package;
- public static String JavaElementInfoPage_package_contents;
- public static String JavaElementInfoPage_project;
- public static String JavaElementInfoPage_resource_path;
- public static String JavaElementInfoPage_source;
- public static String JavaElementInfoPage_variable;
- public static String JavaElementInfoPage_variable_path;
- public static String JavaElementInfoPage_location;
- public static String JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description;
- public static String JavadocConfigurationPropertyPage_IsIncorrectElement_description;
- public static String JavadocConfigurationPropertyPage_IsJavaProject_description;
- public static String JavadocConfigurationBlock_browse_folder_button;
- public static String JavadocConfigurationBlock_error_notafolder;
- public static String JavadocConfigurationBlock_javadocFolderDialog_label;
- public static String JavadocConfigurationBlock_javadocFolderDialog_message;
- public static String JavadocConfigurationBlock_MalformedURL_error;
- public static String JavadocConfigurationBlock_validate_button;
- public static String JavadocConfigurationBlock_InvalidLocation_message;
- public static String JavadocConfigurationBlock_ValidLocation_message;
- public static String JavadocConfigurationBlock_UnableToValidateLocation_message;
- public static String JavadocConfigurationBlock_MessageDialog_title;
- public static String JavadocConfigurationBlock_location_type_path_label;
- public static String JavadocConfigurationBlock_location_type_jar_label;
- public static String JavadocConfigurationBlock_location_path_label;
- public static String JavadocConfigurationBlock_location_jar_label;
- public static String JavadocConfigurationBlock_jar_path_label;
- public static String JavadocConfigurationBlock_zipImportSource_title;
- public static String JavadocConfigurationBlock_location_in_jarorzip_message;
- public static String JavadocConfigurationBlock_browse_jarorzip_path_title;
- public static String JavadocConfigurationBlock_error_notafile;
- public static String JavadocConfigurationBlock_error_invalidarchivepath;
- public static String JavadocConfigurationBlock_error_archivepathnotabsolute;
- public static String JavadocConfigurationBlock_browse_archive_button;
- public static String JavadocConfigurationBlock_browse_archive_path_button;
- public static String ProblemSeveritiesConfigurationBlock_ignore_documented_unused_parameters;
- public static String ProblemSeveritiesConfigurationBlock_LooselyDeclaredGlobalVar;
- public static String ProblemSeveritiesConfigurationBlock_Optionalsemicolon;
- public static String ProblemSeveritiesConfigurationBlock_pb_redundant_null_check;
- public static String ProblemSeveritiesConfigurationBlock_Resolution;
- public static String ProblemSeveritiesConfigurationBlock_treat_optional_as_fatal;
- public static String ProblemSeveritiesConfigurationBlock_UnresolvedFields;
- public static String ProblemSeveritiesConfigurationBlock_UnresolvedMethods;
- public static String ProblemSeveritiesConfigurationBlock_UnresolvedTypes;
- public static String SourceAttachmentPropertyPage_error_title;
- public static String SourceAttachmentPropertyPage_error_message;
- public static String SourceAttachmentPropertyPage_invalid_container;
- public static String SourceAttachmentPropertyPage_noarchive_message;
- public static String SourceAttachmentPropertyPage_containerentry_message;
- public static String AppearancePreferencePage_description;
- //public static String AppearancePreferencePage_methodreturntype_label;
- public static String AppearancePreferencePage_inferredmethodreturntype_label;
- public static String AppearancePreferencePage_showCategory_label;
-// public static String AppearancePreferencePage_methodtypeparams_label;
-// public static String AppearancePreferencePage_pkgNamePatternEnable_label;
-// public static String AppearancePreferencePage_pkgNamePattern_label;
- public static String AppearancePreferencePage_showMembersInPackagesView;
- public static String AppearancePreferencePage_stackViewsVerticallyInTheJavaBrowsingPerspective;
-// public static String AppearancePreferencePage_note;
-// public static String AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives;
- public static String AppearancePreferencePage_packageNameCompressionPattern_error_isEmpty;
-// public static String AppearancePreferencePage_foldEmptyPackages;
- public static String AppearancePreferencePage_foldEmptySourceFolders;
- public static String CodeFormatterPreferencePage_title;
- public static String CodeFormatterPreferencePage_description;
- public static String SourceAttachmentPropertyPage_not_supported;
- public static String SourceAttachmentPropertyPage_read_only;
- public static String TodoTaskPreferencePage_title;
- public static String TodoTaskPreferencePage_description;
- public static String TodoTaskConfigurationBlock_markers_tasks_high_priority;
- public static String TodoTaskConfigurationBlock_markers_tasks_normal_priority;
- public static String TodoTaskConfigurationBlock_markers_tasks_low_priority;
- public static String TodoTaskConfigurationBlock_markers_tasks_add_button;
- public static String TodoTaskConfigurationBlock_markers_tasks_remove_button;
- public static String TodoTaskConfigurationBlock_markers_tasks_edit_button;
- public static String TodoTaskConfigurationBlock_markers_tasks_name_column;
- public static String TodoTaskConfigurationBlock_markers_tasks_priority_column;
- public static String TodoTaskConfigurationBlock_markers_tasks_setdefault_button;
- public static String TodoTaskConfigurationBlock_casesensitive_label;
- public static String TodoTaskConfigurationBlock_needsbuild_title;
- public static String TodoTaskConfigurationBlock_tasks_default;
- public static String TodoTaskConfigurationBlock_needsfullbuild_message;
- public static String TodoTaskConfigurationBlock_needsprojectbuild_message;
- public static String TodoTaskInputDialog_new_title;
- public static String TodoTaskInputDialog_edit_title;
- public static String TodoTaskInputDialog_name_label;
- public static String TodoTaskInputDialog_priority_label;
- public static String TodoTaskInputDialog_priority_high;
- public static String TodoTaskInputDialog_priority_normal;
- public static String TodoTaskInputDialog_priority_low;
- public static String TodoTaskInputDialog_error_enterName;
- public static String TodoTaskInputDialog_error_comma;
- public static String TodoTaskInputDialog_error_entryExists;
- public static String TodoTaskInputDialog_error_noSpace;
- public static String PropertyAndPreferencePage_useworkspacesettings_change;
- public static String PropertyAndPreferencePage_showprojectspecificsettings_label;
- public static String PropertyAndPreferencePage_useprojectsettings_label;
- public static String JavaBuildPreferencePage_title;
- public static String JavaBuildPreferencePage_description;
- public static String JavaBuildConfigurationBlock_section_general;
- public static String JavaBuildConfigurationBlock_section_output_folder;
- public static String JavaBuildConfigurationBlock_section_access_rules;
- public static String JavaBuildConfigurationBlock_section_include_path_problems;
- public static String JavaBuildConfigurationBlock_error;
- public static String JavaBuildConfigurationBlock_warning;
- public static String JavaBuildConfigurationBlock_ignore;
- public static String JavaBuildConfigurationBlock_needsbuild_title;
- public static String JavaBuildConfigurationBlock_needsfullbuild_message;
- public static String JavaBuildConfigurationBlock_needsprojectbuild_message;
- public static String JavaBuildConfigurationBlock_resource_filter_description;
- public static String JavaBuildConfigurationBlock_resource_filter_label;
- public static String JavaBuildConfigurationBlock_build_invalid_classpath_label;
- public static String JavaBuildConfigurationBlock_build_clean_outputfolder_label;
- public static String JavaBuildConfigurationBlock_enable_exclusion_patterns_label;
- public static String JavaBuildConfigurationBlock_enable_multiple_outputlocations_label;
- public static String JavaBuildConfigurationBlock_pb_incomplete_build_path_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_discourraged_reference_label;
- public static String JavaBuildConfigurationBlock_pb_build_path_cycles_label;
- public static String JavaBuildConfigurationBlock_pb_duplicate_resources_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_forbidden_reference_label;
- public static String JavaBuildConfigurationBlock_pb_max_per_unit_label;
- public static String JavaBuildConfigurationBlock_pb_check_prereq_binary_level_label;
- public static String JavaBuildConfigurationBlock_empty_input;
- public static String JavaBuildConfigurationBlock_invalid_input;
- public static String JavaBuildConfigurationBlock_filter_invalidsegment_error;
- public static String ProblemSeveritiesPreferencePage_title;
- public static String ProblemSeveritiesConfigurationBlock_error;
- public static String ProblemSeveritiesConfigurationBlock_warning;
- public static String ProblemSeveritiesConfigurationBlock_ignore;
- public static String ProblemSeveritiesConfigurationBlock_section_potential_programming_problems;
- public static String ProblemSeveritiesConfigurationBlock_section_unnecessary_code;
- public static String ProblemSeveritiesConfigurationBlock_section_nls;
- public static String ProblemSeveritiesConfigurationBlock_section_code_style;
- public static String ProblemSeveritiesConfigurationBlock_section_deprecations;
- public static String ProblemSeveritiesConfigurationBlock_section_name_shadowing;
- public static String ProblemSeveritiesConfigurationBlock_section_annotations;
- public static String ProblemSeveritiesConfigurationBlock_needsbuild_title;
- public static String ProblemSeveritiesConfigurationBlock_needsfullbuild_message;
- public static String ProblemSeveritiesConfigurationBlock_needsprojectbuild_message;
- public static String ProblemSeveritiesConfigurationBlock_common_description;
- public static String ProblemSeveritiesConfigurationBlock_enableSemanticValidation;
- public static String ProblemSeveritiesConfigurationBlock_pb_unsafe_type_op_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_raw_type_reference;
- public static String ProblemSeveritiesConfigurationBlock_pb_final_param_bound_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_inexact_vararg_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_accidential_assignement_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_local_variable_hiding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_field_hiding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_special_param_hiding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unqualified_field_access_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_finally_block_not_completing_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_undocumented_empty_block_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_when_overriding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_missing_serial_version_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_undefined_field_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_method_naming_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_no_effect_assignment_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_incompatible_interface_method_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_indirect_access_to_static_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_hidden_catchblock_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_static_access_receiver_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_imports_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_local_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_parameter_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_signal_param_in_overriding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_private_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_non_externalized_strings_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_in_deprecation_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_when_overriding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_empty_statement_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unnecessary_type_check_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_incomplete_enum_switch_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unnecessary_else_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_synth_access_emul_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_autoboxing_problem_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_char_array_in_concat_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_missing_override_annotation_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_missing_deprecated_annotation_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_annotation_super_interface_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_type_parameter_hiding_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unused_label_label;
- public static String JavadocProblemsPreferencePage_title;
- public static String JavadocProblemsConfigurationBlock_public;
- public static String JavadocProblemsConfigurationBlock_protected;
- public static String JavadocProblemsConfigurationBlock_default;
- public static String JavadocProblemsConfigurationBlock_private;
- public static String JavadocProblemsConfigurationBlock_error;
- public static String JavadocProblemsConfigurationBlock_warning;
- public static String JavadocProblemsConfigurationBlock_ignore;
- public static String JavadocProblemsConfigurationBlock_needsbuild_title;
- public static String JavadocProblemsConfigurationBlock_needsfullbuild_message;
- public static String JavadocProblemsConfigurationBlock_needsprojectbuild_message;
- public static String JavadocProblemsConfigurationBlock_javadoc_description;
- public static String JavadocProblemsConfigurationBlock_pb_javadoc_support_label;
- public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_label;
- public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_label;
- public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_visibility_label;
- public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_not_visible_ref_label;
- public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_deprecated_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_visibility_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_overriding_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_comments_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_comments_visibility_label;
- public static String JavadocProblemsConfigurationBlock_pb_missing_comments_overriding_label;
- public static String CompliancePreferencePage_title;
- public static String CompliancePreferencePage_description;
- public static String ComplianceConfigurationBlock_error;
- public static String ComplianceConfigurationBlock_warning;
- public static String ComplianceConfigurationBlock_ignore;
- public static String ComplianceConfigurationBlock_version11;
- public static String ComplianceConfigurationBlock_version12;
- public static String ComplianceConfigurationBlock_version13;
- public static String ComplianceConfigurationBlock_version14;
- public static String ComplianceConfigurationBlock_version15;
- public static String ComplianceConfigurationBlock_needsbuild_title;
- public static String ComplianceConfigurationBlock_needsfullbuild_message;
- public static String ComplianceConfigurationBlock_needsprojectbuild_message;
- public static String ComplianceConfigurationBlock_variable_attr_label;
- public static String ComplianceConfigurationBlock_line_number_attr_label;
- public static String ComplianceConfigurationBlock_source_file_attr_label;
- public static String ComplianceConfigurationBlock_codegen_unused_local_label;
- public static String ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label;
- public static String ComplianceConfigurationBlock_compiler_compliance_label;
- public static String ComplianceConfigurationBlock_default_settings_label;
- public static String ComplianceConfigurationBlock_source_compatibility_label;
- public static String ComplianceConfigurationBlock_codegen_targetplatform_label;
- public static String ComplianceConfigurationBlock_pb_assert_as_identifier_label;
- public static String ComplianceConfigurationBlock_pb_enum_as_identifier_label;
- public static String ComplianceConfigurationBlock_compliance_group_label;
- public static String ComplianceConfigurationBlock_classfiles_group_label;
- public static String OptionsConfigurationBlock_job_title;
- public static String OptionsConfigurationBlock_buildall_taskname;
- public static String OptionsConfigurationBlock_buildproject_taskname;
- public static String CodeStylePreferencePage_title;
- public static String CodeTemplatesPreferencePage_title;
- public static String JavaCategoryPropertyPage_text;
- public static String NameConventionConfigurationBlock_field_label;
- public static String NameConventionConfigurationBlock_static_label;
- public static String NameConventionConfigurationBlock_arg_label;
- public static String NameConventionConfigurationBlock_local_label;
-// public static String NameConventionConfigurationBlock_keywordthis_label;
- public static String NameConventionConfigurationBlock_isforbooleangetters_label;
- public static String NameConventionConfigurationBlock_dialog_prefix;
- public static String NameConventionConfigurationBlock_dialog_suffix;
- public static String NameConventionConfigurationBlock_exceptionname_label;
- public static String NameConventionConfigurationBlock_error_emptyprefix;
- public static String NameConventionConfigurationBlock_error_emptysuffix;
- public static String NameConventionConfigurationBlock_error_invalidprefix;
- public static String NameConventionConfigurationBlock_error_invalidsuffix;
- public static String NameConventionConfigurationBlock_list_label;
- public static String NameConventionConfigurationBlock_list_edit_button;
- public static String NameConventionConfigurationBlock_list_name_column;
- public static String NameConventionConfigurationBlock_list_prefix_column;
- public static String NameConventionConfigurationBlock_list_suffix_column;
- public static String NameConventionConfigurationBlock_field_dialog_title;
- public static String NameConventionConfigurationBlock_field_dialog_message;
- public static String NameConventionConfigurationBlock_static_dialog_title;
- public static String NameConventionConfigurationBlock_static_dialog_message;
- public static String NameConventionConfigurationBlock_arg_dialog_title;
- public static String NameConventionConfigurationBlock_arg_dialog_message;
- public static String NameConventionConfigurationBlock_local_dialog_title;
- public static String NameConventionConfigurationBlock_local_dialog_message;
- public static String MembersOrderPreferencePage_category_button_up;
- public static String MembersOrderPreferencePage_category_button_down;
- public static String MembersOrderPreferencePage_visibility_button_up;
- public static String MembersOrderPreferencePage_visibility_button_down;
- public static String MembersOrderPreferencePage_label_description;
-// public static String MembersOrderPreferencePage_fields_label;
- public static String MembersOrderPreferencePage_vars_label;
- public static String MembersOrderPreferencePage_constructors_label;
- public static String MembersOrderPreferencePage_methods_label;
- public static String MembersOrderPreferencePage_staticfields_label;
- public static String MembersOrderPreferencePage_staticmethods_label;
- public static String MembersOrderPreferencePage_initialisers_label;
- public static String MembersOrderPreferencePage_staticinitialisers_label;
- public static String MembersOrderPreferencePage_types_label;
- public static String MembersOrderPreferencePage_public_label;
- public static String MembersOrderPreferencePage_private_label;
- public static String MembersOrderPreferencePage_protected_label;
- public static String MembersOrderPreferencePage_default_label;
- public static String MembersOrderPreferencePage_usevisibilitysort_label;
- public static String CodeTemplateBlock_link_tooltip;
- public static String CodeTemplateBlock_templates_comment_node;
- public static String CodeTemplateBlock_templates_code_node;
- public static String CodeTemplateBlock_catchblock_label;
- public static String CodeTemplateBlock_methodstub_label;
- public static String CodeTemplateBlock_constructorstub_label;
- public static String CodeTemplateBlock_newtype_label;
- public static String CodeTemplateBlock_classbody_label;
- public static String CodeTemplateBlock_interfacebody_label;
- public static String CodeTemplateBlock_enumbody_label;
- public static String CodeTemplateBlock_annotationbody_label;
- public static String CodeTemplateBlock_typecomment_label;
- public static String CodeTemplateBlock_fieldcomment_label;
- public static String CodeTemplateBlock_filecomment_label;
- public static String CodeTemplateBlock_methodcomment_label;
- public static String CodeTemplateBlock_overridecomment_label;
- public static String CodeTemplateBlock_delegatecomment_label;
- public static String CodeTemplateBlock_constructorcomment_label;
- public static String CodeTemplateBlock_gettercomment_label;
- public static String CodeTemplateBlock_settercomment_label;
- public static String CodeTemplateBlock_getterstub_label;
- public static String CodeTemplateBlock_setterstub_label;
- public static String CodeTemplateBlock_templates_edit_button;
- public static String CodeTemplateBlock_templates_import_button;
- public static String CodeTemplateBlock_templates_export_button;
- public static String CodeTemplateBlock_templates_exportall_button;
- public static String CodeTemplateBlock_createcomment_label;
- public static String CodeTemplateBlock_templates_label;
- public static String CodeTemplateBlock_preview;
- public static String CodeTemplateBlock_import_title;
- public static String CodeTemplateBlock_import_extension;
- public static String CodeTemplateBlock_export_title;
- public static String CodeTemplateBlock_export_filename;
- public static String CodeTemplateBlock_export_extension;
- public static String CodeTemplateBlock_export_exists_title;
- public static String CodeTemplateBlock_export_exists_message;
- public static String CodeTemplateBlock_error_read_title;
- public static String CodeTemplateBlock_error_read_message;
- public static String CodeTemplateBlock_error_parse_message;
- public static String CodeTemplateBlock_error_write_title;
- public static String CodeTemplateBlock_error_write_message;
- public static String CodeTemplateBlock_export_error_title;
- public static String CodeTemplateBlock_export_error_hidden;
- public static String CodeTemplateBlock_export_error_canNotWrite;
- public static String TypeFilterPreferencePage_description;
- public static String TypeFilterPreferencePage_list_label;
- public static String TypeFilterPreferencePage_add_button;
- public static String TypeFilterPreferencePage_addpackage_button;
- public static String TypeFilterPreferencePage_edit_button;
- public static String TypeFilterPreferencePage_remove_button;
- public static String TypeFilterPreferencePage_selectall_button;
- public static String TypeFilterPreferencePage_deselectall_button;
- public static String TypeFilterPreferencePage_choosepackage_label;
- public static String TypeFilterPreferencePage_choosepackage_description;
- public static String TypeFilterInputDialog_title;
- public static String TypeFilterInputDialog_message;
- public static String TypeFilterInputDialog_browse_button;
- public static String TypeFilterInputDialog_error_enterName;
- public static String TypeFilterInputDialog_error_invalidName;
- public static String TypeFilterInputDialog_error_entryExists;
- public static String TypeFilterInputDialog_choosepackage_label;
- public static String TypeFilterInputDialog_choosepackage_description;
- public static String JavaEditorPreferencePage_selectionBackgroundColor;
- public static String JavaEditorPreferencePage_selectionForegroundColor;
- public static String SpellingPreferencePage_empty_threshold;
- public static String SpellingPreferencePage_invalid_threshold;
- public static String SpellingPreferencePage_ignore_digits_label;
- public static String SpellingPreferencePage_ignore_mixed_label;
- public static String SpellingPreferencePage_ignore_sentence_label;
- public static String SpellingPreferencePage_ignore_upper_label;
- public static String SpellingPreferencePage_ignore_url_label;
- public static String SpellingPreferencePage_ignore_non_letters_label;
- public static String SpellingPreferencePage_ignore_single_letters_label;
- public static String SpellingPreferencePage_ignore_java_strings_label;
- public static String SpellingPreferencePage_ignore_ampersand_in_properties_label;
- public static String SpellingPreferencePage_proposals_threshold;
- public static String SpellingPreferencePage_dictionary_label;
- public static String SpellingPreferencePage_encoding_label;
- public static String SpellingPreferencePage_workspace_dictionary_label;
- public static String SpellingPreferencePage_browse_label;
- public static String SpellingPreferencePage_dictionary_error;
- public static String SpellingPreferencePage_dictionary_none;
- public static String SpellingPreferencePage_locale_error;
- public static String SpellingPreferencePage_filedialog_title;
- public static String SpellingPreferencePage_filter_dictionary_extension;
- public static String SpellingPreferencePage_filter_all_extension;
- public static String SpellingPreferencePage_filter_dictionary_label;
- public static String SpellingPreferencePage_filter_all_label;
- public static String SpellingPreferencePage_enable_contentassist_label;
- public static String SpellingPreferencePage_group_user;
- public static String SpellingPreferencePage_group_dictionary;
- public static String SpellingPreferencePage_group_dictionaries;
- public static String SpellingPreferencePage_group_advanced;
- public static String SpellingPreferencePage_user_dictionary_description;
- public static String BuildPathPreferencePage_title;
- public static String BuildPathPreferencePage_description;
- public static String UserLibraryPreferencePage_title;
- public static String UserLibraryPreferencePage_description;
- public static String UserLibraryPreferencePage_libraries_label;
- public static String UserLibraryPreferencePage_libraries_new_button;
- public static String UserLibraryPreferencePage_libraries_edit_button;
- public static String UserLibraryPreferencePage_libraries_addjar_button;
- public static String UserLibraryPreferencePage_libraries_addfolder_button;
- public static String UserLibraryPreferencePage_libraries_remove_button;
- public static String UserLibraryPreferencePage_libraries_load_button;
- public static String UserLibraryPreferencePage_libraries_save_button;
- public static String UserLibraryPreferencePage_operation;
- public static String UserLibraryPreferencePage_operation_error;
- public static String UserLibraryPreferencePage_config_error_title;
- public static String UserLibraryPreferencePage_config_error_message;
- public static String UserLibraryPreferencePage_browsejar_new_title;
- public static String UserLibraryPreferencePage_browsejar_edit_title;
- public static String UserLibraryPreferencePage_LibraryNameDialog_new_title;
- public static String UserLibraryPreferencePage_LibraryNameDialog_edit_title;
- public static String UserLibraryPreferencePage_LibraryNameDialog_name_label;
- public static String UserLibraryPreferencePage_LibraryNameDialog_issystem_label;
- public static String UserLibraryPreferencePage_LibraryNameDialog_name_error_entername;
- public static String UserLibraryPreferencePage_LibraryNameDialog_name_error_exists;
- public static String UserLibraryPreferencePage_LibraryNameDialog_name_error_invalid;
- public static String UserLibraryPreferencePage_LoadSaveDialog_save_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_save_ok_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_load_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_label;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_button;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_selectall_button;
- public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_message;
- public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_multiple_message;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_deselectall_button;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_save_label;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_load_label;
- public static String UserLibraryPreferencePage_LoadSaveDialog_filedialog_save_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_filedialog_load_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_error_empty;
- public static String UserLibraryPreferencePage_LoadSaveDialog_error_invalidfile;
- public static String UserLibraryPreferencePage_LoadSaveDialog_overwrite_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_save_ok_message;
- public static String UserLibraryPreferencePage_LoadSaveDialog_overwrite_message;
- public static String UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_title;
- public static String UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_message;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_save_enterlocation;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_save_invalid;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_error_save_nothingselected;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_load_enterlocation;
- public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_load_invalid;
- public static String UserLibraryPreferencePage_LoadSaveDialog_list_error_load_nothingselected;
- public static String UserLibraryPreferencePage_LoadSaveDialog_load_badformat;
- public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_title;
- public static String UserLibraryPreferencePage_browsefolder_new_title;
- public static String UserLibraryPreferencePage_browsefolder_new_message;
- public static String EditTemplateDialog_error_noname;
- public static String EditTemplateDialog_error_spaces;
- public static String EditTemplateDialog_title_new;
- public static String EditTemplateDialog_title_edit;
- public static String EditTemplateDialog_name;
- public static String EditTemplateDialog_description;
- public static String EditTemplateDialog_context;
- public static String EditTemplateDialog_pattern;
- public static String EditTemplateDialog_insert_variable;
- public static String EditTemplateDialog_undo;
- public static String EditTemplateDialog_cut;
- public static String EditTemplateDialog_copy;
- public static String EditTemplateDialog_paste;
- public static String EditTemplateDialog_select_all;
- public static String EditTemplateDialog_content_assist;
- public static String JavaEditorPreferencePage_folding_title;
- public static String FoldingConfigurationBlock_enable;
- public static String FoldingConfigurationBlock_combo_caption;
- public static String FoldingConfigurationBlock_info_no_preferences;
- public static String FoldingConfigurationBlock_error_not_exist;
- public static String FoldingConfigurationBlock_warning_providerNotFound_resetToDefault;
- public static String SmartTypingConfigurationBlock_autoclose_title;
- public static String SmartTypingConfigurationBlock_automove_title;
- public static String SmartTypingConfigurationBlock_tabs_title;
- public static String SmartTypingConfigurationBlock_tabs_message_tab_text;
- public static String SmartTypingConfigurationBlock_tabs_message_others_text;
- public static String SmartTypingConfigurationBlock_tabs_message_tooltip;
- public static String SmartTypingConfigurationBlock_tabs_message_spaces;
- public static String SmartTypingConfigurationBlock_tabs_message_tabs;
- public static String SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces;
- public static String SmartTypingConfigurationBlock_pasting_title;
- public static String SmartTypingConfigurationBlock_strings_title;
- public static String CodeAssistConfigurationBlock_sortingSection_title;
- public static String CodeAssistConfigurationBlock_autoactivationSection_title;
- public static String CodeAssistConfigurationBlock_insertionSection_title;
- public static String JavaEditorPreferencePage_coloring_category_java;
- public static String JavaEditorPreferencePage_coloring_category_javadoc;
- public static String JavaEditorPreferencePage_coloring_category_comments;
- public static String ProjectSelectionDialog_title;
- public static String ProjectSelectionDialog_desciption;
- public static String ProjectSelectionDialog_filter;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, PreferencesMessages.class);
- }
-
- public static String NameConventionConfigurationBlock_use_override_annotation_label;
- public static String ProblemSeveritiesConfigurationBlock_pb_unhandled_surpresswarning_tokens;
- public static String ProblemSeveritiesConfigurationBlock_pb_enable_surpresswarning_annotation;
- public static String SmartTypingConfigurationBlock_annotationReporting_link;
- public static String CodeAssistConfigurationBlock_restricted_link;
- public static String CodeAssistConfigurationBlock_hideDiscouraged_label;
- public static String CodeAssistConfigurationBlock_hideForbidden_label;
- public static String UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_up_button;
- public static String UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_down_button;
- public static String EditTemplateDialog_autoinsert;
- public static String ComplianceConfigurationBlock_jrecompliance_info;
- public static String ComplianceConfigurationBlock_jrecompliance_info_project;
- public static String ProblemSeveritiesConfigurationBlock_section_generics;
- public static String JavaBasePreferencePage_dialogs;
- public static String JavaBasePreferencePage_do_not_hide_description;
- public static String JavaBasePreferencePage_do_not_hide_button;
- public static String JavaBasePreferencePage_do_not_hide_dialog_title;
- public static String JavaBasePreferencePage_do_not_hide_dialog_message;
- public static String CodeAssistConfigurationBlock_matchCamelCase_label;
- public static String ComplianceConfigurationBlock_version16;
- public static String ComplianceConfigurationBlock_src_greater_compliance;
- public static String ComplianceConfigurationBlock_classfile_greater_compliance;
- public static String ComplianceConfigurationBlock_classfile_greater_source;
- public static String ProblemSeveritiesConfigurationBlock_pb_parameter_assignment;
- public static String ProblemSeveritiesConfigurationBlock_pb_null_reference;
- public static String ProblemSeveritiesConfigurationBlock_pb_potential_null_reference;
- public static String ProblemSeveritiesConfigurationBlock_pb_duplicate_local_variables;
- public static String ProblemSeveritiesConfigurationBlock_pb_fall_through_case;
- public static String CodeAssistConfigurationBlock_hideDeprecated_label;
- public static String ProblemSeveritiesconfigurationBlock_pb_uninitialized_local_variable;
- public static String ProblemSeveritiesconfigurationBlock_pb_uninitialized_global_variable;
-
- public static String CodeAssistStaticMembersConfigurationBlock_description;
- public static String CodeAssistStaticMembersConfigurationBlock_newType_button;
- public static String CodeAssistStaticMembersConfigurationBlock_newMember_button;
- public static String CodeAssistStaticMembersConfigurationBlock_edit_button;
- public static String CodeAssistStaticMembersConfigurationBlock_remove_button;
-
- public static String FavoriteStaticMemberInputDialog_member_title;
- public static String FavoriteStaticMemberInputDialog_member_labelText;
- public static String FavoriteStaticMemberInputDialog_type_title;
- public static String FavoriteStaticMemberInputDialog_type_labelText;
- public static String FavoriteStaticMemberInputDialog_browse_button;
- public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_title;
- public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_description;
- public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message;
- public static String FavoriteStaticMemberInputDialog_error_enterName;
- public static String FavoriteStaticMemberInputDialog_error_invalidMemberName;
- public static String FavoriteStaticMemberInputDialog_error_invalidTypeName;
- public static String FavoriteStaticMemberInputDialog_error_entryExists;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties
deleted file mode 100644
index f56806a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties
+++ /dev/null
@@ -1,911 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2010 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-# John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
-# Sebastian Davids, sdavids@gmx.de - 187316 [preferences] Mark Occurences Pref Page; Link to
-###############################################################################
-
-
-BuildPathsPropertyPage_error_message=An error occurred while setting the include path
-BuildPathsPropertyPage_error_title=Error Setting Include Path
-BuildPathsPropertyPage_job_title=Setting include path
-BuildPathsPropertyPage_no_java_project_message=Not a JavaScript project.
-BuildPathsPropertyPage_closed_project_message=JavaScript information is not available for a closed project.
-
-BuildPathsPropertyPage_unsavedchanges_title=Setting JavaScript Include Path
-BuildPathsPropertyPage_unsavedchanges_message=The JavaScript Include path property page contains unsaved modifications. Do you want to save changes so that other include path related property pages can be updated?
-BuildPathsPropertyPage_unsavedchanges_button_save=Apply
-BuildPathsPropertyPage_unsavedchanges_button_discard=Discard
-BuildPathsPropertyPage_unsavedchanges_button_ignore=Apply Later
-
-ClasspathVariablesPreferencePage_title=Include Path Variables
-ClasspathVariablesPreferencePage_description=A include path variable can be added to a project's include path.
-
-ClasspathVariablesPreferencePage_savechanges_title=Includepath Variables
-ClasspathVariablesPreferencePage_savechanges_message=Do you want to apply the changes to the include path variables now? Your changes will be lost if another page modifies the include variables as well.
-
-ImportOrganizePreferencePage_description=Preferences used by the Organize Imports action:
-ImportOrganizePreferencePage_title=Organize Imports
-
-ImportOrganizeConfigurationBlock_order_label=Define the &sorting order of import statements. A package or type name prefix (e.g. org.eclipse) is a valid entry. An import is always added to the most specific group.
-ImportOrganizeConfigurationBlock_other_static=* - all unmatched static imports
-ImportOrganizeConfigurationBlock_other_normal=* - all unmatched type imports
-ImportOrganizeConfigurationBlock_other_normal_label=Enable 'Other' group
-ImportOrganizeConfigurationBlock_order_add_button=&New...
-ImportOrganizeConfigurationBlock_order_edit_button=&Edit...
-ImportOrganizeConfigurationBlock_order_up_button=&Up
-ImportOrganizeConfigurationBlock_order_down_button=Do&wn
-ImportOrganizeConfigurationBlock_order_remove_button=&Remove
-ImportOrganizeConfigurationBlock_order_add_static_button=New Stati&c...
-ImportOrganizeConfigurationBlock_order_load_button=I&mport...
-ImportOrganizeConfigurationBlock_order_save_button=E&xport...
-ImportOrganizeConfigurationBlock_other_description=Group all import not covered by all other groups:
-ImportOrganizeConfigurationBlock_ignoreLowerCase_label=Do not create imports for &types starting with a lowercase letter
-ImportOrganizeConfigurationBlock_threshold_label=Number of &imports needed for .* (e.g. 'org.eclipse.*'):
-ImportOrganizeConfigurationBlock_error_invalidthreshold=Invalid import number.
-ImportOrganizeConfigurationBlock_error_invalidnumberofemptylines=Invalid number of empty lines between groups
-ImportOrganizeConfigurationBlock_loadDialog_title=Load Import Order from File
-ImportOrganizeConfigurationBlock_loadDialog_error_title=Load Import Order
-ImportOrganizeConfigurationBlock_loadDialog_error_message=Importing failed. Not a valid import order file.
-ImportOrganizeConfigurationBlock_saveDialog_title=Save Import Order to File
-ImportOrganizeConfigurationBlock_saveDialog_error_title=Save Import Order
-ImportOrganizeConfigurationBlock_staticthreshold_label=Number of &static imports needed for .* (e.g. 'java.lang.Math.*'):
-ImportOrganizeConfigurationBlock_saveDialog_error_message=Exporting import order file failed.
-ImportOrganizeConfigurationBlock_emptylines_between_groups_label=Empt&y lines between import groups:
-ImportOrganizeInputDialog_title=Import Group
-ImportOrganizeInputDialog_browse_packages_button=&Packages...
-ImportOrganizeInputDialog_browse_types_label=&Types...
-ImportOrganizeInputDialog_title_static=Static Import Group
-ImportOrganizeInputDialog_ChoosePackageDialog_title=Package Selection
-ImportOrganizeInputDialog_ChoosePackageDialog_description=Choose package name or package prefix:
-ImportOrganizeInputDialog_ChoosePackageDialog_empty=No packages available.
-ImportOrganizeInputDialog_ChooseTypeDialog_title=Type Selection
-ImportOrganizeInputDialog_ChooseTypeDialog_description=Choose type name:
-ImportOrganizeInputDialog_ChooseTypeDialog_error_message=A problem occurred while collecting types. Check log for more details.
-
-ImportOrganizeInputDialog_error_enterName=Enter a name or prefix.
-ImportOrganizeInputDialog_error_invalidName=Not a valid type or package name.
-ImportOrganizeInputDialog_error_entryExists=Entry already exists in list.
-ImportOrganizeInputDialog_name_group_label=Enter a prefix (e.g. 'org.eclipse') or '*' to match all imports:
-ImportOrganizeInputDialog_name_group_static_label=Enter a prefix (e.g. 'org.eclipse') or '*' to match all imports:
-JavaBasePreferencePage_description=General settings for JavaScript development:
-
-JavaBasePreferencePage_doubleclick_action=Action on double click in the Script and Project Explorers
-JavaBasePreferencePage_doubleclick_gointo=&Go into the selected element
-JavaBasePreferencePage_doubleclick_expand=E&xpand the selected element
-JavaBasePreferencePage_do_not_hide_button=&Clear
-
-JavaBasePreferencePage_refactoring_title= Refactoring JavaScript code
-JavaBasePreferencePage_refactoring_auto_save= &Save all modified resources automatically prior to refactoring
-JavaBasePreferencePage_refactoring_lightweight=Rename in editor &without dialog
-JavaBasePreferencePage_do_not_hide_description=Clear all 'do not show again' settings and show all hidden dialogs again
-JavaBasePreferencePage_do_not_hide_dialog_title=Hidden Dialogs
-JavaBasePreferencePage_do_not_hide_dialog_message=All 'do not ask again' settings for JavaScript dialogs cleared. Hidden dialogs will be shown again.
-
-JavaBasePreferencePage_search= Search
-JavaBasePreferencePage_search_small_menu=Use &reduced search menu
-
-NewJavaProjectPreferencePage_title=New Project
-NewJavaProjectPreferencePage_description=Specify the JavaScript global context root used as default by the New JavaScript Project creation wizard:
-
-NewJavaProjectPreferencePage_sourcefolder_label=JavaScript global context root
-NewJavaProjectPreferencePage_sourcefolder_project=&Project
-NewJavaProjectPreferencePage_sourcefolder_folder=&Folder
-NewJavaProjectPreferencePage_folders_src=&Root folder name:
-
-
-NewJavaProjectPreferencePage_folders_error_namesempty=Enter folder names.
-NewJavaProjectPreferencePage_folders_error_invalidsrcname=Invalid source folder name: {0}
-NewJavaProjectPreferencePage_folders_error_invalidcp=Settings will result in an invalid include path. Check for nested folders.
-
-NewJavaProjectPreferencePage_error_decode=Error while decoding JRE entry
-
-JavaEditorPreferencePage_showQuickFixables= Indicate annotations solvable with &Quick Fix in vertical ruler
-JavaEditorPreferencePage_analyseAnnotationsWhileTyping= Report &problems as you type
-
-JavaEditorPreferencePage_multiLineComment=Multi-line comment
-JavaEditorPreferencePage_singleLineComment=Single-line comment
-JavaEditorPreferencePage_returnKeyword= Keyword 'return'
-JavaEditorPreferencePage_keywords=Keywords excluding 'return'
-JavaEditorPreferencePage_strings=Strings
-JavaEditorPreferencePage_others=Others
-JavaEditorPreferencePage_operators=Operators
-JavaEditorPreferencePage_brackets=Brackets
-JavaEditorPreferencePage_javaCommentTaskTags=Task Tags
-JavaEditorPreferencePage_javaDocKeywords=Tags
-JavaEditorPreferencePage_javaDocHtmlTags=HTML markup
-JavaEditorPreferencePage_javaDocLinks=Links
-JavaEditorPreferencePage_javaDocOthers=Others
-JavaEditorPreferencePage_backgroundColor=Background color
-JavaEditorPreferencePage_systemDefault=&System Default
-JavaEditorPreferencePage_custom=C&ustom:
-JavaEditorPreferencePage_semanticHighlighting_option= &Enable advanced coloring
-JavaEditorPreferencePage_foreground=Ele&ment:
-JavaEditorPreferencePage_color=C&olor:
-JavaEditorPreferencePage_bold=&Bold
-JavaEditorPreferencePage_italic=&Italic
-JavaEditorPreferencePage_strikethrough=&Strikethrough
-JavaEditorPreferencePage_underline=&Underline
-JavaEditorPreferencePage_enable=Enab&le
-JavaEditorPreferencePage_preview=Previe&w:
-JavaEditorPreferencePage_displayedTabWidth=Displayed &tab width:
-JavaEditorPreferencePage_insertSpaceForTabs=Ins&ert spaces for tab (see Code Formatter preference page)
-JavaEditorPreferencePage_showOverviewRuler=Show overview &ruler
-JavaEditorPreferencePage_highlightMatchingBrackets=Highlight &matching brackets
-JavaEditorPreferencePage_highlightCurrentLine=Highlight &current line
-JavaEditorPreferencePage_showPrintMargin=Sho&w print margin
-JavaEditorPreferencePage_printMarginColumn=&Print margin column:
-JavaEditorPreferencePage_insertSingleProposalsAutomatically=Insert single &proposals automatically
-JavaEditorPreferencePage_showOnlyProposalsVisibleInTheInvocationContext=Hide proposals &not visible in the invocation context
-JavaEditorPreferencePage_presentProposalsInAlphabeticalOrder=&Sort proposals
-JavaEditorPreferencePage_coloring_element=&Element:
-JavaEditorPreferencePage_enableAutoActivation=&Enable auto activation
-#JavaEditorPreferencePage_automaticallyAddImportInsteadOfQualifiedName=Add import instead of qua&lified name
-#JavaEditorPreferencePage_suggestStaticImports=&Use static imports (only 5.0 or higher)
-JavaEditorPreferencePage_completionInserts=Completion inser&ts
-JavaEditorPreferencePage_completionOverwrites=Completion over&writes
-JavaEditorPreferencePage_completionToggleHint=Press 'Ctrl' to toggle while content assist is active
-JavaEditorPreferencePage_fillArgumentNamesOnMethodCompletion=&Fill argument names on completion
-JavaEditorPreferencePage_guessArgumentNamesOnMethodCompletion=&Guess filled function arguments
-JavaEditorPreferencePage_autoActivationDelay=A&uto activation delay:
-JavaEditorPreferencePage_autoActivationTriggersForJava=Auto activation triggers for &JavaScript:
-JavaEditorPreferencePage_autoActivationTriggersForJavaDoc=Auto activation triggers for JSD&oc:
-JavaEditorPreferencePage_completePrefixes= &Insert common prefixes automatically
-
-JavaEditorPreferencePage_backgroundForCompletionProposals= Completion proposal background
-JavaEditorPreferencePage_foregroundForCompletionProposals= Completion proposal foreground
-JavaEditorPreferencePage_backgroundForMethodParameters= Parameter hints background
-JavaEditorPreferencePage_foregroundForMethodParameters= Parameter hints foreground
-JavaEditorPreferencePage_backgroundForCompletionReplacement= Completion overwrite background
-JavaEditorPreferencePage_foregroundForCompletionReplacement= Completion overwrite foreground
-JavaEditorPreferencePage_sourceHoverBackgroundColor= Source hover background
-
-JavaEditorPreferencePage_general=Appeara&nce
-JavaEditorPreferencePage_colors=Synta&x
-JavaEditorPreferencePage_empty_input=Empty input
-JavaEditorPreferencePage_invalid_input=''{0}'' is not a valid input.
-JavaEditorPreferencePage_showLineNumbers=Show lin&e numbers
-JavaEditorPreferencePage_lineNumberForegroundColor=Line number foreground
-JavaEditorPreferencePage_matchingBracketsHighlightColor2=Matching brackets highlight
-JavaEditorPreferencePage_currentLineHighlighColor=Current line highlight
-JavaEditorPreferencePage_printMarginColor2=Print margin
-JavaEditorPreferencePage_appearanceOptions=Appearance co&lor options:
-
-JavaEditorPreferencePage_typing_tabTitle=T&yping
-JavaEditorPreferencePage_typing_description= Enable these typing aids in Smart Insert mode:
-JavaEditorPreferencePage_closeStrings= "&Strings"
-JavaEditorPreferencePage_closeBrackets= (Parentheses), [square] and <angle> brac&kets
-JavaEditorPreferencePage_closeBraces= {B&races}
-JavaEditorPreferencePage_closeJavaDocs= JSD&oc and comment regions
-JavaEditorPreferencePage_wrapStrings= &Wrap automatically
-JavaEditorPreferencePage_escapeStrings= Escape text w&hen pasting into a string literal
-JavaEditorPreferencePage_addJavaDocTags= Add &JSDoc tags
-JavaEditorPreferencePage_smartPaste= Adjust &indentation
-JavaEditorPreferencePage_link=JavaScript editor preferences. Note that some preferences may be set on the <a>Text Editors</a> preference page.
-JavaEditorPreferencePage_link_tooltip=Show the shared text editor preferences
-JavaEditorPreferencePage_importsOnPaste=&Update imports
-JavaEditorPreferencePage_subWordNavigation= Smart &caret positioning in JavaScript names (overrides platform behavior)
-JavaEditorPreferencePage_typing_smartSemicolon= Se&micolons
-JavaEditorPreferencePage_typing_smartOpeningBrace= &Braces
-JavaEditorPreferencePage_typing_smartTab= &Tab key adjusts the indentation of the current line
-JavaEditorPropertyPage_SaveActionLink_Text=The actions to execute when the JavaScript Editor is saved can be configured on to the <a>Save Action</a> property page.
-
-# DO NOT TRANSLATE "org.eclipse.ui.preferencePages.GeneralTextEditor", "org.eclipse.ui.preferencePages.ColorsAndFonts", and "org.eclipse.ui.editors.preferencePages.Annotations"
-JavaEditorColoringConfigurationBlock_link= Default colors and font can be configured on the <a href=\"org.eclipse.ui.preferencePages.GeneralTextEditor\">Text Editors</a> and on the <a href=\"org.eclipse.ui.preferencePages.ColorsAndFonts\">Colors and Fonts</a> preference pages. Decorations for annotations can be configured on the <a href=\"org.eclipse.ui.editors.preferencePages.Annotations\">Annotations</a> preference page.
-
-JavaEditorPreferencePage_hoverTab_title= Ho&vers
-
-JavaBasePreferencePage_dialogs=JavaScript dialogs
-
-JavaEditorPreferencePage_quickassist_lightbulb=L&ight bulb for quick assists
-JavaEditorPreferencePage_showJavaElementOnly= O&nly show the selected JavaScript element
-
-JavaEditorPreferencePage_accessibility_disableCustomCarets= &Use custom caret
-JavaEditorPreferencePage_accessibility_wideCaret= Enable thic&k caret
-
-JavaEditorHoverConfigurationBlock_annotationRollover= &Expand vertical ruler icons upon hovering (does not affect open editors)
-JavaEditorHoverConfigurationBlock_hoverPreferences= Text &Hover key modifier preferences:
-JavaEditorHoverConfigurationBlock_enabled= &Enabled
-JavaEditorHoverConfigurationBlock_keyModifier= Pressed key &modifier while hovering:
-JavaEditorHoverConfigurationBlock_description= Descriptio&n:
-JavaEditorHoverConfigurationBlock_modifierIsNotValid= Modifier ''{0}'' is not valid.
-JavaEditorHoverConfigurationBlock_modifierIsNotValidForHover= Modifier ''{0}'' for ''{1}'' hover is not valid.
-JavaEditorHoverConfigurationBlock_duplicateModifier= ''{0}'' hover uses the same modifier as ''{1}'' hover.
-JavaEditorHoverConfigurationBlock_nameColumnTitle= Text Hover Name
-JavaEditorHoverConfigurationBlock_modifierColumnTitle= Pressed Key Modifier While Hovering
-
-JavaEditorHoverConfigurationBlock_delimiter= +
-JavaEditorHoverConfigurationBlock_insertDelimiterAndModifierAndDelimiter= \ + {0} +
-JavaEditorHoverConfigurationBlock_insertModifierAndDelimiter= \ {0} +
-JavaEditorHoverConfigurationBlock_insertDelimiterAndModifier= \ + {0}
-
-MarkOccurrencesConfigurationBlock_title= &Mark Occurrences
-
-# DO NOT TRANSLATE "org.eclipse.ui.editors.preferencePages.Annotations"
-MarkOccurrencesConfigurationBlock_link= The appearance can be configured on the <a href=\"org.eclipse.ui.editors.preferencePages.Annotations\">Annotations</a> preference page.
-
-MarkOccurrencesConfigurationBlock_link_tooltip=Show the annotations preferences
-MarkOccurrencesConfigurationBlock_markOccurrences= Mark &occurrences of the selected element in the current file.
-#MarkOccurrencesConfigurationBlock_markTypeOccurrences= &Types
-MarkOccurrencesConfigurationBlock_markMethodOccurrences= &Functions
-MarkOccurrencesConfigurationBlock_markConstantOccurrences= &Constants
-#MarkOccurrencesConfigurationBlock_markFieldOccurrences= &Non-constant fields
-MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences= &Local variables
-#MarkOccurrencesConfigurationBlock_markExceptionOccurrences= E&xpressions throwing a declared exception
-MarkOccurrencesConfigurationBlock_markMethodExitPoints= Function &exits
-#MarkOccurrencesConfigurationBlock_markImplementors= Functions implementing an &interface
-MarkOccurrencesConfigurationBlock_markBreakContinueTargets= Targets of &break and continue statements
-MarkOccurrencesConfigurationBlock_stickyOccurrences= &Keep marks when the selection changes
-
-JavaElementInfoPage_binary=binary
-JavaElementInfoPage_classpath_entry_kind=Classpath entry kind:
-JavaElementInfoPage_library=library
-JavaElementInfoPage_nameLabel=Name:
-JavaElementInfoPage_not_present=not present
-JavaElementInfoPage_package=Package:
-JavaElementInfoPage_package_contents=Package contents:
-JavaElementInfoPage_project=project
-JavaElementInfoPage_resource_path=Resource path:
-JavaElementInfoPage_source=source
-JavaElementInfoPage_variable=variable
-JavaElementInfoPage_variable_path=Variable path:
-JavaElementInfoPage_location=Location:
-
-JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description=Specify the location (URL) of the documentation generated by JSDoc. The JSDoc location will contain a file called 'package-list'.
-JavadocConfigurationBlock_workspace_archive_selection_dialog_title=JSDoc Archive Selection Dialog
-JavadocConfigurationBlock_workspace_archive_selection_dialog_description=&Choose the archive containing the documentation
-JavadocConfigurationPropertyPage_IsIncorrectElement_description=JSDoc location can only be attached to JavaScript projects or archives and class folders in JavaScript projects. Source folders use the location specified at their project.
-JavadocConfigurationPropertyPage_IsJavaProject_description=Specify the location of the project\'s JSDoc documentation. This location is used by the JSDoc export wizard as the default value and by the \'Open External JSDoc\' action. For example: \'file:/c:/myworkspace/myproject/doc\'.
-JavadocConfigurationPropertyPage_invalid_container=The current class path entry belongs to container ''{0}'' which can not be configured.
-JavadocConfigurationPropertyPage_not_supported=The current class path entry belongs to container ''{0}'' which does not support the attachment of Javadoc to its entries.
-
-JavadocConfigurationBlock_browse_archive_button=&Browse...
-JavadocConfigurationBlock_error_notafolder=Location does not exist.
-JavadocConfigurationPropertyPage_read_only=The current class path entry belongs to container ''{0}'' which does not allow user modifications to Javadoc locations on its entries.
-JavadocConfigurationBlock_javadocFolderDialog_label=JSDoc Location Selection
-JavadocConfigurationBlock_javadocFolderDialog_message=Select JSDoc location:
-JavadocConfigurationBlock_MalformedURL_error=Invalid URL
-JavadocConfigurationBlock_validate_button=&Validate...
-JavadocConfigurationBlock_workspace_radio=Wor&kspace file
-JavadocConfigurationBlock_InvalidLocation_message=Location might be invalid. Files 'package-list' and 'index.html' that are typically available at the root of documentation created by the JSDoc tool have not been found.
-JavadocConfigurationBlock_ValidLocation_message=Location is likely valid. Files 'package-list' and 'index.html' have been found. Open the location in your browser?
-JavadocConfigurationBlock_UnableToValidateLocation_message=Cannot validate JSDoc location.
-JavadocConfigurationBlock_MessageDialog_title=Validating JSDoc Location
-JavadocConfigurationBlock_location_type_path_label=JSDoc &URL (e.g. 'http://www.sample-url.org/doc/' or 'file:/c:/myworkspace/myproject/doc')
-JavadocConfigurationBlock_location_type_jar_label=JSDoc in ar&chive
-JavadocConfigurationBlock_location_path_label=&JSDoc location path:
-JavadocConfigurationBlock_location_jar_label=Archive &path:
-JavadocConfigurationBlock_jar_path_label=Path &within archive:
-JavadocConfigurationBlock_zipImportSource_title=JSDoc Archive Selection
-JavadocConfigurationBlock_location_in_jarorzip_message=&Select the folder that is the root of the JSDoc documentation:
-JavadocConfigurationBlock_browse_jarorzip_path_title=JSDoc Root Location
-JavadocConfigurationBlock_browse_archive_path_button=Br&owse...
-JavadocConfigurationBlock_browse_folder_button=&Browse...
-JavadocConfigurationBlock_error_notafile=Archive can not be found in file system
-JavadocConfigurationBlock_external_radio=E&xternal file
-JavadocConfigurationBlock_error_invalidarchivepath=Archive path is not a valid path.
-JavadocConfigurationBlock_error_archivepathnotabsolute=Archive path must be an absolute path.
-JavadocConfigurationBlock_error_archive_not_found_in_workspace=Archive can not be found in workspace
-
-SourceAttachmentPropertyPage_error_title=Error Attaching Source
-SourceAttachmentPropertyPage_read_only=The current class path entry belongs to container ''{0}'' which does not allow user modifications to source attachments on its entries.
-SourceAttachmentPropertyPage_error_message=An error occurred while associating the source
-SourceAttachmentPropertyPage_not_supported=The current class path entry belongs to container ''{0}'' which does not support the attachment of sources to its entries.
-SourceAttachmentPropertyPage_noarchive_message=Source can only be attached to archive and class folders in JavaScript projects.
-SourceAttachmentPropertyPage_invalid_container=The current class path entry belongs to container ''{0}'' which can not be configured.
-SourceAttachmentPropertyPage_containerentry_message=JAR belongs to the container ''{0}''.\nTo configure the source attachment, go directly to the corresponding configuration page (For example for JREs go to ''Installed JREs'' page in the preferences).
-
-
-AppearancePreferencePage_description= Appearance of JavaScript elements in viewers:
-#AppearancePreferencePage_methodreturntype_label= Show &function return types
-AppearancePreferencePage_inferredmethodreturntype_label= Show inferred &function return types
-#AppearancePreferencePage_methodtypeparams_label=Show function type pa&rameters
-AppearancePreferencePage_showCategory_label=Show categ&ories
-#AppearancePreferencePage_pkgNamePatternEnable_label= &Compress all package name segments, except the final segment
-#AppearancePreferencePage_pkgNamePattern_label= Com&pression pattern (e.g. given package name 'org.eclipse.wst.jsdt' pattern '.' will compress it to '..jdt', '0' to 'jdt', '1~.' to 'o~.e~.jdt'):
-AppearancePreferencePage_coloredlabels_label=Sho&w colored labels
-AppearancePreferencePage_showMembersInPackagesView=S&how members in Script and Project Explorers
-AppearancePreferencePage_stackViewsVerticallyInTheJavaBrowsingPerspective=&Stack views vertically in the JavaScript Browsing perspective
-#AppearancePreferencePage_note=Note:
-#AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives=This preference will only take effect on new perspectives
-AppearancePreferencePage_packageNameCompressionPattern_error_isEmpty=Enter a package name compression pattern
-#AppearancePreferencePage_foldEmptyPackages= &Fold empty packages in hierarchical Script Explorer layout
-AppearancePreferencePage_foldEmptySourceFolders= &Fold empty source folders in hierarchical Script and Project Explorer layouts
-
-CodeFormatterPreferencePage_title=Code Formatter
-CodeFormatterPreferencePage_description=Sele&ct a profile:
-
-
-TodoTaskPreferencePage_title=Task Tags
-TodoTaskPreferencePage_description=&Strings indicating tasks in JavaScript comments. The entry marked as default will be used in the code templates.
-
-TodoTaskConfigurationBlock_markers_tasks_high_priority=High
-TodoTaskConfigurationBlock_markers_tasks_normal_priority=Normal
-TodoTaskConfigurationBlock_markers_tasks_low_priority=Low
-TodoTaskConfigurationBlock_markers_tasks_add_button=&New...
-TodoTaskConfigurationBlock_markers_tasks_remove_button=&Remove
-TodoTaskConfigurationBlock_markers_tasks_edit_button=&Edit...
-TodoTaskConfigurationBlock_markers_tasks_name_column=Tag
-TodoTaskConfigurationBlock_markers_tasks_priority_column=Priority
-TodoTaskConfigurationBlock_markers_tasks_setdefault_button=Defa&ult
-TodoTaskConfigurationBlock_casesensitive_label=&Case sensitive task tag names
-
-TodoTaskConfigurationBlock_needsbuild_title=Task Tags Settings Changed
-TodoTaskConfigurationBlock_tasks_default={0} (default)
-TodoTaskConfigurationBlock_needsfullbuild_message=The task tags settings have changed. A full rebuild is required to for changes to take effect. Do the full build now?
-TodoTaskConfigurationBlock_needsprojectbuild_message=The task tags settings have changed. A rebuild of the project is required for changes to take effect. Build the project now?
-
-TodoTaskInputDialog_new_title=New Task Tag
-TodoTaskInputDialog_edit_title=Edit Task Tag
-TodoTaskInputDialog_name_label=T&ag:
-TodoTaskInputDialog_priority_label=&Priority:
-TodoTaskInputDialog_priority_high=High
-TodoTaskInputDialog_priority_normal=Normal
-TodoTaskInputDialog_priority_low=Low
-TodoTaskInputDialog_error_enterName=Enter task tag name.
-TodoTaskInputDialog_error_comma=Name cannot contain a comma.
-TodoTaskInputDialog_error_entryExists=An entry with the same name already exists.
-TodoTaskInputDialog_error_noSpace=Name cannot begin or end with a whitespace.
-
-PropertyAndPreferencePage_useworkspacesettings_change=Configure Workspace Settings...
-PropertyAndPreferencePage_showprojectspecificsettings_label=Configure Project Specific Settings...
-PropertyAndPreferencePage_useprojectsettings_label=Enable pr&oject specific settings
-
-JavaBuildPreferencePage_title=Builder
-JavaBuildPreferencePage_description=Options for the JavaScript compiler:\nNote that a full rebuild is required for changes to take effect.
-
-JavaBuildConfigurationBlock_section_general=&General
-JavaBuildConfigurationBlock_section_output_folder=Out&put folder
-JavaBuildConfigurationBlock_section_access_rules=A&ccess rule severities
-JavaBuildConfigurationBlock_section_include_path_problems=&Include path problems
-
-
-JavaBuildConfigurationBlock_error=Error
-JavaBuildConfigurationBlock_warning=Warning
-JavaBuildConfigurationBlock_ignore=Ignore
-
-JavaBuildConfigurationBlock_needsbuild_title=Building Settings Changed
-JavaBuildConfigurationBlock_needsfullbuild_message=The Building settings have changed. A full rebuild is required for changes to take effect. Do the full build now?
-ProblemSeveritiesConfigurationBlock_treat_optional_as_fatal=Treat errors like &fatal compiler errors (make compiled code not executable)
-JavaBuildConfigurationBlock_needsprojectbuild_message=The Building settings have changed. A rebuild of the project is required for changes to take effect. Build the project now?
-
-JavaBuildConfigurationBlock_resource_filter_description=Filtered resources are not be copied to the output folder during a build. List is comma separated (e.g. '*.doc, plugin.xml, scripts/')
-JavaBuildConfigurationBlock_resource_filter_label=Fi&ltered Resources:
-JavaBuildConfigurationBlock_build_invalid_classpath_label=Abo&rt build when include path errors occur
-JavaBuildConfigurationBlock_build_recreate_modified=Rebuild class files modified by others
-
-JavaBuildConfigurationBlock_build_clean_outputfolder_label=Scrub output folders &when cleaning projects
-JavaBuildConfigurationBlock_enable_exclusion_patterns_label=Enable use of e&xclusion patterns in source folders
-JavaBuildConfigurationBlock_enable_multiple_outputlocations_label=Enable use of m&ultiple output locations for source folders
-
-JavaBuildConfigurationBlock_pb_incomplete_build_path_label=I&ncomplete build path:
-ProblemSeveritiesConfigurationBlock_pb_discourraged_reference_label=Di&scouraged reference (access rules):
-JavaBuildConfigurationBlock_pb_build_path_cycles_label=Circular d&ependencies:
-JavaBuildConfigurationBlock_pb_duplicate_resources_label=Duplica&ted resources:
-ProblemSeveritiesConfigurationBlock_pb_forbidden_reference_label=&Forbidden reference (access rules):
-JavaBuildConfigurationBlock_pb_max_per_unit_label=&Maximum number of problems reported per JavaScript file:
-
-JavaBuildConfigurationBlock_pb_check_prereq_binary_level_label=In&compatible required binaries:
-
-JavaBuildConfigurationBlock_empty_input=Number of problems cannot be empty.
-JavaBuildConfigurationBlock_invalid_input={0} is not a valid number of problems.
-JavaBuildConfigurationBlock_filter_invalidsegment_error=Filter is invalid: {0}
-
-ProblemSeveritiesPreferencePage_title=Problem Severities
-
-ProblemSeveritiesConfigurationBlock_error=Error
-ProblemSeveritiesConfigurationBlock_warning=Warning
-ProblemSeveritiesConfigurationBlock_ignore=Ignore
-
-ProblemSeveritiesConfigurationBlock_section_potential_programming_problems=&Potential programming problems
-ProblemSeveritiesConfigurationBlock_section_unnecessary_code=&Unnecessary code
-ProblemSeveritiesConfigurationBlock_section_nls=String e&xternalization
-ProblemSeveritiesConfigurationBlock_Resolution=&Resolution
-ProblemSeveritiesConfigurationBlock_section_code_style=&Code style
-ProblemSeveritiesConfigurationBlock_section_generics=&Generic types
-ProblemSeveritiesConfigurationBlock_section_deprecations=D&eprecated and restricted API
-ProblemSeveritiesConfigurationBlock_section_name_shadowing=Name &shadowing and conflicts
-ProblemSeveritiesConfigurationBlock_section_annotations=A&nnotations
-ProblemSeveritiesConfigurationBlock_needsbuild_title=Error/Warning Settings Changed
-ProblemSeveritiesConfigurationBlock_UnresolvedTypes=Unresolved Types
-ProblemSeveritiesConfigurationBlock_UnresolvedFields=Unresolved Fields
-ProblemSeveritiesConfigurationBlock_needsfullbuild_message=The Error/Warning settings have changed. A full rebuild is required for changes to take effect. Do the full build now?
-ProblemSeveritiesConfigurationBlock_needsprojectbuild_message=The Error/Warning settings have changed. A rebuild of the project is required for changes to take effect. Build the project now?
-
-ProblemSeveritiesConfigurationBlock_common_description=Select the severity level for the following optional JavaScript validator problems:
-ProblemSeveritiesConfigurationBlock_pb_unsafe_type_op_label=Unchecked generic type operation:
-ProblemSeveritiesConfigurationBlock_pb_raw_type_reference=Usage of a raw type:
-ProblemSeveritiesConfigurationBlock_pb_final_param_bound_label=Generic t&ype parameter declared with a final type bound:
-ProblemSeveritiesConfigurationBlock_pb_inexact_vararg_label=Inexact type &match for vararg arguments:
-
-ProblemSeveritiesConfigurationBlock_pb_accidential_assignement_label=Po&ssible accidental boolean assignment (e.g. 'if (a = b)'):
-ProblemSeveritiesConfigurationBlock_pb_local_variable_hiding_label=Local &variable declaration hides another field or variable:
-ProblemSeveritiesConfigurationBlock_pb_field_hiding_label=Field declaration &hides another field or variable:
-ProblemSeveritiesConfigurationBlock_pb_special_param_hiding_label=Include constructor or setter function parameters
-ProblemSeveritiesConfigurationBlock_pb_unqualified_field_access_label=Un&qualified access to instance field:
-ProblemSeveritiesConfigurationBlock_pb_finally_block_not_completing_label='&finally' does not complete normally:
-ProblemSeveritiesConfigurationBlock_pb_undocumented_empty_block_label=Undocumented empty &block:
-ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_label=Unnecessary declaration of thrown checked exception:
-ProblemSeveritiesConfigurationBlock_pb_unhandled_surpresswarning_tokens=Unhandled warning token in '@SuppressWarnings':
-ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_when_overriding_label=Check overriding and implementing functions
-ProblemSeveritiesConfigurationBlock_pb_missing_serial_version_label=Seriali&zable class without serialVersionUID:
-
-ProblemSeveritiesConfigurationBlock_pb_undefined_field_label=Undefined Field:
-ProblemSeveritiesConfigurationBlock_pb_method_naming_label=&Function with a constructor name:
-ProblemSeveritiesConfigurationBlock_pb_no_effect_assignment_label=Assignmen&t has no effect (e.g. 'x = x'):
-ProblemSeveritiesConfigurationBlock_pb_incompatible_interface_method_label=Interface function conflicts &with protected 'Object' function:
-ProblemSeveritiesConfigurationBlock_pb_indirect_access_to_static_label=&Indirect access to static member:
-ProblemSeveritiesConfigurationBlock_pb_hidden_catchblock_label=Hidden catch bloc&k:
-ProblemSeveritiesConfigurationBlock_pb_static_access_receiver_label=&Non-static access to static member:
-ProblemSeveritiesConfigurationBlock_pb_unused_imports_label=Unused &import:
-ProblemSeveritiesConfigurationBlock_pb_unused_local_label=&Local variable is never read:
-ProblemSeveritiesConfigurationBlock_pb_unused_parameter_label=Parameter is never read:
-ProblemSeveritiesConfigurationBlock_pb_signal_param_in_overriding_label=Check overriding and implementing functions
-ProblemSeveritiesConfigurationBlock_pb_unused_private_label=Unused local or private member:
-ProblemSeveritiesConfigurationBlock_pb_parameter_assignment=Parameter assignment:
-ProblemSeveritiesConfigurationBlock_pb_redundant_null_check=Redundant null check:
-ProblemSeveritiesConfigurationBlock_pb_non_externalized_strings_label=Non-externalized strings (missing/unused $NON-NLS$ tag):
-ProblemSeveritiesConfigurationBlock_pb_deprecation_label=Deprecated API:
-ProblemSeveritiesConfigurationBlock_pb_deprecation_in_deprecation_label=Signal use of deprecated API inside deprecated code
-ProblemSeveritiesConfigurationBlock_pb_deprecation_when_overriding_label=Signal overriding or implementing deprecated function
-ProblemSeveritiesConfigurationBlock_pb_empty_statement_label=Empty statement:
-ProblemSeveritiesConfigurationBlock_LooselyDeclaredGlobalVar=Loosely Declared, Globally Scoped Variable Usage
-ProblemSeveritiesConfigurationBlock_pb_unnecessary_type_check_label=Unnecessary cast or 'instanceof' operation:
-ProblemSeveritiesConfigurationBlock_pb_incomplete_enum_switch_label=Enum type constant not covered on 'switch':
-ProblemSeveritiesConfigurationBlock_pb_null_reference=Null reference:
-ProblemSeveritiesConfigurationBlock_UnresolvedMethods=Unresolved Methods
-ProblemSeveritiesConfigurationBlock_Optionalsemicolon=Optional Semi-Colon
-ProblemSeveritiesConfigurationBlock_pb_potential_null_reference=Potential null pointer access:
-ProblemSeveritiesConfigurationBlock_pb_duplicate_local_variables=Duplicate local variables:
-ProblemSeveritiesConfigurationBlock_pb_fall_through_case='switch' case fall-through:
-ProblemSeveritiesConfigurationBlock_pb_unnecessary_else_label=Unnecessary 'else' statement:
-ProblemSeveritiesConfigurationBlock_pb_synth_access_emul_label=Access to a non-accessible member of an enclosing type:
-ProblemSeveritiesConfigurationBlock_pb_autoboxing_problem_label=Boxing and unboxing conversions:
-ProblemSeveritiesConfigurationBlock_pb_char_array_in_concat_label=Using a char array in string concatenation:
-ProblemSeveritiesConfigurationBlock_pb_missing_override_annotation_label=Missing '@Override' annotation:
-ProblemSeveritiesConfigurationBlock_pb_enable_surpresswarning_annotation=Enable '@SuppressWarnings' annotations
-ProblemSeveritiesConfigurationBlock_pb_missing_deprecated_annotation_label=Missing '@Deprecated' annotation:
-ProblemSeveritiesConfigurationBlock_pb_annotation_super_interface_label=Annotation is used as super interface:
-ProblemSeveritiesConfigurationBlock_ignore_documented_unused_parameters=Ignore parameters documented with '&@param' tag
-ProblemSeveritiesConfigurationBlock_enableSemanticValidation=Enable JavaScript se&mantic validation
-ProblemSeveritiesConfigurationBlock_pb_type_parameter_hiding_label=Type parameter hides another type:
-ProblemSeveritiesConfigurationBlock_pb_unused_label_label=Unused 'break' or 'continue' label:
-ProblemSeveritiesconfigurationBlock_pb_uninitialized_local_variable=Uninitialized local variables:
-ProblemSeveritiesconfigurationBlock_pb_uninitialized_global_variable=Uninitialized global variables:
-JavadocProblemsPreferencePage_title=JSDoc Comments
-
-JavadocProblemsConfigurationBlock_public=Public
-JavadocProblemsConfigurationBlock_protected=Protected
-JavadocProblemsConfigurationBlock_default=Default
-JavadocProblemsConfigurationBlock_private=Private
-
-JavadocProblemsConfigurationBlock_error=Error
-JavadocProblemsConfigurationBlock_warning=Warning
-JavadocProblemsConfigurationBlock_ignore=Ignore
-
-JavadocProblemsConfigurationBlock_needsbuild_title=JSDoc Settings Changed
-JavadocProblemsConfigurationBlock_needsfullbuild_message=The JSDoc settings have changed. A full rebuild is required for changes to take effect. Do the full build now?
-JavadocProblemsConfigurationBlock_needsprojectbuild_message=The JSDoc settings have changed. A rebuild of the project is required for changes to take effect. Build the project now?
-
-JavadocProblemsConfigurationBlock_javadoc_description=Severity level for problems in JSDoc comments:
-
-JavadocProblemsConfigurationBlock_pb_javadoc_support_label=Proc&ess JSDoc comments (includes search and refactoring)
-JavadocProblemsConfigurationBlock_pb_invalid_javadoc_label=Mal&formed JSDoc comments:
-JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_label=Report e&rrors in tags
-JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_visibility_label=On&ly consider members as visible as:
-JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_not_visible_ref_label=Report non &visible references
-JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_deprecated_label=Report de&precated references
-JavadocProblemsConfigurationBlock_pb_missing_javadoc_label=Missing JSDoc &tags:
-JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_visibility_label=O&nly consider members as visible as:
-JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_overriding_label=C&heck overriding and implementing functions
-JavadocProblemsConfigurationBlock_pb_missing_comments_label=&Missing JSDoc comments:
-JavadocProblemsConfigurationBlock_pb_missing_comments_visibility_label=&Only consider members as visible as:
-JavadocProblemsConfigurationBlock_pb_missing_comments_overriding_label=Chec&k overriding and implementing functions
-
-
-CompliancePreferencePage_title=Compiler
-CompliancePreferencePage_description=Options for the JavaScript validator:\nNote that a full rebuild is required for changes to take effect.
-
-ComplianceConfigurationBlock_error=Error
-ComplianceConfigurationBlock_warning=Warning
-ComplianceConfigurationBlock_ignore=Ignore
-
-ComplianceConfigurationBlock_version11=1.1
-ComplianceConfigurationBlock_version12=1.2
-ComplianceConfigurationBlock_version13=1.3
-ComplianceConfigurationBlock_version14=ECMAScript 3
-ComplianceConfigurationBlock_version15=ECMAScript 4
-ComplianceConfigurationBlock_version16=6.0
-
-ComplianceConfigurationBlock_needsbuild_title=Compiler Settings Changed
-ComplianceConfigurationBlock_needsfullbuild_message=The compiler settings have changed. A full rebuild is required for changes to take effect. Do the full build now?
-ComplianceConfigurationBlock_needsprojectbuild_message=The compiler settings have changed. A rebuild of the project is required for changes to take effect. Build the project now?
-
-ComplianceConfigurationBlock_variable_attr_label=Add varia&ble attributes to generated class files (used by the debugger)
-ComplianceConfigurationBlock_line_number_attr_label=Add &line number attributes to generated class files (used by the debugger)
-ComplianceConfigurationBlock_source_file_attr_label=Add source &file name to generated class file (used by the debugger)
-ComplianceConfigurationBlock_src_greater_compliance=Source compatibility must be equal or less than compliance level.
-ComplianceConfigurationBlock_codegen_unused_local_label=Pr&eserve unused (never read) local variables
-ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label=Inline finally bl&ocks (larger class files, but improved performance)
-ComplianceConfigurationBlock_compiler_compliance_label=ECMAScript compliance level:
-ComplianceConfigurationBlock_default_settings_label=Use defaul&t compliance settings
-ComplianceConfigurationBlock_source_compatibility_label=Source co&mpatibility:
-ComplianceConfigurationBlock_codegen_targetplatform_label=Ge&nerated .class files compatibility:
-ComplianceConfigurationBlock_pb_assert_as_identifier_label=Disallow identifie&rs called 'assert':
-ComplianceConfigurationBlock_pb_enum_as_identifier_label=Disallo&w identifiers called 'enum':
-ComplianceConfigurationBlock_compliance_group_label=ECMAScript Compliance
-ComplianceConfigurationBlock_classfiles_group_label=Classfile Generation
-ComplianceConfigurationBlock_classfile_greater_compliance=Classfile compatibility must be equal or less than compliance level.
-ComplianceConfigurationBlock_classfile_greater_source=Classfile compatibility must be greater or equal than source compatibility.
-
-ComplianceConfigurationBlock_jrecompliance_info=When selecting {0} compliance, make sure to have a compatible JRE installed and activated (Currently {1}). <a href="1" >Configure...</a>
-ComplianceConfigurationBlock_jrecompliance_info_project=When selecting {0} compliance, make sure to have a compatible JRE installed and activated (Currently {1}). Configure the <a href="1" >Installed JREs</a> or change the JRE on the <a href="2" >Java build path</a>.
-
-OptionsConfigurationBlock_job_title=Rebuilding
-
-OptionsConfigurationBlock_buildall_taskname=Build all...
-OptionsConfigurationBlock_buildproject_taskname=Build project ''{0}''...
-
-CodeStylePreferencePage_title=Code Style
-CodeTemplatesPreferencePage_title=Code Templates
-
-JavaCategoryPropertyPage_text=<form>\
-Project specific settings for project ''{0}''. If specified, they override settings defined in the global workspace preferences.\
-<li><a href=''{1}''>Build path</a>: Configures the paths used to find source files and classes and defines the output locations for the generated class files.</li>\
-<li><a href=''{2}''>Compiler</a>: Specifies the used compiler compliance and various options for the JavaScript validator like <a href=''{3}''>Todo</a> tasks, problem <a href=''{4}''>severities</a>, <a href=''{5}''>JSDoc</a> processing and <a href=''{6}''>build</a> options</li>\
-<li><a href=''{7}''>Code Style</a>: Defines the rules used when creating code, including your preferred code <a href=''{8}''>formatter</a> settings, used code <a href=''{9}''>templates</a> and <a href=''{10}''>import</a> order</li>\
-<li><a href=''{11}''>JSDoc location</a>: Configures the location where you want to generate your documentation to.</li>\
-</form>
-
-
-NameConventionConfigurationBlock_field_label=Fields
-NameConventionConfigurationBlock_static_label=Static Fields
-NameConventionConfigurationBlock_arg_label=Parameters
-NameConventionConfigurationBlock_local_label=Local Variables
-#NameConventionConfigurationBlock_keywordthis_label=&Qualify all generated field accesses with 'this.'
-NameConventionConfigurationBlock_isforbooleangetters_label=&Use 'is' prefix for getters that return boolean
-NameConventionConfigurationBlock_use_override_annotation_label=Add '@O&verride' annotation for new overriding functions
-
-NameConventionConfigurationBlock_dialog_prefix=P&refix list:
-NameConventionConfigurationBlock_dialog_suffix=S&uffix list:
-
-NameConventionConfigurationBlock_exceptionname_label=E&xception variable name in catch blocks:
-
-NameConventionConfigurationBlock_error_emptyprefix=Prefix strings cannot contain an empty entry.
-NameConventionConfigurationBlock_error_emptysuffix=Suffix strings cannot contain an empty entry.
-NameConventionConfigurationBlock_error_invalidprefix={0} is not a valid prefix.
-NameConventionConfigurationBlock_error_invalidsuffix={0} is not a valid suffix.
-
-NameConventionConfigurationBlock_list_label=&Conventions for variable names:
-NameConventionConfigurationBlock_list_edit_button=&Edit...
-NameConventionConfigurationBlock_list_name_column=Variable type
-NameConventionConfigurationBlock_list_prefix_column=Prefix list
-NameConventionConfigurationBlock_list_suffix_column=Suffix list
-
-NameConventionConfigurationBlock_field_dialog_title=Field Name Conventions
-NameConventionConfigurationBlock_field_dialog_message=Specify prefix and suffix to be used for fields (comma separated):
-
-NameConventionConfigurationBlock_static_dialog_title=Static Field Name Conventions
-NameConventionConfigurationBlock_static_dialog_message=Specify prefix and suffix to be used for static fields (comma separated):
-
-NameConventionConfigurationBlock_arg_dialog_title=Parameter Name Conventions
-NameConventionConfigurationBlock_arg_dialog_message=Specify prefix and suffix to be used for parameters (comma separated):
-
-NameConventionConfigurationBlock_local_dialog_title=Local Variable Name Conventions
-NameConventionConfigurationBlock_local_dialog_message=Specify prefix and suffix to be used for local variables (comma separated):
-
-MembersOrderPreferencePage_category_button_up=&Up
-MembersOrderPreferencePage_category_button_down=D&own
-
-MembersOrderPreferencePage_visibility_button_up=U&p
-MembersOrderPreferencePage_visibility_button_down=Do&wn
-
-MembersOrderPreferencePage_label_description=&Choose the order in which members will be displayed. The order is also used by the 'Sort Members' action.
-
-
-#MembersOrderPreferencePage_fields_label=Fields
-MembersOrderPreferencePage_vars_label=Vars
-MembersOrderPreferencePage_constructors_label=Constructors
-MembersOrderPreferencePage_methods_label=Functions
-MembersOrderPreferencePage_staticfields_label=Static Fields
-MembersOrderPreferencePage_staticmethods_label=Static Functions
-MembersOrderPreferencePage_initialisers_label=Initializers
-MembersOrderPreferencePage_staticinitialisers_label=Static Initializers
-MembersOrderPreferencePage_types_label=Types
-MembersOrderPreferencePage_public_label=Public
-MembersOrderPreferencePage_private_label=Private
-MembersOrderPreferencePage_protected_label=Protected
-MembersOrderPreferencePage_default_label=Default
-MembersOrderPreferencePage_usevisibilitysort_label=&Sort members in same category by visibility
-CodeTemplateBlock_templates_comment_node=Comments
-CodeTemplateBlock_templates_code_node=Code
-
-CodeTemplateBlock_catchblock_label=Catch block body
-CodeTemplateBlock_methodstub_label=Function body
-CodeTemplateBlock_constructorstub_label=Constructor body
-CodeTemplateBlock_newtype_label=New JavaScript files
-CodeTemplateBlock_classbody_label=Class body
-CodeTemplateBlock_interfacebody_label=Interface body
-CodeTemplateBlock_enumbody_label=Enum body
-CodeTemplateBlock_annotationbody_label=Annotation body
-CodeTemplateBlock_typecomment_label=Types
-CodeTemplateBlock_fieldcomment_label=Fields
-CodeTemplateBlock_filecomment_label=Files
-CodeTemplateBlock_methodcomment_label=Functions
-CodeTemplateBlock_overridecomment_label=Overriding functions
-CodeTemplateBlock_delegatecomment_label=Delegate functions
-CodeTemplateBlock_constructorcomment_label=Constructors
-CodeTemplateBlock_gettercomment_label=Getters
-CodeTemplateBlock_settercomment_label=Setters
-CodeTemplateBlock_getterstub_label=Getter body
-CodeTemplateBlock_setterstub_label=Setter body
-
-CodeTemplateBlock_templates_edit_button=&Edit...
-CodeTemplateBlock_templates_import_button=I&mport...
-CodeTemplateBlock_templates_export_button=E&xport...
-CodeTemplateBlock_templates_exportall_button=Ex&port All...
-
-CodeTemplateBlock_link_tooltip=Show code style settings
-CodeTemplateBlock_createcomment_label=Au&tomatically add comments for new functions and types
-CodeTemplateBlock_templates_label=C&onfigure generated code and comments:
-CodeTemplateBlock_preview=Pa&ttern:
-
-CodeTemplateBlock_import_title=Import Templates
-CodeTemplateBlock_import_extension=*.xml
-
-CodeTemplateBlock_export_title=Export {0} Code Template(s)
-CodeTemplateBlock_export_filename=codetemplates.xml
-CodeTemplateBlock_export_extension=*.xml
-
-CodeTemplateBlock_export_exists_title=Export Code Templates
-CodeTemplateBlock_export_exists_message={0} already exists.\nDo you want to replace it?
-
-CodeTemplateBlock_error_read_title= Code Templates
-CodeTemplateBlock_error_read_message= Failed to read templates.
-
-CodeTemplateBlock_error_parse_message= Failed to parse templates:\n{0}
-
-CodeTemplateBlock_error_write_title=Code Templates
-CodeTemplateBlock_error_write_message=Failed to write templates.
-
-CodeTemplateBlock_export_error_title= Export Templates
-CodeTemplateBlock_export_error_hidden= Export failed.\n{0} is a hidden file.
-CodeTemplateBlock_export_error_canNotWrite= Export failed.\n{0} cannot be modified.
-
-TypeFilterPreferencePage_description=All types in packages that match the selected filter strings will not be shown in the 'Open Type' dialog. They will also be ignored in content assist or quick fix proposals. For example 'java.awt.*' will hide all types from the awt packages.
-TypeFilterPreferencePage_list_label=&Filter list:
-TypeFilterPreferencePage_add_button=&New...
-TypeFilterPreferencePage_addpackage_button=Add &Packages...
-TypeFilterPreferencePage_edit_button=&Edit...
-TypeFilterPreferencePage_remove_button=&Remove
-TypeFilterPreferencePage_selectall_button=Ena&ble All
-TypeFilterPreferencePage_deselectall_button=Di&sable All
-
-TypeFilterPreferencePage_choosepackage_label=Package Selection
-TypeFilterPreferencePage_choosepackage_description=&Choose packages to filter:
-
-TypeFilterInputDialog_title=Type Filter
-TypeFilterInputDialog_message=&Type filter name ('*' and '?' are valid wildcards):
-TypeFilterInputDialog_browse_button=&Browse...
-TypeFilterInputDialog_error_enterName=Enter a qualified type name.
-TypeFilterInputDialog_error_invalidName=Invalid name: {0}.
-TypeFilterInputDialog_error_entryExists=Entry already exists.
-TypeFilterInputDialog_choosepackage_label=Package Selection
-TypeFilterInputDialog_choosepackage_description=&Choose packages to filter:
-
-JavaEditorPreferencePage_selectionBackgroundColor= Selection background color
-JavaEditorPreferencePage_selectionForegroundColor= Selection foreground color
-
-SpellingPreferencePage_empty_threshold= A maximum number of correction proposals must be specified.
-SpellingPreferencePage_invalid_threshold=''{0}'' is not a valid maximum number of correction proposals.
-SpellingPreferencePage_ignore_digits_label=Ignore &words with digits
-SpellingPreferencePage_ignore_mixed_label=Ignore &mixed case words
-SpellingPreferencePage_ignore_sentence_label=Ignore &sentence capitalization
-SpellingPreferencePage_ignore_upper_label=Ignore u&pper case words
-SpellingPreferencePage_ignore_url_label=Ignore &internet addresses
-SpellingPreferencePage_ignore_single_letters_label=I&gnore single letters
-SpellingPreferencePage_ignore_java_strings_label=Ignore Ja&va string literals
-SpellingPreferencePage_ignore_ampersand_in_properties_label=Ignore '&&' in &JavaScript properties files
-SpellingPreferencePage_ignore_non_letters_label=Ignore &non-letters at word boundaries
-SpellingPreferencePage_proposals_threshold= Ma&ximum number of correction proposals:
-SpellingPreferencePage_dictionary_label=Plat&form dictionary:
-SpellingPreferencePage_workspace_dictionary_label=&User defined dictionary:
-SpellingPreferencePage_browse_label=&Browse...
-SpellingPreferencePage_dictionary_error=The dictionary file must be read/write accessible.
-SpellingPreferencePage_dictionary_none=none
-SpellingPreferencePage_encoding_label=En&coding:
-SpellingPreferencePage_locale_error=There is no dictionary available for this language.
-SpellingPreferencePage_filedialog_title=Select User Dictionary
-SpellingPreferencePage_filter_dictionary_extension=*.dictionary
-SpellingPreferencePage_filter_all_extension=*.*
-SpellingPreferencePage_filter_dictionary_label=Dictionary Files
-SpellingPreferencePage_filter_all_label=All Files
-SpellingPreferencePage_enable_contentassist_label=Ma&ke dictionary available to content assist
-SpellingPreferencePage_group_user=Options
-SpellingPreferencePage_group_dictionary=Dictionary
-SpellingPreferencePage_group_dictionaries=Dictionaries
-SpellingPreferencePage_group_advanced=Advanced
-SpellingPreferencePage_user_dictionary_description=The user dictionary is a text file with one word on each line
-
-BuildPathPreferencePage_title=Build Path
-BuildPathPreferencePage_description=Build path settings:
-
-UserLibraryPreferencePage_title=User Libraries
-UserLibraryPreferencePage_description=User libraries can be included in a JavaScript project. They consist of external JavaScript source files that will be made available for validation and content assist purposes in the project.
-
-UserLibraryPreferencePage_libraries_label=&Defined user libraries:
-UserLibraryPreferencePage_libraries_new_button=&New...
-UserLibraryPreferencePage_libraries_edit_button=&Edit...
-UserLibraryPreferencePage_libraries_addjar_button=Add &.js file...
-UserLibraryPreferencePage_libraries_addfolder_button=Add folder...
-UserLibraryPreferencePage_libraries_remove_button=&Remove
-UserLibraryPreferencePage_libraries_load_button=I&mport...
-UserLibraryPreferencePage_libraries_save_button=E&xport...
-
-UserLibraryPreferencePage_operation=Updating classpath containers...
-UserLibraryPreferencePage_operation_error=Error while updating classpath containers
-
-UserLibraryPreferencePage_config_error_title=User Libraries
-UserLibraryPreferencePage_config_error_message=Configuration of user libraries failed.
-UserLibraryPreferencePage_browsejar_new_title=.js File Selection
-UserLibraryPreferencePage_browsejar_edit_title=Edit .js File Selection
-UserLibraryPreferencePage_browsefolder_new_title=Folder Selection
-UserLibraryPreferencePage_browsefolder_new_message=Select a folder from the file system. Any .js files contained in it and its sub-folders will be added to the library.
-
-UserLibraryPreferencePage_LibraryNameDialog_new_title=New User Library
-UserLibraryPreferencePage_LibraryNameDialog_edit_title=Edit User Library
-UserLibraryPreferencePage_LibraryNameDialog_name_label=&User library name:
-UserLibraryPreferencePage_LibraryNameDialog_issystem_label=&System library (added to the boot class path)
-UserLibraryPreferencePage_LibraryNameDialog_name_error_entername=Enter a library name.
-UserLibraryPreferencePage_LibraryNameDialog_name_error_exists=Library {0} already exists.
-UserLibraryPreferencePage_LibraryNameDialog_name_error_invalid=Name contains invalid characters.
-
-UserLibraryPreferencePage_LoadSaveDialog_save_title=Export User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_save_ok_title=Export User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_load_title=Import User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_location_label=&File location:
-UserLibraryPreferencePage_LoadSaveDialog_location_button=&Browse...
-UserLibraryPreferencePage_LoadSaveDialog_list_selectall_button=&Select All
-UserLibraryPreferencePage_LoadSaveDialog_load_replace_message=An existing library will be replaced. Do you want to continue?
-UserLibraryPreferencePage_LoadSaveDialog_load_replace_multiple_message={0} libraries will be replaced. Do you want to continue?
-UserLibraryPreferencePage_LoadSaveDialog_list_deselectall_button=&Deselect All
-UserLibraryPreferencePage_LoadSaveDialog_list_save_label=S&elect libraries to export:
-UserLibraryPreferencePage_LoadSaveDialog_list_load_label=Libraries contained in the s&elected file:
-UserLibraryPreferencePage_LoadSaveDialog_filedialog_save_title=Export User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_filedialog_load_title=Import User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_error_empty=The selected file contains no user libraries
-UserLibraryPreferencePage_LoadSaveDialog_error_invalidfile=The selected file is not a valid user library data file
-UserLibraryPreferencePage_LoadSaveDialog_overwrite_title=Export User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_save_ok_message=Libraries successfully exported.
-UserLibraryPreferencePage_LoadSaveDialog_overwrite_message=The file already exists. Do you want to overwrite the existing file?
-UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_title=Export User Libraries
-UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_message=Could not export file. {0}.
-UserLibraryPreferencePage_LoadSaveDialog_location_error_save_enterlocation=A location must be specified for the export.
-UserLibraryPreferencePage_LoadSaveDialog_location_error_save_invalid=The export location is invalid.
-UserLibraryPreferencePage_LoadSaveDialog_list_error_save_nothingselected=Select the libraries to export.
-UserLibraryPreferencePage_LoadSaveDialog_location_error_load_enterlocation=A location must be specified for the import target.
-UserLibraryPreferencePage_LoadSaveDialog_location_error_load_invalid=The location path does not point to a file.
-UserLibraryPreferencePage_LoadSaveDialog_list_error_load_nothingselected=Select the libraries to import.
-UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_up_button=&Up
-UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_down_button=D&own
-UserLibraryPreferencePage_LoadSaveDialog_load_badformat=bad format
-UserLibraryPreferencePage_LoadSaveDialog_load_replace_title=Import User Libraries
-
-
-# template stuff
-
-# edit template dialog
-EditTemplateDialog_error_noname=Template name cannot be empty.
-EditTemplateDialog_error_spaces=Template name cannot contain spaces.
-EditTemplateDialog_title_new=New Template
-EditTemplateDialog_title_edit=Edit Template
-
-EditTemplateDialog_name=&Name:
-EditTemplateDialog_description=&Description:
-EditTemplateDialog_context=&Context:
-EditTemplateDialog_pattern=&Pattern:
-EditTemplateDialog_insert_variable=Insert &Variable...
-
-EditTemplateDialog_undo=&Undo
-EditTemplateDialog_cut=Cu&t
-EditTemplateDialog_copy=&Copy
-EditTemplateDialog_paste=&Paste
-EditTemplateDialog_select_all=Select &All
-EditTemplateDialog_autoinsert=Auto&matically insert
-EditTemplateDialog_content_assist=Insert &Variable...
-
-JavaEditorPreferencePage_folding_title= &Folding
-
-FoldingConfigurationBlock_enable= Enable f&olding
-FoldingConfigurationBlock_combo_caption= Select folding to &use:
-FoldingConfigurationBlock_info_no_preferences= The selected folding provider did not provide a preference control
-FoldingConfigurationBlock_error_not_exist= The ''{0}'' folding provider does not exist.
-FoldingConfigurationBlock_warning_providerNotFound_resetToDefault= The ''{0}'' folding provider could not be found. Resetting to the default folding provider.
-
-
-# smart typing block
-SmartTypingConfigurationBlock_autoclose_title=Automatically close
-SmartTypingConfigurationBlock_automove_title=Automatically insert at correct position
-SmartTypingConfigurationBlock_tabs_title=Tabulators
-# The argument will be replaced by the tab display size
-SmartTypingConfigurationBlock_tabs_message_tab_text=The tab display value (currently {0}) and whether spaces are used to indent lines are configured on the <a>formatter preference page</a>. The current indentation mode uses tabs.
-# The first argument will be replaced by the tab display size, the second by the indent size and the third by the NLSed string of 'SmartTypingConfigurationBlock_tabs_message_spaces' or 'SmartTypingConfigurationBlock_tabs_message_tabs' (see below)
-SmartTypingConfigurationBlock_tabs_message_others_text=The tab display value (currently {0}) and whether spaces are used to indent lines are configured on the <a>formatter preference page</a>. The current indentation size is {1}, using {2}.
-SmartTypingConfigurationBlock_tabs_message_tooltip=Go to the formatter preference page
-SmartTypingConfigurationBlock_tabs_message_spaces=spaces
-SmartTypingConfigurationBlock_tabs_message_tabs=tabs
-SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces=tabs and spaces
-SmartTypingConfigurationBlock_pasting_title=When pasting
-SmartTypingConfigurationBlock_strings_title=In string literals
-# do not translate the href arguments (org.eclipse.wst.jsdt.ui.preferences.ProblemSeveritiesPreferencePage and org.eclipse.ui.editors.preferencePages.Spelling)
-SmartTypingConfigurationBlock_annotationReporting_link=Also see the <a href="org.eclipse.wst.jsdt.ui.preferences.ProblemSeveritiesPreferencePage">compiler warnings</a> and <a href="org.eclipse.ui.editors.preferencePages.Spelling">spell checking</a> preferences.
-
-# code assist block
-CodeAssistConfigurationBlock_insertionSection_title=Insertion
-CodeAssistConfigurationBlock_sortingSection_title=Sorting and Filtering
-CodeAssistConfigurationBlock_matchCamelCase_label=Show ca&mel case matches
-CodeAssistConfigurationBlock_autoactivationSection_title=Auto-Activation
-# do not translate the href arguments (org.eclipse.wst.jsdt.ui.preferences.ProblemSeveritiesPreferencePage)
-CodeAssistConfigurationBlock_restricted_link=Proposals with <a href="org.eclipse.wst.jsdt.ui.preferences.ProblemSeveritiesPreferencePage">access restrictions</a>:
-CodeAssistConfigurationBlock_hideForbidden_label=Hide fo&rbidden references
-CodeAssistConfigurationBlock_hideDiscouraged_label=Hide dis&couraged references
-CodeAssistConfigurationBlock_hideDeprecated_label=&Hide deprecated references
-
-# {0} will be replaced by the keyboard shortcut for the command (e.g. "Ctrl+Space", or "no shortcut")
-CodeAssistAdvancedConfigurationBlock_page_description=Configure the behavior of the content assist ({0}) command.
-# stand-in text if there is no keyboard shortcut in above statement
-CodeAssistAdvancedConfigurationBlock_no_shortcut=no shortcut
-CodeAssistAdvancedConfigurationBlock_default_table_description=Select the proposal kinds contained in the 'default' content assist list:
-CodeAssistAdvancedConfigurationBlock_default_table_category_column_title=Default Proposal Kinds
-CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title=Key Binding
-# do not translate the href argument (org.eclipse.ui.preferencePages.Keys)
-CodeAssistAdvancedConfigurationBlock_key_binding_hint=Individual key bindings can be assigned to each proposal kind on the <a href="org.eclipse.ui.preferencePages.Keys">Keys</a> preference page.
-CodeAssistAdvancedConfigurationBlock_separate_table_description=Content assist cycling: Select the proposal kinds that are cycled through when repeatedly invoking content assist:
-CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title=Separate Proposal Kinds
-CodeAssistAdvancedConfigurationBlock_Up=&Up
-CodeAssistAdvancedConfigurationBlock_Down=D&own
-CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout=Timeout for fetching a parameter name from attached JSDoc:
-
-# Abbreviation for milliseconds
-CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_ms=ms
-
-CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_emptyInput=Empty input.
-CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidInput=''{0}'' is not a valid input.
-CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidRange=Value must be between {0} and {1}.
-
-CodeAssistStaticMembersConfigurationBlock_description= Define a list of static members or types with static members. Content assist will propose those static members even if the import is missing.
-CodeAssistStaticMembersConfigurationBlock_newType_button= New &Type...
-CodeAssistStaticMembersConfigurationBlock_newMember_button= New &Member...
-CodeAssistStaticMembersConfigurationBlock_edit_button= &Edit
-CodeAssistStaticMembersConfigurationBlock_remove_button= &Remove
-
-FavoriteStaticMemberInputDialog_member_title= New Member Favorite
-FavoriteStaticMemberInputDialog_member_labelText= Enter a fully qualified static member (e.g. \'java.lang.Math.sqrt\'):
-FavoriteStaticMemberInputDialog_type_title= New Type Favorite
-FavoriteStaticMemberInputDialog_type_labelText= Enter a fully qualified type (e.g. \'java.lang.Math\'):
-FavoriteStaticMemberInputDialog_browse_button= &Browse...
-FavoriteStaticMemberInputDialog_ChooseTypeDialog_title= Type Selection
-FavoriteStaticMemberInputDialog_ChooseTypeDialog_description= Choose type name:
-FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message= A problem occurred while collecting types. See the error Log for details.
-FavoriteStaticMemberInputDialog_error_enterName=Enter a name or prefix.
-FavoriteStaticMemberInputDialog_error_invalidTypeName=Not a valid type name.
-FavoriteStaticMemberInputDialog_error_invalidMemberName=Not a valid member name.
-FavoriteStaticMemberInputDialog_error_entryExists=Entry already exists in list.
-
-# coloring
-JavaEditorPreferencePage_coloring_category_java=JavaScript
-JavaEditorPreferencePage_coloring_category_javadoc=JSDoc
-JavaEditorPreferencePage_coloring_category_comments=Comments
-
-ProjectSelectionDialog_title=Project Specific Configuration
-ProjectSelectionDialog_desciption=&Select the project to configure:
-ProjectSelectionDialog_filter=Show only &projects with project specific settings
-
-CleanUpPreferencePage_Description=A&ctive profile:
-CleanUpPreferencePage_Title=Code Clean Up
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesConfigurationBlock.java
deleted file mode 100644
index d86e8632..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesConfigurationBlock.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-
-/**
- */
-public class ProblemSeveritiesConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final String SETTINGS_SECTION_NAME= "ProblemSeveritiesConfigurationBlock"; //$NON-NLS-1$
-
- private static final Key PREF_PB_SEMANTIC_VALIDATION_ENABLEMENT = getJDTCoreKey(JavaScriptCore.COMPILER_SEMANTIC_VALIDATION);
-
- // Preference store keys, see JavaScriptCore.getOptions
- private static final Key PREF_PB_UNDEFINED_FIELD= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNDEFINED_FIELD);
-// private static final Key PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= getJDTCoreKey(JavaScriptCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME);
- private static final Key PREF_PB_DEPRECATION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_DEPRECATION);
- private static final Key PREF_PB_DEPRECATION_IN_DEPRECATED_CODE=getJDTCoreKey(JavaScriptCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE);
- private static final Key PREF_PB_DEPRECATION_WHEN_OVERRIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_DEPRECATION_WHEN_OVERRIDING_DEPRECATED_METHOD);
-
- private static final Key PREF_PB_HIDDEN_CATCH_BLOCK= getJDTCoreKey(JavaScriptCore.COMPILER_PB_HIDDEN_CATCH_BLOCK);
- private static final Key PREF_PB_UNUSED_LOCAL= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_LOCAL);
- private static final Key PREF_PB_UNUSED_PARAMETER= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_PARAMETER);
-// private static final Key PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE);
- private static final Key PREF_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE);
- private static final Key PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT);
-// private static final Key PREF_PB_SYNTHETIC_ACCESS_EMULATION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION);
- private static final Key PREF_PB_NON_EXTERNALIZED_STRINGS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_NON_NLS_STRING_LITERAL);
-// private static final Key PREF_PB_UNUSED_IMPORT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_IMPORT);
- private static final Key PREF_PB_UNUSED_PRIVATE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER);
-// private static final Key PREF_PB_STATIC_ACCESS_RECEIVER= getJDTCoreKey(JavaScriptCore.COMPILER_PB_STATIC_ACCESS_RECEIVER);
- private static final Key PREF_PB_NO_EFFECT_ASSIGNMENT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT);
-// private static final Key PREF_PB_CHAR_ARRAY_IN_CONCAT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION);
- private static final Key PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT);
- private static final Key PREF_PB_LOCAL_VARIABLE_HIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_LOCAL_VARIABLE_HIDING);
- private static final Key PREF_PB_FIELD_HIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FIELD_HIDING);
-// private static final Key PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= getJDTCoreKey(JavaScriptCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD);
- private static final Key PREF_PB_INDIRECT_STATIC_ACCESS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INDIRECT_STATIC_ACCESS);
- private static final Key PREF_PB_EMPTY_STATEMENT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_EMPTY_STATEMENT);
- private static final Key PREF_PB_UNNECESSARY_ELSE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNNECESSARY_ELSE);
-// private static final Key PREF_PB_UNNECESSARY_TYPE_CHECK= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK);
-// private static final Key PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD);
-// private static final Key PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION);
-// private static final Key PREF_PB_MISSING_SERIAL_VERSION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_SERIAL_VERSION);
- private static final Key PREF_PB_UNDOCUMENTED_EMPTY_BLOCK= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK);
- private static final Key PREF_PB_FINALLY_BLOCK_NOT_COMPLETING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING);
- private static final Key PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING);
-// private static final Key PREF_PB_UNQUALIFIED_FIELD_ACCESS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS);
- private static final Key PREF_PB_FORBIDDEN_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE);
- private static final Key PREF_PB_DISCOURRAGED_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE);
- private static final Key PREF_PB_UNUSED_LABEL= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNUSED_LABEL);
- private static final Key PREF_PB_PARAMETER_ASSIGNMENT= getJDTCoreKey(JavaScriptCore.COMPILER_PB_PARAMETER_ASSIGNMENT);
- private static final Key PREF_PB_FALLTHROUGH_CASE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FALLTHROUGH_CASE);
-
- private static final Key PREF_PB_NULL_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_NULL_REFERENCE);
- private static final Key PREF_PB_POTENTIAL_NULL_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_POTENTIAL_NULL_REFERENCE);
- private static final Key PREF_PB_DUPLICATE_LOCAL_VARIABLES= getJDTCoreKey(JavaScriptCore.COMPILER_PB_DUPLICATE_LOCAL_VARIABLES);
- private static final Key PREF_PB_REDUNDANT_NULL_CHECK= getJDTCoreKey(JavaScriptCore.COMPILER_PB_REDUNDANT_NULL_CHECK);
- private static final Key PREF_PB_UNINITIALIZED_LOCAL_VARIABLE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE);
- private static final Key PREF_PB_UNINITIALIZED_GLOBAL_VARIABLE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNINITIALIZED_GLOBAL_VARIABLE);
-
-// private static final Key PREF_15_PB_UNCHECKED_TYPE_OPERATION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION);
-// private static final Key PREF_15_PB_FINAL_PARAM_BOUND= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FINAL_PARAMETER_BOUND);
-// private static final Key PREF_15_PB_VARARGS_ARGUMENT_NEED_CAST= getJDTCoreKey(JavaScriptCore.COMPILER_PB_VARARGS_ARGUMENT_NEED_CAST);
-// private static final Key PREF_15_PB_AUTOBOXING_PROBLEM= getJDTCoreKey(JavaScriptCore.COMPILER_PB_AUTOBOXING);
-
-// private static final Key PREF_15_PB_MISSING_OVERRIDE_ANNOTATION= getJDTCoreKey(JavaScriptCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION);
-// private static final Key PREF_15_PB_ANNOTATION_SUPER_INTERFACE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_ANNOTATION_SUPER_INTERFACE);
-// private static final Key PREF_15_PB_TYPE_PARAMETER_HIDING= getJDTCoreKey(JavaScriptCore.COMPILER_PB_TYPE_PARAMETER_HIDING);
-// private static final Key PREF_15_PB_INCOMPLETE_ENUM_SWITCH= getJDTCoreKey(JavaScriptCore.COMPILER_PB_INCOMPLETE_ENUM_SWITCH);
-// private static final Key PREF_15_PB_RAW_TYPE_REFERENCE= getJDTCoreKey(JavaScriptCore.COMPILER_PB_RAW_TYPE_REFERENCE);
-
-// private static final Key PREF_PB_SUPPRESS_WARNINGS= getJDTCoreKey(JavaScriptCore.COMPILER_PB_SUPPRESS_WARNINGS);
-// private static final Key PREF_PB_UNHANDLED_WARNING_TOKEN= getJDTCoreKey(JavaScriptCore.COMPILER_PB_UNHANDLED_WARNING_TOKEN);
- //private static final Key PREF_PB_FATAL_OPTIONAL_ERROR= getJDTCoreKey(JavaScriptCore.COMPILER_PB_FATAL_OPTIONAL_ERROR);
-
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- private static final Key PREF_UNRESOLVED_TYPE_OPTIONAL_ERROR = getJDTCoreKey(JavaScriptCore.UNRESOLVED_TYPE_REFERENCE);
- private static final Key PREF_UNRESOLVED_FIELD_OPTIONAL_ERROR = getJDTCoreKey(JavaScriptCore.UNRESOLVED_FIELD_REFERENCE);
- private static final Key PREF_UNRESOLVED_METHOD_OPTIONAL_ERROR = getJDTCoreKey(JavaScriptCore.UNRESOLVED_METHOD_REFERENCE);
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
-
-
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
- private static final Key PREF_LOOSE_VAR = getJDTCoreKey(JavaScriptCore.LOOSE_VAR_DECL);
- private static final Key PREF_OPTIONAL_SEMICOLON = getJDTCoreKey(JavaScriptCore.OPTIONAL_SEMICOLON);
-
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- // values
- private static final String ERROR= JavaScriptCore.ERROR;
- private static final String WARNING= JavaScriptCore.WARNING;
- private static final String IGNORE= JavaScriptCore.IGNORE;
-
- private static final String ENABLED= JavaScriptCore.ENABLED;
- private static final String DISABLED= JavaScriptCore.DISABLED;
-
-
- private PixelConverter fPixelConverter;
-
- private ControlEnableState fBlockEnableState;
- private Composite fControlsComposite;
- private Button semanticCheckBox;
-
- public ProblemSeveritiesConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getKeys(), container);
-
- // compatibilty code for the merge of the two option PB_SIGNAL_PARAMETER:
- if (ENABLED.equals(getValue(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT))) {
-// setValue(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, ENABLED);
- }
- }
-
- private static Key[] getKeys() {
- return new Key[] {
- PREF_PB_SEMANTIC_VALIDATION_ENABLEMENT,
- PREF_PB_UNDEFINED_FIELD,
- /*PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME,*/ PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
- PREF_PB_UNUSED_PARAMETER, PREF_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE,
- /*PREF_PB_SYNTHETIC_ACCESS_EMULATION,*/ PREF_PB_NON_EXTERNALIZED_STRINGS,
- /*PREF_PB_UNUSED_IMPORT,*/ PREF_PB_UNUSED_LABEL,
- /*PREF_PB_STATIC_ACCESS_RECEIVER, */PREF_PB_DEPRECATION_IN_DEPRECATED_CODE,
- PREF_PB_NO_EFFECT_ASSIGNMENT, /*PREF_PB_INCOMPATIBLE_INTERFACE_METHOD,*/
- PREF_PB_UNUSED_PRIVATE,/* PREF_PB_CHAR_ARRAY_IN_CONCAT,*/ PREF_PB_UNNECESSARY_ELSE,
- PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, PREF_PB_LOCAL_VARIABLE_HIDING, PREF_PB_FIELD_HIDING,
- /*PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD,*/ PREF_PB_INDIRECT_STATIC_ACCESS,
- PREF_PB_EMPTY_STATEMENT, /*PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, */PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT,
-// PREF_PB_UNNECESSARY_TYPE_CHECK, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, PREF_PB_UNQUALIFIED_FIELD_ACCESS,
- PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, PREF_PB_DEPRECATION_WHEN_OVERRIDING,
- PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING, /*PREF_PB_MISSING_SERIAL_VERSION, */
- PREF_PB_PARAMETER_ASSIGNMENT, PREF_PB_NULL_REFERENCE, PREF_PB_POTENTIAL_NULL_REFERENCE,
- PREF_PB_DUPLICATE_LOCAL_VARIABLES,
- PREF_PB_REDUNDANT_NULL_CHECK, PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, PREF_PB_UNINITIALIZED_GLOBAL_VARIABLE, PREF_PB_FALLTHROUGH_CASE,
-// PREF_15_PB_UNCHECKED_TYPE_OPERATION, PREF_15_PB_FINAL_PARAM_BOUND, PREF_15_PB_VARARGS_ARGUMENT_NEED_CAST,
-// PREF_15_PB_AUTOBOXING_PROBLEM, PREF_15_PB_MISSING_OVERRIDE_ANNOTATION, PREF_15_PB_ANNOTATION_SUPER_INTERFACE,
- /*PREF_15_PB_TYPE_PARAMETER_HIDING, PREF_15_PB_INCOMPLETE_ENUM_SWITCH,*/
- /*PREF_15_PB_RAW_TYPE_REFERENCE,*/ /*PREF_PB_FATAL_OPTIONAL_ERROR,*/
- PREF_PB_FORBIDDEN_REFERENCE, PREF_PB_DISCOURRAGED_REFERENCE/*, PREF_PB_SUPPRESS_WARNINGS, PREF_PB_UNHANDLED_WARNING_TOKEN*/,PREF_UNRESOLVED_TYPE_OPTIONAL_ERROR,PREF_UNRESOLVED_FIELD_OPTIONAL_ERROR,PREF_UNRESOLVED_METHOD_OPTIONAL_ERROR,PREF_LOOSE_VAR,PREF_OPTIONAL_SEMICOLON
- };
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- fPixelConverter= new PixelConverter(parent);
- setShell(parent.getShell());
-
- Composite mainComp= new Composite(parent, SWT.NONE);
- mainComp.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- mainComp.setLayout(layout);
-
- String label = PreferencesMessages.ProblemSeveritiesConfigurationBlock_enableSemanticValidation;
- semanticCheckBox = addCheckBox(mainComp, label, PREF_PB_SEMANTIC_VALIDATION_ENABLEMENT, new String[]{ENABLED, DISABLED}, 0);
- Label horizontalLine= new Label(mainComp, SWT.SEPARATOR | SWT.HORIZONTAL);
- horizontalLine.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
- horizontalLine.setFont(mainComp.getFont());
-
- Composite commonComposite= createStyleTabContent(mainComp);
- GridData gridData= GridDataFactory.fillDefaults().grab(true, true).span(3, 1).create();
- gridData.heightHint= fPixelConverter.convertHeightInCharsToPixels(20);
- commonComposite.setLayoutData(gridData);
-
- fControlsComposite = commonComposite;
-
- validateSettings(null, null, null);
-
- return mainComp;
- }
-
- private Composite createStyleTabContent(Composite folder) {
- String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
-
- String[] errorWarningIgnoreLabels= new String[] {
- PreferencesMessages.ProblemSeveritiesConfigurationBlock_error,
- PreferencesMessages.ProblemSeveritiesConfigurationBlock_warning,
- PreferencesMessages.ProblemSeveritiesConfigurationBlock_ignore
- };
-
- String[] enabledDisabled= new String[] { ENABLED, DISABLED };
-
- int nColumns= 3;
-
- final ScrolledPageContent sc1 = new ScrolledPageContent(folder);
-
- Composite composite= sc1.getBody();
- GridLayout layout= new GridLayout(nColumns, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- Label description= new Label(composite, SWT.LEFT | SWT.WRAP);
- description.setFont(description.getFont());
- description.setText(PreferencesMessages.ProblemSeveritiesConfigurationBlock_common_description);
- description.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, nColumns - 1, 1));
-
- int indentStep= fPixelConverter.convertWidthInCharsToPixels(1);
-
- int defaultIndent= indentStep * 0;
- int extraIndent= indentStep * 2;
- String label;
- ExpandableComposite excomposite;
- Composite inner;
- /* START -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_Resolution;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_UnresolvedTypes;
- addComboBox(inner, label, PREF_UNRESOLVED_TYPE_OPTIONAL_ERROR, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_UnresolvedFields;
- addComboBox(inner, label, PREF_UNRESOLVED_FIELD_OPTIONAL_ERROR, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_UnresolvedMethods;
- addComboBox(inner, label, PREF_UNRESOLVED_METHOD_OPTIONAL_ERROR, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
- /* END -------------------------------- Bug 203292 Type/Method/Filed resolution error configuration --------------------- */
- // --- style
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_code_style;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_static_access_receiver_label;
-// addComboBox(inner, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_indirect_access_to_static_label;
-// addComboBox(inner, label, PREF_PB_INDIRECT_STATIC_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unqualified_field_access_label;
-// addComboBox(inner, label, PREF_PB_UNQUALIFIED_FIELD_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_undocumented_empty_block_label;
- addComboBox(inner, label, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_synth_access_emul_label;
-// addComboBox(inner, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_method_naming_label;
-// addComboBox(inner, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_parameter_assignment;
- addComboBox(inner, label, PREF_PB_PARAMETER_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_non_externalized_strings_label;
- addComboBox(inner, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- // --- potential_programming_problems
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_potential_programming_problems;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
- /* START -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_LooselyDeclaredGlobalVar;
- addComboBox(inner, label, PREF_LOOSE_VAR, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_Optionalsemicolon;
- addComboBox(inner, label, PREF_OPTIONAL_SEMICOLON, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- /* END -------------------------------- Bug 197884 Loosly defined var (for statement) and optional semi-colon --------------------- */
-
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_undefined_field_label;
- addComboBox(inner, label, PREF_PB_UNDEFINED_FIELD, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_missing_serial_version_label;
-// addComboBox(inner, label, PREF_PB_MISSING_SERIAL_VERSION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_no_effect_assignment_label;
- addComboBox(inner, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_accidential_assignement_label;
- addComboBox(inner, label, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_finally_block_not_completing_label;
- addComboBox(inner, label, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_empty_statement_label;
- addComboBox(inner, label, PREF_PB_EMPTY_STATEMENT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_char_array_in_concat_label;
-// addComboBox(inner, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_hidden_catchblock_label;
- addComboBox(inner, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_inexact_vararg_label;
-// addComboBox(inner, label, PREF_15_PB_VARARGS_ARGUMENT_NEED_CAST, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_autoboxing_problem_label;
-// addComboBox(inner, label, PREF_15_PB_AUTOBOXING_PROBLEM, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_incomplete_enum_switch_label;
-// addComboBox(inner, label, PREF_15_PB_INCOMPLETE_ENUM_SWITCH, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_fall_through_case;
- addComboBox(inner, label, PREF_PB_FALLTHROUGH_CASE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_null_reference;
- addComboBox(inner, label, PREF_PB_NULL_REFERENCE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_potential_null_reference;
- addComboBox(inner, label, PREF_PB_POTENTIAL_NULL_REFERENCE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_duplicate_local_variables;
- addComboBox(inner, label, PREF_PB_DUPLICATE_LOCAL_VARIABLES, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesconfigurationBlock_pb_uninitialized_local_variable;
- addComboBox(inner, label, PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesconfigurationBlock_pb_uninitialized_global_variable;
- addComboBox(inner, label, PREF_PB_UNINITIALIZED_GLOBAL_VARIABLE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- // --- name_shadowing
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_name_shadowing;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_field_hiding_label;
- addComboBox(inner, label, PREF_PB_FIELD_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_local_variable_hiding_label;
- addComboBox(inner, label, PREF_PB_LOCAL_VARIABLE_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_special_param_hiding_label;
-// addCheckBox(inner, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, enabledDisabled, extraIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_type_parameter_hiding_label;
-// addComboBox(inner, label, PREF_15_PB_TYPE_PARAMETER_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_incompatible_interface_method_label;
-// addComboBox(inner, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
- // --- API access rules
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_deprecations;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_deprecation_label;
- addComboBox(inner, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_deprecation_in_deprecation_label;
- addCheckBox(inner, label, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, extraIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_deprecation_when_overriding_label;
- addCheckBox(inner, label, PREF_PB_DEPRECATION_WHEN_OVERRIDING, enabledDisabled, extraIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_forbidden_reference_label;
- addComboBox(inner, label, PREF_PB_FORBIDDEN_REFERENCE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_discourraged_reference_label;
- addComboBox(inner, label, PREF_PB_DISCOURRAGED_REFERENCE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
-
-
- // --- unnecessary_code
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_unnecessary_code;
- excomposite= createStyleSection(composite, label, nColumns);
-
- inner= new Composite(excomposite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayout(new GridLayout(nColumns, false));
- excomposite.setClient(inner);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_local_label;
- addComboBox(inner, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_parameter_label;
- addComboBox(inner, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_signal_param_in_overriding_label;
-// addCheckBox(inner, label, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, enabledDisabled, extraIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_ignore_documented_unused_parameters;
- addCheckBox(inner, label, PREF_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE, enabledDisabled, extraIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_imports_label;
-// addComboBox(inner, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_private_label;
- addComboBox(inner, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_redundant_null_check;
- addComboBox(inner, label, PREF_PB_REDUNDANT_NULL_CHECK, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unnecessary_else_label;
- addComboBox(inner, label, PREF_PB_UNNECESSARY_ELSE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unnecessary_type_check_label;
-// addComboBox(inner, label, PREF_PB_UNNECESSARY_TYPE_CHECK, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_label;
-// addComboBox(inner, label, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_when_overriding_label;
-// addCheckBox(inner, label, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING, enabledDisabled, extraIndent);
-
- label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unused_label_label;
- addComboBox(inner, label, PREF_PB_UNUSED_LABEL, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-
-
- // --- generics
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_generics;
-// excomposite= createStyleSection(composite, label, nColumns);
-//
-//
-// inner= new Composite(excomposite, SWT.NONE);
-// inner.setFont(composite.getFont());
-// inner.setLayout(new GridLayout(nColumns, false));
-// excomposite.setClient(inner);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unsafe_type_op_label;
-// addComboBox(inner, label, PREF_15_PB_UNCHECKED_TYPE_OPERATION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_raw_type_reference;
-// addComboBox(inner, label, PREF_15_PB_RAW_TYPE_REFERENCE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_final_param_bound_label;
-// addComboBox(inner, label, PREF_15_PB_FINAL_PARAM_BOUND, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-//
-// // --- annotations
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_section_annotations;
-// excomposite= createStyleSection(composite, label, nColumns);
-//
-//
-// inner= new Composite(excomposite, SWT.NONE);
-// inner.setFont(composite.getFont());
-// inner.setLayout(new GridLayout(nColumns, false));
-// excomposite.setClient(inner);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_missing_override_annotation_label;
-// addComboBox(inner, label, PREF_15_PB_MISSING_OVERRIDE_ANNOTATION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_missing_deprecated_annotation_label;
-// addComboBox(inner, label, PREF_PB_MISSING_DEPRECATED_ANNOTATION, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_annotation_super_interface_label;
-// addComboBox(inner, label, PREF_15_PB_ANNOTATION_SUPER_INTERFACE, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_unhandled_surpresswarning_tokens;
-// addComboBox(inner, label, PREF_PB_UNHANDLED_WARNING_TOKEN, errorWarningIgnore, errorWarningIgnoreLabels, defaultIndent);
-//
-// label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_pb_enable_surpresswarning_annotation;
-// addCheckBox(inner, label, PREF_PB_SUPPRESS_WARNINGS, enabledDisabled, 0);
-
- //new Label(composite, SWT.NONE);
-
- //String[] enableDisableValues= new String[] { ENABLED, DISABLED };
- //label= PreferencesMessages.ProblemSeveritiesConfigurationBlock_treat_optional_as_fatal;
- //addCheckBox(composite, label, PREF_PB_FATAL_OPTIONAL_ERROR, enableDisableValues, 0);
-
-
- IDialogSettings section= JavaScriptPlugin.getDefault().getDialogSettings().getSection(SETTINGS_SECTION_NAME);
- restoreSectionExpansionStates(section);
-
- return sc1;
- }
-
- /* (non-javadoc)
- * Update fields and validate.
- * @param changedKey Key that changed, or null, if all changed.
- */
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (!areSettingsEnabled()) {
- return;
- }
-
- if (changedKey != null) {
- if (PREF_PB_UNUSED_PARAMETER.equals(changedKey) || PREF_PB_SEMANTIC_VALIDATION_ENABLEMENT.equals(changedKey) )
-// PREF_PB_DEPRECATION.equals(changedKey) ||
-// PREF_PB_LOCAL_VARIABLE_HIDING.equals(changedKey) ||
-// PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION.equals(changedKey))
- {
- updateEnableStates();
-// } else if (PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING.equals(changedKey)) {
-// // merging the two options
-// setValue(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, newValue);
- } else {
- return;
- }
- } else {
- updateEnableStates();
- }
- fContext.statusChanged(new StatusInfo());
- }
-
- private void updateEnableStates() {
- boolean notJustParseErrors = checkValue(PREF_PB_SEMANTIC_VALIDATION_ENABLEMENT, ENABLED);
- enableConfigControls(notJustParseErrors);
-
- if (!notJustParseErrors) {
- boolean enableUnusedParams= !checkValue(PREF_PB_UNUSED_PARAMETER, IGNORE);
- // getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING).setEnabled(enableUnusedParams);
- getCheckBox(PREF_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE).setEnabled(enableUnusedParams);
-
- boolean enableDeprecation= !checkValue(PREF_PB_DEPRECATION, IGNORE);
- getCheckBox(PREF_PB_DEPRECATION_IN_DEPRECATED_CODE).setEnabled(enableDeprecation);
- getCheckBox(PREF_PB_DEPRECATION_WHEN_OVERRIDING).setEnabled(enableDeprecation);
-
- // boolean enableThrownExceptions= !checkValue(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, IGNORE);
- // getCheckBox(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING).setEnabled(enableThrownExceptions);
-
- // boolean enableHiding= !checkValue(PREF_PB_LOCAL_VARIABLE_HIDING, IGNORE);
- // getCheckBox(PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD).setEnabled(enableHiding);
- }
- }
-
- protected void enableConfigControls(boolean enable) {
- if (enable) {
- if (fBlockEnableState != null) {
- fBlockEnableState.restore();
- fBlockEnableState= null;
- }
- } else {
- if (fBlockEnableState == null) {
- fBlockEnableState= ControlEnableState.disable(fControlsComposite);
- }
- }
- }
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- String title= PreferencesMessages.ProblemSeveritiesConfigurationBlock_needsbuild_title;
- String message;
- if (workspaceSettings) {
- message= PreferencesMessages.ProblemSeveritiesConfigurationBlock_needsfullbuild_message;
- } else {
- message= PreferencesMessages.ProblemSeveritiesConfigurationBlock_needsprojectbuild_message;
- }
- return new String[] { title, message };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#dispose()
- */
- public void dispose() {
- IDialogSettings section= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(SETTINGS_SECTION_NAME);
- storeSectionExpansionStates(section);
- super.dispose();
- }
-
- protected void controlChanged(Widget widget) {
- if(widget == semanticCheckBox) {
- String newValue= semanticCheckBox.getSelection() ? ENABLED : DISABLED;
- ControlData data= (ControlData) widget.getData();
- String oldValue= setValue(data.getKey(), newValue);
- validateSettings(data.getKey(), oldValue, newValue);
- } else {
- super.controlChanged(widget);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesPreferencePage.java
deleted file mode 100644
index ec9c10cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProblemSeveritiesPreferencePage.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Page used to configure both workspace and project specific compiler settings
- */
-public class ProblemSeveritiesPreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.ProblemSeveritiesPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.ProblemSeveritiesPreferencePage"; //$NON-NLS-1$
-
- public static final String DATA_SELECT_OPTION_KEY= "select_option_key"; //$NON-NLS-1$
- public static final String DATA_SELECT_OPTION_QUALIFIER= "select_option_qualifier"; //$NON-NLS-1$
-
- private ProblemSeveritiesConfigurationBlock fConfigurationBlock;
-
- public ProblemSeveritiesPreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- //setDescription(PreferencesMessages.getString("ProblemSeveritiesPreferencePage.description")); //$NON-NLS-1$
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.ProblemSeveritiesPreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new ProblemSeveritiesConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
- if (isProjectPreferencePage()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PROBLEM_SEVERITIES_PROPERTY_PAGE);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PROBLEM_SEVERITIES_PREFERENCE_PAGE);
- }
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
- */
- public void applyData(Object data) {
- super.applyData(data);
- if (data instanceof Map && fConfigurationBlock != null) {
- Map map= (Map) data;
- Object key= map.get(DATA_SELECT_OPTION_KEY);
- Object qualifier= map.get(DATA_SELECT_OPTION_QUALIFIER);
- if (key instanceof String && qualifier instanceof String) {
- fConfigurationBlock.selectOption((String) key, (String) qualifier);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProfilePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProfilePreferencePage.java
deleted file mode 100644
index 18631ee1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProfilePreferencePage.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.ui.preferences.IWorkingCopyManager;
-import org.eclipse.ui.preferences.WorkingCopyManager;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileConfigurationBlock;
-
-public abstract class ProfilePreferencePage extends PropertyAndPreferencePage {
-
- private ProfileConfigurationBlock fConfigurationBlock;
-
- public ProfilePreferencePage() {
- super();
- }
-
- protected abstract ProfileConfigurationBlock createConfigurationBlock(PreferencesAccess access);
-
- public void createControl(Composite parent) {
- IPreferencePageContainer container= getContainer();
- IWorkingCopyManager workingCopyManager;
- if (container instanceof IWorkbenchPreferenceContainer) {
- workingCopyManager= ((IWorkbenchPreferenceContainer) container).getWorkingCopyManager();
- } else {
- workingCopyManager= new WorkingCopyManager(); // non shared
- }
- PreferencesAccess access= PreferencesAccess.getWorkingCopyPreferences(workingCopyManager);
- fConfigurationBlock= createConfigurationBlock(access);
-
- super.createControl(parent);
- }
-
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.enableProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- protected void performDefaults() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- super.performDefaults();
- }
-
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- super.performApply();
- }
-
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProjectSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProjectSelectionDialog.java
deleted file mode 100644
index 494c5250..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ProjectSelectionDialog.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.Set;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-public class ProjectSelectionDialog extends SelectionStatusDialog {
-
- // the visual selection widget group
- private TableViewer fTableViewer;
- private Set fProjectsWithSpecifics;
-
- // sizing constants
- private final static int SIZING_SELECTION_WIDGET_HEIGHT= 250;
- private final static int SIZING_SELECTION_WIDGET_WIDTH= 300;
-
- private final static String DIALOG_SETTINGS_SHOW_ALL= "ProjectSelectionDialog.show_all"; //$NON-NLS-1$
-
- private ViewerFilter fFilter;
-
- public ProjectSelectionDialog(Shell parentShell, Set projectsWithSpecifics) {
- super(parentShell);
- setTitle(PreferencesMessages.ProjectSelectionDialog_title);
- setMessage(PreferencesMessages.ProjectSelectionDialog_desciption);
- fProjectsWithSpecifics= projectsWithSpecifics;
-
- int shellStyle = getShellStyle();
- setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
-
- fFilter= new ViewerFilter() {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- return fProjectsWithSpecifics.contains(element);
- }
- };
-
- }
-
- /* (non-Javadoc)
- * Method declared on Dialog.
- */
- protected Control createDialogArea(Composite parent) {
- // page group
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Font font= parent.getFont();
- composite.setFont(font);
-
- createMessageArea(composite);
-
- fTableViewer= new TableViewer(composite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- doSelectionChanged(((IStructuredSelection) event.getSelection()).toArray());
- }
- });
- fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- okPressed();
- }
- });
- GridData data= new GridData(SWT.FILL, SWT.FILL, true, true);
- data.heightHint= SIZING_SELECTION_WIDGET_HEIGHT;
- data.widthHint= SIZING_SELECTION_WIDGET_WIDTH;
- fTableViewer.getTable().setLayoutData(data);
-
- fTableViewer.setLabelProvider(new JavaScriptElementLabelProvider());
- fTableViewer.setContentProvider(new StandardJavaScriptElementContentProvider());
- fTableViewer.setComparator(new JavaScriptElementComparator());
- fTableViewer.getControl().setFont(font);
-
- Button checkbox= new Button(composite, SWT.CHECK);
- checkbox.setText(PreferencesMessages.ProjectSelectionDialog_filter);
- checkbox.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false));
- checkbox.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- updateFilter(((Button) e.widget).getSelection());
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- updateFilter(((Button) e.widget).getSelection());
- }
- });
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- boolean doFilter= !dialogSettings.getBoolean(DIALOG_SETTINGS_SHOW_ALL) && !fProjectsWithSpecifics.isEmpty();
- checkbox.setSelection(doFilter);
- updateFilter(doFilter);
-
- IJavaScriptModel input= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- fTableViewer.setInput(input);
-
- doSelectionChanged(new Object[0]);
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- protected void updateFilter(boolean selected) {
- if (selected) {
- fTableViewer.addFilter(fFilter);
- } else {
- fTableViewer.removeFilter(fFilter);
- }
- JavaScriptPlugin.getDefault().getDialogSettings().put(DIALOG_SETTINGS_SHOW_ALL, !selected);
- }
-
- private void doSelectionChanged(Object[] objects) {
- if (objects.length != 1) {
- updateStatus(new StatusInfo(IStatus.ERROR, "")); //$NON-NLS-1$
- setSelectionResult(null);
- } else {
- updateStatus(new StatusInfo());
- setSelectionResult(objects);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult()
- */
- protected void computeResult() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertiesFileEditorColorSettingPreviewCode.txt b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertiesFileEditorColorSettingPreviewCode.txt
deleted file mode 100644
index 3f2a5c3a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertiesFileEditorColorSettingPreviewCode.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-#
-# Properties
-#
-JavaElementProperties.name Name
-JavaElementProperties.name2= Name is {0}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertyAndPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertyAndPreferencePage.java
deleted file mode 100644
index 1ef90644..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PropertyAndPreferencePage.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.ControlEnableState;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.IWorkbenchPropertyPage;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-
-/**
- * Base for project property and preference pages
- */
-public abstract class PropertyAndPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IWorkbenchPropertyPage {
-
- private Control fConfigurationBlockControl;
- private ControlEnableState fBlockEnableState;
- private Link fChangeWorkspaceSettings;
- private SelectionButtonDialogField fUseProjectSettings;
- private IStatus fBlockStatus;
- private Composite fParentComposite;
-
- private IProject fProject; // project or null
- private Map fData; // page data
-
- public static final String DATA_NO_LINK= "PropertyAndPreferencePage.nolink"; //$NON-NLS-1$
-
- public PropertyAndPreferencePage() {
- fBlockStatus= new StatusInfo();
- fBlockEnableState= null;
- fProject= null;
- fData= null;
- }
-
- protected abstract Control createPreferenceContent(Composite composite);
- protected abstract boolean hasProjectSpecificOptions(IProject project);
-
- protected abstract String getPreferencePageID();
- protected abstract String getPropertyPageID();
-
- protected boolean supportsProjectSpecificOptions() {
- return getPropertyPageID() != null;
- }
-
- protected boolean offerLink() {
- return fData == null || !Boolean.TRUE.equals(fData.get(DATA_NO_LINK));
- }
-
- protected Label createDescriptionLabel(Composite parent) {
- fParentComposite= parent;
- if (isProjectPreferencePage()) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
-
- IDialogFieldListener listener= new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- enableProjectSpecificSettings(((SelectionButtonDialogField)field).isSelected());
- }
- };
-
- fUseProjectSettings= new SelectionButtonDialogField(SWT.CHECK);
- fUseProjectSettings.setDialogFieldListener(listener);
- fUseProjectSettings.setLabelText(PreferencesMessages.PropertyAndPreferencePage_useprojectsettings_label);
- fUseProjectSettings.doFillIntoGrid(composite, 1);
- LayoutUtil.setHorizontalGrabbing(fUseProjectSettings.getSelectionButton(null));
-
- if (offerLink()) {
- fChangeWorkspaceSettings= createLink(composite, PreferencesMessages.PropertyAndPreferencePage_useworkspacesettings_change);
- fChangeWorkspaceSettings.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false));
- } else {
- LayoutUtil.setHorizontalSpan(fUseProjectSettings.getSelectionButton(null), 2);
- }
-
- Label horizontalLine= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- horizontalLine.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
- horizontalLine.setFont(composite.getFont());
- } else if (supportsProjectSpecificOptions() && offerLink()) {
- fChangeWorkspaceSettings= createLink(parent, PreferencesMessages.PropertyAndPreferencePage_showprojectspecificsettings_label);
- fChangeWorkspaceSettings.setLayoutData(new GridData(SWT.END, SWT.CENTER, true, false));
- }
-
- return super.createDescriptionLabel(parent);
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#createContents(Composite)
- */
- protected Control createContents(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
- composite.setFont(parent.getFont());
-
- GridData data= new GridData(GridData.FILL, GridData.FILL, true, true);
-
- fConfigurationBlockControl= createPreferenceContent(composite);
- fConfigurationBlockControl.setLayoutData(data);
-
- if (isProjectPreferencePage()) {
- boolean useProjectSettings= hasProjectSpecificOptions(getProject());
- enableProjectSpecificSettings(useProjectSettings);
- }
-
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- private Link createLink(Composite composite, String text) {
- Link link= new Link(composite, SWT.NONE);
- link.setFont(composite.getFont());
- link.setText("<A>" + text + "</A>"); //$NON-NLS-1$//$NON-NLS-2$
- link.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- doLinkActivated((Link) e.widget);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- doLinkActivated((Link) e.widget);
- }
- });
- return link;
- }
-
- protected boolean useProjectSettings() {
- return isProjectPreferencePage() && fUseProjectSettings != null && fUseProjectSettings.isSelected();
- }
-
- protected boolean isProjectPreferencePage() {
- return fProject != null;
- }
-
- protected IProject getProject() {
- return fProject;
- }
-
- final void doLinkActivated(Link link) {
- Map data= new HashMap();
- data.put(DATA_NO_LINK, Boolean.TRUE);
-
- if (isProjectPreferencePage()) {
- openWorkspacePreferences(data);
- } else {
- HashSet projectsWithSpecifics= new HashSet();
- try {
- IJavaScriptProject[] projects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
- for (int i= 0; i < projects.length; i++) {
- IJavaScriptProject curr= projects[i];
- if (hasProjectSpecificOptions(curr.getProject())) {
- projectsWithSpecifics.add(curr);
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- ProjectSelectionDialog dialog= new ProjectSelectionDialog(getShell(), projectsWithSpecifics);
- if (dialog.open() == Window.OK) {
- IJavaScriptProject res= (IJavaScriptProject) dialog.getFirstResult();
- openProjectProperties(res.getProject(), data);
- }
- }
- }
-
- protected final void openWorkspacePreferences(Object data) {
- String id= getPreferencePageID();
- PreferencesUtil.createPreferenceDialogOn(getShell(), id, new String[] { id }, data).open();
- }
-
- protected final void openProjectProperties(IProject project, Object data) {
- String id= getPropertyPageID();
- if (id != null) {
- PreferencesUtil.createPropertyDialogOn(getShell(), project, id, new String[] { id }, data).open();
- }
- }
-
-
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- fUseProjectSettings.setSelection(useProjectSpecificSettings);
- enablePreferenceContent(useProjectSpecificSettings);
- updateLinkVisibility();
- doStatusChanged();
- }
-
- private void updateLinkVisibility() {
- if (fChangeWorkspaceSettings == null || fChangeWorkspaceSettings.isDisposed()) {
- return;
- }
-
- if (isProjectPreferencePage()) {
- fChangeWorkspaceSettings.setEnabled(!useProjectSettings());
- }
- }
-
-
- protected void setPreferenceContentStatus(IStatus status) {
- fBlockStatus= status;
- doStatusChanged();
- }
-
- /**
- * Returns a new status change listener that calls {@link #setPreferenceContentStatus(IStatus)}
- * when the status has changed
- * @return The new listener
- */
- protected IStatusChangeListener getNewStatusChangedListener() {
- return new IStatusChangeListener() {
- public void statusChanged(IStatus status) {
- setPreferenceContentStatus(status);
- }
- };
- }
-
- protected IStatus getPreferenceContentStatus() {
- return fBlockStatus;
- }
-
- protected void doStatusChanged() {
- if (!isProjectPreferencePage() || useProjectSettings()) {
- updateStatus(fBlockStatus);
- } else {
- updateStatus(new StatusInfo());
- }
- }
-
- protected void enablePreferenceContent(boolean enable) {
- if (enable) {
- if (fBlockEnableState != null) {
- fBlockEnableState.restore();
- fBlockEnableState= null;
- }
- } else {
- if (fBlockEnableState == null) {
- fBlockEnableState= ControlEnableState.disable(fConfigurationBlockControl);
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- if (useProjectSettings()) {
- enableProjectSpecificSettings(false);
- }
- super.performDefaults();
- }
-
- private void updateStatus(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement()
- */
- public IAdaptable getElement() {
- return fProject;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- fProject= (IProject) element.getAdapter(IResource.class);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
- */
- public void applyData(Object data) {
- if (data instanceof Map) {
- fData= (Map) data;
- }
- if (fChangeWorkspaceSettings != null) {
- if (!offerLink()) {
- fChangeWorkspaceSettings.dispose();
- fParentComposite.layout(true, true);
- }
- }
- }
-
- protected Map getData() {
- return fData;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantConfigurationBlock.java
deleted file mode 100644
index e84e26a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantConfigurationBlock.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.jface.preference.IPreferencePageContainer;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.ISaveParticipantPreferenceConfiguration;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.SaveParticipantDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.SaveParticipantRegistry;
-
-import com.ibm.icu.text.Collator;
-
-/**
- * Configures Java Editor save participants.
- *
- *
- */
-class SaveParticipantConfigurationBlock implements IPreferenceAndPropertyConfigurationBlock {
-
- private interface IDelegateOperation {
- public void run(ISaveParticipantPreferenceConfiguration block);
- }
-
- private final PreferencePage fPreferencePage;
- private final IScopeContext fContext;
- private final ArrayList fConfigurations;
-
- public SaveParticipantConfigurationBlock(IScopeContext context, PreferencePage preferencePage) {
- Assert.isNotNull(context);
- Assert.isNotNull(preferencePage);
-
- fContext= context;
- fPreferencePage= preferencePage;
- fConfigurations= new ArrayList();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#createControl(org.eclipse.swt.widgets.Composite)
- *
- */
- public Control createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- GridLayout gridLayout= new GridLayout(2, false);
- gridLayout.marginHeight= 0;
- gridLayout.marginWidth= 0;
- composite.setLayout(gridLayout);
-
- SaveParticipantRegistry registry= JavaScriptPlugin.getDefault().getSaveParticipantRegistry();
- SaveParticipantDescriptor[] descriptors= registry.getSaveParticipantDescriptors();
-
- if (descriptors.length == 0)
- return composite;
-
- Arrays.sort(descriptors, new Comparator() {
- public int compare(Object o1, Object o2) {
- SaveParticipantDescriptor d1= (SaveParticipantDescriptor)o1;
- SaveParticipantDescriptor d2= (SaveParticipantDescriptor)o2;
- return Collator.getInstance().compare(d1.getPostSaveListener().getName(), d2.getPostSaveListener().getName());
- }
- });
-
- IPreferencePageContainer container= fPreferencePage.getContainer();
- for (int i= 0; i < descriptors.length; i++) {
- final SaveParticipantDescriptor descriptor= descriptors[i];
- ISaveParticipantPreferenceConfiguration configuration= descriptor.createPreferenceConfiguration();
- configuration.createControl(composite, container);
- fConfigurations.add(configuration);
- }
-
- return composite;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#dispose()
- */
- public void dispose() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- block.dispose();
- }
- });
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#initialize()
- */
- public void initialize() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- IAdaptable element= null;
- if (fPreferencePage instanceof PropertyAndPreferencePage) {
- element= ((PropertyAndPreferencePage)fPreferencePage).getElement();
- }
- block.initialize(fContext, element);
- }
- });
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#performDefaults()
- */
- public void performDefaults() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- block.performDefaults();
- }
- });
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.IPreferenceConfigurationBlock#performOk()
- */
- public void performOk() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- block.performOk();
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- public void enableProjectSettings() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- block.enableProjectSettings();
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- public void disableProjectSettings() {
- delegateToPreferenceConfiguration(new IDelegateOperation() {
- public void run(ISaveParticipantPreferenceConfiguration block) {
- block.disableProjectSettings();
- }
- });
- }
-
- private void delegateToPreferenceConfiguration(IDelegateOperation op) {
- for (int i= 0; i < fConfigurations.size(); i++) {
- ISaveParticipantPreferenceConfiguration block= (ISaveParticipantPreferenceConfiguration)fConfigurations.get(i);
- op.run(block);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantPreferencePage.java
deleted file mode 100644
index 89608b6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SaveParticipantPreferencePage.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Configures Java Editor save participant preferences.
- *
- *
- */
-public final class SaveParticipantPreferencePage extends AbstractConfigurationBlockPreferenceAndPropertyPage {
-
- public static final String PROPERTY_PAGE_ID= "org.eclipse.wst.jsdt.ui.propertyPages.SaveParticipantPreferencePage"; //$NON-NLS-1$
- public static final String PREFERENCE_PAGE_ID= "org.eclipse.wst.jsdt.ui.preferences.SaveParticipantPreferencePage"; //$NON-NLS-1$
-
- /**
- * {@inheritDoc}
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /**
- * {@inheritDoc}
- */
- protected IPreferenceAndPropertyConfigurationBlock createConfigurationBlock(IScopeContext context) {
- return new SaveParticipantConfigurationBlock(context, this);
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getPreferencePageID() {
- return PREFERENCE_PAGE_ID;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getPropertyPageID() {
- return PROPERTY_PAGE_ID;
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean hasProjectSpecificOptions(IProject project) {
- return JavaScriptPlugin.getDefault().getSaveParticipantRegistry().hasSettingsInScope(new ProjectScope(project));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ScrolledPageContent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ScrolledPageContent.java
deleted file mode 100644
index e3dbf0ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ScrolledPageContent.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-public class ScrolledPageContent extends SharedScrolledComposite {
-
- private FormToolkit fToolkit;
-
- public ScrolledPageContent(Composite parent) {
- this(parent, SWT.V_SCROLL | SWT.H_SCROLL);
- }
-
- public ScrolledPageContent(Composite parent, int style) {
- super(parent, style);
-
- setFont(parent.getFont());
-
- fToolkit= JavaScriptPlugin.getDefault().getDialogsFormToolkit();
-
- setExpandHorizontal(true);
- setExpandVertical(true);
-
- Composite body= new Composite(this, SWT.NONE);
- body.setFont(parent.getFont());
- setContent(body);
- }
-
-
- public void adaptChild(Control childControl) {
- fToolkit.adapt(childControl, true, true);
- }
-
- public Composite getBody() {
- return (Composite) getContent();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingConfigurationBlock.java
deleted file mode 100644
index 7dcb40d1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingConfigurationBlock.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Configures Java Editor typing preferences.
- *
- *
- */
-class SmartTypingConfigurationBlock extends AbstractConfigurationBlock {
-
- public SmartTypingConfigurationBlock(OverlayPreferenceStore store) {
- super(store);
-
- store.addKeys(createOverlayStoreKeys());
- }
-
- private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
-
- return new OverlayPreferenceStore.OverlayKey[] {
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE),
-
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS),
-
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_SEMICOLON),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_TAB),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_OPENING_BRACE),
- };
- }
-
- /**
- * Creates page for mark occurrences preferences.
- *
- * @param parent the parent composite
- * @return the control for the preference page
- */
- public Control createControl(Composite parent) {
- ScrolledPageContent scrolled= new ScrolledPageContent(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrolled.setExpandHorizontal(true);
- scrolled.setExpandVertical(true);
-
- Composite control= new Composite(scrolled, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- control.setLayout(layout);
-
- Composite composite;
-
- composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_autoclose_title);
- addAutoclosingSection(composite);
-
- composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_automove_title);
- addAutopositionSection(composite);
-
- composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_tabs_title);
- addTabSection(composite);
-
- composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_pasting_title);
- addPasteSection(composite);
-
- composite= createSubsection(control, null, PreferencesMessages.SmartTypingConfigurationBlock_strings_title);
- addStringsSection(composite);
-
- scrolled.setContent(control);
- final Point size= control.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- scrolled.setMinSize(size.x, size.y);
- return scrolled;
- }
-
- private void addStringsSection(Composite composite) {
- GridLayout layout= new GridLayout();
- composite.setLayout(layout);
-
- String label;
- Button master, slave;
- label= PreferencesMessages.JavaEditorPreferencePage_wrapStrings;
- master= addCheckBox(composite, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_escapeStrings;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 0);
- createDependency(master, slave);
- }
-
- private void addPasteSection(Composite composite) {
- GridLayout layout= new GridLayout();
- composite.setLayout(layout);
-
- String label;
- label= PreferencesMessages.JavaEditorPreferencePage_smartPaste;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_PASTE, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_importsOnPaste;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, 0);
- }
-
- private void addTabSection(Composite composite) {
- GridLayout layout= new GridLayout();
- composite.setLayout(layout);
-
- String label;
- label= PreferencesMessages.JavaEditorPreferencePage_typing_smartTab;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_TAB, 0);
-
- createMessage(composite);
- }
-
- private void addAutopositionSection(Composite composite) {
-
- GridLayout layout= new GridLayout();
- composite.setLayout(layout);
-
- String label;
-
- label= PreferencesMessages.JavaEditorPreferencePage_typing_smartSemicolon;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_SEMICOLON, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_typing_smartOpeningBrace;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_OPENING_BRACE, 0);
- }
-
- private void addAutoclosingSection(Composite composite) {
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- composite.setLayout(layout);
-
- String label;
- Button master, slave;
-
- label= PreferencesMessages.JavaEditorPreferencePage_closeStrings;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_closeBrackets;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_closeBraces;
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_closeJavaDocs;
- master= addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 0);
-
- label= PreferencesMessages.JavaEditorPreferencePage_addJavaDocTags;
- slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 0);
- createDependency(master, slave);
- }
-
- private void createMessage(final Composite composite) {
- // TODO create a link with an argument, so the formatter preference page can open the
- // current profile automatically.
- String linkTooltip= PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tooltip;
- String text;
- String indentMode= JavaScriptPlugin.getDefault().getCombinedPreferenceStore().getString(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- if (JavaScriptCore.TAB.equals(indentMode))
- text= Messages.format(PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tab_text, new String[] {Integer.toString(getTabDisplaySize())});
- else
- text= Messages.format(PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_others_text, new String[] {Integer.toString(getTabDisplaySize()), Integer.toString(getIndentSize()), getIndentMode()});
-
- final Link link= new Link(composite, SWT.NONE);
- link.setText(text);
- link.setToolTipText(linkTooltip);
- GridData gd= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gd.widthHint= 300; // don't get wider initially
- link.setLayoutData(gd);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(link.getShell(), "org.eclipse.wst.jsdt.ui.preferences.CodeFormatterPreferencePage", null, null); //$NON-NLS-1$
- }
- });
-
- final IPreferenceStore combinedStore= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- final IPropertyChangeListener propertyChangeListener= new IPropertyChangeListener() {
- private boolean fHasRun= false;
- public void propertyChange(PropertyChangeEvent event) {
- if (fHasRun)
- return;
- if (composite.isDisposed())
- return;
- String property= event.getProperty();
- if (DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR.equals(property)
- || DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE.equals(property)) {
- fHasRun= true;
- link.dispose();
- createMessage(composite);
- Dialog.applyDialogFont(composite);
- composite.redraw();
- composite.layout();
- }
- }
- };
- combinedStore.addPropertyChangeListener(propertyChangeListener);
- link.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(org.eclipse.swt.events.DisposeEvent e) {
- combinedStore.removePropertyChangeListener(propertyChangeListener);
- }
- });
- }
-
- private String getIndentMode() {
- String indentMode= JavaScriptPlugin.getDefault().getCombinedPreferenceStore().getString(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
-
- if (JavaScriptCore.SPACE.equals(indentMode))
- return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_spaces;
-
- if (JavaScriptCore.TAB.equals(indentMode))
- return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabs;
-
- if (DefaultCodeFormatterConstants.MIXED.equals(indentMode))
- return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces;
-
- Assert.isTrue(false, "Illegal indent mode - must not happen"); //$NON-NLS-1$
- return null;
- }
-
- private int getIndentSize() {
- return CodeFormatterUtil.getIndentWidth(null);
- }
-
- private int getTabDisplaySize() {
- return CodeFormatterUtil.getTabWidth(null);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingPreferencePage.java
deleted file mode 100644
index 5e90154f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SmartTypingPreferencePage.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * The page for setting the editor options.
- */
-public final class SmartTypingPreferencePage extends AbstractConfigurationBlockPreferencePage {
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId()
- */
- protected String getHelpId() {
- return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription()
- */
- protected void setDescription() {
- String description= PreferencesMessages.JavaEditorPreferencePage_typing_tabTitle;
- setDescription(description);
- }
-
- /*
- * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore()
- */
- protected void setPreferenceStore() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- }
-
-
- protected Label createDescriptionLabel(Composite parent) {
- return null; // no description for new look.
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore)
- */
- protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) {
- return new SmartTypingConfigurationBlock(overlayPreferenceStore);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SourceAttachmentPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SourceAttachmentPropertyPage.java
deleted file mode 100644
index afb0b259..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/SourceAttachmentPropertyPage.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PropertyPage;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock;
-
-/**
- * Property page to configure a archive's JARs source attachment
- */
-public class SourceAttachmentPropertyPage extends PropertyPage implements IStatusChangeListener {
-
- private SourceAttachmentBlock fSourceAttachmentBlock;
- private IPackageFragmentRoot fRoot;
- private IPath fContainerPath;
- private IIncludePathEntry fEntry;
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.SourceAttachmentPage" ; //$NON-NLS-1$
-
- public SourceAttachmentPropertyPage() {
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.SOURCE_ATTACHMENT_PROPERTY_PAGE);
- }
-
- /*
- * @see PreferencePage#createContents
- */
- protected Control createContents(Composite composite) {
- initializeDialogUnits(composite);
- Control result= createPageContent(composite);
- Dialog.applyDialogFont(result);
- return result;
- }
-
- private Control createPageContent(Composite composite) {
- try {
- fContainerPath= null;
- fEntry= null;
- fRoot= getJARPackageFragmentRoot();
- if (fRoot == null || fRoot.getKind() != IPackageFragmentRoot.K_BINARY) {
- return createMessageContent(composite, PreferencesMessages.SourceAttachmentPropertyPage_noarchive_message);
- }
-
- IPath containerPath= null;
- IJavaScriptProject jproject= fRoot.getJavaScriptProject();
- IIncludePathEntry entry= fRoot.getRawIncludepathEntry();
- if (entry == null) {
- // use a dummy entry to use for initialization
- entry= JavaScriptCore.newLibraryEntry(fRoot.getPath(), null, null);
- } else {
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- containerPath= entry.getPath();
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- if (initializer == null || container == null) {
- return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_invalid_container, containerPath.toString()));
- }
- String containerName= container.getDescription();
-
- IStatus status= initializer.getSourceAttachmentStatus(containerPath, jproject);
- if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
- return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_not_supported, containerName));
- }
- if (status.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_READ_ONLY) {
- return createMessageContent(composite, Messages.format(PreferencesMessages.SourceAttachmentPropertyPage_read_only, containerName));
- }
- entry= JavaModelUtil.findEntryInContainer(container, fRoot.getPath());
- Assert.isNotNull(entry);
- }
- }
- fContainerPath= containerPath;
- fEntry= entry;
-
- fSourceAttachmentBlock= new SourceAttachmentBlock(this, entry);
- return fSourceAttachmentBlock.createControl(composite);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return createMessageContent(composite, PreferencesMessages.SourceAttachmentPropertyPage_noarchive_message);
- }
- }
-
-
- private Control createMessageContent(Composite composite, String message) {
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- inner.setLayout(layout);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.widthHint= convertWidthInCharsToPixels(80);
-
- Label label= new Label(inner, SWT.LEFT + SWT.WRAP);
- label.setText(message);
- label.setLayoutData(gd);
- return inner;
- }
-
-
- /*
- * @see IPreferencePage#performOk
- */
- public boolean performOk() {
- if (fSourceAttachmentBlock != null) {
- try {
- IIncludePathEntry entry= fSourceAttachmentBlock.getNewEntry();
- if (entry.equals(fEntry)) {
- return true; // no change
- }
-
- IRunnableWithProgress runnable= SourceAttachmentBlock.getRunnable(getShell(), entry, fRoot.getJavaScriptProject(), fContainerPath);
- PlatformUI.getWorkbench().getProgressService().run(true, true, runnable);
- } catch (InvocationTargetException e) {
- String title= PreferencesMessages.SourceAttachmentPropertyPage_error_title;
- String message= PreferencesMessages.SourceAttachmentPropertyPage_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- return false;
- } catch (InterruptedException e) {
- // cancelled
- return false;
- }
- }
- return true;
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- if (fSourceAttachmentBlock != null) {
- fSourceAttachmentBlock.setDefaults();
- }
- super.performDefaults();
- }
-
- private IPackageFragmentRoot getJARPackageFragmentRoot() throws CoreException {
- // try to find it as Java element (needed for external jars)
- IAdaptable adaptable= getElement();
- IJavaScriptElement elem= (IJavaScriptElement) adaptable.getAdapter(IJavaScriptElement.class);
- if (elem instanceof IPackageFragmentRoot) {
- return (IPackageFragmentRoot) elem;
- }
- // not on classpath or not in a java project
- IResource resource= (IResource) adaptable.getAdapter(IResource.class);
- if (resource instanceof IFile) {
- IProject proj= resource.getProject();
- if (proj.hasNature(JavaScriptCore.NATURE_ID)) {
- IJavaScriptProject jproject= JavaScriptCore.create(proj);
- return jproject.getPackageFragmentRoot(resource);
- }
- }
- return null;
- }
-
-
- /*
- * @see IStatusChangeListener#statusChanged
- */
- public void statusChanged(IStatus status) {
- setValid(!status.matches(IStatus.ERROR));
- StatusUtil.applyToStatusLine(this, status);
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskConfigurationBlock.java
deleted file mode 100644
index b5082608..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskConfigurationBlock.java
+++ /dev/null
@@ -1,369 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-
-/**
- */
-public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock {
-
- private static final Key PREF_COMPILER_TASK_TAGS= getJDTCoreKey(JavaScriptCore.COMPILER_TASK_TAGS);
- private static final Key PREF_COMPILER_TASK_PRIORITIES= getJDTCoreKey(JavaScriptCore.COMPILER_TASK_PRIORITIES);
-
- private static final Key PREF_COMPILER_TASK_CASE_SENSITIVE= getJDTCoreKey(JavaScriptCore.COMPILER_TASK_CASE_SENSITIVE);
-
- private static final String PRIORITY_HIGH= JavaScriptCore.COMPILER_TASK_PRIORITY_HIGH;
- private static final String PRIORITY_NORMAL= JavaScriptCore.COMPILER_TASK_PRIORITY_NORMAL;
- private static final String PRIORITY_LOW= JavaScriptCore.COMPILER_TASK_PRIORITY_LOW;
-
- private static final String ENABLED= JavaScriptCore.ENABLED;
- private static final String DISABLED= JavaScriptCore.DISABLED;
-
- public static class TodoTask {
- public String name;
- public String priority;
- }
-
- private class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider, IFontProvider {
-
- public TodoTaskLabelProvider() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- return null; // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- return getColumnText(element, 0);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- TodoTask task= (TodoTask) element;
- if (columnIndex == 0) {
- String name= task.name;
- if (isDefaultTask(task)) {
- name=Messages.format(PreferencesMessages.TodoTaskConfigurationBlock_tasks_default, name);
- }
- return name;
- } else {
- if (PRIORITY_HIGH.equals(task.priority)) {
- return PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_high_priority;
- } else if (PRIORITY_NORMAL.equals(task.priority)) {
- return PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_normal_priority;
- } else if (PRIORITY_LOW.equals(task.priority)) {
- return PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_low_priority;
- }
- return ""; //$NON-NLS-1$
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- if (isDefaultTask((TodoTask) element)) {
- return JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT);
- }
- return null;
- }
- }
-
- private static class TodoTaskSorter extends ViewerComparator {
- public int compare(Viewer viewer, Object e1, Object e2) {
- return getComparator().compare(((TodoTask) e1).name, ((TodoTask) e2).name);
- }
- }
-
- private static final int IDX_ADD= 0;
- private static final int IDX_EDIT= 1;
- private static final int IDX_REMOVE= 2;
- private static final int IDX_DEFAULT= 4;
-
- private IStatus fTaskTagsStatus;
- private ListDialogField fTodoTasksList;
- private SelectionButtonDialogField fCaseSensitiveCheckBox;
-
-
- public TodoTaskConfigurationBlock(IStatusChangeListener context, IProject project, IWorkbenchPreferenceContainer container) {
- super(context, project, getKeys(), container);
-
- TaskTagAdapter adapter= new TaskTagAdapter();
- String[] buttons= new String[] {
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_add_button,
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_edit_button,
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_remove_button,
- null,
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_setdefault_button,
- };
- fTodoTasksList= new ListDialogField(adapter, buttons, new TodoTaskLabelProvider());
- fTodoTasksList.setDialogFieldListener(adapter);
- fTodoTasksList.setRemoveButtonIndex(IDX_REMOVE);
-
- String[] columnsHeaders= new String[] {
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_name_column,
- PreferencesMessages.TodoTaskConfigurationBlock_markers_tasks_priority_column,
- };
-
- fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription(columnsHeaders, true));
- fTodoTasksList.setViewerComparator(new TodoTaskSorter());
-
-
- fCaseSensitiveCheckBox= new SelectionButtonDialogField(SWT.CHECK);
- fCaseSensitiveCheckBox.setLabelText(PreferencesMessages.TodoTaskConfigurationBlock_casesensitive_label);
- fCaseSensitiveCheckBox.setDialogFieldListener(adapter);
-
- unpackTodoTasks();
- if (fTodoTasksList.getSize() > 0) {
- fTodoTasksList.selectFirstElement();
- } else {
- fTodoTasksList.enableButton(IDX_EDIT, false);
- fTodoTasksList.enableButton(IDX_DEFAULT, false);
- }
-
- fTaskTagsStatus= new StatusInfo();
- }
-
- public void setEnabled(boolean isEnabled) {
- fTodoTasksList.setEnabled(isEnabled);
- fCaseSensitiveCheckBox.setEnabled(isEnabled);
- }
-
- final boolean isDefaultTask(TodoTask task) {
- return fTodoTasksList.getIndexOfElement(task) == 0;
- }
-
- private void setToDefaultTask(TodoTask task) {
- List elements= fTodoTasksList.getElements();
- elements.remove(task);
- elements.add(0, task);
- fTodoTasksList.setElements(elements);
- fTodoTasksList.enableButton(IDX_DEFAULT, false);
- }
-
- private static Key[] getKeys() {
- return new Key[] {
- PREF_COMPILER_TASK_TAGS, PREF_COMPILER_TASK_PRIORITIES, PREF_COMPILER_TASK_CASE_SENSITIVE
- };
- }
-
- public class TaskTagAdapter implements IListAdapter, IDialogFieldListener {
-
- private boolean canEdit(List selectedElements) {
- return selectedElements.size() == 1;
- }
-
- private boolean canSetToDefault(List selectedElements) {
- return selectedElements.size() == 1 && !isDefaultTask((TodoTask) selectedElements.get(0));
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doTodoButtonPressed(index);
- }
-
- public void selectionChanged(ListDialogField field) {
- List selectedElements= field.getSelectedElements();
- field.enableButton(IDX_EDIT, canEdit(selectedElements));
- field.enableButton(IDX_DEFAULT, canSetToDefault(selectedElements));
- }
-
- public void doubleClicked(ListDialogField field) {
- if (canEdit(field.getSelectedElements())) {
- doTodoButtonPressed(IDX_EDIT);
- }
- }
-
- public void dialogFieldChanged(DialogField field) {
- updateModel(field);
- }
-
- }
-
- protected Control createContents(Composite parent) {
- setShell(parent.getShell());
-
- Composite markersComposite= createMarkersTabContent(parent);
-
- validateSettings(null, null, null);
-
- return markersComposite;
- }
-
- private Composite createMarkersTabContent(Composite folder) {
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
-
- PixelConverter conv= new PixelConverter(folder);
-
- Composite markersComposite= new Composite(folder, SWT.NULL);
- markersComposite.setLayout(layout);
- markersComposite.setFont(folder.getFont());
-
- GridData data= new GridData(GridData.FILL_BOTH);
- data.widthHint= conv.convertWidthInCharsToPixels(50);
- Control listControl= fTodoTasksList.getListControl(markersComposite);
- listControl.setLayoutData(data);
-
- Control buttonsControl= fTodoTasksList.getButtonBox(markersComposite);
- buttonsControl.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING));
-
- fCaseSensitiveCheckBox.doFillIntoGrid(markersComposite, 2);
-
- return markersComposite;
- }
-
- protected void validateSettings(Key changedKey, String oldValue, String newValue) {
- if (!areSettingsEnabled()) {
- return;
- }
-
- if (changedKey != null) {
- if (PREF_COMPILER_TASK_TAGS.equals(changedKey)) {
- fTaskTagsStatus= validateTaskTags();
- } else {
- return;
- }
- } else {
- fTaskTagsStatus= validateTaskTags();
- }
- IStatus status= fTaskTagsStatus; //StatusUtil.getMostSevere(new IStatus[] { fTaskTagsStatus });
- fContext.statusChanged(status);
- }
-
- private IStatus validateTaskTags() {
- return new StatusInfo();
- }
-
- protected final void updateModel(DialogField field) {
- if (field == fTodoTasksList) {
- StringBuffer tags= new StringBuffer();
- StringBuffer prios= new StringBuffer();
- List list= fTodoTasksList.getElements();
- for (int i= 0; i < list.size(); i++) {
- if (i > 0) {
- tags.append(',');
- prios.append(',');
- }
- TodoTask elem= (TodoTask) list.get(i);
- tags.append(elem.name);
- prios.append(elem.priority);
- }
- setValue(PREF_COMPILER_TASK_TAGS, tags.toString());
- setValue(PREF_COMPILER_TASK_PRIORITIES, prios.toString());
- validateSettings(PREF_COMPILER_TASK_TAGS, null, null);
- } else if (field == fCaseSensitiveCheckBox) {
- String state= fCaseSensitiveCheckBox.isSelected() ? ENABLED : DISABLED;
- setValue(PREF_COMPILER_TASK_CASE_SENSITIVE, state);
- }
- }
-
- protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
- String title= PreferencesMessages.TodoTaskConfigurationBlock_needsbuild_title;
- String message;
- if (fProject == null) {
- message= PreferencesMessages.TodoTaskConfigurationBlock_needsfullbuild_message;
- } else {
- message= PreferencesMessages.TodoTaskConfigurationBlock_needsprojectbuild_message;
- }
- return new String[] { title, message };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
- */
- protected void updateControls() {
- unpackTodoTasks();
- }
-
- private void unpackTodoTasks() {
- String currTags= getValue(PREF_COMPILER_TASK_TAGS);
- String currPrios= getValue(PREF_COMPILER_TASK_PRIORITIES);
- String[] tags= getTokens(currTags, ","); //$NON-NLS-1$
- String[] prios= getTokens(currPrios, ","); //$NON-NLS-1$
- ArrayList elements= new ArrayList(tags.length);
- for (int i= 0; i < tags.length; i++) {
- TodoTask task= new TodoTask();
- task.name= tags[i].trim();
- task.priority= (i < prios.length) ? prios[i] : PRIORITY_NORMAL;
- elements.add(task);
- }
- fTodoTasksList.setElements(elements);
-
- boolean isCaseSensitive= checkValue(PREF_COMPILER_TASK_CASE_SENSITIVE, ENABLED);
- fCaseSensitiveCheckBox.setSelection(isCaseSensitive);
- }
-
- private void doTodoButtonPressed(int index) {
- TodoTask edited= null;
- if (index != IDX_ADD) {
- edited= (TodoTask) fTodoTasksList.getSelectedElements().get(0);
- }
- if (index == IDX_ADD || index == IDX_EDIT) {
- TodoTaskInputDialog dialog= new TodoTaskInputDialog(getShell(), edited, fTodoTasksList.getElements());
- if (dialog.open() == Window.OK) {
- if (edited != null) {
- fTodoTasksList.replaceElement(edited, dialog.getResult());
- } else {
- fTodoTasksList.addElement(dialog.getResult());
- }
- }
- } else if (index == IDX_DEFAULT) {
- setToDefaultTask(edited);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskInputDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskInputDialog.java
deleted file mode 100644
index 6ec191cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskInputDialog.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.TodoTaskConfigurationBlock.TodoTask;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ComboDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-/**
- * Dialog to enter a na new task tag
- */
-public class TodoTaskInputDialog extends StatusDialog {
-
- private class CompilerTodoTaskInputAdapter implements IDialogFieldListener {
- public void dialogFieldChanged(DialogField field) {
- doValidation();
- }
- }
-
- private StringDialogField fNameDialogField;
- private ComboDialogField fPriorityDialogField;
-
- private List fExistingNames;
-
- public TodoTaskInputDialog(Shell parent, TodoTask task, List existingEntries) {
- super(parent);
-
- fExistingNames= new ArrayList(existingEntries.size());
- for (int i= 0; i < existingEntries.size(); i++) {
- TodoTask curr= (TodoTask) existingEntries.get(i);
- if (!curr.equals(task)) {
- fExistingNames.add(curr.name);
- }
- }
-
- if (task == null) {
- setTitle(PreferencesMessages.TodoTaskInputDialog_new_title);
- } else {
- setTitle(PreferencesMessages.TodoTaskInputDialog_edit_title);
- }
-
- CompilerTodoTaskInputAdapter adapter= new CompilerTodoTaskInputAdapter();
-
- fNameDialogField= new StringDialogField();
- fNameDialogField.setLabelText(PreferencesMessages.TodoTaskInputDialog_name_label);
- fNameDialogField.setDialogFieldListener(adapter);
-
- fNameDialogField.setText((task != null) ? task.name : ""); //$NON-NLS-1$
-
- String[] items= new String[] {
- PreferencesMessages.TodoTaskInputDialog_priority_high,
- PreferencesMessages.TodoTaskInputDialog_priority_normal,
- PreferencesMessages.TodoTaskInputDialog_priority_low
- };
-
- fPriorityDialogField= new ComboDialogField(SWT.READ_ONLY);
- fPriorityDialogField.setLabelText(PreferencesMessages.TodoTaskInputDialog_priority_label);
- fPriorityDialogField.setItems(items);
- if (task != null) {
- if (JavaScriptCore.COMPILER_TASK_PRIORITY_HIGH.equals(task.priority)) {
- fPriorityDialogField.selectItem(0);
- } else if (JavaScriptCore.COMPILER_TASK_PRIORITY_NORMAL.equals(task.priority)) {
- fPriorityDialogField.selectItem(1);
- } else {
- fPriorityDialogField.selectItem(2);
- }
- } else {
- fPriorityDialogField.selectItem(1);
- }
- }
-
- public TodoTask getResult() {
- TodoTask task= new TodoTask();
- task.name= fNameDialogField.getText().trim();
- switch (fPriorityDialogField.getSelectionIndex()) {
- case 0 :
- task.priority= JavaScriptCore.COMPILER_TASK_PRIORITY_HIGH;
- break;
- case 1 :
- task.priority= JavaScriptCore.COMPILER_TASK_PRIORITY_NORMAL;
- break;
- default :
- task.priority= JavaScriptCore.COMPILER_TASK_PRIORITY_LOW;
- break;
- }
- return task;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
-
- fNameDialogField.doFillIntoGrid(inner, 2);
- fPriorityDialogField.doFillIntoGrid(inner, 2);
-
- LayoutUtil.setHorizontalGrabbing(fNameDialogField.getTextControl(null));
- LayoutUtil.setWidthHint(fNameDialogField.getTextControl(null), convertWidthInCharsToPixels(45));
-
- fNameDialogField.postSetFocusOnDialogField(parent.getDisplay());
-
- applyDialogFont(composite);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.TASK_TAG_INPUT_DIALOG);
-
- return composite;
- }
-
- private void doValidation() {
- StatusInfo status= new StatusInfo();
- String newText= fNameDialogField.getText();
- if (newText.length() == 0) {
- status.setError(PreferencesMessages.TodoTaskInputDialog_error_enterName);
- } else {
- if (newText.indexOf(',') != -1) {
- status.setError(PreferencesMessages.TodoTaskInputDialog_error_comma);
- } else if (fExistingNames.contains(newText)) {
- status.setError(PreferencesMessages.TodoTaskInputDialog_error_entryExists);
- } else if (Character.isWhitespace(newText.charAt(0)) || Character.isWhitespace(newText.charAt(newText.length() - 1))) {
- status.setError(PreferencesMessages.TodoTaskInputDialog_error_noSpace);
- }
- }
- updateStatus(status);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.TODO_TASK_INPUT_DIALOG);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskPreferencePage.java
deleted file mode 100644
index 1960c358..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TodoTaskPreferencePage.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/*
- * The page to configure the task tags
- */
-public class TodoTaskPreferencePage extends PropertyAndPreferencePage {
-
- public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.TodoTaskPreferencePage"; //$NON-NLS-1$
- public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.TodoTaskPreferencePage"; //$NON-NLS-1$
-
- private TodoTaskConfigurationBlock fConfigurationBlock;
-
- public TodoTaskPreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setDescription(PreferencesMessages.TodoTaskPreferencePage_description);
-
- // only used when page is shown programatically
- setTitle(PreferencesMessages.TodoTaskPreferencePage_title);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- IWorkbenchPreferenceContainer container= (IWorkbenchPreferenceContainer) getContainer();
- fConfigurationBlock= new TodoTaskConfigurationBlock(getNewStatusChangedListener(), getProject(), container);
-
- super.createControl(parent);
-
- if (isProjectPreferencePage()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TODOTASK_PROPERTY_PAGE);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TODOTASK_PREFERENCE_PAGE);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#createPreferenceContent(org.eclipse.swt.widgets.Composite)
- */
- protected Control createPreferenceContent(Composite composite) {
- return fConfigurationBlock.createContents(composite);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#hasProjectSpecificOptions(org.eclipse.core.resources.IProject)
- */
- protected boolean hasProjectSpecificOptions(IProject project) {
- return fConfigurationBlock.hasProjectSpecificOptions(project);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPreferencePageID()
- */
- protected String getPreferencePageID() {
- return PREF_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#getPropertyPageID()
- */
- protected String getPropertyPageID() {
- return PROP_ID;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#enableProjectSpecificSettings(boolean)
- */
- protected void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- super.enableProjectSpecificSettings(useProjectSpecificSettings);
- if (fConfigurationBlock != null) {
- fConfigurationBlock.useProjectSpecificSettings(useProjectSpecificSettings);
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performDefaults();
- }
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- if (fConfigurationBlock != null && !fConfigurationBlock.performOk()) {
- return false;
- }
- return super.performOk();
- }
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performApply()
- */
- public void performApply() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.performApply();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- if (fConfigurationBlock != null) {
- fConfigurationBlock.dispose();
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.PropertyAndPreferencePage#setElement(org.eclipse.core.runtime.IAdaptable)
- */
- public void setElement(IAdaptable element) {
- super.setElement(element);
- setDescription(null); // no description for property page
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterInputDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterInputDialog.java
deleted file mode 100644
index d8a4b165..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterInputDialog.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.PackageSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-
-/**
- * Dialog to enter a new entry in the type filter preference page.
- */
-public class TypeFilterInputDialog extends StatusDialog {
-
- private class TypeFilterInputAdapter implements IDialogFieldListener, IStringButtonAdapter {
- /*
- * @see IDialogFieldListener#dialogFieldChanged(DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- doValidation();
- }
- /*
- * @see IStringButtonAdapter#changeControlPressed(DialogField)
- */
- public void changeControlPressed(DialogField field) {
- doButtonPressed();
- }
- }
-
- private StringButtonDialogField fNameDialogField;
- private List fExistingEntries;
-
- public TypeFilterInputDialog(Shell parent, List existingEntries) {
- super(parent);
-
- fExistingEntries= existingEntries;
-
- setTitle(PreferencesMessages.TypeFilterInputDialog_title);
-
- TypeFilterInputAdapter adapter= new TypeFilterInputAdapter();
-
- fNameDialogField= new StringButtonDialogField(adapter);
- fNameDialogField.setLabelText(PreferencesMessages.TypeFilterInputDialog_message);
- fNameDialogField.setButtonLabel(PreferencesMessages.TypeFilterInputDialog_browse_button);
- fNameDialogField.setDialogFieldListener(adapter);
-
- fNameDialogField.setText(""); //$NON-NLS-1$
- }
-
- public void setInitialString(String input) {
- Assert.isNotNull(input);
- fNameDialogField.setText(input);
- }
-
- public Object getResult() {
- return fNameDialogField.getText();
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- LayoutUtil.doDefaultLayout(inner, new DialogField[] { fNameDialogField }, true, 0, 0);
-
- int fieldWidthHint= convertWidthInCharsToPixels(60);
- Text text= fNameDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, fieldWidthHint);
- LayoutUtil.setHorizontalGrabbing(text);
- TextFieldNavigationHandler.install(text);
-
- fNameDialogField.postSetFocusOnDialogField(parent.getDisplay());
-
- applyDialogFont(composite);
- return composite;
- }
-
- private void doButtonPressed() {
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
- int flags= PackageSelectionDialog.F_SHOW_PARENTS | PackageSelectionDialog.F_HIDE_DEFAULT_PACKAGE | PackageSelectionDialog.F_REMOVE_DUPLICATES;
- PackageSelectionDialog dialog = new PackageSelectionDialog(getShell(), context, flags , scope);
- dialog.setTitle(PreferencesMessages.TypeFilterInputDialog_choosepackage_label);
- dialog.setMessage(PreferencesMessages.TypeFilterInputDialog_choosepackage_description);
- dialog.setMultipleSelection(false);
- dialog.setFilter(fNameDialogField.getText());
- if (dialog.open() == IDialogConstants.OK_ID) {
- IPackageFragment res= (IPackageFragment) dialog.getFirstResult();
- fNameDialogField.setText(res.getElementName() + "*"); //$NON-NLS-1$
- }
- }
-
- private void doValidation() {
- StatusInfo status= new StatusInfo();
- String newText= fNameDialogField.getText();
- if (newText.length() == 0) {
- status.setError(PreferencesMessages.TypeFilterInputDialog_error_enterName);
- } else {
- newText= newText.replace('*', 'X').replace('?', 'Y');
- IStatus val= JavaScriptConventions.validatePackageName(newText, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3);
- if (val.matches(IStatus.ERROR)) {
- status.setError(Messages.format(PreferencesMessages.TypeFilterInputDialog_error_invalidName, val.getMessage()));
- } else {
- if (fExistingEntries.contains(newText)) {
- status.setError(PreferencesMessages.TypeFilterInputDialog_error_entryExists);
- }
- }
- }
- updateStatus(status);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterPreferencePage.java
deleted file mode 100644
index 5f04d0a9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/TypeFilterPreferencePage.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.PackageSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/*
- * The page for setting the type filters
- */
-public class TypeFilterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- public static final String TYPE_FILTER_PREF_PAGE_ID= "org.eclipse.wst.jsdt.ui.preferences.TypeFilterPreferencePage"; //$NON-NLS-1$
-
- private static final String PREF_FILTER_ENABLED= PreferenceConstants.TYPEFILTER_ENABLED;
- private static final String PREF_FILTER_DISABLED= PreferenceConstants.TYPEFILTER_DISABLED;
-
- private static String[] unpackOrderList(String str) {
- StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
- int nTokens= tok.countTokens();
- String[] res= new String[nTokens];
- for (int i= 0; i < nTokens; i++) {
- res[i]= tok.nextToken();
- }
- return res;
- }
-
- private static String packOrderList(List orderList) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < orderList.size(); i++) {
- buf.append((String) orderList.get(i));
- buf.append(';');
- }
- return buf.toString();
- }
-
- private class TypeFilterAdapter implements IListAdapter, IDialogFieldListener {
-
- private boolean canEdit(ListDialogField field) {
- return field.getSelectedElements().size() == 1;
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doButtonPressed(index);
- }
-
- public void selectionChanged(ListDialogField field) {
- fFilterListField.enableButton(IDX_EDIT, canEdit(field));
- }
-
- public void dialogFieldChanged(DialogField field) {
- }
-
- public void doubleClicked(ListDialogField field) {
- if (canEdit(field)) {
- doButtonPressed(IDX_EDIT);
- }
- }
- }
-
- private static final int IDX_ADD= 0;
- private static final int IDX_ADD_PACKAGE= 1;
- private static final int IDX_EDIT= 2;
- private static final int IDX_REMOVE= 3;
- private static final int IDX_SELECT= 5;
- private static final int IDX_DESELECT= 6;
-
- private CheckedListDialogField fFilterListField;
-
- public TypeFilterPreferencePage() {
- super();
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- setDescription(PreferencesMessages.TypeFilterPreferencePage_description);
-
- String[] buttonLabels= new String[] {
- PreferencesMessages.TypeFilterPreferencePage_add_button,
- PreferencesMessages.TypeFilterPreferencePage_addpackage_button,
- PreferencesMessages.TypeFilterPreferencePage_edit_button,
- PreferencesMessages.TypeFilterPreferencePage_remove_button,
- /* 4 */ null,
- PreferencesMessages.TypeFilterPreferencePage_selectall_button,
- PreferencesMessages.TypeFilterPreferencePage_deselectall_button,
- };
-
- TypeFilterAdapter adapter= new TypeFilterAdapter();
-
- fFilterListField= new CheckedListDialogField(adapter, buttonLabels, new LabelProvider());
- fFilterListField.setDialogFieldListener(adapter);
- fFilterListField.setLabelText(PreferencesMessages.TypeFilterPreferencePage_list_label);
- fFilterListField.setCheckAllButtonIndex(IDX_SELECT);
- fFilterListField.setUncheckAllButtonIndex(IDX_DESELECT);
- fFilterListField.setRemoveButtonIndex(IDX_REMOVE);
-
- fFilterListField.enableButton(IDX_EDIT, false);
-
- initialize(false);
- }
-
- /*
- * @see PreferencePage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TYPE_FILTER_PREFERENCE_PAGE);
- }
-
- protected Control createContents(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
-
- composite.setLayout(layout);
-
- fFilterListField.doFillIntoGrid(composite, 3);
- LayoutUtil.setHorizontalSpan(fFilterListField.getLabelControl(null), 2);
- LayoutUtil.setWidthHint(fFilterListField.getLabelControl(null), convertWidthInCharsToPixels(40));
- LayoutUtil.setHorizontalGrabbing(fFilterListField.getListControl(null));
-
- fFilterListField.getTableViewer().setComparator(new ViewerComparator());
-
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- private void initialize(boolean fromDefault) {
- IPreferenceStore store= getPreferenceStore();
-
- String enabled= fromDefault ? store.getDefaultString(PREF_FILTER_ENABLED) : store.getString(PREF_FILTER_ENABLED);
- String disabled= fromDefault ? store.getDefaultString(PREF_FILTER_DISABLED) : store.getString(PREF_FILTER_DISABLED);
-
- ArrayList res= new ArrayList();
-
- String[] enabledEntries= unpackOrderList(enabled);
- for (int i= 0; i < enabledEntries.length; i++) {
- res.add(enabledEntries[i]);
- }
- String[] disabledEntries= unpackOrderList(disabled);
- for (int i= 0; i < disabledEntries.length; i++) {
- res.add(disabledEntries[i]);
- }
-
- fFilterListField.setElements(res);
- fFilterListField.setCheckedElements(Arrays.asList(enabledEntries));
- }
-
-
- private void doButtonPressed(int index) {
- if (index == IDX_ADD) { // add new
- List existing= fFilterListField.getElements();
- TypeFilterInputDialog dialog= new TypeFilterInputDialog(getShell(), existing);
- if (dialog.open() == Window.OK) {
- Object res= dialog.getResult();
- fFilterListField.addElement(res);
- fFilterListField.setChecked(res, true);
- }
- } else if (index == IDX_ADD_PACKAGE) { // add packages
- String[] res= choosePackage();
- if (res != null) {
- fFilterListField.addElements(Arrays.asList(res));
- for (int i= 0; i < res.length; i++) {
- fFilterListField.setChecked(res[i], true);
- }
- }
-
- } else if (index == IDX_EDIT) { // edit
- List selected= fFilterListField.getSelectedElements();
- if (selected.isEmpty()) {
- return;
- }
- String editedEntry= (String) selected.get(0);
-
- List existing= fFilterListField.getElements();
- existing.remove(editedEntry);
-
- TypeFilterInputDialog dialog= new TypeFilterInputDialog(getShell(), existing);
- dialog.setInitialString(editedEntry);
- if (dialog.open() == Window.OK) {
- fFilterListField.replaceElement(editedEntry, dialog.getResult());
- }
- }
- }
-
- private String[] choosePackage() {
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
- int flags= PackageSelectionDialog.F_SHOW_PARENTS | PackageSelectionDialog.F_HIDE_DEFAULT_PACKAGE | PackageSelectionDialog.F_REMOVE_DUPLICATES;
- PackageSelectionDialog dialog = new PackageSelectionDialog(getShell(), context, flags , scope);
- dialog.setTitle(PreferencesMessages.TypeFilterPreferencePage_choosepackage_label);
- dialog.setMessage(PreferencesMessages.TypeFilterPreferencePage_choosepackage_description);
- dialog.setMultipleSelection(true);
- if (dialog.open() == IDialogConstants.OK_ID) {
- Object[] fragments= dialog.getResult();
- String[] res= new String[fragments.length];
- for (int i= 0; i < res.length; i++) {
- res[i]= ((IPackageFragment) fragments[i]).getElementName() + ".*"; //$NON-NLS-1$
- }
- return res;
- }
- return null;
- }
-
-
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- initialize(true);
-
- super.performDefaults();
- }
-
-
- /*
- * @see org.eclipse.jface.preference.IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore prefs= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- List checked= fFilterListField.getCheckedElements();
- List unchecked= fFilterListField.getElements();
- unchecked.removeAll(checked);
-
- prefs.setValue(PREF_FILTER_ENABLED, packOrderList(checked));
- prefs.setValue(PREF_FILTER_DISABLED, packOrderList(unchecked));
- JavaScriptPlugin.getDefault().savePluginPreferences();
- return true;
- }
-
-
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/UserLibraryPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/UserLibraryPreferencePage.java
deleted file mode 100644
index e53aae1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/UserLibraryPreferencePage.java
+++ /dev/null
@@ -1,1311 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.jface.resource.StringConverter;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.AccessRulesDialog;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathSupport;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElementAttribute;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElementSorter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPUserLibraryElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ClasspathAttributeConfigurationDescriptors;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.TreeListDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-public class UserLibraryPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- public static final String ID= "org.eclipse.wst.jsdt.ui.preferences.UserLibraryPreferencePage"; //$NON-NLS-1$
- public static final String DATA_DO_CREATE= "do_create"; //$NON-NLS-1$
- public static final String DATA_LIBRARY_TO_SELECT= "select_library"; //$NON-NLS-1$
-
- public static class LibraryNameDialog extends StatusDialog implements IDialogFieldListener {
-
- private StringDialogField fNameField;
-
- private CPUserLibraryElement fElementToEdit;
- private List fExistingLibraries;
-
- public LibraryNameDialog(Shell parent, CPUserLibraryElement elementToEdit, List existingLibraries) {
- super(parent);
- if (elementToEdit == null) {
- setTitle(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_new_title);
- } else {
- setTitle(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_edit_title);
- }
-
- fElementToEdit= elementToEdit;
- fExistingLibraries= existingLibraries;
-
- fNameField= new StringDialogField();
- fNameField.setDialogFieldListener(this);
- fNameField.setLabelText(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_label);
-
- if (elementToEdit != null) {
- fNameField.setText(elementToEdit.getName());
- } else {
- fNameField.setText(""); //$NON-NLS-1$
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fNameField }, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fNameField.getTextControl(null));
- fNameField.postSetFocusOnDialogField(parent.getDisplay());
-
- Dialog.applyDialogFont(composite);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.CP_EDIT_USER_LIBRARY);
-
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- if (field == fNameField) {
- updateStatus(validateSettings());
- }
- }
-
- private IStatus validateSettings() {
- String name= fNameField.getText();
- if (name.length() == 0) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_error_entername);
- }
- for (int i= 0; i < fExistingLibraries.size(); i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) fExistingLibraries.get(i);
- if (curr != fElementToEdit && name.equals(curr.getName())) {
- return new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_error_exists, name));
- }
- }
- IStatus status= ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
- if (status.matches(IStatus.ERROR)) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LibraryNameDialog_name_error_invalid);
- }
- return StatusInfo.OK_STATUS;
- }
-
- public CPUserLibraryElement getNewLibrary() {
- CPListElement[] entries= null;
- if (fElementToEdit != null) {
- entries= fElementToEdit.getChildren();
- }
- return new CPUserLibraryElement(fNameField.getText(), entries);
- }
-
- }
-
- public static class LoadSaveDialog extends StatusDialog implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
-
-
- private static final String VERSION1= "1"; //$NON-NLS-1$ // using OS strings for archive path and source attachment
- private static final String CURRENT_VERSION= "2"; //$NON-NLS-1$
-
- private static final String TAG_ROOT= "eclipse-userlibraries"; //$NON-NLS-1$
- private static final String TAG_VERSION= "version"; //$NON-NLS-1$
- private static final String TAG_LIBRARY= "library"; //$NON-NLS-1$
- private static final String TAG_ARCHIVE_PATH= "path"; //$NON-NLS-1$
- private static final String TAG_ARCHIVE= "archive"; //$NON-NLS-1$
- private static final String TAG_NAME= "name"; //$NON-NLS-1$
- private static final String TAG_JSDOC= "jsdoc"; //$NON-NLS-1$
- private static final String TAG_ACCESSRULES= "accessrules"; //$NON-NLS-1$
- private static final String TAG_ACCESSRULE= "accessrule"; //$NON-NLS-1$
- private static final String TAG_RULE_KIND= "kind"; //$NON-NLS-1$
- private static final String TAG_RULE_PATTERN= "pattern"; //$NON-NLS-1$
-
- private static final String PREF_LASTPATH= JavaScriptUI.ID_PLUGIN + ".lastuserlibrary"; //$NON-NLS-1$
- private static final String PREF_USER_LIBRARY_LOADSAVE_SIZE= "UserLibraryLoadSaveDialog.size"; //$NON-NLS-1$
-
- private List fExistingLibraries;
- private IDialogSettings fSettings;
-
- private File fLastFile;
-
- private StringButtonDialogField fLocationField;
- private CheckedListDialogField fExportImportList;
- private Point fInitialSize;
- private final boolean fIsSave;
-
- public LoadSaveDialog(Shell shell, boolean isSave, List existingLibraries, IDialogSettings dialogSettings) {
- super(shell);
- initializeDialogUnits(shell);
-
- setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
-
- fExistingLibraries= existingLibraries;
- fSettings= dialogSettings;
- fLastFile= null;
- fIsSave= isSave;
-
- int defaultWidth= convertWidthInCharsToPixels(80);
- int defaultHeigth= convertHeightInCharsToPixels(34);
- String lastSize= fSettings.get(PREF_USER_LIBRARY_LOADSAVE_SIZE);
- if (lastSize != null) {
- fInitialSize= StringConverter.asPoint(lastSize, new Point(defaultWidth, defaultHeigth));
- } else {
- fInitialSize= new Point(defaultWidth, defaultHeigth);
- }
-
- if (isSave()) {
- setTitle(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_title);
- } else {
- setTitle(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_title);
- }
-
- fLocationField= new StringButtonDialogField(this);
- fLocationField.setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_label);
- fLocationField.setButtonLabel(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_button);
- fLocationField.setDialogFieldListener(this);
-
- String[] buttonNames= new String[] {
- PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_selectall_button,
- PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_deselectall_button
- };
- fExportImportList= new CheckedListDialogField(this, buttonNames, new CPListLabelProvider());
- fExportImportList.setCheckAllButtonIndex(0);
- fExportImportList.setUncheckAllButtonIndex(1);
- fExportImportList.setViewerComparator(new CPListElementSorter());
- fExportImportList.setDialogFieldListener(this);
- if (isSave()) {
- fExportImportList.setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_save_label);
- fExportImportList.setElements(fExistingLibraries);
- fExportImportList.checkAll(true);
- } else {
- fExportImportList.setLabelText(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_load_label);
- }
- String lastPath= fSettings.get(PREF_LASTPATH);
- if (lastPath != null) {
- fLocationField.setText(lastPath);
- } else {
- fLocationField.setText(""); //$NON-NLS-1$
- }
- }
-
- protected Point getInitialSize() {
- return fInitialSize;
- }
-
- private boolean isSave() {
- return fIsSave;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- DialogField[] fields;
- if (isSave()) {
- fields= new DialogField[] { fExportImportList, fLocationField };
- } else {
- fields= new DialogField[] { fLocationField, fExportImportList };
- }
- LayoutUtil.doDefaultLayout(composite, fields, true, SWT.DEFAULT, SWT.DEFAULT);
- fExportImportList.getListControl(null).setLayoutData(new GridData(GridData.FILL_BOTH));
-
- fLocationField.postSetFocusOnDialogField(parent.getDisplay());
-
- Dialog.applyDialogFont(composite);
-
- if (isSave()) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.CP_EXPORT_USER_LIBRARY);
- } else {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.CP_IMPORT_USER_LIBRARY);
- }
-
- return composite;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void changeControlPressed(DialogField field) {
- String label= isSave() ? PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_filedialog_save_title : PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_filedialog_load_title;
- FileDialog dialog= new FileDialog(getShell(), isSave() ? SWT.SAVE : SWT.OPEN);
- dialog.setText(label);
- dialog.setFilterExtensions(new String[] {"*.userlibraries", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
- String lastPath= fLocationField.getText();
- if (lastPath.length() == 0 || !new File(lastPath).exists()) {
- lastPath= fSettings.get(PREF_LASTPATH);
- }
- if (lastPath != null) {
- dialog.setFileName(lastPath);
- }
- String fileName= dialog.open();
- if (fileName != null) {
- fSettings.put(PREF_LASTPATH, fileName);
- fLocationField.setText(fileName);
- }
- }
-
- private IStatus updateShownLibraries(IStatus status) {
- if (!status.isOK()) {
- fExportImportList.removeAllElements();
- fExportImportList.setEnabled(false);
- fLastFile= null;
- } else {
- File file= new File(fLocationField.getText());
- if (!file.equals(fLastFile)) {
- fLastFile= file;
- try {
- List elements= loadLibraries(file);
- fExportImportList.setElements(elements);
- fExportImportList.checkAll(true);
- fExportImportList.setEnabled(true);
- if (elements.isEmpty()) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_error_empty);
- }
- } catch (IOException e) {
- fExportImportList.removeAllElements();
- fExportImportList.setEnabled(false);
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_error_invalidfile);
- }
- }
- }
- return status;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- if (field == fLocationField) {
- IStatus status= validateSettings();
- if (!isSave()) {
- status= updateShownLibraries(status);
- }
- updateStatus(status);
- } else if (field == fExportImportList) {
- updateStatus(validateSettings());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField, int)
- */
- public void customButtonPressed(ListDialogField field, int index) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void selectionChanged(ListDialogField field) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#doubleClicked(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void doubleClicked(ListDialogField field) {
- List selectedElements= fExportImportList.getSelectedElements();
- if (selectedElements.size() == 1) {
- Object elem= selectedElements.get(0);
- fExportImportList.setChecked(elem, !fExportImportList.isChecked(elem));
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- if (isSave()) {
- final File file= new File(fLocationField.getText());
- if (file.exists()) {
- String title= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_overwrite_title;
- String message= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_overwrite_message;
- if (!MessageDialog.openQuestion(getShell(), title, message)) {
- return;
- }
- }
- try {
- String encoding= "UTF-8"; //$NON-NLS-1$
- IPath filePath= Path.fromOSString(file.getCanonicalPath());
- final IPath workspacePath= ResourcesPlugin.getWorkspace().getRoot().getLocation();
- if (filePath.matchingFirstSegments(workspacePath) == workspacePath.segmentCount()) {
- IPath path= filePath.removeFirstSegments(workspacePath.segmentCount());
- path= path.makeRelative();
- final IFile result= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
- try {
- encoding= result.getCharset(true);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- final List elements= fExportImportList.getCheckedElements();
- final String charset= encoding;
- IRunnableContext context= PlatformUI.getWorkbench().getProgressService();
- try {
- context.run(true, true, new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- saveLibraries(elements, file, charset, monitor);
- } catch (IOException e) {
- throw new InvocationTargetException(e);
- }
- }
- });
- fSettings.put(PREF_LASTPATH, file.getPath());
- } catch (InvocationTargetException e) {
- String errorTitle= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_title;
- String errorMessage= Messages.format(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_message, e.getMessage());
- ExceptionHandler.handle(e, getShell(), errorTitle, errorMessage);
- return;
- } catch (InterruptedException e) {
- // cancelled
- return;
- }
- String savedTitle= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_ok_title;
- String savedMessage= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_save_ok_message;
- MessageDialog.openInformation(getShell(), savedTitle, savedMessage);
- } catch (IOException exception) {
- JavaScriptPlugin.log(exception);
- }
- } else {
- HashSet map= new HashSet(fExistingLibraries.size());
- for (int k= 0; k < fExistingLibraries.size(); k++) {
- CPUserLibraryElement elem= (CPUserLibraryElement) fExistingLibraries.get(k);
- map.add(elem.getName());
- }
- int nReplaced= 0;
- List elements= getLoadedLibraries();
- for (int i= 0; i < elements.size(); i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) elements.get(i);
- if (map.contains(curr.getName())) {
- nReplaced++;
- }
- }
- if (nReplaced > 0) {
- String replaceTitle= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_title;
- String replaceMessage;
- if (nReplaced == 1) {
- replaceMessage= PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_message;
- } else {
- replaceMessage= Messages.format(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_replace_multiple_message, String.valueOf(nReplaced));
- }
- if (!MessageDialog.openConfirm(getShell(), replaceTitle, replaceMessage)) {
- return;
- }
- }
- }
- super.okPressed();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#close()
- */
- public boolean close() {
- Point point= getShell().getSize();
- fSettings.put(PREF_USER_LIBRARY_LOADSAVE_SIZE, StringConverter.asString(point));
- return super.close();
- }
-
- private IStatus validateSettings() {
- String name= fLocationField.getText();
- fLastFile= null;
- if (isSave()) {
- if (name.length() == 0) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_save_enterlocation);
- }
- File file= new File(name);
- if (file.isDirectory()) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_save_invalid);
- }
- if (fExportImportList.getCheckedSize() == 0) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_error_save_nothingselected);
- }
- fLastFile= file;
- } else {
- if (name.length() == 0) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_load_enterlocation);
- }
- if (!new File(name).isFile()) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_location_error_load_invalid);
- }
- if (fExportImportList.getSize() > 0 && fExportImportList.getCheckedSize() == 0) {
- return new StatusInfo(IStatus.ERROR, PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_list_error_load_nothingselected);
- }
- }
- return new StatusInfo();
- }
-
- protected static void saveLibraries(List libraries, File file, String encoding, IProgressMonitor monitor) throws IOException {
- OutputStream stream= new FileOutputStream(file);
- try {
- DocumentBuilder docBuilder= null;
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- docBuilder= factory.newDocumentBuilder();
- Document document= docBuilder.newDocument();
-
- // Create the document
- Element rootElement= document.createElement(TAG_ROOT);
- document.appendChild(rootElement);
-
- rootElement.setAttribute(TAG_VERSION, CURRENT_VERSION);
-
- for (int i= 0; i < libraries.size(); i++) {
- Element libraryElement= document.createElement(TAG_LIBRARY);
- rootElement.appendChild(libraryElement);
-
- CPUserLibraryElement curr= (CPUserLibraryElement) libraries.get(i);
- libraryElement.setAttribute(TAG_NAME, curr.getName());
-
- CPListElement[] children= curr.getChildren();
- for (int k= 0; k < children.length; k++) {
- CPListElement child= children[k];
-
- Element childElement= document.createElement(TAG_ARCHIVE);
- libraryElement.appendChild(childElement);
-
- childElement.setAttribute(TAG_ARCHIVE_PATH, child.getPath().toPortableString());
-
- String javadocLocation= (String) child.getAttribute(CPListElement.JAVADOC);
- if (javadocLocation != null) {
- childElement.setAttribute(TAG_JSDOC, javadocLocation);
- }
-
- IAccessRule[] accessRules= (IAccessRule[]) child.getAttribute(CPListElement.ACCESSRULES);
- if (accessRules != null && accessRules.length > 0) {
- Element rulesElement= document.createElement(TAG_ACCESSRULES);
- childElement.appendChild(rulesElement);
- for (int n= 0; n < accessRules.length; n++) {
- IAccessRule rule= accessRules[n];
- Element ruleElement= document.createElement(TAG_ACCESSRULE);
- rulesElement.appendChild(ruleElement);
- ruleElement.setAttribute(TAG_RULE_KIND, String.valueOf(rule.getKind()));
- ruleElement.setAttribute(TAG_RULE_PATTERN, rule.getPattern().toPortableString());
- }
- }
- }
- }
-
- // Write the document to the stream
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
- transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
-
- DOMSource source = new DOMSource(document);
- StreamResult result = new StreamResult(stream);
- transformer.transform(source, result);
- } catch (ParserConfigurationException e) {
- throw new IOException(e.getMessage());
- } catch (TransformerException e) {
- throw new IOException(e.getMessage());
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // ignore
- }
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
- private static List loadLibraries(File file) throws IOException {
- InputStream stream= new FileInputStream(file);
- Element cpElement;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- cpElement = parser.parse(new InputSource(stream)).getDocumentElement();
- } catch (SAXException e) {
- throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
- } catch (ParserConfigurationException e) {
- throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
- } finally {
- stream.close();
- }
-
- if (!cpElement.getNodeName().equalsIgnoreCase(TAG_ROOT)) {
- throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
- }
-
- String version= cpElement.getAttribute(TAG_VERSION);
-
- NodeList libList= cpElement.getElementsByTagName(TAG_LIBRARY);
- int length = libList.getLength();
-
- ArrayList result= new ArrayList(length);
- for (int i= 0; i < length; i++) {
- Node lib= libList.item(i);
- if (!(lib instanceof Element)) {
- continue;
- }
- Element libElement= (Element) lib;
- String name= libElement.getAttribute(TAG_NAME);
-
- CPUserLibraryElement newLibrary= new CPUserLibraryElement(name, null);
- result.add(newLibrary);
-
- NodeList archiveList= libElement.getElementsByTagName(TAG_ARCHIVE);
- for (int k= 0; k < archiveList.getLength(); k++) {
- Node archiveNode= archiveList.item(k);
- if (!(archiveNode instanceof Element)) {
- continue;
- }
- Element archiveElement= (Element) archiveNode;
-
- String pathString= archiveElement.getAttribute(TAG_ARCHIVE_PATH);
- IPath path= version.equals(VERSION1) ? Path.fromOSString(pathString) : Path.fromPortableString(pathString);
- CPListElement newArchive= new CPListElement(newLibrary, null, IIncludePathEntry.CPE_LIBRARY, path, null);
- newLibrary.add(newArchive);
-
- if (archiveElement.hasAttribute(TAG_JSDOC)) {
- String javadoc= archiveElement.getAttribute(TAG_JSDOC);
- newArchive.setAttribute(CPListElement.JAVADOC, javadoc);
- }
-
- NodeList rulesParentNodes= archiveElement.getElementsByTagName(TAG_ACCESSRULES);
- if (rulesParentNodes.getLength() > 0 && rulesParentNodes.item(0) instanceof Element) {
- Element ruleParentElement= (Element) rulesParentNodes.item(0); // take first, ignore others
- NodeList ruleElements= ruleParentElement.getElementsByTagName(TAG_ACCESSRULE);
- int nRuleElements= ruleElements.getLength();
- if (nRuleElements > 0) {
- ArrayList resultingRules= new ArrayList(nRuleElements);
- for (int n= 0; n < nRuleElements; n++) {
- Node node= ruleElements.item(n);
- if (node instanceof Element) {
- Element ruleElement= (Element) node;
- try {
- int kind= Integer.parseInt(ruleElement.getAttribute(TAG_RULE_KIND));
- IPath pattern= Path.fromPortableString(ruleElement.getAttribute(TAG_RULE_PATTERN));
- resultingRules.add(JavaScriptCore.newAccessRule(pattern, kind));
- } catch (NumberFormatException e) {
- // ignore
- }
- }
- }
- newArchive.setAttribute(CPListElement.ACCESSRULES, resultingRules.toArray(new IAccessRule[resultingRules.size()]));
- }
- }
- }
- }
- return result;
- }
-
- public List getLoadedLibraries() {
- return fExportImportList.getCheckedElements();
- }
- }
-
- private IDialogSettings fDialogSettings;
- private TreeListDialogField fLibraryList;
- private IJavaScriptProject fDummyProject;
- private ClasspathAttributeConfigurationDescriptors fAttributeDescriptors;
-
- private static final int IDX_NEW= 0;
- private static final int IDX_EDIT= 1;
- private static final int IDX_ADD_FILE= 2;
- private static final int IDX_ADD_FOLDER=3;
- private static final int IDX_REMOVE= 4;
- private static final int IDX_LOAD= 5;
- private static final int IDX_SAVE= 6;
-
- /**
- * Constructor for ClasspathVariablesPreferencePage
- */
- public UserLibraryPreferencePage() {
- setPreferenceStore(JavaScriptPlugin.getDefault().getPreferenceStore());
- fDummyProject= createPlaceholderProject();
-
- fAttributeDescriptors= JavaScriptPlugin.getDefault().getClasspathAttributeConfigurationDescriptors();
-
- // title only used when page is shown programatically
- setTitle(PreferencesMessages.UserLibraryPreferencePage_title);
- setDescription(PreferencesMessages.UserLibraryPreferencePage_description);
- noDefaultAndApplyButton();
-
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- UserLibraryAdapter adapter= new UserLibraryAdapter();
- String[] buttonLabels= new String[] {
- PreferencesMessages.UserLibraryPreferencePage_libraries_new_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_edit_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_addjar_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_addfolder_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_remove_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_load_button,
- PreferencesMessages.UserLibraryPreferencePage_libraries_save_button
- };
-
- fLibraryList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fLibraryList.setLabelText(PreferencesMessages.UserLibraryPreferencePage_libraries_label);
-
- String[] names= JavaScriptCore.getUserLibraryNames();
- ArrayList elements= new ArrayList();
-
- for (int i= 0; i < names.length; i++) {
- IPath path= new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(names[i]);
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(path, fDummyProject);
- elements.add(new CPUserLibraryElement(names[i], container, fDummyProject));
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- // ignore
- }
- }
- fLibraryList.setElements(elements);
- fLibraryList.setViewerComparator(new CPListElementSorter());
-
- doSelectionChanged(fLibraryList); //update button enable state
- }
-
- private static IJavaScriptProject createPlaceholderProject() {
- String name= "####jsdtinternal"; //$NON-NLS-1$
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- while (true) {
- IProject project= root.getProject(name);
- if (!project.exists()) {
- return JavaScriptCore.create(project);
- }
- name += '1';
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object)
- */
- public void applyData(Object data) {
- if (data instanceof Map) {
- Map map= (Map) data;
- Object selectedLibrary= map.get(DATA_LIBRARY_TO_SELECT);
- boolean createIfNotExists= Boolean.TRUE.equals(map.get(DATA_DO_CREATE));
- if (selectedLibrary instanceof String) {
- int nElements= fLibraryList.getSize();
- for (int i= 0; i < nElements; i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) fLibraryList.getElement(i);
- if (curr.getName().equals(selectedLibrary)) {
- fLibraryList.selectElements(new StructuredSelection(curr));
- fLibraryList.expandElement(curr, 1);
- break;
- }
- }
- if (createIfNotExists) {
- CPUserLibraryElement elem= new CPUserLibraryElement((String) selectedLibrary, null, createPlaceholderProject());
- fLibraryList.addElement(elem);
- fLibraryList.selectElements(new StructuredSelection(elem));
- }
- }
- }
- }
-
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CP_USERLIBRARIES_PREFERENCE_PAGE);
- }
-
- /*
- * @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
- */
- protected Control createContents(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibraryList }, true);
- LayoutUtil.setHorizontalGrabbing(fLibraryList.getTreeControl(null));
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- /*
- * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- super.performDefaults();
- }
-
- /*
- * @see PreferencePage#performOk()
- */
- public boolean performOk() {
- try {
- PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- if (monitor != null) {
- monitor= new NullProgressMonitor();
- }
-
- updateUserLibararies(monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- });
- } catch (InterruptedException e) {
- // cancelled by user
- } catch (InvocationTargetException e) {
- String title= PreferencesMessages.UserLibraryPreferencePage_config_error_title;
- String message= PreferencesMessages.UserLibraryPreferencePage_config_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
- return true;
- }
-
-
- private void updateUserLibararies(IProgressMonitor monitor) throws CoreException {
- List list= fLibraryList.getElements();
- HashSet oldNames= new HashSet(Arrays.asList(JavaScriptCore.getUserLibraryNames()));
- int nExisting= list.size();
-
- HashSet newEntries= new HashSet(list.size());
- for (int i= 0; i < nExisting; i++) {
- CPUserLibraryElement element= (CPUserLibraryElement) list.get(i);
- boolean contained= oldNames.remove(element.getName());
- if (!contained) {
- newEntries.add(element);
- }
- }
-
- int len= nExisting + oldNames.size();
- monitor.beginTask(PreferencesMessages.UserLibraryPreferencePage_operation, len);
- MultiStatus multiStatus= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, PreferencesMessages.UserLibraryPreferencePage_operation_error, null);
-
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(JavaScriptCore.USER_LIBRARY_CONTAINER_ID);
- IJavaScriptProject jproject= fDummyProject;
-
- for (int i= 0; i < nExisting; i++) {
- CPUserLibraryElement element= (CPUserLibraryElement) list.get(i);
- IPath path= element.getPath();
- if (newEntries.contains(element) || element.hasChanges(JavaScriptCore.getJsGlobalScopeContainer(path, jproject))) {
- IJsGlobalScopeContainer updatedContainer= element.getUpdatedContainer();
- try {
- initializer.requestJsGlobalScopeContainerUpdate(path, jproject, updatedContainer);
- } catch (CoreException e) {
- multiStatus.add(e.getStatus());
- }
- }
- monitor.worked(1);
- }
-
- Iterator iter= oldNames.iterator();
- while (iter.hasNext()) {
- String name= (String) iter.next();
-
- IPath path= new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(name);
- try {
- initializer.requestJsGlobalScopeContainerUpdate(path, jproject, null);
- } catch (CoreException e) {
- multiStatus.add(e.getStatus());
- }
- monitor.worked(1);
- }
-
- if (!multiStatus.isOK()) {
- throw new CoreException(multiStatus);
- }
- }
-
- private CPUserLibraryElement getSingleSelectedLibrary(List selected) {
- if (selected.size() == 1 && selected.get(0) instanceof CPUserLibraryElement) {
- return (CPUserLibraryElement) selected.get(0);
- }
- return null;
- }
-
- private void editAttributeEntry(CPListElementAttribute elem) {
- String key= elem.getKey();
- CPListElement selElement= elem.getParent();
- if (key.equals(CPListElement.ACCESSRULES)) {
- AccessRulesDialog dialog= new AccessRulesDialog(getShell(), selElement, null, false);
- if (dialog.open() == Window.OK) {
- selElement.setAttribute(CPListElement.ACCESSRULES, dialog.getAccessRules());
- fLibraryList.refresh(elem);
- fLibraryList.expandElement(elem, 2);
- }
- } else if (!elem.isBuiltIn()) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(key);
- if (config != null) {
- IIncludePathAttribute result= config.performEdit(getShell(), elem.getClasspathAttributeAccess());
- if (result != null) {
- elem.setValue(result.getValue());
- fLibraryList.refresh(elem);
- }
- }
- }
- }
-
- protected void doSelectionChanged(TreeListDialogField field) {
- List list= field.getSelectedElements();
- field.enableButton(IDX_REMOVE, canRemove(list));
- field.enableButton(IDX_EDIT, canEdit(list));
- field.enableButton(IDX_ADD_FILE, canAdd(list));
- field.enableButton(IDX_ADD_FOLDER, canAdd(list));
- field.enableButton(IDX_SAVE, field.getSize() > 0);
- }
-
- protected void doCustomButtonPressed(TreeListDialogField field, int index) {
- if (index == IDX_NEW) {
- editUserLibraryElement(null);
- } else if (index == IDX_ADD_FILE) {
- doAdd(field.getSelectedElements());
- } else if (index == IDX_ADD_FOLDER) {
- doAddFolder(field.getSelectedElements());
- } else if (index == IDX_REMOVE) {
- doRemove(field.getSelectedElements());
- } else if (index == IDX_EDIT) {
- doEdit(field.getSelectedElements());
- } else if (index == IDX_SAVE) {
- doSave();
- } else if (index == IDX_LOAD) {
- doLoad();
- }
- }
-
- protected void doDoubleClicked(TreeListDialogField field) {
- List selected= field.getSelectedElements();
- if (canEdit(selected)) {
- doEdit(field.getSelectedElements());
- }
- }
-
- protected void doKeyPressed(TreeListDialogField field, KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- List selection= field.getSelectedElements();
- if (canRemove(selection)) {
- doRemove(selection);
- }
- }
- }
-
- private void doEdit(List selected) {
- if (selected.size() == 1) {
- Object curr= selected.get(0);
- if (curr instanceof CPListElementAttribute) {
- editAttributeEntry((CPListElementAttribute) curr);
- } else if (curr instanceof CPUserLibraryElement) {
- editUserLibraryElement((CPUserLibraryElement) curr);
- } else if (curr instanceof CPListElement) {
- CPListElement elem= (CPListElement) curr;
- if(elem.getPath().lastSegment().endsWith(".js")) { //$NON-NLS-1$
- editArchiveElement(elem, (CPUserLibraryElement) elem.getParentContainer(), false);
- } else {
- editArchiveElement(elem, (CPUserLibraryElement) elem.getParentContainer(), true);
- }
- }
- doSelectionChanged(fLibraryList);
- }
- }
-
- private void editUserLibraryElement(CPUserLibraryElement element) {
- LibraryNameDialog dialog= new LibraryNameDialog(getShell(), element, fLibraryList.getElements());
- if (dialog.open() == Window.OK) {
- CPUserLibraryElement newLibrary= dialog.getNewLibrary();
- if (element != null) {
- fLibraryList.replaceElement(element, newLibrary);
- } else {
- fLibraryList.addElement(newLibrary);
- }
- fLibraryList.expandElement(newLibrary, AbstractTreeViewer.ALL_LEVELS);
- fLibraryList.selectElements(new StructuredSelection(newLibrary));
- }
- }
-
- private void editArchiveElement(CPListElement existingElement, CPUserLibraryElement parent, boolean isFolder) {
- CPListElement[] elements= null;
- if(isFolder) {
- elements = openExtJsFolderDialog(parent);
- } else {
- elements = openExtJSFileDialog(existingElement, parent);
- }
- if (elements != null) {
- for (int i= 0; i < elements.length; i++) {
- if (existingElement != null) {
- parent.replace(existingElement, elements[i]);
- } else {
- parent.add(elements[i]);
- }
- }
- fLibraryList.refresh(parent);
- fLibraryList.selectElements(new StructuredSelection(Arrays.asList(elements)));
- fLibraryList.expandElement(parent, 2);
- }
- }
-
-
- private void doRemove(List selected) {
- Object selectionAfter= null;
- for (int i= 0; i < selected.size(); i++) {
- Object curr= selected.get(i);
- if (curr instanceof CPUserLibraryElement) {
- fLibraryList.removeElement(curr);
- } else if (curr instanceof CPListElement) {
- Object parent= ((CPListElement) curr).getParentContainer();
- if (parent instanceof CPUserLibraryElement) {
- CPUserLibraryElement elem= (CPUserLibraryElement) parent;
- elem.remove((CPListElement) curr);
- fLibraryList.refresh(elem);
- selectionAfter= parent;
- }
- } else if (curr instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) curr;
- if (attrib.isBuiltIn()) {
- Object value= null;
- String key= attrib.getKey();
- if (key.equals(CPListElement.ACCESSRULES)) {
- value= new IAccessRule[0];
- }
- attrib.getParent().setAttribute(key, value);
- fLibraryList.refresh(attrib);
- } else {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(attrib.getKey());
- if (config != null) {
- IIncludePathAttribute result= config.performRemove(attrib.getClasspathAttributeAccess());
- if (result != null) {
- attrib.setValue(result.getValue());
- fLibraryList.refresh(attrib);
- }
- }
- }
- }
- }
- if (fLibraryList.getSelectedElements().isEmpty()) {
- if (selectionAfter != null) {
- fLibraryList.selectElements(new StructuredSelection(selectionAfter));
- } else {
- fLibraryList.selectFirstElement();
- }
- } else {
- doSelectionChanged(fLibraryList);
- }
- }
-
- private void doAdd(List list) {
- if (canAdd(list)) {
- CPUserLibraryElement element= getSingleSelectedLibrary(list);
- editArchiveElement(null, element, false);
- }
- }
-
- private void doAddFolder(List list) {
- if (canAdd(list)) {
- CPUserLibraryElement element= getSingleSelectedLibrary(list);
- editArchiveElement(null, element, true);
- }
- }
-
- private void doLoad() {
- List existing= fLibraryList.getElements();
- LoadSaveDialog dialog= new LoadSaveDialog(getShell(), false, existing, fDialogSettings);
- if (dialog.open() == Window.OK) {
- HashMap map= new HashMap(existing.size());
- for (int k= 0; k < existing.size(); k++) {
- CPUserLibraryElement elem= (CPUserLibraryElement) existing.get(k);
- map.put(elem.getName(), elem);
- }
-
- List list= dialog.getLoadedLibraries();
- for (int i= 0; i < list.size(); i++) {
- CPUserLibraryElement elem= (CPUserLibraryElement) list.get(i);
- CPUserLibraryElement found= (CPUserLibraryElement) map.get(elem.getName());
- if (found == null) {
- existing.add(elem);
- map.put(elem.getName(), elem);
- } else {
- existing.set(existing.indexOf(found), elem); // replace
- }
- }
- fLibraryList.setElements(existing);
- fLibraryList.selectElements(new StructuredSelection(list));
- }
- }
-
- private void doSave() {
- LoadSaveDialog dialog= new LoadSaveDialog(getShell(), true, fLibraryList.getElements(), fDialogSettings);
- dialog.open();
- }
-
- private boolean canAdd(List list) {
- return getSingleSelectedLibrary(list) != null;
- }
-
- private boolean canEdit(List list) {
- if (list.size() != 1)
- return false;
-
- Object firstElement= list.get(0);
- if (firstElement instanceof IAccessRule)
- return false;
- if (firstElement instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) firstElement;
- if (!attrib.isBuiltIn()) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(attrib.getKey());
- return config != null && config.canEdit(attrib.getClasspathAttributeAccess());
- }
- }
- return true;
- }
-
- private boolean canRemove(List list) {
- if (list.size() == 0) {
- return false;
- }
- for (int i= 0; i < list.size(); i++) {
- Object elem= list.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isNonModifiable()) {
- return false;
- }
- if (attrib.isBuiltIn()) {
- if (attrib.getKey().equals(CPListElement.ACCESSRULES)) {
- return ((IAccessRule[]) attrib.getValue()).length > 0;
- }
- if (attrib.getValue() == null) {
- return false;
- }
- } else {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(attrib.getKey());
- if (config == null || !config.canRemove(attrib.getClasspathAttributeAccess()) ) {
- return false;
- }
- }
- } else if (elem instanceof CPListElement) {
- // ok to remove
- } else if (elem instanceof CPUserLibraryElement) {
- // ok to remove
- } else { // unknown element
- return false;
- }
- }
- return true;
- }
-
- private CPListElement[] openExtJSFileDialog(CPListElement existing, Object parent) {
- String lastUsedPath;
- if (existing != null) {
- lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
- } else {
- lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
- if (lastUsedPath == null) {
- lastUsedPath= ""; //$NON-NLS-1$
- }
- }
- String title= (existing == null) ? PreferencesMessages.UserLibraryPreferencePage_browsejar_new_title : PreferencesMessages.UserLibraryPreferencePage_browsejar_edit_title;
-
- FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
- dialog.setText(title);
- dialog.setFilterExtensions(new String[] {"*.js"}); //$NON-NLS-1$
- dialog.setFilterPath(lastUsedPath);
- if (existing != null) {
- dialog.setFileName(existing.getPath().lastSegment());
- }
-
- String res= dialog.open();
- if (res == null) {
- return null;
- }
- String[] fileNames= dialog.getFileNames();
- int nChosen= fileNames.length;
-
- IPath filterPath= Path.fromOSString(dialog.getFilterPath());
- CPListElement[] elems= new CPListElement[nChosen];
- for (int i= 0; i < nChosen; i++) {
- IPath path= filterPath.append(fileNames[i]).makeAbsolute();
- CPListElement curr= new CPListElement(parent, null, IIncludePathEntry.CPE_LIBRARY, path, null);
- curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport.guessJavadocLocation(curr));
- elems[i]= curr;
- }
- fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());
-
- return elems;
- }
-
- private CPListElement[] openExtJsFolderDialog(final Object parent) {
- String lastUsedPath = fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
- if (lastUsedPath == null) {
- lastUsedPath= ""; //$NON-NLS-1$
- }
-
- DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.NONE);
- dialog.setText(PreferencesMessages.UserLibraryPreferencePage_browsefolder_new_title);
- dialog.setMessage(PreferencesMessages.UserLibraryPreferencePage_browsefolder_new_title);
- dialog.setFilterPath(lastUsedPath);
-
- String result= dialog.open();
- if (result == null) {
- return null;
- }
- IPath filterPath= Path.fromOSString(dialog.getFilterPath());
- CPListElement[] elems= new CPListElement[1];
- CPListElement curr= new CPListElement(parent, null, IIncludePathEntry.CPE_LIBRARY, filterPath.makeAbsolute(), null);
- curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport.guessJavadocLocation(curr));
- elems[0] = curr;
-
- fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, result);
-
- return elems;
- }
-
-
- private class UserLibraryAdapter implements ITreeListAdapter {
-
- private final Object[] EMPTY= new Object[0];
-
- public void customButtonPressed(TreeListDialogField field, int index) {
- doCustomButtonPressed(field, index);
- }
-
- public void selectionChanged(TreeListDialogField field) {
- doSelectionChanged(field);
- }
-
- public void doubleClicked(TreeListDialogField field) {
- doDoubleClicked(field);
- }
-
- public void keyPressed(TreeListDialogField field, KeyEvent event) {
- doKeyPressed(field, event);
- }
-
- public Object[] getChildren(TreeListDialogField field, Object element) {
- if (element instanceof CPUserLibraryElement) {
- CPUserLibraryElement elem= (CPUserLibraryElement) element;
- return elem.getChildren();
- } else if (element instanceof CPListElement) {
- return ((CPListElement)element).getChildren();
- } else if (element instanceof CPListElementAttribute) {
- CPListElementAttribute attribute= (CPListElementAttribute) element;
- if (CPListElement.ACCESSRULES.equals(attribute.getKey())) {
- return (IAccessRule[]) attribute.getValue();
- }
- }
- return EMPTY;
- }
-
- public Object getParent(TreeListDialogField field, Object element) {
- if (element instanceof CPListElementAttribute) {
- return ((CPListElementAttribute) element).getParent();
- } else if (element instanceof CPListElement) {
- return ((CPListElement) element).getParentContainer();
- }
- return null;
- }
-
- public boolean hasChildren(TreeListDialogField field, Object element) {
- return getChildren(field, element).length > 0;
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/WorkInProgressPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/WorkInProgressPreferencePage.java
deleted file mode 100644
index bd76933b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/WorkInProgressPreferencePage.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Preference page for work in progress.
- */
-public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- private List fCheckBoxes;
- private List fRadioButtons;
- private List fTextControls;
-
- /**
- * creates a new preference page.
- */
- public WorkInProgressPreferencePage() {
- setPreferenceStore(getPreferenceStore());
- fRadioButtons= new ArrayList();
- fCheckBoxes= new ArrayList();
- fTextControls= new ArrayList();
- }
-
- Button addCheckBox(Composite parent, String label, String key) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
-
- Button button= new Button(parent, SWT.CHECK);
- button.setText(label);
- button.setData(key);
- button.setLayoutData(gd);
-
- button.setSelection(getPreferenceStore().getBoolean(key));
-
- fCheckBoxes.add(button);
- return button;
- }
-
- /*
- * @see PreferencePage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$
- }
-
- protected Control createContents(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite result= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= 0;
- layout.verticalSpacing= convertVerticalDLUsToPixels(10);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- result.setLayout(layout);
-
- // Add your controls here
-
- applyDialogFont(result);
- return result;
- }
-
-
- /*
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- public void init(IWorkbench workbench) {
- }
-
- protected void createSpacer(Composite composite, int columnSpan) {
- Label label= new Label(composite, SWT.NONE);
- GridData gd= new GridData();
- gd.horizontalSpan= columnSpan;
- label.setLayoutData(gd);
- }
-
- /*
- * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore()
- */
- protected IPreferenceStore doGetPreferenceStore() {
- return JavaScriptPlugin.getDefault().getPreferenceStore();
- }
-
- /*
- * @see PreferencePage#performDefaults()
- */
- protected void performDefaults() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- button.setSelection(store.getDefaultBoolean(key));
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- String[] info= (String[]) button.getData();
- button.setSelection(info[1].equals(store.getDefaultString(info[0])));
- }
- for (int i= 0; i < fTextControls.size(); i++) {
- Text text= (Text) fTextControls.get(i);
- String key= (String) text.getData();
- text.setText(store.getDefaultString(key));
- }
-
- super.performDefaults();
- }
-
- /*
- * @see IPreferencePage#performOk()
- */
- public boolean performOk() {
- IPreferenceStore store= getPreferenceStore();
- for (int i= 0; i < fCheckBoxes.size(); i++) {
- Button button= (Button) fCheckBoxes.get(i);
- String key= (String) button.getData();
- store.setValue(key, button.getSelection());
- }
- for (int i= 0; i < fRadioButtons.size(); i++) {
- Button button= (Button) fRadioButtons.get(i);
- if (button.getSelection()) {
- String[] info= (String[]) button.getData();
- store.setValue(info[0], info[1]);
- }
- }
- for (int i= 0; i < fTextControls.size(); i++) {
- Text text= (Text) fTextControls.get(i);
- String key= (String) text.getData();
- store.setValue(key, text.getText());
- }
-
- JavaScriptPlugin.getDefault().savePluginPreferences();
- return super.performOk();
- }
-
- public static void initDefaults(IPreferenceStore store) {
- // Initialize your defaults here
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpConfigurationBlock.java
deleted file mode 100644
index 35153a64..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpConfigurationBlock.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpPreferenceUtil;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BulletListBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.IProfileVersioner;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileConfigurationBlock;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileStore;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-/**
- * The clean up configuration block for the clean up preference page.
- */
-public class CleanUpConfigurationBlock extends ProfileConfigurationBlock {
-
- private static final String CLEANUP_PAGE_SETTINGS_KEY= "cleanup_page"; //$NON-NLS-1$
- private static final String DIALOGSTORE_LASTSAVELOADPATH= JavaScriptUI.ID_PLUGIN + ".cleanup"; //$NON-NLS-1$
-
- private final IScopeContext fCurrContext;
- private SelectionButtonDialogField fShowCleanUpWizardDialogField;
- private CleanUpProfileManager fProfileManager;
- private ProfileStore fProfileStore;
- private BulletListBlock fBrowserBlock;
-
- public CleanUpConfigurationBlock(IProject project, PreferencesAccess access) {
- super(project, access, DIALOGSTORE_LASTSAVELOADPATH);
-
- if (project != null) {
- fCurrContext= null;
- } else {
- fCurrContext= access.getInstanceScope();
- }
- }
-
- protected IProfileVersioner createProfileVersioner() {
- return new CleanUpProfileVersioner();
- }
-
- protected ProfileStore createProfileStore(IProfileVersioner versioner) {
- fProfileStore= new ProfileStore(CleanUpConstants.CLEANUP_PROFILES, versioner);
- return fProfileStore;
- }
-
- protected ProfileManager createProfileManager(List profiles, IScopeContext context, PreferencesAccess access, IProfileVersioner profileVersioner) {
- profiles.addAll(CleanUpPreferenceUtil.getBuiltInProfiles());
- fProfileManager= new CleanUpProfileManager(profiles, context, access, profileVersioner);
- return fProfileManager;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void configurePreview(Composite composite, int numColumns, final ProfileManager profileManager) {
- Map settings= profileManager.getSelected().getSettings();
- final Map sharedSettings= new Hashtable();
- fill(settings, sharedSettings);
-
- final ICleanUp[] cleanUps= CleanUpRefactoring.createCleanUps(sharedSettings);
-
- createLabel(composite, CleanUpMessages.CleanUpConfigurationBlock_SelectedCleanUps_label, numColumns);
-
- fBrowserBlock= new BulletListBlock();
- Control control= fBrowserBlock.createControl(composite);
- ((GridData)control.getLayoutData()).horizontalSpan= numColumns;
- fBrowserBlock.setText(getSelectedCleanUpsInfo(cleanUps));
-
- profileManager.addObserver(new Observer() {
-
- public void update(Observable o, Object arg) {
- final int value= ((Integer)arg).intValue();
- switch (value) {
- case ProfileManager.PROFILE_CREATED_EVENT:
- case ProfileManager.PROFILE_DELETED_EVENT:
- case ProfileManager.SELECTION_CHANGED_EVENT:
- case ProfileManager.SETTINGS_CHANGED_EVENT:
- fill(profileManager.getSelected().getSettings(), sharedSettings);
- fBrowserBlock.setText(getSelectedCleanUpsInfo(cleanUps));
- }
- }
-
- });
- }
-
- private String getSelectedCleanUpsInfo(ICleanUp[] cleanUps) {
- if (cleanUps.length == 0)
- return ""; //$NON-NLS-1$
-
- StringBuffer buf= new StringBuffer();
-
- boolean first= true;
- for (int i= 0; i < cleanUps.length; i++) {
- String[] descriptions= cleanUps[i].getDescriptions();
- if (descriptions != null) {
- for (int j= 0; j < descriptions.length; j++) {
- if (first) {
- first= false;
- } else {
- buf.append('\n');
- }
- buf.append(descriptions[j]);
- }
- }
- }
-
- return buf.toString();
- }
-
- private void fill(Map settings, Map sharedSettings) {
- sharedSettings.clear();
- for (Iterator iterator= settings.keySet().iterator(); iterator.hasNext();) {
- String key= (String)iterator.next();
- sharedSettings.put(key, settings.get(key));
- }
- }
-
- protected ModifyDialog createModifyDialog(Shell shell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile) {
- return new CleanUpModifyDialog(shell, profile, profileManager, profileStore, newProfile, CLEANUP_PAGE_SETTINGS_KEY, DIALOGSTORE_LASTSAVELOADPATH);
- }
-
- /**
- * {@inheritDoc}
- */
- public Composite createContents(Composite parent) {
- Composite composite= super.createContents(parent);
-
- if (fCurrContext == null)
- return composite;
-
- fShowCleanUpWizardDialogField= new SelectionButtonDialogField(SWT.CHECK);
- fShowCleanUpWizardDialogField.setLabelText(CleanUpMessages.CleanUpConfigurationBlock_ShowCleanUpWizard_checkBoxLabel);
- fShowCleanUpWizardDialogField.doFillIntoGrid(composite, 5);
-
- IEclipsePreferences node= fCurrContext.getNode(JavaScriptUI.ID_PLUGIN);
- boolean showWizard;
- if (node.get(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, null) != null) {
- showWizard= node.getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true);
- } else {
- showWizard= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true);
- }
- if (showWizard)
- fShowCleanUpWizardDialogField.setSelection(true);
-
- fShowCleanUpWizardDialogField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- doShowCleanUpWizard(fShowCleanUpWizardDialogField.isSelected());
- }
- });
-
- return composite;
- }
-
- private void doShowCleanUpWizard(boolean showWizard) {
- IEclipsePreferences preferences= fCurrContext.getNode(JavaScriptUI.ID_PLUGIN);
- if (preferences.get(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, null) != null &&
- preferences.getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true) == showWizard)
- return;
-
- preferences.putBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, showWizard);
- }
-
- /**
- * {@inheritDoc}
- */
- public void performDefaults() {
- super.performDefaults();
- if (fCurrContext == null)
- return;
-
- fCurrContext.getNode(JavaScriptUI.ID_PLUGIN).remove(CleanUpConstants.SHOW_CLEAN_UP_WIZARD);
- boolean showWizard= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).getBoolean(CleanUpConstants.SHOW_CLEAN_UP_WIZARD, true);
- fShowCleanUpWizardDialogField.setDialogFieldListener(null);
- fShowCleanUpWizardDialogField.setSelection(showWizard);
- fShowCleanUpWizardDialogField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- doShowCleanUpWizard(fShowCleanUpWizardDialogField.isSelected());
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- protected void preferenceChanged(PreferenceChangeEvent event) {
- if (CleanUpConstants.CLEANUP_PROFILES.equals(event.getKey())) {
- try {
- String id= fCurrContext.getNode(JavaScriptUI.ID_PLUGIN).get(CleanUpConstants.CLEANUP_PROFILE, null);
- if (id == null)
- fProfileManager.getDefaultProfile().getID();
-
- List oldProfiles= fProfileManager.getSortedProfiles();
- Profile[] oldProfilesArray= (Profile[])oldProfiles.toArray(new Profile[oldProfiles.size()]);
- for (int i= 0; i < oldProfilesArray.length; i++) {
- if (oldProfilesArray[i] instanceof CustomProfile) {
- fProfileManager.deleteProfile((CustomProfile)oldProfilesArray[i]);
- }
- }
-
- List newProfiles= fProfileStore.readProfilesFromString((String)event.getNewValue());
- for (Iterator iterator= newProfiles.iterator(); iterator.hasNext();) {
- CustomProfile profile= (CustomProfile)iterator.next();
- fProfileManager.addProfile(profile);
- }
-
- Profile profile= fProfileManager.getProfile(id);
- if (profile != null) {
- fProfileManager.setSelected(profile);
- } else {
- fProfileManager.setSelected(fProfileManager.getDefaultProfile());
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- } else if (CleanUpConstants.CLEANUP_PROFILE.equals(event.getKey())) {
- if (event.getNewValue() == null) {
- fProfileManager.setSelected(fProfileManager.getDefaultProfile());
- } else {
- Profile profile= fProfileManager.getProfile((String)event.getNewValue());
- if (profile != null) {
- fProfileManager.setSelected(profile);
- }
- }
- }
- }
-
- public void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- fBrowserBlock.setEnabled(useProjectSpecificSettings);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java
deleted file mode 100644
index 7b1bb799..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import org.eclipse.osgi.util.NLS;
-
-public class CleanUpMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.CleanUpMessages"; //$NON-NLS-1$
-
- public static String CleanUpConfigurationBlock_SelectedCleanUps_label;
- public static String CleanUpConfigurationBlock_ShowCleanUpWizard_checkBoxLabel;
-
-
- public static String CleanUpModifyDialog_TabPageName_CodeFormating;
- public static String CleanUpModifyDialog_TabPageName_CodeStyle;
-
-
- public static String CleanUpProfileManager_ProfileName_EclipseBuildIn;
-
- public static String CodeFormatingTabPage_CheckboxName_FormatSourceCode;
- public static String CodeFormatingTabPage_FormatterSettings_Description;
- public static String CodeFormatingTabPage_GroupName_Formatter;
-// public static String CodeFormatingTabPage_Imports_GroupName;
-// public static String CodeFormatingTabPage_OrganizeImports_CheckBoxLable;
-// public static String CodeFormatingTabPage_OrganizeImportsSettings_Description;
- public static String CodeFormatingTabPage_SortMembers_GroupName;
- public static String CodeFormatingTabPage_SortMembers_Description;
-// public static String CodeFormatingTabPage_SortMembersFields_CheckBoxLabel;
-
- public static String CodeFormatingTabPage_RemoveTrailingWhitespace_all_radio;
-
- public static String CodeFormatingTabPage_RemoveTrailingWhitespace_checkbox_text;
-
- public static String CodeFormatingTabPage_RemoveTrailingWhitespace_ignoreEmpty_radio;
-
-
- public static String CodeStyleTabPage_CheckboxName_ConvertForLoopToEnhanced;
- public static String CodeStyleTabPage_CheckboxName_UseBlocks;
-// public static String CodeStyleTabPage_CheckboxName_UseFinal;
-// public static String CodeStyleTabPage_CheckboxName_UseFinalForFields;
-// public static String CodeStyleTabPage_CheckboxName_UseFinalForLocals;
-// public static String CodeStyleTabPage_CheckboxName_UseFinalForParameters;
- public static String CodeStyleTabPage_CheckboxName_UseParentheses;
- public static String CodeStyleTabPage_GroupName_ControlStatments;
- public static String CodeStyleTabPage_GroupName_Expressions;
-// public static String CodeStyleTabPage_GroupName_VariableDeclarations;
- public static String CodeStyleTabPage_RadioName_AlwaysUseBlocks;
- public static String CodeStyleTabPage_RadioName_AlwaysUseParantheses;
- public static String CodeStyleTabPage_RadioName_NeverUseBlocks;
- public static String CodeStyleTabPage_RadioName_NeverUseParantheses;
- public static String CodeStyleTabPage_RadioName_UseBlocksSpecial;
-
-
-
- public static String UnnecessaryCodeTabPage_CheckboxName_UnnecessaryNLSTags;
- public static String UnnecessaryCodeTabPage_CheckboxName_UnusedFields;
- public static String UnnecessaryCodeTabPage_CheckboxName_UnusedLocalVariables;
- public static String UnnecessaryCodeTabPage_CheckboxName_UnusedMembers;
- public static String UnnecessaryCodeTabPage_CheckboxName_UnusedMethods;
- public static String UnnecessaryCodeTabPage_GroupName_UnnecessaryCode;
- public static String UnnecessaryCodeTabPage_GroupName_UnusedCode;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, CleanUpMessages.class);
- }
-
- private CleanUpMessages() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties
deleted file mode 100644
index 63985bcc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties
+++ /dev/null
@@ -1,55 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2010 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-CleanUpModifyDialog_TabPageName_CodeStyle=&Code Style
-CleanUpModifyDialog_TabPageName_CodeFormating=Code &Organizing
-
-CleanUpProfileManager_ProfileName_EclipseBuildIn=Eclipse [built-in]
-CleanUpConfigurationBlock_SelectedCleanUps_label=Details:
-CleanUpConfigurationBlock_ShowCleanUpWizard_checkBoxLabel=&Show profile selection dialog for the 'Source > Clean Up' action
-
-CodeFormatingTabPage_GroupName_Formatter=Formatter
-#CodeFormatingTabPage_Imports_GroupName=Imports
-CodeFormatingTabPage_CheckboxName_FormatSourceCode=&Format source code
-CodeFormatingTabPage_FormatterSettings_Description=The settings for the Formatter can be changed on the Formatter preference page.
-#CodeFormatingTabPage_OrganizeImports_CheckBoxLable=Organize i&mports
-CodeFormatingTabPage_RemoveTrailingWhitespace_all_radio=&All lines
-#CodeFormatingTabPage_OrganizeImportsSettings_Description=The settings for organizing imports can be changed on the Organize Imports preference page.
-CodeFormatingTabPage_SortMembers_GroupName=Members
-CodeFormatingTabPage_SortMembers_Description=The settings for sorting members can be changed on the Members Sort Order preference page.
-#CodeFormatingTabPage_SortMembersFields_CheckBoxLabel=Also sort vars, enum constants, and initializers
-CodeFormatingTabPage_RemoveTrailingWhitespace_checkbox_text=Remove trailing &whitespace
-CodeFormatingTabPage_RemoveTrailingWhitespace_ignoreEmpty_radio=Ignore empty &lines
-
-CodeStyleTabPage_CheckboxName_UseBlocks=Use bloc&ks in if/while/for/do statements
-CodeStyleTabPage_RadioName_AlwaysUseBlocks=Al&ways
-CodeStyleTabPage_RadioName_NeverUseBlocks=No block for sin&gle statements
-CodeStyleTabPage_GroupName_Expressions=Expressions
-#CodeStyleTabPage_CheckboxName_UseFinal=U&se modifier 'final' where possible
-#CodeStyleTabPage_CheckboxName_UseFinalForParameters=&Parameter
-CodeStyleTabPage_RadioName_AlwaysUseParantheses=Alwa&ys
-CodeStyleTabPage_RadioName_NeverUseParantheses=Only &if necessary
-#CodeStyleTabPage_GroupName_VariableDeclarations=Var declarations
-#CodeStyleTabPage_CheckboxName_UseFinalForFields=Pr&ivate fields
-#CodeStyleTabPage_CheckboxName_UseFinalForLocals=&Local variables
-CodeStyleTabPage_CheckboxName_ConvertForLoopToEnhanced=Conver&t for loops to enhanced
-CodeStyleTabPage_GroupName_ControlStatments=Control statements
-CodeStyleTabPage_RadioName_UseBlocksSpecial=No &block for single 'return' or 'throw' statements
-CodeStyleTabPage_CheckboxName_UseParentheses=Use parent&heses around conditions
-
-
-
-UnnecessaryCodeTabPage_GroupName_UnusedCode=Unused code
-UnnecessaryCodeTabPage_CheckboxName_UnusedMembers=Remove unuse&d private members
-UnnecessaryCodeTabPage_CheckboxName_UnusedFields=V&ars
-UnnecessaryCodeTabPage_CheckboxName_UnusedMethods=&Functions
-UnnecessaryCodeTabPage_CheckboxName_UnusedLocalVariables=Remove unused &local variables
-UnnecessaryCodeTabPage_GroupName_UnnecessaryCode=Unnecessary code
-UnnecessaryCodeTabPage_CheckboxName_UnnecessaryNLSTags=Remove unnecessary '$NON-NLS$' ta&gs \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpModifyDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpModifyDialog.java
deleted file mode 100644
index 2d9c8ddd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpModifyDialog.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileStore;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-
-public class CleanUpModifyDialog extends ModifyDialog {
-
- /**
- * Constant array for boolean selection
- */
- static String[] FALSE_TRUE = {
- CleanUpConstants.FALSE,
- CleanUpConstants.TRUE
- };
-
- public CleanUpModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile, String dialogPreferencesKey, String lastSavePathKey) {
- super(parentShell, profile, profileManager, profileStore, newProfile, dialogPreferencesKey, lastSavePathKey);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void addPages(final Map values) {
- addTabPage(CleanUpMessages.CleanUpModifyDialog_TabPageName_CodeStyle, new CodeStyleTabPage(this, values));
-// addTabPage(CleanUpMessages.CleanUpModifyDialog_TabPageName_MemberAccesses, new MemberAccessesTabPage(this, values));
-// addTabPage(CleanUpMessages.CleanUpModifyDialog_TabPageName_UnnecessaryCode, new UnnecessaryCodeTabPage(this, values));
-// addTabPage(CleanUpMessages.CleanUpModifyDialog_TabPageName_MissingCode, new MissingCodeTabPage(this, values));
- addTabPage(CleanUpMessages.CleanUpModifyDialog_TabPageName_CodeFormating, new CodeFormatingTabPage(this, values));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpPreview.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpPreview.java
deleted file mode 100644
index 28bcb222..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpPreview.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.formatter.IContentFormatterExtension;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.MultiFixMessages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.JavaPreview;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-
-
-public class CleanUpPreview extends JavaPreview {
-
- private ICleanUp[] fPreviewCleanUps;
- private boolean fFormat;
- public CleanUpPreview(Composite parent, ICleanUp[] cleanUps) {
- super(JavaScriptCore.getDefaultOptions(), parent);
- fPreviewCleanUps= cleanUps;
- fFormat= false;
- }
-
- public void setCleanUps(ICleanUp[] fCleanUps) {
- fPreviewCleanUps= fCleanUps;
- }
-
- public void setFormat(boolean enable) {
- fFormat= enable;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void doFormatPreview() {
-
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < fPreviewCleanUps.length; i++) {
- buf.append(fPreviewCleanUps[i].getPreview());
- buf.append("\n"); //$NON-NLS-1$
- }
- format(buf.toString());
- }
-
- private void format(String text) {
- if (text == null) {
- fPreviewDocument.set(""); //$NON-NLS-1$
- return;
- }
- fPreviewDocument.set(text);
-
- if (!fFormat)
- return;
-
- fSourceViewer.setRedraw(false);
- final IFormattingContext context = new CommentFormattingContext();
- try {
- final IContentFormatter formatter = fViewerConfiguration.getContentFormatter(fSourceViewer);
- if (formatter instanceof IContentFormatterExtension) {
- final IContentFormatterExtension extension = (IContentFormatterExtension) formatter;
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, JavaScriptCore.getOptions());
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
- extension.format(fPreviewDocument, context);
- } else
- formatter.format(fPreviewDocument, new Region(0, fPreviewDocument.getLength()));
- } catch (Exception e) {
- final IStatus status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR,
- MultiFixMessages.CleanUpRefactoringWizard_formatterException_errorMessage, e);
- JavaScriptPlugin.log(status);
- } finally {
- context.dispose();
- fSourceViewer.setRedraw(true);
- }
- }
-
- public void setWorkingValues(Map workingValues) {
- //Don't change the formatter settings
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileManager.java
deleted file mode 100644
index 2febc5f8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileManager.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.IProfileVersioner;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CleanUpProfileManager extends ProfileManager {
-
- public static KeySet[] KEY_SETS= {
- new KeySet(JavaScriptUI.ID_PLUGIN, new ArrayList(CleanUpConstants.getEclipseDefaultSettings().keySet()))
- };
-
- private final PreferencesAccess fPreferencesAccess;
-
- public CleanUpProfileManager(List profiles, IScopeContext context, PreferencesAccess preferencesAccess, IProfileVersioner profileVersioner) {
- super(profiles, context, preferencesAccess, profileVersioner, KEY_SETS, CleanUpConstants.CLEANUP_PROFILE, CleanUpConstants.CLEANUP_SETTINGS_VERSION_KEY);
- fPreferencesAccess= preferencesAccess;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.ProfileManager#getDefaultProfile()
- */
- public Profile getDefaultProfile() {
- return getProfile(CleanUpConstants.DEFAULT_PROFILE);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void updateProfilesWithName(String oldName, Profile newProfile, boolean applySettings) {
- super.updateProfilesWithName(oldName, newProfile, applySettings);
-
- IEclipsePreferences node= fPreferencesAccess.getInstanceScope().getNode(JavaScriptUI.ID_PLUGIN);
- String name= node.get(CleanUpConstants.CLEANUP_ON_SAVE_PROFILE, null);
- if (name != null && name.equals(oldName)) {
- if (newProfile == null) {
- node.remove(CleanUpConstants.CLEANUP_ON_SAVE_PROFILE);
- } else {
- node.put(CleanUpConstants.CLEANUP_ON_SAVE_PROFILE, newProfile.getID());
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileVersioner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileVersioner.java
deleted file mode 100644
index 57bb9ad4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpProfileVersioner.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.IProfileVersioner;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-
-
-public class CleanUpProfileVersioner implements IProfileVersioner {
-
- public static final String PROFILE_KIND= "CleanUpProfile"; //$NON-NLS-1$
-
- private static final int VERSION_1= 1; // 3.3M2
- private static final int VERSION_2= 2; // 3.3M3 Added ORGANIZE_IMPORTS
-
- public static final int CURRENT_VERSION= VERSION_2;
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.IProfileVersioner#getFirstVersion()
- */
- public int getFirstVersion() {
- return VERSION_1;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.IProfileVersioner#getCurrentVersion()
- */
- public int getCurrentVersion() {
- return CURRENT_VERSION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.IProfileVersioner#updateAndComplete(org.eclipse.wst.jsdt.internal.ui.preferences.cleanup.ProfileManager.CustomProfile)
- */
- public void update(CustomProfile profile) {
- if (profile.getVersion() == VERSION_1)
- updateFrom1To2(profile);
-
- profile.setVersion(CURRENT_VERSION);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getProfileKind() {
- return PROFILE_KIND;
- }
-
- private static void updateFrom1To2(CustomProfile profile) {
- Map defaultSettings= CleanUpConstants.getEclipseDefaultSettings();
- profile.getSettings().put(CleanUpConstants.ORGANIZE_IMPORTS, defaultSettings.get(CleanUpConstants.ORGANIZE_IMPORTS));
- }
-
- }
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpTabPage.java
deleted file mode 100644
index 7a059a30..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpTabPage.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.JavaPreview;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage;
-
-public abstract class CleanUpTabPage extends ModifyDialogTabPage {
-
- private final Map fValues;
- private JavaPreview fCleanUpPreview;
- private final boolean fIsSaveAction;
- private int fCount;
- private int fSelectedCount;
-
- public CleanUpTabPage(IModificationListener listener, Map values, boolean isSaveAction) {
- super(listener, values);
- fValues= values;
- fIsSaveAction= isSaveAction;
- fCount= 0;
- fSelectedCount= 0;
- }
-
- /**
- * @return is this tab page shown in the save action dialog
- */
- public boolean isSaveAction() {
- return fIsSaveAction;
- }
-
- public int getCleanUpCount() {
- return fCount;
- }
-
- public int getSelectedCleanUpCount() {
- return fSelectedCount;
- }
-
- protected abstract ICleanUp[] createPreviewCleanUps(Map values);
-
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fCleanUpPreview= new CleanUpPreview(parent, createPreviewCleanUps(fValues));
- return fCleanUpPreview;
- }
-
- protected void doUpdatePreview() {
- fCleanUpPreview.setWorkingValues(fValues);
- fCleanUpPreview.update();
- }
-
- protected void initializePage() {
- fCleanUpPreview.update();
- }
-
- protected void registerPreference(final CheckboxPreference preference) {
- fCount++;
- preference.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- if (preference.getChecked()) {
- fSelectedCount++;
- } else {
- fSelectedCount--;
- }
- }
- });
- if (preference.getChecked()) {
- fSelectedCount++;
- }
- }
-
- protected void registerSlavePreference(final CheckboxPreference master, final RadioPreference[] slaves) {
- internalRegisterSlavePreference(master, slaves);
- registerPreference(master);
- }
-
- protected void registerSlavePreference(final CheckboxPreference master, final CheckboxPreference[] slaves) {
- internalRegisterSlavePreference(master, slaves);
- fCount+= slaves.length;
-
- master.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- if (master.getChecked()) {
- for (int i= 0; i < slaves.length; i++) {
- if (slaves[i].getChecked()) {
- fSelectedCount++;
- }
- }
- } else {
- for (int i= 0; i < slaves.length; i++) {
- if (slaves[i].getChecked()) {
- fSelectedCount--;
- }
- }
- }
- }
- });
-
- for (int i= 0; i < slaves.length; i++) {
- final CheckboxPreference slave= slaves[i];
- slave.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- if (slave.getChecked()) {
- fSelectedCount++;
- } else {
- fSelectedCount--;
- }
- }
- });
- }
-
- if (master.getChecked()) {
- for (int i= 0; i < slaves.length; i++) {
- if (slaves[i].getChecked()) {
- fSelectedCount++;
- }
- }
- }
- }
-
- private void internalRegisterSlavePreference(final CheckboxPreference master, final ButtonPreference[] slaves) {
- master.addObserver( new Observer() {
- public void update(Observable o, Object arg) {
- for (int i= 0; i < slaves.length; i++) {
- slaves[i].setEnabled(master.getChecked());
- }
- }
- });
-
- for (int i= 0; i < slaves.length; i++) {
- slaves[i].setEnabled(master.getChecked());
- }
- }
-
- protected void intent(Composite group) {
- Label l= new Label(group, SWT.NONE);
- GridData gd= new GridData();
- gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(4);
- l.setLayoutData(gd);
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeFormatingTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeFormatingTabPage.java
deleted file mode 100644
index ba554b45..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeFormatingTabPage.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Alex Blewitt - https://bugs.eclipse.org/bugs/show_bug.cgi?id=168954
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.fix.CodeFormatCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.CommentFormatCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ImportsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.SortMembersCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.JavaPreview;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog;
-
-public final class CodeFormatingTabPage extends CleanUpTabPage {
-
- private final Map fValues;
- private CleanUpPreview fPreview;
-
- public CodeFormatingTabPage(ModifyDialog dialog, Map values) {
- this(dialog, values, false);
- }
-
- public CodeFormatingTabPage(IModificationListener listener, Map values, boolean isSaveParticipantConfiguration) {
- super(listener, values, isSaveParticipantConfiguration);
- fValues= values;
- }
-
- protected ICleanUp[] createPreviewCleanUps(Map values) {
- return new ICleanUp[] {
- new ImportsCleanUp(values),
- new CommentFormatCleanUp(values),
- new CodeFormatCleanUp(values),
- new SortMembersCleanUp(values)
- };
- }
-
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= (CleanUpPreview)super.doCreateJavaPreview(parent);
- fPreview.showInvisibleCharacters(true);
- fPreview.setFormat(CleanUpConstants.TRUE.equals(fValues.get(CleanUpConstants.FORMAT_SOURCE_CODE)));
- return fPreview;
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- Group group= createGroup(numColumns, composite, CleanUpMessages.CodeFormatingTabPage_GroupName_Formatter);
-
- if (!isSaveAction()) {
- final CheckboxPreference format= createCheckboxPref(group, numColumns, CleanUpMessages.CodeFormatingTabPage_CheckboxName_FormatSourceCode, CleanUpConstants.FORMAT_SOURCE_CODE, CleanUpModifyDialog.FALSE_TRUE);
- registerPreference(format);
- format.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- fPreview.setFormat(format.getChecked());
- fPreview.update();
- }
- });
- }
-
- final CheckboxPreference whiteSpace= createCheckboxPref(group, numColumns, CleanUpMessages.CodeFormatingTabPage_RemoveTrailingWhitespace_checkbox_text, CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES, CleanUpModifyDialog.FALSE_TRUE);
- intent(group);
- final RadioPreference allPref= createRadioPref(group, 1, CleanUpMessages.CodeFormatingTabPage_RemoveTrailingWhitespace_all_radio, CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_ALL, CleanUpModifyDialog.FALSE_TRUE);
- final RadioPreference ignoreEmptyPref= createRadioPref(group, 1, CleanUpMessages.CodeFormatingTabPage_RemoveTrailingWhitespace_ignoreEmpty_radio, CleanUpConstants.FORMAT_REMOVE_TRAILING_WHITESPACES_IGNORE_EMPTY, CleanUpModifyDialog.FALSE_TRUE);
- registerSlavePreference(whiteSpace, new RadioPreference[] {allPref, ignoreEmptyPref});
-
- if (!isSaveAction()) {
- createLabel(numColumns, group, CleanUpMessages.CodeFormatingTabPage_FormatterSettings_Description).setFont(composite.getFont());
-
-// Group importsGroup= createGroup(numColumns, composite, CleanUpMessages.CodeFormatingTabPage_Imports_GroupName);
-// CheckboxPreference organizeImports= createCheckboxPref(importsGroup, numColumns, CleanUpMessages.CodeFormatingTabPage_OrganizeImports_CheckBoxLable, CleanUpConstants.ORGANIZE_IMPORTS, CleanUpModifyDialog.FALSE_TRUE);
-// registerPreference(organizeImports);
-// createLabel(numColumns, importsGroup, CleanUpMessages.CodeFormatingTabPage_OrganizeImportsSettings_Description).setFont(composite.getFont());
- }
-
- Group sortMembersGroup= createGroup(numColumns, composite, CleanUpMessages.CodeFormatingTabPage_SortMembers_GroupName);
-
-// final CheckboxPreference sortMembersPref= createCheckboxPref(sortMembersGroup, numColumns, CleanUpMessages.CodeFormatingTabPage_SortMembers_CheckBoxLabel, CleanUpConstants.SORT_MEMBERS, CleanUpModifyDialog.FALSE_TRUE);
-// intent(sortMembersGroup);
-// final RadioPreference sortAllPref= createRadioPref(sortMembersGroup, numColumns - 1, CleanUpMessages.CodeFormatingTabPage_SortMembersFields_CheckBoxLabel, CleanUpConstants.SORT_MEMBERS_ALL, CleanUpModifyDialog.FALSE_TRUE);
-// intent(sortMembersGroup);
-// final Button nullRadio= new Button(sortMembersGroup, SWT.RADIO);
-// nullRadio.setText(CleanUpMessages.CodeFormatingTabPage_SortMembersExclusive_radio0);
-// nullRadio.setLayoutData(createGridData(numColumns - 1, GridData.FILL_HORIZONTAL, SWT.DEFAULT));
-// nullRadio.setFont(composite.getFont());
-// intent(sortMembersGroup);
-// final Label warningImage= new Label(sortMembersGroup, SWT.LEFT | SWT.WRAP);
-// warningImage.setImage(Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));
-// warningImage.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false));
-// final Label warningLabel= createLabel(numColumns - 2, sortMembersGroup, CleanUpMessages.CodeFormatingTabPage_SortMembersSemanticChange_warning);
-
-// registerSlavePreference(sortMembersPref, new RadioPreference[] {sortAllPref});
-// sortMembersPref.addObserver(new Observer() {
-// public void update(Observable o, Object arg) {
-// nullRadio.setEnabled(sortMembersPref.getChecked());
-//
-// boolean warningEnabled= sortMembersPref.getChecked() && sortAllPref.getChecked();
-// warningImage.setEnabled(warningEnabled);
-// warningLabel.setEnabled(warningEnabled);
-// }
-// });
-// sortAllPref.addObserver(new Observer() {
-// public void update(Observable o, Object arg) {
-// boolean warningEnabled= sortMembersPref.getChecked() && sortAllPref.getChecked();
-// warningImage.setEnabled(warningEnabled);
-// warningLabel.setEnabled(warningEnabled);
-// }
-// });
-// nullRadio.setEnabled(sortMembersPref.getChecked());
-// nullRadio.setSelection(CleanUpConstants.FALSE.equals(fValues.get(CleanUpConstants.SORT_MEMBERS_ALL)));
-// boolean warningEnabled= sortMembersPref.getChecked() && sortAllPref.getChecked();
-// warningImage.setEnabled(warningEnabled);
-// warningLabel.setEnabled(warningEnabled);
-
- createLabel(numColumns, sortMembersGroup, CleanUpMessages.CodeFormatingTabPage_SortMembers_Description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java
deleted file mode 100644
index 0816e01d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.fix.ControlStatementsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ExpressionsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.VariableDeclarationCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog;
-
-public final class CodeStyleTabPage extends CleanUpTabPage {
-
- public CodeStyleTabPage(ModifyDialog dialog, Map values) {
- this(dialog, values, false);
- }
-
- public CodeStyleTabPage(IModificationListener listener, Map values, boolean isSaveParticipantConfiguration) {
- super(listener, values, isSaveParticipantConfiguration);
- }
-
- protected ICleanUp[] createPreviewCleanUps(Map values) {
- return new ICleanUp[] {
- new ControlStatementsCleanUp(values),
- new ExpressionsCleanUp(values),
- new VariableDeclarationCleanUp(values)
- };
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- Group controlGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_ControlStatments);
-
- final CheckboxPreference useBlockPref= createCheckboxPref(controlGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseBlocks, CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS, CleanUpModifyDialog.FALSE_TRUE);
- intent(controlGroup);
- final RadioPreference useBlockAlwaysPref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_AlwaysUseBlocks, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_ALWAYS, CleanUpModifyDialog.FALSE_TRUE);
- intent(controlGroup);
- final RadioPreference useBlockJDTStylePref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_UseBlocksSpecial, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NO_FOR_RETURN_AND_THROW, CleanUpModifyDialog.FALSE_TRUE);
- intent(controlGroup);
- final RadioPreference useBlockNeverPref= createRadioPref(controlGroup, numColumns - 1, CleanUpMessages.CodeStyleTabPage_RadioName_NeverUseBlocks, CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER, CleanUpModifyDialog.FALSE_TRUE);
- registerSlavePreference(useBlockPref, new RadioPreference[] {useBlockAlwaysPref, useBlockJDTStylePref, useBlockNeverPref});
-
-
- Group expressionsGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_Expressions);
-
- final CheckboxPreference useParenthesesPref= createCheckboxPref(expressionsGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseParentheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpModifyDialog.FALSE_TRUE);
- intent(expressionsGroup);
- final RadioPreference useParenthesesAlwaysPref= createRadioPref(expressionsGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_AlwaysUseParantheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS, CleanUpModifyDialog.FALSE_TRUE);
- final RadioPreference useParenthesesNeverPref= createRadioPref(expressionsGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_NeverUseParantheses, CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpModifyDialog.FALSE_TRUE);
- registerSlavePreference(useParenthesesPref, new RadioPreference[] {useParenthesesAlwaysPref, useParenthesesNeverPref});
-
-// Group variableGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_VariableDeclarations);
-
-// final CheckboxPreference useFinalPref= createCheckboxPref(variableGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinal, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, CleanUpModifyDialog.FALSE_TRUE);
-// intent(variableGroup);
-// final CheckboxPreference useFinalFieldsPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForFields, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, CleanUpModifyDialog.FALSE_TRUE);
-// final CheckboxPreference useFinalParametersPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForParameters, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpModifyDialog.FALSE_TRUE);
-// final CheckboxPreference useFinalVariablesPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForLocals, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, CleanUpModifyDialog.FALSE_TRUE);
-// registerSlavePreference(useFinalPref, new CheckboxPreference[] {useFinalFieldsPref, useFinalParametersPref, useFinalVariablesPref});
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/UnnecessaryCodeTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/UnnecessaryCodeTabPage.java
deleted file mode 100644
index c8e7afed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/UnnecessaryCodeTabPage.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.cleanup;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.StringCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.UnnecessaryCodeCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.UnusedCodeCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialog;
-
-public final class UnnecessaryCodeTabPage extends CleanUpTabPage {
-
- public UnnecessaryCodeTabPage(ModifyDialog dialog, Map values) {
- this(dialog, values, false);
- }
-
- public UnnecessaryCodeTabPage(IModificationListener listener, Map values, boolean isSaveParticipantConfiguration) {
- super(listener, values, isSaveParticipantConfiguration);
- }
-
- protected ICleanUp[] createPreviewCleanUps(Map values) {
- return new ICleanUp[] {
- new UnusedCodeCleanUp(values),
- new UnnecessaryCodeCleanUp(values),
- new StringCleanUp(values)
- };
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- Group unusedCodeGroup= createGroup(5, composite, CleanUpMessages.UnnecessaryCodeTabPage_GroupName_UnusedCode);
-
-// CheckboxPreference removeImports= createCheckboxPref(unusedCodeGroup, 5, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedImports, CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpModifyDialog.FALSE_TRUE);
-// registerPreference(removeImports);
-
- final CheckboxPreference unusedMembersPref= createCheckboxPref(unusedCodeGroup, 5, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedMembers, CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpModifyDialog.FALSE_TRUE);
- intent(unusedCodeGroup);
-// final CheckboxPreference typesPref= createCheckboxPref(unusedCodeGroup, 1, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedTypes, CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES, CleanUpModifyDialog.FALSE_TRUE);
-// final CheckboxPreference constructorPref= createCheckboxPref(unusedCodeGroup, 1, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedConstructors, CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, CleanUpModifyDialog.FALSE_TRUE);
- final CheckboxPreference fieldsPref= createCheckboxPref(unusedCodeGroup, 1, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedFields, CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS, CleanUpModifyDialog.FALSE_TRUE);
- final CheckboxPreference methodsPref= createCheckboxPref(unusedCodeGroup, 1, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedMethods, CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS, CleanUpModifyDialog.FALSE_TRUE);
- registerSlavePreference(unusedMembersPref, new CheckboxPreference[] {/*typesPref, constructorPref, */fieldsPref, methodsPref});
-
- CheckboxPreference removeLocals= createCheckboxPref(unusedCodeGroup, numColumns, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnusedLocalVariables, CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES, CleanUpModifyDialog.FALSE_TRUE);
- registerPreference(removeLocals);
-
- Group unnecessaryGroup= createGroup(numColumns, composite, CleanUpMessages.UnnecessaryCodeTabPage_GroupName_UnnecessaryCode);
-//
-// CheckboxPreference casts= createCheckboxPref(unnecessaryGroup, numColumns, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnnecessaryCasts, CleanUpConstants.REMOVE_UNNECESSARY_CASTS, CleanUpModifyDialog.FALSE_TRUE);
-// registerPreference(casts);
-
- CheckboxPreference nls= createCheckboxPref(unnecessaryGroup, numColumns, CleanUpMessages.UnnecessaryCodeTabPage_CheckboxName_UnnecessaryNLSTags, CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS, CleanUpModifyDialog.FALSE_TRUE);
- registerPreference(nls);
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/AlreadyExistsDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/AlreadyExistsDialog.java
deleted file mode 100644
index 65bddf8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/AlreadyExistsDialog.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-
-/**
- * The dialog to rename an imported profile.
- */
-public class AlreadyExistsDialog extends StatusDialog {
-
- private Composite fComposite;
- protected Text fNameText;
- private Button fRenameRadio, fOverwriteRadio;
-
- private final int NUM_COLUMNS= 2;
-
- private final StatusInfo fOk;
- private final StatusInfo fEmpty;
- private final StatusInfo fDuplicate;
-
- private final CustomProfile fProfile;
- private final ProfileManager fProfileManager;
-
- public AlreadyExistsDialog(Shell parentShell, CustomProfile profile, ProfileManager profileManager) {
- super(parentShell);
- fProfile= profile;
- fProfileManager= profileManager;
- fOk= new StatusInfo();
- fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.AlreadyExistsDialog_message_profile_already_exists);
- fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.AlreadyExistsDialog_message_profile_name_empty);
-
- setHelpAvailable(false);
- }
-
-
- public void create() {
- super.create();
- setTitle(FormatterMessages.AlreadyExistsDialog_dialog_title);
- }
-
- public Control createDialogArea(Composite parent) {
-
- initializeComposite(parent);
-
- createLabel(Messages.format(FormatterMessages.AlreadyExistsDialog_dialog_label, fProfile.getName()));
-
- fRenameRadio= createRadioButton(FormatterMessages.AlreadyExistsDialog_rename_radio_button_desc);
- fNameText= createTextField();
-
- fOverwriteRadio= createRadioButton(FormatterMessages.AlreadyExistsDialog_overwrite_radio_button_desc);
-
- fRenameRadio.setSelection(true);
-
- fNameText.setText(fProfile.getName());
- fNameText.setSelection(0, fProfile.getName().length());
- fNameText.setFocus();
-
- fNameText.addModifyListener( new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation();
- }
- });
-
- fRenameRadio.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fNameText.setEnabled(true);
- fNameText.setFocus();
- fNameText.setSelection(0, fNameText.getText().length());
- doValidation();
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- fOverwriteRadio.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fNameText.setEnabled(false);
- doValidation();
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- updateStatus(fDuplicate);
-
- applyDialogFont(fComposite);
-
- return fComposite;
- }
-
- private void initializeComposite(Composite parent) {
- fComposite= new Composite(parent, SWT.NULL);
-
- final GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- layout.numColumns= NUM_COLUMNS;
-
- fComposite.setLayout(layout);
- }
-
- private Label createLabel(String text) {
- final GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= NUM_COLUMNS;
- gd.widthHint= convertWidthInCharsToPixels(60);
- final Label label= new Label(fComposite, SWT.WRAP);
- label.setText(text);
- label.setLayoutData(gd);
- return label;
- }
-
- private Button createRadioButton(String text) {
- final GridData gd = new GridData();
- gd.horizontalSpan = NUM_COLUMNS;
- gd.widthHint= convertWidthInCharsToPixels(60);
- final Button radio= new Button(fComposite, SWT.RADIO);
- radio.setLayoutData(gd);
- radio.setText(text);
- return radio;
- }
-
- private Text createTextField() {
- final GridData gd = new GridData( GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= NUM_COLUMNS;
- gd.horizontalIndent= 15;
- final Text text= new Text(fComposite, SWT.SINGLE | SWT.BORDER);
- text.setLayoutData(gd);
- return text;
- }
-
-
- /**
- * Validate the current settings
- */
- protected void doValidation() {
-
- if (fOverwriteRadio.getSelection()) {
- updateStatus(fOk);
- return;
- }
-
- final String name= fNameText.getText().trim();
-
- if (name.length() == 0) {
- updateStatus(fEmpty);
- return;
- }
-
- if (fProfileManager.containsName(name)) {
- updateStatus(fDuplicate);
- return;
- }
-
- updateStatus(fOk);
- }
-
-
- protected void okPressed() {
- if (!getStatus().isOK())
- return;
- if (fRenameRadio.getSelection())
- fProfile.rename(fNameText.getText().trim(), fProfileManager);
- super.okPressed();
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BlankLinesTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BlankLinesTabPage.java
deleted file mode 100644
index 5c05d90c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BlankLinesTabPage.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-
-public class BlankLinesTabPage extends FormatterTabPage {
-
- private final String PREVIEW=
- createPreviewHeader(FormatterMessages.BlankLinesTabPage_preview_header) +
- "var data;\n" + //$NON-NLS-1$
- "var data2;\n" + //$NON-NLS-1$
- "var data3;\n" + //$NON-NLS-1$
- "function foo(otherdata) {\n" + //$NON-NLS-1$
- "// " + FormatterMessages.BlankLinesTabPage_preview_comment_between_here + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
- "\n\n\n\n\n" + //$NON-NLS-1$
- "// " + FormatterMessages.BlankLinesTabPage_preview_comment_and_here_are_5_blank_lines + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
- " var first;\n" + //$NON-NLS-1$
- " var second;\n" + //$NON-NLS-1$
- " function foo2() {\n" + //$NON-NLS-1$
- " var abc;\n" + //$NON-NLS-1$
- " var xyz;\n" + //$NON-NLS-1$
- " };\n" + //$NON-NLS-1$
- "}\n"; //$NON-NLS-1$
-
- private final static int MIN_NUMBER_LINES= 0;
- private final static int MAX_NUMBER_LINES= 99;
-
-
- private CompilationUnitPreview fPreview;
-
- /**
- * Create a new BlankLinesTabPage.
- * @param modifyDialog The main configuration dialog
- *
- * @param workingValues The values wherein the options are stored.
- */
- public BlankLinesTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- Group group;
-
-// STP - Commented-out next 6 lines (20070207)
-// group= createGroup(numColumns, composite, FormatterMessages.BlankLinesTabPage_compilation_unit_group_title);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_compilation_unit_option_before_package, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_PACKAGE);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_compilation_unit_option_after_package, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_PACKAGE);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_compilation_unit_option_before_import, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_IMPORTS);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_compilation_unit_option_after_import, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AFTER_IMPORTS);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_compilation_unit_option_between_type_declarations, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS);
-
-// STP - Commented-out next 7 lines (20070207)
-// group= createGroup(numColumns, composite, FormatterMessages.BlankLinesTabPage_class_group_title);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_before_first_decl, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_before_decls_of_same_kind, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_before_member_class_decls, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_before_field_decls, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIELD);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_before_method_decls, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_METHOD);
-// createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_class_option_at_beginning_of_method_body, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY);
-
-// STP - Added next 6 lines (20070207)
-group= createGroup(numColumns, composite, FormatterMessages.BlankLinesTabPage_function_group_title);
-createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_function_option_before_first_decl, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION);
-createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_function_option_before_decls_of_same_kind, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK);
-createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_function_option_before_field_decls, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_FIELD);
-createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_function_option_before_function_decls, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_BEFORE_METHOD);
-createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_function_option_at_beginning_of_function_body, DefaultCodeFormatterConstants.FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY);
-
- group= createGroup(numColumns, composite, FormatterMessages.BlankLinesTabPage_blank_lines_group_title);
- createBlankLineTextField(group, numColumns, FormatterMessages.BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve, DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE);
- }
-
- protected void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- /*
- * A helper method to create a number preference for blank lines.
- */
- private void createBlankLineTextField(Composite composite, int numColumns, String message, String key) {
- createNumberPref(composite, numColumns, message, key, MIN_NUMBER_LINES, MAX_NUMBER_LINES);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
- */
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
- */
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java
deleted file mode 100644
index 50fb752b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-public class BracesTabPage extends FormatterTabPage {
-
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- private final String PREVIEW=
- createPreviewHeader(FormatterMessages.BracesTabPage_preview_header) +
- "function foo(data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " var abc = 1;\n" + //$NON-NLS-1$
- " var xyz = 'one';\n" + //$NON-NLS-1$
- " var arr1 = [ '1', '2', '3', '4' ];\n" + //$NON-NLS-1$
- " var arr2 = [];\n" + //$NON-NLS-1$
- " var car = { carMake: 'Toyota', carModel: 'Celica', carYear: 2000 };\n" + //$NON-NLS-1$
- " var car2 = {};\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " switch (data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " case 0:\n" + //$NON-NLS-1$
- " abc = 0;\n" + //$NON-NLS-1$
- " xyz = 'zero';\n" + //$NON-NLS-1$
- " break;\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " default:\n" + //$NON-NLS-1$
- " abc = -1;\n" + //$NON-NLS-1$
- " xyz = 'unknown';\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " }\n\n" + //$NON-NLS-1$
- " if ( document.form1.year.value > 2000 ) {\n" + //$NON-NLS-1$
- " abc += 27;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " else if ( document.form1.year.value > 1900 ) {\n" + //$NON-NLS-1$
- " abc += 19;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " else {\n" + //$NON-NLS-1$
- " abc = 0;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- "}"; //$NON-NLS-1$
-
-
-
- private CompilationUnitPreview fPreview;
-
-
- private final String [] fBracePositions= {
- DefaultCodeFormatterConstants.END_OF_LINE,
- DefaultCodeFormatterConstants.NEXT_LINE,
- DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED
- };
-
- private final String [] fExtendedBracePositions= {
- DefaultCodeFormatterConstants.END_OF_LINE,
- DefaultCodeFormatterConstants.NEXT_LINE,
- DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED,
- DefaultCodeFormatterConstants.NEXT_LINE_ON_WRAP
- };
-
- private final String [] fBracePositionNames= {
- FormatterMessages.BracesTabPage_position_same_line,
- FormatterMessages.BracesTabPage_position_next_line,
- FormatterMessages.BracesTabPage_position_next_line_indented
- };
-
- private final String [] fExtendedBracePositionNames= {
- FormatterMessages.BracesTabPage_position_same_line,
- FormatterMessages.BracesTabPage_position_next_line,
- FormatterMessages.BracesTabPage_position_next_line_indented,
- FormatterMessages.BracesTabPage_position_next_line_on_wrap
- };
-
-
- /**
- * Create a new BracesTabPage.
- * @param modifyDialog
- * @param workingValues
- */
- public BracesTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- final Group group= createGroup(numColumns, composite, FormatterMessages.BracesTabPage_group_brace_positions_title);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_anonymous_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_constructor_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION);
- createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_method_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enumconst_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT);
-// createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_annotation_type_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION);
- createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
- createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks_in_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE);
- createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_switch_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
-
- ComboPreference objectInitOption= createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_object_initializer, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_OBJLIT_INITIALIZER);
- final CheckboxPreference objectInitCheckBox= createIndentedCheckboxPref(group, numColumns, FormatterMessages.BracesTabPage_option_keep_empty_object_initializer_on_one_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_OBJLIT_INITIALIZER_ON_ONE_LINE, FALSE_TRUE);
- objectInitOption.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- updateOptionEnablement((ComboPreference) o, objectInitCheckBox);
- }
- });
- updateOptionEnablement(objectInitOption, objectInitCheckBox);
-
-
- ComboPreference arrayInitOption= createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_array_initializer, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
- final CheckboxPreference arrayInitCheckBox= createIndentedCheckboxPref(group, numColumns, FormatterMessages.BracesTabPage_option_keep_empty_array_initializer_on_one_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE, FALSE_TRUE);
-
- arrayInitOption.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- updateOptionEnablement((ComboPreference) o, arrayInitCheckBox);
- }
- });
- updateOptionEnablement(arrayInitOption, arrayInitCheckBox);
-
- }
-
- /**
- * @param arrayInitOption
- * @param arrayInitCheckBox
- */
- protected final void updateOptionEnablement(ComboPreference arrayInitOption, CheckboxPreference arrayInitCheckBox) {
- arrayInitCheckBox.setEnabled(!arrayInitOption.hasValue(DefaultCodeFormatterConstants.END_OF_LINE));
- }
-
- protected void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- private ComboPreference createBracesCombo(Composite composite, int numColumns, String message, String key) {
- return createComboPref(composite, numColumns, message, key, fBracePositions, fBracePositionNames);
- }
-
- private ComboPreference createExtendedBracesCombo(Composite composite, int numColumns, String message, String key) {
- return createComboPref(composite, numColumns, message, key, fExtendedBracePositions, fExtendedBracePositionNames);
- }
-
- private CheckboxPreference createIndentedCheckboxPref(Composite composite, int numColumns, String message, String key, String [] values) {
- CheckboxPreference pref= createCheckboxPref(composite, numColumns, message, key, values);
- GridData data= (GridData) pref.getControl().getLayoutData();
- data.horizontalIndent= fPixelConverter.convertWidthInCharsToPixels(1);
- return pref;
- }
-
-
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CodeFormatterConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CodeFormatterConfigurationBlock.java
deleted file mode 100644
index a6582873..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CodeFormatterConfigurationBlock.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.List;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-
-/**
- * The code formatter preference page.
- */
-
-public class CodeFormatterConfigurationBlock extends ProfileConfigurationBlock {
-
- private static final String FORMATTER_DIALOG_PREFERENCE_KEY= "formatter_page"; //$NON-NLS-1$
-
- private static final String DIALOGSTORE_LASTSAVELOADPATH= JavaScriptUI.ID_PLUGIN + ".codeformatter"; //$NON-NLS-1$
-
- /**
- * Some Java source code used for preview.
- */
- protected final String PREVIEW= "/**\n* " + //$NON-NLS-1$
- FormatterMessages.CodingStyleConfigurationBlock_preview_title +
- "\n*/\n\n" + //$NON-NLS-1$
- "" + //$NON-NLS-1$
- "var index=0;" + //$NON-NLS-1$
- "var arr=[];" + //$NON-NLS-1$
- "var obj={x:\"\",y:function(){}};" + //$NON-NLS-1$
- "function foo(){var1= new Object();}" + //$NON-NLS-1$
- "function pop(){return arr[index--];}" + //$NON-NLS-1$
- "function push( elem){arr[index++]=elem;}" + //$NON-NLS-1$
- "function isEmpty() {return index==0;}" + //$NON-NLS-1$
- ""; //$NON-NLS-1$
-
- private class PreviewController implements Observer {
-
- public PreviewController(ProfileManager profileManager) {
- profileManager.addObserver(this);
- fJavaPreview.setWorkingValues(profileManager.getSelected().getSettings());
- fJavaPreview.update();
- }
-
- public void update(Observable o, Object arg) {
- final int value= ((Integer)arg).intValue();
- switch (value) {
- case ProfileManager.PROFILE_CREATED_EVENT:
- case ProfileManager.PROFILE_DELETED_EVENT:
- case ProfileManager.SELECTION_CHANGED_EVENT:
- case ProfileManager.SETTINGS_CHANGED_EVENT:
- fJavaPreview.setWorkingValues(((ProfileManager)o).getSelected().getSettings());
- fJavaPreview.update();
- }
- }
-
- }
-
-
- /**
- * The JavaPreview.
- */
- private JavaPreview fJavaPreview;
-
- /**
- * Create a new <code>CodeFormatterConfigurationBlock</code>.
- */
- public CodeFormatterConfigurationBlock(IProject project, PreferencesAccess access) {
- super(project, access, DIALOGSTORE_LASTSAVELOADPATH);
- }
-
- protected IProfileVersioner createProfileVersioner() {
- return new ProfileVersioner();
- }
-
- protected ProfileStore createProfileStore(IProfileVersioner versioner) {
- return new FormatterProfileStore(versioner);
- }
-
- protected ProfileManager createProfileManager(List profiles, IScopeContext context, PreferencesAccess access, IProfileVersioner profileVersioner) {
- return new FormatterProfileManager(profiles, context, access, profileVersioner);
- }
-
- protected void configurePreview(Composite composite, int numColumns, ProfileManager profileManager) {
- createLabel(composite, FormatterMessages.CodingStyleConfigurationBlock_preview_label_text, numColumns);
- CompilationUnitPreview result= new CompilationUnitPreview(profileManager.getSelected().getSettings(), composite);
- result.setPreviewText(PREVIEW);
- fJavaPreview= result;
-
- final GridData gd = new GridData(GridData.FILL_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan = numColumns;
- gd.verticalSpan= 7;
- gd.widthHint = 0;
- gd.heightHint = 0;
- fJavaPreview.getControl().setLayoutData(gd);
-
- new PreviewController(profileManager);
- }
-
-
- protected ModifyDialog createModifyDialog(Shell shell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile) {
- return new FormatterModifyDialog(shell, profile, profileManager, profileStore, newProfile, FORMATTER_DIALOG_PREFERENCE_KEY, DIALOGSTORE_LASTSAVELOADPATH);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CommentsTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CommentsTabPage.java
deleted file mode 100644
index f6c8bbf2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CommentsTabPage.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-
-/**
- * Tab page for the comment formatter settings.
- */
-public class CommentsTabPage extends FormatterTabPage {
-
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- /**
- * Constant array for insert / not_insert.
- */
- private static String[] DO_NOT_INSERT_INSERT = {
- JavaScriptCore.DO_NOT_INSERT,
- JavaScriptCore.INSERT
- };
-
- private static abstract class Controller implements Observer {
-
- private final Collection fMasters;
- private final Collection fSlaves;
-
- public Controller(Collection masters, Collection slaves) {
- fMasters= masters;
- fSlaves= slaves;
- for (final Iterator iter= fMasters.iterator(); iter.hasNext();) {
- ((CheckboxPreference)iter.next()).addObserver(this);
- }
- }
-
- public void update(Observable o, Object arg) {
- boolean enabled= areSlavesEnabled();
-
- for (final Iterator iter= fSlaves.iterator(); iter.hasNext();) {
- final Object obj= iter.next();
- if (obj instanceof Preference) {
- ((Preference)obj).setEnabled(enabled);
- } else if (obj instanceof Control) {
- ((Group)obj).setEnabled(enabled);
- }
- }
- }
-
- public Collection getMasters() {
- return fMasters;
- }
-
- public Collection getSlaves() {
- return fSlaves;
- }
-
- protected abstract boolean areSlavesEnabled();
- }
-
- private final static class OrController extends Controller {
-
- public OrController(Collection masters, Collection slaves) {
- super(masters, slaves);
- update(null, null);
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean areSlavesEnabled() {
- for (final Iterator iter= getMasters().iterator(); iter.hasNext();) {
- if (((CheckboxPreference)iter.next()).getChecked())
- return true;
- }
- return false;
- }
- }
-
- private final String PREVIEW=
- createPreviewHeader("An example for comment formatting. This example is meant to illustrate the various possibilities offered by <i>Eclipse</i> in order to format comments.") + //$NON-NLS-1$
- "/**\n" + //$NON-NLS-1$
- " * This is the comment for the example function.\n" + //$NON-NLS-1$
- " */\n" + //$NON-NLS-1$
- " function foo(arg) {\n" + //$NON-NLS-1$
- " /**\n" + //$NON-NLS-1$
- " *\n" + //$NON-NLS-1$
- " * These possibilities include:\n" + //$NON-NLS-1$
- " * <ul><li>Formatting of header comments.</li><li>Formatting of JSdoc tags</li></ul>\n" + //$NON-NLS-1$
- " */\n" + //$NON-NLS-1$
- " var data;\n" + //$NON-NLS-1$
- " /**\n" + //$NON-NLS-1$
- " * The following is some sample code which illustrates source formatting within JSdoc comments:\n" + //$NON-NLS-1$
- " * <pre>function foo(a,b) { var a=1; var b=true; return a; }</pre>\n" + //$NON-NLS-1$
- " * Descriptions of parameters and return values are best appended at end of the JSdoc comment.\n" + //$NON-NLS-1$
- " * @param a The first parameter. This should be a number between 1 and 100.\n" + //$NON-NLS-1$
- " * @param b The second parameter. This should be a number between 1 and 5.\n" + //$NON-NLS-1$
- " * @return The result of the foo operation, usually within 1 and 100.\n" + //$NON-NLS-1$
- " */\n" + //$NON-NLS-1$
- " function foo2(a,b);\n" + //$NON-NLS-1$
- "}"; //$NON-NLS-1$
-
- private CompilationUnitPreview fPreview;
-
- public CommentsTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- // global group
- final Group globalGroup= createGroup(numColumns, composite, FormatterMessages.CommentsTabPage_group1_title);
- final CheckboxPreference javadoc= createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.commentsTabPage_enable_javadoc_comment_formatting, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT);
- final CheckboxPreference blockComment= createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.CommentsTabPage_enable_block_comment_formatting, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT);
- final CheckboxPreference singleLineComments= createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.CommentsTabPage_enable_line_comment_formatting, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT);
- final CheckboxPreference header= createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.CommentsTabPage_format_header, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER);
- createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.CommentsTabPage_never_indent_block_comments_on_first_column, DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_BLOCK_COMMENTS_ON_FIRST_COLUMN);
- createPrefTrueFalse(globalGroup, numColumns, FormatterMessages.CommentsTabPage_never_indent_line_comments_on_first_column, DefaultCodeFormatterConstants.FORMATTER_NEVER_INDENT_LINE_COMMENTS_ON_FIRST_COLUMN);
-
- // javadoc comment formatting settings
- final Group settingsGroup= createGroup(numColumns, composite, FormatterMessages.CommentsTabPage_group2_title);
- final CheckboxPreference html= createPrefTrueFalse(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_format_html, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML);
- final CheckboxPreference code= createPrefTrueFalse(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_format_code_snippets, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE);
- final CheckboxPreference blankJavadoc= createPrefInsert(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_blank_line_before_javadoc_tags, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS);
- final CheckboxPreference indentJavadoc= createPrefTrueFalse(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_indent_javadoc_tags, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS);
- final CheckboxPreference indentDesc= createCheckboxPref(settingsGroup, numColumns , FormatterMessages.CommentsTabPage_indent_description_after_param, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION, FALSE_TRUE);
- ((GridData)indentDesc.getControl().getLayoutData()).horizontalIndent= fPixelConverter.convertWidthInCharsToPixels(4);
- final CheckboxPreference nlParam= createPrefInsert(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_new_line_after_param_tags, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER);
- final CheckboxPreference blankLinesJavadoc= createPrefTrueFalse(settingsGroup, numColumns, FormatterMessages.CommentsTabPage_clear_blank_lines, DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT);
-
- // block comment settings
- final Group blockSettingsGroup= createGroup(numColumns, composite, FormatterMessages.CommentsTabPage_group4_title);
- final CheckboxPreference blankLinesBlock= createPrefTrueFalse(blockSettingsGroup, numColumns, FormatterMessages.CommentsTabPage_remove_blank_block_comment_lines, DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT);
-
- final Group widthGroup= createGroup(numColumns, composite, FormatterMessages.CommentsTabPage_group3_title);
- final NumberPreference lineWidth= createNumberPref(widthGroup, numColumns, FormatterMessages.CommentsTabPage_line_width, DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH, 0, 9999);
-
- ArrayList javaDocMaster= new ArrayList();
- javaDocMaster.add(javadoc);
- javaDocMaster.add(header);
-
- ArrayList javaDocSlaves= new ArrayList();
- javaDocSlaves.add(settingsGroup);
- javaDocSlaves.add(html);
- javaDocSlaves.add(code);
- javaDocSlaves.add(blankJavadoc);
- javaDocSlaves.add(indentJavadoc);
- javaDocSlaves.add(nlParam);
- javaDocSlaves.add(blankLinesJavadoc);
-
- new OrController(javaDocMaster, javaDocSlaves);
-
- ArrayList indentMasters= new ArrayList();
- indentMasters.add(javadoc);
- indentMasters.add(header);
- indentMasters.add(indentJavadoc);
-
- ArrayList indentSlaves= new ArrayList();
- indentSlaves.add(indentDesc);
-
- new Controller(indentMasters, indentSlaves) {
- protected boolean areSlavesEnabled() {
- return (javadoc.getChecked() || header.getChecked()) && indentJavadoc.getChecked();
- }
- }.update(null, null);
-
- ArrayList blockMasters= new ArrayList();
- blockMasters.add(blockComment);
- blockMasters.add(header);
-
- ArrayList blockSlaves= new ArrayList();
- blockSlaves.add(blockSettingsGroup);
- blockSlaves.add(blankLinesBlock);
-
- new OrController(blockMasters, blockSlaves);
-
- ArrayList lineWidthMasters= new ArrayList();
- lineWidthMasters.add(javadoc);
- lineWidthMasters.add(blockComment);
- lineWidthMasters.add(singleLineComments);
- lineWidthMasters.add(header);
-
- ArrayList lineWidthSlaves= new ArrayList();
- lineWidthSlaves.add(widthGroup);
- lineWidthSlaves.add(lineWidth);
-
- new OrController(lineWidthMasters, lineWidthSlaves);
- }
-
- protected void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
- */
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
- */
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-
- private CheckboxPreference createPrefTrueFalse(Composite composite, int numColumns, String text, String key) {
- return createCheckboxPref(composite, numColumns, text, key, FALSE_TRUE);
- }
-
- private CheckboxPreference createPrefInsert(Composite composite, int numColumns, String text, String key) {
- return createCheckboxPref(composite, numColumns, text, key, DO_NOT_INSERT_INSERT);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CompilationUnitPreview.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CompilationUnitPreview.java
deleted file mode 100644
index 0629126b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CompilationUnitPreview.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.formatter.IContentFormatterExtension;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-
-
-public class CompilationUnitPreview extends JavaPreview {
-
- private String fPreviewText;
-
- /**
- * @param workingValues
- * @param parent
- */
- public CompilationUnitPreview(Map workingValues, Composite parent) {
-
- super(workingValues, parent);
- }
-
- protected void doFormatPreview() {
- if (fPreviewText == null) {
- fPreviewDocument.set(""); //$NON-NLS-1$
- return;
- }
- fPreviewDocument.set(fPreviewText);
-
- fSourceViewer.setRedraw(false);
- final IFormattingContext context = new CommentFormattingContext();
- try {
- final IContentFormatter formatter = fViewerConfiguration.getContentFormatter(fSourceViewer);
- if (formatter instanceof IContentFormatterExtension) {
- final IContentFormatterExtension extension = (IContentFormatterExtension) formatter;
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, fWorkingValues);
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
- extension.format(fPreviewDocument, context);
- } else
- formatter.format(fPreviewDocument, new Region(0, fPreviewDocument.getLength()));
- } catch (Exception e) {
- final IStatus status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR,
- FormatterMessages.JavaPreview_formatter_exception, e);
- JavaScriptPlugin.log(status);
- } finally {
- context.dispose();
- fSourceViewer.setRedraw(true);
- }
- }
-
- public void setPreviewText(String previewText) {
-// if (previewText == null) throw new IllegalArgumentException();
- fPreviewText= previewText;
- update();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ControlStatementsTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ControlStatementsTabPage.java
deleted file mode 100644
index 7c385f34..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ControlStatementsTabPage.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-
-public class ControlStatementsTabPage extends FormatterTabPage {
-
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- /**
- * Constant array for insert / not_insert.
- */
- private static String[] DO_NOT_INSERT_INSERT = {
- JavaScriptCore.DO_NOT_INSERT,
- JavaScriptCore.INSERT
- };
-
-
- private final String PREVIEW=
- createPreviewHeader(FormatterMessages.ControlStatementsTabPage_preview_header) +
- "function bar() {\n" + //$NON-NLS-1$
- " do {} while (true);\n" + //$NON-NLS-1$
- "}\n" + //$NON-NLS-1$
- "function foo2() {\n" + //$NON-NLS-1$
- " if (true) {\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " if (true) {\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " } else if (false) {\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " } else {\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "}\n" + //$NON-NLS-1$
- "function foo(state) {\n" + //$NON-NLS-1$
- " if (true) return;\n" + //$NON-NLS-1$
- " if (true)\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " else if (false)\n" + //$NON-NLS-1$
- " return;\n" + //$NON-NLS-1$
- " else return;\n" + //$NON-NLS-1$
- "}\n" + //$NON-NLS-1$
- "function foo4(n) {\n" + //$NON-NLS-1$
- " if ( n < 0 ) {" + //$NON-NLS-1$
- " throw myException;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "}\n" + //$NON-NLS-1$
- "try { a = foo3(b); } catch (e) { a = \"ERROR\"; } finally { c = a; }"; //$NON-NLS-1$
-
-
-
- private CompilationUnitPreview fPreview;
-
- protected CheckboxPreference fThenStatementPref, fSimpleIfPref;
-
-
- public ControlStatementsTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- final Group generalGroup= createGroup(numColumns, composite, FormatterMessages.ControlStatementsTabPage_general_group_title);
- createOption(generalGroup, numColumns, FormatterMessages.ControlStatementsTabPage_general_group_insert_new_line_before_else_statements, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT, DO_NOT_INSERT_INSERT);
- createOption(generalGroup, numColumns, FormatterMessages.ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT, DO_NOT_INSERT_INSERT);
- createOption(generalGroup, numColumns, FormatterMessages.ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT, DO_NOT_INSERT_INSERT);
- createOption(generalGroup, numColumns, FormatterMessages.ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT, DO_NOT_INSERT_INSERT);
-
- final Group ifElseGroup= createGroup(numColumns, composite, FormatterMessages.ControlStatementsTabPage_if_else_group_title);
- fThenStatementPref= createOption(ifElseGroup, numColumns, FormatterMessages.ControlStatementsTabPage_if_else_group_keep_then_on_same_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE, FALSE_TRUE);
-
- Label l= new Label(ifElseGroup, SWT.NONE);
- GridData gd= new GridData();
- gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(4);
- l.setLayoutData(gd);
-
- fSimpleIfPref= createOption(ifElseGroup, numColumns - 1, FormatterMessages.ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE, FALSE_TRUE);
-
- fThenStatementPref.addObserver( new Observer() {
- public void update(Observable o, Object arg) {
- fSimpleIfPref.setEnabled(!fThenStatementPref.getChecked());
- }
-
- });
-
- fSimpleIfPref.setEnabled(!fThenStatementPref.getChecked());
-
- createOption(ifElseGroup, numColumns, FormatterMessages.ControlStatementsTabPage_if_else_group_keep_else_on_same_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE, FALSE_TRUE);
- createCheckboxPref(ifElseGroup, numColumns, FormatterMessages.ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line, DefaultCodeFormatterConstants.FORMATTER_COMPACT_ELSE_IF, FALSE_TRUE);
- createCheckboxPref(ifElseGroup, numColumns, FormatterMessages.ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line, DefaultCodeFormatterConstants.FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE, FALSE_TRUE);
- }
-
- protected void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
- */
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
- */
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-
- private CheckboxPreference createOption(Composite composite, int span, String name, String key, String [] values) {
- return createCheckboxPref(composite, span, name, key, values);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CreateProfileDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CreateProfileDialog.java
deleted file mode 100644
index 92e4e694..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/CreateProfileDialog.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * The dialog to create a new profile.
- */
-public class CreateProfileDialog extends StatusDialog {
-
-
- private static final String PREF_OPEN_EDIT_DIALOG= JavaScriptUI.ID_PLUGIN + ".codeformatter.create_profile_dialog.open_edit"; //$NON-NLS-1$
-
-
- private Text fNameText;
- private Combo fProfileCombo;
- private Button fEditCheckbox;
-
- private final static StatusInfo fOk= new StatusInfo();
- private final static StatusInfo fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.CreateProfileDialog_status_message_profile_name_is_empty);
- private final static StatusInfo fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.CreateProfileDialog_status_message_profile_with_this_name_already_exists);
-
- private final ProfileManager fProfileManager;
- private final List fSortedProfiles;
- private final String [] fSortedNames;
-
- private CustomProfile fCreatedProfile;
- protected boolean fOpenEditDialog;
-
-
- private final IProfileVersioner fProfileVersioner;
-
- public CreateProfileDialog(Shell parentShell, ProfileManager profileManager, IProfileVersioner profileVersioner) {
- super(parentShell);
- fProfileManager= profileManager;
- fProfileVersioner= profileVersioner;
- fSortedProfiles= fProfileManager.getSortedProfiles();
- fSortedNames= fProfileManager.getSortedDisplayNames();
- }
-
-
- public void create() {
- super.create();
- setTitle(FormatterMessages.CreateProfileDialog_dialog_title);
- }
-
- public Control createDialogArea(Composite parent) {
-
- final int numColumns= 2;
-
- GridData gd;
-
- final GridLayout layout= new GridLayout(numColumns, false);
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
-
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(layout);
-
- // Create "Profile name:" label
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = numColumns;
- gd.widthHint= convertWidthInCharsToPixels(60);
- final Label nameLabel = new Label(composite, SWT.WRAP);
- nameLabel.setText(FormatterMessages.CreateProfileDialog_profile_name_label_text);
- nameLabel.setLayoutData(gd);
-
- // Create text field to enter name
- gd = new GridData( GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= numColumns;
- fNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
- fNameText.setLayoutData(gd);
- fNameText.addModifyListener( new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doValidation();
- }
- });
-
- // Create "Initialize settings ..." label
- gd = new GridData();
- gd.horizontalSpan = numColumns;
- Label profileLabel = new Label(composite, SWT.WRAP);
- profileLabel.setText(FormatterMessages.CreateProfileDialog_base_profile_label_text);
- profileLabel.setLayoutData(gd);
-
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= numColumns;
- fProfileCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
- fProfileCombo.setLayoutData(gd);
-
-
- // "Open the edit dialog now" checkbox
- gd= new GridData();
- gd.horizontalSpan= numColumns;
- fEditCheckbox= new Button(composite, SWT.CHECK);
- fEditCheckbox.setText(FormatterMessages.CreateProfileDialog_open_edit_dialog_checkbox_text);
- fEditCheckbox.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fOpenEditDialog= ((Button)e.widget).getSelection();
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- final IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();//.get(PREF_OPEN_EDIT_DIALOG);
- if (dialogSettings.get(PREF_OPEN_EDIT_DIALOG) != null) {
- fOpenEditDialog= dialogSettings.getBoolean(PREF_OPEN_EDIT_DIALOG);
- } else {
- fOpenEditDialog= true;
- }
- fEditCheckbox.setSelection(fOpenEditDialog);
-
- fProfileCombo.setItems(fSortedNames);
- fProfileCombo.setText(fProfileManager.getDefaultProfile().getName());
- updateStatus(fEmpty);
-
- applyDialogFont(composite);
-
- fNameText.setFocus();
-
- return composite;
- }
-
-
- /**
- * Validate the current settings
- */
- protected void doValidation() {
- final String name= fNameText.getText().trim();
-
- if (fProfileManager.containsName(name)) {
- updateStatus(fDuplicate);
- return;
- }
- if (name.length() == 0) {
- updateStatus(fEmpty);
- return;
- }
- updateStatus(fOk);
- }
-
-
- protected void okPressed() {
- if (!getStatus().isOK())
- return;
-
- JavaScriptPlugin.getDefault().getDialogSettings().put(PREF_OPEN_EDIT_DIALOG, fOpenEditDialog);
-
- final Map baseSettings= new HashMap(((Profile)fSortedProfiles.get(fProfileCombo.getSelectionIndex())).getSettings());
- final String profileName= fNameText.getText();
-
- fCreatedProfile= new CustomProfile(profileName, baseSettings, fProfileVersioner.getCurrentVersion(), fProfileVersioner.getProfileKind());
- fProfileManager.addProfile(fCreatedProfile);
- super.okPressed();
- }
-
- public final CustomProfile getCreatedProfile() {
- return fCreatedProfile;
- }
-
- public final boolean openEditDialog() {
- return fOpenEditDialog;
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.java
deleted file mode 100644
index c6b41144..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.java
+++ /dev/null
@@ -1,498 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * istvan@benedek-home.de - 103706 [formatter] indent empty lines
- * Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class FormatterMessages extends NLS {
-
- private static final String BUNDLE_NAME= FormatterMessages.class.getName();
-
- private FormatterMessages() {
- // Do not instantiate
- }
-
- public static String CommentsTabPage_remove_blank_block_comment_lines;
- public static String FormatterTabPage_ShowInvisibleCharacters_label;
- public static String ModifyDialog_BuiltIn_Status;
- public static String ModifyDialog_Duplicate_Status;
- public static String ModifyDialog_EmptyName_Status;
- public static String ModifyDialog_Export_Button;
- public static String ModifyDialog_NewCreated_Status;
- public static String ModifyDialog_ProfileName_Label;
- public static String ModifyDialog_Shared_Status;
- public static String ProfileConfigurationBlock_load_profile_wrong_profile_message;
- public static String WhiteSpaceTabPage_assignments;
- public static String WhiteSpaceTabPage_assignments_before_assignment_operator;
- public static String WhiteSpaceTabPage_assignments_after_assignment_operator;
- public static String WhiteSpaceTabPage_operators;
- public static String WhiteSpaceTabPage_operators_before_binary_operators;
- public static String WhiteSpaceTabPage_operators_after_binary_operators;
- public static String WhiteSpaceTabPage_operators_before_unary_operators;
- public static String WhiteSpaceTabPage_operators_after_unary_operators;
- public static String WhiteSpaceTabPage_operators_before_prefix_operators;
- public static String WhiteSpaceTabPage_operators_after_prefix_operators;
- public static String WhiteSpaceTabPage_operators_before_postfix_operators;
- public static String WhiteSpaceTabPage_operators_after_postfix_operators;
-// public static String WhiteSpaceTabPage_classes;
-// public static String WhiteSpaceTabPage_classes_before_opening_brace_of_a_class;
-// public static String WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class;
-// public static String WhiteSpaceTabPage_classes_before_comma_implements;
-// public static String WhiteSpaceTabPage_classes_after_comma_implements;
- public static String WhiteSpaceTabPage_methods;
- public static String WhiteSpaceTabPage_constructors;
- public static String WhiteSpaceTabPage_fields;
- public static String WhiteSpaceTabPage_fields_before_comma;
- public static String WhiteSpaceTabPage_fields_after_comma;
- public static String WhiteSpaceTabPage_localvars;
- public static String WhiteSpaceTabPage_localvars_before_comma;
- public static String WhiteSpaceTabPage_localvars_after_comma;
- public static String WhiteSpaceTabPage_arrayinit;
- public static String WhiteSpaceTabPage_arraydecls;
- public static String WhiteSpaceTabPage_arrayelem;
- public static String WhiteSpaceTabPage_arrayalloc;
- public static String WhiteSpaceTabPage_calls;
- public static String WhiteSpaceTabPage_calls_before_comma_in_method_args;
- public static String WhiteSpaceTabPage_calls_after_comma_in_method_args;
- public static String WhiteSpaceTabPage_calls_before_comma_in_alloc;
- public static String WhiteSpaceTabPage_calls_after_comma_in_alloc;
- public static String WhiteSpaceTabPage_calls_before_comma_in_qalloc;
- public static String WhiteSpaceTabPage_calls_after_comma_in_qalloc;
- public static String WhiteSpaceTabPage_statements;
- public static String WhiteSpaceTabPage_blocks;
- public static String WhiteSpaceTabPage_switch;
- public static String WhiteSpaceTabPage_switch_before_case_colon;
- public static String WhiteSpaceTabPage_switch_before_default_colon;
- public static String WhiteSpaceTabPage_do;
- public static String WhiteSpaceTabPage_try;
- public static String WhiteSpaceTabPage_if;
- public static String WhiteSpaceTabPage_for;
- public static String WhiteSpaceTabPage_for_before_comma_init;
- public static String WhiteSpaceTabPage_for_after_comma_init;
- public static String WhiteSpaceTabPage_for_before_comma_inc;
- public static String WhiteSpaceTabPage_for_after_comma_inc;
- public static String WhiteSpaceTabPage_labels;
-// public static String WhiteSpaceTabPage_annotations;
- public static String WhiteSpaceTabPage_annotation_types;
- public static String WhiteSpaceTabPage_param_type_ref;
- public static String WhiteSpaceTabPage_type_arguments;
- public static String WhiteSpaceTabPage_type_parameters;
- public static String WhiteSpaceTabPage_conditionals;
- public static String WhiteSpaceTabPage_typecasts;
- public static String WhiteSpaceTabPage_parenexpr;
- public static String WhiteSpaceTabPage_declarations;
- public static String WhiteSpaceTabPage_expressions;
- public static String WhiteSpaceTabPage_arrays;
- public static String WhiteSpaceTabPage_parameterized_types;
- public static String WhiteSpaceTabPage_after_opening_brace;
- public static String WhiteSpaceTabPage_after_closing_brace;
- public static String WhiteSpaceTabPage_before_opening_brace;
- public static String WhiteSpaceTabPage_before_closing_brace;
- public static String WhiteSpaceTabPage_between_empty_braces;
- public static String WhiteSpaceTabPage_after_opening_paren;
- public static String WhiteSpaceTabPage_after_closing_paren;
- public static String WhiteSpaceTabPage_before_opening_paren;
- public static String WhiteSpaceTabPage_before_closing_paren;
- public static String WhiteSpaceTabPage_between_empty_parens;
- public static String WhiteSpaceTabPage_after_opening_bracket;
- public static String WhiteSpaceTabPage_before_opening_bracket;
- public static String WhiteSpaceTabPage_before_closing_bracket;
- public static String WhiteSpaceTabPage_between_empty_brackets;
- public static String WhiteSpaceTabPage_before_comma_in_params;
- public static String WhiteSpaceTabPage_after_comma_in_params;
- public static String WhiteSpaceTabPage_before_comma_in_throws;
- public static String WhiteSpaceTabPage_after_comma_in_throws;
- public static String WhiteSpaceTabPage_before_ellipsis;
- public static String WhiteSpaceTabPage_after_ellipsis;
- public static String WhiteSpaceTabPage_before_comma;
- public static String WhiteSpaceTabPage_after_comma;
- public static String WhiteSpaceTabPage_after_semicolon;
- public static String WhiteSpaceTabPage_before_semicolon;
- public static String WhiteSpaceTabPage_before_colon;
- public static String WhiteSpaceTabPage_after_colon;
- public static String WhiteSpaceTabPage_before_question;
- public static String WhiteSpaceTabPage_after_question;
- public static String WhiteSpaceTabPage_after_opening_angle_bracket;
- public static String WhiteSpaceTabPage_after_closing_angle_bracket;
- public static String WhiteSpaceTabPage_before_opening_angle_bracket;
- public static String WhiteSpaceTabPage_before_closing_angle_bracket;
- public static String WhiteSpaceTabPage_before_and_list;
- public static String WhiteSpaceTabPage_after_and_list;
-// public static String WhiteSpaceTabPage_enum_decl_before_opening_brace;
-// public static String WhiteSpaceTabPage_enum_decl_before_comma;
-// public static String WhiteSpaceTabPage_enum_decl_after_comma;
-// public static String WhiteSpaceTabPage_enum_const_arg_before_opening_paren;
-// public static String WhiteSpaceTabPage_enum_const_arg_after_opening_paren;
-// public static String WhiteSpaceTabPage_enum_const_arg_between_empty_parens;
-// public static String WhiteSpaceTabPage_enum_const_arg_before_comma;
-// public static String WhiteSpaceTabPage_enum_const_arg_after_comma;
-// public static String WhiteSpaceTabPage_enum_const_arg_before_closing_paren;
-// public static String WhiteSpaceTabPage_enum_const_before_opening_brace;
- public static String WhiteSpaceTabPage_annot_type_method_before_opening_paren;
- public static String WhiteSpaceTabPage_annot_type_method_between_empty_parens;
- public static String WhiteSpaceTabPage_before_parenthesized_expressions;
- public static String WhiteSpaceTabPage_insert_space;
- public static String WhiteSpaceTabPage_object_initializer;
- public static String WhiteSpaceTabPage_object_initializer_before_colon;
- public static String WhiteSpaceTabPage_object_initializer_after_colon;
- public static String WhiteSpaceOptions_return;
- public static String WhiteSpaceOptions_throw;
- public static String WhiteSpaceOptions_before;
- public static String WhiteSpaceOptions_after;
- public static String WhiteSpaceOptions_operator;
- public static String WhiteSpaceOptions_assignment_operator;
- public static String WhiteSpaceOptions_binary_operator;
- public static String WhiteSpaceOptions_unary_operator;
- public static String WhiteSpaceOptions_prefix_operator;
- public static String WhiteSpaceOptions_postfix_operator;
- public static String WhiteSpaceOptions_opening_paren;
- public static String WhiteSpaceOptions_catch;
- public static String WhiteSpaceOptions_for;
- public static String WhiteSpaceOptions_if;
- public static String WhiteSpaceOptions_switch;
- public static String WhiteSpaceOptions_while;
- public static String WhiteSpaceOptions_assert;
- public static String WhiteSpaceOptions_member_function_declaration;
- public static String WhiteSpaceOptions_constructor;
- public static String WhiteSpaceOptions_method;
- public static String WhiteSpaceOptions_method_call;
- public static String WhiteSpaceOptions_paren_expr;
- public static String WhiteSpaceOptions_annotation_modifier;
- public static String WhiteSpaceOptions_annotation_modifier_args;
- public static String WhiteSpaceOptions_annotation_type_member;
- public static String WhiteSpaceOptions_annotation_type;
- public static String WhiteSpaceOptions_type_cast;
- public static String WhiteSpaceOptions_parameterized_type;
- public static String WhiteSpaceOptions_type_arguments;
- public static String WhiteSpaceOptions_type_parameters;
- public static String WhiteSpaceOptions_vararg_parameter;
- public static String WhiteSpaceOptions_closing_paren;
- public static String WhiteSpaceOptions_opening_brace;
- public static String WhiteSpaceOptions_closing_brace;
- public static String WhiteSpaceOptions_opening_bracket;
- public static String WhiteSpaceOptions_closing_bracket;
- public static String WhiteSpaceOptions_class_decl;
- public static String WhiteSpaceOptions_anon_class_decl;
- public static String WhiteSpaceOptions_initializer;
- public static String WhiteSpaceOptions_block;
- public static String WhiteSpaceOptions_array_decl;
- public static String WhiteSpaceOptions_array_element_access;
- public static String WhiteSpaceOptions_array_alloc;
- public static String WhiteSpaceOptions_array_init;
- public static String WhiteSpaceOptions_arguments;
- public static String WhiteSpaceOptions_initialization;
- public static String WhiteSpaceOptions_incrementation;
- public static String WhiteSpaceOptions_parameters;
- public static String WhiteSpaceOptions_explicit_constructor_call;
- public static String WhiteSpaceOptions_alloc_expr;
- public static String WhiteSpaceOptions_throws;
- public static String WhiteSpaceOptions_mult_decls;
- public static String WhiteSpaceOptions_local_vars;
- public static String WhiteSpaceOptions_fields;
- public static String WhiteSpaceOptions_implements_clause;
- public static String WhiteSpaceOptions_colon;
- public static String WhiteSpaceOptions_conditional;
- public static String WhiteSpaceOptions_wildcard;
- public static String WhiteSpaceOptions_label;
- public static String WhiteSpaceOptions_comma;
- public static String WhiteSpaceOptions_semicolon;
- public static String WhiteSpaceOptions_question_mark;
- public static String WhiteSpaceOptions_between_empty_parens;
- public static String WhiteSpaceOptions_between_empty_braces;
- public static String WhiteSpaceOptions_between_empty_brackets;
- public static String WhiteSpaceOptions_constructor_decl;
- public static String WhiteSpaceOptions_method_decl;
- public static String WhiteSpaceOptions_case;
- public static String WhiteSpaceOptions_default;
- public static String WhiteSpaceOptions_statements;
- public static String WhiteSpaceOptions_before_opening_paren;
- public static String WhiteSpaceOptions_after_opening_paren;
- public static String WhiteSpaceOptions_before_closing_paren;
- public static String WhiteSpaceOptions_after_closing_paren;
- public static String WhiteSpaceOptions_before_opening_brace;
- public static String WhiteSpaceOptions_after_opening_brace;
- public static String WhiteSpaceOptions_after_closing_brace;
- public static String WhiteSpaceOptions_before_closing_brace;
- public static String WhiteSpaceOptions_before_opening_bracket;
- public static String WhiteSpaceOptions_after_opening_bracket;
- public static String WhiteSpaceOptions_before_closing_bracket;
- public static String WhiteSpaceOptions_before_opening_angle_bracket;
- public static String WhiteSpaceOptions_after_opening_angle_bracket;
- public static String WhiteSpaceOptions_before_closing_angle_bracket;
- public static String WhiteSpaceOptions_after_closing_angle_bracket;
- public static String WhiteSpaceOptions_before_operator;
- public static String WhiteSpaceOptions_after_operator;
- public static String WhiteSpaceOptions_before_comma;
- public static String WhiteSpaceOptions_after_comma;
- public static String WhiteSpaceOptions_after_colon;
- public static String WhiteSpaceOptions_before_colon;
- public static String WhiteSpaceOptions_before_semicolon;
- public static String WhiteSpaceOptions_after_semicolon;
- public static String WhiteSpaceOptions_before_question_mark;
- public static String WhiteSpaceOptions_after_question_mark;
- public static String WhiteSpaceOptions_before_and;
- public static String WhiteSpaceOptions_after_and;
- public static String WhiteSpaceOptions_before_ellipsis;
- public static String WhiteSpaceOptions_after_ellipsis;
- public static String WhiteSpaceOptions_return_with_parenthesized_expression;
- public static String WhiteSpaceOptions_throw_with_parenthesized_expression;
- public static String WhiteSpaceOptions_object_initializer;
-
- // ===[ LineWrapping ]====================================================
- public static String LineWrappingTabPage_compact_if_else;
- public static String LineWrappingTabPage_extends_clause;
- public static String LineWrappingTabPage_enum_constant_arguments;
- public static String LineWrappingTabPage_enum_constants;
- public static String LineWrappingTabPage_implements_clause;
- public static String LineWrappingTabPage_parameters;
- public static String LineWrappingTabPage_arguments;
-// public static String LineWrappingTabPage_qualified_invocations;
-// public static String LineWrappingTabPage_throws_clause;
- public static String LineWrappingTabPage_object_allocation;
- public static String LineWrappingTabPage_qualified_object_allocation;
- public static String LineWrappingTabPage_array_init;
- public static String LineWrappingTabPage_explicit_constructor_invocations;
- public static String LineWrappingTabPage_conditionals;
- public static String LineWrappingTabPage_binary_exprs;
- public static String LineWrappingTabPage_indentation_default;
- public static String LineWrappingTabPage_indentation_on_column;
- public static String LineWrappingTabPage_indentation_by_one;
- public static String LineWrappingTabPage_class_decls;
- public static String LineWrappingTabPage_method_decls;
- public static String LineWrappingTabPage_constructor_decls;
- public static String LineWrappingTabPage_function_calls;
- public static String LineWrappingTabPage_expressions;
- public static String LineWrappingTabPage_statements;
- public static String LineWrappingTabPage_wrapping_policy_label_text;
- public static String LineWrappingTabPage_indentation_policy_label_text;
- public static String LineWrappingTabPage_force_split_checkbox_text;
- public static String LineWrappingTabPage_force_split_checkbox_multi_text;
- public static String LineWrappingTabPage_line_width_for_preview_label_text;
- public static String LineWrappingTabPage_group;
- public static String LineWrappingTabPage_multi_group;
- public static String LineWrappingTabPage_multiple_selections;
- public static String LineWrappingTabPage_occurences;
- public static String LineWrappingTabPage_splitting_do_not_split;
- public static String LineWrappingTabPage_splitting_wrap_when_necessary;
- public static String LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary;
- public static String LineWrappingTabPage_splitting_wrap_always;
- public static String LineWrappingTabPage_splitting_wrap_always_indent_all_but_first;
- public static String LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary;
- public static String LineWrappingTabPage_width_indent;
- public static String LineWrappingTabPage_width_indent_option_max_line_width;
- public static String LineWrappingTabPage_width_indent_option_default_indent_wrapped;
- public static String LineWrappingTabPage_width_indent_option_default_indent_array;
- public static String LineWrappingTabPage_width_indent_option_default_indent_objlit;
- public static String LineWrappingTabPage_error_invalid_value;
- public static String LineWrappingTabPage_assignment_alignment;
- public static String LineWrappingTabPage_binary_expression_wrap_operator;
- public static String LineWrappingTabPage_binary_expression;
- public static String LineWrappingTabPage_function_decls;
- public static String LineWrappingTabPage_object_init;
-
- public static String BlankLinesTabPage_preview_header;
- public static String BlankLinesTabPage_compilation_unit_group_title;
- public static String BlankLinesTabPage_compilation_unit_option_before_package;
- public static String BlankLinesTabPage_compilation_unit_option_after_package;
- public static String BlankLinesTabPage_compilation_unit_option_before_import;
- public static String BlankLinesTabPage_compilation_unit_option_after_import;
- public static String BlankLinesTabPage_compilation_unit_option_between_import_groups;
- public static String BlankLinesTabPage_compilation_unit_option_between_type_declarations;
-// public static String BlankLinesTabPage_class_group_title;
-// public static String BlankLinesTabPage_class_option_before_first_decl;
-// public static String BlankLinesTabPage_class_option_before_decls_of_same_kind;
-// public static String BlankLinesTabPage_class_option_before_member_class_decls;
-// public static String BlankLinesTabPage_class_option_before_field_decls;
-// public static String BlankLinesTabPage_class_option_before_method_decls;
-// public static String BlankLinesTabPage_class_option_at_beginning_of_method_body;
- public static String BlankLinesTabPage_blank_lines_group_title;
- public static String BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve;
- public static String BlankLinesTabPage_function_group_title;
- public static String BlankLinesTabPage_function_option_before_first_decl;
- public static String BlankLinesTabPage_function_option_before_decls_of_same_kind;
- public static String BlankLinesTabPage_function_option_before_field_decls;
- public static String BlankLinesTabPage_function_option_before_function_decls;
- public static String BlankLinesTabPage_function_option_at_beginning_of_function_body;
- public static String BlankLinesTabPage_preview_comment_between_here;
- public static String BlankLinesTabPage_preview_comment_and_here_are_5_blank_lines;
-
- public static String BracesTabPage_preview_header;
- public static String BracesTabPage_position_same_line;
- public static String BracesTabPage_position_next_line;
- public static String BracesTabPage_position_next_line_indented;
- public static String BracesTabPage_position_next_line_on_wrap;
- public static String BracesTabPage_group_brace_positions_title;
- public static String BracesTabPage_option_class_declaration;
- public static String BracesTabPage_option_anonymous_class_declaration;
- public static String BracesTabPage_option_method_declaration;
- public static String BracesTabPage_option_constructor_declaration;
- public static String BracesTabPage_option_blocks;
- public static String BracesTabPage_option_blocks_in_case;
- public static String BracesTabPage_option_switch_case;
- public static String BracesTabPage_option_array_initializer;
- public static String BracesTabPage_option_keep_empty_array_initializer_on_one_line;
- public static String BracesTabPage_option_annotation_type_declaration;
- public static String BracesTabPage_option_function_declaration;
- public static String BracesTabPage_option_object_initializer;
- public static String BracesTabPage_option_keep_empty_object_initializer_on_one_line;
-
-
- public static String CodingStyleConfigurationBlock_preview_title;
-
-
- // ===[ Comments ]========================================================
- public static String CommentsTabPage_group1_title;
- public static String commentsTabPage_enable_javadoc_comment_formatting;
- public static String CommentsTabPage_enable_line_comment_formatting;
- public static String CommentsTabPage_enable_block_comment_formatting;
- public static String CommentsTabPage_format_header;
- public static String CommentsTabPage_format_html;
- public static String CommentsTabPage_format_code_snippets;
- public static String CommentsTabPage_group2_title;
- public static String CommentsTabPage_clear_blank_lines;
- public static String CommentsTabPage_blank_line_before_javadoc_tags;
- public static String CommentsTabPage_indent_javadoc_tags;
- public static String CommentsTabPage_indent_description_after_param;
- public static String CommentsTabPage_new_line_after_param_tags;
- public static String CommentsTabPage_group3_title;
- public static String CommentsTabPage_group4_title;
- public static String CommentsTabPage_group5_title;
- public static String CommentsTabPage_line_width;
- public static String CommentsTabPage_never_indent_block_comments_on_first_column;
- public static String CommentsTabPage_never_indent_line_comments_on_first_column;
- public static String ControlStatementsTabPage_preview_header;
- public static String ControlStatementsTabPage_general_group_title;
- public static String ControlStatementsTabPage_general_group_insert_new_line_before_else_statements;
- public static String ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements;
- public static String ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements;
- public static String ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements;
- public static String ControlStatementsTabPage_if_else_group_title;
- public static String ControlStatementsTabPage_if_else_group_keep_then_on_same_line;
- public static String ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line;
- public static String ControlStatementsTabPage_if_else_group_keep_else_on_same_line;
- public static String ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line;
- public static String ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line;
-
- public static String IndentationTabPage_preview_header;
- public static String IndentationTabPage_general_group_title;
- public static String IndentationTabPage_general_group_option_tab_policy;
- public static String IndentationTabPage_general_group_option_tab_policy_SPACE;
- public static String IndentationTabPage_general_group_option_tab_policy_TAB;
- public static String IndentationTabPage_general_group_option_tab_policy_MIXED;
- public static String IndentationTabPage_general_group_option_tab_size;
- public static String IndentationTabPage_general_group_option_indent_size;
- public static String IndentationTabPage_field_alignment_group_title;
- public static String IndentationTabPage_field_alignment_group_align_fields_in_columns;
- public static String IndentationTabPage_indent_group_title;
- public static String IndentationTabPage_class_group_option_indent_declarations_within_class_body;
- public static String IndentationTabPage_class_group_option_indent_declarations_within_annot_decl;
- public static String IndentationTabPage_block_group_option_indent_statements_compare_to_body;
- public static String IndentationTabPage_block_group_option_indent_statements_compare_to_block;
- public static String IndentationTabPage_switch_group_option_indent_statements_within_switch_body;
- public static String IndentationTabPage_switch_group_option_indent_statements_within_case_body;
- public static String IndentationTabPage_switch_group_option_indent_break_statements;
- public static String IndentationTabPage_indent_empty_lines;
- public static String IndentationTabPage_use_tabs_only_for_leading_indentations;
-
- public static String ModifyDialog_tabpage_braces_title;
- public static String ModifyDialog_tabpage_indentation_title;
- public static String ModifyDialog_tabpage_whitespace_title;
- public static String ModifyDialog_tabpage_blank_lines_title;
- public static String ModifyDialog_tabpage_new_lines_title;
- public static String ModifyDialog_tabpage_control_statements_title;
- public static String ModifyDialog_tabpage_line_wrapping_title;
- public static String ModifyDialog_tabpage_comments_title;
-
- public static String NewLinesTabPage_preview_header;
- public static String NewLinesTabPage_newlines_group_title;
- public static String NewLinesTabPage_newlines_group_option_empty_class_body;
- public static String NewLinesTabPage_newlines_group_option_empty_annotation_decl_body;
- public static String NewLinesTabPage_newlines_group_option_empty_anonymous_class_body;
- public static String NewLinesTabPage_newlines_group_option_empty_method_body;
- public static String NewLinesTabPage_newlines_group_option_empty_block;
- public static String NewLinesTabPage_newlines_group_option_empty_end_of_file;
- public static String NewLinesTabPage_empty_statement_group_title;
- public static String NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line;
- public static String NewLinesTabPage_arrayInitializer_group_title;
- public static String NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer;
- public static String NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer;
- public static String NewLinesTabPage_annotations_group_title;
- public static String NewLinesTabPage_annotations_group_option_after_annotation;
- public static String NewLinesTabPage_newlines_group_option_empty_function_body;
- public static String NewLinesTabPage_objectInitializer_group_title;
- public static String NewLinesTabPage_object_group_option_after_opening_brace_of_object_initializer;
- public static String NewLinesTabPage_object_group_option_before_closing_brace_of_object_initializer;
- public static String NewLinesTabPage_object_group_option_after_comma_in_object_initializer;
-
- public static String ProfileManager_default_profile_name;
- public static String ProfileManager_eclipse_profile_name;
- public static String ProfileManager_java_conventions_profile_name;
-
- public static String JavaPreview_formatter_exception;
- public static String WhiteSpaceTabPage_sort_by_java_element;
- public static String WhiteSpaceTabPage_sort_by_syntax_element;
-
- public static String AlreadyExistsDialog_message_profile_already_exists;
- public static String AlreadyExistsDialog_message_profile_name_empty;
- public static String AlreadyExistsDialog_dialog_title;
- public static String AlreadyExistsDialog_dialog_label;
- public static String AlreadyExistsDialog_rename_radio_button_desc;
- public static String AlreadyExistsDialog_overwrite_radio_button_desc;
-
- public static String CodingStyleConfigurationBlock_save_profile_dialog_title;
- public static String CodingStyleConfigurationBlock_save_profile_error_title;
- public static String CodingStyleConfigurationBlock_save_profile_error_message;
- public static String CodingStyleConfigurationBlock_load_profile_dialog_title;
- public static String CodingStyleConfigurationBlock_load_profile_error_title;
- public static String CodingStyleConfigurationBlock_load_profile_error_message;
- public static String CodingStyleConfigurationBlock_load_profile_error_too_new_title;
- public static String CodingStyleConfigurationBlock_load_profile_error_too_new_message;
- public static String CodingStyleConfigurationBlock_save_profile_overwrite_title;
- public static String CodingStyleConfigurationBlock_save_profile_overwrite_message;
- public static String CodingStyleConfigurationBlock_edit_button_desc;
- public static String CodingStyleConfigurationBlock_remove_button_desc;
- public static String CodingStyleConfigurationBlock_new_button_desc;
- public static String CodingStyleConfigurationBlock_load_button_desc;
- public static String CodingStyleConfigurationBlock_save_button_desc;
- public static String CodingStyleConfigurationBlock_preview_label_text;
- public static String CodingStyleConfigurationBlock_error_reading_xml_message;
- public static String CodingStyleConfigurationBlock_error_serializing_xml_message;
- public static String CodingStyleConfigurationBlock_delete_confirmation_title;
- public static String CodingStyleConfigurationBlock_delete_confirmation_question;
-
- public static String CreateProfileDialog_status_message_profile_with_this_name_already_exists;
- public static String CreateProfileDialog_status_message_profile_name_is_empty;
- public static String CreateProfileDialog_dialog_title;
- public static String CreateProfileDialog_profile_name_label_text;
- public static String CreateProfileDialog_base_profile_label_text;
- public static String CreateProfileDialog_open_edit_dialog_checkbox_text;
-
- public static String ModifyDialog_dialog_title;
- public static String ModifyDialog_apply_button;
- public static String ModifyDialogTabPage_preview_label_text;
-
- public static String ProfileManager_unmanaged_profile;
- public static String ProfileManager_unmanaged_profile_with_name;
-
- public static String ModifyDialogTabPage_error_msg_values_text_unassigned;
- public static String ModifyDialogTabPage_error_msg_values_items_text_unassigned;
- public static String ModifyDialogTabPage_NumberPreference_error_invalid_key;
- public static String ModifyDialogTabPage_NumberPreference_error_invalid_value;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, FormatterMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties
deleted file mode 100644
index 65625567..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties
+++ /dev/null
@@ -1,561 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2010 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-# istvan@benedek-home.de - 103706 [formatter] indent empty lines
-# Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently
-###############################################################################
-
-
-WhiteSpaceTabPage_assignments=Assignments
-WhiteSpaceTabPage_assignments_before_assignment_operator=before assignment operator
-WhiteSpaceTabPage_assignments_after_assignment_operator=after assignment operator
-
-WhiteSpaceTabPage_object_initializer=Object initializers
-WhiteSpaceTabPage_object_initializer_before_colon=before object initializer colon
-WhiteSpaceTabPage_object_initializer_after_colon=after object initializer colon
-
-WhiteSpaceTabPage_operators=Operators
-WhiteSpaceTabPage_operators_before_binary_operators=before binary operators
-WhiteSpaceTabPage_operators_after_binary_operators=after binary operators
-WhiteSpaceTabPage_operators_before_unary_operators=before unary operators
-WhiteSpaceTabPage_operators_after_unary_operators=after unary operators
-WhiteSpaceTabPage_operators_before_prefix_operators=before prefix operators
-WhiteSpaceTabPage_operators_after_prefix_operators=after prefix operators
-WhiteSpaceTabPage_operators_before_postfix_operators=before postfix operators
-WhiteSpaceTabPage_operators_after_postfix_operators=after postfix operators
-
-#WhiteSpaceTabPage_classes=Classes
-#WhiteSpaceTabPage_classes_before_opening_brace_of_a_class=before opening brace of a class
-#WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class=before opening brace of an anonymous class
-#WhiteSpaceTabPage_classes_before_comma_implements=before comma in implements clause
-#WhiteSpaceTabPage_classes_after_comma_implements=after comma in implements clause
-
-WhiteSpaceTabPage_methods=Functions
-WhiteSpaceTabPage_constructors=Constructors
-
-WhiteSpaceTabPage_fields=Vars
-WhiteSpaceTabPage_fields_before_comma=before comma in multiple var declarations
-WhiteSpaceTabPage_fields_after_comma=after comma in multiple var declarations
-
-WhiteSpaceTabPage_localvars=Local variables
-WhiteSpaceTabPage_localvars_before_comma=before comma in multiple local declarations
-WhiteSpaceTabPage_localvars_after_comma=after comma in multiple local declarations
-
-WhiteSpaceTabPage_arrayinit=Array initializers
-WhiteSpaceTabPage_arraydecls=Array declarations
-WhiteSpaceTabPage_arrayelem=Array element access
-WhiteSpaceTabPage_arrayalloc=Array allocation
-
-WhiteSpaceTabPage_calls=Function invocations
-
-WhiteSpaceTabPage_calls_before_comma_in_method_args=before comma in function arguments
-WhiteSpaceTabPage_calls_after_comma_in_method_args=after comma in function arguments
-WhiteSpaceTabPage_calls_before_comma_in_alloc=before comma in object allocation arguments
-WhiteSpaceTabPage_calls_after_comma_in_alloc=after comma in object allocation arguments
-WhiteSpaceTabPage_calls_before_comma_in_qalloc=before comma in explicit constructor call
-WhiteSpaceTabPage_calls_after_comma_in_qalloc=after comma in explicit constructor call
-
-WhiteSpaceTabPage_statements=Control statements
-
-WhiteSpaceTabPage_blocks=Blocks
-
-WhiteSpaceTabPage_switch='switch'
-WhiteSpaceTabPage_switch_before_case_colon=before colon in case
-WhiteSpaceTabPage_switch_before_default_colon=before colon in default
-
-WhiteSpaceTabPage_do='while' & 'do while'
-
-
-WhiteSpaceTabPage_try='catch'
-
-WhiteSpaceTabPage_if='if else'
-
-WhiteSpaceTabPage_for='for'
-WhiteSpaceTabPage_for_before_comma_init=before comma in initialization
-WhiteSpaceTabPage_for_after_comma_init=after comma in initialization
-WhiteSpaceTabPage_for_before_comma_inc=before comma in increments
-WhiteSpaceTabPage_for_after_comma_inc=after comma in increments
-
-
-WhiteSpaceTabPage_labels=Labels
-#WhiteSpaceTabPage_annotations=Annotations
-WhiteSpaceTabPage_annotation_types=Annotation types
-WhiteSpaceTabPage_param_type_ref=Type reference
-WhiteSpaceTabPage_type_arguments=Type arguments
-WhiteSpaceTabPage_type_parameters=Type parameters
-
-WhiteSpaceTabPage_conditionals=Conditionals
-
-WhiteSpaceTabPage_typecasts=Type casts
-
-WhiteSpaceTabPage_parenexpr=Parenthesized expressions
-WhiteSpaceTabPage_declarations=Declarations
-WhiteSpaceTabPage_expressions=Expressions
-WhiteSpaceTabPage_arrays=Arrays
-WhiteSpaceTabPage_parameterized_types=Parameterized types
-
-WhiteSpaceTabPage_after_opening_brace=after opening brace
-WhiteSpaceTabPage_after_closing_brace=after closing brace
-WhiteSpaceTabPage_before_opening_brace=before opening brace
-WhiteSpaceTabPage_before_closing_brace=before closing brace
-WhiteSpaceTabPage_between_empty_braces=between empty braces
-
-
-WhiteSpaceTabPage_after_opening_paren=after opening parenthesis
-WhiteSpaceTabPage_after_closing_paren=after closing parenthesis
-WhiteSpaceTabPage_before_opening_paren=before opening parenthesis
-WhiteSpaceTabPage_before_closing_paren=before closing parenthesis
-WhiteSpaceTabPage_between_empty_parens=between empty parenthesis
-
-WhiteSpaceTabPage_after_opening_bracket=after opening bracket
-WhiteSpaceTabPage_before_opening_bracket=before opening bracket
-WhiteSpaceTabPage_before_closing_bracket=before closing bracket
-WhiteSpaceTabPage_between_empty_brackets=between empty brackets
-
-WhiteSpaceTabPage_before_comma_in_params=before comma in parameters
-WhiteSpaceTabPage_after_comma_in_params=after comma in parameters
-WhiteSpaceTabPage_before_comma_in_throws=before comma in 'throws' clause
-WhiteSpaceTabPage_after_comma_in_throws=after comma in 'throws' clause
-
-WhiteSpaceTabPage_before_ellipsis=before ellipsis in vararg parameters
-WhiteSpaceTabPage_after_ellipsis=after ellipsis in vararg parameters
-
-WhiteSpaceTabPage_before_comma=before comma
-WhiteSpaceTabPage_after_comma=after comma
-
-WhiteSpaceTabPage_after_semicolon=after semicolon
-WhiteSpaceTabPage_before_semicolon=before semicolon
-
-WhiteSpaceTabPage_before_colon=before colon
-WhiteSpaceTabPage_after_colon=after colon
-
-WhiteSpaceTabPage_before_question=before question mark
-WhiteSpaceTabPage_after_question=after question mark
-
-
-WhiteSpaceTabPage_after_opening_angle_bracket=after opening angle bracket
-WhiteSpaceTabPage_after_closing_angle_bracket=after closing angle bracket
-WhiteSpaceTabPage_before_opening_angle_bracket=before opening angle bracket
-WhiteSpaceTabPage_before_closing_angle_bracket=before closing angle bracket
-WhiteSpaceTabPage_before_parenthesized_expressions=before parenthesized expressions
-
-WhiteSpaceTabPage_before_and_list=before '&' in type bounds
-WhiteSpaceTabPage_after_and_list=after '&' in type bounds
-
-#WhiteSpaceTabPage_enum_decl_before_opening_brace=before opening brace in declaration
-#WhiteSpaceTabPage_enum_decl_before_comma=before comma between constants
-#WhiteSpaceTabPage_enum_decl_after_comma=after comma between constants
-#WhiteSpaceTabPage_enum_const_arg_before_opening_paren=before opening parenthesis in constant arguments
-#WhiteSpaceTabPage_enum_const_arg_after_opening_paren=after opening parenthesis in constant arguments
-#WhiteSpaceTabPage_enum_const_arg_between_empty_parens=between empty parenthesis in constant arguments
-#WhiteSpaceTabPage_enum_const_arg_before_comma=before comma in constant arguments
-#WhiteSpaceTabPage_enum_const_arg_after_comma=after comma in constant arguments
-#WhiteSpaceTabPage_enum_const_arg_before_closing_paren=before closing parenthesis in constant arguments
-#WhiteSpaceTabPage_enum_const_before_opening_brace=before opening brace of constant body
-
-WhiteSpaceTabPage_annot_type_method_before_opening_paren=before opening parenthesis in annotation type members
-WhiteSpaceTabPage_annot_type_method_between_empty_parens=between parenthesis in annotation type members
-
-
-WhiteSpaceOptions_before=Before
-WhiteSpaceOptions_after=After
-
-WhiteSpaceOptions_operator=Operator
-WhiteSpaceOptions_assignment_operator=Assignment operator
-WhiteSpaceOptions_binary_operator=Binary operator
-WhiteSpaceOptions_unary_operator=Unary operator
-WhiteSpaceOptions_prefix_operator=Prefix operator
-WhiteSpaceOptions_postfix_operator=Postfix operator
-
-
-WhiteSpaceOptions_opening_paren=Opening parenthesis
-WhiteSpaceOptions_catch='catch'
-WhiteSpaceOptions_for='for'
-WhiteSpaceOptions_if='if'
-WhiteSpaceOptions_switch='switch'
-WhiteSpaceOptions_while='while'
-WhiteSpaceOptions_assert='assert'
-WhiteSpaceOptions_member_function_declaration=Member function declaration
-WhiteSpaceOptions_constructor=Constructor
-WhiteSpaceOptions_method=Function
-WhiteSpaceOptions_method_call=Function call
-WhiteSpaceOptions_paren_expr=Parenthesized expression
-WhiteSpaceOptions_annotation_modifier=Annotation
-WhiteSpaceOptions_annotation_modifier_args=Annotation arguments
-WhiteSpaceOptions_annotation_type_member=Annotation type member
-WhiteSpaceOptions_annotation_type=Annotation type
-
-WhiteSpaceOptions_type_cast=Type cast
-WhiteSpaceOptions_parameterized_type=Parameterized type
-WhiteSpaceOptions_type_arguments=Type arguments
-WhiteSpaceOptions_type_parameters=Type parameters
-WhiteSpaceOptions_vararg_parameter=Vararg parameters
-
-WhiteSpaceOptions_closing_paren=Closing parenthesis
-
-WhiteSpaceOptions_opening_brace=Opening brace
-WhiteSpaceOptions_closing_brace=Closing brace
-WhiteSpaceOptions_opening_bracket=Opening bracket
-WhiteSpaceOptions_closing_bracket=Closing bracket
-WhiteSpaceOptions_class_decl=Type declaration
-WhiteSpaceOptions_anon_class_decl=Anonymous type declaration
-WhiteSpaceOptions_initializer=Array initializer
-WhiteSpaceOptions_block=Block
-
-WhiteSpaceOptions_array_decl=Array declaration
-WhiteSpaceOptions_array_element_access=Array element access
-WhiteSpaceOptions_array_alloc=Array allocation
-WhiteSpaceOptions_array_init=Array initializer
-
-WhiteSpaceOptions_arguments=Arguments
-WhiteSpaceOptions_initialization=Initialization
-WhiteSpaceOptions_incrementation=Increment
-WhiteSpaceOptions_parameters=Parameters
-
-WhiteSpaceOptions_explicit_constructor_call=Explicit constructor call
-WhiteSpaceOptions_alloc_expr=Allocation expression
-WhiteSpaceOptions_throws='throws' clause
-WhiteSpaceOptions_mult_decls=Multiple declarations
-WhiteSpaceOptions_local_vars=Local variables
-WhiteSpaceOptions_fields=Fields
-WhiteSpaceOptions_return='return'
-WhiteSpaceOptions_throw='throw'
-WhiteSpaceOptions_implements_clause='extends'/'implements' clause
-WhiteSpaceOptions_colon=Colon
-WhiteSpaceOptions_conditional=Conditional
-WhiteSpaceOptions_wildcard=Wildcard type
-WhiteSpaceOptions_label=Label
-WhiteSpaceOptions_comma=Comma
-WhiteSpaceOptions_object_initializer=Object Initializer
-
-WhiteSpaceOptions_semicolon=Semicolon
-WhiteSpaceOptions_question_mark=Question mark
-WhiteSpaceOptions_between_empty_parens=Between empty parenthesis
-WhiteSpaceOptions_between_empty_braces=Between empty braces
-WhiteSpaceOptions_between_empty_brackets=Between empty brackets
-WhiteSpaceOptions_constructor_decl=Constructor declaration
-WhiteSpaceOptions_method_decl=Function declaration
-WhiteSpaceOptions_case='case'
-WhiteSpaceOptions_default='default'
-WhiteSpaceOptions_statements=Statements
-
-
-
-WhiteSpaceOptions_before_opening_paren=Before opening parenthesis
-WhiteSpaceOptions_after_opening_paren=After opening parenthesis
-WhiteSpaceOptions_before_closing_paren=Before closing parenthesis
-
-WhiteSpaceOptions_after_closing_paren=After closing parenthesis
-WhiteSpaceOptions_before_opening_brace=Before opening brace
-WhiteSpaceOptions_after_opening_brace=After opening brace
-WhiteSpaceOptions_after_closing_brace=After closing brace
-WhiteSpaceOptions_before_closing_brace=Before closing brace
-WhiteSpaceOptions_before_opening_bracket=Before opening bracket
-WhiteSpaceOptions_after_opening_bracket=After opening bracket
-WhiteSpaceOptions_before_closing_bracket=Before closing bracket
-
-WhiteSpaceOptions_before_opening_angle_bracket=Before opening angle bracket
-WhiteSpaceOptions_after_opening_angle_bracket=After opening angle bracket
-WhiteSpaceOptions_before_closing_angle_bracket=Before closing angle bracket
-WhiteSpaceOptions_return_with_parenthesized_expression='return' with parenthesized expression
-WhiteSpaceOptions_throw_with_parenthesized_expression='throws' with parenthesized expression
-WhiteSpaceOptions_after_closing_angle_bracket=After closing angle bracket
-
-WhiteSpaceOptions_before_operator=Before operator
-WhiteSpaceOptions_after_operator=After operator
-WhiteSpaceOptions_before_comma=Before comma
-WhiteSpaceOptions_after_comma=After comma
-WhiteSpaceOptions_after_colon=After colon
-WhiteSpaceOptions_before_colon=Before colon
-WhiteSpaceOptions_before_semicolon=Before semicolon
-WhiteSpaceOptions_after_semicolon=After semicolon
-WhiteSpaceOptions_before_question_mark=Before question mark
-WhiteSpaceOptions_after_question_mark=After question mark
-
-WhiteSpaceOptions_before_and=Before & list
-WhiteSpaceOptions_after_and=After & list
-
-WhiteSpaceOptions_before_ellipsis=Before Ellipsis
-WhiteSpaceOptions_after_ellipsis=After Ellipsis
-
-WhiteSpaceTabPage_insert_space=&Insert space:
-
-
-#===[ LineWrapping ]==========================================================
-LineWrappingTabPage_compact_if_else=Compact 'if else'
-LineWrappingTabPage_extends_clause='extends' clause
-LineWrappingTabPage_enum_constant_arguments=Constant arguments
-LineWrappingTabPage_enum_constants=Constants
-LineWrappingTabPage_implements_clause='implements' clause
-LineWrappingTabPage_parameters=Parameters
-LineWrappingTabPage_arguments=Arguments
-#LineWrappingTabPage_qualified_invocations=Qualified invocations
-#LineWrappingTabPage_throws_clause='throws' clause
-LineWrappingTabPage_object_allocation=Object allocation arguments
-LineWrappingTabPage_qualified_object_allocation=Qualified object allocation arguments
-LineWrappingTabPage_array_init=Array initializers
-LineWrappingTabPage_explicit_constructor_invocations=Explicit constructor invocations
-LineWrappingTabPage_conditionals=Conditionals
-LineWrappingTabPage_binary_exprs=Binary expressions
-LineWrappingTabPage_indentation_default=Default indentation
-LineWrappingTabPage_indentation_on_column=Indent on column
-LineWrappingTabPage_indentation_by_one=Indent by one
-LineWrappingTabPage_class_decls=Class Declarations
-LineWrappingTabPage_method_decls=Function Declarations
-LineWrappingTabPage_constructor_decls=Constructor declarations
-LineWrappingTabPage_function_calls=Function Calls
-LineWrappingTabPage_expressions=Expressions
-LineWrappingTabPage_statements=Statements
-LineWrappingTabPage_wrapping_policy_label_text=Lin&e wrapping policy:
-LineWrappingTabPage_indentation_policy_label_text=Indent&ation policy:
-LineWrappingTabPage_force_split_checkbox_text=&Force split
-LineWrappingTabPage_force_split_checkbox_multi_text=&Force split
-LineWrappingTabPage_line_width_for_preview_label_text=&Set line width for preview window:
-LineWrappingTabPage_group=Settings for {0}
-LineWrappingTabPage_multi_group=Settings for {0} ({1} items)
-LineWrappingTabPage_multiple_selections=Settings for multiple selections ({0} items)
-LineWrappingTabPage_occurences={0} ({1} of {2})
-LineWrappingTabPage_splitting_do_not_split=Do not wrap
-LineWrappingTabPage_splitting_wrap_when_necessary=Wrap only when necessary
-LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary=Always wrap first element, others when necessary
-LineWrappingTabPage_splitting_wrap_always=Wrap all elements, every element on a new line
-LineWrappingTabPage_splitting_wrap_always_indent_all_but_first=Wrap all elements, indent all but the first element
-LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary=Wrap all elements, except first element if not necessary
-LineWrappingTabPage_width_indent=Line width and indentation levels
-LineWrappingTabPage_width_indent_option_max_line_width=Ma&ximum line width:
-LineWrappingTabPage_width_indent_option_default_indent_wrapped=Defa&ult indentation for wrapped lines:
-LineWrappingTabPage_width_indent_option_default_indent_array=Default indentation for arra&y initializers:
-LineWrappingTabPage_width_indent_option_default_indent_objlit=D&efault indentation for object literal initializers:
-LineWrappingTabPage_error_invalid_value=The key ''{0}'' contained an invalid value; resetting to defaults.
-LineWrappingTabPage_assignment_alignment=Assignments
-LineWrappingTabPage_function_decls=Function Declarations
-LineWrappingTabPage_object_init=Object initializers
-
-LineWrappingTabPage_binary_expression = Binary Expression settings
-LineWrappingTabPage_binary_expression_wrap_operator=Wrap &before operator
-
-#===[ BlankLines ]=========================================================
-BlankLinesTabPage_preview_header=Blank Lines
-BlankLinesTabPage_compilation_unit_group_title=Blank lines in JavaScript file
-BlankLinesTabPage_compilation_unit_option_before_package=Before p&ackage declaration:
-BlankLinesTabPage_compilation_unit_option_after_package=After packa&ge declaration:
-BlankLinesTabPage_compilation_unit_option_before_import=&Before import declaration:
-BlankLinesTabPage_compilation_unit_option_after_import=After import de&claration:
-BlankLinesTabPage_compilation_unit_option_between_import_groups=Between i&mport groups:
-BlankLinesTabPage_compilation_unit_option_between_type_declarations=Between class declarat&ions:
-#BlankLinesTabPage_class_group_title=Blank lines within class declarations
-#BlankLinesTabPage_class_option_before_first_decl=Before &first declaration:
-#BlankLinesTabPage_class_option_before_decls_of_same_kind=Before declarations of the same &kind:
-#BlankLinesTabPage_class_option_before_member_class_decls=Before member cla&ss declarations:
-#BlankLinesTabPage_class_option_before_field_decls=B&efore field declarations:
-#BlankLinesTabPage_class_option_before_method_decls=Before &function declarations:
-#BlankLinesTabPage_class_option_at_beginning_of_method_body= At beginning of function bod&y:
-BlankLinesTabPage_function_group_title=Blank lines within function declarations
-BlankLinesTabPage_function_option_before_first_decl=Before &first declaration:
-BlankLinesTabPage_function_option_before_decls_of_same_kind=Before declarations of the same &kind:
-BlankLinesTabPage_function_option_before_field_decls=B&efore field declarations:
-BlankLinesTabPage_function_option_before_function_decls=Before f&unction declarations:
-BlankLinesTabPage_function_option_at_beginning_of_function_body= At beginning of function bod&y:
-#BlankLinesTabPage_function_option_before_member_class_decls=Before member cla&ss declarations:
-BlankLinesTabPage_blank_lines_group_title=Existing blank lines
-BlankLinesTabPage_blank_lines_option_empty_lines_to_preserve=N&umber of empty lines to preserve:
-BlankLinesTabPage_preview_comment_between_here=Between here...
-BlankLinesTabPage_preview_comment_and_here_are_5_blank_lines=...and here are 5 blank lines
-
-BracesTabPage_preview_header=Braces
-BracesTabPage_position_same_line=Same line
-BracesTabPage_position_next_line=Next line
-BracesTabPage_position_next_line_indented=Next line indented
-BracesTabPage_position_next_line_on_wrap=Next line on wrap
-
-BracesTabPage_group_brace_positions_title=Brace positions
-BracesTabPage_option_class_declaration=&Class or interface declaration:
-BracesTabPage_option_anonymous_class_declaration=Anon&ymous class declaration:
-BracesTabPage_option_method_declaration=&Function declaration:
-BracesTabPage_option_constructor_declaration=Constr&uctor declaration:
-BracesTabPage_option_blocks=&Blocks:
-BracesTabPage_option_blocks_in_case=Bloc&ks in case statement:
-BracesTabPage_option_switch_case='&switch' statement:
-BracesTabPage_option_array_initializer=Array initiali&zer:
-BracesTabPage_option_keep_empty_array_initializer_on_one_line=Keep empty array &initializer on one line
-BracesTabPage_option_annotation_type_declaration=&Annotation type declaration:
-BracesTabPage_option_function_declaration=Fu&nction declaration:
-BracesTabPage_option_object_initializer=Object initiali&zer:
-BracesTabPage_option_keep_empty_object_initializer_on_one_line=Keep empty object &initializer on one line
-
-CodingStyleConfigurationBlock_preview_title=A sample source file for the code formatter preview
-
-#===[ Comments ]==============================================================
-CommentsTabPage_group1_title=General settings
-commentsTabPage_enable_javadoc_comment_formatting=Enable &JSDoc comment formatting
-CommentsTabPage_enable_line_comment_formatting=Enable line &comment formatting
-CommentsTabPage_enable_block_comment_formatting=Enable &block comment formatting
-CommentsTabPage_remove_blank_block_comment_lines=Rem&ove blank lines
-CommentsTabPage_format_header=Enable &header comment formatting
-CommentsTabPage_format_html=Format HTML ta&gs
-CommentsTabPage_format_code_snippets=Format &JavaScript code snippets inside 'pre' tags
-
-CommentsTabPage_group2_title=JSDoc comment settings
-CommentsTabPage_clear_blank_lines=Remove blank l&ines
-CommentsTabPage_blank_line_before_javadoc_tags=Blan&k line before JSDoc tags
-CommentsTabPage_indent_javadoc_tags=Indent JSDoc tag&s
-CommentsTabPage_indent_description_after_param=Ind&ent description a&fter @param
-CommentsTabPage_new_line_after_param_tags=New line &after @param tags
-CommentsTabPage_group3_title=Line width
-CommentsTabPage_line_width=Ma&ximum line width for comments:
-
-CommentsTabPage_group4_title=Block comment settings
-
-CommentsTabPage_group5_title=Indentation settings
-CommentsTabPage_never_indent_block_comments_on_first_column=Never indent bl&ock comments on first column
-CommentsTabPage_never_indent_line_comments_on_first_column=Ne&ver indent line comments on first column
-ControlStatementsTabPage_preview_header=If...else
-ControlStatementsTabPage_general_group_title=General
-ControlStatementsTabPage_general_group_insert_new_line_before_else_statements=Insert new line before '&else' in an 'if' statement
-ControlStatementsTabPage_general_group_insert_new_line_before_catch_statements=Insert new line before '&catch' in a 'try' statement
-ControlStatementsTabPage_general_group_insert_new_line_before_finally_statements=Insert new line before '&finally' in a 'try' statement
-ControlStatementsTabPage_general_group_insert_new_line_before_while_in_do_statements=Insert new line before 'w&hile' in a 'do' statement
-
-ControlStatementsTabPage_if_else_group_title='if else'
-ControlStatementsTabPage_if_else_group_keep_then_on_same_line=Keep 'then' statement &on same line
-ControlStatementsTabPage_if_else_group_keep_simple_if_on_one_line=Keep &simple 'if' on one line
-ControlStatementsTabPage_if_else_group_keep_else_on_same_line=Keep 'else' st&atement on same line
-ControlStatementsTabPage_if_else_group_keep_else_if_on_one_line=&Keep 'else if' on one line
-ControlStatementsTabPage_if_else_group_keep_guardian_clause_on_one_line=Keep 'return' or 'throw' cla&use on one line
-
-IndentationTabPage_preview_header=Indentation
-
-IndentationTabPage_general_group_title=General settings
-IndentationTabPage_general_group_option_tab_policy=Tab polic&y:
-IndentationTabPage_general_group_option_tab_policy_SPACE=Spaces only
-IndentationTabPage_general_group_option_tab_policy_TAB=Tabs only
-IndentationTabPage_general_group_option_tab_policy_MIXED=Mixed
-IndentationTabPage_general_group_option_tab_size=Tab &size:
-IndentationTabPage_general_group_option_indent_size=&Indentation size:
-
-IndentationTabPage_field_alignment_group_title=Alignment of fields in class declarations
-IndentationTabPage_field_alignment_group_align_fields_in_columns=&Align fields in columns
-
-IndentationTabPage_indent_group_title=Indent
-
-IndentationTabPage_class_group_option_indent_declarations_within_class_body=Declarations within class &body
-IndentationTabPage_class_group_option_indent_declarations_within_annot_decl=Declarations within annotation declaration
-IndentationTabPage_block_group_option_indent_statements_compare_to_body=Stat&ements within function body
-IndentationTabPage_block_group_option_indent_statements_compare_to_block=Statements within bl&ocks
-IndentationTabPage_indent_empty_lines=Empty lines
-
-IndentationTabPage_switch_group_option_indent_statements_within_switch_body=Statements wit&hin 'switch' body
-IndentationTabPage_switch_group_option_indent_statements_within_case_body=Statements within '&case' body
-IndentationTabPage_switch_group_option_indent_break_statements='brea&k' statements
-
-IndentationTabPage_use_tabs_only_for_leading_indentations=Use tabs only for leading indentations
-
-ModifyDialog_tabpage_braces_title=B&races
-ModifyDialog_ProfileName_Label=&Profile name:
-ModifyDialog_NewCreated_Status=A new profile will be created.
-ModifyDialog_tabpage_indentation_title=In&dentation
-ModifyDialog_tabpage_whitespace_title=&White Space
-ModifyDialog_tabpage_blank_lines_title=Bla&nk Lines
-ModifyDialog_tabpage_new_lines_title=New &Lines
-ModifyDialog_tabpage_control_statements_title=Con&trol Statements
-ModifyDialog_tabpage_line_wrapping_title=Line Wrapp&ing
-ModifyDialog_tabpage_comments_title=Co&mments
-
-NewLinesTabPage_preview_header=New Lines
-NewLinesTabPage_newlines_group_title=Insert new line
-
-#===[ NewLines ]=========================================================
-NewLinesTabPage_newlines_group_option_empty_class_body=in empty &class body
-NewLinesTabPage_newlines_group_option_empty_annotation_decl_body=in empty annotation body
-NewLinesTabPage_newlines_group_option_empty_anonymous_class_body=in empty &anonymous class body
-NewLinesTabPage_newlines_group_option_empty_method_body=in empt&y function body
-NewLinesTabPage_newlines_group_option_empty_block=in empty &block
-NewLinesTabPage_newlines_group_option_empty_end_of_file=at end of &file
-NewLinesTabPage_empty_statement_group_title=Empty statements
-NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line=Put empty &statement on new line
-NewLinesTabPage_newlines_group_option_empty_function_body=in empt&y function body
-NewLinesTabPage_objectInitializer_group_title=Object initializers
-NewLinesTabPage_object_group_option_after_opening_brace_of_object_initializer=Insert new line after openin&g brace of object initializer
-NewLinesTabPage_object_group_option_before_closing_brace_of_object_initializer=Insert new line before closing brace of object initiali&zer
-NewLinesTabPage_object_group_option_after_comma_in_object_initializer=Insert new line after comma in object initializer
-
-NewLinesTabPage_arrayInitializer_group_title=Array initializers
-NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer=Insert new line &after opening brace of array initializer
-NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer=Insert new line before closing brace of array initializ&er
-
-NewLinesTabPage_annotations_group_title=Annotations
-NewLinesTabPage_annotations_group_option_after_annotation=&Insert new line after annotations
-
-#===[ ProfileManager ]===================================================
-ProfileManager_default_profile_name=Eclipse 2.1 [built-in]
-ProfileManager_eclipse_profile_name=Eclipse [built-in]
-ProfileManager_java_conventions_profile_name=Java Conventions [built-in]
-
-JavaPreview_formatter_exception=The formatter threw an unhandled exception while formatting the preview.
-WhiteSpaceTabPage_sort_by_java_element=Sort options by Java element
-WhiteSpaceTabPage_sort_by_syntax_element=Sort options by Syntax element
-
-
-AlreadyExistsDialog_message_profile_already_exists=A profile with this name already exists.
-AlreadyExistsDialog_message_profile_name_empty=Profile name is empty
-AlreadyExistsDialog_dialog_title=Load Profile
-AlreadyExistsDialog_dialog_label=A profile with the name ''{0}'' already exists in this workspace. What would you like to do?
-AlreadyExistsDialog_rename_radio_button_desc=&Rename the imported profile:
-AlreadyExistsDialog_overwrite_radio_button_desc=&Overwrite the existing profile
-
-CodingStyleConfigurationBlock_save_profile_dialog_title=Export Profile
-CodingStyleConfigurationBlock_save_profile_error_title=Export Profile
-CodingStyleConfigurationBlock_save_profile_error_message=Could not export the profiles.
-CodingStyleConfigurationBlock_load_profile_dialog_title=Import Profile
-CodingStyleConfigurationBlock_load_profile_error_title=Import Profile
-CodingStyleConfigurationBlock_load_profile_error_message=Import failed. Not a valid profile.
-CodingStyleConfigurationBlock_load_profile_error_too_new_title=Importing Profile
-CodingStyleConfigurationBlock_load_profile_error_too_new_message=This profile has been created with \
-a more recent Eclipse build than the one you are using. Some older settings might be reset to their \
-default values and newer settings are ignored. Please note \
-that upgrading profiles from older to newer builds is fully supported.
-CodingStyleConfigurationBlock_save_profile_overwrite_title=Export Profile
-CodingStyleConfigurationBlock_save_profile_overwrite_message=The file ''{0}'' already exists.\nDo you want to replace it?
-CodingStyleConfigurationBlock_edit_button_desc=&Edit...
-CodingStyleConfigurationBlock_remove_button_desc=&Remove
-CodingStyleConfigurationBlock_new_button_desc=Ne&w...
-CodingStyleConfigurationBlock_load_button_desc=I&mport...
-CodingStyleConfigurationBlock_save_button_desc=E&xport...
-CodingStyleConfigurationBlock_preview_label_text=Prev&iew:
-CodingStyleConfigurationBlock_error_reading_xml_message=Problems reading profiles from XML
-CodingStyleConfigurationBlock_error_serializing_xml_message=Problems serializing the profiles to XML
-CodingStyleConfigurationBlock_delete_confirmation_title=Confirm Remove
-CodingStyleConfigurationBlock_delete_confirmation_question=Are you sure you want to remove profile ''{0}''?
-
-CreateProfileDialog_status_message_profile_with_this_name_already_exists=A profile with this name already exists.
-CreateProfileDialog_status_message_profile_name_is_empty=Profile name is empty
-CreateProfileDialog_dialog_title=New Profile
-CreateProfileDialog_profile_name_label_text=&Profile name:
-CreateProfileDialog_base_profile_label_text=I&nitialize settings with the following profile:
-CreateProfileDialog_open_edit_dialog_checkbox_text=&Open the edit dialog now
-
-ModifyDialog_dialog_title=Profile ''{0}''
-ModifyDialog_apply_button=Apply
-ModifyDialog_Export_Button=&Export...
-ModifyDialog_Duplicate_Status=A profile with this name already exists.
-ModifyDialog_BuiltIn_Status=This is a built-in profile, change the name to create a new profile.
-ModifyDialog_Shared_Status=This is a shared profile, change the name to create a new profile.
-ModifyDialog_EmptyName_Status=Profile name is empty.
-ModifyDialogTabPage_preview_label_text=Pre&view:
-
-ProfileManager_unmanaged_profile=Unmanaged profile
-ProfileManager_unmanaged_profile_with_name=Unmanaged profile ''{0}''
-
-ModifyDialogTabPage_error_msg_values_text_unassigned=Values and text must be assigned.
-ModifyDialogTabPage_error_msg_values_items_text_unassigned=Values, items and text must be assigned.
-
-ModifyDialogTabPage_NumberPreference_error_invalid_key=The key {0} does not yield a valid integer value.
-ModifyDialogTabPage_NumberPreference_error_invalid_value=Invalid value: Please enter a number between {0} and {1}.
-ProfileConfigurationBlock_load_profile_wrong_profile_message=Import failed. This is not a valid profile: Expected ''{0}'' but encountered ''{1}''.
-FormatterTabPage_ShowInvisibleCharacters_label=Show &invisible characters
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterModifyDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterModifyDialog.java
deleted file mode 100644
index fd4195b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterModifyDialog.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-
-public class FormatterModifyDialog extends ModifyDialog {
-
- public FormatterModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile, String dialogPreferencesKey, String lastSavePathKey) {
- super(parentShell, profile, profileManager, profileStore, newProfile, dialogPreferencesKey, lastSavePathKey);
- }
-
- protected void addPages(Map values) {
- addTabPage(FormatterMessages.ModifyDialog_tabpage_indentation_title, new IndentationTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_braces_title, new BracesTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_whitespace_title, new WhiteSpaceTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_blank_lines_title, new BlankLinesTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_new_lines_title, new NewLinesTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_control_statements_title, new ControlStatementsTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_line_wrapping_title, new LineWrappingTabPage(this, values));
- addTabPage(FormatterMessages.ModifyDialog_tabpage_comments_title, new CommentsTabPage(this, values));
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileManager.java
deleted file mode 100644
index 4d0faed4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileManager.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class FormatterProfileManager extends ProfileManager {
-
- public final static String ECLIPSE21_PROFILE= "org.eclipse.wst.jsdt.ui.default_profile"; //$NON-NLS-1$
- public final static String ECLIPSE_PROFILE= "org.eclipse.wst.jsdt.ui.default.eclipse_profile"; //$NON-NLS-1$
- public final static String JAVA_PROFILE= "org.eclipse.wst.jsdt.ui.default.sun_profile"; //$NON-NLS-1$
-
- public final static String DEFAULT_PROFILE= ECLIPSE_PROFILE;
-
- private final static KeySet[] KEY_SETS= new KeySet[] {
- new KeySet(JavaScriptCore.PLUGIN_ID, new ArrayList(DefaultCodeFormatterConstants.getJavaConventionsSettings().keySet())),
- new KeySet(JavaScriptUI.ID_PLUGIN, Collections.EMPTY_LIST)
- };
-
- private final static String PROFILE_KEY= PreferenceConstants.FORMATTER_PROFILE;
- private final static String FORMATTER_SETTINGS_VERSION= "formatter_settings_version"; //$NON-NLS-1$
-
- public FormatterProfileManager(List profiles, IScopeContext context, PreferencesAccess preferencesAccess, IProfileVersioner profileVersioner) {
- super(addBuiltinProfiles(profiles, profileVersioner), context, preferencesAccess, profileVersioner, KEY_SETS, PROFILE_KEY, FORMATTER_SETTINGS_VERSION);
- }
-
- private static List addBuiltinProfiles(List profiles, IProfileVersioner profileVersioner) {
- final Profile javaProfile= new BuiltInProfile(JAVA_PROFILE, FormatterMessages.ProfileManager_java_conventions_profile_name, getJavaSettings(), 1, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
- profiles.add(javaProfile);
-
- final Profile eclipseProfile= new BuiltInProfile(ECLIPSE_PROFILE, FormatterMessages.ProfileManager_eclipse_profile_name, getEclipseSettings(), 2, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
- profiles.add(eclipseProfile);
-
- final Profile eclipse21Profile= new BuiltInProfile(ECLIPSE21_PROFILE, FormatterMessages.ProfileManager_default_profile_name, getEclipse21Settings(), 3, profileVersioner.getCurrentVersion(), profileVersioner.getProfileKind());
- profiles.add(eclipse21Profile);
- return profiles;
- }
-
-
- /**
- * @return Returns the settings for the default profile.
- */
- public static Map getEclipse21Settings() {
- final Map options= DefaultCodeFormatterConstants.getEclipse21Settings();
-
- ProfileVersioner.setLatestCompliance(options);
- return options;
- }
-
- /**
- * @return Returns the settings for the new eclipse profile.
- */
- public static Map getEclipseSettings() {
- final Map options= DefaultCodeFormatterConstants.getEclipseDefaultSettings();
-
- ProfileVersioner.setLatestCompliance(options);
- return options;
- }
-
- /**
- * @return Returns the settings for the Java Conventions profile.
- */
- public static Map getJavaSettings() {
- final Map options= DefaultCodeFormatterConstants.getJavaConventionsSettings();
-
- ProfileVersioner.setLatestCompliance(options);
- return options;
- }
-
- /**
- * @return Returns the default settings.
- */
- public static Map getDefaultSettings() {
- return getEclipseSettings();
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager#getSelectedProfileId(org.eclipse.core.runtime.preferences.IScopeContext)
- */
- protected String getSelectedProfileId(IScopeContext instanceScope) {
- String profileId= instanceScope.getNode(JavaScriptUI.ID_PLUGIN).get(PROFILE_KEY, null);
- if (profileId == null) {
- // request from bug 129427
- profileId= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).get(PROFILE_KEY, null);
- // fix for bug 89739
- if (DEFAULT_PROFILE.equals(profileId)) { // default default:
- IEclipsePreferences node= instanceScope.getNode(JavaScriptCore.PLUGIN_ID);
- if (node != null) {
- String tabSetting= node.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, null);
- if (JavaScriptCore.SPACE.equals(tabSetting)) {
- profileId= JAVA_PROFILE;
- }
- }
- }
- }
- return profileId;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager#getDefaultProfile()
- */
- public Profile getDefaultProfile() {
- return getProfile(DEFAULT_PROFILE);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileStore.java
deleted file mode 100644
index 93cfa678..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterProfileStore.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.osgi.service.prefs.BackingStoreException;
-import org.xml.sax.InputSource;
-
-
-
-public class FormatterProfileStore extends ProfileStore {
-
- /**
- * Preference key where all profiles are stored
- */
- private static final String PREF_FORMATTER_PROFILES= "org.eclipse.wst.jsdt.ui.formatterprofiles"; //$NON-NLS-1$
-
- private final IProfileVersioner fProfileVersioner;
-
- public FormatterProfileStore(IProfileVersioner profileVersioner) {
- super(PREF_FORMATTER_PROFILES, profileVersioner);
- fProfileVersioner= profileVersioner;
- }
-
- /**
- * {@inheritDoc}
- */
- public List readProfiles(IScopeContext scope) throws CoreException {
- List profiles= super.readProfiles(scope);
- if (profiles == null) {
- profiles= readOldForCompatibility(scope);
- }
- return profiles;
- }
-
- /**
- * Read the available profiles from the internal XML file and return them
- * as collection.
- * @return returns a list of <code>CustomProfile</code> or <code>null</code>
- */
- private List readOldForCompatibility(IScopeContext instanceScope) {
-
- // in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
- final String STORE_FILE= "code_formatter_profiles.xml"; //$NON-NLS-1$
-
- File file= JavaScriptPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
- if (!file.exists())
- return null;
-
- try {
- // note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
- final FileReader reader= new FileReader(file);
- try {
- List res= readProfilesFromStream(new InputSource(reader));
- if (res != null) {
- for (int i= 0; i < res.size(); i++) {
- fProfileVersioner.update((CustomProfile) res.get(i));
- }
- writeProfiles(res, instanceScope);
- }
- file.delete(); // remove after successful write
- return res;
- } finally {
- reader.close();
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e); // log but ignore
- } catch (IOException e) {
- JavaScriptPlugin.log(e); // log but ignore
- }
- return null;
- }
-
-
- public static void checkCurrentOptionsVersion() {
- PreferencesAccess access= PreferencesAccess.getOriginalPreferences();
- ProfileVersioner profileVersioner= new ProfileVersioner();
-
- IScopeContext instanceScope= access.getInstanceScope();
- IEclipsePreferences uiPreferences= instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
- int version= uiPreferences.getInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, 0);
- if (version >= profileVersioner.getCurrentVersion()) {
- return; // is up to date
- }
- try {
- List profiles= (new FormatterProfileStore(profileVersioner)).readProfiles(instanceScope);
- if (profiles == null) {
- profiles= new ArrayList();
- }
- ProfileManager manager= new FormatterProfileManager(profiles, instanceScope, access, profileVersioner);
- if (manager.getSelected() instanceof CustomProfile) {
- manager.commitChanges(instanceScope); // updates JavaScriptCore options
- }
- uiPreferences.putInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, profileVersioner.getCurrentVersion());
- savePreferences(instanceScope);
-
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i= 0; i < projects.length; i++) {
- IScopeContext scope= access.getProjectScope(projects[i]);
- if (manager.hasProjectSpecificSettings(scope)) {
- manager= new FormatterProfileManager(profiles, scope, access, profileVersioner);
- manager.commitChanges(scope); // updates JavaScriptCore project options
- savePreferences(scope);
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BackingStoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static void savePreferences(final IScopeContext context) throws BackingStoreException {
- try {
- context.getNode(JavaScriptUI.ID_PLUGIN).flush();
- } finally {
- context.getNode(JavaScriptCore.PLUGIN_ID).flush();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterTabPage.java
deleted file mode 100644
index 26dd0c69..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterTabPage.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public abstract class FormatterTabPage extends ModifyDialogTabPage {
-
- private final static String SHOW_INVISIBLE_PREFERENCE_KEY= JavaScriptUI.ID_PLUGIN + ".formatter_page.show_invisible_characters"; //$NON-NLS-1$
-
- private JavaPreview fPreview;
- private final IDialogSettings fDialogSettings;
- private Button fShowInvisibleButton;
-
- public FormatterTabPage(IModificationListener modifyListener, Map workingValues) {
- super(modifyListener, workingValues);
-
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- }
-
- protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
-
- createLabel(numColumns - 1, composite, FormatterMessages.ModifyDialogTabPage_preview_label_text);
-
- fShowInvisibleButton= new Button(composite, SWT.CHECK);
- fShowInvisibleButton.setText(FormatterMessages.FormatterTabPage_ShowInvisibleCharacters_label);
- fShowInvisibleButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, true, false));
- fShowInvisibleButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fPreview.showInvisibleCharacters(fShowInvisibleButton.getSelection());
- fDialogSettings.put(SHOW_INVISIBLE_PREFERENCE_KEY, fShowInvisibleButton.getSelection());
- }
- });
- fShowInvisibleButton.setSelection(isShowInvisible());
-
- fPreview= doCreateJavaPreview(composite);
- fDefaultFocusManager.add(fPreview.getControl());
- fPreview.showInvisibleCharacters(fShowInvisibleButton.getSelection());
-
- final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, 0);
- gd.widthHint= 0;
- gd.heightHint=0;
- fPreview.getControl().setLayoutData(gd);
-
- return composite;
- }
-
- private boolean isShowInvisible() {
- return fDialogSettings.getBoolean(SHOW_INVISIBLE_PREFERENCE_KEY);
- }
-
- protected void doUpdatePreview() {
- boolean showInvisible= isShowInvisible();
- fPreview.showInvisibleCharacters(showInvisible);
- fShowInvisibleButton.setSelection(showInvisible);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IProfileVersioner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IProfileVersioner.java
deleted file mode 100644
index a61220b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IProfileVersioner.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-
-public interface IProfileVersioner {
-
- public int getFirstVersion();
-
- public int getCurrentVersion();
-
- public String getProfileKind();
-
- /**
- * Update the <code>profile</code> to the
- * current version number
- */
- public void update(CustomProfile profile);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IndentationTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IndentationTabPage.java
deleted file mode 100644
index 68bebb22..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/IndentationTabPage.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * istvan@benedek-home.de
- * - 103706 [formatter] indent empty lines
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-
-public class IndentationTabPage extends FormatterTabPage {
-
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- private final String PREVIEW=
- createPreviewHeader(FormatterMessages.IndentationTabPage_preview_header) +
- "function foo(data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " var abc = 1;\n" + //$NON-NLS-1$
- " var xyz = 'one';\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " switch (data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " case 0:\n" + //$NON-NLS-1$
- " abc = 0;\n" + //$NON-NLS-1$
- " xyz = 'zero';\n" + //$NON-NLS-1$
- " break;\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " default:\n" + //$NON-NLS-1$
- " abc = -1;\n" + //$NON-NLS-1$
- " xyz = 'unknown';\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " }\n\n" + //$NON-NLS-1$
- " if ( document.form1.year.value > 2000 ) {\n" + //$NON-NLS-1$
- " abc += 27;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " else if ( document.form1.year.value > 1900 ) {\n" + //$NON-NLS-1$
- " abc += 19;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " else {\n" + //$NON-NLS-1$
- " abc = 0;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- "}"; //$NON-NLS-1$
-
- private CompilationUnitPreview fPreview;
- private String fOldTabChar= null;
-
- public IndentationTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- final Group generalGroup= createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_general_group_title);
-
- final String[] tabPolicyValues= new String[] {JavaScriptCore.SPACE, JavaScriptCore.TAB, DefaultCodeFormatterConstants.MIXED};
- final String[] tabPolicyLabels= new String[] {
- FormatterMessages.IndentationTabPage_general_group_option_tab_policy_SPACE,
- FormatterMessages.IndentationTabPage_general_group_option_tab_policy_TAB,
- FormatterMessages.IndentationTabPage_general_group_option_tab_policy_MIXED
- };
- final ComboPreference tabPolicy= createComboPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_tab_policy, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, tabPolicyValues, tabPolicyLabels);
- final CheckboxPreference onlyForLeading= createCheckboxPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_use_tabs_only_for_leading_indentations, DefaultCodeFormatterConstants.FORMATTER_USE_TABS_ONLY_FOR_LEADING_INDENTATIONS, FALSE_TRUE);
- final NumberPreference indentSize= createNumberPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_indent_size, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, 32);
- final NumberPreference tabSize= createNumberPref(generalGroup, numColumns, FormatterMessages.IndentationTabPage_general_group_option_tab_size, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, 32);
-
- String tabchar= (String) fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- updateTabPreferences(tabchar, tabSize, indentSize, onlyForLeading);
- tabPolicy.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- updateTabPreferences((String) arg, tabSize, indentSize, onlyForLeading);
- }
- });
- tabSize.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- indentSize.updateWidget();
- }
- });
-
- final Group typeMemberGroup= createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_field_alignment_group_title);
- createCheckboxPref(typeMemberGroup, numColumns, FormatterMessages.IndentationTabPage_field_alignment_group_align_fields_in_columns, DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, FALSE_TRUE);
-
- final Group classGroup = createGroup(numColumns, composite, FormatterMessages.IndentationTabPage_indent_group_title);
-// createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_class_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER, FALSE_TRUE);
-// createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_decl, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_DECLARATION_HEADER, FALSE_TRUE);
-// createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_enum_const, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ENUM_CONSTANT_HEADER, FALSE_TRUE);
-// createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_class_group_option_indent_declarations_within_annot_decl, DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ANNOTATION_DECLARATION_HEADER, FALSE_TRUE);
-
-
-// final Group blockGroup= createGroup(numColumns, composite, FormatterMessages.getString("IndentationTabPage.block_group.title")); //$NON-NLS-1$
- //createCheckboxPref(classGroup, numColumns, FormatterMessages.getString("IndentationTabPage.block_group.option.indent_statements_within_blocks_and_methods"), DefaultCodeFormatterConstants.FORMATTER_INDENT_BLOCK_STATEMENTS, FALSE_TRUE); //$NON-NLS-1$
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, FALSE_TRUE);
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_block_group_option_indent_statements_compare_to_block, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, FALSE_TRUE);
-
-
-// final Group switchGroup= createGroup(numColumns, composite, FormatterMessages.getString("IndentationTabPage.switch_group.title")); //$NON-NLS-1$
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_switch_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, FALSE_TRUE);
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_statements_within_case_body, DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, FALSE_TRUE);
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_switch_group_option_indent_break_statements, DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, FALSE_TRUE);
- createCheckboxPref(classGroup, numColumns, FormatterMessages.IndentationTabPage_indent_empty_lines, DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, FALSE_TRUE);
- }
-
- public void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
- */
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
- */
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-
- private void updateTabPreferences(String tabPolicy, NumberPreference tabPreference, NumberPreference indentPreference, CheckboxPreference onlyForLeading) {
- /*
- * If the tab-char is SPACE (or TAB), INDENTATION_SIZE
- * preference is not used by the core formatter. We piggy back the
- * visual tab length setting in that preference in that case. If the
- * user selects MIXED, we use the previous TAB_SIZE preference as the
- * new INDENTATION_SIZE (as this is what it really is) and set the
- * visual tab size to the value piggy backed in the INDENTATION_SIZE
- * preference. See also CodeFormatterUtil.
- */
- if (DefaultCodeFormatterConstants.MIXED.equals(tabPolicy)) {
- if (JavaScriptCore.SPACE.equals(fOldTabChar) || JavaScriptCore.TAB.equals(fOldTabChar))
- swapTabValues();
- tabPreference.setEnabled(true);
- tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- indentPreference.setEnabled(true);
- indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
- onlyForLeading.setEnabled(true);
- } else if (JavaScriptCore.SPACE.equals(tabPolicy)) {
- if (DefaultCodeFormatterConstants.MIXED.equals(fOldTabChar))
- swapTabValues();
- tabPreference.setEnabled(true);
- tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
- indentPreference.setEnabled(true);
- indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- onlyForLeading.setEnabled(false);
- } else if (JavaScriptCore.TAB.equals(tabPolicy)) {
- if (DefaultCodeFormatterConstants.MIXED.equals(fOldTabChar))
- swapTabValues();
- tabPreference.setEnabled(true);
- tabPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- indentPreference.setEnabled(false);
- indentPreference.setKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- onlyForLeading.setEnabled(true);
- } else {
- Assert.isTrue(false);
- }
- fOldTabChar= tabPolicy;
- }
-
- private void swapTabValues() {
- Object tabSize= fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
- Object indentSize= fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE);
- fWorkingValues.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, indentSize);
- fWorkingValues.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, tabSize);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/JavaPreview.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/JavaPreview.java
deleted file mode 100644
index 30fa4964..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/JavaPreview.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.preference.PreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.MarginPainter;
-import org.eclipse.jface.text.WhitespaceCharacterPainter;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public abstract class JavaPreview {
-
-
- private final class JavaSourcePreviewerUpdater {
-
- final IPropertyChangeListener fontListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(PreferenceConstants.EDITOR_TEXT_FONT)) {
- final Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
- fSourceViewer.getTextWidget().setFont(font);
- if (fMarginPainter != null) {
- fMarginPainter.initialize();
- }
- }
- }
- };
-
- final IPropertyChangeListener propertyListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (fViewerConfiguration.affectsTextPresentation(event)) {
- fViewerConfiguration.handlePropertyChangeEvent(event);
- fSourceViewer.invalidateTextPresentation();
- }
- }
- };
-
-
- public JavaSourcePreviewerUpdater() {
-
- JFaceResources.getFontRegistry().addListener(fontListener);
- fPreferenceStore.addPropertyChangeListener(propertyListener);
-
- fSourceViewer.getTextWidget().addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- JFaceResources.getFontRegistry().removeListener(fontListener);
- fPreferenceStore.removePropertyChangeListener(propertyListener);
- }
- });
- }
- }
-
- protected final SimpleJavaSourceViewerConfiguration fViewerConfiguration;
- protected final Document fPreviewDocument;
- protected final SourceViewer fSourceViewer;
- protected final IPreferenceStore fPreferenceStore;
-
- protected final MarginPainter fMarginPainter;
-
- protected Map fWorkingValues;
-
- private int fTabSize= 0;
- private WhitespaceCharacterPainter fWhitespaceCharacterPainter;
-
- /**
- * Create a new Java preview
- * @param workingValues
- * @param parent
- */
- public JavaPreview(Map workingValues, Composite parent) {
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- fPreviewDocument= new Document();
- fWorkingValues= workingValues;
- tools.setupJavaDocumentPartitioner( fPreviewDocument, IJavaScriptPartitions.JAVA_PARTITIONING);
-
- PreferenceStore prioritizedSettings= new PreferenceStore();
- prioritizedSettings.setValue(JavaScriptCore.COMPILER_SOURCE, JavaScriptCore.VERSION_1_5);
- prioritizedSettings.setValue(JavaScriptCore.COMPILER_COMPLIANCE, JavaScriptCore.VERSION_1_5);
- prioritizedSettings.setValue(JavaScriptCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaScriptCore.VERSION_1_5);
- prioritizedSettings.setValue(JavaScriptCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaScriptCore.ERROR);
-
- IPreferenceStore[] chain= { prioritizedSettings, JavaScriptPlugin.getDefault().getCombinedPreferenceStore() };
- fPreferenceStore= new ChainedPreferenceStore(chain);
- fSourceViewer= new JavaSourceViewer(parent, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, fPreferenceStore);
- fViewerConfiguration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), fPreferenceStore, null, IJavaScriptPartitions.JAVA_PARTITIONING, true);
- fSourceViewer.configure(fViewerConfiguration);
- fSourceViewer.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
-
- fMarginPainter= new MarginPainter(fSourceViewer);
- final RGB rgb= PreferenceConverter.getColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR);
- fMarginPainter.setMarginRulerColor(tools.getColorManager().getColor(rgb));
- fSourceViewer.addPainter(fMarginPainter);
-
- new JavaSourcePreviewerUpdater();
- fSourceViewer.setDocument(fPreviewDocument);
- }
-
- public Control getControl() {
- return fSourceViewer.getControl();
- }
-
-
- public void update() {
- if (fWorkingValues == null) {
- fPreviewDocument.set(""); //$NON-NLS-1$
- return;
- }
-
- // update the print margin
- final String value= (String)fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT);
- final int lineWidth= getPositiveIntValue(value, 0);
- fMarginPainter.setMarginRulerColumn(lineWidth);
-
- // update the tab size
- final int tabSize= getPositiveIntValue((String) fWorkingValues.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE), 0);
- if (tabSize != fTabSize) fSourceViewer.getTextWidget().setTabs(tabSize);
- fTabSize= tabSize;
-
- final StyledText widget= (StyledText)fSourceViewer.getControl();
- final int height= widget.getClientArea().height;
- final int top0= widget.getTopPixel();
-
- final int totalPixels0= getHeightOfAllLines(widget);
- final int topPixelRange0= totalPixels0 > height ? totalPixels0 - height : 0;
-
- widget.setRedraw(false);
- doFormatPreview();
- fSourceViewer.setSelection(null);
-
- final int totalPixels1= getHeightOfAllLines(widget);
- final int topPixelRange1= totalPixels1 > height ? totalPixels1 - height : 0;
-
- final int top1= topPixelRange0 > 0 ? (int)(topPixelRange1 * top0 / (double)topPixelRange0) : 0;
- widget.setTopPixel(top1);
- widget.setRedraw(true);
- }
-
- private int getHeightOfAllLines(StyledText styledText) {
- int height= 0;
- int lineCount= styledText.getLineCount();
- for (int i= 0; i < lineCount; i++)
- height= height + styledText.getLineHeight(styledText.getOffsetAtLine(i));
- return height;
- }
-
- protected abstract void doFormatPreview();
-
-
- private static int getPositiveIntValue(String string, int defaultValue) {
- try {
- int i= Integer.parseInt(string);
- if (i >= 0) {
- return i;
- }
- } catch (NumberFormatException e) {
- }
- return defaultValue;
- }
-
-
-
- public Map getWorkingValues() {
- return fWorkingValues;
- }
-
-
- public void setWorkingValues(Map workingValues) {
- fWorkingValues= workingValues;
- }
-
- public void showInvisibleCharacters(boolean enable) {
- if (enable) {
- if (fWhitespaceCharacterPainter == null) {
- fWhitespaceCharacterPainter= new WhitespaceCharacterPainter(fSourceViewer);
- fSourceViewer.addPainter(fWhitespaceCharacterPainter);
- }
- } else {
- fSourceViewer.removePainter(fWhitespaceCharacterPainter);
- fWhitespaceCharacterPainter= null;
- }
- update();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/LineWrappingTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/LineWrappingTabPage.java
deleted file mode 100644
index f640bc67..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/LineWrappingTabPage.java
+++ /dev/null
@@ -1,893 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-/**
- * The line wrapping tab page.
- */
-public class LineWrappingTabPage extends FormatterTabPage {
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- /**
- * Represents a line wrapping category. All members are final.
- */
- private final static class Category {
- public final String key;
- public final String name;
- public final String previewText;
- public final List children;
- public final List preferences;
-
- public int index;
-
- public Category(String _key, String _previewText, String _name) {
- this.key= _key;
- this.name= _name;
- this.previewText= _previewText != null ? createPreviewHeader(_name) + _previewText : null;
- children= new ArrayList();
- preferences= new ArrayList();
- }
-
- /**
- * @param _name Category name
- */
- public Category(String _name) {
- this(null, null, _name);
- }
-
- public String toString() {
- return name;
- }
-
- public void addPreference(Preference specificPreference) {
- preferences.add(specificPreference);
- }
-
- public Preference[] getSpecificPreferences() {
- return (Preference[])preferences.toArray(new Preference[preferences.size()]);
- }
- }
-
-
- private final static String PREF_CATEGORY_INDEX= JavaScriptUI.ID_PLUGIN + "formatter_page.line_wrapping_tab_page.last_category_index"; //$NON-NLS-1$
-
-
- private final class CategoryListener implements ISelectionChangedListener, IDoubleClickListener {
-
- private final List fCategoriesList;
-
- private int fIndex= 0;
-
- public CategoryListener(List categoriesTree) {
- fCategoriesList= new ArrayList();
- flatten(fCategoriesList, categoriesTree);
- }
-
- private void flatten(List categoriesList, List categoriesTree) {
- for (final Iterator iter= categoriesTree.iterator(); iter.hasNext(); ) {
- final Category category= (Category) iter.next();
- category.index= fIndex++;
- categoriesList.add(category);
- flatten(categoriesList, category.children);
- }
- }
-
- public void add(Category category) {
- category.index= fIndex++;
- fCategoriesList.add(category);
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- if (event != null)
- fSelection= (IStructuredSelection)event.getSelection();
-
- if (fSelection.size() == 0) {
- disableAll();
- return;
- }
-
- if (!fOptionsGroup.isEnabled())
- enableDefaultComponents(true);
-
- fSelectionState.refreshState(fSelection);
-
- final Category category= (Category)fSelection.getFirstElement();
- fDialogSettings.put(PREF_CATEGORY_INDEX, category.index);
-
- fOptionsGroup.setText(getGroupLabel(category));
- }
-
- private String getGroupLabel(Category category) {
- if (fSelection.size() == 1) {
- if (fSelectionState.getElements().size() == 1)
- return Messages.format(FormatterMessages.LineWrappingTabPage_group, category.name.toLowerCase());
- return Messages.format(FormatterMessages.LineWrappingTabPage_multi_group, new String[] {category.name.toLowerCase(), Integer.toString(fSelectionState.getElements().size())});
- }
- return Messages.format(FormatterMessages.LineWrappingTabPage_multiple_selections, new String[] {Integer.toString(fSelectionState.getElements().size())});
- }
-
- private void disableAll() {
- enableDefaultComponents(false);
- fIndentStyleCombo.setEnabled(false);
- fForceSplit.setEnabled(false);
- }
-
- private void enableDefaultComponents(boolean enabled) {
- fOptionsGroup.setEnabled(enabled);
- fWrappingStyleCombo.setEnabled(enabled);
- fWrappingStylePolicy.setEnabled(enabled);
- }
-
- public void restoreSelection() {
- int index;
- try {
- index= fDialogSettings.getInt(PREF_CATEGORY_INDEX);
- } catch (NumberFormatException ex) {
- index= -1;
- }
- if (index < 0 || index > fCategoriesList.size() - 1) {
- index= 1; // In order to select a category with preview initially
- }
- final Category category= (Category)fCategoriesList.get(index);
- fCategoriesViewer.setSelection(new StructuredSelection(new Category[] {category}));
- }
-
- public void doubleClick(DoubleClickEvent event) {
- final ISelection selection= event.getSelection();
- if (selection instanceof IStructuredSelection) {
- final Category node= (Category)((IStructuredSelection)selection).getFirstElement();
- fCategoriesViewer.setExpandedState(node, !fCategoriesViewer.getExpandedState(node));
- }
- }
- }
-
- private class SelectionState {
- private List fElements= new ArrayList();
- private boolean fRequiresRelayout;
-
- public void refreshState(IStructuredSelection selection) {
- Map wrappingStyleMap= new HashMap();
- Map indentStyleMap= new HashMap();
- Map forceWrappingMap= new HashMap();
- fRequiresRelayout= false;
- showSpecificControls(false);
- fElements.clear();
- evaluateElements(selection.iterator());
- evaluateMaps(wrappingStyleMap, indentStyleMap, forceWrappingMap);
- setPreviewText(getPreviewText(wrappingStyleMap, indentStyleMap, forceWrappingMap));
- refreshControls(wrappingStyleMap, indentStyleMap, forceWrappingMap);
- }
-
- public List getElements() {
- return fElements;
- }
-
- private void evaluateElements(Iterator iterator) {
- Category category;
- String value;
- while (iterator.hasNext()) {
- category= (Category) iterator.next();
- value= (String)fWorkingValues.get(category.key);
- if (value != null) {
- if (!fElements.contains(category))
- fElements.add(category);
- }
- else {
- evaluateElements(category.children.iterator());
- }
- }
- }
-
- private void evaluateMaps(Map wrappingStyleMap, Map indentStyleMap, Map forceWrappingMap) {
- Iterator iterator= fElements.iterator();
- while (iterator.hasNext()) {
- insertIntoMap(wrappingStyleMap, indentStyleMap, forceWrappingMap, (Category)iterator.next());
- }
- }
-
- private String getPreviewText(Map wrappingMap, Map indentMap, Map forceMap) {
- Iterator iterator= fElements.iterator();
- String previewText= ""; //$NON-NLS-1$
- while (iterator.hasNext()) {
- Category category= (Category)iterator.next();
- previewText= previewText + category.previewText + "\n\n"; //$NON-NLS-1$
- }
- return previewText;
- }
-
- private void insertIntoMap(Map wrappingMap, Map indentMap, Map forceMap, Category category) {
- final String value= (String)fWorkingValues.get(category.key);
- Integer wrappingStyle;
- Integer indentStyle;
- Boolean forceWrapping;
-
- try {
- wrappingStyle= new Integer(DefaultCodeFormatterConstants.getWrappingStyle(value));
- indentStyle= new Integer(DefaultCodeFormatterConstants.getIndentStyle(value));
- forceWrapping= new Boolean(DefaultCodeFormatterConstants.getForceWrapping(value));
- } catch (IllegalArgumentException e) {
- forceWrapping= new Boolean(false);
- indentStyle= new Integer(DefaultCodeFormatterConstants.INDENT_DEFAULT);
- wrappingStyle= new Integer(DefaultCodeFormatterConstants.WRAP_NO_SPLIT);
- }
-
- increaseMapEntry(wrappingMap, wrappingStyle);
- increaseMapEntry(indentMap, indentStyle);
- increaseMapEntry(forceMap, forceWrapping);
- }
-
- private void increaseMapEntry(Map map, Object type) {
- Integer count= (Integer)map.get(type);
- if (count == null) // not in map yet -> count == 0
- map.put(type, new Integer(1));
- else
- map.put(type, new Integer(count.intValue() + 1));
- }
-
- private void refreshControls(Map wrappingStyleMap, Map indentStyleMap, Map forceWrappingMap) {
- updateCombos(wrappingStyleMap, indentStyleMap);
- updateButton(forceWrappingMap);
- Integer wrappingStyleMax= getWrappingStyleMax(wrappingStyleMap);
- boolean isInhomogeneous= (fElements.size() != ((Integer)wrappingStyleMap.get(wrappingStyleMax)).intValue());
- updateControlEnablement(isInhomogeneous, wrappingStyleMax.intValue());
- showSpecificControls(true);
- if (fRequiresRelayout) {
- fOptionsComposite.layout(true, true);
- }
- doUpdatePreview();
- notifyValuesModified();
- }
-
- private void showSpecificControls(boolean show) {
- if (fElements.size() != 1)
- return;
-
- Preference[] preferences= ((Category)fElements.get(0)).getSpecificPreferences();
- if (preferences.length == 0)
- return;
-
- fRequiresRelayout= true;
- for (int i= 0; i < preferences.length; i++) {
- Preference preference= preferences[i];
- Control control= preference.getControl();
- control.setVisible(show);
- ((GridData)control.getLayoutData()).exclude= !show;
- }
- }
-
- private Integer getWrappingStyleMax(Map wrappingStyleMap) {
- int maxCount= 0, maxStyle= 0;
- for (int i=0; i<WRAPPING_NAMES.length; i++) {
- Integer count= (Integer)wrappingStyleMap.get(new Integer(i));
- if (count == null)
- continue;
- if (count.intValue() > maxCount) {
- maxCount= count.intValue();
- maxStyle= i;
- }
- }
- return new Integer(maxStyle);
- }
-
- private void updateButton(Map forceWrappingMap) {
- Integer nrOfTrue= (Integer)forceWrappingMap.get(Boolean.TRUE);
- Integer nrOfFalse= (Integer)forceWrappingMap.get(Boolean.FALSE);
-
- if (nrOfTrue == null || nrOfFalse == null)
- fForceSplit.setSelection(nrOfTrue != null);
- else
- fForceSplit.setSelection(nrOfTrue.intValue() > nrOfFalse.intValue());
-
- int max= getMax(nrOfTrue, nrOfFalse);
- String label= FormatterMessages.LineWrappingTabPage_force_split_checkbox_multi_text;
- fForceSplit.setText(getLabelText(label, max, fElements.size()));
- }
-
- private String getLabelText(String label, int count, int nElements) {
- if (nElements == 1 || count == 0)
- return label;
- return Messages.format(FormatterMessages.LineWrappingTabPage_occurences, new String[] {label, Integer.toString(count), Integer.toString(nElements)});
- }
-
- private int getMax(Integer nrOfTrue, Integer nrOfFalse) {
- if (nrOfTrue == null)
- return nrOfFalse.intValue();
- if (nrOfFalse == null)
- return nrOfTrue.intValue();
- if (nrOfTrue.compareTo(nrOfFalse) >= 0)
- return nrOfTrue.intValue();
- return nrOfFalse.intValue();
- }
-
- private void updateCombos(Map wrappingStyleMap, Map indentStyleMap) {
- updateCombo(fWrappingStyleCombo, wrappingStyleMap, WRAPPING_NAMES);
- updateCombo(fIndentStyleCombo, indentStyleMap, INDENT_NAMES);
- }
-
- private void updateCombo(Combo combo, Map map, final String[] items) {
- String[] newItems= new String[items.length];
- int maxCount= 0, maxStyle= 0;
-
- for(int i = 0; i < items.length; i++) {
- Integer count= (Integer) map.get(new Integer(i));
- int val= (count == null) ? 0 : count.intValue();
- if (val > maxCount) {
- maxCount= val;
- maxStyle= i;
- }
- newItems[i]= getLabelText(items[i], val, fElements.size());
- }
- combo.setItems(newItems);
- combo.setText(newItems[maxStyle]);
- }
- }
-
- protected static final String[] INDENT_NAMES = {
- FormatterMessages.LineWrappingTabPage_indentation_default,
- FormatterMessages.LineWrappingTabPage_indentation_on_column,
- FormatterMessages.LineWrappingTabPage_indentation_by_one
- };
-
-
- protected static final String[] WRAPPING_NAMES = {
- FormatterMessages.LineWrappingTabPage_splitting_do_not_split,
- FormatterMessages.LineWrappingTabPage_splitting_wrap_when_necessary, // COMPACT_SPLIT
- FormatterMessages.LineWrappingTabPage_splitting_always_wrap_first_others_when_necessary, // COMPACT_FIRST_BREAK_SPLIT
- FormatterMessages.LineWrappingTabPage_splitting_wrap_always, // ONE_PER_LINE_SPLIT
- FormatterMessages.LineWrappingTabPage_splitting_wrap_always_indent_all_but_first, // NEXT_SHIFTED_SPLIT
- FormatterMessages.LineWrappingTabPage_splitting_wrap_always_except_first_only_if_necessary
- };
-
-
- private final Category fCompactIfCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF,
- "function foo(int argument) {\n" + //$NON-NLS-1$
- " if (argument==0)\n" + //$NON-NLS-1$
- " return 0;\n" + //$NON-NLS-1$
- " if (argument==1)\n" + //$NON-NLS-1$
- " return 42;\n" + //$NON-NLS-1$
- " else\n" + //$NON-NLS-1$
- " return 43;\n" + //$NON-NLS-1$
- "}", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_compact_if_else
- );
-
-
-// private final Category fTypeDeclarationSuperclassCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION,
-// "class Example extends OtherClass {}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_extends_clause
-// );
-//
-//
-// private final Category fTypeDeclarationSuperinterfacesCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION,
-// "class Example implements I1, I2, I3 {}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_implements_clause
-// );
-
-
-// private final Category fConstructorDeclarationsParametersCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION,
-// "class Example {Example(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) { this();}" + //$NON-NLS-1$
-// "Example() {}}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_parameters
-// );
-
- private final Category fMethodDeclarationsParametersCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION,
- "function foo(arg1, arg2, arg3, arg4, arg5, arg6) { var x = 0; return x;}", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_parameters
- );
-
- private final Category fMessageSendArgumentsCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION,
- "function foo() {Other.bar( 100, 200, 300, 400, 500, 600, 700, 800, 900 );}", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_arguments
- );
-
-// private final Category fMessageSendSelectorCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION,
-// "function foofoofoofoofoo(aLongParmName) {return aLongParmName.getFirstSomething();}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_qualified_invocations
-// );
-
-// private final Category fMethodThrowsClauseCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION,
-// "class Example {" + //$NON-NLS-1$
-// "int foo() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
-// " return Other.doSomething();}}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_throws_clause
-// );
-
-// private final Category fConstructorThrowsClauseCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION,
-// "class Example {" + //$NON-NLS-1$
-// "Example() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
-// " return Other.doSomething();}}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_throws_clause
-// );
-
-
- private final Category fAllocationExpressionArgumentsCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION,
- "foo( new SomeClass(100, 200, 300, 400, 500, 600, 700, 800, 900 ) );", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_object_allocation
- );
-
-// private final Category fQualifiedAllocationExpressionCategory= new Category (
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION,
-// "class Example {SomeClass foo() {return SomeOtherClass.new SomeClass(100, 200, 300, 400, 500 );}}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_qualified_object_allocation
-// );
-
- private final Category fArrayInitializerExpressionsCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER,
- "fArray= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_array_init
- );
-
- private final Category fObjectInitializerExpressionsCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER,
- "anObject = { color:'red', wheels:4, engine:{ cylinders:4, size:2.2 } };", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_object_init
- );
-
-// private final Category fExplicitConstructorArgumentsCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL,
-// "class Example extends AnotherClass {Example() {super(100, 200, 300, 400, 500, 600, 700);}}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_explicit_constructor_invocations
-// );
-
- private final Category fConditionalExpressionCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION,
- "function exampleFunction( anArgument) {return anArgument ? 100000 : 200000;}", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_conditionals
- );
-
- private final Category fBinaryExpressionCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION,
- "function foo() {" + //$NON-NLS-1$
- " var sum= 100 + 200 + 300 + 400 + 500 + 600 + 700 + 800;" + //$NON-NLS-1$
- " var product= 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10;" + //$NON-NLS-1$
- " var val= true && false && true && false && true;" + //$NON-NLS-1$
- " return product / sum;}", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_binary_exprs
- );
-
-// private final Category fEnumConstArgumentsCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ENUM_CONSTANT,
-// "enum Example {" + //$NON-NLS-1$
-// "GREEN(0, 255, 0), RED(255, 0, 0) }", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_enum_constant_arguments
-// );
-
-// private final Category fEnumDeclInterfacesCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_ENUM_DECLARATION,
-// "enum Example implements A, B, C {" + //$NON-NLS-1$
-// "}", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_enum_superinterfaces
-// );
-//
-// private final Category fEnumConstantsCategory= new Category(
-// DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
-// "enum Example {" + //$NON-NLS-1$
-// "CANCELLED, RUNNING, WAITING, FINISHED }" + //$NON-NLS-1$
-// "enum Example {" + //$NON-NLS-1$
-// "GREEN(0, 255, 0), RED(255, 0, 0) }", //$NON-NLS-1$
-// FormatterMessages.LineWrappingTabPage_enum_constants
-// );
-
- private final Category fAssignmentCategory= new Category(
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ASSIGNMENT,
- "var string = \"TextTextText\";\n" + //$NON-NLS-1$
- "function foo() {\n" + //$NON-NLS-1$
- " for (int i = 0; i < 10; i++) {\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- " var s;\n" + //$NON-NLS-1$
- " s = \"TextTextText\";\n" + //$NON-NLS-1$
- "}\n", //$NON-NLS-1$
- FormatterMessages.LineWrappingTabPage_assignment_alignment
- );
-
- /**
- * The default preview line width.
- */
- private static int DEFAULT_PREVIEW_WINDOW_LINE_WIDTH= 40;
-
- /**
- * The key to save the user's preview window width in the dialog settings.
- */
- private static final String PREF_PREVIEW_LINE_WIDTH= JavaScriptUI.ID_PLUGIN + ".codeformatter.line_wrapping_tab_page.preview_line_width"; //$NON-NLS-1$
-
- /**
- * The dialog settings.
- */
- protected final IDialogSettings fDialogSettings;
-
- protected TreeViewer fCategoriesViewer;
- protected Label fWrappingStylePolicy;
- protected Combo fWrappingStyleCombo;
- protected Label fIndentStylePolicy;
- protected Combo fIndentStyleCombo;
- protected Button fForceSplit;
-
- protected CompilationUnitPreview fPreview;
-
- protected Group fOptionsGroup;
-
- /**
- * A collection containing the categories tree. This is used as model for the tree viewer.
- * @see TreeViewer
- */
- private final List fCategories;
-
- /**
- * The category listener which makes the selection persistent.
- */
- protected final CategoryListener fCategoryListener;
-
- /**
- * The current selection of elements.
- */
- protected IStructuredSelection fSelection;
-
- /**
- * An object containing the state for the UI.
- */
- SelectionState fSelectionState;
-
- /**
- * A special options store wherein the preview line width is kept.
- */
- protected final Map fPreviewPreferences;
-
- /**
- * The key for the preview line width.
- */
- private final String LINE_SPLIT= DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT;
-
-
- private Composite fOptionsComposite;
-
- /**
- * Create a new line wrapping tab page.
- * @param modifyDialog
- * @param workingValues
- */
- public LineWrappingTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
-
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- final String previewLineWidth= fDialogSettings.get(PREF_PREVIEW_LINE_WIDTH);
-
- fPreviewPreferences= new HashMap();
- fPreviewPreferences.put(LINE_SPLIT, previewLineWidth != null ? previewLineWidth : Integer.toString(DEFAULT_PREVIEW_WINDOW_LINE_WIDTH));
-
- fCategories= createCategories();
- fCategoryListener= new CategoryListener(fCategories);
- }
-
- /**
- * @return Create the categories tree.
- */
- protected List createCategories() {
-
-// final Category classDeclarations= new Category(FormatterMessages.LineWrappingTabPage_class_decls);
-// classDeclarations.children.add(fTypeDeclarationSuperclassCategory);
-// classDeclarations.children.add(fTypeDeclarationSuperinterfacesCategory);
-
-// final Category constructorDeclarations= new Category(null, null, FormatterMessages.LineWrappingTabPage_constructor_decls);
-// constructorDeclarations.children.add(fConstructorDeclarationsParametersCategory);
-// constructorDeclarations.children.add(fConstructorThrowsClauseCategory);
-
- final Category methodDeclarations= new Category(null, null, FormatterMessages.LineWrappingTabPage_method_decls);
- methodDeclarations.children.add(fMethodDeclarationsParametersCategory);
-// methodDeclarations.children.add(fMethodThrowsClauseCategory);
-
-// final Category enumDeclarations= new Category(FormatterMessages.LineWrappingTabPage_enum_decls);
-// enumDeclarations.children.add(fEnumConstantsCategory);
-// enumDeclarations.children.add(fEnumDeclInterfacesCategory);
-// enumDeclarations.children.add(fEnumConstArgumentsCategory);
-
- final Category functionCalls= new Category(FormatterMessages.LineWrappingTabPage_function_calls);
- functionCalls.children.add(fMessageSendArgumentsCategory);
-// functionCalls.children.add(fMessageSendSelectorCategory);
-// functionCalls.children.add(fExplicitConstructorArgumentsCategory);
- functionCalls.children.add(fAllocationExpressionArgumentsCategory);
-// functionCalls.children.add(fQualifiedAllocationExpressionCategory);
-
- final Category expressions= new Category(FormatterMessages.LineWrappingTabPage_expressions);
- expressions.children.add(fBinaryExpressionCategory);
- expressions.children.add(fConditionalExpressionCategory);
- expressions.children.add(fArrayInitializerExpressionsCategory);
- expressions.children.add(fObjectInitializerExpressionsCategory);
- expressions.children.add(fAssignmentCategory);
-
- final Category statements= new Category(FormatterMessages.LineWrappingTabPage_statements);
- statements.children.add(fCompactIfCategory);
-
- final List root= new ArrayList();
-// root.add(classDeclarations);
-// root.add(constructorDeclarations);
- root.add(methodDeclarations);
-// root.add(enumDeclarations);
- root.add(functionCalls);
- root.add(expressions);
- root.add(statements);
-
- return root;
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- fOptionsComposite= composite;
-
- final Group lineWidthGroup= createGroup(numColumns, composite, FormatterMessages.LineWrappingTabPage_width_indent);
-
- createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_max_line_width, DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, 0, 9999);
- createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_default_indent_wrapped, DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, 0, 9999);
- createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_default_indent_array, DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, 0, 9999);
- createNumberPref(lineWidthGroup, numColumns, FormatterMessages.LineWrappingTabPage_width_indent_option_default_indent_objlit, DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_OBJLIT_INITIALIZER, 0, 9999);
-
- fCategoriesViewer= new TreeViewer(composite /*categoryGroup*/, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL );
- fCategoriesViewer.setContentProvider(new ITreeContentProvider() {
- public Object[] getElements(Object inputElement) {
- return ((Collection)inputElement).toArray();
- }
- public Object[] getChildren(Object parentElement) {
- return ((Category)parentElement).children.toArray();
- }
- public Object getParent(Object element) { return null; }
- public boolean hasChildren(Object element) {
- return !((Category)element).children.isEmpty();
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
- public void dispose() {}
- });
- fCategoriesViewer.setLabelProvider(new LabelProvider());
- fCategoriesViewer.setInput(fCategories);
-
- fCategoriesViewer.setExpandedElements(fCategories.toArray());
-
- final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, SWT.DEFAULT);
- fCategoriesViewer.getControl().setLayoutData(gd);
-
- fOptionsGroup = createGroup(numColumns, composite, ""); //$NON-NLS-1$
-
- // label "Select split style:"
- fWrappingStylePolicy= createLabel(numColumns, fOptionsGroup, FormatterMessages.LineWrappingTabPage_wrapping_policy_label_text);
-
- // combo SplitStyleCombo
- fWrappingStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
- fWrappingStyleCombo.setItems(WRAPPING_NAMES);
- fWrappingStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
-
- // label "Select indentation style:"
- fIndentStylePolicy= createLabel(numColumns, fOptionsGroup, FormatterMessages.LineWrappingTabPage_indentation_policy_label_text);
-
- // combo SplitStyleCombo
- fIndentStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
- fIndentStyleCombo.setItems(INDENT_NAMES);
- fIndentStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
-
- // button "Force split"
- fForceSplit= new Button(fOptionsGroup, SWT.CHECK);
- fForceSplit.setLayoutData(createGridData(numColumns - 1, GridData.HORIZONTAL_ALIGN_BEGINNING, SWT.DEFAULT));
- fForceSplit.setText(FormatterMessages.LineWrappingTabPage_force_split_checkbox_text);
-
- Preference expressionWrapPositionPreference= createCheckboxPref(fOptionsGroup, 1, FormatterMessages.LineWrappingTabPage_binary_expression_wrap_operator, DefaultCodeFormatterConstants.FORMATTER_WRAP_BEFORE_BINARY_OPERATOR, FALSE_TRUE);
- Control control= expressionWrapPositionPreference.getControl();
- control.setVisible(false);
- ((GridData)control.getLayoutData()).exclude= true;
- fBinaryExpressionCategory.addPreference(expressionWrapPositionPreference);
-
- // selection state object
- fSelectionState= new SelectionState();
-
- }
-
-
- protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
-
- super.doCreatePreviewPane(composite, numColumns);
-
- final NumberPreference previewLineWidth= new NumberPreference(composite, numColumns / 2, fPreviewPreferences, LINE_SPLIT,
- 0, 9999, FormatterMessages.LineWrappingTabPage_line_width_for_preview_label_text);
- fDefaultFocusManager.add(previewLineWidth);
- previewLineWidth.addObserver(fUpdater);
- previewLineWidth.addObserver(new Observer() {
- public void update(Observable o, Object arg) {
- fDialogSettings.put(PREF_PREVIEW_LINE_WIDTH, (String)fPreviewPreferences.get(LINE_SPLIT));
- }
- });
-
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
- */
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
-
- protected void initializePage() {
-
- fCategoriesViewer.addSelectionChangedListener(fCategoryListener);
- fCategoriesViewer.addDoubleClickListener(fCategoryListener);
-
- fForceSplit.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- forceSplitChanged(fForceSplit.getSelection());
- }
- });
- fIndentStyleCombo.addSelectionListener( new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- indentStyleChanged(((Combo)e.widget).getSelectionIndex());
- }
- });
- fWrappingStyleCombo.addSelectionListener( new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- wrappingStyleChanged(((Combo)e.widget).getSelectionIndex());
- }
- });
-
- fCategoryListener.restoreSelection();
-
- fDefaultFocusManager.add(fCategoriesViewer.getControl());
- fDefaultFocusManager.add(fWrappingStyleCombo);
- fDefaultFocusManager.add(fIndentStyleCombo);
- fDefaultFocusManager.add(fForceSplit);
- }
-
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- final Object normalSetting= fWorkingValues.get(LINE_SPLIT);
- fWorkingValues.put(LINE_SPLIT, fPreviewPreferences.get(LINE_SPLIT));
- fPreview.update();
- fWorkingValues.put(LINE_SPLIT, normalSetting);
- }
-
- protected void setPreviewText(String text) {
- final Object normalSetting= fWorkingValues.get(LINE_SPLIT);
- fWorkingValues.put(LINE_SPLIT, fPreviewPreferences.get(LINE_SPLIT));
- fPreview.setPreviewText(text);
- fWorkingValues.put(LINE_SPLIT, normalSetting);
- }
-
- protected void forceSplitChanged(boolean forceSplit) {
- Iterator iterator= fSelectionState.fElements.iterator();
- String currentKey;
- while (iterator.hasNext()) {
- currentKey= ((Category)iterator.next()).key;
- try {
- changeForceSplit(currentKey, forceSplit);
- } catch (IllegalArgumentException e) {
- fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(forceSplit, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK,
- Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
- }
- }
- fSelectionState.refreshState(fSelection);
- }
-
- private void changeForceSplit(String currentKey, boolean forceSplit) throws IllegalArgumentException{
- String value= (String)fWorkingValues.get(currentKey);
- value= DefaultCodeFormatterConstants.setForceWrapping(value, forceSplit);
- if (value == null)
- throw new IllegalArgumentException();
- fWorkingValues.put(currentKey, value);
- }
-
- protected void wrappingStyleChanged(int wrappingStyle) {
- Iterator iterator= fSelectionState.fElements.iterator();
- String currentKey;
- while (iterator.hasNext()) {
- currentKey= ((Category)iterator.next()).key;
- try {
- changeWrappingStyle(currentKey, wrappingStyle);
- } catch (IllegalArgumentException e) {
- fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, wrappingStyle, DefaultCodeFormatterConstants.INDENT_DEFAULT));
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK,
- Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
- }
- }
- fSelectionState.refreshState(fSelection);
- }
-
- private void changeWrappingStyle(String currentKey, int wrappingStyle) throws IllegalArgumentException {
- String value= (String)fWorkingValues.get(currentKey);
- value= DefaultCodeFormatterConstants.setWrappingStyle(value, wrappingStyle);
- if (value == null)
- throw new IllegalArgumentException();
- fWorkingValues.put(currentKey, value);
- }
-
- protected void indentStyleChanged(int indentStyle) {
- Iterator iterator= fSelectionState.fElements.iterator();
- String currentKey;
- while (iterator.hasNext()) {
- currentKey= ((Category)iterator.next()).key;
- try {
- changeIndentStyle(currentKey, indentStyle);
- } catch (IllegalArgumentException e) {
- fWorkingValues.put(currentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, indentStyle));
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK,
- Messages.format(FormatterMessages.LineWrappingTabPage_error_invalid_value, currentKey), e));
- }
- }
- fSelectionState.refreshState(fSelection);
- }
-
- private void changeIndentStyle(String currentKey, int indentStyle) throws IllegalArgumentException{
- String value= (String)fWorkingValues.get(currentKey);
- value= DefaultCodeFormatterConstants.setIndentStyle(value, indentStyle);
- if (value == null)
- throw new IllegalArgumentException();
- fWorkingValues.put(currentKey, value);
- }
-
- protected void updateControlEnablement(boolean inhomogenous, int wrappingStyle) {
- boolean doSplit= wrappingStyle != DefaultCodeFormatterConstants.WRAP_NO_SPLIT;
- fIndentStylePolicy.setEnabled(true);
- fIndentStyleCombo.setEnabled(inhomogenous || doSplit);
- fForceSplit.setEnabled(inhomogenous || doSplit);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialog.java
deleted file mode 100644
index c72473d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialog.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ModifyDialogTabPage.IModificationListener;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public abstract class ModifyDialog extends StatusDialog implements IModificationListener {
-
- /**
- * The keys to retrieve the preferred area from the dialog settings.
- */
- private static final String DS_KEY_PREFERRED_WIDTH= "modify_dialog.preferred_width"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_HEIGHT= "modify_dialog.preferred_height"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_X= "modify_dialog.preferred_x"; //$NON-NLS-1$
- private static final String DS_KEY_PREFERRED_Y= "modify_dialog.preferred_y"; //$NON-NLS-1$
-
-
- /**
- * The key to store the number (beginning at 0) of the tab page which had the
- * focus last time.
- */
- private static final String DS_KEY_LAST_FOCUS= "modify_dialog.last_focus"; //$NON-NLS-1$
-
- private static final int APPLAY_BUTTON_ID= IDialogConstants.CLIENT_ID;
- private static final int SAVE_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
-
- private final String fKeyPreferredWidth;
- private final String fKeyPreferredHight;
- private final String fKeyPreferredX;
- private final String fKeyPreferredY;
- private final String fKeyLastFocus;
- private final String fLastSaveLoadPathKey;
- private final ProfileStore fProfileStore;
- private final boolean fNewProfile;
- private Profile fProfile;
- private final Map fWorkingValues;
- private final List fTabPages;
- private final IDialogSettings fDialogSettings;
- private TabFolder fTabFolder;
- private final ProfileManager fProfileManager;
- private Button fApplyButton;
- private Button fSaveButton;
- private StringDialogField fProfileNameField;
-
- public ModifyDialog(Shell parentShell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile, String dialogPreferencesKey, String lastSavePathKey) {
- super(parentShell);
-
- fProfileStore= profileStore;
- fLastSaveLoadPathKey= lastSavePathKey;
-
- fKeyPreferredWidth= JavaScriptUI.ID_PLUGIN + dialogPreferencesKey + DS_KEY_PREFERRED_WIDTH;
- fKeyPreferredHight= JavaScriptUI.ID_PLUGIN + dialogPreferencesKey + DS_KEY_PREFERRED_HEIGHT;
- fKeyPreferredX= JavaScriptUI.ID_PLUGIN + dialogPreferencesKey + DS_KEY_PREFERRED_X;
- fKeyPreferredY= JavaScriptUI.ID_PLUGIN + dialogPreferencesKey + DS_KEY_PREFERRED_Y;
- fKeyLastFocus= JavaScriptUI.ID_PLUGIN + dialogPreferencesKey + DS_KEY_LAST_FOCUS;
-
- fProfileManager= profileManager;
- fNewProfile= newProfile;
- setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MAX );
-
- fProfile= profile;
- setTitle(Messages.format(FormatterMessages.ModifyDialog_dialog_title, profile.getName()));
- fWorkingValues= new HashMap(fProfile.getSettings());
- setStatusLineAboveButtons(false);
- fTabPages= new ArrayList();
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- }
-
- protected abstract void addPages(Map values);
-
- public void create() {
- super.create();
- int lastFocusNr= 0;
- try {
- lastFocusNr= fDialogSettings.getInt(fKeyLastFocus);
- if (lastFocusNr < 0) lastFocusNr= 0;
- if (lastFocusNr > fTabPages.size() - 1) lastFocusNr= fTabPages.size() - 1;
- } catch (NumberFormatException x) {
- lastFocusNr= 0;
- }
-
- if (!fNewProfile) {
- fTabFolder.setSelection(lastFocusNr);
- ((ModifyDialogTabPage)fTabFolder.getSelection()[0].getData()).setInitialFocus();
- }
- }
-
- protected Control createDialogArea(Composite parent) {
-
- final Composite composite= (Composite)super.createDialogArea(parent);
-
- Composite nameComposite= new Composite(composite, SWT.NONE);
- nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- nameComposite.setLayout(new GridLayout(3, false));
-
- fProfileNameField= new StringDialogField();
- fProfileNameField.setLabelText(FormatterMessages.ModifyDialog_ProfileName_Label);
- fProfileNameField.setText(fProfile.getName());
- fProfileNameField.getLabelControl(nameComposite).setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
- fProfileNameField.getTextControl(nameComposite).setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- fProfileNameField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- doValidate();
- }
- });
-
- fSaveButton= createButton(nameComposite, SAVE_BUTTON_ID, FormatterMessages.ModifyDialog_Export_Button, false);
-
- fTabFolder = new TabFolder(composite, SWT.NONE);
- fTabFolder.setFont(composite.getFont());
- fTabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- addPages(fWorkingValues);
-
- applyDialogFont(composite);
-
- fTabFolder.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {}
- public void widgetSelected(SelectionEvent e) {
- final TabItem tabItem= (TabItem)e.item;
- final ModifyDialogTabPage page= (ModifyDialogTabPage)tabItem.getData();
- // page.fSashForm.setWeights();
- fDialogSettings.put(fKeyLastFocus, fTabPages.indexOf(page));
- page.makeVisible();
- }
- });
-
- doValidate();
-
- return composite;
- }
-
- public void updateStatus(IStatus status) {
- if (status == null) {
- doValidate();
- } else {
- super.updateStatus(status);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#getInitialSize()
- */
- protected Point getInitialSize() {
- Point initialSize= super.getInitialSize();
- try {
- int lastWidth= fDialogSettings.getInt(fKeyPreferredWidth);
- if (initialSize.x > lastWidth)
- lastWidth= initialSize.x;
- int lastHeight= fDialogSettings.getInt(fKeyPreferredHight);
- if (initialSize.y > lastHeight)
- lastHeight= initialSize.x;
- return new Point(lastWidth, lastHeight);
- } catch (NumberFormatException ex) {
- }
- return initialSize;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point)
- */
- protected Point getInitialLocation(Point initialSize) {
- try {
- return new Point(fDialogSettings.getInt(fKeyPreferredX), fDialogSettings.getInt(fKeyPreferredY));
- } catch (NumberFormatException ex) {
- return super.getInitialLocation(initialSize);
- }
- }
-
- public boolean close() {
- final Rectangle shell= getShell().getBounds();
-
- fDialogSettings.put(fKeyPreferredWidth, shell.width);
- fDialogSettings.put(fKeyPreferredHight, shell.height);
- fDialogSettings.put(fKeyPreferredX, shell.x);
- fDialogSettings.put(fKeyPreferredY, shell.y);
-
- return super.close();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- applyPressed();
- super.okPressed();
- }
-
- protected void buttonPressed(int buttonId) {
- if (buttonId == APPLAY_BUTTON_ID) {
- applyPressed();
- setTitle(Messages.format(FormatterMessages.ModifyDialog_dialog_title, fProfile.getName()));
- } else if (buttonId == SAVE_BUTTON_ID) {
- saveButtonPressed();
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- private void applyPressed() {
- if (!fProfile.getName().equals(fProfileNameField.getText())) {
- fProfile= fProfile.rename(fProfileNameField.getText(), fProfileManager);
- }
- fProfile.setSettings(new HashMap(fWorkingValues));
- fProfileManager.setSelected(fProfile);
- doValidate();
- }
-
- private void saveButtonPressed() {
- Profile selected= new CustomProfile(fProfileNameField.getText(), new HashMap(fWorkingValues), fProfile.getVersion(), fProfileManager.getProfileVersioner().getProfileKind());
-
- final FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
- dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_save_profile_dialog_title);
- dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
-
- final String lastPath= JavaScriptPlugin.getDefault().getDialogSettings().get(fLastSaveLoadPathKey + ".savepath"); //$NON-NLS-1$
- if (lastPath != null) {
- dialog.setFilterPath(lastPath);
- }
- final String path= dialog.open();
- if (path == null)
- return;
-
- JavaScriptPlugin.getDefault().getDialogSettings().put(fLastSaveLoadPathKey + ".savepath", dialog.getFilterPath()); //$NON-NLS-1$
-
- final File file= new File(path);
- if (file.exists() && !MessageDialog.openQuestion(getShell(), FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_title, Messages.format(FormatterMessages.CodingStyleConfigurationBlock_save_profile_overwrite_message, path))) {
- return;
- }
- String encoding= ProfileStore.ENCODING;
- final IContentType type= Platform.getContentTypeManager().getContentType("org.eclipse.core.runtime.xml"); //$NON-NLS-1$
- if (type != null)
- encoding= type.getDefaultCharset();
- final Collection profiles= new ArrayList();
- profiles.add(selected);
- try {
- fProfileStore.writeProfilesToFile(profiles, file, encoding);
- } catch (CoreException e) {
- final String title= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_title;
- final String message= FormatterMessages.CodingStyleConfigurationBlock_save_profile_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- fApplyButton= createButton(parent, APPLAY_BUTTON_ID, FormatterMessages.ModifyDialog_apply_button, false);
- fApplyButton.setEnabled(false);
-
- GridLayout layout= (GridLayout) parent.getLayout();
- layout.numColumns++;
- layout.makeColumnsEqualWidth= false;
- Label label= new Label(parent, SWT.NONE);
- GridData data= new GridData();
- data.widthHint= layout.horizontalSpacing;
- label.setLayoutData(data);
- super.createButtonsForButtonBar(parent);
- }
-
- protected final void addTabPage(String title, ModifyDialogTabPage tabPage) {
- final TabItem tabItem= new TabItem(fTabFolder, SWT.NONE);
- applyDialogFont(tabItem.getControl());
- tabItem.setText(title);
- tabItem.setData(tabPage);
- tabItem.setControl(tabPage.createContents(fTabFolder));
- fTabPages.add(tabPage);
- }
-
- public void valuesModified() {
- doValidate();
- }
-
- protected void updateButtonsEnableState(IStatus status) {
- super.updateButtonsEnableState(status);
- if (fApplyButton != null && !fApplyButton.isDisposed()) {
- fApplyButton.setEnabled(hasChanges() && !status.matches(IStatus.ERROR));
- }
- if (fSaveButton != null && !fSaveButton.isDisposed()) {
- fSaveButton.setEnabled(!validateProfileName().matches(IStatus.ERROR));
- }
- }
-
- private void doValidate() {
- IStatus status= validateProfileName();
- if (status.matches(IStatus.ERROR)) {
- updateStatus(status);
- return;
- }
-
- String name= fProfileNameField.getText().trim();
- if (!name.equals(fProfile.getName()) && fProfileManager.containsName(name)) {
- updateStatus(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, FormatterMessages.ModifyDialog_Duplicate_Status));
- return;
- }
-
- if (fProfile.isBuiltInProfile() || fProfile.isSharedProfile()) {
- updateStatus(new Status(IStatus.INFO, JavaScriptUI.ID_PLUGIN, FormatterMessages.ModifyDialog_NewCreated_Status));
- return;
- }
-
- updateStatus(StatusInfo.OK_STATUS);
- }
-
- private IStatus validateProfileName() {
- final String name= fProfileNameField.getText().trim();
-
- if (fProfile.isBuiltInProfile()) {
- if (fProfile.getName().equals(name)) {
- return new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, FormatterMessages.ModifyDialog_BuiltIn_Status);
- }
- }
-
- if (fProfile.isSharedProfile()) {
- if (fProfile.getName().equals(name)) {
- return new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, FormatterMessages.ModifyDialog_Shared_Status);
- }
- }
-
- if (name.length() == 0) {
- return new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, FormatterMessages.ModifyDialog_EmptyName_Status);
- }
-
- return StatusInfo.OK_STATUS;
- }
-
- private boolean hasChanges() {
- if (!fProfileNameField.getText().trim().equals(fProfile.getName()))
- return true;
-
- Iterator iter= fProfile.getSettings().entrySet().iterator();
- for (;iter.hasNext();) {
- Map.Entry curr= (Map.Entry) iter.next();
- if (!fWorkingValues.get(curr.getKey()).equals(curr.getValue())) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialogTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialogTabPage.java
deleted file mode 100644
index e540b1e8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ModifyDialogTabPage.java
+++ /dev/null
@@ -1,817 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public abstract class ModifyDialogTabPage {
-
- public interface IModificationListener {
-
- void updateStatus(IStatus status);
-
- void valuesModified();
-
- }
-
- /**
- * This is the default listener for any of the Preference
- * classes. It is added by the respective factory methods and
- * updates the page's preview on each change.
- */
- protected final Observer fUpdater= new Observer() {
- public void update(Observable o, Object arg) {
- doUpdatePreview();
- notifyValuesModified();
- }
- };
-
-
- /**
- * The base class of all Preference classes. A preference class provides a wrapper
- * around one or more SWT widgets and handles the input of values for some key.
- * On each change, the new value is written to the map and the listeners are notified.
- */
- protected abstract class Preference extends Observable {
- private final Map fPreferences;
- private boolean fEnabled;
- private String fKey;
-
- /**
- * Create a new Preference.
- * @param preferences The map where the value is written.
- * @param key The key for which a value is managed.
- */
- public Preference(Map preferences, String key) {
- fPreferences= preferences;
- fEnabled= true;
- fKey= key;
- }
- /**
- * @return Gets the map of this Preference.
- */
- protected final Map getPreferences() {
- return fPreferences;
- }
-
- /**
- * Set the enabled state of all SWT widgets of this preference.
- * @param enabled new value
- */
- public final void setEnabled(boolean enabled) {
- fEnabled= enabled;
- updateWidget();
- }
-
- /**
- * @return Gets the enabled state of all SWT widgets of this Preference.
- */
- public final boolean getEnabled() {
- return fEnabled;
- }
-
- /**
- * Set the key which is used to store the value.
- * @param key New value
- */
- public final void setKey(String key) {
- if (key == null || !fKey.equals(key)) {
- fKey= key;
- updateWidget();
- }
- }
- /**
- * @return Gets the currently used key which is used to store the value.
- */
- public final String getKey() {
- return fKey;
- }
-
- /**
- * Returns the main control of a preference, which is mainly used to
- * manage the focus. This may be <code>null</code> if the preference doesn't
- * have a control which is able to have the focus.
- * @return The main control
- */
- public abstract Control getControl();
-
- /**
- * To be implemented in subclasses. Update the SWT widgets when the state
- * of this object has changed (enabled, key, ...).
- */
- protected abstract void updateWidget();
- }
-
- /**
- * Wrapper around a checkbox and a label.
- */
- protected class ButtonPreference extends Preference {
- private final String[] fValues;
- private final Button fCheckbox;
-
- /**
- * Create a new CheckboxPreference.
- * @param composite The composite on which the SWT widgets are added.
- * @param numColumns The number of columns in the composite's GridLayout.
- * @param preferences The map to store the values.
- * @param key The key to store the values.
- * @param values An array of two elements indicating the values to store on unchecked/checked.
- * @param text The label text for this Preference.
- * @param style SWT style flag for the button
- */
- public ButtonPreference(Composite composite, int numColumns,
- Map preferences, String key,
- String [] values, String text, int style) {
- super(preferences, key);
- if (values == null || text == null)
- throw new IllegalArgumentException(FormatterMessages.ModifyDialogTabPage_error_msg_values_text_unassigned);
- fValues= values;
-
- fCheckbox= new Button(composite, style);
- fCheckbox.setText(text);
- fCheckbox.setLayoutData(createGridData(numColumns, GridData.FILL_HORIZONTAL, SWT.DEFAULT));
- fCheckbox.setFont(composite.getFont());
-
- updateWidget();
-
- fCheckbox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- checkboxChecked(((Button)e.widget).getSelection());
- }
- });
- }
-
- protected void checkboxChecked(boolean state) {
- getPreferences().put(getKey(), state ? fValues[1] : fValues[0]);
- setChanged();
- notifyObservers();
- }
-
- protected void updateWidget() {
- if (getKey() != null) {
- fCheckbox.setEnabled(getEnabled());
- fCheckbox.setSelection(getChecked());
- } else {
- fCheckbox.setSelection(false);
- fCheckbox.setEnabled(false);
- }
- }
-
- public boolean getChecked() {
- return fValues[1].equals(getPreferences().get(getKey()));
- }
-
- public void setChecked(boolean checked) {
- getPreferences().put(getKey(), checked ? fValues[1] : fValues[0]);
- updateWidget();
- checkboxChecked(checked);
- }
-
- public Control getControl() {
- return fCheckbox;
- }
- }
-
- protected final class CheckboxPreference extends ButtonPreference {
- public CheckboxPreference(Composite composite, int numColumns, Map preferences, String key, String[] values, String text) {
- super(composite, numColumns, preferences, key, values, text, SWT.CHECK);
- }
- }
-
- protected final class RadioPreference extends ButtonPreference {
- public RadioPreference(Composite composite, int numColumns, Map preferences, String key, String[] values, String text) {
- super(composite, numColumns, preferences, key, values, text, SWT.RADIO);
- }
- }
-
- /**
- * Wrapper around a Combo box.
- */
- protected final class ComboPreference extends Preference {
- private final String [] fItems;
- private final String[] fValues;
- private final Combo fCombo;
-
- /**
- * Create a new ComboPreference.
- * @param composite The composite on which the SWT widgets are added.
- * @param numColumns The number of columns in the composite's GridLayout.
- * @param preferences The map to store the values.
- * @param key The key to store the values.
- * @param values An array of n elements indicating the values to store for each selection.
- * @param text The label text for this Preference.
- * @param items An array of n elements indicating the text to be written in the combo box.
- */
- public ComboPreference(Composite composite, int numColumns,
- Map preferences, String key,
- String [] values, String text, String [] items) {
- super(preferences, key);
- if (values == null || items == null || text == null)
- throw new IllegalArgumentException(FormatterMessages.ModifyDialogTabPage_error_msg_values_items_text_unassigned);
- fValues= values;
- fItems= items;
- createLabel(numColumns - 1, composite, text);
- fCombo= new Combo(composite, SWT.SINGLE | SWT.READ_ONLY);
- fCombo.setFont(composite.getFont());
- fCombo.setItems(items);
-
- int max= 0;
- for (int i= 0; i < items.length; i++)
- if (items[i].length() > max) max= items[i].length();
-
- fCombo.setLayoutData(createGridData(1, GridData.HORIZONTAL_ALIGN_FILL, fCombo.computeSize(SWT.DEFAULT, SWT.DEFAULT).x));
-
- updateWidget();
-
- fCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- comboSelected(((Combo)e.widget).getSelectionIndex());
- }
- });
- }
-
- protected void comboSelected(int index) {
- getPreferences().put(getKey(), fValues[index]);
- setChanged();
- notifyObservers(fValues[index]);
- }
-
- protected void updateWidget() {
- if (getKey() != null) {
- fCombo.setEnabled(getEnabled());
- fCombo.setText(getSelectedItem());
- } else {
- fCombo.setText(""); //$NON-NLS-1$
- fCombo.setEnabled(false);
- }
- }
-
- public String getSelectedItem() {
- final String selected= (String)getPreferences().get(getKey());
- for (int i= 0; i < fValues.length; i++) {
- if (fValues[i].equals(selected)) {
- return fItems[i];
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- public boolean hasValue(String value) {
- return value.equals(getPreferences().get(getKey()));
- }
-
- public Control getControl() {
- return fCombo;
- }
- }
-
- /**
- * Wrapper around a textfied which requests an integer input of a given range.
- */
- protected final class NumberPreference extends Preference {
-
- private final int fMinValue, fMaxValue;
- private final Label fNumberLabel;
- private final Text fNumberText;
-
- protected int fSelected;
- protected int fOldSelected;
-
-
- /**
- * Create a new NumberPreference.
- * @param composite The composite on which the SWT widgets are added.
- * @param numColumns The number of columns in the composite's GridLayout.
- * @param preferences The map to store the values.
- * @param key The key to store the values.
- * @param minValue The minimum value which is valid input.
- * @param maxValue The maximum value which is valid input.
- * @param text The label text for this Preference.
- */
- public NumberPreference(Composite composite, int numColumns,
- Map preferences, String key,
- int minValue, int maxValue, String text) {
- super(preferences, key);
-
- fNumberLabel= createLabel(numColumns - 1, composite, text, GridData.FILL_HORIZONTAL);
- fNumberText= new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
- fNumberText.setFont(composite.getFont());
-
- final int length= Integer.toString(maxValue).length() + 3;
- fNumberText.setLayoutData(createGridData(1, GridData.HORIZONTAL_ALIGN_END, fPixelConverter.convertWidthInCharsToPixels(length)));
-
- fMinValue= minValue;
- fMaxValue= maxValue;
-
- updateWidget();
-
- fNumberText.addFocusListener(new FocusListener() {
- public void focusGained(FocusEvent e) {
- NumberPreference.this.focusGained();
- }
- public void focusLost(FocusEvent e) {
- NumberPreference.this.focusLost();
- }
- });
-
- fNumberText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- fieldModified();
- }
- });
- }
-
- private IStatus createErrorStatus() {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(FormatterMessages.ModifyDialogTabPage_NumberPreference_error_invalid_value, new String [] {Integer.toString(fMinValue), Integer.toString(fMaxValue)}), null);
-
- }
-
- protected void focusGained() {
- fOldSelected= fSelected;
- fNumberText.setSelection(0, fNumberText.getCharCount());
- }
-
- protected void focusLost() {
- updateStatus(null);
- final String input= fNumberText.getText();
- if (!validInput(input))
- fSelected= fOldSelected;
- else
- fSelected= Integer.parseInt(input);
- if (fSelected != fOldSelected) {
- saveSelected();
- fNumberText.setText(Integer.toString(fSelected));
- }
- }
-
-
- protected void fieldModified() {
- final String trimInput= fNumberText.getText().trim();
- final boolean valid= validInput(trimInput);
-
- updateStatus(valid ? null : createErrorStatus());
-
- if (valid) {
- final int number= Integer.parseInt(trimInput);
- if (fSelected != number) {
- fSelected= number;
- saveSelected();
- }
- }
- }
-
- private boolean validInput(String trimInput) {
- int number;
-
- try {
- number= Integer.parseInt(trimInput);
- } catch (NumberFormatException x) {
- return false;
- }
-
- if (number < fMinValue) return false;
- if (number > fMaxValue) return false;
- return true;
- }
-
- private void saveSelected() {
- getPreferences().put(getKey(), Integer.toString(fSelected));
- setChanged();
- notifyObservers();
- }
-
- protected void updateWidget() {
- final boolean hasKey= getKey() != null;
-
- fNumberLabel.setEnabled(hasKey && getEnabled());
- fNumberText.setEnabled(hasKey && getEnabled());
-
- if (hasKey) {
- String s= (String)getPreferences().get(getKey());
- try {
- fSelected= Integer.parseInt(s);
- } catch (NumberFormatException e) {
- final String message= Messages.format(FormatterMessages.ModifyDialogTabPage_NumberPreference_error_invalid_key, getKey());
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, message, e));
- s= ""; //$NON-NLS-1$
- }
- fNumberText.setText(s);
- } else {
- fNumberText.setText(""); //$NON-NLS-1$
- }
- }
-
- public Control getControl() {
- return fNumberText;
- }
- }
-
-
- /**
- * This class provides the default way to preserve and re-establish the focus
- * over multiple modify sessions. Each ModifyDialogTabPage has its own instance,
- * and it should add all relevant controls upon creation, always in the same sequence.
- * This established a mapping of controls to indexes, which allows to restore the focus
- * in a later session.
- * The index is saved in the dialog settings, and there is only one common preference for
- * all tab pages. It is always the currently active tab page which stores its focus
- * index.
- */
- protected final static class DefaultFocusManager extends FocusAdapter {
-
- private final static String PREF_LAST_FOCUS_INDEX= JavaScriptUI.ID_PLUGIN + "formatter_page.modify_dialog_tab_page.last_focus_index"; //$NON-NLS-1$
-
- private final IDialogSettings fDialogSettings;
-
- private final Map fItemMap;
- private final List fItemList;
-
- private int fIndex;
-
- public DefaultFocusManager() {
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fItemMap= new HashMap();
- fItemList= new ArrayList();
- fIndex= 0;
- }
-
- public void focusGained(FocusEvent e) {
- fDialogSettings.put(PREF_LAST_FOCUS_INDEX, ((Integer)fItemMap.get(e.widget)).intValue());
- }
-
- public void add(Control control) {
- control.addFocusListener(this);
- fItemList.add(fIndex, control);
- fItemMap.put(control, new Integer(fIndex++));
- }
-
- public void add(Preference preference) {
- final Control control= preference.getControl();
- if (control != null)
- add(control);
- }
-
- public boolean isUsed() {
- return fIndex != 0;
- }
-
- public void restoreFocus() {
- int index= 0;
- try {
- index= fDialogSettings.getInt(PREF_LAST_FOCUS_INDEX);
- // make sure the value is within the range
- if ((index >= 0) && (index <= fItemList.size() - 1)) {
- ((Control)fItemList.get(index)).setFocus();
- }
- } catch (NumberFormatException ex) {
- // this is the first time
- }
- }
-
- public void resetFocus() {
- fDialogSettings.put(PREF_LAST_FOCUS_INDEX, -1);
- }
- }
-
- /**
- * The default focus manager. This widget knows all widgets which can have the focus
- * and listens for focusGained events, on which it stores the index of the current
- * focus holder. When the dialog is restarted, <code>restoreFocus()</code> sets the
- * focus to the last control which had it.
- *
- * The standard Preference object are managed by this focus manager if they are created
- * using the respective factory methods. Other SWT widgets can be added in subclasses
- * when they are created.
- */
- protected final DefaultFocusManager fDefaultFocusManager;
-
- /**
- * A pixel converter for layout calculations
- */
- protected PixelConverter fPixelConverter;
-
-
- /**
- * The map where the current settings are stored.
- */
- protected final Map fWorkingValues;
-
- /**
- * The modify dialog where we can display status messages.
- */
- private final IModificationListener fModifyListener;
-
-
- /*
- * Create a new <code>ModifyDialogTabPage</code>
- */
- public ModifyDialogTabPage(IModificationListener modifyListener, Map workingValues) {
- fWorkingValues= workingValues;
- fModifyListener= modifyListener;
- fDefaultFocusManager= new DefaultFocusManager();
- }
-
- /**
- * Create the contents of this tab page. Subclasses cannot override this,
- * instead they must implement <code>doCreatePreferences</code>. <code>doCreatePreview</code> may also
- * be overridden as necessary.
- * @param parent The parent composite
- * @return Created content control
- */
- public final Composite createContents(Composite parent) {
- final int numColumns= 4;
-
- if (fPixelConverter == null) {
- fPixelConverter= new PixelConverter(parent);
- }
-
- final SashForm fSashForm = new SashForm(parent, SWT.HORIZONTAL);
- fSashForm.setFont(parent.getFont());
-
- final Composite settingsPane= new Composite(fSashForm, SWT.NONE);
- settingsPane.setFont(fSashForm.getFont());
-
- final GridLayout layout= new GridLayout(numColumns, false);
- layout.verticalSpacing= (int)(1.5 * fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING));
- layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- settingsPane.setLayout(layout);
- doCreatePreferences(settingsPane, numColumns);
-
- final Composite previewPane= new Composite(fSashForm, SWT.NONE);
- previewPane.setLayout(createGridLayout(numColumns, true));
- previewPane.setFont(fSashForm.getFont());
- doCreatePreviewPane(previewPane, numColumns);
-
- initializePage();
-
- fSashForm.setWeights(new int [] {3, 3});
- return fSashForm;
- }
-
- /**
- * This method is called after all controls have been alloated, including the preview.
- * It can be used to set the preview text and to create listeners.
- *
- */
- protected abstract void initializePage();
-
-
- /**
- * Create the left side of the modify dialog. This is meant to be implemented by subclasses.
- * @param composite Composite to create in
- * @param numColumns Number of columns to use
- */
- protected abstract void doCreatePreferences(Composite composite, int numColumns);
-
-
- /**
- * Create the right side of the modify dialog. By default, the preview is displayed there.
- * Subclasses can override this method in order to customize the right-hand side of the
- * dialog.
- * @param composite Composite to create in
- * @param numColumns Number of columns to use
- * @return Created composite
- */
- protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
-
- createLabel(numColumns, composite, FormatterMessages.ModifyDialogTabPage_preview_label_text);
-
- final JavaPreview preview= doCreateJavaPreview(composite);
- fDefaultFocusManager.add(preview.getControl());
-
- final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, 0);
- gd.widthHint= 0;
- gd.heightHint=0;
- preview.getControl().setLayoutData(gd);
-
- return composite;
- }
-
-
- /**
- * To be implemented by subclasses. This method should return an instance of JavaPreview.
- * Currently, the choice is between CompilationUnitPreview which contains a valid compilation
- * unit, or a SnippetPreview which formats several independent code snippets and displays them
- * in the same window.
- * @param parent Parent composite
- * @return Created preview
- */
- protected abstract JavaPreview doCreateJavaPreview(Composite parent);
-
-
- /**
- * This is called when the page becomes visible.
- * Common tasks to do include:
- * <ul><li>Updating the preview.</li>
- * <li>Setting the focus</li>
- * </ul>
- */
- final public void makeVisible() {
- fDefaultFocusManager.resetFocus();
- doUpdatePreview();
- }
-
- /**
- * Update the preview. To be implemented by subclasses.
- */
- protected abstract void doUpdatePreview();
-
- protected void notifyValuesModified() {
- fModifyListener.valuesModified();
- }
- /**
- * Each tab page should remember where its last focus was, and reset it
- * correctly within this method. This method is only called after
- * initialization on the first tab page to be displayed in order to restore
- * the focus of the last session.
- */
- public void setInitialFocus() {
- if (fDefaultFocusManager.isUsed()) {
- fDefaultFocusManager.restoreFocus();
- }
- }
-
-
- /**
- * Set the status field on the dialog. This can be used by tab pages to report
- * inconsistent input. The OK button is disabled if the kind is IStatus.ERROR.
- * @param status Status describing the current page error state
- */
- protected void updateStatus(IStatus status) {
- fModifyListener.updateStatus(status);
- }
-
- /*
- * Factory methods to make GUI construction easier
- */
-
- /*
- * Create a GridLayout with the default margin and spacing settings, as
- * well as the specified number of columns.
- */
- protected GridLayout createGridLayout(int numColumns, boolean margins) {
- final GridLayout layout= new GridLayout(numColumns, false);
- layout.verticalSpacing= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- if (margins) {
- layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- } else {
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- }
- return layout;
- }
-
- /*
- * Convenience method to create a GridData.
- */
- protected static GridData createGridData(int numColumns, int style, int widthHint) {
- final GridData gd= new GridData(style);
- gd.horizontalSpan= numColumns;
- gd.widthHint= widthHint;
- return gd;
- }
-
-
- /*
- * Convenience method to create a label.
- */
- protected static Label createLabel(int numColumns, Composite parent, String text) {
- return createLabel(numColumns, parent, text, GridData.FILL_HORIZONTAL);
- }
-
- /*
- * Convenience method to create a label
- */
- protected static Label createLabel(int numColumns, Composite parent, String text, int gridDataStyle) {
- final Label label= new Label(parent, SWT.WRAP);
- label.setFont(parent.getFont());
- label.setText(text);
-
- PixelConverter pixelConverter= new PixelConverter(parent);
- label.setLayoutData(createGridData(numColumns, gridDataStyle, pixelConverter.convertHorizontalDLUsToPixels(150)));
- return label;
- }
-
- /*
- * Convenience method to create a group
- */
- protected Group createGroup(int numColumns, Composite parent, String text ) {
- final Group group= new Group(parent, SWT.NONE);
- group.setFont(parent.getFont());
- group.setLayoutData(createGridData(numColumns, GridData.FILL_HORIZONTAL, SWT.DEFAULT));
-
- final GridLayout layout= new GridLayout(numColumns, false);
- layout.verticalSpacing= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
-
- //layout.marginHeight= fPixelConverter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- //layout.marginWidth= fPixelConverter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
-
- group.setLayout(layout);//createGridLayout(numColumns, true));
- group.setText(text);
- return group;
- }
-
-
- /*
- * Convenience method to create a NumberPreference. The widget is registered as
- * a potential focus holder, and the default updater is added.
- */
- protected NumberPreference createNumberPref(Composite composite, int numColumns, String name, String key,
- int minValue, int maxValue) {
- final NumberPreference pref= new NumberPreference(composite, numColumns, fWorkingValues,
- key, minValue, maxValue, name);
- fDefaultFocusManager.add(pref);
- pref.addObserver(fUpdater);
- return pref;
- }
-
- /*
- * Convenience method to create a ComboPreference. The widget is registered as
- * a potential focus holder, and the default updater is added.
- */
- protected ComboPreference createComboPref(Composite composite, int numColumns, String name,
- String key, String [] values, String [] items) {
- final ComboPreference pref= new ComboPreference(composite, numColumns,
- fWorkingValues, key, values, name, items);
- fDefaultFocusManager.add(pref);
- pref.addObserver(fUpdater);
- return pref;
- }
-
- /*
- * Convenience method to create a CheckboxPreference. The widget is registered as
- * a potential focus holder, and the default updater is added.
- */
- protected CheckboxPreference createCheckboxPref(Composite composite, int numColumns, String name, String key,
- String [] values) {
- final CheckboxPreference pref= new CheckboxPreference(composite, numColumns,
- fWorkingValues, key, values, name);
- fDefaultFocusManager.add(pref);
- pref.addObserver(fUpdater);
- return pref;
- }
-
- protected RadioPreference createRadioPref(Composite composite, int numColumns, String name, String key,
- String [] values) {
- final RadioPreference pref= new RadioPreference(composite, numColumns,
- fWorkingValues, key, values, name);
- fDefaultFocusManager.add(pref);
- pref.addObserver(fUpdater);
- return pref;
- }
-
-
- /*
- * Create a nice javadoc comment for some string.
- */
- protected static String createPreviewHeader(String title) {
- return "/**\n* " + title + "\n*/\n"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/NewLinesTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/NewLinesTabPage.java
deleted file mode 100644
index 78f88cc3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/NewLinesTabPage.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Map;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-
-
-public class NewLinesTabPage extends FormatterTabPage {
-
- /**
- * Constant array for boolean selection
- */
- private static String[] FALSE_TRUE = {
- DefaultCodeFormatterConstants.FALSE,
- DefaultCodeFormatterConstants.TRUE
- };
-
- /**
- * Constant array for insert / not_insert.
- */
- private static String[] DO_NOT_INSERT_INSERT = {
- JavaScriptCore.DO_NOT_INSERT,
- JavaScriptCore.INSERT
- };
-
-
- private final String PREVIEW=
- createPreviewHeader(FormatterMessages.NewLinesTabPage_preview_header) +
- "var someData;\n" + //$NON-NLS-1$
- "var someMoreData = 5;\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- "function foo(data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " var abc = 1;\n" + //$NON-NLS-1$
- " var xyz = 'one';\n" + //$NON-NLS-1$
- " var arr1 = ['123',function() {return 5},'abc'];\n" + //$NON-NLS-1$
- " var obj1 = { make: 'Ford', model: 'Thunderbird', year: 1967 };\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " if (data>5) {\n" + //$NON-NLS-1$
- " data = 5;\n" + //$NON-NLS-1$
- " } else {\n" + //$NON-NLS-1$
- " data--;\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " switch (data) {\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " case 0:\n" + //$NON-NLS-1$
- " abc = 0;\n" + //$NON-NLS-1$
- " xyz = 'zero';\n" + //$NON-NLS-1$
- " break;\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " default:\n" + //$NON-NLS-1$
- " abc = -1;\n" + //$NON-NLS-1$
- " xyz = 'unknown';\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "\n" + //$NON-NLS-1$
- "}"; //$NON-NLS-1$
-
-
-
- protected CheckboxPreference fThenStatementPref, fSimpleIfPref;
-
- private CompilationUnitPreview fPreview;
-
- public NewLinesTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
-
- final Group newlinesGroup= createGroup(numColumns, composite, FormatterMessages.NewLinesTabPage_newlines_group_title);
-// createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_class_body, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION, DO_NOT_INSERT_INSERT);
-// createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_anonymous_class_body, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION, DO_NOT_INSERT_INSERT);
- createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_method_body, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY, DO_NOT_INSERT_INSERT);
- createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_block, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK, DO_NOT_INSERT_INSERT);
-// createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPa/ge_newlines_group_option_empty_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_DECLARATION, DO_NOT_INSERT_INSERT);
-// createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_enum_constant, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ENUM_CONSTANT, DO_NOT_INSERT_INSERT);
-// createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_annotation_decl_body, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANNOTATION_DECLARATION, DO_NOT_INSERT_INSERT);
- createPref(newlinesGroup, numColumns, FormatterMessages.NewLinesTabPage_newlines_group_option_empty_end_of_file, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AT_END_OF_FILE_IF_MISSING, DO_NOT_INSERT_INSERT);
-
- final Group objectInitializerGroup= createGroup(numColumns, composite, FormatterMessages.NewLinesTabPage_objectInitializer_group_title);
- createPref(objectInitializerGroup, numColumns, FormatterMessages.NewLinesTabPage_object_group_option_after_opening_brace_of_object_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_OBJLIT_INITIALIZER, DO_NOT_INSERT_INSERT);
- createPref(objectInitializerGroup, numColumns, FormatterMessages.NewLinesTabPage_object_group_option_before_closing_brace_of_object_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_OBJLIT_INITIALIZER, DO_NOT_INSERT_INSERT);
- createPref(objectInitializerGroup, numColumns, FormatterMessages.NewLinesTabPage_object_group_option_after_comma_in_object_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_COMMA_IN_OBJLIT_INITIALIZER, DO_NOT_INSERT_INSERT);
-
- final Group arrayInitializerGroup= createGroup(numColumns, composite, FormatterMessages.NewLinesTabPage_arrayInitializer_group_title);
- createPref(arrayInitializerGroup, numColumns, FormatterMessages.NewLinesTabPage_array_group_option_after_opening_brace_of_array_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, DO_NOT_INSERT_INSERT);
- createPref(arrayInitializerGroup, numColumns, FormatterMessages.NewLinesTabPage_array_group_option_before_closing_brace_of_array_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER, DO_NOT_INSERT_INSERT);
-
- final Group emptyStatementsGroup= createGroup(numColumns, composite, FormatterMessages.NewLinesTabPage_empty_statement_group_title);
- createPref(emptyStatementsGroup, numColumns, FormatterMessages.NewLinesTabPage_emtpy_statement_group_option_empty_statement_on_new_line, DefaultCodeFormatterConstants.FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE, FALSE_TRUE);
-
-// final Group annotationsGroup= createGroup(numColumns, composite, FormatterMessages.NewLinesTabPage_annotations_group_title);
-// createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_option_after_annotation, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION, DO_NOT_INSERT_INSERT);
-
- }
-
- protected void initializePage() {
- fPreview.setPreviewText(PREVIEW);
- }
-
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new CompilationUnitPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-
- private CheckboxPreference createPref(Composite composite, int numColumns, String message, String key, String[] values) {
- return createCheckboxPref(composite, numColumns, message, key, values);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileConfigurationBlock.java
deleted file mode 100644
index df47a709..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileConfigurationBlock.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesMessages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.osgi.service.prefs.BackingStoreException;
-
-public abstract class ProfileConfigurationBlock {
-
- private class StoreUpdater implements Observer {
-
- public StoreUpdater() {
- fProfileManager.addObserver(this);
- }
-
- public void update(Observable o, Object arg) {
- try {
- fPreferenceListenerEnabled= false;
- final int value= ((Integer)arg).intValue();
- switch (value) {
- case ProfileManager.PROFILE_DELETED_EVENT:
- case ProfileManager.PROFILE_RENAMED_EVENT:
- case ProfileManager.PROFILE_CREATED_EVENT:
- case ProfileManager.SETTINGS_CHANGED_EVENT:
- try {
- fProfileStore.writeProfiles(fProfileManager.getSortedProfiles(), fInstanceScope); // update profile store
- fProfileManager.commitChanges(fCurrContext);
- } catch (CoreException x) {
- JavaScriptPlugin.log(x);
- }
- break;
- case ProfileManager.SELECTION_CHANGED_EVENT:
- fProfileManager.commitChanges(fCurrContext);
- break;
- }
- } finally {
- fPreferenceListenerEnabled= true;
- }
- }
- }
-
- class ProfileComboController implements Observer, SelectionListener {
-
- private final List fSortedProfiles;
-
- public ProfileComboController() {
- fSortedProfiles= fProfileManager.getSortedProfiles();
- fProfileCombo.addSelectionListener(this);
- fProfileManager.addObserver(this);
- updateProfiles();
- updateSelection();
- }
-
- public void widgetSelected(SelectionEvent e) {
- final int index= fProfileCombo.getSelectionIndex();
- fProfileManager.setSelected((Profile)fSortedProfiles.get(index));
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {}
-
- public void update(Observable o, Object arg) {
- if (arg == null) return;
- final int value= ((Integer)arg).intValue();
- switch (value) {
- case ProfileManager.PROFILE_CREATED_EVENT:
- case ProfileManager.PROFILE_DELETED_EVENT:
- case ProfileManager.PROFILE_RENAMED_EVENT:
- updateProfiles();
- updateSelection();
- break;
- case ProfileManager.SELECTION_CHANGED_EVENT:
- updateSelection();
- break;
- }
- }
-
- private void updateProfiles() {
- fProfileCombo.setItems(fProfileManager.getSortedDisplayNames());
- }
-
- private void updateSelection() {
- fProfileCombo.setText(fProfileManager.getSelected().getName());
- }
- }
-
- class ButtonController implements Observer, SelectionListener {
-
- public ButtonController() {
- fProfileManager.addObserver(this);
- fNewButton.addSelectionListener(this);
- fEditButton.addSelectionListener(this);
- fDeleteButton.addSelectionListener(this);
- fLoadButton.addSelectionListener(this);
- update(fProfileManager, null);
- }
-
- public void update(Observable o, Object arg) {
- Profile selected= ((ProfileManager)o).getSelected();
- final boolean notBuiltIn= !selected.isBuiltInProfile();
- fDeleteButton.setEnabled(notBuiltIn);
- }
-
- public void widgetSelected(SelectionEvent e) {
- final Button button= (Button)e.widget;
- if (button == fEditButton)
- modifyButtonPressed();
- else if (button == fDeleteButton)
- deleteButtonPressed();
- else if (button == fNewButton)
- newButtonPressed();
- else if (button == fLoadButton)
- loadButtonPressed();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- private void modifyButtonPressed() {
- final StatusDialog modifyDialog= createModifyDialog(fComposite.getShell(), fProfileManager.getSelected(), fProfileManager, fProfileStore, false);
- modifyDialog.open();
- }
-
- private void deleteButtonPressed() {
- if (MessageDialog.openQuestion(
- fComposite.getShell(),
- FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_title,
- Messages.format(FormatterMessages.CodingStyleConfigurationBlock_delete_confirmation_question, fProfileManager.getSelected().getName()))) {
- fProfileManager.deleteSelected();
- }
- }
-
- private void newButtonPressed() {
- final CreateProfileDialog p= new CreateProfileDialog(fComposite.getShell(), fProfileManager, fProfileVersioner);
- if (p.open() != Window.OK)
- return;
- if (!p.openEditDialog())
- return;
- final StatusDialog modifyDialog= createModifyDialog(fComposite.getShell(), p.getCreatedProfile(), fProfileManager, fProfileStore, true);
- modifyDialog.open();
- }
-
- private void loadButtonPressed() {
- final FileDialog dialog= new FileDialog(fComposite.getShell(), SWT.OPEN);
- dialog.setText(FormatterMessages.CodingStyleConfigurationBlock_load_profile_dialog_title);
- dialog.setFilterExtensions(new String [] {"*.xml"}); //$NON-NLS-1$
- final String lastPath= JavaScriptPlugin.getDefault().getDialogSettings().get(fLastSaveLoadPathKey + ".loadpath"); //$NON-NLS-1$
- if (lastPath != null) {
- dialog.setFilterPath(lastPath);
- }
- final String path= dialog.open();
- if (path == null)
- return;
- JavaScriptPlugin.getDefault().getDialogSettings().put(fLastSaveLoadPathKey + ".loadpath", dialog.getFilterPath()); //$NON-NLS-1$
-
- final File file= new File(path);
- Collection profiles= null;
- try {
- profiles= fProfileStore.readProfilesFromFile(file);
- } catch (CoreException e) {
- final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
- final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_message;
- ExceptionHandler.handle(e, fComposite.getShell(), title, message);
- }
- if (profiles == null || profiles.isEmpty())
- return;
-
- final CustomProfile profile= (CustomProfile)profiles.iterator().next();
-
- if (!fProfileVersioner.getProfileKind().equals(profile.getKind())) {
- final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_title;
- final String message= Messages.format(FormatterMessages.ProfileConfigurationBlock_load_profile_wrong_profile_message, new String[] {fProfileVersioner.getProfileKind(), profile.getKind()});
- MessageDialog.openError(fComposite.getShell(), title, message);
- return;
- }
-
- if (profile.getVersion() > fProfileVersioner.getCurrentVersion()) {
- final String title= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_title;
- final String message= FormatterMessages.CodingStyleConfigurationBlock_load_profile_error_too_new_message;
- MessageDialog.openWarning(fComposite.getShell(), title, message);
- }
-
- if (fProfileManager.containsName(profile.getName())) {
- final AlreadyExistsDialog aeDialog= new AlreadyExistsDialog(fComposite.getShell(), profile, fProfileManager);
- if (aeDialog.open() != Window.OK)
- return;
- }
- fProfileVersioner.update(profile);
- fProfileManager.addProfile(profile);
- }
- }
-
- /**
- * The GUI controls
- */
- private Composite fComposite;
- private Combo fProfileCombo;
- private Button fEditButton;
- private Button fDeleteButton;
- private Button fNewButton;
- private Button fLoadButton;
-
- private PixelConverter fPixConv;
- /**
- * The ProfileManager, the model of this page.
- */
- private final ProfileManager fProfileManager;
- private final IScopeContext fCurrContext;
- private final IScopeContext fInstanceScope;
- private final ProfileStore fProfileStore;
- private final IProfileVersioner fProfileVersioner;
- private final String fLastSaveLoadPathKey;
- private IPreferenceChangeListener fPreferenceListener;
- private final PreferencesAccess fPreferenceAccess;
- private boolean fPreferenceListenerEnabled;
-
- public ProfileConfigurationBlock(IProject project, final PreferencesAccess access, String lastSaveLoadPathKey) {
-
- fPreferenceAccess= access;
- fLastSaveLoadPathKey= lastSaveLoadPathKey;
-
- fProfileVersioner= createProfileVersioner();
- fProfileStore= createProfileStore(fProfileVersioner);
- fInstanceScope= access.getInstanceScope();
- if (project != null) {
- fCurrContext= access.getProjectScope(project);
- } else {
- fCurrContext= fInstanceScope;
- }
-
- List profiles= null;
- try {
- profiles= fProfileStore.readProfiles(fInstanceScope);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- if (profiles == null) {
- try {
- // bug 129427
- profiles= fProfileStore.readProfiles(new DefaultScope());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- if (profiles == null)
- profiles= new ArrayList();
-
- fProfileManager= createProfileManager(profiles, fCurrContext, access, fProfileVersioner);
-
- new StoreUpdater();
-
- fPreferenceListenerEnabled= true;
- fPreferenceListener= new IPreferenceChangeListener() {
- public void preferenceChange(PreferenceChangeEvent event) {
- if (fPreferenceListenerEnabled) {
- preferenceChanged(event);
- }
- }
- };
- access.getInstanceScope().getNode(JavaScriptUI.ID_PLUGIN).addPreferenceChangeListener(fPreferenceListener);
-
- }
-
- protected void preferenceChanged(PreferenceChangeEvent event) {
-
- }
-
- protected abstract IProfileVersioner createProfileVersioner();
-
- protected abstract ProfileStore createProfileStore(IProfileVersioner versioner);
-
- protected abstract ProfileManager createProfileManager(List profiles, IScopeContext context, PreferencesAccess access, IProfileVersioner profileVersioner);
-
- protected abstract ModifyDialog createModifyDialog(Shell shell, Profile profile, ProfileManager profileManager, ProfileStore profileStore, boolean newProfile);
-
- protected abstract void configurePreview(Composite composite, int numColumns, ProfileManager profileManager);
-
- private static Button createButton(Composite composite, String text, final int style) {
- final Button button= new Button(composite, SWT.PUSH);
- button.setFont(composite.getFont());
- button.setText(text);
-
- final GridData gd= new GridData(style);
- gd.widthHint= SWTUtil.getButtonWidthHint(button);
- button.setLayoutData(gd);
- return button;
- }
-
- /**
- * Create the contents
- * @param parent Parent composite
- * @return Created control
- */
- public Composite createContents(Composite parent) {
-
- final int numColumns = 5;
-
- fPixConv = new PixelConverter(parent);
- fComposite = createComposite(parent, numColumns);
-
- Label profileLabel= new Label(fComposite, SWT.NONE);
- profileLabel.setText(PreferencesMessages.CleanUpPreferencePage_Description);
- GridData data= new GridData(SWT.FILL, SWT.FILL, true, false);
- data.horizontalSpan= numColumns;
- profileLabel.setLayoutData(data);
-
- fProfileCombo= createProfileCombo(fComposite, 3, fPixConv.convertWidthInCharsToPixels(20));
- fEditButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_edit_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
- fDeleteButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_remove_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
-
- fNewButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_new_button_desc, GridData.HORIZONTAL_ALIGN_BEGINNING);
- fLoadButton= createButton(fComposite, FormatterMessages.CodingStyleConfigurationBlock_load_button_desc, GridData.HORIZONTAL_ALIGN_END);
- createLabel(fComposite, "", 3); //$NON-NLS-1$
-
- configurePreview(fComposite, numColumns, fProfileManager);
-
- new ButtonController();
- new ProfileComboController();
-
- return fComposite;
- }
-
- private static Combo createProfileCombo(Composite composite, int span, int widthHint) {
- final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = span;
- gd.widthHint= widthHint;
-
- final Combo combo= new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY );
- combo.setFont(composite.getFont());
- combo.setLayoutData(gd);
- return combo;
- }
-
- protected static Label createLabel(Composite composite, String text, int numColumns) {
- final GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan = numColumns;
- gd.widthHint= 0;
-
- final Label label = new Label(composite, SWT.WRAP);
- label.setFont(composite.getFont());
- label.setText(text);
- label.setLayoutData(gd);
- return label;
- }
-
- private Composite createComposite(Composite parent, int numColumns) {
- final Composite composite = new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- final GridLayout layout = new GridLayout(numColumns, false);
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- composite.setLayout(layout);
- return composite;
- }
-
- public final boolean hasProjectSpecificOptions(IProject project) {
- if (project != null) {
- return fProfileManager.hasProjectSpecificSettings(new ProjectScope(project));
- }
- return false;
- }
-
- public boolean performOk() {
- return true;
- }
-
- public void performApply() {
- try {
- fCurrContext.getNode(JavaScriptUI.ID_PLUGIN).flush();
- fCurrContext.getNode(JavaScriptCore.PLUGIN_ID).flush();
- if (fCurrContext != fInstanceScope) {
- fInstanceScope.getNode(JavaScriptUI.ID_PLUGIN).flush();
- fInstanceScope.getNode(JavaScriptCore.PLUGIN_ID).flush();
- }
- } catch (BackingStoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- public void performDefaults() {
- Profile profile= fProfileManager.getDefaultProfile();
- if (profile != null) {
- int defaultIndex= fProfileManager.getSortedProfiles().indexOf(profile);
- if (defaultIndex != -1) {
- fProfileManager.setSelected(profile);
- }
- }
- }
-
- public void dispose() {
- if (fPreferenceListener != null) {
- fPreferenceAccess.getInstanceScope().getNode(JavaScriptUI.ID_PLUGIN).removePreferenceChangeListener(fPreferenceListener);
- fPreferenceListener= null;
- }
- }
-
- public void enableProjectSpecificSettings(boolean useProjectSpecificSettings) {
- if (useProjectSpecificSettings) {
- fProfileManager.commitChanges(fCurrContext);
- } else {
- fProfileManager.clearAllSettings(fCurrContext);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileManager.java
deleted file mode 100644
index 9053cb46..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileManager.java
+++ /dev/null
@@ -1,795 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Observable;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.PreferencesAccess;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.osgi.service.prefs.BackingStoreException;
-
-/**
- * The model for the set of profiles which are available in the workbench.
- */
-public abstract class ProfileManager extends Observable {
-
- public static final class KeySet {
-
- private final List fKeys;
- private final String fNodeName;
-
- public KeySet(String nodeName, List keys) {
- fNodeName= nodeName;
- fKeys= keys;
- }
-
- public String getNodeName() {
- return fNodeName;
- }
-
- public List getKeys() {
- return fKeys;
- }
- }
-
- /**
- * A prefix which is prepended to every ID of a user-defined profile, in order
- * to differentiate it from a built-in profile.
- */
- public final static String ID_PREFIX= "_"; //$NON-NLS-1$
-
- /**
- * Represents a profile with a unique ID, a name and a map
- * containing the code formatter settings.
- */
- public static abstract class Profile implements Comparable {
-
- public abstract String getName();
- public abstract Profile rename(String name, ProfileManager manager);
-
- public abstract Map getSettings();
- public abstract void setSettings(Map settings);
-
- public abstract int getVersion();
-
- public boolean hasEqualSettings(Map otherMap, List allKeys) {
- Map settings= getSettings();
- for (Iterator iter= allKeys.iterator(); iter.hasNext(); ){
- String key= (String) iter.next();
- Object other= otherMap.get(key);
- Object curr= settings.get(key);
- if (other == null) {
- if (curr != null) {
- return false;
- }
- } else if (!other.equals(curr)) {
- return false;
- }
- }
- return true;
- }
-
- public abstract boolean isProfileToSave();
-
- public abstract String getID();
-
- public boolean isSharedProfile() {
- return false;
- }
-
- public boolean isBuiltInProfile() {
- return false;
- }
- }
-
- /**
- * Represents a built-in profile. The state of a built-in profile
- * cannot be changed after instantiation.
- */
- public static final class BuiltInProfile extends Profile {
- private final String fName;
- private final String fID;
- private final Map fSettings;
- private final int fOrder;
- private final int fCurrentVersion;
- private final String fProfileKind;
-
- public BuiltInProfile(String ID, String name, Map settings, int order, int currentVersion, String profileKind) {
- fName= name;
- fID= ID;
- fSettings= settings;
- fOrder= order;
- fCurrentVersion= currentVersion;
- fProfileKind= profileKind;
- }
-
- public String getName() {
- return fName;
- }
-
- public Profile rename(String name, ProfileManager manager) {
- final String trimmed= name.trim();
- CustomProfile newProfile= new CustomProfile(trimmed, fSettings, fCurrentVersion, fProfileKind);
- manager.addProfile(newProfile);
- return newProfile;
- }
-
- public Map getSettings() {
- return fSettings;
- }
-
- public void setSettings(Map settings) {
- }
-
- public String getID() {
- return fID;
- }
-
- public final int compareTo(Object o) {
- if (o instanceof BuiltInProfile) {
- return fOrder - ((BuiltInProfile)o).fOrder;
- }
- return -1;
- }
-
- public boolean isProfileToSave() {
- return false;
- }
-
- public boolean isBuiltInProfile() {
- return true;
- }
-
- public int getVersion() {
- return fCurrentVersion;
- }
-
- }
-
- /**
- * Represents a user-defined profile. A custom profile can be modified after instantiation.
- */
- public static class CustomProfile extends Profile {
- private String fName;
- private Map fSettings;
- protected ProfileManager fManager;
- private int fVersion;
- private final String fKind;
-
- public CustomProfile(String name, Map settings, int version, String kind) {
- fName= name;
- fSettings= settings;
- fVersion= version;
- fKind= kind;
- }
-
- public String getName() {
- return fName;
- }
-
- public Profile rename(String name, ProfileManager manager) {
- final String trimmed= name.trim();
- if (trimmed.equals(getName()))
- return this;
-
- String oldID= getID(); // remember old id before changing name
- fName= trimmed;
-
- manager.profileRenamed(this, oldID);
- return this;
- }
-
- public Map getSettings() {
- return fSettings;
- }
-
- public void setSettings(Map settings) {
- if (settings == null)
- throw new IllegalArgumentException();
- fSettings= settings;
- if (fManager != null) {
- fManager.profileChanged(this);
- }
- }
-
- public String getID() {
- return ID_PREFIX + fName;
- }
-
- public void setManager(ProfileManager profileManager) {
- fManager= profileManager;
- }
-
- public ProfileManager getManager() {
- return fManager;
- }
-
- public int getVersion() {
- return fVersion;
- }
-
- public void setVersion(int version) {
- fVersion= version;
- }
-
- public int compareTo(Object o) {
- if (o instanceof SharedProfile) {
- return -1;
- }
- if (o instanceof CustomProfile) {
- return getName().compareToIgnoreCase(((Profile)o).getName());
- }
- return 1;
- }
-
- public boolean isProfileToSave() {
- return true;
- }
-
- public String getKind() {
- return fKind;
- }
-
- }
-
- public final class SharedProfile extends CustomProfile {
-
- public SharedProfile(String oldName, Map options, int version, String profileKind) {
- super(oldName, options, version, profileKind);
- }
-
- public Profile rename(String name, ProfileManager manager) {
- CustomProfile profile= new CustomProfile(name.trim(), getSettings(), getVersion(), getKind());
-
- manager.profileReplaced(this, profile);
- return profile;
- }
-
- public String getID() {
- return SHARED_PROFILE;
- }
-
- public final int compareTo(Object o) {
- return 1;
- }
-
- public boolean isProfileToSave() {
- return false;
- }
-
- public boolean isSharedProfile() {
- return true;
- }
- }
-
-
- /**
- * The possible events for observers listening to this class.
- */
- public final static int SELECTION_CHANGED_EVENT= 1;
- public final static int PROFILE_DELETED_EVENT= 2;
- public final static int PROFILE_RENAMED_EVENT= 3;
- public final static int PROFILE_CREATED_EVENT= 4;
- public final static int SETTINGS_CHANGED_EVENT= 5;
-
-
- /**
- * The key of the preference where the selected profile is stored.
- */
- private final String fProfileKey;
-
- /**
- * The key of the preference where the version of the current settings is stored
- */
- private final String fProfileVersionKey;
-
-
- private final static String SHARED_PROFILE= "org.eclipse.wst.jsdt.ui.default.shared"; //$NON-NLS-1$
-
-
- /**
- * A map containing the available profiles, using the IDs as keys.
- */
- private final Map fProfiles;
-
- /**
- * The available profiles, sorted by name.
- */
- private final List fProfilesByName;
-
-
- /**
- * The currently selected profile.
- */
- private Profile fSelected;
-
-
- /**
- * The keys of the options to be saved with each profile
- */
- private final KeySet[] fKeySets;
-
- private final PreferencesAccess fPreferencesAccess;
- private final IProfileVersioner fProfileVersioner;
-
- /**
- * Create and initialize a new profile manager.
- * @param profiles Initial custom profiles (List of type <code>CustomProfile</code>)
- * @param profileVersioner
- */
- public ProfileManager(
- List profiles,
- IScopeContext context,
- PreferencesAccess preferencesAccess,
- IProfileVersioner profileVersioner,
- KeySet[] keySets,
- String profileKey,
- String profileVersionKey) {
-
- fPreferencesAccess= preferencesAccess;
- fProfileVersioner= profileVersioner;
- fKeySets= keySets;
- fProfileKey= profileKey;
- fProfileVersionKey= profileVersionKey;
-
- fProfiles= new HashMap();
- fProfilesByName= new ArrayList();
-
- for (final Iterator iter = profiles.iterator(); iter.hasNext();) {
- final Profile profile= (Profile) iter.next();
- if (profile instanceof CustomProfile) {
- ((CustomProfile)profile).setManager(this);
- }
- fProfiles.put(profile.getID(), profile);
- fProfilesByName.add(profile);
- }
-
- Collections.sort(fProfilesByName);
-
- String profileId= getSelectedProfileId(fPreferencesAccess.getInstanceScope());
-
- Profile profile= (Profile) fProfiles.get(profileId);
- if (profile == null) {
- profile= getDefaultProfile();
- }
- fSelected= profile;
-
- if (context.getName() == ProjectScope.SCOPE && hasProjectSpecificSettings(context)) {
- Map map= readFromPreferenceStore(context, profile);
- if (map != null) {
-
- List allKeys= new ArrayList();
- for (int i= 0; i < fKeySets.length; i++) {
- allKeys.addAll(fKeySets[i].getKeys());
- }
- Collections.sort(allKeys);
-
- Profile matching= null;
-
- String projProfileId= context.getNode(JavaScriptUI.ID_PLUGIN).get(fProfileKey, null);
- if (projProfileId != null) {
- Profile curr= (Profile) fProfiles.get(projProfileId);
- if (curr != null && (curr.isBuiltInProfile() || curr.hasEqualSettings(map, allKeys))) {
- matching= curr;
- }
- } else {
- // old version: look for similar
- for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
- Profile curr= (Profile) iter.next();
- if (curr.hasEqualSettings(map, allKeys)) {
- matching= curr;
- break;
- }
- }
- }
- if (matching == null) {
- String name;
- if (projProfileId != null && !fProfiles.containsKey(projProfileId)) {
- name= Messages.format(FormatterMessages.ProfileManager_unmanaged_profile_with_name, projProfileId.substring(ID_PREFIX.length()));
- } else {
- name= FormatterMessages.ProfileManager_unmanaged_profile;
- }
- // current settings do not correspond to any profile -> create a 'team' profile
- SharedProfile shared= new SharedProfile(name, map, fProfileVersioner.getCurrentVersion(), fProfileVersioner.getProfileKind());
- shared.setManager(this);
- fProfiles.put(shared.getID(), shared);
- fProfilesByName.add(shared); // add last
- matching= shared;
- }
- fSelected= matching;
- }
- }
- }
-
- protected String getSelectedProfileId(IScopeContext instanceScope) {
- String profileId= instanceScope.getNode(JavaScriptUI.ID_PLUGIN).get(fProfileKey, null);
- if (profileId == null) {
- // request from bug 129427
- profileId= new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).get(fProfileKey, null);
- }
- return profileId;
- }
-
- /**
- * Notify observers with a message. The message must be one of the following:
- * @param message Message to send out
- *
- * @see #SELECTION_CHANGED_EVENT
- * @see #PROFILE_DELETED_EVENT
- * @see #PROFILE_RENAMED_EVENT
- * @see #PROFILE_CREATED_EVENT
- * @see #SETTINGS_CHANGED_EVENT
- */
- protected void notifyObservers(int message) {
- setChanged();
- notifyObservers(new Integer(message));
- }
-
- public static boolean hasProjectSpecificSettings(IScopeContext context, KeySet[] keySets) {
- for (int i= 0; i < keySets.length; i++) {
- KeySet keySet= keySets[i];
- IEclipsePreferences preferences= context.getNode(keySet.getNodeName());
- for (final Iterator keyIter= keySet.getKeys().iterator(); keyIter.hasNext();) {
- final String key= (String)keyIter.next();
- Object val= preferences.get(key, null);
- if (val != null) {
- return true;
- }
- }
- }
- return false;
- }
-
- public boolean hasProjectSpecificSettings(IScopeContext context) {
- return hasProjectSpecificSettings(context, fKeySets);
- }
-
- /**
- * Only to read project specific settings to find out to what profile it matches.
- * @param context The project context
- */
- private Map readFromPreferenceStore(IScopeContext context, Profile workspaceProfile) {
- final Map profileOptions= new HashMap();
- IEclipsePreferences uiPrefs= context.getNode(JavaScriptUI.ID_PLUGIN);
-
- int version= uiPrefs.getInt(fProfileVersionKey, fProfileVersioner.getFirstVersion());
- if (version != fProfileVersioner.getCurrentVersion()) {
- Map allOptions= new HashMap();
- for (int i= 0; i < fKeySets.length; i++) {
- addAll(context.getNode(fKeySets[i].getNodeName()), allOptions);
- }
- CustomProfile profile= new CustomProfile("tmp", allOptions, version, fProfileVersioner.getProfileKind()); //$NON-NLS-1$
- fProfileVersioner.update(profile);
- return profile.getSettings();
- }
-
- boolean hasValues= false;
- for (int i= 0; i < fKeySets.length; i++) {
- KeySet keySet= fKeySets[i];
- IEclipsePreferences preferences= context.getNode(keySet.getNodeName());
- for (final Iterator keyIter = keySet.getKeys().iterator(); keyIter.hasNext(); ) {
- final String key= (String) keyIter.next();
- Object val= preferences.get(key, null);
- if (val != null) {
- hasValues= true;
- } else {
- val= workspaceProfile.getSettings().get(key);
- }
- profileOptions.put(key, val);
- }
- }
-
- if (!hasValues) {
- return null;
- }
-
- setLatestCompliance(profileOptions);
- return profileOptions;
- }
-
-
- /**
- * @param uiPrefs
- * @param allOptions
- */
- private void addAll(IEclipsePreferences uiPrefs, Map allOptions) {
- try {
- String[] keys= uiPrefs.keys();
- for (int i= 0; i < keys.length; i++) {
- String key= keys[i];
- String val= uiPrefs.get(key, null);
- if (val != null) {
- allOptions.put(key, val);
- }
- }
- } catch (BackingStoreException e) {
- // ignore
- }
-
- }
-
- private boolean updatePreferences(IEclipsePreferences prefs, List keys, Map profileOptions) {
- boolean hasChanges= false;
- for (final Iterator keyIter = keys.iterator(); keyIter.hasNext(); ) {
- final String key= (String) keyIter.next();
- final String oldVal= prefs.get(key, null);
- final String val= (String) profileOptions.get(key);
- if (val == null) {
- if (oldVal != null) {
- prefs.remove(key);
- hasChanges= true;
- }
- } else if (!val.equals(oldVal)) {
- prefs.put(key, val);
- hasChanges= true;
- }
- }
- return hasChanges;
- }
-
-
- /**
- * Update all formatter settings with the settings of the specified profile.
- * @param profile The profile to write to the preference store
- */
- private void writeToPreferenceStore(Profile profile, IScopeContext context) {
- final Map profileOptions= profile.getSettings();
-
- for (int i= 0; i < fKeySets.length; i++) {
- updatePreferences(context.getNode(fKeySets[i].getNodeName()), fKeySets[i].getKeys(), profileOptions);
- }
-
- final IEclipsePreferences uiPrefs= context.getNode(JavaScriptUI.ID_PLUGIN);
- if (uiPrefs.getInt(fProfileVersionKey, 0) != fProfileVersioner.getCurrentVersion()) {
- uiPrefs.putInt(fProfileVersionKey, fProfileVersioner.getCurrentVersion());
- }
-
- if (context.getName() == InstanceScope.SCOPE) {
- uiPrefs.put(fProfileKey, profile.getID());
- } else if (context.getName() == ProjectScope.SCOPE && !profile.isSharedProfile()) {
- uiPrefs.put(fProfileKey, profile.getID());
- }
- }
-
-
- /**
- * Get an immutable list as view on all profiles, sorted alphabetically. Unless the set
- * of profiles has been modified between the two calls, the sequence is guaranteed to
- * correspond to the one returned by <code>getSortedNames</code>.
- * @return a list of elements of type <code>Profile</code>
- *
- * @see #getSortedDisplayNames()
- */
- public List getSortedProfiles() {
- return Collections.unmodifiableList(fProfilesByName);
- }
-
- /**
- * Get the names of all profiles stored in this profile manager, sorted alphabetically. Unless the set of
- * profiles has been modified between the two calls, the sequence is guaranteed to correspond to the one
- * returned by <code>getSortedProfiles</code>.
- * @return All names, sorted alphabetically
- * @see #getSortedProfiles()
- */
- public String[] getSortedDisplayNames() {
- final String[] sortedNames= new String[fProfilesByName.size()];
- int i= 0;
- for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
- Profile curr= (Profile) iter.next();
- sortedNames[i++]= curr.getName();
- }
- return sortedNames;
- }
-
- /**
- * Get the profile for this profile id.
- * @param ID The profile ID
- * @return The profile with the given ID or <code>null</code>
- */
- public Profile getProfile(String ID) {
- return (Profile)fProfiles.get(ID);
- }
-
- /**
- * Activate the selected profile, update all necessary options in
- * preferences and save profiles to disk.
- */
- public void commitChanges(IScopeContext scopeContext) {
- if (fSelected != null) {
- writeToPreferenceStore(fSelected, scopeContext);
- }
- }
-
- public void clearAllSettings(IScopeContext context) {
- for (int i= 0; i < fKeySets.length; i++) {
- updatePreferences(context.getNode(fKeySets[i].getNodeName()), fKeySets[i].getKeys(), Collections.EMPTY_MAP);
- }
-
- final IEclipsePreferences uiPrefs= context.getNode(JavaScriptUI.ID_PLUGIN);
- uiPrefs.remove(fProfileKey);
- }
-
- /**
- * Get the currently selected profile.
- * @return The currently selected profile.
- */
- public Profile getSelected() {
- return fSelected;
- }
-
- /**
- * Set the selected profile. The profile must already be contained in this profile manager.
- * @param profile The profile to select
- */
- public void setSelected(Profile profile) {
- final Profile newSelected= (Profile)fProfiles.get(profile.getID());
- if (newSelected != null && !newSelected.equals(fSelected)) {
- fSelected= newSelected;
- notifyObservers(SELECTION_CHANGED_EVENT);
- }
- }
-
- /**
- * Check whether a user-defined profile in this profile manager
- * already has this name.
- * @param name The name to test for
- * @return Returns <code>true</code> if a profile with the given name exists
- */
- public boolean containsName(String name) {
- for (final Iterator iter = fProfilesByName.iterator(); iter.hasNext();) {
- Profile curr= (Profile) iter.next();
- if (name.equals(curr.getName())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Add a new custom profile to this profile manager.
- * @param profile The profile to add
- */
- public void addProfile(CustomProfile profile) {
- profile.setManager(this);
- final CustomProfile oldProfile= (CustomProfile)fProfiles.get(profile.getID());
- if (oldProfile != null) {
- fProfiles.remove(oldProfile.getID());
- fProfilesByName.remove(oldProfile);
- oldProfile.setManager(null);
- }
- fProfiles.put(profile.getID(), profile);
- fProfilesByName.add(profile);
- Collections.sort(fProfilesByName);
- fSelected= profile;
- notifyObservers(PROFILE_CREATED_EVENT);
- }
-
- /**
- * Delete the currently selected profile from this profile manager. The next profile
- * in the list is selected.
- * @return true if the profile has been successfully removed, false otherwise.
- */
- public boolean deleteSelected() {
- if (!(fSelected instanceof CustomProfile))
- return false;
-
- return deleteProfile((CustomProfile)fSelected);
- }
-
- public boolean deleteProfile(CustomProfile profile) {
- int index= fProfilesByName.indexOf(profile);
-
- fProfiles.remove(profile.getID());
- fProfilesByName.remove(profile);
-
- profile.setManager(null);
-
- if (index >= fProfilesByName.size())
- index--;
- fSelected= (Profile) fProfilesByName.get(index);
-
- if (!profile.isSharedProfile()) {
- updateProfilesWithName(profile.getID(), null, false);
- }
-
- notifyObservers(PROFILE_DELETED_EVENT);
- return true;
- }
-
-
- public void profileRenamed(CustomProfile profile, String oldID) {
- fProfiles.remove(oldID);
- fProfiles.put(profile.getID(), profile);
-
- if (!profile.isSharedProfile()) {
- updateProfilesWithName(oldID, profile, false);
- }
-
- Collections.sort(fProfilesByName);
- notifyObservers(PROFILE_RENAMED_EVENT);
- }
-
- public void profileReplaced(CustomProfile oldProfile, CustomProfile newProfile) {
- fProfiles.remove(oldProfile.getID());
- fProfiles.put(newProfile.getID(), newProfile);
- fProfilesByName.remove(oldProfile);
- fProfilesByName.add(newProfile);
- Collections.sort(fProfilesByName);
-
- if (!oldProfile.isSharedProfile()) {
- updateProfilesWithName(oldProfile.getID(), null, false);
- }
-
- setSelected(newProfile);
- notifyObservers(PROFILE_CREATED_EVENT);
- notifyObservers(SELECTION_CHANGED_EVENT);
- }
-
- public void profileChanged(CustomProfile profile) {
- if (!profile.isSharedProfile()) {
- updateProfilesWithName(profile.getID(), profile, true);
- }
-
- notifyObservers(SETTINGS_CHANGED_EVENT);
- }
-
-
- protected void updateProfilesWithName(String oldName, Profile newProfile, boolean applySettings) {
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i= 0; i < projects.length; i++) {
- IScopeContext projectScope= fPreferencesAccess.getProjectScope(projects[i]);
- IEclipsePreferences node= projectScope.getNode(JavaScriptUI.ID_PLUGIN);
- String profileId= node.get(fProfileKey, null);
- if (oldName.equals(profileId)) {
- if (newProfile == null) {
- node.remove(fProfileKey);
- } else {
- if (applySettings) {
- writeToPreferenceStore(newProfile, projectScope);
- } else {
- node.put(fProfileKey, newProfile.getID());
- }
- }
- }
- }
-
- IScopeContext instanceScope= fPreferencesAccess.getInstanceScope();
- final IEclipsePreferences uiPrefs= instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
- if (newProfile != null && oldName.equals(uiPrefs.get(fProfileKey, null))) {
- writeToPreferenceStore(newProfile, instanceScope);
- }
- }
-
- private static void setLatestCompliance(Map map) {
- JavaModelUtil.set50CompilanceOptions(map);
- }
-
- public abstract Profile getDefaultProfile();
-
- public IProfileVersioner getProfileVersioner() {
- return fProfileVersioner;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileStore.java
deleted file mode 100644
index 0031f254..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileStore.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.IScopeContext;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIException;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.Profile;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.Attributes;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-
-/**
- * Can load/store profiles from/to profilesKey
- */
-public class ProfileStore {
-
- /** The default encoding to use */
- public static final String ENCODING= "UTF-8"; //$NON-NLS-1$
-
- protected static final String VERSION_KEY_SUFFIX= ".version"; //$NON-NLS-1$
-
- /**
- * A SAX event handler to parse the xml format for profiles.
- */
- private final static class ProfileDefaultHandler extends DefaultHandler {
-
- private List fProfiles;
- private int fVersion;
-
- private String fName;
- private Map fSettings;
- private String fKind;
-
- public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
-
- if (qName.equals(XML_NODE_SETTING)) {
-
- final String key= attributes.getValue(XML_ATTRIBUTE_ID);
- final String value= attributes.getValue(XML_ATTRIBUTE_VALUE);
- fSettings.put(key, value);
-
- } else if (qName.equals(XML_NODE_PROFILE)) {
-
- fName= attributes.getValue(XML_ATTRIBUTE_NAME);
- fKind= attributes.getValue(XML_ATTRIBUTE_PROFILE_KIND);
- if (fKind == null) //Can only be an CodeFormatterProfile created pre 3.3M2
- fKind= ProfileVersioner.CODE_FORMATTER_PROFILE_KIND;
-
- fSettings= new HashMap(200);
-
- }
- else if (qName.equals(XML_NODE_ROOT)) {
-
- fProfiles= new ArrayList();
- try {
- fVersion= Integer.parseInt(attributes.getValue(XML_ATTRIBUTE_VERSION));
- } catch (NumberFormatException ex) {
- throw new SAXException(ex);
- }
-
- }
- }
-
- public void endElement(String uri, String localName, String qName) {
- if (qName.equals(XML_NODE_PROFILE)) {
- fProfiles.add(new CustomProfile(fName, fSettings, fVersion, fKind));
- fName= null;
- fSettings= null;
- fKind= null;
- }
- }
-
- public List getProfiles() {
- return fProfiles;
- }
-
- }
-
- /**
- * Identifiers for the XML file.
- */
- private final static String XML_NODE_ROOT= "profiles"; //$NON-NLS-1$
- private final static String XML_NODE_PROFILE= "profile"; //$NON-NLS-1$
- private final static String XML_NODE_SETTING= "setting"; //$NON-NLS-1$
-
- private final static String XML_ATTRIBUTE_VERSION= "version"; //$NON-NLS-1$
- private final static String XML_ATTRIBUTE_ID= "id"; //$NON-NLS-1$
- private final static String XML_ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
- private final static String XML_ATTRIBUTE_PROFILE_KIND= "kind"; //$NON-NLS-1$
- private final static String XML_ATTRIBUTE_VALUE= "value"; //$NON-NLS-1$
-
- private final IProfileVersioner fProfileVersioner;
- private final String fProfilesKey;
- private final String fProfilesVersionKey;
-
-
- public ProfileStore(String profilesKey, IProfileVersioner profileVersioner) {
- fProfilesKey= profilesKey;
- fProfileVersioner= profileVersioner;
- fProfilesVersionKey= profilesKey + VERSION_KEY_SUFFIX;
- }
-
- /**
- * @return Returns the collection of profiles currently stored in the preference store or
- * <code>null</code> if the loading failed. The elements are of type {@link ProfileManager.CustomProfile}
- * and are all updated to the latest version.
- * @throws CoreException
- */
- public List readProfiles(IScopeContext scope) throws CoreException {
- return readProfilesFromString(scope.getNode(JavaScriptUI.ID_PLUGIN).get(fProfilesKey, null));
- }
-
- public void writeProfiles(Collection profiles, IScopeContext instanceScope) throws CoreException {
- ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
- try {
- writeProfilesToStream(profiles, stream, ENCODING, fProfileVersioner);
- String val;
- try {
- val= stream.toString(ENCODING);
- } catch (UnsupportedEncodingException e) {
- val= stream.toString();
- }
- IEclipsePreferences uiPreferences = instanceScope.getNode(JavaScriptUI.ID_PLUGIN);
- uiPreferences.put(fProfilesKey, val);
- uiPreferences.putInt(fProfilesVersionKey, fProfileVersioner.getCurrentVersion());
- } finally {
- try { stream.close(); } catch (IOException e) { /* ignore */ }
- }
- }
-
- public List readProfilesFromString(String profiles) throws CoreException {
- if (profiles != null && profiles.length() > 0) {
- byte[] bytes;
- try {
- bytes= profiles.getBytes(ENCODING);
- } catch (UnsupportedEncodingException e) {
- bytes= profiles.getBytes();
- }
- InputStream is= new ByteArrayInputStream(bytes);
- try {
- List res= readProfilesFromStream(new InputSource(is));
- if (res != null) {
- for (int i= 0; i < res.size(); i++) {
- fProfileVersioner.update((CustomProfile) res.get(i));
- }
- }
- return res;
- } finally {
- try { is.close(); } catch (IOException e) { /* ignore */ }
- }
- }
- return null;
- }
-
-
- /**
- * Read the available profiles from the internal XML file and return them
- * as collection or <code>null</code> if the file is not a profile file.
- * @param file The file to read from
- * @return returns a list of <code>CustomProfile</code> or <code>null</code>
- * @throws CoreException
- */
- public List readProfilesFromFile(File file) throws CoreException {
- try {
- final FileInputStream reader= new FileInputStream(file);
- try {
- return readProfilesFromStream(new InputSource(reader));
- } finally {
- try { reader.close(); } catch (IOException e) { /* ignore */ }
- }
- } catch (IOException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
- }
- }
-
- /**
- * Load profiles from a XML stream and add them to a map or <code>null</code> if the source is not a profile store.
- * @param inputSource The input stream
- * @return returns a list of <code>CustomProfile</code> or <code>null</code>
- * @throws CoreException
- */
- public static List readProfilesFromStream(InputSource inputSource) throws CoreException {
-
- final ProfileDefaultHandler handler= new ProfileDefaultHandler();
- try {
- final SAXParserFactory factory= SAXParserFactory.newInstance();
- final SAXParser parser= factory.newSAXParser();
- parser.parse(inputSource, handler);
- } catch (SAXException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
- } catch (IOException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
- } catch (ParserConfigurationException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
- }
- return handler.getProfiles();
- }
-
- /**
- * Write the available profiles to the internal XML file.
- * @param profiles List of <code>CustomProfile</code>
- * @param file File to write
- * @param encoding the encoding to use
- * @throws CoreException
- */
- public void writeProfilesToFile(Collection profiles, File file, String encoding) throws CoreException {
- final OutputStream stream;
- try {
- stream= new FileOutputStream(file);
- try {
- writeProfilesToStream(profiles, stream, encoding, fProfileVersioner);
- } finally {
- try { stream.close(); } catch (IOException e) { /* ignore */ }
- }
- } catch (IOException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
- }
- }
-
- /**
- * Save profiles to an XML stream
- * @param profiles the list of <code>CustomProfile</code>
- * @param stream the stream to write to
- * @param encoding the encoding to use
- * @throws CoreException
- */
- public static void writeProfilesToStream(Collection profiles, OutputStream stream, String encoding, IProfileVersioner profileVersioner) throws CoreException {
-
- try {
- final DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- final DocumentBuilder builder= factory.newDocumentBuilder();
- final Document document= builder.newDocument();
-
- final Element rootElement = document.createElement(XML_NODE_ROOT);
- rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profileVersioner.getCurrentVersion()));
-
- document.appendChild(rootElement);
-
- for(final Iterator iter= profiles.iterator(); iter.hasNext();) {
- final Profile profile= (Profile)iter.next();
- if (profile.isProfileToSave()) {
- final Element profileElement= createProfileElement(profile, document, profileVersioner);
- rootElement.appendChild(profileElement);
- }
- }
-
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
- transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
- transformer.transform(new DOMSource(document), new StreamResult(stream));
- } catch (TransformerException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
- } catch (ParserConfigurationException e) {
- throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
- }
- }
-
-
- /*
- * Create a new profile element in the specified document. The profile is not added
- * to the document by this method.
- */
- private static Element createProfileElement(Profile profile, Document document, IProfileVersioner profileVersioner) {
- final Element element= document.createElement(XML_NODE_PROFILE);
- element.setAttribute(XML_ATTRIBUTE_NAME, profile.getName());
- element.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profile.getVersion()));
- element.setAttribute(XML_ATTRIBUTE_PROFILE_KIND, profileVersioner.getProfileKind());
-
- final Iterator keyIter= profile.getSettings().keySet().iterator();
-
- while (keyIter.hasNext()) {
- final String key= (String)keyIter.next();
- final String value= (String)profile.getSettings().get(key);
- if (value != null) {
- final Element setting= document.createElement(XML_NODE_SETTING);
- setting.setAttribute(XML_ATTRIBUTE_ID, key);
- setting.setAttribute(XML_ATTRIBUTE_VALUE, value);
- element.appendChild(setting);
- } else {
- JavaScriptPlugin.logErrorMessage("ProfileStore: Profile does not contain value for key " + key); //$NON-NLS-1$
- }
- }
- return element;
- }
-
-
- /*
- * Creates a UI exception for logging purposes
- */
- private static JavaUIException createException(Throwable t, String message) {
- return new JavaUIException(JavaUIStatus.createError(IStatus.ERROR, message, t));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileVersioner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileVersioner.java
deleted file mode 100644
index 2432699e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/ProfileVersioner.java
+++ /dev/null
@@ -1,687 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
-
-
-public class ProfileVersioner implements IProfileVersioner {
-
- public static final String CODE_FORMATTER_PROFILE_KIND= "CodeFormatterProfile"; //$NON-NLS-1$
-
- private static final int VERSION_1= 1; // < 20040113 (includes M6)
- private static final int VERSION_2= 2; // before renaming almost all
- private static final int VERSION_3= 3; // after renaming almost all
- private static final int VERSION_4= 4;
- private static final int VERSION_5= 5; // after splitting of FORMATTER_INDENT_BLOCK_STATEMENTS
- private static final int VERSION_6= 6; // after splitting of new_line_in_control_statements
- private static final int VERSION_7= 7; // after moving comment formatter to JSDT Core
- private static final int VERSION_8= 8; // fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=89739
- private static final int VERSION_9= 9; // after storing project profile names in preferences
- private static final int VERSION_10= 10; // splitting options for annotation types
- private static final int VERSION_11= 11; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=49412
-
- private static final int CURRENT_VERSION= VERSION_11;
-
- public int getFirstVersion() {
- return VERSION_1;
- }
-
- public int getCurrentVersion() {
- return CURRENT_VERSION;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getProfileKind() {
- return CODE_FORMATTER_PROFILE_KIND;
- }
-
- public void update(CustomProfile profile) {
- final Map oldSettings= profile.getSettings();
- Map newSettings= updateAndComplete(oldSettings, profile.getVersion());
- profile.setVersion(CURRENT_VERSION);
- profile.setSettings(newSettings);
- }
-
- private static Map updateAndComplete(Map oldSettings, int version) {
- final Map newSettings= FormatterProfileManager.getDefaultSettings();
-
- switch (version) {
-
- case VERSION_1:
- version1to2(oldSettings);
-
- case VERSION_2:
- version2to3(oldSettings);
-
- case VERSION_3:
- version3to4(oldSettings);
-
- case VERSION_4:
- version4to5(oldSettings);
-
- case VERSION_5:
- version5to6(oldSettings);
-
- case VERSION_6:
- version6to7(oldSettings);
-
- case VERSION_7:
- case VERSION_8:
- case VERSION_9:
- version9to10(oldSettings);
-
- case VERSION_10 :
- version10to11(oldSettings);
-
- default:
- for (final Iterator iter= oldSettings.keySet().iterator(); iter.hasNext(); ) {
- final String key= (String)iter.next();
- if (!newSettings.containsKey(key))
- continue;
-
- final String value= (String)oldSettings.get(key);
- if (value != null) {
- newSettings.put(key, value);
- }
- }
-
- }
- setLatestCompliance(newSettings);
- return newSettings;
- }
-
- /**
- * Updates the map to use the latest the source compliance
- * @param map The map to update
- */
- public static void setLatestCompliance(Map map) {
- JavaModelUtil.set50CompilanceOptions(map);
- }
-
- private static void version1to2(final Map oldSettings) {
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_WITHIN_MESSAGE_SEND,
- FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_MESSAGE_SEND,
- FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_MESSAGE_SEND);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_OPEN_PAREN_IN_PARENTHESIZED_EXPRESSION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION);
-
- checkAndReplace(oldSettings,
- JavaScriptCore.PLUGIN_ID + ".formatter.inset_space_between_empty_arguments", //$NON-NLS-1$
- FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_ARGUMENTS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_METHOD_DECLARATION_OPEN_PAREN,
- FORMATTER_INSERT_SPACE_BEFORE_CONSTRUCTOR_DECLARATION_OPEN_PAREN);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_OPEN_PAREN_IN_PARENTHESIZED_EXPRESSION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION);
- }
-
- public static int getVersionStatus(CustomProfile profile) {
- final int version= profile.getVersion();
- if (version < CURRENT_VERSION)
- return -1;
- else if (version > CURRENT_VERSION)
- return 1;
- else
- return 0;
- }
-
-
- private static void mapOldValueRangeToNew(Map settings, String oldKey, String [] oldValues,
- String newKey, String [] newValues) {
-
- if (!settings.containsKey(oldKey))
- return;
-
- final String value= ((String)settings.get(oldKey));
-
- if (value == null)
- return;
-
- for (int i = 0; i < oldValues.length; i++) {
- if (value.equals(oldValues[i])) {
- settings.put(newKey, newValues[i]);
- }
- }
-
- }
-
- private static void duplicate(Map settings, String existingKey, String newKey) {
- checkAndReplace(settings, existingKey, new String [] {newKey});
- }
-
- private static void checkAndReplace(Map settings, String oldKey, String newKey) {
- checkAndReplace(settings, oldKey, new String [] {newKey});
- }
-
- private static void checkAndReplace(Map settings, String oldKey, String newKey1, String newKey2) {
- checkAndReplace(settings, oldKey, new String [] {newKey1, newKey2});
- }
-
- private static void checkAndReplace(Map settings, String oldKey, String [] newKeys) {
- if (!settings.containsKey(oldKey))
- return;
-
- final String value= (String)settings.get(oldKey);
-
- if (value == null)
- return;
-
- for (int i = 0; i < newKeys.length; i++) {
- settings.put(newKeys[i], value);
- }
- }
-
- private static void checkAndReplaceBooleanWithINSERT(Map settings, String oldKey, String newKey) {
- if (!settings.containsKey(oldKey))
- return;
-
- String value= (String)settings.get(oldKey);
-
- if (value == null)
- return;
-
- if (DefaultCodeFormatterConstants.TRUE.equals(value))
- value= JavaScriptCore.INSERT;
- else
- value= JavaScriptCore.DO_NOT_INSERT;
-
- settings.put(newKey, value);
- }
-
-
- private static void version2to3(Map oldSettings) {
-
- checkAndReplace(oldSettings,
- FORMATTER_ARRAY_INITIALIZER_CONTINUATION_INDENTATION,
- DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_BLOCK_CLOSE_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_CATCH_EXPRESSION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_FOR_PARENS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_IF_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_SWITCH_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_SYNCHRONIZED_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_IN_WHILE_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MESSAGESEND_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_THROWS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_THROWS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_MESSAGE_SEND,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_MESSAGE_SEND,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_THROWS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_THROWS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICITCONSTRUCTORCALL_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICITCONSTRUCTORCALL_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS);
-
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MESSAGESEND_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_FIRST_ARGUMENT,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_MESSAGE_SEND,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_ANONYMOUS_TYPE_OPEN_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_BLOCK_OPEN_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_CATCH_EXPRESSION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_METHOD_OPEN_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_CONSTRUCTOR_DECLARATION_OPEN_PAREN,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_FIRST_INITIALIZER,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_FOR_PAREN,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_IF_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_MESSAGE_SEND,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_METHOD_DECLARATION_OPEN_PAREN,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_OPEN_PAREN_IN_PARENTHESIZED_EXPRESSION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_SWITCH_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_SWITCH_OPEN_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_SYNCHRONIZED_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_TYPE_OPEN_BRACE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_WHILE_CONDITION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_REFERENCE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_ARRAY_INITIALIZER,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_MESSAGESEND_ARGUMENTS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_FORMAT_GUARDIAN_CLAUSE_ON_ONE_LINE,
- DefaultCodeFormatterConstants.FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_BRACKET_IN_ARRAY_REFERENCE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_BRACKET_IN_ARRAY_TYPE_REFERENCE,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATORS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR);
-
- checkAndReplace(oldSettings,
- FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATORS,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR);
-
- checkAndReplace(oldSettings,
- FORMATTER_ALLOCATION_EXPRESSION_ARGUMENTS_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION);
-
- checkAndReplace(oldSettings,
- FORMATTER_COMPACT_IF_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF);
-
- checkAndReplace(oldSettings,
- FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT ,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_QUALIFIED_ALLOCATION_EXPRESSION_ARGUMENTS_ALIGNMENT ,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION);
-
- checkAndReplace(oldSettings,
- FORMATTER_BINARY_EXPRESSION_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION);
-
- checkAndReplace(oldSettings,
- FORMATTER_COMPACT_IF_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF);
-
- checkAndReplace(oldSettings,
- FORMATTER_CONDITIONAL_EXPRESSION_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
-
- checkAndReplace(oldSettings,
- FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
-
- checkAndReplace(oldSettings,
- FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_MESSAGE_SEND_SELECTOR_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_TYPE_DECLARATION_SUPERCLASS_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_TYPE_DECLARATION_SUPERINTERFACES_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_METHOD_THROWS_CLAUSE_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_EXPLICIT_CONSTRUCTOR_ARGUMENTS_ALIGNMENT,
- DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL);
-
-
- mapOldValueRangeToNew(oldSettings,
- FORMATTER_TYPE_MEMBER_ALIGNMENT, new String [] {FORMATTER_NO_ALIGNMENT, FORMATTER_MULTICOLUMN},
- DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS, new String [] {DefaultCodeFormatterConstants.FALSE, DefaultCodeFormatterConstants.TRUE});
-
-
- checkAndReplace(oldSettings,
- FORMATTER_ANONYMOUS_TYPE_DECLARATION_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_ARRAY_INITIALIZER_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
-
- checkAndReplace(oldSettings,
- FORMATTER_BLOCK_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
-
- checkAndReplace(oldSettings,
- FORMATTER_METHOD_DECLARATION_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_TYPE_DECLARATION_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION);
-
- checkAndReplace(oldSettings,
- FORMATTER_SWITCH_BRACE_POSITION,
- DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH);
-
- }
-
- private static void version3to4(Map oldSettings) {
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.align_type_members_on_columns", //$NON-NLS-1$
- DefaultCodeFormatterConstants.FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS);
-
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.formatter.insert_space_after_comma__in_superinterfaces", //$NON-NLS-1$
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES);
-
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.formatter.insert_space_before_comma__in_superinterfaces", //$NON-NLS-1$
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES);
-
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.formatter.insert_space_between_empty_arguments_in_method_invocation", //$NON-NLS-1$
- DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION);
- }
-
- private static void version4to5(Map oldSettings) {
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.formatter.indent_block_statements", //$NON-NLS-1$
- new String[] { DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY, DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK });
- }
-
- private static void version5to6(Map oldSettings) {
- checkAndReplace(oldSettings,
- "org.eclipse.wst.jsdt.core.formatter.insert_new_line_in_control_statements", //$NON-NLS-1$
- new String[] {
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT
- });
- }
-
- private static void version6to7(Map oldSettings) {
- checkAndReplace(oldSettings, FORMATTER_COMMENT_FORMAT, FORMATTER_COMMENT_FORMAT2);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_FORMATHEADER, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_FORMATSOURCE, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_INDENTROOTTAGS, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_LINELENGTH, DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_CLEARBLANKLINES, FORMATTER_COMMENT_CLEAR_BLANK_LINES);
- checkAndReplace(oldSettings, FORMATTER_COMMENT_FORMATHTML, DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML);
-
- checkAndReplaceBooleanWithINSERT(oldSettings, FORMATTER_COMMENT_NEWLINEFORPARAMETER, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER);
- checkAndReplaceBooleanWithINSERT(oldSettings, FORMATTER_COMMENT_SEPARATEROOTTAGS, DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS);
- }
-
- private static void version9to10(Map oldSettings) {
- duplicate(oldSettings,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION,
- DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANNOTATION_DECLARATION);
- duplicate(oldSettings,
- DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER,
- DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ANNOTATION_DECLARATION_HEADER);
- }
-
- private static void version10to11(Map oldSettings) {
- checkAndReplace(oldSettings,
- FORMATTER_COMMENT_FORMAT2,
- new String[] {
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT
- });
- checkAndReplace(oldSettings, FORMATTER_COMMENT_CLEAR_BLANK_LINES,
- new String[] {
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT,
- });
- }
-
- /* old format constant values */
-
- private static final String FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.method_declaration_arguments_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.message_send_arguments_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_MESSAGE_SEND_SELECTOR_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.message_send_selector_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_QUALIFIED_ALLOCATION_EXPRESSION_ARGUMENTS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.qualified_allocation_expression_arguments_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_TYPE_DECLARATION_SUPERCLASS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.type_declaration_superclass_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_TYPE_DECLARATION_SUPERINTERFACES_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.type_declaration_superinterfaces_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_METHOD_THROWS_CLAUSE_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.method_throws_clause_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_CONDITIONAL_EXPRESSION_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.conditional_expression_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_ALLOCATION_EXPRESSION_ARGUMENTS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.allocation_expression_arguments_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_COMPACT_IF_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.compact_if_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.array_initializer_expressions_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_BINARY_EXPRESSION_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.binary_expression_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_EXPLICIT_CONSTRUCTOR_ARGUMENTS_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.explicit_constructor_arguments_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_ANONYMOUS_TYPE_DECLARATION_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.anonymous_type_declaration_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_ARRAY_INITIALIZER_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.array_initializer_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_BLOCK_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.block_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_METHOD_DECLARATION_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.method_declaration_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_TYPE_DECLARATION_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.type_declaration_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_SWITCH_BRACE_POSITION = JavaScriptCore.PLUGIN_ID + ".formatter.switch_brace_position"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MESSAGESEND_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_messagesend_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_OPEN_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_open_paren_in_parenthesized_expression"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_MESSAGE_SEND = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_message_send"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_MESSAGE_SEND = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_message_send"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MESSAGESEND_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_messagesend_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_MESSAGE_SEND = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_message_send"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_FIRST_ARGUMENT = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_first_argument"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_WITHIN_MESSAGE_SEND = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_within_message_send"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_BLOCK_CLOSE_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_block_close_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_ANONYMOUS_TYPE_OPEN_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_anonymous_type_open_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_BLOCK_OPEN_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_block_open_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_CATCH_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_catch_expression"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_CONSTRUCTOR_DECLARATION_OPEN_PAREN = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_constructor_declaration_open_paren"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_FIRST_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_first_initializer"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_FOR_PAREN = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_for_paren"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_IF_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_if_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_METHOD_DECLARATION_OPEN_PAREN = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_method_declaration_open_paren"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_METHOD_OPEN_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_method_open_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_OPEN_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_open_paren_in_parenthesized_expression"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_SWITCH_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_switch_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_SWITCH_OPEN_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_switch_open_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_SYNCHRONIZED_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_synchronized_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_TYPE_OPEN_BRACE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_type_open_brace"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_WHILE_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_while_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_brackets_in_array_reference";//$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_ARRAY_INITIALIZER = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_array_initializer"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_MESSAGESEND_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_between_empty_messagesend_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_CATCH_EXPRESSION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_catch_expression"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_FOR_PARENS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_for_parens"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_IF_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_if_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_SWITCH_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_switch_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_SYNCHRONIZED_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_synchronized_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_IN_WHILE_CONDITION = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_in_while_condition"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_BRACKET_IN_ARRAY_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_bracket_in_array_reference";//$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_BRACKET_IN_ARRAY_TYPE_REFERENCE = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_bracket_in_array_type_reference"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATORS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_assignment_operators"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATORS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_assignment_operators"; //$NON-NLS-1$
- private static final String FORMATTER_FORMAT_GUARDIAN_CLAUSE_ON_ONE_LINE = JavaScriptCore.PLUGIN_ID + ".formatter.format_guardian_clause_on_one_line"; //$NON-NLS-1$
- private static final String FORMATTER_ARRAY_INITIALIZER_CONTINUATION_INDENTATION = JavaScriptCore.PLUGIN_ID + ".formatter.array_initializer_continuation_indentation"; //$NON-NLS-1$
- private static final String FORMATTER_TYPE_MEMBER_ALIGNMENT = JavaScriptCore.PLUGIN_ID + ".formatter.type_member_alignment"; //$NON-NLS-1$
- private static final String FORMATTER_MULTICOLUMN = "256"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_throws"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_throws"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICITCONSTRUCTORCALL_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICITCONSTRUCTORCALL_ARGUMENTS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_throws"; //$NON-NLS-1$
- private static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_THROWS = JavaScriptCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_throws"; //$NON-NLS-1$
- private static final String FORMATTER_NO_ALIGNMENT = "0";//$NON-NLS-1$
- private static final String FORMATTER_COMMENT_FORMAT2= JavaScriptCore.PLUGIN_ID + ".formatter.comment.format_comments"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_CLEAR_BLANK_LINES= JavaScriptCore.PLUGIN_ID + ".formatter.comment.clear_blank_lines"; //$NON-NLS-1$
-
- // Old comment formatter constants
- private static final String FORMATTER_COMMENT_FORMATSOURCE= "comment_format_source_code"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION= "comment_indent_parameter_description"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_FORMATHEADER= "comment_format_header"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_INDENTROOTTAGS= "comment_indent_root_tags"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_FORMAT= "comment_format_comments"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_NEWLINEFORPARAMETER= "comment_new_line_for_parameter"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_SEPARATEROOTTAGS= "comment_separate_root_tags"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_CLEARBLANKLINES= "comment_clear_blank_lines"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_LINELENGTH= "comment_line_length"; //$NON-NLS-1$
- private static final String FORMATTER_COMMENT_FORMATHTML= "comment_format_html"; //$NON-NLS-1$
-
- }
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/SnippetPreview.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/SnippetPreview.java
deleted file mode 100644
index 815d9d32..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/SnippetPreview.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-public class SnippetPreview extends JavaPreview {
-
- public final static class PreviewSnippet {
-
- public String header;
- public final String source;
- public final int kind;
-
- public PreviewSnippet(int kind, String source) {
- this.kind= kind;
- this.source= source;
- }
- }
-
- private ArrayList fSnippets;
-
- public SnippetPreview(Map workingValues, Composite parent) {
- super(workingValues, parent);
- fSnippets= new ArrayList();
- }
-
- protected void doFormatPreview() {
- if (fSnippets.isEmpty()) {
- fPreviewDocument.set(""); //$NON-NLS-1$
- return;
- }
-
- //This delimiter looks best for invisible characters
- final String delimiter= "\n"; //$NON-NLS-1$
-
- final StringBuffer buffer= new StringBuffer();
- for (final Iterator iter= fSnippets.iterator(); iter.hasNext();) {
- final PreviewSnippet snippet= (PreviewSnippet) iter.next();
- String formattedSource;
- try {
- formattedSource= CodeFormatterUtil.format(snippet.kind, snippet.source, 0, null, delimiter, fWorkingValues);
- } catch (Exception e) {
- final IStatus status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR,
- FormatterMessages.JavaPreview_formatter_exception, e);
- JavaScriptPlugin.log(status);
- continue;
- }
- buffer.append(delimiter);
- buffer.append(formattedSource);
- buffer.append(delimiter);
- buffer.append(delimiter);
- }
- fPreviewDocument.set(buffer.toString());
- }
-
-
-
- public void add(PreviewSnippet snippet) {
- fSnippets.add(snippet);
- }
-
- public void remove(PreviewSnippet snippet) {
- fSnippets.remove(snippet);
- }
-
- public void addAll(Collection snippets) {
- fSnippets.addAll(snippets);
- }
-
- public void clear() {
- fSnippets.clear();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java
deleted file mode 100644
index dff85b0c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java
+++ /dev/null
@@ -1,1261 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.SnippetPreview.PreviewSnippet;
-
-
-/**
- * Manage code formatter white space options on a higher level.
- */
-public final class WhiteSpaceOptions {
-
- /**
- * Represents a node in the options tree.
- */
- public abstract static class Node {
-
- private final InnerNode fParent;
- private final String fName;
-
- public int index;
-
- protected final Map fWorkingValues;
- protected final ArrayList fChildren;
-
- public Node(InnerNode parent, Map workingValues, String message) {
- if (workingValues == null || message == null)
- throw new IllegalArgumentException();
- fParent= parent;
- fWorkingValues= workingValues;
- fName= message;
- fChildren= new ArrayList();
- if (fParent != null)
- fParent.add(this);
- }
-
- public abstract void setChecked(boolean checked);
-
- public boolean hasChildren() {
- return !fChildren.isEmpty();
- }
-
- public List getChildren() {
- return Collections.unmodifiableList(fChildren);
- }
-
- public InnerNode getParent() {
- return fParent;
- }
-
- public final String toString() {
- return fName;
- }
-
- public abstract List getSnippets();
-
- public abstract void getCheckedLeafs(List list);
- }
-
- /**
- * A node representing a group of options in the tree.
- */
- public static class InnerNode extends Node {
-
- public InnerNode(InnerNode parent, Map workingValues, String messageKey) {
- super(parent, workingValues, messageKey);
- }
-
- public void setChecked(boolean checked) {
- for (final Iterator iter = fChildren.iterator(); iter.hasNext();)
- ((Node)iter.next()).setChecked(checked);
- }
-
- public void add(Node child) {
- fChildren.add(child);
- }
-
- public List getSnippets() {
- final ArrayList snippets= new ArrayList(fChildren.size());
- for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
- final List childSnippets= ((Node)iter.next()).getSnippets();
- for (final Iterator chIter= childSnippets.iterator(); chIter.hasNext(); ) {
- final Object snippet= chIter.next();
- if (!snippets.contains(snippet))
- snippets.add(snippet);
- }
- }
- return snippets;
- }
-
- public void getCheckedLeafs(List list) {
- for (Iterator iter= fChildren.iterator(); iter.hasNext();) {
- ((Node)iter.next()).getCheckedLeafs(list);
- }
- }
- }
-
-
- /**
- * A node representing a concrete white space option in the tree.
- */
- public static class OptionNode extends Node {
- private final String fKey;
- private final ArrayList fSnippets;
-
- public OptionNode(InnerNode parent, Map workingValues, String messageKey, String key, PreviewSnippet snippet) {
- super(parent, workingValues, messageKey);
- fKey= key;
- fSnippets= new ArrayList(1);
- fSnippets.add(snippet);
- }
-
- public void setChecked(boolean checked) {
- fWorkingValues.put(fKey, checked ? JavaScriptCore.INSERT : JavaScriptCore.DO_NOT_INSERT);
- }
-
- public boolean getChecked() {
- return JavaScriptCore.INSERT.equals(fWorkingValues.get(fKey));
- }
-
- public List getSnippets() {
- return fSnippets;
- }
-
- public void getCheckedLeafs(List list) {
- if (getChecked())
- list.add(this);
- }
- }
-
-
-
- /**
- * Preview snippets.
- */
-
- private final PreviewSnippet FOR_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "for (i= 0, j= array.length; i < array.length; i++, j--) {}\nfor (s in MyData) {}"); //$NON-NLS-1$
-
- private final PreviewSnippet WHILE_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "while (condition) {}; do {} while (condition);"); //$NON-NLS-1$
-
- private final PreviewSnippet CATCH_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
-// "try { number= Integer.parseInt(value); } catch (NumberFormatException e) {}"); //$NON-NLS-1$
- "try {\n} catch (err) {\n}"); //$NON-NLS-1$
-
- private final PreviewSnippet IF_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "if (condition) { return foo; } else {return bar;}"); //$NON-NLS-1$
-
-// private final PreviewSnippet SYNCHRONIZED_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "synchronized (list) { list.add(element); }"); //$NON-NLS-1$
-
- private final PreviewSnippet SWITCH_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "switch (number) { case RED: return GREEN; case GREEN: return BLUE; case BLUE: return RED; default: return BLACK;}"); //$NON-NLS-1$
-
- private final PreviewSnippet CONSTRUCTOR_DECL_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "MyClass() throws E0, E1 { this(0,0,0);}" + //$NON-NLS-1$
-// "MyClass(int x, int y, int z) throws E0, E1 { super(x, y, z, true);}"); //$NON-NLS-1$
- CodeFormatter.K_STATEMENTS,
- "function Foo(x, y) {\n this.x = 1;\n this.y = 2;\n}\n" + //$NON-NLS-1$
- "obj1 = new Foo();\nobj2 = new Foo(3, 4);"); //$NON-NLS-1$
-
- private final PreviewSnippet METHOD_DECL_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "void foo() throws E0, E1 {};" + //$NON-NLS-1$
-// "void bar(int x, int y) throws E0, E1 {}"); //$NON-NLS-1$
- CodeFormatter.K_STATEMENTS,
- "function foo() {};\nfunction bar(x,y){}"); //$NON-NLS-1$
-
- private final PreviewSnippet ARRAY_DECL_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "var arr2=[];\n" + //$NON-NLS-1$
- "var arr3=[4];\n" + //$NON-NLS-1$
- "var arr4=[\'one\',\'two\',\'three\']"); //$NON-NLS-1$
-
- private final PreviewSnippet ARRAY_REF_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
-// "array[i].foo();"); //$NON-NLS-1$
- "array[i];"); //$NON-NLS-1$
-
- private final PreviewSnippet METHOD_CALL_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "foo();\n" + //$NON-NLS-1$
- "bar(x, y);"); //$NON-NLS-1$
-
-// private final PreviewSnippet CONSTR_CALL_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "this();\n\n" + //$NON-NLS-1$
-// "this(x, y);\n"); //$NON-NLS-1$
-
- private final PreviewSnippet ALLOC_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "s= new Foo(); p= new Bar(x, y);"); //$NON-NLS-1$
-
- private final PreviewSnippet LABEL_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "label: for (i= 0; i<list.length; i++) {for (j= 0; j < list[i].length; j++) continue label;}"); //$NON-NLS-1$
-
-// private final PreviewSnippet SEMICOLON_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "int a= 4; foo(); bar(x, y);"); //$NON-NLS-1$
-
- private final PreviewSnippet CONDITIONAL_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "value= condition ? TRUE : FALSE;"); //$NON-NLS-1$
-
-// private final PreviewSnippet CLASS_DECL_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_JAVASCRIPT_UNIT,
-// "class MyClass implements I0, I1, I2 {}"); //$NON-NLS-1$
-
-// private final PreviewSnippet ANON_CLASS_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "AnonClass= new AnonClass() {void foo(Some s) { }};"); //$NON-NLS-1$
-
- private final PreviewSnippet OPERATOR_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "var arr= new Array();\nvar a= -4 + -9;\nvar b= a++ / --a;\na += 4;\nvar value= true && false;"); //$NON-NLS-1$
-
-// private final PreviewSnippet CAST_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "String s= ((String)object);"); //$NON-NLS-1$
-
- private final PreviewSnippet MULT_LOCAL_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
-// "int a= 0, b= 1, c= 2, d= 3;"); //$NON-NLS-1$
- "var a= 0, b= 1, c= 2, d= 3;"); //$NON-NLS-1$
-
-// private final PreviewSnippet MULT_FIELD_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "int a=0,b=1,c=2,d=3;"); //$NON-NLS-1$
-
- private final PreviewSnippet BLOCK_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "if (true) { return 1; } else { return 2; }"); //$NON-NLS-1$
-
- private final PreviewSnippet PAREN_EXPR_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "result= (a *( b + c + d) * (e + f));"); //$NON-NLS-1$
-
- private final PreviewSnippet ASSERT_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "assert condition : reportError();" //$NON-NLS-1$
- );
-
- private final PreviewSnippet RETURN_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "return (o);" //$NON-NLS-1$
- );
-
- private final PreviewSnippet THROW_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "throw (e);" //$NON-NLS-1$
- );
-
- private final PreviewSnippet OBJECT_INITIALIZER_PREVIEW= new PreviewSnippet(
- CodeFormatter.K_STATEMENTS,
- "anObject = { color:'red', wheels:4, engine:{ cylinders:4, size:2.2 } };" //$NON-NLS-1$
- );
-
-// private final PreviewSnippet ANNOTATION_DECL_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "@interface MyAnnotation { String value(); }\n@interface OtherAnnotation { }\n" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet ANNOTATION_MODIFIER_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "@Annot(x=23, y=-3)\npublic class A { }\n" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet ENUM_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "enum MyEnum { GREEN(0, 1), RED() {\nvoid process() {}\n}\n}" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet PARAMETERIZED_TYPE_REFERENCE_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "Map<String, Element> map=\n new HashMap<String, Element>();" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet TYPE_ARGUMENTS_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_STATEMENTS,
-// "x.<String, Element>foo();" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet TYPE_PARAMETER_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "class MyGenericType<S, T extends Element & List> { }" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet VARARG_PARAMETER_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "void format(String s, Object ... args) {}" //$NON-NLS-1$
-// );
-
-// private final PreviewSnippet WILDCARD_PREVIEW= new PreviewSnippet(
-// CodeFormatter.K_CLASS_BODY_DECLARATIONS,
-// "Map<X<?>, Y<? extends K, ? super V>> t;" //$NON-NLS-1$
-// );
-
- /**
- * Create the tree, in this order: syntax element - position - abstract element
- * @param workingValues
- * @return returns roots (type <code>Node</code>)
- */
- public List createTreeBySyntaxElem(Map workingValues) {
- final ArrayList roots= new ArrayList();
-
- InnerNode element;
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_opening_paren);
- createBeforeOpenParenTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterOpenParenTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_closing_paren);
- createBeforeClosingParenTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
-// createAfterCloseParenTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_opening_brace);
- createBeforeOpenBraceTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterOpenBraceTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_closing_brace);
-// createBeforeClosingBraceTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterCloseBraceTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_opening_bracket);
- createBeforeOpenBracketTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterOpenBracketTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_closing_bracket);
- createBeforeClosingBracketTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_operator);
- createBeforeOperatorTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterOperatorTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_comma);
- createBeforeCommaTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterCommaTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_colon);
- createBeforeColonTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterColonTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_semicolon);
- createBeforeSemicolonTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterSemicolonTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_question_mark);
- createBeforeQuestionTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_before));
- createAfterQuestionTree(workingValues, createChild(element, workingValues, FormatterMessages.WhiteSpaceOptions_after));
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_parens);
- createBetweenEmptyParenTree(workingValues, element);
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_braces);
- createBetweenEmptyBracesTree(workingValues, element);
- roots.add(element);
-
- element= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_brackets);
- createBetweenEmptyBracketsTree(workingValues, element);
- roots.add(element);
-
- return roots;
- }
-
- /**
- * Create the tree, in this order: position - syntax element - abstract
- * element
- * @param workingValues
- * @return returns roots (type <code>Node</code>)
- */
- public List createAltTree(Map workingValues) {
-
- final ArrayList roots= new ArrayList();
-
- InnerNode parent;
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_opening_paren);
- createBeforeOpenParenTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_opening_paren);
- createAfterOpenParenTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_closing_paren);
- createBeforeClosingParenTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_closing_paren);
-// createAfterCloseParenTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_parens);
- createBetweenEmptyParenTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_opening_brace);
- createBeforeOpenBraceTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_opening_brace);
- createAfterOpenBraceTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_closing_brace);
-// createBeforeClosingBraceTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_closing_brace);
- createAfterCloseBraceTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_braces);
- createBetweenEmptyBracesTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_opening_bracket);
- createBeforeOpenBracketTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_opening_bracket);
- createAfterOpenBracketTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_closing_bracket);
- createBeforeClosingBracketTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_between_empty_brackets);
- createBetweenEmptyBracketsTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_opening_angle_bracket);
-// createBeforeOpenAngleBracketTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_opening_angle_bracket);
-// createAfterOpenAngleBracketTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_closing_angle_bracket);
-// createBeforeClosingAngleBracketTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_closing_angle_bracket);
-// createAfterClosingAngleBracketTree(workingValues, parent);
-
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_operator);
- createBeforeOperatorTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_operator);
- createAfterOperatorTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_comma);
- createBeforeCommaTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_comma);
- createAfterCommaTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_colon);
- createAfterColonTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_colon);
- createBeforeColonTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_semicolon);
- createBeforeSemicolonTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_semicolon);
- createAfterSemicolonTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_question_mark);
- createBeforeQuestionTree(workingValues, parent);
-
- parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_question_mark);
- createAfterQuestionTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_at);
-// createBeforeAtTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_at);
-// createAfterAtTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_and);
-// createBeforeAndTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_and);
-// createAfterAndTree(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_before_ellipsis);
-// createBeforeEllipsis(workingValues, parent);
-
-// parent= createParentNode(roots, workingValues, FormatterMessages.WhiteSpaceOptions_after_ellipsis);
-// createAfterEllipsis(workingValues, parent);
-
- return roots;
- }
-
- private InnerNode createParentNode(List roots, Map workingValues, String text) {
- final InnerNode parent= new InnerNode(null, workingValues, text);
- roots.add(parent);
- return parent;
- }
-
- public ArrayList createTreeByJavaElement(Map workingValues) {
-
- final InnerNode declarations= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_declarations);
-// createClassTree(workingValues, declarations);
-// createFieldTree(workingValues, declarations);
- createLocalVariableTree(workingValues, declarations);
-// createConstructorTree(workingValues, declarations);
- createMethodDeclTree(workingValues, declarations);
- createLabelTree(workingValues, declarations);
-// createAnnotationTree(workingValues, declarations);
-// createEnumTree(workingValues, declarations);
-// createAnnotationTypeTree(workingValues, declarations);
-
- final InnerNode statements= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_statements);
-// createOption(statements, workingValues, FormatterMessages.WhiteSpaceOptions_before_semicolon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, SEMICOLON_PREVIEW);
- createBlockTree(workingValues, statements);
- createIfStatementTree(workingValues, statements);
- createForStatementTree(workingValues, statements);
- createSwitchStatementTree(workingValues, statements);
- createDoWhileTree(workingValues, statements);
-// createSynchronizedTree(workingValues, statements);
- createTryStatementTree(workingValues, statements);
-// createAssertTree(workingValues, statements);
- createReturnTree(workingValues, statements);
- createThrowTree(workingValues, statements);
-
- final InnerNode expressions= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_expressions);
- createFunctionCallTree(workingValues, expressions);
- createAssignmentTree(workingValues, expressions);
- createOperatorTree(workingValues, expressions);
- createParenthesizedExpressionTree(workingValues, expressions);
- createConditionalTree(workingValues, expressions);
- createObjectInitializerTree(workingValues, expressions);
-// createTypecastTree(workingValues, expressions);
-
- final InnerNode arrays= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_arrays);
- createArrayInitializerTree(workingValues, arrays);
- createArrayElementAccessTree(workingValues, arrays);
-
-// final InnerNode paramtypes= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_parameterized_types);
-// createParameterizedTypeTree(workingValues, paramtypes);
-// createTypeArgumentTree(workingValues, paramtypes);
-// createTypeParameterTree(workingValues, paramtypes);
-// createWildcardTypeTree(workingValues, paramtypes);
-
- final ArrayList roots= new ArrayList();
- roots.add(declarations);
- roots.add(statements);
- roots.add(expressions);
- roots.add(arrays);
-// roots.add(paramtypes);
- return roots;
- }
-
- private void createBeforeQuestionTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_conditional, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_wildcard, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_WILDCARD, WILDCARD_PREVIEW);
- }
-
-// private void createBeforeAtTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AT_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
-// }
-
-// private void createBeforeAndTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AND_IN_TYPE_PARAMETER, TYPE_PARAMETER_PREVIEW);
-// }
-
- private void createBeforeSemicolonTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR, FOR_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_statements, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, SEMICOLON_PREVIEW);
- }
-
- private void createBeforeColonTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_assert, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT, ASSERT_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_conditional, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_label, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT, LABEL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_object_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_OBJECT_INITIALIZER, OBJECT_INITIALIZER_PREVIEW);
-
- final InnerNode switchStatement= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_switch);
- createOption(switchStatement, workingValues, FormatterMessages.WhiteSpaceOptions_case, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE, SWITCH_PREVIEW);
- createOption(switchStatement, workingValues, FormatterMessages.WhiteSpaceOptions_default, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT, SWITCH_PREVIEW);
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_FOR, FOR_PREVIEW);
- }
-
- private void createBeforeCommaTree(Map workingValues, final InnerNode parent) {
-
- final InnerNode forStatement= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for);
- createOption(forStatement, workingValues, FormatterMessages.WhiteSpaceOptions_initialization, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS, FOR_PREVIEW);
- createOption(forStatement, workingValues, FormatterMessages.WhiteSpaceOptions_incrementation, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS, FOR_PREVIEW);
-
- final InnerNode invocation= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_arguments);
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_method_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, METHOD_CALL_PREVIEW);
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_explicit_constructor_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_alloc_expr, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION, ALLOC_PREVIEW);
-
- final InnerNode decl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameters);
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS, METHOD_DECL_PREVIEW);
-
- final InnerNode throwsDecl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_throws);
- createOption(throwsDecl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(throwsDecl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS, METHOD_DECL_PREVIEW);
-
- final InnerNode multDecls= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_mult_decls);
-// createOption(multDecls, workingValues, FormatterMessages.WhiteSpaceOptions_fields, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, MULT_FIELD_PREVIEW);
- createOption(multDecls, workingValues, FormatterMessages.WhiteSpaceOptions_local_vars, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, MULT_LOCAL_PREVIEW);
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_implements_clause, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES, CLASS_DECL_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_DECLARATIONS, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, ENUM_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameterized_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
- }
-
- private void createBeforeOperatorTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_assignment_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_unary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_binary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_prefix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_postfix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR, OPERATOR_PREVIEW);
- }
-
- private void createBeforeClosingBracketTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, ARRAY_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_element_access, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
- }
-
-// private void createBeforeClosingAngleBracketTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameterized_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// }
-
-
- private void createBeforeOpenBracketTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE, ARRAY_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, ARRAY_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_element_access, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
- }
-
-// private void createBeforeOpenAngleBracketTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameterized_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// }
-
-// private void createBeforeClosingBraceTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_init, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER, CLASS_DECL_PREVIEW);
-// }
-
- private void createBeforeOpenBraceTree(Map workingValues, final InnerNode parent) {
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_class_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION, CLASS_DECL_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_anon_class_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION, ANON_CLASS_PREVIEW);
-
- final InnerNode functionDecl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_member_function_declaration); {
- createOption(functionDecl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
- createOption(functionDecl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- }
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_block, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK, BLOCK_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_switch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH, SWITCH_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_DECLARATION, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_body, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
- }
-
- private void createBeforeClosingParenTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_catch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH, CATCH_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_if, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF, IF_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_switch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_synchronized, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_while, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE, WHILE_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_cast, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST, CAST_PREVIEW);
-
- final InnerNode decl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_member_function_declaration);
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_method_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_paren_expr, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-
- }
-
- private void createBeforeOpenParenTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_catch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH, CATCH_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_if, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF, IF_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_switch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_synchronized, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_while, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE, WHILE_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_return_with_parenthesized_expression, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_RETURN, RETURN_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_throw_with_parenthesized_expression, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_THROW, THROW_PREVIEW);
-
- final InnerNode decls= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_member_function_declaration);
- createOption(decls, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
- createOption(decls, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_method_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_paren_expr, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_type_member, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, ANNOTATION_DECL_PREVIEW);
-
- }
-
- private void createAfterQuestionTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_conditional, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_wildcard, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_WILDCARD, WILDCARD_PREVIEW);
- }
-
-// private void createAfterAtTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
-// }
-
-// private void createAfterAndTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AND_IN_TYPE_PARAMETER, TYPE_PARAMETER_PREVIEW);
-// }
-
-// private void createBeforeEllipsis(Map workingValues, InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_vararg_parameter, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ELLIPSIS, VARARG_PARAMETER_PREVIEW);
-// }
-
-// private void createAfterEllipsis(Map workingValues, InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_vararg_parameter, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ELLIPSIS, VARARG_PARAMETER_PREVIEW);
-// }
-
- private void createAfterSemicolonTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR, FOR_PREVIEW);
- }
-
- private void createAfterColonTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_assert, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT, ASSERT_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_conditional, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_label, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT, LABEL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_object_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_OBJECT_INITIALIZER, OBJECT_INITIALIZER_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_FOR, FOR_PREVIEW);
- }
-
- private void createAfterCommaTree(Map workingValues, final InnerNode parent) {
-
- final InnerNode forStatement= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for); {
- createOption(forStatement, workingValues, FormatterMessages.WhiteSpaceOptions_initialization, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS, FOR_PREVIEW);
- createOption(forStatement, workingValues, FormatterMessages.WhiteSpaceOptions_incrementation, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS, FOR_PREVIEW);
- }
- final InnerNode invocation= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_arguments); {
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, METHOD_CALL_PREVIEW);
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_explicit_constructor_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(invocation, workingValues, FormatterMessages.WhiteSpaceOptions_alloc_expr, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION, ALLOC_PREVIEW);
- }
- final InnerNode decl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameters); {
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(decl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS, METHOD_DECL_PREVIEW);
- }
- final InnerNode throwsDecl= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_throws); {
- createOption(throwsDecl, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, CONSTRUCTOR_DECL_PREVIEW);
- createOption(throwsDecl, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS, METHOD_DECL_PREVIEW);
- }
- final InnerNode multDecls= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_mult_decls); {
-// createOption(multDecls, workingValues, FormatterMessages.WhiteSpaceOptions_fields, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, MULT_FIELD_PREVIEW);
- createOption(multDecls, workingValues, FormatterMessages.WhiteSpaceOptions_local_vars, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, MULT_LOCAL_PREVIEW);
- }
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_implements_clause, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES, CLASS_DECL_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_DECLARATIONS, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, ENUM_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameterized_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
- }
-
- private void createAfterOperatorTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_assignment_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_unary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_binary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_prefix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR, OPERATOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_postfix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR, OPERATOR_PREVIEW);
- }
-
- private void createAfterOpenBracketTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION, ARRAY_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_element_access, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
- }
-
-// private void createAfterOpenAngleBracketTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_parameterized_type, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// }
-
- private void createAfterOpenBraceTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- }
-
- private void createAfterCloseBraceTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_block, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK, BLOCK_PREVIEW);
- }
-
-// private void createAfterCloseParenTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_cast, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST, CAST_PREVIEW);
-// }
-
-// private void createAfterClosingAngleBracketTree(Map workingValues, final InnerNode parent) {
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_parameters, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
- //createOption(parent, workingValues, "WhiteSpaceOptions.parameterized_type", DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW); //$NON-NLS-1$
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// }
-
- private void createAfterOpenParenTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_catch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH, CATCH_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_for, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_if, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF, IF_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_switch, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_synchronized, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_while, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE, WHILE_PREVIEW);
-
- final InnerNode decls= createChild(parent, workingValues, FormatterMessages.WhiteSpaceOptions_member_function_declaration); {
- createOption(decls, workingValues, FormatterMessages.WhiteSpaceOptions_constructor, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
- createOption(decls, workingValues, FormatterMessages.WhiteSpaceOptions_method, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- }
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_type_cast, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST, CAST_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_method_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_paren_expr, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_modifier_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
- }
-
- private void createBetweenEmptyParenTree(Map workingValues, final InnerNode parent) {
-
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_constructor_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_method_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_method_call, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
-
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_enum_constant_arguments, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_annotation_type_member, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, ANNOTATION_DECL_PREVIEW);
- }
-
- private void createBetweenEmptyBracketsTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION, ARRAY_DECL_PREVIEW);
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_array_decl, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE, ARRAY_DECL_PREVIEW);
- }
-
- private void createBetweenEmptyBracesTree(Map workingValues, final InnerNode parent) {
- createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_initializer, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- }
-
- // syntax element tree
-
-// private InnerNode createClassTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_classes);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_classes_before_opening_brace_of_a_class, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION, CLASS_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_classes_before_opening_brace_of_anon_class, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION, ANON_CLASS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_classes_before_comma_implements, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES, CLASS_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_classes_after_comma_implements, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES, CLASS_DECL_PREVIEW);
-// return root;
-// }
-
- private InnerNode createAssignmentTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_assignments);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_assignments_before_assignment_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_assignments_after_assignment_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, OPERATOR_PREVIEW);
- return root;
- }
-
- private InnerNode createObjectInitializerTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_object_initializer);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_object_initializer_before_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_OBJECT_INITIALIZER, OBJECT_INITIALIZER_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_object_initializer_after_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_OBJECT_INITIALIZER, OBJECT_INITIALIZER_PREVIEW);
- return root;
- }
-
- private InnerNode createOperatorTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_operators);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_before_binary_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_after_binary_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_before_unary_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_after_unary_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_before_prefix_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_after_prefix_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_before_postfix_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR, OPERATOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_operators_after_postfix_operators, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR, OPERATOR_PREVIEW);
- return root;
- }
-
- private InnerNode createMethodDeclTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_methods);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_between_empty_parens, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION, METHOD_DECL_PREVIEW);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS, METHOD_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS, METHOD_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_ellipsis, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ELLIPSIS, VARARG_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_ellipsis, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ELLIPSIS, VARARG_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma_in_throws, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS, METHOD_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma_in_throws, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS, METHOD_DECL_PREVIEW);
-
- return root;
- }
-
-// private InnerNode createConstructorTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_constructors);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_between_empty_parens, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION, CONSTRUCTOR_DECL_PREVIEW);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS, CONSTRUCTOR_DECL_PREVIEW);
-//// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma_in_throws, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, CONSTRUCTOR_DECL_PREVIEW);
-//// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma_in_throws, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS, CONSTRUCTOR_DECL_PREVIEW);
-// return root;
-// }
-
-// private InnerNode createFieldTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_fields);
-//
-//// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_fields_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, MULT_FIELD_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_fields_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS, MULT_LOCAL_PREVIEW);
-// return root;
-// }
-
- private InnerNode createLocalVariableTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_localvars);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_localvars_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, MULT_LOCAL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_localvars_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS, MULT_LOCAL_PREVIEW);
- return root;
- }
-
- private InnerNode createArrayInitializerTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_arrayinit);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_between_empty_braces, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER, ARRAY_DECL_PREVIEW);
- return root;
- }
-
- private InnerNode createArrayElementAccessTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_arrayelem);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE, ARRAY_REF_PREVIEW);
-
- return root;
- }
-
- private InnerNode createFunctionCallTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_calls);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_between_empty_parens, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_before_comma_in_method_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_after_comma_in_method_args, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, METHOD_CALL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_before_comma_in_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION, ALLOC_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_after_comma_in_alloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION, ALLOC_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_before_comma_in_qalloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, CONSTRUCTOR_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_calls_after_comma_in_qalloc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS, CONSTRUCTOR_DECL_PREVIEW);
- return root;
- }
-
- private InnerNode createBlockTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_blocks);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK, BLOCK_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_closing_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK, BLOCK_PREVIEW);
- return root;
- }
-
- private InnerNode createSwitchStatementTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_switch);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_switch_before_case_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE, SWITCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_switch_before_default_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT, SWITCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH, SWITCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH, SWITCH_PREVIEW);
- return root;
- }
-
- private InnerNode createDoWhileTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_do);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE, WHILE_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE, WHILE_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE, WHILE_PREVIEW);
-
- return root;
- }
-
-// private InnerNode createSynchronizedTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_synchronized);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED, SYNCHRONIZED_PREVIEW);
-// return root;
-// }
-
- private InnerNode createTryStatementTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_try);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH, CATCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH, CATCH_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH, CATCH_PREVIEW);
- return root;
- }
- private InnerNode createIfStatementTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_if);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF, IF_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF, IF_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF, IF_PREVIEW);
- return root;
- }
-
- private InnerNode createForStatementTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_for);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_for_before_comma_init, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_for_after_comma_init, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_for_before_comma_inc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_for_after_comma_inc, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_semicolon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR, FOR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_semicolon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR, FOR_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_FOR, FOR_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_FOR, FOR_PREVIEW);
-
- return root;
- }
-
-// private InnerNode createAssertTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_assert);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT, ASSERT_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT, ASSERT_PREVIEW);
-// return root;
-// }
-//
- private InnerNode createReturnTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceOptions_return);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_parenthesized_expressions, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_RETURN, RETURN_PREVIEW);
- return root;
- }
-
- private InnerNode createThrowTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceOptions_throw);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_parenthesized_expressions, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PARENTHESIZED_EXPRESSION_IN_THROW, THROW_PREVIEW);
- return root;
- }
-
- private InnerNode createLabelTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_labels);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT, LABEL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT, LABEL_PREVIEW);
- return root;
- }
-
-// private InnerNode createAnnotationTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_annotations);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_at, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// //createOption(root, workingValues, "WhiteSpaceTabPage.between_empty_parens", DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW); //$NON-NLS-1$
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW);
-// //createOption(root, workingValues, "WhiteSpaceTabPage.after_closing_paren", DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_ANNOTATION, ANNOTATION_MODIFIER_PREVIEW); //$NON-NLS-1$
-//
-// return root;
-// }
-
-// private InnerNode createAnnotationTypeTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_annotation_types);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_at, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AT_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_at, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AT_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANNOTATION_TYPE_DECLARATION, ANNOTATION_DECL_PREVIEW);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_annot_type_method_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, ANNOTATION_DECL_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_annot_type_method_between_empty_parens, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ANNOTATION_TYPE_MEMBER_DECLARATION, ANNOTATION_DECL_PREVIEW);
-// return root;
-// }
-
-// private InnerNode createEnumTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_enums);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_decl_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_DECLARATION, ENUM_PREVIEW);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_decl_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_DECLARATIONS, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_decl_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_DECLARATIONS, ENUM_PREVIEW);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_between_empty_parens, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ENUM_CONSTANT_ARGUMENTS, ENUM_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_arg_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// //createOption(inner, workingValues, "WhiteSpaceTabPage.enum_const_arg.after_closing_paren", DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_ENUM_CONSTANT, ENUM_PREVIEW); //$NON-NLS-1$
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_enum_const_before_opening_brace, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ENUM_CONSTANT, ENUM_PREVIEW);
-// return root;
-// }
-
-// private InnerNode createParameterizedTypeTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_param_type_ref);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, PARAMETERIZED_TYPE_REFERENCE_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, PARAMETERIZED_TYPE_REFERENCE_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, PARAMETERIZED_TYPE_REFERENCE_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, PARAMETERIZED_TYPE_REFERENCE_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, PARAMETERIZED_TYPE_REFERENCE_PREVIEW);
- //createOption(root, workingValues, "WhiteSpaceTabPage.after_closing_angle_bracket", DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, TYPE_ARGUMENTS_PREVIEW); //$NON-NLS-1$
-// return root;
-// }
-
-// private InnerNode createTypeArgumentTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_type_arguments);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_closing_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENTS, TYPE_ARGUMENTS_PREVIEW);
-// return root;
-// }
-
-// private InnerNode createTypeParameterTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_type_parameters);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_comma_in_params, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_closing_angle_bracket, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_PARAMETERS, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_and_list, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_AND_IN_TYPE_PARAMETER, TYPE_PARAMETER_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_and_list, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_AND_IN_TYPE_PARAMETER, TYPE_PARAMETER_PREVIEW);
-// return root;
-// }
-
-// private InnerNode createWildcardTypeTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_wildcardtype);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_question, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_WILDCARD, WILDCARD_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_question, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_WILDCARD, WILDCARD_PREVIEW);
-// return root;
-// }
-
-
- private InnerNode createConditionalTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_conditionals);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_question, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_question, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_colon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL, CONDITIONAL_PREVIEW);
- return root;
- }
-
-
-// private InnerNode createTypecastTree(Map workingValues, InnerNode parent) {
-// final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_typecasts);
-//
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST, CAST_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST, CAST_PREVIEW);
-// createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST, CAST_PREVIEW);
-// return root;
-// }
-
-
- private InnerNode createParenthesizedExpressionTree(Map workingValues, InnerNode parent) {
- final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceTabPage_parenexpr);
-
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_after_opening_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
- createOption(root, workingValues, FormatterMessages.WhiteSpaceTabPage_before_closing_paren, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION, PAREN_EXPR_PREVIEW);
- return root;
- }
-
-
-
- private static InnerNode createChild(InnerNode root, Map workingValues, String message) {
- return new InnerNode(root, workingValues, message);
- }
-
- private static OptionNode createOption(InnerNode root, Map workingValues, String message, String key, PreviewSnippet snippet) {
- return new OptionNode(root, workingValues, message, key, snippet);
- }
-
- public static void makeIndexForNodes(List tree, List flatList) {
- for (final Iterator iter= tree.iterator(); iter.hasNext();) {
- final Node node= (Node) iter.next();
- node.index= flatList.size();
- flatList.add(node);
- makeIndexForNodes(node.getChildren(), flatList);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceTabPage.java
deleted file mode 100644
index 0bb5552b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/WhiteSpaceTabPage.java
+++ /dev/null
@@ -1,475 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.preferences.formatter;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
-import org.eclipse.ui.part.PageBook;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.WhiteSpaceOptions.InnerNode;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.WhiteSpaceOptions.Node;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.WhiteSpaceOptions.OptionNode;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public class WhiteSpaceTabPage extends FormatterTabPage {
-
-
- /**
- * Encapsulates a view of the options tree which is structured by
- * syntactical element.
- */
-
- private final class SyntaxComponent implements ISelectionChangedListener, ICheckStateListener, IDoubleClickListener {
-
- private final String PREF_NODE_KEY= JavaScriptUI.ID_PLUGIN + "formatter_page.white_space_tab_page.node"; //$NON-NLS-1$
-
- private final List fIndexedNodeList;
- private final List fTree;
-
- private ContainerCheckedTreeViewer fTreeViewer;
- private Composite fComposite;
-
- private Node fLastSelected= null;
-
- public SyntaxComponent() {
- fIndexedNodeList= new ArrayList();
- fTree= new WhiteSpaceOptions().createAltTree(fWorkingValues);
- WhiteSpaceOptions.makeIndexForNodes(fTree, fIndexedNodeList);
- }
-
- public void createContents(final int numColumns, final Composite parent) {
- fComposite= new Composite(parent, SWT.NONE);
- fComposite.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, SWT.DEFAULT));
- fComposite.setLayout(createGridLayout(numColumns, false));
-
- createLabel(numColumns, fComposite, FormatterMessages.WhiteSpaceTabPage_insert_space);
-
- fTreeViewer= new ContainerCheckedTreeViewer(fComposite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
- fTreeViewer.setContentProvider(new ITreeContentProvider() {
- public Object[] getElements(Object inputElement) {
- return ((Collection)inputElement).toArray();
- }
- public Object[] getChildren(Object parentElement) {
- return ((Node)parentElement).getChildren().toArray();
- }
- public Object getParent(Object element) {
- return ((Node)element).getParent();
- }
- public boolean hasChildren(Object element) {
- return ((Node)element).hasChildren();
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
- public void dispose() {}
- });
- fTreeViewer.setLabelProvider(new LabelProvider());
- fTreeViewer.getControl().setLayoutData(createGridData(numColumns, GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL, SWT.DEFAULT));
- fDefaultFocusManager.add(fTreeViewer.getControl());
- }
-
- public void initialize() {
- fTreeViewer.addCheckStateListener(this);
- fTreeViewer.addSelectionChangedListener(this);
- fTreeViewer.addDoubleClickListener(this);
- fTreeViewer.setInput(fTree);
- restoreSelection();
- refreshState();
- }
-
- public void refreshState() {
- final ArrayList checked= new ArrayList(100);
- for (Iterator iter= fTree.iterator(); iter.hasNext();)
- ((Node) iter.next()).getCheckedLeafs(checked);
- fTreeViewer.setGrayedElements(new Object[0]);
- fTreeViewer.setCheckedElements(checked.toArray());
- fPreview.clear();
- if (fLastSelected != null) {
- fPreview.addAll(fLastSelected.getSnippets());
- }
- doUpdatePreview();
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- final IStructuredSelection selection= (IStructuredSelection)event.getSelection();
- if (selection.isEmpty())
- return;
- final Node node= (Node)selection.getFirstElement();
- if (node == fLastSelected)
- return;
- fDialogSettings.put(PREF_NODE_KEY, node.index);
- fPreview.clear();
- fPreview.addAll(node.getSnippets());
- doUpdatePreview();
- fLastSelected= node;
- }
-
- public void checkStateChanged(CheckStateChangedEvent event) {
- final Node node= (Node)event.getElement();
- node.setChecked(event.getChecked());
- doUpdatePreview();
- notifyValuesModified();
- }
-
- public void restoreSelection() {
- int index;
- try {
- index= fDialogSettings.getInt(PREF_NODE_KEY);
- } catch (NumberFormatException ex) {
- index= -1;
- }
- if (index < 0 || index > fIndexedNodeList.size() - 1) {
- index= 0;
- }
- final Node node= (Node)fIndexedNodeList.get(index);
- if (node != null) {
- fTreeViewer.expandToLevel(node, 0);
- fTreeViewer.setSelection(new StructuredSelection(new Node [] {node}));
- fLastSelected= node;
- }
- }
-
- public void doubleClick(DoubleClickEvent event) {
- final ISelection selection= event.getSelection();
- if (selection instanceof IStructuredSelection) {
- final Node node= (Node)((IStructuredSelection)selection).getFirstElement();
- fTreeViewer.setExpandedState(node, !fTreeViewer.getExpandedState(node));
- }
- }
-
- public Control getControl() {
- return fComposite;
- }
- }
-
-
-
- private final class JavaElementComponent implements ISelectionChangedListener, ICheckStateListener {
-
- private final String PREF_INNER_INDEX= JavaScriptUI.ID_PLUGIN + "formatter_page.white_space.java_view.inner"; //$NON-NLS-1$
- private final String PREF_OPTION_INDEX= JavaScriptUI.ID_PLUGIN + "formatter_page.white_space.java_view.option"; //$NON-NLS-1$
-
- private final ArrayList fIndexedNodeList;
- private final ArrayList fTree;
-
- private InnerNode fLastSelected;
-
- private TreeViewer fInnerViewer;
- private CheckboxTableViewer fOptionsViewer;
-
- private Composite fComposite;
-
- public JavaElementComponent() {
- fIndexedNodeList= new ArrayList();
- fTree= new WhiteSpaceOptions().createTreeByJavaElement(fWorkingValues);
- WhiteSpaceOptions.makeIndexForNodes(fTree, fIndexedNodeList);
- }
-
- public void createContents(int numColumns, Composite parent) {
-
- fComposite= new Composite(parent, SWT.NONE);
- fComposite.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, SWT.DEFAULT));
- fComposite.setLayout(createGridLayout(numColumns, false));
-
- createLabel(numColumns, fComposite, FormatterMessages.WhiteSpaceTabPage_insert_space, GridData.HORIZONTAL_ALIGN_BEGINNING);
-
- final SashForm sashForm= new SashForm(fComposite, SWT.VERTICAL);
- sashForm.setLayoutData(createGridData(numColumns, GridData.FILL_BOTH, SWT.DEFAULT));
-
- fInnerViewer= new TreeViewer(sashForm, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
-
- fInnerViewer.setContentProvider(new ITreeContentProvider() {
- public Object[] getElements(Object inputElement) {
- return ((Collection)inputElement).toArray();
- }
- public Object[] getChildren(Object parentElement) {
- final List children= ((Node)parentElement).getChildren();
- final ArrayList innerChildren= new ArrayList();
- for (final Iterator iter= children.iterator(); iter.hasNext();) {
- final Object o= iter.next();
- if (o instanceof InnerNode) innerChildren.add(o);
- }
- return innerChildren.toArray();
- }
- public Object getParent(Object element) {
- if (element instanceof InnerNode)
- return ((InnerNode)element).getParent();
- return null;
- }
- public boolean hasChildren(Object element) {
- final List children= ((Node)element).getChildren();
- for (final Iterator iter= children.iterator(); iter.hasNext();)
- if (iter.next() instanceof InnerNode) return true;
- return false;
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
- public void dispose() {}
- });
-
- fInnerViewer.setLabelProvider(new LabelProvider());
-
- final GridData innerGd= createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL, SWT.DEFAULT);
- innerGd.heightHint= fPixelConverter.convertHeightInCharsToPixels(3);
- fInnerViewer.getControl().setLayoutData(innerGd);
-
- fOptionsViewer= CheckboxTableViewer.newCheckList(sashForm, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL);
- fOptionsViewer.setContentProvider(new ArrayContentProvider());
- fOptionsViewer.setLabelProvider(new LabelProvider());
-
- final GridData optionsGd= createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL, SWT.DEFAULT);
- optionsGd.heightHint= fPixelConverter.convertHeightInCharsToPixels(3);
- fOptionsViewer.getControl().setLayoutData(optionsGd);
-
- fDefaultFocusManager.add(fInnerViewer.getControl());
- fDefaultFocusManager.add(fOptionsViewer.getControl());
-
- fInnerViewer.setInput(fTree);
- }
-
- public void refreshState() {
- if (fLastSelected != null) {
- innerViewerChanged(fLastSelected);
- }
- }
-
- public void initialize() {
- fInnerViewer.addSelectionChangedListener(this);
- fOptionsViewer.addSelectionChangedListener(this);
- fOptionsViewer.addCheckStateListener(this);
- restoreSelections();
- refreshState();
- }
-
- private void restoreSelections() {
- Node node;
- final int innerIndex= getValidatedIndex(PREF_INNER_INDEX);
- node= (Node)fIndexedNodeList.get(innerIndex);
- if (node instanceof InnerNode) {
- fInnerViewer.expandToLevel(node, 0);
- fInnerViewer.setSelection(new StructuredSelection(new Object[] {node}));
- fLastSelected= (InnerNode)node;
- }
-
- final int optionIndex= getValidatedIndex(PREF_OPTION_INDEX);
- node= (Node)fIndexedNodeList.get(optionIndex);
- if (node instanceof OptionNode) {
- fOptionsViewer.setSelection(new StructuredSelection(new Object[] {node}));
- }
-
- }
-
- private int getValidatedIndex(String key) {
- int index;
- try {
- index= fDialogSettings.getInt(key);
- } catch (NumberFormatException ex) {
- index= 0;
- }
- if (index < 0 || index > fIndexedNodeList.size() - 1) {
- index= 0;
- }
- return index;
- }
-
- public Control getControl() {
- return fComposite;
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- final IStructuredSelection selection= (IStructuredSelection)event.getSelection();
-
- if (selection.isEmpty() || !(selection.getFirstElement() instanceof Node))
- return;
-
- final Node selected= (Node)selection.getFirstElement();
-
- if (selected == null || selected == fLastSelected)
- return;
-
-
- if (event.getSource() == fInnerViewer && selected instanceof InnerNode) {
- fLastSelected= (InnerNode)selected;
- fDialogSettings.put(PREF_INNER_INDEX, selected.index);
- innerViewerChanged((InnerNode)selected);
- }
- else if (event.getSource() == fOptionsViewer && selected instanceof OptionNode)
- fDialogSettings.put(PREF_OPTION_INDEX, selected.index);
- }
-
- private void innerViewerChanged(InnerNode selectedNode) {
-
- final List children= selectedNode.getChildren();
-
- final ArrayList optionsChildren= new ArrayList();
- for (final Iterator iter= children.iterator(); iter.hasNext();) {
- final Object o= iter.next();
- if (o instanceof OptionNode) optionsChildren.add(o);
- }
-
- fOptionsViewer.setInput(optionsChildren.toArray());
-
- for (final Iterator iter= optionsChildren.iterator(); iter.hasNext();) {
- final OptionNode child= (OptionNode)iter.next();
- fOptionsViewer.setChecked(child, child.getChecked());
- }
-
- fPreview.clear();
- fPreview.addAll(selectedNode.getSnippets());
- doUpdatePreview();
- }
-
- public void checkStateChanged(CheckStateChangedEvent event) {
- final OptionNode option= (OptionNode)event.getElement();
- if (option != null)
- option.setChecked(event.getChecked());
- doUpdatePreview();
- notifyValuesModified();
- }
- }
-
-
-
- /**
- * This component switches between the two view and is responsible for delegating
- * the appropriate update requests.
- */
- private final class SwitchComponent extends SelectionAdapter {
- private final String PREF_VIEW_KEY= JavaScriptUI.ID_PLUGIN + "formatter_page.white_space_tab_page.view"; //$NON-NLS-1$
- private final String [] fItems= new String [] {
- FormatterMessages.WhiteSpaceTabPage_sort_by_java_element,
- FormatterMessages.WhiteSpaceTabPage_sort_by_syntax_element
- };
-
- private Combo fSwitchCombo;
- private PageBook fPageBook;
- private final SyntaxComponent fSyntaxComponent;
- private final JavaElementComponent fJavaElementComponent;
-
- public SwitchComponent() {
- fSyntaxComponent= new SyntaxComponent();
- fJavaElementComponent= new JavaElementComponent();
- }
-
- public void widgetSelected(SelectionEvent e) {
- final int index= fSwitchCombo.getSelectionIndex();
- if (index == 0) {
- fDialogSettings.put(PREF_VIEW_KEY, false);
- fJavaElementComponent.refreshState();
- fPageBook.showPage(fJavaElementComponent.getControl());
- }
- else if (index == 1) {
- fDialogSettings.put(PREF_VIEW_KEY, true);
- fSyntaxComponent.refreshState();
- fPageBook.showPage(fSyntaxComponent.getControl());
- }
- }
-
- public void createContents(int numColumns, Composite parent) {
-
- fPageBook= new PageBook(parent, SWT.NONE);
- fPageBook.setLayoutData(createGridData(numColumns, GridData.FILL_BOTH, SWT.DEFAULT));
-
- fJavaElementComponent.createContents(numColumns, fPageBook);
- fSyntaxComponent.createContents(numColumns, fPageBook);
-
- fSwitchCombo= new Combo(parent, SWT.READ_ONLY);
- final GridData gd= createGridData(numColumns, GridData.HORIZONTAL_ALIGN_END, SWT.DEFAULT);
- fSwitchCombo.setLayoutData(gd);
- fSwitchCombo.setItems(fItems);
- }
-
- public void initialize() {
- fSwitchCombo.addSelectionListener(this);
- fJavaElementComponent.initialize();
- fSyntaxComponent.initialize();
- restoreSelection();
- }
-
- private void restoreSelection() {
- final boolean selectSyntax= fDialogSettings.getBoolean(PREF_VIEW_KEY);
- if (selectSyntax) {
- fSyntaxComponent.refreshState();
- fSwitchCombo.setText(fItems[1]);
- fPageBook.showPage(fSyntaxComponent.getControl());
- } else {
- fJavaElementComponent.refreshState();
- fSwitchCombo.setText(fItems[0]);
- fPageBook.showPage(fJavaElementComponent.getControl());
- }
- }
- }
-
-
-
-
- private final SwitchComponent fSwitchComponent;
- protected final IDialogSettings fDialogSettings;
-
- protected SnippetPreview fPreview;
-
-
- /**
- * Create a new white space dialog page.
- * @param modifyDialog
- * @param workingValues
- */
- public WhiteSpaceTabPage(ModifyDialog modifyDialog, Map workingValues) {
- super(modifyDialog, workingValues);
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fSwitchComponent= new SwitchComponent();
- }
-
- protected void doCreatePreferences(Composite composite, int numColumns) {
- fSwitchComponent.createContents(numColumns, composite);
- }
-
- protected void initializePage() {
- fSwitchComponent.initialize();
- }
-
- protected JavaPreview doCreateJavaPreview(Composite parent) {
- fPreview= new SnippetPreview(fWorkingValues, parent);
- return fPreview;
- }
-
- protected void doUpdatePreview() {
- super.doUpdatePreview();
- fPreview.update();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionHandler.java
deleted file mode 100644
index 0ad0032e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionHandler.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.ProgressMonitorWrapper;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Copy of org.eclipse.ltk.internal.ui.refactoring.ChangeExceptionHandler
- *
- */
-public class ChangeExceptionHandler {
-
- public static class NotCancelableProgressMonitor extends ProgressMonitorWrapper {
- public NotCancelableProgressMonitor(IProgressMonitor monitor) {
- super(monitor);
- }
- public void setCanceled(boolean b) {
- // ignore set cancel
- }
- public boolean isCanceled() {
- return false;
- }
- }
-
- private Shell fParent;
- private String fName;
-
- private static class RefactorErrorDialog extends ErrorDialog {
- public RefactorErrorDialog(Shell parentShell, String dialogTitle, String dialogMessage, IStatus status, int displayMask) {
- super(parentShell, dialogTitle, dialogMessage, status, displayMask);
- }
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- Button ok= getButton(IDialogConstants.OK_ID);
- ok.setText( RefactoringMessages.ChangeExceptionHandler_undo_button);
- Button abort= createButton(parent, IDialogConstants.CANCEL_ID, RefactoringMessages.ChangeExceptionHandler_abort_button, true);
- abort.moveBelow(ok);
- abort.setFocus();
- }
- protected Control createMessageArea (Composite parent) {
- Control result= super.createMessageArea(parent);
- new Label(parent, SWT.NONE); // filler
- Label label= new Label(parent, SWT.NONE);
- label.setText(RefactoringMessages.ChangeExceptionHandler_message);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- applyDialogFont(result);
- return result;
- }
- }
-
- public ChangeExceptionHandler(Shell parent, Refactoring refactoring) {
- fParent= parent;
- fName= refactoring.getName();
- }
-
- public void handle(Change change, RuntimeException exception) {
- JavaScriptPlugin.log(exception);
- IStatus status= null;
- if (exception.getMessage() == null) {
- status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- RefactoringMessages.ChangeExceptionHandler_status_without_detail, exception);
- } else {
- status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- exception.getMessage(), exception);
- }
- handle(change, status);
- }
-
- public void handle(Change change, CoreException exception) {
- JavaScriptPlugin.log(exception);
- handle(change, exception.getStatus());
- }
-
- private void handle(Change change, IStatus status) {
- if (change instanceof CompositeChange) {
- Change undo= ((CompositeChange)change).getUndoUntilException();
- if (undo != null) {
- JavaScriptPlugin.log(status);
- final ErrorDialog dialog= new RefactorErrorDialog(fParent,
- RefactoringMessages.ChangeExceptionHandler_dialog_title,
- Messages.format(RefactoringMessages.ChangeExceptionHandler_dialog_message, fName),
- status, IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR);
- int result= dialog.open();
- if (result == IDialogConstants.OK_ID) {
- performUndo(undo);
- }
- return;
- }
- }
- ErrorDialog dialog= new ErrorDialog(fParent,
- RefactoringMessages.ChangeExceptionHandler_dialog_title,
- Messages.format(RefactoringMessages.ChangeExceptionHandler_dialog_message, fName),
- status, IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR);
- dialog.open();
- }
-
- private void performUndo(final Change undo) {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- monitor.beginTask("", 11); //$NON-NLS-1$
- try {
- undo.initializeValidationData(new NotCancelableProgressMonitor(new SubProgressMonitor(monitor, 1)));
- if (undo.isValid(new SubProgressMonitor(monitor,1)).hasFatalError()) {
- monitor.done();
- return;
- }
- undo.perform(new SubProgressMonitor(monitor, 9));
- } finally {
- undo.dispose();
- }
- }
- };
- WorkbenchRunnableAdapter adapter= new WorkbenchRunnableAdapter(runnable,
- ResourcesPlugin.getWorkspace().getRoot());
- ProgressMonitorDialog dialog= new ProgressMonitorDialog(fParent);
- try {
- dialog.run(false, false, adapter);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, fParent,
- RefactoringMessages.ChangeExceptionHandler_undo_dialog_title,
- RefactoringMessages.ChangeExceptionHandler_undo_dialog_message + fName);
- } catch (InterruptedException e) {
- // can't happen
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionsControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionsControl.java
deleted file mode 100644
index 70192378..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeExceptionsControl.java
+++ /dev/null
@@ -1,317 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ExceptionInfo;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * A special control to add and remove thrown exceptions.
- */
-public class ChangeExceptionsControl extends Composite {
-//TODO: cleanup, adapt NLS strings
-
- private static class ExceptionInfoContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object inputElement) {
- return removeMarkedAsDeleted((List) inputElement);
- }
- private ExceptionInfo[] removeMarkedAsDeleted(List exceptionInfos){
- List result= new ArrayList(exceptionInfos.size());
- for (Iterator iter= exceptionInfos.iterator(); iter.hasNext();) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (! info.isDeleted())
- result.add(info);
- }
- return (ExceptionInfo[]) result.toArray(new ExceptionInfo[result.size()]);
- }
- public void dispose() {
- // do nothing
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // do nothing
- }
- }
-
- private static class ExceptionInfoLabelProvider extends LabelProvider implements ITableLabelProvider {
- private Image fInterfaceImage;
-
- public ExceptionInfoLabelProvider() {
- super();
- fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS);
- }
-
- public Image getColumnImage(Object element, int columnIndex) {
- return fInterfaceImage;
- }
- public String getColumnText(Object element, int columnIndex) {
- ExceptionInfo info= (ExceptionInfo) element;
- return info.getType().getFullyQualifiedName();
- }
- }
-
- private final IExceptionListChangeListener fListener;
- private final IJavaScriptProject fProject;
-
- private TableViewer fTableViewer;
- private Button fRemoveButton;
- private List fExceptionInfos;
-
- public ChangeExceptionsControl(Composite parent, int style, IExceptionListChangeListener listener, IJavaScriptProject project) {
- super(parent, style);
- Assert.isNotNull(listener);
- fListener= listener;
- Assert.isNotNull(project);
- fProject= project;
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- setLayout(layout);
-
- createExceptionList(this);
- createButtonComposite(this);
- }
-
- public void setInput(List exceptionInfos) {
- Assert.isNotNull(exceptionInfos);
- fExceptionInfos= exceptionInfos;
- fTableViewer.setInput(fExceptionInfos);
- if (fExceptionInfos.size() > 0)
- fTableViewer.setSelection(new StructuredSelection(fExceptionInfos.get(0)));
- }
-
- private void createExceptionList(Composite parent) {
- final Table table= new Table(parent, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
- table.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- fTableViewer= new TableViewer(table);
- fTableViewer.setUseHashlookup(true);
- fTableViewer.setContentProvider(new ExceptionInfoContentProvider());
- fTableViewer.setLabelProvider(new ExceptionInfoLabelProvider());
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- updateButtonsEnabledState();
- }
- });
- }
-
- private ExceptionInfo[] getSelectedItems() {
- ISelection selection= fTableViewer.getSelection();
- if (selection == null)
- return new ExceptionInfo[0];
-
- if (!(selection instanceof IStructuredSelection))
- return new ExceptionInfo[0];
-
- List selected= ((IStructuredSelection) selection).toList();
- return (ExceptionInfo[]) selected.toArray(new ExceptionInfo[selected.size()]);
- }
-
- // ---- Button bar --------------------------------------------------------------------------------------
-
- private void createButtonComposite(Composite parent) {
- Composite buttonComposite= new Composite(parent, SWT.NONE);
- buttonComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- GridLayout gl= new GridLayout();
- gl.marginHeight= 0;
- gl.marginWidth= 0;
- buttonComposite.setLayout(gl);
-
- createAddButton(buttonComposite);
- fRemoveButton= createRemoveButton(buttonComposite);
- updateButtonsEnabledState();
- }
-
- private void updateButtonsEnabledState() {
- if (fRemoveButton != null)
- fRemoveButton.setEnabled(getTableSelectionCount() != 0);
- }
-
- private int getTableSelectionCount() {
- return getTable().getSelectionCount();
- }
-
- private int getTableItemCount() {
- return getTable().getItemCount();
- }
-
- private Table getTable() {
- return fTableViewer.getTable();
- }
-
- private Button createAddButton(Composite buttonComposite) {
- Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.ChangeExceptionsControl_buttons_add);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.setEnabled(true);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- doAddException();
- }
- });
- return button;
- }
-
- private void doAddException() {
- IType newException= chooseException();
- if (newException == null)
- return;
-
- ExceptionInfo info= findExceptionInfo(newException);
- if (info != null) {
- if (info.isDeleted()) {
- info.markAsOld();
- fTableViewer.refresh();
- }
- fListener.exceptionListChanged();
- fTableViewer.getControl().setFocus();
- fTableViewer.setSelection(new StructuredSelection(info), true);
- return;
- }
-
- info= ExceptionInfo.createInfoForAddedException(newException);
- fExceptionInfos.add(info);
- fListener.exceptionListChanged();
- fTableViewer.refresh();
- fTableViewer.getControl().setFocus();
- int row= getTableItemCount() - 1;
- getTable().setSelection(row);
- updateButtonsEnabledState();
-
- }
-
- private IType chooseException() {
- IJavaScriptElement[] elements= new IJavaScriptElement[] { fProject.getJavaScriptProject() };
- final IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(elements);
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
- PlatformUI.getWorkbench().getProgressService(), scope, IJavaScriptSearchConstants.CLASS);
- dialog.setTitle(RefactoringMessages.ChangeExceptionsControl_choose_title);
- dialog.setMessage(RefactoringMessages.ChangeExceptionsControl_choose_message);
- dialog.setInitialPattern("*Exception*"); //$NON-NLS-1$
- dialog.setValidator(new ISelectionStatusValidator() {
- public IStatus validate(Object[] selection) {
- if (selection.length == 0)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- try {
- return checkException((IType)selection[0]);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return StatusInfo.OK_STATUS;
- }
- }
- });
-
- if (dialog.open() == Window.OK) {
- return (IType) dialog.getFirstResult();
- }
- return null;
- }
-
- private IStatus checkException(final IType type) throws JavaScriptModelException {
- ITypeHierarchy hierarchy= type.newSupertypeHierarchy(new NullProgressMonitor());
- IType curr= type;
- while (curr != null) {
- String name= curr.getFullyQualifiedName();
- if ("java.lang.Throwable".equals(name)) //$NON-NLS-1$
- return StatusInfo.OK_STATUS;
- curr= hierarchy.getSuperclass(curr);
- }
- return JavaUIStatus.createError(IStatus.ERROR,
- RefactoringMessages.ChangeExceptionsControl_not_exception, null);
- }
-
- private ExceptionInfo findExceptionInfo(IType exception) {
- for (Iterator iter= fExceptionInfos.iterator(); iter.hasNext(); ) {
- ExceptionInfo info= (ExceptionInfo) iter.next();
- if (info.getType().equals(exception))
- return info;
- }
- return null;
- }
-
- private Button createRemoveButton(Composite buttonComposite) {
- final Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.ChangeExceptionsControl_buttons_remove);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int index= getTable().getSelectionIndices()[0];
- ExceptionInfo[] selected= getSelectedItems();
- for (int i= 0; i < selected.length; i++) {
- if (selected[i].isAdded())
- fExceptionInfos.remove(selected[i]);
- else
- selected[i].markAsDeleted();
- }
- restoreSelection(index);
- }
- private void restoreSelection(int index) {
- fTableViewer.refresh();
- fTableViewer.getControl().setFocus();
- int itemCount= getTableItemCount();
- if (itemCount != 0) {
- if (index >= itemCount)
- index= itemCount - 1;
- getTable().setSelection(index);
- }
- fListener.exceptionListChanged();
- updateButtonsEnabledState();
- }
- });
- return button;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeParametersControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeParametersControl.java
deleted file mode 100644
index 6ffe9b08..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeParametersControl.java
+++ /dev/null
@@ -1,732 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableFontProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.contentassist.ContentAssistHandler;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TableTextCellEditor;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.VariableNamesProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-
-/**
- * A special control to edit and reorder method parameters.
- */
-public class ChangeParametersControl extends Composite {
-
-
- static final boolean SHOW_TYPES=false;
- public static class Mode {
- private final String fName;
- private Mode(String name) {
- fName= name;
- }
- public static final Mode EXTRACT_METHOD= new Mode("EXTRACT_METHOD"); //$NON-NLS-1$
- public static final Mode CHANGE_METHOD_SIGNATURE= new Mode("CHANGE_METHOD_SIGNATURE"); //$NON-NLS-1$
- public static final Mode INTRODUCE_PARAMETER= new Mode("INTRODUCE_PARAMETER"); //$NON-NLS-1$
- public String toString() {
- return fName;
- }
- public boolean canChangeTypes() {
- return this == CHANGE_METHOD_SIGNATURE;
- }
- public boolean canAddParameters() {
- return this == Mode.CHANGE_METHOD_SIGNATURE;
- }
- public boolean canChangeDefault() {
- return this == Mode.CHANGE_METHOD_SIGNATURE;
- }
- }
-
- private static class ParameterInfoContentProvider implements IStructuredContentProvider {
- public Object[] getElements(Object inputElement) {
- return removeMarkedAsDeleted((List) inputElement);
- }
- private ParameterInfo[] removeMarkedAsDeleted(List paramInfos){
- List result= new ArrayList(paramInfos.size());
- for (Iterator iter= paramInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (! info.isDeleted())
- result.add(info);
- }
- return (ParameterInfo[]) result.toArray(new ParameterInfo[result.size()]);
- }
- public void dispose() {
- // do nothing
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // do nothing
- }
- }
-
- private static class ParameterInfoLabelProvider extends LabelProvider implements ITableLabelProvider, ITableFontProvider {
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
- public String getColumnText(Object element, int columnIndex) {
- ParameterInfo info= (ParameterInfo) element;
- switch (columnIndex) {
- case TYPE_PROP:
- return info.getNewTypeName();
- case NEWNAME_PROP:
- return info.getNewName();
- case DEFAULT_PROP:
- if (info.isAdded())
- return info.getDefaultValue();
- else
- return "-"; //$NON-NLS-1$
- default:
- throw new IllegalArgumentException(columnIndex + ": " + element); //$NON-NLS-1$
- }
- }
- public Font getFont(Object element, int columnIndex) {
- ParameterInfo info= (ParameterInfo) element;
- if (info.isAdded())
- return JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT);
- else
- return null;
- }
- }
-
- private class ParametersCellModifier implements ICellModifier {
- public boolean canModify(Object element, String property) {
- Assert.isTrue(element instanceof ParameterInfo);
- if (JavaScriptCore.IS_ECMASCRIPT4 && property.equals(PROPERTIES[TYPE_PROP]))
- return fMode.canChangeTypes();
- else if (property.equals(PROPERTIES[NEWNAME_PROP]))
- return true;
- else if (property.equals(PROPERTIES[DEFAULT_PROP]))
- return (((ParameterInfo)element).isAdded());
- Assert.isTrue(false);
- return false;
- }
- public Object getValue(Object element, String property) {
- Assert.isTrue(element instanceof ParameterInfo);
- if (JavaScriptCore.IS_ECMASCRIPT4 && property.equals(PROPERTIES[TYPE_PROP]))
- return ((ParameterInfo) element).getNewTypeName();
- else if (property.equals(PROPERTIES[NEWNAME_PROP]))
- return ((ParameterInfo) element).getNewName();
- else if (property.equals(PROPERTIES[DEFAULT_PROP]))
- return ((ParameterInfo) element).getDefaultValue();
- Assert.isTrue(false);
- return null;
- }
- public void modify(Object element, String property, Object value) {
- if (element instanceof TableItem)
- element= ((TableItem) element).getData();
- if (!(element instanceof ParameterInfo))
- return;
- boolean unchanged;
- ParameterInfo parameterInfo= (ParameterInfo) element;
- if (property.equals(PROPERTIES[NEWNAME_PROP])) {
- unchanged= parameterInfo.getNewName().equals(value);
- parameterInfo.setNewName((String) value);
- } else if (property.equals(PROPERTIES[DEFAULT_PROP])) {
- unchanged= parameterInfo.getDefaultValue().equals(value);
- parameterInfo.setDefaultValue((String) value);
- } else if (property.equals(PROPERTIES[TYPE_PROP])) {
- unchanged= parameterInfo.getNewTypeName().equals(value);
- parameterInfo.setNewTypeName((String) value);
- } else {
- throw new IllegalStateException();
- }
- if (! unchanged) {
- ChangeParametersControl.this.fListener.parameterChanged(parameterInfo);
- ChangeParametersControl.this.fTableViewer.update(parameterInfo, new String[] { property });
- }
- }
- }
-
- private static final String[] PROPERTIES_NO_RETURN = new String[] { RefactoringMessages.ChangeParametersControl_new, RefactoringMessages.ChangeParametersControl_default };
- private static final String[] PROPERTIES_WITH_RETURN = new String[] { RefactoringMessages.ChangeParametersControl_type, RefactoringMessages.ChangeParametersControl_new, RefactoringMessages.ChangeParametersControl_default };
-
- private static final String[] PROPERTIES= JavaScriptCore.IS_ECMASCRIPT4?PROPERTIES_WITH_RETURN:PROPERTIES_NO_RETURN;
-
-
-
-
- private static final int TYPE_PROP= JavaScriptCore.IS_ECMASCRIPT4?0:-1;
- private static final int NEWNAME_PROP= JavaScriptCore.IS_ECMASCRIPT4?1:0;
- private static final int DEFAULT_PROP= JavaScriptCore.IS_ECMASCRIPT4?2:1;
-
- private static final int ROW_COUNT= 7;
-
- private final Mode fMode;
- private final IParameterListChangeListener fListener;
- private List fParameterInfos;
- private final StubTypeContext fTypeContext;
- private final String[] fParamNameProposals;
- private ContentAssistHandler fNameContentAssistHandler;
-
- private TableViewer fTableViewer;
- private Button fUpButton;
- private Button fDownButton;
- private Button fEditButton;
- private Button fAddButton;
- private Button fRemoveButton;
-
- public ChangeParametersControl(Composite parent, int style, String label, IParameterListChangeListener listener, Mode mode, StubTypeContext typeContext) {
- this(parent, style, label, listener, mode, typeContext, new String[0]);
- }
-
- public ChangeParametersControl(Composite parent, int style, String label, IParameterListChangeListener listener, Mode mode) {
- this(parent, style, label, listener, mode, null, new String[0]);
- }
-
- public ChangeParametersControl(Composite parent, int style, String label, IParameterListChangeListener listener, Mode mode, String[] paramNameProposals) {
- this(parent, style, label, listener, mode, null, paramNameProposals);
- }
-
- /**
- * @param label the label before the table or <code>null</code>
- * @param typeContext the package in which to complete types
- */
- private ChangeParametersControl(Composite parent, int style, String label, IParameterListChangeListener listener, Mode mode, StubTypeContext typeContext, String[] paramNameProposals) {
- super(parent, style);
- Assert.isNotNull(listener);
- fListener= listener;
- fMode= mode;
- fTypeContext= typeContext;
- fParamNameProposals= paramNameProposals;
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- setLayout(layout);
-
- if (label != null) {
- Label tableLabel= new Label(this, SWT.NONE);
- GridData labelGd= new GridData();
- labelGd.horizontalSpan= 2;
- tableLabel.setLayoutData(labelGd);
- tableLabel.setText(label);
- }
-
- createParameterList(this);
- createButtonComposite(this);
- }
-
-
- public void setInput(List parameterInfos) {
- Assert.isNotNull(parameterInfos);
- fParameterInfos= parameterInfos;
- fTableViewer.setInput(fParameterInfos);
- if (fParameterInfos.size() > 0)
- fTableViewer.setSelection(new StructuredSelection(fParameterInfos.get(0)));
- }
-
- public void editParameter(ParameterInfo info) {
- fTableViewer.getControl().setFocus();
- if (! info.isDeleted()) {
- fTableViewer.setSelection(new StructuredSelection(info), true);
- updateButtonsEnabledState();
- editColumnOrNextPossible(NEWNAME_PROP);
- return;
- }
- }
-
- // ---- Parameter table -----------------------------------------------------------------------------------
-
- private void createParameterList(Composite parent) {
- TableLayoutComposite layouter= new TableLayoutComposite(parent, SWT.NONE);
- addColumnLayoutData(layouter);
-
- final Table table= new Table(layouter, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
- TableColumn tc;
-
-// if (SHOW_TYPES)
-// {
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- tc= new TableColumn(table, SWT.NONE, TYPE_PROP);
- tc.setResizable(true);
- tc.setText(SHOW_TYPES?RefactoringMessages.ChangeParametersControl_table_type:""); //$NON-NLS-1$
-//
- }
-
- int index= NEWNAME_PROP;
-// if (!SHOW_TYPES)
-// index--;
- tc= new TableColumn(table, SWT.NONE,index);
- tc.setResizable(true);
- tc.setText(RefactoringMessages.ChangeParametersControl_table_name);
-
- if (fMode.canChangeDefault()){
- index= DEFAULT_PROP;
-// if (!SHOW_TYPES)
-// index--;
- tc= new TableColumn(table, SWT.NONE, index);
- tc.setResizable(true);
- tc.setText(RefactoringMessages.ChangeParametersControl_table_defaultValue);
- }
-
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= SWTUtil.getTableHeightHint(table, ROW_COUNT);
- gd.widthHint= 40;
- layouter.setLayoutData(gd);
-
- fTableViewer= new TableViewer(table);
- fTableViewer.setUseHashlookup(true);
- fTableViewer.setContentProvider(new ParameterInfoContentProvider());
- fTableViewer.setLabelProvider(new ParameterInfoLabelProvider());
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- updateButtonsEnabledState();
- }
- });
-
- table.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_RETURN && e.stateMask == SWT.NONE) {
- editColumnOrNextPossible(0);
- e.detail= SWT.TRAVERSE_NONE;
- }
- }
- });
- table.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == SWT.F2 && e.stateMask == SWT.NONE) {
- editColumnOrNextPossible(0);
- e.doit= false;
- }
- }
- });
-
- addCellEditors();
- }
-
- private void editColumnOrNextPossible(int column){
- ParameterInfo[] selected= getSelectedElements();
- if (selected.length != 1)
- return;
- int nextColumn= column;
- do {
- fTableViewer.editElement(selected[0], nextColumn);
- if (fTableViewer.isCellEditorActive())
- return;
- nextColumn= nextColumn(nextColumn);
- } while (nextColumn != column);
- }
-
- private void editColumnOrPrevPossible(int column){
- ParameterInfo[] selected= getSelectedElements();
- if (selected.length != 1)
- return;
- int prevColumn= column;
- do {
- fTableViewer.editElement(selected[0], prevColumn);
- if (fTableViewer.isCellEditorActive())
- return;
- prevColumn= prevColumn(prevColumn);
- } while (prevColumn != column);
- }
-
- private int nextColumn(int column) {
- return (column >= getTable().getColumnCount() - 1) ? 0 : column + 1;
- }
-
- private int prevColumn(int column) {
- return (column <= 0) ? getTable().getColumnCount() - 1 : column - 1;
- }
-
- private void addColumnLayoutData(TableLayoutComposite layouter) {
- if (fMode.canChangeDefault()){
- // layouter.addColumnData(new ColumnWeightData(33, true));
- layouter.addColumnData(new ColumnWeightData(33, true));
- layouter.addColumnData(new ColumnWeightData(34, true));
- } else if (SHOW_TYPES){
- layouter.addColumnData(new ColumnWeightData(50, true));
- layouter.addColumnData(new ColumnWeightData(50, true));
- }
- else
- {
- layouter.addColumnData(new ColumnWeightData(1, true));
- layouter.addColumnData(new ColumnWeightData(99, true));
- }
- }
-
- private ParameterInfo[] getSelectedElements() {
- ISelection selection= fTableViewer.getSelection();
- if (selection == null)
- return new ParameterInfo[0];
-
- if (!(selection instanceof IStructuredSelection))
- return new ParameterInfo[0];
-
- List selected= ((IStructuredSelection) selection).toList();
- return (ParameterInfo[]) selected.toArray(new ParameterInfo[selected.size()]);
- }
-
- // ---- Button bar --------------------------------------------------------------------------------------
-
- private void createButtonComposite(Composite parent) {
- Composite buttonComposite= new Composite(parent, SWT.NONE);
- buttonComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- GridLayout gl= new GridLayout();
- gl.marginHeight= 0;
- gl.marginWidth= 0;
- buttonComposite.setLayout(gl);
-
- if (fMode.canAddParameters())
- fAddButton= createAddButton(buttonComposite);
-
- fEditButton= createEditButton(buttonComposite);
-
- if (fMode.canAddParameters())
- fRemoveButton= createRemoveButton(buttonComposite);
-
- if (buttonComposite.getChildren().length != 0)
- addSpacer(buttonComposite);
-
- fUpButton= createButton(buttonComposite, RefactoringMessages.ChangeParametersControl_buttons_move_up, true);
- fDownButton= createButton(buttonComposite, RefactoringMessages.ChangeParametersControl_buttons_move_down, false);
-
- updateButtonsEnabledState();
- }
-
- private void addSpacer(Composite parent) {
- Label label= new Label(parent, SWT.NONE);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint= 5;
- label.setLayoutData(gd);
- }
-
- private void updateButtonsEnabledState() {
- fUpButton.setEnabled(canMove(true));
- fDownButton.setEnabled(canMove(false));
- if (fEditButton != null)
- fEditButton.setEnabled(getTableSelectionCount() == 1);
- if (fAddButton != null)
- fAddButton.setEnabled(true);
- if (fRemoveButton != null)
- fRemoveButton.setEnabled(getTableSelectionCount() != 0);
- }
-
- private int getTableSelectionCount() {
- return getTable().getSelectionCount();
- }
-
- private int getTableItemCount() {
- return getTable().getItemCount();
- }
-
- private Table getTable() {
- return fTableViewer.getTable();
- }
-
- private Button createEditButton(Composite buttonComposite) {
- Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.ChangeParametersControl_buttons_edit);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- try {
- ParameterInfo[] selected= getSelectedElements();
- Assert.isTrue(selected.length == 1);
- ParameterInfo parameterInfo= selected[0];
- ParameterEditDialog dialog= new ParameterEditDialog(getShell(), parameterInfo, fMode.canChangeTypes(), fMode.canChangeDefault(), fTypeContext);
- dialog.open();
- fListener.parameterChanged(parameterInfo);
- fTableViewer.update(parameterInfo, PROPERTIES);
- } finally {
- fTableViewer.getControl().setFocus();
- }
- }
- });
- return button;
- }
-
- private Button createAddButton(Composite buttonComposite) {
- Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.ChangeParametersControl_buttons_add);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- String[] excludedParamNames= new String[fParameterInfos.size()];
- for (int i= 0; i < fParameterInfos.size(); i++) {
- ParameterInfo info= (ParameterInfo) fParameterInfos.get(i);
- excludedParamNames[i]= info.getNewName();
- }
- IJavaScriptProject javaProject= fTypeContext.getCuHandle().getJavaScriptProject();
- String newParamName= StubUtility.suggestArgumentName(javaProject, RefactoringMessages.ChangeParametersControl_new_parameter_default_name, excludedParamNames);
- ParameterInfo newInfo= ParameterInfo.createInfoForAddedParameter("Object", newParamName, "null"); //$NON-NLS-1$ //$NON-NLS-2$
- int insertIndex= fParameterInfos.size();
- for (int i= fParameterInfos.size() - 1; i >= 0; i--) {
- ParameterInfo info= (ParameterInfo) fParameterInfos.get(i);
- if (info.isNewVarargs()) {
- insertIndex= i;
- break;
- }
- }
- fParameterInfos.add(insertIndex, newInfo);
- fListener.parameterAdded(newInfo);
- fTableViewer.refresh();
- fTableViewer.getControl().setFocus();
- fTableViewer.setSelection(new StructuredSelection(newInfo), true);
- updateButtonsEnabledState();
- editColumnOrNextPossible(0);
- }
- });
- return button;
- }
-
- private Button createRemoveButton(Composite buttonComposite) {
- final Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.ChangeParametersControl_buttons_remove);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int index= getTable().getSelectionIndices()[0];
- ParameterInfo[] selected= getSelectedElements();
- for (int i= 0; i < selected.length; i++) {
- if (selected[i].isAdded())
- fParameterInfos.remove(selected[i]);
- else
- selected[i].markAsDeleted();
- }
- restoreSelection(index);
- }
- private void restoreSelection(int index) {
- fTableViewer.refresh();
- fTableViewer.getControl().setFocus();
- int itemCount= getTableItemCount();
- if (itemCount != 0 && index >= itemCount) {
- index= itemCount - 1;
- getTable().setSelection(index);
- }
- fListener.parameterListChanged();
- updateButtonsEnabledState();
- }
- });
- return button;
- }
-
- private Button createButton(Composite buttonComposite, String text, final boolean up) {
- Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(text);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- ISelection savedSelection= fTableViewer.getSelection();
- if (savedSelection == null)
- return;
- ParameterInfo[] selection= getSelectedElements();
- if (selection.length == 0)
- return;
-
- if (up) {
- moveUp(selection);
- } else {
- moveDown(selection);
- }
- fTableViewer.refresh();
- fTableViewer.setSelection(savedSelection);
- fListener.parameterListChanged();
- fTableViewer.getControl().setFocus();
- }
- });
- return button;
- }
-
- //---- editing -----------------------------------------------------------------------------------------------
-
- private void addCellEditors() {
- fTableViewer.setColumnProperties(PROPERTIES);
-
- final TableTextCellEditor editors[]= new TableTextCellEditor[PROPERTIES.length];
-
- if(JavaScriptCore.IS_ECMASCRIPT4) editors[TYPE_PROP]= new TableTextCellEditor(fTableViewer, TYPE_PROP);
- editors[NEWNAME_PROP]= new TableTextCellEditor(fTableViewer, NEWNAME_PROP);
- editors[DEFAULT_PROP]= new TableTextCellEditor(fTableViewer, DEFAULT_PROP);
-
- if (fMode.canChangeTypes() && (JavaScriptCore.IS_ECMASCRIPT4) ) {
- SubjectControlContentAssistant assistant= installParameterTypeContentAssist(editors[TYPE_PROP].getText());
- editors[TYPE_PROP].setContentAssistant(assistant);
- }
- if (fParamNameProposals.length > 0 ) {
- SubjectControlContentAssistant assistant= installParameterNameContentAssist(editors[NEWNAME_PROP].getText());
- editors[NEWNAME_PROP].setContentAssistant(assistant);
- }
-
- for (int i = 0; i < editors.length; i++) {
- final int editorColumn= i;
- final TableTextCellEditor editor = editors[i];
- // support tabbing between columns while editing:
- editor.getText().addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- switch (e.detail) {
- case SWT.TRAVERSE_TAB_NEXT :
- editColumnOrNextPossible(nextColumn(editorColumn));
- e.detail= SWT.TRAVERSE_NONE;
- break;
-
- case SWT.TRAVERSE_TAB_PREVIOUS :
- editColumnOrPrevPossible(prevColumn(editorColumn));
- e.detail= SWT.TRAVERSE_NONE;
- break;
-
- default :
- break;
- }
- }
- });
- TextFieldNavigationHandler.install(editor.getText());
- }
-
- editors[NEWNAME_PROP].setActivationListener(new TableTextCellEditor.IActivationListener(){
- public void activate() {
- ParameterInfo[] selected= getSelectedElements();
- if (selected.length == 1 && fNameContentAssistHandler != null) {
- fNameContentAssistHandler.setEnabled(selected[0].isAdded());
- }
- }
- });
-
- fTableViewer.setCellEditors(editors);
- fTableViewer.setCellModifier(new ParametersCellModifier());
- }
-
- private SubjectControlContentAssistant installParameterTypeContentAssist(Text text) {
- JavaTypeCompletionProcessor processor= new JavaTypeCompletionProcessor(true, false);
- if (fTypeContext == null)
- processor.setCompletionContext(null, null, null);
- else
- processor.setCompletionContext(fTypeContext.getCuHandle(), fTypeContext.getBeforeString(), fTypeContext.getAfterString());
- SubjectControlContentAssistant contentAssistant= ControlContentAssistHelper.createJavaContentAssistant(processor);
- ContentAssistHandler.createHandlerForText(text, contentAssistant);
- return contentAssistant;
- }
-
- private SubjectControlContentAssistant installParameterNameContentAssist(Text text) {
- VariableNamesProcessor processor= new VariableNamesProcessor(fParamNameProposals);
- SubjectControlContentAssistant contentAssistant= ControlContentAssistHelper.createJavaContentAssistant(processor);
- fNameContentAssistHandler= ContentAssistHandler.createHandlerForText(text, contentAssistant);
- return contentAssistant;
- }
-
- //---- change order ----------------------------------------------------------------------------------------
-
- private void moveUp(ParameterInfo[] selection) {
- moveUp(fParameterInfos, Arrays.asList(selection));
- }
-
- private void moveDown(ParameterInfo[] selection) {
- Collections.reverse(fParameterInfos);
- moveUp(fParameterInfos, Arrays.asList(selection));
- Collections.reverse(fParameterInfos);
- }
-
- private static void moveUp(List elements, List move) {
- List res= new ArrayList(elements.size());
- List deleted= new ArrayList();
- Object floating= null;
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object curr= iter.next();
- if (move.contains(curr)) {
- res.add(curr);
- } else if (((ParameterInfo) curr).isDeleted()) {
- deleted.add(curr);
- } else {
- if (floating != null)
- res.add(floating);
- floating= curr;
- }
- }
- if (floating != null) {
- res.add(floating);
- }
- res.addAll(deleted);
- elements.clear();
- for (Iterator iter= res.iterator(); iter.hasNext();) {
- elements.add(iter.next());
- }
- }
-
- private boolean canMove(boolean up) {
- int notDeletedInfosCount= getNotDeletedInfosCount();
- if (notDeletedInfosCount == 0)
- return false;
- int[] indc= getTable().getSelectionIndices();
- if (indc.length == 0)
- return false;
- int invalid= up ? 0 : notDeletedInfosCount - 1;
- for (int i= 0; i < indc.length; i++) {
- if (indc[i] == invalid)
- return false;
- }
- return true;
- }
-
- private int getNotDeletedInfosCount(){
- if (fParameterInfos == null) // during initialization
- return 0;
- int result= 0;
- for (Iterator iter= fParameterInfos.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if (! info.isDeleted())
- result++;
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeSignatureWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeSignatureWizard.java
deleted file mode 100644
index 0d6d6785..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeSignatureWizard.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-public class ChangeSignatureWizard extends RefactoringWizard {
-
- public ChangeSignatureWizard(ChangeSignatureRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.ChangeSignatureRefactoring_modify_Parameters);
- }
-
- protected void addUserInputPages(){
- addPage(new ChangeSignatureInputPage());
- }
-
- private static class ChangeSignatureInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "ChangeSignatureInputPage"; //$NON-NLS-1$
- private JavaSourceViewer fSignaturePreview;
- private Document fSignaturePreviewDocument;
- private Button fLeaveDelegateCheckBox;
- private Button fDeprecateDelegateCheckBox;
-
- public ChangeSignatureInputPage() {
- super(PAGE_NAME);
- setMessage(RefactoringMessages.ChangeSignatureInputPage_change);
- fSignaturePreviewDocument= new Document();
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- composite.setLayout(layout);
- initializeDialogUnits(composite);
-
- try {
- createHeadControls(composite);
-
-
- createParameterExceptionsFolder(composite);
- fLeaveDelegateCheckBox= DelegateUIHelper.generateLeaveDelegateCheckbox(composite, getRefactoring(), false);
- if (fLeaveDelegateCheckBox != null) {
- fDeprecateDelegateCheckBox= new Button(composite, SWT.CHECK);
- GridData data= new GridData();
- data.horizontalAlignment= GridData.FILL;
- data.horizontalIndent= (layout.marginWidth + fDeprecateDelegateCheckBox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- data.horizontalSpan= 2;
- fDeprecateDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox.setText(DelegateUIHelper.getDeprecateDelegateCheckBoxTitle());
- final ChangeSignatureRefactoring refactoring= getChangeMethodSignatureRefactoring();
- fDeprecateDelegateCheckBox.setSelection(DelegateUIHelper.loadDeprecateDelegateSetting(refactoring));
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- fDeprecateDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- }
- });
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
- Label sep= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- sep.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- createSignaturePreview(composite);
-
- update(false);
- setControl(composite);
- Dialog.applyDialogFont(composite);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ChangeSignatureInputPage_Change_Signature, RefactoringMessages.ChangeSignatureInputPage_Internal_Error);
- }
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.MODIFY_PARAMETERS_WIZARD_PAGE);
- }
-
- private void createHeadControls(Composite parent) throws JavaScriptModelException {
- //must create controls column-wise to get mnemonics working:
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout layout= new GridLayout(3, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- createAccessControl(composite);
- createReturnTypeControl(composite);
- }
- createNameControl(composite);
- }
-
- private void createAccessControl(Composite parent) throws JavaScriptModelException {
- Composite access= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- access.setLayout(layout);
-
- final int[] availableVisibilities= getChangeMethodSignatureRefactoring().getAvailableVisibilities();
- int currentVisibility= getChangeMethodSignatureRefactoring().getVisibility();
-
- Label label= new Label(access, SWT.NONE);
- label.setText(RefactoringMessages.ChangeSignatureInputPage_access_modifier);
-
- final Combo combo= new Combo(access, SWT.DROP_DOWN | SWT.READ_ONLY);
- if (availableVisibilities.length == 0) {
- combo.setEnabled(false);
- } else {
- for (int i= 0; i < availableVisibilities.length; i++) {
- combo.add(getAccessModifierString(availableVisibilities[i]));
- }
- combo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int newVisibility= availableVisibilities[combo.getSelectionIndex()];
- getChangeMethodSignatureRefactoring().setVisibility(newVisibility);
- update(true);
- }
- });
- }
- combo.setText(getAccessModifierString(currentVisibility));
- combo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // ensure that "Access modifier:" and "Return type:" Labels are not too close:
- Dialog.applyDialogFont(access);
- access.pack();
- int minLabelWidth= label.getSize().x + 3 * layout.horizontalSpacing;
- if (minLabelWidth > combo.getSize().x)
- label.setLayoutData(new GridData(minLabelWidth, label.getSize().y));
- }
-
- private String getAccessModifierString(int modifier) {
- switch (modifier) {
- case Modifier.PUBLIC :
- return JdtFlags.VISIBILITY_STRING_PUBLIC;
- case Modifier.PROTECTED :
- return JdtFlags.VISIBILITY_STRING_PROTECTED;
- case Modifier.NONE :
- return RefactoringMessages.ChangeSignatureInputPage_default;
- case Modifier.PRIVATE :
- return JdtFlags.VISIBILITY_STRING_PRIVATE;
- default :
- throw new IllegalArgumentException("\"" + modifier + "\" is not a Modifier constant"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- private void createReturnTypeControl(Composite parent) {
- Composite returnType= new Composite(parent, SWT.NONE);
- returnType.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout(1, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- returnType.setLayout(layout);
-
- Label label= new Label(returnType, SWT.NONE);
- label.setText(RefactoringMessages.ChangeSignatureInputPage_return_type);
-
- final Text text= new Text(returnType, SWT.BORDER);
- text.setText(getChangeMethodSignatureRefactoring().getReturnTypeString());
- text.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- TextFieldNavigationHandler.install(text);
-
- if (getChangeMethodSignatureRefactoring().canChangeNameAndReturnType()) {
- text.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- getChangeMethodSignatureRefactoring().setNewReturnTypeName(text.getText());
- update(true);
- }
- });
- } else {
- text.setEnabled(false);
- }
-
- JavaTypeCompletionProcessor processor= new JavaTypeCompletionProcessor(true, true);
- StubTypeContext stubTypeContext= getChangeMethodSignatureRefactoring().getStubTypeContext();
- processor.setCompletionContext(stubTypeContext.getCuHandle(), stubTypeContext.getBeforeString(), stubTypeContext.getAfterString());
- ControlContentAssistHelper.createTextContentAssistant(text, processor);
- }
-
- private void createNameControl(Composite parent) {
- Composite name= new Composite(parent, SWT.NONE);
- name.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout(1, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- name.setLayout(layout);
-
- Label label= new Label(name, SWT.NONE);
- label.setText(RefactoringMessages.ChangeSignatureInputPage_method_name);
-
- final Text text= new Text(name, SWT.BORDER);
- text.setText(getChangeMethodSignatureRefactoring().getMethodName());
- text.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- TextFieldNavigationHandler.install(text);
-
- if (getChangeMethodSignatureRefactoring().canChangeNameAndReturnType()) {
- text.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- getChangeMethodSignatureRefactoring().setNewMethodName(text.getText());
- update(true);
- }
- });
- } else {
- text.setEnabled(false);
- }
- }
-
- private void createParameterExceptionsFolder(Composite composite) {
- TabFolder folder= new TabFolder(composite, SWT.TOP);
- folder.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- TabItem item= new TabItem(folder, SWT.NONE);
- item.setText(RefactoringMessages.ChangeSignatureInputPage_parameters);
- item.setControl(createParameterTableControl(folder));
- if(JavaScriptCore.IS_ECMASCRIPT4) {
- TabItem itemEx= new TabItem(folder, SWT.NONE);
- itemEx.setText(RefactoringMessages.ChangeSignatureInputPage_exceptions);
- itemEx.setControl(createExceptionsTableControl(folder));
- }
- folder.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- ((TabItem) e.item).getControl().setFocus();
- }
- });
- }
-
- private Control createParameterTableControl(Composite composite) {
-
- Composite border= new Composite(composite, SWT.NONE);
- border.setLayout(new GridLayout());
-
- String labelText= null; //no label
- ChangeParametersControl cp= new ChangeParametersControl(border, SWT.NONE, labelText, new IParameterListChangeListener() {
- public void parameterChanged(ParameterInfo parameter) {
- update(true);
- }
- public void parameterListChanged() {
- update(true);
- }
- public void parameterAdded(ParameterInfo parameter) {
- update(true);
- }
- }, ChangeParametersControl.Mode.CHANGE_METHOD_SIGNATURE, getChangeMethodSignatureRefactoring().getStubTypeContext());
- cp.setLayoutData(new GridData(GridData.FILL_BOTH));
- cp.setInput(getChangeMethodSignatureRefactoring().getParameterInfos());
- return border;
- }
-
- private Control createExceptionsTableControl(Composite parent) {
- Composite border= new Composite(parent, SWT.NONE);
- border.setLayout(new GridLayout());
-
- ChangeExceptionsControl cp= new ChangeExceptionsControl(border, SWT.NONE, new IExceptionListChangeListener() {
- public void exceptionListChanged() {
- update(true);
- }
- }, getChangeMethodSignatureRefactoring().getMethod().getJavaScriptProject());
- cp.setLayoutData(new GridData(GridData.FILL_BOTH));
- cp.setInput(getChangeMethodSignatureRefactoring().getExceptionInfos());
- return border;
- }
-
- public void dispose() {
- DelegateUIHelper.saveLeaveDelegateSetting(fLeaveDelegateCheckBox);
- DelegateUIHelper.saveDeprecateDelegateSetting(fDeprecateDelegateCheckBox);
- super.dispose();
- }
-
- private void createSignaturePreview(Composite composite) {
- Label previewLabel= new Label(composite, SWT.NONE);
- previewLabel.setText(RefactoringMessages.ChangeSignatureInputPage_method_Signature_Preview);
-
-// //XXX: use ViewForm to draw a flat border. Beware of common problems with wrapping layouts
-// //inside GridLayout. GridData must be constrained to force wrapping. See bug 9866 et al.
-// ViewForm border= new ViewForm(composite, SWT.BORDER | SWT.FLAT);
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSignaturePreview= new JavaSourceViewer(composite, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP /*| SWT.BORDER*/, store);
- fSignaturePreview.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- fSignaturePreview.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- fSignaturePreview.getTextWidget().setBackground(composite.getBackground());
- fSignaturePreview.setDocument(fSignaturePreviewDocument);
- fSignaturePreview.setEditable(false);
-
- //Layouting problems with wrapped text: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=9866
- Control signaturePreviewControl= fSignaturePreview.getControl();
- PixelConverter pixelConverter= new PixelConverter(signaturePreviewControl);
- GridData gdata= new GridData(GridData.FILL_BOTH);
- gdata.widthHint= pixelConverter.convertWidthInCharsToPixels(50);
- gdata.heightHint= pixelConverter.convertHeightInCharsToPixels(2);
- signaturePreviewControl.setLayoutData(gdata);
-
-// //XXX must force JavaSourceViewer text widget to wrap:
-// border.setContent(signaturePreviewControl);
-// GridData borderData= new GridData(GridData.FILL_BOTH);
-// borderData.widthHint= gdata.widthHint;
-// borderData.heightHint= gdata.heightHint;
-// border.setLayoutData(borderData);
- }
-
- private ChangeSignatureRefactoring getChangeMethodSignatureRefactoring(){
- return (ChangeSignatureRefactoring)getRefactoring();
- }
-
- private void update(boolean displayErrorMessage){
- updateStatus(displayErrorMessage);
- updateSignaturePreview();
- }
-
- private void updateStatus(boolean displayErrorMessage) {
- try{
- if (getChangeMethodSignatureRefactoring().isSignatureSameAsInitial()){
- if (displayErrorMessage)
- setErrorMessage(RefactoringMessages.ChangeSignatureInputPage_unchanged);
- else
- setErrorMessage(null);
- setPageComplete(false);
- return;
- }
- RefactoringStatus nameCheck= getChangeMethodSignatureRefactoring().checkSignature();
- if (displayErrorMessage) {
- setPageComplete(nameCheck);
- } else {
- setErrorMessage(null);
- setPageComplete(true);
- }
- } catch (JavaScriptModelException e){
- setErrorMessage(RefactoringMessages.ChangeSignatureInputPage_Internal_Error);
- setPageComplete(false);
- JavaScriptPlugin.log(e);
- }
- }
-
- private void updateSignaturePreview() {
- try{
- int top= fSignaturePreview.getTextWidget().getTopPixel();
- fSignaturePreviewDocument.set(getChangeMethodSignatureRefactoring().getNewMethodSignature());
- fSignaturePreview.getTextWidget().setTopPixel(top);
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.ChangeSignatureRefactoring_modify_Parameters, RefactoringMessages.ChangeSignatureInputPage_exception);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeContentProvider.java
deleted file mode 100644
index 583065d6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeContentProvider.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
-
-class ChangeTypeContentProvider implements ITreeContentProvider {
-
- private ChangeTypeRefactoring fGeneralizeType;
-
- ChangeTypeContentProvider(ChangeTypeRefactoring gt){
- fGeneralizeType= gt;
- }
-
- public Object[] getChildren(Object element) {
- if (element instanceof RootType){
- return ((RootType)element).getChildren();
- }
- Object[] superTypes = getDirectSuperTypes((ITypeBinding)element).toArray();
- Arrays.sort(superTypes, new Comparator(){
- public int compare(Object o1, Object o2) {
- String name1 = ((ITypeBinding)o1).getQualifiedName();
- String name2 = ((ITypeBinding)o2).getQualifiedName();
- return name1.compareTo(name2);
- }
- });
- return superTypes;
- }
-
- /**
- * Returns the direct superclass and direct superinterfaces. Class Object is
- * included in the result if the root of the hierarchy is a top-level
- * interface.
- */
- public Set/*<ITypeBinding>*/ getDirectSuperTypes(ITypeBinding type){
- Set/*<ITypeBinding>*/ result= new HashSet();
- if (type.getSuperclass() != null){
- result.add(type.getSuperclass());
- }
- return result;
- }
-
- public Object[] getElements(Object element) {
- Assert.isTrue(element instanceof RootType);
- return ((RootType)element).getChildren();
- }
-
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- public Object getParent(Object element) {
- return null;
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- /**
- * Artificial "root node" of the tree view. This is needed to handle situations where the replacement
- * types do not have a single common supertype. Also, the tree view does not show the root node by
- * default.
- */
- static class RootType {
- RootType(ITypeBinding root){
- fRoot = root;
- }
- public ITypeBinding[] getChildren(){
- return new ITypeBinding[]{ fRoot };
- }
- private ITypeBinding fRoot;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeWizard.java
deleted file mode 100644
index 0e024db7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ChangeTypeWizard.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-
-
-/**
- * @author tip
- */
-public class ChangeTypeWizard extends RefactoringWizard {
-
- private ChangeTypeRefactoring fCT;
-
- public ChangeTypeWizard(ChangeTypeRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.ChangeTypeWizard_title);
- fCT= ref;
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new ChangeTypeInputPage());
- }
-
- // For debugging
- static String print(Collection/*<ITypeBinding>*/ types){
- if (types.isEmpty())
- return "{ }"; //$NON-NLS-1$
- String result = "{ "; //$NON-NLS-1$
- for (Iterator it=types.iterator(); it.hasNext(); ){
- ITypeBinding type= (ITypeBinding)it.next();
- result += type.getQualifiedName();
- if (it.hasNext()){
- result += ", "; //$NON-NLS-1$
- } else {
- result += " }"; //$NON-NLS-1$
- }
- }
- return result;
- }
-
-
- /**
- * A JavaScriptElementLabelProvider that supports graying out of invalid types.
- */
- private class ChangeTypeLabelProvider extends BindingLabelProvider
- implements IColorProvider {
-
- private Color fGrayColor;
- private HashMap/*<Image color, Image gray>*/ fGrayImages;
-
- public ChangeTypeLabelProvider(){
- fGrayColor= Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
- fGrayImages= new HashMap();
- }
-
- private Collection/*<ITypeBinding>*/ fInvalidTypes;
-
- public void grayOut(Collection/*<ITypeBinding>*/ invalidTypes){
- fInvalidTypes= invalidTypes;
- /*
- * Invalidate all labels. Invalidating only invalid types doesn't
- * work since there can be multiple nodes in the tree that
- * correspond to the same invalid IType. The TreeViewer only updates
- * the label of one of these ITypes and leaves the others in their
- * old state.
- */
- fireLabelProviderChanged(new LabelProviderChangedEvent(this));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- if (isInvalid(element))
- return fGrayColor;
- else
- return null;
- }
-
- private boolean isInvalid(Object element) {
- if (fInvalidTypes == null)
- return false; // initially, everything is enabled
- else
- return fInvalidTypes.contains(element);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- Image image= super.getImage(element);
- if (isInvalid(element) && image != null) {
- Image grayImage= (Image) fGrayImages.get(image);
- if (grayImage == null) {
- grayImage= new Image(Display.getCurrent(), image, SWT.IMAGE_GRAY);
- fGrayImages.put(image, grayImage);
- }
- return grayImage;
- } else {
- return image;
- }
- }
-
- public void dispose() {
- for (Iterator iter= fGrayImages.values().iterator(); iter.hasNext();) {
- Image image= (Image) iter.next();
- image.dispose();
- }
- fGrayImages.clear();
- super.dispose();
- }
- }
-
- private class ChangeTypeInputPage extends UserInputWizardPage{
-
- public static final String PAGE_NAME= "ChangeTypeInputPage";//$NON-NLS-1$
- private final String MESSAGE= RefactoringMessages.ChangeTypeInputPage_Select_Type;
- private ChangeTypeLabelProvider fLabelProvider;
- private TreeViewer fTreeViewer;
- private boolean fTreeUpdated= false;
-
- public ChangeTypeInputPage() {
- super(PAGE_NAME);
- setMessage(MESSAGE);
- }
-
- private class ValidTypesTask implements Runnable {
- private Collection/*<ITypeBinding>*/ fInvalidTypes;
- private Collection/*<ITypeBinding>*/ fValidTypes;
- public void run() {
- IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
- pm.beginTask(RefactoringMessages.ChangeTypeWizard_analyzing, 1000);
- ChangeTypeRefactoring ct= (ChangeTypeRefactoring)ChangeTypeWizard.this.getRefactoring();
- fInvalidTypes = new HashSet();
- fInvalidTypes.addAll(fCT.getAllSuperTypes(ct.getOriginalType()));
- fValidTypes= ct.computeValidTypes(new SubProgressMonitor(pm, 950));
- fInvalidTypes.add(ct.getOriginalType());
- fInvalidTypes.removeAll(fValidTypes);
- pm.worked(50);
- pm.done();
- }
- };
- boolean internalError= false;
- try {
- getWizard().getContainer().run(true, true, runnable);
- } catch (InvocationTargetException e) {
- internalError= true;
- JavaScriptPlugin.log(e);
- ChangeTypeInputPage.this.setErrorMessage(RefactoringMessages.ChangeTypeWizard_internalError);
- } catch (InterruptedException e) {
- ChangeTypeInputPage.this.setMessage(RefactoringMessages.ChangeTypeWizard_computationInterrupted);
- }
-
- fLabelProvider.grayOut(fInvalidTypes);
-
- if (internalError) {
- setPageComplete(false);
- } else if (fValidTypes == null || fValidTypes.size() == 0){
- ChangeTypeInputPage.this.setErrorMessage(RefactoringMessages.ChangeTypeWizard_declCannotBeChanged);
- setPageComplete(false);
- } else {
- TreeItem selection= getInitialSelection(fValidTypes);
- fTreeViewer.getTree().setSelection(new TreeItem[]{ selection });
- setPageComplete(true);
- ChangeTypeInputPage.this.setMessage(""); //$NON-NLS-1$
- }
- }
- }
-
- private TreeItem getInitialSelection(Collection/*<ITypeBinding>*/ types) {
-
- // first, find a most general valid type (there may be more than one)
- ITypeBinding type= (ITypeBinding)types.iterator().next();
- for (Iterator it= types.iterator(); it.hasNext(); ){
- ITypeBinding other= (ITypeBinding)it.next();
- if (getGeneralizeTypeRefactoring().isSubTypeOf(type, other)){
- type= other;
- }
- }
-
- // now find a corresponding TreeItem (there may be more than one)
- return findItem(fTreeViewer.getTree().getItems(), type);
- }
-
- private TreeItem findItem(TreeItem[] items, ITypeBinding type){
- for (int i=0; i < items.length; i++){
- if (items[i].getData().equals(type)) return items[i];
- }
- for (int i=0; i < items.length; i++){
- TreeItem item= findItem(items[i].getItems(), type);
- if (item != null) return item;
- }
- return null;
- }
-
-
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- setControl(composite);
- composite.setLayout(new GridLayout());
- composite.setLayoutData(new GridData());
-
- Label label= new Label(composite, SWT.NONE);
- label.setText(Messages.format(
- RefactoringMessages.ChangeTypeWizard_pleaseChooseType,
- ((ChangeTypeRefactoring) getRefactoring()).getTarget()));
- label.setLayoutData(new GridData());
-
- addTreeComponent(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CHANGE_TYPE_WIZARD_PAGE);
- }
-
- /**
- * Tree-viewer that shows the allowable types in a tree view.
- */
- private void addTreeComponent(Composite parent) {
- fTreeViewer= new TreeViewer(parent, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.grabExcessHorizontalSpace= true;
- gd.grabExcessVerticalSpace= true;
- GC gc= null;
- try {
- gc= new GC(parent);
- gc.setFont(gc.getFont());
- gd.heightHint= Dialog.convertHeightInCharsToPixels(gc.getFontMetrics(), 6); // 6 characters tall
- } finally {
- if (gc != null) {
- gc.dispose();
- gc= null;
- }
- }
- fTreeViewer.getTree().setLayoutData(gd);
-
- fTreeViewer.setContentProvider(new ChangeTypeContentProvider(((ChangeTypeRefactoring)getRefactoring())));
- fLabelProvider= new ChangeTypeLabelProvider();
- fTreeViewer.setLabelProvider(fLabelProvider);
- ISelectionChangedListener listener= new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection selection= (IStructuredSelection)event.getSelection();
- typeSelected((ITypeBinding)selection.getFirstElement());
- }
- };
- fTreeViewer.addSelectionChangedListener(listener);
- fTreeViewer.setInput(new ChangeTypeContentProvider.RootType(getGeneralizeTypeRefactoring().getOriginalType()));
- fTreeViewer.expandToLevel(10);
- }
-
- private void typeSelected(ITypeBinding type) {
- boolean isValid= getGeneralizeTypeRefactoring().getValidTypes().contains(type);
- ChangeTypeInputPage.this.setPageComplete(isValid);
- if (isValid) {
- ChangeTypeInputPage.this.setMessage(""); //$NON-NLS-1$
- } else {
- if (getGeneralizeTypeRefactoring().getOriginalType().equals(type)) {
- ChangeTypeInputPage.this.setMessage(Messages.format(
- RefactoringMessages.ChangeTypeWizard_with_itself, type.getName()));
-
- } else {
- ChangeTypeInputPage.this.setMessage(Messages.format(
- RefactoringMessages.ChangeTypeWizard_grayed_types,
- new Object[] {type.getName(), getGeneralizeTypeRefactoring().getOriginalType().getName()}));
- }
- }
- }
-
- private ChangeTypeRefactoring getGeneralizeTypeRefactoring(){
- return (ChangeTypeRefactoring)getRefactoring();
- }
- /*
- * @see org.eclipse.jface.wizard.IWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- initializeRefactoring();
- return super.getNextPage();
- }
-
- private ITypeBinding getSelectedType() {
- IStructuredSelection ss= (IStructuredSelection)fTreeViewer.getSelection();
- return (ITypeBinding)ss.getFirstElement();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringWizardPage#performFinish()
- */
- public boolean performFinish(){
- initializeRefactoring();
- return super.performFinish();
- }
-
- private void initializeRefactoring() {
- getGeneralizeTypeRefactoring().setSelectedType(getSelectedType());
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#dispose()
- */
- public void dispose() {
- fTreeViewer= null;
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible && fTreeViewer != null)
- fTreeViewer.getTree().setFocus();
- if (!fTreeUpdated){
- fTreeViewer.getTree().getDisplay().asyncExec(new ValidTypesTask());
- fTreeUpdated= true;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ComboSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ComboSelectionDialog.java
deleted file mode 100644
index 447c6669..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ComboSelectionDialog.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-
-
-class ComboSelectionDialog extends Dialog{
-
- private String fSelection= null;
- private final String fShellTitle;
- private final String fLabelText;
- private final String[] fAllowedStrings;
- private final int fInitialSelectionIndex;
- public ComboSelectionDialog(Shell parentShell, String shellTitle, String labelText, String[] comboStrings, int initialSelectionIndex) {
- super(parentShell);
- Assert.isNotNull(shellTitle);
- Assert.isNotNull(labelText);
- Assert.isTrue(comboStrings.length > 0);
- Assert.isTrue(initialSelectionIndex >= 0 && initialSelectionIndex < comboStrings.length);
- fShellTitle= shellTitle;
- fLabelText= labelText;
- fAllowedStrings= comboStrings;
- fInitialSelectionIndex= initialSelectionIndex;
- }
-
- String getSelectedString(){
- return fSelection;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- getShell().setText(fShellTitle);
-
- Composite composite = (Composite)super.createDialogArea(parent);
- Composite innerComposite = new Composite(composite, SWT.NONE);
- innerComposite.setLayoutData(new GridData());
- GridLayout gl= new GridLayout();
- gl.numColumns= 2;
- innerComposite.setLayout(gl);
-
- Label label= new Label(innerComposite, SWT.NONE);
- label.setText(fLabelText);
- label.setLayoutData(new GridData());
-
- final Combo combo= new Combo(innerComposite, SWT.READ_ONLY);
- for (int i = 0; i < fAllowedStrings.length; i++) {
- combo.add(fAllowedStrings[i]);
- }
- combo.select(fInitialSelectionIndex);
- fSelection= combo.getItem(combo.getSelectionIndex());
- GridData gd= new GridData();
- gd.widthHint= convertWidthInCharsToPixels(getMaxStringLength());
- combo.setLayoutData(gd);
- combo.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fSelection= combo.getItem(combo.getSelectionIndex());
- }
- });
- applyDialogFont(composite);
- return composite;
- }
-
- private int getMaxStringLength() {
- int max= 0;
- for (int i= 0; i < fAllowedStrings.length; i++) {
- max= Math.max(max, fAllowedStrings[i].length());
- }
- return max;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CompilationUnitChangeNode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CompilationUnitChangeNode.java
deleted file mode 100644
index 9103bf71..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CompilationUnitChangeNode.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup;
-import org.eclipse.ltk.ui.refactoring.LanguageElementNode;
-import org.eclipse.ltk.ui.refactoring.TextEditChangeNode;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class CompilationUnitChangeNode extends TextEditChangeNode {
-
- static final ChildNode[] EMPTY_CHILDREN= new ChildNode[0];
-
- private static class JavaLanguageNode extends LanguageElementNode {
-
- private IJavaScriptElement fJavaElement;
- private static JavaElementImageProvider fgImageProvider= new JavaElementImageProvider();
-
- public JavaLanguageNode(TextEditChangeNode parent, IJavaScriptElement element) {
- super(parent);
- fJavaElement= element;
- Assert.isNotNull(fJavaElement);
- }
-
- public JavaLanguageNode(ChildNode parent, IJavaScriptElement element) {
- super(parent);
- fJavaElement= element;
- Assert.isNotNull(fJavaElement);
- }
-
- public String getText() {
- return JavaScriptElementLabels.getElementLabel(fJavaElement, JavaScriptElementLabels.ALL_DEFAULT);
- }
-
- public ImageDescriptor getImageDescriptor() {
- return fgImageProvider.getJavaImageDescriptor(
- fJavaElement,
- JavaElementImageProvider.OVERLAY_ICONS | JavaElementImageProvider.SMALL_ICONS);
- }
-
- public IRegion getTextRange() throws CoreException {
- ISourceRange range= ((ISourceReference)fJavaElement).getSourceRange();
- return new Region(range.getOffset(), range.getLength());
- }
- }
-
- public CompilationUnitChangeNode(TextEditBasedChange change) {
- super(change);
- }
-
- protected ChildNode[] createChildNodes() {
- final TextEditBasedChange change= getTextEditBasedChange();
- IJavaScriptUnit cunit= (IJavaScriptUnit) change.getAdapter(IJavaScriptUnit.class);
- if (cunit != null) {
- List children= new ArrayList(5);
- Map map= new HashMap(20);
- TextEditBasedChangeGroup[] changes= getSortedChangeGroups(change);
- for (int i= 0; i < changes.length; i++) {
- TextEditBasedChangeGroup tec= changes[i];
- try {
- IJavaScriptElement element= getModifiedJavaElement(tec, cunit);
- if (element.equals(cunit)) {
- children.add(createTextEditGroupNode(this, tec));
- } else {
- JavaLanguageNode pjce= getChangeElement(map, element, children, this);
- pjce.addChild(createTextEditGroupNode(pjce, tec));
- }
- } catch (JavaScriptModelException e) {
- children.add(createTextEditGroupNode(this, tec));
- }
- }
- return (ChildNode[]) children.toArray(new ChildNode[children.size()]);
- } else {
- return EMPTY_CHILDREN;
- }
- }
-
- private static class OffsetComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- TextEditBasedChangeGroup c1= (TextEditBasedChangeGroup)o1;
- TextEditBasedChangeGroup c2= (TextEditBasedChangeGroup)o2;
- int p1= getOffset(c1);
- int p2= getOffset(c2);
- if (p1 < p2)
- return -1;
- if (p1 > p2)
- return 1;
- // same offset
- return 0;
- }
- private int getOffset(TextEditBasedChangeGroup edit) {
- return edit.getRegion().getOffset();
- }
- }
-
- private TextEditBasedChangeGroup[] getSortedChangeGroups(TextEditBasedChange change) {
- TextEditBasedChangeGroup[] edits= change.getChangeGroups();
- List result= new ArrayList(edits.length);
- for (int i= 0; i < edits.length; i++) {
- if (!edits[i].getTextEditGroup().isEmpty())
- result.add(edits[i]);
- }
- Comparator comparator= new OffsetComparator();
- Collections.sort(result, comparator);
- return (TextEditBasedChangeGroup[])result.toArray(new TextEditBasedChangeGroup[result.size()]);
- }
-
- private IJavaScriptElement getModifiedJavaElement(TextEditBasedChangeGroup edit, IJavaScriptUnit cunit) throws JavaScriptModelException {
- IRegion range= edit.getRegion();
- if (range.getOffset() == 0 && range.getLength() == 0)
- return cunit;
- IJavaScriptElement result= cunit.getElementAt(range.getOffset());
- if (result == null)
- return cunit;
-
- try {
- while(true) {
- ISourceReference ref= (ISourceReference)result;
- IRegion sRange= new Region(ref.getSourceRange().getOffset(), ref.getSourceRange().getLength());
- if (result.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT || result.getParent() == null || coveredBy(edit, sRange))
- break;
- result= result.getParent();
- }
- } catch(JavaScriptModelException e) {
- // Do nothing, use old value.
- } catch(ClassCastException e) {
- // Do nothing, use old value.
- }
- return result;
- }
-
- private JavaLanguageNode getChangeElement(Map map, IJavaScriptElement element, List children, TextEditChangeNode cunitChange) {
- JavaLanguageNode result= (JavaLanguageNode)map.get(element);
- if (result != null)
- return result;
- IJavaScriptElement parent= element.getParent();
- if (parent instanceof IJavaScriptUnit) {
- result= new JavaLanguageNode(cunitChange, element);
- children.add(result);
- map.put(element, result);
- } else {
- JavaLanguageNode parentChange= getChangeElement(map, parent, children, cunitChange);
- result= new JavaLanguageNode(parentChange, element);
- parentChange.addChild(result);
- map.put(element, result);
- }
- return result;
- }
-
- private boolean coveredBy(TextEditBasedChangeGroup group, IRegion sourceRegion) {
- int sLength= sourceRegion.getLength();
- if (sLength == 0)
- return false;
- int sOffset= sourceRegion.getOffset();
- int sEnd= sOffset + sLength - 1;
- TextEdit[] edits= group.getTextEdits();
- for (int i= 0; i < edits.length; i++) {
- TextEdit edit= edits[i];
- if (edit.isDeleted())
- return false;
- int rOffset= edit.getOffset();
- int rLength= edit.getLength();
- int rEnd= rOffset + rLength - 1;
- if (rLength == 0) {
- if (!(sOffset < rOffset && rOffset <= sEnd))
- return false;
- } else {
- if (!(sOffset <= rOffset && rEnd <= sEnd))
- return false;
- }
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ConvertAnonymousToNestedWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ConvertAnonymousToNestedWizard.java
deleted file mode 100644
index 604eb35c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ConvertAnonymousToNestedWizard.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-
-public class ConvertAnonymousToNestedWizard extends RefactoringWizard {
-
- public ConvertAnonymousToNestedWizard(ConvertAnonymousToNestedRefactoring ref) {
- super(ref, PREVIEW_EXPAND_FIRST_NODE | DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.ConvertAnonymousToNestedAction_wizard_title);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new ConvertAnonymousToNestedInputPage());
- }
-
- private static class ConvertAnonymousToNestedInputPage extends UserInputWizardPage {
-
- private static final String DESCRIPTION = RefactoringMessages.ConvertAnonymousToNestedInputPage_description;
- public static final String PAGE_NAME= "ConvertAnonymousToNestedInputPage";//$NON-NLS-1$
-
- public ConvertAnonymousToNestedInputPage() {
- super(PAGE_NAME);
- setDescription(DESCRIPTION);
- }
-
- public void createControl(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.verticalSpacing= 8;
- result.setLayout(layout);
-
- addVisibilityControl(result);
- Text textField= addFieldNameField(result);
- addDeclareFinalCheckbox(result);
- addDeclareAsStaticCheckbox(result);
-
- textField.setFocus();
- setPageComplete(false);
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE);
- }
-
- private Text addFieldNameField(Composite result) {
- Label nameLabel= new Label(result, SWT.NONE);
- nameLabel.setText(RefactoringMessages.ConvertAnonymousToNestedInputPage_class_name);
- nameLabel.setLayoutData(new GridData());
-
- final Text classNameField= new Text(result, SWT.BORDER | SWT.SINGLE);
- classNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- classNameField.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- ConvertAnonymousToNestedInputPage.this.getConvertRefactoring().setClassName(classNameField.getText());
- ConvertAnonymousToNestedInputPage.this.updateStatus();
- }
- });
- TextFieldNavigationHandler.install(classNameField);
- return classNameField;
- }
-
- private void updateStatus() {
- setPageComplete(getConvertRefactoring().validateInput());
- }
-
- private void addVisibilityControl(Composite result) {
- int[] availableVisibilities= getConvertRefactoring().getAvailableVisibilities();
- int currectVisibility= getConvertRefactoring().getVisibility();
- IVisibilityChangeListener visibilityChangeListener= new IVisibilityChangeListener(){
- public void visibilityChanged(int newVisibility) {
- getConvertRefactoring().setVisibility(newVisibility);
- }
-
- public void modifierChanged(int modifier, boolean isChecked) {
- }
- };
- Composite visibilityComposite= VisibilityControlUtil.createVisibilityControl(result, visibilityChangeListener, availableVisibilities, currectVisibility);
- if(visibilityComposite != null) {
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- visibilityComposite.setLayoutData(gd);
- }
- }
-
- public void addDeclareFinalCheckbox(Composite result) {
- GridData gd;
- final Button declareFinalCheckbox= new Button(result, SWT.CHECK);
- declareFinalCheckbox.setEnabled(getConvertRefactoring().canEnableSettingFinal());
- declareFinalCheckbox.setSelection(getConvertRefactoring().getDeclareFinal());
- declareFinalCheckbox.setText(RefactoringMessages.ConvertAnonymousToNestedInputPage_declare_final);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- declareFinalCheckbox.setLayoutData(gd);
- declareFinalCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getConvertRefactoring().setDeclareFinal(declareFinalCheckbox.getSelection());
- }
- });
- }
-
- public void addDeclareAsStaticCheckbox(Composite result) {
- GridData gd;
- final Button declareAsStaticCheckbox= new Button(result, SWT.CHECK);
- ConvertAnonymousToNestedRefactoring r= getConvertRefactoring();
- declareAsStaticCheckbox.setEnabled((!r.mustInnerClassBeStatic() && !r.isLocalInnerType()));
- declareAsStaticCheckbox.setSelection(getConvertRefactoring().getDeclareStatic());
- declareAsStaticCheckbox.setText(RefactoringMessages.ConvertAnonymousToNestedInputPage_declare_static);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- declareAsStaticCheckbox.setLayoutData(gd);
- declareAsStaticCheckbox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- getConvertRefactoring().setDeclareStatic(declareAsStaticCheckbox.getSelection());
- }
- });
- }
-
- private ConvertAnonymousToNestedRefactoring getConvertRefactoring(){
- return (ConvertAnonymousToNestedRefactoring)getRefactoring();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CreateTextFileChangePreviewViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CreateTextFileChangePreviewViewer.java
deleted file mode 100644
index 0aadda6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/CreateTextFileChangePreviewViewer.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.ui.refactoring.ChangePreviewViewerInput;
-import org.eclipse.ltk.ui.refactoring.IChangePreviewViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ViewerPane;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-/**
- * Change preview viewer for <code>CreateTextFileChange</code> objects.
- */
-public final class CreateTextFileChangePreviewViewer implements IChangePreviewViewer {
-
- private static class CreateTextFilePreviewer extends ViewerPane {
-
- private ImageDescriptor fDescriptor;
-
- private Image fImage;
-
- public CreateTextFilePreviewer(Composite parent, int style) {
- super(parent, style);
- }
-
- public void setImageDescriptor(ImageDescriptor imageDescriptor) {
- fDescriptor= imageDescriptor;
- }
-
- public void setText(String text) {
- super.setText(text);
- Image current= null;
- if (fDescriptor != null) {
- current= fImage;
- fImage= fDescriptor.createImage();
- } else {
- current= fImage;
- fImage= null;
- }
- setImage(fImage);
- if (current != null) {
- current.dispose();
- }
- }
-
- }
-
- private CreateTextFilePreviewer fPane;
-
- private SourceViewer fSourceViewer;
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT);
- Dialog.applyDialogFont(fPane);
-
- fSourceViewer= new SourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
- fSourceViewer.setEditable(false);
- fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- fPane.setContent(fSourceViewer.getControl());
- }
-
- /**
- * {@inheritDoc}
- */
- public Control getControl() {
- return fPane;
- }
-
- public void refresh() {
- fSourceViewer.refresh();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInput(ChangePreviewViewerInput input) {
- Change change= input.getChange();
- if (change != null) {
- Object element= change.getModifiedElement();
- if (element instanceof IAdaptable) {
- IAdaptable adaptable= (IAdaptable) element;
- IWorkbenchAdapter workbenchAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class);
- if (workbenchAdapter != null) {
- fPane.setImageDescriptor(workbenchAdapter.getImageDescriptor(element));
- } else {
- fPane.setImageDescriptor(null);
- }
- } else {
- fPane.setImageDescriptor(null);
- }
- }
- if (!(change instanceof CreateTextFileChange)) {
- fSourceViewer.setInput(null);
- fPane.setText(""); //$NON-NLS-1$
- return;
- }
- CreateTextFileChange textFileChange= (CreateTextFileChange) change;
- fPane.setText(textFileChange.getName());
- IDocument document= new Document(textFileChange.getPreview());
- // This is a temporary work around until we get the
- // source viewer registry.
- fSourceViewer.unconfigure();
- String textType= textFileChange.getTextType();
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- if ("java".equals(textType)) { //$NON-NLS-1$
- textTools.setupJavaDocumentPartitioner(document);
- fSourceViewer.configure(new JavaScriptSourceViewerConfiguration(textTools.getColorManager(), store, null, null));
- }
-// else if ("properties".equals(textType)) { //$NON-NLS-1$
-// PropertiesFileDocumentSetupParticipant.setupDocument(document);
-// fSourceViewer.configure(new PropertiesFileSourceViewerConfiguration(textTools.getColorManager(), store, null, IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING));
-// }
- else {
- fSourceViewer.configure(new SourceViewerConfiguration());
- }
- fSourceViewer.setInput(document);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/DelegateUIHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/DelegateUIHelper.java
deleted file mode 100644
index c5e407b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/DelegateUIHelper.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * This is a helper class to keep a consistent design between refactorings
- * capable of creating delegates.
- *
- *
- *
- */
-public class DelegateUIHelper {
-
- public static Button generateDeprecateDelegateCheckbox(Composite parent, Refactoring refactoring) {
- final IDelegateUpdating updating= (IDelegateUpdating) refactoring.getAdapter(IDelegateUpdating.class);
- if (updating == null || !updating.canEnableDelegateUpdating())
- return null;
- final Button button= createCheckbox(parent, getDeprecateDelegateCheckBoxTitle(), loadDeprecateDelegateSetting(updating));
- updating.setDeprecateDelegates(button.getSelection());
- button.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- updating.setDeprecateDelegates(button.getSelection());
- }
- });
- return button;
- }
-
- public static Button generateLeaveDelegateCheckbox(Composite parent, Refactoring refactoring, boolean plural) {
- final IDelegateUpdating updating= (IDelegateUpdating) refactoring.getAdapter(IDelegateUpdating.class);
- if (updating == null || !updating.canEnableDelegateUpdating())
- return null;
- final Button button= createCheckbox(parent, updating.getDelegateUpdatingTitle(plural), loadLeaveDelegateSetting(updating));
- updating.setDelegateUpdating(button.getSelection());
- button.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- updating.setDelegateUpdating(button.getSelection());
- }
- });
- return button;
- }
-
- public static void saveLeaveDelegateSetting(Button button) {
- saveBooleanSetting(DELEGATE_UPDATING, button);
- }
-
- public static void saveDeprecateDelegateSetting(Button button) {
- saveBooleanSetting(DELEGATE_DEPRECATION, button);
- }
-
- public static boolean loadLeaveDelegateSetting(IDelegateUpdating refactoring) {
- return getBooleanSetting(DELEGATE_UPDATING, refactoring.getDelegateUpdating());
- }
-
- public static boolean loadDeprecateDelegateSetting(IDelegateUpdating refactoring) {
- return getBooleanSetting(DELEGATE_DEPRECATION, refactoring.getDeprecateDelegates());
- }
-
- public static String getDeprecateDelegateCheckBoxTitle() {
- return RefactoringMessages.DelegateCreator_deprecate_delegates;
- }
-
- // ************** Helper methods *******************
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String DELEGATE_UPDATING= "delegateUpdating"; //$NON-NLS-1$
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String DELEGATE_DEPRECATION= "delegateDeprecation"; //$NON-NLS-1$
-
- private DelegateUIHelper() {
- // no instances
- }
-
- private static Button createCheckbox(Composite parent, String title, boolean value) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(title);
- checkBox.setSelection(value);
- return checkBox;
- }
-
- private static boolean getBooleanSetting(String key, boolean defaultValue) {
- String update= JavaScriptPlugin.getDefault().getDialogSettings().get(key);
- if (update != null)
- return Boolean.valueOf(update).booleanValue();
- else
- return defaultValue;
- }
-
- private static void saveBooleanSetting(String key, Button button) {
- if (button != null && !button.isDisposed() && button.getEnabled())
- JavaScriptPlugin.getDefault().getDialogSettings().put(key, button.getSelection());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractConstantWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractConstantWizard.java
deleted file mode 100644
index e3b52a1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractConstantWizard.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.VariableNamesProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-public class ExtractConstantWizard extends RefactoringWizard {
-
- private static final String MESSAGE = RefactoringMessages.ExtractConstantInputPage_enter_name;
-
- public ExtractConstantWizard(ExtractConstantRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.ExtractConstantWizard_defaultPageTitle);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
-
- String message= null;
- int messageType= IMessageProvider.NONE;
- if(!getExtractConstantRefactoring().selectionAllStaticFinal()) {
- message= RefactoringMessages.ExtractConstantInputPage_selection_refers_to_nonfinal_fields;
- messageType= IMessageProvider.INFORMATION;
- } else {
- message= MESSAGE;
- messageType= IMessageProvider.NONE;
- }
-
- String[] guessedNames= getExtractConstantRefactoring().guessConstantNames();
- String initialValue= guessedNames.length == 0 ? "" : guessedNames[0]; //$NON-NLS-1$
- addPage(new ExtractConstantInputPage(message, messageType, initialValue, guessedNames));
- }
-
- private ExtractConstantRefactoring getExtractConstantRefactoring(){
- return (ExtractConstantRefactoring) getRefactoring();
- }
-
- private static class ExtractConstantInputPage extends TextInputWizardPage {
- private static final String QUALIFY_REFERENCES= "qualifyReferences"; //$NON-NLS-1$
-
- private Label fLabel;
- private final boolean fInitialValid;
- private final int fOriginalMessageType;
- private final String fOriginalMessage;
-
- private Button fQualifyReferences;
- private String[] fConstNameProposals;
-
- private VariableNamesProcessor fContentAssistProcessor;
- private String fAccessModifier;
-
- public ExtractConstantInputPage(String description, int messageType, String initialValue, String[] guessedNames) {
- super(description, true, initialValue);
- fOriginalMessage= description;
- fOriginalMessageType= messageType;
- fInitialValid= ! ("".equals(initialValue)); //$NON-NLS-1$
- fConstNameProposals= guessedNames;
- }
-
- public void createControl(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.verticalSpacing= 8;
- result.setLayout(layout);
- RowLayouter layouter= new RowLayouter(2);
-
- Label label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ExtractConstantInputPage_constant_name);
-
- Text text= createTextInputField(result);
- text.selectAll();
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (fConstNameProposals.length > 0) {
- fContentAssistProcessor= new VariableNamesProcessor(fConstNameProposals);
- ControlContentAssistHelper.createTextContentAssistant(text, fContentAssistProcessor);
- }
-
- layouter.perform(label, text, 1);
-
- addAccessModifierGroup(result, layouter);
- addReplaceAllCheckbox(result, layouter);
- addQualifyReferencesCheckbox(result, layouter);
- addSeparator(result, layouter);
- addLabel(result, layouter);
-
- validateTextField(text.getText());
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_CONSTANT_WIZARD_PAGE);
- }
-
- private void addAccessModifierGroup(Composite result, RowLayouter layouter) {
- fAccessModifier= getExtractConstantRefactoring().getVisibility();
- if (getExtractConstantRefactoring().getTargetIsInterface())
- return;
-
- Label label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ExtractConstantInputPage_access_modifiers);
-
- Composite group= new Composite(result, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout layout= new GridLayout();
- layout.numColumns= 4; layout.marginWidth= 0;
- group.setLayout(layout);
-
- String[] labels= new String[] {
- RefactoringMessages.ExtractMethodInputPage_public,
- RefactoringMessages.ExtractMethodInputPage_protected,
- RefactoringMessages.ExtractMethodInputPage_default,
- RefactoringMessages.ExtractMethodInputPage_private
- };
- String[] data= new String[] { JdtFlags.VISIBILITY_STRING_PUBLIC,
- JdtFlags.VISIBILITY_STRING_PROTECTED,
- JdtFlags.VISIBILITY_STRING_PACKAGE,
- JdtFlags.VISIBILITY_STRING_PRIVATE }; //
-
- updateContentAssistImage();
- for (int i= 0; i < labels.length; i++) {
- Button radio= new Button(group, SWT.RADIO);
- radio.setText(labels[i]);
- radio.setData(data[i]);
- if (data[i] == fAccessModifier)
- radio.setSelection(true);
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- setAccessModifier((String)event.widget.getData());
- }
- });
- }
- layouter.perform(label, group, 1);
- }
-
- private void updateContentAssistImage() {
- if (fContentAssistProcessor == null)
- return;
-
- int flags;
- if (fAccessModifier == JdtFlags.VISIBILITY_STRING_PRIVATE) {
- flags= Flags.AccPrivate;
- } else if (fAccessModifier == JdtFlags.VISIBILITY_STRING_PUBLIC) {
- flags= Flags.AccPublic;
- } else {
- flags= Flags.AccDefault;
- }
- ImageDescriptor imageDesc= JavaElementImageProvider.getFieldImageDescriptor(false, flags);
- imageDesc= new JavaScriptElementImageDescriptor(imageDesc, JavaScriptElementImageDescriptor.STATIC | JavaScriptElementImageDescriptor.FINAL, JavaElementImageProvider.BIG_SIZE);
- fContentAssistProcessor.setProposalImageDescriptor(imageDesc);
- }
-
- private void addReplaceAllCheckbox(Composite result, RowLayouter layouter) {
- String title= RefactoringMessages.ExtractConstantInputPage_replace_all;
- boolean defaultValue= getExtractConstantRefactoring().replaceAllOccurrences();
- final Button checkBox= createCheckbox(result, title, defaultValue, layouter);
- getExtractConstantRefactoring().setReplaceAllOccurrences(checkBox.getSelection());
- checkBox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getExtractConstantRefactoring().setReplaceAllOccurrences(checkBox.getSelection());
- }
- });
- }
-
- private void addQualifyReferencesCheckbox(Composite result, RowLayouter layouter) {
- String title= RefactoringMessages.ExtractConstantInputPage_qualify_constant_references_with_class_name;
- boolean defaultValue= getBooleanSetting(QUALIFY_REFERENCES, getExtractConstantRefactoring().qualifyReferencesWithDeclaringClassName());
- fQualifyReferences= createCheckbox(result, title, defaultValue, layouter);
- getExtractConstantRefactoring().setQualifyReferencesWithDeclaringClassName(fQualifyReferences.getSelection());
- fQualifyReferences.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getExtractConstantRefactoring().setQualifyReferencesWithDeclaringClassName(fQualifyReferences.getSelection());
- }
- });
- }
-
- private void addLabel(Composite result, RowLayouter layouter) {
- fLabel= new Label(result, SWT.WRAP);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(50);
- fLabel.setLayoutData(gd);
- updatePreviewLabel();
- layouter.perform(fLabel);
- }
-
- private void addSeparator(Composite result, RowLayouter layouter) {
- Label separator= new Label(result, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- layouter.perform(separator);
- }
-
- private void updatePreviewLabel(){
- try {
- if (fLabel != null)
- fLabel.setText(RefactoringMessages.ExtractConstantInputPage_signature_preview + getExtractConstantRefactoring().getConstantSignaturePreview());
- } catch(JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ExtractTempInputPage_extract_local, RefactoringMessages.ExtractConstantInputPage_exception);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#validateTextField(String)
- */
- protected RefactoringStatus validateTextField(String text) {
- try {
- getExtractConstantRefactoring().setConstantName(text);
- updatePreviewLabel();
- RefactoringStatus result= getExtractConstantRefactoring().checkConstantNameOnChange();
- if (fOriginalMessageType == IMessageProvider.INFORMATION && result.getSeverity() == RefactoringStatus.OK)
- return RefactoringStatus.createInfoStatus(fOriginalMessage);
- else
- return result;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return RefactoringStatus.createFatalErrorStatus(RefactoringMessages.ExtractConstantInputPage_Internal_Error);
- }
- }
-
- private void setAccessModifier(String accessModifier) {
- getExtractConstantRefactoring().setVisibility(accessModifier);
- fAccessModifier= accessModifier;
- updateContentAssistImage();
- updatePreviewLabel();
- }
-
- private ExtractConstantRefactoring getExtractConstantRefactoring(){
- return (ExtractConstantRefactoring)getRefactoring();
- }
-
- private static Button createCheckbox(Composite parent, String title, boolean value, RowLayouter layouter){
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(title);
- checkBox.setSelection(value);
- layouter.perform(checkBox);
- return checkBox;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#isInitialInputValid()
- */
- protected boolean isInitialInputValid() {
- return fInitialValid;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#restoreMessage()
- */
- protected void restoreMessage() {
- setMessage(fOriginalMessage, fOriginalMessageType);
- }
-
- private boolean getBooleanSetting(String key, boolean defaultValue) {
- String update= getRefactoringSettings().get(key);
- if (update != null)
- return Boolean.valueOf(update).booleanValue();
- else
- return defaultValue;
- }
-
- private void saveBooleanSetting(String key, Button checkBox) {
- if (checkBox != null)
- getRefactoringSettings().put(key, checkBox.getSelection());
- }
-
- private boolean saveSettings() {
- if (getContainer() instanceof Dialog)
- return ((Dialog)getContainer()).getReturnCode() == IDialogConstants.OK_ID;
- return true;
- }
-
- public void dispose() {
- if (saveSettings()) {
- saveBooleanSetting(QUALIFY_REFERENCES, fQualifyReferences);
- }
- super.dispose();
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMemberPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMemberPage.java
deleted file mode 100644
index d6fafa40..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMemberPage.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Wizard page for the extract supertype refactoring, which, apart from pull up
- * facilities, also allows to specify the types where to extract the supertype.
- *
- *
- */
-public final class ExtractSupertypeMemberPage extends PullUpMemberPage {
-
- /** Dialog to select supertypes */
- private static class SupertypeSelectionDialog extends SelectionDialog {
-
- /** The table viewer */
- private TableViewer fViewer;
-
- /**
- * Creates a new supertype selection dialog.
- *
- * @param shell
- * the parent shell
- */
- public SupertypeSelectionDialog(final Shell shell) {
- super(shell);
- }
-
- /**
- * {@inheritDoc}
- */
- public void create() {
- setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE);
- super.create();
- getShell().setText(RefactoringMessages.ExtractSupertypeMemberPage_choose_type_caption);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Control createDialogArea(final Composite composite) {
- Assert.isNotNull(composite);
- setMessage(RefactoringMessages.ExtractSupertypeMemberPage_choose_type_message);
- final Composite control= (Composite) super.createDialogArea(composite);
- createMessageArea(control);
- fViewer= new TableViewer(control, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- fViewer.setLabelProvider(createLabelProvider());
- fViewer.setContentProvider(new ArrayContentProvider());
- fViewer.setComparator(new SupertypeSelectionViewerSorter());
- fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- setSelectionResult(((IStructuredSelection) fViewer.getSelection()).toArray());
- }
- });
- fViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(final DoubleClickEvent event) {
- setSelectionResult(((IStructuredSelection) fViewer.getSelection()).toArray());
- close();
- }
- });
- final GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= convertHeightInCharsToPixels(15);
- data.widthHint= convertWidthInCharsToPixels(55);
- fViewer.getTable().setLayoutData(data);
- applyDialogFont(control);
- return control;
- }
-
- /**
- * Sets the input of this dialog.
- *
- * @param object
- * the input
- */
- public void setInput(final Object object) {
- fViewer.setInput(object);
- }
- }
-
- /** The label provider */
- private static class SupertypeSelectionLabelProvider extends AppearanceAwareLabelProvider implements ITableLabelProvider {
-
- /**
- * Creates a new supertype selection label provider.
- *
- * @param textFlags
- * the text flags
- * @param imageFlags
- * the image flags
- */
- public SupertypeSelectionLabelProvider(final long textFlags, final int imageFlags) {
- super(textFlags, imageFlags);
- }
-
- /**
- * {@inheritDoc}
- */
- public Image getColumnImage(final Object element, final int index) {
- return getImage(element);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getColumnText(final Object element, final int index) {
- return getText(element);
- }
- }
-
- /** The viewer sorter */
- private static class SupertypeSelectionViewerSorter extends ViewerComparator {
-
- /**
- * {@inheritDoc}
- */
- public int compare(final Viewer viewer, final Object first, final Object second) {
- final IType predecessor= (IType) first;
- final IType successor= (IType) second;
- return getComparator().compare(predecessor.getElementName(), successor.getElementName());
- }
- }
-
- /**
- * Creates a label provider for a type list.
- *
- * @return a label provider
- */
- private static ILabelProvider createLabelProvider() {
- return new SupertypeSelectionLabelProvider(JavaScriptElementLabels.T_TYPE_PARAMETERS | JavaScriptElementLabels.T_POST_QUALIFIED, JavaElementImageProvider.OVERLAY_ICONS);
- }
-
- /** The supertype name field */
- private Text fNameField;
-
- /** The table viewer */
- private TableViewer fTableViewer;
-
- /** The types to extract */
- private final Set fTypesToExtract= new HashSet(2);
-
- /**
- * Creates a new extract supertype member page.
- *
- * @param name
- * the page name
- * @param page
- * the method page
- */
- public ExtractSupertypeMemberPage(final String name, final ExtractSupertypeMethodPage page) {
- super(name, page);
- setDescription(RefactoringMessages.ExtractSupertypeMemberPage_page_title);
- METHOD_LABELS[PULL_UP_ACTION]= RefactoringMessages.ExtractSupertypeMemberPage_extract;
- METHOD_LABELS[DECLARE_ABSTRACT_ACTION]= RefactoringMessages.ExtractSupertypeMemberPage_declare_abstract;
- TYPE_LABELS[PULL_UP_ACTION]= RefactoringMessages.ExtractSupertypeMemberPage_extract;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void checkPageCompletionStatus(final boolean display) {
- final RefactoringStatus status= getProcessor().checkExtractedCompilationUnit();
- setMessage(null);
- if (display)
- setPageComplete(status);
- else
- setPageComplete(!status.hasFatalError());
- fSuccessorPage.fireSettingsChanged();
- }
-
- /**
- * Computes the candidate types.
- *
- * @throws InterruptedException
- * if the computation has been interrupted
- */
- protected void computeCandidateTypes() throws InterruptedException {
- if (fCandidateTypes != null && fCandidateTypes.length > 0)
- return;
- try {
- getWizard().getContainer().run(true, true, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor monitor) throws InvocationTargetException {
- try {
- fCandidateTypes= getProcessor().getCandidateTypes(new RefactoringStatus(), monitor);
- } finally {
- monitor.done();
- }
- }
- });
- } catch (InvocationTargetException exception) {
- ExceptionHandler.handle(exception, getShell(), RefactoringMessages.ExtractSupertypeMemberPage_extract_supertype, RefactoringMessages.PullUpInputPage_exception);
- } catch (InterruptedException exception) {
- fCandidateTypes= new IType[0];
- throw new InterruptedException();
- } catch (OperationCanceledException exception) {
- fCandidateTypes= new IType[0];
- }
- }
-
- /**
- * Creates the button composite.
- *
- * @param parent
- * the parent control
- */
- protected void createButtonComposite(final Composite parent) {
- final Composite buttons= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- buttons.setLayout(layout);
- buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- final Button addButton= new Button(buttons, SWT.PUSH);
- addButton.setText(RefactoringMessages.ExtractSupertypeMemberPage_add_button_label);
- addButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(addButton);
- addButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- try {
- computeCandidateTypes();
- } catch (InterruptedException exception) {
- return;
- }
- final LinkedList list= new LinkedList(Arrays.asList(fCandidateTypes));
- for (final Iterator outer= list.iterator(); outer.hasNext();) {
- final IType first= (IType) outer.next();
- for (final Iterator inner= fTypesToExtract.iterator(); inner.hasNext();) {
- final IType second= (IType) inner.next();
- if (second.getFullyQualifiedName().equals(first.getFullyQualifiedName()))
- outer.remove();
- }
- }
- final SupertypeSelectionDialog dialog= new SupertypeSelectionDialog(getShell());
- dialog.create();
- dialog.setInput(list.toArray());
- final int result= dialog.open();
- if (result == Window.OK) {
- final Object[] objects= dialog.getResult();
- if (objects != null && objects.length > 0) {
- for (int index= 0; index < objects.length; index++) {
- fTypesToExtract.add(objects[index]);
- }
- fTableViewer.setInput(fTypesToExtract.toArray());
- handleTypesChanged();
- }
- }
- }
- });
-
- final Button removeButton= new Button(buttons, SWT.PUSH);
- removeButton.setText(RefactoringMessages.ExtractSupertypeMemberPage_remove_button_label);
- removeButton.setEnabled(fCandidateTypes.length > 0 && !fTableViewer.getSelection().isEmpty());
- removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(removeButton);
- removeButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- final IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
- if (!selection.isEmpty()) {
- final IType declaring= getDeclaringType();
- for (final Iterator iterator= selection.iterator(); iterator.hasNext();) {
- final Object element= iterator.next();
- if (!declaring.equals(element))
- fTypesToExtract.remove(element);
- }
- fTableViewer.setInput(fTypesToExtract.toArray());
- handleTypesChanged();
- }
- }
- });
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- final IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
- if (selection.isEmpty()) {
- removeButton.setEnabled(false);
- return;
- } else {
- final Object[] elements= selection.toArray();
- if (elements.length == 1 && elements[0].equals(getDeclaringType())) {
- removeButton.setEnabled(false);
- return;
- }
- }
- removeButton.setEnabled(true);
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- public void createControl(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- composite.setLayout(layout);
- createSuperTypeField(composite);
- createSpacer(composite);
- createSuperTypeCheckbox(composite);
- createInstanceOfCheckbox(composite, layout.marginWidth);
- createStubCheckbox(composite);
- createSuperTypeControl(composite);
- createSpacer(composite);
- createMemberTableLabel(composite);
- createMemberTableComposite(composite);
- createStatusLine(composite);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- initializeEnablement();
- initializeCheckboxes();
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_SUPERTYPE_WIZARD_PAGE);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void createSuperTypeControl(final Composite parent) {
- try {
- createSuperTypeList(parent);
- } catch (JavaScriptModelException exception) {
- ExceptionHandler.handle(exception, getShell(), RefactoringMessages.ExtractSupertypeMemberPage_extract_supertype, RefactoringMessages.PullUpInputPage_exception);
- }
- }
-
- /**
- * Creates the super type field.
- *
- * @param parent
- * the parent control
- */
- protected void createSuperTypeField(final Composite parent) {
- final Label label= new Label(parent, SWT.NONE);
- label.setText(RefactoringMessages.ExtractSupertypeMemberPage_name_label);
- label.setLayoutData(new GridData());
-
- fNameField= new Text(parent, SWT.BORDER);
- fNameField.addModifyListener(new ModifyListener() {
-
- public void modifyText(ModifyEvent e) {
- handleNameChanged(fNameField.getText());
- }
- });
- fNameField.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
- TextFieldNavigationHandler.install(fNameField);
- }
-
- /**
- * Creates the super type list.
- *
- * @param parent
- * the parent control
- */
- protected void createSuperTypeList(final Composite parent) throws JavaScriptModelException {
- createSpacer(parent);
-
- final Label label= new Label(parent, SWT.NONE);
- label.setText(RefactoringMessages.ExtractSupertypeMemberPage_types_list_caption);
- GridData data= new GridData();
- data.horizontalSpan= 2;
- label.setLayoutData(data);
-
- final Composite composite= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
- data= new GridData(GridData.FILL_BOTH);
- data.horizontalSpan= 2;
- composite.setLayoutData(data);
-
- fTableViewer= new TableViewer(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- data= new GridData(GridData.FILL_BOTH);
- data.heightHint= SWTUtil.getTableHeightHint(fTableViewer.getTable(), 3);
- fTableViewer.getTable().setLayoutData(data);
- fTableViewer.setLabelProvider(createLabelProvider());
- fTableViewer.setContentProvider(new ArrayContentProvider());
- fTableViewer.setComparator(new JavaScriptElementComparator());
- fTypesToExtract.add(getDeclaringType());
- fTableViewer.setInput(fTypesToExtract.toArray());
-
- createButtonComposite(composite);
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getCreateStubsButtonLabel() {
- return RefactoringMessages.ExtractSupertypeMemberPage_create_stubs_label;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getDeclareAbstractActionLabel() {
- return RefactoringMessages.ExtractSupertypeMemberPage_declare_abstract;
- }
-
- /**
- * Returns the declaring type.
- *
- * @return the declaring type
- */
- public IType getDeclaringType() {
- return getProcessor().getDeclaringType();
- }
-
- /**
- * {@inheritDoc}
- */
- public IType getDestinationType() {
- return getProcessor().computeExtractedType(fNameField.getText());
- }
-
- /**
- * Returns the extract supertype refactoring.
- */
- public ExtractSupertypeRefactoring getExtractSuperTypeRefactoring() {
- return (ExtractSupertypeRefactoring) getRefactoring();
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getInstanceofButtonLabel() {
- return RefactoringMessages.ExtractSupertypeMemberPage_use_supertype_label;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getNoMembersMessage() {
- return RefactoringMessages.ExtractSupertypeMemberPage_no_members_selected;
- }
-
- /**
- * Returns the refactoring processor.
- *
- * @return the refactoring processor
- */
- protected ExtractSupertypeProcessor getProcessor() {
- return getExtractSuperTypeRefactoring().getExtractSupertypeProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getPullUpActionLabel() {
- return RefactoringMessages.ExtractSupertypeMemberPage_extract;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getReplaceButtonLabel() {
- return RefactoringMessages.ExtractSupertypeMemberPage_use_instanceof_label;
- }
-
- /**
- * {@inheritDoc}
- */
- protected int getTableRowCount() {
- return 6;
- }
-
- /**
- * Handles the name changed event.
- *
- * @param name
- * the name
- */
- protected void handleNameChanged(final String name) {
- if (name != null)
- getProcessor().setTypeName(name);
- checkPageCompletionStatus(true);
- }
-
- /**
- * Handles the types changed event.
- */
- protected void handleTypesChanged() {
- getProcessor().setTypesToExtract((IType[]) fTypesToExtract.toArray(new IType[fTypesToExtract.size()]));
- }
-
- /**
- * {@inheritDoc}
- */
- public void setVisible(final boolean visible) {
- super.setVisible(visible);
- if (visible) {
- fNameField.setFocus();
- getProcessor().resetChanges();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMethodPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMethodPage.java
deleted file mode 100644
index 0f8f564b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeMethodPage.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ExtractSupertypeRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Wizard page to select methods to be deleted after extract supertype.
- *
- *
- */
-public class ExtractSupertypeMethodPage extends PullUpMethodPage {
-
- /**
- * Returns the extract supertype refactoring.
- */
- public ExtractSupertypeRefactoring getExtractSuperTypeRefactoring() {
- return (ExtractSupertypeRefactoring) getRefactoring();
- }
-
- /**
- * Returns the refactoring processor.
- *
- * @return the refactoring processor
- */
- protected ExtractSupertypeProcessor getProcessor() {
- return getExtractSuperTypeRefactoring().getExtractSupertypeProcessor();
- }
-
- /**
- * {@inheritDoc}
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_SUPERTYPE_WIZARD_PAGE);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setVisible(final boolean visible) {
- if (visible) {
- final ExtractSupertypeProcessor processor= getProcessor();
- processor.resetChanges();
- try {
- getWizard().getContainer().run(false, false, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- processor.createWorkingCopyLayer(monitor);
- }
- });
- } catch (InvocationTargetException exception) {
- JavaScriptPlugin.log(exception);
- } catch (InterruptedException exception) {
- // Does not happen
- }
- }
- super.setVisible(visible);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java
deleted file mode 100644
index 6485a654..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Refactoring wizard for the extract supertype refactoring.
- *
- *
- */
-public final class ExtractSupertypeWizard extends RefactoringWizard {
-
- /** The page name */
- private static final String PAGE_NAME= "ExtractSupertypeMemberPage"; //$NON-NLS-1$
-
- /**
- * Creates a new extract supertype wizard.
- *
- * @param refactoring
- * the refactoring
- */
- public ExtractSupertypeWizard(final Refactoring refactoring) {
- super(refactoring, WIZARD_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.ExtractSupertypeWizard_defaultPageTitle);
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR_EXTRACT_SUPERTYPE);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void addUserInputPages() {
- final ExtractSupertypeMethodPage page= new ExtractSupertypeMethodPage();
- addPage(new ExtractSupertypeMemberPage(PAGE_NAME, page));
- addPage(page);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractTempWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractTempWizard.java
deleted file mode 100644
index fff3a2bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractTempWizard.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractTempRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.VariableNamesProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-
-public class ExtractTempWizard extends RefactoringWizard {
-
- /* package */ static final String DIALOG_SETTING_SECTION= "ExtractTempWizard"; //$NON-NLS-1$
-
- public ExtractTempWizard(ExtractTempRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.ExtractTempWizard_defaultPageTitle);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new ExtractTempInputPage(getExtractTempRefactoring().guessTempNames()));
- }
-
- private ExtractTempRefactoring getExtractTempRefactoring(){
- return (ExtractTempRefactoring)getRefactoring();
- }
-
- private static class ExtractTempInputPage extends TextInputWizardPage {
-
- private static final String DECLARE_FINAL= "declareFinal"; //$NON-NLS-1$
- private static final String REPLACE_ALL= "replaceOccurrences"; //$NON-NLS-1$
-
- private final boolean fInitialValid;
- private static final String DESCRIPTION = RefactoringMessages.ExtractTempInputPage_enter_name;
- private String[] fTempNameProposals;
- private IDialogSettings fSettings;
-
- public ExtractTempInputPage(String[] tempNameProposals) {
- super(DESCRIPTION, true, tempNameProposals.length == 0 ? "" : tempNameProposals[0]); //$NON-NLS-1$
- Assert.isNotNull(tempNameProposals);
- fTempNameProposals= tempNameProposals;
- fInitialValid= tempNameProposals.length > 0;
- }
-
- public void createControl(Composite parent) {
- loadSettings();
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.verticalSpacing= 8;
- result.setLayout(layout);
- RowLayouter layouter= new RowLayouter(2);
-
- Label label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ExtractTempInputPage_variable_name);
-
- Text text= createTextInputField(result);
- text.selectAll();
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- ControlContentAssistHelper.createTextContentAssistant(text, new VariableNamesProcessor(fTempNameProposals));
-
- layouter.perform(label, text, 1);
-
- addReplaceAllCheckbox(result, layouter);
- addDeclareFinalCheckbox(result, layouter);
-
- validateTextField(text.getText());
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_TEMP_WIZARD_PAGE);
- }
-
- private void loadSettings() {
- fSettings= getDialogSettings().getSection(ExtractTempWizard.DIALOG_SETTING_SECTION);
- if (fSettings == null) {
- fSettings= getDialogSettings().addNewSection(ExtractTempWizard.DIALOG_SETTING_SECTION);
- fSettings.put(DECLARE_FINAL, false);
- fSettings.put(REPLACE_ALL, true);
- }
- getExtractTempRefactoring().setDeclareFinal(fSettings.getBoolean(DECLARE_FINAL));
- getExtractTempRefactoring().setReplaceAllOccurrences(fSettings.getBoolean(REPLACE_ALL));
- }
-
- private void addReplaceAllCheckbox(Composite result, RowLayouter layouter) {
- String title= RefactoringMessages.ExtractTempInputPage_replace_all;
- boolean defaultValue= getExtractTempRefactoring().replaceAllOccurrences();
- final Button checkBox= createCheckbox(result, title, defaultValue, layouter);
- getExtractTempRefactoring().setReplaceAllOccurrences(checkBox.getSelection());
- checkBox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fSettings.put(REPLACE_ALL, checkBox.getSelection());
- getExtractTempRefactoring().setReplaceAllOccurrences(checkBox.getSelection());
- }
- });
- }
-
- private void addDeclareFinalCheckbox(Composite result, RowLayouter layouter) {
- String title= RefactoringMessages.ExtractTempInputPage_declare_final;
- boolean defaultValue= getExtractTempRefactoring().declareFinal();
- final Button checkBox= createCheckbox(result, title, defaultValue, layouter);
- getExtractTempRefactoring().setDeclareFinal(checkBox.getSelection());
- checkBox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- fSettings.put(DECLARE_FINAL, checkBox.getSelection());
- getExtractTempRefactoring().setDeclareFinal(checkBox.getSelection());
- }
- });
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#textModified(java.lang.String)
- */
- protected void textModified(String text) {
- getExtractTempRefactoring().setTempName(text);
- super.textModified(text);
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#validateTextField(String)
- */
- protected RefactoringStatus validateTextField(String text) {
- return getExtractTempRefactoring().checkTempName(text);
- }
-
- private ExtractTempRefactoring getExtractTempRefactoring(){
- return (ExtractTempRefactoring)getRefactoring();
- }
-
- private static Button createCheckbox(Composite parent, String title, boolean value, RowLayouter layouter){
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(title);
- checkBox.setSelection(value);
- layouter.perform(checkBox);
- return checkBox;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#isInitialInputValid()
- */
- protected boolean isInitialInputValid() {
- return fInitialValid;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IExceptionListChangeListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IExceptionListChangeListener.java
deleted file mode 100644
index 26367053..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IExceptionListChangeListener.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-
-public interface IExceptionListChangeListener {
-
- /**
- * Gets fired if the exception list got modified by adding or removing exceptions
- */
- public void exceptionListChanged();
-
-
-// /**
-// * Gets fired when the given parameter has changed
-// * @param parameter the parameter that has changed.
-// */
-// public void exceptionChanged(ExceptionInfo exception);
-//
-// /**
-// * Gets fired when the given exception has been added
-// * @param exception the exception that has been added.
-// */
-// public void exceptionAdded(ExceptionInfo exception);
-//
-//
-// /**
-// * Gets fired if the exception list got modified by reordering or removing
-// * exceptions (note that adding is handled by <code>exceptionAdded</code>))
-// */
-// public void exceptionListChanged();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IParameterListChangeListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IParameterListChangeListener.java
deleted file mode 100644
index 2b9fd878..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IParameterListChangeListener.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-
-public interface IParameterListChangeListener {
-
- /**
- * Gets fired when the given parameter has changed
- * @param parameter the parameter that has changed.
- */
- public void parameterChanged(ParameterInfo parameter);
-
- /**
- * Gets fired when the given parameter has been added
- * @param parameter the parameter that has been added.
- */
- public void parameterAdded(ParameterInfo parameter);
-
-
- /**
- * Gets fired if the parameter list got modified by reordering or removing
- * parameters (note that adding is handled by <code>parameterAdded</code>))
- */
- public void parameterListChanged();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IScheduledRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IScheduledRefactoring.java
deleted file mode 100644
index c6acaeeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IScheduledRefactoring.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-
-public interface IScheduledRefactoring {
-
- /**
- * The scheduling rule used to perform the
- * refactoring.
- *
- * @return {@link ISchedulingRule} not null
- */
- public ISchedulingRule getSchedulingRule();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IVisibilityChangeListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IVisibilityChangeListener.java
deleted file mode 100644
index 7f0ec5f8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IVisibilityChangeListener.java
+++ /dev/null
@@ -1,15 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-public interface IVisibilityChangeListener{
- void visibilityChanged(int newVisibility);
- void modifierChanged(int modifier, boolean isChecked);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineConstantWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineConstantWizard.java
deleted file mode 100644
index 83e6ddf2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineConstantWizard.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineConstantRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-public class InlineConstantWizard extends RefactoringWizard {
-
- private static final String MESSAGE = RefactoringMessages.InlineConstantWizard_message;
-
- public InlineConstantWizard(InlineConstantRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.InlineConstantWizard_Inline_Constant);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
-
- String message= null;
- int messageType= IMessageProvider.NONE;
- if(!getInlineConstantRefactoring().isInitializerAllStaticFinal()) {
- message= RefactoringMessages.InlineConstantWizard_initializer_refers_to_fields;
- messageType= IMessageProvider.INFORMATION;
- } else {
- message= MESSAGE;
- messageType= IMessageProvider.NONE;
- }
-
- addPage(new InlineConstantInputPage(message, messageType));
- }
-
- private InlineConstantRefactoring getInlineConstantRefactoring(){
- return (InlineConstantRefactoring)getRefactoring();
- }
-
- private static class InlineConstantInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "InlineConstantInputPage";//$NON-NLS-1$
-
- private InlineConstantRefactoring fRefactoring;
- private Group fInlineMode;
- private Button fRemove;
-
- private final int fOriginalMessageType;
- private final String fOriginalMessage;
-
- public InlineConstantInputPage(String description, int messageType) {
- super(PAGE_NAME);
- fOriginalMessage= description;
- fOriginalMessageType= messageType;
- setDescription(description);
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- fRefactoring= (InlineConstantRefactoring)getRefactoring();
- fRefactoring.setReplaceAllReferences(fRefactoring.isDeclarationSelected());
- fRefactoring.setRemoveDeclaration(true);
-
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- result.setLayout(layout);
- GridData gd= null;
-
- fInlineMode= new Group(result, SWT.NONE);
- fInlineMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fInlineMode.setLayout(new GridLayout());
- fInlineMode.setText(RefactoringMessages.InlineConstantInputPage_Inline);
-
- final Button all= new Button(fInlineMode, SWT.RADIO);
- all.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- all.setText(RefactoringMessages.InlineConstantInputPage_All_references);
- all.setSelection(fRefactoring.getReplaceAllReferences());
- all.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRefactoring.setReplaceAllReferences(true);
- fRemove.setEnabled(true);
- }
- });
-
- fRemove= new Button(fInlineMode, SWT.CHECK);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent= convertWidthInCharsToPixels(3);
- fRemove.setLayoutData(gd);
- fRemove.setText(RefactoringMessages.InlineConstantInputPage_Delete_constant);
- fRemove.setEnabled(all.getSelection());
- fRemove.setSelection(fRefactoring.getRemoveDeclaration());
- fRemove.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setRemoveDeclaration(fRemove.getSelection());
- }
- });
-
-
- final Button onlySelected= new Button(fInlineMode, SWT.RADIO);
- onlySelected.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- onlySelected.setText(RefactoringMessages.InlineConstantInputPage_Only_selected);
- onlySelected.setSelection(!fRefactoring.getReplaceAllReferences());
- onlySelected.setEnabled(!fRefactoring.isDeclarationSelected());
- onlySelected.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRefactoring.setReplaceAllReferences(false);
- fRemove.setEnabled(false);
- }
- });
- Dialog.applyDialogFont(result);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INLINE_CONSTANT_WIZARD_PAGE);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#restoreMessage()
- */
- protected void restoreMessage() {
- setMessage(fOriginalMessage, fOriginalMessageType);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineTempWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineTempWizard.java
deleted file mode 100644
index c829cd5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/InlineTempWizard.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineTempRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-public class InlineTempWizard extends RefactoringWizard {
-
- public InlineTempWizard(InlineTempRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE | NO_BACK_BUTTON_ON_STATUS_DIALOG);
- setDefaultPageTitle(RefactoringMessages.InlineTempWizard_defaultPageTitle);
- }
-
- protected void addUserInputPages() {
- addPage(new InlineTempInputPage());
- }
-
- public int getMessageLineWidthInChars() {
- return 0;
- }
-
- private static class InlineTempInputPage extends MessageWizardPage {
-
- public static final String PAGE_NAME= "InlineTempInputPage"; //$NON-NLS-1$
-
- public InlineTempInputPage() {
- super(PAGE_NAME, true, MessageWizardPage.STYLE_QUESTION);
- }
-
- public void createControl(Composite parent) {
- super.createControl(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INLINE_TEMP_WIZARD_PAGE);
- }
-
- protected String getMessageString() {
- InlineTempRefactoring refactoring= (InlineTempRefactoring) getRefactoring();
- int occurrences= refactoring.getReferences().length;
- final String identifier= refactoring.getVariableDeclaration().getName().getIdentifier();
- switch (occurrences) {
- case 0:
- return Messages.format(
- RefactoringMessages.InlineTempInputPage_message_zero,
- identifier);
-
- case 1:
- return Messages.format(RefactoringMessages.InlineTempInputPage_message_one, identifier);
-
- default:
- return Messages.format(RefactoringMessages.InlineTempInputPage_message_multi, new Object[] {
- new Integer(occurrences), identifier });
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryInputPage.java
deleted file mode 100644
index 20624b1e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryInputPage.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * @author rfuhrer
- */
-public class IntroduceFactoryInputPage extends UserInputWizardPage {
- /**
- * The name of the factory method to be created.
- */
- private Text fMethodName;
-
- private RefactoringStatus fMethodNameStatus;
- private RefactoringStatus fDestinationStatus;
-
- /**
- * Constructor for IntroduceFactoryInputPage.
- * @param name the name of the page
- */
- public IntroduceFactoryInputPage(String name) {
- super(name);
- }
-
- private Text createTextInputField(Composite result) {
- final Text textField = new Text(result, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
- textField.selectAll();
- TextFieldNavigationHandler.install(textField);
- return textField;
- }
-
- /**
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite result = new Composite(parent, SWT.NONE);
-
- setControl(result);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- result.setLayout(layout);
-
- Label methNameLabel= new Label(result, SWT.NONE);
- methNameLabel.setText(RefactoringMessages.IntroduceFactoryInputPage_method_name);
-
- fMethodName= createTextInputField(result);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- fMethodName.setLayoutData(gd);
- fMethodName.setText(getUseFactoryRefactoring().getNewMethodName());
-
- final Label factoryTypeLabel= new Label(result, SWT.NONE);
- factoryTypeLabel.setText(RefactoringMessages.IntroduceFactoryInputPage_factoryClassLabel);
-
- Composite inner= new Composite(result, SWT.NONE);
- GridLayout innerLayout= new GridLayout();
- innerLayout.marginHeight= 0; innerLayout.marginWidth= 0;
- innerLayout.numColumns= 2;
- inner.setLayout(innerLayout);
- inner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- final Text factoryTypeName= createTextInputField(inner);
- factoryTypeName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- final Button browseTypes= new Button(inner, SWT.PUSH);
- browseTypes.setText(RefactoringMessages.IntroduceFactoryInputPage_browseLabel);
- gd= new GridData();
- gd.horizontalAlignment= GridData.END;
- gd.widthHint = SWTUtil.getButtonWidthHint(browseTypes);
- browseTypes.setLayoutData(gd);
-
- final Button protectCtorCB= new Button(result, SWT.CHECK);
- protectCtorCB.setText(RefactoringMessages.IntroduceFactoryInputPage_protectConstructorLabel);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- protectCtorCB.setLayoutData(gd);
-
- fMethodName.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- fMethodNameStatus = getUseFactoryRefactoring().setNewMethodName(fMethodName.getText());
- validateInput(true);
- /*
- boolean nameOk= status.isOK();
-
- if (status.hasFatalError()) {
- IntroduceFactoryInputPage.this.setPageComplete(false);
-
- }
- IntroduceFactoryInputPage.this.setPageComplete(!status.hasFatalError());
- IntroduceFactoryInputPage.this.setErrorMessage(nameOk ?
- "" : //$NON-NLS-1$
- status.getMessageMatchingSeverity(RefactoringStatus.ERROR));
- */
- }
- });
- protectCtorCB.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- boolean isChecked = protectCtorCB.getSelection();
-
- getUseFactoryRefactoring().setProtectConstructor(isChecked);
- }
- });
-
- factoryTypeName.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- fDestinationStatus= getUseFactoryRefactoring().setFactoryClass(factoryTypeName.getText());
- validateInput(false);
- /*
- boolean nameOk= status.isOK();
-
- IntroduceFactoryInputPage.this.setPageComplete(nameOk);
- IntroduceFactoryInputPage.this.setErrorMessage(nameOk ? "" : //$NON-NLS-1$
- status.getMessageMatchingSeverity(RefactoringStatus.ERROR));
- */
- }
- });
- browseTypes.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IType factoryType= chooseFactoryClass();
-
- if (factoryType == null)
- return;
-
- RefactoringStatus status= getUseFactoryRefactoring().setFactoryClass(factoryType.getFullyQualifiedName());
- boolean nameOk= status.isOK();
-
- factoryTypeName.setText(factoryType.getFullyQualifiedName());
- IntroduceFactoryInputPage.this.setPageComplete(nameOk);
- IntroduceFactoryInputPage.this.setErrorMessage(nameOk ? "" : //$NON-NLS-1$
- status.getMessageMatchingSeverity(RefactoringStatus.ERROR));
- }
- });
-
- // Set up the initial state of the various dialog options.
- if (getUseFactoryRefactoring().canProtectConstructor())
- protectCtorCB.setSelection(true);
- else {
- protectCtorCB.setSelection(false);
- protectCtorCB.setEnabled(false);
- getUseFactoryRefactoring().setProtectConstructor(false);
- }
- factoryTypeName.setText(getUseFactoryRefactoring().getFactoryClassName());
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INTRODUCE_FACTORY_WIZARD_PAGE);
- }
-
- private IType chooseFactoryClass() {
- IJavaScriptProject proj= getUseFactoryRefactoring().getProject();
-
- if (proj == null)
- return null;
-
- IJavaScriptElement[] elements= new IJavaScriptElement[] { proj };
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(elements);
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(
- getShell(), false, getWizard().getContainer(), scope, IJavaScriptSearchConstants.CLASS);
-
- dialog.setTitle(RefactoringMessages.IntroduceFactoryInputPage_chooseFactoryClass_title);
- dialog.setMessage(RefactoringMessages.IntroduceFactoryInputPage_chooseFactoryClass_message);
-
- if (dialog.open() == Window.OK) {
- return (IType) dialog.getFirstResult();
- }
- return null;
- }
-
- private IntroduceFactoryRefactoring getUseFactoryRefactoring() {
- return (IntroduceFactoryRefactoring) getRefactoring();
- }
-
- private void validateInput(boolean methodName) {
- RefactoringStatus merged= new RefactoringStatus();
- if (fMethodNameStatus != null && (methodName || fMethodNameStatus.hasError()))
- merged.merge(fMethodNameStatus);
- if (fDestinationStatus != null && (!methodName || fDestinationStatus.hasError()))
- merged.merge(fDestinationStatus);
-
- setPageComplete(!merged.hasError());
- int severity= merged.getSeverity();
- String message= merged.getMessageMatchingSeverity(severity);
- if (severity >= RefactoringStatus.INFO) {
- setMessage(message, severity);
- } else {
- setMessage("", NONE); //$NON-NLS-1$
- }
- }
- }
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryWizard.java
deleted file mode 100644
index 850ec44f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceFactoryWizard.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring;
-
-/**
- * @author rfuhrer@watson.ibm.com
- */
-public class IntroduceFactoryWizard extends RefactoringWizard {
- /**
- * Constructor for IntroduceFactoryWizard.
- * @param ref the refactoring
- * @param pageTitle the page title
- */
- public IntroduceFactoryWizard(IntroduceFactoryRefactoring ref, String pageTitle) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(pageTitle);
- }
-
- /**
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- String message= RefactoringMessages.IntroduceFactoryInputPage_name_factory;
-
- IntroduceFactoryInputPage page= new IntroduceFactoryInputPage(message);
-
- addPage(page);
- }
-
- public IntroduceFactoryRefactoring getIntroduceFactoryRefactoring() {
- return (IntroduceFactoryRefactoring) getRefactoring();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionInputPage.java
deleted file mode 100644
index 8d0dea24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionInputPage.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- *
- */
-public class IntroduceIndirectionInputPage extends UserInputWizardPage {
-
- /**
- * The name of the intermediary method to be created.
- */
- private Text fIntermediaryMethodName;
-
- private Combo fIntermediaryTypeName;
- private static final int INTERMEDIARY_TYPE_COUNT= 10;
- private static List fgIntermediaryTypes= new ArrayList(INTERMEDIARY_TYPE_COUNT);
-
- /**
- * Constructor for IntroduceIndirectionInputPage.
- * @param name the name of the page
- */
- public IntroduceIndirectionInputPage(String name) {
- super(name);
- }
-
- private Text createIntermediaryNameCombo(Composite result) {
- final Text textField= new Text(result, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
- textField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- TextFieldNavigationHandler.install(textField);
- return textField;
- }
-
- private Combo createIntermediaryTypeCombo(Composite composite) {
- final Combo textCombo= new Combo(composite, SWT.SINGLE | SWT.BORDER);
- textCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- textCombo.setItems((String[]) fgIntermediaryTypes.toArray(new String[fgIntermediaryTypes.size()]));
- textCombo.setVisibleItemCount(INTERMEDIARY_TYPE_COUNT);
-
- JavaTypeCompletionProcessor processor= new JavaTypeCompletionProcessor(false, false, true);
- processor.setPackageFragment(getIntroduceIndirectionRefactoring().getInvocationPackage());
- ControlContentAssistHelper.createComboContentAssistant(textCombo, processor);
- TextFieldNavigationHandler.install(textCombo);
- return textCombo;
- }
-
- /**
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
-
- setControl(result);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- result.setLayout(layout);
-
- Label methNameLabel= new Label(result, SWT.NONE);
- methNameLabel.setText(RefactoringMessages.IntroduceIndirectionInputPage_new_method_name);
-
- fIntermediaryMethodName= createIntermediaryNameCombo(result);
-
- final Label intermediaryTypeLabel= new Label(result, SWT.NONE);
- intermediaryTypeLabel.setText(RefactoringMessages.IntroduceIndirectionInputPage_declaring_class);
-
- Composite inner= new Composite(result, SWT.NONE);
- GridLayout innerLayout= new GridLayout();
- innerLayout.marginHeight= 0;
- innerLayout.marginWidth= 0;
- innerLayout.numColumns= 2;
- inner.setLayout(innerLayout);
- inner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- fIntermediaryTypeName= createIntermediaryTypeCombo(inner);
- fIntermediaryTypeName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- final Button browseTypes= new Button(inner, SWT.PUSH);
- browseTypes.setText(RefactoringMessages.IntroduceIndirectionInputPage_browse);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.END;
- gd.widthHint= SWTUtil.getButtonWidthHint(browseTypes);
- browseTypes.setLayoutData(gd);
-
- final Button enableReferencesCheckBox= new Button(result, SWT.CHECK);
- enableReferencesCheckBox.setText(RefactoringMessages.IntroduceIndirectionInputPage_update_references);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- gd.verticalIndent= 2;
- enableReferencesCheckBox.setLayoutData(gd);
-
- fIntermediaryMethodName.setText(getIntroduceIndirectionRefactoring().getIntermediaryMethodName());
- fIntermediaryTypeName.setText(getIntroduceIndirectionRefactoring().getIntermediaryClassName());
-
- fIntermediaryMethodName.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- });
-
- enableReferencesCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- getIntroduceIndirectionRefactoring().setEnableUpdateReferences(enableReferencesCheckBox.getSelection());
- }
- });
-
- fIntermediaryTypeName.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- });
-
- browseTypes.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IType intermediaryType= chooseIntermediaryClass();
-
- if (intermediaryType == null)
- return;
-
- fIntermediaryTypeName.setText(intermediaryType.getFullyQualifiedName());
- }
- });
-
- if (getIntroduceIndirectionRefactoring().canEnableUpdateReferences())
- enableReferencesCheckBox.setSelection(true);
- else {
- enableReferencesCheckBox.setSelection(false);
- enableReferencesCheckBox.setEnabled(false);
- getIntroduceIndirectionRefactoring().setEnableUpdateReferences(false);
- }
-
- fIntermediaryMethodName.setFocus();
- fIntermediaryMethodName.selectAll();
- validateInput();
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INTRODUCE_INDIRECTION_WIZARD_PAGE);
- }
-
- private IType chooseIntermediaryClass() {
- IJavaScriptProject proj= getIntroduceIndirectionRefactoring().getProject();
-
- if (proj == null)
- return null;
-
- IJavaScriptElement[] elements= new IJavaScriptElement[] { proj };
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(elements);
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaScriptSearchConstants.CLASS);
-
- dialog.setTitle(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class);
- dialog.setMessage(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class_long);
-
- if (dialog.open() == Window.OK) {
- return (IType) dialog.getFirstResult();
- }
- return null;
- }
-
- private IntroduceIndirectionRefactoring getIntroduceIndirectionRefactoring() {
- return (IntroduceIndirectionRefactoring) getRefactoring();
- }
-
- private void validateInput() {
- RefactoringStatus merged= new RefactoringStatus();
- merged.merge(getIntroduceIndirectionRefactoring().setIntermediaryClassName(fIntermediaryTypeName.getText()));
- merged.merge(getIntroduceIndirectionRefactoring().setIntermediaryMethodName(fIntermediaryMethodName.getText()));
-
- setPageComplete(!merged.hasError());
- int severity= merged.getSeverity();
- String message= merged.getMessageMatchingSeverity(severity);
- if (severity >= RefactoringStatus.INFO) {
- setMessage(message, severity);
- } else {
- setMessage("", NONE); //$NON-NLS-1$
- }
- }
-
- protected boolean performFinish() {
- storeIntermediaryTypeName();
- return super.performFinish();
- }
-
- public IWizardPage getNextPage() {
- storeIntermediaryTypeName();
- return super.getNextPage();
- }
-
- private void storeIntermediaryTypeName() {
- String destination= fIntermediaryTypeName.getText();
- if (!fgIntermediaryTypes.remove(destination) && fgIntermediaryTypes.size() >= INTERMEDIARY_TYPE_COUNT)
- fgIntermediaryTypes.remove(fgIntermediaryTypes.size() - 1);
- fgIntermediaryTypes.add(0, destination);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java
deleted file mode 100644
index f020cb21..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring;
-
-/**
- *
- */
-public class IntroduceIndirectionWizard extends RefactoringWizard {
-
- /**
- * Constructor for IntroduceIndirectionWizard.
- * @param ref the refactoring
- * @param pageTitle the page title
- */
- public IntroduceIndirectionWizard(IntroduceIndirectionRefactoring ref, String pageTitle) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(pageTitle);
- }
-
- /**
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- IntroduceIndirectionInputPage page= new IntroduceIndirectionInputPage("IntroduceIndirectionInputPage"); //$NON-NLS-1$
- addPage(page);
- }
-
- public IntroduceIndirectionRefactoring getIntroduceIndirectionRefactoring() {
- return (IntroduceIndirectionRefactoring) getRefactoring();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceParameterWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceParameterWizard.java
deleted file mode 100644
index 02f38fc8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceParameterWizard.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.IntroduceParameterRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-public class IntroduceParameterWizard extends RefactoringWizard {
-
- public IntroduceParameterWizard(IntroduceParameterRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.IntroduceParameterWizard_defaultPageTitle);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new IntroduceParameterInputPage(getIntroduceParameterRefactoring().guessParameterNames()));
- }
-
- private IntroduceParameterRefactoring getIntroduceParameterRefactoring(){
- return (IntroduceParameterRefactoring)getRefactoring();
- }
-
- private static class IntroduceParameterInputPage extends UserInputWizardPage {
-
- private static final String DESCRIPTION = RefactoringMessages.IntroduceParameterInputPage_description;
- public static final String PAGE_NAME= "IntroduceParameterInputPage";//$NON-NLS-1$
- private String[] fParamNameProposals;
-
- private JavaSourceViewer fSignaturePreview;
- private Document fSignaturePreviewDocument;
- private Button fLeaveDelegateCheckBox;
- private Button fDeprecateDelegateCheckBox;
-
- public IntroduceParameterInputPage(String[] tempNameProposals) {
- super(PAGE_NAME);
- setDescription(DESCRIPTION);
- Assert.isNotNull(tempNameProposals);
- fParamNameProposals= tempNameProposals;
- fSignaturePreviewDocument= new Document();
- }
-
- private IntroduceParameterRefactoring getIntroduceParameterRefactoring(){
- return (IntroduceParameterRefactoring)getRefactoring();
- }
-
- public void createControl(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- result.setLayout(layout);
-
- createParameterTableControl(result);
- fLeaveDelegateCheckBox= DelegateUIHelper.generateLeaveDelegateCheckbox(result, getRefactoring(), false);
- if (fLeaveDelegateCheckBox != null) {
- fDeprecateDelegateCheckBox= new Button(result, SWT.CHECK);
- GridData data= new GridData();
- data.horizontalAlignment= GridData.FILL;
- data.horizontalIndent= (layout.marginWidth + fDeprecateDelegateCheckBox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- fDeprecateDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox.setText(DelegateUIHelper.getDeprecateDelegateCheckBoxTitle());
- final IntroduceParameterRefactoring refactoring= getIntroduceParameterRefactoring();
- fDeprecateDelegateCheckBox.setSelection(DelegateUIHelper.loadDeprecateDelegateSetting(refactoring));
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- fDeprecateDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- }
- });
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
- Label sep= new Label(result, SWT.SEPARATOR | SWT.HORIZONTAL);
- sep.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- createSignaturePreview(result);
-
- update(false);
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INTRODUCE_PARAMETER_WIZARD_PAGE);
- }
-
- private ChangeParametersControl createParameterTableControl(Composite composite) {
- String labelText= RefactoringMessages.IntroduceParameterWizard_parameters;
- ChangeParametersControl cp= new ChangeParametersControl(composite, SWT.NONE, labelText, new IParameterListChangeListener() {
- public void parameterChanged(ParameterInfo parameter) {
- update(true);
- }
- public void parameterListChanged() {
- update(true);
- }
- public void parameterAdded(ParameterInfo parameter) {
- update(true);
- }
- }, ChangeParametersControl.Mode.INTRODUCE_PARAMETER, fParamNameProposals);
- cp.setLayoutData(new GridData(GridData.FILL_BOTH));
- cp.setInput(getIntroduceParameterRefactoring().getParameterInfos());
- cp.editParameter(getIntroduceParameterRefactoring().getAddedParameterInfo());
- return cp;
- }
-
- public void dispose() {
- DelegateUIHelper.saveLeaveDelegateSetting(fLeaveDelegateCheckBox);
- DelegateUIHelper.saveDeprecateDelegateSetting(fDeprecateDelegateCheckBox);
- super.dispose();
- }
-
- private void createSignaturePreview(Composite composite) {
- Label previewLabel= new Label(composite, SWT.NONE);
- previewLabel.setText(RefactoringMessages.ChangeSignatureInputPage_method_Signature_Preview);
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSignaturePreview= new JavaSourceViewer(composite, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP /*| SWT.BORDER*/, store);
- fSignaturePreview.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- fSignaturePreview.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- fSignaturePreview.getTextWidget().setBackground(composite.getBackground());
- fSignaturePreview.setDocument(fSignaturePreviewDocument);
- fSignaturePreview.setEditable(false);
-
- //Layouting problems with wrapped text: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=9866
- Control signaturePreviewControl= fSignaturePreview.getControl();
- PixelConverter pixelConverter= new PixelConverter(signaturePreviewControl);
- GridData gdata= new GridData(GridData.FILL_BOTH);
- gdata.widthHint= pixelConverter.convertWidthInCharsToPixels(50);
- gdata.heightHint= pixelConverter.convertHeightInCharsToPixels(2);
- signaturePreviewControl.setLayoutData(gdata);
- }
-
- private void update(boolean displayErrorMessage){
- updateStatus(displayErrorMessage);
- updateSignaturePreview();
- }
-
- private void updateStatus(boolean displayErrorMessage) {
- RefactoringStatus nameCheck= getIntroduceParameterRefactoring().validateInput();
- if (displayErrorMessage) {
- setPageComplete(nameCheck);
- } else {
- setErrorMessage(null);
- setPageComplete(true);
- }
- }
-
- private void updateSignaturePreview() {
- try{
- int top= fSignaturePreview.getTextWidget().getTopPixel();
- fSignaturePreviewDocument.set(getIntroduceParameterRefactoring().getMethodSignaturePreview());
- fSignaturePreview.getTextWidget().setTopPixel(top);
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.IntroduceParameterWizard_defaultPageTitle, RefactoringMessages.ChangeSignatureInputPage_exception);
- }
- }
-
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/JavaStatusContextViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/JavaStatusContextViewer.java
deleted file mode 100644
index eda3e04a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/JavaStatusContextViewer.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.ui.refactoring.TextStatusContextViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStringStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.InternalClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class JavaStatusContextViewer extends TextStatusContextViewer {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.IStatusContextViewer#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- super.createControl(parent);
- final SourceViewer viewer= getSourceViewer();
- viewer.unconfigure();
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- viewer.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- viewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- }
-
- protected SourceViewer createSourceViewer(Composite parent) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- return new JavaSourceViewer(parent, null, null, false, SWT.LEFT_TO_RIGHT | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION, store);
- }
-
- private IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) {
-
- IJavaScriptElement element= file.getParent();
- while (element != null && element.getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- element= element.getParent();
-
- return (IPackageFragmentRoot) element;
- }
-
- public void setInput(RefactoringStatusContext context) {
- if (context instanceof JavaStatusContext) {
- JavaStatusContext jsc= (JavaStatusContext)context;
- IDocument document= null;
- if (jsc.isBinary()) {
- IClassFile file= jsc.getClassFile();
- IEditorInput editorInput= new InternalClassFileEditorInput(file);
- document= getDocument(JavaScriptPlugin.getDefault().getClassFileDocumentProvider(), editorInput);
- if (document.getLength() == 0)
- document= new Document(Messages.format(RefactoringMessages.JavaStatusContextViewer_no_source_found0, getPackageFragmentRoot(file).getElementName()));
- updateTitle(file);
- } else {
- IJavaScriptUnit cunit= jsc.getCompilationUnit();
- if (cunit.isWorkingCopy()) {
- try {
- document= newJavaDocument(cunit.getSource());
- } catch (JavaScriptModelException e) {
- // document is null which is a valid input.
- }
- } else {
- IEditorInput editorInput= new FileEditorInput((IFile)cunit.getResource());
- document= getDocument(JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider(), editorInput);
- }
- if (document == null)
- document= new Document(RefactoringMessages.JavaStatusContextViewer_no_source_available);
- updateTitle(cunit);
- }
- setInput(document, createRegion(jsc.getSourceRange()));
- } else if (context instanceof JavaStringStatusContext) {
- updateTitle(null);
- JavaStringStatusContext sc= (JavaStringStatusContext)context;
- setInput(newJavaDocument(sc.getSource()), createRegion(sc.getSourceRange()));
- }
- }
-
- private IDocument newJavaDocument(String source) {
- IDocument result= new Document(source);
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- textTools.setupJavaDocumentPartitioner(result);
- return result;
- }
-
- private static IRegion createRegion(ISourceRange range) {
- return new Region(range.getOffset(), range.getLength());
- }
-
- private IDocument getDocument(IDocumentProvider provider, IEditorInput input) {
- if (input == null)
- return null;
- IDocument result= null;
- try {
- provider.connect(input);
- result= provider.getDocument(input);
- } catch (CoreException e) {
- } finally {
- provider.disconnect(input);
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MessageWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MessageWizardPage.java
deleted file mode 100644
index 6a319194..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MessageWizardPage.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-
-public abstract class MessageWizardPage extends UserInputWizardPage {
-
- public static final int STYLE_NONE= 0;
- public static final int STYLE_INFORMATION= 1;
- public static final int STYLE_QUESTION= 2;
- public static final int STYLE_ERROR= 3;
- public static final int STYLE_WARNING= 4;
-
- private final int fStyle;
-
- public MessageWizardPage(String pageName, boolean isLastUserPage, int style) {
- super(pageName);
- fStyle= style;
- }
-
- protected abstract String getMessageString();
-
- protected Image getMessageImage() {
- switch (fStyle) {
- case STYLE_ERROR :
- return Display.getCurrent().getSystemImage(SWT.ICON_ERROR);
- case STYLE_WARNING :
- return Display.getCurrent().getSystemImage(SWT.ICON_WARNING);
- case STYLE_INFORMATION :
- return Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION);
- case STYLE_QUESTION :
- return Display.getCurrent().getSystemImage(SWT.ICON_QUESTION);
- default :
- return null;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN) * 3 / 2;
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING) * 2;
- layout.numColumns= 2;
- result.setLayout(layout);
-
- Image image= getMessageImage();
- if (image != null) {
- Label label= new Label(result, SWT.NULL);
- image.setBackground(label.getBackground());
- label.setImage(image);
- label.setLayoutData(new GridData(
- GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_BEGINNING));
- }
-
- String message= getMessageString();
- if (message != null) {
- Label messageLabel= new Label(result, SWT.WRAP);
- messageLabel.setText(message);
- GridData data= new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING);
- data.widthHint= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
- messageLabel.setLayoutData(data);
- messageLabel.setFont(result.getFont());
- }
- Dialog.applyDialogFont(result);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInnerToTopWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInnerToTopWizard.java
deleted file mode 100644
index 0f1b985c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInnerToTopWizard.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-public class MoveInnerToTopWizard extends RefactoringWizard {
-
- private class MoveInnerToToplnputPage extends TextInputWizardPage {
-
- private Text fFieldNameEntryText;
-
- private Label fFieldNameLabel;
-
- private Button fFinalCheckBox;
-
- private final boolean fInitialInputValid;
-
- public MoveInnerToToplnputPage(String initialValue) {
- super(RefactoringMessages.MoveInnerToToplnputPage_description, true, initialValue);
- final MoveInnerToTopRefactoring refactoring= getMoveRefactoring();
- final boolean mandatory= refactoring.isCreatingInstanceFieldMandatory();
- fInitialInputValid= (!initialValue.equals("")) || !mandatory; //$NON-NLS-1$
- if (!mandatory)
- refactoring.setCreateInstanceField(false);
- }
-
- private void addFieldNameEntry(Composite newControl) {
- fFieldNameLabel= new Label(newControl, SWT.NONE);
- if (getMoveRefactoring().isCreatingInstanceFieldMandatory())
- fFieldNameLabel.setText(RefactoringMessages.MoveInnerToToplnputPage_enter_name_mandatory);
- else
- fFieldNameLabel.setText(RefactoringMessages.MoveInnerToToplnputPage_enter_name);
- fFieldNameLabel.setLayoutData(new GridData());
-
- fFieldNameEntryText= createTextInputField(newControl);
- fFieldNameEntryText.selectAll();
- fFieldNameEntryText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
-
- private void addFinalCheckBox(Composite newControl) {
- fFinalCheckBox= new Button(newControl, SWT.CHECK);
- fFinalCheckBox.setText(RefactoringMessages.MoveInnerToToplnputPage_instance_final);
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.horizontalSpan= 2;
- fFinalCheckBox.setLayoutData(data);
- fFinalCheckBox.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent event) {
- getMoveRefactoring().setMarkInstanceFieldAsFinal(fFinalCheckBox.getSelection());
- }
- });
- fFieldNameEntryText.addModifyListener(new ModifyListener() {
-
- public final void modifyText(ModifyEvent event) {
- final String text= fFieldNameEntryText.getText();
- final MoveInnerToTopRefactoring refactoring= getMoveRefactoring();
- if (refactoring.isCreatingInstanceFieldMandatory())
- setPageComplete(validateTextField(text));
- final boolean empty= text.length() == 0;
- if (refactoring.isCreatingInstanceFieldMandatory()) {
- // Do nothing
- } else if (refactoring.isCreatingInstanceFieldPossible()) {
- fFinalCheckBox.setEnabled(!empty);
- }
- if (!refactoring.isCreatingInstanceFieldMandatory())
- refactoring.setCreateInstanceField(!empty);
- }
- });
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- Composite newControl= new Composite(parent, SWT.NONE);
- setControl(newControl);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newControl, IJavaHelpContextIds.MOVE_INNER_TO_TOP_WIZARD_PAGE);
- newControl.setLayout(new GridLayout());
- Dialog.applyDialogFont(newControl);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.verticalSpacing= 8;
- newControl.setLayout(layout);
-
- addFieldNameEntry(newControl);
- addFinalCheckBox(newControl);
-
- if (getMoveRefactoring().isCreatingInstanceFieldPossible()) {
- fFinalCheckBox.setSelection(getMoveRefactoring().isInstanceFieldMarkedFinal());
- fFinalCheckBox.setEnabled(true);
- } else {
- fFinalCheckBox.setSelection(false);
- fFinalCheckBox.setEnabled(false);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#isEmptyInputValid()
- */
- protected boolean isEmptyInputValid() {
- return !getMoveRefactoring().isCreatingInstanceFieldMandatory();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#isInitialInputValid()
- */
- protected boolean isInitialInputValid() {
- return fInitialInputValid;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- String message= getMoveRefactoring().isCreatingInstanceFieldMandatory() ? RefactoringMessages.MoveInnerToToplnputPage_mandatory_info : RefactoringMessages.MoveInnerToToplnputPage_optional_info;
- setPageComplete(RefactoringStatus.createInfoStatus(message));
- } else {
- setPageComplete(new RefactoringStatus());
- getContainer().updateMessage();
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage#validateTextField(String)
- */
- protected RefactoringStatus validateTextField(String text) {
- final MoveInnerToTopRefactoring refactoring= getMoveRefactoring();
- refactoring.setEnclosingInstanceName(text);
- if (refactoring.isCreatingInstanceFieldMandatory())
- return refactoring.checkEnclosingInstanceName(text);
- else if (!text.equals("")) //$NON-NLS-1$
- return refactoring.checkEnclosingInstanceName(text);
- else
- return new RefactoringStatus();
- }
- }
-
- public MoveInnerToTopWizard(Refactoring refactoring) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.MoveInnerToTopWizard_Move_Inner);
- }
-
- /*
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- final MoveInnerToTopRefactoring refactoring= getMoveRefactoring();
- if (refactoring.isCreatingInstanceFieldPossible())
- addPage(new MoveInnerToToplnputPage(refactoring.isCreatingInstanceFieldMandatory() ? refactoring.getEnclosingInstanceName() : "")); //$NON-NLS-1$
- else
- setChangeCreationCancelable(false);
- }
-
- private MoveInnerToTopRefactoring getMoveRefactoring() {
- return (MoveInnerToTopRefactoring) getRefactoring();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInstanceMethodWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInstanceMethodWizard.java
deleted file mode 100644
index 28c73ccd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveInstanceMethodWizard.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveInstanceMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refactoring wizard for the 'move instance method' refactoring.
- */
-public final class MoveInstanceMethodWizard extends RefactoringWizard {
-
- /**
- * The input wizard page of the 'move instance method' refactoring.
- */
- public final class MoveInstanceMethodPage extends UserInputWizardPage {
-
- /** The page name */
- protected static final String PAGE_NAME= "MoveInstanceMethodPage"; //$NON-NLS-1$
-
- /** The "leave delegate" checkbox */
- protected Button fLeaveDelegateCheckBox= null;
-
- /** The "deprecate delegate" checkbox */
- protected Button fDeprecateDelegateCheckBox= null;
-
- /** The method name text field */
- protected Text fMethodNameField= null;
-
- /** The current method name status */
- protected RefactoringStatus fMethodNameStatus= new RefactoringStatus();
-
- /** The target name text field */
- protected Text fTargetNameField= null;
-
- /** The target name label */
- protected Label fTargetNameLabel= null;
-
- /** The current target name status */
- protected RefactoringStatus fTargetNameStatus= new RefactoringStatus();
-
- /** The current target type status */
- protected RefactoringStatus fTargetTypeStatus= new RefactoringStatus();
-
- /**
- * Creates a new move instance method page.
- */
- public MoveInstanceMethodPage() {
- super(PAGE_NAME);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(final Composite parent) {
- Assert.isNotNull(parent);
- final Composite control= new Composite(parent, SWT.NONE);
- setControl(control);
-
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- control.setLayout(layout);
-
- Label label= new Label(control, SWT.SINGLE);
- label.setText(Messages.format(RefactoringMessages.MoveInstanceMethodPage_New_receiver, JavaScriptElementLabels.getElementLabel(fProcessor.getMethod(), JavaScriptElementLabels.ALL_DEFAULT | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PRE_TYPE_PARAMETERS | JavaScriptElementLabels.M_PARAMETER_NAMES)));
-
- GridData data= new GridData();
- data.horizontalSpan= 2;
- label.setLayoutData(data);
-
- final TableLayoutComposite composite= new TableLayoutComposite(control, SWT.NULL);
- composite.addColumnData(new ColumnWeightData(40, true));
- composite.addColumnData(new ColumnWeightData(60, true));
-
- final Table table= new Table(composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
- table.setHeaderVisible(true);
- table.setLinesVisible(false);
-
- TableColumn column= new TableColumn(table, SWT.NONE);
- column.setText(RefactoringMessages.MoveInstanceMethodPage_Name);
- column.setResizable(true);
-
- column= new TableColumn(table, SWT.NONE);
- column.setText(RefactoringMessages.MoveInstanceMethodPage_Type);
- column.setResizable(true);
-
- final TableViewer viewer= new TableViewer(table);
- viewer.setContentProvider(new ArrayContentProvider());
- viewer.setLabelProvider(new TargetLabelProvider());
-
- final IVariableBinding[] candidateTargets= fProcessor.getCandidateTargets();
- viewer.setInput(candidateTargets);
- final IVariableBinding[] possibleTargets= fProcessor.getPossibleTargets();
- viewer.setSelection(new StructuredSelection(new Object[] { possibleTargets[0]}));
-
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public final void selectionChanged(final SelectionChangedEvent event) {
- final Object element= ((IStructuredSelection) event.getSelection()).getFirstElement();
- if (element instanceof IVariableBinding) {
- final IVariableBinding target= (IVariableBinding) element;
- final IVariableBinding[] targets= fProcessor.getPossibleTargets();
- boolean success= false;
- for (int index= 0; index < targets.length; index++) {
- if (Bindings.equals(target, targets[index])) {
- handleTargetChanged(target);
- success= true;
- break;
- }
- }
- if (!success)
- fTargetTypeStatus= RefactoringStatus.createWarningStatus(Messages.format(RefactoringMessages.MoveInstanceMethodPage_invalid_target, target.getName()));
- else
- fTargetTypeStatus= new RefactoringStatus();
- handleStatusChanged();
- }
- }
- });
-
- data= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
- data.heightHint= SWTUtil.getTableHeightHint(table, 7);
- data.horizontalSpan= 2;
- composite.setLayoutData(data);
-
- label= new Label(control, SWT.SINGLE);
- label.setText(RefactoringMessages.MoveInstanceMethodPage_Method_name);
- label.setLayoutData(new GridData());
-
- fMethodNameField= new Text(control, SWT.SINGLE | SWT.BORDER);
- fMethodNameField.setText(fProcessor.getMethodName());
- fMethodNameField.selectAll();
- fMethodNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fMethodNameField.setFocus();
- fMethodNameField.addModifyListener(new ModifyListener() {
-
- public final void modifyText(final ModifyEvent event) {
- fMethodNameStatus= fProcessor.setMethodName(fMethodNameField.getText());
- handleStatusChanged();
- }
- });
- TextFieldNavigationHandler.install(fMethodNameField);
-
- fTargetNameLabel= new Label(control, SWT.SINGLE);
- fTargetNameLabel.setText(RefactoringMessages.MoveInstanceMethodPage_Target_name);
- fTargetNameLabel.setLayoutData(new GridData());
-
- fTargetNameField= new Text(control, SWT.SINGLE | SWT.BORDER);
- final String name= fProcessor.getTargetName();
- if (name != null && name.length() > 0)
- fTargetNameField.setText(fProcessor.getTargetName());
- else {
- setPageComplete(RefactoringStatus.createInfoStatus(RefactoringCoreMessages.Checks_Choose_name));
- setPageComplete(false);
- }
- fTargetNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fTargetNameField.addModifyListener(new ModifyListener() {
-
- public final void modifyText(final ModifyEvent event) {
- fTargetNameStatus= fProcessor.setTargetName(fTargetNameField.getText());
- handleStatusChanged();
- }
- });
- TextFieldNavigationHandler.install(fTargetNameField);
-
- label= new Label(control, SWT.NONE);
-
- data= new GridData();
- data.horizontalSpan= 2;
- label.setLayoutData(data);
-
- fLeaveDelegateCheckBox= DelegateUIHelper.generateLeaveDelegateCheckbox(control, getRefactoring(), false);
- if (fLeaveDelegateCheckBox != null) {
- fDeprecateDelegateCheckBox= new Button(control, SWT.CHECK);
- data= new GridData();
- data.horizontalAlignment= GridData.FILL;
- data.horizontalIndent= (layout.marginWidth + fDeprecateDelegateCheckBox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- data.horizontalSpan= 2;
- fDeprecateDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox.setText(DelegateUIHelper.getDeprecateDelegateCheckBoxTitle());
- fDeprecateDelegateCheckBox.setSelection(DelegateUIHelper.loadDeprecateDelegateSetting(fProcessor));
- fProcessor.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- fDeprecateDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fProcessor.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- }
- });
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
-
- fProcessor.setInlineDelegator(!fLeaveDelegateCheckBox.getSelection());
- fProcessor.setRemoveDelegator(!fLeaveDelegateCheckBox.getSelection());
-
- handleTargetChanged(possibleTargets[0]);
-
- Dialog.applyDialogFont(control);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.MOVE_MEMBERS_WIZARD_PAGE);
- }
-
- public void dispose() {
- DelegateUIHelper.saveLeaveDelegateSetting(fLeaveDelegateCheckBox);
- DelegateUIHelper.saveDeprecateDelegateSetting(fDeprecateDelegateCheckBox);
- super.dispose();
- }
-
- /**
- * Handles the status changed event.
- */
- protected final void handleStatusChanged() {
- final RefactoringStatus status= new RefactoringStatus();
- status.merge(fMethodNameStatus);
- status.merge(fTargetNameStatus);
- status.merge(fTargetTypeStatus);
- if (!fTargetTypeStatus.isOK())
- setPageComplete(false);
- else
- setPageComplete(status);
- }
-
- /**
- * Handles the target changed event.
- *
- * @param target the changed target
- */
- protected final void handleTargetChanged(final IVariableBinding target) {
- Assert.isNotNull(target);
- fProcessor.setTarget(target);
- fTargetNameField.setEnabled(fProcessor.needsTargetNode());
- fTargetNameLabel.setEnabled(fProcessor.needsTargetNode());
- }
- }
-
- /**
- * Table label provider for the target selection table.
- */
- public static class TargetLabelProvider extends BindingLabelProvider implements ITableLabelProvider {
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(final Object element, final int column) {
- if (column == 0)
- return getImage(element);
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(final Object element, final int column) {
- final IVariableBinding binding= (IVariableBinding) element;
- switch (column) {
- case 0:
- return getText(binding);
- case 1:
- return getText(binding.getType());
- default:
- return null;
- }
- }
- }
-
- /** The default create delegator setting */
- protected static boolean DEFAULT_CREATE_DELEGATOR_SETTING= false;
-
- /** The default deprecate delegator setting */
- protected static boolean DEFAULT_DEPRECATE_DELEGATOR_SETTING= false;
-
- /** The associated move instance method processor */
- protected final MoveInstanceMethodProcessor fProcessor;
-
- /**
- * Creates a new move instance method wizard.
- *
- * @param refactoring the refactoring to host
- */
- public MoveInstanceMethodWizard(final MoveInstanceMethodRefactoring refactoring) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE);
- fProcessor= refactoring.getMoveMethodProcessor();
- setDefaultPageTitle(RefactoringMessages.MoveInstanceMethodWizard_Move_Method);
- }
-
- /*
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- addPage(new MoveInstanceMethodPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveMembersWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveMembersWizard.java
deleted file mode 100644
index 60b73633..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/MoveMembersWizard.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class MoveMembersWizard extends RefactoringWizard {
-
- public MoveMembersWizard(MoveRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.MoveMembersWizard_page_title);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new MoveMembersInputPage());
- }
-
- private static class MoveMembersInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "MoveMembersInputPage"; //$NON-NLS-1$
- private static final long LABEL_FLAGS= JavaScriptElementLabels.ALL_DEFAULT;
-
- private Combo fDestinationField;
- private Button fLeaveDelegateCheckBox;
- private Button fDeprecateDelegateCheckBox;
- private static final int MRU_COUNT= 10;
- private static List fgMruDestinations= new ArrayList(MRU_COUNT);
-
- public MoveMembersInputPage() {
- super(PAGE_NAME);
- }
-
- public void setVisible(boolean visible){
- if (visible){
- String message= Messages.format(RefactoringMessages.MoveMembersInputPage_descriptionKey,
- new String[]{new Integer(getMoveProcessor().getMembersToMove().length).toString(),
- JavaModelUtil.getFullyQualifiedName(getMoveProcessor().getDeclaringType())});
- setDescription(message);
- }
- super.setVisible(visible);
- }
-
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- composite.setLayout(layout);
-
- addLabel(composite);
- addDestinationControls(composite);
- fLeaveDelegateCheckBox= DelegateUIHelper.generateLeaveDelegateCheckbox(composite, getRefactoring(), getMoveProcessor().getMembersToMove().length > 1);
- GridData data= new GridData();
- data.horizontalSpan= 2;
- if (fLeaveDelegateCheckBox != null) {
- fLeaveDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox= new Button(composite, SWT.CHECK);
- data= new GridData();
- data.horizontalAlignment= GridData.FILL;
- data.horizontalIndent= (layout.marginWidth + fDeprecateDelegateCheckBox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- data.horizontalSpan= 2;
- fDeprecateDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox.setText(DelegateUIHelper.getDeprecateDelegateCheckBoxTitle());
- fDeprecateDelegateCheckBox.setSelection(DelegateUIHelper.loadDeprecateDelegateSetting(getMoveProcessor()));
- getMoveProcessor().setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- fDeprecateDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- getMoveProcessor().setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- }
- });
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.MOVE_MEMBERS_WIZARD_PAGE);
- }
-
- public void dispose() {
- DelegateUIHelper.saveLeaveDelegateSetting(fLeaveDelegateCheckBox);
- DelegateUIHelper.saveDeprecateDelegateSetting(fDeprecateDelegateCheckBox);
- super.dispose();
- }
-
- private void addLabel(Composite parent) {
- Label label= new Label(parent, SWT.NONE);
- IMember[] members= getMoveProcessor().getMembersToMove();
- if (members.length == 1) {
- label.setText(Messages.format(
- RefactoringMessages.MoveMembersInputPage_destination_single,
- JavaScriptElementLabels.getElementLabel(members[0], LABEL_FLAGS)));
- } else {
- label.setText(Messages.format(
- RefactoringMessages.MoveMembersInputPage_destination_multi,
- String.valueOf(members.length)));
- }
- GridData gd= new GridData();
- gd.horizontalSpan= 2;
- label.setLayoutData(gd);
- }
-
- private void addDestinationControls(Composite composite) {
- fDestinationField= new Combo(composite, SWT.SINGLE | SWT.BORDER);
- fDestinationField.setFocus();
- fDestinationField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fDestinationField.setItems((String[]) fgMruDestinations.toArray(new String[fgMruDestinations.size()]));
- fDestinationField.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- handleDestinationChanged();
- }
- private void handleDestinationChanged() {
- IStatus status= JavaScriptConventions.validateJavaScriptTypeName(fDestinationField.getText());
- if (status.getSeverity() == IStatus.ERROR){
- error(status.getMessage());
- } else {
- try {
- final IType declaring= getMoveProcessor().getDeclaringType();
- IType resolvedType= declaring.getJavaScriptProject().findType(fDestinationField.getText());
- if (resolvedType == null)
- resolvedType= declaring.getJavaScriptProject().findType(declaring.getPackageFragment().getElementName(), fDestinationField.getText());
- IStatus validationStatus= validateDestinationType(resolvedType, fDestinationField.getText());
- if (validationStatus.isOK()){
- setErrorMessage(null);
- setPageComplete(true);
- } else {
- error(validationStatus.getMessage());
- }
- } catch(JavaScriptModelException ex) {
- JavaScriptPlugin.log(ex); //no ui here
- error(RefactoringMessages.MoveMembersInputPage_invalid_name);
- }
- }
- }
- private void error(String message){
- setErrorMessage(message);
- setPageComplete(false);
- }
- });
- if (fgMruDestinations.size() > 0) {
- fDestinationField.select(0);
- } else {
- setPageComplete(false);
- }
- JavaTypeCompletionProcessor processor= new JavaTypeCompletionProcessor(false, false, true);
- IPackageFragment context= (IPackageFragment) getMoveProcessor().getDeclaringType().getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- processor.setPackageFragment(context);
- ControlContentAssistHelper.createComboContentAssistant(fDestinationField, processor);
- TextFieldNavigationHandler.install(fDestinationField);
-
- Button button= new Button(composite, SWT.PUSH);
- button.setText(RefactoringMessages.MoveMembersInputPage_browse);
- button.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- openTypeSelectionDialog();
- }
- });
- }
-
- protected boolean performFinish() {
- initializeRefactoring();
- return super.performFinish();
- }
-
- public IWizardPage getNextPage() {
- initializeRefactoring();
- return super.getNextPage();
- }
-
- private void initializeRefactoring() {
- try {
- String destination= fDestinationField.getText();
- if (!fgMruDestinations.remove(destination) && fgMruDestinations.size() >= MRU_COUNT)
- fgMruDestinations.remove(fgMruDestinations.size() - 1);
- fgMruDestinations.add(0, destination);
-
- getMoveProcessor().setDestinationTypeFullyQualifiedName(destination);
- } catch(JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.MoveMembersInputPage_move_Member, RefactoringMessages.MoveMembersInputPage_exception);
- }
- }
-
- private IJavaScriptSearchScope createWorkspaceSourceScope(){
- IJavaScriptElement[] project= new IJavaScriptElement[] { getMoveProcessor().getDeclaringType().getJavaScriptProject() };
- return SearchEngine.createJavaSearchScope(project, IJavaScriptSearchScope.REFERENCED_PROJECTS | IJavaScriptSearchScope.SOURCES);
- }
-
- private void openTypeSelectionDialog(){
- int elementKinds= IJavaScriptSearchConstants.TYPE;
- final IJavaScriptSearchScope scope= createWorkspaceSourceScope();
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
- getWizard().getContainer(), scope, elementKinds);
- dialog.setTitle(RefactoringMessages.MoveMembersInputPage_choose_Type);
- dialog.setMessage(RefactoringMessages.MoveMembersInputPage_dialogMessage);
- dialog.setValidator(new ISelectionStatusValidator(){
- public IStatus validate(Object[] selection) {
- Assert.isTrue(selection.length <= 1);
- if (selection.length == 0)
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_Invalid_selection, null);
- Object element= selection[0];
- if (! (element instanceof IType))
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_Invalid_selection, null);
- IType type= (IType)element;
- return validateDestinationType(type, type.getElementName());
- }
- });
- dialog.setInitialPattern(createInitialFilter());
- if (dialog.open() == Window.CANCEL)
- return;
- IType firstResult= (IType)dialog.getFirstResult();
- fDestinationField.setText(JavaModelUtil.getFullyQualifiedName(firstResult));
- }
-
- private String createInitialFilter() {
- if (! fDestinationField.getText().trim().equals("")) //$NON-NLS-1$
- return fDestinationField.getText();
- else
- return getMoveProcessor().getDeclaringType().getElementName();
- }
-
- private static IStatus validateDestinationType(IType type, String typeName){
- if (type == null || ! type.exists())
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, Messages.format(RefactoringMessages.MoveMembersInputPage_not_found, typeName), null);
- if (type.isBinary())
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_no_binary, null);
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- private MoveStaticMembersProcessor getMoveProcessor() {
- return (MoveStaticMembersProcessor)getRefactoring().getAdapter(MoveStaticMembersProcessor.class);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ParameterEditDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ParameterEditDialog.java
deleted file mode 100644
index 5a5f07e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ParameterEditDialog.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypeContextChecker;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-
-public class ParameterEditDialog extends StatusDialog {
-
- private final ParameterInfo fParameter;
- private final boolean fEditType;
- private final boolean fEditDefault;
- private final StubTypeContext fContext;
- private Text fType;
- private Text fName;
- private Text fDefaultValue;
-
- /**
- * @param context the <code>IPackageFragment</code> for type ContentAssist.
- * Can be <code>null</code> if <code>canEditType</code> is <code>false</code>.
- */
- public ParameterEditDialog(Shell parentShell, ParameterInfo parameter, boolean canEditType, boolean canEditDefault, StubTypeContext context) {
- super(parentShell);
- fParameter= parameter;
- fEditType= canEditType;
- fEditDefault= canEditDefault;
- fContext= context;
- }
-
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText(RefactoringMessages.ParameterEditDialog_title);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite result= (Composite)super.createDialogArea(parent);
- GridLayout layout= (GridLayout)result.getLayout();
- layout.numColumns= 2;
- Label label;
- GridData gd;
-
- label= new Label(result, SWT.NONE);
- String newName = fParameter.getNewName();
- if (newName.length() == 0)
- label.setText(RefactoringMessages.ParameterEditDialog_message_new);
- else
- label.setText(Messages.format(RefactoringMessages.ParameterEditDialog_message, newName));
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- label.setLayoutData(gd);
-
- if (fEditType) {
- label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ParameterEditDialog_type);
- fType= new Text(result, SWT.BORDER);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- fType.setLayoutData(gd);
- fType.setText(fParameter.getNewTypeName());
- fType.addModifyListener(
- new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate((Text)e.widget);
- }
- });
- TextFieldNavigationHandler.install(fType);
- JavaTypeCompletionProcessor processor= new JavaTypeCompletionProcessor(true, false);
- processor.setCompletionContext(fContext.getCuHandle(), fContext.getBeforeString(), fContext.getAfterString());
- ControlContentAssistHelper.createTextContentAssistant(fType, processor);
- }
-
- label= new Label(result, SWT.NONE);
- fName= new Text(result, SWT.BORDER);
- initializeDialogUnits(fName);
- label.setText(RefactoringMessages.ParameterEditDialog_name);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint= convertWidthInCharsToPixels(45);
- fName.setLayoutData(gd);
- fName.setText(newName);
- fName.addModifyListener(
- new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate((Text)e.widget);
- }
- });
- TextFieldNavigationHandler.install(fName);
-
- if (fEditDefault && fParameter.isAdded()) {
- label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ParameterEditDialog_defaultValue);
- fDefaultValue= new Text(result, SWT.BORDER);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- fDefaultValue.setLayoutData(gd);
- fDefaultValue.setText(fParameter.getDefaultValue());
- fDefaultValue.addModifyListener(
- new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validate((Text)e.widget);
- }
- });
- TextFieldNavigationHandler.install(fDefaultValue);
- }
- applyDialogFont(result);
- return result;
- }
-
- protected void okPressed() {
- if (fType != null) {
- fParameter.setNewTypeName(fType.getText());
- }
- fParameter.setNewName(fName.getText());
- if (fDefaultValue != null) {
- fParameter.setDefaultValue(fDefaultValue.getText());
- }
- super.okPressed();
- }
-
- private void validate(Text first) {
- IStatus[] result= new IStatus[3];
- if (first == fType) {
- result[0]= validateType();
- result[1]= validateName();
- result[2]= validateDefaultValue();
- } else if (first == fName) {
- result[0]= validateName();
- result[1]= validateType();
- result[2]= validateDefaultValue();
- } else {
- result[0]= validateDefaultValue();
- result[1]= validateName();
- result[2]= validateType();
- }
- for (int i= 0; i < result.length; i++) {
- IStatus status= result[i];
- if (status != null && !status.isOK()) {
- updateStatus(status);
- return;
- }
- }
- updateStatus(createOkStatus());
- }
-
- private IStatus validateType() {
- if (fType == null)
- return null;
- String type= fType.getText();
-
- RefactoringStatus status= TypeContextChecker.checkParameterTypeSyntax(type, fContext.getCuHandle().getJavaScriptProject());
- if (status == null || status.isOK())
- return createOkStatus();
- if (status.hasError())
- return createErrorStatus(status.getEntryWithHighestSeverity().getMessage());
- else
- return createWarningStatus(status.getEntryWithHighestSeverity().getMessage());
- }
-
- private IStatus validateName() {
- if (fName == null)
- return null;
- String text= fName.getText();
- if (text.length() == 0)
- return createErrorStatus(RefactoringMessages.ParameterEditDialog_name_error);
- IStatus status= JavaScriptConventions.validateFieldName(text);
- if (status.matches(IStatus.ERROR))
- return status;
- if (! Checks.startsWithLowerCase(text))
- return createWarningStatus(RefactoringCoreMessages.ExtractTempRefactoring_convention);
- return createOkStatus();
- }
-
- private IStatus validateDefaultValue() {
- if (fDefaultValue == null)
- return null;
- String defaultValue= fDefaultValue.getText();
- if (defaultValue.length() == 0)
- return createErrorStatus(RefactoringMessages.ParameterEditDialog_defaultValue_error);
- if (ChangeSignatureRefactoring.isValidExpression(defaultValue))
- return createOkStatus();
- String msg= Messages.format(RefactoringMessages.ParameterEditDialog_defaultValue_invalid, new String[]{defaultValue});
- return createErrorStatus(msg);
-
- }
-
- private Status createOkStatus() {
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- private Status createWarningStatus(String message) {
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.WARNING, message, null);
- }
-
- private Status createErrorStatus(String message) {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, message, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PromoteTempWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PromoteTempWizard.java
deleted file mode 100644
index ee588069..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PromoteTempWizard.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.FieldNameProcessor;
-
-public class PromoteTempWizard extends RefactoringWizard {
-
- public PromoteTempWizard(PromoteTempToFieldRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.ConvertLocalToField_title);
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages(){
- addPage(new PromoteTempInputPage());
- }
-
- private static class PromoteTempInputPage extends UserInputWizardPage {
-
- private static final String DESCRIPTION = RefactoringMessages.PromoteTempInputPage_description;
- public static final String PAGE_NAME= "PromoteTempInputPage";//$NON-NLS-1$
- private static final String[] RADIO_BUTTON_LABELS= {
- RefactoringMessages.PromoteTempInputPage_Field_declaration,
- RefactoringMessages.PromoteTempInputPage_Current_method,
- RefactoringMessages.PromoteTempInputPage_constructors};
- private static final Integer[] RADIO_BUTTON_DATA= {
- new Integer(PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD),
- new Integer(PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD),
- new Integer(PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR)};
- private Button fDeclareStaticCheckbox;
- private Button fDeclareFinalCheckbox;
- private Button[] fInitializeInRadioButtons;
- private Text fNameField;
-
- public PromoteTempInputPage() {
- super(PAGE_NAME);
- setDescription(DESCRIPTION);
- }
-
- public void createControl(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.verticalSpacing= 8;
- result.setLayout(layout);
-
- addFieldNameField(result);
- addVisibilityControl(result);
- addInitizeInRadioButtonGroup(result);
- addDeclareStaticCheckbox(result);
- addDeclareFinalCheckbox(result);
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE);
- }
-
- private void addFieldNameField(Composite result) {
- Label nameLabel= new Label(result, SWT.NONE);
- nameLabel.setText(RefactoringMessages.PromoteTempInputPage_Field_name);
- nameLabel.setLayoutData(new GridData());
-
- String[] guessedFieldNames= getPromoteTempRefactoring().guessFieldNames();
-
- fNameField = new Text(result, SWT.BORDER | SWT.SINGLE);
- fNameField.setText(guessedFieldNames[0]);
- fNameField.selectAll();
- fNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fNameField.addModifyListener(new ModifyListener(){
- public void modifyText(ModifyEvent e) {
- PromoteTempInputPage.this.getPromoteTempRefactoring().setFieldName(fNameField.getText());
- PromoteTempInputPage.this.updateStatus();
- }
- });
- IContentAssistProcessor processor= new FieldNameProcessor(guessedFieldNames, getPromoteTempRefactoring());
- ControlContentAssistHelper.createTextContentAssistant(fNameField, processor);
- TextFieldNavigationHandler.install(fNameField);
- }
-
- private void updateStatus() {
- setPageComplete(getPromoteTempRefactoring().validateInput());
- }
-
- private void addInitizeInRadioButtonGroup(Composite result) {
- GridData gd;
- Group initializeIn= new Group(result, SWT.NONE);
- initializeIn.setText(RefactoringMessages.PromoteTempInputPage_Initialize);
- initializeIn.setLayout(new GridLayout());
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- initializeIn.setLayoutData(gd);
-
- Assert.isTrue(RADIO_BUTTON_LABELS.length == RADIO_BUTTON_DATA.length);
- fInitializeInRadioButtons= new Button[RADIO_BUTTON_LABELS.length];
- for (int i= 0; i < RADIO_BUTTON_LABELS.length; i++) {
- Integer dataItem= RADIO_BUTTON_DATA[i];
- fInitializeInRadioButtons[i]= new Button(initializeIn, SWT.RADIO);
- fInitializeInRadioButtons[i].setEnabled(canEnable(dataItem.intValue()));
- fInitializeInRadioButtons[i].setText(RADIO_BUTTON_LABELS[i]);
- fInitializeInRadioButtons[i].setSelection(dataItem.intValue() == getPromoteTempRefactoring().getInitializeIn());
- fInitializeInRadioButtons[i].setLayoutData(new GridData());
- fInitializeInRadioButtons[i].setData(dataItem);
- final int j= i;
- fInitializeInRadioButtons[i].addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getPromoteTempRefactoring().setInitializeIn(getDataAsInt(fInitializeInRadioButtons[j]));
- updateButtonsEnablement();
- }
- });
- }
- }
-
- private void updateButtonsEnablement() {
- fDeclareFinalCheckbox.setEnabled(getPromoteTempRefactoring().canEnableSettingFinal());
- fDeclareStaticCheckbox.setEnabled(getPromoteTempRefactoring().canEnableSettingStatic());
- for (int i= 0; i < fInitializeInRadioButtons.length; i++) {
- fInitializeInRadioButtons[i].setEnabled(canEnable(getDataAsInt(fInitializeInRadioButtons[i])));
- }
- }
-
- private static int getDataAsInt(Button button){
- return ((Integer)button.getData()).intValue();
- }
-
- private boolean canEnable(int initializeIn){
- switch(initializeIn){
- case PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR:
- return getPromoteTempRefactoring().canEnableSettingDeclareInConstructors();
- case PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD:
- return getPromoteTempRefactoring().canEnableSettingDeclareInFieldDeclaration();
- case PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD:
- return getPromoteTempRefactoring().canEnableSettingDeclareInMethod();
- default: Assert.isTrue(false); return false;
- }
- }
-
- public void addDeclareStaticCheckbox(Composite result) {
- GridData gd;
- fDeclareStaticCheckbox= new Button(result, SWT.CHECK);
- fDeclareStaticCheckbox.setEnabled(getPromoteTempRefactoring().canEnableSettingStatic());
- fDeclareStaticCheckbox.setSelection(getPromoteTempRefactoring().getDeclareStatic());
- fDeclareStaticCheckbox.setText(RefactoringMessages.PromoteTempInputPage_declare_static);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- fDeclareStaticCheckbox.setLayoutData(gd);
- fDeclareStaticCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getPromoteTempRefactoring().setDeclareStatic(fDeclareStaticCheckbox.getSelection());
- updateButtonsEnablement();
- }
- });
- }
-
- private void addDeclareFinalCheckbox(Composite result) {
- GridData gd;
- fDeclareFinalCheckbox= new Button(result, SWT.CHECK);
- fDeclareFinalCheckbox.setEnabled(getPromoteTempRefactoring().canEnableSettingFinal());
- fDeclareFinalCheckbox.setSelection(getPromoteTempRefactoring().getDeclareFinal());
- fDeclareFinalCheckbox.setText(RefactoringMessages.PromoteTempInputPage_declare_final);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- fDeclareFinalCheckbox.setLayoutData(gd);
- fDeclareFinalCheckbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getPromoteTempRefactoring().setDeclareFinal(fDeclareFinalCheckbox.getSelection());
- updateButtonsEnablement();
- }
- });
- }
-
- private void addVisibilityControl(Composite result) {
- int[] availableVisibilities= getPromoteTempRefactoring().getAvailableVisibilities();
- int currectVisibility= getPromoteTempRefactoring().getVisibility();
- IVisibilityChangeListener visibilityChangeListener= new IVisibilityChangeListener(){
- public void visibilityChanged(int newVisibility) {
- getPromoteTempRefactoring().setVisibility(newVisibility);
- }
-
- public void modifierChanged(int modifier, boolean isChecked) {
- }
- };
- Composite visibilityComposite= VisibilityControlUtil.createVisibilityControl(result, visibilityChangeListener, availableVisibilities, currectVisibility);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan= 2;
- visibilityComposite.setLayoutData(gd);
- }
-
- private PromoteTempToFieldRefactoring getPromoteTempRefactoring(){
- return (PromoteTempToFieldRefactoring)getRefactoring();
- }
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible && fNameField != null)
- fNameField.setFocus();
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullPushCheckboxTableViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullPushCheckboxTableViewer.java
deleted file mode 100644
index 6bee6fb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullPushCheckboxTableViewer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.IMemberActionInfo;
-
-class PullPushCheckboxTableViewer extends CheckboxTableViewer{
- public PullPushCheckboxTableViewer(Table table) {
- super(table);
- }
-
- /*
- * @see org.eclipse.jface.viewers.StructuredViewer#doUpdateItem(org.eclipse.swt.widgets.Widget, java.lang.Object, boolean)
- */
- protected void doUpdateItem(Widget widget, Object element, boolean fullMap) {
- super.doUpdateItem(widget, element, fullMap);
- if (! (widget instanceof TableItem))
- return;
- TableItem item= (TableItem)widget;
- IMemberActionInfo info= (IMemberActionInfo)element;
- item.setChecked(PullPushCheckboxTableViewer.getCheckState(info));
- Assert.isTrue(item.getChecked() == PullPushCheckboxTableViewer.getCheckState(info));
- }
-
- /*
- * @see org.eclipse.jface.viewers.Viewer#inputChanged(java.lang.Object, java.lang.Object)
- */
- protected void inputChanged(Object input, Object oldInput) {
- super.inputChanged(input, oldInput);
- // XXX workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=9390
- setCheckState((IMemberActionInfo[])input);
- }
-
- private void setCheckState(IMemberActionInfo[] infos) {
- if (infos == null)
- return;
- for (int i= 0; i < infos.length; i++) {
- IMemberActionInfo info= infos[i];
- setChecked(info, PullPushCheckboxTableViewer.getCheckState(info));
- }
- }
-
- private static boolean getCheckState(IMemberActionInfo info) {
- return info.isActive();
- }
-
- /*
- * @see org.eclipse.jface.viewers.Viewer#refresh()
- */
- public void refresh() {
- int topIndex = getTable().getTopIndex();
- super.refresh();
- // XXX workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=9390
- setCheckState((IMemberActionInfo[])getInput());
- if (topIndex < getTable().getItemCount())
- getTable().setTopIndex(topIndex); //see bug 31645
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMemberPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMemberPage.java
deleted file mode 100644
index 4dd1b9bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMemberPage.java
+++ /dev/null
@@ -1,972 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.HierarchyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.IMemberActionInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * Wizard page for pull up refactoring wizards which allows to specify the
- * actions on the members to pull up.
- *
- *
- */
-public class PullUpMemberPage extends UserInputWizardPage {
-
- private class MemberActionCellModifier implements ICellModifier {
-
- public boolean canModify(final Object element, final String property) {
- if (!ACTION_PROPERTY.equals(property))
- return false;
- return ((MemberActionInfo) element).isEditable();
- }
-
- public Object getValue(final Object element, final String property) {
- if (!ACTION_PROPERTY.equals(property))
- return null;
- final MemberActionInfo info= (MemberActionInfo) element;
- return new Integer(info.getAction());
- }
-
- public void modify(final Object element, final String property, final Object value) {
- if (!ACTION_PROPERTY.equals(property))
- return;
- final int action= ((Integer) value).intValue();
- MemberActionInfo info;
- if (element instanceof Item) {
- info= (MemberActionInfo) ((Item) element).getData();
- } else
- info= (MemberActionInfo) element;
- if (!canModify(info, property))
- return;
- Assert.isTrue(info.isMethodInfo());
- info.setAction(action);
- updateWizardPage(null, true);
- }
- }
-
- private class MemberActionInfo implements IMemberActionInfo {
-
- private static final int NO_ACTION= 2;
-
- private int fAction;
-
- private final IMember fMember;
-
- public MemberActionInfo(final IMember member, final int action) {
- Assert.isTrue((member instanceof IFunction) || (member instanceof IField) || (member instanceof IType));
- assertAction(member, action);
- fMember= member;
- fAction= action;
- }
-
- private void assertAction(final IMember member, final int action) {
- if (member instanceof IFunction) {
- try {
- Assert.isTrue(action != DECLARE_ABSTRACT_ACTION || !JdtFlags.isStatic(member));
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- Assert.isTrue(action == NO_ACTION || action == DECLARE_ABSTRACT_ACTION || action == PULL_UP_ACTION);
- } else {
- Assert.isTrue(action == NO_ACTION || action == PULL_UP_ACTION);
- }
- }
-
- public int getAction() {
- return fAction;
- }
-
- public String getActionLabel() {
- switch (fAction) {
- case PULL_UP_ACTION:
- return getPullUpActionLabel();
- case DECLARE_ABSTRACT_ACTION:
- return getDeclareAbstractActionLabel();
- case NO_ACTION:
- return ""; //$NON-NLS-1$
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public String[] getAllowedLabels() {
- if (isFieldInfo())
- return new String[] { ""}; //$NON-NLS-1$
- else if (isMethodInfo())
- return METHOD_LABELS;
- else if (isTypeInfo())
- return TYPE_LABELS;
- else {
- Assert.isTrue(false);
- return null;
- }
- }
-
- public IMember getMember() {
- return fMember;
- }
-
- public boolean isActive() {
- return getAction() != NO_ACTION;
- }
-
- public boolean isEditable() {
- if (fAction == NO_ACTION)
- return false;
- if (!isMethodInfo())
- return false;
- final IFunction method= (IFunction) fMember;
- try {
- return !JdtFlags.isStatic(method);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return false;
- }
- }
-
- public boolean isFieldInfo() {
- return getMember() instanceof IField;
- }
-
- public boolean isMethodInfo() {
- return getMember() instanceof IFunction;
- }
-
- public boolean isTypeInfo() {
- return getMember() instanceof IType;
- }
-
- public void setAction(final int action) {
- assertAction(fMember, action);
- fAction= action;
- }
- }
-
- private static class MemberActionInfoLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- private final ILabelProvider fLabelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_SMALL_ICONS);
-
- public void dispose() {
- super.dispose();
- fLabelProvider.dispose();
- }
-
- public Image getColumnImage(final Object element, final int columnIndex) {
- final MemberActionInfo info= (MemberActionInfo) element;
- switch (columnIndex) {
- case MEMBER_COLUMN:
- return fLabelProvider.getImage(info.getMember());
- case ACTION_COLUMN:
- return null;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public String getColumnText(final Object element, final int columnIndex) {
- final MemberActionInfo info= (MemberActionInfo) element;
- switch (columnIndex) {
- case MEMBER_COLUMN:
- return fLabelProvider.getText(info.getMember());
- case ACTION_COLUMN:
- return info.getActionLabel();
- default:
- Assert.isTrue(false);
- return null;
- }
- }
- }
-
- private static final int ACTION_COLUMN= 1;
-
- private static final String ACTION_PROPERTY= "action"; //$NON-NLS-1$
-
- protected static final int DECLARE_ABSTRACT_ACTION= 1;
-
- private static final int MEMBER_COLUMN= 0;
-
- private static final String MEMBER_PROPERTY= "member"; //$NON-NLS-1$
-
- protected static final int PULL_UP_ACTION= 0;
-
- private static final String SETTING_INSTANCEOF= "InstanceOf"; //$NON-NLS-1$
-
- private static final String SETTING_REPLACE= "Replace"; //$NON-NLS-1$
-
- private static int getEditableCount(final MemberActionInfo[] infos) {
- int result= 0;
- for (int i= 0; i < infos.length; i++) {
- final MemberActionInfo info= infos[i];
- if (info.isEditable())
- result++;
- }
- return result;
- }
-
- private static void putToStringMapping(final Map result, final String[] actionLabels, final int actionIndex) {
- result.put(actionLabels[actionIndex], new Integer(actionIndex));
- }
-
- private static void setActionForInfos(final MemberActionInfo[] infos, final int action) {
- for (int i= 0; i < infos.length; i++) {
- infos[i].setAction(action);
- }
- }
-
- private Button fAddButton;
-
- protected IType[] fCandidateTypes= {};
-
- private Button fCreateStubsButton;
-
- private Button fDeselectAllButton;
-
- private Button fEditButton;
-
- private Button fInstanceofButton;
-
- private Label fLabel;
-
- private Button fReplaceButton;
-
- private Button fSelectAllButton;
-
- private Label fStatusLine;
-
- protected final PullUpMethodPage fSuccessorPage;
-
- private Combo fSuperTypesCombo;
-
- private CheckboxTableViewer fTableViewer;
-
- protected final String[] METHOD_LABELS;
-
- protected final String[] TYPE_LABELS;
-
- public PullUpMemberPage(final String name, final PullUpMethodPage page) {
- super(name);
- fSuccessorPage= page;
- setDescription(RefactoringMessages.PullUpInputPage1_page_message);
- METHOD_LABELS= new String[2];
- METHOD_LABELS[PULL_UP_ACTION]= RefactoringMessages.PullUpInputPage1_pull_up;
- METHOD_LABELS[DECLARE_ABSTRACT_ACTION]= RefactoringMessages.PullUpInputPage1_declare_abstract;
-
- TYPE_LABELS= new String[1];
- TYPE_LABELS[PULL_UP_ACTION]= RefactoringMessages.PullUpInputPage1_pull_up;
- }
-
- private boolean areAllMembersMarkedAsPullUp() {
- return getMembersForAction(PULL_UP_ACTION).length == getTableInput().length;
- }
-
- protected boolean areAllMembersMarkedAsWithNoAction() {
- return getMembersForAction(MemberActionInfo.NO_ACTION).length == getTableInput().length;
- }
-
- private MemberActionInfo[] asMemberActionInfos() {
- final PullUpRefactoringProcessor processor= getPullUpRefactoring().getPullUpProcessor();
- final List toPullUp= Arrays.asList(processor.getMembersToMove());
- final IMember[] members= processor.getPullableMembersOfDeclaringType();
- final MemberActionInfo[] result= new MemberActionInfo[members.length];
- for (int i= 0; i < members.length; i++) {
- final IMember member= members[i];
- if (toPullUp.contains(member))
- result[i]= new MemberActionInfo(member, PULL_UP_ACTION);
- else
- result[i]= new MemberActionInfo(member, MemberActionInfo.NO_ACTION);
- }
- return result;
- }
-
- public boolean canFlipToNextPage() {
- if (getMethodsForAction(PULL_UP_ACTION).length == 0)
- return isPageComplete();
- return super.canFlipToNextPage();
- }
-
- private void checkAdditionalRequired() {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor pm) throws InvocationTargetException {
- try {
- checkPullUp(getPullUpRefactoring().getPullUpProcessor().getAdditionalRequiredMembersToPullUp(pm), true);
- } catch (JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- } finally {
- pm.done();
- }
- }
- });
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.PullUpInputPage_pull_Up, RefactoringMessages.PullUpInputPage_exception);
- } catch (InterruptedException e) {
- Assert.isTrue(false);
- }
- }
-
- protected void checkPageCompletionStatus(final boolean displayErrors) {
- if (areAllMembersMarkedAsWithNoAction()) {
- if (displayErrors)
- setErrorMessage(getNoMembersMessage());
- setPageComplete(false);
- } else {
- setErrorMessage(null);
- setPageComplete(true);
- }
- fSuccessorPage.fireSettingsChanged();
- }
-
- private void checkPullUp(final IMember[] elements, final boolean displayErrors) {
- setActionForMembers(elements, PULL_UP_ACTION);
- updateWizardPage(null, displayErrors);
- }
-
- private void createButtonComposite(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- final GridLayout gl= new GridLayout();
- gl.marginHeight= 0;
- gl.marginWidth= 0;
- composite.setLayout(gl);
-
- fSelectAllButton= new Button(composite, SWT.PUSH);
- fSelectAllButton.setText(RefactoringMessages.PullUpWizard_select_all_label);
- fSelectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fSelectAllButton.setEnabled(true);
- SWTUtil.setButtonDimensionHint(fSelectAllButton);
- fSelectAllButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- final IMember[] members= getMembers();
- setActionForMembers(members, PULL_UP_ACTION);
- updateWizardPage(null, true);
- }
- });
-
- fDeselectAllButton= new Button(composite, SWT.PUSH);
- fDeselectAllButton.setText(RefactoringMessages.PullUpWizard_deselect_all_label);
- fDeselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fDeselectAllButton.setEnabled(false);
- SWTUtil.setButtonDimensionHint(fDeselectAllButton);
- fDeselectAllButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- final IMember[] members= getMembers();
- setActionForMembers(members, MemberActionInfo.NO_ACTION);
- updateWizardPage(null, true);
- }
- });
-
- fEditButton= new Button(composite, SWT.PUSH);
- fEditButton.setText(RefactoringMessages.PullUpInputPage1_Edit);
-
- final GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.verticalIndent= new PixelConverter(parent).convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- fEditButton.setLayoutData(data);
- fEditButton.setEnabled(false);
- SWTUtil.setButtonDimensionHint(fEditButton);
- fEditButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- editSelectedMembers();
- }
- });
-
- fAddButton= new Button(composite, SWT.PUSH);
- fAddButton.setText(RefactoringMessages.PullUpInputPage1_Add_Required);
- fAddButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(fAddButton);
- fAddButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- checkAdditionalRequired();
- }
- });
- }
-
- public void createControl(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- composite.setLayout(layout);
-
- createSuperTypeControl(composite);
- createSpacer(composite);
- createSuperTypeCheckbox(composite);
- createInstanceOfCheckbox(composite, layout.marginWidth);
- createStubCheckbox(composite);
- createSpacer(composite);
- createMemberTableLabel(composite);
- createMemberTableComposite(composite);
- createStatusLine(composite);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- initializeEnablement();
- initializeCheckboxes();
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PULL_UP_WIZARD_PAGE);
- }
-
- protected void createInstanceOfCheckbox(final Composite result, final int margin) {
- final HierarchyProcessor processor= getPullUpRefactoring().getPullUpProcessor();
- fInstanceofButton= new Button(result, SWT.CHECK);
- fInstanceofButton.setSelection(false);
- final GridData gd= new GridData();
- gd.horizontalIndent= (margin + fInstanceofButton.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- gd.horizontalSpan= 2;
- fInstanceofButton.setLayoutData(gd);
- fInstanceofButton.setText(getInstanceofButtonLabel());
- processor.setInstanceOf(fInstanceofButton.getSelection());
- fInstanceofButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent e) {
- processor.setInstanceOf(fInstanceofButton.getSelection());
- }
- });
- fReplaceButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent e) {
- fInstanceofButton.setEnabled(fReplaceButton.getSelection());
- }
- });
- }
-
- private void createMemberTable(final Composite parent) {
- final TableLayoutComposite layouter= new TableLayoutComposite(parent, SWT.NONE);
- layouter.addColumnData(new ColumnWeightData(60, true));
- layouter.addColumnData(new ColumnWeightData(40, true));
-
- final Table table= new Table(layouter, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- final GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= SWTUtil.getTableHeightHint(table, getTableRowCount());
- gd.widthHint= convertWidthInCharsToPixels(30);
- layouter.setLayoutData(gd);
-
- final TableLayout tableLayout= new TableLayout();
- table.setLayout(tableLayout);
-
- final TableColumn column0= new TableColumn(table, SWT.NONE);
- column0.setText(RefactoringMessages.PullUpInputPage1_Member);
-
- final TableColumn column1= new TableColumn(table, SWT.NONE);
- column1.setText(RefactoringMessages.PullUpInputPage1_Action);
-
- fTableViewer= new PullPushCheckboxTableViewer(table);
- fTableViewer.setUseHashlookup(true);
- fTableViewer.setContentProvider(new ArrayContentProvider());
- fTableViewer.setLabelProvider(new MemberActionInfoLabelProvider());
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- updateButtonEnablement(event.getSelection());
- }
- });
- fTableViewer.addCheckStateListener(new ICheckStateListener() {
-
- public void checkStateChanged(final CheckStateChangedEvent event) {
- final boolean checked= event.getChecked();
- final MemberActionInfo info= (MemberActionInfo) event.getElement();
- if (checked)
- info.setAction(PULL_UP_ACTION);
- else
- info.setAction(MemberActionInfo.NO_ACTION);
- updateWizardPage(null, true);
- }
- });
- fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(final DoubleClickEvent event) {
- editSelectedMembers();
- }
- });
-
- setTableInput();
- checkPullUp(getPullUpRefactoring().getPullUpProcessor().getMembersToMove(), false);
- setupCellEditors(table);
- }
-
- protected void createMemberTableComposite(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- final GridData data= new GridData(GridData.FILL_BOTH);
- data.horizontalSpan= 2;
- composite.setLayoutData(data);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- createMemberTable(composite);
- createButtonComposite(composite);
- }
-
- protected void createMemberTableLabel(final Composite parent) {
- fLabel= new Label(parent, SWT.NONE);
- fLabel.setText(RefactoringMessages.PullUpInputPage1_Specify_actions);
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- fLabel.setLayoutData(data);
- }
-
- protected void createSpacer(final Composite parent) {
- final Label label= new Label(parent, SWT.NONE);
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- data.heightHint= convertHeightInCharsToPixels(1) / 2;
- label.setLayoutData(data);
- }
-
- protected void createStatusLine(final Composite composite) {
- fStatusLine= new Label(composite, SWT.NONE);
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- updateStatusLine();
- fStatusLine.setLayoutData(data);
- }
-
- // String -> Integer
- private Map createStringMappingForSelectedMembers() {
- final Map result= new HashMap();
- putToStringMapping(result, METHOD_LABELS, PULL_UP_ACTION);
- putToStringMapping(result, METHOD_LABELS, DECLARE_ABSTRACT_ACTION);
- return result;
- }
-
- protected void createStubCheckbox(final Composite parent) {
- fCreateStubsButton= new Button(parent, SWT.CHECK);
- fCreateStubsButton.setText(getCreateStubsButtonLabel());
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- fCreateStubsButton.setLayoutData(data);
- fCreateStubsButton.setEnabled(false);
- fCreateStubsButton.setSelection(getPullUpRefactoring().getPullUpProcessor().getCreateMethodStubs());
- }
-
- protected void createSuperTypeCheckbox(final Composite parent) {
- fReplaceButton= new Button(parent, SWT.CHECK);
- fReplaceButton.setText(getReplaceButtonLabel());
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- fReplaceButton.setLayoutData(data);
- fReplaceButton.setEnabled(true);
- fReplaceButton.setSelection(getPullUpRefactoring().getPullUpProcessor().isReplace());
- }
-
- private void createSuperTypeCombo(final IProgressMonitor pm, final Composite parent) throws JavaScriptModelException {
- final Label label= new Label(parent, SWT.NONE);
- label.setText(RefactoringMessages.PullUpInputPage1_Select_destination);
- label.setLayoutData(new GridData());
-
- fSuperTypesCombo= new Combo(parent, SWT.READ_ONLY);
- fCandidateTypes= getPullUpRefactoring().getPullUpProcessor().getCandidateTypes(new RefactoringStatus(), pm);
- if (fCandidateTypes.length > 0) {
- for (int i= 0; i < fCandidateTypes.length; i++) {
- final String comboLabel= JavaModelUtil.getFullyQualifiedName(fCandidateTypes[i]);
- fSuperTypesCombo.add(comboLabel);
- }
- fSuperTypesCombo.select(fCandidateTypes.length - 1);
- fSuperTypesCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
- }
-
- protected void createSuperTypeControl(final Composite parent) {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor monitor) throws InvocationTargetException {
- try {
- createSuperTypeCombo(monitor, parent);
- } catch (JavaScriptModelException exception) {
- throw new InvocationTargetException(exception);
- } finally {
- monitor.done();
- }
- }
- });
- } catch (InvocationTargetException exception) {
- ExceptionHandler.handle(exception, getShell(), RefactoringMessages.PullUpInputPage_pull_Up, RefactoringMessages.PullUpInputPage_exception);
- } catch (InterruptedException exception) {
- Assert.isTrue(false);
- }
- }
-
- public void dispose() {
- fInstanceofButton= null;
- fReplaceButton= null;
- fTableViewer= null;
- super.dispose();
- }
-
- private void editSelectedMembers() {
- if (!fEditButton.isEnabled())
- return;
-
- final ISelection preserved= fTableViewer.getSelection();
- try {
- final String shellTitle= RefactoringMessages.PullUpInputPage1_Edit_members;
- final String labelText= RefactoringMessages.PullUpInputPage1_Mark_selected_members;
- final Map stringMapping= createStringMappingForSelectedMembers();
- final String[] keys= (String[]) stringMapping.keySet().toArray(new String[stringMapping.keySet().size()]);
- Arrays.sort(keys);
- final int initialSelectionIndex= getInitialSelectionIndexForEditDialog(stringMapping, keys);
- final ComboSelectionDialog dialog= new ComboSelectionDialog(getShell(), shellTitle, labelText, keys, initialSelectionIndex);
- dialog.setBlockOnOpen(true);
- if (dialog.open() == Window.CANCEL)
- return;
- final int action= ((Integer) stringMapping.get(dialog.getSelectedString())).intValue();
- setActionForInfos(getSelectedMembers(), action);
- } finally {
- updateWizardPage(preserved, true);
- }
- }
-
- private boolean enableEditButton(final IStructuredSelection ss) {
- if (ss.isEmpty() || ss.size() == 0)
- return false;
- return ss.size() == getEditableCount(getSelectedMembers());
- }
-
- private MemberActionInfo[] getActiveInfos() {
- final MemberActionInfo[] infos= getTableInput();
- final List result= new ArrayList(infos.length);
- for (int i= 0; i < infos.length; i++) {
- final MemberActionInfo info= infos[i];
- if (info.isActive())
- result.add(info);
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- private int getCommonActionCodeForSelectedInfos() {
- final MemberActionInfo[] infos= getSelectedMembers();
- if (infos.length == 0)
- return -1;
-
- final int code= infos[0].getAction();
- for (int i= 0; i < infos.length; i++) {
- if (code != infos[i].getAction())
- return -1;
- }
- return code;
- }
-
- protected String getCreateStubsButtonLabel() {
- return RefactoringMessages.PullUpInputPage1_Create_stubs;
- }
-
- protected String getDeclareAbstractActionLabel() {
- return RefactoringMessages.PullUpInputPage1_declare_abstract;
- }
-
- public IType getDestinationType() {
- final int index= fSuperTypesCombo.getSelectionIndex();
- if (index >= 0)
- return fCandidateTypes[index];
- return null;
- }
-
- private int getInitialSelectionIndexForEditDialog(final Map stringMapping, final String[] keys) {
- final int commonActionCode= getCommonActionCodeForSelectedInfos();
- if (commonActionCode == -1)
- return 0;
- for (final Iterator iter= stringMapping.keySet().iterator(); iter.hasNext();) {
- final String key= (String) iter.next();
- final int action= ((Integer) stringMapping.get(key)).intValue();
- if (commonActionCode == action) {
- for (int i= 0; i < keys.length; i++) {
- if (key.equals(keys[i]))
- return i;
- }
- Assert.isTrue(false);
- }
- }
- return 0;
- }
-
- protected String getInstanceofButtonLabel() {
- return RefactoringMessages.PullUpInputPage1_label_use_in_instanceof;
- }
-
- private IMember[] getMembers() {
- final MemberActionInfo[] infos= getTableInput();
- final List result= new ArrayList(infos.length);
- for (int index= 0; index < infos.length; index++) {
- result.add(infos[index].getMember());
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- private IMember[] getMembersForAction(final int action) {
- final MemberActionInfo[] infos= getTableInput();
- final List result= new ArrayList(infos.length);
- for (int index= 0; index < infos.length; index++) {
- if (infos[index].getAction() == action)
- result.add(infos[index].getMember());
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- private IFunction[] getMethodsForAction(final int action) {
- final MemberActionInfo[] infos= getTableInput();
- final List list= new ArrayList(infos.length);
- for (int index= 0; index < infos.length; index++) {
- if (infos[index].isMethodInfo() && infos[index].getAction() == action) {
- list.add(infos[index].getMember());
- }
- }
- return (IFunction[]) list.toArray(new IFunction[list.size()]);
- }
-
- public IWizardPage getNextPage() {
- initializeRefactoring();
- storeDialogSettings();
- if (getMethodsForAction(PULL_UP_ACTION).length == 0)
- return computeSuccessorPage();
-
- return super.getNextPage();
- }
-
- protected String getNoMembersMessage() {
- return RefactoringMessages.PullUpInputPage1_Select_members_to_pull_up;
- }
-
- protected String getPullUpActionLabel() {
- return RefactoringMessages.PullUpInputPage1_pull_up;
- }
-
- private PullUpRefactoring getPullUpRefactoring() {
- return (PullUpRefactoring) getRefactoring();
- }
-
- protected String getReplaceButtonLabel() {
- return RefactoringMessages.PullUpInputPage1_label_use_destination;
- }
-
- private MemberActionInfo[] getSelectedMembers() {
- Assert.isTrue(fTableViewer.getSelection() instanceof IStructuredSelection);
- final IStructuredSelection structured= (IStructuredSelection) fTableViewer.getSelection();
- final List result= structured.toList();
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- private MemberActionInfo[] getTableInput() {
- return (MemberActionInfo[]) fTableViewer.getInput();
- }
-
- protected int getTableRowCount() {
- return 10;
- }
-
- private void initializeCheckBox(final Button checkbox, final String property, final boolean def) {
- final String s= JavaScriptPlugin.getDefault().getDialogSettings().get(property);
- if (s != null)
- checkbox.setSelection(new Boolean(s).booleanValue());
- else
- checkbox.setSelection(def);
- }
-
- protected void initializeCheckboxes() {
- initializeCheckBox(fReplaceButton, SETTING_REPLACE, true);
- initializeCheckBox(fInstanceofButton, SETTING_INSTANCEOF, false);
- }
-
- protected void initializeEnablement() {
- MemberActionInfo[] infos= asMemberActionInfos();
- final boolean enabled= infos.length > 0;
- fTableViewer.getTable().setEnabled(enabled);
- fStatusLine.setEnabled(enabled);
- fAddButton.setEnabled(enabled);
- fLabel.setEnabled(enabled);
- }
-
- private void initializeRefactoring() {
- final PullUpRefactoringProcessor processor= getPullUpRefactoring().getPullUpProcessor();
- processor.setMembersToMove(getMembersForAction(PULL_UP_ACTION));
- processor.setAbstractMethods(getMethodsForAction(DECLARE_ABSTRACT_ACTION));
- final IType destination= getDestinationType();
- if (destination != null)
- processor.setDestinationType(destination);
- processor.setCreateMethodStubs(fCreateStubsButton.getSelection());
- processor.setReplace(fReplaceButton.getSelection());
- processor.setInstanceOf(fInstanceofButton.getSelection());
- processor.setDeletedMethods(getMethodsForAction(PULL_UP_ACTION));
- }
-
- protected boolean performFinish() {
- initializeRefactoring();
- storeDialogSettings();
- return super.performFinish();
- }
-
- private void setActionForMembers(final IMember[] members, final int action) {
- final MemberActionInfo[] infos= getTableInput();
- for (int i= 0; i < members.length; i++) {
- for (int j= 0; j < infos.length; j++) {
- if (infos[j].getMember().equals(members[i]))
- infos[j].setAction(action);
- }
- }
- }
-
- private void setTableInput() {
- fTableViewer.setInput(asMemberActionInfos());
- }
-
- private void setupCellEditors(final Table table) {
- final ComboBoxCellEditor editor= new ComboBoxCellEditor();
- editor.setStyle(SWT.READ_ONLY);
- fTableViewer.setCellEditors(new CellEditor[] { null, editor});
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- if (editor.getControl() == null & !table.isDisposed())
- editor.create(table);
- final ISelection sel= event.getSelection();
- if (!(sel instanceof IStructuredSelection))
- return;
- final IStructuredSelection structured= (IStructuredSelection) sel;
- if (structured.size() != 1)
- return;
- final MemberActionInfo info= (MemberActionInfo) structured.getFirstElement();
- editor.setItems(info.getAllowedLabels());
- editor.setValue(new Integer(info.getAction()));
- }
- });
-
- final ICellModifier cellModifier= new MemberActionCellModifier();
- fTableViewer.setCellModifier(cellModifier);
- fTableViewer.setColumnProperties(new String[] { MEMBER_PROPERTY, ACTION_PROPERTY});
- }
-
- public void setVisible(final boolean visible) {
- super.setVisible(visible);
- if (visible) {
- try {
- getPullUpRefactoring().getPullUpProcessor().resetEnvironment();
- } finally {
- fTableViewer.setSelection(new StructuredSelection(getActiveInfos()), true);
- fTableViewer.getControl().setFocus();
- }
- }
- }
-
- private void storeDialogSettings() {
- final IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- settings.put(SETTING_REPLACE, fReplaceButton.getSelection());
- settings.put(SETTING_INSTANCEOF, fInstanceofButton.getSelection());
- }
-
- private void updateButtonEnablement(final ISelection selection) {
- if (fEditButton != null)
- fEditButton.setEnabled(enableEditButton((IStructuredSelection) selection));
- fCreateStubsButton.setEnabled(getMethodsForAction(DECLARE_ABSTRACT_ACTION).length != 0);
- fInstanceofButton.setEnabled(fReplaceButton.getSelection());
- if (fSelectAllButton != null)
- fSelectAllButton.setEnabled(!areAllMembersMarkedAsPullUp());
- if (fDeselectAllButton != null)
- fDeselectAllButton.setEnabled(!areAllMembersMarkedAsWithNoAction());
- }
-
- private void updateStatusLine() {
- if (fStatusLine == null)
- return;
- final int selected= fTableViewer.getCheckedElements().length;
- final String[] keys= { String.valueOf(selected)};
- final String msg= Messages.format(RefactoringMessages.PullUpInputPage1_status_line, keys);
- fStatusLine.setText(msg);
- }
-
- private void updateWizardPage(final ISelection selection, final boolean displayErrors) {
- fTableViewer.refresh();
- if (selection != null) {
- fTableViewer.getControl().setFocus();
- fTableViewer.setSelection(selection);
- }
- checkPageCompletionStatus(displayErrors);
- updateButtonEnablement(fTableViewer.getSelection());
- updateStatusLine();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMethodPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMethodPage.java
deleted file mode 100644
index 2fc358df..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpMethodPage.java
+++ /dev/null
@@ -1,562 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.HierarchyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-/**
- * Wizard page for pull up refactoring wizards which allows to specify the
- * methods to be deleted in subtypes after pull up.
- *
- *
- */
-public class PullUpMethodPage extends UserInputWizardPage {
-
- private static class PullUpFilter extends ViewerFilter {
-
- private static boolean anySubtypeCanBeShown(final IType type, final Map typeToMemberArray, final ITypeHierarchy hierarchy) {
- final IType[] subTypes= hierarchy.getSubclasses(type);
- for (int i= 0; i < subTypes.length; i++) {
- if (canBeShown(subTypes[i], typeToMemberArray, hierarchy))
- return true;
- }
- return false;
- }
-
- private static boolean canBeShown(final IType type, final Map typeToMemberArray, final ITypeHierarchy hierarchy) {
- if (typeToMemberArray.containsKey(type))
- return true;
- return anySubtypeCanBeShown(type, typeToMemberArray, hierarchy);
- }
-
- private static Set computeShowableSubtypesOfMainType(final ITypeHierarchy hierarchy, final Map typeToMemberArray) {
- final Set result= new HashSet();
- final IType[] subtypes= hierarchy.getAllSubtypes(hierarchy.getType());
- for (int i= 0; i < subtypes.length; i++) {
- final IType subtype= subtypes[i];
- if (canBeShown(subtype, typeToMemberArray, hierarchy))
- result.add(subtype);
- }
- return result;
- }
-
- private static Set computeTypesToShow(final ITypeHierarchy hierarchy, final Map typeToMemberArray) {
- final Set typesToShow= new HashSet();
- typesToShow.add(hierarchy.getType());
- typesToShow.addAll(computeShowableSubtypesOfMainType(hierarchy, typeToMemberArray));
- return typesToShow;
- }
-
- private final Set fTypesToShow;
-
- public PullUpFilter(final ITypeHierarchy hierarchy, final IMember[] members) {
- // IType -> IMember[]
- final Map map= PullUpMethodPage.createTypeToMemberArrayMapping(members);
- fTypesToShow= computeTypesToShow(hierarchy, map);
- }
-
- public boolean select(final Viewer viewer, final Object parentElement, final Object element) {
- if (element instanceof IFunction)
- return true;
- return fTypesToShow.contains(element);
- }
- }
-
- private static class PullUpHierarchyContentProvider implements ITreeContentProvider {
-
- private IType fDeclaringType;
-
- private ITypeHierarchy fHierarchy;
-
- private Map fTypeToMemberArray; // IType -> IMember[]
-
- public PullUpHierarchyContentProvider(final IType declaringType, final IMember[] members) {
- fDeclaringType= declaringType;
- fTypeToMemberArray= PullUpMethodPage.createTypeToMemberArrayMapping(members);
- }
-
- public void dispose() {
- fHierarchy= null;
- fTypeToMemberArray.clear();
- fTypeToMemberArray= null;
- fDeclaringType= null;
- }
-
- public Object[] getChildren(final Object parentElement) {
- if (parentElement instanceof IType)
- return getSubclassesAndMembers((IType) parentElement);
- else
- return new Object[0];
- }
-
- public Object[] getElements(final Object inputElement) {
- Assert.isTrue(inputElement == null || inputElement instanceof ITypeHierarchy);
- return new IType[] { fHierarchy.getType()};
- }
-
- private IMember[] getMembers(final IType type) {
- if (fTypeToMemberArray.containsKey(type))
- return (IMember[]) (fTypeToMemberArray.get(type));
- else
- return new IMember[0];
- }
-
- public Object getParent(final Object element) {
- if (element instanceof IType)
- return fHierarchy.getSuperclass((IType) element);
- if (element instanceof IMember)
- return ((IMember) element).getDeclaringType();
- Assert.isTrue(false, "Should not get here"); //$NON-NLS-1$
- return null;
- }
-
- private IType[] getSubclasses(final IType type) {
- if (type.equals(fDeclaringType))
- return new IType[0];
- return fHierarchy.getSubclasses(type);
- }
-
- private Object[] getSubclassesAndMembers(final IType type) {
- final Set set= new HashSet();
- set.addAll(Arrays.asList(getSubclasses(type)));
- set.addAll(Arrays.asList(getMembers(type)));
- return set.toArray();
- }
-
- public boolean hasChildren(final Object element) {
- if (!(element instanceof IType))
- return false;
- final IType type= (IType) element;
- return (fHierarchy.getAllSubtypes(type).length > 0) || fTypeToMemberArray.containsKey(type);
- }
-
- public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) {
- Assert.isTrue(newInput == null || newInput instanceof ITypeHierarchy);
- fHierarchy= (ITypeHierarchy) newInput;
- }
- }
-
- private static final String PAGE_NAME= "PullUpMethodPage"; //$NON-NLS-1$
-
- // IType -> IMember[]
- private static Map createTypeToMemberArrayMapping(final IMember[] members) {
- final Map typeToMemberSet= createTypeToMemberSetMapping(members);
-
- final Map typeToMemberArray= new HashMap();
- for (final Iterator iter= typeToMemberSet.keySet().iterator(); iter.hasNext();) {
- final IType type= (IType) iter.next();
- final Set memberSet= (Set) typeToMemberSet.get(type);
- final IMember[] memberArray= (IMember[]) memberSet.toArray(new IMember[memberSet.size()]);
- typeToMemberArray.put(type, memberArray);
- }
- return typeToMemberArray;
- }
-
- // IType -> Set of IMember
- private static Map createTypeToMemberSetMapping(final IMember[] members) {
- final Map typeToMemberSet= new HashMap();
- for (int i= 0; i < members.length; i++) {
- final IMember member= members[i];
- final IType type= member.getDeclaringType();
- if (!typeToMemberSet.containsKey(type))
- typeToMemberSet.put(type, new HashSet());
- ((Set) typeToMemberSet.get(type)).add(member);
- }
- return typeToMemberSet;
- }
-
- private boolean fChangedSettings= true;
-
- private Label fSelectionLabel;
-
- private SourceViewer fSourceViewer;
-
- private ContainerCheckedTreeViewer fTreeViewer;
-
- private Label fTypeHierarchyLabel;
-
- public PullUpMethodPage() {
- super(PAGE_NAME);
- setMessage(RefactoringMessages.PullUpInputPage_select_methods);
- }
-
- private void checkAllParents(final IType parent) {
- final ITypeHierarchy th= getTreeInput();
- final IType root= getTreeInput().getType();
- IType type= parent;
- while (!root.equals(type)) {
- fTreeViewer.setChecked(type, true);
- type= th.getSuperclass(type);
- }
- fTreeViewer.setChecked(root, true);
- }
-
- public void checkPulledUp() {
- uncheckAll();
- final HierarchyProcessor processor= getPullUpRefactoring().getPullUpProcessor();
- fTreeViewer.setCheckedElements(processor.getMembersToMove());
- final IType parent= processor.getDeclaringType();
- fTreeViewer.setChecked(parent, true);
- checkAllParents(parent);
- }
-
- private void createButtonComposite(final Composite superComposite) {
- final Composite buttonComposite= new Composite(superComposite, SWT.NONE);
- buttonComposite.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
- final GridLayout layout= new GridLayout(2, false);
- layout.marginWidth= 0;
- buttonComposite.setLayout(layout);
-
- fSelectionLabel= new Label(buttonComposite, SWT.LEFT | SWT.WRAP | SWT.HORIZONTAL);
- GridData data= new GridData(GridData.BEGINNING, GridData.BEGINNING, true, false);
- data.widthHint= convertWidthInCharsToPixels(32);
- fSelectionLabel.setLayoutData(data);
-
- final Button button= new Button(buttonComposite, SWT.PUSH);
- button.setText(RefactoringMessages.PullUpInputPage2_Select);
- button.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent e) {
- checkPulledUp();
- updateSelectionLabel();
- }
- });
- }
-
- public void createControl(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout());
-
- createTreeAndSourceViewer(composite);
- createButtonComposite(composite);
- setControl(composite);
-
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PULL_UP_WIZARD_PAGE);
- }
-
- private void createHierarchyTreeComposite(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- final GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- layout.horizontalSpacing= 1;
- layout.verticalSpacing= 1;
- composite.setLayout(layout);
-
- createTypeHierarchyLabel(composite);
- createTreeViewer(composite);
- }
-
- private void createSourceViewer(final Composite c) {
- final IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSourceViewer= new JavaSourceViewer(c, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION, store);
- fSourceViewer.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- fSourceViewer.setEditable(false);
- fSourceViewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
- fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- }
-
- private void createSourceViewerComposite(final Composite parent) {
- final Composite c= new Composite(parent, SWT.NONE);
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
- final GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- layout.horizontalSpacing= 1;
- layout.verticalSpacing= 1;
- c.setLayout(layout);
-
- createSourceViewerLabel(c);
- createSourceViewer(c);
- }
-
- private void createSourceViewerLabel(final Composite c) {
- final Label label= new Label(c, SWT.WRAP);
- final GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- label.setText(RefactoringMessages.PullUpInputPage2_Source);
- label.setLayoutData(gd);
- }
-
- private void createTreeAndSourceViewer(final Composite superComposite) {
- final SashForm composite= new SashForm(superComposite, SWT.HORIZONTAL);
- initializeDialogUnits(superComposite);
- final GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= convertHeightInCharsToPixels(20);
- gd.widthHint= convertWidthInCharsToPixels(10);
- composite.setLayoutData(gd);
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- layout.horizontalSpacing= 1;
- layout.verticalSpacing= 1;
- composite.setLayout(layout);
-
- createHierarchyTreeComposite(composite);
- createSourceViewerComposite(composite);
- composite.setWeights(new int[] { 50, 50});
- }
-
- private void createTreeViewer(final Composite composite) {
- final Tree tree= new Tree(composite, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
- tree.setLayoutData(new GridData(GridData.FILL_BOTH));
- fTreeViewer= new ContainerCheckedTreeViewer(tree);
- fTreeViewer.setLabelProvider(new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_SMALL_ICONS));
- fTreeViewer.setUseHashlookup(true);
- fTreeViewer.setComparator(new JavaScriptElementComparator());
- fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- treeViewerSelectionChanged(event);
- }
- });
- fTreeViewer.addCheckStateListener(new ICheckStateListener() {
-
- public void checkStateChanged(final CheckStateChangedEvent event) {
- updateSelectionLabel();
- }
- });
- }
-
- private void createTypeHierarchyLabel(final Composite composite) {
- fTypeHierarchyLabel= new Label(composite, SWT.WRAP);
- final GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- fTypeHierarchyLabel.setLayoutData(gd);
- }
-
- public void fireSettingsChanged() {
- fChangedSettings= true;
- }
-
- private IFunction[] getCheckedMethods() {
- final Object[] checked= fTreeViewer.getCheckedElements();
- final List members= new ArrayList(checked.length);
- for (int i= 0; i < checked.length; i++) {
- if (checked[i] instanceof IFunction)
- members.add(checked[i]);
- }
- return (IFunction[]) members.toArray(new IFunction[members.size()]);
- }
-
- private ISourceReference getFirstSelectedSourceReference(final SelectionChangedEvent event) {
- final ISelection s= event.getSelection();
- if (!(s instanceof IStructuredSelection))
- return null;
- final IStructuredSelection ss= (IStructuredSelection) s;
- if (ss.size() != 1)
- return null;
- final Object first= ss.getFirstElement();
- if (!(first instanceof ISourceReference))
- return null;
- return (ISourceReference) first;
- }
-
- public IWizardPage getNextPage() {
- initializeRefactoring();
- return super.getNextPage();
- }
-
- private PullUpRefactoring getPullUpRefactoring() {
- return (PullUpRefactoring) getRefactoring();
- }
-
- private String getSupertypeSignature() {
- return JavaElementUtil.createSignature(getPullUpRefactoring().getPullUpProcessor().getDestinationType());
- }
-
- private ITypeHierarchy getTreeInput() {
- return (ITypeHierarchy) fTreeViewer.getInput();
- }
-
- private void initializeRefactoring() {
- getPullUpRefactoring().getPullUpProcessor().setDeletedMethods(getCheckedMethods());
- }
-
- private void initializeTreeViewer() {
- try {
- getContainer().run(false, false, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor pm) {
- try {
- initializeTreeViewer(pm);
- } finally {
- pm.done();
- }
- }
- });
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.PullUpInputPage_pull_Up, RefactoringMessages.PullUpInputPage_exception);
- } catch (InterruptedException e) {
- Assert.isTrue(false);
- }
- }
-
- private void initializeTreeViewer(final IProgressMonitor pm) {
- try {
- pm.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 2);
- final PullUpRefactoringProcessor processor= getPullUpRefactoring().getPullUpProcessor();
- final IMember[] matchingMethods= processor.getMatchingElements(new SubProgressMonitor(pm, 1), false);
- final ITypeHierarchy hierarchy= processor.getDestinationTypeHierarchy(new SubProgressMonitor(pm, 1));
- removeAllTreeViewFilters();
- fTreeViewer.addFilter(new PullUpFilter(hierarchy, matchingMethods));
- fTreeViewer.setContentProvider(new PullUpHierarchyContentProvider(processor.getDeclaringType(), matchingMethods));
- fTreeViewer.setInput(hierarchy);
- precheckElements(fTreeViewer);
- fTreeViewer.expandAll();
- updateSelectionLabel();
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.PullUpInputPage_pull_up1, RefactoringMessages.PullUpInputPage_exception);
- fTreeViewer.setInput(null);
- } finally {
- pm.done();
- }
- }
-
- protected boolean performFinish() {
- initializeRefactoring();
- return super.performFinish();
- }
-
- private void precheckElements(final ContainerCheckedTreeViewer treeViewer) {
- final IMember[] members= getPullUpRefactoring().getPullUpProcessor().getMembersToMove();
- for (int i= 0; i < members.length; i++) {
- treeViewer.setChecked(members[i], true);
- }
- }
-
- private void removeAllTreeViewFilters() {
- final ViewerFilter[] filters= fTreeViewer.getFilters();
- for (int i= 0; i < filters.length; i++) {
- fTreeViewer.removeFilter(filters[i]);
- }
- }
-
- private void setHierarchyLabelText() {
- final String message= Messages.format(RefactoringMessages.PullUpInputPage_subtypes, getSupertypeSignature());
- fTypeHierarchyLabel.setText(message);
- }
-
- private void setSourceViewerContents(String contents) {
- if (contents != null) {
- final IJavaScriptProject project= getPullUpRefactoring().getPullUpProcessor().getDestinationType().getJavaScriptProject();
- final String[] lines= Strings.convertIntoLines(contents);
- if (lines.length > 0) {
- final int indent= Strings.computeIndentUnits(lines[lines.length - 1], project);
- contents= Strings.changeIndent(contents, indent, project, "", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- final IDocument document= (contents == null) ? new Document() : new Document(contents);
- JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document);
- fSourceViewer.setDocument(document);
- }
-
- public void setVisible(final boolean visible) {
- if (visible && fChangedSettings) {
- fChangedSettings= false;
- initializeTreeViewer();
- setHierarchyLabelText();
- }
- super.setVisible(visible);
- }
-
- private void showInSourceViewer(final ISourceReference selected) throws JavaScriptModelException {
- if (selected == null)
- setSourceViewerContents(null);
- else
- setSourceViewerContents(selected.getSource());
- }
-
- private void treeViewerSelectionChanged(final SelectionChangedEvent event) {
- try {
- showInSourceViewer(getFirstSelectedSourceReference(event));
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.PullUpInputPage_pull_up1, RefactoringMessages.PullUpInputPage_see_log);
- }
- }
-
- private void uncheckAll() {
- final IType root= getTreeInput().getType();
- fTreeViewer.setChecked(root, false);
- }
-
- private void updateSelectionLabel() {
- fSelectionLabel.setText(Messages.format(RefactoringMessages.PullUpInputPage_hierarchyLabal, String.valueOf(getCheckedMethods().length)));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpWizard.java
deleted file mode 100644
index ac13d488..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PullUpWizard.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PullUpRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Refactoring wizard for the pull up refactoring.
- */
-public final class PullUpWizard extends RefactoringWizard {
-
- /** The page name */
- private static final String PAGE_NAME= "PullUpMemberPage"; //$NON-NLS-1$
-
- /**
- * Creates a new pull up wizard.
- *
- * @param refactoring
- * the pull up refactoring
- */
- public PullUpWizard(final PullUpRefactoring refactoring) {
- super(refactoring, WIZARD_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.PullUpWizard_defaultPageTitle);
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR_PULL_UP);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void addUserInputPages() {
- final PullUpMethodPage page= new PullUpMethodPage();
- addPage(new PullUpMemberPage(PullUpWizard.PAGE_NAME, page));
- addPage(page);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PushDownWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PushDownWizard.java
deleted file mode 100644
index 48d43c17..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/PushDownWizard.java
+++ /dev/null
@@ -1,599 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor.MemberActionInfo;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public final class PushDownWizard extends RefactoringWizard {
-
- private static class PushDownInputPage extends UserInputWizardPage {
-
- private static class MemberActionInfoLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- private static String getActionLabel(final int action) {
- switch (action) {
- case MemberActionInfo.NO_ACTION:
- return ""; //$NON-NLS-1$
- case MemberActionInfo.PUSH_ABSTRACT_ACTION:
- return RefactoringMessages.PushDownInputPage_leave_abstract;
- case MemberActionInfo.PUSH_DOWN_ACTION:
- return RefactoringMessages.PushDownInputPage_push_down;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private static String[] getAvailableActionLabels(final MemberActionInfo info) {
- final int[] actions= info.getAvailableActions();
- final String[] result= new String[actions.length];
- for (int index= 0; index < actions.length; index++) {
- result[index]= getActionLabel(actions[index]);
- }
- return result;
- }
-
- private final ILabelProvider fLabelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_SMALL_ICONS);
-
- public void dispose() {
- fLabelProvider.dispose();
- super.dispose();
- }
-
- public Image getColumnImage(final Object element, final int index) {
- final MemberActionInfo info= (MemberActionInfo) element;
- switch (index) {
- case MEMBER_COLUMN:
- return fLabelProvider.getImage(info.getMember());
- case ACTION_COLUMN:
- return null;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- public String getColumnText(final Object element, final int index) {
- final MemberActionInfo info= (MemberActionInfo) element;
- switch (index) {
- case MEMBER_COLUMN:
- return fLabelProvider.getText(info.getMember());
- case ACTION_COLUMN:
- return getActionLabel(info.getAction());
- default:
- Assert.isTrue(false);
- return null;
- }
- }
- }
-
- private class PushDownCellModifier implements ICellModifier {
-
- public boolean canModify(final Object element, final String property) {
- if (!ACTION_PROPERTY.equals(property))
- return false;
- return ((MemberActionInfo) element).isEditable();
- }
-
- public Object getValue(final Object element, final String property) {
- if (!ACTION_PROPERTY.equals(property))
- return null;
-
- final MemberActionInfo info= (MemberActionInfo) element;
- return new Integer(info.getAction());
- }
-
- public void modify(final Object element, final String property, final Object value) {
- if (!ACTION_PROPERTY.equals(property))
- return;
-
- final int action= ((Integer) value).intValue();
- MemberActionInfo info;
- if (element instanceof Item) {
- info= (MemberActionInfo) ((Item) element).getData();
- } else
- info= (MemberActionInfo) element;
- if (!canModify(info, property))
- return;
- info.setAction(action);
- PushDownInputPage.this.updateWizardPage(null, true);
- }
- }
-
- private static final int ACTION_COLUMN= 1;
-
- private final static String ACTION_PROPERTY= "action"; //$NON-NLS-1$
-
- private static final int MEMBER_COLUMN= 0;
-
- private final static String MEMBER_PROPERTY= "member"; //$NON-NLS-1$
-
- private static final String PAGE_NAME= "PushDownInputPage"; //$NON-NLS-1$
-
- private static final int ROW_COUNT= 10;
-
- private static int countEditableInfos(final MemberActionInfo[] infos) {
- int result= 0;
- for (int index= 0; index < infos.length; index++) {
- if (infos[index].isEditable())
- result++;
- }
- return result;
- }
-
- private static void setInfoAction(final MemberActionInfo[] infos, final int action) {
- for (int index= 0; index < infos.length; index++) {
- infos[index].setAction(action);
- }
- }
-
- private Button fDeselectAllButton;
-
- private Button fEditButton;
-
- private Button fSelectAllButton;
-
- private Label fStatusLine;
-
- private PullPushCheckboxTableViewer fTableViewer;
-
- public PushDownInputPage() {
- super(PAGE_NAME);
- }
-
- private boolean areAllElementsMarkedAsNoAction() {
- return countInfosForAction(MemberActionInfo.NO_ACTION) == ((MemberActionInfo[]) fTableViewer.getInput()).length;
- }
-
- private boolean areAllElementsMarkedAsPushDownAction() {
- return countInfosForAction(MemberActionInfo.PUSH_DOWN_ACTION) == ((MemberActionInfo[]) fTableViewer.getInput()).length;
- }
-
- private void checkPageCompletionStatus(final boolean displayErrorMessage) {
- if (areAllElementsMarkedAsNoAction()) {
- if (displayErrorMessage)
- setErrorMessage(RefactoringMessages.PushDownInputPage_Select_members_to_push_down);
- setPageComplete(false);
- } else {
- setErrorMessage(null);
- setPageComplete(true);
- }
- }
-
- private int countInfosForAction(final int action) {
- final MemberActionInfo[] infos= (MemberActionInfo[]) fTableViewer.getInput();
- int count= 0;
- for (int index= 0; index < infos.length; index++) {
- final MemberActionInfo info= infos[index];
- if (info.getAction() == action)
- count++;
- }
- return count;
- }
-
- private void createButtonComposite(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- final GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- fSelectAllButton= new Button(composite, SWT.PUSH);
- fSelectAllButton.setText(RefactoringMessages.PullUpWizard_select_all_label);
- fSelectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fSelectAllButton.setEnabled(true);
- SWTUtil.setButtonDimensionHint(fSelectAllButton);
- fSelectAllButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- final IMember[] members= getMembers();
- setActionForMembers(members, MemberActionInfo.PUSH_DOWN_ACTION);
- updateWizardPage(null, true);
- }
- });
-
- fDeselectAllButton= new Button(composite, SWT.PUSH);
- fDeselectAllButton.setText(RefactoringMessages.PullUpWizard_deselect_all_label);
- fDeselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fDeselectAllButton.setEnabled(false);
- SWTUtil.setButtonDimensionHint(fDeselectAllButton);
- fDeselectAllButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- final IMember[] members= getMembers();
- setActionForMembers(members, MemberActionInfo.NO_ACTION);
- updateWizardPage(null, true);
- }
- });
-
- fEditButton= new Button(composite, SWT.PUSH);
- fEditButton.setText(RefactoringMessages.PushDownInputPage_Edit);
- final GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.verticalIndent= new PixelConverter(parent).convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- fEditButton.setLayoutData(data);
- fEditButton.setEnabled(false);
- SWTUtil.setButtonDimensionHint(fEditButton);
- fEditButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- PushDownInputPage.this.editSelectedMembers();
- }
- });
-
- final Button addButton= new Button(composite, SWT.PUSH);
- addButton.setText(RefactoringMessages.PushDownInputPage_Add_Required);
- addButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(addButton);
- addButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(final SelectionEvent event) {
- PushDownInputPage.this.markAdditionalRequiredMembersAsMembersToPushDown();
- }
- });
- }
-
- public void createControl(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout());
-
- createMemberTableLabel(composite);
- createMemberTableComposite(composite);
- createStatusLine(composite);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.PUSH_DOWN_WIZARD_PAGE);
- }
-
- private void createMemberTable(final Composite parent) {
- final TableLayoutComposite layouter= new TableLayoutComposite(parent, SWT.NONE);
- layouter.addColumnData(new ColumnWeightData(60, true));
- layouter.addColumnData(new ColumnWeightData(40, true));
-
- final Table table= new Table(layouter, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- final GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= SWTUtil.getTableHeightHint(table, ROW_COUNT);
- data.widthHint= convertWidthInCharsToPixels(30);
- layouter.setLayoutData(data);
-
- final TableLayout layout= new TableLayout();
- table.setLayout(layout);
-
- final TableColumn first= new TableColumn(table, SWT.NONE);
- first.setText(RefactoringMessages.PushDownInputPage_Member);
-
- final TableColumn second= new TableColumn(table, SWT.NONE);
- second.setText(RefactoringMessages.PushDownInputPage_Action);
-
- fTableViewer= new PullPushCheckboxTableViewer(table);
- fTableViewer.setUseHashlookup(true);
- fTableViewer.setContentProvider(new ArrayContentProvider());
- fTableViewer.setLabelProvider(new MemberActionInfoLabelProvider());
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- PushDownInputPage.this.updateButtonEnablementState((IStructuredSelection) event.getSelection());
- }
- });
- fTableViewer.addCheckStateListener(new ICheckStateListener() {
-
- public void checkStateChanged(final CheckStateChangedEvent event) {
- final boolean checked= event.getChecked();
- final MemberActionInfo info= (MemberActionInfo) event.getElement();
- if (checked)
- info.setAction(MemberActionInfo.PUSH_DOWN_ACTION);
- else
- info.setAction(MemberActionInfo.NO_ACTION);
- updateWizardPage(null, true);
- }
- });
- fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(final DoubleClickEvent event) {
- PushDownInputPage.this.editSelectedMembers();
- }
- });
-
- fTableViewer.setInput(getPushDownRefactoring().getPushDownProcessor().getMemberActionInfos());
- updateWizardPage(null, false);
- setupCellEditors(table);
- }
-
- private void createMemberTableComposite(final Composite parent) {
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- final GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- createMemberTable(composite);
- createButtonComposite(composite);
- }
-
- private void createMemberTableLabel(final Composite parent) {
- final Label label= new Label(parent, SWT.NONE);
- label.setText(RefactoringMessages.PushDownInputPage_Specify_actions);
- label.setLayoutData(new GridData());
- }
-
- private void createStatusLine(final Composite composite) {
- fStatusLine= new Label(composite, SWT.NONE);
- final GridData data= new GridData();
- data.horizontalSpan= 2;
- updateStatusLine();
- fStatusLine.setLayoutData(data);
- }
-
- // String -> Integer
- private Map createStringMappingForSelectedElements() {
- final Map result= new HashMap();
- int action= MemberActionInfo.PUSH_DOWN_ACTION;
- result.put(MemberActionInfoLabelProvider.getActionLabel(action), new Integer(action));
- int action1= MemberActionInfo.PUSH_ABSTRACT_ACTION;
- result.put(MemberActionInfoLabelProvider.getActionLabel(action1), new Integer(action1));
- return result;
- }
-
- private void editSelectedMembers() {
- if (!fEditButton.isEnabled())
- return;
- final ISelection preserved= fTableViewer.getSelection();
- try {
- final Map stringMapping= createStringMappingForSelectedElements();
- final String[] keys= (String[]) stringMapping.keySet().toArray(new String[stringMapping.keySet().size()]);
- Arrays.sort(keys);
- final int initialSelectionIndex= getInitialSelectionIndexForEditDialog(stringMapping, keys);
-
- final ComboSelectionDialog dialog= new ComboSelectionDialog(getShell(), RefactoringMessages.PushDownInputPage_Edit_members, RefactoringMessages.PushDownInputPage_Mark_selected_members, keys, initialSelectionIndex);
- dialog.setBlockOnOpen(true);
- if (dialog.open() == Window.CANCEL)
- return;
- final int action= ((Integer) stringMapping.get(dialog.getSelectedString())).intValue();
- setInfoAction(getSelectedMemberActionInfos(), action);
- } finally {
- updateWizardPage(preserved, true);
- }
- }
-
- private boolean enableEditButton(final IStructuredSelection selection) {
- if (selection.isEmpty() || selection.size() == 0)
- return false;
- return selection.size() == countEditableInfos(getSelectedMemberActionInfos());
- }
-
- private MemberActionInfo[] getActiveInfos() {
- final MemberActionInfo[] infos= getPushDownRefactoring().getPushDownProcessor().getMemberActionInfos();
- final List result= new ArrayList(infos.length);
- for (int index= 0; index < infos.length; index++) {
- final MemberActionInfo info= infos[index];
- if (info.isActive())
- result.add(info);
- }
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- private int getCommonActionCodeForSelectedInfos() {
- final MemberActionInfo[] infos= getSelectedMemberActionInfos();
- if (infos.length == 0)
- return -1;
-
- final int code= infos[0].getAction();
- for (int index= 0; index < infos.length; index++) {
- if (code != infos[index].getAction())
- return -1;
- }
- return code;
- }
-
- private int getInitialSelectionIndexForEditDialog(final Map mapping, final String[] keys) {
- final int commonActionCode= getCommonActionCodeForSelectedInfos();
- if (commonActionCode == -1)
- return 0;
- for (final Iterator iterator= mapping.keySet().iterator(); iterator.hasNext();) {
- final String key= (String) iterator.next();
- final int action= ((Integer) mapping.get(key)).intValue();
- if (commonActionCode == action) {
- for (int index= 0; index < keys.length; index++) {
- if (key.equals(keys[index]))
- return index;
- }
- Assert.isTrue(false);// there's no way
- }
- }
- return 0;
- }
-
- private IMember[] getMembers() {
- final MemberActionInfo[] infos= (MemberActionInfo[]) fTableViewer.getInput();
- final List result= new ArrayList(infos.length);
- for (int index= 0; index < infos.length; index++) {
- result.add(infos[index].getMember());
- }
- return (IMember[]) result.toArray(new IMember[result.size()]);
- }
-
- private PushDownRefactoring getPushDownRefactoring() {
- return (PushDownRefactoring) getRefactoring();
- }
-
- private MemberActionInfo[] getSelectedMemberActionInfos() {
- Assert.isTrue(fTableViewer.getSelection() instanceof IStructuredSelection);
- final List result= ((IStructuredSelection) fTableViewer.getSelection()).toList();
- return (MemberActionInfo[]) result.toArray(new MemberActionInfo[result.size()]);
- }
-
- public void markAdditionalRequiredMembersAsMembersToPushDown() {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, new IRunnableWithProgress() {
-
- public void run(final IProgressMonitor pm) throws InvocationTargetException {
- try {
- getPushDownRefactoring().getPushDownProcessor().computeAdditionalRequiredMembersToPushDown(pm);
- updateWizardPage(null, true);
- } catch (final JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- } finally {
- pm.done();
- }
- }
- });
- } catch (final InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.PushDownInputPage_Push_Down, RefactoringMessages.PushDownInputPage_Internal_Error);
- } catch (final InterruptedException e) {
- Assert.isTrue(false);// not cancelable
- }
- }
-
- private void setActionForMembers(final IMember[] members, final int action) {
- final MemberActionInfo[] infos= (MemberActionInfo[]) fTableViewer.getInput();
- for (int offset= 0; offset < members.length; offset++) {
- for (int index= 0; index < infos.length; index++) {
- if (infos[index].getMember().equals(members[offset]))
- infos[index].setAction(action);
- }
- }
- }
-
- private void setupCellEditors(final Table table) {
- final ComboBoxCellEditor comboBoxCellEditor= new ComboBoxCellEditor();
- comboBoxCellEditor.setStyle(SWT.READ_ONLY);
- fTableViewer.setCellEditors(new CellEditor[] { null, comboBoxCellEditor});
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(final SelectionChangedEvent event) {
- if (comboBoxCellEditor.getControl() == null & !table.isDisposed())
- comboBoxCellEditor.create(table);
- Assert.isTrue(event.getSelection() instanceof IStructuredSelection);
- final IStructuredSelection ss= (IStructuredSelection) event.getSelection();
- if (ss.size() != 1)
- return;
- final MemberActionInfo mac= (MemberActionInfo) ss.getFirstElement();
- comboBoxCellEditor.setItems(MemberActionInfoLabelProvider.getAvailableActionLabels(mac));
- comboBoxCellEditor.setValue(new Integer(mac.getAction()));
- }
- });
-
- final ICellModifier cellModifier= new PushDownCellModifier();
- fTableViewer.setCellModifier(cellModifier);
- fTableViewer.setColumnProperties(new String[] { MEMBER_PROPERTY, ACTION_PROPERTY});
- }
-
- public void setVisible(final boolean visible) {
- super.setVisible(visible);
- if (visible) {
- fTableViewer.setSelection(new StructuredSelection(getActiveInfos()), true);
- fTableViewer.getControl().setFocus();
- }
- }
-
- private void updateButtonEnablementState(final IStructuredSelection tableSelection) {
- if (tableSelection == null || fEditButton == null)
- return;
- fEditButton.setEnabled(enableEditButton(tableSelection));
- if (fSelectAllButton != null)
- fSelectAllButton.setEnabled(!areAllElementsMarkedAsPushDownAction());
- if (fDeselectAllButton != null)
- fDeselectAllButton.setEnabled(!areAllElementsMarkedAsNoAction());
- }
-
- private void updateStatusLine() {
- if (fStatusLine == null)
- return;
- final int selected= fTableViewer.getCheckedElements().length;
- final String[] keys= { String.valueOf(selected)};
- final String msg= Messages.format(RefactoringMessages.PushDownInputPage_status_line, keys);
- fStatusLine.setText(msg);
- }
-
- private void updateWizardPage(final ISelection preserved, final boolean displayErrorMessage) {
- fTableViewer.refresh();
- if (preserved != null) {
- fTableViewer.getControl().setFocus();
- fTableViewer.setSelection(preserved);
- }
- checkPageCompletionStatus(displayErrorMessage);
- updateButtonEnablementState(((IStructuredSelection) fTableViewer.getSelection()));
- updateStatusLine();
- }
- }
-
- public PushDownWizard(final PushDownRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.PushDownWizard_defaultPageTitle);
- }
-
- protected void addUserInputPages() {
- addPage(new PushDownInputPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/QualifiedNameComponent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/QualifiedNameComponent.java
deleted file mode 100644
index f0d9a161..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/QualifiedNameComponent.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameRefactoringWizard;
-
-public class QualifiedNameComponent extends Composite {
-
- private Text fPatterns;
-
- public QualifiedNameComponent(Composite parent, int style, final IQualifiedNameUpdating refactoring, IDialogSettings settings) {
- super(parent, style);
- GridLayout layout= new GridLayout();
- layout.marginWidth=0; layout.marginHeight= 0;
- layout.numColumns= 2;
- setLayout(layout);
- Label label= new Label(this, SWT.NONE);
- label.setText(RefactoringMessages.QualifiedNameComponent_patterns_label);
- fPatterns= new Text(this, SWT.BORDER);
- fPatterns.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- label= new Label(this, SWT.NONE);
- label.setText(RefactoringMessages.QualifiedNameComponent_patterns_description);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan=2;
- label.setLayoutData(gd);
- String text= refactoring.getFilePatterns();
- if (text == null)
- text= settings.get(RenameRefactoringWizard.QUALIFIED_NAMES_PATTERNS);
- if (text != null) {
- fPatterns.setText(text);
- refactoring.setFilePatterns(text);
- }
- fPatterns.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- refactoring.setFilePatterns(fPatterns.getText());
- }
- });
- }
-
- public void setEnabled(boolean enabled) {
- super.setEnabled(enabled);
- Control[] children= getChildren();
- for (int i= 0; i < children.length; i++) {
- children[i].setEnabled(enabled);
- }
- }
-
- public void savePatterns(IDialogSettings settings) {
- settings.put(RenameRefactoringWizard.QUALIFIED_NAMES_PATTERNS, fPatterns.getText());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringAdapterFactory.java
deleted file mode 100644
index 3a715b2e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringAdapterFactory.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
- package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.IAdapterFactory;
-import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
-import org.eclipse.ltk.ui.refactoring.TextEditChangeNode;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MultiStateCompilationUnitChange;
-
-public class RefactoringAdapterFactory implements IAdapterFactory {
-
- private static final Class[] ADAPTER_LIST= new Class[] {
- TextEditChangeNode.class
- };
-
- public Class[] getAdapterList() {
- return ADAPTER_LIST;
- }
-
- public Object getAdapter(Object object, Class key) {
- if (!TextEditChangeNode.class.equals(key))
- return null;
- if (!(object instanceof CompilationUnitChange) && !(object instanceof MultiStateCompilationUnitChange))
- return null;
- return new CompilationUnitChangeNode((TextEditBasedChange)object);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringExecutionHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringExecutionHelper.java
deleted file mode 100644
index 6f531f13..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringExecutionHelper.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.IJobManager;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IThreadListener;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.PerformChangeOperation;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringUI;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-
-/**
- * A helper class to execute a refactoring. The class takes care of pushing the
- * undo change onto the undo stack and folding editor edits into one editor
- * undo object.
- */
-public class RefactoringExecutionHelper {
-
- private final Refactoring fRefactoring;
- private final Shell fParent;
- private final IRunnableContext fExecContext;
- private final int fStopSeverity;
- private final int fSaveMode;
-
- private class Operation implements IWorkspaceRunnable {
- public Change fChange;
- public PerformChangeOperation fPerformChangeOperation;
- private final boolean fForked;
-
- public Operation(boolean forked) {
- fForked= forked;
- }
-
- public void run(IProgressMonitor pm) throws CoreException {
- try {
- pm.beginTask("", fForked ? 7 : 11); //$NON-NLS-1$
- pm.subTask(""); //$NON-NLS-1$
-
- final RefactoringStatus status= fRefactoring.checkAllConditions(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
- if (status.getSeverity() >= fStopSeverity) {
- final boolean[] canceled= { false };
- if (fForked) {
- fParent.getDisplay().syncExec(new Runnable() {
- public void run() {
- canceled[0]= showStatusDialog(status);
- }
- });
- } else {
- canceled[0]= showStatusDialog(status);
- }
- if (canceled[0]) {
- throw new OperationCanceledException();
- }
- }
-
- fChange= fRefactoring.createChange(new SubProgressMonitor(pm, 2, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
- fChange.initializeValidationData(new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
-
- fPerformChangeOperation= RefactoringUI.createUIAwareChangeOperation(fChange);
- fPerformChangeOperation.setUndoManager(RefactoringCore.getUndoManager(), fRefactoring.getName());
- if (fRefactoring instanceof IScheduledRefactoring)
- fPerformChangeOperation.setSchedulingRule(((IScheduledRefactoring)fRefactoring).getSchedulingRule());
-
- if (! fForked)
- fPerformChangeOperation.run(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
- } finally {
- pm.done();
- }
- }
-
- /**
- * @param status the status to show
- * @return <code>true</code> iff the operation should be cancelled
- */
- private boolean showStatusDialog(RefactoringStatus status) {
- Dialog dialog= RefactoringUI.createRefactoringStatusDialog(status, fParent, fRefactoring.getName(), false);
- return dialog.open() == IDialogConstants.CANCEL_ID;
- }
- }
-
- /**
- * @param refactoring
- * @param stopSeverity a refactoring status constant from {@link RefactoringStatus}
- * @param saveMode a save mode from {@link RefactoringSaveHelper}
- * @param parent
- * @param context
- */
- public RefactoringExecutionHelper(Refactoring refactoring, int stopSeverity, int saveMode, Shell parent, IRunnableContext context) {
- super();
- Assert.isNotNull(refactoring);
- Assert.isNotNull(parent);
- Assert.isNotNull(context);
- fRefactoring= refactoring;
- fStopSeverity= stopSeverity;
- fParent= parent;
- fExecContext= context;
- fSaveMode= saveMode;
- }
-
- /**
- * Must be called in the UI thread.
- * @param fork if set, the operation will be forked
- * @param cancelable if set, the operation will be cancellable
- * @throws InterruptedException thrown when the operation is cancelled
- * @throws InvocationTargetException thrown when the operation failed to execute
- */
- public void perform(boolean fork, boolean cancelable) throws InterruptedException, InvocationTargetException {
- Assert.isTrue(Display.getCurrent() != null);
- final IJobManager manager= Job.getJobManager();
- final ISchedulingRule rule;
- if (fRefactoring instanceof IScheduledRefactoring) {
- rule= ((IScheduledRefactoring)fRefactoring).getSchedulingRule();
- } else {
- rule= ResourcesPlugin.getWorkspace().getRoot();
- }
- class OperationRunner extends WorkbenchRunnableAdapter implements IThreadListener {
- public OperationRunner(IWorkspaceRunnable runnable, ISchedulingRule schedulingRule) {
- super(runnable, schedulingRule);
- }
- public void threadChange(Thread thread) {
- manager.transferRule(getSchedulingRule(), thread);
- }
- }
- try {
- try {
- Runnable r= new Runnable() {
- public void run() {
- manager.beginRule(rule, null);
- }
- };
- BusyIndicator.showWhile(fParent.getDisplay(), r);
- } catch (OperationCanceledException e) {
- throw new InterruptedException(e.getMessage());
- }
-
- RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(fSaveMode);
- if (!saveHelper.saveEditors(fParent))
- throw new InterruptedException();
- final Operation op= new Operation(fork);
- fRefactoring.setValidationContext(fParent);
- try{
- fExecContext.run(fork, cancelable, new OperationRunner(op, rule));
- if (fork && op.fPerformChangeOperation != null)
- fExecContext.run(false, false, new OperationRunner(op.fPerformChangeOperation, rule));
-
- if (op.fPerformChangeOperation != null) {
- RefactoringStatus validationStatus= op.fPerformChangeOperation.getValidationStatus();
- if (validationStatus != null && validationStatus.hasFatalError()) {
- MessageDialog.openError(fParent, fRefactoring.getName(),
- Messages.format(
- RefactoringMessages.RefactoringExecutionHelper_cannot_execute,
- validationStatus.getMessageMatchingSeverity(RefactoringStatus.FATAL)));
- return;
- }
- }
- } catch (InvocationTargetException e) {
- PerformChangeOperation pco= op.fPerformChangeOperation;
- if (pco != null && pco.changeExecutionFailed()) {
- ChangeExceptionHandler handler= new ChangeExceptionHandler(fParent, fRefactoring);
- Throwable inner= e.getTargetException();
- if (inner instanceof RuntimeException) {
- handler.handle(pco.getChange(), (RuntimeException)inner);
- } else if (inner instanceof CoreException) {
- handler.handle(pco.getChange(), (CoreException)inner);
- } else {
- throw e;
- }
- } else {
- throw e;
- }
- } catch (OperationCanceledException e) {
- throw new InterruptedException(e.getMessage());
- } finally {
- saveHelper.triggerBuild();
- }
- } finally {
- manager.endRule(rule);
- fRefactoring.setValidationContext(null);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringMessages.java
deleted file mode 100644
index b4a8cbc3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringMessages.java
+++ /dev/null
@@ -1,968 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class RefactoringMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.refactoring.refactoringui";//$NON-NLS-1$
-
- public static String ChangeExceptionHandler_abort_button;
-
- public static String ChangeExceptionHandler_dialog_message;
-
- public static String ChangeExceptionHandler_dialog_title;
-
- public static String ChangeExceptionHandler_message;
-
- public static String ChangeExceptionHandler_status_without_detail;
-
- public static String ChangeExceptionHandler_undo_button;
-
- public static String ChangeExceptionHandler_undo_dialog_message;
-
- public static String ChangeExceptionHandler_undo_dialog_title;
-
- public static String ChangeExceptionsControl_buttons_add;
-
- public static String ChangeExceptionsControl_buttons_remove;
-
- public static String ChangeExceptionsControl_choose_message;
-
- public static String ChangeExceptionsControl_choose_title;
-
- public static String ChangeExceptionsControl_not_exception;
-
- public static String ChangeParametersControl_buttons_add;
-
- public static String ChangeParametersControl_buttons_edit;
-
- public static String ChangeParametersControl_buttons_move_down;
-
- public static String ChangeParametersControl_buttons_move_up;
-
- public static String ChangeParametersControl_buttons_remove;
-
- public static String ChangeParametersControl_default;
-
- public static String ChangeParametersControl_new;
-
- public static String ChangeParametersControl_new_parameter_default_name;
-
- public static String ChangeParametersControl_table_defaultValue;
-
- public static String ChangeParametersControl_table_name;
-
- public static String ChangeParametersControl_table_type;
-
- public static String ChangeParametersControl_type;
-
- public static String ChangeSignatureInputPage_access_modifier;
-
- public static String ChangeSignatureInputPage_change;
-
- public static String ChangeSignatureInputPage_Change_Signature;
-
- public static String ChangeSignatureInputPage_default;
-
- public static String ChangeSignatureInputPage_exception;
-
- public static String ChangeSignatureInputPage_exceptions;
-
- public static String ChangeSignatureInputPage_Internal_Error;
-
- public static String ChangeSignatureInputPage_method_name;
-
- public static String ChangeSignatureInputPage_method_Signature_Preview;
-
- public static String ChangeSignatureInputPage_parameters;
-
- public static String ChangeSignatureInputPage_return_type;
-
- public static String ChangeSignatureInputPage_unchanged;
-
- public static String ChangeSignatureRefactoring_modify_Parameters;
-
- public static String ChangeTypeAction_description;
-
- public static String ChangeTypeAction_dialog_title;
-
- public static String ChangeTypeAction_exception;
-
- public static String ChangeTypeAction_label;
-
- public static String ChangeTypeAction_tooltipText;
-
- public static String ChangeTypeInputPage_Select_Type;
-
- public static String ChangeTypeWizard_analyzing;
-
- public static String ChangeTypeWizard_computationInterrupted;
-
- public static String ChangeTypeWizard_declCannotBeChanged;
-
- public static String ChangeTypeWizard_grayed_types;
-
- public static String ChangeTypeWizard_internalError;
-
- public static String ChangeTypeWizard_pleaseChooseType;
-
- public static String ChangeTypeWizard_title;
-
- public static String ChangeTypeWizard_with_itself;
-
- public static String ConvertAnonymousToNestedAction_Convert_Anonymous;
-
- public static String ConvertAnonymousToNestedAction_dialog_title;
-
- public static String ConvertAnonymousToNestedAction_wizard_title;
-
- public static String ConvertAnonymousToNestedInputPage_class_name;
-
- public static String ConvertAnonymousToNestedInputPage_declare_final;
-
- public static String ConvertAnonymousToNestedInputPage_declare_static;
-
- public static String ConvertAnonymousToNestedInputPage_description;
-
- public static String ConvertLocalToField_label;
-
- public static String ConvertLocalToField_title;
-
- public static String ConvertNestedToTopAction_Convert;
-
- public static String ConvertNestedToTopAction_not_possible;
-
- public static String ConvertNestedToTopAction_Refactoring;
-
- public static String ConvertNestedToTopAction_To_activate;
-
- public static String DelegateCreator_deprecate_delegates;
-
- public static String DeleteWizard_1;
-
- public static String DeleteWizard_10;
-
- public static String DeleteWizard_11;
-
- public static String DeleteWizard_12;
-
- public static String DeleteWizard_2;
-
- public static String DeleteWizard_3;
-
- public static String DeleteWizard_4;
-
- public static String DeleteWizard_5;
-
- public static String DeleteWizard_6;
-
- public static String DeleteWizard_7;
-
- public static String DeleteWizard_8;
-
- public static String DeleteWizard_9;
-
- public static String DeleteWizard_also_delete_sub_packages;
-
- public static String ExtractConstantAction_extract_constant;
-
- public static String ExtractConstantAction_label;
-
- public static String ExtractConstantInputPage_access_modifiers;
-
- public static String ExtractConstantInputPage_constant_name;
-
- public static String ExtractConstantInputPage_enter_name;
-
- public static String ExtractConstantInputPage_exception;
-
- public static String ExtractConstantInputPage_Internal_Error;
-
- public static String ExtractConstantInputPage_qualify_constant_references_with_class_name;
-
- public static String ExtractConstantInputPage_replace_all;
-
- public static String ExtractConstantInputPage_selection_refers_to_nonfinal_fields;
-
- public static String ExtractConstantInputPage_signature_preview;
-
- public static String ExtractConstantWizard_defaultPageTitle;
-
- public static String ExtractInterfaceAction_Extract_Interface;
-
- public static String ExtractInterfaceAction_not_possible;
-
- public static String ExtractInterfaceAction_Refactoring;
-
- public static String ExtractInterfaceAction_To_activate;
-
- public static String ExtractInterfaceInputPage_change_references;
-
- public static String ExtractInterfaceInputPage_description;
-
- public static String ExtractInterfaceInputPage_Deselect_All;
-
- public static String ExtractInterfaceInputPage_Extract_Interface;
-
- public static String ExtractInterfaceInputPage_Interface_name;
-
- public static String ExtractInterfaceInputPage_Internal_Error;
-
- public static String ExtractInterfaceInputPage_Members;
-
- public static String ExtractInterfaceInputPage_Select_All;
-
- public static String ExtractInterfaceWizard_12;
-
- public static String ExtractInterfaceWizard_abstract_label;
-
- public static String ExtractInterfaceWizard_Extract_Interface;
-
- public static String ExtractInterfaceWizard_generate_comments;
-
- public static String ExtractInterfaceWizard_public_label;
-
- public static String ExtractInterfaceWizard_use_supertype;
-
- public static String ExtractMethodAction_dialog_title;
-
- public static String ExtractMethodAction_label;
-
- public static String ExtractMethodInputPage_access_Modifiers;
-
- public static String ExtractMethodInputPage_anonymous_type_label;
-
- public static String ExtractMethodInputPage_default;
-
- public static String ExtractMethodInputPage_description;
-
- public static String ExtractMethodInputPage_destination_type;
-
- public static String ExtractMethodInputPage_duplicates_multi;
-
- public static String ExtractMethodInputPage_duplicates_none;
-
- public static String ExtractMethodInputPage_duplicates_single;
-
- public static String ExtractMethodInputPage_generateJavadocComment;
-
- public static String ExtractMethodInputPage_label_text;
-
- public static String ExtractMethodInputPage_parameters;
-
- public static String ExtractMethodInputPage_private;
-
- public static String ExtractMethodInputPage_protected;
-
- public static String ExtractMethodInputPage_public;
-
- public static String ExtractMethodInputPage_signature_preview;
-
- public static String ExtractMethodInputPage_throwRuntimeExceptions;
-
- public static String ExtractMethodInputPage_validation_emptyMethodName;
-
- public static String ExtractMethodInputPage_validation_emptyParameterName;
-
- public static String ExtractMethodWizard_extract_method;
-
- public static String ExtractSuperTypeAction_label;
-
- public static String ExtractSuperTypeAction_unavailable;
-
- public static String ExtractSupertypeMemberPage_add_button_label;
-
- public static String ExtractSupertypeMemberPage_choose_type_caption;
-
- public static String ExtractSupertypeMemberPage_choose_type_message;
-
- public static String ExtractSupertypeMemberPage_create_stubs_label;
-
- public static String ExtractSupertypeMemberPage_declare_abstract;
-
- public static String ExtractSupertypeMemberPage_extract;
-
- public static String ExtractSupertypeMemberPage_extract_supertype;
-
- public static String ExtractSupertypeMemberPage_name_label;
-
- public static String ExtractSupertypeMemberPage_no_members_selected;
-
- public static String ExtractSupertypeMemberPage_page_title;
-
- public static String ExtractSupertypeMemberPage_remove_button_label;
-
- public static String ExtractSupertypeMemberPage_types_list_caption;
-
- public static String ExtractSupertypeMemberPage_use_instanceof_label;
-
- public static String ExtractSupertypeMemberPage_use_supertype_label;
-
- public static String ExtractSupertypeWizard_defaultPageTitle;
-
- public static String ExtractTempAction_extract_temp;
-
- public static String ExtractTempAction_label;
-
- public static String ExtractTempInputPage_declare_final;
-
- public static String ExtractTempInputPage_enter_name;
-
- public static String ExtractTempInputPage_exception;
-
- public static String ExtractTempInputPage_extract_local;
-
- public static String ExtractTempInputPage_replace_all;
-
- public static String ExtractTempInputPage_signature_preview;
-
- public static String ExtractTempInputPage_variable_name;
-
- public static String ExtractTempWizard_defaultPageTitle;
-
- public static String InferTypeArgumentsAction_dialog_title;
-
- public static String InferTypeArgumentsAction_label;
-
- public static String InferTypeArgumentsAction_unavailable;
-
- public static String InferTypeArgumentsInputPage_description;
-
- public static String InferTypeArgumentsWizard_assumeCloneSameType;
-
- public static String InferTypeArgumentsWizard_defaultPageTitle;
-
- public static String InferTypeArgumentsWizard_leaveUnconstrainedRaw;
-
- public static String InferTypeArgumentsWizard_lengthyDescription;
-
- public static String InlineAction_dialog_title;
-
- public static String InlineAction_Inline;
-
- public static String InlineAction_select;
-
- public static String InlineConstantAction_dialog_title;
-
- public static String InlineConstantAction_inline_Constant;
-
- public static String InlineConstantAction_no_constant_reference_or_declaration;
-
- public static String InlineConstantAction_unexpected_exception;
-
- public static String InlineConstantInputPage_All_references;
-
- public static String InlineConstantInputPage_Delete_constant;
-
- public static String InlineConstantInputPage_Inline;
-
- public static String InlineConstantInputPage_Only_selected;
-
- public static String InlineConstantWizard_initializer_refers_to_fields;
-
- public static String InlineConstantWizard_Inline_Constant;
-
- public static String InlineConstantWizard_message;
-
- public static String InlineMethodAction_dialog_title;
-
- public static String InlineMethodAction_inline_Method;
-
- public static String InlineMethodAction_no_method_invocation_or_declaration_selected;
-
- public static String InlineMethodAction_unexpected_exception;
-
- public static String InlineMethodInputPage_all_invocations;
-
- public static String InlineMethodInputPage_delete_declaration;
-
- public static String InlineMethodInputPage_description;
-
- public static String InlineMethodInputPage_inline;
-
- public static String InlineMethodInputPage_only_selected;
-
- public static String InlineMethodWizard_page_title;
-
- public static String InlineTempAction_inline_temp;
-
- public static String InlineTempAction_label;
-
- public static String InlineTempInputPage_message_multi;
-
- public static String InlineTempInputPage_message_one;
-
- public static String InlineTempInputPage_message_zero;
-
- public static String InlineTempWizard_defaultPageTitle;
-
- public static String IntroduceFactoryAction_description;
-
- public static String IntroduceFactoryAction_dialog_title;
-
- public static String IntroduceFactoryAction_exception;
-
- public static String IntroduceFactoryAction_label;
-
- public static String IntroduceFactoryAction_tooltipText;
-
- public static String IntroduceFactoryAction_use_factory;
-
- public static String IntroduceFactoryInputPage_browseLabel;
-
- public static String IntroduceFactoryInputPage_chooseFactoryClass_message;
-
- public static String IntroduceFactoryInputPage_chooseFactoryClass_title;
-
- public static String IntroduceFactoryInputPage_factoryClassLabel;
-
- public static String IntroduceFactoryInputPage_method_name;
-
- public static String IntroduceFactoryInputPage_name_factory;
-
- public static String IntroduceFactoryInputPage_protectConstructorLabel;
-
- public static String IntroduceIndirectionAction_description;
-
- public static String IntroduceIndirectionAction_dialog_title;
-
- public static String IntroduceIndirectionAction_title;
-
- public static String IntroduceIndirectionAction_tooltip;
-
- public static String IntroduceIndirectionAction_unknown_exception;
-
- public static String IntroduceIndirectionInputPage_browse;
-
- public static String IntroduceIndirectionInputPage_declaring_class;
-
- public static String IntroduceIndirectionInputPage_dialog_choose_declaring_class;
-
- public static String IntroduceIndirectionInputPage_dialog_choose_declaring_class_long;
-
- public static String IntroduceIndirectionInputPage_new_method_name;
-
- public static String IntroduceIndirectionInputPage_select_declaring_class;
-
- public static String IntroduceIndirectionInputPage_update_references;
-
- public static String IntroduceParameterAction_dialog_title;
-
- public static String IntroduceParameterAction_label;
-
- public static String IntroduceParameterInputPage_description;
-
- public static String IntroduceParameterWizard_defaultPageTitle;
-
- public static String IntroduceParameterWizard_parameters;
-
- public static String JavaStatusContextViewer_no_source_available;
-
- public static String JavaStatusContextViewer_no_source_found0;
-
- public static String JavaTypeCompletionProcessor_no_completion;
-
- public static String ModifyParametersAction_unavailable;
-
- public static String MoveAction_Move;
-
- public static String MoveAction_select;
-
- public static String MoveAction_text;
-
- public static String MoveInnerToToplnputPage_description;
-
- public static String MoveInnerToToplnputPage_enter_name;
-
- public static String MoveInnerToToplnputPage_enter_name_mandatory;
-
- public static String MoveInnerToToplnputPage_instance_final;
-
- public static String MoveInnerToToplnputPage_mandatory_info;
-
- public static String MoveInnerToToplnputPage_optional_info;
-
- public static String MoveInnerToTopWizard_Move_Inner;
-
- public static String MoveInstanceMethodAction_dialog_title;
-
- public static String MoveInstanceMethodAction_Move_Method;
-
- public static String MoveInstanceMethodAction_No_reference_or_declaration;
-
- public static String MoveInstanceMethodAction_unexpected_exception;
-
- public static String MoveInstanceMethodPage_Create_button_name;
-
- public static String MoveInstanceMethodPage_Deprecate_button_name;
-
- public static String MoveInstanceMethodPage_invalid_target;
-
- public static String MoveInstanceMethodPage_Method_name;
-
- public static String MoveInstanceMethodPage_Name;
-
- public static String MoveInstanceMethodPage_New_receiver;
-
- public static String MoveInstanceMethodPage_Target_name;
-
- public static String MoveInstanceMethodPage_Type;
-
- public static String MoveInstanceMethodWizard_Move_Method;
-
- public static String MoveMembersAction_error_message;
-
- public static String MoveMembersAction_error_title;
-
- public static String MoveMembersAction_unavailable;
-
- public static String MoveMembersInputPage_browse;
-
- public static String MoveMembersInputPage_choose_Type;
-
- public static String MoveMembersInputPage_descriptionKey;
-
- public static String MoveMembersInputPage_destination_multi;
-
- public static String MoveMembersInputPage_destination_single;
-
- public static String MoveMembersInputPage_dialogMessage;
-
- public static String MoveMembersInputPage_exception;
-
- public static String MoveMembersInputPage_internal_error;
-
- public static String MoveMembersInputPage_invalid_name;
-
- public static String MoveMembersInputPage_Invalid_selection;
-
- public static String MoveMembersInputPage_lowerListLabel;
-
- public static String MoveMembersInputPage_move;
-
- public static String MoveMembersInputPage_move_Member;
-
- public static String MoveMembersInputPage_no_binary;
-
- public static String MoveMembersInputPage_not_found;
-
- public static String MoveMembersInputPage_upperListLabel;
-
- public static String MoveMembersWizard_page_title;
-
- public static String NewTextRefactoringAction_exception;
-
- public static String OpenRefactoringWizardAction_exception;
-
- public static String OpenRefactoringWizardAction_refactoring;
-
- public static String OpenRefactoringWizardAction_unavailable;
-
- public static String ParameterEditDialog_defaultValue;
-
- public static String ParameterEditDialog_defaultValue_error;
-
- public static String ParameterEditDialog_defaultValue_invalid;
-
- public static String ParameterEditDialog_message;
-
- public static String ParameterEditDialog_message_new;
-
- public static String ParameterEditDialog_name;
-
- public static String ParameterEditDialog_name_error;
-
- public static String ParameterEditDialog_title;
-
- public static String ParameterEditDialog_type;
-
- public static String ParameterEditDialog_type_error;
-
- public static String ParameterEditDialog_type_invalid;
-
- public static String PromoteTempInputPage_constructors;
-
- public static String PromoteTempInputPage_Current_method;
-
- public static String PromoteTempInputPage_declare_final;
-
- public static String PromoteTempInputPage_declare_static;
-
- public static String PromoteTempInputPage_description;
-
- public static String PromoteTempInputPage_Field_declaration;
-
- public static String PromoteTempInputPage_Field_name;
-
- public static String PromoteTempInputPage_Initialize;
-
- public static String PullUpAction_unavailable;
-
- public static String PullUpInputPage_exception;
-
- public static String PullUpInputPage_hierarchyLabal;
-
- public static String PullUpInputPage_pull_Up;
-
- public static String PullUpInputPage_pull_up1;
-
- public static String PullUpInputPage_see_log;
-
- public static String PullUpInputPage_select_methods;
-
- public static String PullUpInputPage_subtypes;
-
- public static String PullUpInputPage1_Action;
-
- public static String PullUpInputPage1_Add_Required;
-
- public static String PullUpInputPage1_Create_stubs;
-
- public static String PullUpInputPage1_declare_abstract;
-
- public static String PullUpInputPage1_Edit;
-
- public static String PullUpInputPage1_Edit_members;
-
- public static String PullUpInputPage1_label_use_destination;
-
- public static String PullUpInputPage1_label_use_in_instanceof;
-
- public static String PullUpInputPage1_Mark_selected_members;
-
- public static String PullUpInputPage1_Member;
-
- public static String PullUpInputPage1_page_message;
-
- public static String PullUpInputPage1_pull_up;
-
- public static String PullUpInputPage1_Select_destination;
-
- public static String PullUpInputPage1_Select_members_to_pull_up;
-
- public static String PullUpInputPage1_Specify_actions;
-
- public static String PullUpInputPage1_status_line;
-
- public static String PullUpInputPage2_Select;
-
- public static String PullUpInputPage2_Source;
-
- public static String PullUpWizard_defaultPageTitle;
-
- public static String PullUpWizard_deselect_all_label;
-
- public static String PullUpWizard_select_all_label;
-
- public static String PushDownAction_not_possible;
-
- public static String PushDownAction_Push_Down;
-
- public static String PushDownAction_Refactoring;
-
- public static String PushDownAction_To_activate;
-
- public static String PushDownInputPage_Action;
-
- public static String PushDownInputPage_Add_Required;
-
- public static String PushDownInputPage_Edit;
-
- public static String PushDownInputPage_Edit_members;
-
- public static String PushDownInputPage_Internal_Error;
-
- public static String PushDownInputPage_leave_abstract;
-
- public static String PushDownInputPage_Mark_selected_members;
-
- public static String PushDownInputPage_Member;
-
- public static String PushDownInputPage_push_down;
-
- public static String PushDownInputPage_Push_Down;
-
- public static String PushDownInputPage_Select_members_to_push_down;
-
- public static String PushDownInputPage_Specify_actions;
-
- public static String PushDownInputPage_status_line;
-
- public static String PushDownWizard_defaultPageTitle;
-
- public static String QualifiedNameComponent_patterns_description;
-
- public static String QualifiedNameComponent_patterns_label;
-
- public static String RefactorActionGroup_no_refactoring_available;
-
- public static String RefactoringErrorDialogUtil_okToPerformQuestion;
-
- public static String RefactoringExecutionHelper_cannot_execute;
-
- public static String RefactoringExecutionStarter_IntroduceParameterObject_problem_description;
-
- public static String RefactoringExecutionStarter_IntroduceParameterObject_problem_title;
-
- public static String RefactoringGroup_modify_Parameters_label;
-
- public static String RefactoringGroup_move_label;
-
- public static String RefactoringGroup_pull_Up_label;
-
- public static String RefactoringStarter_always_save;
-
- public static String RefactoringStarter_must_save;
-
- public static String RefactoringStarter_save_all_resources;
-
- public static String RefactoringStarter_saving;
-
- public static String RefactoringStarter_unexpected_exception;
-
- public static String RenameAction_rename;
-
- public static String RenameAction_text;
-
- public static String RenameAction_unavailable;
-
- public static String RenameCuWizard_defaultPageTitle;
-
- public static String RenameCuWizard_inputPage_description;
-
- public static String RenameEnumConstWizard_defaultPageTitle;
-
- public static String RenameEnumConstWizard_inputPage_description;
-
- public static String RenameFieldInputWizardPage_getter_label;
-
- public static String RenameFieldInputWizardPage_rename_getter;
-
- public static String RenameFieldInputWizardPage_rename_getter_to;
-
- public static String RenameFieldInputWizardPage_rename_setter;
-
- public static String RenameFieldInputWizardPage_rename_setter_to;
-
- public static String RenameFieldInputWizardPage_setter_label;
-
- public static String RenameFieldWizard_defaultPageTitle;
-
- public static String RenameFieldWizard_inputPage_description;
-
- public static String RenameInputWizardPage_new_name;
-
- public static String RenameInputWizardPage_update_qualified_names;
-
- public static String RenameInputWizardPage_update_references;
-
- public static String RenameInputWizardPage_update_textual_matches;
-
- public static String RenameJavaElementAction_exception;
-
- public static String RenameJavaElementAction_name;
-
- public static String RenameJavaElementAction_not_available;
-
- public static String RenameJavaProject_defaultPageTitle;
-
- public static String RenameJavaProject_inputPage_description;
-
- public static String RenameLocalVariableWizard_defaultPageTitle;
-
- public static String RenameLocalVariableWizard_inputPage_description;
-
- public static String RenameMethodWizard_defaultPageTitle;
-
- public static String RenameMethodWizard_inputPage_description;
-
- public static String RenamePackageWizard_defaultPageTitle;
-
- public static String RenamePackageWizard_inputPage_description;
-
- public static String RenamePackageWizard_rename_subpackages;
-
- public static String RenameRefactoringWizard_internal_error;
-
- public static String RenameResourceWizard_defaultPageTitle;
-
- public static String RenameResourceWizard_inputPage_description;
-
- public static String RenameSourceFolder_defaultPageTitle;
-
- public static String RenameSourceFolder_inputPage_description;
-
- public static String RenameTempAction_exception;
-
- public static String RenameTypeParameterWizard_defaultPageTitle;
-
- public static String RenameTypeParameterWizard_inputPage_description;
-
- public static String RenameTypeWizard_defaultPageTitle;
-
- public static String RenameTypeWizard_unexpected_exception;
-
- public static String RenameTypeWizardInputPage_description;
-
- public static String RenameTypeWizardInputPage_update_similar_elements;
-
- public static String RenameTypeWizardInputPage_update_similar_elements_configure;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_select_strategy;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_strategy_1;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_strategy_2;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_strategy_3;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_title;
-
- public static String RenameTypeWizardSimilarElementsOptionsDialog_warning_short_names;
-
- public static String RenameTypeWizardSimilarElementsPage_change_element_name;
-
- public static String RenameTypeWizardSimilarElementsPage_change_name;
-
- public static String RenameTypeWizardSimilarElementsPage_enter_new_name;
-
- public static String RenameTypeWizardSimilarElementsPage_field_exists;
-
- public static String RenameTypeWizardSimilarElementsPage_method_exists;
-
- public static String RenameTypeWizardSimilarElementsPage_name_empty;
-
- public static String RenameTypeWizardSimilarElementsPage_name_should_start_lowercase;
-
- public static String RenameTypeWizardSimilarElementsPage_rename_to;
-
- public static String RenameTypeWizardSimilarElementsPage_restore_defaults;
-
- public static String RenameTypeWizardSimilarElementsPage_review_similar_elements;
-
- public static String RenameTypeWizardSimilarElementsPage_select_element_to_view_source;
-
- public static String ReplaceInvocationsAction_dialog_title;
-
- public static String ReplaceInvocationsAction_label;
-
- public static String ReplaceInvocationsAction_unavailable;
-
- public static String ReplaceInvocationsInputPage_replaceAll;
-
- public static String ReplaceInvocationsInputPage_replaceInvocationsBy;
-
- public static String ReplaceInvocationsWizard_title;
-
- public static String SelfEncapsulateField_field_access;
-
- public static String SelfEncapsulateField_keep_references;
-
- public static String SelfEncapsulateField_sef;
-
- public static String SelfEncapsulateField_use_setter_getter;
-
- public static String SelfEncapsulateFieldInputPage_access_Modifiers;
-
- public static String SelfEncapsulateFieldInputPage_default;
-
- public static String SelfEncapsulateFieldInputPage_description;
-
- public static String SelfEncapsulateFieldInputPage_first_method;
-
- public static String SelfEncapsulateFieldInputPage_generateJavadocComment;
-
- public static String SelfEncapsulateFieldInputPage_getter_name;
-
- public static String SelfEncapsulateFieldInputPage_insert_after;
-
- public static String SelfEncapsulateFieldInputPage_private;
-
- public static String SelfEncapsulateFieldInputPage_protected;
-
- public static String SelfEncapsulateFieldInputPage_public;
-
- public static String SelfEncapsulateFieldInputPage_setter_name;
-
- public static String SelfEncapsulateFieldInputPage_usenewgetter_label;
-
- public static String SelfEncapsulateFieldInputPage_usenewsetter_label;
-
- public static String SurroundWithTryCatchAction_dialog_title;
-
- public static String SurroundWithTryCatchAction_exception;
-
- public static String SurroundWithTryCatchAction_label;
-
- public static String SurroundWithTryCatchAction_no_exceptions;
-
- public static String UseSupertypeAction_not_possible;
-
- public static String UseSupertypeAction_Refactoring;
-
- public static String UseSupertypeAction_to_activate;
-
- public static String UseSupertypeAction_use_Supertype;
-
- public static String UseSupertypeInputPage_Internal_Error;
-
- public static String UseSupertypeInputPage_no_possible_updates;
-
- public static String UseSupertypeInputPage_No_updates;
-
- public static String UseSupertypeInputPage_Select_supertype;
-
- public static String UseSupertypeInputPage_Select_supertype_to_use;
-
- public static String UseSupertypeInputPage_updates_possible_in_file;
-
- public static String UseSupertypeInputPage_updates_possible_in_files;
-
- public static String UseSupertypeInputPage_Use_in_instanceof;
-
- public static String UseSupertypeInputPage_Use_Supertype;
-
- public static String UseSupertypeWizard_10;
-
- public static String UseSupertypeWizard_Use_Super_Type_Where_Possible;
-
- public static String VisibilityControlUtil_Access_modifier;
-
- public static String VisibilityControlUtil_defa_ult_4;
-
- public static String VisibilityControlUtil_final;
-
- public static String VisibilityControlUtil_synchronized;
-
- public static String SelfEncapsulateFieldInputPage_useexistingsetter_label;
-
- public static String SelfEncapsulateFieldInputPage_useexistinggetter_label;
-
- public static String JarImportWizard_prepare_import;
- public static String JarImportWizard_error_shared_jar;
- public static String BinaryRefactoringHistoryWizard_error_missing_source_attachment;
- public static String JarImportWizard_cleanup_import;
-
-
- static {
- reloadMessages();
- }
-
- public static void reloadMessages() {
- NLS.initializeMessages(BUNDLE_NAME, RefactoringMessages.class);
- }
-
- private RefactoringMessages() {
- // Do not instantiate
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSaveHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSaveHelper.java
deleted file mode 100644
index 74c88fc9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSaveHelper.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceDescription;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.GlobalBuildAction;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.ListDialog;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-public class RefactoringSaveHelper {
-
- private boolean fFilesSaved;
- private final int fSaveMode;
-
- /**
- * Save mode to save all dirty editors (always ask).
- */
- public static final int SAVE_ALL_ALWAYS_ASK= 1;
-
- /**
- * Save mode to save all dirty editors.
- */
- public static final int SAVE_ALL= 2;
-
- /**
- * Save mode to save all unknown editors, i.e. those that don't work on
- * resources, don't use file buffers, or are otherwise suspect.
- *
- * Used for refactorings with participants or qualified name updating.
- */
- public static final int SAVE_NON_JAVA_UPDATES= 3;
-
- /**
- * Save mode to save only dirty editors on compilation units that are not in
- * working copy mode.
- *
- * Used for refactorings without participants or qualified name updating.
- */
- public static final int SAVE_JAVA_ONLY_UPDATES= 4;
-
- /**
- * Save mode to not save save any editors.
- */
- public static final int SAVE_NOTHING= 5;
-
- /**
- * @param saveMode one of the SAVE_* constants
- */
- public RefactoringSaveHelper(int saveMode) {
- Assert.isTrue(saveMode == SAVE_ALL_ALWAYS_ASK
- || saveMode == SAVE_ALL
- || saveMode == SAVE_NON_JAVA_UPDATES
- || saveMode == SAVE_JAVA_ONLY_UPDATES
- || saveMode == SAVE_NOTHING);
- fSaveMode= saveMode;
- }
-
- /**
- * @param shell
- * @return <code>true</code> if save was successful and refactoring can proceed;
- * false if the refactoring must be cancelled
- */
- public boolean saveEditors(Shell shell) {
- final IEditorPart[] dirtyEditors;
- switch (fSaveMode) {
- case SAVE_ALL_ALWAYS_ASK:
- case SAVE_ALL:
- dirtyEditors= EditorUtility.getDirtyEditors();
- break;
-
- case SAVE_NON_JAVA_UPDATES:
- dirtyEditors= EditorUtility.getDirtyEditorsToSave(false); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=175495
- break;
-
- case SAVE_JAVA_ONLY_UPDATES:
- dirtyEditors= EditorUtility.getDirtyEditorsToSave(false);
- break;
-
- case SAVE_NOTHING:
- return true;
-
- default:
- throw new IllegalStateException(Integer.toString(fSaveMode));
- }
- if (dirtyEditors.length == 0)
- return true;
- if (! askSaveAllDirtyEditors(shell, dirtyEditors))
- return false;
- try {
- // Save isn't cancelable.
- IWorkspace workspace= ResourcesPlugin.getWorkspace();
- IWorkspaceDescription description= workspace.getDescription();
- boolean autoBuild= description.isAutoBuilding();
- description.setAutoBuilding(false);
- workspace.setDescription(description);
- try {
- if (fSaveMode == SAVE_ALL_ALWAYS_ASK || fSaveMode == SAVE_ALL
- || RefactoringSavePreferences.getSaveAllEditors()) {
- if (!JavaScriptPlugin.getActiveWorkbenchWindow().getWorkbench().saveAllEditors(false))
- return false;
- } else {
- IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) throws InterruptedException {
- int count= dirtyEditors.length;
- pm.beginTask("", count); //$NON-NLS-1$
- for (int i= 0; i < count; i++) {
- IEditorPart editor= dirtyEditors[i];
- editor.doSave(new SubProgressMonitor(pm, 1));
- if (pm.isCanceled())
- throw new InterruptedException();
- }
- pm.done();
- }
- };
- try {
- PlatformUI.getWorkbench().getProgressService().runInUI(JavaScriptPlugin.getActiveWorkbenchWindow(), runnable, null);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, shell,
- RefactoringMessages.RefactoringStarter_saving, RefactoringMessages.RefactoringStarter_unexpected_exception);
- return false;
- }
- }
- fFilesSaved= true;
- } finally {
- description.setAutoBuilding(autoBuild);
- workspace.setDescription(description);
- }
- return true;
- } catch (CoreException e) {
- ExceptionHandler.handle(e, shell,
- RefactoringMessages.RefactoringStarter_saving, RefactoringMessages.RefactoringStarter_unexpected_exception);
- return false;
- }
- }
-
- public void triggerBuild() {
- if (fFilesSaved && ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding()) {
- new GlobalBuildAction(JavaScriptPlugin.getActiveWorkbenchWindow(), IncrementalProjectBuilder.INCREMENTAL_BUILD).run();
- }
- }
-
- private boolean askSaveAllDirtyEditors(Shell shell, IEditorPart[] dirtyEditors) {
- final boolean canSaveAutomatically= fSaveMode != SAVE_ALL_ALWAYS_ASK;
- if (canSaveAutomatically && RefactoringSavePreferences.getSaveAllEditors()) //must save everything
- return true;
- ListDialog dialog= new ListDialog(shell) {
- {
- setShellStyle(getShellStyle() | SWT.APPLICATION_MODAL);
- }
- protected Control createDialogArea(Composite parent) {
- Composite result= (Composite) super.createDialogArea(parent);
- if (canSaveAutomatically) {
- final Button check= new Button(result, SWT.CHECK);
- check.setText(RefactoringMessages.RefactoringStarter_always_save);
- check.setSelection(RefactoringSavePreferences.getSaveAllEditors());
- check.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- RefactoringSavePreferences.setSaveAllEditors(check.getSelection());
- }
- });
- applyDialogFont(result);
- }
- return result;
- }
- };
- dialog.setTitle(RefactoringMessages.RefactoringStarter_save_all_resources);
- dialog.setAddCancelButton(true);
- dialog.setLabelProvider(createDialogLabelProvider());
- dialog.setMessage(RefactoringMessages.RefactoringStarter_must_save);
- dialog.setContentProvider(new ArrayContentProvider());
- dialog.setInput(Arrays.asList(dirtyEditors));
- return dialog.open() == Window.OK;
- }
-
- public boolean hasFilesSaved() {
- return fFilesSaved;
- }
-
- private ILabelProvider createDialogLabelProvider() {
- return new LabelProvider() {
- public Image getImage(Object element) {
- return ((IEditorPart) element).getTitleImage();
- }
- public String getText(Object element) {
- return ((IEditorPart) element).getTitle();
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSavePreferences.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSavePreferences.java
deleted file mode 100644
index 2545a1d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringSavePreferences.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class RefactoringSavePreferences {
-
- public static final String PREF_SAVE_ALL_EDITORS= PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS;
-
- public static boolean getSaveAllEditors() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- return store.getBoolean(PREF_SAVE_ALL_EDITORS);
- }
-
- public static void setSaveAllEditors(boolean save) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- store.setValue(PREF_SAVE_ALL_EDITORS, save);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/TextInputWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/TextInputWizardPage.java
deleted file mode 100644
index 7e7e694c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/TextInputWizardPage.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-
-/**
- * A TextInputWizardPage is a simple UserInputWizardPage with facilities
- * to create a text input field and validate its contents.
- * The text is assumed to be a java identifier, hence CamelCase word jumping is installed.
- */
-public abstract class TextInputWizardPage extends UserInputWizardPage{
-
- private String fInitialValue;
- private Text fTextField;
-
- public static final String PAGE_NAME= "TextInputPage";//$NON-NLS-1$
-
- /**
- * Creates a new text input page.
- * @param isLastUserPage <code>true</code> if this page is the wizard's last
- * user input page. Otherwise <code>false</code>.
- */
- public TextInputWizardPage(String description, boolean isLastUserPage) {
- this(description, isLastUserPage, ""); //$NON-NLS-1$
- }
-
- /**
- * Creates a new text input page.
- * @param isLastUserPage <code>true</code> if this page is the wizard's last
- * user input page. Otherwise <code>false</code>
- * @param initialValue the initial value
- */
- public TextInputWizardPage(String description, boolean isLastUserPage, String initialValue) {
- super(PAGE_NAME);
- Assert.isNotNull(initialValue);
- setDescription(description);
- fInitialValue= initialValue;
- }
-
- /**
- * Returns whether the initial input is valid. Typically it is not, because the
- * user is required to provide some information e.g. a new type name etc.
- *
- * @return <code>true</code> iff the input provided at initialization is valid
- */
- protected boolean isInitialInputValid(){
- return false;
- }
-
- /**
- * Returns whether an empty string is a valid input. Typically it is not, because
- * the user is required to provide some information e.g. a new type name etc.
- *
- * @return <code>true</code> iff an empty string is valid
- */
- protected boolean isEmptyInputValid(){
- return false;
- }
-
- /**
- * Returns the content of the text input field.
- *
- * @return the content of the text input field. Returns <code>null</code> if
- * not text input field has been created
- */
- protected String getText() {
- if (fTextField == null)
- return null;
- return fTextField.getText();
- }
-
- /**
- * Sets the new text for the text field. Does nothing if the text field has not been created.
- * @param text the new value
- */
- protected void setText(String text) {
- if (fTextField == null)
- return;
- fTextField.setText(text);
- }
-
- /**
- * Returns the text entry field
- *
- * @return the text entry field
- */
- protected Text getTextField() {
- return fTextField;
- }
-
- /**
- * Returns the initial value.
- *
- * @return the initial value
- */
- public String getInitialValue() {
- return fInitialValue;
- }
-
- /**
- * Performs input validation. Returns a <code>RefactoringStatus</code> which
- * describes the result of input validation. <code>Null<code> is interpreted
- * as no error.
- */
- protected RefactoringStatus validateTextField(String text){
- return null;
- }
-
- protected Text createTextInputField(Composite parent) {
- return createTextInputField(parent, SWT.BORDER);
- }
-
- protected Text createTextInputField(Composite parent, int style) {
- fTextField= new Text(parent, style);
- fTextField.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- textModified(getText());
- }
- });
- fTextField.setText(fInitialValue);
- TextFieldNavigationHandler.install(fTextField);
- return fTextField;
- }
-
- /**
- * Checks the page's state and issues a corresponding error message. The page validation
- * is computed by calling <code>validatePage</code>.
- */
- protected void textModified(String text) {
- if (! isEmptyInputValid() && "".equals(text)){ //$NON-NLS-1$
- setPageComplete(false);
- setErrorMessage(null);
- restoreMessage();
- return;
- }
- if ((! isInitialInputValid()) && fInitialValue.equals(text)){
- setPageComplete(false);
- setErrorMessage(null);
- restoreMessage();
- return;
- }
-
- RefactoringStatus status= validateTextField(text);
- if (status == null)
- status= new RefactoringStatus();
- setPageComplete(status);
- }
-
- /**
- * Subclasses can override if they want to restore the message differently.
- * This implementation calls <code>setMessage(null)</code>, which clears the message
- * thus exposing the description.
- */
- protected void restoreMessage(){
- setMessage(null);
- }
-
- /* (non-Javadoc)
- * Method declared in IDialogPage
- */
- public void dispose() {
- fTextField= null;
- }
-
- /* (non-Javadoc)
- * Method declared in WizardPage
- */
- public void setVisible(boolean visible) {
- if (visible) {
- textModified(getText());
- }
- super.setVisible(visible);
- if (visible && fTextField != null) {
- fTextField.setFocus();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UseSupertypeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UseSupertypeWizard.java
deleted file mode 100644
index 627e387f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UseSupertypeWizard.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.UseSuperTypeRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class UseSupertypeWizard extends RefactoringWizard{
-
- /* package */ static final String DIALOG_SETTING_SECTION= "UseSupertypeWizard"; //$NON-NLS-1$
-
- public UseSupertypeWizard(UseSuperTypeRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.UseSupertypeWizard_Use_Super_Type_Where_Possible);
- }
-
- protected void addUserInputPages(){
- addPage(new UseSupertypeInputPage());
- }
-
- private static class UseSupertypeInputPage extends UserInputWizardPage{
-
- private class UseSupertypeContentProvider implements ITreeContentProvider {
-
- private ITypeHierarchy fHierarchy;
-
- public Object[] getChildren(Object element) {
- if (element instanceof ITypeHierarchy)
- return getElements(element);
- return getDirectSuperTypes((IType)element).toArray();
- }
-
- public Set/*<IType>*/ getDirectSuperTypes(IType type){
- Set/*<IType>*/ result= new HashSet();
- final IType superclass= fHierarchy.getSuperclass(type);
- if (superclass != null) {
- result.add(superclass);
- }
- return result;
- }
-
- public Object[] getElements(Object element) {
- if (element instanceof ITypeHierarchy)
- return getChildren(((ITypeHierarchy) element).getType());
- return new Object[0];
- }
-
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- public Object getParent(Object element) {
- return null;
- }
-
- public void dispose() {
- // Do nothing
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof ITypeHierarchy)
- fHierarchy= (ITypeHierarchy) newInput;
- else
- fHierarchy= null;
- }
- }
-
- private static final String REWRITE_INSTANCEOF= "rewriteInstanceOf"; //$NON-NLS-1$
- public static final String PAGE_NAME= "UseSupertypeInputPage";//$NON-NLS-1$
- private TreeViewer fTreeViewer;
- private final Map fFileCount; //IType -> Integer
- private final static String MESSAGE= RefactoringMessages.UseSupertypeInputPage_Select_supertype;
- private JavaScriptElementLabelProvider fLabelProvider;
- private IDialogSettings fSettings;
-
- public UseSupertypeInputPage() {
- super(PAGE_NAME);
- fFileCount= new HashMap(2);
- setMessage(MESSAGE);
- }
-
- private void loadSettings() {
- fSettings= getDialogSettings().getSection(UseSupertypeWizard.DIALOG_SETTING_SECTION);
- if (fSettings == null) {
- fSettings= getDialogSettings().addNewSection(UseSupertypeWizard.DIALOG_SETTING_SECTION);
- fSettings.put(REWRITE_INSTANCEOF, false);
- }
- getUseSupertypeProcessor().setInstanceOf(fSettings.getBoolean(REWRITE_INSTANCEOF));
- }
-
- private UseSuperTypeProcessor getUseSupertypeProcessor() {
- return getUseSupertypeRefactoring().getUseSuperTypeProcessor();
- }
-
- private UseSuperTypeRefactoring getUseSupertypeRefactoring() {
- return ((UseSuperTypeRefactoring)getRefactoring());
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- loadSettings();
- Composite composite= new Composite(parent, SWT.NONE);
- setControl(composite);
- composite.setLayout(new GridLayout());
-
- Label label= new Label(composite, SWT.NONE);
- label.setText(Messages.format(
- RefactoringMessages.UseSupertypeInputPage_Select_supertype_to_use,
- JavaScriptElementLabels.getElementLabel(getUseSupertypeProcessor().getSubType(), JavaScriptElementLabels.T_FULLY_QUALIFIED)));
- label.setLayoutData(new GridData());
-
- addTreeViewer(composite);
-
- final Button checkbox= new Button(composite, SWT.CHECK);
- checkbox.setText(RefactoringMessages.UseSupertypeInputPage_Use_in_instanceof);
- checkbox.setLayoutData(new GridData());
- checkbox.setSelection(getUseSupertypeProcessor().isInstanceOf());
- checkbox.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getUseSupertypeProcessor().setInstanceOf(checkbox.getSelection());
- fSettings.put(REWRITE_INSTANCEOF, checkbox.getSelection());
- setMessage(MESSAGE);
- setPageComplete(true);
- fFileCount.clear();
- fTreeViewer.refresh();
- }
- });
-
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.USE_SUPERTYPE_WIZARD_PAGE);
- }
-
- private void addTreeViewer(Composite composite) {
- fTreeViewer= new TreeViewer(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- final Tree tree= fTreeViewer.getTree();
- final GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= convertHeightInCharsToPixels(12);
- tree.setLayoutData(data);
- fLabelProvider= new UseSupertypeLabelProvider(fFileCount);
- fTreeViewer.setLabelProvider(fLabelProvider);
- fTreeViewer.setContentProvider(new UseSupertypeContentProvider());
- fTreeViewer.setComparator(new ViewerComparator() {
-
- public boolean isSorterProperty(Object element, String property) {
- return true;
- }
-
- public int compare(Viewer viewer, Object first, Object second) {
- final IType type1= (IType)first;
- final IType type2= (IType)second;
-
- return getComparator().compare(type1.getElementName(), type2.getElementName());
- }
- });
- fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection ss= (IStructuredSelection)event.getSelection();
- if (new Integer(0).equals(fFileCount.get(ss.getFirstElement()))){
- setMessage(RefactoringMessages.UseSupertypeInputPage_No_updates, IMessageProvider.INFORMATION);
- setPageComplete(false);
- } else {
- setMessage(MESSAGE);
- setPageComplete(true);
- }
- fTreeViewer.refresh();
- }
- });
- try {
- fTreeViewer.setInput(SuperTypeHierarchyCache.getTypeHierarchy(getUseSupertypeProcessor().getSubType()));
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- fTreeViewer.expandAll();
- final TreeItem[] items= tree.getItems();
- if (items.length > 0)
- tree.setSelection(new TreeItem[] {items[0]});
- }
-
- public IWizardPage getNextPage() {
- initializeRefactoring();
- IWizardPage nextPage= super.getNextPage();
- updateUpdateLabels();
- return nextPage;
- }
-
- private void updateUpdateLabels() {
- IType selectedType= getSelectedSupertype();
- final int count= getUseSupertypeProcessor().getChanges();
- fFileCount.put(selectedType, new Integer(count));
- if (count == 0) {
- setMessage(RefactoringMessages.UseSupertypeInputPage_No_updates, IMessageProvider.INFORMATION);
- setPageComplete(false);
- }
- fTreeViewer.refresh();
- if (noSupertypeCanBeUsed()){
- setMessage(RefactoringMessages.UseSupertypeWizard_10, IMessageProvider.INFORMATION);
- setPageComplete(false);
- }
- }
-
- private boolean noSupertypeCanBeUsed() {
- return fTreeViewer.getTree().getItemCount() == countFilesWithValue(0);
- }
-
- private int countFilesWithValue(int i) {
- int count= 0;
- for (Iterator iter= fFileCount.keySet().iterator(); iter.hasNext();) {
- if (((Integer)fFileCount.get(iter.next())).intValue() == i)
- count++;
- }
- return count;
- }
-
- private IType getSelectedSupertype() {
- IStructuredSelection ss= (IStructuredSelection)fTreeViewer.getSelection();
- return (IType)ss.getFirstElement();
- }
-
- public boolean performFinish(){
- initializeRefactoring();
- boolean superFinish= super.performFinish();
- if (! superFinish)
- return false;
- final int count= getUseSupertypeProcessor().getChanges();
- if (count == 0) {
- updateUpdateLabels();
- return false;
- }
- return superFinish;
- }
-
- private void initializeRefactoring() {
- IStructuredSelection ss= (IStructuredSelection)fTreeViewer.getSelection();
- getUseSupertypeProcessor().setSuperType((IType)ss.getFirstElement());
- }
-
- public void dispose() {
- fTreeViewer= null;
- fFileCount.clear();
- fLabelProvider= null;
- super.dispose();
- }
-
- private static class UseSupertypeLabelProvider extends JavaScriptElementLabelProvider{
- private final Map fFileCount;
- private UseSupertypeLabelProvider(Map fileCount){
- fFileCount= fileCount;
- }
- public String getText(Object element) {
- String superText= super.getText(element);
- if (! fFileCount.containsKey(element))
- return superText;
- int count= ((Integer)fFileCount.get(element)).intValue();
- if (count == 0){
- String[] keys= {superText};
- return Messages.format(RefactoringMessages.UseSupertypeInputPage_no_possible_updates, keys);
- } else if (count == 1){
- String [] keys= {superText};
- return Messages.format(RefactoringMessages.UseSupertypeInputPage_updates_possible_in_file, keys);
- } else {
- String[] keys= {superText, String.valueOf(count)};
- return Messages.format(RefactoringMessages.UseSupertypeInputPage_updates_possible_in_files, keys);
- }
- }
- }
-
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible && fTreeViewer != null)
- fTreeViewer.getTree().setFocus();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceManager.java
deleted file mode 100644
index cbe5c37c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceManager.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-
-public class UserInterfaceManager {
-
- private Map fMap= new HashMap();
-
- private static class Tuple {
- private Class starter;
- private Class wizard;
- public Tuple(Class s, Class w) {
- starter= s;
- wizard= w;
- }
- }
-
- protected void put(Class processor, Class starter, Class wizard) {
- fMap.put(processor, new Tuple(starter, wizard));
- }
-
-
- public UserInterfaceStarter getStarter(Refactoring refactoring) {
- RefactoringProcessor processor= (RefactoringProcessor)refactoring.getAdapter(RefactoringProcessor.class);
- if (processor == null)
- return null;
- Tuple tuple= (Tuple)fMap.get(processor.getClass());
- if (tuple == null)
- return null;
- try {
- UserInterfaceStarter starter= (UserInterfaceStarter)tuple.starter.newInstance();
- Class wizardClass= tuple.wizard;
- Constructor constructor= wizardClass.getConstructor(new Class[] {Refactoring.class});
- RefactoringWizard wizard= (RefactoringWizard)constructor.newInstance(new Object[] {refactoring});
- starter.initialize(wizard);
- return starter;
- } catch (NoSuchMethodException e) {
- return null;
- } catch (IllegalAccessException e) {
- return null;
- } catch (InstantiationException e) {
- return null;
- } catch (IllegalArgumentException e) {
- return null;
- } catch (InvocationTargetException e) {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceStarter.java
deleted file mode 100644
index fdeb0dc4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/UserInterfaceStarter.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-
-/**
- * Opens the user interface for a given refactoring.
- */
-public class UserInterfaceStarter {
-
- private RefactoringWizard fWizard;
-
- /**
- * Initializes this user interface starter with the given
- * wizard.
- *
- * @param wizard the refactoring wizard to use
- */
- public void initialize(RefactoringWizard wizard) {
- fWizard= wizard;
- }
-
- /**
- * Actually activates the user interface. This default implementation
- * assumes that the configuration element passed to <code>initialize
- * </code> has an attribute wizard denoting the wizard class to be
- * used for the given refactoring.
- * <p>
- * Subclasses may override to open a different user interface
- *
- * @param refactoring the refactoring for which the user interface
- * should be opened
- * @param parent the parent shell to be used
- * @param saveMode a save mode from {@link RefactoringSaveHelper}
- * @return <code>true</code> iff the refactoring was executed,
- * <code>false</code> otherwise
- *
- * @exception CoreException if the user interface can't be activated
- */
- public boolean activate(Refactoring refactoring, Shell parent, int saveMode) throws CoreException {
- String title= fWizard.getDefaultPageTitle();
- if (title == null)
- title= ""; //$NON-NLS-1$
- return new RefactoringStarter().activate(refactoring, fWizard, parent, title, saveMode);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/VisibilityControlUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/VisibilityControlUtil.java
deleted file mode 100644
index acd43112..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/VisibilityControlUtil.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-
-public class VisibilityControlUtil {
- private VisibilityControlUtil(){}
-
- public static Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
- List allowedVisibilities= convertToIntegerList(availableVisibilities);
- if (allowedVisibilities.size() == 1)
- return null;
-
- Group group= new Group(parent, SWT.NONE);
- group.setText(RefactoringMessages.VisibilityControlUtil_Access_modifier);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- group.setLayoutData(gd);
- GridLayout layout= new GridLayout();
- layout.makeColumnsEqualWidth= true;
- layout.numColumns= 4;
- group.setLayout(layout);
-
- String[] labels= new String[] {
- "&public", //$NON-NLS-1$
- "pro&tected", //$NON-NLS-1$
- RefactoringMessages.VisibilityControlUtil_defa_ult_4,
- "pri&vate" //$NON-NLS-1$
- };
- Integer[] data= new Integer[] {
- new Integer(Modifier.PUBLIC),
- new Integer(Modifier.PROTECTED),
- new Integer(Modifier.NONE),
- new Integer(Modifier.PRIVATE)};
- Integer initialVisibility= new Integer(correctVisibility);
- for (int i= 0; i < labels.length; i++) {
- Button radio= new Button(group, SWT.RADIO);
- Integer visibilityCode= data[i];
- radio.setText(labels[i]);
- radio.setData(visibilityCode);
- radio.setSelection(visibilityCode.equals(initialVisibility));
- radio.setEnabled(allowedVisibilities.contains(visibilityCode));
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- visibilityChangeListener.visibilityChanged(((Integer)event.widget.getData()).intValue());
- }
- });
- }
- group.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
- return group;
- }
-
- private static List convertToIntegerList(int[] array) {
- List result= new ArrayList(array.length);
- for (int i= 0; i < array.length; i++) {
- result.add(new Integer(array[i]));
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ApplyRefactoringScriptAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ApplyRefactoringScriptAction.java
deleted file mode 100644
index 4b542f42..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ApplyRefactoringScriptAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-/**
- * Action to apply a refactoring script to the workspace.
- *
- * TODO: remove once bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=131746 is fixed
- */
-public final class ApplyRefactoringScriptAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window, or <code>null</code> */
- private IWorkbenchWindow fWindow= null;
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- // Do nothing
- }
-
- /**
- * {@inheritDoc}
- */
- public void init(final IWorkbenchWindow window) {
- fWindow= window;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(final IAction a) {
- if (fWindow != null) {
- org.eclipse.ltk.ui.refactoring.actions.ApplyRefactoringScriptAction action= new org.eclipse.ltk.ui.refactoring.actions.ApplyRefactoringScriptAction();
- action.init(fWindow);
- action.run(a);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final IAction action, final ISelection selection) {
- // Do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/CreateRefactoringScriptAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/CreateRefactoringScriptAction.java
deleted file mode 100644
index 910e0109..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/CreateRefactoringScriptAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-/**
- * Action to create a refactoring script from the refactoring history.
- *
- * TODO: remove once bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=131746 is fixed
- */
-public final class CreateRefactoringScriptAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window, or <code>null</code> */
- private IWorkbenchWindow fWindow= null;
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- // Do nothing
- }
-
- /**
- * {@inheritDoc}
- */
- public void init(final IWorkbenchWindow window) {
- fWindow= window;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(final IAction a) {
- if (fWindow != null) {
- org.eclipse.ltk.ui.refactoring.actions.CreateRefactoringScriptAction action= new org.eclipse.ltk.ui.refactoring.actions.CreateRefactoringScriptAction();
- action.init(fWindow);
- action.run(a);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final IAction action, final ISelection selection) {
- // Do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineConstantAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineConstantAction.java
deleted file mode 100644
index 2f66db6e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineConstantAction.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-/**
- * Inlines a constant.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- */
-public class InlineConstantAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the java editor
- */
- public InlineConstantAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- public InlineConstantAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.InlineConstantAction_inline_Constant);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
- }
-
- //---- structured selection ---------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isInlineConstantAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no ui
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- Assert.isTrue(RefactoringAvailabilityTester.isInlineConstantAvailable(selection));
-
- Object first= selection.getFirstElement();
- Assert.isTrue(first instanceof IField);
-
- IField field= (IField) first;
- run(field.getNameRange().getOffset(), field.getNameRange().getLength(), field.getJavaScriptUnit());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.InlineConstantAction_dialog_title, RefactoringMessages.InlineConstantAction_unexpected_exception);
- }
- }
-
- //---- text selection -----------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isInlineConstantAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- run(selection.getOffset(), selection.getLength(), SelectionConverter.getInputAsCompilationUnit(fEditor));
- }
-
- private void run(int offset, int length, IJavaScriptUnit cu) {
- Assert.isNotNull(cu);
- Assert.isTrue(offset >= 0);
- Assert.isTrue(length >= 0);
- if (!ActionUtil.isEditable(fEditor, getShell(), cu))
- return;
- try {
- JavaScriptUnit node= RefactoringASTParser.parseWithASTProvider(cu, true, null);
- if (! RefactoringExecutionStarter.startInlineConstantRefactoring(cu, node, offset, length, getShell())) {
- MessageDialog.openInformation(getShell(), RefactoringMessages.InlineConstantAction_dialog_title, RefactoringMessages.InlineConstantAction_no_constant_reference_or_declaration);
- }
-
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.InlineConstantAction_dialog_title, RefactoringMessages.InlineConstantAction_unexpected_exception);
- }
- }
-
- public boolean tryInlineConstant(IJavaScriptUnit unit, JavaScriptUnit node, ITextSelection selection, Shell shell) {
- try {
- if (RefactoringExecutionStarter.startInlineConstantRefactoring(unit, node, selection.getOffset(), selection.getLength(), shell)) {
- return true;
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.InlineConstantAction_dialog_title, RefactoringMessages.InlineConstantAction_unexpected_exception);
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineMethodAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineMethodAction.java
deleted file mode 100644
index b65f2285..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/InlineMethodAction.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-/**
- * Inlines a method.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- */
-public class InlineMethodAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the java editor
- */
- public InlineMethodAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- public InlineMethodAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.InlineMethodAction_inline_Method);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
- }
-
- //---- structured selection ----------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isInlineMethodAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- Assert.isTrue(RefactoringAvailabilityTester.isInlineMethodAvailable(selection));
- IFunction method= (IFunction) selection.getFirstElement();
- ISourceRange nameRange= method.getNameRange();
- run(nameRange.getOffset(), nameRange.getLength(), method.getTypeRoot());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.InlineMethodAction_dialog_title, RefactoringMessages.InlineMethodAction_unexpected_exception);
- }
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isInlineMethodAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- ITypeRoot typeRoot= SelectionConverter.getInputAsTypeRoot(fEditor);
- if (typeRoot == null)
- return;
- if (! JavaElementUtil.isSourceAvailable(typeRoot))
- return;
- run(selection.getOffset(), selection.getLength(), typeRoot);
- }
-
- private void run(int offset, int length, ITypeRoot typeRoot) {
- if (!ActionUtil.isEditable(fEditor, getShell(), typeRoot))
- return;
- try {
- JavaScriptUnit compilationUnit= RefactoringASTParser.parseWithASTProvider(typeRoot, true, null);
- if (! RefactoringExecutionStarter.startInlineMethodRefactoring(typeRoot, compilationUnit, offset, length, getShell())) {
- MessageDialog.openInformation(getShell(), RefactoringMessages.InlineMethodAction_dialog_title, RefactoringMessages.InlineMethodAction_no_method_invocation_or_declaration_selected);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.InlineMethodAction_dialog_title, RefactoringMessages.InlineMethodAction_unexpected_exception);
- }
- }
-
- public boolean tryInlineMethod(ITypeRoot typeRoot, JavaScriptUnit node, ITextSelection selection, Shell shell) {
- try {
- if (RefactoringExecutionStarter.startInlineMethodRefactoring(typeRoot, node, selection.getOffset(), selection.getLength(), shell)) {
- return true;
- }
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ListDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ListDialog.java
deleted file mode 100644
index 3756ef59..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ListDialog.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.dialogs.SelectionDialog;
-
-public class ListDialog extends SelectionDialog {
-
- private IStructuredContentProvider fContentProvider;
- private ILabelProvider fLabelProvider;
- private Object fInput;
- private TableViewer fTableViewer;
- private boolean fAddCancelButton;
-
- public ListDialog(Shell parent) {
- super(parent);
- fAddCancelButton= false;
- }
-
- public void setInput(Object input) {
- fInput= input;
- }
-
- public void setContentProvider(IStructuredContentProvider sp){
- fContentProvider= sp;
- }
-
- public void setLabelProvider(ILabelProvider lp){
- fLabelProvider= lp;
- }
-
- public void setAddCancelButton(boolean addCancelButton) {
- fAddCancelButton= addCancelButton;
- }
-
- public TableViewer getTableViewer(){
- return fTableViewer;
- }
-
- public boolean hasFilters(){
- return fTableViewer.getFilters() != null && fTableViewer.getFilters().length != 0;
- }
-
- public void create() {
- setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE);
- super.create();
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- if (! fAddCancelButton)
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- else
- super.createButtonsForButtonBar(parent);
- }
-
- protected Control createDialogArea(Composite container) {
- Composite parent= (Composite) super.createDialogArea(container);
- createMessageArea(parent);
- fTableViewer= new TableViewer(parent, getTableStyle());
- fTableViewer.setContentProvider(fContentProvider);
- Table table= fTableViewer.getTable();
- fTableViewer.setLabelProvider(fLabelProvider);
- fTableViewer.setInput(fInput);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= convertHeightInCharsToPixels(15);
- gd.widthHint= convertWidthInCharsToPixels(55);
- table.setLayoutData(gd);
- applyDialogFont(parent);
- return parent;
- }
-
- protected int getTableStyle() {
- return SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveInstanceMethodAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveInstanceMethodAction.java
deleted file mode 100644
index 56a16808..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveInstanceMethodAction.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public final class MoveInstanceMethodAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the java editor
- */
- public MoveInstanceMethodAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- public MoveInstanceMethodAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.MoveInstanceMethodAction_Move_Method);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_ACTION);
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveMethodAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no ui
- }
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveMethodAvailable(selection));
- } catch (CoreException e) {
- setEnabled(false);
- }
- }
-
- private static IFunction getSingleSelectedMethod(IStructuredSelection selection) {
- if (selection.isEmpty() || selection.size() != 1)
- return null;
-
- Object first= selection.getFirstElement();
- if (! (first instanceof IFunction))
- return null;
- return (IFunction) first;
- }
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- Assert.isTrue(RefactoringAvailabilityTester.isMoveMethodAvailable(selection));
- IFunction method= getSingleSelectedMethod(selection);
- Assert.isNotNull(method);
- if (!ActionUtil.isEditable(fEditor, getShell(), method))
- return;
- RefactoringExecutionStarter.startMoveMethodRefactoring(method, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.MoveInstanceMethodAction_dialog_title, RefactoringMessages.MoveInstanceMethodAction_unexpected_exception);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- run(selection, SelectionConverter.getInputAsCompilationUnit(fEditor));
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.MoveInstanceMethodAction_dialog_title, RefactoringMessages.MoveInstanceMethodAction_unexpected_exception);
- }
- }
-
- private void run(ITextSelection selection, IJavaScriptUnit cu) throws JavaScriptModelException {
- Assert.isNotNull(cu);
- Assert.isTrue(selection.getOffset() >= 0);
- Assert.isTrue(selection.getLength() >= 0);
-
- if (!ActionUtil.isEditable(fEditor, getShell(), cu))
- return;
-
- IFunction method= getMethod(cu, selection);
- if (method != null) {
- RefactoringExecutionStarter.startMoveMethodRefactoring(method, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.MoveInstanceMethodAction_dialog_title, RefactoringMessages.MoveInstanceMethodAction_No_reference_or_declaration);
- }
- }
-
- private static IFunction getMethod(IJavaScriptUnit cu, ITextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(cu, selection);
- if (element instanceof IFunction)
- return (IFunction) element;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveStaticMembersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveStaticMembersAction.java
deleted file mode 100644
index e53a6197..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/MoveStaticMembersAction.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class MoveStaticMembersAction extends SelectionDispatchAction{
-
- private JavaEditor fEditor;
-
- public MoveStaticMembersAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.RefactoringGroup_move_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_ACTION);
- }
-
- public MoveStaticMembersAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveStaticMembersAvailable(getSelectedMembers(selection)));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no ui
- }
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveStaticAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- public void run(IStructuredSelection selection) {
- try {
- IMember[] members= getSelectedMembers(selection);
- for (int index= 0; index < members.length; index++) {
- if (!ActionUtil.isEditable(getShell(), members[index]))
- return;
- }
- if (RefactoringAvailabilityTester.isMoveStaticMembersAvailable(members))
- RefactoringExecutionStarter.startMoveStaticMembersRefactoring(members, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- public void run(ITextSelection selection) {
- try {
- IMember member= getSelectedMemberFromEditor();
- if (!ActionUtil.isEditable(fEditor, getShell(), member))
- return;
- IMember[] array= new IMember[]{member};
- if (member != null && RefactoringAvailabilityTester.isMoveStaticMembersAvailable(array)){
- RefactoringExecutionStarter.startMoveStaticMembersRefactoring(array, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.MoveMembersAction_unavailable);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- private static IMember[] getSelectedMembers(IStructuredSelection selection){
- if (selection.isEmpty())
- return null;
-
- for (final Iterator iterator= selection.iterator(); iterator.hasNext(); ) {
- if (! (iterator.next() instanceof IMember))
- return null;
- }
- Set memberSet= new HashSet();
- memberSet.addAll(Arrays.asList(selection.toArray()));
- return (IMember[]) memberSet.toArray(new IMember[memberSet.size()]);
- }
-
- private IMember getSelectedMemberFromEditor() throws JavaScriptModelException{
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element == null || ! (element instanceof IMember))
- return null;
- return (IMember)element;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringActions.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringActions.java
deleted file mode 100644
index 01bfd832..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringActions.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-
-/**
- * Helper class for refactoring actions
- */
-public class RefactoringActions {
-
- /**
- * Converts the given selection into a type using the following rules:
- * <ul>
- * <li>if the selection is enclosed by a type than that type is returned.</li>
- * <li>if the selection is inside a compilation unit or class file than the
- * primary type is returned.</li>
- * <li>otherwise <code>null</code> is returned.
- * </ul>
- */
- public static IType getEnclosingOrPrimaryType(JavaTextSelection selection) throws JavaScriptModelException {
- final IJavaScriptElement element= selection.resolveEnclosingElement();
- if (element != null)
- return convertToEnclosingOrPrimaryType(element);
- return null;
- }
- public static IType getEnclosingOrPrimaryType(JavaEditor editor) throws JavaScriptModelException {
- return convertToEnclosingOrPrimaryType(SelectionConverter.resolveEnclosingElement(
- editor, (ITextSelection)editor.getSelectionProvider().getSelection()));
- }
-
- private static IType convertToEnclosingOrPrimaryType(IJavaScriptElement element) throws JavaScriptModelException {
- if (element instanceof IType)
- return (IType)element;
- IType result= (IType)element.getAncestor(IJavaScriptElement.TYPE);
- if (result != null)
- return result;
- if (element instanceof IJavaScriptUnit)
- return ((IJavaScriptUnit)element).findPrimaryType();
- if (element instanceof IClassFile)
- return ((IClassFile)element).getType();
- return null;
- }
-
- /**
- * Converts the given selection into a type using the following rules:
- * <ul>
- * <li>if the selection is enclosed by a type than that type is returned.</li>
- * <li>otherwise <code>null</code> is returned.
- * </ul>
- */
- public static IType getEnclosingType(JavaTextSelection selection) throws JavaScriptModelException {
- return convertToEnclosingType(selection.resolveEnclosingElement());
- }
- public static IType getEnclosingType(JavaEditor editor) throws JavaScriptModelException {
- return convertToEnclosingType(SelectionConverter.resolveEnclosingElement(
- editor, (ITextSelection)editor.getSelectionProvider().getSelection()));
- }
-
- private static IType convertToEnclosingType(IJavaScriptElement element) {
- if (element == null)
- return null;
- if (! (element instanceof IType))
- element= element.getAncestor(IJavaScriptElement.TYPE);
- return (IType)element;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringStarter.java
deleted file mode 100644
index 4e7cae34..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RefactoringStarter.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-/**
- * A helper class to activate the UI of a refactoring
- */
-public class RefactoringStarter {
-
- private RefactoringStatus fStatus;
-
- /**
- * @param refactoring
- * @param wizard
- * @param parent
- * @param dialogTitle
- * @param saveMode a save mode from {@link RefactoringSaveHelper}
- * @return <code>true</code> if the refactoring was executed, <code>false</code> otherwise
- * @throws JavaScriptModelException
- */
- public boolean activate(Refactoring refactoring, RefactoringWizard wizard, Shell parent, String dialogTitle, int saveMode) throws JavaScriptModelException {
- RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(saveMode);
- if (! canActivate(saveHelper, parent))
- return false;
-
- try {
- RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(wizard);
- int result= op.run(parent, dialogTitle);
- fStatus= op.getInitialConditionCheckingStatus();
- if (result == IDialogConstants.CANCEL_ID || result == RefactoringWizardOpenOperation.INITIAL_CONDITION_CHECKING_FAILED) {
- saveHelper.triggerBuild();
- return false;
- } else {
- return true;
- }
- } catch (InterruptedException e) {
- return false; // User action got cancelled
- }
- }
-
- public RefactoringStatus getInitialConditionCheckingStatus() {
- return fStatus;
- }
-
- private boolean canActivate(RefactoringSaveHelper saveHelper, Shell shell) {
- return saveHelper.saveEditors(shell);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameJavaElementAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameJavaElementAction.java
deleted file mode 100644
index ef9262dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameJavaElementAction.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameLinkedMode;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class RenameJavaElementAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- public RenameJavaElementAction(IWorkbenchSite site) {
- super(site);
- }
-
- public RenameJavaElementAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- //---- Structured selection ------------------------------------------------
-
- public void selectionChanged(IStructuredSelection selection) {
- try {
- if (selection.size() == 1) {
- setEnabled(canEnable(selection));
- return;
- }
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- setEnabled(false);
- }
-
- private static boolean canEnable(IStructuredSelection selection) throws CoreException {
- IJavaScriptElement element= getJavaElement(selection);
- if (element == null)
- return false;
- return isRenameAvailable(element);
- }
-
- private static IJavaScriptElement getJavaElement(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object first= selection.getFirstElement();
- if (! (first instanceof IJavaScriptElement))
- return null;
- return (IJavaScriptElement)first;
- }
-
- public void run(IStructuredSelection selection) {
- IJavaScriptElement element= getJavaElement(selection);
- if (element == null)
- return;
- try {
- run(element, false);
- } catch (CoreException e){
- ExceptionHandler.handle(e, RefactoringMessages.RenameJavaElementAction_name, RefactoringMessages.RenameJavaElementAction_exception);
- }
- }
-
- //---- text selection ------------------------------------------------------------
-
- public void selectionChanged(ITextSelection selection) {
- if (selection instanceof JavaTextSelection) {
- try {
- IJavaScriptElement[] elements= ((JavaTextSelection)selection).resolveElementAtOffset();
- if (elements.length == 1) {
- setEnabled(isRenameAvailable(elements[0]));
- } else {
- setEnabled(false);
- }
- } catch (CoreException e) {
- setEnabled(false);
- }
- } else {
- setEnabled(true);
- }
- }
-
- public void run(ITextSelection selection) {
- RenameLinkedMode activeLinkedMode= RenameLinkedMode.getActiveLinkedMode();
- if (activeLinkedMode != null) {
- if (activeLinkedMode.isCaretInLinkedPosition()) {
- activeLinkedMode.startFullDialog();
- return;
- } else {
- activeLinkedMode.cancel();
- }
- }
-
- try {
- IJavaScriptElement element= getJavaElementFromEditor();
- if (element != null && isRenameAvailable(element)) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- run(element, store.getBoolean(PreferenceConstants.REFACTOR_LIGHTWEIGHT));
- return;
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.RenameJavaElementAction_name, RefactoringMessages.RenameJavaElementAction_exception);
- }
- MessageDialog.openInformation(getShell(), RefactoringMessages.RenameJavaElementAction_name, RefactoringMessages.RenameJavaElementAction_not_available);
- }
-
- public boolean canRunInEditor() {
- if (RenameLinkedMode.getActiveLinkedMode() != null)
- return true;
-
- try {
- IJavaScriptElement element= getJavaElementFromEditor();
- if (element == null)
- return false;
-
- return isRenameAvailable(element);
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-
- private IJavaScriptElement getJavaElementFromEditor() throws JavaScriptModelException {
- IJavaScriptElement[] elements= SelectionConverter.codeResolve(fEditor);
- if (elements == null || elements.length != 1)
- return null;
- return elements[0];
- }
-
- //---- helper methods -------------------------------------------------------------------
-
- private void run(IJavaScriptElement element, boolean lightweight) throws CoreException {
- // Work around for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
- if (! ActionUtil.isEditable(fEditor, getShell(), element))
- return;
- //XXX workaround bug 31998
- if (ActionUtil.mustDisableJavaModelAction(getShell(), element))
- return;
-
- if (lightweight && fEditor instanceof CompilationUnitEditor && ! (element instanceof IPackageFragment)) {
- new RenameLinkedMode(element, (CompilationUnitEditor) fEditor).start();
- } else {
- RefactoringExecutionStarter.startRenameRefactoring(element, getShell());
- }
- }
-
- private static boolean isRenameAvailable(IJavaScriptElement element) throws CoreException {
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return RefactoringAvailabilityTester.isRenameAvailable((IJavaScriptProject) element);
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return RefactoringAvailabilityTester.isRenameAvailable((IPackageFragmentRoot) element);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return RefactoringAvailabilityTester.isRenameAvailable((IPackageFragment) element);
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return RefactoringAvailabilityTester.isRenameAvailable((IJavaScriptUnit) element);
- case IJavaScriptElement.TYPE:
- return RefactoringAvailabilityTester.isRenameAvailable((IType) element);
- case IJavaScriptElement.METHOD:
- final IFunction method= (IFunction) element;
- if (method.isConstructor())
- return RefactoringAvailabilityTester.isRenameAvailable(method.getDeclaringType());
- else
- return RefactoringAvailabilityTester.isRenameAvailable(method);
- case IJavaScriptElement.FIELD:
- final IField field= (IField) element;
- return RefactoringAvailabilityTester.isRenameFieldAvailable(field);
- case IJavaScriptElement.LOCAL_VARIABLE:
- return RefactoringAvailabilityTester.isRenameAvailable((ILocalVariable) element);
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameResourceAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameResourceAction.java
deleted file mode 100644
index 1402689b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/RenameResourceAction.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class RenameResourceAction extends SelectionDispatchAction {
-
- public RenameResourceAction(IWorkbenchSite site) {
- super(site);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- IResource element= getResource(selection);
- if (element == null)
- setEnabled(false);
- else
- setEnabled(RefactoringAvailabilityTester.isRenameAvailable(element));
- }
-
- public void run(IStructuredSelection selection) {
- IResource resource = getResource(selection);
- if (!RefactoringAvailabilityTester.isRenameAvailable(resource))
- return;
- try {
- RefactoringExecutionStarter.startRenameResourceRefactoring(resource, getShell());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.RenameJavaElementAction_name, RefactoringMessages.RenameJavaElementAction_exception);
- }
- }
-
- private static IResource getResource(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object first= selection.getFirstElement();
- if (! (first instanceof IResource))
- return null;
- return (IResource)first;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ShowRefactoringHistoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ShowRefactoringHistoryAction.java
deleted file mode 100644
index 05a91524..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/actions/ShowRefactoringHistoryAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-/**
- * Action to show the global refactoring history.
- *
- * TODO: remove once bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=131746 is fixed
- */
-public final class ShowRefactoringHistoryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window, or <code>null</code> */
- private IWorkbenchWindow fWindow= null;
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- // Do nothing
- }
-
- /**
- * {@inheritDoc}
- */
- public void init(final IWorkbenchWindow window) {
- fWindow= window;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(final IAction a) {
- if (fWindow != null) {
- org.eclipse.ltk.ui.refactoring.actions.ShowRefactoringHistoryAction action= new org.eclipse.ltk.ui.refactoring.actions.ShowRefactoringHistoryAction();
- action.init(fWindow);
- action.run(a);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final IAction action, final ISelection selection) {
- // Do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/binary/BinaryRefactoringHistoryWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/binary/BinaryRefactoringHistoryWizard.java
deleted file mode 100644
index 8328888f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/binary/BinaryRefactoringHistoryWizard.java
+++ /dev/null
@@ -1,731 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.binary;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.jar.JarFile;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
-import org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryWizard;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.JavaScriptRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringContribution;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.JavaRefactoringArguments;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.binary.SourceCreationOperation;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.binary.StubCreationOperation;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IScriptableRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-
-/**
- * Partial implementation of a refactoring history wizard which creates stubs
- * from a binary package fragment root while refactoring.
- *
- *
- */
-public abstract class BinaryRefactoringHistoryWizard extends RefactoringHistoryWizard {
-
- /** The meta-inf fragment */
- private static final String META_INF_FRAGMENT= JarFile.MANIFEST_NAME.substring(0, JarFile.MANIFEST_NAME.indexOf('/'));
-
- /** The temporary linked source folder */
- private static final String SOURCE_FOLDER= ".src"; //$NON-NLS-1$
-
- /** The temporary stubs folder */
- private static final String STUB_FOLDER= ".stubs"; //$NON-NLS-1$
-
- /**
- * Updates the new classpath with exclusion patterns for the specified path.
- *
- * @param entries
- * the classpath entries
- * @param path
- * the path
- */
- private static void addExclusionPatterns(final List entries, final IPath path) {
- for (int index= 0; index < entries.size(); index++) {
- final IIncludePathEntry entry= (IIncludePathEntry) entries.get(index);
- if (entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE && entry.getPath().isPrefixOf(path)) {
- final IPath[] patterns= entry.getExclusionPatterns();
- if (!JavaModelUtil.isExcludedPath(path, patterns)) {
- final IPath[] filters= new IPath[patterns.length + 1];
- System.arraycopy(patterns, 0, filters, 0, patterns.length);
- filters[patterns.length]= path.removeFirstSegments(entry.getPath().segmentCount()).addTrailingSeparator();
- entries.set(index, JavaScriptCore.newSourceEntry(entry.getPath(), filters, null));
- }
- }
- }
- }
-
- /**
- * Checks whether the archive referenced by the package fragment root is not
- * shared with multiple java projects in the workspace.
- *
- * @param root
- * the package fragment root
- * @param monitor
- * the progress monitor to use
- * @return the status of the operation
- */
- private static RefactoringStatus checkPackageFragmentRoots(final IPackageFragmentRoot root, final IProgressMonitor monitor) {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 100);
- final IWorkspaceRoot workspace= ResourcesPlugin.getWorkspace().getRoot();
- if (workspace != null) {
- final IJavaScriptModel model= JavaScriptCore.create(workspace);
- if (model != null) {
- try {
- final URI uri= getLocationURI(root.getRawIncludepathEntry());
- if (uri != null) {
- final IJavaScriptProject[] projects= model.getJavaScriptProjects();
- final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- try {
- subMonitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, projects.length * 100);
- for (int index= 0; index < projects.length; index++) {
- final IPackageFragmentRoot[] roots= projects[index].getPackageFragmentRoots();
- final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- try {
- subsubMonitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, roots.length);
- for (int offset= 0; offset < roots.length; offset++) {
- final IPackageFragmentRoot current= roots[offset];
- if (!current.equals(root) && current.getKind() == IPackageFragmentRoot.K_BINARY) {
- final IIncludePathEntry entry= current.getRawIncludepathEntry();
- if (entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY) {
- final URI location= getLocationURI(entry);
- if (uri.equals(location))
- status.addFatalError(Messages.format(RefactoringMessages.JarImportWizard_error_shared_jar, new String[] { current.getJavaScriptProject().getElementName() }));
- }
- }
- subsubMonitor.worked(1);
- }
- } finally {
- subsubMonitor.done();
- }
- }
- } finally {
- subMonitor.done();
- }
- }
- } catch (CoreException exception) {
- status.addError(exception.getLocalizedMessage());
- }
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Configures the classpath of the project before refactoring.
- *
- * @param project
- * the java project
- * @param root
- * the package fragment root to refactor
- * @param folder
- * the temporary source folder
- * @param monitor
- * the progress monitor to use
- * @throws IllegalStateException
- * if the plugin state location does not exist
- * @throws CoreException
- * if an error occurs while configuring the class path
- */
- private static void configureClasspath(final IJavaScriptProject project, final IPackageFragmentRoot root, final IFolder folder, final IProgressMonitor monitor) throws IllegalStateException, CoreException {
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 200);
- final IIncludePathEntry entry= root.getRawIncludepathEntry();
- final IIncludePathEntry[] entries= project.getRawIncludepath();
- final List list= new ArrayList();
- list.addAll(Arrays.asList(entries));
- final IFileStore store= EFS.getLocalFileSystem().getStore(JavaScriptPlugin.getDefault().getStateLocation().append(STUB_FOLDER).append(project.getElementName()));
- if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
- store.delete(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- store.mkdir(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- folder.createLink(store.toURI(), IResource.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- addExclusionPatterns(list, folder.getFullPath());
- for (int index= 0; index < entries.length; index++) {
- if (entries[index].equals(entry))
- list.add(index, JavaScriptCore.newSourceEntry(folder.getFullPath()));
- }
- project.setRawIncludepath((IIncludePathEntry[]) list.toArray(new IIncludePathEntry[list.size()]), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Returns the location URI of the classpath entry
- *
- * @param entry
- * the classpath entry
- * @return the location URI
- */
- public static URI getLocationURI(final IIncludePathEntry entry) {
- IPath path= null;
- if (entry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE)
- path= JavaScriptCore.getResolvedVariablePath(entry.getPath());
- else
- path= entry.getPath();
- final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- URI location= null;
- if (root.exists(path)) {
- location= root.getFile(path).getRawLocationURI();
- } else
- location= URIUtil.toURI(path);
- return location;
- }
-
- /** Is auto build enabled? */
- protected boolean fAutoBuild= true;
-
- /** Has the wizard been cancelled? */
- protected boolean fCancelled= false;
-
- /** The current refactoring arguments, or <code>null</code> */
- protected RefactoringArguments fCurrentArguments= null;
-
- /** The current refactoring to be initialized, or <code>null</code> */
- protected IScriptableRefactoring fCurrentRefactoring= null;
-
- /** The java project or <code>null</code> */
- protected IJavaScriptProject fJavaProject= null;
-
- /**
- * The packages which already have been processed (element type:
- * &lt;IPackageFragment&gt;)
- */
- protected final Collection fProcessedFragments= new HashSet();
-
- /** The temporary source folder, or <code>null</code> */
- protected IFolder fSourceFolder= null;
-
- /**
- * Creates a new stub refactoring history wizard.
- *
- * @param overview
- * <code>true</code> to show an overview of the refactorings,
- * <code>false</code> otherwise
- * @param caption
- * the wizard caption
- * @param title
- * the wizard title
- * @param description
- * the wizard description
- */
- protected BinaryRefactoringHistoryWizard(final boolean overview, final String caption, final String title, final String description) {
- super(overview, caption, title, description);
- }
-
- /**
- * Creates a new stub refactoring history wizard.
- *
- * @param caption
- * the wizard caption
- * @param title
- * the wizard title
- * @param description
- * the wizard description
- */
- protected BinaryRefactoringHistoryWizard(final String caption, final String title, final String description) {
- super(caption, title, description);
- }
-
- /**
- * {@inheritDoc}
- */
- protected RefactoringStatus aboutToPerformHistory(final IProgressMonitor monitor) {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- fJavaProject= null;
- fSourceFolder= null;
- fProcessedFragments.clear();
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 520);
- status.merge(super.aboutToPerformHistory(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
- if (!status.hasFatalError()) {
- final IPackageFragmentRoot root= getPackageFragmentRoot();
- if (root != null) {
- status.merge(checkPackageFragmentRoots(root, new SubProgressMonitor(monitor, 90, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
- if (!status.hasFatalError()) {
- status.merge(checkSourceAttachmentRefactorings(new SubProgressMonitor(monitor, 20, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
- if (!status.hasFatalError()) {
- final IJavaScriptProject project= root.getJavaScriptProject();
- if (project != null) {
- final IFolder folder= project.getProject().getFolder(SOURCE_FOLDER + String.valueOf(System.currentTimeMillis()));
- try {
- fAutoBuild= CoreUtility.enableAutoBuild(false);
- final RefactoringHistory history= getRefactoringHistory();
- if (history != null && !history.isEmpty())
- configureClasspath(project, root, folder, new SubProgressMonitor(monitor, 300, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
- try {
- project.setRawIncludepath(project.readRawIncludepath(), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException throwable) {
- JavaScriptPlugin.log(throwable);
- }
- } finally {
- if (!status.hasFatalError()) {
- fJavaProject= project;
- fSourceFolder= folder;
- }
- }
- }
- }
- }
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- protected RefactoringStatus aboutToPerformRefactoring(final Refactoring refactoring, final RefactoringDescriptor descriptor, final IProgressMonitor monitor) {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 100);
- status.merge(createNecessarySourceCode(refactoring, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
- if (!status.hasFatalError()) {
- if (fCurrentRefactoring != null && fCurrentArguments != null)
- status.merge(fCurrentRefactoring.initialize(fCurrentArguments));
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Can this wizard use the source attachment of the package fragment root if
- * necessary?
- *
- * @return <code>true</code> to use the source attachment,
- * <code>false</code> otherwise
- */
- protected boolean canUseSourceAttachment() {
- final IPackageFragmentRoot root= getPackageFragmentRoot();
- if (root != null) {
- try {
- return root.getSourceAttachmentPath() != null;
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- return false;
- }
-
- /**
- * Checks whether there are any refactorings to be executed which need a
- * source attachment, but none exists.
- *
- * @param monitor
- * the progress monitor
- * @return a status describing the outcome of the check
- */
- protected RefactoringStatus checkSourceAttachmentRefactorings(final IProgressMonitor monitor) {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- if (!canUseSourceAttachment()) {
- final RefactoringDescriptorProxy[] proxies= getRefactoringHistory().getDescriptors();
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, proxies.length * 100);
- for (int index= 0; index < proxies.length; index++) {
- final RefactoringDescriptor descriptor= proxies[index].requestDescriptor(new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- if (descriptor != null) {
- final int flags= descriptor.getFlags();
- if ((flags & JavaScriptRefactoringDescriptor.JAR_SOURCE_ATTACHMENT) != 0)
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringMessages.BinaryRefactoringHistoryWizard_error_missing_source_attachment, descriptor.getDescription())));
- }
- }
- } else
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 1);
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * Creates the necessary source code for the refactoring.
- *
- * @param refactoring
- * the refactoring to create the source code for
- * @param monitor
- * the progress monitor to use
- */
- private RefactoringStatus createNecessarySourceCode(final Refactoring refactoring, final IProgressMonitor monitor) {
- final RefactoringStatus status= new RefactoringStatus();
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, 240);
- final IPackageFragmentRoot root= getPackageFragmentRoot();
- if (root != null && fSourceFolder != null && fJavaProject != null) {
- try {
- final SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 40, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
- final IJavaScriptElement[] elements= root.getChildren();
- final List list= new ArrayList(elements.length);
- try {
- subMonitor.beginTask(RefactoringMessages.JarImportWizard_prepare_import, elements.length);
- for (int index= 0; index < elements.length; index++) {
- final IJavaScriptElement element= elements[index];
- if (!fProcessedFragments.contains(element) && !element.getElementName().equals(META_INF_FRAGMENT))
- list.add(element);
- subMonitor.worked(1);
- }
- } finally {
- subMonitor.done();
- }
- if (!list.isEmpty()) {
- fProcessedFragments.addAll(list);
- final URI uri= fSourceFolder.getRawLocationURI();
- if (uri != null) {
- final IPackageFragmentRoot sourceFolder= fJavaProject.getPackageFragmentRoot(fSourceFolder);
- IWorkspaceRunnable runnable= null;
- if (canUseSourceAttachment()) {
- runnable= new SourceCreationOperation(uri, list) {
-
- private IPackageFragment fFragment= null;
-
- protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
- fFragment.createCompilationUnit(name, content, true, pm);
- }
-
- protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
- fFragment= sourceFolder.createPackageFragment(name, true, pm);
- }
- };
- } else {
- runnable= new StubCreationOperation(uri, list, true) {
-
- private IPackageFragment fFragment= null;
-
- protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
- fFragment.createCompilationUnit(name, content, true, pm);
- }
-
- protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
- fFragment= sourceFolder.createPackageFragment(name, true, pm);
- }
- };
- }
- try {
- runnable.run(new SubProgressMonitor(monitor, 150, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } finally {
- fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 50, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- }
- }
- }
- } catch (CoreException exception) {
- status.addFatalError(exception.getLocalizedMessage());
- }
- }
- } finally {
- monitor.done();
- }
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- protected Refactoring createRefactoring(final RefactoringDescriptor descriptor, final RefactoringStatus status) throws CoreException {
- Assert.isNotNull(descriptor);
- Refactoring refactoring= null;
- if (descriptor instanceof JDTRefactoringDescriptor) {
- final JDTRefactoringDescriptor javaDescriptor= (JDTRefactoringDescriptor) descriptor;
- final RefactoringContribution contribution= RefactoringCore.getRefactoringContribution(javaDescriptor.getID());
- if (contribution instanceof JDTRefactoringContribution) {
- final JDTRefactoringContribution extended= (JDTRefactoringContribution) contribution;
- refactoring= extended.createRefactoring(descriptor);
- }
- if (refactoring != null) {
- final RefactoringArguments arguments= javaDescriptor.createArguments();
- if (arguments instanceof JavaRefactoringArguments) {
- final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments;
- if (fJavaProject != null) {
- final String name= fJavaProject.getElementName();
- extended.setProject(name);
- String handle= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT);
- if (handle != null && !"".equals(handle)) //$NON-NLS-1$
- extended.setAttribute(JDTRefactoringDescriptor.ATTRIBUTE_INPUT, getTransformedHandle(name, handle));
- int count= 1;
- String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- while ((handle= extended.getAttribute(attribute)) != null) {
- if (!"".equals(handle)) //$NON-NLS-1$
- extended.setAttribute(attribute, getTransformedHandle(name, handle));
- count++;
- attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + count;
- }
- }
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
- if (refactoring instanceof IScriptableRefactoring) {
- fCurrentRefactoring= (IScriptableRefactoring) refactoring;
- fCurrentArguments= arguments;
- } else
- status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_initialization_error, javaDescriptor.getID())));
- }
- return refactoring;
- }
- return null;
- }
-
- /**
- * Deconfigures the classpath after all refactoring have been performed.
- *
- * @param entries
- * the classpath entries to reset the project to
- * @param monitor
- * the progress monitor to use
- * @return <code>true</code> if the classpath has been changed,
- * <code>false</code> otherwise
- * @throws CoreException
- * if an error occurs while deconfiguring the classpath
- */
- protected boolean deconfigureClasspath(IIncludePathEntry[] entries, IProgressMonitor monitor) throws CoreException {
- return false;
- }
-
- /**
- * Deconfigures the classpath of the project after refactoring.
- *
- * @param monitor
- * the progress monitor to use
- * @throws CoreException
- * if an error occurs while deconfiguring the classpath
- */
- private void deconfigureClasspath(final IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_cleanup_import, 300);
- if (fJavaProject != null) {
- final IIncludePathEntry[] entries= fJavaProject.readRawIncludepath();
- final boolean changed= deconfigureClasspath(entries, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- final RefactoringHistory history= getRefactoringHistory();
- final boolean valid= history != null && !history.isEmpty();
- if (valid)
- RefactoringCore.getUndoManager().flush();
- if (valid || changed)
- fJavaProject.setRawIncludepath(entries, changed, new SubProgressMonitor(monitor, 60, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- }
- if (fSourceFolder != null) {
- final IFileStore store= EFS.getStore(fSourceFolder.getRawLocationURI());
- if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
- store.delete(EFS.NONE, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- fSourceFolder.delete(true, false, new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- fSourceFolder.clearHistory(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- fSourceFolder= null;
- }
- if (fJavaProject != null) {
- try {
- fJavaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- } finally {
- fJavaProject= null;
- monitor.done();
- }
- }
-
- /**
- * Returns the package fragment root to stub.
- *
- * @return the package fragment root to stub, or <code>null</code>
- */
- protected abstract IPackageFragmentRoot getPackageFragmentRoot();
-
- /**
- * Returns the refactoring history to perform.
- *
- * @return the refactoring history to perform, or the empty history
- */
- protected abstract RefactoringHistory getRefactoringHistory();
-
- /**
- * Returns the transformed handle corresponding to the specified input
- * handle.
- *
- * @param project
- * the project, or <code>null</code> for the workspace
- * @param handle
- * the handle to transform
- * @return the transformed handle, or the original one if nothing needed to
- * be transformed
- */
- private String getTransformedHandle(final String project, final String handle) {
- if (fSourceFolder != null) {
- final IJavaScriptElement target= JavaScriptCore.create(fSourceFolder);
- if (target instanceof IPackageFragmentRoot) {
- final IPackageFragmentRoot extended= (IPackageFragmentRoot) target;
- String sourceIdentifier= null;
- final IJavaScriptElement element= JDTRefactoringDescriptor.handleToElement(project, handle, false);
- if (element != null) {
- final IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null)
- sourceIdentifier= root.getHandleIdentifier();
- else {
- final IJavaScriptProject javaProject= element.getJavaScriptProject();
- if (javaProject != null)
- sourceIdentifier= javaProject.getHandleIdentifier();
- }
- if (sourceIdentifier != null) {
- final IJavaScriptElement result= JavaScriptCore.create(extended.getHandleIdentifier() + element.getHandleIdentifier().substring(sourceIdentifier.length()));
- if (result != null)
- return JDTRefactoringDescriptor.elementToHandle(project, result);
- }
- }
- }
- }
- return handle;
- }
-
- /**
- * {@inheritDoc}
- */
- protected RefactoringStatus historyPerformed(final IProgressMonitor monitor) {
- try {
- monitor.beginTask(RefactoringMessages.JarImportWizard_cleanup_import, 100);
- final RefactoringStatus status= super.historyPerformed(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- if (!status.hasFatalError()) {
- try {
- deconfigureClasspath(new SubProgressMonitor(monitor, 90, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- status.addError(exception.getLocalizedMessage());
- } finally {
- try {
- CoreUtility.enableAutoBuild(fAutoBuild);
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- return status;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean performCancel() {
- fCancelled= true;
- return super.performCancel();
- }
-
- /**
- * {@inheritDoc}
- */
- protected RefactoringStatus refactoringPerformed(final Refactoring refactoring, final IProgressMonitor monitor) {
- try {
- monitor.beginTask("", 120); //$NON-NLS-1$
- final RefactoringStatus status= super.refactoringPerformed(refactoring, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- if (!status.hasFatalError()) {
- if (fSourceFolder != null) {
- try {
- fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
- } catch (CoreException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- return status;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean selectPreviewChange(final Change change) {
- if (fSourceFolder != null) {
- final IPath source= fSourceFolder.getFullPath();
- final Object element= change.getModifiedElement();
- if (element instanceof IAdaptable) {
- final IAdaptable adaptable= (IAdaptable) element;
- final IResource resource= (IResource) adaptable.getAdapter(IResource.class);
- if (resource != null && source.isPrefixOf(resource.getFullPath()))
- return false;
- }
- }
- return super.selectPreviewChange(change);
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean selectStatusEntry(final RefactoringStatusEntry entry) {
- if (fSourceFolder != null) {
- final IPath source= fSourceFolder.getFullPath();
- final RefactoringStatusContext context= entry.getContext();
- if (context instanceof JavaStatusContext) {
- final JavaStatusContext extended= (JavaStatusContext) context;
- final IJavaScriptUnit unit= extended.getCompilationUnit();
- if (unit != null) {
- final IResource resource= unit.getResource();
- if (resource != null && source.isPrefixOf(resource.getFullPath()))
- return false;
- }
- }
- }
- return super.selectStatusEntry(entry);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
deleted file mode 100644
index 0423bf35..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
+++ /dev/null
@@ -1,407 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.ParameterInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ChangeParametersControl;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IParameterListChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-public class ExtractMethodInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "ExtractMethodInputPage";//$NON-NLS-1$
-
- private ExtractMethodRefactoring fRefactoring;
- private Text fTextField;
- private boolean fFirstTime;
- private JavaSourceViewer fSignaturePreview;
- private Document fSignaturePreviewDocument;
- private IDialogSettings fSettings;
-
- private static final String DESCRIPTION = RefactoringMessages.ExtractMethodInputPage_description;
- private static final String THROW_RUNTIME_EXCEPTIONS= "ThrowRuntimeExceptions"; //$NON-NLS-1$
- private static final String GENERATE_JAVADOC= "GenerateJavadoc"; //$NON-NLS-1$
-
- public ExtractMethodInputPage() {
- super(PAGE_NAME);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR_CU);
- setDescription(DESCRIPTION);
- fFirstTime= true;
- fSignaturePreviewDocument= new Document();
- }
-
- public void createControl(Composite parent) {
- fRefactoring= (ExtractMethodRefactoring)getRefactoring();
- loadSettings();
-
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- result.setLayout(layout);
- RowLayouter layouter= new RowLayouter(2);
- GridData gd= null;
-
- initializeDialogUnits(result);
-
- Label label= new Label(result, SWT.NONE);
- label.setText(getLabelText());
-
- fTextField= createTextInputField(result, SWT.BORDER);
- fTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- layouter.perform(label, fTextField, 1);
-
- ASTNode[] destinations= fRefactoring.getDestinations();
- if (destinations.length > 1) {
- label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.ExtractMethodInputPage_destination_type);
- final Combo combo= new Combo(result, SWT.READ_ONLY | SWT.DROP_DOWN);
- for (int i= 0; i < destinations.length; i++) {
- ASTNode declaration= destinations[i];
- combo.add(getLabel(declaration));
- }
- combo.select(0);
- combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- combo.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setDestination(combo.getSelectionIndex());
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- // nothing
- }
- });
- }
-
-// label= new Label(result, SWT.NONE);
-// label.setText(RefactoringMessages.ExtractMethodInputPage_access_Modifiers);
-//
-// Composite group= new Composite(result, SWT.NONE);
-// group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-// layout= new GridLayout();
-// layout.numColumns= 4; layout.marginWidth= 0;
-// group.setLayout(layout);
-//
-// String[] labels= new String[] {
-// RefactoringMessages.ExtractMethodInputPage_public,
-// RefactoringMessages.ExtractMethodInputPage_protected,
-// RefactoringMessages.ExtractMethodInputPage_default,
-// RefactoringMessages.ExtractMethodInputPage_private
-// };
-// Integer[] data= new Integer[] {new Integer(Modifier.PUBLIC), new Integer(Modifier.PROTECTED), new Integer(Modifier.NONE), new Integer(Modifier.PRIVATE)};
-// Integer visibility= new Integer(fRefactoring.getVisibility());
-// for (int i= 0; i < labels.length; i++) {
-// Button radio= new Button(group, SWT.RADIO);
-// radio.setText(labels[i]);
-// radio.setData(data[i]);
-// if (data[i].equals(visibility))
-// radio.setSelection(true);
-// radio.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent event) {
-// setVisibility((Integer)event.widget.getData());
-// }
-// });
-// }
-// layouter.perform(label, group, 1);
-
- if (!fRefactoring.getParameterInfos().isEmpty()) {
- ChangeParametersControl cp= new ChangeParametersControl(result, SWT.NONE,
- RefactoringMessages.ExtractMethodInputPage_parameters,
- new IParameterListChangeListener() {
- public void parameterChanged(ParameterInfo parameter) {
- parameterModified();
- }
- public void parameterListChanged() {
- parameterModified();
- }
- public void parameterAdded(ParameterInfo parameter) {
- updatePreview(getText());
- }
- }, ChangeParametersControl.Mode.EXTRACT_METHOD);
- gd= new GridData(GridData.FILL_BOTH);
- gd.horizontalSpan= 2;
- cp.setLayoutData(gd);
- cp.setInput(fRefactoring.getParameterInfos());
- }
-
-// Button checkBox= new Button(result, SWT.CHECK);
-// checkBox.setText(RefactoringMessages.ExtractMethodInputPage_throwRuntimeExceptions);
-// checkBox.setSelection(fSettings.getBoolean(THROW_RUNTIME_EXCEPTIONS));
-// checkBox.addSelectionListener(new SelectionAdapter() {
-// public void widgetSelected(SelectionEvent e) {
-// setRethrowRuntimeException(((Button)e.widget).getSelection());
-// }
-// });
-// layouter.perform(checkBox);
-//
- Button checkBox= new Button(result, SWT.CHECK);
- checkBox.setText(RefactoringMessages.ExtractMethodInputPage_generateJavadocComment);
- boolean generate= computeGenerateJavadoc();
- setGenerateJavadoc(generate);
- checkBox.setSelection(generate);
- checkBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setGenerateJavadoc(((Button)e.widget).getSelection());
- }
- });
- layouter.perform(checkBox);
-
- int duplicates= fRefactoring.getNumberOfDuplicates();
- checkBox= new Button(result, SWT.CHECK);
- if (duplicates == 0) {
- checkBox.setText(RefactoringMessages.ExtractMethodInputPage_duplicates_none);
- } else if (duplicates == 1) {
- checkBox.setText(RefactoringMessages.ExtractMethodInputPage_duplicates_single);
- } else {
- checkBox.setText(Messages.format(
- RefactoringMessages.ExtractMethodInputPage_duplicates_multi,
- new Integer(duplicates)));
- }
- checkBox.setSelection(fRefactoring.getReplaceDuplicates());
- checkBox.setEnabled(duplicates > 0);
- checkBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setReplaceDuplicates(((Button)e.widget).getSelection());
- }
- });
- layouter.perform(checkBox);
-
- label= new Label(result, SWT.SEPARATOR | SWT.HORIZONTAL);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layouter.perform(label);
-
- createSignaturePreview(result, layouter);
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_METHOD_WIZARD_PAGE);
- }
-
- private String getLabel(ASTNode node) {
- if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration)node).getName().getIdentifier();
- } else if (node instanceof AnonymousClassDeclaration) {
- if (node.getLocationInParent() == ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY) {
- ClassInstanceCreation creation= (ClassInstanceCreation)node.getParent();
- return Messages.format(
- RefactoringMessages.ExtractMethodInputPage_anonymous_type_label,
- ASTNodes.asString(creation.getType()));
- }
- }
- return "UNKNOWN"; //$NON-NLS-1$
- }
-
- private Text createTextInputField(Composite parent, int style) {
- Text result= new Text(parent, style);
- result.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- textModified(getText());
- }
- });
- TextFieldNavigationHandler.install(result);
- return result;
- }
-
- private String getText() {
- if (fTextField == null)
- return null;
- return fTextField.getText();
- }
-
- private String getLabelText(){
- return RefactoringMessages.ExtractMethodInputPage_label_text;
- }
-
-// private void setVisibility(Integer visibility) {
-// fRefactoring.setVisibility(visibility.intValue());
-// updatePreview(getText());
-// }
-//
-// private void setRethrowRuntimeException(boolean value) {
-// fSettings.put(THROW_RUNTIME_EXCEPTIONS, value);
-// fRefactoring.setThrowRuntimeExceptions(value);
-// updatePreview(getText());
-// }
-
- private boolean computeGenerateJavadoc() {
- boolean result= fRefactoring.getGenerateJavadoc();
- if (result)
- return result;
- return fSettings.getBoolean(GENERATE_JAVADOC);
- }
-
- private void setGenerateJavadoc(boolean value) {
- fSettings.put(GENERATE_JAVADOC, value);
- fRefactoring.setGenerateJavadoc(value);
- }
-
- private void createSignaturePreview(Composite composite, RowLayouter layouter) {
- Label previewLabel= new Label(composite, SWT.NONE);
- previewLabel.setText(RefactoringMessages.ExtractMethodInputPage_signature_preview);
- layouter.perform(previewLabel);
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSignaturePreview= new JavaSourceViewer(composite, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP /*| SWT.BORDER*/, store);
- fSignaturePreview.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- fSignaturePreview.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- fSignaturePreview.getTextWidget().setBackground(composite.getBackground());
- fSignaturePreview.setDocument(fSignaturePreviewDocument);
- fSignaturePreview.setEditable(false);
-
- //Layouting problems with wrapped text: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=9866
- Control signaturePreviewControl= fSignaturePreview.getControl();
- PixelConverter pixelConverter= new PixelConverter(signaturePreviewControl);
- GridData gdata= new GridData(GridData.FILL_BOTH);
- gdata.widthHint= pixelConverter.convertWidthInCharsToPixels(50);
- gdata.heightHint= pixelConverter.convertHeightInCharsToPixels(2);
- signaturePreviewControl.setLayoutData(gdata);
- layouter.perform(signaturePreviewControl);
- }
-
- private void updatePreview(String text) {
- if (fSignaturePreview == null)
- return;
-
- if (text.length() == 0)
- text= "someMethodName"; //$NON-NLS-1$
-
- int top= fSignaturePreview.getTextWidget().getTopPixel();
- String signature;
- try {
- signature= fRefactoring.getSignature(text);
- } catch (IllegalArgumentException e) {
- signature= ""; //$NON-NLS-1$
- }
- fSignaturePreviewDocument.set(signature);
- fSignaturePreview.getTextWidget().setTopPixel(top);
- }
-
- private void loadSettings() {
- fSettings= getDialogSettings().getSection(ExtractMethodWizard.DIALOG_SETTING_SECTION);
- if (fSettings == null) {
- fSettings= getDialogSettings().addNewSection(ExtractMethodWizard.DIALOG_SETTING_SECTION);
- fSettings.put(THROW_RUNTIME_EXCEPTIONS, false);
- fSettings.put(GENERATE_JAVADOC, JavaPreferencesSettings.getCodeGenerationSettings(fRefactoring.getCompilationUnit().getJavaScriptProject()).createComments);
- }
- fRefactoring.setThrowRuntimeExceptions(fSettings.getBoolean(THROW_RUNTIME_EXCEPTIONS));
- }
-
- //---- Input validation ------------------------------------------------------
-
- public void setVisible(boolean visible) {
- if (visible) {
- if (fFirstTime) {
- fFirstTime= false;
- setPageComplete(false);
- updatePreview(getText());
- fTextField.setFocus();
- } else {
- setPageComplete(validatePage(true));
- }
- }
- super.setVisible(visible);
- }
-
- private void textModified(String text) {
- fRefactoring.setMethodName(text);
- RefactoringStatus status= validatePage(true);
- if (!status.hasFatalError()) {
- updatePreview(text);
- } else {
- fSignaturePreviewDocument.set(""); //$NON-NLS-1$
- }
- setPageComplete(status);
- }
-
- private void parameterModified() {
- updatePreview(getText());
- setPageComplete(validatePage(false));
- }
-
- private RefactoringStatus validatePage(boolean text) {
- RefactoringStatus result= new RefactoringStatus();
- if (text) {
- result.merge(validateMethodName());
- result.merge(validateParameters());
- } else {
- result.merge(validateParameters());
- result.merge(validateMethodName());
- }
- return result;
- }
-
- private RefactoringStatus validateMethodName() {
- RefactoringStatus result= new RefactoringStatus();
- String text= getText();
- if ("".equals(text)) { //$NON-NLS-1$
- result.addFatalError(RefactoringMessages.ExtractMethodInputPage_validation_emptyMethodName);
- return result;
- }
- result.merge(fRefactoring.checkMethodName());
- return result;
- }
-
- private RefactoringStatus validateParameters() {
- RefactoringStatus result= new RefactoringStatus();
- List parameters= fRefactoring.getParameterInfos();
- for (Iterator iter= parameters.iterator(); iter.hasNext();) {
- ParameterInfo info= (ParameterInfo) iter.next();
- if ("".equals(info.getNewName())) { //$NON-NLS-1$
- result.addFatalError(RefactoringMessages.ExtractMethodInputPage_validation_emptyParameterName);
- return result;
- }
- }
- result.merge(fRefactoring.checkParameterNames());
- result.merge(fRefactoring.checkVarargOrder());
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodWizard.java
deleted file mode 100644
index a0040094..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ExtractMethodWizard.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class ExtractMethodWizard extends RefactoringWizard {
-
- /* package */ static final String DIALOG_SETTING_SECTION= "ExtractMethodWizard"; //$NON-NLS-1$
-
- public ExtractMethodWizard(ExtractMethodRefactoring ref){
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- setDefaultPageTitle(RefactoringMessages.ExtractMethodWizard_extract_method);
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- }
-
- public Change createChange(){
- // creating the change is cheap. So we don't need to show progress.
- try {
- return getRefactoring().createChange(new NullProgressMonitor());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
- }
-
- protected void addUserInputPages(){
- addPage(new ExtractMethodInputPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodInputPage.java
deleted file mode 100644
index 9bae4687..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodInputPage.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class InlineMethodInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "InlineMethodInputPage";//$NON-NLS-1$
- private static final String DESCRIPTION = RefactoringMessages.InlineMethodInputPage_description;
-
- private InlineMethodRefactoring fRefactoring;
- private Group fInlineMode;
- private Button fRemove;
-
- public InlineMethodInputPage() {
- super(PAGE_NAME);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR_CU);
- setDescription(DESCRIPTION);
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- fRefactoring= (InlineMethodRefactoring)getRefactoring();
-
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- result.setLayout(layout);
- GridData gd= null;
-
- boolean all= fRefactoring.getInitialMode() == InlineMethodRefactoring.Mode.INLINE_ALL;
- fInlineMode= new Group(result, SWT.NONE);
- fInlineMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fInlineMode.setLayout(new GridLayout());
- fInlineMode.setText(RefactoringMessages.InlineMethodInputPage_inline);
-
- Button radio= new Button(fInlineMode, SWT.RADIO);
- radio.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- radio.setText(RefactoringMessages.InlineMethodInputPage_all_invocations);
- radio.setSelection(all);
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRemove.setEnabled(fRefactoring.canEnableDeleteSource());
- if (((Button)event.widget).getSelection())
- changeRefactoring(InlineMethodRefactoring.Mode.INLINE_ALL);
- }
- });
-
- fRemove= new Button(fInlineMode, SWT.CHECK);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent= convertWidthInCharsToPixels(3);
- fRemove.setLayoutData(gd);
- fRemove.setText(RefactoringMessages.InlineMethodInputPage_delete_declaration);
- fRemove.setEnabled(all && fRefactoring.canEnableDeleteSource());
- fRemove.setSelection(fRefactoring.canEnableDeleteSource());
- fRefactoring.setDeleteSource(fRefactoring.canEnableDeleteSource());
- fRemove.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setDeleteSource(((Button)e.widget).getSelection());
- }
- });
-
-
- radio= new Button(fInlineMode, SWT.RADIO);
- radio.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- radio.setText(RefactoringMessages.InlineMethodInputPage_only_selected);
- radio.setSelection(!all);
- if (all) {
- radio.setEnabled(false);
- }
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRemove.setEnabled(false);
- if (((Button)event.widget).getSelection())
- changeRefactoring(InlineMethodRefactoring.Mode.INLINE_SINGLE);
- }
- });
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.INLINE_METHOD_WIZARD_PAGE);
- }
-
- private void changeRefactoring(InlineMethodRefactoring.Mode mode) {
- RefactoringStatus status;
- try {
- status= fRefactoring.setCurrentMode(mode);
- } catch (JavaScriptModelException e) {
- status= RefactoringStatus.createFatalErrorStatus(e.getMessage());
- }
- setPageComplete(status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodWizard.java
deleted file mode 100644
index 83c21aeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/InlineMethodWizard.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class InlineMethodWizard extends RefactoringWizard {
-
- /* package */ static final String DIALOG_SETTING_SECTION= "InlineMethodWizard"; //$NON-NLS-1$
-
- public InlineMethodWizard(InlineMethodRefactoring ref){
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.InlineMethodWizard_page_title);
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- }
-
- protected void addUserInputPages(){
- addPage(new InlineMethodInputPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsInputPage.java
deleted file mode 100644
index f93e5bce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsInputPage.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ReplaceInvocationsRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-public class ReplaceInvocationsInputPage extends UserInputWizardPage {
-
- public static final String PAGE_NAME= "ReplaceInvocationsInputPage";//$NON-NLS-1$
-
- private ReplaceInvocationsRefactoring fRefactoring;
-
- private static final long LABEL_FLAGS= JavaScriptElementLabels.M_PRE_TYPE_PARAMETERS | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_EXCEPTIONS;
-
- public ReplaceInvocationsInputPage() {
- super(PAGE_NAME);
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- fRefactoring= (ReplaceInvocationsRefactoring) getRefactoring();
-
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- GridLayout layout= new GridLayout();
- result.setLayout(layout);
-
- createMethodSignature(result);
-
- Label separator= new Label(parent, SWT.NONE);
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, false, false);
- gridData.heightHint= 5;
- separator.setLayoutData(gridData);
-
- Label bodyLabel= new Label(result, SWT.NONE);
- bodyLabel.setText(RefactoringMessages.ReplaceInvocationsInputPage_replaceInvocationsBy);
-
- createBody(result);
-
- Button replaceAll= new Button(result, SWT.CHECK);
- replaceAll.setText(RefactoringMessages.ReplaceInvocationsInputPage_replaceAll);
- boolean canSingle= fRefactoring.canReplaceSingle();
-// replaceAll.setEnabled(canSingle);
- replaceAll.setEnabled(false); // does not work for now...
- replaceAll.setSelection(! canSingle);
- replaceAll.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- boolean all= ((Button) event.widget).getSelection();
- changeMode(all ? ReplaceInvocationsRefactoring.Mode.REPLACE_ALL : ReplaceInvocationsRefactoring.Mode.REPLACE_SINGLE);
- }
- });
-
- Dialog.applyDialogFont(result);
- }
-
- private void createMethodSignature(Composite parent) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- JavaSourceViewer signatureViewer= new JavaSourceViewer(parent, null, null, false, SWT.READ_ONLY | SWT.WRAP /*| SWT.BORDER*/, store);
- signatureViewer.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- signatureViewer.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- signatureViewer.getTextWidget().setBackground(parent.getBackground());
- String signatureLabel= JavaScriptElementLabels.getElementLabel(fRefactoring.getMethod(), LABEL_FLAGS);
- signatureViewer.setDocument(new Document(signatureLabel));
- signatureViewer.setEditable(false);
-
- Control signatureControl= signatureViewer.getControl();
- PixelConverter pixelConverter= new PixelConverter(signatureControl);
- GridData gdata= new GridData(GridData.FILL_HORIZONTAL);
- gdata.widthHint= pixelConverter.convertWidthInCharsToPixels(50);
- signatureControl.setLayoutData(gdata);
- }
-
- private void createBody(Composite parent) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- JavaSourceViewer bodyEditor= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.WRAP | SWT.BORDER, store);
- bodyEditor.configure(new JavaScriptSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null));
- bodyEditor.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- Document bodyDocument= new Document(getInitialBody());
- bodyEditor.setDocument(bodyDocument);
- bodyEditor.setEditable(true);
-
- Control bodyControl= bodyEditor.getControl();
- PixelConverter pixelConverter= new PixelConverter(bodyControl);
- GridData gdata= new GridData(GridData.FILL_BOTH);
- gdata.widthHint= pixelConverter.convertWidthInCharsToPixels(50);
- gdata.minimumHeight= pixelConverter.convertHeightInCharsToPixels(5);
- bodyControl.setLayoutData(gdata);
- bodyControl.setFocus();
-
- bodyDocument.addDocumentListener(new IDocumentListener() {
- public void documentAboutToBeChanged(DocumentEvent event) {
- }
- public void documentChanged(DocumentEvent event) {
- try {
- fRefactoring.setBody(event.getDocument().get(), fRefactoring.getMethod().getParameterNames());
- } catch (JavaScriptModelException ex) {
- // TODO Auto-generated catch block
- JavaScriptPlugin.log(ex);
- }
- }
- });
- }
-
- private String getInitialBody() {
- //TODO
- return ""; //$NON-NLS-1$
-
- }
-
- private void changeMode(ReplaceInvocationsRefactoring.Mode mode) {
- RefactoringStatus status;
- try {
- status= fRefactoring.setCurrentMode(mode);
- } catch (JavaScriptModelException e) {
- status= RefactoringStatus.createFatalErrorStatus(e.getMessage());
- }
- setPageComplete(status);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsWizard.java
deleted file mode 100644
index bf18dca8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/code/ReplaceInvocationsWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.code;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ReplaceInvocationsRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class ReplaceInvocationsWizard extends RefactoringWizard {
-
- public ReplaceInvocationsWizard(ReplaceInvocationsRefactoring ref){
- super(ref, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.ReplaceInvocationsWizard_title);
- }
-
- protected void addUserInputPages(){
- addPage(new ReplaceInvocationsInputPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java
deleted file mode 100644
index 84eb77a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.WorkingCopyOwner;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaTypeCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-
-public class CUPositionCompletionProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
-
- private static final ImageDescriptorRegistry IMAGE_DESC_REGISTRY= JavaScriptPlugin.getImageDescriptorRegistry();
-
- private String fErrorMessage;
- private char[] fProposalAutoActivationSet;
- private CompletionProposalComparator fComparator;
-
- private CompletionContextRequestor fCompletionContextRequestor;
-
- private CUPositionCompletionRequestor fCompletionRequestor;
-
- /**
- * Creates a <code>CUPositionCompletionProcessor</code>.
- * The completion context must be set via {@link #setCompletionContext(IJavaScriptUnit,String,String)}.
- * @param completionRequestor the completion requestor
- */
- public CUPositionCompletionProcessor(CUPositionCompletionRequestor completionRequestor) {
- fCompletionRequestor= completionRequestor;
-
- fComparator= new CompletionProposalComparator();
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- String triggers= preferenceStore.getString(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
- fProposalAutoActivationSet = triggers.toCharArray();
- }
-
- /**
- * @param cuHandle the {@link IJavaScriptUnit} in whose context codeComplete will be invoked.
- * The given cu doesn't have to exist (and if it exists, it will not be modified).
- * An independent working copy consisting of
- * <code>beforeString</code> + ${current_input} + <code>afterString</code> will be used.
- * @param beforeString the string before the input position
- * @param afterString the string after the input position
- */
- public void setCompletionContext(final IJavaScriptUnit cuHandle, final String beforeString, final String afterString) {
- fCompletionContextRequestor= new CompletionContextRequestor() {
- final StubTypeContext fStubTypeContext= new StubTypeContext(cuHandle, beforeString, afterString);
- public StubTypeContext getStubTypeContext() {
- return fStubTypeContext;
- }
- };
- if (cuHandle != null)
- fCompletionRequestor.setJavaProject(cuHandle.getJavaScriptProject());
- }
-
- public void setCompletionContextRequestor(CompletionContextRequestor completionContextRequestor) {
- fCompletionContextRequestor= completionContextRequestor;
- }
-
- /**
- * Computing proposals on a <code>ITextViewer</code> is not supported.
- * @see #computeCompletionProposals(IContentAssistSubjectControl, int)
- * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /**
- * Computing context information on a <code>ITextViewer</code> is not supported.
- * @see #computeContextInformation(IContentAssistSubjectControl, int)
- * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return fProposalAutoActivationSet;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null; //no context
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeContextInformation(IContentAssistSubjectControl, int)
- */
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) {
- return null;
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeCompletionProposals(IContentAssistSubjectControl, int)
- */
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) {
- if (fCompletionContextRequestor.getOriginalCu() == null)
- return null;
- String input= contentAssistSubjectControl.getDocument().get();
- if (documentOffset == 0)
- return null;
- ICompletionProposal[] proposals= internalComputeCompletionProposals(documentOffset, input);
- Arrays.sort(proposals, fComparator);
- return proposals;
- }
-
- private ICompletionProposal[] internalComputeCompletionProposals(int documentOffset, String input) {
- String cuString= fCompletionContextRequestor.getBeforeString() + input + fCompletionContextRequestor.getAfterString();
- IJavaScriptUnit cu= null;
- try {
- /*
- * Explicitly create a new non-shared working copy.
- *
- * The WorkingCopy cannot easily be shared between calls, since IContentAssistProcessor
- * has no dispose() lifecycle method. A workaround could be to pass in a WorkingCopyOwner
- * and dispose the owner's working copies from the caller's dispose().
- */
- cu= fCompletionContextRequestor.getOriginalCu().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
- cu.getBuffer().setContents(cuString);
- int cuPrefixLength= fCompletionContextRequestor.getBeforeString().length();
- fCompletionRequestor.setOffsetReduction(cuPrefixLength);
- cu.codeComplete(cuPrefixLength + documentOffset, fCompletionRequestor);
-
- JavaCompletionProposal[] proposals= fCompletionRequestor.getResults();
- if (proposals.length == 0) {
- String errorMsg= fCompletionRequestor.getErrorMessage();
- if (errorMsg == null || errorMsg.trim().length() == 0)
- errorMsg= RefactoringMessages.JavaTypeCompletionProcessor_no_completion;
- fErrorMessage= errorMsg;
- } else {
- fErrorMessage= fCompletionRequestor.getErrorMessage();
- }
- return proposals;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return null;
- } finally {
- try {
- if (cu != null)
- cu.discardWorkingCopy();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- protected abstract static class CUPositionCompletionRequestor extends CompletionRequestor {
- public static final char[] TRIGGER_CHARACTERS= new char[] { '.' };
-
- private int fOffsetReduction;
- private IJavaScriptProject fJavaProject;
-
- private List fProposals;
- private String fErrorMessage2;
-
- public IJavaScriptProject getJavaProject() {
- return fJavaProject;
- }
-
- private void setJavaProject(IJavaScriptProject javaProject) {
- fJavaProject= javaProject;
- }
-
- private void setOffsetReduction(int offsetReduction) {
- fOffsetReduction= offsetReduction;
- fProposals= new ArrayList();
- }
-
- public final void completionFailure(IProblem error) {
- fErrorMessage2= error.getMessage();
- }
-
- public final JavaCompletionProposal[] getResults() {
- return (JavaCompletionProposal[]) fProposals.toArray(new JavaCompletionProposal[fProposals.size()]);
- }
-
- public final String getErrorMessage() {
- return fErrorMessage2;
- }
-
- protected final void addAdjustedCompletion(String name, String completion,
- int start, int end, int relevance, ImageDescriptor descriptor) {
- JavaCompletionProposal javaCompletionProposal= new JavaCompletionProposal(completion, start - fOffsetReduction, end - start,
- getImage(descriptor), name, relevance);
- javaCompletionProposal.setTriggerCharacters(TRIGGER_CHARACTERS);
- fProposals.add(javaCompletionProposal);
- }
-
- protected final void addAdjustedTypeCompletion(String name, String completion,
- int start, int end, int relevance, ImageDescriptor descriptor, String fullyQualifiedName) {
- JavaTypeCompletionProposal javaCompletionProposal= new JavaTypeCompletionProposal(
- fullyQualifiedName == null ? completion : fullyQualifiedName, null,
- fullyQualifiedName == null ? start - fOffsetReduction : 0,
- end - start, getImage(descriptor), name, relevance, completion);
- javaCompletionProposal.setTriggerCharacters(TRIGGER_CHARACTERS);
- fProposals.add(javaCompletionProposal);
- }
-
- private static Image getImage(ImageDescriptor descriptor) {
- return (descriptor == null) ? null : CUPositionCompletionProcessor.IMAGE_DESC_REGISTRY.get(descriptor);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CompletionContextRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CompletionContextRequestor.java
deleted file mode 100644
index b42eaa13..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/CompletionContextRequestor.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-
-
-public abstract class CompletionContextRequestor {
-
- public abstract StubTypeContext getStubTypeContext();
-
- public IJavaScriptUnit getOriginalCu() {
- return getStubTypeContext().getCuHandle();
- }
-
- public String getBeforeString() {
- return getStubTypeContext().getBeforeString();
- }
-
- public String getAfterString() {
- return getStubTypeContext().getAfterString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/ControlContentAssistHelper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/ControlContentAssistHelper.java
deleted file mode 100644
index 562ed501..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/ControlContentAssistHelper.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContentAssistant;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.contentassist.ContentAssistHandler;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.ContentAssistPreference;
-
-
-/**
- *
- */
-public class ControlContentAssistHelper {
-
- /**
- * @param text the text field to install ContentAssist
- * @param processor the <code>IContentAssistProcessor</code>
- */
- public static void createTextContentAssistant(final Text text, IContentAssistProcessor processor) {
- ContentAssistHandler.createHandlerForText(text, createJavaContentAssistant(processor));
- }
-
- /**
- * @param combo the text field to install ContentAssist
- * @param processor the <code>IContentAssistProcessor</code>
- */
- public static void createComboContentAssistant(final Combo combo, IContentAssistProcessor processor) {
- ContentAssistHandler.createHandlerForCombo(combo, createJavaContentAssistant(processor));
- }
-
- public static SubjectControlContentAssistant createJavaContentAssistant(IContentAssistProcessor processor) {
- final SubjectControlContentAssistant contentAssistant= new SubjectControlContentAssistant();
-
- contentAssistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
-
- ContentAssistPreference.configure(contentAssistant, JavaScriptPlugin.getDefault().getPreferenceStore());
- contentAssistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
- contentAssistant.setInformationControlCreator(new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
- }
- });
-
- return contentAssistant;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/FieldNameProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/FieldNameProcessor.java
deleted file mode 100644
index 3bb4692d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/FieldNameProcessor.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-
-public class FieldNameProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
-
- private String[] fFieldNameProposals;
- private String fErrorMessage;
- private ImageDescriptorRegistry fImageRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
- private PromoteTempToFieldRefactoring fRefactoring;
-
- public FieldNameProcessor(String[] guessedFieldNames, PromoteTempToFieldRefactoring refactoring) {
- fRefactoring= refactoring;
- fFieldNameProposals= refactoring.guessFieldNames();
- Arrays.sort(fFieldNameProposals);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.contentassist.IContentAssistProcessorExtension#computeContextInformation(org.eclipse.jface.contentassist.IContentAssistSubject, int)
- */
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.contentassist.IContentAssistProcessorExtension#computeCompletionProposals(org.eclipse.jface.contentassist.IContentAssistSubject, int)
- */
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- if (fFieldNameProposals.length == 0)
- return null;
- String input= contentAssistSubject.getDocument().get();
-
- ArrayList proposals= new ArrayList();
- String prefix= input.substring(0, documentOffset);
- ImageDescriptor imageDescriptor= JavaElementImageProvider.getFieldImageDescriptor(false, fRefactoring.getVisibility());
- Image image= fImageRegistry.get(imageDescriptor);
- for (int i= 0; i < fFieldNameProposals.length; i++) {
- String tempName= fFieldNameProposals[i];
- if (tempName.length() == 0 || ! tempName.startsWith(prefix))
- continue;
- JavaCompletionProposal proposal= new JavaCompletionProposal(tempName, 0, input.length(), image, tempName, 0);
- proposals.add(proposal);
- }
- fErrorMessage= proposals.size() > 0 ? null : JavaUIMessages.JavaEditor_codeassist_noCompletions;
- return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageCompletionProcessor.java
deleted file mode 100644
index b5fb39e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageCompletionProcessor.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-public class JavaPackageCompletionProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
-
- private IPackageFragmentRoot fPackageFragmentRoot;
- private CompletionProposalComparator fComparator;
- private ILabelProvider fLabelProvider;
-
- private char[] fProposalAutoActivationSet;
-
- /**
- * Creates a <code>JavaPackageCompletionProcessor</code>.
- * The completion context must be set via {@link #setPackageFragmentRoot(IPackageFragmentRoot)}.
- */
- public JavaPackageCompletionProcessor() {
- this(new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_SMALL_ICONS));
- }
-
- /**
- * Creates a <code>JavaPackageCompletionProcessor</code>.
- * The Processor uses the given <code>ILabelProvider</code> to show text and icons for the
- * possible completions.
- * @param labelProvider Used for the popups.
- */
- public JavaPackageCompletionProcessor(ILabelProvider labelProvider) {
- fComparator= new CompletionProposalComparator();
- fLabelProvider= labelProvider;
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- String triggers= preferenceStore.getString(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
- fProposalAutoActivationSet = triggers.toCharArray();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return fProposalAutoActivationSet;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null; //no context
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeContextInformation(IContentAssistSubjectControl, int)
- */
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubjectControl,
- int documentOffset) {
- return null;
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeCompletionProposals(IContentAssistSubjectControl, int)
- */
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) {
- if (fPackageFragmentRoot == null)
- return null;
- String input= contentAssistSubjectControl.getDocument().get();
- ICompletionProposal[] proposals= createPackagesProposals(documentOffset, input);
- Arrays.sort(proposals, fComparator);
- return proposals;
- }
-
- public void setPackageFragmentRoot(IPackageFragmentRoot packageFragmentRoot) {
- fPackageFragmentRoot= packageFragmentRoot;
- }
-
- private ICompletionProposal[] createPackagesProposals(int documentOffset, String input) {
- ArrayList proposals= new ArrayList();
- String prefix= input.substring(0, documentOffset);
- try {
- IJavaScriptElement[] packageFragments= fPackageFragmentRoot.getChildren();
- for (int i= 0; i < packageFragments.length; i++) {
- IPackageFragment pack= (IPackageFragment) packageFragments[i];
- String packName= pack.getElementName();
- if (packName.length() == 0 || ! packName.startsWith(prefix))
- continue;
- Image image= fLabelProvider.getImage(pack);
- JavaCompletionProposal proposal= new JavaCompletionProposal(packName, 0, input.length(), image, fLabelProvider.getText(pack), 0);
- proposals.add(proposal);
- }
- } catch (JavaScriptModelException e) {
- //fPackageFragmentRoot is not a proper root -> no proposals
- }
- return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageFragmentRootCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageFragmentRootCompletionProcessor.java
deleted file mode 100644
index 9b2b12d8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaPackageFragmentRootCompletionProcessor.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-/**
- * TODO: this class is not used anywhere yet.
- * (ContentAssist should be added to all source folder dialog fields.)
- */
-public class JavaPackageFragmentRootCompletionProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
- private static final ImageDescriptorRegistry IMAGE_DESC_REGISTRY= JavaScriptPlugin.getImageDescriptorRegistry();
-
- private IPackageFragmentRoot fPackageFragmentRoot;
- private CompletionProposalComparator fComparator;
-
- private char[] fProposalAutoActivationSet;
-
- /**
- * Creates a <code>JavaPackageCompletionProcessor</code> to complete existing packages
- * in the context of <code>packageFragmentRoot</code>.
- *
- * @param packageFragmentRoot the context for package completion
- */
- public JavaPackageFragmentRootCompletionProcessor(IPackageFragmentRoot packageFragmentRoot) {
- fPackageFragmentRoot= packageFragmentRoot;
- fComparator= new CompletionProposalComparator();
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- String triggers= preferenceStore.getString(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
- fProposalAutoActivationSet = triggers.toCharArray();
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return fProposalAutoActivationSet;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null; //no context
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeContextInformation(IContentAssistSubjectControl, int)
- */
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubject,
- int documentOffset) {
- return null;
- }
-
- /*
- * @see ISubjectControlContentAssistProcessor#computeCompletionProposals(IContentAssistSubjectControl, int)
- */
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) {
- String input= contentAssistSubjectControl.getDocument().get();
- ICompletionProposal[] proposals= createPackagesProposals(documentOffset, input);
- Arrays.sort(proposals, fComparator);
- return proposals;
- }
-
- private ICompletionProposal[] createPackagesProposals(int documentOffset, String input) {
- ArrayList proposals= new ArrayList();
- String prefix= input.substring(0, documentOffset);
- try {
- IJavaScriptElement[] packageFragments= fPackageFragmentRoot.getChildren();
- for (int i= 0; i < packageFragments.length; i++) {
- IPackageFragment pack= (IPackageFragment) packageFragments[i];
- String packName= pack.getElementName();
- if (packName.length() == 0 || ! packName.startsWith(prefix))
- continue;
- Image image= getImage(JavaPluginImages.DESC_OBJS_PACKAGE);
- JavaCompletionProposal proposal= new JavaCompletionProposal(packName, 0, input.length(), image, packName, 0);
- proposals.add(proposal);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private static Image getImage(ImageDescriptor descriptor) {
- return (descriptor == null) ? null : JavaPackageFragmentRootCompletionProcessor.IMAGE_DESC_REGISTRY.get(descriptor);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaSourcePackageFragmentRootCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaSourcePackageFragmentRootCompletionProcessor.java
deleted file mode 100644
index 5d142ab1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaSourcePackageFragmentRootCompletionProcessor.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-/**
- * Simple completion processor that completes package fragment roots that are source
- * folders.
- */
-public class JavaSourcePackageFragmentRootCompletionProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
-
- private char[] fProposalAutoActivationSet;
- private IJavaScriptModel fRoot;
- private CompletionProposalComparator fComparator;
- private JavaScriptElementLabelProvider fLabelProvider;
-
- public JavaSourcePackageFragmentRootCompletionProcessor() {
- fRoot= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- String triggers= preferenceStore.getString(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
- fProposalAutoActivationSet= triggers.toCharArray();
- fComparator= new CompletionProposalComparator();
- fLabelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_SMALL_ICONS);
- }
-
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- public char[] getCompletionProposalAutoActivationCharacters() {
- return fProposalAutoActivationSet;
- }
-
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- public String getErrorMessage() {
- return null;
- }
-
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- if (fRoot == null) {
- return null;
- }
-
- String input= contentAssistSubject.getDocument().get();
- String prefix= input.substring(0, documentOffset);
-
- ICompletionProposal[] proposals= createSourcePackageFragmentRootProposals(prefix, input.length());
- Arrays.sort(proposals, fComparator);
- return proposals;
- }
-
- /**
- * @param prefix prefixString with thatthe sourcepackagefragmentroots must begin
- * @param replacementLength length of the text to replace
- * @return array with sourcepackagefragmentroots
- */
- private ICompletionProposal[] createSourcePackageFragmentRootProposals(String prefix, int replacementLength) {
- List proposals= new ArrayList();
- try {
- IJavaScriptProject[] projects= fRoot.getJavaScriptProjects();
- for (int i= 0; i < projects.length; i++) {
- IJavaScriptProject project= projects[i];
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- for (int j= 0; j < roots.length; j++) {
- IPackageFragmentRoot root= roots[j];
- if (root.exists() && (root.getKind() == IPackageFragmentRoot.K_SOURCE)) {
- String name= root.getPath().toString();
- if (name.length() > 1) {
- name= name.substring(1);
- }
- if (name.startsWith(prefix)) {
- Image image= fLabelProvider.getImage(root);
- JavaCompletionProposal proposal= new JavaCompletionProposal(name, 0, replacementLength, image,
- name, 0);
- proposals.add(proposal);
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- // nothing to do
- }
-
- return (ICompletionProposal[])proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java
deleted file mode 100644
index 78ce7591..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-
-public class JavaTypeCompletionProcessor extends CUPositionCompletionProcessor {
-
- public static final String DUMMY_CLASS_NAME= "$$__$$"; //$NON-NLS-1$
-
- /**
- * The CU name to be used if no parent IJavaScriptUnit is available.
- * The main type of this class will be filtered out from the proposals list.
- */
- public static final String DUMMY_CU_NAME= DUMMY_CLASS_NAME + JavaModelUtil.DEFAULT_CU_SUFFIX;
-
- /**
- * Creates a <code>JavaTypeCompletionProcessor</code>.
- * The completion context must be set via {@link #setPackageFragment(IPackageFragment)}.
- *
- * @param enableBaseTypes complete java base types iff <code>true</code>
- * @param enableVoid complete <code>void</code> base type iff <code>true</code>
- */
- public JavaTypeCompletionProcessor(boolean enableBaseTypes, boolean enableVoid) {
- this(enableBaseTypes, enableVoid, false);
- }
-
- /**
- * Creates a <code>JavaTypeCompletionProcessor</code>.
- * The completion context must be set via {@link #setPackageFragment(IPackageFragment)}.
- *
- * @param enableBaseTypes complete java base types iff <code>true</code>
- * @param enableVoid complete <code>void</code> base type iff <code>true</code>
- * @param fullyQualify always complete to fully qualifies type iff <code>true</code>
- */
- public JavaTypeCompletionProcessor(boolean enableBaseTypes, boolean enableVoid, boolean fullyQualify) {
- super(new TypeCompletionRequestor(enableBaseTypes, enableVoid, fullyQualify));
- }
-
- public char[] getCompletionProposalAutoActivationCharacters() {
- // disable auto activation in dialog fields, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89476
- return null;
- }
-
- /**
- * @param packageFragment the new completion context
- */
- public void setPackageFragment(IPackageFragment packageFragment) {
- //TODO: Some callers have a better completion context and should include imports
- // and nested classes of their declaring CU in WC's source.
- if (packageFragment == null) {
- setCompletionContext(null, null, null);
- } else {
- String before= "public class " + DUMMY_CLASS_NAME + " { "; //$NON-NLS-1$//$NON-NLS-2$
- String after= " }"; //$NON-NLS-1$
- setCompletionContext(packageFragment.getJavaScriptUnit(DUMMY_CU_NAME), before, after);
- }
- }
-
- public void setExtendsCompletionContext(IJavaScriptElement javaElement) {
- if (javaElement instanceof IPackageFragment) {
- IPackageFragment packageFragment= (IPackageFragment) javaElement;
- IJavaScriptUnit cu= packageFragment.getJavaScriptUnit(DUMMY_CU_NAME);
- setCompletionContext(cu, "public class " + DUMMY_CLASS_NAME + " extends ", " {}"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- } else if (javaElement instanceof IType) {
- // pattern: public class OuterType { public class Type extends /*caret*/ {} }
- IType type= (IType) javaElement;
- String before= "public class " + type.getElementName() + " extends "; //$NON-NLS-1$ //$NON-NLS-2$
- String after= " {}"; //$NON-NLS-1$
- IJavaScriptElement parent= type.getParent();
- while (parent instanceof IType) {
- type= (IType) parent;
- before+= "public class " + type.getElementName() + " {"; //$NON-NLS-1$ //$NON-NLS-2$
- after+= "}"; //$NON-NLS-1$
- parent= type.getParent();
- }
- IJavaScriptUnit cu= type.getJavaScriptUnit();
- setCompletionContext(cu, before, after);
- } else {
- setCompletionContext(null, null, null);
- }
- }
-
-// public void setImplementsCompletionContext(IPackageFragment packageFragment) {
-// IJavaScriptUnit cu= packageFragment.getCompilationUnit(DUMMY_CU_NAME);
-// setCompletionContext(cu, "public class " + DUMMY_CLASS_NAME + " implements ", " {}"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
-// }
-
- protected static class TypeCompletionRequestor extends CUPositionCompletionRequestor {
- private static final String VOID= "void"; //$NON-NLS-1$
- private static final List BASE_TYPES= Arrays.asList(
- new String[] {"boolean", "byte", "char", "double", "float", "int", "long", "short"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-
- private boolean fEnableBaseTypes;
- private boolean fEnableVoid;
- private final boolean fFullyQualify;
-
- public TypeCompletionRequestor(boolean enableBaseTypes, boolean enableVoid, boolean fullyQualify) {
- fFullyQualify= fullyQualify;
- fEnableBaseTypes= enableBaseTypes;
- fEnableVoid= enableVoid;
- setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- setIgnored(CompletionProposal.FIELD_REF, true);
- setIgnored(CompletionProposal.LABEL_REF, true);
- setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
- setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.METHOD_REF, true);
- setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- }
-
- public void accept(CompletionProposal proposal) {
- switch (proposal.getKind()) {
- case CompletionProposal.PACKAGE_REF :
- char[] packageName= proposal.getDeclarationSignature();
- if (TypeFilter.isFiltered(packageName))
- return;
- addAdjustedCompletion(
- new String(packageName),
- new String(proposal.getCompletion()),
- proposal.getReplaceStart(),
- proposal.getReplaceEnd(),
- proposal.getRelevance(),
- JavaPluginImages.DESC_OBJS_PACKAGE);
- return;
-
- case CompletionProposal.TYPE_REF :
- char[] fullName= Signature.toCharArray(proposal.getSignature());
- if (TypeFilter.isFiltered(fullName))
- return;
- StringBuffer buf= new StringBuffer();
- buf.append(Signature.getSimpleName(fullName));
- if (buf.length() == 0)
- return; // this is the dummy class, whose $ have been converted to dots
- char[] typeQualifier= Signature.getQualifier(fullName);
- if (typeQualifier.length > 0) {
- buf.append(" - "); //$NON-NLS-1$
- buf.append(typeQualifier);
- }
- String name= buf.toString();
-
- addAdjustedTypeCompletion(
- name,
- new String(proposal.getCompletion()),
- proposal.getReplaceStart(),
- proposal.getReplaceEnd(),
- proposal.getRelevance(),
- JavaElementImageProvider.getTypeImageDescriptor(false, false, proposal.getFlags(), false),
- fFullyQualify ? new String(fullName) : null);
- return;
-
- case CompletionProposal.KEYWORD:
- if (! fEnableBaseTypes)
- return;
- String keyword= new String(proposal.getName());
- if ( (fEnableVoid && VOID.equals(keyword)) || (fEnableBaseTypes && BASE_TYPES.contains(keyword)) )
- addAdjustedCompletion(
- keyword,
- new String(proposal.getCompletion()),
- proposal.getReplaceStart(),
- proposal.getReplaceEnd(),
- proposal.getRelevance(),
- null);
- return;
-
- default :
- return;
- }
-
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/VariableNamesProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/VariableNamesProcessor.java
deleted file mode 100644
index 4e8bf03d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/contentassist/VariableNamesProcessor.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
-import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-
-public class VariableNamesProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
-
- private String fErrorMessage;
-
- private String[] fTempNameProposals;
-
- private ImageDescriptorRegistry fImageRegistry;
- private ImageDescriptor fProposalImageDescriptor;
-
- public VariableNamesProcessor(String[] tempNameProposals) {
- fTempNameProposals= (String[]) tempNameProposals.clone();
- Arrays.sort(fTempNameProposals);
- fImageRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
- fProposalImageDescriptor= JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE;
-
- }
-
- public void setProposalImageDescriptor(ImageDescriptor proposalImageDescriptor) {
- fProposalImageDescriptor= proposalImageDescriptor;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.contentassist.IContentAssistProcessorExtension#computeContextInformation(org.eclipse.jface.contentassist.IContentAssistSubject, int)
- */
- public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- return null; //no context
- }
-
- /*
- * @see org.eclipse.jface.contentassist.IContentAssistProcessorExtension#computeCompletionProposals(org.eclipse.jface.contentassist.IContentAssistSubject, int)
- */
- public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
- if (fTempNameProposals.length == 0)
- return null;
- String input= contentAssistSubject.getDocument().get();
-
- ArrayList proposals= new ArrayList();
- String prefix= input.substring(0, documentOffset);
- Image image= fImageRegistry.get(fProposalImageDescriptor);
- for (int i= 0; i < fTempNameProposals.length; i++) {
- String tempName= fTempNameProposals[i];
- if (tempName.length() == 0 || ! tempName.startsWith(prefix))
- continue;
- JavaCompletionProposal proposal= new JavaCompletionProposal(tempName, 0, input.length(), image, tempName, 0);
- proposals.add(proposal);
- }
- fErrorMessage= proposals.size() > 0 ? null : JavaUIMessages.JavaEditor_codeassist_noCompletions;
- return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/AccessorDescription.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/AccessorDescription.java
deleted file mode 100644
index a3262996..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/AccessorDescription.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-
-/**
- *
- */
-public class AccessorDescription {
-
- private final static String KEY_ACCESSOR_NAME= "accessorName"; //$NON-NLS-1$
- private final static String KEY_ACCESSOR_PACK= "accessorPackage"; //$NON-NLS-1$
- private final static String KEY_RESOURCE_BUNDLE_NAME= "bundleName"; //$NON-NLS-1$
- private final static String KEY_RESOURCE_BUNDLE_PACK= "bundlePackage"; //$NON-NLS-1$
-
-
- private final IPackageFragment fResourceBundlePackage;
- private final String fAccessorClassName;
- private final IPackageFragment fAccessorClassPackage;
- private final String fResourceBundleName;
-
- /**
- *
- */
- public AccessorDescription(String accessorClassName, IPackageFragment accessorClassPackage, String propertyFileName, IPackageFragment propertyFilePackage) {
- super();
- fAccessorClassName= accessorClassName;
- fAccessorClassPackage= accessorClassPackage;
- fResourceBundleName= propertyFileName;
- fResourceBundlePackage= propertyFilePackage;
- }
-
- public String getLabel() {
- StringBuffer buf= new StringBuffer();
- buf.append(getAccessorClassPackage().getElementName());
- if (buf.length() > 0) {
- buf.append('.');
- }
- buf.append(getAccessorClassName());
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- IPath propertyFilePath= getResourceBundlePackage().getPath().append(getResourceBundleName());
- buf.append(propertyFilePath.makeRelative().toString());
- return buf.toString();
- }
-
- public void serialize(IDialogSettings settings) {
- settings.put(KEY_ACCESSOR_NAME, getAccessorClassName());
- settings.put(KEY_ACCESSOR_PACK, getAccessorClassPackage().getHandleIdentifier());
- settings.put(KEY_RESOURCE_BUNDLE_NAME, getResourceBundleName());
- settings.put(KEY_RESOURCE_BUNDLE_PACK, getResourceBundlePackage().getHandleIdentifier());
- }
-
- /**
- * @return Returns the accessor class name.
- */
- public String getAccessorClassName() {
- return fAccessorClassName;
- }
- /**
- * @return Returns the accessor class package.
- */
- public IPackageFragment getAccessorClassPackage() {
- return fAccessorClassPackage;
- }
- /**
- * @return Returns the resource bundle name.
- */
- public String getResourceBundleName() {
- return fResourceBundleName;
- }
- /**
- * @return Returns the resource bundle package
- */
- public IPackageFragment getResourceBundlePackage() {
- return fResourceBundlePackage;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj != null && obj.getClass().equals(getClass())) {
- AccessorDescription other= (AccessorDescription) obj;
- return other == this ||
- (other.fAccessorClassName.equals(fAccessorClassName)
- && other.fAccessorClassPackage.equals(fAccessorClassPackage)
- && other.fResourceBundleName.equals(fResourceBundleName)
- && other.fResourceBundlePackage.equals(fResourceBundlePackage));
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return fAccessorClassName.hashCode() + fAccessorClassPackage.hashCode() + fResourceBundleName.hashCode() + fResourceBundlePackage.hashCode();
- }
-
- public static AccessorDescription deserialize(IDialogSettings settings) {
- String accessorName= settings.get(KEY_ACCESSOR_NAME);
- if (accessorName == null) {
- return null;
- }
-
- String accessorPackHandle= settings.get(KEY_ACCESSOR_PACK);
- if (accessorPackHandle == null) {
- return null;
- }
- IJavaScriptElement accessorPack= JavaScriptCore.create(accessorPackHandle);
- if (!(accessorPack instanceof IPackageFragment) || !accessorPack.exists()) {
- return null;
- }
-
- String bundleName= settings.get(KEY_RESOURCE_BUNDLE_NAME);
- if (bundleName == null) {
- return null;
- }
-
- String bundlePackHandle= settings.get(KEY_RESOURCE_BUNDLE_PACK);
- if (bundlePackHandle == null) {
- return null;
- }
- IJavaScriptElement bundlePack= JavaScriptCore.create(bundlePackHandle);
- if (!(bundlePack instanceof IPackageFragment) || !bundlePack.exists()) {
- return null;
- }
-
- return new AccessorDescription(accessorName, (IPackageFragment) accessorPack, bundleName, (IPackageFragment) bundlePack);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizard.java
deleted file mode 100644
index 2369c527..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizard.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * good citizen problems - wizard is only valid after constructor (when the pages toggle
- * some values and force an validate the validate can't get a wizard)
- */
-public class ExternalizeWizard extends RefactoringWizard {
-
- public ExternalizeWizard(NLSRefactoring refactoring) {
- super(refactoring,CHECK_INITIAL_CONDITIONS_ON_OPEN | WIZARD_BASED_USER_INTERFACE);
- setDefaultPageTitle(Messages.format(NLSUIMessages.ExternalizeWizardPage_title, refactoring.getCu().getElementName()));
- setWindowTitle(NLSUIMessages.ExternalizeWizard_name);
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXTERNALIZE_STRINGS);
- }
-
- /**
- * @see RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
-
- NLSRefactoring nlsRefac= (NLSRefactoring) getRefactoring();
- ExternalizeWizardPage page= new ExternalizeWizardPage(nlsRefac);
- page.setMessage(NLSUIMessages.ExternalizeWizard_select);
- addPage(page);
-
- /*ExternalizeWizardPage2 page2= new ExternalizeWizardPage2(nlsRefac);
- page2.setMessage(NLSUIMessages.getString("wizard.select_values")); //$NON-NLS-1$
- addPage(page2);*/
- }
-
- public boolean canFinish() {
- IWizardPage page= getContainer().getCurrentPage();
- return super.canFinish() && !(page instanceof ExternalizeWizardPage);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java
deleted file mode 100644
index c5d2a233..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java
+++ /dev/null
@@ -1,1332 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.FontRegistry;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnPixelData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.IFontProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.KeyValuePair;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSSubstitution;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-class ExternalizeWizardPage extends UserInputWizardPage {
-
- private static final String[] PROPERTIES;
- private static final String[] fgTitles;
- private static final int STATE_PROP= 0;
- private static final int VAL_PROP= 1;
- private static final int KEY_PROP= 2;
- private static final int SIZE= 3; //column counter
- private static final int ROW_COUNT= 5;
-
- public static final String PAGE_NAME= "NLSWizardPage1"; //$NON-NLS-1$
- static {
- PROPERTIES= new String[SIZE];
- PROPERTIES[STATE_PROP]= "task"; //$NON-NLS-1$
- PROPERTIES[KEY_PROP]= "key"; //$NON-NLS-1$
- PROPERTIES[VAL_PROP]= "value"; //$NON-NLS-1$
-
- fgTitles= new String[SIZE];
- fgTitles[STATE_PROP]= ""; //$NON-NLS-1$
- fgTitles[KEY_PROP]= NLSUIMessages.ExternalizeWizardPage_key;
- fgTitles[VAL_PROP]= NLSUIMessages.ExternalizeWizardPage_value;
- }
-
- private class CellModifier implements ICellModifier {
-
- /**
- * @see ICellModifier#canModify(Object, String)
- */
- public boolean canModify(Object element, String property) {
- if (property == null)
- return false;
-
- if (!(element instanceof NLSSubstitution))
- return false;
-
- NLSSubstitution subst= (NLSSubstitution) element;
- if (PROPERTIES[KEY_PROP].equals(property) && subst.getState() != NLSSubstitution.EXTERNALIZED) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @see ICellModifier#getValue(Object, String)
- */
- public Object getValue(Object element, String property) {
- if (element instanceof NLSSubstitution) {
- NLSSubstitution substitution= (NLSSubstitution) element;
- String res= null;
- if (PROPERTIES[KEY_PROP].equals(property)) {
- res= substitution.getKeyWithoutPrefix();
- } else if (PROPERTIES[VAL_PROP].equals(property)) {
- res= substitution.getValue();
- } else if (PROPERTIES[STATE_PROP].equals(property)) {
- return new Integer(substitution.getState());
- }
- if (res != null) {
- return unwindEscapeChars(res);
- }
- return ""; //$NON-NLS-1$
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * @see ICellModifier#modify(Object, String, Object)
- */
- public void modify(Object element, String property, Object value) {
- if (element instanceof TableItem) {
- Object data= ((TableItem) element).getData();
- if (data instanceof NLSSubstitution) {
- NLSSubstitution substitution= (NLSSubstitution) data;
- if (PROPERTIES[KEY_PROP].equals(property)) {
- String string = (String)value;
- string = windEscapeChars(string);
- substitution.setKey(string);
- }
- if (PROPERTIES[VAL_PROP].equals(property)) {
- String string = (String)value;
- string = windEscapeChars(string);
- substitution.setValue(string);
- }
- if (PROPERTIES[STATE_PROP].equals(property)) {
- substitution.setState(((Integer) value).intValue());
- if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
- substitution.generateKey(fSubstitutions);
- }
- }
- }
- validateKeys(false);
- fTableViewer.update(data, null);
- }
- }
- }
-
- private class NLSSubstitutionLabelProvider extends LabelProvider implements ITableLabelProvider, IFontProvider {
-
- private FontRegistry fFontRegistry;
-
- public NLSSubstitutionLabelProvider() {
- fFontRegistry= JFaceResources.getFontRegistry();
- }
-
- public String getColumnText(Object element, int columnIndex) {
- String columnText= ""; //$NON-NLS-1$
- if (element instanceof NLSSubstitution) {
- NLSSubstitution substitution= (NLSSubstitution) element;
- if (columnIndex == KEY_PROP) {
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
- columnText= substitution.getKey();
- }
- } else
- if ((columnIndex == VAL_PROP) && (substitution.getValue() != null)) {
- columnText= substitution.getValue();
- }
- }
- return unwindEscapeChars(columnText);
- }
-
- public Image getColumnImage(Object element, int columnIndex) {
- if ((columnIndex == STATE_PROP) && (element instanceof NLSSubstitution)) {
- return getNLSImage((NLSSubstitution) element);
- }
-
- return null;
- }
-
- public Font getFont(Object element) {
- if (element instanceof NLSSubstitution) {
- NLSSubstitution substitution= (NLSSubstitution) element;
- if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
- return fFontRegistry.getBold(JFaceResources.DIALOG_FONT);
- }
- }
- return null;
- }
-
- private Image getNLSImage(NLSSubstitution sub) {
- if ((sub.getValue() == null) && (sub.getKey() != null)) {
- // Missing keys
- JavaScriptElementImageDescriptor imageDescriptor= new JavaScriptElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaScriptElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE);
- return JavaScriptPlugin.getImageDescriptorRegistry().get(imageDescriptor);
- } else
- if (sub.isConflicting(fSubstitutions) || !isKeyValid(sub, null)) {
- JavaScriptElementImageDescriptor imageDescriptor= new JavaScriptElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaScriptElementImageDescriptor.ERROR, JavaElementImageProvider.SMALL_SIZE);
- return JavaScriptPlugin.getImageDescriptorRegistry().get(imageDescriptor);
- } else {
- return getNLSImage(sub.getState());
- }
- }
-
- private Image getNLSImage(int task) {
- switch (task) {
- case NLSSubstitution.EXTERNALIZED :
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_TRANSLATE);
- case NLSSubstitution.IGNORED :
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
- case NLSSubstitution.INTERNALIZED :
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_SKIP);
- default :
- Assert.isTrue(false);
- return null;
- }
- }
-
- private ImageDescriptor getNLSImageDescriptor(int task) {
- switch (task) {
- case NLSSubstitution.EXTERNALIZED :
- return JavaPluginImages.DESC_OBJS_NLS_TRANSLATE;
- case NLSSubstitution.IGNORED :
- return JavaPluginImages.DESC_OBJS_NLS_NEVER_TRANSLATE;
- case NLSSubstitution.INTERNALIZED :
- return JavaPluginImages.DESC_OBJS_NLS_SKIP;
- default :
- Assert.isTrue(false);
- return null;
- }
- }
- }
-
- private static String unwindEscapeChars(String s) {
- if (s != null) {
- StringBuffer sb= new StringBuffer(s.length());
- int length= s.length();
- for (int i= 0; i < length; i++) {
- char c= s.charAt(i);
- sb.append(getUnwoundString(c));
- }
- return sb.toString();
- }
- return null;
- }
-
- private static String getUnwoundString(char c) {
- switch (c) {
- case '\b' :
- return "\\b";//$NON-NLS-1$
- case '\t' :
- return "\\t";//$NON-NLS-1$
- case '\n' :
- return "\\n";//$NON-NLS-1$
- case '\f' :
- return "\\f";//$NON-NLS-1$
- case '\r' :
- return "\\r";//$NON-NLS-1$
- case '\\' :
- return "\\\\";//$NON-NLS-1$
- }
- return String.valueOf(c);
- }
-
- private static String windEscapeChars(String s) {
- if (s == null)
- return null;
-
- char aChar;
- int len= s.length();
- StringBuffer outBuffer= new StringBuffer(len);
-
- for (int x= 0; x < len;) {
- aChar= s.charAt(x++);
- if (aChar == '\\') {
- aChar= s.charAt(x++);
- if (aChar == 'u') {
- // Read the xxxx
- int value= 0;
- for (int i= 0; i < 4; i++) {
- aChar= s.charAt(x++);
- switch (aChar) {
- case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
- value= (value << 4) + aChar - '0';
- break;
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- value= (value << 4) + 10 + aChar - 'a';
- break;
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- value= (value << 4) + 10 + aChar - 'A';
- break;
- default:
- throw new IllegalArgumentException("Malformed \\uxxxx encoding."); //$NON-NLS-1$
- }
- }
- outBuffer.append((char) value);
- } else {
- if (aChar == 't') {
- outBuffer.append('\t');
- } else {
- if (aChar == 'r') {
- outBuffer.append('\r');
- } else {
- if (aChar == 'n') {
- outBuffer.append('\n');
- } else {
- if (aChar == 'f') {
- outBuffer.append('\f');
- } else {
- outBuffer.append(aChar);
- }
- }
- }
- }
- }
- } else
- outBuffer.append(aChar);
- }
- return outBuffer.toString();
- }
-
- private class NLSInputDialog extends StatusDialog implements IDialogFieldListener {
- private StringDialogField fKeyField;
- private StringDialogField fValueField;
- private DialogField fMessageField;
- private NLSSubstitution fSubstitution;
-
- public NLSInputDialog(Shell parent, NLSSubstitution substitution) {
- super(parent);
-
- setTitle(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Title);
-
- fSubstitution= substitution;
-
- fMessageField= new DialogField();
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
- fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_ext_Label);
- } else {
- fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Label);
- }
-
- fKeyField= new StringDialogField();
- fKeyField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_key);
- fKeyField.setDialogFieldListener(this);
-
- fValueField= new StringDialogField();
- fValueField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_value);
- fValueField.setDialogFieldListener(this);
-
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
- fKeyField.setText(substitution.getKeyWithoutPrefix());
- } else {
- fKeyField.setText(""); //$NON-NLS-1$
- }
-
- fValueField.setText(substitution.getValueNonEmpty());
- }
-
- public KeyValuePair getResult() {
- KeyValuePair res= new KeyValuePair(fKeyField.getText(), fValueField.getText());
- return res;
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(composite.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
-
- fMessageField.doFillIntoGrid(inner, 2);
-
- if (fSubstitution.getState() == NLSSubstitution.EXTERNALIZED) {
- fKeyField.doFillIntoGrid(inner, 2);
- LayoutUtil.setWidthHint(fKeyField.getTextControl(null), convertWidthInCharsToPixels(45));
- }
-
- fValueField.doFillIntoGrid(inner, 2);
- LayoutUtil.setWidthHint(fValueField.getTextControl(null), convertWidthInCharsToPixels(45));
- LayoutUtil.setHorizontalGrabbing(fValueField.getTextControl(null));
-
- fValueField.postSetFocusOnDialogField(parent.getDisplay());
-
- applyDialogFont(composite);
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- IStatus keyStatus= validateKey(fKeyField.getText());
- //IStatus valueStatus= StatusInfo.OK_STATUS; // no validation yet
-
- //updateStatus(StatusUtil.getMoreSevere(valueStatus, keyStatus));
- updateStatus(keyStatus);
- }
-
-
- private IStatus validateKey(String val) {
- if (fSubstitution.getState() != NLSSubstitution.EXTERNALIZED) {
- return StatusInfo.OK_STATUS;
- }
-
- if (val == null || val.length() == 0) {
- return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_empty_key);
- }
-
- if (fNLSRefactoring.isEclipseNLS()) {
- if (!Character.isJavaIdentifierStart(val.charAt(0)))
- return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
-
- for (int i= 1, length= val.length(); i < length; i++) {
- if (!Character.isJavaIdentifierPart(val.charAt(i)))
- return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
- }
- } else {
- // validation so keys don't contain spaces
- for (int i= 0; i < val.length(); i++) {
- if (Character.isWhitespace(val.charAt(i))) {
- return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_key);
- }
- }
- }
- return StatusInfo.OK_STATUS;
- }
- }
-
- private static final String SETTINGS_NLS_ACCESSORS= "nls_accessor_history"; //$NON-NLS-1$
- private static final int SETTINGS_MAX_ENTRIES= 5;
-
- private Text fPrefixField;
- private Button fIsEclipseNLS;
- private Table fTable;
- private TableViewer fTableViewer;
- private SourceViewer fSourceViewer;
-
- private final IJavaScriptUnit fCu;
- private NLSSubstitution[] fSubstitutions;
- private Button fExternalizeButton;
- private Button fIgnoreButton;
- private Button fInternalizeButton;
- private Button fRevertButton;
- private Button fEditButton;
- private NLSRefactoring fNLSRefactoring;
- private Button fRenameButton;
- private Combo fAccessorClassField;
-
- private AccessorDescription[] fAccessorChoices;
- private Button fFilterCheckBox;
-
- public ExternalizeWizardPage(NLSRefactoring nlsRefactoring) {
- super(PAGE_NAME);
- fCu= nlsRefactoring.getCu();
- fSubstitutions= nlsRefactoring.getSubstitutions();
- fNLSRefactoring= nlsRefactoring;
- fAccessorChoices= null;
-
- setDescription(NLSUIMessages.ExternalizeWizardPage_description);
- createDefaultExternalization(fSubstitutions, nlsRefactoring.getPrefix());
- }
-
- /*
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite supercomposite= new Composite(parent, SWT.NONE);
- supercomposite.setFont(parent.getFont());
- supercomposite.setLayout(new GridLayout());
-
- createIsEclipseNLSCheckbox(supercomposite);
-
- createKeyPrefixField(supercomposite);
-
- SashForm composite= new SashForm(supercomposite, SWT.VERTICAL);
- composite.setFont(supercomposite.getFont());
-
- GridData data= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(data);
-
- createTableViewer(composite);
- createSourceViewer(composite);
-
- createAccessorInfoComposite(supercomposite);
-
- composite.setWeights(new int[]{65, 45});
-
- validateKeys(false);
- updateButtonStates(StructuredSelection.EMPTY);
-
- // promote control
- setControl(supercomposite);
- Dialog.applyDialogFont(supercomposite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(supercomposite, IJavaHelpContextIds.EXTERNALIZE_WIZARD_KEYVALUE_PAGE);
- }
-
- /**
- * @param supercomposite
- */
- private void createAccessorInfoComposite(Composite supercomposite) {
- Composite accessorComposite= new Composite(supercomposite, SWT.NONE);
- accessorComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout layout= new GridLayout(2, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- accessorComposite.setLayout(layout);
-
- Composite composite= new Composite(accessorComposite, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- layout= new GridLayout(1, true);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
-
- Label accessorClassLabel= new Label(composite, SWT.NONE);
- accessorClassLabel.setText(NLSUIMessages.ExternalizeWizardPage_accessorclass_label);
- accessorClassLabel.setLayoutData(new GridData());
-
-
- SelectionListener listener= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- if (e.widget instanceof Button) {
- doConfigureButtonPressed();
- } else {
- doAccessorSelectionChanged();
- }
- }
- };
-
-
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.widthHint= convertWidthInCharsToPixels(30);
- fAccessorClassField= new Combo(composite, SWT.READ_ONLY);
- fAccessorClassField.setLayoutData(data);
- fAccessorClassField.addSelectionListener(listener);
-
-
- //new Label(composite, SWT.NONE); // placeholder
-
- Button configure= new Button(accessorComposite, SWT.PUSH);
- configure.setText(NLSUIMessages.ExternalizeWizardPage_configure_button);
- data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_END);
- data.widthHint= SWTUtil.getButtonWidthHint(configure);
- configure.setLayoutData(data);
-
- configure.addSelectionListener(listener);
-
- updateAccessorChoices();
-
- }
-
- protected void doAccessorSelectionChanged() {
- int selectionIndex= fAccessorClassField.getSelectionIndex();
- if (fAccessorChoices != null && selectionIndex < fAccessorChoices.length) {
- AccessorDescription selected= fAccessorChoices[selectionIndex];
- fNLSRefactoring.setAccessorClassName(selected.getAccessorClassName());
- fNLSRefactoring.setAccessorClassPackage(selected.getAccessorClassPackage());
- fNLSRefactoring.setResourceBundleName(selected.getResourceBundleName());
- fNLSRefactoring.setResourceBundlePackage(selected.getResourceBundlePackage());
- fNLSRefactoring.setIsEclipseNLS(fNLSRefactoring.detectIsEclipseNLS());
-
- NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
- if (fIsEclipseNLS != null) {
- fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
- fIsEclipseNLS.setEnabled(willCreateAccessorClass());
- }
- validateKeys(true);
- }
- }
-
- private boolean willCreateAccessorClass() {
- try {
- return fNLSRefactoring.willCreateAccessorClass();
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
-
- private void updateAccessorChoices() {
-
- AccessorDescription configured= new AccessorDescription(
- fNLSRefactoring.getAccessorClassName(),
- fNLSRefactoring.getAccessorClassPackage(),
- fNLSRefactoring.getResourceBundleName(),
- fNLSRefactoring.getResourceBundlePackage());
-
- ArrayList currChoices= new ArrayList();
- ArrayList currLabels= new ArrayList();
-
- currChoices.add(configured);
- currLabels.add(configured.getLabel());
-
- AccessorDescription[] choices= fAccessorChoices;
- if (choices == null) {
- choices= loadAccessorDescriptions();
- }
-
- for (int i= 0; i < choices.length; i++) {
- AccessorDescription curr= choices[i];
- if (!curr.equals(configured)) {
- currChoices.add(curr);
- currLabels.add(curr.getLabel());
- }
- }
-
- String[] labels= (String[]) currLabels.toArray(new String[currLabels.size()]);
- fAccessorChoices= (AccessorDescription[]) currChoices.toArray(new AccessorDescription[currChoices.size()]);
-
- fAccessorClassField.setItems(labels);
- fAccessorClassField.select(0);
- }
-
-
- private AccessorDescription[] loadAccessorDescriptions() {
- IDialogSettings section= JavaScriptPlugin.getDefault().getDialogSettings().getSection(SETTINGS_NLS_ACCESSORS);
- if (section == null) {
- return new AccessorDescription[0];
- }
- ArrayList res= new ArrayList();
- for (int i= 0; i < SETTINGS_MAX_ENTRIES; i++) {
- IDialogSettings serializedDesc= section.getSection(String.valueOf(i));
- if (serializedDesc != null) {
- AccessorDescription accessor= AccessorDescription.deserialize(serializedDesc);
- if (accessor != null) {
- res.add(accessor);
- }
- }
- }
- return (AccessorDescription[]) res.toArray(new AccessorDescription[res.size()]);
- }
-
-
-
- private void storeAccessorDescriptions() {
- if (fAccessorChoices == null) {
- return;
- }
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- IDialogSettings nlsSection= dialogSettings.getSection(SETTINGS_NLS_ACCESSORS);
- if (nlsSection == null) {
- nlsSection= dialogSettings.addNewSection(SETTINGS_NLS_ACCESSORS);
- }
- int nEntries= Math.min(SETTINGS_MAX_ENTRIES, fAccessorChoices.length);
- for (int i= 0; i < nEntries; i++) {
- IDialogSettings serializedDesc= nlsSection.addNewSection(String.valueOf(i));
- fAccessorChoices[i].serialize(serializedDesc);
- }
- }
-
-
- private void doConfigureButtonPressed() {
- NLSAccessorConfigurationDialog dialog= new NLSAccessorConfigurationDialog(getShell(), fNLSRefactoring);
- if (dialog.open() == Window.OK) {
- NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
- if (fIsEclipseNLS != null) {
- fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
- fIsEclipseNLS.setEnabled(willCreateAccessorClass());
- }
- validateKeys(true);
- updateAccessorChoices();
- }
- }
-
- private Properties getProperties(IFile propertyFile) {
- Properties props= new Properties();
- try {
- if (propertyFile.exists()) {
- InputStream is= propertyFile.getContents();
- props.load(is);
- is.close();
- }
- } catch (Exception e) {
- // sorry no property
- }
- return props;
- }
-
- private void createTableViewer(Composite composite) {
- createTableComposite(composite);
-
- /*
- * Feature of CellEditors - double click is ignored.
- * The workaround is to register my own listener and force the desired
- * behavior.
- */
- fTableViewer= new TableViewer(fTable) {
- protected void hookControl(Control control) {
- super.hookControl(control);
- ((Table) control).addMouseListener(new MouseAdapter() {
- public void mouseDoubleClick(MouseEvent e) {
- if (getTable().getSelection().length == 0)
- return;
- TableItem item= getTable().getSelection()[0];
- if (item.getBounds(STATE_PROP).contains(e.x, e.y)) {
- List widgetSel= getSelectionFromWidget();
- if (widgetSel == null || widgetSel.size() != 1)
- return;
- NLSSubstitution substitution= (NLSSubstitution) widgetSel.get(0);
- Integer value= (Integer) getCellModifier().getValue(substitution, PROPERTIES[STATE_PROP]);
- int newValue= MultiStateCellEditor.getNextValue(NLSSubstitution.STATE_COUNT, value.intValue());
- getCellModifier().modify(item, PROPERTIES[STATE_PROP], new Integer(newValue));
- }
- }
- });
- }
- };
-
- fTableViewer.setUseHashlookup(true);
-
- final CellEditor[] editors= createCellEditors();
- fTableViewer.setCellEditors(editors);
- fTableViewer.setColumnProperties(PROPERTIES);
- fTableViewer.setCellModifier(new CellModifier());
-
- fTableViewer.setContentProvider(new IStructuredContentProvider() {
- public Object[] getElements(Object inputElement) {
- return fSubstitutions;
- }
- public void dispose() {
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- });
- fTableViewer.addFilter(new ViewerFilter() {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (!fFilterCheckBox.getSelection()) {
- return true;
- }
- NLSSubstitution curr= (NLSSubstitution) element;
- return (curr.getInitialState() == NLSSubstitution.INTERNALIZED) || (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null);
- }
- });
-
-
- fTableViewer.setLabelProvider(new NLSSubstitutionLabelProvider());
- fTableViewer.setInput(new Object());
-
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- ExternalizeWizardPage.this.selectionChanged(event);
- }
- });
- }
-
- private void createDefaultExternalization(NLSSubstitution[] substitutions, String defaultPrefix) {
- for (int i= 0; i < substitutions.length; i++) {
- NLSSubstitution substitution= substitutions[i];
- if (substitution.getState() == NLSSubstitution.INTERNALIZED) {
- substitution.setState(NLSSubstitution.EXTERNALIZED);
- substitution.generateKey(substitutions);
- }
- }
- }
-
- private CellEditor[] createCellEditors() {
- final CellEditor editors[]= new CellEditor[SIZE];
- editors[STATE_PROP]= new MultiStateCellEditor(fTable, NLSSubstitution.STATE_COUNT, NLSSubstitution.DEFAULT);
- editors[KEY_PROP]= new TextCellEditor(fTable);
- editors[VAL_PROP]= new TextCellEditor(fTable);
- return editors;
- }
-
- private void createSourceViewer(Composite parent) {
- Composite c= new Composite(parent, SWT.NONE);
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout gl= new GridLayout();
- gl.marginHeight= 0;
- gl.marginWidth= 0;
- c.setLayout(gl);
-
- Label l= new Label(c, SWT.NONE);
- l.setText(NLSUIMessages.ExternalizeWizardPage_context);
- l.setLayoutData(new GridData());
-
- // source viewer
- JavaScriptTextTools tools= JavaScriptPlugin.getDefault().getJavaTextTools();
- int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSourceViewer= new JavaSourceViewer(c, null, null, false, styles, store);
- fSourceViewer.configure(new JavaScriptSourceViewerConfiguration(tools.getColorManager(), store, null, null));
- fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
-
- try {
-
- String contents= fCu.getBuffer().getContents();
- IDocument document= new Document(contents);
- tools.setupJavaDocumentPartitioner(document);
-
- fSourceViewer.setDocument(document);
- fSourceViewer.setEditable(false);
-
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= convertHeightInCharsToPixels(10);
- gd.widthHint= convertWidthInCharsToPixels(40);
- fSourceViewer.getControl().setLayoutData(gd);
-
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, NLSUIMessages.ExternalizeWizardPage_exception_title, NLSUIMessages.ExternalizeWizardPage_exception_message);
- }
- }
-
- private void createKeyPrefixField(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout gl= new GridLayout();
- gl.numColumns= 2;
- gl.marginWidth= 0;
- composite.setLayout(gl);
-
- Label l= new Label(composite, SWT.NONE);
- l.setText(NLSUIMessages.ExternalizeWizardPage_common_prefix);
- l.setLayoutData(new GridData());
-
- fPrefixField= new Text(composite, SWT.SINGLE | SWT.BORDER);
- fPrefixField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fPrefixField.setText(fNLSRefactoring.getPrefix());
- fPrefixField.selectAll();
-
- fPrefixField.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- fNLSRefactoring.setPrefix(fPrefixField.getText());
- validateKeys(true);
- }
- });
- }
-
- private boolean isEclipseNLSAvailable() {
- if (fNLSRefactoring == null || fNLSRefactoring.getCu() == null)
- return false;
-
- IJavaScriptProject jp= fNLSRefactoring.getCu().getJavaScriptProject();
- if (jp == null || !jp.exists())
- return false;
-
- try {
- return jp.findType("org.eclipse.osgi.util.NLS") != null; //$NON-NLS-1$
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
-
- private void createIsEclipseNLSCheckbox(Composite parent) {
- if (fNLSRefactoring.isEclipseNLS() || isEclipseNLSAvailable()) {
- fIsEclipseNLS= new Button(parent, SWT.CHECK);
- fIsEclipseNLS.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fIsEclipseNLS.setText(NLSUIMessages.ExternalizeWizardPage_isEclipseNLSCheckbox);
- fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
- fIsEclipseNLS.setEnabled(willCreateAccessorClass());
- fIsEclipseNLS.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- super.widgetDefaultSelected(e);
- boolean isEclipseNLS= fIsEclipseNLS.getSelection();
- fNLSRefactoring.setIsEclipseNLS(isEclipseNLS);
- if (isEclipseNLS) {
- fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('.', '_'));
- } else {
- fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('_', '.'));
- }
- fPrefixField.setText(fNLSRefactoring.getPrefix());
- validateKeys(true);
- }
- });
- }
- }
-
- private void validateKeys(boolean refreshTable) {
- RefactoringStatus status= new RefactoringStatus();
- checkInvalidKeys(status);
- checkDuplicateKeys(status);
- checkMissingKeys(status);
- setPageComplete(status);
- if (refreshTable)
- fTableViewer.refresh(true);
- }
-
- private void checkInvalidKeys(RefactoringStatus status) {
- for (int i= 0; i < fSubstitutions.length; i++) {
- if (!isKeyValid(fSubstitutions[i], status))
- return;
- }
- }
-
- private boolean isKeyValid(NLSSubstitution substitution, RefactoringStatus status) {
- if (substitution == null)
- return false;
-
- if (substitution.getState() != NLSSubstitution.EXTERNALIZED)
- return true;
-
- String key= substitution.getKey();
-
- if (fNLSRefactoring.isEclipseNLS()) {
- if (key == null || key.length() == 0 || !Character.isJavaIdentifierStart(key.charAt(0))) {
- if (status != null)
- status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
- return false;
- }
- for (int i= 1, length= key.length(); i < length; i++) {
- if (!Character.isJavaIdentifierPart(key.charAt(i))) {
- if (status != null)
- status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
- return false;
- }
- }
- } else {
- if (key == null || key.length() == 0) {
- if (status != null)
- status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
- return false;
- }
- // validation so keys don't contain spaces
- for (int i= 0; i < key.length(); i++) {
- if (Character.isWhitespace(key.charAt(i))) {
- if (status != null)
- status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
- return false;
- }
- }
- }
-
- return true;
- }
-
- private void checkDuplicateKeys(RefactoringStatus status) {
- for (int i= 0; i < fSubstitutions.length; i++) {
- NLSSubstitution substitution= fSubstitutions[i];
- if (conflictingKeys(substitution)) {
- status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_conflicting);
- return;
- }
- }
- }
-
- private void checkMissingKeys(RefactoringStatus status) {
- for (int i= 0; i < fSubstitutions.length; i++) {
- NLSSubstitution substitution= fSubstitutions[i];
- if ((substitution.getValue() == null) && (substitution.getKey() != null)) {
- status.addWarning(NLSUIMessages.ExternalizeWizardPage_warning_keymissing);
- return;
- }
- }
- }
-
- private boolean conflictingKeys(NLSSubstitution substitution) {
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
- return substitution.isConflicting(fSubstitutions);
- }
- return false;
- }
-
- private void createTableComposite(Composite parent) {
- Composite comp= new Composite(parent, SWT.NONE);
- comp.setFont(parent.getFont());
-
- comp.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- FormLayout fl= new FormLayout();
- fl.marginWidth= 0;
- fl.marginHeight= 0;
- comp.setLayout(fl);
-
- Label l= new Label(comp, SWT.NONE);
- l.setText(NLSUIMessages.ExternalizeWizardPage_strings_to_externalize);
- FormData formData = new FormData();
- formData.left = new FormAttachment(0, 0);
- l.setLayoutData(formData);
-
- Control tableControl= createTable(comp);
- formData = new FormData();
- formData.top = new FormAttachment(l, 5);
- formData.left = new FormAttachment(0, 0);
- formData.right = new FormAttachment(100,0);
- formData.bottom = new FormAttachment(100,0);
- tableControl.setLayoutData(formData);
-
- fFilterCheckBox= new Button(comp, SWT.CHECK);
- fFilterCheckBox.setText(NLSUIMessages.ExternalizeWizardPage_filter_label);
- formData = new FormData();
- formData.right = new FormAttachment(100,0);
- fFilterCheckBox.setLayoutData(formData);
- fFilterCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- doFilterCheckBoxPressed();
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
- fFilterCheckBox.setSelection(hasNewOrMissingSubstitutions());
- }
-
- private boolean hasNewOrMissingSubstitutions() {
- for (int i= 0; i < fSubstitutions.length; i++) {
- NLSSubstitution curr= fSubstitutions[i];
- if (curr.getInitialState() == NLSSubstitution.INTERNALIZED) {
- return true;
- }
- if (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null) {
- return true;
- }
- }
- return false;
- }
-
- /**
- *
- */
- protected void doFilterCheckBoxPressed() {
- fTableViewer.refresh();
- }
-
- private Control createTable(Composite parent) {
- Composite c= new Composite(parent, SWT.NONE);
- GridLayout gl= new GridLayout();
- gl.numColumns= 2;
- gl.marginWidth= 0;
- gl.marginHeight= 0;
- c.setLayout(gl);
-
-
- fTable= new Table(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.BORDER);
- fTable.setFont(parent.getFont());
-
- GridData tableGD= new GridData(GridData.FILL_BOTH);
- tableGD.heightHint= SWTUtil.getTableHeightHint(fTable, ROW_COUNT);
- //tableGD.widthHint= 40;
- fTable.setLayoutData(tableGD);
-
- fTable.setLinesVisible(true);
-
- TableLayout layout= new TableLayout();
- fTable.setLayout(layout);
- fTable.setHeaderVisible(true);
-
- ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[SIZE];
- columnLayoutData[STATE_PROP]= new ColumnPixelData(18, false, true);
- columnLayoutData[KEY_PROP]= new ColumnWeightData(40, true);
- columnLayoutData[VAL_PROP]= new ColumnWeightData(40, true);
-
- for (int i= 0; i < fgTitles.length; i++) {
- TableColumn tc= new TableColumn(fTable, SWT.NONE, i);
- tc.setText(fgTitles[i]);
- layout.addColumnData(columnLayoutData[i]);
- tc.setResizable(columnLayoutData[i].resizable);
- }
-
- createButtonComposite(c);
- return c;
- }
-
- private void createButtonComposite(Composite parent) {
- Composite buttonComp= new Composite(parent, SWT.NONE);
- GridLayout gl= new GridLayout();
- gl.marginHeight= 0;
- gl.marginWidth= 0;
- buttonComp.setLayout(gl);
- buttonComp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- SelectionAdapter adapter= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handleButtonPressed(e.widget);
- }
- };
-
- fExternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Externalize_Selected, adapter);
- fIgnoreButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Ignore_Selected, adapter);
- fInternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Internalize_Selected, adapter);
-
- new Label(buttonComp, SWT.NONE); // separator
-
- fEditButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Edit_key_and_value, adapter);
- fRevertButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Revert_Selected, adapter);
- fRenameButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Rename_Keys, adapter);
-
- fEditButton.setEnabled(false);
- fRenameButton.setEnabled(false);
- buttonComp.pack();
- }
-
- /**
- * @param widget
- */
- protected void handleButtonPressed(Widget widget) {
- if (widget == fExternalizeButton) {
- setSelectedTasks(NLSSubstitution.EXTERNALIZED);
- } else if (widget == fIgnoreButton) {
- setSelectedTasks(NLSSubstitution.IGNORED);
- } else if (widget == fInternalizeButton) {
- setSelectedTasks(NLSSubstitution.INTERNALIZED);
- } else if (widget == fEditButton) {
- openEditButton(fTableViewer.getSelection());
- } else if (widget == fRevertButton) {
- revertStateOfSelection();
- } else if (widget == fRenameButton) {
- openRenameDialog();
- }
- }
-
- /**
- *
- */
- private void openRenameDialog() {
- IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
- List elementsToRename= getExternalizedElements(sel);
- RenameKeysDialog dialog= new RenameKeysDialog(getShell(), elementsToRename);
- if (dialog.open() == Window.OK) {
- fTableViewer.refresh();
- updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
- }
- }
-
- private void revertStateOfSelection() {
- List selection= getSelectedTableEntries();
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- NLSSubstitution substitution= (NLSSubstitution) iter.next();
- substitution.revert();
- }
- fTableViewer.refresh();
- updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
- }
-
- private Button createTaskButton(Composite parent, String label, SelectionAdapter adapter) {
- Button button= new Button(parent, SWT.PUSH);
- button.setText(label);
- button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- SWTUtil.setButtonDimensionHint(button);
- button.addSelectionListener(adapter);
- return button;
- }
-
- private void openEditButton(ISelection selection) {
- try {
- IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
- NLSSubstitution substitution= (NLSSubstitution) sel.getFirstElement();
- if (substitution == null) {
- return;
- }
-
- NLSInputDialog dialog= new NLSInputDialog(getShell(), substitution);
- if (dialog.open() == Window.CANCEL)
- return;
- KeyValuePair kvPair= dialog.getResult();
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
- substitution.setKey(kvPair.getKey());
- }
- substitution.setValue(kvPair.getValue());
- validateKeys(false);
- } finally {
- fTableViewer.refresh();
- fTableViewer.getControl().setFocus();
- fTableViewer.setSelection(selection);
- }
- }
-
- private List getSelectedTableEntries() {
- ISelection sel= fTableViewer.getSelection();
- if (sel instanceof IStructuredSelection)
- return((IStructuredSelection) sel).toList();
- else
- return Collections.EMPTY_LIST;
- }
-
- private void setSelectedTasks(int state) {
- Assert.isTrue(state == NLSSubstitution.EXTERNALIZED || state == NLSSubstitution.IGNORED || state == NLSSubstitution.INTERNALIZED);
- List selected= getSelectedTableEntries();
- String[] props= new String[]{PROPERTIES[STATE_PROP]};
- for (Iterator iter= selected.iterator(); iter.hasNext();) {
- NLSSubstitution substitution= (NLSSubstitution) iter.next();
- substitution.setState(state);
- if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
- substitution.generateKey(fSubstitutions);
- }
- }
- fTableViewer.update(selected.toArray(), props);
- fTableViewer.getControl().setFocus();
- updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
- }
-
- private void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection selection= (IStructuredSelection) event.getSelection();
- updateButtonStates(selection);
- updateSourceView(selection);
- }
-
- private void updateSourceView(IStructuredSelection selection) {
- NLSSubstitution first= (NLSSubstitution) selection.getFirstElement();
- if (first != null) {
- Region region= first.getNLSElement().getPosition();
- fSourceViewer.setSelectedRange(region.getOffset(), region.getLength());
- fSourceViewer.revealRange(region.getOffset(), region.getLength());
- }
- }
-
- private void updateButtonStates(IStructuredSelection selection) {
- fExternalizeButton.setEnabled(true);
- fIgnoreButton.setEnabled(true);
- fInternalizeButton.setEnabled(true);
- fRevertButton.setEnabled(true);
-
- if (containsOnlyElementsOfSameState(NLSSubstitution.EXTERNALIZED, selection)) {
- fExternalizeButton.setEnabled(false);
- }
-
- if (containsOnlyElementsOfSameState(NLSSubstitution.IGNORED, selection)) {
- fIgnoreButton.setEnabled(false);
- }
-
- if (containsOnlyElementsOfSameState(NLSSubstitution.INTERNALIZED, selection)) {
- fInternalizeButton.setEnabled(false);
- }
-
- if (!containsElementsWithChange(selection)) {
- fRevertButton.setEnabled(false);
- }
-
- fRenameButton.setEnabled(getExternalizedElements(selection).size() > 1);
- fEditButton.setEnabled(selection.size() == 1);
- }
-
- private boolean containsElementsWithChange(IStructuredSelection selection) {
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- NLSSubstitution substitution= (NLSSubstitution) iter.next();
- if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
- return true;
- }
- }
- return false;
- }
-
- private List getExternalizedElements(IStructuredSelection selection) {
- ArrayList res= new ArrayList();
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- NLSSubstitution substitution= (NLSSubstitution) iter.next();
- if (substitution.getState() == NLSSubstitution.EXTERNALIZED && !substitution.hasStateChanged()) {
- res.add(substitution);
- }
- }
- return res;
- }
-
- private boolean containsOnlyElementsOfSameState(int state, IStructuredSelection selection) {
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- NLSSubstitution substitution= (NLSSubstitution) iter.next();
- if (substitution.getState() != state) {
- return false;
- }
- }
- return true;
- }
-
- public boolean performFinish() {
- return super.performFinish();
- }
-
- public IWizardPage getNextPage() {
- return super.getNextPage();
- }
-
- public void dispose() {
- storeAccessorDescriptions();
- //widgets will be disposed. only need to null'em
- fPrefixField= null;
- fSourceViewer= null;
- fTable= null;
- fTableViewer= null;
- fEditButton= null;
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/MultiStateCellEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/MultiStateCellEditor.java
deleted file mode 100644
index 4bdd9430..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/MultiStateCellEditor.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-
-public class MultiStateCellEditor extends CellEditor {
-
- private int fValue;
- private final int fStateCount;
-
- /**
- * @param stateCount must be > 1
- * @param initialValue initialValue
- */
- public MultiStateCellEditor(Composite parent, int stateCount, int initialValue) {
- super(parent);
- Assert.isTrue(stateCount > 1, "incorrect state count"); //$NON-NLS-1$
- fStateCount= stateCount;
-
- Assert.isTrue(initialValue >= 0 && initialValue < stateCount, "incorrect initial value"); //$NON-NLS-1$
- fValue= initialValue;
-
- setValueValid(true);
- }
-
- /*
- * @see org.eclipse.jface.viewers.CellEditor#activate()
- */
- public void activate() {
- fValue= getNextValue(fStateCount, fValue);
- fireApplyEditorValue();
- }
-
- public static int getNextValue(int stateCount, int currentValue){
- Assert.isTrue(stateCount > 1, "incorrect state count"); //$NON-NLS-1$
- Assert.isTrue(currentValue >= 0 && currentValue < stateCount, "incorrect initial value"); //$NON-NLS-1$
- return (currentValue + 1) % stateCount;
- }
-
- /*
- * @see org.eclipse.jface.viewers.CellEditor#createControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createControl(Composite parent) {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.CellEditor#doGetValue()
- * @return the Integer value
- */
- protected Object doGetValue() {
- return new Integer(fValue);
- }
-
- /*
- * @see org.eclipse.jface.viewers.CellEditor#doSetFocus()
- */
- protected void doSetFocus() {
- // Ignore
- }
-
- /*
- * @see org.eclipse.jface.viewers.CellEditor#doSetValue(java.lang.Object)
- * @param value an Integer value
- * must be >=0 and < stateCount (value passed in the constructor)
- */
- protected void doSetValue(Object value) {
- Assert.isTrue(value instanceof Integer, "value must be Integer"); //$NON-NLS-1$
- fValue = ((Integer) value).intValue();
- Assert.isTrue(fValue >= 0 && fValue < fStateCount, "invalid value"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSAccessorConfigurationDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSAccessorConfigurationDialog.java
deleted file mode 100644
index 230d31d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSAccessorConfigurationDialog.java
+++ /dev/null
@@ -1,442 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.Separator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class NLSAccessorConfigurationDialog extends StatusDialog {
-
-
- private SourceFirstPackageSelectionDialogField fResourceBundlePackage;
- private StringButtonDialogField fResourceBundleFile;
- private SourceFirstPackageSelectionDialogField fAccessorPackage;
- private StringDialogField fAccessorClassName;
- private StringDialogField fSubstitutionPattern;
-
- private NLSRefactoring fRefactoring;
-
- private IStatus[] fStati;
-
- private static final int IDX_ACCESSOR_CLASS= 0;
- private static final int IDX_ACCESSOR_PACKAGE= 1;
- private static final int IDX_SUBST_PATTERN= 2;
- private static final int IDX_BUNDLE_NAME= 3;
- private static final int IDX_BUNDLE_PACKAGE= 4;
-
- private class AccessorAdapter implements IDialogFieldListener, IStringButtonAdapter {
- public void dialogFieldChanged(DialogField field) {
- validateAll();
- }
-
- public void changeControlPressed(DialogField field) {
- if (field == fResourceBundleFile) {
- browseForPropertyFile();
- } else if (field == fAccessorClassName) {
- browseForAccessorClass();
- }
- }
- }
-
-
- public NLSAccessorConfigurationDialog(Shell parent, NLSRefactoring refactoring) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fRefactoring= refactoring;
- fStati= new IStatus[] { StatusInfo.OK_STATUS, StatusInfo.OK_STATUS, StatusInfo.OK_STATUS, StatusInfo.OK_STATUS, StatusInfo.OK_STATUS };
-
- setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_title);
-
- AccessorAdapter updateListener= new AccessorAdapter();
-
- IJavaScriptUnit cu= refactoring.getCu();
-
- fAccessorPackage= new SourceFirstPackageSelectionDialogField(NLSUIMessages.NLSAccessorConfigurationDialog_accessor_path,
- NLSUIMessages.NLSAccessorConfigurationDialog_accessor_package,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse1,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse2,
- NLSUIMessages.NLSAccessorConfigurationDialog_default_package,
- NLSUIMessages.NLSAccessorConfigurationDialog_accessor_dialog_title,
- NLSUIMessages.NLSAccessorConfigurationDialog_accessor_dialog_message,
- NLSUIMessages.NLSAccessorConfigurationDialog_accessor_dialog_emtpyMessage,
- cu, updateListener, refactoring.getAccessorClassPackage());
-
- fAccessorClassName= createStringButtonField(NLSUIMessages.NLSAccessorConfigurationDialog_className,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse6, updateListener);
- fSubstitutionPattern= createStringField(NLSUIMessages.NLSAccessorConfigurationDialog_substitutionPattern, updateListener);
-
- fResourceBundlePackage= new SourceFirstPackageSelectionDialogField(NLSUIMessages.NLSAccessorConfigurationDialog_property_path,
- NLSUIMessages.NLSAccessorConfigurationDialog_property_package,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse3,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse4,
- NLSUIMessages.NLSAccessorConfigurationDialog_default_package,
- NLSUIMessages.NLSAccessorConfigurationDialog_property_dialog_title,
- NLSUIMessages.NLSAccessorConfigurationDialog_property_dialog_message,
- NLSUIMessages.NLSAccessorConfigurationDialog_property_dialog_emptyMessage,
- cu, updateListener, fRefactoring.getResourceBundlePackage());
-
- fResourceBundleFile= createStringButtonField(NLSUIMessages.NLSAccessorConfigurationDialog_property_file_name,
- NLSUIMessages.NLSAccessorConfigurationDialog_browse5, updateListener);
-
- initFields();
- }
-
- private void initFields() {
- initAccessorClassFields();
- String resourceBundleName= fRefactoring.getResourceBundleName();
- fResourceBundleFile.setText(resourceBundleName != null ? resourceBundleName : (NLSRefactoring.DEFAULT_PROPERTY_FILENAME + NLSRefactoring.PROPERTY_FILE_EXT));
- }
-
- private void initAccessorClassFields() {
- String accessorClassName= fRefactoring.getAccessorClassName();
-
- if (accessorClassName == null) {
- accessorClassName= NLSRefactoring.DEFAULT_ACCESSOR_CLASSNAME;
- }
- fAccessorClassName.setText(accessorClassName);
-
- fSubstitutionPattern.setText(fRefactoring.getSubstitutionPattern());
- }
-
- protected Control createDialogArea(Composite ancestor) {
- Composite parent= (Composite) super.createDialogArea(ancestor);
-
- final int nOfColumns= 4;
-
- initializeDialogUnits(ancestor);
-
- GridLayout layout= (GridLayout) parent.getLayout();
- layout.numColumns= nOfColumns;
- parent.setLayout(layout);
-
- createAccessorPart(parent, nOfColumns, convertWidthInCharsToPixels(40));
-
- Separator s= new Separator(SWT.SEPARATOR | SWT.HORIZONTAL);
- s.doFillIntoGrid(parent, nOfColumns);
-
- createPropertyPart(parent, nOfColumns, convertWidthInCharsToPixels(40));
-
- Dialog.applyDialogFont(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE);
- validateAll();
- return parent;
- }
-
-
- private void createAccessorPart(Composite parent, final int nOfColumns, int textWidth) {
- createLabel(parent, NLSUIMessages.NLSAccessorConfigurationDialog_resourceBundle_title, nOfColumns);
- fAccessorPackage.createControl(parent, nOfColumns, textWidth);
-
- fAccessorClassName.doFillIntoGrid(parent, nOfColumns);
- Text accessorClassText= fAccessorClassName.getTextControl(null);
- LayoutUtil.setWidthHint(accessorClassText, convertWidthInCharsToPixels(60));
- TextFieldNavigationHandler.install(accessorClassText);
-
- fSubstitutionPattern.doFillIntoGrid(parent, nOfColumns);
- Text substitutionPatternText= fSubstitutionPattern.getTextControl(null);
- LayoutUtil.setWidthHint(substitutionPatternText, convertWidthInCharsToPixels(60));
- TextFieldNavigationHandler.install(substitutionPatternText);
-
- fSubstitutionPattern.setEnabled(!fRefactoring.isEclipseNLS());
- }
-
- private void createPropertyPart(Composite parent, final int nOfColumns, final int textWidth) {
- createLabel(parent, NLSUIMessages.NLSAccessorConfigurationDialog_property_location, nOfColumns);
- fResourceBundlePackage.createControl(parent, nOfColumns, textWidth);
-
- fResourceBundleFile.doFillIntoGrid(parent, nOfColumns);
- LayoutUtil.setWidthHint(fResourceBundleFile.getTextControl(null), convertWidthInCharsToPixels(60));
- }
-
- private void createLabel(Composite parent, final String text, final int N_OF_COLUMNS) {
- Separator label= new Separator(SWT.NONE);
- ((Label) label.getSeparator(parent)).setText(text);
- GC gc= new GC(parent);
- int height= gc.stringExtent(text).y;
- gc.dispose();
- label.doFillIntoGrid(parent, N_OF_COLUMNS, height);
- }
-
- private void browseForPropertyFile() {
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaScriptElementLabelProvider());
- dialog.setIgnoreCase(false);
- dialog.setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_Property_File_Selection);
- dialog.setMessage(NLSUIMessages.NLSAccessorConfigurationDialog_Choose_the_property_file);
- dialog.setElements(createFileListInput());
- dialog.setFilter('*' + NLSRefactoring.PROPERTY_FILE_EXT);
- if (dialog.open() == Window.OK) {
- IFile selectedFile= (IFile) dialog.getFirstResult();
- if (selectedFile != null)
- fResourceBundleFile.setText(selectedFile.getName());
- }
- }
-
- protected void browseForAccessorClass() {
- IProgressService service= PlatformUI.getWorkbench().getProgressService();
- IPackageFragmentRoot root= fAccessorPackage.getSelectedFragmentRoot();
-
- IJavaScriptSearchScope scope= root != null ? SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { root }) : SearchEngine.createWorkspaceScope();
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog (getShell(), false,
- service, scope, IJavaScriptSearchConstants.CLASS);
- dialog.setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_Accessor_Selection);
- dialog.setMessage(NLSUIMessages.NLSAccessorConfigurationDialog_Choose_the_accessor_file);
- dialog.setInitialPattern("*Messages"); //$NON-NLS-1$
- if (dialog.open() == Window.OK) {
- IType selectedType= (IType) dialog.getFirstResult();
- if (selectedType != null) {
- fAccessorClassName.setText(selectedType.getElementName());
- fAccessorPackage.setSelected(selectedType.getPackageFragment());
- }
- }
-
-
- }
-
- private Object[] createFileListInput() {
- try {
-
- IPackageFragment fPkgFragment= fResourceBundlePackage.getSelected();
- if (fPkgFragment == null)
- return new Object[0];
- List result= new ArrayList(1);
- Object[] nonjava= fPkgFragment.getNonJavaScriptResources();
- for (int i= 0; i < nonjava.length; i++) {
- if (isPropertyFile(nonjava[i]))
- result.add(nonjava[i]);
- }
- return result.toArray();
-
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, NLSUIMessages.NLSAccessorConfigurationDialog_externalizing, NLSUIMessages .NLSAccessorConfigurationDialog_exception);
- return new Object[0];
- }
- }
-
- private static boolean isPropertyFile(Object o) {
- if (!(o instanceof IFile))
- return false;
- IFile file= (IFile) o;
- return (NLSRefactoring.PROPERTY_FILE_EXT.equals('.' + file.getFileExtension()));
- }
-
- /**
- * checks all entered values delegates to the specific validate methods these methods
- * update the refactoring
- */
- private void validateAll() {
- validateSubstitutionPattern();
-
- validateAccessorClassName();
- checkPackageFragment();
-
- validatePropertyFilename();
- validatePropertyPackage();
-
- updateStatus(StatusUtil.getMostSevere(fStati));
- }
-
- private void validateAccessorClassName() {
- String className= fAccessorClassName.getText();
-
- IStatus status= JavaScriptConventions.validateJavaScriptTypeName(className);
- if (status.getSeverity() == IStatus.ERROR) {
- setInvalid(IDX_ACCESSOR_CLASS, status.getMessage());
- return;
- }
-
- if (className.indexOf('.') != -1) {
- setInvalid(IDX_ACCESSOR_CLASS, NLSUIMessages.NLSAccessorConfigurationDialog_no_dot);
- return;
- }
-
- setValid(IDX_ACCESSOR_CLASS);
- }
-
- private void validatePropertyFilename() {
- String fileName= fResourceBundleFile.getText();
- if ((fileName == null) || (fileName.length() == 0)) {
- setInvalid(IDX_BUNDLE_NAME, NLSUIMessages.NLSAccessorConfigurationDialog_enter_name);
- return;
- }
-
- if (!fileName.endsWith(NLSRefactoring.PROPERTY_FILE_EXT)) {
- setInvalid(IDX_BUNDLE_NAME, Messages.format(NLSUIMessages.NLSAccessorConfigurationDialog_file_name_must_end, NLSRefactoring.PROPERTY_FILE_EXT));
- return;
- }
-
- setValid(IDX_BUNDLE_NAME);
- }
-
- private void validatePropertyPackage() {
-
- IPackageFragmentRoot root= fResourceBundlePackage.getSelectedFragmentRoot();
- if ((root == null) || !root.exists()) {
- setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_property_package_root_invalid);
- return;
- }
-
- IPackageFragment fragment= fResourceBundlePackage.getSelected();
- if ((fragment == null) || !fragment.exists()) {
- setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_property_package_invalid);
- return;
- }
-
- String pkgName= fragment.getElementName();
-
- IStatus status= JavaScriptConventions.validatePackageName(pkgName);
- if ((pkgName.length() > 0) && (status.getSeverity() == IStatus.ERROR)) {
- setInvalid(IDX_BUNDLE_PACKAGE, status.getMessage());
- return;
- }
-
- IPath pkgPath= new Path(pkgName.replace('.', IPath.SEPARATOR)).makeRelative();
-
- IJavaScriptProject project= fRefactoring.getCu().getJavaScriptProject();
- try {
- IJavaScriptElement element= project.findElement(pkgPath);
- if (element == null || !element.exists()) {
- setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_must_exist);
- return;
- }
- IPackageFragment fPkgFragment= (IPackageFragment) element;
- if (!PackageBrowseAdapter.canAddPackage(fPkgFragment)) {
- setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
- return;
- }
- if (!PackageBrowseAdapter.canAddPackageRoot((IPackageFragmentRoot) fPkgFragment.getParent())) {
- setInvalid(IDX_BUNDLE_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_incorrect_package);
- return;
- }
- } catch (JavaScriptModelException e) {
- setInvalid(IDX_BUNDLE_PACKAGE, e.getStatus().getMessage());
- return;
- }
-
- setValid(IDX_BUNDLE_PACKAGE);
- }
-
- private void checkPackageFragment() {
- IPackageFragmentRoot root= fAccessorPackage.getSelectedFragmentRoot();
- if ((root == null) || !root.exists()) {
- setInvalid(IDX_ACCESSOR_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_accessor_package_root_invalid);
- return;
- }
-
- IPackageFragment fragment= fAccessorPackage.getSelected();
- if ((fragment == null) || !fragment.exists()) {
- setInvalid(IDX_ACCESSOR_PACKAGE, NLSUIMessages.NLSAccessorConfigurationDialog_accessor_package_invalid);
- return;
- }
- setValid(IDX_ACCESSOR_PACKAGE);
- }
-
- private void validateSubstitutionPattern() {
- if ((fSubstitutionPattern.getText() == null) || (fSubstitutionPattern.getText().length() == 0)) {
- setInvalid(IDX_SUBST_PATTERN, NLSUIMessages.NLSAccessorConfigurationDialog_substitution_pattern_missing);
- } else {
- setValid(IDX_SUBST_PATTERN);
- }
- }
-
- private void setInvalid(int idx, String msg) {
- fStati[idx]= new StatusInfo(IStatus.ERROR, msg);
- }
-
- private void setValid(int idx) {
- fStati[idx]= StatusInfo.OK_STATUS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- updateRefactoring();
- super.okPressed();
- }
-
-
- void updateRefactoring() {
- fRefactoring.setAccessorClassPackage(fAccessorPackage.getSelected());
- fRefactoring.setAccessorClassName(fAccessorClassName.getText());
-
- fRefactoring.setResourceBundleName(fResourceBundleFile.getText());
- fRefactoring.setResourceBundlePackage(fResourceBundlePackage.getSelected());
-
- if (!fRefactoring.isEclipseNLS())
- fRefactoring.setSubstitutionPattern(fSubstitutionPattern.getText());
-
- fRefactoring.setIsEclipseNLS(fRefactoring.detectIsEclipseNLS());
- }
-
- private StringDialogField createStringField(String label, AccessorAdapter updateListener) {
- StringDialogField field= new StringDialogField();
- field.setDialogFieldListener(updateListener);
- field.setLabelText(label);
- return field;
- }
-
- private StringButtonDialogField createStringButtonField(String label, String button, AccessorAdapter adapter) {
- StringButtonDialogField field= new StringButtonDialogField(adapter);
- field.setDialogFieldListener(adapter);
- field.setLabelText(label);
- field.setButtonLabel(button);
- return field;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.java
deleted file mode 100644
index 2e13833f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class NLSUIMessages extends NLS {
-
- private static final String BUNDLE_NAME= NLSUIMessages.class.getName();
-
- private NLSUIMessages() {
- // Do not instantiate
- }
-
- public static String ExternalizeWizard_name;
- public static String ExternalizeWizard_select;
- public static String ExternalizeWizardPage_title;
- public static String ExternalizeWizardPage_description;
- public static String ExternalizeWizardPage_exception_title;
- public static String ExternalizeWizardPage_exception_message;
- public static String ExternalizeWizardPage_common_prefix;
- public static String ExternalizeWizardPage_context;
- public static String ExternalizeWizardPage_strings_to_externalize;
- public static String ExternalizeWizardPage_Externalize_Selected;
- public static String ExternalizeWizardPage_Ignore_Selected;
- public static String ExternalizeWizardPage_Internalize_Selected;
- public static String ExternalizeWizardPage_Revert_Selected;
- public static String ExternalizeWizardPage_isEclipseNLSCheckbox;
- public static String ExternalizeWizardPage_Rename_Keys;
- public static String ExternalizeWizardPage_NLSInputDialog_Label;
- public static String ExternalizeWizardPage_NLSInputDialog_Enter_key;
- public static String ExternalizeWizardPage_NLSInputDialog_ext_Label;
- public static String ExternalizeWizardPage_NLSInputDialog_Enter_value;
- public static String ExternalizeWizardPage_NLSInputDialog_Title;
- public static String ExternalizeWizardPage_NLSInputDialog_Error_empty_key;
- public static String ExternalizeWizardPage_NLSInputDialog_Error_invalid_key;
- public static String ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key;
- public static String NLSAccessorConfigurationDialog_browse1;
- public static String NLSAccessorConfigurationDialog_browse2;
- public static String NLSAccessorConfigurationDialog_browse3;
- public static String NLSAccessorConfigurationDialog_browse4;
- public static String NLSAccessorConfigurationDialog_browse5;
- public static String NLSAccessorConfigurationDialog_browse6;
- public static String NLSAccessorConfigurationDialog_property_file_name;
- public static String NLSAccessorConfigurationDialog_substitutionPattern;
- public static String NLSAccessorConfigurationDialog_externalizing;
- public static String NLSAccessorConfigurationDialog_exception;
- public static String NLSAccessorConfigurationDialog_must_exist;
- public static String NLSAccessorConfigurationDialog_incorrect_package;
- public static String NLSAccessorConfigurationDialog_enter_name;
- public static String NLSAccessorConfigurationDialog_file_name_must_end;
- public static String NLSAccessorConfigurationDialog_className;
- public static String NLSAccessorConfigurationDialog_no_dot;
- public static String NLSAccessorConfigurationDialog_default_package;
- public static String NLSAccessorConfigurationDialog_default;
- public static String NLSAccessorConfigurationDialog_property_location;
- public static String NLSAccessorConfigurationDialog_Choose_the_property_file;
- public static String NLSAccessorConfigurationDialog_Property_File_Selection;
- public static String NLSAccessorConfigurationDialog_Choose_the_accessor_file;
- public static String NLSAccessorConfigurationDialog_Accessor_Selection;
- public static String NLSAccessorConfigurationDialog_accessor_path;
- public static String NLSAccessorConfigurationDialog_accessor_package;
- public static String NLSAccessorConfigurationDialog_resourceBundle_title;
- public static String NLSAccessorConfigurationDialog_property_path;
- public static String NLSAccessorConfigurationDialog_property_package;
- public static String NLSAccessorConfigurationDialog_accessor_package_root_invalid;
- public static String NLSAccessorConfigurationDialog_accessor_package_invalid;
- public static String NLSAccessorConfigurationDialog_property_package_root_invalid;
- public static String NLSAccessorConfigurationDialog_property_package_invalid;
- public static String NLSAccessorConfigurationDialog_substitution_pattern_missing;
- public static String NLSAccessorConfigurationDialog_accessor_dialog_title;
- public static String NLSAccessorConfigurationDialog_accessor_dialog_message;
- public static String NLSAccessorConfigurationDialog_accessor_dialog_emtpyMessage;
- public static String NLSAccessorConfigurationDialog_property_dialog_title;
- public static String NLSAccessorConfigurationDialog_property_dialog_message;
- public static String NLSAccessorConfigurationDialog_property_dialog_emptyMessage;
- public static String ExternalizeWizardPage_key;
- public static String ExternalizeWizardPage_value;
- public static String ExternalizeWizardPage_Edit_key_and_value;
- public static String ExternalizeWizardPage_accessorclass_label;
- public static String ExternalizeWizardPage_configure_button;
- public static String ExternalizeWizardPage_warning_conflicting;
- public static String ExternalizeWizardPage_warning_keymissing;
- public static String ExternalizeWizardPage_warning_keyInvalid;
- public static String ExternalizeWizardPage_warning_EclipseNLS_keyInvalid;
- public static String ExternalizeWizardPage_filter_label;
- public static String NLSAccessorConfigurationDialog_title;
- public static String PackageBrowseAdapter_package_selection;
- public static String PackageBrowseAdapter_choose_package;
- public static String RenameKeysDialog_title;
- public static String RenameKeysDialog_description_noprefix;
- public static String RenameKeysDialog_description_withprefix;
- public static String SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_title;
- public static String SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_description;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, NLSUIMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties
deleted file mode 100644
index bb7f50da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties
+++ /dev/null
@@ -1,97 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-ExternalizeWizard_name=Externalize Strings
-ExternalizeWizard_select=Select strings to externalize
-
-ExternalizeWizardPage_title=Externalize Strings in ''{0}''
-ExternalizeWizardPage_description= Externalizes strings from code into a properties file. The auto-generated keys should be adjusted.
-ExternalizeWizardPage_exception_title=Externalizing Strings
-ExternalizeWizardPage_exception_message=Unexpected exception while creating UI. See log for a detailed error description.
-ExternalizeWizardPage_common_prefix=&Enter common prefix for generated keys (optional):
-ExternalizeWizardPage_context=Conte&xt:
-ExternalizeWizardPage_strings_to_externalize=St&rings to externalize:
-ExternalizeWizardPage_Externalize_Selected=Externa&lize
-ExternalizeWizardPage_Ignore_Selected=&Ignore
-ExternalizeWizardPage_Internalize_Selected=In&ternalize
-ExternalizeWizardPage_Revert_Selected=Re&vert
-ExternalizeWizardPage_isEclipseNLSCheckbox=&Use Eclipse's string externalization mechanism
-
-ExternalizeWizardPage_Rename_Keys=Rename &keys...
-ExternalizeWizardPage_NLSInputDialog_Label=Enter the new value:
-ExternalizeWizardPage_NLSInputDialog_Enter_key=New &key:
-ExternalizeWizardPage_NLSInputDialog_ext_Label=Enter the new key and value:
-ExternalizeWizardPage_NLSInputDialog_Enter_value=New &value:
-ExternalizeWizardPage_NLSInputDialog_Title=Edit Entry
-ExternalizeWizardPage_NLSInputDialog_Error_empty_key=Key cannot be empty.
-ExternalizeWizardPage_NLSInputDialog_Error_invalid_key=Key contains white spaces.
-ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key=Key is not a valid Java identifier.
-NLSAccessorConfigurationDialog_browse1=&Browse...
-NLSAccessorConfigurationDialog_browse2=B&rowse...
-NLSAccessorConfigurationDialog_browse3=Br&owse...
-NLSAccessorConfigurationDialog_browse4=Bro&wse...
-NLSAccessorConfigurationDialog_browse5=Brows&e...
-NLSAccessorConfigurationDialog_browse6=Brow&se...
-NLSAccessorConfigurationDialog_property_file_name=Propert&y file name:
-NLSAccessorConfigurationDialog_substitutionPattern=S&ubstitution pattern:
-
-NLSAccessorConfigurationDialog_externalizing=Externalizing Strings
-NLSAccessorConfigurationDialog_exception=Unexpected exception while creating the package list. See log for a detailed error description.
-NLSAccessorConfigurationDialog_must_exist=The package does not exist in this project.
-NLSAccessorConfigurationDialog_incorrect_package=Incorrect package.
-NLSAccessorConfigurationDialog_enter_name=The property file is invalid.
-NLSAccessorConfigurationDialog_file_name_must_end=The property file name must end with ''{0}''.
-NLSAccessorConfigurationDialog_className=&Class name:
-NLSAccessorConfigurationDialog_no_dot=Class name should not contain a dot (.).
-NLSAccessorConfigurationDialog_default_package=(default package)
-NLSAccessorConfigurationDialog_default= (default)
-NLSAccessorConfigurationDialog_property_location=Property file location and name:
-NLSAccessorConfigurationDialog_Choose_the_property_file=&Choose the property file:
-NLSAccessorConfigurationDialog_Property_File_Selection=Property File Selection
-NLSAccessorConfigurationDialog_Choose_the_accessor_file=&Choose the accessor class:
-NLSAccessorConfigurationDialog_Accessor_Selection=Accessor class selection
-NLSAccessorConfigurationDialog_accessor_path=Source fol&der:
-NLSAccessorConfigurationDialog_accessor_package=Pac&kage:
-NLSAccessorConfigurationDialog_resourceBundle_title=Resource bundle accessor class (will be created if it does not exist):
-NLSAccessorConfigurationDialog_property_path=Source fo&lder:
-NLSAccessorConfigurationDialog_property_package=P&ackage:
-NLSAccessorConfigurationDialog_accessor_package_root_invalid=The source folder for the accessor class is invalid.
-NLSAccessorConfigurationDialog_accessor_package_invalid=The package for the accessor class is invalid.
-NLSAccessorConfigurationDialog_property_package_root_invalid=The source folder for the resource bundle is invalid.
-NLSAccessorConfigurationDialog_property_package_invalid=The specified package for the resource bundle is invalid.
-NLSAccessorConfigurationDialog_substitution_pattern_missing=The substitution pattern is invalid.
-NLSAccessorConfigurationDialog_accessor_dialog_title=Package Selection
-NLSAccessorConfigurationDialog_accessor_dialog_message=&Choose the destination package:
-NLSAccessorConfigurationDialog_accessor_dialog_emtpyMessage=No packages available.
-NLSAccessorConfigurationDialog_property_dialog_title=Package Selection
-NLSAccessorConfigurationDialog_property_dialog_message=&Choose the destination package:
-NLSAccessorConfigurationDialog_property_dialog_emptyMessage=No packages available.
-
-ExternalizeWizardPage_key=Key
-ExternalizeWizardPage_value=Value
-ExternalizeWizardPage_Edit_key_and_value=E&dit...
-ExternalizeWizardPage_accessorclass_label=&Accessor class:
-ExternalizeWizardPage_configure_button=&Configure...
-ExternalizeWizardPage_warning_conflicting=Conflicting entries: Same key but different values
-ExternalizeWizardPage_warning_keymissing=Entry is missing in property file.
-ExternalizeWizardPage_warning_keyInvalid=Some keys are invalid.
-ExternalizeWizardPage_warning_EclipseNLS_keyInvalid=Some keys are not valid Java identifiers.
-ExternalizeWizardPage_filter_label=Filter all exi&sting ignored and externalized entries
-NLSAccessorConfigurationDialog_title=Configure Accessor Class
-
-PackageBrowseAdapter_package_selection=Package Selection
-PackageBrowseAdapter_choose_package=&Choose a package:
-
-RenameKeysDialog_title=Rename Keys
-RenameKeysDialog_description_noprefix=Enter new prefix: (selected entries do not share a prefix)
-RenameKeysDialog_description_withprefix=Enter replacement prefix for
-SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_title=Source Folder Selection
-SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_description=&Choose a source folder:
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageBrowseAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageBrowseAdapter.java
deleted file mode 100644
index 81445a45..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageBrowseAdapter.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-
-public class PackageBrowseAdapter implements IStringButtonAdapter {
-
- PackageSelectionDialogButtonField fReceiver;
- private IJavaScriptUnit fCu;
-
- public PackageBrowseAdapter(IJavaScriptUnit unit) {
- fCu = unit;
- }
-
- public void setReceiver(PackageSelectionDialogButtonField receiver) {
- fReceiver = receiver;
- }
-
- public void changeControlPressed(DialogField field) {
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(
- Display.getCurrent().getActiveShell(), new JavaScriptElementLabelProvider());
- dialog.setIgnoreCase(false);
- dialog.setTitle(NLSUIMessages.PackageBrowseAdapter_package_selection);
- dialog.setMessage(NLSUIMessages.PackageBrowseAdapter_choose_package);
- dialog.setElements(createPackageListInput(fCu, null));
- if (dialog.open() == Window.OK) {
- IPackageFragment selectedPackage= (IPackageFragment)dialog.getFirstResult();
- if (selectedPackage != null) {
- fReceiver.setPackage(selectedPackage);
- }
- }
- }
- public static Object[] createPackageListInput(IJavaScriptUnit cu, String elementNameMatch){
- try{
- IJavaScriptProject project= cu.getJavaScriptProject();
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- List result= new ArrayList();
- HashMap entered =new HashMap();
- for (int i= 0; i < roots.length; i++){
- if (canAddPackageRoot(roots[i])){
- getValidPackages(roots[i], result, entered, elementNameMatch);
- }
- }
- return result.toArray();
- } catch (JavaScriptModelException e){
- JavaScriptPlugin.log(e);
- return new Object[0];
- }
- }
-
- static boolean canAddPackageRoot(IPackageFragmentRoot root) throws JavaScriptModelException{
- if (! root.exists())
- return false;
- if (root.isArchive())
- return false;
- if (root.isExternal())
- return false;
- if (root.isReadOnly())
- return false;
- if (! root.isStructureKnown())
- return false;
- return true;
- }
-
- static void getValidPackages(IPackageFragmentRoot root, List result, HashMap entered, String elementNameMatch) throws JavaScriptModelException {
- IJavaScriptElement[] children= null;
- try {
- children= root.getChildren();
- } catch (JavaScriptModelException e){
- return;
- }
- for (int i= 0; i < children.length; i++){
- if (children[i] instanceof IPackageFragment) {
- IPackageFragment packageFragment = (IPackageFragment)children[i];
- String packageName = packageFragment.getElementName();
-
- if ((entered != null) && (entered.containsKey(packageName)) == true) {
- continue;
- }
-
- if (canAddPackage(packageFragment)) {
- if ((elementNameMatch == null) || (elementNameMatch.equals(packageName))) {
- result.add(packageFragment);
- if (entered != null) {
- entered.put(packageName, null);
- }
- }
- }
- }
- }
- }
-
- static boolean canAddPackage(IPackageFragment p) throws JavaScriptModelException{
- if (! p.exists())
- return false;
- if (p.isReadOnly())
- return false;
- if (! p.isStructureKnown())
- return false;
- return true;
- }
-
- public static List searchAllPackages(IJavaScriptProject project, String matcher) {
- try{
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- List result= new ArrayList();
- for (int i= 0; i < roots.length; i++){
- if (canAddPackageRoot(roots[i])){
- getValidPackages(roots[i], result, null, matcher);
- }
- }
- return result;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return new ArrayList(0);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageFragmentSelection.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageFragmentSelection.java
deleted file mode 100644
index ebd983b9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageFragmentSelection.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
-
-class PackageFragmentSelection extends StringButtonStatusDialogField implements SourceChangeListener {
-
- private final SourceFirstPackageSelectionDialogField fDialogField;
- private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
- private IDialogFieldListener fUpdateListener;
-
- public PackageFragmentSelection(SourceFirstPackageSelectionDialogField field, String packageLabel, String browseLabel,
- String statusHint, IStringButtonAdapter adapter) {
- super(adapter);
- fDialogField= field;
- setLabelText(packageLabel);
- setButtonLabel(browseLabel);
- setStatusWidthHint(statusHint);
- fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
- }
-
- public void setUpdateListener(IDialogFieldListener updateListener) {
- fUpdateListener= updateListener;
- }
-
- public Control[] doFillIntoGrid(Composite parent, int nColumns, int textWidth) {
- Control[] res= super.doFillIntoGrid(parent, nColumns);
-
- final Text text= getTextControl(null);
- text.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- updateListener();
- }
- });
- LayoutUtil.setWidthHint(text, textWidth);
- LayoutUtil.setHorizontalGrabbing(text);
- ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
- TextFieldNavigationHandler.install(text);
-
- return res;
- }
-
- public void setPackageFragment(IPackageFragment fragment) {
- if (fragment != null) {
- setText(fragment.getElementName());
- }
-
- updateListener();
- }
-
- private void updateListener() {
- if (fUpdateListener != null) {
- fUpdateListener.dialogFieldChanged(this);
- }
- }
-
- public IPackageFragment getPackageFragment() {
- return calculateFragment(fDialogField.getSelectedFragmentRoot());
- }
-
- private IPackageFragment calculateFragment(IPackageFragmentRoot root) {
- if (root == null) {
- return null;
- } else {
- return root.getPackageFragment(getText());
- }
- }
-
- public void sourceRootChanged(IPackageFragmentRoot newRoot) {
- fCurrPackageCompletionProcessor.setPackageFragmentRoot(newRoot);
-
- setPackageFragment(calculateFragment(newRoot));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionDialogButtonField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionDialogButtonField.java
deleted file mode 100644
index 19fb6ab8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionDialogButtonField.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public final class PackageSelectionDialogButtonField extends StringButtonDialogField {
-
- private IPackageFragment fPackageFragment;
-
- public PackageSelectionDialogButtonField(String label, String button, PackageBrowseAdapter adapter, IJavaScriptProject root) {
- super(adapter);
- setContentAssistProcessor(new JavaPackageCompletionProcessor(new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_ROOT)));
-
- IPackageFragmentRoot[] roots;
- try {
- roots= root.getAllPackageFragmentRoots();
- ((JavaPackageCompletionProcessor)getContentAssistProcessor()).setPackageFragmentRoot(roots[0]);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- // if exception no content assist .. but thats no problem
- }
- setLabelText(label);
- setButtonLabel(button);
- adapter.setReceiver(this);
- }
-
- public void setPackage(IPackageFragment packageFragment) {
- fPackageFragment= packageFragment;
- if (fPackageFragment != null) {
- setText(fPackageFragment.getElementName());
-
- JavaPackageCompletionProcessor contentAssist= (JavaPackageCompletionProcessor)getContentAssistProcessor();
- contentAssist.setPackageFragmentRoot((IPackageFragmentRoot)packageFragment.getParent());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionStringButtonAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionStringButtonAdapter.java
deleted file mode 100644
index 921826e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/PackageSelectionStringButtonAdapter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-class PackageSelectionStringButtonAdapter implements IStringButtonAdapter {
-
- private final SourceFirstPackageSelectionDialogField fPackageSelectionField;
- private String fEmtpyListMessage;
- private String fMessage;
- private String fTitle;
-
- PackageSelectionStringButtonAdapter(SourceFirstPackageSelectionDialogField field, String title, String message,
- String emtpyListMessage) {
- fPackageSelectionField= field;
- fTitle= title;
- fMessage= message;
- fEmtpyListMessage= emtpyListMessage;
- }
-
- public void changeControlPressed(DialogField field) {
- IPackageFragmentRoot root= fPackageSelectionField.getSelectedFragmentRoot();
-
- IJavaScriptElement[] packages= null;
- try {
- if (root != null && root.exists()) {
- packages= root.getChildren();
- }
- } catch (JavaScriptModelException e) {
- // no need to react
- }
-
- if (packages == null) {
- packages= new IJavaScriptElement[0];
- }
-
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(field.getLabelControl(null).getShell(),
- new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT));
- dialog.setIgnoreCase(true);
-
- dialog.setTitle(fTitle);
- dialog.setMessage(fMessage);
- dialog.setEmptyListMessage(fEmtpyListMessage);
- dialog.setElements(packages);
-
- // TODO initial selection
- // List selection = new ArrayList();
- // selection.add(fPackageSelectionField.fPackageSelection.getPackageFragment());
- // dialog.setInitialElementSelections(selection);
-
- if (dialog.open() == Window.OK) {
- IPackageFragment fragment= (IPackageFragment)dialog.getFirstResult();
- fPackageSelectionField.setSelected(fragment);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/RenameKeysDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/RenameKeysDialog.java
deleted file mode 100644
index 6d9f9a6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/RenameKeysDialog.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import java.util.List;
-
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSSubstitution;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-/**
- *
- */
-public class RenameKeysDialog extends StatusDialog {
-
- private StringDialogField fNameField;
- private List fSelectedSubstitutions;
- private int fCommonPrefixLength;
-
- /**
- * @param parent
- */
- public RenameKeysDialog(Shell parent, List selectedSubstitutions) {
- super(parent);
- setTitle(NLSUIMessages.RenameKeysDialog_title);
-
- fSelectedSubstitutions= selectedSubstitutions;
- String prefix= getInitialPrefix(selectedSubstitutions);
- fCommonPrefixLength= prefix.length();
-
- fNameField= new StringDialogField();
- fNameField.setText(prefix);
-
- if (prefix.length() == 0) {
- fNameField.setLabelText(NLSUIMessages.RenameKeysDialog_description_noprefix);
- } else {
- fNameField.setLabelText(NLSUIMessages.RenameKeysDialog_description_withprefix + prefix + ':');
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- fNameField.doFillIntoGrid(composite, 2);
- LayoutUtil.setHorizontalGrabbing(fNameField.getTextControl(null));
- return composite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- */
- protected void okPressed() {
- String prefix= fNameField.getText();
- for (int i= 0; i < fSelectedSubstitutions.size(); i++) {
- NLSSubstitution sub= (NLSSubstitution) fSelectedSubstitutions.get(i);
- String newKey= prefix + sub.getKey().substring(fCommonPrefixLength);
- sub.setKey(newKey);
- }
- super.okPressed();
- }
-
- private String getInitialPrefix(List selectedSubstitutions) {
- String prefix= null;
- for (int i= 0; i < selectedSubstitutions.size(); i++) {
- NLSSubstitution sub= (NLSSubstitution) selectedSubstitutions.get(i);
- String curr= sub.getKey();
- if (prefix == null) {
- prefix= curr;
- } else if (!curr.startsWith(prefix)) {
- prefix= getCommonPrefix(prefix, curr);
- if (prefix.length() == 0) {
- return prefix;
- }
- }
- }
- return prefix;
- }
-
- private String getCommonPrefix(String a, String b) {
- String shorter= a.length() <= b.length() ? a : b;
- int len= shorter.length();
- for (int i= 0; i < len; i++) {
- if (a.charAt(i) != b.charAt(i)) {
- return a.substring(0, i);
- }
- }
- return shorter;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceChangeListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceChangeListener.java
deleted file mode 100644
index 473b0bb4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceChangeListener.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-public interface SourceChangeListener {
-
- public void sourceRootChanged(IPackageFragmentRoot newRoot);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceContainerDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceContainerDialog.java
deleted file mode 100644
index 42af79b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceContainerDialog.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-public class SourceContainerDialog extends ElementTreeSelectionDialog {
-
- private class PackageAndProjectSelectionValidator extends TypedElementSelectionValidator {
-
- public PackageAndProjectSelectionValidator() {
- super(new Class[]{IPackageFragmentRoot.class},false);
- }
-
- public boolean isSelectedValid(Object element) {
- try {
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject) element;
- IPath path= jproject.getProject().getFullPath();
- return (jproject.findPackageFragmentRoot(path) != null);
- } else
- if (element instanceof IPackageFragmentRoot) {
- return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
- }
- return true;
- } catch (JavaScriptModelException e) {
- // fall through returning false
- }
- return false;
- }
- }
-
- /**
- * A TypedViewerFilter that accepts only PackageFragments and JavaProjects.
- * PackageFragments are only accepted if they are of the kind K_SOURCE.
- */
- private class JavaTypedViewerFilter extends TypedViewerFilter {
-
- public JavaTypedViewerFilter() {
- super(new Class[]{IPackageFragmentRoot.class, IJavaScriptProject.class});
- }
-
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot fragmentRoot= (IPackageFragmentRoot)element;
- try {
- return (fragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE);
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
- return super.select(viewer, parent, element);
- }
- }
-
- private SourceContainerDialog(Shell shell) {
- super(shell,new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT),new StandardJavaScriptElementContentProvider());
- setValidator(new PackageAndProjectSelectionValidator());
- setComparator(new JavaScriptElementComparator());
- setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
- setMessage(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
- addFilter(new JavaTypedViewerFilter());
- }
-
- public static IPackageFragmentRoot getSourceContainer(Shell shell, IWorkspaceRoot workspaceRoot, IJavaScriptElement initElement) {
- SourceContainerDialog dialog= new SourceContainerDialog(shell);
- dialog.setInput(JavaScriptCore.create(workspaceRoot));
- dialog.setInitialSelection(initElement);
-
- if (dialog.open() == Window.OK) {
- Object element= dialog.getFirstResult();
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject) element;
- return jproject.getPackageFragmentRoot(jproject.getProject());
- } else
- if (element instanceof IPackageFragmentRoot) {
- return (IPackageFragmentRoot) element;
- }
- return null;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFirstPackageSelectionDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFirstPackageSelectionDialogField.java
deleted file mode 100644
index f6be3758..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFirstPackageSelectionDialogField.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-class SourceFirstPackageSelectionDialogField {
-
- private SourceFolderSelectionDialogButtonField fSourceFolderSelection;
- private PackageFragmentSelection fPackageSelection;
- private Shell fShell;
-
- public SourceFirstPackageSelectionDialogField(String sourceLabel, String packageLabel, String browseLabel1,
- String browseLabel2, String statusHint, String dialogTitle, String dialogMessage, String dialogEmptyMessage,
- IJavaScriptUnit cu, IDialogFieldListener updateListener, IPackageFragment fragment) {
- fSourceFolderSelection= new SourceFolderSelectionDialogButtonField(sourceLabel, browseLabel1, new SFStringButtonAdapter());
-
- fPackageSelection= new PackageFragmentSelection(this, packageLabel, browseLabel2, statusHint,
- new PackageSelectionStringButtonAdapter(this, dialogTitle, dialogMessage, dialogEmptyMessage));
- fPackageSelection.setDialogFieldListener(new PackageSelectionDialogFieldListener());
-
- fSourceFolderSelection.setSourceChangeListener(fPackageSelection);
-
- setDefaults(fragment, cu);
-
- fPackageSelection.setUpdateListener(updateListener);
- fSourceFolderSelection.setUpdateListener(updateListener);
- }
-
- private void setDefaults(IPackageFragment fragment, IJavaScriptUnit cu) {
- IJavaScriptElement element= fragment;
- if (element == null) {
- element= cu;
- }
-
- fSourceFolderSelection.setRoot(searchSourcePackageFragmentRoot(element));
- fPackageSelection.setPackageFragment(searchPackageFragment(element));
- }
-
- private IPackageFragment searchPackageFragment(IJavaScriptElement jElement) {
- return (IPackageFragment)jElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- }
-
- private IPackageFragmentRoot searchSourcePackageFragmentRoot(IJavaScriptElement jElement) {
- IJavaScriptElement parent= jElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (parent == null) {
- return null;
- }
-
- IPackageFragmentRoot res= (IPackageFragmentRoot)parent;
- try {
- if (res.getKind() == IPackageFragmentRoot.K_SOURCE) {
- return res;
- }
- } catch (JavaScriptModelException e) {
- // nothing to do
- }
-
- return null;
- }
-
- class PackageSelectionDialogFieldListener implements IDialogFieldListener {
-
- public void dialogFieldChanged(DialogField field) {
- String packName= fPackageSelection.getText();
- if (packName.length() == 0)
- fPackageSelection.setStatus(NLSUIMessages.NLSAccessorConfigurationDialog_default);
- else
- fPackageSelection.setStatus(""); //$NON-NLS-1$
- }
- }
-
- class SFStringButtonAdapter implements IStringButtonAdapter {
- public void changeControlPressed(DialogField field) {
-
- IPackageFragmentRoot newSourceContainer= chooseSourceContainer(fSourceFolderSelection.getRoot());
- if (newSourceContainer != null) {
- fSourceFolderSelection.setRoot(newSourceContainer);
- }
- }
- }
-
- private IPackageFragmentRoot chooseSourceContainer(IJavaScriptElement initElement) {
- Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaScriptProject.class };
- TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
- public boolean isSelectedValid(Object element) {
- try {
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject)element;
- IPath path= jproject.getProject().getFullPath();
- return (jproject.findPackageFragmentRoot(path) != null);
- } else if (element instanceof IPackageFragmentRoot) {
- return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
- }
- return true;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus()); // just log, no ui in validation
- }
- return false;
- }
- };
-
- acceptedClasses= new Class[] { IJavaScriptModel.class, IPackageFragmentRoot.class, IJavaScriptProject.class };
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragmentRoot) {
- try {
- return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus()); // just log, no ui in validation
- return false;
- }
- }
- return super.select(viewer, parent, element);
- }
- };
-
- StandardJavaScriptElementContentProvider provider= new StandardJavaScriptElementContentProvider();
- ILabelProvider labelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT);
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(fShell, labelProvider, provider);
- dialog.setValidator(validator);
- dialog.setComparator(new JavaScriptElementComparator());
- dialog.setTitle(NLSUIMessages.SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_title);
- dialog.setMessage(NLSUIMessages.SourceFirstPackageSelectionDialogField_ChooseSourceContainerDialog_description);
- dialog.addFilter(filter);
- dialog.setInput(JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()));
- dialog.setInitialSelection(initElement);
-
- if (dialog.open() == Window.OK) {
- Object element= dialog.getFirstResult();
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject)element;
- return jproject.getPackageFragmentRoot(jproject.getProject());
- } else if (element instanceof IPackageFragmentRoot) {
- return (IPackageFragmentRoot)element;
- }
- return null;
- }
- return null;
- }
-
-
- public IPackageFragment getSelected() {
- IPackageFragment res= fPackageSelection.getPackageFragment();
- return res;
- }
-
- public IPackageFragmentRoot getSelectedFragmentRoot() {
- return fSourceFolderSelection.getRoot();
- }
-
- public void setSelected(IPackageFragment newSelection) {
- fPackageSelection.setPackageFragment(newSelection);
- fSourceFolderSelection.setRoot(searchSourcePackageFragmentRoot(newSelection));
- }
-
- public void createControl(Composite parent, int nOfColumns, int textWidth) {
- fShell= parent.getShell();
- PixelConverter converter= new PixelConverter(parent);
- fSourceFolderSelection.doFillIntoGrid(parent, nOfColumns, textWidth);
- LayoutUtil.setWidthHint(fSourceFolderSelection.getTextControl(null), converter.convertWidthInCharsToPixels(60));
-
- fPackageSelection.doFillIntoGrid(parent, nOfColumns, textWidth);
- LayoutUtil.setWidthHint(fPackageSelection.getTextControl(null), converter.convertWidthInCharsToPixels(60));
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFolderSelectionDialogButtonField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFolderSelectionDialogButtonField.java
deleted file mode 100644
index 7e3b4fd2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/SourceFolderSelectionDialogButtonField.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaSourcePackageFragmentRootCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-
-class SourceFolderSelectionDialogButtonField extends StringButtonDialogField implements IDialogFieldListener {
-
- private IPackageFragmentRoot fRoot;
- private SourceChangeListener fListener;
- private IDialogFieldListener fUpdateListener;
-
- public SourceFolderSelectionDialogButtonField(String descriptionLabel, String browseLabel, IStringButtonAdapter adapter) {
- super(adapter);
- setContentAssistProcessor(new JavaSourcePackageFragmentRootCompletionProcessor());
- setLabelText(descriptionLabel);
- setButtonLabel(browseLabel);
- setDialogFieldListener(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- // propagate a textchange to the fragment root of this
- setRoot(getRootFromString(getText()));
- }
-
- public void setUpdateListener(IDialogFieldListener updateListener) {
- fUpdateListener= updateListener;
- }
-
- public Control[] doFillIntoGrid(Composite parent, int nColumns, int textWidth) {
- Control[] res= super.doFillIntoGrid(parent, nColumns);
-
- final Text text= getTextControl(null);
- LayoutUtil.setWidthHint(text, textWidth);
- LayoutUtil.setHorizontalGrabbing(text);
-
- return res;
- }
-
- public void setSourceChangeListener(SourceChangeListener listener) {
- fListener= listener;
- }
-
- /**
- * tries to build a packagefragmentroot out of a string and sets the string into this
- * packagefragmentroot.
- *
- * @param rootString
- */
- private IPackageFragmentRoot getRootFromString(String rootString) {
- if (rootString.length() == 0) {
- return null;
- }
- IPath path= new Path(rootString);
- IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
- IResource res= workspaceRoot.findMember(path);
- if (res == null) {
- return null;
- }
- int resType= res.getType();
- if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
- IProject proj= res.getProject();
- if (!proj.isOpen()) {
- return null;
- }
- IJavaScriptProject jproject= JavaScriptCore.create(proj);
- IPackageFragmentRoot root= jproject.getPackageFragmentRoot(res);
- if (root.exists()) {
- return root;
- }
- }
- return null;
- }
-
- public void setRoot(IPackageFragmentRoot root) {
- fRoot= root;
-
- if (fRoot != null) {
- String str= getRootString();
- if (!getText().equals(str)) {
- setText(str);
- }
- } else {
- // dont ripple if the root is not a real root
- }
-
- fListener.sourceRootChanged(fRoot);
- if (fUpdateListener != null) {
- fUpdateListener.dialogFieldChanged(this);
- }
- }
-
- public IPackageFragmentRoot getRoot() {
- return fRoot;
- }
-
- private String getRootString() {
- return (fRoot == null) ? "" : fRoot.getPath().makeRelative().toString(); //$NON-NLS-1$
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/CompilationUnitEntry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/CompilationUnitEntry.java
deleted file mode 100644
index 554a3e5c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/CompilationUnitEntry.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-public class CompilationUnitEntry implements IAdaptable {
-
- private final String fMessage;
- private final IJavaScriptUnit fCompilationUnit;
-
- public CompilationUnitEntry(String message, IJavaScriptUnit compilationUnit) {
- fMessage= message;
- fCompilationUnit= compilationUnit;
- }
-
- public String getMessage() {
- return fMessage;
- }
-
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- public Object getAdapter(Class adapter) {
- if (IJavaScriptUnit.class.equals(adapter))
- return getCompilationUnit();
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/FileEntry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/FileEntry.java
deleted file mode 100644
index 78efc5e6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/FileEntry.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-
-public class FileEntry implements IAdaptable {
-
- private IFile fPropertiesFile;
- private String fMessage;
-
- public FileEntry(IFile propertiesFile, String message) {
- fPropertiesFile= propertiesFile;
- fMessage= message;
- }
-
- public IFile getPropertiesFile() {
- return fPropertiesFile;
- }
-
- public String getMessage() {
- return fMessage;
- }
-
- public String toString() {
- return fMessage;
- }
-
- public Object getAdapter(Class adapter) {
- if (IResource.class.equals(adapter))
- return fPropertiesFile;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/LineReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/LineReader.java
deleted file mode 100644
index b6e01ab4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/LineReader.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-
-
-class LineReader extends Object {
- protected static final int LF= '\n';
- protected static final int CR= '\r';
-
- private BufferedReader fReader;
-
- protected int fPushbackChar;
- protected boolean fPushback;
-
- public LineReader(InputStream in, String encoding) throws IOException {
- this(new InputStreamReader(in, encoding));
- }
-
- public LineReader(Reader reader) {
- fPushback= false;
- fReader= new BufferedReader(reader);
- }
-
- public int readLine(StringBuffer sb) throws IOException {
- int ch= -1;
- sb.setLength(0);
- if (fPushback) {
- ch= fPushbackChar;
- fPushback= false;
- } else
- ch= fReader.read();
- while (ch >= 0) {
- if (ch == LF)
- return 1;
- if (ch == CR) {
- ch= fReader.read();
- if (ch == LF)
- return 2;
- else {
- fPushbackChar= ch;
- fPushback= true;
- return 1;
- }
- }
- sb.append((char) ch);
- ch= fReader.read();
- }
- return -1;
- }
-
- public void close() throws IOException {
- fReader.close();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchEditorOpener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchEditorOpener.java
deleted file mode 100644
index 7ee03709..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchEditorOpener.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchEditorOpener;
-
-/**
- */
-public class NLSSearchEditorOpener extends JavaSearchEditorOpener {
- protected Object getElementToOpen(Match match) {
- Object element= match.getElement();
- if (element instanceof IJavaScriptElement) {
- return element;
- } else if (element instanceof FileEntry) {
- FileEntry fileEntry= (FileEntry) element;
- return fileEntry.getPropertiesFile();
- } else if (element instanceof CompilationUnitEntry) {
- return ((CompilationUnitEntry)element).getCompilationUnit();
- }
- // this should not happen
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.java
deleted file mode 100644
index 3b797785..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class NLSSearchMessages extends NLS {
-
- private static final String BUNDLE_NAME= NLSSearchMessages.class.getName();
-
- private NLSSearchMessages() {
- // Do not instantiate
- }
-
- public static String NLSSearchQuery_label;
- public static String NLSSearchQuery_oneProblemInScope_description;
- public static String NLSSearchQuery_propertiesNotExists;
- public static String NLSSearchQuery_wrapperNotExists;
- public static String NLSSearchQuery_xProblemsInScope_description;
-
- public static String NLSSearchResultCollector_duplicateKeys;
- public static String NLSSearchResultCollector_unusedKeys;
- public static String NLSSearchResultLabelProvider2_undefinedKeys;
- public static String NLSSearchResultRequestor_searching;
-
- public static String SearchOperation_pluralLabelPatternPostfix;
- public static String SearchOperation_singularLabelPostfix;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, NLSSearchMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties
deleted file mode 100644
index 194c33e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties
+++ /dev/null
@@ -1,25 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-SearchOperation_singularLabelPostfix=''{0}'' - 1 problem in ''{1}''
-SearchOperation_pluralLabelPatternPostfix=''{0}'' - {1} problems in ''{2}''
-
-NLSSearchResultCollector_unusedKeys=Unused keys in: {0}
-NLSSearchResultRequestor_searching=Searching for unused properties ...
-NLSSearchResultCollector_duplicateKeys=Duplicate keys in: {0}
-NLSSearchResultLabelProvider2_undefinedKeys=Undefined keys in: {0}
-
-# ### New Search: ###
-NLSSearchQuery_label=Search for Broken NLS Keys
-NLSSearchQuery_wrapperNotExists=Resource bundle accessor class ''{0}'' does not exist.
-NLSSearchQuery_propertiesNotExists=Properties file ''{0}'' does not exist.
-NLSSearchQuery_oneProblemInScope_description=1 problem in {0}
-NLSSearchQuery_xProblemsInScope_description={0} problems in {1}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchQuery.java
deleted file mode 100644
index bf0a9826..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchQuery.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.ISearchResult;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-
-public class NLSSearchQuery implements ISearchQuery {
-
- private NLSSearchResult fResult;
- private IJavaScriptElement[] fWrapperClass;
- private IFile[] fPropertiesFile;
- private IJavaScriptSearchScope fScope;
- private String fScopeDescription;
-
- public NLSSearchQuery(IJavaScriptElement[] wrapperClass, IFile[] propertiesFile, IJavaScriptSearchScope scope, String scopeDescription) {
- fWrapperClass= wrapperClass;
- fPropertiesFile= propertiesFile;
- fScope= scope;
- fScopeDescription= scopeDescription;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public IStatus run(IProgressMonitor monitor) {
- monitor.beginTask("", 5 * fWrapperClass.length); //$NON-NLS-1$
-
- try {
- final AbstractTextSearchResult textResult= (AbstractTextSearchResult) getSearchResult();
- textResult.removeAll();
- AppearanceAwareLabelProvider labelProvider= new AppearanceAwareLabelProvider(JavaScriptElementLabels.ALL_POST_QUALIFIED, 0);
-
- for (int i= 0; i < fWrapperClass.length; i++) {
- IJavaScriptElement wrapperClass= fWrapperClass[i];
- IFile propertieFile= fPropertiesFile[i];
- if (! wrapperClass.exists())
- return JavaUIStatus.createError(0, Messages.format(NLSSearchMessages.NLSSearchQuery_wrapperNotExists, wrapperClass.getElementName()), null);
- if (! wrapperClass.exists())
- return JavaUIStatus.createError(0, Messages.format(NLSSearchMessages.NLSSearchQuery_propertiesNotExists, propertieFile.getName()), null);
-
- SearchPattern pattern= SearchPattern.createPattern(wrapperClass, IJavaScriptSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- SearchParticipant[] participants= new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
-
- NLSSearchResultRequestor requestor= new NLSSearchResultRequestor(propertieFile, fResult);
- try {
- SearchEngine engine= new SearchEngine();
- engine.search(pattern, participants, fScope, requestor, new SubProgressMonitor(monitor, 4));
- requestor.reportUnusedPropertyNames(new SubProgressMonitor(monitor, 1));
-
- IJavaScriptUnit compilationUnit= ((IType)wrapperClass).getJavaScriptUnit();
- CompilationUnitEntry groupElement= new CompilationUnitEntry(Messages.format(NLSSearchMessages.NLSSearchResultCollector_unusedKeys, labelProvider.getText(compilationUnit)), compilationUnit);
-
- boolean hasUnusedPropertie= false;
- IField[] fields= ((IType)wrapperClass).getFields();
- for (int j= 0; j < fields.length; j++) {
- IField field= fields[j];
- if (isNLSField(field)) {
- ISourceRange sourceRange= field.getSourceRange();
- if (sourceRange != null) {
- String fieldName= field.getElementName();
- if (!requestor.hasPropertyKey(fieldName)) {
- fResult.addMatch(new Match(compilationUnit, sourceRange.getOffset(), sourceRange.getLength()));
- }
- if (!requestor.isUsedPropertyKey(fieldName)) {
- hasUnusedPropertie= true;
- fResult.addMatch(new Match(groupElement, sourceRange.getOffset(), sourceRange.getLength()));
- }
- }
- }
- }
- if (hasUnusedPropertie)
- fResult.addCompilationUnitGroup(groupElement);
-
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- } finally {
- monitor.done();
- }
- return Status.OK_STATUS;
- }
-
- private boolean isNLSField(IField field) throws JavaScriptModelException {
- int flags= field.getFlags();
- if (!Flags.isPublic(flags))
- return false;
-
- if (!Flags.isStatic(flags))
- return false;
-
- String fieldName= field.getElementName();
- if (NLSRefactoring.BUNDLE_NAME.equals(fieldName))
- return false;
-
- if ("RESOURCE_BUNDLE".equals(fieldName)) //$NON-NLS-1$
- return false;
-
- return true;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#getLabel()
- */
- public String getLabel() {
- return NLSSearchMessages.NLSSearchQuery_label;
- }
-
- public String getResultLabel(int nMatches) {
- if (fWrapperClass.length == 1) {
- if (nMatches == 1) {
- String[] args= new String[] {fWrapperClass[0].getElementName(), fScopeDescription};
- return Messages.format(NLSSearchMessages.SearchOperation_singularLabelPostfix, args);
- }
- String[] args= new String[] {fWrapperClass[0].getElementName(), String.valueOf(nMatches), fScopeDescription};
- return Messages.format(NLSSearchMessages.SearchOperation_pluralLabelPatternPostfix, args);
- } else {
- if (nMatches == 1) {
- return Messages.format(NLSSearchMessages.NLSSearchQuery_oneProblemInScope_description, fScopeDescription);
- }
- return Messages.format(NLSSearchMessages.NLSSearchQuery_xProblemsInScope_description, new Object[] {String.valueOf(nMatches), fScopeDescription});
- }
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#canRerun()
- */
- public boolean canRerun() {
- return true;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground()
- */
- public boolean canRunInBackground() {
- return true;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#getSearchResult()
- */
- public ISearchResult getSearchResult() {
- if (fResult == null)
- fResult= new NLSSearchResult(this);
- return fResult;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResult.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResult.java
deleted file mode 100644
index 135461d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResult.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.IEditorMatchAdapter;
-import org.eclipse.search.ui.text.IFileMatchAdapter;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-
-public class NLSSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter {
-
- private static final Match[] NO_MATCHES= new Match[0];
-
- /*
- * Element (group key) is always IJavaScriptElement or FileEntry.
- */
- private NLSSearchQuery fQuery;
- private final List fFileEntryGroups;
- private final List fCompilationUnitGroups;
-
- public NLSSearchResult(NLSSearchQuery query) {
- fQuery= query;
- fFileEntryGroups= new ArrayList();
- fCompilationUnitGroups= new ArrayList();
- }
-
- public void addFileEntryGroup(FileEntry group) {
- fFileEntryGroups.add(group);
- }
-
- public void addCompilationUnitGroup(CompilationUnitEntry group) {
- fCompilationUnitGroups.add(group);
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.ui.IEditorPart)
- */
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) {
- //TODO: copied from JavaSearchResult:
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput instanceof IFileEditorInput) {
- IFileEditorInput fileEditorInput= (IFileEditorInput) editorInput;
- return computeContainedMatches(result, fileEditorInput.getFile());
- } else if (editorInput instanceof IClassFileEditorInput) {
- IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) editorInput;
- Set matches= new HashSet();
- collectMatches(matches, classFileEditorInput.getClassFile());
- return (Match[]) matches.toArray(new Match[matches.size()]);
- }
- return NO_MATCHES;
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.core.resources.IFile)
- */
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IFile file) {
- Set matches= new HashSet();
- for (Iterator iter= fFileEntryGroups.iterator(); iter.hasNext();) {
- FileEntry element= (FileEntry)iter.next();
- if (element.getPropertiesFile().equals(file)) {
- matches.addAll(Arrays.asList(getMatches(element)));
- }
- }
- if (matches.size() > 0)
- return (Match[]) matches.toArray(new Match[matches.size()]);
-
- try {
- for (Iterator iter= fCompilationUnitGroups.iterator(); iter.hasNext();) {
- CompilationUnitEntry element= (CompilationUnitEntry)iter.next();
- IJavaScriptUnit cu= element.getCompilationUnit();
- if (cu.exists() && file.equals(cu.getCorrespondingResource())) {
- matches.addAll(Arrays.asList(getMatches(element)));
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return NO_MATCHES;
- }
-
- //TODO: copied from JavaSearchResult:
- IJavaScriptElement javaElement= JavaScriptCore.create(file);
- collectMatches(matches, javaElement);
- return (Match[]) matches.toArray(new Match[matches.size()]);
- }
-
- private void collectMatches(Set matches, IJavaScriptElement element) {
- //TODO: copied from JavaSearchResult:
- Match[] m= getMatches(element);
- if (m.length != 0) {
- for (int i= 0; i < m.length; i++) {
- matches.add(m[i]);
- }
- }
- if (element instanceof IParent) {
- IParent parent= (IParent) element;
- try {
- IJavaScriptElement[] children= parent.getChildren();
- for (int i= 0; i < children.length; i++) {
- collectMatches(matches, children[i]);
- }
- } catch (JavaScriptModelException e) {
- // we will not be tracking these results
- }
- }
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getFile(java.lang.Object)
- */
- public IFile getFile(Object element) {
- if (element instanceof FileEntry) {
- return ((FileEntry) element).getPropertiesFile();
- } else {
- IJavaScriptElement javaElement= null;
- if (element instanceof CompilationUnitEntry) {
- javaElement= ((CompilationUnitEntry)element).getCompilationUnit();
- } else {
- javaElement= (IJavaScriptElement) element;
- }
- IResource resource= null;
- try {
- resource= javaElement.getCorrespondingResource();
- } catch (JavaScriptModelException e) {
- // no resource
- }
- if (resource instanceof IFile)
- return (IFile) resource;
- else
- return null;
- }
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#isShownInEditor(org.eclipse.search.ui.text.Match, org.eclipse.ui.IEditorPart)
- */
- public boolean isShownInEditor(Match match, IEditorPart editor) {
- IEditorInput editorInput= editor.getEditorInput();
- if (match.getElement() instanceof FileEntry) {
- IFile file= ((FileEntry) match.getElement()).getPropertiesFile();
- if (editorInput instanceof IFileEditorInput) {
- return ((IFileEditorInput) editorInput).getFile().equals(file);
- }
- } else if (match.getElement() instanceof IJavaScriptElement || match.getElement() instanceof CompilationUnitEntry) {
- IJavaScriptElement je= null;
- if (match.getElement() instanceof IJavaScriptElement) {
- je= (IJavaScriptElement) match.getElement();
- } else {
- je= ((CompilationUnitEntry)match.getElement()).getCompilationUnit();
- }
- if (editorInput instanceof IFileEditorInput) {
- try {
- IJavaScriptUnit cu= (IJavaScriptUnit) je.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu == null)
- return false;
- else
- return ((IFileEditorInput) editorInput).getFile().equals(cu.getCorrespondingResource());
- } catch (JavaScriptModelException e) {
- return false;
- }
- } else if (editorInput instanceof IClassFileEditorInput) {
- return ((IClassFileEditorInput) editorInput).getClassFile().equals(je.getAncestor(IJavaScriptElement.CLASS_FILE));
- }
- }
- return false;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getLabel()
- */
- public String getLabel() {
- return fQuery.getResultLabel(getMatchCount());
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getTooltip()
- */
- public String getTooltip() {
- return getLabel();
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- return JavaPluginImages.DESC_OBJS_SEARCH_REF;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getQuery()
- */
- public ISearchQuery getQuery() {
- return fQuery;
- }
-
- public IFileMatchAdapter getFileMatchAdapter() {
- return this;
- }
-
- public IEditorMatchAdapter getEditorMatchAdapter() {
- return this;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultLabelProvider2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultLabelProvider2.java
deleted file mode 100644
index 992b2ea1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultLabelProvider2.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.search.TextSearchLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-
-class NLSSearchResultLabelProvider2 extends TextSearchLabelProvider {
-
- private AppearanceAwareLabelProvider fLabelProvider;
-
- public NLSSearchResultLabelProvider2(AbstractTextSearchViewPage page) {
- super(page);
- fLabelProvider= new AppearanceAwareLabelProvider(JavaScriptElementLabels.ALL_POST_QUALIFIED, 0);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.search.TextSearchLabelProvider#doGetText(java.lang.Object)
- */
- protected String doGetText(Object element) {
- if (element instanceof FileEntry) {
- FileEntry fileEntry= (FileEntry) element;
- return fileEntry.getMessage();
- } else if (element instanceof CompilationUnitEntry) {
- return ((CompilationUnitEntry)element).getMessage();
- } else {
- return Messages.format(NLSSearchMessages.NLSSearchResultLabelProvider2_undefinedKeys, fLabelProvider.getText(element));
- }
- }
-
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- if (element instanceof FileEntry)
- element= ((FileEntry) element).getPropertiesFile();
- if (element instanceof CompilationUnitEntry)
- element= ((CompilationUnitEntry)element).getCompilationUnit();
-
- return fLabelProvider.getImage(element);
- }
-
- /*
- * @see org.eclipse.jface.viewers.LabelProvider#dispose()
- */
- public void dispose() {
- fLabelProvider.dispose();
- fLabelProvider= null;
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultPage.java
deleted file mode 100644
index 4f8edaf0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultPage.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchResultPage;
-import org.eclipse.wst.jsdt.internal.ui.search.TextSearchTableContentProvider;
-
-
-public class NLSSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable {
-
- private TextSearchTableContentProvider fContentProvider;
- private NLSSearchEditorOpener fEditorOpener= new NLSSearchEditorOpener();
-
- public NLSSearchResultPage() {
- super(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT);
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#showMatch(org.eclipse.search.ui.text.Match,
- * int, int)
- */
- protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException {
- try {
- IEditorPart editor= fEditorOpener.openMatch(match);
- if (editor != null && activate)
- editor.getEditorSite().getPage().activate(editor);
- if (editor instanceof ITextEditor) {
- ITextEditor textEditor= (ITextEditor) editor;
- textEditor.selectAndReveal(currentOffset, currentLength);
- }
- } catch (JavaScriptModelException e1) {
- throw new PartInitException(e1.getStatus());
- }
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#elementsChanged(java.lang.Object[])
- */
- protected void elementsChanged(Object[] objects) {
- if (fContentProvider != null)
- fContentProvider.elementsChanged(objects);
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#clear()
- */
- protected void clear() {
- if (fContentProvider != null)
- fContentProvider.clear();
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTreeViewer(org.eclipse.jface.viewers.TreeViewer)
- */
- protected void configureTreeViewer(TreeViewer viewer) {
- throw new IllegalStateException("Doesn't support tree mode."); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTableViewer(org.eclipse.jface.viewers.TableViewer)
- */
- protected void configureTableViewer(TableViewer viewer) {
- viewer.setComparator(new ViewerComparator() {
- public int category(Object element) {
- if (element instanceof FileEntry) {
- return 0;
- } else {
- return 1;
- }
- }
- });
- viewer.setLabelProvider(new NLSSearchResultLabelProvider2(this));
- fContentProvider= new TextSearchTableContentProvider();
- viewer.setContentProvider(fContentProvider);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class adapter) {
- if (IShowInTargetList.class.equals(adapter)) {
- return JavaSearchResultPage.SHOW_IN_TARGET_LIST;
- }
- return null;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java
deleted file mode 100644
index b528627d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.Position;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.PropertyFileDocumentModel;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-
-class NLSSearchResultRequestor extends SearchRequestor {
- /*
- * Matches are added to fResult. Element (group key) is IJavaScriptElement or FileEntry.
- */
-
- private static final StringMatcher fgGetClassNameMatcher= new StringMatcher("*.class.getName()*", false, false); //$NON-NLS-1$
-
- private NLSSearchResult fResult;
- private IFile fPropertiesFile;
- private Properties fProperties;
- private HashSet fUsedPropertyNames;
-
- public NLSSearchResultRequestor(IFile propertiesFile, NLSSearchResult result) {
- fPropertiesFile= propertiesFile;
- fResult= result;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.search.SearchRequestor#beginReporting()
- */
- public void beginReporting() {
- loadProperties();
- fUsedPropertyNames= new HashSet(fProperties.size());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.wst.jsdt.core.search.SearchMatch)
- */
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- if (match.getAccuracy() == SearchMatch.A_INACCURATE)
- return;
-
- int offset= match.getOffset();
- int length= match.getLength();
- if (offset == -1 || length == -1)
- return;
-
- if (! (match.getElement() instanceof IJavaScriptElement))
- return;
- IJavaScriptElement javaElement= (IJavaScriptElement) match.getElement();
-
- // ignore matches in import declarations:
- if (javaElement.getElementType() == IJavaScriptElement.IMPORT_DECLARATION)
- return;
- if (javaElement.getElementType() == IJavaScriptElement.CLASS_FILE)
- return; //matches in import statements of class files
- if (javaElement.getElementType() == IJavaScriptElement.TYPE)
- return; //classes extending the accessor class and workaround for bug 61286
-
- // heuristic: ignore matches in resource bundle name field:
- if (javaElement.getElementType() == IJavaScriptElement.FIELD) {
- IField field= (IField) javaElement;
- String source= field.getSource();
- if (source != null && fgGetClassNameMatcher.match(source))
- return;
- }
-
- if (javaElement instanceof ISourceReference) {
- String source= ((ISourceReference) javaElement).getSource();
- if (source != null) {
- if (source.indexOf("NLS.initializeMessages") != -1) //$NON-NLS-1$
- return;
- }
- }
-
- // found reference to NLS Wrapper - now check if the key is there:
- Position mutableKeyPosition= new Position(offset, length);
- //TODO: What to do if argument string not found? Currently adds a match with type name.
- String key= findKey(mutableKeyPosition, javaElement);
- if (key != null && isKeyDefined(key))
- return;
-
- IJavaScriptUnit[] allCompilationUnits= JavaModelUtil.getAllCompilationUnits(new IJavaScriptElement[] {javaElement});
- Object element= javaElement;
- if (allCompilationUnits != null && allCompilationUnits.length == 1)
- element= allCompilationUnits[0];
-
- fResult.addMatch(new Match(element, mutableKeyPosition.getOffset(), mutableKeyPosition.getLength()));
- }
-
- public void reportUnusedPropertyNames(IProgressMonitor pm) {
- //Don't use endReporting() for long running operation.
- pm.beginTask("", fProperties.size()); //$NON-NLS-1$
- boolean hasUnused= false;
- pm.setTaskName(NLSSearchMessages.NLSSearchResultRequestor_searching);
- String message= Messages.format(NLSSearchMessages.NLSSearchResultCollector_unusedKeys, getPropertiesName(fPropertiesFile));
- FileEntry groupElement= new FileEntry(fPropertiesFile, message);
-
- for (Enumeration enumeration= fProperties.propertyNames(); enumeration.hasMoreElements();) {
- String propertyName= (String) enumeration.nextElement();
- if (!fUsedPropertyNames.contains(propertyName)) {
- addMatch(groupElement, propertyName);
- hasUnused= true;
- }
- pm.worked(1);
- }
- if (hasUnused)
- fResult.addFileEntryGroup(groupElement);
- pm.done();
- }
-
- private String getPropertiesName(IFile propertiesFile) {
- String path= propertiesFile.getFullPath().removeLastSegments(1).toOSString();
- return propertiesFile.getName() + " - " + path; //$NON-NLS-1$
- }
-
- private void addMatch(FileEntry groupElement, String propertyName) {
- /*
- * TODO (bug 63794): Should read in .properties file with our own reader and not
- * with Properties.load(InputStream) . Then, we can remember start position and
- * original version (not interpreting escape characters) for each property.
- *
- * The current workaround is to escape the key again before searching in the
- * .properties file. However, this can fail if the key is escaped in a different
- * manner than what PropertyFileDocumentModel.unwindEscapeChars(.) produces.
- */
- String escapedPropertyName= PropertyFileDocumentModel.unwindEscapeChars(propertyName);
- int start= findPropertyNameStartPosition(escapedPropertyName);
- int length;
- if (start == -1) { // not found -> report at beginning
- start= 0;
- length= 0;
- } else {
- length= escapedPropertyName.length();
- }
- fResult.addMatch(new Match(groupElement, start, length));
- }
-
- /**
- * Checks if the key is defined in the property file
- * and adds it to the list of used properties.
- *
- * @param key the key
- * @return <code>true</code> if the key is defined
- */
- private boolean isKeyDefined(String key) {
- if (key == null)
- return true; // Parse error - don't check key
-
- fUsedPropertyNames.add(key);
- if (fProperties.getProperty(key) != null) {
- return true;
- }
- return false;
- }
-
- public boolean hasPropertyKey(String key) {
- return fProperties.containsKey(key);
- }
-
- public boolean isUsedPropertyKey(String key) {
- return fUsedPropertyNames.contains(key);
- }
-
- /**
- * Finds the key defined by the given match. The assumption is that
- * the key is the first argument and it is a string i.e. quoted ("...").
- *
- * @param keyPositionResult reference parameter: will be filled with the position of the found key
- * @param enclosingElement enclosing java element
- * @return a string denoting the key, null if no key can be found
- * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code>
- */
- private String findKey(Position keyPositionResult, IJavaScriptElement enclosingElement) throws CoreException {
- IJavaScriptUnit unit= (IJavaScriptUnit)enclosingElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (unit == null)
- return null;
-
- String source= unit.getSource();
- if (source == null)
- return null;
-
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(source.toCharArray());
- scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length());
-
- try {
- if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT)
- return null;
-
- if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier)
- return null;
-
- String src= new String(scanner.getCurrentTokenSource());
- int keyStart= scanner.getCurrentTokenStartPosition();
- int keyEnd= scanner.getCurrentTokenEndPosition();
-
- if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) {
- // Old school
- // next must be key string:
- if (scanner.getNextToken() != ITerminalSymbols.TokenNameStringLiteral)
- return null;
- // found it:
- keyStart= scanner.getCurrentTokenStartPosition() + 1;
- keyEnd= scanner.getCurrentTokenEndPosition();
- keyPositionResult.setOffset(keyStart);
- keyPositionResult.setLength(keyEnd - keyStart);
- return source.substring(keyStart, keyEnd);
- } else {
- keyPositionResult.setOffset(keyStart);
- keyPositionResult.setLength(keyEnd - keyStart + 1);
- return src;
- }
- } catch (InvalidInputException e) {
- return null;
- }
- }
-
- /**
- * Finds the start position in the property file. We assume that
- * the key is the first match on a line.
- *
- * @param propertyName the property name
- * @return the start position of the property name in the file, -1 if not found
- */
- private int findPropertyNameStartPosition(String propertyName) {
- // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319
- InputStream stream= null;
- LineReader lineReader= null;
- String encoding;
- try {
- encoding= fPropertiesFile.getCharset();
- } catch (CoreException e1) {
- encoding= "ISO-8859-1"; //$NON-NLS-1$
- }
- try {
- stream= createInputStream(fPropertiesFile);
- lineReader= new LineReader(stream, encoding);
- } catch (CoreException cex) {
- // failed to get input stream
- JavaScriptPlugin.log(cex);
- return -1;
- } catch (IOException e) {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException ce) {
- JavaScriptPlugin.log(ce);
- }
- }
- return -1;
- }
- int start= 0;
- try {
- StringBuffer buf= new StringBuffer(80);
- int eols= lineReader.readLine(buf);
- int keyLength= propertyName.length();
- while (eols > 0) {
- String line= buf.toString();
- int i= line.indexOf(propertyName);
- int charPos= i + keyLength;
- char terminatorChar= 0;
- boolean hasNoValue= (charPos >= line.length());
- if (i > -1 && !hasNoValue)
- terminatorChar= line.charAt(charPos);
- if (line.trim().startsWith(propertyName) &&
- (hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) {
- start += line.indexOf(propertyName);
- eols= -17; // found key
- } else {
- start += line.length() + eols;
- buf.setLength(0);
- eols= lineReader.readLine(buf);
- }
- }
- if (eols != -17)
- start= -1; //key not found in file. See bug 63794. This can happen if the key contains escaped characters.
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- return -1;
- } finally {
- try {
- lineReader.close();
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
- return start;
- }
-
- private void loadProperties() {
- Set duplicateKeys= new HashSet();
- fProperties= new Properties(duplicateKeys);
- InputStream stream;
- try {
- stream= new BufferedInputStream(createInputStream(fPropertiesFile));
- } catch (CoreException ex) {
- fProperties= new Properties();
- return;
- }
- try {
- fProperties.load(stream);
- } catch (IOException ex) {
- fProperties= new Properties();
- return;
- } finally {
- try {
- stream.close();
- } catch (IOException ex) {
- }
- reportDuplicateKeys(duplicateKeys);
- }
- }
-
- private InputStream createInputStream(IFile propertiesFile) throws CoreException {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- if (manager != null) {
- ITextFileBuffer buffer= manager.getTextFileBuffer(propertiesFile.getFullPath(), LocationKind.IFILE);
- if (buffer != null) {
- return new ByteArrayInputStream(buffer.getDocument().get().getBytes());
- }
- }
-
- return propertiesFile.getContents();
- }
-
- private void reportDuplicateKeys(Set duplicateKeys) {
- if (duplicateKeys.size() == 0)
- return;
-
- String message= Messages.format(NLSSearchMessages.NLSSearchResultCollector_duplicateKeys, getPropertiesName(fPropertiesFile));
- FileEntry groupElement= new FileEntry(fPropertiesFile, message);
- Iterator iter= duplicateKeys.iterator();
- while (iter.hasNext()) {
- String propertyName= (String) iter.next();
- addMatch(groupElement, propertyName);
- }
- fResult.addFileEntryGroup(groupElement);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/Properties.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/Properties.java
deleted file mode 100644
index b3c34344..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/Properties.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-
-
-
-class Properties extends java.util.Properties {
-
- private static final long serialVersionUID= 1L;
-
- private Set fDuplicateKeys;
-
- public Properties() {
- }
-
- public Properties(Set duplicateKeys) {
- super();
- Assert.isNotNull(duplicateKeys);
- fDuplicateKeys= duplicateKeys;
- }
-
- public Properties (Properties properties, Set duplicateKeys) {
- super(properties);
- Assert.isNotNull(duplicateKeys);
- fDuplicateKeys= duplicateKeys;
- }
- /*
- * @see java.util.Map#put(Object, Object)
- */
- public Object put(Object arg0, Object arg1) {
- if (arg0 != null && containsKey(arg0))
- fDuplicateKeys.add(arg0);
- return super.put(arg0, arg1);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/SearchBrokenNLSKeysUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/SearchBrokenNLSKeysUtil.java
deleted file mode 100644
index a0c43316..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/SearchBrokenNLSKeysUtil.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.nls.search;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-
-
-public class SearchBrokenNLSKeysUtil {
-
- public static void search(String scopeName, IType[] accessorClasses, IFile[] propertieFiles) {
- NLSSearchQuery query= new NLSSearchQuery(accessorClasses, propertieFiles, SearchEngine.createWorkspaceScope(), scopeName);
- NewSearchUI.runQueryInBackground(query);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties
deleted file mode 100644
index db78ca79..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties
+++ /dev/null
@@ -1,618 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-#######################################
-# org.eclipse.wst.jsdt.internal.ui.refactoring
-#######################################
-
-RefactorActionGroup_no_refactoring_available= <no refactoring available>
-
-RenameInputWizardPage_new_name= New na&me:
-
-RenameRefactoringWizard_internal_error= An unexpected exception occurred. See the error log for more details.
-
-#######################################
-# org.eclipse.wst.jsdt.internal.ui.actions
-#######################################
-
-OpenRefactoringWizardAction_refactoring=Refactoring
-OpenRefactoringWizardAction_exception=An unexpected exception occurred. See the error log for more details.
-
-ExtractMethodAction_label=E&xtract Function...
-ExtractMethodAction_dialog_title=Extract Function
-
-SurroundWithTryCatchAction_label=Surround with tr&y/catch Block
-SurroundWithTryCatchAction_dialog_title=Surround with try/catch
-SurroundWithTryCatchAction_exception=An unexpected exception occurred. See the error log for more details.
-SurroundWithTryCatchAction_no_exceptions=No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ?
-
-RefactoringGroup_modify_Parameters_label=&Change Function Signature...
-RefactoringGroup_pull_Up_label=Pull &Up...
-RefactoringGroup_move_label=&Move...
-
-
-RefactoringStarter_unexpected_exception=An unexpected exception occurred. See the error log for more details.
-RefactoringStarter_saving=Saving Resources
-RefactoringStarter_always_save=&Always save all modified resources automatically prior to refactoring
-RefactoringStarter_save_all_resources=Save Modified Resources
-RefactoringStarter_must_save=Some modified resources must be saved before this operation.
-
-RefactoringExecutionHelper_cannot_execute=The operation cannot be performed due to the following problem:\n\n{0}
-
-#######################################
-# org.eclipse.wst.jsdt.internal.ui.code
-#######################################
-
-ExtractMethodWizard_extract_method=Extract Function
-
-ExtractMethodInputPage_access_Modifiers=&Access modifier:
-ExtractMethodInputPage_public=public
-ExtractMethodInputPage_default=default
-ExtractMethodInputPage_protected=protected
-ExtractMethodInputPage_private=private
-ExtractMethodInputPage_signature_preview=Function signature preview:
-ExtractMethodInputPage_description=Enter new function name and specify the function's visibility
-ExtractMethodInputPage_label_text=Function &name:
-ExtractMethodInputPage_parameters=&Parameters:
-ExtractMethodInputPage_throwRuntimeExceptions=Declare thrown runtime e&xceptions
-ExtractMethodInputPage_validation_emptyMethodName=Provide a function name
-ExtractMethodInputPage_validation_emptyParameterName=Parameter names cannot be empty
-ExtractMethodInputPage_duplicates_none=&Replace all occurrences of statements with function
-ExtractMethodInputPage_duplicates_single=&Replace 1 occurrence of statements with function
-ExtractMethodInputPage_duplicates_multi=&Replace {0} occurrences of statements with function
-ExtractMethodInputPage_destination_type=Destination &type:
-ExtractMethodInputPage_anonymous_type_label=new {0}() '{'...}
-ExtractMethodInputPage_generateJavadocComment=Generate function &comment
-
-InlineMethodWizard_page_title=Inline Function
-
-#######################################
-# org.eclipse.wst.jsdt.internal.ui.sef
-#######################################
-
-SelfEncapsulateField_sef=Encapsulate Var
-SelfEncapsulateField_field_access=Var access in declaring type:
-SelfEncapsulateField_use_setter_getter=us&e setter and getter
-SelfEncapsulateField_keep_references=&keep var reference
-
-SelfEncapsulateFieldInputPage_description=Create getting and setting functions for the var and use only those to access the var
-SelfEncapsulateFieldInputPage_getter_name=&Getter name:
-SelfEncapsulateFieldInputPage_setter_name=&Setter name:
-SelfEncapsulateFieldInputPage_insert_after=&Insert new functions after:
-SelfEncapsulateFieldInputPage_first_method=As first function
-SelfEncapsulateFieldInputPage_access_Modifiers=Access modifier:
-SelfEncapsulateFieldInputPage_public=&public
-SelfEncapsulateFieldInputPage_default=defa&ult
-SelfEncapsulateFieldInputPage_protected=pro&tected
-SelfEncapsulateFieldInputPage_private=pri&vate
-SelfEncapsulateFieldInputPage_generateJavadocComment=Generate function &comments
-SelfEncapsulateFieldInputPage_useexistingsetter_label=(using existing setter)
-SelfEncapsulateFieldInputPage_useexistinggetter_label=(using existing getter)
-SelfEncapsulateFieldInputPage_usenewgetter_label=(new setter created)
-SelfEncapsulateFieldInputPage_usenewsetter_label=(new getter created)
-
-#######################################
-# Misc
-#######################################
-
-ExtractTempWizard_defaultPageTitle=Extract Local Variable
-ExtractTempInputPage_enter_name=Enter a name for the new local variable
-ExtractTempInputPage_variable_name=&Variable name:
-ExtractTempInputPage_replace_all=&Replace all occurrences of the selected expression with references to the local variable
-ExtractTempInputPage_declare_final=&Declare the local variable as \'final\'
-ExtractTempInputPage_signature_preview=Signature Preview:
-ExtractTempInputPage_extract_local=Extract local variable
-ExtractTempInputPage_exception=An unexpected exception occurred. See the error log for more details
-
-ExtractConstantInputPage_enter_name=Enter a name for the new constant
-ExtractConstantInputPage_constant_name=&Constant name:
-ExtractConstantInputPage_replace_all=&Replace all occurrences of the selected expression with references to the constant
-ExtractConstantInputPage_qualify_constant_references_with_class_name=&Qualify constant references with type name
-ExtractConstantInputPage_signature_preview=Signature Preview:
-ExtractConstantInputPage_exception=An unexpected exception occurred. See the error log for more details
-ExtractConstantInputPage_access_modifiers=Access modifier:
-ExtractConstantInputPage_selection_refers_to_nonfinal_fields=The selected expression refers to non-final or non-static vars
-
-PromoteTempInputPage_description=Select visibility and name for the new var
-
-MoveMembersWizard_page_title=Move Static Members
-
-RenameInputWizardPage_update_references=Update &references
-RenameInputWizardPage_update_textual_matches=Update &textual occurrences in comments and strings (forces preview)
-RenameInputWizardPage_update_qualified_names=Update fully &qualified names in non-JavaScript text files (forces preview)
-
-PullUpInputPage_select_methods=Select the functions to be removed in subclasses.
-PullUpInputPage_pull_Up=Pull Up
-PullUpInputPage_pull_up1=Pull Up Functions
-PullUpInputPage_exception=An unexpected exception occurred. See the error log for more details
-
-ExtractTempAction_label=Extract &Local Variable...
-ExtractTempAction_extract_temp=Extract Local Variable
-
-ConvertLocalToField_label=Con&vert Local Variable to Var...
-ConvertLocalToField_title=Convert Local Variable to Var
-
-ExtractConstantAction_label=Extr&act Constant...
-ExtractSuperTypeAction_label=Ex&tract Superclass...
-ExtractConstantAction_extract_constant=Extract Constant
-
-InlineTempAction_inline_temp=Inline Local Variable
-InlineTempAction_label=&Inline Local Variable...
-
-RenameAction_rename=Rename
-RenameAction_unavailable=Operation unavailable on the current selection.\n\nSelect a javaScript project, source folder, resource, or a JavaScript file, or a non-readonly type, var, function, parameter, local variable, or type variable.
-RenameAction_text=Re&name...
-
-NewTextRefactoringAction_exception=An unexpected exception occurred. See the error log for more details
-
-RenameEnumConstWizard_defaultPageTitle=Rename Enum Constant
-RenameEnumConstWizard_inputPage_description=Enter the new name for this constant.
-
-RenameFieldWizard_defaultPageTitle=Rename Var
-RenameFieldWizard_inputPage_description=Enter the new name for this var.
-RenameFieldInputWizardPage_rename_getter=Rename &getter function
-RenameFieldInputWizardPage_rename_getter_to=Rename &getter: ''{0}'' to ''{1}''
-RenameFieldInputWizardPage_rename_setter=Rename &setter function
-RenameFieldInputWizardPage_rename_setter_to=Rename &setter: ''{0}'' to ''{1}''
-RenameFieldInputWizardPage_setter_label={0} ({1})
-RenameFieldInputWizardPage_getter_label={0} ({1})
-
-MoveMembersInputPage_descriptionKey={0} member(s) from ''{1}''
-MoveMembersInputPage_destination_single=Destination &type for ''{0}'':
-MoveMembersInputPage_destination_multi=Destination &type for {0} selected elements:
-MoveMembersInputPage_browse=&Browse...
-MoveMembersInputPage_move_Member=Move Member
-MoveMembersInputPage_exception=An unexpected exception occurred. See the error log for more details
-MoveMembersInputPage_choose_Type=Choose Type
-MoveMembersInputPage_dialogMessage=&Choose a type (? = any character, * = any string):
-MoveMembersInputPage_upperListLabel=&Matching types:
-MoveMembersInputPage_lowerListLabel=&Qualifier:
-MoveMembersInputPage_not_found=Destination type does not exist (fully qualified type name expected)
-MoveMembersInputPage_invalid_name=Invalid Type Name
-MoveMembersInputPage_Invalid_selection=Invalid selection
-MoveMembersInputPage_no_binary=Cannot move members to binary types
-MoveMembersInputPage_internal_error=An unexpected exception occurred. See the error log for more details.
-MoveMembersInputPage_move=Move Members
-
-RenameJavaElementAction_exception=An unexpected exception occurred. See the error log for more details
-RenameJavaElementAction_not_available=Operation unavailable on the current selection.\nSelect a javaScript project, source folder, resource, package, JavaScript file, type, var, function, parameter or a local variable
-RenameJavaElementAction_name=Rename
-
-MoveAction_text=&Move...
-
-QualifiedNameComponent_patterns_label=File name &patterns:
-QualifiedNameComponent_patterns_description= The patterns are separated by commas (* = any string, ? = any character)
-
-DelegateCreator_deprecate_delegates=Mark as &deprecated
-
-PullUpInputPage_hierarchyLabal={0} function(s) selected
-PullUpInputPage_see_log=An unexpected exception occurred. See the error log for more details
-
-##Change Signature
-ChangeSignatureInputPage_change=Change the signature of the selected function and all its overriding functions.
-ChangeSignatureInputPage_access_modifier=A&ccess modifier:
-ChangeSignatureInputPage_default=default
-ChangeSignatureInputPage_return_type=Return &type:
-ChangeSignatureInputPage_method_name=Function &name:
-ChangeSignatureInputPage_parameters=Pa&rameters
-ChangeSignatureInputPage_exceptions=E&xceptions
-ChangeSignatureInputPage_method_Signature_Preview=Function signature preview:
-ChangeSignatureInputPage_exception=An unexpected exception occurred. See the error log for more details
-ChangeSignatureInputPage_unchanged=Function signature is unchanged.
-ChangeSignatureInputPage_Internal_Error=An unexpected exception occurred. See the error log for more details.
-ChangeSignatureInputPage_Change_Signature=Change Signature
-ChangeSignatureRefactoring_modify_Parameters=Change Function Signature
-
-RenameTempAction_exception=An unexpected exception occurred. See the error log for more details
-ModifyParametersAction_unavailable=To activate this refactoring, please select the name of a function. Binary functions and annotation elements are not supported.
-OpenRefactoringWizardAction_unavailable=Operation Unavailable
-PullUpAction_unavailable=To activate this refactoring, select a top-level type or the name of a non-binary instance function or var.
-MoveMembersAction_unavailable=To activate this refactoring, please select the name of a non-binary static function or var.
-PullUpInputPage_subtypes=&Subtypes of type ''{0}''
-
-MoveMembersAction_error_title=Refactoring
-MoveMembersAction_error_message=Cannot perform operation.
-RefactoringErrorDialogUtil_okToPerformQuestion=\n\nOK to perform the operation on this function?
-
-ChangeParametersControl_table_type=Type
-ChangeParametersControl_table_name=Name
-ChangeParametersControl_new=new
-ChangeParametersControl_default=default
-ChangeParametersControl_type=type
-ChangeParametersControl_table_defaultValue=Default value
-ChangeParametersControl_new_parameter_default_name=newParam
-ChangeParametersControl_buttons_move_up=&Up
-ChangeParametersControl_buttons_move_down=D&own
-ChangeParametersControl_buttons_edit=&Edit...
-ChangeParametersControl_buttons_add=&Add
-ChangeParametersControl_buttons_remove=Re&move
-
-ChangeExceptionsControl_buttons_add=&Add...
-ChangeExceptionsControl_buttons_remove=Re&move
-ChangeExceptionsControl_choose_title=Add Exception
-ChangeExceptionsControl_choose_message=&Choose an Exception (? = any character, * = any string):
-ChangeExceptionsControl_not_exception=Not an Exception
-
-ChangeExceptionHandler_undo_button=Undo
-ChangeExceptionHandler_abort_button=Abort
-ChangeExceptionHandler_message=\n Click 'Undo' to undo all successfully executed changes of the current refactoring.\n Click 'Abort' to abort the current refactoring.
-ChangeExceptionHandler_dialog_title=Refactoring
-ChangeExceptionHandler_status_without_detail=Exception does not provide a detail message
-ChangeExceptionHandler_undo_dialog_title=Undo Refactoring
-ChangeExceptionHandler_undo_dialog_message=An unexpected exception occurred while undoing the refactoring
-ChangeExceptionHandler_dialog_message=An exception has been caught while processing the refactoring ''{0}''.
-
-ParameterEditDialog_title=Function Parameter
-ParameterEditDialog_message_new=Declaration of Parameter:
-ParameterEditDialog_message=Declaration of Parameter ''{0}'':
-
-ParameterEditDialog_type=&Type:
-ParameterEditDialog_type_error=Type name must not be empty.
-ParameterEditDialog_name=&Name:
-ParameterEditDialog_name_error= Parameter name must not be empty.
-ParameterEditDialog_defaultValue=&Default value:
-ParameterEditDialog_defaultValue_error= Default value must not be empty.
-ParameterEditDialog_defaultValue_invalid=''{0}'' is not a valid expression.
-
-InlineTempWizard_defaultPageTitle= Inline Local Variable
-InlineTempInputPage_message_one= Inline 1 occurrence of local variable ''{0}'' ?
-InlineTempInputPage_message_multi= Inline {0} occurrences of local variable ''{1}'' ?
-InlineTempInputPage_message_zero=Inline 0 occurrences of local variable ''{0}'' ?\n\nSince no references have been found, the variable declaration will simply be removed.
-
-ConvertAnonymousToNestedInputPage_description=Select the name and modifiers for the new nested type
-ConvertAnonymousToNestedInputPage_class_name=Type &name:
-ConvertAnonymousToNestedInputPage_declare_final=Declare the nested type as \'&final\'
-ConvertAnonymousToNestedInputPage_declare_static=Declare the nested type as \'&static\'
-
-ExtractConstantWizard_defaultPageTitle=Extract Constant
-ExtractConstantInputPage_Internal_Error=An unexpected exception occurred. See the error log for more details.
-
-ExtractSupertypeWizard_defaultPageTitle=Extract Superclass
-ExtractSupertypeMemberPage_page_title=Select the members to extract to the new type.
-ExtractSupertypeMemberPage_name_label=&Superclass name:
-ExtractSupertypeMemberPage_create_stubs_label=&Create necessary functions stubs in non-abstract subtypes of the extracted type
-ExtractSupertypeMemberPage_types_list_caption=&Types to extract a superclass from:
-ExtractSupertypeMemberPage_extract_supertype=Extract Superclass
-ExtractSupertypeMemberPage_extract=extract
-ExtractSupertypeMemberPage_add_button_label=A&dd...
-ExtractSupertypeMemberPage_declare_abstract=declare abstract in superclass
-ExtractSupertypeMemberPage_use_supertype_label=&Use the extracted class in 'instanceof' expressions
-ExtractSupertypeMemberPage_remove_button_label=Re&move
-ExtractSupertypeMemberPage_choose_type_caption=Choose Types
-ExtractSupertypeMemberPage_choose_type_message=Choose types where to extract the new superclass from:
-ExtractSupertypeMemberPage_no_members_selected=No members selected to extract or declare abstract
-ExtractSupertypeMemberPage_use_instanceof_label=Use the &extracted class where possible
-
-ExtractInterfaceInputPage_description=Select the name for the new interface and select the members that will be declared in the interface.
-ExtractInterfaceInputPage_Interface_name=&Interface name:
-ExtractInterfaceInputPage_Members=&Members to declare in the interface:
-ExtractInterfaceInputPage_Extract_Interface=Extract Interface
-ExtractInterfaceInputPage_Internal_Error=An unexpected exception occurred. See the error log for more details.
-ExtractInterfaceInputPage_Select_All=Select &All
-ExtractInterfaceInputPage_Deselect_All=&Deselect All
-ExtractInterfaceInputPage_change_references=Use the extracted interface &type where possible
-ExtractInterfaceWizard_Extract_Interface=Extract Interface
-ExtractInterfaceWizard_generate_comments=Generate function &comments
-ExtractInterfaceWizard_use_supertype=&Use the extracted interface in \'instanceof\' expressions
-ExtractInterfaceWizard_public_label=&public
-ExtractInterfaceWizard_abstract_label=a&bstract
-
-InlineConstantInputPage_Inline=Inline
-InlineConstantInputPage_All_references=&All references
-InlineConstantInputPage_Delete_constant=&Delete constant declaration
-InlineConstantInputPage_Only_selected=&Only the selected reference
-InlineConstantWizard_message=Specify where to inline references to the constant.
-InlineConstantWizard_Inline_Constant=Inline Constant
-InlineConstantWizard_initializer_refers_to_fields=This constant\'s initializer refers to non-final or non-static vars
-
-MoveInnerToTopWizard_Move_Inner=Convert Member Type to Top Level
-MoveInnerToToplnputPage_description=Specify a name for the var that will be used to access the enclosing instance
-MoveInnerToToplnputPage_instance_final=&Declare instance var as \'final\'
-MoveInnerToToplnputPage_optional_info=Choose a name to optionally create an enclosing instance var.
-MoveInnerToToplnputPage_mandatory_info=Choose a name for the enclosing instance var.
-MoveInnerToToplnputPage_enter_name_mandatory=Enclosing instance var &name:
-MoveInnerToToplnputPage_enter_name=Enclosing instance var &name (optional):
-
-MoveInstanceMethodWizard_Move_Method=Move Function
-MoveInstanceMethodPage_Target_name=New &parameter name:
-MoveInstanceMethodPage_Method_name=New &function name:
-MoveInstanceMethodPage_New_receiver=&New target for ''{0}'':
-MoveInstanceMethodPage_Name=Name
-MoveInstanceMethodPage_Type=Type
-MoveInstanceMethodPage_Create_button_name=&Keep original function as delegate to moved function
-MoveInstanceMethodPage_Deprecate_button_name=Mark as &deprecated
-MoveInstanceMethodPage_invalid_target=Target ''{0}'' is used in an assignment.
-
-PromoteTempInputPage_Field_declaration=Var decla&ration
-PromoteTempInputPage_Current_method=&Current function
-PromoteTempInputPage_constructors=C&lass constructor(s)
-PromoteTempInputPage_Field_name=F&ield name:
-PromoteTempInputPage_Initialize=Initialize in
-PromoteTempInputPage_declare_static=D&eclare var as \'static\'
-PromoteTempInputPage_declare_final=Decl&are var as \'final\'
-
-UseSupertypeInputPage_Select_supertype=Select the supertype to use
-UseSupertypeInputPage_Use_in_instanceof=&Use the selected supertype in \'instanceof\' expressions
-UseSupertypeInputPage_Select_supertype_to_use=&Select supertype to use instead of ''{0}'':
-UseSupertypeInputPage_No_updates=No updates possible for the selected supertype
-UseSupertypeInputPage_Use_Supertype=Use Supertype
-UseSupertypeInputPage_Internal_Error=An unexpected exception occurred. See the error log for more details.
-UseSupertypeInputPage_no_possible_updates={0} - no possible updates found
-UseSupertypeInputPage_updates_possible_in_file={0} - updates possible in 1 file
-UseSupertypeInputPage_updates_possible_in_files={0} - updates possible in {1} files
-UseSupertypeWizard_Use_Super_Type_Where_Possible=Use Super Type Where Possible
-
-VisibilityControlUtil_Access_modifier=Access modifier
-VisibilityControlUtil_defa_ult_4=d&efault
-VisibilityControlUtil_final=&final
-VisibilityControlUtil_synchronized=s&ynchronized
-
-PullUpWizard_defaultPageTitle=Pull Up
-PullUpWizard_select_all_label=Select &All
-PullUpWizard_deselect_all_label=Dese&lect All
-PullUpInputPage1_pull_up=pull up
-PullUpInputPage1_declare_abstract=declare abstract in destination
-PullUpInputPage1_Create_stubs=&Create necessary functions stubs in non-abstract subtypes of the destination type
-PullUpInputPage1_Select_destination=&Select destination type:
-PullUpInputPage1_Specify_actions=S&pecify actions for members:
-PullUpInputPage1_Edit=Set Act&ion...
-PullUpInputPage1_Add_Required=Add &Required
-PullUpInputPage1_Edit_members=Set Action
-PullUpInputPage1_Mark_selected_members=&Action for selected member(s):
-PullUpInputPage1_label_use_destination=Use the d&estination type where possible
-PullUpInputPage1_Member=Member
-PullUpInputPage1_Action=Action
-PullUpInputPage1_Select_members_to_pull_up=No members selected to pull up or declare abstract
-PullUpInputPage1_label_use_in_instanceof=&Use the destination type in 'instanceof' expressions
-PullUpInputPage1_page_message=Select the destination type and the members to pull up.
-PullUpInputPage1_status_line={0} member(s) selected.
-
-PullUpInputPage2_Select=Restore &Defaults
-PullUpInputPage2_Source=Source
-
-PushDownWizard_defaultPageTitle= Push Down
-PushDownInputPage_leave_abstract=leave abstract declaration
-PushDownInputPage_push_down=push down
-PushDownInputPage_Specify_actions=&Specify actions for members:
-PushDownInputPage_Member=Member
-PushDownInputPage_Action=Action
-PushDownInputPage_Edit=Se&t Action...
-PushDownInputPage_Add_Required=Add &Required
-PushDownInputPage_Push_Down=Push Down
-PushDownInputPage_Internal_Error=An unexpected exception occurred. See the error log for more details.
-PushDownInputPage_Edit_members=Set Action
-PushDownInputPage_Mark_selected_members=&Action for selected member(s):
-PushDownInputPage_Select_members_to_push_down=No members selected to push down or declare abstract
-PushDownInputPage_status_line={0} member(s) selected.
-
-MoveInstanceMethodAction_dialog_title=Move Function
-MoveInstanceMethodAction_Move_Method=Move Function...
-MoveInstanceMethodAction_unexpected_exception=An unexpected exception occurred. See the error log for more details
-MoveInstanceMethodAction_No_reference_or_declaration=No function reference or declaration selected.
-
-InlineConstantAction_dialog_title=Inline Constant
-InlineConstantAction_inline_Constant=Inline &Constant...
-InlineConstantAction_unexpected_exception=An unexpected exception occurred. See the error log for more details
-InlineConstantAction_no_constant_reference_or_declaration=No constant reference or declaration selected.
-
-InlineMethodInputPage_description=Specify where to inline the function invocation.
-InlineMethodInputPage_inline=Inline
-InlineMethodInputPage_all_invocations=&All invocations
-InlineMethodInputPage_delete_declaration=&Delete function declaration
-InlineMethodInputPage_only_selected=&Only the selected invocation
-
-InlineMethodAction_dialog_title=Inline Function
-InlineMethodAction_inline_Method=I&nline Function...
-InlineMethodAction_unexpected_exception=An unexpected exception occurred. See the error log for more details
-InlineMethodAction_no_method_invocation_or_declaration_selected=No function invocation or declaration selected.
-
-UseSupertypeAction_use_Supertype=Use Supertype W&here Possible...
-UseSupertypeAction_to_activate=To activate this refactoring, please select the name of a type.
-UseSupertypeAction_Refactoring=Refactoring
-UseSupertypeAction_not_possible=Cannot perform operation.
-
-PushDownAction_Push_Down=Push &Down...
-PushDownAction_To_activate=To activate this refactoring, please select the name of a non-binary instance function or var.
-PushDownAction_Refactoring=Refactoring
-PushDownAction_not_possible=Cannot perform operation.
-
-MoveAction_Move=Move
-MoveAction_select=Select a static function, a static var or an instance function that can be moved to a component (parameter or var).
-
-InlineAction_Inline=&Inline...
-InlineAction_dialog_title=Inline
-InlineAction_select=Select a function declaration, a function invocation, a static final var or a local variable that you want to inline.
-
-ExtractInterfaceAction_Extract_Interface=&Extract Interface...
-ExtractInterfaceAction_To_activate=To activate this refactoring, please select the name of a top level type.
-ExtractInterfaceAction_Refactoring=Refactoring
-ExtractSuperTypeAction_unavailable=To activate this refactoring, please select a top-level type or the name of a non-binary instance function or var.
-ExtractInterfaceAction_not_possible=Cannot perform operation.
-
-ConvertNestedToTopAction_Convert=Con&vert Member Type to Top Level
-ConvertNestedToTopAction_To_activate=To activate this refactoring, please select the name of a member type.
-ConvertNestedToTopAction_Refactoring=Refactoring
-ConvertNestedToTopAction_not_possible=Cannot perform operation.
-
-ConvertAnonymousToNestedAction_dialog_title=Convert Anonymous Class to Nested Class
-ConvertAnonymousToNestedAction_Convert_Anonymous=C&onvert Anonymous Class to Nested...
-ConvertAnonymousToNestedAction_wizard_title=Convert Anonymous Class to Nested Class
-
-###################### Temporary Participant Keys #################################
-RenameResourceWizard_defaultPageTitle=Rename Resource
-RenameResourceWizard_inputPage_description=Enter the new name for this resource.
-
-RenameJavaProject_defaultPageTitle=Rename JavaScript Project
-RenameJavaProject_inputPage_description=Enter the new name for this JavaScript project.
-
-RenameSourceFolder_defaultPageTitle=Rename Source Folder
-RenameSourceFolder_inputPage_description=Enter the new name for this source folder.
-
-RenamePackageWizard_defaultPageTitle=Rename Package
-RenamePackageWizard_inputPage_description=Enter the new name for this package.
-RenamePackageWizard_rename_subpackages=Rename &subpackages
-
-RenameCuWizard_defaultPageTitle= Rename JavaScript file
-RenameCuWizard_inputPage_description= Enter the new name for this JavaScript file.
-
-RenameTypeParameterWizard_defaultPageTitle=Rename Type Variable
-RenameTypeParameterWizard_inputPage_description=Enter the new name for this type variable.
-
-RenameMethodWizard_defaultPageTitle=Rename Function
-RenameMethodWizard_inputPage_description= Enter the new name for this function.
-
-RenameLocalVariableWizard_defaultPageTitle=Rename Local Variable
-RenameLocalVariableWizard_inputPage_description=Enter the new name for this local variable.
-
-ExtractInterfaceWizard_12=Declare interface functions as ''{0}''
-
-ParameterEditDialog_type_invalid=''{0}'' is not a valid parameter type name.
-UseSupertypeWizard_10=No updates are possible for the supertypes
-
-DeleteWizard_1=Confirm Delete
-DeleteWizard_2=An unexpected exception occurred. See the error log for more details.
-DeleteWizard_3=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.
-DeleteWizard_4=Are you sure you want to delete {0}?
-DeleteWizard_5=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.
-DeleteWizard_6=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.\n\nNote that all subelements of the selected linked packages and package fragment roots will be removed from the workspace.
-DeleteWizard_7=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.
-DeleteWizard_8=Are you sure you want to delete {0}?
-DeleteWizard_9=Are you sure you want to delete these {0} elements?
-DeleteWizard_10=Are you sure you want to delete these {0} elements?\n\nSelection contains linked resources.\nOnly the workspace links will be deleted. Link targets will remain unchanged.
-DeleteWizard_11=Are you sure you want to delete these {0} elements?\n\nSelection contains linked packages.\nOnly the workspace links will be deleted. Link targets will remain unchanged.\n\nNote that all subelements of linked packages and package fragment roots will be removed from the workspace.
-DeleteWizard_12=The selected element(s) do not exist anymore and cannot be deleted.
-DeleteWizard_also_delete_sub_packages=Delete &subpackages of selected packages
-
-#####################################
-# Rename Type
-#####################################
-
-RenameTypeWizard_defaultPageTitle= Rename Type
-RenameTypeWizard_unexpected_exception=An unexpected exception occurred. See the error log for more details
-
-RenameTypeWizardInputPage_description=Enter the new name for this type.
-RenameTypeWizardInputPage_update_similar_elements=Update &similarly named variables and functions
-RenameTypeWizardInputPage_update_similar_elements_configure=<a>&Configure...</a>
-RenameTypeWizardSimilarElementsPage_name_empty=Please enter a name.
-RenameTypeWizardSimilarElementsPage_rename_to=Rename ''{0}'' to ''{1}''
-RenameTypeWizardSimilarElementsPage_change_element_name=Change Element Name
-RenameTypeWizardSimilarElementsPage_enter_new_name=Enter a new name for the selected element:
-RenameTypeWizardSimilarElementsPage_field_exists=A var with this name already exists in the file.
-RenameTypeWizardSimilarElementsPage_method_exists=A function with this name already exists in the file.
-RenameTypeWizardSimilarElementsPage_restore_defaults=Restore &Defaults
-RenameTypeWizardSimilarElementsPage_change_name=&Change Name...
-RenameTypeWizardSimilarElementsPage_name_should_start_lowercase=Element names should start with a lowercase character.
-RenameTypeWizardSimilarElementsPage_review_similar_elements=&Similarly named variables and functions to be renamed
-RenameTypeWizardSimilarElementsPage_select_element_to_view_source=Select an element
-
-RenameTypeWizardSimilarElementsOptionsDialog_title=Similar Names Configuration
-RenameTypeWizardSimilarElementsOptionsDialog_select_strategy=Strategy for matching type names (e.g., 'SomeClass') in variable and function names:
-RenameTypeWizardSimilarElementsOptionsDialog_warning_short_names=Short type names or short suffixes may lead to unexpected results when matching partial names. Please review the matched elements carefully.
-RenameTypeWizardSimilarElementsOptionsDialog_strategy_1=Find &exact names only ('someClass' or 'someClass()')
-RenameTypeWizardSimilarElementsOptionsDialog_strategy_2=Also find e&mbedded names ('mySomeClassToUse' or 'getSomeClass()')
-RenameTypeWizardSimilarElementsOptionsDialog_strategy_3=Also find name &suffixes ('class', 'myClass', or 'getClassToUse()')
-
-#######################################
-# IntroduceParameter
-#######################################
-IntroduceParameterAction_label=Introduce &Parameter...
-IntroduceParameterAction_dialog_title=Introduce Parameter
-
-IntroduceParameterWizard_defaultPageTitle=Introduce Parameter
-IntroduceParameterWizard_parameters=&Parameters:
-IntroduceParameterInputPage_description=Enter the name for the new parameter.
-
-#######################################
-# Introduce Indirection
-#######################################
-IntroduceIndirectionAction_title=Introduce Indirec&tion...
-IntroduceIndirectionAction_dialog_title=Introduce Indirection
-IntroduceIndirectionAction_tooltip=Introduce an Indirection to Encapsulate Function Calls
-IntroduceIndirectionAction_description=Introduces an indirection to encapsulate calls to the selected function
-IntroduceIndirectionAction_unknown_exception=An unexpected exception occurred. See the error log for more details
-IntroduceIndirectionInputPage_browse=&Browse...
-IntroduceIndirectionInputPage_new_method_name=New function &name:
-IntroduceIndirectionInputPage_declaring_class=Declaring &type:
-IntroduceIndirectionInputPage_update_references=&Redirect all function invocations
-IntroduceIndirectionInputPage_select_declaring_class=Please select a declaring type.
-IntroduceIndirectionInputPage_dialog_choose_declaring_class=Choose Type
-IntroduceIndirectionInputPage_dialog_choose_declaring_class_long=&Choose the type where to insert the new function:
-
-#######################################
-# Introduce Factory
-#######################################
-IntroduceFactoryAction_label=Intr&oduce Factory...
-IntroduceFactoryAction_dialog_title=Introduce Factory
-IntroduceFactoryAction_tooltipText=Introduce a Factory to Encapsulate Object Instantiation
-IntroduceFactoryAction_description=Creates a factory to encapsulate calls to the selected constructor
-IntroduceFactoryAction_use_factory=Introduce Factory
-IntroduceFactoryAction_exception=An unexpected exception occurred. See the error log for more details
-IntroduceFactoryInputPage_name_factory=Factory options
-IntroduceFactoryInputPage_method_name=Factory function &name:
-IntroduceFactoryInputPage_protectConstructorLabel=Ma&ke constructor private
-IntroduceFactoryInputPage_browseLabel=&Browse...
-IntroduceFactoryInputPage_factoryClassLabel=Factory &class:
-IntroduceFactoryInputPage_chooseFactoryClass_title=Choose Factory Class
-IntroduceFactoryInputPage_chooseFactoryClass_message=&Choose the class on which to place the factory function:
-
-#######################################
-# Generalize Declared Type
-#######################################
-ChangeTypeAction_label=Generali&ze Declared Type...
-ChangeTypeAction_tooltipText=Generalize Variable\'s Declared Type
-ChangeTypeAction_description=Change variable\'s declared type to more general type consistent with usage
-ChangeTypeAction_exception=An unexpected exception occurred. See the error log for more details
-ChangeTypeAction_dialog_title=Generalize Declared Type
-
-ChangeTypeWizard_title=Generalize Declared Type
-ChangeTypeWizard_declCannotBeChanged=Type of selected declaration cannot be changed
-ChangeTypeWizard_pleaseChooseType=&Choose new type for ''{0}'':
-ChangeTypeWizard_analyzing=Analyzing...
-ChangeTypeWizard_internalError=An unexpected exception occurred. See the error log for more details.
-ChangeTypeWizard_computationInterrupted=Computation of valid types was interrupted
-ChangeTypeWizard_grayed_types= Type ''{0}'' cannot be used as a replacement for type ''{1}''
-ChangeTypeWizard_with_itself= Cannot replace type ''{0}'' with itself
-ChangeTypeInputPage_Select_Type=Press "Compute" to determine allowable supertypes
-
-JavaTypeCompletionProcessor_no_completion=No completions available.
-JavaStatusContextViewer_no_source_found0=Source not found\n\nThe jar file {0} has no source attachment.
-JavaStatusContextViewer_no_source_available=No source available
-
-#######################################
-# Infer Type Arguments
-#######################################
-InferTypeArgumentsAction_label=Infer &Generic Type Arguments...
-InferTypeArgumentsAction_dialog_title=Infer Generic Type Arguments
-InferTypeArgumentsAction_unavailable=To activate this refactoring, please select a set of JavaScript files, packages, source folders, or javaScript projects.
-
-InferTypeArgumentsWizard_defaultPageTitle=Infer Generic Type Arguments
-InferTypeArgumentsInputPage_description=Infer Generic Type Arguments
-InferTypeArgumentsWizard_lengthyDescription=Infer type arguments for references to generic types and remove unnecessary casts.
-InferTypeArgumentsWizard_assumeCloneSameType=&Assume clone() returns an instance of the receiver type
-InferTypeArgumentsWizard_leaveUnconstrainedRaw=&Leave unconstrained type arguments raw (rather than inferring <?>)
-
-#######################################
-# Replace Invocations
-#######################################
-ReplaceInvocationsAction_label=Replace In&vocations...
-ReplaceInvocationsWizard_title=Replace Function Invocations
-ReplaceInvocationsAction_dialog_title=Replace Invocations
-ReplaceInvocationsInputPage_replaceInvocationsBy=&Replace Invocations by:
-ReplaceInvocationsInputPage_replaceAll=Replace &all invocations
-ReplaceInvocationsAction_unavailable=An unexpected exception occurred. See the error log for more details
-RefactoringExecutionStarter_IntroduceParameterObject_problem_title=Introduce Parameter Object
-RefactoringExecutionStarter_IntroduceParameterObject_problem_description=Cannot add a parameter object as the selected function overrides or implements a read only function
-
-
-JarImportWizard_prepare_import=Prepare replay of refactorings...
-JarImportWizard_error_shared_jar=Cannot replay refactorings, since the JAR file is also on the build path of project ''{0}''.
-BinaryRefactoringHistoryWizard_error_missing_source_attachment=The refactoring ''{0}'' cannot be performed, since it needs a source attachment.
-JarImportWizard_cleanup_import=Finish replay of refactorings...
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CopyToClipboardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CopyToClipboardAction.java
deleted file mode 100644
index 2a4391b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CopyToClipboardAction.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypedSource;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaElementTransfer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ParentChecker;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-
-public class CopyToClipboardAction extends SelectionDispatchAction{
-
- private final Clipboard fClipboard;
- private boolean fAutoRepeatOnFailure= false;
-
- public CopyToClipboardAction(IWorkbenchSite site, Clipboard clipboard) {
- super(site);
- setText(ReorgMessages.CopyToClipboardAction_0);
- setDescription(ReorgMessages.CopyToClipboardAction_1);
- Assert.isNotNull(clipboard);
- fClipboard= clipboard;
- ISharedImages workbenchImages= getWorkbenchSharedImages();
- setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
- setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
- setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
- update(getSelection());
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.COPY_ACTION);
- }
-
- public void setAutoRepeatOnFailure(boolean autorepeatOnFailure){
- fAutoRepeatOnFailure= autorepeatOnFailure;
- }
-
- private static ISharedImages getWorkbenchSharedImages() {
- return JavaScriptPlugin.getDefault().getWorkbench().getSharedImages();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (elements.size() != resources.length + javaElements.length)
- setEnabled(false);
- else
- setEnabled(canEnable(resources, javaElements));
- } catch (JavaScriptModelException e) {
- //no ui here - this happens on selection changes
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (elements.size() == resources.length + javaElements.length && canEnable(resources, javaElements))
- doRun(resources, javaElements);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), ReorgMessages.CopyToClipboardAction_2, ReorgMessages.CopyToClipboardAction_3);
- }
- }
-
- private void doRun(IResource[] resources, IJavaScriptElement[] javaElements) throws CoreException {
- new ClipboardCopier(resources, javaElements, fClipboard, getShell(), fAutoRepeatOnFailure).copyToClipboard();
- }
-
- private boolean canEnable(IResource[] resources, IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- return new CopyToClipboardEnablementPolicy(resources, javaElements).canEnable();
- }
-
- //----------------------------------------------------------------------------------------//
-
- private static class ClipboardCopier{
- private final boolean fAutoRepeatOnFailure;
- private final IResource[] fResources;
- private final IJavaScriptElement[] fJavaElements;
- private final Clipboard fClipboard;
- private final Shell fShell;
- private final ILabelProvider fLabelProvider;
-
- private ClipboardCopier(IResource[] resources, IJavaScriptElement[] javaElements, Clipboard clipboard, Shell shell, boolean autoRepeatOnFailure){
- Assert.isNotNull(resources);
- Assert.isNotNull(javaElements);
- Assert.isNotNull(clipboard);
- Assert.isNotNull(shell);
- fResources= resources;
- fJavaElements= javaElements;
- fClipboard= clipboard;
- fShell= shell;
- fLabelProvider= createLabelProvider();
- fAutoRepeatOnFailure= autoRepeatOnFailure;
- }
-
- public void copyToClipboard() throws CoreException{
- //Set<String> fileNames
- Set fileNames= new HashSet(fResources.length + fJavaElements.length);
- StringBuffer namesBuf = new StringBuffer();
- processResources(fileNames, namesBuf);
- processJavaElements(fileNames, namesBuf);
-
- IType[] mainTypes= ReorgUtils.getMainTypes(fJavaElements);
- IJavaScriptUnit[] cusOfMainTypes= ReorgUtils.getCompilationUnits(mainTypes);
- IResource[] resourcesOfMainTypes= ReorgUtils.getResources(cusOfMainTypes);
- addFileNames(fileNames, resourcesOfMainTypes);
-
- IResource[] cuResources= ReorgUtils.getResources(getCompilationUnits(fJavaElements));
- addFileNames(fileNames, cuResources);
-
- IResource[] resourcesForClipboard= ReorgUtils.union(fResources, ReorgUtils.union(cuResources, resourcesOfMainTypes));
- IJavaScriptElement[] javaElementsForClipboard= ReorgUtils.union(fJavaElements, cusOfMainTypes);
-
- TypedSource[] typedSources= TypedSource.createTypedSources(javaElementsForClipboard);
- String[] fileNameArray= (String[]) fileNames.toArray(new String[fileNames.size()]);
- copyToClipboard(resourcesForClipboard, fileNameArray, namesBuf.toString(), javaElementsForClipboard, typedSources, 0);
- }
-
- private static IJavaScriptElement[] getCompilationUnits(IJavaScriptElement[] javaElements) {
- List cus= ReorgUtils.getElementsOfType(javaElements, IJavaScriptElement.JAVASCRIPT_UNIT);
- return (IJavaScriptUnit[]) cus.toArray(new IJavaScriptUnit[cus.size()]);
- }
-
- private void processResources(Set fileNames, StringBuffer namesBuf) {
- for (int i= 0; i < fResources.length; i++) {
- IResource resource= fResources[i];
- addFileName(fileNames, resource);
-
- if (i > 0)
- namesBuf.append('\n');
- namesBuf.append(getName(resource));
- }
- }
-
- private void processJavaElements(Set fileNames, StringBuffer namesBuf) {
- for (int i= 0; i < fJavaElements.length; i++) {
- IJavaScriptElement element= fJavaElements[i];
- switch (element.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- case IJavaScriptElement.CLASS_FILE :
- addFileName(fileNames, ReorgUtils.getResource(element));
- break;
- default :
- break;
- }
-
- if (fResources.length > 0 || i > 0)
- namesBuf.append('\n');
- namesBuf.append(getName(element));
- }
- }
-
- private static void addFileNames(Set fileName, IResource[] resources) {
- for (int i= 0; i < resources.length; i++) {
- addFileName(fileName, resources[i]);
- }
- }
-
- private static void addFileName(Set fileName, IResource resource){
- if (resource == null)
- return;
- IPath location = resource.getLocation();
- if (location != null) {
- fileName.add(location.toOSString());
- } else {
- // not a file system path. skip file.
- }
- }
-
- private void copyToClipboard(IResource[] resources, String[] fileNames, String names, IJavaScriptElement[] javaElements, TypedSource[] typedSources, int repeat){
- final int repeat_max_count= 10;
- try{
- fClipboard.setContents( createDataArray(resources, javaElements, fileNames, names, typedSources),
- createDataTypeArray(resources, javaElements, fileNames, typedSources));
- } catch (SWTError e) {
- if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD || repeat >= repeat_max_count)
- throw e;
- if (fAutoRepeatOnFailure) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e1) {
- // do nothing.
- }
- }
- if (fAutoRepeatOnFailure || MessageDialog.openQuestion(fShell, ReorgMessages.CopyToClipboardAction_4, ReorgMessages.CopyToClipboardAction_5))
- copyToClipboard(resources, fileNames, names, javaElements, typedSources, repeat+1);
- }
- }
-
- private static Transfer[] createDataTypeArray(IResource[] resources, IJavaScriptElement[] javaElements, String[] fileNames, TypedSource[] typedSources) {
- List result= new ArrayList(4);
- if (resources.length != 0)
- result.add(ResourceTransfer.getInstance());
- if (javaElements.length != 0)
- result.add(JavaElementTransfer.getInstance());
- if (fileNames.length != 0)
- result.add(FileTransfer.getInstance());
- if (typedSources.length != 0)
- result.add(TypedSourceTransfer.getInstance());
- result.add(TextTransfer.getInstance());
- return (Transfer[]) result.toArray(new Transfer[result.size()]);
- }
-
- private static Object[] createDataArray(IResource[] resources, IJavaScriptElement[] javaElements, String[] fileNames, String names, TypedSource[] typedSources) {
- List result= new ArrayList(4);
- if (resources.length != 0)
- result.add(resources);
- if (javaElements.length != 0)
- result.add(javaElements);
- if (fileNames.length != 0)
- result.add(fileNames);
- if (typedSources.length != 0)
- result.add(typedSources);
- result.add(names);
- return result.toArray();
- }
-
- private static ILabelProvider createLabelProvider(){
- return new JavaScriptElementLabelProvider(
- JavaScriptElementLabelProvider.SHOW_VARIABLE
- + JavaScriptElementLabelProvider.SHOW_PARAMETERS
- + JavaScriptElementLabelProvider.SHOW_TYPE
- );
- }
- private String getName(IResource resource){
- return fLabelProvider.getText(resource);
- }
- private String getName(IJavaScriptElement javaElement){
- return fLabelProvider.getText(javaElement);
- }
- }
-
- private static class CopyToClipboardEnablementPolicy {
- private final IResource[] fResources;
- private final IJavaScriptElement[] fJavaElements;
- public CopyToClipboardEnablementPolicy(IResource[] resources, IJavaScriptElement[] javaElements){
- Assert.isNotNull(resources);
- Assert.isNotNull(javaElements);
- fResources= resources;
- fJavaElements= javaElements;
- }
-
- public boolean canEnable() throws JavaScriptModelException{
- if (fResources.length + fJavaElements.length == 0)
- return false;
- if (hasProjects() && hasNonProjects())
- return false;
- if (! canCopyAllToClipboard())
- return false;
- if (! new ParentChecker(fResources, fJavaElements).haveCommonParent())
- return false;
- return true;
- }
-
- private boolean canCopyAllToClipboard() throws JavaScriptModelException {
- for (int i= 0; i < fResources.length; i++) {
- if (! canCopyToClipboard(fResources[i])) return false;
- }
- for (int i= 0; i < fJavaElements.length; i++) {
- if (! canCopyToClipboard(fJavaElements[i])) return false;
- }
- return true;
- }
-
- private static boolean canCopyToClipboard(IJavaScriptElement element) throws JavaScriptModelException {
- if (element == null || ! element.exists())
- return false;
-
- if (JavaElementUtil.isDefaultPackage(element))
- return false;
-
- return true;
- }
-
- private static boolean canCopyToClipboard(IResource resource) {
- return resource != null &&
- resource.exists() &&
- ! resource.isPhantom() &&
- resource.getType() != IResource.ROOT;
- }
-
- private boolean hasProjects() {
- for (int i= 0; i < fResources.length; i++) {
- if (ReorgUtils.isProject(fResources[i])) return true;
- }
- for (int i= 0; i < fJavaElements.length; i++) {
- if (ReorgUtils.isProject(fJavaElements[i])) return true;
- }
- return false;
- }
-
- private boolean hasNonProjects() {
- for (int i= 0; i < fResources.length; i++) {
- if (! ReorgUtils.isProject(fResources[i])) return true;
- }
- for (int i= 0; i < fJavaElements.length; i++) {
- if (! ReorgUtils.isProject(fJavaElements[i])) return true;
- }
- return false;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CreateTargetQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CreateTargetQueries.java
deleted file mode 100644
index 893f2fab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CreateTargetQueries.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ICreateTargetQueries;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ICreateTargetQuery;
-
-public class CreateTargetQueries implements ICreateTargetQueries {
-
- private final Wizard fWizard;
- private final Shell fShell;
-
- public CreateTargetQueries(Wizard wizard) {
- fWizard= wizard;
- fShell= null;
- }
-
- public CreateTargetQueries(Shell shell) {
- fShell = shell;
- fWizard= null;
- }
-
- public ICreateTargetQuery createNewPackageQuery() {
- return new ICreateTargetQuery() {
- public Object getCreatedTarget(Object selection) {
- return null;
- }
-
- public String getNewButtonLabel() {
- return ReorgMessages.ReorgMoveWizard_newPackage;
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CutAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CutAction.java
deleted file mode 100644
index 4ca8533c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/CutAction.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class CutAction extends SelectionDispatchAction{
-
- private CopyToClipboardAction fCopyToClipboardAction;
-
- public CutAction(IWorkbenchSite site, Clipboard clipboard) {
- super(site);
- setText(ReorgMessages.CutAction_text);
- fCopyToClipboardAction= new CopyToClipboardAction(site, clipboard);
-
- ISharedImages workbenchImages= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages();
- setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
- setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
- setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CUT_ACTION);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- if (!selection.isEmpty()) {
- try {
- // cannot cut top-level types. this deletes the cu and then you cannot paste because the cu is gone.
- if (!containsOnlyElementsInsideCompilationUnits(selection) || containsTopLevelTypes(selection)) {
- setEnabled(false);
- return;
- }
- fCopyToClipboardAction.selectionChanged(selection);
- setEnabled(fCopyToClipboardAction.isEnabled() && RefactoringAvailabilityTester.isDeleteAvailable(selection));
- } catch (CoreException e) {
- // no ui here - this happens on selection changes
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- } else
- setEnabled(false);
- }
-
- private static boolean containsOnlyElementsInsideCompilationUnits(IStructuredSelection selection) {
- for (Iterator iter = selection.iterator(); iter.hasNext();) {
- Object object= iter.next();
- if (! (object instanceof IJavaScriptElement && ReorgUtils.isInsideCompilationUnit((IJavaScriptElement)object)))
- return false;
- }
- return true;
- }
-
- private static boolean containsTopLevelTypes(IStructuredSelection selection) {
- for (Iterator iter = selection.iterator(); iter.hasNext();) {
- Object each= iter.next();
- if ((each instanceof IType) && ((IType)each).getDeclaringType() == null)
- return true;
- }
- return false;
- }
-
- public void run(IStructuredSelection selection) {
- try {
- selectionChanged(selection);
- if (isEnabled()) {
- fCopyToClipboardAction.run(selection);
- RefactoringExecutionStarter.startCutRefactoring(selection.toArray(), getShell());
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- } catch (InterruptedException e) {
- //OK
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteAction.java
deleted file mode 100644
index 32ba24cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteAction.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.DeleteResourceAction;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-
-public class DeleteAction extends SelectionDispatchAction {
-
- public DeleteAction(IWorkbenchSite site) {
- super(site);
- setText(ReorgMessages.DeleteAction_3);
- setDescription(ReorgMessages.DeleteAction_4);
- ISharedImages workbenchImages= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages();
- setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE_DISABLED));
- setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
- setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.DELETE_ACTION);
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())) {
- setEnabled(createWorkbenchAction(selection).isEnabled());
- return;
- }
- try {
- setEnabled(RefactoringAvailabilityTester.isDeleteAvailable(selection.toArray()));
- } catch (CoreException e) {
- //no ui here - this happens on selection changes
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- private IAction createWorkbenchAction(IStructuredSelection selection) {
- DeleteResourceAction action= new DeleteResourceAction(getShell());
- action.selectionChanged(selection);
- return action;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())) {
- createWorkbenchAction(selection).run();
- return;
- }
- try {
- RefactoringExecutionStarter.startDeleteRefactoring(selection.toArray(), getShell());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteUserInterfaceManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteUserInterfaceManager.java
deleted file mode 100644
index b0fe6b8d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteUserInterfaceManager.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteProcessor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceManager;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceStarter;
-
-public class DeleteUserInterfaceManager extends UserInterfaceManager {
- private static final UserInterfaceManager fgInstance= new DeleteUserInterfaceManager();
-
- public static UserInterfaceManager getDefault() {
- return fgInstance;
- }
-
- private DeleteUserInterfaceManager() {
- put(JavaDeleteProcessor.class, UserInterfaceStarter.class, DeleteWizard.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteWizard.java
deleted file mode 100644
index bf29ea4f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DeleteWizard.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.participants.DeleteRefactoring;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.MessageWizardPage;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class DeleteWizard extends RefactoringWizard {
-
- public DeleteWizard(Refactoring refactoring) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE | YES_NO_BUTTON_STYLE | NO_PREVIEW_PAGE | NO_BACK_BUTTON_ON_STATUS_DIALOG);
- setDefaultPageTitle(RefactoringMessages.DeleteWizard_1);
- ((JavaDeleteProcessor)((DeleteRefactoring)getRefactoring()).getProcessor()).setQueries(new ReorgQueries(this));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- addPage(new DeleteInputPage());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringWizard#getMessageLineWidthInChars()
- */
- public int getMessageLineWidthInChars() {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.Wizard#needsProgressMonitor()
- */
- public boolean needsProgressMonitor() {
- DeleteRefactoring refactoring= (DeleteRefactoring)getRefactoring();
- RefactoringProcessor processor= refactoring.getProcessor();
- if (processor instanceof JavaDeleteProcessor) {
- return ((JavaDeleteProcessor)processor).needsProgressMonitor();
- }
- return super.needsProgressMonitor();
- }
-
- private static class DeleteInputPage extends MessageWizardPage {
- private static final String PAGE_NAME= "DeleteInputPage"; //$NON-NLS-1$
- private static final String DIALOG_SETTINGS_DELETE_SUB_PACKAGES= "deleteSubPackages"; //$NON-NLS-1$
- private Button fDeleteSubPackagesCheckBox;
-
- public DeleteInputPage() {
- super(PAGE_NAME, true, MessageWizardPage.STYLE_QUESTION);
- }
-
- protected String getMessageString() {
- try {
- if (1 == numberOfSelectedElements()) {
- String pattern= createConfirmationStringForOneElement();
- String name= getNameOfSingleSelectedElement();
- return Messages.format(pattern, new String[] { name });
- } else {
- String pattern= createConfirmationStringForManyElements();
- return Messages.format(pattern, new String[] { String.valueOf(numberOfSelectedElements())});
- }
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setPageComplete(false);
- if (e.isDoesNotExist())
- return RefactoringMessages.DeleteWizard_12;
- return RefactoringMessages.DeleteWizard_2;
- }
- }
-
- public void createControl(Composite parent) {
- super.createControl(parent);
-
- if (getDeleteProcessor().hasSubPackagesToDelete())
- addDeleteSubPackagesCheckBox();
- }
-
- /**
- * Adds the "delete subpackages" checkbox to the composite. Note that
- * this code assumes that the control of the parent is a Composite with
- * GridLayout and a horizontal span of 2.
- *
- * @see MessageWizardPage#createControl(Composite)
- */
- private void addDeleteSubPackagesCheckBox() {
-
- Composite c= new Composite((Composite) getControl(), SWT.NONE);
- GridLayout gd= new GridLayout();
- gd.horizontalSpacing= 10;
- c.setLayout(gd);
-
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.horizontalSpan= 2;
- c.setLayoutData(data);
-
- final boolean selection= getRefactoringSettings().getBoolean(DIALOG_SETTINGS_DELETE_SUB_PACKAGES);
-
- fDeleteSubPackagesCheckBox= new Button(c, SWT.CHECK);
- fDeleteSubPackagesCheckBox.setText(RefactoringMessages.DeleteWizard_also_delete_sub_packages);
- fDeleteSubPackagesCheckBox.setSelection(selection);
-
- fDeleteSubPackagesCheckBox.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent event) {
- getDeleteProcessor().setDeleteSubPackages(fDeleteSubPackagesCheckBox.getSelection());
- }
- });
-
- getDeleteProcessor().setDeleteSubPackages(fDeleteSubPackagesCheckBox.getSelection());
- }
-
- private String getNameOfSingleSelectedElement() throws JavaScriptModelException {
- if (getSingleSelectedResource() != null)
- return ReorgUtils.getName(getSingleSelectedResource());
- else
- return ReorgUtils.getName(getSingleSelectedJavaElement());
- }
-
- private IJavaScriptElement getSingleSelectedJavaElement() {
- IJavaScriptElement[] elements= getSelectedJavaElements();
- return elements.length == 1 ? elements[0] : null;
- }
-
- private IResource getSingleSelectedResource() {
- IResource[] resources= getSelectedResources();
- return resources.length == 1 ? resources[0] : null;
- }
-
- private int numberOfSelectedElements() {
- return getSelectedJavaElements().length + getSelectedResources().length;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringWizardPage#performFinish()
- */
- protected boolean performFinish() {
- return super.performFinish() || getDeleteProcessor().wasCanceled(); //close the dialog if canceled
- }
-
- protected boolean saveSettings() {
- if (getContainer() instanceof Dialog)
- return ((Dialog) getContainer()).getReturnCode() == IDialogConstants.OK_ID;
- return true;
- }
-
- public void dispose() {
- if (fDeleteSubPackagesCheckBox != null && saveSettings())
- getRefactoringSettings().put(DIALOG_SETTINGS_DELETE_SUB_PACKAGES, fDeleteSubPackagesCheckBox.getSelection());
- super.dispose();
- }
-
- private String createConfirmationStringForOneElement() throws JavaScriptModelException {
- IJavaScriptElement[] elements= getSelectedJavaElements();
- if (elements.length == 1) {
- IJavaScriptElement element= elements[0];
- if (isDefaultPackageWithLinkedFiles(element))
- return RefactoringMessages.DeleteWizard_3;
-
- if (!isLinkedResource(element))
- return RefactoringMessages.DeleteWizard_4;
-
- if (isLinkedPackageOrPackageFragmentRoot(element))
- //XXX workaround for jcore bugs 31998 and 31456 - linked packages or source folders cannot be deleted properly
- return RefactoringMessages.DeleteWizard_6;
-
- return RefactoringMessages.DeleteWizard_5;
- } else {
- if (isLinked(getSelectedResources()[0])) //checked before that this will work
- return RefactoringMessages.DeleteWizard_7;
- else
- return RefactoringMessages.DeleteWizard_8;
- }
- }
-
- private String createConfirmationStringForManyElements() throws JavaScriptModelException {
- IResource[] resources= getSelectedResources();
- IJavaScriptElement[] javaElements= getSelectedJavaElements();
- if (!containsLinkedResources(resources, javaElements))
- return RefactoringMessages.DeleteWizard_9;
-
- if (!containsLinkedPackagesOrPackageFragmentRoots(javaElements))
- return RefactoringMessages.DeleteWizard_10;
-
- //XXX workaround for jcore bugs - linked packages or source folders cannot be deleted properly
- return RefactoringMessages.DeleteWizard_11;
- }
-
- private static boolean isLinkedPackageOrPackageFragmentRoot(IJavaScriptElement element) {
- if ((element instanceof IPackageFragment) || (element instanceof IPackageFragmentRoot))
- return isLinkedResource(element);
- else
- return false;
- }
-
- private static boolean containsLinkedPackagesOrPackageFragmentRoots(IJavaScriptElement[] javaElements) {
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (isLinkedPackageOrPackageFragmentRoot(element))
- return true;
- }
- return false;
- }
-
- private static boolean containsLinkedResources(IResource[] resources, IJavaScriptElement[] javaElements) throws JavaScriptModelException {
- for (int i= 0; i < javaElements.length; i++) {
- IJavaScriptElement element= javaElements[i];
- if (isLinkedResource(element))
- return true;
- if (isDefaultPackageWithLinkedFiles(element))
- return true;
- }
- for (int i= 0; i < resources.length; i++) {
- IResource resource= resources[i];
- if (isLinked(resource))
- return true;
- }
- return false;
- }
-
- private static boolean isDefaultPackageWithLinkedFiles(Object firstElement) throws JavaScriptModelException {
- if (!JavaElementUtil.isDefaultPackage(firstElement))
- return false;
- IPackageFragment defaultPackage= (IPackageFragment)firstElement;
- IJavaScriptUnit[] cus= defaultPackage.getJavaScriptUnits();
- for (int i= 0; i < cus.length; i++) {
- if (isLinkedResource(cus[i]))
- return true;
- }
- return false;
- }
-
- private static boolean isLinkedResource(IJavaScriptElement element) {
- return isLinked(ReorgUtils.getResource(element));
- }
-
- private static boolean isLinked(IResource resource) {
- return resource != null && resource.isLinked();
- }
-
- private IJavaScriptElement[] getSelectedJavaElements() {
- return getDeleteProcessor().getJavaElementsToDelete();
- }
-
- private IResource[] getSelectedResources() {
- return getDeleteProcessor().getResourcesToDelete();
- }
-
- private JavaDeleteProcessor getDeleteProcessor() {
- return (JavaDeleteProcessor) ((DeleteRefactoring) getRefactoring()).getProcessor();
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DestinationContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DestinationContentProvider.java
deleted file mode 100644
index 47165a24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/DestinationContentProvider.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgDestinationValidator;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-
-public final class DestinationContentProvider extends StandardJavaScriptElementContentProvider {
-
- private IReorgDestinationValidator fValidator;
-
- public DestinationContentProvider(IReorgDestinationValidator validator) {
- super(true);
- fValidator= validator;
- }
-
- public boolean hasChildren(Object element) {
- if (element instanceof IJavaScriptElement){
- IJavaScriptElement javaElement= (IJavaScriptElement) element;
- if (! fValidator.canChildrenBeDestinations(javaElement))
- return false;
- if (javaElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT){
- if (((IPackageFragmentRoot)javaElement).isArchive())
- return false;
- }
- } else if (element instanceof IResource) {
- IResource resource= (IResource) element;
- if (! fValidator.canChildrenBeDestinations(resource))
- return false;
- }
- return super.hasChildren(element);
- }
-
- public Object[] getChildren(Object element) {
- try {
- if (element instanceof IJavaScriptModel) {
- return concatenate(getJavaProjects((IJavaScriptModel)element), getOpenNonJavaProjects((IJavaScriptModel)element));
- } else {
- Object[] children= doGetChildren(element);
- ArrayList result= new ArrayList(children.length);
- for (int i= 0; i < children.length; i++) {
- if (children[i] instanceof IJavaScriptElement) {
- IJavaScriptElement javaElement= (IJavaScriptElement) children[i];
- if (fValidator.canElementBeDestination(javaElement) || fValidator.canChildrenBeDestinations(javaElement))
- result.add(javaElement);
- } else if (children[i] instanceof IResource) {
- IResource resource= (IResource) children[i];
- if (fValidator.canElementBeDestination(resource) || fValidator.canChildrenBeDestinations(resource))
- result.add(resource);
- }
- }
- return result.toArray();
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return new Object[0];
- }
- }
-
- private Object[] doGetChildren(Object parentElement) {
- if (parentElement instanceof IContainer) {
- final IContainer container= (IContainer) parentElement;
- return getResources(container);
- }
- return super.getChildren(parentElement);
- }
-
- // Copied from supertype
- private Object[] getResources(IContainer container) {
- try {
- IResource[] members= container.members();
- IJavaScriptProject javaProject= JavaScriptCore.create(container.getProject());
- if (javaProject == null || !javaProject.exists())
- return members;
- boolean isFolderOnClasspath = javaProject.isOnIncludepath(container);
- List nonJavaResources= new ArrayList();
- // Can be on classpath but as a member of non-java resource folder
- for (int i= 0; i < members.length; i++) {
- IResource member= members[i];
- // A resource can also be a java element
- // in the case of exclusion and inclusion filters.
- // We therefore exclude Java elements from the list
- // of non-Java resources.
- if (isFolderOnClasspath) {
- if (javaProject.findPackageFragmentRoot(member.getFullPath()) == null) {
- nonJavaResources.add(member);
- }
- } else if (!javaProject.isOnIncludepath(member)) {
- nonJavaResources.add(member);
- }
- }
- return nonJavaResources.toArray();
- } catch(CoreException e) {
- return NO_CHILDREN;
- }
- }
-
- private static Object[] getOpenNonJavaProjects(IJavaScriptModel model) throws JavaScriptModelException {
- Object[] nonJavaProjects= model.getNonJavaScriptResources();
- ArrayList result= new ArrayList(nonJavaProjects.length);
- for (int i= 0; i < nonJavaProjects.length; i++) {
- IProject project = (IProject) nonJavaProjects[i];
- if (project.isOpen())
- result.add(project);
- }
- return result.toArray();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/NewNameQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/NewNameQueries.java
deleted file mode 100644
index 1d72dec9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/NewNameQueries.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQueries;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.INewNameQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-
-public class NewNameQueries implements INewNameQueries {
-
- private static final String INVALID_NAME_NO_MESSAGE= "";//$NON-NLS-1$
- private final Wizard fWizard;
- private final Shell fShell;
-
- public NewNameQueries() {
- fShell= null;
- fWizard= null;
- }
-
- public NewNameQueries(Wizard wizard) {
- fWizard= wizard;
- fShell= null;
- }
-
- public NewNameQueries(Shell shell) {
- fShell = shell;
- fWizard= null;
- }
-
- private Shell getShell() {
- Assert.isTrue(fWizard == null || fShell == null);
- if (fWizard != null)
- return fWizard.getContainer().getShell();
-
- if (fShell != null)
- return fShell;
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- public INewNameQuery createNewCompilationUnitNameQuery(IJavaScriptUnit cu, String initialSuggestedName) {
- String[] keys= {JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName())};
- String message= Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys);
- return createStaticQuery(createCompilationUnitNameValidator(cu), message, initialSuggestedName, getShell());
- }
-
-
- public INewNameQuery createNewResourceNameQuery(IResource res, String initialSuggestedName) {
- String[] keys= {res.getName()};
- String message= Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys);
- return createStaticQuery(createResourceNameValidator(res), message, initialSuggestedName, getShell());
- }
-
-
- public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String initialSuggestedName) {
- String[] keys= {pack.getElementName()};
- String message= Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys);
- return createStaticQuery(createPackageNameValidator(pack), message, initialSuggestedName, getShell());
- }
-
- public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) {
- String[] keys= {root.getElementName()};
- String message= Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys);
- return createStaticQuery(createPackageFragmentRootNameValidator(root), message, initialSuggestedName, getShell());
- }
-
-
- public INewNameQuery createNullQuery(){
- return createStaticQuery(null);
- }
-
-
- public INewNameQuery createStaticQuery(final String newName){
- return new INewNameQuery(){
- public String getNewName() {
- return newName;
- }
- };
- }
-
- private static INewNameQuery createStaticQuery(final IInputValidator validator, final String message, final String initial, final Shell shell){
- return new INewNameQuery(){
- public String getNewName() throws OperationCanceledException {
- InputDialog dialog= new InputDialog(shell, ReorgMessages.ReorgQueries_nameConflictMessage, message, initial, validator) {
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.InputDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Control area= super.createDialogArea(parent);
- TextFieldNavigationHandler.install(getText());
- return area;
- }
- };
- if (dialog.open() == Window.CANCEL)
- throw new OperationCanceledException();
- return dialog.getValue();
- }
- };
- }
-
- private static IInputValidator createResourceNameValidator(final IResource res){
- IInputValidator validator= new IInputValidator(){
- public String isValid(String newText) {
- if (newText == null || "".equals(newText) || res.getParent() == null) //$NON-NLS-1$
- return INVALID_NAME_NO_MESSAGE;
- if (res.getParent().findMember(newText) != null)
- return ReorgMessages.ReorgQueries_resourceWithThisNameAlreadyExists;
- if (! res.getParent().getFullPath().isValidSegment(newText))
- return ReorgMessages.ReorgQueries_invalidNameMessage;
- IStatus status= res.getParent().getWorkspace().validateName(newText, res.getType());
- if (status.getSeverity() == IStatus.ERROR)
- return status.getMessage();
-
- if (res.getName().equalsIgnoreCase(newText))
- return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage;
-
- return null;
- }
- };
- return validator;
- }
-
- private static IInputValidator createCompilationUnitNameValidator(final IJavaScriptUnit cu) {
- IInputValidator validator= new IInputValidator(){
- public String isValid(String newText) {
- if (newText == null || "".equals(newText)) //$NON-NLS-1$
- return INVALID_NAME_NO_MESSAGE;
- String newCuName= JavaModelUtil.getRenamedCUName(cu, newText);
- IStatus status= JavaScriptConventions.validateCompilationUnitName(newCuName);
- if (status.getSeverity() == IStatus.ERROR)
- return status.getMessage();
- RefactoringStatus refStatus;
- refStatus= Checks.checkCompilationUnitNewName(cu, newText);
- if (refStatus.hasFatalError())
- return refStatus.getMessageMatchingSeverity(RefactoringStatus.FATAL);
-
- if (cu.getElementName().equalsIgnoreCase(newCuName))
- return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage;
-
- return null;
- }
- };
- return validator;
- }
-
-
- private static IInputValidator createPackageFragmentRootNameValidator(final IPackageFragmentRoot root) {
- return new IInputValidator() {
- IInputValidator resourceNameValidator= createResourceNameValidator(root.getResource());
- public String isValid(String newText) {
- return resourceNameValidator.isValid(newText);
- }
- };
- }
-
- private static IInputValidator createPackageNameValidator(final IPackageFragment pack) {
- IInputValidator validator= new IInputValidator(){
- public String isValid(String newText) {
- if (newText == null || "".equals(newText)) //$NON-NLS-1$
- return INVALID_NAME_NO_MESSAGE;
- IStatus status= JavaScriptConventions.validatePackageName(newText);
- if (status.getSeverity() == IStatus.ERROR)
- return status.getMessage();
-
- IJavaScriptElement parent= pack.getParent();
- try {
- if (parent instanceof IPackageFragmentRoot){
- if (! RenamePackageProcessor.isPackageNameOkInRoot(newText, (IPackageFragmentRoot)parent))
- return ReorgMessages.ReorgQueries_packagewithThatNameexistsMassage;
- }
- } catch (CoreException e) {
- return INVALID_NAME_NO_MESSAGE;
- }
- if (pack.getElementName().equalsIgnoreCase(newText))
- return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage;
-
- return null;
- }
- };
- return validator;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/PasteAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/PasteAction.java
deleted file mode 100644
index c20d9318..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/PasteAction.java
+++ /dev/null
@@ -1,1141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
-import org.eclipse.ui.actions.CopyProjectOperation;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.PackageDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypedSource;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.TextChangeCompatibility;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IConfirmQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgQueries;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaElementTransfer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ParentChecker;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringFileBuffers;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.ResourceUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.OthersWorkingSetUpdater;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-
-public class PasteAction extends SelectionDispatchAction{
-
- private final Clipboard fClipboard;
-
- public PasteAction(IWorkbenchSite site, Clipboard clipboard) {
- super(site);
- Assert.isNotNull(clipboard);
- fClipboard= clipboard;
-
- setText(ReorgMessages.PasteAction_4);
- setDescription(ReorgMessages.PasteAction_5);
-
- ISharedImages workbenchImages= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages();
- setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
- setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
- setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.PASTE_ACTION);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- // Moved condition checking to run (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=78450)
- }
-
- private Paster[] createEnabledPasters(TransferData[] availableDataTypes) throws JavaScriptModelException {
- Paster paster;
- Shell shell = getShell();
- List result= new ArrayList(2);
- paster= new ProjectPaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
-
- paster= new JavaElementAndResourcePaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
-
- paster= new TypedSourcePaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
-
- paster= new FilePaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
-
- paster= new WorkingSetPaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
-
- paster= new TextPaster(shell, fClipboard);
- if (paster.canEnable(availableDataTypes))
- result.add(paster);
- return (Paster[]) result.toArray(new Paster[result.size()]);
- }
-
- private static Object getContents(final Clipboard clipboard, final Transfer transfer, Shell shell) {
- //see bug 33028 for explanation why we need this
- final Object[] result= new Object[1];
- shell.getDisplay().syncExec(new Runnable() {
- public void run() {
- result[0]= clipboard.getContents(transfer);
- }
- });
- return result[0];
- }
-
- private static boolean isAvailable(Transfer transfer, TransferData[] availableDataTypes) {
- for (int i= 0; i < availableDataTypes.length; i++) {
- if (transfer.isSupportedType(availableDataTypes[i])) return true;
- }
- return false;
- }
-
- public void run(IStructuredSelection selection) {
- try {
- TransferData[] availableTypes= fClipboard.getAvailableTypes();
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- IWorkingSet[] workingSets= ReorgUtils.getWorkingSets(elements);
- Paster[] pasters= createEnabledPasters(availableTypes);
- for (int i= 0; i < pasters.length; i++) {
- if (pasters[i].canPasteOn(javaElements, resources, workingSets)) {
- pasters[i].paste(javaElements, resources, workingSets, availableTypes);
- return;// one is enough
- }
- }
- String msg= resources.length + javaElements.length + workingSets.length == 0
- ? ReorgMessages.PasteAction_cannot_no_selection
- : ReorgMessages.PasteAction_cannot_selection;
- MessageDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), ReorgMessages.PasteAction_name, msg);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- } catch (InterruptedException e) {
- // OK
- }
- }
-
- private abstract static class Paster{
- private final Shell fShell;
- private final Clipboard fClipboard2;
- protected Paster(Shell shell, Clipboard clipboard){
- fShell= shell;
- fClipboard2= clipboard;
- }
- protected final Shell getShell() {
- return fShell;
- }
- protected final Clipboard getClipboard() {
- return fClipboard2;
- }
-
- protected final IResource[] getClipboardResources(TransferData[] availableDataTypes) {
- Transfer transfer= ResourceTransfer.getInstance();
- if (isAvailable(transfer, availableDataTypes)) {
- return (IResource[])getContents(fClipboard2, transfer, getShell());
- }
- return null;
- }
-
- protected final IJavaScriptElement[] getClipboardJavaElements(TransferData[] availableDataTypes) {
- Transfer transfer= JavaElementTransfer.getInstance();
- if (isAvailable(transfer, availableDataTypes)) {
- return (IJavaScriptElement[])getContents(fClipboard2, transfer, getShell());
- }
- return null;
- }
-
- protected final TypedSource[] getClipboardTypedSources(TransferData[] availableDataTypes) {
- Transfer transfer= TypedSourceTransfer.getInstance();
- if (isAvailable(transfer, availableDataTypes)) {
- return (TypedSource[])getContents(fClipboard2, transfer, getShell());
- }
- return null;
- }
-
- protected final String getClipboardText(TransferData[] availableDataTypes) {
- Transfer transfer= TextTransfer.getInstance();
- if (isAvailable(transfer, availableDataTypes)) {
- return (String) getContents(fClipboard2, transfer, getShell());
- }
- return null;
- }
-
- /**
- * Used to be called on selection change, but is only called on execution now
- * (before {@link #canPasteOn(IJavaScriptElement[], IResource[], IWorkingSet[])}).
- * @param availableTypes transfer types
- * @return whether the paste action can be enabled
- * @throws JavaScriptModelException
- */
- public abstract boolean canEnable(TransferData[] availableTypes) throws JavaScriptModelException;
-
- /**
- * Only called if {@link #canEnable(TransferData[])} returns <code>true</code>.
- * @param selectedJavaElements
- * @param selectedResources
- * @param selectedWorkingSets
- * @return whether the paste action can be enabled
- * @throws JavaScriptModelException
- */
- public abstract boolean canPasteOn(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException;
-
- /**
- * only called if {@link #canPasteOn(IJavaScriptElement[], IResource[], IWorkingSet[])} returns <code>true</code>
- * @param selectedJavaElements
- * @param selectedResources
- * @param selectedWorkingSets
- * @param availableTypes
- * @throws JavaScriptModelException
- * @throws InterruptedException
- * @throws InvocationTargetException
- */
- public abstract void paste(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException, InterruptedException, InvocationTargetException;
- }
-
- private static class TextPaster extends Paster {
-
- private static class ParsedCu {
- private final String fText;
- private final String fTypeName;
- private final String fPackageName;
-
- public static ParsedCu[] parse(IJavaScriptProject javaProject, String text) {
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(text.toCharArray());
-
- ArrayList cus= new ArrayList();
- int start= 0;
- boolean tokensScanned= false;
- int tok;
- while (true) {
- try {
- tok= scanner.getNextToken();
- } catch (InvalidInputException e) {
- // Handle gracefully to give the ASTParser a chance to recover,
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=168691
- tok= ITerminalSymbols.TokenNameEOF;
- }
- if (tok == ITerminalSymbols.TokenNamepackage && tokensScanned) {
- int packageStart= scanner.getCurrentTokenStartPosition();
- ParsedCu cu= parseCu(javaProject, text.substring(start, packageStart));
- if (cu != null) {
- cus.add(cu);
- start= packageStart;
- }
- } else if (tok == ITerminalSymbols.TokenNameEOF) {
- ParsedCu cu= parseCu(javaProject, text.substring(start, text.length()));
- if (cu != null) {
- cus.add(cu);
- }
- break;
- }
- tokensScanned= true;
- }
-
- return (ParsedCu[]) cus.toArray(new ParsedCu[cus.size()]);
- }
-
- private static ParsedCu parseCu(IJavaScriptProject javaProject, String text) {
- String packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(javaProject);
- parser.setSource(text.toCharArray());
- parser.setStatementsRecovery(true);
- JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(null);
-
- if (unit == null)
- return null;
-
- int typesCount= unit.types().size();
- String typeName= null;
- if (typesCount > 0) {
- // get first most visible type:
- int maxVisibility= Modifier.PRIVATE;
- for (ListIterator iter= unit.types().listIterator(typesCount); iter.hasPrevious();) {
- AbstractTypeDeclaration type= (AbstractTypeDeclaration) iter.previous();
- int visibility= JdtFlags.getVisibilityCode(type);
- if (! JdtFlags.isHigherVisibility(maxVisibility, visibility)) {
- maxVisibility= visibility;
- typeName= type.getName().getIdentifier();
- }
- }
- }
- if (typeName == null)
- return null;
-
- PackageDeclaration pack= unit.getPackage();
- if (pack != null) {
- packageName= pack.getName().getFullyQualifiedName();
- }
-
- return new ParsedCu(text, typeName, packageName);
- }
-
- private ParsedCu(String text, String typeName, String packageName) {
- fText= text;
- fTypeName= typeName;
- fPackageName= packageName;
- }
-
- public String getTypeName() {
- return fTypeName;
- }
-
- public String getPackageName() {
- return fPackageName;
- }
-
- public String getText() {
- return fText;
- }
- }
-
- private IPackageFragmentRoot fDestination;
- /**
- * destination pack iff pasted 1 CU to package fragment or compilation unit, <code>null</code> otherwise
- */
- private IPackageFragment fDestinationPack;
- private ParsedCu[] fParsedCus;
- private TransferData[] fAvailableTypes;
-
- protected TextPaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
-
- public boolean canEnable(TransferData[] availableTypes) {
- fAvailableTypes= availableTypes;
- return PasteAction.isAvailable(TextTransfer.getInstance(), availableTypes);
- }
-
- public boolean canPasteOn(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException {
- if (selectedWorkingSets.length != 0)
- return false;
- if (resources.length != 0)
- return false; //alternative: create text file?
- if (javaElements.length > 1)
- return false;
-
- String text= getClipboardText(fAvailableTypes);
- IJavaScriptProject javaProject= null;
- IJavaScriptElement destination= null;
- if (javaElements.length == 1) {
- destination= javaElements[0];
- javaProject= destination.getJavaScriptProject();
- }
- fParsedCus= ParsedCu.parse(javaProject, text);
-
- if (fParsedCus.length == 0)
- return false;
-
- if (destination == null)
- return true;
-
- /*
- * 1 CU: paste into package, adapt package declaration
- * 2+ CUs: always paste into source folder
- */
-
- IPackageFragmentRoot packageFragmentRoot;
- IPackageFragment destinationPack;
- switch (destination.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- IPackageFragmentRoot[] packageFragmentRoots= ((IJavaScriptProject) destination).getPackageFragmentRoots();
- for (int i= 0; i < packageFragmentRoots.length; i++) {
- packageFragmentRoot= packageFragmentRoots[i];
- if (isWritable(packageFragmentRoot)) {
- fDestination= packageFragmentRoot;
- return true;
- }
- }
- return false;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- packageFragmentRoot= (IPackageFragmentRoot) destination;
- if (isWritable(packageFragmentRoot)) {
- fDestination= packageFragmentRoot;
- return true;
- }
- return false;
-
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- destinationPack= (IPackageFragment) destination;
- packageFragmentRoot= (IPackageFragmentRoot) destinationPack.getParent();
- if (isWritable(packageFragmentRoot)) {
- fDestination= packageFragmentRoot;
- if (fParsedCus.length == 1) {
- fDestinationPack= destinationPack;
- }
- return true;
- }
- return false;
-
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- destinationPack= (IPackageFragment) destination.getParent();
- packageFragmentRoot= (IPackageFragmentRoot) destinationPack.getParent();
- if (isWritable(packageFragmentRoot)) {
- fDestination= packageFragmentRoot;
- if (fParsedCus.length == 1) {
- fDestinationPack= destinationPack;
- }
- return true;
- }
- return false;
-
- default:
- return false;
- }
- }
-
- private boolean isWritable(IPackageFragmentRoot packageFragmentRoot) {
- try {
- return packageFragmentRoot.exists() && ! packageFragmentRoot.isArchive() && ! packageFragmentRoot.isReadOnly()
- && packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE;
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
-
- public void paste(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException, InterruptedException, InvocationTargetException{
- final IEditorPart[] editorPart= new IEditorPart[1];
-
- IRunnableWithProgress op= new IRunnableWithProgress() {
- private IPath fVMPath;
- private String fCompilerCompliance;
-
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- final ArrayList cus= new ArrayList();
- try {
- JavaScriptCore.run(new IWorkspaceRunnable() {
- public void run(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1 + fParsedCus.length); //$NON-NLS-1$
-
- if (fDestination == null) {
- fDestination= createNewProject(new SubProgressMonitor(pm, 1));
- } else {
- pm.worked(1);
- }
- IConfirmQuery confirmQuery= new ReorgQueries(getShell()).createYesYesToAllNoNoToAllQuery(ReorgMessages.PasteAction_TextPaster_confirmOverwriting, true, IReorgQueries.CONFIRM_OVERWRITING);
- for (int i= 0; i < fParsedCus.length; i++) {
- if (pm.isCanceled())
- break;
- IJavaScriptUnit cu= pasteCU(fParsedCus[i], new SubProgressMonitor(pm, 1), confirmQuery);
- if (cu != null)
- cus.add(cu);
- }
-
- }
- }, monitor);
- } catch (OperationCanceledException e) {
- // cancelling is fine
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- IResource[] cuResources= ResourceUtil.getFiles((IJavaScriptUnit[]) cus.toArray(new IJavaScriptUnit[cus.size()]));
- SelectionUtil.selectAndReveal(cuResources, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
- }
-
- private IJavaScriptUnit pasteCU(ParsedCu parsedCu, SubProgressMonitor pm, IConfirmQuery confirmQuery) throws CoreException, OperationCanceledException {
- pm.beginTask("", 4); //$NON-NLS-1$
- try {
- IPackageFragment destinationPack;
- if (fDestinationPack != null) {
- destinationPack= fDestinationPack;
- pm.worked(1);
- } else {
- String packageName= parsedCu.getPackageName();
- destinationPack= fDestination.getPackageFragment(packageName);
- if (! destinationPack.exists()) {
- JavaModelUtil.getPackageFragmentRoot(destinationPack).createPackageFragment(packageName, true, new SubProgressMonitor(pm, 1));
- } else {
- pm.worked(1);
- }
- }
-
- final String cuName= parsedCu.getTypeName() + JavaModelUtil.DEFAULT_CU_SUFFIX;
- IJavaScriptUnit cu= destinationPack.getJavaScriptUnit(cuName);
- boolean alreadyExists= cu.exists();
- if (alreadyExists) {
- String msg= Messages.format(ReorgMessages.PasteAction_TextPaster_exists, new Object[] {cuName});
- boolean overwrite= confirmQuery.confirm(msg);
- if (! overwrite)
- return null;
-
- editorPart[0]= openCu(cu); //Open editor before overwriting to allow undo to restore original package declaration
- }
-
- destinationPack.createCompilationUnit(cuName, parsedCu.getText(), true, new SubProgressMonitor(pm, 1));
-
- if (! alreadyExists) {
- editorPart[0]= openCu(cu);
- }
- if (fDestinationPack != null && ! fDestinationPack.getElementName().equals(parsedCu.getPackageName())) {
- if (! alreadyExists && editorPart[0] != null)
- editorPart[0].doSave(new SubProgressMonitor(pm, 1)); //avoid showing error marker due to missing/wrong package declaration
- else
- pm.worked(1);
- } else {
- pm.worked(1);
- }
- return cu;
- } finally {
- pm.done();
- }
- }
-
- private IPackageFragmentRoot createNewProject(SubProgressMonitor pm) throws CoreException {
- pm.beginTask("", 10); //$NON-NLS-1$
- IProject project;
- int i= 1;
- do {
- String name= Messages.format(ReorgMessages.PasteAction_projectName, i == 1 ? (Object) "" : new Integer(i)); //$NON-NLS-1$
- project= JavaScriptPlugin.getWorkspace().getRoot().getProject(name);
- i++;
- } while (project.exists());
-
- BuildPathsBlock.createProject(project, null, new SubProgressMonitor(pm, 3));
- BuildPathsBlock.addJavaNature(project, new SubProgressMonitor(pm, 1));
- IJavaScriptProject javaProject= JavaScriptCore.create(project);
-
- IResource srcFolder;
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
- if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
- IFolder folder= project.getFolder(sourceFolderName);
- if (! folder.exists()) {
- folder.create(false, true, new SubProgressMonitor(pm, 1));
- }
- srcFolder= folder;
- } else {
- srcFolder= project;
- }
-
- if (fCompilerCompliance != null) {
- Map options= javaProject.getOptions(false);
- JavaModelUtil.setCompilanceOptions(options, fCompilerCompliance);
- JavaModelUtil.setDefaultClassfileOptions(options, fCompilerCompliance);
- javaProject.setOptions(options);
- }
- IIncludePathEntry srcEntry= JavaScriptCore.newSourceEntry(srcFolder.getFullPath());
- IIncludePathEntry jreEntry= JavaScriptCore.newContainerEntry(fVMPath);
- //IPath outputLocation= BuildPathsBlock.getDefaultOutputLocation(javaProject);
- IIncludePathEntry[] cpes= new IIncludePathEntry[] { srcEntry, jreEntry };
- javaProject.setRawIncludepath(cpes, new SubProgressMonitor(pm, 1));
- return javaProject.getPackageFragmentRoot(srcFolder);
- }
-
- };
-
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null) {
- context= new BusyIndicatorRunnableContext();
- }
- PlatformUI.getWorkbench().getProgressService().runInUI(context, op, JavaScriptPlugin.getWorkspace().getRoot());
-
- if (editorPart[0] != null)
- editorPart[0].getEditorSite().getPage().activate(editorPart[0]); //activate editor again, since runInUI restores previous active part
- }
-
- private IEditorPart openCu(IJavaScriptUnit cu) {
- try {
- return JavaScriptUI.openInEditor(cu, true, true);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- return null;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
- }
- }
-
- private static class WorkingSetPaster extends Paster {
- protected WorkingSetPaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
- public void paste(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException, InterruptedException, InvocationTargetException {
- IWorkingSet workingSet= selectedWorkingSets[0];
- Set elements= new HashSet(Arrays.asList(workingSet.getElements()));
- IJavaScriptElement[] javaElements= getClipboardJavaElements(availableTypes);
- if (javaElements != null) {
- for (int i= 0; i < javaElements.length; i++) {
- if (!ReorgUtils.containsElementOrParent(elements, javaElements[i]))
- elements.add(javaElements[i]);
- }
- }
- IResource[] resources= getClipboardResources(availableTypes);
- if (resources != null) {
- List realJavaElements= new ArrayList();
- List realResource= new ArrayList();
- ReorgUtils.splitIntoJavaElementsAndResources(resources, realJavaElements, realResource);
- for (Iterator iter= realJavaElements.iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement)iter.next();
- if (!ReorgUtils.containsElementOrParent(elements, element))
- elements.add(element);
- }
- for (Iterator iter= realResource.iterator(); iter.hasNext();) {
- IResource element= (IResource)iter.next();
- if (!ReorgUtils.containsElementOrParent(elements, element))
- elements.add(element);
- }
- }
- workingSet.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- }
- public boolean canEnable(TransferData[] availableTypes) throws JavaScriptModelException {
- return isAvailable(ResourceTransfer.getInstance(), availableTypes) ||
- isAvailable(JavaElementTransfer.getInstance(), availableTypes);
- }
- public boolean canPasteOn(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException {
- if (selectedResources.length != 0 || selectedJavaElements.length != 0 || selectedWorkingSets.length != 1)
- return false;
- IWorkingSet ws= selectedWorkingSets[0];
- return !OthersWorkingSetUpdater.ID.equals(ws.getId());
- }
- }
-
- private static class ProjectPaster extends Paster{
-
- protected ProjectPaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
-
- public boolean canEnable(TransferData[] availableDataTypes) {
- boolean resourceTransfer= isAvailable(ResourceTransfer.getInstance(), availableDataTypes);
- boolean javaElementTransfer= isAvailable(JavaElementTransfer.getInstance(), availableDataTypes);
- if (! javaElementTransfer)
- return canPasteSimpleProjects(availableDataTypes);
- if (! resourceTransfer)
- return canPasteJavaProjects(availableDataTypes);
- return canPasteJavaProjects(availableDataTypes) && canPasteSimpleProjects(availableDataTypes);
- }
-
- public void paste(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) {
- pasteProjects(availableTypes);
- }
-
- private void pasteProjects(TransferData[] availableTypes) {
- pasteProjects(getProjectsToPaste(availableTypes));
- }
-
- private void pasteProjects(IProject[] projects){
- Shell shell= getShell();
- for (int i = 0; i < projects.length; i++) {
- new CopyProjectOperation(shell).copyProject(projects[i]);
- }
- }
- private IProject[] getProjectsToPaste(TransferData[] availableTypes) {
- IResource[] resources= getClipboardResources(availableTypes);
- IJavaScriptElement[] javaElements= getClipboardJavaElements(availableTypes);
- Set result= new HashSet();
- if (resources != null)
- result.addAll(Arrays.asList(resources));
- if (javaElements != null)
- result.addAll(Arrays.asList(ReorgUtils.getNotNulls(ReorgUtils.getResources(javaElements))));
- Assert.isTrue(result.size() > 0);
- return (IProject[]) result.toArray(new IProject[result.size()]);
- }
-
- public boolean canPasteOn(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets) {
- return selectedWorkingSets.length == 0; // Can't paste on working sets here
- }
-
- private boolean canPasteJavaProjects(TransferData[] availableDataTypes) {
- IJavaScriptElement[] javaElements= getClipboardJavaElements(availableDataTypes);
- return javaElements != null &&
- javaElements.length != 0 &&
- ! ReorgUtils.hasElementsNotOfType(javaElements, IJavaScriptElement.JAVASCRIPT_PROJECT);
- }
-
- private boolean canPasteSimpleProjects(TransferData[] availableDataTypes) {
- IResource[] resources= getClipboardResources(availableDataTypes);
- if (resources == null || resources.length == 0) return false;
- for (int i= 0; i < resources.length; i++) {
- if (resources[i].getType() != IResource.PROJECT || ! ((IProject)resources[i]).isOpen())
- return false;
- }
- return true;
- }
- }
-
- private static class FilePaster extends Paster{
- protected FilePaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
-
- public void paste(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException {
- String[] fileData= getClipboardFiles(availableTypes);
- if (fileData == null)
- return;
-
- IContainer container= getAsContainer(getTarget(javaElements, resources));
- if (container == null)
- return;
-
- new CopyFilesAndFoldersOperation(getShell()).copyFiles(fileData, container);
- }
-
- private Object getTarget(IJavaScriptElement[] javaElements, IResource[] resources) {
- if (javaElements.length + resources.length == 1){
- if (javaElements.length == 1)
- return javaElements[0];
- else
- return resources[0];
- } else
- return getCommonParent(javaElements, resources);
- }
-
- public boolean canPasteOn(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException {
- Object target= getTarget(javaElements, resources);
- return target != null && canPasteFilesOn(getAsContainer(target)) && selectedWorkingSets.length == 0;
- }
-
- public boolean canEnable(TransferData[] availableDataTypes) throws JavaScriptModelException {
- return isAvailable(FileTransfer.getInstance(), availableDataTypes);
- }
-
- private boolean canPasteFilesOn(Object target) {
- boolean isPackageFragment= target instanceof IPackageFragment;
- boolean isJavaProject= target instanceof IJavaScriptProject;
- boolean isPackageFragmentRoot= target instanceof IPackageFragmentRoot;
- boolean isContainer= target instanceof IContainer;
-
- if (!(isPackageFragment || isJavaProject || isPackageFragmentRoot || isContainer))
- return false;
-
- if (isContainer) {
- return true;
- } else {
- IJavaScriptElement element= (IJavaScriptElement)target;
- return !element.isReadOnly();
- }
- }
-
- private IContainer getAsContainer(Object target) throws JavaScriptModelException{
- if (target == null)
- return null;
- if (target instanceof IContainer)
- return (IContainer)target;
- if (target instanceof IFile)
- return ((IFile)target).getParent();
- return getAsContainer(((IJavaScriptElement)target).getCorrespondingResource());
- }
-
- private String[] getClipboardFiles(TransferData[] availableDataTypes) {
- Transfer transfer= FileTransfer.getInstance();
- if (isAvailable(transfer, availableDataTypes)) {
- return (String[])getContents(getClipboard(), transfer, getShell());
- }
- return null;
- }
- private Object getCommonParent(IJavaScriptElement[] javaElements, IResource[] resources) {
- return new ParentChecker(resources, javaElements).getCommonParent();
- }
- }
- private static class JavaElementAndResourcePaster extends Paster {
-
- protected JavaElementAndResourcePaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
-
- private TransferData[] fAvailableTypes;
-
- public void paste(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException, InterruptedException, InvocationTargetException{
- IResource[] clipboardResources= getClipboardResources(availableTypes);
- if (clipboardResources == null)
- clipboardResources= new IResource[0];
- IJavaScriptElement[] clipboardJavaElements= getClipboardJavaElements(availableTypes);
- if (clipboardJavaElements == null)
- clipboardJavaElements= new IJavaScriptElement[0];
-
- Object destination= getTarget(javaElements, resources);
- if (destination instanceof IJavaScriptElement)
- ReorgCopyStarter.create(clipboardJavaElements, clipboardResources, (IJavaScriptElement)destination).run(getShell());
- else if (destination instanceof IResource)
- ReorgCopyStarter.create(clipboardJavaElements, clipboardResources, (IResource)destination).run(getShell());
- }
-
- private Object getTarget(IJavaScriptElement[] javaElements, IResource[] resources) {
- if (javaElements.length + resources.length == 1){
- if (javaElements.length == 1)
- return javaElements[0];
- else
- return resources[0];
- } else
- return getCommonParent(javaElements, resources);
- }
-
- private Object getCommonParent(IJavaScriptElement[] javaElements, IResource[] resources) {
- return new ParentChecker(resources, javaElements).getCommonParent();
- }
-
- public boolean canPasteOn(IJavaScriptElement[] javaElements, IResource[] resources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException {
- if (selectedWorkingSets.length != 0)
- return false;
- IResource[] clipboardResources= getClipboardResources(fAvailableTypes);
- if (clipboardResources == null)
- clipboardResources= new IResource[0];
- IJavaScriptElement[] clipboardJavaElements= getClipboardJavaElements(fAvailableTypes);
- if (clipboardJavaElements == null)
- clipboardJavaElements= new IJavaScriptElement[0];
- Object destination= getTarget(javaElements, resources);
- if (destination instanceof IJavaScriptElement)
- return ReorgCopyStarter.create(clipboardJavaElements, clipboardResources, (IJavaScriptElement)destination) != null;
- if (destination instanceof IResource)
- return ReorgCopyStarter.create(clipboardJavaElements, clipboardResources, (IResource)destination) != null;
- return false;
- }
-
- public boolean canEnable(TransferData[] availableTypes) {
- fAvailableTypes= availableTypes;
- return isAvailable(JavaElementTransfer.getInstance(), availableTypes) || isAvailable(ResourceTransfer.getInstance(), availableTypes);
- }
- }
-
- private static class TypedSourcePaster extends Paster{
-
- protected TypedSourcePaster(Shell shell, Clipboard clipboard) {
- super(shell, clipboard);
- }
- private TransferData[] fAvailableTypes;
-
- public boolean canEnable(TransferData[] availableTypes) throws JavaScriptModelException {
- fAvailableTypes= availableTypes;
- return isAvailable(TypedSourceTransfer.getInstance(), availableTypes);
- }
-
- public boolean canPasteOn(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets) throws JavaScriptModelException {
- if (selectedResources.length != 0 || selectedWorkingSets.length != 0)
- return false;
- TypedSource[] typedSources= getClipboardTypedSources(fAvailableTypes);
- Object destination= getTarget(selectedJavaElements, selectedResources);
- if (destination instanceof IJavaScriptElement)
- return ReorgTypedSourcePasteStarter.create(typedSources, (IJavaScriptElement)destination) != null;
- return false;
- }
-
- public void paste(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources, IWorkingSet[] selectedWorkingSets, TransferData[] availableTypes) throws JavaScriptModelException, InterruptedException, InvocationTargetException {
- TypedSource[] typedSources= getClipboardTypedSources(availableTypes);
- IJavaScriptElement destination= getTarget(selectedJavaElements, selectedResources);
- ReorgTypedSourcePasteStarter.create(typedSources, destination).run(getShell());
- }
-
- private static IJavaScriptElement getTarget(IJavaScriptElement[] selectedJavaElements, IResource[] selectedResources) {
- Assert.isTrue(selectedResources.length == 0);
- if (selectedJavaElements.length == 1)
- return getAsTypeOrCu(selectedJavaElements[0]);
- Object parent= new ParentChecker(selectedResources, selectedJavaElements).getCommonParent();
- if (parent instanceof IJavaScriptElement)
- return getAsTypeOrCu((IJavaScriptElement)parent);
- return null;
- }
- private static IJavaScriptElement getAsTypeOrCu(IJavaScriptElement element) {
- //try to get type first
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT || element.getElementType() == IJavaScriptElement.TYPE)
- return element;
- IJavaScriptElement ancestorType= element.getAncestor(IJavaScriptElement.TYPE);
- if (ancestorType != null)
- return ancestorType;
- return ReorgUtils.getCompilationUnit(element);
- }
- private static class ReorgTypedSourcePasteStarter {
-
- private final PasteTypedSourcesRefactoring fPasteRefactoring;
-
- private ReorgTypedSourcePasteStarter(PasteTypedSourcesRefactoring pasteRefactoring) {
- Assert.isNotNull(pasteRefactoring);
- fPasteRefactoring= pasteRefactoring;
- }
-
- public static ReorgTypedSourcePasteStarter create(TypedSource[] typedSources, IJavaScriptElement destination) {
- Assert.isNotNull(typedSources);
- Assert.isNotNull(destination);
- PasteTypedSourcesRefactoring pasteRefactoring= PasteTypedSourcesRefactoring.create(typedSources);
- if (pasteRefactoring == null)
- return null;
- if (! pasteRefactoring.setDestination(destination).isOK())
- return null;
- return new ReorgTypedSourcePasteStarter(pasteRefactoring);
- }
-
- public void run(Shell parent) throws InterruptedException, InvocationTargetException {
- IRunnableContext context= new ProgressMonitorDialog(parent);
- new RefactoringExecutionHelper(fPasteRefactoring, RefactoringCore.getConditionCheckingFailedSeverity(), RefactoringSaveHelper.SAVE_NOTHING, parent, context).perform(false, false);
- }
- }
- private static class PasteTypedSourcesRefactoring extends Refactoring {
-
- private final TypedSource[] fSources;
- private IJavaScriptElement fDestination;
-
- static PasteTypedSourcesRefactoring create(TypedSource[] sources){
- if (! isAvailable(sources))
- return null;
- return new PasteTypedSourcesRefactoring(sources);
- }
- public RefactoringStatus setDestination(IJavaScriptElement destination) {
- fDestination= destination;
- if (ReorgUtils.getCompilationUnit(destination) == null)
- return RefactoringStatus.createFatalErrorStatus(ReorgMessages.PasteAction_wrong_destination);
- if (! destination.exists())
- return RefactoringStatus.createFatalErrorStatus(ReorgMessages.PasteAction_element_doesnot_exist);
- if (! canPasteAll(destination))
- return RefactoringStatus.createFatalErrorStatus(ReorgMessages.PasteAction_invalid_destination);
- return new RefactoringStatus();
- }
- private boolean canPasteAll(IJavaScriptElement destination) {
- for (int i= 0; i < fSources.length; i++) {
- if (! canPaste(fSources[i].getType(), destination))
- return false;
- }
- return true;
- }
- private static boolean canPaste(int elementType, IJavaScriptElement destination) {
- IType ancestorType= getAncestorType(destination);
- if (ancestorType != null)
- return canPasteToType(elementType);
- return canPasteToCu(elementType);
- }
- private static boolean canPasteToType(int elementType) {
- return elementType == IJavaScriptElement.TYPE ||
- elementType == IJavaScriptElement.FIELD ||
- elementType == IJavaScriptElement.INITIALIZER ||
- elementType == IJavaScriptElement.METHOD;
- }
- private static boolean canPasteToCu(int elementType) {
- return elementType == IJavaScriptElement.TYPE ||
- elementType == IJavaScriptElement.IMPORT_DECLARATION;
- }
- PasteTypedSourcesRefactoring(TypedSource[] sources){
- Assert.isNotNull(sources);
- Assert.isTrue(sources.length != 0);
- fSources= sources;
- }
-
- private static boolean isAvailable(TypedSource[] sources) {
- return sources != null && sources.length > 0;
- }
-
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return new RefactoringStatus();
- }
-
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
- RefactoringStatus result= Checks.validateModifiesFiles(
- ResourceUtil.getFiles(new IJavaScriptUnit[]{getDestinationCu()}), getValidationContext());
- return result;
- }
-
- public Change createChange(IProgressMonitor pm) throws CoreException {
- ASTParser p= ASTParser.newParser(AST.JLS3);
- p.setSource(getDestinationCu());
- JavaScriptUnit cuNode= (JavaScriptUnit) p.createAST(pm);
- ASTRewrite rewrite= ASTRewrite.create(cuNode.getAST());
- TypedSource source= null;
- for (int i= fSources.length - 1; i >= 0; i--) {
- source= fSources[i];
- final ASTNode destination= getDestinationNodeForSourceElement(fDestination, source.getType(), cuNode);
- if (destination != null) {
- if (destination instanceof JavaScriptUnit)
- insertToCu(rewrite, createNewNodeToInsertToCu(source, rewrite), (JavaScriptUnit) destination);
- else if (destination instanceof AbstractTypeDeclaration)
- insertToType(rewrite, createNewNodeToInsertToType(source, rewrite), (AbstractTypeDeclaration) destination);
- }
- }
- final CompilationUnitChange result= new CompilationUnitChange(ReorgMessages.PasteAction_change_name, getDestinationCu());
- try {
- ITextFileBuffer buffer= RefactoringFileBuffers.acquire(getDestinationCu());
- TextEdit rootEdit= rewrite.rewriteAST(buffer.getDocument(), fDestination.getJavaScriptProject().getOptions(true));
- if (getDestinationCu().isWorkingCopy())
- result.setSaveMode(TextFileChange.LEAVE_DIRTY);
- TextChangeCompatibility.addTextEdit(result, ReorgMessages.PasteAction_edit_name, rootEdit);
- } finally {
- RefactoringFileBuffers.release(getDestinationCu());
- }
- return result;
- }
-
- private static void insertToType(ASTRewrite rewrite, ASTNode node, AbstractTypeDeclaration typeDeclaration) {
- switch (node.getNodeType()) {
- case ASTNode.TYPE_DECLARATION:
- case ASTNode.FUNCTION_DECLARATION:
- case ASTNode.FIELD_DECLARATION:
- case ASTNode.INITIALIZER:
- rewrite.getListRewrite(typeDeclaration, typeDeclaration.getBodyDeclarationsProperty()).insertAt(node, ASTNodes.getInsertionIndex((BodyDeclaration) node, typeDeclaration.bodyDeclarations()), null);
- break;
- default:
- Assert.isTrue(false, String.valueOf(node.getNodeType()));
- }
- }
-
- private static void insertToCu(ASTRewrite rewrite, ASTNode node, JavaScriptUnit cuNode) {
- switch (node.getNodeType()) {
- case ASTNode.TYPE_DECLARATION:
- rewrite.getListRewrite(cuNode, JavaScriptUnit.TYPES_PROPERTY).insertAt(node, ASTNodes.getInsertionIndex((AbstractTypeDeclaration) node, cuNode.types()), null);
- break;
- case ASTNode.IMPORT_DECLARATION:
- rewrite.getListRewrite(cuNode, JavaScriptUnit.IMPORTS_PROPERTY).insertLast(node, null);
- break;
- case ASTNode.PACKAGE_DECLARATION:
- // only insert if none exists
- if (cuNode.getPackage() == null)
- rewrite.set(cuNode, JavaScriptUnit.PACKAGE_PROPERTY, node, null);
- break;
- default:
- Assert.isTrue(false, String.valueOf(node.getNodeType()));
- }
- }
-
- /**
- * @return an AbstractTypeDeclaration, a JavaScriptUnit, or null
- */
- private ASTNode getDestinationNodeForSourceElement(IJavaScriptElement destination, int kind, JavaScriptUnit unit) throws JavaScriptModelException {
- final IType ancestor= getAncestorType(destination);
- if (ancestor != null)
- return ASTNodeSearchUtil.getAbstractTypeDeclarationNode(ancestor, unit);
- if (kind == IJavaScriptElement.TYPE || kind == IJavaScriptElement.IMPORT_DECLARATION || kind == IJavaScriptElement.IMPORT_CONTAINER)
- return unit;
- return null;
- }
-
- private static IType getAncestorType(IJavaScriptElement destinationElement) {
- return destinationElement.getElementType() == IJavaScriptElement.TYPE ? (IType)destinationElement: (IType)destinationElement.getAncestor(IJavaScriptElement.TYPE);
- }
- private ASTNode createNewNodeToInsertToCu(TypedSource source, ASTRewrite rewrite) {
- switch(source.getType()){
- case IJavaScriptElement.TYPE:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.TYPE_DECLARATION);
- case IJavaScriptElement.IMPORT_DECLARATION:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.IMPORT_DECLARATION);
- default: Assert.isTrue(false, String.valueOf(source.getType()));
- return null;
- }
- }
-
- private ASTNode createNewNodeToInsertToType(TypedSource source, ASTRewrite rewrite) {
- switch(source.getType()){
- case IJavaScriptElement.TYPE:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.TYPE_DECLARATION);
- case IJavaScriptElement.METHOD:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.FUNCTION_DECLARATION);
- case IJavaScriptElement.FIELD:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.FIELD_DECLARATION);
- case IJavaScriptElement.INITIALIZER:
- return rewrite.createStringPlaceholder(source.getSource(), ASTNode.INITIALIZER);
- default: Assert.isTrue(false);
- return null;
- }
- }
-
- private IJavaScriptUnit getDestinationCu() {
- return ReorgUtils.getCompilationUnit(fDestination);
- }
-
- public String getName() {
- return ReorgMessages.PasteAction_name;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameCuWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameCuWizard.java
deleted file mode 100644
index c60f756c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameCuWizard.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameCuWizard extends RenameTypeWizard {
-
- public RenameCuWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenameCuWizard_defaultPageTitle,
- RefactoringMessages.RenameCuWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR_CU,
- IJavaHelpContextIds.RENAME_CU_WIZARD_PAGE);
- }
-
- protected RefactoringStatus validateNewName(String newName) {
- String fullName= JavaModelUtil.getRenamedCUName(getCompilationUnit(), newName);
- return super.validateNewName(fullName);
- }
-
- private IJavaScriptUnit getCompilationUnit() {
- return (IJavaScriptUnit) getCompilationUnitProcessor().getElements()[0];
- }
-
- protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
- return new RenameTypeWizardInputPage(message, IJavaHelpContextIds.RENAME_CU_WIZARD_PAGE, true, initialSetting) {
- protected RefactoringStatus validateTextField(String text) {
- return validateNewName(text);
- }
- protected String getNewName(INameUpdating nameUpdating) {
- String result= nameUpdating.getNewElementName();
- // If renaming a CU we have to remove the java file extension
- return JavaScriptCore.removeJavaScriptLikeExtension(result);
- }
- };
- }
-
- protected boolean isRenameType() {
- // the flag 'willRenameType' may change in checkInitialConditions(), but
- // only from true to false.
- return getCompilationUnitProcessor().isWillRenameType();
- }
-
- private RenameCompilationUnitProcessor getCompilationUnitProcessor() {
- return ((RenameCompilationUnitProcessor) ((RenameRefactoring) getRefactoring()).getProcessor());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameFieldWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameFieldWizard.java
deleted file mode 100644
index 32c9f2aa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameFieldWizard.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameFieldWizard extends RenameRefactoringWizard {
-
- public RenameFieldWizard(Refactoring refactoring) {
- super(refactoring, RefactoringMessages.RenameFieldWizard_defaultPageTitle,
- RefactoringMessages.RenameFieldWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR_FIELD,
- IJavaHelpContextIds.RENAME_FIELD_WIZARD_PAGE);
- }
-
- protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
- return new RenameFieldInputWizardPage(message, IJavaHelpContextIds.RENAME_FIELD_WIZARD_PAGE, initialSetting) {
- protected RefactoringStatus validateTextField(String text) {
- RefactoringStatus result= validateNewName(text);
- updateGetterSetterLabels();
- return result;
- }
- };
- }
-
- private static class RenameFieldInputWizardPage extends RenameInputWizardPage {
-
- private Button fRenameGetter;
- private Button fRenameSetter;
- private String fGetterRenamingErrorMessage;
- private String fSetterRenamingErrorMessage;
-
- public RenameFieldInputWizardPage(String message, String contextHelpId, String initialValue) {
- super(message, contextHelpId, true, initialValue);
- }
-
- public void createControl(Composite parent) {
- super.createControl(parent);
- Composite parentComposite= (Composite)getControl();
-
- Composite composite= new Composite(parentComposite, SWT.NONE);
- final GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- getGetterSetterRenamingEnablement();
-
- fRenameGetter= new Button(composite, SWT.CHECK);
- boolean getterEnablement= fGetterRenamingErrorMessage == null;
- fRenameGetter.setEnabled(getterEnablement);
- boolean getterSelection= getterEnablement && getBooleanSetting(RenameRefactoringWizard.FIELD_RENAME_GETTER, getRenameFieldProcessor().getRenameGetter());
- fRenameGetter.setSelection(getterSelection);
- getRenameFieldProcessor().setRenameGetter(getterSelection);
- fRenameGetter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fRenameGetter.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getRenameFieldProcessor().setRenameGetter(fRenameGetter.getSelection());
- updateLeaveDelegateCheckbox(getRenameFieldProcessor().getDelegateCount());
- }
- });
-
- fRenameSetter= new Button(composite, SWT.CHECK);
- boolean setterEnablement= fSetterRenamingErrorMessage == null;
- fRenameSetter.setEnabled(setterEnablement);
- boolean setterSelection= setterEnablement && getBooleanSetting(RenameRefactoringWizard.FIELD_RENAME_SETTER, getRenameFieldProcessor().getRenameSetter());
- fRenameSetter.setSelection(setterSelection);
- getRenameFieldProcessor().setRenameSetter(setterSelection);
- fRenameSetter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fRenameSetter.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getRenameFieldProcessor().setRenameSetter(fRenameSetter.getSelection());
- updateLeaveDelegateCheckbox(getRenameFieldProcessor().getDelegateCount());
- }
- });
-
- updateGetterSetterLabels();
- updateLeaveDelegateCheckbox(getRenameFieldProcessor().getDelegateCount());
- Dialog.applyDialogFont(composite);
- }
-
- public void dispose() {
- if (saveSettings()) {
- if (fRenameGetter.isEnabled())
- saveBooleanSetting(RenameRefactoringWizard.FIELD_RENAME_GETTER, fRenameGetter);
- if (fRenameSetter.isEnabled())
- saveBooleanSetting(RenameRefactoringWizard.FIELD_RENAME_SETTER, fRenameSetter);
- }
- super.dispose();
- }
-
- private void getGetterSetterRenamingEnablement() {
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable(){
- public void run() {
- checkGetterRenamingEnablement();
- checkSetterRenamingEnablement();
- }
- });
- }
-
- protected void updateGetterSetterLabels(){
- fRenameGetter.setText(getRenameGetterLabel());
- fRenameSetter.setText(getRenameSetterLabel());
- }
-
- private String getRenameGetterLabel(){
- String defaultLabel= RefactoringMessages.RenameFieldInputWizardPage_rename_getter;
- if (fGetterRenamingErrorMessage != null)
- return constructDisabledGetterRenamingLabel(defaultLabel);
- try {
- IFunction getter= getRenameFieldProcessor().getGetter();
- if (getter == null || ! getter.exists())
- return defaultLabel;
- String oldGetterName= getter.getElementName();
- String newGetterName= createNewGetterName();
- return Messages.format(RefactoringMessages.RenameFieldInputWizardPage_rename_getter_to, new String[]{oldGetterName, newGetterName});
- } catch(CoreException e) {
- JavaScriptPlugin.log(e) ;
- return defaultLabel;
- }
- }
-
- private String getRenameSetterLabel(){
- String defaultLabel= RefactoringMessages.RenameFieldInputWizardPage_rename_setter;
- if (fSetterRenamingErrorMessage != null)
- return constructDisabledSetterRenamingLabel(defaultLabel);
- try {
- IFunction setter= getRenameFieldProcessor().getSetter();
- if (setter == null || ! setter.exists())
- return defaultLabel;
- String oldSetterName= setter.getElementName();
- String newSetterName= createNewSetterName();
- return Messages.format(RefactoringMessages.RenameFieldInputWizardPage_rename_setter_to, new String[]{oldSetterName, newSetterName});
- } catch(CoreException e) {
- JavaScriptPlugin.log(e);
- return defaultLabel;
- }
- }
- private String constructDisabledSetterRenamingLabel(String defaultLabel) {
- if (fSetterRenamingErrorMessage.equals("")) //$NON-NLS-1$
- return defaultLabel;
- String[] keys= {defaultLabel, fSetterRenamingErrorMessage};
- return Messages.format(RefactoringMessages.RenameFieldInputWizardPage_setter_label, keys);
- }
-
- private String constructDisabledGetterRenamingLabel(String defaultLabel) {
- if (fGetterRenamingErrorMessage.equals("")) //$NON-NLS-1$
- return defaultLabel;
- String[] keys= {defaultLabel, fGetterRenamingErrorMessage};
- return Messages.format(RefactoringMessages.RenameFieldInputWizardPage_getter_label, keys);
- }
-
- private String createNewGetterName() throws CoreException {
- return getRenameFieldProcessor().getNewGetterName();
- }
-
- private String createNewSetterName() throws CoreException {
- return getRenameFieldProcessor().getNewSetterName();
- }
-
- private String checkGetterRenamingEnablement() {
- if (fGetterRenamingErrorMessage != null)
- return fGetterRenamingErrorMessage;
- try {
- fGetterRenamingErrorMessage= getRenameFieldProcessor().canEnableGetterRenaming();
- return fGetterRenamingErrorMessage;
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return ""; //$NON-NLS-1$
- }
- }
-
- private String checkSetterRenamingEnablement() {
- if (fSetterRenamingErrorMessage != null)
- return fSetterRenamingErrorMessage;
- try {
- fSetterRenamingErrorMessage= getRenameFieldProcessor().canEnableSetterRenaming();
- return fSetterRenamingErrorMessage;
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return ""; //$NON-NLS-1$
- }
- }
-
- private RenameFieldProcessor getRenameFieldProcessor() {
- return (RenameFieldProcessor)((RenameRefactoring)getRefactoring()).getProcessor();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInformationPopup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInformationPopup.java
deleted file mode 100644
index 9bad38c0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInformationPopup.java
+++ /dev/null
@@ -1,822 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener2;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.bindings.keys.IKeyLookup;
-import org.eclipse.jface.bindings.keys.KeyLookupFactory;
-import org.eclipse.jface.bindings.keys.KeyStroke;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.text.ITextListener;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.IViewportListener;
-import org.eclipse.jface.text.IWidgetTokenKeeper;
-import org.eclipse.jface.text.IWidgetTokenKeeperExtension;
-import org.eclipse.jface.text.IWidgetTokenOwner;
-import org.eclipse.jface.text.IWidgetTokenOwnerExtension;
-import org.eclipse.jface.text.TextEvent;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.util.Geometry;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.ShellAdapter;
-import org.eclipse.swt.events.ShellEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.graphics.Region;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.swt.widgets.Tracker;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaBasePreferencePage;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-public class RenameInformationPopup implements IWidgetTokenKeeper, IWidgetTokenKeeperExtension {
-
- private class PopupVisibilityManager implements IPartListener2, ControlListener, MouseListener, KeyListener, ITextListener, IViewportListener {
-
- public void start() {
- fEditor.getSite().getWorkbenchWindow().getPartService().addPartListener(this);
- final ISourceViewer viewer= fEditor.getViewer();
- final StyledText textWidget= viewer.getTextWidget();
- textWidget.addControlListener(this);
- textWidget.addMouseListener(this);
- textWidget.addKeyListener(this);
- fEditor.getSite().getShell().addControlListener(this);
- viewer.addTextListener(this);
- viewer.addViewportListener(this);
- fPopup.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- fEditor.getSite().getWorkbenchWindow().getPartService().removePartListener(PopupVisibilityManager.this);
- if (! textWidget.isDisposed()) {
- textWidget.removeControlListener(PopupVisibilityManager.this);
- textWidget.removeMouseListener(PopupVisibilityManager.this);
- textWidget.removeKeyListener(PopupVisibilityManager.this);
- }
- fEditor.getSite().getShell().removeControlListener(PopupVisibilityManager.this);
- viewer.removeTextListener(PopupVisibilityManager.this);
- viewer.removeViewportListener(PopupVisibilityManager.this);
- if (fMenuImage != null) {
- fMenuImage.dispose();
- fMenuImage= null;
- }
- if (fMenuManager != null) {
- fMenuManager.dispose();
- fMenuManager= null;
- }
- fRenameLinkedMode.cancel();
- }
- });
- }
-
- public void partActivated(IWorkbenchPartReference partRef) {
- IWorkbenchPart fPart= fEditor.getEditorSite().getPart();
- if (partRef.getPart(false) == fPart) {
- updateVisibility();
- }
- }
-
- public void partBroughtToTop(IWorkbenchPartReference partRef) {
- }
-
- public void partClosed(IWorkbenchPartReference partRef) {
- }
-
- public void partDeactivated(IWorkbenchPartReference partRef) {
- IWorkbenchPart fPart= fEditor.getEditorSite().getPart();
- if (fPopup != null && ! fPopup.isDisposed() && partRef.getPart(false) == fPart) {
- fPopup.setVisible(false);
- }
- }
-
- public void partHidden(IWorkbenchPartReference partRef) {
- }
-
- public void partInputChanged(IWorkbenchPartReference partRef) {
- }
-
- public void partOpened(IWorkbenchPartReference partRef) {
- }
-
- public void partVisible(IWorkbenchPartReference partRef) {
- }
-
-
- public void controlMoved(ControlEvent e) {
- updatePopupLocation(true);
- updateVisibility(); //only for hiding outside editor area
- }
-
- public void controlResized(ControlEvent e) {
- updatePopupLocation(true);
- updateVisibility(); //only for hiding outside editor area
- }
-
-
- public void mouseDoubleClick(MouseEvent e) {
- }
-
- public void mouseDown(MouseEvent e) {
- }
-
- public void mouseUp(MouseEvent e) {
- updatePopupLocation(false);
- updateVisibility();
- }
-
- public void keyPressed(KeyEvent e) {
- updatePopupLocation(false);
- updateVisibility();
- }
-
- public void keyReleased(KeyEvent e) {
- }
-
-
- public void textChanged(TextEvent event) {
- updatePopupLocation(false);
- updateVisibility(); //only for hiding outside editor area
- }
-
- public void viewportChanged(int verticalOffset) {
- updatePopupLocation(true);
- updateVisibility(); //only for hiding outside editor area
- }
- }
-
- /**
- * Cached platform flags for dealing with platform-specific issues.
- */
- private static boolean CARBON = "carbon".equals(SWT.getPlatform()); //$NON-NLS-1$
-
- private static final int WIDGET_PRIORITY= 1000;
-
- private static final String DIALOG_SETTINGS_SECTION= "RenameInformationPopup"; //$NON-NLS-1$
- private static final String SNAP_POSITION_KEY= "snap_position"; //$NON-NLS-1$
-
- private static final int SNAP_POSITION_UNDER_RIGHT_FIELD= 0;
- private static final int SNAP_POSITION_OVER_RIGHT_FIELD= 1;
- private static final int SNAP_POSITION_UNDER_LEFT_FIELD= 2;
- private static final int SNAP_POSITION_OVER_LEFT_FIELD= 3;
- private static final int SNAP_POSITION_LOWER_RIGHT= 4;
-
- private static final int POPUP_VISIBILITY_DELAY= 300;
-
- /**
- * Offset of info hover arrow from the left or right side.
- */
- private static final int HAO= 10;
-
- /**
- * Width of info hover arrow.
- */
- private static final int HAW= 8;
-
- /**
- * Height of info hover arrow.
- */
- private static final int HAH= 10;
-
- /**
- * Gap between linked position and popup.
- */
- private static final int GAP= 2;
-
- private final CompilationUnitEditor fEditor;
- private final RenameLinkedMode fRenameLinkedMode;
-
- private int fSnapPosition;
- private Shell fPopup;
- private GridLayout fPopupLayout;
- private Region fRegion;
-
- private Image fMenuImage;
- private MenuManager fMenuManager;
- private ToolBar fToolBar;
- private String fOpenDialogBinding= ""; //$NON-NLS-1$
- private boolean fIsMenuUp= false;
-
- private boolean fDelayJobFinished= false;
-
- public RenameInformationPopup(CompilationUnitEditor editor, RenameLinkedMode renameLinkedMode) {
- fEditor= editor;
- fRenameLinkedMode= renameLinkedMode;
- restoreSnapPosition();
- }
-
- private void restoreSnapPosition() {
- IDialogSettings settings= getDialogSettings();
- try {
- fSnapPosition= settings.getInt(SNAP_POSITION_KEY);
- } catch (NumberFormatException e) {
- // default:
- fSnapPosition= SNAP_POSITION_UNDER_LEFT_FIELD;
- }
- }
-
- private IDialogSettings getDialogSettings() {
- return JavaScriptPlugin.getDefault().getDialogSettingsSection(DIALOG_SETTINGS_SECTION);
- }
-
- public void open() {
- // Must cache here, since editor context is not available in menu from popup shell:
- fOpenDialogBinding= getOpenDialogBinding();
-
- Shell workbenchShell= fEditor.getSite().getShell();
- final Display display= workbenchShell.getDisplay();
-
- fPopup= new Shell(workbenchShell, SWT.ON_TOP | SWT.NO_TRIM | SWT.TOOL);
- fPopupLayout= new GridLayout(2, false);
- fPopupLayout.marginWidth= 1;
- fPopupLayout.marginHeight= 1;
- fPopupLayout.marginLeft= 4;
- fPopupLayout.horizontalSpacing= 0;
- fPopup.setLayout(fPopupLayout);
-
- createContent(fPopup);
- updatePopupLocation(true);
- new PopupVisibilityManager().start();
-
- // Leave linked mode when popup loses focus
- // (except when focus goes back to workbench window or menu is open):
- fPopup.addShellListener(new ShellAdapter() {
- public void shellDeactivated(ShellEvent e) {
- if (fIsMenuUp)
- return;
-
- final Shell editorShell= fEditor.getSite().getShell();
- display.asyncExec(new Runnable() {
- // post to UI thread since editor shell only gets activated after popup has lost focus
- public void run() {
- Shell activeShell= display.getActiveShell();
- if (activeShell != editorShell) {
- fRenameLinkedMode.cancel();
- }
- }
- });
- }
- });
-
- if (! CARBON) { // carbon draws its own border...
- fPopup.addPaintListener(new PaintListener() {
- public void paintControl(PaintEvent pe) {
- pe.gc.drawPolygon(getPolygon(true));
- }
- });
- }
-
-// fPopup.moveBelow(null); // make sure hovers are on top of the info popup
-// XXX workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=170774
-// fPopup.moveBelow(workbenchShell.getShells()[0]);
-
- UIJob delayJob= new UIJob(display, ReorgMessages.RenameInformationPopup_delayJobName) {
- public IStatus runInUIThread(IProgressMonitor monitor) {
- fDelayJobFinished= true;
- if (fPopup != null && ! fPopup.isDisposed()) {
- updateVisibility();
- }
- return Status.OK_STATUS;
- }
- };
- delayJob.setSystem(true);
- delayJob.setPriority(Job.INTERACTIVE);
- delayJob.schedule(POPUP_VISIBILITY_DELAY);
- }
-
- public void close() {
- if (fPopup != null) {
- if (!fPopup.isDisposed()) {
- fPopup.close();
- }
- fPopup= null;
- }
- releaseWidgetToken();
- if (fRegion != null) {
- if (! fRegion.isDisposed()) {
- fRegion.dispose();
- }
- }
- }
-
- public Shell getShell() {
- return fPopup;
- }
-
- private void updatePopupLocation(boolean force) {
- if (! force && fSnapPosition == SNAP_POSITION_LOWER_RIGHT)
- return;
-
- packPopup();
- Point loc= computePopupLocation(fSnapPosition);
- if (loc != null) {
- fPopup.setLocation(loc);
- // XXX workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=170774
-// fPopup.moveBelow(fEditor.getSite().getShell().getShells()[0]);
- }
- }
-
- private void updateVisibility() {
- if (fPopup != null && !fPopup.isDisposed() && fDelayJobFinished) {
- boolean visible= false;
- //TODO: Check for visibility of linked position, not whether popup is outside of editor?
- if (fRenameLinkedMode.isCaretInLinkedPosition()) {
- StyledText textWidget= fEditor.getViewer().getTextWidget();
- Rectangle eArea= Geometry.toDisplay(textWidget, textWidget.getClientArea());
- Rectangle pBounds= fPopup.getBounds();
- pBounds.x-= GAP;
- pBounds.y-= GAP;
- pBounds.width+= 2 * GAP;
- pBounds.height+= 2 * GAP;
- if (eArea.intersects(pBounds)) {
- visible= true;
- }
- }
- if (visible && ! fPopup.isVisible()) {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IWidgetTokenOwnerExtension) {
- IWidgetTokenOwnerExtension widgetTokenOwnerExtension= (IWidgetTokenOwnerExtension) viewer;
- widgetTokenOwnerExtension.requestWidgetToken(this, WIDGET_PRIORITY);
- }
- } else if (! visible && fPopup.isVisible()) {
- releaseWidgetToken();
- }
- fPopup.setVisible(visible);
- }
- }
-
- private void releaseWidgetToken() {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IWidgetTokenOwner) {
- IWidgetTokenOwner widgetTokenOwner= (IWidgetTokenOwner) viewer;
- widgetTokenOwner.releaseWidgetToken(this);
- }
- }
-
- /**
- * @param snapPosition one of the SNAP_POSITION_* constants
- * @return the location in display coordinates or <code>null</code> iff not visible
- */
- private Point computePopupLocation(int snapPosition) {
- if (fPopup == null || fPopup.isDisposed())
- return null;
-
- switch (snapPosition) {
- case SNAP_POSITION_LOWER_RIGHT:
- {
- StyledText eWidget= fEditor.getViewer().getTextWidget();
- Rectangle eBounds= eWidget.getClientArea();
- Point eLowerRight= eWidget.toDisplay(eBounds.x + eBounds.width, eBounds.y + eBounds.height);
- Point pSize= getExtent();
- return new Point(eLowerRight.x - pSize.x - 5, eLowerRight.y - pSize.y - 5);
- }
-
- case SNAP_POSITION_UNDER_RIGHT_FIELD:
- case SNAP_POSITION_OVER_RIGHT_FIELD:
- {
- LinkedPosition position= fRenameLinkedMode.getCurrentLinkedPosition();
- if (position == null)
- return null;
- ISourceViewer viewer= fEditor.getViewer();
- ITextViewerExtension5 viewer5= (ITextViewerExtension5) viewer;
- int widgetOffset= viewer5.modelOffset2WidgetOffset(position.offset + position.length);
-
- StyledText textWidget= viewer.getTextWidget();
- Point pos= textWidget.getLocationAtOffset(widgetOffset);
- Point pSize= getExtent();
- if (snapPosition == SNAP_POSITION_OVER_RIGHT_FIELD) {
- pos.y-= pSize.y + GAP;
- } else {
- pos.y+= textWidget.getLineHeight(widgetOffset) + GAP;
- }
- pos.x+= GAP;
- Point dPos= textWidget.toDisplay(pos);
- Rectangle displayBounds= textWidget.getDisplay().getClientArea();
- Rectangle dPopupRect= Geometry.createRectangle(dPos, pSize);
- Geometry.moveInside(dPopupRect, displayBounds);
- return new Point(dPopupRect.x, dPopupRect.y);
- }
-
- case SNAP_POSITION_UNDER_LEFT_FIELD:
- case SNAP_POSITION_OVER_LEFT_FIELD:
- default: // same as SNAP_POSITION_UNDER_LEFT_FIELD
- {
- LinkedPosition position= fRenameLinkedMode.getCurrentLinkedPosition();
- if (position == null)
- return null;
- ISourceViewer viewer= fEditor.getViewer();
- ITextViewerExtension5 viewer5= (ITextViewerExtension5) viewer;
- int widgetOffset= viewer5.modelOffset2WidgetOffset(position.offset/* + position.length*/);
-
- StyledText textWidget= viewer.getTextWidget();
- Point pos= textWidget.getLocationAtOffset(widgetOffset);
- Point pSize= getExtent();
- pSize.y+= HAH + 1;
- pos.x-= HAO;
- if (snapPosition == SNAP_POSITION_OVER_LEFT_FIELD) {
- pos.y-= pSize.y;
- } else {
- pos.y+= textWidget.getLineHeight(widgetOffset);
- }
- Point dPos= textWidget.toDisplay(pos);
- Rectangle displayBounds= textWidget.getDisplay().getClientArea();
- Rectangle dPopupRect= Geometry.createRectangle(dPos, pSize);
- Geometry.moveInside(dPopupRect, displayBounds);
- return new Point(dPopupRect.x, dPopupRect.y);
- }
-
- }
- }
-
- private void addMoveSupport(final Shell popupShell, final Control movedControl) {
- movedControl.addMouseListener(new MouseAdapter() {
-
- public void mouseDown(final MouseEvent downEvent) {
- if (downEvent.button != 1) {
- return;
- }
-
- final Point POPUP_SOURCE= popupShell.getLocation();
- final StyledText textWidget= fEditor.getViewer().getTextWidget();
- Point pSize= getExtent();
- int originalSnapPosition= fSnapPosition;
-
- /*
- * Feature in Tracker: it is not possible to directly control the feedback,
- * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=121300
- * and https://bugs.eclipse.org/bugs/show_bug.cgi?id=121298#c1 .
- *
- * Workaround is to have an offscreen rectangle for tracking mouse movement
- * and a manually updated rectangle for the actual drop target.
- */
- final Tracker tracker= new Tracker(textWidget, SWT.NONE);
-
- final Point[] LOCATIONS= {
- textWidget.toControl(computePopupLocation(SNAP_POSITION_UNDER_RIGHT_FIELD)),
- textWidget.toControl(computePopupLocation(SNAP_POSITION_OVER_RIGHT_FIELD)),
- textWidget.toControl(computePopupLocation(SNAP_POSITION_UNDER_LEFT_FIELD)),
- textWidget.toControl(computePopupLocation(SNAP_POSITION_OVER_LEFT_FIELD)),
- textWidget.toControl(computePopupLocation(SNAP_POSITION_LOWER_RIGHT))
- };
-
- final Rectangle[] DROP_TARGETS= {
- Geometry.createRectangle(LOCATIONS[0], pSize),
- Geometry.createRectangle(LOCATIONS[1], pSize),
- new Rectangle(LOCATIONS[2].x, LOCATIONS[2].y + HAH, pSize.x, pSize.y),
- Geometry.createRectangle(LOCATIONS[3], pSize),
- Geometry.createRectangle(LOCATIONS[4], pSize)
- };
- final Rectangle MOUSE_MOVE_SOURCE= new Rectangle(1000000, 0, 0, 0);
- tracker.setRectangles(new Rectangle[] { MOUSE_MOVE_SOURCE, DROP_TARGETS[fSnapPosition] });
- tracker.setStippled(true);
-
- ControlListener moveListener= new ControlAdapter() {
- /*
- * @see org.eclipse.swt.events.ControlAdapter#controlMoved(org.eclipse.swt.events.ControlEvent)
- */
- public void controlMoved(ControlEvent moveEvent) {
- Rectangle[] currentRects= tracker.getRectangles();
- final Rectangle mouseMoveCurrent= currentRects[0];
- Point popupLoc= new Point(
- POPUP_SOURCE.x + mouseMoveCurrent.x - MOUSE_MOVE_SOURCE.x,
- POPUP_SOURCE.y + mouseMoveCurrent.y - MOUSE_MOVE_SOURCE.y);
-
- popupShell.setLocation(popupLoc);
-
- Point ePopupLoc= textWidget.toControl(popupLoc);
- int minDist= Integer.MAX_VALUE;
- for (int snapPos= 0; snapPos < DROP_TARGETS.length; snapPos++) {
- int dist= Geometry.distanceSquared(ePopupLoc, LOCATIONS[snapPos]);
- if (dist < minDist) {
- minDist= dist;
- fSnapPosition= snapPos;
- currentRects[1]= DROP_TARGETS[snapPos];
- }
- }
- tracker.setRectangles(currentRects);
- }
- };
- tracker.addControlListener(moveListener);
- boolean committed= tracker.open();
- tracker.close();
- tracker.dispose();
- if (committed) {
- getDialogSettings().put(SNAP_POSITION_KEY, fSnapPosition);
- } else {
- fSnapPosition= originalSnapPosition;
- }
- updatePopupLocation(true);
- activateEditor();
- }
- });
- }
-
- private void packPopup() {
- boolean isUnderLeft= fSnapPosition == SNAP_POSITION_UNDER_LEFT_FIELD;
- boolean isOverLeft= fSnapPosition == SNAP_POSITION_OVER_LEFT_FIELD;
- fPopupLayout.marginTop= isUnderLeft ? HAH : 0;
- fPopupLayout.marginBottom= isOverLeft ? HAH + 1 : 0;
- fPopup.pack();
-
- Region oldRegion= fRegion;
- if (isUnderLeft || isOverLeft) {
- fRegion= new Region();
- fRegion.add(getPolygon(false));
- fPopup.setRegion(fRegion);
- Rectangle bounds= fRegion.getBounds();
- fPopup.setSize(bounds.width, bounds.height + 1);
- } else {
- fRegion= null;
- fPopup.setRegion(null);
- }
-
- if (oldRegion != null) {
- oldRegion.dispose();
- }
- }
-
- private Point getExtent() {
- Point e = fPopup.getSize();
- switch (fSnapPosition) {
- case SNAP_POSITION_UNDER_LEFT_FIELD:
- e.y -= HAH;
- break;
- case SNAP_POSITION_OVER_LEFT_FIELD:
- e.y -= HAH + 1;
- break;
- }
- return e;
- }
-
- private int[] getPolygon(boolean border) {
- Point e = getExtent();
- int b = border ? 1 : 0;
- if (true /*arrowOnLeft*/) {
- switch (fSnapPosition) {
- case SNAP_POSITION_OVER_LEFT_FIELD:
- return new int[] {
- 0, 0,
- e.x - b, 0,
- e.x - b, e.y - b,
- HAO + HAW, e.y - b,
- HAO + HAW / 2, e.y + HAH - b,
- HAO, e.y - b,
- 0, e.y - b,
- 0, 0 };
-
- case SNAP_POSITION_UNDER_LEFT_FIELD:
- return new int[] {
- 0, HAH,
- HAO + b, HAH,
- HAO + HAW / 2, b,
- HAO + HAW - b, HAH,
- e.x - b, HAH,
- e.x - b, e.y + HAH - b,
- 0, e.y + HAH - b,
- 0, HAH };
-
- default:
- return new int[] {
- 0, 0,
- e.x - b, 0,
- e.x - b, e.y - b,
- 0, e.y - b,
- 0, 0 };
- }
- }
- //TODO: BiDi?
- return new int[] { 0, 0, e.x - b, 0, e.x - b, e.y - b,
- e.x - HAO - b, e.y - b, e.x - HAO - HAW / 2, e.y + HAH - b,
- e.x - HAO - HAW, e.y - b, 0, e.y - b, 0, 0 };
- }
-
- private void createContent(Composite parent) {
- Display display= parent.getDisplay();
- Color foreground= display.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- Color background= display.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- addMoveSupport(fPopup, parent);
-
- StyledText hint= new StyledText(fPopup, SWT.READ_ONLY | SWT.SINGLE);
- String enterKeyName= getEnterBinding();
- String hintTemplate= ReorgMessages.RenameInformationPopup_EnterNewName;
- hint.setText(Messages.format(hintTemplate, enterKeyName));
- hint.setForeground(foreground);
- hint.setStyleRange(new StyleRange(hintTemplate.indexOf("{0}"), enterKeyName.length(), null, null, SWT.BOLD)); //$NON-NLS-1$
- hint.setEnabled(false); // text must not be selectable
- addMoveSupport(fPopup, hint);
-
- addViewMenu(parent);
-
- recursiveSetBackgroundColor(parent, background);
-
- }
-
- private ToolBar addViewMenu(final Composite parent) {
- fToolBar= new ToolBar(parent, SWT.FLAT);
- final ToolItem menuButton = new ToolItem(fToolBar, SWT.PUSH, 0);
- fMenuImage= JavaPluginImages.DESC_ELCL_VIEW_MENU.createImage();
- menuButton.setImage(fMenuImage);
- menuButton.setToolTipText(ReorgMessages.RenameInformationPopup_menu);
- fToolBar.addMouseListener(new MouseAdapter() {
- public void mouseDown(MouseEvent e) {
- showMenu(fToolBar);
- }
- });
- menuButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- showMenu(fToolBar);
- }
- });
- fToolBar.pack();
- return fToolBar;
- }
-
- private void showMenu(ToolBar toolBar) {
- Menu menu= getMenuManager().createContextMenu(toolBar);
- menu.setLocation(toolBar.toDisplay(0, toolBar.getSize().y));
- fIsMenuUp= true;
- menu.setVisible(true);
- }
-
- private MenuManager getMenuManager() {
- if (fMenuManager != null) {
- return fMenuManager;
- }
-
- fMenuManager= new MenuManager();
- fMenuManager.setRemoveAllWhenShown(true);
-
- fMenuManager.addMenuListener(new IMenuListener2() {
- public void menuAboutToHide(IMenuManager manager) {
- fIsMenuUp= false;
- }
- public void menuAboutToShow(IMenuManager manager) {
- IAction refactorAction= new Action(ReorgMessages.RenameInformationPopup_RenameInWorkspace) {
- public void run() {
- activateEditor();
- fRenameLinkedMode.doRename(false);
- }
- };
- refactorAction.setAccelerator(SWT.CR);
- manager.add(refactorAction);
-
- IAction previewAction= new Action(ReorgMessages.RenameInformationPopup_Preview) {
- public void run() {
- activateEditor();
- fRenameLinkedMode.doRename(true);
- }
- };
- previewAction.setAccelerator(SWT.CTRL | SWT.CR);
- manager.add(previewAction);
-
- IAction openDialogAction= new Action(ReorgMessages.RenameInformationPopup_OpenDialog + '\t' + fOpenDialogBinding) {
- public void run() {
- activateEditor();
- fRenameLinkedMode.startFullDialog();
- }
- };
- manager.add(openDialogAction);
-
- manager.add(new Separator());
-
- MenuManager subMenuManager= new MenuManager(ReorgMessages.RenameInformationPopup_SnapTo);
- addMoveMenuItem(subMenuManager, SNAP_POSITION_UNDER_LEFT_FIELD, ReorgMessages.RenameInformationPopup_snap_under_left);
- addMoveMenuItem(subMenuManager, SNAP_POSITION_UNDER_RIGHT_FIELD, ReorgMessages.RenameInformationPopup_snap_under_right);
- addMoveMenuItem(subMenuManager, SNAP_POSITION_OVER_LEFT_FIELD, ReorgMessages.RenameInformationPopup_snap_over_left);
- addMoveMenuItem(subMenuManager, SNAP_POSITION_OVER_RIGHT_FIELD, ReorgMessages.RenameInformationPopup_snap_over_right);
- addMoveMenuItem(subMenuManager, SNAP_POSITION_LOWER_RIGHT, ReorgMessages.RenameInformationPopup_snap_bottom_right);
- manager.add(subMenuManager);
-
- IAction prefsAction= new Action(ReorgMessages.RenameInformationPopup_preferences) {
- public void run() {
- fRenameLinkedMode.cancel();
- String linkedModePrefPageID= "org.eclipse.ui.editors.preferencePages.LinkedModePreferencePage"; //$NON-NLS-1$
- String refactoringPrefPageID= JavaBasePreferencePage.JAVA_BASE_PREF_PAGE_ID;
- PreferencesUtil.createPreferenceDialogOn(fEditor.getSite().getShell(), refactoringPrefPageID, new String[] { linkedModePrefPageID, refactoringPrefPageID }, null).open();
- }
- };
- manager.add(prefsAction);
- }
- });
- return fMenuManager;
- }
-
- private void addMoveMenuItem(IMenuManager manager, final int snapPosition, String text) {
- IAction action= new Action(text, IAction.AS_RADIO_BUTTON) {
- public void run() {
- fSnapPosition= snapPosition;
- getDialogSettings().put(SNAP_POSITION_KEY, fSnapPosition);
- updatePopupLocation(true);
- activateEditor();
- }
- };
- action.setChecked(fSnapPosition == snapPosition);
- manager.add(action);
- }
-
- private static String getEnterBinding() {
- return KeyStroke.getInstance(KeyLookupFactory.getDefault().formalKeyLookup(IKeyLookup.CR_NAME)).format();
- }
-
- /**
- * WARNING: only works in workbench window context!
- * @return the keybinding for Refactor &gt; Rename
- */
- private static String getOpenDialogBinding() {
- IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService == null)
- return ""; //$NON-NLS-1$
- String binding= bindingService.getBestActiveBindingFormattedFor(IJavaEditorActionDefinitionIds.RENAME_ELEMENT);
- return binding == null ? "" : binding; //$NON-NLS-1$
- }
-
- private static void recursiveSetBackgroundColor(Control control, Color color) {
- control.setBackground(color);
- if (control instanceof Composite) {
- Control[] children= ((Composite) control).getChildren();
- for (int i= 0; i < children.length; i++) {
- recursiveSetBackgroundColor(children[i], color);
- }
- }
- }
-
- public boolean ownsFocusShell() {
- if (fIsMenuUp)
- return true;
- if (fPopup == null || fPopup.isDisposed())
- return false;
- Shell activeShell= fPopup.getDisplay().getActiveShell();
- if (fPopup == activeShell)
- return true;
- return false;
- }
-
- private void activateEditor() {
- fEditor.getSite().getShell().setActive();
- }
-
- public boolean requestWidgetToken(IWidgetTokenOwner owner) {
- return false;
- }
-
- public boolean requestWidgetToken(IWidgetTokenOwner owner, int priority) {
- return false;
- }
-
- public boolean setFocus(IWidgetTokenOwner owner) {
- if (fToolBar != null && ! fToolBar.isDisposed())
- showMenu(fToolBar);
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInputWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInputWizardPage.java
deleted file mode 100644
index ccd61d09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameInputWizardPage.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IDelegateUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IQualifiedNameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.DelegateUIHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.QualifiedNameComponent;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.TextInputWizardPage;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-
-abstract class RenameInputWizardPage extends TextInputWizardPage {
-
- private String fHelpContextID;
- private Button fUpdateReferences;
- private Button fUpdateTextualMatches;
- private Button fUpdateQualifiedNames;
- private Button fLeaveDelegateCheckBox;
- private Button fDeprecateDelegateCheckBox;
- private QualifiedNameComponent fQualifiedNameComponent;
-
- /**
- * Creates a new text input page.
- * @param isLastUserPage <code>true</code> if this page is the wizard's last
- * user input page. Otherwise <code>false</code>.
- * @param initialValue the initial value
- */
- public RenameInputWizardPage(String description, String contextHelpId, boolean isLastUserPage, String initialValue) {
- super(description, isLastUserPage, initialValue);
- fHelpContextID= contextHelpId;
- }
-
- public void createControl(Composite parent) {
- Composite superComposite= new Composite(parent, SWT.NONE);
- setControl(superComposite);
- initializeDialogUnits(superComposite);
- superComposite.setLayout(new GridLayout());
- Composite composite= new Composite(superComposite, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
-
- composite.setLayout(layout);
- RowLayouter layouter= new RowLayouter(2);
-
- Label label= new Label(composite, SWT.NONE);
- label.setText(getLabelText());
-
- Text text= createTextInputField(composite);
- text.selectAll();
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint= convertWidthInCharsToPixels(25);
- text.setLayoutData(gd);
-
- layouter.perform(label, text, 1);
-
- Label separator= new Label(composite, SWT.NONE);
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, false, false);
- gridData.heightHint= 2;
- separator.setLayoutData(gridData);
-
-
- int indent= convertWidthInCharsToPixels(2);
-
- addOptionalUpdateReferencesCheckbox(composite, layouter);
- addAdditionalOptions(composite, layouter);
- addOptionalUpdateTextualMatches(composite, layouter);
- addOptionalUpdateQualifiedNameComponent(composite, layouter, indent);
- addOptionalLeaveDelegateCheckbox(composite, layouter);
- addOptionalDeprecateDelegateCheckbox(composite, layouter, indent);
- updateForcePreview();
-
- Dialog.applyDialogFont(superComposite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), fHelpContextID);
- }
-
- /**
- * Clients can override this method to provide more UI elements. By default, does nothing
- *
- * @param composite the parent composite
- * @param layouter the row layouter to use
- */
- protected void addAdditionalOptions(Composite composite, RowLayouter layouter) {
- // none by default
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- INameUpdating nameUpdating= (INameUpdating)getRefactoring().getAdapter(INameUpdating.class);
- if (nameUpdating != null) {
- String newName= getNewName(nameUpdating);
- if (newName != null && newName.length() > 0 && !newName.equals(getInitialValue())) {
- Text textField= getTextField();
- textField.setText(newName);
- textField.setSelection(0, newName.length());
- }
- }
- }
- super.setVisible(visible);
- }
-
- /**
- * Returns the new name for the Java element or <code>null</code>
- * if no new name is provided
- *
- * @return the new name or <code>null</code>
- */
- protected String getNewName(INameUpdating nameUpdating) {
- return nameUpdating.getNewElementName();
- }
-
- protected boolean saveSettings() {
- // always save
-// if (getContainer() instanceof Dialog)
-// return ((Dialog)getContainer()).getReturnCode() == IDialogConstants.OK_ID;
- return true;
- }
-
- public void dispose() {
- if (saveSettings()) {
- saveBooleanSetting(RenameRefactoringWizard.UPDATE_TEXTUAL_MATCHES, fUpdateTextualMatches);
- saveBooleanSetting(RenameRefactoringWizard.UPDATE_QUALIFIED_NAMES, fUpdateQualifiedNames);
- if (fQualifiedNameComponent != null)
- fQualifiedNameComponent.savePatterns(getRefactoringSettings());
- DelegateUIHelper.saveLeaveDelegateSetting(fLeaveDelegateCheckBox);
- DelegateUIHelper.saveDeprecateDelegateSetting(fDeprecateDelegateCheckBox);
- }
- super.dispose();
- }
-
- private void addOptionalUpdateReferencesCheckbox(Composite result, RowLayouter layouter) {
- final IReferenceUpdating ref= (IReferenceUpdating)getRefactoring().getAdapter(IReferenceUpdating.class);
- if (ref == null || !ref.canEnableUpdateReferences())
- return;
- String title= RefactoringMessages.RenameInputWizardPage_update_references;
- boolean defaultValue= true; //bug 77901
- fUpdateReferences= createCheckbox(result, title, defaultValue, layouter);
- ref.setUpdateReferences(fUpdateReferences.getSelection());
- fUpdateReferences.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- ref.setUpdateReferences(fUpdateReferences.getSelection());
- }
- });
- }
-
- private void addOptionalUpdateTextualMatches(Composite result, RowLayouter layouter) {
- final ITextUpdating refactoring= (ITextUpdating) getRefactoring().getAdapter(ITextUpdating.class);
- if (refactoring == null || !refactoring.canEnableTextUpdating())
- return;
- String title= RefactoringMessages.RenameInputWizardPage_update_textual_matches;
- boolean defaultValue= getBooleanSetting(RenameRefactoringWizard.UPDATE_TEXTUAL_MATCHES, refactoring.getUpdateTextualMatches());
- fUpdateTextualMatches= createCheckbox(result, title, defaultValue, layouter);
- refactoring.setUpdateTextualMatches(fUpdateTextualMatches.getSelection());
- fUpdateTextualMatches.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- refactoring.setUpdateTextualMatches(fUpdateTextualMatches.getSelection());
- updateForcePreview();
- }
- });
- }
-
- private void addOptionalUpdateQualifiedNameComponent(Composite parent, RowLayouter layouter, int marginWidth) {
- final IQualifiedNameUpdating ref= (IQualifiedNameUpdating)getRefactoring().getAdapter(IQualifiedNameUpdating.class);
- if (ref == null || !ref.canEnableQualifiedNameUpdating())
- return;
- fUpdateQualifiedNames= new Button(parent, SWT.CHECK);
- int indent= marginWidth + fUpdateQualifiedNames.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
- fUpdateQualifiedNames.setText(RefactoringMessages.RenameInputWizardPage_update_qualified_names);
- layouter.perform(fUpdateQualifiedNames);
-
- fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, ref, getRefactoringSettings());
- layouter.perform(fQualifiedNameComponent);
- GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
- gd.horizontalAlignment= GridData.FILL;
- gd.horizontalIndent= indent;
-
- boolean defaultSelection= getBooleanSetting(RenameRefactoringWizard.UPDATE_QUALIFIED_NAMES, ref.getUpdateQualifiedNames());
- fUpdateQualifiedNames.setSelection(defaultSelection);
- updateQulifiedNameUpdating(ref, defaultSelection);
-
- fUpdateQualifiedNames.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- boolean enabled= ((Button)e.widget).getSelection();
- updateQulifiedNameUpdating(ref, enabled);
- }
- });
- }
-
- private void updateQulifiedNameUpdating(final IQualifiedNameUpdating ref, boolean enabled) {
- fQualifiedNameComponent.setEnabled(enabled);
- ref.setUpdateQualifiedNames(enabled);
- updateForcePreview();
- }
-
- private void addOptionalLeaveDelegateCheckbox(Composite result, RowLayouter layouter) {
- final IDelegateUpdating refactoring= (IDelegateUpdating) getRefactoring().getAdapter(IDelegateUpdating.class);
- if (refactoring == null || !refactoring.canEnableDelegateUpdating())
- return;
- fLeaveDelegateCheckBox= createCheckbox(result, refactoring.getDelegateUpdatingTitle(false), DelegateUIHelper.loadLeaveDelegateSetting(refactoring), layouter);
- refactoring.setDelegateUpdating(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- refactoring.setDelegateUpdating(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
-
- private void addOptionalDeprecateDelegateCheckbox(Composite result, RowLayouter layouter, int marginWidth) {
- final IDelegateUpdating refactoring= (IDelegateUpdating) getRefactoring().getAdapter(IDelegateUpdating.class);
- if (refactoring == null || !refactoring.canEnableDelegateUpdating())
- return;
- fDeprecateDelegateCheckBox= new Button(result, SWT.CHECK);
- GridData data= new GridData();
- data.horizontalAlignment= GridData.FILL;
- data.horizontalIndent= (marginWidth + fDeprecateDelegateCheckBox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
- fDeprecateDelegateCheckBox.setLayoutData(data);
- fDeprecateDelegateCheckBox.setText(DelegateUIHelper.getDeprecateDelegateCheckBoxTitle());
- fDeprecateDelegateCheckBox.setSelection(DelegateUIHelper.loadDeprecateDelegateSetting(refactoring));
- layouter.perform(fDeprecateDelegateCheckBox);
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- fDeprecateDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- refactoring.setDeprecateDelegates(fDeprecateDelegateCheckBox.getSelection());
- }
- });
- if (fLeaveDelegateCheckBox != null) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- fLeaveDelegateCheckBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fDeprecateDelegateCheckBox.setEnabled(fLeaveDelegateCheckBox.getSelection());
- }
- });
- }
- }
-
- protected void updateLeaveDelegateCheckbox(int delegateCount) {
- if (fLeaveDelegateCheckBox == null)
- return;
- final IDelegateUpdating refactoring= (IDelegateUpdating) getRefactoring().getAdapter(IDelegateUpdating.class);
- fLeaveDelegateCheckBox.setEnabled(delegateCount > 0);
- fLeaveDelegateCheckBox.setText(refactoring.getDelegateUpdatingTitle(delegateCount > 1));
- if (delegateCount == 0) {
- fLeaveDelegateCheckBox.setSelection(false);
- refactoring.setDelegateUpdating(false);
- }
- }
-
- protected String getLabelText() {
- return RefactoringMessages.RenameInputWizardPage_new_name;
- }
-
- protected boolean getBooleanSetting(String key, boolean defaultValue) {
- String update= getRefactoringSettings().get(key);
- if (update != null)
- return Boolean.valueOf(update).booleanValue();
- else
- return defaultValue;
- }
-
- protected void saveBooleanSetting(String key, Button checkBox) {
- if (checkBox != null)
- getRefactoringSettings().put(key, checkBox.getSelection());
- }
-
- private static Button createCheckbox(Composite parent, String title, boolean value, RowLayouter layouter) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(title);
- checkBox.setSelection(value);
- layouter.perform(checkBox);
- return checkBox;
- }
-
- private void updateForcePreview() {
- boolean forcePreview= false;
- Refactoring refactoring= getRefactoring();
- ITextUpdating tu= (ITextUpdating) refactoring.getAdapter(ITextUpdating.class);
- IQualifiedNameUpdating qu= (IQualifiedNameUpdating)refactoring.getAdapter(IQualifiedNameUpdating.class);
- if (tu != null) {
- forcePreview= tu.getUpdateTextualMatches();
- }
- if (qu != null) {
- forcePreview |= qu.getUpdateQualifiedNames();
- }
- getRefactoringWizard().setForcePreviewReview(forcePreview);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameJavaProjectWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameJavaProjectWizard.java
deleted file mode 100644
index d1d4475e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameJavaProjectWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameJavaProjectWizard extends RenameRefactoringWizard {
-
- public RenameJavaProjectWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenameJavaProject_defaultPageTitle,
- RefactoringMessages.RenameJavaProject_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR,
- IJavaHelpContextIds.RENAME_JAVA_PROJECT_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java
deleted file mode 100644
index 18501474..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java
+++ /dev/null
@@ -1,610 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.Comparator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IEditingSupport;
-import org.eclipse.jface.text.IEditingSupportRegistry;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.refactoring.IJavaScriptRefactorings;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.DelegateUIHelper;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.LinkedNamesAssistProposal.DeleteBlockingExitPolicy;
-import org.eclipse.wst.jsdt.ui.refactoring.RenameSupport;
-
-public class RenameLinkedMode {
-
- private class FocusEditingSupport implements IEditingSupport {
- public boolean ownsFocusShell() {
- if (fInfoPopup == null)
- return false;
- if (fInfoPopup.ownsFocusShell()) {
- return true;
- }
-
- Shell editorShell= fEditor.getSite().getShell();
- Shell activeShell= editorShell.getDisplay().getActiveShell();
- if (editorShell == activeShell)
- return true;
- return false;
- }
-
- public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) {
- return false; //leave on external modification outside positions
- }
- }
-
- private class EditorSynchronizer implements ILinkedModeListener {
- public void left(LinkedModeModel model, int flags) {
- linkedModeLeft();
- if ( (flags & ILinkedModeListener.UPDATE_CARET) != 0) {
- doRename(fShowPreview);
- }
- }
-
- public void resume(LinkedModeModel model, int flags) {
- }
-
- public void suspend(LinkedModeModel model) {
- }
- }
-
- private class ExitPolicy extends DeleteBlockingExitPolicy {
- public ExitPolicy(IDocument document) {
- super(document);
- }
-
- public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) {
- fShowPreview|= (event.stateMask & SWT.CTRL) != 0;
- return super.doExit(model, event, offset, length);
- }
- }
-
-
- private static RenameLinkedMode fgActiveLinkedMode;
-
- private final CompilationUnitEditor fEditor;
- private final IJavaScriptElement fJavaElement;
-
- private RenameInformationPopup fInfoPopup;
-
- private boolean fOriginalSaved;
- private Point fOriginalSelection;
- private String fOriginalName;
-
- private LinkedPosition fNamePosition;
- private LinkedModeModel fLinkedModeModel;
- private LinkedPositionGroup fLinkedPositionGroup;
- private final FocusEditingSupport fFocusEditingSupport;
- private boolean fShowPreview;
-
-
- public RenameLinkedMode(IJavaScriptElement element, CompilationUnitEditor editor) {
- Assert.isNotNull(element);
- Assert.isNotNull(editor);
- fEditor= editor;
- fJavaElement= element;
- fFocusEditingSupport= new FocusEditingSupport();
- }
-
- public static RenameLinkedMode getActiveLinkedMode() {
- if (fgActiveLinkedMode != null) {
- ISourceViewer viewer= fgActiveLinkedMode.fEditor.getViewer();
- if (viewer != null) {
- StyledText textWidget= viewer.getTextWidget();
- if (textWidget != null && ! textWidget.isDisposed()) {
- return fgActiveLinkedMode;
- }
- }
- // make sure we don't hold onto the active linked mode if anything went wrong with canceling:
- fgActiveLinkedMode= null;
- }
- return null;
- }
-
- public void start() {
- if (getActiveLinkedMode() != null) {
- // for safety; should already be handled in RenameJavaElementAction
- fgActiveLinkedMode.startFullDialog();
- return;
- }
-
- fOriginalSaved= ! fEditor.isDirty();
-
- ISourceViewer viewer= fEditor.getViewer();
- IDocument document= viewer.getDocument();
- fOriginalSelection= viewer.getSelectedRange();
- int offset= fOriginalSelection.x;
-
- try {
- JavaScriptUnit root= JavaScriptPlugin.getDefault().getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null);
-
- fLinkedPositionGroup= new LinkedPositionGroup();
- ASTNode selectedNode= NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y);
- if (! (selectedNode instanceof SimpleName)) {
- return; // TODO: show dialog
- }
- SimpleName nameNode= (SimpleName) selectedNode;
-
- fOriginalName= nameNode.getIdentifier();
- final int pos= nameNode.getStartPosition();
- ASTNode[] sameNodes= LinkedNodeFinder.findByNode(root, nameNode);
-
- //TODO: copied from LinkedNamesAssistProposal#apply(..):
- // sort for iteration order, starting with the node @ offset
- Arrays.sort(sameNodes, new Comparator() {
- public int compare(Object o1, Object o2) {
- return rank((ASTNode) o1) - rank((ASTNode) o2);
- }
- /**
- * Returns the absolute rank of an <code>ASTNode</code>. Nodes
- * preceding <code>pos</code> are ranked last.
- *
- * @param node the node to compute the rank for
- * @return the rank of the node with respect to the invocation offset
- */
- private int rank(ASTNode node) {
- int relativeRank= node.getStartPosition() + node.getLength() - pos;
- if (relativeRank < 0)
- return Integer.MAX_VALUE + relativeRank;
- else
- return relativeRank;
- }
- });
- for (int i= 0; i < sameNodes.length; i++) {
- ASTNode elem= sameNodes[i];
- LinkedPosition linkedPosition= new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i);
- if (i == 0)
- fNamePosition= linkedPosition;
- fLinkedPositionGroup.addPosition(linkedPosition);
- }
-
- fLinkedModeModel= new LinkedModeModel();
- fLinkedModeModel.addGroup(fLinkedPositionGroup);
- fLinkedModeModel.forceInstall();
- fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
- fLinkedModeModel.addLinkingListener(new EditorSynchronizer());
-
- LinkedModeUI ui= new EditorLinkedModeUI(fLinkedModeModel, viewer);
- ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
- ui.setExitPolicy(new ExitPolicy(document));
- ui.enter();
-
- viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection
-
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.register(fFocusEditingSupport);
- }
-
- openSecondaryPopup();
-// startAnimation();
- fgActiveLinkedMode= this;
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
-// private void startAnimation() {
-// //TODO:
-// // - switch off if animations disabled
-// // - show rectangle around target for 500ms after animation
-// Shell shell= fEditor.getSite().getShell();
-// StyledText textWidget= fEditor.getViewer().getTextWidget();
-//
-// // from popup:
-// Rectangle startRect= fPopup.getBounds();
-//
-// // from editor:
-//// Point startLoc= textWidget.getParent().toDisplay(textWidget.getLocation());
-//// Point startSize= textWidget.getSize();
-//// Rectangle startRect= new Rectangle(startLoc.x, startLoc.y, startSize.x, startSize.y);
-//
-// // from hell:
-//// Rectangle startRect= shell.getClientArea();
-//
-// Point caretLocation= textWidget.getLocationAtOffset(textWidget.getCaretOffset());
-// Point displayLocation= textWidget.toDisplay(caretLocation);
-// Rectangle targetRect= new Rectangle(displayLocation.x, displayLocation.y, 0, 0);
-//
-// RectangleAnimation anim= new RectangleAnimation(shell, startRect, targetRect);
-// anim.schedule();
-// }
-
- void doRename(boolean showPreview) {
- cancel();
-
- Image image= null;
- Label label= null;
-
- fShowPreview|= showPreview;
- try {
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof SourceViewer) {
- SourceViewer sourceViewer= (SourceViewer) viewer;
- Control viewerControl= sourceViewer.getControl();
- if (viewerControl instanceof Composite) {
- Composite composite= (Composite) viewerControl;
- Display display= composite.getDisplay();
-
- // Flush pending redraw requests:
- while (! display.isDisposed() && display.readAndDispatch()) {
- }
-
- // Copy editor area:
- GC gc= new GC(composite);
- Point size;
- try {
- size= composite.getSize();
- image= new Image(gc.getDevice(), size.x, size.y);
- gc.copyArea(image, 0, 0);
- } finally {
- gc.dispose();
- gc= null;
- }
-
- // Persist editor area while executing refactoring:
- label= new Label(composite, SWT.NONE);
- label.setImage(image);
- label.setBounds(0, 0, size.x, size.y);
- label.moveAbove(null);
- }
- }
-
- String newName= fNamePosition.getContent();
- if (fOriginalName.equals(newName))
- return;
- RenameSupport renameSupport= undoAndCreateRenameSupport(newName);
- if (renameSupport == null)
- return;
-
- Shell shell= fEditor.getSite().getShell();
- boolean executed;
- if (fShowPreview) { // could have been updated by undoAndCreateRenameSupport(..)
- executed= renameSupport.openDialog(shell, true);
- } else {
- renameSupport.perform(shell, fEditor.getSite().getWorkbenchWindow());
- executed= true;
- }
- if (executed) {
- restoreFullSelection();
- }
- JavaModelUtil.reconcile(getCompilationUnit());
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- } catch (InterruptedException ex) {
- // canceling is OK -> redo text changes in that case?
- } catch (InvocationTargetException ex) {
- JavaScriptPlugin.log(ex);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } finally {
- if (label != null)
- label.dispose();
- if (image != null)
- image.dispose();
- }
- }
-
- public void cancel() {
- if (fLinkedModeModel != null) {
- fLinkedModeModel.exit(ILinkedModeListener.NONE);
- }
- linkedModeLeft();
- }
-
- private void restoreFullSelection() {
- if (fOriginalSelection.y != 0) {
- int originalOffset= fOriginalSelection.x;
- LinkedPosition[] positions= fLinkedPositionGroup.getPositions();
- for (int i= 0; i < positions.length; i++) {
- LinkedPosition position= positions[i];
- if (! position.isDeleted() && position.includes(originalOffset)) {
- fEditor.getViewer().setSelectedRange(position.offset, position.length);
- return;
- }
- }
- }
- }
-
- private RenameSupport undoAndCreateRenameSupport(String newName) throws CoreException {
- // Assumption: the linked mode model should be shut down by now.
-
- ISourceViewer viewer= fEditor.getViewer();
- final IDocument document= viewer.getDocument();
-
- try {
- if (! fOriginalName.equals(newName)) {
- fEditor.getSite().getWorkbenchWindow().run(false, true, new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- LinkedPosition[] positions= fLinkedPositionGroup.getPositions();
- Arrays.sort(positions, new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((LinkedPosition) o1).offset - ((LinkedPosition) o2).offset;
- }
- });
- int correction= 0;
- int originalLength= fOriginalName.length();
- for (int i= 0; i < positions.length; i++) {
- LinkedPosition position= positions[i];
- try {
- int length= position.getLength();
- document.replace(position.getOffset() + correction, length, fOriginalName);
- correction= correction - length + originalLength;
- } catch (BadLocationException e) {
- throw new InvocationTargetException(e);
- }
- }
- if (fOriginalSaved) {
- fEditor.doSave(monitor); // started saved -> end saved
- }
- }
- });
- }
- } catch (InvocationTargetException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), ReorgMessages.RenameLinkedMode_error_saving_editor, e));
- } catch (InterruptedException e) {
- // cancelling is OK
- return null;
- } finally {
- JavaModelUtil.reconcile(getCompilationUnit());
- }
-
- viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y);
-
- RenameJavaScriptElementDescriptor descriptor= createRenameDescriptor(fJavaElement, newName);
- RenameSupport renameSupport= RenameSupport.create(descriptor);
- return renameSupport;
- }
-
- private IJavaScriptUnit getCompilationUnit() {
- return (IJavaScriptUnit) EditorUtility.getEditorInputJavaElement(fEditor, false);
- }
-
- public void startFullDialog() {
- cancel();
-
- try {
- String newName= fNamePosition.getContent();
- RenameSupport renameSupport= undoAndCreateRenameSupport(newName);
- if (renameSupport != null)
- renameSupport.openDialog(fEditor.getSite().getShell());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * @param javaElement
- * @param newName
- * @return a rename descriptor with current settings as used in the refactoring dialogs
- * @throws JavaScriptModelException
- */
- private RenameJavaScriptElementDescriptor createRenameDescriptor(IJavaScriptElement javaElement, String newName) throws JavaScriptModelException {
- String contributionId;
- // see RefactoringExecutionStarter#createRenameSupport(..):
- int elementType= javaElement.getElementType();
- switch (elementType) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- contributionId= IJavaScriptRefactorings.RENAME_JAVA_PROJECT;
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- contributionId= IJavaScriptRefactorings.RENAME_SOURCE_FOLDER;
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- contributionId= IJavaScriptRefactorings.RENAME_PACKAGE;
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- contributionId= IJavaScriptRefactorings.RENAME_JAVASCRIPT_UNIT;
- break;
- case IJavaScriptElement.TYPE:
- contributionId= IJavaScriptRefactorings.RENAME_TYPE;
- break;
- case IJavaScriptElement.METHOD:
- final IFunction method= (IFunction) javaElement;
- if (method.isConstructor())
- return createRenameDescriptor(method.getDeclaringType(), newName);
- else
- contributionId= IJavaScriptRefactorings.RENAME_METHOD;
- break;
- case IJavaScriptElement.FIELD:
- contributionId= IJavaScriptRefactorings.RENAME_FIELD;
- break;
- case IJavaScriptElement.LOCAL_VARIABLE:
- contributionId= IJavaScriptRefactorings.RENAME_LOCAL_VARIABLE;
- break;
- default:
- return null;
- }
-
- RenameJavaScriptElementDescriptor descriptor= (RenameJavaScriptElementDescriptor) RefactoringCore.getRefactoringContribution(contributionId).createDescriptor();
- descriptor.setJavaElement(javaElement);
- descriptor.setNewName(newName);
- if (elementType != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- descriptor.setUpdateReferences(true);
-
- IDialogSettings javaSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- IDialogSettings refactoringSettings= javaSettings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS); //TODO: undocumented API
- if (refactoringSettings == null) {
- refactoringSettings= javaSettings.addNewSection(RefactoringWizardPage.REFACTORING_SETTINGS);
- }
-
- switch (elementType) {
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- descriptor.setDeprecateDelegate(refactoringSettings.getBoolean(DelegateUIHelper.DELEGATE_DEPRECATION));
- descriptor.setKeepOriginal(refactoringSettings.getBoolean(DelegateUIHelper.DELEGATE_UPDATING));
- }
- switch (elementType) {
- case IJavaScriptElement.TYPE:
-// case IJavaScriptElement.JAVASCRIPT_UNIT: // TODO
- descriptor.setUpdateSimilarDeclarations(refactoringSettings.getBoolean(RenameRefactoringWizard.TYPE_UPDATE_SIMILAR_ELEMENTS));
- int strategy;
- try {
- strategy= refactoringSettings.getInt(RenameRefactoringWizard.TYPE_SIMILAR_MATCH_STRATEGY);
- } catch (NumberFormatException e) {
- strategy= RenamingNameSuggestor.STRATEGY_EXACT;
- }
- descriptor.setMatchStrategy(strategy);
- }
- switch (elementType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- descriptor.setUpdateHierarchy(refactoringSettings.getBoolean(RenameRefactoringWizard.PACKAGE_RENAME_SUBPACKAGES));
- }
- switch (elementType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.TYPE:
- String fileNamePatterns= refactoringSettings.get(RenameRefactoringWizard.QUALIFIED_NAMES_PATTERNS);
- if (fileNamePatterns != null && fileNamePatterns.length() != 0) {
- descriptor.setFileNamePatterns(fileNamePatterns);
- boolean updateQualifiedNames= refactoringSettings.getBoolean(RenameRefactoringWizard.UPDATE_QUALIFIED_NAMES);
- descriptor.setUpdateQualifiedNames(updateQualifiedNames);
- fShowPreview|= updateQualifiedNames;
- }
- }
- switch (elementType) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.FIELD:
- boolean updateTextualOccurrences= refactoringSettings.getBoolean(RenameRefactoringWizard.UPDATE_TEXTUAL_MATCHES);
- descriptor.setUpdateTextualOccurrences(updateTextualOccurrences);
- fShowPreview|= updateTextualOccurrences;
- }
- switch (elementType) {
- case IJavaScriptElement.FIELD:
- descriptor.setRenameGetters(refactoringSettings.getBoolean(RenameRefactoringWizard.FIELD_RENAME_GETTER));
- descriptor.setRenameSetters(refactoringSettings.getBoolean(RenameRefactoringWizard.FIELD_RENAME_SETTER));
- }
- return descriptor;
- }
-
- private void linkedModeLeft() {
- fgActiveLinkedMode= null;
- if (fInfoPopup != null) {
- fInfoPopup.close();
- }
-
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.unregister(fFocusEditingSupport);
- }
- }
-
- private void openSecondaryPopup() {
- fInfoPopup= new RenameInformationPopup(fEditor, this);
- fInfoPopup.open();
- }
-
- public boolean isCaretInLinkedPosition() {
- return getCurrentLinkedPosition() != null;
- }
-
- public LinkedPosition getCurrentLinkedPosition() {
- Point selection= fEditor.getViewer().getSelectedRange();
- int start= selection.x;
- int end= start + selection.y;
- LinkedPosition[] positions= fLinkedPositionGroup.getPositions();
- for (int i= 0; i < positions.length; i++) {
- LinkedPosition position= positions[i];
- if (position.includes(start) && position.includes(end))
- return position;
- }
- return null;
- }
-
- public boolean isEnabled() {
- try {
- String newName= fNamePosition.getContent();
- if (fOriginalName.equals(newName))
- return false;
- /*
- * TODO: use JavaRenameProcessor#checkNewElementName(String)
- * but make sure implementations don't access outdated Java Model
- * (cache all necessary information before starting linked mode).
- */
- IJavaScriptProject project= fJavaElement.getJavaScriptProject();
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String complianceLevel= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- return JavaScriptConventions.validateIdentifier(newName, sourceLevel, complianceLevel).isOK();
- } catch (BadLocationException e) {
- return false;
- }
-
- }
-
- public boolean isOriginalName() {
- try {
- String newName= fNamePosition.getContent();
- return fOriginalName.equals(newName);
- } catch (BadLocationException e) {
- return false;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLocalVariableWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLocalVariableWizard.java
deleted file mode 100644
index f5271bb5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLocalVariableWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public final class RenameLocalVariableWizard extends RenameRefactoringWizard {
-
- public RenameLocalVariableWizard(Refactoring refactoring) {
- super(
- refactoring,
- RefactoringMessages.RenameLocalVariableWizard_defaultPageTitle,
- RefactoringMessages.RenameTypeParameterWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR, IJavaHelpContextIds.RENAME_LOCAL_VARIABLE_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodUserInterfaceStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodUserInterfaceStarter.java
deleted file mode 100644
index 0093d6cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodUserInterfaceStarter.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringCoreMessages;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public class RenameMethodUserInterfaceStarter extends RenameUserInterfaceStarter {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameUserInterfaceStarter#activate(org.eclipse.wst.jsdt.internal.corext.refactoring.base.Refactoring, org.eclipse.swt.widgets.Shell)
- */
- public boolean activate(Refactoring refactoring, Shell parent, int saveMode) throws CoreException {
- RenameVirtualMethodProcessor processor= (RenameVirtualMethodProcessor)refactoring.getAdapter(RenameVirtualMethodProcessor.class);
- if (processor != null) {
- RefactoringStatus status= processor.checkInitialConditions(new NullProgressMonitor());
- if (!status.hasFatalError()) {
- IFunction method= processor.getMethod();
- if (!method.equals(processor.getOriginalMethod())) {
- String message= null;
- message= Messages.format(
- RefactoringCoreMessages.MethodChecks_overrides,
- new String[]{
- JavaElementUtil.createMethodSignature(method),
- JavaModelUtil.getFullyQualifiedName(method.getDeclaringType())});
-
- message= Messages.format(
- ReorgMessages.RenameMethodUserInterfaceStarter_message,
- message);
- if (!MessageDialog.openQuestion(parent,
- ReorgMessages.RenameMethodUserInterfaceStarter_name,
- message)) {
- return false;
- }
- }
- }
- }
- return super.activate(refactoring, parent, saveMode);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodWizard.java
deleted file mode 100644
index afc5d7c3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameMethodWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameMethodWizard extends RenameRefactoringWizard {
-
- public RenameMethodWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenameMethodWizard_defaultPageTitle,
- RefactoringMessages.RenameMethodWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR_METHOD,
- IJavaHelpContextIds.RENAME_METHOD_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenamePackageWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenamePackageWizard.java
deleted file mode 100644
index 71a3e344..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenamePackageWizard.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-
-
-public class RenamePackageWizard extends RenameRefactoringWizard {
-
- public RenamePackageWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenamePackageWizard_defaultPageTitle,
- RefactoringMessages.RenamePackageWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR_PACKAGE,
- IJavaHelpContextIds.RENAME_PACKAGE_WIZARD_PAGE);
- }
-
- protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
- return new RenamePackageInputWizardPage(message, IJavaHelpContextIds.RENAME_PACKAGE_WIZARD_PAGE, initialSetting) {
- protected RefactoringStatus validateTextField(String text) {
- return validateNewName(text);
- }
- };
- }
-
- private static class RenamePackageInputWizardPage extends RenameInputWizardPage {
-
- private Button fRenameSubpackages;
- public RenamePackageInputWizardPage(String message, String contextHelpId, String initialValue) {
- super(message, contextHelpId, true, initialValue);
- }
-
- protected void addAdditionalOptions(Composite composite, RowLayouter layouter) {
- fRenameSubpackages= new Button(composite, SWT.CHECK);
- fRenameSubpackages.setText(RefactoringMessages.RenamePackageWizard_rename_subpackages);
- boolean subpackagesSelection= getBooleanSetting(RenameRefactoringWizard.PACKAGE_RENAME_SUBPACKAGES, getRenamePackageProcessor().getRenameSubpackages());
- fRenameSubpackages.setSelection(subpackagesSelection);
- getRenamePackageProcessor().setRenameSubpackages(subpackagesSelection);
- fRenameSubpackages.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fRenameSubpackages.addSelectionListener(new SelectionAdapter(){
- public void widgetSelected(SelectionEvent e) {
- getRenamePackageProcessor().setRenameSubpackages(fRenameSubpackages.getSelection());
- }
- });
- layouter.perform(fRenameSubpackages);
-
- Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layouter.perform(separator);
- }
-
- public void dispose() {
- if (saveSettings() && fRenameSubpackages.isEnabled())
- saveBooleanSetting(RenameRefactoringWizard.PACKAGE_RENAME_SUBPACKAGES, fRenameSubpackages);
- super.dispose();
- }
-
- private RenamePackageProcessor getRenamePackageProcessor() {
- return (RenamePackageProcessor) ((RenameRefactoring) getRefactoring()).getProcessor();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameRefactoringWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameRefactoringWizard.java
deleted file mode 100644
index 4ed13f70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameRefactoringWizard.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameRefactoringWizard extends RefactoringWizard {
-
- private final String fInputPageDescription;
- private final String fPageContextHelpId;
- private final ImageDescriptor fInputPageImageDescriptor;
-
- // dialog settings constants:
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String UPDATE_TEXTUAL_MATCHES= "updateTextualMatches"; //$NON-NLS-1$
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String UPDATE_QUALIFIED_NAMES= "updateQualifiedNames"; //$NON-NLS-1$
- /**
- * Dialog settings key (value is of type String).
- */
- public static final String QUALIFIED_NAMES_PATTERNS= "patterns"; //$NON-NLS-1$
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String TYPE_UPDATE_SIMILAR_ELEMENTS= "updateSimilarElements"; //$NON-NLS-1$
- /**
- * Dialog settings key (value is of type int).
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor
- */
- public static final String TYPE_SIMILAR_MATCH_STRATEGY= "updateSimilarElementsMatchStrategy"; //$NON-NLS-1$
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String PACKAGE_RENAME_SUBPACKAGES= "renameSubpackages"; //$NON-NLS-1$
-
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String FIELD_RENAME_GETTER= "renameGetter"; //$NON-NLS-1$
- /**
- * Dialog settings key (value is of type boolean).
- */
- public static final String FIELD_RENAME_SETTER= "renameSetter"; //$NON-NLS-1$
-
-
- public RenameRefactoringWizard(Refactoring refactoring, String defaultPageTitle, String inputPageDescription,
- ImageDescriptor inputPageImageDescriptor, String pageContextHelpId) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(defaultPageTitle);
- fInputPageDescription= inputPageDescription;
- fInputPageImageDescriptor= inputPageImageDescriptor;
- fPageContextHelpId= pageContextHelpId;
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- }
-
- /* non java-doc
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- String initialSetting= getNameUpdating().getCurrentElementName();
- RenameInputWizardPage inputPage= createInputPage(fInputPageDescription, initialSetting);
- inputPage.setImageDescriptor(fInputPageImageDescriptor);
- addPage(inputPage);
- }
-
- private INameUpdating getNameUpdating() {
- return (INameUpdating)getRefactoring().getAdapter(INameUpdating.class);
- }
-
- protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
- return new RenameInputWizardPage(message, fPageContextHelpId, true, initialSetting) {
- protected RefactoringStatus validateTextField(String text) {
- return validateNewName(text);
- }
- };
- }
-
- protected RefactoringStatus validateNewName(String newName) {
- INameUpdating ref= getNameUpdating();
- ref.setNewElementName(newName);
- try{
- return ref.checkNewElementName(newName);
- } catch (CoreException e){
- JavaScriptPlugin.log(e);
- return RefactoringStatus.createFatalErrorStatus(RefactoringMessages.RenameRefactoringWizard_internal_error);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameResourceWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameResourceWizard.java
deleted file mode 100644
index 246e222a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameResourceWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameResourceWizard extends RenameRefactoringWizard {
-
- public RenameResourceWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenameResourceWizard_defaultPageTitle,
- RefactoringMessages.RenameResourceWizard_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR,
- IJavaHelpContextIds.RENAME_RESOURCE_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSelectionState.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSelectionState.java
deleted file mode 100644
index 1372beb7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSelectionState.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IViewReference;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-public class RenameSelectionState {
- private final Display fDisplay;
- private final Object fElement;
- private final List fParts;
- private final List fSelections;
-
- public RenameSelectionState(Object element) {
- fElement= element;
- fParts= new ArrayList();
- fSelections= new ArrayList();
-
- IWorkbenchWindow dw = JavaScriptPlugin.getActiveWorkbenchWindow();
- if (dw == null) {
- fDisplay= null;
- return;
- }
- fDisplay= dw.getShell().getDisplay();
- IWorkbenchPage page = dw.getActivePage();
- if (page == null)
- return;
- IViewReference vrefs[]= page.getViewReferences();
- for(int i= 0; i < vrefs.length; i++) {
- consider(vrefs[i].getPart(false));
- }
- IEditorReference refs[]= page.getEditorReferences();
- for(int i= 0; i < refs.length; i++) {
- consider(refs[i].getPart(false));
- }
- }
-
- private void consider(IWorkbenchPart part) {
- if (part == null)
- return;
- ISetSelectionTarget target= null;
- if (!(part instanceof ISetSelectionTarget)) {
- target= (ISetSelectionTarget)part.getAdapter(ISetSelectionTarget.class);
- if (target == null)
- return;
- } else {
- target= (ISetSelectionTarget)part;
- }
- ISelectionProvider selectionProvider= part.getSite().getSelectionProvider();
- if (selectionProvider == null)
- return;
- ISelection s= selectionProvider.getSelection();
- if (!(s instanceof IStructuredSelection))
- return;
- IStructuredSelection selection= (IStructuredSelection)s;
- if (!selection.toList().contains(fElement))
- return;
- fParts.add(part);
- fSelections.add(selection);
- }
-
- public void restore(Object newElement) {
- if (fDisplay == null)
- return;
- for (int i= 0; i < fParts.size(); i++) {
- IStructuredSelection currentSelection= (IStructuredSelection)fSelections.get(i);
- boolean changed= false;
- final ISetSelectionTarget target= (ISetSelectionTarget)fParts.get(i);
- final IStructuredSelection[] newSelection= new IStructuredSelection[1];
- newSelection[0]= currentSelection;
- if (currentSelection instanceof TreeSelection) {
- TreeSelection treeSelection= (TreeSelection)currentSelection;
- TreePath[] paths= treeSelection.getPaths();
- for (int p= 0; p < paths.length; p++) {
- TreePath path= paths[p];
- if (path.getSegmentCount() > 0 && path.getLastSegment().equals(fElement)) {
- paths[p]= createTreePath(path, newElement);
- changed= true;
- }
- }
- if (changed) {
- newSelection[0]= new TreeSelection(paths, treeSelection.getElementComparer());
- }
- } else {
- Object[] elements= currentSelection.toArray();
- for (int e= 0; e < elements.length; e++) {
- if (elements[e].equals(fElement)) {
- elements[e]= newElement;
- changed= true;
- }
- }
- if (changed) {
- newSelection[0]= new StructuredSelection(elements);
- }
- }
- if (changed) {
- fDisplay.asyncExec(new Runnable() {
- public void run() {
- target.selectReveal(newSelection[0]);
- }
- });
- }
- }
- }
-
- // Method assumes that segment count of path > 0.
- private TreePath createTreePath(TreePath old, Object newElement) {
- int count= old.getSegmentCount();
- Object[] newObjects= new Object[count];
- for (int i= 0; i < count - 1; i++) {
- newObjects[i]= old.getSegment(i);
- }
- newObjects[count - 1]= newElement;
- return new TreePath(newObjects);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSourceFolderWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSourceFolderWizard.java
deleted file mode 100644
index 1a95fbbb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameSourceFolderWizard.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class RenameSourceFolderWizard extends RenameRefactoringWizard {
-
- public RenameSourceFolderWizard(Refactoring refactoring) {
- super(refactoring,
- RefactoringMessages.RenameSourceFolder_defaultPageTitle,
- RefactoringMessages.RenameSourceFolder_inputPage_description,
- JavaPluginImages.DESC_WIZBAN_REFACTOR,
- IJavaHelpContextIds.RENAME_SOURCE_FOLDER_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeParameterWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeParameterWizard.java
deleted file mode 100644
index 33bcc9dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeParameterWizard.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-/**
- * Wizard for the rename type parameter refactoring.
- */
-public final class RenameTypeParameterWizard extends RenameRefactoringWizard {
-
- /**
- * Creates a new rename type parameter wizard.
- *
- * @param refactoring
- * the refactoring to create the wizard for
- */
- public RenameTypeParameterWizard(Refactoring refactoring) {
- super(refactoring, RefactoringMessages.RenameTypeParameterWizard_defaultPageTitle, RefactoringMessages.RenameTypeParameterWizard_inputPage_description, JavaPluginImages.DESC_WIZBAN_REFACTOR, IJavaHelpContextIds.RENAME_TYPE_PARAMETER_WIZARD_PAGE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizard.java
deleted file mode 100644
index c0193313..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizard.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-/**
- * The type renaming wizard.
- */
-public class RenameTypeWizard extends RenameRefactoringWizard {
-
- public RenameTypeWizard(Refactoring refactoring) {
- this(refactoring, RefactoringMessages.RenameTypeWizard_defaultPageTitle, RefactoringMessages.RenameTypeWizardInputPage_description, JavaPluginImages.DESC_WIZBAN_REFACTOR_TYPE,
- IJavaHelpContextIds.RENAME_TYPE_WIZARD_PAGE);
- }
-
- public RenameTypeWizard(Refactoring refactoring, String defaultPageTitle, String inputPageDescription, ImageDescriptor inputPageImageDescriptor, String pageContextHelpId) {
- super(refactoring, defaultPageTitle, inputPageDescription, inputPageImageDescriptor, pageContextHelpId);
- }
-
- /*
- * non java-doc
- *
- * @see RefactoringWizard#addUserInputPages
- */
- protected void addUserInputPages() {
- super.addUserInputPages();
- if (isRenameType())
- addPage(new RenameTypeWizardSimilarElementsPage());
-
- }
-
- public RenameTypeProcessor getRenameTypeProcessor() {
- RefactoringProcessor proc= ((RenameRefactoring) getRefactoring()).getProcessor();
- if (proc instanceof RenameTypeProcessor)
- return (RenameTypeProcessor) proc;
- else if (proc instanceof RenameCompilationUnitProcessor) {
- RenameCompilationUnitProcessor rcu= (RenameCompilationUnitProcessor) proc;
- return rcu.getRenameTypeProcessor();
- }
- Assert.isTrue(false); // Should never get here
- return null;
- }
-
- protected boolean isRenameType() {
- return true;
- }
-
- protected RenameInputWizardPage createInputPage(String message, String initialSetting) {
- return new RenameTypeWizardInputPage(message, IJavaHelpContextIds.RENAME_TYPE_WIZARD_PAGE, true, initialSetting) {
-
- protected RefactoringStatus validateTextField(String text) {
- return validateNewName(text);
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java
deleted file mode 100644
index de516370..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ISimilarDeclarationUpdating;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.RowLayouter;
-
-/**
- * Wizard page for renaming a type (with similarly named elements)
- *
- *
- *
- */
-class RenameTypeWizardInputPage extends RenameInputWizardPage {
-
- private Button fUpdateSimilarElements;
- private int fSelectedStrategy;
-
- private Link fUpdateSimilarElementsButton;
-
- public RenameTypeWizardInputPage(String description, String contextHelpId, boolean isLastUserPage, String initialValue) {
- super(description, contextHelpId, isLastUserPage, initialValue);
- }
-
- protected void addAdditionalOptions(Composite composite, RowLayouter layouter) {
-
- if (getSimilarElementUpdating() == null || !getSimilarElementUpdating().canEnableSimilarDeclarationUpdating())
- return;
-
- try {
- fSelectedStrategy= getRefactoringSettings().getInt(RenameRefactoringWizard.TYPE_SIMILAR_MATCH_STRATEGY);
- } catch (NumberFormatException e) {
- fSelectedStrategy= getSimilarElementUpdating().getMatchStrategy();
- }
-
- getSimilarElementUpdating().setMatchStrategy(fSelectedStrategy);
-
- Composite c= new Composite(composite, SWT.NULL);
- GridLayout layout= new GridLayout(2, false);
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- c.setLayout(layout);
-
- fUpdateSimilarElements= new Button(c, SWT.CHECK);
- fUpdateSimilarElements.setText(RefactoringMessages.RenameTypeWizardInputPage_update_similar_elements);
-
- final boolean updateSimilarElements= getBooleanSetting(RenameRefactoringWizard.TYPE_UPDATE_SIMILAR_ELEMENTS, getSimilarElementUpdating().getUpdateSimilarDeclarations());
- fUpdateSimilarElements.setSelection(updateSimilarElements);
- getSimilarElementUpdating().setUpdateSimilarDeclarations(updateSimilarElements);
- fUpdateSimilarElements.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fUpdateSimilarElements.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- getSimilarElementUpdating().setUpdateSimilarDeclarations(fUpdateSimilarElements.getSelection());
- fUpdateSimilarElementsButton.setEnabled(fUpdateSimilarElements.getSelection());
- }
- });
-
- fUpdateSimilarElementsButton= new Link(c, SWT.NONE);
- GridData d= new GridData();
- d.grabExcessHorizontalSpace= true;
- d.horizontalAlignment= SWT.RIGHT;
- fUpdateSimilarElementsButton.setText(RefactoringMessages.RenameTypeWizardInputPage_update_similar_elements_configure);
- fUpdateSimilarElementsButton.setEnabled(updateSimilarElements);
- fUpdateSimilarElementsButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- RenameTypeWizardSimilarElementsOptionsDialog dialog= new RenameTypeWizardSimilarElementsOptionsDialog(getShell(), fSelectedStrategy);
- if (dialog.open() == Window.OK) {
- fSelectedStrategy= dialog.getSelectedStrategy();
- getSimilarElementUpdating().setMatchStrategy(fSelectedStrategy);
- }
- }
- });
- fUpdateSimilarElementsButton.setLayoutData(d);
-
- GridData forC= new GridData();
- forC.grabExcessHorizontalSpace= true;
- forC.horizontalAlignment= SWT.FILL;
- forC.horizontalSpan= 2;
- c.setLayoutData(forC);
-
- final Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layouter.perform(separator);
- }
-
- public void dispose() {
- if (saveSettings())
- if (fUpdateSimilarElements != null && !fUpdateSimilarElements.isDisposed() && fUpdateSimilarElements.isEnabled()) {
- saveBooleanSetting(RenameRefactoringWizard.TYPE_UPDATE_SIMILAR_ELEMENTS, fUpdateSimilarElements);
- getRefactoringSettings().put(RenameRefactoringWizard.TYPE_SIMILAR_MATCH_STRATEGY, fSelectedStrategy);
- }
-
- super.dispose();
- }
-
- /*
- * Override - we don't want to initialize the next page (may needlessly
- * trigger change creation if similar elements page is skipped, which is not
- * indicated by fIsLastUserInputPage in parent).
- */
- public boolean canFlipToNextPage() {
- return isPageComplete();
- }
-
- private ISimilarDeclarationUpdating getSimilarElementUpdating() {
- return (ISimilarDeclarationUpdating) getRefactoring().getAdapter(ISimilarDeclarationUpdating.class);
- }
-
- protected boolean performFinish() {
- boolean returner= super.performFinish();
- // check if we got deferred to the error page
- if (!returner && getContainer().getCurrentPage() != null)
- getContainer().getCurrentPage().setPreviousPage(this);
- return returner;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.ui.refactoring.UserInputWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- RenameTypeWizard wizard= (RenameTypeWizard) getWizard();
- IWizardPage nextPage;
-
- if (wizard.isRenameType()) {
- final RenameTypeProcessor renameTypeProcessor= wizard.getRenameTypeProcessor();
- try {
- getContainer().run(true, true, new IRunnableWithProgress() {
-
- public void run(IProgressMonitor pm) throws InterruptedException {
- try {
- renameTypeProcessor.initializeReferences(pm);
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.RenameTypeWizard_defaultPageTitle,
- RefactoringMessages.RenameTypeWizard_unexpected_exception);
- } finally {
- pm.done();
- }
- }
- });
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.RenameTypeWizard_defaultPageTitle,
- RefactoringMessages.RenameTypeWizard_unexpected_exception);
- } catch (InterruptedException e) {
- // user canceled
- return this;
- }
-
- if (renameTypeProcessor.hasSimilarElementsToRename()) {
- nextPage= super.getNextPage();
- } else {
- nextPage= computeSuccessorPage();
- }
-
- } else
- nextPage= computeSuccessorPage();
-
- nextPage.setPreviousPage(this);
- return nextPage;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java
deleted file mode 100644
index 6154e656..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamingNameSuggestor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-
-/**
- * Option dialog for selecting a similarly named element renaming strategy
- *
- *
- *
- */
-public class RenameTypeWizardSimilarElementsOptionsDialog extends MessageDialog {
-
- private SelectionButtonDialogField fExactStrategyRadio;
- private SelectionButtonDialogField fEmbeddedStrategyRadio;
- private SelectionButtonDialogField fSuffixStrategyRadio;
-
- private Label fWarningLabel;
- private Label fWarningImageLabel;
- private int fSelectedStrategy;
-
- public RenameTypeWizardSimilarElementsOptionsDialog(Shell parentShell, int defaultStrategy) {
- super(parentShell, RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_title, null, new String(), INFORMATION, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
- setShellStyle(getShellStyle() | SWT.RESIZE);
- fSelectedStrategy= defaultStrategy;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.dialogs.IconAndMessageDialog#createMessageArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createMessageArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite messageComposite= new Composite(parent, SWT.NONE);
- messageComposite.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- messageComposite.setLayout(layout);
- messageComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Label infoLabel= new Label(messageComposite, SWT.WRAP);
- infoLabel.setText(RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_select_strategy);
- GridData gd= new GridData(GridData.FILL, GridData.CENTER, true, false);
- gd.widthHint= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
- infoLabel.setLayoutData(gd);
- infoLabel.setFont(parent.getFont());
-
- int indent= convertWidthInCharsToPixels(3);
-
- fExactStrategyRadio= new SelectionButtonDialogField(SWT.RADIO);
- fExactStrategyRadio.setLabelText(RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_strategy_1);
- fExactStrategyRadio.doFillIntoGrid(messageComposite, 1);
- fExactStrategyRadio.setSelection(fSelectedStrategy == RenamingNameSuggestor.STRATEGY_EXACT);
- LayoutUtil.setHorizontalIndent(fExactStrategyRadio.getSelectionButton(null), indent);
-
- fEmbeddedStrategyRadio= new SelectionButtonDialogField(SWT.RADIO);
- fEmbeddedStrategyRadio.setLabelText(RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_strategy_2);
- fEmbeddedStrategyRadio.doFillIntoGrid(messageComposite, 1);
- fEmbeddedStrategyRadio.setSelection(fSelectedStrategy == RenamingNameSuggestor.STRATEGY_EMBEDDED);
- LayoutUtil.setHorizontalIndent(fEmbeddedStrategyRadio.getSelectionButton(null), indent);
-
- fSuffixStrategyRadio= new SelectionButtonDialogField(SWT.RADIO);
- fSuffixStrategyRadio.setLabelText(RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_strategy_3);
- fSuffixStrategyRadio.doFillIntoGrid(messageComposite, 1);
- fSuffixStrategyRadio.setSelection(fSelectedStrategy == RenamingNameSuggestor.STRATEGY_SUFFIX);
- LayoutUtil.setHorizontalIndent(fSuffixStrategyRadio.getSelectionButton(null), indent);
-
- final Composite warningComposite= new Composite(messageComposite, SWT.NONE);
- layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- warningComposite.setLayout(layout);
- warningComposite.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
- warningComposite.setFont(messageComposite.getFont());
-
- Image image= Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING);
- fWarningImageLabel= new Label(warningComposite, SWT.LEFT | SWT.WRAP);
- fWarningImageLabel.setImage(image);
- fWarningImageLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- fWarningLabel= new Label(warningComposite, SWT.WRAP);
- fWarningLabel.setText(RefactoringMessages.RenameTypeWizardSimilarElementsOptionsDialog_warning_short_names);
- GridData gridData= new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- gridData.widthHint= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
- fWarningLabel.setLayoutData(gridData);
- fWarningLabel.setFont(warningComposite.getFont());
-
- fExactStrategyRadio.setDialogFieldListener(new IDialogFieldListener() {
-
- public void dialogFieldChanged(DialogField field) {
- updateLabel();
- fSelectedStrategy= RenamingNameSuggestor.STRATEGY_EXACT;
- }
- });
-
- fEmbeddedStrategyRadio.setDialogFieldListener(new IDialogFieldListener() {
-
- public void dialogFieldChanged(DialogField field) {
- updateLabel();
- fSelectedStrategy= RenamingNameSuggestor.STRATEGY_EMBEDDED;
- }
- });
-
- fSuffixStrategyRadio.setDialogFieldListener(new IDialogFieldListener() {
-
- public void dialogFieldChanged(DialogField field) {
- updateLabel();
- fSelectedStrategy= RenamingNameSuggestor.STRATEGY_SUFFIX;
- }
- });
-
- updateLabel();
-
- return messageComposite;
- }
-
-
- protected boolean customShouldTakeFocus() {
- return true;
- }
-
- private void updateLabel() {
- fWarningImageLabel.setEnabled(!fExactStrategyRadio.isSelected());
- fWarningLabel.setEnabled(!fExactStrategyRadio.isSelected());
- }
-
- /**
- * @return one of the STRATEGY_* constants in {@link RenamingNameSuggestor}
- */
- public int getSelectedStrategy() {
- return fSelectedStrategy;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsPage.java
deleted file mode 100644
index 992f7090..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsPage.java
+++ /dev/null
@@ -1,778 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.custom.ViewForm;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-/**
- *
- * Wizard page for displaying a tree of similarly named elements renamed along with a
- * type.
- *
- *
- *
- */
-class RenameTypeWizardSimilarElementsPage extends UserInputWizardPage {
-
- public static class EditElementDialog extends StatusDialog implements IDialogFieldListener {
-
- private StringDialogField fNameField;
- private IJavaScriptElement fElementToEdit;
-
- public EditElementDialog(Shell parent, IJavaScriptElement elementToEdit, String newName) {
- super(parent);
- setTitle(RefactoringMessages.RenameTypeWizardSimilarElementsPage_change_element_name);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fElementToEdit= elementToEdit;
-
- fNameField= new StringDialogField();
- fNameField.setDialogFieldListener(this);
- fNameField.setLabelText(RefactoringMessages.RenameTypeWizardSimilarElementsPage_enter_new_name);
-
- fNameField.setText(newName);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- final Composite composite= (Composite) super.createDialogArea(parent);
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fNameField }, true, SWT.DEFAULT, SWT.DEFAULT);
- fNameField.postSetFocusOnDialogField(parent.getDisplay());
-
- LayoutUtil.setWidthHint(fNameField.getLabelControl(null), convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH));
- Text text= fNameField.getTextControl(null);
- LayoutUtil.setHorizontalGrabbing(text);
- TextFieldNavigationHandler.install(text);
-
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- if (field == fNameField)
- updateStatus(validateSettings());
- }
-
- private IStatus validateSettings() {
- final String name= fNameField.getText();
- if (name.length() == 0) {
- return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_empty);
- }
- IStatus status= JavaScriptConventions.validateIdentifier(name);
- if (status.matches(IStatus.ERROR))
- return status;
- if (!Checks.startsWithLowerCase(name))
- return new StatusInfo(IStatus.WARNING, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_should_start_lowercase);
-
- if (fElementToEdit instanceof IMember && ((IMember) fElementToEdit).getDeclaringType() != null) {
- IType type= ((IMember) fElementToEdit).getDeclaringType();
- if (fElementToEdit instanceof IField) {
- final IField f= type.getField(name);
- if (f.exists())
- return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_field_exists);
- }
- if (fElementToEdit instanceof IFunction) {
- final IFunction m= type.getFunction(name, ((IFunction) fElementToEdit).getParameterTypes());
- if (m.exists())
- return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_method_exists);
- }
- }
-
- // cannot check local variables; no .getLocalVariable(String) in IMember
-
- return StatusInfo.OK_STATUS;
- }
-
- public String getNewName() {
- return fNameField.getText();
- }
- }
-
- private static class SimilarElementTreeContentProvider implements ITreeContentProvider {
-
- private Map/* <IJavaScriptElement,Set<IJavaScriptElement>> */fTreeElementMap;
- private Set/* <IJavaScriptUnit> */fTopLevelElements;
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- final Set children= (Set) fTreeElementMap.get(parentElement);
- if (children != null)
- return children.toArray();
- else
- return new Object[0];
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- if (element instanceof IMember || element instanceof ILocalVariable) {
- return ((IJavaScriptElement) element).getParent();
- }
- if (element instanceof IJavaScriptUnit)
- return null;
- Assert.isTrue(false, "Should not get here"); //$NON-NLS-1$
- return null;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return fTreeElementMap.containsKey(element);
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- Assert.isTrue(inputElement == null || inputElement instanceof Map);
- return fTopLevelElements.toArray();
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- fTreeElementMap.clear();
- fTreeElementMap= null;
- fTopLevelElements= null;
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- Assert.isTrue(newInput == null || newInput instanceof Map);
- if (newInput == null)
- return;
- final Map similarElementsMap= (Map) newInput;
- final IJavaScriptElement[] similarElements= (IJavaScriptElement[]) similarElementsMap.keySet().toArray(new IJavaScriptElement[0]);
- fTreeElementMap= new HashMap();
- fTopLevelElements= new HashSet();
- for (int i= 0; i < similarElements.length; i++) {
- final IType declaring= (IType) similarElements[i].getAncestor(IJavaScriptElement.TYPE);
- if (similarElements[i] instanceof IMember) {
- // methods, fields, initializers, inner types
- addToMap(declaring, similarElements[i]);
- } else {
- // local variables
- final IJavaScriptElement parent= similarElements[i].getParent();
- if (parent instanceof IMember) {
- // parent is a method or an initializer
- addToMap(parent, similarElements[i]);
- addToMap(declaring, parent);
- }
- }
- handleDeclaring(declaring);
- }
- }
-
- private void handleDeclaring(final IJavaScriptElement someType) {
-
- final IJavaScriptElement enclosing= someType.getParent();
- if (enclosing instanceof IJavaScriptUnit) {
- fTopLevelElements.add(someType.getParent());
- addToMap(someType.getParent(), someType);
- } else {
- addToMap(enclosing, someType);
- handleDeclaring(enclosing);
- }
- }
-
- private void addToMap(final IJavaScriptElement key, final IJavaScriptElement element) {
- Set elements= (Set) fTreeElementMap.get(key);
- if (elements == null) {
- elements= new HashSet();
- fTreeElementMap.put(key, elements);
- }
- elements.add(element);
- }
-
- }
-
- private static class SimilarLabelProvider extends JavaScriptElementLabelProvider {
-
- private Map fDescriptorImageMap= new HashMap();
- private Map fElementToNewName;
-
- public SimilarLabelProvider() {
- super(JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_SMALL_ICONS);
- }
-
- public void initialize(Map elementToNewName) {
- this.fElementToNewName= elementToNewName;
- }
-
- public void dispose() {
- for (Iterator iter= fDescriptorImageMap.values().iterator(); iter.hasNext();) {
- Image image= (Image) iter.next();
- image.dispose();
- }
- super.dispose();
- }
-
- private Image manageImageDescriptor(ImageDescriptor descriptor) {
- Image image= (Image) fDescriptorImageMap.get(descriptor);
- if (image == null) {
- image= descriptor.createImage();
- fDescriptorImageMap.put(descriptor, image);
- }
- return image;
- }
-
- public Image getImage(Object element) {
- if (isSimilarElement(element))
- return manageImageDescriptor(JavaPluginImages.DESC_OBJS_DEFAULT_CHANGE);
- return super.getImage(element);
- }
-
- public Image getJavaImage(Object element) {
- return super.getImage(element);
- }
-
- public String getText(Object element) {
- if (isSimilarElement(element)) {
- return Messages.format(RefactoringMessages.RenameTypeWizardSimilarElementsPage_rename_to, new String[] { super.getText(element), (String)fElementToNewName.get(element) } );
- }
- return super.getText(element);
- }
-
- private boolean isSimilarElement(Object element) {
- return fElementToNewName.containsKey(element);
- }
-
- }
-
- private static class SimilarElementComparator extends JavaScriptElementComparator {
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.JavaElementSorter#category(java.lang.Object)
- */
- public int category(Object element) {
-
- /*
- * We'd like to present the elements in the same order as they
- * appear in the source. This can be achieved by assigning a
- * distinct category to every element; the category being derived
- * from the source position of the element.
- */
-
- ISourceRange sourceRange= null;
- if (element instanceof IMember) {
- IMember member= (IMember) element;
- try {
- sourceRange= member.getNameRange();
- } catch (JavaScriptModelException e) {
- // fall through
- }
- }
- if (element instanceof ILocalVariable) {
- ILocalVariable var= (ILocalVariable) element;
- sourceRange= var.getNameRange();
- }
-
- if (sourceRange != null)
- return 100 + sourceRange.getOffset(); // +100: safe distance from all other categories.
-
- return super.category(element);
- }
- }
-
- public static final String PAGE_NAME= "SimilarElementSelectionPage"; //$NON-NLS-1$
-
- private final long LABEL_FLAGS= JavaScriptElementLabels.DEFAULT_QUALIFIED | JavaScriptElementLabels.ROOT_POST_QUALIFIED | JavaScriptElementLabels.APPEND_ROOT_PATH | JavaScriptElementLabels.M_PARAMETER_TYPES
- | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_APP_RETURNTYPE | JavaScriptElementLabels.M_EXCEPTIONS | JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.T_TYPE_PARAMETERS;
-
- private Label fSimilarElementsLabel;
- private SourceViewer fSourceViewer;
- private ContainerCheckedTreeViewer fTreeViewer;
- private SimilarLabelProvider fTreeViewerLabelProvider;
- private Map fSimilarElementsToNewName;
- private Button fEditElementButton;
- private boolean fWasInitialized;
- private CLabel fCurrentElementLabel;
-
- public RenameTypeWizardSimilarElementsPage() {
- super(PAGE_NAME);
- }
-
- // --- UI creation
-
- public void createControl(Composite parent) {
-
- ViewForm viewForm= new ViewForm(parent, SWT.BORDER | SWT.FLAT);
-
- Composite inner= new Composite(viewForm, SWT.NULL);
- GridLayout layout= new GridLayout();
- inner.setLayout(layout);
-
- createTreeAndSourceViewer(inner);
- createButtonComposite(inner);
- viewForm.setContent(inner);
-
- setControl(viewForm);
-
- Dialog.applyDialogFont(viewForm);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.RENAME_TYPE_WIZARD_PAGE);
- }
-
- private void createTreeAndSourceViewer(Composite superComposite) {
- SashForm composite= new SashForm(superComposite, SWT.HORIZONTAL);
- initializeDialogUnits(superComposite);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= convertHeightInCharsToPixels(20);
- gd.widthHint= convertWidthInCharsToPixels(10);
- composite.setLayoutData(gd);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- createSimilarElementTreeComposite(composite);
- createSourceViewerComposite(composite);
- composite.setWeights(new int[] { 50, 50 });
- }
-
- private void createSimilarElementTreeComposite(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- composite.setLayout(layout);
-
- createTypeHierarchyLabel(composite);
- createTreeViewer(composite);
- }
-
- private void createTypeHierarchyLabel(Composite composite) {
- fSimilarElementsLabel= new Label(composite, SWT.WRAP);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint= JavaElementImageProvider.SMALL_SIZE.x;
- fSimilarElementsLabel.setLayoutData(gd);
- fSimilarElementsLabel.setText(RefactoringMessages.RenameTypeWizardSimilarElementsPage_review_similar_elements);
- }
-
- private void createTreeViewer(Composite composite) {
- Tree tree= new Tree(composite, SWT.CHECK | SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL);
- tree.setLayoutData(new GridData(GridData.FILL_BOTH));
- fTreeViewer= new ContainerCheckedTreeViewer(tree);
- fTreeViewer.setUseHashlookup(true);
- fTreeViewer.setComparator(new SimilarElementComparator());
- fTreeViewer.setContentProvider(new SimilarElementTreeContentProvider());
- fTreeViewerLabelProvider= new SimilarLabelProvider();
- fTreeViewer.setLabelProvider(fTreeViewerLabelProvider);
- fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(SelectionChangedEvent event) {
- RenameTypeWizardSimilarElementsPage.this.treeViewerSelectionChanged(event);
- }
- });
- fTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(DoubleClickEvent event) {
- RenameTypeWizardSimilarElementsPage.this.editCurrentElement();
- }
- });
- }
-
- private void createSourceViewerComposite(Composite parent) {
- Composite c= new Composite(parent, SWT.NONE);
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- c.setLayout(layout);
-
- createSourceViewerLabel(c);
- createSourceViewer(c);
- }
-
- private void createSourceViewerLabel(Composite c) {
- fCurrentElementLabel= new CLabel(c, SWT.NONE);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint= JavaElementImageProvider.SMALL_SIZE.x;
- fCurrentElementLabel.setText(RefactoringMessages.RenameTypeWizardSimilarElementsPage_select_element_to_view_source);
- fCurrentElementLabel.setLayoutData(gd);
- }
-
- private void createSourceViewer(Composite c) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fSourceViewer= new JavaSourceViewer(c, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION, store);
- fSourceViewer.configure(new JavaScriptSourceViewerConfiguration(getJavaTextTools().getColorManager(), store, null, null));
- fSourceViewer.setEditable(false);
- fSourceViewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
- fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
- Document document= new Document();
- getJavaTextTools().setupJavaDocumentPartitioner(document);
- fSourceViewer.setDocument(document);
- }
-
- private static JavaScriptTextTools getJavaTextTools() {
- return JavaScriptPlugin.getDefault().getJavaTextTools();
- }
-
- private void createButtonComposite(Composite superComposite) {
- Composite buttonComposite= new Composite(superComposite, SWT.NONE);
- buttonComposite.setLayoutData(new GridData());
- GridLayout layout= new GridLayout(2, false);
- layout.marginWidth= 0;
- buttonComposite.setLayout(layout);
-
- Button returnToDefaults= new Button(buttonComposite, SWT.PUSH);
- returnToDefaults.setText(RefactoringMessages.RenameTypeWizardSimilarElementsPage_restore_defaults);
- returnToDefaults.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(returnToDefaults);
- returnToDefaults.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- RenameTypeWizardSimilarElementsPage.this.resetDataInRefAndUI();
- }
- });
- fEditElementButton= new Button(buttonComposite, SWT.PUSH);
- fEditElementButton.setText(RefactoringMessages.RenameTypeWizardSimilarElementsPage_change_name);
- fEditElementButton.setLayoutData(new GridData());
- fEditElementButton.setEnabled(false);
- SWTUtil.setButtonDimensionHint(fEditElementButton);
- fEditElementButton.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- RenameTypeWizardSimilarElementsPage.this.editCurrentElement();
- }
- });
- }
-
-
- // ---------------------- Acting
-
- public void setVisible(boolean visible) {
- if (visible) {
- initializeUIFromRef();
- }
- super.setVisible(visible);
- selectFirstElement();
- }
-
- private void selectFirstElement() {
- if (fTreeViewer.getTree().getItemCount() > 0) {
- TreeItem item= fTreeViewer.getTree().getItem(0);
- if (item.getData() != null) {
- fTreeViewer.reveal(item.getData());
- Object data= getFirstSimilarElement(item);
- if (data != null) {
- fTreeViewer.setSelection(new StructuredSelection(data));
- }
- }
- }
- fTreeViewer.getTree().setFocus();
- }
-
- private Object getFirstSimilarElement(TreeItem item) {
- Object data= item.getData();
- if (isSimilarElement(data)) {
- return data;
- } else {
- TreeItem[] children= item.getItems();
- for (int i= 0; i < children.length; i++) {
- Object childData= getFirstSimilarElement(children[i]);
- if (childData != null)
- return childData;
- }
- }
- return null;
- }
-
- private void initializeUIFromRef() {
- // Get data from the refactoring
- final Map elementsToNewNames= getRenameTypeProcessor().getSimilarElementsToNewNames();
- try {
- // To prevent flickering, stop redrawing
- getShell().setRedraw(false);
- if (fSimilarElementsToNewName == null || elementsToNewNames != fSimilarElementsToNewName) {
- fSimilarElementsToNewName= elementsToNewNames;
- fTreeViewerLabelProvider.initialize(fSimilarElementsToNewName);
- fTreeViewer.setInput(fSimilarElementsToNewName);
- }
- fTreeViewer.expandAll();
- restoreSelectionAndNames(getRenameTypeProcessor().getSimilarElementsToSelection());
- } finally {
- getShell().setRedraw(true);
- }
- fWasInitialized= true;
- }
-
- private void initializeRefFromUI() {
- IJavaScriptElement[] selected= getCheckedSimilarElements();
- Map selection= getRenameTypeProcessor().getSimilarElementsToSelection();
- for (Iterator iter= selection.keySet().iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- selection.put(element, Boolean.FALSE);
- }
- for (int i= 0; i < selected.length; i++)
- selection.put(selected[i], Boolean.TRUE);
-
- }
-
- private void resetDataInRefAndUI() {
- getRenameTypeProcessor().resetSelectedSimilarElements();
- restoreSelectionAndNames(getRenameTypeProcessor().getSimilarElementsToSelection());
- }
-
- protected void editCurrentElement() {
- IStructuredSelection selection= (IStructuredSelection) fTreeViewer.getSelection();
- if ( (selection != null) && isSimilarElement(selection.getFirstElement())) {
- IJavaScriptElement element= (IJavaScriptElement) selection.getFirstElement();
- String newName= (String) fSimilarElementsToNewName.get(element);
- if (newName == null)
- return;
- EditElementDialog dialog= new EditElementDialog(getShell(), element, newName);
- if (dialog.open() == Window.OK) {
- String changedName= dialog.getNewName();
- if (!changedName.equals(newName)) {
- fSimilarElementsToNewName.put(element, changedName);
- fTreeViewer.update(element, null);
- }
- }
- }
- }
-
- private void restoreSelectionAndNames(final Map selection) {
- final Map selectedElements= selection;
- for (Iterator iter= selectedElements.keySet().iterator(); iter.hasNext();) {
- IJavaScriptElement element= (IJavaScriptElement) iter.next();
- boolean isSelected= ((Boolean) selectedElements.get(element)).booleanValue();
- fTreeViewer.setChecked(element, isSelected);
- fTreeViewer.update(element, null);
- }
- }
-
- // ------------ Navigation
-
- /*
- * @see IWizardPage#getNextPage()
- */
- public IWizardPage getNextPage() {
- if (fWasInitialized)
- initializeRefFromUI();
- // computes the input successor page
- // (=create changes)
- IWizardPage nextPage= super.getNextPage();
- if (nextPage != this) // if user pressed cancel, then the next page is the current page
- nextPage.setPreviousPage(this);
- return nextPage;
- }
-
-
- /*
- * @see IWizardPage#getPreviousPage()
- */
- public IWizardPage getPreviousPage() {
- if (fWasInitialized)
- initializeRefFromUI();
- return super.getPreviousPage();
- }
-
- /*
- * @see RefactoringWizardPage#performFinish()
- */
- protected boolean performFinish() {
- initializeRefFromUI();
- return super.performFinish();
- }
-
- // ------------ Helper
-
- private boolean isSimilarElement(Object element) {
- if (!fWasInitialized)
- return false;
-
- return fSimilarElementsToNewName.containsKey(element);
- }
-
- private void treeViewerSelectionChanged(SelectionChangedEvent event) {
- try {
- final IJavaScriptElement selection= getFirstSelectedSourceReference(event);
- setSourceViewerContents(selection);
- fEditElementButton.setEnabled(selection != null && (isSimilarElement(selection)));
- fCurrentElementLabel.setText(selection != null ? JavaScriptElementLabels.getElementLabel(selection, LABEL_FLAGS) : RefactoringMessages.RenameTypeWizardSimilarElementsPage_select_element_to_view_source);
- fCurrentElementLabel.setImage(selection != null ? fTreeViewerLabelProvider.getJavaImage(selection) : null);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.RenameTypeWizard_defaultPageTitle, RefactoringMessages.RenameTypeWizard_unexpected_exception);
- }
- }
-
- private IJavaScriptElement getFirstSelectedSourceReference(SelectionChangedEvent event) {
- ISelection s= event.getSelection();
- if (! (s instanceof IStructuredSelection))
- return null;
- IStructuredSelection strSel= (IStructuredSelection) s;
- if (strSel.size() != 1)
- return null;
- Object first= strSel.getFirstElement();
- if (! (first instanceof IJavaScriptElement))
- return null;
- return (IJavaScriptElement) first;
- }
-
- private void setSourceViewerContents(IJavaScriptElement el) throws JavaScriptModelException {
- String EMPTY= ""; //$NON-NLS-1$
- if (el == null) {
- fSourceViewer.getDocument().set(EMPTY);
- return;
- }
- IJavaScriptUnit element= (IJavaScriptUnit) el.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (element == null) {
- fSourceViewer.getDocument().set(EMPTY);
- return;
- }
-
- String contents= element.getSource();
- try {
- fSourceViewer.setRedraw(false);
- fSourceViewer.getDocument().set(contents == null ? EMPTY : contents);
- ISourceRange sr= getNameRange(el);
- if (sr != null) {
- fSourceViewer.setSelectedRange(sr.getOffset(), sr.getLength());
- }
- } finally {
- fSourceViewer.setRedraw(true);
- }
- }
-
- private ISourceRange getNameRange(IJavaScriptElement element) throws JavaScriptModelException {
- if (element instanceof IMember)
- return ((IMember) element).getNameRange();
- else if (element instanceof ILocalVariable)
- return ((ILocalVariable) element).getNameRange();
- else
- return null;
- }
-
- private IJavaScriptElement[] getCheckedSimilarElements() {
- Object[] checked= fTreeViewer.getCheckedElements();
- List elements= new ArrayList(checked.length);
- for (int i= 0; i < checked.length; i++) {
- if (isSimilarElement(checked[i]))
- elements.add(checked[i]);
- }
- return (IJavaScriptElement[]) elements.toArray(new IJavaScriptElement[elements.size()]);
- }
-
- public RenameTypeProcessor getRenameTypeProcessor() {
- RefactoringProcessor proc= ((RenameRefactoring) getRefactoring()).getProcessor();
- if (proc instanceof RenameTypeProcessor)
- return (RenameTypeProcessor) proc;
- else if (proc instanceof RenameCompilationUnitProcessor) {
- RenameCompilationUnitProcessor rcu= (RenameCompilationUnitProcessor) proc;
- return rcu.getRenameTypeProcessor();
- }
- Assert.isTrue(false); // Should never get here
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceManager.java
deleted file mode 100644
index 53e9ccfc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceManager.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameJavaProjectProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameLocalVariableProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameResourceProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameSourceFolderProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceManager;
-
-public class RenameUserInterfaceManager extends UserInterfaceManager {
- private static final UserInterfaceManager fgInstance= new RenameUserInterfaceManager();
-
- public static UserInterfaceManager getDefault() {
- return fgInstance;
- }
-
- private RenameUserInterfaceManager() {
- put(RenameResourceProcessor.class, RenameUserInterfaceStarter.class, RenameResourceWizard.class);
-
- put(RenameJavaProjectProcessor.class, RenameUserInterfaceStarter.class, RenameJavaProjectWizard.class);
- put(RenameSourceFolderProcessor.class, RenameUserInterfaceStarter.class, RenameSourceFolderWizard.class);
- put(RenamePackageProcessor.class, RenameUserInterfaceStarter.class, RenamePackageWizard.class);
- put(RenameCompilationUnitProcessor.class, RenameUserInterfaceStarter.class, RenameCuWizard.class);
- put(RenameTypeProcessor.class, RenameUserInterfaceStarter.class, RenameTypeWizard.class);
- put(RenameFieldProcessor.class, RenameUserInterfaceStarter.class, RenameFieldWizard.class);
- put(RenameNonVirtualMethodProcessor.class, RenameMethodUserInterfaceStarter.class, RenameMethodWizard.class);
- put(RenameVirtualMethodProcessor.class, RenameMethodUserInterfaceStarter.class, RenameMethodWizard.class);
- put(RenameLocalVariableProcessor.class, RenameUserInterfaceStarter.class, RenameLocalVariableWizard.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceStarter.java
deleted file mode 100644
index 8eae3ed1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameUserInterfaceStarter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceStarter;
-
-public class RenameUserInterfaceStarter extends UserInterfaceStarter {
-
- public boolean activate(Refactoring refactoring, Shell parent, int saveMode) throws CoreException {
- RenameProcessor processor= (RenameProcessor)refactoring.getAdapter(RenameProcessor.class);
- Object[] elements= processor.getElements();
- RenameSelectionState state= elements.length == 1 ? new RenameSelectionState(elements[0]) : null;
- boolean executed= super.activate(refactoring, parent, saveMode);
- INameUpdating nameUpdating= (INameUpdating)refactoring.getAdapter(INameUpdating.class);
- if (executed && nameUpdating != null && state != null) {
- Object newElement= nameUpdating.getNewElement();
- if (newElement != null) {
- state.restore(newElement);
- }
- }
- return executed;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyAction.java
deleted file mode 100644
index 7a60a5a0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyAction.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.CopyProjectAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-
-public class ReorgCopyAction extends SelectionDispatchAction {
-
- public ReorgCopyAction(IWorkbenchSite site) {
- super(site);
- setText(ReorgMessages.ReorgCopyAction_3);
- setDescription(ReorgMessages.ReorgCopyAction_4);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.COPY_ACTION);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- if (!selection.isEmpty()) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())) {
- setEnabled(createWorkbenchAction(selection).isEnabled());
- return;
- }
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (elements.size() != resources.length + javaElements.length)
- setEnabled(false);
- else
- setEnabled(RefactoringAvailabilityTester.isCopyAvailable(resources, javaElements));
- } catch (JavaScriptModelException e) {
- // no ui here - this happens on selection changes
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- } else
- setEnabled(false);
- }
-
- private CopyProjectAction createWorkbenchAction(IStructuredSelection selection) {
- CopyProjectAction action= new CopyProjectAction(getShell());
- action.selectionChanged(selection);
- return action;
- }
-
- public void run(IStructuredSelection selection) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())){
- createWorkbenchAction(selection).run();
- return;
- }
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (RefactoringAvailabilityTester.isCopyAvailable(resources, javaElements))
- RefactoringExecutionStarter.startCopyRefactoring(resources, javaElements, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyStarter.java
deleted file mode 100644
index fad72a3b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyStarter.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-
-public class ReorgCopyStarter {
-
- public static ReorgCopyStarter create(IJavaScriptElement[] javaElements, IResource[] resources, IJavaScriptElement destination) throws JavaScriptModelException {
- Assert.isNotNull(javaElements);
- Assert.isNotNull(resources);
- Assert.isNotNull(destination);
- ICopyPolicy copyPolicy= ReorgPolicyFactory.createCopyPolicy(resources, javaElements);
- if (!copyPolicy.canEnable())
- return null;
- JavaCopyProcessor copyProcessor= new JavaCopyProcessor(copyPolicy);
- if (!copyProcessor.setDestination(destination).isOK())
- return null;
- return new ReorgCopyStarter(copyProcessor);
- }
-
- public static ReorgCopyStarter create(IJavaScriptElement[] javaElements, IResource[] resources, IResource destination) throws JavaScriptModelException {
- Assert.isNotNull(javaElements);
- Assert.isNotNull(resources);
- Assert.isNotNull(destination);
- ICopyPolicy copyPolicy= ReorgPolicyFactory.createCopyPolicy(resources, javaElements);
- if (!copyPolicy.canEnable())
- return null;
- JavaCopyProcessor copyProcessor= new JavaCopyProcessor(copyPolicy);
- if (!copyProcessor.setDestination(destination).isOK())
- return null;
- return new ReorgCopyStarter(copyProcessor);
- }
-
- private final JavaCopyProcessor fCopyProcessor;
-
- private ReorgCopyStarter(JavaCopyProcessor copyProcessor) {
- Assert.isNotNull(copyProcessor);
- fCopyProcessor= copyProcessor;
- }
-
- public void run(Shell parent) throws InterruptedException, InvocationTargetException {
- IRunnableContext context= new ProgressMonitorDialog(parent);
- fCopyProcessor.setNewNameQueries(new NewNameQueries(parent));
- fCopyProcessor.setReorgQueries(new ReorgQueries(parent));
- new RefactoringExecutionHelper(new JavaCopyRefactoring(fCopyProcessor), RefactoringCore.getConditionCheckingFailedSeverity(), RefactoringSaveHelper.SAVE_NOTHING, parent, context).perform(false, false);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyWizard.java
deleted file mode 100644
index b512fbbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgCopyWizard.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgDestinationValidator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-
-
-public class ReorgCopyWizard extends RefactoringWizard {
-
- public ReorgCopyWizard(CopyRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | NO_PREVIEW_PAGE);
- setDefaultPageTitle(ReorgMessages.ReorgCopyWizard_1);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringWizard#addUserInputPages()
- */
- protected void addUserInputPages() {
- addPage(new CopyInputPage());
- }
-
- private static class CopyInputPage extends ReorgUserInputPage{
-
- private static final String PAGE_NAME= "CopyInputPage"; //$NON-NLS-1$
-
- public CopyInputPage() {
- super(PAGE_NAME);
- }
-
- private JavaCopyProcessor getCopyProcessor(){
- return (JavaCopyProcessor)((CopyRefactoring)getRefactoring()).getCopyProcessor();
- }
-
- protected Object getInitiallySelectedElement() {
- return getCopyProcessor().getCommonParentForInputElements();
- }
-
- protected IJavaScriptElement[] getJavaElements() {
- return getCopyProcessor().getJavaElements();
- }
-
- protected IResource[] getResources() {
- return getCopyProcessor().getResources();
- }
-
- protected IReorgDestinationValidator getDestinationValidator() {
- return getCopyProcessor();
- }
-
- protected RefactoringStatus verifyDestination(Object selected) throws JavaScriptModelException{
- if (selected instanceof IJavaScriptElement)
- return getCopyProcessor().setDestination((IJavaScriptElement)selected);
- if (selected instanceof IResource)
- return getCopyProcessor().setDestination((IResource)selected);
- return RefactoringStatus.createFatalErrorStatus(ReorgMessages.ReorgCopyWizard_2);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.java
deleted file mode 100644
index 0d103669..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class ReorgMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgMessages";//$NON-NLS-1$
-
- private ReorgMessages() {
- // Do not instantiate
- }
-
- public static String CutAction_text;
- public static String copyAction_description;
- public static String copyAction_destination_label;
- public static String copyAction_name;
- public static String deleteAction_checkDeletion;
- public static String deleteAction_confirm_title;
- public static String deleteAction_confirmReadOnly;
- public static String deleteAction_description;
- public static String DestinationRenderer_packages;
- public static String moveAction_checkMove;
- public static String moveAction_error_readOnly;
- public static String moveAction_label;
- public static String moveAction_name;
- public static String moveAction_destination_label;
- public static String PasteAction_projectName;
- public static String RenameInformationPopup_delayJobName;
- public static String RenameInformationPopup_EnterNewName;
- public static String RenameInformationPopup_menu;
- public static String RenameInformationPopup_OpenDialog;
- public static String RenameInformationPopup_preferences;
- public static String RenameInformationPopup_Preview;
- public static String RenameInformationPopup_RenameInWorkspace;
- public static String RenameInformationPopup_snap_bottom_right;
- public static String RenameInformationPopup_snap_over_left;
- public static String RenameInformationPopup_snap_over_right;
- public static String RenameInformationPopup_snap_under_left;
- public static String RenameInformationPopup_snap_under_right;
- public static String RenameInformationPopup_SnapTo;
- public static String RenameLinkedMode_error_saving_editor;
- public static String ReorgAction_checkSaveTargets;
- public static String ReorgAction_checkSaveTargets_title;
- public static String ReorgAction_exception_saving;
- public static String ReorgAction_task_saving;
- public static String ReorgAction_exception;
- public static String ReorgAction_reorganize;
- public static String CopyResourcesToClipboardAction_copy;
- public static String CutSourceReferencesToClipboardAction_cut;
- public static String DeleteResourceAction_delete;
- public static String DeleteResourceAction_exception;
- public static String PasteSourceReferencesFromClipboardAction_paste1;
- public static String PasteSourceReferencesFromClipboardAction_exception;
- public static String ReorgExceptionHandler_see_details;
- public static String ReorgGroup_copy;
- public static String ReorgGroup_paste;
- public static String ReorgGroup_pasteAction_description;
- public static String ReorgGroup_delete;
- public static String SourceReferenceAction_exception;
- public static String JdtCopyAction_referenced;
- public static String JdtCopyAction_update_classpath;
- public static String JdtCopyAction_Copy;
- public static String JdtMoveAction_move;
- public static String JdtMoveAction_update_references;
- public static String JdtMoveAction_preview;
- public static String JdtMoveAction_exception;
- public static String JdtMoveAction_referenced;
- public static String JdtMoveAction_update_classpath;
- public static String JdtMoveAction_Move;
- public static String JdtMoveAction_default_package_warning;
- public static String DeleteSourceReferencesAction_delete_elements;
- public static String DeleteSourceReferencesAction_exception;
- public static String DeleteSourceReferencesAction_delete1;
- public static String DeleteSourceReferencesAction_confirm_gs_delete;
- public static String DeleteSourceReferencesAction_delete_gs;
- public static String DeleteSourceReferencesAction_title;
- public static String DeleteSourceReferencesAction_read_only;
- public static String DeleteSourceReferencesAction_cu_read_only;
- public static String DeleteSourceReferencesAction_cu_empty;
- public static String DeleteSourceReferencesAction_cus_empty;
- public static String ReorgDestinationAction_duplicate_name;
- public static String ReorgDestinationAction_error;
- public static String ReorgDestinationAction_exception;
- public static String ReorgDestinationAction_duplicate;
- public static String ReorgDestinationAction_exception_title;
- public static String ReorgDestinationAction_error_occurred;
- public static String ReorgQueries_enterNewNameQuestion;
- public static String ReorgQueries_nameConflictMessage;
- public static String ReorgQueries_resourceWithThisNameAlreadyExists;
- public static String ReorgQueries_invalidNameMessage;
- public static String ReorgQueries_packagewithThatNameexistsMassage;
- public static String ReorgQueries_resourceExistsWithDifferentCaseMassage;
- public static String ReorgQueries_Confirm_Overwritting;
- public static String ReorgQueries_exists_read_only;
- public static String ReorgQueries_exists;
- public static String ReorgQueries_skip_all;
- public static String CopyToClipboardProblemDialog_title;
- public static String CopyToClipboardProblemDialog_message;
- public static String PasteResourcesFromClipboardAction_error_title;
- public static String PasteResourcesFromClipboardAction_error_message;
- public static String ReorgExceptionHandler_error_title;
- public static String ReorgExceptionHandler_error_message;
- public static String DeleteSourceReferencesAction_sure;
- public static String DeleteSourceReferencesAction_sure_elements;
- public static String DeleteSourceReferenceAction_error_title;
- public static String DeleteSourceReferenceAction_error_message;
- public static String DeleteSourceReferenceAction_deleting;
- public static String DeleteResourcesAction_deleteAction_confirm_message;
- public static String DeleteResourcesAction_Delete;
- public static String DeleteResourcesAction_sure_delete;
- public static String DeleteResourcesAction_sure_delete_resources;
- public static String DeleteResourcesAction_default_package;
- public static String DeleteResourcesAction_referenced;
- public static String DeleteResourcesAction_sure_delete_linked_single;
- public static String DeleteResourcesAction_sure_delete_linked_single_package_or_pfr;
- public static String DeleteResourcesAction_sure_delete_linked_multiple;
- public static String DeleteResourcesAction_sure_delete_linked_multiple_with_packages_or_pfr;
- public static String CopyToClipboardAction_0;
- public static String CopyToClipboardAction_1;
- public static String CopyToClipboardAction_2;
- public static String CopyToClipboardAction_3;
- public static String CopyToClipboardAction_4;
- public static String CopyToClipboardAction_5;
- public static String DeleteAction_3;
- public static String DeleteAction_4;
- public static String NewNameQueries_21;
- public static String NewNameQueries_22;
- public static String ReorgCopyAction_3;
- public static String ReorgCopyAction_4;
- public static String ReorgCopyWizard_1;
- public static String ReorgCopyWizard_2;
- public static String ReorgMoveAction_3;
- public static String ReorgMoveAction_4;
- public static String ReorgMoveWizard_3;
- public static String ReorgMoveWizard_4;
- public static String ReorgMoveWizard_textual_move;
- public static String ReorgMoveWizard_newPackage;
- public static String ReorgUserInputPage_choose_destination_single;
- public static String ReorgUserInputPage_choose_destination_multi;
- public static String RenameMethodUserInterfaceStarter_name;
- public static String RenameMethodUserInterfaceStarter_message;
- public static String PasteAction_4;
- public static String PasteAction_5;
- public static String PasteAction_change_name;
- public static String PasteAction_edit_name;
- public static String PasteAction_element_doesnot_exist;
- public static String PasteAction_invalid_destination;
- public static String PasteAction_name;
- public static String PasteAction_wrong_destination;
- public static String PasteAction_TextPaster_exists;
- public static String PasteAction_TextPaster_confirmOverwriting;
- public static String PasteAction_cannot_selection;
- public static String PasteAction_cannot_no_selection;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, ReorgMessages.class);
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties
deleted file mode 100644
index 6afcbb54..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties
+++ /dev/null
@@ -1,176 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-CutAction_text=Cu&t
-
-copyAction_description=Copy the selected elements
-copyAction_destination_label=&Select the copy destination
-copyAction_name=Copy
-
-deleteAction_checkDeletion=Check Deletion
-deleteAction_confirm_title=Confirm Delete
-deleteAction_confirmReadOnly=The selected elements contain read-only resources. Do you still want to delete them?
-deleteAction_description=Delete the selected elements
-DestinationRenderer_packages=packages
-
-moveAction_checkMove=Check Move
-moveAction_error_readOnly=The selected elements contain read-only resources. Do you still want to move them?
-moveAction_label=Mo&ve...
-moveAction_name=Move
-moveAction_destination_label=&Select the move destination:
-
-ReorgAction_checkSaveTargets=These elements contain unsaved changes.\nCheck the elements you want to save before proceeding.
-ReorgAction_checkSaveTargets_title=Save Resources
-ReorgAction_exception_saving=An exception occurred while saving editor contents.
-ReorgAction_task_saving=Saving
-ReorgAction_exception=Unexpected exception. See log for details
-ReorgAction_reorganize=Reorganize
-
-CopyResourcesToClipboardAction_copy=&Copy
-
-CutSourceReferencesToClipboardAction_cut=Cu&t
-
-DeleteResourceAction_delete=Delete
-DeleteResourceAction_exception=Unexpected exception. See log for details
-
-PasteSourceReferencesFromClipboardAction_paste1=Paste
-PasteSourceReferencesFromClipboardAction_exception=Unexpected exception. See log for details
-
-ReorgExceptionHandler_see_details=See details
-ReorgGroup_copy=&Copy
-ReorgGroup_paste=&Paste
-ReorgGroup_pasteAction_description=Pastes elements from the clipboard
-ReorgGroup_delete=&Delete
-
-SourceReferenceAction_exception=Unexpected exception. See log for details
-
-JdtCopyAction_referenced=Source Folder ''{0}'' is referenced by other projects.
-JdtCopyAction_update_classpath=Do you want to update includepath of the other projects?
-JdtCopyAction_Copy=Copy
-
-JdtMoveAction_move=Move
-JdtMoveAction_update_references=Update &references to the moved element(s)
-JdtMoveAction_preview=Preview...
-JdtMoveAction_exception=Unexpected exception occurred. See log for details
-JdtMoveAction_referenced=Source Folder root ''{0}'' is referenced by other projects.
-JdtMoveAction_update_classpath=Do you want to update includepath of the other projects?
-JdtMoveAction_Move=Move
-JdtMoveAction_default_package_warning=Moving JavaScript files to or from the default package will not update references.
-
-DeleteSourceReferencesAction_delete_elements=Delete elements
-DeleteSourceReferencesAction_exception=Unexpected exception. See log for details
-DeleteSourceReferencesAction_delete1=Delete
-DeleteSourceReferencesAction_confirm_gs_delete=Confirm Delete of Getters/Setters
-DeleteSourceReferencesAction_delete_gs=Do you also want to delete getters/setters for the selected vars?
-DeleteSourceReferencesAction_title=Delete
-DeleteSourceReferencesAction_read_only=Cannot delete. All selected elements are defined in read-only files.
-DeleteSourceReferencesAction_cu_read_only=JavaScript file ''{0}'' is read-only. Do you still want to delete it?
-DeleteSourceReferencesAction_cu_empty=After the delete operation the JavaScript file ''{0}'' contains no types. \nOK to delete this JavaScript file?
-DeleteSourceReferencesAction_cus_empty=After the delete operation {0} JavaScript files contain no types. \nOK to delete these JavaScript files?
-
-ReorgDestinationAction_duplicate_name=Duplicate Element Name
-ReorgDestinationAction_error=An error occurred while reorganizing resources
-ReorgDestinationAction_exception=Unexpected exception occurred. See log for details
-ReorgDestinationAction_duplicate=Two or more elements named {0} are selected
-ReorgDestinationAction_exception_title=Exception
-ReorgDestinationAction_error_occurred=Error occurred while performing this operation.
-
-ReorgQueries_enterNewNameQuestion=Enter a new name for ''{0}'':
-ReorgQueries_nameConflictMessage=Name Conflict
-ReorgQueries_resourceWithThisNameAlreadyExists=Resource with this name already exists
-ReorgQueries_invalidNameMessage=Invalid name
-ReorgQueries_packagewithThatNameexistsMassage=Package with that name exists
-ReorgQueries_resourceExistsWithDifferentCaseMassage=Resource exists with different case
-ReorgQueries_Confirm_Overwritting=Confirm Overwriting
-ReorgQueries_exists_read_only=''{0}'' exists and is read-only. Do you wish to overwrite ?
-ReorgQueries_exists=''{0}'' exists. Do you wish to overwrite ?
-ReorgQueries_skip_all=Skip All
-
-CopyToClipboardProblemDialog_title=Problem Copying to Clipboard
-CopyToClipboardProblemDialog_message=There was a problem when accessing the system clipboard. Retry?
-
-PasteResourcesFromClipboardAction_error_title=Paste
-PasteResourcesFromClipboardAction_error_message=Internal error occurred. Please see log for details.
-
-ReorgExceptionHandler_error_title=Problems Deleting
-ReorgExceptionHandler_error_message=Resource {0} is out of synch with the file system. Do you want to delete it anyway?
-
-DeleteSourceReferencesAction_sure=Are you sure you want to delete ''{0}''?
-DeleteSourceReferencesAction_sure_elements=Are you sure you want to delete these {0} elements?
-DeleteSourceReferenceAction_error_title=Delete
-DeleteSourceReferenceAction_error_message=An error occurred while performing this operation. See log for details.
-DeleteSourceReferenceAction_deleting=Deleting
-
-DeleteResourcesAction_deleteAction_confirm_message=The selection includes a folder that contains a JavaScript source folder. Delete this folder?
-DeleteResourcesAction_Delete=Delete
-DeleteResourcesAction_sure_delete=Are you sure you want to delete ''{0}''?
-DeleteResourcesAction_sure_delete_resources=Are you sure you want to delete these {0} resources?
-DeleteResourcesAction_default_package=(default package)
-DeleteResourcesAction_referenced=Source Folder ''{0}'' is referenced by the following projects. Do you still want to delete it?
-DeleteResourcesAction_sure_delete_linked_single=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.
-DeleteResourcesAction_sure_delete_linked_single_package_or_pfr=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.\n\nNote that all subelements of the selected source folders will be removed from the workspace as well.
-DeleteResourcesAction_sure_delete_linked_multiple=Are you sure you want to delete these {0} resources?\n\nSelection contains linked resources.\nOnly the workspace links will be deleted. Link targets will remain unchanged.
-DeleteResourcesAction_sure_delete_linked_multiple_with_packages_or_pfr=Are you sure you want to delete these {0} resources?\n\nSelection contains linked source folders.\nOnly the workspace links will be deleted. Link targets will remain unchanged.\n\nNote that all subelements of linked source folders will be removed from the workspace as well.
-CopyToClipboardAction_0=&Copy
-CopyToClipboardAction_1=Copy the selected elements to the clipboard
-CopyToClipboardAction_2=Copy To Clipboard
-CopyToClipboardAction_3=Internal error. See log for details.
-CopyToClipboardAction_4=Problem Copying to Clipboard
-CopyToClipboardAction_5=There was a problem when accessing the system clipboard. Retry?
-DeleteAction_3=&Delete
-DeleteAction_4=Deletes the selected elements
-NewNameQueries_21=Error
-NewNameQueries_22=Internal error occurred. See log for details.
-ReorgCopyAction_3=&Copy...
-ReorgCopyAction_4=Copy the selected elements
-ReorgCopyWizard_1=Copy
-ReorgCopyWizard_2=The selected element cannot be the destination of this operation.
-ReorgMoveAction_3=&Move...
-ReorgMoveAction_4=Move the selected elements
-ReorgMoveWizard_3=Move
-ReorgMoveWizard_4=The selected element cannot be the destination of this operation.
-ReorgMoveWizard_textual_move=Textual Move
-ReorgMoveWizard_newPackage=Create &Package...
-ReorgUserInputPage_choose_destination_single=&Choose destination for ''{0}'':
-ReorgUserInputPage_choose_destination_multi=&Choose destination for {0} selected elements:
-
-RenameMethodUserInterfaceStarter_name= Rename Refactoring
-RenameMethodUserInterfaceStarter_message= {0}\n\nOK to perform the operation on this method?
-
-PasteAction_4=&Paste
-PasteAction_5=Pastes elements from the clipboard
-PasteAction_change_name=Paste
-PasteAction_projectName=_pasted_code_{0}
-PasteAction_edit_name=paste elements
-PasteAction_element_doesnot_exist=The selected element does not exist in the workspace
-PasteAction_invalid_destination=The selected element cannot be the destination of this paste operation
-PasteAction_name=Paste
-PasteAction_wrong_destination=A member of a JavaScript file should be selected as the destination
-PasteAction_TextPaster_confirmOverwriting=Confirm Overwriting
-PasteAction_TextPaster_exists=''{0}'' already exists. Do you want to overwrite?
-PasteAction_cannot_selection=Cannot paste the clipboard contents into the selected elements.
-PasteAction_cannot_no_selection=Cannot paste the clipboard contents.
-
-RenameLinkedMode_error_saving_editor=An error occurred while saving the editor
-
-RenameInformationPopup_SnapTo=&Snap To
-RenameInformationPopup_snap_under_left=&Under Left
-RenameInformationPopup_snap_under_right=U&nder Right
-RenameInformationPopup_snap_over_left=&Over Left
-RenameInformationPopup_snap_over_right=O&ver Right
-RenameInformationPopup_snap_bottom_right=&Bottom Right
-RenameInformationPopup_menu=Menu
-RenameInformationPopup_RenameInWorkspace=&Refactor
-RenameInformationPopup_Preview=Pre&view...
-RenameInformationPopup_OpenDialog=&Open Rename Dialog...
-RenameInformationPopup_preferences=&Preferences...
-RenameInformationPopup_EnterNewName=Enter new name, press {0} to refactor
-RenameInformationPopup_delayJobName=delayed RenameInformationPopup
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveAction.java
deleted file mode 100644
index 62b09ce0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveAction.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.MoveProjectAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class ReorgMoveAction extends SelectionDispatchAction {
- public ReorgMoveAction(IWorkbenchSite site) {
- super(site);
- setText(ReorgMessages.ReorgMoveAction_3);
- setDescription(ReorgMessages.ReorgMoveAction_4);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_ACTION);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- if (!selection.isEmpty()) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())) {
- setEnabled(createWorkbenchAction(selection).isEnabled());
- return;
- }
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (elements.size() != resources.length + javaElements.length)
- setEnabled(false);
- else
- setEnabled(RefactoringAvailabilityTester.isMoveAvailable(resources, javaElements));
- } catch (JavaScriptModelException e) {
- // no ui here - this happens on selection changes
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- } else
- setEnabled(false);
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- private MoveProjectAction createWorkbenchAction(IStructuredSelection selection) {
- MoveProjectAction action= new MoveProjectAction(getShell());
- action.selectionChanged(selection);
- return action;
- }
-
- public void run(IStructuredSelection selection) {
- if (ReorgUtils.containsOnlyProjects(selection.toList())) {
- createWorkbenchAction(selection).run();
- return;
- }
- try {
- List elements= selection.toList();
- IResource[] resources= ReorgUtils.getResources(elements);
- IJavaScriptElement[] javaElements= ReorgUtils.getJavaElements(elements);
- if (RefactoringAvailabilityTester.isMoveAvailable(resources, javaElements))
- RefactoringExecutionStarter.startMoveRefactoring(resources, javaElements, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveStarter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveStarter.java
deleted file mode 100644
index 323c67c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveStarter.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.JavaMoveRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-
-public class ReorgMoveStarter {
- private final JavaMoveProcessor fMoveProcessor;
-
- private ReorgMoveStarter(JavaMoveProcessor moveProcessor) {
- Assert.isNotNull(moveProcessor);
- fMoveProcessor= moveProcessor;
- }
-
- public static ReorgMoveStarter create(IJavaScriptElement[] javaElements, IResource[] resources, IJavaScriptElement destination) throws JavaScriptModelException {
- Assert.isNotNull(javaElements);
- Assert.isNotNull(resources);
- Assert.isNotNull(destination);
- IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements);
- if (!policy.canEnable())
- return null;
- JavaMoveProcessor processor= new JavaMoveProcessor(policy);
- if (! processor.setDestination(destination).isOK())
- return null;
- return new ReorgMoveStarter(processor);
- }
-
- public static ReorgMoveStarter create(IJavaScriptElement[] javaElements, IResource[] resources, IResource destination) throws JavaScriptModelException {
- Assert.isNotNull(javaElements);
- Assert.isNotNull(resources);
- Assert.isNotNull(destination);
- IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements);
- if (!policy.canEnable())
- return null;
- JavaMoveProcessor processor= new JavaMoveProcessor(policy);
- if (! processor.setDestination(destination).isOK())
- return null;
- return new ReorgMoveStarter(processor);
- }
-
- public void run(Shell parent) throws InterruptedException, InvocationTargetException {
- try {
- JavaMoveRefactoring ref= new JavaMoveRefactoring(fMoveProcessor);
- if (fMoveProcessor.hasAllInputSet()) {
- IRunnableContext context= new ProgressMonitorDialog(parent);
- fMoveProcessor.setCreateTargetQueries(new CreateTargetQueries(parent));
- fMoveProcessor.setReorgQueries(new ReorgQueries(parent));
- new RefactoringExecutionHelper(ref, RefactoringCore.getConditionCheckingFailedSeverity(), RefactoringSaveHelper.SAVE_ALL, parent, context).perform(false, false);
- } else {
- RefactoringWizard wizard= new ReorgMoveWizard(ref);
- /*
- * We want to get the shell from the refactoring dialog but it's not known at this point,
- * so we pass the wizard and then, once the dialog is open, we will have access to its shell.
- */
- fMoveProcessor.setCreateTargetQueries(new CreateTargetQueries(wizard));
- fMoveProcessor.setReorgQueries(new ReorgQueries(wizard));
- new RefactoringStarter().activate(ref, wizard, parent, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_ALL);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveWizard.java
deleted file mode 100644
index 90949fa8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMoveWizard.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ICreateTargetQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgDestinationValidator;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.QualifiedNameComponent;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-
-public class ReorgMoveWizard extends RefactoringWizard {
-
- public ReorgMoveWizard(MoveRefactoring ref) {
- super(ref, DIALOG_BASED_USER_INTERFACE | computeHasPreviewPage(ref));
- if (isTextualMove(ref))
- setDefaultPageTitle(ReorgMessages.ReorgMoveWizard_textual_move);
- else
- setDefaultPageTitle(ReorgMessages.ReorgMoveWizard_3);
- }
-
- private static boolean isTextualMove(MoveRefactoring ref) {
- JavaMoveProcessor moveProcessor= (JavaMoveProcessor) ref.getAdapter(JavaMoveProcessor.class);
- return moveProcessor.isTextualMove();
- }
-
- private static int computeHasPreviewPage(MoveRefactoring refactoring) {
- JavaMoveProcessor processor= (JavaMoveProcessor)refactoring.getAdapter(JavaMoveProcessor.class);
- if (processor.canUpdateReferences() || processor.canEnableQualifiedNameUpdating())
- return NONE;
- return NO_PREVIEW_PAGE;
- }
-
- protected void addUserInputPages() {
- addPage(new MoveInputPage());
- }
-
- private static class MoveInputPage extends ReorgUserInputPage{
-
- private static final String PAGE_NAME= "MoveInputPage"; //$NON-NLS-1$
- private Button fReferenceCheckbox;
- private Button fQualifiedNameCheckbox;
- private QualifiedNameComponent fQualifiedNameComponent;
- private ICreateTargetQuery fCreateTargetQuery;
-
- private Object fDestination;
-
- public MoveInputPage() {
- super(PAGE_NAME);
- }
-
- private JavaMoveProcessor getJavaMoveProcessor(){
- return (JavaMoveProcessor)getRefactoring().getAdapter(JavaMoveProcessor.class);
- }
-
- protected Object getInitiallySelectedElement() {
- return getJavaMoveProcessor().getCommonParentForInputElements();
- }
-
- protected IJavaScriptElement[] getJavaElements() {
- return getJavaMoveProcessor().getJavaElements();
- }
-
- protected IResource[] getResources() {
- return getJavaMoveProcessor().getResources();
- }
-
- protected IReorgDestinationValidator getDestinationValidator() {
- return getJavaMoveProcessor();
- }
-
- protected boolean performFinish() {
- return super.performFinish() || getJavaMoveProcessor().wasCanceled(); //close the dialog if canceled
- }
-
- protected RefactoringStatus verifyDestination(Object selected) throws JavaScriptModelException{
- JavaMoveProcessor processor= getJavaMoveProcessor();
- final RefactoringStatus refactoringStatus;
- if (selected instanceof IJavaScriptElement)
- refactoringStatus= processor.setDestination((IJavaScriptElement)selected);
- else if (selected instanceof IResource)
- refactoringStatus= processor.setDestination((IResource)selected);
- else refactoringStatus= RefactoringStatus.createFatalErrorStatus(ReorgMessages.ReorgMoveWizard_4);
-
- updateUIStatus();
- fDestination= selected;
- return refactoringStatus;
- }
-
- private void updateUIStatus() {
- getRefactoringWizard().setForcePreviewReview(false);
- JavaMoveProcessor processor= getJavaMoveProcessor();
- if (fReferenceCheckbox != null){
- fReferenceCheckbox.setEnabled(canUpdateReferences());
- processor.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
- }
- if (fQualifiedNameCheckbox != null){
- boolean enabled= processor.canEnableQualifiedNameUpdating();
- fQualifiedNameCheckbox.setEnabled(enabled);
- if (enabled) {
- fQualifiedNameComponent.setEnabled(processor.getUpdateQualifiedNames());
- if (processor.getUpdateQualifiedNames())
- getRefactoringWizard().setForcePreviewReview(true);
- } else {
- fQualifiedNameComponent.setEnabled(false);
- }
- processor.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
- }
- }
-
- private void addUpdateReferenceComponent(Composite result) {
- final JavaMoveProcessor processor= getJavaMoveProcessor();
- if (! processor.canUpdateReferences())
- return;
- fReferenceCheckbox= new Button(result, SWT.CHECK);
- fReferenceCheckbox.setText(ReorgMessages.JdtMoveAction_update_references);
- fReferenceCheckbox.setSelection(processor.getUpdateReferences());
- fReferenceCheckbox.setEnabled(canUpdateReferences());
-
- fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- processor.setUpdateReferences(((Button)e.widget).getSelection());
- updateUIStatus();
- }
- });
- }
-
- private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
- final JavaMoveProcessor processor= getJavaMoveProcessor();
- if (!processor.canEnableQualifiedNameUpdating() || !processor.canUpdateQualifiedNames())
- return;
- fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
- int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
- fQualifiedNameCheckbox.setText(RefactoringMessages.RenameInputWizardPage_update_qualified_names);
- fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fQualifiedNameCheckbox.setSelection(processor.getUpdateQualifiedNames());
-
- fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, processor, getRefactoringSettings());
- fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
- gd.horizontalAlignment= GridData.FILL;
- gd.horizontalIndent= indent;
- updateQualifiedNameUpdating(processor, processor.getUpdateQualifiedNames());
-
- fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- boolean enabled= ((Button)e.widget).getSelection();
- updateQualifiedNameUpdating(processor, enabled);
- }
-
- });
- }
-
- private void updateQualifiedNameUpdating(final JavaMoveProcessor processor, boolean enabled) {
- fQualifiedNameComponent.setEnabled(enabled);
- processor.setUpdateQualifiedNames(enabled);
- updateUIStatus();
- }
-
- public void createControl(Composite parent) {
- Composite result;
-
- boolean showDestinationTree= ! getJavaMoveProcessor().hasDestinationSet();
- if (showDestinationTree) {
- fCreateTargetQuery= getJavaMoveProcessor().getCreateTargetQuery();
- super.createControl(parent);
- getTreeViewer().getTree().setFocus();
- result= (Composite)super.getControl();
- } else {
- initializeDialogUnits(parent);
- result= new Composite(parent, SWT.NONE);
- setControl(result);
- result.setLayout(new GridLayout());
- Dialog.applyDialogFont(result);
- }
- addUpdateReferenceComponent(result);
- addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
- setControl(result);
- Dialog.applyDialogFont(result);
- }
-
- protected Control addLabel(Composite parent) {
- if (fCreateTargetQuery != null) {
- Composite firstLine= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout(2, false);
- layout.marginHeight= layout.marginWidth= 0;
- firstLine.setLayout(layout);
- firstLine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Control label= super.addLabel(firstLine);
- label.addTraverseListener(new TraverseListener() {
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_MNEMONIC && e.doit) {
- e.detail= SWT.TRAVERSE_NONE;
- getTreeViewer().getTree().setFocus();
- }
- }
- });
-
- Button newButton= new Button(firstLine, SWT.PUSH);
- newButton.setText(fCreateTargetQuery.getNewButtonLabel());
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
- gd.widthHint = SWTUtil.getButtonWidthHint(newButton);
- newButton.setLayoutData(gd);
- newButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- doNewButtonPressed();
- }
- });
-
- return firstLine;
-
- } else {
- return super.addLabel(parent);
- }
- }
-
- private boolean canUpdateReferences() {
- return getJavaMoveProcessor().canUpdateReferences();
- }
-
- private void doNewButtonPressed() {
- Object newElement= fCreateTargetQuery.getCreatedTarget(fDestination);
- if (newElement != null) {
- TreeViewer viewer= getTreeViewer();
- ITreeContentProvider contentProvider= (ITreeContentProvider) viewer.getContentProvider();
- viewer.refresh(contentProvider.getParent(newElement));
- viewer.setSelection(new StructuredSelection(newElement), true);
- viewer.getTree().setFocus();
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgQueries.java
deleted file mode 100644
index ed0cf9f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgQueries.java
+++ /dev/null
@@ -1,418 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IConfirmQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgQueries;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.ListDialog;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class ReorgQueries implements IReorgQueries {
-
- private final Wizard fWizard;
- private final Shell fShell;
-
- public ReorgQueries(Wizard wizard){
- Assert.isNotNull(wizard);
- fWizard= wizard;
- fShell= null;
- }
-
- public ReorgQueries(Shell shell){
- Assert.isNotNull(shell);
- fWizard= null;
- fShell= shell;
- }
-
- private Shell getShell() {
- Assert.isTrue(fShell == null || fWizard == null);
- Assert.isTrue(fShell != null || fWizard != null);
- if (fWizard != null)
- return fWizard.getContainer().getShell();
- else
- return fShell;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IReorgQueries#createYesYesToAllNoNoToAllQuery(java.lang.String)
- */
- public IConfirmQuery createYesYesToAllNoNoToAllQuery(String dialogTitle, boolean allowCancel, int queryID) {
- return new YesYesToAllNoNoToAllQuery(getShell(), allowCancel, dialogTitle);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IReorgQueries#createYesNoQuery(java.lang.String)
- */
- public IConfirmQuery createYesNoQuery(String dialogTitle, boolean allowCancel, int queryID) {
- return new YesNoQuery(getShell(), allowCancel, dialogTitle);
- }
-
- public IConfirmQuery createSkipQuery(String dialogTitle, int queryID) {
- return new SkipQuery(getShell(), dialogTitle);
- }
-
- private static class YesYesToAllNoNoToAllQuery implements IConfirmQuery{
- private final boolean fAllowCancel;
- private boolean fYesToAll= false;
- private boolean fNoToAll= false;
- private final Shell fShell;
- private final String fDialogTitle;
-
- YesYesToAllNoNoToAllQuery(Shell parent, boolean allowCancel, String dialogTitle){
- fShell= parent;
- fDialogTitle= dialogTitle;
- fAllowCancel= allowCancel;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IConfirmQuery#confirm(java.lang.String)
- */
- public boolean confirm(final String question) throws OperationCanceledException {
- if (fYesToAll)
- return true;
-
- if (fNoToAll)
- return false;
-
- final int[] result= new int[1];
- fShell.getDisplay().syncExec(createQueryRunnable(question, result));
- return getResult(result);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IConfirmQuery#confirm(java.lang.String, java.lang.Object[])
- */
- public boolean confirm(String question, Object[] elements) throws OperationCanceledException {
- if (fYesToAll)
- return true;
-
- if (fNoToAll)
- return false;
-
- final int[] result= new int[1];
- fShell.getDisplay().syncExec(createQueryRunnable(question, elements, result));
- return getResult(result);
- }
-
- private Runnable createQueryRunnable(final String question, final int[] result) {
- return new Runnable() {
- public void run() {
- int[] resultId= getResultIDs();
-
- MessageDialog dialog= new MessageDialog(
- fShell,
- fDialogTitle,
- null,
- question,
- MessageDialog.QUESTION,
- getButtonLabels(),
- 0);
- dialog.open();
-
- if (dialog.getReturnCode() == -1) { //MessageDialog closed without choice => cancel | no
- //see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=48400
- result[0]= fAllowCancel ? IDialogConstants.CANCEL_ID : IDialogConstants.NO_ID;
- } else {
- result[0]= resultId[dialog.getReturnCode()];
- }
- }
-
- private String[] getButtonLabels() {
- if (YesYesToAllNoNoToAllQuery.this.fAllowCancel)
- return new String[] {
- IDialogConstants.YES_LABEL,
- IDialogConstants.YES_TO_ALL_LABEL,
- IDialogConstants.NO_LABEL,
- IDialogConstants.NO_TO_ALL_LABEL,
- IDialogConstants.CANCEL_LABEL };
- else
- return new String[] {
- IDialogConstants.YES_LABEL,
- IDialogConstants.YES_TO_ALL_LABEL,
- IDialogConstants.NO_LABEL,
- IDialogConstants.NO_TO_ALL_LABEL};
- }
-
- private int[] getResultIDs() {
- if (YesYesToAllNoNoToAllQuery.this.fAllowCancel)
- return new int[] {
- IDialogConstants.YES_ID,
- IDialogConstants.YES_TO_ALL_ID,
- IDialogConstants.NO_ID,
- IDialogConstants.NO_TO_ALL_ID,
- IDialogConstants.CANCEL_ID};
- else
- return new int[] {
- IDialogConstants.YES_ID,
- IDialogConstants.YES_TO_ALL_ID,
- IDialogConstants.NO_ID,
- IDialogConstants.NO_TO_ALL_ID};
- }
- };
- }
-
- private Runnable createQueryRunnable(final String question, final Object[] elements, final int[] result) {
- return new Runnable() {
- public void run() {
- ListDialog dialog= new YesNoListDialog(fShell, true);
- dialog.setAddCancelButton(false);
- dialog.setBlockOnOpen(true);
- dialog.setContentProvider(new ArrayContentProvider());
- dialog.setLabelProvider(new JavaScriptElementLabelProvider());
- dialog.setTitle(fDialogTitle);
- dialog.setMessage(question);
- dialog.setInput(elements);
-
- dialog.open();
- result[0]= dialog.getReturnCode();
- }
- };
- }
-
- private boolean getResult(int[] result) throws OperationCanceledException {
- switch(result[0]){
- case IDialogConstants.YES_TO_ALL_ID:
- fYesToAll= true;
- return true;
- case IDialogConstants.YES_ID:
- return true;
- case IDialogConstants.CANCEL_ID:
- throw new OperationCanceledException();
- case IDialogConstants.NO_ID:
- return false;
- case IDialogConstants.NO_TO_ALL_ID:
- fNoToAll= true;
- return false;
- default:
- Assert.isTrue(false);
- return false;
- }
- }
- }
-
- private static class YesNoQuery implements IConfirmQuery{
-
- private final Shell fShell;
- private final String fDialogTitle;
- private final boolean fAllowCancel;
-
- YesNoQuery(Shell parent, boolean allowCancel, String dialogTitle){
- fShell= parent;
- fDialogTitle= dialogTitle;
- fAllowCancel= allowCancel;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IConfirmQuery#confirm(java.lang.String)
- */
- public boolean confirm(String question) throws OperationCanceledException {
- final int[] result= new int[1];
- fShell.getDisplay().syncExec(createQueryRunnable(question, result));
- return getResult(result);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IReorgQueries.IConfirmQuery#confirm(java.lang.String, java.lang.Object[])
- */
- public boolean confirm(String question, Object[] elements) throws OperationCanceledException {
- final int[] result= new int[1];
- fShell.getDisplay().syncExec(createQueryRunnable(question, elements, result));
- return getResult(result);
- }
-
- private Runnable createQueryRunnable(final String question, final int[] result){
- return new Runnable() {
- public void run() {
- MessageDialog dialog= new MessageDialog(
- fShell,
- fDialogTitle,
- null,
- question,
- MessageDialog.QUESTION,
- getButtonLabels(),
- 0);
- dialog.open();
-
- switch (dialog.getReturnCode()) {
- case -1 : //MessageDialog closed without choice => cancel | no
- //see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=48400
- result[0]= fAllowCancel ? IDialogConstants.CANCEL_ID : IDialogConstants.NO_ID;
- break;
- case 0 :
- result[0]= IDialogConstants.YES_ID;
- break;
- case 1 :
- result[0]= IDialogConstants.NO_ID;
- break;
- case 2 :
- if (fAllowCancel)
- result[0]= IDialogConstants.CANCEL_ID;
- else
- Assert.isTrue(false);
- break;
- default :
- Assert.isTrue(false);
- break;
- }
- }
-
- private String[] getButtonLabels() {
- if (fAllowCancel)
- return new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL };
- else
- return new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL};
- }
- };
- }
-
- private Runnable createQueryRunnable(final String question, final Object[] elements, final int[] result) {
- return new Runnable() {
- public void run() {
- ListDialog dialog= new YesNoListDialog(fShell, false);
- dialog.setAddCancelButton(false);
- dialog.setBlockOnOpen(true);
- dialog.setContentProvider(new ArrayContentProvider());
- dialog.setLabelProvider(new JavaScriptElementLabelProvider());
- dialog.setTitle(fDialogTitle);
- dialog.setMessage(question);
- dialog.setInput(elements);
-
- dialog.open();
- result[0]= dialog.getReturnCode();
- }
- };
- }
-
- private boolean getResult(int[] result) throws OperationCanceledException {
- switch(result[0]){
- case IDialogConstants.YES_ID:
- return true;
- case IDialogConstants.CANCEL_ID:
- throw new OperationCanceledException();
- case IDialogConstants.NO_ID:
- return false;
- default:
- Assert.isTrue(false);
- return false;
- }
- }
- }
-
- private static class SkipQuery implements IConfirmQuery{
-
- private final Shell fShell;
- private final String fDialogTitle;
- private boolean fSkipAll;
-
- SkipQuery(Shell parent, String dialogTitle){
- fShell= parent;
- fDialogTitle= dialogTitle;
- fSkipAll= false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IConfirmQuery#confirm(java.lang.String)
- */
- public boolean confirm(String question) throws OperationCanceledException {
- if (fSkipAll)
- return false;
- final int[] result= new int[1];
- fShell.getDisplay().syncExec(createQueryRunnable(question, result));
- return getResult(result);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.refactoring.reorg2.IReorgQueries.IConfirmQuery#confirm(java.lang.String, java.lang.Object[])
- */
- public boolean confirm(String question, Object[] elements) throws OperationCanceledException {
- throw new UnsupportedOperationException("Not supported for skip queries"); //$NON-NLS-1$
- }
-
- private Runnable createQueryRunnable(final String question, final int[] result){
- return new Runnable() {
- public void run() {
- MessageDialog dialog= new MessageDialog(
- fShell,
- fDialogTitle,
- null,
- question,
- MessageDialog.QUESTION,
- getButtonLabels(),
- 0);
- dialog.open();
-
- switch (dialog.getReturnCode()) {
- case -1 : //MessageDialog closed without choice => cancel | no
- //see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=48400
- result[0]= IDialogConstants.CANCEL_ID;
- break;
- default:
- result[0]= dialog.getReturnCode();
- }
- }
-
- private String[] getButtonLabels() {
- return new String[] {IDialogConstants.SKIP_LABEL, ReorgMessages.ReorgQueries_skip_all, IDialogConstants.CANCEL_LABEL};
- }
- };
- }
-
- private boolean getResult(int[] result) throws OperationCanceledException {
- switch(result[0]){
- // skip button
- case 0:
- return false;
- // skip all button
- case 1:
- fSkipAll= true;
- return false;
- // Cancel button
- case 2:
- throw new OperationCanceledException();
- default:
- return false;
- }
- }
- }
-
- private static final class YesNoListDialog extends ListDialog {
- private final boolean fYesToAllNoToAll;
- private YesNoListDialog(Shell parent, boolean includeYesToAllNoToAll) {
- super(parent, SWT.TITLE | SWT.BORDER | SWT.RESIZE | SWT.APPLICATION_MODAL);
- fYesToAllNoToAll= includeYesToAllNoToAll;
- }
-
- protected void buttonPressed(int buttonId) {
- super.buttonPressed(buttonId);
- setReturnCode(buttonId);
- close();
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, true);
- if (fYesToAllNoToAll)
- createButton(parent, IDialogConstants.YES_TO_ALL_ID, IDialogConstants.YES_TO_ALL_LABEL, false);
- createButton(parent, IDialogConstants.NO_ID, IDialogConstants.NO_LABEL, false);
- if (fYesToAllNoToAll)
- createButton(parent, IDialogConstants.NO_TO_ALL_ID, IDialogConstants.NO_TO_ALL_LABEL, false);
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgUserInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgUserInputPage.java
deleted file mode 100644
index bdd32911..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgUserInputPage.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.IReorgDestinationValidator;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-
-abstract class ReorgUserInputPage extends UserInputWizardPage{
- private static final long LABEL_FLAGS= JavaScriptElementLabels.ALL_DEFAULT
- | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE;
- private TreeViewer fViewer;
- public ReorgUserInputPage(String pageName) {
- super(pageName);
- }
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- result.setLayout(new GridLayout());
-
- Object initialSelection= getInitiallySelectedElement();
- verifyDestination(initialSelection, true);
-
- addLabel(result);
-
- fViewer= createViewer(result);
- fViewer.setSelection(new StructuredSelection(initialSelection), true);
- fViewer.addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent event) {
- ReorgUserInputPage.this.viewerSelectionChanged(event);
- }
- });
- Dialog.applyDialogFont(result);
- }
-
- protected Control addLabel(Composite parent) {
- Label label= new Label(parent, SWT.WRAP);
- String text;
- int resources= getResources().length;
- int javaElements= getJavaElements().length;
-
- if (resources == 0 && javaElements == 1) {
- text= Messages.format(
- ReorgMessages.ReorgUserInputPage_choose_destination_single,
- JavaScriptElementLabels.getElementLabel(getJavaElements()[0], LABEL_FLAGS));
- } else if (resources == 1 && javaElements == 0) {
- text= Messages.format(
- ReorgMessages.ReorgUserInputPage_choose_destination_single,
- getResources()[0].getName());
- } else {
- text= Messages.format(
- ReorgMessages.ReorgUserInputPage_choose_destination_multi,
- String.valueOf(resources + javaElements));
- }
-
- label.setText(text);
- GridData data= new GridData(SWT.FILL, SWT.END, true, false);
- data.widthHint= convertWidthInCharsToPixels(50);
- label.setLayoutData(data);
- return label;
- }
-
- private void viewerSelectionChanged(SelectionChangedEvent event) {
- ISelection selection= event.getSelection();
- if (!(selection instanceof IStructuredSelection))
- return;
- IStructuredSelection ss= (IStructuredSelection)selection;
- verifyDestination(ss.getFirstElement(), false);
- }
-
- protected abstract Object getInitiallySelectedElement();
-
- /** Set and verify destination */
- protected abstract RefactoringStatus verifyDestination(Object selected) throws JavaScriptModelException;
-
- protected abstract IResource[] getResources();
- protected abstract IJavaScriptElement[] getJavaElements();
-
- protected abstract IReorgDestinationValidator getDestinationValidator();
-
- private final void verifyDestination(Object selected, boolean initialVerification) {
- try {
- RefactoringStatus status= verifyDestination(selected);
- if (initialVerification)
- setPageComplete(status.isOK());
- else
- setPageComplete(status);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- setPageComplete(false);
- }
- }
-
- private TreeViewer createViewer(Composite parent) {
- TreeViewer treeViewer= new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(40);
- gd.heightHint= convertHeightInCharsToPixels(15);
- treeViewer.getTree().setLayoutData(gd);
- treeViewer.setLabelProvider(new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_SMALL_ICONS));
- treeViewer.setContentProvider(new DestinationContentProvider(getDestinationValidator()));
- treeViewer.setComparator(new JavaScriptElementComparator());
- treeViewer.setInput(JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()));
- return treeViewer;
- }
-
- protected TreeViewer getTreeViewer() {
- return fViewer;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/TypedSourceTransfer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/TypedSourceTransfer.java
deleted file mode 100644
index 435d7f12..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/TypedSourceTransfer.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.reorg;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypedSource;
-
-public class TypedSourceTransfer extends ByteArrayTransfer {
-
- /**
- * Singleton instance.
- */
- private static final TypedSourceTransfer fgInstance = new TypedSourceTransfer();
-
- // Create a unique ID to make sure that different Eclipse
- // applications use different "types" of <code>TypedSourceTransfer</code>
- private static final String TYPE_NAME = "typed-source-transfer-format:" + System.currentTimeMillis() + ":" + fgInstance.hashCode();//$NON-NLS-2$//$NON-NLS-1$
-
- private static final int TYPEID = registerType(TYPE_NAME);
-
- private TypedSourceTransfer() {
- }
-
- /**
- * Returns the singleton instance.
- *
- * @return the singleton instance
- */
- public static TypedSourceTransfer getInstance() {
- return fgInstance;
- }
-
- /* (non-Javadoc)
- * Method declared on Transfer.
- */
- protected int[] getTypeIds() {
- return new int[] {TYPEID};
- }
-
- /* (non-Javadoc)
- * Returns the type names.
- *
- * @return the list of type names
- */
- protected String[] getTypeNames() {
- return new String[] {TYPE_NAME};
- }
-
- /* (non-Javadoc)
- * Method declared on Transfer.
- */
- protected void javaToNative(Object data, TransferData transferData) {
- if (! (data instanceof TypedSource[]))
- return;
- TypedSource[] sources = (TypedSource[]) data;
-
- /*
- * The serialization format is:
- * (int) number of elements
- * Then, the following for each element:
- * (int) type (see <code>IJavaScriptElement</code>)
- * (String) source of the element
- */
-
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- DataOutputStream dataOut = new DataOutputStream(out);
-
- dataOut.writeInt(sources.length);
-
- for (int i = 0; i < sources.length; i++) {
- writeJavaElement(dataOut, sources[i]);
- }
-
- dataOut.close();
- out.close();
-
- super.javaToNative(out.toByteArray(), transferData);
- } catch (IOException e) {
- //it's best to send nothing if there were problems
- }
- }
-
- /* (non-Javadoc)
- * Method declared on Transfer.
- */
- protected Object nativeToJava(TransferData transferData) {
-
- byte[] bytes = (byte[]) super.nativeToJava(transferData);
- if (bytes == null)
- return null;
- DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
- try {
- int count = in.readInt();
- TypedSource[] results = new TypedSource[count];
- for (int i = 0; i < count; i++) {
- results[i] = readJavaElement(in);
- Assert.isNotNull(results[i]);
- }
- in.close();
- return results;
- } catch (IOException e) {
- return null;
- }
- }
-
- private static TypedSource readJavaElement(DataInputStream dataIn) throws IOException {
- int type= dataIn.readInt();
- String source= dataIn.readUTF();
- return TypedSource.create(source, type);
- }
-
- private static void writeJavaElement(DataOutputStream dataOut, TypedSource sourceReference) throws IOException {
- dataOut.writeInt(sourceReference.getType());
- dataOut.writeUTF(sourceReference.getSource());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldInputPage.java
deleted file mode 100644
index dd5d464b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldInputPage.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.refactoring.sef;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class SelfEncapsulateFieldInputPage extends UserInputWizardPage {
-
- private SelfEncapsulateFieldRefactoring fRefactoring;
- private IDialogSettings fSettings;
- private List fEnablements;
-
- private static final String GENERATE_JAVADOC= "GenerateJavadoc"; //$NON-NLS-1$
-
-
- public SelfEncapsulateFieldInputPage() {
- super("InputPage"); //$NON-NLS-1$
- setDescription(RefactoringMessages.SelfEncapsulateFieldInputPage_description);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR_CU);
- }
-
- public void createControl(Composite parent) {
- fRefactoring= (SelfEncapsulateFieldRefactoring)getRefactoring();
- fEnablements= new ArrayList();
- loadSettings();
-
- Composite result= new Composite(parent, SWT.NONE);
- setControl(result);
- initializeDialogUnits(result);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 3;
- layout.verticalSpacing= 8;
- result.setLayout(layout);
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint= convertWidthInCharsToPixels(25);
-
- Label label= new Label(result, SWT.LEAD);
- label.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_getter_name);
-
- Text getter= new Text(result, SWT.BORDER);
- getter.setText(fRefactoring.getGetterName());
- getter.setLayoutData(gd);
- TextFieldNavigationHandler.install(getter);
-
- final Label reUseGetter= new Label(result,SWT.LEAD);
- GridData getterGD= new GridData();
- getterGD.widthHint=convertWidthInCharsToPixels(23);
- reUseGetter.setLayoutData(getterGD);
- updateUseGetter(reUseGetter);
- getter.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- String getterName= ((Text)e.widget).getText();
- fRefactoring.setGetterName(getterName);
- updateUseGetter(reUseGetter);
- processValidation();
- }
- });
-
- if (needsSetter()) {
- label= new Label(result, SWT.LEAD);
- label.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_setter_name);
-
- Text setter= new Text(result, SWT.BORDER);
- setter.setText(fRefactoring.getSetterName());
- setter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- final Label reUseSetter= new Label(result, SWT.LEAD);
- GridData setterGD= new GridData();
- setterGD.widthHint=convertWidthInCharsToPixels(23);
- reUseSetter.setLayoutData(setterGD);
- updateUseSetter(reUseSetter);
- setter.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- String setterName= ((Text)e.widget).getText();
- fRefactoring.setSetterName(setterName);
- updateUseSetter(reUseSetter);
- processValidation();
- }
-
- });
- TextFieldNavigationHandler.install(setter);
- }
-
- // createSeparator(result, layouter);
- createFieldAccessBlock(result);
-
- label= new Label(result, SWT.LEFT);
- label.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_insert_after);
- fEnablements.add(label);
- final Combo combo= new Combo(result, SWT.READ_ONLY);
- fillWithPossibleInsertPositions(combo, fRefactoring.getField());
- combo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRefactoring.setInsertionIndex(combo.getSelectionIndex() - 1);
- }
- });
- GridData gridData= new GridData(GridData.FILL_HORIZONTAL);
- gridData.horizontalSpan=2;
- combo.setLayoutData(gridData);
- fEnablements.add(combo);
-
-
- createAccessModifier(result);
-
- Button checkBox= new Button(result, SWT.CHECK);
- checkBox.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_generateJavadocComment);
- checkBox.setSelection(fRefactoring.getGenerateJavadoc());
- checkBox.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setGenerateJavadoc(((Button)e.widget).getSelection());
- }
- });
- GridData checkGD= new GridData(GridData.FILL_HORIZONTAL);
- checkGD.horizontalSpan=3;
- checkBox.setLayoutData(checkGD);
- fEnablements.add(checkBox);
-
- updateEnablements();
-
- processValidation();
-
- getter.setFocus();
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.SEF_WIZARD_PAGE);
- }
-
- private void updateUseSetter(Label reUseSetter) {
- if (fRefactoring.isUsingLocalSetter())
- reUseSetter.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_useexistingsetter_label);
- else
- reUseSetter.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_usenewgetter_label);
- updateEnablements();
- }
-
- private void updateEnablements() {
- boolean enable=!(fRefactoring.isUsingLocalSetter()&&fRefactoring.isUsingLocalGetter());
- for (Iterator iter= fEnablements.iterator(); iter.hasNext();) {
- Control control= (Control) iter.next();
- control.setEnabled(enable);
- }
- }
-
- private void updateUseGetter(Label reUseGetter) {
- if (fRefactoring.isUsingLocalGetter())
- reUseGetter.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_useexistinggetter_label);
- else
- reUseGetter.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_usenewsetter_label);
- updateEnablements();
- }
-
- private void loadSettings() {
- fSettings= getDialogSettings().getSection(SelfEncapsulateFieldWizard.DIALOG_SETTING_SECTION);
- if (fSettings == null) {
- fSettings= getDialogSettings().addNewSection(SelfEncapsulateFieldWizard.DIALOG_SETTING_SECTION);
- fSettings.put(GENERATE_JAVADOC, JavaPreferencesSettings.getCodeGenerationSettings(fRefactoring.getField().getJavaScriptProject()).createComments);
- }
- fRefactoring.setGenerateJavadoc(fSettings.getBoolean(GENERATE_JAVADOC));
- }
-
- private void createAccessModifier(Composite result) {
- int visibility= fRefactoring.getVisibility();
- if (Flags.isPublic(visibility))
- return;
- GridLayout layout;
- Label label;
- label= new Label(result, SWT.NONE);
- label.setText(RefactoringMessages.SelfEncapsulateFieldInputPage_access_Modifiers);
- fEnablements.add(label);
- Composite group= new Composite(result, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout= new GridLayout();
- layout.numColumns= 4; layout.marginWidth= 0; layout.marginHeight= 0;
- group.setLayout(layout);
- GridData gridData= new GridData(GridData.FILL_HORIZONTAL);
- gridData.horizontalSpan=2;
- group.setLayoutData(gridData);
-
- Object[] info= createData(visibility);
- String[] labels= (String[])info[0];
- Integer[] data= (Integer[])info[1];
- for (int i= 0; i < labels.length; i++) {
- Button radio= new Button(group, SWT.RADIO);
- radio.setText(labels[i]);
- radio.setData(data[i]);
- int iData= data[i].intValue();
- if (iData == visibility)
- radio.setSelection(true);
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- fRefactoring.setVisibility(((Integer)event.widget.getData()).intValue());
- }
- });
- fEnablements.add(radio);
- }
- }
-
- private void createFieldAccessBlock(Composite result) {
- Label label= new Label(result, SWT.LEFT);
- label.setText(RefactoringMessages.SelfEncapsulateField_field_access);
-
- Composite group= new Composite(result, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0; layout.marginHeight= 0; layout.numColumns= 2;
- group.setLayout(layout);
- GridData gridData= new GridData(GridData.FILL_HORIZONTAL);
- gridData.horizontalSpan=2;
- group.setLayoutData(gridData);
- Button radio= new Button(group, SWT.RADIO);
- radio.setText(RefactoringMessages.SelfEncapsulateField_use_setter_getter);
- radio.setSelection(true);
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setEncapsulateDeclaringClass(true);
- }
- });
- radio.setLayoutData(new GridData());
-
- radio= new Button(group, SWT.RADIO);
- radio.setText(RefactoringMessages.SelfEncapsulateField_keep_references);
- radio.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fRefactoring.setEncapsulateDeclaringClass(false);
- }
- });
- radio.setLayoutData(new GridData());
- }
-
- private Object[] createData(int visibility) {
- String pub= RefactoringMessages.SelfEncapsulateFieldInputPage_public;
- String def= RefactoringMessages.SelfEncapsulateFieldInputPage_default;
- String priv= RefactoringMessages.SelfEncapsulateFieldInputPage_private;
-
- String[] labels= null;
- Integer[] data= null;
- if (Flags.isPrivate(visibility)) {
- labels= new String[] { pub, def, priv };
- data= new Integer[] {new Integer(Flags.AccPublic), new Integer(0), new Integer(Flags.AccPrivate) };
- } else {
- labels= new String[] { pub, def };
- data= new Integer[] {new Integer(Flags.AccPublic), new Integer(0)};
- }
- return new Object[] {labels, data};
- }
-
- private void fillWithPossibleInsertPositions(Combo combo, IField field) {
- int select= 0;
- combo.add(RefactoringMessages.SelfEncapsulateFieldInputPage_first_method);
- try {
- IFunction[] methods= field.getDeclaringType().getFunctions();
- for (int i= 0; i < methods.length; i++) {
- combo.add(JavaScriptElementLabels.getElementLabel(methods[i], JavaScriptElementLabels.M_PARAMETER_TYPES));
- }
- if (methods.length > 0)
- select= methods.length;
- } catch (JavaScriptModelException e) {
- // Fall through
- }
- combo.select(select);
- fRefactoring.setInsertionIndex(select - 1);
- }
-
- private void setGenerateJavadoc(boolean value) {
- fSettings.put(GENERATE_JAVADOC, value);
- fRefactoring.setGenerateJavadoc(value);
- }
-
- private void processValidation() {
- RefactoringStatus status= fRefactoring.checkMethodNames();
- String message= null;
- boolean valid= true;
- if (status.hasFatalError()) {
- message= status.getMessageMatchingSeverity(RefactoringStatus.FATAL);
- valid= false;
- }
- setErrorMessage(message);
- setPageComplete(valid);
- }
-
- private boolean needsSetter() {
- try {
- return !JdtFlags.isFinal(fRefactoring.getField());
- } catch(JavaScriptModelException e) {
- return true;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldWizard.java
deleted file mode 100644
index 6858b3da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/sef/SelfEncapsulateFieldWizard.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.refactoring.sef;
-
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-
-public class SelfEncapsulateFieldWizard extends RefactoringWizard {
-
- /* package */ static final String DIALOG_SETTING_SECTION= "SelfEncapsulateFieldWizard"; //$NON-NLS-1$
-
- public SelfEncapsulateFieldWizard(SelfEncapsulateFieldRefactoring refactoring) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE);
- setDefaultPageTitle(RefactoringMessages.SelfEncapsulateField_sef);
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- }
-
- protected void addUserInputPages() {
- addPage(new SelfEncapsulateFieldInputPage());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/BreakContinueTargetFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/BreakContinueTargetFinder.java
deleted file mode 100644
index 74b6a958..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/BreakContinueTargetFinder.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.EnhancedForStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.LabeledStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Class used to find the target for a break or continue statement according
- * to the language specification.
- * <p>
- * The target statement is a while, do, switch, for or a labeled statement.
- * Break is described in section 14.15 of the JLS3 and continue in section 14.16.</p>
- *
- *
- */
-public class BreakContinueTargetFinder extends ASTVisitor {
- private ASTNode fSelected;
- private boolean fIsBreak;
- private SimpleName fLabel;
- private String fContents;//contents are used for scanning to select the right extent of the keyword
- private static final Class[] STOPPERS= {FunctionDeclaration.class, Initializer.class};
- private static final Class[] BREAKTARGETS= {ForStatement.class, ForInStatement.class, EnhancedForStatement.class, WhileStatement.class, DoStatement.class, SwitchStatement.class};
- private static final Class[] CONTINUETARGETS= {ForStatement.class, ForInStatement.class, EnhancedForStatement.class, WhileStatement.class, DoStatement.class};
- private static final int BRACE_LENGTH= 1;
-
- /*
- * Initializes the finder. Returns error message or <code>null</code> if everything is OK.
- */
- public String initialize(JavaScriptUnit root, int offset, int length) {
- return initialize(root, NodeFinder.perform(root, offset, length));
- }
-
- /*
- * Initializes the finder. Returns error message or <code>null</code> if everything is OK.
- */
- public String initialize(JavaScriptUnit root, ASTNode node) {
- ASTNode controlNode= getBreakOrContinueNode(node);
- if (controlNode != null){
- fContents= getContents(root);
- if (fContents == null)
- return SearchMessages.BreakContinueTargetFinder_cannot_highlight;
-
- fSelected= controlNode;
- fIsBreak= fSelected instanceof BreakStatement;
- fLabel= getLabel();
- return null;
- } else {
- return SearchMessages.BreakContinueTargetFinder_no_break_or_continue_selected;
- }
- }
-
- /* Returns contents or <code>null</code> if there's trouble. */
- private String getContents(JavaScriptUnit root) {
- try {
- IJavaScriptElement rootElem= root.getJavaElement();
- if ((rootElem instanceof ISourceReference))
- return ((ISourceReference)rootElem).getSource();
- else
- return null;
- } catch (JavaScriptModelException e) {
- //We must handle it here because JavaEditor does not expect an exception
-
- /* showing a dialog here would be too heavy but we cannot just
- * swallow the exception */
- JavaScriptPlugin.log(e);
- return null;
- }
- }
-
- //extract the control node: handle labels
- private ASTNode getBreakOrContinueNode(ASTNode selectedNode) {
- if (selectedNode instanceof BreakStatement)
- return selectedNode;
- if (selectedNode instanceof ContinueStatement)
- return selectedNode;
- if (selectedNode instanceof SimpleName && selectedNode.getParent() instanceof BreakStatement)
- return selectedNode.getParent();
- if (selectedNode instanceof SimpleName && selectedNode.getParent() instanceof ContinueStatement)
- return selectedNode.getParent();
- return null;
- }
-
- public List perform() {
- return getNodesToHighlight();
- }
-
- private SimpleName getLabel() {
- if (fIsBreak){
- BreakStatement bs= (BreakStatement) fSelected;
- return bs.getLabel();
- } else {
- ContinueStatement cs= (ContinueStatement) fSelected;
- return cs.getLabel();
- }
- }
-
- private List getNodesToHighlight() {
- ASTNode targetNode= findTargetNode(fSelected);
- if (!isEnclosingStatement(targetNode))
- return Collections.EMPTY_LIST;
-
- List list= new ArrayList();
- ASTNode node= makeFakeNodeForFirstToken(targetNode);
- if (node != null)
- list.add(node);
-
- if (fIsBreak) {
- node= makeFakeNodeForClosingBrace(targetNode);
- if (node != null)
- list.add(node);
- }
-
- return list;
-
- }
-
- private boolean isEnclosingStatement(ASTNode targetNode) {
- return (targetNode != null) && !(targetNode instanceof FunctionDeclaration) && !(targetNode instanceof Initializer);
- }
-
- private ASTNode findTargetNode(ASTNode node) {
- do {
- node= node.getParent();
- } while (keepWalkingUp(node));
- return node;
- }
-
- private ASTNode makeFakeNodeForFirstToken(ASTNode node) {
- try {
- int length= getLengthOfFirstTokenOf(node);
- if (length < 1)
- return node;//fallback
- return makeFakeNode(node.getStartPosition(), length, node.getAST());
- } catch (InvalidInputException e) {
- return node;//fallback
- }
- }
-
- private SimpleName makeFakeNode(int start, int length, AST ast) {
- String fakeName= makeStringOfLength(length);
- SimpleName name= ast.newSimpleName(fakeName);
- name.setSourceRange(start, length);
- return name;
- }
-
- private ASTNode makeFakeNodeForClosingBrace(ASTNode targetNode) {
- ASTNode maybeBlock= getOptionalBlock(targetNode);
- if (maybeBlock == null)
- return null;
-
- /* Ideally, we'd scan backwards to find the '}' token, but it may be an overkill
- * so I'll just assume the closing brace token has a fixed length. */
- return makeFakeNode(ASTNodes.getExclusiveEnd(maybeBlock)-BRACE_LENGTH, BRACE_LENGTH, targetNode.getAST());
- }
-
- /*
- * Block cannot be return type here because SwitchStatement has no block
- * and yet it does have a closing brace.
- */
- private ASTNode getOptionalBlock(ASTNode targetNode) {
- final ASTNode[] maybeBlock= new ASTNode[1];
- targetNode.accept(new ASTVisitor(){
- public boolean visit(ForStatement node) {
- if (node.getBody() instanceof Block)
- maybeBlock[0]= node.getBody();
- return false;
- }
- public boolean visit(ForInStatement node) {
- if (node.getBody() instanceof Block)
- maybeBlock[0]= node.getBody();
- return false;
- }
- public boolean visit(EnhancedForStatement node) {
- if (node.getBody() instanceof Block)
- maybeBlock[0]= node.getBody();
- return false;
- }
- public boolean visit(WhileStatement node) {
- if (node.getBody() instanceof Block)
- maybeBlock[0]= node.getBody();
- return false;
- }
- public boolean visit(DoStatement node) {
- if (node.getBody() instanceof Block)
- maybeBlock[0]= node.getBody();
- return false;
- }
- public boolean visit(SwitchStatement node) {
- maybeBlock[0]= node;
- return false;
- }
- });
- return maybeBlock[0];
- }
-
- private static String makeStringOfLength(int length) {
- char[] chars= new char[length];
- Arrays.fill(chars, 'x');
- return new String(chars);
- }
-
- //must scan because of unicode
- private int getLengthOfFirstTokenOf(ASTNode node) throws InvalidInputException {
- IScanner scanner= ToolFactory.createScanner(true, true, false, true);
- scanner.setSource(getSource(node).toCharArray());
- scanner.getNextToken();
- return scanner.getRawTokenSource().length;
- }
-
- private String getSource(ASTNode node) {
- return fContents.substring(node.getStartPosition(), ASTNodes.getInclusiveEnd(node));
- }
-
- private boolean keepWalkingUp(ASTNode node) {
- if (node == null)
- return false;
- if (isAnyInstanceOf(STOPPERS, node))
- return false;
- if (fLabel != null && LabeledStatement.class.isInstance(node)){
- LabeledStatement ls= (LabeledStatement)node;
- return ! areEqualLabels(ls.getLabel(), fLabel);
- }
- if (fLabel == null && fIsBreak && isAnyInstanceOf(BREAKTARGETS, node))
- return false;
- if (fLabel == null && !fIsBreak && isAnyInstanceOf(CONTINUETARGETS, node))
- return false;
- return true;
- }
-
- //TODO see bug 33739 - resolveBinding always returns null
- //so we just compare names
- private static boolean areEqualLabels(SimpleName labelToMatch, SimpleName labelSelected) {
- return labelSelected.getIdentifier().equals(labelToMatch.getIdentifier());
- }
-
- private static boolean isAnyInstanceOf(Class[] continueTargets, ASTNode node) {
- for (int i= 0; i < continueTargets.length; i++) {
- if (continueTargets[i].isInstance(node))
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesFinder.java
deleted file mode 100644
index 2ad5cf66..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesFinder.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTMatcher;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-
-public class ExceptionOccurrencesFinder extends ASTVisitor implements IOccurrencesFinder {
-
- public static final String IS_EXCEPTION= "isException"; //$NON-NLS-1$
-
- private AST fAST;
- private Name fSelectedName;
-
- private ITypeBinding fException;
- private ASTNode fStart;
- private List fResult;
-
- public ExceptionOccurrencesFinder() {
- fResult= new ArrayList();
- }
-
- public String initialize(JavaScriptUnit root, int offset, int length) {
- return initialize(root, NodeFinder.perform(root, offset, length));
- }
-
- public String initialize(JavaScriptUnit root, ASTNode node) {
- fAST= root.getAST();
- if (!(node instanceof Name)) {
- return SearchMessages.ExceptionOccurrencesFinder_no_exception;
- }
- fSelectedName= ASTNodes.getTopMostName((Name)node);
- ASTNode parent= fSelectedName.getParent();
- FunctionDeclaration decl= resolveMethodDeclaration(parent);
- if (decl != null && methodThrowsException(decl, fSelectedName)) {
- fException= fSelectedName.resolveTypeBinding();
- fStart= decl.getBody();
- } else if (parent instanceof Type) {
- parent= parent.getParent();
- if (parent instanceof SingleVariableDeclaration && parent.getParent() instanceof CatchClause) {
- CatchClause catchClause= (CatchClause)parent.getParent();
- TryStatement tryStatement= (TryStatement)catchClause.getParent();
- if (tryStatement != null) {
- IVariableBinding var= catchClause.getException().resolveBinding();
- if (var != null && var.getType() != null) {
- fException= var.getType();
- fStart= tryStatement.getBody();
- }
- }
- }
- }
- if (fException == null || fStart == null)
- return SearchMessages.ExceptionOccurrencesFinder_no_exception;
- return null;
- }
-
- private FunctionDeclaration resolveMethodDeclaration(ASTNode node) {
- if (node instanceof FunctionDeclaration)
- return (FunctionDeclaration)node;
- JSdoc doc= (JSdoc) ASTNodes.getParent(node, ASTNode.JSDOC);
- if (doc == null)
- return null;
- if (doc.getParent() instanceof FunctionDeclaration)
- return (FunctionDeclaration) doc.getParent();
- return null;
- }
-
- private boolean methodThrowsException(FunctionDeclaration method, Name exception) {
- ASTMatcher matcher = new ASTMatcher();
- for (Iterator iter = method.thrownExceptions().iterator(); iter.hasNext();) {
- Name thrown = (Name)iter.next();
- if (exception.subtreeMatch(matcher, thrown))
- return true;
- }
- return false;
- }
-
- public List perform() {
- fStart.accept(this);
- if (fSelectedName != null) {
- fResult.add(fSelectedName);
- }
- return fResult;
- }
-
- public void collectOccurrenceMatches(IJavaScriptElement element, IDocument document, Collection resultingMatches) {
- HashMap lineToLineElement= new HashMap();
-
- for (Iterator iter= fResult.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode) iter.next();
- int startPosition= node.getStartPosition();
- int length= node.getLength();
- try {
- boolean isException= node == fSelectedName;
- int line= document.getLineOfOffset(startPosition);
- Integer lineInteger= new Integer(line);
- ExceptionOccurrencesGroupKey groupKey= (ExceptionOccurrencesGroupKey) lineToLineElement.get(lineInteger);
- if (groupKey == null) {
- IRegion region= document.getLineInformation(line);
- String lineContents= document.get(region.getOffset(), region.getLength()).trim();
- groupKey= new ExceptionOccurrencesGroupKey(element, line, lineContents, isException);
- lineToLineElement.put(lineInteger, groupKey);
- } else if (isException) {
- // the line with the target exception always has the exception icon:
- groupKey.setException(true);
- }
- Match match= new Match(groupKey, startPosition, length);
- resultingMatches.add(match);
- } catch (BadLocationException e) {
- //nothing
- }
- }
- }
-
- public String getJobLabel() {
- return SearchMessages.ExceptionOccurrencesFinder_searchfor ;
- }
-
- public String getElementName() {
- if (fSelectedName != null) {
- return ASTNodes.asString(fSelectedName);
- }
- return null;
- }
-
- public String getUnformattedPluralLabel() {
- return SearchMessages.ExceptionOccurrencesFinder_label_plural;
- }
-
- public String getUnformattedSingularLabel() {
- return SearchMessages.ExceptionOccurrencesFinder_label_singular;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- return false;
- }
-
- public boolean visit(ClassInstanceCreation node) {
- if (matches(node.resolveConstructorBinding())) {
- fResult.add(node.getType());
- }
- return super.visit(node);
- }
-
- public boolean visit(ConstructorInvocation node) {
- if (matches(node.resolveConstructorBinding())) {
- // mark this
- SimpleName name= fAST.newSimpleName("xxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 4);
- fResult.add(name);
- }
- return super.visit(node);
- }
-
- public boolean visit(FunctionInvocation node) {
- if (matches(node.resolveMethodBinding()))
- fResult.add(node.getName());
- return super.visit(node);
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- if (matches(node.resolveConstructorBinding())) {
- SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 5);
- fResult.add(name);
- }
- return super.visit(node);
- }
-
- public boolean visit(SuperMethodInvocation node) {
- if (matches(node.resolveMethodBinding())) {
- fResult.add(node.getName());
- }
- return super.visit(node);
- }
-
- public boolean visit(ThrowStatement node) {
- if (matches(node.getExpression().resolveTypeBinding())) {
- SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 5);
- fResult.add(name);
-
- }
- return super.visit(node);
- }
-
- public boolean visit(TypeDeclarationStatement node) {
- // don't dive into local type declarations.
- return false;
- }
-
- private boolean matches(IFunctionBinding binding) {
- return false;
- }
-
- private boolean matches(ITypeBinding exception) {
- if (exception == null)
- return false;
- while (exception != null) {
- if (Bindings.equals(fException, exception))
- return true;
- exception= exception.getSuperclass();
- }
- return false;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesGroupKey.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesGroupKey.java
deleted file mode 100644
index 57f0af3d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ExceptionOccurrencesGroupKey.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class ExceptionOccurrencesGroupKey extends JavaElementLine {
- private boolean fIsException;
-
- /**
- * @param element either an IJavaScriptUnit or an IClassFile
- */
- public ExceptionOccurrencesGroupKey(IJavaScriptElement element, int line, String lineContents, boolean isException) {
- super(element, line, lineContents);
- fIsException= isException;
- }
-
- public boolean isException() {
- return fIsException;
- }
-
- public void setException(boolean isException) {
- fIsException= isException;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/FindOccurrencesEngine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/FindOccurrencesEngine.java
deleted file mode 100644
index d41bf29c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/FindOccurrencesEngine.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-public abstract class FindOccurrencesEngine {
-
- private IOccurrencesFinder fFinder;
-
- private static class FindOccurencesClassFileEngine extends FindOccurrencesEngine {
- private IClassFile fClassFile;
-
- public FindOccurencesClassFileEngine(IClassFile file, IOccurrencesFinder finder) {
- super(finder);
- fClassFile= file;
- }
- protected JavaScriptUnit createAST() {
- return JavaScriptPlugin.getDefault().getASTProvider().getAST(fClassFile, ASTProvider.WAIT_YES, null);
- }
- protected IJavaScriptElement getInput() {
- return fClassFile;
- }
- protected ISourceReference getSourceReference() {
- return fClassFile;
- }
- }
-
- private static class FindOccurencesCUEngine extends FindOccurrencesEngine {
- private IJavaScriptUnit fCUnit;
-
- public FindOccurencesCUEngine(IJavaScriptUnit unit, IOccurrencesFinder finder) {
- super(finder);
- fCUnit= unit;
- }
- protected JavaScriptUnit createAST() {
- return JavaScriptPlugin.getDefault().getASTProvider().getAST(fCUnit, ASTProvider.WAIT_YES, null);
- }
- protected IJavaScriptElement getInput() {
- return fCUnit;
- }
- protected ISourceReference getSourceReference() {
- return fCUnit;
- }
- }
-
- protected FindOccurrencesEngine(IOccurrencesFinder finder) {
- fFinder= finder;
- }
-
- public static FindOccurrencesEngine create(IJavaScriptElement root, IOccurrencesFinder finder) {
- if (root == null || finder == null)
- return null;
-
- IJavaScriptUnit unit= (IJavaScriptUnit)root.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (unit != null)
- return new FindOccurencesCUEngine(unit, finder);
- IClassFile cf= (IClassFile)root.getAncestor(IJavaScriptElement.CLASS_FILE);
- if (cf != null)
- return new FindOccurencesClassFileEngine(cf, finder);
- return null;
- }
-
- protected abstract JavaScriptUnit createAST();
-
- protected abstract IJavaScriptElement getInput();
-
- protected abstract ISourceReference getSourceReference();
-
- protected IOccurrencesFinder getOccurrencesFinder() {
- return fFinder;
- }
-
- public String run(int offset, int length) throws JavaScriptModelException {
- ISourceReference sr= getSourceReference();
- if (sr.getSourceRange() == null) {
- return SearchMessages.FindOccurrencesEngine_noSource_text;
- }
-
- final JavaScriptUnit root= createAST();
- if (root == null) {
- return SearchMessages.FindOccurrencesEngine_cannotParse_text;
- }
- String message= fFinder.initialize(root, offset, length);
- if (message != null)
- return message;
-
- final IDocument document= new Document(getSourceReference().getSource());
-
- performNewSearch(fFinder, document, getInput());
- return null;
- }
-
- private void performNewSearch(IOccurrencesFinder finder, IDocument document, IJavaScriptElement element) {
- NewSearchUI.runQueryInBackground(new OccurrencesSearchQuery(finder, document, element));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/GroupAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/GroupAction.java
deleted file mode 100644
index 06f92a1a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/GroupAction.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.action.Action;
-
-
-public class GroupAction extends Action {
- private int fGrouping;
- private JavaSearchResultPage fPage;
-
- public GroupAction(String label, String tooltip, JavaSearchResultPage page, int grouping) {
- super(label);
- setToolTipText(tooltip);
- fPage= page;
- fGrouping= grouping;
- }
-
- public void run() {
- fPage.setGrouping(fGrouping);
- }
-
- public int getGrouping() {
- return fGrouping;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/IOccurrencesFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/IOccurrencesFinder.java
deleted file mode 100644
index d6ebc3c8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/IOccurrencesFinder.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-public interface IOccurrencesFinder {
-
- public String initialize(JavaScriptUnit root, int offset, int length);
-
- public List perform();
-
- public String getJobLabel();
-
- /**
- * Returns the plural label for this finder with 3 placeholders:
- * <ul>
- * <li>{0} for the {@link #getElementName() element name}</li>
- * <li>{1} for the number of results found</li>
- * <li>{2} for the scope (name of the compilation unit)</li>
- * </ul>
- * @return the unformatted label
- */
- public String getUnformattedPluralLabel();
-
- /**
- * Returns the singular label for this finder with 2 placeholders:
- * <ul>
- * <li>{0} for the {@link #getElementName() element name}</li>
- * <li>{1} for the scope (name of the compilation unit)</li>
- * </ul>
- * @return the unformatted label
- */
- public String getUnformattedSingularLabel();
-
- /**
- * Returns the name of the lement to look for or <code>null</code> if the finder hasn't
- * been initialized yet.
- * @return the name of the element
- */
- public String getElementName();
-
- public void collectOccurrenceMatches(IJavaScriptElement element, IDocument document, Collection resultingMatches);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ImplementOccurrencesFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ImplementOccurrencesFinder.java
deleted file mode 100644
index 265597a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/ImplementOccurrencesFinder.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-
-
-/**
- * Finds all implement occurrences of an extended class or an implemented interface.
- *
- *
- */
-public class ImplementOccurrencesFinder implements org.eclipse.wst.jsdt.internal.ui.search.IOccurrencesFinder {
-
-
- private class MethodVisitor extends ASTVisitor {
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.FunctionDeclaration)
- */
- public boolean visit(FunctionDeclaration node) {
- IFunctionBinding binding= node.resolveBinding();
- if (binding != null) {
- IFunctionBinding method= Bindings.findOverriddenMethodInHierarchy(fSelectedType, binding);
- if (method != null)
- fResult.add(node.getName());
- }
- return super.visit(node);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration)
- */
- public boolean visit(AnonymousClassDeclaration node) {
- // don't dive into anonymous type declarations.
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.TypeDeclarationStatement)
- */
- public boolean visit(TypeDeclarationStatement node) {
- // don't dive into local type declarations.
- return false;
- }
- }
-
-
- private ASTNode fStart;
- private List fResult;
- private ASTNode fSelectedNode;
- private ITypeBinding fSelectedType;
-
- public ImplementOccurrencesFinder() {
- fResult= new ArrayList();
- }
-
- public String initialize(JavaScriptUnit root, int offset, int length) {
- return initialize(root, NodeFinder.perform(root, offset, length));
- }
-
- public String initialize(JavaScriptUnit root, ASTNode node) {
- if (!(node instanceof Name))
- return SearchMessages.ImplementOccurrencesFinder_invalidTarget;
-
- fSelectedNode= ASTNodes.getNormalizedNode(node);
- if (!(fSelectedNode instanceof Type))
- return SearchMessages.ImplementOccurrencesFinder_invalidTarget;
-
- ASTNode typeDeclaration= fSelectedNode.getParent();
- if (!(typeDeclaration instanceof AbstractTypeDeclaration))
- return SearchMessages.ImplementOccurrencesFinder_invalidTarget;
-
- fSelectedType= ((Type)fSelectedNode).resolveBinding();
- if (fSelectedType == null)
- return SearchMessages.ImplementOccurrencesFinder_invalidTarget;
-
- fStart= typeDeclaration;
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.search.IOccurrencesFinder#perform()
- */
- public List perform() {
- fStart.accept(new MethodVisitor());
- if (fSelectedNode != null)
- fResult.add(fSelectedNode);
-
- return fResult;
- }
-
- public void collectOccurrenceMatches(IJavaScriptElement element, IDocument document, Collection resultingMatches) {
- for (Iterator iter= fResult.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode) iter.next();
- int startPosition= node.getStartPosition();
- int length= node.getLength();
- try {
- int line= document.getLineOfOffset(startPosition);
- IRegion region= document.getLineInformation(line);
- String lineContents= document.get(region.getOffset(), region.getLength()).trim();
- JavaElementLine groupKey= new JavaElementLine(element, line, lineContents);
- resultingMatches.add(new Match(groupKey, startPosition, length));
- } catch (BadLocationException e) {
- //nothing
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.search.IOccurrencesFinder#getJobLabel()
- */
- public String getJobLabel() {
- return SearchMessages.ImplementOccurrencesFinder_searchfor ;
- }
-
- public String getElementName() {
- if (fSelectedNode != null) {
- return ASTNodes.asString(fSelectedNode);
- }
- return null;
- }
-
- public String getUnformattedPluralLabel() {
- return SearchMessages.ImplementOccurrencesFinder_label_plural;
- }
-
- public String getUnformattedSingularLabel() {
- return SearchMessages.ImplementOccurrencesFinder_label_singular;
- }
-
- public void releaseAST() {
- fStart= null;
- fSelectedType= null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementLine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementLine.java
deleted file mode 100644
index 9a0b3586..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementLine.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class JavaElementLine {
- private IJavaScriptElement fElement;
- private int fLine;
- private String fLineContents;
-
- /**
- * @param element either an IJavaScriptUnit or an IClassFile
- */
- public JavaElementLine(IJavaScriptElement element, int line, String lineContents) {
- fElement= element;
- fLine= line;
- fLineContents= lineContents;
- }
-
- public IJavaScriptElement getJavaElement() {
- return fElement;
- }
-
- public int getLine() {
- return fLine;
- }
-
- public String getLineContents() {
- return fLineContents;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementMatch.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementMatch.java
deleted file mode 100644
index ff002664..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaElementMatch.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.search.ui.text.Match;
-
-/**
- * A search match with additional java-specific info.
- */
-public class JavaElementMatch extends Match {
- private final int fAccuracy;
- private final int fMatchRule;
- private final boolean fIsWriteAccess;
- private final boolean fIsReadAccess;
- private final boolean fIsJavadoc;
- private final boolean fIsSuperInvocation;
-
- JavaElementMatch(Object element, int matchRule, int offset, int length, int accuracy, boolean isReadAccess, boolean isWriteAccess, boolean isJavadoc, boolean isSuperInvocation) {
- super(element, offset, length);
- fAccuracy= accuracy;
- fMatchRule= matchRule;
- fIsWriteAccess= isWriteAccess;
- fIsReadAccess= isReadAccess;
- fIsJavadoc= isJavadoc;
- fIsSuperInvocation= isSuperInvocation;
- }
-
- public int getAccuracy() {
- return fAccuracy;
- }
-
- public boolean isWriteAccess() {
- return fIsWriteAccess;
- }
-
- public boolean isReadAccess() {
- return fIsReadAccess;
- }
-
- public boolean isJavadoc() {
- return fIsJavadoc;
- }
-
- public boolean isSuperInvocation() {
- return fIsSuperInvocation;
- }
-
- public int getMatchRule() {
- return fMatchRule;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaMatchFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaMatchFilter.java
deleted file mode 100644
index c6b2ffb6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaMatchFilter.java
+++ /dev/null
@@ -1,507 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.StringTokenizer;
-
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.search.ui.text.MatchFilter;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.PatternQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-abstract class JavaMatchFilter extends MatchFilter {
-
- public abstract boolean filters(JavaElementMatch match);
-
- /**
- * Returns whether this filter is applicable for this query
- * @param query
- * @return returns <code>true</code> if this match filter is applicable for the given query
- */
- public abstract boolean isApplicable(JavaSearchQuery query);
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.text.MatchFilter#filters(org.eclipse.search.ui.text.Match)
- */
- public boolean filters(Match match) {
- if (match instanceof JavaElementMatch) {
- return filters((JavaElementMatch) match);
- }
- return false;
- }
-
- private static final String SETTINGS_LAST_USED_FILTERS= "filters_last_used"; //$NON-NLS-1$
-
- public static MatchFilter[] getLastUsedFilters() {
- String string= JavaScriptPlugin.getDefault().getDialogSettings().get(SETTINGS_LAST_USED_FILTERS);
- if (string != null && string.length() > 0) {
- return decodeFiltersString(string);
- }
- return getDefaultFilters();
- }
-
- public static void setLastUsedFilters(MatchFilter[] filters) {
- String encoded= encodeFilters(filters);
- JavaScriptPlugin.getDefault().getDialogSettings().put(SETTINGS_LAST_USED_FILTERS, encoded);
- }
-
- public static MatchFilter[] getDefaultFilters() {
- return new MatchFilter[] { IMPORT_FILTER };
- }
-
- private static String encodeFilters(MatchFilter[] enabledFilters) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < enabledFilters.length; i++) {
- MatchFilter matchFilter= enabledFilters[i];
- buf.append(matchFilter.getID());
- buf.append(';');
- }
- return buf.toString();
- }
-
- private static JavaMatchFilter[] decodeFiltersString(String encodedString) {
- StringTokenizer tokenizer= new StringTokenizer(encodedString, String.valueOf(';'));
- HashSet result= new HashSet();
- while (tokenizer.hasMoreTokens()) {
- JavaMatchFilter curr= findMatchFilter(tokenizer.nextToken());
- if (curr != null) {
- result.add(curr);
- }
- }
- return (JavaMatchFilter[]) result.toArray(new JavaMatchFilter[result.size()]);
- }
-
- private static final JavaMatchFilter POTENTIAL_FILTER= new PotentialFilter();
- private static final JavaMatchFilter IMPORT_FILTER= new ImportFilter();
- private static final JavaMatchFilter JAVADOC_FILTER= new JavadocFilter();
- private static final JavaMatchFilter READ_FILTER= new ReadFilter();
- private static final JavaMatchFilter WRITE_FILTER= new WriteFilter();
-
- //private static final JavaMatchFilter POLYMORPHIC_FILTER= new PolymorphicFilter();
- private static final JavaMatchFilter INEXACT_FILTER= new InexactMatchFilter();
- private static final JavaMatchFilter ERASURE_FILTER= new ErasureMatchFilter();
-
- //private static final JavaMatchFilter NON_PUBLIC_FILTER= new NonPublicFilter();
- private static final JavaMatchFilter STATIC_FILTER= new StaticFilter();
- private static final JavaMatchFilter NON_STATIC_FILTER= new NonStaticFilter();
- private static final JavaMatchFilter DEPRECATED_FILTER= new DeprecatedFilter();
- private static final JavaMatchFilter NON_DEPRECATED_FILTER= new NonDeprecatedFilter();
-
- private static final JavaMatchFilter[] ALL_FILTERS= new JavaMatchFilter[] {
- POTENTIAL_FILTER,
- IMPORT_FILTER,
- JAVADOC_FILTER,
- READ_FILTER,
- WRITE_FILTER,
-
- /*POLYMORPHIC_FILTER,*/
- INEXACT_FILTER,
- ERASURE_FILTER,
-
- /* NON_PUBLIC_FILTER,*/
- STATIC_FILTER,
- NON_STATIC_FILTER,
- DEPRECATED_FILTER,
- NON_DEPRECATED_FILTER
- };
-
- public static JavaMatchFilter[] allFilters() {
- return ALL_FILTERS;
- }
-
- public static JavaMatchFilter[] allFilters(JavaSearchQuery query) {
- ArrayList res= new ArrayList();
- for (int i= 0; i < ALL_FILTERS.length; i++) {
- JavaMatchFilter curr= ALL_FILTERS[i];
- if (curr.isApplicable(query)) {
- res.add(curr);
- }
- }
- return (JavaMatchFilter[]) res.toArray(new JavaMatchFilter[res.size()]);
- }
-
- private static JavaMatchFilter findMatchFilter(String id) {
- for (int i= 0; i < ALL_FILTERS.length; i++) {
- JavaMatchFilter matchFilter= ALL_FILTERS[i];
- if (matchFilter.getID().equals(id))
- return matchFilter;
- }
- return null;
- }
-}
-
-class PotentialFilter extends JavaMatchFilter {
- public boolean filters(JavaElementMatch match) {
- return match.getAccuracy() == SearchMatch.A_INACCURATE;
- }
-
- public String getName() {
- return SearchMessages.MatchFilter_PotentialFilter_name;
- }
-
- public String getActionLabel() {
- return SearchMessages.MatchFilter_PotentialFilter_actionLabel;
- }
-
- public String getDescription() {
- return SearchMessages.MatchFilter_PotentialFilter_description;
- }
-
- public boolean isApplicable(JavaSearchQuery query) {
- return true;
- }
-
- public String getID() {
- return "filter_potential"; //$NON-NLS-1$
- }
-}
-
-class ImportFilter extends JavaMatchFilter {
- public boolean filters(JavaElementMatch match) {
- return match.getElement() instanceof IImportDeclaration;
- }
-
- public String getName() {
- return SearchMessages.MatchFilter_ImportFilter_name;
- }
-
- public String getActionLabel() {
- return SearchMessages.MatchFilter_ImportFilter_actionLabel;
- }
-
- public String getDescription() {
- return SearchMessages.MatchFilter_ImportFilter_description;
- }
-
- public boolean isApplicable(JavaSearchQuery query) {
- QuerySpecification spec= query.getSpecification();
- if (spec instanceof ElementQuerySpecification) {
- ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
- IJavaScriptElement element= elementSpec.getElement();
- return element instanceof IType || element instanceof IPackageFragment;
- } else if (spec instanceof PatternQuerySpecification) {
- PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
- int searchFor= patternSpec.getSearchFor();
- return searchFor == IJavaScriptSearchConstants.TYPE || searchFor == IJavaScriptSearchConstants.PACKAGE;
- }
- return false;
- }
-
- public String getID() {
- return "filter_imports"; //$NON-NLS-1$
- }
-}
-
-abstract class VariableFilter extends JavaMatchFilter {
- public boolean isApplicable(JavaSearchQuery query) {
- QuerySpecification spec= query.getSpecification();
- if (spec instanceof ElementQuerySpecification) {
- ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
- IJavaScriptElement element= elementSpec.getElement();
- return element instanceof IField || element instanceof ILocalVariable;
- } else if (spec instanceof PatternQuerySpecification) {
- PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
- return patternSpec.getSearchFor() == IJavaScriptSearchConstants.FIELD;
- }
- return false;
- }
-
-}
-
-class WriteFilter extends VariableFilter {
- public boolean filters(JavaElementMatch match) {
- return match.isWriteAccess() && !match.isReadAccess();
- }
- public String getName() {
- return SearchMessages.MatchFilter_WriteFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_WriteFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_WriteFilter_description;
- }
- public String getID() {
- return "filter_writes"; //$NON-NLS-1$
- }
-}
-
-class ReadFilter extends VariableFilter {
- public boolean filters(JavaElementMatch match) {
- return match.isReadAccess() && !match.isWriteAccess();
- }
- public String getName() {
- return SearchMessages.MatchFilter_ReadFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_ReadFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_ReadFilter_description;
- }
- public String getID() {
- return "filter_reads"; //$NON-NLS-1$
- }
-}
-
-class JavadocFilter extends JavaMatchFilter {
- public boolean filters(JavaElementMatch match) {
- return match.isJavadoc();
- }
- public String getName() {
- return SearchMessages.MatchFilter_JavadocFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_JavadocFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_JavadocFilter_description;
- }
- public boolean isApplicable(JavaSearchQuery query) {
- return true;
- }
- public String getID() {
- return "filter_javadoc"; //$NON-NLS-1$
- }
-}
-
-class PolymorphicFilter extends JavaMatchFilter {
- public boolean filters(JavaElementMatch match) {
- return match.isSuperInvocation();
- }
-
- public String getName() {
- return SearchMessages.MatchFilter_PolymorphicFilter_name;
- }
-
- public String getActionLabel() {
- return SearchMessages.MatchFilter_PolymorphicFilter_actionLabel;
- }
-
- public String getDescription() {
- return SearchMessages.MatchFilter_PolymorphicFilter_description;
- }
-
- public boolean isApplicable(JavaSearchQuery query) {
- QuerySpecification spec= query.getSpecification();
- switch (spec.getLimitTo()) {
- case IJavaScriptSearchConstants.REFERENCES:
- case IJavaScriptSearchConstants.ALL_OCCURRENCES:
- if (spec instanceof ElementQuerySpecification) {
- ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
- return elementSpec.getElement() instanceof IFunction;
- } else if (spec instanceof PatternQuerySpecification) {
- PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
- return patternSpec.getSearchFor() == IJavaScriptSearchConstants.METHOD;
- }
- }
- return false;
- }
-
- public String getID() {
- return "filter_polymorphic"; //$NON-NLS-1$
- }
-}
-
-abstract class GenericTypeFilter extends JavaMatchFilter {
- public boolean isApplicable(JavaSearchQuery query) {
- return false;
- }
-}
-
-class ErasureMatchFilter extends GenericTypeFilter {
- public boolean filters(JavaElementMatch match) {
- return (match.getMatchRule() & (SearchPattern.R_FULL_MATCH | SearchPattern.R_EQUIVALENT_MATCH)) == 0;
- }
- public String getName() {
- return SearchMessages.MatchFilter_ErasureFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_ErasureFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_ErasureFilter_description;
- }
- public String getID() {
- return "filter_erasure"; //$NON-NLS-1$
- }
-}
-
-class InexactMatchFilter extends GenericTypeFilter {
- public boolean filters(JavaElementMatch match) {
- return (match.getMatchRule() & (SearchPattern.R_FULL_MATCH)) == 0;
- }
- public String getName() {
- return SearchMessages.MatchFilter_InexactFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_InexactFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_InexactFilter_description;
- }
- public String getID() {
- return "filter_inexact"; //$NON-NLS-1$
- }
-}
-
-abstract class ModifierFilter extends JavaMatchFilter {
- public boolean isApplicable(JavaSearchQuery query) {
- return true;
- }
-}
-
-class NonPublicFilter extends ModifierFilter {
- public boolean filters(JavaElementMatch match) {
- Object element= match.getElement();
- if (element instanceof IMember) {
- try {
- return ! JdtFlags.isPublic((IMember) element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
- public String getName() {
- return SearchMessages.MatchFilter_NonPublicFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_NonPublicFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_NonPublicFilter_description;
- }
- public String getID() {
- return "filter_non_public"; //$NON-NLS-1$
- }
-}
-
-class StaticFilter extends ModifierFilter {
- public boolean filters(JavaElementMatch match) {
- Object element= match.getElement();
- if (element instanceof IMember) {
- try {
- return JdtFlags.isStatic((IMember) element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
- public String getName() {
- return SearchMessages.MatchFilter_StaticFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_StaticFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_StaticFilter_description;
- }
- public String getID() {
- return "filter_static"; //$NON-NLS-1$
- }
-}
-
-class NonStaticFilter extends ModifierFilter {
- public boolean filters(JavaElementMatch match) {
- Object element= match.getElement();
- if (element instanceof IMember) {
- try {
- return ! JdtFlags.isStatic((IMember) element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
- public String getName() {
- return SearchMessages.MatchFilter_NonStaticFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_NonStaticFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_NonStaticFilter_description;
- }
- public String getID() {
- return "filter_non_static"; //$NON-NLS-1$
- }
-}
-
-class DeprecatedFilter extends ModifierFilter {
- public boolean filters(JavaElementMatch match) {
- Object element= match.getElement();
- if (element instanceof IMember) {
- try {
- return JdtFlags.isDeprecated((IMember) element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
- public String getName() {
- return SearchMessages.MatchFilter_DeprecatedFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_DeprecatedFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_DeprecatedFilter_description;
- }
- public String getID() {
- return "filter_deprecated"; //$NON-NLS-1$
- }
-}
-
-class NonDeprecatedFilter extends ModifierFilter {
- public boolean filters(JavaElementMatch match) {
- Object element= match.getElement();
- if (element instanceof IMember) {
- try {
- return !JdtFlags.isDeprecated((IMember) element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
- public String getName() {
- return SearchMessages.MatchFilter_NonDeprecatedFilter_name;
- }
- public String getActionLabel() {
- return SearchMessages.MatchFilter_NonDeprecatedFilter_actionLabel;
- }
- public String getDescription() {
- return SearchMessages.MatchFilter_NonDeprecatedFilter_description;
- }
- public String getID() {
- return "filter_non_deprecated"; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchContentProvider.java
deleted file mode 100644
index 90b5f883..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchContentProvider.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public abstract class JavaSearchContentProvider implements IStructuredContentProvider {
- protected final Object[] EMPTY_ARR= new Object[0];
-
- private JavaSearchResult fResult;
- private JavaSearchResultPage fPage;
-
- JavaSearchContentProvider(JavaSearchResultPage page) {
- fPage= page;
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- initialize((JavaSearchResult) newInput);
-
- }
-
- protected void initialize(JavaSearchResult result) {
- fResult= result;
- }
-
- public abstract void elementsChanged(Object[] updatedElements);
- public abstract void clear();
-
- public void dispose() {
- // nothing to do
- }
-
- JavaSearchResultPage getPage() {
- return fPage;
- }
-
- JavaSearchResult getSearchResult() {
- return fResult;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchEditorOpener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchEditorOpener.java
deleted file mode 100644
index fa5a4a29..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchEditorOpener.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.IEditorDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IEditorRegistry;
-import org.eclipse.ui.IReusableEditor;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.InternalClassFileEditorInput;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavaSearchEditorOpener {
-
- private IEditorReference fReusedEditor;
-
- public IEditorPart openElement(Object element) throws PartInitException, JavaScriptModelException {
- IWorkbenchPage wbPage= JavaScriptPlugin.getActivePage();
- if (NewSearchUI.reuseEditor())
- return showWithReuse(element, wbPage);
- else
- return showWithoutReuse(element, wbPage);
- }
-
- public IEditorPart openMatch(Match match) throws PartInitException, JavaScriptModelException {
- Object element= getElementToOpen(match);
- return openElement(element);
- }
-
- protected Object getElementToOpen(Match match) {
- return match.getElement();
- }
-
- private IEditorPart showWithoutReuse(Object element, IWorkbenchPage wbPage) throws PartInitException, JavaScriptModelException {
- return EditorUtility.openInEditor(element, false);
- }
-
- private IEditorPart showWithReuse(Object element, IWorkbenchPage wbPage) throws JavaScriptModelException, PartInitException {
- IFile file= getFile(element);
- if (file != null) {
- String editorID= getEditorID(file);
- return showInEditor(wbPage, new FileEditorInput(file), editorID);
- } else {
- IClassFile cf= getClassFile(element);
- if (cf != null)
- return showInEditor(wbPage, new InternalClassFileEditorInput(cf), JavaScriptUI.ID_CF_EDITOR);
- }
- return null;
- }
-
- private IFile getFile(Object element) throws JavaScriptModelException {
- if (element instanceof IFile)
- return (IFile) element;
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement jElement= (IJavaScriptElement) element;
- IJavaScriptUnit cu= (IJavaScriptUnit) jElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- return (IFile) cu.getCorrespondingResource();
- }
- IClassFile cf= (IClassFile) jElement.getAncestor(IJavaScriptElement.CLASS_FILE);
- if (cf != null)
- return (IFile) cf.getCorrespondingResource();
- }
- return null;
- }
-
- private String getEditorID(IFile file) throws PartInitException {
- IEditorDescriptor desc= IDE.getEditorDescriptor(file);
- if (desc == null)
- return JavaScriptPlugin.getDefault().getWorkbench().getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID).getId();
- else
- return desc.getId();
- }
-
- private IEditorPart showInEditor(IWorkbenchPage page, IEditorInput input, String editorId) {
- IEditorPart editor= page.findEditor(input);
- if (editor != null) {
- page.bringToTop(editor);
- return editor;
- }
- IEditorReference reusedEditorRef= fReusedEditor;
- if (reusedEditorRef != null) {
- boolean isOpen= reusedEditorRef.getEditor(false) != null;
- boolean canBeReused= isOpen && !reusedEditorRef.isDirty() && !reusedEditorRef.isPinned();
- if (canBeReused) {
- boolean showsSameInputType= reusedEditorRef.getId().equals(editorId);
- if (!showsSameInputType) {
- page.closeEditors(new IEditorReference[] { reusedEditorRef }, false);
- fReusedEditor= null;
- } else {
- editor= reusedEditorRef.getEditor(true);
- if (editor instanceof IReusableEditor) {
- ((IReusableEditor) editor).setInput(input);
- page.bringToTop(editor);
- return editor;
- }
- }
- }
- }
- // could not reuse
- try {
- editor= page.openEditor(input, editorId, false);
- if (editor instanceof IReusableEditor) {
- IEditorReference reference= (IEditorReference) page.getReference(editor);
- fReusedEditor= reference;
- } else {
- fReusedEditor= null;
- }
- return editor;
- } catch (PartInitException ex) {
- MessageDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), SearchMessages.Search_Error_openEditor_title, SearchMessages.Search_Error_openEditor_message);
- return null;
- }
- }
-
- private IClassFile getClassFile(Object element) {
- if (!(element instanceof IJavaScriptElement))
- return null;
- if (element instanceof IClassFile)
- return (IClassFile) element;
- IJavaScriptElement jElement= (IJavaScriptElement) element;
- if (jElement instanceof IMember)
- return ((IMember) jElement).getClassFile();
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPage.java
deleted file mode 100644
index c4eb57e8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPage.java
+++ /dev/null
@@ -1,976 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.search.ui.ISearchPage;
-import org.eclipse.search.ui.ISearchPageContainer;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.PatternQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-public class JavaSearchPage extends DialogPage implements ISearchPage {
-
- private static class SearchPatternData {
- private int searchFor;
- private int limitTo;
- private String pattern;
- private boolean isCaseSensitive;
- private IJavaScriptElement javaElement;
- private int includeMask;
- private int scope;
- private IWorkingSet[] workingSets;
-
- public SearchPatternData(int searchFor, int limitTo, boolean isCaseSensitive, String pattern, IJavaScriptElement element, int includeMask) {
- this(searchFor, limitTo, pattern, isCaseSensitive, element, ISearchPageContainer.WORKSPACE_SCOPE, null, includeMask);
- }
-
- public SearchPatternData(int searchFor, int limitTo, String pattern, boolean isCaseSensitive, IJavaScriptElement element, int scope, IWorkingSet[] workingSets, int includeMask) {
- this.searchFor= searchFor;
- this.limitTo= limitTo;
- this.pattern= pattern;
- this.isCaseSensitive= isCaseSensitive;
- this.scope= scope;
- this.workingSets= workingSets;
- this.includeMask= includeMask;
-
- setJavaElement(element);
- }
-
- public void setJavaElement(IJavaScriptElement javaElement) {
- this.javaElement= javaElement;
- }
-
- public boolean isCaseSensitive() {
- return isCaseSensitive;
- }
-
- public IJavaScriptElement getJavaElement() {
- return javaElement;
- }
-
- public int getLimitTo() {
- return limitTo;
- }
-
- public String getPattern() {
- return pattern;
- }
-
- public int getScope() {
- return scope;
- }
-
- public int getSearchFor() {
- return searchFor;
- }
-
- public IWorkingSet[] getWorkingSets() {
- return workingSets;
- }
-
- public int getIncludeMask() {
- return includeMask;
- }
-
- public void store(IDialogSettings settings) {
- settings.put("searchFor", searchFor); //$NON-NLS-1$
- settings.put("scope", scope); //$NON-NLS-1$
- settings.put("pattern", pattern); //$NON-NLS-1$
- settings.put("limitTo", limitTo); //$NON-NLS-1$
- settings.put("javaElement", javaElement != null ? javaElement.getHandleIdentifier() : ""); //$NON-NLS-1$ //$NON-NLS-2$
- settings.put("isCaseSensitive", isCaseSensitive); //$NON-NLS-1$
- if (workingSets != null) {
- String[] wsIds= new String[workingSets.length];
- for (int i= 0; i < workingSets.length; i++) {
- wsIds[i]= workingSets[i].getName();
- }
- settings.put("workingSets", wsIds); //$NON-NLS-1$
- } else {
- settings.put("workingSets", new String[0]); //$NON-NLS-1$
- }
- settings.put("includeMask", includeMask); //$NON-NLS-1$
- }
-
- public static SearchPatternData create(IDialogSettings settings) {
- String pattern= settings.get("pattern"); //$NON-NLS-1$
- if (pattern.length() == 0) {
- return null;
- }
- IJavaScriptElement elem= null;
- String handleId= settings.get("javaElement"); //$NON-NLS-1$
- if (handleId != null && handleId.length() > 0) {
- IJavaScriptElement restored= JavaScriptCore.create(handleId);
- if (restored != null && isSearchableType(restored) && restored.exists()) {
- elem= restored;
- }
- }
- String[] wsIds= settings.getArray("workingSets"); //$NON-NLS-1$
- IWorkingSet[] workingSets= null;
- if (wsIds != null && wsIds.length > 0) {
- IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
- workingSets= new IWorkingSet[wsIds.length];
- for (int i= 0; workingSets != null && i < wsIds.length; i++) {
- workingSets[i]= workingSetManager.getWorkingSet(wsIds[i]);
- if (workingSets[i] == null) {
- workingSets= null;
- }
- }
- }
-
- try {
- int searchFor= settings.getInt("searchFor"); //$NON-NLS-1$
- int scope= settings.getInt("scope"); //$NON-NLS-1$
- int limitTo= settings.getInt("limitTo"); //$NON-NLS-1$
- boolean isCaseSensitive= settings.getBoolean("isCaseSensitive"); //$NON-NLS-1$
-
- int includeMask;
- if (settings.get("includeMask") != null) { //$NON-NLS-1$
- includeMask= settings.getInt("includeMask"); //$NON-NLS-1$
- } else {
- includeMask= JavaSearchScopeFactory.NO_JRE;
- if (settings.get("includeJRE") == null ? forceIncludeAll(limitTo, elem) : settings.getBoolean("includeJRE")) { //$NON-NLS-1$ //$NON-NLS-2$
- includeMask= JavaSearchScopeFactory.ALL;
- }
- }
- return new SearchPatternData(searchFor, limitTo, pattern, isCaseSensitive, elem, scope, workingSets, includeMask);
- } catch (NumberFormatException e) {
- return null;
- }
- }
-
- }
-
- // search for
- private final static int TYPE= IJavaScriptSearchConstants.TYPE;
- private final static int METHOD= IJavaScriptSearchConstants.METHOD;
-// private final static int PACKAGE= IJavaScriptSearchConstants.PACKAGE;
- private final static int CONSTRUCTOR= IJavaScriptSearchConstants.CONSTRUCTOR;
- private final static int FIELD= IJavaScriptSearchConstants.FIELD;
- private final static int VAR= IJavaScriptSearchConstants.VAR;
- private final static int FUNCTION= IJavaScriptSearchConstants.FUNCTION;
-
- // limit to
- private final static int DECLARATIONS= IJavaScriptSearchConstants.DECLARATIONS;
-// private final static int IMPLEMENTORS= IJavaScriptSearchConstants.IMPLEMENTORS;
- private final static int REFERENCES= IJavaScriptSearchConstants.REFERENCES;
- private final static int ALL_OCCURRENCES= IJavaScriptSearchConstants.ALL_OCCURRENCES;
- private final static int READ_ACCESSES= IJavaScriptSearchConstants.READ_ACCESSES;
- private final static int WRITE_ACCESSES= IJavaScriptSearchConstants.WRITE_ACCESSES;
-
- public static final String PARTICIPANT_EXTENSION_POINT= "org.eclipse.wst.jsdt.ui.queryParticipants"; //$NON-NLS-1$
-
- public static final String EXTENSION_POINT_ID= "org.eclipse.wst.jsdt.ui.JavaSearchPage"; //$NON-NLS-1$
-
- private static final int HISTORY_SIZE= 12;
-
- // Dialog store id constants
- private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$
- private final static String STORE_CASE_SENSITIVE= "CASE_SENSITIVE"; //$NON-NLS-1$
- private final static String STORE_INCLUDE_MASK= "INCLUDE_MASK"; //$NON-NLS-1$
- private final static String STORE_HISTORY= "HISTORY"; //$NON-NLS-1$
- private final static String STORE_HISTORY_SIZE= "HISTORY_SIZE"; //$NON-NLS-1$
-
- private final List fPreviousSearchPatterns;
-
- private SearchPatternData fInitialData;
- private IJavaScriptElement fJavaElement;
- private boolean fFirstTime= true;
- private IDialogSettings fDialogSettings;
- private boolean fIsCaseSensitive;
-
- private Combo fPattern;
- private ISearchPageContainer fContainer;
- private Button fCaseSensitive;
-
- private Button[] fSearchFor;
- private Button[] fLimitTo;
- private Button[] fIncludeMasks;
-
-
- /**
- *
- */
- public JavaSearchPage() {
- fPreviousSearchPatterns= new ArrayList();
- }
-
-
- //---- Action Handling ------------------------------------------------
-
- public boolean performAction() {
- return performNewSearch();
- }
-
- private boolean performNewSearch() {
- SearchPatternData data= getPatternData();
-
- // Setup search scope
- IJavaScriptSearchScope scope= null;
- String scopeDescription= ""; //$NON-NLS-1$
-
- int searchFor= data.getSearchFor();
- int limitTo= data.getLimitTo();
-
- int includeMask= data.getIncludeMask();
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
-
- switch (getContainer().getSelectedScope()) {
- case ISearchPageContainer.WORKSPACE_SCOPE:
- scopeDescription= factory.getWorkspaceScopeDescription(includeMask);
- scope= factory.createWorkspaceScope(includeMask);
- break;
- case ISearchPageContainer.SELECTION_SCOPE:
- IJavaScriptElement[] javaElements= factory.getJavaElements(getContainer().getSelection());
- scope= factory.createJavaSearchScope(javaElements, includeMask);
- scopeDescription= factory.getSelectionScopeDescription(javaElements, includeMask);
- break;
- case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: {
- String[] projectNames= getContainer().getSelectedProjectNames();
- scope= factory.createJavaProjectSearchScope(projectNames, includeMask);
- scopeDescription= factory.getProjectScopeDescription(projectNames, includeMask);
- break;
- }
- case ISearchPageContainer.WORKING_SET_SCOPE: {
- IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
- // should not happen - just to be sure
- if (workingSets == null || workingSets.length < 1)
- return false;
- scopeDescription= factory.getWorkingSetScopeDescription(workingSets, includeMask);
- scope= factory.createJavaSearchScope(workingSets, includeMask);
- SearchUtil.updateLRUWorkingSets(workingSets);
- }
- }
-
- QuerySpecification querySpec= null;
- if (data.getJavaElement() != null && getPattern().equals(fInitialData.getPattern())) {
- if (limitTo == REFERENCES)
- SearchUtil.warnIfBinaryConstant(data.getJavaElement(), getShell());
- querySpec= new ElementQuerySpecification(data.getJavaElement(), limitTo, scope, scopeDescription);
- } else {
- querySpec= new PatternQuerySpecification(data.getPattern(), searchFor, data.isCaseSensitive(), data.getLimitTo(), scope, scopeDescription);
- data.setJavaElement(null);
- }
-
- JavaSearchQuery textSearchJob= new JavaSearchQuery(querySpec);
- NewSearchUI.runQueryInBackground(textSearchJob);
- return true;
- }
-
- private int getLimitTo() {
- for (int i= 0; i < fLimitTo.length; i++) {
- Button button= fLimitTo[i];
- if (button.getSelection()) {
- return getIntData(button);
- }
- }
- return -1;
- }
-
- private int setLimitTo(int searchFor, int limitTo) {
-// if (searchFor != TYPE && limitTo == IMPLEMENTORS) {
-// limitTo= REFERENCES;
-// }
-
- if ( searchFor != FIELD && searchFor != VAR && (limitTo == READ_ACCESSES || limitTo == WRITE_ACCESSES)) {
- limitTo= REFERENCES;
- }
-
- for (int i= 0; i < fLimitTo.length; i++) {
- Button button= fLimitTo[i];
- int val= getIntData(button);
- button.setSelection(limitTo == val);
-
- switch (val) {
- case DECLARATIONS:
- case REFERENCES:
- case ALL_OCCURRENCES:
- button.setEnabled(true);
- break;
-// case IMPLEMENTORS:
-// button.setEnabled(searchFor == TYPE);
-// break;
- case READ_ACCESSES:
- case WRITE_ACCESSES:
- button.setEnabled(searchFor == FIELD || searchFor==VAR);
- break;
- }
- }
- return limitTo;
- }
-
- private int getIncludeMask() {
- int mask= 0;
- for (int i= 0; i < fIncludeMasks.length; i++) {
- Button button= fIncludeMasks[i];
- if (button.getSelection()) {
- mask |= getIntData(button);
- }
- }
- return mask;
- }
-
- private void setIncludeMask(int includeMask, int limitTo) {
- for (int i= 0; i < fIncludeMasks.length; i++) {
- Button button= fIncludeMasks[i];
- button.setSelection((includeMask & getIntData(button)) != 0);
- }
- }
-
-
- private String[] getPreviousSearchPatterns() {
- // Search results are not persistent
- int patternCount= fPreviousSearchPatterns.size();
- String [] patterns= new String[patternCount];
- for (int i= 0; i < patternCount; i++)
- patterns[i]= ((SearchPatternData) fPreviousSearchPatterns.get(i)).getPattern();
- return patterns;
- }
-
- private int getSearchFor() {
- for (int i= 0; i < fSearchFor.length; i++) {
- Button button= fSearchFor[i];
- if (button.getSelection()) {
- return getIntData(button);
- }
- }
- Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$
- return -1;
- }
-
- private void setSearchFor(int searchFor) {
- for (int i= 0; i < fSearchFor.length; i++) {
- Button button= fSearchFor[i];
- button.setSelection(searchFor == getIntData(button));
- }
- }
-
- private int getIntData(Button button) {
- return ((Integer) button.getData()).intValue();
- }
-
- private String getPattern() {
- return fPattern.getText();
- }
-
-
- private SearchPatternData findInPrevious(String pattern) {
- for (Iterator iter= fPreviousSearchPatterns.iterator(); iter.hasNext();) {
- SearchPatternData element= (SearchPatternData) iter.next();
- if (pattern.equals(element.getPattern())) {
- return element;
- }
- }
- return null;
- }
-
- /**
- * Return search pattern data and update previous searches.
- * An existing entry will be updated.
- * @return the pattern data
- */
- private SearchPatternData getPatternData() {
- String pattern= getPattern();
- SearchPatternData match= findInPrevious(pattern);
- if (match != null) {
- fPreviousSearchPatterns.remove(match);
- }
- match= new SearchPatternData(
- getSearchFor(),
- getLimitTo(),
- pattern,
- fCaseSensitive.getSelection(),
- fJavaElement,
- getContainer().getSelectedScope(),
- getContainer().getSelectedWorkingSets(),
- getIncludeMask()
- );
-
- fPreviousSearchPatterns.add(0, match); // insert on top
- return match;
- }
-
- /*
- * Implements method from IDialogPage
- */
- public void setVisible(boolean visible) {
- if (visible && fPattern != null) {
- if (fFirstTime) {
- fFirstTime= false;
- // Set item and text here to prevent page from resizing
- fPattern.setItems(getPreviousSearchPatterns());
- initSelections();
- }
- fPattern.setFocus();
- }
- updateOKStatus();
- super.setVisible(visible);
- }
-
- public boolean isValid() {
- return true;
- }
-
- //---- Widget creation ------------------------------------------------
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- readConfiguration();
-
- Composite result= new Composite(parent, SWT.NONE);
-
- GridLayout layout= new GridLayout(2, false);
- layout.horizontalSpacing= 10;
- result.setLayout(layout);
-
- Control expressionComposite= createExpression(result);
- expressionComposite.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
-
- Label separator= new Label(result, SWT.NONE);
- separator.setVisible(false);
- GridData data= new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1);
- data.heightHint= convertHeightInCharsToPixels(1) / 3;
- separator.setLayoutData(data);
-
- Control searchFor= createSearchFor(result);
- searchFor.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1));
-
- Control limitTo= createLimitTo(result);
- limitTo.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1));
-
- Control includeMask= createIncludeMask(result);
- includeMask.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1));
-
- //createParticipants(result);
-
- SelectionAdapter javaElementInitializer= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- if (getSearchFor() == fInitialData.getSearchFor())
- fJavaElement= fInitialData.getJavaElement();
- else
- fJavaElement= null;
- int limitToVal= setLimitTo(getSearchFor(), getLimitTo());
- setIncludeMask(getIncludeMask(), limitToVal);
- doPatternModified();
- }
- };
-
- for (int i= 0; i < fSearchFor.length; i++) {
- fSearchFor[i].addSelectionListener(javaElementInitializer);
- }
-
- setControl(result);
-
- Dialog.applyDialogFont(result);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE);
- }
-
-
- /*private Control createParticipants(Composite result) {
- if (!SearchParticipantsExtensionPoint.hasAnyParticipants())
- return new Composite(result, SWT.NULL);
- Button selectParticipants= new Button(result, SWT.PUSH);
- selectParticipants.setText(SearchMessages.getString("SearchPage.select_participants.label")); //$NON-NLS-1$
- GridData gd= new GridData();
- gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING;
- gd.horizontalAlignment= GridData.HORIZONTAL_ALIGN_END;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalAlignment= GridData.END;
- gd.horizontalSpan= 2;
- selectParticipants.setLayoutData(gd);
- selectParticipants.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencePageSupport.showPreferencePage(getShell(), "org.eclipse.wst.jsdt.ui.preferences.SearchParticipantsExtensionPoint", new SearchParticipantsExtensionPoint()); //$NON-NLS-1$
- }
-
- });
- return selectParticipants;
- }*/
-
-
- private Control createExpression(Composite parent) {
- Composite result= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout(2, false);
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- result.setLayout(layout);
-
- // Pattern text + info
- Label label= new Label(result, SWT.LEFT);
- label.setText(SearchMessages.SearchPage_expression_label);
- label.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1));
-
- // Pattern combo
- fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER);
- fPattern.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- handlePatternSelected();
- updateOKStatus();
- }
- });
- fPattern.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doPatternModified();
- updateOKStatus();
-
- }
- });
- TextFieldNavigationHandler.install(fPattern);
- GridData data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
- data.widthHint= convertWidthInCharsToPixels(50);
- fPattern.setLayoutData(data);
-
- // Ignore case checkbox
- fCaseSensitive= new Button(result, SWT.CHECK);
- fCaseSensitive.setText(SearchMessages.SearchPage_expression_caseSensitive);
- fCaseSensitive.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fIsCaseSensitive= fCaseSensitive.getSelection();
- }
- });
- fCaseSensitive.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 1, 1));
-
- return result;
- }
-
- final void updateOKStatus() {
- boolean isValid= isValidSearchPattern();
- getContainer().setPerformActionEnabled(isValid);
- }
-
- private boolean isValidSearchPattern() {
- if (getPattern().length() == 0) {
- return false;
- }
- if (fJavaElement != null) {
- return true;
- }
- return SearchPattern.createPattern(getPattern(), getSearchFor(), getLimitTo(), SearchPattern.R_EXACT_MATCH) != null;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- */
- public void dispose() {
- writeConfiguration();
- super.dispose();
- }
-
- private void doPatternModified() {
- if (fInitialData != null && getPattern().equals(fInitialData.getPattern()) && fInitialData.getJavaElement() != null && fInitialData.getSearchFor() == getSearchFor()) {
- fCaseSensitive.setEnabled(false);
- fCaseSensitive.setSelection(true);
- fJavaElement= fInitialData.getJavaElement();
- } else {
- fCaseSensitive.setEnabled(true);
- fCaseSensitive.setSelection(fIsCaseSensitive);
- fJavaElement= null;
- }
- }
-
- private void handlePatternSelected() {
- int selectionIndex= fPattern.getSelectionIndex();
- if (selectionIndex < 0 || selectionIndex >= fPreviousSearchPatterns.size())
- return;
-
- SearchPatternData initialData= (SearchPatternData) fPreviousSearchPatterns.get(selectionIndex);
-
- setSearchFor(initialData.getSearchFor());
- int limitToVal= setLimitTo(initialData.getSearchFor(), initialData.getLimitTo());
- setIncludeMask(initialData.getIncludeMask(), limitToVal);
-
- fPattern.setText(initialData.getPattern());
- fIsCaseSensitive= initialData.isCaseSensitive();
- fJavaElement= initialData.getJavaElement();
- fCaseSensitive.setEnabled(fJavaElement == null);
- fCaseSensitive.setSelection(initialData.isCaseSensitive());
-
-
- if (initialData.getWorkingSets() != null)
- getContainer().setSelectedWorkingSets(initialData.getWorkingSets());
- else
- getContainer().setSelectedScope(initialData.getScope());
-
- fInitialData= initialData;
- }
-
-
- private Control createSearchFor(Composite parent) {
- Group result= new Group(parent, SWT.NONE);
- result.setText(SearchMessages.SearchPage_searchFor_label);
- result.setLayout(new GridLayout(2, true));
-
- fSearchFor= new Button[] {
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_function, FUNCTION, true),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_var, VAR, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_method, METHOD, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_field, FIELD, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_type, TYPE, false),
-// createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_package, PACKAGE, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_searchFor_constructor, CONSTRUCTOR, false)
- };
-
- // Fill with dummy radio buttons
- Label filler= new Label(result, SWT.NONE);
- filler.setVisible(false);
- filler.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
-
- return result;
- }
-
- private Control createLimitTo(Composite parent) {
- Group result= new Group(parent, SWT.NONE);
- result.setText(SearchMessages.SearchPage_limitTo_label);
- result.setLayout(new GridLayout(2, true));
-
- fLimitTo= new Button[] {
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_declarations, DECLARATIONS, false),
-// createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_implementors, IMPLEMENTORS, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_references, REFERENCES, true),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_allOccurrences, ALL_OCCURRENCES, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_readReferences, READ_ACCESSES, false),
- createButton(result, SWT.RADIO, SearchMessages.SearchPage_limitTo_writeReferences, WRITE_ACCESSES, false)
- };
-
- SelectionAdapter listener= new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- updateUseJRE();
- }
- };
- for (int i= 0; i < fLimitTo.length; i++) {
- fLimitTo[i].addSelectionListener(listener);
- }
- return result;
- }
-
- private Control createIncludeMask(Composite parent) {
- Group result= new Group(parent, SWT.NONE);
- result.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- result.setText(SearchMessages.SearchPage_searchIn_label);
- result.setLayout(new GridLayout(4, false));
- fIncludeMasks= new Button[] {
- createButton(result, SWT.CHECK, SearchMessages.SearchPage_searchIn_sources, JavaSearchScopeFactory.SOURCES, true),
- createButton(result, SWT.CHECK, SearchMessages.SearchPage_searchIn_projects, JavaSearchScopeFactory.PROJECTS, true),
- createButton(result, SWT.CHECK, SearchMessages.SearchPage_searchIn_jre, JavaSearchScopeFactory.JRE, false),
- createButton(result, SWT.CHECK, SearchMessages.SearchPage_searchIn_libraries, JavaSearchScopeFactory.LIBS, true),
- };
- return result;
- }
-
- private Button createButton(Composite parent, int style, String text, int data, boolean isSelected) {
- Button button= new Button(parent, style);
- button.setText(text);
- button.setData(new Integer(data));
- button.setLayoutData(new GridData());
- button.setSelection(isSelected);
- return button;
- }
-
- private void initSelections() {
- ISelection sel= getContainer().getSelection();
- SearchPatternData initData= null;
-
- if (sel instanceof IStructuredSelection) {
- initData= tryStructuredSelection((IStructuredSelection) sel);
- } else if (sel instanceof ITextSelection) {
- IEditorPart activePart= getActiveEditor();
- if (activePart instanceof JavaEditor) {
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolve((JavaEditor) activePart);
- if (elements != null && elements.length > 0) {
- initData= determineInitValuesFrom(elements[0]);
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- if (initData == null) {
- initData= trySimpleTextSelection((ITextSelection) sel);
- }
- }
- if (initData == null) {
- initData= getDefaultInitValues();
- }
-
- fInitialData= initData;
- fJavaElement= initData.getJavaElement();
- fCaseSensitive.setSelection(initData.isCaseSensitive());
- fCaseSensitive.setEnabled(fJavaElement == null);
-
- setSearchFor(initData.getSearchFor());
- int limitToVal= setLimitTo(initData.getSearchFor(), initData.getLimitTo());
- setIncludeMask(initData.getIncludeMask(), limitToVal);
-
- fPattern.setText(initData.getPattern());
- }
-
- private void updateUseJRE() {
- setIncludeMask(getIncludeMask(), getLimitTo());
- }
-
- private static boolean forceIncludeAll(int limitTo, IJavaScriptElement elem) {
- return elem != null && (limitTo == DECLARATIONS /*|| limitTo == IMPLEMENTORS*/);
- }
-
- private SearchPatternData tryStructuredSelection(IStructuredSelection selection) {
- if (selection == null || selection.size() > 1)
- return null;
-
- Object o= selection.getFirstElement();
- SearchPatternData res= null;
- if (o instanceof IJavaScriptElement) {
- res= determineInitValuesFrom((IJavaScriptElement) o);
-// } else if (o instanceof LogicalPackage) {
-// LogicalPackage lp= (LogicalPackage)o;
-// return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive, lp.getElementName(), null, getLastIncludeMask());
- } else if (o instanceof IAdaptable) {
- IJavaScriptElement element= (IJavaScriptElement) ((IAdaptable) o).getAdapter(IJavaScriptElement.class);
- if (element != null) {
- res= determineInitValuesFrom(element);
- }
- }
- if (res == null && o instanceof IAdaptable) {
- IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class);
- if (adapter != null) {
- return new SearchPatternData(VAR, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null, getLastIncludeMask());
- }
- }
- return res;
- }
-
- final static boolean isSearchableType(IJavaScriptElement element) {
- switch (element.getElementType()) {
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.IMPORT_DECLARATION:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.METHOD:
- return true;
- }
- return false;
- }
-
- private SearchPatternData determineInitValuesFrom(IJavaScriptElement element) {
- try {
- //JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- //boolean isInsideJRE= factory.isInsideJRE(element);
- int includeMask= getLastIncludeMask();
-
- switch (element.getElementType()) {
-// case IJavaScriptElement.PACKAGE_FRAGMENT:
-// case IJavaScriptElement.PACKAGE_DECLARATION:
-// return new SearchPatternData(PACKAGE, REFERENCES, true, element.getElementName(), element, includeMask);
-// case IJavaScriptElement.IMPORT_DECLARATION: {
-// IImportDeclaration declaration= (IImportDeclaration) element;
-// if (declaration.isOnDemand()) {
-// String name= Signature.getQualifier(declaration.getElementName());
-// return new SearchPatternData(PACKAGE, DECLARATIONS, true, name, element, JavaSearchScopeFactory.ALL);
-// }
-// return new SearchPatternData(TYPE, DECLARATIONS, true, element.getElementName(), element, JavaSearchScopeFactory.ALL);
-// }
- case IJavaScriptElement.TYPE:
- return new SearchPatternData(TYPE, REFERENCES, true, PatternStrings.getTypeSignature((IType) element), element, includeMask);
- case IJavaScriptElement.JAVASCRIPT_UNIT: {
- IType mainType= ((IJavaScriptUnit) element).findPrimaryType();
- if (mainType != null) {
- return new SearchPatternData(TYPE, REFERENCES, true, PatternStrings.getTypeSignature(mainType), mainType, includeMask);
- }
- break;
- }
- case IJavaScriptElement.CLASS_FILE: {
- IType mainType= ((IClassFile) element).getType();
- if (mainType.exists()) {
- return new SearchPatternData(TYPE, REFERENCES, true, PatternStrings.getTypeSignature(mainType), mainType, includeMask);
- }
- break;
- }
- case IJavaScriptElement.FIELD:
- IField field = (IField) element;
- return new SearchPatternData(field.getParent().getElementType()==IJavaScriptElement.TYPE?FIELD:VAR, REFERENCES, true,
- PatternStrings.getFieldSignature(field), element, includeMask);
- case IJavaScriptElement.METHOD:
- IFunction method= (IFunction) element;
- int searchFor= method.isConstructor() ? CONSTRUCTOR : METHOD;
- if (method.getParent().getElementType()!=IJavaScriptElement.TYPE)
- searchFor=FUNCTION;
- return new SearchPatternData(searchFor, REFERENCES, true, PatternStrings.getMethodSignature(method), element, includeMask);
- }
-
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- ExceptionHandler.handle(e, SearchMessages.Search_Error_javaElementAccess_title, SearchMessages.Search_Error_javaElementAccess_message);
- }
- // element might not exist
- }
- return null;
- }
-
- private SearchPatternData trySimpleTextSelection(ITextSelection selection) {
- String selectedText= selection.getText();
- if (selectedText != null && selectedText.length() > 0) {
- int i= 0;
- while (i < selectedText.length() && !IndentManipulation.isLineDelimiterChar(selectedText.charAt(i))) {
- i++;
- }
- if (i > 0) {
- return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, selectedText.substring(0, i), null, JavaSearchScopeFactory.ALL);
- }
- }
- return null;
- }
-
- private SearchPatternData getDefaultInitValues() {
- if (!fPreviousSearchPatterns.isEmpty()) {
- return (SearchPatternData) fPreviousSearchPatterns.get(0);
- }
-
- return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null, getLastIncludeMask()); //$NON-NLS-1$
- }
-
- private int getLastIncludeMask() {
- try {
- return getDialogSettings().getInt(STORE_INCLUDE_MASK);
- } catch (NumberFormatException e) {
- return JavaSearchScopeFactory.NO_JRE;
- }
- }
-
- /*
- * Implements method from ISearchPage
- */
- public void setContainer(ISearchPageContainer container) {
- fContainer= container;
- }
-
- /**
- * Returns the search page's container.
- * @return the search page container
- */
- private ISearchPageContainer getContainer() {
- return fContainer;
- }
-
- private IEditorPart getActiveEditor() {
- IWorkbenchPage activePage= JavaScriptPlugin.getActivePage();
- if (activePage != null) {
- return activePage.getActiveEditor();
- }
- return null;
- }
-
- //--------------- Configuration handling --------------
-
- /**
- * Returns the page settings for this Java search page.
- *
- * @return the page settings to be used
- */
- private IDialogSettings getDialogSettings() {
- if (fDialogSettings == null) {
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettingsSection(PAGE_NAME);
- }
- return fDialogSettings;
- }
-
- /**
- * Initializes itself from the stored page settings.
- */
- private void readConfiguration() {
- IDialogSettings s= getDialogSettings();
- fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE);
-
- try {
- int historySize= s.getInt(STORE_HISTORY_SIZE);
- for (int i= 0; i < historySize; i++) {
- IDialogSettings histSettings= s.getSection(STORE_HISTORY + i);
- if (histSettings != null) {
- SearchPatternData data= SearchPatternData.create(histSettings);
- if (data != null) {
- fPreviousSearchPatterns.add(data);
- }
- }
- }
- } catch (NumberFormatException e) {
- // ignore
- }
- }
-
- /**
- * Stores the current configuration in the dialog store.
- */
- private void writeConfiguration() {
- IDialogSettings s= getDialogSettings();
- s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
- s.put(STORE_INCLUDE_MASK, getIncludeMask());
-
- int historySize= Math.min(fPreviousSearchPatterns.size(), HISTORY_SIZE);
- s.put(STORE_HISTORY_SIZE, historySize);
- for (int i= 0; i < historySize; i++) {
- IDialogSettings histSettings= s.addNewSection(STORE_HISTORY + i);
- SearchPatternData data= ((SearchPatternData) fPreviousSearchPatterns.get(i));
- data.store(histSettings);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPageScoreComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPageScoreComputer.java
deleted file mode 100644
index 7001add8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchPageScoreComputer.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.search.ui.ISearchPageScoreComputer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-
-public class JavaSearchPageScoreComputer implements ISearchPageScoreComputer {
-
- public int computeScore(String id, Object element) {
- if (!JavaSearchPage.EXTENSION_POINT_ID.equals(id))
- // Can't decide
- return ISearchPageScoreComputer.UNKNOWN;
-
- if (element instanceof IJavaScriptElement || element instanceof IClassFileEditorInput || element instanceof LogicalPackage)
- return 90;
-
- return ISearchPageScoreComputer.LOWEST;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java
deleted file mode 100644
index 62cebcba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.ISearchResult;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.SearchUtils;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.IMatchPresentation;
-import org.eclipse.wst.jsdt.ui.search.IQueryParticipant;
-import org.eclipse.wst.jsdt.ui.search.ISearchRequestor;
-import org.eclipse.wst.jsdt.ui.search.PatternQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-public class JavaSearchQuery implements ISearchQuery {
-
- private static final String PERF_SEARCH_PARTICIPANT= "org.eclipse.wst.jsdt.ui/perf/search/participants"; //$NON-NLS-1$
-
- private ISearchResult fResult;
- private final QuerySpecification fPatternData;
-
- public JavaSearchQuery(QuerySpecification data) {
- if (data == null) {
- throw new IllegalArgumentException("data must not be null"); //$NON-NLS-1$
- }
- fPatternData= data;
- }
-
- private static class SearchRequestor implements ISearchRequestor {
- private IQueryParticipant fParticipant;
- private JavaSearchResult fSearchResult;
- public void reportMatch(Match match) {
- IMatchPresentation participant= fParticipant.getUIParticipant();
- if (participant == null || match.getElement() instanceof IJavaScriptElement || match.getElement() instanceof IResource) {
- fSearchResult.addMatch(match);
- } else {
- fSearchResult.addMatch(match, participant);
- }
- }
-
- protected SearchRequestor(IQueryParticipant participant, JavaSearchResult result) {
- super();
- fParticipant= participant;
- fSearchResult= result;
- }
- }
-
- public IStatus run(IProgressMonitor monitor) {
- final JavaSearchResult textResult= (JavaSearchResult) getSearchResult();
- textResult.removeAll();
- // Don't need to pass in working copies in 3.0 here
- SearchEngine engine= new SearchEngine();
- try {
-
- int totalTicks= 1000;
- IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(fPatternData.getScope());
- final SearchParticipantRecord[] participantDescriptors= SearchParticipantsExtensionPoint.getInstance().getSearchParticipants(projects);
- final int[] ticks= new int[participantDescriptors.length];
- for (int i= 0; i < participantDescriptors.length; i++) {
- final int iPrime= i;
- ISafeRunnable runnable= new ISafeRunnable() {
- public void handleException(Throwable exception) {
- ticks[iPrime]= 0;
- String message= SearchMessages.JavaSearchQuery_error_participant_estimate;
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, message, exception));
- }
-
- public void run() throws Exception {
- ticks[iPrime]= participantDescriptors[iPrime].getParticipant().estimateTicks(fPatternData);
- }
- };
-
- SafeRunner.run(runnable);
- totalTicks+= ticks[i];
- }
-
- SearchPattern pattern;
- String stringPattern;
-
- if (fPatternData instanceof ElementQuerySpecification) {
- IJavaScriptElement element= ((ElementQuerySpecification) fPatternData).getElement();
- stringPattern= JavaScriptElementLabels.getElementLabel(element, JavaScriptElementLabels.ALL_DEFAULT);
- if (!element.exists()) {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(SearchMessages.JavaSearchQuery_error_element_does_not_exist, stringPattern), null);
- }
- pattern= SearchPattern.createPattern(element, fPatternData.getLimitTo(), SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
- } else {
- PatternQuerySpecification patternSpec = (PatternQuerySpecification) fPatternData;
- stringPattern= patternSpec.getPattern();
- int matchMode= getMatchMode(stringPattern) | SearchPattern.R_ERASURE_MATCH;
- if (patternSpec.isCaseSensitive())
- matchMode |= SearchPattern.R_CASE_SENSITIVE;
- pattern= SearchPattern.createPattern(patternSpec.getPattern(), patternSpec.getSearchFor(), patternSpec.getLimitTo(), matchMode);
- }
-
- if (pattern == null) {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, Messages.format(SearchMessages.JavaSearchQuery_error_unsupported_pattern, stringPattern), null);
- }
- monitor.beginTask(Messages.format(SearchMessages.JavaSearchQuery_task_label, stringPattern), totalTicks);
- IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000);
-
- boolean ignorePotentials= NewSearchUI.arePotentialMatchesIgnored();
- NewSearchResultCollector collector= new NewSearchResultCollector(textResult, ignorePotentials);
-
-
- engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, fPatternData.getScope(), collector, mainSearchPM);
- for (int i= 0; i < participantDescriptors.length; i++) {
- final ISearchRequestor requestor= new SearchRequestor(participantDescriptors[i].getParticipant(), textResult);
- final IProgressMonitor participantPM= new SubProgressMonitor(monitor, ticks[i]);
-
- final int iPrime= i;
- ISafeRunnable runnable= new ISafeRunnable() {
- public void handleException(Throwable exception) {
- participantDescriptors[iPrime].getDescriptor().disable();
- String message= SearchMessages.JavaSearchQuery_error_participant_search;
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, message, exception));
- }
-
- public void run() throws Exception {
-
- final IQueryParticipant participant= participantDescriptors[iPrime].getParticipant();
-
- final PerformanceStats stats= PerformanceStats.getStats(PERF_SEARCH_PARTICIPANT, participant);
- stats.startRun();
-
- participant.search(requestor, fPatternData, participantPM);
-
- stats.endRun();
- }
- };
-
- SafeRunner.run(runnable);
- }
-
- } catch (CoreException e) {
- return e.getStatus();
- }
- String message= Messages.format(SearchMessages.JavaSearchQuery_status_ok_message, String.valueOf(textResult.getMatchCount()));
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), 0, message, null);
- }
-
- private int getMatchMode(String pattern) {
- if (pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1) {
- return SearchPattern.R_PATTERN_MATCH;
- } else if (SearchUtils.isCamelCasePattern(pattern)) {
- return SearchPattern.R_CAMELCASE_MATCH;
- }
- return SearchPattern.R_EXACT_MATCH;
- }
-
- public String getLabel() {
- return SearchMessages.JavaSearchQuery_label;
- }
-
- public String getResultLabel(int nMatches) {
- if (nMatches == 1) {
- String[] args= { getSearchPatternDescription(), fPatternData.getScopeDescription() };
- switch (fPatternData.getLimitTo()) {
- case IJavaScriptSearchConstants.IMPLEMENTORS:
- return Messages.format(SearchMessages.JavaSearchOperation_singularImplementorsPostfix, args);
- case IJavaScriptSearchConstants.DECLARATIONS:
- return Messages.format(SearchMessages.JavaSearchOperation_singularDeclarationsPostfix, args);
- case IJavaScriptSearchConstants.REFERENCES:
- return Messages.format(SearchMessages.JavaSearchOperation_singularReferencesPostfix, args);
- case IJavaScriptSearchConstants.ALL_OCCURRENCES:
- return Messages.format(SearchMessages.JavaSearchOperation_singularOccurrencesPostfix, args);
- case IJavaScriptSearchConstants.READ_ACCESSES:
- return Messages.format(SearchMessages.JavaSearchOperation_singularReadReferencesPostfix, args);
- case IJavaScriptSearchConstants.WRITE_ACCESSES:
- return Messages.format(SearchMessages.JavaSearchOperation_singularWriteReferencesPostfix, args);
- default:
- return Messages.format(SearchMessages.JavaSearchOperation_singularOccurrencesPostfix, args);
- }
- } else {
- Object[] args= { getSearchPatternDescription(), new Integer(nMatches), fPatternData.getScopeDescription() };
- switch (fPatternData.getLimitTo()) {
- case IJavaScriptSearchConstants.IMPLEMENTORS:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralImplementorsPostfix, args);
- case IJavaScriptSearchConstants.DECLARATIONS:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralDeclarationsPostfix, args);
- case IJavaScriptSearchConstants.REFERENCES:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralReferencesPostfix, args);
- case IJavaScriptSearchConstants.ALL_OCCURRENCES:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralOccurrencesPostfix, args);
- case IJavaScriptSearchConstants.READ_ACCESSES:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralReadReferencesPostfix, args);
- case IJavaScriptSearchConstants.WRITE_ACCESSES:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralWriteReferencesPostfix, args);
- default:
- return Messages.format(SearchMessages.JavaSearchOperation_pluralOccurrencesPostfix, args);
- }
- }
- }
-
- private String getSearchPatternDescription() {
- if (fPatternData instanceof ElementQuerySpecification) {
- IJavaScriptElement element= ((ElementQuerySpecification) fPatternData).getElement();
- return JavaScriptElementLabels.getElementLabel(element, JavaScriptElementLabels.ALL_DEFAULT
- | JavaScriptElementLabels.ALL_FULLY_QUALIFIED | JavaScriptElementLabels.USE_RESOLVED);
- }
- return ((PatternQuerySpecification) fPatternData).getPattern();
- }
-
- ImageDescriptor getImageDescriptor() {
- if (fPatternData.getLimitTo() == IJavaScriptSearchConstants.IMPLEMENTORS || fPatternData.getLimitTo() == IJavaScriptSearchConstants.DECLARATIONS)
- return JavaPluginImages.DESC_OBJS_SEARCH_DECL;
- else
- return JavaPluginImages.DESC_OBJS_SEARCH_REF;
- }
-
- public boolean canRerun() {
- return true;
- }
-
- public boolean canRunInBackground() {
- return true;
- }
-
- public ISearchResult getSearchResult() {
- if (fResult == null) {
- JavaSearchResult result= new JavaSearchResult(this);
- new SearchResultUpdater(result);
- fResult= result;
- }
- return fResult;
- }
-
- QuerySpecification getSpecification() {
- return fPatternData;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResult.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResult.java
deleted file mode 100644
index 4b60a587..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResult.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.IEditorMatchAdapter;
-import org.eclipse.search.ui.text.IFileMatchAdapter;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.search.ui.text.MatchFilter;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.search.IMatchPresentation;
-
-public class JavaSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter {
-
- private static final Match[] NO_MATCHES= new Match[0];
-
- private final JavaSearchQuery fQuery;
- private final Map fElementsToParticipants;
-
- public JavaSearchResult(JavaSearchQuery query) {
- fQuery= query;
- fElementsToParticipants= new HashMap();
- setActiveMatchFilters(JavaMatchFilter.getLastUsedFilters());
- }
-
- public ImageDescriptor getImageDescriptor() {
- return fQuery.getImageDescriptor();
- }
-
- public String getLabel() {
- return fQuery.getResultLabel(getMatchCount());
- }
-
- public String getTooltip() {
- return getLabel();
- }
-
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) {
- return computeContainedMatches(editor.getEditorInput());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#setMatchFilters(org.eclipse.search.ui.text.MatchFilter[])
- */
- public void setActiveMatchFilters(MatchFilter[] filters) {
- super.setActiveMatchFilters(filters);
- JavaMatchFilter.setLastUsedFilters(filters);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getAllMatchFilters()
- */
- public MatchFilter[] getAllMatchFilters() {
- return JavaMatchFilter.allFilters(fQuery);
- }
-
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IFile file) {
- return computeContainedMatches(file);
- }
-
- private Match[] computeContainedMatches(IAdaptable adaptable) {
- IJavaScriptElement javaElement= (IJavaScriptElement) adaptable.getAdapter(IJavaScriptElement.class);
- Set matches= new HashSet();
- if (javaElement != null) {
- collectMatches(matches, javaElement);
- }
- IFile file= (IFile) adaptable.getAdapter(IFile.class);
- if (file != null) {
- collectMatches(matches, file);
- }
- if (!matches.isEmpty()) {
- return (Match[]) matches.toArray(new Match[matches.size()]);
- }
- return NO_MATCHES;
- }
-
-
- private void collectMatches(Set matches, IFile element) {
- Match[] m= getMatches(element);
- if (m.length != 0) {
- for (int i= 0; i < m.length; i++) {
- matches.add(m[i]);
- }
- }
- }
-
- private void collectMatches(Set matches, IJavaScriptElement element) {
- Match[] m= getMatches(element);
- if (m.length != 0) {
- for (int i= 0; i < m.length; i++) {
- matches.add(m[i]);
- }
- }
- if (element instanceof IParent) {
- IParent parent= (IParent) element;
- try {
- IJavaScriptElement[] children= parent.getChildren();
- for (int i= 0; i < children.length; i++) {
- collectMatches(matches, children[i]);
- }
- } catch (JavaScriptModelException e) {
- // we will not be tracking these results
- }
- }
- }
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.ISearchResultCategory#getFile(java.lang.Object)
- */
- public IFile getFile(Object element) {
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement javaElement= (IJavaScriptElement) element;
- IJavaScriptUnit cu= (IJavaScriptUnit) javaElement.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- return (IFile) cu.getResource();
- } else {
- IClassFile cf= (IClassFile) javaElement.getAncestor(IJavaScriptElement.CLASS_FILE);
- if (cf != null)
- return (IFile) cf.getResource();
- }
- return null;
- }
- if (element instanceof IFile)
- return (IFile) element;
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.search2.ui.text.IStructureProvider#isShownInEditor(org.eclipse.search2.ui.text.Match,
- * org.eclipse.ui.IEditorPart)
- */
- public boolean isShownInEditor(Match match, IEditorPart editor) {
- Object element= match.getElement();
- if (element instanceof IJavaScriptElement) {
- element= ((IJavaScriptElement) element).getOpenable(); // class file or compilation unit
- return element != null && element.equals(editor.getEditorInput().getAdapter(IJavaScriptElement.class));
- } else if (element instanceof IFile) {
- return element.equals(editor.getEditorInput().getAdapter(IFile.class));
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.ISearchResult#getQuery()
- */
- public ISearchQuery getQuery() {
- return fQuery;
- }
-
- synchronized IMatchPresentation getSearchParticpant(Object element) {
- return (IMatchPresentation) fElementsToParticipants.get(element);
- }
-
- boolean addMatch(Match match, IMatchPresentation participant) {
- Object element= match.getElement();
- if (fElementsToParticipants.get(element) != null) {
- // TODO must access the participant id / label to properly report the error.
- JavaScriptPlugin.log(new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), 0, "A second search participant was found for an element", null)); //$NON-NLS-1$
- return false;
- }
- fElementsToParticipants.put(element, participant);
- addMatch(match);
- return true;
- }
-
- public void removeAll() {
- synchronized(this) {
- fElementsToParticipants.clear();
- }
- super.removeAll();
- }
-
- public void removeMatch(Match match) {
- synchronized(this) {
- if (getMatchCount(match.getElement()) == 1)
- fElementsToParticipants.remove(match.getElement());
- }
- super.removeMatch(match);
- }
- public IFileMatchAdapter getFileMatchAdapter() {
- return this;
- }
-
- public IEditorMatchAdapter getEditorMatchAdapter() {
- return this;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResultPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResultPage.java
deleted file mode 100644
index baea1a46..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchResultPage.java
+++ /dev/null
@@ -1,547 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashMap;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.search.ui.IContextMenuConstants;
-import org.eclipse.search.ui.ISearchResultViewPart;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.CopyQualifiedNameAction;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.ResourceTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTableViewer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-import org.eclipse.wst.jsdt.ui.search.IMatchPresentation;
-
-public class JavaSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable {
-
- public static class DecoratorIgnoringViewerSorter extends ViewerComparator {
-
- private final ILabelProvider fLabelProvider;
-
- public DecoratorIgnoringViewerSorter(ILabelProvider labelProvider) {
- fLabelProvider= labelProvider;
- }
-
- public int compare(Viewer viewer, Object e1, Object e2) {
- String name1= fLabelProvider.getText(e1);
- String name2= fLabelProvider.getText(e2);
- if (name1 == null)
- name1 = "";//$NON-NLS-1$
- if (name2 == null)
- name2 = "";//$NON-NLS-1$
- return getComparator().compare(name1, name2);
- }
- }
-
-
- private static final int DEFAULT_ELEMENT_LIMIT = 1000;
- private static final String FALSE = "FALSE"; //$NON-NLS-1$
- private static final String TRUE = "TRUE"; //$NON-NLS-1$
- private static final String KEY_GROUPING= "org.eclipse.wst.jsdt.search.resultpage.grouping"; //$NON-NLS-1$
- private static final String KEY_SORTING= "org.eclipse.wst.jsdt.search.resultpage.sorting"; //$NON-NLS-1$
- private static final String KEY_LIMIT_ENABLED= "org.eclipse.wst.jsdt.search.resultpage.limit_enabled"; //$NON-NLS-1$
- private static final String KEY_LIMIT= "org.eclipse.wst.jsdt.search.resultpage.limit"; //$NON-NLS-1$
-
- private static final String GROUP_GROUPING= "org.eclipse.wst.jsdt.search.resultpage.grouping"; //$NON-NLS-1$
- private static final String GROUP_FILTERING = "org.eclipse.wst.jsdt.search.resultpage.filtering"; //$NON-NLS-1$
-
- private NewSearchViewActionGroup fActionGroup;
- private JavaSearchContentProvider fContentProvider;
- private int fCurrentSortOrder;
- private SortAction fSortByNameAction;
- private SortAction fSortByParentName;
- private SortAction fSortByPathAction;
-
- private GroupAction fGroupTypeAction;
- private GroupAction fGroupFileAction;
- private GroupAction fGroupPackageAction;
- private GroupAction fGroupProjectAction;
-
- private SelectionDispatchAction fCopyQualifiedNameAction;
-
- private SortingLabelProvider fSortingLabelProvider;
-
- private int fCurrentGrouping;
-
- private static final String[] SHOW_IN_TARGETS= new String[] { JavaScriptUI.ID_PACKAGES , IPageLayout.ID_RES_NAV };
- public static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return SHOW_IN_TARGETS;
- }
- };
-
- private JavaSearchEditorOpener fEditorOpener= new JavaSearchEditorOpener();
-
- public JavaSearchResultPage() {
- fCopyQualifiedNameAction= null;
-
- initSortActions();
- initGroupingActions();
- setElementLimit(new Integer(DEFAULT_ELEMENT_LIMIT));
- }
-
- private void initSortActions() {
- fSortByNameAction= new SortAction(SearchMessages.JavaSearchResultPage_sortByName, this, SortingLabelProvider.SHOW_ELEMENT_CONTAINER);
- fSortByPathAction= new SortAction(SearchMessages.JavaSearchResultPage_sortByPath, this, SortingLabelProvider.SHOW_PATH);
- fSortByParentName= new SortAction(SearchMessages.JavaSearchResultPage_sortByParentName, this, SortingLabelProvider.SHOW_CONTAINER_ELEMENT);
- }
-
- private void initGroupingActions() {
- fGroupProjectAction= new GroupAction(SearchMessages.JavaSearchResultPage_groupby_project, SearchMessages.JavaSearchResultPage_groupby_project_tooltip, this, LevelTreeContentProvider.LEVEL_PROJECT);
- JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$
- if(JavaScriptCore.IS_ECMASCRIPT4) fGroupPackageAction= new GroupAction(SearchMessages.JavaSearchResultPage_groupby_package, SearchMessages.JavaSearchResultPage_groupby_package_tooltip, this, LevelTreeContentProvider.LEVEL_PACKAGE);
- if(JavaScriptCore.IS_ECMASCRIPT4) JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$
- fGroupFileAction= new GroupAction(SearchMessages.JavaSearchResultPage_groupby_file, SearchMessages.JavaSearchResultPage_groupby_file_tooltip, this, LevelTreeContentProvider.LEVEL_FILE);
- JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$
- fGroupTypeAction= new GroupAction(SearchMessages.JavaSearchResultPage_groupby_type, SearchMessages.JavaSearchResultPage_groupby_type_tooltip, this, LevelTreeContentProvider.LEVEL_TYPE);
- JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "type_mode.gif"); //$NON-NLS-1$
- }
-
- public void setViewPart(ISearchResultViewPart part) {
- super.setViewPart(part);
- fActionGroup= new NewSearchViewActionGroup(part);
- }
-
- public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException {
- IEditorPart editor;
- try {
- editor= fEditorOpener.openMatch(match);
- } catch (JavaScriptModelException e) {
- throw new PartInitException(e.getStatus());
- }
-
- if (editor != null && activate)
- editor.getEditorSite().getPage().activate(editor);
- Object element= match.getElement();
- if (editor instanceof ITextEditor) {
- ITextEditor textEditor= (ITextEditor) editor;
- textEditor.selectAndReveal(offset, length);
- } else if (editor != null){
- if (element instanceof IFile) {
- IFile file= (IFile) element;
- showWithMarker(editor, file, offset, length);
- }
- } else {
- JavaSearchResult result= (JavaSearchResult) getInput();
- IMatchPresentation participant= result.getSearchParticpant(element);
- if (participant != null)
- participant.showMatch(match, offset, length, activate);
- }
- }
-
- private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
- try {
- IMarker marker= file.createMarker(NewSearchUI.SEARCH_MARKER);
- HashMap attributes= new HashMap(4);
- attributes.put(IMarker.CHAR_START, new Integer(offset));
- attributes.put(IMarker.CHAR_END, new Integer(offset + length));
- marker.setAttributes(attributes);
- IDE.gotoMarker(editor, marker);
- marker.delete();
- } catch (CoreException e) {
- throw new PartInitException(SearchMessages.JavaSearchResultPage_error_marker, e);
- }
- }
-
- private SelectionDispatchAction getCopyQualifiedNameAction() {
- if (fCopyQualifiedNameAction == null) {
- fCopyQualifiedNameAction= new CopyQualifiedNameAction(getSite());
- }
- return fCopyQualifiedNameAction;
- }
-
- protected void fillContextMenu(IMenuManager mgr) {
- super.fillContextMenu(mgr);
- addSortActions(mgr);
-
- mgr.appendToGroup(IContextMenuConstants.GROUP_EDIT, getCopyQualifiedNameAction());
-
- fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
- fActionGroup.fillContextMenu(mgr);
- }
-
- private void addSortActions(IMenuManager mgr) {
- if (getLayout() != FLAG_LAYOUT_FLAT)
- return;
- MenuManager sortMenu= new MenuManager(SearchMessages.JavaSearchResultPage_sortBylabel);
- sortMenu.add(fSortByNameAction);
- sortMenu.add(fSortByPathAction);
- sortMenu.add(fSortByParentName);
-
- fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
- fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
- fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
-
- mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
- }
-
- protected void fillToolbar(IToolBarManager tbm) {
- super.fillToolbar(tbm);
-
- IActionBars actionBars = getSite().getActionBars();
- if (actionBars != null) {
- actionBars.setGlobalActionHandler(CopyQualifiedNameAction.ACTION_HANDLER_ID, getCopyQualifiedNameAction());
- }
-
- if (getLayout() != FLAG_LAYOUT_FLAT)
- addGroupActions(tbm);
- }
-
- private void addGroupActions(IToolBarManager mgr) {
- mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(GROUP_GROUPING));
- mgr.appendToGroup(GROUP_GROUPING, fGroupProjectAction);
- if(JavaScriptCore.IS_ECMASCRIPT4) mgr.appendToGroup(GROUP_GROUPING, fGroupPackageAction);
- mgr.appendToGroup(GROUP_GROUPING, fGroupFileAction);
- mgr.appendToGroup(GROUP_GROUPING, fGroupTypeAction);
-
- updateGroupingActions();
- }
-
-
- private void updateGroupingActions() {
- fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
- if(JavaScriptCore.IS_ECMASCRIPT4) fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
- fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
- fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
- }
-
-
- public void dispose() {
- fActionGroup.dispose();
- super.dispose();
- }
-
- protected void elementsChanged(Object[] objects) {
- if (fContentProvider != null)
- fContentProvider.elementsChanged(objects);
- }
-
- protected void clear() {
- if (fContentProvider != null)
- fContentProvider.clear();
- }
-
- private void addDragAdapters(StructuredViewer viewer) {
- Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance() };
- int ops= DND.DROP_COPY | DND.DROP_LINK;
-
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(viewer),
- new ResourceTransferDragAdapter(viewer)
- };
-
- viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
- }
-
- protected void configureTableViewer(TableViewer viewer) {
- viewer.setUseHashlookup(true);
- fSortingLabelProvider= new SortingLabelProvider(this);
- viewer.setLabelProvider(new DecoratingJavaLabelProvider(fSortingLabelProvider, false));
- fContentProvider=new JavaSearchTableContentProvider(this);
- viewer.setContentProvider(fContentProvider);
- viewer.setComparator(new DecoratorIgnoringViewerSorter(fSortingLabelProvider));
- setSortOrder(fCurrentSortOrder);
- addDragAdapters(viewer);
- }
-
- protected void configureTreeViewer(TreeViewer viewer) {
- PostfixLabelProvider postfixLabelProvider= new PostfixLabelProvider(this);
- viewer.setUseHashlookup(true);
- viewer.setComparator(new DecoratorIgnoringViewerSorter(postfixLabelProvider));
- viewer.setLabelProvider(new DecoratingJavaLabelProvider(postfixLabelProvider, false));
- fContentProvider= new LevelTreeContentProvider(this, fCurrentGrouping);
- viewer.setContentProvider(fContentProvider);
- addDragAdapters(viewer);
- }
-
- protected TreeViewer createTreeViewer(Composite parent) {
- ProblemTreeViewer problemTreeViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- ColoredViewersManager.install(problemTreeViewer);
- return problemTreeViewer;
- }
-
- protected TableViewer createTableViewer(Composite parent) {
- ProblemTableViewer problemTableViewer= new ProblemTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- ColoredViewersManager.install(problemTableViewer);
- return problemTableViewer;
- }
-
- void setSortOrder(int order) {
- if (fSortingLabelProvider != null) {
- fCurrentSortOrder= order;
- StructuredViewer viewer= getViewer();
- //viewer.getControl().setRedraw(false);
- fSortingLabelProvider.setOrder(order);
- //viewer.getControl().setRedraw(true);
- viewer.refresh();
- getSettings().put(KEY_SORTING, fCurrentSortOrder);
- }
- }
-
- public void init(IPageSite site) {
- super.init(site);
- IMenuManager menuManager = site.getActionBars().getMenuManager();
- menuManager.insertBefore(IContextMenuConstants.GROUP_PROPERTIES, new Separator(GROUP_FILTERING));
- fActionGroup.fillActionBars(site.getActionBars());
- menuManager.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, new Action(SearchMessages.JavaSearchResultPage_preferences_label) {
- public void run() {
- String pageId= "org.eclipse.search.preferences.SearchPreferencePage"; //$NON-NLS-1$
- PreferencesUtil.createPreferenceDialogOn(JavaScriptPlugin.getActiveWorkbenchShell(), pageId, null, null).open();
- }
- });
- }
-
- /**
- * Precondition here: the viewer must be showing a tree with a LevelContentProvider.
- * @param grouping
- */
- void setGrouping(int grouping) {
- fCurrentGrouping= grouping;
- StructuredViewer viewer= getViewer();
- LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
- cp.setLevel(grouping);
- updateGroupingActions();
- getSettings().put(KEY_GROUPING, fCurrentGrouping);
- getViewPart().updateLabel();
- }
-
- protected StructuredViewer getViewer() {
- // override so that it's visible in the package.
- return super.getViewer();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#restoreState(org.eclipse.ui.IMemento)
- */
- public void restoreState(IMemento memento) {
- super.restoreState(memento);
-
- int sortOrder= SortingLabelProvider.SHOW_ELEMENT_CONTAINER;
- int grouping= LevelTreeContentProvider.LEVEL_PACKAGE;
- int elementLimit= DEFAULT_ELEMENT_LIMIT;
-
- try {
- sortOrder= getSettings().getInt(KEY_SORTING);
- } catch (NumberFormatException e) {
- }
- try {
- grouping= getSettings().getInt(KEY_GROUPING);
- } catch (NumberFormatException e) {
- }
- if (FALSE.equals(getSettings().get(KEY_LIMIT_ENABLED))) {
- elementLimit= -1;
- } else {
- try {
- elementLimit= getSettings().getInt(KEY_LIMIT);
- } catch (NumberFormatException e) {
- }
- }
- if (memento != null) {
- Integer value= memento.getInteger(KEY_GROUPING);
- if (value != null)
- grouping= value.intValue();
- value= memento.getInteger(KEY_SORTING);
- if (value != null)
- sortOrder= value.intValue();
- boolean limitElements= !FALSE.equals(memento.getString(KEY_LIMIT_ENABLED));
- value= memento.getInteger(KEY_LIMIT);
- if (value != null)
- elementLimit= limitElements ? value.intValue() : -1;
- }
-
- fCurrentGrouping= grouping;
- fCurrentSortOrder= sortOrder;
- setElementLimit(new Integer(elementLimit));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#saveState(org.eclipse.ui.IMemento)
- */
- public void saveState(IMemento memento) {
- super.saveState(memento);
- memento.putInteger(KEY_GROUPING, fCurrentGrouping);
- memento.putInteger(KEY_SORTING, fCurrentSortOrder);
- int limit= getElementLimit().intValue();
- if (limit != -1)
- memento.putString(KEY_LIMIT_ENABLED, TRUE);
- else
- memento.putString(KEY_LIMIT_ENABLED, FALSE);
- memento.putInteger(KEY_LIMIT, limit);
- }
-
- private boolean isQueryRunning() {
- AbstractTextSearchResult result= getInput();
- if (result != null) {
- return NewSearchUI.isQueryRunning(result.getQuery());
- }
- return false;
- }
-
- public String getLabel() {
- String label= super.getLabel();
- AbstractTextSearchResult input= getInput();
- if (input != null && input.getActiveMatchFilters() != null && input.getActiveMatchFilters().length > 0) {
- if (isQueryRunning()) {
- String message= SearchMessages.JavaSearchResultPage_filtered_message;
- return Messages.format(message, new Object[] { label });
-
- } else {
- int filteredOut= input.getMatchCount() - getFilteredMatchCount();
- String message= SearchMessages.JavaSearchResultPage_filteredWithCount_message;
- return Messages.format(message, new Object[] { label, String.valueOf(filteredOut) });
- }
- }
- return label;
- }
-
- private int getFilteredMatchCount() {
- StructuredViewer viewer= getViewer();
- if (viewer instanceof TreeViewer) {
- ITreeContentProvider tp= (ITreeContentProvider) viewer.getContentProvider();
- return getMatchCount(tp, getRootElements((TreeViewer) getViewer()));
- } else {
- return getMatchCount((TableViewer) viewer);
- }
- }
-
- private Object[] getRootElements(TreeViewer viewer) {
- Tree t= viewer.getTree();
- Item[] roots= t.getItems();
- Object[] elements= new Object[roots.length];
- for (int i = 0; i < elements.length; i++) {
- elements[i]= roots[i].getData();
- }
- return elements;
- }
-
- private Object[] getRootElements(TableViewer viewer) {
- Table t= viewer.getTable();
- Item[] roots= t.getItems();
- Object[] elements= new Object[roots.length];
- for (int i = 0; i < elements.length; i++) {
- elements[i]= roots[i].getData();
- }
- return elements;
- }
-
-
- private int getMatchCount(ITreeContentProvider cp, Object[] elements) {
- int count= 0;
- for (int j = 0; j < elements.length; j++) {
- count+= getDisplayedMatchCount(elements[j]);
- Object[] children = cp.getChildren(elements[j]);
- count+= getMatchCount(cp, children);
- }
- return count;
- }
-
- private int getMatchCount(TableViewer viewer) {
- Object[] elements= getRootElements(viewer);
- int count= 0;
- for (int i = 0; i < elements.length; i++) {
- count+= getDisplayedMatchCount(elements[i]);
- }
- return count;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class adapter) {
- if (IShowInTargetList.class.equals(adapter)) {
- return SHOW_IN_TARGET_LIST;
- }
- return null;
- }
-
- protected void handleOpen(OpenEvent event) {
- Object firstElement= ((IStructuredSelection)event.getSelection()).getFirstElement();
- if (firstElement instanceof IJavaScriptUnit ||
- firstElement instanceof IClassFile ||
- firstElement instanceof IMember) {
- if (getDisplayedMatchCount(firstElement) == 0) {
- try {
- fEditorOpener.openElement(firstElement);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getSite().getShell(), SearchMessages.JavaSearchResultPage_open_editor_error_title, SearchMessages.JavaSearchResultPage_open_editor_error_message);
- }
- return;
- }
- }
- super.handleOpen(event);
- }
-
- public void setElementLimit(Integer elementLimit) {
- super.setElementLimit(elementLimit);
- int limit= elementLimit.intValue();
- getSettings().put(KEY_LIMIT, limit);
- getSettings().put(KEY_LIMIT_ENABLED, limit != -1 ? TRUE : FALSE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchScopeFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchScopeFactory.java
deleted file mode 100644
index bc7a74be..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchScopeFactory.java
+++ /dev/null
@@ -1,436 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavaSearchScopeFactory {
-
- public static final int JRE= IJavaScriptSearchScope.SYSTEM_LIBRARIES;
- public static final int LIBS= IJavaScriptSearchScope.APPLICATION_LIBRARIES;
- public static final int PROJECTS= IJavaScriptSearchScope.REFERENCED_PROJECTS;
- public static final int SOURCES= IJavaScriptSearchScope.SOURCES;
-
- public static final int ALL= JRE | LIBS | PROJECTS | SOURCES;
- public static final int NO_PROJ= JRE | LIBS | SOURCES;
- public static final int NO_JRE= LIBS | PROJECTS | SOURCES;
- public static final int NO_JRE_NO_PROJ= LIBS | PROJECTS | SOURCES;
-
- private static JavaSearchScopeFactory fgInstance;
- private final IJavaScriptSearchScope EMPTY_SCOPE= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {});
-
- private JavaSearchScopeFactory() {
- }
-
- public static JavaSearchScopeFactory getInstance() {
- if (fgInstance == null)
- fgInstance= new JavaSearchScopeFactory();
- return fgInstance;
- }
-
- public IWorkingSet[] queryWorkingSets() throws JavaScriptModelException, InterruptedException {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- if (shell == null)
- return null;
- IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true);
- if (dialog.open() != Window.OK) {
- throw new InterruptedException();
- }
-
- IWorkingSet[] workingSets= dialog.getSelection();
- if (workingSets.length > 0)
- return workingSets;
- return null; // 'no working set' selected
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet[] workingSets, boolean includeJRE) {
- return createJavaSearchScope(workingSets, includeJRE ? ALL : NO_JRE);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet[] workingSets, int includeMask) {
- if (workingSets == null || workingSets.length < 1)
- return EMPTY_SCOPE;
-
- Set javaElements= new HashSet(workingSets.length * 10);
- for (int i= 0; i < workingSets.length; i++) {
- IWorkingSet workingSet= workingSets[i];
- if (workingSet.isEmpty() && workingSet.isAggregateWorkingSet()) {
- return createWorkspaceScope(includeMask);
- }
- addJavaElements(javaElements, workingSet);
- }
- return createJavaSearchScope(javaElements, includeMask);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet workingSet, boolean includeJRE) {
- return createJavaSearchScope(workingSet, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IWorkingSet workingSet, int includeMask) {
- Set javaElements= new HashSet(10);
- if (workingSet.isEmpty() && workingSet.isAggregateWorkingSet()) {
- return createWorkspaceScope(includeMask);
- }
- addJavaElements(javaElements, workingSet);
- return createJavaSearchScope(javaElements, includeMask);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IResource[] resources, boolean includeJRE) {
- return createJavaSearchScope(resources, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IResource[] resources, int includeMask) {
- if (resources == null)
- return EMPTY_SCOPE;
- Set javaElements= new HashSet(resources.length);
- addJavaElements(javaElements, resources);
- return createJavaSearchScope(javaElements, includeMask);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(ISelection selection, boolean includeJRE) {
- return createJavaSearchScope(selection, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(ISelection selection, int includeMask) {
- return createJavaSearchScope(getJavaElements(selection), includeMask);
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(String[] projectNames, boolean includeJRE) {
- return createJavaProjectSearchScope(projectNames, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(String[] projectNames, int includeMask) {
- ArrayList res= new ArrayList();
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int i= 0; i < projectNames.length; i++) {
- IJavaScriptProject project= JavaScriptCore.create(root.getProject(projectNames[i]));
- if (project.exists()) {
- res.add(project);
- }
- }
- return createJavaSearchScope(res, includeMask);
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(IJavaScriptProject project, boolean includeJRE) {
- return createJavaProjectSearchScope(project, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(IJavaScriptProject project, int includeMask) {
- return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { project }, getSearchFlags(includeMask));
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(IEditorInput editorInput, boolean includeJRE) {
- return createJavaProjectSearchScope(editorInput, includeJRE ? ALL : NO_JRE);
- }
-
- public IJavaScriptSearchScope createJavaProjectSearchScope(IEditorInput editorInput, int includeMask) {
- IJavaScriptElement elem= JavaScriptUI.getEditorInputJavaElement(editorInput);
- if (elem != null) {
- IJavaScriptProject project= elem.getJavaScriptProject();
- if (project != null) {
- return createJavaProjectSearchScope(project, includeMask);
- }
- }
- return EMPTY_SCOPE;
- }
-
- public String getWorkspaceScopeDescription(boolean includeJRE) {
- return includeJRE ? SearchMessages.WorkspaceScope : SearchMessages.WorkspaceScopeNoJRE;
- }
-
- public String getWorkspaceScopeDescription(int includeMask) {
- return getWorkspaceScopeDescription((includeMask & JRE) != 0);
- }
-
- public String getProjectScopeDescription(String[] projectNames, int includeMask) {
- if (projectNames.length == 0) {
- return SearchMessages.JavaSearchScopeFactory_undefined_projects;
- }
- boolean includeJRE= (includeMask & JRE) != 0;
- String scopeDescription;
- if (projectNames.length == 1) {
- String label= includeJRE ? SearchMessages.EnclosingProjectScope : SearchMessages.EnclosingProjectScopeNoJRE;
- scopeDescription= Messages.format(label, projectNames[0]);
- } else if (projectNames.length == 2) {
- String label= includeJRE ? SearchMessages.EnclosingProjectsScope2 : SearchMessages.EnclosingProjectsScope2NoJRE;
- scopeDescription= Messages.format(label, new String[] { projectNames[0], projectNames[1]});
- } else {
- String label= includeJRE ? SearchMessages.EnclosingProjectsScope : SearchMessages.EnclosingProjectsScopeNoJRE;
- scopeDescription= Messages.format(label, new String[] { projectNames[0], projectNames[1]});
- }
- return scopeDescription;
- }
-
- public String getProjectScopeDescription(IJavaScriptProject project, boolean includeJRE) {
- if (includeJRE) {
- return Messages.format(SearchMessages.ProjectScope, project.getElementName());
- } else {
- return Messages.format(SearchMessages.ProjectScopeNoJRE, project.getElementName());
- }
- }
-
- public String getProjectScopeDescription(IEditorInput editorInput, boolean includeJRE) {
- IJavaScriptElement elem= JavaScriptUI.getEditorInputJavaElement(editorInput);
- if (elem != null) {
- IJavaScriptProject project= elem.getJavaScriptProject();
- if (project != null) {
- return getProjectScopeDescription(project, includeJRE);
- }
- }
- return Messages.format(SearchMessages.ProjectScope, ""); //$NON-NLS-1$
- }
-
- public String getHierarchyScopeDescription(IType type) {
- return Messages.format(SearchMessages.HierarchyScope, new String[] { type.getElementName() });
- }
-
- public String getSelectionScopeDescription(IJavaScriptElement[] javaElements, int includeMask) {
- return getSelectionScopeDescription(javaElements, (includeMask & JRE) != 0);
- }
-
-
- public String getSelectionScopeDescription(IJavaScriptElement[] javaElements, boolean includeJRE) {
- if (javaElements.length == 0) {
- return SearchMessages.JavaSearchScopeFactory_undefined_selection;
- }
- String scopeDescription;
- if (javaElements.length == 1) {
- String label= includeJRE ? SearchMessages.SingleSelectionScope : SearchMessages.SingleSelectionScopeNoJRE;
- scopeDescription= Messages.format(label, javaElements[0].getElementName());
- } else if (javaElements.length == 1) {
- String label= includeJRE ? SearchMessages.DoubleSelectionScope : SearchMessages.DoubleSelectionScopeNoJRE;
- scopeDescription= Messages.format(label, new String[] { javaElements[0].getElementName(), javaElements[1].getElementName()});
- } else {
- String label= includeJRE ? SearchMessages.SelectionScope : SearchMessages.SelectionScopeNoJRE;
- scopeDescription= Messages.format(label, new String[] { javaElements[0].getElementName(), javaElements[1].getElementName()});
- }
- return scopeDescription;
- }
-
- public String getWorkingSetScopeDescription(IWorkingSet[] workingSets, int includeMask) {
- return getWorkingSetScopeDescription(workingSets, (includeMask & JRE) != 0);
- }
-
- public String getWorkingSetScopeDescription(IWorkingSet[] workingSets, boolean includeJRE) {
- if (workingSets.length == 0) {
- return SearchMessages.JavaSearchScopeFactory_undefined_workingsets;
- }
- if (workingSets.length == 1) {
- String label= includeJRE ? SearchMessages.SingleWorkingSetScope : SearchMessages.SingleWorkingSetScopeNoJRE;
- return Messages.format(label, workingSets[0].getLabel());
- }
- Arrays.sort(workingSets, new WorkingSetComparator());
- if (workingSets.length == 2) {
- String label= includeJRE ? SearchMessages.DoubleWorkingSetScope : SearchMessages.DoubleWorkingSetScopeNoJRE;
- return Messages.format(label, new String[] { workingSets[0].getLabel(), workingSets[1].getLabel()});
- }
- String label= includeJRE ? SearchMessages.WorkingSetsScope : SearchMessages.WorkingSetsScopeNoJRE;
- return Messages.format(label, new String[] { workingSets[0].getLabel(), workingSets[1].getLabel()});
- }
-
- public IProject[] getProjects(IJavaScriptSearchScope scope) {
- IPath[] paths= scope.enclosingProjectsAndJars();
- HashSet temp= new HashSet();
- for (int i= 0; i < paths.length; i++) {
- IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(paths[i]);
- if (resource != null && resource.getType() == IResource.PROJECT)
- temp.add(resource);
- }
- return (IProject[]) temp.toArray(new IProject[temp.size()]);
- }
-
- public IJavaScriptElement[] getJavaElements(ISelection selection) {
- if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
- return getJavaElements(((IStructuredSelection)selection).toArray());
- } else {
- return new IJavaScriptElement[0];
- }
- }
-
- private IJavaScriptElement[] getJavaElements(Object[] elements) {
- if (elements.length == 0)
- return new IJavaScriptElement[0];
-
- Set result= new HashSet(elements.length);
- for (int i= 0; i < elements.length; i++) {
- Object selectedElement= elements[i];
- if (selectedElement instanceof IJavaScriptElement) {
- addJavaElements(result, (IJavaScriptElement) selectedElement);
- } else if (selectedElement instanceof IResource) {
- addJavaElements(result, (IResource) selectedElement);
- } else if (selectedElement instanceof LogicalPackage) {
- addJavaElements(result, (LogicalPackage) selectedElement);
- } else if (selectedElement instanceof IWorkingSet) {
- IWorkingSet ws= (IWorkingSet)selectedElement;
- addJavaElements(result, ws);
- } else if (selectedElement instanceof IAdaptable) {
- IResource resource= (IResource) ((IAdaptable) selectedElement).getAdapter(IResource.class);
- if (resource != null)
- addJavaElements(result, resource);
- }
-
- }
- return (IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] javaElements, boolean includeJRE) {
- return createJavaSearchScope(javaElements, includeJRE ? NO_PROJ : NO_JRE_NO_PROJ);
- }
-
- public IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] javaElements, int includeMask) {
- if (javaElements.length == 0)
- return EMPTY_SCOPE;
- return SearchEngine.createJavaSearchScope(javaElements, getSearchFlags(includeMask));
- }
-
- private IJavaScriptSearchScope createJavaSearchScope(Collection javaElements, int includeMask) {
- if (javaElements.isEmpty())
- return EMPTY_SCOPE;
- IJavaScriptElement[] elementArray= (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]);
- return SearchEngine.createJavaSearchScope(elementArray, getSearchFlags(includeMask));
- }
-
- private static int getSearchFlags(int includeMask) {
- return includeMask;
- }
-
- private void addJavaElements(Set javaElements, IResource[] resources) {
- for (int i= 0; i < resources.length; i++)
- addJavaElements(javaElements, resources[i]);
- }
-
- private void addJavaElements(Set javaElements, IResource resource) {
- IJavaScriptElement javaElement= (IJavaScriptElement)resource.getAdapter(IJavaScriptElement.class);
- if (javaElement == null)
- // not a Java resource
- return;
-
- if (javaElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
- // add other possible package fragments
- try {
- addJavaElements(javaElements, ((IFolder)resource).members());
- } catch (CoreException ex) {
- // don't add elements
- }
- }
-
- javaElements.add(javaElement);
- }
-
- private void addJavaElements(Set javaElements, IJavaScriptElement javaElement) {
- javaElements.add(javaElement);
- }
-
- private void addJavaElements(Set javaElements, IWorkingSet workingSet) {
- if (workingSet == null)
- return;
-
- if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
- try {
- IJavaScriptProject[] projects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
- javaElements.addAll(Arrays.asList(projects));
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return;
- }
-
- IAdaptable[] elements= workingSet.getElements();
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement javaElement=(IJavaScriptElement) elements[i].getAdapter(IJavaScriptElement.class);
- if (javaElement != null) {
- addJavaElements(javaElements, javaElement);
- continue;
- }
- IResource resource= (IResource)elements[i].getAdapter(IResource.class);
- if (resource != null) {
- addJavaElements(javaElements, resource);
- }
-
- // else we don't know what to do with it, ignore.
- }
- }
-
- private void addJavaElements(Set javaElements, LogicalPackage selectedElement) {
- IPackageFragment[] packages= selectedElement.getFragments();
- for (int i= 0; i < packages.length; i++)
- addJavaElements(javaElements, packages[i]);
- }
-
- public IJavaScriptSearchScope createWorkspaceScope(boolean includeJRE) {
- return createWorkspaceScope(includeJRE ? ALL : NO_JRE);
- }
-
- public IJavaScriptSearchScope createWorkspaceScope(int includeMask) {
- if ((includeMask & NO_PROJ) != NO_PROJ) {
- try {
- IJavaScriptProject[] projects= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaScriptProjects();
- return SearchEngine.createJavaSearchScope(projects, getSearchFlags(includeMask));
- } catch (JavaScriptModelException e) {
- // ignore, use workspace scope instead
- }
- }
- return SearchEngine.createWorkspaceScope();
- }
-
- public boolean isInsideJRE(IJavaScriptElement element) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null) {
- try {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(entry.getPath(), root.getJavaScriptProject());
- return container != null && container.getKind() == IJsGlobalScopeContainer.K_DEFAULT_SYSTEM;
- }
- return false;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return true; // include JRE in doubt
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchTableContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchTableContentProvider.java
deleted file mode 100644
index e3e72a94..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchTableContentProvider.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.widgets.Table;
-
-public class JavaSearchTableContentProvider extends JavaSearchContentProvider implements IStructuredContentProvider {
- public JavaSearchTableContentProvider(JavaSearchResultPage page) {
- super(page);
- }
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof JavaSearchResult) {
- Set filteredElements= new HashSet();
- Object[] rawElements= ((JavaSearchResult)inputElement).getElements();
- int limit= getPage().getElementLimit().intValue();
- for (int i= 0; i < rawElements.length; i++) {
- if (getPage().getDisplayedMatchCount(rawElements[i]) > 0) {
- filteredElements.add(rawElements[i]);
- if (limit != -1 && limit < filteredElements.size()) {
- break;
- }
- }
- }
- return filteredElements.toArray();
- }
- return EMPTY_ARR;
- }
-
- public void elementsChanged(Object[] updatedElements) {
- if (getSearchResult() == null)
- return;
-
- int addCount= 0;
- int removeCount= 0;
- int addLimit= getAddLimit();
-
- TableViewer viewer= (TableViewer) getPage().getViewer();
- Set updated= new HashSet();
- Set added= new HashSet();
- Set removed= new HashSet();
- for (int i= 0; i < updatedElements.length; i++) {
- if (getPage().getDisplayedMatchCount(updatedElements[i]) > 0) {
- if (viewer.testFindItem(updatedElements[i]) != null)
- updated.add(updatedElements[i]);
- else {
- if (addLimit > 0) {
- added.add(updatedElements[i]);
- addLimit--;
- addCount++;
- }
- }
- } else {
- removed.add(updatedElements[i]);
- removeCount++;
- }
- }
-
- viewer.add(added.toArray());
- viewer.update(updated.toArray(), new String[] { SearchLabelProvider.PROPERTY_MATCH_COUNT });
- viewer.remove(removed.toArray());
- }
-
- private int getAddLimit() {
- int limit= getPage().getElementLimit().intValue();
- if (limit != -1) {
- Table table= (Table) getPage().getViewer().getControl();
- int itemCount= table.getItemCount();
- if (itemCount >= limit) {
- return 0;
- }
- return limit - itemCount;
- }
- return Integer.MAX_VALUE;
- }
-
- public void clear() {
- getPage().getViewer().refresh();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LRUWorkingSetsList.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LRUWorkingSetsList.java
deleted file mode 100644
index d7ec1fb6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LRUWorkingSetsList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-
-public class LRUWorkingSetsList {
-
- private final ArrayList fLRUList;
- private final int fSize;
- private final WorkingSetsComparator fComparator= new WorkingSetsComparator();
-
- public LRUWorkingSetsList(int size) {
- fSize= size;
- fLRUList= new ArrayList(size);
- }
-
- public void add(IWorkingSet[] workingSets) {
- removeDeletedWorkingSets();
- IWorkingSet[] existingWorkingSets= find(fLRUList, workingSets);
- if (existingWorkingSets != null)
- fLRUList.remove(existingWorkingSets);
- else if (fLRUList.size() == fSize)
- fLRUList.remove(fSize - 1);
- fLRUList.add(0, workingSets);
-
- }
-
- public Iterator iterator() {
- removeDeletedWorkingSets();
- return fLRUList.iterator();
- }
-
- public Iterator sortedIterator() {
- removeDeletedWorkingSets();
- ArrayList sortedList= new ArrayList(fLRUList);
- Collections.sort(sortedList, fComparator);
- return sortedList.iterator();
- }
-
- private void removeDeletedWorkingSets() {
- Iterator iter= new ArrayList(fLRUList).iterator();
- while (iter.hasNext()) {
- IWorkingSet[] workingSets= (IWorkingSet[])iter.next();
- for (int i= 0; i < workingSets.length; i++) {
- if (PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(workingSets[i].getName()) == null) {
- fLRUList.remove(workingSets);
- break;
- }
- }
- }
- }
-
- private IWorkingSet[] find(ArrayList list, IWorkingSet[] workingSets) {
- Set workingSetList= new HashSet(Arrays.asList(workingSets));
- Iterator iter= list.iterator();
- while (iter.hasNext()) {
- IWorkingSet[] lruWorkingSets= (IWorkingSet[])iter.next();
- Set lruWorkingSetList= new HashSet(Arrays.asList(lruWorkingSets));
- if (lruWorkingSetList.equals(workingSetList))
- return lruWorkingSets;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LevelTreeContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LevelTreeContentProvider.java
deleted file mode 100644
index d38724f8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/LevelTreeContentProvider.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-public class LevelTreeContentProvider extends JavaSearchContentProvider implements ITreeContentProvider {
- private Map fChildrenMap;
- private StandardJavaScriptElementContentProvider fContentProvider;
-
- public static final int LEVEL_TYPE= 1;
- public static final int LEVEL_FILE= 2;
- public static final int LEVEL_PACKAGE= 3;
- public static final int LEVEL_PROJECT= 4;
-
- private static final int[][] JAVA_ELEMENT_TYPES= {{IJavaScriptElement.TYPE},
- {IJavaScriptElement.CLASS_FILE, IJavaScriptElement.JAVASCRIPT_UNIT},
- {IJavaScriptElement.PACKAGE_FRAGMENT},
- {IJavaScriptElement.JAVASCRIPT_PROJECT, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT},
- {IJavaScriptElement.JAVASCRIPT_MODEL}};
- private static final int[][] RESOURCE_TYPES= {
- {},
- {IResource.FILE},
- {IResource.FOLDER},
- {IResource.PROJECT},
- {IResource.ROOT}};
-
- private static final int MAX_LEVEL= JAVA_ELEMENT_TYPES.length - 1;
- private int fCurrentLevel;
- static class FastJavaElementProvider extends StandardJavaScriptElementContentProvider {
- public Object getParent(Object element) {
- return internalGetParent(element);
- }
- }
-
- public LevelTreeContentProvider(JavaSearchResultPage page, int level) {
- super(page);
- fCurrentLevel= level;
- fContentProvider= new FastJavaElementProvider();
- }
-
- public Object getParent(Object child) {
- Object possibleParent= internalGetParent(child);
- if (possibleParent instanceof IJavaScriptElement) {
- IJavaScriptElement javaElement= (IJavaScriptElement) possibleParent;
- for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) {
- for (int i= 0; i < JAVA_ELEMENT_TYPES[j].length; i++) {
- if (javaElement.getElementType() == JAVA_ELEMENT_TYPES[j][i]) {
- return null;
- }
- }
- }
- } else if (possibleParent instanceof IResource) {
- IResource resource= (IResource) possibleParent;
- for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) {
- for (int i= 0; i < RESOURCE_TYPES[j].length; i++) {
- if (resource.getType() == RESOURCE_TYPES[j][i]) {
- return null;
- }
- }
- }
- }
- if (fCurrentLevel != LEVEL_FILE && child instanceof IType) {
- IType type= (IType) child;
- if (possibleParent instanceof IJavaScriptUnit
- || possibleParent instanceof IClassFile)
- possibleParent= type.getPackageFragment();
- }
- return possibleParent;
- }
-
- private Object internalGetParent(Object child) {
- return fContentProvider.getParent(child);
- }
-
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- protected synchronized void initialize(JavaSearchResult result) {
- super.initialize(result);
- fChildrenMap= new HashMap();
- if (result != null) {
- Object[] elements= result.getElements();
- for (int i= 0; i < elements.length; i++) {
- if (getPage().getDisplayedMatchCount(elements[i]) > 0) {
- insert(null, null, elements[i]);
- }
- }
- }
- }
-
- protected void insert(Map toAdd, Set toUpdate, Object child) {
- Object parent= getParent(child);
- while (parent != null) {
- if (insertChild(parent, child)) {
- if (toAdd != null)
- insertInto(parent, child, toAdd);
- } else {
- if (toUpdate != null)
- toUpdate.add(parent);
- return;
- }
- child= parent;
- parent= getParent(child);
- }
- if (insertChild(getSearchResult(), child)) {
- if (toAdd != null)
- insertInto(getSearchResult(), child, toAdd);
- }
- }
-
- private boolean insertChild(Object parent, Object child) {
- return insertInto(parent, child, fChildrenMap);
- }
-
- private boolean insertInto(Object parent, Object child, Map map) {
- Set children= (Set) map.get(parent);
- if (children == null) {
- children= new HashSet();
- map.put(parent, children);
- }
- return children.add(child);
- }
-
- protected void remove(Set toRemove, Set toUpdate, Object element) {
- // precondition here: fResult.getMatchCount(child) <= 0
-
- if (hasChildren(element)) {
- if (toUpdate != null)
- toUpdate.add(element);
- } else {
- if (getPage().getDisplayedMatchCount(element) == 0) {
- fChildrenMap.remove(element);
- Object parent= getParent(element);
- if (parent != null) {
- if (removeFromSiblings(element, parent)) {
- remove(toRemove, toUpdate, parent);
- }
- } else {
- if (removeFromSiblings(element, getSearchResult())) {
- if (toRemove != null)
- toRemove.add(element);
- }
- }
- } else {
- if (toUpdate != null) {
- toUpdate.add(element);
- }
- }
- }
- }
-
- /**
- * @param element
- * @param parent
- * @return returns true if it really was a remove (i.e. element was a child of parent).
- */
- private boolean removeFromSiblings(Object element, Object parent) {
- Set siblings= (Set) fChildrenMap.get(parent);
- if (siblings != null) {
- return siblings.remove(element);
- } else {
- return false;
- }
- }
-
- public Object[] getChildren(Object parentElement) {
- Set children= (Set) fChildrenMap.get(parentElement);
- if (children == null)
- return EMPTY_ARR;
- int limit= getPage().getElementLimit().intValue();
- if (limit != -1 && limit < children.size()) {
- Object[] limitedArray= new Object[limit];
- Iterator iterator= children.iterator();
- for (int i= 0; i < limit; i++) {
- limitedArray[i]= iterator.next();
- }
- return limitedArray;
- }
-
- return children.toArray();
- }
-
- public boolean hasChildren(Object element) {
- Set children= (Set) fChildrenMap.get(element);
- return children != null && !children.isEmpty();
- }
-
- public synchronized void elementsChanged(Object[] updatedElements) {
- if (getSearchResult() == null)
- return;
-
- AbstractTreeViewer viewer= (AbstractTreeViewer) getPage().getViewer();
-
- Set toRemove= new HashSet();
- Set toUpdate= new HashSet();
- Map toAdd= new HashMap();
- for (int i= 0; i < updatedElements.length; i++) {
- if (getPage().getDisplayedMatchCount(updatedElements[i]) > 0)
- insert(toAdd, toUpdate, updatedElements[i]);
- else
- remove(toRemove, toUpdate, updatedElements[i]);
- }
-
- viewer.remove(toRemove.toArray());
- for (Iterator iter= toAdd.keySet().iterator(); iter.hasNext();) {
- Object parent= iter.next();
- HashSet children= (HashSet) toAdd.get(parent);
- viewer.add(parent, children.toArray());
- }
- for (Iterator elementsToUpdate= toUpdate.iterator(); elementsToUpdate.hasNext();) {
- viewer.refresh(elementsToUpdate.next());
- }
-
- }
-
- public void clear() {
- initialize(getSearchResult());
- getPage().getViewer().refresh();
- }
-
- public void setLevel(int level) {
- fCurrentLevel= level;
- initialize(getSearchResult());
- getPage().getViewer().refresh();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/MethodExitsFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/MethodExitsFinder.java
deleted file mode 100644
index da2c1567..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/MethodExitsFinder.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LocalVariableIndex;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer;
-
-
-public class MethodExitsFinder extends ASTVisitor {
-
- private AST fAST;
- private FunctionDeclaration fMethodDeclaration;
- private List fResult;
- private List fCatchedExceptions;
-
- public String initialize(JavaScriptUnit root, int offset, int length) {
- return initialize(root, NodeFinder.perform(root, offset, length));
- }
-
- public String initialize(JavaScriptUnit root, ASTNode node) {
- fAST= root.getAST();
-
- if (node instanceof ReturnStatement) {
- fMethodDeclaration= (FunctionDeclaration)ASTNodes.getParent(node, ASTNode.FUNCTION_DECLARATION);
- if (fMethodDeclaration == null)
- return SearchMessages.MethodExitsFinder_no_return_type_selected;
- return null;
-
- }
-
- Type type= null;
- if (node instanceof Type) {
- type= (Type)node;
- } else if (node instanceof Name) {
- Name name= ASTNodes.getTopMostName((Name)node);
- if (name.getParent() instanceof Type) {
- type= (Type)name.getParent();
- }
- }
- if (type == null)
- return SearchMessages.MethodExitsFinder_no_return_type_selected;
- type= ASTNodes.getTopMostType(type);
- if (!(type.getParent() instanceof FunctionDeclaration))
- return SearchMessages.MethodExitsFinder_no_return_type_selected;
- fMethodDeclaration= (FunctionDeclaration)type.getParent();
- return null;
- }
-
- public List perform() {
- fResult= new ArrayList();
- markReferences();
- if (fResult.size() > 0) {
- Type returnType= fMethodDeclaration.getReturnType2();
- if (returnType != null)
- fResult.add(fMethodDeclaration.getReturnType2());
- }
- return fResult;
- }
-
- private void markReferences() {
- fCatchedExceptions= new ArrayList();
- boolean isVoid= true;
- Type returnType= fMethodDeclaration.getReturnType2();
- if (returnType != null) {
- ITypeBinding returnTypeBinding= returnType.resolveBinding();
- isVoid= returnTypeBinding != null && Bindings.isVoidType(returnTypeBinding);
- }
- fMethodDeclaration.accept(this);
- Block block= fMethodDeclaration.getBody();
- if (block != null) {
- List statements= block.statements();
- if (statements.size() > 0) {
- Object lastObject = statements.get(statements.size() - 1);
- if(lastObject instanceof Statement) {
- Statement last = (Statement) lastObject;
- int maxVariableId= LocalVariableIndex.perform(fMethodDeclaration);
- FlowContext flowContext= new FlowContext(0, maxVariableId + 1);
- flowContext.setConsiderAccessMode(false);
- flowContext.setComputeMode(FlowContext.ARGUMENTS);
- InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(flowContext);
- FlowInfo info= flowAnalyzer.perform(new ASTNode[] {last});
- if (!info.isNoReturn() && !isVoid) {
- if (!info.isPartialReturn())
- return;
- }
- }
- }
- SimpleName name= fAST.newSimpleName("x"); //$NON-NLS-1$
- name.setSourceRange(fMethodDeclaration.getStartPosition() + fMethodDeclaration.getLength() - 1, 1);
- fResult.add(name);
- }
- }
-
- public boolean visit(TypeDeclaration node) {
- // Don't dive into a local type.
- return false;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- // Don't dive into a local type.
- return false;
- }
-
-
- public boolean visit(ReturnStatement node) {
- fResult.add(node);
- return super.visit(node);
- }
-
- public boolean visit(TryStatement node) {
- int currentSize= fCatchedExceptions.size();
- List catchClauses= node.catchClauses();
- for (Iterator iter= catchClauses.iterator(); iter.hasNext();) {
- IVariableBinding variable= ((CatchClause)iter.next()).getException().resolveBinding();
- if (variable != null && variable.getType() != null) {
- fCatchedExceptions.add(variable.getType());
- }
- }
- node.getBody().accept(this);
- int toRemove= fCatchedExceptions.size() - currentSize;
- for(int i= toRemove; i > 0; i--) {
- fCatchedExceptions.remove(currentSize);
- }
-
- // visit catch and finally
- for (Iterator iter= catchClauses.iterator(); iter.hasNext(); ) {
- ((CatchClause)iter.next()).accept(this);
- }
- if (node.getFinally() != null)
- node.getFinally().accept(this);
-
- // return false. We have visited the body by ourselves.
- return false;
- }
-
- public boolean visit(ThrowStatement node) {
- ITypeBinding exception= node.getExpression().resolveTypeBinding();
- if (isExitPoint(exception)) {
- SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 5);
- fResult.add(name);
- }
- return true;
- }
-
- public boolean visit(FunctionInvocation node) {
- if (isExitPoint(node.resolveMethodBinding())) {
- fResult.add(node.getName());
- }
- return true;
- }
-
- public boolean visit(SuperMethodInvocation node) {
- if (isExitPoint(node.resolveMethodBinding())) {
- fResult.add(node.getName());
- }
- return true;
- }
-
- public boolean visit(ClassInstanceCreation node) {
- if (isExitPoint(node.resolveConstructorBinding())) {
- fResult.add(node.getType());
- }
- return true;
- }
-
- public boolean visit(ConstructorInvocation node) {
- if (isExitPoint(node.resolveConstructorBinding())) {
- // mark this
- SimpleName name= fAST.newSimpleName("xxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 4);
- fResult.add(name);
- }
- return true;
- }
-
- public boolean visit(SuperConstructorInvocation node) {
- if (isExitPoint(node.resolveConstructorBinding())) {
- SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
- name.setSourceRange(node.getStartPosition(), 5);
- fResult.add(name);
- }
- return true;
- }
-
- private boolean isExitPoint(ITypeBinding binding) {
- if (binding == null)
- return false;
- return !isCatched(binding);
- }
-
- private boolean isExitPoint(IFunctionBinding binding) {
- return false;
- }
-
- private boolean isCatched(ITypeBinding binding) {
- for (Iterator iter= fCatchedExceptions.iterator(); iter.hasNext();) {
- ITypeBinding catchException= (ITypeBinding)iter.next();
- if (catches(catchException, binding))
- return true;
- }
- return false;
- }
-
- private boolean catches(ITypeBinding catchTypeBinding, ITypeBinding throwTypeBinding) {
- while(throwTypeBinding != null) {
- if (throwTypeBinding == catchTypeBinding)
- return true;
- throwTypeBinding= throwTypeBinding.getSuperclass();
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchResultCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchResultCollector.java
deleted file mode 100644
index 18bb876f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchResultCollector.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.search.FieldReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.LocalVariableReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.MethodReferenceMatch;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.core.search.SearchParticipant;
-import org.eclipse.wst.jsdt.core.search.SearchRequestor;
-
-public class NewSearchResultCollector extends SearchRequestor {
- private JavaSearchResult fSearch;
- private boolean fIgnorePotentials;
-
- public NewSearchResultCollector(JavaSearchResult search, boolean ignorePotentials) {
- super();
- fSearch= search;
- fIgnorePotentials= ignorePotentials;
- }
-
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- IJavaScriptElement enclosingElement= (IJavaScriptElement) match.getElement();
- if (enclosingElement != null) {
- if (fIgnorePotentials && (match.getAccuracy() == SearchMatch.A_INACCURATE))
- return;
- boolean isWriteAccess= false;
- boolean isReadAccess= false;
- if (match instanceof FieldReferenceMatch) {
- FieldReferenceMatch fieldRef= ((FieldReferenceMatch) match);
- isWriteAccess= fieldRef.isWriteAccess();
- isReadAccess= fieldRef.isReadAccess();
- } else if (match instanceof LocalVariableReferenceMatch) {
- LocalVariableReferenceMatch localVarRef= ((LocalVariableReferenceMatch) match);
- isWriteAccess= localVarRef.isWriteAccess();
- isReadAccess= localVarRef.isReadAccess();
- }
- boolean isSuperInvocation= false;
- if (match instanceof MethodReferenceMatch) {
- MethodReferenceMatch methodRef= (MethodReferenceMatch) match;
- isSuperInvocation= methodRef.isSuperInvocation();
- }
- fSearch.addMatch(new JavaElementMatch(enclosingElement, match.getRule(), match.getOffset(), match.getLength(), match.getAccuracy(), isReadAccess, isWriteAccess, match.isInsideDocComment(), isSuperInvocation));
- }
- }
-
- public void beginReporting() {
- }
-
- public void endReporting() {
- }
-
- public void enterParticipant(SearchParticipant participant) {
- }
-
- public void exitParticipant(SearchParticipant participant) {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchViewActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchViewActionGroup.java
deleted file mode 100644
index d9e4995f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/NewSearchViewActionGroup.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-class NewSearchViewActionGroup extends CompositeActionGroup {
- private OpenEditorActionGroup fOpenEditorActionGroup;
-
- public NewSearchViewActionGroup(IViewPart part) {
- Assert.isNotNull(part);
- OpenViewActionGroup openViewActionGroup;
- setGroups(new ActionGroup[]{
- fOpenEditorActionGroup= new OpenEditorActionGroup(part),
- openViewActionGroup= new OpenViewActionGroup(part),
- new GenerateActionGroup(part),
- new RefactorActionGroup(part),
- new JavaSearchActionGroup(part)
- });
- openViewActionGroup.containsShowInMenu(false);
- }
-
- public void handleOpen(OpenEvent event) {
- IAction openAction= fOpenEditorActionGroup.getOpenAction();
- if (openAction != null && openAction.isEnabled()) {
- openAction.run();
- return;
- }
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesFinder.java
deleted file mode 100644
index 2bebcdd4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesFinder.java
+++ /dev/null
@@ -1,295 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression.Operator;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-
-public class OccurrencesFinder extends ASTVisitor implements IOccurrencesFinder {
-
- public static final String IS_WRITEACCESS= "writeAccess"; //$NON-NLS-1$
- public static final String IS_VARIABLE= "variable"; //$NON-NLS-1$
-
- private JavaScriptUnit fRoot;
- private Name fSelectedNode;
- private IBinding fTarget;
- private List fUsages= new ArrayList/*<ASTNode>*/();
- private List fWriteUsages= new ArrayList/*<ASTNode>*/();
- private boolean fTargetIsStaticMethodImport;
-
- public OccurrencesFinder(IBinding target) {
- super(true);
- fTarget= target;
- }
-
- public OccurrencesFinder() {
- super(true);
- }
-
- public String initialize(JavaScriptUnit root, int offset, int length) {
- return initialize(root, NodeFinder.perform(root, offset, length));
- }
-
- public String initialize(JavaScriptUnit root, ASTNode node) {
- if (!(node instanceof Name))
- return SearchMessages.OccurrencesFinder_no_element;
- fRoot= root;
- fSelectedNode= (Name)node;
- fTarget= fSelectedNode.resolveBinding();
- if (fTarget == null)
- return SearchMessages.OccurrencesFinder_no_binding;
- fTarget= getBindingDeclaration(fTarget);
-
- fTargetIsStaticMethodImport= isStaticImport(fSelectedNode.getParent());
- return null;
- }
-
- public List perform() {
- fRoot.accept(this);
- return fUsages;
- }
-
- public void collectOccurrenceMatches(IJavaScriptElement element, IDocument document, Collection resultingMatches) {
- boolean isVariable= fTarget instanceof IVariableBinding;
- HashMap lineToGroup= new HashMap();
-
- for (Iterator iter= fUsages.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode) iter.next();
- int startPosition= node.getStartPosition();
- int length= node.getLength();
- try {
- boolean isWriteAccess= fWriteUsages.contains(node);
- int line= document.getLineOfOffset(startPosition);
- Integer lineInteger= new Integer(line);
- OccurrencesGroupKey groupKey= (OccurrencesGroupKey) lineToGroup.get(lineInteger);
- if (groupKey == null) {
- IRegion region= document.getLineInformation(line);
- String lineContents= document.get(region.getOffset(), region.getLength()).trim();
- groupKey= new OccurrencesGroupKey(element, line, lineContents, isWriteAccess, isVariable);
- lineToGroup.put(lineInteger, groupKey);
- } else if (isWriteAccess) {
- // a line with read an write access is considered as write access:
- groupKey.setWriteAccess(true);
- }
- Match match= new Match(groupKey, startPosition, length);
- resultingMatches.add(match);
- } catch (BadLocationException e) {
- //nothing
- }
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.search.IOccurrencesFinder#getJobLabel()
- */
- public String getJobLabel() {
- return SearchMessages.OccurrencesFinder_searchfor ;
- }
-
- public String getElementName() {
- if (fSelectedNode != null) {
- return ASTNodes.asString(fSelectedNode);
- }
- return null;
- }
-
- public String getUnformattedPluralLabel() {
- return SearchMessages.OccurrencesFinder_label_plural;
- }
-
- public String getUnformattedSingularLabel() {
- return SearchMessages.OccurrencesFinder_label_singular;
- }
-
- public boolean visit(QualifiedName node) {
- final IBinding binding= node.resolveBinding();
- if (binding instanceof IVariableBinding && ((IVariableBinding)binding).isField()) {
- SimpleName name= node.getName();
- return !match(name, fUsages, name.resolveBinding());
- }
- if (binding instanceof IFunctionBinding) {
- if (isStaticImport(node)) {
- SimpleName name= node.getName();
- return !matchStaticImport(name, fUsages, (IFunctionBinding)binding);
- }
- }
- return !match(node, fUsages, binding);
- }
-
- private static boolean isStaticImport(ASTNode node) {
- if (!(node instanceof QualifiedName))
- return false;
-
- ASTNode parent= ((QualifiedName)node).getParent();
- return parent instanceof ImportDeclaration && ((ImportDeclaration)parent).isStatic();
- }
-
- public boolean visit(FunctionInvocation node) {
- if (fTargetIsStaticMethodImport)
- return !matchStaticImport(node.getName(), fUsages, node.resolveMethodBinding());
-
- return true;
- }
-
- public boolean visit(SimpleName node) {
- return !match(node, fUsages, node.resolveBinding());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.dom.ASTVisitor#visit(org.eclipse.wst.jsdt.core.dom.ConstructorInvocation)
- */
- public boolean visit(ClassInstanceCreation node) {
- // match with the constructor and the type.
- Type type= node.getType();
- if (type!=null)
- {
- if (type instanceof SimpleType) {
- Name name= ((SimpleType) type).getName();
- if (name instanceof QualifiedName)
- name= ((QualifiedName)name).getName();
- match(name, fUsages, node.resolveConstructorBinding());
- }
-
- }
- else
- {
- Expression member = node.getMember();
- if (member instanceof SimpleName)
- {
- SimpleName name=(SimpleName)member;
- match(name,fUsages,node.resolveConstructorBinding());
- }
- }
-
- return super.visit(node);
- }
-
- public boolean visit(Assignment node) {
- Expression lhs= node.getLeftHandSide();
- SimpleName name= getSimpleName(lhs);
- if (name != null)
- match(name, fWriteUsages, name.resolveBinding());
- lhs.accept(this);
- node.getRightHandSide().accept(this);
- return false;
- }
-
- public boolean visit(SingleVariableDeclaration node) {
- match(node.getName(), fWriteUsages, node.resolveBinding());
- return super.visit(node);
- }
-
- public boolean visit(VariableDeclarationFragment node) {
- if (node.getParent().getNodeType() == ASTNode.FIELD_DECLARATION || node.getInitializer() != null)
- match(node.getName(), fWriteUsages, node.resolveBinding());
- return super.visit(node);
- }
-
- public boolean visit(PrefixExpression node) {
- PrefixExpression.Operator operator= node.getOperator();
- if (operator == Operator.INCREMENT || operator == Operator.DECREMENT) {
- Expression operand= node.getOperand();
- SimpleName name= getSimpleName(operand);
- if (name != null)
- match(name, fWriteUsages, name.resolveBinding());
- }
- return super.visit(node);
- }
-
- public boolean visit(PostfixExpression node) {
- Expression operand= node.getOperand();
- SimpleName name= getSimpleName(operand);
- if (name != null)
- match(name, fWriteUsages, name.resolveBinding());
- return super.visit(node);
- }
-
- private boolean match(Name node, List result, IBinding binding) {
- if (binding != null && Bindings.equals(getBindingDeclaration(binding), fTarget)) {
- result.add(node);
- return true;
- }
- return false;
- }
-
- private boolean matchStaticImport(Name node, List result, IFunctionBinding binding) {
- if (binding == null || node == null || !(fTarget instanceof IFunctionBinding) || !Modifier.isStatic(binding.getModifiers()))
- return false;
-
- IFunctionBinding targetMethodBinding= (IFunctionBinding)fTarget;
- if ((fTargetIsStaticMethodImport || Modifier.isStatic(targetMethodBinding.getModifiers())) && (targetMethodBinding.getDeclaringClass().getTypeDeclaration() == binding.getDeclaringClass().getTypeDeclaration())) {
- if (node.getFullyQualifiedName().equals(targetMethodBinding.getName())) {
- result.add(node);
- return true;
- }
- }
- return false;
- }
-
- private SimpleName getSimpleName(Expression expression) {
- if (expression instanceof SimpleName)
- return ((SimpleName)expression);
- else if (expression instanceof QualifiedName)
- return (((QualifiedName) expression).getName());
- else if (expression instanceof FieldAccess)
- return ((FieldAccess)expression).getName();
- return null;
- }
-
- private IBinding getBindingDeclaration(IBinding binding) {
- switch (binding.getKind()) {
- case IBinding.TYPE :
- return ((ITypeBinding)binding).getTypeDeclaration();
- case IBinding.METHOD :
- return ((IFunctionBinding)binding).getMethodDeclaration();
- case IBinding.VARIABLE :
- return ((IVariableBinding)binding).getVariableDeclaration();
- default:
- return binding;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesGroupKey.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesGroupKey.java
deleted file mode 100644
index 8aea0b5c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesGroupKey.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-public class OccurrencesGroupKey extends JavaElementLine {
- private boolean fIsWriteAccess;
- private boolean fIsVariable;
-
- /**
- * Create a new occurrences group key.
- *
- * @param element either an IJavaScriptUnit or an IClassFile
- * @param line the line number
- * @param lineContents the line contents
- * @param isWriteAccess <code>true</code> if it groups writable occurrences
- * @param isVariable <code>true</code> if it groups variable occurrences
- */
- public OccurrencesGroupKey(IJavaScriptElement element, int line, String lineContents, boolean isWriteAccess, boolean isVariable) {
- super(element, line, lineContents);
- fIsWriteAccess= isWriteAccess;
- fIsVariable= isVariable;
- }
-
- public boolean isVariable() {
- return fIsVariable;
- }
-
- public boolean isWriteAccess() {
- return fIsWriteAccess;
- }
-
- public void setWriteAccess(boolean isWriteAccess) {
- fIsWriteAccess= isWriteAccess;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchLabelProvider.java
deleted file mode 100644
index cce21299..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchLabelProvider.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-class OccurrencesSearchLabelProvider extends TextSearchLabelProvider {
-
- public OccurrencesSearchLabelProvider(AbstractTextSearchViewPage page) {
- super(page);
- }
-
- protected String doGetText(Object element) {
- JavaElementLine jel= (JavaElementLine) element;
- return jel.getLineContents().replace('\t', ' ');
- }
-
- public Image getImage(Object element) {
- if (element instanceof OccurrencesGroupKey) {
- OccurrencesGroupKey group= (OccurrencesGroupKey) element;
- if (group.isVariable()) {
- if (group.isWriteAccess())
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_WRITEACCESS);
- else
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_READACCESS);
- }
-
- } else if (element instanceof ExceptionOccurrencesGroupKey) {
- ExceptionOccurrencesGroupKey group= (ExceptionOccurrencesGroupKey) element;
- if (group.isException())
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- }
-
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_OCCURRENCE);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchQuery.java
deleted file mode 100644
index c4834a35..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchQuery.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.ISearchResult;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-
-public class OccurrencesSearchQuery implements ISearchQuery {
-
- private final OccurrencesSearchResult fResult;
- private IOccurrencesFinder fFinder;
- private IDocument fDocument;
- private final IJavaScriptElement fElement;
- private final String fJobLabel;
- private final String fSingularLabel;
- private final String fPluralLabel;
- private final String fName;
-
- public OccurrencesSearchQuery(IOccurrencesFinder finder, IDocument document, IJavaScriptElement element) {
- fFinder= finder;
- fDocument= document;
- fElement= element;
- fJobLabel= fFinder.getJobLabel();
- fResult= new OccurrencesSearchResult(this);
- fSingularLabel= fFinder.getUnformattedSingularLabel();
- fPluralLabel= fFinder.getUnformattedPluralLabel();
- fName= fFinder.getElementName();
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- public IStatus run(IProgressMonitor monitor) {
- if (fFinder == null) {
- return new StatusInfo(IStatus.ERROR, "Query has already been running"); //$NON-NLS-1$
- }
- try {
- fFinder.perform();
- ArrayList resultingMatches= new ArrayList();
- fFinder.collectOccurrenceMatches(fElement, fDocument, resultingMatches);
- if (!resultingMatches.isEmpty()) {
- fResult.addMatches((Match[]) resultingMatches.toArray(new Match[resultingMatches.size()]));
- }
- //Don't leak AST:
- fFinder= null;
- fDocument= null;
- } finally {
- monitor.done();
- }
- return Status.OK_STATUS;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#getLabel()
- */
- public String getLabel() {
- return fJobLabel;
- }
-
- public String getResultLabel(int nMatches) {
- if (nMatches == 1) {
- return Messages.format(fSingularLabel, new Object[] { fName, fElement.getElementName() });
- } else {
- return Messages.format(fPluralLabel, new Object[] { fName, new Integer(nMatches), fElement.getElementName() });
- }
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#canRerun()
- */
- public boolean canRerun() {
- return false; // must release finder to not keep AST reference
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground()
- */
- public boolean canRunInBackground() {
- return true;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchQuery#getSearchResult()
- */
- public ISearchResult getSearchResult() {
- return fResult;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResult.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResult.java
deleted file mode 100644
index 2005ec82..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResult.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.IEditorMatchAdapter;
-import org.eclipse.search.ui.text.IFileMatchAdapter;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-
-
-public class OccurrencesSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter {
-
- protected static final Match[] NO_MATCHES= new Match[0];
- private OccurrencesSearchQuery fQuery;
-
- public OccurrencesSearchResult(OccurrencesSearchQuery query) {
- fQuery= query;
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.core.resources.IFile)
- */
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IFile file) {
- Object[] elements= getElements();
- if (elements.length == 0)
- return NO_MATCHES;
- //all matches from same file:
- JavaElementLine jel= (JavaElementLine) elements[0];
- try {
- if (file.equals(jel.getJavaElement().getCorrespondingResource()))
- return collectMatches(elements);
- } catch (JavaScriptModelException e) {
- // no resource
- }
- return NO_MATCHES;
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.ui.IEditorPart)
- */
- public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) {
- //TODO same code in JavaSearchResult
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput instanceof IFileEditorInput) {
- IFileEditorInput fileEditorInput= (IFileEditorInput) editorInput;
- return computeContainedMatches(result, fileEditorInput.getFile());
-
- } else if (editorInput instanceof IClassFileEditorInput) {
- IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) editorInput;
- IClassFile classFile= classFileEditorInput.getClassFile();
-
- Object[] elements= getElements();
- if (elements.length == 0)
- return NO_MATCHES;
- //all matches from same file:
- JavaElementLine jel= (JavaElementLine) elements[0];
- if (jel.getJavaElement().equals(classFile))
- return collectMatches(elements);
- }
- return NO_MATCHES;
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getFile(java.lang.Object)
- */
- public IFile getFile(Object element) {
- JavaElementLine jel= (JavaElementLine) element;
- IResource resource= null;
- try {
- resource= jel.getJavaElement().getCorrespondingResource();
- } catch (JavaScriptModelException e) {
- // no resource
- }
- if (resource instanceof IFile)
- return (IFile) resource;
- else
- return null;
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchResult#isShownInEditor(org.eclipse.search.ui.text.Match, org.eclipse.ui.IEditorPart)
- */
- public boolean isShownInEditor(Match match, IEditorPart editor) {
- Object element= match.getElement();
- IJavaScriptElement je= ((JavaElementLine) element).getJavaElement();
- IEditorInput editorInput= editor.getEditorInput();
- if (editorInput instanceof IFileEditorInput) {
- try {
- return ((IFileEditorInput)editorInput).getFile().equals(je.getCorrespondingResource());
- } catch (JavaScriptModelException e) {
- return false;
- }
- } else if (editorInput instanceof IClassFileEditorInput) {
- return ((IClassFileEditorInput)editorInput).getClassFile().equals(je);
- }
-
- return false;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getLabel()
- */
- public String getLabel() {
- return fQuery.getResultLabel(getMatchCount());
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getTooltip()
- */
- public String getTooltip() {
- return getLabel();
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getImageDescriptor()
- */
- public ImageDescriptor getImageDescriptor() {
- return JavaPluginImages.DESC_OBJS_SEARCH_REF;
- }
-
- /*
- * @see org.eclipse.search.ui.ISearchResult#getQuery()
- */
- public ISearchQuery getQuery() {
- return fQuery;
- }
-
- public IFileMatchAdapter getFileMatchAdapter() {
- return this;
- }
-
- public IEditorMatchAdapter getEditorMatchAdapter() {
- return this;
- }
-
- private Match[] collectMatches(Object[] elements) {
- Match[] matches= new Match[getMatchCount()];
- int writeIndex= 0;
- for (int i= 0; i < elements.length; i++) {
- Match[] perElement= getMatches(elements[i]);
- for (int j= 0; j < perElement.length; j++) {
- matches[writeIndex++]= perElement[j];
- }
- }
- return matches;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResultPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResultPage.java
deleted file mode 100644
index 862875bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OccurrencesSearchResultPage.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-
-public class OccurrencesSearchResultPage extends AbstractTextSearchViewPage {
-
- private TextSearchTableContentProvider fContentProvider;
-
- public OccurrencesSearchResultPage() {
- super(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT);
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#showMatch(org.eclipse.search.ui.text.Match, int, int)
- */
- protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException {
- JavaElementLine element= (JavaElementLine) match.getElement();
- IJavaScriptElement javaElement= element.getJavaElement();
- try {
- IEditorPart editor= JavaScriptUI.openInEditor(javaElement, activate, false);
- if (editor instanceof ITextEditor) {
- ITextEditor textEditor= (ITextEditor) editor;
- textEditor.selectAndReveal(currentOffset, currentLength);
- }
- } catch (PartInitException e1) {
- return;
- } catch (JavaScriptModelException e1) {
- return;
- }
-
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#elementsChanged(java.lang.Object[])
- */
- protected void elementsChanged(Object[] objects) {
- if (fContentProvider != null)
- fContentProvider.elementsChanged(objects);
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#clear()
- */
- protected void clear() {
- if (fContentProvider != null)
- fContentProvider.clear();
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTreeViewer(org.eclipse.jface.viewers.TreeViewer)
- */
- protected void configureTreeViewer(TreeViewer viewer) {
- throw new IllegalStateException("Doesn't support tree mode."); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTableViewer(org.eclipse.jface.viewers.TableViewer)
- */
- protected void configureTableViewer(TableViewer viewer) {
- viewer.setComparator(new ViewerComparator() {
- public int compare(Viewer v, Object e1, Object e2) {
- JavaElementLine jel1= (JavaElementLine) e1;
- JavaElementLine jel2= (JavaElementLine) e2;
- return jel1.getLine() - jel2.getLine();
- }
- });
- viewer.setLabelProvider(new OccurrencesSearchLabelProvider(this));
- fContentProvider= new TextSearchTableContentProvider();
- viewer.setContentProvider(fContentProvider);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OpenJavaSearchPageAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OpenJavaSearchPageAction.java
deleted file mode 100644
index 665b0e75..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/OpenJavaSearchPageAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Opens the Search Dialog and brings the Java search page to front
- */
-public class OpenJavaSearchPageAction implements IWorkbenchWindowActionDelegate {
-
- private static final String JAVA_SEARCH_PAGE_ID= "org.eclipse.wst.jsdt.ui.JavaSearchPage"; //$NON-NLS-1$
-
- private IWorkbenchWindow fWindow;
-
- public OpenJavaSearchPageAction() {
- }
-
- public void init(IWorkbenchWindow window) {
- fWindow= window;
- }
-
- public void run(IAction action) {
- if (fWindow == null || fWindow.getActivePage() == null) {
- beep();
- JavaScriptPlugin.logErrorMessage("Could not open the search dialog - for some reason the window handle was null"); //$NON-NLS-1$
- return;
- }
- NewSearchUI.openSearchDialog(fWindow, JAVA_SEARCH_PAGE_ID);
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- // do nothing since the action isn't selection dependent.
- }
-
- public void dispose() {
- fWindow= null;
- }
-
- protected void beep() {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- if (shell != null && shell.getDisplay() != null)
- shell.getDisplay().beep();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PatternStrings.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PatternStrings.java
deleted file mode 100644
index cf4883e4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PatternStrings.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class PatternStrings {
-
- public static String getSignature(IJavaScriptElement element) {
- if (element == null)
- return null;
- else
- switch (element.getElementType()) {
- case IJavaScriptElement.METHOD:
- return getMethodSignature((IFunction)element);
- case IJavaScriptElement.TYPE:
- return getTypeSignature((IType) element);
- case IJavaScriptElement.FIELD:
- return getFieldSignature((IField) element);
- default:
- return element.getElementName();
- }
- }
-
- public static String getMethodSignature(IFunction method) {
- StringBuffer buffer= new StringBuffer();
- if (method.getDeclaringType()!=null)
- {
- buffer.append(JavaScriptElementLabels.getElementLabel(
- method.getDeclaringType(),
- JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.USE_RESOLVED));
- boolean isConstructor= method.getElementName().equals(method.getDeclaringType().getElementName());
- if (!isConstructor) {
- buffer.append('.');
- }
-
- buffer.append(getUnqualifiedMethodSignature(method, !isConstructor));
-
- }
-
-
- return buffer.toString();
- }
-
- private static String getUnqualifiedMethodSignature(IFunction method, boolean includeName) {
- StringBuffer buffer= new StringBuffer();
- if (includeName) {
- buffer.append(method.getElementName());
- }
- buffer.append('(');
-
- String[] types= method.getParameterTypes();
- for (int i= 0; i < types.length; i++) {
- if (i > 0)
- buffer.append(", "); //$NON-NLS-1$
- String typeSig= Signature.toString(types[i]);
- buffer.append(typeSig);
- }
- buffer.append(')');
-
- return buffer.toString();
- }
-
- public static String getUnqualifiedMethodSignature(IFunction method) {
- return getUnqualifiedMethodSignature(method, true);
- }
-
- public static String getTypeSignature(IType field) {
- return JavaScriptElementLabels.getElementLabel(field,
- JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.T_TYPE_PARAMETERS | JavaScriptElementLabels.USE_RESOLVED);
- }
-
- public static String getFieldSignature(IField field) {
- return JavaScriptElementLabels.getElementLabel(field, JavaScriptElementLabels.F_FULLY_QUALIFIED);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PostfixLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PostfixLabelProvider.java
deleted file mode 100644
index 5749a59b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/PostfixLabelProvider.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class PostfixLabelProvider extends SearchLabelProvider {
- private ITreeContentProvider fContentProvider;
-
- public PostfixLabelProvider(JavaSearchResultPage page) {
- super(page);
- fContentProvider= new LevelTreeContentProvider.FastJavaElementProvider();
- }
-
- public Image getImage(Object element) {
- Image image= super.getImage(element);
- if (image != null)
- return image;
- return getParticipantImage(element);
- }
-
- public String getText(Object element) {
- String labelWithCounts= getLabelWithCounts(element, internalGetText(element));
- return labelWithCounts + getQualification(element);
- }
-
- private String getQualification(Object element) {
- StringBuffer res= new StringBuffer();
-
- ITreeContentProvider provider= (ITreeContentProvider) fPage.getViewer().getContentProvider();
- Object visibleParent= provider.getParent(element);
- Object realParent= fContentProvider.getParent(element);
- Object lastElement= element;
- while (realParent != null && !(realParent instanceof IJavaScriptModel) && !realParent.equals(visibleParent)) {
- if (!isSameInformation(realParent, lastElement)) {
- res.append(JavaScriptElementLabels.CONCAT_STRING).append(internalGetText(realParent));
- }
- lastElement= realParent;
- realParent= fContentProvider.getParent(realParent);
- }
- return res.toString();
- }
-
- protected boolean hasChildren(Object element) {
- ITreeContentProvider contentProvider= (ITreeContentProvider) fPage.getViewer().getContentProvider();
- return contentProvider.hasChildren(element);
- }
-
- private String internalGetText(Object element) {
- String text= super.getText(element);
- if (text != null && text.length() > 0)
- return text;
- return getParticipantText(element);
- }
-
- private boolean isSameInformation(Object realParent, Object lastElement) {
- if (lastElement instanceof IType) {
- IType type= (IType) lastElement;
- if (realParent instanceof IClassFile) {
- if (type.getClassFile().equals(realParent))
- return true;
- } else if (realParent instanceof IJavaScriptUnit) {
- if (type.getJavaScriptUnit().equals(realParent))
- return true;
- }
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.IRichLabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- ColoredString coloredString= getColoredLabelWithCounts(element, super.getRichTextLabel(element));
- coloredString.append(getQualification(element), ColoredJavaElementLabels.QUALIFIER_STYLE);
- return coloredString;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchLabelProvider.java
deleted file mode 100644
index f01b8717..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchLabelProvider.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.ui.preferences.ScopedPreferenceStore;
-import org.eclipse.wst.jsdt.core.search.SearchMatch;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-import org.eclipse.wst.jsdt.ui.search.IMatchPresentation;
-
-public abstract class SearchLabelProvider extends AppearanceAwareLabelProvider {
-
- public static final String PROPERTY_MATCH_COUNT= "org.eclipse.wst.jsdt.search.matchCount"; //$NON-NLS-1$
-
- // copied from SearchPreferencePage
- private static final String EMPHASIZE_POTENTIAL_MATCHES= "org.eclipse.search.potentialMatch.emphasize"; //$NON-NLS-1$
- private static final String POTENTIAL_MATCH_FG_COLOR= "org.eclipse.search.potentialMatch.fgColor"; //$NON-NLS-1$
-
- protected static final long DEFAULT_SEARCH_TEXTFLAGS= (DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED) & ~JavaScriptElementLabels.M_APP_RETURNTYPE;
- protected static final int DEFAULT_SEARCH_IMAGEFLAGS= DEFAULT_IMAGEFLAGS;
-
- private Color fPotentialMatchFgColor;
- private Map fLabelProviderMap;
-
- protected JavaSearchResultPage fPage;
-
- private ScopedPreferenceStore fSearchPreferences;
- private IPropertyChangeListener fSearchPropertyListener;
-
- public SearchLabelProvider(JavaSearchResultPage page) {
- super(DEFAULT_SEARCH_TEXTFLAGS, DEFAULT_SEARCH_IMAGEFLAGS);
- addLabelDecorator(new ProblemsLabelDecorator(null));
-
- fPage= page;
- fLabelProviderMap= new HashMap(5);
-
- fSearchPreferences= new ScopedPreferenceStore(new InstanceScope(), NewSearchUI.PLUGIN_ID);
- fSearchPropertyListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doSearchPropertyChange(event);
- }
- };
- fSearchPreferences.addPropertyChangeListener(fSearchPropertyListener);
- }
-
- final void doSearchPropertyChange(PropertyChangeEvent event) {
- if (fPotentialMatchFgColor == null)
- return;
- if (POTENTIAL_MATCH_FG_COLOR.equals(event.getProperty()) || EMPHASIZE_POTENTIAL_MATCHES.equals(event.getProperty())) {
- fPotentialMatchFgColor.dispose();
- fPotentialMatchFgColor= null;
- LabelProviderChangedEvent lpEvent= new LabelProviderChangedEvent(SearchLabelProvider.this, null); // refresh all
- fireLabelProviderChanged(lpEvent);
- }
- }
-
- public Color getForeground(Object element) {
- if (arePotentialMatchesEmphasized()) {
- if (getNumberOfPotentialMatches(element) > 0)
- return getForegroundColor();
- }
- return super.getForeground(element);
- }
-
- private Color getForegroundColor() {
- if (fPotentialMatchFgColor == null) {
- fPotentialMatchFgColor= new Color(JavaScriptPlugin.getActiveWorkbenchShell().getDisplay(), getPotentialMatchForegroundColor());
- }
- return fPotentialMatchFgColor;
- }
-
- protected final int getNumberOfPotentialMatches(Object element) {
- int res= 0;
- AbstractTextSearchResult result= fPage.getInput();
- if (result != null) {
- Match[] matches= result.getMatches(element);
- for (int i = 0; i < matches.length; i++) {
- if ((matches[i]) instanceof JavaElementMatch) {
- if (((JavaElementMatch)matches[i]).getAccuracy() == SearchMatch.A_INACCURATE)
- res++;
- }
- }
- }
- return res;
- }
-
- protected final ColoredString getColoredLabelWithCounts(Object element, ColoredString coloredName) {
- String name= coloredName.getString();
- String decorated= getLabelWithCounts(element, name);
- if (decorated.length() > name.length()) {
- ColoredJavaElementLabels.decorateColoredString(coloredName, decorated, ColoredJavaElementLabels.COUNTER_STYLE);
- }
- return coloredName;
- }
-
- protected final String getLabelWithCounts(Object element, String elementName) {
- int matchCount= fPage.getDisplayedMatchCount(element);
- int potentialCount= getNumberOfPotentialMatches(element);
-
- if (matchCount < 2) {
- if (matchCount == 1 && hasChildren(element)) {
- if (potentialCount > 0)
- return Messages.format(SearchMessages.SearchLabelProvider_potential_singular, elementName);
- return Messages.format(SearchMessages.SearchLabelProvider_exact_singular, elementName);
- }
- if (potentialCount > 0)
- return Messages.format(SearchMessages.SearchLabelProvider_potential_noCount, elementName);
- return Messages.format(SearchMessages.SearchLabelProvider_exact_noCount, elementName);
- } else {
- int exactCount= matchCount - potentialCount;
-
- if (potentialCount > 0 && exactCount > 0) {
- String[] args= new String[] { elementName, String.valueOf(matchCount), String.valueOf(exactCount), String.valueOf(potentialCount) };
- return Messages.format(SearchMessages.SearchLabelProvider_exact_and_potential_plural, args);
- } else if (exactCount == 0) {
- String[] args= new String[] { elementName, String.valueOf(matchCount) };
- return Messages.format(SearchMessages.SearchLabelProvider_potential_plural, args);
- }
- String[] args= new String[] { elementName, String.valueOf(matchCount) };
- return Messages.format(SearchMessages.SearchLabelProvider_exact_plural, args);
- }
- }
-
- protected boolean hasChildren(Object elem) {
- return false;
- }
-
- public void dispose() {
- if (fPotentialMatchFgColor != null) {
- fPotentialMatchFgColor.dispose();
- fPotentialMatchFgColor= null;
- }
- fSearchPreferences.removePropertyChangeListener(fSearchPropertyListener);
- for (Iterator labelProviders = fLabelProviderMap.values().iterator(); labelProviders.hasNext();) {
- ILabelProvider labelProvider = (ILabelProvider) labelProviders.next();
- labelProvider.dispose();
- }
- fSearchPreferences= null;
- fSearchPropertyListener= null;
- fLabelProviderMap.clear();
-
- super.dispose();
- }
-
- public void addListener(ILabelProviderListener listener) {
- super.addListener(listener);
- for (Iterator labelProviders = fLabelProviderMap.values().iterator(); labelProviders.hasNext();) {
- ILabelProvider labelProvider = (ILabelProvider) labelProviders.next();
- labelProvider.addListener(listener);
- }
- }
-
- public boolean isLabelProperty(Object element, String property) {
- if (PROPERTY_MATCH_COUNT.equals(property))
- return true;
- return getLabelProvider(element).isLabelProperty(element, property);
- }
-
- public void removeListener(ILabelProviderListener listener) {
- super.removeListener(listener);
- for (Iterator labelProviders = fLabelProviderMap.values().iterator(); labelProviders.hasNext();) {
- ILabelProvider labelProvider = (ILabelProvider) labelProviders.next();
- labelProvider.removeListener(listener);
- }
- }
-
- protected String getParticipantText(Object element) {
- ILabelProvider labelProvider= getLabelProvider(element);
- if (labelProvider != null)
- return labelProvider.getText(element);
- return ""; //$NON-NLS-1$
-
- }
-
- protected Image getParticipantImage(Object element) {
- ILabelProvider lp= getLabelProvider(element);
- if (lp == null)
- return null;
- return lp.getImage(element);
- }
-
-
- private ILabelProvider getLabelProvider(Object element) {
- IMatchPresentation participant= ((JavaSearchResult) fPage.getInput()).getSearchParticpant(element);
- if (participant == null)
- return null;
-
- ILabelProvider lp= (ILabelProvider) fLabelProviderMap.get(participant);
- if (lp == null) {
- lp= participant.createLabelProvider();
- fLabelProviderMap.put(participant, lp);
-
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- lp.addListener((ILabelProviderListener) listeners[i]);
- }
- }
- return lp;
- }
-
- private boolean arePotentialMatchesEmphasized() {
- return fSearchPreferences.getBoolean(EMPHASIZE_POTENTIAL_MATCHES);
- }
-
- private RGB getPotentialMatchForegroundColor() {
- return PreferenceConverter.getColor(fSearchPreferences, POTENTIAL_MATCH_FG_COLOR);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.java
deleted file mode 100644
index 0808b063..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class SearchMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.search.SearchMessages";//$NON-NLS-1$
-
- private SearchMessages() {
- // Do not instantiate
- }
-
- public static String JavaSearchResultPage_preferences_label;
- public static String JavaSearchScopeFactory_undefined_projects;
- public static String JavaSearchScopeFactory_undefined_selection;
- public static String JavaSearchScopeFactory_undefined_workingsets;
- public static String MatchFilter_DeprecatedFilter_actionLabel;
- public static String MatchFilter_DeprecatedFilter_description;
- public static String MatchFilter_DeprecatedFilter_name;
- public static String MatchFilter_NonDeprecatedFilter_actionLabel;
- public static String MatchFilter_NonDeprecatedFilter_description;
- public static String MatchFilter_NonDeprecatedFilter_name;
- public static String MatchFilter_NonPublicFilter_actionLabel;
- public static String MatchFilter_NonPublicFilter_description;
- public static String MatchFilter_NonPublicFilter_name;
- public static String MatchFilter_NonStaticFilter_actionLabel;
- public static String MatchFilter_NonStaticFilter_description;
- public static String MatchFilter_NonStaticFilter_name;
- public static String MatchFilter_StaticFilter_actionLabel;
- public static String MatchFilter_StaticFilter_description;
- public static String MatchFilter_StaticFilter_name;
- public static String SearchLabelProvider_exact_singular;
- public static String SearchLabelProvider_exact_noCount;
- public static String SearchLabelProvider_exact_and_potential_plural;
- public static String SearchLabelProvider_potential_singular;
- public static String SearchLabelProvider_potential_noCount;
- public static String SearchLabelProvider_potential_plural;
- public static String SearchLabelProvider_exact_plural;
- public static String group_search;
- public static String group_declarations;
- public static String group_references;
- public static String group_readReferences;
- public static String group_writeReferences;
- public static String group_implementors;
- public static String group_occurrences;
- public static String group_occurrences_quickMenu_noEntriesAvailable;
- public static String Search_Error_search_title;
- public static String Search_Error_search_message;
- public static String Search_Error_search_notsuccessful_message;
- public static String Search_Error_javaElementAccess_title;
- public static String Search_Error_javaElementAccess_message;
- public static String Search_Error_search_notsuccessful_title;
- public static String Search_Error_openEditor_title;
- public static String Search_Error_openEditor_message;
- public static String Search_Error_codeResolve;
- public static String SearchElementSelectionDialog_title;
- public static String SearchElementSelectionDialog_message;
- public static String SearchPage_searchFor_label;
- public static String SearchPage_searchFor_type;
- public static String SearchPage_searchFor_method;
- public static String SearchPage_searchFor_function;
- public static String SearchPage_searchFor_var;
- public static String SearchPage_searchFor_field;
- public static String SearchPage_searchFor_constructor;
- public static String SearchPage_limitTo_label;
- public static String SearchPage_limitTo_declarations;
- public static String SearchPage_limitTo_references;
- public static String SearchPage_limitTo_allOccurrences;
- public static String SearchPage_limitTo_readReferences;
- public static String SearchPage_limitTo_writeReferences;
- public static String SearchPage_expression_label;
- public static String SearchPage_expression_caseSensitive;
- public static String SearchPage_searchIn_jre;
- public static String SearchPage_searchIn_label;
- public static String SearchPage_searchIn_libraries;
- public static String SearchPage_searchIn_projects;
- public static String SearchPage_searchIn_sources;
- public static String SearchUtil_workingSetConcatenation;
- public static String Search_FindDeclarationAction_label;
- public static String Search_FindDeclarationAction_tooltip;
- public static String Search_FindDeclarationsInProjectAction_label;
- public static String Search_FindDeclarationsInProjectAction_tooltip;
- public static String Search_FindDeclarationsInWorkingSetAction_label;
- public static String Search_FindDeclarationsInWorkingSetAction_tooltip;
- public static String Search_FindHierarchyDeclarationsAction_label;
- public static String Search_FindHierarchyDeclarationsAction_tooltip;
- public static String Search_FindImplementorsAction_label;
- public static String Search_FindImplementorsAction_tooltip;
- public static String Search_FindImplementorsInProjectAction_label;
- public static String Search_FindImplementorsInProjectAction_tooltip;
- public static String Search_FindImplementorsInWorkingSetAction_label;
- public static String Search_FindImplementorsInWorkingSetAction_tooltip;
- public static String Search_FindReferencesAction_label;
- public static String Search_FindReferencesAction_tooltip;
- public static String Search_FindReferencesAction_BinPrimConstWarnDialog_title;
- public static String Search_FindReferencesAction_BinPrimConstWarnDialog_message;
- public static String Search_FindReferencesInProjectAction_label;
- public static String Search_FindReferencesInProjectAction_tooltip;
- public static String Search_FindReferencesInWorkingSetAction_label;
- public static String Search_FindReferencesInWorkingSetAction_tooltip;
- public static String Search_FindHierarchyReferencesAction_label;
- public static String Search_FindHierarchyReferencesAction_tooltip;
- public static String Search_FindReadReferencesAction_label;
- public static String Search_FindReadReferencesAction_tooltip;
- public static String Search_FindReadReferencesInProjectAction_label;
- public static String Search_FindReadReferencesInProjectAction_tooltip;
- public static String Search_FindReadReferencesInWorkingSetAction_label;
- public static String Search_FindReadReferencesInWorkingSetAction_tooltip;
- public static String Search_FindReadReferencesInHierarchyAction_label;
- public static String Search_FindReadReferencesInHierarchyAction_tooltip;
- public static String Search_FindWriteReferencesAction_label;
- public static String Search_FindWriteReferencesAction_tooltip;
- public static String Search_FindWriteReferencesInProjectAction_label;
- public static String Search_FindWriteReferencesInProjectAction_tooltip;
- public static String Search_FindWriteReferencesInWorkingSetAction_label;
- public static String Search_FindWriteReferencesInWorkingSetAction_tooltip;
- public static String Search_FindWriteReferencesInHierarchyAction_label;
- public static String Search_FindWriteReferencesInHierarchyAction_tooltip;
- public static String Search_FindOccurrencesInFile_shortLabel;
- public static String Search_FindOccurrencesInFile_label;
- public static String Search_FindOccurrencesInFile_tooltip;
- public static String FindOccurrencesEngine_noSource_text;
- public static String FindOccurrencesEngine_cannotParse_text;
- public static String OccurrencesFinder_no_element;
- public static String OccurrencesFinder_no_binding;
- public static String OccurrencesFinder_searchfor;
- public static String OccurrencesFinder_label_singular;
- public static String OccurrencesFinder_label_plural;
- public static String ExceptionOccurrencesFinder_no_exception;
- public static String ExceptionOccurrencesFinder_searchfor;
- public static String ExceptionOccurrencesFinder_label_singular;
- public static String ExceptionOccurrencesFinder_label_plural;
- public static String ImplementOccurrencesFinder_invalidTarget;
- public static String ImplementOccurrencesFinder_searchfor;
- public static String ImplementOccurrencesFinder_label_singular;
- public static String ImplementOccurrencesFinder_label_plural;
- public static String JavaSearchOperation_singularDeclarationsPostfix;
- public static String JavaSearchOperation_singularReferencesPostfix;
- public static String JavaSearchOperation_singularReadReferencesPostfix;
- public static String JavaSearchOperation_singularWriteReferencesPostfix;
- public static String JavaSearchOperation_singularImplementorsPostfix;
- public static String JavaSearchOperation_singularOccurrencesPostfix;
- public static String JavaSearchOperation_pluralDeclarationsPostfix;
- public static String JavaSearchOperation_pluralReferencesPostfix;
- public static String JavaSearchOperation_pluralReadReferencesPostfix;
- public static String JavaSearchOperation_pluralWriteReferencesPostfix;
- public static String JavaSearchOperation_pluralImplementorsPostfix;
- public static String JavaSearchOperation_pluralOccurrencesPostfix;
- public static String JavaElementAction_typeSelectionDialog_title;
- public static String JavaElementAction_typeSelectionDialog_message;
- public static String JavaElementAction_error_open_message;
- public static String JavaElementAction_operationUnavailable_title;
- public static String JavaElementAction_operationUnavailable_generic;
- public static String JavaElementAction_operationUnavailable_field;
- public static String JavaElementAction_operationUnavailable_interface;
- public static String WorkspaceScope;
- public static String WorkspaceScopeNoJRE;
- public static String SingleWorkingSetScope;
- public static String SingleWorkingSetScopeNoJRE;
- public static String DoubleWorkingSetScope;
- public static String DoubleWorkingSetScopeNoJRE;
- public static String WorkingSetsScope;
- public static String WorkingSetsScopeNoJRE;
-
- public static String SelectionScope;
- public static String SelectionScopeNoJRE;
- public static String SingleSelectionScope;
- public static String SingleSelectionScopeNoJRE;
- public static String DoubleSelectionScope;
- public static String DoubleSelectionScopeNoJRE;
- public static String EnclosingProjectsScope;
- public static String EnclosingProjectsScopeNoJRE;
- public static String EnclosingProjectsScope2;
- public static String EnclosingProjectsScope2NoJRE;
- public static String EnclosingProjectScope;
- public static String EnclosingProjectScopeNoJRE;
- public static String ProjectScope;
- public static String ProjectScopeNoJRE;
- public static String HierarchyScope;
- public static String JavaSearchResultPage_sortByName;
- public static String JavaSearchResultPage_sortByPath;
- public static String JavaSearchResultPage_open_editor_error_title;
- public static String JavaSearchResultPage_open_editor_error_message;
- public static String JavaSearchResultPage_sortByParentName;
- public static String JavaSearchResultPage_filtered_message;
- public static String JavaSearchResultPage_sortBylabel;
- public static String JavaSearchResultPage_error_marker;
- public static String JavaSearchResultPage_groupby_project;
- public static String JavaSearchResultPage_groupby_project_tooltip;
- public static String JavaSearchResultPage_groupby_package;
- public static String JavaSearchResultPage_groupby_package_tooltip;
- public static String JavaSearchResultPage_filteredWithCount_message;
- public static String JavaSearchResultPage_groupby_file;
- public static String JavaSearchResultPage_groupby_file_tooltip;
- public static String JavaSearchResultPage_groupby_type;
- public static String JavaSearchResultPage_groupby_type_tooltip;
- public static String JavaSearchQuery_task_label;
- public static String JavaSearchQuery_label;
- public static String JavaSearchQuery_error_unsupported_pattern;
- public static String JavaSearchQuery_status_ok_message;
- public static String JavaSearchQuery_error_participant_estimate;
- public static String JavaSearchQuery_error_participant_search;
- public static String SearchParticipant_error_noID;
- public static String SearchParticipant_error_noNature;
- public static String SearchParticipant_error_noClass;
- public static String SearchParticipant_error_classCast;
- public static String MatchFilter_ImportFilter_name;
- public static String MatchFilter_ImportFilter_actionLabel;
- public static String MatchFilter_ImportFilter_description;
- public static String MatchFilter_WriteFilter_name;
- public static String MatchFilter_WriteFilter_actionLabel;
- public static String MatchFilter_WriteFilter_description;
- public static String MatchFilter_ReadFilter_name;
- public static String MatchFilter_ReadFilter_actionLabel;
- public static String MatchFilter_ReadFilter_description;
- public static String MatchFilter_JavadocFilter_name;
- public static String MatchFilter_JavadocFilter_actionLabel;
- public static String MatchFilter_JavadocFilter_description;
- public static String MatchFilter_PolymorphicFilter_name;
- public static String MatchFilter_PolymorphicFilter_actionLabel;
- public static String MatchFilter_PolymorphicFilter_description;
- public static String MatchFilter_ErasureFilter_name;
- public static String MatchFilter_ErasureFilter_actionLabel;
- public static String MatchFilter_ErasureFilter_description;
- public static String MatchFilter_InexactFilter_name;
- public static String MatchFilter_InexactFilter_actionLabel;
- public static String MatchFilter_InexactFilter_description;
- public static String MethodExitsFinder_no_return_type_selected;
- public static String BreakContinueTargetFinder_cannot_highlight;
- public static String BreakContinueTargetFinder_no_break_or_continue_selected;
- public static String TextSearchLabelProvider_matchCountFormat;
- static {
- NLS.initializeMessages(BUNDLE_NAME, SearchMessages.class);
- }
-
- public static String JavaSearchQuery_error_element_does_not_exist;
- public static String MatchFilter_PotentialFilter_name;
- public static String MatchFilter_PotentialFilter_actionLabel;
- public static String MatchFilter_PotentialFilter_description;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties
deleted file mode 100644
index 8d2bb465..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties
+++ /dev/null
@@ -1,312 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-SearchLabelProvider_exact_singular={0} (1 match)
-SearchLabelProvider_exact_noCount={0}
-SearchLabelProvider_exact_and_potential_plural={0} ({1} matches: {2} exact, {3} potential)
-SearchLabelProvider_potential_singular={0} (potential match)
-SearchLabelProvider_potential_noCount={0} (potential match)
-SearchLabelProvider_potential_plural={0} ({1} potential matches)
-SearchLabelProvider_exact_plural={0} ({1} matches)
-
-group_search=S&earch
-group_declarations= Dec&larations
-group_references= Re&ferences
-group_readReferences= &Read Access
-group_writeReferences= &Write Access
-group_implementors= &Implementors
-group_occurrences= Occurre&nces in File
-group_occurrences_quickMenu_noEntriesAvailable= <no entries available>
-
-Search_Error_search_title=Search Error
-Search_Error_search_message=The search operation has reported problems
-Search_Error_search_notsuccessful_message=The search operation has reported problems
-Search_Error_javaElementAccess_title=Search Error
-Search_Error_javaElementAccess_message=An error occurred while accessing a JavaScript element
-
-Search_Error_search_notsuccessful_title=Search
-
-Search_Error_openEditor_title=Search Error
-Search_Error_openEditor_message=Could not open the editor
-
-Search_Error_codeResolve= Code resolve error
-
-SearchElementSelectionDialog_title=Search
-SearchElementSelectionDialog_message=Select the element to search for.
-
-SearchPage_searchFor_label= Search For
-SearchPage_searchFor_type= &Type
-SearchPage_searchIn_label=Search In
-SearchPage_searchIn_jre=Browser libraries
-SearchPage_searchFor_method= &Method
-SearchPage_searchFor_function= Fu&nction
-SearchPage_searchIn_sources=Sourc&es
-SearchPage_searchFor_field= &Field
-SearchPage_searchFor_var= &Var
-SearchPage_searchIn_projects=Re&quired projects
-SearchPage_searchIn_libraries=Applicatio&n libraries
-SearchPage_searchFor_constructor= Constr&uctor
-
-SearchPage_limitTo_label= Limit To
-SearchPage_limitTo_declarations= Dec&larations
-SearchPage_limitTo_references= &References
-SearchPage_limitTo_allOccurrences= All &occurrences
-SearchPage_limitTo_readReferences= Read a&ccesses
-SearchPage_limitTo_writeReferences= Wr&ite accesses
-
-SearchPage_expression_label= Se&arch string (* = any string, ? = any character):
-SearchPage_expression_caseSensitive= Case sensiti&ve
-
-
-# Concatenate two working set names e.g. "Source, Lib"
-SearchUtil_workingSetConcatenation= {0}, {1}
-
-Search_FindDeclarationAction_label= &Workspace
-Search_FindDeclarationAction_tooltip= Search for Declarations of the Selected Element in the Workspace
-
-Search_FindDeclarationsInProjectAction_label= &Project
-Search_FindDeclarationsInProjectAction_tooltip= Search for Declarations of the Selected Element in Resources in the Enclosing Project of the Selected Element
-
-Search_FindDeclarationsInWorkingSetAction_label= Working &Set...
-Search_FindDeclarationsInWorkingSetAction_tooltip= Search for Declarations of the Selected Element in a Working Set
-
-Search_FindHierarchyDeclarationsAction_label= &Hierarchy
-Search_FindHierarchyDeclarationsAction_tooltip= Search for Declarations of the Selected Element in its Hierarchy
-
-Search_FindImplementorsAction_label= &Workspace
-Search_FindImplementorsAction_tooltip= Search for Implementors of the Selected Interface
-
-Search_FindImplementorsInProjectAction_label= &Project
-Search_FindImplementorsInProjectAction_tooltip= Search for Implementors of the Selected Interface in Resources in the Enclosing Project of the Selected Element
-
-Search_FindImplementorsInWorkingSetAction_label= Working &Set...
-Search_FindImplementorsInWorkingSetAction_tooltip= Search for Implementors of the Selected Interface in a Working Set
-
-Search_FindReferencesAction_label= &Workspace
-Search_FindReferencesAction_tooltip= Search for References to the Selected Element in the Workspace
-
-Search_FindReferencesAction_BinPrimConstWarnDialog_title= Search for References to a Binary Constant
-Search_FindReferencesAction_BinPrimConstWarnDialog_message= Matches to this constant will only be discovered in source files and binary files where the constant value is not inlined.
-
-Search_FindReferencesInProjectAction_label= &Project
-Search_FindReferencesInProjectAction_tooltip= Search for References to the Selected Element in Resources in the Enclosing Project of the Selected Element
-
-Search_FindReferencesInWorkingSetAction_label= Working &Set...
-Search_FindReferencesInWorkingSetAction_tooltip= Search for References to the Selected Element in a Working Set
-
-Search_FindHierarchyReferencesAction_label= &Hierarchy
-Search_FindHierarchyReferencesAction_tooltip= Search for References of the Selected Element in its Hierarchy
-
-Search_FindReadReferencesAction_label= &Workspace
-Search_FindReadReferencesAction_tooltip= Search for Read References to the Selected Element in the Workspace
-
-Search_FindReadReferencesInProjectAction_label= &Project
-Search_FindReadReferencesInProjectAction_tooltip= Search for Read References to the Selected Element in Resources in the Enclosing Project of the Selected Element
-
-Search_FindReadReferencesInWorkingSetAction_label= Working &Set...
-Search_FindReadReferencesInWorkingSetAction_tooltip= Search for Read References to the Selected Element in a Working Set
-
-Search_FindReadReferencesInHierarchyAction_label= &Hierarchy
-Search_FindReadReferencesInHierarchyAction_tooltip= Search for Read References of the Selected Element in its Hierarchy
-
-Search_FindWriteReferencesAction_label= &Workspace
-Search_FindWriteReferencesAction_tooltip= Search for Write References to the Selected Element in the Workspace
-
-Search_FindWriteReferencesInProjectAction_label= &Project
-Search_FindWriteReferencesInProjectAction_tooltip= Search for Write References to the Selected Element in Resources in the Enclosing Project of the Selected Element
-
-Search_FindWriteReferencesInWorkingSetAction_label= Working &Set...
-Search_FindWriteReferencesInWorkingSetAction_tooltip= Search for Write References to the Selected Element in a Working Set
-
-Search_FindWriteReferencesInHierarchyAction_label= &Hierarchy
-Search_FindWriteReferencesInHierarchyAction_tooltip= Search for Write References of the Selected Element in its Hierarchy
-
-Search_FindOccurrencesInFile_shortLabel= &Identifier
-Search_FindOccurrencesInFile_label= I&dentifiers in File
-Search_FindOccurrencesInFile_tooltip= Find Occurrences of the Selected Element in the Editor
-
-FindOccurrencesEngine_noSource_text= No source available. To perform this operation you need to attach source.
-FindOccurrencesEngine_cannotParse_text= Cannot analyze the JavaScript file or class file.
-
-OccurrencesFinder_no_element= Cannot search for the current selection. Please select a valid JavaScript element name.
-OccurrencesFinder_no_binding= Selected JavaScript element is unknown.
-OccurrencesFinder_searchfor=Search for Occurrences in File
-# The first argument will be replaced by the element name and the second one by the file name
-OccurrencesFinder_label_singular=''{0}'' - 1 occurrence in ''{1}''
-# The first argument will be replaced by the element name, the second by the count and the last by the file name
-OccurrencesFinder_label_plural=''{0}'' - {1} occurrences in ''{2}''
-
-ExceptionOccurrencesFinder_no_exception= Cannot search for current selection. Please select an exception.
-ExceptionOccurrencesFinder_searchfor= Search for Exception Occurrences
-
-# The first argument will be replaced by the element name and the second one by the file name
-ExceptionOccurrencesFinder_label_singular=''{0}'' - 1 exception occurrence in ''{1}''
-# The first argument will be replaced by the element name, the second by the count and the last by the file name
-ExceptionOccurrencesFinder_label_plural=''{0}'' - {1} exception occurrences in ''{2}''
-
-ImplementOccurrencesFinder_invalidTarget= Cannot search for current selection. Please select a type behind 'implements' or 'extends'.
-ImplementOccurrencesFinder_searchfor= Search for Implement Occurrences
-
-# The first argument will be replaced by the element name and the second one by the file name
-ImplementOccurrencesFinder_label_singular=''{0}'' - 1 implement occurrence in ''{1}''
-# The first argument will be replaced by the element name, the second by the count and the last by the file name
-ImplementOccurrencesFinder_label_plural=''{0}'' - {1} implement occurrences in ''{2}''
-
-
-# The first argument will be replaced by the pattern and the second by the scope
-JavaSearchOperation_singularDeclarationsPostfix=''{0}'' - 1 declaration in {1}
-JavaSearchOperation_singularReferencesPostfix=''{0}'' - 1 reference in {1}
-JavaSearchOperation_singularReadReferencesPostfix=''{0}'' - 1 read reference in {1}
-JavaSearchOperation_singularWriteReferencesPostfix=''{0}'' - 1 write reference in {1}
-JavaSearchOperation_singularImplementorsPostfix=''{0}'' - 1 implementor in {1}
-JavaSearchOperation_singularOccurrencesPostfix=''{0}'' - 1 occurrence in {1}
-
-JavaSearchOperation_pluralDeclarationsPostfix=''{0}'' - {1} declarations in {2}
-JavaSearchOperation_pluralReferencesPostfix=''{0}'' - {1} references in {2}
-JavaSearchOperation_pluralReadReferencesPostfix=''{0}'' - {1} read references in {2}
-JavaSearchOperation_pluralWriteReferencesPostfix=''{0}'' - {1} write references in {2}
-JavaSearchOperation_pluralImplementorsPostfix=''{0}'' - {1} implementors in {2}
-JavaSearchOperation_pluralOccurrencesPostfix=''{0}'' - {1} occurrences in {2}
-JavaElementAction_typeSelectionDialog_title=Search
-JavaElementAction_typeSelectionDialog_message=&Select the type to search:
-JavaElementAction_error_open_message=An exception occurred while opening the type.
-
-JavaElementAction_operationUnavailable_title= Operation Unavailable
-JavaElementAction_operationUnavailable_generic= The operation is unavailable on the current selection. Please select a valid JavaScript element name.
-JavaElementAction_operationUnavailable_field= The operation is unavailable on the current selection. Please select the name of a field or local variable.
-JavaElementAction_operationUnavailable_interface= The operation is unavailable on the current selection. Please select the name of an interface.
-
-WorkspaceScope= workspace
-WorkspaceScopeNoJRE= workspace (no Browser Library)
-
-SingleWorkingSetScope= working set ''{0}''
-SingleWorkingSetScopeNoJRE= working set ''{0}'' (no Browser Library)
-DoubleWorkingSetScope= working sets ''{0}'', ''{1}''
-DoubleWorkingSetScopeNoJRE= working set ''{0}'', ''{1}'' (no Browser Library)
-WorkingSetsScope= working set ''{0}'', ''{1}'', ...
-WorkingSetsScopeNoJRE= working set ''{0}'', ''{1}'', ... (no Browser Library)
-
-SingleSelectionScope= ''{0}''
-SingleSelectionScopeNoJRE= ''{0}'' (no Browser Library)
-DoubleSelectionScope= ''{0}'', ''{1}''
-DoubleSelectionScopeNoJRE= ''{0}'', ''{1}'' (no Browser Library)
-SelectionScope= ''{0}'', ''{1}'', ...
-SelectionScopeNoJRE= ''{0}'', ''{1}'', ... (no Browser Library)
-
-EnclosingProjectsScope=projects ''{0}'', ''{1}'', ...
-EnclosingProjectsScopeNoJRE=projects ''{0}'', ''{1}'', ... (no Browser Library)
-EnclosingProjectScope=project ''{0}''
-EnclosingProjectScopeNoJRE=project ''{0}'' (no Browser Library)
-EnclosingProjectsScope2=projects ''{0}'', ''{1}''
-EnclosingProjectsScope2NoJRE=projects ''{0}'', ''{1}'' (no Browser Library)
-
-ProjectScope= project ''{0}''
-ProjectScopeNoJRE= project ''{0}'' (no Browser Library)
-HierarchyScope= hierarchy of ''{0}''
-
-JavaSearchResultPage_sortByName=Name
-JavaSearchResultPage_sortByPath=Path
-JavaSearchResultPage_open_editor_error_title=Open Element
-JavaSearchResultPage_open_editor_error_message=Opening element failed.
-JavaSearchResultPage_sortByParentName=Parent Name
-JavaSearchResultPage_filtered_message={0} (Filtered)
-JavaSearchResultPage_preferences_label=Preferences...
-JavaSearchResultPage_sortBylabel=Sort By
-JavaSearchResultPage_error_marker=Could not create marker
-
-JavaSearchResultPage_groupby_project=Project
-JavaSearchResultPage_groupby_project_tooltip=Group by Project
-JavaSearchResultPage_groupby_package=Namespace
-JavaSearchResultPage_groupby_package_tooltip=Group by NameSpace
-JavaSearchResultPage_filteredWithCount_message={0} ({1} matches filtered from view)
-JavaSearchResultPage_groupby_file=File
-JavaSearchResultPage_groupby_file_tooltip=Group by File
-JavaSearchResultPage_groupby_type=Type
-JavaSearchResultPage_groupby_type_tooltip=Group by Type
-
-JavaSearchQuery_task_label=Searching for ''{0}''...
-JavaSearchQuery_label=JavaScript Search
-JavaSearchQuery_error_unsupported_pattern=Unsupported search pattern: "{0}"
-JavaSearchScopeFactory_undefined_projects=empty scope
-JavaSearchQuery_status_ok_message=Found {0} matches.
-
-JavaSearchQuery_error_participant_estimate=An error occurred while estimating progress data
-JavaSearchScopeFactory_undefined_selection=empty scope
-JavaSearchQuery_error_element_does_not_exist=Element ''{0}'' does not exist anymore
-JavaSearchScopeFactory_undefined_workingsets=empty scope
-JavaSearchQuery_error_participant_search=An error occurred during participant search
-
-SearchParticipant_error_noID=Missing id attribute on search participant extension {0}
-SearchParticipant_error_noNature=Missing nature attribute on search participant {0}
-SearchParticipant_error_noClass=Missing class attribute on search participant {0}
-SearchParticipant_error_classCast=Search participant doesn't implement IQueryParticipant
-
-
-MatchFilter_ImportFilter_name=In imports
-MatchFilter_ImportFilter_actionLabel=In &Imports
-MatchFilter_ImportFilter_description=Filters matches that are in import statements
-
-
-MatchFilter_WriteFilter_name=Writes
-MatchFilter_WriteFilter_actionLabel=&Writes
-MatchFilter_WriteFilter_description=Filters matches that are write accesses
-
-MatchFilter_ReadFilter_name=Reads
-MatchFilter_ReadFilter_actionLabel=&Reads
-MatchFilter_ReadFilter_description=Filters matches that are not write accesses
-
-MatchFilter_JavadocFilter_name=In JSDoc
-MatchFilter_JavadocFilter_actionLabel=In &JSDoc
-MatchFilter_JavadocFilter_description=Filters matches that are inside JSDoc comments
-
-MatchFilter_PolymorphicFilter_name=References to overridden
-MatchFilter_PolymorphicFilter_actionLabel=References to &Overridden
-MatchFilter_PolymorphicFilter_description=Filters references to methods that are declared in a supertype. Calling these methods may or may not invoke the search target at run time.
-
-MatchFilter_ErasureFilter_name=Incompatible type arguments
-MatchFilter_ErasureFilter_actionLabel=In&compatible Type Arguments
-MatchFilter_ErasureFilter_description=Filters parameterized type matches that are not assignment compatible with the search pattern
-
-MatchFilter_InexactFilter_name=Inexact type arguments
-MatchFilter_InexactFilter_actionLabel=Ine&xact Type Arguments
-MatchFilter_InexactFilter_description=Filters parameterized type matches where the type arguments don't exactly match the search pattern's type arguments
-
-MatchFilter_PotentialFilter_name=Potential matches
-MatchFilter_PotentialFilter_actionLabel=&Potential matches
-MatchFilter_PotentialFilter_description=Filters potential matches (usually due to a problem with the include path).
-
-MatchFilter_NonPublicFilter_name=In non-public
-MatchFilter_NonPublicFilter_actionLabel=In &Non-Public
-MatchFilter_NonPublicFilter_description=Filters matches that are inside non-public members
-
-MatchFilter_StaticFilter_name=In static
-MatchFilter_StaticFilter_actionLabel=In &Static
-MatchFilter_StaticFilter_description=Filters matches that are inside static members
-
-MatchFilter_NonStaticFilter_name=In non-static
-MatchFilter_NonStaticFilter_actionLabel=In Non-St&atic
-MatchFilter_NonStaticFilter_description=Filters matches that are inside non-static members
-
-MatchFilter_DeprecatedFilter_name=In deprecated
-MatchFilter_DeprecatedFilter_actionLabel=In &Deprecated
-MatchFilter_DeprecatedFilter_description=Filters matches that are inside deprecated members
-
-MatchFilter_NonDeprecatedFilter_name=In non-deprecated
-MatchFilter_NonDeprecatedFilter_actionLabel=In Non-Dep&recated
-MatchFilter_NonDeprecatedFilter_description=Filters matches that are inside non-deprecated members
-
-MethodExitsFinder_no_return_type_selected=No return type selected
-
-BreakContinueTargetFinder_cannot_highlight=Occurrences in this element cannot be highlighted
-BreakContinueTargetFinder_no_break_or_continue_selected=No break or continue selected
-
-TextSearchLabelProvider_matchCountFormat={0} ({1} matches)
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantDescriptor.java
deleted file mode 100644
index 26b508a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantDescriptor.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.search.IQueryParticipant;
-
-/**
- */
-public class SearchParticipantDescriptor {
- private static final String CLASS= "class"; //$NON-NLS-1$
- private static final String NATURE= "nature"; //$NON-NLS-1$
- private static final String ID= "id"; //$NON-NLS-1$
-
- private IConfigurationElement fConfigurationElement;
- private boolean fEnabled; //
-
- protected SearchParticipantDescriptor(IConfigurationElement configElement) {
- fConfigurationElement= configElement;
- fEnabled= true;
- }
-
- /**
- * checks whether a participant has all the proper attributes.
- *
- * @return returns a status describing the result of the validation
- */
- protected IStatus checkSyntax() {
- if (fConfigurationElement.getAttribute(ID) == null) {
- String format= SearchMessages.SearchParticipant_error_noID;
- String message= Messages.format(format, new String[] { fConfigurationElement.getDeclaringExtension().getUniqueIdentifier() });
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, message, null);
- }
- if (fConfigurationElement.getAttribute(NATURE) == null) {
- String format= SearchMessages.SearchParticipant_error_noNature;
- String message= Messages.format(format, new String[] { fConfigurationElement.getAttribute(ID)});
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, message, null);
- }
-
- if (fConfigurationElement.getAttribute(CLASS) == null) {
- String format= SearchMessages.SearchParticipant_error_noClass;
- String message= Messages.format(format, new String[] { fConfigurationElement.getAttribute(ID)});
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, message, null);
- }
- return Status.OK_STATUS;
- }
-
- public String getID() {
- return fConfigurationElement.getAttribute(ID);
- }
-
- public void disable() {
- fEnabled= false;
- }
-
- public boolean isEnabled() {
- return fEnabled;
- }
-
- protected IQueryParticipant create() throws CoreException {
- try {
- return (IQueryParticipant) fConfigurationElement.createExecutableExtension(CLASS);
- } catch (ClassCastException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, SearchMessages.SearchParticipant_error_classCast, e));
- }
- }
-
- protected String getNature() {
- return fConfigurationElement.getAttribute(NATURE);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantRecord.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantRecord.java
deleted file mode 100644
index 27823bd8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantRecord.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.wst.jsdt.ui.search.IQueryParticipant;
-
-/**
- */
-public class SearchParticipantRecord {
- private SearchParticipantDescriptor fDescriptor;
- private IQueryParticipant fParticipant;
-
- public SearchParticipantRecord(SearchParticipantDescriptor descriptor, IQueryParticipant participant) {
- super();
- fDescriptor= descriptor;
- fParticipant= participant;
- }
- /**
- * @return Returns the descriptor.
- */
- public SearchParticipantDescriptor getDescriptor() {
- return fDescriptor;
- }
- /**
- * @return Returns the participant.
- */
- public IQueryParticipant getParticipant() {
- return fParticipant;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantsExtensionPoint.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantsExtensionPoint.java
deleted file mode 100644
index 3c5e4d26..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchParticipantsExtensionPoint.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/*
- * Created on Apr 13, 2004
- *
- * TODO To change the template for this generated file go to Window -
- * Preferences - Java - Code Generation - Code and Comments
- */
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class SearchParticipantsExtensionPoint {
-
- private Set fActiveParticipants= null;
- private static SearchParticipantsExtensionPoint fgInstance;
-
- public boolean hasAnyParticipants() {
- return Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT).length > 0;
- }
-
- private synchronized Set getAllParticipants() {
- if (fActiveParticipants != null)
- return fActiveParticipants;
- IConfigurationElement[] allParticipants= Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT);
- fActiveParticipants= new HashSet(allParticipants.length);
- for (int i= 0; i < allParticipants.length; i++) {
- SearchParticipantDescriptor descriptor= new SearchParticipantDescriptor(allParticipants[i]);
- IStatus status= descriptor.checkSyntax();
- if (status.isOK()) {
- fActiveParticipants.add(descriptor);
- } else {
- JavaScriptPlugin.log(status);
- }
- }
- return fActiveParticipants;
- }
-
- private void collectParticipants(Set participants, IProject[] projects) {
- Iterator activeParticipants= getAllParticipants().iterator();
- Set seenParticipants= new HashSet();
- while (activeParticipants.hasNext()) {
- SearchParticipantDescriptor participant= (SearchParticipantDescriptor) activeParticipants.next();
- if (participant.isEnabled()) {
- String id= participant.getID();
- for (int i= 0; i < projects.length; i++) {
- if (seenParticipants.contains(id))
- continue;
- try {
- if (projects[i].hasNature(participant.getNature())) {
- participants.add(new SearchParticipantRecord(participant, participant.create()));
- seenParticipants.add(id);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e.getStatus());
- participant.disable();
- }
- }
- }
- }
- }
-
-
-
- public SearchParticipantRecord[] getSearchParticipants(IProject[] concernedProjects) throws CoreException {
- Set participantSet= new HashSet();
- collectParticipants(participantSet, concernedProjects);
- SearchParticipantRecord[] participants= new SearchParticipantRecord[participantSet.size()];
- return (SearchParticipantRecord[]) participantSet.toArray(participants);
- }
-
- public static SearchParticipantsExtensionPoint getInstance() {
- if (fgInstance == null)
- fgInstance= new SearchParticipantsExtensionPoint();
- return fgInstance;
- }
-
- public static void debugSetInstance(SearchParticipantsExtensionPoint instance) {
- fgInstance= instance;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchResultUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchResultUpdater.java
deleted file mode 100644
index cff0e3ab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchResultUpdater.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.search.ui.IQueryListener;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class SearchResultUpdater implements IElementChangedListener, IQueryListener {
-
- JavaSearchResult fResult;
- private static final int REMOVED_FLAGS= IJavaScriptElementDelta.F_MOVED_TO |
- IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH |
- IJavaScriptElementDelta.F_CLOSED |
- IJavaScriptElementDelta.F_CONTENT;
-
- public SearchResultUpdater(JavaSearchResult result) {
- fResult= result;
- NewSearchUI.addQueryListener(this);
- JavaScriptCore.addElementChangedListener(this);
- // TODO make this work with resources
- }
-
- public void elementChanged(ElementChangedEvent event) {
- //long t0= System.currentTimeMillis();
- IJavaScriptElementDelta delta= event.getDelta();
- Set removedElements= new HashSet();
- Set potentiallyRemovedElements= new HashSet();
- collectRemoved(potentiallyRemovedElements, removedElements, delta);
- if (removedElements.size() > 0)
- handleRemoved(removedElements);
- if (potentiallyRemovedElements.size() > 0)
- handleRemoved(potentiallyRemovedElements);
- //System.out.println(this+"handled delta in: "+(System.currentTimeMillis()-t0));
- }
-
- private void handleRemoved(Set removedElements) {
- Object[] elements= fResult.getElements();
- for (int i= 0; i < elements.length; i++) {
- if (isContainedInRemoved(removedElements, elements[i])) {
- if (elements[i] instanceof IJavaScriptElement) {
- IJavaScriptElement je= (IJavaScriptElement)elements[i];
- if (!je.exists()) {
- //System.out.println("removing: "+je+" in "+fResult.getUserData());
- Match[] matches= fResult.getMatches(elements[i]);
- for (int j= 0; j < matches.length; j++) {
- fResult.removeMatch(matches[j]);
- }
- }
- } else if (elements[i] instanceof IResource) {
- IResource resource= (IResource)elements[i];
- if (!resource.exists()) {
- //System.out.println("removing: "+resource+" in "+fResult.getUserData());
- Match[] matches= fResult.getMatches(elements[i]);
- for (int j= 0; j < matches.length; j++) {
- fResult.removeMatch(matches[j]);
- }
- }
-
- }
- }
- }
- }
-
- private boolean isContainedInRemoved(Set removedElements, Object object) {
- for (Iterator elements= removedElements.iterator(); elements.hasNext();) {
- if (isParentOf(elements.next(), object))
- return true;
- }
- return false;
- }
-
- private boolean isParentOf(Object ancestor, Object descendant) {
- while (descendant != null && !ancestor.equals(descendant))
- descendant= getParent(descendant);
- return descendant != null;
- }
-
- private Object getParent(Object object) {
- if (object instanceof IJavaScriptElement)
- return ((IJavaScriptElement)object).getParent();
- else if (object instanceof IResource)
- return ((IResource)object).getParent();
- return null;
- }
-
- private void collectRemoved(Set potentiallyRemovedSet, Set removedElements, IJavaScriptElementDelta delta) {
- if (delta.getKind() == IJavaScriptElementDelta.REMOVED)
- removedElements.add(delta.getElement());
- else if (delta.getKind() == IJavaScriptElementDelta.CHANGED) {
- int flags= delta.getFlags();
- if ((flags & REMOVED_FLAGS) != 0) {
- potentiallyRemovedSet.add(delta.getElement());
- } else {
- IJavaScriptElementDelta[] childDeltas= delta.getAffectedChildren();
- for (int i= 0; i < childDeltas.length; i++) {
- collectRemoved(potentiallyRemovedSet, removedElements, childDeltas[i]);
- }
- }
- }
- IResourceDelta[] resourceDeltas= delta.getResourceDeltas();
- if (resourceDeltas != null) {
- for (int i= 0; i < resourceDeltas.length; i++) {
- collectRemovals(removedElements, resourceDeltas[i]);
- }
- }
- }
-
- public void queryAdded(ISearchQuery query) {
- // don't care
- }
-
- public void queryRemoved(ISearchQuery query) {
- if (fResult.equals(query.getSearchResult())) {
- JavaScriptCore.removeElementChangedListener(this);
- NewSearchUI.removeQueryListener(this);
- }
- }
-
- private void collectRemovals(Set removals, IResourceDelta delta) {
- if (delta.getKind() == IResourceDelta.REMOVED)
- removals.add(delta.getResource());
- else {
- IResourceDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- collectRemovals(removals, children[i]);
- }
- }
- }
-
- public void queryStarting(ISearchQuery query) {
- // not interested
- }
-
- public void queryFinished(ISearchQuery query) {
- // not interested
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchUtil.java
deleted file mode 100644
index 0de796f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchUtil.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.search.ui.ISearchQuery;
-import org.eclipse.search.ui.NewSearchUI;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.osgi.framework.Bundle;
-
-/**
- * This class contains some utility methods for J Search.
- */
-public class SearchUtil {
-
- // LRU working sets
- public static final int LRU_WORKINGSET_LIST_SIZE= 3;
- private static LRUWorkingSetsList fgLRUWorkingSets;
-
- // Settings store
- private static final String DIALOG_SETTINGS_KEY= "JavaElementSearchActions"; //$NON-NLS-1$
- private static final String STORE_LRU_WORKING_SET_NAMES= "lastUsedWorkingSetNames"; //$NON-NLS-1$
-
- private static final String BIN_PRIM_CONST_WARN_DIALOG_ID= "BinaryPrimitiveConstantWarningDialog"; //$NON-NLS-1$
-
- public static boolean isSearchPlugInActivated() {
- return Platform.getBundle("org.eclipse.search").getState() == Bundle.ACTIVE; //$NON-NLS-1$
- }
-
-
- /**
- * This helper method with Object as parameter is needed to prevent the loading
- * of the Search plug-in: the VM verifies the method call and hence loads the
- * types used in the method signature, eventually triggering the loading of
- * a plug-in (in this case ISearchQuery results in Search plug-in being loaded).
- */
- public static void runQueryInBackground(Object query) {
- NewSearchUI.runQueryInBackground((ISearchQuery)query);
- }
-
- /**
- * This helper method with Object as parameter is needed to prevent the loading
- * of the Search plug-in: the VM verifies the method call and hence loads the
- * types used in the method signature, eventually triggering the loading of
- * a plug-in (in this case ISearchQuery results in Search plug-in being loaded).
- */
- public static IStatus runQueryInForeground(IRunnableContext context, Object query) {
- return NewSearchUI.runQueryInForeground(context, (ISearchQuery)query);
- }
-
- /**
- * Returns the compilation unit for the given java element.
- *
- * @param element the java element whose compilation unit is searched for
- * @return the compilation unit of the given java element
- */
- static IJavaScriptUnit findCompilationUnit(IJavaScriptElement element) {
- if (element == null)
- return null;
- return (IJavaScriptUnit) element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- }
-
-
- public static String toString(IWorkingSet[] workingSets) {
- Arrays.sort(workingSets, new WorkingSetComparator());
- String result= ""; //$NON-NLS-1$
- if (workingSets != null && workingSets.length > 0) {
- boolean firstFound= false;
- for (int i= 0; i < workingSets.length; i++) {
- String workingSetLabel= workingSets[i].getLabel();
- if (firstFound)
- result= Messages.format(SearchMessages.SearchUtil_workingSetConcatenation, new String[] {result, workingSetLabel});
- else {
- result= workingSetLabel;
- firstFound= true;
- }
- }
- }
- return result;
- }
-
- // ---------- LRU working set handling ----------
-
- /**
- * Updates the LRU list of working sets.
- *
- * @param workingSets the workings sets to be added to the LRU list
- */
- public static void updateLRUWorkingSets(IWorkingSet[] workingSets) {
- if (workingSets == null || workingSets.length < 1)
- return;
-
- getLRUWorkingSets().add(workingSets);
- saveState(getDialogStoreSection());
- }
-
- private static void saveState(IDialogSettings settingsStore) {
- IWorkingSet[] workingSets;
- Iterator iter= fgLRUWorkingSets.iterator();
- int i= 0;
- while (iter.hasNext()) {
- workingSets= (IWorkingSet[])iter.next();
- String[] names= new String[workingSets.length];
- for (int j= 0; j < workingSets.length; j++)
- names[j]= workingSets[j].getName();
- settingsStore.put(STORE_LRU_WORKING_SET_NAMES + i, names);
- i++;
- }
- }
-
- public static LRUWorkingSetsList getLRUWorkingSets() {
- if (fgLRUWorkingSets == null) {
- restoreState();
- }
- return fgLRUWorkingSets;
- }
-
- private static void restoreState() {
- fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
- IDialogSettings settingsStore= getDialogStoreSection();
-
- boolean foundLRU= false;
- for (int i= LRU_WORKINGSET_LIST_SIZE - 1; i >= 0; i--) {
- String[] lruWorkingSetNames= settingsStore.getArray(STORE_LRU_WORKING_SET_NAMES + i);
- if (lruWorkingSetNames != null) {
- Set workingSets= new HashSet(2);
- for (int j= 0; j < lruWorkingSetNames.length; j++) {
- IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[j]);
- if (workingSet != null) {
- workingSets.add(workingSet);
- }
- }
- foundLRU= true;
- if (!workingSets.isEmpty())
- fgLRUWorkingSets.add((IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]));
- }
- }
- if (!foundLRU)
- // try old preference format
- restoreFromOldFormat();
- }
-
- private static IDialogSettings getDialogStoreSection() {
- IDialogSettings settingsStore= JavaScriptPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY);
- if (settingsStore == null)
- settingsStore= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY);
- return settingsStore;
- }
-
- private static void restoreFromOldFormat() {
- fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
- IDialogSettings settingsStore= getDialogStoreSection();
-
- boolean foundLRU= false;
- String[] lruWorkingSetNames= settingsStore.getArray(STORE_LRU_WORKING_SET_NAMES);
- if (lruWorkingSetNames != null) {
- for (int i= lruWorkingSetNames.length - 1; i >= 0; i--) {
- IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[i]);
- if (workingSet != null) {
- foundLRU= true;
- fgLRUWorkingSets.add(new IWorkingSet[]{workingSet});
- }
- }
- }
- if (foundLRU)
- // save in new format
- saveState(settingsStore);
- }
-
- public static void warnIfBinaryConstant(IJavaScriptElement element, Shell shell) {
- if (isBinaryPrimitiveConstantOrString(element))
- OptionalMessageDialog.open(
- BIN_PRIM_CONST_WARN_DIALOG_ID,
- shell,
- SearchMessages.Search_FindReferencesAction_BinPrimConstWarnDialog_title,
- null,
- SearchMessages.Search_FindReferencesAction_BinPrimConstWarnDialog_message,
- MessageDialog.INFORMATION,
- new String[] { IDialogConstants.OK_LABEL },
- 0);
- }
-
- private static boolean isBinaryPrimitiveConstantOrString(IJavaScriptElement element) {
- if (element != null && element.getElementType() == IJavaScriptElement.FIELD) {
- IField field= (IField)element;
- int flags;
- try {
- flags= field.getFlags();
- } catch (JavaScriptModelException ex) {
- return false;
- }
- return false;
- }
- return false;
- }
-
- private static boolean isPrimitiveOrString(IField field) {
- String fieldType;
- try {
- fieldType= field.getTypeSignature();
- } catch (JavaScriptModelException ex) {
- return false;
- }
- char first= fieldType.charAt(0);
- return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED && first != Signature.C_ARRAY)
- || (first == Signature.C_RESOLVED && fieldType.substring(1, fieldType.length() - 1).equals(String.class.getName()));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortAction.java
deleted file mode 100644
index 3fc25e91..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortAction.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.BusyIndicator;
-
-
-public class SortAction extends Action {
- private int fSortOrder;
- private JavaSearchResultPage fPage;
-
- public SortAction(String label, JavaSearchResultPage page, int sortOrder) {
- super(label);
- fPage= page;
- fSortOrder= sortOrder;
- }
-
- public void run() {
- BusyIndicator.showWhile(fPage.getViewer().getControl().getDisplay(), new Runnable() {
- public void run() {
- fPage.setSortOrder(fSortOrder);
- }
- });
- }
-
- public int getSortOrder() {
- return fSortOrder;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortingLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortingLabelProvider.java
deleted file mode 100644
index b1cfa089..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SortingLabelProvider.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class SortingLabelProvider extends SearchLabelProvider {
-
- public static final int SHOW_ELEMENT_CONTAINER= 1; // default
- public static final int SHOW_CONTAINER_ELEMENT= 2;
- public static final int SHOW_PATH= 3;
-
- private static final long FLAGS_QUALIFIED= DEFAULT_SEARCH_TEXTFLAGS | JavaScriptElementLabels.F_FULLY_QUALIFIED | JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.I_FULLY_QUALIFIED
- | JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.D_QUALIFIED | JavaScriptElementLabels.CF_QUALIFIED | JavaScriptElementLabels.CU_QUALIFIED | ColoredJavaElementLabels.COLORIZE;
-
-
- private int fCurrentOrder;
-
- public SortingLabelProvider(JavaSearchResultPage page) {
- super(page);
- fCurrentOrder= SHOW_ELEMENT_CONTAINER;
- }
-
- public Image getImage(Object element) {
- Image image= null;
- if (element instanceof IJavaScriptElement || element instanceof IResource)
- image= super.getImage(element);
- if (image != null)
- return image;
- return getParticipantImage(element);
- }
-
- public final String getText(Object element) {
- if (element instanceof IImportDeclaration)
- element= ((IImportDeclaration)element).getParent().getParent();
-
- String text= super.getText(element);
- if (text.length() > 0) {
- String labelWithCount= getLabelWithCounts(element, text);
- if (fCurrentOrder == SHOW_ELEMENT_CONTAINER) {
- labelWithCount += getPostQualification(element, text);
- }
- return labelWithCount;
- }
- return getParticipantText(element);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- if (element instanceof IImportDeclaration)
- element= ((IImportDeclaration)element).getParent().getParent();
-
- ColoredString text= super.getRichTextLabel(element);
- if (text.length() > 0) {
- ColoredString countLabel= getColoredLabelWithCounts(element, text);
- if (fCurrentOrder == SHOW_ELEMENT_CONTAINER) {
- countLabel.append(getPostQualification(element, text.getString()), ColoredJavaElementLabels.QUALIFIER_STYLE);
- }
- return countLabel;
- }
- return new ColoredString(getParticipantText(element));
- }
-
- private String getPostQualification(Object element, String text) {
- String textLabel= JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_POST_QUALIFIED);
- int indexOf= textLabel.indexOf(JavaScriptElementLabels.CONCAT_STRING);
- if (indexOf != -1) {
- return textLabel.substring(indexOf);
- }
- return new String();
- }
-
- public void setOrder(int orderFlag) {
- fCurrentOrder= orderFlag;
- long flags= 0;
- if (orderFlag == SHOW_ELEMENT_CONTAINER)
- flags= DEFAULT_SEARCH_TEXTFLAGS;
- else if (orderFlag == SHOW_CONTAINER_ELEMENT)
- flags= FLAGS_QUALIFIED;
- else if (orderFlag == SHOW_PATH) {
- flags= FLAGS_QUALIFIED | JavaScriptElementLabels.PREPEND_ROOT_PATH;
- }
- setTextFlags(flags);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchLabelProvider.java
deleted file mode 100644
index f7c55f45..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchLabelProvider.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-
-public abstract class TextSearchLabelProvider extends LabelProvider {
-
- private AbstractTextSearchViewPage fPage;
- private String fMatchCountFormat;
-
- public TextSearchLabelProvider(AbstractTextSearchViewPage page) {
- fPage= page;
- fMatchCountFormat= SearchMessages.TextSearchLabelProvider_matchCountFormat;
- }
-
- public final String getText(Object element) {
- int matchCount= fPage.getInput().getMatchCount(element);
- String text= doGetText(element);
- if (matchCount < 2)
- return text;
- else {
- return Messages.format(fMatchCountFormat, new Object[] { text, new Integer(matchCount) });
- }
- }
-
- protected abstract String doGetText(Object element);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchTableContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchTableContentProvider.java
deleted file mode 100644
index a759f60e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/TextSearchTableContentProvider.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.search.ui.text.AbstractTextSearchResult;
-
-/**
- * TODO: this class should replace JavaSearchTableContentProvider
- * (must generalize type of fResult to AbstractTextSearchResult in JavaSearchContentProvider)
- */
-public class TextSearchTableContentProvider implements IStructuredContentProvider {
- protected final Object[] EMPTY_ARRAY= new Object[0];
- private AbstractTextSearchResult fSearchResult;
- private TableViewer fTableViewer;
-
- /*
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof AbstractTextSearchResult)
- return ((AbstractTextSearchResult) inputElement).getElements();
- return EMPTY_ARRAY;
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- public void dispose() {
- //nothing
- }
-
- /*
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- fTableViewer= (TableViewer) viewer;
- fSearchResult= (AbstractTextSearchResult) newInput;
- }
-
- public void elementsChanged(Object[] updatedElements) {
- //TODO: copied from JavaSearchTableContentProvider
- int addCount= 0;
- int removeCount= 0;
- for (int i= 0; i < updatedElements.length; i++) {
- if (fSearchResult.getMatchCount(updatedElements[i]) > 0) {
- if (fTableViewer.testFindItem(updatedElements[i]) != null)
- fTableViewer.refresh(updatedElements[i]);
- else
- fTableViewer.add(updatedElements[i]);
- addCount++;
- } else {
- fTableViewer.remove(updatedElements[i]);
- removeCount++;
- }
- }
- }
-
- public void clear() {
- //TODO: copied from JavaSearchTableContentProvider
- fTableViewer.refresh();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetComparator.java
deleted file mode 100644
index 31d40770..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetComparator.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.Comparator;
-
-import org.eclipse.ui.IWorkingSet;
-
-import com.ibm.icu.text.Collator;
-
-public class WorkingSetComparator implements Comparator {
-
- private Collator fCollator= Collator.getInstance();
-
- /*
- * @see Comparator#compare(Object, Object)
- */
- public int compare(Object o1, Object o2) {
- String name1= null;
- String name2= null;
-
- if (o1 instanceof IWorkingSet)
- name1= ((IWorkingSet)o1).getLabel();
-
- if (o2 instanceof IWorkingSet)
- name2= ((IWorkingSet)o2).getLabel();
-
- return fCollator.compare(name1, name2);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetsComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetsComparator.java
deleted file mode 100644
index 4cb06218..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/WorkingSetsComparator.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.search;
-
-import java.util.Comparator;
-
-import org.eclipse.ui.IWorkingSet;
-
-import com.ibm.icu.text.Collator;
-
-class WorkingSetsComparator implements Comparator {
-
- private Collator fCollator= Collator.getInstance();
-
- /*
- * @see Comparator#compare(Object, Object)
- */
- public int compare(Object o1, Object o2) {
- String name1= null;
- String name2= null;
-
- if (o1 instanceof IWorkingSet[]) {
- IWorkingSet[] workingSets= (IWorkingSet[])o1;
- if (workingSets.length > 0)
- name1= workingSets[0].getLabel();
- }
-
- if (o2 instanceof IWorkingSet[]) {
- IWorkingSet[] workingSets= (IWorkingSet[])o1;
- if (workingSets.length > 0)
- name2= workingSets[0].getLabel();
- }
-
- return fCollator.compare(name1, name2);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractInformationControl.java
deleted file mode 100644
index b16e86dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractInformationControl.java
+++ /dev/null
@@ -1,775 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.PopupDialog;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlExtension;
-import org.eclipse.jface.text.IInformationControlExtension2;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseMoveListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ActionHandler;
-import org.eclipse.ui.commands.HandlerSubmission;
-import org.eclipse.ui.commands.ICommand;
-import org.eclipse.ui.commands.ICommandManager;
-import org.eclipse.ui.commands.IKeySequenceBinding;
-import org.eclipse.ui.commands.Priority;
-import org.eclipse.ui.keys.KeySequence;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-import org.eclipse.wst.jsdt.ui.actions.CustomFiltersActionGroup;
-
-/**
- * Abstract class for Show hierarchy in light-weight controls.
- *
- *
- */
-public abstract class AbstractInformationControl extends PopupDialog implements IInformationControl, IInformationControlExtension, IInformationControlExtension2, DisposeListener {
-
- /**
- * The NamePatternFilter selects the elements which
- * match the given string patterns.
- *
- *
- */
- protected class NamePatternFilter extends ViewerFilter {
-
- public NamePatternFilter() {
- }
-
- /* (non-Javadoc)
- * Method declared on ViewerFilter.
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- StringMatcher matcher= getMatcher();
- if (matcher == null || !(viewer instanceof TreeViewer))
- return true;
- TreeViewer treeViewer= (TreeViewer) viewer;
-
- String matchName= ((ILabelProvider) treeViewer.getLabelProvider()).getText(element);
- if (matchName != null && matcher.match(matchName))
- return true;
-
- return hasUnfilteredChild(treeViewer, element);
- }
-
- private boolean hasUnfilteredChild(TreeViewer viewer, Object element) {
- if (element instanceof IParent) {
- Object[] children= ((ITreeContentProvider) viewer.getContentProvider()).getChildren(element);
- for (int i= 0; i < children.length; i++)
- if (select(viewer, element, children[i]))
- return true;
- }
- return false;
- }
- }
-
- /** The control's text widget */
- private Text fFilterText;
- /** The control's tree widget */
- private TreeViewer fTreeViewer;
- /** The current string matcher */
- protected StringMatcher fStringMatcher;
- private ICommand fInvokingCommand;
- private KeySequence[] fInvokingCommandKeySequences;
-
- /**
- * Fields that support the dialog menu
- *
- * - now appended to framework menu
- */
- private Composite fViewMenuButtonComposite;
-
- private CustomFiltersActionGroup fCustomFiltersActionGroup;
-
- private IAction fShowViewMenuAction;
- private HandlerSubmission fShowViewMenuHandlerSubmission;
-
- /**
- * Field for tree style since it must be remembered by the instance.
- *
- *
- */
- private int fTreeStyle;
-
- /**
- * Creates a tree information control with the given shell as parent. The given
- * styles are applied to the shell and the tree widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param treeStyle the additional styles for the tree widget
- * @param invokingCommandId the id of the command that invoked this control or <code>null</code>
- * @param showStatusField <code>true</code> iff the control has a status field at the bottom
- */
- public AbstractInformationControl(Shell parent, int shellStyle, int treeStyle, String invokingCommandId, boolean showStatusField) {
- super(parent, shellStyle, true, true, true, true, null, null);
- if (invokingCommandId != null) {
- ICommandManager commandManager= PlatformUI.getWorkbench().getCommandSupport().getCommandManager();
- fInvokingCommand= commandManager.getCommand(invokingCommandId);
- if (fInvokingCommand != null && !fInvokingCommand.isDefined())
- fInvokingCommand= null;
- else
- // Pre-fetch key sequence - do not change because scope will change later.
- getInvokingCommandKeySequences();
- }
- fTreeStyle= treeStyle;
- // Title and status text must be set to get the title label created, so force empty values here.
- if (hasHeader())
- setTitleText(""); //$NON-NLS-1$
- setInfoText(""); // //$NON-NLS-1$
-
- // Create all controls early to preserve the life cycle of the original implementation.
- create();
-
- // Status field text can only be computed after widgets are created.
- setInfoText(getStatusFieldText());
- }
-
- /**
- * Create the main content for this information control.
- *
- * @param parent The parent composite
- * @return The control representing the main content.
- *
- */
- protected Control createDialogArea(Composite parent) {
- fTreeViewer= createTreeViewer(parent, fTreeStyle);
-
- fCustomFiltersActionGroup= new CustomFiltersActionGroup(getId(), fTreeViewer);
-
- final Tree tree= fTreeViewer.getTree();
- tree.addKeyListener(new KeyListener() {
- public void keyPressed(KeyEvent e) {
- if (e.character == 0x1B) // ESC
- dispose();
- }
- public void keyReleased(KeyEvent e) {
- // do nothing
- }
- });
-
- tree.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- gotoSelectedElement();
- }
- });
-
- tree.addMouseMoveListener(new MouseMoveListener() {
- TreeItem fLastItem= null;
- public void mouseMove(MouseEvent e) {
- if (tree.equals(e.getSource())) {
- Object o= tree.getItem(new Point(e.x, e.y));
- if (o instanceof TreeItem) {
- if (!o.equals(fLastItem)) {
- fLastItem= (TreeItem)o;
- tree.setSelection(new TreeItem[] { fLastItem });
- } else if (e.y < tree.getItemHeight() / 4) {
- // Scroll up
- Point p= tree.toDisplay(e.x, e.y);
- Item item= fTreeViewer.scrollUp(p.x, p.y);
- if (item instanceof TreeItem) {
- fLastItem= (TreeItem)item;
- tree.setSelection(new TreeItem[] { fLastItem });
- }
- } else if (e.y > tree.getBounds().height - tree.getItemHeight() / 4) {
- // Scroll down
- Point p= tree.toDisplay(e.x, e.y);
- Item item= fTreeViewer.scrollDown(p.x, p.y);
- if (item instanceof TreeItem) {
- fLastItem= (TreeItem)item;
- tree.setSelection(new TreeItem[] { fLastItem });
- }
- }
- }
- }
- }
- });
-
- tree.addMouseListener(new MouseAdapter() {
- public void mouseUp(MouseEvent e) {
-
- if (tree.getSelectionCount() < 1)
- return;
-
- if (e.button != 1)
- return;
-
- if (tree.equals(e.getSource())) {
- Object o= tree.getItem(new Point(e.x, e.y));
- TreeItem selection= tree.getSelection()[0];
- if (selection.equals(o))
- gotoSelectedElement();
- }
- }
- });
-
- installFilter();
-
- addDisposeListener(this);
- return fTreeViewer.getControl();
- }
-
- /**
- * Creates a tree information control with the given shell as parent. The given
- * styles are applied to the shell and the tree widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param treeStyle the additional styles for the tree widget
- */
- public AbstractInformationControl(Shell parent, int shellStyle, int treeStyle) {
- this(parent, shellStyle, treeStyle, null, false);
- }
-
- protected abstract TreeViewer createTreeViewer(Composite parent, int style);
-
- /**
- * Returns the name of the dialog settings section.
- *
- * @return the name of the dialog settings section
- */
- protected abstract String getId();
-
- protected TreeViewer getTreeViewer() {
- return fTreeViewer;
- }
-
- /**
- * Returns <code>true</code> if the control has a header, <code>false</code> otherwise.
- * <p>
- * The default is to return <code>false</code>.
- * </p>
- *
- * @return <code>true</code> if the control has a header
- */
- protected boolean hasHeader() {
- // default is to have no header
- return false;
- }
-
- protected Text getFilterText() {
- return fFilterText;
- }
-
- protected Text createFilterText(Composite parent) {
- fFilterText= new Text(parent, SWT.NONE);
- Dialog.applyDialogFont(fFilterText);
-
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.horizontalAlignment= GridData.FILL;
- data.verticalAlignment= GridData.CENTER;
- fFilterText.setLayoutData(data);
-
- fFilterText.addKeyListener(new KeyListener() {
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == 0x0D) // return
- gotoSelectedElement();
- if (e.keyCode == SWT.ARROW_DOWN)
- fTreeViewer.getTree().setFocus();
- if (e.keyCode == SWT.ARROW_UP)
- fTreeViewer.getTree().setFocus();
- if (e.character == 0x1B) // ESC
- dispose();
- }
- public void keyReleased(KeyEvent e) {
- // do nothing
- }
- });
-
- return fFilterText;
- }
-
- protected void createHorizontalSeparator(Composite parent) {
- Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
- separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
-
- protected void updateStatusFieldText() {
- setInfoText(getStatusFieldText());
- }
-
- /**
- * Handles click in status field.
- * <p>
- * Default does nothing.
- * </p>
- */
- protected void handleStatusFieldClicked() {
- }
-
- protected String getStatusFieldText() {
- return ""; //$NON-NLS-1$
- }
-
- private void installFilter() {
- fFilterText.setText(""); //$NON-NLS-1$
-
- fFilterText.addModifyListener(new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- String text= ((Text) e.widget).getText();
- int length= text.length();
- if (length > 0 && text.charAt(length -1 ) != '*') {
- text= text + '*';
- }
- setMatcherString(text, true);
- }
- });
- }
-
- /**
- * The string matcher has been modified. The default implementation
- * refreshes the view and selects the first matched element
- */
- protected void stringMatcherUpdated() {
- // refresh viewer to re-filter
- fTreeViewer.getControl().setRedraw(false);
- fTreeViewer.refresh();
- fTreeViewer.expandAll();
- selectFirstMatch();
- fTreeViewer.getControl().setRedraw(true);
- }
-
- /**
- * Sets the patterns to filter out for the receiver.
- * <p>
- * The following characters have special meaning:
- * ? => any character
- * * => any string
- * </p>
- *
- * @param pattern the pattern
- * @param update <code>true</code> if the viewer should be updated
- */
- protected void setMatcherString(String pattern, boolean update) {
- if (pattern.length() == 0) {
- fStringMatcher= null;
- } else {
- boolean ignoreCase= pattern.toLowerCase().equals(pattern);
- fStringMatcher= new StringMatcher(pattern, ignoreCase, false);
- }
-
- if (update)
- stringMatcherUpdated();
- }
-
- protected StringMatcher getMatcher() {
- return fStringMatcher;
- }
-
- /**
- * Implementers can modify
- *
- * @return the selected element
- */
- protected Object getSelectedElement() {
- if (fTreeViewer == null)
- return null;
-
- return ((IStructuredSelection) fTreeViewer.getSelection()).getFirstElement();
- }
-
- private void gotoSelectedElement() {
- Object selectedElement= getSelectedElement();
- if (selectedElement != null) {
- try {
- dispose();
- IEditorPart part= EditorUtility.openInEditor(selectedElement, true);
- if (part != null && selectedElement instanceof IJavaScriptElement)
- EditorUtility.revealInEditor(part, (IJavaScriptElement) selectedElement);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
- }
-
- /**
- * Selects the first element in the tree which
- * matches the current filter pattern.
- */
- protected void selectFirstMatch() {
- Tree tree= fTreeViewer.getTree();
- Object element= findElement(tree.getItems());
- if (element != null)
- fTreeViewer.setSelection(new StructuredSelection(element), true);
- else
- fTreeViewer.setSelection(StructuredSelection.EMPTY);
- }
-
- private IJavaScriptElement findElement(TreeItem[] items) {
- ILabelProvider labelProvider= (ILabelProvider)fTreeViewer.getLabelProvider();
- for (int i= 0; i < items.length; i++) {
- IJavaScriptElement element= (IJavaScriptElement)items[i].getData();
- if (fStringMatcher == null)
- return element;
-
- if (element != null) {
- String label= labelProvider.getText(element);
- if (fStringMatcher.match(label))
- return element;
- }
-
- element= findElement(items[i].getItems());
- if (element != null)
- return element;
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInformation(String information) {
- // this method is ignored, see IInformationControlExtension2
- }
-
- /**
- * {@inheritDoc}
- */
- public abstract void setInput(Object information);
-
- /**
- * Fills the view menu.
- * Clients can extend or override.
- *
- * @param viewMenu the menu manager that manages the menu
- *
- */
- protected void fillViewMenu(IMenuManager viewMenu) {
- fCustomFiltersActionGroup.fillViewMenu(viewMenu);
- }
-
- /*
- * Overridden to call the old framework method.
- *
- * @see org.eclipse.jface.dialogs.PopupDialog#fillDialogMenu(IMenuManager)
- *
- */
- protected void fillDialogMenu(IMenuManager dialogMenu) {
- super.fillDialogMenu(dialogMenu);
- fillViewMenu(dialogMenu);
- }
-
- protected void inputChanged(Object newInput, Object newSelection) {
- fFilterText.setText(""); //$NON-NLS-1$
- fTreeViewer.setInput(newInput);
- if (newSelection != null) {
- fTreeViewer.setSelection(new StructuredSelection(newSelection));
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void setVisible(boolean visible) {
- if (visible) {
- open();
- } else {
- removeHandlerAndKeyBindingSupport();
- saveDialogBounds(getShell());
- getShell().setVisible(false);
- removeHandlerAndKeyBindingSupport();
- }
- }
-
- /*
- * @see org.eclipse.jface.dialogs.PopupDialog#open()
- *
- */
- public int open() {
- addHandlerAndKeyBindingSupport();
- return super.open();
- }
-
- /**
- * {@inheritDoc}
- */
- public final void dispose() {
- close();
- }
-
- /**
- * {@inheritDoc}
- * @param event can be null
- * <p>
- * Subclasses may extend.
- * </p>
- */
- public void widgetDisposed(DisposeEvent event) {
- removeHandlerAndKeyBindingSupport();
- fTreeViewer= null;
- fFilterText= null;
- }
-
- /**
- * Adds handler and key binding support.
- *
- *
- */
- protected void addHandlerAndKeyBindingSupport() {
- // Register action with command support
- if (fShowViewMenuHandlerSubmission == null) {
- fShowViewMenuHandlerSubmission= new HandlerSubmission(null, getShell(), null, fShowViewMenuAction.getActionDefinitionId(), new ActionHandler(fShowViewMenuAction), Priority.MEDIUM);
- PlatformUI.getWorkbench().getCommandSupport().addHandlerSubmission(fShowViewMenuHandlerSubmission);
- }
- }
-
- /**
- * Removes handler and key binding support.
- *
- *
- */
- protected void removeHandlerAndKeyBindingSupport() {
- // Remove handler submission
- if (fShowViewMenuHandlerSubmission != null)
- PlatformUI.getWorkbench().getCommandSupport().removeHandlerSubmission(fShowViewMenuHandlerSubmission);
-
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasContents() {
- return fTreeViewer != null && fTreeViewer.getInput() != null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setSizeConstraints(int maxWidth, int maxHeight) {
- // ignore
- }
-
- /**
- * {@inheritDoc}
- */
- public Point computeSizeHint() {
- // return the shell's size - note that it already has the persisted size if persisting
- // is enabled.
- return getShell().getSize();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setLocation(Point location) {
- /*
- * If the location is persisted, it gets managed by PopupDialog - fine. Otherwise, the location is
- * computed in Window#getInitialLocation, which will center it in the parent shell / main
- * monitor, which is wrong for two reasons:
- * - we want to center over the editor / subject control, not the parent shell
- * - the center is computed via the initalSize, which may be also wrong since the size may
- * have been updated since via min/max sizing of AbstractInformationControlManager.
- * In that case, override the location with the one computed by the manager. Note that
- * the call to constrainShellSize in PopupDialog.open will still ensure that the shell is
- * entirely visible.
- */
- if (!getPersistBounds() || getDialogSettings() == null)
- getShell().setLocation(location);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setSize(int width, int height) {
- getShell().setSize(width, height);
- }
-
- /**
- * {@inheritDoc}
- */
- public void addDisposeListener(DisposeListener listener) {
- getShell().addDisposeListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeDisposeListener(DisposeListener listener) {
- getShell().removeDisposeListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setForegroundColor(Color foreground) {
- applyForegroundColor(foreground, getContents());
- }
-
- /**
- * {@inheritDoc}
- */
- public void setBackgroundColor(Color background) {
- applyBackgroundColor(background, getContents());
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isFocusControl() {
- return fTreeViewer.getControl().isFocusControl() || fFilterText.isFocusControl();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
- getShell().forceFocus();
- fFilterText.setFocus();
- }
-
- /**
- * {@inheritDoc}
- */
- public void addFocusListener(FocusListener listener) {
- getShell().addFocusListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeFocusListener(FocusListener listener) {
- getShell().removeFocusListener(listener);
- }
-
- final protected ICommand getInvokingCommand() {
- return fInvokingCommand;
- }
-
- final protected KeySequence[] getInvokingCommandKeySequences() {
- if (fInvokingCommandKeySequences == null) {
- if (getInvokingCommand() != null) {
- List list= getInvokingCommand().getKeySequenceBindings();
- if (!list.isEmpty()) {
- fInvokingCommandKeySequences= new KeySequence[list.size()];
- for (int i= 0; i < fInvokingCommandKeySequences.length; i++) {
- fInvokingCommandKeySequences[i]= ((IKeySequenceBinding) list.get(i)).getKeySequence();
- }
- return fInvokingCommandKeySequences;
- }
- }
- }
- return fInvokingCommandKeySequences;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.PopupDialog#getDialogSettings()
- */
- protected IDialogSettings getDialogSettings() {
- String sectionName= getId();
-
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(sectionName);
- if (settings == null)
- settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(sectionName);
-
- return settings;
- }
-
- /*
- * Overridden to insert the filter text into the title and menu area.
- *
- *
- */
- protected Control createTitleMenuArea(Composite parent) {
- fViewMenuButtonComposite= (Composite) super.createTitleMenuArea(parent);
-
- // If there is a header, then the filter text must be created
- // underneath the title and menu area.
-
- if (hasHeader()) {
- fFilterText= createFilterText(parent);
- }
-
- // Create show view menu action
- fShowViewMenuAction= new Action("showViewMenu") { //$NON-NLS-1$
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- showDialogMenu();
- }
- };
- fShowViewMenuAction.setEnabled(true);
- fShowViewMenuAction.setActionDefinitionId("org.eclipse.ui.window.showViewMenu"); //$NON-NLS-1$
-
- return fViewMenuButtonComposite;
- }
-
- /*
- * Overridden to insert the filter text into the title control
- * if there is no header specified.
- *
- */
- protected Control createTitleControl(Composite parent) {
- if (hasHeader()) {
- return super.createTitleControl(parent);
- }
- fFilterText= createFilterText(parent);
- return fFilterText;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.PopupDialog#setTabOrder(org.eclipse.swt.widgets.Composite)
- */
- protected void setTabOrder(Composite composite) {
- if (hasHeader()) {
- composite.setTabList(new Control[] { fFilterText, fTreeViewer.getTree() });
- } else {
- fViewMenuButtonComposite.setTabList(new Control[] { fFilterText });
- composite.setTabList(new Control[] { fViewMenuButtonComposite, fTreeViewer.getTree() });
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java
deleted file mode 100644
index 70f53db1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.StringConverter;
-import org.eclipse.jface.text.TextAttribute;
-import org.eclipse.jface.text.rules.BufferedRuleBasedScanner;
-import org.eclipse.jface.text.rules.IRule;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IColorManagerExtension;
-
-
-/**
- * Initialized with a color manager and a preference store, its subclasses are
- * only responsible for providing a list of preference keys for based on which tokens
- * are generated and to use this tokens to define the rules controlling this scanner.
- * <p>
- * This scanner stores the color defined by the color preference key into
- * the color manager under the same key.
- * </p>
- * <p>
- * Preference color key + {@link PreferenceConstants#EDITOR_BOLD_SUFFIX} are used
- * to retrieve whether the token is rendered in bold.
- * </p>
- * <p>
- * Preference color key + {@link PreferenceConstants#EDITOR_ITALIC_SUFFIX} are used
- * to retrieve whether the token is rendered in italic.
- * </p>
- * <p>
- * Preference color key + {@link PreferenceConstants#EDITOR_STRIKETHROUGH_SUFFIX} are used
- * to retrieve whether the token is rendered in strikethrough.
- * </p>
- * <p>
- * Preference color key + {@link PreferenceConstants#EDITOR_UNDERLINE_SUFFIX} are used
- * to retrieve whether the token is rendered in underline.
- * </p>
- */
-public abstract class AbstractJavaScanner extends BufferedRuleBasedScanner {
-
-
- private IColorManager fColorManager;
- private IPreferenceStore fPreferenceStore;
-
- private Map fTokenMap= new HashMap();
- private String[] fPropertyNamesColor;
- /**
- * Preference keys for boolean preferences which are <code>true</code>,
- * iff the corresponding token should be rendered bold.
- */
- private String[] fPropertyNamesBold;
- /**
- * Preference keys for boolean preferences which are <code>true</code>,
- * iff the corresponding token should be rendered italic.
- *
- *
- */
- private String[] fPropertyNamesItalic;
- /**
- * Preference keys for boolean preferences which are <code>true</code>,
- * iff the corresponding token should be rendered strikethrough.
- *
- *
- */
- private String[] fPropertyNamesStrikethrough;
- /**
- * Preference keys for boolean preferences which are <code>true</code>,
- * iff the corresponding token should be rendered underline.
- *
- *
- */
- private String[] fPropertyNamesUnderline;
-
-
- private boolean fNeedsLazyColorLoading;
-
- /**
- * Returns an array of preference keys which define the tokens
- * used in the rules of this scanner.
- * <p>
- * The preference key is used access the color in the preference
- * store and in the color manager.
- * </p>
- * <p>
- * Preference key + {@link PreferenceConstants#EDITOR_BOLD_SUFFIX} is used
- * to retrieve whether the token is rendered in bold.
- * </p>
- * <p>
- * Preference key + {@link PreferenceConstants#EDITOR_ITALIC_SUFFIX} is used
- * to retrieve whether the token is rendered in italic.
- * </p>
- * <p>
- * Preference key + {@link PreferenceConstants#EDITOR_UNDERLINE_SUFFIX} is used
- * to retrieve whether the token is rendered underlined.
- * </p>
- * <p>
- * Preference key + {@link PreferenceConstants#EDITOR_STRIKETHROUGH_SUFFIX} is used
- * to retrieve whether the token is rendered stricken out.
- * </p>
- */
- abstract protected String[] getTokenProperties();
-
- /**
- * Creates the list of rules controlling this scanner.
- */
- abstract protected List createRules();
-
-
- /**
- * Creates an abstract Java scanner.
- */
- public AbstractJavaScanner(IColorManager manager, IPreferenceStore store) {
- super();
- fColorManager= manager;
- fPreferenceStore= store;
- }
-
- /**
- * Must be called after the constructor has been called.
- */
- public final void initialize() {
-
- fPropertyNamesColor= getTokenProperties();
- int length= fPropertyNamesColor.length;
- fPropertyNamesBold= new String[length];
- fPropertyNamesItalic= new String[length];
- fPropertyNamesStrikethrough= new String[length];
- fPropertyNamesUnderline= new String[length];
-
- for (int i= 0; i < length; i++) {
- fPropertyNamesBold[i]= getBoldKey(fPropertyNamesColor[i]);
- fPropertyNamesItalic[i]= getItalicKey(fPropertyNamesColor[i]);
- fPropertyNamesStrikethrough[i]= getStrikethroughKey(fPropertyNamesColor[i]);
- fPropertyNamesUnderline[i]= getUnderlineKey(fPropertyNamesColor[i]);
- }
-
- fNeedsLazyColorLoading= Display.getCurrent() == null;
- for (int i= 0; i < length; i++) {
- if (fNeedsLazyColorLoading)
- addTokenWithProxyAttribute(fPropertyNamesColor[i], fPropertyNamesBold[i], fPropertyNamesItalic[i], fPropertyNamesStrikethrough[i], fPropertyNamesUnderline[i]);
- else
- addToken(fPropertyNamesColor[i], fPropertyNamesBold[i], fPropertyNamesItalic[i], fPropertyNamesStrikethrough[i], fPropertyNamesUnderline[i]);
- }
-
- initializeRules();
- }
-
- protected String getBoldKey(String colorKey) {
- return colorKey + PreferenceConstants.EDITOR_BOLD_SUFFIX;
- }
-
- protected String getItalicKey(String colorKey) {
- return colorKey + PreferenceConstants.EDITOR_ITALIC_SUFFIX;
- }
-
- protected String getStrikethroughKey(String colorKey) {
- return colorKey + PreferenceConstants.EDITOR_STRIKETHROUGH_SUFFIX;
- }
-
- protected String getUnderlineKey(String colorKey) {
- return colorKey + PreferenceConstants.EDITOR_UNDERLINE_SUFFIX;
- }
-
- public IToken nextToken() {
- if (fNeedsLazyColorLoading)
- resolveProxyAttributes();
- return super.nextToken();
- }
-
- private void resolveProxyAttributes() {
- if (fNeedsLazyColorLoading && Display.getCurrent() != null) {
- for (int i= 0; i < fPropertyNamesColor.length; i++) {
- addToken(fPropertyNamesColor[i], fPropertyNamesBold[i], fPropertyNamesItalic[i], fPropertyNamesStrikethrough[i], fPropertyNamesUnderline[i]);
- }
- fNeedsLazyColorLoading= false;
- }
- }
-
- private void addTokenWithProxyAttribute(String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) {
- fTokenMap.put(colorKey, new Token(createTextAttribute(null, boldKey, italicKey, strikethroughKey, underlineKey)));
- }
-
- private void addToken(String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) {
- if (fColorManager != null && colorKey != null && fColorManager.getColor(colorKey) == null) {
- RGB rgb= PreferenceConverter.getColor(fPreferenceStore, colorKey);
- if (fColorManager instanceof IColorManagerExtension) {
- IColorManagerExtension ext= (IColorManagerExtension) fColorManager;
- ext.unbindColor(colorKey);
- ext.bindColor(colorKey, rgb);
- }
- }
-
- if (!fNeedsLazyColorLoading)
- fTokenMap.put(colorKey, new Token(createTextAttribute(colorKey, boldKey, italicKey, strikethroughKey, underlineKey)));
- else {
- Token token= ((Token)fTokenMap.get(colorKey));
- if (token != null)
- token.setData(createTextAttribute(colorKey, boldKey, italicKey, strikethroughKey, underlineKey));
- }
- }
-
- /**
- * Create a text attribute based on the given color, bold, italic, strikethrough and underline preference keys.
- *
- * @param colorKey the color preference key
- * @param boldKey the bold preference key
- * @param italicKey the italic preference key
- * @param strikethroughKey the strikethrough preference key
- * @param underlineKey the italic preference key
- * @return the created text attribute
- *
- */
- private TextAttribute createTextAttribute(String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) {
- Color color= null;
- if (colorKey != null)
- color= fColorManager.getColor(colorKey);
-
- int style= fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL;
- if (fPreferenceStore.getBoolean(italicKey))
- style |= SWT.ITALIC;
-
- if (fPreferenceStore.getBoolean(strikethroughKey))
- style |= TextAttribute.STRIKETHROUGH;
-
- if (fPreferenceStore.getBoolean(underlineKey))
- style |= TextAttribute.UNDERLINE;
-
- return new TextAttribute(color, null, style);
- }
-
- protected Token getToken(String key) {
- if (fNeedsLazyColorLoading)
- resolveProxyAttributes();
- return (Token) fTokenMap.get(key);
- }
-
- private void initializeRules() {
- List rules= createRules();
- if (rules != null) {
- IRule[] result= new IRule[rules.size()];
- rules.toArray(result);
- setRules(result);
- }
- }
-
- private int indexOf(String property) {
- if (property != null) {
- int length= fPropertyNamesColor.length;
- for (int i= 0; i < length; i++) {
- if (property.equals(fPropertyNamesColor[i]) || property.equals(fPropertyNamesBold[i]) || property.equals(fPropertyNamesItalic[i]) || property.equals(fPropertyNamesStrikethrough[i]) || property.equals(fPropertyNamesUnderline[i]))
- return i;
- }
- }
- return -1;
- }
-
- public boolean affectsBehavior(PropertyChangeEvent event) {
- return indexOf(event.getProperty()) >= 0;
- }
-
- public void adaptToPreferenceChange(PropertyChangeEvent event) {
- String p= event.getProperty();
- int index= indexOf(p);
- Token token= getToken(fPropertyNamesColor[index]);
- if (fPropertyNamesColor[index].equals(p))
- adaptToColorChange(token, event);
- else if (fPropertyNamesBold[index].equals(p))
- adaptToStyleChange(token, event, SWT.BOLD);
- else if (fPropertyNamesItalic[index].equals(p))
- adaptToStyleChange(token, event, SWT.ITALIC);
- else if (fPropertyNamesStrikethrough[index].equals(p))
- adaptToStyleChange(token, event, TextAttribute.STRIKETHROUGH);
- else if (fPropertyNamesUnderline[index].equals(p))
- adaptToStyleChange(token, event, TextAttribute.UNDERLINE);
- }
-
- private void adaptToColorChange(Token token, PropertyChangeEvent event) {
- RGB rgb= null;
-
- Object value= event.getNewValue();
- if (value instanceof RGB)
- rgb= (RGB) value;
- else if (value instanceof String)
- rgb= StringConverter.asRGB((String) value);
-
- if (rgb != null) {
-
- String property= event.getProperty();
- Color color= fColorManager.getColor(property);
-
- if ((color == null || !rgb.equals(color.getRGB())) && fColorManager instanceof IColorManagerExtension) {
- IColorManagerExtension ext= (IColorManagerExtension) fColorManager;
-
- ext.unbindColor(property);
- ext.bindColor(property, rgb);
-
- color= fColorManager.getColor(property);
- }
-
- Object data= token.getData();
- if (data instanceof TextAttribute) {
- TextAttribute oldAttr= (TextAttribute) data;
- token.setData(new TextAttribute(color, oldAttr.getBackground(), oldAttr.getStyle()));
- }
- }
- }
-
- private void adaptToStyleChange(Token token, PropertyChangeEvent event, int styleAttribute) {
- boolean eventValue= false;
- Object value= event.getNewValue();
- if (value instanceof Boolean)
- eventValue= ((Boolean) value).booleanValue();
- else if (IPreferenceStore.TRUE.equals(value))
- eventValue= true;
-
- Object data= token.getData();
- if (data instanceof TextAttribute) {
- TextAttribute oldAttr= (TextAttribute) data;
- boolean activeValue= (oldAttr.getStyle() & styleAttribute) == styleAttribute;
- if (activeValue != eventValue)
- token.setData(new TextAttribute(oldAttr.getForeground(), oldAttr.getBackground(), eventValue ? oldAttr.getStyle() | styleAttribute : oldAttr.getStyle() & ~styleAttribute));
- }
- }
- /**
- * Returns the preference store.
- *
- * @return the preference store.
- *
- *
- */
- protected IPreferenceStore getPreferenceStore() {
- return fPreferenceStore;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/BufferedDocumentScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/BufferedDocumentScanner.java
deleted file mode 100644
index 40e05f21..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/BufferedDocumentScanner.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-/**
- * A buffered document scanner. The buffer always contains a section
- * of a fixed size of the document to be scanned.
- */
-
-public final class BufferedDocumentScanner implements ICharacterScanner {
-
- /** The document being scanned. */
- private IDocument fDocument;
- /** The offset of the document range to scan. */
- private int fRangeOffset;
- /** The length of the document range to scan. */
- private int fRangeLength;
- /** The delimiters of the document. */
- private char[][] fDelimiters;
-
- /** The buffer. */
- private final char[] fBuffer;
- /** The offset of the buffer within the document. */
- private int fBufferOffset;
- /** The valid length of the buffer for access. */
- private int fBufferLength;
- /** The offset of the scanner within the buffer. */
- private int fOffset;
-
-
- /**
- * Creates a new buffered document scanner.
- * The buffer size is set to the given number of characters.
- *
- * @param size the buffer size
- */
- public BufferedDocumentScanner(int size) {
- Assert.isTrue(size >= 1);
- fBuffer= new char[size];
- }
-
- /**
- * Fills the buffer with the contents of the document starting at the given offset.
- *
- * @param offset the document offset at which the buffer starts
- */
- private final void updateBuffer(int offset) {
-
- fBufferOffset= offset;
-
- if (fBufferOffset + fBuffer.length > fRangeOffset + fRangeLength)
- fBufferLength= fRangeLength - (fBufferOffset - fRangeOffset);
- else
- fBufferLength= fBuffer.length;
-
- try {
- final String content= fDocument.get(fBufferOffset, fBufferLength);
- content.getChars(0, fBufferLength, fBuffer, 0);
- } catch (BadLocationException e) {
- }
- }
-
- /**
- * Configures the scanner by providing access to the document range over which to scan.
- *
- * @param document the document to scan
- * @param offset the offset of the document range to scan
- * @param length the length of the document range to scan
- */
- public final void setRange(IDocument document, int offset, int length) {
-
- fDocument= document;
- fRangeOffset= offset;
- fRangeLength= length;
-
- String[] delimiters= document.getLegalLineDelimiters();
- fDelimiters= new char[delimiters.length][];
- for (int i= 0; i < delimiters.length; i++)
- fDelimiters[i]= delimiters[i].toCharArray();
-
- updateBuffer(offset);
- fOffset= 0;
- }
-
- /*
- * @see ICharacterScanner#read()
- */
- public final int read() {
-
- if (fOffset == fBufferLength) {
- int end= fBufferOffset + fBufferLength;
- if (end == fDocument.getLength() || end == fRangeOffset + fRangeLength)
- return EOF;
- else {
- updateBuffer(fBufferOffset + fBufferLength);
- fOffset= 0;
- }
- }
-
- try {
- return fBuffer[fOffset++];
- } catch (ArrayIndexOutOfBoundsException ex) {
- StringBuffer buf= new StringBuffer();
- buf.append("Detailed state of 'BufferedDocumentScanner:'"); //$NON-NLS-1$
- buf.append("\n\tfOffset= "); //$NON-NLS-1$
- buf.append(fOffset);
- buf.append("\n\tfBufferOffset= "); //$NON-NLS-1$
- buf.append(fBufferOffset);
- buf.append("\n\tfBufferLength= "); //$NON-NLS-1$
- buf.append(fBufferLength);
- buf.append("\n\tfRangeOffset= "); //$NON-NLS-1$
- buf.append(fRangeOffset);
- buf.append("\n\tfRangeLength= "); //$NON-NLS-1$
- buf.append(fRangeLength);
- JavaScriptPlugin.logErrorMessage(buf.toString());
- throw ex;
- }
- }
-
- /*
- * @see ICharacterScanner#unread
- */
- public final void unread() {
-
- if (fOffset == 0) {
- if (fBufferOffset == fRangeOffset) {
- // error: BOF
- } else {
- updateBuffer(fBufferOffset - fBuffer.length);
- fOffset= fBuffer.length - 1;
- }
- } else {
- --fOffset;
- }
- }
-
- /*
- * @see ICharacterScanner#getColumn()
- */
- public final int getColumn() {
-
- try {
- final int offset= fBufferOffset + fOffset;
- final int line= fDocument.getLineOfOffset(offset);
- final int start= fDocument.getLineOffset(line);
- return offset - start;
- } catch (BadLocationException e) {
- }
-
- return -1;
- }
-
- /*
- * @see ICharacterScanner#getLegalLineDelimiters()
- */
- public final char[][] getLegalLineDelimiters() {
- return fDelimiters;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ChangeHoverInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ChangeHoverInformationControl.java
deleted file mode 100644
index a33b1a34..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ChangeHoverInformationControl.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.SourceViewerInformationControl;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Specialized source viewer information control used to display quick diff hovers.
- *
- *
- */
-class ChangeHoverInformationControl extends SourceViewerInformationControl {
-
- /** The font name for the viewer font - the same as the java editor's. */
- private static final String SYMBOLIC_FONT_NAME= "org.eclipse.wst.jsdt.ui.editors.textfont"; //$NON-NLS-1$
-
- /** The maximum width of the control, set in <code>setSizeConstraints(int, int)</code>. */
- int fMaxWidth= Integer.MAX_VALUE;
- /** The maximum height of the control, set in <code>setSizeConstraints(int, int)</code>. */
- int fMaxHeight= Integer.MAX_VALUE;
-
- /** The partition type to be used as the starting partition type by the partition scanner. */
- private String fPartition;
- /** The horizontal scroll index. */
- private int fHorizontalScrollPixel;
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int)
- */
- public void setSizeConstraints(int maxWidth, int maxHeight) {
- fMaxWidth= maxWidth;
- fMaxHeight= maxHeight;
- }
-
- /**
- * Creates a new information control.
- *
- * @param parent the shell that is the parent of this hover / control
- * @param shellStyle the additional styles for the shell
- * @param style the additional styles for the styled text widget
- * @param partition the initial partition type to be used for the underlying viewer
- * @param statusFieldText the text to be used in the optional status field
- * or <code>null</code> if the status field should be hidden
- */
- public ChangeHoverInformationControl(Shell parent, int shellStyle, int style, String partition, String statusFieldText) {
- super(parent, shellStyle, style, statusFieldText);
- setViewerFont();
- setStartingPartitionType(partition);
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#computeSizeHint()
- */
- public Point computeSizeHint() {
- Point size= super.computeSizeHint();
- size.x= Math.min(size.x, fMaxWidth);
- size.y= Math.min(size.y, fMaxHeight);
- return size;
- }
-
- /**
- * Sets the font for this viewer sustaining selection and scroll position.
- */
- private void setViewerFont() {
- Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME);
-
- if (getViewer().getDocument() != null) {
-
- Point selection= getViewer().getSelectedRange();
- int topIndex= getViewer().getTopIndex();
-
- StyledText styledText= getViewer().getTextWidget();
- Control parent= styledText;
- if (getViewer() instanceof ITextViewerExtension) {
- ITextViewerExtension extension= (ITextViewerExtension) getViewer();
- parent= extension.getControl();
- }
-
- parent.setRedraw(false);
-
- styledText.setFont(font);
-
- getViewer().setSelectedRange(selection.x , selection.y);
- getViewer().setTopIndex(topIndex);
-
- if (parent instanceof Composite) {
- Composite composite= (Composite) parent;
- composite.layout(true);
- }
-
- parent.setRedraw(true);
-
- } else {
- StyledText styledText= getViewer().getTextWidget();
- styledText.setFont(font);
- }
- }
-
- /**
- * Sets the initial partition for the underlying source viewer.
- *
- * @param partition the partition type
- */
- public void setStartingPartitionType(String partition) {
- if (partition == null)
- fPartition= IDocument.DEFAULT_CONTENT_TYPE;
- else
- fPartition= partition;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String)
- */
- public void setInformation(String content) {
- super.setInformation(content);
- IDocument doc= getViewer().getDocument();
- if (doc == null)
- return;
-
- // ensure that we can scroll enough
- ensureScrollable();
-
- String start= null;
- if (IJavaScriptPartitions.JAVA_DOC.equals(fPartition)) {
- start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
- } else if (IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(fPartition)) {
- start= "/*" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
- }
- if (start != null) {
- try {
- doc.replace(0, 0, start);
- int startLen= start.length();
- getViewer().setDocument(doc, startLen, doc.getLength() - startLen);
- } catch (BadLocationException e) {
- // impossible
- Assert.isTrue(false);
- }
- }
-
- getViewer().getTextWidget().setHorizontalPixel(fHorizontalScrollPixel);
- }
-
- /**
- * Ensures that the control can be scrolled at least to
- * <code>fHorizontalScrollPixel</code> and adjusts <code>fMaxWidth</code>
- * accordingly.
- */
- private void ensureScrollable() {
- IDocument doc= getViewer().getDocument();
- if (doc == null)
- return;
-
- StyledText widget= getViewer().getTextWidget();
- if (widget == null || widget.isDisposed())
- return;
-
- int last= doc.getNumberOfLines() - 1;
- GC gc= new GC(widget);
- gc.setFont(widget.getFont());
- int maxWidth= 0;
- String content= new String();
-
- try {
- for (int i= 0; i <= last; i++) {
- IRegion line;
- line= doc.getLineInformation(i);
- content= doc.get(line.getOffset(), line.getLength());
- int width= gc.textExtent(content).x;
- if (width > maxWidth) {
- maxWidth= width;
- }
- }
- } catch (BadLocationException e) {
- return;
- } finally {
- gc.dispose();
- }
-
- // limit the size of the window to the maximum width minus scrolling,
- // but never more than the configured max size (viewport size).
- fMaxWidth= Math.max(0, Math.min(fMaxWidth, maxWidth - fHorizontalScrollPixel + 8));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.SourceViewerInformationControl#hasContents()
- */
- public boolean hasContents() {
- return super.hasContents() && fMaxWidth > 0;
- }
-
- /**
- * Sets the horizontal scroll index in pixels.
- *
- * @param scrollIndex the new horizontal scroll index
- */
- public void setHorizontalScrollPixel(int scrollIndex) {
- scrollIndex= Math.max(0, scrollIndex);
- fHorizontalScrollPixel= scrollIndex;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java
deleted file mode 100644
index 6c3bedf3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IRule;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.IWordDetector;
-import org.eclipse.jface.text.rules.Token;
-
-
-/**
- * An implementation of <code>IRule</code> capable of detecting words.
- * <p>
- * Word rules also allow for the association of tokens with specific words.
- * That is, not only can the rule be used to provide tokens for exact matches,
- * but also for the generalized notion of a word in the context in which it is used.
- * A word rules uses a word detector to determine what a word is.</p>
- * <p>
- * This word rule allows a word detector to be shared among different word matchers.
- * Its up to the word matchers to decide if a word matches and, in this a case, which
- * token is associated with that word.
- * </p>
- *
- * @see IWordDetector
- *
- */
-public class CombinedWordRule implements IRule {
-
- /**
- * Word matcher, that associates matched words with tokens.
- */
- public static class WordMatcher {
-
- /** The table of predefined words and token for this matcher */
- private Map fWords= new HashMap();
-
- /**
- * Adds a word and the token to be returned if it is detected.
- *
- * @param word the word this rule will search for, may not be <code>null</code>
- * @param token the token to be returned if the word has been found, may not be <code>null</code>
- */
- public void addWord(String word, IToken token) {
- Assert.isNotNull(word);
- Assert.isNotNull(token);
-
- fWords.put(new CharacterBuffer(word), token);
- }
-
- /**
- * Returns the token associated to the given word and the scanner state.
- *
- * @param scanner the scanner
- * @param word the word
- * @return the token or <code>null</code> if none is associated by this matcher
- */
- public IToken evaluate(ICharacterScanner scanner, CharacterBuffer word) {
- IToken token= (IToken) fWords.get(word);
- if (token != null)
- return token;
- return Token.UNDEFINED;
- }
-
- /**
- * Removes all words.
- */
- public void clearWords() {
- fWords.clear();
- }
- }
-
- /**
- * Character buffer, mutable <b>or</b> suitable for use as key in hash maps.
- */
- public static class CharacterBuffer {
-
- /** Buffer content */
- private char[] fContent;
- /** Buffer content size */
- private int fLength= 0;
-
- /** Is hash code cached? */
- private boolean fIsHashCached= false;
- /** The hash code */
- private int fHashCode;
-
- /**
- * Initialize with the given capacity.
- *
- * @param capacity the initial capacity
- */
- public CharacterBuffer(int capacity) {
- fContent= new char[capacity];
- }
-
- /**
- * Initialize with the given content.
- *
- * @param content the initial content
- */
- public CharacterBuffer(String content) {
- fContent= content.toCharArray();
- fLength= content.length();
- }
-
- /**
- * Empties this buffer.
- */
- public void clear() {
- fIsHashCached= false;
- fLength= 0;
- }
-
- /**
- * Appends the given character to the buffer.
- *
- * @param c the character
- */
- public void append(char c) {
- fIsHashCached= false;
- if (fLength == fContent.length) {
- char[] old= fContent;
- fContent= new char[old.length << 1];
- System.arraycopy(old, 0, fContent, 0, old.length);
- }
- fContent[fLength++]= c;
- }
-
- /**
- * Returns the length of the content.
- *
- * @return the length
- */
- public int length() {
- return fLength;
- }
-
- /**
- * Returns the content as string.
- *
- * @return the content
- */
- public String toString() {
- return new String(fContent, 0, fLength);
- }
-
- /**
- * Returns the character at the given position.
- *
- * @param i the position
- * @return the character at position <code>i</code>
- */
- public char charAt(int i) {
- return fContent[i];
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- if (fIsHashCached)
- return fHashCode;
-
- int hash= 0;
- for (int i= 0, n= fLength; i < n; i++)
- hash= 29*hash + fContent[i];
- fHashCode= hash;
- fIsHashCached= true;
- return hash;
- }
-
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj == this)
- return true;
- if (!(obj instanceof CharacterBuffer))
- return false;
- CharacterBuffer buffer= (CharacterBuffer) obj;
- int length= buffer.length();
- if (length != fLength)
- return false;
- for (int i= 0; i < length; i++)
- if (buffer.charAt(i) != fContent[i])
- return false;
- return true;
- }
-
- /**
- * Is the content equal to the given string?
- *
- * @param string the string
- * @return <code>true</code> iff the content is the same character sequence as in the string
- */
- public boolean equals(String string) {
- int length= string.length();
- if (length != fLength)
- return false;
- for (int i= 0; i < length; i++)
- if (string.charAt(i) != fContent[i])
- return false;
- return true;
- }
- }
-
- /** Internal setting for the uninitialized column constraint */
- private static final int UNDEFINED= -1;
-
- /** The word detector used by this rule */
- private IWordDetector fDetector;
- /** The default token to be returned on success and if nothing else has been specified. */
- private IToken fDefaultToken;
- /** The column constraint */
- private int fColumn= UNDEFINED;
- /** Buffer used for pattern detection */
- private CharacterBuffer fBuffer= new CharacterBuffer(16);
-
- /** List of word matchers */
- private List fMatchers= new ArrayList();
-
- /**
- * Creates a rule which, with the help of an word detector, will return the token
- * associated with the detected word. If no token has been associated, the scanner
- * will be rolled back and an undefined token will be returned in order to allow
- * any subsequent rules to analyze the characters.
- *
- * @param detector the word detector to be used by this rule, may not be <code>null</code>
- *
- * @see WordMatcher#addWord(String, IToken)
- */
- public CombinedWordRule(IWordDetector detector) {
- this(detector, null, Token.UNDEFINED);
- }
-
- /**
- * Creates a rule which, with the help of an word detector, will return the token
- * associated with the detected word. If no token has been associated, the
- * specified default token will be returned.
- *
- * @param detector the word detector to be used by this rule, may not be <code>null</code>
- * @param defaultToken the default token to be returned on success
- * if nothing else is specified, may not be <code>null</code>
- *
- * @see WordMatcher#addWord(String, IToken)
- */
- public CombinedWordRule(IWordDetector detector, IToken defaultToken) {
- this(detector, null, defaultToken);
- }
-
- /**
- * Creates a rule which, with the help of an word detector, will return the token
- * associated with the detected word. If no token has been associated, the scanner
- * will be rolled back and an undefined token will be returned in order to allow
- * any subsequent rules to analyze the characters.
- *
- * @param detector the word detector to be used by this rule, may not be <code>null</code>
- * @param matcher the initial word matcher
- *
- * @see WordMatcher#addWord(String, IToken)
- */
- public CombinedWordRule(IWordDetector detector, WordMatcher matcher) {
- this(detector, matcher, Token.UNDEFINED);
- }
-
- /**
- * Creates a rule which, with the help of an word detector, will return the token
- * associated with the detected word. If no token has been associated, the
- * specified default token will be returned.
- *
- * @param detector the word detector to be used by this rule, may not be <code>null</code>
- * @param matcher the initial word matcher
- * @param defaultToken the default token to be returned on success
- * if nothing else is specified, may not be <code>null</code>
- *
- * @see WordMatcher#addWord(String, IToken)
- */
- public CombinedWordRule(IWordDetector detector, WordMatcher matcher, IToken defaultToken) {
-
- Assert.isNotNull(detector);
- Assert.isNotNull(defaultToken);
-
- fDetector= detector;
- fDefaultToken= defaultToken;
- if (matcher != null)
- addWordMatcher(matcher);
- }
-
-
- /**
- * Adds the given matcher.
- *
- * @param matcher the matcher
- */
- public void addWordMatcher(WordMatcher matcher) {
- fMatchers.add(matcher);
- }
-
- /**
- * Sets a column constraint for this rule. If set, the rule's token
- * will only be returned if the pattern is detected starting at the
- * specified column. If the column is smaller then 0, the column
- * constraint is considered removed.
- *
- * @param column the column in which the pattern starts
- */
- public void setColumnConstraint(int column) {
- if (column < 0)
- column= UNDEFINED;
- fColumn= column;
- }
-
- /*
- * @see IRule#evaluate(ICharacterScanner)
- */
- public IToken evaluate(ICharacterScanner scanner) {
- int c= scanner.read();
- if (fDetector.isWordStart((char) c)) {
- if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
-
- fBuffer.clear();
- do {
- fBuffer.append((char) c);
- c= scanner.read();
- } while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c));
- scanner.unread();
-
- for (int i= 0, n= fMatchers.size(); i < n; i++) {
- IToken token= ((WordMatcher) fMatchers.get(i)).evaluate(scanner, fBuffer);
- if (!token.isUndefined())
- return token;
- }
-
- if (fDefaultToken.isUndefined())
- unreadBuffer(scanner);
-
- return fDefaultToken;
- }
- }
-
- scanner.unread();
- return Token.UNDEFINED;
- }
-
- /**
- * 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();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java
deleted file mode 100644
index 6daf4b25..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.reconciler.DirtyRegion;
-import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
-import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
-
-/**
- * A reconciling strategy consisting of a sequence of internal reconciling strategies.
- * By default, all requests are passed on to the contained strategies.
- *
- *
- */
-public class CompositeReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension {
-
- /** The list of internal reconciling strategies. */
- private IReconcilingStrategy[] fStrategies;
-
- /**
- * Creates a new, empty composite reconciling strategy.
- */
- public CompositeReconcilingStrategy() {
- }
-
- /**
- * Sets the reconciling strategies for this composite strategy.
- *
- * @param strategies the strategies to be set or <code>null</code>
- */
- public void setReconcilingStrategies(IReconcilingStrategy[] strategies) {
- fStrategies= strategies;
- }
-
- /**
- * Returns the previously set stratgies or <code>null</code>.
- *
- * @return the contained strategies or <code>null</code>
- */
- public IReconcilingStrategy[] getReconcilingStrategies() {
- return fStrategies;
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument)
- */
- public void setDocument(IDocument document) {
- if (fStrategies == null)
- return;
-
- for (int i= 0; i < fStrategies.length; i++)
- fStrategies[i].setDocument(document);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion)
- */
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- if (fStrategies == null)
- return;
-
- for (int i= 0; i < fStrategies.length; i++)
- fStrategies[i].reconcile(dirtyRegion, subRegion);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
- */
- public void reconcile(IRegion partition) {
- if (fStrategies == null)
- return;
-
- for (int i= 0; i < fStrategies.length; i++)
- fStrategies[i].reconcile(partition);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor)
- */
- public void setProgressMonitor(IProgressMonitor monitor) {
- if (fStrategies == null)
- return;
-
- for (int i=0; i < fStrategies.length; i++) {
- if (fStrategies[i] instanceof IReconcilingStrategyExtension) {
- IReconcilingStrategyExtension extension= (IReconcilingStrategyExtension) fStrategies[i];
- extension.setProgressMonitor(monitor);
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#initialReconcile()
- */
- public void initialReconcile() {
- if (fStrategies == null)
- return;
-
- for (int i=0; i < fStrategies.length; i++) {
- if (fStrategies[i] instanceof IReconcilingStrategyExtension) {
- IReconcilingStrategyExtension extension= (IReconcilingStrategyExtension) fStrategies[i];
- extension.initialReconcile();
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ContentAssistPreference.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ContentAssistPreference.java
deleted file mode 100644
index 4fc5f560..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ContentAssistPreference.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavadocCompletionProcessor;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class ContentAssistPreference {
-
- /** Preference key for content assist auto activation */
- private final static String AUTOACTIVATION= PreferenceConstants.CODEASSIST_AUTOACTIVATION;
- /** Preference key for content assist auto activation delay */
- private final static String AUTOACTIVATION_DELAY= PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY;
- /** Preference key for content assist proposal color */
- private final static String PROPOSALS_FOREGROUND= PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND;
- /** Preference key for content assist proposal color */
- private final static String PROPOSALS_BACKGROUND= PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND;
- /** Preference key for content assist parameters color */
- private final static String PARAMETERS_FOREGROUND= PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND;
- /** Preference key for content assist parameters color */
- private final static String PARAMETERS_BACKGROUND= PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND;
- /** Preference key for content assist auto insert */
- private final static String AUTOINSERT= PreferenceConstants.CODEASSIST_AUTOINSERT;
-
- /** Preference key for java content assist auto activation triggers */
- private final static String AUTOACTIVATION_TRIGGERS_JAVA= PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA;
- /** Preference key for jsdoc content assist auto activation triggers */
- private final static String AUTOACTIVATION_TRIGGERS_JAVADOC= PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC;
-
- /** Preference key for visibility of proposals */
- private final static String SHOW_VISIBLE_PROPOSALS= PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS;
- /** Preference key for case sensitivity of proposals */
- private final static String CASE_SENSITIVITY= PreferenceConstants.CODEASSIST_CASE_SENSITIVITY;
- /** Preference key for adding imports on code assist */
- /** Preference key for filling argument names on method completion */
- private static final String FILL_METHOD_ARGUMENTS= PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES;
- /** Preference key for prefix completion. */
- private static final String PREFIX_COMPLETION= PreferenceConstants.CODEASSIST_PREFIX_COMPLETION;
-
-
- private static Color getColor(IPreferenceStore store, String key, IColorManager manager) {
- RGB rgb= PreferenceConverter.getColor(store, key);
- return manager.getColor(rgb);
- }
-
- private static Color getColor(IPreferenceStore store, String key) {
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- return getColor(store, key, textTools.getColorManager());
- }
-
- private static JavaCompletionProcessor getJavaProcessor(ContentAssistant assistant) {
- IContentAssistProcessor p= assistant.getContentAssistProcessor(IDocument.DEFAULT_CONTENT_TYPE);
- if (p instanceof JavaCompletionProcessor)
- return (JavaCompletionProcessor) p;
- return null;
- }
-
- private static JavadocCompletionProcessor getJavaDocProcessor(ContentAssistant assistant) {
- IContentAssistProcessor p= assistant.getContentAssistProcessor(IJavaScriptPartitions.JAVA_DOC);
- if (p instanceof JavadocCompletionProcessor)
- return (JavadocCompletionProcessor) p;
- return null;
- }
-
- private static void configureJavaProcessor(ContentAssistant assistant, IPreferenceStore store) {
- JavaCompletionProcessor jcp= getJavaProcessor(assistant);
- if (jcp == null)
- return;
-
- String triggers= store.getString(AUTOACTIVATION_TRIGGERS_JAVA);
- if (triggers != null)
- jcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray());
-
- boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS);
- jcp.restrictProposalsToVisibility(enabled);
-
- enabled= store.getBoolean(CASE_SENSITIVITY);
- jcp.restrictProposalsToMatchingCases(enabled);
- }
-
- private static void configureJavaDocProcessor(ContentAssistant assistant, IPreferenceStore store) {
- JavadocCompletionProcessor jdcp= getJavaDocProcessor(assistant);
- if (jdcp == null)
- return;
-
- String triggers= store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC);
- if (triggers != null)
- jdcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray());
-
- boolean enabled= store.getBoolean(CASE_SENSITIVITY);
- jdcp.restrictProposalsToMatchingCases(enabled);
- }
-
- /**
- * Configure the given content assistant from the given store.
- */
- public static void configure(ContentAssistant assistant, IPreferenceStore store) {
-
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- IColorManager manager= textTools.getColorManager();
-
-
- boolean enabled= store.getBoolean(AUTOACTIVATION);
- assistant.enableAutoActivation(enabled);
-
- int delay= store.getInt(AUTOACTIVATION_DELAY);
- assistant.setAutoActivationDelay(delay);
-
- Color c= getColor(store, PROPOSALS_FOREGROUND, manager);
- assistant.setProposalSelectorForeground(c);
-
- c= getColor(store, PROPOSALS_BACKGROUND, manager);
- assistant.setProposalSelectorBackground(c);
-
- c= getColor(store, PARAMETERS_FOREGROUND, manager);
- assistant.setContextInformationPopupForeground(c);
- assistant.setContextSelectorForeground(c);
-
- c= getColor(store, PARAMETERS_BACKGROUND, manager);
- assistant.setContextInformationPopupBackground(c);
- assistant.setContextSelectorBackground(c);
-
- enabled= store.getBoolean(AUTOINSERT);
- assistant.enableAutoInsert(enabled);
-
- enabled= store.getBoolean(PREFIX_COMPLETION);
- assistant.enablePrefixCompletion(enabled);
-
- configureJavaProcessor(assistant, store);
- configureJavaDocProcessor(assistant, store);
- }
-
-
- private static void changeJavaProcessor(ContentAssistant assistant, IPreferenceStore store, String key) {
- JavaCompletionProcessor jcp= getJavaProcessor(assistant);
- if (jcp == null)
- return;
-
- if (AUTOACTIVATION_TRIGGERS_JAVA.equals(key)) {
- String triggers= store.getString(AUTOACTIVATION_TRIGGERS_JAVA);
- if (triggers != null)
- jcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray());
- } else if (SHOW_VISIBLE_PROPOSALS.equals(key)) {
- boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS);
- jcp.restrictProposalsToVisibility(enabled);
- } else if (CASE_SENSITIVITY.equals(key)) {
- boolean enabled= store.getBoolean(CASE_SENSITIVITY);
- jcp.restrictProposalsToMatchingCases(enabled);
- }
- }
-
- private static void changeJavaDocProcessor(ContentAssistant assistant, IPreferenceStore store, String key) {
- JavadocCompletionProcessor jdcp= getJavaDocProcessor(assistant);
- if (jdcp == null)
- return;
-
- if (AUTOACTIVATION_TRIGGERS_JAVADOC.equals(key)) {
- String triggers= store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC);
- if (triggers != null)
- jdcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray());
- } else if (CASE_SENSITIVITY.equals(key)) {
- boolean enabled= store.getBoolean(CASE_SENSITIVITY);
- jdcp.restrictProposalsToMatchingCases(enabled);
- }
- }
-
- /**
- * Changes the configuration of the given content assistant according to the given property
- * change event and the given preference store.
- */
- public static void changeConfiguration(ContentAssistant assistant, IPreferenceStore store, PropertyChangeEvent event) {
-
- String p= event.getProperty();
-
- if (AUTOACTIVATION.equals(p)) {
- boolean enabled= store.getBoolean(AUTOACTIVATION);
- assistant.enableAutoActivation(enabled);
- } else if (AUTOACTIVATION_DELAY.equals(p)) {
- int delay= store.getInt(AUTOACTIVATION_DELAY);
- assistant.setAutoActivationDelay(delay);
- } else if (PROPOSALS_FOREGROUND.equals(p)) {
- Color c= getColor(store, PROPOSALS_FOREGROUND);
- assistant.setProposalSelectorForeground(c);
- } else if (PROPOSALS_BACKGROUND.equals(p)) {
- Color c= getColor(store, PROPOSALS_BACKGROUND);
- assistant.setProposalSelectorBackground(c);
- } else if (PARAMETERS_FOREGROUND.equals(p)) {
- Color c= getColor(store, PARAMETERS_FOREGROUND);
- assistant.setContextInformationPopupForeground(c);
- assistant.setContextSelectorForeground(c);
- } else if (PARAMETERS_BACKGROUND.equals(p)) {
- Color c= getColor(store, PARAMETERS_BACKGROUND);
- assistant.setContextInformationPopupBackground(c);
- assistant.setContextSelectorBackground(c);
- } else if (AUTOINSERT.equals(p)) {
- boolean enabled= store.getBoolean(AUTOINSERT);
- assistant.enableAutoInsert(enabled);
- } else if (PREFIX_COMPLETION.equals(p)) {
- boolean enabled= store.getBoolean(PREFIX_COMPLETION);
- assistant.enablePrefixCompletion(enabled);
- }
-
- changeJavaProcessor(assistant, store, p);
- changeJavaDocProcessor(assistant, store, p);
- }
-
- public static boolean fillArgumentsOnMethodCompletion(IPreferenceStore store) {
- return store.getBoolean(FILL_METHOD_ARGUMENTS);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java
deleted file mode 100644
index 4362d93a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.text.CharacterIterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-
-
-/**
- * An <code>IDocument</code> based implementation of
- * <code>CharacterIterator</code> and <code>CharSequence</code>. Note that
- * the supplied document is not copied; if the document is modified during the
- * lifetime of a <code>DocumentCharacterIterator</code>, the methods
- * returning document content may not always return the same values. Also, if
- * accessing the document fails with a {@link BadLocationException}, any of
- * <code>CharacterIterator</code> methods as well as <code>charAt</code>may
- * return {@link CharacterIterator#DONE}.
- *
- *
- */
-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) throws IllegalArgumentException {
- 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) throws IllegalArgumentException {
- 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()
- */
- public char first() {
- return setIndex(getBeginIndex());
- }
-
- /*
- * @see java.text.CharacterIterator#last()
- */
- public char last() {
- if (fFirst == fLast)
- return setIndex(getEndIndex());
- else
- return setIndex(getEndIndex() - 1);
- }
-
- /*
- * @see java.text.CharacterIterator#current()
- */
- public char current() {
- if (fIndex >= fFirst && fIndex < fLast)
- try {
- return fDocument.getChar(fIndex);
- } catch (BadLocationException e) {
- // ignore
- }
- return DONE;
- }
-
- /*
- * @see java.text.CharacterIterator#next()
- */
- public char next() {
- return setIndex(Math.min(fIndex + 1, getEndIndex()));
- }
-
- /*
- * @see java.text.CharacterIterator#previous()
- */
- public char previous() {
- if (fIndex > getBeginIndex()) {
- return setIndex(fIndex - 1);
- } else {
- return DONE;
- }
- }
-
- /*
- * @see java.text.CharacterIterator#setIndex(int)
- */
- public char setIndex(int position) {
- if (position >= getBeginIndex() && position <= getEndIndex())
- fIndex= position;
- else
- throw new IllegalArgumentException();
-
- invariant();
- return current();
- }
-
- /*
- * @see java.text.CharacterIterator#getBeginIndex()
- */
- public int getBeginIndex() {
- return fFirst;
- }
-
- /*
- * @see java.text.CharacterIterator#getEndIndex()
- */
- public int getEndIndex() {
- return fLast;
- }
-
- /*
- * @see java.text.CharacterIterator#getIndex()
- */
- public int getIndex() {
- return fIndex;
- }
-
- /*
- * @see java.text.CharacterIterator#clone()
- */
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new InternalError();
- }
- }
-
- /*
- * @see java.lang.CharSequence#length()
- */
- 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}
- */
- 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;
- }
- else
- throw new IndexOutOfBoundsException();
- }
-
- /*
- * @see java.lang.CharSequence#subSequence(int, int)
- */
- 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);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java
deleted file mode 100644
index fbbbc5e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java
+++ /dev/null
@@ -1,560 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IPartitionTokenScanner;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * This scanner recognizes the JSDoc comments, multi line comments, single line comments,
- * strings, characters, and regular expressions.
- */
-public class FastJavaPartitionScanner implements IPartitionTokenScanner, IJavaScriptPartitions {
-
- // states
- private static final int JAVASCRIPT= 0;
- private static final int SINGLE_LINE_COMMENT= 1;
- private static final int MULTI_LINE_COMMENT= 2;
- private static final int JSDOC= 3;
- private static final int CHARACTER= 4;
- private static final int STRING= 5;
- private static final int REGULAR_EXPRESSION = 6;
-
- // beginning of prefixes and postfixes
- private static final int NONE= 0;
- private static final int BACKSLASH= 1; // postfix for STRING and CHARACTER
- private static final int SLASH= 2; // prefix for SINGLE_LINE or MULTI_LINE or JSDOC
- private static final int SLASH_STAR= 3; // prefix for MULTI_LINE_COMMENT or JSDOC
- private static final int SLASH_STAR_STAR= 4; // prefix for MULTI_LINE_COMMENT or JSDOC
- private static final int STAR= 5; // postfix for MULTI_LINE_COMMENT or JSDOC
- private static final int CARRIAGE_RETURN=6; // postfix for STRING, CHARACTER and SINGLE_LINE_COMMENT
- private static final int REGULAR_EXPRESSION_END=7;
-
- /** The scanner. */
- private final BufferedDocumentScanner fScanner= new BufferedDocumentScanner(1000); // faster implementation
-
- /** The offset of the last returned token. */
- private int fTokenOffset;
- /** The length of the last returned token. */
- private int fTokenLength;
-
- /** The state of the scanner. */
- private int fState;
- /** The last significant characters read. */
- private int fLast;
- /** The amount of characters already read on first call to nextToken(). */
- private int fPrefixLength;
-
- private final IToken[] fTokens= new IToken[] {
- new Token(null),
- new Token(JAVA_SINGLE_LINE_COMMENT),
- new Token(JAVA_MULTI_LINE_COMMENT),
- new Token(JAVA_DOC),
- new Token(JAVA_CHARACTER),
- new Token(JAVA_STRING),
- new Token(JAVA_STRING) // regular expression same as string
- };
-
- public FastJavaPartitionScanner() {
- // create the scanner
- }
-
- /*
- * @see org.eclipse.jface.text.rules.ITokenScanner#nextToken()
- */
- public IToken nextToken() {
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
-
- int lastNonWhitespaceChar = NONE;
- int currentChar = NONE;
-
- while (true) {
- if (!Character.isWhitespace((char)currentChar))
- lastNonWhitespaceChar = currentChar;
-
- // read in the next char
- currentChar= fScanner.read();
-
- // characters
- switch (currentChar) {
- case ICharacterScanner.EOF:
- if (fTokenLength > 0) {
- fLast= NONE; // ignore last
- return preFix(fState, JAVASCRIPT, NONE, 0);
-
- } else {
- fLast= NONE;
- fPrefixLength= 0;
- return Token.EOF;
- }
-
- case '\r':
- if (fLast != CARRIAGE_RETURN) {
- fLast= CARRIAGE_RETURN;
- fTokenLength++;
- continue;
-
- } else {
- switch (fState) {
- case SINGLE_LINE_COMMENT:
- case CHARACTER:
- case STRING:
- case REGULAR_EXPRESSION:
- if (fTokenLength > 0) {
- IToken token= fTokens[fState];
-
- fLast= CARRIAGE_RETURN;
- fPrefixLength= 1;
-
- fState= JAVASCRIPT;
- return token;
-
- } else {
- consume();
- continue;
- }
-
- default:
- consume();
- continue;
- }
- }
-
- case '\n':
- switch (fState) {
- case SINGLE_LINE_COMMENT:
- case CHARACTER:
- case REGULAR_EXPRESSION:
- case STRING:
- return postFix(fState);
-
- default:
- consume();
- continue;
- }
-
- default:
- if (fLast == CARRIAGE_RETURN) {
- switch (fState) {
- case SINGLE_LINE_COMMENT:
- case REGULAR_EXPRESSION:
- case CHARACTER:
- case STRING:
-
- int last;
- int newState;
- switch (currentChar) {
- case '/':
- last= SLASH;
- newState= JAVASCRIPT;
- break;
-
- case '*':
- last= STAR;
- newState= JAVASCRIPT;
- break;
-
- case '\'':
- last= NONE;
- newState= CHARACTER;
- break;
-
- case '"':
- last= NONE;
- newState= STRING;
- break;
-
- case '\r':
- last= CARRIAGE_RETURN;
- newState= JAVASCRIPT;
- break;
-
- case '\\':
- last= BACKSLASH;
- newState= JAVASCRIPT;
- break;
-
- default:
- last= NONE;
- newState= JAVASCRIPT;
- break;
- }
-
- fLast= NONE; // ignore fLast
- return preFix(fState, newState, last, 1);
-
- default:
- break;
- }
- }
- }
-
- // states
- switch (fState) {
- case JAVASCRIPT:
- switch (currentChar) {
- case '/':
- if (fLast == SLASH) {
- if (fTokenLength - getLastLength(fLast) > 0) {
- return preFix(JAVASCRIPT, SINGLE_LINE_COMMENT, NONE, 2);
- } else {
- preFix(JAVASCRIPT, SINGLE_LINE_COMMENT, NONE, 2);
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
- break;
- }
-
- } else {
- switch (lastNonWhitespaceChar) //possible chars before regexp
- {
- case '(':
- case ',':
- case '=':
- case ':':
- case '[':
- case '!':
- case '&':
- case '?':
- case '{':
- case '}':
- int tempChar = fScanner.read();
- fScanner.unread();
- switch(tempChar) {
- case '/':
- case '*':
- break;
- default:
- //check if regexp
- fLast= NONE; // ignore fLast
- if (fTokenLength > 0)
- return preFix(JAVASCRIPT, REGULAR_EXPRESSION, NONE, 1);
- else {
- preFix(JAVASCRIPT, REGULAR_EXPRESSION, NONE, 1);
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
- break;
- }
- }
-
- }
- fTokenLength++;
- fLast= SLASH;
- break;
- }
-
- case '*':
- if (fLast == SLASH) {
- if (fTokenLength - getLastLength(fLast) > 0)
- return preFix(JAVASCRIPT, MULTI_LINE_COMMENT, SLASH_STAR, 2);
- else {
- preFix(JAVASCRIPT, MULTI_LINE_COMMENT, SLASH_STAR, 2);
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
- break;
- }
-
- } else {
- consume();
- break;
- }
-
- case '\'':
- fLast= NONE; // ignore fLast
- if (fTokenLength > 0)
- return preFix(JAVASCRIPT, CHARACTER, NONE, 1);
- else {
- preFix(JAVASCRIPT, CHARACTER, NONE, 1);
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
- break;
- }
-
- case '"':
- fLast= NONE; // ignore fLast
- if (fTokenLength > 0)
- return preFix(JAVASCRIPT, STRING, NONE, 1);
- else {
- preFix(JAVASCRIPT, STRING, NONE, 1);
- fTokenOffset += fTokenLength;
- fTokenLength= fPrefixLength;
- break;
- }
-
- default:
- consume();
- break;
- }
- break;
-
- case SINGLE_LINE_COMMENT:
- consume();
- break;
-
- case JSDOC:
- switch (currentChar) {
- case '/':
- switch (fLast) {
- case SLASH_STAR_STAR:
- return postFix(MULTI_LINE_COMMENT);
-
- case STAR:
- return postFix(JSDOC);
-
- default:
- consume();
- break;
- }
- break;
-
- case '*':
- fTokenLength++;
- fLast= STAR;
- break;
-
- default:
- consume();
- break;
- }
- break;
-
- case MULTI_LINE_COMMENT:
- switch (currentChar) {
- case '*':
- if (fLast == SLASH_STAR) {
- fLast= SLASH_STAR_STAR;
- fTokenLength++;
- fState= JSDOC;
- } else {
- fTokenLength++;
- fLast= STAR;
- }
- break;
-
- case '/':
- if (fLast == STAR) {
- return postFix(MULTI_LINE_COMMENT);
- } else {
- consume();
- break;
- }
-
- default:
- consume();
- break;
- }
- break;
-
- case STRING:
- switch (currentChar) {
- case '\\':
- fLast= (fLast == BACKSLASH) ? NONE : BACKSLASH;
- fTokenLength++;
- break;
-
- case '\"':
- if (fLast != BACKSLASH) {
- return postFix(STRING);
-
- } else {
- consume();
- break;
- }
-
- default:
- consume();
- break;
- }
- break;
-
- case REGULAR_EXPRESSION:
- switch (currentChar) {
-
- case '\\':
- fLast= (fLast == BACKSLASH) ? NONE : BACKSLASH;
- fTokenLength++;
- break;
-
- case '/':
- fLast= (fLast == BACKSLASH) ? NONE : SLASH;
- fTokenLength++;
- break;
-
- case 'g':
- case 'm':
- case 'i':
- if (fLast==SLASH || fLast==REGULAR_EXPRESSION_END)
- {
- fLast=REGULAR_EXPRESSION_END;
- fTokenLength++;
- }
- else
- consume();
- break;
-
-
-
- default:
- if (fLast==SLASH || fLast==REGULAR_EXPRESSION_END)
- {
- fTokenLength--;
- fScanner.unread();
- return postFix(REGULAR_EXPRESSION);
- }
- consume();
- break;
- }
- break;
-
- case CHARACTER:
- switch (currentChar) {
- case '\\':
- fLast= (fLast == BACKSLASH) ? NONE : BACKSLASH;
- fTokenLength++;
- break;
-
- case '\'':
- if (fLast != BACKSLASH) {
- return postFix(CHARACTER);
-
- } else {
- consume();
- break;
- }
-
- default:
- consume();
- break;
- }
- break;
- }
- }
- }
-
- private static final int getLastLength(int last) {
- switch (last) {
- default:
- return -1;
-
- case NONE:
- return 0;
-
- case CARRIAGE_RETURN:
- case BACKSLASH:
- case SLASH:
- case STAR:
- return 1;
-
- case SLASH_STAR:
- return 2;
-
- case SLASH_STAR_STAR:
- return 3;
- }
- }
-
- private final void consume() {
- fTokenLength++;
- fLast= NONE;
- }
-
- private final IToken postFix(int state) {
- fTokenLength++;
- fLast= NONE;
- fState= JAVASCRIPT;
- fPrefixLength= 0;
- return fTokens[state];
- }
-
- private final IToken preFix(int state, int newState, int last, int prefixLength) {
- fTokenLength -= getLastLength(fLast);
- fLast= last;
- fPrefixLength= prefixLength;
- IToken token= fTokens[state];
- fState= newState;
- return token;
- }
-
- private static int getState(String contentType) {
-
- if (contentType == null)
- return JAVASCRIPT;
-
- else if (contentType.equals(JAVA_SINGLE_LINE_COMMENT))
- return SINGLE_LINE_COMMENT;
-
- else if (contentType.equals(JAVA_MULTI_LINE_COMMENT))
- return MULTI_LINE_COMMENT;
-
- else if (contentType.equals(JAVA_DOC))
- return JSDOC;
-
- else if (contentType.equals(JAVA_STRING))
- return STRING;
-
- else if (contentType.equals(JAVA_CHARACTER))
- return CHARACTER;
-
- else
- return JAVASCRIPT;
- }
-
- /*
- * @see IPartitionTokenScanner#setPartialRange(IDocument, int, int, String, int)
- */
- public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) {
-
- fScanner.setRange(document, offset, length);
- fTokenOffset= partitionOffset;
- fTokenLength= 0;
- fPrefixLength= offset - partitionOffset;
- fLast= NONE;
-
- if (offset == partitionOffset) {
- // restart at beginning of partition
- fState= JAVASCRIPT;
- } else {
- fState= getState(contentType);
- }
- }
-
- /*
- * @see ITokenScanner#setRange(IDocument, int, int)
- */
- public void setRange(IDocument document, int offset, int length) {
-
- fScanner.setRange(document, offset, length);
- fTokenOffset= offset;
- fTokenLength= 0;
- fPrefixLength= 0;
- fLast= NONE;
- fState= JAVASCRIPT;
- }
-
- /*
- * @see ITokenScanner#getTokenLength()
- */
- public int getTokenLength() {
- return fTokenLength;
- }
-
- /*
- * @see ITokenScanner#getTokenOffset()
- */
- public int getTokenOffset() {
- return fTokenOffset;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java
deleted file mode 100644
index 1c9dd9ac..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.jface.text.source.DefaultAnnotationHover;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-
-/**
- * Determines all markers for the given line and collects, concatenates, and formats
- * returns their messages in HTML.
- *
- *
- */
-public class HTMLAnnotationHover extends DefaultAnnotationHover {
-
- /*
- * Formats a message as HTML text.
- */
- protected String formatSingleMessage(String message) {
- StringBuffer buffer= new StringBuffer();
- HTMLPrinter.addPageProlog(buffer);
- HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message));
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-
- /*
- * Formats several message as HTML text.
- */
- protected String formatMultipleMessages(List messages) {
- StringBuffer buffer= new StringBuffer();
- HTMLPrinter.addPageProlog(buffer);
- HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(JavaUIMessages.JavaAnnotationHover_multipleMarkersAtThisLine));
-
- HTMLPrinter.startBulletList(buffer);
- Iterator e= messages.iterator();
- while (e.hasNext())
- HTMLPrinter.addBullet(buffer, HTMLPrinter.convertToHTMLContent((String) e.next()));
- HTMLPrinter.endBulletList(buffer);
-
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ISourceVersionDependent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ISourceVersionDependent.java
deleted file mode 100644
index 8139b38e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ISourceVersionDependent.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-/**
- * Mix-in for any rule that changes its behavior based on the Java source
- * version.
- *
- *
- */
-public interface ISourceVersionDependent {
-
- /**
- * Sets the configured java source version to one of the
- * <code>JavaScriptCore.VERSION_X_Y</code> values.
- *
- * @param version the new java source version
- * @see org.eclipse.wst.jsdt.core.JavaScriptCore
- */
- void setSourceVersion(String version);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java
deleted file mode 100644
index 3f162e17..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.wst.jsdt.internal.ui.text.TypingRun.ChangeType;
-
-
-/**
- * Listener for <code>TypingRun</code> events.
- *
- *
- */
-public interface ITypingRunListener {
- /**
- * Called when a new <code>TypingRun</code> is started.
- *
- * @param run the newly started run
- */
- void typingRunStarted(TypingRun run);
-
- /**
- * Called whenever a <code>TypingRun</code> is ended.
- *
- * @param run the ended run
- * @param reason the type of change that caused the end of the run
- */
- void typingRunEnded(TypingRun run, ChangeType reason);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java
deleted file mode 100644
index 6429c72d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.text.CharacterIterator;
-
-import org.eclipse.core.runtime.Assert;
-
-import com.ibm.icu.text.BreakIterator;
-
-
-
-/**
- * A java break iterator. It returns all breaks, including before and after
- * whitespace, and it returns all camel case breaks.
- * <p>
- * A line break may be any of "\n", "\r", "\r\n", "\n\r".
- * </p>
- *
- *
- */
-public class JavaBreakIterator extends BreakIterator {
-
- /**
- * A run of common characters.
- */
- protected static abstract class Run {
- /** The length of this run. */
- protected int length;
-
- public Run() {
- init();
- }
-
- /**
- * Returns <code>true</code> if this run consumes <code>ch</code>,
- * <code>false</code> otherwise. If <code>true</code> is returned,
- * the length of the receiver is adjusted accordingly.
- *
- * @param ch the character to test
- * @return <code>true</code> if <code>ch</code> was consumed
- */
- protected boolean consume(char ch) {
- if (isValid(ch)) {
- length++;
- return true;
- }
- return false;
- }
-
- /**
- * Whether this run accepts that character; does not update state. Called
- * from the default implementation of <code>consume</code>.
- *
- * @param ch the character to test
- * @return <code>true</code> if <code>ch</code> is accepted
- */
- protected abstract boolean isValid(char ch);
-
- /**
- * Resets this run to the initial state.
- */
- protected void init() {
- length= 0;
- }
- }
-
- static final class Whitespace extends Run {
- protected boolean isValid(char ch) {
- return Character.isWhitespace(ch) && ch != '\n' && ch != '\r';
- }
- }
-
- static final class LineDelimiter extends Run {
- /** State: INIT -> delimiter -> EXIT. */
- private char fState;
- private static final char INIT= '\0';
- private static final char EXIT= '\1';
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#init()
- */
- protected void init() {
- super.init();
- fState= INIT;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#consume(char)
- */
- protected boolean consume(char ch) {
- if (!isValid(ch) || fState == EXIT)
- return false;
-
- if (fState == INIT) {
- fState= ch;
- length++;
- return true;
- } else if (fState != ch) {
- fState= EXIT;
- length++;
- return true;
- } else {
- return false;
- }
- }
-
- protected boolean isValid(char ch) {
- return ch == '\n' || ch == '\r';
- }
- }
-
- static final class Identifier extends Run {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#isValid(char)
- */
- protected boolean isValid(char ch) {
- return Character.isJavaIdentifierPart(ch);
- }
- }
-
- static final class CamelCaseIdentifier extends Run {
- /* states */
- private static final int S_INIT= 0;
- private static final int S_LOWER= 1;
- private static final int S_ONE_CAP= 2;
- private static final int S_ALL_CAPS= 3;
- private static final int S_EXIT= 4;
- private static final int S_EXIT_MINUS_ONE= 5;
-
- /* character types */
- private static final int K_INVALID= 0;
- private static final int K_LOWER= 1;
- private static final int K_UPPER= 2;
- private static final int K_OTHER= 3;
-
- private int fState;
-
- private final static int[][] MATRIX= new int[][] {
- // K_INVALID, K_LOWER, K_UPPER, K_OTHER
- { S_EXIT, S_LOWER, S_ONE_CAP, S_LOWER }, // S_INIT
- { S_EXIT, S_LOWER, S_EXIT, S_LOWER }, // S_LOWER
- { S_EXIT, S_LOWER, S_ALL_CAPS, S_LOWER }, // S_ONE_CAP
- { S_EXIT, S_EXIT_MINUS_ONE, S_ALL_CAPS, S_LOWER }, // S_ALL_CAPS
- };
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#init()
- */
- protected void init() {
- super.init();
- fState= S_INIT;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#consumes(char)
- */
- protected boolean consume(char ch) {
- int kind= getKind(ch);
- fState= MATRIX[fState][kind];
- switch (fState) {
- case S_LOWER:
- case S_ONE_CAP:
- case S_ALL_CAPS:
- length++;
- return true;
- case S_EXIT:
- return false;
- case S_EXIT_MINUS_ONE:
- length--;
- return false;
- default:
- Assert.isTrue(false);
- return false;
- }
- }
-
- /**
- * Determines the kind of a character.
- *
- * @param ch the character to test
- */
- private int getKind(char ch) {
- if (Character.isUpperCase(ch))
- return K_UPPER;
- if (Character.isLowerCase(ch))
- return K_LOWER;
- if (Character.isJavaIdentifierPart(ch)) // _, digits...
- return K_OTHER;
- return K_INVALID;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#isValid(char)
- */
- protected boolean isValid(char ch) {
- return Character.isJavaIdentifierPart(ch);
- }
- }
-
- static final class Other extends Run {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaBreakIterator.Run#isValid(char)
- */
- protected boolean isValid(char ch) {
- return !Character.isWhitespace(ch) && !Character.isJavaIdentifierPart(ch);
- }
- }
-
- private static final Run WHITESPACE= new Whitespace();
- private static final Run DELIMITER= new LineDelimiter();
- private static final Run CAMELCASE= new CamelCaseIdentifier(); // new Identifier();
- private static final Run OTHER= new Other();
-
- /** The platform break iterator (word instance) used as a base. */
- protected final BreakIterator fIterator;
- /** The text we operate on. */
- protected CharSequence fText;
- /** our current position for the stateful methods. */
- private int fIndex;
-
-
- /**
- * Creates a new break iterator.
- */
- public JavaBreakIterator() {
- fIterator= BreakIterator.getWordInstance();
- fIndex= fIterator.current();
- }
-
- /*
- * @see java.text.BreakIterator#current()
- */
- public int current() {
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#first()
- */
- public int first() {
- fIndex= fIterator.first();
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#following(int)
- */
- public int following(int offset) {
- // work around too eager IAEs in standard implementation
- if (offset == getText().getEndIndex())
- return DONE;
-
- int next= fIterator.following(offset);
- if (next == DONE)
- return DONE;
-
- // TODO deal with complex script word boundaries
- // Math.min(offset + run.length, next) does not work
- // since BreakIterator.getWordInstance considers _ as boundaries
- // seems to work fine, however
- Run run= consumeRun(offset);
- return offset + run.length;
-
- }
-
- /**
- * Consumes a run of characters at the limits of which we introduce a break.
- * @param offset the offset to start at
- * @return the run that was consumed
- */
- private Run consumeRun(int offset) {
- // assert offset < length
-
- char ch= fText.charAt(offset);
- int length= fText.length();
- Run run= getRun(ch);
- while (run.consume(ch) && offset < length - 1) {
- offset++;
- ch= fText.charAt(offset);
- }
-
- return run;
- }
-
- /**
- * Returns a run based on a character.
- *
- * @param ch the character to test
- * @return the correct character given <code>ch</code>
- */
- private Run getRun(char ch) {
- Run run;
- if (WHITESPACE.isValid(ch))
- run= WHITESPACE;
- else if (DELIMITER.isValid(ch))
- run= DELIMITER;
- else if (CAMELCASE.isValid(ch))
- run= CAMELCASE;
- else if (OTHER.isValid(ch))
- run= OTHER;
- else {
- Assert.isTrue(false);
- return null;
- }
-
- run.init();
- return run;
- }
-
- /*
- * @see java.text.BreakIterator#getText()
- */
- public CharacterIterator getText() {
- return fIterator.getText();
- }
-
- /*
- * @see java.text.BreakIterator#isBoundary(int)
- */
- public boolean isBoundary(int offset) {
- if (offset == getText().getBeginIndex())
- return true;
- else
- return following(offset - 1) == offset;
- }
-
- /*
- * @see java.text.BreakIterator#last()
- */
- public int last() {
- fIndex= fIterator.last();
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#next()
- */
- public int next() {
- fIndex= following(fIndex);
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#next(int)
- */
- public int next(int n) {
- return fIterator.next(n);
- }
-
- /*
- * @see java.text.BreakIterator#preceding(int)
- */
- public int preceding(int offset) {
- if (offset == getText().getBeginIndex())
- return DONE;
-
- if (isBoundary(offset - 1))
- return offset - 1;
-
- int previous= offset - 1;
- do {
- previous= fIterator.preceding(previous);
- } while (!isBoundary(previous));
-
- int last= DONE;
- while (previous < offset) {
- last= previous;
- previous= following(previous);
- }
-
- return last;
- }
-
- /*
- * @see java.text.BreakIterator#previous()
- */
- public int previous() {
- fIndex= preceding(fIndex);
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#setText(java.lang.String)
- */
- public void setText(String newText) {
- setText((CharSequence) newText);
- }
-
- /**
- * Creates a break iterator given a char sequence.
- * @param newText the new text
- */
- public void setText(CharSequence newText) {
- fText= newText;
- fIterator.setText(new SequenceCharacterIterator(newText));
- first();
- }
-
- /*
- * @see java.text.BreakIterator#setText(java.text.CharacterIterator)
- */
- public void setText(CharacterIterator newText) {
- if (newText instanceof CharSequence) {
- fText= (CharSequence) newText;
- fIterator.setText(newText);
- first();
- } else {
- throw new UnsupportedOperationException("CharacterIterator not supported"); //$NON-NLS-1$
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java
deleted file mode 100644
index cb58a35d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.LineChangeHover;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.editors.text.EditorsUI;
-
-/**
- * A line change hover for Java source code. Adds a custom information control creator returning a
- * source viewer with syntax coloring.
- *
- *
- */
-public class JavaChangeHover extends LineChangeHover {
-
- /** The last computed partition type. */
- private String fPartition;
- /** The last created information control. */
- private ChangeHoverInformationControl fInformationControl;
- /** The document partitioning to be used by this hover. */
- private String fPartitioning;
- /** The last created information control. */
- private int fLastScrollIndex= 0;
-
- /**
- * The orientation to be used by this hover.
- * Allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT
- *
- */
- private int fOrientation;
-
- /**
- * Creates a new change hover for the given document partitioning.
- *
- * @param partitioning the document partitioning
- * @param orientation the orientation, allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT
- */
- public JavaChangeHover(String partitioning, int orientation) {
- Assert.isLegal(orientation == SWT.RIGHT_TO_LEFT || orientation == SWT.LEFT_TO_RIGHT);
- fPartitioning= partitioning;
- fOrientation= orientation;
- }
-
- /*
- * @see org.eclipse.ui.internal.editors.text.LineChangeHover#formatSource(java.lang.String)
- */
- protected String formatSource(String content) {
- return content;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverControlCreator()
- */
- public IInformationControlCreator getHoverControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int shellStyle= SWT.TOOL | SWT.NO_TRIM | fOrientation;
- fInformationControl= new ChangeHoverInformationControl(parent, shellStyle, SWT.NONE, fPartition, EditorsUI.getTooltipAffordanceString());
- fInformationControl.setHorizontalScrollPixel(fLastScrollIndex);
- return fInformationControl;
- }
- };
- }
-
- /*
- * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
- *
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE | SWT.TOOL | fOrientation;
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- fInformationControl= new ChangeHoverInformationControl(parent, shellStyle, style, fPartition, null);
- fInformationControl.setHorizontalScrollPixel(fLastScrollIndex);
- return fInformationControl;
- }
- };
- }
-
- /*
- * @see org.eclipse.jface.text.source.LineChangeHover#computeLineRange(org.eclipse.jface.text.source.ISourceViewer, int, int, int)
- */
- protected Point computeLineRange(ISourceViewer viewer, int line, int first, int number) {
- Point lineRange= super.computeLineRange(viewer, line, first, number);
- if (lineRange != null) {
- fPartition= getPartition(viewer, lineRange.x);
- } else {
- fPartition= IDocument.DEFAULT_CONTENT_TYPE;
- }
- fLastScrollIndex= viewer.getTextWidget().getHorizontalPixel();
- if (fInformationControl != null) {
- fInformationControl.setStartingPartitionType(fPartition);
- fInformationControl.setHorizontalScrollPixel(fLastScrollIndex);
- }
- return lineRange;
- }
-
- /**
- * Returns the partition type of the document displayed in <code>viewer</code> at <code>startLine</code>.
-
- * @param viewer the viewer
- * @param startLine the line in the viewer
- * @return the partition type at the start of <code>startLine</code>, or <code>IDocument.DEFAULT_CONTENT_TYPE</code> if none can be detected
- */
- private String getPartition(ISourceViewer viewer, int startLine) {
- if (viewer == null)
- return null;
- IDocument doc= viewer.getDocument();
- if (doc == null)
- return null;
- if (startLine <= 0)
- return IDocument.DEFAULT_CONTENT_TYPE;
- try {
- ITypedRegion region= TextUtilities.getPartition(doc, fPartitioning, doc.getLineOffset(startLine) - 1, true);
- return region.getType();
- } catch (BadLocationException e) {
- }
- return IDocument.DEFAULT_CONTENT_TYPE;
- }
-
-
- /*
- * @see org.eclipse.jface.text.source.LineChangeHover#getTabReplacement()
- */
- protected String getTabReplacement() {
- return Character.toString('\t');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCodeReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCodeReader.java
deleted file mode 100644
index c73d8a73..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCodeReader.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.io.IOException;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.SingleCharReader;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-
-
-/**
- * Reads from a document either forwards or backwards. May be configured to
- * skip comments and strings.
- */
-public class JavaCodeReader extends SingleCharReader {
-
- /** The EOF character */
- public static final int EOF= -1;
-
- private boolean fSkipComments= false;
- private boolean fSkipStrings= false;
- private boolean fForward= false;
-
- private IDocument fDocument;
- private int fOffset;
-
- private int fEnd= -1;
- private int fCachedLineNumber= -1;
- private int fCachedLineOffset= -1;
-
-
- public JavaCodeReader() {
- }
-
- /**
- * Returns the offset of the last read character. Should only be called after read has been called.
- */
- public int getOffset() {
- return fForward ? fOffset -1 : fOffset;
- }
-
- public void configureForwardReader(IDocument document, int offset, int length, boolean skipComments, boolean skipStrings) throws IOException {
- fDocument= document;
- fOffset= offset;
- fSkipComments= skipComments;
- fSkipStrings= skipStrings;
-
- fForward= true;
- fEnd= Math.min(fDocument.getLength(), fOffset + length);
- }
-
- public void configureBackwardReader(IDocument document, int offset, boolean skipComments, boolean skipStrings) throws IOException {
- fDocument= document;
- fOffset= offset;
- fSkipComments= skipComments;
- fSkipStrings= skipStrings;
-
- fForward= false;
- try {
- fCachedLineNumber= fDocument.getLineOfOffset(fOffset);
- } catch (BadLocationException x) {
- throw new IOException(x.getMessage());
- }
- }
-
- /*
- * @see Reader#close()
- */
- public void close() throws IOException {
- fDocument= null;
- }
-
- /*
- * @see SingleCharReader#read()
- */
- public int read() throws IOException {
- try {
- return fForward ? readForwards() : readBackwards();
- } catch (BadLocationException x) {
- throw new IOException(x.getMessage());
- }
- }
-
- private void gotoCommentEnd() throws BadLocationException {
- while (fOffset < fEnd) {
- char current= fDocument.getChar(fOffset++);
- if (current == '*') {
- if (fOffset < fEnd && fDocument.getChar(fOffset) == '/') {
- ++ fOffset;
- return;
- }
- }
- }
- }
-
- private void gotoStringEnd(char delimiter) throws BadLocationException {
- while (fOffset < fEnd) {
- char current= fDocument.getChar(fOffset++);
- if (current == '\\') {
- // ignore escaped characters
- ++ fOffset;
- } else if (current == delimiter) {
- return;
- }
- }
- }
-
- private void gotoLineEnd() throws BadLocationException {
- int line= fDocument.getLineOfOffset(fOffset);
- fOffset= fDocument.getLineOffset(line + 1);
- }
-
- private int readForwards() throws BadLocationException {
- while (fOffset < fEnd) {
- char current= fDocument.getChar(fOffset++);
-
- switch (current) {
- case '/':
-
- if (fSkipComments && fOffset < fEnd) {
- char next= fDocument.getChar(fOffset);
- if (next == '*') {
- // a comment starts, advance to the comment end
- ++ fOffset;
- gotoCommentEnd();
- continue;
- } else if (next == '/') {
- // '//'-comment starts, advance to the line end
- gotoLineEnd();
- continue;
- }
- }
-
- return current;
-
- case '"':
- case '\'':
-
- if (fSkipStrings) {
- gotoStringEnd(current);
- continue;
- }
-
- return current;
- }
-
- return current;
- }
-
- return EOF;
- }
-
- private void handleSingleLineComment() throws BadLocationException {
- int line= fDocument.getLineOfOffset(fOffset);
- if (line < fCachedLineNumber) {
- fCachedLineNumber= line;
- fCachedLineOffset= fDocument.getLineOffset(line);
- int offset= fOffset;
- while (fCachedLineOffset < offset) {
- char current= fDocument.getChar(offset--);
- if (current == '/' && fCachedLineOffset <= offset && fDocument.getChar(offset) == '/') {
- fOffset= offset;
- return;
- }
- }
- }
- }
-
- private void gotoCommentStart() throws BadLocationException {
- while (0 < fOffset) {
- char current= fDocument.getChar(fOffset--);
- if (current == '*' && 0 <= fOffset && fDocument.getChar(fOffset) == '/')
- return;
- }
- }
-
- private void gotoStringStart(char delimiter) throws BadLocationException {
- while (0 < fOffset) {
- char current= fDocument.getChar(fOffset);
- if (current == delimiter) {
- if ( !(0 <= fOffset && fDocument.getChar(fOffset -1) == '\\'))
- return;
- }
- -- fOffset;
- }
- }
-
- private int readBackwards() throws BadLocationException {
-
- while (0 < fOffset) {
- -- fOffset;
-
- handleSingleLineComment();
-
- char current= fDocument.getChar(fOffset);
- switch (current) {
- case '/':
-
- if (fSkipComments && fOffset > 1) {
- char next= fDocument.getChar(fOffset - 1);
- if (next == '*') {
- // a comment ends, advance to the comment start
- fOffset -= 2;
- gotoCommentStart();
- continue;
- }
- }
-
- return current;
-
- case '"':
- case '\'':
-
- if (fSkipStrings) {
- -- fOffset;
- gotoStringStart(current);
- continue;
- }
-
- return current;
- }
-
- return current;
- }
-
- return EOF;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java
deleted file mode 100644
index 5adc3e24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IColorManagerExtension;
-
-/**
- * Java color manager.
- */
-public class JavaColorManager implements IColorManager, IColorManagerExtension {
-
- protected Map fKeyTable= new HashMap(10);
- protected Map fDisplayTable= new HashMap(2);
-
- /**
- * Flag which tells if the colors are automatically disposed when
- * the current display gets disposed.
- */
- private boolean fAutoDisposeOnDisplayDispose;
-
-
- /**
- * Creates a new Java color manager which automatically
- * disposes the allocated colors when the current display
- * gets disposed.
- */
- public JavaColorManager() {
- this(true);
- }
-
- /**
- * Creates a new Java color manager.
- *
- * @param autoDisposeOnDisplayDispose if <code>true</code> the color manager
- * automatically disposes all managed colors when the current display gets disposed
- * and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()} are ignored.
- *
- *
- */
- public JavaColorManager(boolean autoDisposeOnDisplayDispose) {
- fAutoDisposeOnDisplayDispose= autoDisposeOnDisplayDispose;
- }
-
- public void dispose(Display display) {
- Map colorTable= (Map) fDisplayTable.get(display);
- if (colorTable != null) {
- Iterator e= colorTable.values().iterator();
- while (e.hasNext()) {
- Color color= (Color)e.next();
- if (color != null && !color.isDisposed())
- color.dispose();
- }
- }
- }
-
- /*
- * @see IColorManager#getColor(RGB)
- */
- public Color getColor(RGB rgb) {
-
- if (rgb == null)
- return null;
-
- final Display display= Display.getCurrent();
- Map colorTable= (Map) fDisplayTable.get(display);
- if (colorTable == null) {
- colorTable= new HashMap(10);
- fDisplayTable.put(display, colorTable);
- if (fAutoDisposeOnDisplayDispose) {
- display.disposeExec(new Runnable() {
- public void run() {
- dispose(display);
- }
- });
- }
- }
-
- Color color= (Color) colorTable.get(rgb);
- if (color == null) {
- color= new Color(Display.getCurrent(), rgb);
- colorTable.put(rgb, color);
- }
-
- return color;
- }
-
- /*
- * @see IColorManager#dispose
- */
- public void dispose() {
- if (!fAutoDisposeOnDisplayDispose)
- dispose(Display.getCurrent());
- }
-
- /*
- * @see IColorManager#getColor(String)
- */
- public Color getColor(String key) {
-
- if (key == null)
- return null;
-
- RGB rgb= (RGB) fKeyTable.get(key);
- return getColor(rgb);
- }
-
- /*
- * @see IColorManagerExtension#bindColor(String, RGB)
- */
- public void bindColor(String key, RGB rgb) {
- Object value= fKeyTable.get(key);
- if (value != null)
- throw new UnsupportedOperationException();
-
- fKeyTable.put(key, rgb);
- }
-
- /*
- * @see IColorManagerExtension#unbindColor(String)
- */
- public void unbindColor(String key) {
- fKeyTable.remove(key);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCommentScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCommentScanner.java
deleted file mode 100644
index e74b324a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCommentScanner.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Michel Ishizuka <cqw10305@nifty.com> - Bug 113266 [syntax highlighting] javadoc tag names including period is not highlighting correctly
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.IWordDetector;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants;
-
-/**
- * AbstractJavaCommentScanner.java
- */
-public class JavaCommentScanner extends AbstractJavaScanner{
-
- private static class AtJavaIdentifierDetector implements IWordDetector {
-
- public boolean isWordStart(char c) {
- return c == '@' || Character.isJavaIdentifierStart(c);
- }
-
- public boolean isWordPart(char c) {
- return c == '.' || Character.isJavaIdentifierPart(c);
- }
- }
-
- private class TaskTagMatcher extends CombinedWordRule.WordMatcher {
-
- private IToken fToken;
- /**
- * Uppercase words
- *
- */
- private Map fUppercaseWords= new HashMap();
- /**
- * <code>true</code> if task tag detection is case-sensitive.
- *
- */
- private boolean fCaseSensitive= true;
- /**
- * Buffer for uppercase word
- *
- */
- private CombinedWordRule.CharacterBuffer fBuffer= new CombinedWordRule.CharacterBuffer(16);
-
- public TaskTagMatcher(IToken token) {
- fToken= token;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher#clearWords()
- *
- */
- public synchronized void clearWords() {
- super.clearWords();
- fUppercaseWords.clear();
- }
-
- public synchronized void addTaskTags(String value) {
- String[] tasks= split(value, ","); //$NON-NLS-1$
- for (int i= 0; i < tasks.length; i++) {
- if (tasks[i].length() > 0) {
- addWord(tasks[i], fToken);
- }
- }
- }
-
- private String[] split(String value, String delimiters) {
- StringTokenizer tokenizer= new StringTokenizer(value, delimiters);
- int size= tokenizer.countTokens();
- String[] tokens= new String[size];
- int i= 0;
- while (i < size)
- tokens[i++]= tokenizer.nextToken();
- return tokens;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher#addWord(java.lang.String, org.eclipse.jface.text.rules.IToken)
- *
- */
- public synchronized void addWord(String word, IToken token) {
- Assert.isNotNull(word);
- Assert.isNotNull(token);
-
- super.addWord(word, token);
- fUppercaseWords.put(new CombinedWordRule.CharacterBuffer(word.toUpperCase()), token);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher#evaluate(org.eclipse.jface.text.rules.ICharacterScanner, org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.CharacterBuffer)
- *
- */
- public synchronized IToken evaluate(ICharacterScanner scanner, CombinedWordRule.CharacterBuffer word) {
- if (fCaseSensitive)
- return super.evaluate(scanner, word);
-
- fBuffer.clear();
- for (int i= 0, n= word.length(); i < n; i++)
- fBuffer.append(Character.toUpperCase(word.charAt(i)));
-
- IToken token= (IToken) fUppercaseWords.get(fBuffer);
- if (token != null)
- return token;
- return Token.UNDEFINED;
- }
-
- /**
- * Is task tag detection case-senstive?
- *
- * @return <code>true</code> iff task tag detection is case-sensitive
- *
- */
- public boolean isCaseSensitive() {
- return fCaseSensitive;
- }
-
- /**
- * Enables/disables the case-sensitivity of the task tag detection.
- *
- * @param caseSensitive <code>true</code> iff case-sensitivity should be enabled
- *
- */
- public void setCaseSensitive(boolean caseSensitive) {
- fCaseSensitive= caseSensitive;
- }
- }
-
- private static final String COMPILER_TASK_TAGS= JavaScriptCore.COMPILER_TASK_TAGS;
- protected static final String TASK_TAG= IJavaScriptColorConstants.TASK_TAG;
- /**
- * Preference key of a string preference, specifying if task tag detection is case-sensitive.
- *
- */
- private static final String COMPILER_TASK_CASE_SENSITIVE= JavaScriptCore.COMPILER_TASK_CASE_SENSITIVE;
- /**
- * Preference value of enabled preferences.
- *
- */
- private static final String ENABLED= JavaScriptCore.ENABLED;
-
- private TaskTagMatcher fTaskTagMatcher;
- private Preferences fCorePreferenceStore;
- private String fDefaultTokenProperty;
- private String[] fTokenProperties;
-
- public JavaCommentScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore, String defaultTokenProperty) {
- this(manager, store, coreStore, defaultTokenProperty, new String[] { defaultTokenProperty, TASK_TAG });
- }
-
- public JavaCommentScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore, String defaultTokenProperty, String[] tokenProperties) {
- super(manager, store);
-
- fCorePreferenceStore= coreStore;
- fDefaultTokenProperty= defaultTokenProperty;
- fTokenProperties= tokenProperties;
-
- initialize();
- }
-
- /**
- * Initialize with the given arguments.
- *
- * @param manager Color manager
- * @param store Preference store
- * @param defaultTokenProperty Default token property
- *
- *
- */
- public JavaCommentScanner(IColorManager manager, IPreferenceStore store, String defaultTokenProperty) {
- this(manager, store, null, defaultTokenProperty, new String[] { defaultTokenProperty, TASK_TAG });
- }
-
- /**
- * Initialize with the given arguments.
- *
- * @param manager Color manager
- * @param store Preference store
- * @param defaultTokenProperty Default token property
- * @param tokenProperties Token properties
- *
- *
- */
- public JavaCommentScanner(IColorManager manager, IPreferenceStore store, String defaultTokenProperty, String[] tokenProperties) {
- this(manager, store, null, defaultTokenProperty, tokenProperties);
- }
-
- /*
- * @see AbstractJavaScanner#createRules()
- */
- protected List createRules() {
- List list= new ArrayList();
- Token defaultToken= getToken(fDefaultTokenProperty);
-
- List matchers= createMatchers();
- if (matchers.size() > 0) {
- CombinedWordRule combinedWordRule= new CombinedWordRule(new AtJavaIdentifierDetector(), defaultToken);
- for (int i= 0, n= matchers.size(); i < n; i++)
- combinedWordRule.addWordMatcher((WordMatcher) matchers.get(i));
- list.add(combinedWordRule);
- }
-
- setDefaultReturnToken(defaultToken);
-
- return list;
- }
-
- /**
- * Creates a list of word matchers.
- *
- * @return the list of word matchers
- */
- protected List createMatchers() {
- List list= new ArrayList();
-
- // Add rule for Task Tags.
- boolean isCaseSensitive= true;
- String tasks= null;
- if (getPreferenceStore().contains(COMPILER_TASK_TAGS)) {
- tasks= getPreferenceStore().getString(COMPILER_TASK_TAGS);
- isCaseSensitive= ENABLED.equals(getPreferenceStore().getString(COMPILER_TASK_CASE_SENSITIVE));
- } else if (fCorePreferenceStore != null) {
- tasks= fCorePreferenceStore.getString(COMPILER_TASK_TAGS);
- isCaseSensitive= ENABLED.equals(fCorePreferenceStore.getString(COMPILER_TASK_CASE_SENSITIVE));
- }
- if (tasks != null) {
- fTaskTagMatcher= new TaskTagMatcher(getToken(TASK_TAG));
- fTaskTagMatcher.addTaskTags(tasks);
- fTaskTagMatcher.setCaseSensitive(isCaseSensitive);
- list.add(fTaskTagMatcher);
- }
-
- return list;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#affectsBehavior(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public boolean affectsBehavior(PropertyChangeEvent event) {
- return event.getProperty().equals(COMPILER_TASK_TAGS) || event.getProperty().equals(COMPILER_TASK_CASE_SENSITIVE) || super.affectsBehavior(event);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#adaptToPreferenceChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- public void adaptToPreferenceChange(PropertyChangeEvent event) {
- if (fTaskTagMatcher != null && event.getProperty().equals(COMPILER_TASK_TAGS)) {
- Object value= event.getNewValue();
- if (value instanceof String) {
- synchronized (fTaskTagMatcher) {
- fTaskTagMatcher.clearWords();
- fTaskTagMatcher.addTaskTags((String) value);
- }
- }
- } else if (fTaskTagMatcher != null && event.getProperty().equals(COMPILER_TASK_CASE_SENSITIVE)) {
- Object value= event.getNewValue();
- if (value instanceof String)
- fTaskTagMatcher.setCaseSensitive(ENABLED.equals(value));
- } else if (super.affectsBehavior(event))
- super.adaptToPreferenceChange(event);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#getTokenProperties()
- */
- protected String[] getTokenProperties() {
- return fTokenProperties;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCompositeReconcilingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCompositeReconcilingStrategy.java
deleted file mode 100644
index 009efdbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaCompositeReconcilingStrategy.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.reconciler.DirtyRegion;
-import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.IProblemRequestorExtension;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaReconcilingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.spelling.JavaSpellingReconcileStrategy;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Reconciling strategy for Java code. This is a composite strategy containing the
- * regular java model reconciler and the comment spelling strategy.
- */
-public class JavaCompositeReconcilingStrategy extends CompositeReconcilingStrategy {
-
- private ITextEditor fEditor;
- private JavaReconcilingStrategy fJavaStrategy;
-
- /**
- * Creates a new Java reconciling strategy.
- *
- * @param viewer the source viewer
- * @param editor the editor of the strategy's reconciler
- * @param documentPartitioning the document partitioning this strategy uses for configuration
- */
- public JavaCompositeReconcilingStrategy(ISourceViewer viewer, ITextEditor editor, String documentPartitioning) {
- fEditor= editor;
- fJavaStrategy= new JavaReconcilingStrategy(editor);
- setReconcilingStrategies(new IReconcilingStrategy[] {
- fJavaStrategy,
- new JavaSpellingReconcileStrategy(viewer, EditorsUI.getSpellingService(), IJavaScriptPartitions.JAVA_PARTITIONING)
- });
- }
-
- /**
- * Returns the problem requestor for the editor's input element.
- *
- * @return the problem requestor for the editor's input element
- */
- private IProblemRequestorExtension getProblemRequestorExtension() {
- IDocumentProvider p= fEditor.getDocumentProvider();
- if (p == null) {
- // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522
- p= JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider();
- }
- IAnnotationModel m= p.getAnnotationModel(fEditor.getEditorInput());
- if (m instanceof IProblemRequestorExtension)
- return (IProblemRequestorExtension) m;
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion)
- */
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- IProblemRequestorExtension e= getProblemRequestorExtension();
- if (e != null) {
- try {
- e.beginReportingSequence();
- super.reconcile(dirtyRegion, subRegion);
- } finally {
- e.endReportingSequence();
- }
- } else {
- super.reconcile(dirtyRegion, subRegion);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
- */
- public void reconcile(IRegion partition) {
- IProblemRequestorExtension e= getProblemRequestorExtension();
- if (e != null) {
- try {
- e.beginReportingSequence();
- super.reconcile(partition);
- } finally {
- e.endReportingSequence();
- }
- } else {
- super.reconcile(partition);
- }
- }
-
- /**
- * Tells this strategy whether to inform its listeners.
- *
- * @param notify <code>true</code> if listeners should be notified
- */
- public void notifyListeners(boolean notify) {
- fJavaStrategy.notifyListeners(notify);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#initialReconcile()
- */
- public void initialReconcile() {
- IProblemRequestorExtension e= getProblemRequestorExtension();
- if (e != null) {
- try {
- e.beginReportingSequence();
- super.initialReconcile();
- } finally {
- e.endReportingSequence();
- }
- } else {
- super.initialReconcile();
- }
- }
-
- /**
- * Called before reconciling is started.
- *
- *
- */
- public void aboutToBeReconciled() {
- fJavaStrategy.aboutToBeReconciled();
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaElementProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaElementProvider.java
deleted file mode 100644
index 0f4e1800..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaElementProvider.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.information.IInformationProvider;
-import org.eclipse.jface.text.information.IInformationProviderExtension;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/**
- * Provides a Java element to be displayed in by an information presenter.
- */
-public class JavaElementProvider implements IInformationProvider, IInformationProviderExtension {
-
- private JavaEditor fEditor;
- private boolean fUseCodeResolve;
-
- public JavaElementProvider(IEditorPart editor) {
- fUseCodeResolve= false;
- if (editor instanceof JavaEditor)
- fEditor= (JavaEditor)editor;
- }
-
- public JavaElementProvider(IEditorPart editor, boolean useCodeResolve) {
- this(editor);
- fUseCodeResolve= useCodeResolve;
- }
-
- /*
- * @see IInformationProvider#getSubject(ITextViewer, int)
- */
- public IRegion getSubject(ITextViewer textViewer, int offset) {
- if (textViewer != null && fEditor != null) {
- IRegion region= JavaWordFinder.findWord(textViewer.getDocument(), offset);
- if (region != null)
- return region;
- else
- return new Region(offset, 0);
- }
- return null;
- }
-
- /*
- * @see IInformationProvider#getInformation(ITextViewer, IRegion)
- */
- public String getInformation(ITextViewer textViewer, IRegion subject) {
- return getInformation2(textViewer, subject).toString();
- }
-
- /*
- * @see IInformationProviderExtension#getElement(ITextViewer, IRegion)
- */
- public Object getInformation2(ITextViewer textViewer, IRegion subject) {
- if (fEditor == null)
- return null;
-
- try {
- if (fUseCodeResolve) {
- IStructuredSelection sel= SelectionConverter.getStructuredSelection(fEditor);
- if (!sel.isEmpty())
- return sel.getFirstElement();
- }
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element != null)
- return element;
-
- return EditorUtility.getEditorInputJavaElement(fEditor, false);
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaHeuristicScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaHeuristicScanner.java
deleted file mode 100644
index 2ca59a9f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaHeuristicScanner.java
+++ /dev/null
@@ -1,950 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.TypedRegion;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Utility methods for heuristic based Java manipulations in an incomplete Java source file.
- *
- * <p>An instance holds some internal position in the document and is therefore not threadsafe.</p>
- *
- *
- */
-public final class JavaHeuristicScanner implements Symbols {
- /**
- * 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= '>';
-
- /**
- * 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.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
- */
- public boolean stop(char ch, int position, boolean forward) {
- return !Character.isWhitespace(ch);
- }
- }
-
- /**
- * Stops upon a non-whitespace character in the default partition.
- *
- * @see JavaHeuristicScanner.NonWhitespace
- */
- private final class NonWhitespaceDefaultPartition extends NonWhitespace {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
- */
- public boolean stop(char ch, int position, boolean forward) {
- return super.stop(ch, position, true) && isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- 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.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
- */
- 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 JavaHeuristicScanner.NonJavaIdentifierPart
- */
- private final class NonJavaIdentifierPartDefaultPartition extends NonJavaIdentifierPart {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
- */
- public boolean stop(char ch, int position, boolean forward) {
- return super.stop(ch, position, true) || !isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- 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.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, int)
- */
- public boolean stop(char ch, int position, boolean forward) {
- return Arrays.binarySearch(fChars, ch) >= 0 && isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- 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 final static 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 JavaHeuristicScanner(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, IJavaScriptPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
- *
- * @param document the document to scan.
- */
- public JavaHeuristicScanner(IDocument document) {
- this(document, IJavaScriptPartitions.JAVA_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 Symbols}.
- * 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 Symbols} describing the next token
- */
- public int nextToken(int start, int bound) {
- int pos= scanForward(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 COMMA:
- return TokenCOMMA;
- case QUESTIONMARK:
- return TokenQUESTIONMARK;
- case EQUAL:
- return TokenEQUAL;
- case LANGLE:
- return TokenLESSTHAN;
- case RANGLE:
- return TokenGREATERTHAN;
- }
-
- // 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);
-
-
- } else {
- // 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 Symbols}.
- * 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 Symbols} 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:
- return TokenCOLON;
- case COMMA:
- return TokenCOMMA;
- case QUESTIONMARK:
- return TokenQUESTIONMARK;
- case EQUAL:
- return TokenEQUAL;
- case LANGLE:
- return TokenLESSTHAN;
- case RANGLE:
- return TokenGREATERTHAN;
- }
-
- // 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);
-
-
- } else {
- // operators, number literals etc
- return TokenOTHER;
- }
-
- }
-
- /**
- * 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 Symbols}
- */
- 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 ("while".equals(s)) //$NON-NLS-1$
- return TokenWHILE;
- break;
- case 6:
- if ("return".equals(s)) //$NON-NLS-1$
- return TokenRETURN;
- if ("static".equals(s)) //$NON-NLS-1$
- return TokenSTATIC;
- if ("switch".equals(s)) //$NON-NLS-1$
- return TokenSWITCH;
- break;
- case 7:
- if ("default".equals(s)) //$NON-NLS-1$
- return TokenDEFAULT;
- if ("finally".equals(s)) //$NON-NLS-1$
- return TokenFINALLY;
- break;
- case 9:
- if ("interface".equals(s)) //$NON-NLS-1$
- return TokenINTERFACE;
- break;
- case 12:
- if ("synchronized".equals(s)) //$NON-NLS-1$
- return TokenSYNCHRONIZED;
- break;
- }
- 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>
- */
- public int findClosingPeer(int start, int bound, final char openingPeer, final char closingPeer) {
- Assert.isLegal(start >= 0);
-
- try {
- CharacterMatch match= new CharacterMatch(new char[] {openingPeer, closingPeer});
- int depth= 1;
- start -= 1;
- while (true) {
- start= scanForward(start + 1, bound, match);
- 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, 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;
- }
- }
-
- /**
- * Computes the surrounding block around <code>offset</code>. The search is started at the
- * beginning of <code>offset</code>, i.e. an opening brace at <code>offset</code> will not be
- * part of the surrounding block, but a closing brace will.
- *
- * @param offset the offset for which the surrounding block is computed
- * @return a region describing the surrounding block, or <code>null</code> if none can be found
- */
- public IRegion findSurroundingBlock(int offset) {
- if (offset < 1 || offset >= fDocument.getLength())
- return null;
-
- int begin= findOpeningPeer(offset - 1, LBRACE, RBRACE);
- int end= findClosingPeer(offset, LBRACE, RBRACE);
- if (begin == NOT_FOUND || end == NOT_FOUND)
- return null;
- return new Region(begin, end + 1 - begin);
- }
-
- /**
- * 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>
- * 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>
- * @return the smallest position of a non-whitespace character in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int findNonWhitespaceForward(int position, int bound) {
- return scanForward(position, bound, fNonWSDefaultPart);
- }
-
- /**
- * 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 Java 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
- */
- public 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 Java 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 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> for at least one
- * ch in <code>chars</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 chars an array of <code>char</code> to search for
- * @return the lowest position of a non-whitespace character in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int scanForward(int position, int bound, char[] chars) {
- return scanForward(position, bound, new CharacterMatch(chars));
- }
-
- /**
- * 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
- */
- public 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;
- }
-
- /**
- * Finds the highest position in <code>fDocument</code> such that the position is &lt;= <code>position</code>
- * and &gt; <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
- * ch in <code>chars</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>
- * @param ch the <code>char</code> to search for
- * @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int scanBackward(int position, int bound, char ch) {
- return scanBackward(position, bound, new CharacterMatch(ch));
- }
-
- /**
- * Finds the highest position in <code>fDocument</code> such that the position is &lt;= <code>position</code>
- * and &gt; <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
- * ch in <code>chars</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>
- * @param chars an array of <code>char</code> to search for
- * @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int scanBackward(int position, int bound, char[] chars) {
- return scanBackward(position, bound, new CharacterMatch(chars));
- }
-
- /**
- * Checks whether <code>position</code> resides in a default (Java) 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
- */
- public boolean isDefaultPartition(int position) {
- return fPartition.equals(getPartition(position).getType());
- }
-
- /**
- * 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, LPAREN, RPAREN);
- if (position > 0) {
- switch (previousToken(position - 1, bound)) {
- case TokenIF:
- case TokenFOR:
- case TokenWHILE:
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns <code>true</code> if the document, when scanned backwards from <code>start</code>
- * appears to contain a class instance creation, i.e. a possibly qualified name preceded by a
- * <code>new</code> keyword. The <code>start</code> must be at the end of the type name, and
- * before any generic signature or constructor parameter list. The heuristic will return
- * <code>true</code> if <code>start</code> is at the following positions (|):
- *
- * <pre>
- * new java.util. ArrayList|&lt;String&gt;(10)
- * new ArrayList |(10)
- * new / * comment * / ArrayList |(10)
- * </pre>
- *
- * but not the following:
- *
- * <pre>
- * new java.util. ArrayList&lt;String&gt;(10)|
- * new java.util. ArrayList&lt;String&gt;|(10)
- * new ArrayList (10)|
- * ArrayList |(10)
- * </pre>
- *
- * @param start the position where the type name of the class instance creation supposedly ends
- * @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 after the type name of a class
- * instance creation
- *
- */
- public boolean looksLikeClassInstanceCreationBackward(int start, int bound) {
- int token= previousToken(start - 1, bound);
- if (token == Symbols.TokenIDENT) { // type name
- token= previousToken(getPosition(), bound);
- while (token == Symbols.TokenOTHER) { // dot of qualification
- token= previousToken(getPosition(), bound);
- if (token != Symbols.TokenIDENT) // qualification name
- return false;
- token= previousToken(getPosition(), bound);
- }
- return token == Symbols.TokenNEW;
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if <code>identifier</code> is probably a
- * type variable or type name, <code>false</code> if it is rather not.
- * This is a heuristic.
- *
- * @param identifier the identifier to check
- * @return <code>true</code> if <code>identifier</code> is probably a
- * type variable or type name, <code>false</code> if not
- *
- */
- public static boolean isGenericStarter(CharSequence identifier) {
- /* This heuristic allows any identifiers if they start with an upper
- * case. This will fail when a comparison is made with constants:
- *
- * if (MAX > foo)
- *
- * will try to find the matching '<' which will never come
- *
- * Also, it will fail on lower case types and type variables
- */
- int length= identifier.length();
- if (length > 0 && Character.isUpperCase(identifier.charAt(0))) {
- for (int i= 0; i < length; i++) {
- if (identifier.charAt(i) == '_')
- return false;
- }
- return true;
- }
- return false;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaIndenter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaIndenter.java
deleted file mode 100644
index 62dda75c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaIndenter.java
+++ /dev/null
@@ -1,1649 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-
-
-/**
- * Uses the {@link org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner} to
- * get the indentation level for a certain position in a document.
- *
- * <p>
- * An instance holds some internal position in the document and is therefore
- * not threadsafe.
- * </p>
- *
- *
- */
-public final class JavaIndenter {
-
- /**
- * The JDT Core preferences.
- *
- */
- private final class CorePrefs {
- final boolean prefUseTabs;
- final int prefTabSize;
- final int prefIndentationSize;
- final boolean prefArrayDimensionsDeepIndent;
- final int prefArrayIndent;
- final boolean prefArrayDeepIndent;
- final boolean prefTernaryDeepAlign;
- final int prefTernaryIndent;
- final int prefCaseIndent;
- final int prefAssignmentIndent;
- final int prefCaseBlockIndent;
- final int prefSimpleIndent;
- final int prefBracketIndent;
- final boolean prefMethodDeclDeepIndent;
- final int prefMethodDeclIndent;
- final boolean prefMethodCallDeepIndent;
- final int prefMethodCallIndent;
- final boolean prefParenthesisDeepIndent;
- final int prefParenthesisIndent;
- final int prefBlockIndent;
- final int prefMethodBodyIndent;
- final int prefTypeIndent;
- final boolean prefIndentBracesForBlocks;
- final boolean prefIndentBracesForArrays;
- final boolean prefIndentBracesForMethods;
- final boolean prefIndentBracesForTypes;
- final int prefContinuationIndent;
- final boolean prefHasGenerics;
- final String prefTabChar;
-
- private final IJavaScriptProject fProject;
-
- /**
- * Returns <code>true</code> if the class is used outside the workbench,
- * <code>false</code> in normal mode
- *
- * @return <code>true</code> if the plug-ins are not available
- */
- private boolean isStandalone() {
- return JavaScriptCore.getPlugin() == null;
- }
-
- /**
- * 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) {
- if (fProject == null)
- return JavaScriptCore.getOption(key);
- return fProject.getOption(key, true);
- }
-
- CorePrefs(IJavaScriptProject project) {
- fProject= project;
- if (isStandalone()) {
- prefUseTabs= true;
- prefTabSize= 4;
- prefIndentationSize= 4;
- prefArrayDimensionsDeepIndent= true;
- prefContinuationIndent= 2;
- prefBlockIndent= 1;
- prefArrayIndent= prefContinuationIndent;
- prefArrayDeepIndent= true;
- prefTernaryDeepAlign= false;
- prefTernaryIndent= prefContinuationIndent;
- prefCaseIndent= 0;
- prefAssignmentIndent= prefBlockIndent;
- prefCaseBlockIndent= prefBlockIndent;
- prefIndentBracesForBlocks= false;
- prefSimpleIndent= (prefIndentBracesForBlocks && prefBlockIndent == 0) ? 1 : prefBlockIndent;
- prefBracketIndent= prefBlockIndent;
- prefMethodDeclDeepIndent= true;
- prefMethodDeclIndent= 1;
- prefMethodCallDeepIndent= false;
- prefMethodCallIndent= 1;
- prefParenthesisDeepIndent= false;
- prefParenthesisIndent= prefContinuationIndent;
- prefMethodBodyIndent= 1;
- prefTypeIndent= 1;
- prefIndentBracesForArrays= false;
- prefIndentBracesForMethods= false;
- prefIndentBracesForTypes= false;
- prefHasGenerics= false;
- prefTabChar= JavaScriptCore.TAB;
- } else {
- prefUseTabs= prefUseTabs();
- prefTabSize= prefTabSize();
- prefIndentationSize= prefIndentationSize();
- prefArrayDimensionsDeepIndent= prefArrayDimensionsDeepIndent();
- prefContinuationIndent= prefContinuationIndent();
- prefBlockIndent= prefBlockIndent();
- prefArrayIndent= prefArrayIndent();
- prefArrayDeepIndent= prefArrayDeepIndent();
- prefTernaryDeepAlign= prefTernaryDeepAlign();
- prefTernaryIndent= prefTernaryIndent();
- prefCaseIndent= prefCaseIndent();
- prefAssignmentIndent= prefAssignmentIndent();
- prefCaseBlockIndent= prefCaseBlockIndent();
- prefIndentBracesForBlocks= prefIndentBracesForBlocks();
- prefSimpleIndent= prefSimpleIndent();
- prefBracketIndent= prefBracketIndent();
- prefMethodDeclDeepIndent= prefMethodDeclDeepIndent();
- prefMethodDeclIndent= prefMethodDeclIndent();
- prefMethodCallDeepIndent= prefMethodCallDeepIndent();
- prefMethodCallIndent= prefMethodCallIndent();
- prefParenthesisDeepIndent= prefParenthesisDeepIndent();
- prefParenthesisIndent= prefParenthesisIndent();
- prefMethodBodyIndent= prefMethodBodyIndent();
- prefTypeIndent= prefTypeIndent();
- prefIndentBracesForArrays= prefIndentBracesForArrays();
- prefIndentBracesForMethods= prefIndentBracesForMethods();
- prefIndentBracesForTypes= prefIndentBracesForTypes();
- prefHasGenerics= hasGenerics();
- prefTabChar= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- }
- }
-
- private boolean prefUseTabs() {
- return !JavaScriptCore.SPACE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
- }
-
- private int prefTabSize() {
- return CodeFormatterUtil.getTabWidth(fProject);
- }
-
- private int prefIndentationSize() {
- return CodeFormatterUtil.getIndentWidth(fProject);
- }
-
- private boolean prefArrayDimensionsDeepIndent() {
- return true; // sensible default, no formatter setting
- }
-
- private int prefArrayIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
- try {
- if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return prefContinuationIndent(); // default
- }
-
- private boolean prefArrayDeepIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
- try {
- return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return true;
- }
-
- private boolean prefTernaryDeepAlign() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
- try {
- return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return false;
- }
-
- private int prefTernaryIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
- try {
- if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- else
- return prefContinuationIndent();
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return prefContinuationIndent();
- }
-
- private int prefCaseIndent() {
- if (DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
- return prefBlockIndent();
- else
- return 0;
- }
-
- private int prefAssignmentIndent() {
- return prefBlockIndent();
- }
-
- private int prefCaseBlockIndent() {
- if (true)
- return prefBlockIndent();
-
- if (DefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
- return prefBlockIndent();
- else
- return 0;
- }
-
- private int prefSimpleIndent() {
- if (prefIndentBracesForBlocks() && prefBlockIndent() == 0)
- return 1;
- else return prefBlockIndent();
- }
-
- private int prefBracketIndent() {
- return prefBlockIndent();
- }
-
- private boolean prefMethodDeclDeepIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- try {
- return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return true;
- }
-
- private int prefMethodDeclIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- try {
- if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- else
- return prefContinuationIndent();
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return 1;
- }
-
- private boolean prefMethodCallDeepIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- try {
- return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return false; // sensible default
- }
-
- private int prefMethodCallIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- try {
- if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- else
- return prefContinuationIndent();
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return 1; // sensible default
- }
-
- private boolean prefParenthesisDeepIndent() {
- if (true) // don't do parenthesis deep indentation
- return false;
-
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
- try {
- return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return false; // sensible default
- }
-
- private int prefParenthesisIndent() {
- return prefContinuationIndent();
- }
-
- private int prefBlockIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
- if (DefaultCodeFormatterConstants.FALSE.equals(option))
- return 0;
-
- return 1; // sensible default
- }
-
- private int prefMethodBodyIndent() {
- if (DefaultCodeFormatterConstants.FALSE.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY)))
- return 0;
-
- return 1; // sensible default
- }
-
- private int prefTypeIndent() {
- String option= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER);
- if (DefaultCodeFormatterConstants.FALSE.equals(option))
- return 0;
-
- return 1; // sensible default
- }
-
- private boolean prefIndentBracesForBlocks() {
- return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK));
- }
-
- private boolean prefIndentBracesForArrays() {
- return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER));
- }
-
- private boolean prefIndentBracesForMethods() {
- return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION));
- }
-
- private boolean prefIndentBracesForTypes() {
- return DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION));
- }
-
- private int prefContinuationIndent() {
- try {
- return Integer.parseInt(getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION));
- } catch (NumberFormatException e) {
- // ignore and return default
- }
-
- return 2; // sensible default
- }
- private boolean hasGenerics() {
- return JavaScriptCore.VERSION_1_5.compareTo(getCoreFormatterOption(JavaScriptCore.COMPILER_SOURCE)) <= 0;
- }
- }
-
- /** The document being scanned. */
- private final IDocument fDocument;
- /** The indentation accumulated by <code>findReferencePosition</code>. */
- private int fIndent;
- /**
- * The absolute (character-counted) indentation offset for special cases
- * (method defs, array initializers)
- */
- private int fAlign;
- /** The stateful scanposition 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 JavaHeuristicScanner fScanner;
- /**
- * The JDT Core preferences.
- *
- */
- private final CorePrefs fPrefs;
-
- /**
- * Creates a new instance.
- *
- * @param document the document to scan
- * @param scanner the {@link JavaHeuristicScanner} to be used for scanning
- * the document. It must be installed on the same <code>IDocument</code>.
- */
- public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) {
- this(document, scanner, null);
- }
-
- /**
- * Creates a new instance.
- *
- * @param document the document to scan
- * @param scanner the {@link JavaHeuristicScanner}to be used for scanning
- * the document. It must be installed on the same
- * <code>IDocument</code>.
- * @param project the java project to get the formatter preferences from, or
- * <code>null</code> to use the workspace settings
- *
- */
- public JavaIndenter(IDocument document, JavaHeuristicScanner scanner, IJavaScriptProject 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 StringBuffer 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 StringBuffer getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
-
- int unit;
- if (assumeOpeningBrace)
- unit= findReferencePosition(offset, Symbols.TokenLBRACE);
- else
- unit= findReferencePosition(offset, peekChar(offset));
-
- // if we were unable to find anything, return null
- if (unit == JavaHeuristicScanner.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 StringBuffer 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 StringBuffer computeIndentation(int offset, boolean assumeOpeningBrace) {
-
- StringBuffer reference= getReferenceIndentation(offset, assumeOpeningBrace);
-
- // handle special alignment
- if (fAlign != JavaHeuristicScanner.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);
- }
-
- /**
- * 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= fPrefs.prefTabSize;
- 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 StringBuffer stripExceedingChars(StringBuffer reference, int indentLength) {
- final int tabSize= fPrefs.prefTabSize;
- 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>StringBuffer</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 StringBuffer getLeadingWhitespace(int offset) {
- StringBuffer indent= new StringBuffer();
- 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 StringBuffer createIndent(int start, final int indent, final boolean convertSpaceRunsToTabs) {
- final boolean convertTabs= fPrefs.prefUseTabs && convertSpaceRunsToTabs;
- final int tabLen= fPrefs.prefTabSize;
- final StringBuffer ret= new StringBuffer();
- 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
- * @return the modified <code>buffer</code> reflecting the indentation
- * adapted to <code>additional</code>
- */
- private StringBuffer createReusingIndent(StringBuffer buffer, int additional) {
- int refLength= computeVisualLength(buffer);
- int addLength= fPrefs.prefIndentationSize * additional; // 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= fPrefs.prefTabSize;
- int maxCopyLength= tabSize > 0 ? minLength - minLength % tabSize : minLength; // maximum indent to copy
- stripExceedingChars(buffer, maxCopyLength);
-
-
- // add additional indent
- int missing= totalLength - maxCopyLength;
- final int tabs, spaces;
- if (JavaScriptCore.SPACE.equals(fPrefs.prefTabChar)) {
- tabs= 0;
- spaces= missing;
- } else if (JavaScriptCore.TAB.equals(fPrefs.prefTabChar)) {
- tabs= tabSize > 0 ? missing / tabSize : 0;
- spaces= tabSize > 0 ? missing % tabSize : missing;
- } else if (DefaultCodeFormatterConstants.MIXED.equals(fPrefs.prefTabChar)) {
- tabs= tabSize > 0 ? missing / tabSize : 0;
- spaces= tabSize > 0 ? missing % tabSize : missing;
- } else {
- Assert.isTrue(false);
- return null;
- }
- for(int i= 0; i < tabs; i++)
- buffer.append('\t');
- for(int i= 0; i < spaces; i++)
- buffer.append(' ');
- return buffer;
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>offset</code>,
- * or <code>NOT_FOUND</code>. 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 JavaHeuristicScanner#NOT_FOUND}
- */
- public int findReferencePosition(int offset) {
- return findReferencePosition(offset, peekChar(offset));
- }
-
- /**
- * Peeks the next char 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 peekChar(int offset) {
- if (offset < fDocument.getLength()) {
- try {
- IRegion line= fDocument.getLineInformationOfOffset(offset);
- int lineOffset= line.getOffset();
- int next= fScanner.nextToken(offset, lineOffset + line.getLength());
- return next;
- } catch (BadLocationException e) {
- }
- }
- return Symbols.TokenEOF;
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>position</code>,
- * or <code>NOT_FOUND</code>.
- *
- * <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 JavaHeuristicScanner#NOT_FOUND}
- */
- public int findReferencePosition(int offset, int nextToken) {
- boolean danglingElse= false;
- boolean unindent= false;
- boolean indent= false;
- boolean matchBrace= false;
- boolean matchParen= false;
- boolean matchCase= false;
-
- // 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, JavaHeuristicScanner.UNBOUND);
- boolean bracelessBlockStart= fScanner.isBracelessBlockStart(prevPos, JavaHeuristicScanner.UNBOUND);
-
- switch (nextToken) {
- case Symbols.TokenELSE:
- danglingElse= true;
- break;
- case Symbols.TokenCASE:
- case Symbols.TokenDEFAULT:
- if (isFirstTokenOnLine)
- matchCase= true;
- break;
- case Symbols.TokenLBRACE: // for opening-brace-on-new-line style
- if (bracelessBlockStart && !fPrefs.prefIndentBracesForBlocks)
- unindent= true;
- else if ((prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && !fPrefs.prefIndentBracesForArrays)
- unindent= true;
- else if (!bracelessBlockStart && fPrefs.prefIndentBracesForMethods)
- indent= true;
- break;
- case Symbols.TokenRBRACE: // closing braces get unindented
- if (isFirstTokenOnLine)
- matchBrace= true;
- break;
- case Symbols.TokenRPAREN:
- if (isFirstTokenOnLine)
- matchParen= true;
- 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, matchBrace, matchParen, matchCase);
- if (unindent)
- fIndent--;
- if (indent)
- fIndent++;
- return ref;
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>position</code>,
- * or <code>NOT_FOUND</code>.<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 <code>JavaHeuristicScanner.NOT_FOUND</code>.
- *
- * @param offset the offset for which the reference is computed
- * @param danglingElse whether a dangling else should be assumed at <code>position</code>
- * @param matchBrace whether the position of the matching brace should be
- * returned instead of doing code analysis
- * @param matchParen whether the position of the matching parenthesis
- * should be returned instead of doing code analysis
- * @param matchCase whether the position of a switch statement reference
- * should be returned (either an earlier case statement or the
- * switch block brace)
- * @return the reference statement relative to which <code>position</code>
- * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
- */
- public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen, boolean matchCase) {
- fIndent= 0; // the indentation modification
- fAlign= JavaHeuristicScanner.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.
- if (matchBrace) {
- if (skipScope(Symbols.TokenLBRACE, Symbols.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().length() == 0)
- 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, false, matchParen, matchCase);
- fIndent--;
- return pos;
- }
- }
-
- // align parenthesis'
- if (matchParen) {
- if (skipScope(Symbols.TokenLPAREN, Symbols.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, matchBrace, false, matchCase);
- fIndent--;
- return pos;
- }
- }
-
- // 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
- if (matchCase) {
- return matchCaseAlignment();
- }
-
- nextToken();
- switch (fToken) {
- case Symbols.TokenGREATERTHAN:
- case Symbols.TokenRBRACKET:
- case Symbols.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;
- //$FALL-THROUGH$
- case Symbols.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 Symbols.TokenLPAREN:
- case Symbols.TokenLBRACE:
- case Symbols.TokenLBRACKET:
- return handleScopeIntroduction(offset + 1);
-
- case Symbols.TokenEOF:
- // trap when hitting start of document
- return JavaHeuristicScanner.NOT_FOUND;
-
- case Symbols.TokenEQUAL:
- // indent assignments
- fIndent= fPrefs.prefAssignmentIndent;
- return fPosition;
-
- case Symbols.TokenCOLON:
- // TODO handle ternary deep indentation
- fIndent= fPrefs.prefCaseBlockIndent;
- return fPosition;
-
- case Symbols.TokenQUESTIONMARK:
- if (fPrefs.prefTernaryDeepAlign) {
- setFirstElementAlignment(fPosition, offset + 1);
- return fPosition;
- } else {
- fIndent= fPrefs.prefTernaryIndent;
- return fPosition;
- }
-
- // indentation for blockless introducers:
- case Symbols.TokenDO:
- case Symbols.TokenWHILE:
- case Symbols.TokenELSE:
- fIndent= fPrefs.prefSimpleIndent;
- return fPosition;
-
- case Symbols.TokenTRY:
- return skipToStatementStart(danglingElse, false);
- case Symbols.TokenRPAREN:
- int line= fLine;
- if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) {
- int scope= fPosition;
- nextToken();
- if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
- fIndent= fPrefs.prefSimpleIndent;
- return fPosition;
- }
- fPosition= scope;
- if (looksLikeMethodDecl()) {
- return skipToStatementStart(danglingElse, false);
- }
- if (fToken == Symbols.TokenCATCH) {
- return skipToStatementStart(danglingElse, false);
- }
- fPosition= scope;
- if (looksLikeAnonymousTypeDecl()) {
- return skipToStatementStart(danglingElse, false);
- }
- }
- // restore
- fPosition= offset;
- fLine= line;
- // else: fall through to default
- //$FALL-THROUGH$
- case Symbols.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
- default:
- // inside whatever we don't know about: similar to the list case:
- // if we are inside a continued expression, then either align with a previous line that has indentation
- // or indent from the expression start line (either a scope introducer or the start of the expr).
- return skipToPreviousListItemOrListStart();
-
- }
- }
-
- /**
- * 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;
- while (true) {
- nextToken();
-
- if (isInBlock) {
- switch (fToken) {
- // exit on all block introducers
- case Symbols.TokenIF:
- case Symbols.TokenELSE:
- case Symbols.TokenCATCH:
- case Symbols.TokenDO:
- case Symbols.TokenWHILE:
- case Symbols.TokenFINALLY:
- case Symbols.TokenFOR:
- case Symbols.TokenTRY:
- case Symbols.TokenCOLON:
- return fPosition;
-
- case Symbols.TokenSTATIC:
- mayBeMethodBody= READ_IDENT; // treat static blocks like methods
- break;
-
- case Symbols.TokenSYNCHRONIZED:
- // if inside a method declaration, use body indentation
- // else use block indentation.
- if (mayBeMethodBody != READ_IDENT)
- return fPosition;
- break;
-
- case Symbols.TokenCLASS:
- case Symbols.TokenINTERFACE:
- case Symbols.TokenENUM:
- isTypeBody= true;
- break;
-
- case Symbols.TokenSWITCH:
- fIndent= fPrefs.prefCaseIndent;
- return fPosition;
- }
- }
-
- 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 Symbols.TokenLPAREN:
- case Symbols.TokenLBRACE:
- case Symbols.TokenLBRACKET:
- case Symbols.TokenSEMICOLON:
- case Symbols.TokenEOF:
- if (isInBlock)
- fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
- // else: fIndent set by previous calls
- return fPreviousPos;
-
- case Symbols.TokenCOLON:
- int pos= fPreviousPos;
- if (!isConditional())
- return pos;
- break;
-
- case Symbols.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() && looksLikeArrayInitializerIntro()) {
- continue; // it's an array
- } else {
- if (isInBlock)
- fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
- return pos; // it's not - do as with all the above
- }
-
- // scopes: skip them
- case Symbols.TokenRPAREN:
- if (isInBlock)
- mayBeMethodBody= READ_PARENS;
- //$FALL-THROUGH$
- case Symbols.TokenRBRACKET:
- case Symbols.TokenGREATERTHAN:
- 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 Symbols.TokenIF:
- if (danglingElse)
- return fPosition;
- else
- break;
- case Symbols.TokenELSE:
- // skip behind the next if, as we have that one covered
- pos= fPosition;
- if (skipNextIF())
- break;
- else
- return pos;
-
- case Symbols.TokenDO:
- // align the WHILE position with its do
- return fPosition;
-
- case Symbols.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 Symbols.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.prefIndentBracesForTypes ? 1 : 0);
- else if (isMethodBody)
- return fPrefs.prefMethodBodyIndent + (fPrefs.prefIndentBracesForMethods ? 1 : 0);
- else
- return fIndent;
- }
-
- /**
- * Returns true if the colon at the current position is part of a conditional
- * (ternary) expression, false otherwise.
- *
- * @return true if the colon at the current position is part of a conditional
- */
- private boolean isConditional() {
- while (true) {
- nextToken();
- switch (fToken) {
-
- // search for case labels, which consist of (possibly qualified) identifiers or numbers
- case Symbols.TokenIDENT:
- case Symbols.TokenOTHER: // dots for qualified constants
- continue;
- case Symbols.TokenCASE:
- 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 Symbols.TokenLPAREN:
- case Symbols.TokenLBRACKET:
- case Symbols.TokenEOF:
- return fPosition;
- case Symbols.TokenLBRACE:
- // opening brace of switch statement
- fIndent= fPrefs.prefCaseIndent;
- return fPosition;
- case Symbols.TokenCASE:
- case Symbols.TokenDEFAULT:
- // align with previous label
- fIndent= 0;
- return fPosition;
-
- // scopes: skip them
- case Symbols.TokenRPAREN:
- case Symbols.TokenRBRACKET:
- case Symbols.TokenRBRACE:
- case Symbols.TokenGREATERTHAN:
- 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)}.
- *
- * @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;
- while (true) {
- nextToken();
-
- // if any line item comes with its own indentation, adapt to it
- if (fLine < startLine) {
- try {
- int lineOffset= fDocument.getLineOffset(startLine);
- int bound= Math.min(fDocument.getLength(), startPosition + 1);
- fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, bound);
- } catch (BadLocationException e) {
- // ignore and return just the position
- }
- return startPosition;
- }
-
- switch (fToken) {
- // scopes: skip them
- case Symbols.TokenRPAREN:
- case Symbols.TokenRBRACKET:
- case Symbols.TokenRBRACE:
- case Symbols.TokenGREATERTHAN:
- skipScope();
- break;
-
- // scope introduction: special treat who special is
- case Symbols.TokenLPAREN:
- case Symbols.TokenLBRACE:
- case Symbols.TokenLBRACKET:
- return handleScopeIntroduction(startPosition + 1);
-
- case Symbols.TokenSEMICOLON:
- return fPosition;
- case Symbols.TokenQUESTIONMARK:
- if (fPrefs.prefTernaryDeepAlign) {
- setFirstElementAlignment(fPosition - 1, fPosition + 1);
- return fPosition;
- } else {
- fIndent= fPrefs.prefTernaryIndent;
- return fPosition;
- }
- case Symbols.TokenEOF:
- 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>Symbols.TokenRPAREN</code>, <code>Symbols.TokenRBRACE</code>,
- * and <code>Symbols.TokenRBRACKET</code>.
- *
- * @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
- */
- private boolean skipScope() {
- switch (fToken) {
- case Symbols.TokenRPAREN:
- return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN);
- case Symbols.TokenRBRACKET:
- return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET);
- case Symbols.TokenRBRACE:
- return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE);
- case Symbols.TokenGREATERTHAN:
- if (!fPrefs.prefHasGenerics)
- return false;
- int storedPosition= fPosition;
- int storedToken= fToken;
- nextToken();
- switch (fToken) {
- case Symbols.TokenIDENT:
- if (!JavaHeuristicScanner.isGenericStarter(getTokenContent()))
- break;
- //$FALL-THROUGH$
- case Symbols.TokenQUESTIONMARK:
- case Symbols.TokenGREATERTHAN:
- if (skipScope(Symbols.TokenLESSTHAN, Symbols.TokenGREATERTHAN))
- return true;
- }
- // <> are harder to detect - restore the position if we fail
- fPosition= storedPosition;
- fToken= storedToken;
- return false;
-
- default:
- 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>Symbols.TokenLPAREN</code>, <code>Symbols.TokenLBRACE</code>,
- * and <code>Symbols.TokenLBRACKET</code>. Returns as the reference position
- * either the token introducing the scope or - if available - the first
- * java 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.
- * @return the indent
- */
- private int handleScopeIntroduction(int bound) {
- switch (fToken) {
- // scope introduction: special treat who special is
- case Symbols.TokenLPAREN:
- int pos= fPosition; // store
-
- // special: method declaration deep indentation
- if (looksLikeMethodDecl()) {
- if (fPrefs.prefMethodDeclDeepIndent)
- return setFirstElementAlignment(pos, bound);
- else {
- fIndent= fPrefs.prefMethodDeclIndent;
- return pos;
- }
- } else {
- fPosition= pos;
- if (looksLikeMethodCall()) {
- if (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 Symbols.TokenLBRACE:
- pos= fPosition; // store
-
- // special: array initializer
- if (looksLikeArrayInitializerIntro())
- if (fPrefs.prefArrayDeepIndent)
- return setFirstElementAlignment(pos, bound);
- else
- fIndent= fPrefs.prefArrayIndent;
- else
- fIndent= fPrefs.prefBlockIndent;
-
- // 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() && !fPrefs.prefIndentBracesForArrays
- || !fPrefs.prefIndentBracesForBlocks) {
- fPosition= pos; // restore
- return skipToStatementStart(true, true); // set to true to match the first if
- } else {
- return pos;
- }
-
- case Symbols.TokenLBRACKET:
- pos= fPosition; // store
-
- // 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:
- 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 Java 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 == JavaHeuristicScanner.NOT_FOUND)
- fAlign= firstPossible;
- return fAlign;
- }
-
-
- /**
- * Returns <code>true</code> if the next token received after calling
- * <code>nextToken</code> is either an equal sign or an array designator ('[]').
- *
- * @return <code>true</code> if the next elements look like the start of an array definition
- */
- private boolean looksLikeArrayInitializerIntro() {
- nextToken();
- if (fToken == Symbols.TokenEQUAL || skipBrackets()) {
- return true;
- }
- 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 == Symbols.TokenELSE);
-
- while (true) {
- nextToken();
- switch (fToken) {
- // scopes: skip them
- case Symbols.TokenRPAREN:
- case Symbols.TokenRBRACKET:
- case Symbols.TokenRBRACE:
- case Symbols.TokenGREATERTHAN:
- skipScope();
- break;
-
- case Symbols.TokenIF:
- // found it, return
- return true;
- case Symbols.TokenELSE:
- // recursively skip else-if blocks
- skipNextIF();
- break;
-
- // shortcut scope starts
- case Symbols.TokenLPAREN:
- case Symbols.TokenLBRACE:
- case Symbols.TokenLBRACKET:
- case Symbols.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 == Symbols.TokenWHILE);
- nextToken();
- switch (fToken) {
- case Symbols.TokenRBRACE:
- skipScope(); // and fall thru
- //$FALL-THROUGH$
- case Symbols.TokenSEMICOLON:
- skipToStatementStart(false, false);
- return fToken == Symbols.TokenDO;
- }
- 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 == Symbols.TokenRBRACKET) {
- nextToken();
- if (fToken == Symbols.TokenLBRACKET) {
- 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, JavaHeuristicScanner.UNBOUND);
- fPreviousPos= start;
- fPosition= fScanner.getPosition() + 1;
- try {
- fLine= fDocument.getLineOfOffset(fPosition);
- } catch (BadLocationException e) {
- fLine= -1;
- }
- }
-
- /**
- * 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 a type declaration (an identifier with optional
- * brackets) which also covers the visibility modifier of constructors; it
- * does not recognize package visible constructors.
- *
- * @return <code>true</code> if the current position looks like a method
- * declaration header.
- */
- private boolean looksLikeMethodDecl() {
- /*
- * TODO This heuristic does not recognize package private constructors
- * since those do have neither type nor visibility keywords.
- * One option would be to go over the parameter list, but that might
- * be empty as well, or not typed in yet - hard to do without an AST...
- */
-
- nextToken();
- if (fToken == Symbols.TokenIDENT) { // method name
- do nextToken();
- while (skipBrackets()); // optional brackets for array valued return types
-
- return fToken == Symbols.TokenIDENT; // return type name
-
- }
- 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 == Symbols.TokenIDENT) { // type name
- nextToken();
- while (fToken == Symbols.TokenOTHER) { // dot of qualification
- nextToken();
- if (fToken != Symbols.TokenIDENT) // qualificating name
- return false;
- nextToken();
- }
- return fToken == Symbols.TokenNEW;
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if the current tokens look like a method
- * call header (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() {
- // TODO [5.0] add awareness for constructor calls with generic types: new ArrayList<String>()
- nextToken();
- return fToken == Symbols.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 == Symbols.TokenEOF) {
- return false;
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java
deleted file mode 100644
index adeecc46..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java
+++ /dev/null
@@ -1,755 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.IDecoratorManager;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.keys.KeySequence;
-import org.eclipse.ui.keys.SWTKeySupport;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.CategoryFilterActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.OverrideIndicatorLabelDecorator;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-/**
- * Show outline in light-weight control.
- *
- *
- */
-public class JavaOutlineInformationControl extends AbstractInformationControl {
-
- private KeyAdapter fKeyAdapter;
- private OutlineContentProvider fOutlineContentProvider;
- private IJavaScriptElement fInput= null;
-
- private OutlineSorter fOutlineSorter;
-
- private OutlineLabelProvider fInnerLabelProvider;
-
- private boolean fShowOnlyMainType;
- private LexicalSortingAction fLexicalSortingAction;
- private SortByDefiningTypeAction fSortByDefiningTypeAction;
- private ShowOnlyMainTypeAction fShowOnlyMainTypeAction;
- private Map fTypeHierarchies= new HashMap();
-
- /**
- * Category filter action group.
- *
- */
- private CategoryFilterActionGroup fCategoryFilterActionGroup;
- private String fPattern;
-
- private class OutlineLabelProvider extends AppearanceAwareLabelProvider {
-
- private boolean fShowDefiningType;
-
- private OutlineLabelProvider() {
- super(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.ALL_CATEGORY, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS);
- }
-
- /*
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- String text= super.getText(element);
- if (fShowDefiningType) {
- try {
- IType type= getDefiningType(element);
- if (type != null) {
- StringBuffer buf= new StringBuffer(super.getText(type));
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(text);
- return buf.toString();
- }
- } catch (JavaScriptModelException e) {
- }
- }
- return text;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- if (fOutlineContentProvider.isShowingInheritedMembers()) {
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement je= (IJavaScriptElement)element;
- if (fInput.getElementType() == IJavaScriptElement.CLASS_FILE)
- je= je.getAncestor(IJavaScriptElement.CLASS_FILE);
- else
- je= je.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (fInput.equals(je)) {
- return null;
- }
- }
- return JFaceResources.getColorRegistry().get(ColoredViewersManager.INHERITED_COLOR_NAME);
- }
- return null;
- }
-
- public void setShowDefiningType(boolean showDefiningType) {
- fShowDefiningType= showDefiningType;
- }
-
- public boolean isShowDefiningType() {
- return fShowDefiningType;
- }
-
- private IType getDefiningType(Object element) throws JavaScriptModelException {
- int kind= ((IJavaScriptElement) element).getElementType();
-
- if (kind != IJavaScriptElement.METHOD && kind != IJavaScriptElement.FIELD && kind != IJavaScriptElement.INITIALIZER) {
- return null;
- }
- IType declaringType= ((IMember) element).getDeclaringType();
- if (kind != IJavaScriptElement.METHOD) {
- return declaringType;
- }
- if (declaringType == null) {
- return null;
- }
- ITypeHierarchy hierarchy= getSuperTypeHierarchy(declaringType);
- if (hierarchy == null) {
- return declaringType;
- }
- IFunction method= (IFunction) element;
- MethodOverrideTester tester= new MethodOverrideTester(declaringType, hierarchy);
- IFunction res= tester.findDeclaringMethod(method, true);
- if (res == null || method.equals(res)) {
- return declaringType;
- }
- return res.getDeclaringType();
- }
- }
-
-
- private class OutlineTreeViewer extends TreeViewer {
-
- private boolean fIsFiltering= false;
-
- private OutlineTreeViewer(Tree tree) {
- super(tree);
-
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object[] getFilteredChildren(Object parent) {
- Object[] result = getRawChildren(parent);
- int unfilteredChildren= result.length;
- ViewerFilter[] filters = getFilters();
- if (filters != null) {
- for (int i= 0; i < filters.length; i++)
- result = filters[i].filter(this, parent, result);
- }
- fIsFiltering= unfilteredChildren != result.length;
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void internalExpandToLevel(Widget node, int level) {
- if (!fIsFiltering && node instanceof TreeItem && getMatcher() == null) {
- TreeItem treeItem= (TreeItem)node;
- if (treeItem.getParentItem() != null && treeItem.getData() instanceof IJavaScriptElement) {
- IJavaScriptElement je= (IJavaScriptElement) treeItem.getData();
- if (je.getElementType() == IJavaScriptElement.IMPORT_CONTAINER || isInnerType(je)) {
- setExpanded(treeItem, false);
- return;
- }
- }
- }
- super.internalExpandToLevel(node, level);
- }
-
- private boolean isInnerType(IJavaScriptElement element) {
- if (element != null && element.getElementType() == IJavaScriptElement.TYPE) {
- IType type= (IType)element;
- try {
- return type.isMember();
- } catch (JavaScriptModelException e) {
- IJavaScriptElement parent= type.getParent();
- if (parent != null) {
- int parentElementType= parent.getElementType();
- return (parentElementType != IJavaScriptElement.JAVASCRIPT_UNIT && parentElementType != IJavaScriptElement.CLASS_FILE);
- }
- }
- }
- return false;
- }
- }
-
-
- private class OutlineContentProvider extends StandardJavaScriptElementContentProvider {
-
- private boolean fShowInheritedMembers;
-
- /**
- * Creates a new Outline content provider.
- *
- * @param showInheritedMembers <code>true</code> iff inherited members are shown
- */
- private OutlineContentProvider(boolean showInheritedMembers) {
- super(true);
- fShowInheritedMembers= showInheritedMembers;
- }
-
- public boolean isShowingInheritedMembers() {
- return fShowInheritedMembers;
- }
-
- public void toggleShowInheritedMembers() {
- Tree tree= getTreeViewer().getTree();
-
- tree.setRedraw(false);
- fShowInheritedMembers= !fShowInheritedMembers;
- getTreeViewer().refresh();
- getTreeViewer().expandToLevel(2);
-
- // reveal selection
- Object selectedElement= getSelectedElement();
- if (selectedElement != null)
- getTreeViewer().reveal(selectedElement);
-
- tree.setRedraw(true);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getChildren(Object element) {
- if (fShowOnlyMainType) {
- if (element instanceof ITypeRoot) {
- element= ((ITypeRoot)element).findPrimaryType();
- }
-
- if (element == null)
- return NO_CHILDREN;
- }
-
- if (fShowInheritedMembers && element instanceof IType) {
- IType type= (IType)element;
- if (type.getDeclaringType() == null) {
- ITypeHierarchy th= getSuperTypeHierarchy(type);
- if (th != null) {
- List children= new ArrayList();
- IType[] superClasses= th.getAllSuperclasses(type);
- children.addAll(Arrays.asList(super.getChildren(type)));
- for (int i= 0, scLength= superClasses.length; i < scLength; i++)
- children.addAll(Arrays.asList(super.getChildren(superClasses[i])));
- return children.toArray();
- }
- }
- }
- return super.getChildren(element);
- }
-
- /**
- * {@inheritDoc}
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- super.inputChanged(viewer, oldInput, newInput);
- fTypeHierarchies.clear();
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- super.dispose();
- if (fCategoryFilterActionGroup != null) {
- fCategoryFilterActionGroup.dispose();
- fCategoryFilterActionGroup= null;
- }
- fTypeHierarchies.clear();
- }
- }
-
-
- private class ShowOnlyMainTypeAction extends Action {
-
- private static final String STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED= "GoIntoTopLevelTypeAction.isChecked"; //$NON-NLS-1$
-
- private TreeViewer fOutlineViewer;
-
- private ShowOnlyMainTypeAction(TreeViewer outlineViewer) {
- super(TextMessages.JavaOutlineInformationControl_GoIntoTopLevelType_label, IAction.AS_CHECK_BOX);
- setToolTipText(TextMessages.JavaOutlineInformationControl_GoIntoTopLevelType_tooltip);
- setDescription(TextMessages.JavaOutlineInformationControl_GoIntoTopLevelType_description);
-
- JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
-
- fOutlineViewer= outlineViewer;
-
- boolean showclass= getDialogSettings().getBoolean(STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED);
- setTopLevelTypeOnly(showclass);
- }
-
- /*
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- setTopLevelTypeOnly(!fShowOnlyMainType);
- }
-
- private void setTopLevelTypeOnly(boolean show) {
- fShowOnlyMainType= show;
- setChecked(show);
-
- Tree tree= fOutlineViewer.getTree();
- tree.setRedraw(false);
-
- fOutlineViewer.refresh(false);
- if (!fShowOnlyMainType)
- fOutlineViewer.expandToLevel(2);
-
-
- // reveal selection
- Object selectedElement= getSelectedElement();
- if (selectedElement != null)
- fOutlineViewer.reveal(selectedElement);
-
- tree.setRedraw(true);
-
- getDialogSettings().put(STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED, show);
- }
- }
-
- private class OutlineSorter extends AbstractHierarchyViewerSorter {
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#getHierarchy(org.eclipse.wst.jsdt.core.IType)
- *
- */
- protected ITypeHierarchy getHierarchy(IType type) {
- return getSuperTypeHierarchy(type);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#isSortByDefiningType()
- *
- */
- public boolean isSortByDefiningType() {
- return fSortByDefiningTypeAction.isChecked();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#isSortAlphabetically()
- *
- */
- public boolean isSortAlphabetically() {
- return fLexicalSortingAction.isChecked();
- }
- }
-
-
- private class LexicalSortingAction extends Action {
-
- private static final String STORE_LEXICAL_SORTING_CHECKED= "LexicalSortingAction.isChecked"; //$NON-NLS-1$
-
- private TreeViewer fOutlineViewer;
-
- private LexicalSortingAction(TreeViewer outlineViewer) {
- super(TextMessages.JavaOutlineInformationControl_LexicalSortingAction_label, IAction.AS_CHECK_BOX);
- setToolTipText(TextMessages.JavaOutlineInformationControl_LexicalSortingAction_tooltip);
- setDescription(TextMessages.JavaOutlineInformationControl_LexicalSortingAction_description);
-
- JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
-
- fOutlineViewer= outlineViewer;
-
- boolean checked=getDialogSettings().getBoolean(STORE_LEXICAL_SORTING_CHECKED);
- setChecked(checked);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_BROWSING_ACTION);
- }
-
- public void run() {
- valueChanged(isChecked(), true);
- }
-
- private void valueChanged(final boolean on, boolean store) {
- setChecked(on);
- BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fOutlineViewer.refresh(false);
- }
- });
-
- if (store)
- getDialogSettings().put(STORE_LEXICAL_SORTING_CHECKED, on);
- }
- }
-
-
- private class SortByDefiningTypeAction extends Action {
-
- private static final String STORE_SORT_BY_DEFINING_TYPE_CHECKED= "SortByDefiningType.isChecked"; //$NON-NLS-1$
-
- private TreeViewer fOutlineViewer;
-
- /**
- * Creates the action.
- *
- * @param outlineViewer the outline viewer
- */
- private SortByDefiningTypeAction(TreeViewer outlineViewer) {
- super(TextMessages.JavaOutlineInformationControl_SortByDefiningTypeAction_label);
- setDescription(TextMessages.JavaOutlineInformationControl_SortByDefiningTypeAction_description);
- setToolTipText(TextMessages.JavaOutlineInformationControl_SortByDefiningTypeAction_tooltip);
-
- JavaPluginImages.setLocalImageDescriptors(this, "definingtype_sort_co.gif"); //$NON-NLS-1$
-
- fOutlineViewer= outlineViewer;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SORT_BY_DEFINING_TYPE_ACTION);
-
- boolean state= getDialogSettings().getBoolean(STORE_SORT_BY_DEFINING_TYPE_CHECKED);
- setChecked(state);
- fInnerLabelProvider.setShowDefiningType(state);
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fInnerLabelProvider.setShowDefiningType(isChecked());
- getDialogSettings().put(STORE_SORT_BY_DEFINING_TYPE_CHECKED, isChecked());
-
- setMatcherString(fPattern, false);
- fOutlineViewer.refresh(true);
-
- // reveal selection
- Object selectedElement= getSelectedElement();
- if (selectedElement != null)
- fOutlineViewer.reveal(selectedElement);
- }
- });
- }
- }
-
- /**
- * String matcher that can match two patterns.
- *
- *
- */
- private static class OrStringMatcher extends StringMatcher {
-
- private StringMatcher fMatcher1;
- private StringMatcher fMatcher2;
-
- private OrStringMatcher(String pattern1, String pattern2, boolean ignoreCase, boolean foo) {
- super("", false, false); //$NON-NLS-1$
- fMatcher1= new StringMatcher(pattern1, ignoreCase, false);
- fMatcher2= new StringMatcher(pattern2, ignoreCase, false);
- }
-
- public boolean match(String text) {
- return fMatcher2.match(text) || fMatcher1.match(text);
- }
-
- }
-
-
- /**
- * Creates a new Java outline information control.
- *
- * @param parent
- * @param shellStyle
- * @param treeStyle
- * @param commandId
- */
- public JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle, String commandId) {
- super(parent, shellStyle, treeStyle, commandId, true);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Text createFilterText(Composite parent) {
- Text text= super.createFilterText(parent);
- text.addKeyListener(getKeyAdapter());
- return text;
- }
-
- /**
- * {@inheritDoc}
- */
- protected TreeViewer createTreeViewer(Composite parent, int style) {
- Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= tree.getItemHeight() * 12;
- tree.setLayoutData(gd);
-
- final TreeViewer treeViewer= new OutlineTreeViewer(tree);
- ColoredViewersManager.install(treeViewer);
-
- // Hard-coded filters
- treeViewer.addFilter(new NamePatternFilter());
- treeViewer.addFilter(new MemberFilter());
-
- fInnerLabelProvider= new OutlineLabelProvider();
- fInnerLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
- IDecoratorManager decoratorMgr= PlatformUI.getWorkbench().getDecoratorManager();
- if (decoratorMgr.getEnabled("org.eclipse.wst.jsdt.ui.override.decorator")) //$NON-NLS-1$
- fInnerLabelProvider.addLabelDecorator(new OverrideIndicatorLabelDecorator(null));
-
- treeViewer.setLabelProvider(fInnerLabelProvider);
-
- fLexicalSortingAction= new LexicalSortingAction(treeViewer);
- fSortByDefiningTypeAction= new SortByDefiningTypeAction(treeViewer);
- fShowOnlyMainTypeAction= new ShowOnlyMainTypeAction(treeViewer);
- fCategoryFilterActionGroup= new CategoryFilterActionGroup(treeViewer, getId(), getInputForCategories());
-
- fOutlineContentProvider= new OutlineContentProvider(false);
- treeViewer.setContentProvider(fOutlineContentProvider);
- fOutlineSorter= new OutlineSorter();
- treeViewer.setComparator(fOutlineSorter);
- treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
-
-
- treeViewer.getTree().addKeyListener(getKeyAdapter());
-
- return treeViewer;
- }
-
- /**
- * {@inheritDoc}
- */
- protected String getStatusFieldText() {
- KeySequence[] sequences= getInvokingCommandKeySequences();
- if (sequences == null || sequences.length == 0)
- return ""; //$NON-NLS-1$
-
- String keySequence= sequences[0].format();
-
- if (fOutlineContentProvider.isShowingInheritedMembers())
- return Messages.format(JavaUIMessages.JavaOutlineControl_statusFieldText_hideInheritedMembers, keySequence);
- else
- return Messages.format(JavaUIMessages.JavaOutlineControl_statusFieldText_showInheritedMembers, keySequence);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractInformationControl#getId()
- *
- */
- protected String getId() {
- return "org.eclipse.wst.jsdt.internal.ui.text.QuickOutline"; //$NON-NLS-1$
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInput(Object information) {
- if (information == null || information instanceof String) {
- inputChanged(null, null);
- return;
- }
- IJavaScriptElement je= (IJavaScriptElement)information;
- IJavaScriptUnit cu= (IJavaScriptUnit)je.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null)
- fInput= cu;
- else
- fInput= je.getAncestor(IJavaScriptElement.CLASS_FILE);
-
- inputChanged(fInput, information);
-
- fCategoryFilterActionGroup.setInput(getInputForCategories());
- }
-
- private KeyAdapter getKeyAdapter() {
- if (fKeyAdapter == null) {
- fKeyAdapter= new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
- KeySequence keySequence = KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator));
- KeySequence[] sequences= getInvokingCommandKeySequences();
- if (sequences == null)
- return;
- for (int i= 0; i < sequences.length; i++) {
- if (sequences[i].equals(keySequence)) {
- e.doit= false;
- toggleShowInheritedMembers();
- return;
- }
- }
- }
- };
- }
- return fKeyAdapter;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void handleStatusFieldClicked() {
- toggleShowInheritedMembers();
- }
-
- protected void toggleShowInheritedMembers() {
- long flags= fInnerLabelProvider.getTextFlags();
- flags ^= JavaScriptElementLabels.ALL_POST_QUALIFIED;
- fInnerLabelProvider.setTextFlags(flags);
- fOutlineContentProvider.toggleShowInheritedMembers();
- updateStatusFieldText();
- fCategoryFilterActionGroup.setInput(getInputForCategories());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractInformationControl#fillViewMenu(org.eclipse.jface.action.IMenuManager)
- */
- protected void fillViewMenu(IMenuManager viewMenu) {
- super.fillViewMenu(viewMenu);
- viewMenu.add(fShowOnlyMainTypeAction);
-
- viewMenu.add(new Separator("Sorters")); //$NON-NLS-1$
- viewMenu.add(fLexicalSortingAction);
-
- viewMenu.add(fSortByDefiningTypeAction);
-
- fCategoryFilterActionGroup.setInput(getInputForCategories());
- fCategoryFilterActionGroup.contributeToViewMenu(viewMenu);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractInformationControl#setMatcherString(java.lang.String, boolean)
- *
- */
- protected void setMatcherString(String pattern, boolean update) {
- fPattern= pattern;
- if (pattern.length() == 0 || !fSortByDefiningTypeAction.isChecked()) {
- super.setMatcherString(pattern, update);
- return;
- }
-
- boolean ignoreCase= pattern.toLowerCase().equals(pattern);
- String pattern2= "*" + JavaScriptElementLabels.CONCAT_STRING + pattern; //$NON-NLS-1$
- fStringMatcher= new OrStringMatcher(pattern, pattern2, ignoreCase, false);
-
- if (update)
- stringMatcherUpdated();
-
- }
-
- private IJavaScriptElement[] getInputForCategories() {
- if (fInput == null)
- return new IJavaScriptElement[0];
-
- if (fOutlineContentProvider.isShowingInheritedMembers()) {
- IJavaScriptElement p= fInput;
- if (p instanceof ITypeRoot) {
- p= ((ITypeRoot)p).findPrimaryType();
- }
- while (p != null && !(p instanceof IType)) {
- p= p.getParent();
- }
- if (!(p instanceof IType))
- return new IJavaScriptElement[] {fInput};
-
- ITypeHierarchy hierarchy= getSuperTypeHierarchy((IType)p);
- if (hierarchy == null)
- return new IJavaScriptElement[] {fInput};
-
- IType[] supertypes= hierarchy.getAllSuperclasses((IType)p);
- IJavaScriptElement[] result= new IJavaScriptElement[supertypes.length + 1];
- result[0]= fInput;
- System.arraycopy(supertypes, 0, result, 1, supertypes.length);
- return result;
- } else {
- return new IJavaScriptElement[] {fInput};
- }
- }
-
- private ITypeHierarchy getSuperTypeHierarchy(IType type) {
- ITypeHierarchy th= (ITypeHierarchy)fTypeHierarchies.get(type);
- if (th == null) {
- try {
- th= SuperTypeHierarchyCache.getTypeHierarchy(type, getProgressMonitor());
- } catch (JavaScriptModelException e) {
- return null;
- } catch (OperationCanceledException e) {
- return null;
- }
- fTypeHierarchies.put(type, th);
- }
- return th;
- }
-
- private IProgressMonitor getProgressMonitor() {
- IWorkbenchPage wbPage= JavaScriptPlugin.getActivePage();
- if (wbPage == null)
- return null;
-
- IEditorPart editor= wbPage.getActiveEditor();
- if (editor == null)
- return null;
-
- return editor.getEditorSite().getActionBars().getStatusLineManager().getProgressMonitor();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPairMatcher.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPairMatcher.java
deleted file mode 100644
index 2d65a656..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPairMatcher.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Christian Plesner Hansen (plesner@quenta.org) - changed implementation to use DefaultCharacterPairMatcher
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Helper class for match pairs of characters.
- */
-public final class JavaPairMatcher extends DefaultCharacterPairMatcher implements ISourceVersionDependent {
-
- /**
- * Stores the source version state.
- *
- */
- private boolean fHighlightAngularBrackets= false;
-
-
- public JavaPairMatcher(char[] pairs) {
- super(pairs, IJavaScriptPartitions.JAVA_PARTITIONING);
- }
-
- /* @see ICharacterPairMatcher#match(IDocument, int) */
- public IRegion match(IDocument document, int offset) {
- try {
- return performMatch(document, offset);
- } catch (BadLocationException ble) {
- return null;
- }
- }
-
- /*
- * Performs the actual work of matching for #match(IDocument, int).
- */
- private IRegion performMatch(IDocument document, int offset) throws BadLocationException {
- if (offset < 0 || document == null) return null;
- final char prevChar= document.getChar(Math.max(offset - 1, 0));
- if ((prevChar == '<' || prevChar == '>') && !fHighlightAngularBrackets)
- return null;
- if (prevChar == '<' && isLessThanOperator(document, offset - 1))
- return null;
- final IRegion region= super.match(document, offset);
- if (region == null) return region;
- if (prevChar == '>') {
- final int peer= region.getOffset();
- if (isLessThanOperator(document, peer)) return null;
- }
- return region;
- }
-
- /**
- * Returns true if the character at the specified offset is a
- * less-than sign, rather than an type parameter list open
- * angle bracket.
- *
- * @param document a document
- * @param offset an offset within the document
- * @return true if the character at the specified offset is not
- * a type parameter start bracket
- * @throws BadLocationException
- */
- private boolean isLessThanOperator(IDocument document, int offset) throws BadLocationException {
- if (offset < 0) return false;
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document, IJavaScriptPartitions.JAVA_PARTITIONING, TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, offset, false));
- return !isTypeParameterBracket(offset, document, scanner);
- }
-
- /**
- * Checks if the angular bracket at <code>offset</code> is a type
- * parameter bracket.
- *
- * @param offset the offset of the opening bracket
- * @param document the document
- * @param scanner a java heuristic scanner on <code>document</code>
- * @return <code>true</code> if the bracket is part of a type parameter,
- * <code>false</code> otherwise
- *
- */
- private boolean isTypeParameterBracket(int offset, IDocument document, JavaHeuristicScanner scanner) {
- /*
- * type parameter come after braces (closing or opening), semicolons, or after
- * a Type name (heuristic: starts with capital character, or after a modifier
- * keyword in a method declaration (visibility, static, synchronized, final)
- */
-
- try {
- IRegion line= document.getLineInformationOfOffset(offset);
-
- int prevToken= scanner.previousToken(offset - 1, line.getOffset());
- int prevTokenOffset= scanner.getPosition() + 1;
- String previous= prevToken == Symbols.TokenEOF ? null : document.get(prevTokenOffset, offset - prevTokenOffset).trim();
-
- if ( prevToken == Symbols.TokenLBRACE
- || prevToken == Symbols.TokenRBRACE
- || prevToken == Symbols.TokenSEMICOLON
- || prevToken == Symbols.TokenSYNCHRONIZED
- || prevToken == Symbols.TokenSTATIC
- || (prevToken == Symbols.TokenIDENT && isTypeParameterIntroducer(previous))
- || prevToken == Symbols.TokenEOF)
- return true;
- } catch (BadLocationException e) {
- return false;
- }
-
- return false;
- }
-
- /**
- * Returns <code>true</code> if <code>identifier</code> is an identifier
- * that could come right before a type parameter list. It uses a heuristic:
- * if the identifier starts with an upper case, it is assumed a type name.
- * Also, if <code>identifier</code> is a method modifier, it is assumed
- * that the angular bracket is part of the generic type parameter of a
- * method.
- *
- * @param identifier the identifier to check
- * @return <code>true</code> if the identifier could introduce a type
- * parameter list
- *
- */
- private boolean isTypeParameterIntroducer(String identifier) {
- return identifier.length() > 0
- && (Character.isUpperCase(identifier.charAt(0))
- || identifier.startsWith("final") //$NON-NLS-1$
- || identifier.startsWith("public") //$NON-NLS-1$
- || identifier.startsWith("public") //$NON-NLS-1$
- || identifier.startsWith("protected") //$NON-NLS-1$
- || identifier.startsWith("private")); //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String)
- */
- public void setSourceVersion(String version) {
- if (JavaScriptCore.VERSION_1_5.compareTo(version) <= 0)
- fHighlightAngularBrackets= true;
- else
- fHighlightAngularBrackets= false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPartitionScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPartitionScanner.java
deleted file mode 100644
index cba6046b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPartitionScanner.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.text.rules.EndOfLineRule;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IPredicateRule;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.IWordDetector;
-import org.eclipse.jface.text.rules.MultiLineRule;
-import org.eclipse.jface.text.rules.RuleBasedPartitionScanner;
-import org.eclipse.jface.text.rules.SingleLineRule;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.text.rules.WordRule;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * This scanner recognizes the JavaDoc comments and Java multi line comments.
- */
-public class JavaPartitionScanner extends RuleBasedPartitionScanner implements IJavaScriptPartitions {
-
- /**
- * Detector for empty comments.
- */
- static class EmptyCommentDetector implements IWordDetector {
-
- /*
- * @see IWordDetector#isWordStart
- */
- public boolean isWordStart(char c) {
- return (c == '/');
- }
-
- /*
- * @see IWordDetector#isWordPart
- */
- public boolean isWordPart(char c) {
- return (c == '*' || c == '/');
- }
- }
-
-
- /**
- * Word rule for empty comments.
- */
- static class EmptyCommentRule extends WordRule implements IPredicateRule {
-
- private IToken fSuccessToken;
- /**
- * Constructor for EmptyCommentRule.
- * @param successToken
- */
- public EmptyCommentRule(IToken successToken) {
- super(new EmptyCommentDetector());
- fSuccessToken= successToken;
- addWord("/**/", fSuccessToken); //$NON-NLS-1$
- }
-
- /*
- * @see IPredicateRule#evaluate(ICharacterScanner, boolean)
- */
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- return evaluate(scanner);
- }
-
- /*
- * @see IPredicateRule#getSuccessToken()
- */
- public IToken getSuccessToken() {
- return fSuccessToken;
- }
- }
-
-
-
- /**
- * Creates the partitioner and sets up the appropriate rules.
- */
- public JavaPartitionScanner() {
- super();
-
- IToken string= new Token(JAVA_STRING);
- IToken character= new Token(JAVA_CHARACTER);
- IToken javaDoc= new Token(JAVA_DOC);
- IToken multiLineComment= new Token(JAVA_MULTI_LINE_COMMENT);
- IToken singleLineComment= new Token(JAVA_SINGLE_LINE_COMMENT);
-
- List rules= new ArrayList();
-
- // Add rule for single line comments.
- rules.add(new EndOfLineRule("//", singleLineComment)); //$NON-NLS-1$
-
- // Add rule for strings.
- rules.add(new SingleLineRule("\"", "\"", string, '\\')); //$NON-NLS-2$ //$NON-NLS-1$
-
- // Add rule for character constants.
- rules.add(new SingleLineRule("'", "'", character, '\\')); //$NON-NLS-2$ //$NON-NLS-1$
-
- // Add special case word rule.
- EmptyCommentRule wordRule= new EmptyCommentRule(multiLineComment);
- rules.add(wordRule);
-
- // Add rules for multi-line comments and javadoc.
- rules.add(new MultiLineRule("/**", "*/", javaDoc)); //$NON-NLS-1$ //$NON-NLS-2$
- rules.add(new MultiLineRule("/*", "*/", multiLineComment)); //$NON-NLS-1$ //$NON-NLS-2$
-
- IPredicateRule[] result= new IPredicateRule[rules.size()];
- rules.toArray(result);
- setPredicateRules(result);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java
deleted file mode 100644
index 366c8243..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.jface.text.presentation.PresentationReconciler;
-
-
-/**
- * Presentation reconciler, adding functionality for operation without a viewer.
- *
- *
- */
-public class JavaPresentationReconciler extends PresentationReconciler {
-
- /** Last used document */
- private IDocument fLastDocument;
-
- /**
- * Constructs a "repair description" for the given damage and returns
- * this description as a text presentation.
- * <p>
- * NOTE: Should not be used if this reconciler is installed on a viewer.
- * </p>
- *
- * @param damage the damage to be repaired
- * @param document the document whose presentation must be repaired
- * @return the presentation repair description as text presentation
- */
- public TextPresentation createRepairDescription(IRegion damage, IDocument document) {
- if (document != fLastDocument) {
- setDocumentToDamagers(document);
- setDocumentToRepairers(document);
- fLastDocument= document;
- }
- return createPresentation(damage, document);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaReconciler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaReconciler.java
deleted file mode 100644
index 612805bb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaReconciler.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.reconciler.DirtyRegion;
-import org.eclipse.jface.text.reconciler.MonoReconciler;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.events.ShellAdapter;
-import org.eclipse.swt.events.ShellEvent;
-import org.eclipse.swt.events.ShellListener;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.spelling.SpellingService;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-
-
-/**
- * A reconciler that is also activated on editor activation.
- */
-public class JavaReconciler extends MonoReconciler {
-
- /**
- * Internal part listener for activating the reconciler.
- */
- private class PartListener implements IPartListener {
-
- /*
- * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart)
- */
- public void partActivated(IWorkbenchPart part) {
- if (part == fTextEditor) {
- if (hasJavaModelChanged())
- JavaReconciler.this.forceReconciling();
- setEditorActive(true);
- }
- }
-
- /*
- * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart)
- */
- public void partBroughtToTop(IWorkbenchPart part) {
- }
-
- /*
- * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
- */
- public void partClosed(IWorkbenchPart part) {
- }
-
- /*
- * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart)
- */
- public void partDeactivated(IWorkbenchPart part) {
- if (part == fTextEditor) {
- setJavaModelChanged(false);
- setEditorActive(false);
- }
- }
-
- /*
- * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
- */
- public void partOpened(IWorkbenchPart part) {
- }
- }
-
- /**
- * Internal Shell activation listener for activating the reconciler.
- */
- private class ActivationListener extends ShellAdapter {
-
- private Control fControl;
-
- public ActivationListener(Control control) {
- Assert.isNotNull(control);
- fControl= control;
- }
-
- /*
- * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent)
- */
- public void shellActivated(ShellEvent e) {
- if (!fControl.isDisposed() && fControl.isVisible()) {
- if (hasJavaModelChanged())
- JavaReconciler.this.forceReconciling();
- setEditorActive(true);
- }
- }
-
- /*
- * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent)
- */
- public void shellDeactivated(ShellEvent e) {
- if (!fControl.isDisposed() && fControl.getShell() == e.getSource()) {
- setJavaModelChanged(false);
- setEditorActive(false);
- }
- }
- }
-
- /**
- * Internal Java element changed listener
- *
- *
- */
- private class ElementChangedListener implements IElementChangedListener {
- /*
- * @see org.eclipse.wst.jsdt.core.IElementChangedListener#elementChanged(org.eclipse.wst.jsdt.core.ElementChangedEvent)
- */
- public void elementChanged(ElementChangedEvent event) {
- if (event.getDelta().getFlags() == IJavaScriptElementDelta.F_AST_AFFECTED)
- return;
- setJavaModelChanged(true);
- if (!fIsReconciling && isEditorActive() )
- JavaReconciler.this.forceReconciling();
- }
- }
-
- /**
- * Internal resource change listener.
- *
- *
- */
- class ResourceChangeListener implements IResourceChangeListener {
-
- private IResource getResource() {
- IEditorInput input= fTextEditor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFileEditorInput fileInput= (IFileEditorInput) input;
- return fileInput.getFile();
- }
- return null;
- }
-
- /*
- * @see IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
- */
- public void resourceChanged(IResourceChangeEvent e) {
- IResourceDelta delta= e.getDelta();
- IResource resource= getResource();
- if (delta != null && resource != null) {
- IResourceDelta child= delta.findMember(resource.getFullPath());
- if (child != null) {
- IMarkerDelta[] deltas= child.getMarkerDeltas();
- int i= deltas.length;
- while (--i >= 0) {
- try {
- if (deltas[i].getMarker().isSubtypeOf(IMarker.PROBLEM)) {
- forceReconciling();
- return;
- }
- } catch (CoreException e1) {
- // ignore and try next one
- }
- }
- }
- }
- }
- }
-
-
- /** The reconciler's editor */
- private ITextEditor fTextEditor;
- /** The part listener */
- private IPartListener fPartListener;
- /** The shell listener */
- private ShellListener fActivationListener;
- /**
- * The mutex that keeps us from running multiple reconcilers on one editor.
- */
- private Object fMutex;
- /**
- * The Java element changed listener.
- *
- */
- private IElementChangedListener fJavaElementChangedListener;
- /**
- * Tells whether the Java model sent out a changed event.
- *
- */
- private volatile boolean fHasJavaModelChanged= true;
- /**
- * Tells whether this reconciler's editor is active.
- *
- */
- private volatile boolean fIsEditorActive= true;
- /**
- * The resource change listener.
- *
- */
- private IResourceChangeListener fResourceChangeListener;
- /**
- * The property change listener.
- *
- */
- private IPropertyChangeListener fPropertyChangeListener;
- /**
- * Tells whether a reconcile is in progress.
- *
- */
- private volatile boolean fIsReconciling= false;
-
- private boolean fIninitalProcessDone= false;
-
- /**
- * Creates a new reconciler.
- *
- * @param editor the editor
- * @param strategy the reconcile strategy
- * @param isIncremental <code>true</code> if this is an incremental reconciler
- */
- public JavaReconciler(ITextEditor editor, JavaCompositeReconcilingStrategy strategy, boolean isIncremental) {
- super(strategy, isIncremental);
- fTextEditor= editor;
-
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898
- // when re-using editors, a new reconciler is set up by the source viewer
- // and the old one uninstalled. However, the old reconciler may still be
- // running.
- // To avoid having to reconcilers calling CompilationUnitEditor.reconciled,
- // we synchronized on a lock object provided by the editor.
- // The critical section is really the entire run() method of the reconciler
- // thread, but synchronizing process() only will keep JavaReconcilingStrategy
- // from running concurrently on the same editor.
- // TODO remove once we have ensured that there is only one reconciler per editor.
- if (editor instanceof CompilationUnitEditor)
- fMutex= ((CompilationUnitEditor) editor).getReconcilerLock();
- else
- fMutex= new Object(); // Null Object
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconciler#install(org.eclipse.jface.text.ITextViewer)
- */
- public void install(ITextViewer textViewer) {
- super.install(textViewer);
-
- fPartListener= new PartListener();
- IWorkbenchPartSite site= fTextEditor.getSite();
- IWorkbenchWindow window= site.getWorkbenchWindow();
- window.getPartService().addPartListener(fPartListener);
-
- fActivationListener= new ActivationListener(textViewer.getTextWidget());
- Shell shell= window.getShell();
- shell.addShellListener(fActivationListener);
-
- fJavaElementChangedListener= new ElementChangedListener();
- JavaScriptCore.addElementChangedListener(fJavaElementChangedListener);
-
- fResourceChangeListener= new ResourceChangeListener();
- IWorkspace workspace= JavaScriptPlugin.getWorkspace();
- workspace.addResourceChangeListener(fResourceChangeListener);
-
- fPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (SpellingService.PREFERENCE_SPELLING_ENABLED.equals(event.getProperty()) || SpellingService.PREFERENCE_SPELLING_ENGINE.equals(event.getProperty()))
- forceReconciling();
- }
- };
- JavaScriptPlugin.getDefault().getCombinedPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall()
- */
- public void uninstall() {
-
- IWorkbenchPartSite site= fTextEditor.getSite();
- IWorkbenchWindow window= site.getWorkbenchWindow();
- window.getPartService().removePartListener(fPartListener);
- fPartListener= null;
-
- Shell shell= window.getShell();
- if (shell != null && !shell.isDisposed())
- shell.removeShellListener(fActivationListener);
- fActivationListener= null;
-
- JavaScriptCore.removeElementChangedListener(fJavaElementChangedListener);
- fJavaElementChangedListener= null;
-
- IWorkspace workspace= JavaScriptPlugin.getWorkspace();
- workspace.removeResourceChangeListener(fResourceChangeListener);
- fResourceChangeListener= null;
-
- JavaScriptPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- fPropertyChangeListener= null;
-
- super.uninstall();
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.AbstractReconciler#forceReconciling()
- */
- protected void forceReconciling() {
- if (!fIninitalProcessDone)
- return;
-
- super.forceReconciling();
- JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE);
- strategy.notifyListeners(false);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.AbstractReconciler#aboutToReconcile()
- *
- */
- protected void aboutToBeReconciled() {
- JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE);
- strategy.aboutToBeReconciled();
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerReset()
- */
- protected void reconcilerReset() {
- super.reconcilerReset();
- JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE);
- strategy.notifyListeners(true);
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.MonoReconciler#initialProcess()
- */
- protected void initialProcess() {
- synchronized (fMutex) {
- super.initialProcess();
- }
- fIninitalProcessDone= true;
- }
-
- /*
- * @see org.eclipse.jface.text.reconciler.MonoReconciler#process(org.eclipse.jface.text.reconciler.DirtyRegion)
- */
- protected void process(DirtyRegion dirtyRegion) {
- synchronized (fMutex) {
- fIsReconciling= true;
- super.process(dirtyRegion);
- fIsReconciling= false;
- }
- }
-
- /**
- * Tells whether the Java Model has changed or not.
- *
- * @return <code>true</code> iff the Java Model has changed
- *
- */
- private synchronized boolean hasJavaModelChanged() {
- return fHasJavaModelChanged;
- }
-
- /**
- * Sets whether the Java Model has changed or not.
- *
- * @param state <code>true</code> iff the java model has changed
- *
- */
- private synchronized void setJavaModelChanged(boolean state) {
- fHasJavaModelChanged= state;
- }
-
- /**
- * Tells whether this reconciler's editor is active.
- *
- * @return <code>true</code> iff the editor is active
- *
- */
- private synchronized boolean isEditorActive() {
- return fIsEditorActive;
- }
-
-
- /**
- * Sets whether this reconciler's editor is active.
- *
- * @param state <code>true</code> iff the editor is active
- *
- */
- private synchronized void setEditorActive(boolean state) {
- fIsEditorActive= state;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWhitespaceDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWhitespaceDetector.java
deleted file mode 100644
index c26d8cfb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWhitespaceDetector.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.jface.text.rules.IWhitespaceDetector;
-
-/**
- * A java aware white space detector.
- */
-public class JavaWhitespaceDetector implements IWhitespaceDetector {
-
- /**
- * @see IWhitespaceDetector#isWhitespace
- */
- public boolean isWhitespace(char c) {
- return Character.isWhitespace(c);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordDetector.java
deleted file mode 100644
index d1a268e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordDetector.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.jface.text.rules.IWordDetector;
-
-/**
- * A Java aware word detector.
- */
-public class JavaWordDetector implements IWordDetector {
-
- /*
- * @see IWordDetector#isWordStart
- */
- public boolean isWordStart(char c) {
- return Character.isJavaIdentifierStart(c);
- }
-
- /*
- * @see IWordDetector#isWordPart
- */
- public boolean isWordPart(char c) {
- return Character.isJavaIdentifierPart(c);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordFinder.java
deleted file mode 100644
index 89259da8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordFinder.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-
-public class JavaWordFinder {
-
- public static IRegion findWord(IDocument document, int offset) {
-
- int start= -2;
- int end= -1;
-
- try {
- int pos= offset;
- char c;
-
- while (pos >= 0) {
- c= document.getChar(pos);
- if (!Character.isJavaIdentifierPart(c))
- break;
- --pos;
- }
- start= pos;
-
- pos= offset;
- int length= document.getLength();
-
- while (pos < length) {
- c= document.getChar(pos);
- if (!Character.isJavaIdentifierPart(c))
- break;
- ++pos;
- }
- end= pos;
-
- } catch (BadLocationException x) {
- }
-
- if (start >= -1 && end > -1) {
- if (start == offset && end == offset)
- return new Region(offset, 0);
- else if (start == offset)
- return new Region(start, end - start);
- else
- return new Region(start + 1, end - start - 1);
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java
deleted file mode 100644
index bb064f85..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.text.CharacterIterator;
-
-import org.eclipse.core.runtime.Assert;
-
-import com.ibm.icu.text.BreakIterator;
-
-
-
-/**
- * Breaks java text into word starts, also stops at line start and end. No
- * direction dependency.
- *
- *
- */
-public class JavaWordIterator extends BreakIterator {
-
- /**
- * The underlying java break iterator. It returns all breaks, including
- * before and after every whitespace.
- */
- private JavaBreakIterator fIterator;
- /** The current index for the stateful operations. */
- private int fIndex;
-
- /**
- * Creates a new word iterator.
- */
- public JavaWordIterator() {
- fIterator= new JavaBreakIterator();
- first();
- }
-
- /*
- * @see java.text.BreakIterator#first()
- */
- public int first() {
- fIndex= fIterator.first();
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#last()
- */
- public int last() {
- fIndex= fIterator.last();
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#next(int)
- */
- public int next(int n) {
- int next= 0;
- while (--n > 0 && next != DONE) {
- next= next();
- }
- return next;
- }
-
- /*
- * @see java.text.BreakIterator#next()
- */
- public int next() {
- fIndex= following(fIndex);
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#previous()
- */
- public int previous() {
- fIndex= preceding(fIndex);
- return fIndex;
- }
-
-
- /*
- * @see java.text.BreakIterator#preceding(int)
- */
- public int preceding(int offset) {
- int first= fIterator.preceding(offset);
- if (isWhitespace(first, offset)) {
- int second= fIterator.preceding(first);
- if (second != DONE && !isDelimiter(second, first))
- return second;
- }
- return first;
- }
-
- /*
- * @see java.text.BreakIterator#following(int)
- */
- public int following(int offset) {
- int first= fIterator.following(offset);
- if (eatFollowingWhitespace(offset, first)) {
- int second= fIterator.following(first);
- if (isWhitespace(first, second))
- return second;
- }
- return first;
- }
-
- private boolean eatFollowingWhitespace(int offset, int exclusiveEnd) {
- if (exclusiveEnd == DONE || offset == DONE)
- return false;
-
- if (isWhitespace(offset, exclusiveEnd))
- return false;
- if (isDelimiter(offset, exclusiveEnd))
- return false;
-
- return true;
- }
-
- /**
- * Returns <code>true</code> if the given sequence into the underlying text
- * represents a delimiter, <code>false</code> otherwise.
- *
- * @param offset the offset
- * @param exclusiveEnd the end offset
- * @return <code>true</code> if the given range is a delimiter
- */
- private boolean isDelimiter(int offset, int exclusiveEnd) {
- if (exclusiveEnd == DONE || offset == DONE)
- return false;
-
- Assert.isTrue(offset >= 0);
- Assert.isTrue(exclusiveEnd <= getText().getEndIndex());
- Assert.isTrue(exclusiveEnd > offset);
-
- CharSequence seq= fIterator.fText;
-
- while (offset < exclusiveEnd) {
- char ch= seq.charAt(offset);
- if (ch != '\n' && ch != '\r')
- return false;
- offset++;
- }
-
- return true;
- }
-
- /**
- * Returns <code>true</code> if the given sequence into the underlying text
- * represents whitespace, but not a delimiter, <code>false</code> otherwise.
- *
- * @param offset the offset
- * @param exclusiveEnd the end offset
- * @return <code>true</code> if the given range is whitespace
- */
- private boolean isWhitespace(int offset, int exclusiveEnd) {
- if (exclusiveEnd == DONE || offset == DONE)
- return false;
-
- Assert.isTrue(offset >= 0);
- Assert.isTrue(exclusiveEnd <= getText().getEndIndex());
- Assert.isTrue(exclusiveEnd > offset);
-
- CharSequence seq= fIterator.fText;
-
- while (offset < exclusiveEnd) {
- char ch= seq.charAt(offset);
- if (!Character.isWhitespace(ch))
- return false;
- if (ch == '\n' || ch == '\r')
- return false;
- offset++;
- }
-
- return true;
- }
-
- /*
- * @see java.text.BreakIterator#current()
- */
- public int current() {
- return fIndex;
- }
-
- /*
- * @see java.text.BreakIterator#getText()
- */
- public CharacterIterator getText() {
- return fIterator.getText();
- }
-
- /**
- * Sets the text as <code>CharSequence</code>.
- * @param newText the new text
- */
- public void setText(CharSequence newText) {
- fIterator.setText(newText);
- first();
- }
-
- /*
- * @see java.text.BreakIterator#setText(java.text.CharacterIterator)
- */
- public void setText(CharacterIterator newText) {
- fIterator.setText(newText);
- first();
- }
-
- /*
- * @see java.text.BreakIterator#setText(java.lang.String)
- */
- public void setText(String newText) {
- setText((CharSequence) newText);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/LineBreakingReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/LineBreakingReader.java
deleted file mode 100644
index db4f0474..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/LineBreakingReader.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.Reader;
-
-import org.eclipse.swt.graphics.GC;
-
-import com.ibm.icu.text.BreakIterator;
-
-/*
- * Not a real reader. Could change if requested
- */
-public class LineBreakingReader {
-
- private BufferedReader fReader;
- private GC fGC;
- private int fMaxWidth;
-
- private String fLine;
- private int fOffset;
-
- private BreakIterator fLineBreakIterator;
- private boolean fBreakWords;
-
- /**
- * Creates a reader that breaks an input text to fit in a given width.
- *
- * @param reader Reader of the input text
- * @param gc The graphic context that defines the currently used font sizes
- * @param maxLineWidth The max width (pixels) where the text has to fit in
- */
- public LineBreakingReader(Reader reader, GC gc, int maxLineWidth) {
- fReader= new BufferedReader(reader);
- fGC= gc;
- fMaxWidth= maxLineWidth;
- fOffset= 0;
- fLine= null;
- fLineBreakIterator= BreakIterator.getLineInstance();
- fBreakWords= true;
- }
-
- public boolean isFormattedLine() {
- return fLine != null;
- }
-
- /**
- * Reads the next line. The lengths of the line will not exceed the given maximum
- * width.
- *
- * @return the next line
- * @throws IOException
- */
- public String readLine() throws IOException {
- if (fLine == null) {
- String line= fReader.readLine();
- if (line == null)
- return null;
-
- int lineLen= fGC.textExtent(line).x;
- if (lineLen < fMaxWidth) {
- return line;
- }
- fLine= line;
- fLineBreakIterator.setText(line);
- fOffset= 0;
- }
- int breakOffset= findNextBreakOffset(fOffset);
- String res;
- if (breakOffset != BreakIterator.DONE) {
- res= fLine.substring(fOffset, breakOffset);
- fOffset= findWordBegin(breakOffset);
- if (fOffset == fLine.length()) {
- fLine= null;
- }
- } else {
- res= fLine.substring(fOffset);
- fLine= null;
- }
- return res;
- }
-
- private int findNextBreakOffset(int currOffset) {
- int currWidth= 0;
- int nextOffset= fLineBreakIterator.following(currOffset);
- while (nextOffset != BreakIterator.DONE) {
- String word= fLine.substring(currOffset, nextOffset);
- int wordWidth= fGC.textExtent(word).x;
- int nextWidth= wordWidth + currWidth;
- if (nextWidth > fMaxWidth) {
- if (currWidth > 0)
- return currOffset;
-
- if (!fBreakWords)
- return nextOffset;
-
- // need to fit into fMaxWidth
- int length= word.length();
- while (length >= 0) {
- length--;
- word= word.substring(0, length);
- wordWidth= fGC.textExtent(word).x;
- if (wordWidth + currWidth < fMaxWidth)
- return currOffset + length;
- }
- return nextOffset;
- }
- currWidth= nextWidth;
- currOffset= nextOffset;
- nextOffset= fLineBreakIterator.next();
- }
- return nextOffset;
- }
-
- private int findWordBegin(int idx) {
- while (idx < fLine.length() && Character.isWhitespace(fLine.charAt(idx))) {
- idx++;
- }
- return idx;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/PreferencesAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/PreferencesAdapter.java
deleted file mode 100644
index 60a28c17..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/PreferencesAdapter.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Adapts {@link org.eclipse.core.runtime.Preferences} to
- * {@link org.eclipse.jface.preference.IPreferenceStore}
- *
- *
- */
-public class PreferencesAdapter implements IPreferenceStore {
-
- /**
- * Property change listener. Listens for events of type
- * {@link org.eclipse.core.runtime.Preferences.PropertyChangeEvent} and fires
- * a {@link org.eclipse.jface.util.PropertyChangeEvent} on the
- * adapter with arguments from the received event.
- */
- private class PropertyChangeListener implements Preferences.IPropertyChangeListener {
-
- /*
- * @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
- */
- public void propertyChange(Preferences.PropertyChangeEvent event) {
- firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
- }
- }
-
- /** Listeners on the adapter */
- private ListenerList fListeners= new ListenerList(ListenerList.IDENTITY);
-
- /** Listener on the adapted Preferences */
- private PropertyChangeListener fListener= new PropertyChangeListener();
-
- /** Adapted Preferences */
- private Preferences fPreferences;
-
- /** True iff no events should be forwarded */
- private boolean fSilent;
-
- /**
- * Initialize with empty Preferences.
- */
- public PreferencesAdapter() {
- this(new Preferences());
- }
- /**
- * Initialize with the given Preferences.
- *
- * @param preferences The preferences to wrap.
- */
- public PreferencesAdapter(Preferences preferences) {
- fPreferences= preferences;
- }
-
- /**
- * {@inheritDoc}
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- if (fListeners.size() == 0)
- fPreferences.addPropertyChangeListener(fListener);
- fListeners.add(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.remove(listener);
- if (fListeners.size() == 0)
- fPreferences.removePropertyChangeListener(fListener);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(String name) {
- return fPreferences.contains(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
- if (!fSilent) {
- final PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- final IPropertyChangeListener listener= (IPropertyChangeListener)listeners[i];
- Runnable runnable= new Runnable() {
- public void run() {
- listener.propertyChange(event);
- }
- };
-
- if (Display.getCurrent() != null)
- runnable.run();
- else {
- // Post runnable into UI thread
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- Display display;
- if (shell != null)
- display= shell.getDisplay();
- else
- display= Display.getDefault();
- display.asyncExec(runnable);
- }
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getBoolean(String name) {
- return fPreferences.getBoolean(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean getDefaultBoolean(String name) {
- return fPreferences.getDefaultBoolean(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDefaultDouble(String name) {
- return fPreferences.getDefaultDouble(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public float getDefaultFloat(String name) {
- return fPreferences.getDefaultFloat(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public int getDefaultInt(String name) {
- return fPreferences.getDefaultInt(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public long getDefaultLong(String name) {
- return fPreferences.getDefaultLong(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultString(String name) {
- return fPreferences.getDefaultString(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public double getDouble(String name) {
- return fPreferences.getDouble(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public float getFloat(String name) {
- return fPreferences.getFloat(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInt(String name) {
- return fPreferences.getInt(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public long getLong(String name) {
- return fPreferences.getLong(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getString(String name) {
- return fPreferences.getString(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isDefault(String name) {
- return fPreferences.isDefault(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean needsSaving() {
- return fPreferences.needsSaving();
- }
-
- /**
- * {@inheritDoc}
- */
- public void putValue(String name, String value) {
- try {
- fSilent= true;
- fPreferences.setValue(name, value);
- } finally {
- fSilent= false;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, double value) {
- fPreferences.setDefault(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, float value) {
- fPreferences.setDefault(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, int value) {
- fPreferences.setDefault(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, long value) {
- fPreferences.setDefault(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, String defaultObject) {
- fPreferences.setDefault(name, defaultObject);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefault(String name, boolean value) {
- fPreferences.setDefault(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setToDefault(String name) {
- fPreferences.setToDefault(name);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, double value) {
- fPreferences.setValue(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, float value) {
- fPreferences.setValue(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, int value) {
- fPreferences.setValue(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, long value) {
- fPreferences.setValue(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, String value) {
- fPreferences.setValue(name, value);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String name, boolean value) {
- fPreferences.setValue(name, value);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java
deleted file mode 100644
index 2fff66c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.text.CharacterIterator;
-
-import org.eclipse.core.runtime.Assert;
-
-
-
-/**
- * A <code>CharSequence</code> based implementation of <code>CharacterIterator</code>.
- *
- *
- */
-public class SequenceCharacterIterator implements CharacterIterator {
-
- private int fIndex= -1;
- private final CharSequence fSequence;
- 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 sequence.
- *
- * @param sequence the sequence backing this iterator
- */
- public SequenceCharacterIterator(CharSequence sequence) {
- this(sequence, 0);
- }
-
- /**
- * Creates an iterator.
- *
- * @param sequence the sequence backing this iterator
- * @param first the first character to consider
- * @throws IllegalArgumentException if the indices are out of bounds
- */
- public SequenceCharacterIterator(CharSequence sequence, int first) throws IllegalArgumentException {
- this(sequence, first, sequence.length());
- }
-
- /**
- * Creates an iterator.
- *
- * @param sequence the sequence 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 SequenceCharacterIterator(CharSequence sequence, int first, int last) throws IllegalArgumentException {
- if (sequence == null)
- throw new NullPointerException();
- if (first < 0 || first > last)
- throw new IllegalArgumentException();
- if (last > sequence.length())
- throw new IllegalArgumentException();
- fSequence= sequence;
- fFirst= first;
- fLast= last;
- fIndex= first;
- invariant();
- }
-
- /*
- * @see java.text.CharacterIterator#first()
- */
- public char first() {
- return setIndex(getBeginIndex());
- }
-
- /*
- * @see java.text.CharacterIterator#last()
- */
- public char last() {
- if (fFirst == fLast)
- return setIndex(getEndIndex());
- else
- return setIndex(getEndIndex() - 1);
- }
-
- /*
- * @see java.text.CharacterIterator#current()
- */
- public char current() {
- if (fIndex >= fFirst && fIndex < fLast)
- return fSequence.charAt(fIndex);
- else
- return DONE;
- }
-
- /*
- * @see java.text.CharacterIterator#next()
- */
- public char next() {
- return setIndex(Math.min(fIndex + 1, getEndIndex()));
- }
-
- /*
- * @see java.text.CharacterIterator#previous()
- */
- public char previous() {
- if (fIndex > getBeginIndex()) {
- return setIndex(fIndex - 1);
- } else {
- return DONE;
- }
- }
-
- /*
- * @see java.text.CharacterIterator#setIndex(int)
- */
- public char setIndex(int position) {
- if (position >= getBeginIndex() && position <= getEndIndex())
- fIndex= position;
- else
- throw new IllegalArgumentException();
-
- invariant();
- return current();
- }
-
- /*
- * @see java.text.CharacterIterator#getBeginIndex()
- */
- public int getBeginIndex() {
- return fFirst;
- }
-
- /*
- * @see java.text.CharacterIterator#getEndIndex()
- */
- public int getEndIndex() {
- return fLast;
- }
-
- /*
- * @see java.text.CharacterIterator#getIndex()
- */
- public int getIndex() {
- return fIndex;
- }
-
- /*
- * @see java.text.CharacterIterator#clone()
- */
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new InternalError();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SimpleJavaSourceViewerConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SimpleJavaSourceViewerConfiguration.java
deleted file mode 100644
index 744dc4a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SimpleJavaSourceViewerConfiguration.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IAutoEditStrategy;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
-import org.eclipse.jface.text.information.IInformationPresenter;
-import org.eclipse.jface.text.source.IAnnotationHover;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration;
-
-
-/**
- * A simple {@linkplain org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration Java source viewer configuration}.
- * <p>
- * This simple source viewer configuration basically provides syntax coloring
- * and disables all other features like code assist, quick outlines, hyperlinking, etc.
- * </p>
- *
- *
- */
-public class SimpleJavaSourceViewerConfiguration extends JavaScriptSourceViewerConfiguration {
-
-
- private boolean fConfigureFormatter;
-
- /**
- * Creates a new Java source viewer configuration for viewers in the given editor
- * using the given preference store, the color manager and the specified document partitioning.
- *
- * @param colorManager the color manager
- * @param preferenceStore the preference store, can be read-only
- * @param editor the editor in which the configured viewer(s) will reside, or <code>null</code> if none
- * @param partitioning the document partitioning for this configuration, or <code>null</code> for the default partitioning
- * @param configureFormatter <code>true</code> if a content formatter should be configured
- */
- public SimpleJavaSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, String partitioning, boolean configureFormatter) {
- super(colorManager, preferenceStore, editor, partitioning);
- fConfigureFormatter= configureFormatter;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
- */
- public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
- */
- public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
- */
- public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
- */
- public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
- */
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
- */
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
- */
- public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
- if (fConfigureFormatter)
- return super.getContentFormatter(sourceViewer);
- else
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
- */
- public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
- */
- public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration#getOutlinePresenter(org.eclipse.jface.text.source.ISourceViewer, boolean)
- */
- public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.JavaScriptSourceViewerConfiguration#getHierarchyPresenter(org.eclipse.jface.text.source.ISourceViewer, boolean)
- */
- public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectors(org.eclipse.jface.text.source.ISourceViewer)
- */
- public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SingleTokenJavaScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SingleTokenJavaScanner.java
deleted file mode 100644
index 70d855c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SingleTokenJavaScanner.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-import java.util.List;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-
-
-/**
- *
- */
-public final class SingleTokenJavaScanner extends AbstractJavaScanner{
-
-
- private String[] fProperty;
-
- public SingleTokenJavaScanner(IColorManager manager, IPreferenceStore store, String property) {
- super(manager, store);
- fProperty= new String[] { property };
- initialize();
- }
-
- /*
- * @see AbstractJavaScanner#getTokenProperties()
- */
- protected String[] getTokenProperties() {
- return fProperty;
- }
-
- /*
- * @see AbstractJavaScanner#createRules()
- */
- protected List createRules() {
- setDefaultReturnToken(getToken(fProperty[0]));
- return null;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java
deleted file mode 100644
index 43260176..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.jface.text.TextViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.VerifyKeyListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.internal.ui.text.TypingRun.ChangeType;
-
-
-
-/**
- * Installs as a verify key listener on a viewer and overwrites the behavior
- * of the backspace key. Clients may register undo specifications for certain
- * offsets in a document. The <code>SmartBackspaceManager</code> will manage the
- * specifications and execute the contained <code>TextEdit</code>s when backspace
- * is pressed at the given offset and the specification is still valid.
- * <p>
- * Undo specifications are removed after a number of typing runs.
- * </p>
- *
- *
- */
-public class SmartBackspaceManager {
- /* independent of JDT - may be moved to jface.text */
-
- /**
- * An undo specification describes the change that should be executed if
- * backspace is pressed at its trigger offset.
- *
- *
- */
- public static final class UndoSpec {
- private final int triggerOffset;
- private final IRegion selection;
- private final TextEdit[] undoEdits;
- private final UndoSpec child;
- int lives;
-
- /**
- * Creates a new spec. A specification consists of a number of
- * <code>TextEdit</code>s that will be executed when backspace is
- * pressed at <code>triggerOffset</code>. The spec will be removed
- * when it is executed, or if more than <code>lives</code>
- * <code>TypingRun</code>s have ended after registering the spec.
- * <p>
- * Optionally, a child specification can be registered. After executing
- * the spec, the child spec will be registered with the manager. This allows
- * to create chains of <code>UndoSpec</code>s that will be executed upon
- * repeated pressing of backspace.
- * </p>
- *
- * @param triggerOffset the offset where this spec is active
- * @param selection the selection after executing the undo spec
- * @param edits the <code>TextEdit</code>s to perform when executing
- * the spec
- * @param lives the number of <code>TypingRun</code>s before removing
- * the spec
- * @param child a child specification that will be registered after
- * executing this spec, or <code>null</code>
- */
- public UndoSpec(int triggerOffset, IRegion selection, TextEdit[] edits, int lives, UndoSpec child) {
- Assert.isLegal(triggerOffset >= 0);
- Assert.isLegal(selection != null);
- Assert.isLegal(lives >= 0);
- Assert.isLegal(edits != null);
- Assert.isLegal(edits.length > 0);
- for (int i= 0; i < edits.length; i++) {
- Assert.isLegal(edits[i] != null);
- }
-
- this.triggerOffset= triggerOffset;
- this.selection= selection;
- this.undoEdits= edits;
- this.lives= lives;
- this.child= child;
- }
- }
-
-
- private class BackspaceListener implements VerifyKeyListener {
-
- /*
- * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
- */
- public void verifyKey(VerifyEvent event) {
- if (fViewer != null && isBackspace(event)) {
- int offset= getCaretOffset();
- UndoSpec spec= removeEdit(offset);
- if (spec != null) {
- try {
- beginChange();
- for (int i= 0; i < spec.undoEdits.length; i++) {
- spec.undoEdits[i].apply(getDocument(), TextEdit.UPDATE_REGIONS);
- }
- fViewer.setSelectedRange(spec.selection.getOffset(), spec.selection.getLength());
- if (spec.child != null)
- register(spec.child);
- } catch (MalformedTreeException e) {
- // fall back to standard bs
- return;
- } catch (BadLocationException e) {
- // fall back to standard bs
- return;
- } finally {
- endChange();
- }
- event.doit= false;
- }
-
- }
- }
-
- private void beginChange() {
- ITextViewer viewer= fViewer;
- if (viewer instanceof TextViewer) {
- TextViewer v= (TextViewer) viewer;
- v.getRewriteTarget().beginCompoundChange();
- }
- }
-
- private void endChange() {
- ITextViewer viewer= fViewer;
- if (viewer instanceof TextViewer) {
- TextViewer v= (TextViewer) viewer;
- v.getRewriteTarget().endCompoundChange();
- }
- }
-
- private boolean isBackspace(VerifyEvent event) {
- return event.doit == true && event.character == SWT.BS && event.stateMask == 0;
- }
-
- private int getCaretOffset() {
- ITextViewer viewer= fViewer;
- Point point= viewer.getSelectedRange();
- return point.x;
- }
-
- }
-
- private ITextViewer fViewer;
- private BackspaceListener fBackspaceListener;
- private Map fSpecs;
- private TypingRunDetector fRunDetector;
- private ITypingRunListener fRunListener;
-
- /**
- * Registers an undo specification with this manager.
- *
- * @param spec the specification to register
- * @throws IllegalStateException if the manager is not installed
- */
- public void register(UndoSpec spec) {
- if (fViewer == null)
- throw new IllegalStateException();
-
- ensureListenerInstalled();
- addEdit(spec);
- }
-
- private void addEdit(UndoSpec spec) {
- Integer i= new Integer(spec.triggerOffset);
- fSpecs.put(i, spec);
- }
-
- private UndoSpec removeEdit(int offset) {
- Integer i= new Integer(offset);
- UndoSpec spec= (UndoSpec) fSpecs.remove(i);
- return spec;
- }
-
- private void ensureListenerInstalled() {
- if (fBackspaceListener == null) {
- fBackspaceListener= new BackspaceListener();
- ITextViewer viewer= fViewer;
- if (viewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) viewer).prependVerifyKeyListener(fBackspaceListener);
- else
- viewer.getTextWidget().addVerifyKeyListener(fBackspaceListener);
- }
- }
-
- private void ensureListenerRemoved() {
- if (fBackspaceListener != null) {
- ITextViewer viewer= fViewer;
- if (viewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) viewer).removeVerifyKeyListener(fBackspaceListener);
- else
- viewer.getTextWidget().removeVerifyKeyListener(fBackspaceListener);
- fBackspaceListener= null;
- }
- }
-
- private IDocument getDocument() {
- return fViewer.getDocument();
- }
-
- /**
- * Installs the receiver on a text viewer.
- *
- * @param viewer
- */
- public void install(ITextViewer viewer) {
- Assert.isLegal(viewer != null);
-
- fViewer= viewer;
- fSpecs= new HashMap();
- fRunDetector= new TypingRunDetector();
- fRunDetector.install(viewer);
- fRunListener= new ITypingRunListener() {
-
- /*
- * @see org.eclipse.jface.text.TypingRunDetector.ITypingRunListener#typingRunStarted(org.eclipse.jface.text.TypingRunDetector.TypingRun)
- */
- public void typingRunStarted(TypingRun run) {
- }
-
- /*
- * @see org.eclipse.jface.text.TypingRunDetector.ITypingRunListener#typingRunEnded(org.eclipse.jface.text.TypingRunDetector.TypingRun)
- */
- public void typingRunEnded(TypingRun run, ChangeType reason) {
- if (reason == TypingRun.SELECTION)
- fSpecs.clear();
- else
- prune();
- }
- };
- fRunDetector.addTypingRunListener(fRunListener);
- }
-
- private void prune() {
- for (Iterator it= fSpecs.values().iterator(); it.hasNext();) {
- UndoSpec spec= (UndoSpec) it.next();
- if (--spec.lives < 0)
- it.remove();
- }
- }
-
- /**
- * Uninstalls the receiver. No undo specifications may be registered on an
- * uninstalled manager.
- */
- public void uninstall() {
- if (fViewer != null) {
- fRunDetector.removeTypingRunListener(fRunListener);
- fRunDetector.uninstall();
- fRunDetector= null;
- ensureListenerRemoved();
- fViewer= null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java
deleted file mode 100644
index 4b3bf8f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-/**
- * Symbols for the heuristic java scanner.
- *
- *
- */
-public interface Symbols {
- 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 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 TokenFINALLY= 1021;
- int TokenSYNCHRONIZED= 1022;
- int TokenGOTO= 1023;
- int TokenDEFAULT= 1024;
- int TokenNEW= 1025;
- int TokenCLASS= 1026;
- int TokenINTERFACE= 1027;
- int TokenENUM= 1028;
- int TokenIDENT= 2000;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.java
deleted file mode 100644
index f8e728d0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class TextMessages extends NLS {
-
- private static final String BUNDLE_NAME= TextMessages.class.getName();
-
- private TextMessages() {
- // Do not instantiate
- }
-
- public static String JavaOutlineInformationControl_SortByDefiningTypeAction_label;
- public static String JavaOutlineInformationControl_SortByDefiningTypeAction_tooltip;
- public static String JavaOutlineInformationControl_SortByDefiningTypeAction_description;
- public static String JavaOutlineInformationControl_LexicalSortingAction_label;
- public static String JavaOutlineInformationControl_LexicalSortingAction_tooltip;
- public static String JavaOutlineInformationControl_LexicalSortingAction_description;
- public static String JavaOutlineInformationControl_GoIntoTopLevelType_label;
- public static String JavaOutlineInformationControl_GoIntoTopLevelType_tooltip;
- public static String JavaOutlineInformationControl_GoIntoTopLevelType_description;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, TextMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties
deleted file mode 100644
index 00680b58..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties
+++ /dev/null
@@ -1,25 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-
-JavaOutlineInformationControl_SortByDefiningTypeAction_label= Sort by the Defining &Type
-JavaOutlineInformationControl_SortByDefiningTypeAction_tooltip= Sort Members by the Defining Type
-JavaOutlineInformationControl_SortByDefiningTypeAction_description= Sort members by the defining type
-
-JavaOutlineInformationControl_LexicalSortingAction_label= &Sort
-JavaOutlineInformationControl_LexicalSortingAction_tooltip= Sort
-JavaOutlineInformationControl_LexicalSortingAction_description= Enable Sorting
-
-JavaOutlineInformationControl_GoIntoTopLevelType_label= &Go Into Top Level Type
-JavaOutlineInformationControl_GoIntoTopLevelType_tooltip= Go Into Top Level Type
-JavaOutlineInformationControl_GoIntoTopLevelType_description= Show children of top level type only
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java
deleted file mode 100644
index 99e7f314..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-
-
-/**
- * Describes a run of similar typing changes.
- * <p>
- * XXX to be extended with further information, e.g. offset, length, and
- * content of the run.
- * </p>
- *
- *
- */
-public final class TypingRun {
- /**
- * A change of type <code>DELETE</code> deletes one single character (through delete or
- * backspace or empty paste).
- */
- public static final ChangeType DELETE= new ChangeType(true, "DELETE"); //$NON-NLS-1$
- /**
- * A change of type <code>INSERT</code> inserts one single character
- * (normal typing).
- */
- public static final ChangeType INSERT= new ChangeType(true, "INSERT"); //$NON-NLS-1$
- /**
- * A change of type <code>NO_CHANGE</code> does not change anything.
- */
- public static final ChangeType NO_CHANGE= new ChangeType(false, "NO_CHANGE"); //$NON-NLS-1$
- /**
- * A change of type <code>OVERTYPE</code> replaces one single character
- * (overwrite mode, pasting a single character).
- */
- public static final ChangeType OVERTYPE= new ChangeType(true, "OVERTYPE"); //$NON-NLS-1$
- /**
- * A change of type <code>SELECTION</code> does not change text, but
- * changes the focus, or selection. Such a change ends all typing runs.
- */
- public static final ChangeType SELECTION= new ChangeType(false, "SELECTION"); //$NON-NLS-1$
- /**
- * A change of type <code>UNKNOWN</code> modifies text in an
- * unspecified way. An example is pasting more than one character, or
- * deleting an entire selection, or reverting a file. Such a change ends
- * all typing runs and cannot form a typing run with any other change,
- * including a change of type <code>UNKNOWN</code>.
- */
- public static final ChangeType UNKNOWN= new ChangeType(true, "UNKNOWN"); //$NON-NLS-1$
-
-
- /**
- * Enumeration of change types.
- *
- *
- */
- public static final class ChangeType {
- private final boolean fIsModification;
- private final String fName;
-
- /** Private ctor for type safe enumeration. */
- private ChangeType(boolean isRunPart, String name) {
- fIsModification= isRunPart;
- fName= name;
- }
-
- /**
- * Returns <code>true</code> if changes of this type modify text.
- *
- * @return <code>true</code> if changes of this type modify text,
- * <code>false</code> otherwise
- */
- boolean isModification() {
- return fIsModification;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fName;
- }
- }
-
- /**
- * Creates a new run.
- *
- * @param type the type of the run
- */
- TypingRun(ChangeType type) {
- this.type= type;
- }
-
- /** The change type of this run. */
- public final ChangeType type;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java
deleted file mode 100644
index 9aa5bec2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java
+++ /dev/null
@@ -1,469 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.ITextListener;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.wst.jsdt.internal.ui.text.TypingRun.ChangeType;
-
-
-/**
- * When connected to a text viewer, a <code>TypingRunDetector</code> observes
- * <code>TypingRun</code> events. A typing run is a sequence of similar text
- * modifications, such as inserting or deleting single characters.
- * <p>
- * Listeners are informed about the start and end of a <code>TypingRun</code>.
- * </p>
- *
- *
- */
-public class TypingRunDetector {
- /*
- * Implementation note: This class is independent of JDT and may be pulled
- * up to jface.text if needed.
- */
-
- /** Debug flag. */
- private static final boolean DEBUG= false;
-
- /**
- * Instances of this class abstract a text modification into a simple
- * description. Typing runs consists of a sequence of one or more modifying
- * changes of the same type. Every change records the type of change
- * described by a text modification, and an offset it can be followed by
- * another change of the same run.
- */
- private static final class Change {
- private ChangeType fType;
- private int fNextOffset;
-
- /**
- * Creates a new change of type <code>type</code>.
- *
- * @param type the <code>ChangeType</code> of the new change
- * @param nextOffset the offset of the next change in a typing run
- */
- public Change(ChangeType type, int nextOffset) {
- fType= type;
- fNextOffset= nextOffset;
- }
-
- /**
- * Returns <code>true</code> if the receiver can extend the typing run
- * the last change of which is described by <code>change</code>.
- *
- * @param change the last change in a typing run
- * @return <code>true</code> if the receiver is a valid extension to
- * <code>change</code>, <code>false</code> otherwise
- */
- public boolean canFollow(Change change) {
- if (fType == TypingRun.NO_CHANGE)
- return true;
- if (fType.equals(TypingRun.UNKNOWN))
- return false;
- if (fType.equals(change.fType)) {
- if (fType == TypingRun.DELETE)
- return fNextOffset == change.fNextOffset - 1;
- else if (fType == TypingRun.INSERT)
- return fNextOffset == change.fNextOffset + 1;
- else if (fType == TypingRun.OVERTYPE)
- return fNextOffset == change.fNextOffset + 1;
- else if (fType == TypingRun.SELECTION)
- return true;
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if the receiver describes a text
- * modification, <code>false</code> if it describes a focus /
- * selection change.
- *
- * @return <code>true</code> if the receiver is a text modification
- */
- public boolean isModification() {
- return fType.isModification();
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fType.toString() + "@" + fNextOffset; //$NON-NLS-1$
- }
-
- /**
- * Returns the change type of this change.
- *
- * @return the change type of this change
- */
- public ChangeType getType() {
- return fType;
- }
- }
-
- /**
- * Observes any events that modify the content of the document displayed in
- * the editor. Since text events may start a new run, this listener is
- * always registered if the detector is connected.
- */
- private class TextListener implements ITextListener {
-
- /*
- * @see org.eclipse.jface.text.ITextListener#textChanged(org.eclipse.jface.text.TextEvent)
- */
- public void textChanged(TextEvent event) {
- handleTextChanged(event);
- }
- }
-
- /**
- * Observes non-modifying events that will end a run, such as clicking into
- * the editor, moving the caret, and the editor losing focus. These events
- * can never start a run, therefore this listener is only registered if
- * there is an ongoing run.
- */
- private class SelectionListener implements MouseListener, KeyListener, FocusListener {
-
- /*
- * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
- */
- public void focusGained(FocusEvent e) {
- handleSelectionChanged();
- }
-
- /*
- * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
- */
- public void focusLost(FocusEvent e) {
- }
-
- /*
- * @see MouseListener#mouseDoubleClick
- */
- public void mouseDoubleClick(MouseEvent e) {
- }
-
- /*
- * If the right mouse button is pressed, the current editing command is closed
- * @see MouseListener#mouseDown
- */
- public void mouseDown(MouseEvent e) {
- if (e.button == 1)
- handleSelectionChanged();
- }
-
- /*
- * @see MouseListener#mouseUp
- */
- public void mouseUp(MouseEvent e) {
- }
-
- /*
- * @see KeyListener#keyPressed
- */
- public void keyReleased(KeyEvent e) {
- }
-
- /*
- * On cursor keys, the current editing command is closed
- * @see KeyListener#keyPressed
- */
- public void keyPressed(KeyEvent e) {
- switch (e.keyCode) {
- case SWT.ARROW_UP:
- case SWT.ARROW_DOWN:
- case SWT.ARROW_LEFT:
- case SWT.ARROW_RIGHT:
- case SWT.END:
- case SWT.HOME:
- case SWT.PAGE_DOWN:
- case SWT.PAGE_UP:
- handleSelectionChanged();
- break;
- }
- }
- }
-
- /** The listeners. */
- private final Set fListeners= new HashSet();
- /**
- * The viewer we work upon. Set to <code>null</code> in
- * <code>uninstall</code>.
- */
- private ITextViewer fViewer;
- /** The text event listener. */
- private final TextListener fTextListener= new TextListener();
- /**
- * The selection listener. Set to <code>null</code> when no run is active.
- */
- private SelectionListener fSelectionListener;
-
- /* state variables */
-
- /** The most recently observed change. Never <code>null</code>. */
- private Change fLastChange;
- /** The current run, or <code>null</code> if there is none. */
- private TypingRun fRun;
-
- /**
- * Installs the receiver with a text viewer.
- *
- * @param viewer the viewer to install on
- */
- public void install(ITextViewer viewer) {
- Assert.isLegal(viewer != null);
- fViewer= viewer;
- connect();
- }
-
- /**
- * Initializes the state variables and registers any permanent listeners.
- */
- private void connect() {
- if (fViewer != null) {
- fLastChange= new Change(TypingRun.UNKNOWN, -1);
- fRun= null;
- fSelectionListener= null;
- fViewer.addTextListener(fTextListener);
- }
- }
-
- /**
- * Uninstalls the receiver and removes all listeners. <code>install()</code>
- * must be called for events to be generated.
- */
- public void uninstall() {
- if (fViewer != null) {
- fListeners.clear();
- disconnect();
- fViewer= null;
- }
- }
-
- /**
- * Disconnects any registered listeners.
- */
- private void disconnect() {
- fViewer.removeTextListener(fTextListener);
- ensureSelectionListenerRemoved();
- }
-
- /**
- * Adds a listener for <code>TypingRun</code> events. Repeatedly adding
- * the same listener instance has no effect. Listeners may be added even
- * if the receiver is neither connected nor installed.
- *
- * @param listener the listener add
- */
- public void addTypingRunListener(ITypingRunListener listener) {
- Assert.isLegal(listener != null);
- fListeners.add(listener);
- if (fListeners.size() == 1)
- connect();
- }
-
- /**
- * Removes the listener from this manager. If <code>listener</code> is not
- * registered with the receiver, nothing happens.
- *
- * @param listener the listener to remove, or <code>null</code>
- */
- public void removeTypingRunListener(ITypingRunListener listener) {
- fListeners.remove(listener);
- if (fListeners.size() == 0)
- disconnect();
- }
-
- /**
- * Handles an incoming text event.
- *
- * @param event the text event that describes the text modification
- */
- void handleTextChanged(TextEvent event) {
- Change type= computeChange(event);
- handleChange(type);
- }
-
- /**
- * Computes the change abstraction given a text event.
- *
- * @param event the text event to analyze
- * @return a change object describing the event
- */
- private Change computeChange(TextEvent event) {
- DocumentEvent e= event.getDocumentEvent();
- if (e == null)
- return new Change(TypingRun.NO_CHANGE, -1);
-
- int start= e.getOffset();
- int end= e.getOffset() + e.getLength();
- String newText= e.getText();
- if (newText == null)
- newText= new String();
-
- if (start == end) {
- // no replace / delete / overwrite
- if (newText.length() == 1)
- return new Change(TypingRun.INSERT, end + 1);
- } else if (start == end - 1) {
- if (newText.length() == 1)
- return new Change(TypingRun.OVERTYPE, end);
- if (newText.length() == 0)
- return new Change(TypingRun.DELETE, start);
- }
-
- return new Change(TypingRun.UNKNOWN, -1);
- }
-
- /**
- * Handles an incoming selection event.
- */
- void handleSelectionChanged() {
- handleChange(new Change(TypingRun.SELECTION, -1));
- }
-
- /**
- * State machine. Changes state given the current state and the incoming
- * change.
- *
- * @param change the incoming change
- */
- private void handleChange(Change change) {
- if (change.getType() == TypingRun.NO_CHANGE)
- return;
-
- if (DEBUG)
- System.err.println("Last change: " + fLastChange); //$NON-NLS-1$
-
- if (!change.canFollow(fLastChange))
- endIfStarted(change);
- fLastChange= change;
- if (change.isModification())
- startOrContinue();
-
- if (DEBUG)
- System.err.println("New change: " + change); //$NON-NLS-1$
- }
-
- /**
- * Starts a new run if there is none and informs all listeners. If there
- * already is a run, nothing happens.
- */
- private void startOrContinue() {
- if (!hasRun()) {
- if (DEBUG)
- System.err.println("+Start run"); //$NON-NLS-1$
- fRun= new TypingRun(fLastChange.getType());
- ensureSelectionListenerAdded();
- fireRunBegun(fRun);
- }
- }
-
- /**
- * Returns <code>true</code> if there is an active run, <code>false</code>
- * otherwise.
- *
- * @return <code>true</code> if there is an active run, <code>false</code>
- * otherwise
- */
- private boolean hasRun() {
- return fRun != null;
- }
-
- /**
- * Ends any active run and informs all listeners. If there is none, nothing
- * happens.
- *
- * @param change the change that triggered ending the active run
- */
- private void endIfStarted(Change change) {
- if (hasRun()) {
- ensureSelectionListenerRemoved();
- if (DEBUG)
- System.err.println("-End run"); //$NON-NLS-1$
- fireRunEnded(fRun, change.getType());
- fRun= null;
- }
- }
-
- /**
- * Adds the selection listener to the text widget underlying the viewer, if
- * not already done.
- */
- private void ensureSelectionListenerAdded() {
- if (fSelectionListener == null) {
- fSelectionListener= new SelectionListener();
- StyledText textWidget= fViewer.getTextWidget();
- textWidget.addFocusListener(fSelectionListener);
- textWidget.addKeyListener(fSelectionListener);
- textWidget.addMouseListener(fSelectionListener);
- }
- }
-
- /**
- * If there is a selection listener, it is removed from the text widget
- * underlying the viewer.
- */
- private void ensureSelectionListenerRemoved() {
- if (fSelectionListener != null) {
- StyledText textWidget= fViewer.getTextWidget();
- textWidget.removeFocusListener(fSelectionListener);
- textWidget.removeKeyListener(fSelectionListener);
- textWidget.removeMouseListener(fSelectionListener);
- fSelectionListener= null;
- }
- }
-
- /**
- * Informs all listeners about a newly started <code>TypingRun</code>.
- *
- * @param run the new run
- */
- private void fireRunBegun(TypingRun run) {
- List listeners= new ArrayList(fListeners);
- for (Iterator it= listeners.iterator(); it.hasNext();) {
- ITypingRunListener listener= (ITypingRunListener) it.next();
- listener.typingRunStarted(fRun);
- }
- }
-
- /**
- * Informs all listeners about an ended <code>TypingRun</code>.
- *
- * @param run the previously active run
- * @param reason the type of change that caused the run to be ended
- */
- private void fireRunEnded(TypingRun run, ChangeType reason) {
- List listeners= new ArrayList(fListeners);
- for (Iterator it= listeners.iterator(); it.hasNext();) {
- ITypingRunListener listener= (ITypingRunListener) it.next();
- listener.typingRunEnded(fRun, reason);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java
deleted file mode 100644
index 63cfb864..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.comment;
-
-import org.eclipse.jface.text.formatter.FormattingContext;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-
-/**
- * Formatting context for the comment formatter.
- *
- *
- */
-public class CommentFormattingContext extends FormattingContext {
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingContext#getPreferenceKeys()
- */
- public String[] getPreferenceKeys() {
- return new String[] {
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_PARAMETER_DESCRIPTION,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_INDENT_ROOT_TAGS,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_NEW_LINE_FOR_PARAMETER,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_INSERT_EMPTY_LINE_BEFORE_ROOT_TAGS,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_BLOCK_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES_IN_JAVADOC_COMMENT,
- DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML }; }
-
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingContext#isBooleanPreference(java.lang.String)
- */
- public boolean isBooleanPreference(String key) {
- return !key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingContext#isIntegerPreference(java.lang.String)
- */
- public boolean isIntegerPreference(String key) {
- return key.equals(DefaultCodeFormatterConstants.FORMATTER_COMMENT_LINE_LENGTH);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingStrategy.java
deleted file mode 100644
index 201b1e52..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingStrategy.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.comment;
-
-import java.util.LinkedList;
-import java.util.Map;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Formatting strategy for general source code comments.
- *
- *
- */
-public class CommentFormattingStrategy extends ContextBasedFormattingStrategy {
-
- /** Documents to be formatted by this strategy */
- private final LinkedList fDocuments= new LinkedList();
-
- /** Partitions to be formatted by this strategy */
- private final LinkedList fPartitions= new LinkedList();
-
- /** Last formatted document's hash-code. */
- private int fLastDocumentHash;
-
- /** Last formatted document header's hash-code. */
- private int fLastHeaderHash;
-
- /** End of the first class or interface token in the last document. */
- private int fLastMainTokenEnd= -1;
-
- /** End of the header in the last document. */
- private int fLastDocumentsHeaderEnd;
-
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingStrategyExtension#format()
- */
- public void format() {
-
- final IDocument document= (IDocument) fDocuments.getFirst();
-
- TextEdit edit= calculateTextEdit();
- if (edit == null)
- return;
-
- try {
- edit.apply(document);
- } catch (MalformedTreeException x) {
- JavaScriptPlugin.log(x);
- } catch (BadLocationException x) {
- JavaScriptPlugin.log(x);
- }
- }
-
- /**
- * Calculates the <code>TextEdit</code> used to format the region with the
- * properties indicated in the formatting context previously supplied by
- * <code>formatterStarts(IFormattingContext)</code>.
- *
- * @see CommentFormattingStrategy#format()
- * @return A <code>TextEdit</code>, or <code>null</code> if no formating is required
- *
- */
- public TextEdit calculateTextEdit() {
- super.format();
-
- final IDocument document= (IDocument) fDocuments.removeFirst();
- final TypedPosition position= (TypedPosition)fPartitions.removeFirst();
- if (document == null || position == null)
- return null;
-
- Map preferences= getPreferences();
- final boolean isFormattingHeader= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER));
- int documentsHeaderEnd= computeHeaderEnd(document, preferences);
-
- TextEdit edit= null;
- if (position.offset >= documentsHeaderEnd) {
- // not a header
- try {
- // compute offset in document of region passed to the formatter
- int sourceOffset= document.getLineOffset(document.getLineOfOffset(position.getOffset()));
-
- // format region
- int partitionOffset= position.getOffset() - sourceOffset;
- int sourceLength= partitionOffset + position.getLength();
- String source= document.get(sourceOffset, sourceLength);
- CodeFormatter commentFormatter= ToolFactory.createCodeFormatter(preferences, ToolFactory.M_FORMAT_EXISTING);
- int indentationLevel= inferIndentationLevel(source.substring(0, partitionOffset), getTabSize(preferences), getIndentSize(preferences));
- edit= commentFormatter.format(getKindForPartitionType(position.getType()), source, partitionOffset, position.getLength(), indentationLevel, TextUtilities.getDefaultLineDelimiter(document));
-
- // move edit offset to match document
- if (edit != null)
- edit.moveTree(sourceOffset);
- } catch (BadLocationException x) {
- JavaScriptPlugin.log(x);
- }
- } else if (isFormattingHeader) {
- boolean wasJavaDoc= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT));
- if (!wasJavaDoc)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, DefaultCodeFormatterConstants.TRUE);
-
- boolean wasBlockComment= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT));
- if (!wasBlockComment)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT, DefaultCodeFormatterConstants.TRUE);
-
- boolean wasLineComment= DefaultCodeFormatterConstants.TRUE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT));
- if (!wasLineComment)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, DefaultCodeFormatterConstants.TRUE);
-
- try {
- // compute offset in document of region passed to the formatter
- int sourceOffset= document.getLineOffset(document.getLineOfOffset(position.getOffset()));
-
- // format region
- int partitionOffset= position.getOffset() - sourceOffset;
- int sourceLength= partitionOffset + position.getLength();
- String source= document.get(sourceOffset, sourceLength);
- CodeFormatter commentFormatter= ToolFactory.createCodeFormatter(preferences);
- int indentationLevel= inferIndentationLevel(source.substring(0, partitionOffset), getTabSize(preferences), getIndentSize(preferences));
- edit= commentFormatter.format(getKindForPartitionType(position.getType()), source, partitionOffset, position.getLength(), indentationLevel, TextUtilities.getDefaultLineDelimiter(document));
-
- // move edit offset to match document
- if (edit != null)
- edit.moveTree(sourceOffset);
- } catch (BadLocationException x) {
- JavaScriptPlugin.log(x);
- } finally {
- if (!wasJavaDoc)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, DefaultCodeFormatterConstants.FALSE);
- if (!wasBlockComment)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT, DefaultCodeFormatterConstants.FALSE);
- if (!wasLineComment)
- preferences.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, DefaultCodeFormatterConstants.FALSE);
- }
-
- }
- return edit;
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingStrategyExtension#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
- */
- public void formatterStarts(IFormattingContext context) {
- super.formatterStarts(context);
-
- fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
- fDocuments.addLast(context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM));
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.IFormattingStrategyExtension#formatterStops()
- */
- public void formatterStops() {
- fPartitions.clear();
- fDocuments.clear();
-
- super.formatterStops();
- }
-
- /**
- * Map from {@link IJavaScriptPartitions}comment partition types to
- * {@link CodeFormatter}code snippet kinds.
- *
- * @param type the partition type
- * @return the code snippet kind
- *
- */
- private static int getKindForPartitionType(String type) {
- if (IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT.equals(type))
- return CodeFormatter.K_SINGLE_LINE_COMMENT;
- if (IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(type))
- return CodeFormatter.K_MULTI_LINE_COMMENT;
- if (IJavaScriptPartitions.JAVA_DOC.equals(type))
- return CodeFormatter.K_JAVA_DOC;
- return CodeFormatter.K_UNKNOWN;
- }
-
- /**
- * Infer the indentation level based on the given reference indentation
- * and tab size.
- *
- * @param reference the reference indentation
- * @param tabSize the tab size
- * @param indentSize the indent size in space equivalents
- * @return the inferred indentation level
- *
- */
- private int inferIndentationLevel(String reference, int tabSize, int indentSize) {
- StringBuffer expanded= expandTabs(reference, tabSize);
-
- int referenceWidth= expanded.length();
- if (tabSize == 0)
- return referenceWidth;
-
- int level= referenceWidth / indentSize;
- if (referenceWidth % indentSize > 0)
- level++;
- return level;
- }
-
- /**
- * Expands the given string's tabs according to the given tab size.
- *
- * @param string the string
- * @param tabSize the tab size
- * @return the expanded string
- *
- */
- private static StringBuffer expandTabs(String string, int tabSize) {
- StringBuffer expanded= new StringBuffer();
- for (int i= 0, n= string.length(), chars= 0; i < n; i++) {
- char ch= string.charAt(i);
- if (ch == '\t') {
- for (; chars < tabSize; chars++)
- expanded.append(' ');
- chars= 0;
- } else {
- expanded.append(ch);
- chars++;
- if (chars >= tabSize)
- chars= 0;
- }
-
- }
- return expanded;
- }
-
- /**
- * Returns the visual tab size.
- *
- * @param preferences the preferences
- * @return the visual tab size
- *
- */
- private static int getTabSize(Map preferences) {
- /*
- * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used
- * by the core formatter.
- * We piggy back the visual tab length setting in that preference in
- * that case. See CodeFormatterUtil.
- */
- String key;
- if (JavaScriptCore.SPACE.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
- key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
- else
- key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
-
- if (preferences.containsKey(key))
- try {
- return Integer.parseInt((String) preferences.get(key));
- } catch (NumberFormatException e) {
- // use default
- }
- return 4;
- }
-
- /**
- * Returns the indentation size in space equivalents.
- *
- * @param preferences the preferences
- * @return the indentation size in space equivalents
- *
- */
- private static int getIndentSize(Map preferences) {
- /*
- * FORMATTER_INDENTATION_SIZE is only used if FORMATTER_TAB_CHAR is MIXED. Otherwise, the
- * indentation size is in FORMATTER_TAB_CHAR. See CodeFormatterUtil.
- */
- String key;
- if (DefaultCodeFormatterConstants.MIXED.equals(preferences.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
- key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
- else
- key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
-
- if (preferences.containsKey(key))
- try {
- return Integer.parseInt((String) preferences.get(key));
- } catch (NumberFormatException e) {
- // use default
- }
- return 4;
- }
-
- /**
- * Returns the end offset for the document's header.
- *
- * @param document the document
- * @param preferences the given preferences to format
- * @return the header's end offset
- */
- private int computeHeaderEnd(IDocument document, Map preferences) {
- if (document == null)
- return -1;
-
- try {
- if (fLastMainTokenEnd >= 0 && document.hashCode() == fLastDocumentHash && fLastMainTokenEnd < document.getLength() && document.get(0, fLastMainTokenEnd).hashCode() == fLastHeaderHash)
- return fLastDocumentsHeaderEnd;
- } catch (BadLocationException e) {
- // should not happen -> recompute
- }
-
- IScanner scanner= ToolFactory.createScanner(true, false, false, (String) preferences.get(JavaScriptCore.COMPILER_SOURCE), (String) preferences.get(JavaScriptCore.COMPILER_COMPLIANCE));
- scanner.setSource(document.get().toCharArray());
-
- try {
- int offset= -1;
- boolean foundComment= false;
- int terminal= scanner.getNextToken();
- while (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal== ITerminalSymbols.TokenNameWHITESPACE ||
- terminal == ITerminalSymbols.TokenNameCOMMENT_LINE || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK)
- {
-
- if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC)
- offset= scanner.getCurrentTokenStartPosition();
-
- foundComment= terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK;
-
- terminal= scanner.getNextToken();
- }
-
- int mainTokenEnd= scanner.getCurrentTokenEndPosition();
- if (terminal != ITerminalSymbols.TokenNameEOF) {
- mainTokenEnd++;
- if (offset == -1 || (foundComment && (terminal == ITerminalSymbols.TokenNameimport || terminal == ITerminalSymbols.TokenNamepackage)))
- offset= scanner.getCurrentTokenStartPosition();
- } else
- offset= -1;
-
- try {
- fLastHeaderHash= document.get(0, mainTokenEnd).hashCode();
- } catch (BadLocationException e) {
- // should not happen -> recompute next time
- mainTokenEnd= -1;
- }
-
- fLastDocumentHash= document.hashCode();
- fLastMainTokenEnd= mainTokenEnd;
- fLastDocumentsHeaderEnd= offset;
- return offset;
-
- } catch (InvalidInputException ex) {
- // enable formatting
- return -1;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTResolving.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTResolving.java
deleted file mode 100644
index f8d23252..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTResolving.java
+++ /dev/null
@@ -1,930 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayAccess;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.QualifiedType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TypeLiteral;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType.Code;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.dom.TypeBindingVisitor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ASTResolving {
-
- public static ITypeBinding guessBindingForReference(ASTNode node) {
- return Bindings.normalizeTypeBinding(getPossibleReferenceBinding(node));
- }
-
- private static ITypeBinding getPossibleReferenceBinding(ASTNode node) {
- ASTNode parent= node.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.ASSIGNMENT:
- Assignment assignment= (Assignment) parent;
- if (node.equals(assignment.getLeftHandSide())) {
- // field write access: xx= expression
- return assignment.getRightHandSide().resolveTypeBinding();
- }
- // read access
- return assignment.getLeftHandSide().resolveTypeBinding();
- case ASTNode.INFIX_EXPRESSION:
- InfixExpression infix= (InfixExpression) parent;
- InfixExpression.Operator op= infix.getOperator();
- if (op == InfixExpression.Operator.CONDITIONAL_AND || op == InfixExpression.Operator.CONDITIONAL_OR) {
- // boolean operation
- return infix.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
- } else if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED || op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) {
- // asymmetric operation
- return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- }
- if (node.equals(infix.getLeftOperand())) {
- // xx operation expression
- ITypeBinding rigthHandBinding= infix.getRightOperand().resolveTypeBinding();
- if (rigthHandBinding != null) {
- return rigthHandBinding;
- }
- } else {
- // expression operation xx
- ITypeBinding leftHandBinding= infix.getLeftOperand().resolveTypeBinding();
- if (leftHandBinding != null) {
- return leftHandBinding;
- }
- }
- if (op != InfixExpression.Operator.EQUALS && op != InfixExpression.Operator.NOT_EQUALS) {
- return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- }
- break;
- case ASTNode.INSTANCEOF_EXPRESSION:
- InstanceofExpression instanceofExpression= (InstanceofExpression) parent;
- return instanceofExpression.getRightOperand().resolveBinding();
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
- if (frag.getInitializer().equals(node)) {
- return frag.getName().resolveTypeBinding();
- }
- break;
- case ASTNode.SUPER_METHOD_INVOCATION:
- SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent;
- IFunctionBinding superMethodBinding= ASTNodes.getMethodBinding(superMethodInvocation.getName());
- if (superMethodBinding != null) {
- return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding);
- }
- break;
- case ASTNode.FUNCTION_INVOCATION:
- FunctionInvocation methodInvocation= (FunctionInvocation) parent;
- IFunctionBinding methodBinding= methodInvocation.resolveMethodBinding();
- if (methodBinding != null) {
- return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding);
- }
- break;
- case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: {
- SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent;
- IFunctionBinding superBinding= superInvocation.resolveConstructorBinding();
- if (superBinding != null) {
- return getParameterTypeBinding(node, superInvocation.arguments(), superBinding);
- }
- break;
- }
- case ASTNode.CONSTRUCTOR_INVOCATION: {
- ConstructorInvocation constrInvocation= (ConstructorInvocation) parent;
- IFunctionBinding constrBinding= constrInvocation.resolveConstructorBinding();
- if (constrBinding != null) {
- return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding);
- }
- break;
- }
- case ASTNode.CLASS_INSTANCE_CREATION: {
- ClassInstanceCreation creation= (ClassInstanceCreation) parent;
- IFunctionBinding creationBinding= creation.resolveConstructorBinding();
- if (creationBinding != null) {
- return getParameterTypeBinding(node, creation.arguments(), creationBinding);
- }
- break;
- }
- case ASTNode.PARENTHESIZED_EXPRESSION:
- return guessBindingForReference(parent);
- case ASTNode.ARRAY_ACCESS:
- if (((ArrayAccess) parent).getIndex().equals(node)) {
- return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- } else {
- return getPossibleReferenceBinding(parent);
- }
- case ASTNode.ARRAY_CREATION:
- if (((ArrayCreation) parent).dimensions().contains(node)) {
- return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- }
- break;
- case ASTNode.ARRAY_INITIALIZER:
- ASTNode initializerParent= parent.getParent();
- int dim= 1;
- while (initializerParent instanceof ArrayInitializer) {
- initializerParent= initializerParent.getParent();
- dim++;
- }
- Type creationType= null;
- if (initializerParent instanceof ArrayCreation) {
- creationType= ((ArrayCreation) initializerParent).getType();
- } else if (initializerParent instanceof VariableDeclaration) {
- VariableDeclaration varDecl= (VariableDeclaration) initializerParent;
- creationType= ASTNodes.getType(varDecl);
- dim-= varDecl.getExtraDimensions();
- }
- if (creationType != null) {
- while ((creationType instanceof ArrayType) && dim > 0) {
- creationType= ((ArrayType) creationType).getComponentType();
- dim--;
- }
- return creationType.resolveBinding();
- }
- break;
- case ASTNode.CONDITIONAL_EXPRESSION:
- ConditionalExpression expression= (ConditionalExpression) parent;
- if (node.equals(expression.getExpression())) {
- return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
- }
- if (node.equals(expression.getElseExpression())) {
- return expression.getThenExpression().resolveTypeBinding();
- }
- return expression.getElseExpression().resolveTypeBinding();
- case ASTNode.POSTFIX_EXPRESSION:
- return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- case ASTNode.PREFIX_EXPRESSION:
- if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) {
- return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
- }
- return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- case ASTNode.IF_STATEMENT:
- case ASTNode.WHILE_STATEMENT:
- case ASTNode.DO_STATEMENT:
- if (node instanceof Expression) {
- return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
- }
- break;
- case ASTNode.SWITCH_STATEMENT:
- if (((SwitchStatement) parent).getExpression().equals(node)) {
- return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
- }
- break;
- case ASTNode.RETURN_STATEMENT:
- FunctionDeclaration decl= ASTResolving.findParentMethodDeclaration(parent);
- if (decl != null && !decl.isConstructor()) {
- return decl.getReturnType2().resolveBinding();
- }
- break;
- case ASTNode.THROW_STATEMENT:
- case ASTNode.CATCH_CLAUSE:
- return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
- case ASTNode.FIELD_ACCESS:
- if (node.equals(((FieldAccess) parent).getName())) {
- return getPossibleReferenceBinding(parent);
- }
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- return getPossibleReferenceBinding(parent);
- case ASTNode.QUALIFIED_NAME:
- if (node.equals(((QualifiedName) parent).getName())) {
- return getPossibleReferenceBinding(parent);
- }
- break;
- case ASTNode.SWITCH_CASE:
- if (node.equals(((SwitchCase) parent).getExpression()) && parent.getParent() instanceof SwitchStatement) {
- return ((SwitchStatement) parent.getParent()).getExpression().resolveTypeBinding();
- }
- break;
- default:
- // do nothing
- }
-
- return null;
- }
-
- public static Type guessTypeForReference(AST ast, ASTNode node) {
- ASTNode parent= node.getParent();
- while (parent != null) {
- switch (parent.getNodeType()) {
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- if (((VariableDeclarationFragment) parent).getInitializer() == node) {
- return ASTNodeFactory.newType(ast, (VariableDeclaration) parent);
- }
- return null;
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- if (((VariableDeclarationFragment) parent).getInitializer() == node) {
- return ASTNodeFactory.newType(ast, (VariableDeclaration) parent);
- }
- return null;
- case ASTNode.ARRAY_ACCESS:
- if (!((ArrayAccess) parent).getIndex().equals(node)) {
- Type type= guessTypeForReference(ast, parent);
- if (type != null) {
- return ast.newArrayType(type);
- }
- }
- return null;
- case ASTNode.FIELD_ACCESS:
- if (node.equals(((FieldAccess) parent).getName())) {
- node= parent;
- parent= parent.getParent();
- } else {
- return null;
- }
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- case ASTNode.PARENTHESIZED_EXPRESSION:
- node= parent;
- parent= parent.getParent();
- break;
- case ASTNode.QUALIFIED_NAME:
- if (node.equals(((QualifiedName) parent).getName())) {
- node= parent;
- parent= parent.getParent();
- } else {
- return null;
- }
- break;
- default:
- return null;
- }
- }
- return null;
- }
-
- private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IFunctionBinding binding) {
- ITypeBinding[] paramTypes= binding.getParameterTypes();
- int index= args.indexOf(node);
- if (binding.isVarargs() && index >= paramTypes.length - 1) {
- return paramTypes[paramTypes.length - 1].getComponentType();
- }
- if (index >= 0 && index < paramTypes.length) {
- return paramTypes[index];
- }
- return null;
- }
-
- public static ITypeBinding guessBindingForTypeReference(ASTNode node) {
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent == QualifiedName.QUALIFIER_PROPERTY) {
- return null; // can't guess type for X.A
- }
- if (locationInParent == SimpleType.NAME_PROPERTY) {
- node= node.getParent();
- }
- ITypeBinding binding= Bindings.normalizeTypeBinding(getPossibleTypeBinding(node));
- return binding;
- }
-
- private static ITypeBinding getPossibleTypeBinding(ASTNode node) {
- ASTNode parent= node.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.ARRAY_TYPE: {
- int dim= 1;
- while (parent.getParent() instanceof ArrayType) {
- parent= parent.getParent();
- dim++;
- }
- ITypeBinding parentBinding= getPossibleTypeBinding(parent);
- if (parentBinding != null && parentBinding.getDimensions() == dim) {
- return parentBinding.getElementType();
- }
- return null;
- }
- case ASTNode.QUALIFIED_TYPE: {
- ITypeBinding parentBinding= getPossibleTypeBinding(parent);
- if (parentBinding == null || !parentBinding.isMember()) {
- return null;
- }
- if (node.getLocationInParent() == QualifiedType.QUALIFIER_PROPERTY) {
- return parentBinding.getDeclaringClass();
- }
- return parentBinding;
- }
- case ASTNode.VARIABLE_DECLARATION_STATEMENT:
- return guessVariableType(((VariableDeclarationStatement) parent).fragments());
- case ASTNode.FIELD_DECLARATION:
- return guessVariableType(((FieldDeclaration) parent).fragments());
- case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
- return guessVariableType(((VariableDeclarationExpression) parent).fragments());
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- SingleVariableDeclaration varDecl= (SingleVariableDeclaration) parent;
- if (varDecl.getInitializer() != null) {
- return Bindings.normalizeTypeBinding(varDecl.getInitializer().resolveTypeBinding());
- }
- break;
- case ASTNode.ARRAY_CREATION:
- ArrayCreation creation= (ArrayCreation) parent;
- if (creation.getInitializer() != null) {
- return creation.getInitializer().resolveTypeBinding();
- }
- return getPossibleReferenceBinding(parent);
- case ASTNode.TYPE_LITERAL:
- return ((TypeLiteral) parent).getType().resolveBinding();
- case ASTNode.CLASS_INSTANCE_CREATION:
- return getPossibleReferenceBinding(parent);
- case ASTNode.TAG_ELEMENT:
- TagElement tagElement= (TagElement) parent;
- if (TagElement.TAG_THROWS.equals(tagElement.getTagName()) || TagElement.TAG_EXCEPTION.equals(tagElement.getTagName())) {
- ASTNode methNode= tagElement.getParent().getParent();
- if (methNode instanceof FunctionDeclaration) {
- List thrownExcpetions= ((FunctionDeclaration) methNode).thrownExceptions();
- if (thrownExcpetions.size() == 1) {
- return ((Name) thrownExcpetions.get(0)).resolveTypeBinding();
- }
- }
- }
- break;
- }
- return null;
- }
-
- private static ITypeBinding guessVariableType(List fragments) {
- for (Iterator iter= fragments.iterator(); iter.hasNext();) {
- VariableDeclarationFragment frag= (VariableDeclarationFragment) iter.next();
- if (frag.getInitializer() != null) {
- return Bindings.normalizeTypeBinding(frag.getInitializer().resolveTypeBinding());
- }
- }
- return null;
- }
-
- /**
- * Finds all type bindings that contain a method of a given signature
- * @param searchRoot the ast node to start the search from
- * @param selector the method name
- * @param arguments the method arguments
- * @param context the context in which the method would be called
- * @return returns all types known in the AST that have a method with a given name
- */
- public static ITypeBinding[] getQualifierGuess(ASTNode searchRoot, final String selector, List arguments, final IBinding context) {
- final int nArgs= arguments.size();
- final ArrayList result= new ArrayList();
-
- // test if selector is a object method
- ITypeBinding binding= searchRoot.getAST().resolveWellKnownType("Object"); //$NON-NLS-1$
- IFunctionBinding[] objectMethods= binding.getDeclaredMethods();
- for (int i= 0; i < objectMethods.length; i++) {
- IFunctionBinding meth= objectMethods[i];
- if (meth.getName().equals(selector) && meth.getParameterTypes().length == nArgs) {
- return new ITypeBinding[] { binding };
- }
- }
-
- visitAllBindings(searchRoot, new TypeBindingVisitor() {
- private HashSet fVisitedBindings= new HashSet(100);
-
- public boolean visit(ITypeBinding node) {
- node= Bindings.normalizeTypeBinding(node);
- if (node == null) {
- return true;
- }
-
- if (!fVisitedBindings.add(node.getKey())) {
- return true;
- }
- if (context != null && !isUseableTypeInContext(node, context, false)) {
- return true;
- }
-
- IFunctionBinding[] methods= node.getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- IFunctionBinding meth= methods[i];
- if (meth.getName().equals(selector) && meth.getParameterTypes().length == nArgs) {
- result.add(node);
- }
- }
- return true;
- }
- });
- return (ITypeBinding[]) result.toArray(new ITypeBinding[result.size()]);
- }
-
- public static void visitAllBindings(ASTNode astRoot, TypeBindingVisitor visitor) {
- try {
- astRoot.accept(new AllBindingsVisitor(visitor));
- } catch (AllBindingsVisitor.VisitCancelledException e) {
- }
- }
-
- private static class AllBindingsVisitor extends GenericVisitor {
- private final TypeBindingVisitor fVisitor;
-
- private static class VisitCancelledException extends RuntimeException {
- private static final long serialVersionUID= 1L;
- }
- public AllBindingsVisitor(TypeBindingVisitor visitor) {
- super(true);
- fVisitor= visitor;
- }
- public boolean visit(SimpleName node) {
- ITypeBinding binding= node.resolveTypeBinding();
- if (binding != null) {
- boolean res= fVisitor.visit(binding);
- if (res) {
- res= Bindings.visitHierarchy(binding, fVisitor);
- }
- if (!res) {
- throw new VisitCancelledException();
- }
- }
- return false;
- }
- }
-
-
- public static IBinding getParentMethodOrTypeBinding(ASTNode node) {
- do {
- if (node instanceof FunctionDeclaration) {
- return ((FunctionDeclaration) node).resolveBinding();
- } else if (node instanceof AbstractTypeDeclaration) {
- return ((AbstractTypeDeclaration) node).resolveBinding();
- } else if (node instanceof AnonymousClassDeclaration) {
- return ((AnonymousClassDeclaration) node).resolveBinding();
- }
- node= node.getParent();
- } while (node != null);
-
- return null;
- }
-
- public static BodyDeclaration findParentBodyDeclaration(ASTNode node) {
- while ((node != null) && (!(node instanceof BodyDeclaration))) {
- node= node.getParent();
- }
- return (BodyDeclaration) node;
- }
-
- public static ASTNode findParentBodyDeclaration(ASTNode node, boolean treatModifiersOutside) {
- StructuralPropertyDescriptor lastLocation= null;
-
- while (node != null) {
- if (node instanceof BodyDeclaration) {
- BodyDeclaration decl= (BodyDeclaration) node;
- if (!treatModifiersOutside || lastLocation != decl.getModifiersProperty()) {
- return decl;
- }
- treatModifiersOutside= false;
- }
- else if (node instanceof JavaScriptUnit)
- return node;
- lastLocation= node.getLocationInParent();
- node= node.getParent();
- }
- return node;
- }
-
-
- public static JavaScriptUnit findParentCompilationUnit(ASTNode node) {
- return (JavaScriptUnit) findAncestor(node, ASTNode.JAVASCRIPT_UNIT);
- }
-
- /**
- * Finds the parent type of a node.
- *
- * @param node the node inside the type to find
- * @param treatModifiersOutside if set, modifiers are not part of their type, but of the type's parent
- * @return returns either a AbstractTypeDeclaration or an AnonymousTypeDeclaration
- */
- public static ASTNode findParentType(ASTNode node, boolean treatModifiersOutside) {
- StructuralPropertyDescriptor lastLocation= null;
-
- while (node != null) {
- if (node instanceof AbstractTypeDeclaration) {
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node;
- if (!treatModifiersOutside || lastLocation != decl.getModifiersProperty()) {
- return decl;
- }
- } else if (node instanceof AnonymousClassDeclaration) {
- return node;
- }
- lastLocation= node.getLocationInParent();
- node= node.getParent();
- }
- return null;
- }
-
- public static ASTNode findParentType(ASTNode node) {
- return findParentType(node, false);
- }
-
-
- public static ASTNode findParent(ASTNode node) {
- while (node != null) {
-
- if (node instanceof JavaScriptUnit) {
- return node;
- }
- else if (node instanceof AbstractTypeDeclaration) {
- return node;
-
- } else if (node instanceof AnonymousClassDeclaration) {
- return node;
- }
- node= node.getParent();
- }
- return null;
- }
-
- /**
- * Returns the method binding of the node's parent method declaration or <code>null</code> if the node
- * is not inside a method
- * @param node
- * @return JavaScriptUnit
- */
- public static FunctionDeclaration findParentMethodDeclaration(ASTNode node) {
- while (node != null) {
- if (node.getNodeType() == ASTNode.FUNCTION_DECLARATION) {
- return (FunctionDeclaration) node;
- }
- if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) {
- return null;
- }
- node= node.getParent();
- }
- return null;
- }
-
- public static ASTNode findAncestor(ASTNode node, int nodeType) {
- while ((node != null) && (node.getNodeType() != nodeType)) {
- node= node.getParent();
- }
- return node;
- }
-
- public static Statement findParentStatement(ASTNode node) {
- while ((node != null) && (!(node instanceof Statement))) {
- node= node.getParent();
- if (node instanceof BodyDeclaration) {
- return null;
- }
- }
- return (Statement) node;
- }
-
- public static TryStatement findParentTryStatement(ASTNode node) {
- while ((node != null) && (!(node instanceof TryStatement))) {
- node= node.getParent();
- if (node instanceof BodyDeclaration) {
- return null;
- }
- }
- return (TryStatement) node;
- }
-
- public static boolean isInsideConstructorInvocation(FunctionDeclaration methodDeclaration, ASTNode node) {
- if (methodDeclaration.isConstructor()) {
- Statement statement= ASTResolving.findParentStatement(node);
- if (statement instanceof ConstructorInvocation || statement instanceof SuperConstructorInvocation) {
- return true; // argument in a this or super call
- }
- }
- return false;
- }
-
- public static boolean isInsideModifiers(ASTNode node) {
- while (node != null && !(node instanceof BodyDeclaration)) {
- node= node.getParent();
- }
- return false;
- }
-
- public static boolean isInStaticContext(ASTNode selectedNode) {
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration) {
- if (isInsideConstructorInvocation((FunctionDeclaration) decl, selectedNode)) {
- return true;
- }
- return Modifier.isStatic(decl.getModifiers());
- } else if (decl instanceof Initializer) {
- return Modifier.isStatic(((Initializer)decl).getModifiers());
- } else if (decl instanceof FieldDeclaration) {
- return Modifier.isStatic(((FieldDeclaration)decl).getModifiers());
- }
- return false;
- }
-
- public static boolean isWriteAccess(Name selectedNode) {
- ASTNode curr= selectedNode;
- ASTNode parent= curr.getParent();
- while (parent != null) {
- switch (parent.getNodeType()) {
- case ASTNode.QUALIFIED_NAME:
- if (((QualifiedName) parent).getQualifier() == curr) {
- return false;
- }
- break;
- case ASTNode.FIELD_ACCESS:
- if (((FieldAccess) parent).getExpression() == curr) {
- return false;
- }
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- break;
- case ASTNode.ASSIGNMENT:
- return ((Assignment) parent).getLeftHandSide() == curr;
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- return ((VariableDeclaration) parent).getName() == curr;
- case ASTNode.POSTFIX_EXPRESSION:
- case ASTNode.PREFIX_EXPRESSION:
- return true;
- default:
- return false;
- }
-
- curr= parent;
- parent= curr.getParent();
- }
- return false;
- }
-
- public static int getPossibleTypeKinds(ASTNode node, boolean is50OrHigher) {
- int kinds= internalGetPossibleTypeKinds(node);
- if (!is50OrHigher) {
- kinds &= (SimilarElementsRequestor.INTERFACES | SimilarElementsRequestor.CLASSES);
- }
- return kinds;
- }
-
-
- private static int internalGetPossibleTypeKinds(ASTNode node) {
- int kind= SimilarElementsRequestor.ALL_TYPES;
-
- int mask= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE;
-
- ASTNode parent= node.getParent();
- while (parent instanceof QualifiedName) {
- if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY) {
- return SimilarElementsRequestor.REF_TYPES;
- }
- node= parent;
- parent= parent.getParent();
- mask= SimilarElementsRequestor.REF_TYPES;
- }
- while (parent instanceof Type) {
- if (parent instanceof QualifiedType) {
- if (node.getLocationInParent() == QualifiedType.QUALIFIER_PROPERTY) {
- return mask & (SimilarElementsRequestor.REF_TYPES);
- }
- mask&= SimilarElementsRequestor.REF_TYPES;
- }
- node= parent;
- parent= parent.getParent();
- }
-
- switch (parent.getNodeType()) {
- case ASTNode.TYPE_DECLARATION:
- if (node.getLocationInParent() == TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) {
- kind= SimilarElementsRequestor.CLASSES;
- }
- break;
- case ASTNode.FUNCTION_DECLARATION:
- if (node.getLocationInParent() == FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY) {
- kind= SimilarElementsRequestor.CLASSES;
- } else if (node.getLocationInParent() == FunctionDeclaration.RETURN_TYPE2_PROPERTY) {
- kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE;
- }
- break;
- case ASTNode.INSTANCEOF_EXPRESSION:
- kind= SimilarElementsRequestor.REF_TYPES;
- break;
- case ASTNode.THROW_STATEMENT:
- kind= SimilarElementsRequestor.CLASSES;
- break;
- case ASTNode.CLASS_INSTANCE_CREATION:
- if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) {
- kind= SimilarElementsRequestor.CLASSES;
- } else {
- kind= SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES;
- }
- break;
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- int superParent= parent.getParent().getNodeType();
- if (superParent == ASTNode.CATCH_CLAUSE) {
- kind= SimilarElementsRequestor.CLASSES;
- }
- break;
- case ASTNode.TAG_ELEMENT:
- kind= SimilarElementsRequestor.REF_TYPES;
- break;
- case ASTNode.TYPE_LITERAL:
- kind= SimilarElementsRequestor.REF_TYPES;
- break;
- default:
- }
- return kind & mask;
- }
-
- public static String getFullName(Name name) {
- return name.getFullyQualifiedName();
- }
-
- public static IJavaScriptUnit findCompilationUnitForBinding(IJavaScriptUnit cu, JavaScriptUnit astRoot, ITypeBinding binding) throws JavaScriptModelException {
- if (binding == null || !binding.isFromSource()) {
- return null;
- }
- ASTNode node= astRoot.findDeclaringNode(binding.getTypeDeclaration());
- if (node == null) {
- IJavaScriptUnit targetCU= Bindings.findCompilationUnit(binding, cu.getJavaScriptProject());
- if (targetCU != null) {
- return targetCU;
- }
- return null;
- } else if (node instanceof JavaScriptUnit || node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) {
- return cu;
- }
-
-
- return null;
- }
-
-
- private static final Code[] CODE_ORDER= { PrimitiveType.CHAR, PrimitiveType.SHORT, PrimitiveType.INT, PrimitiveType.LONG, PrimitiveType.FLOAT, PrimitiveType.DOUBLE };
-
- public static ITypeBinding[] getNarrowingTypes(AST ast, ITypeBinding type) {
- ArrayList res= new ArrayList();
- res.add(type);
- if (type.isPrimitive()) {
- Code code= PrimitiveType.toCode(type.getName());
- for (int i= 0; i < CODE_ORDER.length && code != CODE_ORDER[i]; i++) {
- String typeName= CODE_ORDER[i].toString();
- res.add(ast.resolveWellKnownType(typeName));
- }
- }
- return (ITypeBinding[]) res.toArray(new ITypeBinding[res.size()]);
- }
-
- public static ITypeBinding[] getRelaxingTypes(AST ast, ITypeBinding type) {
- ArrayList res= new ArrayList();
- res.add(type);
- if (type.isArray()) {
- res.add(ast.resolveWellKnownType("java.lang.Object")); //$NON-NLS-1$
- res.add(ast.resolveWellKnownType("java.io.Serializable")); //$NON-NLS-1$
- res.add(ast.resolveWellKnownType("java.lang.Cloneable")); //$NON-NLS-1$
- } else if (type.isPrimitive()) {
- Code code= PrimitiveType.toCode(type.getName());
- boolean found= false;
- for (int i= 0; i < CODE_ORDER.length; i++) {
- if (found) {
- String typeName= CODE_ORDER[i].toString();
- res.add(ast.resolveWellKnownType(typeName));
- }
- if (code == CODE_ORDER[i]) {
- found= true;
- }
- }
- } else {
- collectRelaxingTypes(res, type);
- }
- return (ITypeBinding[]) res.toArray(new ITypeBinding[res.size()]);
- }
-
- private static void collectRelaxingTypes(Collection res, ITypeBinding type) {
- ITypeBinding binding= type.getSuperclass();
- if (binding != null) {
- if (!res.contains(binding)) {
- res.add(binding);
- }
- collectRelaxingTypes(res, binding);
- }
- }
-
- public static String[] getUsedVariableNames(ASTNode node) {
- JavaScriptUnit root= (JavaScriptUnit) node.getRoot();
- Collection res= (new ScopeAnalyzer(root)).getUsedVariableNames(node.getStartPosition(), node.getLength());
- return (String[]) res.toArray(new String[res.size()]);
- }
-
- public static boolean isUseableTypeInContext(ITypeBinding[] binding, IBinding context, boolean noWildcards) {
- for (int i= 0; i < binding.length; i++) {
- if (!isUseableTypeInContext(binding[i], context, noWildcards)) {
- return false;
- }
- }
- return true;
- }
-
-
- public static boolean isUseableTypeInContext(ITypeBinding type, IBinding context, boolean noWildcards) {
- if (type.isArray()) {
- type= type.getElementType();
- }
- if (type.isAnonymous()) {
- return false;
- }
- if (type.isPrimitive()) {
- return true;
- }
- return true;
- }
-
- // pretty signatures
-
- public static String getTypeSignature(ITypeBinding type) {
- return BindingLabelProvider.getBindingLabel(type, BindingLabelProvider.DEFAULT_TEXTFLAGS);
- }
-
- public static String getMethodSignature(IFunctionBinding binding, boolean inOtherCU) {
- StringBuffer buf= new StringBuffer();
- if (inOtherCU && !binding.isConstructor()) {
- buf.append(binding.getDeclaringClass().getTypeDeclaration().getName()).append('.'); // simple type name
- }
- return BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS);
- }
-
- public static String getMethodSignature(String name, ITypeBinding[] params, boolean isVarArgs) {
- StringBuffer buf= new StringBuffer();
- buf.append(name).append('(');
- for (int i= 0; i < params.length; i++) {
- if (i > 0) {
- buf.append(JavaScriptElementLabels.COMMA_STRING);
- }
- if (isVarArgs && i == params.length - 1) {
- buf.append(getTypeSignature(params[i].getElementType()));
- buf.append("..."); //$NON-NLS-1$
- } else {
- buf.append(getTypeSignature(params[i]));
- }
- }
- buf.append(')');
- return buf.toString();
- }
-
- public static JavaScriptUnit createQuickFixAST(IJavaScriptUnit compilationUnit, IProgressMonitor monitor) {
- ASTParser astParser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
- astParser.setSource(compilationUnit);
- astParser.setResolveBindings(true);
- astParser.setStatementsRecovery(ASTProvider.SHARED_AST_STATEMENT_RECOVERY);
- astParser.setBindingsRecovery(ASTProvider.SHARED_BINDING_RECOVERY);
- return (JavaScriptUnit) astParser.createAST(monitor);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTRewriteCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTRewriteCorrectionProposal.java
deleted file mode 100644
index f6bab134..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ASTRewriteCorrectionProposal.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-
-/**
- * A proposal for quick fixes and quick assists that works on a AST rewriter.
- * Either a rewriter is directly passed in the constructor or method {@link #getRewrite()}
- * is overridden to provide the AST rewriter that is evaluated to the document when the
- * proposal is applied.
- *
- *
- */
-public class ASTRewriteCorrectionProposal extends CUCorrectionProposal {
-
- private ASTRewrite fRewrite;
- private ImportRewrite fImportRewrite;
-
- /**
- * Constructs a AST rewrite correction proposal.
- *
- * @param name the display name of the proposal.
- * @param cu the compilation unit that is modified.
- * @param rewrite the AST rewrite that is invoked when the proposal is applied or
- * <code>null</code> if {@link #getRewrite()} is overridden.
- * @param relevance The relevance of this proposal.
- * @param image The image that is displayed for this proposal or <code>null</code> if no
- * image is desired.
- */
- public ASTRewriteCorrectionProposal(String name, IJavaScriptUnit cu, ASTRewrite rewrite, int relevance, Image image) {
- super(name, cu, relevance, image);
- fRewrite= rewrite;
- }
-
- /**
- * Returns the import rewriter used for this compilation unit. <code>
- */
- public ImportRewrite getImportRewrite() {
- return fImportRewrite;
- }
-
- /**
- * Sets the import rewriter used for this compilation unit.
- */
- public void setImportRewrite(ImportRewrite rewrite) {
- fImportRewrite= rewrite;
- }
-
- /**
- * Sets the import rewriter used for this compilation unit.
- */
- public ImportRewrite createImportRewrite(JavaScriptUnit astRoot) {
- fImportRewrite= StubUtility.createImportRewrite(astRoot, true);
- return fImportRewrite;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#addEdits(org.eclipse.jface.text.IDocument)
- */
- protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
- super.addEdits(document, editRoot);
- ASTRewrite rewrite= getRewrite();
- if (rewrite != null) {
- try {
- TextEdit edit= rewrite.rewriteAST();
- editRoot.addChild(edit);
- } catch (IllegalArgumentException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
- if (fImportRewrite != null) {
- editRoot.addChild(fImportRewrite.rewriteImports(new NullProgressMonitor()));
- }
- }
-
- /**
- * Returns the rewriter that has been passed in the constructor. Implementors can override this
- * method to create the rewriter lazy. This method will only be called once.
- *
- * @return returns the rewriter to be used.
- * @throws CoreException an exception is thrown when the rewriter could not be created.
- */
- protected ASTRewrite getRewrite() throws CoreException {
- if (fRewrite == null) {
- IStatus status= JavaUIStatus.createError(IStatus.ERROR, "Rewriter not initialized", null); //$NON-NLS-1$
- throw new CoreException(status);
- }
- return fRewrite;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AbstractMethodCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AbstractMethodCompletionProposal.java
deleted file mode 100644
index 7968d87f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AbstractMethodCompletionProposal.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-public abstract class AbstractMethodCompletionProposal extends LinkedCorrectionProposal {
-
- private ASTNode fNode;
- private ITypeBinding fSenderBinding;
-
- public AbstractMethodCompletionProposal(String label, IJavaScriptUnit targetCU, ASTNode invocationNode, ITypeBinding binding, int relevance, Image image) {
- super(label, targetCU, null, relevance, image);
-
- Assert.isTrue(binding != null && Bindings.isDeclarationBinding(binding));
-
- fNode= invocationNode;
- fSenderBinding= binding;
- }
-
- protected ASTNode getInvocationNode() {
- return fNode;
- }
-
- /**
- * @return The binding of the type declaration (generic type)
- */
- protected ITypeBinding getSenderBinding() {
- return fSenderBinding;
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- JavaScriptUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
- ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
- ASTNode newTypeDecl= null;
- boolean isInDifferentCU;
- if (typeDecl != null) {
- isInDifferentCU= false;
- newTypeDecl= typeDecl;
- } else {
- isInDifferentCU= true;
- astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
- newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
- }
- createImportRewrite(astRoot);
-
- if (newTypeDecl != null) {
- ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
-
- FunctionDeclaration newStub= getStub(rewrite, newTypeDecl);
-
- ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
- List members= (List) newTypeDecl.getStructuralProperty(property);
-
- int insertIndex;
- if (isConstructor()) {
- insertIndex= findConstructorInsertIndex(members);
- } else if (!isInDifferentCU) {
- insertIndex= findMethodInsertIndex(members, fNode.getStartPosition());
- } else {
- insertIndex= members.size();
- }
- ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
- listRewriter.insertAt(newStub, insertIndex, null);
-
- return rewrite;
- }
- return null;
- }
-
- private FunctionDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
- AST ast= targetTypeDecl.getAST();
- FunctionDeclaration decl= ast.newFunctionDeclaration();
-
- SimpleName newNameNode= getNewName(rewrite);
-
- decl.setConstructor(isConstructor());
-
- addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());
-
- ArrayList takenNames= new ArrayList();
-
- decl.setName(newNameNode);
-
- IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
- for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
- takenNames.add(declaredFields[i].getName());
- }
-
- String bodyStatement= ""; //$NON-NLS-1$
- if (!isConstructor()) {
- Type returnType= getNewMethodType(rewrite);
- if (returnType == null) {
- decl.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
- } else {
- decl.setReturnType2(returnType);
- }
- if (returnType != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
- bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaScriptProject().getOptions(true));
- }
- }
-
- addNewParameters(rewrite, takenNames, decl.parameters());
-
- Block body= ast.newBlock();
- String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), newNameNode.getIdentifier(), isConstructor(), bodyStatement, String.valueOf('\n'));
- if (placeHolder != null) {
- ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
- body.statements().add(todoNode);
- }
-
- decl.setBody(body);
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaScriptProject());
- if (settings.createComments && !fSenderBinding.isAnonymous()) {
- String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
-
-
- private int findMethodInsertIndex(List decls, int currPos) {
- int nDecls= decls.size();
- for (int i= 0; i < nDecls; i++) {
- ASTNode curr= (ASTNode) decls.get(i);
- if (curr instanceof FunctionDeclaration && currPos < curr.getStartPosition() + curr.getLength()) {
- return i + 1;
- }
- }
- return nDecls;
- }
-
- private int findConstructorInsertIndex(List decls) {
- int nDecls= decls.size();
- int lastMethod= 0;
- for (int i= nDecls - 1; i >= 0; i--) {
- ASTNode curr= (ASTNode) decls.get(i);
- if (curr instanceof FunctionDeclaration) {
- if (((FunctionDeclaration) curr).isConstructor()) {
- return i + 1;
- }
- lastMethod= i;
- }
- }
- return lastMethod;
- }
-
- protected abstract boolean isConstructor();
-
- protected abstract void addNewModifiers(ASTRewrite rewrite, ASTNode targetTypeDecl, List exceptions);
- protected abstract void addNewParameters(ASTRewrite rewrite, List takenNames, List params) throws CoreException;
-
- protected abstract SimpleName getNewName(ASTRewrite rewrite);
- protected abstract Type getNewMethodType(ASTRewrite rewrite) throws CoreException;
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddArgumentCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddArgumentCorrectionProposal.java
deleted file mode 100644
index 46298ff4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddArgumentCorrectionProposal.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.lang.reflect.Modifier;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class AddArgumentCorrectionProposal extends LinkedCorrectionProposal {
-
- private int[] fInsertIndexes;
- private ITypeBinding[] fParamTypes;
- private ASTNode fCallerNode;
-
- public AddArgumentCorrectionProposal(String label, IJavaScriptUnit cu, ASTNode callerNode, int[] insertIdx, ITypeBinding[] expectedTypes, int relevance) {
- super(label, cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- fCallerNode= callerNode;
- fInsertIndexes= insertIdx;
- fParamTypes= expectedTypes;
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() {
- AST ast= fCallerNode.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- ChildListPropertyDescriptor property= getProperty();
-
- for (int i= 0; i < fInsertIndexes.length; i++) {
- int idx= fInsertIndexes[i];
- String key= "newarg_" + i; //$NON-NLS-1$
- Expression newArg= evaluateArgumentExpressions(ast, fParamTypes[idx], key);
- ListRewrite listRewriter= rewrite.getListRewrite(fCallerNode, property);
- listRewriter.insertAt(newArg, idx, null);
-
- addLinkedPosition(rewrite.track(newArg), i == 0, key);
- }
- return rewrite;
- }
-
- private ChildListPropertyDescriptor getProperty() {
- List list= fCallerNode.structuralPropertiesForType();
- for (int i= 0; i < list.size(); i++) {
- StructuralPropertyDescriptor curr= (StructuralPropertyDescriptor) list.get(i);
- if (curr.isChildListProperty() && "arguments".equals(curr.getId())) { //$NON-NLS-1$
- return (ChildListPropertyDescriptor) curr;
- }
- }
- return null;
-
- }
-
-
- private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
- JavaScriptUnit root= (JavaScriptUnit) fCallerNode.getRoot();
-
- int offset= fCallerNode.getStartPosition();
- Expression best= null;
- ITypeBinding bestType= null;
-
- ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
- IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
- for (int i= 0; i < bindings.length; i++) {
- IVariableBinding curr= (IVariableBinding) bindings[i];
- ITypeBinding type= curr.getType();
- if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
- if (best == null || isMoreSpecific(bestType, type)) {
- best= ast.newSimpleName(curr.getName());
- bestType= type;
- }
- addLinkedPositionProposal(key, curr.getName(), null);
- }
- }
- Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
- if (best == null) {
- best= defaultExpression;
- }
- addLinkedPositionProposal(key, ASTNodes.asString(defaultExpression), null);
- return best;
- }
-
- private boolean isMoreSpecific(ITypeBinding best, ITypeBinding curr) {
- return (canAssign(best, curr) && !canAssign(curr, best));
- }
-
-
- private boolean canAssign(ITypeBinding curr, ITypeBinding best) {
- return curr.isAssignmentCompatible(best);
- }
-
- private boolean testModifier(IVariableBinding curr) {
- int modifiers= curr.getModifiers();
- int staticFinal= Modifier.STATIC | Modifier.FINAL;
- if ((modifiers & staticFinal) == staticFinal) {
- return false;
- }
- if (Modifier.isStatic(modifiers) && !ASTResolving.isInStaticContext(fCallerNode)) {
- return false;
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddImportCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddImportCorrectionProposal.java
deleted file mode 100644
index 9adbe716..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AddImportCorrectionProposal.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-
-public class AddImportCorrectionProposal extends ASTRewriteCorrectionProposal {
-
- private final String fTypeName;
- private final String fQualifierName;
-
- public AddImportCorrectionProposal(String name, IJavaScriptUnit cu, int relevance, Image image, String qualifierName, String typeName, SimpleName node) {
- super(name, cu, ASTRewrite.create(node.getAST()), relevance, image);
- fTypeName= typeName;
- fQualifierName= qualifierName;
- }
-
- public String getQualifiedTypeName() {
- return fQualifierName + '.' + fTypeName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeCorrectionProposal#performChange(org.eclipse.ui.IEditorPart, org.eclipse.jface.text.IDocument)
- */
- protected void performChange(IEditorPart activeEditor, IDocument document) throws CoreException {
- super.performChange(activeEditor, document);
- rememberSelection();
- }
-
-
- private void rememberSelection() throws CoreException {
- QualifiedTypeNameHistory.remember(getQualifiedTypeName());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java
deleted file mode 100644
index cf9bbcf5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java
+++ /dev/null
@@ -1,2172 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Konstantin Scheglov (scheglov_ke@nlmk.ru) - initial API and implementation
- * (reports 71244 & 74746: New Quick Assist's [quick assist])
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BooleanLiteral;
-import org.eclipse.wst.jsdt.core.dom.BreakStatement;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.ContinueStatement;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression.Operator;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.ExpressionsFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.fix.ExpressionsCleanUp;
-import org.eclipse.wst.jsdt.ui.CodeStyleConfiguration;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickAssistProcessor;
-
-/**
- */
-public class AdvancedQuickAssistProcessor implements IQuickAssistProcessor {
- public AdvancedQuickAssistProcessor() {
- super();
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistProcessor#hasAssists(org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistContext)
- */
- public boolean hasAssists(IInvocationContext context) throws CoreException {
- ASTNode coveringNode = context.getCoveringNode();
- if (coveringNode != null) {
- ArrayList coveredNodes= getFullyCoveredNodes(context, coveringNode);
- return getInverseIfProposals(context, coveringNode, null)
- || getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, null)
- || getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, null)
- || getInverseIfIntoContinueInLoopsProposals(context, coveringNode, null)
- || getInverseConditionProposals(context, coveringNode, coveredNodes, null)
- || getRemoveExtraParenthesisProposals(context, coveringNode, coveredNodes, null)
- || getAddParanoidalParenthesisProposals(context, coveringNode, coveredNodes, null)
- || getJoinAndIfStatementsProposals(context, coveringNode, null)
- || getSplitAndConditionProposals(context, coveringNode, null)
- || getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, null)
- || getSplitOrConditionProposals(context, coveringNode, null)
- || getInverseConditionalExpressionProposals(context, coveringNode, null)
- || getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, null)
- || getExchangeOperandsProposals(context, coveringNode, null)
- || getPickOutStringProposals(context, coveringNode, null)
- || getReplaceIfElseWithConditionalProposals(context, coveringNode, null)
- || getReplaceConditionalWithIfElseProposals(context, coveringNode, null)
- || getInverseLocalVariableProposals(context, coveringNode, null)
- || getPushNegationDownProposals(context, coveringNode, null)
- || getPullNegationUpProposals(context, coveringNode, coveredNodes, null)
- || getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, null)
- || getConvertSwitchToIfProposals(context, coveringNode, null);
- }
- return false;
- }
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistContext, org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation[])
- */
- public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations)
- throws CoreException {
- ASTNode coveringNode = context.getCoveringNode();
- if (coveringNode != null) {
- ArrayList coveredNodes = getFullyCoveredNodes(context, coveringNode);
- ArrayList resultingCollections = new ArrayList();
- if (noErrorsAtLocation(locations)) {
- getInverseIfProposals(context, coveringNode, resultingCollections);
- getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, resultingCollections);
- getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, resultingCollections);
- getInverseIfIntoContinueInLoopsProposals(context, coveringNode, resultingCollections);
- getInverseConditionProposals(context, coveringNode, coveredNodes, resultingCollections);
- getRemoveExtraParenthesisProposals(context, coveringNode, coveredNodes, resultingCollections);
- getAddParanoidalParenthesisProposals(context, coveringNode, coveredNodes, resultingCollections);
- getJoinAndIfStatementsProposals(context, coveringNode, resultingCollections);
- getSplitAndConditionProposals(context, coveringNode, resultingCollections);
- getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, resultingCollections);
- getSplitOrConditionProposals(context, coveringNode, resultingCollections);
- getInverseConditionalExpressionProposals(context, coveringNode, resultingCollections);
- getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, resultingCollections);
- getExchangeOperandsProposals(context, coveringNode, resultingCollections);
- getPickOutStringProposals(context, coveringNode, resultingCollections);
- getReplaceIfElseWithConditionalProposals(context, coveringNode, resultingCollections);
- getReplaceConditionalWithIfElseProposals(context, coveringNode, resultingCollections);
- getInverseLocalVariableProposals(context, coveringNode, resultingCollections);
- getPushNegationDownProposals(context, coveringNode, resultingCollections);
- getPullNegationUpProposals(context, coveringNode, coveredNodes, resultingCollections);
- getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, resultingCollections);
- getConvertSwitchToIfProposals(context, coveringNode, resultingCollections);
- }
- return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
- }
- return null;
- }
- private static boolean noErrorsAtLocation(IProblemLocation[] locations) {
- if (locations != null) {
- for (int i = 0; i < locations.length; i++) {
- if (locations[i].isError()) {
- return false;
- }
- }
- }
- return true;
- }
- private static boolean getIfReturnIntoIfElseAtEndOfVoidMethodProposals(IInvocationContext context, ASTNode covering,
- Collection resultingCollections) {
- Statement coveringStatement = ASTResolving.findParentStatement(covering);
- if (!(coveringStatement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) coveringStatement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // 'then' block should have 'return' as last statement
- Statement thenStatement = ifStatement.getThenStatement();
- if (!(thenStatement instanceof Block)) {
- return false;
- }
- Block thenBlock = (Block) thenStatement;
- List thenStatements = thenBlock.statements();
- if (thenStatements.isEmpty() || !(thenStatements.get(thenStatements.size() - 1) instanceof ReturnStatement)) {
- return false;
- }
- // method should return 'void'
- FunctionDeclaration coveringMetod = ASTResolving.findParentMethodDeclaration(covering);
- if (coveringMetod == null) {
- return false;
- }
- Type returnType = coveringMetod.getReturnType2();
- if (!(returnType instanceof PrimitiveType)
- || ((PrimitiveType) returnType).getPrimitiveTypeCode() != PrimitiveType.VOID)
- return false;
- //
- List statements = coveringMetod.getBody().statements();
- int ifIndex = statements.indexOf(ifStatement);
- if (ifIndex == -1) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = coveringStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // remove last 'return' in 'then' block
- ListRewrite listRewriter = rewrite.getListRewrite(thenBlock,
- (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
- listRewriter.remove((ASTNode) thenStatements.get(thenStatements.size() - 1), null);
- // prepare original nodes
- Expression conditionPlaceholder = (Expression) rewrite.createMoveTarget(ifStatement.getExpression());
- Statement thenPlaceholder = (Statement) rewrite.createMoveTarget(ifStatement.getThenStatement());
- // prepare 'else' block
- Block elseBlock = ast.newBlock();
- for (int i = ifIndex + 1; i < statements.size(); i++) {
- Statement statement = (Statement) statements.get(i);
- elseBlock.statements().add(rewrite.createMoveTarget(statement));
- }
- // prepare new 'if' statement
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(conditionPlaceholder);
- newIf.setThenStatement(thenPlaceholder);
- newIf.setElseStatement(elseBlock);
- rewrite.replace(ifStatement, newIf, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfElse_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) {
- Statement coveringStatement = ASTResolving.findParentStatement(covering);
- if (!(coveringStatement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) coveringStatement;
- if (ifStatement.getElseStatement() == null) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = coveringStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- Statement thenStatement= ifStatement.getThenStatement();
- Statement elseStatement= ifStatement.getElseStatement();
-
- // prepare original nodes
- Expression inversedExpression = getInversedBooleanExpression(rewrite, ifStatement.getExpression());
-
- Statement newElseStatement = (Statement) rewrite.createMoveTarget(thenStatement);
- Statement newThenStatement = (Statement) rewrite.createMoveTarget(elseStatement);
- // set new nodes
- rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);
-
- if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580
- Block elseBlock = ast.newBlock();
- elseBlock.statements().add(newThenStatement);
- newThenStatement= elseBlock;
- }
- rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
- rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getInverseIfContinueIntoIfThenInLoopsProposals(IInvocationContext context, ASTNode covering,
- Collection resultingCollections) {
- Statement coveringStatement = ASTResolving.findParentStatement(covering);
- if (!(coveringStatement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) coveringStatement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // check that 'then' is 'continue'
- if (!(ifStatement.getThenStatement() instanceof ContinueStatement)) {
- return false;
- }
- // check that 'if' statement is statement in block that is body of loop
- Block loopBlock = null;
- if ((ifStatement.getParent() instanceof Block) && (ifStatement.getParent().getParent() instanceof ForStatement)) {
- loopBlock = (Block) ifStatement.getParent();
- } else if ((ifStatement.getParent() instanceof Block)
- && (ifStatement.getParent().getParent() instanceof WhileStatement)) {
- loopBlock = (Block) ifStatement.getParent();
- } else {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = coveringStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // create inverted 'if' statement
- Expression inversedExpression = getInversedBooleanExpression(rewrite, ifStatement.getExpression());
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(inversedExpression);
- // prepare 'then' for new 'if'
- Block thenBlock = ast.newBlock();
- int ifIndex = loopBlock.statements().indexOf(ifStatement);
- for (int i = ifIndex + 1; i < loopBlock.statements().size(); i++) {
- Statement statement = (Statement) loopBlock.statements().get(i);
- thenBlock.statements().add(rewrite.createMoveTarget(statement));
- }
- newIf.setThenStatement(thenBlock);
- // replace 'if' statement in loop
- rewrite.replace(ifStatement, newIf, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfContinue_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getInverseIfIntoContinueInLoopsProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) {
- Statement coveringStatement = ASTResolving.findParentStatement(covering);
- if (!(coveringStatement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) coveringStatement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // prepare outer control structure and block that contains 'if' statement
- ASTNode ifParent = ifStatement.getParent();
- Block ifParentBlock = null;
- ASTNode ifParentStructure = ifParent;
- if (ifParentStructure instanceof Block) {
- ifParentBlock = (Block) ifParent;
- ifParentStructure = ifParentStructure.getParent();
- }
- // check that control structure is loop and 'if' statement if last statement
- if (!(ifParentStructure instanceof ForStatement) && !(ifParentStructure instanceof WhileStatement)&& !(ifParentStructure instanceof ForInStatement)) {
- return false;
- }
- if ((ifParentBlock != null) && (ifParentBlock.statements().indexOf(ifStatement) != ifParentBlock.statements().size() - 1)) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = coveringStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // create inverted 'if' statement
- Expression inversedExpression = getInversedBooleanExpression(rewrite, ifStatement.getExpression());
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(inversedExpression);
- newIf.setThenStatement(ast.newContinueStatement());
- //
- if (ifParentBlock == null) {
- // if there is no block, create it
- ifParentBlock = ast.newBlock();
- ifParentBlock.statements().add(newIf);
- for (Iterator iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext();) {
- Statement statement = (Statement) iter.next();
- ifParentBlock.statements().add(rewrite.createMoveTarget(statement));
- }
- // replace 'if' statement as body with new block
- if (ifParentStructure instanceof ForStatement) {
- rewrite.set(ifParentStructure, ForStatement.BODY_PROPERTY, ifParentBlock, null);
- } else if (ifParentStructure instanceof WhileStatement) {
- rewrite.set(ifParentStructure, WhileStatement.BODY_PROPERTY, ifParentBlock, null);
- }
- } else {
- // if there was block, replace
- ListRewrite listRewriter = rewrite.getListRewrite(ifParentBlock,
- (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
- listRewriter.replace(ifStatement, newIf, null);
- // add statements from 'then' to the end of block
- for (Iterator iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext();) {
- Statement statement = (Statement) iter.next();
- listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
- }
- }
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfToContinue_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static ArrayList getUnwrappedStatements(Statement body) {
- ArrayList statements = new ArrayList();
- if (body instanceof Block) {
- for (Iterator iter = ((Block) body).statements().iterator(); iter.hasNext();) {
- Statement statement = (Statement) iter.next();
- statements.add(statement);
- }
- } else {
- statements.add(body);
- }
- return statements;
- }
- private static boolean getInverseConditionProposals(IInvocationContext context, ASTNode covering, ArrayList coveredNodes, Collection resultingCollections) {
- if (coveredNodes.isEmpty()) {
- return false;
- }
- //
- final AST ast = covering.getAST();
- final ASTRewrite rewrite = ASTRewrite.create(ast);
- // check sub-expressions in fully covered nodes
- boolean hasChanges = false;
- for (Iterator iter = coveredNodes.iterator(); iter.hasNext();) {
- ASTNode covered = (ASTNode) iter.next();
- Expression coveredExpression= getBooleanExpression(covered);
- if (coveredExpression != null) {
- Expression inversedExpression = getInversedBooleanExpression(rewrite, coveredExpression);
- rewrite.replace(coveredExpression, inversedExpression, null);
- hasChanges = true;
- }
- }
- //
- if (!hasChanges) {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditions_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static Expression getInversedBooleanExpression(ASTRewrite rewrite, Expression expression) {
- return getInversedBooleanExpression(rewrite, expression, null);
- }
- private interface SimpleNameRenameProvider {
- SimpleName getRenamed(SimpleName name);
- }
- private static Expression getRenamedNameCopy(SimpleNameRenameProvider provider,
- ASTRewrite rewrite,
- Expression expression) {
- if (provider != null) {
- if (expression instanceof SimpleName) {
- SimpleName name= (SimpleName) expression;
- SimpleName newName= provider.getRenamed(name);
- if (newName != null) {
- return newName;
- }
- }
- }
- return (Expression) rewrite.createCopyTarget(expression);
- }
- private static Expression getInversedBooleanExpression(ASTRewrite rewrite, Expression expression, SimpleNameRenameProvider provider) {
- if (!isBoolean(expression)) {
- return (Expression) rewrite.createCopyTarget(expression);
- }
- AST ast= rewrite.getAST();
- //
- if (expression instanceof BooleanLiteral) {
- return ast.newBooleanLiteral(!((BooleanLiteral) expression).booleanValue());
- }
- if (expression instanceof InfixExpression) {
- InfixExpression infixExpression= (InfixExpression) expression;
- InfixExpression.Operator operator= infixExpression.getOperator();
- if (operator == InfixExpression.Operator.LESS) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER_EQUALS, provider);
- }
- if (operator == InfixExpression.Operator.GREATER) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.LESS_EQUALS, provider);
- }
- if (operator == InfixExpression.Operator.LESS_EQUALS) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER, provider);
- }
- if (operator == InfixExpression.Operator.GREATER_EQUALS) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.LESS, provider);
- }
- if (operator == InfixExpression.Operator.EQUALS) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.NOT_EQUALS, provider);
- }
- if (operator == InfixExpression.Operator.NOT_EQUALS) {
- return getInversedInfixBooleanExpression(rewrite, infixExpression, InfixExpression.Operator.EQUALS, provider);
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_AND) {
- return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_OR, provider);
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_OR) {
- return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_AND, provider);
- }
- if (operator == InfixExpression.Operator.AND) {
- return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.OR, provider);
- }
- if (operator == InfixExpression.Operator.OR) {
- return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.AND, provider);
- }
- }
- if (expression instanceof PrefixExpression) {
- PrefixExpression prefixExpression= (PrefixExpression) expression;
- if (prefixExpression.getOperator() == PrefixExpression.Operator.NOT) {
- return getRenamedNameCopy(provider, rewrite, prefixExpression.getOperand());
- }
- }
- if (expression instanceof InstanceofExpression) {
- PrefixExpression prefixExpression= ast.newPrefixExpression();
- prefixExpression.setOperator(PrefixExpression.Operator.NOT);
- ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
- parenthesizedExpression.setExpression((Expression) rewrite.createCopyTarget(expression));
- prefixExpression.setOperand(parenthesizedExpression);
- return prefixExpression;
- }
- if (expression instanceof ParenthesizedExpression) {
- ParenthesizedExpression parenthesizedExpression= (ParenthesizedExpression) expression;
- Expression innerExpression= parenthesizedExpression.getExpression();
- while (innerExpression instanceof ParenthesizedExpression) {
- innerExpression= ((ParenthesizedExpression) innerExpression).getExpression();
- }
- if (innerExpression instanceof InstanceofExpression) {
- return getInversedBooleanExpression(rewrite, innerExpression, provider);
- }
- parenthesizedExpression= ast.newParenthesizedExpression();
- parenthesizedExpression.setExpression(getInversedBooleanExpression(rewrite, innerExpression, provider));
- return parenthesizedExpression;
- }
- //
- PrefixExpression prefixExpression= ast.newPrefixExpression();
- prefixExpression.setOperator(PrefixExpression.Operator.NOT);
- prefixExpression.setOperand(getRenamedNameCopy(provider, rewrite, expression));
- return prefixExpression;
- }
- private static boolean isBoolean(Expression expression) {
- return expression.resolveTypeBinding() == expression.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
- }
- private static Expression getInversedInfixBooleanExpression(ASTRewrite rewrite, InfixExpression expression, InfixExpression.Operator newOperator, SimpleNameRenameProvider provider) {
- InfixExpression newExpression = rewrite.getAST().newInfixExpression();
- newExpression.setOperator(newOperator);
- newExpression.setLeftOperand(getInversedBooleanExpression(rewrite, expression.getLeftOperand(), provider));
- newExpression.setRightOperand(getInversedBooleanExpression(rewrite, expression.getRightOperand(), provider));
- return newExpression;
- }
-
- private static Expression parenthesizeIfRequired(Expression operand, int newOperatorPrecedence) {
- if (newOperatorPrecedence < getExpressionPrecedence(operand)) {
- return getParenthesizedExpression(operand.getAST(), operand);
- }
- return operand;
- }
-
- private static Expression getInversedAndOrExpression(ASTRewrite rewrite, InfixExpression infixExpression, Operator newOperator, SimpleNameRenameProvider provider) {
- InfixExpression newExpression = rewrite.getAST().newInfixExpression();
- newExpression.setOperator(newOperator);
-
- int newOperatorPrecedence = getInfixOperatorPrecedence(newOperator);
- //
- Expression leftOperand = getInversedBooleanExpression(rewrite, infixExpression.getLeftOperand(), provider);
- newExpression.setLeftOperand(parenthesizeIfRequired(leftOperand, newOperatorPrecedence));
-
- Expression rightOperand = getInversedBooleanExpression(rewrite, infixExpression.getRightOperand(), provider);
- newExpression.setRightOperand(parenthesizeIfRequired(rightOperand, newOperatorPrecedence));
-
- List extraOperands= infixExpression.extendedOperands();
- List newExtraOperands= newExpression.extendedOperands();
- for (int i= 0; i < extraOperands.size(); i++) {
- Expression extraOperand = getInversedBooleanExpression(rewrite, (Expression) extraOperands.get(i), provider);
- newExtraOperands.add(parenthesizeIfRequired(extraOperand, newOperatorPrecedence));
- }
- return newExpression;
- }
- private static boolean getRemoveExtraParenthesisProposals(IInvocationContext context, ASTNode covering, ArrayList coveredNodes,
- Collection resultingCollections) {
- ArrayList nodes;
- if ((context.getSelectionLength() == 0) && (covering instanceof ParenthesizedExpression)) {
- nodes = new ArrayList();
- nodes.add(covering);
- } else {
- nodes= coveredNodes;
- }
- if (nodes.isEmpty())
- return false;
-
- IFix fix= ExpressionsFix.createRemoveUnnecessaryParenthesisFix(context.getASTRoot(), (ASTNode[])nodes.toArray(new ASTNode[nodes.size()]));
- if (fix == null)
- return false;
-
- if (resultingCollections == null)
- return true;
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
- Map options= new Hashtable();
- options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), 1, image, context);
- resultingCollections.add(proposal);
- return true;
- }
- private static int getExpressionPrecedence(Expression expression) {
- if (expression instanceof PostfixExpression) {
- return 0;
- }
- if (expression instanceof PrefixExpression) {
- return 1;
- }
- if (expression instanceof ClassInstanceCreation) {
- return 2;
- }
- if (expression instanceof InfixExpression) {
- InfixExpression infixExpression = (InfixExpression) expression;
- InfixExpression.Operator operator = infixExpression.getOperator();
- return getInfixOperatorPrecedence(operator);
- }
- if (expression instanceof InstanceofExpression) {
- return 6;
- }
- if (expression instanceof ConditionalExpression) {
- return 13;
- }
- if (expression instanceof Assignment) {
- return 14;
- }
- if (expression instanceof FunctionInvocation) {
- return 2;
- }
- return -1;
- }
- private static int getInfixOperatorPrecedence(InfixExpression.Operator operator) {
- if ((operator == InfixExpression.Operator.TIMES) || (operator == InfixExpression.Operator.DIVIDE)
- || (operator == InfixExpression.Operator.REMAINDER)) {
- return 3;
- }
- if ((operator == InfixExpression.Operator.PLUS) || (operator == InfixExpression.Operator.MINUS)) {
- return 4;
- }
- if ((operator == InfixExpression.Operator.LEFT_SHIFT)
- || (operator == InfixExpression.Operator.RIGHT_SHIFT_SIGNED)
- || (operator == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED)) {
- return 5;
- }
- if ((operator == InfixExpression.Operator.LESS) || (operator == InfixExpression.Operator.GREATER)
- || (operator == InfixExpression.Operator.LESS_EQUALS)
- || (operator == InfixExpression.Operator.GREATER_EQUALS)) {
- return 6;
- }
- if ((operator == InfixExpression.Operator.EQUALS) || (operator == InfixExpression.Operator.NOT_EQUALS)
- ||(operator == InfixExpression.Operator.EQUAL_EQUAL_EQUAL) || (operator == InfixExpression.Operator.NOT_EQUAL_EQUAL)
- ||(operator == InfixExpression.Operator.INSTANCEOF)) { return 7;
- }
- if (operator == InfixExpression.Operator.AND) {
- return 8;
- }
- if (operator == InfixExpression.Operator.XOR) {
- return 9;
- }
- if (operator == InfixExpression.Operator.OR) {
- return 10;
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_AND) {
- return 11;
- }
- if (operator == InfixExpression.Operator.CONDITIONAL_OR) {
- return 12;
- }
- return -1;
- }
-
- private static boolean getAddParanoidalParenthesisProposals(IInvocationContext context, ASTNode covering, ArrayList coveredNodes,
- Collection resultingCollections) throws CoreException {
-
- IFix fix= ExpressionsFix.createAddParanoidalParenthesisFix(context.getASTRoot(), (ASTNode[])coveredNodes.toArray(new ASTNode[coveredNodes.size()]));
- if (fix == null)
- return false;
-
- if (resultingCollections == null)
- return true;
-
- // add correction proposal
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- Map options= new Hashtable();
- options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), 1, image, context);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static ArrayList getFullyCoveredNodes(IInvocationContext context, ASTNode coveringNode) {
- final ArrayList coveredNodes = new ArrayList();
- final int selectionBegin = context.getSelectionOffset();
- final int selectionEnd = selectionBegin + context.getSelectionLength();
- coveringNode.accept(new GenericVisitor() {
- protected boolean visitNode(ASTNode node) {
- int nodeStart= node.getStartPosition();
- int nodeEnd= nodeStart + node.getLength();
- // if node does not intersects with selection, don't visit children
- if (nodeEnd < selectionBegin || selectionEnd < nodeStart) {
- return false;
- }
- // if node is fully covered, we don't need to visit children
- if (isCovered(node)) {
- ASTNode parent = node.getParent();
- if ((parent == null) || !isCovered(parent)) {
- coveredNodes.add(node);
- return false;
- }
- }
- // if node only partly intersects with selection, we try to find fully covered children
- return true;
- }
- private boolean isCovered(ASTNode node) {
- int begin = node.getStartPosition();
- int end = begin + node.getLength();
- return (begin >= selectionBegin) && (end <= selectionEnd);
- }
- });
- return coveredNodes;
- }
- private static boolean getJoinAndIfStatementsProposals(IInvocationContext context, ASTNode node,
- Collection resultingCollections) {
- Operator andOperator = InfixExpression.Operator.CONDITIONAL_AND;
- boolean result = false;
- //
- Statement statement = ASTResolving.findParentStatement(node);
- if (!(statement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) statement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // case when current IfStatement is sole child of another IfStatement
- {
- IfStatement outerIf = null;
- if (ifStatement.getParent() instanceof IfStatement) {
- outerIf = (IfStatement) ifStatement.getParent();
- } else if (ifStatement.getParent() instanceof Block) {
- Block block = (Block) ifStatement.getParent();
- if ((block.getParent() instanceof IfStatement) && (block.statements().size() == 1)) {
- outerIf = (IfStatement) block.getParent();
- }
- }
- if ((outerIf != null) && (outerIf.getElseStatement() == null)) {
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = statement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare condition parts, add parenthesis if needed
- Expression outerCondition = getParenthesizedForAndIfNeeded(ast, rewrite, outerIf.getExpression());
- Expression innerCondition = getParenthesizedForAndIfNeeded(ast, rewrite, ifStatement.getExpression());
- // create compound condition
- InfixExpression condition = ast.newInfixExpression();
- condition.setOperator(andOperator);
- condition.setLeftOperand(outerCondition);
- condition.setRightOperand(innerCondition);
- // create new IfStatement
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(condition);
- Statement bodyPlaceholder = (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
- newIf.setThenStatement(bodyPlaceholder);
- rewrite.replace(outerIf, newIf, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOuter_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label,
- context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- result = true;
- }
- }
- // case when current IfStatement has another IfStatement as sole child
- {
- IfStatement innerIf = null;
- if (ifStatement.getThenStatement() instanceof IfStatement) {
- innerIf = (IfStatement) ifStatement.getThenStatement();
- } else if (ifStatement.getThenStatement() instanceof Block) {
- Block block = (Block) ifStatement.getThenStatement();
- if ((block.statements().size() == 1) && (block.statements().get(0) instanceof IfStatement)) {
- innerIf = (IfStatement) block.statements().get(0);
- }
- }
- if ((innerIf != null) && (innerIf.getElseStatement() == null)) {
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = statement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare condition parts, add parenthesis if needed
- Expression outerCondition = getParenthesizedForAndIfNeeded(ast, rewrite, ifStatement.getExpression());
- Expression innerCondition = getParenthesizedForAndIfNeeded(ast, rewrite, innerIf.getExpression());
- // create compound condition
- InfixExpression condition = ast.newInfixExpression();
- condition.setOperator(andOperator);
- condition.setLeftOperand(outerCondition);
- condition.setRightOperand(innerCondition);
- // create new IfStatement
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(condition);
- Statement bodyPlaceholder = (Statement) rewrite.createCopyTarget(innerIf.getThenStatement());
- newIf.setThenStatement(bodyPlaceholder);
- rewrite.replace(ifStatement, newIf, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithInner_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label,
- context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- result = true;
- }
- }
- return result;
- }
- private static Expression getParenthesizedForAndIfNeeded(AST ast, ASTRewrite rewrite, Expression expression) {
- boolean addParentheses = false;
- int nodeType = expression.getNodeType();
- if (nodeType == ASTNode.INFIX_EXPRESSION) {
- InfixExpression infixExpression = (InfixExpression) expression;
- addParentheses = infixExpression.getOperator() == InfixExpression.Operator.CONDITIONAL_OR;
- } else {
- addParentheses = nodeType == ASTNode.CONDITIONAL_EXPRESSION || nodeType == ASTNode.ASSIGNMENT
- || nodeType == ASTNode.INSTANCEOF_EXPRESSION;
- }
- expression = (Expression) rewrite.createCopyTarget(expression);
- if (addParentheses) {
- return getParenthesizedExpression(ast, expression);
- }
- return expression;
- }
- private static Expression getParenthesizedExpression(AST ast, Expression expression) {
- ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
- parenthesizedExpression.setExpression(expression);
- return parenthesizedExpression;
- }
- private static boolean getSplitAndConditionProposals(IInvocationContext context, ASTNode node,
- Collection resultingCollections) {
- Operator andOperator = InfixExpression.Operator.CONDITIONAL_AND;
- // check that user invokes quick assist on infix expression
- if (!(node instanceof InfixExpression)) {
- return false;
- }
- InfixExpression infixExpression = (InfixExpression) node;
- if (infixExpression.getOperator() != andOperator) {
- return false;
- }
- int offset= isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
- if (offset == -1) {
- return false;
- }
-
- // check that infix expression belongs to IfStatement
- Statement statement = ASTResolving.findParentStatement(node);
- if (!(statement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) statement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // check that infix expression is part of first level && condition of IfStatement
- InfixExpression topInfixExpression = infixExpression;
- while ((topInfixExpression.getParent() instanceof InfixExpression)
- && ((InfixExpression) topInfixExpression.getParent()).getOperator() == andOperator) {
- topInfixExpression = (InfixExpression) topInfixExpression.getParent();
- }
- if (ifStatement.getExpression() != topInfixExpression) {
- return false;
- }
- //
- if (resultingCollections == null) {
- return true;
- }
- AST ast = ifStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
-
- // prepare left and right conditions
- Expression[] newOperands= { null, null };
- breakInfixOperationAtOperation(rewrite, topInfixExpression, andOperator, offset, true, newOperands);
-
- Expression leftCondition= newOperands[0];
- Expression rightCondition= newOperands[1];
-
- // replace condition in inner IfStatement
- rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, rightCondition, null);
- // prepare outer IfStatement
- IfStatement outerIfStatement = ast.newIfStatement();
- outerIfStatement.setExpression(leftCondition);
- Block outerBlock = ast.newBlock();
- outerIfStatement.setThenStatement(outerBlock);
- ASTNode ifPlaceholder = rewrite.createMoveTarget(ifStatement);
- outerBlock.statements().add(ifPlaceholder);
- // replace ifStatement
- rewrite.replace(ifStatement, outerIfStatement, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_splitAndCondition_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean isSelectingOperator(ASTNode n1, ASTNode n2, int offset, int length) {
- // between the nodes
- if (offset + length <= n2.getStartPosition() && offset >= ASTNodes.getExclusiveEnd(n1)) {
- return true;
- }
- // or exactly select the node (but not with infix expressions)
- if (n1.getStartPosition() == offset && ASTNodes.getExclusiveEnd(n2) == offset + length) {
- if (n1 instanceof InfixExpression || n2 instanceof InfixExpression) {
- return false;
- }
- return true;
- }
- return false;
- }
-
- private static int isOperatorSelected(InfixExpression infixExpression, int offset, int length) {
- ASTNode left= infixExpression.getLeftOperand();
- ASTNode right= infixExpression.getRightOperand();
-
- if (isSelectingOperator(left, right, offset, length)) {
- return ASTNodes.getExclusiveEnd(left);
- }
- List extended= infixExpression.extendedOperands();
- for (int i= 0; i < extended.size(); i++) {
- left= right;
- right= (ASTNode) extended.get(i);
- if (isSelectingOperator(left, right, offset, length)) {
- return ASTNodes.getExclusiveEnd(left);
- }
- }
- return -1;
- }
-
- private static boolean getJoinOrIfStatementsProposals(IInvocationContext context, ASTNode covering, ArrayList coveredNodes,
- Collection resultingCollections) {
- Operator orOperator = InfixExpression.Operator.CONDITIONAL_OR;
- if (coveredNodes.size() < 2)
- return false;
- // check that all covered nodes are IfStatement's with same 'then' statement and without 'else'
- String commonThenSource = null;
- for (Iterator iter = coveredNodes.iterator(); iter.hasNext();) {
- ASTNode node = (ASTNode) iter.next();
- if (!(node instanceof IfStatement))
- return false;
- //
- IfStatement ifStatement = (IfStatement) node;
- if (ifStatement.getElseStatement() != null)
- return false;
- //
- Statement thenStatement = ifStatement.getThenStatement();
- try {
- String thenSource = context.getCompilationUnit().getBuffer().getText(thenStatement.getStartPosition(),
- thenStatement.getLength());
- if (commonThenSource == null) {
- commonThenSource = thenSource;
- } else {
- if (!commonThenSource.equals(thenSource))
- return false;
- }
- } catch (Throwable e) {
- return false;
- }
- }
- if (resultingCollections == null) {
- return true;
- }
- //
- final AST ast = covering.getAST();
- final ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare OR'ed condition
- InfixExpression condition = null;
- boolean hasRightOperand = false;
- Statement thenStatement = null;
- for (Iterator iter = coveredNodes.iterator(); iter.hasNext();) {
- IfStatement ifStatement = (IfStatement) iter.next();
- if (thenStatement == null)
- thenStatement = (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
- Expression ifCondition = getParenthesizedForOrIfNeeded(ast, rewrite, ifStatement.getExpression());
- if (condition == null) {
- condition = ast.newInfixExpression();
- condition.setOperator(orOperator);
- condition.setLeftOperand(ifCondition);
- } else if (!hasRightOperand) {
- condition.setRightOperand(ifCondition);
- hasRightOperand = true;
- } else {
- InfixExpression newCondition = ast.newInfixExpression();
- newCondition.setOperator(orOperator);
- newCondition.setLeftOperand(condition);
- newCondition.setRightOperand(ifCondition);
- condition = newCondition;
- }
- }
- // prepare new IfStatement with OR'ed condition
- IfStatement newIf = ast.newIfStatement();
- newIf.setExpression(condition);
- newIf.setThenStatement(thenStatement);
- //
- ListRewrite listRewriter = null;
- for (Iterator iter = coveredNodes.iterator(); iter.hasNext();) {
- IfStatement ifStatement = (IfStatement) iter.next();
- if (listRewriter == null) {
- Block sourceBlock = (Block) ifStatement.getParent();
- //int insertIndex = sourceBlock.statements().indexOf(ifStatement);
- listRewriter = rewrite.getListRewrite(sourceBlock,
- (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
- }
- if (newIf != null) {
- listRewriter.replace(ifStatement, newIf, null);
- newIf = null;
- } else {
- listRewriter.remove(ifStatement, null);
- }
- }
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOr_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static Expression getParenthesizedForOrIfNeeded(AST ast, ASTRewrite rewrite, Expression expression) {
- boolean addParentheses = false;
- int nodeType = expression.getNodeType();
- addParentheses = nodeType == ASTNode.CONDITIONAL_EXPRESSION || nodeType == ASTNode.ASSIGNMENT
- || nodeType == ASTNode.INSTANCEOF_EXPRESSION;
- expression = (Expression) rewrite.createCopyTarget(expression);
- if (addParentheses) {
- return getParenthesizedExpression(ast, expression);
- }
- return expression;
- }
- private static boolean getSplitOrConditionProposals(IInvocationContext context, ASTNode node,
- Collection resultingCollections) {
- Operator orOperator = InfixExpression.Operator.CONDITIONAL_OR;
- // check that user invokes quick assist on infix expression
- if (!(node instanceof InfixExpression)) {
- return false;
- }
- InfixExpression infixExpression = (InfixExpression) node;
- if (infixExpression.getOperator() != orOperator) {
- return false;
- }
- int offset= isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
- if (offset == -1) {
- return false;
- }
- // check that infix expression belongs to IfStatement
- Statement statement = ASTResolving.findParentStatement(node);
- if (!(statement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) statement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // check that infix expression is part of first level || condition of IfStatement
- InfixExpression topInfixExpression = infixExpression;
- while ((topInfixExpression.getParent() instanceof InfixExpression)
- && ((InfixExpression) topInfixExpression.getParent()).getOperator() == orOperator) {
- topInfixExpression = (InfixExpression) topInfixExpression.getParent();
- }
- if (ifStatement.getExpression() != topInfixExpression) {
- return false;
- }
- //
- if (resultingCollections == null) {
- return true;
- }
- AST ast = ifStatement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
-
- // prepare left and right conditions
- Expression[] newOperands= { null, null };
- breakInfixOperationAtOperation(rewrite, topInfixExpression, orOperator, offset, true, newOperands);
-
- Expression leftCondition= newOperands[0];
- Expression rightCondition= newOperands[1];
-
- // prepare first statement
- IfStatement firstIf = ast.newIfStatement();
- firstIf.setExpression(leftCondition);
- firstIf.setThenStatement((Statement) rewrite.createCopyTarget(ifStatement.getThenStatement()));
- // prepare second statement
- IfStatement secondIf = ast.newIfStatement();
- secondIf.setExpression(rightCondition);
- secondIf.setThenStatement((Statement) rewrite.createCopyTarget(ifStatement.getThenStatement()));
- // add first and second IfStatement's
- Block sourceBlock = (Block) ifStatement.getParent();
- int insertIndex = sourceBlock.statements().indexOf(ifStatement);
- ListRewrite listRewriter = rewrite.getListRewrite(sourceBlock,
- (ChildListPropertyDescriptor) statement.getLocationInParent());
- listRewriter.replace(ifStatement, firstIf, null);
- listRewriter.insertAt(secondIf, insertIndex + 1, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_splitOrCondition_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getInverseConditionalExpressionProposals(IInvocationContext context, ASTNode covering,
- Collection resultingCollections) {
- // try to find conditional expression as parent
- while (covering instanceof Expression) {
- if (covering instanceof ConditionalExpression)
- break;
- covering = covering.getParent();
- }
- if (!(covering instanceof ConditionalExpression)) {
- return false;
- }
- ConditionalExpression expression = (ConditionalExpression) covering;
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = covering.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare new conditional expression
- ConditionalExpression newExpression = ast.newConditionalExpression();
- newExpression.setExpression(getInversedBooleanExpression(rewrite, expression.getExpression()));
- newExpression.setThenExpression((Expression) rewrite.createCopyTarget(expression.getElseExpression()));
- newExpression.setElseExpression((Expression) rewrite.createCopyTarget(expression.getThenExpression()));
- // replace old expression with new
- rewrite.replace(expression, newExpression, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditionalExpression_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(),
- rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getExchangeInnerAndOuterIfConditionsProposals(IInvocationContext context, ASTNode node,
- Collection resultingCollections) {
- boolean result = false;
- //
- Statement statement = ASTResolving.findParentStatement(node);
- if (!(statement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement = (IfStatement) statement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- // case when current IfStatement is sole child of another IfStatement
- {
- IfStatement outerIf = null;
- if (ifStatement.getParent() instanceof IfStatement) {
- outerIf = (IfStatement) ifStatement.getParent();
- } else if (ifStatement.getParent() instanceof Block) {
- Block block = (Block) ifStatement.getParent();
- if ((block.getParent() instanceof IfStatement) && (block.statements().size() == 1)) {
- outerIf = (IfStatement) block.getParent();
- }
- }
- if ((outerIf != null) && (outerIf.getElseStatement() == null)) {
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = statement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare conditions
- Expression outerCondition = (Expression) rewrite.createCopyTarget(outerIf.getExpression());
- Expression innerCondition = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
- // exchange conditions
- rewrite.replace(outerIf.getExpression(), innerCondition, null);
- rewrite.replace(ifStatement.getExpression(), outerCondition, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_exchangeInnerAndOuterIfConditions_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label,
- context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- result = true;
- }
- }
- // case when current IfStatement has another IfStatement as sole child
- {
- IfStatement innerIf = null;
- if (ifStatement.getThenStatement() instanceof IfStatement) {
- innerIf = (IfStatement) ifStatement.getThenStatement();
- } else if (ifStatement.getThenStatement() instanceof Block) {
- Block block = (Block) ifStatement.getThenStatement();
- if ((block.statements().size() == 1) && (block.statements().get(0) instanceof IfStatement)) {
- innerIf = (IfStatement) block.statements().get(0);
- }
- }
- if ((innerIf != null) && (innerIf.getElseStatement() == null)) {
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast = statement.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare conditions
- Expression innerCondition = (Expression) rewrite.createCopyTarget(innerIf.getExpression());
- Expression outerCondition = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
- // exchange conditions
- rewrite.replace(innerIf.getExpression(), outerCondition, null);
- rewrite.replace(ifStatement.getExpression(), innerCondition, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_exchangeInnerAndOuterIfConditions_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label,
- context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- result = true;
- }
- }
- return result;
- }
- private static boolean getExchangeOperandsProposals(IInvocationContext context, ASTNode node,
- Collection resultingCollections) {
- // check that user invokes quick assist on infix expression
- if (!(node instanceof InfixExpression)) {
- return false;
- }
- InfixExpression infixExpression = (InfixExpression) node;
- Operator operator = infixExpression.getOperator();
- if ((operator != InfixExpression.Operator.CONDITIONAL_AND) && (operator != InfixExpression.Operator.AND)
- && (operator != InfixExpression.Operator.CONDITIONAL_OR) && (operator != InfixExpression.Operator.OR)
- && (operator != InfixExpression.Operator.EQUALS) && (operator != InfixExpression.Operator.PLUS)
- && (operator != InfixExpression.Operator.TIMES) && (operator != InfixExpression.Operator.XOR)) {
- return false;
- }
-
- int offset= isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
- if (offset == -1) {
- return false;
- }
-
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- AST ast = infixExpression.getAST();
- ASTRewrite rewrite = ASTRewrite.create(ast);
- // prepare left and right expressions
- Expression leftExpression = null;
- Expression rightExpression = null;
- InfixExpression currentExpression = infixExpression;
- leftExpression= combineOperands(rewrite, leftExpression, infixExpression.getLeftOperand(), true, operator);
- if (infixExpression.getRightOperand().getStartPosition() <= context.getSelectionOffset()) {
- leftExpression= combineOperands(rewrite, leftExpression, infixExpression.getRightOperand(), true, operator);
- } else {
- rightExpression= combineOperands(rewrite, rightExpression, infixExpression.getRightOperand(), true, operator);
- }
- for (Iterator iter= currentExpression.extendedOperands().iterator(); iter.hasNext();) {
- Expression extendedOperand= (Expression) iter.next();
- if (extendedOperand.getStartPosition() <= context.getSelectionOffset()) {
- leftExpression= combineOperands(rewrite, leftExpression, extendedOperand, true, operator);
- } else {
- rightExpression= combineOperands(rewrite, rightExpression, extendedOperand, true, operator);
- }
- }
- // create new infix expression
- InfixExpression newInfix = ast.newInfixExpression();
- newInfix.setOperator(operator);
- newInfix.setLeftOperand(rightExpression);
- newInfix.setRightOperand(leftExpression);
- rewrite.replace(infixExpression, newInfix, null);
- // add correction proposal
- String label = CorrectionMessages.AdvancedQuickAssistProcessor_exchangeOperands_description;
- Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- /**
- * Breaks an infix operation with possible extended operators at the given operator and returns the new left and right operands.
- * a & b & c -> [[a' & b' ] & c' ] (c' == copy of c)
- * @param rewrite
- * @param expression
- * @param operator
- * @param operatorOffset
- */
- private static void breakInfixOperationAtOperation(ASTRewrite rewrite, Expression expression, Operator operator, int operatorOffset, boolean removeParenthesis, Expression[] res) {
- if (expression.getStartPosition() + expression.getLength() <= operatorOffset) {
- // add to the left
- res[0]= combineOperands(rewrite, res[0], expression, removeParenthesis, operator);
- return;
- }
- if (operatorOffset <= expression.getStartPosition()) {
- // add to the right
- res[1]= combineOperands(rewrite, res[1], expression, removeParenthesis, operator);
- return;
- }
- if (!(expression instanceof InfixExpression)) {
- throw new IllegalArgumentException("Cannot break up non-infix expression"); //$NON-NLS-1$
- }
- InfixExpression infixExpression= (InfixExpression) expression;
- if (infixExpression.getOperator() != operator) {
- throw new IllegalArgumentException("Incompatible operator"); //$NON-NLS-1$
- }
- breakInfixOperationAtOperation(rewrite, infixExpression.getLeftOperand(), operator, operatorOffset, removeParenthesis, res);
- breakInfixOperationAtOperation(rewrite, infixExpression.getRightOperand(), operator, operatorOffset, removeParenthesis, res);
-
- List extended= infixExpression.extendedOperands();
- for (int i= 0; i < extended.size(); i++) {
- breakInfixOperationAtOperation(rewrite, (Expression) extended.get(i), operator, operatorOffset, removeParenthesis, res);
- }
- }
-
- private static Expression combineOperands(ASTRewrite rewrite, Expression existing, Expression nodeToAdd, boolean removeParenthesis, Operator operator) {
- if (existing == null && removeParenthesis) {
- while (nodeToAdd instanceof ParenthesizedExpression) {
- nodeToAdd= ((ParenthesizedExpression) nodeToAdd).getExpression();
- }
- }
- Expression newRight= (Expression) rewrite.createMoveTarget(nodeToAdd);
- if (existing == null) {
- return newRight;
- }
- AST ast= rewrite.getAST();
- InfixExpression infix= ast.newInfixExpression();
- infix.setOperator(operator);
- infix.setLeftOperand(existing);
- infix.setRightOperand(newRight);
- return infix;
- }
-
-// private static boolean isNegated(Expression expression) {
-// if (!(expression.getParent() instanceof ParenthesizedExpression))
-// return false;
-//
-// ParenthesizedExpression parenthesis= (ParenthesizedExpression)expression.getParent();
-// if (!(parenthesis.getParent() instanceof PrefixExpression))
-// return false;
-//
-// PrefixExpression prefix= (PrefixExpression)parenthesis.getParent();
-// if (!(prefix.getOperator() == PrefixExpression.Operator.NOT))
-// return false;
-//
-// return true;
-// }
-// private static String[] suggestLocalVariableNames(IJavaScriptUnit cu, ITypeBinding binding) {
-// return StubUtility.getVariableNameSuggestions(StubUtility.LOCAL, cu.getJavaScriptProject(), binding, null, null);
-// }
-
- private static boolean getPickOutStringProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- // we work with String's
- if (!(node instanceof StringLiteral)) {
- return false;
- }
- // user should select part of String
- int selectionPos= context.getSelectionOffset();
- int selectionLen= context.getSelectionLength();
- if (selectionLen == 0) {
- return false;
- }
- int valueStart= node.getStartPosition() + 1;
- int valueEnd= node.getStartPosition() + node.getLength() - 1;
-
- // selection must be inside node and the quotes and not contain the full value
- if ((selectionPos < valueStart) || (selectionPos + selectionLen > valueEnd) || (valueEnd - valueStart == selectionLen)) {
- return false;
- }
-
- // prepare string parts positions
- StringLiteral stringLiteral= (StringLiteral) node;
- String stringValue= stringLiteral.getEscapedValue();
-
- int firstPos= selectionPos - node.getStartPosition();
- int secondPos= firstPos + selectionLen;
-
-
- // prepare new string literals
-
- AST ast= node.getAST();
- StringLiteral leftLiteral= ast.newStringLiteral();
- StringLiteral centerLiteral= ast.newStringLiteral();
- StringLiteral rightLiteral= ast.newStringLiteral();
- try {
- leftLiteral.setEscapedValue('"' + stringValue.substring(1, firstPos) + '"');
- centerLiteral.setEscapedValue('"' + stringValue.substring(firstPos, secondPos) + '"');
- rightLiteral.setEscapedValue('"' + stringValue.substring(secondPos, stringValue.length() - 1) + '"');
- } catch (IllegalArgumentException e) {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- // prepare new expression instead of StringLiteral
- InfixExpression expression= ast.newInfixExpression();
- expression.setOperator(InfixExpression.Operator.PLUS);
- if (firstPos != 1 ) {
- expression.setLeftOperand(leftLiteral);
- }
-
-
- if (firstPos == 1) {
- expression.setLeftOperand(centerLiteral);
- } else {
- expression.setRightOperand(centerLiteral);
- }
-
- if (secondPos < stringValue.length() - 1) {
- if (firstPos == 1) {
- expression.setRightOperand(rightLiteral);
- } else {
- expression.extendedOperands().add(rightLiteral);
- }
- }
- // use new expression instead of old StirngLiteral
- rewrite.replace(stringLiteral, expression, null);
- // add correction proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_pickSelectedString;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- proposal.addLinkedPosition(rewrite.track(centerLiteral), true, "CENTER_STRING"); //$NON-NLS-1$
- resultingCollections.add(proposal);
- return true;
- }
-
- private static Statement getSingleStatement(Statement statement) {
- if (statement instanceof Block) {
- List blockStatements= ((Block) statement).statements();
- if (blockStatements.size() != 1) {
- return null;
- }
- return (Statement) blockStatements.get(0);
- }
- return statement;
- }
-
- private static boolean getReplaceIfElseWithConditionalProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- if (!(node instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement= (IfStatement) node;
- Statement thenStatement= getSingleStatement(ifStatement.getThenStatement());
- Statement elseStatement= getSingleStatement(ifStatement.getElseStatement());
- if (thenStatement == null || elseStatement == null) {
- return false;
- }
- Expression assigned= null;
- Expression thenExpression= null;
- Expression elseExpression= null;
-
- ITypeBinding exprBinding= null;
- if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) {
- thenExpression= ((ReturnStatement) thenStatement).getExpression();
- elseExpression= ((ReturnStatement) elseStatement).getExpression();
- FunctionDeclaration declaration= ASTResolving.findParentMethodDeclaration(node);
- if (declaration == null || declaration.isConstructor()) {
- return false;
- }
- exprBinding= declaration.getReturnType2().resolveBinding();
- } else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) {
- Expression inner1= ((ExpressionStatement) thenStatement).getExpression();
- Expression inner2= ((ExpressionStatement) elseStatement).getExpression();
- if (inner1 instanceof Assignment && inner2 instanceof Assignment) {
- Assignment assign1= (Assignment) inner1;
- Assignment assign2= (Assignment) inner2;
- Expression left1= assign1.getLeftHandSide();
- Expression left2= assign2.getLeftHandSide();
- if (left1 instanceof Name && left2 instanceof Name && assign1.getOperator() == assign2.getOperator()) {
- IBinding bind1= ((Name) left1).resolveBinding();
- IBinding bind2= ((Name) left2).resolveBinding();
- if (bind1 == bind2 && bind1 instanceof IVariableBinding) {
- assigned= left1;
- exprBinding= ((IVariableBinding) bind1).getType();
- thenExpression= assign1.getRightHandSide();
- elseExpression= assign2.getRightHandSide();
- }
- }
- }
- }
- if (thenExpression == null || elseExpression == null) {
- return false;
- }
-
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast= node.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_replaceIfWithConditional;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
-
-
- // prepare conditional expression
- ConditionalExpression conditionalExpression = ast.newConditionalExpression();
- Expression conditionCopy= (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
- conditionalExpression.setExpression(conditionCopy);
- Expression thenCopy= (Expression) rewrite.createCopyTarget(thenExpression);
- Expression elseCopy= (Expression) rewrite.createCopyTarget(elseExpression);
-
-
- if (!JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaScriptProject())) {
- ITypeBinding thenBinding= thenExpression.resolveTypeBinding();
- ITypeBinding elseBinding= elseExpression.resolveTypeBinding();
- if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) {
- proposal.createImportRewrite(context.getASTRoot());
- }
- }
- conditionalExpression.setThenExpression(thenCopy);
- conditionalExpression.setElseExpression(elseCopy);
-
- // replace 'if' statement with conditional expression
- if (assigned == null) {
- ReturnStatement returnStatement = ast.newReturnStatement();
- returnStatement.setExpression(conditionalExpression);
- rewrite.replace(ifStatement, returnStatement, null);
- } else {
- Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide((Expression) rewrite.createCopyTarget(assigned));
- assignment.setRightHandSide(conditionalExpression);
- assignment.setOperator(((Assignment) assigned.getParent()).getOperator());
-
- ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
- rewrite.replace(ifStatement, expressionStatement, null);
- }
-
- // add correction proposal
- resultingCollections.add(proposal);
- return true;
- }
-
- private static ReturnStatement createReturnExpression(ASTRewrite rewrite, Expression expression) {
- AST ast= rewrite.getAST();
- ReturnStatement thenReturn = ast.newReturnStatement();
- thenReturn.setExpression((Expression) rewrite.createCopyTarget(expression));
- return thenReturn;
- }
-
- private static Statement createAssignmentStatement(ASTRewrite rewrite, Assignment.Operator assignmentOperator, Expression origAssignee, Expression origAssigned) {
- AST ast= rewrite.getAST();
- Assignment elseAssignment= ast.newAssignment();
- elseAssignment.setOperator(assignmentOperator);
- elseAssignment.setLeftHandSide((Expression) rewrite.createCopyTarget(origAssignee));
- elseAssignment.setRightHandSide((Expression) rewrite.createCopyTarget(origAssigned));
- ExpressionStatement statement = ast.newExpressionStatement(elseAssignment);
- return statement;
- }
-
- private static boolean getReplaceConditionalWithIfElseProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) {
- // check that parent statement is assignment
- while (!(covering instanceof ConditionalExpression) && covering instanceof Expression) {
- covering= covering.getParent();
- }
- if (!(covering instanceof ConditionalExpression)) {
- return false;
- }
-
- StructuralPropertyDescriptor locationInParent= covering.getLocationInParent();
- if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY) {
- if (covering.getParent().getLocationInParent() != ExpressionStatement.EXPRESSION_PROPERTY) {
- return false;
- }
- } else if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
- ASTNode statement= covering.getParent().getParent();
- if (!(statement instanceof VariableDeclarationStatement) || statement.getLocationInParent() != Block.STATEMENTS_PROPERTY) {
- return false;
- }
- } else if (locationInParent != ReturnStatement.EXPRESSION_PROPERTY) {
- return false;
- }
-
- ConditionalExpression conditional= (ConditionalExpression) covering;
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast= covering.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- // prepare new 'if' statement
- Expression expression= conditional.getExpression();
- while (expression instanceof ParenthesizedExpression) {
- expression= ((ParenthesizedExpression) expression).getExpression();
- }
- IfStatement ifStatement= ast.newIfStatement();
- ifStatement.setExpression((Expression) rewrite.createCopyTarget(expression));
- if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY) {
- Assignment assignment= (Assignment) covering.getParent();
- Expression assignee= assignment.getLeftHandSide();
- Assignment.Operator op= assignment.getOperator();
-
- ifStatement.setThenStatement(createAssignmentStatement(rewrite, op, assignee, conditional.getThenExpression()));
- ifStatement.setElseStatement(createAssignmentStatement(rewrite, op, assignee, conditional.getElseExpression()));
-
- // replace return conditional expression with if/then/else/return
- rewrite.replace(covering.getParent().getParent(), ifStatement, null);
-
- } else if (locationInParent == ReturnStatement.EXPRESSION_PROPERTY) {
- ifStatement.setThenStatement(createReturnExpression(rewrite, conditional.getThenExpression()));
- ifStatement.setElseStatement(createReturnExpression(rewrite, conditional.getElseExpression()));
- //
- // replace return conditional expression with if/then/else/return
- rewrite.replace(conditional.getParent(), ifStatement, null);
- } else if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
- VariableDeclarationFragment frag= (VariableDeclarationFragment) covering.getParent();
- Assignment.Operator op= Assignment.Operator.ASSIGN;
-
- Expression assignee= frag.getName();
- ifStatement.setThenStatement(createAssignmentStatement(rewrite, op, assignee, conditional.getThenExpression()));
- ifStatement.setElseStatement(createAssignmentStatement(rewrite, op, assignee, conditional.getElseExpression()));
-
- rewrite.set(frag, VariableDeclarationFragment.INITIALIZER_PROPERTY, null, null); // clear initializer
-
- ASTNode statement= frag.getParent();
- rewrite.getListRewrite(statement.getParent(), Block.STATEMENTS_PROPERTY).insertAfter(ifStatement, statement, null);
- }
-
- // add correction proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_replaceConditionalWithIf;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getInverseLocalVariableProposals(IInvocationContext context,
- ASTNode covering,
- Collection resultingCollections) {
- final AST ast= covering.getAST();
- // cursor should be placed on variable name
- if (!(covering instanceof SimpleName)) {
- return false;
- }
- SimpleName coveringName= (SimpleName) covering;
- if (!coveringName.isDeclaration()) {
- return false;
- }
- // prepare bindings
- final IBinding variableBinding= coveringName.resolveBinding();
- if (!(variableBinding instanceof IVariableBinding)) {
- return false;
- }
- IVariableBinding binding= (IVariableBinding) variableBinding;
- if (binding.isField()) {
- return false;
- }
- // we operate only on boolean variable
- if (!isBoolean(coveringName)) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- // find linked nodes
- final FunctionDeclaration method= ASTResolving.findParentMethodDeclaration(covering);
- SimpleName[] linkedNodes= LinkedNodeFinder.findByBinding(method, variableBinding);
- //
- final ASTRewrite rewrite= ASTRewrite.create(ast);
- // create proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseBooleanVariable;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- final String KEY_NAME= "name"; //$NON-NLS-1$
- final LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label,
- context.getCompilationUnit(),
- rewrite,
- 1,
- image);
- // prepare new variable identifier
- final String oldIdentifier= coveringName.getIdentifier();
- final String notString = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, ""); //$NON-NLS-1$
- final String newIdentifier;
- if (oldIdentifier.startsWith(notString)) {
- int notLength= notString.length();
- if (oldIdentifier.length() > notLength) {
- newIdentifier= Character.toLowerCase(oldIdentifier.charAt(notLength)) + oldIdentifier.substring(notLength + 1);
- } else {
- newIdentifier= oldIdentifier;
- }
- } else {
- newIdentifier= Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_negatedVariableName, Character.toUpperCase(oldIdentifier.charAt(0)) + oldIdentifier.substring(1));
- }
- //
- proposal.addLinkedPositionProposal(KEY_NAME, newIdentifier, null);
- proposal.addLinkedPositionProposal(KEY_NAME, oldIdentifier, null);
- // iterate over linked nodes and replace variable references with negated reference
- final HashSet renamedNames= new HashSet();
- for (int i= 0; i < linkedNodes.length; i++) {
- SimpleName name= linkedNodes[i];
- if (renamedNames.contains(name)) {
- continue;
- }
- // prepare new name with new identifier
- SimpleName newName= ast.newSimpleName(newIdentifier);
- proposal.addLinkedPosition(rewrite.track(newName), name == coveringName, KEY_NAME);
- //
- StructuralPropertyDescriptor location= name.getLocationInParent();
- if (location == SingleVariableDeclaration.NAME_PROPERTY) {
- // set new name
- rewrite.replace(name, newName, null);
- } else if (location == Assignment.LEFT_HAND_SIDE_PROPERTY) {
- Assignment assignment= (Assignment) name.getParent();
- Expression expression= assignment.getRightHandSide();
- int exStart= expression.getStartPosition();
- int exEnd= exStart + expression.getLength();
- // collect all names that are used in assignments
- HashSet overlapNames= new HashSet();
- for (int j= 0; j < linkedNodes.length; j++) {
- SimpleName name2= linkedNodes[j];
- if (name2 == null) {
- continue;
- }
- int name2Start= name2.getStartPosition();
- if (exStart <= name2Start && name2Start < exEnd) {
- overlapNames.add(name2);
- }
- }
- // prepare inverted expression
- SimpleNameRenameProvider provider= new SimpleNameRenameProvider() {
- public SimpleName getRenamed(SimpleName simpleName) {
- if (simpleName.resolveBinding() == variableBinding) {
- renamedNames.add(simpleName);
- return ast.newSimpleName(newIdentifier);
- }
- return null;
- }
- };
- Expression inversedExpression= getInversedBooleanExpression(rewrite, expression, provider);
- // if any name was not renamed during expression inverting, we can not already rename it, so fail to create assist
- for (Iterator iter= overlapNames.iterator(); iter.hasNext();) {
- Object o= iter.next();
- if (!renamedNames.contains(o)) {
- return false;
- }
- }
- // check operator and replace if needed
- Assignment.Operator operator= assignment.getOperator();
- if (operator == Assignment.Operator.BIT_AND_ASSIGN) {
- Assignment newAssignment= ast.newAssignment();
- newAssignment.setLeftHandSide(newName);
- newAssignment.setRightHandSide(inversedExpression);
- newAssignment.setOperator(Assignment.Operator.BIT_OR_ASSIGN);
- rewrite.replace(assignment, newAssignment, null);
- } else if (operator == Assignment.Operator.BIT_OR_ASSIGN) {
- Assignment newAssignment= ast.newAssignment();
- newAssignment.setLeftHandSide(newName);
- newAssignment.setRightHandSide(inversedExpression);
- newAssignment.setOperator(Assignment.Operator.BIT_AND_ASSIGN);
- rewrite.replace(assignment, newAssignment, null);
- } else {
- rewrite.replace(expression, inversedExpression, null);
- // set new name
- rewrite.replace(name, newName, null);
- }
- } else if (location == VariableDeclarationFragment.NAME_PROPERTY) {
- // replace initializer for variable
- VariableDeclarationFragment vdf= (VariableDeclarationFragment) name.getParent();
- Expression expression= vdf.getInitializer();
- if (expression != null) {
- rewrite.replace(expression, getInversedBooleanExpression(rewrite, expression), null);
- }
- // set new name
- rewrite.replace(name, newName, null);
- } else if ((name.getParent() instanceof PrefixExpression)
- && (((PrefixExpression) name.getParent()).getOperator() == PrefixExpression.Operator.NOT)) {
- rewrite.replace(name.getParent(), newName, null);
- } else {
- PrefixExpression expression= ast.newPrefixExpression();
- expression.setOperator(PrefixExpression.Operator.NOT);
- expression.setOperand(newName);
- rewrite.replace(name, expression, null);
- }
- }
- // add correction proposal
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getPushNegationDownProposals(IInvocationContext context,
- ASTNode covering,
- Collection resultingCollections) {
- PrefixExpression negationExpression= null;
- ParenthesizedExpression parenthesizedExpression= null;
- // check for case when cursor is on '!' before parentheses
- if (covering instanceof PrefixExpression) {
- PrefixExpression prefixExpression= (PrefixExpression) covering;
- if ((prefixExpression.getOperator() == PrefixExpression.Operator.NOT)
- && (prefixExpression.getOperand() instanceof ParenthesizedExpression)) {
- negationExpression= prefixExpression;
- parenthesizedExpression= (ParenthesizedExpression) prefixExpression.getOperand();
- }
- }
- // check for case when cursor is on parenthesized expression that is negated
- if ((covering instanceof ParenthesizedExpression)
- && (covering.getParent() instanceof PrefixExpression)
- && (((PrefixExpression) covering.getParent()).getOperator() == PrefixExpression.Operator.NOT)) {
- negationExpression= (PrefixExpression) covering.getParent();
- parenthesizedExpression= (ParenthesizedExpression) covering;
- }
- //
- if (negationExpression == null) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- final AST ast= covering.getAST();
- final ASTRewrite rewrite= ASTRewrite.create(ast);
- // prepared inverted expression
- Expression inversedExpression= getInversedBooleanExpression(rewrite, parenthesizedExpression.getExpression());
- // check, may be we should keep parentheses
- boolean keepParentheses= false;
- if (negationExpression.getParent() instanceof Expression) {
- int parentPrecedence= getExpressionPrecedence((Expression) negationExpression.getParent());
- int inversedExpressionPrecedence= getExpressionPrecedence(inversedExpression);
- keepParentheses= parentPrecedence < inversedExpressionPrecedence;
- }
- // replace negated expression with inverted one
- if (keepParentheses) {
- ParenthesizedExpression pe= ast.newParenthesizedExpression();
- pe.setExpression(inversedExpression);
- rewrite.replace(negationExpression, pe, null);
- } else {
- rewrite.replace(negationExpression, inversedExpression, null);
- }
- // add correction proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_pushNegationDown;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static Expression getBooleanExpression(ASTNode node) {
- if (!(node instanceof Expression)) {
- return null;
- }
-
- // check if the node is a location where it can be negated
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent == QualifiedName.NAME_PROPERTY) {
- node= node.getParent();
- locationInParent= node.getLocationInParent();
- }
- while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
- node= node.getParent();
- locationInParent= node.getLocationInParent();
- }
- Expression expression= (Expression) node;
- if (!isBoolean(expression)) {
- return null;
- }
- if (expression.getParent() instanceof InfixExpression) {
- return expression;
- }
- if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY
- || locationInParent == IfStatement.EXPRESSION_PROPERTY
- || locationInParent == WhileStatement.EXPRESSION_PROPERTY
- || locationInParent == DoStatement.EXPRESSION_PROPERTY
- || locationInParent == ReturnStatement.EXPRESSION_PROPERTY
- || locationInParent == ForStatement.EXPRESSION_PROPERTY
- || locationInParent == FunctionInvocation.ARGUMENTS_PROPERTY
- || locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY
- || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
- || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY
- || locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY
- || locationInParent == ConditionalExpression.EXPRESSION_PROPERTY
- || locationInParent == PrefixExpression.OPERAND_PROPERTY) {
- return expression;
- }
- return null;
- }
-
-
-
- private static boolean getPullNegationUpProposals(IInvocationContext context, ASTNode covering, ArrayList coveredNodes, Collection resultingCollections) {
- if (coveredNodes.size() != 1) {
- return false;
- }
- //
- ASTNode fullyCoveredNode= (ASTNode) coveredNodes.get(0);
-
- Expression expression= getBooleanExpression(fullyCoveredNode);
- if (expression == null) {
- return false;
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- AST ast= expression.getAST();
- final ASTRewrite rewrite= ASTRewrite.create(ast);
- // prepared inverted expression
- Expression inversedExpression= getInversedBooleanExpression(rewrite, expression);
- // prepare ParenthesizedExpression
- ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
- parenthesizedExpression.setExpression(inversedExpression);
- // prepare NOT prefix expression
- PrefixExpression prefixExpression = ast.newPrefixExpression();
- prefixExpression.setOperator(PrefixExpression.Operator.NOT);
- prefixExpression.setOperand(parenthesizedExpression);
- // replace old expression
- rewrite.replace(expression, prefixExpression, null);
- // add correction proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_pullNegationUp;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getJoinIfListInIfElseIfProposals(IInvocationContext context,
- ASTNode covering,
- ArrayList coveredNodes,
- Collection resultingCollections) {
- if (coveredNodes.isEmpty()) {
- return false;
- }
- // check that we have more than one covered statement
- if (coveredNodes.size() < 2) {
- return false;
- }
- // check that all selected nodes are 'if' statements with only 'then' statement
- for (Iterator iter= coveredNodes.iterator(); iter.hasNext();) {
- ASTNode node= (ASTNode) iter.next();
- if (!(node instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement= (IfStatement) node;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
- }
- // we could produce quick assist
- if (resultingCollections == null) {
- return true;
- }
- //
- final AST ast= covering.getAST();
- final ASTRewrite rewrite= ASTRewrite.create(ast);
- //
- IfStatement firstIfStatement= (IfStatement) coveredNodes.get(0);
- IfStatement firstNewIfStatement= null;
- //
- IfStatement prevIfStatement= null;
- for (Iterator iter= coveredNodes.iterator(); iter.hasNext();) {
- IfStatement ifStatement= (IfStatement) iter.next();
- // prepare new 'if' statement
- IfStatement newIfStatement= ast.newIfStatement();
- newIfStatement.setExpression((Expression) rewrite.createMoveTarget(ifStatement.getExpression()));
- // prepare 'then' statement and convert into block if needed
- Statement thenStatement= (Statement) rewrite.createMoveTarget(ifStatement.getThenStatement());
- if (ifStatement.getThenStatement() instanceof IfStatement) {
- IfStatement ifBodyStatement= (IfStatement) ifStatement.getThenStatement();
- if (ifBodyStatement.getElseStatement() == null) {
- Block thenBlock= ast.newBlock();
- thenBlock.statements().add(thenStatement);
- thenStatement= thenBlock;
- }
- }
- newIfStatement.setThenStatement(thenStatement);
- //
- if (prevIfStatement != null) {
- prevIfStatement.setElseStatement(newIfStatement);
- rewrite.remove(ifStatement, null);
- } else {
- firstNewIfStatement= newIfStatement;
- }
- prevIfStatement= newIfStatement;
- }
- rewrite.replace(firstIfStatement, firstNewIfStatement, null);
- // add correction proposal
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_joinIfSequence;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
- private static boolean getConvertSwitchToIfProposals(IInvocationContext context,
- ASTNode covering,
- Collection resultingCollections) {
- if (!(covering instanceof SwitchStatement)) {
- return false;
- }
- // we could produce quick assist (if all 'case' statements end with 'break')
- if (resultingCollections == null) {
- return true;
- }
- //
- final AST ast= covering.getAST();
- final ASTRewrite rewrite= ASTRewrite.create(ast);
- final ImportRewrite importRewrite= CodeStyleConfiguration.createImportRewrite(context.getASTRoot(), true);
- //
- SwitchStatement switchStatement= (SwitchStatement) covering;
- IfStatement firstIfStatement= null;
- IfStatement currentIfStatement= null;
- Block currentBlock= null;
- boolean hasStopAsLastExecutableStatement = false;
- Block defaultBlock= null;
- InfixExpression currentCondition= null;
- boolean defaultFound= false;
- int caseCount = 0;
-
- ArrayList allBlocks= new ArrayList();
- //
- for (Iterator iter= switchStatement.statements().iterator(); iter.hasNext();) {
- Statement statement= (Statement) iter.next();
- if (statement instanceof SwitchCase) {
- SwitchCase switchCase= (SwitchCase) statement;
- caseCount++;
- // special case: pass through
- if (currentBlock != null) {
- if (!hasStopAsLastExecutableStatement) {
- return false;
- }
- currentBlock= null;
- }
- // for 'default' we just will not create condition
- if (switchCase.isDefault()) {
- defaultFound= true;
- if (currentCondition != null) {
- // we can not convert one or more 'case' statements and 'default' nor in conditional if, nor in 'else' without code duplication
- return false;
- }
- continue;
- }
- if (defaultFound) {
- return false;
- }
- // prepare condition
- InfixExpression switchCaseCondition= createSwitchCaseCondition(ast, rewrite, importRewrite, switchStatement, switchCase);
- if (currentCondition == null) {
- currentCondition= switchCaseCondition;
- } else {
- InfixExpression condition= ast.newInfixExpression();
- condition.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
- condition.setLeftOperand(currentCondition);
- condition.setRightOperand(switchCaseCondition);
- currentCondition= condition;
- }
- } else if (statement instanceof BreakStatement) {
- currentBlock= null;
- } else {
- // ensure that current block exists as 'then' statement of 'if'
- if (currentBlock == null) {
- defaultFound= false;
- if (currentCondition != null) {
- IfStatement ifStatement;
- if (firstIfStatement == null) {
- firstIfStatement= ast.newIfStatement();
- ifStatement= firstIfStatement;
- } else {
- ifStatement= ast.newIfStatement();
- currentIfStatement.setElseStatement(ifStatement);
- }
- currentIfStatement= ifStatement;
- ifStatement.setExpression(currentCondition);
- currentCondition= null;
- currentBlock= ast.newBlock();
- ifStatement.setThenStatement(currentBlock);
- allBlocks.add(currentBlock);
- } else {
- // case for default:
- defaultBlock= ast.newBlock();
- currentBlock= defaultBlock;
- allBlocks.add(currentBlock);
- // delay adding of default block
- }
- }
- // add current statement in current block
- {
- hasStopAsLastExecutableStatement = hasStopAsLastExecutableStatement(statement);
- Statement copyStatement= copyStatementExceptBreak(ast, rewrite, statement);
-
-
- currentBlock.statements().add(copyStatement);
- }
- }
- }
- // check, may be we have delayed default block
- if (defaultBlock != null) {
- currentIfStatement.setElseStatement(defaultBlock);
- }
- // remove unnecessary blocks in blocks
- for (int i= 0; i < allBlocks.size(); i++) {
- Block block= (Block) allBlocks.get(i);
- List statements= block.statements();
- if (statements.size() == 1 && statements.get(0) instanceof Block) {
- Block innerBlock= (Block) statements.remove(0);
- block.getParent().setStructuralProperty(block.getLocationInParent(), innerBlock);
- }
- }
- // replace 'switch' with single if-else-if statement
- rewrite.replace(switchStatement, firstIfStatement, null);
- // prepare label, specially for Daniel :-)
- String label= CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf;
-
- // add correction proposal
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label,
- context.getCompilationUnit(),
- rewrite,
- 1,
- image);
- proposal.setImportRewrite(importRewrite);
- resultingCollections.add(proposal);
- return true;
- }
- private static InfixExpression createSwitchCaseCondition(AST ast, ASTRewrite rewrite, ImportRewrite importRewrite,
- SwitchStatement switchStatement, SwitchCase switchCase) {
- InfixExpression condition= ast.newInfixExpression();
- condition.setOperator(InfixExpression.Operator.EQUALS);
- //
- Expression leftExpression= (Expression) rewrite.createCopyTarget(switchStatement.getExpression());
- condition.setLeftOperand(leftExpression);
- //
- Expression rightExpression= null;
- Expression expression= switchCase.getExpression();
- if (expression instanceof SimpleName && ((SimpleName) expression).resolveBinding() instanceof IVariableBinding) {
- ((SimpleName) expression).resolveBinding();
- }
- condition.setRightOperand(rightExpression);
- //
- return condition;
- }
-
-
- private static boolean hasStopAsLastExecutableStatement(Statement lastStatement) {
- if ((lastStatement instanceof ReturnStatement) || (lastStatement instanceof BreakStatement)) {
- return true;
- }
- if (lastStatement instanceof Block) {
- Block block= (Block)lastStatement;
- lastStatement = (Statement) block.statements().get(block.statements().size() - 1);
- return hasStopAsLastExecutableStatement(lastStatement);
- }
- return false;
- }
- private static Statement copyStatementExceptBreak(AST ast, ASTRewrite rewrite, Statement source) {
- if (source instanceof Block) {
- Block block= (Block) source;
- Block newBlock= ast.newBlock();
- for (Iterator iter= block.statements().iterator(); iter.hasNext();) {
- Statement statement= (Statement) iter.next();
- if (statement instanceof BreakStatement) {
- continue;
- }
- newBlock.statements().add(copyStatementExceptBreak(ast, rewrite, statement));
- }
- return newBlock;
- }
- return (Statement) rewrite.createMoveTarget(source);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssignToVariableAssistProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssignToVariableAssistProposal.java
deleted file mode 100644
index ceee8c40..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssignToVariableAssistProposal.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Proposals for 'Assign to variable' quick assist
- * - Assign an expression from an ExpressionStatement to a local or field
- * - Assign a parameter to a field
- * */
-public class AssignToVariableAssistProposal extends LinkedCorrectionProposal {
-
- public static final int LOCAL= 1;
- public static final int FIELD= 2;
-
- private final String KEY_NAME= "name"; //$NON-NLS-1$
- private final String KEY_TYPE= "type"; //$NON-NLS-1$
-
- private final int fVariableKind;
- private final ASTNode fNodeToAssign; // ExpressionStatement or SingleVariableDeclaration
- private final ITypeBinding fTypeBinding;
-
- private VariableDeclarationFragment fExistingFragment;
-
- public AssignToVariableAssistProposal(IJavaScriptUnit cu, int variableKind, ExpressionStatement node, ITypeBinding typeBinding, int relevance) {
- super("", cu, null, relevance, null); //$NON-NLS-1$
-
- fVariableKind= variableKind;
- fNodeToAssign= node;
-
- fTypeBinding= typeBinding;
- if (variableKind == LOCAL) {
- setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntolocal_description);
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL));
- } else {
- setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntofield_description);
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE));
- }
- createImportRewrite((JavaScriptUnit) node.getRoot());
- }
-
- public AssignToVariableAssistProposal(IJavaScriptUnit cu, SingleVariableDeclaration parameter, VariableDeclarationFragment existingFragment, ITypeBinding typeBinding, int relevance) {
- super("", cu, null, relevance, null); //$NON-NLS-1$
-
- fVariableKind= FIELD;
- fNodeToAssign= parameter;
- fTypeBinding= typeBinding;
- fExistingFragment= existingFragment;
-
- if (existingFragment == null) {
- setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assignparamtofield_description);
- } else {
- setDisplayName(Messages.format(CorrectionMessages.AssignToVariableAssistProposal_assigntoexistingfield_description, existingFragment.getName().getIdentifier()));
- }
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE));
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- if (fVariableKind == FIELD) {
- return doAddField();
- } else { // LOCAL
- return doAddLocal();
- }
- }
-
- private ASTRewrite doAddLocal() throws CoreException {
- Expression expression= ((ExpressionStatement) fNodeToAssign).getExpression();
- AST ast= fNodeToAssign.getAST();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- createImportRewrite((JavaScriptUnit) fNodeToAssign.getRoot());
-
- String[] varNames= suggestLocalVariableNames(fTypeBinding, expression);
- for (int i= 0; i < varNames.length; i++) {
- addLinkedPositionProposal(KEY_NAME, varNames[i], null);
- }
-
- VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
- newDeclFrag.setName(ast.newSimpleName(varNames[0]));
- newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));
-
- // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
- VariableDeclarationExpression newDecl= ast.newVariableDeclarationExpression(newDeclFrag);
-
- Type type= evaluateType(ast);
- newDecl.setType(type);
-
- rewrite.replace(expression, newDecl, null);
-
- addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
- addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
- setEndPosition(rewrite.track(fNodeToAssign)); // set cursor after expression statement
-
- return rewrite;
- }
-
- private ASTRewrite doAddField() throws CoreException {
- boolean isParamToField= fNodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
-
- ASTNode newTypeDecl= ASTResolving.findParentType(fNodeToAssign);
- if (newTypeDecl == null) {
- return null;
- }
-
- Expression expression= isParamToField ? ((SingleVariableDeclaration) fNodeToAssign).getName() : ((ExpressionStatement) fNodeToAssign).getExpression();
-
- AST ast= newTypeDecl.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- createImportRewrite((JavaScriptUnit) fNodeToAssign.getRoot());
-
- BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(fNodeToAssign);
- Block body;
- if (bodyDecl instanceof FunctionDeclaration) {
- body= ((FunctionDeclaration) bodyDecl).getBody();
- } else if (bodyDecl instanceof Initializer) {
- body= ((Initializer) bodyDecl).getBody();
- } else {
- return null;
- }
-
- boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
- boolean isStatic= Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
- boolean isConstructorParam= isParamToField && fNodeToAssign.getParent() instanceof FunctionDeclaration && ((FunctionDeclaration) fNodeToAssign.getParent()).isConstructor();
- int modifiers= Modifier.PRIVATE;
- if (isStatic) {
- modifiers |= Modifier.STATIC;
- } else if (isConstructorParam) {
- modifiers |= Modifier.FINAL;
- }
-
- VariableDeclarationFragment newDeclFrag= addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression);
- String varName= newDeclFrag.getName().getIdentifier();
-
- Assignment assignment= ast.newAssignment();
- assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
-
- boolean needsThis= StubUtility.useThisForFieldAccess(getCompilationUnit().getJavaScriptProject());
- if (isParamToField) {
- needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
- }
-
- SimpleName accessName= ast.newSimpleName(varName);
- if (needsThis) {
- FieldAccess fieldAccess= ast.newFieldAccess();
- fieldAccess.setName(accessName);
- if (isStatic) {
- String typeName= ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
- fieldAccess.setExpression(ast.newSimpleName(typeName));
- } else {
- fieldAccess.setExpression(ast.newThisExpression());
- }
- assignment.setLeftHandSide(fieldAccess);
- } else {
- assignment.setLeftHandSide(accessName);
- }
-
- ASTNode selectionNode;
- if (isParamToField) {
- // assign parameter to field
- ExpressionStatement statement= ast.newExpressionStatement(assignment);
- int insertIdx= findAssignmentInsertIndex(body.statements());
- rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
- selectionNode= statement;
-
- } else {
- rewrite.replace(expression, assignment, null);
- selectionNode= fNodeToAssign;
- }
-
- addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
- if (!isParamToField) {
- FieldDeclaration fieldDeclaration= (FieldDeclaration) newDeclFrag.getParent();
- addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
- }
- addLinkedPosition(rewrite.track(accessName), true, KEY_NAME);
- setEndPosition(rewrite.track(selectionNode));
-
- return rewrite;
- }
-
- private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) throws CoreException {
- if (fExistingFragment != null) {
- return fExistingFragment;
- }
-
- ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
- List decls= (List) newTypeDecl.getStructuralProperty(property);
- AST ast= newTypeDecl.getAST();
- String[] varNames= suggestFieldNames(fTypeBinding, expression, modifiers);
- for (int i= 0; i < varNames.length; i++) {
- addLinkedPositionProposal(KEY_NAME, varNames[i], null);
- }
- String varName= varNames[0];
-
- VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
- newDeclFrag.setName(ast.newSimpleName(varName));
-
- FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);
-
- Type type= evaluateType(ast);
- newDecl.setType(type);
- newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
-
- ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false);
-
- int insertIndex= findFieldInsertIndex(decls, fNodeToAssign.getStartPosition());
- rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);
-
- return newDeclFrag;
- }
-
-
- private Type evaluateType(AST ast) throws CoreException {
- ITypeBinding[] proposals= ASTResolving.getRelaxingTypes(ast, fTypeBinding);
- for (int i= 0; i < proposals.length; i++) {
- addLinkedPositionProposal(KEY_TYPE, proposals[i]);
- }
- return getImportRewrite().addImport(fTypeBinding, ast);
- }
-
- private String[] suggestLocalVariableNames(ITypeBinding binding, Expression expression) {
- IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- return StubUtility.getVariableNameSuggestions(StubUtility.LOCAL, project, binding, expression, getUsedVariableNames());
- }
-
- private String[] suggestFieldNames(ITypeBinding binding, Expression expression, int modifiers) {
- IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- int varKind= Modifier.isStatic(modifiers) ? StubUtility.STATIC_FIELD : StubUtility.INSTANCE_FIELD;
- return StubUtility.getVariableNameSuggestions(varKind, project, binding, expression, getUsedVariableNames());
- }
-
- private Collection getUsedVariableNames() {
- return Arrays.asList(ASTResolving.getUsedVariableNames(fNodeToAssign));
- }
-
- private int findAssignmentInsertIndex(List statements) {
-
- HashSet paramsBefore= new HashSet();
- List params = ((FunctionDeclaration) fNodeToAssign.getParent()).parameters();
- for (int i = 0; i < params.size() && (params.get(i) != fNodeToAssign); i++) {
- SingleVariableDeclaration decl= (SingleVariableDeclaration) params.get(i);
- paramsBefore.add(decl.getName().getIdentifier());
- }
-
- int i= 0;
- for (i = 0; i < statements.size(); i++) {
- Statement curr= (Statement) statements.get(i);
- switch (curr.getNodeType()) {
- case ASTNode.CONSTRUCTOR_INVOCATION:
- case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
- break;
- case ASTNode.EXPRESSION_STATEMENT:
- Expression expr= ((ExpressionStatement) curr).getExpression();
- if (expr instanceof Assignment) {
- Assignment assignment= (Assignment) expr;
- Expression rightHand = assignment.getRightHandSide();
- if (rightHand instanceof SimpleName && paramsBefore.contains(((SimpleName) rightHand).getIdentifier())) {
- IVariableBinding binding = Bindings.getAssignedVariable(assignment);
- if (binding == null || binding.isField()) {
- break;
- }
- }
- }
- return i;
- default:
- return i;
-
- }
- }
- return i;
-
- }
-
- private int findFieldInsertIndex(List decls, int currPos) {
- for (int i= decls.size() - 1; i >= 0; i--) {
- ASTNode curr= (ASTNode) decls.get(i);
- if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) {
- return i + 1;
- }
- }
- return 0;
- }
-
- /**
- * Returns the variable kind.
- * @return int
- */
- public int getVariableKind() {
- return fVariableKind;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssistContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssistContext.java
deleted file mode 100644
index 5dcca525..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/AssistContext.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-/**
- */
-public class AssistContext implements IInvocationContext {
-
- private IJavaScriptUnit fCompilationUnit;
- private int fOffset;
- private int fLength;
-
- private JavaScriptUnit fASTRoot;
-
- /*
- * Constructor for CorrectionContext.
- */
- public AssistContext(IJavaScriptUnit cu, int offset, int length) {
- fCompilationUnit= cu;
- fOffset= offset;
- fLength= length;
-
- fASTRoot= null;
- }
-
- /**
- * Returns the compilation unit.
- * @return Returns a IJavaScriptUnit
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * Returns the length.
- * @return int
- */
- public int getSelectionLength() {
- return fLength;
- }
-
- /**
- * Returns the offset.
- * @return int
- */
- public int getSelectionOffset() {
- return fOffset;
- }
-
- public JavaScriptUnit getASTRoot() {
- if (fASTRoot == null) {
- fASTRoot= ASTProvider.getASTProvider().getAST(fCompilationUnit, ASTProvider.WAIT_YES, null);
- if (fASTRoot == null) {
- // see bug 63554
- fASTRoot= ASTResolving.createQuickFixAST(fCompilationUnit, null);
- }
- }
- return fASTRoot;
- }
-
-
- /**
- * @param root The ASTRoot to set.
- */
- public void setASTRoot(JavaScriptUnit root) {
- fASTRoot= root;
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IInvocationContext#getCoveringNode()
- */
- public ASTNode getCoveringNode() {
- NodeFinder finder= new NodeFinder(fOffset, fLength);
- getASTRoot().accept(finder);
- return finder.getCoveringNode();
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IInvocationContext#getCoveredNode()
- */
- public ASTNode getCoveredNode() {
- NodeFinder finder= new NodeFinder(fOffset, fLength);
- getASTRoot().accept(finder);
- return finder.getCoveredNode();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CUCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CUCorrectionProposal.java
deleted file mode 100644
index bfe0876e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CUCorrectionProposal.java
+++ /dev/null
@@ -1,584 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Iterator;
-
-import org.eclipse.compare.rangedifferencer.IRangeComparator;
-import org.eclipse.compare.rangedifferencer.RangeDifference;
-import org.eclipse.compare.rangedifferencer.RangeDifferencer;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.ProposalPosition;
-import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.DocumentChange;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.compare.JavaTokenComparator;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-/**
- * A proposal for quick fixes and quick assist that work on a single compilation unit.
- * Either a {@link TextChange text change} is directly passed in the constructor or method
- * {@link #addEdits(IDocument, TextEdit)} is overridden to provide the text edits that are
- * applied to the document when the proposal is evaluated.
- * <p>
- * The proposal takes care of the preview of the changes as proposal information.
- * </p>
- *
- */
-public class CUCorrectionProposal extends ChangeCorrectionProposal {
-
- private IJavaScriptUnit fCompilationUnit;
- private LinkedProposalModel fLinkedProposalModel;
-
-
- /**
- * Constructs a correction proposal working on a compilation unit with a given text change
- *
- * @param name the name that is displayed in the proposal selection dialog.
- * @param cu the compilation unit on that the change works.
- * @param change the change that is executed when the proposal is applied or <code>null</code>
- * if implementors override {@link #addEdits(IDocument, TextEdit)} to provide
- * the text edits or {@link #createTextChange()} to provide a text change.
- * @param relevance the relevance of this proposal.
- * @param image the image that is displayed for this proposal or <code>null</code> if no
- * image is desired.
- */
- public CUCorrectionProposal(String name, IJavaScriptUnit cu, TextChange change, int relevance, Image image) {
- super(name, change, relevance, image);
- if (cu == null) {
- throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
- }
- fCompilationUnit= cu;
- fLinkedProposalModel= null;
- }
-
- /**
- * Constructs a correction proposal working on a compilation unit.
- * <p>Users have to override {@link #addEdits(IDocument, TextEdit)} to provide
- * the text edits or {@link #createTextChange()} to provide a text change.
- * </p>
- *
- * @param name The name that is displayed in the proposal selection dialog.
- * @param cu The compilation unit on that the change works.
- * @param relevance The relevance of this proposal.
- * @param image The image that is displayed for this proposal or <code>null</code> if no
- * image is desired.
- */
- protected CUCorrectionProposal(String name, IJavaScriptUnit cu, int relevance, Image image) {
- this(name, cu, null, relevance, image);
- }
-
- /**
- * Called when the {@link CompilationUnitChange} is initialized. Subclasses can override to
- * add text edits to the root edit of the change. Implementors must not access the proposal,
- * e.g getting the change.
- * <p>The default implementation does not add any edits</p>
- *
- * @param document content of the underlying compilation unit. To be accessed read only.
- * @param editRoot The root edit to add all edits to
- * @throws CoreException can be thrown if adding the edits is failing.
- */
- protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
- if (false) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, "Implementors can throw an exception", null)); //$NON-NLS-1$
- }
- }
-
- protected LinkedProposalModel getLinkedProposalModel() {
- if (fLinkedProposalModel == null) {
- fLinkedProposalModel= new LinkedProposalModel();
- }
- return fLinkedProposalModel;
- }
-
- protected void setLinkedProposalModel(LinkedProposalModel model) {
- fLinkedProposalModel= model;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- StringBuffer buf= new StringBuffer();
-
- try {
- TextChange change= getTextChange();
-
- IDocument previewContent= change.getPreviewDocument(new NullProgressMonitor());
- String currentConentString= change.getCurrentContent(new NullProgressMonitor());
-
- /*
- * Do not change the type of those local variables. We use Object
- * here in order to prevent loading of the Compare plug-in at load
- * time of this class.
- */
- Object leftSide= new JavaTokenComparator(previewContent.get());
- Object rightSide= new JavaTokenComparator(currentConentString);
-
- RangeDifference[] differences= RangeDifferencer.findRanges((IRangeComparator)leftSide, (IRangeComparator)rightSide);
- for (int i= 0; i < differences.length; i++) {
- RangeDifference curr= differences[i];
- int start= ((JavaTokenComparator)leftSide).getTokenStart(curr.leftStart());
- int end= ((JavaTokenComparator)leftSide).getTokenStart(curr.leftEnd());
- if (curr.kind() == RangeDifference.CHANGE && curr.leftLength() > 0) {
- buf.append("<b>"); //$NON-NLS-1$
- appendContent(previewContent, start, end, buf, false);
- buf.append("</b>"); //$NON-NLS-1$
- } else if (curr.kind() == RangeDifference.NOCHANGE) {
- appendContent(previewContent, start, end, buf, true);
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- return buf.toString();
- }
-
- private final int surroundLines= 1;
-
- private void appendContent(IDocument text, int startOffset, int endOffset, StringBuffer buf, boolean surroundLinesOnly) throws BadLocationException {
- int startLine= text.getLineOfOffset(startOffset);
- int endLine= text.getLineOfOffset(endOffset);
-
- boolean dotsAdded= false;
- if (surroundLinesOnly && startOffset == 0) { // no surround lines for the top no-change range
- startLine= Math.max(endLine - surroundLines, 0);
- buf.append("...<br>"); //$NON-NLS-1$
- dotsAdded= true;
- }
-
- for (int i= startLine; i <= endLine; i++) {
- if (surroundLinesOnly) {
- if ((i - startLine > surroundLines) && (endLine - i > surroundLines)) {
- if (!dotsAdded) {
- buf.append("...<br>"); //$NON-NLS-1$
- dotsAdded= true;
- } else if (endOffset == text.getLength()) {
- return; // no surround lines for the bottom no-change range
- }
- continue;
- }
- }
-
- IRegion lineInfo= text.getLineInformation(i);
- int start= lineInfo.getOffset();
- int end= start + lineInfo.getLength();
-
- int from= Math.max(start, startOffset);
- int to= Math.min(end, endOffset);
- String content= text.get(from, to - from);
- if (surroundLinesOnly && (from == start) && Strings.containsOnlyWhitespaces(content)) {
- continue; // ignore empty lines except when range started in the middle of a line
- }
- for (int k= 0; k < content.length(); k++) {
- char ch= content.charAt(k);
- if (ch == '<') {
- buf.append("&lt;"); //$NON-NLS-1$
- } else if (ch == '>') {
- buf.append("&gt;"); //$NON-NLS-1$
- } else {
- buf.append(ch);
- }
- }
- if (to == end && to != endOffset) { // new line when at the end of the line, and not end of range
- buf.append("<br>"); //$NON-NLS-1$
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
- */
- public void apply(IDocument document) {
- try {
- IJavaScriptUnit unit= getCompilationUnit();
- IEditorPart part= null;
- if (unit.getResource().exists()) {
- boolean canEdit= performValidateEdit(unit);
- if (!canEdit) {
- return;
- }
- part= EditorUtility.isOpenInEditor(unit);
- if (part == null) {
- part= JavaScriptUI.openInEditor(unit);
- if (part != null) {
- document= JavaScriptUI.getDocumentProvider().getDocument(part.getEditorInput());
- }
- }
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null && part != null) {
- page.bringToTop(part);
- }
- if (part != null) {
- part.setFocus();
- }
- }
- performChange(part, document);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, CorrectionMessages.CUCorrectionProposal_error_title, CorrectionMessages.CUCorrectionProposal_error_message);
- }
- }
-
- private boolean performValidateEdit(IJavaScriptUnit unit) {
- IStatus status= Resources.makeCommittable(unit.getResource(), JavaScriptPlugin.getActiveWorkbenchShell());
- if (!status.isOK()) {
- String label= CorrectionMessages.CUCorrectionProposal_error_title;
- String message= CorrectionMessages.CUCorrectionProposal_error_message;
- ErrorDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), label, message, status);
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeCorrectionProposal#performChange(org.eclipse.jface.text.IDocument, org.eclipse.ui.IEditorPart)
- */
- protected void performChange(IEditorPart part, IDocument document) throws CoreException {
- try {
- super.performChange(part, document);
- if (part == null) {
- return;
- }
-
- if (fLinkedProposalModel != null) {
- if (fLinkedProposalModel.hasLinkedPositions() && part instanceof JavaEditor) {
- // enter linked mode
- ITextViewer viewer= ((JavaEditor) part).getViewer();
- enterLinkedMode(viewer, part);
- } else if (part instanceof ITextEditor) {
- LinkedProposalPositionGroup.PositionInformation endPosition= fLinkedProposalModel.getEndPosition();
- if (endPosition != null) {
- // select a result
- int pos= endPosition.getOffset() + endPosition.getLength();
- ((ITextEditor) part).selectAndReveal(pos, 0);
- }
- }
- }
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
-
- }
-
- private void enterLinkedMode(ITextViewer viewer, IEditorPart editor) throws BadLocationException {
- IDocument document= viewer.getDocument();
-
- LinkedModeModel model= new LinkedModeModel();
- boolean added= false;
-
- Iterator iterator= fLinkedProposalModel.getPositionGroupIterator();
- while (iterator.hasNext()) {
- LinkedProposalPositionGroup curr= (LinkedProposalPositionGroup) iterator.next();
-
- LinkedPositionGroup group= new LinkedPositionGroup();
-
- LinkedProposalPositionGroup.PositionInformation[] positions= curr.getPositions();
- if (positions.length > 0) {
- LinkedProposalPositionGroup.Proposal[] linkedModeProposals= curr.getProposals();
- if (linkedModeProposals.length <= 1) {
- for (int i= 0; i < positions.length; i++) {
- LinkedProposalPositionGroup.PositionInformation pos= positions[i];
- if (pos.getOffset() != -1) {
- group.addPosition(new LinkedPosition(document, pos.getOffset(), pos.getLength(), pos.getSequenceRank()));
- }
- }
- } else {
- LinkedPositionProposalImpl[] proposalImpls= new LinkedPositionProposalImpl[linkedModeProposals.length];
- for (int i= 0; i < linkedModeProposals.length; i++) {
- proposalImpls[i]= new LinkedPositionProposalImpl(linkedModeProposals[i], model);
- }
-
- for (int i= 0; i < positions.length; i++) {
- LinkedProposalPositionGroup.PositionInformation pos= positions[i];
- if (pos.getOffset() != -1) {
- group.addPosition(new ProposalPosition(document, pos.getOffset(), pos.getLength(), pos.getSequenceRank(), proposalImpls));
- }
- }
- }
- model.addGroup(group);
- added= true;
- }
- }
-
- model.forceInstall();
-
- if (editor instanceof JavaEditor) {
- model.addLinkingListener(new EditorHighlightingSynchronizer((JavaEditor) editor));
- }
-
- if (added) { // only set up UI if there are any positions set
- LinkedModeUI ui= new EditorLinkedModeUI(model, viewer);
- LinkedProposalPositionGroup.PositionInformation endPosition= fLinkedProposalModel.getEndPosition();
- if (endPosition != null && endPosition.getOffset() != -1) {
- ui.setExitPosition(viewer, endPosition.getOffset() + endPosition.getLength(), 0, Integer.MAX_VALUE);
- } else {
- int cursorPosition= viewer.getSelectedRange().x;
- if (cursorPosition != 0) {
- ui.setExitPosition(viewer, cursorPosition, 0, Integer.MAX_VALUE);
- }
- }
- ui.setExitPolicy(new LinkedModeExitPolicy());
- ui.enter();
-
- IRegion region= ui.getSelectedRegion();
- viewer.setSelectedRange(region.getOffset(), region.getLength());
- viewer.revealRange(region.getOffset(), region.getLength());
- }
- }
-
-
- /**
- * Creates the text change for this proposal.
- * This method is only called once and only when no text change has been passed in
- * {@link #CUCorrectionProposal(String, IJavaScriptUnit, TextChange, int, Image)}.
- *
- * @return returns the created text change.
- * @throws CoreException thrown if the creation of the text change failed.
- */
- protected TextChange createTextChange() throws CoreException {
- IJavaScriptUnit cu= getCompilationUnit();
- String name= getName();
- TextChange change;
- if (!cu.getResource().exists()) {
- String source;
- try {
- source= cu.getSource();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- source= new String(); // empty
- }
- Document document= new Document(source);
- document.setInitialLineDelimiter(StubUtility.getLineDelimiterUsed(cu));
- change= new DocumentChange(name, document);
- } else {
- CompilationUnitChange cuChange = new CompilationUnitChange(name, cu);
- cuChange.setSaveMode(TextFileChange.LEAVE_DIRTY);
- change= cuChange;
- }
- TextEdit rootEdit= new MultiTextEdit();
- change.setEdit(rootEdit);
-
- // initialize text change
- IDocument document= change.getCurrentDocument(new NullProgressMonitor());
- addEdits(document, rootEdit);
- return change;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeCorrectionProposal#createChange()
- */
- protected final Change createChange() throws CoreException {
- return createTextChange(); // make sure that only text changes are allowed here
- }
-
- /**
- * Gets the text change that is invoked when the change is applied.
- *
- * @return returns the text change that is invoked when the change is applied.
- * @throws CoreException throws an exception if accessing the change failed
- */
- public final TextChange getTextChange() throws CoreException {
- return (TextChange) getChange();
- }
-
- /**
- * The compilation unit on that the change works.
- *
- * @return the compilation unit on that the change works.
- */
- public final IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * Creates a preview of the content of the compilation unit after applying the change.
- *
- * @return returns the preview of the changed compilation unit.
- * @throws CoreException thrown if the creation of the change failed.
- */
- public String getPreviewContent() throws CoreException {
- return getTextChange().getPreviewContent(new NullProgressMonitor());
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- try {
- return getPreviewContent();
- } catch (CoreException e) {
- }
- return super.toString();
- }
-
-
- private static class LinkedModeExitPolicy implements LinkedModeUI.IExitPolicy {
- public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) {
- if (event.character == '=') {
- return new ExitFlags(ILinkedModeListener.EXIT_ALL, true);
- }
- return null;
- }
- }
-
- private static class LinkedPositionProposalImpl implements ICompletionProposalExtension2, IJavaCompletionProposal {
-
- private final LinkedProposalPositionGroup.Proposal fProposal;
- private final LinkedModeModel fLinkedPositionModel;
-
-
- public LinkedPositionProposalImpl(LinkedProposalPositionGroup.Proposal proposal, LinkedModeModel model) {
- fProposal= proposal;
- fLinkedPositionModel= model;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- IDocument doc= viewer.getDocument();
- LinkedPosition position= fLinkedPositionModel.findPosition(new LinkedPosition(doc, offset, 0));
- if (position != null) {
- try {
- try {
- TextEdit edit= fProposal.computeEdits(offset, position, trigger, stateMask, fLinkedPositionModel);
- if (edit != null) {
- edit.apply(position.getDocument(), 0);
- }
- } catch (MalformedTreeException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, "Unexpected exception applying edit", e)); //$NON-NLS-1$
- } catch (BadLocationException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, "Unexpected exception applying edit", e)); //$NON-NLS-1$
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- return fProposal.getDisplayString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fProposal.getImage();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal#getRelevance()
- */
- public int getRelevance() {
- return fProposal.getRelevance();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
- */
- public void apply(IDocument document) {
- // not called
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return fProposal.getAdditionalProposalInfo();
- }
-
- public Point getSelection(IDocument document) { return null; }
- public IContextInformation getContextInformation() { return null; }
- public void selected(ITextViewer viewer, boolean smartToggle) {}
- public void unselected(ITextViewer viewer) {}
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- // ignore event
- String insert= getDisplayString();
-
- int off;
- LinkedPosition pos= fLinkedPositionModel.findPosition(new LinkedPosition(document, offset, 0));
- if (pos != null) {
- off= pos.getOffset();
- } else {
- off= Math.max(0, offset - insert.length());
- }
- int length= offset - off;
-
- if (offset <= document.getLength()) {
- try {
- String content= document.get(off, length);
- if (insert.startsWith(content))
- return true;
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- // and ignore and return false
- }
- }
- return false;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeCorrectionProposal.java
deleted file mode 100644
index 66f687ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeCorrectionProposal.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.IUndoManager;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-/**
- * Implementation of a Java completion proposal to be used for quick fix and quick assist
- * proposals that invoke a {@link Change}. The proposal offers a proposal information but no context
- * information.
- *
- *
- */
-public class ChangeCorrectionProposal implements IJavaCompletionProposal, ICommandAccess {
-
- private Change fChange;
- private String fName;
- private int fRelevance;
- private Image fImage;
- private String fCommandId;
-
- /**
- * Constructs a change correction proposal.
- *
- * @param name The name that is displayed in the proposal selection dialog.
- * @param change The change that is executed when the proposal is applied or <code>null</code>
- * if the change will be created by implementors of {@link #createChange()}.
- * @param relevance The relevance of this proposal.
- * @param image The image that is displayed for this proposal or <code>null</code> if no
- * image is desired.
- */
- public ChangeCorrectionProposal(String name, Change change, int relevance, Image image) {
- if (name == null) {
- throw new IllegalArgumentException("Name must not be null"); //$NON-NLS-1$
- }
- fName= name;
- fChange= change;
- fRelevance= relevance;
- fImage= image;
- fCommandId= null;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
- try {
- performChange(JavaScriptPlugin.getActivePage().getActiveEditor(), document);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, CorrectionMessages.ChangeCorrectionProposal_error_title, CorrectionMessages.ChangeCorrectionProposal_error_message);
- }
- }
-
- /**
- * Performs the change associated with this proposal.
- *
- * @param activeEditor The editor currently active or <code>null</code> if no
- * editor is active.
- * @param document The document of the editor currently active or <code>null</code> if
- * no editor is visible.
- * @throws CoreException Thrown when the invocation of the change failed.
- */
- protected void performChange(IEditorPart activeEditor, IDocument document) throws CoreException {
- Change change= null;
- IRewriteTarget rewriteTarget= null;
- try {
- change= getChange();
- if (change != null) {
- if (document != null) {
- LinkedModeModel.closeAllModels(document);
- }
- if (activeEditor != null) {
- rewriteTarget= (IRewriteTarget) activeEditor.getAdapter(IRewriteTarget.class);
- if (rewriteTarget != null) {
- rewriteTarget.beginCompoundChange();
- }
- }
-
- change.initializeValidationData(new NullProgressMonitor());
- RefactoringStatus valid= change.isValid(new NullProgressMonitor());
- if (valid.hasFatalError()) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- valid.getMessageMatchingSeverity(RefactoringStatus.FATAL), null);
- throw new CoreException(status);
- } else {
- IUndoManager manager= RefactoringCore.getUndoManager();
- manager.aboutToPerformChange(change);
- Change undoChange= change.perform(new NullProgressMonitor());
- manager.changePerformed(change, true);
- if (undoChange != null) {
- undoChange.initializeValidationData(new NullProgressMonitor());
- manager.addUndo(getName(), undoChange);
- }
- }
- }
- } finally {
- if (rewriteTarget != null) {
- rewriteTarget.endCompoundChange();
- }
-
- if (change != null) {
- change.dispose();
- }
- }
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- StringBuffer buf= new StringBuffer();
- buf.append("<p>"); //$NON-NLS-1$
- try {
- Change change= getChange();
- if (change != null) {
- String name= change.getName();
- if (name.length() == 0) {
- return null;
- }
- buf.append(name);
- } else {
- return null;
- }
- } catch (CoreException e) {
- buf.append("Unexpected error when accessing this proposal:<p><pre>"); //$NON-NLS-1$
- buf.append(e.getLocalizedMessage());
- buf.append("</pre>"); //$NON-NLS-1$
- }
- buf.append("</p>"); //$NON-NLS-1$
- return buf.toString();
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return null;
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- String shortCutString= CorrectionCommandHandler.getShortCutString(getCommandId());
- if (shortCutString != null) {
- return Messages.format(CorrectionMessages.ChangeCorrectionProposal_name_with_shortcut, new String[] { getName(), shortCutString });
- }
- return getName();
- }
-
- /**
- * Returns the name of the proposal.
- *
- * @return return the name of the proposal
- */
- public String getName() {
- return fName;
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return null;
- }
-
- /**
- * Sets the proposal's image or <code>null</code> if no image is desired.
- *
- * @param image the desired image.
- */
- public void setImage(Image image) {
- fImage= image;
- }
-
- /**
- * Returns the change that will be executed when the proposal is applied.
- *
- * @return returns the change for this proposal.
- * @throws CoreException thrown when the change could not be created
- */
- public final Change getChange() throws CoreException {
- if (fChange == null) {
- fChange= createChange();
- }
- return fChange;
- }
-
- /**
- * Creates the text change for this proposal.
- * This method is only called once and only when no text change has been passed in
- * {@link #ChangeCorrectionProposal(String, Change, int, Image)}.
- *
- * @return returns the created change.
- * @throws CoreException thrown if the creation of the change failed.
- */
- protected Change createChange() throws CoreException {
- return new NullChange();
- }
-
- /**
- * Sets the display name.
- *
- * @param name the name to set
- */
- public void setDisplayName(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Name must not be null"); //$NON-NLS-1$
- }
- fName= name;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal#getRelevance()
- */
- public int getRelevance() {
- return fRelevance;
- }
-
- /**
- * Sets the relevance.
- * @param relevance the relevance to set
- */
- public void setRelevance(int relevance) {
- fRelevance= relevance;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IShortcutProposal#getProposalId()
- */
- public String getCommandId() {
- return fCommandId;
- }
-
- /**
- * Set the proposal id to allow assigning a shortcut to the correction proposal.
- *
- * @param commandId The proposal id for this proposal or <code>null</code> if no command
- * should be assigned to this proposal.
- */
- public void setCommandId(String commandId) {
- fCommandId= commandId;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeMethodSignatureProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeMethodSignatureProposal.java
deleted file mode 100644
index 0f17ce97..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ChangeMethodSignatureProposal.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-
-public class ChangeMethodSignatureProposal extends LinkedCorrectionProposal {
-
- public static interface ChangeDescription {
- }
-
- public static class SwapDescription implements ChangeDescription {
- final int index;
- public SwapDescription(int index) {
- this.index= index;
- }
- }
-
- public static class RemoveDescription implements ChangeDescription {
- }
-
- static class ModifyDescription implements ChangeDescription {
- public final String name;
- public final ITypeBinding type;
- Type resultingParamType;
- SimpleName[] resultingParamName;
- SimpleName resultingTagArg;
-
- private ModifyDescription(ITypeBinding type, String name) {
- this.type= type;
- this.name= name;
- }
- }
-
- public static class EditDescription extends ModifyDescription {
- String orginalName;
-
- public EditDescription(ITypeBinding type, String name) {
- super(type, name);
- }
- }
-
- public static class InsertDescription extends ModifyDescription {
- public InsertDescription(ITypeBinding type, String name) {
- super(type, name);
- }
- }
-
- private ASTNode fInvocationNode;
- private IFunctionBinding fSenderBinding;
- private ChangeDescription[] fParameterChanges;
- private ChangeDescription[] fExceptionChanges;
-
- public ChangeMethodSignatureProposal(String label, IJavaScriptUnit targetCU, ASTNode invocationNode, IFunctionBinding binding, ChangeDescription[] paramChanges, ChangeDescription[] exceptionChanges, int relevance, Image image) {
- super(label, targetCU, null, relevance, image);
-
- Assert.isTrue(binding != null && Bindings.isDeclarationBinding(binding));
-
- fInvocationNode= invocationNode;
- fSenderBinding= binding;
- fParameterChanges= paramChanges;
- fExceptionChanges= exceptionChanges;
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- JavaScriptUnit astRoot= (JavaScriptUnit) fInvocationNode.getRoot();
- ASTNode methodDecl= astRoot.findDeclaringNode(fSenderBinding);
- ASTNode newMethodDecl= null;
- boolean isInDifferentCU;
- if (methodDecl != null) {
- isInDifferentCU= false;
- newMethodDecl= methodDecl;
- } else {
- isInDifferentCU= true;
- astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
- newMethodDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
- }
- createImportRewrite(astRoot);
-
- if (newMethodDecl instanceof FunctionDeclaration) {
- FunctionDeclaration decl= (FunctionDeclaration) newMethodDecl;
-
- ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
- if (fParameterChanges != null) {
- modifyParameters(rewrite, decl, isInDifferentCU);
- }
- if (fExceptionChanges != null) {
- modifyExceptions(rewrite, decl);
- }
- return rewrite;
- }
- return null;
- }
-
- private void modifyParameters(ASTRewrite rewrite, FunctionDeclaration methodDecl, boolean isInDifferentCU) throws CoreException {
- AST ast= methodDecl.getAST();
-
- ArrayList usedNames= new ArrayList();
- boolean hasCreatedVariables= false;
-
- IVariableBinding[] declaredFields= fSenderBinding.getDeclaringClass().getDeclaredFields();
- for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
- usedNames.add(declaredFields[i].getName());
- }
-
- ImportRewrite imports= getImportRewrite();
- ListRewrite listRewrite= rewrite.getListRewrite(methodDecl, FunctionDeclaration.PARAMETERS_PROPERTY);
-
- List parameters= methodDecl.parameters(); // old parameters
- int k= 0; // index over the oldParameters
-
- for (int i= 0; i < fParameterChanges.length; i++) {
- ChangeDescription curr= fParameterChanges[i];
-
- if (curr == null) {
- SingleVariableDeclaration oldParam= (SingleVariableDeclaration) parameters.get(k);
- usedNames.add(oldParam.getName().getIdentifier());
- k++;
- } else if (curr instanceof InsertDescription) {
- InsertDescription desc= (InsertDescription) curr;
- SingleVariableDeclaration newNode= ast.newSingleVariableDeclaration();
- newNode.setType(imports.addImport(desc.type, ast));
- newNode.setName(ast.newSimpleName("x")); //$NON-NLS-1$
-
- // remember to set name later
- desc.resultingParamName= new SimpleName[] {newNode.getName()};
- desc.resultingParamType= newNode.getType();
- hasCreatedVariables= true;
-
- listRewrite.insertAt(newNode, i, null);
-
- JSdoc javadoc= methodDecl.getJavadoc();
- if (javadoc != null) {
- TagElement newTagElement= ast.newTagElement();
- newTagElement.setTagName(TagElement.TAG_PARAM);
- SimpleName arg= ast.newSimpleName("x"); //$NON-NLS-1$
- newTagElement.fragments().add(arg);
- insertTabStop(rewrite, newTagElement.fragments(), "param_tagcomment" + i); //$NON-NLS-1$
- insertParamTag(rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY), parameters, k, newTagElement);
- desc.resultingTagArg= arg; // set the name later
- } else {
- desc.resultingTagArg= null;
- }
- } else if (curr instanceof RemoveDescription) {
- SingleVariableDeclaration decl= (SingleVariableDeclaration) parameters.get(k);
-
- listRewrite.remove(decl, null);
- k++;
-
- TagElement tagNode= findParamTag(methodDecl, decl);
- if (tagNode != null) {
- rewrite.remove(tagNode, null);
- }
- } else if (curr instanceof EditDescription) {
- EditDescription desc= (EditDescription) curr;
-
- ITypeBinding newTypeBinding= desc.type;
- SingleVariableDeclaration decl= (SingleVariableDeclaration) parameters.get(k);
-
- if (k == parameters.size() - 1 && i == fParameterChanges.length - 1 && decl.isVarargs() && newTypeBinding.isArray()) {
- newTypeBinding= newTypeBinding.getElementType(); // stick with varargs if it was before
- } else {
- rewrite.set(decl, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.FALSE, null);
- }
-
- Type newType= imports.addImport(newTypeBinding, ast);
- rewrite.replace(decl.getType(), newType, null);
- rewrite.set(decl, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
-
- IBinding binding= decl.getName().resolveBinding();
- if (binding != null) {
- SimpleName[] names= LinkedNodeFinder.findByBinding(decl.getRoot(), binding);
- SimpleName[] newNames= new SimpleName[names.length];
- for (int j= 0; j < names.length; j++) {
- SimpleName newName= ast.newSimpleName("x"); //$NON-NLS-1$ // name will be set later
- newNames[j]= newName;
- rewrite.replace(names[j], newName, null);
-
- }
- desc.resultingParamName= newNames;
- } else {
- SimpleName newName= ast.newSimpleName("x"); //$NON-NLS-1$ // name will be set later
- rewrite.replace(decl.getName(), newName, null);
- // remember to set name later
- desc.resultingParamName= new SimpleName[] {newName};
- }
-
- desc.resultingParamType= newType;
- desc.orginalName= decl.getName().getIdentifier();
- hasCreatedVariables= true;
-
- k++;
-
- TagElement tagNode= findParamTag(methodDecl, decl);
- if (tagNode != null) {
- List fragments= tagNode.fragments();
- if (!fragments.isEmpty()) {
- SimpleName arg= ast.newSimpleName("x"); //$NON-NLS-1$
- rewrite.replace((ASTNode) fragments.get(0), arg, null);
- desc.resultingTagArg= arg;
- }
- }
-
- } else if (curr instanceof SwapDescription) {
- SingleVariableDeclaration decl1= (SingleVariableDeclaration) parameters.get(k);
- SingleVariableDeclaration decl2= (SingleVariableDeclaration) parameters.get(((SwapDescription) curr).index);
-
- rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
- rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
-
- usedNames.add(decl1.getName().getIdentifier());
- k++;
-
- TagElement tagNode1= findParamTag(methodDecl, decl1);
- TagElement tagNode2= findParamTag(methodDecl, decl2);
- if (tagNode1 != null && tagNode2 != null) {
- rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
- rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
- }
- }
- }
- if (!hasCreatedVariables) {
- return;
- }
-
- if (methodDecl.getBody() != null) {
- // avoid take a name of a local variable inside
- JavaScriptUnit root= (JavaScriptUnit) methodDecl.getRoot();
- IBinding[] bindings= (new ScopeAnalyzer(root)).getDeclarationsAfter(methodDecl.getBody().getStartPosition(), ScopeAnalyzer.VARIABLES);
- for (int i= 0; i < bindings.length; i++) {
- usedNames.add(bindings[i].getName());
- }
- }
-
- fixupNames(rewrite, usedNames, methodDecl, isInDifferentCU);
- }
-
- private void fixupNames(ASTRewrite rewrite, ArrayList usedNames, FunctionDeclaration methodDecl, boolean isInDifferentCU) {
- AST ast= rewrite.getAST();
- // set names for new parameters
- for (int i= 0; i < fParameterChanges.length; i++) {
- ChangeDescription curr= fParameterChanges[i];
- if (curr instanceof ModifyDescription) {
- ModifyDescription desc= (ModifyDescription) curr;
-
- String typeKey= getParamTypeGroupId(i);
- String nameKey= getParamNameGroupId(i);
-
- // collect name suggestions
- String favourite= null;
- String[] excludedNames= (String[]) usedNames.toArray(new String[usedNames.size()]);
-
- String suggestedName= desc.name;
- if (suggestedName != null) {
- favourite= StubUtility.suggestArgumentName(getCompilationUnit().getJavaScriptProject(), suggestedName, excludedNames);
- addLinkedPositionProposal(nameKey, favourite, null);
- }
-
- if (desc instanceof EditDescription) {
- addLinkedPositionProposal(nameKey, ((EditDescription)desc).orginalName, null);
- }
-
- Type type= desc.resultingParamType;
- String[] suggestedNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaScriptProject(), type, excludedNames);
- for (int k= 0; k < suggestedNames.length; k++) {
- addLinkedPositionProposal(nameKey, suggestedNames[k], null);
- }
- if (favourite == null) {
- favourite= suggestedNames[0];
- }
- usedNames.add(favourite);
-
- SimpleName[] names= desc.resultingParamName;
- for (int j= 0; j < names.length; j++) {
- names[j].setIdentifier(favourite);
- addLinkedPosition(rewrite.track(names[j]), false, nameKey);
- }
-
- addLinkedPosition(rewrite.track(desc.resultingParamType), true, typeKey);
-
- // collect type suggestions
- ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, desc.type);
- for (int k= 0; k < bindings.length; k++) {
- addLinkedPositionProposal(typeKey, bindings[k]);
- }
-
- SimpleName tagArg= desc.resultingTagArg;
- if (tagArg != null) {
- tagArg.setIdentifier(favourite);
- addLinkedPosition(rewrite.track(tagArg), false, nameKey);
- }
- }
- }
- }
-
- private TagElement findParamTag(FunctionDeclaration decl, SingleVariableDeclaration param) {
- JSdoc javadoc= decl.getJavadoc();
- if (javadoc != null) {
- return JavadocTagsSubProcessor.findParamTag(javadoc, param.getName().getIdentifier());
- }
- return null;
- }
-
- private TagElement insertParamTag(ListRewrite tagRewriter, List parameters, int currentIndex, TagElement newTagElement) {
- HashSet previousNames= new HashSet();
- for (int n = 0; n < currentIndex; n++) {
- SingleVariableDeclaration var= (SingleVariableDeclaration) parameters.get(n);
- previousNames.add(var.getName().getIdentifier());
- }
-
- JavadocTagsSubProcessor.insertTag(tagRewriter, newTagElement, previousNames);
- return newTagElement;
- }
-
- private void modifyExceptions(ASTRewrite rewrite, FunctionDeclaration methodDecl) throws CoreException {
- AST ast= methodDecl.getAST();
-
- ImportRewrite imports= getImportRewrite();
- ListRewrite listRewrite= rewrite.getListRewrite(methodDecl, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY);
-
- List exceptions= methodDecl.thrownExceptions(); // old exceptions
- int k= 0; // index over the old exceptions
-
- for (int i= 0; i < fExceptionChanges.length; i++) {
- ChangeDescription curr= fExceptionChanges[i];
-
- if (curr == null) {
- k++;
- } else if (curr instanceof InsertDescription) {
- InsertDescription desc= (InsertDescription) curr;
- String type= imports.addImport(desc.type);
- ASTNode newNode= ASTNodeFactory.newName(ast, type);
-
- listRewrite.insertAt(newNode, i, null);
-
- String key= getExceptionTypeGroupId(i);
- addLinkedPosition(rewrite.track(newNode), false, key);
-
- JSdoc javadoc= methodDecl.getJavadoc();
- if (javadoc != null) {
- TagElement newTagElement= ast.newTagElement();
- newTagElement.setTagName(TagElement.TAG_THROWS);
- ASTNode newRef= ASTNodeFactory.newName(ast, type);
- newTagElement.fragments().add(newRef);
- insertTabStop(rewrite, newTagElement.fragments(), "throws_tagcomment" + i); //$NON-NLS-1$
- insertThrowsTag(rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY), exceptions, k, newTagElement);
-
- addLinkedPosition(rewrite.track(newRef), false, key);
- }
-
- } else if (curr instanceof RemoveDescription) {
- Name node= (Name) exceptions.get(k);
-
- listRewrite.remove(node, null);
- k++;
-
- TagElement tagNode= findThrowsTag(methodDecl, node);
- if (tagNode != null) {
- rewrite.remove(tagNode, null);
- }
- } else if (curr instanceof EditDescription) {
- EditDescription desc= (EditDescription) curr;
-
- Name oldNode= (Name) exceptions.get(k);
-
- String type= imports.addImport(desc.type);
- ASTNode newNode= ASTNodeFactory.newName(ast, type);
-
- listRewrite.replace(oldNode, newNode, null);
- String key= getExceptionTypeGroupId(i);
- addLinkedPosition(rewrite.track(newNode), false, key);
-
- k++;
-
- TagElement tagNode= findThrowsTag(methodDecl, oldNode);
- if (tagNode != null) {
- ASTNode newRef= ASTNodeFactory.newName(ast, type);
- rewrite.replace((ASTNode) tagNode.fragments().get(0), newRef, null);
- addLinkedPosition(rewrite.track(newRef), false, key);
- }
-
- } else if (curr instanceof SwapDescription) {
- Name decl1= (Name) exceptions.get(k);
- Name decl2= (Name) exceptions.get(((SwapDescription) curr).index);
-
- rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
- rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
-
- k++;
-
- TagElement tagNode1= findThrowsTag(methodDecl, decl1);
- TagElement tagNode2= findThrowsTag(methodDecl, decl2);
- if (tagNode1 != null && tagNode2 != null) {
- rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
- rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
- }
- }
- }
- }
-
- private void insertTabStop(ASTRewrite rewriter, List fragments, String linkedName) {
- TextElement textElement= rewriter.getAST().newTextElement();
- textElement.setText(""); //$NON-NLS-1$
- fragments.add(textElement);
- addLinkedPosition(rewriter.track(textElement), false, linkedName);
- }
-
- private TagElement findThrowsTag(FunctionDeclaration decl, Name exception) {
- JSdoc javadoc= decl.getJavadoc();
- if (javadoc != null) {
- String name= ASTNodes.getSimpleNameIdentifier(exception);
- return JavadocTagsSubProcessor.findThrowsTag(javadoc, name);
- }
- return null;
- }
-
- private TagElement insertThrowsTag(ListRewrite tagRewriter, List exceptions, int currentIndex, TagElement newTagElement) {
- HashSet previousNames= new HashSet();
- for (int n = 0; n < currentIndex; n++) {
- Name curr= (Name) exceptions.get(n);
- previousNames.add(ASTNodes.getSimpleNameIdentifier(curr));
- }
-
- JavadocTagsSubProcessor.insertTag(tagRewriter, newTagElement, previousNames);
- return newTagElement;
- }
-
-
- public String getParamNameGroupId(int idx) {
- return "param_name_" + idx; //$NON-NLS-1$
- }
-
- public String getParamTypeGroupId(int idx) {
- return "param_type_" + idx; //$NON-NLS-1$
- }
-
- public String getExceptionTypeGroupId(int idx) {
- return "exc_type_" + idx; //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java
deleted file mode 100644
index 3671578a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-public class ConstructorFromSuperclassProposal extends LinkedCorrectionProposal {
-
- private TypeDeclaration fTypeNode;
- private IFunctionBinding fSuperConstructor;
-
- public ConstructorFromSuperclassProposal(IJavaScriptUnit cu, TypeDeclaration typeNode, IFunctionBinding superConstructor, int relevance) {
- super("", cu, null, relevance, null); //$NON-NLS-1$
- fTypeNode= typeNode;
- fSuperConstructor= superConstructor;
- }
-
- /**
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
- */
- public Image getImage() {
- return JavaScriptPlugin.getImageDescriptorRegistry().get(
- new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaScriptElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE)
- );
- }
-
- /**
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- StringBuffer buf= new StringBuffer();
- buf.append(fTypeNode.getName().getIdentifier());
- buf.append('(');
- if (fSuperConstructor != null) {
- ITypeBinding[] paramTypes= fSuperConstructor.getParameterTypes();
- for (int i= 0; i < paramTypes.length; i++) {
- if (i > 0) {
- buf.append(',');
- }
- buf.append(paramTypes[i].getName());
- }
- }
- buf.append(')');
- return Messages.format(CorrectionMessages.ConstructorFromSuperclassProposal_description, buf.toString());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() throws CoreException {
- AST ast= fTypeNode.getAST();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- createImportRewrite((JavaScriptUnit) fTypeNode.getRoot());
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaScriptProject());
- if (!settings.createComments) {
- settings= null;
- }
-
- FunctionDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, settings);
- rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null);
-
- addLinkedRanges(rewrite, newMethodDecl);
-
- return rewrite;
- }
-
- private void addLinkedRanges(ASTRewrite rewrite, FunctionDeclaration newStub) {
- List parameters= newStub.parameters();
- for (int i= 0; i < parameters.size(); i++) {
- SingleVariableDeclaration curr= (SingleVariableDeclaration) parameters.get(i);
- String name= curr.getName().getIdentifier();
- addLinkedPosition(rewrite.track(curr.getType()), false, "arg_type_" + name); //$NON-NLS-1$
- addLinkedPosition(rewrite.track(curr.getName()), false, "arg_name_" + name); //$NON-NLS-1$
- }
- }
-
- private FunctionDeclaration createNewMethodDeclaration(AST ast, IFunctionBinding binding, ASTRewrite rewrite, CodeGenerationSettings commentSettings) throws CoreException {
- String name= fTypeNode.getName().getIdentifier();
- FunctionDeclaration decl= ast.newFunctionDeclaration();
- decl.setConstructor(true);
- decl.setName(ast.newSimpleName(name));
- Block body= ast.newBlock();
- decl.setBody(body);
-
- SuperConstructorInvocation invocation= null;
-
- List parameters= decl.parameters();
- String[] paramNames= getArgumentNames(binding);
-
- ITypeBinding enclosingInstance= getEnclosingInstance();
- if (enclosingInstance != null) {
- invocation= addEnclosingInstanceAccess(rewrite, parameters, paramNames, enclosingInstance);
- }
-
- if (binding == null) {
- decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
- } else {
- decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));
-
- ITypeBinding[] params= binding.getParameterTypes();
- for (int i= 0; i < params.length; i++) {
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- var.setType(getImportRewrite().addImport(params[i], ast));
- var.setName(ast.newSimpleName(paramNames[i]));
- parameters.add(var);
- }
-
- if (invocation == null) {
- invocation= ast.newSuperConstructorInvocation();
- }
-
- List arguments= invocation.arguments();
- for (int i= 0; i < paramNames.length; i++) {
- Name argument= ast.newSimpleName(paramNames[i]);
- arguments.add(argument);
- addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
- }
- }
-
- String bodyStatement= (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaScriptProject().getOptions(true)); //$NON-NLS-1$
- String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
- if (placeHolder != null) {
- ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
- body.statements().add(todoNode);
- }
- if (commentSettings != null) {
- String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
- if (string != null) {
- JSdoc javadoc= (JSdoc) rewrite.createStringPlaceholder(string, ASTNode.JSDOC);
- decl.setJavadoc(javadoc);
- }
- }
- return decl;
- }
-
- private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, List parameters, String[] paramNames, ITypeBinding enclosingInstance) throws CoreException {
- AST ast= rewrite.getAST();
- SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
-
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- var.setType(getImportRewrite().addImport(enclosingInstance, ast));
- String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaScriptProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
- String firstName= enclosingArgNames[0];
- var.setName(ast.newSimpleName(firstName));
- parameters.add(var);
-
- Name enclosing= ast.newSimpleName(firstName);
- invocation.setExpression(enclosing);
-
- String key= "arg_name_" + firstName; //$NON-NLS-1$
- addLinkedPosition(rewrite.track(enclosing), false, key);
- for (int i= 0; i < enclosingArgNames.length; i++) {
- addLinkedPositionProposal(key, enclosingArgNames[i], null); // alternative names
- }
- return invocation;
- }
-
- private ITypeBinding getEnclosingInstance() {
- ITypeBinding currBinding= fTypeNode.resolveBinding();
- if (currBinding == null || Modifier.isStatic(currBinding.getModifiers())) {
- return null;
- }
- ITypeBinding superBinding= currBinding.getSuperclass();
- if (superBinding == null || superBinding.getDeclaringClass() == null || Modifier.isStatic(superBinding.getModifiers())) {
- return null;
- }
- ITypeBinding enclosing= superBinding.getDeclaringClass();
-
- while (currBinding != null) {
- if (Bindings.isSuperType(enclosing, currBinding)) {
- return null; // enclosing in scope
- }
- if (Modifier.isStatic(currBinding.getModifiers())) {
- return null; // no more enclosing instances
- }
- currBinding= currBinding.getDeclaringClass();
- }
- return enclosing;
- }
-
-
- private String[] getArgumentNames(IFunctionBinding binding) {
- if (binding == null) {
- return new String[0];
- }
- return StubUtility.suggestArgumentNames(getCompilationUnit().getJavaScriptProject(), binding);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ContributedProcessorDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ContributedProcessorDescriptor.java
deleted file mode 100644
index 47a31b6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ContributedProcessorDescriptor.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.expressions.EvaluationContext;
-import org.eclipse.core.expressions.EvaluationResult;
-import org.eclipse.core.expressions.Expression;
-import org.eclipse.core.expressions.ExpressionConverter;
-import org.eclipse.core.expressions.ExpressionTagNames;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-public final class ContributedProcessorDescriptor {
-
- private final IConfigurationElement fConfigurationElement;
- private Object fProcessorInstance;
- private Boolean fStatus;
- private boolean fLastResult;
- private String fRequiredSourceLevel;
- private final Set fHandledMarkerTypes;
-
- private static final String ID= "id"; //$NON-NLS-1$
- private static final String CLASS= "class"; //$NON-NLS-1$
-
- private static final String REQUIRED_SOURCE_LEVEL= "requiredSourceLevel"; //$NON-NLS-1$
-
- private static final String HANDLED_MARKER_TYPES= "handledMarkerTypes"; //$NON-NLS-1$
- private static final String MARKER_TYPE= "markerType"; //$NON-NLS-1$
-
- public ContributedProcessorDescriptor(IConfigurationElement element, boolean testMarkerTypes) {
- fConfigurationElement= element;
- fProcessorInstance= null;
- fStatus= null; // undefined
- if (fConfigurationElement.getChildren(ExpressionTagNames.ENABLEMENT).length == 0) {
- fStatus= Boolean.TRUE;
- }
- fRequiredSourceLevel= element.getAttribute(REQUIRED_SOURCE_LEVEL);
- fHandledMarkerTypes= testMarkerTypes ? getHandledMarkerTypes(element) : null;
- }
-
- private Set getHandledMarkerTypes(IConfigurationElement element) {
- HashSet map= new HashSet(7);
- IConfigurationElement[] children= element.getChildren(HANDLED_MARKER_TYPES);
- for (int i= 0; i < children.length; i++) {
- IConfigurationElement[] types= children[i].getChildren(MARKER_TYPE);
- for (int k= 0; k < types.length; k++) {
- String attribute= types[k].getAttribute(ID);
- if (attribute != null) {
- map.add(attribute);
- }
- }
- }
- if (map.isEmpty()) {
- map.add(IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER);
- map.add(IJavaScriptModelMarker.BUILDPATH_PROBLEM_MARKER);
- map.add(IJavaScriptModelMarker.TASK_MARKER);
- }
- return map;
- }
-
- public IStatus checkSyntax() {
- IConfigurationElement[] children= fConfigurationElement.getChildren(ExpressionTagNames.ENABLEMENT);
- if (children.length > 1) {
- String id= fConfigurationElement.getAttribute(ID);
- return new StatusInfo(IStatus.ERROR, "Only one < enablement > element allowed. Disabling " + id); //$NON-NLS-1$
- }
- return new StatusInfo(IStatus.OK, "Syntactically correct quick assist/fix processor"); //$NON-NLS-1$
- }
-
- private boolean matches(IJavaScriptUnit cunit) {
- if (fRequiredSourceLevel != null) {
- String current= cunit.getJavaScriptProject().getOption(JavaScriptCore.COMPILER_SOURCE, true);
- if (JavaModelUtil.isVersionLessThan(current, fRequiredSourceLevel)) {
- return false;
- }
- }
-
- if (fStatus != null) {
- return fStatus.booleanValue();
- }
-
- IConfigurationElement[] children= fConfigurationElement.getChildren(ExpressionTagNames.ENABLEMENT);
- if (children.length == 1) {
- try {
- ExpressionConverter parser= ExpressionConverter.getDefault();
- Expression expression= parser.perform(children[0]);
- EvaluationContext evalContext= new EvaluationContext(null, cunit);
- evalContext.addVariable("compilationUnit", cunit); //$NON-NLS-1$
- IJavaScriptProject javaProject= cunit.getJavaScriptProject();
- String[] natures= javaProject.getProject().getDescription().getNatureIds();
- evalContext.addVariable("projectNatures", Arrays.asList(natures)); //$NON-NLS-1$
- evalContext.addVariable("sourceLevel", javaProject.getOption(JavaScriptCore.COMPILER_SOURCE, true)); //$NON-NLS-1$
- fLastResult= !(expression.evaluate(evalContext) != EvaluationResult.TRUE);
- return fLastResult;
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- fStatus= Boolean.FALSE;
- return false;
- }
-
- public Object getProcessor(IJavaScriptUnit cunit) throws CoreException {
- if (matches(cunit)) {
- if (fProcessorInstance == null) {
- fProcessorInstance= fConfigurationElement.createExecutableExtension(CLASS);
- }
- return fProcessorInstance;
- }
- return null;
- }
-
- public boolean canHandleMarkerType(String markerType) {
- return fHandledMarkerTypes == null || fHandledMarkerTypes.contains(markerType);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectMainTypeNameProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectMainTypeNameProposal.java
deleted file mode 100644
index 3d705b6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectMainTypeNameProposal.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-/**
- * Renames the primary type to be compatible with the name of the compilation unit.
- * All constructors and local references to the type are renamed as well.
- */
-public class CorrectMainTypeNameProposal extends ASTRewriteCorrectionProposal {
-
- private final String fOldName;
- private final String fNewName;
- private final IInvocationContext fContext;
-
- /**
- * Constructor for CorrectTypeNameProposal.
- */
- public CorrectMainTypeNameProposal(IJavaScriptUnit cu, IInvocationContext context, String oldTypeName, String newTypeName, int relevance) {
- super("", cu, null, relevance, null); //$NON-NLS-1$
- fContext= context;
-
- setDisplayName(Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renametype_description, newTypeName));
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
-
- fOldName= oldTypeName;
- fNewName= newTypeName;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() throws CoreException {
- JavaScriptUnit astRoot= fContext.getASTRoot();
-
- AST ast= astRoot.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName);
- if (decl != null) {
- ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName());
- for (int i= 0; i < sameNodes.length; i++) {
- rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null);
- }
- }
- return rewrite;
- }
-
- private AbstractTypeDeclaration findTypeDeclaration(List types, String name) {
- for (Iterator iter= types.iterator(); iter.hasNext();) {
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) iter.next();
- if (name.equals(decl.getName().getIdentifier())) {
- return decl;
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandHandler.java
deleted file mode 100644
index d34de8a2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandHandler.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.bindings.TriggerSequence;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-/**
- * Handler to be used to run a quick fix or assist by keyboard shortcut
- */
-public class CorrectionCommandHandler extends AbstractHandler {
-
- private final JavaEditor fEditor;
- private final String fId;
- private final boolean fIsAssist;
-
- public CorrectionCommandHandler(JavaEditor editor, String id, boolean isAssist) {
- fEditor= editor;
- fId= id;
- fIsAssist= isAssist;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection= fEditor.getSelectionProvider().getSelection();
- IJavaScriptUnit cu= JavaScriptUI.getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
- IAnnotationModel model= JavaScriptUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
- if (selection instanceof ITextSelection && cu != null && model != null) {
- if (! ActionUtil.isEditable(fEditor)) {
- return null;
- }
- ICompletionProposal proposal= findCorrection(fId, fIsAssist, (ITextSelection) selection, cu, model);
- if (proposal != null) {
- invokeProposal(proposal, ((ITextSelection) selection).getOffset());
- }
- }
- return null;
- }
-
- private ICompletionProposal findCorrection(String id, boolean isAssist, ITextSelection selection, IJavaScriptUnit cu, IAnnotationModel model) {
- AssistContext context= new AssistContext(cu, selection.getOffset(), selection.getLength());
- Collection proposals= new ArrayList(10);
- if (isAssist) {
- if (id.equals(LinkedNamesAssistProposal.ASSIST_ID)) {
- return getLocalRenameProposal(context); // shortcut for local rename
- }
- JavaCorrectionProcessor.collectAssists(context, new ProblemLocation[0], proposals);
- } else {
- try {
- boolean goToClosest= selection.getLength() == 0;
- Annotation[] annotations= getAnnotations(selection.getOffset(), goToClosest);
- JavaCorrectionProcessor.collectProposals(context, model, annotations, true, false, proposals);
- } catch (BadLocationException e) {
- return null;
- }
- }
- for (Iterator iter= proposals.iterator(); iter.hasNext();) {
- Object curr= iter.next();
- if (curr instanceof ICommandAccess) {
- if (id.equals(((ICommandAccess) curr).getCommandId())) {
- return (ICompletionProposal) curr;
- }
- }
- }
- return null;
- }
-
- private Annotation[] getAnnotations(int offset, boolean goToClosest) throws BadLocationException {
- ArrayList resultingAnnotations= new ArrayList();
- JavaCorrectionAssistant.collectQuickFixableAnnotations(fEditor, offset, goToClosest, resultingAnnotations);
- return (Annotation[]) resultingAnnotations.toArray(new Annotation[resultingAnnotations.size()]);
- }
-
- private ICompletionProposal getLocalRenameProposal(IInvocationContext context) {
- ASTNode node= context.getCoveringNode();
- if (node instanceof SimpleName) {
- return new LinkedNamesAssistProposal(context.getCompilationUnit(), (SimpleName) node);
- }
- return null;
- }
-
- private IDocument getDocument() {
- return JavaScriptUI.getDocumentProvider().getDocument(fEditor.getEditorInput());
- }
-
-
- private void invokeProposal(ICompletionProposal proposal, int offset) {
- if (proposal instanceof ICompletionProposalExtension2) {
- ITextViewer viewer= fEditor.getViewer();
- if (viewer != null) {
- ((ICompletionProposalExtension2) proposal).apply(viewer, (char) 0, 0, offset);
- return;
- }
- } else if (proposal instanceof ICompletionProposalExtension) {
- IDocument document= getDocument();
- if (document != null) {
- ((ICompletionProposalExtension) proposal).apply(document, (char) 0, offset);
- return;
- }
- }
- IDocument document= getDocument();
- if (document != null) {
- proposal.apply(document);
- }
- }
-
- public static String getShortCutString(String proposalId) {
- if (proposalId != null) {
- IBindingService bindingService= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService != null) {
- TriggerSequence[] activeBindingsFor= bindingService.getActiveBindingsFor(proposalId);
- if (activeBindingsFor.length > 0) {
- return activeBindingsFor[0].format();
- }
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandInstaller.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandInstaller.java
deleted file mode 100644
index 29d76a5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionCommandInstaller.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.LegacyHandlerSubmissionExpression;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.IHandlerActivation;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-
-public class CorrectionCommandInstaller {
-
- /**
- * All correction commands must start with the following prefix.
- */
- public static final String COMMAND_PREFIX= "org.eclipse.wst.jsdt.ui.correction."; //$NON-NLS-1$
-
- /**
- * Commands for quick assist must have the following suffix.
- */
- public static final String ASSIST_SUFFIX= ".assist"; //$NON-NLS-1$
-
- private List fCorrectionHandlerActivations;
-
- public CorrectionCommandInstaller() {
- fCorrectionHandlerActivations= null;
- }
-
- public void registerCommands(CompilationUnitEditor editor) {
- IWorkbench workbench= PlatformUI.getWorkbench();
- ICommandService commandService= (ICommandService) workbench.getAdapter(ICommandService.class);
- IHandlerService handlerService= (IHandlerService) workbench.getAdapter(IHandlerService.class);
- if (commandService == null || handlerService == null) {
- return;
- }
-
- if (fCorrectionHandlerActivations != null) {
- JavaScriptPlugin.logErrorMessage("correction handler activations not released"); //$NON-NLS-1$
- }
- fCorrectionHandlerActivations= new ArrayList();
-
- Collection definedCommandIds= commandService.getDefinedCommandIds();
- for (Iterator iter= definedCommandIds.iterator(); iter.hasNext();) {
- String id= (String) iter.next();
- if (id.startsWith(COMMAND_PREFIX)) {
- boolean isAssist= id.endsWith(ASSIST_SUFFIX);
- CorrectionCommandHandler handler= new CorrectionCommandHandler(editor, id, isAssist);
- IHandlerActivation activation= handlerService.activateHandler(id, handler, new LegacyHandlerSubmissionExpression(null, null, editor.getSite()));
- fCorrectionHandlerActivations.add(activation);
- }
- }
- }
-
- public void deregisterCommands() {
- IHandlerService handlerService= (IHandlerService) PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
- if (handlerService != null && fCorrectionHandlerActivations != null) {
- handlerService.deactivateHandlers(fCorrectionHandlerActivations);
- fCorrectionHandlerActivations= null;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java
deleted file mode 100644
index da19a970..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java
+++ /dev/null
@@ -1,590 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.PerformChangeOperation;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolutionGenerator;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.MarkerUtilities;
-import org.eclipse.ui.views.markers.WorkbenchMarkerResolution;
-import org.eclipse.wst.jsdt.core.CorrectionEngine;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.ASTRequestor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MultiStateCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaMarkerAnnotation;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- */
-public class CorrectionMarkerResolutionGenerator implements IMarkerResolutionGenerator, IMarkerResolutionGenerator2 {
-
- public static class CorrectionMarkerResolution extends WorkbenchMarkerResolution {
-
- private static final IMarker[] NO_MARKERS= new IMarker[0];
- private static final int BATCH_SIZE= 40;
-
- private IJavaScriptUnit fCompilationUnit;
- private int fOffset;
- private int fLength;
- private IJavaCompletionProposal fProposal;
- private final IMarker fMarker;
-
- /**
- * Constructor for CorrectionMarkerResolution.
- * @param marker
- */
- public CorrectionMarkerResolution(IJavaScriptUnit cu, int offset, int length, IJavaCompletionProposal proposal, IMarker marker) {
- fCompilationUnit= cu;
- fOffset= offset;
- fLength= length;
- fProposal= proposal;
- fMarker= marker;
- }
-
- /* (non-Javadoc)
- * @see IMarkerResolution#getLabel()
- */
- public String getLabel() {
- return fProposal.getDisplayString();
- }
-
- /* (non-Javadoc)
- * @see IMarkerResolution#run(IMarker)
- */
- public void run(IMarker marker) {
- try {
- IEditorPart part= EditorUtility.isOpenInEditor(fCompilationUnit);
- if (part == null) {
- part= JavaScriptUI.openInEditor(fCompilationUnit, true, false);
- if (part instanceof ITextEditor) {
- ((ITextEditor) part).selectAndReveal(fOffset, fLength);
- }
- }
- if (part != null) {
- IEditorInput input= part.getEditorInput();
- IDocument doc= JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(input);
- fProposal.apply(doc);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- public void run(IMarker[] markers, IProgressMonitor monitor) {
- if (markers.length == 1) {
- run(markers[0]);
- return;
- }
- IProgressMonitor pm= monitor;
- if (pm == null)
- pm= new NullProgressMonitor();
-
- try {
- if (fProposal instanceof FixCorrectionProposal) {
- ICleanUp cleanUp= ((FixCorrectionProposal)fProposal).getCleanUp();
- if (cleanUp != null) {
- Hashtable/*<IJavaScriptUnit, List<IProblemLocation>*/ problemLocations= new Hashtable();
- for (int i= 0; i < markers.length; i++) {
- IMarker marker= markers[i];
- IJavaScriptUnit cu= getCompilationUnit(marker);
-
- if (cu != null) {
- try {
- IEditorInput input= EditorUtility.getEditorInput(cu);
- IProblemLocation location= findProblemLocation(input, marker);
- if (location != null) {
- if (!problemLocations.containsKey(cu.getPrimary())) {
- problemLocations.put(cu.getPrimary(), new ArrayList());
- }
- List l= (List)problemLocations.get(cu.getPrimary());
- l.add(location);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- if (problemLocations.size() > 0) {
-
- Set cus= problemLocations.keySet();
- Hashtable projects= new Hashtable();
- for (Iterator iter= cus.iterator(); iter.hasNext();) {
- IJavaScriptUnit cu= (IJavaScriptUnit)iter.next();
- IJavaScriptProject project= cu.getJavaScriptProject();
- if (!projects.containsKey(project)) {
- projects.put(project, new ArrayList());
- }
- ((List)projects.get(project)).add(cu);
- }
-
- pm.beginTask("", problemLocations.size() * 2 + 2 + projects.keySet().size()); //$NON-NLS-1$
-
- String name= ""; //$NON-NLS-1$
- String[] descriptions= cleanUp.getDescriptions();
- if (descriptions != null && descriptions.length == 1) {
- name= descriptions[0];
- }
- CompositeChange allChanges= new CompositeChange(name);
-
- for (Iterator projectIter= projects.keySet().iterator(); projectIter.hasNext();) {
- IJavaScriptProject project= (IJavaScriptProject)projectIter.next();
- List compilationUnitsList= (List)projects.get(project);
- IJavaScriptUnit[] compilationUnits= (IJavaScriptUnit[])compilationUnitsList.toArray(new IJavaScriptUnit[compilationUnitsList.size()]);
-
- try {
- cleanUpProject(project, compilationUnits, cleanUp, problemLocations, allChanges, pm);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } finally {
- pm.worked(1);
- }
- }
-
- if (pm.isCanceled())
- return;
-
- allChanges.initializeValidationData(new SubProgressMonitor(pm, 1));
-
- if (!validChanges(allChanges))
- return;
-
- PerformChangeOperation op= new PerformChangeOperation(allChanges);
- op.setUndoManager(RefactoringCore.getUndoManager(), allChanges.getName());
- try {
- op.run(new SubProgressMonitor(pm, 1));
- } catch (CoreException e1) {
- JavaScriptPlugin.log(e1);
- } finally {
- pm.worked(1);
- }
- IEditorPart part= EditorUtility.isOpenInEditor(fCompilationUnit);
- if (part instanceof ITextEditor) {
- ((ITextEditor) part).selectAndReveal(fOffset, fLength);
- part.setFocus();
- }
- }
- }
- }
- } finally {
- pm.done();
- }
- }
-
- private boolean validChanges(CompositeChange change) {
- RefactoringStatus result= new RefactoringStatus();
- List files= new ArrayList();
- try {
- findFilesToBeModified(change, files);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return false;
- }
- result.merge(Checks.validateModifiesFiles((IFile[])files.toArray(new IFile[files.size()]), JavaScriptPlugin.getActiveWorkbenchShell().getShell()));
- if (result.hasFatalError()) {
- RefactoringStatusEntry[] entries= result.getEntries();
- IStatus status;
- if (entries.length > 1) {
- status= new MultiStatus(JavaScriptUI.ID_PLUGIN, 0, result.getMessageMatchingSeverity(RefactoringStatus.ERROR), null);
- for (int i= 0; i < entries.length; i++) {
- ((MultiStatus)status).add(new Status(entries[i].getSeverity(), JavaScriptUI.ID_PLUGIN, 0, entries[i].getMessage(), null));
- }
- } else {
- RefactoringStatusEntry entry= entries[0];
- status= new Status(entry.getSeverity(), JavaScriptUI.ID_PLUGIN, 0, entry.getMessage(), null);
- }
- ErrorDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell().getShell(), CorrectionMessages.CorrectionMarkerResolutionGenerator__multiFixErrorDialog_Titel, CorrectionMessages.CorrectionMarkerResolutionGenerator_multiFixErrorDialog_description, status);
- return false;
- }
- return true;
- }
-
- private void findFilesToBeModified(CompositeChange change, List result) throws JavaScriptModelException {
- Change[] children= change.getChildren();
- for (int i=0;i < children.length;i++) {
- Change child= children[i];
- if (child instanceof CompositeChange) {
- findFilesToBeModified((CompositeChange)child, result);
- } else if (child instanceof MultiStateCompilationUnitChange) {
- result.add(((MultiStateCompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
- } else if (child instanceof CompilationUnitChange) {
- result.add(((CompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
- }
- }
- }
-
- private void cleanUpProject(IJavaScriptProject project, IJavaScriptUnit[] compilationUnits, ICleanUp cleanUp, Hashtable problemLocations, CompositeChange result, IProgressMonitor monitor) throws CoreException {
- cleanUp.checkPreConditions(project, compilationUnits, new SubProgressMonitor(monitor, 1));
- for (int i= 0; i < compilationUnits.length; i++) {
- IJavaScriptUnit cu= compilationUnits[i];
- JavaScriptUnit root= getASTRoot(cu, new SubProgressMonitor(monitor, 1));
- List locationList= (List)problemLocations.get(cu);
- IProblemLocation[] locations= (IProblemLocation[])locationList.toArray(new IProblemLocation[locationList.size()]);
-
- IFix fix= cleanUp.createFix(root, locations);
-
- if (monitor.isCanceled())
- return;
-
- if (fix != null) {
- TextChange change= fix.createChange();
-
- if (monitor.isCanceled())
- return;
-
- result.add(change);
- monitor.worked(1);
- }
-
- }
- cleanUp.checkPostConditions(null);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolution2#getDescription()
- */
- public String getDescription() {
- return fProposal.getAdditionalProposalInfo();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolution2#getImage()
- */
- public Image getImage() {
- return fProposal.getImage();
- }
-
- /**
- * {@inheritDoc}
- */
- public IMarker[] findOtherMarkers(IMarker[] markers) {
- if (!(fProposal instanceof FixCorrectionProposal))
- return NO_MARKERS;
-
- FixCorrectionProposal fix= (FixCorrectionProposal)fProposal;
- final ICleanUp cleanUp= fix.getCleanUp();
- if (cleanUp == null)
- return NO_MARKERS;
-
- final Hashtable fileMarkerTable= getMarkersForFiles(markers);
- if (fileMarkerTable.isEmpty())
- return NO_MARKERS;
-
- Hashtable projectICUTable= getCompilationUnitsForProjects(fileMarkerTable);
- if (projectICUTable.size() == 0)
- return NO_MARKERS;
-
- final List result= new ArrayList();
-
- for (Iterator iter= projectICUTable.keySet().iterator(); iter.hasNext();) {
- IJavaScriptProject project= (IJavaScriptProject)iter.next();
- List cus= (List)projectICUTable.get(project);
- ASTParser parser= getParser(project);
-
- int start= 0;
- int end= 0;
- while (end < cus.size()) {
- end= Math.min(start + BATCH_SIZE, cus.size());
-
- List toParse= cus.subList(start, end);
- IJavaScriptUnit[] units= (IJavaScriptUnit[])toParse.toArray(new IJavaScriptUnit[toParse.size()]);
- parser.createASTs(units, new String[0], new ASTRequestor() {
- /**
- * {@inheritDoc}
- */
- public void acceptAST(IJavaScriptUnit cu, JavaScriptUnit root) {
- try {
- IEditorInput input= EditorUtility.getEditorInput(cu);
-
- List fileMarkers= (List)fileMarkerTable.get(cu.getResource());
-
- for (Iterator iterator= fileMarkers.iterator(); iterator.hasNext();) {
- IMarker marker= (IMarker)iterator.next();
- IProblemLocation location= findProblemLocation(input, marker);
- if (location != null) {
- if (cleanUp.canFix(root, location)) {
- result.add(marker);
- }
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }, new NullProgressMonitor());
-
- start= end;
- }
- }
- if (result.size() == 0)
- return NO_MARKERS;
-
- return (IMarker[])result.toArray(new IMarker[result.size()]);
- }
-
- /**
- * Returns the markers with the same type as fMarker.getType for each IFile.
- */
- private Hashtable/*<IFile, List<IMarker>>*/ getMarkersForFiles(IMarker[] markers) {
- final Hashtable result= new Hashtable();
-
- String markerType;
- try {
- markerType= fMarker.getType();
- } catch (CoreException e1) {
- JavaScriptPlugin.log(e1);
- return result;
- }
-
- for (int i= 0; i < markers.length; i++) {
- IMarker marker= markers[i];
- if (!marker.equals(fMarker)) {
- String currMarkerType= null;
- try {
- currMarkerType= marker.getType();
- } catch (CoreException e1) {
- JavaScriptPlugin.log(e1);
- }
-
- if (currMarkerType != null && currMarkerType.equals(markerType)) {
- IResource res= marker.getResource();
- if (res instanceof IFile && res.isAccessible()) {
- List markerList= (List)result.get(res);
- if (markerList == null) {
- markerList= new ArrayList();
- result.put(res, markerList);
- }
- markerList.add(marker);
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Returns the ICompilationUnits for each IJavaScriptProject
- */
- private Hashtable/*<IJavaScriptProject, List<IJavaScriptUnit>>*/ getCompilationUnitsForProjects(final Hashtable/*<IFile, List<IMarker>>*/ fileMarkerTable) {
- Hashtable result= new Hashtable();
- for (Iterator iter= fileMarkerTable.keySet().iterator(); iter.hasNext();) {
- IFile res= (IFile)iter.next();
- IJavaScriptElement element= JavaScriptCore.create(res);
-
- if (element instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit)element;
- List cus= (List)result.get(cu.getJavaScriptProject());
- if (cus == null) {
- cus= new ArrayList();
- result.put(cu.getJavaScriptProject(), cus);
- }
- cus.add(cu);
- }
- }
- return result;
- }
-
- private static ASTParser getParser(IJavaScriptProject javaProject) {
- ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
- parser.setResolveBindings(true);
- parser.setProject(javaProject);
- return parser;
- }
-
- private static JavaScriptUnit getASTRoot(IJavaScriptUnit compilationUnit, IProgressMonitor monitor) {
- JavaScriptUnit result= ASTProvider.getASTProvider().getAST(compilationUnit, ASTProvider.WAIT_YES, monitor);
- if (result == null) {
- // see bug 63554
- result= ASTResolving.createQuickFixAST(compilationUnit, monitor);
- }
- return result;
- }
- }
-
- private static final IMarkerResolution[] NO_RESOLUTIONS= new IMarkerResolution[0];
-
-
- /**
- * Constructor for CorrectionMarkerResolutionGenerator.
- */
- public CorrectionMarkerResolutionGenerator() {
- super();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolutionGenerator2#hasResolutions(org.eclipse.core.resources.IMarker)
- */
- public boolean hasResolutions(IMarker marker) {
- return internalHasResolutions(marker);
- }
-
- /* (non-Javadoc)
- * @see IMarkerResolutionGenerator#getResolutions(IMarker)
- */
- public IMarkerResolution[] getResolutions(IMarker marker) {
- return internalGetResolutions(marker);
- }
-
- private static boolean internalHasResolutions(IMarker marker) {
- int id= marker.getAttribute(IJavaScriptModelMarker.ID, -1);
- IJavaScriptUnit cu= getCompilationUnit(marker);
- return cu != null && JavaCorrectionProcessor.hasCorrections(cu, id, MarkerUtilities.getMarkerType(marker));
- }
-
- private static IMarkerResolution[] internalGetResolutions(IMarker marker) {
- if (!internalHasResolutions(marker)) {
- return NO_RESOLUTIONS;
- }
-
- try {
- IJavaScriptUnit cu= getCompilationUnit(marker);
- if (cu != null) {
- IEditorInput input= EditorUtility.getEditorInput(cu);
- if (input != null) {
- IProblemLocation location= findProblemLocation(input, marker);
- if (location != null) {
-
- IInvocationContext context= new AssistContext(cu, location.getOffset(), location.getLength());
- if (!hasProblem (context.getASTRoot().getProblems(), location))
- return NO_RESOLUTIONS;
-
- ArrayList proposals= new ArrayList();
- JavaCorrectionProcessor.collectCorrections(context, new IProblemLocation[] { location }, proposals);
- Collections.sort(proposals, new CompletionProposalComparator());
-
- int nProposals= proposals.size();
- IMarkerResolution[] resolutions= new IMarkerResolution[nProposals];
- for (int i= 0; i < nProposals; i++) {
- resolutions[i]= new CorrectionMarkerResolution(context.getCompilationUnit(), location.getOffset(), location.getLength(), (IJavaCompletionProposal) proposals.get(i), marker);
- }
- return resolutions;
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return NO_RESOLUTIONS;
- }
-
- private static boolean hasProblem(IProblem[] problems, IProblemLocation location) {
- for (int i= 0; i < problems.length; i++) {
- IProblem problem= problems[i];
- if (problem.getID() == location.getProblemId() && problem.getSourceStart() == location.getOffset())
- return true;
- }
- return false;
- }
-
- private static IJavaScriptUnit getCompilationUnit(IMarker marker) {
- IResource res= marker.getResource();
- if (res instanceof IFile && res.isAccessible()) {
- IJavaScriptElement element= JavaScriptCore.create((IFile) res);
- if (element instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) element;
- }
- return null;
- }
-
- private static IProblemLocation findProblemLocation(IEditorInput input, IMarker marker) {
- IAnnotationModel model= JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(input);
- if (model != null) { // open in editor
- Iterator iter= model.getAnnotationIterator();
- while (iter.hasNext()) {
- Object curr= iter.next();
- if (curr instanceof JavaMarkerAnnotation) {
- JavaMarkerAnnotation annot= (JavaMarkerAnnotation) curr;
- if (marker.equals(annot.getMarker())) {
- Position pos= model.getPosition(annot);
- if (pos != null) {
- return new ProblemLocation(pos.getOffset(), pos.getLength(), annot);
- }
- }
- }
- }
- } else { // not open in editor
- IJavaScriptUnit cu= getCompilationUnit(marker);
- return createFromMarker(marker, cu);
- }
- return null;
- }
-
- private static IProblemLocation createFromMarker(IMarker marker, IJavaScriptUnit cu) {
- try {
- int id= marker.getAttribute(IJavaScriptModelMarker.ID, -1);
- int start= marker.getAttribute(IMarker.CHAR_START, -1);
- int end= marker.getAttribute(IMarker.CHAR_END, -1);
- int severity= marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
- String[] arguments= CorrectionEngine.getProblemArguments(marker);
- String markerType= marker.getType();
- if (cu != null && id != -1 && start != -1 && end != -1 && arguments != null) {
- boolean isError= (severity == IMarker.SEVERITY_ERROR);
- return new ProblemLocation(start, end - start, id, arguments, isError, markerType);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.java
deleted file mode 100644
index ebf8673c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-public final class CorrectionMessages extends NLS {
-
- private static final String BUNDLE_NAME= CorrectionMessages.class.getName();
-
- private CorrectionMessages() {
- // Do not instantiate
- }
-
- public static String FixCorrectionProposal_WarningAdditionalProposalInfo;
- public static String LocalCorrectionsSubProcessor_renaming_duplicate_method;
- public static String LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description;
- public static String ModifierCorrectionSubProcessor_addstatictoparenttype_description;
- public static String ModifierCorrectionSubProcessor_changefieldmodifiertononstatic_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertostaticfinal_description;
- public static String ModifierCorrectionSubProcessor_creategetterunsingencapsulatefield_description;
- public static String ModifierCorrectionSubProcessor_createsetterusingencapsulatefield_description;
- public static String ModifierCorrectionSubProcessor_encapsulate_field_error_message;
- public static String ModifierCorrectionSubProcessor_encapsulate_field_error_title;
- public static String ModifierCorrectionSubProcessor_overrides_deprecated_description;
- public static String ModifierCorrectionSubProcessor_remove_override;
- public static String ModifierCorrectionSubProcessor_removefinal_description;
- public static String ModifierCorrectionSubProcessor_removevolatile_description;
- public static String ModifierCorrectionSubProcessor_replacewithgetter_description;
- public static String ModifierCorrectionSubProcessor_replacewithsetter_description;
- public static String QuickAssistProcessor_convert_anonym_to_nested;
- public static String QuickAssistProcessor_convert_local_to_field_description;
- public static String QuickAssistProcessor_extract_to_constant_description;
- public static String QuickAssistProcessor_inline_local_description;
- public static String QuickAssistProcessor_name_extension_from_class;
- public static String QuickAssistProcessor_name_extension_from_interface;
- public static String SerialVersionDefaultProposal_message_default_info;
- public static String SerialVersionHashProposal_message_generated_info;
- public static String SerialVersionHashProposal_dialog_error_caption;
- public static String SerialVersionHashProposal_dialog_error_message;
- public static String SerialVersionHashProposal_computing_id;
- public static String SerialVersionHashProposal_save_caption;
- public static String SerialVersionHashProposal_save_message;
- public static String CorrectPackageDeclarationProposal_name;
- public static String CorrectPackageDeclarationProposal_remove_description;
- public static String CorrectPackageDeclarationProposal_add_description;
- public static String CorrectPackageDeclarationProposal_change_description;
- public static String JavaCorrectionProcessor_addquote_description;
- public static String ChangeCorrectionProposal_error_title;
- public static String ChangeCorrectionProposal_error_message;
- public static String ChangeCorrectionProposal_name_with_shortcut;
- public static String CUCorrectionProposal_error_title;
- public static String CUCorrectionProposal_error_message;
- public static String ReorgCorrectionsSubProcessor_renametype_description;
- public static String ReorgCorrectionsSubProcessor_renamecu_description;
- public static String ReorgCorrectionsSubProcessor_movecu_default_description;
- public static String ReorgCorrectionsSubProcessor_movecu_description;
- public static String ReorgCorrectionsSubProcessor_organizeimports_description;
- public static String ReorgCorrectionsSubProcessor_addcp_project_description;
- public static String ReorgCorrectionsSubProcessor_addcp_archive_description;
- public static String ReorgCorrectionsSubProcessor_addcp_classfolder_description;
- public static String ReorgCorrectionsSubProcessor_50_project_compliance_description;
- public static String ReorgCorrectionsSubProcessor_50_workspace_compliance_description;
- public static String ReorgCorrectionsSubProcessor_addcp_variable_description;
- public static String ReorgCorrectionsSubProcessor_addcp_library_description;
- public static String LocalCorrectionsSubProcessor_surroundwith_description;
- public static String LocalCorrectionsSubProcessor_addthrows_description;
- public static String LocalCorrectionsSubProcessor_addadditionalcatch_description;
- public static String LocalCorrectionsSubProcessor_unnecessaryinstanceof_description;
- public static String LocalCorrectionsSubProcessor_unnecessarythrow_description;
- public static String LocalCorrectionsSubProcessor_classtointerface_description;
- public static String LocalCorrectionsSubProcessor_externalizestrings_description;
- public static String LocalCorrectionsSubProcessor_externalizestrings_dialog_title;
- public static String LocalCorrectionsSubProcessor_extendstoimplements_description;
- public static String LocalCorrectionsSubProcessor_setparenteses_bitop_description;
- public static String LocalCorrectionsSubProcessor_uninitializedvariable_description;
- public static String LocalCorrectionsSubProcessor_removesemicolon_description;
- public static String LocalCorrectionsSubProcessor_removeunreachablecode_description;
- public static String LocalCorrectionsSubProcessor_removeelse_description;
- public static String LocalCorrectionsSubProcessor_hiding_local_label;
- public static String LocalCorrectionsSubProcessor_hiding_field_label;
- public static String LocalCorrectionsSubProcessor_rename_var_label;
- public static String LocalCorrectionsSubProcessor_hiding_argument_label;
- public static String LocalCorrectionsSubProcessor_setparenteses_description;
- public static String LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
- public static String LocalCorrectionsSubProcessor_InferGenericTypeArguments;
- public static String LocalCorrectionsSubProcessor_InferGenericTypeArguments_description;
- public static String TypeMismatchSubProcessor_addcast_description;
- public static String TypeMismatchSubProcessor_changecast_description;
- public static String TypeMismatchSubProcessor_changereturntype_description;
- public static String TypeMismatchSubProcessor_changereturnofoverridden_description;
- public static String TypeMismatchSubProcessor_changereturnofimplemented_description;
- public static String TypeMismatchSubProcessor_removeexceptions_description;
- public static String TypeMismatchSubProcessor_addexceptions_description;
- public static String RemoveDeclarationCorrectionProposal_removeunusedfield_description;
- public static String RemoveDeclarationCorrectionProposal_removeunusedmethod_description;
- public static String RemoveDeclarationCorrectionProposal_removeunusedconstructor_description;
- public static String RemoveDeclarationCorrectionProposal_removeunusedtype_description;
- public static String RemoveDeclarationCorrectionProposal_removeunusedvar_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertostatic_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertononstatic_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertofinal_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertodefault_description;
- public static String ModifierCorrectionSubProcessor_changemodifiertononfinal_description;
- public static String ModifierCorrectionSubProcessor_changevisibility_description;
- public static String ModifierCorrectionSubProcessor_removeabstract_description;
- public static String ModifierCorrectionSubProcessor_removebody_description;
- public static String ModifierCorrectionSubProcessor_default;
- public static String ModifierCorrectionSubProcessor_addabstract_description;
- public static String ModifierCorrectionSubProcessor_removenative_description;
- public static String ModifierCorrectionSubProcessor_addmissingbody_description;
- public static String ModifierCorrectionSubProcessor_setmethodabstract_description;
- public static String ModifierCorrectionSubProcessor_changemethodtononfinal_description;
- public static String ModifierCorrectionSubProcessor_changeoverriddenvisibility_description;
- public static String ModifierCorrectionSubProcessor_changemethodvisibility_description;
- public static String ModifierCorrectionSubProcessor_changemethodtononstatic_description;
- public static String ModifierCorrectionSubProcessor_removeinvalidmodifiers_description;
- public static String ReturnTypeSubProcessor_constrnamemethod_description;
- public static String ReturnTypeSubProcessor_voidmethodreturns_description;
- public static String ReturnTypeSubProcessor_removereturn_description;
- public static String ReturnTypeSubProcessor_missingreturntype_description;
- public static String ReturnTypeSubProcessor_wrongconstructorname_description;
- public static String ReturnTypeSubProcessor_changetovoid_description;
- public static String MissingReturnTypeCorrectionProposal_addreturnstatement_description;
- public static String MissingReturnTypeCorrectionProposal_changereturnstatement_description;
- public static String TypeParameterMismatchSubProcessor_removeTypeParameter;
- public static String UnresolvedElementsSubProcessor_swaparguments_description;
- public static String UnresolvedElementsSubProcessor_addargumentcast_description;
- public static String UnresolvedElementsSubProcessor_changemethod_description;
- public static String UnresolvedElementsSubProcessor_changetoouter_description;
- public static String UnresolvedElementsSubProcessor_changetomethod_description;
- public static String UnresolvedElementsSubProcessor_createmethod_description;
- public static String UnresolvedElementsSubProcessor_createmethod_other_description;
- public static String UnresolvedElementsSubProcessor_createconstructor_description;
- public static String UnresolvedElementsSubProcessor_changetype_description;
- public static String UnresolvedElementsSubProcessor_changetype_nopack_description;
- public static String UnresolvedElementsSubProcessor_importtype_description;
- public static String UnresolvedElementsSubProcessor_changevariable_description;
- public static String UnresolvedElementsSubProcessor_createfield_description;
- public static String UnresolvedElementsSubProcessor_createfield_other_description;
- public static String UnresolvedElementsSubProcessor_createlocal_description;
- public static String UnresolvedElementsSubProcessor_createparameter_description;
- public static String UnresolvedElementsSubProcessor_createconst_description;
- public static String UnresolvedElementsSubProcessor_createenum_description;
- public static String UnresolvedElementsSubProcessor_createconst_other_description;
- public static String UnresolvedElementsSubProcessor_removestatement_description;
- public static String UnresolvedElementsSubProcessor_changeparamsignature_description;
- public static String UnresolvedElementsSubProcessor_changemethodtargetcast_description;
- public static String UnresolvedElementsSubProcessor_changeparamsignature_constr_description;
- public static String UnresolvedElementsSubProcessor_swapparams_description;
- public static String UnresolvedElementsSubProcessor_swapparams_constr_description;
- public static String UnresolvedElementsSubProcessor_removeparam_description;
- public static String UnresolvedElementsSubProcessor_removeparams_description;
- public static String UnresolvedElementsSubProcessor_removeparam_constr_description;
- public static String UnresolvedElementsSubProcessor_removeparams_constr_description;
- public static String UnresolvedElementsSubProcessor_addargument_description;
- public static String UnresolvedElementsSubProcessor_addarguments_description;
- public static String UnresolvedElementsSubProcessor_removeargument_description;
- public static String UnresolvedElementsSubProcessor_removearguments_description;
- public static String UnresolvedElementsSubProcessor_addparam_description;
- public static String UnresolvedElementsSubProcessor_addparams_description;
- public static String UnresolvedElementsSubProcessor_addparam_constr_description;
- public static String UnresolvedElementsSubProcessor_addparams_constr_description;
- public static String UnresolvedElementsSubProcessor_importexplicit_description;
- public static String UnresolvedElementsSubProcessor_missingcastbrackets_description;
- public static String UnresolvedElementsSubProcessor_methodtargetcast2_description;
- public static String UnresolvedElementsSubProcessor_changemethodtargetcast2_description;
- public static String UnresolvedElementsSubProcessor_methodtargetcast_description;
- public static String UnresolvedElementsSubProcessor_arraychangetomethod_description;
- public static String UnresolvedElementsSubProcessor_arraychangetolength_description;
- public static String UnresolvedElementsSubProcessor_addnewkeyword_description;
- public static String JavadocTagsSubProcessor_addjavadoc_method_description;
- public static String JavadocTagsSubProcessor_addjavadoc_type_description;
- public static String JavadocTagsSubProcessor_addjavadoc_field_description;
- public static String JavadocTagsSubProcessor_addjavadoc_paramtag_description;
- public static String JavadocTagsSubProcessor_addjavadoc_throwstag_description;
- public static String JavadocTagsSubProcessor_addjavadoc_returntag_description;
- public static String JavadocTagsSubProcessor_addjavadoc_enumconst_description;
- public static String JavadocTagsSubProcessor_addjavadoc_allmissing_description;
- public static String JavadocTagsSubProcessor_removetag_description;
- public static String NoCorrectionProposal_description;
- public static String MarkerResolutionProposal_additionaldesc;
- public static String NewCUCompletionUsingWizardProposal_createclass_description;
- public static String NewCUCompletionUsingWizardProposal_createenum_description;
- public static String NewCUCompletionUsingWizardProposal_createclass_inpackage_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerclass_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerenum_description;
- public static String NewCUCompletionUsingWizardProposal_createannotation_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerclass_intype_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerenum_intype_description;
- public static String NewCUCompletionUsingWizardProposal_createinterface_description;
- public static String NewCUCompletionUsingWizardProposal_createinterface_inpackage_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerinterface_description;
- public static String NewCUCompletionUsingWizardProposal_createenum_inpackage_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerannotation_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerinterface_intype_description;
- public static String NewCUCompletionUsingWizardProposal_createinnerannotation_intype_description;
- public static String NewCUCompletionUsingWizardProposal_createannotation_inpackage_description;
- public static String NewCUCompletionUsingWizardProposal_createclass_info;
- public static String NewCUCompletionUsingWizardProposal_createenum_info;
- public static String NewCUCompletionUsingWizardProposal_createinterface_info;
- public static String NewCUCompletionUsingWizardProposal_createannotation_info;
- public static String UnimplementedMethodsCompletionProposal_description;
- public static String UnimplementedMethodsCompletionProposal_info;
- public static String ConstructorFromSuperclassProposal_description;
- public static String AssignToVariableAssistProposal_assigntolocal_description;
- public static String AssignToVariableAssistProposal_assigntofield_description;
- public static String AssignToVariableAssistProposal_assignparamtofield_description;
- public static String QuickAssistProcessor_catchclausetothrows_description;
- public static String QuickAssistProcessor_removecatchclause_description;
- public static String QuickAssistProcessor_unwrap_ifstatement;
- public static String QuickAssistProcessor_unwrap_whilestatement;
- public static String QuickAssistProcessor_unwrap_forstatement;
- public static String QuickAssistProcessor_unwrap_dostatement;
- public static String QuickAssistProcessor_unwrap_trystatement;
- public static String QuickAssistProcessor_unwrap_anonymous;
- public static String QuickAssistProcessor_unwrap_block;
- public static String QuickAssistProcessor_unwrap_methodinvocation;
- public static String QuickAssistProcessor_splitdeclaration_description;
- public static String QuickAssistProcessor_joindeclaration_description;
- public static String QuickAssistProcessor_addfinallyblock_description;
- public static String QuickAssistProcessor_addelseblock_description;
- public static String QuickAssistProcessor_replacethenwithblock_description;
- public static String QuickAssistProcessor_replaceelsewithblock_description;
- public static String QuickAssistProcessor_replacethenelsewithblock_description;
- public static String QuickAssistProcessor_replacebodywithblock_description;
- public static String QuickAssistProcessor_invertequals_description;
- public static String QuickAssistProcessor_typetoarrayInitializer_description;
- public static String QuickAssistProcessor_createmethodinsuper_description;
- public static String LinkedNamesAssistProposal_proposalinfo;
- public static String LinkedNamesAssistProposal_description;
- public static String QuickTemplateProcessor_surround_label;
- public static String NewCUCompletionUsingWizardProposal_dialogtitle;
- public static String NewCUCompletionUsingWizardProposal_tooltip_enclosingtype;
- public static String NewCUCompletionUsingWizardProposal_tooltip_package;
- public static String JavaCorrectionProcessor_error_quickfix_message;
- public static String JavaCorrectionProcessor_error_status;
- public static String JavaCorrectionProcessor_error_quickassist_message;
- public static String TaskMarkerProposal_description;
- public static String TypeChangeCompletionProposal_field_name;
- public static String TypeChangeCompletionProposal_variable_name;
- public static String TypeChangeCompletionProposal_param_name;
- public static String TypeChangeCompletionProposal_method_name;
- public static String ImplementInterfaceProposal_name;
- public static String AdvancedQuickAssistProcessor_convertToIfElse_description;
- public static String AdvancedQuickAssistProcessor_inverseIf_description;
- public static String AdvancedQuickAssistProcessor_inverseBooleanVariable;
- public static String AdvancedQuickAssistProcessor_castAndAssign;
- public static String AdvancedQuickAssistProcessor_pullNegationUp;
- public static String AdvancedQuickAssistProcessor_joinIfSequence;
- public static String AdvancedQuickAssistProcessor_pickSelectedString;
- public static String AdvancedQuickAssistProcessor_negatedVariableName;
- public static String AdvancedQuickAssistProcessor_pushNegationDown;
- public static String AdvancedQuickAssistProcessor_convertSwitchToIf;
- public static String AdvancedQuickAssistProcessor_inverseIfContinue_description;
- public static String AdvancedQuickAssistProcessor_inverseIfToContinue_description;
- public static String AdvancedQuickAssistProcessor_exchangeInnerAndOuterIfConditions_description;
- public static String AdvancedQuickAssistProcessor_inverseConditions_description;
- public static String AdvancedQuickAssistProcessor_inverseConditionalExpression_description;
- public static String AdvancedQuickAssistProcessor_replaceIfWithConditional;
- public static String AdvancedQuickAssistProcessor_replaceConditionalWithIf;
- public static String AdvancedQuickAssistProcessor_joinWithOuter_description;
- public static String AdvancedQuickAssistProcessor_joinWithInner_description;
- public static String AdvancedQuickAssistProcessor_splitAndCondition_description;
- public static String AdvancedQuickAssistProcessor_joinWithOr_description;
- public static String AdvancedQuickAssistProcessor_splitOrCondition_description;
- public static String AdvancedQuickAssistProcessor_exchangeOperands_description;
- public static String AddTypeParameterProposal_method_label;
- public static String AddTypeParameterProposal_type_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, CorrectionMessages.class);
- }
-
- public static String LocalCorrectionsSubProcessor_externalizestrings_additional_info;
- public static String AssignToVariableAssistProposal_assigntoexistingfield_description;
- public static String ReorgCorrectionsSubProcessor_50_compliance_operation;
- public static String ReorgCorrectionsSubProcessor_no_50jre_title;
- public static String ReorgCorrectionsSubProcessor_no_50jre_message;
- public static String ReorgCorrectionsSubProcessor_50_compliance_changeworkspace_description;
- public static String ReorgCorrectionsSubProcessor_50_compliance_changeproject_description;
- public static String ReorgCorrectionsSubProcessor_50_compliance_changeProjectJREToDefault_description;
- public static String ReorgCorrectionsSubProcessor_50_compliance_changeWorkspaceJRE_description;
- public static String ReorgCorrectionsSubProcessor_50_compliance_changeProjectJRE_description;
- public static String ModifierCorrectionSubProcessor_default_visibility_label;
- public static String ReorgCorrectionsSubProcessor_configure_buildpath_label;
- public static String ReorgCorrectionsSubProcessor_configure_buildpath_description;
- public static String QuickAssistProcessor_extract_to_local_description;
- public static String SuppressWarningsSubProcessor_suppress_warnings_initializer_label;
- public static String SuppressWarningsSubProcessor_suppress_warnings_label;
- public static String ReorgCorrectionsSubProcessor_accessrules_description;
- public static String UnresolvedElementsSubProcessor_change_full_type_description;
- public static String LocalCorrectionsSubProcessor_qualify_left_hand_side_description;
- public static String LocalCorrectionsSubProcessor_LocalCorrectionsSubProcessor_qualify_right_hand_side_description;
- public static String UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description;
- public static String UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description;
- public static String MissingAnnotationAttributesProposal_add_missing_attributes_label;
- public static String FixCorrectionProposal_HitCtrlEnter_description;
- public static String FixCorrectionProposal_hitCtrlEnter_variable_description;
- public static String CorrectionMarkerResolutionGenerator__multiFixErrorDialog_Titel;
- public static String CorrectionMarkerResolutionGenerator_multiFixErrorDialog_description;
- public static String LocalCorrectionsSubProcessor_insert_break_statement;
- public static String SuppressWarningsSubProcessor_fix_suppress_token_label;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties
deleted file mode 100644
index 08041258..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties
+++ /dev/null
@@ -1,353 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-# ------ SerialVersionProposal
-
-SerialVersionDefaultProposal_message_default_info=Adds a default serial version ID to the selected type.<p></p><p>Use this option to add a user-defined ID in combination with custom serialization code if the type did undergo structural changes since its first release.</p>
-SerialVersionHashProposal_message_generated_info=Adds a generated serial version ID to the selected type.<p></p><p>Use this option to add a compiler-generated ID if the type did not undergo structural changes since its first release.</p>
-
-SerialVersionHashProposal_dialog_error_caption=Error
-SerialVersionHashProposal_dialog_error_message=The following problem occurred: {0}
-
-SerialVersionHashProposal_computing_id=Computing serial version ID...
-SerialVersionHashProposal_save_caption=Quick Fix
-SerialVersionHashProposal_save_message=The JavaScript file has been modified.\n\nOK to save before computing the serial version ID?
-
-# ------ CorrectPackageDeclarationProposal
-
-CorrectPackageDeclarationProposal_name=Correct package declaration
-
-CorrectPackageDeclarationProposal_remove_description=Remove package declaration ''package {0}''
-CorrectPackageDeclarationProposal_add_description=Add package declaration ''{0};''
-CorrectPackageDeclarationProposal_change_description=Change package declaration to ''{0}''
-CorrectionMarkerResolutionGenerator__multiFixErrorDialog_Titel=Error
-
-# ------ JavaCorrectionProcessor
-
-JavaCorrectionProcessor_addquote_description=Insert missing quote
-
-ChangeCorrectionProposal_error_title=Quick Fix
-ChangeCorrectionProposal_error_message=An exception occurred while applying the quick fix.
-ChangeCorrectionProposal_name_with_shortcut={0} ({1} direct access)
-
-CUCorrectionProposal_error_title=Quick Fix
-CUCorrectionProposal_error_message=An exception occurred while applying the quick fix.
-
-ReorgCorrectionsSubProcessor_renametype_description=Rename type to ''{0}''
-ReorgCorrectionsSubProcessor_renamecu_description=Rename JavaScript file to ''{0}''
-ReorgCorrectionsSubProcessor_movecu_default_description=Move ''{0}'' to the default package
-ReorgCorrectionsSubProcessor_movecu_description=Move ''{0}'' to package ''{1}''
-ReorgCorrectionsSubProcessor_no_50jre_title=Change To 5.0 Quick Fix
-ReorgCorrectionsSubProcessor_no_50jre_message=The compiler compliance has been changed to 5.0, but no 5.0 JRE could be found in the installed JRE's. You have to manually set the correct JRE or add a new JRE in the preferences (Java - Installed JRE's).
-ReorgCorrectionsSubProcessor_50_compliance_operation=Updating to new JRE
-ReorgCorrectionsSubProcessor_accessrules_description=Configure access rules...
-ReorgCorrectionsSubProcessor_organizeimports_description=Organize imports
-
-ReorgCorrectionsSubProcessor_addcp_project_description=Add project ''{0}'' to build path of ''{1}''
-ReorgCorrectionsSubProcessor_addcp_archive_description=Add archive ''{0}'' to build path of ''{1}''
-ReorgCorrectionsSubProcessor_addcp_classfolder_description=Add class folder ''{0}'' to build path of ''{1}''
-ReorgCorrectionsSubProcessor_50_project_compliance_description=Change project compliance and JRE to 5.0
-ReorgCorrectionsSubProcessor_configure_buildpath_description=Open the JavaScript include path property page of project ''{0}''
-ReorgCorrectionsSubProcessor_50_workspace_compliance_description=Change workspace compliance and JRE to 5.0
-ReorgCorrectionsSubProcessor_50_compliance_changeworkspace_description=<p>Set workspace compiler compliance settings to '5.0'
-ReorgCorrectionsSubProcessor_50_compliance_changeproject_description=<p>Set project compiler compliance settings to '5.0'
-ReorgCorrectionsSubProcessor_50_compliance_changeProjectJREToDefault_description=<p>Set project JRE build path entry to 'default JRE'
-ReorgCorrectionsSubProcessor_50_compliance_changeWorkspaceJRE_description=<p>Set workspace default JRE to ''{0}''
-ReorgCorrectionsSubProcessor_50_compliance_changeProjectJRE_description=<p>Set project JRE build path entry to {0}
-ReorgCorrectionsSubProcessor_addcp_variable_description=Add variable entry ''{0}'' to build path of ''{1}''
-ReorgCorrectionsSubProcessor_addcp_library_description=Add library ''{0}'' to build path of ''{1}''
-ReorgCorrectionsSubProcessor_configure_buildpath_label=Configure build path...
-
-LocalCorrectionsSubProcessor_surroundwith_description=Surround with try/catch
-LocalCorrectionsSubProcessor_addthrows_description=Add throws declaration
-LocalCorrectionsSubProcessor_addadditionalcatch_description=Add catch clause to surrounding try
-LocalCorrectionsSubProcessor_unnecessaryinstanceof_description=Replace with null check
-LocalCorrectionsSubProcessor_unnecessarythrow_description=Remove thrown exception
-LocalCorrectionsSubProcessor_classtointerface_description=Change ''{0}'' to interface
-
-LocalCorrectionsSubProcessor_externalizestrings_description=Open the 'Externalize Strings' wizard
-LocalCorrectionsSubProcessor_externalizestrings_dialog_title=Externalize Strings
-LocalCorrectionsSubProcessor_extendstoimplements_description=Change 'extends' to 'implements'
-LocalCorrectionsSubProcessor_LocalCorrectionsSubProcessor_qualify_right_hand_side_description=Qualify right hand side
-LocalCorrectionsSubProcessor_setparenteses_bitop_description=Put bit operations in parentheses
-LocalCorrectionsSubProcessor_externalizestrings_additional_info=Open the 'Externalize Strings' wizard
-LocalCorrectionsSubProcessor_uninitializedvariable_description=Initialize variable
-LocalCorrectionsSubProcessor_removesemicolon_description=Remove semicolon
-LocalCorrectionsSubProcessor_renaming_duplicate_method=Rename function ''{0}''
-LocalCorrectionsSubProcessor_removeunreachablecode_description=Remove
-LocalCorrectionsSubProcessor_removeelse_description=Remove 'else' keyword and braces.
-LocalCorrectionsSubProcessor_insert_break_statement=Insert 'break' statement
-
-LocalCorrectionsSubProcessor_hiding_local_label=Rename local variable ''{0}''
-LocalCorrectionsSubProcessor_hiding_field_label=Rename var ''{0}''
-LocalCorrectionsSubProcessor_rename_var_label=Rename ''{0}''
-LocalCorrectionsSubProcessor_hiding_argument_label=Rename argument ''{0}''
-LocalCorrectionsSubProcessor_setparenteses_description=Put expression in parentheses
-LocalCorrectionsSubProcessor_InferGenericTypeArguments=Infer Generic Type Arguments...
-LocalCorrectionsSubProcessor_InferGenericTypeArguments_description=Start the 'Infer Generic Type Arguments' refactoring
-LocalCorrectionsSubProcessor_setparenteses_instanceof_description=Put 'instanceof' in parentheses
-LocalCorrectionsSubProcessor_qualify_left_hand_side_description=Qualify left hand side
-LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description=Replace with ''{0}''
-TypeMismatchSubProcessor_addcast_description=Add cast to ''{0}''
-TypeMismatchSubProcessor_changecast_description=Change cast to ''{0}''
-TypeMismatchSubProcessor_changereturntype_description=Change function return type to ''{0}''
-TypeMismatchSubProcessor_changereturnofoverridden_description=Change return type of overridden ''{0}.(..)"
-TypeMismatchSubProcessor_changereturnofimplemented_description=Change return type of implemented ''{0}.(..)"
-TypeMismatchSubProcessor_removeexceptions_description=Remove exceptions from ''{0}(..)''
-TypeParameterMismatchSubProcessor_removeTypeParameter=Remove type parameter
-TypeMismatchSubProcessor_addexceptions_description=Add exceptions to ''{0}.{1}(..)''
-
-RemoveDeclarationCorrectionProposal_removeunusedfield_description=Remove declaration of ''{0}'' and assignments without possible side effects
-RemoveDeclarationCorrectionProposal_removeunusedmethod_description=Remove function ''{0}''
-RemoveDeclarationCorrectionProposal_removeunusedconstructor_description=Remove constructor ''{0}''
-RemoveDeclarationCorrectionProposal_removeunusedtype_description=Remove type ''{0}''
-RemoveDeclarationCorrectionProposal_removeunusedvar_description=Remove declaration of ''{0}'' and assignments without possible side effects
-
-ModifierCorrectionSubProcessor_changemodifiertostatic_description=Change modifier of ''{0}'' to ''static''
-ModifierCorrectionSubProcessor_changemodifiertostaticfinal_description=Change modfier to 'static final'
-ModifierCorrectionSubProcessor_changemodifiertononstatic_description=Remove ''static'' modifier of ''{0}''
-ModifierCorrectionSubProcessor_changemodifiertofinal_description=Change modifier of ''{0}'' to final
-ModifierCorrectionSubProcessor_addstatictoparenttype_description=Add 'static' modifier to parent type
-ModifierCorrectionSubProcessor_overrides_deprecated_description=Mark method as deprecated
-ModifierCorrectionSubProcessor_encapsulate_field_error_message=Cannot perform refactoring. See log for more details.
-ModifierCorrectionSubProcessor_changemodifiertodefault_description=Change modifier of ''{0}'' to default visibility
-ModifierCorrectionSubProcessor_changemodifiertononfinal_description=Remove ''final'' modifier of ''{0}''
-ModifierCorrectionSubProcessor_changevisibility_description=Change visibility of ''{0}'' to ''{1}''
-ModifierCorrectionSubProcessor_removeabstract_description=Remove 'abstract' modifier
-ModifierCorrectionSubProcessor_removevolatile_description=Remove 'volatile' modifier
-ModifierCorrectionSubProcessor_removebody_description=Remove method body
-ModifierCorrectionSubProcessor_remove_override=Remove '@Override' annotation
-ModifierCorrectionSubProcessor_default=default
-ModifierCorrectionSubProcessor_addabstract_description=Make type ''{0}'' abstract
-SuppressWarningsSubProcessor_suppress_warnings_label=Add @SuppressWarnings ''{0}'' to ''{1}''
-ModifierCorrectionSubProcessor_removenative_description=Remove 'native' modifier
-ModifierCorrectionSubProcessor_removefinal_description=Remove 'final' modifier
-ModifierCorrectionSubProcessor_default_visibility_label=(default)
-ModifierCorrectionSubProcessor_addmissingbody_description=Add body
-ModifierCorrectionSubProcessor_setmethodabstract_description=Add 'abstract' modifier
-ModifierCorrectionSubProcessor_replacewithgetter_description=Replace {0} with getter
-ModifierCorrectionSubProcessor_replacewithsetter_description=Replace {0} with setter
-ModifierCorrectionSubProcessor_encapsulate_field_error_title=Encapsulate Field
-ModifierCorrectionSubProcessor_changemethodtononfinal_description=Remove ''final'' modifier of ''{0}''(..)
-ModifierCorrectionSubProcessor_changeoverriddenvisibility_description=Change visibility of ''{0}'' to ''{1}''
-ModifierCorrectionSubProcessor_changemethodvisibility_description=Change method visibility to ''{0}''
-ModifierCorrectionSubProcessor_changemethodtononstatic_description=Remove ''static'' modifier of ''{0}''(..)
-SuppressWarningsSubProcessor_suppress_warnings_initializer_label=initializer
-ModifierCorrectionSubProcessor_removeinvalidmodifiers_description=Remove invalid modifiers
-
-ReturnTypeSubProcessor_constrnamemethod_description=Change to constructor
-ReturnTypeSubProcessor_voidmethodreturns_description=Change function return type to ''{0}''
-ReturnTypeSubProcessor_removereturn_description=Change to 'return;'
-ReturnTypeSubProcessor_missingreturntype_description=Set function return type to ''{0}''
-ReturnTypeSubProcessor_wrongconstructorname_description=Change to constructor
-
-ReturnTypeSubProcessor_changetovoid_description=Change return type to 'void'
-
-MissingReturnTypeCorrectionProposal_addreturnstatement_description=Add return statement
-MissingAnnotationAttributesProposal_add_missing_attributes_label=Add missing attributes
-MissingReturnTypeCorrectionProposal_changereturnstatement_description=Change return statement
-
-UnresolvedElementsSubProcessor_swaparguments_description=Swap arguments {0} and {1}
-UnresolvedElementsSubProcessor_addargumentcast_description=Cast argument {0} to ''{1}''
-UnresolvedElementsSubProcessor_changemethod_description=Change to ''{0}(..)''
-UnresolvedElementsSubProcessor_changetoouter_description=Qualify with enclosing type ''{0}''
-UnresolvedElementsSubProcessor_changetomethod_description=Change to ''{0}''
-UnresolvedElementsSubProcessor_createmethod_description=Create function ''{0}''
-UnresolvedElementsSubProcessor_createmethod_other_description=Create function ''{0}'' in type ''{1}''
-UnresolvedElementsSubProcessor_createconstructor_description=Create constructor ''{0}''
-
-UnresolvedElementsSubProcessor_changetype_description=Change to ''{0}'' ({1})
-UnresolvedElementsSubProcessor_changetype_nopack_description=Change to ''{0}''
-UnresolvedElementsSubProcessor_change_full_type_description=Change type to ''{0}''
-UnresolvedElementsSubProcessor_importtype_description=Import ''{0}'' ({1})
-
-UnresolvedElementsSubProcessor_changevariable_description=Change to ''{0}''
-UnresolvedElementsSubProcessor_createfield_description=Create var ''{0}''
-UnresolvedElementsSubProcessor_createfield_other_description=Create var ''{0}'' in type ''{1}''
-UnresolvedElementsSubProcessor_createlocal_description=Create local variable ''{0}''
-UnresolvedElementsSubProcessor_createparameter_description=Create parameter ''{0}''
-
-UnresolvedElementsSubProcessor_createconst_description=Create constant ''{0}''
-UnresolvedElementsSubProcessor_createenum_description=Create enum constant ''{0}'' in ''{1}''
-UnresolvedElementsSubProcessor_createconst_other_description=Create constant ''{0}'' in type ''{1}''
-
-UnresolvedElementsSubProcessor_removestatement_description=Remove assignment
-
-UnresolvedElementsSubProcessor_changeparamsignature_description=Change function ''{0}'' to ''{1}''
-UnresolvedElementsSubProcessor_changemethodtargetcast_description=Change function receiver cast
-UnresolvedElementsSubProcessor_changeparamsignature_constr_description=Change constructor ''{0}'' to ''{1}''
-UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description=Change to ''{0}''
-UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description=Create attribute ''{0}()''
-UnresolvedElementsSubProcessor_swapparams_description=Change function ''{0}'': Swap parameters ''{1}''
-UnresolvedElementsSubProcessor_swapparams_constr_description=Change constructor ''{0}'': Swap parameters ''{1}''
-UnresolvedElementsSubProcessor_removeparam_description=Change function ''{0}'': Remove parameter ''{1}''
-UnresolvedElementsSubProcessor_removeparams_description=Change function ''{0}'': Remove parameters ''{1}''
-UnresolvedElementsSubProcessor_removeparam_constr_description=Change constructor ''{0}'': Remove parameter ''{1}''
-UnresolvedElementsSubProcessor_removeparams_constr_description=Change constructor ''{0}'': Remove parameters ''{1}''
-UnresolvedElementsSubProcessor_addargument_description=Add argument to match ''{0}''
-UnresolvedElementsSubProcessor_addarguments_description=Add arguments to match ''{0}''
-UnresolvedElementsSubProcessor_removeargument_description=Remove argument to match ''{0}''
-UnresolvedElementsSubProcessor_removearguments_description=Remove arguments to match ''{0}''
-UnresolvedElementsSubProcessor_addparam_description=Change function ''{0}'': Add parameter ''{1}''
-UnresolvedElementsSubProcessor_addparams_description=Change function ''{0}'': Add parameters ''{1}''
-UnresolvedElementsSubProcessor_addparam_constr_description=Change constructor ''{0}'': Add parameter ''{1}''
-UnresolvedElementsSubProcessor_addparams_constr_description=Change constructor ''{0}'': Add parameters ''{1}''
-
-UnresolvedElementsSubProcessor_importexplicit_description= Explicitly import ''{0}''
-UnresolvedElementsSubProcessor_missingcastbrackets_description=Add parentheses around cast
-UnresolvedElementsSubProcessor_methodtargetcast2_description=Add cast to ''{0}''
-UnresolvedElementsSubProcessor_changemethodtargetcast2_description=Change cast of ''{0}''
-UnresolvedElementsSubProcessor_methodtargetcast_description=Add cast to method receiver
-UnresolvedElementsSubProcessor_arraychangetomethod_description=Change to ''{0}(..)''
-UnresolvedElementsSubProcessor_arraychangetolength_description=Change to 'length'
-UnresolvedElementsSubProcessor_addnewkeyword_description=Insert 'new' keyword
-
-JavadocTagsSubProcessor_addjavadoc_method_description=Add JSDoc comment
-JavadocTagsSubProcessor_addjavadoc_type_description=Add JSDoc comment
-JavadocTagsSubProcessor_addjavadoc_field_description=Add JSDoc comment
-JavadocTagsSubProcessor_addjavadoc_paramtag_description=Add '@param' tag
-JavadocTagsSubProcessor_addjavadoc_throwstag_description=Add '@throws' tag
-JavadocTagsSubProcessor_addjavadoc_returntag_description=Add '@return' tag
-JavadocTagsSubProcessor_addjavadoc_enumconst_description=Add JSDoc comment
-JavadocTagsSubProcessor_addjavadoc_allmissing_description=Add all missing tags
-JavadocTagsSubProcessor_removetag_description=Remove tag
-
-NoCorrectionProposal_description=No suggestions available
-
-MarkerResolutionProposal_additionaldesc=Problem description: {0}
-
-NewCUCompletionUsingWizardProposal_createclass_description=Create class ''{0}''
-NewCUCompletionUsingWizardProposal_createenum_description=Create enum ''{0}''
-NewCUCompletionUsingWizardProposal_createclass_inpackage_description=Create class ''{0}'' in package ''{1}''
-NewCUCompletionUsingWizardProposal_createinnerclass_description=Create member class ''{0}''
-NewCUCompletionUsingWizardProposal_createinnerenum_description=Create member enum ''{0}''
-NewCUCompletionUsingWizardProposal_createannotation_description=Create annotation ''{0}''
-NewCUCompletionUsingWizardProposal_createinnerclass_intype_description=Create class ''{0}'' in type ''{1}''
-NewCUCompletionUsingWizardProposal_createinnerenum_intype_description=Create enum ''{0}'' in type ''{1}''
-
-NewCUCompletionUsingWizardProposal_createinterface_description=Create interface ''{0}''
-NewCUCompletionUsingWizardProposal_createinterface_inpackage_description=Create interface ''{0}'' in package ''{1}''
-NewCUCompletionUsingWizardProposal_createinnerinterface_description=Create member interface ''{0}''
-NewCUCompletionUsingWizardProposal_createenum_inpackage_description=Create enum ''{0}'' in package ''{1}''
-NewCUCompletionUsingWizardProposal_createinnerannotation_description=Create member annotation ''{0}''
-NewCUCompletionUsingWizardProposal_createinnerinterface_intype_description=Create interface ''{0}'' in type ''{1}''
-NewCUCompletionUsingWizardProposal_createinnerannotation_intype_description=Create annotation ''{0}'' in type ''{1}''
-NewCUCompletionUsingWizardProposal_createannotation_inpackage_description=Create annotation ''{0}'' in package ''{1}''
-
-NewCUCompletionUsingWizardProposal_createclass_info=Opens the new class wizard to create the type.
-NewCUCompletionUsingWizardProposal_createenum_info=Opens the new enum wizard to create the type.
-NewCUCompletionUsingWizardProposal_createinterface_info=Opens the new interface wizard to create the type.
-NewCUCompletionUsingWizardProposal_createannotation_info=Opens the new annotation wizard to create the type.
-
-
-UnimplementedMethodsCompletionProposal_description=Add unimplemented functions
-UnimplementedMethodsCompletionProposal_info={0} function(s) to implement:
-
-ConstructorFromSuperclassProposal_description=Add constructor ''{0}''
-
-AssignToVariableAssistProposal_assigntolocal_description=Assign statement to new local variable
-AssignToVariableAssistProposal_assigntofield_description=Assign statement to new field
-AssignToVariableAssistProposal_assignparamtofield_description=Assign parameter to new var
-AssignToVariableAssistProposal_assigntoexistingfield_description=Assign parameter to var ''{0}''
-
-QuickAssistProcessor_catchclausetothrows_description=Replace catch clause with throws
-QuickAssistProcessor_removecatchclause_description=Remove catch clause
-QuickAssistProcessor_name_extension_from_interface={0}Extension
-
-
-QuickAssistProcessor_unwrap_ifstatement=Remove surrounding 'if' statement
-QuickAssistProcessor_unwrap_whilestatement=Remove surrounding 'while' statement
-QuickAssistProcessor_unwrap_forstatement=Remove surrounding 'for' statement
-QuickAssistProcessor_unwrap_dostatement=Remove surrounding 'do' statement
-QuickAssistProcessor_unwrap_trystatement=Remove surrounding 'try' block
-QuickAssistProcessor_unwrap_anonymous=Remove surrounding anonymous class
-QuickAssistProcessor_unwrap_block=Remove surrounding block
-QuickAssistProcessor_unwrap_methodinvocation=Remove surrounding method invocation
-
-QuickAssistProcessor_splitdeclaration_description=Split variable declaration
-QuickAssistProcessor_extract_to_local_description=Extract to local variable
-QuickAssistProcessor_extract_to_constant_description=Extract to constant
-QuickAssistProcessor_joindeclaration_description=Join variable declaration
-QuickAssistProcessor_addfinallyblock_description=Add finally block
-QuickAssistProcessor_addelseblock_description=Add else block
-
-QuickAssistProcessor_replacethenwithblock_description=Change 'if' statement to block
-QuickAssistProcessor_replaceelsewithblock_description=Change 'else' statement to block
-QuickAssistProcessor_replacethenelsewithblock_description=Change 'if-else' statements to blocks
-QuickAssistProcessor_replacebodywithblock_description=Change body statement to block
-
-QuickAssistProcessor_invertequals_description=Invert equals
-QuickAssistProcessor_inline_local_description=Inline local variable
-QuickAssistProcessor_convert_anonym_to_nested=Convert anonymous to nested class
-QuickAssistProcessor_name_extension_from_class={0}Implementation
-QuickAssistProcessor_typetoarrayInitializer_description=Add type to initializer
-QuickAssistProcessor_convert_local_to_field_description=Convert local variable to field
-QuickAssistProcessor_createmethodinsuper_description=Create ''{1}()'' in super type ''{0}''
-
-
-LinkedNamesAssistProposal_proposalinfo=Link all references for a local rename (does not change references in other files)
-LinkedNamesAssistProposal_description=Rename in file
-
-QuickTemplateProcessor_surround_label={0} ({1})
-
-NewCUCompletionUsingWizardProposal_dialogtitle=New
-NewCUCompletionUsingWizardProposal_tooltip_enclosingtype=Enclosing Type:
-NewCUCompletionUsingWizardProposal_tooltip_package=Package:
-
-JavaCorrectionProcessor_error_quickfix_message=An error occurred while computing quick fixes. Check log for details.
-JavaCorrectionProcessor_error_status=Exception while processing quick fixes or quick assists
-JavaCorrectionProcessor_error_quickassist_message=An error occurred while computing quick assists. Check log for details.
-
-TaskMarkerProposal_description=Remove task tag
-
-TypeChangeCompletionProposal_field_name=Change type of ''{0}'' to ''{1}''
-TypeChangeCompletionProposal_variable_name=Change type of ''{0}'' to ''{1}''
-TypeChangeCompletionProposal_param_name=Change type of ''{0}'' to ''{1}''
-TypeChangeCompletionProposal_method_name=Change return type of ''{0}(..)'' to ''{1}''
-ImplementInterfaceProposal_name=Let ''{0}'' implement ''{1}''
-
-AdvancedQuickAssistProcessor_convertToIfElse_description=Convert to 'if-else'
-AdvancedQuickAssistProcessor_inverseIf_description=Invert 'if' statement
-AdvancedQuickAssistProcessor_inverseBooleanVariable=Invert local variable
-AdvancedQuickAssistProcessor_castAndAssign=Introduce new local with casted type
-AdvancedQuickAssistProcessor_pullNegationUp=Pull negation up
-AdvancedQuickAssistProcessor_joinIfSequence=Join 'if' sequence in if-else-if
-AdvancedQuickAssistProcessor_pickSelectedString=Pick out selected part of String
-AdvancedQuickAssistProcessor_negatedVariableName=not{0}
-AdvancedQuickAssistProcessor_pushNegationDown=Push negation down
-AdvancedQuickAssistProcessor_convertSwitchToIf=Convert 'switch' to 'if-else'
-AdvancedQuickAssistProcessor_inverseIfContinue_description=Invert 'if/continue' statement, convert to 'if'
-AdvancedQuickAssistProcessor_inverseIfToContinue_description=Invert 'if' statement, convert to 'continue'
-AdvancedQuickAssistProcessor_exchangeInnerAndOuterIfConditions_description=Exchange conditions for inner and outer 'if' statements
-AdvancedQuickAssistProcessor_inverseConditions_description=Invert conditions
-AdvancedQuickAssistProcessor_inverseConditionalExpression_description=Invert conditional expression
-AdvancedQuickAssistProcessor_replaceIfWithConditional=Replace 'if-else' with conditional
-AdvancedQuickAssistProcessor_replaceConditionalWithIf=Replace conditional with 'if-else'
-AdvancedQuickAssistProcessor_joinWithOuter_description=Join 'if' statement with outer 'if' statement
-AdvancedQuickAssistProcessor_joinWithInner_description=Join 'if' statement with inner 'if' statement
-AdvancedQuickAssistProcessor_splitAndCondition_description=Split && condition
-AdvancedQuickAssistProcessor_joinWithOr_description=Join selected 'if' statements with ||
-AdvancedQuickAssistProcessor_splitOrCondition_description=Split || condition
-AdvancedQuickAssistProcessor_exchangeOperands_description=Exchange left and right operands for infix expression
-
-AddTypeParameterProposal_method_label=Add type parameter ''{0}'' to ''{1}''
-AddTypeParameterProposal_type_label=Add type parameter ''{0}'' to ''{1}''
-
-FixCorrectionProposal_HitCtrlEnter_description='Ctrl+Enter' to fix all problems of same category in file
-FixCorrectionProposal_hitCtrlEnter_variable_description=''Ctrl+Enter'' to fix {0} problems of same category in file
-FixCorrectionProposal_WarningAdditionalProposalInfo=Warning:
-
-CorrectionMarkerResolutionGenerator_multiFixErrorDialog_description=A problem occurred while applying the quick fixes.
-
-SuppressWarningsSubProcessor_fix_suppress_token_label=Change to ''{0}''
-ModifierCorrectionSubProcessor_changefieldmodifiertononstatic_description=Remove ''static'' modifier of ''{0}''
-ModifierCorrectionSubProcessor_creategetterunsingencapsulatefield_description=Create getter using 'Encapsulate Field'
-ModifierCorrectionSubProcessor_createsetterusingencapsulatefield_description=Create setter using 'Encapsulate Field'
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/FixCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/FixCorrectionProposal.java
deleted file mode 100644
index dcf46dd5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/FixCorrectionProposal.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.fix.AbstractFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-/**
- * A correction proposal which uses an {@link IFix} to
- * fix a problem. A fix correction proposal may have an {@link ICleanUp}
- * attached which can be executed instead of the provided IFix.
- */
-public class FixCorrectionProposal extends LinkedCorrectionProposal implements ICompletionProposalExtension2, IStatusLineProposal {
-
- private final IFix fFix;
- private final ICleanUp fCleanUp;
- private JavaScriptUnit fCompilationUnit;
-
- public FixCorrectionProposal(IFix fix, ICleanUp cleanUp, int relevance, Image image, IInvocationContext context) {
- super(fix.getDescription(), fix.getCompilationUnit(), null, relevance, image);
- fFix= fix;
- fCleanUp= cleanUp;
- fCompilationUnit= context.getASTRoot();
- }
-
- public ICleanUp getCleanUp() {
- return fCleanUp;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeCorrectionProposal#getImage()
- */
- public Image getImage() {
- IStatus status= fFix.getStatus();
- if (!status.isOK()) {
- ImageImageDescriptor image= new ImageImageDescriptor(super.getImage());
-
- int flag= JavaScriptElementImageDescriptor.WARNING;
- if (status.getSeverity() == IStatus.ERROR) {
- flag= JavaScriptElementImageDescriptor.ERROR;
- }
-
- ImageDescriptor composite= new JavaScriptElementImageDescriptor(image, flag, new Point(image.getImageData().width, image.getImageData().height));
- return composite.createImage();
- } else {
- return super.getImage();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- String result= super.getAdditionalProposalInfo();
- IStatus status= fFix.getStatus();
- if (!status.isOK()) {
- StringBuffer buf= new StringBuffer();
- buf.append("<b>"); //$NON-NLS-1$
- buf.append(CorrectionMessages.FixCorrectionProposal_WarningAdditionalProposalInfo);
- buf.append("</b>"); //$NON-NLS-1$
- buf.append(status.getMessage());
- buf.append("<br><br>"); //$NON-NLS-1$
- buf.append(result);
- return buf.toString();
- } else {
- if (fFix instanceof AbstractFix) {
- AbstractFix af = (AbstractFix) fFix;
- String info = af.getAdditionalInfo();
- if (info != null) {
- StringBuffer sb=new StringBuffer();
- sb.append(info);
- sb.append("<br>"); //$NON-NLS-1$
- sb.append(result);
- return sb.toString();
- }
- }
- return result;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeCorrectionProposal#getRelevance()
- */
- public int getRelevance() {
- IStatus status= fFix.getStatus();
- if (status.getSeverity() == IStatus.WARNING) {
- return super.getRelevance() - 100;
- } else {
- return super.getRelevance();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#createTextChange()
- */
- protected TextChange createTextChange() throws CoreException {
- IFix fix= fFix;
- TextChange createChange= fix.createChange();
- if (createChange instanceof TextFileChange)
- ((TextFileChange)createChange).setSaveMode(TextFileChange.LEAVE_DIRTY);
-
- if (fix instanceof LinkedFix) {
- setLinkedProposalModel(((LinkedFix) fix).getLinkedPositions());
- }
-
- if (createChange == null)
- return new CompilationUnitChange("", getCompilationUnit()); //$NON-NLS-1$
-
- return createChange;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- if (stateMask == SWT.CONTROL && fCleanUp != null){
- CleanUpRefactoring refactoring= new CleanUpRefactoring();
- refactoring.addCompilationUnit(getCompilationUnit());
- refactoring.addCleanUp(fCleanUp);
- refactoring.setLeaveFilesDirty(true);
-
- int stopSeverity= RefactoringCore.getConditionCheckingFailedSeverity();
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- ProgressMonitorDialog context= new ProgressMonitorDialog(shell);
- RefactoringExecutionHelper executer= new RefactoringExecutionHelper(refactoring, stopSeverity, RefactoringSaveHelper.SAVE_NOTHING, shell, context);
- try {
- executer.perform(true, true);
- } catch (InterruptedException e) {
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- }
- return;
- }
- apply(viewer.getDocument());
- }
-
- public void selected(ITextViewer viewer, boolean smartToggle) {
- }
-
- public void unselected(ITextViewer viewer) {
- }
-
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getStatusMessage() {
- if (fCleanUp == null)
- return null;
-
- int count= fCleanUp.maximalNumberOfFixes(fCompilationUnit);
- if (count == -1) {
- return CorrectionMessages.FixCorrectionProposal_HitCtrlEnter_description;
- } else if (count < 2) {
- return ""; //$NON-NLS-1$
- } else {
- return Messages.format(CorrectionMessages.FixCorrectionProposal_hitCtrlEnter_variable_description, new Integer(count));
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ICommandAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ICommandAccess.java
deleted file mode 100644
index c0145884..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ICommandAccess.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-/**
- * Correction proposals implement this interface to by invokable by a command.
- * (e.g. keyboard shortcut)
- */
-public interface ICommandAccess {
-
- /**
- * Returns the id of the command that should invoke this correction proposal
- * @return the id of the command. This id must start with {@link CorrectionCommandInstaller#COMMAND_PREFIX}
- * to be recognixes as correction command.
- */
- String getCommandId();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/IStatusLineProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/IStatusLineProposal.java
deleted file mode 100644
index cbb4e78e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/IStatusLineProposal.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-/**
- * A proposal which is able to show a message
- * on the status line of the content assistant
- * in which this proposal is shown.
- *
- * @see org.eclipse.jface.text.contentassist.IContentAssistantExtension2
- */
-public interface IStatusLineProposal {
-
- /**
- * The message to show when this proposal is
- * selected by the user in the content assistant.
- *
- * @return The message to show, or null for no message.
- */
- public String getStatusMessage();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionAssistant.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionAssistant.java
deleted file mode 100644
index ad6f269a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionAssistant.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.quickassist.QuickAssistAssistant;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-
-
-public class JavaCorrectionAssistant extends QuickAssistAssistant {
-
- private ITextViewer fViewer;
- private ITextEditor fEditor;
- private Position fPosition;
- private Annotation[] fCurrentAnnotations;
-
- private QuickAssistLightBulbUpdater fLightBulbUpdater;
-
-
- /**
- * Constructor for JavaCorrectionAssistant.
- */
- public JavaCorrectionAssistant(ITextEditor editor) {
- super();
- Assert.isNotNull(editor);
- fEditor= editor;
-
- JavaCorrectionProcessor processor= new JavaCorrectionProcessor(this);
-
- setQuickAssistProcessor(processor);
-
- setInformationControlCreator(getInformationControlCreator());
-
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- IColorManager manager= textTools.getColorManager();
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- Color c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager);
- setProposalSelectorForeground(c);
-
- c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager);
- setProposalSelectorBackground(c);
- }
-
- public IEditorPart getEditor() {
- return fEditor;
- }
-
-
- private IInformationControlCreator getInformationControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, new HTMLTextPresenter());
- }
- };
- }
-
- private static Color getColor(IPreferenceStore store, String key, IColorManager manager) {
- RGB rgb= PreferenceConverter.getColor(store, key);
- return manager.getColor(rgb);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistant#install(org.eclipse.jface.text.ITextViewer)
- */
- public void install(ISourceViewer sourceViewer) {
- super.install(sourceViewer);
- fViewer= sourceViewer;
-
- fLightBulbUpdater= new QuickAssistLightBulbUpdater(fEditor, sourceViewer);
- fLightBulbUpdater.install();
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ContentAssistant#uninstall()
- */
- public void uninstall() {
- if (fLightBulbUpdater != null) {
- fLightBulbUpdater.uninstall();
- fLightBulbUpdater= null;
- }
- super.uninstall();
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.QuickAssistAssistant#showPossibleQuickAssists()
- *
- */
-
- /**
- * Show completions at caret position. If current
- * position does not contain quick fixes look for
- * next quick fix on same line by moving from left
- * to right and restarting at end of line if the
- * beginning of the line is reached.
- *
- * @see org.eclipse.jface.text.quickassist.IQuickAssistAssistant#showPossibleQuickAssists()
- */
- public String showPossibleQuickAssists() {
- fPosition= null;
- fCurrentAnnotations= null;
-
- if (fViewer == null || fViewer.getDocument() == null)
- // Let superclass deal with this
- return super.showPossibleQuickAssists();
-
-
- ArrayList resultingAnnotations= new ArrayList(20);
- try {
- Point selectedRange= fViewer.getSelectedRange();
- int currOffset= selectedRange.x;
- int currLength= selectedRange.y;
- boolean goToClosest= (currLength == 0);
-
- int newOffset= collectQuickFixableAnnotations(fEditor, currOffset, goToClosest, resultingAnnotations);
- if (newOffset != currOffset) {
- storePosition(currOffset, currLength);
- fViewer.setSelectedRange(newOffset, 0);
- fViewer.revealRange(newOffset, 0);
- }
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- fCurrentAnnotations= (Annotation[]) resultingAnnotations.toArray(new Annotation[resultingAnnotations.size()]);
-
- return super.showPossibleQuickAssists();
- }
-
-
- private static IRegion getRegionOfInterest(ITextEditor editor, int invocationLocation) throws BadLocationException {
- IDocumentProvider documentProvider= editor.getDocumentProvider();
- if (documentProvider == null) {
- return null;
- }
- IDocument document= documentProvider.getDocument(editor.getEditorInput());
- if (document == null) {
- return null;
- }
- return document.getLineInformationOfOffset(invocationLocation);
- }
-
- public static int collectQuickFixableAnnotations(ITextEditor editor, int invocationLocation, boolean goToClosest, ArrayList resultingAnnotations) throws BadLocationException {
- IAnnotationModel model= JavaScriptUI.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
- if (model == null) {
- return invocationLocation;
- }
-
- ensureUpdatedAnnotations(editor);
-
- Iterator iter= model.getAnnotationIterator();
- if (goToClosest) {
- IRegion lineInfo= getRegionOfInterest(editor, invocationLocation);
- if (lineInfo == null) {
- return invocationLocation;
- }
- int rangeStart= lineInfo.getOffset();
- int rangeEnd= rangeStart + lineInfo.getLength();
-
- ArrayList allAnnotations= new ArrayList();
- ArrayList allPositions= new ArrayList();
- int bestOffset= Integer.MAX_VALUE;
- while (iter.hasNext()) {
- Annotation annot= (Annotation) iter.next();
- if (JavaCorrectionProcessor.isQuickFixableType(annot)) {
- Position pos= model.getPosition(annot);
- if (pos != null && isInside(pos.offset, rangeStart, rangeEnd)) { // inside our range?
- allAnnotations.add(annot);
- allPositions.add(pos);
- bestOffset= processAnnotation(annot, pos, invocationLocation, bestOffset);
- }
- }
- }
- if (bestOffset == Integer.MAX_VALUE) {
- return invocationLocation;
- }
- for (int i= 0; i < allPositions.size(); i++) {
- Position pos= (Position) allPositions.get(i);
- if (isInside(bestOffset, pos.offset, pos.offset + pos.length)) {
- resultingAnnotations.add(allAnnotations.get(i));
- }
- }
- return bestOffset;
- } else {
- while (iter.hasNext()) {
- Annotation annot= (Annotation) iter.next();
- if (JavaCorrectionProcessor.isQuickFixableType(annot)) {
- Position pos= model.getPosition(annot);
- if (pos != null && isInside(invocationLocation, pos.offset, pos.offset + pos.length)) {
- resultingAnnotations.add(annot);
- }
- }
- }
- return invocationLocation;
- }
- }
-
- private static void ensureUpdatedAnnotations(ITextEditor editor) {
- Object inputElement= editor.getEditorInput().getAdapter(IJavaScriptElement.class);
- if (inputElement instanceof IJavaScriptUnit) {
- JavaScriptPlugin.getDefault().getASTProvider().getAST((IJavaScriptUnit) inputElement, ASTProvider.WAIT_ACTIVE_ONLY, null);
- }
- }
-
- private static int processAnnotation(Annotation annot, Position pos, int invocationLocation, int bestOffset) {
- int posBegin= pos.offset;
- int posEnd= posBegin + pos.length;
- if (isInside(invocationLocation, posBegin, posEnd)) { // covers invocation location?
- return invocationLocation;
- } else if (bestOffset != invocationLocation) {
- int newClosestPosition= computeBestOffset(posBegin, invocationLocation, bestOffset);
- if (newClosestPosition != -1) {
- if (newClosestPosition != bestOffset) { // new best
- if (JavaCorrectionProcessor.hasCorrections(annot)) { // only jump to it if there are proposals
- return newClosestPosition;
- }
- }
- }
- }
- return bestOffset;
- }
-
-
- private static boolean isInside(int offset, int start, int end) {
- return offset == start || offset == end || (offset > start && offset < end); // make sure to handle 0-length ranges
- }
-
- /**
- * Computes and returns the invocation offset given a new
- * position, the initial offset and the best invocation offset
- * found so far.
- * <p>
- * The closest offset to the left of the initial offset is the
- * best. If there is no offset on the left, the closest on the
- * right is the best.</p>
- * @return -1 is returned if the given offset is not closer or the new best offset
- */
- private static int computeBestOffset(int newOffset, int invocationLocation, int bestOffset) {
- if (newOffset <= invocationLocation) {
- if (bestOffset > invocationLocation) {
- return newOffset; // closest was on the right, prefer on the left
- } else if (bestOffset <= newOffset) {
- return newOffset; // we are closer or equal
- }
- return -1; // further away
- }
-
- if (newOffset <= bestOffset)
- return newOffset; // we are closer or equal
-
- return -1; // further away
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ContentAssistant#possibleCompletionsClosed()
- */
- protected void possibleCompletionsClosed() {
- super.possibleCompletionsClosed();
- restorePosition();
- }
-
- private void storePosition(int currOffset, int currLength) {
- fPosition= new Position(currOffset, currLength);
- }
-
- private void restorePosition() {
- if (fPosition != null && !fPosition.isDeleted() && fViewer.getDocument() != null) {
- fViewer.setSelectedRange(fPosition.offset, fPosition.length);
- fViewer.revealRange(fPosition.offset, fPosition.length);
- }
- fPosition= null;
- }
-
- /**
- * Returns true if the last invoked completion was called with an updated offset.
- */
- public boolean isUpdatedOffset() {
- return fPosition != null;
- }
-
- /**
- * Returns the annotations at the current offset
- */
- public Annotation[] getAnnotationsAtOffset() {
- return fCurrentAnnotations;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java
deleted file mode 100644
index 45c6a653..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.contentassist.ContentAssistEvent;
-import org.eclipse.jface.text.contentassist.ICompletionListener;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMarkerHelpRegistry;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickAssistProcessor;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickFixProcessor;
-
-
-public class JavaCorrectionProcessor implements org.eclipse.jface.text.quickassist.IQuickAssistProcessor {
-
- private static final String QUICKFIX_PROCESSOR_CONTRIBUTION_ID= "quickFixProcessors"; //$NON-NLS-1$
- private static final String QUICKASSIST_PROCESSOR_CONTRIBUTION_ID= "quickAssistProcessors"; //$NON-NLS-1$
- public static final int IQUICKFIXABLE_PROBLEM_ID = IProblem.Javadoc + IProblem.Internal + 1025;
-
- private static ContributedProcessorDescriptor[] fgContributedAssistProcessors= null;
- private static ContributedProcessorDescriptor[] fgContributedCorrectionProcessors= null;
-
- private static ContributedProcessorDescriptor[] getProcessorDescriptors(String contributionId, boolean testMarkerTypes) {
- IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(JavaScriptUI.ID_PLUGIN, contributionId);
- ArrayList res= new ArrayList(elements.length);
-
- for (int i= 0; i < elements.length; i++) {
- ContributedProcessorDescriptor desc= new ContributedProcessorDescriptor(elements[i], testMarkerTypes);
- IStatus status= desc.checkSyntax();
- if (status.isOK()) {
- res.add(desc);
- } else {
- JavaScriptPlugin.log(status);
- }
- }
- return (ContributedProcessorDescriptor[]) res.toArray(new ContributedProcessorDescriptor[res.size()]);
- }
-
- private static ContributedProcessorDescriptor[] getCorrectionProcessors() {
- if (fgContributedCorrectionProcessors == null) {
- fgContributedCorrectionProcessors= getProcessorDescriptors(QUICKFIX_PROCESSOR_CONTRIBUTION_ID, true);
- }
- return fgContributedCorrectionProcessors;
- }
-
- private static ContributedProcessorDescriptor[] getAssistProcessors() {
- if (fgContributedAssistProcessors == null) {
- fgContributedAssistProcessors= getProcessorDescriptors(QUICKASSIST_PROCESSOR_CONTRIBUTION_ID, false);
- }
- return fgContributedAssistProcessors;
- }
-
- public static boolean hasCorrections(IJavaScriptUnit cu, int problemId, String markerType) {
- ContributedProcessorDescriptor[] processors= getCorrectionProcessors();
- SafeHasCorrections collector= new SafeHasCorrections(cu, problemId);
- for (int i= 0; i < processors.length; i++) {
- if (processors[i].canHandleMarkerType(markerType)) {
- collector.process(processors[i]);
- if (collector.hasCorrections()) {
- return true;
- }
- }
- }
- return false;
- }
-
- public static boolean isQuickFixableType(Annotation annotation) {
- return (annotation instanceof IJavaAnnotation || annotation instanceof SimpleMarkerAnnotation || annotation instanceof IQuickFixableAnnotation) && !annotation.isMarkedDeleted();
- }
-
-
- public static boolean hasCorrections(Annotation annotation) {
- if (annotation instanceof IJavaAnnotation) {
- IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
- int problemId= javaAnnotation.getId();
- if (problemId != -1) {
- IJavaScriptUnit cu= javaAnnotation.getCompilationUnit();
- if (cu != null) {
- return hasCorrections(cu, problemId, javaAnnotation.getMarkerType());
- }
- }
- }
- if (annotation instanceof SimpleMarkerAnnotation) {
- return hasCorrections(((SimpleMarkerAnnotation) annotation).getMarker());
- }
- if (annotation instanceof IQuickFixableAnnotation) {
- return ((IQuickFixableAnnotation) annotation).isQuickFixableStateSet() && ((IQuickFixableAnnotation) annotation).isQuickFixable();
- }
- return false;
- }
-
- private static boolean hasCorrections(IMarker marker) {
- if (marker == null || !marker.exists())
- return false;
-
- IMarkerHelpRegistry registry= IDE.getMarkerHelpRegistry();
- return registry != null && registry.hasResolutions(marker);
- }
-
- public static boolean hasAssists(IInvocationContext context) {
- ContributedProcessorDescriptor[] processors= getAssistProcessors();
- SafeHasAssist collector= new SafeHasAssist(context);
-
- for (int i= 0; i < processors.length; i++) {
- collector.process(processors[i]);
- if (collector.hasAssists()) {
- return true;
- }
- }
- return false;
- }
-
- private JavaCorrectionAssistant fAssistant;
- private String fErrorMessage;
-
- /*
- * Constructor for JavaCorrectionProcessor.
- */
- public JavaCorrectionProcessor(JavaCorrectionAssistant assistant) {
- fAssistant= assistant;
- fAssistant.addCompletionListener(new ICompletionListener() {
-
- public void assistSessionEnded(ContentAssistEvent event) {
- fAssistant.setStatusLineVisible(false);
- }
-
- public void assistSessionStarted(ContentAssistEvent event) {
- fAssistant.setStatusLineVisible(true);
- }
-
- public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) {
- if (proposal instanceof IStatusLineProposal) {
- IStatusLineProposal statusLineProposal= (IStatusLineProposal)proposal;
- String message= statusLineProposal.getStatusMessage();
- if (message != null) {
- fAssistant.setStatusMessage(message);
- } else {
- fAssistant.setStatusMessage(""); //$NON-NLS-1$
- }
- } else {
- fAssistant.setStatusMessage(""); //$NON-NLS-1$
- }
- }
- });
- }
-
- /*
- * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
- */
- public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext quickAssistContext) {
- ITextViewer viewer= quickAssistContext.getSourceViewer();
- int documentOffset= quickAssistContext.getOffset();
-
- IEditorPart part= fAssistant.getEditor();
-
- IJavaScriptUnit cu= JavaScriptUI.getWorkingCopyManager().getWorkingCopy(part.getEditorInput());
- IAnnotationModel model= JavaScriptUI.getDocumentProvider().getAnnotationModel(part.getEditorInput());
-
- int length= viewer != null ? viewer.getSelectedRange().y : 0;
- AssistContext context= new AssistContext(cu, documentOffset, length);
-
- Annotation[] annotations= fAssistant.getAnnotationsAtOffset();
-
- fErrorMessage= null;
-
- ICompletionProposal[] res= null;
- if (model != null && annotations != null) {
- ArrayList proposals= new ArrayList(10);
- IStatus status= collectProposals(context, model, annotations, true, !fAssistant.isUpdatedOffset(), proposals);
- res= (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- if (!status.isOK()) {
- fErrorMessage= status.getMessage();
- JavaScriptPlugin.log(status);
- }
- }
-
- if (res == null || res.length == 0) {
- return new ICompletionProposal[] { new ChangeCorrectionProposal(CorrectionMessages.NoCorrectionProposal_description, new NullChange(""), 0, null) }; //$NON-NLS-1$
- }
- if (res.length > 1) {
- Arrays.sort(res, new CompletionProposalComparator());
- }
- return res;
- }
-
- public static IStatus collectProposals(IInvocationContext context, IAnnotationModel model, Annotation[] annotations, boolean addQuickFixes, boolean addQuickAssists, Collection proposals) {
- ArrayList problems= new ArrayList();
-
- // collect problem locations and corrections from marker annotations
- for (int i= 0; i < annotations.length; i++) {
- Annotation curr= annotations[i];
- if (curr instanceof IJavaAnnotation) {
- ProblemLocation problemLocation= getProblemLocation((IJavaAnnotation) curr, model);
- if (problemLocation != null) {
- problems.add(problemLocation);
- }
- } else if (addQuickFixes && curr instanceof SimpleMarkerAnnotation) {
- // don't collect if annotation is already a java annotation
- collectMarkerProposals((SimpleMarkerAnnotation) curr, proposals);
- } else if(curr instanceof IQuickFixableAnnotation) {
- IProblemLocation problemLocation= getProblemLocation(curr, model);
- if (problemLocation != null) {
- problems.add(problemLocation);
- }
- }
- }
- MultiStatus resStatus= null;
-
- IProblemLocation[] problemLocations= (IProblemLocation[]) problems.toArray(new IProblemLocation[problems.size()]);
- if (addQuickFixes) {
- IStatus status= collectCorrections(context, problemLocations, proposals);
- if (!status.isOK()) {
- resStatus= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.ERROR, CorrectionMessages.JavaCorrectionProcessor_error_quickfix_message, null);
- resStatus.add(status);
- }
- }
- if (addQuickAssists) {
- IStatus status= collectAssists(context, problemLocations, proposals);
- if (!status.isOK()) {
- if (resStatus == null) {
- resStatus= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.ERROR, CorrectionMessages.JavaCorrectionProcessor_error_quickassist_message, null);
- }
- resStatus.add(status);
- }
- }
- if (resStatus != null) {
- return resStatus;
- }
- return Status.OK_STATUS;
- }
-
- private static ProblemLocation getProblemLocation(IJavaAnnotation javaAnnotation, IAnnotationModel model) {
- int problemId= javaAnnotation.getId();
- if (problemId != -1) {
- Position pos= model.getPosition((Annotation) javaAnnotation);
- if (pos != null) {
- return new ProblemLocation(pos.getOffset(), pos.getLength(), javaAnnotation); // java problems all handled by the quick assist processors
- }
- }
- return null;
- }
-
- private static IProblemLocation getProblemLocation(Annotation annotation, IAnnotationModel model) {
- Position pos= model.getPosition(annotation);
- if(pos != null)
- return new ProblemLocation(pos.getOffset(), pos.getLength(), IQUICKFIXABLE_PROBLEM_ID, new String[]{annotation.getText()}, false, annotation.getType());
- return null;
- }
-
- private static void collectMarkerProposals(SimpleMarkerAnnotation annotation, Collection proposals) {
- IMarker marker= annotation.getMarker();
- IMarkerResolution[] res= IDE.getMarkerHelpRegistry().getResolutions(marker);
- if (res.length > 0) {
- for (int i= 0; i < res.length; i++) {
- proposals.add(new MarkerResolutionProposal(res[i], marker));
- }
- }
- }
-
- private static abstract class SafeCorrectionProcessorAccess implements ISafeRunnable {
- private MultiStatus fMulti= null;
- private ContributedProcessorDescriptor fDescriptor;
-
- public void process(ContributedProcessorDescriptor[] desc) {
- for (int i= 0; i < desc.length; i++) {
- fDescriptor= desc[i];
- SafeRunner.run(this);
- }
- }
-
- public void process(ContributedProcessorDescriptor desc) {
- fDescriptor= desc;
- SafeRunner.run(this);
- }
-
- public void run() throws Exception {
- safeRun(fDescriptor);
- }
-
- protected abstract void safeRun(ContributedProcessorDescriptor processor) throws Exception;
-
- public void handleException(Throwable exception) {
- if (fMulti == null) {
- fMulti= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, CorrectionMessages.JavaCorrectionProcessor_error_status, null);
- }
- fMulti.merge(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, CorrectionMessages.JavaCorrectionProcessor_error_status, exception));
- }
-
- public IStatus getStatus() {
- if (fMulti == null) {
- return Status.OK_STATUS;
- }
- return fMulti;
- }
-
- }
-
- private static class SafeCorrectionCollector extends SafeCorrectionProcessorAccess {
- private final IInvocationContext fContext;
- private final Collection fProposals;
- private IProblemLocation[] fLocations;
-
- public SafeCorrectionCollector(IInvocationContext context, Collection proposals) {
- fContext= context;
- fProposals= proposals;
- }
-
- public void setProblemLocations(IProblemLocation[] locations) {
- fLocations= locations;
- }
-
- public void safeRun(ContributedProcessorDescriptor desc) throws Exception {
- IQuickFixProcessor curr= (IQuickFixProcessor) desc.getProcessor(fContext.getCompilationUnit());
- if (curr != null) {
- IJavaCompletionProposal[] res= curr.getCorrections(fContext, fLocations);
- if (res != null) {
- for (int k= 0; k < res.length; k++) {
- fProposals.add(res[k]);
- }
- }
- }
- }
- }
-
- private static class SafeAssistCollector extends SafeCorrectionProcessorAccess {
- private final IInvocationContext fContext;
- private final IProblemLocation[] fLocations;
- private final Collection fProposals;
-
- public SafeAssistCollector(IInvocationContext context, IProblemLocation[] locations, Collection proposals) {
- fContext= context;
- fLocations= locations;
- fProposals= proposals;
- }
-
- public void safeRun(ContributedProcessorDescriptor desc) throws Exception {
- IQuickAssistProcessor curr= (IQuickAssistProcessor) desc.getProcessor(fContext.getCompilationUnit());
- if (curr != null) {
- IJavaCompletionProposal[] res= curr.getAssists(fContext, fLocations);
- if (res != null) {
- for (int k= 0; k < res.length; k++) {
- fProposals.add(res[k]);
- }
- }
- }
- }
- }
-
- private static class SafeHasAssist extends SafeCorrectionProcessorAccess {
- private final IInvocationContext fContext;
- private boolean fHasAssists;
-
- public SafeHasAssist(IInvocationContext context) {
- fContext= context;
- fHasAssists= false;
- }
-
- public boolean hasAssists() {
- return fHasAssists;
- }
-
- public void safeRun(ContributedProcessorDescriptor desc) throws Exception {
- IQuickAssistProcessor processor= (IQuickAssistProcessor) desc.getProcessor(fContext.getCompilationUnit());
- if (processor != null && processor.hasAssists(fContext)) {
- fHasAssists= true;
- }
- }
- }
-
- private static class SafeHasCorrections extends SafeCorrectionProcessorAccess {
- private final IJavaScriptUnit fCu;
- private final int fProblemId;
- private boolean fHasCorrections;
-
- public SafeHasCorrections(IJavaScriptUnit cu, int problemId) {
- fCu= cu;
- fProblemId= problemId;
- fHasCorrections= false;
- }
-
- public boolean hasCorrections() {
- return fHasCorrections;
- }
-
- public void safeRun(ContributedProcessorDescriptor desc) throws Exception {
- IQuickFixProcessor processor= (IQuickFixProcessor) desc.getProcessor(fCu);
- if (processor != null && processor.hasCorrections(fCu, fProblemId)) {
- fHasCorrections= true;
- }
- }
- }
-
-
- public static IStatus collectCorrections(IInvocationContext context, IProblemLocation[] locations, Collection proposals) {
- ContributedProcessorDescriptor[] processors= getCorrectionProcessors();
- SafeCorrectionCollector collector= new SafeCorrectionCollector(context, proposals);
- for (int i= 0; i < processors.length; i++) {
- ContributedProcessorDescriptor curr= processors[i];
- IProblemLocation[] handled= getHandledProblems(locations, curr);
- if (handled != null) {
- collector.setProblemLocations(handled);
- collector.process(curr);
- }
- }
- return collector.getStatus();
- }
-
- private static IProblemLocation[] getHandledProblems(IProblemLocation[] locations, ContributedProcessorDescriptor processor) {
- // implementation tries to avoid creating a new array
- boolean allHandled= true;
- ArrayList res= null;
- for (int i= 0; i < locations.length; i++) {
- IProblemLocation curr= locations[i];
- if (processor.canHandleMarkerType(curr.getMarkerType())) {
- if (!allHandled) { // first handled problem
- if (res == null) {
- res= new ArrayList(locations.length - i);
- }
- res.add(curr);
- }
- } else if (allHandled) {
- if (i > 0) { // first non handled problem
- res= new ArrayList(locations.length - i);
- for (int k= 0; k < i; k++) {
- res.add(locations[k]);
- }
- }
- allHandled= false;
- }
- }
- if (allHandled) {
- return locations;
- }
- if (res == null) {
- return null;
- }
- return (IProblemLocation[]) res.toArray(new IProblemLocation[res.size()]);
- }
-
- public static IStatus collectAssists(IInvocationContext context, IProblemLocation[] locations, Collection proposals) {
- ContributedProcessorDescriptor[] processors= getAssistProcessors();
- SafeAssistCollector collector= new SafeAssistCollector(context, locations, proposals);
- collector.process(processors);
-
- return collector.getStatus();
- }
-
- /*
- * @see IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#canFix(org.eclipse.jface.text.source.Annotation)
- *
- */
- public boolean canFix(Annotation annotation) {
- return hasCorrections(annotation);
- }
-
- /*
- * @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#canAssist(org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext)
- *
- */
- public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
- if (invocationContext instanceof IInvocationContext)
- return hasAssists((IInvocationContext)invocationContext);
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavadocTagsSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavadocTagsSubProcessor.java
deleted file mode 100644
index b8d39bff..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavadocTagsSubProcessor.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- *
- */
-public class JavadocTagsSubProcessor {
-
- private static final class AddJavadocCommentProposal extends CUCorrectionProposal {
-
- private final int fInsertPosition;
- private final String fComment;
-
- private AddJavadocCommentProposal(String name, IJavaScriptUnit cu, int relevance, int insertPosition, String comment) {
- super(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG));
- fInsertPosition= insertPosition;
- fComment= comment;
- }
-
- protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
- try {
- String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document);
- final IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- IRegion region= document.getLineInformationOfOffset(fInsertPosition);
-
- String lineContent= document.get(region.getOffset(), region.getLength());
- String indentString= Strings.getIndentString(lineContent, project);
- String str= Strings.changeIndent(fComment, 0, project, indentString, lineDelimiter);
- InsertEdit edit= new InsertEdit(fInsertPosition, str);
- rootEdit.addChild(edit);
- if (fComment.charAt(fComment.length() - 1) != '\n') {
- rootEdit.addChild(new InsertEdit(fInsertPosition, lineDelimiter));
- rootEdit.addChild(new InsertEdit(fInsertPosition, indentString));
- }
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
- }
-
- private static final class AddMissingJavadocTagProposal extends LinkedCorrectionProposal {
-
- private final BodyDeclaration fBodyDecl; // MethodDecl or TypeDecl
- private final ASTNode fMissingNode;
-
- public AddMissingJavadocTagProposal(String label, IJavaScriptUnit cu, BodyDeclaration methodDecl, ASTNode missingNode, int relevance) {
- super(label, cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG));
- fBodyDecl= methodDecl;
- fMissingNode= missingNode;
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- AST ast= fBodyDecl.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- insertMissingJavadocTag(rewrite, fMissingNode, fBodyDecl);
- return rewrite;
- }
-
- private void insertMissingJavadocTag(ASTRewrite rewrite, ASTNode missingNode, BodyDeclaration bodyDecl) {
- AST ast= bodyDecl.getAST();
- JSdoc javadoc= bodyDecl.getJavadoc();
- ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY);
-
- StructuralPropertyDescriptor location= missingNode.getLocationInParent();
- TagElement newTag;
- if (location == SingleVariableDeclaration.NAME_PROPERTY) {
- // normal parameter
- SingleVariableDeclaration decl= (SingleVariableDeclaration) missingNode.getParent();
-
- String name= ((SimpleName) missingNode).getIdentifier();
- newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_PARAM);
- List fragments= newTag.fragments();
- fragments.add(ast.newSimpleName(name));
-
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) bodyDecl;
- List params= methodDeclaration.parameters();
-
- Set sameKindLeadingNames= getPreviousParamNames(params, decl);
-
- insertTag(tagsRewriter, newTag, sameKindLeadingNames);
- } else if (location == FunctionDeclaration.RETURN_TYPE2_PROPERTY) {
- newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_RETURN);
- insertTag(tagsRewriter, newTag, null);
- } else if (location == FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY) {
- newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_THROWS);
- TextElement excNode= ast.newTextElement();
- excNode.setText(ASTNodes.asString(missingNode));
- newTag.fragments().add(excNode);
- List exceptions= ((FunctionDeclaration) bodyDecl).thrownExceptions();
- insertTag(tagsRewriter, newTag, getPreviousExceptionNames(exceptions, missingNode));
- } else {
- Assert.isTrue(false, "AddMissingJavadocTagProposal: unexpected node location"); //$NON-NLS-1$
- return;
- }
-
- TextElement textElement= ast.newTextElement();
- textElement.setText(""); //$NON-NLS-1$
- newTag.fragments().add(textElement);
- addLinkedPosition(rewrite.track(textElement), false, "comment_start"); //$NON-NLS-1$
- }
- }
-
- private static final class AddAllMissingJavadocTagsProposal extends LinkedCorrectionProposal {
-
- private final BodyDeclaration fBodyDecl;
-
- public AddAllMissingJavadocTagsProposal(String label, IJavaScriptUnit cu, BodyDeclaration bodyDecl, int relevance) {
- super(label, cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG));
- fBodyDecl= bodyDecl;
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- ASTRewrite rewrite= ASTRewrite.create(fBodyDecl.getAST());
- if (fBodyDecl instanceof FunctionDeclaration) {
- insertAllMissingMethodTags(rewrite, (FunctionDeclaration) fBodyDecl);
- } else {
- insertAllMissingTypeTags(rewrite, (TypeDeclaration) fBodyDecl);
- }
- return rewrite;
- }
-
- private void insertAllMissingMethodTags(ASTRewrite rewriter, FunctionDeclaration methodDecl) {
- AST ast= methodDecl.getAST();
- JSdoc javadoc= methodDecl.getJavadoc();
- ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY);
-
- List typeParamNames= new ArrayList();
- List params= methodDecl.parameters();
- for (int i= params.size() - 1; i >= 0 ; i--) {
- SingleVariableDeclaration decl= (SingleVariableDeclaration) params.get(i);
- String name= decl.getName().getIdentifier();
- if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) {
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_PARAM);
- newTag.fragments().add(ast.newSimpleName(name));
- insertTabStop(rewriter, newTag.fragments(), "methParam" + i); //$NON-NLS-1$
- Set sameKindLeadingNames= getPreviousParamNames(params, decl);
- sameKindLeadingNames.addAll(typeParamNames);
- insertTag(tagsRewriter, newTag, sameKindLeadingNames);
- }
- }
- if (!methodDecl.isConstructor()) {
- Type type= methodDecl.getReturnType2();
- if (!type.isPrimitiveType() || (((PrimitiveType) type).getPrimitiveTypeCode() != PrimitiveType.VOID)) {
- if (findTag(javadoc, TagElement.TAG_RETURN, null) == null) {
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_RETURN);
- insertTabStop(rewriter, newTag.fragments(), "return"); //$NON-NLS-1$
- insertTag(tagsRewriter, newTag, null);
- }
- }
- }
- List thrownExceptions= methodDecl.thrownExceptions();
- for (int i= thrownExceptions.size() - 1; i >= 0 ; i--) {
- Name exception= (Name) thrownExceptions.get(i);
- ITypeBinding binding= exception.resolveTypeBinding();
- if (binding != null) {
- String name= binding.getName();
- if (findThrowsTag(javadoc, name) == null) {
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_THROWS);
- TextElement excNode= ast.newTextElement();
- excNode.setText(ASTNodes.asString(exception));
- newTag.fragments().add(excNode);
- insertTabStop(rewriter, newTag.fragments(), "exception" + i); //$NON-NLS-1$
- insertTag(tagsRewriter, newTag, getPreviousExceptionNames(thrownExceptions, exception));
- }
- }
- }
- }
-
- private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) {
- AST ast= typeDecl.getAST();
- JSdoc javadoc= typeDecl.getJavadoc();
- ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY);
- }
-
- private void insertTabStop(ASTRewrite rewriter, List fragments, String linkedName) {
- TextElement textElement= rewriter.getAST().newTextElement();
- textElement.setText(""); //$NON-NLS-1$
- fragments.add(textElement);
- addLinkedPosition(rewriter.track(textElement), false, linkedName);
- }
-
- }
-
- public static void getMissingJavadocTagProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode node= problem.getCoveringNode(context.getASTRoot());
- if (node == null) {
- return;
- }
- node= ASTNodes.getNormalizedNode(node);
-
- BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
- if (bodyDeclaration == null) {
- return;
- }
- JSdoc javadoc= bodyDeclaration.getJavadoc();
- if (javadoc == null) {
- return;
- }
-
- String label;
- StructuralPropertyDescriptor location= node.getLocationInParent();
- if (location == SingleVariableDeclaration.NAME_PROPERTY) {
- label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_paramtag_description;
- if (node.getParent().getLocationInParent() != FunctionDeclaration.PARAMETERS_PROPERTY) {
- return; // paranoia checks
- }
- } else if (location == FunctionDeclaration.RETURN_TYPE2_PROPERTY) {
- label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_returntag_description;
- } else if (location == FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY) {
- label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_throwstag_description;
- } else {
- return;
- }
- ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDeclaration, node, 1);
- proposals.add(proposal);
-
- String label2= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_allmissing_description;
- ASTRewriteCorrectionProposal addAllMissing= new AddAllMissingJavadocTagsProposal(label2, context.getCompilationUnit(), bodyDeclaration, 5);
- proposals.add(addAllMissing);
- }
-
- public static void getMissingJavadocCommentProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- ASTNode node= problem.getCoveringNode(context.getASTRoot());
- if (node == null) {
- return;
- }
- BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node);
- if (declaration == null) {
- return;
- }
- IJavaScriptUnit cu= context.getCompilationUnit();
- ITypeBinding binding= Bindings.getBindingOfParentType(declaration);
- if (binding == null) {
- return;
- }
-
- if (declaration instanceof FunctionDeclaration) {
- FunctionDeclaration methodDecl= (FunctionDeclaration) declaration;
- IFunctionBinding methodBinding= methodDecl.resolveBinding();
- IFunctionBinding overridden= null;
- if (methodBinding != null) {
- overridden= Bindings.findOverriddenMethod(methodBinding, true);
- }
-
- String string= CodeGeneration.getMethodComment(cu, binding.getName(), methodDecl, overridden, String.valueOf('\n'));
- if (string != null) {
- String label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_method_description;
- proposals.add(new AddJavadocCommentProposal(label, cu, 1, declaration.getStartPosition(), string));
- }
- } else if (declaration instanceof AbstractTypeDeclaration) {
- String typeQualifiedName= Bindings.getTypeQualifiedName(binding);
-
- String string= CodeGeneration.getTypeComment(cu, typeQualifiedName, String.valueOf('\n'));
- if (string != null) {
- String label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_type_description;
- proposals.add(new AddJavadocCommentProposal(label, cu, 1, declaration.getStartPosition(), string));
- }
- } else if (declaration instanceof FieldDeclaration) {
- String comment= "/**\n *\n */\n"; //$NON-NLS-1$
- List fragments= ((FieldDeclaration)declaration).fragments();
- if (fragments != null && fragments.size() > 0) {
- VariableDeclaration decl= (VariableDeclaration)fragments.get(0);
- String fieldName= decl.getName().getIdentifier();
- String typeName= binding.getName();
- comment= CodeGeneration.getFieldComment(cu, typeName, fieldName, String.valueOf('\n'));
- }
- if (comment != null) {
- String label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_field_description;
- proposals.add(new AddJavadocCommentProposal(label, cu, 1, declaration.getStartPosition(), comment));
- }
- }
- }
-
- private static Set getPreviousParamNames(List params, ASTNode missingNode) {
- Set previousNames= new HashSet();
- for (int i = 0; i < params.size(); i++) {
- SingleVariableDeclaration curr= (SingleVariableDeclaration) params.get(i);
- if (curr == missingNode) {
- return previousNames;
- }
- previousNames.add(curr.getName().getIdentifier());
- }
- return previousNames;
- }
-
- private static Set getPreviousExceptionNames(List list, ASTNode missingNode) {
- Set previousNames= new HashSet();
- for (int i= 0; i < list.size() && missingNode != list.get(i); i++) {
- Name curr= (Name) list.get(i);
- previousNames.add(ASTNodes.getSimpleNameIdentifier(curr));
- }
- return previousNames;
- }
-
- public static TagElement findTag(JSdoc javadoc, String name, String arg) {
- List tags= javadoc.tags();
- int nTags= tags.size();
- for (int i= 0; i < nTags; i++) {
- TagElement curr= (TagElement) tags.get(i);
- if (name.equals(curr.getTagName())) {
- if (arg != null) {
- String argument= getArgument(curr);
- if (arg.equals(argument)) {
- return curr;
- }
- } else {
- return curr;
- }
- }
- }
- return null;
- }
-
- public static TagElement findParamTag(JSdoc javadoc, String arg) {
- List tags= javadoc.tags();
- int nTags= tags.size();
- for (int i= 0; i < nTags; i++) {
- TagElement curr= (TagElement) tags.get(i);
- String currName= curr.getTagName();
- if (TagElement.TAG_PARAM.equals(currName)) {
- String argument= getArgument(curr);
- if (arg.equals(argument)) {
- return curr;
- }
- }
- }
- return null;
- }
-
-
- public static TagElement findThrowsTag(JSdoc javadoc, String arg) {
- List tags= javadoc.tags();
- int nTags= tags.size();
- for (int i= 0; i < nTags; i++) {
- TagElement curr= (TagElement) tags.get(i);
- String currName= curr.getTagName();
- if (TagElement.TAG_THROWS.equals(currName) || TagElement.TAG_EXCEPTION.equals(currName)) {
- String argument= getArgument(curr);
- if (arg.equals(argument)) {
- return curr;
- }
- }
- }
- return null;
- }
-
- public static void insertTag(ListRewrite rewriter, TagElement newElement, Set sameKindLeadingNames) {
- insertTag(rewriter, newElement, sameKindLeadingNames, null);
- }
-
- public static void insertTag(ListRewrite rewriter, TagElement newElement, Set sameKindLeadingNames, TextEditGroup groupDescription) {
- List tags= rewriter.getRewrittenList();
-
- String insertedTagName= newElement.getTagName();
-
- ASTNode after= null;
- int tagRanking= getTagRanking(insertedTagName);
- for (int i= tags.size() - 1; i >= 0; i--) {
- TagElement curr= (TagElement) tags.get(i);
- String tagName= curr.getTagName();
- if (tagName == null || tagRanking > getTagRanking(tagName)) {
- after= curr;
- break;
- }
- if (sameKindLeadingNames != null && isSameTag(insertedTagName, tagName)) {
- String arg= getArgument(curr);
- if (arg != null && sameKindLeadingNames.contains(arg)) {
- after= curr;
- break;
- }
- }
- }
- if (after != null) {
- rewriter.insertAfter(newElement, after, groupDescription);
- } else {
- rewriter.insertFirst(newElement, groupDescription);
- }
- }
-
- private static boolean isSameTag(String insertedTagName, String tagName) {
- if (insertedTagName.equals(tagName)) {
- return true;
- }
- if (TagElement.TAG_EXCEPTION.equals(tagName)) {
- return TagElement.TAG_THROWS.equals(insertedTagName);
- }
- return false;
- }
-
- private static String[] TAG_ORDER= { // see http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#orderoftags
- TagElement.TAG_AUTHOR,
- TagElement.TAG_VERSION,
- TagElement.TAG_PARAM,
- TagElement.TAG_RETURN,
- TagElement.TAG_THROWS, // synonym to TAG_EXCEPTION
- TagElement.TAG_SEE,
- TagElement.TAG_SINCE,
- TagElement.TAG_SERIAL,
- TagElement.TAG_DEPRECATED
- };
-
- private static int getTagRanking(String tagName) {
- if (tagName.equals(TagElement.TAG_EXCEPTION)) {
- tagName= TagElement.TAG_THROWS;
- }
- for (int i= 0; i < TAG_ORDER.length; i++) {
- if (tagName.equals(TAG_ORDER[i])) {
- return i;
- }
- }
- return TAG_ORDER.length;
- }
-
- private static String getArgument(TagElement curr) {
- List fragments= curr.fragments();
- if (!fragments.isEmpty()) {
- Object first= fragments.get(0);
- if (first instanceof Name) {
- return ASTNodes.getSimpleNameIdentifier((Name) first);
- } else if (first instanceof TextElement && TagElement.TAG_PARAM.equals(curr.getTagName())) {
- String text= ((TextElement) first).getText();
- if ("<".equals(text) && fragments.size() >= 3) { //$NON-NLS-1$
- Object second= fragments.get(1);
- Object third= fragments.get(2);
- if (second instanceof Name && third instanceof TextElement && ">".equals(((TextElement) third).getText())) { //$NON-NLS-1$
- return '<' + ASTNodes.getSimpleNameIdentifier((Name) second) + '>';
- }
- } else if (text.startsWith(String.valueOf('<')) && text.endsWith(String.valueOf('>')) && text.length() > 2) {
- return text.substring(1, text.length() - 1);
- }
- }
- }
- return null;
- }
-
- public static void getRemoveJavadocTagProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode node= problem.getCoveringNode(context.getASTRoot());
- while (node != null && !(node instanceof TagElement)) {
- node= node.getParent();
- }
- if (node == null) {
- return;
- }
- ASTRewrite rewrite= ASTRewrite.create(node.getAST());
- rewrite.remove(node, null);
-
- String label= CorrectionMessages.JavadocTagsSubProcessor_removetag_description;
- Image image= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
- proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedCorrectionProposal.java
deleted file mode 100644
index 9a4afb7e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedCorrectionProposal.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-
-/**
- * A proposal for quick fixes and quick assists that works on a AST rewriter and enters the
- * linked mode when the proposal is set up.
- * Either a rewriter is directly passed in the constructor or method {@link #getRewrite()} is overridden
- * to provide the AST rewriter that is evaluated to the document when the proposal is
- * applied.
- *
- */
-public class LinkedCorrectionProposal extends ASTRewriteCorrectionProposal {
-
- /**
- * Constructs a linked correction proposal.
- * @param name The display name of the proposal.
- * @param cu The compilation unit that is modified.
- * @param rewrite The AST rewrite that is invoked when the proposal is applied
- * <code>null</code> can be passed if {@link #getRewrite()} is overridden.
- * @param relevance The relevance of this proposal.
- * @param image The image that is displayed for this proposal or <code>null</code> if no
- * image is desired.
- */
- public LinkedCorrectionProposal(String name, IJavaScriptUnit cu, ASTRewrite rewrite, int relevance, Image image) {
- super(name, cu, rewrite, relevance, image);
- }
-
- /**
- * Adds a linked position to be shown when the proposal is applied. All position with the
- * same group id are linked.
- * @param position The position to add.
- * @param isFirst If set, the proposal is jumped to first.
- * @param groupID The id of the group the proposal belongs to. All proposals in the same group
- * are linked.
- */
- public void addLinkedPosition(ITrackedNodePosition position, boolean isFirst, String groupID) {
- getLinkedProposalModel().getPositionGroup(groupID, true).addPosition(position, isFirst);
- }
-
- /**
- * Sets the end position of the linked mode to the end of the passed range.
- * @param position The position that describes the end position of the linked mode.
- */
- public void setEndPosition(ITrackedNodePosition position) {
- getLinkedProposalModel().setEndPosition(position);
- }
-
- /**
- * Adds a linked position proposal to the group with the given id.
- * @param groupID The id of the group that should present the proposal
- * @param proposal The string to propose.
- * @param image The image to show for the position proposal or <code>null</code> if
- * no image is desired.
- */
- public void addLinkedPositionProposal(String groupID, String proposal, Image image) {
- getLinkedProposalModel().getPositionGroup(groupID, true).addProposal(proposal, image, 10);
- }
-
- /**
- * Adds a linked position proposal to the group with the given id.
- * @param groupID The id of the group that should present the proposal
- * @param displayString The name of the proposal
- * @param proposal The string to insert.
- * @param image The image to show for the position proposal or <code>null</code> if
- * no image is desired.
- * @deprecated use {@link #addLinkedPositionProposal(String, String, Image)} instead
- */
- public void addLinkedPositionProposal(String groupID, String displayString, String proposal, Image image) {
- addLinkedPositionProposal(groupID, proposal, image);
- }
-
- /**
- * Adds a linked position proposal to the group with the given id.
- * @param groupID The id of the group that should present the proposal
- * @param type The binding to use as type name proposal.
- */
- public void addLinkedPositionProposal(String groupID, ITypeBinding type) {
- getLinkedProposalModel().getPositionGroup(groupID, true).addProposal(type, getCompilationUnit(), 10);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedNamesAssistProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedNamesAssistProposal.java
deleted file mode 100644
index fbba6fb6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LinkedNamesAssistProposal.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Arrays;
-import java.util.Comparator;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
-import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-/**
- * A template proposal.
- */
-public class LinkedNamesAssistProposal implements IJavaCompletionProposal, ICompletionProposalExtension2, ICommandAccess {
-
- /**
- * An exit policy that skips Backspace and Delete at the beginning and at the end
- * of a linked position, respectively.
- *
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=183925 .
- */
- public static class DeleteBlockingExitPolicy implements IExitPolicy {
- private IDocument fDocument;
-
- public DeleteBlockingExitPolicy(IDocument document) {
- fDocument= document;
- }
-
- public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) {
- if (length == 0 && (event.character == SWT.BS || event.character == SWT.DEL)) {
- LinkedPosition position= model.findPosition(new LinkedPosition(fDocument, offset, 0, LinkedPositionGroup.NO_STOP));
- if (position != null) {
- if (event.character == SWT.BS) {
- if (offset - 1 < position.getOffset()) {
- //skip backspace at beginning of linked position
- event.doit= false;
- }
- } else /* event.character == SWT.DEL */ {
- if (offset + 1 > position.getOffset() + position.getLength()) {
- //skip delete at end of linked position
- event.doit= false;
- }
- }
- }
- }
-
- return null; // don't change behavior
- }
- }
-
-
- public static final String ASSIST_ID= "org.eclipse.wst.jsdt.ui.correction.renameInFile.assist"; //$NON-NLS-1$
-
- private SimpleName fNode;
- private IJavaScriptUnit fCompilationUnit;
- private String fLabel;
- private String fValueSuggestion;
- private int fRelevance;
-
- public LinkedNamesAssistProposal(IJavaScriptUnit cu, SimpleName node) {
- this(CorrectionMessages.LinkedNamesAssistProposal_description, cu, node, null);
- fNode= node;
- fCompilationUnit= cu;
- fRelevance= 8;
- }
-
- public LinkedNamesAssistProposal(String label, IJavaScriptUnit cu, SimpleName node, String valueSuggestion) {
- fLabel= label;
- fNode= node;
- fCompilationUnit= cu;
- fValueSuggestion= valueSuggestion;
- fRelevance= 8;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- try {
- Point seletion= viewer.getSelectedRange();
-
- // get full ast
- JavaScriptUnit root= JavaScriptPlugin.getDefault().getASTProvider().getAST(fCompilationUnit, ASTProvider.WAIT_YES, null);
-
- ASTNode nameNode= NodeFinder.perform(root, fNode.getStartPosition(), fNode.getLength());
- final int pos= fNode.getStartPosition();
-
- ASTNode[] sameNodes;
- if (nameNode instanceof SimpleName) {
- sameNodes= LinkedNodeFinder.findByNode(root, (SimpleName) nameNode);
- } else {
- sameNodes= new ASTNode[] { nameNode };
- }
-
- // sort for iteration order, starting with the node @ offset
- Arrays.sort(sameNodes, new Comparator() {
-
- public int compare(Object o1, Object o2) {
- return rank((ASTNode) o1) - rank((ASTNode) o2);
- }
-
- /**
- * Returns the absolute rank of an <code>ASTNode</code>. Nodes
- * preceding <code>offset</code> are ranked last.
- *
- * @param node the node to compute the rank for
- * @return the rank of the node with respect to the invocation offset
- */
- private int rank(ASTNode node) {
- int relativeRank= node.getStartPosition() + node.getLength() - pos;
- if (relativeRank < 0)
- return Integer.MAX_VALUE + relativeRank;
- else
- return relativeRank;
- }
-
- });
-
- IDocument document= viewer.getDocument();
- LinkedPositionGroup group= new LinkedPositionGroup();
- for (int i= 0; i < sameNodes.length; i++) {
- ASTNode elem= sameNodes[i];
- group.addPosition(new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i));
- }
-
- LinkedModeModel model= new LinkedModeModel();
- model.addGroup(group);
- model.forceInstall();
- JavaEditor editor= getJavaEditor();
- if (editor != null) {
- model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
- }
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, viewer);
- ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
- ui.setExitPosition(viewer, offset, 0, LinkedPositionGroup.NO_STOP);
- ui.enter();
-
- if (fValueSuggestion != null) {
- document.replace(nameNode.getStartPosition(), nameNode.getLength(), fValueSuggestion);
- IRegion selectedRegion= ui.getSelectedRegion();
- seletion= new Point(selectedRegion.getOffset(), fValueSuggestion.length());
- }
-
- viewer.setSelectedRange(seletion.x, seletion.y); // by default full word is selected, restore original selection
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * Returns the currently active java editor, or <code>null</code> if it
- * cannot be determined.
- *
- * @return the currently active java editor, or <code>null</code>
- */
- private JavaEditor getJavaEditor() {
- IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor();
- if (part instanceof JavaEditor)
- return (JavaEditor) part;
- else
- return null;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
- // can't do anything
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return null;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return CorrectionMessages.LinkedNamesAssistProposal_proposalinfo;
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- String shortCutString= CorrectionCommandHandler.getShortCutString(getCommandId());
- if (shortCutString != null) {
- return Messages.format(CorrectionMessages.ChangeCorrectionProposal_name_with_shortcut, new String[] { fLabel, shortCutString });
- }
- return fLabel;
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LINKED_RENAME);
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return null;
- }
-
- /*
- * @see IJavaCompletionProposal#getRelevance()
- */
- public int getRelevance() {
- return fRelevance;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
- */
- public void selected(ITextViewer textViewer, boolean smartToggle) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
- */
- public void unselected(ITextViewer textViewer) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IShortcutProposal#getProposalId()
- */
- public String getCommandId() {
- return ASSIST_ID;
- }
-
- public void setRelevance(int relevance) {
- fRelevance= relevance;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
deleted file mode 100644
index 23fa4479..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
+++ /dev/null
@@ -1,896 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - Access to static proposal
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.InstanceofExpression;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.CodeStyleFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.StringFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.UnusedCodeFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.CodeStyleCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.StringCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.nls.ExternalizeWizard;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- */
-public class LocalCorrectionsSubProcessor {
-
- private static final String ADD_EXCEPTION_TO_THROWS_ID= "org.eclipse.wst.jsdt.ui.correction.addThrowsDecl"; //$NON-NLS-1$
- private static final String ADD_NON_NLS_ID= "org.eclipse.wst.jsdt.ui.correction.addNonNLS"; //$NON-NLS-1$
- private static final String ADD_STATIC_ACCESS_ID= "org.eclipse.wst.jsdt.ui.correction.changeToStatic"; //$NON-NLS-1$
- private static final String REMOVE_UNNECESSARY_NLS_TAG_ID= "org.eclipse.wst.jsdt.ui.correction.removeNlsTag"; //$NON-NLS-1$
-
- public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
- while (selectedNode != null && !(selectedNode instanceof Statement)) {
- selectedNode= selectedNode.getParent();
- }
- if (selectedNode == null) {
- return;
- }
-
- int offset= selectedNode.getStartPosition();
- int length= selectedNode.getLength();
- int selectionEnd= context.getSelectionOffset() + context.getSelectionLength();
- if (selectionEnd > offset + length) {
- // extend the selection if more than one statement is selected (bug 72149)
- length= selectionEnd - offset;
- }
-
- SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length, null);
- if (refactoring == null)
- return;
-
- refactoring.setLeaveDirty(true);
- if (refactoring.checkActivationBasics(astRoot).isOK()) {
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, (CompilationUnitChange) refactoring.createChange(null), 6, image);
- proposals.add(proposal);
- }
-
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl == null) {
- return;
- }
-
- ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(offset, length));
- if (uncaughtExceptions.length == 0) {
- return;
- }
-
- TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode);
- if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) {
- ASTRewrite rewrite= ASTRewrite.create(surroundingTry.getAST());
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 7, image);
-
- ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
-
- AST ast= astRoot.getAST();
- ListRewrite clausesRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
- for (int i= 0; i < uncaughtExceptions.length; i++) {
- ITypeBinding excBinding= uncaughtExceptions[i];
- String varName= StubUtility.getExceptionVariableName(cu.getJavaScriptProject());
- SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
- var.setName(ast.newSimpleName(varName));
- var.setType(imports.addImport(excBinding, ast));
- CatchClause newClause= ast.newCatchClause();
- newClause.setException(var);
- String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, selectedNode, String.valueOf('\n'));
- if (catchBody != null) {
- ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
- newClause.getBody().statements().add(node);
- }
- clausesRewrite.insertLast(newClause, null);
-
- String typeKey= "type" + i; //$NON-NLS-1$
- String nameKey= "name" + i; //$NON-NLS-1$
- proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
- proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
- addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
- }
- proposals.add(proposal);
- }
-
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methodDecl= (FunctionDeclaration) decl;
- IFunctionBinding binding= methodDecl.resolveBinding();
- if (binding != null) {
- ArrayList unhandledExceptions= new ArrayList(uncaughtExceptions.length);
- for (int i= 0; i < uncaughtExceptions.length; i++) {
- ITypeBinding curr= uncaughtExceptions[i];
- if (!canRemoveException(curr, null)) {
- unhandledExceptions.add(curr);
- }
- }
- uncaughtExceptions= (ITypeBinding[]) unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
-
- List exceptions= methodDecl.thrownExceptions();
- int nExistingExceptions= exceptions.size();
- ChangeDescription[] desc= new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
- for (int i= 0; i < exceptions.size(); i++) {
- Name elem= (Name) exceptions.get(i);
- if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) {
- desc[i]= new RemoveDescription();
- }
- }
- for (int i = 0; i < uncaughtExceptions.length; i++) {
- desc[i + nExistingExceptions]= new InsertDescription(uncaughtExceptions[i], ""); //$NON-NLS-1$
- }
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
-
- ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, 8, image);
- for (int i= 0; i < uncaughtExceptions.length; i++) {
- addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
- }
- proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID);
- proposals.add(proposal);
- }
- }
- }
-
- private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) {
- // all super classes except Object
- while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$
- proposal.addLinkedPositionProposal(key, exc);
- exc= exc.getSuperclass();
- }
- }
-
-
- private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) {
- while (curr != null) {
- for (int i= 0; i < addedExceptions.length; i++) {
- if (curr == addedExceptions[i]) {
- return true;
- }
- }
- curr= curr.getSuperclass();
- }
- return false;
- }
-
- public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
-
- QuickAssistProcessor.getCatchClauseToThrowsProposals(context, selectedNode, proposals);
- }
-
- public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- final IJavaScriptUnit cu= context.getCompilationUnit();
- if (cu == null || !cu.exists()){
- return;
- }
- String name= CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_description;
-
- ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 2, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)) {
- public void apply(IDocument document) {
- try {
- NLSRefactoring refactoring= NLSRefactoring.create(cu);
- if (refactoring == null)
- return;
- ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
- String dialogTitle= CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_dialog_title;
- new RefactoringStarter().activate(refactoring, wizard, JavaScriptPlugin.getActiveWorkbenchShell(), dialogTitle, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- public String getAdditionalProposalInfo() {
- return CorrectionMessages.LocalCorrectionsSubProcessor_externalizestrings_additional_info;
- }
-
- };
- proposals.add(proposal);
-
- IFix fix= StringFix.createFix(context.getASTRoot(), problem, false, true);
- if (fix != null) {
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
- Map options= new Hashtable();
- options.put(CleanUpConstants.ADD_MISSING_NLS_TAGS, CleanUpConstants.TRUE);
- FixCorrectionProposal addNLS= new FixCorrectionProposal(fix, new StringCleanUp(options), 3, image, context);
- addNLS.setCommandId(ADD_NON_NLS_ID);
- proposals.add(addNLS);
- }
- }
-
- public static void getUnnecessaryNLSTagProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IFix fix= StringFix.createFix(context.getASTRoot(), problem, true, false);
- if (fix != null) {
- Image image= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
- Map options= new Hashtable();
- options.put(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new StringCleanUp(options), 6, image, context);
- proposal.setCommandId(REMOVE_UNNECESSARY_NLS_TAG_ID);
- proposals.add(proposal);
- }
- }
-
-
- /*
- * Fix instance accesses and indirect (static) accesses to static fields/methods
- */
- public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IFix fix= CodeStyleFix.createIndirectAccessToStaticFix(context.getASTRoot(), problem);
- if (fix != null) {
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- Map options= new HashMap();
- options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new CodeStyleCleanUp(options), 6, image, context);
- proposal.setCommandId(ADD_STATIC_ACCESS_ID);
- proposals.add(proposal);
- return;
- }
-
- IFix[] fixes= CodeStyleFix.createNonStaticAccessFixes(context.getASTRoot(), problem);
- if (fixes != null) {
- IFix fix1= fixes[0];
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- Map options= new HashMap();
- options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix1, new CodeStyleCleanUp(options), 6, image, context);
- proposal.setCommandId(ADD_STATIC_ACCESS_ID);
- proposals.add(proposal);
-
- if (fixes.length > 1) {
- Map options1= new HashMap();
- options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpConstants.TRUE);
- options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, CleanUpConstants.TRUE);
- options1.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, CleanUpConstants.TRUE);
- IFix fix2= fixes[1];
- proposal= new FixCorrectionProposal(fix2, new CodeStyleCleanUp(options), 5, image, context);
- proposals.add(proposal);
- }
- }
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4);
- }
-
- public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
- ASTNode typeNode= null;
- ITypeBinding binding= null;
- if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent() instanceof AbstractTypeDeclaration) {
- AbstractTypeDeclaration typeDecl= (AbstractTypeDeclaration) selectedNode.getParent();
- binding= typeDecl.resolveBinding();
- typeNode= typeDecl;
- } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
- ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
- AnonymousClassDeclaration anonymDecl= creation.getAnonymousClassDeclaration();
- binding= anonymDecl.resolveBinding();
- typeNode= anonymDecl;
- }
- if (typeNode != null && binding != null) {
- UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
- proposals.add(proposal);
- }
- if (typeNode instanceof TypeDeclaration) {
- TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
- ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeAbstractProposal(cu, typeDeclaration, 5);
- proposals.add(proposal);
- }
- }
-
- public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof Name)) {
- return;
- }
- Name name= (Name) selectedNode;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding)) {
- return;
- }
- IVariableBinding varBinding= (IVariableBinding) binding;
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode node= astRoot.findDeclaringNode(binding);
- if (node instanceof VariableDeclarationFragment) {
- ASTRewrite rewrite= ASTRewrite.create(node.getAST());
-
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
- if (fragment.getInitializer() != null) {
- return;
- }
- Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
- if (expression == null) {
- return;
- }
- rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
-
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
- proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$
- proposals.add(proposal);
- }
- }
-
- public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
-
- TypeDeclaration typeDeclaration= null;
- if (selectedNode.getLocationInParent() == TypeDeclaration.NAME_PROPERTY) {
- typeDeclaration= (TypeDeclaration) selectedNode.getParent();
- } else {
- BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (declaration instanceof Initializer && problem.getProblemId() == IProblem.UnhandledExceptionInDefaultConstructor) {
- addUncaughtExceptionProposals(context, problem, proposals);
- }
- return;
- }
-
- ITypeBinding binding= typeDeclaration.resolveBinding();
- if (binding == null || binding.getSuperclass() == null) {
- return;
- }
- IJavaScriptUnit cu= context.getCompilationUnit();
- IFunctionBinding[] methods= binding.getSuperclass().getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- IFunctionBinding curr= methods[i];
- if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
- proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5));
- }
- }
- }
-
- public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- int problemId = problem.getProblemId();
- UnusedCodeFix fix= UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, false);
- if (fix != null) {
- addProposal(context, proposals, fix);
- }
-
- if (problemId==IProblem.LocalVariableIsNeverUsed){
- fix= UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, true);
- addProposal(context, proposals, fix);
- }
-
- }
-
- private static void addProposal(IInvocationContext context, Collection proposals, final UnusedCodeFix fix) {
- if (fix != null) {
- Image image= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, fix.getCleanUp(), 10, image, context);
- proposals.add(proposal);
- }
- }
-
- public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_removesemicolon_description;
- ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$
- proposals.add(proposal);
- }
-
- public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
-
- ASTNode curr= selectedNode;
- while (curr instanceof ParenthesizedExpression) {
- curr= ((ParenthesizedExpression) curr).getExpression();
- }
-
- if (curr instanceof InstanceofExpression) {
- AST ast= curr.getAST();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- InstanceofExpression inst= (InstanceofExpression) curr;
-
- InfixExpression expression= ast.newInfixExpression();
- expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand()));
- expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
- expression.setRightOperand(ast.newNullLiteral());
-
-
- if (false/*ASTNodes.needsParentheses(expression)*/) {
- ParenthesizedExpression parents= ast.newParenthesizedExpression();
- parents.setExpression(expression);
- rewrite.replace(inst, parents, null);
- } else {
- rewrite.replace(inst, expression, null);
- }
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
- proposals.add(proposal);
- }
-
- }
-
- public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null || !(selectedNode.getParent() instanceof FunctionDeclaration)) {
- return;
- }
- FunctionDeclaration decl= (FunctionDeclaration) selectedNode.getParent();
- IFunctionBinding binding= decl.resolveBinding();
- if (binding != null) {
- List thrownExceptions= decl.thrownExceptions();
- int index= thrownExceptions.indexOf(selectedNode);
- if (index == -1) {
- return;
- }
- ChangeDescription[] desc= new ChangeDescription[thrownExceptions.size()];
- desc[index]= new RemoveDescription();
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessarythrow_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
-
- proposals.add(new ChangeMethodSignatureProposal(label, cu, selectedNode, binding, null, desc, 5, image));
- }
- }
-
-// public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
-// IFix fix= CodeStyleFix.createAddFieldQualifierFix(context.getASTRoot(), problem);
-// if (fix != null) {
-// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
-// Map options= new HashMap();
-// options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, CleanUpConstants.TRUE);
-// options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, CleanUpConstants.TRUE);
-// FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new CodeStyleCleanUp(options), 5, image, context);
-// proposal.setCommandId(ADD_FIELD_QUALIFICATION_ID);
-// proposals.add(proposal);
-// }
-// }
-//
- public static void addInvalidVariableNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- // hiding, redefined or future keyword
-
- JavaScriptUnit root= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(root);
- if (selectedNode instanceof FunctionDeclaration) {
- selectedNode= ((FunctionDeclaration) selectedNode).getName();
- }
- if (!(selectedNode instanceof SimpleName)) {
- return;
- }
- SimpleName nameNode= (SimpleName) selectedNode;
- String valueSuggestion= null;
-
- String name;
- switch (problem.getProblemId()) {
- case IProblem.LocalVariableHidingLocalVariable:
- case IProblem.LocalVariableHidingField:
- name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_local_label, nameNode.getIdentifier());
- break;
- case IProblem.FieldHidingLocalVariable:
- case IProblem.FieldHidingField:
- case IProblem.DuplicateField:
- name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_field_label, nameNode.getIdentifier());
- break;
- case IProblem.ArgumentHidingLocalVariable:
- case IProblem.ArgumentHidingField:
- name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_argument_label, nameNode.getIdentifier());
- break;
- case IProblem.DuplicateMethod:
- name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_renaming_duplicate_method, nameNode.getIdentifier());
- break;
-
- default:
- name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_rename_var_label, nameNode.getIdentifier());
- }
-
- if (problem.getProblemId() == IProblem.UseEnumAsAnIdentifier) {
- valueSuggestion= "enumeration"; //$NON-NLS-1$
- } else {
- valueSuggestion= nameNode.getIdentifier() + '1';
- }
-
- LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(name, context.getCompilationUnit(), nameNode, valueSuggestion);
- proposals.add(proposal);
- }
-
- public static void getInvalidOperatorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- JavaScriptUnit root= context.getASTRoot();
- AST ast= root.getAST();
-
- ASTNode selectedNode= problem.getCoveringNode(root);
-
- while (selectedNode instanceof ParenthesizedExpression) {
- selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
- }
-
- if (selectedNode instanceof PrefixExpression) {
- // !x instanceof X -> !(x instanceof X)
-
- PrefixExpression expression= (PrefixExpression) selectedNode;
- if (expression.getOperator() == PrefixExpression.Operator.NOT) {
- ASTNode parent= expression.getParent();
-
- String label= null;
- switch (parent.getNodeType()) {
- case ASTNode.INSTANCEOF_EXPRESSION:
- label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
- break;
- case ASTNode.INFIX_EXPRESSION:
- label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description;
- break;
- }
-
- if (label != null) {
- ASTRewrite rewrite= ASTRewrite.create(ast);
- rewrite.replace(selectedNode, rewrite.createMoveTarget(expression.getOperand()), null);
-
- ParenthesizedExpression newParentExpr= ast.newParenthesizedExpression();
- newParentExpr.setExpression((Expression) rewrite.createMoveTarget(parent));
- PrefixExpression newPrefixExpr= ast.newPrefixExpression();
- newPrefixExpr.setOperand(newParentExpr);
- newPrefixExpr.setOperator(PrefixExpression.Operator.NOT);
-
- rewrite.replace(parent, newPrefixExpr, null);
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
- proposals.add(proposal);
- }
- }
- } else if (selectedNode instanceof InfixExpression && isBitOperation((((InfixExpression) selectedNode).getOperator()))) {
- // a & b == c -> (a & b) == c
- final CompareInBitWiseOpFinder opFinder= new CompareInBitWiseOpFinder(selectedNode);
- if (opFinder.getCompareExpression() != null) { // compare operation inside bit operations: set parents
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_bitop_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
- CUCorrectionProposal proposal= new CUCorrectionProposal(label, context.getCompilationUnit(), 5, image) {
- protected void addEdits(IDocument document, TextEdit edit) throws CoreException {
- InfixExpression compareExpression= opFinder.getCompareExpression();
- InfixExpression expression= opFinder.getParentInfixExpression();
- ASTNode left= compareExpression.getLeftOperand();
- if (expression.getStartPosition() < left.getStartPosition()) {
- edit.addChild(new InsertEdit(expression.getStartPosition(), String.valueOf('(')));
- edit.addChild(new InsertEdit(ASTNodes.getExclusiveEnd(left), String.valueOf(')')));
- }
- ASTNode rigth= compareExpression.getRightOperand();
- int selEnd= ASTNodes.getExclusiveEnd(expression);
- if (selEnd > ASTNodes.getExclusiveEnd(rigth)) {
- edit.addChild(new InsertEdit(rigth.getStartPosition(), String.valueOf('(')));
- edit.addChild(new InsertEdit(selEnd, String.valueOf(')')));
- }
- }
- };
- proposals.add(proposal);
- }
- }
- }
-
- private static boolean isBitOperation(InfixExpression.Operator op) {
- return op == InfixExpression.Operator.AND || op == InfixExpression.Operator.OR || op == InfixExpression.Operator.XOR;
- }
-
- private static class CompareInBitWiseOpFinder extends ASTVisitor {
-
- private InfixExpression fCompareExpression= null;
- private final ASTNode fSelectedNode;
-
- public CompareInBitWiseOpFinder(ASTNode selectedNode) {
- fSelectedNode= selectedNode;
- selectedNode.accept(this);
- }
-
- public boolean visit(InfixExpression e) {
- InfixExpression.Operator op= e.getOperator();
- if (isBitOperation(op)) {
- return true;
- } else if (op == InfixExpression.Operator.EQUALS || op == InfixExpression.Operator.NOT_EQUALS) {
- fCompareExpression= e;
- return false;
- }
- return false;
- }
-
- public InfixExpression getCompareExpression() {
- return fCompareExpression;
- }
-
- public InfixExpression getParentInfixExpression() {
- ASTNode expr= fSelectedNode;
- ASTNode parent= expr.getParent(); // include all parents
- while (parent instanceof InfixExpression && isBitOperation(((InfixExpression) parent).getOperator())) {
- expr= parent;
- parent= expr.getParent();
- }
- return (InfixExpression) expr;
- }
- }
-
- public static void getUnnecessaryElseProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- JavaScriptUnit root= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(root);
- if (selectedNode == null) {
- return;
- }
- if (!(selectedNode.getParent() instanceof IfStatement)) {
- return;
- }
- IfStatement ifStatement= (IfStatement) selectedNode.getParent();
- ASTNode ifParent= ifStatement.getParent();
- if (!(ifParent instanceof Block)) {
- return;
- }
-
- ASTRewrite rewrite= ASTRewrite.create(root.getAST());
- ASTNode placeholder=QuickAssistProcessor.getCopyOfInner(rewrite, ifStatement.getElseStatement(), false);
- if (placeholder == null) {
- return;
- }
- rewrite.remove(ifStatement.getElseStatement(), null);
-
- ListRewrite listRewrite= rewrite.getListRewrite(ifParent, Block.STATEMENTS_PROPERTY);
- listRewrite.insertAfter(placeholder, ifStatement, null);
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeelse_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
- proposals.add(proposal);
- }
-
- public static void getUnreachableCodeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- JavaScriptUnit root= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(root);
- if (selectedNode == null) {
- return;
- }
- if (selectedNode.getParent() instanceof ExpressionStatement) {
- selectedNode= selectedNode.getParent();
- }
-
- if (selectedNode instanceof Statement) {
- ASTRewrite rewrite= ASTRewrite.create(selectedNode.getAST());
- rewrite.remove(selectedNode, null);
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_description;
- Image image= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 3, image);
- proposals.add(proposal);
- }
- }
-
- public static void getAssignmentHasNoEffectProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- JavaScriptUnit root= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(root);
- if (!(selectedNode instanceof Assignment)) {
- return;
- }
- ASTNode assignedNode= ((Assignment) selectedNode).getLeftHandSide();
- ASTNode assignExpression= ((Assignment) selectedNode).getRightHandSide();
- if (!(assignedNode instanceof SimpleName) && !(assignExpression instanceof SimpleName)) {
- return;
- }
-
- IBinding binding= (assignedNode instanceof SimpleName) ? ((SimpleName) assignedNode).resolveBinding() : ((SimpleName) assignExpression).resolveBinding();
- if (!(binding instanceof IVariableBinding)) {
- return;
- }
- ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
- if (typeBinding == null) {
- return;
- }
- IVariableBinding fieldBinding= Bindings.findFieldInHierarchy(typeBinding, binding.getName());
- if (fieldBinding == null || fieldBinding.getDeclaringClass() != typeBinding && Modifier.isPrivate(fieldBinding.getModifiers())) {
- return;
- }
-
- if (binding != fieldBinding) {
- if (assignedNode instanceof SimpleName) {
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_left_hand_side_description;
- proposals.add(createNoSideEffectProposal(context, (SimpleName) assignedNode, fieldBinding, label, 6));
- }
- if (assignExpression instanceof SimpleName) {
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_LocalCorrectionsSubProcessor_qualify_right_hand_side_description;
- proposals.add(createNoSideEffectProposal(context, (SimpleName) assignExpression, fieldBinding, label, 5));
- }
- }
-
- if (binding == fieldBinding && ASTResolving.findParentBodyDeclaration(selectedNode) instanceof FunctionDeclaration) {
- SimpleName simpleName= (SimpleName) ((assignedNode instanceof SimpleName) ? assignedNode : assignExpression);
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, simpleName.getIdentifier());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- proposals.add(new NewVariableCompletionProposal(label, context.getCompilationUnit(), NewVariableCompletionProposal.PARAM, simpleName, null, 5, image));
- }
-
-
- }
-
- private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
- AST ast= nodeToQualify.getAST();
-
- Expression qualifier;
- if (Modifier.isStatic(fieldBinding.getModifiers())) {
- ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
- qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
- } else {
- qualifier= ast.newThisExpression();
- }
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
- FieldAccess access= ast.newFieldAccess();
- access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
- access.setExpression(qualifier);
- rewrite.replace(nodeToQualify, access, null);
-
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
- }
-
-// public static void addValueForAnnotationProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
-// IJavaScriptUnit cu= context.getCompilationUnit();
-// ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
-// if (selectedNode instanceof Annotation) {
-// Annotation annotation= (Annotation) selectedNode;
-// if (annotation.resolveTypeBinding() == null) {
-// return;
-// }
-// MissingAnnotationAttributesProposal proposal= new MissingAnnotationAttributesProposal(cu, annotation, 10);
-// proposals.add(proposal);
-// }
-// }
-
- public static void addFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode instanceof SwitchCase && selectedNode.getParent() instanceof SwitchStatement) {
- AST ast= selectedNode.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- ListRewrite listRewrite= rewrite.getListRewrite(selectedNode.getParent(), SwitchStatement.STATEMENTS_PROPERTY);
- listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null);
-
- String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
- proposals.add(proposal);
- }
- }
-
- public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode instanceof Name) {
- IBinding binding= ((Name) selectedNode).resolveBinding();
- if (binding instanceof IVariableBinding) {
- IVariableBinding variableBinding= (IVariableBinding) binding;
- if (variableBinding.isField()) {
- String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
- String fieldName= variableBinding.getName();
- String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
- if (methodName != null) {
- AST ast= selectedNode.getAST();
- ASTRewrite astRewrite= ASTRewrite.create(ast);
- ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);
-
- FunctionInvocation method= ast.newFunctionInvocation();
- String qfn= importRewrite.addImport(methodName[0]);
- method.setExpression(ast.newName(qfn));
- method.setName(ast.newSimpleName(methodName[1]));
- astRewrite.replace(selectedNode, method, null);
-
- String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, method);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, 10, image);
- proposal.setImportRewrite(importRewrite);
- proposals.add(proposal);
- }
- }
- }
- }
- }
-
- private static Map/*<String,String[]>*/ resolveMap;
- private static String[] getMethod(String fieldName) {
- if (resolveMap==null){
- resolveMap=new HashMap();
- resolveMap.put("java.util.Collections.EMPTY_MAP", new String[]{"java.util.Collections","emptyMap"}); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- resolveMap.put("java.util.Collections.EMPTY_SET", new String[]{"java.util.Collections","emptySet"}); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- resolveMap.put("java.util.Collections.EMPTY_LIST", new String[]{"java.util.Collections","emptyList"});//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- return (String[]) resolveMap.get(fieldName);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MarkerResolutionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MarkerResolutionProposal.java
deleted file mode 100644
index 794fb2a0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MarkerResolutionProposal.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-/**
- */
-public class MarkerResolutionProposal implements IJavaCompletionProposal {
-
- private IMarkerResolution fResolution;
- private IMarker fMarker;
-
- /**
- * Constructor for MarkerResolutionProposal.
- */
- public MarkerResolutionProposal(IMarkerResolution resolution, IMarker marker) {
- fResolution= resolution;
- fMarker= marker;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
- */
- public void apply(IDocument document) {
- fResolution.run(fMarker);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- if (fResolution instanceof IMarkerResolution2) {
- return ((IMarkerResolution2) fResolution).getDescription();
- }
- if (fResolution instanceof IJavaCompletionProposal) {
- return ((IJavaCompletionProposal) fResolution).getAdditionalProposalInfo();
- }
- try {
- String problemDesc= (String) fMarker.getAttribute(IMarker.MESSAGE);
- return Messages.format(CorrectionMessages.MarkerResolutionProposal_additionaldesc, problemDesc);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- return fResolution.getLabel();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
- */
- public Image getImage() {
- if (fResolution instanceof IMarkerResolution2) {
- return ((IMarkerResolution2) fResolution).getImage();
- }
- if (fResolution instanceof IJavaCompletionProposal) {
- return ((IJavaCompletionProposal) fResolution).getImage();
- }
- return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.IJavaCompletionProposal#getRelevance()
- */
- public int getRelevance() {
- if (fResolution instanceof IJavaCompletionProposal) {
- return ((IJavaCompletionProposal) fResolution).getRelevance();
- }
- return 10;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument)
- */
- public Point getSelection(IDocument document) {
- if (fResolution instanceof IJavaCompletionProposal) {
- return ((IJavaCompletionProposal) fResolution).getSelection(document);
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java
deleted file mode 100644
index 7182a0a2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.List;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class MissingReturnTypeCorrectionProposal extends LinkedCorrectionProposal {
-
- private static final String RETURN_EXPRESSION_KEY= "value"; //$NON-NLS-1$
-
- private FunctionDeclaration fMethodDecl;
- private ReturnStatement fExistingReturn;
-
- public MissingReturnTypeCorrectionProposal(IJavaScriptUnit cu, FunctionDeclaration decl, ReturnStatement existingReturn, int relevance) {
- super("", cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); //$NON-NLS-1$
- fMethodDecl= decl;
- fExistingReturn= existingReturn;
- }
-
- public String getDisplayString() {
- if (fExistingReturn != null) {
- return CorrectionMessages.MissingReturnTypeCorrectionProposal_changereturnstatement_description;
- } else {
- return CorrectionMessages.MissingReturnTypeCorrectionProposal_addreturnstatement_description;
- }
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() {
- AST ast= fMethodDecl.getAST();
-
- ITypeBinding returnBinding= getReturnTypeBinding();
-
- if (fExistingReturn != null) {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Expression expression= evaluateReturnExpressions(ast, returnBinding, fExistingReturn.getStartPosition());
- if (expression != null) {
- rewrite.set(fExistingReturn, ReturnStatement.EXPRESSION_PROPERTY, expression, null);
-
- addLinkedPosition(rewrite.track(expression), true, RETURN_EXPRESSION_KEY);
- }
- return rewrite;
- } else {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Block block= fMethodDecl.getBody();
-
- List statements= block.statements();
- int nStatements= statements.size();
- ASTNode lastStatement= null;
- if (nStatements > 0) {
- lastStatement= (ASTNode) statements.get(nStatements - 1);
- }
-
- if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) {
- Expression expression= ((ExpressionStatement) lastStatement).getExpression();
- ITypeBinding binding= expression.resolveTypeBinding();
- if (binding != null && binding.isAssignmentCompatible(returnBinding)) {
- Expression placeHolder= (Expression) rewrite.createMoveTarget(expression);
-
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(placeHolder);
-
- rewrite.replace(lastStatement, returnStatement, null);
- return rewrite;
- }
- }
-
- int offset;
- if (lastStatement == null) {
- offset= block.getStartPosition() + 1;
- } else {
- offset= lastStatement.getStartPosition() + lastStatement.getLength();
- }
- ReturnStatement returnStatement= ast.newReturnStatement();
- Expression expression= evaluateReturnExpressions(ast, returnBinding, offset);
-
- returnStatement.setExpression(expression);
-
- rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null);
-
- addLinkedPosition(rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY);
- return rewrite;
- }
- }
-
- private ITypeBinding getReturnTypeBinding() {
- IFunctionBinding methodBinding= fMethodDecl.resolveBinding();
- if (methodBinding != null && methodBinding.getReturnType() != null) {
- return methodBinding.getReturnType();
- }
- return null;
- }
-
-
- /*
- * Evaluates possible return expressions. The favourite expression is returned.
- */
- private Expression evaluateReturnExpressions(AST ast, ITypeBinding returnBinding, int returnOffset) {
- JavaScriptUnit root= (JavaScriptUnit) fMethodDecl.getRoot();
-
- Expression result= null;
- if (returnBinding != null) {
- ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
- IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY );
- for (int i= 0; i < bindings.length; i++) {
- IVariableBinding curr= (IVariableBinding) bindings[i];
- ITypeBinding type= curr.getType();
- if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr)) {
- if (result == null) {
- result= ast.newSimpleName(curr.getName());
- }
- addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null);
- }
- }
- }
- Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, fMethodDecl.getReturnType2(), fMethodDecl.getExtraDimensions());
- addLinkedPositionProposal(RETURN_EXPRESSION_KEY, ASTNodes.asString(defaultExpression), null);
- if (result == null) {
- return defaultExpression;
- }
- return result;
- }
-
- private boolean testModifier(IVariableBinding curr) {
- int modifiers= curr.getModifiers();
- int staticFinal= Modifier.STATIC | Modifier.FINAL;
- if ((modifiers & staticFinal) == staticFinal) {
- return false;
- }
- if (Modifier.isStatic(modifiers) && !Modifier.isStatic(fMethodDecl.getModifiers())) {
- return false;
- }
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java
deleted file mode 100644
index 0ba900f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.VariableDeclarationRewrite;
-
-public class ModifierChangeCompletionProposal extends LinkedCorrectionProposal {
-
- private IBinding fBinding;
- private ASTNode fNode;
- private int fIncludedModifiers;
- private int fExcludedModifiers;
-
- public ModifierChangeCompletionProposal(String label, IJavaScriptUnit targetCU, IBinding binding, ASTNode node, int includedModifiers, int excludedModifiers, int relevance, Image image) {
- super(label, targetCU, null, relevance, image);
- fBinding= binding;
- fNode= node;
- fIncludedModifiers= includedModifiers;
- fExcludedModifiers= excludedModifiers;
- }
-
- protected ASTRewrite getRewrite() {
- JavaScriptUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
- ASTNode boundNode= astRoot.findDeclaringNode(fBinding);
- ASTNode declNode= null;
-
- TextEditGroup selectionDescription= null;
-
- if (boundNode != null) {
- declNode= boundNode; // is same CU
- } else {
- selectionDescription= new TextEditGroup("selection"); // in different CU, needs selection //$NON-NLS-1$
- //setSelectionDescription(selectionDescription);
- JavaScriptUnit newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
- declNode= newRoot.findDeclaringNode(fBinding.getKey());
- }
- if (declNode != null) {
- AST ast= declNode.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)declNode;
- ASTNode parent= declNode.getParent();
- if (parent instanceof FieldDeclaration) {
- FieldDeclaration fieldDecl= (FieldDeclaration) parent;
- if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split
- VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, selectionDescription);
- return rewrite;
- }
- } else if (parent instanceof VariableDeclarationStatement) {
- VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent;
- if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split
- VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, selectionDescription);
- return rewrite;
- }
- } else if (parent instanceof VariableDeclarationExpression) {
- // can't separate
- }
- declNode= parent;
- }
- ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declNode);
- listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, selectionDescription);
- return rewrite;
- }
- return null;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
deleted file mode 100644
index 9aa93eeb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
+++ /dev/null
@@ -1,1073 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.NumberLiteral;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment.Operator;
-import org.eclipse.wst.jsdt.core.dom.Modifier.ModifierKeyword;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalPositionGroup;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.sef.SelfEncapsulateFieldWizard;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- */
-public class ModifierCorrectionSubProcessor {
-
-
- public static final int TO_STATIC= 1;
- public static final int TO_VISIBLE= 2;
- public static final int TO_NON_PRIVATE= 3;
- public static final int TO_NON_STATIC= 4;
- public static final int TO_NON_FINAL= 5;
-
- public static void addNonAccessibleReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int kind, int relevance) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
-
- IBinding binding=null;
- switch (selectedNode.getNodeType()) {
- case ASTNode.SIMPLE_NAME:
- binding= ((SimpleName) selectedNode).resolveBinding();
- break;
- case ASTNode.QUALIFIED_NAME:
- binding= ((QualifiedName) selectedNode).resolveBinding();
- break;
- case ASTNode.SIMPLE_TYPE:
- binding= ((SimpleType) selectedNode).resolveBinding();
- break;
- case ASTNode.FUNCTION_INVOCATION:
- binding= ((FunctionInvocation) selectedNode).getName().resolveBinding();
- break;
- case ASTNode.SUPER_METHOD_INVOCATION:
- binding= ((SuperMethodInvocation) selectedNode).getName().resolveBinding();
- break;
- case ASTNode.FIELD_ACCESS:
- binding= ((FieldAccess) selectedNode).getName().resolveBinding();
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- binding= ((SuperFieldAccess) selectedNode).getName().resolveBinding();
- break;
- case ASTNode.CLASS_INSTANCE_CREATION:
- binding= ((ClassInstanceCreation) selectedNode).resolveConstructorBinding();
- break;
- case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
- binding= ((SuperConstructorInvocation) selectedNode).resolveConstructorBinding();
- break;
- default:
- return;
- }
- ITypeBinding typeBinding= null;
- String name;
- IBinding bindingDecl;
- boolean isLocalVar= false;
- if (binding instanceof IFunctionBinding) {
- IFunctionBinding methodDecl= (IFunctionBinding) binding;
- bindingDecl= methodDecl.getMethodDeclaration();
- typeBinding= methodDecl.getDeclaringClass();
- name= methodDecl.getName() + "()"; //$NON-NLS-1$
- } else if (binding instanceof IVariableBinding) {
- IVariableBinding varDecl= (IVariableBinding) binding;
- typeBinding= varDecl.getDeclaringClass();
- name= binding.getName();
- isLocalVar= !varDecl.isField();
- bindingDecl= varDecl.getVariableDeclaration();
- } else if (binding instanceof ITypeBinding) {
- typeBinding= (ITypeBinding) binding;
- bindingDecl= typeBinding.getTypeDeclaration();
- name= binding.getName();
- } else {
- return;
- }
- if (typeBinding != null && typeBinding.isFromSource() || isLocalVar) {
- int includedModifiers= 0;
- int excludedModifiers= 0;
- String label;
- switch (kind) {
- case TO_VISIBLE:
- excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
- includedModifiers= getNeededVisibility(selectedNode, typeBinding);
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changevisibility_description, new String[] { name, getVisibilityString(includedModifiers) });
- break;
- case TO_STATIC:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertostatic_description, name);
- includedModifiers= Modifier.STATIC;
- break;
- case TO_NON_STATIC:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertononstatic_description, name);
- excludedModifiers= Modifier.STATIC;
- break;
- case TO_NON_PRIVATE:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertodefault_description, name);
- excludedModifiers= Modifier.PRIVATE;
- break;
- case TO_NON_FINAL:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertononfinal_description, name);
- excludedModifiers= Modifier.FINAL;
- break;
- default:
- throw new IllegalArgumentException("not supported"); //$NON-NLS-1$
- }
- IJavaScriptUnit targetCU= isLocalVar ? cu : ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), typeBinding.getTypeDeclaration());
- if (targetCU != null) {
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- proposals.add(new ModifierChangeCompletionProposal(label, targetCU, bindingDecl, selectedNode, includedModifiers, excludedModifiers, relevance, image));
- }
- }
- if (kind == TO_VISIBLE && bindingDecl.getKind() == IBinding.VARIABLE) {
- UnresolvedElementsSubProcessor.getVariableProposals(context, problem, (IVariableBinding) bindingDecl, proposals);
- }
- }
-
- public static void addChangeOverriddenModfierProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int kind) throws JavaScriptModelException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof FunctionDeclaration)) {
- return;
- }
-
- IFunctionBinding method= ((FunctionDeclaration) selectedNode).resolveBinding();
- ITypeBinding curr= method.getDeclaringClass();
-
-
- if (kind == TO_VISIBLE && problem.getProblemId() != IProblem.OverridingNonVisibleMethod) {
- IFunctionBinding defining= Bindings.findOverriddenMethod(method, false);
- if (defining != null) {
- int excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
- int includedModifiers= JdtFlags.getVisibilityCode(defining);
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemethodvisibility_description, new String[] { getVisibilityString(includedModifiers) });
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- proposals.add(new ModifierChangeCompletionProposal(label, cu, method, selectedNode, includedModifiers, excludedModifiers, 8, image));
- }
- }
-
- IFunctionBinding overriddenInClass= null;
- while (overriddenInClass == null && curr.getSuperclass() != null) {
- curr= curr.getSuperclass();
- overriddenInClass= Bindings.findOverriddenMethodInType(curr, method);
- }
- if (overriddenInClass != null) {
- IFunctionBinding overriddenDecl= overriddenInClass.getMethodDeclaration();
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), overriddenDecl.getDeclaringClass());
- if (targetCU != null) {
- String methodName= curr.getName() + '.' + overriddenInClass.getName();
- String label;
- int excludedModifiers;
- int includedModifiers;
- switch (kind) {
- case TO_VISIBLE:
- excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
- includedModifiers= JdtFlags.getVisibilityCode(method);
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changeoverriddenvisibility_description, new String[] { methodName, getVisibilityString(includedModifiers) });
- break;
- case TO_NON_FINAL:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemethodtononfinal_description, methodName);
- excludedModifiers= Modifier.FINAL;
- includedModifiers= 0;
- break;
- case TO_NON_STATIC:
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemethodtononstatic_description, methodName);
- excludedModifiers= Modifier.STATIC;
- includedModifiers= 0;
- break;
- default:
- Assert.isTrue(false, "not supported"); //$NON-NLS-1$
- return;
- }
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- proposals.add(new ModifierChangeCompletionProposal(label, targetCU, overriddenDecl, selectedNode, includedModifiers, excludedModifiers, 7, image));
- }
- }
- }
-
- public static void addNonFinalLocalProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof SimpleName)) {
- return;
- }
-
- IBinding binding= ((SimpleName) selectedNode).resolveBinding();
- if (binding instanceof IVariableBinding) {
- binding= ((IVariableBinding) binding).getVariableDeclaration();
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertofinal_description, binding.getName());
- proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 5, image));
- }
- }
-
-
-
- public static void addRemoveInvalidModfiersProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int relevance) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode instanceof FunctionDeclaration) {
- selectedNode= ((FunctionDeclaration) selectedNode).getName();
- }
-
- if (!(selectedNode instanceof SimpleName)) {
- return;
- }
-
- IBinding binding= ((SimpleName) selectedNode).resolveBinding();
- if (binding != null) {
- String methodName= binding.getName();
- String label= null;
- int problemId= problem.getProblemId();
-
-
- int excludedModifiers= 0;
- int includedModifiers= 0;
-
- switch (problemId) {
- case IProblem.CannotHideAnInstanceMethodWithAStaticMethod:
- case IProblem.UnexpectedStaticModifierForMethod:
- excludedModifiers= Modifier.STATIC;
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemethodtononstatic_description, methodName);
- break;
- case IProblem.UnexpectedStaticModifierForField:
- excludedModifiers= Modifier.STATIC;
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changefieldmodifiertononstatic_description, methodName);
- break;
- case IProblem.IllegalModifierCombinationFinalVolatileForField:
- excludedModifiers= Modifier.VOLATILE;
- label= CorrectionMessages.ModifierCorrectionSubProcessor_removevolatile_description;
- break;
- case IProblem.IllegalModifierForClass:
- excludedModifiers= ~(Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
- break;
- case IProblem.IllegalModifierForMemberClass:
- excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
- break;
- case IProblem.IllegalModifierForLocalClass:
- excludedModifiers= ~(Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
- break;
- case IProblem.IllegalModifierForField:
- excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT);
- break;
- case IProblem.IllegalModifierForMethod:
- excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE | Modifier.STRICTFP);
- if (((IFunctionBinding) binding).isConstructor()) {
- excludedModifiers |= Modifier.STATIC;
- }
- break;
- default:
- Assert.isTrue(false, "not supported"); //$NON-NLS-1$
- return;
- }
-
- if (label == null)
- label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_removeinvalidmodifiers_description, methodName);
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, includedModifiers, excludedModifiers, relevance, image));
-
- if (problemId == IProblem.IllegalModifierCombinationFinalVolatileForField) {
- proposals.add(new ModifierChangeCompletionProposal(CorrectionMessages.ModifierCorrectionSubProcessor_removefinal_description, cu, binding, selectedNode, 0, Modifier.FINAL, relevance + 1, image));
- }
-
- if (problemId == IProblem.UnexpectedStaticModifierForField && binding instanceof IVariableBinding) {
- ITypeBinding declClass= ((IVariableBinding) binding).getDeclaringClass();
- if (declClass.isMember()) {
- proposals.add(new ModifierChangeCompletionProposal(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertostaticfinal_description, cu, binding, selectedNode, Modifier.FINAL, Modifier.VOLATILE, relevance + 1, image));
- ASTNode parentType= context.getASTRoot().findDeclaringNode(declClass);
- if (parentType != null) {
- proposals.add(new ModifierChangeCompletionProposal(CorrectionMessages.ModifierCorrectionSubProcessor_addstatictoparenttype_description, cu, declClass, parentType, Modifier.STATIC, 0, relevance - 1, image));
- }
- }
- }
- if (problemId == IProblem.UnexpectedStaticModifierForMethod && binding instanceof IFunctionBinding) {
- ITypeBinding declClass= ((IFunctionBinding) binding).getDeclaringClass();
- if (declClass.isMember()) {
- ASTNode parentType= context.getASTRoot().findDeclaringNode(declClass);
- if (parentType != null) {
- proposals.add(new ModifierChangeCompletionProposal(CorrectionMessages.ModifierCorrectionSubProcessor_addstatictoparenttype_description, cu, declClass, parentType, Modifier.STATIC, 0, relevance - 1, image));
- }
- }
- }
- }
- }
-
- private static String getVisibilityString(int code) {
- if (Modifier.isPublic(code)) {
- return "public"; //$NON-NLS-1$
- } else if (Modifier.isProtected(code)) {
- return "protected"; //$NON-NLS-1$
- } else if (Modifier.isPrivate(code)) {
- return "private"; //$NON-NLS-1$
- }
- return CorrectionMessages.ModifierCorrectionSubProcessor_default;
- }
-
-
- private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType) {
- ITypeBinding currNodeBinding= Bindings.getBindingOfParentType(currNode);
- if (currNodeBinding == null) { // import
- return Modifier.PUBLIC;
- }
-
- if (Bindings.isSuperType(targetType, currNodeBinding)) {
- return Modifier.PROTECTED;
- }
-
- if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
- return 0;
- }
- return Modifier.PUBLIC;
- }
-
- public static void addAbstractMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
-
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
- FunctionDeclaration decl;
- if (selectedNode instanceof SimpleName) {
- decl= (FunctionDeclaration) selectedNode.getParent();
- } else if (selectedNode instanceof FunctionDeclaration) {
- decl= (FunctionDeclaration) selectedNode;
- } else {
- return;
- }
-
- ASTNode parentType= ASTResolving.findParentType(decl);
- TypeDeclaration parentTypeDecl= null;
- boolean parentIsAbstractClass= false;
- if (parentType instanceof TypeDeclaration) {
- parentTypeDecl= (TypeDeclaration) parentType;
- parentIsAbstractClass= Modifier.isAbstract(parentTypeDecl.getModifiers());
- }
- boolean hasNoBody= (decl.getBody() == null);
-
- if (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstractClass) {
- AST ast= astRoot.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Modifier modifierNode= ASTNodes.findModifierNode(Modifier.ABSTRACT, decl.modifiers());
- if (modifierNode != null) {
- rewrite.remove(modifierNode, null);
- }
-
- if (hasNoBody) {
- Block newBody= ast.newBlock();
- rewrite.set(decl, FunctionDeclaration.BODY_PROPERTY, newBody, null);
-
- Expression expr= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
- if (expr != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expr);
- newBody.statements().add(returnStatement);
- }
- }
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_removeabstract_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
- proposals.add(proposal);
- }
-
- if (!hasNoBody && problem.getProblemId() == IProblem.BodyForAbstractMethod) {
- ASTRewrite rewrite= ASTRewrite.create(decl.getAST());
- rewrite.remove(decl.getBody(), null);
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_removebody_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
- proposals.add(proposal2);
- }
-
- if (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentTypeDecl != null)) {
- ASTRewriteCorrectionProposal proposal= getMakeTypeAbstractProposal(cu, parentTypeDecl, 5);
- proposals.add(proposal);
- }
-
- }
-
- public static void addNativeMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
-
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
- FunctionDeclaration decl;
- if (selectedNode instanceof SimpleName) {
- decl= (FunctionDeclaration) selectedNode.getParent();
- } else if (selectedNode instanceof FunctionDeclaration) {
- decl= (FunctionDeclaration) selectedNode;
- } else {
- return;
- }
-
- {
- AST ast= astRoot.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Modifier modifierNode= ASTNodes.findModifierNode(Modifier.NATIVE, decl.modifiers());
- if (modifierNode != null) {
- rewrite.remove(modifierNode, null);
- }
-
- Block newBody= ast.newBlock();
- rewrite.set(decl, FunctionDeclaration.BODY_PROPERTY, newBody, null);
-
- Expression expr= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
- if (expr != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expr);
- newBody.statements().add(returnStatement);
- }
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_removenative_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
- proposals.add(proposal);
- }
-
- if (decl.getBody() != null) {
- ASTRewrite rewrite= ASTRewrite.create(decl.getAST());
- rewrite.remove(decl.getBody(), null);
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_removebody_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
- proposals.add(proposal2);
- }
-
- }
-
-
-
- public static ASTRewriteCorrectionProposal getMakeTypeAbstractProposal(IJavaScriptUnit cu, TypeDeclaration typeDeclaration, int relevance) {
- AST ast= typeDeclaration.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- Modifier newModifier= ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- rewrite.getListRewrite(typeDeclaration, TypeDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, null);
-
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_addabstract_description, typeDeclaration.getName().getIdentifier());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, relevance, image);
- proposal.addLinkedPosition(rewrite.track(newModifier), true, "modifier"); //$NON-NLS-1$
- return proposal;
- }
-
- public static void addMethodRequiresBodyProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
- AST ast= context.getASTRoot().getAST();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof FunctionDeclaration)) {
- return;
- }
- FunctionDeclaration decl= (FunctionDeclaration) selectedNode;
- {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Modifier modifierNode= ASTNodes.findModifierNode(Modifier.ABSTRACT, decl.modifiers());
- if (modifierNode != null) {
- rewrite.remove(modifierNode, null);
- }
-
- Block body= ast.newBlock();
- rewrite.set(decl, FunctionDeclaration.BODY_PROPERTY, body, null);
-
-
- if (!decl.isConstructor()) {
- Type returnType= decl.getReturnType2();
- Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, decl.getExtraDimensions());
- if (expression != null) {
- ReturnStatement returnStatement= ast.newReturnStatement();
- returnStatement.setExpression(expression);
- body.statements().add(returnStatement);
- }
- }
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_addmissingbody_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 9, image);
-
- proposals.add(proposal);
- }
- {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- Modifier newModifier= ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
- rewrite.getListRewrite(decl, FunctionDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, null);
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_setmethodabstract_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 8, image);
- proposal.addLinkedPosition(rewrite.track(newModifier), true, "modifier"); //$NON-NLS-1$
-
- proposals.add(proposal);
- }
-
- }
-
-
- public static void addNeedToEmulateProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof SimpleName)) {
- return;
- }
-
- IBinding binding= ((SimpleName) selectedNode).resolveBinding();
- if (binding instanceof IVariableBinding) {
- binding= ((IVariableBinding) binding).getVariableDeclaration();
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertofinal_description, binding.getName());
- proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 5, image));
- }
- }
-
- public static void addOverridingDeprecatedMethodProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (!(selectedNode instanceof FunctionDeclaration)) {
- return;
- }
- boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaScriptProject());
- FunctionDeclaration methodDecl= (FunctionDeclaration) selectedNode;
- AST ast= methodDecl.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- JSdoc javadoc= methodDecl.getJavadoc();
- if (javadoc != null || !is50OrHigher) {
- if (!is50OrHigher) {
- javadoc= ast.newJSdoc();
- rewrite.set(methodDecl, FunctionDeclaration.JAVADOC_PROPERTY, javadoc, null);
- }
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_DEPRECATED);
- JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY), newTag, null);
- }
-
- String label= CorrectionMessages.ModifierCorrectionSubProcessor_overrides_deprecated_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 15, image);
- proposals.add(proposal);
- }
-
- private static final String KEY_MODIFIER= "modifier"; //$NON-NLS-1$
-
- private static class ModifierLinkedModeProposal extends LinkedProposalPositionGroup.Proposal {
-
- private final int fModifier;
-
- public ModifierLinkedModeProposal(int modifier, int relevance) {
- super(null, null, relevance);
- fModifier= modifier;
- }
-
- public String getAdditionalProposalInfo() {
- return getDisplayString();
- }
-
- public String getDisplayString() {
- if (fModifier == 0) {
- return CorrectionMessages.ModifierCorrectionSubProcessor_default_visibility_label;
- } else {
- return ModifierKeyword.fromFlagValue(fModifier).toString();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.corext.fix.PositionGroup.Proposal#computeEdits(int, org.eclipse.jface.text.link.LinkedPosition, char, int, org.eclipse.jface.text.link.LinkedModeModel)
- */
- public TextEdit computeEdits(int offset, LinkedPosition currentPosition, char trigger, int stateMask, LinkedModeModel model) throws CoreException {
- try {
- IDocument document= currentPosition.getDocument();
- MultiTextEdit edit= new MultiTextEdit();
- int documentLen= document.getLength();
- if (fModifier == 0) {
- int end= currentPosition.offset + currentPosition.length; // current end position
- int k= end;
- while (k < documentLen && IndentManipulation.isIndentChar(document.getChar(k))) {
- k++;
- }
- // first remove space then replace range (remove space can destroy empty position)
- edit.addChild(new ReplaceEdit(end, k - end, new String())); // remove extra spaces
- edit.addChild(new ReplaceEdit(currentPosition.offset, currentPosition.length, new String()));
- } else {
- // first then replace range the insert space (insert space can destroy empty position)
- edit.addChild(new ReplaceEdit(currentPosition.offset, currentPosition.length, ModifierKeyword.fromFlagValue(fModifier).toString()));
- int end= currentPosition.offset + currentPosition.length; // current end position
- if (end < documentLen && !Character.isWhitespace(document.getChar(end))) {
- edit.addChild(new ReplaceEdit(end, 0, String.valueOf(' '))); // insert extra space
- }
- }
- return edit;
- } catch (BadLocationException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, e.getMessage(), e));
- }
- }
- }
-
- public static void installLinkedVisibilityProposals(LinkedProposalModel linkedProposalModel, ASTRewrite rewrite, List modifiers, boolean inInterface) {
- ASTNode modifier= findVisibilityModifier(modifiers);
- if (modifier != null) {
- int selected= ((Modifier) modifier).getKeyword().toFlagValue();
-
- LinkedProposalPositionGroup positionGroup= linkedProposalModel.getPositionGroup(KEY_MODIFIER, true);
- positionGroup.addPosition(rewrite.track(modifier), false);
- positionGroup.addProposal(new ModifierLinkedModeProposal(selected, 10));
-
- // add all others
- int[] flagValues= inInterface ? new int[] { Modifier.PUBLIC, 0 } : new int[] { Modifier.PUBLIC, 0, Modifier.PROTECTED, Modifier.PRIVATE };
- for (int i= 0; i < flagValues.length; i++) {
- if (flagValues[i] != selected) {
- positionGroup.addProposal(new ModifierLinkedModeProposal(flagValues[i], 9 - i));
- }
- }
- }
- }
-
- private static Modifier findVisibilityModifier(List modifiers) {
- for (int i= 0; i < modifiers.size(); i++) {
- Object curr= modifiers.get(i);
- if (curr instanceof Modifier) {
- Modifier modifier= (Modifier) curr;
- ModifierKeyword keyword= modifier.getKeyword();
- if (keyword == ModifierKeyword.PUBLIC_KEYWORD || keyword == ModifierKeyword.PROTECTED_KEYWORD || keyword == ModifierKeyword.PRIVATE_KEYWORD) {
- return modifier;
- }
- }
- }
- return null;
- }
-
- private static class ProposalParameter {
- public final boolean useSuper;
- public final IJavaScriptUnit compilationUnit;
- public final ASTRewrite astRewrite;
- public final Expression accessNode;
- public final Expression qualifier;
- public final IVariableBinding variableBinding;
-
- public ProposalParameter(boolean useSuper, IJavaScriptUnit compilationUnit, ASTRewrite rewrite, Expression accessNode, Expression qualifier, IVariableBinding variableBinding) {
- this.useSuper= useSuper;
- this.compilationUnit= compilationUnit;
- this.astRewrite= rewrite;
- this.accessNode= accessNode;
- this.qualifier= qualifier;
- this.variableBinding= variableBinding;
- }
- }
-
- public static class SelfEncapsulateFieldProposal extends ChangeCorrectionProposal {
-
- private IField fField;
- private boolean fNoDialog;
-
- public SelfEncapsulateFieldProposal(int relevance, IField field, boolean isReadAccess) {
- super(getDescription(isReadAccess), null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- fField= field;
- fNoDialog= false;
- }
-
- public void setNoDialog(boolean noDialog) {
- fNoDialog= noDialog;
- }
-
- private static String getDescription(boolean getter) {
- if (getter)
- return CorrectionMessages.ModifierCorrectionSubProcessor_creategetterunsingencapsulatefield_description;
- else
- return CorrectionMessages.ModifierCorrectionSubProcessor_createsetterusingencapsulatefield_description;
- }
-
- public void apply(IDocument document) {
- try {
- final SelfEncapsulateFieldRefactoring refactoring= new SelfEncapsulateFieldRefactoring(fField);
- refactoring.setVisibility(Flags.AccPublic);
- refactoring.setConsiderVisibility(false);//private field references are just searched in local file
- if (fNoDialog) {
- IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- final RefactoringExecutionHelper helper= new RefactoringExecutionHelper(refactoring, RefactoringStatus.ERROR, RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES, JavaScriptPlugin.getActiveWorkbenchShell(), window);
- if (Display.getCurrent() != null) {
- try {
- helper.perform(false, false);
- } catch (InterruptedException e) {
- JavaScriptPlugin.log(e);
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- }
- } else {
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- try {
- helper.perform(false, false);
- } catch (InterruptedException e) {
- JavaScriptPlugin.log(e);
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- }
- }
- });
- }
- } else {
- new RefactoringStarter().activate(refactoring, new SelfEncapsulateFieldWizard(refactoring), JavaScriptPlugin.getActiveWorkbenchShell(), "", RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES); //$NON-NLS-1$
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, CorrectionMessages.ModifierCorrectionSubProcessor_encapsulate_field_error_title, CorrectionMessages.ModifierCorrectionSubProcessor_encapsulate_field_error_message);
- }
- }
- }
-
- public static void addGetterSetterProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int relevance) {
- ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot());
- IJavaScriptUnit compilationUnit= context.getCompilationUnit();
- if (coveringNode instanceof SimpleName) {
- SimpleName sn= (SimpleName) coveringNode;
- if (sn.isDeclaration())
- return;
- IVariableBinding variableBinding= (IVariableBinding) sn.resolveBinding();
- if (variableBinding == null || !variableBinding.isField())
- return;
- ChangeCorrectionProposal proposal= getProposal(compilationUnit, sn, variableBinding, relevance);
- if (proposal != null)
- proposals.add(proposal);
- }
- }
-
- private static ChangeCorrectionProposal getProposal(IJavaScriptUnit cu, SimpleName sn, IVariableBinding variableBinding, int relevance) {
- Expression accessNode= sn;
- Expression qualifier= null;
- AST ast= sn.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- boolean useSuper= false;
- boolean writeAccess= ASTResolving.isWriteAccess(sn);
- ASTNode parent= sn.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.QUALIFIED_NAME:
- accessNode= (Expression) parent;
- qualifier= ((QualifiedName) parent).getQualifier();
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- accessNode= (Expression) parent;
- qualifier= ((SuperFieldAccess) parent).getQualifier();
- useSuper= true;
- break;
- }
- ProposalParameter gspc= new ProposalParameter(useSuper, cu, rewrite, accessNode, qualifier, variableBinding);
- if (writeAccess)
- return addSetterProposal(gspc, relevance);
- else
- return addGetterProposal(gspc, relevance);
- }
-
- /**
- * Proposes a getter for this field
- * @param context
- * @param relevance relevance of this proposal
- * @return the proposal if available or null
- */
- private static ChangeCorrectionProposal addGetterProposal(ProposalParameter context, int relevance) {
- IFunctionBinding method= findGetter(context);
- if (method != null) {
- Expression mi= createMethodInvocation(context, method, null);
- context.astRewrite.replace(context.accessNode, mi, null);
-
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_replacewithgetter_description, context.accessNode);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
- return proposal;
- } else {
- IJavaScriptElement element= context.variableBinding.getJavaElement();
- if (element instanceof IField) {
- IField field= (IField) element;
- try {
- if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
- return new SelfEncapsulateFieldProposal(relevance, field, true);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return null;
- }
-
- private static IFunctionBinding findGetter(ProposalParameter context) {
- ITypeBinding returnType= context.variableBinding.getType();
- String getterName= GetterSetterUtil.getGetterName(context.variableBinding, context.compilationUnit.getJavaScriptProject(), null, isBoolean(context));
- ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
- IFunctionBinding getter= Bindings.findMethodInHierarchy(declaringType, getterName, new ITypeBinding[0]);
- if (getter != null && getter.getReturnType().isAssignmentCompatible(returnType) && Modifier.isStatic(getter.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))
- return getter;
- return null;
- }
-
- private static Expression createMethodInvocation(ProposalParameter context, IFunctionBinding method, Expression argument) {
- AST ast= context.astRewrite.getAST();
- Expression qualifier= context.qualifier;
- if (context.useSuper) {
- SuperMethodInvocation invocation= ast.newSuperMethodInvocation();
- invocation.setName(ast.newSimpleName(method.getName()));
- if (qualifier != null)
- invocation.setQualifier((Name) context.astRewrite.createCopyTarget(qualifier));
- if (argument != null)
- invocation.arguments().add(argument);
- return invocation;
- } else {
- FunctionInvocation invocation= ast.newFunctionInvocation();
- invocation.setName(ast.newSimpleName(method.getName()));
- if (qualifier != null)
- invocation.setExpression((Expression) context.astRewrite.createCopyTarget(qualifier));
- if (argument != null)
- invocation.arguments().add(argument);
- return invocation;
- }
- }
-
- /**
- * Proposes a setter for this field
- * @param context
- * @param relevance relevance of this proposal
- * @return the proposal if available or null
- */
- private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
- boolean isBoolean= isBoolean(context);
- String setterName= GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaScriptProject(), null, isBoolean);
- ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
- IFunctionBinding method= Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
- if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
- Expression assignedValue= getAssignedValue(context);
- if (assignedValue == null)
- return null; //we don't know how to handle those cases.
- Expression mi= createMethodInvocation(context, method, assignedValue);
- context.astRewrite.replace(context.accessNode.getParent(), mi, null);
-
- String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_replacewithsetter_description, context.accessNode);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
- return proposal;
- } else {
- IJavaScriptElement element= context.variableBinding.getJavaElement();
- if (element instanceof IField) {
- IField field= (IField) element;
- try {
- if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
- return new SelfEncapsulateFieldProposal(relevance, field, false);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return null;
- }
-
- private static boolean isBoolean(ProposalParameter context) {
- AST ast= context.astRewrite.getAST();
- boolean isBoolean= ast.resolveWellKnownType("boolean") == context.variableBinding.getType(); //$NON-NLS-1$
- if (!isBoolean)
- isBoolean= ast.resolveWellKnownType("java.lang.Boolean") == context.variableBinding.getType(); //$NON-NLS-1$
- return isBoolean;
- }
-
- private static Expression getAssignedValue(ProposalParameter context) {
- ASTNode parent= context.accessNode.getParent();
- AST ast= context.astRewrite.getAST();
- switch (parent.getNodeType()) {
- case ASTNode.ASSIGNMENT:
- Assignment assignment= ((Assignment) parent);
- Expression rightHandSide= assignment.getRightHandSide();
- Expression copiedRightOp= (Expression) context.astRewrite.createCopyTarget(rightHandSide);
- if (isNotInBlock(parent))
- break;
- if (assignment.getOperator() == Operator.ASSIGN) {
- ITypeBinding rightHandSideType= rightHandSide.resolveTypeBinding();
- copiedRightOp= checkForNarrowCast(context, copiedRightOp, true, rightHandSideType);
- return copiedRightOp;
- }
- IFunctionBinding getter= findGetter(context);
- if (getter != null) {
- InfixExpression infix= ast.newInfixExpression();
- infix.setLeftOperand(createMethodInvocation(context, getter, null));
- infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
- infix.setRightOperand(copiedRightOp);
- ITypeBinding infixType= infix.resolveTypeBinding();
- return checkForNarrowCast(context, infix, true, infixType);
- }
- break;
- case ASTNode.POSTFIX_EXPRESSION:
- PostfixExpression po= (PostfixExpression) parent;
- if (isNotInBlock(parent))
- break;
- InfixExpression.Operator postfixOp= null;
- if (po.getOperator() == PostfixExpression.Operator.INCREMENT)
- postfixOp= InfixExpression.Operator.PLUS;
- if (po.getOperator() == PostfixExpression.Operator.DECREMENT)
- postfixOp= InfixExpression.Operator.MINUS;
- if (postfixOp == null)
- break;
- return createInfixInvocationFromPostPrefixExpression(context, postfixOp);
- case ASTNode.PREFIX_EXPRESSION:
- PrefixExpression pe= (PrefixExpression) parent;
- if (isNotInBlock(parent))
- break;
- InfixExpression.Operator prefixOp= null;
- if (pe.getOperator() == PrefixExpression.Operator.INCREMENT)
- prefixOp= InfixExpression.Operator.PLUS;
- if (pe.getOperator() == PrefixExpression.Operator.DECREMENT)
- prefixOp= InfixExpression.Operator.MINUS;
- if (prefixOp == null)
- break;
- return createInfixInvocationFromPostPrefixExpression(context, prefixOp);
- }
-
- return null;
- }
-
- private static boolean isNotInBlock(ASTNode parent) {
- ASTNode grandParent= parent.getParent();
- return (grandParent.getNodeType() != ASTNode.EXPRESSION_STATEMENT) || (grandParent.getParent().getNodeType() != ASTNode.BLOCK);
- }
-
- private static Expression createInfixInvocationFromPostPrefixExpression(ProposalParameter context, InfixExpression.Operator operator) {
- AST ast= context.astRewrite.getAST();
- IFunctionBinding getter= findGetter(context);
- if (getter != null) {
- InfixExpression infix= ast.newInfixExpression();
- infix.setLeftOperand(createMethodInvocation(context, getter, null));
- infix.setOperator(operator);
- NumberLiteral number= ast.newNumberLiteral();
- number.setToken("1"); //$NON-NLS-1$
- infix.setRightOperand(number);
- ITypeBinding infixType= infix.resolveTypeBinding();
- return checkForNarrowCast(context, infix, true, infixType);
- }
- return null;
- }
-
- /**
- *
- * @param context general context
- * @param expression the right handside
- * @param parenthesize if true places () around expression
- * @param expressionType the type of the right handside. Can be null
- * @return the casted expression if necessary
- */
- private static Expression checkForNarrowCast(ProposalParameter context, Expression expression, boolean parenthesize, ITypeBinding expressionType) {
- PrimitiveType castTo= null;
- ITypeBinding type= context.variableBinding.getType();
- if (type.isEqualTo(expressionType))
- return expression; //no cast for same type
- AST ast= context.astRewrite.getAST();
- if (JavaModelUtil.is50OrHigher(context.compilationUnit.getJavaScriptProject())) {
- if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
- if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
- if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
- }
- if (ast.resolveWellKnownType("char").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
- if (ast.resolveWellKnownType("byte").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
- if (ast.resolveWellKnownType("short").isEqualTo(type)) //$NON-NLS-1$
- castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
- return expression;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NameMatcher.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NameMatcher.java
deleted file mode 100644
index 01463356..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NameMatcher.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-public class NameMatcher {
-
- /**
- * Returns a similarity value of the two names.
- * The range of is from 0 to 256. no similarity is negative
- */
- public static boolean isSimilarName(String name1, String name2) {
- return getSimilarity(name1, name2) >= 0;
- }
-
- /**
- * Returns a similarity value of the two names.
- * The range of is from 0 to 256. no similarity is negative
- */
- public static int getSimilarity(String name1, String name2) {
- if (name1.length() > name2.length()) {
- String tmp= name1;
- name1= name2;
- name2= tmp;
- }
- int name1len= name1.length();
- int name2len= name2.length();
-
- int nMatched= 0;
-
- int i= 0;
- while (i < name1len && isSimilarChar(name1.charAt(i), name2.charAt(i))) {
- i++;
- nMatched++;
- }
-
- int k= name1len;
- int diff= name2len - name1len;
- while (k > i && isSimilarChar(name1.charAt(k - 1), name2.charAt(k + diff - 1))) {
- k--;
- nMatched++;
- }
-
- if (nMatched == name2len) {
- return 200;
- }
-
- if (name2len - nMatched > nMatched) {
- return -1;
- }
-
- int tolerance= name2len / 4 + 1;
- return (tolerance - (k - i)) * 256 / tolerance;
- }
-
- private static boolean isSimilarChar(char ch1, char ch2) {
- return Character.toLowerCase(ch1) == Character.toLowerCase(ch2);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java
deleted file mode 100644
index 000e4361..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt;
- * IBM Corporation - updates
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewClassCreationWizard;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.wizards.NewTypeWizardPage;
-
-/**
- * This proposal is listed in the corrections list for a "type not found" problem.
- * It offers to create a new type by running the class/interface wizard.
- * If selected, this proposal will open a {@link NewClassCreationWizard},
- * {@link NewInterfaceCreationWizard}, {@link NewEnumCreationWizard} or {@link NewAnnotationCreationWizard}.
- *
- * @see UnresolvedElementsSubProcessor#getTypeProposals(org.eclipse.wst.jsdt.ui.text.java.IInvocationContext, org.eclipse.wst.jsdt.ui.text.java.IProblemLocation, java.util.Collection)
- */
-
-public class NewCUCompletionUsingWizardProposal extends ChangeCorrectionProposal {
-
- public static final int K_CLASS= 1;
- public static final int K_INTERFACE= 2;
- public static final int K_ENUM= 3;
- public static final int K_ANNOTATION= 4;
-
- private Name fNode;
- private IJavaScriptUnit fCompilationUnit;
- private int fTypeKind;
- private IJavaScriptElement fTypeContainer; // IType or IPackageFragment
- private String fTypeNameWithParameters;
- private IType fCreatedType;
-
- private boolean fShowDialog;
-
- public NewCUCompletionUsingWizardProposal(IJavaScriptUnit cu, Name node, int typeKind, IJavaScriptElement typeContainer, int severity) {
- super("", null, severity, null); //$NON-NLS-1$
-
- fCompilationUnit= cu;
- fNode= node;
- fTypeKind= typeKind;
- fTypeContainer= typeContainer;
- fTypeNameWithParameters= getTypeName(typeKind, node);
-
- fCreatedType= null;
-
- String containerName= ASTNodes.getQualifier(node);
- String typeName= fTypeNameWithParameters;
- boolean isInnerType= typeContainer instanceof IType;
- switch (typeKind) {
- case K_CLASS:
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS));
- if (isInnerType) {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerclass_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerclass_intype_description, new String[] { typeName, containerName }));
- }
- } else {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createclass_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createclass_inpackage_description, new String[] { typeName, containerName }));
- }
- }
- break;
- case K_INTERFACE:
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE));
- if (isInnerType) {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerinterface_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerinterface_intype_description, new String[] { typeName, containerName }));
- }
- } else {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinterface_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinterface_inpackage_description, new String[] { typeName, containerName }));
- }
- }
- break;
- case K_ENUM:
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ENUM));
- if (isInnerType) {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerenum_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerenum_intype_description, new String[] { typeName, containerName }));
- }
- } else {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createenum_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createenum_inpackage_description, new String[] { typeName, containerName }));
- }
- }
- break;
- case K_ANNOTATION:
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ANNOTATION));
- if (isInnerType) {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerannotation_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinnerannotation_intype_description, new String[] { typeName, containerName }));
- }
- } else {
- if (containerName.length() == 0) {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createannotation_description, typeName));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.NewCUCompletionUsingWizardProposal_createannotation_inpackage_description, new String[] { typeName, containerName }));
- }
- }
- break;
- default:
- throw new IllegalArgumentException("Unknown type kind"); //$NON-NLS-1$
- }
- fShowDialog= true;
- }
-
- private static String getTypeName(int typeKind, Name node) {
- String name= ASTNodes.getSimpleNameIdentifier(node);
- return name;
- }
-
-
- public void apply(IDocument document) {
- NewElementWizard wizard= null;
- wizard.init(JavaScriptPlugin.getDefault().getWorkbench(), new StructuredSelection(fCompilationUnit));
-
- IType createdType= null;
-
- if (fShowDialog) {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- dialog.getShell().setText(CorrectionMessages.NewCUCompletionUsingWizardProposal_dialogtitle);
-
- configureWizardPage(wizard);
- if (dialog.open() == Window.OK) {
- createdType= (IType) wizard.getCreatedElement();
- }
- } else {
- wizard.addPages();
- try {
- NewTypeWizardPage page= configureWizardPage(wizard);
- page.createType(null);
- createdType= page.getCreatedType();
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (InterruptedException e) {
- }
- }
-
- if (createdType != null) {
- IJavaScriptElement container= createdType.getParent();
- if (container instanceof IJavaScriptUnit) {
- container= container.getParent();
- }
- if (!container.equals(fTypeContainer)) {
- // add import
- try {
- ImportRewrite rewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
- rewrite.addImport(createdType.getFullyQualifiedName('.'));
- JavaModelUtil.applyEdit(fCompilationUnit, rewrite.rewriteImports(null), false, null);
- } catch (CoreException e) {
- }
- }
- fCreatedType= createdType;
- }
-
- }
-
- private NewTypeWizardPage configureWizardPage(NewElementWizard wizard) {
- IWizardPage[] pages= wizard.getPages();
- Assert.isTrue(pages.length > 0 && pages[0] instanceof NewTypeWizardPage);
-
- NewTypeWizardPage page= (NewTypeWizardPage) pages[0];
- fillInWizardPageName(page);
- fillInWizardPageSuperTypes(page);
- return page;
- }
-
- /**
- * Fill-in the "Package" and "Name" fields.
- * @param page the wizard page.
- */
- private void fillInWizardPageName(NewTypeWizardPage page) {
- // allow to edit when there are type parameters
- page.setTypeName(fTypeNameWithParameters, fTypeNameWithParameters.indexOf('<') != -1);
-
- boolean isInEnclosingType= fTypeContainer instanceof IType;
- if (isInEnclosingType) {
- page.setEnclosingType((IType) fTypeContainer, true);
- } else {
- page.setPackageFragment((IPackageFragment) fTypeContainer, true);
- }
- page.setEnclosingTypeSelection(isInEnclosingType, true);
- }
-
- /**
- * Fill-in the "Super Class" and "Super Interfaces" fields.
- * @param page the wizard page.
- */
- private void fillInWizardPageSuperTypes(NewTypeWizardPage page) {
- ITypeBinding type= getPossibleSuperTypeBinding(fNode);
- type= Bindings.normalizeTypeBinding(type);
- if (type != null) {
- if (type.isArray()) {
- type= type.getElementType();
- }
- if (type.isTopLevel() || type.isMember()) {
- if (type.isClass() && (fTypeKind == K_CLASS)) {
- page.setSuperClass(type.getQualifiedName(), true);
- }
- }
- }
- }
-
- private ITypeBinding getPossibleSuperTypeBinding(ASTNode node) {
- if (fTypeKind == K_ANNOTATION) {
- return null;
- }
-
- AST ast= node.getAST();
- node= ASTNodes.getNormalizedNode(node);
- ASTNode parent= node.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.FUNCTION_DECLARATION:
- if (node.getLocationInParent() == FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY) {
- return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
- }
- break;
- case ASTNode.THROW_STATEMENT :
- return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
- case ASTNode.SINGLE_VARIABLE_DECLARATION:
- if (parent.getLocationInParent() == CatchClause.EXCEPTION_PROPERTY) {
- return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
- }
- break;
- case ASTNode.VARIABLE_DECLARATION_STATEMENT:
- case ASTNode.FIELD_DECLARATION:
- return null; // no guessing for LHS types, cannot be a supertype of a known type
- }
- return ASTResolving.guessBindingForTypeReference(node);
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- StringBuffer buf= new StringBuffer();
- switch (fTypeKind) {
- case K_CLASS:
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_createclass_info);
- break;
- case K_INTERFACE:
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_createinterface_info);
- break;
- case K_ENUM:
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_createenum_info);
- break;
- case K_ANNOTATION:
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_createannotation_info);
- break;
- }
- buf.append("<br>"); //$NON-NLS-1$
- buf.append("<br>"); //$NON-NLS-1$
- if (fTypeContainer instanceof IType) {
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_tooltip_enclosingtype);
- } else {
- buf.append(CorrectionMessages.NewCUCompletionUsingWizardProposal_tooltip_package);
- }
- buf.append(" <b>"); //$NON-NLS-1$
- buf.append(JavaScriptElementLabels.getElementLabel(fTypeContainer, JavaScriptElementLabels.T_FULLY_QUALIFIED));
- buf.append("</b><br>"); //$NON-NLS-1$
- buf.append("public "); //$NON-NLS-1$
-
-
- switch (fTypeKind) {
- case K_CLASS:
- buf.append("class <b>"); //$NON-NLS-1$
- break;
- case K_INTERFACE:
- buf.append("interface <b>"); //$NON-NLS-1$
- break;
- case K_ENUM:
- buf.append("enum <b>"); //$NON-NLS-1$
- break;
- case K_ANNOTATION:
- buf.append("@interface <b>"); //$NON-NLS-1$
- break;
- }
- nameToHTML(fTypeNameWithParameters, buf);
-
- ITypeBinding superclass= getPossibleSuperTypeBinding(fNode);
- if (superclass != null) {
- if (superclass.isClass()) {
- if (fTypeKind == K_CLASS) {
- buf.append("</b> extends <b>"); //$NON-NLS-1$
- nameToHTML(BindingLabelProvider.getBindingLabel(superclass, BindingLabelProvider.DEFAULT_TEXTFLAGS), buf);
- }
- } else {
- if (fTypeKind == K_INTERFACE) {
- buf.append("</b> extends <b>"); //$NON-NLS-1$
- } else {
- buf.append("</b> implements <b>"); //$NON-NLS-1$
- }
- nameToHTML(BindingLabelProvider.getBindingLabel(superclass, BindingLabelProvider.DEFAULT_TEXTFLAGS), buf);
- }
- }
- buf.append("</b> {<br>}<br>"); //$NON-NLS-1$
- return buf.toString();
- }
-
- private void nameToHTML(String name, StringBuffer buf) {
- for (int i= 0; i < name.length(); i++) {
- char ch= name.charAt(i);
- if (ch == '>') {
- buf.append("&gt;"); //$NON-NLS-1$
- } else if (ch == '<') {
- buf.append("&lt;"); //$NON-NLS-1$
- } else {
- buf.append(ch);
- }
- }
- }
-
- /**
- * Returns the showDialog.
- * @return boolean
- */
- public boolean isShowDialog() {
- return fShowDialog;
- }
-
- /**
- * Sets the showDialog.
- * @param showDialog The showDialog to set
- */
- public void setShowDialog(boolean showDialog) {
- fShowDialog= showDialog;
- }
-
- public IType getCreatedType() {
- return fCreatedType;
- }
-
-
- public int getTypeKind() {
- return fTypeKind;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewDefiningMethodProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewDefiningMethodProposal.java
deleted file mode 100644
index 20e02544..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewDefiningMethodProposal.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-
-/**
- *
- */
-public class NewDefiningMethodProposal extends AbstractMethodCompletionProposal {
-
- private final IFunctionBinding fMethod;
- private final String[] fParamNames;
-
- public NewDefiningMethodProposal(String label, IJavaScriptUnit targetCU, ASTNode invocationNode, ITypeBinding binding, IFunctionBinding method, String[] paramNames, int relevance) {
- super(label,targetCU,invocationNode,binding,relevance,null);
- fMethod= method;
- fParamNames= paramNames;
-
- ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, method.getModifiers());
- setImage(JavaScriptPlugin.getImageDescriptorRegistry().get(desc));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#isConstructor()
- */
- protected boolean isConstructor() {
- return fMethod.isConstructor();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#addNewParameters(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite, java.util.List, java.util.List)
- */
- protected void addNewParameters(ASTRewrite rewrite, List takenNames, List params) throws CoreException {
- AST ast= rewrite.getAST();
- ImportRewrite importRewrite= getImportRewrite();
- ITypeBinding[] bindings= fMethod.getParameterTypes();
-
- IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- String[][] paramNames= StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);
-
- for (int i= 0; i < bindings.length; i++) {
- ITypeBinding curr= bindings[i];
-
- String[] proposedNames= paramNames[i];
-
- SingleVariableDeclaration newParam= ast.newSingleVariableDeclaration();
-
- newParam.setType(importRewrite.addImport(curr, ast));
- newParam.setName(ast.newSimpleName(proposedNames[0]));
-
- params.add(newParam);
-
- String groupId= "arg_name_" + i; //$NON-NLS-1$
- addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);
-
- for (int k= 0; k < proposedNames.length; k++) {
- addLinkedPositionProposal(groupId, proposedNames[k], null);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#getNewName()
- */
- protected SimpleName getNewName(ASTRewrite rewrite) {
- AST ast= rewrite.getAST();
- SimpleName nameNode= ast.newSimpleName(fMethod.getName());
- return nameNode;
- }
-
- private int evaluateModifiers() {
- int modifiers= fMethod.getModifiers();
- if (Modifier.isPrivate(modifiers)) {
- modifiers |= Modifier.PROTECTED;
- }
- return modifiers & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.ABSTRACT | Modifier.STRICTFP);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#addNewModifiers(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite, java.util.List)
- */
- protected void addNewModifiers(ASTRewrite rewrite, ASTNode targetTypeDecl, List modifiers) {
- modifiers.addAll(rewrite.getAST().newModifiers(evaluateModifiers()));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#getNewMethodType(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite)
- */
- protected Type getNewMethodType(ASTRewrite rewrite) throws CoreException {
- return getImportRewrite().addImport(fMethod.getReturnType(), rewrite.getAST());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewMethodCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewMethodCompletionProposal.java
deleted file mode 100644
index 3f98d5f1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewMethodCompletionProposal.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-
-public class NewMethodCompletionProposal extends AbstractMethodCompletionProposal {
-
- private static final String KEY_NAME= "name"; //$NON-NLS-1$
- private static final String KEY_TYPE= "type"; //$NON-NLS-1$
-
- private List fArguments;
-
- // invocationNode is FunctionInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation
- public NewMethodCompletionProposal(String label, IJavaScriptUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) {
- super(label, targetCU, invocationNode, binding, relevance, image);
- fArguments= arguments;
- }
-
- private int evaluateModifiers(ASTNode targetTypeDecl) {
- ASTNode invocationNode= getInvocationNode();
- if (invocationNode instanceof FunctionInvocation) {
- int modifiers= 0;
- Expression expression= ((FunctionInvocation)invocationNode).getExpression();
- if (expression != null) {
- if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
- modifiers |= Modifier.STATIC;
- }
- } else if (ASTResolving.isInStaticContext(invocationNode)) {
- modifiers |= Modifier.STATIC;
- }
- ASTNode node= ASTResolving.findParentType(invocationNode);
- if (targetTypeDecl.equals(node)) {
- modifiers |= Modifier.PRIVATE;
- } else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
- modifiers |= Modifier.PROTECTED;
- if (ASTResolving.isInStaticContext(node)) {
- modifiers |= Modifier.STATIC;
- }
- } else {
- modifiers |= Modifier.PUBLIC;
- }
- return modifiers;
- }
- return Modifier.PUBLIC;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#addNewModifiers(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite, java.util.List)
- */
- protected void addNewModifiers(ASTRewrite rewrite, ASTNode targetTypeDecl, List modifiers) {
- modifiers.addAll(rewrite.getAST().newModifiers(evaluateModifiers(targetTypeDecl)));
- ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, modifiers, false);
- }
-
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#isConstructor()
- */
- protected boolean isConstructor() {
- ASTNode node= getInvocationNode();
-
- return node.getNodeType() != ASTNode.FUNCTION_INVOCATION && node.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#getNewName(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite)
- */
- protected SimpleName getNewName(ASTRewrite rewrite) {
- ASTNode invocationNode= getInvocationNode();
- String name;
- if (invocationNode instanceof FunctionInvocation) {
- name= ((FunctionInvocation)invocationNode).getName().getIdentifier();
- } else if (invocationNode instanceof SuperMethodInvocation) {
- name= ((SuperMethodInvocation)invocationNode).getName().getIdentifier();
- } else {
- name= getSenderBinding().getName(); // name of the class
- }
- AST ast= rewrite.getAST();
- SimpleName newNameNode= ast.newSimpleName(name);
- addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);
-
- ASTNode invocationName= getInvocationNameNode();
- if (invocationName != null && invocationName.getAST() == ast) { // in the same CU
- addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME);
- }
- return newNameNode;
- }
-
- private ASTNode getInvocationNameNode() {
- ASTNode node= getInvocationNode();
- if (node instanceof FunctionInvocation) {
- return ((FunctionInvocation)node).getName();
- } else if (node instanceof SuperMethodInvocation) {
- return ((SuperMethodInvocation)node).getName();
- } else if (node instanceof ClassInstanceCreation) {
- Type type= ((ClassInstanceCreation)node).getType();
- return type;
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#getNewMethodType(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite)
- */
- protected Type getNewMethodType(ASTRewrite rewrite) throws CoreException {
- ASTNode node= getInvocationNode();
- AST ast= rewrite.getAST();
-
- Type newTypeNode= null;
- ITypeBinding[] otherProposals= null;
-
- if (node.getParent() instanceof FunctionInvocation) {
- FunctionInvocation parent= (FunctionInvocation) node.getParent();
- if (parent.getExpression() == node) {
- ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), parent.getName().getIdentifier(), parent.arguments(), getSenderBinding());
- if (bindings.length > 0) {
- newTypeNode= getImportRewrite().addImport(bindings[0], ast);
- otherProposals= bindings;
- }
- }
- }
- if (newTypeNode == null) {
- ITypeBinding binding= ASTResolving.guessBindingForReference(node);
- if (binding != null) {
- newTypeNode= getImportRewrite().addImport(binding, ast);
- } else {
- ASTNode parent= node.getParent();
- if (parent instanceof ExpressionStatement) {
- return null;
- }
- newTypeNode= ASTResolving.guessTypeForReference(ast, node);
- if (newTypeNode == null) {
- newTypeNode= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
- }
- }
- }
-
- addLinkedPosition(rewrite.track(newTypeNode), false, KEY_TYPE);
- if (otherProposals != null) {
- for (int i= 0; i < otherProposals.length; i++) {
- addLinkedPositionProposal(KEY_TYPE, otherProposals[i]);
- }
- }
-
- return newTypeNode;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#addNewParameters(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite, java.util.List, java.util.List)
- */
- protected void addNewParameters(ASTRewrite rewrite, List takenNames, List params) throws CoreException {
- AST ast= rewrite.getAST();
-
- List arguments= fArguments;
-
- for (int i= 0; i < arguments.size(); i++) {
- Expression elem= (Expression) arguments.get(i);
- SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
-
- // argument type
- String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
- Type type= evaluateParameterType(ast, elem, argTypeKey);
- param.setType(type);
-
- // argument name
- String argNameKey= "arg_name_" + i; //$NON-NLS-1$
- String name= evaluateParameterName(takenNames, elem, type, argNameKey);
- param.setName(ast.newSimpleName(name));
-
- params.add(param);
-
- addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey);
- addLinkedPosition(rewrite.track(param.getName()), false, argNameKey);
- }
- }
-
- private Type evaluateParameterType(AST ast, Expression elem, String key) throws CoreException {
- ITypeBinding binding= Bindings.normalizeTypeBinding(elem.resolveTypeBinding());
- if (binding != null) {
- ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
- for (int i= 0; i < typeProposals.length; i++) {
- addLinkedPositionProposal(key, typeProposals[i]);
- }
- return getImportRewrite().addImport(binding, ast);
- }
- return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
- }
-
- private String evaluateParameterName(List takenNames, Expression argNode, Type type, String key) {
- IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- String[] names= StubUtility.getVariableNameSuggestions(StubUtility.PARAMETER, project, type, argNode, takenNames);
- for (int i= 0; i < names.length; i++) {
- addLinkedPositionProposal(key, names[i], null);
- }
- String favourite= names[0];
- takenNames.add(favourite);
- return favourite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.AbstractMethodCompletionProposal#addNewExceptions(org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite, java.util.List)
- */
- protected void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewVariableCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewVariableCompletionProposal.java
deleted file mode 100644
index a1db2d64..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewVariableCompletionProposal.java
+++ /dev/null
@@ -1,483 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-
-public class NewVariableCompletionProposal extends LinkedCorrectionProposal {
-
- public static final int LOCAL= 1;
- public static final int FIELD= 2;
- public static final int PARAM= 3;
-
- public static final int CONST_FIELD= 4;
- public static final int ENUM_CONST= 5;
-
- private static final String KEY_NAME= "name"; //$NON-NLS-1$
- private static final String KEY_TYPE= "type"; //$NON-NLS-1$
- private static final String KEY_INITIALIZER= "initializer"; //$NON-NLS-1$
-
- final private int fVariableKind;
- final private SimpleName fOriginalNode;
- final private ITypeBinding fSenderBinding;
-
- public NewVariableCompletionProposal(String label, IJavaScriptUnit cu, int variableKind, SimpleName node, ITypeBinding senderBinding, int relevance, Image image) {
- super(label, cu, null, relevance, image);
- if (senderBinding == null) {
- Assert.isTrue(variableKind == PARAM || variableKind == LOCAL);
- } else {
- Assert.isTrue(Bindings.isDeclarationBinding(senderBinding));
- }
-
- fVariableKind= variableKind;
- fOriginalNode= node;
- fSenderBinding= senderBinding;
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- JavaScriptUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode);
- switch (fVariableKind) {
- case PARAM:
- return doAddParam(cu);
- case FIELD:
- case CONST_FIELD:
- return doAddField(cu);
- case LOCAL:
- return doAddLocal(cu);
- default:
- throw new IllegalArgumentException("Unsupported variable kind: " + fVariableKind); //$NON-NLS-1$
- }
- }
-
- private ASTRewrite doAddParam(JavaScriptUnit cu) throws CoreException {
- AST ast= cu.getAST();
- SimpleName node= fOriginalNode;
-
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) decl;
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- ImportRewrite imports= createImportRewrite((JavaScriptUnit) decl.getRoot());
-
- SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
- newDecl.setType(evaluateVariableType(ast, imports, methodDeclaration.resolveBinding()));
- newDecl.setName(ast.newSimpleName(node.getIdentifier()));
-
- ListRewrite listRewriter= rewrite.getListRewrite(decl, FunctionDeclaration.PARAMETERS_PROPERTY);
- listRewriter.insertLast(newDecl, null);
-
- addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
- addLinkedPosition(rewrite.track(node), true, KEY_NAME);
- addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);
-
- // add javadoc tag
- JSdoc javadoc= methodDeclaration.getJavadoc();
- if (javadoc != null) {
- HashSet leadingNames= new HashSet();
- for (Iterator iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
- SingleVariableDeclaration curr= (SingleVariableDeclaration) iter.next();
- leadingNames.add(curr.getName().getIdentifier());
- }
- SimpleName newTagRef= ast.newSimpleName(node.getIdentifier());
-
- TagElement newTagElement= ast.newTagElement();
- newTagElement.setTagName(TagElement.TAG_PARAM);
- newTagElement.fragments().add(newTagRef);
- TextElement commentStart= ast.newTextElement();
- newTagElement.fragments().add(commentStart);
-
- addLinkedPosition(rewrite.track(newTagRef), true, KEY_NAME);
- addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
-
- ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY);
- JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
- }
-
- return rewrite;
- }
- return null;
- }
-
- private boolean isAssigned(Statement statement, SimpleName name) {
- if (statement instanceof ExpressionStatement) {
- ExpressionStatement exstat= (ExpressionStatement) statement;
- if (exstat.getExpression() instanceof Assignment) {
- Assignment assignment= (Assignment) exstat.getExpression();
- return assignment.getLeftHandSide() == name;
- }
- }
- return false;
- }
-
- private boolean isForStatementInit(Statement statement, SimpleName name) {
- if (statement instanceof ForStatement) {
- ForStatement forStatement= (ForStatement) statement;
- List list = forStatement.initializers();
- if (list.size() == 1 && list.get(0) instanceof Assignment) {
- Assignment assignment= (Assignment) list.get(0);
- return assignment.getLeftHandSide() == name;
- }
- }
- return false;
- }
-
-
- private ASTRewrite doAddLocal(JavaScriptUnit cu) throws CoreException {
- AST ast= cu.getAST();
-
- ASTNode body;
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(fOriginalNode);
- IBinding targetContext= null;
- if (decl instanceof FunctionDeclaration) {
- body= (((FunctionDeclaration) decl).getBody());
- targetContext= ((FunctionDeclaration) decl).resolveBinding();
- } else if (decl instanceof Initializer) {
- body= (((Initializer) decl).getBody());
- targetContext= Bindings.getBindingOfParentType(decl);
- } else if (decl ==null ) {
- body= cu;
- targetContext= cu.resolveBinding();
- } else {
- return null;
- }
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- ImportRewrite imports= createImportRewrite(cu);
-
- SimpleName[] names= getAllReferences(body);
- ASTNode dominant= getDominantNode(names);
-
- Statement dominantStatement= ASTResolving.findParentStatement(dominant);
- if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
- dominantStatement= (Statement) dominantStatement.getParent();
- }
-
- SimpleName node= names[0];
-
- if (isAssigned(dominantStatement, node)) {
- // x = 1; -> int x = 1;
- Assignment assignment= (Assignment) node.getParent();
-
- // trick to avoid comment removal around the statement: keep the expression statement
- // and replace the assignment with an VariableDeclarationExpression
- VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
- VariableDeclarationExpression newDecl= ast.newVariableDeclarationExpression(newDeclFrag);
- newDecl.setType(evaluateVariableType(ast, imports, targetContext));
-
- Expression placeholder= (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
- newDeclFrag.setInitializer(placeholder);
- newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
- rewrite.replace(assignment, newDecl, null);
-
- addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
- addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
-
- setEndPosition(rewrite.track(assignment.getParent()));
-
- return rewrite;
- } else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
- // for (x = 1;;) ->for (int x = 1;;)
-
- Assignment assignment= (Assignment) node.getParent();
-
- VariableDeclarationFragment frag= ast.newVariableDeclarationFragment();
- VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag);
- frag.setName(ast.newSimpleName(node.getIdentifier()));
- Expression placeholder= (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
- frag.setInitializer(placeholder);
- expression.setType(evaluateVariableType(ast, imports, targetContext));
-
- rewrite.replace(assignment, expression, null);
-
- addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
- addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
-
- setEndPosition(rewrite.track(expression));
-
- return rewrite;
- }
- // foo(x) -> int x; foo(x)
-
- VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
- VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag);
-
- newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
- newDecl.setType(evaluateVariableType(ast, imports, targetContext));
-// newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
-
- addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
- addLinkedPosition(rewrite.track(node), true, KEY_NAME);
- addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
-
- Statement statement= dominantStatement;
- List list= ASTNodes.getContainingList(statement);
- while (list == null && statement.getParent() instanceof Statement) { // parent must be if, for or while
- statement= (Statement) statement.getParent();
- list= ASTNodes.getContainingList(statement);
- }
- if (list != null) {
- ASTNode parent= statement.getParent();
- StructuralPropertyDescriptor childProperty= statement.getLocationInParent();
- if (childProperty.isChildListProperty()) {
- rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
- return rewrite;
- } else {
- return null;
- }
- }
- return rewrite;
- }
-
- private SimpleName[] getAllReferences(ASTNode body) {
- SimpleName[] names= LinkedNodeFinder.findByProblems(body, fOriginalNode);
- if (names == null) {
- return new SimpleName[] { fOriginalNode };
- }
- if (names.length > 1) {
- Arrays.sort(names, new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((SimpleName) o1).getStartPosition() - ((SimpleName) o2).getStartPosition();
- }
- });
- }
- return names;
- }
-
-
- private ASTNode getDominantNode(SimpleName[] names) {
- ASTNode dominator= names[0]; //ASTResolving.findParentStatement(names[0]);
- for (int i= 1; i < names.length; i++) {
- ASTNode curr= names[i];// ASTResolving.findParentStatement(names[i]);
- if (curr != dominator) {
- ASTNode parent= getCommonParent(curr, dominator);
-
- if (curr.getStartPosition() < dominator.getStartPosition()) {
- dominator= curr;
- }
- while (dominator.getParent() != parent) {
- dominator= dominator.getParent();
- }
- }
- }
- int parentKind= dominator.getParent().getNodeType();
- if (parentKind != ASTNode.BLOCK && parentKind != ASTNode.FOR_STATEMENT && parentKind != ASTNode.FOR_IN_STATEMENT) {
- return dominator.getParent();
- }
- return dominator;
- }
-
- private ASTNode getCommonParent(ASTNode node1, ASTNode node2) {
- ASTNode parent= node1.getParent();
- while (parent != null && !ASTNodes.isParent(node2, parent)) {
- parent= parent.getParent();
- }
- return parent;
- }
-
- private ASTRewrite doAddField(JavaScriptUnit astRoot) throws CoreException {
- SimpleName node= fOriginalNode;
- boolean isInDifferentCU= false;
-
- ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
- if (newTypeDecl == null) {
- astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
- newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
- isInDifferentCU= true;
- }
- ImportRewrite imports= createImportRewrite(astRoot);
-
- if (newTypeDecl != null) {
- AST ast= newTypeDecl.getAST();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
- fragment.setName(ast.newSimpleName(node.getIdentifier()));
-
- Type type= evaluateVariableType(ast, imports, fSenderBinding);
-
- FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
- newDecl.setType(type);
- newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
-
- if (fVariableKind == CONST_FIELD) {
- fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
- }
-
- ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
- List decls= (List) newTypeDecl.getStructuralProperty(property);
-
- int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();
-
- int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);
-
- ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
- listRewriter.insertAt(newDecl, insertIndex, null);
-
- ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false);
-
- addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
- if (!isInDifferentCU) {
- addLinkedPosition(rewrite.track(node), true, KEY_NAME);
- }
- addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);
-
- if (fragment.getInitializer() != null) {
- addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
- }
- return rewrite;
- }
- return null;
- }
-
- private int findFieldInsertIndex(List decls, FieldDeclaration newDecl, int maxOffset) {
- if (maxOffset != -1) {
- for (int i= decls.size() - 1; i >= 0; i--) {
- ASTNode curr= (ASTNode) decls.get(i);
- if (maxOffset > curr.getStartPosition() + curr.getLength()) {
- return ASTNodes.getInsertionIndex(newDecl, decls.subList(0, i + 1));
- }
- }
- return 0;
- }
- return ASTNodes.getInsertionIndex(newDecl, decls);
- }
-
- private Type evaluateVariableType(AST ast, ImportRewrite imports, IBinding targetContext) throws CoreException {
- if (fOriginalNode.getParent() instanceof FunctionInvocation) {
- FunctionInvocation parent= (FunctionInvocation) fOriginalNode.getParent();
- if (parent.getExpression() == fOriginalNode) {
- // _x_.foo() -> guess qualifier type by looking for a type with method 'foo'
- ITypeBinding[] bindings= ASTResolving.getQualifierGuess(fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext);
- if (bindings.length > 0) {
- for (int i= 0; i < bindings.length; i++) {
- addLinkedPositionProposal(KEY_TYPE, bindings[i]);
- }
- return imports.addImport(bindings[0], ast);
- }
- }
- }
-
- ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode);
- if (binding != null) {
-
- if (isVariableAssigned()) {
- ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
- for (int i= 0; i < typeProposals.length; i++) {
- addLinkedPositionProposal(KEY_TYPE, typeProposals[i]);
- }
- }
- return imports.addImport(binding, ast);
- }
- // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is
- Type type= ASTResolving.guessTypeForReference(ast, fOriginalNode);
- if (type != null) {
- return type;
- }
- if (fVariableKind == CONST_FIELD) {
- return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
- }
- return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
- }
-
- private boolean isVariableAssigned() {
- ASTNode parent= fOriginalNode.getParent();
- return (parent instanceof Assignment) && (fOriginalNode == ((Assignment) parent).getLeftHandSide());
- }
-
-
- private int evaluateFieldModifiers(ASTNode newTypeDecl) {
- int modifiers= 0;
-
- if (fVariableKind == CONST_FIELD) {
- modifiers |= Modifier.FINAL | Modifier.STATIC;
- } else {
- ASTNode parent= fOriginalNode.getParent();
- if (parent instanceof QualifiedName) {
- IBinding qualifierBinding= ((QualifiedName)parent).getQualifier().resolveBinding();
- if (qualifierBinding instanceof ITypeBinding) {
- modifiers |= Modifier.STATIC;
- }
- } else if (ASTResolving.isInStaticContext(fOriginalNode)) {
- modifiers |= Modifier.STATIC;
- }
- }
- ASTNode node= ASTResolving.findParentType(fOriginalNode, true);
- if (newTypeDecl.equals(node)) {
- modifiers |= Modifier.PRIVATE;
- } else if (node instanceof AnonymousClassDeclaration) {
- modifiers |= Modifier.PROTECTED;
- } else {
- modifiers |= Modifier.PUBLIC;
- }
-
- return modifiers;
- }
-
-
-
- /**
- * Returns the variable kind.
- * @return int
- */
- public int getVariableKind() {
- return fVariableKind;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ProblemLocation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ProblemLocation.java
deleted file mode 100644
index 4f9b513e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ProblemLocation.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaMarkerAnnotation;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- *
- */
-public class ProblemLocation implements IProblemLocation {
-
- private final int fId;
- private final String[] fArguments;
- private final int fOffset;
- private final int fLength;
- private final boolean fIsError;
- private final String fMarkerType;
-
- public ProblemLocation(int offset, int length, IJavaAnnotation annotation) {
- fId= annotation.getId();
- fArguments= annotation.getArguments();
- fOffset= offset;
- fLength= length;
- fIsError= JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(annotation.getType());
-
- String markerType= annotation.getMarkerType();
- fMarkerType= markerType != null ? markerType : IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER;
- }
-
- public ProblemLocation(int offset, int length, int id, String[] arguments, boolean isError, String markerType) {
- fId= id;
- fArguments= arguments;
- fOffset= offset;
- fLength= length;
- fIsError= isError;
- fMarkerType= markerType;
- }
-
- public ProblemLocation(IProblem problem) {
- fId= problem.getID();
- fArguments= problem.getArguments();
- fOffset= problem.getSourceStart();
- fLength= problem.getSourceEnd() - fOffset + 1;
- fIsError= problem.isError();
- fMarkerType= problem instanceof CategorizedProblem ? ((CategorizedProblem) problem).getMarkerType() : IJavaScriptModelMarker.JAVASCRIPT_MODEL_PROBLEM_MARKER;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getProblemId()
- */
- public int getProblemId() {
- return fId;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getProblemArguments()
- */
- public String[] getProblemArguments() {
- return fArguments;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getLength()
- */
- public int getLength() {
- return fLength;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getOffset()
- */
- public int getOffset() {
- return fOffset;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IProblemLocation#isError()
- */
- public boolean isError() {
- return fIsError;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.text.java.IProblemLocation#getMarkerType()
- */
- public String getMarkerType() {
- return fMarkerType;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getCoveringNode(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit)
- */
- public ASTNode getCoveringNode(JavaScriptUnit astRoot) {
- NodeFinder finder= new NodeFinder(fOffset, fLength);
- astRoot.accept(finder);
- return finder.getCoveringNode();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation#getCoveredNode(org.eclipse.wst.jsdt.core.dom.JavaScriptUnit)
- */
- public ASTNode getCoveredNode(JavaScriptUnit astRoot) {
- NodeFinder finder= new NodeFinder(fOffset, fLength);
- astRoot.accept(finder);
- return finder.getCoveredNode();
- }
-
- public String toString() {
- StringBuffer buf= new StringBuffer();
- buf.append("Id: ").append(getErrorCode(fId)).append('\n'); //$NON-NLS-1$
- buf.append('[').append(fOffset).append(", ").append(fLength).append(']').append('\n'); //$NON-NLS-1$
- String[] arg= fArguments;
- if (arg != null) {
- for (int i= 0; i < arg.length; i++) {
- buf.append(arg[i]);
- buf.append('\n');
- }
- }
- return buf.toString();
- }
-
- private String getErrorCode(int code) {
- StringBuffer buf= new StringBuffer();
-
- if ((code & IProblem.TypeRelated) != 0) {
- buf.append("TypeRelated + "); //$NON-NLS-1$
- }
- if ((code & IProblem.FieldRelated) != 0) {
- buf.append("FieldRelated + "); //$NON-NLS-1$
- }
- if ((code & IProblem.ConstructorRelated) != 0) {
- buf.append("ConstructorRelated + "); //$NON-NLS-1$
- }
- if ((code & IProblem.MethodRelated) != 0) {
- buf.append("MethodRelated + "); //$NON-NLS-1$
- }
- if ((code & IProblem.ImportRelated) != 0) {
- buf.append("ImportRelated + "); //$NON-NLS-1$
- }
- if ((code & IProblem.Internal) != 0) {
- buf.append("Internal + "); //$NON-NLS-1$
- }
- if ((code & IProblem.Syntax) != 0) {
- buf.append("Syntax + "); //$NON-NLS-1$
- }
- if ((code & IProblem.Javadoc) != 0) {
- buf.append("Javadoc + "); //$NON-NLS-1$
- }
- buf.append(code & IProblem.IgnoreCategoriesMask);
-
- return buf.toString();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.java
deleted file mode 100644
index eb74fddd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationPresentation;
-import org.eclipse.jface.text.source.ImageUtilities;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ISelectionListenerWithAST;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-/**
- *
- */
-public class QuickAssistLightBulbUpdater {
-
- public static class AssistAnnotation extends Annotation implements IAnnotationPresentation {
-
- //XXX: To be fully correct this should be a non-static fields in QuickAssistLightBulbUpdater
- private static final int LAYER;
-
- static {
- Annotation annotation= new Annotation("org.eclipse.wst.jsdt.ui.warning", false, null); //$NON-NLS-1$
- AnnotationPreference preference= EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
- if (preference != null)
- LAYER= preference.getPresentationLayer() - 1;
- else
- LAYER= IAnnotationAccessExtension.DEFAULT_LAYER;
-
- }
-
- private Image fImage;
-
- public AssistAnnotation() {
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
- */
- public int getLayer() {
- return LAYER;
- }
-
- private Image getImage() {
- if (fImage == null) {
- fImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_QUICK_ASSIST);
- }
- return fImage;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.Annotation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle)
- */
- public void paint(GC gc, Canvas canvas, Rectangle r) {
- ImageUtilities.drawImage(getImage(), gc, canvas, r, SWT.CENTER, SWT.TOP);
- }
-
- }
-
- private final Annotation fAnnotation;
- private boolean fIsAnnotationShown;
- private ITextEditor fEditor;
- private ITextViewer fViewer;
-
- private ISelectionListenerWithAST fListener;
- private IPropertyChangeListener fPropertyChangeListener;
-
- public QuickAssistLightBulbUpdater(ITextEditor part, ITextViewer viewer) {
- fEditor= part;
- fViewer= viewer;
- fAnnotation= new AssistAnnotation();
- fIsAnnotationShown= false;
- fPropertyChangeListener= null;
- }
-
- public boolean isSetInPreferences() {
- return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB);
- }
-
- private void installSelectionListener() {
- fListener= new ISelectionListenerWithAST() {
- public void selectionChanged(IEditorPart part, ITextSelection selection, JavaScriptUnit astRoot) {
- doSelectionChanged(selection.getOffset(), selection.getLength(), astRoot);
- }
- };
- SelectionListenerWithASTManager.getDefault().addListener(fEditor, fListener);
- }
-
- private void uninstallSelectionListener() {
- if (fListener != null) {
- SelectionListenerWithASTManager.getDefault().removeListener(fEditor, fListener);
- fListener= null;
- }
- IAnnotationModel model= getAnnotationModel();
- if (model != null) {
- removeLightBulb(model);
- }
- }
-
- public void install() {
- if (isSetInPreferences()) {
- installSelectionListener();
- }
- if (fPropertyChangeListener == null) {
- fPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doPropertyChanged(event.getProperty());
- }
- };
- PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
- }
- }
-
- public void uninstall() {
- uninstallSelectionListener();
- if (fPropertyChangeListener != null) {
- PreferenceConstants.getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- fPropertyChangeListener= null;
- }
- }
-
- protected void doPropertyChanged(String property) {
- if (property.equals(PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB)) {
- if (isSetInPreferences()) {
- IJavaScriptUnit cu= getCompilationUnit();
- if (cu != null) {
- installSelectionListener();
- Point point= fViewer.getSelectedRange();
- JavaScriptUnit astRoot= ASTProvider.getASTProvider().getAST(cu, ASTProvider.WAIT_ACTIVE_ONLY, null);
- if (astRoot != null) {
- doSelectionChanged(point.x, point.y, astRoot);
- }
- }
- } else {
- uninstallSelectionListener();
- }
- }
- }
-
- private IJavaScriptUnit getCompilationUnit() {
- IJavaScriptElement elem= JavaScriptUI.getEditorInputJavaElement(fEditor.getEditorInput());
- if (elem instanceof IJavaScriptUnit) {
- return (IJavaScriptUnit) elem;
- }
- return null;
- }
-
- private IAnnotationModel getAnnotationModel() {
- return JavaScriptUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
- }
-
- private IDocument getDocument() {
- return JavaScriptUI.getDocumentProvider().getDocument(fEditor.getEditorInput());
- }
-
-
- private void doSelectionChanged(int offset, int length, JavaScriptUnit astRoot) {
-
- final IAnnotationModel model= getAnnotationModel();
- final IJavaScriptUnit cu= getCompilationUnit();
- if (model == null || cu == null) {
- return;
- }
-
- final AssistContext context= new AssistContext(cu, offset, length);
- context.setASTRoot(astRoot);
-
- boolean hasQuickFix= hasQuickFixLightBulb(model, context.getSelectionOffset());
- if (hasQuickFix) {
- removeLightBulb(model);
- return; // there is already a quick fix light bulb at the new location
- }
-
- calculateLightBulb(model, context);
- }
-
- /*
- * Needs to be called synchronized
- */
- private void calculateLightBulb(IAnnotationModel model, IInvocationContext context) {
- boolean needsAnnotation= JavaCorrectionProcessor.hasAssists(context);
- if (fIsAnnotationShown) {
- model.removeAnnotation(fAnnotation);
- }
- if (needsAnnotation) {
- model.addAnnotation(fAnnotation, new Position(context.getSelectionOffset(), context.getSelectionLength()));
- }
- fIsAnnotationShown= needsAnnotation;
- }
-
- private void removeLightBulb(IAnnotationModel model) {
- synchronized (this) {
- if (fIsAnnotationShown) {
- model.removeAnnotation(fAnnotation);
- fIsAnnotationShown= false;
- }
- }
- }
-
- /*
- * Tests if there is already a quick fix light bulb on the current line
- */
- private boolean hasQuickFixLightBulb(IAnnotationModel model, int offset) {
- try {
- IDocument document= getDocument();
- if (document == null) {
- return false;
- }
-
- // we access a document and annotation model from within a job
- // since these are only read accesses, we won't hurt anyone else if
- // this goes boink
-
- // may throw an IndexOutOfBoundsException upon concurrent document modification
- int currLine= document.getLineOfOffset(offset);
-
- // this iterator is not protected, it may throw ConcurrentModificationExceptions
- Iterator iter= model.getAnnotationIterator();
- while (iter.hasNext()) {
- Annotation annot= (Annotation) iter.next();
- if (JavaCorrectionProcessor.isQuickFixableType(annot)) {
- // may throw an IndexOutOfBoundsException upon concurrent annotation model changes
- Position pos= model.getPosition(annot);
- if (pos != null) {
- // may throw an IndexOutOfBoundsException upon concurrent document modification
- int startLine= document.getLineOfOffset(pos.getOffset());
- if (startLine == currLine && JavaCorrectionProcessor.hasCorrections(annot)) {
- return true;
- }
- }
- }
- }
- } catch (BadLocationException e) {
- // ignore
- } catch (IndexOutOfBoundsException e) {
- // concurrent modification - too bad, ignore
- } catch (ConcurrentModificationException e) {
- // concurrent modification - too bad, ignore
- }
- return false;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistProcessor.java
deleted file mode 100644
index 389123e1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickAssistProcessor.java
+++ /dev/null
@@ -1,1366 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids <sdavids@gmx.de> - Bug 37432 getInvertEqualsProposal
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ArrayCreation;
-import org.eclipse.wst.jsdt.core.dom.ArrayInitializer;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.CatchClause;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConditionalExpression;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ExpressionStatement;
-import org.eclipse.wst.jsdt.core.dom.ForInStatement;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.InfixExpression;
-import org.eclipse.wst.jsdt.core.dom.Initializer;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.TryStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.dom.WithStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.ControlStatementsFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.ConvertLoopFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.LinkedProposalModel;
-import org.eclipse.wst.jsdt.internal.corext.fix.VariableDeclarationFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractTempRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.InlineTempRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.fix.ControlStatementsCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ConvertLoopCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.ICleanUp;
-import org.eclipse.wst.jsdt.internal.ui.fix.VariableDeclarationCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickAssistProcessor;
-
-/**
- */
-public class QuickAssistProcessor implements IQuickAssistProcessor {
-
- public static final String SPLIT_JOIN_VARIABLE_DECLARATION_ID= "org.eclipse.wst.jsdt.ui.correction.splitJoinVariableDeclaration.assist"; //$NON-NLS-1$
- public static final String CONVERT_FOR_LOOP_ID= "org.eclipse.wst.jsdt.ui.correction.convertForLoop.assist"; //$NON-NLS-1$
- public static final String ASSIGN_TO_LOCAL_ID= "org.eclipse.wst.jsdt.ui.correction.assignToLocal.assist"; //$NON-NLS-1$
- public static final String ASSIGN_TO_FIELD_ID= "org.eclipse.wst.jsdt.ui.correction.assignToField.assist"; //$NON-NLS-1$
- public static final String ASSIGN_PARAM_TO_FIELD_ID= "org.eclipse.wst.jsdt.ui.correction.assignParamToField.assist"; //$NON-NLS-1$
- public static final String ADD_BLOCK_ID= "org.eclipse.wst.jsdt.ui.correction.addBlock.assist"; //$NON-NLS-1$
- public static final String EXTRACT_LOCAL_ID= "org.eclipse.wst.jsdt.ui.correction.extractLocal.assist"; //$NON-NLS-1$
- public static final String EXTRACT_CONSTANT_ID= "org.eclipse.wst.jsdt.ui.correction.extractConstant.assist"; //$NON-NLS-1$
- public static final String INLINE_LOCAL_ID= "org.eclipse.wst.jsdt.ui.correction.inlineLocal.assist"; //$NON-NLS-1$
- public static final String CONVERT_LOCAL_TO_FIELD_ID= "org.eclipse.wst.jsdt.ui.correction.convertLocalToField.assist"; //$NON-NLS-1$
- public static final String CONVERT_ANONYMOUS_TO_LOCAL_ID= "org.eclipse.wst.jsdt.ui.correction.convertAnonymousToLocal.assist"; //$NON-NLS-1$
-
- public QuickAssistProcessor() {
- super();
- }
-
- public boolean hasAssists(IInvocationContext context) throws CoreException {
- ASTNode coveringNode= context.getCoveringNode();
- if (coveringNode != null) {
- return getCatchClauseToThrowsProposals(context, coveringNode, null)
- || getRenameLocalProposals(context, coveringNode, null, false, null)
- || getAssignToVariableProposals(context, coveringNode, null)
- || getUnWrapProposals(context, coveringNode, null)
- || getAssignParamToFieldProposals(context, coveringNode, null)
- || getJoinVariableProposals(context, coveringNode, null)
- || getAddFinallyProposals(context, coveringNode, null)
- || getAddElseProposals(context, coveringNode, null)
- || getSplitVariableProposals(context, coveringNode, null)
- || getAddBlockProposals(context, coveringNode, null)
- || getArrayInitializerToArrayCreation(context, coveringNode, null)
- || getCreateInSuperClassProposals(context, coveringNode, null)
- || getInvertEqualsProposal(context, coveringNode, null)
- || getExtractLocalProposal(context, coveringNode, null)
- || getInlineLocalProposal(context, coveringNode, null)
- || getConvertLocalToFieldProposal(context, coveringNode, null)
- || getConvertAnonymousToNestedProposal(context, coveringNode, null)
- || getRemoveBlockProposals(context, coveringNode, null)
- || getMakeVariableDeclarationFinalProposals(context, coveringNode, null);
- }
- return false;
- }
-
- public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
- ASTNode coveringNode= context.getCoveringNode();
- if (coveringNode != null) {
- ArrayList resultingCollections= new ArrayList();
- boolean noErrorsAtLocation= noErrorsAtLocation(locations);
-
- // quick assists that show up also if there is an error/warning
- getRenameLocalProposals(context, coveringNode, locations, noErrorsAtLocation, resultingCollections);
- getAssignToVariableProposals(context, coveringNode, resultingCollections);
- getAssignParamToFieldProposals(context, coveringNode, resultingCollections);
-
- if (noErrorsAtLocation) {
- getCatchClauseToThrowsProposals(context, coveringNode, resultingCollections);
- getUnWrapProposals(context, coveringNode, resultingCollections);
- getSplitVariableProposals(context, coveringNode, resultingCollections);
- getJoinVariableProposals(context, coveringNode, resultingCollections);
- getAddFinallyProposals(context, coveringNode, resultingCollections);
- getAddElseProposals(context, coveringNode, resultingCollections);
- getAddBlockProposals(context, coveringNode, resultingCollections);
- getInvertEqualsProposal(context, coveringNode, resultingCollections);
- getArrayInitializerToArrayCreation(context, coveringNode, resultingCollections);
- getCreateInSuperClassProposals(context, coveringNode, resultingCollections);
- getExtractLocalProposal(context, coveringNode, resultingCollections);
- getInlineLocalProposal(context, coveringNode, resultingCollections);
- getConvertLocalToFieldProposal(context, coveringNode, resultingCollections);
- getConvertAnonymousToNestedProposal(context, coveringNode, resultingCollections);
- getRemoveBlockProposals(context, coveringNode, resultingCollections);
- getMakeVariableDeclarationFinalProposals(context, coveringNode, resultingCollections);
- }
- return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
- }
- return null;
- }
-
- private boolean noErrorsAtLocation(IProblemLocation[] locations) {
- if (locations != null) {
- for (int i= 0; i < locations.length; i++) {
- if (locations[i].isError()) {
- return false;
- }
- }
- }
- return true;
- }
-
- private static boolean getExtractLocalProposal(IInvocationContext context, ASTNode covering, Collection proposals) throws CoreException {
- ASTNode node= context.getCoveredNode();
-
- if (!(node instanceof Expression)) {
- return false;
- }
- final Expression expression= (Expression) node;
-
- ITypeBinding binding= expression.resolveTypeBinding();
- if (binding == null || Bindings.isVoidType(binding)) {
- return false;
- }
- if (proposals == null) {
- return true;
- }
-
- final IJavaScriptUnit cu= context.getCompilationUnit();
- final ExtractTempRefactoring extractTempRefactoring= new ExtractTempRefactoring(context.getASTRoot(), expression.getStartPosition(), expression.getLength());
- if (extractTempRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- String label= CorrectionMessages.QuickAssistProcessor_extract_to_local_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image) {
- protected TextChange createTextChange() throws CoreException {
- extractTempRefactoring.setTempName(extractTempRefactoring.guessTempName()); // expensive
- extractTempRefactoring.setLinkedProposalModel(getLinkedProposalModel());
- return extractTempRefactoring.createTextChange(new NullProgressMonitor());
- }
- };
- proposal.setCommandId(EXTRACT_LOCAL_ID);
- proposals.add(proposal);
- }
- final ExtractConstantRefactoring extractConstRefactoring= new ExtractConstantRefactoring(context.getASTRoot(), expression.getStartPosition(), expression.getLength());
- if (extractConstRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- String label= CorrectionMessages.QuickAssistProcessor_extract_to_constant_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 4, image) {
- protected TextChange createTextChange() throws CoreException {
- extractConstRefactoring.setConstantName(extractConstRefactoring.guessConstantName()); // expensive
- extractConstRefactoring.setLinkedProposalModel(getLinkedProposalModel());
- return extractConstRefactoring.createTextChange(new NullProgressMonitor());
- }
- };
- proposal.setCommandId(EXTRACT_CONSTANT_ID);
- proposals.add(proposal);
- }
- return false;
- }
-
-
- private static boolean getConvertAnonymousToNestedProposal(IInvocationContext context, final ASTNode node, Collection proposals) throws CoreException {
- if (!(node instanceof Name))
- return false;
-
- ASTNode normalized= ASTNodes.getNormalizedNode(node);
- if (normalized.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY)
- return false;
-
- final AnonymousClassDeclaration anonymTypeDecl= ((ClassInstanceCreation) normalized.getParent()).getAnonymousClassDeclaration();
- if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) {
- return false;
- }
-
- if (proposals == null) {
- return true;
- }
-
- final IJavaScriptUnit cu= context.getCompilationUnit();
- final ConvertAnonymousToNestedRefactoring refactoring= new ConvertAnonymousToNestedRefactoring(anonymTypeDecl);
- String extTypeName= ASTNodes.getSimpleNameIdentifier((Name) node);
-
- refactoring.setClassName(Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_interface, extTypeName));
-
- if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
- refactoring.setLinkedProposalModel(linkedProposalModel);
-
- String label= CorrectionMessages.QuickAssistProcessor_convert_anonym_to_nested;
- Image image= JavaScriptPlugin.getImageDescriptorRegistry().get(JavaElementImageProvider.getTypeImageDescriptor(true, false, Flags.AccPrivate, false));
- RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, refactoring, 5, image);
- proposal.setLinkedProposalModel(linkedProposalModel);
- proposal.setCommandId(CONVERT_ANONYMOUS_TO_LOCAL_ID);
- proposals.add(proposal);
- }
- return false;
- }
-
- private static boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- ASTNode parent= node.getParent();
-
- VariableDeclarationFragment fragment= null;
- boolean onFirstAccess= false;
- if (node instanceof SimpleName && node.getLocationInParent() == Assignment.LEFT_HAND_SIDE_PROPERTY) {
- onFirstAccess= true;
- SimpleName name= (SimpleName) node;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding)) {
- return false;
- }
- ASTNode declaring= context.getASTRoot().findDeclaringNode(binding);
- if (declaring instanceof VariableDeclarationFragment) {
- fragment= (VariableDeclarationFragment) declaring;
- } else {
- return false;
- }
- } else if (parent instanceof VariableDeclarationFragment) {
- fragment= (VariableDeclarationFragment) parent;
- } else {
- return false;
- }
-
- IVariableBinding binding= fragment.resolveBinding();
- if (fragment.getInitializer() != null || binding == null || binding.isField()) {
- return false;
- }
-
- if (!(fragment.getParent() instanceof VariableDeclarationStatement)) {
- return false;
- }
- VariableDeclarationStatement statement= (VariableDeclarationStatement) fragment.getParent();
-
- SimpleName[] names= LinkedNodeFinder.findByBinding(statement.getParent(), binding);
- if (names.length <= 1 || names[0] != fragment.getName()) {
- return false;
- }
- SimpleName firstAccess= names[1];
- if (onFirstAccess) {
- if (firstAccess != node) {
- return false;
- }
- } else {
- if (firstAccess.getLocationInParent() != Assignment.LEFT_HAND_SIDE_PROPERTY) {
- return false;
- }
- }
- Assignment assignment= (Assignment) firstAccess.getParent();
- if (assignment.getLocationInParent() != ExpressionStatement.EXPRESSION_PROPERTY) {
- return false;
- }
- ExpressionStatement assignParent= (ExpressionStatement) assignment.getParent();
-
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= statement.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= CorrectionMessages.QuickAssistProcessor_joindeclaration_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
-
- Expression placeholder= (Expression) rewrite.createMoveTarget(assignment.getRightHandSide());
- rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, placeholder, null);
-
-
- if (onFirstAccess) {
- // replace assignment with variable declaration
- rewrite.replace(assignParent, rewrite.createMoveTarget(statement), null);
- } else {
- // different scopes -> remove assignments, set variable initializer
- if (ASTNodes.isControlStatementBody(assignParent.getLocationInParent())) {
- Block block= ast.newBlock();
- rewrite.replace(assignParent, block, null);
- } else {
- rewrite.remove(assignParent, null);
- }
- }
-
- proposal.setEndPosition(rewrite.track(fragment.getName()));
- resultingCollections.add(proposal);
- return true;
-
- }
-
- private static boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- VariableDeclarationFragment fragment;
- if (node instanceof VariableDeclarationFragment) {
- fragment= (VariableDeclarationFragment) node;
- } else if (node.getLocationInParent() == VariableDeclarationFragment.NAME_PROPERTY) {
- fragment= (VariableDeclarationFragment) node.getParent();
- } else {
- return false;
- }
-
- if (fragment.getInitializer() == null) {
- return false;
- }
-
- Statement statement;
- ASTNode fragParent= fragment.getParent();
- if (fragParent instanceof VariableDeclarationStatement) {
- statement= (VariableDeclarationStatement) fragParent;
- } else if (fragParent instanceof VariableDeclarationExpression) {
- statement= (Statement) fragParent.getParent();
- } else {
- return false;
- }
- // statement is ForStatement or VariableDeclarationStatement
-
- ASTNode statementParent= statement.getParent();
- StructuralPropertyDescriptor property= statement.getLocationInParent();
- if (!property.isChildListProperty()) {
- return false;
- }
-
- List list= (List) statementParent.getStructuralProperty(property);
-
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= statement.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= CorrectionMessages.QuickAssistProcessor_splitdeclaration_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
-
- Statement newStatement;
- int insertIndex= list.indexOf(statement);
-
- Expression placeholder= (Expression) rewrite.createMoveTarget(fragment.getInitializer());
- ITypeBinding binding= fragment.getInitializer().resolveTypeBinding();
- if (placeholder instanceof ArrayInitializer && binding != null && binding.isArray()) {
- ArrayCreation creation= ast.newArrayCreation();
- creation.setInitializer((ArrayInitializer) placeholder);
- final ITypeBinding componentType= binding.getElementType();
- Type type= null;
- if (componentType.isPrimitive())
- type= ast.newPrimitiveType(PrimitiveType.toCode(componentType.getName()));
- else
- type= ast.newSimpleType(ast.newSimpleName(componentType.getName()));
- creation.setType(ast.newArrayType(type, binding.getDimensions()));
- placeholder= creation;
- }
- Assignment assignment= ast.newAssignment();
- assignment.setRightHandSide(placeholder);
- assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
-
- if (statement instanceof VariableDeclarationStatement) {
- newStatement= ast.newExpressionStatement(assignment);
- insertIndex+= 1; // add after declaration
- } else {
- rewrite.replace(fragment.getParent(), assignment, null);
- VariableDeclarationFragment newFrag= ast.newVariableDeclarationFragment();
- newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
- newFrag.setExtraDimensions(fragment.getExtraDimensions());
-
- VariableDeclarationExpression oldVarDecl= (VariableDeclarationExpression) fragParent;
-
- VariableDeclarationStatement newVarDec= ast.newVariableDeclarationStatement(newFrag);
- newVarDec.setType((Type) ASTNode.copySubtree(ast, oldVarDecl.getType()));
- newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers()));
- newStatement= newVarDec;
- }
-
- ListRewrite listRewriter= rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
- listRewriter.insertAt(newStatement, insertIndex, null);
-
- resultingCollections.add(proposal);
- return true;
- }
-
- private static boolean getAssignToVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- Statement statement= ASTResolving.findParentStatement(node);
- if (!(statement instanceof ExpressionStatement)) {
- return false;
- }
- ExpressionStatement expressionStatement= (ExpressionStatement) statement;
-
- Expression expression= expressionStatement.getExpression();
- if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
- return false; // too confusing and not helpful
- }
-
- ITypeBinding typeBinding= expression.resolveTypeBinding();
- typeBinding= Bindings.normalizeTypeBinding(typeBinding);
- if (typeBinding == null) {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, 2);
- localProposal.setCommandId(ASSIGN_TO_LOCAL_ID);
- resultingCollections.add(localProposal);
-
- ASTNode type= ASTResolving.findParentType(expression);
- if (type != null) {
- AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, 1);
- fieldProposal.setCommandId(ASSIGN_TO_FIELD_ID);
- resultingCollections.add(fieldProposal);
- }
- return false;
-
- }
-
- private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- node= ASTNodes.getNormalizedNode(node);
- ASTNode parent= node.getParent();
- if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof FunctionDeclaration)) {
- return false;
- }
- SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent;
- IVariableBinding binding= paramDecl.resolveBinding();
-
- FunctionDeclaration methodDecl= (FunctionDeclaration) parent.getParent();
- if (binding == null || methodDecl.getBody() == null) {
- return false;
- }
- ITypeBinding typeBinding= binding.getType();
- if (typeBinding == null) {
- return false;
- }
-
- if (resultingCollections == null) {
- return true;
- }
-
- ITypeBinding parentType= Bindings.getBindingOfParentType(node);
- if (parentType != null) {
- // assign to existing fields
- JavaScriptUnit root= context.getASTRoot();
- IVariableBinding[] declaredFields= parentType.getDeclaredFields();
- boolean isStaticContext= ASTResolving.isInStaticContext(node);
- for (int i= 0; i < declaredFields.length; i++) {
- IVariableBinding curr= declaredFields[i];
- if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
- ASTNode fieldDeclFrag= root.findDeclaringNode(curr);
- if (fieldDeclFrag instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment) fieldDeclFrag;
- if (fragment.getInitializer() == null) {
- resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, 1));
- }
- }
- }
- }
- }
-
- AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, 3);
- fieldProposal.setCommandId(ASSIGN_PARAM_TO_FIELD_ID);
- resultingCollections.add(fieldProposal);
- return true;
- }
-
- private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
- if (tryStatement == null || tryStatement.getFinally() != null) {
- return false;
- }
- Statement statement= ASTResolving.findParentStatement(node);
- if (tryStatement != statement && tryStatement.getBody() != statement) {
- return false; // an node inside a catch or finally block
- }
-
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= tryStatement.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- Block finallyBody= ast.newBlock();
-
- rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);
-
- String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- Statement statement= ASTResolving.findParentStatement(node);
- if (!(statement instanceof IfStatement)) {
- return false;
- }
- IfStatement ifStatement= (IfStatement) statement;
- if (ifStatement.getElseStatement() != null) {
- return false;
- }
-
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= statement.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- Block body= ast.newBlock();
-
- rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null);
-
- String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
- if (catchClause == null) {
- return false;
- }
-
- Statement statement= ASTResolving.findParentStatement(node);
- if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
- return false; // selection is in a statement inside the body
- }
-
- Type type= catchClause.getException().getType();
- if (!type.isSimpleType()) {
- return false;
- }
-
- BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(catchClause);
- if (!(bodyDeclaration instanceof FunctionDeclaration) && !(bodyDeclaration instanceof Initializer)) {
- return false;
- }
-
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= bodyDeclaration.getAST();
-
- if (bodyDeclaration instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) bodyDeclaration;
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- removeCatchBlock(rewrite, catchClause);
-
- ITypeBinding binding= type.resolveBinding();
- if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptions())) {
- Name name= ((SimpleType) type).getName();
- Name newName= (Name) ASTNode.copySubtree(ast, name);
-
- ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, FunctionDeclaration.THROWN_EXCEPTIONS_PROPERTY);
- listRewriter.insertLast(newName, null);
- }
-
- String label= CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 4, image);
- resultingCollections.add(proposal);
- }
- { // for initializers or method declarations
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- removeCatchBlock(rewrite, catchClause);
- String label= CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
- resultingCollections.add(proposal);
- }
-
- return true;
- }
-
- private static void removeCatchBlock(ASTRewrite rewrite, CatchClause catchClause) {
- TryStatement tryStatement= (TryStatement) catchClause.getParent();
- if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
- rewrite.remove(catchClause, null);
- } else {
- Block block= tryStatement.getBody();
- List statements= block.statements();
- int nStatements= statements.size();
- if (nStatements == 1) {
- ASTNode first= (ASTNode) statements.get(0);
- rewrite.replace(tryStatement, rewrite.createCopyTarget(first), null);
- } else if (nStatements > 1) {
- ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- ASTNode first= (ASTNode) statements.get(0);
- ASTNode last= (ASTNode) statements.get(statements.size() - 1);
- ASTNode newStatement= listRewrite.createCopyTarget(first, last);
- if (ASTNodes.isControlStatementBody(tryStatement.getLocationInParent())) {
- Block newBlock= rewrite.getAST().newBlock();
- newBlock.statements().add(newStatement);
- newStatement= newBlock;
- }
- rewrite.replace(tryStatement, newStatement, null);
- } else {
- rewrite.remove(tryStatement, null);
- }
- }
- }
-
- private static boolean isNotYetThrown(ITypeBinding binding, List thrownExcpetions) {
- for (int i= 0; i < thrownExcpetions.size(); i++) {
- Name name= (Name) thrownExcpetions.get(i);
- ITypeBinding elem= (ITypeBinding) name.resolveBinding();
- if (elem != null) {
- if (Bindings.isSuperType(elem, binding)) { // existing exception is base class of new
- return false;
- }
- }
- }
- return true;
- }
-
-
- private static boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, IProblemLocation[] locations, boolean noErrorsAtLocation, Collection resultingCollections) {
- if (!(node instanceof SimpleName)) {
- return false;
- }
- SimpleName name= (SimpleName) node;
- IBinding binding= name.resolveBinding();
- if (binding != null && binding.getKind() == IBinding.PACKAGE) {
- return false;
- }
-
- if (locations != null) {
- for (int i= 0; i < locations.length; i++) {
- switch (locations[i].getProblemId()) {
- case IProblem.LocalVariableHidingLocalVariable:
- case IProblem.LocalVariableHidingField:
- case IProblem.FieldHidingLocalVariable:
- case IProblem.FieldHidingField:
- case IProblem.ArgumentHidingLocalVariable:
- case IProblem.ArgumentHidingField:
- return false;
- }
- }
- }
-
- if (resultingCollections == null) {
- return true;
- }
-
- LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(context.getCompilationUnit(), name);
- if (!noErrorsAtLocation) {
- proposal.setRelevance(1);
- }
-
- resultingCollections.add(proposal);
- return true;
- }
-
- public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) {
- if (statement.getNodeType() == ASTNode.BLOCK) {
- Block block= (Block) statement;
- List innerStatements= block.statements();
- int nStatements= innerStatements.size();
- if (nStatements == 1) {
- return rewrite.createCopyTarget(((ASTNode) innerStatements.get(0)));
- } else if (nStatements > 1) {
- if (toControlStatementBody) {
- return rewrite.createCopyTarget(block);
- }
- ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- ASTNode first= (ASTNode) innerStatements.get(0);
- ASTNode last= (ASTNode) innerStatements.get(nStatements - 1);
- return listRewrite.createCopyTarget(first, last);
- }
- return null;
- } else {
- return rewrite.createCopyTarget(statement);
- }
- }
-
-
- private static boolean getUnWrapProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- ASTNode outer= node;
-
- Block block= null;
- if (outer.getNodeType() == ASTNode.BLOCK) {
- block= (Block) outer;
- outer= block.getParent();
- }
-
- ASTNode body= null;
- String label= null;
- if (outer instanceof IfStatement) {
- IfStatement ifStatement= (IfStatement) outer;
- Statement elseBlock= ifStatement.getElseStatement();
- if (elseBlock == null || ((elseBlock instanceof Block) && ((Block) elseBlock).statements().isEmpty())) {
- body= ifStatement.getThenStatement();
- }
- label= CorrectionMessages.QuickAssistProcessor_unwrap_ifstatement;
- } else if (outer instanceof WhileStatement) {
- body=((WhileStatement) outer).getBody();
- label= CorrectionMessages.QuickAssistProcessor_unwrap_whilestatement;
- } else if (outer instanceof ForStatement) {
- body=((ForStatement) outer).getBody();
- label= CorrectionMessages.QuickAssistProcessor_unwrap_forstatement;
- } else if (outer instanceof DoStatement) {
- body=((DoStatement) outer).getBody();
- label= CorrectionMessages.QuickAssistProcessor_unwrap_dostatement;
- } else if (outer instanceof TryStatement) {
- TryStatement tryStatement= (TryStatement) outer;
- if (tryStatement.catchClauses().isEmpty()) {
- body= tryStatement.getBody();
- }
- label= CorrectionMessages.QuickAssistProcessor_unwrap_trystatement;
- } else if (outer instanceof AnonymousClassDeclaration) {
- List decls= ((AnonymousClassDeclaration) outer).bodyDeclarations();
- for (int i= 0; i < decls.size(); i++) {
- ASTNode elem= (ASTNode) decls.get(i);
- if (elem instanceof FunctionDeclaration) {
- Block curr= ((FunctionDeclaration) elem).getBody();
- if (curr != null && !curr.statements().isEmpty()) {
- if (body != null) {
- return false;
- }
- body= curr;
- }
- } else if (elem instanceof TypeDeclaration) {
- return false;
- }
- }
- label= CorrectionMessages.QuickAssistProcessor_unwrap_anonymous;
- outer= ASTResolving.findParentStatement(outer);
- if (outer == null) {
- return false; // private Object o= new Object() { ... };
- }
- } else if (outer instanceof Block) {
- // -> a block in a block
- body= block;
- outer= block;
- label= CorrectionMessages.QuickAssistProcessor_unwrap_block;
- } else if (outer instanceof ParenthesizedExpression) {
- //ParenthesizedExpression expression= (ParenthesizedExpression) outer;
- //body= expression.getExpression();
- //label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.parenthesis"); //$NON-NLS-1$
- } else if (outer instanceof FunctionInvocation) {
- FunctionInvocation invocation= (FunctionInvocation) outer;
- if (invocation.arguments().size() == 1) {
- body= (ASTNode) invocation.arguments().get(0);
- if (invocation.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
- int kind= body.getNodeType();
- if (kind != ASTNode.ASSIGNMENT && kind != ASTNode.PREFIX_EXPRESSION && kind != ASTNode.POSTFIX_EXPRESSION
- && kind != ASTNode.FUNCTION_INVOCATION && kind != ASTNode.SUPER_METHOD_INVOCATION) {
- body= null;
- }
- }
- label= CorrectionMessages.QuickAssistProcessor_unwrap_methodinvocation;
- }
- }
- if (body == null) {
- return false;
- }
- ASTRewrite rewrite= ASTRewrite.create(outer.getAST());
- ASTNode inner= getCopyOfInner(rewrite, body, ASTNodes.isControlStatementBody(outer.getLocationInParent()));
- if (inner == null) {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
-
- rewrite.replace(outer, inner, null);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static boolean isControlStatementWithBlock(ASTNode node) {
- switch (node.getNodeType()) {
- case ASTNode.IF_STATEMENT:
- case ASTNode.WHILE_STATEMENT:
- case ASTNode.FOR_STATEMENT:
- case ASTNode.FOR_IN_STATEMENT:
- case ASTNode.DO_STATEMENT:
- return true;
- default:
- return false;
- }
- }
-
- private static boolean getRemoveBlockProposals(IInvocationContext context, ASTNode coveringNode, Collection resultingCollections) {
- IFix[] fixes= ControlStatementsFix.createRemoveBlockFix(context.getASTRoot(), coveringNode);
- if (fixes != null) {
- if (resultingCollections == null) {
- return true;
- }
- Map options= new Hashtable();
- options.put(CleanUpConstants.CONTROL_STATEMENTS_USE_BLOCKS, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.CONTROL_STATMENTS_USE_BLOCKS_NEVER, CleanUpConstants.TRUE);
- ICleanUp cleanUp= new ControlStatementsCleanUp(options);
- for (int i= 0; i < fixes.length; i++) {
- IFix fix= fixes[i];
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, cleanUp, 0, image, context);
- resultingCollections.add(proposal);
- }
- return true;
- }
- return false;
- }
-
- private static boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- Statement statement= ASTResolving.findParentStatement(node);
- if (statement == null) {
- return false;
- }
-
- if (!isControlStatementWithBlock(statement)) {
- if (!isControlStatementWithBlock(statement.getParent())) {
- return false;
- }
- int statementStart= statement.getStartPosition();
- int statementEnd= statementStart + statement.getLength();
-
- int offset= context.getSelectionOffset();
- int length= context.getSelectionLength();
- if (length == 0) {
- if (offset != statementEnd) { // cursor at end
- return false;
- }
- } else {
- if (offset > statementStart || offset + length < statementEnd) { // statement selected
- return false;
- }
- }
- statement= (Statement) statement.getParent();
- }
-
- StructuralPropertyDescriptor childProperty= null;
- ASTNode child= null;
- switch (statement.getNodeType()) {
- case ASTNode.IF_STATEMENT:
- int selectionStart= context.getSelectionOffset();
- int selectionEnd= context.getSelectionOffset() + context.getSelectionLength();
- ASTNode then= ((IfStatement) statement).getThenStatement();
- if (selectionEnd <= then.getStartPosition() + then.getLength()) {
- if (!(then instanceof Block)) {
- childProperty= IfStatement.THEN_STATEMENT_PROPERTY;
- child= then;
- }
- } else if (selectionStart >= then.getStartPosition() + then.getLength()) {
- ASTNode elseStatement= ((IfStatement) statement).getElseStatement();
- if (!(elseStatement instanceof Block)) {
- childProperty= IfStatement.ELSE_STATEMENT_PROPERTY;
- child= elseStatement;
- }
- }
- break;
- case ASTNode.WHILE_STATEMENT:
- ASTNode whileBody= ((WhileStatement) statement).getBody();
- if (!(whileBody instanceof Block)) {
- childProperty= WhileStatement.BODY_PROPERTY;
- child= whileBody;
- }
- break;
- case ASTNode.WITH_STATEMENT:
- ASTNode withBody= ((WithStatement) statement).getBody();
- if (!(withBody instanceof Block)) {
- childProperty= WithStatement.BODY_PROPERTY;
- child= withBody;
- }
- break;
- case ASTNode.FOR_STATEMENT:
- ASTNode forBody= ((ForStatement) statement).getBody();
- if (!(forBody instanceof Block)) {
- childProperty= ForStatement.BODY_PROPERTY;
- child= forBody;
- }
- break;
- case ASTNode.FOR_IN_STATEMENT:
- ASTNode forInBody= ((ForInStatement) statement).getBody();
- if (!(forInBody instanceof Block)) {
- childProperty= ForInStatement.BODY_PROPERTY;
- child= forInBody;
- }
- break;
- case ASTNode.DO_STATEMENT:
- ASTNode doBody= ((DoStatement) statement).getBody();
- if (!(doBody instanceof Block)) {
- childProperty= DoStatement.BODY_PROPERTY;
- child= doBody;
- }
- break;
- default:
- }
- if (child == null) {
- return false;
- }
-
- if (resultingCollections == null) {
- return true;
- }
- AST ast= statement.getAST();
- {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- ASTNode childPlaceholder= rewrite.createMoveTarget(child);
- Block replacingBody= ast.newBlock();
- replacingBody.statements().add(childPlaceholder);
- rewrite.set(statement, childProperty, replacingBody, null);
-
- String label;
- if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
- label = CorrectionMessages.QuickAssistProcessor_replacethenwithblock_description;
- } else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
- label = CorrectionMessages.QuickAssistProcessor_replaceelsewithblock_description;
- } else {
- label = CorrectionMessages.QuickAssistProcessor_replacebodywithblock_description;
- }
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 10, image);
- proposal.setCommandId(ADD_BLOCK_ID);
- proposal.setEndPosition(rewrite.track(child));
- resultingCollections.add(proposal);
- }
-
- if (statement.getNodeType() == ASTNode.IF_STATEMENT) {
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- while (statement.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
- statement= (Statement) statement.getParent();
- }
-
- boolean missingBlockFound= false;
- boolean foundElse= false;
-
- IfStatement ifStatement;
- Statement thenStatment;
- Statement elseStatment;
- do {
- ifStatement= (IfStatement) statement;
- thenStatment= ifStatement.getThenStatement();
- elseStatment= ifStatement.getElseStatement();
-
- if (!(thenStatment instanceof Block)) {
- ASTNode childPlaceholder1= rewrite.createMoveTarget(thenStatment);
- Block replacingBody1= ast.newBlock();
- replacingBody1.statements().add(childPlaceholder1);
- rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, replacingBody1, null);
- if (thenStatment != child) {
- missingBlockFound= true;
- }
- }
- if (elseStatment != null) {
- foundElse= true;
- }
- statement= elseStatment;
- } while (elseStatment instanceof IfStatement);
-
- if (elseStatment != null && !(elseStatment instanceof Block)) {
- ASTNode childPlaceholder2= rewrite.createMoveTarget(elseStatment);
-
- Block replacingBody2= ast.newBlock();
- replacingBody2.statements().add(childPlaceholder2);
- rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, replacingBody2, null);
- if (elseStatment != child) {
- missingBlockFound= true;
- }
- }
-
- if (missingBlockFound && foundElse) {
- String label = CorrectionMessages.QuickAssistProcessor_replacethenelsewithblock_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 10, image);
- resultingCollections.add(proposal);
- }
- }
- return true;
- }
-
- private static boolean getInvertEqualsProposal(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- ASTNode parent= node.getParent();
- if (!(parent instanceof FunctionInvocation)) {
- return false;
- }
- FunctionInvocation method= (FunctionInvocation) parent;
- if (!"equals".equals(method.getName().getIdentifier())) { //$NON-NLS-1$
- return false;
- }
- List arguments= method.arguments();
- if (arguments.size() != 1) { //overloaded equals w/ more than 1 argument
- return false;
- }
- Expression right= (Expression) arguments.get(0);
- ITypeBinding binding = right.resolveTypeBinding();
- if (binding != null && !(binding.isClass())) { //overloaded equals w/ non-class/interface argument or null
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
-
- Expression left= method.getExpression();
-
- AST ast= method.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- if (left == null) { // equals(x) -> x.equals(this)
- FunctionInvocation replacement= ast.newFunctionInvocation();
- replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName()));
- replacement.arguments().add(ast.newThisExpression());
- replacement.setExpression((Expression) rewrite.createCopyTarget(right));
- rewrite.replace(method, replacement, null);
- } else if (right instanceof ThisExpression) { // x.equals(this) -> equals(x)
- FunctionInvocation replacement= ast.newFunctionInvocation();
- replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName()));
- replacement.arguments().add(rewrite.createCopyTarget(left));
- rewrite.replace(method, replacement, null);
- } else {
- ASTNode leftExpression= left;
- while (leftExpression instanceof ParenthesizedExpression) {
- leftExpression= ((ParenthesizedExpression) left).getExpression();
- }
- rewrite.replace(right, rewrite.createCopyTarget(leftExpression), null);
-
- if ((right instanceof Assignment)
- || (right instanceof ConditionalExpression)
- || (right instanceof InfixExpression)) {
- ParenthesizedExpression paren= ast.newParenthesizedExpression();
- paren.setExpression((Expression) rewrite.createCopyTarget(right));
- rewrite.replace(left, paren, null);
- } else {
- rewrite.replace(left, rewrite.createCopyTarget(right), null);
- }
- }
-
- String label= CorrectionMessages.QuickAssistProcessor_invertequals_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
-
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static boolean getArrayInitializerToArrayCreation(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
- if (!(node instanceof ArrayInitializer)) {
- return false;
- }
- ArrayInitializer initializer= (ArrayInitializer) node;
-
- ASTNode parent= initializer.getParent();
- while (parent instanceof ArrayInitializer) {
- initializer= (ArrayInitializer) parent;
- parent= parent.getParent();
- }
- ITypeBinding typeBinding= initializer.resolveTypeBinding();
- if (!(parent instanceof VariableDeclaration) || typeBinding == null || !typeBinding.isArray()) {
- return false;
- }
- if (resultingCollections == null) {
- return true;
- }
-
- AST ast= node.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= CorrectionMessages.QuickAssistProcessor_typetoarrayInitializer_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
-
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
-
- ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
- String typeName= imports.addImport(typeBinding);
-
- ArrayCreation creation= ast.newArrayCreation();
- creation.setInitializer((ArrayInitializer) rewrite.createMoveTarget(initializer));
- creation.setType((ArrayType) ASTNodeFactory.newType(ast, typeName));
-
- rewrite.replace(initializer, creation, null);
-
- resultingCollections.add(proposal);
- return true;
- }
-
-
- public static boolean getCreateInSuperClassProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
- if (!(node instanceof SimpleName) || !(node.getParent() instanceof FunctionDeclaration)) {
- return false;
- }
- FunctionDeclaration decl= (FunctionDeclaration) node.getParent();
- if (decl.getName() != node || decl.resolveBinding() == null || Modifier.isPrivate(decl.getModifiers())) {
- return false;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- JavaScriptUnit astRoot= context.getASTRoot();
-
- IFunctionBinding binding= decl.resolveBinding();
- ITypeBinding[] paramTypes= binding.getParameterTypes();
-
- ITypeBinding[] superTypes= Bindings.getAllSuperTypes(binding.getDeclaringClass());
- if (resultingCollections == null) {
- for (int i= 0; i < superTypes.length; i++) {
- ITypeBinding curr= superTypes[i];
- if (curr.isFromSource() && Bindings.findOverriddenMethodInType(curr, binding) == null) {
- return true;
- }
- }
- return false;
- }
- List params= decl.parameters();
- String[] paramNames= new String[paramTypes.length];
- for (int i = 0; i < params.size(); i++) {
- SingleVariableDeclaration param= (SingleVariableDeclaration) params.get(i);
- paramNames[i]= param.getName().getIdentifier();
- }
-
- for (int i= 0; i < superTypes.length; i++) {
- ITypeBinding curr= superTypes[i];
- if (curr.isFromSource()) {
- IFunctionBinding method= Bindings.findOverriddenMethodInType(curr, binding);
- if (method == null) {
- ITypeBinding typeDecl= curr.getTypeDeclaration();
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, typeDecl);
- if (targetCU != null) {
- String label= Messages.format(CorrectionMessages.QuickAssistProcessor_createmethodinsuper_description, new String[] { curr.getName(), binding.getName() });
- resultingCollections.add(new NewDefiningMethodProposal(label, targetCU, astRoot, typeDecl, binding, paramNames, 6));
- }
- }
- }
- }
- return true;
- }
-
- private static boolean getConvertIterableLoopProposal(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
- ForStatement forStatement= getEnclosingForStatementHeader(node);
- if (forStatement == null)
- return false;
-
- if (resultingCollections == null)
- return true;
-
- IFix fix= ConvertLoopFix.createConvertIterableLoopToEnhancedFix(context.getASTRoot(), forStatement);
- if (fix == null)
- return false;
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- Map options= new HashMap();
- options.put(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, CleanUpConstants.TRUE);
- ICleanUp cleanUp= new ConvertLoopCleanUp(options);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, cleanUp, 1, image, context);
- proposal.setCommandId(CONVERT_FOR_LOOP_ID);
-
- resultingCollections.add(proposal);
- return true;
- }
-
- private static ForStatement getEnclosingForStatementHeader(ASTNode node) {
- if (node instanceof ForStatement)
- return (ForStatement) node;
-
- while (node != null) {
- ASTNode parent= node.getParent();
- if (parent instanceof ForStatement) {
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent == ForStatement.EXPRESSION_PROPERTY
- || locationInParent == ForStatement.INITIALIZERS_PROPERTY
- || locationInParent == ForStatement.UPDATERS_PROPERTY)
- return (ForStatement) parent;
- else
- return null;
- }
- node= parent;
- }
- return null;
- }
-
- private static boolean getMakeVariableDeclarationFinalProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
- SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(context.getSelectionOffset(), context.getSelectionLength()), false);
- context.getASTRoot().accept(analyzer);
- ASTNode[] selectedNodes= analyzer.getSelectedNodes();
- if (selectedNodes.length == 0)
- return false;
-
- IFix fix= VariableDeclarationFix.createChangeModifierToFinalFix(context.getASTRoot(), selectedNodes);
- if (fix == null)
- return false;
-
- if (resultingCollections == null)
- return true;
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- Map options= new Hashtable();
- options.put(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpConstants.TRUE);
- options.put(CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, CleanUpConstants.TRUE);
- VariableDeclarationCleanUp cleanUp= new VariableDeclarationCleanUp(options);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, cleanUp, 5, image, context);
- resultingCollections.add(proposal);
- return true;
- }
-
- private static boolean getInlineLocalProposal(IInvocationContext context, final ASTNode node, Collection proposals) throws CoreException {
- if (!(node instanceof SimpleName))
- return false;
-
- SimpleName name= (SimpleName) node;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding))
- return false;
- IVariableBinding varBinding= (IVariableBinding) binding;
- if (varBinding.isField() || varBinding.isParameter())
- return false;
- ASTNode decl= context.getASTRoot().findDeclaringNode(varBinding);
- if (!(decl instanceof VariableDeclarationFragment) || decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY)
- return false;
-
- if (proposals == null) {
- return true;
- }
-
- InlineTempRefactoring refactoring= new InlineTempRefactoring((VariableDeclaration) decl);
- if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- String label= CorrectionMessages.QuickAssistProcessor_inline_local_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, 5, image);
- proposal.setCommandId(INLINE_LOCAL_ID);
- proposals.add(proposal);
-
- }
- return true;
- }
-
- private static boolean getConvertLocalToFieldProposal(IInvocationContext context, final ASTNode node, Collection proposals) throws CoreException {
- if (!(node instanceof SimpleName))
- return false;
-
- SimpleName name= (SimpleName) node;
- IBinding binding= name.resolveBinding();
- if (!(binding instanceof IVariableBinding) || name.getLocationInParent() != VariableDeclarationFragment.NAME_PROPERTY)
- return false;
- IVariableBinding varBinding= (IVariableBinding) binding;
- if (varBinding.isField() || varBinding.isParameter())
- return false;
- VariableDeclarationFragment decl= (VariableDeclarationFragment) name.getParent();
- if (decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY)
- return false;
-
- if (proposals == null) {
- return true;
- }
-
- PromoteTempToFieldRefactoring refactoring= new PromoteTempToFieldRefactoring(decl);
- if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
- String label= CorrectionMessages.QuickAssistProcessor_convert_local_to_field_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
- refactoring.setLinkedProposalModel(linkedProposalModel);
-
- RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, 5, image);
- proposal.setLinkedProposalModel(linkedProposalModel);
- proposal.setCommandId(CONVERT_LOCAL_TO_FIELD_ID);
- proposals.add(proposal);
- }
- return true;
- }
-
- private static class RefactoringCorrectionProposal extends CUCorrectionProposal {
- private final Refactoring fRefactoring;
-
- public RefactoringCorrectionProposal(String name, IJavaScriptUnit cu, Refactoring refactoring, int relevance, Image image) {
- super(name, cu, null, relevance, image);
- fRefactoring= refactoring;
- }
-
- protected TextChange createTextChange() throws CoreException {
- return (TextChange) fRefactoring.createChange(new NullProgressMonitor());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickFixProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickFixProcessor.java
deleted file mode 100644
index 4035aad2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickFixProcessor.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickFixProcessor;
-
-/**
- */
-public class QuickFixProcessor implements IQuickFixProcessor {
-
-
- public boolean hasCorrections(IJavaScriptUnit cu, int problemId) {
- switch (problemId) {
- case IProblem.UnterminatedString:
-// case IProblem.UnusedImport:
-// case IProblem.DuplicateImport:
-// case IProblem.CannotImportPackage:
-// case IProblem.ConflictingImport:
-// case IProblem.ImportNotFound:
-// case IProblem.UndefinedMethod:
- case IProblem.UndefinedConstructor:
- case IProblem.ParameterMismatch:
- case IProblem.MethodButWithConstructorName:
- case IProblem.UndefinedField:
- case IProblem.UndefinedName:
- //case IProblem.PublicClassMustMatchFileName:
- //case IProblem.PackageIsNotExpectedPackage:
- case IProblem.UndefinedType:
- case IProblem.TypeMismatch:
- case IProblem.UnhandledException:
- case IProblem.UnreachableCatch:
- case IProblem.VoidMethodReturnsValue:
- case IProblem.ShouldReturnValue:
- case IProblem.MissingReturnType:
- //case IProblem.NonExternalizedStringLiteral:
- case IProblem.NonStaticAccessToStaticField:
- case IProblem.NonStaticAccessToStaticMethod:
- case IProblem.StaticMethodRequested:
- case IProblem.NonStaticFieldFromStaticInvocation:
- case IProblem.InstanceMethodDuringConstructorInvocation:
- case IProblem.InstanceFieldDuringConstructorInvocation:
- case IProblem.NotVisibleMethod:
- case IProblem.NotVisibleConstructor:
- case IProblem.NotVisibleType:
- case IProblem.NotVisibleField:
- //case IProblem.BodyForAbstractMethod:
- //case IProblem.AbstractMethodInAbstractClass:
- //case IProblem.AbstractMethodMustBeImplemented:
- case IProblem.BodyForNativeMethod:
- //case IProblem.OuterLocalMustBeFinal:
- case IProblem.UninitializedLocalVariable:
- case IProblem.UndefinedConstructorInDefaultConstructor:
- case IProblem.UnhandledExceptionInDefaultConstructor:
- //case IProblem.NotVisibleConstructorInDefaultConstructor:
- case IProblem.AmbiguousType:
- case IProblem.UnusedPrivateMethod:
- //case IProblem.UnusedPrivateConstructor:
- case IProblem.UnusedPrivateField:
- case IProblem.UnusedPrivateType:
- case IProblem.LocalVariableIsNeverUsed:
- case IProblem.ArgumentIsNeverUsed:
- case IProblem.MethodRequiresBody:
- case IProblem.NeedToEmulateFieldReadAccess:
- case IProblem.NeedToEmulateFieldWriteAccess:
- case IProblem.NeedToEmulateMethodAccess:
- case IProblem.NeedToEmulateConstructorAccess:
- case IProblem.SuperfluousSemicolon:
- case IProblem.UnnecessaryInstanceof:
- case IProblem.IndirectAccessToStaticField:
- case IProblem.IndirectAccessToStaticMethod:
- case IProblem.Task:
- case IProblem.UnusedMethodDeclaredThrownException:
- case IProblem.UnusedConstructorDeclaredThrownException:
- case IProblem.UnqualifiedFieldAccess:
- case IProblem.JavadocMissing:
- case IProblem.JavadocMissingParamTag:
- case IProblem.JavadocMissingReturnTag:
- case IProblem.JavadocMissingThrowsTag:
- case IProblem.JavadocUndefinedType:
- case IProblem.JavadocAmbiguousType:
- case IProblem.JavadocNotVisibleType:
- case IProblem.JavadocInvalidThrowsClassName:
- case IProblem.JavadocDuplicateThrowsClassName:
- case IProblem.JavadocDuplicateReturnTag:
- case IProblem.JavadocDuplicateParamName:
- case IProblem.JavadocInvalidParamName:
- case IProblem.JavadocUnexpectedTag:
- case IProblem.JavadocInvalidTag:
- //case IProblem.NonBlankFinalLocalAssignment:
- case IProblem.DuplicateFinalLocalInitialization:
- case IProblem.FinalFieldAssignment:
- case IProblem.DuplicateBlankFinalFieldInitialization:
- case IProblem.InheritedMethodReducesVisibility:
- case IProblem.MethodReducesVisibility:
- //case IProblem.OverridingNonVisibleMethod:
- case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod:
- case IProblem.CannotHideAnInstanceMethodWithAStaticMethod:
- case IProblem.UnexpectedStaticModifierForMethod:
- case IProblem.LocalVariableHidingLocalVariable:
- case IProblem.LocalVariableHidingField:
- case IProblem.FieldHidingLocalVariable:
- case IProblem.FieldHidingField:
- case IProblem.ArgumentHidingLocalVariable:
- case IProblem.ArgumentHidingField:
- case IProblem.DuplicateField:
- case IProblem.DuplicateMethod:
- case IProblem.DuplicateNestedType:
- case IProblem.IllegalModifierForClass:
- case IProblem.IllegalModifierForMemberClass:
- case IProblem.IllegalModifierForLocalClass:
- case IProblem.IllegalModifierForField:
- case IProblem.IllegalModifierForMethod:
- case IProblem.UnexpectedStaticModifierForField:
- case IProblem.IllegalModifierCombinationFinalVolatileForField:
- case IProblem.IncompatibleReturnType:
- case IProblem.IncompatibleExceptionInThrowsClause:
- case IProblem.NoMessageSendOnArrayType:
- case IProblem.InvalidOperator:
- case IProblem.UnnecessaryElse:
- case IProblem.SuperclassMustBeAClass:
- case IProblem.UseAssertAsAnIdentifier:
- case IProblem.UseEnumAsAnIdentifier:
- case IProblem.RedefinedLocal:
- case IProblem.RedefinedArgument:
- case IProblem.CodeCannotBeReached:
- case IProblem.InvalidUsageOfForeachStatements:
- case IProblem.OverridingDeprecatedMethod:
- case IProblem.IsClassPathCorrect:
- case IProblem.MethodReturnsVoid:
- case IProblem.ForbiddenReference:
- case IProblem.DiscouragedReference:
- case IProblem.UnnecessaryNLSTag:
- case IProblem.AssignmentHasNoEffect:
- case IProblem.FallthroughCase:
- return true;
- default:
-// if (JavaModelUtil.is50OrHigher(cu.getJavaScriptProject())) {
-// return SuppressWarningsSubProcessor.hasSuppressWarningsProposal(problemId);
-// }
- return false;
- }
- }
-
- private static int moveBack(int offset, int start, String ignoreCharacters, IJavaScriptUnit cu) {
- try {
- IBuffer buf= cu.getBuffer();
- while (offset >= start) {
- if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) {
- return offset;
- }
- offset--;
- }
- } catch(JavaScriptModelException e) {
- }
- return start;
- }
-
-
- /* (non-Javadoc)
- * @see IAssistProcessor#getCorrections(org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistContext, org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation[])
- */
- public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
- if (locations == null || locations.length == 0) {
- return null;
- }
-
- HashSet handledProblems= new HashSet(locations.length);
- ArrayList resultingCollections= new ArrayList();
- for (int i= 0; i < locations.length; i++) {
- IProblemLocation curr= locations[i];
- Integer id= new Integer(curr.getProblemId());
- if (handledProblems.add(id)) {
- process(context, curr, resultingCollections);
- }
- }
- return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
- }
-
- private void process(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- int id= problem.getProblemId();
- if (id == 0) { // no proposals for none-problem locations
- return;
- }
- switch (id) {
- case IProblem.UnterminatedString:
- String quoteLabel= CorrectionMessages.JavaCorrectionProcessor_addquote_description;
- int pos= moveBack(problem.getOffset() + problem.getLength(), problem.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$
- proposals.add(new ReplaceCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, 0, "\"", 0)); //$NON-NLS-1$
- break;
- case IProblem.DuplicateImport:
- case IProblem.CannotImportPackage:
- case IProblem.ConflictingImport:
- ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
- break;
- case IProblem.ImportNotFound:
- ReorgCorrectionsSubProcessor.importNotFoundProposals(context, problem, proposals);
- ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
- break;
- case IProblem.UndefinedMethod:
- case IProblem.UndefinedFunction:
- UnresolvedElementsSubProcessor.getMethodProposals(context, problem, false, proposals);
- break;
- case IProblem.UndefinedConstructor:
- UnresolvedElementsSubProcessor.getConstructorProposals(context, problem, proposals);
- break;
- case IProblem.ParameterMismatch:
- UnresolvedElementsSubProcessor.getMethodProposals(context, problem, true, proposals);
- break;
- case IProblem.MethodButWithConstructorName:
- ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, problem, proposals);
- break;
- case IProblem.UndefinedField:
- case IProblem.UndefinedName:
- UnresolvedElementsSubProcessor.getVariableProposals(context, problem, null, proposals);
- break;
- case IProblem.AmbiguousType:
- case IProblem.JavadocAmbiguousType:
- UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, problem, proposals);
- break;
- case IProblem.UndefinedType:
- case IProblem.JavadocUndefinedType:
- UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals);
- break;
- case IProblem.TypeMismatch:
- TypeMismatchSubProcessor.addTypeMismatchProposals(context, problem, proposals);
- break;
- case IProblem.IncompatibleReturnType:
- TypeMismatchSubProcessor.addIncompatibleReturnTypeProposals(context, problem, proposals);
- break;
- case IProblem.IncompatibleExceptionInThrowsClause:
- TypeMismatchSubProcessor.addIncompatibleThrowsProposals(context, problem, proposals);
- break;
- case IProblem.UnhandledException:
- LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, problem, proposals);
- break;
- case IProblem.UnreachableCatch:
- LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, problem, proposals);
- break;
- case IProblem.VoidMethodReturnsValue:
- ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, problem, proposals);
- break;
- case IProblem.MethodReturnsVoid:
- ReturnTypeSubProcessor.addMethodRetunsVoidProposals(context, problem, proposals);
- break;
- case IProblem.MissingReturnType:
- ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, problem, proposals);
- break;
- case IProblem.ShouldReturnValue:
- ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, problem, proposals);
- break;
- case IProblem.NonExternalizedStringLiteral:
- LocalCorrectionsSubProcessor.addNLSProposals(context, problem, proposals);
- break;
- case IProblem.UnnecessaryNLSTag:
- LocalCorrectionsSubProcessor.getUnnecessaryNLSTagProposals(context, problem, proposals);
- break;
- case IProblem.NonStaticAccessToStaticField:
- case IProblem.NonStaticAccessToStaticMethod:
- case IProblem.IndirectAccessToStaticField:
- case IProblem.IndirectAccessToStaticMethod:
- LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals);
- break;
- case IProblem.StaticMethodRequested:
- case IProblem.NonStaticFieldFromStaticInvocation:
- case IProblem.InstanceMethodDuringConstructorInvocation:
- case IProblem.InstanceFieldDuringConstructorInvocation:
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_STATIC, 5);
- break;
- case IProblem.NonBlankFinalLocalAssignment:
- case IProblem.DuplicateFinalLocalInitialization:
- case IProblem.FinalFieldAssignment:
- case IProblem.DuplicateBlankFinalFieldInitialization:
- case IProblem.ClassExtendFinalClass:
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL, 9);
- break;
- case IProblem.InheritedMethodReducesVisibility:
- case IProblem.MethodReducesVisibility:
- case IProblem.OverridingNonVisibleMethod:
- ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE);
- break;
- case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod:
- ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC);
- break;
- case IProblem.CannotHideAnInstanceMethodWithAStaticMethod:
- case IProblem.IllegalModifierForClass:
- case IProblem.UnexpectedStaticModifierForField:
- case IProblem.IllegalModifierCombinationFinalVolatileForField:
- case IProblem.IllegalModifierForMemberClass:
- case IProblem.IllegalModifierForLocalClass:
- case IProblem.IllegalModifierForField:
- case IProblem.IllegalModifierForMethod:
- case IProblem.UnexpectedStaticModifierForMethod:
- ModifierCorrectionSubProcessor.addRemoveInvalidModfiersProposal(context, problem, proposals, 5);
- break;
- case IProblem.NotVisibleField:
- ModifierCorrectionSubProcessor.addGetterSetterProposal(context,problem,proposals, 15);
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, 10);
- break;
- case IProblem.NotVisibleMethod:
- case IProblem.NotVisibleConstructor:
- case IProblem.NotVisibleType:
- case IProblem.JavadocNotVisibleType:
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, 10);
- break;
- case IProblem.BodyForAbstractMethod:
- case IProblem.AbstractMethodInAbstractClass:
- ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, problem, proposals);
- break;
- case IProblem.AbstractMethodMustBeImplemented:
- LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, problem, proposals);
- break;
- case IProblem.BodyForNativeMethod:
- ModifierCorrectionSubProcessor.addNativeMethodProposals(context, problem, proposals);
- break;
- case IProblem.MethodRequiresBody:
- ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, problem, proposals);
- break;
- case IProblem.OuterLocalMustBeFinal:
- ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, problem, proposals);
- break;
- case IProblem.UninitializedLocalVariable:
- LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, problem, proposals);
- break;
- case IProblem.UnhandledExceptionInDefaultConstructor:
- case IProblem.UndefinedConstructorInDefaultConstructor:
- case IProblem.NotVisibleConstructorInDefaultConstructor:
- LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, problem, proposals);
- break;
- case IProblem.UnusedPrivateMethod:
- case IProblem.UnusedPrivateConstructor:
- case IProblem.UnusedPrivateField:
- case IProblem.UnusedPrivateType:
- case IProblem.LocalVariableIsNeverUsed:
- case IProblem.ArgumentIsNeverUsed:
- LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
- break;
- case IProblem.NeedToEmulateFieldReadAccess:
- case IProblem.NeedToEmulateFieldWriteAccess:
- case IProblem.NeedToEmulateMethodAccess:
- case IProblem.NeedToEmulateConstructorAccess:
- ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE, 5);
- break;
- case IProblem.SuperfluousSemicolon:
- LocalCorrectionsSubProcessor.addSuperfluousSemicolonProposal(context, problem, proposals);
- break;
- case IProblem.UnnecessaryInstanceof:
- LocalCorrectionsSubProcessor.addUnnecessaryInstanceofProposal(context, problem, proposals);
- break;
- case IProblem.UnusedMethodDeclaredThrownException:
- case IProblem.UnusedConstructorDeclaredThrownException:
- LocalCorrectionsSubProcessor.addUnnecessaryThrownExceptionProposal(context, problem, proposals);
- break;
- case IProblem.UnqualifiedFieldAccess:
- ModifierCorrectionSubProcessor.addGetterSetterProposal(context, problem, proposals, 15);
-// LocalCorrectionsSubProcessor.addUnqualifiedFieldAccessProposal(context, problem, proposals);
- break;
- case IProblem.Task:
- proposals.add(new TaskMarkerProposal(context.getCompilationUnit(), problem, 10));
- break;
- case IProblem.JavadocMissing:
- JavadocTagsSubProcessor.getMissingJavadocCommentProposals(context, problem, proposals);
- break;
- case IProblem.JavadocMissingParamTag:
- case IProblem.JavadocMissingReturnTag:
- case IProblem.JavadocMissingThrowsTag:
- JavadocTagsSubProcessor.getMissingJavadocTagProposals(context, problem, proposals);
- break;
- case IProblem.JavadocInvalidThrowsClassName:
- case IProblem.JavadocDuplicateThrowsClassName:
- case IProblem.JavadocDuplicateReturnTag:
- case IProblem.JavadocDuplicateParamName:
- case IProblem.JavadocInvalidParamName:
- case IProblem.JavadocUnexpectedTag:
- case IProblem.JavadocInvalidTag:
- JavadocTagsSubProcessor.getRemoveJavadocTagProposals(context, problem, proposals);
- break;
- case IProblem.LocalVariableHidingLocalVariable:
- case IProblem.LocalVariableHidingField:
- case IProblem.FieldHidingLocalVariable:
- case IProblem.FieldHidingField:
- case IProblem.ArgumentHidingLocalVariable:
- case IProblem.ArgumentHidingField:
- case IProblem.UseAssertAsAnIdentifier:
- case IProblem.UseEnumAsAnIdentifier:
- case IProblem.RedefinedLocal:
- case IProblem.RedefinedArgument:
- case IProblem.DuplicateField:
- case IProblem.DuplicateMethod:
- case IProblem.DuplicateNestedType:
- LocalCorrectionsSubProcessor.addInvalidVariableNameProposals(context, problem, proposals);
- break;
- case IProblem.NoMessageSendOnArrayType:
- UnresolvedElementsSubProcessor.getArrayAccessProposals(context, problem, proposals);
- break;
- case IProblem.InvalidOperator:
- LocalCorrectionsSubProcessor.getInvalidOperatorProposals(context, problem, proposals);
- break;
- case IProblem.UnnecessaryElse:
- LocalCorrectionsSubProcessor.getUnnecessaryElseProposals(context, problem, proposals);
- break;
- case IProblem.CodeCannotBeReached:
- LocalCorrectionsSubProcessor.getUnreachableCodeProposals(context, problem, proposals);
- break;
- case IProblem.InvalidUsageOfForeachStatements:
- ReorgCorrectionsSubProcessor.getNeed50ComplianceProposals(context, problem, proposals);
- break;
- case IProblem.OverridingDeprecatedMethod:
- ModifierCorrectionSubProcessor.addOverridingDeprecatedMethodProposal(context, problem, proposals);
- break;
- case IProblem.IsClassPathCorrect:
- ReorgCorrectionsSubProcessor.getIncorrectBuildPathProposals(context, problem, proposals);
- break;
- case IProblem.ForbiddenReference:
- case IProblem.DiscouragedReference:
- ReorgCorrectionsSubProcessor.getAccessRulesProposals(context, problem, proposals);
- break;
- case IProblem.AssignmentHasNoEffect:
- LocalCorrectionsSubProcessor.getAssignmentHasNoEffectProposals(context, problem, proposals);
- break;
- case IProblem.FallthroughCase:
- LocalCorrectionsSubProcessor.addFallThroughProposals(context, problem, proposals);
- break;
- default:
- }
-// if (JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaScriptProject())) {
-// SuppressWarningsSubProcessor.addSuppressWarningsProposals(context, problem, proposals);
-// }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickTemplateProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickTemplateProcessor.java
deleted file mode 100644
index 56800f18..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/QuickTemplateProcessor.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContext;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.SurroundWithTemplateProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.TemplateProposal;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickAssistProcessor;
-
-import com.ibm.icu.text.Collator;
-
-
-/**
- * Quick template processor.
- */
-public class QuickTemplateProcessor implements IQuickAssistProcessor {
-
- private static final String $_LINE_SELECTION= "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
-
- public QuickTemplateProcessor() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistProcessor#hasAssists(org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistContext)
- */
- public boolean hasAssists(IInvocationContext context) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
- IDocument document= getDocument(cu);
-
- int offset= context.getSelectionOffset();
- int length= context.getSelectionLength();
- if (length == 0) {
- return false;
- }
-
- try {
- int startLine= document.getLineOfOffset(offset);
- int endLine= document.getLineOfOffset(offset + length);
- IRegion region= document.getLineInformation(endLine);
- return startLine < endLine || length > 0 && offset == region.getOffset() && length == region.getLength();
- } catch (BadLocationException e) {
- return false;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.wst.jsdt.internal.ui.text.correction.IAssistContext, org.eclipse.wst.jsdt.internal.ui.text.correction.IProblemLocation[])
- */
- public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
- if (locations != null && locations.length > 0) {
- return new IJavaCompletionProposal[0];
- }
-
- try {
- int offset= context.getSelectionOffset();
- int length= context.getSelectionLength();
- if (length == 0) {
- return null;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- IDocument document= getDocument(cu);
-
- // test if selection is either a full line or spans over multiple lines
- int startLine= document.getLineOfOffset(offset);
- int endLine= document.getLineOfOffset(offset + length);
- IRegion endLineRegion= document.getLineInformation(endLine);
- //if end position is at start of line, set it back to the previous line's end
- if (endLine > startLine && endLineRegion.getOffset() == offset + length) {
- endLine--;
- endLineRegion= document.getLineInformation(endLine);
- length= endLineRegion.getOffset() + endLineRegion.getLength() - offset;
- }
- if (startLine == endLine) {
- if (length == 0 || offset != endLineRegion.getOffset() || length != endLineRegion.getLength()) {
- AssistContext invocationContext= new AssistContext(cu, offset, length);
- if (!SurroundWith.isApplicable(invocationContext))
- return null;
- }
- } else {
- // expand selection
- offset= document.getLineOffset(startLine);
- length= endLineRegion.getOffset() + endLineRegion.getLength() - offset;
- }
-
- ArrayList resultingCollections= new ArrayList();
- collectSurroundTemplates(document, cu, offset, length, resultingCollections);
- sort(resultingCollections);
- return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, "", e)); //$NON-NLS-1$
- }
- }
-
- private void sort(ArrayList proposals) {
- Collections.sort(proposals, new Comparator() {
- public int compare(Object o1, Object o2) {
- IJavaCompletionProposal p1= (IJavaCompletionProposal)o1;
- IJavaCompletionProposal p2= (IJavaCompletionProposal)o2;
- return Collator.getInstance().compare(p1.getDisplayString(), p2.getDisplayString());
- }
- });
- }
-
- private IDocument getDocument(IJavaScriptUnit cu) throws JavaScriptModelException {
- IFile file= (IFile) cu.getResource();
- IDocument document= JavaScriptUI.getDocumentProvider().getDocument(new FileEditorInput(file));
- if (document == null) {
- return new Document(cu.getSource()); // only used by test cases
- }
- return document;
- }
-
- private void collectSurroundTemplates(IDocument document, IJavaScriptUnit cu, int offset, int length, Collection result) throws BadLocationException, CoreException {
- CompilationUnitContextType contextType= (CompilationUnitContextType) JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType(JavaContextType.NAME);
- CompilationUnitContext context= contextType.createContext(document, offset, length, cu);
- context.setVariable("selection", document.get(offset, length)); //$NON-NLS-1$
- context.setForceEvaluation(true);
-
- int start= context.getStart();
- int end= context.getEnd();
- IRegion region= new Region(start, end - start);
-
- AssistContext invocationContext= new AssistContext(cu, start, end - start);
- Statement[] selectedStatements= SurroundWith.getSelectedStatements(invocationContext);
-
- Template[] templates= JavaScriptPlugin.getDefault().getTemplateStore().getTemplates();
- for (int i= 0; i != templates.length; i++) {
- Template currentTemplate= templates[i];
- if (context.canEvaluate(currentTemplate) && currentTemplate.getContextTypeId().equals(JavaContextType.NAME) && currentTemplate.getPattern().indexOf($_LINE_SELECTION) != -1) {
- // TODO using jdt proposals for the moment, as jdt expects IJavaCompletionProposals
-
- if (selectedStatements != null) {
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- TemplateProposal proposal= new SurroundWithTemplateProposal(cu, currentTemplate, context, region, image, selectedStatements);
- String[] arg= new String[] { currentTemplate.getName(), currentTemplate.getDescription() };
- proposal.setDisplayString(Messages.format(CorrectionMessages.QuickTemplateProcessor_surround_label, arg));
- result.add(proposal);
- } else {
- TemplateProposal proposal= new TemplateProposal(currentTemplate, context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)) {
- /**
- * {@inheritDoc}
- */
- public boolean validate(IDocument doc, int off, DocumentEvent event) {
- return false;
- }
- };
- String[] arg= new String[] { currentTemplate.getName(), currentTemplate.getDescription() };
- proposal.setDisplayString(Messages.format(CorrectionMessages.QuickTemplateProcessor_surround_label, arg));
- result.add(proposal);
- }
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RemoveDeclarationCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RemoveDeclarationCorrectionProposal.java
deleted file mode 100644
index f2ed3531..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RemoveDeclarationCorrectionProposal.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.PostfixExpression;
-import org.eclipse.wst.jsdt.core.dom.PrefixExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-
-public class RemoveDeclarationCorrectionProposal extends ASTRewriteCorrectionProposal {
-
- private static class SideEffectFinder extends ASTVisitor {
-
- private ArrayList fSideEffectNodes;
-
- public SideEffectFinder(ArrayList res) {
- fSideEffectNodes= res;
- }
-
- public boolean visit(Assignment node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(PostfixExpression node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(PrefixExpression node) {
- Object operator= node.getOperator();
- if (operator == PrefixExpression.Operator.INCREMENT || operator == PrefixExpression.Operator.DECREMENT) {
- fSideEffectNodes.add(node);
- }
- return false;
- }
-
- public boolean visit(FunctionInvocation node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(ClassInstanceCreation node) {
- fSideEffectNodes.add(node);
- return false;
- }
-
- public boolean visit(SuperMethodInvocation node) {
- fSideEffectNodes.add(node);
- return false;
- }
- }
-
-
- private SimpleName fName;
-
- public RemoveDeclarationCorrectionProposal(IJavaScriptUnit cu, SimpleName name, int relevance) {
- super("", cu, null, relevance, JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE)); //$NON-NLS-1$
- fName= name;
- }
-
- public String getDisplayString() {
- IBinding binding= fName.resolveBinding();
- String name= fName.getIdentifier();
- switch (binding.getKind()) {
- case IBinding.TYPE:
- return Messages.format(CorrectionMessages.RemoveDeclarationCorrectionProposal_removeunusedtype_description, name);
- case IBinding.METHOD:
- if (((IFunctionBinding) binding).isConstructor()) {
- return Messages.format(CorrectionMessages.RemoveDeclarationCorrectionProposal_removeunusedconstructor_description, name);
- } else {
- return Messages.format(CorrectionMessages.RemoveDeclarationCorrectionProposal_removeunusedmethod_description, name);
- }
- case IBinding.VARIABLE:
- if (((IVariableBinding) binding).isField()) {
- return Messages.format(CorrectionMessages.RemoveDeclarationCorrectionProposal_removeunusedfield_description, name);
- } else {
- return Messages.format(CorrectionMessages.RemoveDeclarationCorrectionProposal_removeunusedvar_description, name);
- }
- default:
- return super.getDisplayString();
- }
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() {
- IBinding binding= fName.resolveBinding();
- JavaScriptUnit root= (JavaScriptUnit) fName.getRoot();
- ASTRewrite rewrite;
- if (binding.getKind() == IBinding.METHOD) {
- IFunctionBinding decl= ((IFunctionBinding) binding).getMethodDeclaration();
- ASTNode declaration= root.findDeclaringNode(decl);
- rewrite= ASTRewrite.create(root.getAST());
- rewrite.remove(declaration, null);
- } else if (binding.getKind() == IBinding.TYPE) {
- ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
- ASTNode declaration= root.findDeclaringNode(decl);
- rewrite= ASTRewrite.create(root.getAST());
- rewrite.remove(declaration, null);
- } else if (binding.getKind() == IBinding.VARIABLE) {
- // needs full AST
- JavaScriptUnit completeRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null);
-
- SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, fName.getStartPosition(), fName.getLength());
-
- rewrite= ASTRewrite.create(completeRoot.getAST());
- SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
- for (int i= 0; i < references.length; i++) {
- removeVariableReferences(rewrite, references[i]);
- }
-
- IVariableBinding bindingDecl= ((IVariableBinding) nameNode.resolveBinding()).getVariableDeclaration();
- ASTNode declaringNode= completeRoot.findDeclaringNode(bindingDecl);
- if (declaringNode instanceof SingleVariableDeclaration) {
- removeParamTag(rewrite, (SingleVariableDeclaration) declaringNode);
- }
- } else {
- throw new IllegalArgumentException("Unexpected binding"); //$NON-NLS-1$
- }
- return rewrite;
- }
-
- private void removeParamTag(ASTRewrite rewrite, SingleVariableDeclaration varDecl) {
- if (varDecl.getParent() instanceof FunctionDeclaration) {
- JSdoc javadoc= ((FunctionDeclaration) varDecl.getParent()).getJavadoc();
- if (javadoc != null) {
- TagElement tagElement= JavadocTagsSubProcessor.findParamTag(javadoc, varDecl.getName().getIdentifier());
- if (tagElement != null) {
- rewrite.remove(tagElement, null);
- }
- }
- }
- }
-
- /**
- * Remove the field or variable declaration including the initializer.
- */
- private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference) {
- ASTNode parent= reference.getParent();
- while (parent instanceof QualifiedName) {
- parent= parent.getParent();
- }
- if (parent instanceof FieldAccess) {
- parent= parent.getParent();
- }
-
- int nameParentType= parent.getNodeType();
- if (nameParentType == ASTNode.ASSIGNMENT) {
- Assignment assignment= (Assignment) parent;
- Expression rightHand= assignment.getRightHandSide();
-
- ASTNode assignParent= assignment.getParent();
- if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
- removeVariableWithInitializer(rewrite, rightHand, assignParent);
- } else {
- rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), null);
- }
- } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
- rewrite.remove(parent, null);
- } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
- ASTNode varDecl= frag.getParent();
- List fragments;
- if (varDecl instanceof VariableDeclarationExpression) {
- fragments= ((VariableDeclarationExpression) varDecl).fragments();
- } else if (varDecl instanceof FieldDeclaration) {
- fragments= ((FieldDeclaration) varDecl).fragments();
- } else {
- fragments= ((VariableDeclarationStatement) varDecl).fragments();
- }
- if (fragments.size() == 1) {
- rewrite.remove(varDecl, null);
- } else {
- rewrite.remove(frag, null); // don't try to preserve
- }
- }
- }
-
- private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode) {
- ArrayList sideEffectNodes= new ArrayList();
- initializerNode.accept(new SideEffectFinder(sideEffectNodes));
- int nSideEffects= sideEffectNodes.size();
- if (nSideEffects == 0) {
- if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
- rewrite.replace(statementNode, rewrite.getAST().newBlock(), null);
- } else {
- rewrite.remove(statementNode, null);
- }
- } else {
- // do nothing yet
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RenameNodeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RenameNodeCompletionProposal.java
deleted file mode 100644
index c9bccd34..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/RenameNodeCompletionProposal.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.LinkedNodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-/**
- *
- */
-public class RenameNodeCompletionProposal extends CUCorrectionProposal {
-
- private String fNewName;
- private int fOffset;
- private int fLength;
-
- public RenameNodeCompletionProposal(String name, IJavaScriptUnit cu, int offset, int length, String newName, int relevance) {
- super(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- fOffset= offset;
- fLength= length;
- fNewName= newName;
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#addEdits(org.eclipse.jface.text.IDocument)
- */
- protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
- super.addEdits(doc, root);
-
- // build a full AST
- JavaScriptUnit unit= JavaScriptPlugin.getDefault().getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null);
-
- ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
- if (name instanceof SimpleName) {
-
- SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
- if (names != null) {
- for (int i= 0; i < names.length; i++) {
- SimpleName curr= names[i];
- root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
- }
- return;
- }
- }
- root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java
deleted file mode 100644
index 6e02567f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java
+++ /dev/null
@@ -1,512 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.core.search.SearchPattern;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.corext.fix.IFix;
-import org.eclipse.wst.jsdt.internal.corext.fix.UnusedCodeFix;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.AddToClasspathChange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeNameMatchCollector;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.fix.UnusedCodeCleanUp;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BuildPathsPropertyPage;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.launching.IVMInstall;
-import org.eclipse.wst.jsdt.launching.IVMInstall2;
-import org.eclipse.wst.jsdt.launching.IVMInstallType;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.actions.OrganizeImportsAction;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class ReorgCorrectionsSubProcessor {
-
- public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
- boolean isLinked= cu.getResource().isLinked();
-
- IJavaScriptProject javaProject= cu.getJavaScriptProject();
- String sourceLevel= javaProject.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String compliance= javaProject.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
-
- JavaScriptUnit root= context.getASTRoot();
-
- ASTNode coveredNode= problem.getCoveredNode(root);
- if (!(coveredNode instanceof SimpleName))
- return;
-
- ASTNode parentType= coveredNode.getParent();
- if (!(parentType instanceof AbstractTypeDeclaration))
- return;
-
- String currTypeName= ((SimpleName) coveredNode).getIdentifier();
- String newTypeName= JavaScriptCore.removeJavaScriptLikeExtension(cu.getElementName());
-
- boolean hasOtherPublicTypeBefore= false;
-
- boolean found= false;
- List types= root.types();
- for (int i= 0; i < types.size(); i++) {
- AbstractTypeDeclaration curr= (AbstractTypeDeclaration) types.get(i);
- if (parentType != curr) {
- if (newTypeName.equals(curr.getName().getIdentifier())) {
- return;
- }
- if (!found && Modifier.isPublic(curr.getModifiers())) {
- hasOtherPublicTypeBefore= true;
- }
- } else {
- found= true;
- }
- }
- if (!JavaScriptConventions.validateJavaScriptTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
- proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, 5));
- }
-
- if (!hasOtherPublicTypeBefore) {
- String newCUName= JavaModelUtil.getRenamedCUName(cu, currTypeName);
- IJavaScriptUnit newCU= ((IPackageFragment) (cu.getParent())).getJavaScriptUnit(newCUName);
- if (!newCU.exists() && !isLinked && !JavaScriptConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
- RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);
-
- // rename CU
- String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, newCUName);
- proposals.add(new ChangeCorrectionProposal(label, change, 6, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
- }
- }
- }
-
- public static void removeImportStatementProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IFix fix= UnusedCodeFix.createRemoveUnusedImportFix(context.getASTRoot(), problem);
- if (fix != null) {
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_DELETE_IMPORT);
- Map options= new Hashtable();
- options.put(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpConstants.TRUE);
- FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new UnusedCodeCleanUp(options), 6, image, context);
- proposals.add(proposal);
- }
-
- final IJavaScriptUnit cu= context.getCompilationUnit();
- String name= CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description;
- ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)) {
- public void apply(IDocument document) {
- IEditorInput input= new FileEditorInput((IFile) cu.getResource());
- IWorkbenchPage p= JavaScriptPlugin.getActivePage();
- if (p == null) {
- return;
- }
- IEditorPart part= p.findEditor(input);
- if (part instanceof JavaEditor) {
- OrganizeImportsAction action= new OrganizeImportsAction((JavaEditor) part);
- action.run(cu);
- }
- }
- };
- proposals.add(proposal);
- }
-
- public static void importNotFoundProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
- IJavaScriptProject project= cu.getJavaScriptProject();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode != null) {
- ImportDeclaration importDeclaration= (ImportDeclaration) ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
- if (importDeclaration == null) {
- return;
- }
- if (!importDeclaration.isOnDemand()) {
- int kind= JavaModelUtil.is50OrHigher(cu.getJavaScriptProject()) ? SimilarElementsRequestor.REF_TYPES : SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES;
- UnresolvedElementsSubProcessor.addNewTypeProposals(cu, importDeclaration.getName(), kind, 5, proposals);
- }
-
-
- String name= ASTNodes.asString(importDeclaration.getName());
- char[] packageName;
- char[] typeName= null;
- if (importDeclaration.isOnDemand()) {
- packageName= name.toCharArray();
- } else {
- packageName= Signature.getQualifier(name).toCharArray();
- typeName= Signature.getSimpleName(name).toCharArray();
- }
- IJavaScriptSearchScope scope= SearchEngine.createWorkspaceScope();
- ArrayList res= new ArrayList();
- TypeNameMatchCollector requestor= new TypeNameMatchCollector(res);
- int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
- new SearchEngine().searchAllTypeNames(packageName, matchMode, typeName,
- matchMode, IJavaScriptSearchConstants.TYPE, scope, requestor,
- IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
-
- if (res.isEmpty()) {
- return;
- }
- HashSet addedClaspaths= new HashSet();
- for (int i= 0; i < res.size(); i++) {
- TypeNameMatch curr= (TypeNameMatch) res.get(i);
- IType type= curr.getType();
- if (type != null) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) type.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry == null) {
- continue;
- }
- IJavaScriptProject other= root.getJavaScriptProject();
- int entryKind= entry.getEntryKind();
- if ((entry.isExported() || entryKind == IIncludePathEntry.CPE_SOURCE) && addedClaspaths.add(other)) {
- String[] args= { other.getElementName(), project.getElementName() };
- String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_project_description, args);
- IIncludePathEntry newEntry= JavaScriptCore.newProjectEntry(other.getPath());
- AddToClasspathChange change= new AddToClasspathChange(project, newEntry);
- if (change.validateClasspath()) {
- ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(label, change, 8, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- proposals.add(proposal);
- }
- }
- if ((entryKind == IIncludePathEntry.CPE_LIBRARY || entryKind == IIncludePathEntry.CPE_VARIABLE || entryKind == IIncludePathEntry.CPE_CONTAINER) && addedClaspaths.add(entry)) {
- String label= getAddClasspathLabel(entry, root, project);
- if (label != null) {
- AddToClasspathChange change= new AddToClasspathChange(project, entry);
- if (change.validateClasspath()) {
- ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(label, change, 7, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- proposals.add(proposal);
- }
- }
- }
- }
- }
- }
- }
-
- private static String getAddClasspathLabel(IIncludePathEntry entry, IPackageFragmentRoot root, IJavaScriptProject project) {
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY:
- if (root.isArchive()) {
- String[] args= { JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED), project.getElementName() };
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_archive_description, args);
- } else {
- String[] args= { JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED), project.getElementName() };
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_classfolder_description, args);
- }
- case IIncludePathEntry.CPE_VARIABLE: {
- String[] args= { JavaScriptElementLabels.getElementLabel(root, 0), project.getElementName() };
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_variable_description, args);
- }
- case IIncludePathEntry.CPE_CONTAINER:
- try {
- String[] args= { JavaScriptElementLabels.getContainerEntryLabel(entry.getPath(), root.getJavaScriptProject()), project.getElementName() };
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_library_description, args);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- break;
- }
- return null;
- }
-
- private static final class OpenBuildPathCorrectionProposal extends ChangeCorrectionProposal {
- private final IProject fProject;
- private final IBinding fReferencedType;
- private OpenBuildPathCorrectionProposal(IProject project, String label, int relevance, IBinding referencedType) {
- super(label, null, relevance, null);
- fProject= project;
- fReferencedType= referencedType;
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ACCESSRULES_ATTRIB));
- }
- public void apply(IDocument document) {
- Map data= null;
- if (fReferencedType != null) {
- IJavaScriptElement elem= fReferencedType.getJavaElement();
- if (elem != null) {
- IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (root != null) {
- try {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- if (entry != null) {
- data= new HashMap(1);
- data.put(BuildPathsPropertyPage.DATA_REVEAL_ENTRY, entry);
- if (entry.getEntryKind() != IIncludePathEntry.CPE_CONTAINER) {
- data.put(BuildPathsPropertyPage.DATA_REVEAL_ATTRIBUTE_KEY, CPListElement.ACCESSRULES);
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- }
- }
- PreferencesUtil.createPropertyDialogOn(JavaScriptPlugin.getActiveWorkbenchShell(), fProject, BuildPathsPropertyPage.PROP_ID, null, data).open();
- }
- public String getAdditionalProposalInfo() {
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_configure_buildpath_description, fProject.getName());
- }
- }
-
- private static final class ChangeTo50Compliance extends ChangeCorrectionProposal implements IWorkspaceRunnable {
-
- private final IJavaScriptProject fProject;
- private final boolean fChangeOnWorkspace;
-
- private Job fUpdateJob;
- private boolean f50JREFound;
-
- public ChangeTo50Compliance(String name, IJavaScriptProject project, boolean changeOnWorkspace, int relevance) {
- super(name, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- fProject= project;
- fChangeOnWorkspace= changeOnWorkspace;
- fUpdateJob= null;
- f50JREFound= false;
- }
-
- private boolean is50orGreaterVMInstall(IVMInstall install) {
- if (install instanceof IVMInstall2) {
- String compliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, JavaScriptCore.VERSION_1_3);
- return JavaModelUtil.is50OrHigher(compliance);
- }
- return false;
- }
-
- private IVMInstall find50OrGreaterVMInstall() {
- IVMInstallType[] installTypes= JavaRuntime.getVMInstallTypes();
- for (int i= 0; i < installTypes.length; i++) {
- IVMInstall[] installs= installTypes[i].getVMInstalls();
- for (int k= 0; k < installs.length; k++) {
- if (is50orGreaterVMInstall(installs[k])) {
- return installs[k];
- }
- }
- }
- return null;
- }
-
- public void run(IProgressMonitor monitor) throws CoreException {
- boolean needsBuild= updateJRE(monitor);
- if (needsBuild) {
- fUpdateJob= CoreUtility.getBuildJob(fChangeOnWorkspace ? null : fProject.getProject());
- }
- }
-
- private boolean updateJRE( IProgressMonitor monitor) throws CoreException, JavaScriptModelException {
- try {
- IVMInstall vm50Install= find50OrGreaterVMInstall();
- f50JREFound= vm50Install != null;
- if (vm50Install != null) {
- IVMInstall install= JavaRuntime.getVMInstall(fProject); // can be null
- if (fChangeOnWorkspace) {
- monitor.beginTask(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_operation, 4);
- IVMInstall defaultVM= JavaRuntime.getDefaultVMInstall(); // can be null
- if (defaultVM != null && !defaultVM.equals(install)) {
- IPath newPath= new Path(JavaRuntime.JRE_CONTAINER);
- updateClasspath(newPath, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
- if (defaultVM == null || !is50orGreaterVMInstall(defaultVM)) {
- JavaRuntime.setDefaultVMInstall(vm50Install, new SubProgressMonitor(monitor, 3), true);
- return false;
- }
- return true;
- } else {
- if (install == null || !is50orGreaterVMInstall(install)) {
- IPath newPath= new Path(JavaRuntime.JRE_CONTAINER).append(vm50Install.getVMInstallType().getId()).append(vm50Install.getName());
- updateClasspath(newPath, monitor);
- return false;
- }
- }
- }
- } finally {
- monitor.done();
- }
- return true;
- }
-
- private void updateClasspath(IPath newPath, IProgressMonitor monitor) throws JavaScriptModelException {
- IIncludePathEntry[] classpath= fProject.getRawIncludepath();
- IPath jreContainerPath= new Path(JavaRuntime.JRE_CONTAINER);
- for (int i= 0; i < classpath.length; i++) {
- IIncludePathEntry curr= classpath[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_CONTAINER && curr.getPath().matchingFirstSegments(jreContainerPath) > 0) {
- classpath[i]= JavaScriptCore.newContainerEntry(newPath, curr.getAccessRules(), curr.getExtraAttributes(), curr.isExported());
- }
- }
- fProject.setRawIncludepath(classpath, monitor);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- StringBuffer message= new StringBuffer();
- if (fChangeOnWorkspace) {
- message.append(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_changeworkspace_description);
- } else {
- message.append(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_changeproject_description);
- }
-
- IVMInstall vm50Install= find50OrGreaterVMInstall();
- if (vm50Install != null) {
- try {
- IVMInstall install= JavaRuntime.getVMInstall(fProject); // can be null
- if (fChangeOnWorkspace) {
- IVMInstall defaultVM= JavaRuntime.getDefaultVMInstall(); // can be null
- if (defaultVM != null && !defaultVM.equals(install)) {
- message.append(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_changeProjectJREToDefault_description);
- }
- if (defaultVM == null || !is50orGreaterVMInstall(defaultVM)) {
- message.append(Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_changeWorkspaceJRE_description, vm50Install.getName()));
- }
- } else {
- if (install == null || !is50orGreaterVMInstall(install)) {
- message.append(Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_50_compliance_changeProjectJRE_description, vm50Install.getName()));
- }
- }
- } catch (CoreException e) {
- // ignore
- }
- }
- return message.toString();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
- if (fChangeOnWorkspace) {
- Hashtable map= JavaScriptCore.getOptions();
- JavaModelUtil.set50CompilanceOptions(map);
- JavaScriptCore.setOptions(map);
- } else {
- Map map= fProject.getOptions(false);
- int optionsCount= map.size();
- JavaModelUtil.set50CompilanceOptions(map);
- if (map.size() > optionsCount) {
- // options have been added -> ensure that all compliance options from preference page set
- JavaModelUtil.setDefaultClassfileOptions(map, JavaScriptCore.VERSION_1_5);
- }
- fProject.setOptions(map);
- }
- try {
- IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
- progressService.run(true, true, new WorkbenchRunnableAdapter(this));
- } catch (InvocationTargetException e) {
- JavaScriptPlugin.log(e);
- } catch (InterruptedException e) {
- return;
- }
-
- if (fUpdateJob != null) {
- fUpdateJob.schedule();
- }
-
- if (!f50JREFound) {
- MessageDialog.openInformation(JavaScriptPlugin.getActiveWorkbenchShell(), CorrectionMessages.ReorgCorrectionsSubProcessor_no_50jre_title, CorrectionMessages.ReorgCorrectionsSubProcessor_no_50jre_message);
- }
- }
- }
-
- public static void getNeed50ComplianceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptProject project= context.getCompilationUnit().getJavaScriptProject();
-
- String label1= CorrectionMessages.ReorgCorrectionsSubProcessor_50_project_compliance_description;
- proposals.add(new ChangeTo50Compliance(label1, project, false, 5));
-
- if (project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, false) == null) {
- String label2= CorrectionMessages.ReorgCorrectionsSubProcessor_50_workspace_compliance_description;
- proposals.add(new ChangeTo50Compliance(label2, project, true, 6));
- }
- }
-
- public static void getIncorrectBuildPathProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IProject project= context.getCompilationUnit().getJavaScriptProject().getProject();
- String label= CorrectionMessages.ReorgCorrectionsSubProcessor_configure_buildpath_label;
- OpenBuildPathCorrectionProposal proposal= new OpenBuildPathCorrectionProposal(project, label, 5, null);
- proposals.add(proposal);
- }
-
- public static void getAccessRulesProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IBinding referencedElement= null;
- ASTNode node= problem.getCoveredNode(context.getASTRoot());
- if (node instanceof Type) {
- referencedElement= ((Type) node).resolveBinding();
- } else if (node instanceof Name) {
- referencedElement= ((Name) node).resolveBinding();
- }
- IProject project= context.getCompilationUnit().getJavaScriptProject().getProject();
- String label= CorrectionMessages.ReorgCorrectionsSubProcessor_accessrules_description;
- OpenBuildPathCorrectionProposal proposal= new OpenBuildPathCorrectionProposal(project, label, 5, referencedElement);
- proposals.add(proposal);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReplaceCorrectionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReplaceCorrectionProposal.java
deleted file mode 100644
index dbeaa821..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReplaceCorrectionProposal.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class ReplaceCorrectionProposal extends CUCorrectionProposal {
-
- private String fReplacementString;
- private int fOffset;
- private int fLength;
-
- public ReplaceCorrectionProposal(String name, IJavaScriptUnit cu, int offset, int length, String replacementString, int relevance) {
- super(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- fReplacementString= replacementString;
- fOffset= offset;
- fLength= length;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#addEdits(org.eclipse.jface.text.IDocument)
- */
- protected void addEdits(IDocument doc, TextEdit rootEdit) throws CoreException {
- super.addEdits(doc, rootEdit);
-
- TextEdit edit= new ReplaceEdit(fOffset, fLength, fReplacementString);
- rootEdit.addChild(edit);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReturnTypeSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReturnTypeSubProcessor.java
deleted file mode 100644
index 4b171352..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/ReturnTypeSubProcessor.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTVisitor;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.core.dom.ReturnStatement;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-import org.eclipse.wst.jsdt.core.dom.TextElement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- */
-public class ReturnTypeSubProcessor {
-
- private static class ReturnStatementCollector extends ASTVisitor {
- private ArrayList fResult= new ArrayList();
-
- public Iterator returnStatements() {
- return fResult.iterator();
- }
-
- public ITypeBinding getTypeBinding(AST ast) {
- boolean couldBeObject= false;
- for (int i= 0; i < fResult.size(); i++) {
- ReturnStatement node= (ReturnStatement) fResult.get(i);
- Expression expr= node.getExpression();
- if (expr != null) {
- ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
- if (binding != null) {
- return binding;
- } else {
- couldBeObject= true;
- }
- } else {
- return ast.resolveWellKnownType("void"); //$NON-NLS-1$
- }
- }
- if (couldBeObject) {
- return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
- return ast.resolveWellKnownType("void"); //$NON-NLS-1$
- }
-
- public boolean visit(ReturnStatement node) {
- fResult.add(node);
- return false;
- }
-
- public boolean visit(AnonymousClassDeclaration node) {
- return false;
- }
-
- public boolean visit(TypeDeclaration node) {
- return false;
- }
-
-
-
- }
-
-
- public static void addMethodWithConstrNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode instanceof FunctionDeclaration) {
- FunctionDeclaration declaration= (FunctionDeclaration) selectedNode;
-
- ASTRewrite rewrite= ASTRewrite.create(declaration.getAST());
- rewrite.set(declaration, FunctionDeclaration.CONSTRUCTOR_PROPERTY, Boolean.TRUE, null);
-
- String label= CorrectionMessages.ReturnTypeSubProcessor_constrnamemethod_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
- proposals.add(proposal);
- }
-
- }
-
- public static void addVoidMethodReturnsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
-
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
- ReturnStatement returnStatement= (ReturnStatement) selectedNode;
- Expression expr= returnStatement.getExpression();
- if (expr != null) {
- AST ast= astRoot.getAST();
-
- ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
- if (binding == null) {
- binding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
-
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) decl;
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_voidmethodreturns_description, BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
- ImportRewrite imports= proposal.createImportRewrite(astRoot);
- Type newReturnType= imports.addImport(binding, ast);
-
- if (methodDeclaration.isConstructor()) {
- rewrite.set(methodDeclaration, FunctionDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
- rewrite.set(methodDeclaration, FunctionDeclaration.RETURN_TYPE2_PROPERTY, newReturnType, null);
- } else {
- rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
- }
- String key= "return_type"; //$NON-NLS-1$
- proposal.addLinkedPosition(rewrite.track(newReturnType), true, key);
- ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, binding);
- for (int i= 0; i < bindings.length; i++) {
- proposal.addLinkedPositionProposal(key, bindings[i]);
- }
-
- JSdoc javadoc= methodDeclaration.getJavadoc();
- if (javadoc != null) {
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_RETURN);
- TextElement commentStart= ast.newTextElement();
- newTag.fragments().add(commentStart);
-
- JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY), newTag, null);
- proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
-
- }
- proposals.add(proposal);
- }
- ASTRewrite rewrite= ASTRewrite.create(decl.getAST());
- rewrite.remove(returnStatement.getExpression(), null);
-
- String label= CorrectionMessages.ReturnTypeSubProcessor_removereturn_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
- proposals.add(proposal);
- }
- }
-
-
-
- public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) decl;
-
- ReturnStatementCollector eval= new ReturnStatementCollector();
- decl.accept(eval);
-
- AST ast= astRoot.getAST();
-
- ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
- typeBinding= Bindings.normalizeTypeBinding(typeBinding);
- if (typeBinding == null) {
- typeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
- }
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
-
- ImportRewrite imports= proposal.createImportRewrite(astRoot);
-
- Type type= imports.addImport(typeBinding, ast);
-
- rewrite.set(methodDeclaration, FunctionDeclaration.RETURN_TYPE2_PROPERTY, type, null);
- rewrite.set(methodDeclaration, FunctionDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
-
- JSdoc javadoc= methodDeclaration.getJavadoc();
- if (javadoc != null && typeBinding != null) {
- TagElement newTag= ast.newTagElement();
- newTag.setTagName(TagElement.TAG_RETURN);
- TextElement commentStart= ast.newTextElement();
- newTag.fragments().add(commentStart);
-
- JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, JSdoc.TAGS_PROPERTY), newTag, null);
- proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
- }
-
- String key= "return_type"; //$NON-NLS-1$
- proposal.addLinkedPosition(rewrite.track(type), true, key);
- if (typeBinding != null) {
- ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, typeBinding);
- for (int i= 0; i < bindings.length; i++) {
- proposal.addLinkedPositionProposal(key, bindings[i]);
- }
- }
-
- proposals.add(proposal);
-
- // change to constructor
- ASTNode parentType= ASTResolving.findParentType(decl);
- if (parentType instanceof AbstractTypeDeclaration) {
- String constructorName= ((TypeDeclaration) parentType).getName().getIdentifier();
- ASTNode nameNode= methodDeclaration.getName();
- label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, constructorName);
- proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, 5));
- }
- }
- }
-
- public static void addMissingReturnStatementProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methodDecl= (FunctionDeclaration) decl;
- Block block= methodDecl.getBody();
- if (block == null) {
- return;
- }
- ReturnStatement existingStatement= (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null;
- proposals.add( new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, 6));
-
- Type returnType= methodDecl.getReturnType2();
- if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) { //$NON-NLS-1$
- AST ast= methodDecl.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null);
- JSdoc javadoc= methodDecl.getJavadoc();
- if (javadoc != null) {
- TagElement tagElement= JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null);
- if (tagElement != null) {
- rewrite.remove(tagElement, null);
- }
- }
-
- String label= CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
- proposals.add(proposal);
- }
- }
- }
-
- public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaScriptModelException {
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (!(selectedNode instanceof ReturnStatement)) {
- return;
- }
- ReturnStatement returnStatement= (ReturnStatement) selectedNode;
- Expression expression= returnStatement.getExpression();
- if (expression == null) {
- return;
- }
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methDecl= (FunctionDeclaration) decl;
- Type retType= methDecl.getReturnType2();
- if (retType == null || retType.resolveBinding() == null) {
- return;
- }
- TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, 4, proposals);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElement.java
deleted file mode 100644
index 73a2326c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElement.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.Arrays;
-
-public class SimilarElement {
-
- private final int fKind;
- private final String fName;
- private final String[] fTypesParameters;
- private final int fRelevance;
-
- public SimilarElement(int kind, String name, int relevance) {
- this(kind, name, null, relevance);
- }
-
- public SimilarElement(int kind, String name, String[] typesParameters, int relevance) {
- fKind= kind;
- fName= name;
- fTypesParameters= typesParameters;
- fRelevance= relevance;
- }
-
- /**
- * Gets the kind.
- * @return Returns a int
- */
- public int getKind() {
- return fKind;
- }
-
- /**
- * Gets the parameter types.
- * @return Returns a int
- */
- public String[] getTypesParameter() {
- return fTypesParameters;
- }
-
- /**
- * Gets the name.
- * @return Returns a String
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Gets the relevance.
- * @return Returns a int
- */
- public int getRelevance() {
- return fRelevance;
- }
-
- /* (non-Javadoc)
- * @see Object#equals(Object)
- */
- public boolean equals(Object obj) {
- if (obj instanceof SimilarElement) {
- SimilarElement elem= (SimilarElement) obj;
- return fName.equals(elem.fName) && fKind == elem.fKind && Arrays.equals(fTypesParameters, elem.fTypesParameters);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see Object#hashCode()
- */
- public int hashCode() {
- return fName.hashCode() + fKind;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElementsRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElementsRequestor.java
deleted file mode 100644
index a3be6bbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SimilarElementsRequestor.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.HashSet;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JSdoc;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-
-public class SimilarElementsRequestor extends CompletionRequestor {
-
- public static final int CLASSES= 1 << 1;
- public static final int INTERFACES= 1 << 2;
- public static final int ANNOTATIONS= 1 << 3;
- public static final int ENUMS= 1 << 4;
- public static final int VARIABLES= 1 << 5;
- public static final int PRIMITIVETYPES= 1 << 6;
- public static final int VOIDTYPE= 1 << 7;
- public static final int REF_TYPES= CLASSES | INTERFACES | ENUMS | ANNOTATIONS;
- public static final int REF_TYPES_AND_VAR= REF_TYPES | VARIABLES;
- public static final int ALL_TYPES= PRIMITIVETYPES | REF_TYPES_AND_VAR;
-
- private static final String[] PRIM_TYPES= { "boolean", "byte", "char", "short", "int", "long", "float", "double" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-
- private int fKind;
- private String fName;
-
- private HashSet fResult;
-
- public static SimilarElement[] findSimilarElement(IJavaScriptUnit cu, Name name, int kind) throws JavaScriptModelException {
- int pos= name.getStartPosition();
- int nArguments= -1;
-
- String identifier= ASTNodes.getSimpleNameIdentifier(name);
- String returnType= null;
- IJavaScriptUnit preparedCU= null;
-
- try {
-// if (name.isQualifiedName()) {
-// pos= ((QualifiedName) name).getName().getStartPosition();
-// } else {
- pos= name.getStartPosition() + 1; // first letter must be included, other
- // }
- JSdoc javadoc= (JSdoc) ASTNodes.getParent(name, ASTNode.JSDOC);
- if (javadoc != null) {
- preparedCU= createPreparedCU(cu, javadoc, name.getStartPosition());
- cu= preparedCU;
- }
-
- SimilarElementsRequestor requestor= new SimilarElementsRequestor(identifier, kind, nArguments, returnType);
- /* ORIGINAL -------- BC */
- requestor.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.KEYWORD, true);
- requestor.setIgnored(CompletionProposal.LABEL_REF, true);
- requestor.setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.PACKAGE_REF, true);
- requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.METHOD_REF, true);
- requestor.setIgnored(CompletionProposal.FIELD_REF, true);
- requestor.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
- requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- requestor.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
-
-//
-//
-// requestor.setIgnored(CompletionProposal.ANNOTATION_ATTRIBUTE_REF, false);
-// requestor.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, false);
-// requestor.setIgnored(CompletionProposal.FIELD_REF, false);
-// requestor.setIgnored(CompletionProposal.KEYWORD, false);
-// requestor.setIgnored(CompletionProposal.LABEL_REF, false);
-// requestor.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, false);
-// requestor.setIgnored(CompletionProposal.METHOD_DECLARATION, false);
-// requestor.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, false);
-// requestor.setIgnored(CompletionProposal.METHOD_REF, false);
-// requestor.setIgnored(CompletionProposal.PACKAGE_REF, false);
-// requestor.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, false);
-// requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, false);
-//
-// requestor.setIgnored(CompletionProposal.JSDOC_BLOCK_TAG, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_FIELD_REF, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_INLINE_TAG, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_METHOD_REF, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_PARAM_REF, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_TYPE_REF, true);
-// requestor.setIgnored(CompletionProposal.JSDOC_VALUE_REF, true);
-//
-// requestor.setIgnored(CompletionProposal.TYPE_REF, true);
-//
-
-
-
-
- return requestor.process(cu, pos);
- } finally {
- if (preparedCU != null) {
- preparedCU.discardWorkingCopy();
- }
- }
- }
-
- private static IJavaScriptUnit createPreparedCU(IJavaScriptUnit cu, JSdoc comment, int wordStart) throws JavaScriptModelException {
- int startpos= comment.getStartPosition();
- boolean isTopLevel= comment.getParent().getParent() instanceof JavaScriptUnit;
- char[] content= (char[]) cu.getBuffer().getCharacters().clone();
- if (isTopLevel && (wordStart + 6 < content.length)) {
- content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p';
- content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't';
- }
- if (wordStart < content.length) {
- for (int i= startpos; i < wordStart; i++) {
- content[i]= ' ';
- }
- }
-
- /*
- * Explicitly create a new non-shared working copy.
- */
- IJavaScriptUnit newCU= cu.getWorkingCopy(null);
- newCU.getBuffer().setContents(content);
- return newCU;
- }
-
-
- /**
- * Constructor for SimilarElementsRequestor.
- */
- private SimilarElementsRequestor(String name, int kind, int nArguments, String preferredType) {
- super();
- fName= name;
- fKind= kind;
-
- fResult= new HashSet();
- }
-
- private void addResult(SimilarElement elem) {
- fResult.add(elem);
- }
-
- private SimilarElement[] process(IJavaScriptUnit cu, int pos) throws JavaScriptModelException {
- try {
- cu.codeComplete(pos, this);
- processKeywords();
- return (SimilarElement[]) fResult.toArray(new SimilarElement[fResult.size()]);
- } finally {
- fResult.clear();
- }
- }
-
- private boolean isKind(int kind) {
- return (fKind & kind) != 0;
- }
-
- /**
- * Method addPrimitiveTypes.
- */
- private void processKeywords() {
- if (isKind(PRIMITIVETYPES)) {
- for (int i= 0; i < PRIM_TYPES.length; i++) {
- if (NameMatcher.isSimilarName(fName, PRIM_TYPES[i])) {
- addResult(new SimilarElement(PRIMITIVETYPES, PRIM_TYPES[i], 50));
- }
- }
- }
- if (isKind(VOIDTYPE)) {
- String voidType= "void"; //$NON-NLS-1$
- if (NameMatcher.isSimilarName(fName, voidType)) {
- addResult(new SimilarElement(PRIMITIVETYPES, voidType, 50));
- }
- }
- }
-
- private static final int getKind(int flags, char[] typeNameSig) {
- return CLASSES;
- }
-
-
- private void addType(char[] typeNameSig, int flags, int relevance) {
- int kind= getKind(flags, typeNameSig);
- if (!isKind(kind)) {
- return;
- }
- String fullName= new String(Signature.toCharArray(typeNameSig));
- if (TypeFilter.isFiltered(fullName)) {
- return;
- }
- if (NameMatcher.isSimilarName(fName, Signature.getSimpleName(fullName))) {
- addResult(new SimilarElement(kind, fullName, relevance));
- }
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.CompletionRequestor#accept(org.eclipse.wst.jsdt.core.CompletionProposal)
- */
- public void accept(CompletionProposal proposal) {
- if (proposal.getKind() == CompletionProposal.TYPE_REF) {
- addType(proposal.getSignature(), proposal.getFlags(), proposal.getRelevance());
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SurroundWith.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SurroundWith.java
deleted file mode 100644
index 119d48da..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/SurroundWith.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.dom.LocalVariableIndex;
-import org.eclipse.wst.jsdt.internal.corext.dom.ModifierRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.Selection;
-import org.eclipse.wst.jsdt.internal.corext.dom.VariableDeclarationRewrite;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.FlowInfo;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.surround.SurroundWithAnalyzer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-public abstract class SurroundWith {
-
- private static final class SplitSelectedOperator implements ISplitOperation {
-
- private List fAccessedInside;
- private List fStatements;
- private List fAccessedAfter;
- private ASTRewrite fRewrite;
- private ListRewrite fBlockRewrite;
- private VariableDeclarationStatement fLastStatement= null;
-
- public SplitSelectedOperator(List inside, List after, ListRewrite blockRewrite, ASTRewrite rewrite, List statements) {
- super();
- fAccessedInside= inside;
- fStatements= statements;
- fAccessedAfter= after;
- fRewrite= rewrite;
- fBlockRewrite= blockRewrite;
- }
-
- public boolean needsSplit(VariableDeclarationFragment last, VariableDeclarationFragment current) {
- return fAccessedInside.contains(last) != fAccessedInside.contains(current) || fAccessedAfter.contains(last) != fAccessedAfter.contains(current);
- }
-
- public void initializeStatement(VariableDeclarationStatement statement, VariableDeclarationFragment current) {
- if (fAccessedAfter.contains(current)) {
- if (fAccessedInside.contains(current))
- makeFinal(statement, fRewrite);
- handleInitializer(current);
-
- if (fLastStatement != null) {
- fBlockRewrite.insertAfter(statement, fLastStatement, null);
- }
- fLastStatement= statement;
- } else {
- if (fLastStatement != null) {
- handleNewStatement(statement);
- } else {
- handleStatement(statement);
- fLastStatement= statement;
- }
- }
- }
-
- protected void handleStatement(Statement statement) {
- fStatements.add(fRewrite.createMoveTarget(statement));
- }
-
- protected void handleNewStatement(Statement statement) {
- fStatements.add(statement);
- }
-
- protected void handleInitializer(VariableDeclarationFragment fragment) {
- splitOffInitializer(fStatements, fragment, fRewrite);
- }
-
- }
-
- private static final class SplitUnselectedOperator implements ISplitOperation {
-
- private List fAccessedInside;
- private ListRewrite fBlockRewrite;
- private ASTRewrite fRewrite;
- private VariableDeclarationStatement fLastStatement;
-
- private SplitUnselectedOperator(List accessedInside, ListRewrite blockRewrite, ASTRewrite rewrite) {
- super();
- fAccessedInside= accessedInside;
- fBlockRewrite= blockRewrite;
- fRewrite= rewrite;
- fLastStatement= null;
- }
-
- public boolean needsSplit(VariableDeclarationFragment last, VariableDeclarationFragment current) {
- return fAccessedInside.contains(last) != fAccessedInside.contains(current);
- }
-
- public void initializeStatement(VariableDeclarationStatement statement, VariableDeclarationFragment current) {
- if (fAccessedInside.contains(current))
- makeFinal(statement, fRewrite);
-
- if (fLastStatement != null)
- fBlockRewrite.insertAfter(statement, fLastStatement, null);
- fLastStatement= statement;
- }
- }
-
- protected interface ISplitOperation {
- boolean needsSplit(VariableDeclarationFragment last, VariableDeclarationFragment current);
- void initializeStatement(VariableDeclarationStatement statement, VariableDeclarationFragment current);
- }
-
- private final JavaScriptUnit fRootNode;
- private final Statement[] fSelectedStatements;
- private boolean fIsNewContext;
- private ITrackedNodePosition fFirstInsertedPosition;
- private ITrackedNodePosition fLastInsertedPosition;
-
- public SurroundWith(JavaScriptUnit root, Statement[] selectedStatements) {
- fRootNode= root;
- fSelectedStatements= selectedStatements;
- }
-
-
- public static boolean isApplicable(IInvocationContext context) throws JavaScriptModelException {
- IJavaScriptUnit unit= context.getCompilationUnit();
- JavaScriptUnit ast= ASTProvider.getASTProvider().getAST(unit, ASTProvider.WAIT_NO, null);
- if (ast == null)
- return true;
-
- Selection selection= Selection.createFromStartLength(context.getSelectionOffset(), context.getSelectionLength());
- SurroundWithAnalyzer analyzer= new SurroundWithAnalyzer(unit, selection);
- context.getASTRoot().accept(analyzer);
-
- return analyzer.getStatus().isOK() && analyzer.hasSelectedNodes();
- }
-
- /**
- * Selected nodes in <code>context</code> under <code>selection</code> or null if no valid selection.
- * @param context The context in which the proposal is applyed.
- * @return Selected nodes or null if no valid selection.
- * @throws JavaScriptModelException
- */
- public static Statement[] getSelectedStatements(IInvocationContext context) throws JavaScriptModelException {
- Selection selection= Selection.createFromStartLength(context.getSelectionOffset(), context.getSelectionLength());
- SurroundWithAnalyzer analyzer= new SurroundWithAnalyzer(context.getCompilationUnit(), selection);
- context.getASTRoot().accept(analyzer);
-
- if (!analyzer.getStatus().isOK() || !analyzer.hasSelectedNodes()) {
- return null;
- } else {
- return analyzer.getSelectedStatements();
- }
- }
-
- public int getBodyStart() {
- return fFirstInsertedPosition.getStartPosition();
- }
-
- public int getBodyLength() {
- return fLastInsertedPosition.getStartPosition() + fLastInsertedPosition.getLength() - getBodyStart();
- }
-
- /**
- * Returns the rewriter to be used.
- * @return Returns the rewriter to be used.
- * @throws CoreException A core exception is thrown when the could not be created.
- */
- public ASTRewrite getRewrite() throws CoreException {
- Statement[] selectedStatements= fSelectedStatements;
- AST ast= getAst();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- BodyDeclaration enclosingBodyDeclaration= (BodyDeclaration)ASTNodes.getParent(selectedStatements[0], BodyDeclaration.class);
- int maxVariableId= LocalVariableIndex.perform(enclosingBodyDeclaration) + 1;
-
- fIsNewContext= isNewContext();
-
- List accessedAfter= getVariableDeclarationsAccessedAfter(selectedStatements[selectedStatements.length - 1], maxVariableId);
- List readInside;
- readInside= getVariableDeclarationReadsInside(selectedStatements, maxVariableId);
-
- List inserted= new ArrayList();
- moveToBlock(selectedStatements, inserted, accessedAfter, readInside, rewrite);
- if (fIsNewContext) {
- ImportRewrite importRewrite= StubUtility.createImportRewrite((JavaScriptUnit)selectedStatements[0].getRoot(), false);
- for (int i= 0; i < selectedStatements.length; i++) {
- qualifyThisExpressions(selectedStatements[i], rewrite, importRewrite);
- }
- }
-
- if (selectedStatements.length == 1 && ASTNodes.isControlStatementBody(selectedStatements[0].getLocationInParent())) {
- Block wrap= ast.newBlock();
- rewrite.replace(selectedStatements[0], wrap, null);
- ListRewrite listRewrite= rewrite.getListRewrite(wrap, Block.STATEMENTS_PROPERTY);
-
- for (Iterator iterator= inserted.iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- listRewrite.insertLast(node, null);
- }
-
- } else {
- ListRewrite listRewrite= getListRewrite(selectedStatements[0], rewrite);
-
- ASTNode current= selectedStatements[selectedStatements.length - 1];
- for (Iterator iterator= inserted.iterator(); iterator.hasNext();) {
- ASTNode node= (ASTNode)iterator.next();
- listRewrite.insertAfter(node, current, null);
- current= node;
- }
- }
-
- fFirstInsertedPosition= rewrite.track((ASTNode)inserted.get(0));
- fLastInsertedPosition= rewrite.track((ASTNode)inserted.get(inserted.size() - 1));
-
- return rewrite;
- }
-
-
- /**
- * @return true if the code will be moved to a new context?
- */
- protected abstract boolean isNewContext();
-
- /**
- * List of VariableDeclaration of variables which are read in <code>selectedNodes</code>.
- *
- * @param maxVariableId Maximum number of variable declarations block
- * @param selectedNodes The selectedNodes
- * @return List of VariableDeclaration
- */
- protected List getVariableDeclarationReadsInside(Statement[] selectedNodes, int maxVariableId) {
- ArrayList result= new ArrayList();
- if (!fIsNewContext)
- return result;
-
- IVariableBinding[] reads= getReads(selectedNodes, maxVariableId);
- for (int i= 0; i < reads.length; i++) {
- IVariableBinding read= reads[i];
- if (!read.isField()) {
- ASTNode readDecl= getRootNode().findDeclaringNode(read);
- if (readDecl instanceof VariableDeclaration) {
- result.add(readDecl);
- }
- }
- }
-
- return result;
- }
-
- /**
- * List of VariableDeclarationFragments which are accessed after <code>startNode</code>.
- *
- * @param startNode The node after to inspect
- * @param maxVariableId The maximum number of variable declarations
- * @return List of VariableDeclarationFragments which can't be moved to the new block
- */
- protected List getVariableDeclarationsAccessedAfter(ASTNode startNode, int maxVariableId) {
-
- List statements;
- if (startNode.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) {
- SwitchStatement block= (SwitchStatement)ASTNodes.getParent(startNode, SwitchStatement.class);
- statements= block.statements();
- } else {
- Block block= (Block)ASTNodes.getParent(startNode, Block.class);
- statements= block.statements();
- }
- List bodyAfterSelection= statements.subList(statements.indexOf(startNode) + 1, statements.size());
-
- List result= new ArrayList();
- if (!bodyAfterSelection.isEmpty()) {
-
- IVariableBinding[] accesses= getAccesses((ASTNode[]) bodyAfterSelection.toArray(new ASTNode[bodyAfterSelection.size()]), maxVariableId);
-
- for (int i= 0; i < accesses.length; i++) {
- IVariableBinding curVar= accesses[i];
- if (!curVar.isField()) {
- ASTNode readDecl= ASTNodes.findDeclaration(curVar, getRootNode());
- if (readDecl instanceof VariableDeclarationFragment) {
- result.add(readDecl);
- }
- }
- }
- }
- return result;
- }
-
- /**
- * @param region The region to inspect
- * @param maxVariableId Max number of variables in region
- * @return All variables with read access in region
- */
- private IVariableBinding[] getReads(ASTNode[] region, int maxVariableId) {
- FlowContext flowContext= new FlowContext(0, maxVariableId);
- flowContext.setConsiderAccessMode(true);
- flowContext.setComputeMode(FlowContext.ARGUMENTS);
- FlowInfo argInfo= new InOutFlowAnalyzer(flowContext).perform(region);
- IVariableBinding[] reads= argInfo.get(flowContext, FlowInfo.READ | FlowInfo.READ_POTENTIAL | FlowInfo.UNKNOWN);
- return reads;
- }
-
- /**
- * @param region The region to inspect
- * @param maxVariableId Max number of variables in region
- * @return All variables with read or write access in region
- */
- private IVariableBinding[] getAccesses(ASTNode[] region, int maxVariableId) {
- FlowContext flowContext= new FlowContext(0, maxVariableId);
- flowContext.setConsiderAccessMode(true);
- flowContext.setComputeMode(FlowContext.ARGUMENTS);
- FlowInfo argInfo= new InOutFlowAnalyzer(flowContext).perform(region);
- IVariableBinding[] varsAccessedAfter= argInfo.get(flowContext, FlowInfo.READ | FlowInfo.READ_POTENTIAL | FlowInfo.WRITE | FlowInfo.WRITE_POTENTIAL | FlowInfo.UNKNOWN);
- return varsAccessedAfter;
- }
-
- /**
- * Moves the nodes in toMove to <code>block</block> except the VariableDeclarationFragments
- * in <code>accessedAfter</code>. The initializers (if any) of variable declarations
- * in <code>accessedAfter</code> are moved to the block if the variable declaration is
- * part of <code>toMove</code>. VariableDeclarations in <code>accessedInside</code> are
- * made final unless they are moved to <code>block</code>.
- *
- * i.e. (if <code>i</code> is element of <code>accessedAfter</code>):
- * <code>int i= 10;</code> ---> <code>int i;</code> and <code>{i= 10;}</code>
- *
- * Declarations with more then one fragments are splited if required. i.e.:
- * <code>int i,j,k;</code> ---> <code>int i,j; final int k;</code>
- *
- * @param toMove Nodes to be moved to block
- * @param statements List to move to.
- * @param accessedAfter VariableDeclarationFragments which can not be moved to block
- * @param accessedInside VariableDeclaration which can be made final
- * @param rewrite The rewrite to use.
- */
- private final void moveToBlock(Statement[] toMove, List statements, final List/*<VariableDeclarationFragment>*/ accessedAfter, final List/*<VariableDeclaration>*/ accessedInside, final ASTRewrite rewrite) {
-
- for (int i= 0; i < toMove.length; i++) {
- ASTNode node= toMove[i];
- if (node instanceof VariableDeclarationStatement) {
- VariableDeclarationStatement statement= (VariableDeclarationStatement)node;
- final ListRewrite blockRewrite= getListRewrite(statement, rewrite);
-
- splitVariableDeclarationStatement(statement, createSplitSelectedOperator(accessedAfter, accessedInside, rewrite, statements, blockRewrite), rewrite);
-
- for (Iterator iter= statement.fragments().iterator(); iter.hasNext();) {
- accessedInside.remove(iter.next());
- }
- } else {
- insertNodeAtEnd(rewrite, statements, node);
- }
- }
-
- while (!accessedInside.isEmpty()) {
- VariableDeclaration variableDeclaration= (VariableDeclaration)accessedInside.get(0);
- if (variableDeclaration instanceof SingleVariableDeclaration) {
- if (ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(variableDeclaration)) == null) {
- ModifierRewrite.create(rewrite, variableDeclaration).setModifiers(Modifier.FINAL, Modifier.NONE, null);
- }
- accessedInside.remove(0);
- } else if (variableDeclaration.getParent() instanceof VariableDeclarationStatement) {
- VariableDeclarationStatement statement= (VariableDeclarationStatement)variableDeclaration.getParent();
- final ListRewrite blockRewrite= getListRewrite(statement, rewrite);
-
- splitVariableDeclarationStatement(statement, createSplitUnselectedOperator(accessedInside, rewrite, blockRewrite), rewrite);
-
- for (Iterator iter= statement.fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)iter.next();
- accessedInside.remove(fragment);
- }
- } else if (variableDeclaration.getParent() instanceof VariableDeclarationExpression) {
- VariableDeclarationExpression expression= (VariableDeclarationExpression)variableDeclaration.getParent();
-
- VariableDeclarationRewrite.rewriteModifiers(expression, Modifier.FINAL, 0, rewrite, null);
-
- for (Iterator iter= expression.fragments().iterator(); iter.hasNext();) {
- VariableDeclarationFragment fragment= (VariableDeclarationFragment)iter.next();
- accessedInside.remove(fragment);
- }
- }
- }
- }
-
- private void insertNodeAtEnd(final ASTRewrite rewrite, final List statements, ASTNode node) {
- statements.add(rewrite.createMoveTarget(node));
- }
-
- protected ISplitOperation createSplitUnselectedOperator(List accessedInside, ASTRewrite rewrite, ListRewrite blockRewrite) {
- return new SplitUnselectedOperator(accessedInside, blockRewrite, rewrite);
- }
-
- protected ISplitOperation createSplitSelectedOperator(List accessedAfter, List accessedInside, ASTRewrite rewrite, List statements, ListRewrite blockRewrite) {
- return new SplitSelectedOperator(accessedInside, accessedAfter, blockRewrite, rewrite, statements);
- }
-
- /**
- * Split the fragments in <code>statement</code> to multiple VariableDeclarationStatements whenever
- * <code>splitOperator.needsSplit</code> returns <code>true</code>.
- * i.e.:
- * int i, j; ---> int i; int j; (if splitOperator.needsSplit(i, j) == true)
- *
- * @param statement The VariableDeclarationStatement to split
- * @param splitOperator The operator to use to split
- * @param rewrite The rewriter to use to generate new VariableDeclarationStatements.
- */
- private void splitVariableDeclarationStatement(VariableDeclarationStatement statement, ISplitOperation splitOperator, ASTRewrite rewrite) {
-
- List fragments= statement.fragments();
- Iterator iter= fragments.iterator();
- VariableDeclarationFragment lastFragment= (VariableDeclarationFragment)iter.next();
- VariableDeclarationStatement lastStatement= statement;
-
- splitOperator.initializeStatement(lastStatement, lastFragment);
-
- ListRewrite fragmentsRewrite= null;
- while (iter.hasNext()) {
- VariableDeclarationFragment currentFragment= (VariableDeclarationFragment)iter.next();
-
- if (splitOperator.needsSplit(lastFragment, currentFragment)) {
-
- VariableDeclarationStatement newStatement= getAst().newVariableDeclarationStatement((VariableDeclarationFragment)rewrite.createMoveTarget(currentFragment));
-
- ListRewrite modifierRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
- for (Iterator iterator= statement.modifiers().iterator(); iterator.hasNext();) {
- modifierRewrite.insertLast(rewrite.createCopyTarget((ASTNode)iterator.next()), null);
- }
-
- newStatement.setType((Type)rewrite.createCopyTarget(statement.getType()));
-
- splitOperator.initializeStatement(newStatement, currentFragment);
-
- fragmentsRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.FRAGMENTS_PROPERTY);
-
- lastStatement= newStatement;
- } else if (fragmentsRewrite != null) {
- ASTNode fragment0= rewrite.createMoveTarget(currentFragment);
- fragmentsRewrite.insertLast(fragment0, null);
- }
- lastFragment= currentFragment;
- }
- }
-
- /**
- * Make statement final
- * @param statement
- * @param rewrite
- */
- protected static void makeFinal(VariableDeclarationStatement statement, ASTRewrite rewrite) {
- VariableDeclaration fragment= (VariableDeclaration)statement.fragments().get(0);
- if (ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragment)) == null) {
- ModifierRewrite.create(rewrite, statement).setModifiers(Modifier.FINAL, Modifier.NONE, null);
- }
- }
-
- private void qualifyThisExpressions(ASTNode node, final ASTRewrite rewrite, final ImportRewrite importRewrite) {
- node.accept(new GenericVisitor() {
- /**
- * {@inheritDoc}
- */
- public boolean visit(ThisExpression thisExpr) {
- if (thisExpr.getQualifier() == null) {
- ITypeBinding typeBinding= thisExpr.resolveTypeBinding();
- if (typeBinding != null) {
- IJavaScriptElement javaElement= typeBinding.getJavaElement();
- if (javaElement instanceof IType) {
- String typeName= ((IType)javaElement).getElementName();
- SimpleName simpleName= thisExpr.getAST().newSimpleName(typeName);
- rewrite.set(thisExpr, ThisExpression.QUALIFIER_PROPERTY, simpleName, null);
- }
- }
- }
- return super.visit(thisExpr);
- }
- });
- }
-
- /**
- * Split off initializer in <code>fragment</code> (if any) and add it as a new expression at the end of <code>statements</code>.
- * @param statements The home of the new expression.
- * @param fragment The fragment to split.
- * @param rewrite The rewrite to use.
- */
- protected static void splitOffInitializer(List statements, VariableDeclarationFragment fragment, ASTRewrite rewrite) {
- Expression initializer= fragment.getInitializer();
- if (initializer != null) {
- AST ast= rewrite.getAST();
- Assignment assignment= ast.newAssignment();
- assignment.setLeftHandSide((Expression)rewrite.createCopyTarget(fragment.getName()));
- assignment.setRightHandSide((Expression)rewrite.createMoveTarget(initializer));
- statements.add(ast.newExpressionStatement(assignment));
- }
- }
-
- /**
- * Get a list rewrite for statement sequence node is element
- * @param node
- * @param rewrite
- * @return The list rewrite
- */
- private ListRewrite getListRewrite(ASTNode node, ASTRewrite rewrite) {
- if (node.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) {
- ASTNode block= ASTNodes.getParent(node, SwitchStatement.class);
- return rewrite.getListRewrite(block, SwitchStatement.STATEMENTS_PROPERTY);
- } else {
- ASTNode block= ASTNodes.getParent(node, Block.class);
- return rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
- }
- }
-
- protected final AST getAst() {
- return getRootNode().getAST();
- }
-
- protected final Statement[] getSelectedStatements() {
- return fSelectedStatements;
- }
-
- private JavaScriptUnit getRootNode() {
- if (fSelectedStatements.length > 0)
- return (JavaScriptUnit)fSelectedStatements[0].getRoot();
- return fRootNode;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TaskMarkerProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TaskMarkerProposal.java
deleted file mode 100644
index da15b815..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TaskMarkerProposal.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-/**
- */
-public class TaskMarkerProposal extends CUCorrectionProposal {
-
- private IProblemLocation fLocation;
-
- public TaskMarkerProposal(IJavaScriptUnit cu, IProblemLocation location, int relevance) {
- super("", cu, relevance, null); //$NON-NLS-1$
- fLocation= location;
-
- setDisplayName(CorrectionMessages.TaskMarkerProposal_description);
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#addEdits(org.eclipse.wst.jsdt.internal.corext.textmanipulation.TextBuffer)
- */
- protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
- super.addEdits(document, rootEdit);
-
- try {
- Position pos= getUpdatedPosition(document);
- if (pos != null) {
- rootEdit.addChild(new ReplaceEdit(pos.getOffset(), pos.getLength(), "")); //$NON-NLS-1$
- } else {
- rootEdit.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), "")); //$NON-NLS-1$
- }
- } catch (BadLocationException e) {
- throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
- }
- }
-
- private Position getUpdatedPosition(IDocument document) throws BadLocationException {
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(document.get().toCharArray());
-
- int token= getSurroundingComment(scanner);
- if (token == ITerminalSymbols.TokenNameEOF) {
- return null;
- }
- int commentStart= scanner.getCurrentTokenStartPosition();
- int commentEnd= scanner.getCurrentTokenEndPosition() + 1;
-
- int contentStart= commentStart + 2;
- int contentEnd= commentEnd;
- if (token == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) {
- contentStart= commentStart + 3;
- contentEnd= commentEnd - 2;
- } else if (token == ITerminalSymbols.TokenNameCOMMENT_BLOCK) {
- contentEnd= commentEnd - 2;
- }
- if (hasContent(document, contentStart, fLocation.getOffset()) || hasContent(document, contentEnd, fLocation.getOffset() + fLocation.getLength())) {
- return new Position(fLocation.getOffset(), fLocation.getLength());
- }
-
- IRegion startRegion= document.getLineInformationOfOffset(commentStart);
- int start= startRegion.getOffset();
- boolean contentAtBegining= hasContent(document, start, commentStart);
-
- if (contentAtBegining) {
- start= commentStart;
- }
-
- int end;
- if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
- if (contentAtBegining) {
- end= startRegion.getOffset() + startRegion.getLength(); // only to the end of the line
- } else {
- end= commentEnd; // includes new line
- }
- } else {
- int endLine= document.getLineOfOffset(commentEnd - 1);
- if (endLine + 1 == document.getNumberOfLines() || contentAtBegining) {
- IRegion endRegion= document.getLineInformation(endLine);
- end= endRegion.getOffset() + endRegion.getLength();
- } else {
- IRegion endRegion= document.getLineInformation(endLine + 1);
- end= endRegion.getOffset();
- }
- }
- if (hasContent(document, commentEnd, end)) {
- end= commentEnd;
- start= commentStart; // only remove comment
- }
- return new Position(start, end - start);
- }
-
- private int getSurroundingComment(IScanner scanner) {
- try {
- int start= fLocation.getOffset();
- int end= start + fLocation.getLength();
-
- int token= scanner.getNextToken();
- while (token != ITerminalSymbols.TokenNameEOF) {
- if (TokenScanner.isComment(token)) {
- int currStart= scanner.getCurrentTokenStartPosition();
- int currEnd= scanner.getCurrentTokenEndPosition() + 1;
- if (currStart <= start && end <= currEnd) {
- return token;
- }
- }
- token= scanner.getNextToken();
- }
-
- } catch (InvalidInputException e) {
- // ignore
- }
- return ITerminalSymbols.TokenNameEOF;
- }
-
- private boolean hasContent(IDocument document, int start, int end) throws BadLocationException {
- for (int i= start; i < end; i++) {
- char ch= document.getChar(i);
- if (!Character.isWhitespace(ch)) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeChangeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeChangeCompletionProposal.java
deleted file mode 100644
index a76ee19d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeChangeCompletionProposal.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.FieldDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class TypeChangeCompletionProposal extends LinkedCorrectionProposal {
-
- private IBinding fBinding;
- private JavaScriptUnit fAstRoot;
- private ITypeBinding fNewType;
- private boolean fOfferSuperTypeProposals;
-
- public TypeChangeCompletionProposal(IJavaScriptUnit targetCU, IBinding binding, JavaScriptUnit astRoot, ITypeBinding newType, boolean offerSuperTypeProposals, int relevance) {
- super("", targetCU, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); //$NON-NLS-1$
-
- Assert.isTrue(binding != null && (binding.getKind() == IBinding.METHOD || binding.getKind() == IBinding.VARIABLE) && Bindings.isDeclarationBinding(binding));
-
- fBinding= binding; // must be generic method or (generic) variable
- fAstRoot= astRoot;
- fNewType= newType;
- fOfferSuperTypeProposals= offerSuperTypeProposals;
-
- String typeName= BindingLabelProvider.getBindingLabel(newType, JavaScriptElementLabels.ALL_DEFAULT);
- if (binding.getKind() == IBinding.VARIABLE) {
- IVariableBinding varBinding= (IVariableBinding) binding;
-
- String[] args= { varBinding.getName(), typeName};
- if (varBinding.isField()) {
- setDisplayName(Messages.format(CorrectionMessages.TypeChangeCompletionProposal_field_name, args));
- } else if (astRoot.findDeclaringNode(binding) instanceof SingleVariableDeclaration) {
- setDisplayName(Messages.format(CorrectionMessages.TypeChangeCompletionProposal_param_name, args));
- } else {
- setDisplayName(Messages.format(CorrectionMessages.TypeChangeCompletionProposal_variable_name, args));
- }
- } else {
- String[] args= { binding.getName(), typeName };
- setDisplayName(Messages.format(CorrectionMessages.TypeChangeCompletionProposal_method_name, args));
- }
- }
-
- protected ASTRewrite getRewrite() throws CoreException {
- ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding);
- ASTNode declNode= null;
- JavaScriptUnit newRoot= fAstRoot;
- if (boundNode != null) {
- declNode= boundNode; // is same CU
- } else {
- newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
- declNode= newRoot.findDeclaringNode(fBinding.getKey());
- }
- if (declNode != null) {
- AST ast= declNode.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- ImportRewrite imports= createImportRewrite(newRoot);
-
- Type type= imports.addImport(fNewType, ast);
-
- if (declNode instanceof FunctionDeclaration) {
- FunctionDeclaration methodDecl= (FunctionDeclaration) declNode;
- rewrite.set(methodDecl, FunctionDeclaration.RETURN_TYPE2_PROPERTY, type, null);
- rewrite.set(methodDecl, FunctionDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
- } else if (declNode instanceof VariableDeclarationFragment) {
- ASTNode parent= declNode.getParent();
- if (parent instanceof FieldDeclaration) {
- FieldDeclaration fieldDecl= (FieldDeclaration) parent;
- if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split
- VariableDeclarationFragment placeholder= (VariableDeclarationFragment) rewrite.createMoveTarget(declNode);
- FieldDeclaration newField= ast.newFieldDeclaration(placeholder);
- newField.setType(type);
- AbstractTypeDeclaration typeDecl= (AbstractTypeDeclaration) fieldDecl.getParent();
-
- ListRewrite listRewrite= rewrite.getListRewrite(typeDecl, typeDecl.getBodyDeclarationsProperty());
- if (fieldDecl.fragments().indexOf(declNode) == 0) { // if it as the first in the list-> insert before
- listRewrite.insertBefore(newField, parent, null);
- } else {
- listRewrite.insertAfter(newField, parent, null);
- }
- } else {
- rewrite.set(fieldDecl, FieldDeclaration.TYPE_PROPERTY, type, null);
- rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
- }
- } else if (parent instanceof VariableDeclarationStatement) {
- VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent;
- if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split
- VariableDeclarationFragment placeholder= (VariableDeclarationFragment) rewrite.createMoveTarget(declNode);
- VariableDeclarationStatement newStat= ast.newVariableDeclarationStatement(placeholder);
- newStat.setType(type);
-
- ListRewrite listRewrite= rewrite.getListRewrite(varDecl.getParent(), Block.STATEMENTS_PROPERTY);
- if (varDecl.fragments().indexOf(declNode) == 0) { // if it as the first in the list-> insert before
- listRewrite.insertBefore(newStat, parent, null);
- } else {
- listRewrite.insertAfter(newStat, parent, null);
- }
- } else {
- rewrite.set(varDecl, VariableDeclarationStatement.TYPE_PROPERTY, type, null);
- rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
- }
- } else if (parent instanceof VariableDeclarationExpression) {
- VariableDeclarationExpression varDecl= (VariableDeclarationExpression) parent;
-
- rewrite.set(varDecl, VariableDeclarationExpression.TYPE_PROPERTY, type, null);
- rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
- }
- } else if (declNode instanceof SingleVariableDeclaration) {
- SingleVariableDeclaration variableDeclaration= (SingleVariableDeclaration) declNode;
- rewrite.set(variableDeclaration, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
- rewrite.set(variableDeclaration, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null);
- }
-
- // set up linked mode
- final String KEY_TYPE= "type"; //$NON-NLS-1$
- addLinkedPosition(rewrite.track(type), true, KEY_TYPE);
- if (fOfferSuperTypeProposals) {
- ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, fNewType);
- for (int i= 0; i < typeProposals.length; i++) {
- addLinkedPositionProposal(KEY_TYPE, typeProposals[i]);
- }
- }
- return rewrite;
- }
- return null;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeMismatchSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeMismatchSubProcessor.java
deleted file mode 100644
index 95640c10..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/TypeMismatchSubProcessor.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-
-public class TypeMismatchSubProcessor {
-
- private TypeMismatchSubProcessor() {
- }
-
- public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- String[] args= problem.getProblemArguments();
- if (args.length != 2) {
- return;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- AST ast= astRoot.getAST();
-
- ASTNode selectedNode= problem.getCoveredNode(astRoot);
- if (!(selectedNode instanceof Expression)) {
- return;
- }
- Expression nodeToCast= (Expression) selectedNode;
- Name receiverNode= null;
- ITypeBinding castTypeBinding= null;
-
- int parentNodeType= selectedNode.getParent().getNodeType();
- if (parentNodeType == ASTNode.ASSIGNMENT) {
- Assignment assign= (Assignment) selectedNode.getParent();
- Expression leftHandSide= assign.getLeftHandSide();
- if (selectedNode.equals(leftHandSide)) {
- nodeToCast= assign.getRightHandSide();
- }
- castTypeBinding= assign.getLeftHandSide().resolveTypeBinding();
- if (leftHandSide instanceof Name) {
- receiverNode= (Name) leftHandSide;
- } else if (leftHandSide instanceof FieldAccess) {
- receiverNode= ((FieldAccess) leftHandSide).getName();
- }
- } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
- VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
- if (selectedNode.equals(frag.getName()) || selectedNode.equals(frag.getInitializer())) {
- nodeToCast= frag.getInitializer();
- castTypeBinding= ASTNodes.getType(frag).resolveBinding();
- receiverNode= frag.getName();
- }
- } else {
- // try to find the binding corresponding to 'castTypeName'
- castTypeBinding= ASTResolving.guessBindingForReference(nodeToCast);
- }
- if (castTypeBinding == null) {
- return;
- }
-
- ITypeBinding currBinding= nodeToCast.resolveTypeBinding();
-
- boolean nullOrVoid= currBinding == null || "void".equals(currBinding.getName()); //$NON-NLS-1$
-
- // change method return statement to actual type
- if (!nullOrVoid && parentNodeType == ASTNode.RETURN_STATEMENT) {
- BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
- if (decl instanceof FunctionDeclaration) {
- FunctionDeclaration methodDeclaration= (FunctionDeclaration) decl;
-
-
- currBinding= Bindings.normalizeTypeBinding(currBinding);
- if (currBinding == null) {
- currBinding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
-
- String label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, currBinding.getName());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
-
- ImportRewrite imports= proposal.createImportRewrite(astRoot);
-
- Type newReturnType= imports.addImport(currBinding, ast);
- rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
-
- String returnKey= "return"; //$NON-NLS-1$
- proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey);
- ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(ast, currBinding);
- for (int i= 0; i < typeSuggestions.length; i++) {
- proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]);
- }
- proposals.add(proposal);
- }
- }
-
- if (!nullOrVoid && receiverNode != null) {
- currBinding= Bindings.normalizeTypeBinding(currBinding);
- if (currBinding == null) {
- currBinding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
- addChangeSenderTypeProposals(context, receiverNode, currBinding, true, 6, proposals);
- }
-
- addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, 5, proposals);
- }
-
- public static void addChangeSenderTypeProposals(IInvocationContext context, Expression nodeToCast, ITypeBinding castTypeBinding, boolean isAssignedNode, int relevance, Collection proposals) throws JavaScriptModelException {
- IBinding callerBinding= null;
- switch (nodeToCast.getNodeType()) {
- case ASTNode.FUNCTION_INVOCATION:
- callerBinding= ((FunctionInvocation) nodeToCast).resolveMethodBinding();
- break;
- case ASTNode.SUPER_METHOD_INVOCATION:
- callerBinding= ((SuperMethodInvocation) nodeToCast).resolveMethodBinding();
- break;
- case ASTNode.FIELD_ACCESS:
- callerBinding= ((FieldAccess) nodeToCast).resolveFieldBinding();
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- callerBinding= ((SuperFieldAccess) nodeToCast).resolveFieldBinding();
- break;
- case ASTNode.SIMPLE_NAME:
- case ASTNode.QUALIFIED_NAME:
- callerBinding= ((Name) nodeToCast).resolveBinding();
- break;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- JavaScriptUnit astRoot= context.getASTRoot();
-
- IJavaScriptUnit targetCu= null;
- ITypeBinding declaringType= null;
- IBinding callerBindingDecl= callerBinding;
- if (callerBinding instanceof IVariableBinding) {
- IVariableBinding variableBinding= (IVariableBinding) callerBinding;
-
- if (!variableBinding.isField()) {
- targetCu= cu;
- } else {
- callerBindingDecl= variableBinding.getVariableDeclaration();
- ITypeBinding declaringClass= variableBinding.getDeclaringClass();
- if (declaringClass == null) {
- return; // array length
- }
- declaringType= declaringClass.getTypeDeclaration();
- }
- } else if (callerBinding instanceof IFunctionBinding) {
- IFunctionBinding methodBinding= (IFunctionBinding) callerBinding;
- if (!methodBinding.isConstructor()) {
- declaringType= methodBinding.getDeclaringClass().getTypeDeclaration();
- callerBindingDecl= methodBinding.getMethodDeclaration();
- }
- }
-
- if (declaringType != null && declaringType.isFromSource()) {
- targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
- }
- if (targetCu != null && ASTResolving.isUseableTypeInContext(castTypeBinding, callerBindingDecl, false)) {
- proposals.add(new TypeChangeCompletionProposal(targetCu, callerBindingDecl, astRoot, castTypeBinding, isAssignedNode, relevance));
- }
- }
-
- public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaScriptModelException {
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
- FunctionDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
- if (decl == null) {
- return;
- }
- IFunctionBinding methodDeclBinding= decl.resolveBinding();
- if (methodDeclBinding == null) {
- return;
- }
-
- IFunctionBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
- if (overridden == null || overridden.getReturnType() == methodDeclBinding.getReturnType()) {
- return;
- }
-
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- IFunctionBinding methodDecl= methodDeclBinding.getMethodDeclaration();
- proposals.add(new TypeChangeCompletionProposal(cu, methodDecl, astRoot, overridden.getReturnType(), false, 8));
-
- IJavaScriptUnit targetCu= cu;
-
- IFunctionBinding overriddenDecl= overridden.getMethodDeclaration();
- ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();
-
- ITypeBinding returnType= methodDeclBinding.getReturnType();
- if (overridenDeclType.isFromSource()) {
- targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
- }
- if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
- TypeChangeCompletionProposal proposal= new TypeChangeCompletionProposal(targetCu, overriddenDecl, astRoot, returnType, false, 7);
- proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, overriddenDecl.getName()));
- proposals.add(proposal);
- }
- }
-
- public static void addIncompatibleThrowsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaScriptModelException {
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (!(selectedNode instanceof FunctionDeclaration)) {
- return;
- }
- FunctionDeclaration decl= (FunctionDeclaration) selectedNode;
- IFunctionBinding methodDeclBinding= decl.resolveBinding();
- if (methodDeclBinding == null) {
- return;
- }
-
- IFunctionBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
- if (overridden == null) {
- return;
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ArrayList undeclaredExceptions= new ArrayList();
- {
- ChangeDescription[] changes= new ChangeDescription[0];
-
- String label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_removeexceptions_description, methodDeclBinding.getName());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
- proposals.add(new ChangeMethodSignatureProposal(label, cu, astRoot, methodDeclBinding, null, changes, 8, image));
- }
-
- ITypeBinding declaringType= overridden.getDeclaringClass();
- IJavaScriptUnit targetCu= cu;
- if (declaringType.isFromSource()) {
- targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
- }
- if (targetCu != null) {
- ChangeDescription[] changes= new ChangeDescription[undeclaredExceptions.size()];
-
- for (int i= 0; i < undeclaredExceptions.size(); i++) {
- changes[i]= new InsertDescription((ITypeBinding) undeclaredExceptions.get(i), ""); //$NON-NLS-1$
- }
- IFunctionBinding overriddenDecl= overridden.getMethodDeclaration();
- String[] args= { declaringType.getName(), overridden.getName() };
- String label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_addexceptions_description, args);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
- proposals.add(new ChangeMethodSignatureProposal(label, targetCu, astRoot, overriddenDecl, null, changes, 7, image));
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java
deleted file mode 100644
index d1a5fad0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class UnimplementedMethodsCompletionProposal extends ASTRewriteCorrectionProposal {
-
- private ASTNode fTypeNode;
- private IFunctionBinding[] fMethodsToOverride;
-
- public UnimplementedMethodsCompletionProposal(IJavaScriptUnit cu, ASTNode typeNode, int relevance) {
- super("", cu, null, relevance, null); //$NON-NLS-1$
- setDisplayName(CorrectionMessages.UnimplementedMethodsCompletionProposal_description);
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
-
- fTypeNode= typeNode;
- fMethodsToOverride= null;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
- */
- protected ASTRewrite getRewrite() throws CoreException {
- ITypeBinding binding;
- AST ast= fTypeNode.getAST();
-
- ASTRewrite rewrite= ASTRewrite.create(ast);
- ListRewrite listRewrite;
- if (fTypeNode instanceof AnonymousClassDeclaration) {
- AnonymousClassDeclaration decl= (AnonymousClassDeclaration) fTypeNode;
- binding= decl.resolveBinding();
- listRewrite= rewrite.getListRewrite(decl, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- } else {
- AbstractTypeDeclaration decl= (AbstractTypeDeclaration) fTypeNode;
- binding= decl.resolveBinding();
- listRewrite= rewrite.getListRewrite(decl, decl.getBodyDeclarationsProperty());
- }
- IFunctionBinding[] methods= StubUtility2.getUnimplementedMethods(binding);
- fMethodsToOverride= methods;
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaScriptProject());
- if (binding.isAnonymous()) {
- settings.createComments= false;
- }
- ImportRewrite imports= createImportRewrite((JavaScriptUnit) fTypeNode.getRoot());
- ImportRewriteContext context= new ContextSensitiveImportRewriteContext((JavaScriptUnit) fTypeNode.getRoot(), fTypeNode.getStartPosition(), imports);
- for (int i= 0; i < methods.length; i++) {
- FunctionDeclaration newMethodDecl= StubUtility2.createImplementationStub(getCompilationUnit(), rewrite, imports, ast, methods[i], binding.getName(), settings, false, context);
- listRewrite.insertLast(newMethodDecl, null);
- }
- return rewrite;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.correction.CUCorrectionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- try {
- getChange(); // force the creation of the rewrite
- StringBuffer buf= new StringBuffer();
- buf.append("<b>"); //$NON-NLS-1$
- buf.append(Messages.format(CorrectionMessages.UnimplementedMethodsCompletionProposal_info, String.valueOf(fMethodsToOverride.length)));
- buf.append("</b><ul>"); //$NON-NLS-1$
- for (int i= 0; i < fMethodsToOverride.length; i++) {
- buf.append("<li>"); //$NON-NLS-1$
- buf.append(BindingLabelProvider.getBindingLabel(fMethodsToOverride[i], JavaScriptElementLabels.ALL_FULLY_QUALIFIED));
- buf.append("</li>"); //$NON-NLS-1$
- }
- buf.append("</ul>"); //$NON-NLS-1$
- return buf.toString();
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
deleted file mode 100644
index 283d37af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
+++ /dev/null
@@ -1,1464 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - New class/interface with wizard
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.correction;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTMatcher;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ArrayType;
-import org.eclipse.wst.jsdt.core.dom.Assignment;
-import org.eclipse.wst.jsdt.core.dom.BodyDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.ConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.FieldAccess;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionInvocation;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IPackageBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.core.dom.Name;
-import org.eclipse.wst.jsdt.core.dom.ParenthesizedExpression;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.SimpleType;
-import org.eclipse.wst.jsdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.SuperConstructorInvocation;
-import org.eclipse.wst.jsdt.core.dom.SuperFieldAccess;
-import org.eclipse.wst.jsdt.core.dom.SuperMethodInvocation;
-import org.eclipse.wst.jsdt.core.dom.SwitchCase;
-import org.eclipse.wst.jsdt.core.dom.SwitchStatement;
-import org.eclipse.wst.jsdt.core.dom.ThisExpression;
-import org.eclipse.wst.jsdt.core.dom.ThrowStatement;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.TypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodeFactory;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.ScopeAnalyzer;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-
-public class UnresolvedElementsSubProcessor {
-
- private static final String ADD_IMPORT_ID= "org.eclipse.wst.jsdt.ui.correction.addImport"; //$NON-NLS-1$
-
- public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, IVariableBinding resolvedField, Collection proposals) throws CoreException {
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveredNode(astRoot);
- if (selectedNode == null) {
- return;
- }
-
- // type that defines the variable
- ITypeBinding binding= null;
-
- /* Commented out BC rev 1. quickfixing case 'var k = new <undefinedType>' */
- ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentTypeContext(selectedNode);
-// if (declaringTypeBinding == null) {
-// return;
-// }
-
- // possible type kind of the node
- boolean suggestVariableProposals= true;
- int typeKind= 0;
-
- while (selectedNode instanceof ParenthesizedExpression) {
- selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
- }
-
-
- Name node= null;
-
- switch (selectedNode.getNodeType()) {
- case ASTNode.SIMPLE_NAME:
- node= (SimpleName) selectedNode;
- ASTNode parent= node.getParent();
- StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
- if (locationInParent == FunctionInvocation.EXPRESSION_PROPERTY) {
- typeKind= SimilarElementsRequestor.CLASSES;
- } else if (locationInParent == FieldAccess.NAME_PROPERTY) {
- Expression expression= ((FieldAccess) parent).getExpression();
- if (expression != null) {
- binding= expression.resolveTypeBinding();
- if (binding == null) {
- node= null;
- }
- }
- } else if (parent instanceof SimpleType || parent instanceof ClassInstanceCreation) {
-
- // suggestVariableProposals= false;
- // typeKind= SimilarElementsRequestor.REF_TYPES_AND_VAR;
- } else if (parent instanceof QualifiedName) {
- Name qualifier= ((QualifiedName) parent).getQualifier();
- if (qualifier != node) {
- binding= qualifier.resolveTypeBinding();
- } else {
- typeKind= SimilarElementsRequestor.REF_TYPES;
- }
- ASTNode outerParent= parent.getParent();
- while (outerParent instanceof QualifiedName) {
- outerParent= outerParent.getParent();
- }
- if (outerParent instanceof SimpleType) {
- typeKind= SimilarElementsRequestor.REF_TYPES;
- suggestVariableProposals= false;
- }
- } else if (locationInParent == SwitchCase.EXPRESSION_PROPERTY) {
- ITypeBinding switchExp= ((SwitchStatement) node.getParent().getParent()).getExpression().resolveTypeBinding();
- } else if (locationInParent == SuperFieldAccess.NAME_PROPERTY) {
- binding= declaringTypeBinding.getSuperclass();
- }
- break;
- case ASTNode.QUALIFIED_NAME:
- QualifiedName qualifierName= (QualifiedName) selectedNode;
- ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
- if (qualifierBinding != null) {
- node= qualifierName.getName();
- binding= qualifierBinding;
- } else {
- node= qualifierName.getQualifier();
- typeKind= SimilarElementsRequestor.REF_TYPES;
- suggestVariableProposals= node.isSimpleName();
- }
- if (selectedNode.getParent() instanceof SimpleType) {
- typeKind= SimilarElementsRequestor.REF_TYPES;
- suggestVariableProposals= false;
- }
- break;
- case ASTNode.FIELD_ACCESS:
- FieldAccess access= (FieldAccess) selectedNode;
- Expression expression= access.getExpression();
- if (expression != null) {
- binding= expression.resolveTypeBinding();
- if (binding != null) {
- node= access.getName();
- }
- }
- break;
- case ASTNode.SUPER_FIELD_ACCESS:
- binding= declaringTypeBinding.getSuperclass();
- node= ((SuperFieldAccess) selectedNode).getName();
- break;
- default:
- }
-
- if (node == null) {
- return;
- }
-
- // add type proposals
- if (typeKind != 0) {
- if (!JavaModelUtil.is50OrHigher(cu.getJavaScriptProject())) {
- typeKind &= ~(SimilarElementsRequestor.ANNOTATIONS | SimilarElementsRequestor.ENUMS | SimilarElementsRequestor.VARIABLES);
- }
-
- int relevance= Character.isUpperCase(ASTNodes.getSimpleNameIdentifier(node).charAt(0)) ? 5 : -2;
- addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
-
- typeKind &= ~SimilarElementsRequestor.ANNOTATIONS;
- addNewTypeProposals(cu, node, typeKind, relevance, proposals);
- }
-
- if (!suggestVariableProposals) {
- return;
- }
-
- SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
- boolean isWriteAccess= ASTResolving.isWriteAccess(node);
-
- // similar variables
- addSimilarVariableProposals(cu, astRoot, binding, simpleName, isWriteAccess, proposals);
-
- if (resolvedField == null || binding == null || resolvedField.getDeclaringClass() != binding.getTypeDeclaration() && Modifier.isPrivate(resolvedField.getModifiers())) {
-
- // new fields
- addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
-
- // new parameters and local variables
- if (binding == null) {
- addNewVariableProposals(cu, node, simpleName, proposals);
- }
- }
- }
-
- private static void addNewVariableProposals(IJavaScriptUnit cu, Name node, SimpleName simpleName, Collection proposals) {
- String name= simpleName.getIdentifier();
- ASTNode bodyDeclaration= ASTResolving.findParentBodyDeclaration(node, true);
- int type= bodyDeclaration.getNodeType();
- if (type == ASTNode.FUNCTION_DECLARATION) {
- int relevance= StubUtility.hasParameterName(cu.getJavaScriptProject(), name) ? 8 : 5;
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, simpleName.getIdentifier());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, relevance, image));
- }
- if (type == ASTNode.INITIALIZER || type == ASTNode.JAVASCRIPT_UNIT ||
- (type == ASTNode.FUNCTION_DECLARATION && !ASTResolving.isInsideConstructorInvocation((FunctionDeclaration) bodyDeclaration, node))) {
- int relevance= StubUtility.hasLocalVariableName(cu.getJavaScriptProject(), name) ? 10 : 7;
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createlocal_description, simpleName.getIdentifier());
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
- proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, relevance, image));
- }
-
- if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
- Assignment assignment= (Assignment) node.getParent();
- if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
- ASTNode statement= assignment.getParent();
- ASTRewrite rewrite= ASTRewrite.create(statement.getAST());
- if (ASTNodes.isControlStatementBody(assignment.getParent().getLocationInParent())) {
- rewrite.replace(statement, rewrite.getAST().newBlock(), null);
- } else {
- rewrite.remove(statement, null);
- }
- String label= CorrectionMessages.UnresolvedElementsSubProcessor_removestatement_description;
- Image image= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image);
- proposals.add(proposal);
- }
- }
- }
-
- private static void addNewFieldProposals(IJavaScriptUnit cu, JavaScriptUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaScriptModelException {
- // new variables
- IJavaScriptUnit targetCU;
- ITypeBinding senderDeclBinding;
- if (binding != null) {
- senderDeclBinding= binding.getTypeDeclaration();
- targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
- } else { // binding is null for accesses without qualifier
- senderDeclBinding= declaringTypeBinding;
- targetCU= cu;
- }
-
- if (senderDeclBinding==null || !senderDeclBinding.isFromSource() || targetCU == null) {
- return;
- }
-
- boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);
-
- addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);
-
- if (binding == null && senderDeclBinding.isNested()) {
- ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
- if (anonymDecl != null) {
- ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
- if (!bind.isAnonymous()) {
- addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
- }
- }
- }
- }
-
- private static void addNewFieldForType(IJavaScriptUnit targetCU, ITypeBinding binding, ITypeBinding senderDeclBinding, SimpleName simpleName, boolean isWriteAccess, boolean mustBeConst, Collection proposals) {
- String name= simpleName.getIdentifier();
- String label;
- Image image;
-
- if (!mustBeConst) {
- if (binding == null) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, name);
- image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description, new Object[] { name, ASTResolving.getTypeSignature(senderDeclBinding) } );
- image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
- }
- int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaScriptProject(), name) ? 9 : 6;
- proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderDeclBinding, fieldRelevance, image));
- }
-
- if (!isWriteAccess && !senderDeclBinding.isAnonymous()) {
- if (binding == null) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, name);
- image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description, new Object[] { name, ASTResolving.getTypeSignature(senderDeclBinding) } );
- image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
- }
- int constRelevance= StubUtility.hasConstantName(name) ? 9 : 4;
- proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, senderDeclBinding, constRelevance, image));
- }
- }
-
- private static void addSimilarVariableProposals(IJavaScriptUnit cu, JavaScriptUnit astRoot, ITypeBinding binding, SimpleName node, boolean isWriteAccess, Collection proposals) {
- int kind= ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
- if (!isWriteAccess) {
- kind |= ScopeAnalyzer.METHODS; // also try to find similar methods
- }
-
- IBinding[] varsAndMethodsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
- if (varsAndMethodsInScope.length > 0) {
- // avoid corrections like int i= i;
- String otherNameInAssign= null;
-
- // help with x.getString() -> y.getString()
- String methodSenderName= null;
- String fieldSenderName= null;
-
- ASTNode parent= node.getParent();
- switch (parent.getNodeType()) {
- case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
- // node must be initializer
- otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier();
- break;
- case ASTNode.ASSIGNMENT:
- Assignment assignment= (Assignment) parent;
- if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
- otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier();
- } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
- otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
- }
- break;
- case ASTNode.FUNCTION_INVOCATION:
- FunctionInvocation inv= (FunctionInvocation) parent;
- if (inv.getExpression() == node) {
- methodSenderName= inv.getName().getIdentifier();
- }
- break;
- case ASTNode.QUALIFIED_NAME:
- QualifiedName qualName= (QualifiedName) parent;
- if (qualName.getQualifier() == node) {
- fieldSenderName= qualName.getName().getIdentifier();
- }
- break;
- }
-
-
- ITypeBinding guessedType= ASTResolving.guessBindingForReference(node);
-
- ITypeBinding objectBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- String identifier= node.getIdentifier();
- boolean isInStaticContext= ASTResolving.isInStaticContext(node);
-
- loop: for (int i= 0; i < varsAndMethodsInScope.length; i++) {
- IBinding varOrMeth= varsAndMethodsInScope[i];
- if (varOrMeth instanceof IVariableBinding) {
- IVariableBinding curr= (IVariableBinding) varOrMeth;
- String currName= curr.getName();
- if (currName.equals(otherNameInAssign)) {
- continue loop;
- }
- boolean isFinal= Modifier.isFinal(curr.getModifiers());
- if (isFinal && curr.isField() && isWriteAccess) {
- continue loop;
- }
- if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
- continue loop;
- }
-
- int relevance= 0;
- if (NameMatcher.isSimilarName(currName, identifier)) {
- relevance += 3; // variable with a similar name than the unresolved variable
- }
- if (currName.equalsIgnoreCase(identifier)) {
- relevance+= 5;
- }
- ITypeBinding varType= curr.getType();
- if (varType != null) {
- if (guessedType != null && guessedType != objectBinding) { // too many result with object
- // variable type is compatible with the guessed type
- if (!isWriteAccess && canAssign(varType, guessedType)
- || isWriteAccess && canAssign(guessedType, varType)) {
- relevance += 2; // unresolved variable can be assign to this variable
- }
- }else if (guessedType==null && relevance==0) {
- /* type any? */
- relevance+=1;
- }
- if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
- relevance += 2;
- }
- if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
- relevance += 2;
- }
- }
-
- if (relevance > 0) {
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, currName);
- if(node.getParent() instanceof ClassInstanceCreation) {
- proposals.add(new RenameNodeCompletionProposal(label, cu, node.getParent().getStartPosition(), node.getParent().getLength(), currName, relevance));
- }else {
- proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
- }
- }
- } else if (varOrMeth instanceof IFunctionBinding) {
- IFunctionBinding curr= (IFunctionBinding) varOrMeth;
- if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
- if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
- AST ast= astRoot.getAST();
- ASTRewrite rewrite= ASTRewrite.create(ast);
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr, false));
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 8, image);
- proposals.add(proposal);
-
- FunctionInvocation newInv= ast.newFunctionInvocation();
- newInv.setName(ast.newSimpleName(curr.getName()));
- ITypeBinding[] parameterTypes= curr.getParameterTypes();
- for (int k= 0; k < parameterTypes.length; k++) {
- ASTNode arg= ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
- newInv.arguments().add(arg);
- proposal.addLinkedPosition(rewrite.track(arg), false, null);
- }
- rewrite.replace(node, newInv, null);
- }
- }
- }
- }
- }
- if (binding != null && binding.isArray()) {
- String idLength= "length"; //$NON-NLS-1$
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
- proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, 8));
- }
- }
-
- private static boolean canAssign(ITypeBinding returnType, ITypeBinding guessedType) {
- return returnType.isAssignmentCompatible(guessedType);
- }
-
- private static boolean hasMethodWithName(ITypeBinding typeBinding, String name) {
- IVariableBinding[] fields= typeBinding.getDeclaredFields();
- for (int i= 0; i < fields.length; i++) {
- if (fields[i].getName().equals(name)) {
- return true;
- }
- }
- ITypeBinding superclass= typeBinding.getSuperclass();
- if (superclass != null) {
- return hasMethodWithName(superclass, name);
- }
- return false;
- }
-
- private static boolean hasFieldWithName(ITypeBinding typeBinding, String name) {
- IFunctionBinding[] methods= typeBinding.getDeclaredMethods();
- for (int i= 0; i < methods.length; i++) {
- if (methods[i].getName().equals(name)) {
- return true;
- }
- }
- ITypeBinding superclass= typeBinding.getSuperclass();
- if (superclass != null) {
- return hasMethodWithName(superclass, name);
- }
- return false;
- }
-
- private static int evauateTypeKind(ASTNode node, IJavaScriptProject project) {
- int kind= ASTResolving.getPossibleTypeKinds(node, JavaModelUtil.is50OrHigher(project));
- return kind;
- }
-
-
- public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
- if (selectedNode == null) {
- return;
- }
-
- int kind= evauateTypeKind(selectedNode, cu.getJavaScriptProject());
-
- while (selectedNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
- selectedNode= selectedNode.getParent();
- }
-
- Name node= null;
- if (selectedNode instanceof SimpleType) {
- node= ((SimpleType) selectedNode).getName();
- } else if (selectedNode instanceof ArrayType) {
- Type elementType= ((ArrayType) selectedNode).getElementType();
- if (elementType.isSimpleType()) {
- node= ((SimpleType) elementType).getName();
- } else {
- return;
- }
- } else if (selectedNode instanceof Name) {
- node= (Name) selectedNode;
- } else {
- return;
- }
-
- // change to similar type proposals
- addSimilarTypeProposals(kind, cu, node, 3, proposals);
-
- while (node.getParent() instanceof QualifiedName) {
- node= (Name) node.getParent();
- }
-
- if (selectedNode != node) {
- kind= evauateTypeKind(node, cu.getJavaScriptProject());
- }
- if ((kind & (SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES)) != 0) {
- kind &= ~SimilarElementsRequestor.ANNOTATIONS; // only propose annotations when there are no other suggestions
- }
- addNewTypeProposals(cu, node, kind, 0, proposals);
- }
-
- private static void addSimilarTypeProposals(int kind, IJavaScriptUnit cu, Name node, int relevance, Collection proposals) throws CoreException {
- SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
-
- // try to resolve type in context -> highest severity
- String resolvedTypeName= null;
- ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
- if (binding != null) {
- ITypeBinding simpleBinding= binding;
- if (simpleBinding.isArray()) {
- simpleBinding= simpleBinding.getElementType();
- }
- simpleBinding= simpleBinding.getTypeDeclaration();
-
- resolvedTypeName= simpleBinding.getQualifiedName();
- CUCorrectionProposal proposal= createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2, elements.length);
- proposals.add(proposal);
- if (proposal instanceof AddImportCorrectionProposal)
- proposal.setRelevance(relevance + elements.length + 2);
- } else {
- ASTNode normalizedNode= ASTNodes.getNormalizedNode(node);
- if (!(normalizedNode.getParent() instanceof Type) && node.getParent() != normalizedNode) {
- ITypeBinding normBinding= ASTResolving.guessBindingForTypeReference(normalizedNode);
- if (normBinding != null) {
- proposals.add(createTypeRefChangeFullProposal(cu, normBinding, normalizedNode, relevance + 2));
- }
- }
- }
-
- // add all similar elements
- for (int i= 0; i < elements.length; i++) {
- SimilarElement elem= elements[i];
- if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
- String fullName= elem.getName();
- if (!fullName.equals(resolvedTypeName)) {
- proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance, elements.length));
- }
- }
- }
- }
-
- private static CUCorrectionProposal createTypeRefChangeProposal(IJavaScriptUnit cu, String fullName, Name node, int relevance, int maxProposals) throws CoreException {
- ImportRewrite importRewrite= null;
- String simpleName= fullName;
- String packName= Signature.getQualifier(fullName);
- if (packName.length() > 0) { // no imports for primitive types, type variables
- importRewrite= StubUtility.createImportRewrite((JavaScriptUnit) node.getRoot(), true);
- simpleName= importRewrite.addImport(fullName);
- }
-
- if (!isLikelyTypeName(simpleName)) {
- relevance -= 2;
- }
-
- ASTRewriteCorrectionProposal proposal;
- if (importRewrite != null && node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
- // import only
- String[] arg= { simpleName, packName };
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, arg);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
- int boost= QualifiedTypeNameHistory.getBoost(fullName, 0, maxProposals);
- proposal= new AddImportCorrectionProposal(label, cu, relevance + 100 + boost, image, packName, simpleName, (SimpleName)node);
- proposal.setCommandId(ADD_IMPORT_ID);
- } else {
- String label;
- if (packName.length() == 0) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_nopack_description, simpleName);
- } else {
- String[] arg= { simpleName, packName };
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_description, arg);
- }
- ASTRewrite rewrite= ASTRewrite.create(node.getAST());
- rewrite.replace(node, rewrite.createStringPlaceholder(simpleName, ASTNode.SIMPLE_TYPE), null);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image);
- }
- if (importRewrite != null) {
- proposal.setImportRewrite(importRewrite);
- }
- return proposal;
- }
-
- private static CUCorrectionProposal createTypeRefChangeFullProposal(IJavaScriptUnit cu, ITypeBinding binding, ASTNode node, int relevance) throws CoreException {
- ASTRewrite rewrite= ASTRewrite.create(node.getAST());
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_full_type_description, BindingLabelProvider.getBindingLabel(binding, JavaScriptElementLabels.ALL_DEFAULT));
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
-
-
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance + 3, image);
-
- ImportRewrite imports= proposal.createImportRewrite((JavaScriptUnit) node.getRoot());
- Type type= imports.addImport(binding, node.getAST());
-
- rewrite.replace(node, type, null);
- return proposal;
- }
-
- private static boolean isLikelyTypeName(String name) {
- return name.length() > 0 && Character.isUpperCase(name.charAt(0));
- }
-
- private static boolean isLikelyPackageName(String name) {
- if (name.length() != 0) {
- int i= 0;
- do {
- if (Character.isUpperCase(name.charAt(i))) {
- return false;
- }
- i= name.indexOf('.', i) + 1;
- } while (i != 0 && i < name.length());
- }
- return true;
- }
-
- private static boolean isLikelyTypeParameterName(String name) {
- return name.length() == 1 && Character.isUpperCase(name.charAt(0));
- }
-
- public static void addNewTypeProposals(IJavaScriptUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaScriptModelException {
- Name node= refNode;
- do {
- String typeName= ASTNodes.getSimpleNameIdentifier(node);
- Name qualifier= null;
- // only propose to create types for qualifiers when the name starts with upper case
- boolean isPossibleName= isLikelyTypeName(typeName) || (node == refNode);
- if (isPossibleName) {
- IPackageFragment enclosingPackage= null;
- IType enclosingType= null;
- if (node.isSimpleName()) {
- enclosingPackage= (IPackageFragment) cu.getParent();
- // don't suggest member type, user can select it in wizard
- } else {
- Name qualifierName= ((QualifiedName) node).getQualifier();
- IBinding binding= qualifierName.resolveBinding();
- if (binding != null && binding.isRecovered()) {
- binding= null;
- }
- if (binding instanceof ITypeBinding) {
- enclosingType=(IType) binding.getJavaElement();
- } else if (binding instanceof IPackageBinding) {
- qualifier= qualifierName;
- enclosingPackage= (IPackageFragment) binding.getJavaElement();
- } else {
- IJavaScriptElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
- if (res!= null && res.length > 0 && res[0] instanceof IType) {
- enclosingType= (IType) res[0];
- } else {
- qualifier= qualifierName;
- enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
- }
- }
- }
- int rel= relevance;
- if (enclosingPackage != null && isLikelyPackageName(enclosingPackage.getElementName())) {
- rel += 3;
- }
-
- if ((enclosingPackage != null && !enclosingPackage.getJavaScriptUnit(typeName + JavaModelUtil.DEFAULT_CU_SUFFIX).exists()) // new top level type
- || (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists())) { // new member type
- IJavaScriptElement enclosing= enclosingPackage != null ? (IJavaScriptElement) enclosingPackage : enclosingType;
-
- if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
- proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, NewCUCompletionUsingWizardProposal.K_CLASS, enclosing, rel+3));
- }
-// if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
-// proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, NewCUCompletionUsingWizardProposal.K_INTERFACE, enclosing, rel+2));
-// }
-// if ((kind & SimilarElementsRequestor.ENUMS) != 0) {
-// proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, NewCUCompletionUsingWizardProposal.K_ENUM, enclosing, rel));
-// }
-// if ((kind & SimilarElementsRequestor.ANNOTATIONS) != 0) {
-// proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, NewCUCompletionUsingWizardProposal.K_ANNOTATION, enclosing, rel + 1));
-// }
- }
- }
- node= qualifier;
- } while (node != null);
-
- // type parameter proposals
- if (refNode.isSimpleName() && ((kind & SimilarElementsRequestor.VARIABLES) != 0)) {
- JavaScriptUnit root= (JavaScriptUnit) refNode.getRoot();
- String name= ((SimpleName) refNode).getIdentifier();
- BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(refNode);
- int baseRel= relevance;
- if (isLikelyTypeParameterName(name)) {
- baseRel += 4;
- }
- while (declaration != null) {
- IBinding binding= null;
- int rel= baseRel;
- if (declaration instanceof FunctionDeclaration) {
- binding= ((FunctionDeclaration) declaration).resolveBinding();
- } else if (declaration instanceof TypeDeclaration) {
- binding= ((TypeDeclaration) declaration).resolveBinding();
- rel++;
- }
- if (!Modifier.isStatic(declaration.getModifiers())) {
- declaration= ASTResolving.findParentBodyDeclaration(declaration.getParent());
- } else {
- declaration= null;
- }
- }
- }
- }
-
- public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean isOnlyParameterMismatch, Collection proposals) throws CoreException {
-
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
-
- if (!(selectedNode instanceof SimpleName)) {
- return;
- }
- SimpleName nameNode= (SimpleName) selectedNode;
-
- List arguments;
- Expression sender;
- boolean isSuperInvocation;
-
- ASTNode invocationNode= nameNode.getParent();
- if (invocationNode instanceof FunctionInvocation) {
- FunctionInvocation methodImpl= (FunctionInvocation) invocationNode;
- arguments= methodImpl.arguments();
- sender= methodImpl.getExpression();
- isSuperInvocation= false;
- } else if (invocationNode instanceof SuperMethodInvocation) {
- SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode;
- arguments= methodImpl.arguments();
- sender= methodImpl.getQualifier();
- isSuperInvocation= true;
- } else {
- return;
- }
-
- String methodName= nameNode.getIdentifier();
- int nArguments= arguments.size();
-
- // corrections
- IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
-
- HashSet suggestedRenames= new HashSet();
- for (int i= 0; i < bindings.length; i++) {
- IFunctionBinding binding= (IFunctionBinding) bindings[i];
- String curr= binding.getName();
- if (!curr.equals(methodName) && binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr) && suggestedRenames.add(curr)) {
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changemethod_description, curr);
- proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
- }
- }
- suggestedRenames= null;
-
- if (isOnlyParameterMismatch) {
- ArrayList parameterMismatchs= new ArrayList();
- for (int i= 0; i < bindings.length; i++) {
- IFunctionBinding binding= (IFunctionBinding) bindings[i];
- if (binding.getName().equals(methodName)) {
- parameterMismatchs.add(binding);
- }
- }
- addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
- }
-
- // new method
- addNewMethodProposals(cu, astRoot, sender, arguments, isSuperInvocation, invocationNode, methodName, proposals);
-
- if (!isSuperInvocation && sender == null && invocationNode.getParent() instanceof ThrowStatement) {
- String str= "new "; //$NON-NLS-1$ // do it the manual way, copting all the arguments is nasty
- String label= CorrectionMessages.UnresolvedElementsSubProcessor_addnewkeyword_description;
- int relevance= Character.isUpperCase(methodName.charAt(0)) ? 7 : 4;
- ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, cu, invocationNode.getStartPosition(), 0, str, relevance);
- proposals.add(proposal);
- }
-
- }
-
- private static void addNewMethodProposals(IJavaScriptUnit cu, JavaScriptUnit astRoot, Expression sender, List arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName, Collection proposals) throws JavaScriptModelException {
- ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
- ITypeBinding binding= null;
- if (sender != null) {
- binding= sender.resolveTypeBinding();
- } else {
- binding= nodeParentType;
- if (isSuperInvocation && binding != null) {
- binding= binding.getSuperclass();
- }
- }
- if (binding != null && binding.isFromSource()) {
- ITypeBinding senderDeclBinding= binding.getTypeDeclaration();
-
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
- if (targetCU != null) {
- String label;
- Image image;
- ITypeBinding[] parameterTypes= getParameterTypes(arguments);
- if (parameterTypes != null) {
- String sig= ASTResolving.getMethodSignature(methodName, parameterTypes, false);
-
- if (ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
- if (nodeParentType == senderDeclBinding) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
- image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, senderDeclBinding.getName() } );
- image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
- }
- proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, 5, image));
- }
- if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
- ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
- if (anonymDecl != null) {
- senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
- if (!senderDeclBinding.isAnonymous() && ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
- String[] args= new String[] { sig, ASTResolving.getTypeSignature(senderDeclBinding) };
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
- image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
- proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, 5, image));
- }
- }
- }
- }
- }
- }
- }
-
- private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException {
- int nSimilarElements= similarElements.size();
- ITypeBinding[] argTypes= getArgumentTypes(arguments);
- if (argTypes == null || nSimilarElements == 0) {
- return;
- }
-
- for (int i= 0; i < nSimilarElements; i++) {
- IFunctionBinding elem = (IFunctionBinding) similarElements.get(i);
- int diff= elem.getParameterTypes().length - argTypes.length;
- if (diff == 0) {
- int nProposals= proposals.size();
- doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
- if (nProposals != proposals.size()) {
- return; // only suggest for one method (avoid duplicated proposals)
- }
- } else if (diff > 0) {
- doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals);
- } else {
- doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals);
- }
- }
- }
-
- private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IFunctionBinding methodBinding, Collection proposals) throws CoreException {
- ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
- int k= 0, nSkipped= 0;
- int diff= paramTypes.length - argTypes.length;
- int[] indexSkipped= new int[diff];
- for (int i= 0; i < paramTypes.length; i++) {
- if (k < argTypes.length && canAssign(argTypes[k], paramTypes[i])) {
- k++; // match
- } else {
- if (nSkipped >= diff) {
- return; // too different
- }
- indexSkipped[nSkipped++]= i;
- }
- }
- ITypeBinding declaringType= methodBinding.getDeclaringClass();
- IJavaScriptUnit cu= context.getCompilationUnit();
- JavaScriptUnit astRoot= context.getASTRoot();
-
- // add arguments
- {
- String[] arg= new String[] { ASTResolving.getMethodSignature(methodBinding, false) };
- String label;
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addargument_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addarguments_description, arg);
- }
- AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8);
- proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
- proposals.add(proposal);
- }
-
- // remove parameters
- if (!declaringType.isFromSource()) {
- return;
- }
-
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
- if (targetCU != null) {
- IFunctionBinding methodDecl= methodBinding.getMethodDeclaration();
- ITypeBinding[] declParameterTypes= methodDecl.getParameterTypes();
-
- ChangeDescription[] changeDesc= new ChangeDescription[declParameterTypes.length];
- ITypeBinding[] changedTypes= new ITypeBinding[diff];
- for (int i= diff - 1; i >= 0; i--) {
- int idx= indexSkipped[i];
- changeDesc[idx]= new RemoveDescription();
- changedTypes[i]= declParameterTypes[idx];
- }
- String[] arg= new String[] { ASTResolving.getMethodSignature(methodDecl, !cu.equals(targetCU)), getTypeNames(changedTypes) };
- String label;
- if (methodDecl.isConstructor()) {
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removeparam_constr_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removeparams_constr_description, arg);
- }
- } else {
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removeparam_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removeparams_description, arg);
- }
- }
-
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
- ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, 5, image);
- proposals.add(proposal);
- }
- }
-
- private static String getTypeNames(ITypeBinding[] types) {
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < types.length; i++) {
- if (i > 0) {
- buf.append(", "); //$NON-NLS-1$
- }
- buf.append(ASTResolving.getTypeSignature(types[i]));
- }
- return buf.toString();
- }
-
- private static String getArgumentName(IJavaScriptUnit cu, List arguments, int index) {
- String def= String.valueOf(index + 1);
-
- ASTNode expr= (ASTNode) arguments.get(index);
- if (expr.getLength() > 18) {
- return def;
- }
- ASTMatcher matcher= new ASTMatcher();
- for (int i= 0; i < arguments.size(); i++) {
- if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) {
- return def;
- }
- }
- return '\'' + ASTNodes.asString(expr) + '\'';
- }
-
- private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IFunctionBinding methodRef, Collection proposals) throws CoreException {
- ITypeBinding[] paramTypes= methodRef.getParameterTypes();
- int k= 0, nSkipped= 0;
- int diff= argTypes.length - paramTypes.length;
- int[] indexSkipped= new int[diff];
- for (int i= 0; i < argTypes.length; i++) {
- if (k < paramTypes.length && canAssign(argTypes[i], paramTypes[k])) {
- k++; // match
- } else {
- if (nSkipped >= diff) {
- return; // too different
- }
- indexSkipped[nSkipped++]= i;
- }
- }
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- JavaScriptUnit astRoot= context.getASTRoot();
-
- // remove arguments
- {
- ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
-
- for (int i= diff - 1; i >= 0; i--) {
- rewrite.remove((Expression) arguments.get(indexSkipped[i]), null);
- }
- String[] arg= new String[] { ASTResolving.getMethodSignature(methodRef, false) };
- String label;
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removeargument_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_removearguments_description, arg);
- }
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
- proposals.add(proposal);
- }
-
- IFunctionBinding methodDecl= methodRef.getMethodDeclaration();
- ITypeBinding declaringType= methodDecl.getDeclaringClass();
-
- // add parameters
- if (!declaringType.isFromSource()) {
- return;
- }
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
- if (targetCU != null) {
- boolean isDifferentCU= !cu.equals(targetCU);
-
- if (isImplicitConstructor(methodDecl, targetCU)) {
- return;
- }
-
- ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length];
- ITypeBinding[] changeTypes= new ITypeBinding[diff];
- for (int i= diff - 1; i >= 0; i--) {
- int idx= indexSkipped[i];
- Expression arg= (Expression) arguments.get(idx);
- String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
- ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]);
- if (newType == null) {
- newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
- if (!ASTResolving.isUseableTypeInContext(newType, methodDecl, false)) {
- return;
- }
- changeDesc[idx]= new InsertDescription(newType, name);
- changeTypes[i]= newType;
- }
- String[] arg= new String[] { ASTResolving.getMethodSignature(methodDecl, isDifferentCU), getTypeNames(changeTypes) };
- String label;
- if (methodDecl.isConstructor()) {
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addparam_constr_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addparams_constr_description, arg);
- }
- } else {
- if (diff == 1) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addparam_description, arg);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addparams_description, arg);
- }
- }
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
- ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, 5, image);
- proposals.add(proposal);
- }
- }
-
- private static boolean isImplicitConstructor(IFunctionBinding meth, IJavaScriptUnit targetCU) {
- return meth.isDefaultConstructor();
- }
-
-
-
- private static ITypeBinding[] getParameterTypes(List args) {
- ITypeBinding[] params= new ITypeBinding[args.size()];
- for (int i= 0; i < args.size(); i++) {
- Expression expr= (Expression) args.get(i);
- ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
-
- if (curr == null) {
- curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
- params[i]= curr;
- }
- return params;
- }
-
-
-
- private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IFunctionBinding methodBinding, Collection proposals) throws CoreException {
- ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
- int[] indexOfDiff= new int[paramTypes.length];
- int nDiffs= 0;
- for (int n= 0; n < argTypes.length; n++) {
- if (!canAssign(argTypes[n], paramTypes[n])) {
- indexOfDiff[nDiffs++]= n;
- }
- }
- ITypeBinding declaringTypeDecl= methodBinding.getDeclaringClass().getTypeDeclaration();
-
- IJavaScriptUnit cu= context.getCompilationUnit();
- JavaScriptUnit astRoot= context.getASTRoot();
-
- ASTNode nameNode= problem.getCoveringNode(astRoot);
- if (nameNode == null) {
- return;
- }
-
- if (nDiffs == 0) {
- if (nameNode.getParent() instanceof FunctionInvocation) {
- FunctionInvocation inv= (FunctionInvocation) nameNode.getParent();
- if (inv.getExpression() == null) {
- addQualifierToOuterProposal(context, inv, methodBinding, proposals);
- }
- }
- return;
- }
-
- if (nDiffs == 1) { // one argument mismatching: try to fix
- int idx= indexOfDiff[0];
- Expression nodeToCast= (Expression) arguments.get(idx);
- ITypeBinding castType= paramTypes[idx];
- castType= Bindings.normalizeTypeBinding(castType);
-
- if (castType != null) {
- TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, 5, proposals);
- }
- }
- if (nDiffs == 2) { // try to swap
- int idx1= indexOfDiff[0];
- int idx2= indexOfDiff[1];
- boolean canSwap= canAssign(argTypes[idx1], paramTypes[idx2]) && canAssign(argTypes[idx2], paramTypes[idx1]);
- if (canSwap) {
- Expression arg1= (Expression) arguments.get(idx1);
- Expression arg2= (Expression) arguments.get(idx2);
-
- ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
- rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null);
- rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null);
- {
- String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) };
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swaparguments_description, arg);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
- proposals.add(proposal);
- }
-
- if (declaringTypeDecl.isFromSource()) {
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringTypeDecl);
- if (targetCU != null) {
- ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
- for (int i= 0; i < nDiffs; i++) {
- changeDesc[idx1]= new SwapDescription(idx2);
- }
- IFunctionBinding methodDecl= methodBinding.getMethodDeclaration();
- ITypeBinding[] declParamTypes= methodDecl.getParameterTypes();
-
- ITypeBinding[] swappedTypes= new ITypeBinding[] { declParamTypes[idx1], declParamTypes[idx2] };
- String[] args= new String[] { ASTResolving.getMethodSignature(methodDecl, !targetCU.equals(cu)), getTypeNames(swappedTypes) };
- String label;
- if (methodDecl.isConstructor()) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_constr_description, args);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_description, args);
- }
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, 5, image);
- proposals.add(proposal);
- }
- }
- return;
- }
- }
-
- if (declaringTypeDecl.isFromSource()) {
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringTypeDecl);
- if (targetCU != null) {
- ChangeDescription[] changeDesc= createSignatureChangeDescription(indexOfDiff, nDiffs, paramTypes, arguments, argTypes);
- if (changeDesc != null) {
-
- IFunctionBinding methodDecl= methodBinding.getMethodDeclaration();
- ITypeBinding[] declParamTypes= methodDecl.getParameterTypes();
-
- ITypeBinding[] newParamTypes= new ITypeBinding[changeDesc.length];
- for (int i= 0; i < newParamTypes.length; i++) {
- newParamTypes[i]= changeDesc[i] == null ? declParamTypes[i] : ((EditDescription) changeDesc[i]).type;
- }
- boolean isVarArgs= methodDecl.isVarargs() && newParamTypes.length > 0 && newParamTypes[newParamTypes.length - 1].isArray();
- String[] args= new String[] { ASTResolving.getMethodSignature(methodDecl, !targetCU.equals(cu)), ASTResolving.getMethodSignature(methodDecl.getName(), newParamTypes, isVarArgs) };
- String label;
- if (methodDecl.isConstructor()) {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_constr_description, args);
- } else {
- label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_description, args);
- }
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, 7, image);
- proposals.add(proposal);
- }
- }
- }
- }
-
- private static ChangeDescription[] createSignatureChangeDescription(int[] indexOfDiff, int nDiffs, ITypeBinding[] paramTypes, List arguments, ITypeBinding[] argTypes) {
- ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
- for (int i= 0; i < nDiffs; i++) {
- int diffIndex= indexOfDiff[i];
- Expression arg= (Expression) arguments.get(diffIndex);
- String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
- ITypeBinding argType= argTypes[diffIndex];
-
- changeDesc[diffIndex]= new EditDescription(argType, name);
- }
- return changeDesc;
- }
-
- private static ITypeBinding[] getArgumentTypes(List arguments) {
- ITypeBinding[] res= new ITypeBinding[arguments.size()];
- for (int i= 0; i < res.length; i++) {
- Expression expression= (Expression) arguments.get(i);
- ITypeBinding curr= expression.resolveTypeBinding();
- if (curr == null) {
- return null;
- }
- if (!curr.isNullType()) { // don't normalize null type
- curr= Bindings.normalizeTypeBinding(curr);
- if (curr == null) {
- curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- }
- }
- res[i]= curr;
- }
- return res;
- }
-
- private static void addQualifierToOuterProposal(IInvocationContext context, FunctionInvocation invocationNode, IFunctionBinding binding, Collection proposals) throws CoreException {
- ITypeBinding declaringType= binding.getDeclaringClass();
- ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
- ITypeBinding currType= parentType;
-
- boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());
-
- while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
- if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
- return;
- }
- currType= currType.getDeclaringClass();
- }
- if (currType == null || currType == parentType) {
- return;
- }
-
- ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST());
-
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, ASTResolving.getTypeSignature(currType));
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
-
- ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
- AST ast= invocationNode.getAST();
-
- String qualifier= imports.addImport(currType);
- Name name= ASTNodeFactory.newName(ast, qualifier);
-
- Expression newExpression;
- if (isInstanceMethod) {
- ThisExpression expr= ast.newThisExpression();
- expr.setQualifier(name);
- newExpression= expr;
- } else {
- newExpression= name;
- }
-
- rewrite.set(invocationNode, FunctionInvocation.EXPRESSION_PROPERTY, newExpression, null);
-
- proposals.add(proposal);
- }
-
-
- public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- IJavaScriptUnit cu= context.getCompilationUnit();
-
- JavaScriptUnit astRoot= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(astRoot);
- if (selectedNode == null) {
- return;
- }
-
- ITypeBinding targetBinding= null;
- List arguments= null;
- IFunctionBinding recursiveConstructor= null;
-
- int type= selectedNode.getNodeType();
- if (type == ASTNode.CLASS_INSTANCE_CREATION) {
- ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
-
- IBinding binding= creation.getType().resolveBinding();
- if (binding instanceof ITypeBinding) {
- targetBinding= (ITypeBinding) binding;
- arguments= creation.arguments();
- }
- } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
- ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
- if (typeBinding != null && !typeBinding.isAnonymous()) {
- targetBinding= typeBinding.getSuperclass();
- arguments= ((SuperConstructorInvocation) selectedNode).arguments();
- }
- } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
- ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
- if (typeBinding != null && !typeBinding.isAnonymous()) {
- targetBinding= typeBinding;
- arguments= ((ConstructorInvocation) selectedNode).arguments();
- recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding();
- }
- }
- if (targetBinding == null) {
- return;
- }
- IFunctionBinding[] methods= targetBinding.getDeclaredMethods();
- ArrayList similarElements= new ArrayList();
- for (int i= 0; i < methods.length; i++) {
- IFunctionBinding curr= methods[i];
- if (curr.isConstructor() && recursiveConstructor != curr) {
- similarElements.add(curr); // similar elements can contain a implicit default constructor
- }
- }
-
- addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals);
-
- if (targetBinding.isFromSource()) {
- ITypeBinding targetDecl= targetBinding.getTypeDeclaration();
-
- IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetDecl);
- if (targetCU != null) {
- String[] args= new String[] { ASTResolving.getMethodSignature( ASTResolving.getTypeSignature(targetDecl), getParameterTypes(arguments), false) };
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconstructor_description, args);
- Image image= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaScriptElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
- proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetDecl, 5, image));
- }
- }
- }
-
- public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
- final IJavaScriptUnit cu= context.getCompilationUnit();
- int offset= problem.getOffset();
- int len= problem.getLength();
-
- IJavaScriptElement[] elements= cu.codeSelect(offset, len);
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement curr= elements[i];
- if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
- String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
-
- JavaScriptUnit root= context.getASTRoot();
-
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, qualifiedTypeName);
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
- ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, ASTRewrite.create(root.getAST()), 5, image);
-
- ImportRewrite imports= proposal.createImportRewrite(root);
- imports.addImport(qualifiedTypeName);
-
- proposals.add(proposal);
- }
- }
- }
-
- public static void getArrayAccessProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
-
- JavaScriptUnit root= context.getASTRoot();
- ASTNode selectedNode= problem.getCoveringNode(root);
- if (!(selectedNode instanceof FunctionInvocation)) {
- return;
- }
-
- FunctionInvocation decl= (FunctionInvocation) selectedNode;
- SimpleName nameNode= decl.getName();
- String methodName= nameNode.getIdentifier();
-
- IBinding[] bindings= (new ScopeAnalyzer(root)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
- for (int i= 0; i < bindings.length; i++) {
- String currName= bindings[i].getName();
- if (NameMatcher.isSimilarName(methodName, currName)) {
- String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetomethod_description, currName);
- proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), nameNode.getStartPosition(), nameNode.getLength(), currName, 6));
- }
- }
- // always suggest 'length'
- String lengthId= "length"; //$NON-NLS-1$
- String label= CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetolength_description;
- int offset= nameNode.getStartPosition();
- int length= decl.getStartPosition() + decl.getLength() - offset;
- proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), offset, length, lengthId, 7));
- }
-
-// public static void getAnnotationMemberProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
-// JavaScriptUnit astRoot= context.getASTRoot();
-// IJavaScriptUnit cu= context.getCompilationUnit();
-// ASTNode selectedNode= problem.getCoveringNode(astRoot);
-//
-// Annotation annotation;
-// String memberName;
-// if (selectedNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
-// if (selectedNode.getParent().getLocationInParent() != NormalAnnotation.VALUES_PROPERTY) {
-// return;
-// }
-// annotation= (Annotation) selectedNode.getParent().getParent();
-// memberName= ((SimpleName) selectedNode).getIdentifier();
-// } else if (selectedNode.getLocationInParent() == SingleMemberAnnotation.VALUE_PROPERTY) {
-// annotation= (Annotation) selectedNode.getParent();
-// memberName= "value"; //$NON-NLS-1$
-// } else {
-// return;
-// }
-//
-// ITypeBinding annotBinding= annotation.resolveTypeBinding();
-// if (annotBinding == null) {
-// return;
-// }
-//
-//
-// if (annotation instanceof NormalAnnotation) {
-// // similar names
-// IFunctionBinding[] otherMembers= annotBinding.getDeclaredMethods();
-// for (int i= 0; i < otherMembers.length; i++) {
-// IFunctionBinding binding= otherMembers[i];
-// String curr= binding.getName();
-// int relevance= NameMatcher.isSimilarName(memberName, curr) ? 6 : 3;
-// String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description, curr);
-// proposals.add(new RenameNodeCompletionProposal(label, cu, problem.getOffset(), problem.getLength(), curr, relevance));
-// }
-// }
-//
-// if (annotBinding.isFromSource()) {
-// IJavaScriptUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, annotBinding);
-// if (targetCU != null) {
-// String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description, memberName);
-// Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
-// proposals.add(new NewAnnotationMemberProposal(label, targetCU, selectedNode, annotBinding, 5, image));
-// }
-// }
-// }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java
deleted file mode 100644
index db39e4dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.folding;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.OverlayPreferenceStore;
-import org.eclipse.wst.jsdt.internal.ui.preferences.OverlayPreferenceStore.OverlayKey;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingPreferenceBlock;
-
-
-/**
- * Java default folding preferences.
- *
- *
- */
-public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock {
-
- private IPreferenceStore fStore;
- private OverlayPreferenceStore fOverlayStore;
- private OverlayKey[] fKeys;
- private Map fCheckBoxes= new HashMap();
- private SelectionListener fCheckBoxListener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- public void widgetSelected(SelectionEvent e) {
- Button button= (Button) e.widget;
- fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
- }
- };
-
-
- public DefaultJavaFoldingPreferenceBlock() {
- fStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- fKeys= createKeys();
- fOverlayStore= new OverlayPreferenceStore(fStore, fKeys);
- }
-
- private OverlayKey[] createKeys() {
- ArrayList overlayKeys= new ArrayList();
-
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_JAVADOC));
-// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_INNERTYPES));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_METHODS));
-// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_IMPORTS));
- overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_HEADERS));
-
- return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys.size()]);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
- */
- public Control createControl(Composite composite) {
- fOverlayStore.load();
- fOverlayStore.start();
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout(1, true);
- layout.verticalSpacing= 3;
- layout.marginWidth= 0;
- inner.setLayout(layout);
-
- Label label= new Label(inner, SWT.LEFT);
- label.setText(FoldingMessages.DefaultJavaFoldingPreferenceBlock_title);
-
- addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_comments, PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0);
- addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_headers, PreferenceConstants.EDITOR_FOLDING_HEADERS, 0);
-// addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_innerTypes, PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0);
- addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_methods, PreferenceConstants.EDITOR_FOLDING_METHODS, 0);
-// addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_imports, PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0);
-
- return inner;
- }
-
- private Button addCheckBox(Composite parent, String label, String key, int indentation) {
- Button checkBox= new Button(parent, SWT.CHECK);
- checkBox.setText(label);
-
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- gd.horizontalIndent= indentation;
- gd.horizontalSpan= 1;
- gd.grabExcessVerticalSpace= false;
- checkBox.setLayoutData(gd);
- checkBox.addSelectionListener(fCheckBoxListener);
-
- fCheckBoxes.put(checkBox, key);
-
- return checkBox;
- }
-
- private void initializeFields() {
- Iterator it= fCheckBoxes.keySet().iterator();
- while (it.hasNext()) {
- Button b= (Button) it.next();
- String key= (String) fCheckBoxes.get(b);
- b.setSelection(fOverlayStore.getBoolean(key));
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performOk()
- */
- public void performOk() {
- fOverlayStore.propagate();
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#initialize()
- */
- public void initialize() {
- initializeFields();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performDefaults()
- */
- public void performDefaults() {
- fOverlayStore.loadDefaults();
- initializeFields();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#dispose()
- */
- public void dispose() {
- fOverlayStore.stop();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java
deleted file mode 100644
index c7a203f5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.folding;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingPreferenceBlock;
-
-
-/**
- * Empty preference block for extensions to the
- * <code>org.eclipse.wst.jsdt.ui.javaFoldingStructureProvider</code> extension
- * point that do not specify their own.
- *
- *
- */
-class EmptyJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
- */
- public Control createControl(Composite composite) {
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setLayout(new GridLayout(3, false));
-
- Label label= new Label(inner, SWT.CENTER);
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= 30;
- label.setLayoutData(gd);
-
- label= new Label(inner, SWT.CENTER);
- label.setText(FoldingMessages.EmptyJavaFoldingPreferenceBlock_emptyCaption);
- gd= new GridData(GridData.CENTER);
- label.setLayoutData(gd);
-
- label= new Label(inner, SWT.CENTER);
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= 30;
- label.setLayoutData(gd);
-
- return inner;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#initialize()
- */
- public void initialize() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#performOk()
- */
- public void performOk() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#performDefaults()
- */
- public void performDefaults() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#dispose()
- */
- public void dispose() {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.java
deleted file mode 100644
index 727533a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.folding;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class FoldingMessages extends NLS {
-
- private static final String BUNDLE_NAME= FoldingMessages.class.getName();
-
- private FoldingMessages() {
- // Do not instantiate
- }
-
- public static String DefaultJavaFoldingPreferenceBlock_title;
- public static String DefaultJavaFoldingPreferenceBlock_comments;
-// public static String DefaultJavaFoldingPreferenceBlock_innerTypes;
- public static String DefaultJavaFoldingPreferenceBlock_methods;
-// public static String DefaultJavaFoldingPreferenceBlock_imports;
- public static String DefaultJavaFoldingPreferenceBlock_headers;
- public static String EmptyJavaFoldingPreferenceBlock_emptyCaption;
- public static String JavaFoldingStructureProviderRegistry_warning_providerNotFound_resetToDefault;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, FoldingMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties
deleted file mode 100644
index 76c28dc2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties
+++ /dev/null
@@ -1,22 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-DefaultJavaFoldingPreferenceBlock_title= Initially fold these elements:
-DefaultJavaFoldingPreferenceBlock_comments= &Comments
-#DefaultJavaFoldingPreferenceBlock_innerTypes= Inner &types
-DefaultJavaFoldingPreferenceBlock_methods= &Members
-#DefaultJavaFoldingPreferenceBlock_imports= &Imports
-DefaultJavaFoldingPreferenceBlock_headers= &Header Comments
-
-JavaFoldingStructureProviderRegistry_warning_providerNotFound_resetToDefault= The ''{0}'' folding provider could not be found. Resetting to the default folding provider.
-
-EmptyJavaFoldingPreferenceBlock_emptyCaption=
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java
deleted file mode 100644
index 444acc7a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.folding;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingPreferenceBlock;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProvider;
-
-/**
- * Describes a contribution to the folding provider extension point.
- *
- *
- */
-public final class JavaFoldingStructureProviderDescriptor {
-
- /* extension point attribute names */
-
- private static final String PREFERENCES_CLASS= "preferencesClass"; //$NON-NLS-1$
- private static final String CLASS= "class"; //$NON-NLS-1$
- private static final String NAME= "name"; //$NON-NLS-1$
- private static final String ID= "id"; //$NON-NLS-1$
-
- /** The identifier of the extension. */
- private String fId;
- /** The name of the extension. */
- private String fName;
- /** The class name of the provided <code>IJavaFoldingStructureProvider</code>. */
- private String fClass;
- /**
- * <code>true</code> if the extension specifies a custom
- * <code>IJavaFoldingPreferenceBlock</code>.
- */
- private boolean fHasPreferences;
- /** The configuration element of this extension. */
- private IConfigurationElement fElement;
-
- /**
- * Creates a new descriptor.
- *
- * @param element the configuration element to read
- */
- JavaFoldingStructureProviderDescriptor(IConfigurationElement element) {
- fElement= element;
- fId= element.getAttribute(ID);
- Assert.isLegal(fId != null);
-
- fName= element.getAttribute(NAME);
- if (fName == null)
- fName= fId;
-
- fClass= element.getAttribute(CLASS);
- Assert.isLegal(fClass != null);
-
- if (element.getAttribute(PREFERENCES_CLASS) == null)
- fHasPreferences= false;
- else
- fHasPreferences= true;
- }
-
- /**
- * Creates a folding provider as described in the extension's xml.
- *
- * @return a new instance of the folding provider described by this
- * descriptor
- * @throws CoreException if creation fails
- */
- public IJavaFoldingStructureProvider createProvider() throws CoreException {
- IJavaFoldingStructureProvider prov= (IJavaFoldingStructureProvider) fElement.createExecutableExtension(CLASS);
- return prov;
- }
-
- /**
- * Creates a preferences object as described in the extension's xml.
- *
- * @return a new instance of the reference provider described by this
- * descriptor
- * @throws CoreException if creation fails
- */
- public IJavaFoldingPreferenceBlock createPreferences() throws CoreException {
- if (fHasPreferences) {
- IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) fElement.createExecutableExtension(PREFERENCES_CLASS);
- return prefs;
- } else {
- return new EmptyJavaFoldingPreferenceBlock();
- }
- }
-
- /**
- * Returns the identifier of the described extension.
- *
- * @return Returns the id
- */
- public String getId() {
- return fId;
- }
-
- /**
- * Returns the name of the described extension.
- *
- * @return Returns the name
- */
- public String getName() {
- return fName;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java
deleted file mode 100644
index 1dc6b32b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.folding;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProvider;
-
-
-/**
- *
- */
-public class JavaFoldingStructureProviderRegistry {
-
- private static final String EXTENSION_POINT= "foldingStructureProviders"; //$NON-NLS-1$
-
- /** The map of descriptors, indexed by their identifiers. */
- private Map fDescriptors;
-
- /**
- * Creates a new instance.
- */
- public JavaFoldingStructureProviderRegistry() {
- }
-
- /**
- * Returns an array of <code>JavaFoldingStructureProviderDescriptor</code> describing
- * all extension to the <code>foldingProviders</code> extension point.
- *
- * @return the list of extensions to the
- * <code>quickDiffReferenceProvider</code> extension point
- */
- public JavaFoldingStructureProviderDescriptor[] getFoldingProviderDescriptors() {
- synchronized (this) {
- ensureRegistered();
- return (JavaFoldingStructureProviderDescriptor[]) fDescriptors.values().toArray(new JavaFoldingStructureProviderDescriptor[fDescriptors.size()]);
- }
- }
-
- /**
- * Returns the folding provider descriptor with identifier <code>id</code> or
- * <code>null</code> if no such provider is registered.
- *
- * @param id the identifier for which a provider is wanted
- * @return the corresponding provider descriptor, or <code>null</code> if none can be
- * found
- */
- public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor(String id) {
- synchronized (this) {
- ensureRegistered();
- return (JavaFoldingStructureProviderDescriptor) fDescriptors.get(id);
- }
- }
-
- /**
- * Instantiates and returns the provider that is currently configured in the
- * preferences.
- *
- * @return the current provider according to the preferences
- */
- public IJavaFoldingStructureProvider getCurrentFoldingProvider() {
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- String currentProviderId= preferenceStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
- JavaFoldingStructureProviderDescriptor desc= getFoldingProviderDescriptor(currentProviderId);
-
- // Fallback to default if extension has gone
- if (desc == null) {
- String message= Messages.format(FoldingMessages.JavaFoldingStructureProviderRegistry_warning_providerNotFound_resetToDefault, currentProviderId);
- JavaScriptPlugin.log(new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null));
-
- String defaultProviderId= preferenceStore.getDefaultString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
-
- desc= getFoldingProviderDescriptor(defaultProviderId);
- Assert.isNotNull(desc);
-
- preferenceStore.setToDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
- }
-
- try {
- return desc.createProvider();
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- return null;
- }
- }
-
- /**
- * Ensures that the extensions are read and stored in
- * <code>fDescriptors</code>.
- */
- private void ensureRegistered() {
- if (fDescriptors == null)
- reloadExtensions();
- }
-
- /**
- * Reads all extensions.
- * <p>
- * This method can be called more than once in
- * order to reload from a changed extension registry.
- * </p>
- */
- public void reloadExtensions() {
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- Map map= new HashMap();
-
- IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaScriptPlugin.getPluginId(), EXTENSION_POINT);
- for (int i= 0; i < elements.length; i++) {
- JavaFoldingStructureProviderDescriptor desc= new JavaFoldingStructureProviderDescriptor(elements[i]);
- map.put(desc.getId(), desc);
- }
-
- synchronized(this) {
- fDescriptors= Collections.unmodifiableMap(map);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java
deleted file mode 100644
index a25f1859..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java
+++ /dev/null
@@ -1,591 +0,0 @@
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Iterator;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.browser.Browser;
-import org.eclipse.swt.browser.LocationAdapter;
-import org.eclipse.swt.browser.LocationEvent;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.graphics.TextLayout;
-import org.eclipse.swt.graphics.TextStyle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-
-import org.eclipse.core.runtime.ListenerList;
-
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlExtension;
-import org.eclipse.jface.text.IInformationControlExtension3;
-import org.eclipse.jface.text.IInformationControlExtension4;
-import org.eclipse.jface.text.TextPresentation;
-
-
-/**
- * Displays textual information in a {@link org.eclipse.swt.browser.Browser} widget.
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.</p>
- * <p>
- * Current problems:
- * <ul>
- * <li>the size computation is too small</li>
- * <li>focusLost event is not sent - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532</li>
- * </ul>
- * </p>
- *
- *
- */
-public class BrowserInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension3, IInformationControlExtension4, DisposeListener {
-
-
- /**
- * Tells whether the SWT Browser widget and hence this information
- * control is available.
- *
- * @param parent the parent component used for checking or <code>null</code> if none
- * @return <code>true</code> if this control is available
- */
- public static boolean isAvailable(Composite parent) {
- if (!fgAvailabilityChecked) {
- try {
- Browser browser= new Browser(parent, SWT.NONE);
- browser.dispose();
- fgIsAvailable= true;
- } catch (SWTError er) {
- fgIsAvailable= false;
- } finally {
- fgAvailabilityChecked= true;
- }
- }
-
- return fgIsAvailable;
- }
-
-
- /** Border thickness in pixels. */
- private static final int BORDER= 1;
-
- /**
- * Minimal size constraints.
- *
- */
- private static final int MIN_WIDTH= 80;
- private static final int MIN_HEIGHT= 80;
-
-
- /**
- * Availability checking cache.
- */
- private static boolean fgIsAvailable= false;
- private static boolean fgAvailabilityChecked= false;
-
- /** The control's shell */
- private Shell fShell;
- /** The control's browser widget */
- private Browser fBrowser;
- /** Tells whether the browser has content */
- private boolean fBrowserHasContent;
- /** The control width constraint */
- private int fMaxWidth= SWT.DEFAULT;
- /** The control height constraint */
- private int fMaxHeight= SWT.DEFAULT;
- private Font fStatusTextFont;
- private Label fStatusTextField;
- private String fStatusFieldText;
- private boolean fHideScrollBars;
- private Listener fDeactivateListener;
- private ListenerList fFocusListeners= new ListenerList();
- private Label fSeparator;
- private String fInputText;
- private TextLayout fTextLayout;
-
- private TextStyle fBoldStyle;
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param style the additional styles for the styled text widget
- */
- public BrowserInformationControl(Shell parent, int shellStyle, int style) {
- this(parent, shellStyle, style, null);
- }
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param style the additional styles for the styled text widget
- * @param statusFieldText the text to be used in the optional status field
- * or <code>null</code> if the status field should be hidden
- */
- public BrowserInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) {
- fStatusFieldText= statusFieldText;
-
- fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
- Display display= fShell.getDisplay();
- fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
- fTextLayout= new TextLayout(display);
-
- Composite composite= fShell;
- GridLayout layout= new GridLayout(1, false);
- int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
- layout.marginHeight= border;
- layout.marginWidth= border;
- composite.setLayout(layout);
-
- if (statusFieldText != null) {
- composite= new Composite(composite, SWT.NONE);
- layout= new GridLayout(1, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.verticalSpacing= 1;
- layout.horizontalSpacing= 1;
- composite.setLayout(layout);
-
- GridData gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
-
- composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- // Browser field
- fBrowser= new Browser(composite, SWT.NONE);
- fHideScrollBars= (style & SWT.V_SCROLL) == 0 && (style & SWT.H_SCROLL) == 0;
-
- GridData gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
- fBrowser.setLayoutData(gd);
-
- fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- fBrowser.addKeyListener(new KeyListener() {
-
- public void keyPressed(KeyEvent e) {
- if (e.character == 0x1B) // ESC
- fShell.dispose();
- }
-
- public void keyReleased(KeyEvent e) {}
- });
- /*
- * XXX revisit when the Browser support is better
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=107629. Choosing a link to a
- * non-available target will show an error dialog behind the ON_TOP shell that seemingly
- * blocks the workbench. Disable links completely for now.
- */
- fBrowser.addLocationListener(new LocationAdapter() {
- /*
- * @see org.eclipse.swt.browser.LocationAdapter#changing(org.eclipse.swt.browser.LocationEvent)
- */
- public void changing(LocationEvent event) {
- String location= event.location;
- /*
- * Using the Browser.setText API triggers a location change to "about:blank" with
- * the mozilla widget. The Browser on carbon uses yet another kind of special
- * initialization URLs.
- * TODO remove this code once https://bugs.eclipse.org/bugs/show_bug.cgi?id=130314 is fixed
- */
- if (!"about:blank".equals(location) && !("carbon".equals(SWT.getPlatform()) && location.startsWith("applewebdata:"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- event.doit= false;
- }
- });
-
- // Replace browser's built-in context menu with none
- fBrowser.setMenu(new Menu(fShell, SWT.NONE));
-
- // Status field
- if (statusFieldText != null) {
-
- fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
- fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // Status field label
- fStatusTextField= new Label(composite, SWT.RIGHT);
- fStatusTextField.setText(statusFieldText);
- Font font= fStatusTextField.getFont();
- FontData[] fontDatas= font.getFontData();
- for (int i= 0; i < fontDatas.length; i++)
- fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
- fStatusTextFont= new Font(fStatusTextField.getDisplay(), fontDatas);
- fStatusTextField.setFont(fStatusTextFont);
- gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
- fStatusTextField.setLayoutData(gd);
-
- fStatusTextField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
-
- fStatusTextField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- addDisposeListener(this);
- createTextLayout();
- }
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param style the additional styles for the browser widget
- */
- public BrowserInformationControl(Shell parent,int style) {
- this(parent, SWT.TOOL | SWT.NO_TRIM, style);
- }
-
- /**
- * Creates a default information control with the given shell as parent.
- * No information presenter is used to process the information
- * to be displayed. No additional styles are applied to the styled text widget.
- *
- * @param parent the parent shell
- */
- public BrowserInformationControl(Shell parent) {
- this(parent, SWT.NONE);
- }
-
-
- /*
- * @see IInformationControl#setInformation(String)
- */
- public void setInformation(String content) {
- fBrowserHasContent= content != null && content.length() > 0;
-
- if (!fBrowserHasContent)
- content= "<html><body ></html>"; //$NON-NLS-1$
-
- fInputText= content;
-
- int shellStyle= fShell.getStyle();
- boolean RTL= (shellStyle & SWT.RIGHT_TO_LEFT) != 0;
-
- String[] styles= null;
- if (RTL && !fHideScrollBars)
- styles= new String[] { "direction:rtl;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$
- else if (RTL && fHideScrollBars)
- styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- else if (fHideScrollBars && true)
- styles= new String[] { "overflow:hidden;", "word-wrap: break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$
-
- if (styles != null) {
- StringBuffer buffer= new StringBuffer(content);
- HTMLPrinter.insertStyles(buffer, styles);
- content= buffer.toString();
- }
-
- fBrowser.setText(content);
-
- }
-
- /*
- * @see org.eclipse.jdt.internal.ui.text.IInformationControlExtension4#setStatusText(java.lang.String)
- *
- */
- public void setStatusText(String statusFieldText) {
- fStatusFieldText= statusFieldText;
- }
-
- /*
- * @see IInformationControl#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- if (fShell.isVisible() == visible)
- return;
-
- if (visible) {
- if (fStatusTextField != null) {
- boolean state= fStatusFieldText != null;
- if (state)
- fStatusTextField.setText(fStatusFieldText);
- fStatusTextField.setVisible(state);
- fSeparator.setVisible(state);
- }
- }
-
- fShell.setVisible(visible);
- if (!visible)
- setInformation(""); //$NON-NLS-1$
- }
-
- /**
- * Creates and initializes the text layout used
- * to compute the size hint.
- *
- *
- */
- private void createTextLayout() {
- fTextLayout= new TextLayout(fBrowser.getDisplay());
-
- // Initialize fonts
- Font font= fBrowser.getFont();
- fTextLayout.setFont(font);
- fTextLayout.setWidth(-1);
- FontData[] fontData= font.getFontData();
- for (int i= 0; i < fontData.length; i++)
- fontData[i].setStyle(SWT.BOLD);
- font= new Font(fShell.getDisplay(), fontData);
- fBoldStyle= new TextStyle(font, null, null);
-
- // Compute and set tab width
- fTextLayout.setText(" "); //$NON-NLS-1$
- int tabWidth = fTextLayout.getBounds().width;
- fTextLayout.setTabs(new int[] {tabWidth});
-
- fTextLayout.setText(""); //$NON-NLS-1$
- }
-
- /*
- * @see IInformationControl#dispose()
- */
- public void dispose() {
- fTextLayout.dispose();
- fTextLayout= null;
- fBoldStyle.font.dispose();
- fBoldStyle= null;
- if (fShell != null && !fShell.isDisposed())
- fShell.dispose();
- else
- widgetDisposed(null);
- }
-
- /*
- * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
- */
- public void widgetDisposed(DisposeEvent event) {
- if (fStatusTextFont != null && !fStatusTextFont.isDisposed())
- fStatusTextFont.dispose();
-
- fShell= null;
- fBrowser= null;
- fStatusTextFont= null;
- }
-
- /*
- * @see IInformationControl#setSize(int, int)
- */
- public void setSize(int width, int height) {
- fShell.setSize(Math.min(width, fMaxWidth), Math.min(height, fMaxHeight));
- }
-
- /*
- * @see IInformationControl#setLocation(Point)
- */
- public void setLocation(Point location) {
- fShell.setLocation(location);
- }
-
- /*
- * @see IInformationControl#setSizeConstraints(int, int)
- */
- public void setSizeConstraints(int maxWidth, int maxHeight) {
- fMaxWidth= maxWidth;
- fMaxHeight= maxHeight;
- }
-
- /*
- * @see IInformationControl#computeSizeHint()
- */
- public Point computeSizeHint() {
- TextPresentation presentation= new TextPresentation();
- HTML2TextReader reader= new HTML2TextReader(new StringReader(fInputText), presentation);
- String text;
- try {
- text= reader.getString();
- } catch (IOException e) {
- text= ""; //$NON-NLS-1$
- }
-
- fTextLayout.setText(text);
- Iterator iter= presentation.getAllStyleRangeIterator();
- while (iter.hasNext()) {
- StyleRange sr= (StyleRange)iter.next();
- if (sr.fontStyle == SWT.BOLD)
- fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length - 1);
- }
- Rectangle bounds= fTextLayout.getBounds();
- int width= bounds.width;
- int height= bounds.height;
-
- width += 15;
- height += 25;
-
- if (fStatusFieldText != null && fSeparator != null) {
- fTextLayout.setText(fStatusFieldText);
- Rectangle statusBounds= fTextLayout.getBounds();
- Rectangle separatorBounds= fSeparator.getBounds();
- width= Math.max(width, statusBounds.width);
- height= height + statusBounds.height + separatorBounds.height;
- }
-
- // Apply size constraints
- if (fMaxWidth != SWT.DEFAULT)
- width= Math.min(fMaxWidth, width);
- if (fMaxHeight != SWT.DEFAULT)
- height= Math.min(fMaxHeight, height);
-
- // Ensure minimal size
- width= Math.max(MIN_WIDTH, width);
- height= Math.max(MIN_HEIGHT, height);
-
- return new Point(width, height);
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension3#computeTrim()
- */
- public Rectangle computeTrim() {
- return fShell.computeTrim(0, 0, 0, 0);
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension3#getBounds()
- */
- public Rectangle getBounds() {
- return fShell.getBounds();
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension3#restoresLocation()
- */
- public boolean restoresLocation() {
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension3#restoresSize()
- */
- public boolean restoresSize() {
- return false;
- }
-
- /*
- * @see IInformationControl#addDisposeListener(DisposeListener)
- */
- public void addDisposeListener(DisposeListener listener) {
- fShell.addDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#removeDisposeListener(DisposeListener)
- */
- public void removeDisposeListener(DisposeListener listener) {
- fShell.removeDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#setForegroundColor(Color)
- */
- public void setForegroundColor(Color foreground) {
- fBrowser.setForeground(foreground);
- }
-
- /*
- * @see IInformationControl#setBackgroundColor(Color)
- */
- public void setBackgroundColor(Color background) {
- fBrowser.setBackground(background);
- }
-
- /*
- * @see IInformationControl#isFocusControl()
- */
- public boolean isFocusControl() {
- return fBrowser.isFocusControl();
- }
-
- /*
- * @see IInformationControl#setFocus()
- */
- public void setFocus() {
- fShell.forceFocus();
- fBrowser.setFocus();
- }
-
- /*
- * @see IInformationControl#addFocusListener(FocusListener)
- */
- public void addFocusListener(final FocusListener listener) {
- fBrowser.addFocusListener(listener);
-
- /*
- * FIXME: This is a workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532
- * (Browser widget does not send focusLost event)
- */
- if (fFocusListeners.isEmpty()) {
- fDeactivateListener= new Listener() {
- public void handleEvent(Event event) {
- Object[] listeners= fFocusListeners.getListeners();
- for (int i = 0; i < listeners.length; i++)
- ((FocusListener)listeners[i]).focusLost(new FocusEvent(event));
- }
- };
- fBrowser.getShell().addListener(SWT.Deactivate, fDeactivateListener);
- }
- fFocusListeners.add(listener);
- }
-
- /*
- * @see IInformationControl#removeFocusListener(FocusListener)
- */
- public void removeFocusListener(FocusListener listener) {
- fBrowser.removeFocusListener(listener);
-
- /*
- * FIXME: This is a workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532
- * (Browser widget does not send focusLost event)
- */
- fFocusListeners.remove(listener);
- if (fFocusListeners.isEmpty()) {
- fBrowser.getShell().removeListener(SWT.Deactivate, fDeactivateListener);
- fDeactivateListener= null;
- }
- }
-
- /*
- * @see IInformationControlExtension#hasContents()
- */
- public boolean hasContents() {
- return fBrowserHasContent;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTML2TextReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTML2TextReader.java
deleted file mode 100644
index 2cb56e5a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTML2TextReader.java
+++ /dev/null
@@ -1,330 +0,0 @@
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-
-import java.io.IOException;
-import java.io.PushbackReader;
-import java.io.Reader;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-
-import org.eclipse.jface.text.TextPresentation;
-
-
-/**
- * Reads the text contents from a reader of HTML contents and translates
- * the tags or cut them out.
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- */
-public class HTML2TextReader extends SubstitutionTextReader {
-
- private static final String EMPTY_STRING= ""; //$NON-NLS-1$
- private static final Map fgEntityLookup;
- private static final Set fgTags;
-
- static {
-
- fgTags= new HashSet();
- fgTags.add("b"); //$NON-NLS-1$
- fgTags.add("br"); //$NON-NLS-1$
- fgTags.add("br/"); //$NON-NLS-1$
- fgTags.add("div"); //$NON-NLS-1$
- fgTags.add("h1"); //$NON-NLS-1$
- fgTags.add("h2"); //$NON-NLS-1$
- fgTags.add("h3"); //$NON-NLS-1$
- fgTags.add("h4"); //$NON-NLS-1$
- fgTags.add("h5"); //$NON-NLS-1$
- fgTags.add("p"); //$NON-NLS-1$
- fgTags.add("dl"); //$NON-NLS-1$
- fgTags.add("dt"); //$NON-NLS-1$
- fgTags.add("dd"); //$NON-NLS-1$
- fgTags.add("li"); //$NON-NLS-1$
- fgTags.add("ul"); //$NON-NLS-1$
- fgTags.add("pre"); //$NON-NLS-1$
- fgTags.add("head"); //$NON-NLS-1$
-
- fgEntityLookup= new HashMap(7);
- fgEntityLookup.put("lt", "<"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("gt", ">"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("nbsp", " "); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("amp", "&"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("circ", "^"); //$NON-NLS-1$ //$NON-NLS-2$
- fgEntityLookup.put("tilde", "~"); //$NON-NLS-2$ //$NON-NLS-1$
- fgEntityLookup.put("quot", "\""); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private int fCounter= 0;
- private TextPresentation fTextPresentation;
- private int fBold= 0;
- private int fStartOffset= -1;
- private boolean fInParagraph= false;
- private boolean fIsPreformattedText= false;
- private boolean fIgnore= false;
- private boolean fHeaderDetected= false;
-
- /**
- * Transforms the HTML text from the reader to formatted text.
- *
- * @param reader the reader
- * @param presentation If not <code>null</code>, formattings will be applied to
- * the presentation.
- */
- public HTML2TextReader(Reader reader, TextPresentation presentation) {
- super(new PushbackReader(reader));
- fTextPresentation= presentation;
- }
-
- public int read() throws IOException {
- int c= super.read();
- if (c != -1)
- ++ fCounter;
- return c;
- }
-
- protected void startBold() {
- if (fBold == 0)
- fStartOffset= fCounter;
- ++ fBold;
- }
-
- protected void startPreformattedText() {
- fIsPreformattedText= true;
- setSkipWhitespace(false);
- }
-
- protected void stopPreformattedText() {
- fIsPreformattedText= false;
- setSkipWhitespace(true);
- }
-
- protected void stopBold() {
- -- fBold;
- if (fBold == 0) {
- if (fTextPresentation != null) {
- fTextPresentation.addStyleRange(new StyleRange(fStartOffset, fCounter - fStartOffset, null, null, SWT.BOLD));
- }
- fStartOffset= -1;
- }
- }
-
- /*
- * @see org.eclipse.jdt.internal.ui.text.SubstitutionTextReader#computeSubstitution(int)
- */
- protected String computeSubstitution(int c) throws IOException {
-
- if (c == '<')
- return processHTMLTag();
- else if (fIgnore)
- return EMPTY_STRING;
- else if (c == '&')
- return processEntity();
- else if (fIsPreformattedText)
- return processPreformattedText(c);
-
- return null;
- }
-
- private String html2Text(String html) {
-
- if (html == null || html.length() == 0)
- return EMPTY_STRING;
-
- html= html.toLowerCase();
-
- String tag= html;
- if ('/' == tag.charAt(0))
- tag= tag.substring(1);
-
- if (!fgTags.contains(tag))
- return EMPTY_STRING;
-
-
- if ("pre".equals(html)) { //$NON-NLS-1$
- startPreformattedText();
- return EMPTY_STRING;
- }
-
- if ("/pre".equals(html)) { //$NON-NLS-1$
- stopPreformattedText();
- return EMPTY_STRING;
- }
-
- if (fIsPreformattedText)
- return EMPTY_STRING;
-
- if ("b".equals(html)) { //$NON-NLS-1$
- startBold();
- return EMPTY_STRING;
- }
-
- if ((html.length() > 1 && html.charAt(0) == 'h' && Character.isDigit(html.charAt(1))) || "dt".equals(html)) { //$NON-NLS-1$
- startBold();
- return EMPTY_STRING;
- }
-
- if ("dl".equals(html)) //$NON-NLS-1$
- return LINE_DELIM;
-
- if ("dd".equals(html)) //$NON-NLS-1$
- return "\t"; //$NON-NLS-1$
-
- if ("li".equals(html)) //$NON-NLS-1$
- // FIXME: this hard-coded prefix does not work for RTL languages, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=91682
- return LINE_DELIM + HTMLMessages.getString("HTML2TextReader.listItemPrefix"); //$NON-NLS-1$
-
- if ("/b".equals(html)) { //$NON-NLS-1$
- stopBold();
- return EMPTY_STRING;
- }
-
- if ("p".equals(html)) { //$NON-NLS-1$
- fInParagraph= true;
- return LINE_DELIM;
- }
-
- if ("br".equals(html) || "br/".equals(html) || "div".equals(html)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- return LINE_DELIM;
-
- if ("/p".equals(html)) { //$NON-NLS-1$
- boolean inParagraph= fInParagraph;
- fInParagraph= false;
- return inParagraph ? EMPTY_STRING : LINE_DELIM;
- }
-
- if ((html.startsWith("/h") && html.length() > 2 && Character.isDigit(html.charAt(2))) || "/dt".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$
- stopBold();
- return LINE_DELIM;
- }
-
- if ("/dd".equals(html)) //$NON-NLS-1$
- return LINE_DELIM;
-
- if ("head".equals(html) && !fHeaderDetected) { //$NON-NLS-1$
- fHeaderDetected= true;
- fIgnore= true;
- return EMPTY_STRING;
- }
-
- if ("/head".equals(html) && fHeaderDetected && fIgnore) { //$NON-NLS-1$
- fIgnore= false;
- return EMPTY_STRING;
- }
-
- return EMPTY_STRING;
- }
-
- /*
- * A '<' has been read. Process a html tag
- */
- private String processHTMLTag() throws IOException {
-
- StringBuffer buf= new StringBuffer();
- int ch;
- do {
-
- ch= nextChar();
-
- while (ch != -1 && ch != '>') {
- buf.append(Character.toLowerCase((char) ch));
- ch= nextChar();
- if (ch == '"'){
- buf.append(Character.toLowerCase((char) ch));
- ch= nextChar();
- while (ch != -1 && ch != '"'){
- buf.append(Character.toLowerCase((char) ch));
- ch= nextChar();
- }
- }
- if (ch == '<'){
- unread(ch);
- return '<' + buf.toString();
- }
- }
-
- if (ch == -1)
- return null;
-
- int tagLen= buf.length();
- // needs special treatment for comments
- if ((tagLen >= 3 && "!--".equals(buf.substring(0, 3))) //$NON-NLS-1$
- && !(tagLen >= 5 && "--".equals(buf.substring(tagLen - 2)))) { //$NON-NLS-1$
- // unfinished comment
- buf.append(ch);
- } else {
- break;
- }
- } while (true);
-
- return html2Text(buf.toString());
- }
-
- private String processPreformattedText(int c) {
- if (c == '\r' || c == '\n')
- fCounter++;
- return null;
- }
-
-
- private void unread(int ch) throws IOException {
- ((PushbackReader) getReader()).unread(ch);
- }
-
- protected String entity2Text(String symbol) {
- if (symbol.length() > 1 && symbol.charAt(0) == '#') {
- int ch;
- try {
- if (symbol.charAt(1) == 'x') {
- ch= Integer.parseInt(symbol.substring(2), 16);
- } else {
- ch= Integer.parseInt(symbol.substring(1), 10);
- }
- return EMPTY_STRING + (char)ch;
- } catch (NumberFormatException e) {
- }
- } else {
- String str= (String) fgEntityLookup.get(symbol);
- if (str != null) {
- return str;
- }
- }
- return "&" + symbol; // not found //$NON-NLS-1$
- }
-
- /*
- * A '&' has been read. Process a entity
- */
- private String processEntity() throws IOException {
- StringBuffer buf= new StringBuffer();
- int ch= nextChar();
- while (Character.isLetterOrDigit((char)ch) || ch == '#') {
- buf.append((char) ch);
- ch= nextChar();
- }
-
- if (ch == ';')
- return entity2Text(buf.toString());
-
- buf.insert(0, '&');
- if (ch != -1)
- buf.append((char) ch);
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java
deleted file mode 100644
index cc2bda8e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java
+++ /dev/null
@@ -1,83 +0,0 @@
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-import com.ibm.icu.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-
-/**
- * Helper class to get NLSed messages.
- *
- *
- */
-class HTMLMessages {
-
- private static final String RESOURCE_BUNDLE= HTMLMessages.class.getName();
-
- private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
-
- private HTMLMessages() {
- }
-
- /**
- * Gets a string from the resource bundle.
- *
- * @param key the string used to get the bundle value, must not be null
- * @return the string from the resource bundle
- */
- public static String getString(String key) {
- try {
- return fgResourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
- }
- }
-
- /**
- * Gets a string from the resource bundle and formats it with the given arguments.
- *
- * @param key the string used to get the bundle value, must not be null
- * @param args the arguments used to format the string
- * @return the formatted string
- */
- public static String getFormattedString(String key, Object[] args) {
- String format= null;
- try {
- format= fgResourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
- }
- return MessageFormat.format(format, args);
- }
-
- /**
- * Gets a string from the resource bundle and formats it with the given argument.
- *
- * @param key the string used to get the bundle value, must not be null
- * @param arg the argument used to format the string
- * @return the formatted string
- */
- public static String getFormattedString(String key, Object arg) {
- String format= null;
- try {
- format= fgResourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
- }
- if (arg == null)
- arg= ""; //$NON-NLS-1$
- return MessageFormat.format(format, new Object[] { arg });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties
deleted file mode 100644
index 6b501b1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-###############################################################################
-# Copyright (c) 2006, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-HTMLTextPresenter.ellipse= ...
-
-# The following property value must end with a space
-HTML2TextReader.listItemPrefix=\t-\
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java
deleted file mode 100644
index c30f01fe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java
+++ /dev/null
@@ -1,306 +0,0 @@
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URL;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
-
-
-/**
- * Provides a set of convenience methods for creating HTML pages.
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- */
-public class HTMLPrinter {
-
- private static RGB BG_COLOR_RGB= null;
-
- static {
- final Display display= Display.getDefault();
- if (display != null && !display.isDisposed()) {
- try {
- display.asyncExec(new Runnable() {
- /*
- * @see java.lang.Runnable#run()
- */
- public void run() {
- BG_COLOR_RGB= display.getSystemColor(SWT.COLOR_INFO_BACKGROUND).getRGB();
- }
- });
- } catch (SWTError err) {
- // see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=45294
- if (err.code != SWT.ERROR_DEVICE_DISPOSED)
- throw err;
- }
- }
- }
-
- private HTMLPrinter() {
- }
-
- private static String replace(String text, char c, String s) {
-
- int previous= 0;
- int current= text.indexOf(c, previous);
-
- if (current == -1)
- return text;
-
- StringBuffer buffer= new StringBuffer();
- while (current > -1) {
- buffer.append(text.substring(previous, current));
- buffer.append(s);
- previous= current + 1;
- current= text.indexOf(c, previous);
- }
- buffer.append(text.substring(previous));
-
- return buffer.toString();
- }
-
- public static String convertToHTMLContent(String content) {
- content= replace(content, '&', "&amp;"); //$NON-NLS-1$
- content= replace(content, '"', "&quot;"); //$NON-NLS-1$
- content= replace(content, '<', "&lt;"); //$NON-NLS-1$
- return replace(content, '>', "&gt;"); //$NON-NLS-1$
- }
-
- public static String read(Reader rd) {
-
- StringBuffer buffer= new StringBuffer();
- char[] readBuffer= new char[2048];
-
- try {
- int n= rd.read(readBuffer);
- while (n > 0) {
- buffer.append(readBuffer, 0, n);
- n= rd.read(readBuffer);
- }
- return buffer.toString();
- } catch (IOException x) {
- }
-
- return null;
- }
-
- public static void insertPageProlog(StringBuffer buffer, int position, RGB bgRGB, URL styleSheetURL) {
-
- if (bgRGB == null)
- insertPageProlog(buffer, position, styleSheetURL);
- else {
- StringBuffer pageProlog= new StringBuffer(300);
-
- pageProlog.append("<html>"); //$NON-NLS-1$
-
- appendStyleSheetURL(pageProlog, styleSheetURL);
-
- pageProlog.append("<body text=\"#000000\" bgcolor=\""); //$NON-NLS-1$
- appendColor(pageProlog, bgRGB);
- pageProlog.append("\">"); //$NON-NLS-1$
-
- buffer.insert(position, pageProlog.toString());
- }
- }
- public static void insertPageProlog(StringBuffer buffer, int position, RGB bgRGB, String styleSheet) {
-
- if (bgRGB == null)
- insertPageProlog(buffer, position, styleSheet);
- else {
- StringBuffer pageProlog= new StringBuffer(300);
-
- pageProlog.append("<html>"); //$NON-NLS-1$
-
- appendStyleSheetURL(pageProlog, styleSheet);
-
- pageProlog.append("<body text=\"#000000\" bgcolor=\""); //$NON-NLS-1$
- appendColor(pageProlog, bgRGB);
- pageProlog.append("\">"); //$NON-NLS-1$
-
- buffer.insert(position, pageProlog.toString());
- }
- }
-
- public static void insertStyles(StringBuffer buffer, String[] styles) {
- if (styles == null || styles.length == 0)
- return;
-
- StringBuffer styleBuf= new StringBuffer(10 * styles.length);
- for (int i= 0; styles != null && i < styles.length; i++) {
- styleBuf.append(" style=\""); //$NON-NLS-1$
- styleBuf.append(styles[i]);
- styleBuf.append('"');
- }
-
- // Find insertion index
- // a) within existing body tag with trailing space
- int index= buffer.indexOf("<body "); //$NON-NLS-1$
- if (index != -1) {
- buffer.insert(index+5, styleBuf);
- return;
- }
-
- // b) within existing body tag without attributes
- index= buffer.indexOf("<body>"); //$NON-NLS-1$
- if (index != -1) {
- buffer.insert(index+5, ' ');
- buffer.insert(index+6, styleBuf);
- return;
- }
- }
-
- public static void insertPageProlog(StringBuffer buffer, int position, RGB bgRGB) {
- if (bgRGB == null)
- insertPageProlog(buffer, position);
- else {
- StringBuffer pageProlog= new StringBuffer(60);
- pageProlog.append("<html><body text=\"#000000\" bgcolor=\""); //$NON-NLS-1$
- appendColor(pageProlog, bgRGB);
- pageProlog.append("\">"); //$NON-NLS-1$
- buffer.insert(position, pageProlog.toString());
- }
- }
-
- private static void appendStyleSheetURL(StringBuffer buffer, String styleSheet) {
- if (styleSheet == null)
- return;
-
- buffer.append("<head><style CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); //$NON-NLS-1$
- buffer.append(styleSheet);
- buffer.append("</style></head>"); //$NON-NLS-1$
- }
-
- private static void appendStyleSheetURL(StringBuffer buffer, URL styleSheetURL) {
- if (styleSheetURL == null)
- return;
-
- buffer.append("<head>"); //$NON-NLS-1$
-
- buffer.append("<LINK REL=\"stylesheet\" HREF= \""); //$NON-NLS-1$
- buffer.append(styleSheetURL);
- buffer.append("\" CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); //$NON-NLS-1$
-
- buffer.append("</head>"); //$NON-NLS-1$
- }
-
- private static void appendColor(StringBuffer buffer, RGB rgb) {
- buffer.append('#');
- buffer.append(Integer.toHexString(rgb.red));
- buffer.append(Integer.toHexString(rgb.green));
- buffer.append(Integer.toHexString(rgb.blue));
- }
-
- public static void insertPageProlog(StringBuffer buffer, int position) {
- insertPageProlog(buffer, position, getBgColor());
- }
-
- public static void insertPageProlog(StringBuffer buffer, int position, URL styleSheetURL) {
- insertPageProlog(buffer, position, getBgColor(), styleSheetURL);
- }
-
- public static void insertPageProlog(StringBuffer buffer, int position, String styleSheet) {
- insertPageProlog(buffer, position, getBgColor(), styleSheet);
- }
-
- private static RGB getBgColor() {
- if (BG_COLOR_RGB != null)
- return BG_COLOR_RGB;
- return new RGB(255,255, 225); // RGB value of info bg color on WindowsXP
-
- }
-
- public static void addPageProlog(StringBuffer buffer) {
- insertPageProlog(buffer, buffer.length());
- }
-
- public static void addPageEpilog(StringBuffer buffer) {
- buffer.append("</font></body></html>"); //$NON-NLS-1$
- }
-
- public static void startBulletList(StringBuffer buffer) {
- buffer.append("<ul>"); //$NON-NLS-1$
- }
-
- public static void endBulletList(StringBuffer buffer) {
- buffer.append("</ul>"); //$NON-NLS-1$
- }
-
- public static void addBullet(StringBuffer buffer, String bullet) {
- if (bullet != null) {
- buffer.append("<li>"); //$NON-NLS-1$
- buffer.append(bullet);
- buffer.append("</li>"); //$NON-NLS-1$
- }
- }
-
- public static void addSmallHeader(StringBuffer buffer, String header) {
- if (header != null) {
- buffer.append("<h5>"); //$NON-NLS-1$
- buffer.append(header);
- buffer.append("</h5>"); //$NON-NLS-1$
- }
- }
-
- public static void addParagraph(StringBuffer buffer, String paragraph) {
- if (paragraph != null) {
- buffer.append("<p>"); //$NON-NLS-1$
- buffer.append(paragraph);
- }
- }
-
- public static void addParagraph(StringBuffer buffer, Reader paragraphReader) {
- if (paragraphReader != null)
- addParagraph(buffer, read(paragraphReader));
- }
-
- /**
- * Replaces the following style attributes of the font definition of the <code>html</code>
- * element:
- * <ul>
- * <li>font-size</li>
- * <li>font-weight</li>
- * <li>font-style</li>
- * <li>font-family</li>
- * </ul>
- * The font's name is used as font family, a <code>sans-serif</code> default font family is
- * appended for the case that the given font name is not available.
- * <p>
- * If the listed font attributes are not contained in the passed style list, nothing happens.
- * </p>
- *
- * @param styles CSS style definitions
- * @param fontData the font information to use
- * @return the modified style definitions
- *
- */
- public static String convertTopLevelFont(String styles, FontData fontData) {
- boolean bold= (fontData.getStyle() & SWT.BOLD) != 0;
- boolean italic= (fontData.getStyle() & SWT.ITALIC) != 0;
-
- // See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=155993
- String size= Integer.toString(fontData.getHeight()) + ("carbon".equals(SWT.getPlatform()) ? "px" : "pt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- String family= "'" + fontData.getName() + "',sans-serif"; //$NON-NLS-1$ //$NON-NLS-2$
- styles= styles.replaceFirst("(html\\s*\\{.*(?:\\s|;)font-size:\\s*)\\d+pt(\\;?.*\\})", "$1" + size + "$2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- styles= styles.replaceFirst("(html\\s*\\{.*(?:\\s|;)font-weight:\\s*)\\w+(\\;?.*\\})", "$1" + (bold ? "bold" : "normal") + "$2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- styles= styles.replaceFirst("(html\\s*\\{.*(?:\\s|;)font-style:\\s*)\\w+(\\;?.*\\})", "$1" + (italic ? "italic" : "normal") + "$2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- styles= styles.replaceFirst("(html\\s*\\{.*(?:\\s|;)font-family:\\s*).+?(;.*\\})", "$1" + family + "$2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- return styles;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java
deleted file mode 100644
index 0bc7c856..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java
+++ /dev/null
@@ -1,315 +0,0 @@
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.Iterator;
-
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Drawable;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.widgets.Display;
-
-
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextPresentation;
-
-import com.ibm.icu.text.BreakIterator;
-
-
-/**
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- */
-public class HTMLTextPresenter implements DefaultInformationControl.IInformationPresenter, DefaultInformationControl.IInformationPresenterExtension {
-
- public class LineBreakingReader {
-
- private BufferedReader fReader;
- private GC fGC;
- private int fMaxWidth;
-
- private String fLine;
- private int fOffset;
-
- private BreakIterator fLineBreakIterator;
- private boolean fBreakWords;
-
- /**
- * Creates a reader that breaks an input text to fit in a given width.
- *
- * @param reader Reader of the input text
- * @param gc The graphic context that defines the currently used font sizes
- * @param maxLineWidth The max width (pixels) where the text has to fit in
- */
- public LineBreakingReader(Reader reader, GC gc, int maxLineWidth) {
- fReader= new BufferedReader(reader);
- fGC= gc;
- fMaxWidth= maxLineWidth;
- fOffset= 0;
- fLine= null;
- fLineBreakIterator= BreakIterator.getLineInstance();
- fBreakWords= true;
- }
-
- public boolean isFormattedLine() {
- return fLine != null;
- }
-
- /**
- * Reads the next line. The lengths of the line will not exceed the given maximum
- * width.
- *
- * @return the next line
- * @throws IOException
- */
- public String readLine() throws IOException {
- if (fLine == null) {
- String line= fReader.readLine();
- if (line == null)
- return null;
-
- int lineLen= fGC.textExtent(line).x;
- if (lineLen < fMaxWidth) {
- return line;
- }
- fLine= line;
- fLineBreakIterator.setText(line);
- fOffset= 0;
- }
- int breakOffset= findNextBreakOffset(fOffset);
- String res;
- if (breakOffset != BreakIterator.DONE) {
- res= fLine.substring(fOffset, breakOffset);
- fOffset= findWordBegin(breakOffset);
- if (fOffset == fLine.length()) {
- fLine= null;
- }
- } else {
- res= fLine.substring(fOffset);
- fLine= null;
- }
- return res;
- }
-
- private int findNextBreakOffset(int currOffset) {
- int currWidth= 0;
- int nextOffset= fLineBreakIterator.following(currOffset);
- while (nextOffset != BreakIterator.DONE) {
- String word= fLine.substring(currOffset, nextOffset);
- int wordWidth= fGC.textExtent(word).x;
- int nextWidth= wordWidth + currWidth;
- if (nextWidth > fMaxWidth) {
- if (currWidth > 0)
- return currOffset;
-
- if (!fBreakWords)
- return nextOffset;
-
- // need to fit into fMaxWidth
- int length= word.length();
- while (length >= 0) {
- length--;
- word= word.substring(0, length);
- wordWidth= fGC.textExtent(word).x;
- if (wordWidth + currWidth < fMaxWidth)
- return currOffset + length;
- }
- return nextOffset;
- }
- currWidth= nextWidth;
- currOffset= nextOffset;
- nextOffset= fLineBreakIterator.next();
- }
- return nextOffset;
- }
-
- private int findWordBegin(int idx) {
- while (idx < fLine.length() && Character.isWhitespace(fLine.charAt(idx))) {
- idx++;
- }
- return idx;
- }
- }
- private static final String LINE_DELIM= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- private int fCounter;
- private boolean fEnforceUpperLineLimit;
-
- public HTMLTextPresenter(boolean enforceUpperLineLimit) {
- super();
- fEnforceUpperLineLimit= enforceUpperLineLimit;
- }
-
- public HTMLTextPresenter() {
- this(true);
- }
-
- protected Reader createReader(String hoverInfo, TextPresentation presentation) {
- return new HTML2TextReader(new StringReader(hoverInfo), presentation);
- }
-
- protected void adaptTextPresentation(TextPresentation presentation, int offset, int insertLength) {
-
- int yoursStart= offset;
- int yoursEnd= offset + insertLength -1;
- yoursEnd= Math.max(yoursStart, yoursEnd);
-
- Iterator e= presentation.getAllStyleRangeIterator();
- while (e.hasNext()) {
-
- StyleRange range= (StyleRange) e.next();
-
- int myStart= range.start;
- int myEnd= range.start + range.length -1;
- myEnd= Math.max(myStart, myEnd);
-
- if (myEnd < yoursStart)
- continue;
-
- if (myStart < yoursStart)
- range.length += insertLength;
- else
- range.start += insertLength;
- }
- }
-
- private void append(StringBuffer buffer, String string, TextPresentation presentation) {
-
- int length= string.length();
- buffer.append(string);
-
- if (presentation != null)
- adaptTextPresentation(presentation, fCounter, length);
-
- fCounter += length;
- }
-
- private String getIndent(String line) {
- int length= line.length();
-
- int i= 0;
- while (i < length && Character.isWhitespace(line.charAt(i))) ++i;
-
- return (i == length ? line : line.substring(0, i)) + " "; //$NON-NLS-1$
- }
-
- /*
- * @see IHoverInformationPresenter#updatePresentation(Display display, String, TextPresentation, int, int)
- */
- public String updatePresentation(Display display, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) {
- return updatePresentation((Drawable)display, hoverInfo, presentation, maxWidth, maxHeight);
- }
-
- /*
- * @see IHoverInformationPresenterExtension#updatePresentation(Drawable drawable, String, TextPresentation, int, int)
- *
- */
- public String updatePresentation(Drawable drawable, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) {
-
- if (hoverInfo == null)
- return null;
-
- GC gc= new GC(drawable);
- try {
-
- StringBuffer buffer= new StringBuffer();
- int maxNumberOfLines= Math.round(maxHeight / gc.getFontMetrics().getHeight());
-
- fCounter= 0;
- LineBreakingReader reader= new LineBreakingReader(createReader(hoverInfo, presentation), gc, maxWidth);
-
- boolean lastLineFormatted= false;
- String lastLineIndent= null;
-
- String line=reader.readLine();
- boolean lineFormatted= reader.isFormattedLine();
- boolean firstLineProcessed= false;
-
- while (line != null) {
-
- if (fEnforceUpperLineLimit && maxNumberOfLines <= 0)
- break;
-
- if (firstLineProcessed) {
- if (!lastLineFormatted)
- append(buffer, LINE_DELIM, null);
- else {
- append(buffer, LINE_DELIM, presentation);
- if (lastLineIndent != null)
- append(buffer, lastLineIndent, presentation);
- }
- }
-
- append(buffer, line, null);
- firstLineProcessed= true;
-
- lastLineFormatted= lineFormatted;
- if (!lineFormatted)
- lastLineIndent= null;
- else if (lastLineIndent == null)
- lastLineIndent= getIndent(line);
-
- line= reader.readLine();
- lineFormatted= reader.isFormattedLine();
-
- maxNumberOfLines--;
- }
-
- if (line != null) {
- append(buffer, LINE_DELIM, lineFormatted ? presentation : null);
- append(buffer, HTMLMessages.getString("HTMLTextPresenter.ellipse"), presentation); //$NON-NLS-1$
- }
-
- return trim(buffer, presentation);
-
- } catch (IOException e) {
-
- // ignore TODO do something else?
- return null;
-
- } finally {
- gc.dispose();
- }
- }
-
- private String trim(StringBuffer buffer, TextPresentation presentation) {
-
- int length= buffer.length();
-
- int end= length -1;
- while (end >= 0 && Character.isWhitespace(buffer.charAt(end)))
- -- end;
-
- if (end == -1)
- return ""; //$NON-NLS-1$
-
- if (end < length -1)
- buffer.delete(end + 1, length);
- else
- end= length;
-
- int start= 0;
- while (start < end && Character.isWhitespace(buffer.charAt(start)))
- ++ start;
-
- buffer.delete(0, start);
- presentation.setResultWindow(new Region(start, buffer.length()));
- return buffer.toString();
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SingleCharReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SingleCharReader.java
deleted file mode 100644
index 9c738b9b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SingleCharReader.java
+++ /dev/null
@@ -1,67 +0,0 @@
-// COPIED FROM org.eclipse.jface.internal.text.html
-// to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-import java.io.IOException;
-import java.io.Reader;
-
-
-/**
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- */
-public abstract class SingleCharReader extends Reader {
-
- /**
- * @see Reader#read()
- */
- public abstract int read() throws IOException;
-
- /**
- * @see Reader#read(char[],int,int)
- */
- public int read(char cbuf[], int off, int len) throws IOException {
- int end= off + len;
- for (int i= off; i < end; i++) {
- int ch= read();
- if (ch == -1) {
- if (i == off)
- return -1;
- return i - off;
- }
- cbuf[i]= (char)ch;
- }
- return len;
- }
-
- /**
- * @see Reader#ready()
- */
- public boolean ready() throws IOException {
- return true;
- }
-
- /**
- * Returns the readable content as string.
- * @return the readable content as string
- * @exception IOException in case reading fails
- */
- public String getString() throws IOException {
- StringBuffer buf= new StringBuffer();
- int ch;
- while ((ch= read()) != -1) {
- buf.append((char)ch);
- }
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SubstitutionTextReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SubstitutionTextReader.java
deleted file mode 100644
index 0cfa9cde..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/SubstitutionTextReader.java
+++ /dev/null
@@ -1,162 +0,0 @@
-
-//COPIED FROM org.eclipse.jface.internal.text.html
-//to get around "discouraged access" errors
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.html;
-
-import java.io.IOException;
-import java.io.Reader;
-
-
-/**
- * Reads the text contents from a reader and computes for each character
- * a potential substitution. The substitution may eat more characters than
- * only the one passed into the computation routine.
- * <p>
- * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p>
- */
-public abstract class SubstitutionTextReader extends SingleCharReader {
-
- protected static final String LINE_DELIM= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- private Reader fReader;
- protected boolean fWasWhiteSpace;
- private int fCharAfterWhiteSpace;
-
- /**
- * Tells whether white space characters are skipped.
- */
- private boolean fSkipWhiteSpace= true;
-
- private boolean fReadFromBuffer;
- private StringBuffer fBuffer;
- private int fIndex;
-
-
- protected SubstitutionTextReader(Reader reader) {
- fReader= reader;
- fBuffer= new StringBuffer();
- fIndex= 0;
- fReadFromBuffer= false;
- fCharAfterWhiteSpace= -1;
- fWasWhiteSpace= true;
- }
-
- /**
- * Computes the substitution for the given character and if necessary
- * subsequent characters. Implementation should use <code>nextChar</code>
- * to read subsequent characters.
- *
- * @param c the character to be substituted
- * @return the substitution for <code>c</code>
- * @throws IOException in case computing the substitution fails
- */
- protected abstract String computeSubstitution(int c) throws IOException;
-
- /**
- * Returns the internal reader.
- *
- * @return the internal reader
- */
- protected Reader getReader() {
- return fReader;
- }
-
- /**
- * Returns the next character.
- * @return the next character
- * @throws IOException in case reading the character fails
- */
- protected int nextChar() throws IOException {
- fReadFromBuffer= (fBuffer.length() > 0);
- if (fReadFromBuffer) {
- char ch= fBuffer.charAt(fIndex++);
- if (fIndex >= fBuffer.length()) {
- fBuffer.setLength(0);
- fIndex= 0;
- }
- return ch;
- }
-
- int ch= fCharAfterWhiteSpace;
- if (ch == -1) {
- ch= fReader.read();
- }
- if (fSkipWhiteSpace && Character.isWhitespace((char)ch)) {
- do {
- ch= fReader.read();
- } while (Character.isWhitespace((char)ch));
- if (ch != -1) {
- fCharAfterWhiteSpace= ch;
- return ' ';
- }
- } else {
- fCharAfterWhiteSpace= -1;
- }
- return ch;
- }
-
- /**
- * @see Reader#read()
- */
- public int read() throws IOException {
- int c;
- do {
-
- c= nextChar();
- while (!fReadFromBuffer) {
- String s= computeSubstitution(c);
- if (s == null)
- break;
- if (s.length() > 0)
- fBuffer.insert(0, s);
- c= nextChar();
- }
-
- } while (fSkipWhiteSpace && fWasWhiteSpace && (c == ' '));
- fWasWhiteSpace= (c == ' ' || c == '\r' || c == '\n');
- return c;
- }
-
- /**
- * @see Reader#ready()
- */
- public boolean ready() throws IOException {
- return fReader.ready();
- }
-
- /**
- * @see Reader#close()
- */
- public void close() throws IOException {
- fReader.close();
- }
-
- /**
- * @see Reader#reset()
- */
- public void reset() throws IOException {
- fReader.reset();
- fWasWhiteSpace= true;
- fCharAfterWhiteSpace= -1;
- fBuffer.setLength(0);
- fIndex= 0;
- }
-
- protected final void setSkipWhitespace(boolean state) {
- fSkipWhiteSpace= state;
- }
-
- protected final boolean isSkippingWhitespace() {
- return fSkipWhiteSpace;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java
deleted file mode 100644
index 3069cd15..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java
+++ /dev/null
@@ -1,1035 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.wst.jsdt.internal.ui.text.html.BrowserInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DefaultPositionUpdater;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension2;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension5;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags;
-import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.CharOperation;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.JavaScriptTextTools;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-import org.osgi.framework.Bundle;
-
-/**
- *
- *
- */
-public abstract class AbstractJavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2, ICompletionProposalExtension3, ICompletionProposalExtension5 {
-
-
- /**
- * The control creator.
- *
- *
- */
- private static final class ControlCreator extends AbstractReusableInformationControlCreator {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractReusableInformationControlCreator#doCreateInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl doCreateInformationControl(Shell parent) {
- return new BrowserInformationControl(parent, SWT.NO_TRIM | SWT.TOOL, SWT.NONE, null);
- }
- }
-
-
- /**
- * A class to simplify tracking a reference position in a document.
- */
- static final class ReferenceTracker {
-
- /** The reference position category name. */
- private static final String CATEGORY= "reference_position"; //$NON-NLS-1$
- /** The position updater of the reference position. */
- private final IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(CATEGORY);
- /** The reference position. */
- private final Position fPosition= new Position(0);
-
- /**
- * Called before document changes occur. It must be followed by a call to postReplace().
- *
- * @param document the document on which to track the reference position.
- * @param offset the offset
- * @throws BadLocationException if the offset describes an invalid range in this document
- *
- */
- public void preReplace(IDocument document, int offset) throws BadLocationException {
- fPosition.setOffset(offset);
- try {
- document.addPositionCategory(CATEGORY);
- document.addPositionUpdater(fPositionUpdater);
- document.addPosition(CATEGORY, fPosition);
-
- } catch (BadPositionCategoryException e) {
- // should not happen
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * Called after the document changed occurred. It must be preceded by a call to preReplace().
- *
- * @param document the document on which to track the reference position.
- * @return offset after the replace
- */
- public int postReplace(IDocument document) {
- try {
- document.removePosition(CATEGORY, fPosition);
- document.removePositionUpdater(fPositionUpdater);
- document.removePositionCategory(CATEGORY);
-
- } catch (BadPositionCategoryException e) {
- // should not happen
- JavaScriptPlugin.log(e);
- }
- return fPosition.getOffset();
- }
- }
-
- protected static final class ExitPolicy implements IExitPolicy {
-
- final char fExitCharacter;
- private final IDocument fDocument;
-
- public ExitPolicy(char exitCharacter, IDocument document) {
- fExitCharacter= exitCharacter;
- fDocument= document;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.wst.jsdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
- */
- public ExitFlags doExit(LinkedModeModel environment, VerifyEvent event, int offset, int length) {
-
- if (event.character == fExitCharacter) {
- if (environment.anyPositionContains(offset))
- return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false);
- else
- return new ExitFlags(ILinkedModeListener.UPDATE_CARET, true);
- }
-
- switch (event.character) {
- case ';':
- return new ExitFlags(ILinkedModeListener.NONE, true);
- case SWT.CR:
- // when entering an anonymous class as a parameter, we don't want
- // to jump after the parenthesis when return is pressed
- if (offset > 0) {
- try {
- if (fDocument.getChar(offset - 1) == '{')
- return new ExitFlags(ILinkedModeListener.EXIT_ALL, true);
- } catch (BadLocationException e) {
- }
- }
- return null;
- default:
- return null;
- }
- }
-
- }
-
- private String fDisplayString;
- private String fReplacementString;
- private int fReplacementOffset;
- private int fReplacementLength;
- private int fCursorPosition;
- private Image fImage;
- private IContextInformation fContextInformation;
- private ProposalInfo fProposalInfo;
- private char[] fTriggerCharacters;
- private String fSortString;
- private int fRelevance;
- private boolean fIsInJavadoc;
-
- private StyleRange fRememberedStyleRange;
- private boolean fToggleEating;
- private ITextViewer fTextViewer;
-
-
- /**
- * The control creator.
- *
- *
- */
- private IInformationControlCreator fCreator;
- /**
- * The CSS used to format javadoc information.
- *
- */
- private static String fgCSSStyles;
-
- /**
- * The invocation context of this completion proposal. Can be <code>null</code>.
- */
- protected final JavaContentAssistInvocationContext fInvocationContext;
-
- protected AbstractJavaCompletionProposal() {
- fInvocationContext= null;
- }
-
- protected AbstractJavaCompletionProposal(JavaContentAssistInvocationContext context) {
- fInvocationContext= context;
- }
-
- /*
- * @see ICompletionProposalExtension#getTriggerCharacters()
- */
- public char[] getTriggerCharacters() {
- return fTriggerCharacters;
- }
-
- /**
- * Sets the trigger characters.
- *
- * @param triggerCharacters The set of characters which can trigger the application of this
- * completion proposal
- */
- public void setTriggerCharacters(char[] triggerCharacters) {
- fTriggerCharacters= triggerCharacters;
- }
-
- /**
- * Sets the proposal info.
- *
- * @param proposalInfo The additional information associated with this proposal or
- * <code>null</code>
- */
- public void setProposalInfo(ProposalInfo proposalInfo) {
- fProposalInfo= proposalInfo;
- }
-
- /**
- * Returns the additional proposal info, or <code>null</code> if none exists.
- *
- * @return the additional proposal info, or <code>null</code> if none exists
- */
- protected ProposalInfo getProposalInfo() {
- return fProposalInfo;
- }
-
- /**
- * Sets the cursor position relative to the insertion offset. By default this is the length of
- * the completion string (Cursor positioned after the completion)
- *
- * @param cursorPosition The cursorPosition to set
- */
- public void setCursorPosition(int cursorPosition) {
- Assert.isTrue(cursorPosition >= 0);
- fCursorPosition= cursorPosition;
- }
-
- protected int getCursorPosition() {
- return fCursorPosition;
- }
-
- /*
- * @see ICompletionProposal#apply
- */
- public final void apply(IDocument document) {
- // not used any longer
- apply(document, (char) 0, getReplacementOffset() + getReplacementLength());
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
-
- if (isSupportingRequiredProposals()) {
- CompletionProposal coreProposal= ((MemberProposalInfo)fProposalInfo).fProposal;
- CompletionProposal[] requiredProposals= coreProposal.getRequiredProposals();
- for (int i= 0; requiredProposals != null && i < requiredProposals.length; i++) {
- int oldLen= document.getLength();
- if (requiredProposals[i].getKind() == CompletionProposal.TYPE_REF) {
- LazyJavaCompletionProposal proposal= new LazyJavaTypeCompletionProposal(requiredProposals[i], fInvocationContext);
- proposal.apply(document);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- } else if (requiredProposals[i].getKind() == CompletionProposal.TYPE_IMPORT) {
- ImportCompletionProposal proposal= new ImportCompletionProposal(requiredProposals[i], fInvocationContext, coreProposal.getKind());
- proposal.setReplacementOffset(getReplacementOffset());
- proposal.apply(document);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- } else if (requiredProposals[i].getKind() == CompletionProposal.METHOD_IMPORT) {
- ImportCompletionProposal proposal= new ImportCompletionProposal(requiredProposals[i], fInvocationContext, coreProposal.getKind());
- proposal.setReplacementOffset(getReplacementOffset());
- proposal.apply(document);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- } else if (requiredProposals[i].getKind() == CompletionProposal.FIELD_IMPORT) {
- ImportCompletionProposal proposal= new ImportCompletionProposal(requiredProposals[i], fInvocationContext, coreProposal.getKind());
- proposal.setReplacementOffset(getReplacementOffset());
- proposal.apply(document);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- } else {
- /*
- * In 3.3 we only support the above required proposals, see
- * CompletionProposal#getRequiredProposals()
- */
- Assert.isTrue(false);
- }
- }
- }
-
- try {
- // patch replacement length
- int delta= offset - (getReplacementOffset() + getReplacementLength());
- if (delta > 0)
- setReplacementLength(getReplacementLength() + delta);
-
- boolean isSmartTrigger= isSmartTrigger(trigger);
-
- String replacement;
- if (isSmartTrigger || trigger == (char) 0) {
- replacement= getReplacementString();
- } else {
- StringBuffer buffer= new StringBuffer(getReplacementString());
-
- // fix for PR #5533. Assumes that no eating takes place.
- if ((getCursorPosition() > 0 && getCursorPosition() <= buffer.length() && buffer.charAt(getCursorPosition() - 1) != trigger)) {
- buffer.insert(getCursorPosition(), trigger);
- setCursorPosition(getCursorPosition() + 1);
- }
-
- replacement= buffer.toString();
- setReplacementString(replacement);
- }
-
- // reference position just at the end of the document change.
- int referenceOffset= getReplacementOffset() + getReplacementLength();
- final ReferenceTracker referenceTracker= new ReferenceTracker();
- referenceTracker.preReplace(document, referenceOffset);
-
- replace(document, getReplacementOffset(), getReplacementLength(), replacement);
-
- referenceOffset= referenceTracker.postReplace(document);
- setReplacementOffset(referenceOffset - (replacement == null ? 0 : replacement.length()));
-
- // PR 47097
- if (isSmartTrigger)
- handleSmartTrigger(document, trigger, referenceOffset);
-
- } catch (BadLocationException x) {
- // ignore
- }
- }
-
-
- private boolean isSmartTrigger(char trigger) {
- return trigger == ';' && JavaScriptPlugin.getDefault().getCombinedPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)
- || trigger == '{' && JavaScriptPlugin.getDefault().getCombinedPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE);
- }
-
- private void handleSmartTrigger(IDocument document, char trigger, int referenceOffset) throws BadLocationException {
- DocumentCommand cmd= new DocumentCommand() {
- };
-
- cmd.offset= referenceOffset;
- cmd.length= 0;
- cmd.text= Character.toString(trigger);
- cmd.doit= true;
- cmd.shiftsCaret= true;
- cmd.caretOffset= getReplacementOffset() + getCursorPosition();
-
- SmartSemicolonAutoEditStrategy strategy= new SmartSemicolonAutoEditStrategy(IJavaScriptPartitions.JAVA_PARTITIONING);
- strategy.customizeDocumentCommand(document, cmd);
-
- replace(document, cmd.offset, cmd.length, cmd.text);
- setCursorPosition(cmd.caretOffset - getReplacementOffset() + cmd.text.length());
- }
-
- protected final void replace(IDocument document, int offset, int length, String string) throws BadLocationException {
- if (!document.get(offset, length).equals(string))
- document.replace(offset, length, string);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
-
- IDocument document= viewer.getDocument();
- if (fTextViewer == null)
- fTextViewer= viewer;
-
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96059
- // don't apply the proposal if for some reason we're not valid any longer
- if (!isInJavadoc() && !validate(document, offset, null)) {
- setCursorPosition(offset - getReplacementOffset());
- if (trigger != '\0') {
- try {
- document.replace(offset, 0, String.valueOf(trigger));
- setCursorPosition(getCursorPosition() + 1);
- if (trigger == '(' && autocloseBrackets()) {
- document.replace(getReplacementOffset() + getCursorPosition(), 0, ")"); //$NON-NLS-1$
- setUpLinkedMode(document, ')');
- }
- } catch (BadLocationException x) {
- // ignore
- }
- }
- return;
- }
-
- // don't eat if not in preferences, XOR with modifier key 1 (Ctrl)
- // but: if there is a selection, replace it!
- Point selection= viewer.getSelectedRange();
- fToggleEating= (stateMask & SWT.MOD1) != 0;
- int newLength= selection.x + selection.y - getReplacementOffset();
- if ((insertCompletion() ^ fToggleEating) && newLength >= 0)
- setReplacementLength(newLength);
-
- apply(document, trigger, offset);
- fToggleEating= false;
- }
-
- /**
- * Returns <code>true</code> if the proposal is within javadoc, <code>false</code>
- * otherwise.
- *
- * @return <code>true</code> if the proposal is within javadoc, <code>false</code> otherwise
- */
- protected boolean isInJavadoc(){
- return fIsInJavadoc;
- }
-
- /**
- * Sets the javadoc attribute.
- *
- * @param isInJavadoc <code>true</code> if the proposal is within javadoc
- */
- protected void setInJavadoc(boolean isInJavadoc) {
- fIsInJavadoc= isInJavadoc;
- }
-
- /*
- * @see ICompletionProposal#getSelection
- */
- public Point getSelection(IDocument document) {
- return new Point(getReplacementOffset() + getCursorPosition(), 0);
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return fContextInformation;
- }
-
- /**
- * Sets the context information.
- * @param contextInformation The context information associated with this proposal
- */
- public void setContextInformation(IContextInformation contextInformation) {
- fContextInformation= contextInformation;
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- return fDisplayString;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- Object info= getAdditionalProposalInfo(new NullProgressMonitor());
- return info == null ? (String) info : info.toString();
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension5#getAdditionalProposalInfo(org.eclipse.core.runtime.IProgressMonitor)
- */
- public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
- if (getProposalInfo() != null) {
- String info= getProposalInfo().getInfo(monitor);
- if (info != null && info.length() > 0) {
- StringBuffer buffer= new StringBuffer();
- HTMLPrinter.insertPageProlog(buffer, 0, getCSSStyles());
- buffer.append(info);
- HTMLPrinter.addPageEpilog(buffer);
- info= buffer.toString();
- }
- return info;
- }
- return null;
- }
-
- /**
- * Returns the style information for displaying HTML (Javadoc) content.
- *
- * @return the CSS styles
- *
- */
- protected String getCSSStyles() {
- if (fgCSSStyles == null) {
- Bundle bundle= Platform.getBundle(JavaScriptPlugin.getPluginId());
- URL url= bundle.getEntry("/JavadocHoverStyleSheet.css"); //$NON-NLS-1$
- if (url != null) {
- try {
- url= FileLocator.toFileURL(url);
- BufferedReader reader= new BufferedReader(new InputStreamReader(url.openStream()));
- StringBuffer buffer= new StringBuffer(200);
- String line= reader.readLine();
- while (line != null) {
- buffer.append(line);
- buffer.append('\n');
- line= reader.readLine();
- }
- fgCSSStyles= buffer.toString();
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
- }
- String css= fgCSSStyles;
- if (css != null) {
- FontData fontData= JFaceResources.getFontRegistry().getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
- css= HTMLPrinter.convertTopLevelFont(css, fontData);
- }
- return css;
- }
-
- /*
- * @see ICompletionProposalExtension#getContextInformationPosition()
- */
- public int getContextInformationPosition() {
- if (getContextInformation() == null)
- return getReplacementOffset() - 1;
- return getReplacementOffset() + getCursorPosition();
- }
-
- /**
- * Gets the replacement offset.
- * @return Returns a int
- */
- public int getReplacementOffset() {
- return fReplacementOffset;
- }
-
- /**
- * Sets the replacement offset.
- * @param replacementOffset The replacement offset to set
- */
- public void setReplacementOffset(int replacementOffset) {
- Assert.isTrue(replacementOffset >= 0);
- fReplacementOffset= replacementOffset;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getCompletionOffset()
- */
- public int getPrefixCompletionStart(IDocument document, int completionOffset) {
- return getReplacementOffset();
- }
-
- /**
- * Gets the replacement length.
- * @return Returns a int
- */
- public int getReplacementLength() {
- return fReplacementLength;
- }
-
- /**
- * Sets the replacement length.
- * @param replacementLength The replacementLength to set
- */
- public void setReplacementLength(int replacementLength) {
- Assert.isTrue(replacementLength >= 0);
- fReplacementLength= replacementLength;
- }
-
- /**
- * Gets the replacement string.
- * @return Returns a String
- */
- public String getReplacementString() {
- return fReplacementString;
- }
-
- /**
- * Sets the replacement string.
- * @param replacementString The replacement string to set
- */
- public void setReplacementString(String replacementString) {
- Assert.isNotNull(replacementString);
- fReplacementString= replacementString;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementText()
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- if (!isCamelCaseMatching())
- return getReplacementString();
-
- String prefix= getPrefix(document, completionOffset);
- return getCamelCaseCompound(prefix, getReplacementString());
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /**
- * Sets the image.
- * @param image The image to set
- */
- public void setImage(Image image) {
- fImage= image;
- }
-
- /*
- * @see ICompletionProposalExtension#isValidFor(IDocument, int)
- */
- public boolean isValidFor(IDocument document, int offset) {
- return validate(document, offset, null);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
-
- if (offset < getReplacementOffset())
- return false;
-
- boolean validated= isValidPrefix(getPrefix(document, offset));
-
- if (validated && event != null) {
- // adapt replacement range to document change
- int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength;
- final int newLength= Math.max(getReplacementLength() + delta, 0);
- setReplacementLength(newLength);
- }
-
- return validated;
- }
-
- /**
- * Checks whether <code>prefix</code> is a valid prefix for this proposal. Usually, while code
- * completion is in progress, the user types and edits the prefix in the document in order to
- * filter the proposal list. From {@link #validate(IDocument, int, DocumentEvent) }, the
- * current prefix in the document is extracted and this method is called to find out whether the
- * proposal is still valid.
- * <p>
- * The default implementation checks if <code>prefix</code> is a prefix of the proposal's
- * {@link #getDisplayString() display string} using the {@link #isPrefix(String, String) }
- * method.
- * </p>
- *
- * @param prefix the current prefix in the document
- * @return <code>true</code> if <code>prefix</code> is a valid prefix of this proposal
- */
- protected boolean isValidPrefix(String prefix) {
- /*
- * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667
- * why we do not use the replacement string.
- * String word= fReplacementString;
- */
- return isPrefix(prefix, getDisplayString());
- }
-
- /**
- * Gets the proposal's relevance.
- * @return Returns a int
- */
- public int getRelevance() {
- return fRelevance;
- }
-
- /**
- * Sets the proposal's relevance.
- * @param relevance The relevance to set
- */
- public void setRelevance(int relevance) {
- fRelevance= relevance;
- }
-
- /**
- * Returns the text in <code>document</code> from {@link #getReplacementOffset()} to
- * <code>offset</code>. Returns the empty string if <code>offset</code> is before the
- * replacement offset or if an exception occurs when accessing the document.
- *
- * @param document the document
- * @param offset the offset
- * @return the prefix
- *
- */
- protected String getPrefix(IDocument document, int offset) {
- try {
- int length= offset - getReplacementOffset();
- if (length > 0)
- return document.get(getReplacementOffset(), length);
- } catch (BadLocationException x) {
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Case insensitive comparison of <code>prefix</code> with the start of <code>string</code>.
- *
- * @param prefix the prefix
- * @param string the string to look for the prefix
- * @return <code>true</code> if the string begins with the given prefix and
- * <code>false</code> if <code>prefix</code> is longer than <code>string</code>
- * or the string doesn't start with the given prefix
- *
- */
- protected boolean isPrefix(String prefix, String string) {
- if (prefix == null || string ==null || prefix.length() > string.length())
- return false;
- String start= string.substring(0, prefix.length());
- return start.equalsIgnoreCase(prefix) || isCamelCaseMatching() && CharOperation.camelCaseMatch(prefix.toCharArray(), string.toCharArray());
- }
-
- /**
- * Matches <code>prefix</code> against <code>string</code> and replaces the matched region
- * by prefix. Case is preserved as much as possible. This method returns <code>string</code> if camel case completion
- * is disabled. Examples when camel case completion is enabled:
- * <ul>
- * <li>getCamelCompound("NuPo", "NullPointerException") -> "NuPointerException"</li>
- * <li>getCamelCompound("NuPoE", "NullPointerException") -> "NuPoException"</li>
- * <li>getCamelCompound("hasCod", "hashCode") -> "hasCode"</li>
- * </ul>
- *
- * @param prefix the prefix to match against
- * @param string the string to match
- * @return a compound of prefix and any postfix taken from <code>string</code>
- *
- */
- protected final String getCamelCaseCompound(String prefix, String string) {
- if (prefix.length() > string.length())
- return string;
-
- // a normal prefix - no camel case logic at all
- String start= string.substring(0, prefix.length());
- if (start.equalsIgnoreCase(prefix))
- return string;
-
- final char[] patternChars= prefix.toCharArray();
- final char[] stringChars= string.toCharArray();
-
- for (int i= 1; i <= stringChars.length; i++)
- if (CharOperation.camelCaseMatch(patternChars, 0, patternChars.length, stringChars, 0, i))
- return prefix + string.substring(i);
-
- // Not a camel case match at all.
- // This should not happen -> stay with the default behavior
- return string;
- }
-
- /**
- * Returns true if camel case matching is enabled.
- *
- * @return <code>true</code> if camel case matching is enabled
- *
- */
- protected boolean isCamelCaseMatching() {
- IJavaScriptProject project= getProject();
- String value;
- if (project == null)
- value= JavaScriptCore.getOption(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH);
- else
- value= project.getOption(JavaScriptCore.CODEASSIST_CAMEL_CASE_MATCH, true);
-
- return JavaScriptCore.ENABLED.equals(value);
- }
-
- private IJavaScriptProject getProject() {
- // TODO Auto-generated method stub
- return null;
- }
-
-
- private static boolean insertCompletion() {
- IPreferenceStore preference= JavaScriptPlugin.getDefault().getPreferenceStore();
- return preference.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION);
- }
-
- private static Color getForegroundColor(StyledText text) {
-
- IPreferenceStore preference= JavaScriptPlugin.getDefault().getPreferenceStore();
- RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND);
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- return textTools.getColorManager().getColor(rgb);
- }
-
- private static Color getBackgroundColor(StyledText text) {
-
- IPreferenceStore preference= JavaScriptPlugin.getDefault().getPreferenceStore();
- RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND);
- JavaScriptTextTools textTools= JavaScriptPlugin.getDefault().getJavaTextTools();
- return textTools.getColorManager().getColor(rgb);
- }
-
- private void repairPresentation(ITextViewer viewer) {
- if (fRememberedStyleRange != null) {
- if (viewer instanceof ITextViewerExtension2) {
- // attempts to reduce the redraw area
- ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer;
-
- if (viewer instanceof ITextViewerExtension5) {
-
- ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
- IRegion modelRange= extension.widgetRange2ModelRange(new Region(fRememberedStyleRange.start, fRememberedStyleRange.length));
- if (modelRange != null)
- viewer2.invalidateTextPresentation(modelRange.getOffset(), modelRange.getLength());
-
- } else {
- viewer2.invalidateTextPresentation(fRememberedStyleRange.start + viewer.getVisibleRegion().getOffset(), fRememberedStyleRange.length);
- }
-
- } else
- viewer.invalidateTextPresentation();
- }
- }
-
- private void updateStyle(ITextViewer viewer) {
-
- StyledText text= viewer.getTextWidget();
- if (text == null || text.isDisposed())
- return;
-
- int widgetCaret= text.getCaretOffset();
-
- int modelCaret= 0;
- if (viewer instanceof ITextViewerExtension5) {
- ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
- modelCaret= extension.widgetOffset2ModelOffset(widgetCaret);
- } else {
- IRegion visibleRegion= viewer.getVisibleRegion();
- modelCaret= widgetCaret + visibleRegion.getOffset();
- }
-
- if (modelCaret >= getReplacementOffset() + getReplacementLength()) {
- repairPresentation(viewer);
- return;
- }
-
- int offset= widgetCaret;
- int length= getReplacementOffset() + getReplacementLength() - modelCaret;
-
- Color foreground= getForegroundColor(text);
- Color background= getBackgroundColor(text);
-
- StyleRange range= text.getStyleRangeAtOffset(offset);
- int fontStyle= range != null ? range.fontStyle : SWT.NORMAL;
-
- repairPresentation(viewer);
- fRememberedStyleRange= new StyleRange(offset, length, foreground, background, fontStyle);
- if (range != null) {
- fRememberedStyleRange.strikeout= range.strikeout;
- fRememberedStyleRange.underline= range.underline;
- }
-
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=34754
- try {
- text.setStyleRange(fRememberedStyleRange);
- } catch (IllegalArgumentException x) {
- // catching exception as offset + length might be outside of the text widget
- fRememberedStyleRange= null;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean)
- */
- public void selected(ITextViewer viewer, boolean smartToggle) {
- if (!insertCompletion() ^ smartToggle)
- updateStyle(viewer);
- else {
- repairPresentation(viewer);
- fRememberedStyleRange= null;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer)
- */
- public void unselected(ITextViewer viewer) {
- repairPresentation(viewer);
- fRememberedStyleRange= null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator()
- */
- public IInformationControlCreator getInformationControlCreator() {
- Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- if (shell == null || !BrowserInformationControl.isAvailable(shell))
- return null;
-
- if (fCreator == null) {
- fCreator= new ControlCreator();
- }
- return fCreator;
- }
-
- public String getSortString() {
- return fSortString;
- }
-
- protected void setSortString(String string) {
- fSortString= string;
- }
-
- protected ITextViewer getTextViewer() {
- return fTextViewer;
- }
-
- protected boolean isToggleEating() {
- return fToggleEating;
- }
-
- /**
- * Sets up a simple linked mode at {@link #getCursorPosition()} and an exit policy that will
- * exit the mode when <code>closingCharacter</code> is typed and an exit position at
- * <code>getCursorPosition() + 1</code>.
- *
- * @param document the document
- * @param closingCharacter the exit character
- */
- protected void setUpLinkedMode(IDocument document, char closingCharacter) {
- if (getTextViewer() != null && autocloseBrackets()) {
- int offset= getReplacementOffset() + getCursorPosition();
- int exit= getReplacementOffset() + getReplacementString().length();
- try {
- LinkedPositionGroup group= new LinkedPositionGroup();
- group.addPosition(new LinkedPosition(document, offset, 0, LinkedPositionGroup.NO_STOP));
-
- LinkedModeModel model= new LinkedModeModel();
- model.addGroup(group);
- model.forceInstall();
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer());
- ui.setSimpleMode(true);
- ui.setExitPolicy(new ExitPolicy(closingCharacter, document));
- ui.setExitPosition(getTextViewer(), exit, 0, Integer.MAX_VALUE);
- ui.setCyclingMode(LinkedModeUI.CYCLE_NEVER);
- ui.enter();
- } catch (BadLocationException x) {
- JavaScriptPlugin.log(x);
- }
- }
- }
-
- protected boolean autocloseBrackets() {
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- return preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACKETS);
- }
-
- protected void setDisplayString(String string) {
- fDisplayString= string;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return getDisplayString();
- }
-
- /**
- * Returns the java element proposed by the receiver, possibly <code>null</code>.
- *
- * @return the java element proposed by the receiver, possibly <code>null</code>
- */
- public IJavaScriptElement getJavaElement() {
- if (getProposalInfo() != null)
- try {
- return getProposalInfo().getJavaElement();
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x);
- }
- return null;
- }
-
- /**
- * Tells whether required proposals are supported by this proposal.
- *
- * @return <code>true</code> if required proposals are supported by this proposal
- * @see CompletionProposal#getRequiredProposals()
- *
- */
- protected boolean isSupportingRequiredProposals() {
- if (fInvocationContext == null || !(fProposalInfo instanceof MemberProposalInfo))
- return false;
-
- CompletionProposal proposal= ((MemberProposalInfo)fProposalInfo).fProposal;
- return proposal != null && (proposal.getKind() == CompletionProposal.METHOD_REF || proposal.getKind() == CompletionProposal.FIELD_REF);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java
deleted file mode 100644
index 4f8b472a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.AbstractProposalSorter;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-/**
- * A alphabetic proposal based sorter.
- *
- *
- */
-public final class AlphabeticSorter extends AbstractProposalSorter {
-
- private final CompletionProposalComparator fComparator= new CompletionProposalComparator();
-
- public AlphabeticSorter() {
- fComparator.setOrderAlphabetically(true);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.AbstractProposalSorter#compare(org.eclipse.jface.text.contentassist.ICompletionProposal, org.eclipse.jface.text.contentassist.ICompletionProposal)
- */
- public int compare(ICompletionProposal p1, ICompletionProposal p2) {
- return fComparator.compare(p1, p2);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
deleted file mode 100644
index f2e59387..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OverrideMethodDialog;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-public class AnonymousTypeCompletionProposal extends JavaTypeCompletionProposal implements ICompletionProposalExtension4 {
-
- private String fDeclarationSignature;
- private IType fSuperType;
-
- public AnonymousTypeCompletionProposal(IJavaScriptProject jproject, IJavaScriptUnit cu, int start, int length, String constructorCompletion, String displayName, String declarationSignature, int relevance) {
- super(constructorCompletion, cu, start, length, null, displayName, relevance);
- Assert.isNotNull(declarationSignature);
- Assert.isNotNull(jproject);
- Assert.isNotNull(cu);
-
- fDeclarationSignature= declarationSignature;
- fSuperType= getDeclaringType(jproject, SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature)));
-
- setImage(getImageForType(fSuperType));
- setCursorPosition(constructorCompletion.indexOf('(') + 1);
- }
-
- private int createDummy(String name, StringBuffer buffer) throws JavaScriptModelException {
- String lineDelim= "\n"; // Using newline is ok since source is used in dummy compilation unit //$NON-NLS-1$
- buffer.append("class "); //$NON-NLS-1$
- buffer.append(name);
- buffer.append(" extends "); //$NON-NLS-1$
- if (fDeclarationSignature != null)
- buffer.append(Signature.toString(fDeclarationSignature));
- else
- buffer.append(fSuperType.getFullyQualifiedParameterizedName());
- int start= buffer.length();
- buffer.append("{"); //$NON-NLS-1$
- buffer.append(lineDelim);
- buffer.append(lineDelim);
- buffer.append("}"); //$NON-NLS-1$
- return start;
- }
-
- private boolean createStubs(StringBuffer buffer, ImportRewrite importRewrite) throws CoreException {
- if (importRewrite == null)
- return false;
- if (fSuperType == null)
- return true;
- IJavaScriptUnit copy= null;
- try {
- final String name= "Type" + System.currentTimeMillis(); //$NON-NLS-1$
- copy= fCompilationUnit.getPrimary().getWorkingCopy(null);
- final StringBuffer contents= new StringBuffer();
- int start= 0;
- int end= 0;
- ISourceRange range= fSuperType.getSourceRange();
- final boolean sameUnit= range != null && fCompilationUnit.equals(fSuperType.getJavaScriptUnit());
- final StringBuffer dummy= new StringBuffer();
- final int length= createDummy(name, dummy);
- contents.append(fCompilationUnit.getBuffer().getContents());
- if (sameUnit) {
- final int size= range.getOffset() + range.getLength();
- start= size + length;
- end= contents.length() - size;
- contents.insert(size, dummy.toString());
- } else {
- range= fCompilationUnit.getTypes()[0].getSourceRange();
- start= range.getOffset() + length;
- end= contents.length() - range.getOffset();
- contents.insert(range.getOffset(), dummy.toString());
- }
- copy.getBuffer().setContents(contents.toString());
- JavaModelUtil.reconcile(copy);
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setSource(copy);
- final JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(new NullProgressMonitor());
- IType type= null;
- IType[] types= copy.getAllTypes();
- for (int index= 0; index < types.length; index++) {
- IType result= types[index];
- if (result.getElementName().equals(name)) {
- type= result;
- break;
- }
- }
- if (type != null && type.exists()) {
- ITypeBinding binding= null;
- final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(unit, type.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null) {
- binding= declaration.resolveBinding();
- if (binding != null) {
- IFunctionBinding[] bindings= StubUtility2.getOverridableMethods(unit.getAST(), binding, true);
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fSuperType.getJavaScriptProject());
- String[] keys= null;
-
- OverrideMethodDialog dialog= new OverrideMethodDialog(JavaScriptPlugin.getActiveWorkbenchShell(), null, type, true);
- dialog.setGenerateComment(false);
- dialog.setElementPositionEnabled(false);
- if (dialog.open() == Window.OK) {
- Object[] selection= dialog.getResult();
- if (selection != null) {
- ArrayList result= new ArrayList(selection.length);
- for (int index= 0; index < selection.length; index++) {
- if (selection[index] instanceof IFunctionBinding)
- result.add(((IBinding) selection[index]).getKey());
- }
- keys= (String[]) result.toArray(new String[result.size()]);
- settings.createComments= dialog.getGenerateComment();
- }
- }
-
- if (keys == null) {
- setReplacementString(""); //$NON-NLS-1$
- setReplacementLength(0);
- return false;
- }
- ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
- ListRewrite rewriter= rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
- String key= null;
- FunctionDeclaration stub= null;
- for (int index= 0; index < keys.length; index++) {
- key= keys[index];
- for (int offset= 0; offset < bindings.length; offset++) {
- if (key.equals(bindings[offset].getKey())) {
- stub= StubUtility2.createImplementationStub(copy, rewrite, importRewrite, bindings[offset], binding.getName(), false, settings);
- if (stub != null)
- rewriter.insertFirst(stub, null);
- break;
- }
- }
- }
- IDocument document= new Document(copy.getBuffer().getContents());
- try {
- rewrite.rewriteAST(document, fCompilationUnit.getJavaScriptProject().getOptions(true)).apply(document, TextEdit.UPDATE_REGIONS);
- buffer.append(document.get(start, document.getLength() - start - end));
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- }
- }
- return true;
- } finally {
- if (copy != null)
- copy.discardWorkingCopy();
- }
- }
-
- private IType getDeclaringType(IJavaScriptProject project, String typeName) {
- try {
- return project.findType(typeName, (IProgressMonitor) null);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- private Image getImageForType(IType type) {
- String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
- return JavaPluginImages.get(imageName);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
- */
- public boolean isAutoInsertable() {
- return false;
- }
-
- protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
- String replacementString= getReplacementString();
-
- // construct replacement text: an expression to be formatted
- StringBuffer buf= new StringBuffer("new A("); //$NON-NLS-1$
- buf.append(replacementString);
-
- if (!replacementString.endsWith(")")) { //$NON-NLS-1$
- buf.append(')');
- }
-
- if (!createStubs(buf, impRewrite)) {
- return false;
- }
- if (document.getChar(offset) != ')')
- buf.append(';');
-
- // use the code formatter
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
- final IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
- int indent= Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project);
-
- String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, null, lineDelim, project);
- replacement= Strings.changeIndent(replacement, 0, project, CodeFormatterUtil.createIndentString(indent, project), lineDelim);
- setReplacementString(replacement.substring(replacement.indexOf('(') + 1));
-
- int pos= offset;
- while (pos < document.getLength() && Character.isWhitespace(document.getChar(pos))) {
- pos++;
- }
-
- if (pos < document.getLength() && document.getChar(pos) == ')') {
- setReplacementLength(pos - offset + 1);
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeProposalInfo.java
deleted file mode 100644
index bdefad44..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AnonymousTypeProposalInfo.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-
-
-/**
- * Proposal info that computes the javadoc lazily when it is queried.
- *
- *
- */
-public final class AnonymousTypeProposalInfo extends MemberProposalInfo {
-
- /**
- * Creates a new proposal info.
- *
- * @param project the java project to reference when resolving types
- * @param proposal the proposal to generate information for
- */
- public AnonymousTypeProposalInfo(IJavaScriptProject project, CompletionProposal proposal) {
- super(project, proposal);
- }
-
- /**
- * Resolves the member described by the receiver and returns it if found.
- * Returns <code>null</code> if no corresponding member can be found.
- *
- * @return the resolved member or <code>null</code> if none is found
- * @throws JavaScriptModelException if accessing the java model fails
- */
- protected IMember resolveMember() throws JavaScriptModelException {
- char[] signature= fProposal.getDeclarationSignature();
- String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(signature));
- return fJavaProject.findType(typeName);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalCategory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalCategory.java
deleted file mode 100644
index 3f839e14..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalCategory.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.InvalidRegistryObjectException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.action.LegacyActionTools;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.osgi.framework.Bundle;
-
-/**
- * Describes a category extension to the "javaCompletionProposalComputer" extension point.
- *
- *
- */
-public final class CompletionProposalCategory {
- /** The extension schema name of the icon attribute. */
- private static final String ICON= "icon"; //$NON-NLS-1$
-
- private final String fId;
- private final String fName;
- private final IConfigurationElement fElement;
- /** The image descriptor for this category, or <code>null</code> if none specified. */
- private final ImageDescriptor fImage;
-
- private boolean fIsSeparateCommand= true;
- private boolean fIsEnabled= true;
- private boolean fIsIncluded= true;
- private final CompletionProposalComputerRegistry fRegistry;
-
- private int fSortOrder= 0x10000;
- private String fLastError= null;
-
- CompletionProposalCategory(IConfigurationElement element, CompletionProposalComputerRegistry registry) {
- fElement= element;
- fRegistry= registry;
- IExtension parent= (IExtension) element.getParent();
- fId= parent.getUniqueIdentifier();
- checkNotNull(fId, "id"); //$NON-NLS-1$
- String name= parent.getLabel();
- if (name == null)
- fName= fId;
- else
- fName= name;
-
- String icon= element.getAttribute(ICON);
- ImageDescriptor img= null;
- if (icon != null) {
- Bundle bundle= getBundle();
- if (bundle != null) {
- Path path= new Path(icon);
- URL url= FileLocator.find(bundle, path, null);
- img= ImageDescriptor.createFromURL(url);
- }
- }
- fImage= img;
-
- }
-
- CompletionProposalCategory(String id, String name, CompletionProposalComputerRegistry registry) {
- fRegistry= registry;
- fId= id;
- fName= name;
- fElement= null;
- fImage= null;
- }
-
- private Bundle getBundle() {
- String namespace= fElement.getDeclaringExtension().getContributor().getName();
- Bundle bundle= Platform.getBundle(namespace);
- return bundle;
- }
-
- /**
- * Checks an element that must be defined according to the extension
- * point schema. Throws an
- * <code>InvalidRegistryObjectException</code> if <code>obj</code>
- * is <code>null</code>.
- */
- private void checkNotNull(Object obj, String attribute) throws InvalidRegistryObjectException {
- if (obj == null) {
- Object[] args= { getId(), fElement.getContributor().getName(), attribute };
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_illegal_attribute_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null);
- JavaScriptPlugin.log(status);
- throw new InvalidRegistryObjectException();
- }
- }
-
- /**
- * Returns the identifier of the described extension.
- *
- * @return Returns the id
- */
- public String getId() {
- return fId;
- }
-
- /**
- * Returns the name of the described extension.
- *
- * @return Returns the name
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Returns the name of the described extension
- * without mnemonic hint in order to be displayed
- * in a message.
- *
- * @return Returns the name
- */
- public String getDisplayName() {
- return LegacyActionTools.removeMnemonics(fName);
- }
-
- /**
- * Returns the image descriptor of the described category.
- *
- * @return the image descriptor of the described category
- */
- public ImageDescriptor getImageDescriptor() {
- return fImage;
- }
-
- /**
- * Sets the separate command state of the category.
- *
- * @param enabled the new enabled state.
- */
- public void setSeparateCommand(boolean enabled) {
- fIsSeparateCommand= enabled;
- }
-
- /**
- * Returns the enablement state of the category.
- *
- * @return the enablement state of the category
- */
- public boolean isSeparateCommand() {
- return fIsSeparateCommand;
- }
-
- /**
- * @param included the included
- */
- public void setIncluded(boolean included) {
- fIsIncluded= included;
- }
-
- /**
- * @return included
- */
- public boolean isIncluded() {
- return fIsIncluded;
- }
-
- public boolean isEnabled() {
- return fIsEnabled;
- }
-
- public void setEnabled(boolean isEnabled) {
- fIsEnabled= isEnabled;
- }
-
- /**
- * Returns <code>true</code> if the category contains any computers, <code>false</code>
- * otherwise.
- *
- * @return <code>true</code> if the category contains any computers, <code>false</code>
- * otherwise
- */
- public boolean hasComputers() {
- List descriptors= fRegistry.getProposalComputerDescriptors();
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- return true;
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if the category contains any computers in the given partition, <code>false</code>
- * otherwise.
- *
- * @param partition the partition
- * @return <code>true</code> if the category contains any computers, <code>false</code>
- * otherwise
- */
- public boolean hasComputers(String partition) {
- List descriptors= fRegistry.getProposalComputerDescriptors(partition);
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- return true;
- }
- return false;
- }
-
- /**
- * @return sortOrder
- */
- public int getSortOrder() {
- return fSortOrder;
- }
-
- /**
- * @param sortOrder the sortOrder
- */
- public void setSortOrder(int sortOrder) {
- fSortOrder= sortOrder;
- }
-
- /**
- * Safely computes completion proposals of all computers of this category through their
- * extension. If an extension is disabled, throws an exception or otherwise does not adhere to
- * the contract described in {@link org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer}, it is disabled.
- *
- * @param context the invocation context passed on to the extension
- * @param partition the partition type where to invocation occurred
- * @param monitor the progress monitor passed on to the extension
- * @return the list of computed completion proposals (element type:
- * {@link org.eclipse.jface.text.contentassist.ICompletionProposal})
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) {
- fLastError= null;
- List result= new ArrayList();
- List descriptors= new ArrayList(fRegistry.getProposalComputerDescriptors(partition));
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- result.addAll(desc.computeCompletionProposals(context, monitor));
- if (fLastError == null)
- fLastError= desc.getErrorMessage();
- }
- return result;
- }
-
- /**
- * Safely computes context information objects of all computers of this category through their
- * extension. If an extension is disabled, throws an exception or otherwise does not adhere to
- * the contract described in {@link org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer}, it is disabled.
- *
- * @param context the invocation context passed on to the extension
- * @param partition the partition type where to invocation occurred
- * @param monitor the progress monitor passed on to the extension
- * @return the list of computed context information objects (element type:
- * {@link org.eclipse.jface.text.contentassist.IContextInformation})
- */
- public List computeContextInformation(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) {
- fLastError= null;
- List result= new ArrayList();
- List descriptors= new ArrayList(fRegistry.getProposalComputerDescriptors(partition));
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- result.addAll(desc.computeContextInformation(context, monitor));
- if (fLastError == null)
- fLastError= desc.getErrorMessage();
- }
- return result;
- }
-
- /**
- * Returns the error message from the computers in this category.
- *
- * @return the error message from the computers in this category
- */
- public String getErrorMessage() {
- return fLastError;
- }
-
- /**
- * Notifies the computers in this category of a proposal computation session start.
- */
- public void sessionStarted() {
- List descriptors= new ArrayList(fRegistry.getProposalComputerDescriptors());
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- desc.sessionStarted();
- if (fLastError == null)
- fLastError= desc.getErrorMessage();
- }
- }
-
- /**
- * Notifies the computers in this category of a proposal computation session end.
- */
- public void sessionEnded() {
- List descriptors= new ArrayList(fRegistry.getProposalComputerDescriptors());
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- if (desc.getCategory() == this)
- desc.sessionEnded();
- if (fLastError == null)
- fLastError= desc.getErrorMessage();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java
deleted file mode 100644
index f2b1b439..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java
+++ /dev/null
@@ -1,547 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IContributor;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.InvalidRegistryObjectException;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.osgi.framework.Bundle;
-
-/**
- * The description of an extension to the
- * <code>org.eclipse.wst.jsdt.ui.javaCompletionProposalComputer</code> extension point. Instances are
- * immutable. Instances can be obtained from a {@link CompletionProposalComputerRegistry}.
- *
- * @see CompletionProposalComputerRegistry
- *
- */
-final class CompletionProposalComputerDescriptor {
- /** The default category id. */
- private static final String DEFAULT_CATEGORY_ID= "org.eclipse.wst.jsdt.ui.defaultProposalCategory"; //$NON-NLS-1$
- /** The extension schema name of the category id attribute. */
- private static final String CATEGORY_ID= "categoryId"; //$NON-NLS-1$
- /** The extension schema name of the partition type attribute. */
- private static final String TYPE= "type"; //$NON-NLS-1$
- /** The extension schema name of the class attribute. */
- private static final String CLASS= "class"; //$NON-NLS-1$
- /** The extension schema name of the activate attribute. */
- private static final String ACTIVATE= "activate"; //$NON-NLS-1$
- /** The extension schema name of the partition child elements. */
- private static final String PARTITION= "partition"; //$NON-NLS-1$
- /** Set of Java partition types. */
- private static final Set PARTITION_SET;
- /** The name of the performance event used to trace extensions. */
- private static final String PERFORMANCE_EVENT= JavaScriptPlugin.getPluginId() + "/perf/content_assist/extensions"; //$NON-NLS-1$
- /**
- * If <code>true</code>, execution time of extensions is measured and the data forwarded to
- * core's {@link PerformanceStats} service.
- */
- private static final boolean MEASURE_PERFORMANCE= PerformanceStats.isEnabled(PERFORMANCE_EVENT);
- /**
- * Independently of the {@link PerformanceStats} service, any operation that takes longer than
- * {@value} milliseconds will be flagged as an violation. This timeout does not apply to the
- * first invocation, as it may take longer due to plug-in initialization etc. See also
- * {@link #fIsReportingDelay}.
- */
- private static final long MAX_DELAY= 5000;
-
- /* log constants */
- private static final String COMPUTE_COMPLETION_PROPOSALS= "computeCompletionProposals()"; //$NON-NLS-1$
- private static final String COMPUTE_CONTEXT_INFORMATION= "computeContextInformation()"; //$NON-NLS-1$
- private static final String SESSION_STARTED= "sessionStarted()"; //$NON-NLS-1$
- private static final String SESSION_ENDED= "sessionEnded()"; //$NON-NLS-1$
-
- static {
- Set partitions= new HashSet();
- partitions.add(IDocument.DEFAULT_CONTENT_TYPE);
- partitions.add(IJavaScriptPartitions.JAVA_DOC);
- partitions.add(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- partitions.add(IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- partitions.add(IJavaScriptPartitions.JAVA_STRING);
- partitions.add(IJavaScriptPartitions.JAVA_CHARACTER);
-
- PARTITION_SET= Collections.unmodifiableSet(partitions);
- }
-
- /** The identifier of the extension. */
- private final String fId;
- /** The name of the extension. */
- private final String fName;
- /** The class name of the provided <code>IJavaCompletionProposalComputer</code>. */
- private final String fClass;
- /** The activate attribute value. */
- private final boolean fActivate;
- /** The partition of the extension (element type: {@link String}). */
- private final Set fPartitions;
- /** The configuration element of this extension. */
- private final IConfigurationElement fElement;
- /** The registry we are registered with. */
- private final CompletionProposalComputerRegistry fRegistry;
- /** The computer, if instantiated, <code>null</code> otherwise. */
- private IJavaCompletionProposalComputer fComputer;
- /** The ui category. */
- private final CompletionProposalCategory fCategory;
- /** The first error message in the most recent operation, or <code>null</code>. */
- private String fLastError;
- /**
- * Tells whether to inform the user when <code>MAX_DELAY</code> has been exceeded.
- * We start timing execution after the first session because the first may take
- * longer due to plug-in activation and initialization.
- */
- private boolean fIsReportingDelay= false;
- /** The start of the last operation. */
- private long fStart;
-
- /**
- * Creates a new descriptor.
- *
- * @param element the configuration element to read
- * @param registry the computer registry creating this descriptor
- */
- CompletionProposalComputerDescriptor(IConfigurationElement element, CompletionProposalComputerRegistry registry, List categories) throws InvalidRegistryObjectException {
- Assert.isLegal(registry != null);
- Assert.isLegal(element != null);
-
- fRegistry= registry;
- fElement= element;
- IExtension extension= element.getDeclaringExtension();
- fId= extension.getUniqueIdentifier();
- checkNotNull(fId, "id"); //$NON-NLS-1$
-
- String name= extension.getLabel();
- if (name.length() == 0)
- fName= fId;
- else
- fName= name;
-
- Set partitions= new HashSet();
- IConfigurationElement[] children= element.getChildren(PARTITION);
- if (children.length == 0) {
- fPartitions= PARTITION_SET; // add to all partition types if no partition is configured
- } else {
- for (int i= 0; i < children.length; i++) {
- String type= children[i].getAttribute(TYPE);
- checkNotNull(type, TYPE);
- partitions.add(type);
- }
- fPartitions= Collections.unmodifiableSet(partitions);
- }
-
- String activateAttribute= element.getAttribute(ACTIVATE);
- fActivate= Boolean.valueOf(activateAttribute).booleanValue();
-
- fClass= element.getAttribute(CLASS);
- checkNotNull(fClass, CLASS);
-
- String categoryId= element.getAttribute(CATEGORY_ID);
- if (categoryId == null)
- categoryId= DEFAULT_CATEGORY_ID;
- CompletionProposalCategory category= null;
- for (Iterator it= categories.iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- if (cat.getId().equals(categoryId)) {
- category= cat;
- break;
- }
- }
- if (category == null) {
- // create a category if it does not exist
- fCategory= new CompletionProposalCategory(categoryId, fName, registry);
- categories.add(fCategory);
- } else {
- fCategory= category;
- }
- }
-
- /**
- * Checks an element that must be defined according to the extension
- * point schema. Throws an
- * <code>InvalidRegistryObjectException</code> if <code>obj</code>
- * is <code>null</code>.
- */
- private void checkNotNull(Object obj, String attribute) throws InvalidRegistryObjectException {
- if (obj == null) {
- Object[] args= { getId(), fElement.getContributor().getName(), attribute };
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_illegal_attribute_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null);
- JavaScriptPlugin.log(status);
- throw new InvalidRegistryObjectException();
- }
- }
-
- /**
- * Returns the identifier of the described extension.
- *
- * @return Returns the id
- */
- public String getId() {
- return fId;
- }
-
- /**
- * Returns the name of the described extension.
- *
- * @return Returns the name
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Returns the partition types of the described extension.
- *
- * @return the set of partition types (element type: {@link String})
- */
- public Set getPartitions() {
- return fPartitions;
- }
-
- /**
- * Returns a cached instance of the computer as described in the
- * extension's xml. The computer is
- * {@link #createComputer() created} the first time that this method
- * is called and then cached.
- *
- * @return a new instance of the completion proposal computer as
- * described by this descriptor
- * @throws CoreException if the creation fails
- * @throws InvalidRegistryObjectException if the extension is not
- * valid any longer (e.g. due to plug-in unloading)
- */
- private synchronized IJavaCompletionProposalComputer getComputer() throws CoreException, InvalidRegistryObjectException {
- if (fComputer == null && (fActivate || isPluginLoaded()))
- fComputer= createComputer();
- return fComputer;
- }
-
- private boolean isPluginLoaded() {
- Bundle bundle= getBundle();
- return bundle != null && bundle.getState() == Bundle.ACTIVE;
- }
-
- private Bundle getBundle() {
- String namespace= fElement.getDeclaringExtension().getContributor().getName();
- Bundle bundle= Platform.getBundle(namespace);
- return bundle;
- }
-
- /**
- * Returns a new instance of the computer as described in the
- * extension's xml. Note that the safest way to access the computer
- * is by using the
- * {@linkplain #computeCompletionProposals(ContentAssistInvocationContext, IProgressMonitor) computeCompletionProposals}
- * and
- * {@linkplain #computeContextInformation(ContentAssistInvocationContext, IProgressMonitor) computeContextInformation}
- * methods. These delegate the functionality to the contributed
- * computer, but handle instance creation and any exceptions thrown.
- *
- * @return a new instance of the completion proposal computer as
- * described by this descriptor
- * @throws CoreException if the creation fails
- * @throws InvalidRegistryObjectException if the extension is not
- * valid any longer (e.g. due to plug-in unloading)
- */
- public IJavaCompletionProposalComputer createComputer() throws CoreException, InvalidRegistryObjectException {
- return (IJavaCompletionProposalComputer) fElement.createExecutableExtension(CLASS);
- }
-
- /**
- * Safely computes completion proposals through the described extension. If the extension
- * is disabled, throws an exception or otherwise does not adhere to the contract described in
- * {@link IJavaCompletionProposalComputer}, an empty list is returned.
- *
- * @param context the invocation context passed on to the extension
- * @param monitor the progress monitor passed on to the extension
- * @return the list of computed completion proposals (element type:
- * {@link org.eclipse.jface.text.contentassist.ICompletionProposal})
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (!isEnabled())
- return Collections.EMPTY_LIST;
-
- IStatus status;
- try {
- IJavaCompletionProposalComputer computer= getComputer();
- if (computer == null) // not active yet
- return Collections.EMPTY_LIST;
-
- try {
- PerformanceStats stats= startMeter(context, computer);
- List proposals= computer.computeCompletionProposals(context, monitor);
- stopMeter(stats, COMPUTE_COMPLETION_PROPOSALS);
-
- if (proposals != null) {
- fLastError= computer.getErrorMessage();
- return proposals;
- }
- } finally {
- fIsReportingDelay= true;
- }
- status= createAPIViolationStatus(COMPUTE_COMPLETION_PROPOSALS);
- } catch (InvalidRegistryObjectException x) {
- status= createExceptionStatus(x);
- } catch (CoreException x) {
- status= createExceptionStatus(x);
- } catch (RuntimeException x) {
- status= createExceptionStatus(x);
- } finally {
- monitor.done();
- }
-
- fRegistry.informUser(this, status);
-
- return Collections.EMPTY_LIST;
- }
-
- /**
- * Safely computes context information objects through the described extension. If the extension
- * is disabled, throws an exception or otherwise does not adhere to the contract described in
- * {@link IJavaCompletionProposalComputer}, an empty list is returned.
- *
- * @param context the invocation context passed on to the extension
- * @param monitor the progress monitor passed on to the extension
- * @return the list of computed context information objects (element type:
- * {@link org.eclipse.jface.text.contentassist.IContextInformation})
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (!isEnabled())
- return Collections.EMPTY_LIST;
-
- IStatus status;
- try {
- IJavaCompletionProposalComputer computer= getComputer();
- if (computer == null) // not active yet
- return Collections.EMPTY_LIST;
-
- PerformanceStats stats= startMeter(context, computer);
- List proposals= computer.computeContextInformation(context, monitor);
- stopMeter(stats, COMPUTE_CONTEXT_INFORMATION);
-
- if (proposals != null) {
- fLastError= computer.getErrorMessage();
- return proposals;
- }
-
- status= createAPIViolationStatus(COMPUTE_CONTEXT_INFORMATION);
- } catch (InvalidRegistryObjectException x) {
- status= createExceptionStatus(x);
- } catch (CoreException x) {
- status= createExceptionStatus(x);
- } catch (RuntimeException x) {
- status= createExceptionStatus(x);
- } finally {
- monitor.done();
- }
-
- fRegistry.informUser(this, status);
-
- return Collections.EMPTY_LIST;
- }
-
-
- /**
- * Notifies the described extension of a proposal computation session start.
- * <p><em>
- * Note: This method is called every time code assist is invoked and
- * is <strong>not</strong> filtered by partition type.
- * </em></p>
- */
- public void sessionStarted() {
- if (!isEnabled())
- return;
-
- IStatus status;
- try {
- IJavaCompletionProposalComputer computer= getComputer();
- if (computer == null) // not active yet
- return;
-
- PerformanceStats stats= startMeter(SESSION_STARTED, computer);
- computer.sessionStarted();
- stopMeter(stats, SESSION_ENDED);
-
- return;
- } catch (InvalidRegistryObjectException x) {
- status= createExceptionStatus(x);
- } catch (CoreException x) {
- status= createExceptionStatus(x);
- } catch (RuntimeException x) {
- status= createExceptionStatus(x);
- }
-
- fRegistry.informUser(this, status);
- }
-
- /**
- * Notifies the described extension of a proposal computation session end.
- * <p><em>
- * Note: This method is called every time code assist is invoked and
- * is <strong>not</strong> filtered by partition type.
- * </em></p>
- */
- public void sessionEnded() {
- if (!isEnabled())
- return;
-
- IStatus status;
- try {
- IJavaCompletionProposalComputer computer= getComputer();
- if (computer == null) // not active yet
- return;
-
- PerformanceStats stats= startMeter(SESSION_ENDED, computer);
- computer.sessionEnded();
- stopMeter(stats, SESSION_ENDED);
-
- return;
- } catch (InvalidRegistryObjectException x) {
- status= createExceptionStatus(x);
- } catch (CoreException x) {
- status= createExceptionStatus(x);
- } catch (RuntimeException x) {
- status= createExceptionStatus(x);
- }
-
- fRegistry.informUser(this, status);
- }
-
- private PerformanceStats startMeter(Object context, IJavaCompletionProposalComputer computer) {
- final PerformanceStats stats;
- if (MEASURE_PERFORMANCE) {
- stats= PerformanceStats.getStats(PERFORMANCE_EVENT, computer);
- stats.startRun(context.toString());
- } else {
- stats= null;
- }
-
- if (fIsReportingDelay) {
- fStart= System.currentTimeMillis();
- }
-
- return stats;
- }
-
- private void stopMeter(final PerformanceStats stats, String operation) {
- if (MEASURE_PERFORMANCE) {
- stats.endRun();
- if (stats.isFailure()) {
- IStatus status= createPerformanceStatus(operation);
- fRegistry.informUser(this, status);
- return;
- }
- }
-
- if (fIsReportingDelay) {
- long current= System.currentTimeMillis();
- if (current - fStart > MAX_DELAY) {
- IStatus status= createPerformanceStatus(operation);
- fRegistry.informUser(this, status);
- }
- }
- }
-
- private IStatus createExceptionStatus(InvalidRegistryObjectException x) {
- // extension has become invalid - log & disable
- String blame= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_invalid;
- return new Status(IStatus.INFO, JavaScriptPlugin.getPluginId(), IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$
- }
-
- private IStatus createExceptionStatus(CoreException x) {
- // unable to instantiate the extension - log & disable
- String blame= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_instantiation;
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$
- }
-
- private IStatus createExceptionStatus(RuntimeException x) {
- // misbehaving extension - log & disable
- String blame= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_runtime_ex;
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$
- }
-
- private IStatus createAPIViolationStatus(String operation) {
- String blame= createBlameMessage();
- Object[] args= {operation};
- String reason= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_reason_API, args);
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, blame + " " + reason, null); //$NON-NLS-1$
- }
-
- private IStatus createPerformanceStatus(String operation) {
- String blame= createBlameMessage();
- Object[] args= {operation};
- String reason= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_reason_performance, args);
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, blame + " " + reason, null); //$NON-NLS-1$
- }
-
- private String createBlameMessage() {
- Object[] args= { getName(), fElement.getDeclaringExtension().getContributor().getName() };
- String disable= Messages.format( JavaTextMessages.CompletionProposalComputerDescriptor_blame_message, args);
- return disable;
- }
-
- /**
- * Returns the enablement state of the described extension.
- *
- * @return the enablement state of the described extension
- */
- private boolean isEnabled() {
- return fCategory.isEnabled();
- }
-
- CompletionProposalCategory getCategory() {
- return fCategory;
- }
-
- /**
- * Returns the error message from the described extension.
- *
- * @return the error message from the described extension
- */
- public String getErrorMessage() {
- return fLastError;
- }
-
- /**
- * Returns the contributor of the described extension.
- *
- * @return the contributor of the described extension
- */
- IContributor getContributor() {
- try {
- return fElement.getContributor();
- } catch (InvalidRegistryObjectException e) {
- return null;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java
deleted file mode 100644
index d400768e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IContributor;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.InvalidRegistryObjectException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * A registry for all extensions to the
- * <code>org.eclipse.wst.jsdt.ui.javaCompletionProposalComputer</code>
- * extension point.
- *
- *
- */
-public final class CompletionProposalComputerRegistry {
-
- private static final String EXTENSION_POINT= "javaCompletionProposalComputer"; //$NON-NLS-1$
-
- /** The singleton instance. */
- private static CompletionProposalComputerRegistry fgSingleton= null;
-
- /**
- * Returns the default computer registry.
- * <p>
- * TODO keep this or add some other singleton, e.g. JavaScriptPlugin?
- * </p>
- *
- * @return the singleton instance
- */
- public static synchronized CompletionProposalComputerRegistry getDefault() {
- if (fgSingleton == null) {
- fgSingleton= new CompletionProposalComputerRegistry();
- }
-
- return fgSingleton;
- }
-
- /**
- * The sets of descriptors, grouped by partition type (key type:
- * {@link String}, value type:
- * {@linkplain List List&lt;CompletionProposalComputerDescriptor&gt;}).
- */
- private final Map fDescriptorsByPartition= new HashMap();
- /**
- * Unmodifiable versions of the sets stored in
- * <code>fDescriptorsByPartition</code> (key type: {@link String},
- * value type:
- * {@linkplain List List&lt;CompletionProposalComputerDescriptor&gt;}).
- */
- private final Map fPublicDescriptorsByPartition= new HashMap();
- /**
- * All descriptors (element type:
- * {@link CompletionProposalComputerDescriptor}).
- */
- private final List fDescriptors= new ArrayList();
- /**
- * Unmodifiable view of <code>fDescriptors</code>
- */
- private final List fPublicDescriptors= Collections.unmodifiableList(fDescriptors);
-
- private final List fCategories= new ArrayList();
- private final List fPublicCategories= Collections.unmodifiableList(fCategories);
- /**
- * <code>true</code> if this registry has been loaded.
- */
- private boolean fLoaded= false;
-
- /**
- * Creates a new instance.
- */
- public CompletionProposalComputerRegistry() {
- }
-
- /**
- * Returns the list of {@link CompletionProposalComputerDescriptor}s describing all extensions
- * to the <code>javaCompletionProposalComputer</code> extension point for the given partition
- * type.
- * <p>
- * A valid partition is either one of the constants defined in
- * {@link org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions} or
- * {@link org.eclipse.jface.text.IDocument#DEFAULT_CONTENT_TYPE}. An empty list is returned if
- * there are no extensions for the given partition.
- * </p>
- * <p>
- * The returned list is read-only and is sorted in the order that the extensions were read in.
- * There are no duplicate elements in the returned list. The returned list may change if plug-ins
- * are loaded or unloaded while the application is running or if an extension violates the API
- * contract of {@link org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer}. When
- * computing proposals, it is therefore imperative to copy the returned list before iterating
- * over it.
- * </p>
- *
- * @param partition
- * the partition type for which to retrieve the computer descriptors
- * @return the list of extensions to the <code>javaCompletionProposalComputer</code> extension
- * point (element type: {@link CompletionProposalComputerDescriptor})
- */
- List getProposalComputerDescriptors(String partition) {
- ensureExtensionPointRead();
- List result= (List) fPublicDescriptorsByPartition.get(partition);
- return result != null ? result : Collections.EMPTY_LIST;
- }
-
- /**
- * Returns the list of {@link CompletionProposalComputerDescriptor}s describing all extensions
- * to the <code>javaCompletionProposalComputer</code> extension point.
- * <p>
- * The returned list is read-only and is sorted in the order that the extensions were read in.
- * There are no duplicate elements in the returned list. The returned list may change if plug-ins
- * are loaded or unloaded while the application is running or if an extension violates the API
- * contract of {@link org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer}. When
- * computing proposals, it is therefore imperative to copy the returned list before iterating
- * over it.
- * </p>
- *
- * @return the list of extensions to the <code>javaCompletionProposalComputer</code> extension
- * point (element type: {@link CompletionProposalComputerDescriptor})
- */
- List getProposalComputerDescriptors() {
- ensureExtensionPointRead();
- return fPublicDescriptors;
- }
-
- /**
- * Returns the list of proposal categories contributed to the
- * <code>javaCompletionProposalComputer</code> extension point.
- * <p>
- * <p>
- * The returned list is read-only and is sorted in the order that the extensions were read in.
- * There are no duplicate elements in the returned list. The returned list may change if
- * plug-ins are loaded or unloaded while the application is running.
- * </p>
- *
- * @return list of proposal categories contributed to the
- * <code>javaCompletionProposalComputer</code> extension point (element type:
- * {@link CompletionProposalCategory})
- */
- public List getProposalCategories() {
- ensureExtensionPointRead();
- return fPublicCategories;
- }
-
- /**
- * Ensures that the extensions are read and stored in
- * <code>fDescriptorsByPartition</code>.
- */
- private void ensureExtensionPointRead() {
- boolean reload;
- synchronized (this) {
- reload= !fLoaded;
- fLoaded= true;
- }
- if (reload)
- reload();
- }
-
- /**
- * Reloads the extensions to the extension point.
- * <p>
- * This method can be called more than once in order to reload from
- * a changed extension registry.
- * </p>
- */
- public void reload() {
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- List elements= new ArrayList(Arrays.asList(registry.getConfigurationElementsFor(JavaScriptPlugin.getPluginId(), EXTENSION_POINT)));
-
- Map map= new HashMap();
- List all= new ArrayList();
-
- List categories= getCategories(elements);
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- IConfigurationElement element= (IConfigurationElement) iter.next();
- try {
- CompletionProposalComputerDescriptor desc= new CompletionProposalComputerDescriptor(element, this, categories);
- Set partitions= desc.getPartitions();
- for (Iterator it= partitions.iterator(); it.hasNext();) {
- String partition= (String) it.next();
- List list= (List) map.get(partition);
- if (list == null) {
- list= new ArrayList();
- map.put(partition, list);
- }
- list.add(desc);
- }
- all.add(desc);
-
- } catch (InvalidRegistryObjectException x) {
- /*
- * Element is not valid any longer as the contributing plug-in was unloaded or for
- * some other reason. Do not include the extension in the list and inform the user
- * about it.
- */
- Object[] args= {element.toString()};
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_invalid_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, x);
- informUser(status);
- }
- }
-
- synchronized (this) {
- fCategories.clear();
- fCategories.addAll(categories);
-
- Set partitions= map.keySet();
- fDescriptorsByPartition.keySet().retainAll(partitions);
- fPublicDescriptorsByPartition.keySet().retainAll(partitions);
- for (Iterator it= partitions.iterator(); it.hasNext();) {
- String partition= (String) it.next();
- List old= (List) fDescriptorsByPartition.get(partition);
- List current= (List) map.get(partition);
- if (old != null) {
- old.clear();
- old.addAll(current);
- } else {
- fDescriptorsByPartition.put(partition, current);
- fPublicDescriptorsByPartition.put(partition, Collections.unmodifiableList(current));
- }
- }
-
- fDescriptors.clear();
- fDescriptors.addAll(all);
- }
- }
-
- private List getCategories(List elements) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- String preference= store.getString(PreferenceConstants.CODEASSIST_EXCLUDED_CATEGORIES);
- Set disabled= new HashSet();
- StringTokenizer tok= new StringTokenizer(preference, "\0"); //$NON-NLS-1$
- while (tok.hasMoreTokens())
- disabled.add(tok.nextToken());
- Map ordered= new HashMap();
- preference= store.getString(PreferenceConstants.CODEASSIST_CATEGORY_ORDER);
- tok= new StringTokenizer(preference, "\0"); //$NON-NLS-1$
- while (tok.hasMoreTokens()) {
- StringTokenizer inner= new StringTokenizer(tok.nextToken(), ":"); //$NON-NLS-1$
- String id= inner.nextToken();
- int rank= Integer.parseInt(inner.nextToken());
- ordered.put(id, new Integer(rank));
- }
-
- List categories= new ArrayList();
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- IConfigurationElement element= (IConfigurationElement) iter.next();
- try {
- if (element.getName().equals("proposalCategory")) { //$NON-NLS-1$
- iter.remove(); // remove from list to leave only computers
-
- CompletionProposalCategory category= new CompletionProposalCategory(element, this);
- categories.add(category);
- category.setIncluded(!disabled.contains(category.getId()));
- Integer rank= (Integer) ordered.get(category.getId());
- if (rank != null) {
- int r= rank.intValue();
- boolean separate= r < 0xffff;
- category.setSeparateCommand(separate);
- category.setSortOrder(r);
- }
- }
- } catch (InvalidRegistryObjectException x) {
- /*
- * Element is not valid any longer as the contributing plug-in was unloaded or for
- * some other reason. Do not include the extension in the list and inform the user
- * about it.
- */
- Object[] args= {element.toString()};
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_invalid_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, x);
- informUser(status);
- }
- }
- return categories;
- }
-
- /**
- * Log the status and inform the user about a misbehaving extension.
- *
- * @param descriptor the descriptor of the misbehaving extension
- * @param status a status object that will be logged
- */
- void informUser(CompletionProposalComputerDescriptor descriptor, IStatus status) {
- JavaScriptPlugin.log(status);
- String title= JavaTextMessages.CompletionProposalComputerRegistry_error_dialog_title;
- CompletionProposalCategory category= descriptor.getCategory();
- IContributor culprit= descriptor.getContributor();
- Set affectedPlugins= getAffectedContributors(category, culprit);
-
- final String avoidHint;
- final String culpritName= culprit == null ? null : culprit.getName();
- if (affectedPlugins.isEmpty())
- avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHint, new Object[] {culpritName, category.getDisplayName()});
- else
- avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning, new Object[] {culpritName, category.getDisplayName(), toString(affectedPlugins)});
-
- String message= status.getMessage();
- // inlined from MessageDialog.openError
- MessageDialog dialog = new MessageDialog(JavaScriptPlugin.getActiveWorkbenchShell(), title, null /* default image */, message, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, 0) {
- protected Control createCustomArea(Composite parent) {
- Link link= new Link(parent, SWT.NONE);
- link.setText(avoidHint);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced", null, null).open(); //$NON-NLS-1$
- }
- });
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= this.getMinimumMessageWidth();
- link.setLayoutData(gridData);
- return link;
- }
- };
- dialog.open();
- }
-
- /**
- * Returns the names of contributors affected by disabling a category.
- *
- * @param category the category that would be disabled
- * @param culprit the culprit plug-in, which is not included in the returned list
- * @return the names of the contributors other than <code>culprit</code> that contribute to <code>category</code> (element type: {@link String})
- */
- private Set getAffectedContributors(CompletionProposalCategory category, IContributor culprit) {
- Set affectedPlugins= new HashSet();
- for (Iterator it= getProposalComputerDescriptors().iterator(); it.hasNext();) {
- CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next();
- CompletionProposalCategory cat= desc.getCategory();
- if (cat.equals(category)) {
- IContributor contributor= desc.getContributor();
- if (contributor != null && !culprit.equals(contributor))
- affectedPlugins.add(contributor.getName());
- }
- }
- return affectedPlugins;
- }
-
- private Object toString(Collection collection) {
- // strip brackets off AbstractCollection.toString()
- String string= collection.toString();
- return string.substring(1, string.length() - 1);
- }
-
- private void informUser(IStatus status) {
- JavaScriptPlugin.log(status);
- String title= JavaTextMessages.CompletionProposalComputerRegistry_error_dialog_title;
- String message= status.getMessage();
- MessageDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), title, message);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java
deleted file mode 100644
index 0ee0f3df..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.commands.IParameterValues;
-
-/**
- * Map of parameters for the specific content assist command.
- *
- *
- */
-public final class ContentAssistComputerParameter implements IParameterValues {
- /*
- * @see org.eclipse.core.commands.IParameterValues#getParameterValues()
- */
- public Map getParameterValues() {
- Collection descriptors= CompletionProposalComputerRegistry.getDefault().getProposalCategories();
- Map map= new HashMap(descriptors.size());
- for (Iterator it= descriptors.iterator(); it.hasNext();) {
- CompletionProposalCategory category= (CompletionProposalCategory) it.next();
- map.put(category.getDisplayName(), category.getId());
- }
- return map;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistHistory.java
deleted file mode 100644
index 1f65b15d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistHistory.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Map.Entry;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIException;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIStatus;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * An LRU cache for code assist.
- *
- *
- */
-public final class ContentAssistHistory {
- /**
- * Persistence implementation.
- *
- *
- */
- private static final class ReaderWriter {
-
- private static final String NODE_ROOT= "history"; //$NON-NLS-1$
- private static final String NODE_LHS= "lhs"; //$NON-NLS-1$
- private static final String NODE_RHS= "rhs"; //$NON-NLS-1$
- private static final String ATTRIBUTE_NAME= "name"; //$NON-NLS-1$
- private static final String ATTRIBUTE_MAX_LHS= "maxLHS"; //$NON-NLS-1$
- private static final String ATTRIBUTE_MAX_RHS= "maxRHS"; //$NON-NLS-1$
-
- public void store(ContentAssistHistory history, StreamResult result) throws CoreException {
- try {
- DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- DocumentBuilder builder= factory.newDocumentBuilder();
- Document document= builder.newDocument();
-
- Element rootElement = document.createElement(NODE_ROOT);
- rootElement.setAttribute(ATTRIBUTE_MAX_LHS, Integer.toString(history.fMaxLHS));
- rootElement.setAttribute(ATTRIBUTE_MAX_RHS, Integer.toString(history.fMaxRHS));
- document.appendChild(rootElement);
-
- for (Iterator leftHandSides= history.fLHSCache.keySet().iterator(); leftHandSides.hasNext();) {
- String lhs= (String) leftHandSides.next();
- Element lhsElement= document.createElement(NODE_LHS);
- lhsElement.setAttribute(ATTRIBUTE_NAME, lhs);
- rootElement.appendChild(lhsElement);
-
- Set rightHandSides= (Set) history.fLHSCache.get(lhs);
- for (Iterator rhsIterator= rightHandSides.iterator(); rhsIterator.hasNext();) {
- String rhs= (String) rhsIterator.next();
- Element rhsElement= document.createElement(NODE_RHS);
- rhsElement.setAttribute(ATTRIBUTE_NAME, rhs);
- lhsElement.appendChild(rhsElement);
- }
- }
-
- Transformer transformer=TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
- transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
- DOMSource source = new DOMSource(document);
-
- transformer.transform(source, result);
- } catch (TransformerException e) {
- throw createException(e, JavaTextMessages.ContentAssistHistory_serialize_error);
- } catch (ParserConfigurationException e) {
- throw createException(e, JavaTextMessages.ContentAssistHistory_serialize_error);
- }
- }
-
- public ContentAssistHistory load(InputSource source) throws CoreException {
- Element root;
- try {
- DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- root = parser.parse(source).getDocumentElement();
- } catch (SAXException e) {
- throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error);
- } catch (ParserConfigurationException e) {
- throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error);
- } catch (IOException e) {
- throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error);
- }
-
- if (root == null || !root.getNodeName().equalsIgnoreCase(NODE_ROOT))
- return null;
-
- int maxLHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_LHS), DEFAULT_TRACKED_LHS);
- int maxRHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_RHS), DEFAULT_TRACKED_RHS);
-
- ContentAssistHistory history= new ContentAssistHistory(maxLHS, maxRHS);
-
- NodeList list= root.getChildNodes();
- int length= list.getLength();
- for (int i= 0; i < length; ++i) {
- Node lhsNode= list.item(i);
- if (lhsNode.getNodeType() == Node.ELEMENT_NODE) {
- Element lhsElement= (Element) lhsNode;
- if (lhsElement.getNodeName().equalsIgnoreCase(NODE_LHS)) {
- String lhs= lhsElement.getAttribute(ATTRIBUTE_NAME);
- if (lhs != null) {
- Set cache= history.getCache(lhs);
- NodeList children= lhsElement.getChildNodes();
- int nRHS= children.getLength();
- for (int j= 0; j < nRHS; j++) {
- Node rhsNode= children.item(j);
- if (rhsNode.getNodeType() == Node.ELEMENT_NODE) {
- Element rhsElement= (Element) rhsNode;
- if (rhsElement.getNodeName().equalsIgnoreCase(NODE_RHS)) {
- String rhs= rhsElement.getAttribute(ATTRIBUTE_NAME);
- if (rhs != null) {
- cache.add(rhs);
- }
- }
- }
- }
- }
- }
- }
- }
-
- return history;
- }
-
- private int parseNaturalInt(String attribute, int defaultValue) {
- try {
- int integer= Integer.parseInt(attribute);
- if (integer > 0)
- return integer;
- return defaultValue;
- } catch (NumberFormatException e) {
- return defaultValue;
- }
- }
-
- private JavaUIException createException(Exception e, String message) {
- return new JavaUIException(JavaUIStatus.createError(IStatus.ERROR, message, e));
- }
- }
-
- /**
- * Most recently used variant with capped size that only counts
- * {@linkplain #put(Object, Object) put} as access. This is implemented by always removing an
- * element before it gets put back.
- *
- *
- */
- private static final class MRUMap extends LinkedHashMap {
- private static final long serialVersionUID= 1L;
- private final int fMaxSize;
-
- /**
- * Creates a new <code>MRUMap</code> with the given size.
- *
- * @param maxSize the maximum size of the cache, must be &gt; 0
- */
- public MRUMap(int maxSize) {
- Assert.isLegal(maxSize > 0);
- fMaxSize= maxSize;
- }
-
- /*
- * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
- */
- public Object put(Object key, Object value) {
- Object object= remove(key);
- super.put(key, value);
- return object;
- }
-
- /*
- * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry)
- */
- protected boolean removeEldestEntry(Entry eldest) {
- return size() > fMaxSize;
- }
- }
-
- /**
- * Most recently used variant with capped size that orders the elements by addition.
- * This is implemented by always removing an element before it gets added back.
- *
- *
- */
- private static final class MRUSet extends LinkedHashSet {
- private static final long serialVersionUID= 1L;
- private final int fMaxSize;
-
- /**
- * Creates a new <code>MRUSet</code> with the given size.
- *
- * @param maxSize the maximum size of the cache, must be &gt; 0
- */
- public MRUSet(int maxSize) {
- Assert.isLegal(maxSize > 0);
- fMaxSize= maxSize;
- }
-
- /*
- * @see java.util.HashSet#add(java.lang.Object)
- */
- public boolean add(Object o) {
- if (remove(o)) {
- super.add(o);
- return false;
- }
-
- if (size() >= fMaxSize)
- remove(this.iterator().next());
-
- super.add(o);
- return true;
- }
- }
-
- /**
- * A ranking of the most recently selected types.
- *
- *
- */
- public static final class RHSHistory {
- private final LinkedHashMap fHistory;
- private List fList;
-
- RHSHistory(LinkedHashMap history) {
- fHistory= history;
- }
-
- /**
- * Returns the rank of a type in the history in [0.0,&nbsp;1.0]. The rank of the most
- * recently selected type is 1.0, the rank of any type that is not remembered is zero.
- *
- * @param type the fully qualified type name to get the rank for
- * @return the rank of <code>type</code>
- */
- public float getRank(String type) {
- if (fHistory == null)
- return 0.0F;
- Integer integer= (Integer) fHistory.get(type);
- return integer == null ? 0.0F : integer.floatValue() / fHistory.size();
- }
-
- /**
- * Returns the size of the history.
- *
- * @return the size of the history
- */
- public int size() {
- return fHistory == null ? 0 : fHistory.size();
- }
-
- /**
- * Returns the list of remembered types ordered by recency. The first element is the
- * <i>least</i>, the last element the <i>most</i> recently remembered type.
- *
- * @return the list of remembered types as fully qualified type names (element type:
- * {@link String})
- */
- public List getTypes() {
- if (fHistory == null)
- return Collections.EMPTY_LIST;
- if (fList == null) {
- fList= Collections.unmodifiableList(new ArrayList(fHistory.keySet()));
- }
- return fList;
- }
- }
-
- private static final RHSHistory EMPTY_HISTORY= new RHSHistory(null);
- private static final int DEFAULT_TRACKED_LHS= 100;
- private static final int DEFAULT_TRACKED_RHS= 10;
-
- private static final Set UNCACHEABLE;
- static {
- Set uncacheable= new HashSet();
- uncacheable.add("java.lang.Object"); //$NON-NLS-1$
- uncacheable.add("java.lang.Comparable"); //$NON-NLS-1$
- uncacheable.add("java.io.Serializable"); //$NON-NLS-1$
- uncacheable.add("java.io.Externalizable"); //$NON-NLS-1$
- UNCACHEABLE= Collections.unmodifiableSet(uncacheable);
- }
-
- private final LinkedHashMap/*<IType, MRUSet<IType>>*/ fLHSCache;
- private final int fMaxLHS;
- private final int fMaxRHS;
-
- /**
- * Creates a new history.
- *
- * @param maxLHS the maximum number of tracked left hand sides (&gt; 0)
- * @param maxRHS the maximum number of tracked right hand sides per left hand side(&gt; 0)
- */
- public ContentAssistHistory(int maxLHS, int maxRHS) {
- Assert.isLegal(maxLHS > 0);
- Assert.isLegal(maxRHS > 0);
- fMaxLHS= maxLHS;
- fMaxRHS= maxRHS;
- fLHSCache= new MRUMap(fMaxLHS);
- }
-
- /**
- * Creates a new history, equivalent to
- * <code>ContentAssistHistory(DEFAULT_TRACKED_LHS, DEFAULT_TRACKED_RHS})</code>.
- */
- public ContentAssistHistory() {
- this(DEFAULT_TRACKED_LHS, DEFAULT_TRACKED_RHS);
- }
-
- /**
- * Remembers the selection of a right hand side type (proposal type) for a certain left hand side (expected
- * type) in content assist.
- *
- * @param lhs the left hand side / expected type
- * @param rhs the selected right hand side
- */
- public void remember(IType lhs, IType rhs) {
- Assert.isLegal(lhs != null);
- Assert.isLegal(rhs != null);
-
- try {
- if (!isCacheableRHS(rhs))
- return;
- ITypeHierarchy hierarchy= rhs.newSupertypeHierarchy(getProgressMonitor());
- if (hierarchy.contains(lhs)) {
- // TODO remember for every member of the LHS hierarchy or not? Yes for now.
- IType[] allLHSides= hierarchy.getAllSuperclasses(lhs);
- for (int i= 0; i < allLHSides.length; i++)
- rememberInternal(allLHSides[i], rhs);
- rememberInternal(lhs, rhs);
- }
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x);
- }
- }
-
- /**
- * Returns the {@link RHSHistory history} of the types that have been selected most recently as
- * right hand sides for the given type.
- *
- * @param lhs the fully qualified type name of an expected type for which right hand sides are
- * requested, or <code>null</code>
- * @return the right hand side history for the given type
- */
- public RHSHistory getHistory(String lhs) {
- MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs);
- if (rhsCache != null) {
- int count= rhsCache.size();
- LinkedHashMap history= new LinkedHashMap((int) (count / 0.75));
- int rank= 1;
- for (Iterator it= rhsCache.iterator(); it.hasNext(); rank++) {
- String type= (String) it.next();
- history.put(type, new Integer(rank));
- }
- return new RHSHistory(history);
- }
- return EMPTY_HISTORY;
- }
-
- /**
- * Returns a read-only map from {@link IType} to {@link RHSHistory}, where each value is the
- * history for the key type (see {@link #getHistory(String)}.
- *
- * @return the set of remembered right hand sides ordered by least recent selection
- */
- public Map getEntireHistory() {
- HashMap map= new HashMap((int) (fLHSCache.size() / 0.75));
- for (Iterator it= fLHSCache.entrySet().iterator(); it.hasNext();) {
- Entry entry= (Entry) it.next();
- String lhs= (String) entry.getKey();
- map.put(lhs, getHistory(lhs));
- }
- return Collections.unmodifiableMap(map);
- }
-
- private void rememberInternal(IType lhs, IType rhs) throws JavaScriptModelException {
- if (isCacheableLHS(lhs))
- getCache(lhs.getFullyQualifiedName()).add(rhs.getFullyQualifiedName());
- }
-
- private boolean isCacheableLHS(IType type) throws JavaScriptModelException {
- return !UNCACHEABLE.contains(type.getFullyQualifiedName());
- }
-
- private boolean isCacheableRHS(IType type) throws JavaScriptModelException {
- return !Flags.isAbstract(type.getFlags());
- }
-
- private Set getCache(String lhs) {
- MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs);
- if (rhsCache == null) {
- rhsCache= new MRUSet(fMaxRHS);
- fLHSCache.put(lhs, rhsCache);
- }
-
- return rhsCache;
- }
-
- private IProgressMonitor getProgressMonitor() {
- return new NullProgressMonitor();
- }
-
- /**
- * Stores the history as XML document into the given preferences.
- *
- * @param history the history to store
- * @param preferences the preferences to store the history into
- * @param key the key under which to store the history
- * @throws CoreException if serialization fails
- * @see #load(Preferences, String) on how to restore a history stored by this method
- */
- public static void store(ContentAssistHistory history, Preferences preferences, String key) throws CoreException {
- StringWriter writer= new StringWriter();
- new ReaderWriter().store(history, new StreamResult(writer));
- preferences.setValue(key, writer.toString());
- }
-
- /**
- * Loads a history from an XML encoded preference value.
- *
- * @param preferences the preferences to retrieve the history from
- * @param key the key under which the history is stored
- * @return the deserialized history, or <code>null</code> if there is nothing stored under the
- * given key
- * @throws CoreException if deserialization fails
- * @see #store(ContentAssistHistory, Preferences, String) on how to store a history such that it
- * can be read by this method
- */
- public static ContentAssistHistory load(Preferences preferences, String key) throws CoreException {
- String value= preferences.getString(key);
- if (value != null && value.length() > 0) {
- return new ReaderWriter().load(new InputSource(new StringReader(value)));
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistProcessor.java
deleted file mode 100644
index ef6cd3b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistProcessor.java
+++ /dev/null
@@ -1,559 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.action.LegacyActionTools;
-import org.eclipse.jface.bindings.TriggerSequence;
-import org.eclipse.jface.bindings.keys.KeySequence;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ContentAssistEvent;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.ICompletionListener;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContentAssistantExtension2;
-import org.eclipse.jface.text.contentassist.IContentAssistantExtension3;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-
-/**
- * A content assist processor that aggregates the proposals of the
- * {@link org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer}s contributed via the
- * <code>org.eclipse.wst.jsdt.ui.javaCompletionProposalComputer</code> extension point.
- * <p>
- * Subclasses may extend:
- * <ul>
- * <li><code>createContext</code> to provide the context object passed to the computers</li>
- * <li><code>createProgressMonitor</code> to change the way progress is reported</li>
- * <li><code>filterAndSort</code> to add sorting and filtering</li>
- * <li><code>getContextInformationValidator</code> to add context validation (needed if any
- * contexts are provided)</li>
- * <li><code>getErrorMessage</code> to change error reporting</li>
- * </ul>
- * </p>
- *
- *
- */
-public class ContentAssistProcessor implements IContentAssistProcessor {
- private static final boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ResultCollector")); //$NON-NLS-1$//$NON-NLS-2$
-
- /**
- * Dialog settings key for the "all categories are disabled" warning dialog. See
- * {@link OptionalMessageDialog}.
- *
- *
- */
- private static final String PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY= "EmptyDefaultAssistCategory"; //$NON-NLS-1$
-
- private static final Comparator ORDER_COMPARATOR= new Comparator() {
-
- public int compare(Object o1, Object o2) {
- CompletionProposalCategory d1= (CompletionProposalCategory) o1;
- CompletionProposalCategory d2= (CompletionProposalCategory) o2;
-
- return d1.getSortOrder() - d2.getSortOrder();
- }
-
- };
-
- private final List fCategories;
- private final String fPartition;
- private final ContentAssistant fAssistant;
-
- private char[] fCompletionAutoActivationCharacters;
-
- /* cycling stuff */
- private int fRepetition= -1;
- private List/*<List<CompletionProposalCategory>>*/ fCategoryIteration= null;
- private String fIterationGesture= null;
- private int fNumberOfComputedResults= 0;
- private String fErrorMessage;
-
- public ContentAssistProcessor(ContentAssistant assistant, String partition) {
- Assert.isNotNull(partition);
- Assert.isNotNull(assistant);
- fPartition= partition;
- fCategories= CompletionProposalComputerRegistry.getDefault().getProposalCategories();
- fAssistant= assistant;
- fAssistant.addCompletionListener(new ICompletionListener() {
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionListener#assistSessionStarted(org.eclipse.jface.text.contentassist.ContentAssistEvent)
- */
- public void assistSessionStarted(ContentAssistEvent event) {
- if (event.processor != ContentAssistProcessor.this)
- return;
-
- fIterationGesture= getIterationGesture();
- KeySequence binding= getIterationBinding();
-
- // this may show the warning dialog if all categories are disabled
- fCategoryIteration= getCategoryIteration();
- for (Iterator it= fCategories.iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- cat.sessionStarted();
- }
-
- fRepetition= 0;
- if (event.assistant instanceof IContentAssistantExtension2) {
- IContentAssistantExtension2 extension= (IContentAssistantExtension2) event.assistant;
-
- if (fCategoryIteration.size() == 1) {
- extension.setRepeatedInvocationMode(false);
- extension.setShowEmptyList(false);
- } else {
- extension.setRepeatedInvocationMode(true);
- extension.setStatusLineVisible(true);
- extension.setStatusMessage(createIterationMessage());
- extension.setShowEmptyList(true);
- if (extension instanceof IContentAssistantExtension3) {
- IContentAssistantExtension3 ext3= (IContentAssistantExtension3) extension;
- ((ContentAssistant) ext3).setRepeatedInvocationTrigger(binding);
- }
- }
-
- }
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionListener#assistSessionEnded(org.eclipse.jface.text.contentassist.ContentAssistEvent)
- */
- public void assistSessionEnded(ContentAssistEvent event) {
- if (event.processor != ContentAssistProcessor.this)
- return;
-
- for (Iterator it= fCategories.iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- cat.sessionEnded();
- }
-
- fCategoryIteration= null;
- fRepetition= -1;
- fIterationGesture= null;
- if (event.assistant instanceof IContentAssistantExtension2) {
- IContentAssistantExtension2 extension= (IContentAssistantExtension2) event.assistant;
- extension.setShowEmptyList(false);
- extension.setRepeatedInvocationMode(false);
- extension.setStatusLineVisible(false);
- if (extension instanceof IContentAssistantExtension3) {
- IContentAssistantExtension3 ext3= (IContentAssistantExtension3) extension;
- ((ContentAssistant) ext3).setRepeatedInvocationTrigger(null);
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionListener#selectionChanged(org.eclipse.jface.text.contentassist.ICompletionProposal, boolean)
- */
- public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) {}
-
- });
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- public final ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
- long start= DEBUG ? System.currentTimeMillis() : 0;
-
- clearState();
-
- IProgressMonitor monitor= createProgressMonitor();
- monitor.beginTask(JavaTextMessages.ContentAssistProcessor_computing_proposals, fCategories.size() + 1);
-
- ContentAssistInvocationContext context= createContext(viewer, offset);
- long setup= DEBUG ? System.currentTimeMillis() : 0;
-
- monitor.subTask(JavaTextMessages.ContentAssistProcessor_collecting_proposals);
- List proposals= collectProposals(viewer, offset, monitor, context);
- long collect= DEBUG ? System.currentTimeMillis() : 0;
-
- monitor.subTask(JavaTextMessages.ContentAssistProcessor_sorting_proposals);
- List filtered= filterAndSortProposals(proposals, monitor, context);
- fNumberOfComputedResults= filtered.size();
- long filter= DEBUG ? System.currentTimeMillis() : 0;
-
- ICompletionProposal[] result= (ICompletionProposal[]) filtered.toArray(new ICompletionProposal[filtered.size()]);
- monitor.done();
-
- if (DEBUG) {
- System.err.println("Code Assist Stats (" + result.length + " proposals)"); //$NON-NLS-1$ //$NON-NLS-2$
- System.err.println("Code Assist (setup):\t" + (setup - start) ); //$NON-NLS-1$
- System.err.println("Code Assist (collect):\t" + (collect - setup) ); //$NON-NLS-1$
- System.err.println("Code Assist (sort):\t" + (filter - collect) ); //$NON-NLS-1$
- }
-
- return result;
- }
-
- private void clearState() {
- fErrorMessage=null;
- fNumberOfComputedResults= 0;
- }
-
- private List collectProposals(ITextViewer viewer, int offset, IProgressMonitor monitor, ContentAssistInvocationContext context) {
- List proposals= new ArrayList();
- List providers= getCategories();
- for (Iterator it= providers.iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- List computed= cat.computeCompletionProposals(context, fPartition, new SubProgressMonitor(monitor, 1));
- proposals.addAll(computed);
- if (fErrorMessage == null)
- fErrorMessage= cat.getErrorMessage();
- }
-
- return proposals;
- }
-
- /**
- * Filters and sorts the proposals. The passed list may be modified
- * and returned, or a new list may be created and returned.
- *
- * @param proposals the list of collected proposals (element type:
- * {@link ICompletionProposal})
- * @param monitor a progress monitor
- * @param context TODO
- * @return the list of filtered and sorted proposals, ready for
- * display (element type: {@link ICompletionProposal})
- */
- protected List filterAndSortProposals(List proposals, IProgressMonitor monitor, ContentAssistInvocationContext context) {
- return proposals;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
- clearState();
-
- IProgressMonitor monitor= createProgressMonitor();
- monitor.beginTask(JavaTextMessages.ContentAssistProcessor_computing_contexts, fCategories.size() + 1);
-
- monitor.subTask(JavaTextMessages.ContentAssistProcessor_collecting_contexts);
- List proposals= collectContextInformation(viewer, offset, monitor);
-
- monitor.subTask(JavaTextMessages.ContentAssistProcessor_sorting_contexts);
- List filtered= filterAndSortContextInformation(proposals, monitor);
- fNumberOfComputedResults= filtered.size();
-
- IContextInformation[] result= (IContextInformation[]) filtered.toArray(new IContextInformation[filtered.size()]);
- monitor.done();
- return result;
- }
-
- private List collectContextInformation(ITextViewer viewer, int offset, IProgressMonitor monitor) {
- List proposals= new ArrayList();
- ContentAssistInvocationContext context= createContext(viewer, offset);
-
- List providers= getCategories();
- for (Iterator it= providers.iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- List computed= cat.computeContextInformation(context, fPartition, new SubProgressMonitor(monitor, 1));
- proposals.addAll(computed);
- if (fErrorMessage == null)
- fErrorMessage= cat.getErrorMessage();
- }
-
- return proposals;
- }
-
- /**
- * Filters and sorts the context information objects. The passed
- * list may be modified and returned, or a new list may be created
- * and returned.
- *
- * @param contexts the list of collected proposals (element type:
- * {@link IContextInformation})
- * @param monitor a progress monitor
- * @return the list of filtered and sorted proposals, ready for
- * display (element type: {@link IContextInformation})
- */
- protected List filterAndSortContextInformation(List contexts, IProgressMonitor monitor) {
- return contexts;
- }
-
- /**
- * Sets this processor's set of characters triggering the activation of the
- * completion proposal computation.
- *
- * @param activationSet the activation set
- */
- public final void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
- fCompletionAutoActivationCharacters= activationSet;
- }
-
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public final char[] getCompletionProposalAutoActivationCharacters() {
- return fCompletionAutoActivationCharacters;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- if (fNumberOfComputedResults > 0)
- return null;
- if (fErrorMessage != null)
- return fErrorMessage;
- return JavaUIMessages.JavaEditor_codeassist_noCompletions;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- /**
- * Creates a progress monitor.
- * <p>
- * The default implementation creates a
- * <code>NullProgressMonitor</code>.
- * </p>
- *
- * @return a progress monitor
- */
- protected IProgressMonitor createProgressMonitor() {
- return new NullProgressMonitor();
- }
-
- /**
- * Creates the context that is passed to the completion proposal
- * computers.
- *
- * @param viewer the viewer that content assist is invoked on
- * @param offset the content assist offset
- * @return the context to be passed to the computers
- */
- protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset) {
- return new ContentAssistInvocationContext(viewer, offset);
- }
-
- private List getCategories() {
- if (fCategoryIteration == null)
- return fCategories;
-
- int iteration= fRepetition % fCategoryIteration.size();
- fAssistant.setStatusMessage(createIterationMessage());
- fAssistant.setEmptyMessage(createEmptyMessage());
- fRepetition++;
-
-// fAssistant.setShowMessage(fRepetition % 2 != 0);
-//
- return (List) fCategoryIteration.get(iteration);
- }
-
- private List getCategoryIteration() {
- List sequence= new ArrayList();
- sequence.add(getDefaultCategories());
- for (Iterator it= getSeparateCategories().iterator(); it.hasNext();) {
- CompletionProposalCategory cat= (CompletionProposalCategory) it.next();
- sequence.add(Collections.singletonList(cat));
- }
- return sequence;
- }
-
- private List getDefaultCategories() {
- // default mix - enable all included computers
- List included= getDefaultCategoriesUnchecked();
-
- if ((IJavaScriptPartitions.JAVA_DOC.equals(fPartition) || IDocument.DEFAULT_CONTENT_TYPE.equals(fPartition)) && included.isEmpty() && !fCategories.isEmpty())
- if (informUserAboutEmptyDefaultCategory())
- // preferences were restored - recompute the default categories
- included= getDefaultCategoriesUnchecked();
-
- return included;
- }
-
- private List getDefaultCategoriesUnchecked() {
- List included= new ArrayList();
- for (Iterator it= fCategories.iterator(); it.hasNext();) {
- CompletionProposalCategory category= (CompletionProposalCategory) it.next();
- if (category.isIncluded() && category.hasComputers(fPartition))
- included.add(category);
- }
- return included;
- }
-
- /**
- * Informs the user about the fact that there are no enabled categories in the default content
- * assist set and shows a link to the preferences.
- *
- *
- */
- private boolean informUserAboutEmptyDefaultCategory() {
- if (OptionalMessageDialog.isDialogEnabled(PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY)) {
- final Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- String title= JavaTextMessages.ContentAssistProcessor_all_disabled_title;
- String message= JavaTextMessages.ContentAssistProcessor_all_disabled_message;
- // see PreferencePage#createControl for the 'defaults' label
- final String restoreButtonLabel= JFaceResources.getString("defaults"); //$NON-NLS-1$
- final String linkMessage= Messages.format(JavaTextMessages.ContentAssistProcessor_all_disabled_preference_link, LegacyActionTools.removeMnemonics(restoreButtonLabel));
- final int restoreId= IDialogConstants.CLIENT_ID + 10;
- final int settingsId= IDialogConstants.CLIENT_ID + 11;
- final OptionalMessageDialog dialog= new OptionalMessageDialog(PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY, shell, title, null /* default image */, message, MessageDialog.WARNING, new String[] { restoreButtonLabel, IDialogConstants.CLOSE_LABEL }, 1) {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createCustomArea(Composite composite) {
- // wrap link and checkbox in one composite without space
- Composite parent= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.verticalSpacing= 0;
- parent.setLayout(layout);
-
- Composite linkComposite= new Composite(parent, SWT.NONE);
- layout= new GridLayout();
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- linkComposite.setLayout(layout);
-
- Link link= new Link(linkComposite, SWT.NONE);
- link.setText(linkMessage);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode(settingsId);
- close();
- }
- });
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= this.getMinimumMessageWidth();
- link.setLayoutData(gridData);
-
- // create checkbox and "don't show this message" prompt
- super.createCustomArea(parent);
-
- return parent;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.MessageDialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
- */
- protected void createButtonsForButtonBar(Composite parent) {
- Button[] buttons= new Button[2];
- buttons[0]= createButton(parent, restoreId, restoreButtonLabel, false);
- buttons[1]= createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true);
- setButtons(buttons);
- }
- };
- int returnValue= dialog.open();
- if (restoreId == returnValue || settingsId == returnValue) {
- if (restoreId == returnValue) {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- store.setToDefault(PreferenceConstants.CODEASSIST_CATEGORY_ORDER);
- store.setToDefault(PreferenceConstants.CODEASSIST_EXCLUDED_CATEGORIES);
- }
- if (settingsId == returnValue)
- PreferencesUtil.createPreferenceDialogOn(shell, "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced", null, null).open(); //$NON-NLS-1$
- CompletionProposalComputerRegistry registry= CompletionProposalComputerRegistry.getDefault();
- registry.reload();
- return true;
- }
- }
- return false;
- }
-
- private List getSeparateCategories() {
- ArrayList sorted= new ArrayList();
- for (Iterator it= fCategories.iterator(); it.hasNext();) {
- CompletionProposalCategory category= (CompletionProposalCategory) it.next();
- if (category.isSeparateCommand() && category.hasComputers(fPartition))
- sorted.add(category);
- }
- Collections.sort(sorted, ORDER_COMPARATOR);
- return sorted;
- }
-
- private String createEmptyMessage() {
- return Messages.format(JavaTextMessages.ContentAssistProcessor_empty_message, new String[]{getCategoryLabel(fRepetition)});
- }
-
- private String createIterationMessage() {
- return Messages.format(JavaTextMessages.ContentAssistProcessor_toggle_affordance_update_message, new String[]{ getCategoryLabel(fRepetition), fIterationGesture, getCategoryLabel(fRepetition + 1) });
- }
-
- private String getCategoryLabel(int repetition) {
- int iteration= repetition % fCategoryIteration.size();
- if (iteration == 0)
- return JavaTextMessages.ContentAssistProcessor_defaultProposalCategory;
- return toString((CompletionProposalCategory) ((List) fCategoryIteration.get(iteration)).get(0));
- }
-
- private String toString(CompletionProposalCategory category) {
- return category.getDisplayName();
- }
-
- private String getIterationGesture() {
- TriggerSequence binding= getIterationBinding();
- return binding != null ?
- Messages.format(JavaTextMessages.ContentAssistProcessor_toggle_affordance_press_gesture, new Object[] { binding.format() })
- : JavaTextMessages.ContentAssistProcessor_toggle_affordance_click_gesture;
- }
-
- private KeySequence getIterationBinding() {
- final IBindingService bindingSvc= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- TriggerSequence binding= bindingSvc.getBestActiveBindingFor(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- if (binding instanceof KeySequence)
- return (KeySequence) binding;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java
deleted file mode 100644
index 5d69f003..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-
-
-/**
- * Proposal info that computes the javadoc lazily when it is queried.
- *
- *
- */
-public final class FieldProposalInfo extends MemberProposalInfo {
-
- /**
- * Creates a new proposal info.
- *
- * @param project the java project to reference when resolving types
- * @param proposal the proposal to generate information for
- */
- public FieldProposalInfo(IJavaScriptProject project, CompletionProposal proposal) {
- super(project, proposal);
- }
-
- /**
- * Resolves the member described by the receiver and returns it if found.
- * Returns <code>null</code> if no corresponding member can be found.
- *
- * @return the resolved member or <code>null</code> if none is found
- * @throws JavaScriptModelException if accessing the java model fails
- */
- protected IMember resolveMember() throws JavaScriptModelException {
- char[] declarationSignature= fProposal.getDeclarationSignature();
- // for synthetic fields on arrays, declaration signatures may be null
- // TODO remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed
- if (declarationSignature == null)
- return null;
- String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature));
- IType[] types = this.fJavaProject.findTypes(typeName);
- if(types != null && types.length > 0) {
- for(int i = 0; i < types.length; ++i) {
- IType type = types[i];
- if (type != null) {
- String name= String.valueOf(fProposal.getName());
- IField field= type.getField(name);
- if (field.exists())
- return field;
- }
- }
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FilledArgumentNamesMethodProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FilledArgumentNamesMethodProposal.java
deleted file mode 100644
index 3cad273f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FilledArgumentNamesMethodProposal.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * A method proposal with filled in argument names.
- */
-public final class FilledArgumentNamesMethodProposal extends JavaMethodCompletionProposal {
-
- private IRegion fSelectedRegion; // initialized by apply()
- private int[] fArgumentOffsets;
- private int[] fArgumentLengths;
-
- public FilledArgumentNamesMethodProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- }
-
- /*
- * @see ICompletionProposalExtension#apply(IDocument, char)
- */
- public void apply(IDocument document, char trigger, int offset) {
- super.apply(document, trigger, offset);
- int baseOffset= getReplacementOffset();
- String replacement= getReplacementString();
-
- if (fArgumentOffsets != null && getTextViewer() != null) {
- try {
- LinkedModeModel model= new LinkedModeModel();
- for (int i= 0; i != fArgumentOffsets.length; i++) {
- LinkedPositionGroup group= new LinkedPositionGroup();
- group.addPosition(new LinkedPosition(document, baseOffset + fArgumentOffsets[i], fArgumentLengths[i], LinkedPositionGroup.NO_STOP));
- model.addGroup(group);
- }
-
- model.forceInstall();
- JavaEditor editor= getJavaEditor();
- if (editor != null) {
- model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
- }
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer());
- ui.setExitPosition(getTextViewer(), baseOffset + replacement.length(), 0, Integer.MAX_VALUE);
- ui.setExitPolicy(new ExitPolicy(')', document));
- ui.setDoContextInfo(true);
- ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT);
- ui.enter();
-
- fSelectedRegion= ui.getSelectedRegion();
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- openErrorDialog(e);
- }
- } else {
- fSelectedRegion= new Region(baseOffset + replacement.length(), 0);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaMethodCompletionProposal#needsLinkedMode()
- */
- protected boolean needsLinkedMode() {
- return false; // we handle it ourselves
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
-
- if (!hasParameters() || !hasArgumentList())
- return super.computeReplacementString();
-
- char[][] parameterNames= fProposal.findParameterNames(null);
- int count= parameterNames.length;
- fArgumentOffsets= new int[count];
- fArgumentLengths= new int[count];
- StringBuffer buffer= new StringBuffer(String.valueOf(fProposal.getName()));
-
- FormatterPrefs prefs= getFormatterPrefs();
- if (prefs.beforeOpeningParen)
- buffer.append(SPACE);
- buffer.append(LPAREN);
-
- setCursorPosition(buffer.length());
-
- if (prefs.afterOpeningParen)
- buffer.append(SPACE);
-
- for (int i= 0; i != count; i++) {
- if (i != 0) {
- if (prefs.beforeComma)
- buffer.append(SPACE);
- buffer.append(COMMA);
- if (prefs.afterComma)
- buffer.append(SPACE);
- }
-
- fArgumentOffsets[i]= buffer.length();
- buffer.append(parameterNames[i]);
- fArgumentLengths[i]= parameterNames[i].length;
- }
-
- if (prefs.beforeClosingParen)
- buffer.append(SPACE);
-
- buffer.append(RPAREN);
-
- return buffer.toString();
- }
-
- /**
- * Returns the currently active java editor, or <code>null</code> if it
- * cannot be determined.
- *
- * @return the currently active java editor, or <code>null</code>
- */
- private JavaEditor getJavaEditor() {
- IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor();
- if (part instanceof JavaEditor)
- return (JavaEditor) part;
- else
- return null;
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- if (fSelectedRegion == null)
- return new Point(getReplacementOffset(), 0);
-
- return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
- }
-
- private void openErrorDialog(BadLocationException e) {
- Shell shell= getTextViewer().getTextWidget().getShell();
- MessageDialog.openError(shell, JavaTextMessages.FilledArgumentNamesMethodProposal_error_msg, e.getMessage());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/GetterSetterCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/GetterSetterCompletionProposal.java
deleted file mode 100644
index c6f6b208..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/GetterSetterCompletionProposal.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Collection;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-public class GetterSetterCompletionProposal extends JavaTypeCompletionProposal implements ICompletionProposalExtension4 {
-
- public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set suggestedMethods, Collection result) throws CoreException {
- if (prefix.length() == 0) {
- relevance--;
- }
-
- IField[] fields= type.getFields();
- IFunction[] methods= type.getFunctions();
- for (int i= 0; i < fields.length; i++) {
- IField curr= fields[i];
- String getterName= GetterSetterUtil.getGetterName(curr, null);
- if (getterName.startsWith(prefix) && !hasMethod(methods, getterName) && suggestedMethods.add(getterName)) {
- result.add(new GetterSetterCompletionProposal(curr, offset, length, true, relevance));
- }
-
- String setterName= GetterSetterUtil.getSetterName(curr, null);
- if (setterName.startsWith(prefix) && !hasMethod(methods, setterName) && suggestedMethods.add(setterName)) {
- result.add(new GetterSetterCompletionProposal(curr, offset, length, false, relevance));
- }
- }
- }
-
- private static boolean hasMethod(IFunction[] methods, String name) {
- for (int i= 0; i < methods.length; i++) {
- if (methods[i].getElementName().equals(name)) {
- return true;
- }
- }
- return false;
- }
-
- private final IField fField;
- private final boolean fIsGetter;
-
- public GetterSetterCompletionProposal(IField field, int start, int length, boolean isGetter, int relevance) throws JavaScriptModelException {
- super("", field.getJavaScriptUnit(), start, length, JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC), getDisplayName(field, isGetter), relevance); //$NON-NLS-1$
- Assert.isNotNull(field);
-
- fField= field;
- fIsGetter= isGetter;
- setProposalInfo(new ProposalInfo(field));
- }
-
- private static String getDisplayName(IField field, boolean isGetter) throws JavaScriptModelException {
- StringBuffer buf= new StringBuffer();
- if (isGetter) {
- buf.append(GetterSetterUtil.getGetterName(field, null));
- buf.append("() "); //$NON-NLS-1$
- buf.append(Signature.toString(field.getTypeSignature()));
- buf.append(" - "); //$NON-NLS-1$
- buf.append(Messages.format(JavaTextMessages.GetterSetterCompletionProposal_getter_label, field.getElementName()));
- } else {
- buf.append(GetterSetterUtil.getSetterName(field, null));
- buf.append('(').append(Signature.toString(field.getTypeSignature())).append(')');
- buf.append(" "); //$NON-NLS-1$
- buf.append(Signature.toString(Signature.SIG_VOID));
- buf.append(" - "); //$NON-NLS-1$
- buf.append(Messages.format(JavaTextMessages.GetterSetterCompletionProposal_setter_label, field.getElementName()));
- }
- return buf.toString();
- }
-
- /* (non-Javadoc)
- * @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportRewrite)
- */
- protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fField.getJavaScriptProject());
- boolean addComments= settings.createComments;
- int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);
-
- String stub;
- if (fIsGetter) {
- String getterName= GetterSetterUtil.getGetterName(fField, null);
- stub= GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
- } else {
- String setterName= GetterSetterUtil.getSetterName(fField, null);
- stub= GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
- }
-
- // use the code formatter
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
-
- IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
- int lineStart= region.getOffset();
- int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth);
-
- String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, null, lineDelim, fField.getJavaScriptProject());
-
- if (replacement.endsWith(lineDelim)) {
- replacement= replacement.substring(0, replacement.length() - lineDelim.length());
- }
-
- setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
- return true;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
- */
- public boolean isAutoInsertable() {
- return false;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java
deleted file mode 100644
index 1e132b4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ui.texteditor.HippieProposalProcessor;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-
-
-/**
- * A computer wrapper for the hippie processor.
- *
- *
- */
-public final class HippieProposalComputer implements IJavaCompletionProposalComputer {
- /** The wrapped processor. */
- private final HippieProposalProcessor fProcessor= new HippieProposalProcessor();
-
- /**
- * Default ctor to make it instantiatable via the extension mechanism.
- */
- public HippieProposalComputer() {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return Arrays.asList(fProcessor.computeCompletionProposals(context.getViewer(), context.getInvocationOffset()));
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeContextInformation(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return Arrays.asList(fProcessor.computeContextInformation(context.getViewer(), context.getInvocationOffset()));
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#getErrorMessage()
- */
- public String getErrorMessage() {
- return fProcessor.getErrorMessage();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionStarted()
- */
- public void sessionStarted() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionEnded()
- */
- public void sessionEnded() {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IJavaReconcilingListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IJavaReconcilingListener.java
deleted file mode 100644
index 9dcef635..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IJavaReconcilingListener.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-
-/**
- * Interface of an object listening to Java reconciling.
- *
- *
- */
-public interface IJavaReconcilingListener {
-
- /**
- * Called before reconciling is started.
- */
- void aboutToBeReconciled();
-
- /**
- * Called after reconciling has been finished.
- * @param ast the compilation unit AST or <code>null</code> if
- * the working copy was consistent or reconciliation has been cancelled
- * @param forced <code>true</code> iff this reconciliation was forced
- * @param progressMonitor the progress monitor
- */
- void reconciled(JavaScriptUnit ast, boolean forced, IProgressMonitor progressMonitor);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java
deleted file mode 100644
index c72c404d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-
-/**
- * Extension to <code>IProblemRequestor</code>.
- */
-public interface IProblemRequestorExtension {
-
- /**
- * Sets the progress monitor to this problem requestor.
- *
- * @param monitor the progress monitor to be used
- */
- void setProgressMonitor(IProgressMonitor monitor);
-
- /**
- * Sets the active state of this problem requestor.
- *
- * @param isActive the state of this problem requestor
- */
- void setIsActive(boolean isActive);
-
- /**
- * Informs the problem requestor that a sequence of reportings is about to start. While
- * a sequence is active, multiple peering calls of <code>beginReporting</code> and
- * <code>endReporting</code> can appear.
- *
- *
- */
- void beginReportingSequence();
-
- /**
- * Informs the problem requestor that the sequence of reportings has been finished.
- *
- *
- */
- void endReportingSequence();
-
- /**
- * Tells the problem requestor to handle temporary problems.
- *
- * @param enable <code>true</code> if temporary problems are handled
- *
- */
- void setIsHandlingTemporaryProblems(boolean enable);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IReconcilingParticipant.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IReconcilingParticipant.java
deleted file mode 100644
index da5939e4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IReconcilingParticipant.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-
-
-/**
- * Interface of an object participating in reconciling.
- *
- * @deprecated as of 3.0 use {@link IJavaReconcilingListener}
- */
-public interface IReconcilingParticipant {
-
- /**
- * Called after reconciling has been finished.
- */
- void reconciled();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ImportCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ImportCompletionProposal.java
deleted file mode 100644
index f70c30fd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ImportCompletionProposal.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-
-/**
- * Completion proposal for required imports.
- *
- *
- */
-public class ImportCompletionProposal extends AbstractJavaCompletionProposal {
-
- private final IJavaScriptUnit fCompilationUnit;
- private final int fParentProposalKind;
- private ImportRewrite fImportRewrite;
- private ContextSensitiveImportRewriteContext fImportContext;
- private final CompletionProposal fProposal;
- private boolean fReplacementStringComputed;
-
-
- public ImportCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context, int parentProposalKind) {
- super(context);
- fProposal= proposal;
- fParentProposalKind= parentProposalKind;
- fCompilationUnit= context.getCompilationUnit();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#getReplacementString()
- */
- public final String getReplacementString() {
- if (!fReplacementStringComputed)
- setReplacementString(computeReplacementString());
- return super.getReplacementString();
- }
-
- /**
- * Computes the replacement string.
- *
- * @return the replacement string
- */
- private String computeReplacementString() {
- int proposalKind= fProposal.getKind();
- String qualifiedTypeName= null;
- char[] qualifiedType= null;
- if (proposalKind == CompletionProposal.TYPE_IMPORT) {
- qualifiedType= fProposal.getSignature();
- qualifiedTypeName= String.valueOf(Signature.toCharArray(qualifiedType));
- } else if (proposalKind == CompletionProposal.METHOD_IMPORT || proposalKind == CompletionProposal.FIELD_IMPORT) {
- qualifiedType= fProposal.getDeclarationSignature();
- qualifiedTypeName= String.valueOf(Signature.toCharArray(qualifiedType));
- } else {
- /*
- * In 3.3 we only support the above import proposals, see
- * CompletionProposal#getRequiredProposals()
- */
- Assert.isTrue(false);
- }
-
- /* Add imports if the preference is on. */
- fImportRewrite= createImportRewrite();
- if (fImportRewrite != null) {
- if (proposalKind == CompletionProposal.TYPE_IMPORT) {
- String simpleType= fImportRewrite.addImport(qualifiedTypeName, qualifiedTypeName,fImportContext);
- if (fParentProposalKind == CompletionProposal.METHOD_REF)
- return simpleType + "."; //$NON-NLS-1$
- } else
- fImportRewrite.addStaticImport(qualifiedTypeName, String.valueOf(fProposal.getName()), proposalKind == CompletionProposal.FIELD_IMPORT, fImportContext);
- return ""; //$NON-NLS-1$
- }
-
- // Case where we don't have an import rewrite (see allowAddingImports)
-
- if (fCompilationUnit != null && JavaModelUtil.isImplicitImport(Signature.getQualifier(qualifiedTypeName), fCompilationUnit)) {
- /* No imports for implicit imports. */
-
- if (fProposal.getKind() == CompletionProposal.TYPE_IMPORT && fParentProposalKind == CompletionProposal.FIELD_REF)
- return ""; //$NON-NLS-1$
- qualifiedTypeName= String.valueOf(Signature.getSignatureSimpleName(qualifiedType));
- }
-
- return qualifiedTypeName + "."; //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- try {
- super.apply(document, trigger, offset);
-
- if (fImportRewrite != null && fImportRewrite.hasRecordedChanges()) {
- int oldLen= document.getLength();
- fImportRewrite.rewriteImports(new NullProgressMonitor()).apply(document, TextEdit.UPDATE_REGIONS);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * Creates and returns the import rewrite
- * if imports should be added at all.
- *
- * @return the import rewrite or <code>null</code> if no imports can or should be added
- */
- private ImportRewrite createImportRewrite() {
- if (fCompilationUnit != null && shouldAddImports()) {
- try {
- JavaScriptUnit cu= getASTRoot(fCompilationUnit);
- if (cu == null) {
- ImportRewrite rewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
- fImportContext= null;
- return rewrite;
- } else {
- ImportRewrite rewrite= StubUtility.createImportRewrite(cu, true);
- fImportContext= new ContextSensitiveImportRewriteContext(cu, fInvocationContext.getInvocationOffset(), rewrite);
- return rewrite;
- }
- } catch (CoreException x) {
- JavaScriptPlugin.log(x);
- }
- }
- return null;
- }
-
- private JavaScriptUnit getASTRoot(IJavaScriptUnit compilationUnit) {
- return JavaScriptPlugin.getDefault().getASTProvider().getAST(compilationUnit, ASTProvider.WAIT_NO, new NullProgressMonitor());
- }
-
- /**
- * Returns <code>true</code> if imports should be added. The return value depends on the context
- * and preferences only and does not take into account the contents of the compilation unit or
- * the kind of proposal. Even if <code>true</code> is returned, there may be cases where no
- * imports are added for the proposal. For example:
- * <ul>
- * <li>when completing within the import section</li>
- * <li>when completing informal javadoc references (e.g. within <code>&lt;code&gt;</code>
- * tags)</li>
- * <li>when completing a type that conflicts with an existing import</li>
- * <li>when completing an implicitly imported type (same package, <code>java.lang</code>
- * types)</li>
- * </ul>
- * <p>
- * The decision whether a qualified type or the simple type name should be inserted must take
- * into account these different scenarios.
- * </p>
- *
- * @return <code>true</code> if imports may be added, <code>false</code> if not
- */
- private boolean shouldAddImports() {
- if (isInJavadoc() && !isJavadocProcessingEnabled())
- return false;
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- return preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_ADDIMPORT);
- }
-
- /**
- * Returns whether Javadoc processing is enabled.
- *
- * @return <code>true</code> if Javadoc processing is enabled, <code>false</code> otherwise
- */
- private boolean isJavadocProcessingEnabled() {
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- boolean processJavadoc;
- if (project == null)
- processJavadoc= JavaScriptCore.ENABLED.equals(JavaScriptCore.getOption(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT));
- else
- processJavadoc= JavaScriptCore.ENABLED.equals(project.getOption(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT, true));
- return processJavadoc;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaAutoIndentStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaAutoIndentStrategy.java
deleted file mode 100644
index da476626..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaAutoIndentStrategy.java
+++ /dev/null
@@ -1,1362 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Nikolay Metchev - Fixed https://bugs.eclipse.org/bugs/show_bug.cgi?id=29909
- * Tom Eicher (Avaloq Evolution AG) - block selection mode
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.DocumentRewriteSession;
-import org.eclipse.jface.text.DocumentRewriteSessionType;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.rules.FastPartitioner;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.DoStatement;
-import org.eclipse.wst.jsdt.core.dom.Expression;
-import org.eclipse.wst.jsdt.core.dom.ForStatement;
-import org.eclipse.wst.jsdt.core.dom.IfStatement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.core.dom.WhileStatement;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.FastJavaPartitionScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaIndenter;
-import org.eclipse.wst.jsdt.internal.ui.text.Symbols;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-
-/**
- * Auto indent strategy sensitive to brackets.
- */
-public class JavaAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
-
- /** The line comment introducer. Value is "{@value}" */
- private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
-
- private static class CompilationUnitInfo {
-
- char[] buffer;
- int delta;
-
- CompilationUnitInfo(char[] buffer, int delta) {
- this.buffer= buffer;
- this.delta= delta;
- }
- }
-
-
- private boolean fCloseBrace;
- private boolean fIsSmartMode;
- private boolean fIsSmartTab;
-
- private String fPartitioning;
- private final IJavaScriptProject fProject;
- private static IScanner fgScanner= ToolFactory.createScanner(false, false, false, false);
- /**
- * The viewer.
- * @since 3.5
- */
- private final ISourceViewer fViewer;
-
- /**
- * Creates a new Java auto indent strategy for the given document partitioning.
- *
- * @param partitioning the document partitioning
- * @param project the project to get formatting preferences from, or null to use default preferences
- * @param viewer the source viewer that this strategy is attached to
- */
- public JavaAutoIndentStrategy(String partitioning, IJavaScriptProject project, ISourceViewer viewer) {
- fPartitioning= partitioning;
- fProject= project;
- fViewer= viewer;
- }
-
- private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
-
- int bracketCount= 0;
- while (startOffset < endOffset) {
- char curr= d.getChar(startOffset);
- startOffset++;
- switch (curr) {
- case '/' :
- if (startOffset < endOffset) {
- char next= d.getChar(startOffset);
- if (next == '*') {
- // a comment starts, advance to the comment end
- startOffset= getCommentEnd(d, startOffset + 1, endOffset);
- } else if (next == '/') {
- // '//'-comment: nothing to do anymore on this line
- startOffset= endOffset;
- }
- }
- break;
- case '*' :
- if (startOffset < endOffset) {
- char next= d.getChar(startOffset);
- if (next == '/') {
- // we have been in a comment: forget what we read before
- bracketCount= 0;
- startOffset++;
- }
- }
- break;
- case '{' :
- bracketCount++;
- ignoreCloseBrackets= false;
- break;
- case '}' :
- if (!ignoreCloseBrackets) {
- bracketCount--;
- }
- break;
- case '"' :
- case '\'' :
- startOffset= getStringEnd(d, startOffset, endOffset, curr);
- break;
- default :
- }
- }
- return bracketCount;
- }
-
- // ----------- bracket counting ------------------------------------------------------
-
- private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
- while (offset < endOffset) {
- char curr= d.getChar(offset);
- offset++;
- if (curr == '*') {
- if (offset < endOffset && d.getChar(offset) == '/') {
- return offset + 1;
- }
- }
- }
- return endOffset;
- }
-
- 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);
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-
- private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
- while (offset < endOffset) {
- char curr= d.getChar(offset);
- offset++;
- if (curr == '\\') {
- // ignore escaped characters
- offset++;
- } else if (curr == ch) {
- return offset;
- }
- }
- return endOffset;
- }
-
- 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);
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
- JavaIndenter indenter= new JavaIndenter(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, true, false, false);
- int indLine= d.getLineOfOffset(reference);
- if (indLine != -1 && indLine != line) {
- // take the indent of the found line
- StringBuffer replaceText= new StringBuffer(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) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
- if (c.offset < 1 || d.getLength() == 0)
- return;
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
-
- int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
-
- try {
- // current line
- int line= d.getLineOfOffset(p);
- int lineOffset= d.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
- return;
-
- // line of last Java code
- int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine= d.getLineOfOffset(pos);
-
- // only shift if the last java line is further up and is a braceless block candidate
- if (lastLine < line) {
-
- JavaIndenter indenter= new JavaIndenter(d, scanner, fProject);
- StringBuffer 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) {
- JavaScriptPlugin.log(e);
- }
-
- }
-
- private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
- JavaIndenter indenter= new JavaIndenter(d, scanner, fProject);
- StringBuffer indent= indenter.computeIndentation(c.offset);
- if (indent == null)
- indent= new StringBuffer();
-
- int docLength= d.getLength();
- if (c.offset == -1 || docLength == 0)
- return;
-
- try {
- int p= (c.offset == docLength ? c.offset - 1 : c.offset);
- int line= d.getLineOfOffset(p);
-
- StringBuffer buf= new StringBuffer(c.text + indent);
-
-
- IRegion reg= d.getLineInformation(line);
- int lineEnd= reg.getOffset() + reg.getLength();
-
- int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
- c.length= Math.max(contentStart - c.offset, 0);
-
- int start= reg.getOffset();
- ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start, true);
- if (IJavaScriptPartitions.JAVA_DOC.equals(region.getType()))
- start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
-
- // insert closing brace on new line after an unclosed opening brace
- if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) {
- 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));
- StringBuffer reference= null;
- int nonWS= findEndOfWhiteSpace(d, start, lineEnd);
- if (nonWS < c.offset && d.getChar(nonWS) == '{')
- reference= new StringBuffer(d.get(start, nonWS - start));
- else
- reference= indenter.getReferenceIndentation(c.offset);
- if (reference != null)
- buf.append(reference);
- 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 != JavaHeuristicScanner.NOT_FOUND && d.getChar(firstCharPos) == '{') {
- c.caretOffset= c.offset + buf.length();
- c.shiftsCaret= false;
-
- StringBuffer reference= null;
- int nonWS= findEndOfWhiteSpace(d, start, lineEnd);
- if (nonWS < c.offset && d.getChar(nonWS) == '{')
- reference= new StringBuffer(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) {
- JavaScriptPlugin.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
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- int pos= offset;
- int length= max;
- int scanTo= scanner.scanForward(pos, length, '}');
- if (scanTo == -1)
- scanTo= length;
-
- int closingParen= findClosingParenToLeft(scanner, pos) - 1;
- boolean hasNewToken= looksLikeAnonymousClassDef(document, partitioning, scanner, pos);
- int openingParen= -1;
- while (true) {
- int startScan= closingParen + 1;
- closingParen= scanner.scanForward(startScan, scanTo, ')');
- if (closingParen == -1) {
- if (hasNewToken && openingParen != -1)
- return openingParen + 1;
- break;
- }
-
- 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;
-
- if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1))
- return closingParen + 1;
-
- }
-
- 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 java 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(JavaHeuristicScanner scanner, int position) {
- if (position < 1)
- return position;
-
- if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN)
- return scanner.getPosition() + 1;
- return position;
- }
-
- /**
- * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
- * contains the <code>new</code> keyword.
- *
- * @param document the document being modified
- * @param offset the first character position in <code>document</code> to be considered
- * @param length the length of the character range to be considered
- * @param partitioning the document partitioning
- * @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
- */
- private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
- Assert.isTrue(length >= 0);
- Assert.isTrue(offset >= 0);
- Assert.isTrue(offset + length < document.getLength() + 1);
-
- try {
- String text= document.get(offset, length);
- int pos= text.indexOf("new"); //$NON-NLS-1$
-
- while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
- pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
-
- if (pos < 0)
- return false;
-
- if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
- return false;
-
- if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
- return false;
-
- return true;
-
- } catch (BadLocationException e) {
- }
- return false;
- }
-
- /**
- * Checks whether the content of <code>document</code> at <code>position</code> looks like an
- * anonymous class definition. <code>position</code> must be to the left of the opening
- * parenthesis of the definition's parameter list.
- *
- * @param document the document being modified
- * @param partitioning the document partitioning
- * @param scanner the scanner
- * @param position the first character position in <code>document</code> to be considered
- * @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
- */
- private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) {
- int previousCommaParenEqual= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '(', '='});
- if (previousCommaParenEqual == -1 || position < previousCommaParenEqual + 5) // 2 for borders, 3 for "new"
- return false;
-
- if (isNewMatch(document, previousCommaParenEqual + 1, position - previousCommaParenEqual - 2, partitioning))
- return true;
-
- return false;
- }
-
- /**
- * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
- *
- * @param document the document being modified
- * @param position the position to be checked
- * @param partitioning the document partitioning
- * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
- */
- private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
- Assert.isTrue(position >= 0);
- Assert.isTrue(position <= document.getLength());
-
- try {
- ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
- return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
-
- } catch (BadLocationException e) {
- }
-
- return false;
- }
-
- private boolean isClosed(IDocument document, int offset, int length) {
-
- CompilationUnitInfo info= getCompilationUnitForMethod(document, offset);
- if (info == null)
- return false;
-
- JavaScriptUnit compilationUnit= null;
- try {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(info.buffer);
- compilationUnit= (JavaScriptUnit) parser.createAST(null);
- } catch (ArrayIndexOutOfBoundsException x) {
- // work around for parser problem
- return false;
- }
-
- IProblem[] problems= compilationUnit.getProblems();
- for (int i= 0; i != problems.length; ++i) {
- if (problems[i].getID() == IProblem.UnmatchedBracket)
- return true;
- }
-
- final int relativeOffset= offset - info.delta;
-
- ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
-
- if (length == 0) {
- while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
- node= node.getParent();
- }
-
- if (node == null)
- return false;
-
- switch (node.getNodeType()) {
- case ASTNode.BLOCK:
- return getBlockBalance(document, offset, fPartitioning) <= 0;
-
- case ASTNode.IF_STATEMENT:
- {
- IfStatement ifStatement= (IfStatement) node;
- Expression expression= ifStatement.getExpression();
- IRegion expressionRegion= createRegion(expression, info.delta);
- Statement thenStatement= ifStatement.getThenStatement();
- IRegion thenRegion= createRegion(thenStatement, info.delta);
-
- // between expression and then statement
- if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
- return thenStatement != null;
-
- Statement elseStatement= ifStatement.getElseStatement();
- IRegion elseRegion= createRegion(elseStatement, info.delta);
-
- if (elseStatement != null) {
- int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
- int sourceLength= elseRegion.getOffset() - sourceOffset;
- IRegion elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
- return elseToken != null && elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset();
- }
- }
- break;
-
- case ASTNode.WHILE_STATEMENT:
- case ASTNode.FOR_STATEMENT:
- {
- Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
- IRegion expressionRegion= createRegion(expression, info.delta);
- Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
- IRegion bodyRegion= createRegion(body, info.delta);
-
- // between expression and body statement
- if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
- return body != null;
- }
- break;
-
- case ASTNode.DO_STATEMENT:
- {
- DoStatement doStatement= (DoStatement) node;
- IRegion doRegion= createRegion(doStatement, info.delta);
- Statement body= doStatement.getBody();
- IRegion bodyRegion= createRegion(body, info.delta);
-
- if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
- return body != null;
- }
- break;
- }
-
- return true;
- }
-
- /**
- * Installs a java partitioner with <code>document</code>.
- *
- * @param document the document
- */
- private static void installJavaStuff(Document document) {
- String[] types= new String[] {
- IJavaScriptPartitions.JAVA_DOC,
- IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_STRING,
- IJavaScriptPartitions.JAVA_CHARACTER,
- IDocument.DEFAULT_CONTENT_TYPE
- };
- FastPartitioner partitioner= new FastPartitioner(new FastJavaPartitionScanner(), types);
- partitioner.connect(document);
- document.setDocumentPartitioner(IJavaScriptPartitions.JAVA_PARTITIONING, partitioner);
- }
-
- /**
- * Installs a java partitioner with <code>document</code>.
- *
- * @param document the document
- */
- private static void removeJavaStuff(Document document) {
- document.setDocumentPartitioner(IJavaScriptPartitions.JAVA_PARTITIONING, null);
- }
-
- private void smartPaste(IDocument document, DocumentCommand command) {
- int newOffset= command.offset;
- int newLength= command.length;
- String newText= command.text;
-
- try {
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- JavaIndenter indenter= new JavaIndenter(document, scanner, fProject);
- int offset= newOffset;
-
- // reference position to get the indent from
- int refOffset= indenter.findReferencePosition(offset);
- if (refOffset == JavaHeuristicScanner.NOT_FOUND)
- return;
- int peerOffset= getPeerPosition(document, command);
- peerOffset= indenter.findReferencePosition(peerOffset);
- 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
- IRegion refLine= document.getLineInformationOfOffset(refOffset);
- String prefix= document.get(refLine.getOffset(), newOffset - refLine.getOffset());
-
- // handle the indentation computation inside a temporary document
- Document temp= new Document(prefix + newText);
- DocumentRewriteSession session= temp.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
- scanner= new JavaHeuristicScanner(temp);
- indenter= new JavaIndenter(temp, scanner, fProject);
- installJavaStuff(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;
- StringBuffer addition= new StringBuffer();
- int insertLength= 0;
- int first= document.computeNumberOfLines(prefix) + firstLine; // don't format first line
- int lines= temp.getNumberOfLines();
- int tabLength= getVisualTabLengthPreference();
- boolean changed= false;
- 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= getCurrentIndent(temp, l);
- StringBuffer correct= indenter.computeIndentation(lineOffset);
- if (correct == null)
- return; // bail out
-
- insertLength= subtractIndent(correct, current, addition, tabLength);
- 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;
- }
- removeJavaStuff(temp);
- } else {
- changed= insertLength != 0;
- }
- }
-
- // relatively indent all pasted lines
- if (insertLength > 0)
- addIndent(temp, l, addition, tabLength);
- else if (insertLength < 0)
- cutIndent(temp, l, -insertLength, tabLength);
-
- }
-
- temp.stopRewriteSession(session);
- newText= temp.get(prefix.length(), temp.getLength() - prefix.length());
-
- command.offset= newOffset;
- command.length= newLength;
- command.text= newText;
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
-
- }
-
- /**
- * 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. The space before the asterisk in a javadoc-like
- * comment is not considered part of the indentation.
- *
- * @param document the document
- * @param line the line
- * @return the indentation of <code>line</code> in <code>document</code>
- * @throws BadLocationException if the document is changed concurrently
- */
- private static String getCurrentIndent(Document document, int line) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // go behind line comments
- int to= from;
- while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
- to += 2;
-
- while (to < endOffset) {
- char ch= document.getChar(to);
- if (!Character.isWhitespace(ch))
- break;
- to++;
- }
-
- // don't count the space before javadoc like, asterisk-style comment lines
- if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
- String type= TextUtilities.getContentType(document, IJavaScriptPartitions.JAVA_PARTITIONING, to, true);
- if (type.equals(IJavaScriptPartitions.JAVA_DOC) || type.equals(IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT))
- to--;
- }
-
- return document.get(from, to - from);
- }
-
- /**
- * 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 (might 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
- * @param tabLength the length of a tab
- * @return the difference in length of <code>correct</code> and <code>current</code>
- */
- private int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference, int tabLength) {
- int c1= computeVisualLength(correct, tabLength);
- int c2= computeVisualLength(current, tabLength);
- 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, tabLength);
- }
-
-
- 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 tabLength the length of a tab
- * @throws BadLocationException on concurrent document modification
- */
- private void addIndent(Document document, int line, CharSequence indent, int tabLength) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int insert= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // Compute insert after all leading line comment markers
- int newInsert= insert;
- while (newInsert < endOffset - 2 && document.get(newInsert, 2).equals(LINE_COMMENT))
- newInsert += 2;
-
- // Heuristic to check whether it is commented code or just a comment
- if (newInsert > insert) {
- int whitespaceCount= 0;
- int i= newInsert;
- while (i < endOffset - 1) {
- char ch= document.get(i, 1).charAt(0);
- if (!Character.isWhitespace(ch))
- break;
- whitespaceCount= whitespaceCount + computeVisualLength(ch, tabLength);
- i++;
- }
-
- if (whitespaceCount != 0 && whitespaceCount >= CodeFormatterUtil.getIndentWidth(fProject))
- insert= newInsert;
- }
-
- // 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 tabLength the length of a tab
- * @throws BadLocationException on concurrent document modification
- */
- private void cutIndent(Document document, int line, int toDelete, int tabLength) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- // 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, tabLength);
- if (toDelete >= 0)
- to++;
- else
- break;
- }
-
- document.replace(from, to - from, ""); //$NON-NLS-1$
- }
-
- /**
- * Returns the visual length of a given <code>CharSequence</code> taking into
- * account the visual tabulator length.
- *
- * @param seq the string to measure
- * @param tabLength the length of a tab
- * @return the visual length of <code>seq</code>
- */
- private int computeVisualLength(CharSequence seq, int tabLength) {
- int size= 0;
-
- for (int i= 0; i < seq.length(); i++) {
- char ch= seq.charAt(i);
- if (ch == '\t') {
- if (tabLength != 0)
- size += tabLength - size % tabLength;
- // 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
- * @param tabLength the length of a tab
- * @return the visual length of <code>ch</code>
- */
- private int computeVisualLength(char ch, int tabLength) {
- if (ch == '\t')
- return tabLength;
- else
- 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(fProject);
- }
-
- /**
- * The preference setting that tells whether to insert spaces when pressing the Tab key.
- *
- * @return <code>true</code> if spaces are inserted when pressing the Tab key
- * @since 3.5
- */
- private boolean isInsertingSpacesForTab() {
- return JavaScriptCore.SPACE.equals(getCoreOption(fProject, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
- }
-
- /**
- * Returns the possibly <code>project</code>-specific core preference defined under
- * <code>key</code>.
- *
- * @param project the project to get the preference from, or <code>null</code> to get the global
- * preference
- * @param key the key of the preference
- * @return the value of the preference
- * @since 3.5
- */
- private static String getCoreOption(IJavaScriptProject project, String key) {
- if (project == null)
- return JavaScriptCore.getOption(key);
- return project.getOption(key, true);
- }
-
- 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);
- installJavaStuff(pasted);
- int firstPeer= command.offset;
-
- JavaHeuristicScanner pScanner= new JavaHeuristicScanner(pasted);
- JavaHeuristicScanner dScanner= new JavaHeuristicScanner(document);
-
- // add scope relevant after context to peer search
- int afterToken= dScanner.nextToken(command.offset + command.length, JavaHeuristicScanner.UNBOUND);
- try {
- switch (afterToken) {
- case Symbols.TokenRBRACE:
- pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
- break;
- case Symbols.TokenRPAREN:
- pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
- break;
- case Symbols.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, JavaHeuristicScanner.UNBOUND);
- pPos= pScanner.getPosition();
- switch (token) {
- case Symbols.TokenLBRACE:
- case Symbols.TokenLBRACKET:
- case Symbols.TokenLPAREN:
- pPos= skipScope(pScanner, pPos, token);
- if (pPos == JavaHeuristicScanner.NOT_FOUND)
- return firstPeer;
- break; // closed scope -> keep searching
- case Symbols.TokenRBRACE:
- int peer= dScanner.findOpeningPeer(dPos, '{', '}');
- dPos= peer - 1;
- if (peer == JavaHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
- case Symbols.TokenRBRACKET:
- peer= dScanner.findOpeningPeer(dPos, '[', ']');
- dPos= peer - 1;
- if (peer == JavaHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
- case Symbols.TokenRPAREN:
- peer= dScanner.findOpeningPeer(dPos, '(', ')');
- dPos= peer - 1;
- if (peer == JavaHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
- case Symbols.TokenCASE:
- case Symbols.TokenDEFAULT:
- JavaIndenter indenter= new JavaIndenter(document, dScanner, fProject);
- peer= indenter.findReferencePosition(dPos, false, false, false, true);
- if (peer == JavaHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
-
- case Symbols.TokenEOF:
- return firstPeer;
- default:
- // keep searching
- }
- }
- }
-
- /**
- * Skips the scope opened by <code>token</code>.
- *
- * @param scanner the scanner
- * @param start the start position
- * @param token the token
- * @return the position after the scope or <code>JavaHeuristicScanner.NOT_FOUND</code>
- */
- private static int skipScope(JavaHeuristicScanner scanner, int start, int token) {
- int openToken= token;
- int closeToken;
- switch (token) {
- case Symbols.TokenLPAREN:
- closeToken= Symbols.TokenRPAREN;
- break;
- case Symbols.TokenLBRACKET:
- closeToken= Symbols.TokenRBRACKET;
- break;
- case Symbols.TokenLBRACE:
- closeToken= Symbols.TokenRBRACE;
- break;
- default:
- Assert.isTrue(false);
- return -1; // dummy
- }
-
- int depth= 1;
- int p= start;
-
- while (true) {
- int tok= scanner.nextToken(p, JavaHeuristicScanner.UNBOUND);
- p= scanner.getPosition();
-
- if (tok == openToken) {
- depth++;
- } else if (tok == closeToken) {
- depth--;
- if (depth == 0)
- return p + 1;
- } else if (tok == Symbols.TokenEOF) {
- return JavaHeuristicScanner.NOT_FOUND;
- }
- }
- }
-
- private boolean isLineDelimiter(IDocument document, String text) {
- String[] delimiters= document.getLegalLineDelimiters();
- if (delimiters != null)
- return TextUtilities.equals(delimiters, text) > -1;
- return false;
- }
-
- 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;
- }
- }
-
- private void smartIndentUponE(IDocument d, DocumentCommand c) {
- if (c.offset < 4 || d.getLength() == 0)
- return;
-
- try {
- String content= d.get(c.offset - 3, 3);
- if (content.equals("els")) { //$NON-NLS-1$
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
- int p= c.offset - 3;
-
- // current line
- int line= d.getLineOfOffset(p);
- int lineOffset= d.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
- return;
-
- // line of last Java code
- int pos= scanner.findNonWhitespaceBackward(p - 1, JavaHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine= d.getLineOfOffset(pos);
-
- // only shift if the last java line is further up and is a braceless block candidate
- if (lastLine < line) {
-
- JavaIndenter indenter= new JavaIndenter(d, scanner, fProject);
- int ref= indenter.findReferencePosition(p, true, false, false, false);
- if (ref == JavaHeuristicScanner.NOT_FOUND)
- return;
- int refLine= d.getLineOfOffset(ref);
- String indent= getIndentOfLine(d, refLine);
-
- if (indent != null) {
- c.text= indent.toString() + "else"; //$NON-NLS-1$
- c.length += c.offset - lineOffset;
- c.offset= lineOffset;
- }
- }
-
- return;
- }
-
- if (content.equals("cas")) { //$NON-NLS-1$
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
- int p= c.offset - 3;
-
- // current line
- int line= d.getLineOfOffset(p);
- int lineOffset= d.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
- return;
-
- // line of last Java code
- int pos= scanner.findNonWhitespaceBackward(p - 1, JavaHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine= d.getLineOfOffset(pos);
-
- // only shift if the last java line is further up and is a braceless block candidate
- if (lastLine < line) {
-
- JavaIndenter indenter= new JavaIndenter(d, scanner, fProject);
- int ref= indenter.findReferencePosition(p, false, false, false, true);
- if (ref == JavaHeuristicScanner.NOT_FOUND)
- return;
- int refLine= d.getLineOfOffset(ref);
- int nextToken= scanner.nextToken(ref, JavaHeuristicScanner.UNBOUND);
- String indent;
- if (nextToken == Symbols.TokenCASE || nextToken == Symbols.TokenDEFAULT)
- indent= getIndentOfLine(d, 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) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /*
- * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
- */
- public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
- try {
- if (c.doit == false)
- return;
-
- clearCachedValues();
-
- if (!fIsSmartMode) {
- super.customizeDocumentCommand(d, c);
- return;
- }
-
- if (!fIsSmartTab && isRepresentingTab(c.text))
- return;
-
- if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
- smartIndentAfterNewLine(d, c);
- else if (c.text.length() == 1)
- smartIndentOnKeypress(d, c);
- else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
- if (fViewer == null || fViewer.getTextWidget() == null || !fViewer.getTextWidget().getBlockSelection())
- smartPaste(d, c); // no smart backspace for paste
- } catch(IllegalArgumentException e) {
- // ignore
- }
-
- }
-
- /**
- * Tells whether the given inserted string represents hitting the Tab key.
- *
- * @param text the text to check
- * @return <code>true</code> if the text represents hitting the Tab key
- * @since 3.5
- */
- private boolean isRepresentingTab(String text) {
- if (text == null)
- return false;
-
- if (isInsertingSpacesForTab()) {
- if (text.length() == 0 || text.length() > getVisualTabLengthPreference())
- return false;
- for (int i= 0; i < text.length(); i++) {
- if (text.charAt(i) != ' ')
- return false;
- }
- return true;
- } else
- return text.length() == 1 && text.charAt(0) == '\t';
- }
-
- private static IPreferenceStore getPreferenceStore() {
- return JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- }
-
- private boolean closeBrace() {
- return fCloseBrace;
- }
-
- private void clearCachedValues() {
- IPreferenceStore preferenceStore= getPreferenceStore();
- fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
- fIsSmartTab= preferenceStore.getBoolean(PreferenceConstants.EDITOR_SMART_TAB);
- fIsSmartMode= computeSmartMode();
- }
-
- private boolean computeSmartMode() {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IEditorPart part= page.getActiveEditor();
- if (part instanceof ITextEditorExtension3) {
- ITextEditorExtension3 extension= (ITextEditorExtension3) part;
- return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
- }
- }
- return false;
- }
-
- private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset) {
- try {
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
-
- IRegion sourceRange= scanner.findSurroundingBlock(offset);
- if (sourceRange == null)
- return null;
- String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
-
- StringBuffer contents= new StringBuffer();
- contents.append("function ____f() {"); //$NON-NLS-1$
- final int methodOffset= contents.length();
- contents.append(source);
- contents.append('}');
-
- char[] buffer= contents.toString().toCharArray();
-
- return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
-
- return null;
- }
-
- /**
- * 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 the document
- * @param offset the offset
- * @param partitioning the 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;
-
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(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;
- }
- }
-
- private static IRegion createRegion(ASTNode node, int delta) {
- return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
- }
-
- private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
-
- try {
-
- final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
-
- fgScanner.setSource(source.toCharArray());
-
- int id= fgScanner.getNextToken();
- while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
- id= fgScanner.getNextToken();
-
- if (id == ITerminalSymbols.TokenNameEOF)
- return null;
-
- int tokenOffset= fgScanner.getCurrentTokenStartPosition();
- int tokenLength= fgScanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
- return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
-
- } catch (InvalidInputException x) {
- return null;
- } catch (BadLocationException x) {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCodeScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCodeScanner.java
deleted file mode 100644
index bb416b8a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCodeScanner.java
+++ /dev/null
@@ -1,561 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Philippe Ombredanne <pombredanne@nexb.com> - https://bugs.eclipse.org/bugs/show_bug.cgi?id=150989
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IRule;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.SingleLineRule;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.text.rules.WhitespaceRule;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings;
-import org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule;
-import org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWhitespaceDetector;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordDetector;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants;
-
-
-/**
- * A Java code scanner.
- */
-public final class JavaCodeScanner extends AbstractJavaScanner {
-
- /**
- * Rule to detect java operators.
- *
- *
- */
- private static final class OperatorRule implements IRule {
-
- /** Java operators */
- private final char[] JAVA_OPERATORS= { ';', '.', '=', '/', '\\', '+', '-', '*', '<', '>', ':', '?', '!', ',', '|', '&', '^', '%', '~'};
- /** Token to return for this rule */
- private final IToken fToken;
-
- /**
- * Creates a new operator rule.
- *
- * @param token Token to use for this rule
- */
- public OperatorRule(IToken token) {
- fToken= token;
- }
-
- /**
- * Is this character an operator character?
- *
- * @param character Character to determine whether it is an operator character
- * @return <code>true</code> iff the character is an operator, <code>false</code> otherwise.
- */
- public boolean isOperator(char character) {
- for (int index= 0; index < JAVA_OPERATORS.length; index++) {
- if (JAVA_OPERATORS[index] == character)
- return true;
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.rules.IRule#evaluate(org.eclipse.jface.text.rules.ICharacterScanner)
- */
- public IToken evaluate(ICharacterScanner scanner) {
-
- int character= scanner.read();
- if (isOperator((char) character)) {
- do {
- character= scanner.read();
- } while (isOperator((char) character));
- scanner.unread();
- return fToken;
- } else {
- scanner.unread();
- return Token.UNDEFINED;
- }
- }
- }
-
- /**
- * Rule to detect java brackets.
- *
- *
- */
- private static final class BracketRule implements IRule {
-
- /** Java brackets */
- private final char[] JAVA_BRACKETS= { '(', ')', '{', '}', '[', ']' };
- /** Token to return for this rule */
- private final IToken fToken;
-
- /**
- * Creates a new bracket rule.
- *
- * @param token Token to use for this rule
- */
- public BracketRule(IToken token) {
- fToken= token;
- }
-
- /**
- * Is this character a bracket character?
- *
- * @param character Character to determine whether it is a bracket character
- * @return <code>true</code> iff the character is a bracket, <code>false</code> otherwise.
- */
- public boolean isBracket(char character) {
- for (int index= 0; index < JAVA_BRACKETS.length; index++) {
- if (JAVA_BRACKETS[index] == character)
- return true;
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.rules.IRule#evaluate(org.eclipse.jface.text.rules.ICharacterScanner)
- */
- public IToken evaluate(ICharacterScanner scanner) {
-
- int character= scanner.read();
- if (isBracket((char) character)) {
- do {
- character= scanner.read();
- } while (isBracket((char) character));
- scanner.unread();
- return fToken;
- } else {
- scanner.unread();
- return Token.UNDEFINED;
- }
- }
- }
-
-
- private static class VersionedWordMatcher extends CombinedWordRule.WordMatcher implements ISourceVersionDependent {
-
- private final IToken fDefaultToken;
- private final String fVersion;
- private boolean fIsVersionMatch;
-
- public VersionedWordMatcher(IToken defaultToken, String version, String currentVersion) {
- fDefaultToken= defaultToken;
- fVersion= version;
- setSourceVersion(currentVersion);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String)
- */
- public void setSourceVersion(String version) {
- fIsVersionMatch= fVersion.compareTo(version) <= 0;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher#evaluate(org.eclipse.jface.text.rules.ICharacterScanner, org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.CharacterBuffer)
- */
- public IToken evaluate(ICharacterScanner scanner, CombinedWordRule.CharacterBuffer word) {
- IToken token= super.evaluate(scanner, word);
-
- if (fIsVersionMatch || token.isUndefined())
- return token;
-
- return fDefaultToken;
- }
- }
-
- /**
- * An annotation rule matches the '@' symbol, any following whitespace and
- * optionally a following <code>interface</code> keyword.
- *
- * It does not match if there is a comment between the '@' symbol and
- * the identifier. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=82452
- *
- *
- */
-// private static class AnnotationRule implements IRule, ISourceVersionDependent {
-// /**
-// * A resettable scanner supports marking a position in a scanner and
-// * unreading back to the marked position.
-// */
-// private static final class ResettableScanner implements ICharacterScanner {
-// private final ICharacterScanner fDelegate;
-// private int fReadCount;
-//
-// /**
-// * Creates a new resettable scanner that will forward calls
-// * to <code>scanner</code>, but store a marked position.
-// *
-// * @param scanner the delegate scanner
-// */
-// public ResettableScanner(final ICharacterScanner scanner) {
-// Assert.isNotNull(scanner);
-// fDelegate= scanner;
-// mark();
-// }
-//
-// /*
-// * @see org.eclipse.jface.text.rules.ICharacterScanner#getColumn()
-// */
-// public int getColumn() {
-// return fDelegate.getColumn();
-// }
-//
-// /*
-// * @see org.eclipse.jface.text.rules.ICharacterScanner#getLegalLineDelimiters()
-// */
-// public char[][] getLegalLineDelimiters() {
-// return fDelegate.getLegalLineDelimiters();
-// }
-//
-// /*
-// * @see org.eclipse.jface.text.rules.ICharacterScanner#read()
-// */
-// public int read() {
-// int ch= fDelegate.read();
-// if (ch != ICharacterScanner.EOF)
-// fReadCount++;
-// return ch;
-// }
-//
-// /*
-// * @see org.eclipse.jface.text.rules.ICharacterScanner#unread()
-// */
-// public void unread() {
-// if (fReadCount > 0)
-// fReadCount--;
-// fDelegate.unread();
-// }
-//
-// /**
-// * Marks an offset in the scanned content.
-// */
-// public void mark() {
-// fReadCount= 0;
-// }
-//
-// /**
-// * Resets the scanner to the marked position.
-// */
-// public void reset() {
-// while (fReadCount > 0)
-// unread();
-//
-// while (fReadCount < 0)
-// read();
-// }
-// }
-//
-// private final IWhitespaceDetector fWhitespaceDetector= new JavaWhitespaceDetector();
-// private final IWordDetector fWordDetector= new JavaWordDetector();
-// private final IToken fInterfaceToken;
-// private final IToken fAtToken;
-// private final String fVersion;
-// private boolean fIsVersionMatch;
-//
-// /**
-// * Creates a new rule.
-// *
-// * @param interfaceToken the token to return if
-// * <code>'@\s*interface'</code> is matched
-// * @param atToken the token to return if <code>'@'</code>
-// * is matched, but not <code>'@\s*interface'</code>
-// * @param version the lowest <code>JavaScriptCore.COMPILER_SOURCE</code>
-// * version that this rule is enabled
-// * @param currentVersion the current
-// * <code>JavaScriptCore.COMPILER_SOURCE</code> version
-// */
-// public AnnotationRule(IToken interfaceToken, Token atToken, String version, String currentVersion) {
-// fInterfaceToken= interfaceToken;
-// fAtToken= atToken;
-// fVersion= version;
-// setSourceVersion(currentVersion);
-// }
-//
-// /*
-// * @see org.eclipse.jface.text.rules.IRule#evaluate(org.eclipse.jface.text.rules.ICharacterScanner)
-// */
-// public IToken evaluate(ICharacterScanner scanner) {
-// if (!fIsVersionMatch)
-// return Token.UNDEFINED;
-//
-// ResettableScanner resettable= new ResettableScanner(scanner);
-// if (resettable.read() == '@')
-// return readAnnotation(resettable);
-//
-// resettable.reset();
-// return Token.UNDEFINED;
-// }
-//
-// private IToken readAnnotation(ResettableScanner scanner) {
-// scanner.mark();
-// skipWhitespace(scanner);
-// if (readInterface(scanner)) {
-// return fInterfaceToken;
-// } else {
-// scanner.reset();
-// return fAtToken;
-// }
-// }
-//
-// private boolean readInterface(ICharacterScanner scanner) {
-// int ch= scanner.read();
-// int i= 0;
-// while (i < INTERFACE.length() && INTERFACE.charAt(i) == ch) {
-// i++;
-// ch= scanner.read();
-// }
-// if (i < INTERFACE.length())
-// return false;
-//
-// if (fWordDetector.isWordPart((char) ch))
-// return false;
-//
-// if (ch != ICharacterScanner.EOF)
-// scanner.unread();
-//
-// return true;
-// }
-//
-// private boolean skipWhitespace(ICharacterScanner scanner) {
-// while (fWhitespaceDetector.isWhitespace((char) scanner.read())) {
-// // do nothing
-// }
-//
-// scanner.unread();
-// return true;
-// }
-//
-// /*
-// * @see org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String)
-// */
-// public void setSourceVersion(String version) {
-// fIsVersionMatch= fVersion.compareTo(version) <= 0;
-// }
-//
-// }
-
- private static final String SOURCE_VERSION= JavaScriptCore.COMPILER_SOURCE;
-
- static String[] fgKeywords= {
- "abstract", //$NON-NLS-1$
- "break", //$NON-NLS-1$
- "case", "catch", "class", "const", "continue", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "default", "delete", "debugger", "do", //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-1$
- "else", "export", "extends", //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$
- "final", "finally", "for", "function",//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-2$ //$NON-NLS-1$
- "goto", //$NON-NLS-1$
- "if", "implements", "in", "instanceof", "interface", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "new", //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
- "package", "private", "protected", "public", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "static", "super", "switch", "synchronized", //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "this", "throw", "throws", "transient", "try","typeof", //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
- "var", "volatile", //$NON-NLS-1$ //$NON-NLS-2$
- "while", "with" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
-// private static final String INTERFACE= "interface"; //$NON-NLS-1$
- private static final String RETURN= "return"; //$NON-NLS-1$
- private static String[] fgJava14Keywords= { /*"assert"*/ }; //$NON-NLS-1$
- private static String[] fgJava15Keywords= { "enum" }; //$NON-NLS-1$
-
- private static String[] fgTypes= {/* "void", "boolean", "char", "byte", "short", "strictfp", "int", "long", "float", "double" */}; //$NON-NLS-1$ //$NON-NLS-5$ //$NON-NLS-7$ //$NON-NLS-6$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-2$
-
- private static String[] fgConstants= { "false", "null", "true" , "undefined"}; //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-2$ //$NON-NLS-1$
-
- private static final String ANNOTATION_BASE_KEY= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + SemanticHighlightings.ANNOTATION;
- private static final String ANNOTATION_COLOR_KEY= ANNOTATION_BASE_KEY + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX;
-
- private static String[] fgTokenProperties= {
- IJavaScriptColorConstants.JAVA_KEYWORD,
- IJavaScriptColorConstants.JAVA_STRING,
- IJavaScriptColorConstants.JAVA_DEFAULT,
- IJavaScriptColorConstants.JAVA_KEYWORD_RETURN,
- IJavaScriptColorConstants.JAVA_OPERATOR,
- IJavaScriptColorConstants.JAVA_BRACKET,
- ANNOTATION_COLOR_KEY,
- };
-
- private List fVersionDependentRules= new ArrayList(3);
-
- /**
- * Creates a Java code scanner
- *
- * @param manager the color manager
- * @param store the preference store
- */
- public JavaCodeScanner(IColorManager manager, IPreferenceStore store) {
- super(manager, store);
- initialize();
- }
-
- /*
- * @see AbstractJavaScanner#getTokenProperties()
- */
- protected String[] getTokenProperties() {
- return fgTokenProperties;
- }
-
- /*
- * @see AbstractJavaScanner#createRules()
- */
- protected List createRules() {
-
- List rules= new ArrayList();
-
- // Add rule for character constants.
- Token token= getToken(IJavaScriptColorConstants.JAVA_STRING);
- rules.add(new SingleLineRule("'", "'", token, '\\')); //$NON-NLS-2$ //$NON-NLS-1$
-
-
- // Add generic whitespace rule.
- rules.add(new WhitespaceRule(new JavaWhitespaceDetector()));
-
- String version= getPreferenceStore().getString(SOURCE_VERSION);
-
- // Add JLS3 rule for /@\s*interface/ and /@\s*\w+/
-// token= getToken(ANNOTATION_COLOR_KEY);
-// AnnotationRule atInterfaceRule= new AnnotationRule(getToken(IJavaScriptColorConstants.JAVA_KEYWORD), token, JavaScriptCore.VERSION_1_5, version);
-// rules.add(atInterfaceRule);
-// fVersionDependentRules.add(atInterfaceRule);
-
- // Add word rule for new keywords, 4077
- JavaWordDetector wordDetector= new JavaWordDetector();
- token= getToken(IJavaScriptColorConstants.JAVA_DEFAULT);
- CombinedWordRule combinedWordRule= new CombinedWordRule(wordDetector, token);
-
- token= getToken(IJavaScriptColorConstants.JAVA_DEFAULT);
- VersionedWordMatcher j14Matcher= new VersionedWordMatcher(token, JavaScriptCore.VERSION_1_4, version);
-
- token= getToken(IJavaScriptColorConstants.JAVA_KEYWORD);
- for (int i=0; i<fgJava14Keywords.length; i++)
- j14Matcher.addWord(fgJava14Keywords[i], token);
-
- combinedWordRule.addWordMatcher(j14Matcher);
- fVersionDependentRules.add(j14Matcher);
-
- token= getToken(IJavaScriptColorConstants.JAVA_DEFAULT);
- VersionedWordMatcher j15Matcher= new VersionedWordMatcher(token, JavaScriptCore.VERSION_1_5, version);
- token= getToken(IJavaScriptColorConstants.JAVA_KEYWORD);
- for (int i=0; i<fgJava15Keywords.length; i++)
- j15Matcher.addWord(fgJava15Keywords[i], token);
-
- combinedWordRule.addWordMatcher(j15Matcher);
- fVersionDependentRules.add(j15Matcher);
-
- // Add rule for operators
- token= getToken(IJavaScriptColorConstants.JAVA_OPERATOR);
- rules.add(new OperatorRule(token));
-
- // Add rule for brackets
- token= getToken(IJavaScriptColorConstants.JAVA_BRACKET);
- rules.add(new BracketRule(token));
-
- // Add word rule for keyword 'return'.
- CombinedWordRule.WordMatcher returnWordRule= new CombinedWordRule.WordMatcher();
- token= getToken(IJavaScriptColorConstants.JAVA_KEYWORD_RETURN);
- returnWordRule.addWord(RETURN, token);
- combinedWordRule.addWordMatcher(returnWordRule);
-
- // Add word rule for keywords, types, and constants.
- CombinedWordRule.WordMatcher wordRule= new CombinedWordRule.WordMatcher();
- token= getToken(IJavaScriptColorConstants.JAVA_KEYWORD);
- for (int i=0; i<fgKeywords.length; i++)
- wordRule.addWord(fgKeywords[i], token);
- for (int i=0; i<fgTypes.length; i++)
- wordRule.addWord(fgTypes[i], token);
- for (int i=0; i<fgConstants.length; i++)
- wordRule.addWord(fgConstants[i], token);
-
- combinedWordRule.addWordMatcher(wordRule);
-
- rules.add(combinedWordRule);
-
- setDefaultReturnToken(getToken(IJavaScriptColorConstants.JAVA_DEFAULT));
- return rules;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#getBoldKey(java.lang.String)
- */
- protected String getBoldKey(String colorKey) {
- if ((ANNOTATION_COLOR_KEY).equals(colorKey))
- return ANNOTATION_BASE_KEY + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX;
- return super.getBoldKey(colorKey);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#getItalicKey(java.lang.String)
- */
- protected String getItalicKey(String colorKey) {
- if ((ANNOTATION_COLOR_KEY).equals(colorKey))
- return ANNOTATION_BASE_KEY + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX;
- return super.getItalicKey(colorKey);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#getStrikethroughKey(java.lang.String)
- */
- protected String getStrikethroughKey(String colorKey) {
- if ((ANNOTATION_COLOR_KEY).equals(colorKey))
- return ANNOTATION_BASE_KEY + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX;
- return super.getStrikethroughKey(colorKey);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner#getUnderlineKey(java.lang.String)
- */
- protected String getUnderlineKey(String colorKey) {
- if ((ANNOTATION_COLOR_KEY).equals(colorKey))
- return ANNOTATION_BASE_KEY + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX;
- return super.getUnderlineKey(colorKey);
- }
-
- /*
- * @see AbstractJavaScanner#affectsBehavior(PropertyChangeEvent)
- */
- public boolean affectsBehavior(PropertyChangeEvent event) {
- return event.getProperty().equals(SOURCE_VERSION) || super.affectsBehavior(event);
- }
-
- /*
- * @see AbstractJavaScanner#adaptToPreferenceChange(PropertyChangeEvent)
- */
- public void adaptToPreferenceChange(PropertyChangeEvent event) {
-
- if (event.getProperty().equals(SOURCE_VERSION)) {
- Object value= event.getNewValue();
-
- if (value instanceof String) {
- String s= (String) value;
-
- for (Iterator it= fVersionDependentRules.iterator(); it.hasNext();) {
- ISourceVersionDependent dependent= (ISourceVersionDependent) it.next();
- dependent.setSourceVersion(s);
- }
- }
-
- } else if (super.affectsBehavior(event)) {
- super.adaptToPreferenceChange(event);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProcessor.java
deleted file mode 100644
index fbdd27a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProcessor.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Hashtable;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Java completion processor.
- */
-public class JavaCompletionProcessor extends ContentAssistProcessor {
-
- private final static String VISIBILITY= JavaScriptCore.CODEASSIST_VISIBILITY_CHECK;
- private final static String ENABLED= "enabled"; //$NON-NLS-1$
- private final static String DISABLED= "disabled"; //$NON-NLS-1$
-
- private IContextInformationValidator fValidator;
- protected final IEditorPart fEditor;
-
- public JavaCompletionProcessor(IEditorPart editor, ContentAssistant assistant, String partition) {
- super(assistant, partition);
- fEditor= editor;
- }
-
- /**
- * Tells this processor to restrict its proposal to those element
- * visible in the actual invocation context.
- *
- * @param restrict <code>true</code> if proposals should be restricted
- */
- public void restrictProposalsToVisibility(boolean restrict) {
- Hashtable options= JavaScriptCore.getOptions();
- Object value= options.get(VISIBILITY);
- if (value instanceof String) {
- String newValue= restrict ? ENABLED : DISABLED;
- if ( !newValue.equals(value)) {
- options.put(VISIBILITY, newValue);
- JavaScriptCore.setOptions(options);
- }
- }
- }
-
- /**
- * Tells this processor to restrict is proposals to those
- * starting with matching cases.
- *
- * @param restrict <code>true</code> if proposals should be restricted
- */
- public void restrictProposalsToMatchingCases(boolean restrict) {
- // not yet supported
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- if (fValidator == null)
- fValidator= new JavaParameterListValidator();
- return fValidator;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistProcessor#filterAndSort(java.util.List, org.eclipse.core.runtime.IProgressMonitor)
- */
- protected List filterAndSortProposals(List proposals, IProgressMonitor monitor, ContentAssistInvocationContext context) {
- ProposalSorterRegistry.getDefault().getCurrentSorter().sortProposals(context, proposals);
- return proposals;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistProcessor#createContext(org.eclipse.jface.text.ITextViewer, int)
- */
- protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset) {
- return new JavaContentAssistInvocationContext(viewer, offset, fEditor);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java
deleted file mode 100644
index 2c30be78..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-
-public class JavaCompletionProposal extends AbstractJavaCompletionProposal {
-
- /**
- * Creates a new completion proposal. All fields are initialized based on the provided
- * information.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementOffset the offset of the text to be replaced
- * @param replacementLength the length of the text to be replaced
- * @param image the image to display for this proposal
- * @param displayString the string to be displayed for the proposal If set to <code>null</code>,
- * the replacement string will be taken as display string.
- */
- public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
- this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, false);
- }
-
- /**
- * Creates a new completion proposal. All fields are initialized based on the provided
- * information.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementOffset the offset of the text to be replaced
- * @param replacementLength the length of the text to be replaced
- * @param image the image to display for this proposal
- * @param displayString the string to be displayed for the proposal If set to <code>null</code>,
- * the replacement string will be taken as display string.
- * @param relevance the relevance
- * @param inJavadoc <code>true</code> for a javadoc proposal
- *
- */
- public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, boolean inJavadoc) {
- this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, inJavadoc, null);
- }
-
- /**
- * Creates a new completion proposal. All fields are initialized based on the provided
- * information.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementOffset the offset of the text to be replaced
- * @param replacementLength the length of the text to be replaced
- * @param image the image to display for this proposal
- * @param displayString the string to be displayed for the proposal If set to <code>null</code>,
- * the replacement string will be taken as display string.
- * @param relevance the relevance
- * @param inJavadoc <code>true</code> for a javadoc proposal
- * @param invocationContext the invocation context of this completion proposal or <code>null</code> not available
- *
- */
- public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, boolean inJavadoc, JavaContentAssistInvocationContext invocationContext) {
- super(invocationContext);
- Assert.isNotNull(replacementString);
- Assert.isTrue(replacementOffset >= 0);
- Assert.isTrue(replacementLength >= 0);
-
- setReplacementString(replacementString);
- setReplacementOffset(replacementOffset);
- setReplacementLength(replacementLength);
- setImage(image);
- setDisplayString(displayString == null ? replacementString : displayString);
- setRelevance(relevance);
- setCursorPosition(replacementString.length());
- setInJavadoc(inJavadoc);
- setSortString(displayString == null ? replacementString : displayString);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String)
- */
- protected boolean isValidPrefix(String prefix) {
- String word= getDisplayString();
- if (isInJavadoc()) {
- int idx = word.indexOf("{@link "); //$NON-NLS-1$
- if (idx==0) {
- word = word.substring(7);
- } else {
- idx = word.indexOf("{@value "); //$NON-NLS-1$
- if (idx==0) {
- word = word.substring(8);
- }
- }
- } else if (word.indexOf("this.") != -1) { //$NON-NLS-1$
- word= word.substring(word.indexOf("this.") + 5); //$NON-NLS-1$
- }
- return isPrefix(prefix, word);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementText()
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- String string= getReplacementString();
- int pos= string.indexOf('(');
- if (pos > 0)
- return string.subSequence(0, pos);
- else if (string.startsWith("this.")) //$NON-NLS-1$
- return string.substring(5);
- else
- return string;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposalComputer.java
deleted file mode 100644
index 86d0fb8b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposalComputer.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationExtension;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalCollector;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Computes Java completion proposals and context infos.
- *
- *
- */
-public class JavaCompletionProposalComputer implements IJavaCompletionProposalComputer {
-
- private static final class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
-
- private final IContextInformation fContextInformation;
- private int fPosition;
-
- public ContextInformationWrapper(IContextInformation contextInformation) {
- fContextInformation= contextInformation;
- }
-
- /*
- * @see IContextInformation#getContextDisplayString()
- */
- public String getContextDisplayString() {
- return fContextInformation.getContextDisplayString();
- }
-
- /*
- * @see IContextInformation#getImage()
- */
- public Image getImage() {
- return fContextInformation.getImage();
- }
-
- /*
- * @see IContextInformation#getInformationDisplayString()
- */
- public String getInformationDisplayString() {
- return fContextInformation.getInformationDisplayString();
- }
-
- /*
- * @see IContextInformationExtension#getContextInformationPosition()
- */
- public int getContextInformationPosition() {
- return fPosition;
- }
-
- public void setContextInformationPosition(int position) {
- fPosition= position;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContextInformation#equals(java.lang.Object)
- */
- public boolean equals(Object object) {
- if (object instanceof ContextInformationWrapper)
- return fContextInformation.equals(((ContextInformationWrapper) object).fContextInformation);
- else
- return fContextInformation.equals(object);
- }
- }
-
- private String fErrorMessage;
-
- public JavaCompletionProposalComputer() {
- }
-
- protected int guessContextInformationPosition(ContentAssistInvocationContext context) {
- return context.getInvocationOffset();
- }
-
- private List addContextInformations(JavaContentAssistInvocationContext context, int offset, IProgressMonitor monitor) {
- List proposals= internalComputeCompletionProposals(offset, context, monitor);
- List result= new ArrayList(proposals.size());
-
- for (Iterator it= proposals.iterator(); it.hasNext();) {
- ICompletionProposal proposal= (ICompletionProposal) it.next();
- IContextInformation contextInformation= proposal.getContextInformation();
- if (contextInformation != null) {
- ContextInformationWrapper wrapper= new ContextInformationWrapper(contextInformation);
- wrapper.setContextInformationPosition(offset);
- result.add(wrapper);
- }
- }
- return result;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeContextInformation(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (context instanceof JavaContentAssistInvocationContext) {
- JavaContentAssistInvocationContext javaContext= (JavaContentAssistInvocationContext) context;
-
- int contextInformationPosition= guessContextInformationPosition(javaContext);
- List result= addContextInformations(javaContext, contextInformationPosition, monitor);
- return result;
- }
- return Collections.EMPTY_LIST;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (context instanceof JavaContentAssistInvocationContext) {
- JavaContentAssistInvocationContext javaContext= (JavaContentAssistInvocationContext) context;
- return internalComputeCompletionProposals(context.getInvocationOffset(), javaContext, monitor);
- }
- return Collections.EMPTY_LIST;
- }
-
- private List internalComputeCompletionProposals(int offset, JavaContentAssistInvocationContext context, IProgressMonitor monitor) {
- IJavaScriptUnit unit= context.getCompilationUnit();
- if (unit == null)
- return Collections.EMPTY_LIST;
-
- ITextViewer viewer= context.getViewer();
-
- CompletionProposalCollector collector= createCollector(context);
- collector.setInvocationContext(context);
-
- // Allow completions for unresolved types - since 3.3
- collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF, true);
- collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_IMPORT, true);
- collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
-
- collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF, true);
- collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_IMPORT, true);
- collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
-
- // Set the favorite list to propose static members - since 3.3
- collector.setFavoriteReferences(getFavoriteStaticMembers());
-
- try {
- Point selection= viewer.getSelectedRange();
- if (selection.y > 0)
- collector.setReplacementLength(selection.y);
-
- unit.codeComplete(offset, collector);
- } catch (JavaScriptModelException x) {
- Shell shell= viewer.getTextWidget().getShell();
- if (x.isDoesNotExist() && !unit.getJavaScriptProject().isOnIncludepath(unit))
- MessageDialog.openInformation(shell, JavaTextMessages.CompletionProcessor_error_notOnBuildPath_title, JavaTextMessages.CompletionProcessor_error_notOnBuildPath_message);
- else
- ErrorDialog.openError(shell, JavaTextMessages.CompletionProcessor_error_accessing_title, JavaTextMessages.CompletionProcessor_error_accessing_message, x.getStatus());
- }
-
- ICompletionProposal[] javaProposals= collector.getJavaCompletionProposals();
- int contextInformationOffset= guessContextInformationPosition(context);
- if (contextInformationOffset != offset) {
- for (int i= 0; i < javaProposals.length; i++) {
- if (javaProposals[i] instanceof JavaMethodCompletionProposal) {
- JavaMethodCompletionProposal jmcp= (JavaMethodCompletionProposal) javaProposals[i];
- jmcp.setContextInformationPosition(contextInformationOffset);
- }
- }
- }
-
- List proposals= new ArrayList(Arrays.asList(javaProposals));
- if (proposals.size() == 0) {
- String error= collector.getErrorMessage();
- if (error.length() > 0)
- fErrorMessage= error;
- }
- return proposals;
- }
-
- /**
- * Returns the array with favorite static members.
- *
- * @return the <code>String</code> array with with favorite static members
- * @see org.eclipse.wst.jsdt.core.CompletionRequestor#setFavoriteReferences(String[])
- *
- */
- private String[] getFavoriteStaticMembers() {
- String serializedFavorites= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS);
- if (serializedFavorites != null && serializedFavorites.length() > 0)
- return serializedFavorites.split(";"); //$NON-NLS-1$
- return new String[0];
- }
-
- /**
- * Creates the collector used to get proposals from core.
- */
- protected CompletionProposalCollector createCollector(JavaContentAssistInvocationContext context) {
- CompletionProposalCollector collector = new CompletionProposalCollector(context.getCompilationUnit());
- collector.setInvocationContext(context);
- return collector;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionStarted()
- */
- public void sessionStarted() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionEnded()
- */
- public void sessionEnded() {
- fErrorMessage= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java
deleted file mode 100644
index 5a4c2eb1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SpecificContentAssistExecutor;
-
-/**
- *
- *
- */
-public final class JavaContentAssistHandler extends AbstractHandler {
- private final SpecificContentAssistExecutor fExecutor= new SpecificContentAssistExecutor(CompletionProposalComputerRegistry.getDefault());
-
- public JavaContentAssistHandler() {
- }
-
- /*
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ITextEditor editor= getActiveEditor();
- if (editor == null)
- return null;
-
- String categoryId= event.getParameter("org.eclipse.wst.jsdt.ui.specific_content_assist.category_id"); //$NON-NLS-1$
- if (categoryId == null)
- return null;
-
- fExecutor.invokeContentAssist(editor, categoryId);
-
- return null;
- }
-
- private ITextEditor getActiveEditor() {
- IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page= window.getActivePage();
- if (page != null) {
- IEditorPart editor= page.getActiveEditor();
- if (editor instanceof ITextEditor)
- return (JavaEditor) editor;
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaDoubleClickSelector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaDoubleClickSelector.java
deleted file mode 100644
index 86df2993..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaDoubleClickSelector.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextDoubleClickStrategy;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaPairMatcher;
-
-/**
- * Double click strategy aware of Java identifier syntax rules.
- */
-public class JavaDoubleClickSelector implements ITextDoubleClickStrategy, ISourceVersionDependent {
-
- /**
- * Detects java words depending on the source level. In 1.4 mode, detects
- * <code>[[:ID:]]*</code>. In 1.5 mode, it also detects
- * <code>@\s*[[:IDS:]][[:ID:]]*</code>.
- *
- * Character class definitions:
- * <dl>
- * <dt>[[:IDS:]]</dt><dd>a java identifier start character</dd>
- * <dt>[[:ID:]]</dt><dd>a java identifier part character</dd>
- * <dt>\s</dt><dd>a white space character</dd>
- * <dt>@</dt><dd>the at symbol</dd>
- * </dl>
- *
- *
- */
- private static final class AtJavaIdentifierDetector implements ISourceVersionDependent {
-
- private boolean fSelectAnnotations;
-
- private static final int UNKNOWN= -1;
-
- /* states */
- private static final int WS= 0;
- private static final int ID= 1;
- private static final int IDS= 2;
- private static final int AT= 3;
-
- /* directions */
- private static final int FORWARD= 0;
- private static final int BACKWARD= 1;
-
- /** The current state. */
- private int fState;
- /**
- * The state at the anchor (if already detected by going the other way),
- * or <code>UNKNOWN</code>.
- */
- private int fAnchorState;
- /** The current direction. */
- private int fDirection;
- /** The start of the detected word. */
- private int fStart;
- /** The end of the word. */
- private int fEnd;
-
- /**
- * Initializes the detector at offset <code>anchor</code>.
- *
- * @param anchor the offset of the double click
- */
- private void setAnchor(int anchor) {
- fState= UNKNOWN;
- fAnchorState= UNKNOWN;
- fDirection= UNKNOWN;
- fStart= anchor;
- fEnd= anchor - 1;
- }
-
- private boolean isAt(char c) {
- return fSelectAnnotations && c == '@';
- }
-
- private boolean isIdentifierStart(char c) {
- return Character.isJavaIdentifierStart(c);
- }
-
- private boolean isIdentifierPart(char c) {
- return Character.isJavaIdentifierPart(c);
- }
-
- private boolean isWhitespace(char c) {
- return fSelectAnnotations && Character.isWhitespace(c);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String)
- */
- public void setSourceVersion(String version) {
- if (JavaScriptCore.VERSION_1_5.compareTo(version) <= 0)
- fSelectAnnotations= true;
- else
- fSelectAnnotations= false;
- }
-
- /**
- * Try to add a character to the word going backward. Only call after
- * forward calls!
- *
- * @param c the character to add
- * @param offset the offset of the character
- * @return <code>true</code> if further characters may be added to the
- * word
- */
- private boolean backward(char c, int offset) {
- checkDirection(BACKWARD);
- switch (fState) {
- case AT:
- return false;
- case IDS:
- if (isAt(c)) {
- fStart= offset;
- fState= AT;
- return false;
- }
- if (isWhitespace(c)) {
- fState= WS;
- return true;
- }
- //$FALL-THROUGH$
- case ID:
- if (isIdentifierStart(c)) {
- fStart= offset;
- fState= IDS;
- return true;
- }
- if (isIdentifierPart(c)) {
- fStart= offset;
- fState= ID;
- return true;
- }
- return false;
- case WS:
- if (isWhitespace(c)) {
- return true;
- }
- if (isAt(c)) {
- fStart= offset;
- fState= AT;
- return false;
- }
- return false;
- default:
- return false;
- }
- }
-
- /**
- * Try to add a character to the word going forward.
- *
- * @param c the character to add
- * @param offset the offset of the character
- * @return <code>true</code> if further characters may be added to the
- * word
- */
- private boolean forward(char c, int offset) {
- checkDirection(FORWARD);
- switch (fState) {
- case WS:
- case AT:
- if (isWhitespace(c)) {
- fState= WS;
- return true;
- }
- if (isIdentifierStart(c)) {
- fEnd= offset;
- fState= IDS;
- return true;
- }
- return false;
- case IDS:
- case ID:
- if (isIdentifierStart(c)) {
- fEnd= offset;
- fState= IDS;
- return true;
- }
- if (isIdentifierPart(c)) {
- fEnd= offset;
- fState= ID;
- return true;
- }
- return false;
- case UNKNOWN:
- if (isIdentifierStart(c)) {
- fEnd= offset;
- fState= IDS;
- fAnchorState= fState;
- return true;
- }
- if (isIdentifierPart(c)) {
- fEnd= offset;
- fState= ID;
- fAnchorState= fState;
- return true;
- }
- if (isWhitespace(c)) {
- fState= WS;
- fAnchorState= fState;
- return true;
- }
- if (isAt(c)) {
- fStart= offset;
- fState= AT;
- fAnchorState= fState;
- return true;
- }
- return false;
- default:
- return false;
- }
- }
-
- /**
- * If the direction changes, set state to be the previous anchor state.
- *
- * @param direction the new direction
- */
- private void checkDirection(int direction) {
- if (fDirection == direction)
- return;
-
- if (direction == FORWARD) {
- if (fStart <= fEnd)
- fState= fAnchorState;
- else
- fState= UNKNOWN;
- } else if (direction == BACKWARD) {
- if (fEnd >= fStart)
- fState= fAnchorState;
- else
- fState= UNKNOWN;
- }
-
- fDirection= direction;
- }
-
- /**
- * Returns the region containing <code>anchor</code> that is a java
- * word.
- *
- * @param document the document from which to read characters
- * @param anchor the offset around which to select a word
- * @return the region describing a java word around <code>anchor</code>
- */
- public IRegion getWordSelection(IDocument document, int anchor) {
-
- try {
-
- final int min= 0;
- final int max= document.getLength();
- setAnchor(anchor);
-
- char c;
-
- int offset= anchor;
- while (offset < max) {
- c= document.getChar(offset);
- if (!forward(c, offset))
- break;
- ++offset;
- }
-
- offset= anchor; // use to not select the previous word when right behind it
-// offset= anchor - 1; // use to select the previous word when right behind it
- while (offset >= min) {
- c= document.getChar(offset);
- if (!backward(c, offset))
- break;
- --offset;
- }
-
- return new Region(fStart, fEnd - fStart + 1);
-
- } catch (BadLocationException x) {
- return new Region(anchor, 0);
- }
- }
-
- }
-
- protected static final char[] BRACKETS= {'{', '}', '(', ')', '[', ']', '<', '>' };
- protected JavaPairMatcher fPairMatcher= new JavaPairMatcher(BRACKETS);
- protected final AtJavaIdentifierDetector fWordDetector= new AtJavaIdentifierDetector();
-
-
- public JavaDoubleClickSelector() {
- super();
- }
-
- /**
- * @see ITextDoubleClickStrategy#doubleClicked
- */
- public void doubleClicked(ITextViewer textViewer) {
-
- int offset= textViewer.getSelectedRange().x;
-
- if (offset < 0)
- return;
-
- IDocument document= textViewer.getDocument();
-
- IRegion region= fPairMatcher.match(document, offset);
- if (region != null && region.getLength() >= 2) {
- textViewer.setSelectedRange(region.getOffset() + 1, region.getLength() - 2);
- } else {
- region= selectWord(document, offset);
- textViewer.setSelectedRange(region.getOffset(), region.getLength());
- }
- }
-
- protected IRegion selectWord(IDocument document, int anchor) {
- return fWordDetector.getWordSelection(document, anchor);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String)
- */
- public void setSourceVersion(String version) {
- fPairMatcher.setSourceVersion(version);
- fWordDetector.setSourceVersion(version);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaFormattingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaFormattingStrategy.java
deleted file mode 100644
index 7daa061a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaFormattingStrategy.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.LinkedList;
-import java.util.Map;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Formatting strategy for java source code.
- *
- *
- */
-public class JavaFormattingStrategy extends ContextBasedFormattingStrategy {
-
- /** Documents to be formatted by this strategy */
- private final LinkedList fDocuments= new LinkedList();
- /** Partitions to be formatted by this strategy */
- private final LinkedList fPartitions= new LinkedList();
-
- /**
- * Creates a new java formatting strategy.
- */
- public JavaFormattingStrategy() {
- super();
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
- */
- public void format() {
- super.format();
-
- final IDocument document= (IDocument)fDocuments.removeFirst();
- final TypedPosition partition= (TypedPosition)fPartitions.removeFirst();
-
- if (document != null && partition != null) {
- Map partitioners= null;
- try {
-
- final TextEdit edit= CodeFormatterUtil.reformat(CodeFormatter.K_JAVASCRIPT_UNIT, document.get(), partition.getOffset(), partition.getLength(), 0, TextUtilities.getDefaultLineDelimiter(document), getPreferences());
- if (edit != null) {
- if (edit.getChildrenSize() > 20)
- partitioners= TextUtilities.removeDocumentPartitioners(document);
-
- edit.apply(document);
- }
-
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- // Can only happen on concurrent document modification - log and bail out
- JavaScriptPlugin.log(exception);
- } finally {
- if (partitioners != null)
- TextUtilities.addDocumentPartitioners(document, partitioners);
- }
- }
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
- */
- public void formatterStarts(final IFormattingContext context) {
- super.formatterStarts(context);
-
- fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
- fDocuments.addLast(context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM));
- }
-
- /*
- * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops()
- */
- public void formatterStops() {
- super.formatterStops();
-
- fPartitions.clear();
- fDocuments.clear();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java
deleted file mode 100644
index 7f45bb6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-
-public class JavaMethodCompletionProposal extends LazyJavaCompletionProposal {
- /** Triggers for method proposals without parameters. Do not modify. */
- protected final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[' };
- /** Triggers for method proposals. Do not modify. */
- protected final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
- /** Triggers for method name proposals (static imports). Do not modify. */
- protected final static char[] METHOD_NAME_TRIGGERS= new char[] { ';' };
-
- private boolean fHasParameters;
- private boolean fHasParametersComputed= false;
- private FormatterPrefs fFormatterPrefs;
-
- public JavaMethodCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- }
-
- public void apply(IDocument document, char trigger, int offset) {
- if (trigger == ' ' || trigger == '(')
- trigger= '\0';
- super.apply(document, trigger, offset);
- if (needsLinkedMode()) {
- setUpLinkedMode(document, ')');
- }
- }
-
- protected boolean needsLinkedMode() {
- return hasArgumentList() && hasParameters();
- }
-
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- if (hasArgumentList()) {
- String completion= String.valueOf(fProposal.getName());
- if (isCamelCaseMatching()) {
- String prefix= getPrefix(document, completionOffset);
- return getCamelCaseCompound(prefix, completion);
- }
-
- return completion;
- }
- return super.getPrefixCompletionText(document, completionOffset);
- }
-
- protected IContextInformation computeContextInformation() {
- // no context information for METHOD_NAME_REF proposals (e.g. for static imports)
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=94654
- if (fProposal.getKind() == CompletionProposal.METHOD_REF && hasParameters() && (getReplacementString().endsWith(RPAREN) || getReplacementString().length() == 0)) {
- ProposalContextInformation contextInformation= new ProposalContextInformation(fProposal);
- if (fContextInformationPosition != 0 && fProposal.getCompletion().length == 0)
- contextInformation.setContextInformationPosition(fContextInformationPosition);
- return contextInformation;
- }
- return super.computeContextInformation();
- }
-
- protected char[] computeTriggerCharacters() {
- if (fProposal.getKind() == CompletionProposal.METHOD_NAME_REFERENCE)
- return METHOD_NAME_TRIGGERS;
- if (hasParameters())
- return METHOD_WITH_ARGUMENTS_TRIGGERS;
- return METHOD_TRIGGERS;
- }
-
- /**
- * Returns <code>true</code> if the method being inserted has at least one parameter. Note
- * that this does not say anything about whether the argument list should be inserted. This
- * depends on the position in the document and the kind of proposal; see
- * {@link #hasArgumentList() }.
- *
- * @return <code>true</code> if the method has any parameters, <code>false</code> if it has
- * no parameters
- */
- protected final boolean hasParameters() {
- if (!fHasParametersComputed) {
- fHasParametersComputed= true;
- fHasParameters= computeHasParameters();
- }
- return fHasParameters;
- }
-
- private boolean computeHasParameters() throws IllegalArgumentException {
- return Signature.getParameterCount(fProposal.getSignature()) > 0;
- }
-
- /**
- * Returns <code>true</code> if the argument list should be inserted by the proposal,
- * <code>false</code> if not.
- *
- * @return <code>true</code> when the proposal is not in javadoc nor within an import and comprises the
- * parameter list
- */
- protected boolean hasArgumentList() {
- if (CompletionProposal.METHOD_NAME_REFERENCE == fProposal.getKind())
- return false;
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean noOverwrite= preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION) ^ isToggleEating();
- char[] completion= fProposal.getCompletion();
- return !isInJavadoc() && completion.length > 0 && (noOverwrite || completion[completion.length - 1] == ')');
- }
-
- /**
- * Returns the method formatter preferences.
- *
- * @return the formatter settings
- */
- protected final FormatterPrefs getFormatterPrefs() {
- if (fFormatterPrefs == null)
- fFormatterPrefs= new FormatterPrefs(fInvocationContext.getProject());
- return fFormatterPrefs;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
- if (!hasArgumentList())
- return super.computeReplacementString();
-
- // we're inserting a method plus the argument list - respect formatter preferences
- StringBuffer buffer= new StringBuffer();
- buffer.append(fProposal.getName());
-
- FormatterPrefs prefs= getFormatterPrefs();
- if (prefs.beforeOpeningParen)
- buffer.append(SPACE);
- buffer.append(LPAREN);
-
- if (hasParameters()) {
- setCursorPosition(buffer.length());
-
- if (prefs.afterOpeningParen)
- buffer.append(SPACE);
-
-
- // don't add the trailing space, but let the user type it in himself - typing the closing paren will exit
-// if (prefs.beforeClosingParen)
-// buffer.append(SPACE);
- } else {
- if (prefs.inEmptyList)
- buffer.append(SPACE);
- }
-
- buffer.append(RPAREN);
-
- return buffer.toString();
-
- }
-
- protected ProposalInfo computeProposalInfo() {
- IJavaScriptProject project= fInvocationContext.getProject();
- if (project != null)
- return new MethodProposalInfo(project, fProposal);
- return super.computeProposalInfo();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeSortString()
- */
- protected String computeSortString() {
- /*
- * Lexicographical sort order:
- * 1) by relevance (done by the proposal sorter)
- * 2) by method name
- * 3) by parameter count
- * 4) by parameter type names
- */
- char[] name= fProposal.getName();
- char[] parameterList= Signature.toCharArray(fProposal.getSignature(), null, null, false, false);
- int parameterCount= Signature.getParameterCount(fProposal.getSignature()) % 10; // we don't care about insane methods with >9 parameters
- StringBuffer buf= new StringBuffer(name.length + 2 + parameterList.length);
-
- buf.append(name);
- buf.append('\0'); // separator
- buf.append(parameterCount);
- buf.append(parameterList);
- return buf.toString();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String)
- */
- protected boolean isValidPrefix(String prefix) {
- if (super.isValidPrefix(prefix))
- return true;
-
- String word= getDisplayString();
- if (isInJavadoc()) {
- int idx = word.indexOf("{@link "); //$NON-NLS-1$
- if (idx==0) {
- word = word.substring(7);
- } else {
- idx = word.indexOf("{@value "); //$NON-NLS-1$
- if (idx==0) {
- word = word.substring(8);
- }
- }
- }
- return isPrefix(prefix, word);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaNoTypeCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaNoTypeCompletionProposalComputer.java
deleted file mode 100644
index 90ae4fc1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaNoTypeCompletionProposalComputer.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.Symbols;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalCollector;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- *
- *
- */
-public class JavaNoTypeCompletionProposalComputer extends JavaCompletionProposalComputer {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposalComputer#createCollector(org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext)
- */
- protected CompletionProposalCollector createCollector(JavaContentAssistInvocationContext context) {
- CompletionProposalCollector collector= super.createCollector(context);
- collector.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, false);
- collector.setIgnored(CompletionProposal.FIELD_REF, false);
- collector.setIgnored(CompletionProposal.KEYWORD, false);
- collector.setIgnored(CompletionProposal.LABEL_REF, false);
- collector.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, false);
- collector.setIgnored(CompletionProposal.METHOD_DECLARATION, false);
- collector.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, false);
- collector.setIgnored(CompletionProposal.METHOD_REF, false);
- collector.setIgnored(CompletionProposal.PACKAGE_REF, true);
- collector.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, false);
- collector.setIgnored(CompletionProposal.VARIABLE_DECLARATION, false);
-
- collector.setIgnored(CompletionProposal.JSDOC_BLOCK_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_FIELD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_INLINE_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_METHOD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_PARAM_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_TYPE_REF, true);
-
- collector.setIgnored(CompletionProposal.TYPE_REF, false);
- return collector;
- }
-
- protected int guessContextInformationPosition(ContentAssistInvocationContext context) {
- final int contextPosition= context.getInvocationOffset();
-
- IDocument document= context.getDocument();
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- int bound= Math.max(-1, contextPosition - 200);
-
- // try the innermost scope of parentheses that looks like a method call
- int pos= contextPosition - 1;
- do {
- int paren= scanner.findOpeningPeer(pos, bound, '(', ')');
- if (paren == JavaHeuristicScanner.NOT_FOUND)
- break;
- int token= scanner.previousToken(paren - 1, bound);
- // next token must be a method name (identifier) or the closing angle of a
- // constructor call of a parameterized type.
- if (token == Symbols.TokenIDENT || token == Symbols.TokenGREATERTHAN)
- return paren + 1;
- pos= paren - 1;
- } while (true);
-
- return super.guessContextInformationPosition(context);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaParameterListValidator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaParameterListValidator.java
deleted file mode 100644
index ec7ca822..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaParameterListValidator.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-
-
-
-public class JavaParameterListValidator implements IContextInformationValidator, IContextInformationPresenter {
-
- private int fPosition;
- private ITextViewer fViewer;
- private IContextInformation fInformation;
-
- private int fCurrentParameter;
-
-
-
- public JavaParameterListValidator() {
- }
-
- /**
- * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
- * @see IContextInformationPresenter#install(IContextInformation, ITextViewer, int)
- */
- public void install(IContextInformation info, ITextViewer viewer, int documentPosition) {
- fPosition= documentPosition;
- fViewer= viewer;
- fInformation= info;
-
- fCurrentParameter= -1;
- }
-
- 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 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 int getCharCount(IDocument document, final int start, final int end, String increments, String decrements, boolean considerNesting) throws BadLocationException {
-
- Assert.isTrue((increments.length() != 0 || decrements.length() != 0) && !increments.equals(decrements));
-
- final int NONE= 0;
- final int BRACKET= 1;
- final int BRACE= 2;
- final int PAREN= 3;
- final int ANGLE= 4;
-
- int nestingMode= NONE;
- int nestingLevel= 0;
-
- int charCount= 0;
- int offset= start;
- while (offset < end) {
- char curr= document.getChar(offset++);
- switch (curr) {
- case '/':
- if (offset < end) {
- char next= document.getChar(offset);
- if (next == '*') {
- // a comment starts, advance to the comment end
- offset= getCommentEnd(document, offset + 1, end);
- } else if (next == '/') {
- // '//'-comment: nothing to do anymore on this line
- offset= end;
- }
- }
- break;
- case '*':
- if (offset < end) {
- char next= document.getChar(offset);
- if (next == '/') {
- // we have been in a comment: forget what we read before
- charCount= 0;
- ++ offset;
- }
- }
- break;
- case '"':
- case '\'':
- offset= getStringEnd(document, offset, end, curr);
- break;
- case '[':
- if (considerNesting) {
- if (nestingMode == BRACKET || nestingMode == NONE) {
- nestingMode= BRACKET;
- nestingLevel++;
- }
- break;
- }
- case ']':
- if (considerNesting) {
- if (nestingMode == BRACKET)
- if (--nestingLevel == 0)
- nestingMode= NONE;
- break;
- }
- case '(':
- if (considerNesting) {
- if (nestingMode == ANGLE) {
- // generics heuristic failed
- nestingMode=PAREN;
- nestingLevel= 1;
- }
- if (nestingMode == PAREN || nestingMode == NONE) {
- nestingMode= PAREN;
- nestingLevel++;
- }
- break;
- }
- case ')':
- if (considerNesting) {
- if (nestingMode == PAREN)
- if (--nestingLevel == 0)
- nestingMode= NONE;
- break;
- }
- case '{':
- if (considerNesting) {
- if (nestingMode == ANGLE) {
- // generics heuristic failed
- nestingMode=BRACE;
- nestingLevel= 1;
- }
- if (nestingMode == BRACE || nestingMode == NONE) {
- nestingMode= BRACE;
- nestingLevel++;
- }
- break;
- }
- case '}':
- if (considerNesting) {
- if (nestingMode == BRACE)
- if (--nestingLevel == 0)
- nestingMode= NONE;
- break;
- }
- case '<':
- if (considerNesting) {
- if (nestingMode == ANGLE || nestingMode == NONE && checkGenericsHeuristic(document, offset - 1, start - 1)) {
- nestingMode= ANGLE;
- nestingLevel++;
- }
- break;
- }
- case '>':
- if (considerNesting) {
- if (nestingMode == ANGLE)
- if (--nestingLevel == 0)
- nestingMode= NONE;
- break;
- }
-
- default:
- if (nestingLevel != 0)
- continue;
-
- if (increments.indexOf(curr) >= 0) {
- ++ charCount;
- }
-
- if (decrements.indexOf(curr) >= 0) {
- -- charCount;
- }
- }
- }
-
- return charCount;
- }
-
- private boolean checkGenericsHeuristic(IDocument document, int end, int bound) throws BadLocationException {
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- return scanner.looksLikeClassInstanceCreationBackward(end, bound);
- }
-
- /**
- * @see IContextInformationValidator#isContextInformationValid(int)
- */
- public boolean isContextInformationValid(int position) {
-
- try {
- if (position < fPosition)
- return false;
-
- IDocument document= fViewer.getDocument();
- IRegion line= document.getLineInformationOfOffset(fPosition);
-
- if (position < line.getOffset() || position >= document.getLength())
- return false;
-
- return getCharCount(document, fPosition, position, "(<", ")>", false) >= 0; //$NON-NLS-1$ //$NON-NLS-2$
-
- } catch (BadLocationException x) {
- return false;
- }
- }
-
- /**
- * @see IContextInformationPresenter#updatePresentation(int, TextPresentation)
- */
- public boolean updatePresentation(int position, TextPresentation presentation) {
-
- int currentParameter= -1;
-
- try {
- currentParameter= getCharCount(fViewer.getDocument(), fPosition, position, ",", "", true); //$NON-NLS-1$//$NON-NLS-2$
- } catch (BadLocationException x) {
- return false;
- }
-
- if (fCurrentParameter != -1) {
- if (currentParameter == fCurrentParameter)
- return false;
- }
-
- presentation.clear();
- fCurrentParameter= currentParameter;
-
- String s= fInformation.getInformationDisplayString();
- int[] commas= computeCommaPositions(s);
-
- if (commas.length - 2 < fCurrentParameter) {
- presentation.addStyleRange(new StyleRange(0, s.length(), null, null, SWT.NORMAL));
- return true;
- }
-
- int start= commas[fCurrentParameter] + 1;
- int end= commas[fCurrentParameter + 1];
- if (start > 0)
- presentation.addStyleRange(new StyleRange(0, start, null, null, SWT.NORMAL));
-
- if (end > start)
- presentation.addStyleRange(new StyleRange(start, end - start, null, null, SWT.BOLD));
-
- if (end < s.length())
- presentation.addStyleRange(new StyleRange(end, s.length() - end, null, null, SWT.NORMAL));
-
- return true;
- }
-
- private int[] computeCommaPositions(String code) {
- final int length= code.length();
- int pos= 0;
- List positions= new ArrayList();
- positions.add(new Integer(-1));
- while (pos < length && pos != -1) {
- char ch= code.charAt(pos);
- switch (ch) {
- case ',':
- positions.add(new Integer(pos));
- break;
- case '<':
- pos= code.indexOf('>', pos);
- break;
- case '[':
- pos= code.indexOf(']', pos);
- break;
- default:
- break;
- }
- if (pos != -1)
- pos++;
- }
- positions.add(new Integer(length));
-
- int[] fields= new int[positions.size()];
- for (int i= 0; i < fields.length; i++)
- fields[i]= ((Integer) positions.get(i)).intValue();
- return fields;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaReconcilingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaReconcilingStrategy.java
deleted file mode 100644
index ee6b1c4f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaReconcilingStrategy.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.reconciler.DirtyRegion;
-import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
-import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.WorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension {
-
-
- private ITextEditor fEditor;
-
- private WorkingCopyManager fManager;
- private IDocumentProvider fDocumentProvider;
- private IProgressMonitor fProgressMonitor;
- private boolean fNotify= true;
-
- private IJavaReconcilingListener fJavaReconcilingListener;
- private boolean fIsJavaReconcilingListener;
-
-
- public JavaReconcilingStrategy(ITextEditor editor) {
- fEditor= editor;
- fManager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- fDocumentProvider= JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider();
- fIsJavaReconcilingListener= fEditor instanceof IJavaReconcilingListener;
- if (fIsJavaReconcilingListener)
- fJavaReconcilingListener= (IJavaReconcilingListener)fEditor;
- }
-
- private IProblemRequestorExtension getProblemRequestorExtension() {
- IAnnotationModel model= fDocumentProvider.getAnnotationModel(fEditor.getEditorInput());
- if (model instanceof IProblemRequestorExtension)
- return (IProblemRequestorExtension) model;
- return null;
- }
-
- private void reconcile(final boolean initialReconcile) {
- final JavaScriptUnit[] ast= new JavaScriptUnit[1];
- try {
- final IJavaScriptUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput(), false);
- if (unit != null) {
- SafeRunner.run(new ISafeRunnable() {
- public void run() {
- try {
-
- /* fix for missing cancel flag communication */
- IProblemRequestorExtension extension= getProblemRequestorExtension();
- if (extension != null) {
- extension.setProgressMonitor(fProgressMonitor);
- extension.setIsActive(true);
- }
-
- try {
- boolean isASTNeeded= initialReconcile || JavaScriptPlugin.getDefault().getASTProvider().isActive(unit);
- // reconcile
- if (fIsJavaReconcilingListener && isASTNeeded) {
- int reconcileFlags= IJavaScriptUnit.FORCE_PROBLEM_DETECTION
- | (ASTProvider.SHARED_AST_STATEMENT_RECOVERY ? IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY : 0)
- | (ASTProvider.SHARED_BINDING_RECOVERY ? IJavaScriptUnit.ENABLE_BINDINGS_RECOVERY : 0);
-
- ast[0]= unit.reconcile(ASTProvider.SHARED_AST_LEVEL, reconcileFlags, null, fProgressMonitor);
- if (ast[0] != null) {
- // mark as unmodifiable
- ASTNodes.setFlagsToAST(ast[0], ASTNode.PROTECT);
- }
- } else
- unit.reconcile(IJavaScriptUnit.NO_AST, true, null, fProgressMonitor);
- } catch (OperationCanceledException ex) {
- Assert.isTrue(fProgressMonitor == null || fProgressMonitor.isCanceled());
- ast[0]= null;
- } finally {
- /* fix for missing cancel flag communication */
- if (extension != null) {
- extension.setProgressMonitor(null);
- extension.setIsActive(false);
- }
- }
-
- } catch (JavaScriptModelException ex) {
- handleException(ex);
- }
- }
- public void handleException(Throwable ex) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, "Error in JSDT Core during reconcile", ex); //$NON-NLS-1$
- JavaScriptPlugin.getDefault().getLog().log(status);
- }
- });
-
- }
- } finally {
- // Always notify listeners, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=55969 for the final solution
- try {
- if (fIsJavaReconcilingListener) {
- IProgressMonitor pm= fProgressMonitor;
- if (pm == null)
- pm= new NullProgressMonitor();
- fJavaReconcilingListener.reconciled(ast[0], !fNotify, pm);
- }
- } finally {
- fNotify= true;
- }
- }
- }
-
- /*
- * @see IReconcilingStrategy#reconcile(IRegion)
- */
- public void reconcile(IRegion partition) {
- reconcile(false);
- }
-
- /*
- * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion)
- */
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- reconcile(false);
- }
-
- /*
- * @see IReconcilingStrategy#setDocument(IDocument)
- */
- public void setDocument(IDocument document) {
- }
-
- /*
- * @see IReconcilingStrategyExtension#setProgressMonitor(IProgressMonitor)
- */
- public void setProgressMonitor(IProgressMonitor monitor) {
- fProgressMonitor= monitor;
- }
-
- /*
- * @see IReconcilingStrategyExtension#initialReconcile()
- */
- public void initialReconcile() {
- reconcile(true);
- }
-
- /**
- * Tells this strategy whether to inform its listeners.
- *
- * @param notify <code>true</code> if listeners should be notified
- */
- public void notifyListeners(boolean notify) {
- fNotify= notify;
- }
-
- /**
- * Called before reconciling is started.
- *
- *
- */
- public void aboutToBeReconciled() {
- if (fIsJavaReconcilingListener)
- fJavaReconcilingListener.aboutToBeReconciled();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringAutoIndentStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringAutoIndentStrategy.java
deleted file mode 100644
index 8f9e134e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringAutoIndentStrategy.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Auto indent strategy for java strings
- */
-public class JavaStringAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
-
- private String fPartitioning;
-
- /**
- * The input string doesn't contain any line delimiter.
- *
- * @param inputString the given input string
- * @return the displayable string.
- */
- private String displayString(String inputString, String indentation, String delimiter) {
-
- int length = inputString.length();
- StringBuffer buffer = new StringBuffer(length);
- java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(inputString, "\n\r", true); //$NON-NLS-1$
- while (tokenizer.hasMoreTokens()){
-
- String token = tokenizer.nextToken();
- if (token.equals("\r")) { //$NON-NLS-1$
- buffer.append("\\r"); //$NON-NLS-1$
- if (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equals("\n")) { //$NON-NLS-1$
- buffer.append("\\n"); //$NON-NLS-1$
- buffer.append("\" + " + delimiter); //$NON-NLS-1$
- buffer.append(indentation);
- buffer.append("\""); //$NON-NLS-1$
- continue;
- } else {
- buffer.append("\" + " + delimiter); //$NON-NLS-1$
- buffer.append(indentation);
- buffer.append("\""); //$NON-NLS-1$
- }
- } else {
- continue;
- }
- } else if (token.equals("\n")) { //$NON-NLS-1$
- buffer.append("\\n"); //$NON-NLS-1$
- buffer.append("\" + " + delimiter); //$NON-NLS-1$
- buffer.append(indentation);
- buffer.append("\""); //$NON-NLS-1$
- continue;
- }
-
- StringBuffer tokenBuffer = new StringBuffer();
- for (int i = 0; i < token.length(); i++){
- char c = token.charAt(i);
- switch (c) {
- case '\r' :
- tokenBuffer.append("\\r"); //$NON-NLS-1$
- break;
- case '\n' :
- tokenBuffer.append("\\n"); //$NON-NLS-1$
- break;
- case '\b' :
- tokenBuffer.append("\\b"); //$NON-NLS-1$
- break;
- case '\t' :
- // keep tabs verbatim
- tokenBuffer.append("\t"); //$NON-NLS-1$
- break;
- case '\f' :
- tokenBuffer.append("\\f"); //$NON-NLS-1$
- break;
- case '\"' :
- tokenBuffer.append("\\\""); //$NON-NLS-1$
- break;
- case '\'' :
- tokenBuffer.append("\\'"); //$NON-NLS-1$
- break;
- case '\\' :
- tokenBuffer.append("\\\\"); //$NON-NLS-1$
- break;
- default :
- tokenBuffer.append(c);
- }
- }
- buffer.append(tokenBuffer);
- }
- return buffer.toString();
- }
-
- /**
- * Creates a new Java string auto indent strategy for the given document partitioning.
- *
- * @param partitioning the document partitioning
- */
- public JavaStringAutoIndentStrategy(String partitioning) {
- super();
- fPartitioning= partitioning;
- }
-
- private boolean isLineDelimiter(IDocument document, String text) {
- String[] delimiters= document.getLegalLineDelimiters();
- if (delimiters != null)
- return TextUtilities.equals(delimiters, text) > -1;
- return false;
- }
-
- private String getLineIndentation(IDocument document, int offset) throws BadLocationException {
-
- // find start of line
- int adjustedOffset= (offset == document.getLength() ? offset - 1 : offset);
- IRegion line= document.getLineInformationOfOffset(adjustedOffset);
- int start= line.getOffset();
-
- // find white spaces
- int end= findEndOfWhiteSpace(document, start, offset);
-
- return document.get(start, end - start);
- }
-
- private String getModifiedText(String string, String indentation, String delimiter) {
- return displayString(string, indentation, delimiter);
- }
-
- private void javaStringIndentAfterNewLine(IDocument document, DocumentCommand command) throws BadLocationException {
-
- ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, true);
- int offset= partition.getOffset();
- int length= partition.getLength();
-
- if (command.offset == offset + length && document.getChar(offset + length - 1) == '\"')
- return;
-
- String indentation= getLineIndentation(document, command.offset);
- String delimiter= TextUtilities.getDefaultLineDelimiter(document);
-
- IRegion line= document.getLineInformationOfOffset(offset);
- String string= document.get(line.getOffset(), offset - line.getOffset());
- if (string.trim().length() != 0)
- indentation += String.valueOf("\t\t"); //$NON-NLS-1$
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- if (isLineDelimiter(document, command.text))
- command.text= "\" +" + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$
- else if (command.text.length() > 1 && preferenceStore.getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS))
- command.text= getModifiedText(command.text, indentation, delimiter);
- }
-
- private boolean isSmartMode() {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IEditorPart part= page.getActiveEditor();
- if (part instanceof ITextEditorExtension3) {
- ITextEditorExtension3 extension= (ITextEditorExtension3) part;
- return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
- }
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, DocumentCommand)
- */
- public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
- try {
- if (command.text == null)
- return;
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS) && isSmartMode()) {
- javaStringIndentAfterNewLine(document, command);
- }
-
- } catch (BadLocationException e) {
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringDoubleClickSelector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringDoubleClickSelector.java
deleted file mode 100644
index 8196e34e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaStringDoubleClickSelector.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextUtilities;
-
-/**
- * Double click strategy aware of Java string and character syntax rules.
- */
-public class JavaStringDoubleClickSelector extends JavaDoubleClickSelector {
-
- private String fPartitioning;
-
- /**
- * Creates a new Java string double click selector for the given document partitioning.
- *
- * @param partitioning the document partitioning
- */
- public JavaStringDoubleClickSelector(String partitioning) {
- super();
- fPartitioning= partitioning;
- }
-
- /*
- * @see ITextDoubleClickStrategy#doubleClicked(ITextViewer)
- */
- public void doubleClicked(ITextViewer textViewer) {
-
- int offset= textViewer.getSelectedRange().x;
-
- if (offset < 0)
- return;
-
- IDocument document= textViewer.getDocument();
-
- IRegion region= match(document, offset);
- if (region != null && region.getLength() >= 2) {
- textViewer.setSelectedRange(region.getOffset() + 1, region.getLength() - 2);
- } else {
- region= selectWord(document, offset);
- textViewer.setSelectedRange(region.getOffset(), region.getLength());
- }
- }
-
- private IRegion match(IDocument document, int offset) {
- try {
- if ((document.getChar(offset) == '"') || (document.getChar(offset) == '\'') ||
- (document.getChar(offset - 1) == '"') || (document.getChar(offset - 1) == '\''))
- {
- return TextUtilities.getPartition(document, fPartitioning, offset, true);
- }
- } catch (BadLocationException e) {
- }
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.java
deleted file mode 100644
index aba196ae..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class JavaTextMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaTextMessages.class.getName();
-
- private JavaTextMessages() {
- // Do not instantiate
- }
-
- public static String CompletionProcessor_error_accessing_title;
- public static String CompletionProcessor_error_accessing_message;
- public static String CompletionProcessor_error_notOnBuildPath_title;
- public static String CompletionProcessor_error_notOnBuildPath_message;
- public static String CompletionProposalComputerRegistry_messageAvoidanceHint;
- public static String CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning;
- public static String ContentAssistProcessor_all_disabled_message;
- public static String ContentAssistProcessor_all_disabled_preference_link;
- public static String ContentAssistProcessor_all_disabled_title;
- public static String FilledArgumentNamesMethodProposal_error_msg;
- public static String ParameterGuessingProposal_error_msg;
- public static String GetterSetterCompletionProposal_getter_label;
- public static String GetterSetterCompletionProposal_setter_label;
- public static String MethodCompletionProposal_constructor_label;
- public static String MethodCompletionProposal_method_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaTextMessages.class);
- }
-
- public static String ContentAssistProcessor_computing_proposals;
- public static String ContentAssistProcessor_collecting_proposals;
- public static String ContentAssistProcessor_sorting_proposals;
- public static String ContentAssistProcessor_computing_contexts;
- public static String ContentAssistProcessor_collecting_contexts;
- public static String ContentAssistProcessor_sorting_contexts;
- public static String CompletionProposalComputerDescriptor_illegal_attribute_message;
- public static String CompletionProposalComputerDescriptor_reason_invalid;
- public static String CompletionProposalComputerDescriptor_reason_instantiation;
- public static String CompletionProposalComputerDescriptor_reason_runtime_ex;
- public static String CompletionProposalComputerDescriptor_reason_API;
- public static String CompletionProposalComputerDescriptor_reason_performance;
- public static String CompletionProposalComputerDescriptor_blame_message;
- public static String CompletionProposalComputerRegistry_invalid_message;
- public static String CompletionProposalComputerRegistry_error_dialog_title;
- public static String ContentAssistProcessor_defaultProposalCategory;
- public static String ContentAssistProcessor_toggle_affordance_press_gesture;
- public static String ContentAssistProcessor_toggle_affordance_click_gesture;
- public static String ContentAssistProcessor_toggle_affordance_update_message;
- public static String ContentAssistProcessor_empty_message;
- public static String ContentAssistHistory_serialize_error;
- public static String ContentAssistHistory_deserialize_error;
- public static String ProposalSorterHandle_blame;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties
deleted file mode 100644
index 9476907a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties
+++ /dev/null
@@ -1,69 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2008 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-CompletionProcessor_error_accessing_title=Error Accessing JavaScript file
-CompletionProcessor_error_accessing_message=Cannot access JavaScript file
-
-CompletionProcessor_error_notOnBuildPath_title= Cannot Perform Operation
-CompletionProcessor_error_notOnBuildPath_message= This JavaScript file is not on the build path of a JavaScript project.
-
-CompletionProposalComputerRegistry_error_dialog_title=Problems During Content Assist
-# {0} is the plug-in id of the contributing plug-in, {1} the display name of the proposal category
-CompletionProposalComputerRegistry_messageAvoidanceHint=To avoid this message, disable the ''{0}'' plug-in or disable the ''{1}'' category on the <a>content assist</a> preference page.
-# {0} is the plug-in id of the contributing plug-in, {1} the display name of the proposal category, {2} the comma-separated list of plug-ins other than {0} the contribute to the category
-CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning=To avoid this message, disable the ''{0}'' plug-in or disable the ''{1}'' category on the <a>content assist</a> preference page. Note that disabling the category will also affect completion proposals from the following plug-ins: {2}.
-# {0} is the extension id
-CompletionProposalComputerRegistry_invalid_message=The extension ''{0}'' has become invalid.
-
-CompletionProposalComputerDescriptor_reason_invalid=The extension has become invalid.
-CompletionProposalComputerDescriptor_reason_instantiation=Unable to instantiate the extension.
-CompletionProposalComputerDescriptor_reason_runtime_ex=The extension has thrown a runtime exception.
-# {0} specifies an operation name, e.g. "computeProposals"
-CompletionProposalComputerDescriptor_reason_API=The extension violated the API contract of the ''{0}'' operation.
-CompletionProposalComputerDescriptor_reason_performance=The extension took too long to return from the ''{0}'' operation.
-# {0} is the name of an extension, {1} the contributing plug-in name
-CompletionProposalComputerDescriptor_blame_message= The ''{0}'' proposal computer from the ''{1}'' plug-in did not complete normally.
-# {0} is the identifier of an extension, {1} the contributing plug-in, {2} a required but missing xml attribute
-CompletionProposalComputerDescriptor_illegal_attribute_message= The extension "{0}" from plug-in "{1}" did not specify a value for the required "{2}" attribute. Disabling the extension.
-# {0} is the name of an extension, {1} the id of the extension
-ProposalSorterHandle_blame= Found a problem with the ''{0}'' ({1}) extension to the "javaCompletionProposalSorters" extension point.
-
-FilledArgumentNamesMethodProposal_error_msg=Error inserting parameters
-ParameterGuessingProposal_error_msg=Error guessing parameters
-
-GetterSetterCompletionProposal_getter_label=Getter for ''{0}''
-GetterSetterCompletionProposal_setter_label=Setter for ''{0}''
-MethodCompletionProposal_constructor_label=Default constructor
-MethodCompletionProposal_method_label=Method stub
-
-ContentAssistProcessor_computing_proposals=Computing completion proposals
-ContentAssistProcessor_collecting_proposals=Collecting proposals
-ContentAssistProcessor_sorting_proposals=Sorting
-ContentAssistProcessor_computing_contexts=Computing context information
-ContentAssistProcessor_all_disabled_title=No Default Proposal Kinds
-ContentAssistProcessor_all_disabled_message=No proposal kinds are enabled for the 'default' content assist list.
-# {0} will be replaced by the label of the 'restore defaults' button
-# The preference page should match the title of the 'Java > Editor > Content Assist > Advanced' preference page
-ContentAssistProcessor_all_disabled_preference_link=Change the settings on the <a>Advanced Content Assist preference page</a> or click ''{0}'' to restore the default behavior.
-ContentAssistProcessor_collecting_contexts=Collecting context information
-ContentAssistProcessor_sorting_contexts=Sorting
-ContentAssistProcessor_defaultProposalCategory=Default Proposals
-# {0} will be replaced by a keyboard shortcut (accelerator)
-ContentAssistProcessor_toggle_affordance_press_gesture=Press ''{0}''
-ContentAssistProcessor_toggle_affordance_click_gesture=Click
-# {0} will be replaced by a title describing the displayed proposal category, {1} by either the press_gesture or click_gesture message above, {2} by the name of the next proposal category
-ContentAssistProcessor_toggle_affordance_update_message={1} to show {2}
-# {0} will be replaced by a title describing the displayed proposal category
-ContentAssistProcessor_empty_message= No {0}
-
-ContentAssistHistory_serialize_error=Problems writing content assist history to XML
-ContentAssistHistory_deserialize_error=Problems reading content assist history from XML
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java
deleted file mode 100644
index bfde7264..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * If passed compilation unit is not null, the replacement string will be seen as a qualified type name.
- */
-public class JavaTypeCompletionProposal extends JavaCompletionProposal {
-
- protected final IJavaScriptUnit fCompilationUnit;
-
- /** The unqualified type name. */
- private final String fUnqualifiedTypeName;
- /** The fully qualified type name. */
- private final String fFullyQualifiedTypeName;
-
- public JavaTypeCompletionProposal(String replacementString, IJavaScriptUnit cu, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
- this(replacementString, cu, replacementOffset, replacementLength, image, displayString, relevance, null);
- }
-
- public JavaTypeCompletionProposal(String replacementString, IJavaScriptUnit cu, int replacementOffset, int replacementLength, Image image, String displayString, int relevance,
- String fullyQualifiedTypeName)
- {
- super(replacementString, replacementOffset, replacementLength, image, displayString, relevance);
- fCompilationUnit= cu;
- fFullyQualifiedTypeName= fullyQualifiedTypeName;
- fUnqualifiedTypeName= fullyQualifiedTypeName != null ? Signature.getSimpleName(fullyQualifiedTypeName) : null;
- }
-
- protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
- // avoid adding imports when inside imports container
- if (impRewrite != null && fFullyQualifiedTypeName != null) {
- String replacementString= getReplacementString();
- String qualifiedType= fFullyQualifiedTypeName;
- if (qualifiedType.indexOf('.') != -1 && replacementString.startsWith(qualifiedType) && !replacementString.endsWith(String.valueOf(';'))) {
- IType[] types= impRewrite.getCompilationUnit().getTypes();
- if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) {
- // ignore positions above type.
- setReplacementString(impRewrite.addImport(getReplacementString()));
- return true;
- }
- }
- }
- return false;
- }
-
-
- /* (non-Javadoc)
- * @see ICompletionProposalExtension#apply(IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- try {
- ImportRewrite impRewrite= null;
-
- if (fCompilationUnit != null && allowAddingImports()) {
- impRewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
- }
-
- boolean importAdded= updateReplacementString(document, trigger, offset, impRewrite);
-
- if (importAdded)
- setCursorPosition(getReplacementString().length());
-
- super.apply(document, trigger, offset);
-
- if (importAdded && impRewrite != null) {
- int oldLen= document.getLength();
- impRewrite.rewriteImports(new NullProgressMonitor()).apply(document, TextEdit.UPDATE_REGIONS);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private boolean allowAddingImports() {
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- return preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_ADDIMPORT);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String)
- */
- protected boolean isValidPrefix(String prefix) {
- return super.isValidPrefix(prefix) || isPrefix(prefix, fUnqualifiedTypeName) || isPrefix(prefix, fFullyQualifiedTypeName);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal#getCompletionText()
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- return fUnqualifiedTypeName;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java
deleted file mode 100644
index 83351654..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaHeuristicScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.Symbols;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalCollector;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- *
- *
- */
-public class JavaTypeCompletionProposalComputer extends JavaCompletionProposalComputer {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposalComputer#createCollector(org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext)
- */
- protected CompletionProposalCollector createCollector(JavaContentAssistInvocationContext context) {
- CompletionProposalCollector collector= super.createCollector(context);
- collector.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- collector.setIgnored(CompletionProposal.FIELD_REF, true);
- collector.setIgnored(CompletionProposal.KEYWORD, true);
- collector.setIgnored(CompletionProposal.LABEL_REF, true);
- collector.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
- collector.setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- collector.setIgnored(CompletionProposal.METHOD_REF, true);
- collector.setIgnored(CompletionProposal.PACKAGE_REF, true);
- collector.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
-
- collector.setIgnored(CompletionProposal.JSDOC_BLOCK_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_FIELD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_INLINE_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_METHOD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_PARAM_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_TYPE_REF, true);
-
- collector.setIgnored(CompletionProposal.TYPE_REF, false);
- return collector;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- List types= super.computeCompletionProposals(context, monitor);
- if (context instanceof JavaContentAssistInvocationContext) {
- JavaContentAssistInvocationContext javaContext= (JavaContentAssistInvocationContext) context;
- try {
- if (types.size() > 0 && context.computeIdentifierPrefix().length() == 0) {
- IType expectedType= javaContext.getExpectedType();
- if (expectedType != null) {
- // empty prefix completion - insert LRU types if known, but prune if they already occur in the core list
-
- // compute minmimum relevance and already proposed list
- int relevance= Integer.MAX_VALUE;
- Set proposed= new HashSet();
- for (Iterator it= types.iterator(); it.hasNext();) {
- AbstractJavaCompletionProposal p= (AbstractJavaCompletionProposal) it.next();
- IJavaScriptElement element= p.getJavaElement();
- if (element instanceof IType)
- proposed.add(((IType) element).getFullyQualifiedName());
- relevance= Math.min(relevance, p.getRelevance());
- }
-
- // insert history types
- List history= JavaScriptPlugin.getDefault().getContentAssistHistory().getHistory(expectedType.getFullyQualifiedName()).getTypes();
- relevance-= history.size() + 1;
- for (Iterator it= history.iterator(); it.hasNext();) {
- String type= (String) it.next();
- if (proposed.contains(type))
- continue;
-
- IJavaCompletionProposal proposal= createTypeProposal(relevance, type, javaContext);
-
- if (proposal != null)
- types.add(proposal);
- relevance++;
- }
- }
- }
- } catch (BadLocationException x) {
- // log & ignore
- JavaScriptPlugin.log(x);
- } catch (JavaScriptModelException x) {
- // log & ignore
- JavaScriptPlugin.log(x);
- }
- }
- return types;
- }
-
- private IJavaCompletionProposal createTypeProposal(int relevance, String fullyQualifiedType, JavaContentAssistInvocationContext context) throws JavaScriptModelException {
- IType type= context.getCompilationUnit().getJavaScriptProject().findType(fullyQualifiedType);
- if (type == null)
- return null;
-
- CompletionProposal proposal= CompletionProposal.create(CompletionProposal.TYPE_REF, context.getInvocationOffset());
- proposal.setCompletion(fullyQualifiedType.toCharArray());
- proposal.setDeclarationSignature(type.getPackageFragment().getElementName().toCharArray());
- proposal.setFlags(type.getFlags());
- proposal.setRelevance(relevance);
- proposal.setReplaceRange(context.getInvocationOffset(), context.getInvocationOffset());
- proposal.setSignature(Signature.createTypeSignature(fullyQualifiedType, true).toCharArray());
-
- if (shouldProposeGenerics(context.getProject()))
- return new LazyGenericTypeProposal(proposal, context);
- else
- return new LazyJavaTypeCompletionProposal(proposal, context);
- }
-
- /**
- * Returns <code>true</code> if generic proposals should be allowed,
- * <code>false</code> if not. Note that even though code (in a library)
- * may be referenced that uses generics, it is still possible that the
- * current source does not allow generics.
- *
- * @param project the Java project
- * @return <code>true</code> if the generic proposals should be allowed,
- * <code>false</code> if not
- */
- private final boolean shouldProposeGenerics(IJavaScriptProject project) {
- String sourceVersion;
- if (project != null)
- sourceVersion= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- else
- sourceVersion= JavaScriptCore.getOption(JavaScriptCore.COMPILER_SOURCE);
-
- return sourceVersion != null && JavaScriptCore.VERSION_1_5.compareTo(sourceVersion) <= 0;
- }
-
- protected int guessContextInformationPosition(ContentAssistInvocationContext context) {
- final int contextPosition= context.getInvocationOffset();
-
- IDocument document= context.getDocument();
- JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
- int bound= Math.max(-1, contextPosition - 200);
-
- // try the innermost scope of angle brackets that looks like a generic type argument list
- try {
- int pos= contextPosition - 1;
- do {
- int angle= scanner.findOpeningPeer(pos, bound, '<', '>');
- if (angle == JavaHeuristicScanner.NOT_FOUND)
- break;
- int token= scanner.previousToken(angle - 1, bound);
- // next token must be a method name that is a generic type
- if (token == Symbols.TokenIDENT) {
- int off= scanner.getPosition() + 1;
- int end= angle;
- String ident= document.get(off, end - off).trim();
- if (JavaHeuristicScanner.isGenericStarter(ident))
- return angle + 1;
- }
- pos= angle - 1;
- } while (true);
- } catch (BadLocationException x) {
- }
-
- return super.guessContextInformationPosition(context);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java
deleted file mode 100644
index 2e7dd2ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.text.CharacterIterator;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextDoubleClickStrategy;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-
-import com.ibm.icu.text.BreakIterator;
-
-
-/**
- * Copied from DefaultTextDoubleClickStrategy. Same behavior, but also
- * allows <code>@identifier</code> to be selected.
- *
- *
- */
-public class JavadocDoubleClickStrategy implements ITextDoubleClickStrategy {
-
-
- /**
- * Implements a character iterator that works directly on
- * instances of <code>IDocument</code>. Used to collaborate with
- * the break iterator.
- *
- * @see IDocument
- *
- */
- static class DocumentCharacterIterator implements CharacterIterator {
-
- /** Document to iterate over. */
- private IDocument fDocument;
- /** Start offset of iteration. */
- private int fOffset= -1;
- /** End offset of iteration. */
- private int fEndOffset= -1;
- /** Current offset of iteration. */
- private int fIndex= -1;
-
- /** Creates a new document iterator. */
- public DocumentCharacterIterator() {
- }
-
- /**
- * Configures this document iterator with the document section to be visited.
- *
- * @param document the document to be iterated
- * @param iteratorRange the range in the document to be iterated
- */
- public void setDocument(IDocument document, IRegion iteratorRange) {
- fDocument= document;
- fOffset= iteratorRange.getOffset();
- fEndOffset= fOffset + iteratorRange.getLength();
- }
-
- /*
- * @see CharacterIterator#first()
- */
- public char first() {
- fIndex= fOffset;
- return current();
- }
-
- /*
- * @see CharacterIterator#last()
- */
- public char last() {
- fIndex= fOffset < fEndOffset ? fEndOffset -1 : fEndOffset;
- return current();
- }
-
- /*
- * @see CharacterIterator#current()
- */
- public char current() {
- if (fOffset <= fIndex && fIndex < fEndOffset) {
- try {
- return fDocument.getChar(fIndex);
- } catch (BadLocationException x) {
- }
- }
- return DONE;
- }
-
- /*
- * @see CharacterIterator#next()
- */
- public char next() {
- ++fIndex;
- int end= getEndIndex();
- if (fIndex >= end) {
- fIndex= end;
- return DONE;
- }
- return current();
- }
-
- /*
- * @see CharacterIterator#previous()
- */
- public char previous() {
- if (fIndex == fOffset)
- return DONE;
-
- if (fIndex > fOffset)
- -- fIndex;
-
- return current();
- }
-
- /*
- * @see CharacterIterator#setIndex(int)
- */
- public char setIndex(int index) {
- fIndex= index;
- return current();
- }
-
- /*
- * @see CharacterIterator#getBeginIndex()
- */
- public int getBeginIndex() {
- return fOffset;
- }
-
- /*
- * @see CharacterIterator#getEndIndex()
- */
- public int getEndIndex() {
- return fEndOffset;
- }
-
- /*
- * @see CharacterIterator#getIndex()
- */
- public int getIndex() {
- return fIndex;
- }
-
- /*
- * @see CharacterIterator#clone()
- */
- public Object clone() {
- DocumentCharacterIterator i= new DocumentCharacterIterator();
- i.fDocument= fDocument;
- i.fIndex= fIndex;
- i.fOffset= fOffset;
- i.fEndOffset= fEndOffset;
- return i;
- }
- }
-
-
- /**
- * The document character iterator used by this strategy.
- *
- */
- private DocumentCharacterIterator fDocIter= new DocumentCharacterIterator();
-
-
- /**
- * Creates a new default text double click strategy.
- */
- public JavadocDoubleClickStrategy() {
- super();
- }
-
- /*
- * @see org.eclipse.jface.text.ITextDoubleClickStrategy#doubleClicked(org.eclipse.jface.text.ITextViewer)
- */
- public void doubleClicked(ITextViewer text) {
-
- int position= text.getSelectedRange().x;
-
- if (position < 0)
- return;
-
- IRegion word= getWordRegion(text.getDocument(), position);
-
- if (word != null)
- text.setSelectedRange(word.getOffset(), word.getLength());
- }
-
- /**
- * Returns a region describing the word around <code>position</code>.
- *
- * @param document the document
- * @param position the offset around which to return the word
- * @return the word's region, or <code>null</code> for no selection
- */
- private IRegion getWordRegion(IDocument document, int position) {
- try {
-
- IRegion line= document.getLineInformationOfOffset(position);
- if (position == line.getOffset() + line.getLength())
- return null;
-
- fDocIter.setDocument(document, line);
-
- BreakIterator breakIter= BreakIterator.getWordInstance();
- breakIter.setText(fDocIter);
-
- int start= breakIter.preceding(position);
- if (start == BreakIterator.DONE)
- start= line.getOffset();
-
- int end= breakIter.following(position);
- if (end == BreakIterator.DONE)
- end= line.getOffset() + line.getLength();
-
- if (breakIter.isBoundary(position)) {
- if (end - position > position- start)
- start= position;
- else
- end= position;
- }
-
- if (start > 0 && document.getChar(start - 1) == '@' && Character.isJavaIdentifierPart(document.getChar(start))
- && (start == 1 || Character.isWhitespace(document.getChar(start - 2)) || document.getChar(start - 2) == '{')) {
- // double click after @ident
- start--;
- } else if (end == position && end == start + 1 && end < line.getOffset() + line.getLength() && document.getChar(end) == '@') {
- // double click before " @ident"
- return getWordRegion(document, position + 1);
- }
-
- if (start == end)
- return null;
- return new Region(start, end - start);
-
- } catch (BadLocationException x) {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyGenericTypeProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyGenericTypeProposal.java
deleted file mode 100644
index 0767c9b1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyGenericTypeProposal.java
+++ /dev/null
@@ -1,455 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationExtension;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Proposal for generic types.
- * <p>
- * Only used when compliance is set to 5.0 or higher.
- * </p>
- */
-public final class LazyGenericTypeProposal extends LazyJavaTypeCompletionProposal {
- /** Triggers for types. Do not modify. */
- private final static char[] GENERIC_TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', '<', ' ' };
-
- /**
- * Short-lived context information object for generic types. Currently, these
- * are only created after inserting a type proposal, as core doesn't give us
- * the correct type proposal from within SomeType<|>.
- */
- private static class ContextInformation implements IContextInformation, IContextInformationExtension {
- private final String fInformationDisplayString;
- private final String fContextDisplayString;
- private final Image fImage;
- private final int fPosition;
-
- ContextInformation(LazyGenericTypeProposal proposal) {
- // don't cache the proposal as content assistant
- // might hang on to the context info
- fContextDisplayString= proposal.getDisplayString();
- fInformationDisplayString= computeContextString(proposal);
- fImage= proposal.getImage();
- fPosition= proposal.getReplacementOffset() + proposal.getReplacementString().indexOf('<') + 1;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContextInformation#getContextDisplayString()
- */
- public String getContextDisplayString() {
- return fContextDisplayString;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContextInformation#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContextInformation#getInformationDisplayString()
- */
- public String getInformationDisplayString() {
- return fInformationDisplayString;
- }
-
- private String computeContextString(LazyGenericTypeProposal proposal) {
- try {
- TypeArgumentProposal[] proposals= proposal.computeTypeArgumentProposals();
- if (proposals.length == 0)
- return null;
-
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < proposals.length; i++) {
- buf.append(proposals[i].getDisplayName());
- if (i < proposals.length - 1)
- buf.append(", "); //$NON-NLS-1$
- }
- return buf.toString();
-
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.IContextInformationExtension#getContextInformationPosition()
- */
- public int getContextInformationPosition() {
- return fPosition;
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (obj instanceof ContextInformation) {
- ContextInformation ci= (ContextInformation) obj;
- return getContextInformationPosition() == ci.getContextInformationPosition() && getInformationDisplayString().equals(ci.getInformationDisplayString());
- }
- return false;
- }
- }
-
- private static final class TypeArgumentProposal {
- private final boolean fIsAmbiguous;
- private final String fProposal;
- private final String fTypeDisplayName;
-
- TypeArgumentProposal(String proposal, boolean ambiguous, String typeDisplayName) {
- fIsAmbiguous= ambiguous;
- fProposal= proposal;
- fTypeDisplayName= typeDisplayName;
- }
-
- public String getDisplayName() {
- return fTypeDisplayName;
- }
-
- boolean isAmbiguous() {
- return fIsAmbiguous;
- }
-
- String getProposals() {
- return fProposal;
- }
-
- public String toString() {
- return fProposal;
- }
- }
-
- private IRegion fSelectedRegion; // initialized by apply()
- private TypeArgumentProposal[] fTypeArgumentProposals;
-
- public LazyGenericTypeProposal(CompletionProposal typeProposal, JavaContentAssistInvocationContext context) {
- super(typeProposal, context);
- }
-
- /*
- * @see ICompletionProposalExtension#apply(IDocument, char)
- */
- public void apply(IDocument document, char trigger, int offset) {
-
- if (shouldAppendArguments(document, offset, trigger)) {
- try {
- TypeArgumentProposal[] typeArgumentProposals= computeTypeArgumentProposals();
- if (typeArgumentProposals.length > 0) {
-
- int[] offsets= new int[typeArgumentProposals.length];
- int[] lengths= new int[typeArgumentProposals.length];
- StringBuffer buffer= createParameterList(typeArgumentProposals, offsets, lengths);
-
- // set the generic type as replacement string
- boolean insertClosingParenthesis= trigger == '(' && autocloseBrackets();
- if (insertClosingParenthesis)
- updateReplacementWithParentheses(buffer);
- super.setReplacementString(buffer.toString());
-
- // add import & remove package, update replacement offset
- super.apply(document, '\0', offset);
-
- if (getTextViewer() != null) {
- if (hasAmbiguousProposals(typeArgumentProposals)) {
- adaptOffsets(offsets, buffer);
- installLinkedMode(document, offsets, lengths, typeArgumentProposals, insertClosingParenthesis);
- } else {
- if (insertClosingParenthesis)
- setUpLinkedMode(document, ')');
- else
- fSelectedRegion= new Region(getReplacementOffset() + getReplacementString().length(), 0);
- }
- }
-
- return;
- }
- } catch (JavaScriptModelException e) {
- // log and continue
- JavaScriptPlugin.log(e);
- }
- }
-
- // default is to use the super implementation
- // reasons:
- // - not a parameterized type,
- // - already followed by <type arguments>
- // - proposal type does not inherit from expected type
- super.apply(document, trigger, offset);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal#computeTriggerCharacters()
- */
- protected char[] computeTriggerCharacters() {
- return GENERIC_TYPE_TRIGGERS;
- }
-
- /**
- * Adapt the parameter offsets to any modification of the replacement
- * string done by <code>apply</code>. For example, applying the proposal
- * may add an import instead of inserting the fully qualified name.
- * <p>
- * This assumes that modifications happen only at the beginning of the
- * replacement string and do not touch the type arguments list.
- * </p>
- *
- * @param offsets the offsets to modify
- * @param buffer the original replacement string
- */
- private void adaptOffsets(int[] offsets, StringBuffer buffer) {
- String replacementString= getReplacementString();
- int delta= buffer.length() - replacementString.length(); // due to using an import instead of package
- for (int i= 0; i < offsets.length; i++) {
- offsets[i]-= delta;
- }
- }
-
- /**
- * Computes the type argument proposals for this type proposals. If there is
- * an expected type binding that is a super type of the proposed type, the
- * wildcard type arguments of the proposed type that can be mapped through
- * to type the arguments of the expected type binding are bound accordingly.
- * <p>
- * For type arguments that cannot be mapped to arguments in the expected
- * type, or if there is no expected type, the upper bound of the type
- * argument is proposed.
- * </p>
- * <p>
- * The argument proposals have their <code>isAmbiguos</code> flag set to
- * <code>false</code> if the argument can be mapped to a non-wildcard type
- * argument in the expected type, otherwise the proposal is ambiguous.
- * </p>
- *
- * @return the type argument proposals for the proposed type
- * @throws JavaScriptModelException if accessing the java model fails
- */
- private TypeArgumentProposal[] computeTypeArgumentProposals() throws JavaScriptModelException {
- if (fTypeArgumentProposals == null) {
-
- IType type= (IType) getJavaElement();
- if (type == null)
- return new TypeArgumentProposal[0];
-
-
- return new TypeArgumentProposal[0];
- }
- return fTypeArgumentProposals;
- }
-
- /**
- * Returns <code>true</code> if type arguments should be appended when
- * applying this proposal, <code>false</code> if not (for example if the
- * document already contains a type argument list after the insertion point.
- *
- * @param document the document
- * @param offset the insertion offset
- * @param trigger the trigger character
- * @return <code>true</code> if arguments should be appended
- */
- private boolean shouldAppendArguments(IDocument document, int offset, char trigger) {
- /*
- * No argument list if there were any special triggers (for example a period to qualify an
- * inner type).
- */
- if (trigger != '\0' && trigger != '<' && trigger != '(')
- return false;
-
- /* No argument list if the completion is empty (already within the argument list). */
- char[] completion= fProposal.getCompletion();
- if (completion.length == 0)
- return false;
-
- /* No argument list if there already is a generic signature behind the name. */
- try {
- IRegion region= document.getLineInformationOfOffset(offset);
- String line= document.get(region.getOffset(), region.getLength());
-
- int index= offset - region.getOffset();
- while (index != line.length() && Character.isUnicodeIdentifierPart(line.charAt(index)))
- ++index;
-
- if (index == line.length())
- return true;
-
- char ch= line.charAt(index);
- return ch != '<';
-
- } catch (BadLocationException e) {
- return true;
- }
- }
-
- private StringBuffer createParameterList(TypeArgumentProposal[] typeArguments, int[] offsets, int[] lengths) {
- StringBuffer buffer= new StringBuffer();
- buffer.append(getReplacementString());
-
- FormatterPrefs prefs= getFormatterPrefs();
- final char LESS= '<';
- final char GREATER= '>';
- if (prefs.beforeOpeningBracket)
- buffer.append(SPACE);
- buffer.append(LESS);
- if (prefs.afterOpeningBracket)
- buffer.append(SPACE);
- StringBuffer separator= new StringBuffer(3);
- if (prefs.beforeTypeArgumentComma)
- separator.append(SPACE);
- separator.append(COMMA);
- if (prefs.afterTypeArgumentComma)
- separator.append(SPACE);
-
- for (int i= 0; i != typeArguments.length; i++) {
- if (i != 0)
- buffer.append(separator);
-
- offsets[i]= buffer.length();
- buffer.append(typeArguments[i]);
- lengths[i]= buffer.length() - offsets[i];
- }
- if (prefs.beforeClosingBracket)
- buffer.append(SPACE);
- buffer.append(GREATER);
-
- return buffer;
- }
-
- private void installLinkedMode(IDocument document, int[] offsets, int[] lengths, TypeArgumentProposal[] typeArgumentProposals, boolean withParentheses) {
- int replacementOffset= getReplacementOffset();
- String replacementString= getReplacementString();
-
- try {
- LinkedModeModel model= new LinkedModeModel();
- for (int i= 0; i != offsets.length; i++) {
- if (typeArgumentProposals[i].isAmbiguous()) {
- LinkedPositionGroup group= new LinkedPositionGroup();
- group.addPosition(new LinkedPosition(document, replacementOffset + offsets[i], lengths[i]));
- model.addGroup(group);
- }
- }
- if (withParentheses) {
- LinkedPositionGroup group= new LinkedPositionGroup();
- group.addPosition(new LinkedPosition(document, replacementOffset + getCursorPosition(), 0));
- model.addGroup(group);
- }
-
- model.forceInstall();
- JavaEditor editor= getJavaEditor();
- if (editor != null) {
- model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
- }
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer());
- ui.setExitPolicy(new ExitPolicy(withParentheses ? ')' : '>', document));
- ui.setExitPosition(getTextViewer(), replacementOffset + replacementString.length(), 0, Integer.MAX_VALUE);
- ui.setDoContextInfo(true);
- ui.enter();
-
- fSelectedRegion= ui.getSelectedRegion();
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- openErrorDialog(e);
- }
- }
-
- private boolean hasAmbiguousProposals(TypeArgumentProposal[] typeArgumentProposals) {
- boolean hasAmbiguousProposals= false;
- for (int i= 0; i < typeArgumentProposals.length; i++) {
- if (typeArgumentProposals[i].isAmbiguous()) {
- hasAmbiguousProposals= true;
- break;
- }
- }
- return hasAmbiguousProposals;
- }
-
- /**
- * Returns the currently active java editor, or <code>null</code> if it
- * cannot be determined.
- *
- * @return the currently active java editor, or <code>null</code>
- */
- private JavaEditor getJavaEditor() {
- IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor();
- if (part instanceof JavaEditor)
- return (JavaEditor) part;
- else
- return null;
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- if (fSelectedRegion == null)
- return super.getSelection(document);
-
- return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
- }
-
- private void openErrorDialog(BadLocationException e) {
- Shell shell= getTextViewer().getTextWidget().getShell();
- MessageDialog.openError(shell, JavaTextMessages.FilledArgumentNamesMethodProposal_error_msg, e.getMessage());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeContextInformation()
- */
- protected IContextInformation computeContextInformation() {
- try {
- if (hasParameters()) {
- TypeArgumentProposal[] proposals= computeTypeArgumentProposals();
- if (hasAmbiguousProposals(proposals))
- return new ContextInformation(this);
- }
- } catch (JavaScriptModelException e) {
- }
- return super.computeContextInformation();
- }
-
- protected int computeCursorPosition() {
- if (fSelectedRegion != null)
- return fSelectedRegion.getOffset() - getReplacementOffset();
- return super.computeCursorPosition();
- }
-
- private boolean hasParameters() {
- IType type= (IType) getJavaElement();
- if (type == null)
- return false;
-
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java
deleted file mode 100644
index 0f7ee37e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java
+++ /dev/null
@@ -1,428 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-
-public class LazyJavaCompletionProposal extends AbstractJavaCompletionProposal {
-
- protected static final String LPAREN= "("; //$NON-NLS-1$
- protected static final String RPAREN= ")"; //$NON-NLS-1$
- protected static final String COMMA= ","; //$NON-NLS-1$
- protected static final String SPACE= " "; //$NON-NLS-1$
-
- protected static final class FormatterPrefs {
- /* Methods & constructors */
- public final boolean beforeOpeningParen;
- public final boolean afterOpeningParen;
- public final boolean beforeComma;
- public final boolean afterComma;
- public final boolean beforeClosingParen;
- public final boolean inEmptyList;
-
- /* type parameters */
- public final boolean beforeOpeningBracket;
- public final boolean afterOpeningBracket;
- public final boolean beforeTypeArgumentComma;
- public final boolean afterTypeArgumentComma;
- public final boolean beforeClosingBracket;
-
- FormatterPrefs(IJavaScriptProject project) {
- beforeOpeningParen= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION, false);
- afterOpeningParen= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION, false);
- beforeComma= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, false);
- afterComma= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS, true);
- beforeClosingParen= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION, false);
- inEmptyList= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION, false);
-
- beforeOpeningBracket= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, false);
- afterOpeningBracket= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_OPENING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, false);
- beforeTypeArgumentComma= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, false);
- afterTypeArgumentComma= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_PARAMETERIZED_TYPE_REFERENCE, true);
- beforeClosingBracket= getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_CLOSING_ANGLE_BRACKET_IN_PARAMETERIZED_TYPE_REFERENCE, false);
- }
-
- protected final boolean getCoreOption(IJavaScriptProject project, String key, boolean def) {
- String option= getCoreOption(project, key);
- if (JavaScriptCore.INSERT.equals(option))
- return true;
- if (JavaScriptCore.DO_NOT_INSERT.equals(option))
- return false;
- return def;
- }
-
- protected final String getCoreOption(IJavaScriptProject project, String key) {
- if (project == null)
- return JavaScriptCore.getOption(key);
- return project.getOption(key, true);
- }
- }
-
- private boolean fDisplayStringComputed;
- private boolean fReplacementStringComputed;
- private boolean fReplacementOffsetComputed;
- private boolean fReplacementLengthComputed;
- private boolean fCursorPositionComputed;
- private boolean fImageComputed;
- private boolean fContextInformationComputed;
- private boolean fProposalInfoComputed;
- private boolean fTriggerCharactersComputed;
- private boolean fSortStringComputed;
- private boolean fRelevanceComputed;
- private FormatterPrefs fFormatterPrefs;
-
- /**
- * The core proposal wrapped by this completion proposal.
- */
- protected final CompletionProposal fProposal;
- protected int fContextInformationPosition;
-
- public LazyJavaCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(context);
- Assert.isNotNull(proposal);
- Assert.isNotNull(context);
- Assert.isNotNull(context.getCoreContext());
- fProposal= proposal;
- }
-
- /*
- * @see ICompletionProposalExtension#getTriggerCharacters()
- */
- public final char[] getTriggerCharacters() {
- if (!fTriggerCharactersComputed)
- setTriggerCharacters(computeTriggerCharacters());
- return super.getTriggerCharacters();
- }
-
- protected char[] computeTriggerCharacters() {
- return new char[0];
- }
-
- /**
- * Sets the trigger characters.
- * @param triggerCharacters The set of characters which can trigger the application of this completion proposal
- */
- public final void setTriggerCharacters(char[] triggerCharacters) {
- fTriggerCharactersComputed= true;
- super.setTriggerCharacters(triggerCharacters);
- }
-
- /**
- * Sets the proposal info.
- * @param proposalInfo The additional information associated with this proposal or <code>null</code>
- */
- public final void setProposalInfo(ProposalInfo proposalInfo) {
- fProposalInfoComputed= true;
- super.setProposalInfo(proposalInfo);
- }
-
- /**
- * Returns the additional proposal info, or <code>null</code> if none
- * exists.
- *
- * @return the additional proposal info, or <code>null</code> if none
- * exists
- */
- protected final ProposalInfo getProposalInfo() {
- if (!fProposalInfoComputed)
- setProposalInfo(computeProposalInfo());
- return super.getProposalInfo();
- }
-
- protected ProposalInfo computeProposalInfo() {
- return null;
- }
-
- /**
- * Sets the cursor position relative to the insertion offset. By default this is the length of the completion string
- * (Cursor positioned after the completion)
- * @param cursorPosition The cursorPosition to set
- */
- public final void setCursorPosition(int cursorPosition) {
- fCursorPositionComputed= true;
- super.setCursorPosition(cursorPosition);
- }
-
- protected final int getCursorPosition() {
- if (!fCursorPositionComputed)
- setCursorPosition(computeCursorPosition());
- return super.getCursorPosition();
- }
-
- protected int computeCursorPosition() {
- return getReplacementString().length();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isInJavadoc()
- */
- protected final boolean isInJavadoc() {
- return fInvocationContext.getCoreContext().isInJsdoc();
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public final IContextInformation getContextInformation() {
- if (!fContextInformationComputed)
- setContextInformation(computeContextInformation());
- return super.getContextInformation();
- }
-
- protected IContextInformation computeContextInformation() {
- return null;
- }
-
- /**
- * Sets the context information.
- * @param contextInformation The context information associated with this proposal
- */
- public final void setContextInformation(IContextInformation contextInformation) {
- fContextInformationComputed= true;
- super.setContextInformation(contextInformation);
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public final String getDisplayString() {
- if (!fDisplayStringComputed)
- setDisplayString(computeDisplayString());
- return super.getDisplayString();
- }
-
- protected final void setDisplayString(String string) {
- fDisplayStringComputed= true;
- super.setDisplayString(string);
- }
-
- protected String computeDisplayString() {
- return fInvocationContext.getLabelProvider().createLabel(fProposal);
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public final String getAdditionalProposalInfo() {
- return super.getAdditionalProposalInfo();
- }
-
- /*
- * @see ICompletionProposalExtension#getContextInformationPosition()
- */
- public final int getContextInformationPosition() {
- if (getContextInformation() == null)
- return getReplacementOffset() - 1;
- return getReplacementOffset() + getCursorPosition();
- }
-
- /**
- * Gets the replacement offset.
- * @return Returns a int
- */
- public final int getReplacementOffset() {
- if (!fReplacementOffsetComputed)
- setReplacementOffset(fProposal.getReplaceStart());
- return super.getReplacementOffset();
- }
-
- /**
- * Sets the replacement offset.
- * @param replacementOffset The replacement offset to set
- */
- public final void setReplacementOffset(int replacementOffset) {
- fReplacementOffsetComputed= true;
- super.setReplacementOffset(replacementOffset);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getCompletionOffset()
- */
- public final int getPrefixCompletionStart(IDocument document, int completionOffset) {
- return getReplacementOffset();
- }
-
- /**
- * Gets the replacement length.
- * @return Returns a int
- */
- public final int getReplacementLength() {
- if (!fReplacementLengthComputed)
- setReplacementLength(fProposal.getReplaceEnd() - fProposal.getReplaceStart());
- return super.getReplacementLength();
- }
-
- /**
- * Sets the replacement length.
- * @param replacementLength The replacementLength to set
- */
- public final void setReplacementLength(int replacementLength) {
- fReplacementLengthComputed= true;
- super.setReplacementLength(replacementLength);
- }
-
- /**
- * Gets the replacement string.
- * @return Returns a String
- */
- public final String getReplacementString() {
- if (!fReplacementStringComputed)
- setReplacementString(computeReplacementString());
- return super.getReplacementString();
- }
-
- protected String computeReplacementString() {
- return String.valueOf(fProposal.getCompletion());
- }
-
- /**
- * Sets the replacement string.
- * @param replacementString The replacement string to set
- */
- public final void setReplacementString(String replacementString) {
- fReplacementStringComputed= true;
- super.setReplacementString(replacementString);
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public final Image getImage() {
- if (!fImageComputed)
- setImage(computeImage());
- return super.getImage();
- }
-
- protected Image computeImage() {
- return JavaScriptPlugin.getImageDescriptorRegistry().get(fInvocationContext.getLabelProvider().createImageDescriptor(fProposal));
- }
-
- /**
- * Sets the image.
- * @param image The image to set
- */
- public final void setImage(Image image) {
- fImageComputed= true;
- super.setImage(image);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String)
- */
- protected boolean isValidPrefix(String prefix) {
- if (super.isValidPrefix(prefix))
- return true;
-
- if (fProposal.getKind() == CompletionProposal.METHOD_NAME_REFERENCE) {
- // static imports - includes package & type name
- StringBuffer buf= new StringBuffer();
- buf.append(Signature.toCharArray(fProposal.getDeclarationSignature()));
- buf.append('.');
- buf.append(getDisplayString());
- return isPrefix(prefix, buf.toString());
- }
-
- return false;
- }
-
- /**
- * Gets the proposal's relevance.
- * @return Returns a int
- */
- public final int getRelevance() {
- if (!fRelevanceComputed)
- setRelevance(computeRelevance());
- return super.getRelevance();
- }
-
- /**
- * Sets the proposal's relevance.
- * @param relevance The relevance to set
- */
- public final void setRelevance(int relevance) {
- fRelevanceComputed= true;
- super.setRelevance(relevance);
- }
-
- protected int computeRelevance() {
- final int baseRelevance= fProposal.getRelevance() * 16;
- switch (fProposal.getKind()) {
- case CompletionProposal.PACKAGE_REF:
- return baseRelevance + 0;
- case CompletionProposal.LABEL_REF:
- return baseRelevance + 1;
- case CompletionProposal.KEYWORD:
- return baseRelevance + 2;
- case CompletionProposal.TYPE_REF:
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- return baseRelevance + 3;
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.METHOD_DECLARATION:
- return baseRelevance + 4;
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- return baseRelevance + 4 /* + 99 */;
- case CompletionProposal.FIELD_REF:
- return baseRelevance + 5;
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- return baseRelevance + 6;
- default:
- return baseRelevance;
- }
- }
-
- public final String getSortString() {
- if (!fSortStringComputed)
- setSortString(computeSortString());
- return super.getSortString();
- }
-
- protected final void setSortString(String string) {
- fSortStringComputed= true;
- super.setSortString(string);
- }
-
- protected String computeSortString() {
- return getDisplayString();
- }
-
- protected FormatterPrefs getFormatterPrefs() {
- if (fFormatterPrefs == null) {
- IJavaScriptUnit cu= fInvocationContext.getCompilationUnit();
- fFormatterPrefs= new FormatterPrefs(cu == null ? null : cu.getJavaScriptProject());
- }
- return fFormatterPrefs;
- }
-
- /**
- * Overrides the default context information position. Ignored if set to zero.
- *
- * @param contextInformationPosition the replaced position.
- */
- public void setContextInformationPosition(int contextInformationPosition) {
- fContextInformationPosition= contextInformationPosition;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java
deleted file mode 100644
index 3446017d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java
+++ /dev/null
@@ -1,372 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * If passed compilation unit is not null, the replacement string will be seen as a qualified type name.
- */
-public class LazyJavaTypeCompletionProposal extends LazyJavaCompletionProposal {
- /** Triggers for types. Do not modify. */
- protected static final char[] TYPE_TRIGGERS= new char[] { '\t', '[', '(', ' ' };
- /** Triggers for types in javadoc. Do not modify. */
- protected static final char[] JDOC_TYPE_TRIGGERS= new char[] { '#', '}', ' ', '.' };
-
- /** The compilation unit, or <code>null</code> if none is available. */
- protected final IJavaScriptUnit fCompilationUnit;
-
- private String fQualifiedName;
- private String fSimpleName;
- private ImportRewrite fImportRewrite;
- private ContextSensitiveImportRewriteContext fImportContext;
-
- public LazyJavaTypeCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- fCompilationUnit= context.getCompilationUnit();
- fQualifiedName= null;
- }
-
- public final String getQualifiedTypeName() {
- if (fQualifiedName == null)
- fQualifiedName= String.valueOf(Signature.toCharArray(fProposal.getSignature()));
- return fQualifiedName;
- }
-
- protected final String getSimpleTypeName() {
- if (fSimpleName == null)
- fSimpleName= Signature.getSimpleName(getQualifiedTypeName());
- return fSimpleName;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
- String replacement= super.computeReplacementString();
-
-// /* No import rewriting ever from within the import section. */
-// if (isImportCompletion())
-// return replacement;
-
- /* Always use the simple name for non-formal javadoc references to types. */
- // TODO fix
- if (fProposal.getKind() == CompletionProposal.TYPE_REF && fInvocationContext.getCoreContext().isInJsdocText())
- return getSimpleTypeName();
-
- String qualifiedTypeName= replacement;
-// if (qualifiedTypeName.indexOf('.') == -1)
-// // default package - no imports needed
-// return qualifiedTypeName;
-
- /*
- * If the user types in the qualification, don't force import rewriting on him - insert the
- * qualified name.
- */
- IDocument document= fInvocationContext.getDocument();
- if (document != null) {
- String prefix= getPrefix(document, getReplacementOffset() + getReplacementLength());
- int dotIndex= prefix.lastIndexOf('.');
- // match up to the last dot in order to make higher level matching still work (camel case...)
- if (dotIndex != -1 && qualifiedTypeName.toLowerCase().startsWith(prefix.substring(0, dotIndex + 1).toLowerCase()))
- return qualifiedTypeName;
- }
-
- /*
- * The replacement does not contain a qualification (e.g. an inner type qualified by its
- * parent) - use the replacement directly.
- */
- if (replacement.indexOf('.') == -1) {
- if (isInJavadoc())
- return getSimpleTypeName(); // don't use the braces added for javadoc link proposals
- return replacement;
- }
-
- /* Add imports if the preference is on. */
- fImportRewrite= createImportRewrite();
-
-// if (fImportRewrite != null) {
-// String packageName=null;
-// try {
-// IJavaScriptElement javaElement = this.getProposalInfo().getJavaElement();
-// packageName=JavaModelUtil.getFilePackage(javaElement);
-// } catch (JavaScriptModelException e) {
-// JavaScriptPlugin.log(e);
-// }
-// return fImportRewrite.addImport(qualifiedTypeName,packageName, fImportContext);
-// }
-
- // fall back for the case we don't have an import rewrite (see allowAddingImports)
-
- /* No imports for implicit imports. */
- if (fCompilationUnit != null && JavaModelUtil.isImplicitImport(Signature.getQualifier(qualifiedTypeName), fCompilationUnit)) {
- return Signature.getSimpleName(qualifiedTypeName);
- }
-
- /* Default: use the fully qualified type name. */
- return qualifiedTypeName;
- }
-
- protected final boolean isImportCompletion() {
- char[] completion= fProposal.getCompletion();
- if (completion.length == 0)
- return false;
-
- char last= completion[completion.length - 1];
- /*
- * Proposals end in a semicolon when completing types in normal imports or when completing
- * static members, in a period when completing types in static imports.
- */
- return last == ';' || last == '.';
- }
-
- private ImportRewrite createImportRewrite() {
- if (fCompilationUnit != null && allowAddingImports()) {
- try {
- JavaScriptUnit cu= getASTRoot(fCompilationUnit);
- if (cu == null) {
- ImportRewrite rewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
- fImportContext= null;
- return rewrite;
- } else {
- ImportRewrite rewrite= StubUtility.createImportRewrite(cu, true);
- fImportContext= new ContextSensitiveImportRewriteContext(cu, fInvocationContext.getInvocationOffset(), rewrite);
- return rewrite;
- }
- } catch (CoreException x) {
- JavaScriptPlugin.log(x);
- }
- }
- return null;
- }
-
- private JavaScriptUnit getASTRoot(IJavaScriptUnit compilationUnit) {
- return JavaScriptPlugin.getDefault().getASTProvider().getAST(compilationUnit, ASTProvider.WAIT_NO, new NullProgressMonitor());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- try {
- boolean insertClosingParenthesis= trigger == '(' && autocloseBrackets();
- if (insertClosingParenthesis) {
- StringBuffer replacement= new StringBuffer(getReplacementString());
- updateReplacementWithParentheses(replacement);
- setReplacementString(replacement.toString());
- trigger= '\0';
- }
-
- super.apply(document, trigger, offset);
-
- if (fImportRewrite != null && fImportRewrite.hasRecordedChanges()) {
- int oldLen= document.getLength();
- fImportRewrite.rewriteImports(new NullProgressMonitor()).apply(document, TextEdit.UPDATE_REGIONS);
- setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
- }
-
- if (insertClosingParenthesis)
- setUpLinkedMode(document, ')');
-
- rememberSelection();
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- protected void updateReplacementWithParentheses(StringBuffer replacement) {
- FormatterPrefs prefs= getFormatterPrefs();
-
- if (prefs.beforeOpeningParen)
- replacement.append(SPACE);
- replacement.append(LPAREN);
-
-
- if (prefs.afterOpeningParen)
- replacement.append(SPACE);
-
- setCursorPosition(replacement.length());
-
- if (prefs.afterOpeningParen)
- replacement.append(SPACE);
-
- replacement.append(RPAREN);
- }
-
- /**
- * Remembers the selection in the content assist history.
- *
- * @throws JavaScriptModelException if anything goes wrong
- *
- */
- protected final void rememberSelection() throws JavaScriptModelException {
- IType lhs= fInvocationContext.getExpectedType();
- IType rhs= (IType) getJavaElement();
- if (lhs != null && rhs != null)
- JavaScriptPlugin.getDefault().getContentAssistHistory().remember(lhs, rhs);
-
- QualifiedTypeNameHistory.remember(getQualifiedTypeName());
- }
-
- /**
- * Returns <code>true</code> if imports may be added. The return value depends on the context
- * and preferences only and does not take into account the contents of the compilation unit or
- * the kind of proposal. Even if <code>true</code> is returned, there may be cases where no
- * imports are added for the proposal. For example:
- * <ul>
- * <li>when completing within the import section</li>
- * <li>when completing informal javadoc references (e.g. within <code>&lt;code&gt;</code>
- * tags)</li>
- * <li>when completing a type that conflicts with an existing import</li>
- * <li>when completing an implicitly imported type (same package, <code>java.lang</code>
- * types)</li>
- * </ul>
- * <p>
- * The decision whether a qualified type or the simple type name should be inserted must take
- * into account these different scenarios.
- * </p>
- * <p>
- * Subclasses may extend.
- * </p>
- *
- * @return <code>true</code> if imports may be added, <code>false</code> if not
- */
- protected boolean allowAddingImports() {
- if (isInJavadoc()) {
- // TODO fix
-// if (!fContext.isInJavadocFormalReference())
-// return false;
- if (fProposal.getKind() == CompletionProposal.TYPE_REF && fInvocationContext.getCoreContext().isInJsdocText())
- return false;
-
- if (!isJavadocProcessingEnabled())
- return false;
- }
-
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- return preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_ADDIMPORT);
- }
-
- private boolean isJavadocProcessingEnabled() {
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- boolean processJavadoc;
- if (project == null)
- processJavadoc= JavaScriptCore.ENABLED.equals(JavaScriptCore.getOption(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT));
- else
- processJavadoc= JavaScriptCore.ENABLED.equals(project.getOption(JavaScriptCore.COMPILER_DOC_COMMENT_SUPPORT, true));
- return processJavadoc;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#isValidPrefix(java.lang.String)
- */
- protected boolean isValidPrefix(String prefix) {
- return isPrefix(prefix, getSimpleTypeName()) || isPrefix(prefix, getQualifiedTypeName());
- }
-
- public boolean isValidTypePrefix(String prefix) {
- return isValidPrefix(prefix);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal#getCompletionText()
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- String prefix= getPrefix(document, completionOffset);
-
- String completion;
- // return the qualified name if the prefix is already qualified
- if (prefix.indexOf('.') != -1)
- completion= getQualifiedTypeName();
- else
- completion= getSimpleTypeName();
-
- if (isCamelCaseMatching())
- return getCamelCaseCompound(prefix, completion);
-
- return completion;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeTriggerCharacters()
- */
- protected char[] computeTriggerCharacters() {
- return isInJavadoc() ? JDOC_TYPE_TRIGGERS : TYPE_TRIGGERS;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeProposalInfo()
- */
- protected ProposalInfo computeProposalInfo() {
- if (fCompilationUnit != null) {
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- if (project != null)
- return new TypeProposalInfo(project, fProposal);
- }
- return super.computeProposalInfo();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeSortString()
- */
- protected String computeSortString() {
- // try fast sort string to avoid display string creation
- return getQualifiedTypeName();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeRelevance()
- */
- protected int computeRelevance() {
- /*
- * There are two histories: the RHS history remembers types used for the current expected
- * type (left hand side), while the type history remembers recently used types in general).
- *
- * The presence of an RHS ranking is a much more precise sign for relevance as it proves the
- * subtype relationship between the proposed type and the expected type.
- *
- * The "recently used" factor (of either the RHS or general history) is less important, it should
- * not override other relevance factors such as if the type is already imported etc.
- */
- float rhsHistoryRank= fInvocationContext.getHistoryRelevance(getQualifiedTypeName());
- float typeHistoryRank= QualifiedTypeNameHistory.getDefault().getNormalizedPosition(getQualifiedTypeName());
-
- int recencyBoost= Math.round((rhsHistoryRank + typeHistoryRank) * 5);
- int rhsBoost= rhsHistoryRank > 0.0f ? 50 : 0;
- int baseRelevance= super.computeRelevance();
-
- return baseRelevance + rhsBoost + recencyBoost;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java
deleted file mode 100644
index 55a424cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Proposal info that computes the javadoc lazily when it is queried.
- *
- *
- */
-public abstract class MemberProposalInfo extends ProposalInfo {
- /* configuration */
- protected final IJavaScriptProject fJavaProject;
- protected final CompletionProposal fProposal;
-
- /* cache filled lazily */
- private boolean fJavaElementResolved= false;
-
- /**
- * Creates a new proposal info.
- *
- * @param project the java project to reference when resolving types
- * @param proposal the proposal to generate information for
- */
- public MemberProposalInfo(IJavaScriptProject project, CompletionProposal proposal) {
- Assert.isNotNull(project);
- Assert.isNotNull(proposal);
- fJavaProject= project;
- fProposal= proposal;
- }
-
- /**
- * Returns the java element that this computer corresponds to, possibly <code>null</code>.
- *
- * @return the java element that this computer corresponds to, possibly <code>null</code>
- * @throws JavaScriptModelException
- */
- public IJavaScriptElement getJavaElement() throws JavaScriptModelException {
- if (!fJavaElementResolved) {
- fJavaElementResolved= true;
- fElement= resolveMember();
- }
- return fElement;
- }
-
- /**
- * Resolves the member described by the receiver and returns it if found.
- * Returns <code>null</code> if no corresponding member can be found.
- *
- * @return the resolved member or <code>null</code> if none is found
- * @throws JavaScriptModelException if accessing the java model fails
- */
- protected abstract IMember resolveMember() throws JavaScriptModelException;
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodDeclarationCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodDeclarationCompletionProposal.java
deleted file mode 100644
index 12868532..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodDeclarationCompletionProposal.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Collection;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-/**
- * Method declaration proposal.
- */
-public class MethodDeclarationCompletionProposal extends JavaTypeCompletionProposal implements ICompletionProposalExtension4 {
-
-
- public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set suggestedMethods, Collection result) throws CoreException {
- IFunction[] methods= type.getFunctions();
- String constructorName= type.getElementName();
- if (constructorName.length() > 0 && constructorName.startsWith(prefix) && !hasMethod(methods, constructorName) && suggestedMethods.add(constructorName)) {
- result.add(new MethodDeclarationCompletionProposal(type, constructorName, null, offset, length, relevance + 500));
- }
-
- if (prefix.length() > 0 && !"main".equals(prefix) && !hasMethod(methods, prefix) && suggestedMethods.add(prefix)) { //$NON-NLS-1$
- if (!JavaScriptConventions.validateFunctionName(prefix).matches(IStatus.ERROR)) {
- result.add(new MethodDeclarationCompletionProposal(type, prefix, Signature.SIG_VOID, offset, length, relevance));
- }
- }
- }
-
- private static boolean hasMethod(IFunction[] methods, String name) {
- for (int i= 0; i < methods.length; i++) {
- IFunction curr= methods[i];
- if (curr.getElementName().equals(name) && curr.getParameterTypes().length == 0) {
- return true;
- }
- }
- return false;
- }
-
- private final IType fType;
- private final String fReturnTypeSig;
- private final String fMethodName;
-
- public MethodDeclarationCompletionProposal(IType type, String methodName, String returnTypeSig, int start, int length, int relevance) {
- super("", type.getJavaScriptUnit(), start, length, null, getDisplayName(methodName, returnTypeSig), relevance); //$NON-NLS-1$
- Assert.isNotNull(type);
- Assert.isNotNull(methodName);
-
- fType= type;
- fMethodName= methodName;
- fReturnTypeSig= returnTypeSig;
-
- if (returnTypeSig == null) {
- setProposalInfo(new ProposalInfo(type));
-
- ImageDescriptor desc= new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaScriptElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
- setImage(JavaScriptPlugin.getImageDescriptorRegistry().get(desc));
- } else {
- setImage(JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE));
- }
- }
-
- private static String getDisplayName(String methodName, String returnTypeSig) {
- StringBuffer buf= new StringBuffer();
- buf.append(methodName);
- buf.append('(');
- buf.append(')');
- if (returnTypeSig != null) {
- buf.append(" "); //$NON-NLS-1$
- buf.append(Signature.toString(returnTypeSig));
- buf.append(" - "); //$NON-NLS-1$
- buf.append(JavaTextMessages.MethodCompletionProposal_method_label);
- } else {
- buf.append(" - "); //$NON-NLS-1$
- buf.append(JavaTextMessages.MethodCompletionProposal_constructor_label);
- }
- return buf.toString();
- }
-
- /* (non-Javadoc)
- * @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportRewrite)
- */
- protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fType.getJavaScriptProject());
- boolean addComments= settings.createComments;
-
- String[] empty= new String[0];
- String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
- String declTypeName= fType.getTypeQualifiedName('.');
-
- StringBuffer buf= new StringBuffer();
- if (addComments) {
- String comment= CodeGeneration.getMethodComment(fType.getJavaScriptUnit(), declTypeName, fMethodName, empty, empty, fReturnTypeSig, null, lineDelim);
- if (comment != null) {
- buf.append(comment);
- buf.append(lineDelim);
- }
- }
- if (fReturnTypeSig != null) {
- buf.append("private "); //$NON-NLS-1$
- } else {
- buf.append("public "); //$NON-NLS-1$
- }
-
- if (fReturnTypeSig != null) {
- buf.append(Signature.toString(fReturnTypeSig));
- }
- buf.append(' ');
- buf.append(fMethodName);
-
- buf.append("() {"); //$NON-NLS-1$
- buf.append(lineDelim);
-
- String body= CodeGeneration.getMethodBodyContent(fType.getJavaScriptUnit(), declTypeName, fMethodName, fReturnTypeSig == null, "", lineDelim); //$NON-NLS-1$
- if (body != null) {
- buf.append(body);
- buf.append(lineDelim);
- }
- buf.append("}"); //$NON-NLS-1$
- buf.append(lineDelim);
-
- String stub= buf.toString();
-
- // use the code formatter
- IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
- int lineStart= region.getOffset();
- int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth);
-
- String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, null, lineDelim, fType.getJavaScriptProject());
-
- if (replacement.endsWith(lineDelim)) {
- replacement= replacement.substring(0, replacement.length() - lineDelim.length());
- }
-
- setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
- return true;
- }
-
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- return new String(); // don't let method stub proposals complete incrementally
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
- */
- public boolean isAutoInsertable() {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java
deleted file mode 100644
index eccb0ed6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-
-
-/**
- * Proposal info that computes the javadoc lazily when it is queried.
- *
- *
- */
-public final class MethodProposalInfo extends MemberProposalInfo {
-
- /**
- * Fallback in case we can't match a generic method. The fall back is only based
- * on method name and number of parameters.
- */
- private IFunction fFallbackMatch;
-
- /**
- * Creates a new proposal info.
- *
- * @param project the java project to reference when resolving types
- * @param proposal the proposal to generate information for
- */
- public MethodProposalInfo(IJavaScriptProject project, CompletionProposal proposal) {
- super(project, proposal);
- }
-
- /**
- * Resolves the member described by the receiver and returns it if found.
- * Returns <code>null</code> if no corresponding member can be found.
- *
- * @return the resolved member or <code>null</code> if none is found
- * @throws JavaScriptModelException if accessing the java model fails
- */
- protected IMember resolveMember() throws JavaScriptModelException {
- char[] declarationSignature= fProposal.getDeclarationSignature();
- IFunction func = null;
- if (declarationSignature!=null) {
- String typeName = SignatureUtil.stripSignatureToFQN(String
- .valueOf(declarationSignature));
- String name = String.valueOf(fProposal.getName());
- String[] parameters = Signature.getParameterTypes(String
- .valueOf(fProposal.getSignature()));
- //search all the possible types until a match is found
- IType[] types = fJavaProject.findTypes(typeName);
- if(types != null && types.length >0) {
- for(int i = 0; i < types.length && func != null; ++i) {
- IType type = types[i];
- if (type != null) {
- boolean isConstructor = fProposal.isConstructor();
- try {
- func = findMethod(name, parameters, isConstructor, type);
- } catch(JavaScriptModelException e) {
- //ignore, could not find method
- }
- }
- }
- } else {
- ITypeRoot typeRoot=fJavaProject.findTypeRoot(typeName);
- if(typeRoot != null) {
- func = typeRoot.getFunction(name, parameters);
- }
- }
- }
- return func;
- }
-
- /* adapted from JavaModelUtil */
-
- /**
- * Finds a method in a type. This searches for a method with the same name
- * and signature. Parameter types are only compared by the simple name, no
- * resolving for the fully qualified type name is done. Constructors are
- * only compared by parameters, not the name.
- *
- * @param name The name of the method to find
- * @param paramTypes The type signatures of the parameters e.g.
- * <code>{"QString;","I"}</code>
- * @param isConstructor If the method is a constructor
- * @return The first found method or <code>null</code>, if nothing found
- */
- private IFunction findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaScriptModelException {
- Map typeVariables= computeTypeVariables(type);
- return findMethod(name, paramTypes, isConstructor, type.getFunctions(), typeVariables);
- }
-
- /**
- * The type and method signatures received in
- * <code>CompletionProposals</code> of type <code>FUNCTION_REF</code>
- * contain concrete type bounds. When comparing parameters of the signature
- * with an <code>IFunction</code>, we have to make sure that we match the
- * case where the formal method declaration uses a type variable which in
- * the signature is already substituted with a concrete type (bound).
- * <p>
- * This method creates a map from type variable names to type signatures
- * based on the position they appear in the type declaration. The type
- * signatures are filtered through
- * {@link SignatureUtil#getLowerBound(char[])}.
- * </p>
- *
- * @param type the type to get the variables from
- * @return a map from type variables to concrete type signatures
- * @throws JavaScriptModelException if accessing the java model fails
- */
- private Map computeTypeVariables(IType type) throws JavaScriptModelException {
- Map map= new HashMap();
- char[] declarationSignature= fProposal.getDeclarationSignature();
- if (declarationSignature == null) // array methods don't contain a declaration signature
- return map;
-
- return map;
- }
-
- /**
- * Finds a method by name. This searches for a method with a name and
- * signature. Parameter types are only compared by the simple name, no
- * resolving for the fully qualified type name is done. Constructors are
- * only compared by parameters, not the name.
- *
- * @param name The name of the method to find
- * @param paramTypes The type signatures of the parameters e.g.
- * <code>{"QString;","I"}</code>
- * @param isConstructor If the method is a constructor
- * @param methods The methods to search in
- * @param typeVariables a map from type variables to concretely used types
- * @return The found method or <code>null</code>, if nothing found
- */
- private IFunction findMethod(String name, String[] paramTypes, boolean isConstructor, IFunction[] methods, Map typeVariables) throws JavaScriptModelException {
- for (int i= methods.length - 1; i >= 0; i--) {
- if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i], typeVariables)) {
- return methods[i];
- }
- }
- return fFallbackMatch;
- }
-
- /**
- * Tests if a method equals to the given signature. Parameter types are only
- * compared by the simple name, no resolving for the fully qualified type
- * name is done. Constructors are only compared by parameters, not the name.
- *
- * @param name Name of the method
- * @param paramTypes The type signatures of the parameters e.g.
- * <code>{"QString;","I"}</code>
- * @param isConstructor Specifies if the method is a constructor
- * @param method the method to be compared with this info's method
- * @param typeVariables a map from type variables to types
- * @return Returns <code>true</code> if the method has the given name and
- * parameter types and constructor state.
- */
- private boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IFunction method, Map typeVariables) throws JavaScriptModelException {
- if (isConstructor || name.equals(method.getElementName())) {
- if (isConstructor == method.isConstructor()) {
- String[] otherParams= method.getParameterTypes(); // types may be type variables
- if (paramTypes.length == otherParams.length) {
- fFallbackMatch= method;
- String signature= method.getSignature();
- String[] otherParamsFromSignature= Signature.getParameterTypes(signature); // types are resolved / upper-bounded
- // no need to check method type variables since these are
- // not yet bound when proposing a method
- for (int i= 0; i < paramTypes.length; i++) {
- String ourParamName= computeSimpleTypeName(paramTypes[i], typeVariables);
- String otherParamName1= computeSimpleTypeName(otherParams[i], typeVariables);
- String otherParamName2= computeSimpleTypeName(otherParamsFromSignature[i], typeVariables);
-
- if (!ourParamName.equals(otherParamName1) && !ourParamName.equals(otherParamName2)) {
- return false;
- }
- }
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the simple erased name for a given type signature, possibly replacing type variables.
- *
- * @param signature the type signature
- * @param typeVariables the Map&lt;SimpleName, VariableName>
- * @return the simple erased name for signature
- */
- private String computeSimpleTypeName(String signature, Map typeVariables) {
- // method equality uses erased types
- String erasure=signature;
- erasure= erasure.replaceAll("/", "."); //$NON-NLS-1$//$NON-NLS-2$
- String simpleName= Signature.getSimpleName(Signature.toString(erasure));
- char[] typeVar= (char[]) typeVariables.get(simpleName);
- if (typeVar != null)
- simpleName= String.valueOf(Signature.getSignatureSimpleName(typeVar));
- return simpleName;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/OverrideCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/OverrideCompletionProposal.java
deleted file mode 100644
index e75d71c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/OverrideCompletionProposal.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ChildListPropertyDescriptor;
-import org.eclipse.wst.jsdt.core.dom.ClassInstanceCreation;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ITrackedNodePosition;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.wst.jsdt.core.formatter.IndentManipulation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-
-public class OverrideCompletionProposal extends JavaTypeCompletionProposal implements ICompletionProposalExtension4 {
-
- private IJavaScriptProject fJavaProject;
- private String fMethodName;
- private String[] fParamTypes;
-
- public OverrideCompletionProposal(IJavaScriptProject jproject, IJavaScriptUnit cu, String methodName, String[] paramTypes, int start, int length, String displayName, String completionProposal) {
- super(completionProposal, cu, start, length, null, displayName, 0);
- Assert.isNotNull(jproject);
- Assert.isNotNull(methodName);
- Assert.isNotNull(paramTypes);
- Assert.isNotNull(cu);
-
- fParamTypes= paramTypes;
- fMethodName= methodName;
-
- fJavaProject= jproject;
-
- StringBuffer buffer= new StringBuffer();
- buffer.append(completionProposal);
- buffer.append(" {};"); //$NON-NLS-1$
-
- setReplacementString(buffer.toString());
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getPrefixCompletionText(org.eclipse.jface.text.IDocument,int)
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- return fMethodName;
- }
-
- /*
- * @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
- */
- protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite importRewrite) throws CoreException, BadLocationException {
- final IDocument buffer= new Document(document.get());
- int index= offset - 1;
- while (index >= 0 && Character.isJavaIdentifierPart(buffer.getChar(index)))
- index--;
- final int length= offset - index - 1;
- buffer.replace(index + 1, length, " "); //$NON-NLS-1$
- final ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setStatementsRecovery(true);
- parser.setSource(buffer.get().toCharArray());
- parser.setUnitName(fCompilationUnit.getResource().getFullPath().toString());
- parser.setProject(fCompilationUnit.getJavaScriptProject());
- final JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(new NullProgressMonitor());
- ITypeBinding binding= null;
- ChildListPropertyDescriptor descriptor= null;
- ASTNode node= NodeFinder.perform(unit, index + 1, 0);
- if (node instanceof AnonymousClassDeclaration) {
- switch (node.getParent().getNodeType()) {
- case ASTNode.CLASS_INSTANCE_CREATION:
- binding= ((ClassInstanceCreation) node.getParent()).resolveTypeBinding();
- break;
- }
- descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
- } else if (node instanceof AbstractTypeDeclaration) {
- final AbstractTypeDeclaration declaration= ((AbstractTypeDeclaration) node);
- descriptor= declaration.getBodyDeclarationsProperty();
- binding= declaration.resolveBinding();
- }
- if (binding != null) {
- ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
- IFunctionBinding[] bindings= StubUtility2.getOverridableMethods(rewrite.getAST(), binding, true);
- if (bindings != null && bindings.length > 0) {
- List candidates= new ArrayList(bindings.length);
- IFunctionBinding method= null;
- for (index= 0; index < bindings.length; index++) {
- if (bindings[index].getName().equals(fMethodName) && bindings[index].getParameterTypes().length == fParamTypes.length)
- candidates.add(bindings[index]);
- }
- if (candidates.size() > 1) {
- method= Bindings.findMethodInHierarchy(binding, fMethodName, fParamTypes);
- if (method == null) {
- ITypeBinding objectType= rewrite.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- method= Bindings.findMethodInType(objectType, fMethodName, fParamTypes);
- }
- } else if (candidates.size() == 1)
- method= (IFunctionBinding) candidates.get(0);
- if (method != null) {
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
- ListRewrite rewriter= rewrite.getListRewrite(node, descriptor);
- String key= method.getKey();
- FunctionDeclaration stub= null;
- for (index= 0; index < bindings.length; index++) {
- if (key.equals(bindings[index].getKey())) {
- stub= StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, bindings[index], binding.getName(), false, settings);
- if (stub != null)
- rewriter.insertFirst(stub, null);
- break;
- }
- }
- if (stub != null) {
- IDocument contents= new Document(fCompilationUnit.getBuffer().getContents());
- IRegion region= contents.getLineInformationOfOffset(getReplacementOffset());
- ITrackedNodePosition position= rewrite.track(stub);
- String indent= IndentManipulation.extractIndentString(contents.get(region.getOffset(), region.getLength()), settings.tabWidth, settings.indentWidth);
- try {
- rewrite.rewriteAST(contents, fJavaProject.getOptions(true)).apply(contents, TextEdit.UPDATE_REGIONS);
- } catch (MalformedTreeException exception) {
- JavaScriptPlugin.log(exception);
- } catch (BadLocationException exception) {
- JavaScriptPlugin.log(exception);
- }
- setReplacementString(IndentManipulation.changeIndent(Strings.trimIndentation(contents.get(position.getStartPosition(), position.getLength()), settings.tabWidth, settings.indentWidth, false), 0, settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(contents)));
- }
- }
- }
- }
- return true;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
- */
- public boolean isAutoInsertable() {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuesser.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuesser.java
deleted file mode 100644
index f551ada3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuesser.java
+++ /dev/null
@@ -1,654 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.PositionBasedCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.util.StringMatcher;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-/**
- * This class triggers a code-completion that will track all local ane member variables for later
- * use as a parameter guessing proposal.
- *
- * @author Andrew McCullough
- */
-public class ParameterGuesser {
-
- final class Variable {
-
- /**
- * Variable type. Used to choose the best guess based on scope (Local beats instance beats inherited)
- */
- public static final int LOCAL= 0;
- public static final int FIELD= 1;
- public static final int METHOD= 1;
- public static final int INHERITED_FIELD= 3;
- public static final int INHERITED_METHOD= 3;
-
- public final String typePackage;
- public final String typeName;
- public final String name;
- public final int variableType;
- public final int positionScore;
- public boolean alreadyMatched;
- public char[] triggerChars;
- public ImageDescriptor descriptor;
- public boolean isAutoboxingMatch;
- private String fFQN;
- private boolean fFQNResolved= false;
- private IType fType;
- private boolean fTypeResolved= false;
-
- /**
- * Creates a variable.
- */
- public Variable(String typePackage, String typeName, String name, int variableType, int positionScore, char[] triggers, ImageDescriptor descriptor) {
- if (typePackage == null)
- typePackage= ""; //$NON-NLS-1$
- if (typeName == null)
- typeName= ""; //$NON-NLS-1$
- this.typePackage= typePackage;
- this.typeName= typeName;
- this.name= name;
- this.variableType= variableType;
- this.positionScore= positionScore;
- triggerChars= triggers;
- this.descriptor= descriptor;
- }
-
- /*
- * @see Object#toString()
- */
- public String toString() {
-
- StringBuffer buffer= new StringBuffer();
-
- if (typePackage.length() != 0) {
- buffer.append(typePackage);
- buffer.append('.');
- }
-
- buffer.append(typeName);
- buffer.append(' ');
- buffer.append(name);
- buffer.append(" ("); //$NON-NLS-1$
- buffer.append(variableType);
- buffer.append(')');
-
- return buffer.toString();
- }
-
- String getFQN() {
- if (!fFQNResolved) {
- fFQNResolved= true;
- fFQN= computeFQN(typePackage, typeName);
- }
- return fFQN;
- }
-
- private String computeFQN(String pkg, String type) {
- if (pkg.length() != 0) {
- return pkg + '.' + type;
- }
- return type;
- }
-
-
- IType getType(IJavaScriptProject project) throws JavaScriptModelException {
- if (!fTypeResolved) {
- fTypeResolved= true;
- if (typePackage.length() > 0)
- fType= project.findType(getFQN());
- }
- return fType;
- }
-
- boolean isPrimitive() {
- return ParameterGuesser.PRIMITIVE_ASSIGNMENTS.containsKey(getFQN());
- }
-
- boolean isArrayType() {
- // check for an exact match (fast)
- return getFQN().endsWith("[]"); //$NON-NLS-1$
- }
-
- boolean isHierarchyAssignable(Variable rhs) throws JavaScriptModelException {
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- IType paramType= getType(project);
- IType varType= rhs.getType(project);
- if (varType == null || paramType == null)
- return false;
-
- ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(varType);
- return hierarchy.contains(paramType);
- }
-
- boolean isAutoBoxingAssignable(Variable rhs) {
- // auto-unbox variable to match primitive parameter
- if (isPrimitive()) {
- String unboxedVariable= ParameterGuesser.getAutoUnboxedType(rhs.getFQN());
- return ParameterGuesser.isPrimitiveAssignable(typeName, unboxedVariable);
- }
-
- // variable is primitive, auto-box to match parameter type
- if (rhs.isPrimitive()) {
- String unboxedType= ParameterGuesser.getAutoUnboxedType(getFQN());
- return ParameterGuesser.isPrimitiveAssignable(unboxedType, rhs.typeName);
- }
-
- return false;
- }
-
- /**
- * Return true if <code>rhs</code> is assignable to the receiver
- */
- boolean isAssignable(Variable rhs) throws JavaScriptModelException {
-
- // if there is no package specified, do the check on type name only. This will work for primitives
- // and for local variables that cannot be resolved.
- if (typePackage.length() == 0 || rhs.typePackage.length() == 0) {
-
- if (rhs.typeName.equals(typeName))
- return true;
-
- if (ParameterGuesser.isPrimitiveAssignable(typeName, rhs.typeName))
- return true;
-
- if (fAllowAutoBoxing && isAutoBoxingAssignable(rhs)) {
- rhs.isAutoboxingMatch= true;
- return true;
- }
-
- return false;
- }
-
- // if we get to here, we're doing a "fully qualified match" -- meaning including packages, no primitives
- // and no unresolved variables.
-
- // if there is an exact textual match, there is no need to search type hierarchy.. this is
- // a quick way to pick up an exact match.
- if (rhs.getFQN().equals(getFQN()))
- return true;
-
- // otherwise, we get a match/no match by searching the type hierarchy
- return isHierarchyAssignable(rhs);
- }
- }
-
- private static final char[] NO_TRIGGERS= new char[0];
- private static final char[] VOID= "void".toCharArray(); //$NON-NLS-1$
- private static final char[] HASHCODE= "hashCode()".toCharArray(); //$NON-NLS-1$
- private static final char[] TOSTRING= "toString()".toCharArray(); //$NON-NLS-1$
- private static final char[] CLONE= "clone()".toCharArray(); //$NON-NLS-1$
-
- private final class VariableCollector extends CompletionRequestor {
-
- /** The enclosing type name */
- private String fEnclosingTypeName;
- /** The local and member variables */
- private List fVars;
-
-
- VariableCollector() {
- setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- setIgnored(CompletionProposal.FIELD_REF, false);
- setIgnored(CompletionProposal.KEYWORD, true);
- setIgnored(CompletionProposal.LABEL_REF, true);
- setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- setIgnored(CompletionProposal.METHOD_REF, false);
- setIgnored(CompletionProposal.PACKAGE_REF, true);
- setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- setIgnored(CompletionProposal.TYPE_REF, true);
- setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, false);
- }
-
- public List collect(int codeAssistOffset, IJavaScriptUnit compilationUnit) throws JavaScriptModelException {
- Assert.isTrue(codeAssistOffset >= 0);
- Assert.isNotNull(compilationUnit);
-
- fVars= new ArrayList();
-
- String source= compilationUnit.getSource();
- if (source == null)
- return fVars;
-
- fEnclosingTypeName= getEnclosingTypeName(codeAssistOffset, compilationUnit);
-
- // find some whitespace to start our variable-finding code complete from.
- // this allows the VariableTracker to find all available variables (no prefix to match for the code completion)
- int completionOffset= getCompletionOffset(source, codeAssistOffset);
-
- compilationUnit.codeComplete(completionOffset, this);
-
- // add this, true, false
- int dotPos= fEnclosingTypeName.lastIndexOf('.');
- String thisType;
- String thisPkg;
- if (dotPos != -1) {
- thisType= fEnclosingTypeName.substring(dotPos + 1);
- thisPkg= fEnclosingTypeName.substring(0, dotPos);
- } else {
- thisPkg= new String();
- thisType= fEnclosingTypeName;
- }
- addVariable(Variable.FIELD, thisPkg.toCharArray(), thisType.toCharArray(), "this".toCharArray(), new char[] {'.'}, getFieldDescriptor(Flags.AccPublic)); //$NON-NLS-1$
- addVariable(Variable.FIELD, NO_TRIGGERS, "boolean".toCharArray(), "true".toCharArray(), NO_TRIGGERS, null); //$NON-NLS-1$//$NON-NLS-2$
- addVariable(Variable.FIELD, NO_TRIGGERS, "boolean".toCharArray(), "false".toCharArray(), NO_TRIGGERS, null); //$NON-NLS-1$//$NON-NLS-2$
-
- return fVars;
- }
-
- private String getEnclosingTypeName(int codeAssistOffset, IJavaScriptUnit compilationUnit) throws JavaScriptModelException {
-
- IJavaScriptElement element= compilationUnit.getElementAt(codeAssistOffset);
- if (element == null)
- return null;
-
- element= element.getAncestor(IJavaScriptElement.TYPE);
- if (element == null)
- return null;
-
- return element.getElementName();
- }
-
- /**
- * Determine if the declaring type matches the type of the code completion invocation
- */
- private final boolean isInherited(String declaringTypeName) {
- return !declaringTypeName.equals(fEnclosingTypeName);
- }
-
- private void addVariable(int varType, char[] typePackageName, char[] typeName, char[] name, char[] triggers, ImageDescriptor descriptor) {
- fVars.add(new Variable(new String(typePackageName), new String(typeName), new String(name), varType, fVars.size(), triggers, descriptor));
- }
-
- private void acceptField(char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, int modifiers) {
- if (!isInherited(new String(declaringTypeName)))
- addVariable(Variable.FIELD, typePackageName, typeName, name, NO_TRIGGERS, getFieldDescriptor(modifiers));
- else
- addVariable(Variable.INHERITED_FIELD, typePackageName, typeName, name, NO_TRIGGERS, getFieldDescriptor(modifiers));
- }
-
- private void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers) {
- addVariable(Variable.LOCAL, typePackageName, typeName, name, NO_TRIGGERS, decorate(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, modifiers, false));
- }
-
- private void acceptMethod(char[] declaringTypeName, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers) {
- if (!filter(returnTypeName, completionName))
- addVariable(isInherited(new String(declaringTypeName)) ? Variable.INHERITED_METHOD : Variable.METHOD, returnTypePackageName, returnTypeName, completionName, NO_TRIGGERS, getMemberDescriptor(modifiers));
- }
-
- private boolean filter(char[] returnTypeName, char[] completionName) {
- return Arrays.equals(VOID, returnTypeName) || Arrays.equals(HASHCODE, completionName) || Arrays.equals(TOSTRING, completionName) || Arrays.equals(CLONE, completionName);
- }
-
- protected ImageDescriptor getMemberDescriptor(int modifiers) {
- ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, modifiers);
- return decorate(desc, modifiers, false);
- }
-
- protected ImageDescriptor getFieldDescriptor(int modifiers) {
- ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, modifiers);
- return decorate(desc, modifiers, true);
- }
-
- private ImageDescriptor decorate(ImageDescriptor descriptor, int modifiers, boolean isField) {
- int flags= 0;
-
- if (Flags.isDeprecated(modifiers))
- flags |= JavaScriptElementImageDescriptor.DEPRECATED;
-
- if (Flags.isStatic(modifiers))
- flags |= JavaScriptElementImageDescriptor.STATIC;
-
- if (Flags.isAbstract(modifiers))
- flags |= JavaScriptElementImageDescriptor.ABSTRACT;
-
- return new JavaScriptElementImageDescriptor(descriptor, flags, JavaElementImageProvider.SMALL_SIZE);
-
- }
-
- /*
- * @see org.eclipse.wst.jsdt.core.CompletionRequestor#accept(org.eclipse.wst.jsdt.core.CompletionProposal)
- */
- public void accept(CompletionProposal proposal) {
- if (isIgnored(proposal.getKind()))
- return;
-
- switch (proposal.getKind()) {
- case CompletionProposal.FIELD_REF:
- acceptField(
- Signature.getSignatureSimpleName(proposal.getDeclarationSignature()),
- proposal.getName(),
- Signature.getSignatureQualifier(proposal.getSignature()),
- Signature.getSignatureSimpleName(proposal.getSignature()),
- proposal.getFlags());
- return;
- case CompletionProposal.LOCAL_VARIABLE_REF:
- acceptLocalVariable(
- proposal.getCompletion(),
- Signature.getSignatureQualifier(proposal.getSignature()),
- Signature.getSignatureSimpleName(proposal.getSignature()),
- proposal.getFlags());
- return;
- case CompletionProposal.METHOD_REF:
- if (Signature.getParameterCount(proposal.getSignature()) == 0)
- acceptMethod(
- Signature.getSignatureSimpleName(proposal.getDeclarationSignature()),
- Signature.getSignatureQualifier(Signature.getReturnType(proposal.getSignature())),
- Signature.getSignatureSimpleName(Signature.getReturnType(proposal.getSignature())),
- proposal.getCompletion(),
- proposal.getFlags());
-
- }
-
- }
- }
-
- private static final Map PRIMITIVE_ASSIGNMENTS;
- private static final Map AUTOUNBOX;
-
- static {
- HashMap primitiveAssignments= new HashMap();
- // put (LHS, RHS)
- primitiveAssignments.put("boolean", Collections.singleton("boolean")); //$NON-NLS-1$ //$NON-NLS-2$
- primitiveAssignments.put("byte", Collections.singleton("byte")); //$NON-NLS-1$ //$NON-NLS-2$
- primitiveAssignments.put("short", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"short", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- primitiveAssignments.put("char", Collections.singleton("char")); //$NON-NLS-1$ //$NON-NLS-2$
- primitiveAssignments.put("int", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"int", "short", "char", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- primitiveAssignments.put("long", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"long", "int", "short", "char", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- primitiveAssignments.put("float", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"float", "long", "int", "short", "char", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- primitiveAssignments.put("double", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"double", "float", "long", "int", "short", "char", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- primitiveAssignments.put("primitive number", Collections.unmodifiableSet(new HashSet(Arrays.asList(new String[] {"double", "float", "long", "int", "short", "byte"})))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- PRIMITIVE_ASSIGNMENTS= Collections.unmodifiableMap(primitiveAssignments);
-
- HashMap autounbox= new HashMap();
- autounbox.put("java.lang.Boolean", "boolean"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Byte", "byte"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Short", "short"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Character", "char"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Integer", "int"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Long", "long"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Float", "float"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Double", "double"); //$NON-NLS-1$ //$NON-NLS-2$
- autounbox.put("java.lang.Number", "primitive number"); // dummy for reverse assignment //$NON-NLS-1$ //$NON-NLS-2$
- AUTOUNBOX= Collections.unmodifiableMap(autounbox);
- }
-
- private static final boolean isPrimitiveAssignable(String lhs, String rhs) {
- Set targets= (Set) PRIMITIVE_ASSIGNMENTS.get(lhs);
- return targets != null && targets.contains(rhs);
- }
-
- private static final String getAutoUnboxedType(String type) {
- String primitive= (String) AUTOUNBOX.get(type);
- return primitive;
- }
-
- /** The compilation unit we are computing the completion for */
- private final IJavaScriptUnit fCompilationUnit;
- /** The code assist offset. */
- private final int fCodeAssistOffset;
- /** Local and member variables of the compilation unit */
- private List fVariables;
- private ImageDescriptorRegistry fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
- private boolean fAllowAutoBoxing;
-
- /**
- * Creates a parameter guesser for compilation unit and offset.
- *
- * @param codeAssistOffset the offset at which to perform code assist
- * @param compilationUnit the compilation unit in which code assist is performed
- */
- public ParameterGuesser(int codeAssistOffset, IJavaScriptUnit compilationUnit) {
- Assert.isTrue(codeAssistOffset >= 0);
- Assert.isNotNull(compilationUnit);
-
- fCodeAssistOffset= codeAssistOffset;
- fCompilationUnit= compilationUnit;
-
-
- IJavaScriptProject project= fCompilationUnit.getJavaScriptProject();
- String sourceVersion= project == null
- ? JavaScriptCore.getOption(JavaScriptCore.COMPILER_SOURCE)
- : project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
-
- fAllowAutoBoxing= JavaScriptCore.VERSION_1_5.compareTo(sourceVersion) <= 0;
- }
-
- /**
- * Returns the offset at which code assist is performed.
- */
- public int getCodeAssistOffset() {
- return fCodeAssistOffset;
- }
-
- /**
- * Returns the compilation unit in which code assist is performed.
- */
- public IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * Returns the matches for the type and name argument, ordered by match quality.
- *
- * @param paramPackage - the package of the parameter we are trying to match
- * @param paramType - the qualified name of the parameter we are trying to match
- * @param paramName - the name of the parameter (used to find similarly named matches)
- * @param pos
- * @param document
- * @return returns the name of the best match, or <code>null</code> if no match found
- * @throws JavaScriptModelException
- */
- public ICompletionProposal[] parameterProposals(String paramPackage, String paramType, String paramName, Position pos, IDocument document) throws JavaScriptModelException {
-
- if (fVariables == null) {
- VariableCollector variableCollector= new VariableCollector();
- fVariables= variableCollector.collect(fCodeAssistOffset, fCompilationUnit);
- }
-
- Variable parameter= new Variable(paramPackage, paramType, paramName, Variable.LOCAL, 0, null, null);
-
- List typeMatches= findProposalsMatchingType(fVariables, parameter);
- orderMatches(typeMatches, paramName);
-
- ICompletionProposal[] ret= new ICompletionProposal[typeMatches.size()];
- int i= 0; int replacementLength= 0;
- for (Iterator it= typeMatches.iterator(); it.hasNext();) {
- Variable v= (Variable)it.next();
- if (i == 0) {
- v.alreadyMatched= true;
- replacementLength= v.name.length();
- }
-
- final char[] triggers= new char[v.triggerChars.length + 1];
- System.arraycopy(v.triggerChars, 0, triggers, 0, v.triggerChars.length);
- String displayString= v.isAutoboxingMatch ? v.name : v.name;
- triggers[triggers.length - 1]= ';';
- ICompletionProposal proposal= new PositionBasedCompletionProposal(v.name, pos, replacementLength, getImage(v.descriptor), displayString, null, null) {
- public char[] getTriggerCharacters() {
- return triggers;
- }
- };
- ret[i++]= proposal;
- }
-
- return ret;
- }
-
- private static class MatchComparator implements Comparator {
-
- private String fParamName;
-
- MatchComparator(String paramName) {
- fParamName= paramName;
- }
- public int compare(Object o1, Object o2) {
- Variable one= (Variable)o1;
- Variable two= (Variable)o2;
-
- return score(two) - score(one);
- }
-
- /**
- * The four order criteria as described below - put already used into bit 10, all others into
- * bits 0-9, 11-20, 21-30; 31 is sign - always 0
- * @param v
- * @return the score for <code>v</code>
- */
- private int score(Variable v) {
- int variableScore= 100 - v.variableType; // since these are increasing with distance
- int subStringScore= getLongestCommonSubstring(v.name, fParamName).length();
- // substring scores under 60% are not considered
- // this prevents marginal matches like a - ba and false - isBool that will
- // destroy the sort order
- int shorter= Math.min(v.name.length(), fParamName.length());
- if (subStringScore < 0.6 * shorter)
- subStringScore= 0;
-
- int positionScore= v.positionScore; // since ???
- int matchedScore= v.alreadyMatched ? 0 : 1;
- int autoboxingScore= v.isAutoboxingMatch ? 0 : 1;
-
- int score= autoboxingScore << 30 | variableScore << 21 | subStringScore << 11 | matchedScore << 10 | positionScore;
- return score;
- }
-
- }
-
- /**
- * Determine the best match of all possible type matches. The input into this method is all
- * possible completions that match the type of the argument. The purpose of this method is to
- * choose among them based on the following simple rules:
- *
- * 1) Local Variables > Instance/Class Variables > Inherited Instance/Class Variables
- *
- * 2) A longer case insensitive substring match will prevail
- *
- * 3) Variables that have not been used already during this completion will prevail over
- * those that have already been used (this avoids the same String/int/char from being passed
- * in for multiple arguments)
- *
- * 4) A better source position score will prevail (the declaration point of the variable, or
- * "how close to the point of completion?"
- */
- private static void orderMatches(List typeMatches, String paramName) {
- if (typeMatches != null) Collections.sort(typeMatches, new MatchComparator(paramName));
- }
-
- /**
- * Finds a local or member variable that matched the type of the parameter
- */
- private List findProposalsMatchingType(List proposals, Variable parameter) throws JavaScriptModelException {
-
- if (parameter.getFQN().length() == 0)
- return null;
-
- // traverse the lists in reverse order, since it is empirically true that the code
- // completion engine returns variables in the order they are found -- and we want to find
- // matches closest to the code completion point.. No idea if this behavior is guaranteed.
-
- List matches= new ArrayList();
-
- for (ListIterator iterator= proposals.listIterator(proposals.size()); iterator.hasPrevious(); ) {
- Variable variable= (Variable) iterator.previous();
- variable.isAutoboxingMatch= false;
- if (parameter.isAssignable(variable))
- matches.add(variable);
- }
-
- return matches;
- }
-
- /**
- * Returns the longest common substring of two strings.
- */
- private static String getLongestCommonSubstring(String first, String second) {
-
- String shorter= (first.length() <= second.length()) ? first : second;
- String longer= shorter == first ? second : first;
-
- int minLength= shorter.length();
-
- StringBuffer pattern= new StringBuffer(shorter.length() + 2);
- String longestCommonSubstring= ""; //$NON-NLS-1$
-
- for (int i= 0; i < minLength; i++) {
- for (int j= i + 1; j <= minLength; j++) {
- if (j - i < longestCommonSubstring.length())
- continue;
-
- String substring= shorter.substring(i, j);
- pattern.setLength(0);
- pattern.append('*');
- pattern.append(substring);
- pattern.append('*');
-
- StringMatcher matcher= new StringMatcher(pattern.toString(), true, false);
- if (matcher.match(longer))
- longestCommonSubstring= substring;
- }
- }
-
- return longestCommonSubstring;
- }
-
- private Image getImage(ImageDescriptor descriptor) {
- return (descriptor == null) ? null : fRegistry.get(descriptor);
- }
-
- private static int getCompletionOffset(String source, int start) {
- int index= start;
- char c;
- while (index > 0 && (c= source.charAt(index - 1)) != '{' && c != ';')
- index--;
- return Math.min(index + 1, source.length());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuessingProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuessingProposal.java
deleted file mode 100644
index f61ad6af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ParameterGuessingProposal.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Andrew McCullough - initial API and implementation
- * IBM Corporation - general improvement and bug fixes, partial reimplementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.InclusivePositionUpdater;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.ProposalPosition;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * This is a {@link org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal} which includes templates
- * that represent the best guess completion for each parameter of a method.
- */
-public final class ParameterGuessingProposal extends JavaMethodCompletionProposal {
-
- /** Tells whether this class is in debug mode. */
- private static final boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ResultCollector")); //$NON-NLS-1$//$NON-NLS-2$
-
- private ICompletionProposal[][] fChoices; // initialized by guessParameters()
- private Position[] fPositions; // initialized by guessParameters()
-
- private IRegion fSelectedRegion; // initialized by apply()
- private IPositionUpdater fUpdater;
-
- public ParameterGuessingProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- }
-
- /*
- * @see ICompletionProposalExtension#apply(IDocument, char)
- */
- public void apply(IDocument document, char trigger, int offset) {
- try {
- super.apply(document, trigger, offset);
-
- int baseOffset= getReplacementOffset();
- String replacement= getReplacementString();
-
- if (fPositions != null && getTextViewer() != null) {
-
- LinkedModeModel model= new LinkedModeModel();
-
- for (int i= 0; i < fPositions.length; i++) {
- LinkedPositionGroup group= new LinkedPositionGroup();
- int positionOffset= fPositions[i].getOffset();
- int positionLength= fPositions[i].getLength();
-
- if (fChoices[i].length < 2) {
- group.addPosition(new LinkedPosition(document, positionOffset, positionLength, LinkedPositionGroup.NO_STOP));
- } else {
- ensurePositionCategoryInstalled(document, model);
- document.addPosition(getCategory(), fPositions[i]);
- group.addPosition(new ProposalPosition(document, positionOffset, positionLength, LinkedPositionGroup.NO_STOP, fChoices[i]));
- }
- model.addGroup(group);
- }
-
- model.forceInstall();
- JavaEditor editor= getJavaEditor();
- if (editor != null) {
- model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
- }
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer());
- ui.setExitPosition(getTextViewer(), baseOffset + replacement.length(), 0, Integer.MAX_VALUE);
- ui.setExitPolicy(new ExitPolicy(')', document));
- ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT);
- ui.setDoContextInfo(true);
- ui.enter();
- fSelectedRegion= ui.getSelectedRegion();
-
- } else {
- fSelectedRegion= new Region(baseOffset + replacement.length(), 0);
- }
-
- } catch (BadLocationException e) {
- ensurePositionCategoryRemoved(document);
- JavaScriptPlugin.log(e);
- openErrorDialog(e);
- } catch (BadPositionCategoryException e) {
- ensurePositionCategoryRemoved(document);
- JavaScriptPlugin.log(e);
- openErrorDialog(e);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaMethodCompletionProposal#needsLinkedMode()
- */
- protected boolean needsLinkedMode() {
- return false; // we handle it ourselves
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaMethodCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
-
- if (!hasParameters() || !hasArgumentList())
- return super.computeReplacementString();
-
- long millis= DEBUG ? System.currentTimeMillis() : 0;
- String replacement;
- try {
- replacement= computeGuessingCompletion();
- } catch (JavaScriptModelException x) {
- fPositions= null;
- fChoices= null;
- JavaScriptPlugin.log(x);
- openErrorDialog(x);
- return super.computeReplacementString();
- }
- if (DEBUG) System.err.println("Parameter Guessing: " + (System.currentTimeMillis() - millis)); //$NON-NLS-1$
-
- return replacement;
- }
-
- /**
- * Creates the completion string. Offsets and Lengths are set to the offsets and lengths
- * of the parameters.
- */
- private String computeGuessingCompletion() throws JavaScriptModelException {
-
- StringBuffer buffer= new StringBuffer(String.valueOf(fProposal.getName()));
-
- FormatterPrefs prefs= getFormatterPrefs();
- if (prefs.beforeOpeningParen)
- buffer.append(SPACE);
- buffer.append(LPAREN);
-
- setCursorPosition(buffer.length());
-
- if (prefs.afterOpeningParen)
- buffer.append(SPACE);
-
- fChoices= guessParameters();
- int count= fChoices.length;
- int replacementOffset= getReplacementOffset();
-
- for (int i= 0; i < count; i++) {
- if (i != 0) {
- if (prefs.beforeComma)
- buffer.append(SPACE);
- buffer.append(COMMA);
- if (prefs.afterComma)
- buffer.append(SPACE);
- }
-
- ICompletionProposal proposal= fChoices[i][0];
- String argument= proposal.getDisplayString();
- Position position= fPositions[i];
- position.setOffset(replacementOffset + buffer.length());
- position.setLength(argument.length());
- if (proposal instanceof JavaCompletionProposal) // handle the "unknown" case where we only insert a proposal.
- ((JavaCompletionProposal) proposal).setReplacementOffset(replacementOffset + buffer.length());
- buffer.append(argument);
- }
-
- if (prefs.beforeClosingParen)
- buffer.append(SPACE);
-
- buffer.append(RPAREN);
-
- return buffer.toString();
- }
-
- /**
- * Returns the currently active java editor, or <code>null</code> if it
- * cannot be determined.
- *
- * @return the currently active java editor, or <code>null</code>
- */
- private JavaEditor getJavaEditor() {
- IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor();
- if (part instanceof JavaEditor)
- return (JavaEditor) part;
- else
- return null;
- }
-
- private ICompletionProposal[][] guessParameters() throws JavaScriptModelException {
- // find matches in reverse order. Do this because people tend to declare the variable meant for the last
- // parameter last. That is, local variables for the last parameter in the method completion are more
- // likely to be closer to the point of code completion. As an example consider a "delegation" completion:
- //
- // public void myMethod(int param1, int param2, int param3) {
- // someOtherObject.yourMethod(param1, param2, param3);
- // }
- //
- // The other consideration is giving preference to variables that have not previously been used in this
- // code completion (which avoids "someOtherObject.yourMethod(param1, param1, param1)";
-
- char[][] parameterNames= fProposal.findParameterNames(null);
- int count= parameterNames.length;
- fPositions= new Position[count];
- fChoices= new ICompletionProposal[count][];
-
- IDocument document= fInvocationContext.getDocument();
- IJavaScriptUnit cu= fInvocationContext.getCompilationUnit();
- JavaModelUtil.reconcile(cu);
- String[][] parameterTypes= getParameterSignatures();
- ParameterGuesser guesser= new ParameterGuesser(fProposal.getCompletionLocation() + 1, cu);
-
- for (int i= count - 1; i >= 0; i--) {
- String paramName= new String(parameterNames[i]);
- Position position= new Position(0,0);
-
- ICompletionProposal[] argumentProposals= guesser.parameterProposals(parameterTypes[i][0], parameterTypes[i][1], paramName, position, document);
- if (argumentProposals.length == 0)
- argumentProposals= new ICompletionProposal[] {new JavaCompletionProposal(paramName, 0, paramName.length(), null, paramName, 0)};
-
- fPositions[i]= position;
- fChoices[i]= argumentProposals;
- }
-
- return fChoices;
- }
-
- private String[][] getParameterSignatures() {
- char[] signature= fProposal.getSignature();
- char[][] types= Signature.getParameterTypes(signature);
- String[][] ret= new String[types.length][2];
-
- for (int i= 0; i < types.length; i++) {
- char[] type= types[i];
- ret[i][0]= String.valueOf(Signature.getSignatureQualifier(type));
- ret[i][1]= String.valueOf(Signature.getSignatureSimpleName(type));
- }
- return ret;
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- if (fSelectedRegion == null)
- return new Point(getReplacementOffset(), 0);
-
- return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
- }
-
- private void openErrorDialog(Exception e) {
- Shell shell= getTextViewer().getTextWidget().getShell();
- MessageDialog.openError(shell, JavaTextMessages.ParameterGuessingProposal_error_msg, e.getMessage());
- }
-
- private void ensurePositionCategoryInstalled(final IDocument document, LinkedModeModel model) {
- if (!document.containsPositionCategory(getCategory())) {
- document.addPositionCategory(getCategory());
- fUpdater= new InclusivePositionUpdater(getCategory());
- document.addPositionUpdater(fUpdater);
-
- model.addLinkingListener(new ILinkedModeListener() {
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void left(LinkedModeModel environment, int flags) {
- ensurePositionCategoryRemoved(document);
- }
-
- public void suspend(LinkedModeModel environment) {}
- public void resume(LinkedModeModel environment, int flags) {}
- });
- }
- }
-
- private void ensurePositionCategoryRemoved(IDocument document) {
- if (document.containsPositionCategory(getCategory())) {
- try {
- document.removePositionCategory(getCategory());
- } catch (BadPositionCategoryException e) {
- // ignore
- }
- document.removePositionUpdater(fUpdater);
- }
- }
-
- private String getCategory() {
- return "ParameterGuessingProposal_" + toString(); //$NON-NLS-1$
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalContextInformation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalContextInformation.java
deleted file mode 100644
index ef750200..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalContextInformation.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationExtension;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalLabelProvider;
-
-
-/**
- * Implementation of the <code>IContextInformation</code> interface.
- */
-public final class ProposalContextInformation implements IContextInformation, IContextInformationExtension {
-
- private final String fContextDisplayString;
- private final String fInformationDisplayString;
- private final Image fImage;
- private int fPosition;
-
- /**
- * Creates a new context information.
- */
- public ProposalContextInformation(CompletionProposal proposal) {
- // don't cache the core proposal because the ContentAssistant might
- // hang on to the context info.
- CompletionProposalLabelProvider labelProvider= new CompletionProposalLabelProvider();
- fInformationDisplayString= labelProvider.createParameterList(proposal);
- ImageDescriptor descriptor= labelProvider.createImageDescriptor(proposal);
- if (descriptor != null)
- fImage= JavaScriptPlugin.getImageDescriptorRegistry().get(descriptor);
- else
- fImage= null;
- if (proposal.getCompletion().length == 0)
- fPosition= proposal.getCompletionLocation() + 1;
- else
- fPosition= -1;
- fContextDisplayString= labelProvider.createLabel(proposal);
- }
-
- /*
- * @see IContextInformation#equals
- */
- public boolean equals(Object object) {
- if (object instanceof IContextInformation) {
- IContextInformation contextInformation= (IContextInformation) object;
- boolean equals= getInformationDisplayString().equalsIgnoreCase(contextInformation.getInformationDisplayString());
- if (getContextDisplayString() != null)
- equals= equals && getContextDisplayString().equalsIgnoreCase(contextInformation.getContextDisplayString());
- return equals;
- }
- return false;
- }
-
- /*
- * @see IContextInformation#getInformationDisplayString()
- */
- public String getInformationDisplayString() {
- return fInformationDisplayString;
- }
-
- /*
- * @see IContextInformation#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see IContextInformation#getContextDisplayString()
- */
- public String getContextDisplayString() {
- return fContextDisplayString;
- }
-
- /*
- * @see IContextInformationExtension#getContextInformationPosition()
- */
- public int getContextInformationPosition() {
- return fPosition;
- }
-
- /**
- * Sets the context information position.
- *
- * @param position the new position, or -1 for unknown.
- *
- */
- public void setContextInformationPosition(int position) {
- fPosition= position;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java
deleted file mode 100644
index af5fb3f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader;
-import org.eclipse.wst.jsdt.ui.JSdocContentAccess;
-
-
-public class ProposalInfo {
-
- private boolean fJavadocResolved= false;
- private String fJavadoc= null;
-
- protected IJavaScriptElement fElement;
-
- public ProposalInfo(IMember member) {
- fElement= member;
- }
-
- protected ProposalInfo() {
- fElement= null;
- }
-
- public IJavaScriptElement getJavaElement() throws JavaScriptModelException {
- return fElement;
- }
-
- /**
- * Gets the text for this proposal info formatted as HTML, or
- * <code>null</code> if no text is available.
- *
- * @param monitor a progress monitor
- * @return the additional info text
- */
- public final String getInfo(IProgressMonitor monitor) {
- if (!fJavadocResolved) {
- fJavadocResolved= true;
- fJavadoc= computeInfo(monitor);
- }
- return fJavadoc;
- }
-
- /**
- * Gets the text for this proposal info formatted as HTML, or
- * <code>null</code> if no text is available.
- *
- * @param monitor a progress monitor
- * @return the additional info text
- */
- private String computeInfo(IProgressMonitor monitor) {
- try {
- final IJavaScriptElement javaElement= getJavaElement();
- if (javaElement instanceof IMember) {
- IMember member= (IMember) javaElement;
- return extractJavadoc(member, monitor);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- } catch (IOException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- /**
- * Extracts the javadoc for the given <code>IMember</code> and returns it
- * as HTML.
- *
- * @param member the member to get the documentation for
- * @param monitor a progress monitor
- * @return the javadoc for <code>member</code> or <code>null</code> if
- * it is not available
- * @throws JavaScriptModelException if accessing the javadoc fails
- * @throws IOException if reading the javadoc fails
- */
- private String extractJavadoc(IMember member, IProgressMonitor monitor) throws JavaScriptModelException, IOException {
- if (member != null) {
- Reader reader= getHTMLContentReader(member, monitor);
- if (reader != null)
- return getString(reader);
- }
- return null;
- }
-
- private Reader getHTMLContentReader(IMember member, IProgressMonitor monitor) throws JavaScriptModelException {
- Reader contentReader= JSdocContentAccess.getHTMLContentReader(member, true, true);
- if (contentReader != null)
- return contentReader;
-
- contentReader= JSdocContentAccess.getContentReader(member, true);
- if (contentReader != null)
- return new JavaDoc2HTMLTextReader(contentReader);
-
- if (member.getOpenable().getBuffer() == null) { // only if no source available
- String s= member.getAttachedJavadoc(monitor);
- if (s != null)
- return new StringReader(s);
- }
- return null;
- }
-
- /**
- * Gets the reader content as a String
- */
- private static String getString(Reader reader) {
- StringBuffer buf= new StringBuffer();
- char[] buffer= new char[1024];
- int count;
- try {
- while ((count= reader.read(buffer)) != -1)
- buf.append(buffer, 0, count);
- } catch (IOException e) {
- return null;
- }
- return buf.toString();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterHandle.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterHandle.java
deleted file mode 100644
index 21838b23..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterHandle.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.InvalidRegistryObjectException;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.text.java.AbstractProposalSorter;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.osgi.framework.Bundle;
-
-/**
- * The description of an extension to the
- * <code>org.eclipse.wst.jsdt.ui.javaCompletionProposalSorters</code> extension point. Instances are
- * immutable.
- *
- *
- */
-public final class ProposalSorterHandle {
- /** The extension schema name of the id attribute. */
- private static final String ID= "id"; //$NON-NLS-1$
- /** The extension schema name of the name attribute. */
- private static final String NAME= "name"; //$NON-NLS-1$
- /** The extension schema name of the class attribute. */
- private static final String CLASS= "class"; //$NON-NLS-1$
- /** The extension schema name of the activate attribute. */
- private static final String ACTIVATE= "activate"; //$NON-NLS-1$
- /** The name of the performance event used to trace extensions. */
- private static final String PERFORMANCE_EVENT= JavaScriptPlugin.getPluginId() + "/perf/content_assist_sorters/extensions"; //$NON-NLS-1$
- /**
- * If <code>true</code>, execution time of extensions is measured and extensions may be
- * disabled if execution takes too long.
- */
- private static final boolean MEASURE_PERFORMANCE= PerformanceStats.isEnabled(PERFORMANCE_EVENT);
- /** The one and only operation name. */
- private static final String SORT= "sort"; //$NON-NLS-1$
-
- /** The identifier of the extension. */
- private final String fId;
- /** The name of the extension. */
- private final String fName;
- /** The class name of the provided <code>AbstractProposalSorter</code>. */
- private final String fClass;
- /** The activate attribute value. */
- private final boolean fActivate;
- /** The configuration element of this extension. */
- private final IConfigurationElement fElement;
- /** The computer, if instantiated, <code>null</code> otherwise. */
- private AbstractProposalSorter fSorter;
-
- /**
- * Creates a new descriptor.
- *
- * @param element the configuration element to read
- * @throws InvalidRegistryObjectException if the configuration element is not valid any longer
- * or does not contain mandatory attributes
- */
- ProposalSorterHandle(IConfigurationElement element) throws InvalidRegistryObjectException {
- Assert.isLegal(element != null);
-
- fElement= element;
- fId= element.getAttribute(ID);
- checkNotNull(fId, ID);
-
- String name= element.getAttribute(NAME);
- if (name == null)
- fName= fId;
- else
- fName= name;
-
- String activateAttribute= element.getAttribute(ACTIVATE);
- fActivate= Boolean.valueOf(activateAttribute).booleanValue();
-
- fClass= element.getAttribute(CLASS);
- checkNotNull(fClass, CLASS);
- }
-
- /**
- * Checks an element that must be defined according to the extension
- * point schema. Throws an
- * <code>InvalidRegistryObjectException</code> if <code>obj</code>
- * is <code>null</code>.
- */
- private void checkNotNull(Object obj, String attribute) throws InvalidRegistryObjectException {
- if (obj == null) {
- Object[] args= { getId(), fElement.getContributor().getName(), attribute };
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_illegal_attribute_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, null);
- JavaScriptPlugin.log(status);
- throw new InvalidRegistryObjectException();
- }
- }
-
- /**
- * Returns the identifier of the described extension.
- *
- * @return Returns the id
- */
- public String getId() {
- return fId;
- }
-
- /**
- * Returns the name of the described extension.
- *
- * @return Returns the name
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Returns a cached instance of the sorter as described in the extension's xml. The sorter is
- * {@link #createSorter() created} the first time that this method is called and then cached.
- *
- * @return a new instance of the proposal sorter as described by this descriptor
- * @throws CoreException if the creation fails
- * @throws InvalidRegistryObjectException if the extension is not valid any longer (e.g. due to
- * plug-in unloading)
- */
- private synchronized AbstractProposalSorter getSorter() throws CoreException, InvalidRegistryObjectException {
- if (fSorter == null && (fActivate || isPluginLoaded()))
- fSorter= createSorter();
- return fSorter;
- }
-
- private boolean isPluginLoaded() throws InvalidRegistryObjectException {
- Bundle bundle= getBundle();
- return bundle != null && bundle.getState() == Bundle.ACTIVE;
- }
-
- private Bundle getBundle() throws InvalidRegistryObjectException {
- String symbolicName= fElement.getContributor().getName();
- Bundle bundle= Platform.getBundle(symbolicName);
- return bundle;
- }
-
- /**
- * Returns a new instance of the sorter as described in the
- * extension's xml.
- *
- * @return a new instance of the completion proposal computer as
- * described by this descriptor
- * @throws CoreException if the creation fails
- * @throws InvalidRegistryObjectException if the extension is not
- * valid any longer (e.g. due to plug-in unloading)
- */
- private AbstractProposalSorter createSorter() throws CoreException, InvalidRegistryObjectException {
- return (AbstractProposalSorter) fElement.createExecutableExtension(CLASS);
- }
-
- /**
- * Safely computes completion proposals through the described extension. If the extension throws
- * an exception or otherwise does not adhere to the contract described in
- * {@link AbstractProposalSorter}, the list is returned as is.
- *
- * @param context the invocation context passed on to the extension
- * @param proposals the list of computed completion proposals to be sorted (element type:
- * {@link org.eclipse.jface.text.contentassist.ICompletionProposal}), must be writable
- */
- public void sortProposals(ContentAssistInvocationContext context, List proposals) {
- IStatus status;
- try {
- AbstractProposalSorter sorter= getSorter();
-
- PerformanceStats stats= startMeter(SORT, sorter);
-
- sorter.beginSorting(context);
- Collections.sort(proposals, sorter);
- sorter.endSorting();
-
- status= stopMeter(stats, SORT);
-
- // valid result
- if (status == null)
- return;
-
- status= createAPIViolationStatus(SORT);
-
- } catch (InvalidRegistryObjectException x) {
- status= createExceptionStatus(x);
- } catch (CoreException x) {
- status= createExceptionStatus(x);
- } catch (RuntimeException x) {
- status= createExceptionStatus(x);
- }
-
- JavaScriptPlugin.log(status);
- return;
- }
-
- private IStatus stopMeter(final PerformanceStats stats, String operation) {
- if (MEASURE_PERFORMANCE) {
- stats.endRun();
- if (stats.isFailure())
- return createPerformanceStatus(operation);
- }
- return null;
- }
-
- private PerformanceStats startMeter(String context, AbstractProposalSorter sorter) {
- final PerformanceStats stats;
- if (MEASURE_PERFORMANCE) {
- stats= PerformanceStats.getStats(PERFORMANCE_EVENT, sorter);
- stats.startRun(context);
- } else {
- stats= null;
- }
- return stats;
- }
-
- private Status createExceptionStatus(InvalidRegistryObjectException x) {
- // extension has become invalid - log & disable
- String disable= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_invalid;
- return new Status(IStatus.INFO, JavaScriptPlugin.getPluginId(), IStatus.OK, disable + " " + reason, x); //$NON-NLS-1$
- }
-
- private Status createExceptionStatus(CoreException x) {
- // unable to instantiate the extension - log & disable
- String disable= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_instantiation;
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, disable + " " + reason, x); //$NON-NLS-1$
- }
-
- private Status createExceptionStatus(RuntimeException x) {
- // misbehaving extension - log & disable
- String disable= createBlameMessage();
- String reason= JavaTextMessages.CompletionProposalComputerDescriptor_reason_runtime_ex;
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, disable + " " + reason, x); //$NON-NLS-1$
- }
-
- private Status createAPIViolationStatus(String operation) {
- String disable= createBlameMessage();
- Object[] args= {operation};
- String reason= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_reason_API, args);
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, disable + " " + reason, null); //$NON-NLS-1$
- }
-
- private Status createPerformanceStatus(String operation) {
- String disable= createBlameMessage();
- Object[] args= {operation};
- String reason= Messages.format(JavaTextMessages.CompletionProposalComputerDescriptor_reason_performance, args);
- return new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, disable + " " + reason, null); //$NON-NLS-1$
- }
-
- private String createBlameMessage() {
- Object[] args= { getName(), getId() };
- String disable= Messages.format(JavaTextMessages.ProposalSorterHandle_blame, args);
- return disable;
- }
-
- /**
- * Returns the error message from the described extension, <code>null</code> for no error.
- *
- * @return the error message from the described extension, <code>null</code> for no error
- */
- public String getErrorMessage() {
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterRegistry.java
deleted file mode 100644
index 645939af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalSorterRegistry.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.InvalidRegistryObjectException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- *
- */
-public final class ProposalSorterRegistry {
- private static final String EXTENSION_POINT= "javaCompletionProposalSorters"; //$NON-NLS-1$
- private static final String DEFAULT_ID= "org.eclipse.wst.jsdt.ui.RelevanceSorter"; //$NON-NLS-1$
-
- private static ProposalSorterRegistry fInstance;
-
- public static synchronized ProposalSorterRegistry getDefault() {
- if (fInstance == null)
- fInstance= new ProposalSorterRegistry(JavaScriptPlugin.getDefault().getPreferenceStore(), PreferenceConstants.CODEASSIST_SORTER);
- return fInstance;
- }
-
- private final IPreferenceStore fPreferenceStore;
- private final String fKey;
-
- private Map fSorters= null;
- private ProposalSorterHandle fDefaultSorter;
-
- private ProposalSorterRegistry(final IPreferenceStore preferenceStore, final String key) {
- Assert.isTrue(preferenceStore != null);
- Assert.isTrue(key != null);
- fPreferenceStore= preferenceStore;
- fKey= key;
- }
-
- public ProposalSorterHandle getCurrentSorter() {
- ensureSortersRead();
- String id= fPreferenceStore.getString(fKey);
- ProposalSorterHandle sorter= (ProposalSorterHandle) fSorters.get(id);
- return sorter != null ? sorter : fDefaultSorter;
- }
-
- private synchronized void ensureSortersRead() {
- if (fSorters != null)
- return;
-
- Map sorters= new LinkedHashMap();
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- List elements= new ArrayList(Arrays.asList(registry.getConfigurationElementsFor(JavaScriptPlugin.getPluginId(), EXTENSION_POINT)));
-
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- IConfigurationElement element= (IConfigurationElement) iter.next();
-
- try {
-
- ProposalSorterHandle handle= new ProposalSorterHandle(element);
- final String id= handle.getId();
- sorters.put(id, handle);
- if (DEFAULT_ID.equals(id))
- fDefaultSorter= handle;
-
- } catch (InvalidRegistryObjectException x) {
- /*
- * Element is not valid any longer as the contributing plug-in was unloaded or for
- * some other reason. Do not include the extension in the list and inform the user
- * about it.
- */
- Object[] args= { element.toString() };
- String message= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_invalid_message, args);
- IStatus status= new Status(IStatus.WARNING, JavaScriptPlugin.getPluginId(), IStatus.OK, message, x);
- informUser(status);
- }
- }
-
- fSorters= sorters;
- }
-
- private void informUser(IStatus status) {
- JavaScriptPlugin.log(status);
- String title= JavaTextMessages.CompletionProposalComputerRegistry_error_dialog_title;
- String message= status.getMessage();
- MessageDialog.openError(JavaScriptPlugin.getActiveWorkbenchShell(), title, message);
- }
-
- public ProposalSorterHandle[] getSorters() {
- ensureSortersRead();
- Collection sorters= fSorters.values();
- return (ProposalSorterHandle[]) sorters.toArray(new ProposalSorterHandle[sorters.size()]);
- }
-
- public void select(ProposalSorterHandle handle) {
- Assert.isTrue(handle != null);
- String id= handle.getId();
-
- fPreferenceStore.setValue(fKey, id);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java
deleted file mode 100644
index 787baedd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Comparator;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.AbstractProposalSorter;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalComparator;
-
-/**
- * A relevance based sorter.
- *
- *
- */
-public final class RelevanceSorter extends AbstractProposalSorter {
-
- private final Comparator fComparator= new CompletionProposalComparator();
-
- public RelevanceSorter() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.AbstractProposalSorter#compare(org.eclipse.jface.text.contentassist.ICompletionProposal, org.eclipse.jface.text.contentassist.ICompletionProposal)
- */
- public int compare(ICompletionProposal p1, ICompletionProposal p2) {
- return fComparator.compare(p1, p2);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java
deleted file mode 100644
index f92bb320..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java
+++ /dev/null
@@ -1,1012 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.IAutoEditStrategy;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.texteditor.ITextEditorExtension2;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.SmartBackspaceManager;
-import org.eclipse.wst.jsdt.internal.ui.text.SmartBackspaceManager.UndoSpec;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Modifies <code>DocumentCommand</code>s inserting semicolons and opening braces to place them
- * smartly, i.e. moving them to the end of a line if that is what the user expects.
- *
- * <p>In practice, semicolons and braces (and the caret) are moved to the end of the line if they are typed
- * anywhere except for semicolons in a <code>for</code> statements definition. If the line contains a semicolon
- * or brace after the current caret position, the cursor is moved after it.</p>
- *
- * @see org.eclipse.jface.text.DocumentCommand
- *
- */
-public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy {
-
- /** String representation of a semicolon. */
- private static final String SEMICOLON= ";"; //$NON-NLS-1$
- /** Char representation of a semicolon. */
- private static final char SEMICHAR= ';';
- /** String represenattion of a opening brace. */
- private static final String BRACE= "{"; //$NON-NLS-1$
- /** Char representation of a opening brace */
- private static final char BRACECHAR= '{';
-
- private char fCharacter;
- private String fPartitioning;
-
- /**
- * Creates a new SmartSemicolonAutoEditStrategy.
- *
- * @param partitioning the document partitioning
- */
- public SmartSemicolonAutoEditStrategy(String partitioning) {
- fPartitioning= partitioning;
- }
-
- /*
- * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
- */
- public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
- // 0: early pruning
- // also customize if <code>doit</code> is false (so it works in code completion situations)
- // if (!command.doit)
- // return;
-
- if (command.text == null)
- return;
-
- if (command.text.equals(SEMICOLON))
- fCharacter= SEMICHAR;
- else if (command.text.equals(BRACE))
- fCharacter= BRACECHAR;
- else
- return;
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON))
- return;
- if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE))
- return;
-
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page == null)
- return;
- IEditorPart part= page.getActiveEditor();
- if (!(part instanceof CompilationUnitEditor))
- return;
- CompilationUnitEditor editor= (CompilationUnitEditor)part;
- if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable())
- return;
- ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class);
- if (extension != null && !extension.validateEditorInputState())
- return;
- if (isMultilineSelection(document, command))
- return;
-
- // 1: find concerned line / position in java code, location in statement
- int pos= command.offset;
- ITextSelection line;
- try {
- IRegion l= document.getLineInformationOfOffset(pos);
- line= new TextSelection(document, l.getOffset(), l.getLength());
- } catch (BadLocationException e) {
- return;
- }
-
- // 2: choose action based on findings (is for-Statement?)
- // for now: compute the best position to insert the new character
- int positionInLine= computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning);
- int position= positionInLine + line.getOffset();
-
- // never position before the current position!
- if (position < pos)
- return;
-
- // never double already existing content
- if (alreadyPresent(document, fCharacter, position))
- return;
-
- // don't do special processing if what we do is actually the normal behaviour
- String insertion= adjustSpacing(document, position, fCharacter);
- if (command.offset == position && insertion.equals(command.text))
- return;
-
- try {
-
- final SmartBackspaceManager manager= (SmartBackspaceManager) editor.getAdapter(SmartBackspaceManager.class);
- if (manager != null && JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_BACKSPACE)) {
- TextEdit e1= new ReplaceEdit(command.offset, command.text.length(), document.get(command.offset, command.length));
- UndoSpec s1= new UndoSpec(command.offset + command.text.length(),
- new Region(command.offset, 0),
- new TextEdit[] {e1},
- 0,
- null);
-
- DeleteEdit smart= new DeleteEdit(position, insertion.length());
- ReplaceEdit raw= new ReplaceEdit(command.offset, command.length, command.text);
- UndoSpec s2= new UndoSpec(position + insertion.length(),
- new Region(command.offset + command.text.length(), 0),
- new TextEdit[] {smart, raw},
- 2,
- s1);
- manager.register(s2);
- }
-
- // 3: modify command
- command.offset= position;
- command.length= 0;
- command.caretOffset= position;
- command.text= insertion;
- command.doit= true;
- command.owner= null;
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- }
-
-
- }
-
- /**
- * Returns <code>true</code> if the document command is applied on a multi
- * line selection, <code>false</code> otherwise.
- *
- * @param document the document
- * @param command the command
- * @return <code>true</code> if <code>command</code> is a multiline command
- */
- private boolean isMultilineSelection(IDocument document, DocumentCommand command) {
- try {
- return document.getNumberOfLines(command.offset, command.length) > 1;
- } catch (BadLocationException e) {
- // ignore
- return false;
- }
- }
-
- /**
- * Adds a space before a brace if it is inserted after a parenthesis, equal sign, or one
- * of the keywords <code>try, else, do</code>.
- *
- * @param doc the document we are working on
- * @param position the insert position of <code>character</code>
- * @param character the character to be inserted
- * @return a <code>String</code> consisting of <code>character</code> plus any additional spacing
- */
- private String adjustSpacing(IDocument doc, int position, char character) {
- if (character == BRACECHAR) {
- if (position > 0 && position <= doc.getLength()) {
- int pos= position - 1;
- if (looksLike(doc, pos, ")") //$NON-NLS-1$
- || looksLike(doc, pos, "=") //$NON-NLS-1$
- || looksLike(doc, pos, "]") //$NON-NLS-1$
- || looksLike(doc, pos, "try") //$NON-NLS-1$
- || looksLike(doc, pos, "else") //$NON-NLS-1$
- || looksLike(doc, pos, "synchronized") //$NON-NLS-1$
- || looksLike(doc, pos, "static") //$NON-NLS-1$
- || looksLike(doc, pos, "finally") //$NON-NLS-1$
- || looksLike(doc, pos, "do")) //$NON-NLS-1$
- return new String(new char[] { ' ', character });
- }
- }
-
- return new String(new char[] { character });
- }
-
- /**
- * Checks whether a character to be inserted is already present at the insert location (perhaps
- * separated by some whitespace from <code>position</code>.
- *
- * @param document the document we are working on
- * @param position the insert position of <code>ch</code>
- * @param ch the character to be inserted
- * @return <code>true</code> if <code>ch</code> is already present at <code>location</code>, <code>false</code> otherwise
- */
- private boolean alreadyPresent(IDocument document, char ch, int position) {
- int pos= firstNonWhitespaceForward(document, position, fPartitioning, document.getLength());
- try {
- if (pos != -1 && document.getChar(pos) == ch)
- return true;
- } catch (BadLocationException e) {
- }
-
- return false;
- }
-
- /**
- * Computes the next insert position of the given character in the current line.
- *
- * @param document the document we are working on
- * @param line the line where the change is being made
- * @param offset the position of the caret in the line when <code>character</code> was typed
- * @param character the character to look for
- * @param partitioning the document partitioning
- * @return the position where <code>character</code> should be inserted / replaced
- */
- protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) {
- String text= line.getText();
- if (text == null)
- return 0;
-
- int insertPos;
- if (character == BRACECHAR) {
-
- insertPos= computeArrayInitializationPos(document, line, offset, partitioning);
-
- if (insertPos == -1) {
- insertPos= computeAfterTryDoElse(document, line, offset);
- }
-
- if (insertPos == -1) {
- insertPos= computeAfterParenthesis(document, line, offset, partitioning);
- }
-
- } else if (character == SEMICHAR) {
-
- if (isForStatement(text, offset)) {
- insertPos= -1; // don't do anything in for statements, as semis are vital part of these
- } else {
- int nextPartitionPos= nextPartitionOrLineEnd(document, line, offset, partitioning);
- insertPos= startOfWhitespaceBeforeOffset(text, nextPartitionPos);
- // if there is a semi present, return its location as alreadyPresent() will take it out this way.
- if (insertPos > 0 && text.charAt(insertPos - 1) == character)
- insertPos= insertPos - 1;
- else if (insertPos > 0 && text.charAt(insertPos - 1) == '}') {
- int opening= scanBackward(document, insertPos - 1 + line.getOffset(), partitioning, -1, new char[] { '{' });
- if (opening > -1 && opening < offset + line.getOffset()) {
- if (computeArrayInitializationPos(document, line, opening - line.getOffset(), partitioning) == -1) {
- insertPos= offset;
- }
- }
- }
- }
-
- } else {
- Assert.isTrue(false);
- return -1;
- }
-
- return insertPos;
- }
-
- /**
- * Computes an insert position for an opening brace if <code>offset</code> maps to a position in
- * <code>document</code> that looks like being the RHS of an assignment or like an array definition.
- *
- * @param document the document being modified
- * @param line the current line under investigation
- * @param offset the offset of the caret position, relative to the line start.
- * @param partitioning the document partitioning
- * @return an insert position relative to the line start if <code>line</code> looks like being an array initialization at <code>offset</code>, -1 otherwise
- */
- private static int computeArrayInitializationPos(IDocument document, ITextSelection line, int offset, String partitioning) {
- // search backward while WS, find = (not != <= >= ==) in default partition
- int pos= offset + line.getOffset();
-
- if (pos == 0)
- return -1;
-
- int p= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
-
- if (p == -1)
- return -1;
-
- try {
-
- char ch= document.getChar(p);
- if (ch != '=' && ch != ']')
- return -1;
-
- if (p == 0)
- return offset;
-
- p= firstNonWhitespaceBackward(document, p - 1, partitioning, -1);
- if (p == -1)
- return -1;
-
- ch= document.getChar(p);
- if (Character.isJavaIdentifierPart(ch) || ch == ']' || ch == '[')
- return offset;
-
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Computes an insert position for an opening brace if <code>offset</code> maps to a position in
- * <code>doc</code> involving a keyword taking a block after it. These are: <code>try</code>,
- * <code>do</code>, <code>synchronized</code>, <code>static</code>, <code>finally</code>, or <code>else</code>.
- *
- * @param doc the document being modified
- * @param line the current line under investigation
- * @param offset the offset of the caret position, relative to the line start.
- * @return an insert position relative to the line start if <code>line</code> contains one of the above keywords at or before <code>offset</code>, -1 otherwise
- */
- private static int computeAfterTryDoElse(IDocument doc, ITextSelection line, int offset) {
- // search backward while WS, find 'try', 'do', 'else' in default partition
- int p= offset + line.getOffset();
- p= firstWhitespaceToRight(doc, p);
- if (p == -1)
- return -1;
- p--;
-
- if (looksLike(doc, p, "try") //$NON-NLS-1$
- || looksLike(doc, p, "do") //$NON-NLS-1$
- || looksLike(doc, p, "synchronized") //$NON-NLS-1$
- || looksLike(doc, p, "static") //$NON-NLS-1$
- || looksLike(doc, p, "finally") //$NON-NLS-1$
- || looksLike(doc, p, "else")) //$NON-NLS-1$
- return p + 1 - line.getOffset();
-
- return -1;
- }
-
- /**
- * 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 line the current line under investigation
- * @param offset the offset of the caret position, relative to the line start.
- * @param partitioning the document partitioning
- * @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 computeAfterParenthesis(IDocument document, ITextSelection line, int offset, String partitioning) {
- // 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
- int pos= offset + line.getOffset();
- int length= line.getOffset() + line.getLength();
- int scanTo= scanForward(document, pos, partitioning, length, '}');
- if (scanTo == -1)
- scanTo= length;
-
- int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1;
-
- while (true) {
- int startScan= closingParen + 1;
- closingParen= scanForward(document, startScan, partitioning, scanTo, ')');
- if (closingParen == -1)
- break;
-
- int openingParen= findOpeningParenMatch(document, closingParen, partitioning);
-
- // 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;
-
- if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning))
- return closingParen + 1 - line.getOffset();
-
- if (looksLikeIfWhileForCatch(document, openingParen - 1, partitioning))
- return closingParen + 1 - line.getOffset();
-
- if (looksLikeMethodDecl(document, openingParen - 1, partitioning))
- return closingParen + 1 - line.getOffset();
-
- }
-
- 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 document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @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(IDocument document, int position, String partitioning) {
- final char CLOSING_PAREN= ')';
- try {
- if (position < 1)
- return position;
-
- int nonWS= firstNonWhitespaceBackward(document, position - 1, partitioning, -1);
- if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN)
- return nonWS;
- } catch (BadLocationException e1) {
- }
- return position;
- }
-
- /**
- * Finds the first whitespace character position to the right of (and including) <code>position</code>.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @return the position of a whitespace character greater or equal than <code>position</code> separated only by whitespace, or -1 if none found
- */
- private static int firstWhitespaceToRight(IDocument document, int position) {
- int length= document.getLength();
- Assert.isTrue(position >= 0);
- Assert.isTrue(position <= length);
-
- try {
- while (position < length) {
- char ch= document.getChar(position);
- if (Character.isWhitespace(ch))
- return position;
- position++;
- }
- return position;
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code>
- * and &gt; <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code>
- * and the position is in the default partition.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> &lt; <code>position</code>
- * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
- */
- private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) {
- Assert.isTrue(position < document.getLength());
- Assert.isTrue(bound >= -1);
-
- try {
- while (position > bound) {
- char ch= document.getChar(position);
- if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
- return position;
- position--;
- }
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Finds the smallest position in <code>document</code> such that the position is &gt;= <code>position</code>
- * and &lt; <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code>
- * and the position is in the default partition.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> &gt; <code>position</code>
- * @return the smallest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
- */
- private static int firstNonWhitespaceForward(IDocument document, int position, String partitioning, int bound) {
- Assert.isTrue(position >= 0);
- Assert.isTrue(bound <= document.getLength());
-
- try {
- while (position < bound) {
- char ch= document.getChar(position);
- if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
- return position;
- position++;
- }
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code>
- * and &gt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
- * ch in <code>chars</code> and the position is in the default partition.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code>
- * @param chars an array of <code>char</code> to search for
- * @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>-1</code> if none can be found
- */
- private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) {
- Assert.isTrue(bound >= -1);
- Assert.isTrue(position < document.getLength() );
-
- Arrays.sort(chars);
-
- try {
- while (position > bound) {
-
- if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
- return position;
-
- position--;
- }
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
-// /**
-// * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code>
-// * and &gt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
-// * and the position is in the default partition.
-// *
-// * @param document the document being modified
-// * @param position the first character position in <code>document</code> to be considered
-// * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code>
-// * @param chars an array of <code>char</code> to search for
-// * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
-// */
-// private static int scanBackward(IDocument document, int position, int bound, char ch) {
-// return scanBackward(document, position, bound, new char[] {ch});
-// }
-//
- /**
- * Finds the lowest position in <code>document</code> such that the position is &gt;= <code>position</code>
- * and &lt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
- * ch in <code>chars</code> and the position is in the default partition.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code>
- * @param chars an array of <code>char</code> to search for
- * @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
- */
- private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) {
- Assert.isTrue(position >= 0);
- Assert.isTrue(bound <= document.getLength());
-
- Arrays.sort(chars);
-
- try {
- while (position < bound) {
-
- if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
- return position;
-
- position++;
- }
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Finds the lowest position in <code>document</code> such that the position is &gt;= <code>position</code>
- * and &lt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
- * and the position is in the default partition.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code>
- * @param ch a <code>char</code> to search for
- * @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
- */
- private static int scanForward(IDocument document, int position, String partitioning, int bound, char ch) {
- return scanForward(document, position, partitioning, bound, new char[] {ch});
- }
-
- /**
- * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
- * contains the <code>new</code> keyword.
- *
- * @param document the document being modified
- * @param offset the first character position in <code>document</code> to be considered
- * @param length the length of the character range to be considered
- * @param partitioning the document partitioning
- * @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
- */
- private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
- Assert.isTrue(length >= 0);
- Assert.isTrue(offset >= 0);
- Assert.isTrue(offset + length < document.getLength() + 1);
-
- try {
- String text= document.get(offset, length);
- int pos= text.indexOf("new"); //$NON-NLS-1$
-
- while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
- pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
-
- if (pos < 0)
- return false;
-
- if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
- return false;
-
- if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
- return false;
-
- return true;
-
- } catch (BadLocationException e) {
- }
- return false;
- }
-
- /**
- * Checks whether the content of <code>document</code> at <code>position</code> looks like an
- * anonymous class definition. <code>position</code> must be to the left of the opening
- * parenthesis of the definition's parameter list.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
- */
- private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) {
- int previousCommaParenEqual= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '(', '='});
- if (previousCommaParenEqual == -1 || position < previousCommaParenEqual + 5) // 2 for borders, 3 for "new"
- return false;
-
- if (isNewMatch(document, previousCommaParenEqual + 1, position - previousCommaParenEqual - 2, partitioning))
- return true;
-
- return false;
- }
-
- /**
- * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
- *
- * @param document the document being modified
- * @param position the position to be checked
- * @param partitioning the document partitioning
- * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
- */
- private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
- Assert.isTrue(position >= 0);
- Assert.isTrue(position <= document.getLength());
-
- try {
- // don't use getPartition2 since we're interested in the scanned character's partition
- ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false);
- return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
-
- } catch (BadLocationException e) {
- }
-
- return false;
- }
-
- /**
- * Finds the position of the parenthesis matching the closing parenthesis at <code>position</code>.
- *
- * @param document the document being modified
- * @param position the position in <code>document</code> of a closing parenthesis
- * @param partitioning the document partitioning
- * @return the position in <code>document</code> of the matching parenthesis, or -1 if none can be found
- */
- private static int findOpeningParenMatch(IDocument document, int position, String partitioning) {
- final char CLOSING_PAREN= ')';
- final char OPENING_PAREN= '(';
-
- Assert.isTrue(position < document.getLength());
- Assert.isTrue(position >= 0);
- Assert.isTrue(isDefaultPartition(document, position, partitioning));
-
- try {
-
- Assert.isTrue(document.getChar(position) == CLOSING_PAREN);
-
- int depth= 1;
- while (true) {
- position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN});
- if (position == -1)
- return -1;
-
- if (document.getChar(position) == CLOSING_PAREN)
- depth++;
- else
- depth--;
-
- if (depth == 0)
- return position;
- }
-
- } catch (BadLocationException e) {
- return -1;
- }
- }
-
- /**
- * Checks whether, to the left of <code>position</code> and separated only by whitespace,
- * <code>document</code> contains a keyword taking a parameter list and a block after it.
- * These are: <code>if</code>, <code>while</code>, <code>catch</code>, <code>for</code>, <code>synchronized</code>, <code>switch</code>.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @return <code>true</code> if <code>document</code> contains any of the above keywords to the left of <code>position</code>, <code>false</code> otherwise
- */
- private static boolean looksLikeIfWhileForCatch(IDocument document, int position, String partitioning) {
- position= firstNonWhitespaceBackward(document, position, partitioning, -1);
- if (position == -1)
- return false;
-
- return looksLike(document, position, "if") //$NON-NLS-1$
- || looksLike(document, position, "while") //$NON-NLS-1$
- || looksLike(document, position, "catch") //$NON-NLS-1$
- || looksLike(document, position, "synchronized") //$NON-NLS-1$
- || looksLike(document, position, "switch") //$NON-NLS-1$
- || looksLike(document, position, "for"); //$NON-NLS-1$
- }
-
- /**
- * Checks whether code>document</code> contains the <code>String</code> <code>like</code> such
- * that its last character is at <code>position</code>. If <code>like</code> starts with a
- * identifier part (as determined by {@link Character#isJavaIdentifierPart(char)}), it is also made
- * sure that <code>like</code> is preceded by some non-identifier character or stands at the
- * document start.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param like the <code>String</code> to look for.
- * @return <code>true</code> if <code>document</code> contains <code>like</code> such that it ends at <code>position</code>, <code>false</code> otherwise
- */
- private static boolean looksLike(IDocument document, int position, String like) {
- int length= like.length();
- if (position < length - 1)
- return false;
-
- try {
- if (!like.equals(document.get(position - length + 1, length)))
- return false;
-
- if (position >= length && Character.isJavaIdentifierPart(like.charAt(0)) && Character.isJavaIdentifierPart(document.getChar(position - length)))
- return false;
-
- } catch (BadLocationException e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Checks whether the content of <code>document</code> at <code>position</code> looks like a
- * method declaration header (i.e. only the return type and method name). <code>position</code>
- * must be just left of the opening parenthesis of the parameter list.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @return <code>true</code> if the content of <code>document</code> looks like a method definition, <code>false</code> otherwise
- */
- private static boolean looksLikeMethodDecl(IDocument document, int position, String partitioning) {
-
- // method name
- position= eatIdentToLeft(document, position, partitioning);
- if (position < 1)
- return false;
-
- position= eatBrackets(document, position - 1, partitioning);
- if (position < 1)
- return false;
-
- position= eatIdentToLeft(document, position - 1, partitioning);
-
- return position != -1;
- }
-
- /**
- * From <code>position</code> to the left, eats any whitespace and then a pair of brackets
- * as used to declare an array return type like <pre>String [ ]</pre>.
- * The return value is either the position of the opening bracket or <code>position</code> if no
- * pair of brackets can be parsed.
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @return the smallest character position of bracket pair or <code>position</code>
- */
- private static int eatBrackets(IDocument document, int position, String partitioning) {
- // accept array return type
- int pos= firstNonWhitespaceBackward(document, position, partitioning, -1);
- try {
- if (pos > 1 && document.getChar(pos) == ']') {
- pos= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
- if (pos > 0 && document.getChar(pos) == '[')
- return pos;
- }
- } catch (BadLocationException e) {
- // won't happen
- }
- return position;
- }
-
- /**
- * From <code>position</code> to the left, eats any whitespace and the first identifier, returning
- * the position of the first identifier character (in normal read order).
- * <p>When called on a document with content <code>" some string "</code> and positionition 13, the
- * return value will be 6 (the first letter in <code>string</code>).
- * </p>
- *
- * @param document the document being modified
- * @param position the first character position in <code>document</code> to be considered
- * @param partitioning the document partitioning
- * @return the smallest character position of an identifier or -1 if none can be found; always &lt;= <code>position</code>
- */
- private static int eatIdentToLeft(IDocument document, int position, String partitioning) {
- if (position < 0)
- return -1;
- Assert.isTrue(position < document.getLength());
-
- int p= firstNonWhitespaceBackward(document, position, partitioning, -1);
- if (p == -1)
- return -1;
-
- try {
- while (p >= 0) {
-
- char ch= document.getChar(p);
- if (Character.isJavaIdentifierPart(ch)) {
- p--;
- continue;
- }
-
- // length must be > 0
- if (Character.isWhitespace(ch) && p != position)
- return p + 1;
- else
- return -1;
-
- }
-
- // start of document reached
- return 0;
-
- } catch (BadLocationException e) {
- }
- return -1;
- }
-
- /**
- * Returns a position in the first java partition after the last non-empty and non-comment partition.
- * There is no non-whitespace from the returned position to the end of the partition it is contained in.
- *
- * @param document the document being modified
- * @param line the line under investigation
- * @param offset the caret offset into <code>line</code>
- * @param partitioning the document partitioning
- * @return the position of the next Java partition, or the end of <code>line</code>
- */
- private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) {
- // run relative to document
- final int docOffset= offset + line.getOffset();
- final int eol= line.getOffset() + line.getLength();
- int nextPartitionPos= eol; // init with line end
- int validPosition= docOffset;
-
- try {
- ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, true);
- validPosition= getValidPositionForPartition(document, partition, eol);
- while (validPosition == -1) {
- nextPartitionPos= partition.getOffset() - 1;
- if (nextPartitionPos < docOffset) {
- validPosition= docOffset;
- break;
- }
- partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, false);
- validPosition= getValidPositionForPartition(document, partition, eol);
- }
- } catch (BadLocationException e) {
- }
-
- validPosition= Math.max(validPosition, docOffset);
- // make relative to line
- validPosition -= line.getOffset();
- return validPosition;
- }
-
- /**
- * Returns a valid insert location (except for whitespace) in <code>partition</code> or -1 if
- * there is no valid insert location.
- * An valid insert location is right after any java string or character partition, or at the end
- * of a java default partition, but never behind <code>maxOffset</code>. Comment partitions or
- * empty java partitions do never yield valid insert positions.
- *
- * @param doc the document being modified
- * @param partition the current partition
- * @param maxOffset the maximum offset to consider
- * @return a valid insert location in <code>partition</code>, or -1 if there is no valid insert location
- */
- private static int getValidPositionForPartition(IDocument doc, ITypedRegion partition, int maxOffset) {
- final int INVALID= -1;
-
- if (IJavaScriptPartitions.JAVA_DOC.equals(partition.getType()))
- return INVALID;
- if (IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(partition.getType()))
- return INVALID;
- if (IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT.equals(partition.getType()))
- return INVALID;
-
- int endOffset= Math.min(maxOffset, partition.getOffset() + partition.getLength());
-
- if (IJavaScriptPartitions.JAVA_CHARACTER.equals(partition.getType()))
- return endOffset;
- if (IJavaScriptPartitions.JAVA_STRING.equals(partition.getType()))
- return endOffset;
- if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
- try {
- if (doc.get(partition.getOffset(), endOffset - partition.getOffset()).trim().length() == 0)
- return INVALID;
- else
- return endOffset;
- } catch (BadLocationException e) {
- return INVALID;
- }
- }
- // default: we don't know anything about the partition - assume valid
- return endOffset;
- }
-
- /**
- * Determines whether the current line contains a for statement.
- * Algorithm: any "for" word in the line is a positive, "for" contained in a string literal will
- * produce a false positive.
- *
- * @param line the line where the change is being made
- * @param offset the position of the caret
- * @return <code>true</code> if <code>line</code> contains <code>for</code>, <code>false</code> otherwise
- */
- private static boolean isForStatement(String line, int offset) {
- /* searching for (^|\s)for(\s|$) */
- int forPos= line.indexOf("for"); //$NON-NLS-1$
- if (forPos != -1) {
- if ((forPos == 0 || !Character.isJavaIdentifierPart(line.charAt(forPos - 1))) && (line.length() == forPos + 3 || !Character.isJavaIdentifierPart(line.charAt(forPos + 3))))
- return true;
- }
- return false;
- }
-
- /**
- * Returns the position in <code>text</code> after which there comes only whitespace, up to
- * <code>offset</code>.
- *
- * @param text the text being searched
- * @param offset the maximum offset to search for
- * @return the smallest value <code>v</code> such that <code>text.substring(v, offset).trim() == 0</code>
- */
- private static int startOfWhitespaceBeforeOffset(String text, int offset) {
- int i= Math.min(offset, text.length());
- for (; i >= 1; i--) {
- if (!Character.isWhitespace(text.charAt(i - 1)))
- break;
- }
- return i;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TemplateCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TemplateCompletionProposalComputer.java
deleted file mode 100644
index fc9f3eff..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TemplateCompletionProposalComputer.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaContextType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaDocContextType;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.TemplateEngine;
-import org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.TemplateProposal;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- *
- *
- */
-public final class TemplateCompletionProposalComputer implements IJavaCompletionProposalComputer {
-
- private final TemplateEngine fJavaTemplateEngine;
- private final TemplateEngine fJavadocTemplateEngine;
-
- public TemplateCompletionProposalComputer() {
- TemplateContextType contextType= JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType(JavaContextType.NAME);
- if (contextType == null) {
- contextType= new JavaContextType();
- JavaScriptPlugin.getDefault().getTemplateContextRegistry().addContextType(contextType);
- }
- if (contextType != null)
- fJavaTemplateEngine= new TemplateEngine(contextType);
- else
- fJavaTemplateEngine= null;
- contextType= JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType("javadoc"); //$NON-NLS-1$
- if (contextType == null) {
- contextType= new JavaDocContextType();
- JavaScriptPlugin.getDefault().getTemplateContextRegistry().addContextType(contextType);
- }
- if (contextType != null)
- fJavadocTemplateEngine= new TemplateEngine(contextType);
- else
- fJavadocTemplateEngine= null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- TemplateEngine engine;
- try {
- String partition= TextUtilities.getContentType(context.getDocument(), IJavaScriptPartitions.JAVA_PARTITIONING, context.getInvocationOffset(), true);
- if (partition.equals(IJavaScriptPartitions.JAVA_DOC))
- engine= fJavadocTemplateEngine;
- else
- engine= fJavaTemplateEngine;
- } catch (BadLocationException x) {
- return Collections.EMPTY_LIST;
- }
-
- if (engine != null) {
- if (!(context instanceof JavaContentAssistInvocationContext))
- return Collections.EMPTY_LIST;
-
- JavaContentAssistInvocationContext javaContext= (JavaContentAssistInvocationContext) context;
- IJavaScriptUnit unit= javaContext.getCompilationUnit();
- if (unit == null)
- return Collections.EMPTY_LIST;
-
- engine.reset();
- engine.complete(javaContext.getViewer(), javaContext.getInvocationOffset(), unit);
-
- TemplateProposal[] templateProposals= engine.getResults();
- List result= new ArrayList(Arrays.asList(templateProposals));
-
- IJavaCompletionProposal[] keyWordResults= javaContext.getKeywordProposals();
- if (keyWordResults.length > 0) {
- List removals= new ArrayList();
-
- // update relevance of template proposals that match with a keyword
- // give those templates slightly more relevance than the keyword to
- // sort them first
- // remove keyword templates that don't have an equivalent
- // keyword proposal
- if (keyWordResults.length > 0) {
- outer: for (int k= 0; k < templateProposals.length; k++) {
- TemplateProposal curr= templateProposals[k];
- String name= curr.getTemplate().getName();
- for (int i= 0; i < keyWordResults.length; i++) {
- String keyword= keyWordResults[i].getDisplayString();
- if (name.startsWith(keyword)) {
- curr.setRelevance(keyWordResults[i].getRelevance() + 1);
- continue outer;
- }
- }
- if (isKeyword(name))
- removals.add(curr);
- }
- }
-
- result.removeAll(removals);
- }
- return result;
- }
-
- return Collections.EMPTY_LIST;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeContextInformation(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return Collections.EMPTY_LIST;
- }
-
- private static final Set KEYWORDS;
- static {
- Set keywords= new HashSet(42);
- keywords.add("abstract"); //$NON-NLS-1$
- keywords.add("assert"); //$NON-NLS-1$
- keywords.add("break"); //$NON-NLS-1$
- keywords.add("case"); //$NON-NLS-1$
- keywords.add("catch"); //$NON-NLS-1$
- keywords.add("class"); //$NON-NLS-1$
- keywords.add("continue"); //$NON-NLS-1$
- keywords.add("default"); //$NON-NLS-1$
- keywords.add("do"); //$NON-NLS-1$
- keywords.add("else"); //$NON-NLS-1$
- keywords.add("elseif"); //$NON-NLS-1$
- keywords.add("extends"); //$NON-NLS-1$
- keywords.add("final"); //$NON-NLS-1$
- keywords.add("finally"); //$NON-NLS-1$
- keywords.add("for"); //$NON-NLS-1$
- keywords.add("if"); //$NON-NLS-1$
- keywords.add("implements"); //$NON-NLS-1$
- keywords.add("import"); //$NON-NLS-1$
- keywords.add("instanceof"); //$NON-NLS-1$
- keywords.add("interface"); //$NON-NLS-1$
- keywords.add("native"); //$NON-NLS-1$
- keywords.add("new"); //$NON-NLS-1$
- keywords.add("package"); //$NON-NLS-1$
- keywords.add("private"); //$NON-NLS-1$
- keywords.add("protected"); //$NON-NLS-1$
- keywords.add("public"); //$NON-NLS-1$
- keywords.add("return"); //$NON-NLS-1$
- keywords.add("static"); //$NON-NLS-1$
- keywords.add("strictfp"); //$NON-NLS-1$
- keywords.add("super"); //$NON-NLS-1$
- keywords.add("switch"); //$NON-NLS-1$
- keywords.add("synchronized"); //$NON-NLS-1$
- keywords.add("this"); //$NON-NLS-1$
- keywords.add("throw"); //$NON-NLS-1$
- keywords.add("throws"); //$NON-NLS-1$
- keywords.add("transient"); //$NON-NLS-1$
- keywords.add("try"); //$NON-NLS-1$
- keywords.add("volatile"); //$NON-NLS-1$
- keywords.add("while"); //$NON-NLS-1$
- keywords.add("true"); //$NON-NLS-1$
- keywords.add("false"); //$NON-NLS-1$
- keywords.add("null"); //$NON-NLS-1$
- KEYWORDS= Collections.unmodifiableSet(keywords);
- }
-
- private boolean isKeyword(String name) {
- return KEYWORDS.contains(name);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#getErrorMessage()
- */
- public String getErrorMessage() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionStarted()
- */
- public void sessionStarted() {
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionEnded()
- */
- public void sessionEnded() {
- fJavadocTemplateEngine.reset();
- fJavaTemplateEngine.reset();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TypeProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TypeProposalInfo.java
deleted file mode 100644
index 7f698460..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/TypeProposalInfo.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-
-
-/**
- * Proposal info that computes the javadoc lazily when it is queried.
- *
- *
- */
-public final class TypeProposalInfo extends MemberProposalInfo {
-
- /**
- * Creates a new proposal info.
- *
- * @param project the java project to reference when resolving types
- * @param proposal the proposal to generate information for
- */
- public TypeProposalInfo(IJavaScriptProject project, CompletionProposal proposal) {
- super(project, proposal);
- }
-
- /**
- * Resolves the member described by the receiver and returns it if found.
- * Returns <code>null</code> if no corresponding member can be found.
- *
- * @return the resolved member or <code>null</code> if none is found
- * @throws JavaScriptModelException if accessing the java model fails
- */
- protected IMember resolveMember() throws JavaScriptModelException {
- char[] signature= fProposal.getSignature();
- String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(signature));
- return fJavaProject.findType(typeName);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractAnnotationHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractAnnotationHover.java
deleted file mode 100644
index 18507e8b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractAnnotationHover.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.Iterator;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IStorageEditorInput;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaAnnotationIterator;
-
-
-/**
- * Abstract super class for annotation hovers.
- *
- *
- */
-public abstract class AbstractAnnotationHover extends AbstractJavaEditorTextHover {
-
- private IPreferenceStore fStore= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- private DefaultMarkerAnnotationAccess fAnnotationAccess= new DefaultMarkerAnnotationAccess();
- private boolean fAllAnnotations;
-
-
- public AbstractAnnotationHover(boolean allAnnotations) {
- fAllAnnotations= allAnnotations;
- }
-
- /*
- * Formats a message as HTML text.
- */
- private String formatMessage(String message) {
- StringBuffer buffer= new StringBuffer();
- HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
- buffer.append(HTMLPrinter.convertToHTMLContent(message));
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-
- /*
- * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- IPath path;
- IAnnotationModel model;
- if (textViewer instanceof ISourceViewer) {
- path= null;
- model= ((ISourceViewer)textViewer).getAnnotationModel();
- } else {
- // Get annotation model from file buffer manager
- path= getEditorInputPath();
- model= getAnnotationModel(path);
- }
- if (model == null)
- return null;
-
- try {
- Iterator e= new JavaAnnotationIterator(model, true, fAllAnnotations);
- int layer= -1;
- String message= null;
- while (e.hasNext()) {
- Annotation a= (Annotation) e.next();
-
- AnnotationPreference preference= getAnnotationPreference(a);
- if (preference == null || !(preference.getTextPreferenceKey() != null && fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey()))))
- continue;
-
- Position p= model.getPosition(a);
-
- int l= fAnnotationAccess.getLayer(a);
-
- if (l > layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
- String msg= a.getText();
- if (msg != null && msg.trim().length() > 0) {
- message= msg;
- layer= l;
- }
- }
- }
- if (layer > -1)
- return formatMessage(message);
-
- } finally {
- try {
- if (path != null) {
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- manager.disconnect(path, LocationKind.NORMALIZE, null);
- }
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex.getStatus());
- }
- }
-
- return null;
- }
-
- private IPath getEditorInputPath() {
- if (getEditor() == null)
- return null;
-
- IEditorInput input= getEditor().getEditorInput();
- if (input instanceof IStorageEditorInput) {
- try {
- return ((IStorageEditorInput)input).getStorage().getFullPath();
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex.getStatus());
- }
- }
- return null;
- }
-
- private IAnnotationModel getAnnotationModel(IPath path) {
- if (path == null)
- return null;
-
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- manager.connect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex.getStatus());
- return null;
- }
-
- IAnnotationModel model= null;
- try {
- model= manager.getTextFileBuffer(path, LocationKind.NORMALIZE).getAnnotationModel();
- return model;
- } finally {
- if (model == null) {
- try {
- manager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException ex) {
- JavaScriptPlugin.log(ex.getStatus());
- }
- }
- }
- }
-
- /**
- * Returns the annotation preference for the given annotation.
- *
- * @param annotation the annotation
- * @return the annotation preference or <code>null</code> if none
- */
- private AnnotationPreference getAnnotationPreference(Annotation annotation) {
-
- if (annotation.isMarkedDeleted())
- return null;
- return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java
deleted file mode 100644
index bf96fb9d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHoverExtension;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.wst.jsdt.core.ICodeAssist;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.WorkingCopyManager;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-import org.osgi.framework.Bundle;
-
-/**
- * Abstract class for providing hover information for Java elements.
- *
- *
- */
-public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover, ITextHoverExtension {
- /**
- * The style sheet (css).
- *
- */
- private static String fgStyleSheet;
- private IEditorPart fEditor;
-
- /*
- * @see IJavaEditorTextHover#setEditor(IEditorPart)
- */
- public void setEditor(IEditorPart editor) {
- fEditor= editor;
- }
-
- protected IEditorPart getEditor() {
- return fEditor;
- }
-
- protected ICodeAssist getCodeAssist() {
- if (fEditor != null) {
- IEditorInput input= fEditor.getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- IClassFileEditorInput cfeInput= (IClassFileEditorInput) input;
- return cfeInput.getClassFile();
- }
-
- WorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- return manager.getWorkingCopy(input, false);
- }
-
- return null;
- }
-
- /*
- * @see ITextHover#getHoverRegion(ITextViewer, int)
- */
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- return JavaWordFinder.findWord(textViewer.getDocument(), offset);
- }
-
- /*
- * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
-
- /*
- * The region should be a word region an not of length 0.
- * This check is needed because codeSelect(...) also finds
- * the Java element if the offset is behind the word.
- */
- if (hoverRegion.getLength() == 0)
- return null;
-
- ICodeAssist resolve= getCodeAssist();
- if (resolve != null) {
- try {
- IJavaScriptElement[] result= resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength());
- if (result == null)
- return null;
-
- int nResults= result.length;
- if (nResults == 0)
- return null;
-
- return getHoverInfo(result);
-
- } catch (JavaScriptModelException x) {
- return null;
- }
- }
- return null;
- }
-
- /**
- * Provides hover information for the given Java elements.
- *
- * @param javaElements the Java elements for which to provide hover information
- * @return the hover information string
- *
- */
- protected String getHoverInfo(IJavaScriptElement[] javaElements) {
- return null;
- }
-
- /*
- * @see ITextHoverExtension#getHoverControlCreator()
- *
- */
- public IInformationControlCreator getHoverControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true), EditorsUI.getTooltipAffordanceString());
- }
- };
- }
-
- protected static String getStyleSheet() {
- if (fgStyleSheet == null)
- fgStyleSheet= loadStyleSheet();
- String css= fgStyleSheet;
- if (css != null) {
- FontData fontData= JFaceResources.getFontRegistry().getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
- css= HTMLPrinter.convertTopLevelFont(css, fontData);
- }
-
- return css;
- }
-
- private static String loadStyleSheet() {
- Bundle bundle= Platform.getBundle(JavaScriptPlugin.getPluginId());
- URL styleSheetURL= bundle.getEntry("/JavadocHoverStyleSheet.css"); //$NON-NLS-1$
- if (styleSheetURL != null) {
- try {
- styleSheetURL= FileLocator.toFileURL(styleSheetURL);
- BufferedReader reader= new BufferedReader(new InputStreamReader(styleSheetURL.openStream()));
- StringBuffer buffer= new StringBuffer(200);
- String line= reader.readLine();
- while (line != null) {
- buffer.append(line);
- buffer.append('\n');
- line= reader.readLine();
- }
- return buffer.toString();
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- return ""; //$NON-NLS-1$
- }
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpandHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpandHover.java
deleted file mode 100644
index 407e40fa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpandHover.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IInformationControlCreatorExtension;
-import org.eclipse.jface.text.ITextViewerExtension5;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextViewer;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.CompositeRuler;
-import org.eclipse.jface.text.source.IAnnotationAccess;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.IAnnotationHover;
-import org.eclipse.jface.text.source.IAnnotationHoverExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ILineRange;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.IVerticalRulerListener;
-import org.eclipse.jface.text.source.LineRange;
-import org.eclipse.jface.text.source.VerticalRulerEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput;
-
-
-/**
- * This class got moved here form Platform Text since it was not used there
- * and caused discouraged access warnings. It will be moved down again once
- * annotation roll-over support is provided by Platform Text.
- *
- *
- */
-public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHoverExtension {
-
- private class InformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension {
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl createInformationControl(Shell parent) {
- return new AnnotationExpansionControl(parent, SWT.NONE, fAnnotationAccess);
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReuse(org.eclipse.jface.text.IInformationControl)
- */
- public boolean canReuse(IInformationControl control) {
- return control instanceof AnnotationExpansionControl;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReplace(org.eclipse.jface.text.IInformationControlCreator)
- */
- public boolean canReplace(IInformationControlCreator creator) {
- return creator == this;
- }
- }
-
- private class VerticalRulerListener implements IVerticalRulerListener {
-
- /*
- * @see org.eclipse.jface.text.source.IVerticalRulerListener#annotationSelected(org.eclipse.jface.text.source.VerticalRulerEvent)
- */
- public void annotationSelected(VerticalRulerEvent event) {
- fCompositeRuler.fireAnnotationSelected(event);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IVerticalRulerListener#annotationDefaultSelected(org.eclipse.jface.text.source.VerticalRulerEvent)
- */
- public void annotationDefaultSelected(VerticalRulerEvent event) {
- fCompositeRuler.fireAnnotationDefaultSelected(event);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IVerticalRulerListener#annotationContextMenuAboutToShow(org.eclipse.jface.text.source.VerticalRulerEvent, org.eclipse.swt.widgets.Menu)
- */
- public void annotationContextMenuAboutToShow(VerticalRulerEvent event, Menu menu) {
- fCompositeRuler.fireAnnotationContextMenuAboutToShow(event, menu);
- }
- }
-
-
- private final IInformationControlCreator fgCreator= new InformationControlCreator();
- protected final IVerticalRulerListener fgListener= new VerticalRulerListener();
- protected CompositeRuler fCompositeRuler;
- protected IDoubleClickListener fDblClickListener;
- protected IAnnotationAccess fAnnotationAccess;
-
- /**
- * Creates a new hover instance.
- *
- * @param ruler
- * @param access
- * @param doubleClickListener
- */
- public AnnotationExpandHover(CompositeRuler ruler, IAnnotationAccess access, IDoubleClickListener doubleClickListener) {
- fCompositeRuler= ruler;
- fAnnotationAccess= access;
- fDblClickListener= doubleClickListener;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, int)
- */
- public String getHoverInfo(ISourceViewer sourceViewer, int line) {
- // we don't have any sensible return value as text
- return null;
- }
-
- protected Object getHoverInfoForLine(ISourceViewer viewer, int line) {
- IAnnotationModel model= viewer.getAnnotationModel();
- IDocument document= viewer.getDocument();
-
- if (model == null)
- return null;
-
- List exact= new ArrayList();
- HashMap messagesAtPosition= new HashMap();
-
- Iterator e= model.getAnnotationIterator();
- while (e.hasNext()) {
- Annotation annotation= (Annotation) e.next();
- Position position= model.getPosition(annotation);
- if (position == null)
- continue;
-
- if (compareRulerLine(position, document, line) == 1) {
- if (isDuplicateMessage(messagesAtPosition, position, annotation.getText()))
- continue;
-
- exact.add(annotation);
- }
- }
-
- if (exact.size() < 1)
- return null;
-
- sort(exact, model);
-
- if (exact.size() > 0)
- setLastRulerMouseLocation(viewer, line);
-
- AnnotationHoverInput input= new AnnotationHoverInput();
- input.fAnnotations= (Annotation[]) exact.toArray(new Annotation[0]);
- input.fViewer= viewer;
- input.fRulerInfo= fCompositeRuler;
- input.fAnnotationListener= fgListener;
- input.fDoubleClickListener= fDblClickListener;
- input.model= model;
-
- return input;
- }
-
- protected void sort(List exact, final IAnnotationModel model) {
- class AnnotationComparator implements Comparator {
-
- /*
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- */
- public int compare(Object o1, Object o2) {
- Annotation a1= (Annotation) o1;
- Annotation a2= (Annotation) o2;
-
- Position p1= model.getPosition(a1);
- Position p2= model.getPosition(a2);
-
- // annotation order:
- // primary order: by position in line
- // secondary: annotation importance
- if (p1.offset == p2.offset)
- return getOrder(a2) - getOrder(a1);
- return p1.offset - p2.offset;
- }
- }
-
- Collections.sort(exact, new AnnotationComparator());
-
- }
-
- protected int getOrder(Annotation annotation) {
- if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
- IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
- return extension.getLayer(annotation);
- }
- return IAnnotationAccessExtension.DEFAULT_LAYER;
- }
-
- protected boolean isDuplicateMessage(Map messagesAtPosition, Position position, String message) {
- if (message == null)
- return false;
-
- if (messagesAtPosition.containsKey(position)) {
- Object value= messagesAtPosition.get(position);
- if (message.equals(value))
- return true;
-
- if (value instanceof List) {
- List messages= (List)value;
- if (messages.contains(message))
- return true;
- messages.add(message);
- } else {
- ArrayList messages= new ArrayList();
- messages.add(value);
- messages.add(message);
- messagesAtPosition.put(position, messages);
- }
- } else
- messagesAtPosition.put(position, message);
- return false;
- }
-
- protected void setLastRulerMouseLocation(ISourceViewer viewer, int line) {
- // set last mouse activity in order to get the correct context menu
- if (fCompositeRuler != null) {
- StyledText st= viewer.getTextWidget();
- if (st != null && !st.isDisposed()) {
- if (viewer instanceof ITextViewerExtension5) {
- int widgetLine= ((ITextViewerExtension5)viewer).modelLine2WidgetLine(line);
- Point loc= st.getLocationAtOffset(st.getOffsetAtLine(widgetLine));
- fCompositeRuler.setLocationOfLastMouseButtonActivity(0, loc.y);
- } else if (viewer instanceof TextViewer) {
- // TODO remove once TextViewer implements the extension
- int widgetLine= ((TextViewer)viewer).modelLine2WidgetLine(line);
- Point loc= st.getLocationAtOffset(st.getOffsetAtLine(widgetLine));
- fCompositeRuler.setLocationOfLastMouseButtonActivity(0, loc.y);
- }
- }
- }
- }
-
- /**
- * Returns the distance to the ruler line.
- *
- * @param position the position
- * @param document the document
- * @param line the line number
- * @return the distance to the ruler line
- */
- protected int compareRulerLine(Position position, IDocument document, int line) {
-
- if (position.getOffset() > -1 && position.getLength() > -1) {
- try {
- int firstLine= document.getLineOfOffset(position.getOffset());
- if (line == firstLine)
- return 1;
- if (firstLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength()))
- return 2;
- } catch (BadLocationException x) {
- }
- }
-
- return 0;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverControlCreator()
- */
- public IInformationControlCreator getHoverControlCreator() {
- return fgCreator;
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, org.eclipse.jface.text.source.ILineRange, int)
- */
- public Object getHoverInfo(ISourceViewer sourceViewer, ILineRange lineRange, int visibleLines) {
- return getHoverInfoForLine(sourceViewer, lineRange.getStartLine());
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverLineRange(org.eclipse.jface.text.source.ISourceViewer, int)
- */
- public ILineRange getHoverLineRange(ISourceViewer viewer, int lineNumber) {
- return new LineRange(lineNumber, 1);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#canHandleMouseCursor()
- */
- public boolean canHandleMouseCursor() {
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpansionControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpansionControl.java
deleted file mode 100644
index 0ea7d928..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationExpansionControl.java
+++ /dev/null
@@ -1,844 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.AbstractInformationControlManager;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IInformationControlExtension;
-import org.eclipse.jface.text.IInformationControlExtension2;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IViewportListener;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextViewer;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationAccess;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.IVerticalRulerInfo;
-import org.eclipse.jface.text.source.IVerticalRulerListener;
-import org.eclipse.jface.text.source.VerticalRulerEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.MenuListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackAdapter;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Layout;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Widget;
-
-
-/**
- * A control that can display a number of annotations. The control can decide how it layouts the
- * annotations to present them to the user.
- * <p>
- * This class got moved here form Platform Text since it was not used there
- * and caused discouraged access warnings. It will be moved down again once
- * annotation roll-over support is provided by Platform Text.
- * </p>
- * <p>Each annotation can have its custom context menu and hover.</p>
- *
- *
- */
-public class AnnotationExpansionControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 {
-
-
- public interface ICallback {
- void run(IInformationControlExtension2 control);
- }
-
- /**
- * Input used by the control to display the annotations.
- * TODO move to top-level class
- * TODO encapsulate fields
- *
- *
- */
- public static class AnnotationHoverInput {
- public Annotation[] fAnnotations;
- public ISourceViewer fViewer;
- public IVerticalRulerInfo fRulerInfo;
- public IVerticalRulerListener fAnnotationListener;
- public IDoubleClickListener fDoubleClickListener;
- public ICallback redoAction;
- public IAnnotationModel model;
- }
-
- private final class Item {
- Annotation fAnnotation;
- Canvas canvas;
- StyleRange[] oldStyles;
-
- public void selected() {
- Display disp= fShell.getDisplay();
- canvas.setCursor(fHandCursor);
- // TODO: shade - for now: set grey background
- canvas.setBackground(getSelectionColor(disp));
-
- // highlight the viewer background at its position
- oldStyles= setViewerBackground(fAnnotation);
-
- // set the selection
- fSelection= this;
-
- if (fHoverManager != null)
- fHoverManager.showInformation();
-
- if (fInput.fAnnotationListener != null) {
- VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation);
- fInput.fAnnotationListener.annotationSelected(event);
- }
-
- }
-
- public void defaultSelected() {
- if (fInput.fAnnotationListener != null) {
- VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation);
- fInput.fAnnotationListener.annotationDefaultSelected(event);
- }
-
- dispose();
- }
-
-// public void showContextMenu(Menu menu) {
-// if (fInput.fAnnotationListener != null) {
-// VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation);
-// fInput.fAnnotationListener.annotationContextMenuAboutToShow(event, menu);
-// }
-// }
-
- public void deselect() {
- // hide the popup
-// fHoverManager.disposeInformationControl();
-
- // deselect
- fSelection= null;
-
- resetViewerBackground(oldStyles);
- oldStyles= null;
-
- Display disp= fShell.getDisplay();
- canvas.setCursor(null);
- // TODO: remove shading - for now: set standard background
- canvas.setBackground(disp.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
-
- }
-
- }
-
- /**
- * Disposes of an item
- */
- private final static class MyDisposeListener implements DisposeListener {
- /*
- * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
- */
- public void widgetDisposed(DisposeEvent e) {
- Item item= (Item) ((Widget) e.getSource()).getData();
- item.deselect();
- item.canvas= null;
- item.fAnnotation= null;
- item.oldStyles= null;
-
- ((Widget) e.getSource()).setData(null);
- }
- }
-
- /**
- * Listener on context menu invocation on the items
- */
- private final class MyMenuDetectListener implements Listener {
- /*
- * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
- */
- public void handleEvent(Event event) {
- if (event.type == SWT.MenuDetect) {
- // TODO: show per-item menu
- // for now: show ruler context menu
- if (fInput != null) {
- Control ruler= fInput.fRulerInfo.getControl();
- if (ruler != null && !ruler.isDisposed()) {
- Menu menu= ruler.getMenu();
- if (menu != null && !menu.isDisposed()) {
- menu.setLocation(event.x, event.y);
- menu.addMenuListener(new MenuListener() {
-
- public void menuHidden(MenuEvent e) {
- dispose();
- }
-
- public void menuShown(MenuEvent e) {
- }
-
- });
- menu.setVisible(true);
- }
- }
- }
- }
- }
- }
-
-
- /**
- * Listener on mouse events on the items.
- */
- private final class MyMouseListener extends MouseAdapter {
- /*
- * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseDoubleClick(MouseEvent e) {
- Item item= (Item) ((Widget) e.getSource()).getData();
- if (e.button == 1 && item.fAnnotation == fInput.fAnnotations[0] && fInput.fDoubleClickListener != null) {
- fInput.fDoubleClickListener.doubleClick(null);
- // special code for JDT to renew the annotation set.
- if (fInput.redoAction != null)
- fInput.redoAction.run(AnnotationExpansionControl.this);
- }
-// dispose();
- // TODO special action to invoke double-click action on the vertical ruler
- // how about
-// Canvas can= (Canvas) e.getSource();
-// Annotation a= (Annotation) can.getData();
-// if (a != null) {
-// a.getDoubleClickAction().run();
-// }
- }
-
- /*
- * Using mouseDown as mouseUp isn't fired on some Platforms, for
- * details see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=165533
- *
- * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseDown(MouseEvent e) {
- Item item= (Item) ((Widget) e.getSource()).getData();
- // TODO for now, to make double click work: disable single click on the first item
- // disable later when the annotationlistener selectively handles input
- if (item != null && e.button == 1) // && item.fAnnotation != fInput.fAnnotations[0])
- item.defaultSelected();
- }
-
- }
-
- /**
- * Listener on mouse track events on the items.
- */
- private final class MyMouseTrackListener implements MouseTrackListener {
- /*
- * @see org.eclipse.swt.events.MouseTrackListener#mouseEnter(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseEnter(MouseEvent e) {
- Item item= (Item) ((Widget) e.getSource()).getData();
- if (item != null)
- item.selected();
- }
-
- /*
- * @see org.eclipse.swt.events.MouseTrackListener#mouseExit(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseExit(MouseEvent e) {
-
- Item item= (Item) ((Widget) e.getSource()).getData();
- if (item != null)
- item.deselect();
-
- // if the event lies outside the entire popup, dispose
- org.eclipse.swt.graphics.Region region= fShell.getRegion();
- Canvas can= (Canvas) e.getSource();
- Point p= can.toDisplay(e.x, e.y);
- if (region == null) {
- Rectangle bounds= fShell.getBounds();
-// p= fShell.toControl(p);
- if (!bounds.contains(p))
- dispose();
- } else {
- p= fShell.toControl(p);
- if (!region.contains(p))
- dispose();
- }
-
-
- }
-
- /*
- * @see org.eclipse.swt.events.MouseTrackListener#mouseHover(org.eclipse.swt.events.MouseEvent)
- */
- public void mouseHover(MouseEvent e) {
- if (fHoverManager == null) {
- fHoverManager= new HoverManager();
- fHoverManager.takesFocusWhenVisible(false);
- fHoverManager.install(fComposite);
- fHoverManager.showInformation();
- }
- }
- }
-
-
- /**
- *
- *
- *
- */
- public class LinearLayouter {
-
- private static final int ANNOTATION_SIZE= 14;
- private static final int BORDER_WIDTH= 2;
-
- public Layout getLayout(int itemCount) {
- // simple layout: a row of items
- GridLayout layout= new GridLayout(itemCount, true);
- layout.horizontalSpacing= 1;
- layout.verticalSpacing= 0;
- layout.marginHeight= 1;
- layout.marginWidth= 1;
- return layout;
- }
-
- public Object getLayoutData() {
- GridData gridData= new GridData(ANNOTATION_SIZE + 2 * BORDER_WIDTH, ANNOTATION_SIZE + 2 * BORDER_WIDTH);
- gridData.horizontalAlignment= GridData.CENTER;
- gridData.verticalAlignment= GridData.CENTER;
- return gridData;
- }
-
- public int getAnnotationSize() {
- return ANNOTATION_SIZE;
- }
-
- public int getBorderWidth() {
- return BORDER_WIDTH;
- }
-
- public org.eclipse.swt.graphics.Region getShellRegion(int itemCount) {
- // no special region - set to null for default shell size
- return null;
- }
-
- }
-
-
- /**
- * Listener on paint events on the items. Paints the annotation image on the given <code>GC</code>.
- */
- private final class MyPaintListener implements PaintListener {
- /*
- * @see org.eclipse.swt.events.PaintListener#paintControl(org.eclipse.swt.events.PaintEvent)
- */
- public void paintControl(PaintEvent e) {
- Canvas can= (Canvas) e.getSource();
- Annotation a= ((Item) can.getData()).fAnnotation;
- if (a != null) {
- Rectangle rect= new Rectangle(fLayouter.getBorderWidth(), fLayouter.getBorderWidth(), fLayouter.getAnnotationSize(), fLayouter.getAnnotationSize());
- if (fAnnotationAccessExtension != null)
- fAnnotationAccessExtension.paint(a, e.gc, can, rect);
- }
- }
- }
-
- /**
- * Our own private hover manager used to shop per-item pop-ups.
- */
- private final class HoverManager extends AbstractInformationControlManager {
-
- /**
- *
- */
- public HoverManager() {
- super(new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent);
- }
- });
-
- setMargins(5, 10);
- setAnchor(ANCHOR_BOTTOM);
- setFallbackAnchors(new Anchor[] {ANCHOR_BOTTOM, ANCHOR_LEFT, ANCHOR_RIGHT} );
- }
-
- /*
- * @see org.eclipse.jface.text.AbstractInformationControlManager#computeInformation()
- */
- protected void computeInformation() {
- if (fSelection != null) {
- Rectangle subjectArea= fSelection.canvas.getBounds();
- Annotation annotation= fSelection.fAnnotation;
- String msg;
- if (annotation != null)
- msg= annotation.getText();
- else
- msg= null;
-
- setInformation(msg, subjectArea);
- }
- }
-
-
- }
-
- /** Model data. */
- protected AnnotationHoverInput fInput;
- /** The control's shell */
- private Shell fShell;
- /** The composite combining all the items. */
- protected Composite fComposite;
- /** The hand cursor. */
- private Cursor fHandCursor;
- /** The currently selected item, or <code>null</code> if none is selected. */
- private Item fSelection;
- /** The hover manager for the per-item hovers. */
- private HoverManager fHoverManager;
- /** The annotation access extension. */
- private IAnnotationAccessExtension fAnnotationAccessExtension;
-
-
- /* listener legion */
- private final MyPaintListener fPaintListener;
- private final MyMouseTrackListener fMouseTrackListener;
- private final MyMouseListener fMouseListener;
- private final MyMenuDetectListener fMenuDetectListener;
- private final DisposeListener fDisposeListener;
- private final IViewportListener fViewportListener;
-
- private LinearLayouter fLayouter;
-
- /**
- * Creates a new control.
- *
- * @param parent
- * @param shellStyle
- * @param access
- */
- public AnnotationExpansionControl(Shell parent, int shellStyle, IAnnotationAccess access) {
- fPaintListener= new MyPaintListener();
- fMouseTrackListener= new MyMouseTrackListener();
- fMouseListener= new MyMouseListener();
- fMenuDetectListener= new MyMenuDetectListener();
- fDisposeListener= new MyDisposeListener();
- fViewportListener= new IViewportListener() {
-
- public void viewportChanged(int verticalOffset) {
- dispose();
- }
-
- };
- fLayouter= new LinearLayouter();
-
- if (access instanceof IAnnotationAccessExtension)
- fAnnotationAccessExtension= (IAnnotationAccessExtension) access;
-
- fShell= new Shell(parent, shellStyle | SWT.NO_FOCUS | SWT.ON_TOP);
- Display display= fShell.getDisplay();
- fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
- fComposite= new Composite(fShell, SWT.NO_FOCUS | SWT.NO_REDRAW_RESIZE | SWT.NO_TRIM);
-// fComposite= new Composite(fShell, SWT.NO_FOCUS | SWT.NO_REDRAW_RESIZE | SWT.NO_TRIM | SWT.V_SCROLL);
-
- GridLayout layout= new GridLayout(1, true);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- fShell.setLayout(layout);
-
- GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= fLayouter.getAnnotationSize() + 2 * fLayouter.getBorderWidth() + 4;
- fComposite.setLayoutData(data);
- fComposite.addMouseTrackListener(new MouseTrackAdapter() {
-
- public void mouseExit(MouseEvent e) {
- if (fComposite == null)
- return;
- Control[] children= fComposite.getChildren();
- Rectangle bounds= null;
- for (int i= 0; i < children.length; i++) {
- if (bounds == null)
- bounds= children[i].getBounds();
- else
- bounds.add(children[i].getBounds());
- if (bounds.contains(e.x, e.y))
- return;
- }
-
- // if none of the children contains the event, we leave the popup
- dispose();
- }
-
- });
-
-// fComposite.getVerticalBar().addListener(SWT.Selection, new Listener() {
-//
-// public void handleEvent(Event event) {
-// Rectangle bounds= fShell.getBounds();
-// int x= bounds.x - fLayouter.getAnnotationSize() - fLayouter.getBorderWidth();
-// int y= bounds.y;
-// fShell.setBounds(x, y, bounds.width, bounds.height);
-// }
-//
-// });
-
- fHandCursor= new Cursor(display, SWT.CURSOR_HAND);
- fShell.setCursor(fHandCursor);
- fComposite.setCursor(fHandCursor);
-
- setInfoSystemColor();
- }
-
- private void setInfoSystemColor() {
- Display display= fShell.getDisplay();
- setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String)
- */
- public void setInformation(String information) {
- setInput(null);
- }
-
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object)
- */
- public void setInput(Object input) {
- if (fInput != null && fInput.fViewer != null)
- fInput.fViewer.removeViewportListener(fViewportListener);
-
- if (input instanceof AnnotationHoverInput)
- fInput= (AnnotationHoverInput) input;
- else
- fInput= null;
-
- inputChanged(fInput, null);
- }
-
- protected void inputChanged(Object newInput, Object newSelection) {
- refresh();
- }
-
- protected void refresh() {
- adjustItemNumber();
-
- if (fInput == null)
- return;
-
- if (fInput.fAnnotations == null)
- return;
-
- if (fInput.fViewer != null)
- fInput.fViewer.addViewportListener(fViewportListener);
-
- fShell.setRegion(fLayouter.getShellRegion(fInput.fAnnotations.length));
-
- Layout layout= fLayouter.getLayout(fInput.fAnnotations.length);
- fComposite.setLayout(layout);
-
- Control[] children= fComposite.getChildren();
- for (int i= 0; i < fInput.fAnnotations.length; i++) {
- Canvas canvas= (Canvas) children[i];
- Item item= new Item();
- item.canvas= canvas;
- item.fAnnotation= fInput.fAnnotations[i];
- canvas.setData(item);
- canvas.redraw();
- }
-
- }
-
- protected void adjustItemNumber() {
- if (fComposite == null)
- return;
-
- Control[] children= fComposite.getChildren();
- int oldSize= children.length;
- int newSize= fInput == null ? 0 : fInput.fAnnotations.length;
-
- Display display= fShell.getDisplay();
-
- // add missing items
- for (int i= oldSize; i < newSize; i++) {
- Canvas canvas= new Canvas(fComposite, SWT.NONE);
- Object gridData= fLayouter.getLayoutData();
- canvas.setLayoutData(gridData);
- canvas.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
-
- canvas.addPaintListener(fPaintListener);
-
- canvas.addMouseTrackListener(fMouseTrackListener);
-
- canvas.addMouseListener(fMouseListener);
-
- canvas.addListener(SWT.MenuDetect, fMenuDetectListener);
-
- canvas.addDisposeListener(fDisposeListener);
- }
-
- // dispose of exceeding resources
- for (int i= oldSize; i > newSize; i--) {
- Item item= (Item) children[i - 1].getData();
- item.deselect();
- children[i - 1].dispose();
- }
-
- }
-
- /*
- * @see IInformationControl#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- fShell.setVisible(visible);
- }
-
- /*
- * @see IInformationControl#dispose()
- */
- public void dispose() {
- if (fShell != null) {
- if (!fShell.isDisposed())
- fShell.dispose();
- fShell= null;
- fComposite= null;
- if (fHandCursor != null)
- fHandCursor.dispose();
- fHandCursor= null;
- if (fHoverManager != null)
- fHoverManager.dispose();
- fHoverManager= null;
- fSelection= null;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension#hasContents()
- */
- public boolean hasContents() {
- return fInput.fAnnotations != null && fInput.fAnnotations.length > 0;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int)
- */
- public void setSizeConstraints(int maxWidth, int maxHeight) {
- //fMaxWidth= maxWidth;
- //fMaxHeight= maxHeight;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControl#computeSizeHint()
- */
- public Point computeSizeHint() {
- return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- }
-
- /*
- * @see IInformationControl#setLocation(Point)
- */
- public void setLocation(Point location) {
- fShell.setLocation(location);
- }
-
- /*
- * @see IInformationControl#setSize(int, int)
- */
- public void setSize(int width, int height) {
- fShell.setSize(width, height);
- }
-
- /*
- * @see IInformationControl#addDisposeListener(DisposeListener)
- */
- public void addDisposeListener(DisposeListener listener) {
- fShell.addDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#removeDisposeListener(DisposeListener)
- */
- public void removeDisposeListener(DisposeListener listener) {
- fShell.removeDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#setForegroundColor(Color)
- */
- public void setForegroundColor(Color foreground) {
- fComposite.setForeground(foreground);
- }
-
- /*
- * @see IInformationControl#setBackgroundColor(Color)
- */
- public void setBackgroundColor(Color background) {
- fComposite.setBackground(background);
- }
-
- /*
- * @see IInformationControl#isFocusControl()
- */
- public boolean isFocusControl() {
- if (fComposite.isFocusControl())
- return true;
-
- Control[] children= fComposite.getChildren();
- for (int i= 0; i < children.length; i++) {
- if (children[i].isFocusControl())
- return true;
- }
- return false;
- }
-
- /*
- * @see IInformationControl#setFocus()
- */
- public void setFocus() {
- fShell.forceFocus();
- }
-
- /*
- * @see IInformationControl#addFocusListener(FocusListener)
- */
- public void addFocusListener(FocusListener listener) {
- fShell.addFocusListener(listener);
- }
-
- /*
- * @see IInformationControl#removeFocusListener(FocusListener)
- */
- public void removeFocusListener(FocusListener listener) {
- fShell.removeFocusListener(listener);
- }
-
- private StyleRange[] setViewerBackground(Annotation annotation) {
- StyledText text= fInput.fViewer.getTextWidget();
- if (text == null || text.isDisposed())
- return null;
-
- Display disp= text.getDisplay();
-
- Position pos= fInput.model.getPosition(annotation);
- if (pos == null)
- return null;
-
- IRegion region= ((TextViewer)fInput.fViewer).modelRange2WidgetRange(new Region(pos.offset, pos.length));
- if (region == null)
- return null;
-
- StyleRange[] ranges= text.getStyleRanges(region.getOffset(), region.getLength());
-
- List undoRanges= new ArrayList(ranges.length);
- for (int i= 0; i < ranges.length; i++) {
- undoRanges.add(ranges[i].clone());
- }
-
- int offset= region.getOffset();
- StyleRange current= undoRanges.size() > 0 ? (StyleRange) undoRanges.get(0) : null;
- int curStart= current != null ? current.start : region.getOffset() + region.getLength();
- int curEnd= current != null ? current.start + current.length : -1;
- int index= 0;
-
- // fill no-style regions
- while (curEnd < region.getOffset() + region.getLength()) {
- // add empty range
- if (curStart > offset) {
- StyleRange undoRange= new StyleRange(offset, curStart - offset, null, null);
- undoRanges.add(index, undoRange);
- index++;
- }
-
- // step
- index++;
- if (index < undoRanges.size()) {
- offset= curEnd;
- current= (StyleRange) undoRanges.get(index);
- curStart= current.start;
- curEnd= current.start + current.length;
- } else if (index == undoRanges.size()) {
- // last one
- offset= curEnd;
- current= null;
- curStart= region.getOffset() + region.getLength();
- curEnd= -1;
- } else
- curEnd= region.getOffset() + region.getLength();
- }
-
- // create modified styles (with background)
- List shadedRanges= new ArrayList(undoRanges.size());
- for (Iterator it= undoRanges.iterator(); it.hasNext(); ) {
- StyleRange range= (StyleRange) ((StyleRange) it.next()).clone();
- shadedRanges.add(range);
- range.background= getHighlightColor(disp);
- }
-
- // set the ranges one by one
- for (Iterator iter= shadedRanges.iterator(); iter.hasNext(); ) {
- text.setStyleRange((StyleRange) iter.next());
-
- }
-
- return (StyleRange[]) undoRanges.toArray(undoRanges.toArray(new StyleRange[0]));
- }
-
- private void resetViewerBackground(StyleRange[] oldRanges) {
-
- if (oldRanges == null)
- return;
-
- if (fInput == null)
- return;
-
- StyledText text= fInput.fViewer.getTextWidget();
- if (text == null || text.isDisposed())
- return;
-
- // set the ranges one by one
- for (int i= 0; i < oldRanges.length; i++) {
- text.setStyleRange(oldRanges[i]);
- }
- }
-
- private Color getHighlightColor(Display disp) {
- return disp.getSystemColor(SWT.COLOR_GRAY);
- }
-
- private Color getSelectionColor(Display disp) {
- return disp.getSystemColor(SWT.COLOR_GRAY);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java
deleted file mode 100644
index 326cb086..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-/**
- * This annotation hover shows the description of the
- * selected annotation.
- *
- *
- */
-public class AnnotationHover extends AbstractAnnotationHover {
-
- public AnnotationHover() {
- super(true);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java
deleted file mode 100644
index c61c6d51..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextHoverExtension;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.information.IInformationProviderExtension2;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-
-/**
- * Caution: this implementation is a layer breaker and contains some "shortcuts"
- */
-public class BestMatchHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 {
-
- private List fTextHoverSpecifications;
- private List fInstantiatedTextHovers;
- private ITextHover fBestHover;
-
- public BestMatchHover() {
- installTextHovers();
- }
-
- public BestMatchHover(IEditorPart editor) {
- this();
- setEditor(editor);
- }
-
- /**
- * Installs all text hovers.
- */
- private void installTextHovers() {
-
- // initialize lists - indicates that the initialization happened
- fTextHoverSpecifications= new ArrayList(2);
- fInstantiatedTextHovers= new ArrayList(2);
-
- // populate list
- JavaEditorTextHoverDescriptor[] hoverDescs= JavaScriptPlugin.getDefault().getJavaEditorTextHoverDescriptors();
- for (int i= 0; i < hoverDescs.length; i++) {
- // ensure that we don't add ourselves to the list
- if (!PreferenceConstants.ID_BESTMATCH_HOVER.equals(hoverDescs[i].getId()))
- fTextHoverSpecifications.add(hoverDescs[i]);
- }
- }
-
- private void checkTextHovers() {
- if (fTextHoverSpecifications.size() == 0)
- return;
-
- for (Iterator iterator= new ArrayList(fTextHoverSpecifications).iterator(); iterator.hasNext(); ) {
- JavaEditorTextHoverDescriptor spec= (JavaEditorTextHoverDescriptor) iterator.next();
-
- IJavaEditorTextHover hover= spec.createTextHover();
- if (hover != null) {
- hover.setEditor(getEditor());
- addTextHover(hover);
- fTextHoverSpecifications.remove(spec);
- }
- }
- }
-
- protected void addTextHover(ITextHover hover) {
- if (!fInstantiatedTextHovers.contains(hover))
- fInstantiatedTextHovers.add(hover);
- }
-
- /*
- * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
-
- checkTextHovers();
- fBestHover= null;
-
- if (fInstantiatedTextHovers == null)
- return null;
-
- for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) {
- ITextHover hover= (ITextHover)iterator.next();
-
- String s= hover.getHoverInfo(textViewer, hoverRegion);
- if (s != null && s.trim().length() > 0) {
- fBestHover= hover;
- return s;
- }
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator()
- *
- */
- public IInformationControlCreator getHoverControlCreator() {
- if (fBestHover instanceof ITextHoverExtension)
- return ((ITextHoverExtension)fBestHover).getHoverControlCreator();
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
- *
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- if (fBestHover instanceof IInformationProviderExtension2)
- return ((IInformationProviderExtension2)fBestHover).getInformationPresenterControlCreator();
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java
deleted file mode 100644
index 9c3379dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.swt.SWT;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-import org.osgi.framework.Bundle;
-
-/**
- * Describes a Java editor text hover.
- *
- *
- */
-public class JavaEditorTextHoverDescriptor {
-
- private static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT= "org.eclipse.wst.jsdt.ui.javaEditorTextHovers"; //$NON-NLS-1$
- private static final String HOVER_TAG= "hover"; //$NON-NLS-1$
- private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
- private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$
- private static final String LABEL_ATTRIBUTE= "label"; //$NON-NLS-1$
- private static final String ACTIVATE_PLUG_IN_ATTRIBUTE= "activate"; //$NON-NLS-1$
- private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
-
- public static final String NO_MODIFIER= "0"; //$NON-NLS-1$
- public static final String DISABLED_TAG= "!"; //$NON-NLS-1$
- public static final String VALUE_SEPARATOR= ";"; //$NON-NLS-1$
-
- private int fStateMask;
- private String fModifierString;
- private boolean fIsEnabled;
-
- private IConfigurationElement fElement;
-
-
- /**
- * Returns all Java editor text hovers contributed to the workbench.
- *
- * @return an array with the contributed text hovers
- */
- public static JavaEditorTextHoverDescriptor[] getContributedHovers() {
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- IConfigurationElement[] elements= registry.getConfigurationElementsFor(JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT);
- JavaEditorTextHoverDescriptor[] hoverDescs= createDescriptors(elements);
- initializeFromPreferences(hoverDescs);
- return hoverDescs;
- }
-
- /**
- * Computes the state mask for the given modifier string.
- *
- * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.'
- * @return the state mask or -1 if the input is invalid
- */
- public static int computeStateMask(String modifiers) {
- if (modifiers == null)
- return -1;
-
- if (modifiers.length() == 0)
- return SWT.NONE;
-
- int stateMask= 0;
- StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
- while (modifierTokenizer.hasMoreTokens()) {
- int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
- if (modifier == 0 || (stateMask & modifier) == modifier)
- return -1;
- stateMask= stateMask | modifier;
- }
- return stateMask;
- }
-
- /**
- * Creates a new Java Editor text hover descriptor from the given configuration element.
- *
- * @param element the configuration element
- */
- private JavaEditorTextHoverDescriptor(IConfigurationElement element) {
- Assert.isNotNull(element);
- fElement= element;
- }
-
- /**
- * Creates the Java editor text hover.
- *
- * @return the text hover
- */
- public IJavaEditorTextHover createTextHover() {
- String pluginId = fElement.getContributor().getName();
- boolean isHoversPlugInActivated= Platform.getBundle(pluginId).getState() == Bundle.ACTIVE;
- if (isHoversPlugInActivated || canActivatePlugIn()) {
- try {
- return (IJavaEditorTextHover)fElement.createExecutableExtension(CLASS_ATTRIBUTE);
- } catch (CoreException x) {
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), 0, JavaHoverMessages.JavaTextHover_createTextHover, null));
- }
- }
-
- return null;
- }
-
- //---- XML Attribute accessors ---------------------------------------------
-
- /**
- * Returns the hover's id.
- *
- * @return the id
- */
- public String getId() {
- return fElement.getAttribute(ID_ATTRIBUTE);
- }
-
- /**
- * Returns the hover's class name.
- *
- * @return the class name
- */
- public String getHoverClassName() {
- return fElement.getAttribute(CLASS_ATTRIBUTE);
- }
-
- /**
- * Returns the hover's label.
- *
- * @return the label
- */
- public String getLabel() {
- String label= fElement.getAttribute(LABEL_ATTRIBUTE);
- if (label != null)
- return label;
-
- // Return simple class name
- label= getHoverClassName();
- int lastDot= label.lastIndexOf('.');
- if (lastDot >= 0 && lastDot < label.length() - 1)
- return label.substring(lastDot + 1);
- else
- return label;
- }
-
- /**
- * Returns the hover's description.
- *
- * @return the hover's description or <code>null</code> if not provided
- */
- public String getDescription() {
- return fElement.getAttribute(DESCRIPTION_ATTRIBUTE);
- }
-
-
- public boolean canActivatePlugIn() {
- return Boolean.valueOf(fElement.getAttribute(ACTIVATE_PLUG_IN_ATTRIBUTE)).booleanValue();
- }
-
- public boolean equals(Object obj) {
- if (obj == null || !obj.getClass().equals(this.getClass()) || getId() == null)
- return false;
- return getId().equals(((JavaEditorTextHoverDescriptor)obj).getId());
- }
-
- public int hashCode() {
- return getId().hashCode();
- }
-
- private static JavaEditorTextHoverDescriptor[] createDescriptors(IConfigurationElement[] elements) {
- List result= new ArrayList(elements.length);
- for (int i= 0; i < elements.length; i++) {
- IConfigurationElement element= elements[i];
- if (HOVER_TAG.equals(element.getName())) {
- JavaEditorTextHoverDescriptor desc= new JavaEditorTextHoverDescriptor(element);
- result.add(desc);
- }
- }
- return (JavaEditorTextHoverDescriptor[])result.toArray(new JavaEditorTextHoverDescriptor[result.size()]);
- }
-
- private static void initializeFromPreferences(JavaEditorTextHoverDescriptor[] hovers) {
- String compiledTextHoverModifiers= JavaScriptPlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS);
-
- StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, VALUE_SEPARATOR);
- HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2);
-
- while (tokenizer.hasMoreTokens()) {
- String id= tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- idToModifier.put(id, tokenizer.nextToken());
- }
-
- String compiledTextHoverModifierMasks= JavaScriptPlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS);
-
- tokenizer= new StringTokenizer(compiledTextHoverModifierMasks, VALUE_SEPARATOR);
- HashMap idToModifierMask= new HashMap(tokenizer.countTokens() / 2);
-
- while (tokenizer.hasMoreTokens()) {
- String id= tokenizer.nextToken();
- if (tokenizer.hasMoreTokens())
- idToModifierMask.put(id, tokenizer.nextToken());
- }
-
- for (int i= 0; i < hovers.length; i++) {
- String modifierString= (String)idToModifier.get(hovers[i].getId());
- boolean enabled= true;
- if (modifierString == null)
- modifierString= DISABLED_TAG;
-
- if (modifierString.startsWith(DISABLED_TAG)) {
- enabled= false;
- modifierString= modifierString.substring(1);
- }
-
- if (modifierString.equals(NO_MODIFIER))
- modifierString= ""; //$NON-NLS-1$
-
- hovers[i].fModifierString= modifierString;
- hovers[i].fIsEnabled= enabled;
- hovers[i].fStateMask= computeStateMask(modifierString);
- if (hovers[i].fStateMask == -1) {
- // Fallback: use stored modifier masks
- try {
- hovers[i].fStateMask= Integer.parseInt((String)idToModifierMask.get(hovers[i].getId()));
- } catch (NumberFormatException ex) {
- hovers[i].fStateMask= -1;
- }
- // Fix modifier string
- int stateMask= hovers[i].fStateMask;
- if (stateMask == -1)
- hovers[i].fModifierString= ""; //$NON-NLS-1$
- else
- hovers[i].fModifierString= EditorUtility.getModifierString(stateMask);
- }
- }
- }
-
- /**
- * Returns the configured modifier getStateMask for this hover.
- *
- * @return the hover modifier stateMask or -1 if no hover is configured
- */
- public int getStateMask() {
- return fStateMask;
- }
-
- /**
- * Returns the modifier String as set in the preference store.
- *
- * @return the modifier string
- */
- public String getModifierString() {
- return fModifierString;
- }
-
- /**
- * Returns whether this hover is enabled or not.
- *
- * @return <code>true</code> if enabled
- */
- public boolean isEnabled() {
- return fIsEnabled;
- }
-
- /**
- * Returns this hover descriptors configuration element.
- *
- * @return the configuration element
- *
- */
- public IConfigurationElement getConfigurationElement() {
- return fElement;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java
deleted file mode 100644
index ea42ac1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHoverExtension;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.information.IInformationProviderExtension2;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-
-
-/**
- * Proxy for JavaEditorTextHovers.
- *
- *
- */
-public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 {
-
- private JavaEditorTextHoverDescriptor fHoverDescriptor;
- private IJavaEditorTextHover fHover;
-
- public JavaEditorTextHoverProxy(JavaEditorTextHoverDescriptor descriptor, IEditorPart editor) {
- fHoverDescriptor= descriptor;
- setEditor(editor);
- }
-
- /*
- * @see IJavaEditorTextHover#setEditor(IEditorPart)
- */
- public void setEditor(IEditorPart editor) {
- super.setEditor(editor);
-
- if (fHover != null)
- fHover.setEditor(getEditor());
- }
-
- public boolean isEnabled() {
- return true;
- }
-
- /*
- * @see ITextHover#getHoverRegion(ITextViewer, int)
- */
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (ensureHoverCreated())
- return fHover.getHoverRegion(textViewer, offset);
-
- return null;
- }
-
- /*
- * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- if (ensureHoverCreated())
- return fHover.getHoverInfo(textViewer, hoverRegion);
-
- return null;
- }
-
- private boolean ensureHoverCreated() {
- if (!isEnabled() || fHoverDescriptor == null)
- return false;
- return isCreated() || createHover();
- }
-
- private boolean isCreated() {
- return fHover != null;
- }
-
- private boolean createHover() {
- fHover= fHoverDescriptor.createTextHover();
- if (fHover != null)
- fHover.setEditor(getEditor());
- return isCreated();
- }
-
- /*
- * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator()
- *
- */
- public IInformationControlCreator getHoverControlCreator() {
- if (ensureHoverCreated() && (fHover instanceof ITextHoverExtension))
- return ((ITextHoverExtension)fHover).getHoverControlCreator();
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- if (ensureHoverCreated() && (fHover instanceof IInformationProviderExtension2))
- return ((IInformationProviderExtension2)fHover).getInformationPresenterControlCreator();
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java
deleted file mode 100644
index add3a5af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControlExtension2;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.CompositeRuler;
-import org.eclipse.jface.text.source.IAnnotationAccess;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationPresentation;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.ImageUtilities;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaMarkerAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitDocumentProvider.ProblemAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- *
- *
- *
- */
-public class JavaExpandHover extends AnnotationExpandHover {
-
- /** Id of the no breakpoint fake annotation */
- public static final String NO_BREAKPOINT_ANNOTATION= "org.eclipse.wst.jsdt.internal.ui.NoBreakpointAnnotation"; //$NON-NLS-1$
-
- private static class NoBreakpointAnnotation extends Annotation implements IAnnotationPresentation {
-
- public NoBreakpointAnnotation() {
- super(NO_BREAKPOINT_ANNOTATION, false, JavaHoverMessages.NoBreakpointAnnotation_addBreakpoint);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationPresentation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle)
- */
- public void paint(GC gc, Canvas canvas, Rectangle bounds) {
- // draw affordance so the user know she can click here to get a breakpoint
- Image fImage= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
- ImageUtilities.drawImage(fImage, gc, canvas, bounds, SWT.CENTER);
- }
-
- /*
- * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
- */
- public int getLayer() {
- return IAnnotationPresentation.DEFAULT_LAYER;
- }
- }
-
- private AnnotationPreferenceLookup fLookup= new AnnotationPreferenceLookup();
- private IPreferenceStore fStore= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
-
- public JavaExpandHover(CompositeRuler ruler, IAnnotationAccess access, IDoubleClickListener doubleClickListener) {
- super(ruler, access, doubleClickListener);
- }
-
- /*
- * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getHoverInfoForLine(org.eclipse.jface.text.source.ISourceViewer, int)
- */
- protected Object getHoverInfoForLine(final ISourceViewer viewer, final int line) {
- final boolean showTemporaryProblems= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
- IAnnotationModel model= viewer.getAnnotationModel();
- IDocument document= viewer.getDocument();
-
- if (model == null)
- return null;
-
- List exact= new ArrayList();
- HashMap messagesAtPosition= new HashMap();
-
- Iterator e= model.getAnnotationIterator();
- while (e.hasNext()) {
- Annotation annotation= (Annotation) e.next();
-
- if (fAnnotationAccess instanceof IAnnotationAccessExtension)
- if (!((IAnnotationAccessExtension)fAnnotationAccess).isPaintable(annotation))
- continue;
-
- if (annotation instanceof IJavaAnnotation && !isIncluded((IJavaAnnotation)annotation, showTemporaryProblems))
- continue;
-
- AnnotationPreference pref= fLookup.getAnnotationPreference(annotation);
- if (pref != null) {
- String key= pref.getVerticalRulerPreferenceKey();
- if (key != null && !fStore.getBoolean(key))
- continue;
- }
-
- Position position= model.getPosition(annotation);
- if (position == null)
- continue;
-
- if (compareRulerLine(position, document, line) == 1) {
-
- if (isDuplicateMessage(messagesAtPosition, position, annotation.getText()))
- continue;
-
- exact.add(annotation);
- }
- }
-
- sort(exact, model);
-
- if (exact.size() > 0)
- setLastRulerMouseLocation(viewer, line);
-
- if (exact.size() > 0) {
- Annotation first= (Annotation) exact.get(0);
- if (!isBreakpointAnnotation(first))
- exact.add(0, new NoBreakpointAnnotation());
- }
-
- if (exact.size() <= 1)
- return null;
-
- AnnotationHoverInput input= new AnnotationHoverInput();
- input.fAnnotations= (Annotation[]) exact.toArray(new Annotation[0]);
- input.fViewer= viewer;
- input.fRulerInfo= fCompositeRuler;
- input.fAnnotationListener= fgListener;
- input.fDoubleClickListener= fDblClickListener;
- input.redoAction= new AnnotationExpansionControl.ICallback() {
-
- public void run(IInformationControlExtension2 control) {
- control.setInput(getHoverInfoForLine(viewer, line));
- }
-
- };
- input.model= model;
-
- return input;
- }
-
- private boolean isIncluded(IJavaAnnotation annotation, boolean showTemporaryProblems) {
-
- // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138601
- if (annotation instanceof ProblemAnnotation && JavaMarkerAnnotation.TASK_ANNOTATION_TYPE.equals(annotation.getType()))
- return false;
-
- if (!annotation.isProblem())
- return true;
-
- if (annotation.isMarkedDeleted() && !annotation.hasOverlay())
- return true;
-
- if (annotation.hasOverlay() && !annotation.isMarkedDeleted())
- return true;
-
-
- if (annotation.hasOverlay())
- return (!isIncluded(annotation.getOverlay(), showTemporaryProblems));
-
- return showTemporaryProblems && (JavaCorrectionProcessor.hasCorrections((Annotation) annotation) || (annotation instanceof IQuickFixableAnnotation && ((IQuickFixableAnnotation) annotation).isQuickFixableStateSet() && ((IQuickFixableAnnotation) annotation).isQuickFixable()));
- }
-
- /*
- * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getOrder(org.eclipse.jface.text.source.Annotation)
- */
- protected int getOrder(Annotation annotation) {
- if (isBreakpointAnnotation(annotation))
- return 1000;
- else
- return super.getOrder(annotation);
- }
-
- private boolean isBreakpointAnnotation(Annotation a) {
- if (a instanceof JavaMarkerAnnotation) {
- JavaMarkerAnnotation jma= (JavaMarkerAnnotation) a;
- // HACK to get breakpoints to show up first
- return jma.getType().equals("org.eclipse.debug.core.breakpoint"); //$NON-NLS-1$
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.java
deleted file mode 100644
index 9675337c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class JavaHoverMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaHoverMessages.class.getName();
-
- private JavaHoverMessages() {
- // Do not instantiate
- }
-
- public static String JavadocHover_noAttachments;
- public static String JavadocHover_noAttachedJavadoc;
- public static String JavadocHover_noAttachedSource;
- public static String JavadocHover_noInformation;
- public static String JavadocHover_error_gettingJavadoc;
- public static String JavaTextHover_createTextHover;
- public static String NoBreakpointAnnotation_addBreakpoint;
- public static String NLSStringHover_NLSStringHover_missingKeyWarning;
- public static String NLSStringHover_NLSStringHover_PropertiesFileNotDetectedWarning;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaHoverMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties
deleted file mode 100644
index ea690479..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties
+++ /dev/null
@@ -1,23 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-JavaTextHover_createTextHover= Could not create javaScript text hover
-
-NoBreakpointAnnotation_addBreakpoint= Add a breakpoint
-
-NLSStringHover_NLSStringHover_PropertiesFileNotDetectedWarning= The properties file could not be detected
-NLSStringHover_NLSStringHover_missingKeyWarning= <b>Warning:</b> The key is missing!
-
-JavadocHover_noAttachments= <em>Note: This element neither has attached source nor attached JSDoc and hence no JSDoc could be found.</em>
-JavadocHover_noAttachedSource= <em>Note: This element has no attached source and the JSDoc could not be found in the attached JSDoc.</em>
-JavadocHover_noAttachedJavadoc= <em>Note: This element has no attached JSDoc and the JSDoc could not be found in the attached source.</em>
-JavadocHover_noInformation= <em>Note: The JSDoc for this element could neither be found in the attached source nor the attached JSDoc.</em>
-JavadocHover_error_gettingJavadoc= <em>Note: An exception occurred while getting the JSDoc. See log for details.</em>
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaInformationProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaInformationProvider.java
deleted file mode 100644
index c458c771..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaInformationProvider.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.BrowserInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.information.IInformationProvider;
-import org.eclipse.jface.text.information.IInformationProviderExtension2;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IPerspectiveDescriptor;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-
-
-public class JavaInformationProvider implements IInformationProvider, IInformationProviderExtension2 {
-
-
- /**
- * Control creator.
- *
- *
- */
- private static final class ControlCreator extends AbstractReusableInformationControlCreator {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractReusableInformationControlCreator#doCreateInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl doCreateInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE | SWT.TOOL;
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- if (BrowserInformationControl.isAvailable(parent))
- return new BrowserInformationControl(parent, shellStyle, style);
- else
- return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
- }
- }
-
-
- class EditorWatcher implements IPartListener {
-
- /**
- * @see IPartListener#partOpened(IWorkbenchPart)
- */
- public void partOpened(IWorkbenchPart part) {
- }
-
- /**
- * @see IPartListener#partDeactivated(IWorkbenchPart)
- */
- public void partDeactivated(IWorkbenchPart part) {
- }
-
- /**
- * @see IPartListener#partClosed(IWorkbenchPart)
- */
- public void partClosed(IWorkbenchPart part) {
- if (part == fEditor) {
- fEditor.getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener);
- fPartListener= null;
- }
- }
-
- /**
- * @see IPartListener#partActivated(IWorkbenchPart)
- */
- public void partActivated(IWorkbenchPart part) {
- update();
- }
-
- public void partBroughtToTop(IWorkbenchPart part) {
- update();
- }
- }
-
- protected IEditorPart fEditor;
- protected IPartListener fPartListener;
-
- protected String fCurrentPerspective;
- protected IJavaEditorTextHover fImplementation;
-
- /**
- * The presentation control creator.
- *
- *
- */
- private IInformationControlCreator fPresenterControlCreator;
-
-
-
- public JavaInformationProvider(IEditorPart editor) {
-
- fEditor= editor;
-
- if (fEditor != null) {
-
- fPartListener= new EditorWatcher();
- IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow();
- window.getPartService().addPartListener(fPartListener);
-
- update();
- }
- }
-
- protected void update() {
-
- IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow();
- IWorkbenchPage page= window.getActivePage();
- if (page != null) {
-
- IPerspectiveDescriptor perspective= page.getPerspective();
- if (perspective != null) {
- String perspectiveId= perspective.getId();
-
- if (fCurrentPerspective == null || fCurrentPerspective != perspectiveId) {
- fCurrentPerspective= perspectiveId;
-
- fImplementation= new JavaTypeHover();
- fImplementation.setEditor(fEditor);
- }
- }
- }
- }
-
- /*
- * @see IInformationProvider#getSubject(ITextViewer, int)
- */
- public IRegion getSubject(ITextViewer textViewer, int offset) {
-
- if (textViewer != null)
- return JavaWordFinder.findWord(textViewer.getDocument(), offset);
-
- return null;
- }
-
- /*
- * @see IInformationProvider#getInformation(ITextViewer, IRegion)
- */
- public String getInformation(ITextViewer textViewer, IRegion subject) {
- if (fImplementation != null) {
- String s= fImplementation.getHoverInfo(textViewer, subject);
- if (s != null && s.trim().length() > 0) {
- return s;
- }
- }
-
- return null;
- }
-
- /*
- * @see IInformationProviderExtension2#getInformationPresenterControlCreator()
- *
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- if (fPresenterControlCreator == null)
- fPresenterControlCreator= new ControlCreator();
- return fPresenterControlCreator;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaSourceHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaSourceHover.java
deleted file mode 100644
index d16345b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaSourceHover.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.io.IOException;
-
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.ITextHoverExtension;
-import org.eclipse.jface.text.information.IInformationProviderExtension2;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.part.IWorkbenchPartOrientation;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCodeReader;
-
-/**
- * Provides source as hover info for Java elements.
- */
-public class JavaSourceHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 {
-
- /*
- * @see JavaElementHover
- */
- protected String getHoverInfo(IJavaScriptElement[] result) {
- int nResults= result.length;
-
- if (nResults > 1)
- return null;
-
- IJavaScriptElement curr= result[0];
- if ((curr instanceof IMember || curr instanceof ILocalVariable) && curr instanceof ISourceReference) {
- try {
- String source= ((ISourceReference) curr).getSource();
- if (source == null)
- return null;
-
- source= removeLeadingComments(source);
- String delim= StubUtility.getLineDelimiterUsed(result[0]);
-
- String[] sourceLines= Strings.convertIntoLines(source);
- String firstLine= sourceLines[0];
- if (!Character.isWhitespace(firstLine.charAt(0)))
- sourceLines[0]= ""; //$NON-NLS-1$
- Strings.trimIndentation(sourceLines, curr.getJavaScriptProject());
-
- if (!Character.isWhitespace(firstLine.charAt(0)))
- sourceLines[0]= firstLine;
-
- source= Strings.concatenate(sourceLines, delim);
-
- return source;
-
- } catch (JavaScriptModelException ex) {
- }
- }
-
- return null;
- }
-
- private String removeLeadingComments(String source) {
- JavaCodeReader reader= new JavaCodeReader();
- IDocument document= new Document(source);
- int i;
- try {
- reader.configureForwardReader(document, 0, document.getLength(), true, false);
- int c= reader.read();
- while (c != -1 && (c == '\r' || c == '\n')) {
- c= reader.read();
- }
- i= reader.getOffset();
- reader.close();
- } catch (IOException ex) {
- i= 0;
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException ex) {
- JavaScriptPlugin.log(ex);
- }
- }
-
- if (i < 0)
- return source;
- return source.substring(i);
- }
-
- /*
- * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator()
- *
- */
- public IInformationControlCreator getHoverControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- IEditorPart editor= getEditor();
- int shellStyle= SWT.TOOL | SWT.NO_TRIM;
- if (editor instanceof IWorkbenchPartOrientation)
- shellStyle |= ((IWorkbenchPartOrientation)editor).getOrientation();
- return new SourceViewerInformationControl(parent, shellStyle, SWT.NONE, EditorsUI.getTooltipAffordanceString());
- }
- };
- }
-
- /*
- * @see IInformationProviderExtension2#getInformationPresenterControlCreator()
- *
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- int shellStyle= SWT.RESIZE | SWT.TOOL;
- IEditorPart editor= getEditor();
- if (editor instanceof IWorkbenchPartOrientation)
- shellStyle |= ((IWorkbenchPartOrientation)editor).getOrientation();
- return new SourceViewerInformationControl(parent, shellStyle, style);
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaTypeHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaTypeHover.java
deleted file mode 100644
index 75b74149..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaTypeHover.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover;
-
-
-public class JavaTypeHover implements IJavaEditorTextHover {
-
- private IJavaEditorTextHover fProblemHover;
- private IJavaEditorTextHover fJavadocHover;
-
- public JavaTypeHover() {
- fProblemHover= new ProblemHover();
- fJavadocHover= new JavadocHover();
- }
-
- /*
- * @see IJavaEditorTextHover#setEditor(IEditorPart)
- */
- public void setEditor(IEditorPart editor) {
- fProblemHover.setEditor(editor);
- fJavadocHover.setEditor(editor);
- }
-
- /*
- * @see ITextHover#getHoverRegion(ITextViewer, int)
- */
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- return fJavadocHover.getHoverRegion(textViewer, offset);
- }
-
- /*
- * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- String hoverInfo= fProblemHover.getHoverInfo(textViewer, hoverRegion);
- if (hoverInfo != null)
- return hoverInfo;
-
- return fJavadocHover.getHoverInfo(textViewer, hoverRegion);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java
deleted file mode 100644
index 825acae7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.io.Reader;
-import java.io.StringReader;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.BrowserInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IInformationControlExtension4;
-import org.eclipse.jface.text.ITextHoverExtension;
-import org.eclipse.jface.text.information.IInformationProviderExtension2;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JSdocContentAccess;
-
-/**
- * Provides Javadoc as hover info for Java elements.
- *
- *
- */
-public class JavadocHover extends AbstractJavaEditorTextHover implements IInformationProviderExtension2, ITextHoverExtension {
-
-
- /**
- * Presenter control creator.
- *
- *
- */
- private static final class PresenterControlCreator extends AbstractReusableInformationControlCreator {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractReusableInformationControlCreator#doCreateInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl doCreateInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE | SWT.TOOL;
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- if (BrowserInformationControl.isAvailable(parent))
- return new BrowserInformationControl(parent, shellStyle, style);
- else
- return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
- }
- }
-
-
- /**
- * Hover control creator.
- *
- *
- */
- private static final class HoverControlCreator extends AbstractReusableInformationControlCreator {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractReusableInformationControlCreator#doCreateInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl doCreateInformationControl(Shell parent) {
- if (BrowserInformationControl.isAvailable(parent))
- return new BrowserInformationControl(parent, SWT.TOOL | SWT.NO_TRIM, SWT.NONE, EditorsUI.getTooltipAffordanceString());
- else
- return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true), EditorsUI.getTooltipAffordanceString());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractReusableInformationControlCreator#canReuse(org.eclipse.jface.text.IInformationControl)
- */
- public boolean canReuse(IInformationControl control) {
- if (!super.canReuse(control))
- return false;
-
- if (control instanceof IInformationControlExtension4)
- ((IInformationControlExtension4)control).setStatusText(EditorsUI.getTooltipAffordanceString());
-
- return true;
- }
- }
-
- private final long LABEL_FLAGS= JavaScriptElementLabels.ALL_FULLY_QUALIFIED
- | JavaScriptElementLabels.M_PRE_RETURNTYPE | JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_EXCEPTIONS
- | JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE | JavaScriptElementLabels.M_PRE_TYPE_PARAMETERS | JavaScriptElementLabels.T_TYPE_PARAMETERS
- | JavaScriptElementLabels.USE_RESOLVED;
- private final long LOCAL_VARIABLE_FLAGS= LABEL_FLAGS & ~JavaScriptElementLabels.F_FULLY_QUALIFIED | JavaScriptElementLabels.F_POST_QUALIFIED;
-
-
- /**
- * The hover control creator.
- *
- *
- */
- private IInformationControlCreator fHoverControlCreator;
- /**
- * The presentation control creator.
- *
- *
- */
- private IInformationControlCreator fPresenterControlCreator;
-
-
- /*
- * @see IInformationProviderExtension2#getInformationPresenterControlCreator()
- *
- */
- public IInformationControlCreator getInformationPresenterControlCreator() {
- if (fPresenterControlCreator == null)
- fPresenterControlCreator= new PresenterControlCreator();
- return fPresenterControlCreator;
- }
-
- /*
- * @see ITextHoverExtension#getHoverControlCreator()
- *
- */
- public IInformationControlCreator getHoverControlCreator() {
- if (fHoverControlCreator == null)
- fHoverControlCreator= new HoverControlCreator();
- return fHoverControlCreator;
- }
-
- /*
- * @see JavaElementHover
- */
- protected String getHoverInfo(IJavaScriptElement[] result) {
-
- StringBuffer buffer= new StringBuffer();
- int nResults= result.length;
- if (nResults == 0)
- return null;
-
- boolean hasContents= false;
- if (nResults > 1) {
-
- for (int i= 0; i < result.length; i++) {
- HTMLPrinter.startBulletList(buffer);
- IJavaScriptElement curr= result[i];
- if (curr != null && (curr instanceof IMember || curr.getElementType() == IJavaScriptElement.LOCAL_VARIABLE)) {
- HTMLPrinter.addBullet(buffer, getInfoText(curr));
- hasContents= true;
- }
- HTMLPrinter.endBulletList(buffer);
- }
-
- } else {
-
- IJavaScriptElement curr= result[0];
- if (curr instanceof IMember) {
- IMember member= (IMember) curr;
- HTMLPrinter.addSmallHeader(buffer, getInfoText(member));
- Reader reader;
- try {
- reader= JSdocContentAccess.getHTMLContentReader(member, true, true);
-
- // Provide hint why there's no Javadoc
- if (reader == null && member.isBinary()) {
- boolean hasAttachedJavadoc= JavaDocLocations.getJavadocBaseLocation(member) != null;
- IPackageFragmentRoot root= (IPackageFragmentRoot)member.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- boolean hasAttachedSource= root != null && root.getSourceAttachmentPath() != null;
- IOpenable openable= member.getOpenable();
- boolean hasSource= openable.getBuffer() != null;
-
- if (!hasAttachedSource && !hasAttachedJavadoc)
- reader= new StringReader(JavaHoverMessages.JavadocHover_noAttachments);
- else if (!hasAttachedJavadoc && !hasSource)
- reader= new StringReader(JavaHoverMessages.JavadocHover_noAttachedJavadoc);
- else if (!hasAttachedSource)
- reader= new StringReader(JavaHoverMessages.JavadocHover_noAttachedSource);
- else if (!hasSource)
- reader= new StringReader(JavaHoverMessages.JavadocHover_noInformation);
- }
-
- } catch (JavaScriptModelException ex) {
- reader= new StringReader(JavaHoverMessages.JavadocHover_error_gettingJavadoc);
- JavaScriptPlugin.log(ex.getStatus());
- }
-
- if (reader != null) {
- HTMLPrinter.addParagraph(buffer, reader);
- }
- hasContents= true;
- } else if (curr != null && curr.getElementType() == IJavaScriptElement.LOCAL_VARIABLE) {
- HTMLPrinter.addSmallHeader(buffer, getInfoText(curr));
- hasContents= true;
- }
- }
-
- if (!hasContents)
- return null;
-
- if (buffer.length() > 0) {
- HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-
- return null;
- }
-
- private String getInfoText(IJavaScriptElement member) {
- long flags= member.getElementType() == IJavaScriptElement.LOCAL_VARIABLE ? LOCAL_VARIABLE_FLAGS : LABEL_FLAGS;
- String label= JavaScriptElementLabels.getElementLabel(member, flags);
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < label.length(); i++) {
- char ch= label.charAt(i);
- if (ch == '<') {
- buf.append("&lt;"); //$NON-NLS-1$
- } else if (ch == '>') {
- buf.append("&gt;"); //$NON-NLS-1$
- } else {
- buf.append(ch);
- }
- }
- return buf.toString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/NLSStringHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/NLSStringHover.java
deleted file mode 100644
index 6288c92f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/NLSStringHover.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import java.util.Properties;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.QualifiedName;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.core.dom.StringLiteral;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.AccessorClassReference;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSHintHelper;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ClassFileEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/**
- * Provides externalized string as hover info for NLS key.
- *
- *
- */
-public class NLSStringHover extends AbstractJavaEditorTextHover {
-
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int)
- */
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (!(getEditor() instanceof JavaEditor))
- return null;
-
- IJavaScriptElement je= getEditorInputJavaElement();
- if (je == null)
- return null;
-
- // Never wait for an AST in UI thread.
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(je, ASTProvider.WAIT_NO, null);
- if (ast == null)
- return null;
-
- ASTNode node= NodeFinder.perform(ast, offset, 1);
- if (node instanceof StringLiteral) {
- StringLiteral stringLiteral= (StringLiteral)node;
- return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
- } else if (node instanceof SimpleName) {
- SimpleName simpleName= (SimpleName)node;
- return new Region(simpleName.getStartPosition(), simpleName.getLength());
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
- */
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- if (!(getEditor() instanceof JavaEditor))
- return null;
-
- IJavaScriptElement je= getEditorInputJavaElement();
- if (je == null)
- return null;
-
- JavaScriptUnit ast= JavaScriptPlugin.getDefault().getASTProvider().getAST(je, ASTProvider.WAIT_ACTIVE_ONLY, null);
- if (ast == null)
- return null;
-
- ASTNode node= NodeFinder.perform(ast, hoverRegion.getOffset(), hoverRegion.getLength());
- if (!(node instanceof StringLiteral) && !(node instanceof SimpleName))
- return null;
-
- if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
- return null;
-
- AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, hoverRegion);
- if (ref == null)
- return null;
-
- IStorage propertiesFile;
- try {
- propertiesFile= NLSHintHelper.getResourceBundle(je.getJavaScriptProject(), ref);
- if (propertiesFile == null)
- return toHtml(JavaHoverMessages.NLSStringHover_NLSStringHover_PropertiesFileNotDetectedWarning, ""); //$NON-NLS-1$
- } catch (JavaScriptModelException ex) {
- return null;
- }
-
- final String propertiesFileName= propertiesFile.getName();
- Properties properties= NLSHintHelper.getProperties(propertiesFile);
- if (properties == null)
- return null;
- if (properties.isEmpty())
- return toHtml(propertiesFileName, JavaHoverMessages.NLSStringHover_NLSStringHover_missingKeyWarning);
-
- String identifier= null;
- if (node instanceof StringLiteral) {
- identifier= ((StringLiteral)node).getLiteralValue();
- } else {
- identifier= ((SimpleName)node).getIdentifier();
- }
- if (identifier == null)
- return null;
-
- String value= properties.getProperty(identifier, null);
- if (value != null)
- value= HTMLPrinter.convertToHTMLContent(value);
- else
- value= JavaHoverMessages.NLSStringHover_NLSStringHover_missingKeyWarning;
-
- return toHtml(propertiesFileName, value);
- }
-
- private String toHtml(String header, String string) {
-
- StringBuffer buffer= new StringBuffer();
-
- HTMLPrinter.addSmallHeader(buffer, header);
- HTMLPrinter.addParagraph(buffer, string);
- HTMLPrinter.insertPageProlog(buffer, 0);
- HTMLPrinter.addPageEpilog(buffer);
- return buffer.toString();
- }
-
- private IJavaScriptElement getEditorInputJavaElement() {
- if (getEditor() instanceof CompilationUnitEditor)
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditor().getEditorInput());
- else if (getEditor() instanceof ClassFileEditor) {
- IEditorInput editorInput= getEditor().getEditorInput();
- if (editorInput instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)editorInput).getClassFile();
-
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java
deleted file mode 100644
index 427240bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-/**
- * This annotation hover shows the description of the
- * selected java annotation.
- *
- * XXX: Currently this problem hover only works for
- * Java problems.
- * see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62081
- *
- *
- */
-public class ProblemHover extends AbstractAnnotationHover {
-
- public ProblemHover() {
- super(false);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/SourceViewerInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/SourceViewerInformationControl.java
deleted file mode 100644
index 89898ab4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/SourceViewerInformationControl.java
+++ /dev/null
@@ -1,458 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.java.hover;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlExtension;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaSourceViewer;
-import org.eclipse.wst.jsdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Source viewer based implementation of <code>IInformationControl</code>.
- * Displays information in a source viewer.
- *
- *
- */
-public class SourceViewerInformationControl implements IInformationControl, IInformationControlExtension, DisposeListener {
-
- /** Border thickness in pixels. */
- private static final int BORDER= 1;
- /** The control's shell */
- private Shell fShell;
- /** The control's text widget */
- private StyledText fText;
- /** The control's source viewer */
- private SourceViewer fViewer;
- /**
- * The optional status field.
- *
- *
- */
- private Label fStatusField;
- /**
- * The separator for the optional status field.
- *
- *
- */
- private Label fSeparator;
- /**
- * The font of the optional status text label.
- *
- *
- */
- private Font fStatusTextFont;
- /**
- * The width size constraint.
- *
- */
- private int fMaxWidth= SWT.DEFAULT;
- /**
- * The height size constraint.
- *
- */
- private int fMaxHeight= SWT.DEFAULT;
-
- private Color fBackgroundColor;
- private boolean fIsSystemBackgroundColor= true;
-
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param style the additional styles for the styled text widget
- */
- public SourceViewerInformationControl(Shell parent, int shellStyle, int style) {
- this(parent, shellStyle, style, null);
- }
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param shellStyle the additional styles for the shell
- * @param style the additional styles for the styled text widget
- * @param statusFieldText the text to be used in the optional status field
- * or <code>null</code> if the status field should be hidden
- *
- */
- public SourceViewerInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) {
- GridLayout layout;
- GridData gd;
-
- fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
- Display display= fShell.getDisplay();
- fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
-
- initializeColors();
-
- Composite composite= fShell;
- layout= new GridLayout(1, false);
- int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
- layout.marginHeight= border;
- layout.marginWidth= border;
- composite.setLayout(layout);
- gd= new GridData(GridData.FILL_HORIZONTAL);
- composite.setLayoutData(gd);
-
- if (statusFieldText != null) {
- composite= new Composite(composite, SWT.NONE);
- layout= new GridLayout(1, false);
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- composite.setLayout(layout);
- gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
- composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- composite.setBackground(fBackgroundColor);
- }
-
- // Source viewer
- IPreferenceStore store= JavaScriptPlugin.getDefault().getCombinedPreferenceStore();
- fViewer= new JavaSourceViewer(composite, null, null, false, style, store);
- fViewer.configure(new SimpleJavaSourceViewerConfiguration(JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager(), store, null, IJavaScriptPartitions.JAVA_PARTITIONING, false));
- fViewer.setEditable(false);
-
- fText= fViewer.getTextWidget();
- gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
- fText.setLayoutData(gd);
- fText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- fText.setBackground(fBackgroundColor);
-
- initializeFont();
-
- fText.addKeyListener(new KeyListener() {
-
- public void keyPressed(KeyEvent e) {
- if (e.character == 0x1B) // ESC
- fShell.dispose();
- }
-
- public void keyReleased(KeyEvent e) {}
- });
-
- // Status field
- if (statusFieldText != null) {
-
- // Horizontal separator line
- fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
- fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // Status field label
- fStatusField= new Label(composite, SWT.RIGHT);
- fStatusField.setText(statusFieldText);
- Font font= fStatusField.getFont();
- FontData[] fontDatas= font.getFontData();
- for (int i= 0; i < fontDatas.length; i++)
- fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
- fStatusTextFont= new Font(fStatusField.getDisplay(), fontDatas);
- fStatusField.setFont(fStatusTextFont);
- GridData gd2= new GridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
- fStatusField.setLayoutData(gd2);
-
- // Regarding the color see bug 41128
- fStatusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
- fStatusField.setBackground(fBackgroundColor);
- }
-
- addDisposeListener(this);
- }
-
- private void initializeColors() {
- RGB bgRGB= getHoverBackgroundColorRGB();
- if (bgRGB != null) {
- fBackgroundColor= new Color(fShell.getDisplay(), bgRGB);
- fIsSystemBackgroundColor= false;
- } else {
- fBackgroundColor= fShell.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- fIsSystemBackgroundColor= true;
- }
- }
-
- private RGB getHoverBackgroundColorRGB() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- return store.getBoolean(PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT)
- ? null
- : PreferenceConverter.getColor(store, PreferenceConstants.EDITOR_SOURCE_HOVER_BACKGROUND_COLOR);
- }
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param style the additional styles for the styled text widget
- */
- public SourceViewerInformationControl(Shell parent,int style) {
- this(parent, SWT.NO_TRIM | SWT.TOOL, style);
- }
-
- /**
- * Creates a default information control with the given shell as parent. The given
- * information presenter is used to process the information to be displayed. The given
- * styles are applied to the created styled text widget.
- *
- * @param parent the parent shell
- * @param style the additional styles for the styled text widget
- * @param statusFieldText the text to be used in the optional status field
- * or <code>null</code> if the status field should be hidden
- *
- */
- public SourceViewerInformationControl(Shell parent,int style, String statusFieldText) {
- this(parent, SWT.NO_TRIM | SWT.TOOL, style, statusFieldText);
- }
-
- /**
- * Creates a default information control with the given shell as parent.
- * No information presenter is used to process the information
- * to be displayed. No additional styles are applied to the styled text widget.
- *
- * @param parent the parent shell
- */
- public SourceViewerInformationControl(Shell parent) {
- this(parent, SWT.NONE);
- }
-
- /**
- * Creates a default information control with the given shell as parent.
- * No information presenter is used to process the information
- * to be displayed. No additional styles are applied to the styled text widget.
- *
- * @param parent the parent shell
- * @param statusFieldText the text to be used in the optional status field
- * or <code>null</code> if the status field should be hidden
- *
- */
- public SourceViewerInformationControl(Shell parent, String statusFieldText) {
- this(parent, SWT.NONE, statusFieldText);
- }
-
- /**
- * Initialize the font to the Java editor font.
- *
- *
- */
- private void initializeFont() {
- Font font= JFaceResources.getFont("org.eclipse.wst.jsdt.ui.editors.textfont"); //$NON-NLS-1$
- StyledText styledText= getViewer().getTextWidget();
- styledText.setFont(font);
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object)
- */
- public void setInput(Object input) {
- if (input instanceof String)
- setInformation((String)input);
- else
- setInformation(null);
- }
-
- /*
- * @see IInformationControl#setInformation(String)
- */
- public void setInformation(String content) {
- if (content == null) {
- fViewer.setInput(null);
- return;
- }
-
- IDocument doc= new Document(content);
- JavaScriptPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(doc, IJavaScriptPartitions.JAVA_PARTITIONING);
- fViewer.setInput(doc);
- }
-
- /*
- * @see IInformationControl#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- fShell.setVisible(visible);
- }
-
- /**
- * {@inheritDoc}
- *
- */
- public void widgetDisposed(DisposeEvent event) {
- if (fStatusTextFont != null && !fStatusTextFont.isDisposed())
- fStatusTextFont.dispose();
-
- fStatusTextFont= null;
- fShell= null;
- fText= null;
- }
-
- /**
- * {@inheritDoc}
- */
- public final void dispose() {
- if (!fIsSystemBackgroundColor)
- fBackgroundColor.dispose();
- if (fShell != null && !fShell.isDisposed())
- fShell.dispose();
- else
- widgetDisposed(null);
- }
-
- /*
- * @see IInformationControl#setSize(int, int)
- */
- public void setSize(int width, int height) {
-
- if (fStatusField != null) {
- GridData gd= (GridData)fViewer.getTextWidget().getLayoutData();
- Point statusSize= fStatusField.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
- Point separatorSize= fSeparator.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
- gd.heightHint= height - statusSize.y - separatorSize.y;
- }
- fShell.setSize(width, height);
-
- if (fStatusField != null)
- fShell.pack(true);
- }
-
- /*
- * @see IInformationControl#setLocation(Point)
- */
- public void setLocation(Point location) {
- fShell.setLocation(location);
- }
-
- /*
- * @see IInformationControl#setSizeConstraints(int, int)
- */
- public void setSizeConstraints(int maxWidth, int maxHeight) {
- fMaxWidth= maxWidth;
- fMaxHeight= maxHeight;
- }
-
- /*
- * @see IInformationControl#computeSizeHint()
- */
- public Point computeSizeHint() {
- // compute the preferred size
- int x= SWT.DEFAULT;
- int y= SWT.DEFAULT;
- Point size= fShell.computeSize(x, y);
- if (size.x > fMaxWidth)
- x= fMaxWidth;
- if (size.y > fMaxHeight)
- y= fMaxHeight;
-
- // recompute using the constraints if the preferred size is larger than the constraints
- if (x != SWT.DEFAULT || y != SWT.DEFAULT)
- size= fShell.computeSize(x, y, false);
-
- return size;
- }
-
- /*
- * @see IInformationControl#addDisposeListener(DisposeListener)
- */
- public void addDisposeListener(DisposeListener listener) {
- fShell.addDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#removeDisposeListener(DisposeListener)
- */
- public void removeDisposeListener(DisposeListener listener) {
- fShell.removeDisposeListener(listener);
- }
-
- /*
- * @see IInformationControl#setForegroundColor(Color)
- */
- public void setForegroundColor(Color foreground) {
- fText.setForeground(foreground);
- }
-
- /*
- * @see IInformationControl#setBackgroundColor(Color)
- */
- public void setBackgroundColor(Color background) {
- fText.setBackground(background);
- }
-
- /*
- * @see IInformationControl#isFocusControl()
- */
- public boolean isFocusControl() {
- return fText.isFocusControl();
- }
-
- /*
- * @see IInformationControl#setFocus()
- */
- public void setFocus() {
- fShell.forceFocus();
- fText.setFocus();
- }
-
- /*
- * @see IInformationControl#addFocusListener(FocusListener)
- */
- public void addFocusListener(FocusListener listener) {
- fText.addFocusListener(listener);
- }
-
- /*
- * @see IInformationControl#removeFocusListener(FocusListener)
- */
- public void removeFocusListener(FocusListener listener) {
- fText.removeFocusListener(listener);
- }
-
- /*
- * @see IInformationControlExtension#hasContents()
- */
- public boolean hasContents() {
- return fText.getCharCount() > 0;
- }
-
- protected ISourceViewer getViewer() {
- return fViewer;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/HTMLTagCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/HTMLTagCompletionProposalComputer.java
deleted file mode 100644
index c22b54d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/HTMLTagCompletionProposalComputer.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.wst.jsdt.ui.text.java.IJavadocCompletionProcessor;
-
-/**
- * (renamed from JavaDocCompletionEvaluator which got introduced in 2.0)
- */
-public class HTMLTagCompletionProposalComputer implements IJavaCompletionProposalComputer {
-
- private static final String[] fgHTMLProposals= new String[IHtmlTagConstants.HTML_GENERAL_TAGS.length * 2];
- {
- String tag= null;
-
- int index= 0;
- int offset= 0;
-
- while (index < fgHTMLProposals.length) {
-
- tag= IHtmlTagConstants.HTML_GENERAL_TAGS[offset];
- fgHTMLProposals[index++]= IHtmlTagConstants.HTML_TAG_PREFIX + tag + IHtmlTagConstants.HTML_TAG_POSTFIX;
- fgHTMLProposals[index++]= IHtmlTagConstants.HTML_CLOSE_PREFIX + tag + IHtmlTagConstants.HTML_TAG_POSTFIX;
- offset++;
- }
- }
-
- private IDocument fDocument;
- private int fCurrentPos;
- private int fCurrentLength;
- private String fErrorMessage;
- private List fResult;
-
- private boolean fRestrictToMatchingCase;
-
- public HTMLTagCompletionProposalComputer() {
- }
-
- private static boolean isWordPart(char ch) {
- return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/');
- }
-
- private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) {
- int currPos= pos - 1;
- if (currPos > lineBeginPos) {
- try {
- while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) {
- currPos--;
- }
- return currPos;
- } catch (BadLocationException e) {
- // ignore
- }
- }
- return pos;
- }
-
- private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException {
- int curr= pos;
- while (curr < end && (doc.getChar(curr) != endChar)) {
- curr++;
- }
- if (curr < end) {
- return curr + 1;
- }
- return pos;
- }
-
- private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) {
- if (oldText.length() == 0 || oldText.equals(newText)) {
- return pos;
- }
-
- try {
- IRegion lineInfo= doc.getLineInformationOfOffset(pos);
- int end= lineInfo.getOffset() + lineInfo.getLength();
-
- // for html, search the tag end character
- return findClosingCharacter(doc, pos, end, '>');
- } catch (BadLocationException e) {
- // ignore
- }
- return pos;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#computeCompletionProposals(org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- *
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (!(context instanceof JavadocContentAssistInvocationContext))
- return Collections.EMPTY_LIST;
-
- JavadocContentAssistInvocationContext docContext= (JavadocContentAssistInvocationContext) context;
- int flags= docContext.getFlags();
- fCurrentPos= docContext.getInvocationOffset();
- fCurrentLength= docContext.getSelectionLength();
- fRestrictToMatchingCase= (flags & IJavadocCompletionProcessor.RESTRICT_TO_MATCHING_CASE) != 0;
-
- IJavaScriptUnit cu= docContext.getCompilationUnit();
- if (cu == null)
- return Collections.EMPTY_LIST;
- IEditorInput editorInput= new FileEditorInput((IFile) cu.getResource());
- fDocument= JavaScriptUI.getDocumentProvider().getDocument(editorInput);
- if (fDocument == null) {
- return Collections.EMPTY_LIST;
- }
-
- try {
- fResult= new ArrayList(100);
- evalProposals();
- return fResult;
- } catch (JavaScriptModelException e) {
- fErrorMessage= e.getLocalizedMessage();
- } finally {
- fResult= null;
- }
- return null;
- }
-
- private void evalProposals() throws JavaScriptModelException {
- try {
-
- IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos);
- int lineBeginPos= info.getOffset();
-
- int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos);
- if (word1Begin == fCurrentPos)
- return;
-
- char firstChar= fDocument.getChar(word1Begin);
- if (firstChar == '<') {
- String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin);
- addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG);
- return;
- } else if (!Character.isWhitespace(firstChar)) {
- return;
- }
-
- // TODO really show all tags when there is no prefix?
- // TODO find any unclosed open tag and offer the corresponding close tag
- String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1);
- addAllTags(prefix);
- } catch (BadLocationException e) {
- // ignore
- }
- }
-
- private boolean prefixMatches(String prefix, String proposal) {
- if (fRestrictToMatchingCase) {
- return proposal.startsWith(prefix);
- } else if (proposal.length() >= prefix.length()) {
- return prefix.equalsIgnoreCase(proposal.substring(0, prefix.length()));
- }
- return false;
- }
-
- private void addAllTags(String prefix) {
- String htmlPrefix= "<" + prefix; //$NON-NLS-1$
- for (int i= 0; i < fgHTMLProposals.length; i++) {
- String curr= fgHTMLProposals[i];
- if (prefixMatches(htmlPrefix, curr)) {
- fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), 0));
- }
- }
- }
-
- private void addProposals(String prefix, String[] choices, String imageName) {
- for (int i= 0; i < choices.length; i++) {
- String curr= choices[i];
- if (prefixMatches(prefix, curr)) {
- fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), 0));
- }
- }
- }
-
- private JavaCompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, int severity) {
- int offset= fCurrentPos - oldText.length();
- int length= fCurrentLength + oldText.length();
- if (fCurrentLength == 0)
- length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset;
-
- // bump opening over closing tags
- if (!newText.startsWith(IHtmlTagConstants.HTML_CLOSE_PREFIX))
- severity++;
- JavaCompletionProposal proposal= new JavaCompletionProposal(newText, offset, length, image, labelText, severity, true);
- proposal.setTriggerCharacters( new char[] { '>' });
- return proposal;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#computeContextInformation(org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- *
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return Collections.EMPTY_LIST;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#getErrorMessage()
- *
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionEnded()
- *
- */
- public void sessionEnded() {
- fErrorMessage= null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionStarted()
- *
- */
- public void sessionStarted() {
- fErrorMessage= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java
deleted file mode 100644
index 202c8e83..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-/**
- * Html tag constants.
- *
- *
- */
-public interface IHtmlTagConstants {
-
- /** Html tag close prefix */
- public static final String HTML_CLOSE_PREFIX= "</"; //$NON-NLS-1$
-
- /** Html entity characters */
- public static final char[] HTML_ENTITY_CHARACTERS= new char[] { '<', '>', ' ', '&', '^', '~', '\"' };
-
- /**
- * Html entity start.
- *
- */
- public static final char HTML_ENTITY_START= '&';
- /**
- * Html entity end.
- *
- */
- public static final char HTML_ENTITY_END= ';';
-
- /** Html entity codes */
- public static final String[] HTML_ENTITY_CODES= new String[] { "&lt;", "&gt;", "&nbsp;", "&amp;", "&circ;", "&tilde;", "&quot;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-
- /** Html general tags */
- public static final String[] HTML_GENERAL_TAGS= new String[] { "a", "b", "blockquote", "br", "code", "dd", "dl", "dt", "em", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "i", "li", "nl", "ol", "p", "pre", "q", "strong", "tbody", "td", "th", "tr", "tt", "ul" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$ //$NON-NLS-22$ //$NON-NLS-23$ //$NON-NLS-24$ //$NON-NLS-25$ //$NON-NLS-26$ //$NON-NLS-27$ //$NON-NLS-28$ //$NON-NLS-29$ //$NON-NLS-30$
-
- /** Html tag postfix */
- public static final char HTML_TAG_POSTFIX= '>';
-
- /** Html tag prefix */
- public static final char HTML_TAG_PREFIX= '<';
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java
deleted file mode 100644
index b0da8007..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-/**
- * Javadoc tag constants.
- *
- *
- */
-public interface IJavaDocTagConstants {
-
- /** Javadoc general tags */
- public static final String[] JAVADOC_GENERAL_TAGS= new String[] { "@author", "@deprecated", "@docRoot", "@exception", "@inheritDoc", "@link", "@linkplain", "@param", "@return", "@see", "@serial", "@serialData", "@serialField", "", "@throws", "@value", "@version" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
-
- /** Javadoc link tags */
- public static final String[] JAVADOC_LINK_TAGS= new String[] { "@docRoot", "@inheritDoc", "@link", "@linkplain" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- /** Javadoc parameter tags */
- public static final String[] JAVADOC_PARAM_TAGS= new String[] { "@exception", "@param", "@serialField", "@throws" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- /** Javadoc reference tags */
- public static final String[] JAVADOC_REFERENCE_TAGS= new String[] { "@see" }; //$NON-NLS-1$
-
- /** Javadoc root tags */
- public static final String[] JAVADOC_ROOT_TAGS= new String[] { "@author", "@deprecated", "@return", "@see", "@serial", "@serialData", "", "@version", "@inheritDoc", "@category", "@value", "@literal", "@code" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$
-
- /** Javadoc tag prefix */
- public static final char JAVADOC_TAG_PREFIX= '@';
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDoc2HTMLTextReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDoc2HTMLTextReader.java
deleted file mode 100644
index 24320597..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDoc2HTMLTextReader.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Brock Janiczak (brockj_eclipse@ihug.com.au) - https://bugs.eclipse.org/bugs/show_bug.cgi?id=20644
- * Brock Janiczak (brockj_eclipse@ihug.com.au) - https://bugs.eclipse.org/bugs/show_bug.cgi?id=83607
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter;
-import org.eclipse.wst.jsdt.internal.ui.text.html.SubstitutionTextReader;
-import org.eclipse.wst.jsdt.core.dom.TagElement;
-
-
-/**
- * Processes JavaDoc tags.
- */
-public class JavaDoc2HTMLTextReader extends SubstitutionTextReader {
-
-
- static private class Pair {
- String fTag;
- String fContent;
-
- Pair(String tag, String content) {
- fTag= tag;
- fContent= content;
- }
- }
-
- private List fParameters;
- private String fReturn;
- private List fExceptions;
- private List fAuthors;
- private List fSees;
- private List fSince;
- private List fRest; // list of Pair objects
-
- public JavaDoc2HTMLTextReader(Reader reader) {
- super(reader);
- setSkipWhitespace(false);
- }
-
- private int getTag(StringBuffer buffer) throws IOException {
- int c= nextChar();
- while (c == '.' || c != -1 && Character.isLetter((char) c)) {
- buffer.append((char) c);
- c= nextChar();
- }
- return c;
- }
-
- private int getContent(StringBuffer buffer, char stopChar) throws IOException {
- int c= nextChar();
- while (c != -1 && c != stopChar) {
- buffer.append((char) c);
- c= nextChar();
- }
- return c;
- }
-
- private int getContentUntilNextTag(StringBuffer buffer) throws IOException {
- int c= nextChar();
- boolean blockStartRead= false;
- while (c != -1) {
- if (c == '@') {
- int index= buffer.length();
- while (--index >= 0 && Character.isWhitespace(buffer.charAt(index))) {
- switch (buffer.charAt(index)) {
- case '\n':
- case '\r':
- return c;
- }
- if (index <= 0) {
- return c;
- }
- }
- }
- if (blockStartRead) {
- buffer.append(processBlockTag());
- blockStartRead= false;
- } else {
- buffer.append((char) c);
- }
-
- c= nextChar();
- blockStartRead= c == '{';
- }
- return c;
- }
-
- private String substituteQualification(String qualification) {
- String result= qualification.replace('#', '.');
- if (result.startsWith(".")) { //$NON-NLS-1$
- result= result.substring(1);
- }
- return result;
- }
-
- private void printDefinitions(StringBuffer buffer, List list, boolean firstword) {
- Iterator e= list.iterator();
- while (e.hasNext()) {
- String s= (String) e.next();
- buffer.append("<dd>"); //$NON-NLS-1$
- if (!firstword)
- buffer.append(s);
- else {
- buffer.append("<b>"); //$NON-NLS-1$
-
- int i= getParamEndOffset(s);
- if (i <= s.length()) {
- buffer.append(HTMLPrinter.convertToHTMLContent(s.substring(0, i)));
- buffer.append("</b>"); //$NON-NLS-1$
- buffer.append(s.substring(i));
- } else {
- buffer.append("</b>"); //$NON-NLS-1$
- }
- }
- buffer.append("</dd>"); //$NON-NLS-1$
- }
- }
-
- private int getParamEndOffset(String s) {
- int i= 0;
- final int length= s.length();
- // \s*
- while (i < length && Character.isWhitespace(s.charAt(i)))
- ++i;
- if (i < length && s.charAt(i) == '<') {
- // generic type parameter
- // read <\s*\w*\s*>
- while (i < length && Character.isWhitespace(s.charAt(i)))
- ++i;
- while (i < length && Character.isJavaIdentifierPart(s.charAt(i)))
- ++i;
- while (i < length && s.charAt(i) != '>')
- ++i;
- } else {
- // simply read an identifier
- while (i < length && Character.isJavaIdentifierPart(s.charAt(i)))
- ++i;
- }
-
- return i;
- }
-
- private void print(StringBuffer buffer, String tag, List elements, boolean firstword) {
- if ( !elements.isEmpty()) {
- buffer.append("<dt>"); //$NON-NLS-1$
- buffer.append(tag);
- buffer.append("</dt>"); //$NON-NLS-1$
- printDefinitions(buffer, elements, firstword);
- }
- }
-
- private void print(StringBuffer buffer, String tag, String content) {
- if (content != null) {
- buffer.append("<dt>"); //$NON-NLS-1$
- buffer.append(tag);
- buffer.append("</dt>"); //$NON-NLS-1$
- buffer.append("<dd>"); //$NON-NLS-1$
- buffer.append(content);
- buffer.append("</dd>"); //$NON-NLS-1$
- }
- }
-
- private void printRest(StringBuffer buffer) {
- if ( !fRest.isEmpty()) {
- Iterator e= fRest.iterator();
- while (e.hasNext()) {
- Pair p= (Pair) e.next();
- buffer.append("<dt>"); //$NON-NLS-1$
- if (p.fTag != null)
- buffer.append(p.fTag);
- buffer.append("</dt>"); //$NON-NLS-1$
- buffer.append("<dd>"); //$NON-NLS-1$
- if (p.fContent != null)
- buffer.append(p.fContent);
- buffer.append("</dd>"); //$NON-NLS-1$
- }
- }
- }
-
- private String printSimpleTag() {
- StringBuffer buffer= new StringBuffer();
- buffer.append("<dl>"); //$NON-NLS-1$
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_see_section, fSees, false);
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_parameters_section, fParameters, true);
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_returns_section, fReturn);
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_throws_section, fExceptions, false);
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_author_section, fAuthors, false);
- print(buffer, JavaDocMessages.JavaDoc2HTMLTextReader_since_section, fSince, false);
- printRest(buffer);
- buffer.append("</dl>"); //$NON-NLS-1$
-
- return buffer.toString();
- }
-
- private void handleTag(String tag, String tagContent) {
-
- tagContent= tagContent.trim();
-
- if (TagElement.TAG_PARAM.equals(tag))
- fParameters.add(tagContent);
- else if (TagElement.TAG_RETURN.equals(tag))
- fReturn= tagContent;
- else if (TagElement.TAG_EXCEPTION.equals(tag))
- fExceptions.add(tagContent);
- else if (TagElement.TAG_THROWS.equals(tag))
- fExceptions.add(tagContent);
- else if (TagElement.TAG_AUTHOR.equals(tag))
- fAuthors.add(substituteQualification(tagContent));
- else if (TagElement.TAG_SEE.equals(tag))
- fSees.add(substituteQualification(tagContent));
- else if (TagElement.TAG_SINCE.equals(tag))
- fSince.add(substituteQualification(tagContent));
- else if (tagContent != null)
- fRest.add(new Pair(tag, tagContent));
- }
-
- /*
- * A '@' has been read. Process a javadoc tag
- */
- private String processSimpleTag() throws IOException {
-
- fParameters= new ArrayList();
- fExceptions= new ArrayList();
- fAuthors= new ArrayList();
- fSees= new ArrayList();
- fSince= new ArrayList();
- fRest= new ArrayList();
-
- StringBuffer buffer= new StringBuffer();
- int c= '@';
- while (c != -1) {
-
- buffer.setLength(0);
- buffer.append((char) c);
- c= getTag(buffer);
- String tag= buffer.toString();
-
- buffer.setLength(0);
- if (c != -1) {
- c= getContentUntilNextTag(buffer);
- }
-
- handleTag(tag, buffer.toString());
- }
-
- return printSimpleTag();
- }
-
- private String printBlockTag(String tag, String tagContent) {
-
- if (TagElement.TAG_LINK.equals(tag) || TagElement.TAG_LINKPLAIN.equals(tag)) {
-
- char[] contentChars= tagContent.toCharArray();
- boolean inParentheses= false;
- int labelStart= 0;
-
- for (int i= 0; i < contentChars.length; i++) {
- char nextChar= contentChars[i];
-
- // tagContent always has a leading space
- if (i == 0 && Character.isWhitespace(nextChar)) {
- labelStart= 1;
- continue;
- }
-
- if (nextChar == '(') {
- inParentheses= true;
- continue;
- }
-
- if (nextChar == ')') {
- inParentheses= false;
- continue;
- }
-
- // Stop at first whitespace that is not in parentheses
- if (!inParentheses && Character.isWhitespace(nextChar)) {
- labelStart= i+1;
- break;
- }
- }
- if (TagElement.TAG_LINK.equals(tag))
- return "<code>" + substituteQualification(tagContent.substring(labelStart)) + "</code>"; //$NON-NLS-1$//$NON-NLS-2$
- else
- return substituteQualification(tagContent.substring(labelStart));
-
- } else if (TagElement.TAG_LITERAL.equals(tag)) {
- return printLiteral(tagContent);
-
- } else if (TagElement.TAG_CODE.equals(tag)) {
- return "<code>" + printLiteral(tagContent) + "</code>"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- // If something went wrong at least replace the {} with the content
- return substituteQualification(tagContent);
- }
-
- private String printLiteral(String tagContent) {
- int contentStart= 0;
- for (int i= 0; i < tagContent.length(); i++) {
- if (! Character.isWhitespace(tagContent.charAt(i))) {
- contentStart= i;
- break;
- }
- }
- return HTMLPrinter.convertToHTMLContent(tagContent.substring(contentStart));
- }
-
- /*
- * A '{' has been read. Process a block tag
- */
- private String processBlockTag() throws IOException {
-
- int c= nextChar();
-
- if (c != '@') {
- StringBuffer buffer= new StringBuffer();
- buffer.append('{');
- buffer.append((char) c);
- return buffer.toString();
- }
-
- StringBuffer buffer= new StringBuffer();
- if (c != -1) {
-
- buffer.setLength(0);
- buffer.append((char) c);
-
- c= getTag(buffer);
- String tag= buffer.toString();
-
- buffer.setLength(0);
- if (c != -1 && c != '}') {
- buffer.append((char) c);
- c= getContent(buffer, '}');
- }
-
- return printBlockTag(tag, buffer.toString());
- }
-
- return null;
- }
-
- /*
- * @see SubstitutionTextReaderr#computeSubstitution(int)
- */
- protected String computeSubstitution(int c) throws IOException {
- if (c == '@' && fWasWhiteSpace)
- return processSimpleTag();
-
- if (c == '{')
- return processBlockTag();
-
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
deleted file mode 100644
index fffeb6dd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITypedRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyManager;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-
-/**
- * Auto indent strategy for Javadoc comments.
- */
-public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy {
-
- /** The partitioning that this strategy operates on. */
- private final String fPartitioning;
-
- /**
- * Creates a new Javadoc auto indent strategy for the given document partitioning.
- *
- * @param partitioning the document partitioning
- */
- public JavaDocAutoIndentStrategy(String partitioning) {
- fPartitioning= partitioning;
- }
-
- /**
- * Copies the indentation of the previous line and adds a star.
- * If the javadoc just started on this line add standard method tags
- * and close the javadoc.
- *
- * @param d the document to work on
- * @param c the command to deal with
- */
- private void indentAfterNewLine(IDocument d, DocumentCommand c) {
-
- int offset= c.offset;
- if (offset == -1 || d.getLength() == 0)
- return;
-
- try {
- int p= (offset == d.getLength() ? offset - 1 : offset);
- IRegion line= d.getLineInformationOfOffset(p);
-
- int lineOffset= line.getOffset();
- int firstNonWS= findEndOfWhiteSpace(d, lineOffset, offset);
- Assert.isTrue(firstNonWS >= lineOffset, "indentation must not be negative"); //$NON-NLS-1$
-
- StringBuffer buf= new StringBuffer(c.text);
- IRegion prefix= findPrefixRange(d, line);
- String indentation= d.get(prefix.getOffset(), prefix.getLength());
- int lengthToAdd= Math.min(offset - prefix.getOffset(), prefix.getLength());
-
- buf.append(indentation.substring(0, lengthToAdd));
-
- if (firstNonWS < offset) {
- /* ensure this isn't a double slash comment */
-
- if (d.getChar(firstNonWS) == '/' && d.getChar(firstNonWS+1)!='/') {
- // javadoc started on this line
- buf.append(" * "); //$NON-NLS-1$
-
- if (isPreferenceTrue(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, offset)) {
- c.shiftsCaret= false;
- c.caretOffset= c.offset + buf.length();
- String lineDelimiter= TextUtilities.getDefaultLineDelimiter(d);
-
- String endTag= lineDelimiter + indentation + " */"; //$NON-NLS-1$
-
- if (isPreferenceTrue(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)) {
- // we need to close the comment before computing
- // the correct tags in order to get the method
- d.replace(offset, 0, endTag);
-
- // evaluate method signature
- IJavaScriptUnit unit= getCompilationUnit();
-
- if (unit != null) {
- try {
- JavaModelUtil.reconcile(unit);
- String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
- // only add tags if they are non-empty - the empty line has already been added above.
- if (string != null && !string.trim().equals("*")) //$NON-NLS-1$
- buf.append(string);
- } catch (CoreException e) {
- // ignore
- }
- }
- } else {
- buf.append(endTag);
- }
- }
-
- }
- }
-
- // move the caret behind the prefix, even if we do not have to insert it.
- if (lengthToAdd < prefix.getLength())
- c.caretOffset= offset + prefix.getLength() - lengthToAdd;
- c.text= buf.toString();
-
- } catch (BadLocationException excp) {
- // stop work
- }
- }
-
- /**
- * Returns the value of the given boolean-typed preference.
- *
- * @param preference the preference to look up
- * @return the value of the given preference in the Java plug-in's default preference store
- */
- private boolean isPreferenceTrue(String preference) {
- return JavaScriptPlugin.getDefault().getPreferenceStore().getBoolean(preference);
- }
-
- /**
- * Returns the range of the Javadoc prefix on the given line in
- * <code>document</code>. The prefix greedily matches the following regex
- * pattern: <code>\w*\*\w*</code>, that is, any number of whitespace
- * characters, followed by an asterix ('*'), followed by any number of
- * whitespace characters.
- *
- * @param document the document to which <code>line</code> refers
- * @param line the line from which to extract the prefix range
- * @return an <code>IRegion</code> describing the range of the prefix on
- * the given line
- * @throws BadLocationException if accessing the document fails
- */
- private IRegion findPrefixRange(IDocument document, IRegion line) throws BadLocationException {
- int lineOffset= line.getOffset();
- int lineEnd= lineOffset + line.getLength();
- int indentEnd= findEndOfWhiteSpace(document, lineOffset, lineEnd);
- if (indentEnd < lineEnd && document.getChar(indentEnd) == '*') {
- indentEnd++;
- while (indentEnd < lineEnd && document.getChar(indentEnd) == ' ')
- indentEnd++;
- }
- return new Region(lineOffset, indentEnd - lineOffset);
- }
-
- /**
- * Creates the Javadoc tags for newly inserted comments.
- *
- * @param document the document
- * @param command the command
- * @param indentation the base indentation to use
- * @param lineDelimiter the line delimiter to use
- * @param unit the compilation unit shown in the editor
- * @return the tags to add to the document
- * @throws CoreException if accessing the java model fails
- * @throws BadLocationException if accessing the document fails
- */
- private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IJavaScriptUnit unit)
- throws CoreException, BadLocationException
- {
- IJavaScriptElement element= unit.getElementAt(command.offset);
- if (element == null)
- return null;
-
- switch (element.getElementType()) {
- case IJavaScriptElement.TYPE:
- return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);
-
- case IJavaScriptElement.METHOD:
- return createMethodTags(document, command, indentation, lineDelimiter, (IFunction) element);
-
- default:
- return null;
- }
- }
-
- /**
- * Removes start and end of a comment and corrects indentation and line
- * delimiters.
- *
- * @param comment the computed comment
- * @param indentation the base indentation
- * @param project the java project for the formatter settings, or
- * <code>null</code> for global preferences
- * @param lineDelimiter the line delimiter
- * @return a trimmed version of <code>comment</code>
- */
- private String prepareTemplateComment(String comment, String indentation, IJavaScriptProject project, String lineDelimiter) {
- // trim comment start and end if any
- if (comment.endsWith("*/")) //$NON-NLS-1$
- comment= comment.substring(0, comment.length() - 2);
- comment= comment.trim();
- if (comment.startsWith("/*")) { //$NON-NLS-1$
- if (comment.length() > 2 && comment.charAt(2) == '*') {
- comment= comment.substring(3); // remove '/**'
- } else {
- comment= comment.substring(2); // remove '/*'
- }
- }
- // trim leading spaces, but not new lines
- int nonSpace= 0;
- int len= comment.length();
- while (nonSpace < len && Character.getType(comment.charAt(nonSpace)) == Character.SPACE_SEPARATOR)
- nonSpace++;
- comment= comment.substring(nonSpace);
-
- return Strings.changeIndent(comment, 0, project, indentation, lineDelimiter);
- }
-
- private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type)
- throws CoreException, BadLocationException
- {
- String comment= CodeGeneration.getTypeComment(type.getJavaScriptUnit(), type.getTypeQualifiedName('.'), lineDelimiter);
- if (comment != null) {
- boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
- if (!isFirstComment(document, command, type, javadocComment))
- return null;
- return prepareTemplateComment(comment.trim(), indentation, type.getJavaScriptProject(), lineDelimiter);
- }
- return null;
- }
-
- private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IFunction method)
- throws CoreException, BadLocationException
- {
- IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false);
- IFunction inheritedMethod= getInheritedMethod(method);
- String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
- if (comment != null) {
- comment= comment.trim();
- boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
- if (!isFirstComment(document, command, method, javadocComment))
- return null;
- boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
- if (javadocComment == isJavaDoc) {
- return prepareTemplateComment(comment, indentation, method.getJavaScriptProject(), lineDelimiter);
- }
- }
- return null;
- }
-
- /**
- * Returns <code>true</code> if the comment being inserted at
- * <code>command.offset</code> is the first comment (the first
- * javadoc comment if <code>ignoreJavadoc</code> is
- * <code>true</code>) of the given member.
- * <p>
- * see also https://bugs.eclipse.org/bugs/show_bug.cgi?id=55325 (don't add parameters if the member already has a comment)
- * </p>
- */
- private boolean isFirstComment(IDocument document, DocumentCommand command, IMember member, boolean ignoreNonJavadoc) throws BadLocationException, JavaScriptModelException {
- IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false);
- ISourceRange sourceRange= member.getSourceRange();
- if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
- return false;
- int srcOffset= sourceRange.getOffset();
- int srcLength= sourceRange.getLength();
- int nameRelativeOffset= member.getNameRange().getOffset() - srcOffset;
- int partitionRelativeOffset= partition.getOffset() - srcOffset;
- String token= ignoreNonJavadoc ? "/**" : "/*"; //$NON-NLS-1$ //$NON-NLS-2$
- return document.get(srcOffset, srcLength).lastIndexOf(token, nameRelativeOffset) == partitionRelativeOffset;
- }
-
- /**
- * Unindents a typed slash ('/') if it forms the end of a comment.
- *
- * @param d the document
- * @param c the command
- */
- private void indentAfterCommentEnd(IDocument d, DocumentCommand c) {
- if (c.offset < 2 || d.getLength() == 0) {
- return;
- }
- try {
- if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$
- // modify document command
- c.length++;
- c.offset--;
- }
- } catch (BadLocationException excp) {
- // stop work
- }
- }
-
- /**
- * Guesses if the command operates within a newly created javadoc comment or not.
- * If in doubt, it will assume that the javadoc is new.
- *
- * @param document the document
- * @param commandOffset the command offset
- * @return <code>true</code> if the comment should be closed, <code>false</code> if not
- */
- private boolean isNewComment(IDocument document, int commandOffset) {
-
- try {
- int lineIndex= document.getLineOfOffset(commandOffset) + 1;
- if (lineIndex >= document.getNumberOfLines())
- return true;
-
- IRegion line= document.getLineInformation(lineIndex);
- ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, commandOffset, false);
- int partitionEnd= partition.getOffset() + partition.getLength();
- if (line.getOffset() >= partitionEnd)
- return false;
-
- if (document.getLength() == partitionEnd)
- return true; // partition goes to end of document - probably a new comment
-
- String comment= document.get(partition.getOffset(), partition.getLength());
- if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$
- return true; // enclosed another comment -> probably a new comment
-
- return false;
-
- } catch (BadLocationException e) {
- return false;
- }
- }
-
- private boolean isSmartMode() {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IEditorPart part= page.getActiveEditor();
- if (part instanceof ITextEditorExtension3) {
- ITextEditorExtension3 extension= (ITextEditorExtension3) part;
- return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
- }
- }
- return false;
- }
-
- /*
- * @see IAutoIndentStrategy#customizeDocumentCommand
- */
- public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
-
- if (!isSmartMode())
- return;
-
- if (command.text != null) {
- if (command.length == 0) {
- String[] lineDelimiters= document.getLegalLineDelimiters();
- int index= TextUtilities.endsWith(lineDelimiters, command.text);
- if (index > -1) {
- // ends with line delimiter
- if (lineDelimiters[index].equals(command.text))
- // just the line delimiter
- indentAfterNewLine(document, command);
- return;
- }
- }
-
- if (command.text.equals("/")) { //$NON-NLS-1$
- indentAfterCommentEnd(document, command);
- return;
- }
- }
- }
-
- /**
- * Returns the method inherited from, <code>null</code> if method is newly defined.
- * @param method the method being written
- * @return the ancestor method, or <code>null</code> if none
- * @throws JavaScriptModelException if accessing the java model fails
- */
- private static IFunction getInheritedMethod(IFunction method) throws JavaScriptModelException {
- IType declaringType= method.getDeclaringType();
- if (declaringType==null)
- return null;
- MethodOverrideTester tester= SuperTypeHierarchyCache.getMethodOverrideTester(declaringType);
- return tester.findOverriddenMethod(method, true);
- }
-
- /**
- * Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy,
- * might return <code>null</code> on error.
- * @return the compilation unit represented by the document
- */
- private static IJavaScriptUnit getCompilationUnit() {
-
- IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null)
- return null;
-
- IWorkbenchPage page= window.getActivePage();
- if (page == null)
- return null;
-
- IEditorPart editor= page.getActiveEditor();
- if (editor == null)
- return null;
-
- IWorkingCopyManager manager= JavaScriptPlugin.getDefault().getWorkingCopyManager();
- IJavaScriptUnit unit= manager.getWorkingCopy(editor.getEditorInput());
- if (unit == null)
- return null;
-
- return unit;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.java
deleted file mode 100644
index 1d120a69..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class JavaDocMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaDocMessages.class.getName();
-
- private JavaDocMessages() {
- // Do not instantiate
- }
-
- public static String JavaDoc2HTMLTextReader_parameters_section;
- public static String JavaDoc2HTMLTextReader_returns_section;
- public static String JavaDoc2HTMLTextReader_throws_section;
- public static String JavaDoc2HTMLTextReader_author_section;
- public static String JavaDoc2HTMLTextReader_see_section;
- public static String JavaDoc2HTMLTextReader_since_section;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaDocMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties
deleted file mode 100644
index 82ee803d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties
+++ /dev/null
@@ -1,18 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-JavaDoc2HTMLTextReader_parameters_section=Parameters:
-JavaDoc2HTMLTextReader_returns_section=Returns:
-JavaDoc2HTMLTextReader_throws_section=Throws:
-JavaDoc2HTMLTextReader_author_section=Author:
-JavaDoc2HTMLTextReader_see_section=See Also:
-JavaDoc2HTMLTextReader_since_section=Since:
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocScanner.java
deleted file mode 100644
index bc732568..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocScanner.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.rules.ICharacterScanner;
-import org.eclipse.jface.text.rules.IToken;
-import org.eclipse.jface.text.rules.IWordDetector;
-import org.eclipse.jface.text.rules.SingleLineRule;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.text.rules.WhitespaceRule;
-import org.eclipse.jface.text.rules.WordRule;
-import org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCommentScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaWhitespaceDetector;
-import org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.CharacterBuffer;
-import org.eclipse.wst.jsdt.internal.ui.text.CombinedWordRule.WordMatcher;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants;
-
-/**
- * A rule based JavaDoc scanner.
- */
-public final class JavaDocScanner extends JavaCommentScanner {
-
-
- /**
- * Detector for HTML comment delimiters.
- */
- static class HTMLCommentDetector implements IWordDetector {
-
- /**
- * @see IWordDetector#isWordStart(char)
- */
- public boolean isWordStart(char c) {
- return (c == '<' || c == '-');
- }
-
- /**
- * @see IWordDetector#isWordPart(char)
- */
- public boolean isWordPart(char c) {
- return (c == '-' || c == '!' || c == '>');
- }
- }
-
- class TagRule extends SingleLineRule {
-
- /*
- * @see SingleLineRule
- */
- public TagRule(IToken token) {
- super("<", ">", token, (char) 0); //$NON-NLS-2$ //$NON-NLS-1$
- }
-
- /*
- * @see SingleLineRule
- */
- public TagRule(IToken token, char escapeCharacter) {
- super("<", ">", token, escapeCharacter); //$NON-NLS-2$ //$NON-NLS-1$
- }
-
- private IToken evaluateToken() {
- try {
- final String token= getDocument().get(getTokenOffset(), getTokenLength()) + "."; //$NON-NLS-1$
-
- int offset= 0;
- char character= token.charAt(++offset);
-
- if (character == '/')
- character= token.charAt(++offset);
-
- while (Character.isWhitespace(character))
- character= token.charAt(++offset);
-
- while (Character.isLetterOrDigit(character))
- character= token.charAt(++offset);
-
- while (Character.isWhitespace(character))
- character= token.charAt(++offset);
-
- if (offset >= 2 && token.charAt(offset) == fEndSequence[0])
- return fToken;
-
- } catch (BadLocationException exception) {
- // Do nothing
- }
- return getToken(IJavaScriptColorConstants.JAVADOC_DEFAULT);
- }
-
- /*
- * @see PatternRule#evaluate(ICharacterScanner)
- */
- public IToken evaluate(ICharacterScanner scanner) {
- IToken result= super.evaluate(scanner);
- if (result == fToken)
- return evaluateToken();
- return result;
- }
- }
-
- private static String[] fgTokenProperties= {
- IJavaScriptColorConstants.JAVADOC_KEYWORD,
- IJavaScriptColorConstants.JAVADOC_TAG,
- IJavaScriptColorConstants.JAVADOC_LINK,
- IJavaScriptColorConstants.JAVADOC_DEFAULT,
- TASK_TAG
- };
-
-
- public JavaDocScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore) {
- super(manager, store, coreStore, IJavaScriptColorConstants.JAVADOC_DEFAULT, fgTokenProperties);
- }
-
- /**
- * Initialize with the given arguments
- * @param manager Color manager
- * @param store Preference store
- *
- *
- */
- public JavaDocScanner(IColorManager manager, IPreferenceStore store) {
- this(manager, store, null);
- }
-
- public IDocument getDocument() {
- return fDocument;
- }
-
- /*
- * @see AbstractJavaScanner#createRules()
- */
- protected List createRules() {
-
- List list= new ArrayList();
-
- // Add rule for tags.
- Token token= getToken(IJavaScriptColorConstants.JAVADOC_TAG);
- list.add(new TagRule(token));
-
-
- // Add rule for HTML comments
- WordRule wordRule= new WordRule(new HTMLCommentDetector(), token);
- wordRule.addWord("<!--", token); //$NON-NLS-1$
- wordRule.addWord("--!>", token); //$NON-NLS-1$
- list.add(wordRule);
-
-
- // Add rule for links.
- token= getToken(IJavaScriptColorConstants.JAVADOC_LINK);
- list.add(new SingleLineRule("{@link", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$
- list.add(new SingleLineRule("{@value", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$
-
-
- // Add generic whitespace rule.
- list.add(new WhitespaceRule(new JavaWhitespaceDetector()));
-
-
- list.addAll(super.createRules());
- return list;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaCommentScanner#createMatchers()
- */
- protected List createMatchers() {
- List list= super.createMatchers();
-
- // Add word rule for keywords.
- final IToken token= getToken(IJavaScriptColorConstants.JAVADOC_KEYWORD);
- WordMatcher matcher= new CombinedWordRule.WordMatcher() {
- public IToken evaluate(ICharacterScanner scanner, CharacterBuffer word) {
- int length= word.length();
- if (length > 1 && word.charAt(0) == '@') {
- int i= 0;
- try {
- for (; i <= length; i++)
- scanner.unread();
- int c= scanner.read();
- i--;
- if (c == '*' || Character.isWhitespace((char)c)) {
- scanner.unread();
- return token;
- }
- } finally {
- for (; i >= 0; i--)
- scanner.read();
- }
- }
- return Token.UNDEFINED;
- }
- };
- list.add(matcher);
-
- return list;
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProcessor.java
deleted file mode 100644
index c030bb23..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProcessor.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProcessor;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavadocCompletionProcessor;
-
-/**
- * Javadoc completion processor.
- *
- *
- */
-public class JavadocCompletionProcessor extends JavaCompletionProcessor {
-
- private int fSubProcessorFlags;
-
- public JavadocCompletionProcessor(IEditorPart editor, ContentAssistant assistant) {
- super(editor, assistant, IJavaScriptPartitions.JAVA_DOC);
- fSubProcessorFlags= 0;
- }
-
- /**
- * Tells this processor to restrict is proposals to those
- * starting with matching cases.
- *
- * @param restrict <code>true</code> if proposals should be restricted
- */
- public void restrictProposalsToMatchingCases(boolean restrict) {
- fSubProcessorFlags= restrict ? IJavadocCompletionProcessor.RESTRICT_TO_MATCHING_CASE : 0;
- }
-
- /**
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProcessor#createContext(org.eclipse.jface.text.ITextViewer, int)
- */
- protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset) {
- return new JavadocContentAssistInvocationContext(viewer, offset, fEditor, fSubProcessorFlags);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProposalComputer.java
deleted file mode 100644
index 6cc35cbb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocCompletionProposalComputer.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposalComputer;
-import org.eclipse.wst.jsdt.ui.text.java.CompletionProposalCollector;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- *
- *
- */
-public class JavadocCompletionProposalComputer extends JavaCompletionProposalComputer {
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposalComputer#createCollector(org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext)
- */
- protected CompletionProposalCollector createCollector(JavaContentAssistInvocationContext context) {
- CompletionProposalCollector collector= super.createCollector(context);
- collector.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- collector.setIgnored(CompletionProposal.FIELD_REF, false);
- collector.setIgnored(CompletionProposal.KEYWORD, true);
- collector.setIgnored(CompletionProposal.LABEL_REF, true);
- collector.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
- collector.setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- collector.setIgnored(CompletionProposal.METHOD_REF, false);
- collector.setIgnored(CompletionProposal.PACKAGE_REF, true);
- collector.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- collector.setIgnored(CompletionProposal.JSDOC_TYPE_REF, false);
- collector.setIgnored(CompletionProposal.JSDOC_FIELD_REF, false);
- collector.setIgnored(CompletionProposal.JSDOC_METHOD_REF, false);
- collector.setIgnored(CompletionProposal.JSDOC_PARAM_REF, false);
- collector.setIgnored(CompletionProposal.TYPE_REF, false);
- return collector;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java
deleted file mode 100644
index 09ba30c2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-
-/**
- *
- *
- */
-public final class JavadocContentAssistInvocationContext extends JavaContentAssistInvocationContext {
-
- private final int fFlags;
-
- /**
- * @param viewer
- * @param offset
- * @param editor
- * @param flags see {@link org.eclipse.wst.jsdt.ui.text.java.IJavadocCompletionProcessor#RESTRICT_TO_MATCHING_CASE}
- */
- public JavadocContentAssistInvocationContext(ITextViewer viewer, int offset, IEditorPart editor, int flags) {
- super(viewer, offset, editor);
- fFlags= flags;
- }
-
- /**
- * Returns the flags for this content assist invocation.
- *
- * @return the flags for this content assist invocation
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavadocCompletionProcessor#RESTRICT_TO_MATCHING_CASE
- */
- public int getFlags() {
- return fFlags;
- }
-
- /**
- * Returns the selection length of the viewer.
- *
- * @return the selection length of the viewer
- */
- public int getSelectionLength() {
- return getViewer().getSelectedRange().y;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (!super.equals(obj))
- return false;
-
- return fFlags == ((JavadocContentAssistInvocationContext) obj).fFlags;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext#hashCode()
- */
- public int hashCode() {
- return super.hashCode() << 2 | fFlags;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocInlineTagCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocInlineTagCompletionProposal.java
deleted file mode 100644
index 4e0ac51f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocInlineTagCompletionProposal.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Completions of inline tags such as &#x7b;&#x40;link &#x7d;. See {@link CompletionProposal#JSDOC_INLINE_TAG}.
- *
- *
- */
-public final class JavadocInlineTagCompletionProposal extends LazyJavaCompletionProposal {
- /** Triggers for types in javadoc. Do not modify. */
- protected static final char[] JDOC_INLINE_TAG_TRIGGERS= new char[] { '#', '}', ' ' };
-
- public JavadocInlineTagCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- Assert.isTrue(isInJavadoc());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
- String replacement= super.computeReplacementString();
- // TODO respect the auto-close preference, but do so consistently with method completions
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=113544
-// if (!autocloseBrackets() && replacement.endsWith("}")) //$NON-NLS-1$
-// return replacement.substring(0, replacement.length() - 1);
- return replacement;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- // TODO respect the auto-close preference, but do so consistently with method completions
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=113544
-// boolean needsLinkedMode= autocloseBrackets();
- boolean needsLinkedMode= true;
- if (needsLinkedMode)
- setCursorPosition(getCursorPosition() - 1); // before the closing curly brace
-
- super.apply(document, trigger, offset);
-
- if (needsLinkedMode)
- setUpLinkedMode(document, '}');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocLinkTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocLinkTypeCompletionProposal.java
deleted file mode 100644
index ea6a1194..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocLinkTypeCompletionProposal.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Types directly completed to &#x7b;&#x40;link Type&#x7d;. See {@link CompletionProposal#JSDOC_TYPE_REF}.
- *
- *
- */
-public final class JavadocLinkTypeCompletionProposal extends LazyJavaTypeCompletionProposal {
-
- public JavadocLinkTypeCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) {
- super(proposal, context);
- Assert.isTrue(isInJavadoc());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal#computeReplacementString()
- */
- protected String computeReplacementString() {
- String typeReplacement= super.computeReplacementString();
- // TODO respect the auto-close preference, but do so consistently with method completions
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=113544
-// if (autocloseBrackets())
- if (true)
- return "{@link " + typeReplacement + "}"; //$NON-NLS-1$ //$NON-NLS-2$
- else
- return "{@link " + typeReplacement; //$NON-NLS-1$
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- // convert . to #
- if (trigger == '.')
- trigger= '#';
- // TODO respect the auto-close preference, but do so consistently with method completions
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=113544
-// boolean continueWithMember= trigger == '#' && autocloseBrackets();
- boolean continueWithMember= trigger == '#';
- if (continueWithMember)
- setCursorPosition(getCursorPosition() - 1); // before the closing curly brace
-
- super.apply(document, trigger, offset);
-
- if (continueWithMember)
- setUpLinkedMode(document, '}');
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/LegacyJavadocCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/LegacyJavadocCompletionProposalComputer.java
deleted file mode 100644
index b692f564..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/LegacyJavadocCompletionProposalComputer.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.wst.jsdt.ui.text.java.IJavadocCompletionProcessor;
-import org.eclipse.wst.jsdt.ui.text.java.JavaContentAssistInvocationContext;
-
-/**
- * Java doc completion processor using contributed IJavaDocCompletionProcessor's
- * to evaluate proposals.
- *
- *
- */
-public class LegacyJavadocCompletionProposalComputer implements IJavaCompletionProposalComputer {
-
- private static final String PROCESSOR_CONTRIBUTION_ID= "javadocCompletionProcessor"; //$NON-NLS-1$
-
- private IJavadocCompletionProcessor[] fSubProcessors;
-
- private String fErrorMessage;
-
- public LegacyJavadocCompletionProposalComputer() {
- fSubProcessors= null;
- }
-
-
- private IJavadocCompletionProcessor[] getContributedProcessors() {
- if (fSubProcessors == null) {
- try {
- IExtensionRegistry registry= Platform.getExtensionRegistry();
- IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaScriptUI.ID_PLUGIN, PROCESSOR_CONTRIBUTION_ID);
- IJavadocCompletionProcessor[] result= new IJavadocCompletionProcessor[elements.length];
- for (int i= 0; i < elements.length; i++) {
- result[i]= (IJavadocCompletionProcessor) elements[i].createExecutableExtension("class"); //$NON-NLS-1$
- }
- fSubProcessors= result;
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- fSubProcessors= new IJavadocCompletionProcessor[0];
- }
- }
- return fSubProcessors;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeContextInformation(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (context instanceof JavaContentAssistInvocationContext) {
- JavaContentAssistInvocationContext javaContext= (JavaContentAssistInvocationContext) context;
-
- IJavaScriptUnit cu= javaContext.getCompilationUnit();
- int offset= javaContext.getInvocationOffset();
-
- ArrayList result= new ArrayList();
-
- IJavadocCompletionProcessor[] processors= getContributedProcessors();
- String error= null;
- for (int i= 0; i < processors.length; i++) {
- IJavadocCompletionProcessor curr= processors[i];
- IContextInformation[] contextInfos= curr.computeContextInformation(cu, offset);
- if (contextInfos != null) {
- for (int k= 0; k < contextInfos.length; k++) {
- result.add(contextInfos[k]);
- }
- } else if (error == null) {
- error= curr.getErrorMessage();
- }
- }
- fErrorMessage= error;
- return result;
- }
- return Collections.EMPTY_LIST;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
- */
- public List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
- if (context instanceof JavadocContentAssistInvocationContext) {
- JavadocContentAssistInvocationContext javaContext= (JavadocContentAssistInvocationContext) context;
-
- IJavaScriptUnit cu= javaContext.getCompilationUnit();
- int offset= javaContext.getInvocationOffset();
- int length= javaContext.getSelectionLength();
- Point selection= javaContext.getViewer().getSelectedRange();
- if (selection.y > 0) {
- offset= selection.x;
- length= selection.y;
- }
-
- ArrayList result= new ArrayList();
-
- IJavadocCompletionProcessor[] processors= getContributedProcessors();
- for (int i= 0; i < processors.length; i++) {
- IJavadocCompletionProcessor curr= processors[i];
- IJavaCompletionProposal[] proposals= curr.computeCompletionProposals(cu, offset, length, javaContext.getFlags());
- if (proposals != null) {
- for (int k= 0; k < proposals.length; k++) {
- result.add(proposals[k]);
- }
- }
- }
- return result;
- }
- return Collections.EMPTY_LIST;
- }
-
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalComputer#getErrorMessage()
- */
- public String getErrorMessage() {
- return fErrorMessage;
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionStarted()
- */
- public void sessionStarted() {
- }
-
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposalComputer#sessionEnded()
- */
- public void sessionEnded() {
- fErrorMessage= null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/OAADocReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/OAADocReader.java
deleted file mode 100644
index 6ce518bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/OAADocReader.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.javadoc;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.internal.core.MetadataFile;
-import org.eclipse.wst.jsdt.internal.oaametadata.DocumentedElement;
-import org.eclipse.wst.jsdt.internal.oaametadata.Exception;
-import org.eclipse.wst.jsdt.internal.oaametadata.Method;
-import org.eclipse.wst.jsdt.internal.oaametadata.Parameter;
-import org.eclipse.wst.jsdt.internal.oaametadata.VersionableElement;
-
-public class OAADocReader extends Reader {
-
- StringReader sr;
- StringBuffer buffer = new StringBuffer();
-
- public OAADocReader(MetadataFile openable, IMember member) {
-
- getDoc(openable, member);
- }
-
- private void getDoc(MetadataFile openable, IMember member) {
- DocumentedElement documentation = openable.getDocumentation(member);
- VersionableElement versionableElement = (documentation instanceof VersionableElement) ? (VersionableElement) documentation
- : null;
- Method method = (documentation instanceof Method) ? (Method) documentation
- : null;
- if (documentation != null) {
- if (documentation.description != null) {
- buffer.append("<p>"); //$NON-NLS-1$
- buffer.append(documentation.description);
- buffer.append("</p>"); //$NON-NLS-1$
- }
-
- if (method!=null)
- printMethod(method);
-
- }
- buffer.append("</dl>"); //$NON-NLS-1$
-
- sr = new StringReader(buffer.toString());
- }
-
- private void printMethod(Method method) {
- buffer.append("<dl>"); //$NON-NLS-1$
- if ( method.parameters != null
- && method.parameters.length > 0) {
- printSectionHead(JavaDocMessages.JavaDoc2HTMLTextReader_parameters_section);
- for (int i = 0; i < method.parameters.length; i++) {
- Parameter parameter = method.parameters[i];
- buffer.append("<dd>"); //$NON-NLS-1$
- buffer.append("<b>").append(parameter.name).append("</b> "); //$NON-NLS-1$ //$NON-NLS-2$
- if (parameter.description!=null)
- buffer.append(parameter.description);
- buffer.append("</dd>"); //$NON-NLS-1$
- }
- }
-
- if (method.returns != null)
- printSection(
- JavaDocMessages.JavaDoc2HTMLTextReader_returns_section,
- method.returns.dataType, method.returns.description);
-
- if ( method.exceptions != null
- && method.exceptions.length > 0) {
- printSectionHead(JavaDocMessages.JavaDoc2HTMLTextReader_throws_section);
- for (int i = 0; i < method.exceptions.length; i++) {
- Exception exception = method.exceptions[i];
- buffer.append("<dd>"); //$NON-NLS-1$
- buffer.append(exception.description); //$NON-NLS-1$
- buffer.append("</dd>"); //$NON-NLS-1$
- }
- }
- }
-
- public void close() throws IOException {
- sr.close();
- }
-
- public int read(char[] cbuf, int off, int len) throws IOException {
- return sr.read(cbuf, off, len);
- }
-
- private void printSectionHead(String tag) {
- buffer.append("<dt>"); //$NON-NLS-1$
- buffer.append(tag);
- buffer.append("</dt>"); //$NON-NLS-1$
- }
-
- private void printSection(String tag, String nameIn, String descriptionIn) {
- String name = (nameIn != null && nameIn.length() > 0) ? nameIn : null;
- String description = (descriptionIn != null && descriptionIn.length() > 0) ? descriptionIn
- : null;
- if (name != null || description != null) {
- buffer.append("<dt>"); //$NON-NLS-1$
- buffer.append(tag);
- buffer.append("<dd>"); //$NON-NLS-1$
- if (name != null)
- buffer.append("<b>").append(name).append("</b>"); //$NON-NLS-1$ //$NON-NLS-2$
- if (description != null)
- buffer.append(description);
- buffer.append("</dd>"); //$NON-NLS-1$
- buffer.append("</dt>"); //$NON-NLS-1$
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/JavaSpellingReconcileStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/JavaSpellingReconcileStrategy.java
deleted file mode 100644
index 23161329..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/JavaSpellingReconcileStrategy.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPartitioningException;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector;
-import org.eclipse.ui.texteditor.spelling.SpellingProblem;
-import org.eclipse.ui.texteditor.spelling.SpellingReconcileStrategy;
-import org.eclipse.ui.texteditor.spelling.SpellingService;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Reconcile strategy for spell checking comments.
- *
- */
-public class JavaSpellingReconcileStrategy extends SpellingReconcileStrategy {
-
- public JavaSpellingReconcileStrategy(ISourceViewer viewer, SpellingService spellingService, String partitioning) {
- super(viewer, spellingService);
- fPartitioning = partitioning;
- }
-
- /**
- * Spelling problem collector that forwards {@link SpellingProblem}s as
- * {@link org.eclipse.wst.jsdt.core.compiler.IProblem}s to the
- * {@link org.eclipse.wst.jsdt.core.compiler.IProblemRequestor}.
- */
- private class JSSpellingProblemCollector implements ISpellingProblemCollector {
- private ISpellingProblemCollector fParentCollector;
-
- public JSSpellingProblemCollector(ISpellingProblemCollector parentCollector) {
- fParentCollector = parentCollector;
- }
-
- /*
- * @see
- * org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept
- * (org.eclipse.ui.texteditor.spelling.SpellingProblem)
- */
- public void accept(SpellingProblem problem) {
- try {
- String type = ((IDocumentExtension3) getDocument()).getPartition(fPartitioning, problem.getOffset(), false).getType();
- if (IJavaScriptPartitions.JAVA_DOC.equals(type) || IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(type) || IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT.equals(type))
- fParentCollector.accept(problem);
- }
- catch (BadLocationException e) {
- fParentCollector.accept(problem);
- }
- catch (BadPartitioningException e) {
- fParentCollector.accept(problem);
- }
- }
-
- /*
- * @seeorg.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#
- * beginCollecting()
- */
- public void beginCollecting() {
- fParentCollector.beginCollecting();
- }
-
- /*
- * @seeorg.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#
- * endCollecting()
- */
- public void endCollecting() {
- fParentCollector.endCollecting();
- }
- }
-
-
- /** The id of the problem */
- public static final int SPELLING_PROBLEM_ID = 0x80000000;
- private String fPartitioning;
-
- protected ISpellingProblemCollector createSpellingProblemCollector() {
- return new JSSpellingProblemCollector(super.createSpellingProblemCollector());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/SpellingQuickFixProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/SpellingQuickFixProcessor.java
deleted file mode 100644
index af2610b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/SpellingQuickFixProcessor.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector;
-import org.eclipse.ui.texteditor.spelling.SpellingAnnotation;
-import org.eclipse.ui.texteditor.spelling.SpellingContext;
-import org.eclipse.ui.texteditor.spelling.SpellingProblem;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.core.DocumentAdapter;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.wst.jsdt.ui.text.java.IProblemLocation;
-import org.eclipse.wst.jsdt.ui.text.java.IQuickFixProcessor;
-
-/**
- * Provides a JSDT IQuickFixProcessor for SpellingAnnotations
- */
-public class SpellingQuickFixProcessor implements IQuickFixProcessor {
- private static class SpellingProposal implements IJavaCompletionProposal {
- ICompletionProposal fProposal;
-
- SpellingProposal(ICompletionProposal spellingProposal) {
- super();
- fProposal = spellingProposal;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal#getRelevance
- * ()
- */
- public int getRelevance() {
- return 50;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.jface.text.contentassist.ICompletionProposal#apply(
- * org.eclipse.jface.text.IDocument)
- */
- public void apply(IDocument document) {
- fProposal.apply(document);
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.jface.text.contentassist.ICompletionProposal#
- * getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return fProposal.getAdditionalProposalInfo();
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.jface.text.contentassist.ICompletionProposal#
- * getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return fProposal.getContextInformation();
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.jface.text.contentassist.ICompletionProposal#
- * getDisplayString()
- */
- public String getDisplayString() {
- return fProposal.getDisplayString();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fProposal.getImage();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection
- * (org.eclipse.jface.text.IDocument)
- */
- public Point getSelection(IDocument document) {
- return fProposal.getSelection(document);
- }
- }
-
- static final class SpellingProblemCollector implements ISpellingProblemCollector {
- IQuickAssistInvocationContext fContext = null;
-
- SpellingProblemCollector(final IInvocationContext context) {
- fContext = new IQuickAssistInvocationContext() {
- public ISourceViewer getSourceViewer() {
- return null;
- }
-
- public int getOffset() {
- return context.getSelectionOffset();
- }
-
- public int getLength() {
- return context.getSelectionLength();
- }
- };
- }
-
- private List fProposals = new ArrayList();
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept
- * (org.eclipse.ui.texteditor.spelling.SpellingProblem)
- */
- public void accept(SpellingProblem problem) {
- ICompletionProposal[] proposals = problem.getProposals(fContext);
- for (int i = 0; i < proposals.length; i++) {
- fProposals.add(new SpellingProposal(proposals[i]));
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#
- * beginCollecting()
- */
- public void beginCollecting() {
- fProposals.clear();
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#
- * endCollecting()
- */
- public void endCollecting() {
- }
-
- IJavaCompletionProposal[] getProposals() {
- return (IJavaCompletionProposal[]) fProposals.toArray(new IJavaCompletionProposal[fProposals.size()]);
- }
- }
-
- /**
- *
- */
- public SpellingQuickFixProcessor() {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.wst.jsdt.ui.text.java.IQuickFixProcessor#hasCorrections
- * (org.eclipse.wst.jsdt.core.IJavaScriptUnit, int)
- */
- public boolean hasCorrections(IJavaScriptUnit unit, int problemId) {
- return false;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.wst.jsdt.ui.text.java.IQuickFixProcessor#getCorrections
- * (org.eclipse.wst.jsdt.ui.text.java.IInvocationContext,
- * org.eclipse.wst.jsdt.ui.text.java.IProblemLocation[])
- */
- public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
- List regions = new ArrayList();
- for (int i = 0; i < locations.length; i++) {
- if (locations[i].getMarkerType() == SpellingAnnotation.TYPE) {
- regions.add(new Region(locations[i].getOffset(), locations[i].getLength()));
- }
- }
- SpellingProblemCollector collector = new SpellingProblemCollector(context);
- if (!regions.isEmpty()) {
- SpellingContext spellingContext = new SpellingContext();
- spellingContext.setContentType(Platform.getContentTypeManager().getContentType(JavaScriptCore.JAVA_SOURCE_CONTENT_TYPE));
- EditorsUI.getSpellingService().check(new DocumentAdapter(context.getCompilationUnit().getBuffer()), (IRegion[]) regions.toArray(new IRegion[regions.size()]), spellingContext, collector, new NullProgressMonitor());
- }
- return collector.getProposals();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java
deleted file mode 100644
index 85c3a9f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java
+++ /dev/null
@@ -1,615 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Partial implementation of a spell dictionary.
- *
- *
- */
-public abstract class AbstractSpellDictionary implements ISpellDictionary {
-
- /** The bucket capacity */
- protected static final int BUCKET_CAPACITY= 4;
-
- /** The word buffer capacity */
- protected static final int BUFFER_CAPACITY= 32;
-
- /** The distance threshold */
- protected static final int DISTANCE_THRESHOLD= 160;
-
- /** The hash capacity */
- protected static final int HASH_CAPACITY= 22 * 1024;
-
- /** The phonetic distance algorithm */
- private IPhoneticDistanceAlgorithm fDistanceAlgorithm= new DefaultPhoneticDistanceAlgorithm();
-
- /** The mapping from phonetic hashes to word lists */
- private final Map fHashBuckets= new HashMap(HASH_CAPACITY);
-
- /** The phonetic hash provider */
- private IPhoneticHashProvider fHashProvider= new DefaultPhoneticHashProvider();
-
- /** Is the dictionary already loaded? */
- private boolean fLoaded= false;
- /**
- * Must the dictionary be loaded?
- *
- */
- private boolean fMustLoad= true;
-
- /**
- * Tells whether to strip non-letters at word boundaries.
- *
- */
- boolean fIsStrippingNonLetters= true;
-
- /**
- * Returns all candidates with the same phonetic hash.
- *
- * @param hash
- * The hash to retrieve the candidates of
- * @return Array of candidates for the phonetic hash
- */
- protected final Object getCandidates(final String hash) {
- return fHashBuckets.get(hash);
- }
-
- /**
- * Returns all candidates that have a phonetic hash within a bounded
- * distance to the specified word.
- *
- * @param word
- * The word to find the nearest matches for
- * @param sentence
- * <code>true</code> iff the proposals start a new sentence,
- * <code>false</code> otherwise
- * @param hashs
- * Array of close hashes to find the matches
- * @return Set of ranked words with bounded distance to the specified word
- */
- protected final Set getCandidates(final String word, final boolean sentence, final ArrayList hashs) {
-
- int distance= 0;
- String hash= null;
-
- final StringBuffer buffer= new StringBuffer(BUFFER_CAPACITY);
- final HashSet result= new HashSet(BUCKET_CAPACITY * hashs.size());
-
- for (int index= 0; index < hashs.size(); index++) {
-
- hash= (String)hashs.get(index);
-
- final Object candidates= getCandidates(hash);
- if (candidates == null)
- continue;
- else if (candidates instanceof String) {
- String candidate= (String)candidates;
- distance= fDistanceAlgorithm.getDistance(word, candidate);
- if (distance < DISTANCE_THRESHOLD) {
- buffer.setLength(0);
- buffer.append(candidate);
- if (sentence)
- buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0)));
- result.add(new RankedWordProposal(buffer.toString(), -distance));
- }
- continue;
- }
-
- final ArrayList candidateList= (ArrayList)candidates;
- for (int offset= 0; offset < candidateList.size(); offset++) {
-
- String candidate= (String)candidateList.get(offset);
- distance= fDistanceAlgorithm.getDistance(word, candidate);
-
- if (distance < DISTANCE_THRESHOLD) {
-
- buffer.setLength(0);
- buffer.append(candidate);
-
- if (sentence)
- buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0)));
-
- result.add(new RankedWordProposal(buffer.toString(), -distance));
- }
- }
- }
- return result;
- }
-
- /**
- * Returns all approximations that have a phonetic hash with smallest
- * possible distance to the specified word.
- *
- * @param word
- * The word to find the nearest matches for
- * @param sentence
- * <code>true</code> iff the proposals start a new sentence,
- * <code>false</code> otherwise
- * @param result
- * Set of ranked words with smallest possible distance to the
- * specified word
- */
- protected final void getCandidates(final String word, final boolean sentence, final Set result) {
-
- int distance= 0;
- int minimum= Integer.MAX_VALUE;
-
- StringBuffer buffer= new StringBuffer(BUFFER_CAPACITY);
-
- final Object candidates= getCandidates(fHashProvider.getHash(word));
- if (candidates == null)
- return;
- else if (candidates instanceof String) {
- String candidate= (String)candidates;
- distance= fDistanceAlgorithm.getDistance(word, candidate);
- buffer.append(candidate);
- if (sentence)
- buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0)));
- result.add(new RankedWordProposal(buffer.toString(), -distance));
- return;
- }
-
- final ArrayList candidateList= (ArrayList)candidates;
- final ArrayList matches= new ArrayList(candidateList.size());
-
- for (int index= 0; index < candidateList.size(); index++) {
- String candidate= (String)candidateList.get(index);
- distance= fDistanceAlgorithm.getDistance(word, candidate);
-
- if (distance <= minimum) {
-
- if (distance < minimum)
- matches.clear();
-
- buffer.setLength(0);
- buffer.append(candidate);
-
- if (sentence)
- buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0)));
-
- matches.add(new RankedWordProposal(buffer.toString(), -distance));
- minimum= distance;
- }
- }
-
- result.addAll(matches);
- }
-
- /**
- * Tells whether this dictionary is empty.
- *
- * @return <code>true</code> if this dictionary is empty
- *
- */
- protected boolean isEmpty() {
- return fHashBuckets.size() == 0;
- }
-
- /**
- * Returns the used phonetic distance algorithm.
- *
- * @return The phonetic distance algorithm
- */
- protected final IPhoneticDistanceAlgorithm getDistanceAlgorithm() {
- return fDistanceAlgorithm;
- }
-
- /**
- * Returns the used phonetic hash provider.
- *
- * @return The phonetic hash provider
- */
- protected final IPhoneticHashProvider getHashProvider() {
- return fHashProvider;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellDictionary#getProposals(java.lang.String,boolean)
- */
- public Set getProposals(final String word, final boolean sentence) {
-
- try {
-
- if (!fLoaded) {
- synchronized (this) {
- fLoaded= load(getURL());
- if (fLoaded)
- compact();
- }
- }
-
- } catch (MalformedURLException exception) {
- // Do nothing
- }
-
- final String hash= fHashProvider.getHash(word);
- final char[] mutators= fHashProvider.getMutators();
-
- final ArrayList neighborhood= new ArrayList((word.length() + 1) * (mutators.length + 2));
- neighborhood.add(hash);
-
- final Set candidates= getCandidates(word, sentence, neighborhood);
- neighborhood.clear();
-
- char previous= 0;
- char next= 0;
-
- char[] characters= word.toCharArray();
- for (int index= 0; index < word.length() - 1; index++) {
-
- next= characters[index];
- previous= characters[index + 1];
-
- characters[index]= previous;
- characters[index + 1]= next;
-
- neighborhood.add(fHashProvider.getHash(new String(characters)));
-
- characters[index]= next;
- characters[index + 1]= previous;
- }
-
- final String sentinel= word + " "; //$NON-NLS-1$
-
- characters= sentinel.toCharArray();
- int offset= characters.length - 1;
-
- while (true) {
-
- for (int index= 0; index < mutators.length; index++) {
-
- characters[offset]= mutators[index];
- neighborhood.add(fHashProvider.getHash(new String(characters)));
- }
-
- if (offset == 0)
- break;
-
- characters[offset]= characters[offset - 1];
- --offset;
- }
-
- char mutated= 0;
- characters= word.toCharArray();
-
- for (int index= 0; index < word.length(); index++) {
-
- mutated= characters[index];
- for (int mutator= 0; mutator < mutators.length; mutator++) {
-
- characters[index]= mutators[mutator];
- neighborhood.add(fHashProvider.getHash(new String(characters)));
- }
- characters[index]= mutated;
- }
-
- characters= word.toCharArray();
- final char[] deleted= new char[characters.length - 1];
-
- for (int index= 0; index < deleted.length; index++)
- deleted[index]= characters[index];
-
- next= characters[characters.length - 1];
- offset= deleted.length;
-
- while (true) {
-
- neighborhood.add(fHashProvider.getHash(new String(characters)));
- if (offset == 0)
- break;
-
- previous= next;
- next= deleted[offset - 1];
-
- deleted[offset - 1]= previous;
- --offset;
- }
-
- neighborhood.remove(hash);
- final Set matches= getCandidates(word, sentence, neighborhood);
-
- if (matches.size() == 0 && candidates.size() == 0)
- getCandidates(word, sentence, candidates);
-
- candidates.addAll(matches);
-
- return candidates;
- }
-
- /**
- * Returns the URL of the dictionary word list.
- *
- * @throws MalformedURLException
- * if the URL could not be retrieved
- * @return The URL of the dictionary word list
- */
- protected abstract URL getURL() throws MalformedURLException;
-
- /**
- * Hashes the word into the dictionary.
- *
- * @param word
- * The word to hash in the dictionary
- */
- protected final void hashWord(final String word) {
-
- final String hash= fHashProvider.getHash(word);
- Object bucket= fHashBuckets.get(hash);
-
- if (bucket == null) {
- fHashBuckets.put(hash, word);
- } else if (bucket instanceof ArrayList) {
- ((ArrayList)bucket).add(word);
- } else {
- ArrayList list= new ArrayList(BUCKET_CAPACITY);
- list.add(bucket);
- list.add(word);
- fHashBuckets.put(hash, list);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellDictionary#isCorrect(java.lang.String)
- */
- public boolean isCorrect(String word) {
- word= stripNonLetters(word);
- try {
-
- if (!fLoaded) {
- synchronized (this) {
- fLoaded= load(getURL());
- if (fLoaded)
- compact();
- }
- }
-
- } catch (MalformedURLException exception) {
- // Do nothing
- }
-
- final Object candidates= getCandidates(fHashProvider.getHash(word));
- if (candidates == null)
- return false;
- else if (candidates instanceof String) {
- String candidate= (String)candidates;
- if (candidate.equals(word) || candidate.equals(word.toLowerCase()))
- return true;
- return false;
- }
- final ArrayList candidateList= (ArrayList)candidates;
- if (candidateList.contains(word) || candidateList.contains(word.toLowerCase()))
- return true;
-
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellDictionary#setStripNonLetters(boolean)
- *
- */
- public void setStripNonLetters(boolean state) {
- fIsStrippingNonLetters= state;
- }
-
- /**
- * Strips non-letter characters from the given word.
- * <p>
- * This will only happen if the corresponding preference is enabled.
- * </p>
- *
- * @param word the word to strip
- * @return the stripped word
- *
- */
- protected String stripNonLetters(String word) {
- if (!fIsStrippingNonLetters)
- return word;
-
- int i= 0;
- int j= word.length() - 1;
- while (i <= j && !Character.isLetter(word.charAt(i)))
- i++;
- if (i > j)
- return ""; //$NON-NLS-1$
-
- while (j > i && !Character.isLetter(word.charAt(j)))
- j--;
-
- return word.substring(i, j+1);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.ISpellDictionary#isLoaded()
- */
- public final synchronized boolean isLoaded() {
- return fLoaded || fHashBuckets.size() > 0;
- }
-
- /**
- * Loads a dictionary word list from disk.
- *
- * @param url
- * The URL of the word list to load
- * @return <code>true</code> iff the word list could be loaded, <code>false</code>
- * otherwise
- */
- protected synchronized boolean load(final URL url) {
- if (!fMustLoad)
- return fLoaded;
-
- if (url != null) {
- InputStream stream= null;
- int line= 0;
- try {
- stream= url.openStream();
- if (stream != null) {
- String word= null;
-
- // Setup a reader with a decoder in order to read over malformed input if needed.
- CharsetDecoder decoder= Charset.forName(getEncoding()).newDecoder();
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- final BufferedReader reader= new BufferedReader(new InputStreamReader(stream, decoder));
-
- boolean doRead= true;
- while (doRead) {
- try {
- word= reader.readLine();
- } catch (MalformedInputException ex) {
- // Tell the decoder to replace malformed input in order to read the line.
- decoder.onMalformedInput(CodingErrorAction.REPLACE);
- decoder.reset();
- word= reader.readLine();
- decoder.onMalformedInput(CodingErrorAction.REPORT);
-
- String message= Messages.format(JavaUIMessages.AbstractSpellingDictionary_encodingError, new String[] { word, decoder.replacement(), url.toString() });
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, message, ex);
- JavaScriptPlugin.log(status);
-
- doRead= word != null;
- continue;
- }
- doRead= word != null;
- if (doRead)
- hashWord(word);
- }
- return true;
- }
- } catch (FileNotFoundException ex) {
- String urlString= url.toString();
- String lowercaseUrlString= urlString.toLowerCase();
- if (urlString.equals(lowercaseUrlString))
- JavaScriptPlugin.log(ex);
- else
- try {
- return load(new URL(lowercaseUrlString));
- } catch (MalformedURLException e) {
- JavaScriptPlugin.log(e);
- }
- } catch (IOException exception) {
- if (line > 0) {
- String message= Messages.format(JavaUIMessages.AbstractSpellingDictionary_encodingError, new Object[] { new Integer(line), url.toString() });
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.OK, message, exception);
- JavaScriptPlugin.log(status);
- } else
- JavaScriptPlugin.log(exception);
- } finally {
- fMustLoad= false;
- try {
- if (stream != null)
- stream.close();
- } catch (IOException x) {
- }
- }
- }
- return false;
- }
-
- /**
- * Compacts the dictionary.
- *
- *
- */
- private void compact() {
- Iterator iter= fHashBuckets.values().iterator();
- while (iter.hasNext()) {
- Object element= iter.next();
- if (element instanceof ArrayList)
- ((ArrayList)element).trimToSize();
- }
- }
-
- /**
- * Sets the phonetic distance algorithm to use.
- *
- * @param algorithm
- * The phonetic distance algorithm
- */
- protected final void setDistanceAlgorithm(final IPhoneticDistanceAlgorithm algorithm) {
- fDistanceAlgorithm= algorithm;
- }
-
- /**
- * Sets the phonetic hash provider to use.
- *
- * @param provider
- * The phonetic hash provider
- */
- protected final void setHashProvider(final IPhoneticHashProvider provider) {
- fHashProvider= provider;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.ISpellDictionary#unload()
- */
- public synchronized void unload() {
- fLoaded= false;
- fMustLoad= true;
- fHashBuckets.clear();
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.ISpellDictionary#acceptsWords()
- */
- public boolean acceptsWords() {
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellDictionary#addWord(java.lang.String)
- */
- public void addWord(final String word) {
- // Do nothing
- }
-
- /**
- * Returns the encoding of this dictionary.
- *
- * @return the encoding of this dictionary
- *
- */
- protected String getEncoding() {
- String encoding= JavaScriptPlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.SPELLING_USER_DICTIONARY_ENCODING);
- if (encoding == null || encoding.length() == 0)
- encoding= ResourcesPlugin.getEncoding();
- return encoding;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java
deleted file mode 100644
index ee19af09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-/**
- * Default phonetic distance algorithm for English words.
- * <p>
- * This algorithm implements the Levenshtein text edit distance.
- * </p>
- *
- *
- */
-public final class DefaultPhoneticDistanceAlgorithm implements IPhoneticDistanceAlgorithm {
-
- /** The change case cost */
- public static final int COST_CASE= 10;
-
- /** The insert character cost */
- public static final int COST_INSERT= 95;
-
- /** The remove character cost */
- public static final int COST_REMOVE= 95;
-
- /** The substitute characters cost */
- public static final int COST_SUBSTITUTE= 100;
-
- /** The swap characters cost */
- public static final int COST_SWAP= 90;
-
- /*
- * @see org.eclipse.spelling.done.IPhoneticDistanceAlgorithm#getDistance(java.lang.String,java.lang.String)
- */
- public final int getDistance(final String from, final String to) {
-
- final char[] first= (" " + from).toCharArray(); //$NON-NLS-1$
- final char[] second= (" " + to).toCharArray(); //$NON-NLS-1$
-
- final int rows= first.length;
- final int columns= second.length;
-
- final int[][] metric= new int[rows][columns];
- for (int column= 1; column < columns; column++)
- metric[0][column]= metric[0][column - 1] + COST_REMOVE;
-
- for (int row= 1; row < rows; row++)
- metric[row][0]= metric[row - 1][0] + COST_INSERT;
-
- char source, target;
-
- int swap= Integer.MAX_VALUE;
- int change= Integer.MAX_VALUE;
-
- int minimum, diagonal, insert, remove;
- for (int row= 1; row < rows; row++) {
-
- source= first[row];
- for (int column= 1; column < columns; column++) {
-
- target= second[column];
- diagonal= metric[row - 1][column - 1];
-
- if (source == target) {
- metric[row][column]= diagonal;
- continue;
- }
-
- change= Integer.MAX_VALUE;
- if (Character.toLowerCase(source) == Character.toLowerCase(target))
- change= COST_CASE + diagonal;
-
- swap= Integer.MAX_VALUE;
- if (row != 1 && column != 1 && source == second[column - 1] && first[row - 1] == target)
- swap= COST_SWAP + metric[row - 2][column - 2];
-
- minimum= COST_SUBSTITUTE + diagonal;
- if (swap < minimum)
- minimum= swap;
-
- remove= metric[row][column - 1];
- if (COST_REMOVE + remove < minimum)
- minimum= COST_REMOVE + remove;
-
- insert= metric[row - 1][column];
- if (COST_INSERT + insert < minimum)
- minimum= COST_INSERT + insert;
- if (change < minimum)
- minimum= change;
-
- metric[row][column]= minimum;
- }
- }
- return metric[rows - 1][columns - 1];
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java
deleted file mode 100644
index e27ba0f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java
+++ /dev/null
@@ -1,683 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-/**
- * Default phonetic hash provider for english languages.
- * <p>
- * This algorithm uses an adapted version double metaphone algorithm by
- * Lawrence Philips.
- * <p>
- *
- *
- */
-public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider {
-
- private static final String[] meta01= { "ACH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta02= { "BACHER", "MACHER", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta03= { "CAESAR", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta04= { "CHIA", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta05= { "CH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta06= { "CHAE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta07= { "HARAC", "HARIS", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta08= { "HOR", "HYM", "HIA", "HEM", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] meta09= { "CHORE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta10= { "VAN ", "VON ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta11= { "SCH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta12= { "ORCHES", "ARCHIT", "ORCHID", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta13= { "T", "S", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta14= { "A", "O", "U", "E", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] meta15= { "L", "R", "N", "M", "B", "H", "F", "V", "W", " ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$
- private static final String[] meta16= { "MC", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta17= { "CZ", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta18= { "WICZ", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta19= { "CIA", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta20= { "CC", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta21= { "I", "E", "H", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta22= { "HU", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta23= { "UCCEE", "UCCES", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta24= { "CK", "CG", "CQ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta25= { "CI", "CE", "CY", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta26= { "GN", "KN", "PN", "WR", "PS", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- private static final String[] meta27= { " C", " Q", " G", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta28= { "C", "K", "Q", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta29= { "CE", "CI", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta30= { "DG", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta31= { "I", "E", "Y", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta32= { "DT", "DD", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta33= { "B", "H", "D", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta34= { "B", "H", "D", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta35= { "B", "H", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta36= { "C", "G", "L", "R", "T", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- private static final String[] meta37= { "EY", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta38= { "LI", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta39= { "ES", "EP", "EB", "EL", "EY", "IB", "IL", "IN", "IE", "EI", "ER", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
- private static final String[] meta40= { "ER", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta41= { "DANGER", "RANGER", "MANGER", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta42= { "E", "I", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta43= { "RGY", "OGY", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta44= { "E", "I", "Y", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta45= { "AGGI", "OGGI", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta46= { "VAN ", "VON ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta47= { "SCH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta48= { "ET", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta49= { "C", "X", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta50= { "JOSE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta51= { "SAN ", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta52= { "SAN ", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta53= { "JOSE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta54= { "L", "T", "K", "S", "N", "M", "B", "Z", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$
- private static final String[] meta55= { "S", "K", "L", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta56= { "ILLO", "ILLA", "ALLE", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta57= { "AS", "OS", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta58= { "A", "O", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta59= { "ALLE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta60= { "UMB", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta61= { "ER", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta62= { "P", "B", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta63= { "IE", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta64= { "ME", "MA", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta65= { "ISL", "YSL", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta66= { "SUGAR", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta67= { "SH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta68= { "HEIM", "HOEK", "HOLM", "HOLZ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] meta69= { "SIO", "SIA", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta70= { "SIAN", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta71= { "M", "N", "L", "W", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] meta72= { "Z", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta73= { "Z", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta74= { "SC", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta75= { "OO", "ER", "EN", "UY", "ED", "EM", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- private static final String[] meta76= { "ER", "EN", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta77= { "I", "E", "Y", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- private static final String[] meta78= { "AI", "OI", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta79= { "S", "Z", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta80= { "TION", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta81= { "TIA", "TCH", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta82= { "TH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta83= { "TTH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta84= { "OM", "AM", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta85= { "VAN ", "VON ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta86= { "SCH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta87= { "T", "D", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta88= { "WR", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta89= { "WH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta90= { "EWSKI", "EWSKY", "OWSKI", "OWSKY", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] meta91= { "SCH", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String[] meta92= { "WICZ", "WITZ", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta93= { "IAU", "EAU", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta94= { "AU", "OU", "" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- private static final String[] meta95= { "W", "K", "CZ", "WITZ" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- /** The mutator characters */
- private static final char[] MUTATOR_CHARACTERS= { 'A', 'B', 'X', 'S', 'K', 'J', 'T', 'F', 'H', 'L', 'M', 'N', 'P', 'R', '0' };
-
- /** The vowel characters */
- private static final char[] VOWEL_CHARACTERS= new char[] { 'A', 'E', 'I', 'O', 'U', 'Y' };
-
- /**
- * Test whether the specified string contains one of the candidates in the
- * list.
- *
- * @param candidates
- * Array of candidates to check
- * @param token
- * The token to check for occurrences of the candidates
- * @param offset
- * The offset where to begin checking in the string
- * @param length
- * The length of the range in the string to check
- * @return <code>true</code> iff the string contains one of the
- * candidates, <code>false</code> otherwise.
- */
- protected static final boolean hasOneOf(final String[] candidates, final char[] token, final int offset, final int length) {
-
- if (offset < 0 || offset >= token.length || candidates.length == 0)
- return false;
-
- final String checkable= new String(token, offset, length);
- for (int index= 0; index < candidates.length; index++) {
-
- if (candidates[index].equals(checkable))
- return true;
- }
- return false;
- }
-
- /**
- * Test whether the specified token contains one of the candidates in the
- * list.
- *
- * @param candidates
- * Array of candidates to check
- * @param token
- * The token to check for occurrences of the candidates
- * @return <code>true</code> iff the string contains one of the
- * candidates, <code>false</code> otherwise.
- */
- protected static final boolean hasOneOf(final String[] candidates, final String token) {
-
- for (int index= 0; index < candidates.length; index++) {
-
- if (token.indexOf(candidates[index]) >= 0)
- return true;
- }
- return false;
- }
-
- /**
- * Tests whether the specified token contains a vowel at the specified
- * offset.
- *
- * @param token
- * The token to check for a vowel
- * @param offset
- * The offset where to begin checking in the token
- * @param length
- * The length of the range in the token to check
- * @return <code>true</code> iff the token contains a vowel, <code>false</code>
- * otherwise.
- */
- protected static final boolean hasVowel(final char[] token, final int offset, final int length) {
-
- if (offset >= 0 && offset < length) {
-
- final char character= token[offset];
- for (int index= 0; index < VOWEL_CHARACTERS.length; index++) {
-
- if (VOWEL_CHARACTERS[index] == character)
- return true;
- }
- }
- return false;
- }
-
- /*
- * @see org.eclipse.spelling.done.IPhoneticHasher#getHash(java.lang.String)
- */
- public final String getHash(final String word) {
-
- final String input= word.toUpperCase() + " "; //$NON-NLS-1$
- final char[] hashable= input.toCharArray();
-
- final boolean has95= hasOneOf(meta95, input);
- final StringBuffer buffer= new StringBuffer(hashable.length);
-
- int offset= 0;
- if (hasOneOf(meta26, hashable, 0, 2))
- offset += 1;
-
- if (hashable[0] == 'X') {
- buffer.append('S');
- offset += 1;
- }
-
- while (offset < hashable.length) {
-
- switch (hashable[offset]) {
- case 'A' :
- case 'E' :
- case 'I' :
- case 'O' :
- case 'U' :
- case 'Y' :
- if (offset == 0)
- buffer.append('A');
- offset += 1;
- break;
- case 'B' :
- buffer.append('P');
- if (hashable[offset + 1] == 'B')
- offset += 2;
- else
- offset += 1;
- break;
- case 'C' :
- if ((offset > 1) && !hasVowel(hashable, offset - 2, hashable.length) && hasOneOf(meta01, hashable, (offset - 1), 3) && (hashable[offset + 2] != 'I') && (hashable[offset + 2] != 'E') || hasOneOf(meta02, hashable, (offset - 2), 6)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if ((offset == 0) && hasOneOf(meta03, hashable, offset, 6)) {
- buffer.append('S');
- offset += 2;
- break;
- }
- if (hasOneOf(meta04, hashable, offset, 4)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if (hasOneOf(meta05, hashable, offset, 2)) {
- if ((offset > 0) && hasOneOf(meta06, hashable, offset, 4)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if ((offset == 0) && hasOneOf(meta07, hashable, (offset + 1), 5) || hasOneOf(meta08, hashable, offset + 1, 3) && !hasOneOf(meta09, hashable, 0, 5)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if (hasOneOf(meta10, hashable, 0, 4) || hasOneOf(meta11, hashable, 0, 3) || hasOneOf(meta12, hashable, offset - 2, 6) || hasOneOf(meta13, hashable, offset + 2, 1) || (hasOneOf(meta14, hashable, offset - 1, 1) || (offset == 0)) && hasOneOf(meta15, hashable, offset + 2, 1)) {
- buffer.append('K');
- } else {
- if (offset > 0) {
- if (hasOneOf(meta16, hashable, 0, 2))
- buffer.append('K');
- else
- buffer.append('X');
- } else {
- buffer.append('X');
- }
- }
- offset += 2;
- break;
- }
- if (hasOneOf(meta17, hashable, offset, 2) && !hasOneOf(meta18, hashable, offset, 4)) {
- buffer.append('S');
- offset += 2;
- break;
- }
- if (hasOneOf(meta19, hashable, offset, 2)) {
- buffer.append('X');
- offset += 2;
- break;
- }
- if (hasOneOf(meta20, hashable, offset, 2) && !((offset == 1) && hashable[0] == 'M')) {
- if (hasOneOf(meta21, hashable, offset + 2, 1) && !hasOneOf(meta22, hashable, offset + 2, 2)) {
- if (((offset == 1) && (hashable[offset - 1] == 'A')) || hasOneOf(meta23, hashable, (offset - 1), 5))
- buffer.append("KS"); //$NON-NLS-1$
- else
- buffer.append('X');
- offset += 3;
- break;
- } else {
- buffer.append('K');
- offset += 2;
- break;
- }
- }
- if (hasOneOf(meta24, hashable, offset, 2)) {
- buffer.append('K');
- offset += 2;
- break;
- } else if (hasOneOf(meta25, hashable, offset, 2)) {
- buffer.append('S');
- offset += 2;
- break;
- }
- buffer.append('K');
- if (hasOneOf(meta27, hashable, offset + 1, 2))
- offset += 3;
- else if (hasOneOf(meta28, hashable, offset + 1, 1) && !hasOneOf(meta29, hashable, offset + 1, 2))
- offset += 2;
- else
- offset += 1;
- break;
- case '\u00C7' :
- buffer.append('S');
- offset += 1;
- break;
- case 'D' :
- if (hasOneOf(meta30, hashable, offset, 2)) {
- if (hasOneOf(meta31, hashable, offset + 2, 1)) {
- buffer.append('J');
- offset += 3;
- break;
- } else {
- buffer.append("TK"); //$NON-NLS-1$
- offset += 2;
- break;
- }
- }
- buffer.append('T');
- if (hasOneOf(meta32, hashable, offset, 2)) {
- offset += 2;
- } else {
- offset += 1;
- }
- break;
- case 'F' :
- if (hashable[offset + 1] == 'F')
- offset += 2;
- else
- offset += 1;
- buffer.append('F');
- break;
- case 'G' :
- if (hashable[offset + 1] == 'H') {
- if ((offset > 0) && !hasVowel(hashable, offset - 1, hashable.length)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if (offset < 3) {
- if (offset == 0) {
- if (hashable[offset + 2] == 'I')
- buffer.append('J');
- else
- buffer.append('K');
- offset += 2;
- break;
- }
- }
- if ((offset > 1) && hasOneOf(meta33, hashable, offset - 2, 1) || ((offset > 2) && hasOneOf(meta34, hashable, offset - 3, 1)) || ((offset > 3) && hasOneOf(meta35, hashable, offset - 4, 1))) {
- offset += 2;
- break;
- } else {
- if ((offset > 2) && (hashable[offset - 1] == 'U') && hasOneOf(meta36, hashable, offset - 3, 1)) {
- buffer.append('F');
- } else {
- if ((offset > 0) && (hashable[offset - 1] != 'I'))
- buffer.append('K');
- }
- offset += 2;
- break;
- }
- }
- if (hashable[offset + 1] == 'N') {
- if ((offset == 1) && hasVowel(hashable, 0, hashable.length) && !has95) {
- buffer.append("KN"); //$NON-NLS-1$
- } else {
- if (!hasOneOf(meta37, hashable, offset + 2, 2) && (hashable[offset + 1] != 'Y') && !has95) {
- buffer.append("N"); //$NON-NLS-1$
- } else {
- buffer.append("KN"); //$NON-NLS-1$
- }
- }
- offset += 2;
- break;
- }
- if (hasOneOf(meta38, hashable, offset + 1, 2) && !has95) {
- buffer.append("KL"); //$NON-NLS-1$
- offset += 2;
- break;
- }
- if ((offset == 0) && ((hashable[offset + 1] == 'Y') || hasOneOf(meta39, hashable, offset + 1, 2))) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if ((hasOneOf(meta40, hashable, offset + 1, 2) || (hashable[offset + 1] == 'Y')) && !hasOneOf(meta41, hashable, 0, 6) && !hasOneOf(meta42, hashable, offset - 1, 1) && !hasOneOf(meta43, hashable, offset - 1, 3)) {
- buffer.append('K');
- offset += 2;
- break;
- }
- if (hasOneOf(meta44, hashable, offset + 1, 1) || hasOneOf(meta45, hashable, offset - 1, 4)) {
- if (hasOneOf(meta46, hashable, 0, 4) || hasOneOf(meta47, hashable, 0, 3) || hasOneOf(meta48, hashable, offset + 1, 2)) {
- buffer.append('K');
- } else {
- buffer.append('J');
- }
- offset += 2;
- break;
- }
- if (hashable[offset + 1] == 'G')
- offset += 2;
- else
- offset += 1;
- buffer.append('K');
- break;
- case 'H' :
- if (((offset == 0) || hasVowel(hashable, offset - 1, hashable.length)) && hasVowel(hashable, offset + 1, hashable.length)) {
- buffer.append('H');
- offset += 2;
- } else {
- offset += 1;
- }
- break;
- case 'J' :
- if (hasOneOf(meta50, hashable, offset, 4) || hasOneOf(meta51, hashable, 0, 4)) {
- if ((offset == 0) && (hashable[offset + 4] == ' ') || hasOneOf(meta52, hashable, 0, 4)) {
- buffer.append('H');
- } else {
- buffer.append('J');
- }
- offset += 1;
- break;
- }
- if ((offset == 0) && !hasOneOf(meta53, hashable, offset, 4)) {
- buffer.append('J');
- } else {
- if (hasVowel(hashable, offset - 1, hashable.length) && !has95 && ((hashable[offset + 1] == 'A') || hashable[offset + 1] == 'O')) {
- buffer.append('J');
- } else {
- if (offset == (hashable.length - 1)) {
- buffer.append('J');
- } else {
- if (!hasOneOf(meta54, hashable, offset + 1, 1) && !hasOneOf(meta55, hashable, offset - 1, 1)) {
- buffer.append('J');
- }
- }
- }
- }
- if (hashable[offset + 1] == 'J')
- offset += 2;
- else
- offset += 1;
- break;
- case 'K' :
- if (hashable[offset + 1] == 'K')
- offset += 2;
- else
- offset += 1;
- buffer.append('K');
- break;
- case 'L' :
- if (hashable[offset + 1] == 'L') {
- if (((offset == (hashable.length - 3)) && hasOneOf(meta56, hashable, offset - 1, 4)) || ((hasOneOf(meta57, hashable, (hashable.length - 1) - 1, 2) || hasOneOf(meta58, hashable, hashable.length - 1, 1)) && hasOneOf(meta59, hashable, offset - 1, 4))) {
- buffer.append('L');
- offset += 2;
- break;
- }
- offset += 2;
- } else
- offset += 1;
- buffer.append('L');
- break;
- case 'M' :
- if ((hasOneOf(meta60, hashable, offset - 1, 3) && (((offset + 1) == (hashable.length - 1)) || hasOneOf(meta61, hashable, offset + 2, 2))) || (hashable[offset + 1] == 'M'))
- offset += 2;
- else
- offset += 1;
- buffer.append('M');
- break;
- case 'N' :
- if (hashable[offset + 1] == 'N')
- offset += 2;
- else
- offset += 1;
- buffer.append('N');
- break;
- case '\u00D1' :
- offset += 1;
- buffer.append('N');
- break;
- case 'P' :
- if (hashable[offset + 1] == 'N') {
- buffer.append('F');
- offset += 2;
- break;
- }
- if (hasOneOf(meta62, hashable, offset + 1, 1))
- offset += 2;
- else
- offset += 1;
- buffer.append('P');
- break;
- case 'Q' :
- if (hashable[offset + 1] == 'Q')
- offset += 2;
- else
- offset += 1;
- buffer.append('K');
- break;
- case 'R' :
- if (!((offset == (hashable.length - 1)) && !has95 && hasOneOf(meta63, hashable, offset - 2, 2) && !hasOneOf(meta64, hashable, offset - 4, 2)))
- buffer.append('R');
- if (hashable[offset + 1] == 'R')
- offset += 2;
- else
- offset += 1;
- break;
- case 'S' :
- if (hasOneOf(meta65, hashable, offset - 1, 3)) {
- offset += 1;
- break;
- }
- if ((offset == 0) && hasOneOf(meta66, hashable, offset, 5)) {
- buffer.append('X');
- offset += 1;
- break;
- }
- if (hasOneOf(meta67, hashable, offset, 2)) {
- if (hasOneOf(meta68, hashable, offset + 1, 4))
- buffer.append('S');
- else
- buffer.append('X');
- offset += 2;
- break;
- }
- if (hasOneOf(meta69, hashable, offset, 3) || hasOneOf(meta70, hashable, offset, 4)) {
- buffer.append('S');
- offset += 3;
- break;
- }
- if (((offset == 0) && hasOneOf(meta71, hashable, offset + 1, 1)) || hasOneOf(meta72, hashable, offset + 1, 1)) {
- buffer.append('S');
- if (hasOneOf(meta73, hashable, offset + 1, 1))
- offset += 2;
- else
- offset += 1;
- break;
- }
- if (hasOneOf(meta74, hashable, offset, 2)) {
- if (hashable[offset + 2] == 'H')
- if (hasOneOf(meta75, hashable, offset + 3, 2)) {
- if (hasOneOf(meta76, hashable, offset + 3, 2)) {
- buffer.append("X"); //$NON-NLS-1$
- } else {
- buffer.append("SK"); //$NON-NLS-1$
- }
- offset += 3;
- break;
- } else {
- buffer.append('X');
- offset += 3;
- break;
- }
- if (hasOneOf(meta77, hashable, offset + 2, 1)) {
- buffer.append('S');
- offset += 3;
- break;
- }
- buffer.append("SK"); //$NON-NLS-1$
- offset += 3;
- break;
- }
- if (!((offset == (hashable.length - 1)) && hasOneOf(meta78, hashable, offset - 2, 2)))
- buffer.append('S');
- if (hasOneOf(meta79, hashable, offset + 1, 1))
- offset += 2;
- else
- offset += 1;
- break;
- case 'T' :
- if (hasOneOf(meta80, hashable, offset, 4)) {
- buffer.append('X');
- offset += 3;
- break;
- }
- if (hasOneOf(meta81, hashable, offset, 3)) {
- buffer.append('X');
- offset += 3;
- break;
- }
- if (hasOneOf(meta82, hashable, offset, 2) || hasOneOf(meta83, hashable, offset, 3)) {
- if (hasOneOf(meta84, hashable, (offset + 2), 2) || hasOneOf(meta85, hashable, 0, 4) || hasOneOf(meta86, hashable, 0, 3)) {
- buffer.append('T');
- } else {
- buffer.append('0');
- }
- offset += 2;
- break;
- }
- if (hasOneOf(meta87, hashable, offset + 1, 1)) {
- offset += 2;
- } else
- offset += 1;
- buffer.append('T');
- break;
- case 'V' :
- if (hashable[offset + 1] == 'V')
- offset += 2;
- else
- offset += 1;
- buffer.append('F');
- break;
- case 'W' :
- if (hasOneOf(meta88, hashable, offset, 2)) {
- buffer.append('R');
- offset += 2;
- break;
- }
- if ((offset == 0) && (hasVowel(hashable, offset + 1, hashable.length) || hasOneOf(meta89, hashable, offset, 2))) {
- buffer.append('A');
- }
- if (((offset == (hashable.length - 1)) && hasVowel(hashable, offset - 1, hashable.length)) || hasOneOf(meta90, hashable, offset - 1, 5) || hasOneOf(meta91, hashable, 0, 3)) {
- buffer.append('F');
- offset += 1;
- break;
- }
- if (hasOneOf(meta92, hashable, offset, 4)) {
- buffer.append("TS"); //$NON-NLS-1$
- offset += 4;
- break;
- }
- offset += 1;
- break;
- case 'X' :
- if (!((offset == (hashable.length - 1)) && (hasOneOf(meta93, hashable, offset - 3, 3) || hasOneOf(meta94, hashable, offset - 2, 2))))
- buffer.append("KS"); //$NON-NLS-1$
- if (hasOneOf(meta49, hashable, offset + 1, 1))
- offset += 2;
- else
- offset += 1;
- break;
- case 'Z' :
- if (hashable[offset + 1] == 'H') {
- buffer.append('J');
- offset += 2;
- break;
- } else {
- buffer.append('S');
- }
- if (hashable[offset + 1] == 'Z')
- offset += 2;
- else
- offset += 1;
- break;
- default :
- offset += 1;
- }
- }
- return buffer.toString();
- }
-
- /*
- * @see org.eclipse.spelling.done.IPhoneticHasher#getMutators()
- */
- public final char[] getMutators() {
- return MUTATOR_CHARACTERS;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java
deleted file mode 100644
index 6b6b6655..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java
+++ /dev/null
@@ -1,375 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Default spell checker for standard text.
- *
- *
- */
-public class DefaultSpellChecker implements ISpellChecker {
-
- /** Array of URL prefixes */
- public static final String[] URL_PREFIXES= new String[] { "http://", "https://", "www.", "ftp://", "ftps://", "news://", "mailto://" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-
- /**
- * Does this word contain digits?
- *
- * @param word the word to check
- * @return <code>true</code> iff this word contains digits, <code>false></code> otherwise
- */
- protected static boolean isDigits(final String word) {
-
- for (int index= 0; index < word.length(); index++) {
-
- if (Character.isDigit(word.charAt(index)))
- return true;
- }
- return false;
- }
-
- /**
- * Does this word contain mixed-case letters?
- *
- * @param word
- * The word to check
- * @param sentence
- * <code>true</code> iff the specified word starts a new
- * sentence, <code>false</code> otherwise
- * @return <code>true</code> iff the contains mixed-case letters, <code>false</code>
- * otherwise
- */
- protected static boolean isMixedCase(final String word, final boolean sentence) {
-
- final int length= word.length();
- boolean upper= Character.isUpperCase(word.charAt(0));
-
- if (sentence && upper && (length > 1))
- upper= Character.isUpperCase(word.charAt(1));
-
- if (upper) {
-
- for (int index= length - 1; index > 0; index--) {
- if (Character.isLowerCase(word.charAt(index)))
- return true;
- }
- } else {
-
- for (int index= length - 1; index > 0; index--) {
- if (Character.isUpperCase(word.charAt(index)))
- return true;
- }
- }
- return false;
- }
-
- /**
- * Does this word contain upper-case letters only?
- *
- * @param word
- * The word to check
- * @return <code>true</code> iff this word only contains upper-case
- * letters, <code>false</code> otherwise
- */
- protected static boolean isUpperCase(final String word) {
-
- for (int index= word.length() - 1; index >= 0; index--) {
-
- if (Character.isLowerCase(word.charAt(index)))
- return false;
- }
- return true;
- }
-
- /**
- * Does this word look like an URL?
- *
- * @param word
- * The word to check
- * @return <code>true</code> iff this word looks like an URL, <code>false</code>
- * otherwise
- */
- protected static boolean isUrl(final String word) {
-
- for (int index= 0; index < URL_PREFIXES.length; index++) {
-
- if (word.startsWith(URL_PREFIXES[index]))
- return true;
- }
- return false;
- }
-
- /**
- * The dictionaries to use for spell checking. Synchronized to avoid
- * concurrent modifications.
- */
- private final Set fDictionaries= Collections.synchronizedSet(new HashSet());
-
- /**
- * The words to be ignored. Synchronized to avoid concurrent modifications.
- */
- private final Set fIgnored= Collections.synchronizedSet(new HashSet());
-
- /**
- * The spell event listeners. Synchronized to avoid concurrent
- * modifications.
- */
- private final Set fListeners= Collections.synchronizedSet(new HashSet());
-
- /**
- * The preference store. Assumes the <code>IPreferenceStore</code>
- * implementation is thread safe.
- */
- private final IPreferenceStore fPreferences;
-
- /**
- * The locale of this checker.
- *
- */
- private Locale fLocale;
-
- /**
- * Creates a new default spell checker.
- *
- * @param store the preference store for this spell checker
- * @param locale the locale
- */
- public DefaultSpellChecker(IPreferenceStore store, Locale locale) {
- Assert.isLegal(store != null);
- Assert.isLegal(locale != null);
-
- fPreferences= store;
- fLocale= locale;
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#addDictionary(org.eclipse.spelling.done.ISpellDictionary)
- */
- public final void addDictionary(final ISpellDictionary dictionary) {
- // synchronizing is necessary as this is a write access
- fDictionaries.add(dictionary);
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#addListener(org.eclipse.spelling.done.ISpellEventListener)
- */
- public final void addListener(final ISpellEventListener listener) {
- // synchronizing is necessary as this is a write access
- fListeners.add(listener);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.ISpellChecker#acceptsWords()
- */
- public boolean acceptsWords() {
- // synchronizing might not be needed here since acceptWords is
- // a read-only access and only called in the same thread as
- // the modifying methods add/checkWord (?)
- Set copy;
- synchronized (fDictionaries) {
- copy= new HashSet(fDictionaries);
- }
-
- ISpellDictionary dictionary= null;
- for (final Iterator iterator= copy.iterator(); iterator.hasNext();) {
-
- dictionary= (ISpellDictionary)iterator.next();
- if (dictionary.acceptsWords())
- return true;
- }
- return false;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellChecker#addWord(java.lang.String)
- */
- public void addWord(final String word) {
- // synchronizing is necessary as this is a write access
- Set copy;
- synchronized (fDictionaries) {
- copy= new HashSet(fDictionaries);
- }
-
- final String addable= word.toLowerCase();
- for (final Iterator iterator= copy.iterator(); iterator.hasNext();) {
- ISpellDictionary dictionary= (ISpellDictionary)iterator.next();
- if (dictionary.acceptsWords())
- dictionary.addWord(addable);
- }
-
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.ISpellChecker#checkWord(java.lang.String)
- */
- public final void checkWord(final String word) {
- // synchronizing is necessary as this is a write access
- fIgnored.remove(word.toLowerCase());
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#execute(org.eclipse.spelling.ISpellCheckTokenizer)
- */
- public void execute(final ISpellCheckIterator iterator) {
-
- final boolean ignoreDigits= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_DIGITS);
- final boolean ignoreMixed= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_MIXED);
- final boolean ignoreSentence= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_SENTENCE);
- final boolean ignoreUpper= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_UPPER);
- final boolean ignoreURLS= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_URLS);
- final boolean ignoreNonLetters= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_NON_LETTERS);
- final boolean ignoreSingleLetters= fPreferences.getBoolean(PreferenceConstants.SPELLING_IGNORE_SINGLE_LETTERS);
-
- iterator.setIgnoreSingleLetters(ignoreSingleLetters);
-
- Iterator iter= fDictionaries.iterator();
- while (iter.hasNext())
- ((ISpellDictionary)iter.next()).setStripNonLetters(ignoreNonLetters);
-
- String word= null;
- boolean starts= false;
-
- while (iterator.hasNext()) {
-
- word= (String)iterator.next();
- if (word != null) {
-
- // synchronizing is necessary as this is called inside the reconciler
- if (!fIgnored.contains(word)) {
-
- starts= iterator.startsSentence();
- if (!isCorrect(word)) {
-
- boolean isMixed= isMixedCase(word, true);
- boolean isUpper= isUpperCase(word);
- boolean isDigits= isDigits(word);
- boolean isURL= isUrl(word);
-
- if ( !ignoreMixed && isMixed || !ignoreUpper && isUpper || !ignoreDigits && isDigits || !ignoreURLS && isURL || !(isMixed || isUpper || isDigits || isURL))
- fireEvent(new SpellEvent(this, word, iterator.getBegin(), iterator.getEnd(), starts, false));
-
- } else {
-
- if (!ignoreSentence && starts && Character.isLowerCase(word.charAt(0)))
- fireEvent(new SpellEvent(this, word, iterator.getBegin(), iterator.getEnd(), true, true));
- }
- }
- }
- }
- }
-
- /**
- * Fires the specified event.
- *
- * @param event
- * Event to fire
- */
- protected final void fireEvent(final ISpellEvent event) {
- // synchronizing is necessary as this is called from execute
- Set copy;
- synchronized (fListeners) {
- copy= new HashSet(fListeners);
- }
- for (final Iterator iterator= copy.iterator(); iterator.hasNext();) {
- ((ISpellEventListener)iterator.next()).handle(event);
- }
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#getProposals(java.lang.String,boolean)
- */
- public Set getProposals(final String word, final boolean sentence) {
-
- // synchronizing might not be needed here since getProposals is
- // a read-only access and only called in the same thread as
- // the modifing methods add/removeDictionary (?)
- Set copy;
- synchronized (fDictionaries) {
- copy= new HashSet(fDictionaries);
- }
-
- ISpellDictionary dictionary= null;
- final HashSet proposals= new HashSet();
-
- for (final Iterator iterator= copy.iterator(); iterator.hasNext();) {
-
- dictionary= (ISpellDictionary)iterator.next();
- proposals.addAll(dictionary.getProposals(word, sentence));
- }
- return proposals;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellChecker#ignoreWord(java.lang.String)
- */
- public final void ignoreWord(final String word) {
- // synchronizing is necessary as this is a write access
- fIgnored.add(word.toLowerCase());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellChecker#isCorrect(java.lang.String)
- */
- public final boolean isCorrect(final String word) {
- // synchronizing is necessary as this is called from execute
- Set copy;
- synchronized (fDictionaries) {
- copy= new HashSet(fDictionaries);
- }
-
- if (fIgnored.contains(word.toLowerCase()))
- return true;
-
- ISpellDictionary dictionary= null;
- for (final Iterator iterator= copy.iterator(); iterator.hasNext();) {
-
- dictionary= (ISpellDictionary)iterator.next();
- if (dictionary.isCorrect(word))
- return true;
- }
- return false;
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#removeDictionary(org.eclipse.spelling.done.ISpellDictionary)
- */
- public final void removeDictionary(final ISpellDictionary dictionary) {
- // synchronizing is necessary as this is a write access
- fDictionaries.remove(dictionary);
- }
-
- /*
- * @see org.eclipse.spelling.done.ISpellChecker#removeListener(org.eclipse.spelling.done.ISpellEventListener)
- */
- public final void removeListener(final ISpellEventListener listener) {
- // synchronizing is necessary as this is a write access
- fListeners.remove(listener);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellChecker#getLocale()
- *
- */
- public Locale getLocale() {
- return fLocale;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java
deleted file mode 100644
index 93ebff23..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-/**
- * Interface of algorithms to compute the phonetic distance between two words.
- *
- *
- */
-public interface IPhoneticDistanceAlgorithm {
-
- /**
- * Returns the non-negative phonetic distance between two words
- *
- * @param from
- * The first word
- * @param to
- * The second word
- * @return The non-negative phonetic distance between the words.
- */
- public int getDistance(String from, String to);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java
deleted file mode 100644
index 3de23a26..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-/**
- * Interface of hashers to compute the phonetic hash for a word.
- *
- *
- */
-public interface IPhoneticHashProvider {
-
- /**
- * Returns the phonetic hash for the word.
- *
- * @param word
- * The word to get the phonetic hash for
- * @return The phonetic hash for the word
- */
- public String getHash(String word);
-
- /**
- * Returns an array of characters to compute possible mutations.
- *
- * @return Array of possible mutator characters
- */
- public char[] getMutators();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java
deleted file mode 100644
index d7810148..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Locale;
-
-/**
- * Interface for a spell check engine.
- * <p>
- * This engine can be configured with multiple
- * dictionaries.
- * </p>
- *
- *
- */
-public interface ISpellCheckEngine {
-
- /**
- * Returns a spell checker configured with the global
- * dictionaries and the locale dictionary that correspond to the current
- * {@linkplain org.eclipse.wst.jsdt.ui.PreferenceConstants#SPELLING_LOCALE locale preference}.
- * <p>
- * <strong>Note:</strong> Changes to the spelling engine dictionaries
- * are not propagated to this spell checker.</p>
- *
- * @return a configured instance of the spell checker or <code>null</code> if none
- * @throws IllegalStateException if called after being shut down
- */
- ISpellChecker getSpellChecker() throws IllegalStateException;
-
- /**
- * Returns the locale of the current spell check engine.
- *
- * @return the locale of the current spell check engine
- */
- Locale getLocale();
-
- /**
- * Registers a global dictionary.
- *
- * @param dictionary the global dictionary to register
- */
- void registerGlobalDictionary(ISpellDictionary dictionary);
-
- /**
- * Registers a dictionary tuned for the specified locale with this engine.
- *
- * @param locale
- * The locale to register the dictionary with
- * @param dictionary
- * The dictionary to register
- */
- void registerDictionary(Locale locale, ISpellDictionary dictionary);
-
- /**
- * Shuts down this spell check engine and its associated components.
- * <p>
- * Further calls to this engine result in exceptions.
- * </p>
- */
- void shutdown();
-
- /**
- * Unregisters a dictionary previously registered either by a call to
- * <code>registerDictionary(Locale,ISpellDictionary)</code> or <code>registerDictionary(ISpellDictionary)</code>.
- * <p>
- * If the dictionary was not registered before, nothing happens.</p>
- *
- * @param dictionary the dictionary to unregister
- */
- void unregisterDictionary(ISpellDictionary dictionary);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java
deleted file mode 100644
index f2af6386..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Iterator;
-
-/**
- * Interface for iterators used for spell checking.
- *
- *
- */
-public interface ISpellCheckIterator extends Iterator {
-
- /**
- * Returns the begin index (inclusive) of the current word.
- *
- * @return The begin index of the current word
- */
- public int getBegin();
-
- /**
- * Returns the end index (exclusive) of the current word.
- *
- * @return The end index of the current word
- */
- public int getEnd();
-
- /**
- * Does the current word start a new sentence?
- *
- * @return <code>true<code> iff the current word starts a new sentence, <code>false</code> otherwise
- */
- public boolean startsSentence();
-
- /**
- * Tells whether to ignore single letters
- * from being checked.
- *
- *
- * @param state <code>true</code> if single letters should be ignored
- */
- public void setIgnoreSingleLetters(boolean state);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java
deleted file mode 100644
index 5c5e9f7f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Locale;
-import java.util.Set;
-
-/**
- * Interface for spell checkers.
- *
- *
- */
-public interface ISpellChecker {
-
- /**
- * Adds a dictionary to the list of active dictionaries.
- *
- * @param dictionary
- * The dictionary to add
- */
- void addDictionary(ISpellDictionary dictionary);
-
- /**
- * Adds a spell event listener to the active listeners.
- *
- * @param listener
- * The listener to add
- */
- void addListener(ISpellEventListener listener);
-
- /**
- * Returns whether this spell checker accepts word additions.
- *
- * @return <code>true</code> if word additions are accepted, <code>false</code> otherwise
- */
- boolean acceptsWords();
-
- /**
- * Adds the specified word to the set of correct words.
- *
- * @param word
- * The word to add to the set of correct words
- */
- void addWord(String word);
-
- /**
- * Checks the specified word until calling <code>ignoreWord(String)</code>.
- *
- * @param word
- * The word to check
- */
- void checkWord(String word);
-
- /**
- * Checks the spelling with the spell check iterator. Implementations must
- * be thread safe as this may be called inside a reconciler thread.
- *
- * @param iterator
- * The iterator to use for spell checking
- */
- void execute(ISpellCheckIterator iterator);
-
- /**
- * Returns the ranked proposals for a word.
- *
- * @param word
- * The word to retrieve the proposals for
- * @param sentence
- * <code>true</code> iff the proposals should start a
- * sentence, <code>false</code> otherwise
- * @return Set of ranked proposals for the word
- */
- Set getProposals(String word, boolean sentence);
-
- /**
- * Ignores the specified word until calling <code>checkWord(String)</code>.
- *
- * @param word
- * The word to ignore
- */
- void ignoreWord(String word);
-
- /**
- * Is the specified word correctly spelled? Implementations must be thread
- * safe as this may be called from within a reconciler thread.
- *
- * @param word
- * The word to check its spelling
- * @return <code>true</code> iff the word is correctly spelled, <code>false</code>
- * otherwise
- */
- boolean isCorrect(String word);
-
- /**
- * Remove a dictionary from the list of active dictionaries.
- *
- * @param dictionary
- * The dictionary to remove
- */
- void removeDictionary(ISpellDictionary dictionary);
-
- /**
- * Removes a spell event listener from the active listeners.
- *
- * @param listener
- * The listener to remove
- */
- void removeListener(ISpellEventListener listener);
-
- /**
- * Returns the current locale of the spell check engine.
- *
- * @return The current locale of the engine
- *
- */
- Locale getLocale();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java
deleted file mode 100644
index 96ac4d8f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Set;
-
-/**
- * Interface of dictionaries to use for spell checking.
- *
- *
- */
-public interface ISpellDictionary {
-
- /**
- * Returns whether this dictionary accepts new words.
- *
- * @return <code>true</code> if this dictionary accepts new words, <code>false</code> otherwise
- */
- public boolean acceptsWords();
-
- /**
- * Externalizes the specified word.
- *
- * @param word
- * The word to externalize in the dictionary
- */
- public void addWord(String word);
-
- /**
- * Returns the ranked word proposals for an incorrectly spelled word.
- *
- * @param word
- * The word to retrieve the proposals for
- * @param sentence
- * <code>true</code> iff the proposals start a new sentence,
- * <code>false</code> otherwise
- * @return Array of ranked word proposals
- */
- public Set getProposals(String word, boolean sentence);
-
- /**
- * Is the specified word correctly spelled?
- *
- * @param word the word to spell check
- * @return <code>true</code> iff this word is correctly spelled, <code>false</code> otherwise
- */
- public boolean isCorrect(String word);
-
- /**
- * Is the dictionary loaded?
- *
- * @return <code>true</code> iff it is loaded, <code>false</code> otherwise
- */
- public boolean isLoaded();
-
- /**
- * Empties the dictionary.
- */
- public void unload();
-
- /**
- * Tells whether to strip non-letters from word boundaries.
- *
- * @param state <code>true</code> if non-letters should be stripped
- *
- */
- public void setStripNonLetters(boolean state);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java
deleted file mode 100644
index c087146f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Set;
-
-/**
- * Event fired by spell checkers.
- *
- *
- */
-public interface ISpellEvent {
-
- /**
- * Returns the begin index of the incorrectly spelled word.
- *
- * @return The begin index of the word
- */
- public int getBegin();
-
- /**
- * Returns the end index of the incorrectly spelled word.
- *
- * @return The end index of the word
- */
- public int getEnd();
-
- /**
- * Returns the proposals for the incorrectly spelled word.
- *
- * @return Array of proposals for the word
- */
- public Set getProposals();
-
- /**
- * Returns the incorrectly spelled word.
- *
- * @return The incorrect word
- */
- public String getWord();
-
- /**
- * Was the incorrectly spelled word found in the dictionary?
- *
- * @return <code>true</code> iff the word was found, <code>false</code> otherwise
- */
- public boolean isMatch();
-
- /**
- * Does the incorrectly spelled word start a new sentence?
- *
- * @return <code>true<code> iff the word starts a new sentence, <code>false</code> otherwise
- */
- public boolean isStart();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java
deleted file mode 100644
index 149ffe25..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-
-/**
- * Interface for spell event listeners.
- *
- *
- */
-public interface ISpellEventListener {
-
- /**
- * Handles a spell event.
- *
- * @param event
- * Event to handle
- */
- public void handle(ISpellEvent event);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java
deleted file mode 100644
index f627f67d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Locale;
-
-/**
- * Platform wide read-only locale sensitive dictionary for spell checking.
- *
- *
- */
-public class LocaleSensitiveSpellDictionary extends AbstractSpellDictionary {
-
- /** The locale of this dictionary */
- private final Locale fLocale;
-
- /** The location of the dictionaries */
- private final URL fLocation;
-
- /**
- * Creates a new locale sensitive spell dictionary.
- *
- * @param locale
- * The locale for this dictionary
- * @param location
- * The location of the locale sensitive dictionaries
- */
- public LocaleSensitiveSpellDictionary(final Locale locale, final URL location) {
- fLocation= location;
- fLocale= locale;
- }
-
- /**
- * Returns the locale of this dictionary.
- *
- * @return The locale of this dictionary
- */
- public final Locale getLocale() {
- return fLocale;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getURL()
- */
- protected final URL getURL() throws MalformedURLException {
- return new URL(fLocation, fLocale.toString() + ".dictionary"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java
deleted file mode 100644
index a25dab00..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-/**
- * Persistent modifiable word-list based dictionary.
- *
- *
- */
-public class PersistentSpellDictionary extends AbstractSpellDictionary {
-
- /** The word list location */
- private final URL fLocation;
-
- /**
- * Creates a new persistent spell dictionary.
- *
- * @param url
- * The URL of the word list for this dictionary
- */
- public PersistentSpellDictionary(final URL url) {
- fLocation= url;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.spelling.engine.AbstractSpellDictionary#acceptsWords()
- */
- public boolean acceptsWords() {
- return true;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellDictionary#addWord(java.lang.String)
- */
- public void addWord(final String word) {
- if (isCorrect(word))
- return;
-
- OutputStreamWriter writer= null;
- try {
- Charset charset= Charset.forName(getEncoding());
- ByteBuffer byteBuffer= charset.encode(word + "\n"); //$NON-NLS-1$
- int size= byteBuffer.limit();
- final byte[] byteArray;
- if (byteBuffer.hasArray())
- byteArray= byteBuffer.array();
- else {
- byteArray= new byte[size];
- byteBuffer.get(byteArray);
- }
-
- FileOutputStream fileStream= new FileOutputStream(fLocation.getPath(), true);
-
- // Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
- int bomCutSize= 0;
- if (!isEmpty() && "UTF-16".equals(charset.name())) //$NON-NLS-1$
- bomCutSize= 2;
-
- fileStream.write(byteArray, bomCutSize, size - bomCutSize);
- } catch (IOException exception) {
- JavaScriptPlugin.log(exception);
- return;
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (IOException e) {
- }
- }
-
- hashWord(word);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getURL()
- */
- protected final URL getURL() {
- return fLocation;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java
deleted file mode 100644
index a19d721f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-/**
- * Ranked word proposal for quick fix and content assist.
- *
- *
- */
-public class RankedWordProposal implements Comparable {
-
- /** The word rank */
- private int fRank;
-
- /** The word text */
- private final String fText;
-
- /**
- * Creates a new ranked word proposal.
- *
- * @param text
- * The text of this proposal
- * @param rank
- * The rank of this proposal
- */
- public RankedWordProposal(final String text, final int rank) {
- fText= text;
- fRank= rank;
- }
-
- /*
- * @see java.lang.Comparable#compareTo(java.lang.Object)
- */
- public final int compareTo(Object object) {
-
- final RankedWordProposal word= (RankedWordProposal)object;
- final int rank= word.getRank();
-
- if (fRank < rank)
- return -1;
-
- if (fRank > rank)
- return 1;
-
- return 0;
- }
-
- /*
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public final boolean equals(Object object) {
-
- if (object instanceof RankedWordProposal)
- return object.hashCode() == hashCode();
-
- return false;
- }
-
- /**
- * Returns the rank of the word
- *
- * @return The rank of the word
- */
- public final int getRank() {
- return fRank;
- }
-
- /**
- * Returns the text of this word.
- *
- * @return The text of this word
- */
- public final String getText() {
- return fText;
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public final int hashCode() {
- return fText.hashCode();
- }
-
- /**
- * Sets the rank of the word.
- *
- * @param rank
- * The rank to set
- */
- public final void setRank(final int rank) {
- fRank= rank;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java
deleted file mode 100644
index a4f38c2c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.spelling.engine;
-
-import java.util.Set;
-
-/**
- * Spell event fired for words detected by a spell check iterator.
- *
- *
- */
-public class SpellEvent implements ISpellEvent {
-
- /** The begin index of the word in the spell checkable medium */
- private final int fBegin;
-
- /** The spell checker that causes the event */
- private final ISpellChecker fChecker;
-
- /** The end index of the word in the spell checkable medium */
- private final int fEnd;
-
- /** Was the word found in the dictionary? */
- private final boolean fMatch;
-
- /** Does the word start a new sentence? */
- private final boolean fSentence;
-
- /** The word that causes the spell event */
- private final String fWord;
-
- /**
- * Creates a new spell event.
- *
- * @param checker
- * The spell checker that causes the event
- * @param word
- * The word that causes the event
- * @param begin
- * The begin index of the word in the spell checkable medium
- * @param end
- * The end index of the word in the spell checkable medium
- * @param sentence
- * <code>true</code> iff the word starts a new sentence,
- * <code>false</code> otherwise
- * @param match
- * <code>true</code> iff the word was found in the dictionary,
- * <code>false</code> otherwise
- */
- protected SpellEvent(final ISpellChecker checker, final String word, final int begin, final int end, final boolean sentence, final boolean match) {
- fChecker= checker;
- fEnd= end;
- fBegin= begin;
- fWord= word;
- fSentence= sentence;
- fMatch= match;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#getBegin()
- */
- public final int getBegin() {
- return fBegin;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#getEnd()
- */
- public final int getEnd() {
- return fEnd;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#getProposals()
- */
- public final Set getProposals() {
- return fChecker.getProposals(fWord, fSentence);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#getWord()
- */
- public final String getWord() {
- return fWord;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#isMatch()
- */
- public final boolean isMatch() {
- return fMatch;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.spelling.engine.ISpellEvent#isStart()
- */
- public final boolean isStart() {
- return fSentence;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java
deleted file mode 100644
index e3391323..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IPositionUpdater;
-import org.eclipse.jface.text.Position;
-
-/**
- * Position updater that takes any change in [position.offset, position.offset + position.length] as
- * belonging to the position.
- *
- *
- */
-class InclusivePositionUpdater implements IPositionUpdater {
-
- /** The position category. */
- private final String fCategory;
-
- /**
- * Creates a new updater for the given <code>category</code>.
- *
- * @param category the new category.
- */
- public InclusivePositionUpdater(String category) {
- fCategory= category;
- }
-
- /*
- * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent)
- */
- public void update(DocumentEvent event) {
-
- int eventOffset= event.getOffset();
- int eventOldLength= event.getLength();
- int eventNewLength= event.getText() == null ? 0 : event.getText().length();
- int deltaLength= eventNewLength - eventOldLength;
-
- try {
- Position[] positions= event.getDocument().getPositions(fCategory);
-
- for (int i= 0; i != positions.length; i++) {
-
- Position position= positions[i];
-
- if (position.isDeleted())
- continue;
-
- int offset= position.getOffset();
- int length= position.getLength();
- int end= offset + length;
-
- if (offset > eventOffset + eventOldLength)
- // position comes way
- // after change - shift
- position.setOffset(offset + deltaLength);
- else if (end < eventOffset) {
- // position comes way before change -
- // leave alone
- } else if (offset <= eventOffset && end >= eventOffset + eventOldLength) {
- // event completely internal to the position - adjust length
- position.setLength(length + deltaLength);
- } else if (offset < eventOffset) {
- // event extends over end of position - adjust length
- int newEnd= eventOffset + eventNewLength;
- position.setLength(newEnd - offset);
- } else if (end > eventOffset + eventOldLength) {
- // event extends from before position into it - adjust offset
- // and length
- // offset becomes end of event, length ajusted acordingly
- // we want to recycle the overlapping part
- position.setOffset(eventOffset);
- int deleted= eventOffset + eventOldLength - offset;
- position.setLength(length - deleted + eventNewLength);
- } else {
- // event consumes the position - delete it
- position.delete();
- }
- }
- } catch (BadPositionCategoryException e) {
- // ignore and return
- }
- }
-
- /**
- * Returns the position category.
- *
- * @return the position category
- */
- public String getCategory() {
- return fCategory;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java
deleted file mode 100644
index 41dfc204..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.jface.text.templates.TemplateVariableType;
-
-
-/**
- * {@link MultiVariable}s can store multiple sets of data; the currently active set is determined
- * by the active <em>key</em>. The key may be set via {@link #setKey(Object)}. Data sets are
- * opaque {@link Object} arrays that are converted to the {@link String} values expected by
- * {@link TemplateVariable} using {@link Object#toString() toString}. The
- * {@link #getCurrentChoice() choice} of a master variable is the {@link #setKey(Object) key} for
- * the slave variable.
- */
-public class MultiVariable extends TemplateVariable {
- private static final Object DEFAULT_KEY= new Object();
-
- private final Map fValueMap= new HashMap(); // <Object, Object[]>
- /** The master key defining the active set. */
- private Object fKey;
- /** The currently active object. */
- private Object fCurrentChoice;
-
- public MultiVariable(TemplateVariableType type, String name, int[] offsets) {
- super(type, name, name, offsets);
- fKey= DEFAULT_KEY;
- fValueMap.put(fKey, new String[] { name });
- fCurrentChoice= getChoices()[0];
- }
-
- /**
- * Sets the values of this variable under a specific key.
- *
- * @param key the key for which the values are valid
- * @param values the possible values of this variable
- */
- public void setChoices(Object key, Object[] values) {
- Assert.isNotNull(key);
- Assert.isTrue(values.length > 0);
- // no action when called from super ctor
- if (fValueMap != null) {
- fValueMap.put(key, values);
- if (key.equals(fKey))
- fCurrentChoice= getChoices()[0];
- setResolved(true);
- }
- }
-
- public void setKey(Object defaultKey) {
- Assert.isTrue(fValueMap.containsKey(defaultKey));
- if (!fKey.equals(defaultKey)) {
- fKey= defaultKey;
- fCurrentChoice= getChoices()[0];
- }
- }
-
- public Object getCurrentChoice() {
- return fCurrentChoice;
- }
-
- public void setCurrentChoice(Object currentChoice) {
- Assert.isTrue(Arrays.asList(getChoices()).contains(currentChoice));
- fCurrentChoice= currentChoice;
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariable#setValues(java.lang.String[])
- */
- public void setValues(String[] values) {
- setChoices(values);
- }
-
- public void setChoices(Object[] values) {
- setChoices(DEFAULT_KEY, values);
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariable#getDefaultValue()
- *
- */
- public String getDefaultValue() {
- return toString(fCurrentChoice);
- }
-
- public String toString(Object object) {
- return object.toString();
- }
-
- /*
- * @see org.eclipse.jface.text.templates.TemplateVariable#getValues()
- */
- public String[] getValues() {
- Object[] values= getChoices();
- String[] result= new String[values.length];
- for (int i= 0; i < result.length; i++)
- result[i]= toString(values[i]);
- return result;
- }
-
- public Object[] getChoices() {
- return getChoices(fKey);
- }
-
- /**
- * Returns the choices for the set identified by <code>key</code>.
- *
- * @param key the key
- * @return the choices for this variable and the given set, or
- * <code>null</code> if the set is not defined.
- */
- public Object[] getChoices(Object key) {
- return (Object[]) fValueMap.get(key);
- }
-
- public Object[][] getAllChoices() {
- return (Object[][]) fValueMap.values().toArray(new Object[fValueMap.size()][]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java
deleted file mode 100644
index 3a7f484a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-
-/**
- * Global state for templates. Selecting a proposal for the master template variable
- * will cause the value (and the proposals) for the slave variables to change.
- *
- * @see MultiVariable
- */
-public class MultiVariableGuess {
-
- /**
- * Implementation of the <code>ICompletionProposal</code> interface and extension.
- */
- private static class Proposal implements ICompletionProposal, ICompletionProposalExtension2 {
-
- /** The string to be displayed in the completion proposal popup */
- private String fDisplayString;
- /** The replacement string */
- String fReplacementString;
- /** The replacement offset */
- private int fReplacementOffset;
- /** The replacement length */
- private int fReplacementLength;
- /** The cursor position after this proposal has been applied */
- private int fCursorPosition;
- /** The image to be displayed in the completion proposal popup */
- private Image fImage;
- /** The context information of this proposal */
- private IContextInformation fContextInformation;
- /** The additional info of this proposal */
- private String fAdditionalProposalInfo;
-
- /**
- * Creates a new completion proposal based on the provided information. The replacement string is
- * considered being the display string too. All remaining fields are set to <code>null</code>.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementOffset the offset of the text to be replaced
- * @param replacementLength the length of the text to be replaced
- * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
- */
- public Proposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition) {
- this(replacementString, replacementOffset, replacementLength, cursorPosition, null, null, null, null);
- }
-
- /**
- * Creates a new completion proposal. All fields are initialized based on the provided information.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementOffset the offset of the text to be replaced
- * @param replacementLength the length of the text to be replaced
- * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
- * @param image the image to display for this proposal
- * @param displayString the string to be displayed for the proposal
- * @param contextInformation the context information associated with this proposal
- * @param additionalProposalInfo the additional information associated with this proposal
- */
- public Proposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, String additionalProposalInfo) {
- Assert.isNotNull(replacementString);
- Assert.isTrue(replacementOffset >= 0);
- Assert.isTrue(replacementLength >= 0);
- Assert.isTrue(cursorPosition >= 0);
-
- fReplacementString= replacementString;
- fReplacementOffset= replacementOffset;
- fReplacementLength= replacementLength;
- fCursorPosition= cursorPosition;
- fImage= image;
- fDisplayString= displayString;
- fContextInformation= contextInformation;
- fAdditionalProposalInfo= additionalProposalInfo;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
- try {
- document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
- } catch (BadLocationException x) {
- // ignore
- }
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return new Point(fReplacementOffset + fCursorPosition, 0);
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return fContextInformation;
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- if (fDisplayString != null)
- return fDisplayString;
- return fReplacementString;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return fAdditionalProposalInfo;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- apply(viewer.getDocument());
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
- */
- public void selected(ITextViewer viewer, boolean smartToggle) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
- */
- public void unselected(ITextViewer viewer) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- try {
- String content= document.get(fReplacementOffset, fReplacementLength);
- if (content.startsWith(fReplacementString))
- return true;
- } catch (BadLocationException e) {
- // ignore concurrently modified document
- }
- return false;
- }
- }
-
- private final Map fDependencies= new HashMap();
- private final Map fBackwardDeps= new HashMap();
- private final Map fPositions= new HashMap();
-
- public MultiVariableGuess() {
- }
-
- public ICompletionProposal[] getProposals(final MultiVariable variable, int offset, int length) {
- MultiVariable master= (MultiVariable) fBackwardDeps.get(variable);
- Object[] choices;
- if (master == null)
- choices= variable.getChoices();
- else
- choices= variable.getChoices(master.getCurrentChoice());
-
- if (choices == null)
- return null;
-
- if (fDependencies.containsKey(variable)) {
- ICompletionProposal[] ret= new ICompletionProposal[choices.length];
- for (int i= 0; i < ret.length; i++) {
- final Object choice= choices[i];
- ret[i]= new Proposal(variable.toString(choice), offset, length, offset + length) {
- public void apply(IDocument document) {
- super.apply(document);
- Object oldChoice= variable.getCurrentChoice();
- variable.setCurrentChoice(choice);
- updateSlaves(variable, document, oldChoice);
- }
- };
- }
-
- return ret;
-
- } else {
- if (choices.length < 2)
- return null;
-
- ICompletionProposal[] ret= new ICompletionProposal[choices.length];
- for (int i= 0; i < ret.length; i++)
- ret[i]= new Proposal(variable.toString(choices[i]), offset, length, offset + length);
-
- return ret;
- }
- }
-
- private void updateSlaves(MultiVariable variable, IDocument document, Object oldChoice) {
- Object choice= variable.getCurrentChoice();
- if (!oldChoice.equals(choice)) {
- Set slaves= (Set) fDependencies.get(variable);
- for (Iterator it= slaves.iterator(); it.hasNext();) {
- MultiVariable slave= (MultiVariable) it.next();
- VariablePosition pos= (VariablePosition) fPositions.get(slave);
-
- Object slavesOldChoice= slave.getCurrentChoice();
- slave.setKey(choice); // resets the current choice
- try {
- document.replace(pos.getOffset(), pos.getLength(), slave.getDefaultValue());
- } catch (BadLocationException x) {
- // ignore and continue
- }
- // handle slaves recursively
- if (fDependencies.containsKey(slave))
- updateSlaves(slave, document, slavesOldChoice);
- }
- }
- }
-
- /**
- * @param position
- */
- public void addSlave(VariablePosition position) {
- fPositions.put(position.getVariable(), position);
- }
-
- /**
- * @param master
- * @param slave
- *
- */
- public void addDependency(MultiVariable master, MultiVariable slave) {
- // check for cycles and multi-slaves
- if (fBackwardDeps.containsKey(slave))
- throw new IllegalArgumentException("slave can only serve one master"); //$NON-NLS-1$
- Object parent= master;
- while (parent != null) {
- parent= fBackwardDeps.get(parent);
- if (parent == slave)
- throw new IllegalArgumentException("cycle detected"); //$NON-NLS-1$
- }
-
- Set slaves= (Set) fDependencies.get(master);
- if (slaves == null) {
- slaves= new HashSet();
- fDependencies.put(master, slaves);
- }
- fBackwardDeps.put(slave, master);
- slaves.add(slave);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java
deleted file mode 100644
index 282ae8bc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-
-/**
- * An enhanced implementation of the <code>ICompletionProposal</code> interface implementing all the extension interfaces.
- * It uses a position to track its replacement offset and length. The position must be set up externally.
- */
-public class PositionBasedCompletionProposal implements ICompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2 {
-
- /** The string to be displayed in the completion proposal popup */
- private String fDisplayString;
- /** The replacement string */
- private String fReplacementString;
- /** The replacement position. */
- private Position fReplacementPosition;
- /** The cursor position after this proposal has been applied */
- private int fCursorPosition;
- /** The image to be displayed in the completion proposal popup */
- private Image fImage;
- /** The context information of this proposal */
- private IContextInformation fContextInformation;
- /** The additional info of this proposal */
- private String fAdditionalProposalInfo;
-
- /**
- * Creates a new completion proposal based on the provided information. The replacement string is
- * considered being the display string too. All remaining fields are set to <code>null</code>.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementPosition the position of the text to be replaced
- * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
- */
- public PositionBasedCompletionProposal(String replacementString, Position replacementPosition, int cursorPosition) {
- this(replacementString, replacementPosition, cursorPosition, null, null, null, null);
- }
-
- /**
- * Creates a new completion proposal. All fields are initialized based on the provided information.
- *
- * @param replacementString the actual string to be inserted into the document
- * @param replacementPosition the position of the text to be replaced
- * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
- * @param image the image to display for this proposal
- * @param displayString the string to be displayed for the proposal
- * @param contextInformation the context information associated with this proposal
- * @param additionalProposalInfo the additional information associated with this proposal
- */
- public PositionBasedCompletionProposal(String replacementString, Position replacementPosition, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, String additionalProposalInfo) {
- Assert.isNotNull(replacementString);
- Assert.isTrue(replacementPosition != null);
-
- fReplacementString= replacementString;
- fReplacementPosition= replacementPosition;
- fCursorPosition= cursorPosition;
- fImage= image;
- fDisplayString= displayString;
- fContextInformation= contextInformation;
- fAdditionalProposalInfo= additionalProposalInfo;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
- try {
- document.replace(fReplacementPosition.getOffset(), fReplacementPosition.getLength(), fReplacementString);
- } catch (BadLocationException x) {
- // ignore
- }
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return new Point(fReplacementPosition.getOffset() + fCursorPosition, 0);
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return fContextInformation;
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- if (fDisplayString != null)
- return fDisplayString;
- return fReplacementString;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return fAdditionalProposalInfo;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- apply(viewer.getDocument());
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
- */
- public void selected(ITextViewer viewer, boolean smartToggle) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
- */
- public void unselected(ITextViewer viewer) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- try {
- String content= document.get(fReplacementPosition.getOffset(), offset - fReplacementPosition.getOffset());
- if (fReplacementString.startsWith(content))
- return true;
- } catch (BadLocationException e) {
- // ignore concurrently modified document
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#apply(org.eclipse.jface.text.IDocument, char, int)
- */
- public void apply(IDocument document, char trigger, int offset) {
- // not called any more
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#isValidFor(org.eclipse.jface.text.IDocument, int)
- */
- public boolean isValidFor(IDocument document, int offset) {
- // not called any more
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#getTriggerCharacters()
- */
- public char[] getTriggerCharacters() {
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#getContextInformationPosition()
- */
- public int getContextInformationPosition() {
- return fReplacementPosition.getOffset();
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/SurroundWithTemplateProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/SurroundWithTemplateProposal.java
deleted file mode 100644
index a14fc5a4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/SurroundWithTemplateProposal.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.Block;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.Statement;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.GenericVisitor;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContext;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaContextType;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.AssistContext;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.SurroundWith;
-import org.eclipse.wst.jsdt.ui.text.java.IInvocationContext;
-
-public class SurroundWithTemplateProposal extends TemplateProposal {
-
- private static class SurroundWithTemplate extends SurroundWith {
-
- private static final String $_LINE_SELECTION= "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
-
- private final Template fTemplate;
- private final IJavaScriptProject fCurrentProject;
- private ASTNode fTemplateNode;
-
- public SurroundWithTemplate(IInvocationContext context, Statement[] selectedNodes, Template template) {
- super(context.getASTRoot(), selectedNodes);
- fTemplate= template;
- fCurrentProject= context.getCompilationUnit().getJavaScriptProject();
- }
-
- protected List getVariableDeclarationReadsInside(Statement[] selectedNodes, int maxVariableId) {
- if (isNewContext())
- return super.getVariableDeclarationReadsInside(selectedNodes, maxVariableId);
- return new ArrayList();
- }
-
- protected boolean isNewContext() {
-
- final String templateVariableRegEx= "\\$\\{[^\\}]*\\}"; //$NON-NLS-1$
-
- String template= fTemplate.getPattern();
- int currentPosition= template.indexOf($_LINE_SELECTION);
- int insertionPosition= -1;
- while (currentPosition != -1) {
- insertionPosition= currentPosition;
- template= template.replaceFirst(templateVariableRegEx, ""); //$NON-NLS-1$
- currentPosition= template.indexOf($_LINE_SELECTION);
- }
- template= template.replaceAll(templateVariableRegEx, ""); //$NON-NLS-1$
-
- AST ast= getAst();
- ASTParser parser= ASTParser.newParser(ast.apiLevel());
- parser.setSource(template.toCharArray());
- parser.setProject(fCurrentProject);
- parser.setKind(ASTParser.K_STATEMENTS);
- ASTNode root= parser.createAST(null);
- if (((Block)root).statements().isEmpty()) {
- parser= ASTParser.newParser(ast.apiLevel());
- parser.setSource(template.toCharArray());
- parser.setProject(fCurrentProject);
- parser.setKind(ASTParser.K_EXPRESSION);
- root= parser.createAST(null);
- }
-
- final int lineSelectionPosition= insertionPosition;
- root.accept(new GenericVisitor() {
- public void endVisit(Block node) {
- super.endVisit(node);
- if (fTemplateNode == null && node.getStartPosition() <= lineSelectionPosition && node.getLength() + node.getStartPosition() >= lineSelectionPosition) {
- fTemplateNode= node;
- }
- }
- });
-
- if (fTemplateNode != null && ASTNodes.getParent(fTemplateNode, FunctionDeclaration.class) != null) {
- return true;
- }
-
- return false;
- }
-
- }
-
-
- private final IRegion fRegion;
- private final IJavaScriptUnit fCompilationUnit;
- private final CompilationUnitContext fContext;
- private final Template fTemplate;
- private final Statement[] fSelectedStatements;
- private TemplateProposal fProposal;
- private IRegion fSelectedRegion;
-
- public SurroundWithTemplateProposal(IJavaScriptUnit compilationUnit, Template template, CompilationUnitContext context, IRegion region, Image image, Statement[] selectedStatements) {
- super(template, context, region, image);
- fCompilationUnit= compilationUnit;
- fTemplate= template;
- fContext= context;
- fRegion= region;
- fSelectedStatements= selectedStatements;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.TemplateProposal#getAdditionalProposalInfo()
- */
- public String getPreviewContent() {
- try {
- IDocument document= new Document(fCompilationUnit.getBuffer().getContents());
- CompilationUnitContext context= createNewContext(document);
-
- int offset= context.getCompletionOffset();
- int start= context.getStart();
- int end= context.getEnd();
- IRegion region= new Region(start, end - start);
-
- context.setReadOnly(false);
- TemplateBuffer templateBuffer;
- try {
- templateBuffer= context.evaluate(fTemplate);
- } catch (TemplateException e1) {
- JavaScriptPlugin.log(e1);
- return null;
- }
-
- start= region.getOffset();
- end= region.getOffset() + region.getLength();
- end= Math.max(end, offset);
-
- String templateString= templateBuffer.getString();
- document.replace(start, end - start, templateString);
-
- return document.get();
-
- } catch (MalformedTreeException e) {
- JavaScriptPlugin.log(e);
- } catch (IllegalArgumentException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.template.contentassist.TemplateProposal#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
- try {
- setRedraw(viewer, false);
- IDocument document= viewer.getDocument();
- CompilationUnitContext context= createNewContext(document);
-
- int start= context.getStart();
- int end= context.getEnd();
- IRegion region= new Region(start, end - start);
-
- //Evaluate the template within the new context
- fProposal= new TemplateProposal(fTemplate, context, region, null);
- fProposal.apply(viewer, trigger, stateMask, context.getCompletionOffset());
- } catch (MalformedTreeException e) {
- handleException(viewer, e, fRegion);
- } catch (IllegalArgumentException e) {
- handleException(viewer, e, fRegion);
- } catch (BadLocationException e) {
- handleException(viewer, e, fRegion);
- } catch (CoreException e) {
- handleException(viewer, e, fRegion);
- } finally {
- setRedraw(viewer, true);
- }
- }
-
- private void setRedraw(ITextViewer viewer, boolean redraw) {
- if (viewer instanceof ITextViewerExtension) {
- ITextViewerExtension extension= (ITextViewerExtension) viewer;
- IRewriteTarget target= extension.getRewriteTarget();
- target.setRedraw(redraw);
- }
- }
-
- public Point getSelection(IDocument document) {
- if (fSelectedRegion != null) {
- return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
- } else if (fProposal != null) {
- return fProposal.getSelection(document);
- } else {
- return null;
- }
- }
-
- private CompilationUnitContext createNewContext(IDocument document) throws CoreException, BadLocationException {
- AssistContext invocationContext= new AssistContext(fCompilationUnit, fContext.getStart(), fContext.getEnd() - fContext.getStart());
-
- SurroundWithTemplate surroundWith= new SurroundWithTemplate(invocationContext, fSelectedStatements, fTemplate);
- Map options= fCompilationUnit.getJavaScriptProject().getOptions(true);
-
- surroundWith.getRewrite().rewriteAST(document, options).apply(document);
-
- int offset= surroundWith.getBodyStart();
- int length= surroundWith.getBodyLength();
- String newSelection= document.get(offset, length);
-
- //Create the new context
- CompilationUnitContextType contextType= (CompilationUnitContextType) JavaScriptPlugin.getDefault().getTemplateContextRegistry().getContextType(JavaContextType.NAME);
- CompilationUnitContext context= contextType.createContext(document, offset, newSelection.length(), fCompilationUnit);
- context.setVariable("selection", newSelection); //$NON-NLS-1$
- context.setForceEvaluation(true);
- return context;
- }
-
- private void handleException(ITextViewer viewer, Exception e, IRegion region) {
- JavaScriptPlugin.log(e);
- openErrorDialog(viewer.getTextWidget().getShell(), e);
- fSelectedRegion= region;
- }
-
- private void openErrorDialog(Shell shell, Exception e) {
- MessageDialog.openError(shell, TemplateContentAssistMessages.TemplateEvaluator_error_title, e.getMessage());
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java
deleted file mode 100644
index c39be4c9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class TemplateContentAssistMessages extends NLS {
-
- private static final String BUNDLE_NAME= TemplateContentAssistMessages.class.getName();
-
- private TemplateContentAssistMessages() {
- // Do not instantiate
- }
-
- public static String TemplateProposal_displayString;
- public static String TemplateEvaluator_error_title;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, TemplateContentAssistMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties
deleted file mode 100644
index d6328064..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-# template proposal
-# The first argument is the name and the second is the description
-TemplateProposal_displayString= {0} - {1}
-
-# template evaluator
-TemplateEvaluator_error_title=Template Evaluation Error
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateEngine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateEngine.java
deleted file mode 100644
index 0d48835d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateEngine.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContext;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContextType;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class TemplateEngine {
-
- private static final String $_LINE_SELECTION= "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
- private static final String $_WORD_SELECTION= "${" + GlobalTemplateVariables.WordSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
-
- /** The context type. */
- private TemplateContextType fContextType;
- /** The result proposals. */
- private ArrayList fProposals= new ArrayList();
- /** Positions created on the key documents to remove in reset. */
- private final Map fPositions= new HashMap();
-
- /**
- * Creates the template engine for a particular context type.
- * See <code>TemplateContext</code> for supported context types.
- */
- public TemplateEngine(TemplateContextType contextType) {
- Assert.isNotNull(contextType);
- fContextType= contextType;
- }
-
- /**
- * Empties the collector.
- */
- public void reset() {
- fProposals.clear();
- for (Iterator it= fPositions.entrySet().iterator(); it.hasNext();) {
- Entry entry= (Entry) it.next();
- IDocument doc= (IDocument) entry.getKey();
- Position position= (Position) entry.getValue();
- doc.removePosition(position);
- }
- fPositions.clear();
- }
-
- /**
- * Returns the array of matching templates.
- */
- public TemplateProposal[] getResults() {
- return (TemplateProposal[]) fProposals.toArray(new TemplateProposal[fProposals.size()]);
- }
-
- /**
- * Inspects the context of the compilation unit around <code>completionPosition</code>
- * and feeds the collector with proposals.
- * @param viewer the text viewer
- * @param completionPosition the context position in the document of the text viewer
- * @param compilationUnit the compilation unit (may be <code>null</code>)
- */
- public void complete(ITextViewer viewer, int completionPosition, IJavaScriptUnit compilationUnit) {
- IDocument document= viewer.getDocument();
-
- if (!(fContextType instanceof CompilationUnitContextType))
- return;
-
- Point selection= viewer.getSelectedRange();
- Position position= new Position(completionPosition, selection.y);
-
- // remember selected text
- String selectedText= null;
- if (selection.y != 0) {
- try {
- selectedText= document.get(selection.x, selection.y);
- document.addPosition(position);
- fPositions.put(document, position);
- } catch (BadLocationException e) {}
- }
-
- CompilationUnitContext context= ((CompilationUnitContextType) fContextType).createContext(document, position, compilationUnit);
- context.setVariable("selection", selectedText); //$NON-NLS-1$
- int start= context.getStart();
- int end= context.getEnd();
- IRegion region= new Region(start, end - start);
-
- Template[] templates= JavaScriptPlugin.getDefault().getTemplateStore().getTemplates();
-
- if (selection.y == 0) {
- for (int i= 0; i != templates.length; i++)
- if (context.canEvaluate(templates[i]))
- fProposals.add(new TemplateProposal(templates[i], context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)));
-
- } else {
-
- if (context.getKey().length() == 0)
- context.setForceEvaluation(true);
-
- boolean multipleLinesSelected= areMultipleLinesSelected(viewer);
-
- for (int i= 0; i != templates.length; i++) {
- Template template= templates[i];
- if (context.canEvaluate(template) &&
- template.getContextTypeId().equals(context.getContextType().getId()) &&
- (!multipleLinesSelected && template.getPattern().indexOf($_WORD_SELECTION) != -1 || (multipleLinesSelected && template.getPattern().indexOf($_LINE_SELECTION) != -1)))
- {
- fProposals.add(new TemplateProposal(templates[i], context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)));
- }
- }
- }
- }
-
- /**
- * Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
- * Being completely selected means that all characters except the new line characters are
- * selected.
- *
- * @return <code>true</code> if one or multiple lines are selected
- *
- */
- private boolean areMultipleLinesSelected(ITextViewer viewer) {
- if (viewer == null)
- return false;
-
- Point s= viewer.getSelectedRange();
- if (s.y == 0)
- return false;
-
- try {
-
- IDocument document= viewer.getDocument();
- int startLine= document.getLineOfOffset(s.x);
- int endLine= document.getLineOfOffset(s.x + s.y);
- IRegion line= document.getLineInformation(startLine);
- return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength());
-
- } catch (BadLocationException x) {
- return false;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java
deleted file mode 100644
index 00d1ee76..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IInformationControlCreatorExtension;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.SourceViewerInformationControl;
-
-
-final public class TemplateInformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension {
-
- private SourceViewerInformationControl fControl;
-
- /**
- * The orientation to be used by this hover.
- * Allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT
- *
- */
- private int fOrientation;
-
- /**
- * @param orientation the orientation, allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT
- */
- public TemplateInformationControlCreator(int orientation) {
- Assert.isLegal(orientation == SWT.RIGHT_TO_LEFT || orientation == SWT.LEFT_TO_RIGHT);
- fOrientation= orientation;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell)
- */
- public IInformationControl createInformationControl(Shell parent) {
- fControl= new SourceViewerInformationControl(parent, SWT.TOOL | fOrientation, SWT.NONE);
- fControl.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- fControl= null;
- }
- });
- return fControl;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReuse(org.eclipse.jface.text.IInformationControl)
- */
- public boolean canReuse(IInformationControl control) {
- return fControl == control && fControl != null;
- }
-
- /*
- * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReplace(org.eclipse.jface.text.IInformationControlCreator)
- */
- public boolean canReplace(IInformationControlCreator creator) {
- return (creator != null && getClass() == creator.getClass());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateProposal.java
deleted file mode 100644
index 1e768c7c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateProposal.java
+++ /dev/null
@@ -1,537 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.BadPositionCategoryException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.ITextViewerExtension;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3;
-import org.eclipse.jface.text.contentassist.ICompletionProposalExtension4;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.link.ILinkedModeListener;
-import org.eclipse.jface.text.link.LinkedModeModel;
-import org.eclipse.jface.text.link.LinkedModeUI;
-import org.eclipse.jface.text.link.LinkedPosition;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.ProposalPosition;
-import org.eclipse.jface.text.source.LineRange;
-import org.eclipse.jface.text.templates.DocumentTemplateContext;
-import org.eclipse.jface.text.templates.GlobalTemplateVariables;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateBuffer;
-import org.eclipse.jface.text.templates.TemplateContext;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.text.templates.TemplateVariable;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.part.IWorkbenchPartOrientation;
-import org.eclipse.ui.texteditor.link.EditorLinkedModeUI;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CompilationUnitContext;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaDocContext;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorHighlightingSynchronizer;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IndentUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
-
-/**
- * A template proposal.
- */
-public class TemplateProposal implements IJavaCompletionProposal, ICompletionProposalExtension2, ICompletionProposalExtension3, ICompletionProposalExtension4 {
-
- private final Template fTemplate;
- private final TemplateContext fContext;
- private final Image fImage;
- private IRegion fRegion;
- private int fRelevance;
-
- private IRegion fSelectedRegion; // initialized by apply()
- private String fDisplayString;
-
- /**
- * Creates a template proposal with a template and its context.
- *
- * @param template the template
- * @param context the context in which the template was requested
- * @param region the region this proposal applies to
- * @param image the icon of the proposal
- */
- public TemplateProposal(Template template, TemplateContext context, IRegion region, Image image) {
- Assert.isNotNull(template);
- Assert.isNotNull(context);
- Assert.isNotNull(region);
-
- fTemplate= template;
- fContext= context;
- fImage= image;
- fRegion= region;
-
- fDisplayString= null;
-
- fRelevance= computeRelevance();
- }
-
- /**
- * Computes the relevance to match the relevance values generated by the
- * core content assistant.
- *
- * @return a sensible relevance value.
- */
- private int computeRelevance() {
- // see org.eclipse.wst.jsdt.internal.codeassist.RelevanceConstants
- final int R_DEFAULT= 0;
- final int R_INTERESTING= 5;
- final int R_CASE= 10;
- final int R_NON_RESTRICTED= 3;
- final int R_EXACT_NAME = 4;
- final int R_INLINE_TAG = 31;
-
- int base= R_DEFAULT + R_INTERESTING + R_NON_RESTRICTED;
-
- try {
- if (fContext instanceof DocumentTemplateContext) {
- DocumentTemplateContext templateContext= (DocumentTemplateContext) fContext;
- IDocument document= templateContext.getDocument();
-
- String content= document.get(fRegion.getOffset(), fRegion.getLength());
- if (fTemplate.getName().startsWith(content))
- base += R_CASE;
- if (fTemplate.getName().equalsIgnoreCase(content))
- base += R_EXACT_NAME;
- if (fContext instanceof JavaDocContext)
- base += R_INLINE_TAG;
- }
- } catch (BadLocationException e) {
- // ignore - not a case sensitive match then
- }
-
- // see CompletionProposalCollector.computeRelevance
- // just under keywords, but better than packages
- final int TEMPLATE_RELEVANCE= 1;
- return base * 16 + TEMPLATE_RELEVANCE;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public final void apply(IDocument document) {
- // not called anymore
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
- */
- public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
-
- try {
-
- fContext.setReadOnly(false);
- int start;
- IDocument document;
- TemplateBuffer templateBuffer;
- try {
- beginCompoundChange(viewer);
-
- try {
- // this may already modify the document (e.g. add imports)
- templateBuffer= fContext.evaluate(fTemplate);
- } catch (TemplateException e1) {
- fSelectedRegion= fRegion;
- return;
- }
-
- start= getReplaceOffset();
- int end= getReplaceEndOffset();
- end= Math.max(end, offset);
-
- // insert template string
- document= viewer.getDocument();
- if (end > document.getLength())
- end= offset;
- String templateString= templateBuffer.getString();
- document.replace(start, end - start, templateString);
- } finally {
- endCompoundChange(viewer);
- }
-
- // translate positions
- LinkedModeModel model= new LinkedModeModel();
- TemplateVariable[] variables= templateBuffer.getVariables();
-
- MultiVariableGuess guess= fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext).getMultiVariableGuess() : null;
-
- boolean hasPositions= false;
- for (int i= 0; i != variables.length; i++) {
- TemplateVariable variable= variables[i];
-
- if (variable.isUnambiguous())
- continue;
-
- LinkedPositionGroup group= new LinkedPositionGroup();
-
- int[] offsets= variable.getOffsets();
- int length= variable.getLength();
-
- LinkedPosition first;
- if (guess != null && variable instanceof MultiVariable) {
- first= new VariablePosition(document, offsets[0] + start, length, guess, (MultiVariable) variable);
- guess.addSlave((VariablePosition) first);
- } else {
- String[] values= variable.getValues();
- ICompletionProposal[] proposals= new ICompletionProposal[values.length];
- for (int j= 0; j < values.length; j++) {
- ensurePositionCategoryInstalled(document, model);
- Position pos= new Position(offsets[0] + start, length);
- document.addPosition(getCategory(), pos);
- proposals[j]= new PositionBasedCompletionProposal(values[j], pos, length);
- }
-
- if (proposals.length > 1)
- first= new ProposalPosition(document, offsets[0] + start, length, proposals);
- else
- first= new LinkedPosition(document, offsets[0] + start, length);
- }
-
- for (int j= 0; j != offsets.length; j++)
- if (j == 0)
- group.addPosition(first);
- else
- group.addPosition(new LinkedPosition(document, offsets[j] + start, length));
-
- model.addGroup(group);
- hasPositions= true;
- }
-
- if (hasPositions) {
- model.forceInstall();
- JavaEditor editor= getJavaEditor();
- if (editor != null) {
- model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
- }
-
- LinkedModeUI ui= new EditorLinkedModeUI(model, viewer);
- ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, Integer.MAX_VALUE);
- ui.enter();
-
- fSelectedRegion= ui.getSelectedRegion();
- } else
- fSelectedRegion= new Region(getCaretOffset(templateBuffer) + start, 0);
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- openErrorDialog(viewer.getTextWidget().getShell(), e);
- fSelectedRegion= fRegion;
- } catch (BadPositionCategoryException e) {
- JavaScriptPlugin.log(e);
- openErrorDialog(viewer.getTextWidget().getShell(), e);
- fSelectedRegion= fRegion;
- }
-
- }
-
- private void endCompoundChange(ITextViewer viewer) {
- if (viewer instanceof ITextViewerExtension) {
- ITextViewerExtension extension= (ITextViewerExtension) viewer;
- IRewriteTarget target= extension.getRewriteTarget();
- target.endCompoundChange();
- }
- }
-
- private void beginCompoundChange(ITextViewer viewer) {
- if (viewer instanceof ITextViewerExtension) {
- ITextViewerExtension extension= (ITextViewerExtension) viewer;
- IRewriteTarget target= extension.getRewriteTarget();
- target.beginCompoundChange();
- }
- }
-
- /**
- * Returns the currently active java editor, or <code>null</code> if it
- * cannot be determined.
- *
- * @return the currently active java editor, or <code>null</code>
- */
- private JavaEditor getJavaEditor() {
- IEditorPart part= JavaScriptPlugin.getActivePage().getActiveEditor();
- if (part instanceof JavaEditor)
- return (JavaEditor) part;
- else
- return null;
- }
-
- /**
- * Returns the offset of the range in the document that will be replaced by
- * applying this template.
- *
- * @return the offset of the range in the document that will be replaced by
- * applying this template
- */
- private int getReplaceOffset() {
- int start;
- if (fContext instanceof DocumentTemplateContext) {
- DocumentTemplateContext docContext = (DocumentTemplateContext)fContext;
- start= docContext.getStart();
- } else {
- start= fRegion.getOffset();
- }
- return start;
- }
-
- /**
- * Returns the end offset of the range in the document that will be replaced
- * by applying this template.
- *
- * @return the end offset of the range in the document that will be replaced
- * by applying this template
- */
- private int getReplaceEndOffset() {
- int end;
- if (fContext instanceof DocumentTemplateContext) {
- DocumentTemplateContext docContext = (DocumentTemplateContext)fContext;
- end= docContext.getEnd();
- } else {
- end= fRegion.getOffset() + fRegion.getLength();
- }
- return end;
- }
-
- private void ensurePositionCategoryInstalled(final IDocument document, LinkedModeModel model) {
- if (!document.containsPositionCategory(getCategory())) {
- document.addPositionCategory(getCategory());
- final InclusivePositionUpdater updater= new InclusivePositionUpdater(getCategory());
- document.addPositionUpdater(updater);
-
- model.addLinkingListener(new ILinkedModeListener() {
-
- /*
- * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, int)
- */
- public void left(LinkedModeModel environment, int flags) {
- try {
- document.removePositionCategory(getCategory());
- } catch (BadPositionCategoryException e) {
- // ignore
- }
- document.removePositionUpdater(updater);
- }
-
- public void suspend(LinkedModeModel environment) {}
- public void resume(LinkedModeModel environment, int flags) {}
- });
- }
- }
-
- private String getCategory() {
- return "TemplateProposalCategory_" + toString(); //$NON-NLS-1$
- }
-
- private int getCaretOffset(TemplateBuffer buffer) {
-
- TemplateVariable[] variables= buffer.getVariables();
- for (int i= 0; i != variables.length; i++) {
- TemplateVariable variable= variables[i];
- if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME))
- return variable.getOffsets()[0];
- }
-
- return buffer.getString().length();
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- try {
- fContext.setReadOnly(true);
- TemplateBuffer templateBuffer;
- try {
- templateBuffer= fContext.evaluate(fTemplate);
- } catch (TemplateException e1) {
- return null;
- }
-
- IDocument document= new Document(templateBuffer.getString());
- IndentUtil.indentLines(document, new LineRange(0, document.getNumberOfLines()), null, null);
- return document.get();
-
- } catch (BadLocationException e) {
- handleException(JavaScriptPlugin.getActiveWorkbenchShell(), new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, "", e))); //$NON-NLS-1$
- return null;
- }
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- if (fDisplayString == null) {
- String[] arguments= new String[] { fTemplate.getName(), fTemplate.getDescription() };
- fDisplayString= Messages.format(TemplateContentAssistMessages.TemplateProposal_displayString, arguments);
- }
- return fDisplayString;
- }
-
- public void setDisplayString(String displayString) {
- fDisplayString= displayString;
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return fImage;
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return null;
- }
-
- private void openErrorDialog(Shell shell, Exception e) {
- MessageDialog.openError(shell, TemplateContentAssistMessages.TemplateEvaluator_error_title, e.getMessage());
- }
-
- private void handleException(Shell shell, CoreException e) {
- ExceptionHandler.handle(e, shell, TemplateContentAssistMessages.TemplateEvaluator_error_title, null);
- }
-
- /*
- * @see IJavaCompletionProposal#getRelevance()
- */
- public int getRelevance() {
- return fRelevance;
- }
-
- public void setRelevance(int relevance) {
- fRelevance= relevance;
- }
-
- public Template getTemplate() {
- return fTemplate;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator()
- */
- public IInformationControlCreator getInformationControlCreator() {
- int orientation;
- IEditorPart editor= getJavaEditor();
- if (editor instanceof IWorkbenchPartOrientation)
- orientation= ((IWorkbenchPartOrientation)editor).getOrientation();
- else
- orientation= SWT.LEFT_TO_RIGHT;
- return new TemplateInformationControlCreator(orientation);
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
- */
- public void selected(ITextViewer viewer, boolean smartToggle) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
- */
- public void unselected(ITextViewer viewer) {
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
- */
- public boolean validate(IDocument document, int offset, DocumentEvent event) {
- try {
- int replaceOffset= getReplaceOffset();
- if (offset >= replaceOffset) {
- String content= document.get(replaceOffset, offset - replaceOffset);
- String templateName= fTemplate.getName().toLowerCase();
- boolean valid= templateName.startsWith(content.toLowerCase());
- if (!valid && fContext instanceof JavaDocContext && templateName.startsWith("<")) { //$NON-NLS-1$
- valid= templateName.startsWith(content.toLowerCase(), 1);
- }
- return valid;
- }
- } catch (BadLocationException e) {
- // concurrent modification - ignore
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementString()
- */
- public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
- // bug 114360 - don't make selection templates prefix-completable
- if (isSelectionTemplate())
- return ""; //$NON-NLS-1$
- return fTemplate.getName();
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementOffset()
- */
- public int getPrefixCompletionStart(IDocument document, int completionOffset) {
- return getReplaceOffset();
- }
-
- /*
- * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
- */
- public boolean isAutoInsertable() {
- if (isSelectionTemplate())
- return false;
- return fTemplate.isAutoInsertable();
- }
-
- /**
- * Returns <code>true</code> if the proposal has a selection, e.g. will wrap some code.
- *
- * @return <code>true</code> if the proposals completion length is non zero
- *
- */
- private boolean isSelectionTemplate() {
- if (fContext instanceof DocumentTemplateContext) {
- DocumentTemplateContext ctx= (DocumentTemplateContext) fContext;
- if (ctx.getCompletionLength() > 0)
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/VariablePosition.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/VariablePosition.java
deleted file mode 100644
index 780bdc4d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/VariablePosition.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.link.LinkedPositionGroup;
-import org.eclipse.jface.text.link.ProposalPosition;
-
-
-/**
- *
- */
-public class VariablePosition extends ProposalPosition {
-
- private MultiVariableGuess fGuess;
- private MultiVariable fVariable;
-
- public VariablePosition(IDocument document, int offset, int length, MultiVariableGuess guess, MultiVariable variable) {
- this(document, offset, length, LinkedPositionGroup.NO_STOP, guess, variable);
- }
-
- public VariablePosition(IDocument document, int offset, int length, int sequence, MultiVariableGuess guess, MultiVariable variable) {
- super(document, offset, length, sequence, null);
- Assert.isNotNull(guess);
- Assert.isNotNull(variable);
- fVariable= variable;
- fGuess= guess;
- }
-
-
- /*
- * @see org.eclipse.jface.text.link.ProposalPosition#equals(java.lang.Object)
- */
- public boolean equals(Object o) {
- if (o instanceof VariablePosition && super.equals(o)) {
- return fGuess.equals(((VariablePosition) o).fGuess);
- }
- return false;
- }
-
- /*
- * @see org.eclipse.jface.text.link.ProposalPosition#hashCode()
- */
- public int hashCode() {
- return super.hashCode() | fGuess.hashCode();
- }
-
- /*
- * @see org.eclipse.jface.text.link.ProposalPosition#getChoices()
- */
- public ICompletionProposal[] getChoices() {
- return fGuess.getProposals(fVariable, offset, length);
- }
-
- /**
- * Returns the variable.
- *
- * @return the variable.
- */
- public MultiVariable getVariable() {
- return fVariable;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateContentProvider.java
deleted file mode 100644
index 6aa4fc17..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateContentProvider.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.preferences;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.internal.corext.template.java.TemplateSet;
-
-
-public class TemplateContentProvider implements IStructuredContentProvider {
-
- private TemplateSet fTemplateSet;
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object input) {
- return fTemplateSet.getTemplates();
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- fTemplateSet= (TemplateSet) newInput;
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- fTemplateSet= null;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java
deleted file mode 100644
index a205715b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.preferences;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- */
-final class TemplatePreferencesMessages extends NLS {
-
- private static final String BUNDLE_NAME= TemplatePreferencesMessages.class.getName();
-
- private TemplatePreferencesMessages() {
- // Do not instantiate
- }
-
- public static String TemplateVariableProposal_error_title;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, TemplatePreferencesMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties
deleted file mode 100644
index 3911a0f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-TemplateVariableProposal_error_title=Error applying template variable proposal
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java
deleted file mode 100644
index 8ab4f5e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.preferences;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jface.text.templates.TemplateContextType;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-
-
-
-public class TemplateVariableProcessor implements IContentAssistProcessor {
-
- private static Comparator fgTemplateVariableProposalComparator= new Comparator() {
- public int compare(Object arg0, Object arg1) {
- TemplateVariableProposal proposal0= (TemplateVariableProposal) arg0;
- TemplateVariableProposal proposal1= (TemplateVariableProposal) arg1;
-
- return proposal0.getDisplayString().compareTo(proposal1.getDisplayString());
- }
-
- public boolean equals(Object arg0) {
- return false;
- }
- };
-
-
- /** the context type */
- private TemplateContextType fContextType;
-
- /**
- * Sets the context type.
- */
- public void setContextType(TemplateContextType contextType) {
- fContextType= contextType;
- }
-
- /**
- * Gets the context type.
- */
- public TemplateContextType getContextType() {
- return fContextType;
- }
-
- /*
- * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
- */
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
-
- if (fContextType == null)
- return null;
-
- List proposals= new ArrayList();
-
- String text= viewer.getDocument().get();
- int start= getStart(text, documentOffset);
- int end= documentOffset;
-
- String string= text.substring(start, end);
- int colon= string.indexOf(':');
- boolean includeBrace= true;
- int offset= start;
- String prefix= string;
- if (colon != -1) {
- includeBrace= false;
- offset= start + colon + 1;
- prefix= string.substring(colon + 1);
- } else {
- int escape= string.indexOf("${"); //$NON-NLS-1$
- if (escape != -1) {
- offset= start + escape + 2;
- includeBrace= false;
- prefix= string.substring(escape + 2);
- }
- }
- if (prefix.equals("$")) //$NON-NLS-1$
- prefix= ""; //$NON-NLS-1$
-
- int length= end - offset;
-
- for (Iterator iterator= fContextType.resolvers(); iterator.hasNext(); ) {
- TemplateVariableResolver variable= (TemplateVariableResolver) iterator.next();
-
- if (variable.getType().startsWith(prefix))
- proposals.add(new TemplateVariableProposal(variable, offset, length, viewer, includeBrace));
- }
-
- Collections.sort(proposals, fgTemplateVariableProposalComparator);
- return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- /* Guesses the start position of the completion */
- private int getStart(String string, int end) {
- int start= end;
-
- if (start >= 1 && string.charAt(start - 1) == '$')
- return start - 1;
-
- while ((start != 0) && Character.isUnicodeIdentifierPart(string.charAt(start - 1)))
- start--;
-
- if (start >= 1 && string.charAt(start - 1) == ':') {
- start--;
- while ((start != 0) && Character.isUnicodeIdentifierPart(string.charAt(start - 1)))
- start--;
- }
-
- if (start >= 2 && string.charAt(start - 1) == '{' && string.charAt(start - 2) == '$')
- return start - 2;
-
- return end;
- }
-
- /*
- * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
- */
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
- return null;
- }
-
- /*
- * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- public char[] getCompletionProposalAutoActivationCharacters() {
- return new char[] {'$'};
- }
-
- /*
- * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /*
- * @see IContentAssistProcessor#getErrorMessage()
- */
- public String getErrorMessage() {
- return null;
- }
-
- /*
- * @see IContentAssistProcessor#getContextInformationValidator()
- */
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProposal.java
deleted file mode 100644
index bc021dcb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplateVariableProposal.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.text.template.preferences;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.templates.TemplateVariableResolver;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * A proposal for insertion of template variables.
- */
-public class TemplateVariableProposal implements ICompletionProposal {
-
- private TemplateVariableResolver fResolver;
- private int fOffset;
- private int fLength;
- private ITextViewer fViewer;
-
- private Point fSelection;
- private final boolean fIncludeBrace;
-
- /**
- * Creates a template variable proposal.
- *
- * @param variable the template variable
- * @param offset the offset to replace
- * @param length the length to replace
- * @param viewer the viewer
- * @param includeBrace whether to also replace the ${
- */
- public TemplateVariableProposal(TemplateVariableResolver variable, int offset, int length, ITextViewer viewer, boolean includeBrace) {
- fResolver= variable;
- fOffset= offset;
- fLength= length;
- fViewer= viewer;
- fIncludeBrace= includeBrace;
- }
-
- /*
- * @see ICompletionProposal#apply(IDocument)
- */
- public void apply(IDocument document) {
-
- try {
- String variable;
- String type= fResolver.getType();
- if (type.equals("dollar")) //$NON-NLS-1$
- variable= "$$"; //$NON-NLS-1$
- else if (fIncludeBrace)
- variable= "${" + type + '}'; //$NON-NLS-1$
- else
- variable= type;
- document.replace(fOffset, fLength, variable);
- fSelection= new Point(fOffset + variable.length(), 0);
-
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
-
- Shell shell= fViewer.getTextWidget().getShell();
- MessageDialog.openError(shell, TemplatePreferencesMessages.TemplateVariableProposal_error_title, e.getMessage());
- }
- }
-
- /*
- * @see ICompletionProposal#getSelection(IDocument)
- */
- public Point getSelection(IDocument document) {
- return fSelection;
- }
-
- /*
- * @see ICompletionProposal#getAdditionalProposalInfo()
- */
- public String getAdditionalProposalInfo() {
- return fResolver.getDescription();
- }
-
- /*
- * @see ICompletionProposal#getDisplayString()
- */
- public String getDisplayString() {
- return fResolver.getType();
- }
-
- /*
- * @see ICompletionProposal#getImage()
- */
- public Image getImage() {
- return null;
- }
-
- /*
- * @see ICompletionProposal#getContextInformation()
- */
- public IContextInformation getContextInformation() {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/AbstractHierarchyViewerSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/AbstractHierarchyViewerSorter.java
deleted file mode 100644
index 083e735b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/AbstractHierarchyViewerSorter.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SourcePositionComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-
-/**
- */
-public abstract class AbstractHierarchyViewerSorter extends ViewerComparator {
-
- private static final int OTHER= 1;
- private static final int CLASS= 2;
- private static final int ANONYM= 4;
-
- private JavaScriptElementComparator fNormalSorter;
- private SourcePositionComparator fSourcePositonSorter;
-
- public AbstractHierarchyViewerSorter() {
- fNormalSorter= new JavaScriptElementComparator();
- fSourcePositonSorter= new SourcePositionComparator();
- }
-
- protected abstract ITypeHierarchy getHierarchy(IType type);
- public abstract boolean isSortByDefiningType();
- public abstract boolean isSortAlphabetically();
-
-
- protected int getTypeFlags(IType type) throws JavaScriptModelException {
- return type.getFlags();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
- */
- public int category(Object element) {
- if (element instanceof IType) {
- IType type= (IType) element;
- if (type.getElementName().length() == 0) {
- return ANONYM;
- }
-
- return CLASS;
- }
- return OTHER;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerSorter#compare(null, null, null)
- */
- public int compare(Viewer viewer, Object e1, Object e2) {
- if (!isSortAlphabetically() && !isSortByDefiningType()) {
- return fSourcePositonSorter.compare(viewer, e1, e2);
- }
-
- int cat1= category(e1);
- int cat2= category(e2);
-
- if (cat1 != cat2)
- return cat1 - cat2;
-
- if (cat1 == OTHER) { // method or field
- if (isSortByDefiningType()) {
- try {
- IType def1= (e1 instanceof IFunction) ? getDefiningType((IFunction) e1) : null;
- IType def2= (e2 instanceof IFunction) ? getDefiningType((IFunction) e2) : null;
- if (def1 != null) {
- if (def2 != null) {
- if (!def2.equals(def1)) {
- return compareInHierarchy(def1, def2);
- }
- } else {
- return -1;
- }
- } else {
- if (def2 != null) {
- return 1;
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore, default to normal comparison
- }
- }
- if (isSortAlphabetically()) {
- return fNormalSorter.compare(viewer, e1, e2); // use appearance pref page settings
- }
- return 0;
- } else if (cat1 == ANONYM) {
- return 0;
- } else if (isSortAlphabetically()) {
- String name1= ((IType) e1).getElementName();
- String name2= ((IType) e2).getElementName();
- return getComparator().compare(name1, name2);
- }
- return 0;
- }
-
- private IType getDefiningType(IFunction method) throws JavaScriptModelException {
- int flags= method.getFlags();
- if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
- return null;
- }
-
- IType declaringType= method.getDeclaringType();
- if (declaringType != null) {
- ITypeHierarchy hierarchy = getHierarchy(declaringType);
- if (hierarchy != null) {
- MethodOverrideTester tester = new MethodOverrideTester(declaringType, hierarchy);
- IFunction res = tester.findDeclaringMethod(method, true);
- if (res != null) {
- return res.getDeclaringType();
- }
- }
- }
- return null;
- }
-
-
- private int compareInHierarchy(IType def1, IType def2) {
- if (JavaModelUtil.isSuperType(getHierarchy(def1), def2, def1)) {
- return 1;
- } else if (JavaModelUtil.isSuperType(getHierarchy(def2), def1, def2)) {
- return -1;
- }
- String name1= def1.getElementName();
- String name2= def2.getElementName();
-
- return getComparator().compare(name1, name2);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/EnableMemberFilterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/EnableMemberFilterAction.java
deleted file mode 100644
index 1b834e32..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/EnableMemberFilterAction.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-/**
- * Action enable / disable member filtering
- */
-public class EnableMemberFilterAction extends Action {
-
- private ITypeHierarchyViewPart fView;
-
- public EnableMemberFilterAction(ITypeHierarchyViewPart v, boolean initValue) {
- super(TypeHierarchyMessages.EnableMemberFilterAction_label);
- setDescription(TypeHierarchyMessages.EnableMemberFilterAction_description);
- setToolTipText(TypeHierarchyMessages.EnableMemberFilterAction_tooltip);
-
- JavaPluginImages.setLocalImageDescriptors(this, "impl_co.gif"); //$NON-NLS-1$
-
- fView= v;
- setChecked(initValue);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ENABLE_METHODFILTER_ACTION);
-
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- BusyIndicator.showWhile(fView.getSite().getShell().getDisplay(), new Runnable() {
- public void run() {
- fView.showMembersInHierarchy(isChecked());
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnSelectionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnSelectionAction.java
deleted file mode 100644
index 2fad7b3d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnSelectionAction.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Refocuses the type hierarchy on the currently selection type.
- */
-public class FocusOnSelectionAction extends Action {
-
- private ITypeHierarchyViewPart fViewPart;
-
- public FocusOnSelectionAction(ITypeHierarchyViewPart part) {
- super(TypeHierarchyMessages.FocusOnSelectionAction_label);
- setDescription(TypeHierarchyMessages.FocusOnSelectionAction_description);
- setToolTipText(TypeHierarchyMessages.FocusOnSelectionAction_tooltip);
- fViewPart= part;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FOCUS_ON_SELECTION_ACTION);
- }
-
- private ISelection getSelection() {
- ISelectionProvider provider= fViewPart.getSite().getSelectionProvider();
- if (provider != null) {
- return provider.getSelection();
- }
- return null;
- }
-
-
- /*
- * @see Action#run
- */
- public void run() {
- Object element= SelectionUtil.getSingleElement(getSelection());
- if (element instanceof IType) {
- fViewPart.setInputElement((IType)element);
- }
- }
-
- public boolean canActionBeAdded() {
- Object element= SelectionUtil.getSingleElement(getSelection());
- if (element instanceof IType) {
- IType type= (IType)element;
- setText(Messages.format(
- TypeHierarchyMessages.FocusOnSelectionAction_label,
- JavaScriptElementLabels.getTextLabel(type, 0)));
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnTypeAction.java
deleted file mode 100644
index 507d4121..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/FocusOnTypeAction.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-/**
- * Refocuses the type hierarchy on a type selection from a all types dialog.
- */
-public class FocusOnTypeAction extends Action {
-
- private ITypeHierarchyViewPart fViewPart;
-
- public FocusOnTypeAction(ITypeHierarchyViewPart part) {
- super(TypeHierarchyMessages.FocusOnTypeAction_label);
- setDescription(TypeHierarchyMessages.FocusOnTypeAction_description);
- setToolTipText(TypeHierarchyMessages.FocusOnTypeAction_tooltip);
-
- fViewPart= part;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FOCUS_ON_TYPE_ACTION);
- }
-
- /*
- * @see Action#run
- */
- public void run() {
- Shell parent= fViewPart.getSite().getShell();
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(parent, false,
- PlatformUI.getWorkbench().getProgressService(),
- SearchEngine.createWorkspaceScope(), IJavaScriptSearchConstants.TYPE);
-
- dialog.setTitle(TypeHierarchyMessages.FocusOnTypeAction_dialog_title);
- dialog.setMessage(TypeHierarchyMessages.FocusOnTypeAction_dialog_message);
- if (dialog.open() != IDialogConstants.OK_ID) {
- return;
- }
-
- Object[] types= dialog.getResult();
- if (types != null && types.length > 0) {
- IType type= (IType)types[0];
- fViewPart.setInputElement(type);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyInformationControl.java
deleted file mode 100644
index f08ca712..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyInformationControl.java
+++ /dev/null
@@ -1,369 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.keys.KeySequence;
-import org.eclipse.ui.keys.SWTKeySupport;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.AbstractInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.typehierarchy.SuperTypeHierarchyViewer.SuperTypeHierarchyContentProvider;
-import org.eclipse.wst.jsdt.internal.ui.typehierarchy.TraditionalHierarchyViewer.TraditionalHierarchyContentProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-/**
- * Show hierarchy in light-weight control.
- *
- *
- */
-public class HierarchyInformationControl extends AbstractInformationControl {
-
- private TypeHierarchyLifeCycle fLifeCycle;
- private HierarchyLabelProvider fLabelProvider;
- private KeyAdapter fKeyAdapter;
-
- private Object[] fOtherExpandedElements;
- private TypeHierarchyContentProvider fOtherContentProvider;
-
- private IFunction fFocus; // method to filter for or null if type hierarchy
- private boolean fDoFilter;
-
- private MethodOverrideTester fMethodOverrideTester;
-
- public HierarchyInformationControl(Shell parent, int shellStyle, int treeStyle) {
- super(parent, shellStyle, treeStyle, IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, true);
- fOtherExpandedElements= null;
- fDoFilter= true;
- fMethodOverrideTester= null;
- }
-
- private KeyAdapter getKeyAdapter() {
- if (fKeyAdapter == null) {
- fKeyAdapter= new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
- KeySequence keySequence = KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator));
- KeySequence[] sequences= getInvokingCommandKeySequences();
- if (sequences == null)
- return;
-
- for (int i= 0; i < sequences.length; i++) {
- if (sequences[i].equals(keySequence)) {
- e.doit= false;
- toggleHierarchy();
- return;
- }
- }
- }
- };
- }
- return fKeyAdapter;
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean hasHeader() {
- return true;
- }
-
- protected Text createFilterText(Composite parent) {
- // text set later
- Text text= super.createFilterText(parent);
- text.addKeyListener(getKeyAdapter());
- return text;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.text.JavaOutlineInformationControl#createTreeViewer(org.eclipse.swt.widgets.Composite, int)
- */
- protected TreeViewer createTreeViewer(Composite parent, int style) {
- Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
- GridData gd= new GridData(GridData.FILL_BOTH);
- gd.heightHint= tree.getItemHeight() * 12;
- tree.setLayoutData(gd);
-
- TreeViewer treeViewer= new TreeViewer(tree);
- ColoredViewersManager.install(treeViewer);
- treeViewer.addFilter(new ViewerFilter() {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- return element instanceof IType;
- }
- });
-
- fLifeCycle= new TypeHierarchyLifeCycle(false);
-
- treeViewer.setComparator(new HierarchyViewerSorter(fLifeCycle));
- treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
-
- fLabelProvider= new HierarchyLabelProvider(fLifeCycle);
- fLabelProvider.setFilter(new ViewerFilter() {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- return hasFocusMethod((IType) element);
- }
- });
-
- fLabelProvider.setTextFlags(JavaScriptElementLabels.ALL_DEFAULT | JavaScriptElementLabels.T_POST_QUALIFIED);
- fLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
- treeViewer.setLabelProvider(fLabelProvider);
-
- treeViewer.getTree().addKeyListener(getKeyAdapter());
-
- return treeViewer;
- }
-
- protected boolean hasFocusMethod(IType type) {
- if (fFocus == null) {
- return true;
- }
- if (type.equals(fFocus.getDeclaringType())) {
- return true;
- }
-
- try {
- IFunction method= findMethod(fFocus, type);
- if (method != null) {
- // check visibility
- IPackageFragment pack= (IPackageFragment) fFocus.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- if (JavaModelUtil.isVisibleInHierarchy(method, pack)) {
- return true;
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- JavaScriptPlugin.log(e);
- }
- return false;
-
- }
-
- private IFunction findMethod(IFunction filterMethod, IType typeToFindIn) throws JavaScriptModelException {
- IType filterType= filterMethod.getDeclaringType();
- ITypeHierarchy hierarchy= fLifeCycle.getHierarchy();
-
- boolean filterOverrides= JavaModelUtil.isSuperType(hierarchy, typeToFindIn, filterType);
- IType focusType= filterOverrides ? filterType : typeToFindIn;
-
- if (fMethodOverrideTester == null || !fMethodOverrideTester.getFocusType().equals(focusType)) {
- fMethodOverrideTester= new MethodOverrideTester(focusType, hierarchy);
- }
-
- if (filterOverrides) {
- return fMethodOverrideTester.findOverriddenMethodInType(typeToFindIn, filterMethod);
- } else {
- return fMethodOverrideTester.findOverridingMethodInType(typeToFindIn, filterMethod);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInput(Object information) {
- if (!(information instanceof IJavaScriptElement)) {
- inputChanged(null, null);
- return;
- }
- IJavaScriptElement input= null;
- IFunction locked= null;
- try {
- IJavaScriptElement elem= (IJavaScriptElement) information;
- if (elem.getElementType() == IJavaScriptElement.LOCAL_VARIABLE) {
- elem= elem.getParent();
- }
-
- switch (elem.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- case IJavaScriptElement.TYPE :
- input= elem;
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
- input= ((IJavaScriptUnit) elem).findPrimaryType();
- break;
- case IJavaScriptElement.CLASS_FILE :
- input= ((IClassFile) elem).getType();
- break;
- case IJavaScriptElement.METHOD :
- IFunction method= (IFunction) elem;
- if (!method.isConstructor()) {
- locked= method;
- }
- input= method.getDeclaringType();
- break;
- case IJavaScriptElement.FIELD :
- case IJavaScriptElement.INITIALIZER :
- input= ((IMember) elem).getDeclaringType();
- break;
- case IJavaScriptElement.IMPORT_DECLARATION :
- IImportDeclaration decl= (IImportDeclaration) elem;
- if (decl.isOnDemand()) {
- input= JavaModelUtil.findTypeContainer(decl.getJavaScriptProject(), Signature.getQualifier(decl.getElementName()));
- } else {
- input= decl.getJavaScriptProject().findType(decl.getElementName());
- }
- break;
- default :
- JavaScriptPlugin.logErrorMessage("Element unsupported by the hierarchy: " + elem.getClass()); //$NON-NLS-1$
- input= null;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- super.setTitleText(getHeaderLabel(locked == null ? input : locked));
- try {
- fLifeCycle.ensureRefreshedTypeHierarchy(input, JavaScriptPlugin.getActiveWorkbenchWindow());
- } catch (InvocationTargetException e1) {
- input= null;
- } catch (InterruptedException e1) {
- dispose();
- return;
- }
- IMember[] memberFilter= locked != null ? new IMember[] { locked } : null;
-
- TraditionalHierarchyContentProvider contentProvider= new TraditionalHierarchyContentProvider(fLifeCycle);
- contentProvider.setMemberFilter(memberFilter);
- getTreeViewer().setContentProvider(contentProvider);
-
- fOtherContentProvider= new SuperTypeHierarchyContentProvider(fLifeCycle);
- fOtherContentProvider.setMemberFilter(memberFilter);
-
- fFocus= locked;
-
- Object[] topLevelObjects= contentProvider.getElements(fLifeCycle);
- if (topLevelObjects.length > 0 && contentProvider.getChildren(topLevelObjects[0]).length > 40) {
- fDoFilter= false;
- } else {
- getTreeViewer().addFilter(new NamePatternFilter());
- }
-
- Object selection= null;
- if (input instanceof IMember) {
- selection= input;
- } else if (topLevelObjects.length > 0) {
- selection= topLevelObjects[0];
- }
- inputChanged(fLifeCycle, selection);
- }
-
- protected void stringMatcherUpdated() {
- if (fDoFilter) {
- super.stringMatcherUpdated(); // refresh the view
- } else {
- selectFirstMatch();
- }
- }
-
- protected void toggleHierarchy() {
- TreeViewer treeViewer= getTreeViewer();
-
- treeViewer.getTree().setRedraw(false);
-
- Object[] expandedElements= treeViewer.getExpandedElements();
- TypeHierarchyContentProvider contentProvider= (TypeHierarchyContentProvider) treeViewer.getContentProvider();
- treeViewer.setContentProvider(fOtherContentProvider);
-
- treeViewer.refresh();
- if (fOtherExpandedElements != null) {
- treeViewer.setExpandedElements(fOtherExpandedElements);
- } else {
- treeViewer.expandAll();
- }
-
- treeViewer.getTree().setRedraw(true);
-
- fOtherContentProvider= contentProvider;
- fOtherExpandedElements= expandedElements;
-
- updateStatusFieldText();
- }
-
-
- private String getHeaderLabel(IJavaScriptElement input) {
- if (input instanceof IFunction) {
- String[] args= { input.getParent().getElementName(), JavaScriptElementLabels.getElementLabel(input, JavaScriptElementLabels.ALL_DEFAULT) };
- return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_methodhierarchy_label, args);
- } else if (input != null) {
- String arg= JavaScriptElementLabels.getElementLabel(input, JavaScriptElementLabels.DEFAULT_QUALIFIED);
- return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_hierarchy_label, arg);
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-
- protected String getStatusFieldText() {
- KeySequence[] sequences= getInvokingCommandKeySequences();
- String keyName= ""; //$NON-NLS-1$
- if (sequences != null && sequences.length > 0)
- keyName= sequences[0].format();
-
- if (fOtherContentProvider instanceof TraditionalHierarchyContentProvider) {
- return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_toggle_traditionalhierarchy_label, keyName);
- } else {
- return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_toggle_superhierarchy_label, keyName);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.text.AbstractInformationControl#getId()
- */
- protected String getId() {
- return "org.eclipse.wst.jsdt.internal.ui.typehierarchy.QuickHierarchy"; //$NON-NLS-1$
- }
-
- /**
- * {@inheritDoc}
- */
- protected Object getSelectedElement() {
- Object selectedElement= super.getSelectedElement();
- if (selectedElement instanceof IType && fFocus != null) {
- IType type= (IType) selectedElement;
- try {
- return findMethod(fFocus, type);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return selectedElement;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyLabelProvider.java
deleted file mode 100644
index bc06376f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyLabelProvider.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Label provider for the hierarchy viewers. Types in the hierarchy that are not belonging to the
- * input scope are rendered differently.
- */
-public class HierarchyLabelProvider extends AppearanceAwareLabelProvider {
-
- private static class FocusDescriptor extends CompositeImageDescriptor {
- private ImageDescriptor fBase;
- public FocusDescriptor(ImageDescriptor base) {
- fBase= base;
- }
- protected void drawCompositeImage(int width, int height) {
- drawImage(getImageData(fBase), 0, 0);
- drawImage(getImageData(JavaPluginImages.DESC_OVR_FOCUS), 0, 0);
- }
-
- private ImageData getImageData(ImageDescriptor descriptor) {
- ImageData data= descriptor.getImageData(); // see bug 51965: getImageData can return null
- if (data == null) {
- data= DEFAULT_IMAGE_DATA;
- JavaScriptPlugin.logErrorMessage("Image data not available: " + descriptor.toString()); //$NON-NLS-1$
- }
- return data;
- }
-
- protected Point getSize() {
- return JavaElementImageProvider.BIG_SIZE;
- }
- public int hashCode() {
- return fBase.hashCode();
- }
- public boolean equals(Object object) {
- return object != null && FocusDescriptor.class.equals(object.getClass()) && ((FocusDescriptor)object).fBase.equals(fBase);
- }
- }
-
- private Color fSpecialColor;
-
- private ViewerFilter fFilter;
-
- private TypeHierarchyLifeCycle fHierarchy;
-
- public HierarchyLabelProvider(TypeHierarchyLifeCycle lifeCycle) {
- super(DEFAULT_TEXTFLAGS | JavaScriptElementLabels.USE_RESOLVED, DEFAULT_IMAGEFLAGS);
-
- fHierarchy= lifeCycle;
- fFilter= null;
- }
-
- /**
- * @return Returns the filter.
- */
- public ViewerFilter getFilter() {
- return fFilter;
- }
-
- /**
- * @param filter The filter to set.
- */
- public void setFilter(ViewerFilter filter) {
- fFilter= filter;
- }
-
- protected boolean isDifferentScope(IType type) {
- if (fFilter != null && !fFilter.select(null, null, type)) {
- return true;
- }
-
- IJavaScriptElement input= fHierarchy.getInputElement();
- if (input == null || input.getElementType() == IJavaScriptElement.TYPE) {
- return false;
- }
-
- IJavaScriptElement parent= type.getAncestor(input.getElementType());
- if (input.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
- if (parent == null || parent.getElementName().equals(input.getElementName())) {
- return false;
- }
- } else if (input.equals(parent)) {
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getImage
- */
- public Image getImage(Object element) {
- Image result= null;
- if (element instanceof IType) {
- ImageDescriptor desc= getTypeImageDescriptor((IType) element);
- if (desc != null) {
- if (element.equals(fHierarchy.getInputElement())) {
- desc= new FocusDescriptor(desc);
- }
- result= JavaScriptPlugin.getImageDescriptorRegistry().get(desc);
- }
- } else {
- result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element));
- }
- return decorateImage(result, element);
- }
-
- private ImageDescriptor getTypeImageDescriptor(IType type) {
- ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
- if (hierarchy == null) {
- return new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
- }
-
- int flags= hierarchy.getCachedFlags(type);
- if (flags == -1) {
- return new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
- }
-
- boolean isInner= (type.getDeclaringType() != null);
-
- ImageDescriptor desc= JavaElementImageProvider.getTypeImageDescriptor(isInner, false, flags, isDifferentScope(type));
-
- int adornmentFlags= 0;
- if (Flags.isAbstract(flags)) {
- adornmentFlags |= JavaScriptElementImageDescriptor.ABSTRACT;
- }
- if (Flags.isStatic(flags)) {
- adornmentFlags |= JavaScriptElementImageDescriptor.STATIC;
- }
-
- return new JavaScriptElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- if (element instanceof IFunction) {
- if (fSpecialColor == null) {
- fSpecialColor= Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE);
- }
- return fSpecialColor;
- } else if (element instanceof IType && isDifferentScope((IType) element)) {
- return JFaceResources.getColorRegistry().get(ColoredViewersManager.QUALIFIER_COLOR_NAME);
- }
- return null;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyViewerSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyViewerSorter.java
deleted file mode 100644
index 705ca2de..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HierarchyViewerSorter.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-
-/**
- */
-public class HierarchyViewerSorter extends AbstractHierarchyViewerSorter {
-
- private final TypeHierarchyLifeCycle fHierarchy;
- private boolean fSortByDefiningType;
-
- public HierarchyViewerSorter(TypeHierarchyLifeCycle cycle) {
- fHierarchy= cycle;
- }
-
- public void setSortByDefiningType(boolean sortByDefiningType) {
- fSortByDefiningType= sortByDefiningType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#getTypeKind(org.eclipse.wst.jsdt.core.IType)
- */
- protected int getTypeFlags(IType type) {
- ITypeHierarchy hierarchy= getHierarchy(type);
- if (hierarchy != null) {
- return fHierarchy.getHierarchy().getCachedFlags(type);
- }
- return 0;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#isSortByDefiningType()
- */
- public boolean isSortByDefiningType() {
- return fSortByDefiningType;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#isSortAlphabetically()
- */
- public boolean isSortAlphabetically() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.AbstractHierarchyViewerSorter#getHierarchy(org.eclipse.wst.jsdt.core.IType)
- */
- protected ITypeHierarchy getHierarchy(IType type) {
- return fHierarchy.getHierarchy(); // hierarchy contains all types shown
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryAction.java
deleted file mode 100644
index 2e1ab598..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryAction.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Action used for the type hierarchy forward / backward buttons
- */
-public class HistoryAction extends Action {
-
- private TypeHierarchyViewPart fViewPart;
- private IJavaScriptElement fElement;
-
- public HistoryAction(TypeHierarchyViewPart viewPart, IJavaScriptElement element) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- fViewPart= viewPart;
- fElement= element;
-
- String elementName= JavaScriptElementLabels.getElementLabel(element, JavaScriptElementLabels.ALL_POST_QUALIFIED | JavaScriptElementLabels.ALL_DEFAULT);
- setText(elementName);
- setImageDescriptor(getImageDescriptor(element));
-
- setDescription(Messages.format(TypeHierarchyMessages.HistoryAction_description, elementName));
- setToolTipText(Messages.format(TypeHierarchyMessages.HistoryAction_tooltip, elementName));
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.HISTORY_ACTION);
- }
-
- private ImageDescriptor getImageDescriptor(IJavaScriptElement elem) {
- JavaElementImageProvider imageProvider= new JavaElementImageProvider();
- ImageDescriptor desc= imageProvider.getBaseImageDescriptor(elem, 0);
- imageProvider.dispose();
- return desc;
- }
-
- /*
- * @see Action#run()
- */
- public void run() {
- fViewPart.gotoHistoryEntry(fElement);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryDropDownAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryDropDownAction.java
deleted file mode 100644
index 7ca51af1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryDropDownAction.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-public class HistoryDropDownAction extends Action implements IMenuCreator {
-
- public static class ClearHistoryAction extends Action {
-
- private TypeHierarchyViewPart fView;
-
- public ClearHistoryAction(TypeHierarchyViewPart view) {
- super(TypeHierarchyMessages.HistoryDropDownAction_clearhistory_label);
- fView= view;
- }
-
- public void run() {
- fView.setHistoryEntries(new IJavaScriptElement[0]);
- fView.setInputElement(null);
- }
- }
-
- public static final int RESULTS_IN_DROP_DOWN= 10;
-
- private TypeHierarchyViewPart fHierarchyView;
- private Menu fMenu;
-
- public HistoryDropDownAction(TypeHierarchyViewPart view) {
- fHierarchyView= view;
- fMenu= null;
- setToolTipText(TypeHierarchyMessages.HistoryDropDownAction_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.TYPEHIERARCHY_HISTORY_ACTION);
- setMenuCreator(this);
- }
-
- public void dispose() {
- // action is reused, can be called several times.
- if (fMenu != null) {
- fMenu.dispose();
- fMenu= null;
- }
- }
-
- public Menu getMenu(Menu parent) {
- return null;
- }
-
- public Menu getMenu(Control parent) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- fMenu= new Menu(parent);
- IJavaScriptElement[] elements= fHierarchyView.getHistoryEntries();
- addEntries(fMenu, elements);
- new MenuItem(fMenu, SWT.SEPARATOR);
- addActionToMenu(fMenu, new HistoryListAction(fHierarchyView));
- addActionToMenu(fMenu, new ClearHistoryAction(fHierarchyView));
- return fMenu;
- }
-
- private boolean addEntries(Menu menu, IJavaScriptElement[] elements) {
- boolean checked= false;
-
- int min= Math.min(elements.length, RESULTS_IN_DROP_DOWN);
- for (int i= 0; i < min; i++) {
- HistoryAction action= new HistoryAction(fHierarchyView, elements[i]);
- action.setChecked(elements[i].equals(fHierarchyView.getInputElement()));
- checked= checked || action.isChecked();
- addActionToMenu(menu, action);
- }
-
-
- return checked;
- }
-
-
- protected void addActionToMenu(Menu parent, Action action) {
- ActionContributionItem item= new ActionContributionItem(action);
- item.fill(parent, -1);
- }
-
- public void run() {
- (new HistoryListAction(fHierarchyView)).run();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryListAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryListAction.java
deleted file mode 100644
index 723b673d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/HistoryListAction.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-public class HistoryListAction extends Action {
-
- private class HistoryListDialog extends StatusDialog {
-
- private ListDialogField fHistoryList;
- private IStatus fHistoryStatus;
- private IJavaScriptElement fResult;
-
- private HistoryListDialog(Shell shell, IJavaScriptElement[] elements) {
- super(shell);
- setTitle(TypeHierarchyMessages.HistoryListDialog_title);
-
- String[] buttonLabels= new String[] {
- TypeHierarchyMessages.HistoryListDialog_remove_button,
- };
-
- IListAdapter adapter= new IListAdapter() {
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed();
- }
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged();
- }
-
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked();
- }
- };
-
- JavaScriptElementLabelProvider labelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_QUALIFIED | JavaScriptElementLabelProvider.SHOW_ROOT);
-
- fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider);
- fHistoryList.setLabelText(TypeHierarchyMessages.HistoryListDialog_label);
- fHistoryList.setElements(Arrays.asList(elements));
-
- ISelection sel;
- if (elements.length > 0) {
- sel= new StructuredSelection(elements[0]);
- } else {
- sel= new StructuredSelection();
- }
-
- fHistoryList.selectElements(sel);
- }
-
-
- /*
- * @see Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(parent.getFont());
-
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0);
- LayoutUtil.setHeightHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12));
- LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null));
-
- applyDialogFont(composite);
- return composite;
- }
-
- /**
- * Method doCustomButtonPressed.
- */
- private void doCustomButtonPressed() {
- fHistoryList.removeElements(fHistoryList.getSelectedElements());
- }
-
- private void doDoubleClicked() {
- if (fHistoryStatus.isOK()) {
- okPressed();
- }
- }
-
-
- private void doSelectionChanged() {
- StatusInfo status= new StatusInfo();
- List selected= fHistoryList.getSelectedElements();
- if (selected.size() != 1) {
- status.setError(""); //$NON-NLS-1$
- fResult= null;
- } else {
- fResult= (IJavaScriptElement) selected.get(0);
- }
- fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size() && selected.size() != 0);
- fHistoryStatus= status;
- updateStatus(status);
- }
-
- public IJavaScriptElement getResult() {
- return fResult;
- }
-
- public IJavaScriptElement[] getRemaining() {
- List elems= fHistoryList.getElements();
- return (IJavaScriptElement[]) elems.toArray(new IJavaScriptElement[elems.size()]);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#create()
- */
- public void create() {
- setShellStyle(getShellStyle() | SWT.RESIZE);
- super.create();
- }
-
- }
-
- private TypeHierarchyViewPart fView;
-
- public HistoryListAction(TypeHierarchyViewPart view) {
- fView= view;
- setText(TypeHierarchyMessages.HistoryListAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION);
- }
-
- /*
- * @see IAction#run()
- */
- public void run() {
- IJavaScriptElement[] historyEntries= fView.getHistoryEntries();
- HistoryListDialog dialog= new HistoryListDialog(JavaScriptPlugin.getActiveWorkbenchShell(), historyEntries);
- if (dialog.open() == Window.OK) {
- fView.setHistoryEntries(dialog.getRemaining());
- fView.setInputElement(dialog.getResult());
- }
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ITypeHierarchyLifeCycleListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ITypeHierarchyLifeCycleListener.java
deleted file mode 100644
index e8e6a2cc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ITypeHierarchyLifeCycleListener.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.wst.jsdt.core.IType;
-
-
-/**
- * Used by the TypeHierarchyLifeCycle to inform listeners about a change in the
- * type hierarchy
- */
-public interface ITypeHierarchyLifeCycleListener {
-
- /**
- * A Java element changed.
- */
- void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchyProvider, IType[] changedTypes);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsContentProvider.java
deleted file mode 100644
index b74e0a72..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsContentProvider.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyProvider;
-
-/**
- * Content provider used for the method view.
- * Allows also seeing methods inherited from base classes.
- */
-public class MethodsContentProvider implements IStructuredContentProvider, IWorkingCopyProvider {
-
- private static final Object[] NO_ELEMENTS = new Object[0];
-
- private boolean fShowInheritedMethods;
- private TypeHierarchyLifeCycle fHierarchyLifeCycle;
- private TableViewer fViewer;
-
- public MethodsContentProvider(TypeHierarchyLifeCycle lifecycle) {
- fHierarchyLifeCycle= lifecycle;
- fShowInheritedMethods= false;
- fViewer= null;
- }
-
- /**
- * Turn on / off showing of inherited methods
- */
- public void showInheritedMethods(boolean show) {
- if (show != fShowInheritedMethods) {
- fShowInheritedMethods= show;
- if (fViewer != null) {
- fViewer.refresh();
- }
- }
- }
-
- /* (non-Javadoc)
- * @see IStructuredContentProvider#providesWorkingCopies()
- */
- public boolean providesWorkingCopies() {
- return true;
- }
-
- /**
- * Returns true if inherited methods are shown
- */
- public boolean isShowInheritedMethods() {
- return fShowInheritedMethods;
- }
-
-
- private void addAll(Object[] arr, List res) {
- if (arr != null) {
- for (int j= 0; j < arr.length; j++) {
- res.add(arr[j]);
- }
- }
- }
-
- /*
- * @see IStructuredContentProvider#getElements
- */
- public Object[] getElements(Object element) {
- if (element instanceof IType) {
- IType type= (IType)element;
-
- List res= new ArrayList();
- try {
- ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
- if (fShowInheritedMethods && hierarchy != null) {
- IType[] allSupertypes= hierarchy.getAllSuperclasses(type);
- // sort in from last to first: elements with same name
- // will show up in hierarchy order
- for (int i= allSupertypes.length - 1; i >= 0; i--) {
- IType superType= allSupertypes[i];
- if (superType.exists()) {
- addAll(superType.getFunctions(), res);
- addAll(superType.getInitializers(), res);
- addAll(superType.getFields(), res);
- }
- }
- }
- if (type.exists()) {
- addAll(type.getFunctions(), res);
- addAll(type.getInitializers(), res);
- addAll(type.getFields(), res);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return res.toArray();
- }
- return NO_ELEMENTS;
- }
-
-
- /*
- * @see IContentProvider#inputChanged
- */
- public void inputChanged(Viewer input, Object oldInput, Object newInput) {
- Assert.isTrue(input instanceof TableViewer);
-
- fViewer= (TableViewer) input;
- }
-
- /*
- * @see IContentProvider#dispose
- */
- public void dispose() {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsLabelProvider.java
deleted file mode 100644
index bc08318f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsLabelProvider.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Label provider for the hierarchy method viewers.
- */
-public class MethodsLabelProvider extends AppearanceAwareLabelProvider {
-
- private boolean fShowDefiningType;
- private TypeHierarchyLifeCycle fHierarchy;
- private MethodsViewer fMethodsViewer;
- private IPropertyChangeListener fColorRegistryListener;
-
- public MethodsLabelProvider(TypeHierarchyLifeCycle lifeCycle, MethodsViewer methodsViewer) {
- super(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
- fHierarchy= lifeCycle;
- fShowDefiningType= false;
- fMethodsViewer= methodsViewer;
- fColorRegistryListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(ColoredViewersManager.INHERITED_COLOR_NAME)) {
- fireLabelProviderChanged(new LabelProviderChangedEvent(MethodsLabelProvider.this, null));
- }
- }
- };
- JFaceResources.getColorRegistry().addListener(fColorRegistryListener);
- }
-
- public void setShowDefiningType(boolean showDefiningType) {
- fShowDefiningType= showDefiningType;
- }
-
- public boolean isShowDefiningType() {
- return fShowDefiningType;
- }
-
-
- private IType getDefiningType(Object element) throws JavaScriptModelException {
- int kind= ((IJavaScriptElement) element).getElementType();
-
- if (kind != IJavaScriptElement.METHOD && kind != IJavaScriptElement.FIELD && kind != IJavaScriptElement.INITIALIZER) {
- return null;
- }
- IType declaringType= ((IMember) element).getDeclaringType();
- if (kind != IJavaScriptElement.METHOD) {
- return declaringType;
- }
- ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
- if (hierarchy == null) {
- return declaringType;
- }
- IFunction method= (IFunction) element;
- MethodOverrideTester tester= new MethodOverrideTester(declaringType, hierarchy);
- IFunction res= tester.findDeclaringMethod(method, true);
- if (res == null || method.equals(res)) {
- return declaringType;
- }
- return res.getDeclaringType();
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- String text= super.getText(element);
- String qualifier= getQualifier(element);
- if (qualifier != null) {
- return qualifier + text;
- }
- return text;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getRichTextLabel(java.lang.Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- ColoredString text= super.getRichTextLabel(element);
- String qualifier= getQualifier(element);
- if (qualifier != null) {
- return new ColoredString(qualifier).append(text);
- }
- return text;
-
- }
-
- private String getQualifier(Object element) {
- if (fShowDefiningType) {
- try {
- IType type= getDefiningType(element);
- if (type != null) {
- return super.getText(type) + JavaScriptElementLabels.CONCAT_STRING;
- }
- } catch (JavaScriptModelException e) {
- }
- }
- return null;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- if (fMethodsViewer.isShowInheritedMethods() && element instanceof IFunction) {
- IFunction curr= (IFunction) element;
- IMember declaringType= curr.getDeclaringType();
-
- if (declaringType==null || !declaringType.equals(fMethodsViewer.getInput())) {
- return JFaceResources.getColorRegistry().get(ColoredViewersManager.INHERITED_COLOR_NAME);
- }
- }
- return null;
- }
-
- public void dispose() {
- JFaceResources.getColorRegistry().removeListener(fColorRegistryListener);
- fColorRegistryListener= null;
- super.dispose();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java
deleted file mode 100644
index 0dd3a7db..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTableViewer;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.actions.MemberFilterActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-
-/**
- * Method viewer shows a list of methods of a input type.
- * Offers filter actions.
- * No dependency to the type hierarchy view
- */
-public class MethodsViewer extends ProblemTableViewer {
-
- private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$
- private static final String TAG_SORTBYDEFININGTYPE= "sortbydefiningtype"; //$NON-NLS-1$
- private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$
-
- private MethodsLabelProvider fLabelProvider;
-
- private MemberFilterActionGroup fMemberFilterActionGroup;
-
- private OpenAction fOpen;
- private ShowInheritedMembersAction fShowInheritedMembersAction;
- private SortByDefiningTypeAction fSortByDefiningTypeAction;
-
- public MethodsViewer(Composite parent, final TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
- super(new Table(parent, SWT.MULTI));
-
- fLabelProvider= new MethodsLabelProvider(lifeCycle, this);
-
- setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true));
- setContentProvider(new MethodsContentProvider(lifeCycle));
-
- HierarchyViewerSorter sorter= new HierarchyViewerSorter(lifeCycle);
- sorter.setSortByDefiningType(false);
- setComparator(sorter);
-
- fOpen= new OpenAction(part.getSite());
- addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- fOpen.run();
- }
- });
-
- fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView", false, MemberFilterActionGroup.ALL_FILTERS & ~MemberFilterActionGroup.FILTER_LOCALTYPES); //$NON-NLS-1$
-
- fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false);
- fSortByDefiningTypeAction= new SortByDefiningTypeAction(this, false);
-
- showInheritedMethodsNoRedraw(false);
- sortByDefiningTypeNoRedraw(false);
-
- ColoredViewersManager.install(this);
-
- JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
- }
-
- private void showInheritedMethodsNoRedraw(boolean on) {
- MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider();
- cprovider.showInheritedMethods(on);
- fShowInheritedMembersAction.setChecked(on);
- if (on) {
- fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaScriptElementLabels.ALL_POST_QUALIFIED);
- } else {
- fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~JavaScriptElementLabels.ALL_POST_QUALIFIED);
- }
- if (on) {
- sortByDefiningTypeNoRedraw(false);
- }
- fSortByDefiningTypeAction.setEnabled(!on);
-
- }
-
- /**
- * Show inherited methods
- * @param on the new state
- */
- public void showInheritedMethods(boolean on) {
- if (on == isShowInheritedMethods()) {
- return;
- }
- try {
- getTable().setRedraw(false);
- showInheritedMethodsNoRedraw(on);
- refresh();
- } finally {
- getTable().setRedraw(true);
- }
- }
-
- private void sortByDefiningTypeNoRedraw(boolean on) {
- fSortByDefiningTypeAction.setChecked(on);
- fLabelProvider.setShowDefiningType(on);
- ((HierarchyViewerSorter) getComparator()).setSortByDefiningType(on);
- }
-
- /**
- * Show the name of the defining type
- * @param on the new state
- */
- public void sortByDefiningType(boolean on) {
- if (on == isShowDefiningTypes()) {
- return;
- }
- try {
- getTable().setRedraw(false);
- sortByDefiningTypeNoRedraw(on);
- refresh();
- } finally {
- getTable().setRedraw(true);
- }
- }
-
- /*
- * @see Viewer#inputChanged(Object, Object)
- */
- protected void inputChanged(Object input, Object oldInput) {
- super.inputChanged(input, oldInput);
- }
-
- /**
- * Returns <code>true</code> if inherited methods are shown.
- * @return <code>true</code> if inherited methods are shown.
- */
- public boolean isShowInheritedMethods() {
- return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods();
- }
-
- /**
- * Returns <code>true</code> if defining types are shown.
- * @return <code>true</code> if defining types are shown.
- */
- public boolean isShowDefiningTypes() {
- return fLabelProvider.isShowDefiningType();
- }
-
- /**
- * Saves the state of the filter actions
- * @param memento the memento
- */
- public void saveState(IMemento memento) {
- fMemberFilterActionGroup.saveState(memento);
-
- memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods()));
- memento.putString(TAG_SORTBYDEFININGTYPE, String.valueOf(isShowDefiningTypes()));
-
- ScrollBar bar= getTable().getVerticalBar();
- int position= bar != null ? bar.getSelection() : 0;
- memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position));
- }
-
- /**
- * Restores the state of the filter actions
- * @param memento the memento
- */
- public void restoreState(IMemento memento) {
- fMemberFilterActionGroup.restoreState(memento);
- getControl().setRedraw(false);
- refresh();
- getControl().setRedraw(true);
-
- boolean showInherited= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue();
- showInheritedMethods(showInherited);
-
- boolean showDefiningTypes= Boolean.valueOf(memento.getString(TAG_SORTBYDEFININGTYPE)).booleanValue();
- sortByDefiningType(showDefiningTypes);
-
- ScrollBar bar= getTable().getVerticalBar();
- if (bar != null) {
- Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
- if (vScroll != null) {
- bar.setSelection(vScroll.intValue());
- }
- }
- }
-
- /**
- * Attaches a contextmenu listener to the table
- * @param menuListener the menu listener
- * @param popupId the popup id
- * @param viewSite the view site
- */
- public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
- MenuManager menuMgr= new MenuManager();
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(menuListener);
- Menu menu= menuMgr.createContextMenu(getTable());
- getTable().setMenu(menu);
- viewSite.registerContextMenu(popupId, menuMgr, this);
- }
-
-
- /**
- * Fills up the context menu with items for the method viewer
- * Should be called by the creator of the context menu
- * @param menu teh menu manager
- */
- public void contributeToContextMenu(IMenuManager menu) {
- }
-
- /**
- * Fills up the tool bar with items for the method viewer
- * Should be called by the creator of the tool bar
- * @param tbm the tool bar manager
- */
- public void contributeToToolBar(ToolBarManager tbm) {
- tbm.add(fShowInheritedMembersAction);
- tbm.add(fSortByDefiningTypeAction);
- tbm.add(new Separator());
- fMemberFilterActionGroup.contributeToToolBar(tbm);
- }
-
- public void dispose() {
- if (fMemberFilterActionGroup != null) {
- fMemberFilterActionGroup.dispose();
- fMemberFilterActionGroup= null;
- }
- }
-
- /*
- * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection)
- */
- protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
- // on change of input, try to keep selected methods stable by selecting a method with the same
- // signature: See #5466
- List oldSelections= SelectionUtil.toList(invalidSelection);
- List newSelections= SelectionUtil.toList(newSelection);
- if (!oldSelections.isEmpty()) {
- ArrayList newSelectionElements= new ArrayList(newSelections);
- try {
- Object[] currElements= getFilteredChildren(getInput());
- for (int i= 0; i < oldSelections.size(); i++) {
- Object curr= oldSelections.get(i);
- if (curr instanceof IFunction && !newSelections.contains(curr)) {
- IFunction method= (IFunction) curr;
- if (method.exists()) {
- IFunction similar= findSimilarMethod(method, currElements);
- if (similar != null) {
- newSelectionElements.add(similar);
- }
- }
- }
- }
- if (!newSelectionElements.isEmpty()) {
- newSelection= new StructuredSelection(newSelectionElements);
- } else if (currElements.length > 0) {
- newSelection= new StructuredSelection(currElements[0]);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- setSelection(newSelection);
- updateSelection(newSelection);
- }
-
- private IFunction findSimilarMethod(IFunction meth, Object[] elements) throws JavaScriptModelException {
- String name= meth.getElementName();
- String[] paramTypes= meth.getParameterTypes();
- boolean isConstructor= meth.isConstructor();
-
- for (int i= 0; i < elements.length; i++) {
- Object curr= elements[i];
- if (curr instanceof IFunction && JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, (IFunction) curr)) {
- return (IFunction) curr;
- }
- }
- return null;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowInheritedMembersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowInheritedMembersAction.java
deleted file mode 100644
index f5c5bf11..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowInheritedMembersAction.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Action to show / hide inherited members in the method view
- * Depending in the action state a different label provider is installed in the viewer
- */
-public class ShowInheritedMembersAction extends Action {
-
- private MethodsViewer fMethodsViewer;
-
- /**
- * Creates the action.
- */
- public ShowInheritedMembersAction(MethodsViewer viewer, boolean initValue) {
- super(TypeHierarchyMessages.ShowInheritedMembersAction_label);
- setDescription(TypeHierarchyMessages.ShowInheritedMembersAction_description);
- setToolTipText(TypeHierarchyMessages.ShowInheritedMembersAction_tooltip);
-
- JavaPluginImages.setLocalImageDescriptors(this, "inher_co.gif"); //$NON-NLS-1$
-
- fMethodsViewer= viewer;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SHOW_INHERITED_ACTION);
-
- setChecked(initValue);
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- BusyIndicator.showWhile(fMethodsViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fMethodsViewer.showInheritedMethods(isChecked());
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowQualifiedTypeNamesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowQualifiedTypeNamesAction.java
deleted file mode 100644
index 1117d7dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ShowQualifiedTypeNamesAction.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-/**
- * Action enable / disable showing qualified type names
- */
-public class ShowQualifiedTypeNamesAction extends Action {
-
- private ITypeHierarchyViewPart fView;
-
- public ShowQualifiedTypeNamesAction(ITypeHierarchyViewPart v, boolean initValue) {
- super(TypeHierarchyMessages.ShowQualifiedTypeNamesAction_label);
- setDescription(TypeHierarchyMessages.ShowQualifiedTypeNamesAction_description);
- setToolTipText(TypeHierarchyMessages.ShowQualifiedTypeNamesAction_tooltip);
-
- JavaPluginImages.setLocalImageDescriptors(this, "th_showqualified.gif"); //$NON-NLS-1$
-
- fView= v;
- setChecked(initValue);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SHOW_QUALIFIED_NAMES_ACTION);
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- BusyIndicator.showWhile(fView.getSite().getShell().getDisplay(), new Runnable() {
- public void run() {
- fView.showQualifiedTypeNames(isChecked());
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SortByDefiningTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SortByDefiningTypeAction.java
deleted file mode 100644
index 6e526aba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SortByDefiningTypeAction.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Action to let the label provider show the defining type of the method
- */
-public class SortByDefiningTypeAction extends Action {
-
- private MethodsViewer fMethodsViewer;
-
- /**
- * Creates the action.
- */
- public SortByDefiningTypeAction(MethodsViewer viewer, boolean initValue) {
- super(TypeHierarchyMessages.SortByDefiningTypeAction_label);
- setDescription(TypeHierarchyMessages.SortByDefiningTypeAction_description);
- setToolTipText(TypeHierarchyMessages.SortByDefiningTypeAction_tooltip);
-
- JavaPluginImages.setLocalImageDescriptors(this, "definingtype_sort_co.gif"); //$NON-NLS-1$
-
- fMethodsViewer= viewer;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SORT_BY_DEFINING_TYPE_ACTION);
-
- setChecked(initValue);
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- BusyIndicator.showWhile(fMethodsViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fMethodsViewer.sortByDefiningType(isChecked());
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SubTypeHierarchyViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SubTypeHierarchyViewer.java
deleted file mode 100644
index 4a3f9045..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SubTypeHierarchyViewer.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.List;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-
-/**
- * A viewer including the content provider for the subtype hierarchy.
- * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle
- * on construction (shared type hierarchy)
- */
-public class SubTypeHierarchyViewer extends TypeHierarchyViewer {
-
- public SubTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
- super(parent, new SubTypeHierarchyContentProvider(lifeCycle), lifeCycle, part);
- }
-
- /*
- * @see TypeHierarchyViewer#getTitle
- */
- public String getTitle() {
- if (isMethodFiltering()) {
- return TypeHierarchyMessages.SubTypeHierarchyViewer_filtered_title;
- } else {
- return TypeHierarchyMessages.SubTypeHierarchyViewer_title;
- }
- }
-
- /*
- * @see TypeHierarchyViewer#updateContent
- */
- public void updateContent(boolean expand) {
- getTree().setRedraw(false);
- refresh();
-
- if (expand) {
- int expandLevel= 2;
- if (isMethodFiltering()) {
- expandLevel++;
- }
- expandToLevel(expandLevel);
- }
- getTree().setRedraw(true);
- }
-
- /**
- * Content provider for the subtype hierarchy
- */
- public static class SubTypeHierarchyContentProvider extends TypeHierarchyContentProvider {
- public SubTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) {
- super(lifeCycle);
- }
-
- protected final void getTypesInHierarchy(IType type, List res) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType[] types= hierarchy.getSubclasses(type);
- if (isObject(type)) {
- for (int i= 0; i < types.length; i++) {
- IType curr= types[i];
- res.add(curr);
- }
- } else {
- for (int i= 0; i < types.length; i++) {
- res.add(types[i]);
- }
- }
- }
-
- }
-
- protected IType getParentType(IType type) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- return hierarchy.getSuperclass(type);
- }
- return null;
- }
-
-}
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SuperTypeHierarchyViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SuperTypeHierarchyViewer.java
deleted file mode 100644
index 6ad84781..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/SuperTypeHierarchyViewer.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.List;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-
-/**
- * A viewer including the content provider for the supertype hierarchy.
- * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle
- * on construction (shared type hierarchy)
- */
-public class SuperTypeHierarchyViewer extends TypeHierarchyViewer {
-
- public SuperTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
- super(parent, new SuperTypeHierarchyContentProvider(lifeCycle), lifeCycle, part);
- }
-
- /*
- * @see TypeHierarchyViewer#getTitle
- */
- public String getTitle() {
- if (isMethodFiltering()) {
- return TypeHierarchyMessages.SuperTypeHierarchyViewer_filtered_title;
- } else {
- return TypeHierarchyMessages.SuperTypeHierarchyViewer_title;
- }
- }
-
- /*
- * @see TypeHierarchyViewer#updateContent
- */
- public void updateContent(boolean expand) {
- getTree().setRedraw(false);
- refresh();
- if (expand) {
- expandAll();
- }
- getTree().setRedraw(true);
- }
-
- /*
- * Content provider for the supertype hierarchy
- */
- public static class SuperTypeHierarchyContentProvider extends TypeHierarchyContentProvider {
- public SuperTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) {
- super(lifeCycle);
- }
-
- protected final void getTypesInHierarchy(IType type, List res) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType superClass= hierarchy.getSuperclass(type);
- res.add(superClass);
- }
- }
-
- protected IType getParentType(IType type) {
- // cant handle
- return null;
- }
-
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java
deleted file mode 100644
index eff02c4c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.wst.jsdt.internal.ui.actions.AbstractToggleLinkingAction;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-
-/**
- * This action toggles whether the type hierarchy links its selection to the active
- * editor.
- *
- *
- */
-public class ToggleLinkingAction extends AbstractToggleLinkingAction {
-
- private ITypeHierarchyViewPart fHierarchyViewPart;
-
- /**
- * Constructs a new action.
- */
- public ToggleLinkingAction(ITypeHierarchyViewPart part) {
- setChecked(part.isLinkingEnabled());
- fHierarchyViewPart= part;
- }
-
- /**
- * Runs the action.
- */
- public void run() {
- fHierarchyViewPart.setLinkingEnabled(isChecked());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleOrientationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleOrientationAction.java
deleted file mode 100644
index 4bd77150..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleOrientationAction.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-/**
- * Toggles the orientationof the layout of the type hierarchy
- */
-public class ToggleOrientationAction extends Action {
-
- private ITypeHierarchyViewPart fView;
- private int fActionOrientation;
-
- public ToggleOrientationAction(ITypeHierarchyViewPart v, int orientation) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- if (orientation == ITypeHierarchyViewPart.VIEW_LAYOUT_HORIZONTAL) {
- setText(TypeHierarchyMessages.ToggleOrientationAction_horizontal_label);
- setDescription(TypeHierarchyMessages.ToggleOrientationAction_horizontal_description);
- setToolTipText(TypeHierarchyMessages.ToggleOrientationAction_horizontal_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_horizontal.gif"); //$NON-NLS-1$
- } else if (orientation == ITypeHierarchyViewPart.VIEW_LAYOUT_VERTICAL) {
- setText(TypeHierarchyMessages.ToggleOrientationAction_vertical_label);
- setDescription(TypeHierarchyMessages.ToggleOrientationAction_vertical_description);
- setToolTipText(TypeHierarchyMessages.ToggleOrientationAction_vertical_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_vertical.gif"); //$NON-NLS-1$
- } else if (orientation == ITypeHierarchyViewPart.VIEW_LAYOUT_AUTOMATIC) {
- setText(TypeHierarchyMessages.ToggleOrientationAction_automatic_label);
- setDescription(TypeHierarchyMessages.ToggleOrientationAction_automatic_description);
- setToolTipText(TypeHierarchyMessages.ToggleOrientationAction_automatic_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_automatic.gif"); //$NON-NLS-1$
- } else if (orientation == ITypeHierarchyViewPart.VIEW_LAYOUT_SINGLE) {
- setText(TypeHierarchyMessages.ToggleOrientationAction_single_label);
- setDescription(TypeHierarchyMessages.ToggleOrientationAction_single_description);
- setToolTipText(TypeHierarchyMessages.ToggleOrientationAction_single_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "th_single.gif"); //$NON-NLS-1$
- } else {
- Assert.isTrue(false);
- }
- fView= v;
- fActionOrientation= orientation;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.TOGGLE_ORIENTATION_ACTION);
- }
-
- public int getOrientation() {
- return fActionOrientation;
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- if (isChecked()) {
- fView.setViewLayout(fActionOrientation);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleViewAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleViewAction.java
deleted file mode 100644
index 4324d846..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleViewAction.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-
-/**
- * Action to switch between the different hierarchy views.
- */
-public class ToggleViewAction extends Action {
-
- private ITypeHierarchyViewPart fViewPart;
- private int fViewerIndex;
-
- public ToggleViewAction(ITypeHierarchyViewPart v, int viewerIndex) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- String contextHelpId= null;
- if (viewerIndex == ITypeHierarchyViewPart.HIERARCHY_MODE_SUPERTYPES) {
- setText(TypeHierarchyMessages.ToggleViewAction_supertypes_label);
- contextHelpId= IJavaHelpContextIds.SHOW_SUPERTYPES;
- setDescription(TypeHierarchyMessages.ToggleViewAction_supertypes_description);
- setToolTipText(TypeHierarchyMessages.ToggleViewAction_supertypes_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "super_co.gif"); //$NON-NLS-1$
- } else if (viewerIndex == ITypeHierarchyViewPart.HIERARCHY_MODE_SUBTYPES) {
- setText(TypeHierarchyMessages.ToggleViewAction_subtypes_label);
- contextHelpId= IJavaHelpContextIds.SHOW_SUBTYPES;
- setDescription(TypeHierarchyMessages.ToggleViewAction_subtypes_description);
- setToolTipText(TypeHierarchyMessages.ToggleViewAction_subtypes_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "sub_co.gif"); //$NON-NLS-1$
- } else if (viewerIndex == ITypeHierarchyViewPart.HIERARCHY_MODE_CLASSIC) {
- setText(TypeHierarchyMessages.ToggleViewAction_vajhierarchy_label);
- contextHelpId= IJavaHelpContextIds.SHOW_HIERARCHY;
- setDescription(TypeHierarchyMessages.ToggleViewAction_vajhierarchy_description);
- setToolTipText(TypeHierarchyMessages.ToggleViewAction_vajhierarchy_tooltip);
- JavaPluginImages.setLocalImageDescriptors(this, "hierarchy_co.gif"); //$NON-NLS-1$
- } else {
- Assert.isTrue(false);
- }
-
- fViewPart= v;
- fViewerIndex= viewerIndex;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, contextHelpId);
- }
-
- public int getViewerIndex() {
- return fViewerIndex;
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- fViewPart.setHierarchyMode(fViewerIndex);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java
deleted file mode 100644
index bd452194..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-
-/**
- * A TypeHierarchyViewer that looks like the type hierarchy view of VA/Java:
- * Starting form Object down to the element in focus, then all subclasses from
- * this element.
- * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle
- * on construction (shared type hierarchy)
- */
-public class TraditionalHierarchyViewer extends TypeHierarchyViewer {
-
- public TraditionalHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
- super(parent, new TraditionalHierarchyContentProvider(lifeCycle), lifeCycle, part);
- }
-
- /*
- * @see TypeHierarchyViewer#getTitle
- */
- public String getTitle() {
- if (isMethodFiltering()) {
- return TypeHierarchyMessages.TraditionalHierarchyViewer_filtered_title;
- } else {
- return TypeHierarchyMessages.TraditionalHierarchyViewer_title;
- }
- }
-
- /*
- * @see TypeHierarchyViewer#updateContent
- */
- public void updateContent(boolean expand) {
- getTree().setRedraw(false);
- refresh();
-
- if (expand) {
- TraditionalHierarchyContentProvider contentProvider= (TraditionalHierarchyContentProvider) getContentProvider();
- int expandLevel= contentProvider.getExpandLevel();
- if (isMethodFiltering()) {
- expandLevel++;
- }
- expandToLevel(expandLevel);
- }
- getTree().setRedraw(true);
- }
-
- /**
- * Content provider for the 'traditional' type hierarchy.
- */
- public static class TraditionalHierarchyContentProvider extends TypeHierarchyContentProvider {
-
-
- public TraditionalHierarchyContentProvider(TypeHierarchyLifeCycle provider) {
- super(provider);
- }
-
- public int getExpandLevel() {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType input= hierarchy.getType();
- if (input != null) {
- return getDepth(hierarchy, input) + 2;
- } else {
- return 5;
- }
- }
- return 2;
- }
-
- private int getDepth(ITypeHierarchy hierarchy, IType input) {
- int count= 0;
- IType superType= hierarchy.getSuperclass(input);
- while (superType != null) {
- count++;
- superType= hierarchy.getSuperclass(superType);
- }
- return count;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.typehierarchy.TypeHierarchyContentProvider#getRootTypes(java.util.List)
- */
- protected final void getRootTypes(List res) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType input= hierarchy.getType();
- if (input == null) {
- IType[] classes= hierarchy.getRootClasses();
- for (int i= 0; i < classes.length; i++) {
- res.add(classes[i]);
- }
- } else {
- IType[] roots= hierarchy.getRootClasses();
- for (int i= 0; i < roots.length; i++) {
- if (isObject(roots[i])) {
- res.add(roots[i]);
- return;
- }
- }
- res.addAll(Arrays.asList(roots)); // something wrong with the hierarchy
- }
- }
- }
-
- /*
- * @see TypeHierarchyContentProvider.getTypesInHierarchy
- */
- protected final void getTypesInHierarchy(IType type, List res) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType[] types= hierarchy.getSubclasses(type);
- if (isObject(type)) {
- for (int i= 0; i < types.length; i++) {
- IType curr= types[i];
- res.add(curr);
- }
- } else {
- for (int i= 0; i < types.length; i++) {
- res.add(types[i]);
- }
-
- }
- }
- }
-
- protected IType getParentType(IType type) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- return hierarchy.getSuperclass(type);
- }
- return null;
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java
deleted file mode 100644
index c14454fd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyProvider;
-
-/**
- * Base class for content providers for type hierarchy viewers.
- * Implementors must override 'getTypesInHierarchy'.
- * Java delta processing is also performed by the content provider
- */
-public abstract class TypeHierarchyContentProvider implements ITreeContentProvider, IWorkingCopyProvider {
- protected static final Object[] NO_ELEMENTS= new Object[0];
-
- protected TypeHierarchyLifeCycle fTypeHierarchy;
- protected IMember[] fMemberFilter;
-
- protected TreeViewer fViewer;
-
- private ViewerFilter fWorkingSetFilter;
- private MethodOverrideTester fMethodOverrideTester;
- private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
-
-
- public TypeHierarchyContentProvider(TypeHierarchyLifeCycle lifecycle) {
- fTypeHierarchy= lifecycle;
- fMemberFilter= null;
- fWorkingSetFilter= null;
- fMethodOverrideTester= null;
- fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
- public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchyProvider, IType[] changedTypes) {
- if (changedTypes == null) {
- fMethodOverrideTester= null;
- }
- }
- };
- lifecycle.addChangedListener(fTypeHierarchyLifeCycleListener);
- }
-
- /**
- * Sets members to filter the hierarchy for. Set to <code>null</code> to disable member filtering.
- * When member filtering is enabled, the hierarchy contains only types that contain
- * an implementation of one of the filter members and the members themself.
- * The hierarchy can be empty as well.
- */
- public final void setMemberFilter(IMember[] memberFilter) {
- fMemberFilter= memberFilter;
- }
-
- private boolean initializeMethodOverrideTester(IFunction filterMethod, IType typeToFindIn) {
- IType filterType= filterMethod.getDeclaringType();
- ITypeHierarchy hierarchy= fTypeHierarchy.getHierarchy();
-
- boolean filterOverrides= JavaModelUtil.isSuperType(hierarchy, typeToFindIn, filterType);
- IType focusType= filterOverrides ? filterType : typeToFindIn;
-
- if (fMethodOverrideTester == null || !fMethodOverrideTester.getFocusType().equals(focusType)) {
- fMethodOverrideTester= new MethodOverrideTester(focusType, hierarchy);
- }
- return filterOverrides;
- }
-
- private void addCompatibleMethods(IFunction filterMethod, IType typeToFindIn, List children) throws JavaScriptModelException {
- boolean filterMethodOverrides= initializeMethodOverrideTester(filterMethod, typeToFindIn);
- IFunction[] methods= typeToFindIn.getFunctions();
- for (int i= 0; i < methods.length; i++) {
- IFunction curr= methods[i];
- if (isCompatibleMethod(filterMethod, curr, filterMethodOverrides) && !children.contains(curr)) {
- children.add(curr);
- }
- }
- }
-
- private boolean hasCompatibleMethod(IFunction filterMethod, IType typeToFindIn) throws JavaScriptModelException {
- boolean filterMethodOverrides= initializeMethodOverrideTester(filterMethod, typeToFindIn);
- IFunction[] methods= typeToFindIn.getFunctions();
- for (int i= 0; i < methods.length; i++) {
- if (isCompatibleMethod(filterMethod, methods[i], filterMethodOverrides)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isCompatibleMethod(IFunction filterMethod, IFunction method, boolean filterOverrides) throws JavaScriptModelException {
- if (filterOverrides) {
- return fMethodOverrideTester.isSubsignature(filterMethod, method);
- } else {
- return fMethodOverrideTester.isSubsignature(method, filterMethod);
- }
- }
-
- /**
- * The members to filter or <code>null</code> if member filtering is disabled.
- */
- public IMember[] getMemberFilter() {
- return fMemberFilter;
- }
-
- /**
- * Sets a filter representing a working set or <code>null</code> if working sets are disabled.
- */
- public void setWorkingSetFilter(ViewerFilter filter) {
- fWorkingSetFilter= filter;
- }
-
-
- protected final ITypeHierarchy getHierarchy() {
- return fTypeHierarchy.getHierarchy();
- }
-
-
- /* (non-Javadoc)
- * @see IReconciled#providesWorkingCopies()
- */
- public boolean providesWorkingCopies() {
- return true;
- }
-
-
- /*
- * Called for the root element
- * @see IStructuredContentProvider#getElements
- */
- public Object[] getElements(Object parent) {
- ArrayList types= new ArrayList();
- getRootTypes(types);
- for (int i= types.size() - 1; i >= 0; i--) {
- IType curr= (IType) types.get(i);
- try {
- if (!isInTree(curr)) {
- types.remove(i);
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- return types.toArray();
- }
-
- protected void getRootTypes(List res) {
- ITypeHierarchy hierarchy= getHierarchy();
- if (hierarchy != null) {
- IType input= hierarchy.getType();
- if (input != null) {
- res.add(input);
- }
- // opened on a region: dont show
- }
- }
-
- /**
- * Hook to overwrite. Filter will be applied on the returned types
- */
- protected abstract void getTypesInHierarchy(IType type, List res);
-
- /**
- * Hook to overwrite. Return null if parent is ambiguous.
- */
- protected abstract IType getParentType(IType type);
-
-
- private boolean isInScope(IType type) {
- if (fWorkingSetFilter != null && !fWorkingSetFilter.select(null, null, type)) {
- return false;
- }
-
- IJavaScriptElement input= fTypeHierarchy.getInputElement();
- int inputType= input.getElementType();
- if (inputType == IJavaScriptElement.TYPE) {
- return true;
- }
-
- IJavaScriptElement parent= type.getAncestor(input.getElementType());
- if (inputType == IJavaScriptElement.PACKAGE_FRAGMENT) {
- if (parent == null || parent.getElementName().equals(input.getElementName())) {
- return true;
- }
- } else if (input.equals(parent)) {
- return true;
- }
- return false;
- }
-
- /*
- * Called for the tree children.
- * @see ITreeContentProvider#getChildren
- */
- public Object[] getChildren(Object element) {
- if (element instanceof IType) {
- try {
- IType type= (IType)element;
-
- List children= new ArrayList();
- if (fMemberFilter != null) {
- addFilteredMemberChildren(type, children);
- }
-
- addTypeChildren(type, children);
-
- return children.toArray();
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
- return NO_ELEMENTS;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren
- */
- public boolean hasChildren(Object element) {
- if (element instanceof IType) {
- try {
- IType type= (IType) element;
- return hasTypeChildren(type) || (fMemberFilter != null && hasMemberFilterChildren(type));
- } catch (JavaScriptModelException e) {
- return false;
- }
- }
- return false;
- }
-
- private void addFilteredMemberChildren(IType parent, List children) throws JavaScriptModelException {
- for (int i= 0; i < fMemberFilter.length; i++) {
- IMember member= fMemberFilter[i];
- if (parent.equals(member.getDeclaringType())) {
- if (!children.contains(member)) {
- children.add(member);
- }
- } else if (member instanceof IFunction) {
- addCompatibleMethods((IFunction) member, parent, children);
- }
- }
- }
-
- private void addTypeChildren(IType type, List children) throws JavaScriptModelException {
- ArrayList types= new ArrayList();
- getTypesInHierarchy(type, types);
- int len= types.size();
- for (int i= 0; i < len; i++) {
- IType curr= (IType) types.get(i);
- if (isInTree(curr)) {
- children.add(curr);
- }
- }
- }
-
- protected final boolean isInTree(IType type) throws JavaScriptModelException {
- if (isInScope(type)) {
- if (fMemberFilter != null) {
- return hasMemberFilterChildren(type) || hasTypeChildren(type);
- } else {
- return true;
- }
- }
- return hasTypeChildren(type);
- }
-
- private boolean hasMemberFilterChildren(IType type) throws JavaScriptModelException {
- for (int i= 0; i < fMemberFilter.length; i++) {
- IMember member= fMemberFilter[i];
- if (type.equals(member.getDeclaringType())) {
- return true;
- } else if (member instanceof IFunction) {
- if (hasCompatibleMethod((IFunction) member, type)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean hasTypeChildren(IType type) throws JavaScriptModelException {
- ArrayList types= new ArrayList();
- getTypesInHierarchy(type, types);
- int len= types.size();
- for (int i= 0; i < len; i++) {
- IType curr= (IType) types.get(i);
- if (isInTree(curr)) {
- return true;
- }
- }
- return false;
- }
-
- /*
- * @see IContentProvider#inputChanged
- */
- public void inputChanged(Viewer part, Object oldInput, Object newInput) {
- Assert.isTrue(part instanceof TreeViewer);
- fViewer= (TreeViewer)part;
- }
-
- /*
- * @see IContentProvider#dispose
- */
- public void dispose() {
- fTypeHierarchy.removeChangedListener(fTypeHierarchyLifeCycleListener);
-
- }
-
- /*
- * @see ITreeContentProvider#getParent
- */
- public Object getParent(Object element) {
- if (element instanceof IMember) {
- IMember member= (IMember) element;
- if (member.getElementType() == IJavaScriptElement.TYPE) {
- return getParentType((IType)member);
- }
- return member.getDeclaringType();
- }
- return null;
- }
-
- protected final boolean isAnonymous(IType type) {
- return type.getElementName().length() == 0;
- }
-
- protected final boolean isObject(IType type) {
- return "Object".equals(type.getElementName()) && type.getDeclaringType() == null && "java.lang".equals(type.getPackageFragment().getElementName()); //$NON-NLS-1$//$NON-NLS-2$
- }
-
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java
deleted file mode 100644
index f3542b28..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyLifeCycle.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IRegion;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeHierarchyChangedListener;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Manages a type hierarchy, to keep it refreshed, and to allow it to be shared.
- */
-public class TypeHierarchyLifeCycle implements ITypeHierarchyChangedListener, IElementChangedListener {
-
- private boolean fHierarchyRefreshNeeded;
- private ITypeHierarchy fHierarchy;
- private IJavaScriptElement fInputElement;
- private boolean fIsSuperTypesOnly;
-
- private List fChangeListeners;
-
- public TypeHierarchyLifeCycle() {
- this(false);
- }
-
- public TypeHierarchyLifeCycle(boolean isSuperTypesOnly) {
- fHierarchy= null;
- fInputElement= null;
- fIsSuperTypesOnly= isSuperTypesOnly;
- fChangeListeners= new ArrayList(2);
- }
-
- public ITypeHierarchy getHierarchy() {
- return fHierarchy;
- }
-
- public IJavaScriptElement getInputElement() {
- return fInputElement;
- }
-
-
- public void freeHierarchy() {
- if (fHierarchy != null) {
- fHierarchy.removeTypeHierarchyChangedListener(this);
- JavaScriptCore.removeElementChangedListener(this);
- fHierarchy= null;
- fInputElement= null;
- }
- }
-
- public void removeChangedListener(ITypeHierarchyLifeCycleListener listener) {
- fChangeListeners.remove(listener);
- }
-
- public void addChangedListener(ITypeHierarchyLifeCycleListener listener) {
- if (!fChangeListeners.contains(listener)) {
- fChangeListeners.add(listener);
- }
- }
-
- private void fireChange(IType[] changedTypes) {
- for (int i= fChangeListeners.size()-1; i>=0; i--) {
- ITypeHierarchyLifeCycleListener curr= (ITypeHierarchyLifeCycleListener) fChangeListeners.get(i);
- curr.typeHierarchyChanged(this, changedTypes);
- }
- }
-
- public void ensureRefreshedTypeHierarchy(final IJavaScriptElement element, IRunnableContext context) throws InvocationTargetException, InterruptedException {
- if (element == null || !element.exists()) {
- freeHierarchy();
- return;
- }
- boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement));
-
- if (hierachyCreationNeeded || fHierarchyRefreshNeeded) {
-
- IRunnableWithProgress op= new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) throws InvocationTargetException, InterruptedException {
- try {
- doHierarchyRefresh(element, pm);
- } catch (JavaScriptModelException e) {
- throw new InvocationTargetException(e);
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- }
- }
- };
- fHierarchyRefreshNeeded= true;
- context.run(true, true, op);
- fHierarchyRefreshNeeded= false;
- }
- }
-
- private ITypeHierarchy createTypeHierarchy(IJavaScriptElement element, IProgressMonitor pm) throws JavaScriptModelException {
- if (element.getElementType() == IJavaScriptElement.TYPE) {
- IType type= (IType) element;
- if (fIsSuperTypesOnly) {
- return type.newSupertypeHierarchy(pm);
- } else {
- return type.newTypeHierarchy(pm);
- }
- } else {
- IRegion region= JavaScriptCore.newRegion();
- if (element.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- // for projects only add the contained source folders
- IPackageFragmentRoot[] roots= ((IJavaScriptProject) element).getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (!roots[i].isExternal()) {
- region.add(roots[i]);
- }
- }
- } else if (element.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) {
- IPackageFragmentRoot[] roots= element.getJavaScriptProject().getPackageFragmentRoots();
- String name= element.getElementName();
- for (int i= 0; i < roots.length; i++) {
- IPackageFragment pack= roots[i].getPackageFragment(name);
- if (pack.exists()) {
- region.add(pack);
- }
- }
- } else {
- region.add(element);
- }
- IJavaScriptProject jproject= element.getJavaScriptProject();
- return jproject.newTypeHierarchy(region, pm);
- }
- }
-
-
- public synchronized void doHierarchyRefresh(IJavaScriptElement element, IProgressMonitor pm) throws JavaScriptModelException {
- boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement));
- // to ensure the order of the two listeners always remove / add listeners on operations
- // on type hierarchies
- if (fHierarchy != null) {
- fHierarchy.removeTypeHierarchyChangedListener(this);
- JavaScriptCore.removeElementChangedListener(this);
- }
- if (hierachyCreationNeeded) {
- fHierarchy= createTypeHierarchy(element, pm);
- if (pm != null && pm.isCanceled()) {
- throw new OperationCanceledException();
- }
- fInputElement= element;
- } else {
- fHierarchy.refresh(pm);
- }
- fHierarchy.addTypeHierarchyChangedListener(this);
- JavaScriptCore.addElementChangedListener(this);
- fHierarchyRefreshNeeded= false;
- }
-
- /*
- * @see ITypeHierarchyChangedListener#typeHierarchyChanged
- */
- public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) {
- fHierarchyRefreshNeeded= true;
- fireChange(null);
- }
-
- /*
- * @see IElementChangedListener#elementChanged(ElementChangedEvent)
- */
- public void elementChanged(ElementChangedEvent event) {
- if (fChangeListeners.isEmpty()) {
- return;
- }
-
- if (fHierarchyRefreshNeeded) {
- return;
- } else {
- ArrayList changedTypes= new ArrayList();
- processDelta(event.getDelta(), changedTypes);
- if (changedTypes.size() > 0) {
- fireChange((IType[]) changedTypes.toArray(new IType[changedTypes.size()]));
- }
- }
- }
-
- /*
- * Assume that the hierarchy is intact (no refresh needed)
- */
- private void processDelta(IJavaScriptElementDelta delta, ArrayList changedTypes) {
- IJavaScriptElement element= delta.getElement();
- switch (element.getElementType()) {
- case IJavaScriptElement.TYPE:
- processTypeDelta((IType) element, changedTypes);
- processChildrenDelta(delta, changedTypes); // (inner types)
- break;
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- processChildrenDelta(delta, changedTypes);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- IJavaScriptUnit cu= (IJavaScriptUnit)element;
- if (!JavaModelUtil.isPrimary(cu)) {
- return;
- }
-
- if (delta.getKind() == IJavaScriptElementDelta.CHANGED && isPossibleStructuralChange(delta.getFlags())) {
- try {
- if (cu.exists()) {
- IType[] types= cu.getAllTypes();
- for (int i= 0; i < types.length; i++) {
- processTypeDelta(types[i], changedTypes);
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- } else {
- processChildrenDelta(delta, changedTypes);
- }
- break;
- case IJavaScriptElement.CLASS_FILE:
- if (delta.getKind() == IJavaScriptElementDelta.CHANGED) {
- IType type= ((IClassFile) element).getType();
- processTypeDelta(type, changedTypes);
- } else {
- processChildrenDelta(delta, changedTypes);
- }
- break;
- }
- }
-
- private boolean isPossibleStructuralChange(int flags) {
- return (flags & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_FINE_GRAINED)) == IJavaScriptElementDelta.F_CONTENT;
- }
-
- private void processTypeDelta(IType type, ArrayList changedTypes) {
- if (getHierarchy().contains(type)) {
- changedTypes.add(type);
- }
- }
-
- private void processChildrenDelta(IJavaScriptElementDelta delta, ArrayList changedTypes) {
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- processDelta(children[i], changedTypes); // recursive
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.java
deleted file mode 100644
index fec44802..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class TypeHierarchyMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.typehierarchy.TypeHierarchyMessages";//$NON-NLS-1$
-
- private TypeHierarchyMessages() {
- // Do not instantiate
- }
-
- public static String EnableMemberFilterAction_label;
- public static String EnableMemberFilterAction_tooltip;
- public static String EnableMemberFilterAction_description;
- public static String HistoryDropDownAction_clearhistory_label;
- public static String ToggleOrientationAction_horizontal_label;
- public static String ToggleOrientationAction_horizontal_tooltip;
- public static String ToggleOrientationAction_horizontal_description;
- public static String ToggleOrientationAction_vertical_label;
- public static String ToggleOrientationAction_vertical_tooltip;
- public static String ToggleOrientationAction_vertical_description;
- public static String ToggleOrientationAction_automatic_label;
- public static String ToggleOrientationAction_automatic_tooltip;
- public static String ToggleOrientationAction_automatic_description;
- public static String ToggleOrientationAction_single_label;
- public static String ToggleOrientationAction_single_tooltip;
- public static String ToggleOrientationAction_single_description;
- public static String FocusOnSelectionAction_label;
- public static String FocusOnSelectionAction_tooltip;
- public static String FocusOnSelectionAction_description;
- public static String FocusOnTypeAction_label;
- public static String FocusOnTypeAction_tooltip;
- public static String FocusOnTypeAction_description;
- public static String FocusOnTypeAction_dialog_title;
- public static String FocusOnTypeAction_dialog_message;
- public static String HistoryDropDownAction_tooltip;
- public static String HistoryAction_description;
- public static String HistoryAction_tooltip;
- public static String HistoryListDialog_title;
- public static String HistoryListDialog_label;
- public static String HistoryListDialog_remove_button;
- public static String HistoryListAction_label;
- public static String ShowInheritedMembersAction_label;
- public static String ShowInheritedMembersAction_tooltip;
- public static String ShowInheritedMembersAction_description;
- public static String ShowQualifiedTypeNamesAction_label;
- public static String ShowQualifiedTypeNamesAction_tooltip;
- public static String ShowQualifiedTypeNamesAction_description;
- public static String SortByDefiningTypeAction_label;
- public static String SortByDefiningTypeAction_tooltip;
- public static String SortByDefiningTypeAction_description;
- public static String SubTypeHierarchyViewer_title;
- public static String SubTypeHierarchyViewer_filtered_title;
- public static String SuperTypeHierarchyViewer_title;
- public static String SuperTypeHierarchyViewer_filtered_title;
- public static String TraditionalHierarchyViewer_title;
- public static String TraditionalHierarchyViewer_filtered_title;
- public static String TypeHierarchyViewPart_createinput;
- public static String TypeHierarchyViewPart_error_title;
- public static String TypeHierarchyViewPart_error_message;
- public static String TypeHierarchyViewPart_empty;
- public static String TypeHierarchyViewPart_nodecl;
- public static String TypeHierarchyViewPart_exception_title;
- public static String TypeHierarchyViewPart_exception_message;
- public static String TypeHierarchyViewPart_title;
- public static String TypeHierarchyViewPart_tooltip;
- public static String TypeHierarchyViewPart_ws_title;
- public static String TypeHierarchyViewPart_ws_tooltip;
- public static String TypeHierarchyViewPart_restoreinput;
- public static String TypeHierarchyViewPart_layout_submenu;
- public static String ToggleViewAction_subtypes_label;
- public static String ToggleViewAction_subtypes_tooltip;
- public static String ToggleViewAction_subtypes_description;
- public static String ToggleViewAction_supertypes_label;
- public static String ToggleViewAction_supertypes_tooltip;
- public static String ToggleViewAction_supertypes_description;
- public static String ToggleViewAction_vajhierarchy_label;
- public static String ToggleViewAction_vajhierarchy_tooltip;
- public static String ToggleViewAction_vajhierarchy_description;
- public static String HierarchyInformationControl_methodhierarchy_label;
- public static String HierarchyInformationControl_hierarchy_label;
- public static String HierarchyInformationControl_toggle_traditionalhierarchy_label;
- public static String HierarchyInformationControl_toggle_superhierarchy_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, TypeHierarchyMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties
deleted file mode 100644
index 6cf712cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties
+++ /dev/null
@@ -1,109 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-EnableMemberFilterAction_label=Members in Hierarchy
-EnableMemberFilterAction_tooltip=Lock View and Show Members in Hierarchy
-EnableMemberFilterAction_description=Lock view and show members in hierarchy
-
-ToggleOrientationAction_horizontal_label=&Horizontal View Orientation
-ToggleOrientationAction_horizontal_tooltip=Horizontal View Orientation
-ToggleOrientationAction_horizontal_description=Horizontal View Orientation
-
-ToggleOrientationAction_vertical_label=&Vertical View Orientation
-ToggleOrientationAction_vertical_tooltip=Vertical View Orientation
-ToggleOrientationAction_vertical_description=Vertical View Orientation
-
-ToggleOrientationAction_automatic_label=&Automatic View Orientation
-ToggleOrientationAction_automatic_tooltip=Automatic View Orientation
-ToggleOrientationAction_automatic_description=Automatic View Orientation
-
-
-ToggleOrientationAction_single_label=Hierarchy View &Only
-ToggleOrientationAction_single_tooltip=Hierarchy View Only
-ToggleOrientationAction_single_description=Hierarchy View Only
-
-FocusOnSelectionAction_label=Fo&cus On ''{0}''
-FocusOnSelectionAction_tooltip=Focus the Type Hierarchy on the Selected Element
-FocusOnSelectionAction_description=Focus the Type Hierarchy on the selected element
-
-FocusOnTypeAction_label=Foc&us On...
-FocusOnTypeAction_tooltip=Focus the Type Hierarchy on a New Type
-FocusOnTypeAction_description=Focus the Type Hierarchy on a new type
-FocusOnTypeAction_dialog_title=Focus On Type
-FocusOnTypeAction_dialog_message=&Select the type to be shown in the Type Hierarchy view:
-
-HistoryDropDownAction_tooltip=Previous Type Hierarchies
-HistoryDropDownAction_clearhistory_label=Clear History
-
-HistoryAction_description=Open ''{0}'' in Hierarchy
-HistoryAction_tooltip=Open ''{0}'' in Hierarchy
-
-HistoryListDialog_title=Type Hierarchy History
-HistoryListDialog_label=&Select the element to open in the type hierarchy:
-HistoryListDialog_remove_button=&Remove
-
-HistoryListAction_label=History...
-
-ShowInheritedMembersAction_label=All Inherited Members
-ShowInheritedMembersAction_tooltip=Show All Inherited Members
-ShowInheritedMembersAction_description=Show all inherited members
-
-ShowQualifiedTypeNamesAction_label=Show &Qualified Type Names
-ShowQualifiedTypeNamesAction_tooltip=Show Qualified Type Names
-ShowQualifiedTypeNamesAction_description=Show qualified type names
-
-SortByDefiningTypeAction_label=Sort by the Defining Type
-SortByDefiningTypeAction_tooltip=Sort Methods by the Defining Type
-SortByDefiningTypeAction_description=Sort methods by the defining type
-
-SubTypeHierarchyViewer_title=Hierarchy
-SubTypeHierarchyViewer_filtered_title=Hierarchy
-
-SuperTypeHierarchyViewer_title=Hierarchy
-SuperTypeHierarchyViewer_filtered_title=Hierarchy
-
-TraditionalHierarchyViewer_title=Hierarchy
-TraditionalHierarchyViewer_filtered_title=Hierarchy
-
-TypeHierarchyViewPart_error_title=Open Type Hierarchy
-TypeHierarchyViewPart_createinput=Creating type hierarchy of ''{0}''...
-
-TypeHierarchyViewPart_error_message=The selected element only exists in the editor. To perform this operation you have to save the editor first.
-TypeHierarchyViewPart_empty=To display the type hierarchy, select a type (for example in the outline view or in the editor), and select the \'Open Type Hierarchy\' menu option. Alternatively, you can drag and drop an element (e.g. project, package, type) onto this view.
-TypeHierarchyViewPart_nodecl=All types of the current hierarchy ''{0}'' have been filtered by either the selected working set or the chosen locked method.
-TypeHierarchyViewPart_exception_title=Type Hierarchy
-TypeHierarchyViewPart_exception_message=Creating hierarchy failed. See log for details.
-
-TypeHierarchyViewPart_title={1}
-TypeHierarchyViewPart_tooltip={0} of ''{1}''
-TypeHierarchyViewPart_ws_title={1}, working set: {2}
-TypeHierarchyViewPart_ws_tooltip={0} of {1} - working set: {2}
-
-TypeHierarchyViewPart_restoreinput=Restoring type hierarchy of ''{0}''...
-
-TypeHierarchyViewPart_layout_submenu=&Layout
-
-ToggleViewAction_subtypes_label=Su&btype Hierarchy
-ToggleViewAction_subtypes_tooltip=Show the Subtype Hierarchy
-ToggleViewAction_subtypes_description=Show the subtype hierarchy
-
-ToggleViewAction_supertypes_label=Su&pertype Hierarchy
-ToggleViewAction_supertypes_tooltip=Show the Supertype Hierarchy
-ToggleViewAction_supertypes_description=Show the supertype hierarchy
-
-ToggleViewAction_vajhierarchy_label=&Type Hierarchy
-ToggleViewAction_vajhierarchy_tooltip=Show the Type Hierarchy
-ToggleViewAction_vajhierarchy_description=Show the type hierarchy
-
-HierarchyInformationControl_methodhierarchy_label=Types implementing or defining ''{0}.{1}''
-HierarchyInformationControl_hierarchy_label=Type hierarchy of ''{0}'':
-HierarchyInformationControl_toggle_traditionalhierarchy_label=Press ''{0}'' to see the subtype hierarchy
-HierarchyInformationControl_toggle_superhierarchy_label=Press ''{0}'' to see the supertype hierarchy
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyTransferDropAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyTransferDropAdapter.java
deleted file mode 100644
index 38b11433..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyTransferDropAdapter.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.OpenTypeHierarchyUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-
-public class TypeHierarchyTransferDropAdapter extends SelectionTransferDropAdapter {
-
- private static final int OPERATION = DND.DROP_LINK;
- private TypeHierarchyViewPart fTypeHierarchyViewPart;
-
- public TypeHierarchyTransferDropAdapter(TypeHierarchyViewPart viewPart, AbstractTreeViewer viewer) {
- super(viewer);
- setFullWidthMatchesItem(false);
- fTypeHierarchyViewPart= viewPart;
- }
-
- public void validateDrop(Object target, DropTargetEvent event, int operation) {
- event.detail= DND.DROP_NONE;
- initializeSelection();
- if (target != null){
- super.validateDrop(target, event, operation);
- return;
- }
- if (getInputElement(getSelection()) != null)
- event.detail= TypeHierarchyTransferDropAdapter.OPERATION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDropAdapter#isEnabled(org.eclipse.swt.dnd.DropTargetEvent)
- */
- public boolean isEnabled(DropTargetEvent event) {
- return true;
- }
-
- public void drop(Object target, DropTargetEvent event) {
- if (target != null || event.detail != TypeHierarchyTransferDropAdapter.OPERATION){
- super.drop(target, event);
- return;
- }
- IJavaScriptElement input= getInputElement(getSelection());
- fTypeHierarchyViewPart.setInputElement(input);
- }
-
- private static IJavaScriptElement getInputElement(ISelection selection) {
- Object single= SelectionUtil.getSingleElement(selection);
- if (single == null)
- return null;
- IJavaScriptElement[] candidates= OpenTypeHierarchyUtil.getCandidates(single);
- if (candidates != null && candidates.length > 0)
- return candidates[0];
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
deleted file mode 100644
index 1b582709..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
+++ /dev/null
@@ -1,1646 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.util.TransferDragSourceListener;
-import org.eclipse.jface.util.TransferDropTargetListener;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.IBasicPropertyConstants;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.custom.ViewForm;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.part.IShowInSource;
-import org.eclipse.ui.part.IShowInTargetList;
-import org.eclipse.ui.part.PageBook;
-import org.eclipse.ui.part.ResourceTransfer;
-import org.eclipse.ui.part.ShowInContext;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.views.navigator.LocalSelectionTransfer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.NewWizardsActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectAllAction;
-import org.eclipse.wst.jsdt.internal.ui.dnd.DelegatingDropAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.JdtViewerDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dnd.ResourceTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.packageview.SelectionTransferDragAdapter;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.SelectionProviderMediator;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StatusBarUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-import org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.CCPActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.GenerateActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.JavaSearchActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenEditorActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.OpenViewActionGroup;
-import org.eclipse.wst.jsdt.ui.actions.RefactorActionGroup;
-
-/**
- * view showing the super types/sub types of its input.
- */
-public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
-
- private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
- private static final String DIALOGSTORE_VIEWLAYOUT= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
- private static final String DIALOGSTORE_QUALIFIED_NAMES= "TypeHierarchyViewPart.qualifiednames"; //$NON-NLS-1$
- private static final String DIALOGSTORE_LINKEDITORS= "TypeHierarchyViewPart.linkeditors"; //$NON-NLS-1$
-
- private static final String TAG_INPUT= "input"; //$NON-NLS-1$
- private static final String TAG_VIEW= "view"; //$NON-NLS-1$
- private static final String TAG_LAYOUT= "orientation"; //$NON-NLS-1$
- private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
- private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
- private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
- private static final String TAG_QUALIFIED_NAMES= "qualified_names"; //$NON-NLS-1$
- private static final String TAG_EDITOR_LINKING= "link_editors"; //$NON-NLS-1$
-
- private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
-
-
-
- // the selected type in the hierarchy view
- private IType fSelectedType;
- // input element or null
- private IJavaScriptElement fInputElement;
-
- // history of input elements. No duplicates
- private ArrayList fInputHistory;
-
- private IMemento fMemento;
- private IDialogSettings fDialogSettings;
-
- private TypeHierarchyLifeCycle fHierarchyLifeCycle;
- private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
-
- private IPropertyChangeListener fPropertyChangeListener;
-
- private SelectionProviderMediator fSelectionProviderMediator;
- private ISelectionChangedListener fSelectionChangedListener;
- private IPartListener2 fPartListener;
-
- private int fCurrentLayout;
- private boolean fInComputeLayout;
-
- private boolean fLinkingEnabled;
- private boolean fShowQualifiedTypeNames;
- private boolean fSelectInEditor;
-
- private boolean fIsVisible;
- private boolean fNeedRefresh;
- private boolean fIsEnableMemberFilter;
- private boolean fIsRefreshRunnablePosted;
-
- private int fCurrentViewerIndex;
- private TypeHierarchyViewer[] fAllViewers;
-
- private MethodsViewer fMethodsViewer;
-
- private SashForm fTypeMethodsSplitter;
- private PageBook fViewerbook;
- private PageBook fPagebook;
-
- private Label fNoHierarchyShownLabel;
- private Label fEmptyTypesViewer;
-
- private ViewForm fTypeViewerViewForm;
- private ViewForm fMethodViewerViewForm;
-
- private CLabel fMethodViewerPaneLabel;
- private JavaUILabelProvider fPaneLabelProvider;
- private Composite fParent;
-
- private ToggleViewAction[] fViewActions;
- private ToggleLinkingAction fToggleLinkingAction;
- private HistoryDropDownAction fHistoryDropDownAction;
- private ToggleOrientationAction[] fToggleOrientationActions;
- private EnableMemberFilterAction fEnableMemberFilterAction;
- private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
- private FocusOnTypeAction fFocusOnTypeAction;
- private FocusOnSelectionAction fFocusOnSelectionAction;
- private CompositeActionGroup fActionGroups;
- private SelectAllAction fSelectAllAction;
-
- private WorkingSetFilterActionGroup fWorkingSetActionGroup;
- private Job fRestoreStateJob;
-
- public TypeHierarchyViewPart() {
- fSelectedType= null;
- fInputElement= null;
- fIsVisible= false;
- fIsRefreshRunnablePosted= false;
- fSelectInEditor= true;
- fRestoreStateJob= null;
-
- fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
- fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
- public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
- doTypeHierarchyChanged(typeHierarchy, changedTypes);
- }
- };
- fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
-
- fPropertyChangeListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doPropertyChange(event);
- }
- };
- PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
-
- fIsEnableMemberFilter= false;
-
- fInputHistory= new ArrayList();
- fAllViewers= null;
-
- fViewActions= new ToggleViewAction[] {
- new ToggleViewAction(this, HIERARCHY_MODE_CLASSIC),
- new ToggleViewAction(this, HIERARCHY_MODE_SUPERTYPES),
- new ToggleViewAction(this, HIERARCHY_MODE_SUBTYPES)
- };
-
- fDialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
-
- fHistoryDropDownAction= new HistoryDropDownAction(this);
- fHistoryDropDownAction.setEnabled(false);
-
- fToggleOrientationActions= new ToggleOrientationAction[] {
- new ToggleOrientationAction(this, VIEW_LAYOUT_VERTICAL),
- new ToggleOrientationAction(this, VIEW_LAYOUT_HORIZONTAL),
- new ToggleOrientationAction(this, VIEW_LAYOUT_AUTOMATIC),
- new ToggleOrientationAction(this, VIEW_LAYOUT_SINGLE)
- };
-
- fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
- fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false);
-
- fFocusOnTypeAction= new FocusOnTypeAction(this);
-
- fToggleLinkingAction= new ToggleLinkingAction(this);
-
- fPaneLabelProvider= new JavaUILabelProvider();
-
- fFocusOnSelectionAction= new FocusOnSelectionAction(this);
-
- fPartListener= new IPartListener2() {
- public void partVisible(IWorkbenchPartReference ref) {
- IWorkbenchPart part= ref.getPart(false);
- if (part == TypeHierarchyViewPart.this) {
- visibilityChanged(true);
- }
- }
-
- public void partHidden(IWorkbenchPartReference ref) {
- IWorkbenchPart part= ref.getPart(false);
- if (part == TypeHierarchyViewPart.this) {
- visibilityChanged(false);
- }
- }
-
- public void partActivated(IWorkbenchPartReference ref) {
- IWorkbenchPart part= ref.getPart(false);
- if (part instanceof IEditorPart)
- editorActivated((IEditorPart) part);
- }
-
- public void partInputChanged(IWorkbenchPartReference ref) {
- IWorkbenchPart part= ref.getPart(false);
- if (part instanceof IEditorPart)
- editorActivated((IEditorPart) part);
- }
-
- public void partBroughtToTop(IWorkbenchPartReference ref) {}
- public void partClosed(IWorkbenchPartReference ref) {}
- public void partDeactivated(IWorkbenchPartReference ref) {}
- public void partOpened(IWorkbenchPartReference ref) {}
- };
-
- fSelectionChangedListener= new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- doSelectionChanged(event);
- }
- };
- }
-
- /**
- * Method doPropertyChange.
- * @param event
- */
- protected void doPropertyChange(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (fMethodsViewer != null) {
- if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
- fMethodsViewer.refresh();
- }
- }
- if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- updateHierarchyViewer(true);
- updateTitle();
- }
- }
-
- /**
- * Adds the entry if new. Inserted at the beginning of the history entries list.
- * @param entry The new entry
- */
- private void addHistoryEntry(IJavaScriptElement entry) {
- if (fInputHistory.contains(entry)) {
- fInputHistory.remove(entry);
- }
- fInputHistory.add(0, entry);
- fHistoryDropDownAction.setEnabled(true);
- }
-
- private void updateHistoryEntries() {
- for (int i= fInputHistory.size() - 1; i >= 0; i--) {
- IJavaScriptElement type= (IJavaScriptElement) fInputHistory.get(i);
- if (!type.exists()) {
- fInputHistory.remove(i);
- }
- }
- fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
- }
-
- /**
- * Goes to the selected entry, without updating the order of history entries.
- * @param entry The entry to open
- */
- public void gotoHistoryEntry(IJavaScriptElement entry) {
- if (fInputHistory.contains(entry)) {
- updateInput(entry);
- }
- }
-
- /**
- * Gets all history entries.
- * @return All history entries
- */
- public IJavaScriptElement[] getHistoryEntries() {
- if (fInputHistory.size() > 0) {
- updateHistoryEntries();
- }
- return (IJavaScriptElement[]) fInputHistory.toArray(new IJavaScriptElement[fInputHistory.size()]);
- }
-
- /**
- * Sets the history entries
- * @param elems The history elements to set
- */
- public void setHistoryEntries(IJavaScriptElement[] elems) {
- fInputHistory.clear();
- for (int i= 0; i < elems.length; i++) {
- fInputHistory.add(elems[i]);
- }
- updateHistoryEntries();
- }
-
- /**
- * Selects an member in the methods list or in the current hierarchy.
- * @param member The member to select
- */
- public void selectMember(IMember member) {
- fSelectInEditor= false;
- if (member.getElementType() != IJavaScriptElement.TYPE) {
- Control methodControl= fMethodsViewer.getControl();
- if (methodControl != null && !methodControl.isDisposed()) {
- methodControl.setFocus();
- }
-
- fMethodsViewer.setSelection(new StructuredSelection(member), true);
- } else {
- Control viewerControl= getCurrentViewer().getControl();
- if (viewerControl != null && !viewerControl.isDisposed()) {
- viewerControl.setFocus();
- }
-
- if (!member.equals(fSelectedType)) {
- getCurrentViewer().setSelection(new StructuredSelection(member), true);
- }
- }
- fSelectInEditor= true;
- }
-
- /**
- * Sets the input to a new type
- * @param type The new input type
- * @deprecated
- */
- public void setInput(IType type) {
- setInputElement(type);
- }
-
- /**
- * Returns the input element of the type hierarchy.
- * Can be of type <code>IType</code> or <code>IPackageFragment</code>
- * @return the input element
- */
- public IJavaScriptElement getInputElement() {
- return fInputElement;
- }
-
-
- /**
- * Sets the input to a new element.
- * @param element the input element
- */
- public void setInputElement(IJavaScriptElement element) {
- IMember memberToSelect= null;
- if (element != null) {
- if (element instanceof IMember) {
- if (element.getElementType() != IJavaScriptElement.TYPE) {
- memberToSelect= (IMember) element;
- element= memberToSelect.getDeclaringType();
-
- }
- if (element == null || !element.exists()) {
- MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.TypeHierarchyViewPart_error_title, TypeHierarchyMessages.TypeHierarchyViewPart_error_message);
- return;
- }
- } else {
- int kind= element.getElementType();
- if (kind != IJavaScriptElement.JAVASCRIPT_PROJECT && kind != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaScriptElement.PACKAGE_FRAGMENT) {
- element= null;
- JavaScriptPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
- }
- }
- }
- if (element != null && !element.equals(fInputElement)) {
- addHistoryEntry(element);
- }
-
- updateInput(element);
- if (memberToSelect != null) {
- selectMember(memberToSelect);
- }
- }
-
- /*
- * Changes the input to a new type
- * @param inputElement
- */
- private void updateInput(IJavaScriptElement inputElement) {
- IJavaScriptElement prevInput= fInputElement;
-
- synchronized (this) {
- if (fRestoreStateJob != null) {
- fRestoreStateJob.cancel();
- try {
- fRestoreStateJob.join();
- } catch (InterruptedException e) {
- // ignore
- } finally {
- fRestoreStateJob= null;
- }
- }
- }
-
- // Make sure the UI got repainted before we execute a long running
- // operation. This can be removed if we refresh the hierarchy in a
- // separate thread.
- // Work-around for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881
- processOutstandingEvents();
- if (inputElement == null) {
- clearInput();
- } else {
- fInputElement= inputElement;
- fNoHierarchyShownLabel.setText(Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_createinput, inputElement.getElementName()));
- try {
- fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaScriptPlugin.getActiveWorkbenchWindow());
- // fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow());
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.TypeHierarchyViewPart_exception_title, TypeHierarchyMessages.TypeHierarchyViewPart_exception_message);
- clearInput();
- return;
- } catch (InterruptedException e) {
- fNoHierarchyShownLabel.setText(TypeHierarchyMessages.TypeHierarchyViewPart_empty);
- return;
- }
-
- if (inputElement.getElementType() != IJavaScriptElement.TYPE) {
- setHierarchyMode(HIERARCHY_MODE_CLASSIC);
- }
- // turn off member filtering
- fSelectInEditor= false;
- setMemberFilter(null);
- internalSelectType(null, false); // clear selection
- fIsEnableMemberFilter= false;
- if (!inputElement.equals(prevInput)) {
- updateHierarchyViewer(true);
- }
- IType root= getSelectableType(inputElement);
- internalSelectType(root, true);
- updateMethodViewer(root);
- updateToolbarButtons();
- updateTitle();
- showMembersInHierarchy(false);
- fPagebook.showPage(fTypeMethodsSplitter);
- fSelectInEditor= true;
- }
- }
-
- private void processOutstandingEvents() {
- Display display= getDisplay();
- if (display != null && !display.isDisposed())
- display.update();
- }
-
- private void clearInput() {
- fInputElement= null;
- fHierarchyLifeCycle.freeHierarchy();
-
- updateHierarchyViewer(false);
- updateToolbarButtons();
- }
-
- /*
- * @see IWorbenchPart#setFocus
- */
- public void setFocus() {
- fPagebook.setFocus();
- }
-
- /*
- * @see IWorkbenchPart#dispose
- */
- public void dispose() {
- fHierarchyLifeCycle.freeHierarchy();
- fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
- fPaneLabelProvider.dispose();
-
- if (fMethodsViewer != null) {
- fMethodsViewer.dispose();
- }
-
- if (fPropertyChangeListener != null) {
- JavaScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
- fPropertyChangeListener= null;
- }
-
- getSite().getPage().removePartListener(fPartListener);
-
- if (fActionGroups != null)
- fActionGroups.dispose();
-
- if (fWorkingSetActionGroup != null) {
- fWorkingSetActionGroup.dispose();
- }
-
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class key) {
- if (key == IShowInSource.class) {
- return getShowInSource();
- }
- if (key == IShowInTargetList.class) {
- return new IShowInTargetList() {
- public String[] getShowInTargetIds() {
- return new String[] { JavaScriptUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
- }
-
- };
- }
- if (key == IContextProvider.class) {
- return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
- }
- return super.getAdapter(key);
- }
-
- private Control createTypeViewerControl(Composite parent) {
- fViewerbook= new PageBook(parent, SWT.NULL);
-
- KeyListener keyListener= createKeyListener();
-
- // Create the viewers
- TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
- initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
-
- TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
- initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
-
- TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
- initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
-
- fAllViewers= new TypeHierarchyViewer[3];
- fAllViewers[HIERARCHY_MODE_SUPERTYPES]= superTypesViewer;
- fAllViewers[HIERARCHY_MODE_SUBTYPES]= subTypesViewer;
- fAllViewers[HIERARCHY_MODE_CLASSIC]= vajViewer;
-
- int currViewerIndex;
- try {
- currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
- if (currViewerIndex < 0 || currViewerIndex > 2) {
- currViewerIndex= HIERARCHY_MODE_CLASSIC;
- }
- } catch (NumberFormatException e) {
- currViewerIndex= HIERARCHY_MODE_CLASSIC;
- }
-
- fEmptyTypesViewer= new Label(fViewerbook, SWT.TOP | SWT.LEFT | SWT.WRAP);
-
- for (int i= 0; i < fAllViewers.length; i++) {
- fAllViewers[i].setInput(fAllViewers[i]);
- }
-
- // force the update
- fCurrentViewerIndex= -1;
- setHierarchyMode(currViewerIndex);
-
- return fViewerbook;
- }
-
- private KeyListener createKeyListener() {
- return new KeyAdapter() {
- public void keyReleased(KeyEvent event) {
- if (event.stateMask == 0) {
- if (event.keyCode == SWT.F5) {
- ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
- if (hierarchy != null) {
- fHierarchyLifeCycle.typeHierarchyChanged(hierarchy);
- doTypeHierarchyChangedOnViewers(null);
- }
- updateHierarchyViewer(false);
- return;
- }
- }
- }
- };
- }
-
-
- private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
- typesViewer.getControl().setVisible(false);
- typesViewer.getControl().addKeyListener(keyListener);
- typesViewer.initContextMenu(new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillTypesViewerContextMenu(typesViewer, menu);
- }
- }, cotextHelpId, getSite());
- typesViewer.addPostSelectionChangedListener(fSelectionChangedListener);
- typesViewer.setQualifiedTypeName(isQualifiedTypeNamesEnabled());
- typesViewer.setWorkingSetFilter(fWorkingSetActionGroup.getWorkingSetFilter());
- }
-
- private Control createMethodViewerControl(Composite parent) {
- fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
- fMethodsViewer.initContextMenu(new IMenuListener() {
- public void menuAboutToShow(IMenuManager menu) {
- fillMethodsViewerContextMenu(menu);
- }
- }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
- fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener);
-
- Control control= fMethodsViewer.getTable();
- control.addKeyListener(createKeyListener());
- control.addFocusListener(new FocusListener() {
- public void focusGained(FocusEvent e) {
- fSelectAllAction.setEnabled(true);
- }
-
- public void focusLost(FocusEvent e) {
- fSelectAllAction.setEnabled(false);
- }
- });
-
- return control;
- }
-
- private void initDragAndDrop() {
- for (int i= 0; i < fAllViewers.length; i++) {
- addDragAdapters(fAllViewers[i]);
- addDropAdapters(fAllViewers[i]);
- }
- addDragAdapters(fMethodsViewer);
- fMethodsViewer.addDropSupport(DND.DROP_NONE, new Transfer[0], new DropTargetAdapter());
-
- //DND on empty hierarchy
- DropTarget dropTarget = new DropTarget(fPagebook, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT);
- dropTarget.setTransfer(new Transfer[] { LocalSelectionTransfer.getInstance() });
- dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
- }
-
- private void addDropAdapters(AbstractTreeViewer viewer) {
- Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
- int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT;
-
- TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
- new TypeHierarchyTransferDropAdapter(this, viewer)
- };
- viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
- }
-
- private void addDragAdapters(StructuredViewer viewer) {
- int ops= DND.DROP_COPY | DND.DROP_LINK;
- Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance()};
-
- TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
- new SelectionTransferDragAdapter(viewer),
- new ResourceTransferDragAdapter(viewer)
- };
- viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
- }
-
- /**
- * Returns the inner component in a workbench part.
- * @see IWorkbenchPart#createPartControl(Composite)
- */
- public void createPartControl(Composite container) {
- fParent= container;
- addResizeListener(container);
-
- fPagebook= new PageBook(container, SWT.NONE);
- fWorkingSetActionGroup= new WorkingSetFilterActionGroup(getSite(), fPropertyChangeListener);
-
- // page 1 of page book (no hierarchy label)
-
- fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
- fNoHierarchyShownLabel.setText(TypeHierarchyMessages.TypeHierarchyViewPart_empty);
-
- // page 2 of page book (viewers)
-
- fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
- fTypeMethodsSplitter.setVisible(false);
-
- fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
-
- Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
- fTypeViewerViewForm.setContent(typeViewerControl);
-
- fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
- fTypeMethodsSplitter.setWeights(new int[] {35, 65});
-
- Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
- fMethodViewerViewForm.setContent(methodViewerPart);
-
- fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
- fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
-
- ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
- fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
-
- initDragAndDrop();
-
- MenuManager menu= new MenuManager();
- menu.add(fFocusOnTypeAction);
- fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
-
- fPagebook.showPage(fNoHierarchyShownLabel);
-
- int layout;
- try {
- layout= fDialogSettings.getInt(DIALOGSTORE_VIEWLAYOUT);
- if (layout < 0 || layout > 3) {
- layout= VIEW_LAYOUT_AUTOMATIC;
- }
- } catch (NumberFormatException e) {
- layout= VIEW_LAYOUT_AUTOMATIC;
- }
- // force the update
- fCurrentLayout= -1;
- // will fill the main tool bar
- setViewLayout(layout);
-
- showQualifiedTypeNames(fDialogSettings.getBoolean(DIALOGSTORE_QUALIFIED_NAMES));
- setLinkingEnabled(fDialogSettings.getBoolean(DIALOGSTORE_LINKEDITORS));
-
- // set the filter menu items
- IActionBars actionBars= getViewSite().getActionBars();
- IMenuManager viewMenu= actionBars.getMenuManager();
- for (int i= 0; i < fViewActions.length; i++) {
- ToggleViewAction action= fViewActions[i];
- viewMenu.add(action);
- action.setEnabled(false);
- }
- viewMenu.add(new Separator());
-
- fWorkingSetActionGroup.fillViewMenu(viewMenu);
-
- viewMenu.add(new Separator());
-
- IMenuManager layoutSubMenu= new MenuManager(TypeHierarchyMessages.TypeHierarchyViewPart_layout_submenu);
- viewMenu.add(layoutSubMenu);
- for (int i= 0; i < fToggleOrientationActions.length; i++) {
- layoutSubMenu.add(fToggleOrientationActions[i]);
- }
- viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
- viewMenu.add(fShowQualifiedTypeNamesAction);
- viewMenu.add(fToggleLinkingAction);
-
-
- // fill the method viewer tool bar
- ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
- lowertbmanager.add(fEnableMemberFilterAction);
- lowertbmanager.add(new Separator());
- fMethodsViewer.contributeToToolBar(lowertbmanager);
- lowertbmanager.update(true);
-
- // selection provider
- int nHierarchyViewers= fAllViewers.length;
- StructuredViewer[] trackedViewers= new StructuredViewer[nHierarchyViewers + 1];
- for (int i= 0; i < nHierarchyViewers; i++) {
- trackedViewers[i]= fAllViewers[i];
- }
- trackedViewers[nHierarchyViewers]= fMethodsViewer;
- fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers, getCurrentViewer());
- IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
- fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
-
- getSite().setSelectionProvider(fSelectionProviderMediator);
- getSite().getPage().addPartListener(fPartListener);
-
- // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657
- IJavaScriptElement input= null; //determineInputElement();
- if (fMemento != null) {
- restoreState(fMemento, input);
- } else if (input != null) {
- setInputElement(input);
- } else {
- setViewerVisibility(false);
- }
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
-
-
- fActionGroups= new CompositeActionGroup(new ActionGroup[] {
- new NewWizardsActionGroup(this.getSite()),
- new OpenEditorActionGroup(this),
- new OpenViewActionGroup(this),
- new CCPActionGroup(this),
- new GenerateActionGroup(this),
- new RefactorActionGroup(this),
- new JavaSearchActionGroup(this)
- });
-
- fActionGroups.fillActionBars(actionBars);
- fSelectAllAction= new SelectAllAction(fMethodsViewer);
-
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
- }
-
- private void addResizeListener(Composite parent) {
- parent.addControlListener(new ControlListener() {
- public void controlMoved(ControlEvent e) {
- }
- public void controlResized(ControlEvent e) {
- if (getViewLayout() == VIEW_LAYOUT_AUTOMATIC && !fInComputeLayout) {
- setViewLayout(VIEW_LAYOUT_AUTOMATIC);
- }
- }
- });
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#setViewLayout(int)
- */
- public void setViewLayout(int layout) {
- if (fCurrentLayout != layout || layout == VIEW_LAYOUT_AUTOMATIC) {
- fInComputeLayout= true;
- try {
- boolean methodViewerNeedsUpdate= false;
-
- if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
- && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
-
- boolean horizontal= false;
- if (layout == VIEW_LAYOUT_SINGLE) {
- fMethodViewerViewForm.setVisible(false);
- showMembersInHierarchy(false);
- updateMethodViewer(null);
- } else {
- if (fCurrentLayout == VIEW_LAYOUT_SINGLE) {
- fMethodViewerViewForm.setVisible(true);
- methodViewerNeedsUpdate= true;
- }
- if (layout == VIEW_LAYOUT_AUTOMATIC) {
- if (fParent != null && !fParent.isDisposed()) {
- Point size= fParent.getSize();
- if (size.x != 0 && size.y != 0) {
- // bug 185397 - Hierarchy View flips orientation multiple times on resize
- Control viewFormToolbar= fTypeViewerViewForm.getTopLeft();
- if (viewFormToolbar != null && !viewFormToolbar.isDisposed() && viewFormToolbar.isVisible()) {
- size.y -= viewFormToolbar.getSize().y;
- }
- horizontal= size.x > size.y;
- }
- }
- if (fCurrentLayout == VIEW_LAYOUT_AUTOMATIC) {
- boolean wasHorizontal= fTypeMethodsSplitter.getOrientation() == SWT.HORIZONTAL;
- if (wasHorizontal == horizontal) {
- return; // no real change
- }
- }
-
- } else if (layout == VIEW_LAYOUT_HORIZONTAL) {
- horizontal= true;
- }
- fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
- }
- updateMainToolbar(horizontal);
- fTypeMethodsSplitter.layout();
- }
- if (methodViewerNeedsUpdate) {
- updateMethodViewer(fSelectedType);
- }
- fDialogSettings.put(DIALOGSTORE_VIEWLAYOUT, layout);
- fCurrentLayout= layout;
-
- updateCheckedState();
- } finally {
- fInComputeLayout= false;
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#getViewLayout()
- */
- public int getViewLayout() {
- return fCurrentLayout;
- }
-
- private void updateCheckedState() {
- for (int i= 0; i < fToggleOrientationActions.length; i++) {
- fToggleOrientationActions[i].setChecked(getViewLayout() == fToggleOrientationActions[i].getOrientation());
- }
- }
-
- private void updateMainToolbar(boolean horizontal) {
- IActionBars actionBars= getViewSite().getActionBars();
- IToolBarManager tbmanager= actionBars.getToolBarManager();
-
- if (horizontal) {
- clearMainToolBar(tbmanager);
- ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
- fillMainToolBar(new ToolBarManager(typeViewerToolBar));
- fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
- } else {
- fTypeViewerViewForm.setTopLeft(null);
- fillMainToolBar(tbmanager);
- }
- }
-
- private void fillMainToolBar(IToolBarManager tbmanager) {
- tbmanager.removeAll();
- for (int i= 0; i < fViewActions.length; i++) {
- tbmanager.add(fViewActions[i]);
- }
- tbmanager.add(fHistoryDropDownAction);
- tbmanager.update(false);
- }
-
- private void clearMainToolBar(IToolBarManager tbmanager) {
- tbmanager.removeAll();
- tbmanager.update(false);
- }
-
-
- /*
- * Creates the context menu for the hierarchy viewers
- */
- private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
-
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
- // viewer entries
- viewer.contributeToContextMenu(menu);
-
- if (fFocusOnSelectionAction.canActionBeAdded())
- menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
- menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
-
- fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
- fActionGroups.fillContextMenu(menu);
- fActionGroups.setContext(null);
- }
-
- /*
- * Creates the context menu for the method viewer
- */
- private void fillMethodsViewerContextMenu(IMenuManager menu) {
- JavaScriptPlugin.createStandardGroups(menu);
- // viewer entries
- fMethodsViewer.contributeToContextMenu(menu);
- fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
- fActionGroups.fillContextMenu(menu);
- fActionGroups.setContext(null);
- }
-
- /*
- * Toggles between the empty viewer page and the hierarchy
- */
- private void setViewerVisibility(boolean showHierarchy) {
- if (showHierarchy) {
- fViewerbook.showPage(getCurrentViewer().getControl());
- } else {
- fViewerbook.showPage(fEmptyTypesViewer);
- }
- }
-
- /*
- * Sets the member filter. <code>null</code> disables member filtering.
- */
- private void setMemberFilter(IMember[] memberFilter) {
- Assert.isNotNull(fAllViewers);
- for (int i= 0; i < fAllViewers.length; i++) {
- fAllViewers[i].setMemberFilter(memberFilter);
- }
- }
-
- private IType getSelectableType(IJavaScriptElement elem) {
- if (elem.getElementType() != IJavaScriptElement.TYPE) {
- return getCurrentViewer().getTreeRootType();
- } else {
- return (IType) elem;
- }
- }
-
- private void internalSelectType(IMember elem, boolean reveal) {
- TypeHierarchyViewer viewer= getCurrentViewer();
- viewer.removePostSelectionChangedListener(fSelectionChangedListener);
- viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
- viewer.addPostSelectionChangedListener(fSelectionChangedListener);
- }
-
- /*
- * When the input changed or the hierarchy pane becomes visible,
- * <code>updateHierarchyViewer<code> brings up the correct view and refreshes
- * the current tree
- */
- private void updateHierarchyViewer(final boolean doExpand) {
- if (fInputElement == null) {
- fNoHierarchyShownLabel.setText(TypeHierarchyMessages.TypeHierarchyViewPart_empty);
- fPagebook.showPage(fNoHierarchyShownLabel);
- } else {
- if (getCurrentViewer().containsElements() != null) {
- Runnable runnable= new Runnable() {
- public void run() {
- getCurrentViewer().updateContent(doExpand); // refresh
- }
- };
- BusyIndicator.showWhile(getDisplay(), runnable);
- if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
- setViewerVisibility(true);
- }
- } else {
- fEmptyTypesViewer.setText(Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_nodecl, fInputElement.getElementName()));
- setViewerVisibility(false);
- }
- }
- }
-
- private void updateMethodViewer(final IType input) {
- if (!fIsEnableMemberFilter && fCurrentLayout != VIEW_LAYOUT_SINGLE) {
- if (input == fMethodsViewer.getInput()) {
- if (input != null) {
- Runnable runnable= new Runnable() {
- public void run() {
- fMethodsViewer.refresh(); // refresh
- }
- };
- BusyIndicator.showWhile(getDisplay(), runnable);
- }
- } else {
- if (input != null) {
- fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
- fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
- } else {
- fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
- fMethodViewerPaneLabel.setImage(null);
- }
- Runnable runnable= new Runnable() {
- public void run() {
- fMethodsViewer.setInput(input); // refresh
- }
- };
- BusyIndicator.showWhile(getDisplay(), runnable);
- }
- }
- }
-
- protected void doSelectionChanged(SelectionChangedEvent e) {
- if (e.getSelectionProvider() == fMethodsViewer) {
- methodSelectionChanged(e.getSelection());
- } else {
- typeSelectionChanged(e.getSelection());
- }
- }
-
-
-
- private void methodSelectionChanged(ISelection sel) {
- if (sel instanceof IStructuredSelection) {
- List selected= ((IStructuredSelection)sel).toList();
- int nSelected= selected.size();
- if (fIsEnableMemberFilter) {
- IMember[] memberFilter= null;
- if (nSelected > 0) {
- memberFilter= new IMember[nSelected];
- selected.toArray(memberFilter);
- }
- setMemberFilter(memberFilter);
- updateHierarchyViewer(true);
- updateTitle();
- internalSelectType(fSelectedType, true);
- }
- if (nSelected == 1 && fSelectInEditor) {
- revealElementInEditor(selected.get(0), fMethodsViewer);
- }
- }
- }
-
- private void typeSelectionChanged(ISelection sel) {
- if (sel instanceof IStructuredSelection) {
- List selected= ((IStructuredSelection)sel).toList();
- int nSelected= selected.size();
- if (nSelected != 0) {
- List types= new ArrayList(nSelected);
- for (int i= nSelected-1; i >= 0; i--) {
- Object elem= selected.get(i);
- if (elem instanceof IType && !types.contains(elem)) {
- types.add(elem);
- }
- }
- if (types.size() == 1) {
- fSelectedType= (IType) types.get(0);
- updateMethodViewer(fSelectedType);
- } else if (types.size() == 0) {
- // method selected, no change
- }
- if (nSelected == 1 && fSelectInEditor) {
- revealElementInEditor(selected.get(0), getCurrentViewer());
- }
- } else {
- fSelectedType= null;
- updateMethodViewer(null);
- }
- }
- }
-
- private void revealElementInEditor(Object elem, StructuredViewer originViewer) {
- // only allow revealing when the type hierarchy is the active page
- // no revealing after selection events due to model changes
-
- if (getSite().getPage().getActivePart() != this) {
- return;
- }
-
- if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
- return;
- }
-
- IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
- if (editorPart != null && (elem instanceof IJavaScriptElement)) {
- getSite().getPage().removePartListener(fPartListener);
- getSite().getPage().bringToTop(editorPart);
- EditorUtility.revealInEditor(editorPart, (IJavaScriptElement) elem);
- getSite().getPage().addPartListener(fPartListener);
- }
- }
-
- private Display getDisplay() {
- if (fPagebook != null && !fPagebook.isDisposed()) {
- return fPagebook.getDisplay();
- }
- return null;
- }
-
- private boolean isChildVisible(Composite pb, Control child) {
- Control[] children= pb.getChildren();
- for (int i= 0; i < children.length; i++) {
- if (children[i] == child && children[i].isVisible())
- return true;
- }
- return false;
- }
-
- private void updateTitle() {
- String viewerTitle= getCurrentViewer().getTitle();
-
- String tooltip;
- String title;
- if (fInputElement != null) {
- IWorkingSet workingSet= fWorkingSetActionGroup.getWorkingSet();
- if (workingSet == null) {
- String[] args= new String[] { viewerTitle, JavaScriptElementLabels.getElementLabel(fInputElement, JavaScriptElementLabels.ALL_DEFAULT) };
- title= Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_title, args);
- tooltip= Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_tooltip, args);
- } else {
- String[] args= new String[] { viewerTitle, JavaScriptElementLabels.getElementLabel(fInputElement, JavaScriptElementLabels.ALL_DEFAULT), workingSet.getLabel() };
- title= Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_ws_title, args);
- tooltip= Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_ws_tooltip, args);
- }
- } else {
- title= ""; //$NON-NLS-1$
- tooltip= viewerTitle;
- }
- setContentDescription(title);
- setTitleToolTip(tooltip);
- }
-
- private void updateToolbarButtons() {
- boolean isType= fInputElement instanceof IType;
- for (int i= 0; i < fViewActions.length; i++) {
- ToggleViewAction action= fViewActions[i];
- if (action.getViewerIndex() == HIERARCHY_MODE_CLASSIC) {
- action.setEnabled(fInputElement != null);
- } else {
- action.setEnabled(isType);
- }
- }
- }
-
-
- public void setHierarchyMode(int viewerIndex) {
- Assert.isNotNull(fAllViewers);
- if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
- fCurrentViewerIndex= viewerIndex;
-
- updateHierarchyViewer(true);
- if (fInputElement != null) {
- ISelection currSelection= getCurrentViewer().getSelection();
- if (currSelection == null || currSelection.isEmpty()) {
- internalSelectType(getSelectableType(fInputElement), false);
- currSelection= getCurrentViewer().getSelection();
- }
- if (!fIsEnableMemberFilter) {
- typeSelectionChanged(currSelection);
- }
- }
- updateTitle();
-
- fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
- getCurrentViewer().getTree().setFocus();
- }
- for (int i= 0; i < fViewActions.length; i++) {
- ToggleViewAction action= fViewActions[i];
- action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
- }
- }
-
- public int getHierarchyMode() {
- return fCurrentViewerIndex;
- }
-
- private TypeHierarchyViewer getCurrentViewer() {
- return fAllViewers[fCurrentViewerIndex];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#showMembersInHierarchy(boolean)
- */
- public void showMembersInHierarchy(boolean on) {
- if (on != fIsEnableMemberFilter) {
- fIsEnableMemberFilter= on;
- if (!on) {
- IType methodViewerInput= (IType) fMethodsViewer.getInput();
- setMemberFilter(null);
- updateHierarchyViewer(true);
- updateTitle();
-
- if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
- // avoid that the method view changes content by selecting the previous input
- internalSelectType(methodViewerInput, true);
- } else if (fSelectedType != null) {
- // choose a input that exists
- internalSelectType(fSelectedType, true);
- updateMethodViewer(fSelectedType);
- }
- } else {
- methodSelectionChanged(fMethodsViewer.getSelection());
- }
- }
- fEnableMemberFilterAction.setChecked(on);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#isShowMembersInHierarchy()
- */
- public boolean isShowMembersInHierarchy() {
- return fIsEnableMemberFilter;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#showQualifiedTypeNames(boolean)
- */
- public void showQualifiedTypeNames(boolean on) {
- if (on != fShowQualifiedTypeNames) {
- fShowQualifiedTypeNames= on;
- if (fAllViewers != null) {
- for (int i= 0; i < fAllViewers.length; i++) {
- fAllViewers[i].setQualifiedTypeName(on);
- }
- }
- }
- fShowQualifiedTypeNamesAction.setChecked(on);
- fDialogSettings.put(DIALOGSTORE_QUALIFIED_NAMES, on);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#isQualifiedTypeNamesEnabled()
- */
- public boolean isQualifiedTypeNamesEnabled() {
- return fShowQualifiedTypeNames;
- }
-
- /**
- * Called from ITypeHierarchyLifeCycleListener.
- * Can be called from any thread
- * @param typeHierarchy Hierarchy that has changed
- * @param changedTypes Types in the hierarchy that have change or <code>null</code> if the full hierarchy has changed
- */
- protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
- if (!fIsVisible) {
- fNeedRefresh= true;
- return;
- }
- if (fIsRefreshRunnablePosted) {
- return;
- }
-
- Display display= getDisplay();
- if (display != null) {
- fIsRefreshRunnablePosted= true;
- display.asyncExec(new Runnable() {
- public void run() {
- try {
- if (fPagebook != null && !fPagebook.isDisposed()) {
- doTypeHierarchyChangedOnViewers(changedTypes);
- }
- } finally {
- fIsRefreshRunnablePosted= false;
- }
- }
- });
- }
- }
-
- protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
- if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
- clearInput();
- } else {
- if (changedTypes == null) {
- // hierarchy change
- try {
- fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.TypeHierarchyViewPart_exception_title, TypeHierarchyMessages.TypeHierarchyViewPart_exception_message);
- clearInput();
- return;
- } catch (InterruptedException e) {
- return;
- }
- fMethodsViewer.refresh();
- updateHierarchyViewer(false);
- } else {
- // elements in hierarchy modified
- Object methodViewerInput= fMethodsViewer.getInput();
- fMethodsViewer.refresh();
- fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput));
- fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput));
- if (getCurrentViewer().isMethodFiltering()) {
- if (changedTypes.length == 1) {
- getCurrentViewer().refresh(changedTypes[0]);
- } else {
- updateHierarchyViewer(false);
- }
- } else {
- getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
- }
- }
- }
- }
-
- /*
- * @see IViewPart#init
- */
- public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
- fMemento= memento;
- }
-
- /*
- * @see ViewPart#saveState(IMemento)
- */
- public void saveState(IMemento memento) {
- if (fPagebook == null) {
- // part has not been created
- if (fMemento != null) { //Keep the old state;
- memento.putMemento(fMemento);
- }
- return;
- }
- if (fInputElement != null) {
- String handleIndentifier= fInputElement.getHandleIdentifier();
- memento.putString(TAG_INPUT, handleIndentifier);
- }
- memento.putInteger(TAG_VIEW, getHierarchyMode());
- memento.putInteger(TAG_LAYOUT, getViewLayout());
- memento.putInteger(TAG_QUALIFIED_NAMES, isQualifiedTypeNamesEnabled() ? 1 : 0);
- memento.putInteger(TAG_EDITOR_LINKING, isLinkingEnabled() ? 1 : 0);
-
- int weigths[]= fTypeMethodsSplitter.getWeights();
- int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
- memento.putInteger(TAG_RATIO, ratio);
-
- ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
- int position= bar != null ? bar.getSelection() : 0;
- memento.putInteger(TAG_VERTICAL_SCROLL, position);
-
- IJavaScriptElement selection= (IJavaScriptElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
- if (selection != null) {
- memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
- }
-
- fWorkingSetActionGroup.saveState(memento);
-
- fMethodsViewer.saveState(memento);
- }
-
- /*
- * Restores the type hierarchy settings from a memento.
- */
- private void restoreState(final IMemento memento, IJavaScriptElement defaultInput) {
- IJavaScriptElement input= defaultInput;
- String elementId= memento.getString(TAG_INPUT);
- if (elementId != null) {
- input= JavaScriptCore.create(elementId);
- if (input != null && !input.exists()) {
- input= null;
- }
- }
- if (input == null) {
- doRestoreState(memento, input);
- } else {
- final IJavaScriptElement hierarchyInput= input;
-
- synchronized (this) {
- String label= Messages.format(TypeHierarchyMessages.TypeHierarchyViewPart_restoreinput, hierarchyInput.getElementName());
- fNoHierarchyShownLabel.setText(label);
-
- fRestoreStateJob= new Job(label) {
- protected IStatus run(IProgressMonitor monitor) {
- try {
- doRestoreInBackground(memento, hierarchyInput, monitor);
- } catch (JavaScriptModelException e) {
- return e.getStatus();
- } catch (OperationCanceledException e) {
- return Status.CANCEL_STATUS;
- }
- return Status.OK_STATUS;
- }
- };
- fRestoreStateJob.schedule();
- }
- }
- }
-
- private void doRestoreInBackground(final IMemento memento, final IJavaScriptElement hierarchyInput, IProgressMonitor monitor) throws JavaScriptModelException {
- fHierarchyLifeCycle.doHierarchyRefresh(hierarchyInput, monitor);
- final boolean doRestore= !monitor.isCanceled();
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- // running async: check first if view still exists
- if (fPagebook != null && !fPagebook.isDisposed()) {
- if (doRestore)
- doRestoreState(memento, hierarchyInput);
- else
- fNoHierarchyShownLabel.setText(TypeHierarchyMessages.TypeHierarchyViewPart_empty);
- }
- }
- });
- }
-
-
- final void doRestoreState(IMemento memento, IJavaScriptElement input) {
- synchronized (this) {
- if (fRestoreStateJob == null) {
- return;
- }
- fRestoreStateJob= null;
- }
-
- fWorkingSetActionGroup.restoreState(memento);
- setInputElement(input);
-
- Integer viewerIndex= memento.getInteger(TAG_VIEW);
- if (viewerIndex != null) {
- setHierarchyMode(viewerIndex.intValue());
- }
- Integer layout= memento.getInteger(TAG_LAYOUT);
- if (layout != null) {
- setViewLayout(layout.intValue());
- }
-
- Integer val= memento.getInteger(TAG_EDITOR_LINKING);
- if (val != null) {
- setLinkingEnabled(val.intValue() != 0);
- }
-
- Integer showQualified= memento.getInteger(TAG_QUALIFIED_NAMES);
- if (showQualified != null) {
- showQualifiedTypeNames(showQualified.intValue() != 0);
- }
-
- updateCheckedState();
-
- Integer ratio= memento.getInteger(TAG_RATIO);
- if (ratio != null) {
- fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
- }
- ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
- if (bar != null) {
- Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
- if (vScroll != null) {
- bar.setSelection(vScroll.intValue());
- }
- }
- fMethodsViewer.restoreState(memento);
- }
-
- /**
- * view part becomes visible
- * @param isVisible
- */
- protected void visibilityChanged(boolean isVisible) {
- fIsVisible= isVisible;
- if (isVisible && fNeedRefresh) {
- doTypeHierarchyChangedOnViewers(null);
- }
- fNeedRefresh= false;
- }
-
-
- /**
- * Link selection to active editor.
- * @param editor The activated editor
- */
- protected void editorActivated(IEditorPart editor) {
- if (!isLinkingEnabled()) {
- return;
- }
- if (fInputElement == null) {
- // no type hierarchy shown
- return;
- }
-
- IJavaScriptElement elem= (IJavaScriptElement)editor.getEditorInput().getAdapter(IJavaScriptElement.class);
- if (elem instanceof ITypeRoot) {
- IType type= ((ITypeRoot) elem).findPrimaryType();
- if (type != null) {
- internalSelectType(type, true);
- if (getCurrentViewer().getSelection().isEmpty()) {
- updateMethodViewer(null);
- } else {
- updateMethodViewer(type);
- }
- }
- }
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
- */
- public Object getViewPartInput() {
- return fInputElement;
- }
-
-
- /**
- * @return Returns the <code>IShowInSource</code> for this view.
- */
- protected IShowInSource getShowInSource() {
- return new IShowInSource() {
- public ShowInContext getShowInContext() {
- return new ShowInContext(
- null,
- getSite().getSelectionProvider().getSelection());
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#isLinkingEnabled()
- */
- public boolean isLinkingEnabled() {
- return fLinkingEnabled;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ITypeHierarchyViewPart#setLinkingEnabled(boolean)
- */
- public void setLinkingEnabled(boolean enabled) {
- fLinkingEnabled= enabled;
- fToggleLinkingAction.setChecked(enabled);
- fDialogSettings.put(DIALOGSTORE_LINKEDITORS, enabled);
-
- if (enabled) {
- IWorkbenchPartSite site= getSite();
- if (site != null) {
- IEditorPart editor = site.getPage().getActiveEditor();
- if (editor != null) {
- editorActivated(editor);
- }
- }
- }
- }
-
- public void clearNeededRefresh() {
- fNeedRefresh= false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewer.java
deleted file mode 100644
index 7b2abcea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyViewer.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.typehierarchy;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.IOpenListener;
-import org.eclipse.jface.viewers.OpenEvent;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ProblemTreeViewer;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.actions.OpenAction;
-
-public abstract class TypeHierarchyViewer extends ProblemTreeViewer {
-
- private OpenAction fOpen;
- private HierarchyLabelProvider fLabelProvider;
-
- public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
- super(new Tree(parent, SWT.SINGLE));
-
- fLabelProvider= new HierarchyLabelProvider(lifeCycle);
-
- setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true));
- setUseHashlookup(true);
-
- setContentProvider(contentProvider);
- setComparator(new HierarchyViewerSorter(lifeCycle));
-
- fOpen= new OpenAction(part.getSite());
- addOpenListener(new IOpenListener() {
- public void open(OpenEvent event) {
- fOpen.run();
- }
- });
-
- ColoredViewersManager.install(this);
-
- JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
- }
-
- public void setQualifiedTypeName(boolean on) {
- if (on) {
- fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaScriptElementLabels.T_POST_QUALIFIED);
- } else {
- fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~JavaScriptElementLabels.T_POST_QUALIFIED);
- }
- refresh();
- }
-
- /**
- * Attaches a contextmenu listener to the tree
- * @param menuListener the menu listener
- * @param popupId the popup id
- * @param viewSite the view site
- */
- public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
- MenuManager menuMgr= new MenuManager();
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(menuListener);
- Menu menu= menuMgr.createContextMenu(getTree());
- getTree().setMenu(menu);
- viewSite.registerContextMenu(popupId, menuMgr, this);
- }
-
- /**
- * Fills up the context menu with items for the hierarchy viewer
- * Should be called by the creator of the context menu
- * @param menu the menu manager
- */
- public void contributeToContextMenu(IMenuManager menu) {
- }
-
- /**
- * Set the member filter
- * @param memberFilter the member filters to set
- */
- public void setMemberFilter(IMember[] memberFilter) {
- TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
- if (contentProvider != null) {
- contentProvider.setMemberFilter(memberFilter);
- }
- }
-
- /**
- * Returns if method filtering is enabled.
- * @return <code>true</code>if method filtering is enabled.
- */
- public boolean isMethodFiltering() {
- TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
- if (contentProvider != null) {
- return contentProvider.getMemberFilter() != null;
- }
- return false;
- }
-
- public void setWorkingSetFilter(ViewerFilter filter) {
- fLabelProvider.setFilter(filter);
- TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
- if (contentProvider != null) {
- contentProvider.setWorkingSetFilter(filter);
- }
- }
-
- /**
- * Returns true if the hierarchy contains elements. Returns one of them
- * With member filtering it is possible that no elements are visible
- * @return one of the elements contained
- */
- public Object containsElements() {
- TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
- if (contentProvider != null) {
- Object[] elements= contentProvider.getElements(null);
- if (elements.length > 0) {
- return elements[0];
- }
- }
- return null;
- }
-
- /**
- * Returns true if the hierarchy contains elements. Returns one of them
- * With member filtering it is possible that no elements are visible
- * @return the tree root
- */
- public IType getTreeRootType() {
- TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
- if (contentProvider != null) {
- Object[] elements= contentProvider.getElements(null);
- if (elements.length > 0 && elements[0] instanceof IType) {
- return (IType) elements[0];
- }
- }
- return null;
- }
-
- /**
- * Returns true if the hierarchy contains element the element.
- * @param element the element
- * @return <code>true</code> if element is shown
- */
- public boolean isElementShown(Object element) {
- return findItem(element) != null;
- }
-
- /**
- * Updates the content of this viewer: refresh and expanding the tree in the way wanted.
- * @param doExpand if set, update should expand
- */
- public abstract void updateContent(boolean doExpand);
-
- /**
- * Returns the title for the current view
- * @return the title
- */
- public abstract String getTitle();
-
- /*
- * @see StructuredViewer#setContentProvider
- * Content provider must be of type TypeHierarchyContentProvider
- */
- public void setContentProvider(IContentProvider cp) {
- Assert.isTrue(cp instanceof TypeHierarchyContentProvider);
- super.setContentProvider(cp);
- }
-
- protected TypeHierarchyContentProvider getHierarchyContentProvider() {
- return (TypeHierarchyContentProvider)getContentProvider();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/BusyIndicatorRunnableContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/BusyIndicatorRunnableContext.java
deleted file mode 100644
index 9cb012f0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/BusyIndicatorRunnableContext.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.operation.ModalContext;
-import org.eclipse.swt.custom.BusyIndicator;
-
-/**
- * A runnable context that shows the busy cursor instead of a progress
- * monitor. Note, that the UI thread is blocked even if the runnable
- * is executed in a separate thread by passing <code>fork= true</code>
- * to the context's run method. Furthermore this context doesn't provide
- * any UI to cancel the operation.
- */
-public class BusyIndicatorRunnableContext implements IRunnableContext {
-
- private static class BusyRunnable implements Runnable {
-
- private static class ThreadContext extends Thread {
- IRunnableWithProgress fRunnable;
- Throwable fThrowable;
-
- public ThreadContext(IRunnableWithProgress runnable) {
- this(runnable, "BusyCursorRunnableContext-Thread"); //$NON-NLS-1$
- }
- protected ThreadContext(IRunnableWithProgress runnable, String name) {
- super(name);
- fRunnable= runnable;
- }
- public void run() {
- try {
- fRunnable.run(new NullProgressMonitor());
- } catch (InvocationTargetException e) {
- fThrowable= e;
- } catch (InterruptedException e) {
- fThrowable= e;
- } catch (ThreadDeath e) {
- fThrowable= e;
- throw e;
- } catch (RuntimeException e) {
- fThrowable= e;
- } catch (Error e) {
- fThrowable= e;
- }
- }
- void sync() {
- try {
- join();
- } catch (InterruptedException e) {
- // ok to ignore exception
- }
- }
- }
-
- public Throwable fThrowable;
- private boolean fFork;
- private IRunnableWithProgress fRunnable;
- public BusyRunnable(boolean fork, IRunnableWithProgress runnable) {
- fFork= fork;
- fRunnable= runnable;
- }
- public void run() {
- try {
- internalRun(fFork, fRunnable);
- } catch (InvocationTargetException e) {
- fThrowable= e;
- } catch (InterruptedException e) {
- fThrowable= e;
- }
- }
- private void internalRun(boolean fork, final IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException {
- Thread thread= Thread.currentThread();
- // Do not spawn another thread if we are already in a modal context
- // thread or inside a busy context thread.
- if (thread instanceof ThreadContext || ModalContext.isModalContextThread(thread))
- fork= false;
-
- if (fork) {
- final ThreadContext t= new ThreadContext(runnable);
- t.start();
- t.sync();
- // Check if the separate thread was terminated by an exception
- Throwable throwable= t.fThrowable;
- if (throwable != null) {
- if (throwable instanceof InvocationTargetException) {
- throw (InvocationTargetException) throwable;
- } else if (throwable instanceof InterruptedException) {
- throw (InterruptedException) throwable;
- } else if (throwable instanceof OperationCanceledException) {
- throw new InterruptedException();
- } else {
- throw new InvocationTargetException(throwable);
- }
- }
- } else {
- try {
- runnable.run(new NullProgressMonitor());
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- }
- }
- }
- }
-
- /* (non-Javadoc)
- * Method declared on IRunnableContext.
- */
- public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException {
- BusyRunnable busyRunnable= new BusyRunnable(fork, runnable);
- BusyIndicator.showWhile(null, busyRunnable);
- Throwable throwable= busyRunnable.fThrowable;
- if (throwable instanceof InvocationTargetException) {
- throw (InvocationTargetException)throwable;
- } else if (throwable instanceof InterruptedException) {
- throw (InterruptedException)throwable;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java
deleted file mode 100644
index c2127373..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionDelegate;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.core.util.ConvertUtility;
-import org.eclipse.wst.jsdt.internal.core.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.Logger;
-
-/**
- * Not API
- */
-public class ConvertAction implements IObjectActionDelegate, IActionDelegate {
- IWorkbenchPart fPart;
- Object[] fTarget;
- private static final String FACET_NATURE = "org.eclipse.wst.common.project.facet.core.nature"; //$NON-NLS-1$
- private static final String FACET_PROPERTY_PAGE = "org.eclipse.wst.common.project.facet.ui.FacetsPropertyPage"; //$NON-NLS-1$
-
- private void doInstall(IProject project, final boolean openProperties, IProgressMonitor monitor) {
- boolean configured = false;
-
- monitor.beginTask(Messages.converter_ConfiguringForJavaScript, 5);
- ConvertUtility convertor = new ConvertUtility(project);
- try {
- boolean hadBasicNature = ConvertUtility.hasNature(project);
-
- convertor.configure(new SubProgressMonitor(monitor, 1));
- convertor.addBrowserSupport(!hadBasicNature, new SubProgressMonitor(monitor, 1));
-
- if (!hadBasicNature) {
- /*
- * No nature before, so no existing include path. Define the
- * project itself as an source folder.
- */
- JavaProject jp = (JavaProject) JavaScriptCore.create(project);
- IIncludePathEntry[] oldEntries = null;
- try {
- oldEntries = jp.getRawIncludepath();
- List entries = new ArrayList();
- for (int i = 0; i < oldEntries.length; i++) {
- if (oldEntries[i].getContentKind() != IPackageFragmentRoot.K_SOURCE || oldEntries[i].getEntryKind() != IIncludePathEntry.CPE_SOURCE) {
- entries.add(oldEntries[i]);
- }
- }
- oldEntries = (IIncludePathEntry[]) entries.toArray(new IIncludePathEntry[entries.size()]);
- }
- catch (JavaScriptModelException ex1) {
- Logger.log(Logger.ERROR_DEBUG, null, ex1);
- oldEntries = new IIncludePathEntry[0];
- }
- IIncludePathEntry[] sourcePaths = convertor.getDefaultSourcePaths(project);
- IIncludePathEntry[] newEntries = new IIncludePathEntry[oldEntries.length + sourcePaths.length];
- System.arraycopy(sourcePaths, 0, newEntries, 0, sourcePaths.length);
- System.arraycopy(oldEntries, 0, newEntries, sourcePaths.length, oldEntries.length);
-
-
- try {
- jp.setRawIncludepath(newEntries, project.getFullPath(), new SubProgressMonitor(monitor, 1));
- }
- catch (JavaScriptModelException ex1) {
- Logger.log(Logger.ERROR_DEBUG, null, ex1);
- }
- }
- configured = true;
- }
- catch (CoreException ex) {
- Logger.logException(ex);
- }
-
- if (configured && openProperties) {
- showPropertiesOn(project, new SubProgressMonitor(monitor, 1));
- }
- monitor.done();
- }
-
- private void doUninstall(IProject project, IProgressMonitor monitor) {
-// ConvertUtility nature = new ConvertUtility(project);
-// try {
-// nature.deconfigure();
-// } catch (CoreException ex) {
-// Logger.logException(ex);
-// }
- }
-
- void enableForFacets(IProject project) {
- try {
- IProjectDescription description = project.getDescription();
-
- boolean hasNature = project.hasNature(FACET_NATURE);
- if (!hasNature) {
- List natures = new ArrayList(Arrays.asList(description.getNatureIds()));
- natures.add(FACET_NATURE);
- description.setNatureIds((String[]) natures.toArray(new String[natures.size()]));
- }
-
- if (!hasNature)
- project.setDescription(description, new NullProgressMonitor());
- }
- catch (CoreException e) {
- Logger.logException(e);
- }
- }
-
- private void install(final IProject project, final boolean openProperties) {
- IProgressService service = null;
- if (fPart != null) {
- service = (IProgressService) fPart.getSite().getService(IProgressService.class);
- }
- if (service == null) {
- doInstall(project, openProperties, new NullProgressMonitor());
- }
- else {
- IRunnableWithProgress runnable = new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- doInstall(project, openProperties, monitor);
- }
- };
- try {
- service.run(false, false, runnable);
- }
- catch (InvocationTargetException e) {
- Logger.logException(e);
- }
- catch (InterruptedException e) {
- Logger.logException(e);
- }
- }
- }
-
- public void run(IAction action) {
- if (fTarget == null)
- return;
-
- for (int i = 0; i < fTarget.length; i++) {
- if (fTarget[i] instanceof IResource) {
- final IProject project = ((IResource) fTarget[i]).getProject();
-
- // Temporary until https://bugs.eclipse.org/bugs/show_bug.cgi?id=298483 is resolved
-// enableForFacets(project);
-
- if (!ConvertUtility.hasNature(project)) {
- /* Doesn't have nature, do a full install. */
- install(project, i == fTarget.length - 1);
- }
- else {
- /*
- * Has nature, check for browser library on include path
- * and setup if not found.
- */
- IJavaScriptProject jp = JavaScriptCore.create(project);
- IIncludePathEntry[] rawClasspath = null;
- try {
- rawClasspath = jp.getRawIncludepath();
- }
- catch (JavaScriptModelException ex1) {
- Logger.log(Logger.ERROR_DEBUG, null, ex1);
- }
-
- boolean browserFound = false;
- for (int k = 0; rawClasspath != null && !browserFound && k < rawClasspath.length; k++) {
- if (rawClasspath[k].getPath().equals(ConvertUtility.BROWSER_LIBRARY_PATH)) {
- browserFound = true;
- }
- }
- if (!browserFound) {
- install(project, false);
- }
- }
- }
- }
-
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- fTarget = ((IStructuredSelection) selection).toArray();
- }
- else {
- fTarget = null;
- }
- }
-
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- fPart = targetPart;
- }
-
- private void showPropertiesOn(final IProject project, final IProgressMonitor monitor) {
- IExtension[] extensions = Platform.getExtensionRegistry().getExtensionPoint("org.eclipse.ui.propertyPages").getExtensions(); //$NON-NLS-1$
- final List pageIds = new ArrayList(8);
- pageIds.add(FACET_PROPERTY_PAGE);
- for (int i = 0; i < extensions.length; i++) {
- if (extensions[i].getNamespaceIdentifier().startsWith("org.eclipse.wst.jsdt.")) { //$NON-NLS-1$
- IConfigurationElement[] configurationElements = extensions[i].getConfigurationElements();
- for (int j = 0; j < configurationElements.length; j++) {
- if ("page".equals(configurationElements[j].getName())) { //$NON-NLS-1$
- pageIds.add(configurationElements[j].getAttribute("id")); //$NON-NLS-1$
- }
- }
- }
- }
- Shell shell = (Shell) fPart.getAdapter(Shell.class);
- if (shell == null) {
- IWorkbenchWindow activeWorkbenchWindow = JavaScriptPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
- if (activeWorkbenchWindow != null)
- shell = activeWorkbenchWindow.getShell();
- }
- final Shell finalShell = shell;
- if (finalShell != null) {
- finalShell.getDisplay().asyncExec(new Runnable() {
- public void run() {
- PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(finalShell, project, "org.eclipse.wst.jsdt.ui.propertyPages.BuildPathsPropertyPage", (String[]) pageIds.toArray(new String[pageIds.size()]), null); //$NON-NLS-1$
- if (dialog.open() == Window.CANCEL) {
- doUninstall(project, monitor);
- }
- }
- });
- }
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java
deleted file mode 100644
index 5144d474..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceDescription;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.osgi.framework.Bundle;
-
-
-public class CoreUtility {
-
- public static void createDerivedFolder(IFolder folder, boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
- if (!folder.exists()) {
- IContainer parent= folder.getParent();
- if (parent instanceof IFolder) {
- createDerivedFolder((IFolder)parent, force, local, null);
- }
- folder.create(force ? (IResource.FORCE | IResource.DERIVED) : IResource.DERIVED, local, monitor);
- }
- }
-
- /**
- * Creates a folder and all parent folders if not existing.
- * Project must exist.
- * <code> org.eclipse.ui.dialogs.ContainerGenerator</code> is too heavy
- * (creates a runnable)
- */
- public static void createFolder(IFolder folder, boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
- if (!folder.exists()) {
- IContainer parent= folder.getParent();
- if (parent instanceof IFolder) {
- createFolder((IFolder)parent, force, local, null);
- }
- folder.create(force, local, monitor);
- }
- }
-
- /**
- * Creates an extension. If the extension plugin has not
- * been loaded a busy cursor will be activated during the duration of
- * the load.
- *
- * @param element the config element defining the extension
- * @param classAttribute the name of the attribute carrying the class
- * @return the extension object
- */
- public static Object createExtension(final IConfigurationElement element, final String classAttribute) throws CoreException {
- // If plugin has been loaded create extension.
- // Otherwise, show busy cursor then create extension.
- String pluginId = element.getContributor().getName();
- Bundle bundle = Platform.getBundle(pluginId);
- if (bundle != null && bundle.getState() == Bundle.ACTIVE ) {
- return element.createExecutableExtension(classAttribute);
- } else {
- final Object[] ret = new Object[1];
- final CoreException[] exc = new CoreException[1];
- BusyIndicator.showWhile(null, new Runnable() {
- public void run() {
- try {
- ret[0] = element.createExecutableExtension(classAttribute);
- } catch (CoreException e) {
- exc[0] = e;
- }
- }
- });
- if (exc[0] != null)
- throw exc[0];
- else
- return ret[0];
- }
- }
-
-
- /**
- * Starts a build in the background.
- * @param project The project to build or <code>null</code> to build the workspace.
- */
- public static void startBuildInBackground(final IProject project) {
- getBuildJob(project).schedule();
- }
-
-
- private static final class BuildJob extends Job {
- private final IProject fProject;
- private BuildJob(String name, IProject project) {
- super(name);
- fProject= project;
- }
-
- public boolean isCoveredBy(BuildJob other) {
- if (other.fProject == null) {
- return true;
- }
- return fProject != null && fProject.equals(other.fProject);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IStatus run(IProgressMonitor monitor) {
- synchronized (getClass()) {
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- Job[] buildJobs = Job.getJobManager().find(ResourcesPlugin.FAMILY_MANUAL_BUILD);
- for (int i= 0; i < buildJobs.length; i++) {
- Job curr= buildJobs[i];
- if (curr != this && curr instanceof BuildJob) {
- BuildJob job= (BuildJob) curr;
- if (job.isCoveredBy(this)) {
- curr.cancel(); // cancel all other build jobs of our kind
- }
- }
- }
- }
- try {
- if (fProject != null) {
- monitor.beginTask(Messages.format(JavaUIMessages.CoreUtility_buildproject_taskname, fProject.getName()), 2);
- fProject.build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor,1));
- JavaScriptPlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(monitor,1));
- } else {
- monitor.beginTask(JavaUIMessages.CoreUtility_buildall_taskname, 2);
- JavaScriptPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 2));
- }
- } catch (CoreException e) {
- return e.getStatus();
- } catch (OperationCanceledException e) {
- return Status.CANCEL_STATUS;
- }
- finally {
- monitor.done();
- }
- return Status.OK_STATUS;
- }
- public boolean belongsTo(Object family) {
- return ResourcesPlugin.FAMILY_MANUAL_BUILD == family;
- }
- }
-
- /**
- * Returns a build job
- * @param project The project to build or <code>null</code> to build the workspace.
- */
- public static Job getBuildJob(final IProject project) {
- Job buildJob= new BuildJob(JavaUIMessages.CoreUtility_job_title, project);
- buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
- buildJob.setUser(true);
- return buildJob;
- }
-
- /**
- * Set the autobuild to the value of the parameter and
- * return the old one.
- *
- * @param state the value to be set for autobuilding.
- * @return the old value of the autobuild state
- */
- public static boolean enableAutoBuild(boolean state) throws CoreException {
- IWorkspace workspace= ResourcesPlugin.getWorkspace();
- IWorkspaceDescription desc= workspace.getDescription();
- boolean isAutoBuilding= desc.isAutoBuilding();
- if (isAutoBuilding != state) {
- desc.setAutoBuilding(state);
- workspace.setDescription(desc);
- }
- return isAutoBuilding;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ElementValidator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ElementValidator.java
deleted file mode 100644
index 00c021d9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ElementValidator.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-
-/**
- * Helper class to check if a set of <tt>IJavaScriptElement</tt> objects can be
- * modified by an operation.
- *
- *
- */
-public class ElementValidator {
-
- private ElementValidator() {
- // no instance
- }
-
- /**
- * Checks if the given element is in sync with the underlying file system.
- *
- * @param element the element to be checked
- * @param parent a parent shell used to present a dialog to the user if the
- * element is not in sync
- * @param title a dialog's title used to present a dialog to the user if the
- * element is not in sync
- * @return boolean <code>true</code> if the element is in sync with the file
- * system. Otherwise <code>false</code> is returned
- */
- public static boolean checkInSync(IAdaptable element, Shell parent,String title) {
- return checkInSync(new IAdaptable[] {element}, parent, title);
- }
-
- /**
- * Checks if the given array of elements is in sync with the underlying file
- * system.
- *
- * @param elements the array of elements to be checked
- * @param parent a parent shell used to present a dialog to the user if
- * one of the elements is not in sync
- * @param title a dialog's title used to present a dialog to the user if
- * one of the elements is not in sync
- * @return boolean <code>true</code> if the all elements are in sync with
- * the file system. Otherwise <code>false</code> is returned
- */
- public static boolean checkInSync(IAdaptable[] elements, Shell parent, String title) {
- return checkInSync(getResources(elements), parent, title);
- }
-
- /**
- * Checks if the given element is read-only and if so the methods tries
- * to make the element writable by calling validate edit. If
- * <code>validateEdit</code> was able to make the file writable the method
- * additionally checks if the file has been changed by calling
- * <code>validateEdit</code>.
- *
- * @param element the element to be checked
- * @param parent a parent shell used to present a dialog to the user if the
- * check fails
- * @param title a dialog's title used to present a dialog to the user if the
- * check fails
- * @return boolean <code>true</code> if the element is writable and its
- * content didn't change by calling <code>validateEdit</code>. Otherwise
- * <code>false</code> is returned
- *
- * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
- */
- public static boolean checkValidateEdit(IJavaScriptElement element, Shell parent, String title) {
- return checkValidateEdit(new IJavaScriptElement[] {element}, parent, title);
- }
-
- /**
- * Checks if the given elements are read-only and if so the methods tries to
- * make the element writable by calling <code>validateEdit</code>. If
- * <code>validateEdit</code> was able to make the file writable the method
- * additionally checks if the file has been changed by calling
- * <code>validateEdit</code>.
- *
- * @param elements the elements to be checked
- * @param parent a parent shell used to present a dialog to the user if the
- * check fails
- * @param title a dialog's title used to present a dialog to the user if the
- * check fails
- * @return boolean <code>true</code> if all elements are writable and their
- * content didn't change by calling <code>validateEdit</code>. Otherwise
- * <code>false</code> is returned
- *
- * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object)
- */
- public static boolean checkValidateEdit(IJavaScriptElement[] elements, Shell parent, String title) {
- return checkValidateEdit(getResources(elements), parent, title);
- }
-
- /**
- * Checks a combination of <code>checkInSync</code> and
- * <code>checkValidateEdit</code> depending of the value of
- * <code>editor</code>. If <code>editor</code> is <code>true</code> only
- * <code>checkValidateEdit</code> is performed since the editor does a in
- * sync check on focus change. If <code>editor</code> is <code>false</code>
- * both checks are performed.
- *
- * @param element the element to be checked
- * @param parent a parent shell used to present a dialog to the user if the
- * check fails
- * @param title a dialog's title used to present a dialog to the user if the
- * check fails
- * @return boolean <code>true</code> if the element passed the checks.
- * Otherwise <code>false</code> is returned
- *
- * @see #checkInSync(IAdaptable, Shell, String)
- * @see #checkValidateEdit(IJavaScriptElement, Shell, String)
- */
- public static boolean check(IJavaScriptElement element, Shell parent, String title, boolean editor) {
- return check(new IJavaScriptElement[] {element}, parent, title, editor);
- }
-
- /**
- * Checks a combination of <code>checkInSync</code> and
- * <code>checkValidateEdit</code> depending of the value of
- * <code>editor</code>. If <code>editor</code> is <code>true</code> only
- * <code>checkValidateEdit</code> is performed since the editor does a in
- * sync check on focus change. If <code>editor</code> is <code>false</code>
- * both checks are performed.
- *
- * @param elements the elements to be checked
- * @param parent a parent shell used to present a dialog to the user if the
- * check fails
- * @param title a dialog's title used to present a dialog to the user if the
- * check fails
- * @return boolean <code>true</code> if all elements pass the checks.
- * Otherwise <code>false</code> is returned
- *
- * @see #checkInSync(IAdaptable[], Shell, String)
- * @see #checkValidateEdit(IJavaScriptElement[], Shell, String)
- */
- public static boolean check(IJavaScriptElement[] elements, Shell parent,String title, boolean editor) {
- IResource[] resources= getResources(elements);
- if (!editor && !checkInSync(resources, parent, title))
- return false;
- return checkValidateEdit(resources, parent, title);
- }
-
- private static boolean checkInSync(IResource[] resources, Shell parent, String title) {
- IStatus status= Resources.checkInSync(resources);
- if (status.isOK())
- return true;
- ErrorDialog.openError(parent, title,
- JavaUIMessages.ElementValidator_cannotPerform,
- status);
- return false;
- }
-
- private static boolean checkValidateEdit(IResource[] resources, Shell parent, String title) {
- IStatus status= Resources.makeCommittable(resources, parent);
- if (!status.isOK()) {
- ErrorDialog.openError(parent, title,
- JavaUIMessages.ElementValidator_cannotPerform,
- status);
- return false;
- }
- return true;
- }
-
- private static IResource[] getResources(IAdaptable[] elements) {
- Set result= new HashSet();
- for (int i= 0; i < elements.length; i++) {
- IAdaptable element= elements[i];
- IResource resource= null;
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement je= (IJavaScriptElement)element;
- IJavaScriptUnit cu= (IJavaScriptUnit)je.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- je= cu.getPrimary();
- }
- resource= je.getResource();
- } else {
- resource= (IResource)element.getAdapter(IResource.class);
- }
- if (resource != null)
- result.add(resource);
- }
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ExceptionHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ExceptionHandler.java
deleted file mode 100644
index 999b86a6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ExceptionHandler.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.io.StringWriter;
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-
-/**
- * The default exception handler shows an error dialog when one of its handle methods
- * is called. If the passed exception is a <code>CoreException</code> an error dialog
- * pops up showing the exception's status information. For a <code>InvocationTargetException</code>
- * a normal message dialog pops up showing the exception's message. Additionally the exception
- * is written to the platform log.
- */
-public class ExceptionHandler {
-
- private static ExceptionHandler fgInstance= new ExceptionHandler();
-
- /**
- * Logs the given exception using the platform's logging mechanism. The exception is
- * logged as an error with the error code <code>JavaStatusConstants.INTERNAL_ERROR</code>.
- */
- public static void log(Throwable t, String message) {
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(),
- IJavaStatusConstants.INTERNAL_ERROR, message, t));
- }
-
- /**
- * Handles the given <code>CoreException</code>. The workbench shell is used as a parent
- * for the dialog window.
- *
- * @param e the <code>CoreException</code> to be handled
- * @param title the dialog window's window title
- * @param message message to be displayed by the dialog window
- */
- public static void handle(CoreException e, String title, String message) {
- handle(e, JavaScriptPlugin.getActiveWorkbenchShell(), title, message);
- }
-
- /**
- * Handles the given <code>CoreException</code>.
- *
- * @param e the <code>CoreException</code> to be handled
- * @param parent the dialog window's parent shell
- * @param title the dialog window's window title
- * @param message message to be displayed by the dialog window
- */
- public static void handle(CoreException e, Shell parent, String title, String message) {
- fgInstance.perform(e, parent, title, message);
- }
-
- /**
- * Handles the given <code>InvocationTargetException</code>. The workbench shell is used
- * as a parent for the dialog window.
- *
- * @param e the <code>InvocationTargetException</code> to be handled
- * @param title the dialog window's window title
- * @param message message to be displayed by the dialog window
- */
- public static void handle(InvocationTargetException e, String title, String message) {
- handle(e, JavaScriptPlugin.getActiveWorkbenchShell(), title, message);
- }
-
- /**
- * Handles the given <code>InvocationTargetException</code>.
- *
- * @param e the <code>InvocationTargetException</code> to be handled
- * @param parent the dialog window's parent shell
- * @param title the dialog window's window title
- * @param message message to be displayed by the dialog window
- */
- public static void handle(InvocationTargetException e, Shell parent, String title, String message) {
- fgInstance.perform(e, parent, title, message);
- }
-
- //---- Hooks for subclasses to control exception handling ------------------------------------
-
- protected void perform(CoreException e, Shell shell, String title, String message) {
- JavaScriptPlugin.log(e);
- IStatus status= e.getStatus();
- if (status != null) {
- ErrorDialog.openError(shell, title, message, status);
- } else {
- displayMessageDialog(e, e.getMessage(), shell, title, message);
- }
- }
-
- protected void perform(InvocationTargetException e, Shell shell, String title, String message) {
- Throwable target= e.getTargetException();
- if (target instanceof CoreException) {
- perform((CoreException)target, shell, title, message);
- } else {
- JavaScriptPlugin.log(e);
- if (e.getMessage() != null && e.getMessage().length() > 0) {
- displayMessageDialog(e, e.getMessage(), shell, title, message);
- } else {
- displayMessageDialog(e, target.getMessage(), shell, title, message);
- }
- }
- }
-
- //---- Helper methods -----------------------------------------------------------------------
-
- private void displayMessageDialog(Throwable t, String exceptionMessage, Shell shell, String title, String message) {
- StringWriter msg= new StringWriter();
- if (message != null) {
- msg.write(message);
- msg.write("\n\n"); //$NON-NLS-1$
- }
- if (exceptionMessage == null || exceptionMessage.length() == 0)
- msg.write(JavaUIMessages.ExceptionDialog_seeErrorLogMessage);
- else
- msg.write(exceptionMessage);
- MessageDialog.openError(shell, title, msg.toString());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JSDScopeUiUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JSDScopeUiUtil.java
deleted file mode 100644
index df4cd024..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JSDScopeUiUtil.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-
-
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-
-import org.eclipse.wst.jsdt.core.JSDScopeUtil;
-
-import org.eclipse.wst.jsdt.internal.ui.IJsGlobalScopeContainerInitializerExtension;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-
-
-/**
- * @author childsb
- *
- */
-
-/* (mostly) static methods to figure out classpath entries and container initializers *
- *
- */
-public class JSDScopeUiUtil {
-
- private static final String CLASS="class"; //$NON-NLS-1$
- private static final String ID="id"; //$NON-NLS-1$
-
- public static IJsGlobalScopeContainerInitializerExtension findLibraryUiInitializer(IPath compUnitPath, IJavaScriptProject javaProject) {
- System.out.println("public static IJsGlobalScopeContainerInitializerExtension findLibraryInitializer("); //$NON-NLS-1$
- JsGlobalScopeContainerInitializer init = JSDScopeUtil.findLibraryInitializer(compUnitPath,javaProject);
- return (IJsGlobalScopeContainerInitializerExtension)init;
- }
-
- public static IJsGlobalScopeContainerInitializerExtension getContainerUiInitializer(IPath compUnitPath) {
- try {
- IExtensionRegistry registry = Platform.getExtensionRegistry();
- IExtensionPoint extensionPoint = registry.getExtensionPoint("org.eclipse.wst.jsdt.ui.JsGlobalScopeUIInitializer"); //$NON-NLS-1$
- IConfigurationElement points[] = extensionPoint.getConfigurationElements();
- // int[] priorities = new int[points.length];
-
-
-
- for(int i = 0;i < points.length;i++){
- String id = points[i].getAttribute(ID);
- if(id!=null && compUnitPath.equals(new Path(id))){
- Object o = points[i].createExecutableExtension(CLASS);
- return (IJsGlobalScopeContainerInitializerExtension)o;
- }
-
- }
-
- }catch(Exception e) {
- JavaScriptPlugin.log( e);
- }
- return null;
- //IJsGlobalScopeContainerInitializer init = JSDScopeUtil.getContainerInitializer(compUnitPath);
- //System.out.println("public static IJsGlobalScopeContainerInitializerExtension getContainerInitializer(");
- // return (IJsGlobalScopeContainerInitializerExtension)init;
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavaUIHelp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavaUIHelp.java
deleted file mode 100644
index f8005b61..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavaUIHelp.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.help.HelpSystem;
-import org.eclipse.help.IContext;
-import org.eclipse.help.IContextProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.HelpEvent;
-import org.eclipse.swt.events.HelpListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-public class JavaUIHelp {
-
- public static void setHelp(StructuredViewer viewer, String contextId) {
- JavaUIHelpListener listener= new JavaUIHelpListener(viewer, contextId);
- viewer.getControl().addHelpListener(listener);
- }
-
- public static void setHelp(JavaEditor editor, StyledText text, String contextId) {
- JavaUIHelpListener listener= new JavaUIHelpListener(editor, contextId);
- text.addHelpListener(listener);
- }
-
- /**
- * Creates and returns a help context provider for the given part.
- *
- * @param part the part for which to create the help context provider
- * @param contextId the optional context ID used to retrieve static help
- * @return the help context provider
- */
- public static IContextProvider getHelpContextProvider(IWorkbenchPart part, String contextId) {
- IStructuredSelection selection;
- try {
- selection= SelectionConverter.getStructuredSelection(part);
- } catch (JavaScriptModelException ex) {
- JavaScriptPlugin.log(ex);
- selection= StructuredSelection.EMPTY;
- }
- Object[] elements= selection.toArray();
- return new JavaUIHelpContextProvider(contextId, elements);
- }
-
- private static class JavaUIHelpListener implements HelpListener {
-
- private StructuredViewer fViewer;
- private String fContextId;
- private JavaEditor fEditor;
-
- public JavaUIHelpListener(StructuredViewer viewer, String contextId) {
- fViewer= viewer;
- fContextId= contextId;
- }
-
- public JavaUIHelpListener(JavaEditor editor, String contextId) {
- fContextId= contextId;
- fEditor= editor;
- }
-
- /*
- * @see HelpListener#helpRequested(HelpEvent)
- *
- */
- public void helpRequested(HelpEvent e) {
- try {
- Object[] selected= null;
- if (fViewer != null) {
- ISelection selection= fViewer.getSelection();
- if (selection instanceof IStructuredSelection) {
- selected= ((IStructuredSelection)selection).toArray();
- }
- } else if (fEditor != null) {
- IJavaScriptElement input= SelectionConverter.getInput(fEditor);
- if (ActionUtil.isOnBuildPath(input)) {
- selected= SelectionConverter.codeResolve(fEditor);
- }
- }
- JavadocHelpContext.displayHelp(fContextId, selected);
- } catch (CoreException x) {
- JavaScriptPlugin.log(x);
- }
- }
- }
-
- private static class JavaUIHelpContextProvider implements IContextProvider {
- private String fId;
- private Object[] fSelected;
- public JavaUIHelpContextProvider(String id, Object[] selected) {
- fId= id;
- fSelected= selected;
- }
- public int getContextChangeMask() {
- return SELECTION;
- }
- public IContext getContext(Object target) {
- IContext context= HelpSystem.getContext(fId);
- if (fSelected != null && fSelected.length > 0) {
- try {
- context= new JavadocHelpContext(context, fSelected);
- } catch (JavaScriptModelException e) {
- // since we are updating the UI with async exec it
- // can happen that the element doesn't exist anymore
- // but we are still showing it in the user interface
- if (!e.isDoesNotExist())
- JavaScriptPlugin.log(e);
- }
- }
- return context;
- }
- public String getSearchExpression(Object target) {
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavadocHelpContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavadocHelpContext.java
deleted file mode 100644
index 5cbd432c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/JavadocHelpContext.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.help.HelpSystem;
-import org.eclipse.help.IContext;
-import org.eclipse.help.IContext2;
-import org.eclipse.help.IHelpResource;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTML2TextReader;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.JSdocContentAccess;
-
-import com.ibm.icu.text.BreakIterator;
-
-public class JavadocHelpContext implements IContext2 {
-
-
- public static void displayHelp(String contextId, Object[] selected) throws CoreException {
- IContext context= HelpSystem.getContext(contextId);
- if (context != null) {
- if (selected != null && selected.length > 0) {
- context= new JavadocHelpContext(context, selected);
- }
- PlatformUI.getWorkbench().getHelpSystem().displayHelp(context);
- }
- }
-
-
- private static class JavaUIHelpResource implements IHelpResource {
-
- private IJavaScriptElement fElement;
- private String fUrl;
-
- public JavaUIHelpResource(IJavaScriptElement element, String url) {
- fElement= element;
- fUrl= url;
- }
-
- public String getHref() {
- return fUrl;
- }
-
- public String getLabel() {
- String label= JavaScriptElementLabels.getTextLabel(fElement, JavaScriptElementLabels.ALL_DEFAULT | JavaScriptElementLabels.ALL_FULLY_QUALIFIED);
- return Messages.format(JavaUIMessages.JavaUIHelp_link_label, label);
- }
- }
-
-
- private IHelpResource[] fHelpResources;
- private String fText;
- private String fTitle;
-
-
- // see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=85719
- private static final boolean BUG_85719_FIXED= false;
-
- public JavadocHelpContext(IContext context, Object[] elements) throws JavaScriptModelException {
- Assert.isNotNull(elements);
- if (context instanceof IContext2)
- fTitle= ((IContext2)context).getTitle();
-
- List helpResources= new ArrayList();
-
- String javadocSummary= null;
- for (int i= 0; i < elements.length; i++) {
- if (elements[i] instanceof IJavaScriptElement) {
- IJavaScriptElement element= (IJavaScriptElement) elements[i];
- // if element isn't on the build path skip it
- if (!ActionUtil.isOnBuildPath(element))
- continue;
-
- // Create Javadoc summary
- if (BUG_85719_FIXED) {
- if (javadocSummary == null) {
- javadocSummary= retrieveText(element);
- if (javadocSummary != null) {
- String elementLabel= JavaScriptElementLabels.getTextLabel(element, JavaScriptElementLabels.ALL_DEFAULT);
-
- // FIXME: needs to be NLSed once the code becomes active
- javadocSummary= "<b>Javadoc for " + elementLabel + ":</b><br>" + javadocSummary; //$NON-NLS-1$//$NON-NLS-2$
- }
- } else {
- javadocSummary= ""; // no Javadoc summary for multiple selection //$NON-NLS-1$
- }
- }
-
- URL url= JavaScriptUI.getJSdocLocation(element, true);
- if (url == null || doesNotExist(url)) {
- IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
- if (root != null) {
- url= JavaScriptUI.getJSdocBaseLocation(element);
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- element= element.getJavaScriptProject();
- } else {
- element= root;
- }
- url= JavaScriptUI.getJSdocLocation(element, false);
- }
- }
- if (url != null) {
- IHelpResource javaResource= new JavaUIHelpResource(element, getURLString(url));
- helpResources.add(javaResource);
- }
- }
- }
-
- // Add static help topics
- if (context != null) {
- IHelpResource[] resources= context.getRelatedTopics();
- if (resources != null) {
- for (int j= 0; j < resources.length; j++) {
- helpResources.add(resources[j]);
- }
- }
- }
-
- fHelpResources= (IHelpResource[]) helpResources.toArray(new IHelpResource[helpResources.size()]);
-
- if (context != null)
- fText= context.getText();
-
- if (BUG_85719_FIXED) {
- if (javadocSummary != null && javadocSummary.length() > 0) {
- if (fText != null)
- fText= context.getText() + "<br><br>" + javadocSummary; //$NON-NLS-1$
- else
- fText= javadocSummary;
- }
- }
-
- if (fText == null)
- fText= ""; //$NON-NLS-1$
-
- }
-
- private String getURLString(URL url) {
- String location= url.toExternalForm();
- if (url.getRef() != null) {
- int anchorIdx= location.lastIndexOf('#');
- if (anchorIdx != -1) {
- return location.substring(0, anchorIdx) + "?noframes=true" + location.substring(anchorIdx); //$NON-NLS-1$
- }
- }
- return location + "?noframes=true"; //$NON-NLS-1$
- }
-
- private boolean doesNotExist(URL url) {
- if (url.getProtocol().equals("file")) { //$NON-NLS-1$
- File file= new File(url.getFile());
- return !file.exists();
- }
- return false;
- }
-
- private String retrieveText(IJavaScriptElement elem) throws JavaScriptModelException {
- if (elem instanceof IMember) {
- Reader reader= JSdocContentAccess.getHTMLContentReader((IMember)elem, true, true);
- if (reader != null)
- reader= new HTML2TextReader(reader, null);
- if (reader != null) {
- String str= getString(reader);
- BreakIterator breakIterator= BreakIterator.getSentenceInstance();
- breakIterator.setText(str);
- return str.substring(0, breakIterator.next());
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Gets the reader content as a String
- */
- private static String getString(Reader reader) {
- StringBuffer buf= new StringBuffer();
- char[] buffer= new char[1024];
- int count;
- try {
- while ((count= reader.read(buffer)) != -1)
- buf.append(buffer, 0, count);
- } catch (IOException e) {
- return null;
- }
- return buf.toString();
- }
-
- public IHelpResource[] getRelatedTopics() {
- return fHelpResources;
- }
-
- public String getText() {
- return fText;
- }
-
- public String getStyledText() {
- return fText;
- }
-
- public String getCategory(IHelpResource topic) {
- if (topic instanceof JavaUIHelpResource)
- return JavaUIMessages.JavaUIHelpContext_javaHelpCategory_label;
-
- return null;
- }
-
- /*
- * @see org.eclipse.help.IContext2#getTitle()
- *
- */
- public String getTitle() {
- return fTitle;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/OpenTypeHierarchyUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/OpenTypeHierarchyUtil.java
deleted file mode 100644
index 0839d607..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/OpenTypeHierarchyUtil.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.typehierarchy.TypeHierarchyViewPart;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class OpenTypeHierarchyUtil {
-
- private OpenTypeHierarchyUtil() {
- }
-
- public static TypeHierarchyViewPart open(IJavaScriptElement element, IWorkbenchWindow window) {
- IJavaScriptElement[] candidates= getCandidates(element);
- if (candidates != null) {
- return open(candidates, window);
- }
- return null;
- }
-
- public static TypeHierarchyViewPart open(IJavaScriptElement[] candidates, IWorkbenchWindow window) {
- Assert.isTrue(candidates != null && candidates.length != 0);
-
- IJavaScriptElement input= null;
- if (candidates.length > 1) {
- String title= JavaUIMessages.OpenTypeHierarchyUtil_selectionDialog_title;
- String message= JavaUIMessages.OpenTypeHierarchyUtil_selectionDialog_message;
- input= SelectionConverter.selectJavaElement(candidates, window.getShell(), title, message);
- } else {
- input= candidates[0];
- }
- if (input == null)
- return null;
-
-
- return openInViewPart(window, input);
- }
-
- private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaScriptElement input) {
- IWorkbenchPage page= window.getActivePage();
- try {
- TypeHierarchyViewPart result= (TypeHierarchyViewPart) page.findView(JavaScriptUI.ID_TYPE_HIERARCHY);
- if (result != null) {
- result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
- }
- result= (TypeHierarchyViewPart) page.showView(JavaScriptUI.ID_TYPE_HIERARCHY);
- result.setInputElement(input);
- return result;
- } catch (CoreException e) {
- ExceptionHandler.handle(e, window.getShell(),
- JavaUIMessages.OpenTypeHierarchyUtil_error_open_view, e.getMessage());
- }
- return null;
- }
-
- /**
- * Converts the input to a possible input candidates
- */
- public static IJavaScriptElement[] getCandidates(Object input) {
- if (!(input instanceof IJavaScriptElement)) {
- return null;
- }
- try {
- IJavaScriptElement elem= (IJavaScriptElement) input;
- switch (elem.getElementType()) {
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- return new IJavaScriptElement[] { elem };
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- if (((IPackageFragment)elem).containsJavaResources())
- return new IJavaScriptElement[] {elem};
- break;
- case IJavaScriptElement.IMPORT_DECLARATION:
- IImportDeclaration decl= (IImportDeclaration) elem;
- if (decl.isOnDemand()) {
- elem= JavaModelUtil.findTypeContainer(elem.getJavaScriptProject(), Signature.getQualifier(elem.getElementName()));
- } else {
- elem= elem.getJavaScriptProject().findType(elem.getElementName());
- }
- if (elem == null)
- return null;
- return new IJavaScriptElement[] {elem};
-
- case IJavaScriptElement.CLASS_FILE:
- return new IJavaScriptElement[] { ((IClassFile)input).getType() };
- case IJavaScriptElement.JAVASCRIPT_UNIT: {
- IJavaScriptUnit cu= (IJavaScriptUnit) elem.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- IType[] types= cu.getTypes();
- if (types.length > 0) {
- return types;
- }
- }
- break;
- }
- default:
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PatternConstructor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PatternConstructor.java
deleted file mode 100644
index 0dc557c7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PatternConstructor.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-/**
- *
- */
-public class PatternConstructor {
-
-
- private PatternConstructor() {
- // don't instantiate
- }
-
- /**
- * Creates a pattern element from the pattern string which is either a reg-ex expression or in our old
- * 'StringMatcher' format.
- * @param pattern The search pattern
- * @param isCaseSensitive Set to <code>true</code> to create a case insensitive pattern
- * @param isRegexSearch <code>true</code> if the passed string already is a reg-ex pattern
- * @return The created pattern
- * @throws PatternSyntaxException
- */
- public static Pattern createPattern(String pattern, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException {
- if (!isRegexSearch) {
- pattern= asRegEx(pattern, new StringBuffer()).toString();
- }
-
- if (!isCaseSensitive)
- return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
-
- return Pattern.compile(pattern, Pattern.MULTILINE);
- }
-
- /**
- * Creates a pattern element from the pattern string which is either a reg-ex expression or in our old
- * 'StringMatcher' format.
- * @param patterns The search patterns
- * @param isCaseSensitive Set to <code>true</code> to create a case insensitive pattern
- * @param isRegexSearch <code>true</code> if the passed string already is a reg-ex pattern
- * @return The created pattern
- * @throws PatternSyntaxException
- */
- public static Pattern createPattern(String[] patterns, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException {
- StringBuffer pattern= new StringBuffer();
- for (int i= 0; i < patterns.length; i++) {
- if (i > 0) {
- pattern.append('|');
- }
- if (isRegexSearch) {
- pattern.append(patterns[i]);
- } else {
- asRegEx(patterns[i], pattern);
- }
- }
- return createPattern(pattern.toString(), isCaseSensitive, true);
- }
-
-
- /**
- * Translates a StringMatcher pattern (using '*' and '?') to a regex pattern string
- * @param stringMatcherPattern a pattern using '*' and '?'
- */
- private static StringBuffer asRegEx(String stringMatcherPattern, StringBuffer out) {
- boolean escaped= false;
- boolean quoting= false;
-
- int i= 0;
- while (i < stringMatcherPattern.length()) {
- char ch= stringMatcherPattern.charAt(i++);
-
- if (ch == '*' && !escaped) {
- if (quoting) {
- out.append("\\E"); //$NON-NLS-1$
- quoting= false;
- }
- out.append(".*"); //$NON-NLS-1$
- escaped= false;
- continue;
- } else if (ch == '?' && !escaped) {
- if (quoting) {
- out.append("\\E"); //$NON-NLS-1$
- quoting= false;
- }
- out.append("."); //$NON-NLS-1$
- escaped= false;
- continue;
- } else if (ch == '\\' && !escaped) {
- escaped= true;
- continue;
-
- } else if (ch == '\\' && escaped) {
- escaped= false;
- if (quoting) {
- out.append("\\E"); //$NON-NLS-1$
- quoting= false;
- }
- out.append("\\\\"); //$NON-NLS-1$
- continue;
- }
-
- if (!quoting) {
- out.append("\\Q"); //$NON-NLS-1$
- quoting= true;
- }
- if (escaped && ch != '*' && ch != '?' && ch != '\\')
- out.append('\\');
- out.append(ch);
- escaped= ch == '\\';
-
- }
- if (quoting)
- out.append("\\E"); //$NON-NLS-1$
-
- return out;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PixelConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PixelConverter.java
deleted file mode 100644
index 6166cd9e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/PixelConverter.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Control;
-
-/**
- * @deprecated - use {@link org.eclipse.jface.layout.PixelConverter}
- */
-public class PixelConverter extends org.eclipse.jface.layout.PixelConverter {
-
- public PixelConverter(Control control) {
- super(control);
- }
-
- public PixelConverter(Font font) {
- super(font);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/RowLayouter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/RowLayouter.java
deleted file mode 100644
index 32175cd8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/RowLayouter.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Control;
-
-
-/**
- * Helper class to layout a number of children if the composite uses a <code>GridLayout</code>.
- * If the numbers of widgets to be layouted into one row is smaller than the number of columns
- * defined for the grid layout the helper class assigns a corresponing value to the <code>
- * GridData.horizontalSpan</code> field.
- *
- * Additionally a row layouter manages a default <code>GridData</code> object for each column.
- * If set this grid data is used for the widget if it doesn't manage its own grid data object.
- *
- * Call one of the <code>perform</code> methods to assign the correct grid data objects to
- * a set of widgets according to the number of columns passed to the layouter's constructor.
- */
-public class RowLayouter {
-
- public int spanHorizontalAlignment= -1;
- public int spanGrabExcessHorizontalSpace= -1;
- public int spanHorizontalSpan= -1;
- public int spanHorizontalIndent= -1;
- public int spanWidthHint= -1;
-
- public int spanVerticalAlignment= -1;
- public int spanGrabExcessVerticalSpace= -1;
- public int spanVerticalSpan= -1;
- public int spanHeightHint= -1;
-
- private int fNumColumns;
- private boolean fOrder;
- private Control fLastControl;
- private GridData[] fDefaultGridDatas= new GridData[4];
-
- public RowLayouter(int numColumns) {
- this(numColumns, false);
- }
-
- public RowLayouter(int numColumns, boolean order) {
- fNumColumns= numColumns;
- fOrder= order;
- }
-
- public void setDefaultSpan() {
- spanHorizontalAlignment= GridData.FILL;
- spanGrabExcessHorizontalSpace= 1;
- }
-
- public void perform(Control c1) {
- perform(new Control[] {c1}, 0);
- }
-
- public void perform(Control c1, Control c2, int span) {
- perform(new Control[] {c1, c2}, span);
- }
-
- public void perform(Control c1, Control c2, Control c3, int span) {
- perform(new Control[] {c1, c2, c3}, span);
- }
-
- public void perform(Control[] controls, int spanColumn) {
- int numColumns= numColumns();
- Assert.isTrue(controls.length <= numColumns);
- order(controls);
- int gridIndex= 0;
- for (int i= 0; i < controls.length; i++) {
- Control control= controls[i];
- GridData gd= (GridData)control.getLayoutData();
- if (gd == null)
- gd= getGridData(gridIndex);
-
- if (i == spanColumn) {
- int span= numColumns - (controls.length - 1);
- gridIndex+= span;
- if (gd == null)
- gd= new GridData();
- applyDelta(gd);
- gd.horizontalSpan= span;
- } else {
- gridIndex++;
- }
- control.setLayoutData(gd);
- }
- }
-
- private void applyDelta(GridData gd) {
- if (spanHorizontalAlignment != -1)
- gd.horizontalAlignment= spanHorizontalAlignment;
-
- if (spanGrabExcessHorizontalSpace != -1) {
- if (spanGrabExcessHorizontalSpace == 0)
- gd.grabExcessHorizontalSpace= false;
- else
- gd.grabExcessHorizontalSpace= true;
- }
-
-
- if (spanHorizontalSpan != -1)
- gd.horizontalSpan= spanHorizontalSpan;
-
- if (spanHorizontalIndent != -1)
- gd.horizontalIndent= spanHorizontalIndent;
-
- if (spanWidthHint != -1)
- gd.widthHint= spanWidthHint;
-
- if (spanVerticalAlignment != -1)
- gd.verticalAlignment= spanVerticalAlignment;
-
- if (spanGrabExcessVerticalSpace != -1) {
- if (spanGrabExcessVerticalSpace == 0)
- gd.grabExcessVerticalSpace= false;
- else
- gd.grabExcessVerticalSpace= true;
- }
-
- if (spanVerticalSpan != -1)
- gd.verticalSpan= spanVerticalSpan;
-
- if (spanHeightHint != -1)
- gd.heightHint= spanHeightHint;
- }
- public void setDefaultGridData(GridData gd, int index) {
- if (index >= fDefaultGridDatas.length) {
- GridData[] newDatas= new GridData[index + 4];
- System.arraycopy(fDefaultGridDatas, 0, newDatas, 0, fDefaultGridDatas.length);
- fDefaultGridDatas= newDatas;
- }
- fDefaultGridDatas[index]= gd;
- }
-
- public GridData getGridData(int index) {
- if (index > fDefaultGridDatas.length)
- return null;
-
- return cloneGridData(fDefaultGridDatas[index]);
- }
-
- public int numColumns() {
- return fNumColumns;
- }
-
- protected void order(Control[] controls) {
- if (!fOrder)
- return;
-
- for (int i= 0; i < controls.length; i++) {
- Control control= controls[i];
- control.moveBelow(fLastControl);
- fLastControl= control;
- }
- }
-
- protected GridData cloneGridData(GridData gd) {
- if (gd == null)
- return null;
-
- GridData result= new GridData();
- result.horizontalAlignment= gd.horizontalAlignment;
- result.grabExcessHorizontalSpace= gd.grabExcessHorizontalSpace;
- result.horizontalSpan= gd.horizontalSpan;
- result.horizontalIndent= gd.horizontalIndent;
- result.widthHint= gd.widthHint;
-
- result.verticalAlignment= gd.verticalAlignment;
- result.grabExcessVerticalSpace= gd.grabExcessVerticalSpace;
- result.verticalSpan= gd.verticalSpan;
- result.heightHint= gd.heightHint;
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SWTUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SWTUtil.java
deleted file mode 100644
index 44cc874c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SWTUtil.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Caret;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Widget;
-
-/**
- * Utility class to simplify access to some SWT resources.
- */
-public class SWTUtil {
-
- /**
- * Returns the standard display to be used. The method first checks, if
- * the thread calling this method has an associated disaply. If so, this
- * display is returned. Otherwise the method returns the default display.
- */
- public static Display getStandardDisplay() {
- Display display;
- display= Display.getCurrent();
- if (display == null)
- display= Display.getDefault();
- return display;
- }
-
- /**
- * Returns the shell for the given widget. If the widget doesn't represent
- * a SWT object that manage a shell, <code>null</code> is returned.
- *
- * @return the shell for the given widget
- */
- public static Shell getShell(Widget widget) {
- if (widget instanceof Control)
- return ((Control)widget).getShell();
- if (widget instanceof Caret)
- return ((Caret)widget).getParent().getShell();
- if (widget instanceof DragSource)
- return ((DragSource)widget).getControl().getShell();
- if (widget instanceof DropTarget)
- return ((DropTarget)widget).getControl().getShell();
- if (widget instanceof Menu)
- return ((Menu)widget).getParent().getShell();
- if (widget instanceof ScrollBar)
- return ((ScrollBar)widget).getParent().getShell();
-
- return null;
- }
-
-
- /**
- * Returns a width hint for a button control.
- */
- public static int getButtonWidthHint(Button button) {
- button.setFont(JFaceResources.getDialogFont());
- PixelConverter converter= new PixelConverter(button);
- int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
- return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
- }
-
- /**
- * Sets width and height hint for the button control.
- * <b>Note:</b> This is a NOP if the button's layout data is not
- * an instance of <code>GridData</code>.
- *
- * @param button the button for which to set the dimension hint
- */
- public static void setButtonDimensionHint(Button button) {
- Assert.isNotNull(button);
- Object gd= button.getLayoutData();
- if (gd instanceof GridData) {
- ((GridData)gd).widthHint= getButtonWidthHint(button);
- ((GridData)gd).horizontalAlignment = GridData.FILL;
- }
- }
-
- public static int getTableHeightHint(Table table, int rows) {
- if (table.getFont().equals(JFaceResources.getDefaultFont()))
- table.setFont(JFaceResources.getDialogFont());
- int result= table.getItemHeight() * rows + table.getHeaderHeight();
- if (table.getLinesVisible())
- result+= table.getGridLineWidth() * (rows - 1);
- return result;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SelectionUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SelectionUtil.java
deleted file mode 100644
index 1c59908b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/SelectionUtil.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.part.ISetSelectionTarget;
-
-public class SelectionUtil {
-
- public static List toList(ISelection selection) {
- if (selection instanceof IStructuredSelection)
- return ((IStructuredSelection) selection).toList();
- return null;
- }
-
- /**
- * Returns the selected element if the selection consists of a single
- * element only.
- *
- * @param s the selection
- * @return the selected first element or null
- */
- public static Object getSingleElement(ISelection s) {
- if (! (s instanceof IStructuredSelection))
- return null;
- IStructuredSelection selection= (IStructuredSelection) s;
- if (selection.size() != 1)
- return null;
-
- return selection.getFirstElement();
- }
-
-
- /**
- * Attempts to select and reveal the specified resources in all parts within
- * the supplied workbench window's active page.
- * <p>
- * Checks all parts in the active page to see if they implement
- * <code>ISetSelectionTarget</code>, either directly or as an adapter. If
- * so, tells the part to select and reveal the specified resources.
- * </p>
- *
- * @param resources the resources to be selected and revealed
- * @param window the workbench window to select and reveal the resource
- *
- * @see ISetSelectionTarget
- *
- * @see org.eclipse.ui.wizards.newresource.BasicNewResourceWizard#selectAndReveal(IResource,
- * IWorkbenchWindow)
- */
- public static void selectAndReveal(IResource[] resources, IWorkbenchWindow window) {
- // validate the input
- if (window == null || resources == null || Arrays.asList(resources).contains(null)) {
- return;
- }
- IWorkbenchPage page= window.getActivePage();
- if (page == null) {
- return;
- }
-
- // get all the view and editor parts
- List parts= new ArrayList();
- IWorkbenchPartReference refs[]= page.getViewReferences();
- for (int i= 0; i < refs.length; i++) {
- IWorkbenchPart part= refs[i].getPart(false);
- if (part != null) {
- parts.add(part);
- }
- }
- refs= page.getEditorReferences();
- for (int i= 0; i < refs.length; i++) {
- if (refs[i].getPart(false) != null) {
- parts.add(refs[i].getPart(false));
- }
- }
-
- final ISelection selection= new StructuredSelection(resources);
- Iterator itr= parts.iterator();
- while (itr.hasNext()) {
- IWorkbenchPart part= (IWorkbenchPart) itr.next();
-
- // get the part's ISetSelectionTarget implementation
- ISetSelectionTarget target= null;
- if (part instanceof ISetSelectionTarget) {
- target= (ISetSelectionTarget) part;
- } else {
- target= (ISetSelectionTarget) part.getAdapter(ISetSelectionTarget.class);
- }
-
- if (target != null) {
- // select and reveal resource
- final ISetSelectionTarget finalTarget= target;
- window.getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- finalTarget.selectReveal(selection);
- }
- });
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/StringMatcher.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/StringMatcher.java
deleted file mode 100644
index f2099cde..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/StringMatcher.java
+++ /dev/null
@@ -1,384 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher. Supports '*' and '?' wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
- protected int fLength; // pattern length
- protected boolean fIgnoreWildCards;
- protected boolean fIgnoreCase;
- protected boolean fHasLeadingStar;
- protected boolean fHasTrailingStar;
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound= 0;
-
-
- protected static final char fSingleWildCard= '\u0000';
-
- public static class Position {
- int start; //inclusive
- int end; //exclusive
- public Position(int start, int end) {
- this.start= start;
- this.end= end;
- }
- public int getStart() {
- return start;
- }
- public int getEnd() {
- return end;
- }
- }
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern. The pattern may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase, boolean ignoreWildCards) {
- if (pattern == null)
- throw new IllegalArgumentException();
- fIgnoreCase= ignoreCase;
- fIgnoreWildCards= ignoreWildCards;
- fPattern= pattern;
- fLength= pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null)
- throw new IllegalArgumentException();
-
- int tlen= text.length();
- if (start < 0)
- start= 0;
- if (end > tlen)
- end= tlen;
- if (end < 0 ||start >= end )
- return null;
- if (fLength == 0)
- return new Position(start, start);
- if (fIgnoreWildCards) {
- int x= posIn(text, start, end);
- if (x < 0)
- return null;
- return new Position(x, x+fLength);
- }
-
- int segCount= fSegments.length;
- if (segCount == 0)//pattern contains only '*'(s)
- return new Position (start, end);
-
- int curPos= start;
- int matchStart= -1;
- int i;
- for (i= 0; i < segCount && curPos < end; ++i) {
- String current= fSegments[i];
- int nextMatch= regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0 )
- return null;
- if(i == 0)
- matchStart= nextMatch;
- curPos= nextMatch + current.length();
- }
- if (i < segCount)
- return null;
- return new Position(matchStart, curPos);
- }
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched eitherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- return match(text, 0, text.length());
- }
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text)
- throw new IllegalArgumentException();
-
- if (start > end)
- return false;
-
- if (fIgnoreWildCards)
- return (end - start == fLength) && fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength);
- int segCount= fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern contains only '*'(s)
- return true;
- if (start == end)
- return fLength == 0;
- if (fLength == 0)
- return start == end;
-
- int tlen= text.length();
- if (start < 0)
- start= 0;
- if (end > tlen)
- end= tlen;
-
- int tCurPos= start;
- int bound= end - fBound;
- if ( bound < 0)
- return false;
- int i=0;
- String current= fSegments[i];
- int segLength= current.length();
-
- /* process first segment */
- if (!fHasLeadingStar){
- if(!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos= tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar) && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current= fSegments[i];
- int currentMatch;
- int k= current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch= textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0)
- return false;
- } else {
- currentMatch= regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0)
- return false;
- }
- tCurPos= currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen= current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount ;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments= new String[1];
- fSegments[0]= fPattern;
- fBound= fLength;
- }
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- */
- private void parseWildCards() {
- if(fPattern.startsWith("*"))//$NON-NLS-1$
- fHasLeadingStar= true;
- if(fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar= true;
- }
- }
-
- Vector temp= new Vector();
-
- int pos= 0;
- StringBuffer buf= new StringBuffer();
- while (pos < fLength) {
- char c= fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next= fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments= new String[temp.size()];
- temp.copyInto(fSegments);
- }
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max= end - fLength;
-
- if (!fIgnoreCase) {
- int i= text.indexOf(fPattern, start);
- if (i == -1 || i > max)
- return -1;
- return i;
- }
-
- for (int i= start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength))
- return i;
- }
-
- return -1;
- }
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen= p.length();
-
- int max= end - plen;
- for (int i= start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen))
- return i;
- }
- return -1;
- }
-
-
- protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) {
- while (plen-- > 0) {
- char tchar= text.charAt(tStart++);
- char pchar= p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar)
- continue;
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar))
- continue;
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar))
- continue;
- }
- return false;
- }
- return true;
- }
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen= p.length();
- int max= end - plen;
-
- if (!fIgnoreCase) {
- int i= text.indexOf(p, start);
- if (i == -1 || i > max)
- return -1;
- return i;
- }
-
- for (int i= start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen))
- return i;
- }
-
- return -1;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java
deleted file mode 100644
index 3c6b2745..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnPixelData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-
-/**
- * A special composite to layout columns inside a table. The composite is needed since we have
- * to layout the columns "before" the actual table gets layouted. Hence we can't use a normal
- * layout manager.
- */
-public class TableLayoutComposite extends Composite {
-
- /**
- * The number of extra pixels taken as horizontal trim by the table column.
- * To ensure there are N pixels available for the content of the column,
- * assign N+COLUMN_TRIM for the column width.
- *
- *
- */
- private static int COLUMN_TRIM = "carbon".equals(SWT.getPlatform()) ? 24 : 3; //$NON-NLS-1$
-
- private List columns= new ArrayList();
-
- /**
- * Creates a new <code>TableLayoutComposite</code>.
- */
- public TableLayoutComposite(Composite parent, int style) {
- super(parent, style);
- addControlListener(new ControlAdapter() {
- public void controlResized(ControlEvent e) {
- Rectangle area= getClientArea();
- Table table= (Table)getChildren()[0];
- Point preferredSize= computeTableSize(table);
- int width= area.width - 2 * table.getBorderWidth();
- if (preferredSize.y > area.height) {
- // Subtract the scrollbar width from the total column width
- // if a vertical scrollbar will be required
- Point vBarSize = table.getVerticalBar().getSize();
- width -= vBarSize.x;
- }
- layoutTable(table, width, area, table.getSize().x < area.width);
- }
- });
- }
-
- /**
- * Adds a new column of data to this table layout.
- *
- * @param data the column layout data
- */
- public void addColumnData(ColumnLayoutData data) {
- columns.add(data);
- }
-
- //---- Helpers -------------------------------------------------------------------------------------
-
- private Point computeTableSize(Table table) {
- Point result= table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
-
- int width= 0;
- int size= columns.size();
- for (int i= 0; i < size; ++i) {
- ColumnLayoutData layoutData= (ColumnLayoutData) columns.get(i);
- if (layoutData instanceof ColumnPixelData) {
- ColumnPixelData col= (ColumnPixelData) layoutData;
- width += col.width;
- if (col.addTrim) {
- width += COLUMN_TRIM;
- }
- } else if (layoutData instanceof ColumnWeightData) {
- ColumnWeightData col= (ColumnWeightData) layoutData;
- width += col.minimumWidth;
- } else {
- Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$
- }
- }
- if (width > result.x)
- result.x= width;
- return result;
- }
-
- private void layoutTable(Table table, int width, Rectangle area, boolean increase) {
- // XXX: Layout is being called with an invalid value the first time
- // it is being called on Linux. This method resets the
- // Layout to null so we make sure we run it only when
- // the value is OK.
- if (width <= 1)
- return;
-
- TableColumn[] tableColumns= table.getColumns();
- int size= Math.min(columns.size(), tableColumns.length);
- int[] widths= new int[size];
- int fixedWidth= 0;
- int numberOfWeightColumns= 0;
- int totalWeight= 0;
-
- // First calc space occupied by fixed columns
- for (int i= 0; i < size; i++) {
- ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
- if (col instanceof ColumnPixelData) {
- ColumnPixelData cpd= (ColumnPixelData) col;
- int pixels= cpd.width;
- if (cpd.addTrim) {
- pixels += COLUMN_TRIM;
- }
- widths[i]= pixels;
- fixedWidth += pixels;
- } else if (col instanceof ColumnWeightData) {
- ColumnWeightData cw= (ColumnWeightData) col;
- numberOfWeightColumns++;
- // first time, use the weight specified by the column data, otherwise use the actual width as the weight
- // int weight = firstTime ? cw.weight : tableColumns[i].getWidth();
- int weight= cw.weight;
- totalWeight += weight;
- } else {
- Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$
- }
- }
-
- // Do we have columns that have a weight
- if (numberOfWeightColumns > 0) {
- // Now distribute the rest to the columns with weight.
- int rest= width - fixedWidth;
- int totalDistributed= 0;
- for (int i= 0; i < size; ++i) {
- ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
- if (col instanceof ColumnWeightData) {
- ColumnWeightData cw= (ColumnWeightData) col;
- // calculate weight as above
- // int weight = firstTime ? cw.weight : tableColumns[i].getWidth();
- int weight= cw.weight;
- int pixels= totalWeight == 0 ? 0 : weight * rest / totalWeight;
- if (pixels < cw.minimumWidth)
- pixels= cw.minimumWidth;
- totalDistributed += pixels;
- widths[i]= pixels;
- }
- }
-
- // Distribute any remaining pixels to columns with weight.
- int diff= rest - totalDistributed;
- for (int i= 0; diff > 0; ++i) {
- if (i == size)
- i= 0;
- ColumnLayoutData col= (ColumnLayoutData) columns.get(i);
- if (col instanceof ColumnWeightData) {
- ++widths[i];
- --diff;
- }
- }
- }
-
- if (increase) {
- table.setSize(area.width, area.height);
- }
- for (int i= 0; i < size; i++) {
- tableColumns[i].setWidth(widths[i]);
- }
- if (!increase) {
- table.setSize(area.width, area.height);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TypeNameMatchLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TypeNameMatchLabelProvider.java
deleted file mode 100644
index eaaf02d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TypeNameMatchLabelProvider.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class TypeNameMatchLabelProvider extends LabelProvider {
-
- public static final int SHOW_FULLYQUALIFIED= 0x01;
- public static final int SHOW_PACKAGE_POSTFIX= 0x02;
- public static final int SHOW_PACKAGE_ONLY= 0x04;
- public static final int SHOW_ROOT_POSTFIX= 0x08;
- public static final int SHOW_TYPE_ONLY= 0x10;
- public static final int SHOW_TYPE_CONTAINER_ONLY= 0x20;
- public static final int SHOW_POST_QUALIFIED= 0x40;
-
- private static final Image CLASS_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS);
- private static final Image ANNOTATION_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ANNOTATION);
- private static final Image INTERFACE_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
- private static final Image ENUM_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ENUM);
- private static final Image PKG_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE);
-
- private int fFlags;
-
- public TypeNameMatchLabelProvider(int flags) {
- fFlags= flags;
- }
-
- private boolean isSet(int flag) {
- return (fFlags & flag) != 0;
- }
-
- private String getPackageName(String packName) {
- if (packName.length() == 0)
- return JavaUIMessages.TypeInfoLabelProvider_default_package;
- else
- return packName;
- }
-
- /* non java-doc
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- if (! (element instanceof TypeNameMatch))
- return super.getText(element);
-
- TypeNameMatch typeRef= (TypeNameMatch) element;
- StringBuffer buf= new StringBuffer();
- if (isSet(SHOW_TYPE_ONLY)) {
- buf.append(typeRef.getSimpleTypeName());
- } else if (isSet(SHOW_TYPE_CONTAINER_ONLY)) {
- String containerName= typeRef.getTypeContainerName();
- buf.append(getPackageName(containerName));
- } else if (isSet(SHOW_PACKAGE_ONLY)) {
- String packName= typeRef.getPackageName();
- buf.append(getPackageName(packName));
- } else {
- if (isSet(SHOW_FULLYQUALIFIED)) {
- buf.append(typeRef.getFullyQualifiedName());
- } else if (isSet(SHOW_POST_QUALIFIED)) {
- buf.append(typeRef.getSimpleTypeName());
- String containerName= typeRef.getTypeContainerName();
- if (containerName != null && containerName.length() > 0) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(containerName);
- }
- } else {
- buf.append(typeRef.getTypeQualifiedName());
- }
-
- if (isSet(SHOW_PACKAGE_POSTFIX)) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- String packName= typeRef.getPackageName();
- buf.append(getPackageName(packName));
- }
- }
- if (isSet(SHOW_ROOT_POSTFIX)) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- IPackageFragmentRoot root= typeRef.getPackageFragmentRoot();
- JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED, buf);
- }
- return buf.toString();
- }
-
- /* non java-doc
- * @see ILabelProvider#getImage
- */
- public Image getImage(Object element) {
- if (! (element instanceof TypeNameMatch))
- return super.getImage(element);
-
- if (isSet(SHOW_TYPE_CONTAINER_ONLY)) {
- TypeNameMatch typeRef= (TypeNameMatch) element;
- if (typeRef.getPackageName().equals(typeRef.getTypeContainerName()))
- return PKG_ICON;
-
- // XXX cannot check outer type for interface efficiently (5887)
- return CLASS_ICON;
-
- } else if (isSet(SHOW_PACKAGE_ONLY)) {
- return PKG_ICON;
- } else {
- return CLASS_ICON;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ViewerPane.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ViewerPane.java
deleted file mode 100644
index 88810ac0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ViewerPane.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.util;
-
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.custom.ViewForm;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.ToolBar;
-
-/**
- * A <code>ViewerPane</code> is a convenience class which installs a
- * <code>CLabel</code> and a <code>Toolbar</code> in a <code>ViewForm</code>.
- * <P>
- */
-public class ViewerPane extends ViewForm {
-
- private ToolBarManager fToolBarManager;
-
- public ViewerPane(Composite parent, int style) {
- super(parent, style);
-
- marginWidth= 0;
- marginHeight= 0;
-
- CLabel label= new CLabel(this, SWT.NONE);
- setTopLeft(label);
-
- ToolBar tb= new ToolBar(this, SWT.FLAT);
- setTopCenter(tb);
- fToolBarManager= new ToolBarManager(tb);
- }
-
- /**
- * Sets the receiver's title text.
- */
- public void setText(String label) {
- CLabel cl= (CLabel) getTopLeft();
- cl.setText(label);
- }
-
- public String getText() {
- CLabel cl= (CLabel) getTopLeft();
- return cl.getText();
- }
-
- /**
- * Sets the receiver's title image.
- */
- public void setImage(Image image) {
- CLabel cl= (CLabel) getTopLeft();
- cl.setImage(image);
- }
-
- public Image getImage() {
- CLabel cl= (CLabel) getTopLeft();
- return cl.getImage();
- }
-
- public ToolBarManager getToolBarManager() {
- return fToolBarManager;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java
deleted file mode 100644
index d091d2b8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.ui.IEditorRegistry;
-import org.eclipse.ui.IPropertyListener;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * JavaUILabelProvider that respects settings from the Appearance preference page.
- * Triggers a viewer update when a preference changes.
- */
-public class AppearanceAwareLabelProvider extends JavaUILabelProvider implements IPropertyChangeListener, IPropertyListener {
-
- public final static long DEFAULT_TEXTFLAGS= JavaScriptElementLabels.ROOT_VARIABLE | JavaScriptElementLabels.T_TYPE_PARAMETERS | JavaScriptElementLabels.M_PARAMETER_NAMES |
- JavaScriptElementLabels.M_APP_TYPE_PARAMETERS | JavaScriptElementLabels.M_APP_RETURNTYPE | JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED;
- public final static int DEFAULT_IMAGEFLAGS= JavaElementImageProvider.OVERLAY_ICONS;
-
- private long fTextFlagMask;
- private int fImageFlagMask;
-
- /**
- * Constructor for AppearanceAwareLabelProvider.
- */
- public AppearanceAwareLabelProvider(long textFlags, int imageFlags) {
- super(textFlags, imageFlags);
- initMasks();
- PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this);
- PlatformUI.getWorkbench().getEditorRegistry().addPropertyListener(this);
- }
-
- /**
- * Creates a labelProvider with DEFAULT_TEXTFLAGS and DEFAULT_IMAGEFLAGS
- */
- public AppearanceAwareLabelProvider() {
- this(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
- }
-
- private void initMasks() {
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- fTextFlagMask= -1;
- if (!store.getBoolean(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE)) {
- fTextFlagMask ^= JavaScriptElementLabels.M_APP_RETURNTYPE;
- }
- if (!store.getBoolean(PreferenceConstants.APPEARANCE_METHOD_TYPEPARAMETERS)) {
- fTextFlagMask ^= JavaScriptElementLabels.M_APP_TYPE_PARAMETERS;
- }
- if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) {
- fTextFlagMask ^= JavaScriptElementLabels.P_COMPRESSED;
- }
- if (!store.getBoolean(PreferenceConstants.APPEARANCE_CATEGORY)) {
- fTextFlagMask ^= JavaScriptElementLabels.ALL_CATEGORY;
- }
-
- fImageFlagMask= -1;
- }
-
- /*
- * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- */
- public void propertyChange(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (property.equals(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE)
- || property.equals(PreferenceConstants.APPEARANCE_METHOD_TYPEPARAMETERS)
- || property.equals(PreferenceConstants.APPEARANCE_CATEGORY)
- || property.equals(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW)
- || property.equals(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) {
- initMasks();
- LabelProviderChangedEvent lpEvent= new LabelProviderChangedEvent(this, null); // refresh all
- fireLabelProviderChanged(lpEvent);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IPropertyListener#propertyChanged(java.lang.Object, int)
- */
- public void propertyChanged(Object source, int propId) {
- if (propId == IEditorRegistry.PROP_CONTENTS) {
- fireLabelProviderChanged(new LabelProviderChangedEvent(this, null)); // refresh all
- }
- }
-
- /*
- * @see IBaseLabelProvider#dispose()
- */
- public void dispose() {
- PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this);
- PlatformUI.getWorkbench().getEditorRegistry().removePropertyListener(this);
- super.dispose();
- }
-
- /*
- * @see JavaUILabelProvider#evaluateImageFlags()
- */
- protected int evaluateImageFlags(Object element) {
- return getImageFlags() & fImageFlagMask;
- }
-
- /*
- * @see JavaUILabelProvider#evaluateTextFlags()
- */
- protected long evaluateTextFlags(Object element) {
- return getTextFlags() & fTextFlagMask;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/BindingLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/BindingLabelProvider.java
deleted file mode 100644
index ed06655c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/BindingLabelProvider.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.IPackageBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.Modifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Label provider to render bindings in viewers.
- *
- *
- */
-public class BindingLabelProvider extends LabelProvider {
-
-
- private static int getAdornmentFlags(IBinding binding, int flags) {
- int adornments= 0;
- if (binding instanceof IFunctionBinding && ((IFunctionBinding) binding).isConstructor())
- adornments|= JavaScriptElementImageDescriptor.CONSTRUCTOR;
- final int modifiers= binding.getModifiers();
- if (Modifier.isAbstract(modifiers))
- adornments|= JavaScriptElementImageDescriptor.ABSTRACT;
- if (Modifier.isFinal(modifiers))
- adornments|= JavaScriptElementImageDescriptor.FINAL;
- if (Modifier.isSynchronized(modifiers))
- adornments|= JavaScriptElementImageDescriptor.SYNCHRONIZED;
- if (Modifier.isStatic(modifiers))
- adornments|= JavaScriptElementImageDescriptor.STATIC;
- if (binding.isDeprecated())
- adornments|= JavaScriptElementImageDescriptor.DEPRECATED;
- if (binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) {
- if (Modifier.isTransient(modifiers))
- adornments|= JavaScriptElementImageDescriptor.TRANSIENT;
- if (Modifier.isVolatile(modifiers))
- adornments|= JavaScriptElementImageDescriptor.VOLATILE;
- }
- return adornments;
- }
-
- private static ImageDescriptor getBaseImageDescriptor(IBinding binding, int flags) {
- if (binding instanceof ITypeBinding) {
- ITypeBinding typeBinding= (ITypeBinding) binding;
- if (typeBinding.isArray()) {
- typeBinding= typeBinding.getElementType();
- }
- return getTypeImageDescriptor(typeBinding.getDeclaringClass() != null, typeBinding, flags);
- } else if (binding instanceof IFunctionBinding) {
- return getMethodImageDescriptor(binding.getModifiers());
- } else if (binding instanceof IVariableBinding)
- return getFieldImageDescriptor((IVariableBinding) binding);
- return JavaPluginImages.DESC_OBJS_UNKNOWN;
- }
-
- private static ImageDescriptor getClassImageDescriptor(int modifiers) {
- if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers))
- return JavaPluginImages.DESC_OBJS_CLASS;
- else
- return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT;
- }
-
- private static ImageDescriptor getFieldImageDescriptor(IVariableBinding binding) {
- final int modifiers= binding.getModifiers();
- if (Modifier.isPublic(modifiers))
- return JavaPluginImages.DESC_FIELD_PUBLIC;
- if (Modifier.isProtected(modifiers))
- return JavaPluginImages.DESC_FIELD_PROTECTED;
- if (Modifier.isPrivate(modifiers))
- return JavaPluginImages.DESC_FIELD_PRIVATE;
-
- return JavaPluginImages.DESC_FIELD_DEFAULT;
- }
-
- private static void getFieldLabel(IVariableBinding binding, long flags, StringBuffer buffer) {
- if (((flags & JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE) != 0)) {
- getTypeLabel(binding.getType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- buffer.append(' ');
- }
- // qualification
-
- if ((flags & JavaScriptElementLabels.F_FULLY_QUALIFIED) != 0) {
- ITypeBinding declaringClass= binding.getDeclaringClass();
- if (declaringClass != null) { // test for array.length
- getTypeLabel(declaringClass, JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- buffer.append('.');
- }
- }
- buffer.append(binding.getName());
- if (((flags & JavaScriptElementLabels.F_APP_TYPE_SIGNATURE) != 0)) {
- buffer.append(JavaScriptElementLabels.DECL_STRING);
- getTypeLabel(binding.getType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- }
- // post qualification
- if ((flags & JavaScriptElementLabels.F_POST_QUALIFIED) != 0) {
- ITypeBinding declaringClass= binding.getDeclaringClass();
- if (declaringClass != null) { // test for array.length
- buffer.append(JavaScriptElementLabels.CONCAT_STRING);
- getTypeLabel(declaringClass, JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- }
- }
- }
-
- private static void getLocalVariableLabel(IVariableBinding binding, long flags, StringBuffer buffer) {
- if (((flags & JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE) != 0)) {
- getTypeLabel(binding.getType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- buffer.append(' ');
- }
- if (((flags & JavaScriptElementLabels.F_FULLY_QUALIFIED) != 0)) {
- IFunctionBinding declaringMethod= binding.getDeclaringMethod();
- if (declaringMethod != null) {
- getMethodLabel(declaringMethod, flags, buffer);
- buffer.append('.');
- }
- }
- buffer.append(binding.getName());
- if (((flags & JavaScriptElementLabels.F_APP_TYPE_SIGNATURE) != 0)) {
- buffer.append(JavaScriptElementLabels.DECL_STRING);
- getTypeLabel(binding.getType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- }
- }
-
- private static ImageDescriptor getInnerClassImageDescriptor(int modifiers) {
- if (Modifier.isPublic(modifiers))
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC;
- else if (Modifier.isPrivate(modifiers))
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE;
- else if (Modifier.isProtected(modifiers))
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED;
- else
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT;
- }
-
-// private static ImageDescriptor getInnerInterfaceImageDescriptor(int modifiers) {
-// if (Modifier.isPublic(modifiers))
-// return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC;
-// else if (Modifier.isPrivate(modifiers))
-// return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE;
-// else if (Modifier.isProtected(modifiers))
-// return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED;
-// else
-// return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
-// }
-//
-// private static ImageDescriptor getInterfaceImageDescriptor(int modifiers) {
-// if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers))
-// return JavaPluginImages.DESC_OBJS_INTERFACE;
-// else
-// return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
-// }
-
- private static ImageDescriptor getMethodImageDescriptor(int modifiers) {
- if (Modifier.isPublic(modifiers))
- return JavaPluginImages.DESC_MISC_PUBLIC;
- if (Modifier.isProtected(modifiers))
- return JavaPluginImages.DESC_MISC_PROTECTED;
- if (Modifier.isPrivate(modifiers))
- return JavaPluginImages.DESC_MISC_PRIVATE;
-
- return JavaPluginImages.DESC_MISC_DEFAULT;
- }
-
- private static void appendDimensions(int dim, StringBuffer buffer) {
- for (int i=0 ; i < dim; i++) {
- buffer.append('[').append(']');
- }
- }
-
-
- private static void getMethodLabel(IFunctionBinding binding, long flags, StringBuffer buffer) {
- // return type
- if (((flags & JavaScriptElementLabels.M_PRE_RETURNTYPE) != 0) && !binding.isConstructor()) {
- getTypeLabel(binding.getReturnType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- buffer.append(' ');
- }
- // qualification
- if ((flags & JavaScriptElementLabels.M_FULLY_QUALIFIED) != 0) {
- getTypeLabel(binding.getDeclaringClass(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- buffer.append('.');
- }
- buffer.append(binding.getName());
-
- // parameters
- buffer.append('(');
- if ((flags & JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES) != 0) {
- ITypeBinding[] parameters= ((flags & JavaScriptElementLabels.M_PARAMETER_TYPES) != 0) ? binding.getParameterTypes() : null;
- if (parameters != null) {
- for (int index= 0; index < parameters.length; index++) {
- if (index > 0) {
- buffer.append(JavaScriptElementLabels.COMMA_STRING);
- }
- ITypeBinding paramType= parameters[index];
- if (binding.isVarargs() && (index == parameters.length - 1)) {
- getTypeLabel(paramType.getElementType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- appendDimensions(paramType.getDimensions() - 1, buffer);
- buffer.append(JavaScriptElementLabels.ELLIPSIS_STRING);
- } else {
- getTypeLabel(paramType, (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- }
- }
- }
- } else {
- if (binding.getParameterTypes().length > 0) {
- buffer.append(JavaScriptElementLabels.ELLIPSIS_STRING);
- }
- }
- buffer.append(')');
-
- if (((flags & JavaScriptElementLabels.M_APP_RETURNTYPE) != 0) && !binding.isConstructor()) {
- buffer.append(JavaScriptElementLabels.DECL_STRING);
- getTypeLabel(binding.getReturnType(), (flags & JavaScriptElementLabels.T_TYPE_PARAMETERS), buffer);
- }
- // post qualification
- if ((flags & JavaScriptElementLabels.M_POST_QUALIFIED) != 0) {
- buffer.append(JavaScriptElementLabels.CONCAT_STRING);
- getTypeLabel(binding.getDeclaringClass(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- }
- }
-
- private static ImageDescriptor getTypeImageDescriptor(boolean inner, ITypeBinding binding, int flags) {
- if (binding.isClass()) {
- if ((flags & JavaElementImageProvider.LIGHT_TYPE_ICONS) != 0)
- return JavaPluginImages.DESC_OBJS_CLASSALT;
- if (inner)
- return getInnerClassImageDescriptor(binding.getModifiers());
- return getClassImageDescriptor(binding.getModifiers());
- }
- // primitive type, wildcard
- return null;
- }
-
-
- private static void getTypeLabel(ITypeBinding binding, long flags, StringBuffer buffer) {
- if ((flags & JavaScriptElementLabels.T_FULLY_QUALIFIED) != 0) {
- final IPackageBinding pack= binding.getPackage();
- if (pack != null && !pack.isUnnamed()) {
- buffer.append(pack.getName());
- buffer.append('.');
- }
- }
- if ((flags & (JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.T_CONTAINER_QUALIFIED)) != 0) {
- final ITypeBinding declaring= binding.getDeclaringClass();
- if (declaring != null) {
- getTypeLabel(declaring, JavaScriptElementLabels.T_CONTAINER_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- buffer.append('.');
- }
- final IFunctionBinding declaringMethod= binding.getDeclaringMethod();
- if (declaringMethod != null) {
- getMethodLabel(declaringMethod, 0, buffer);
- buffer.append('.');
- }
- }
-
- if (binding.isArray()) {
- getTypeLabel(binding.getElementType(), flags & JavaScriptElementLabels.T_TYPE_PARAMETERS, buffer);
- appendDimensions(binding.getDimensions(), buffer);
- } else { // type variables, primitive, reftype
- String name= binding.getTypeDeclaration().getName();
- if (name.length() == 0) {
- if (binding.isAnonymous()) {
- ITypeBinding baseType= binding.getSuperclass();
-
- if (baseType != null) {
- StringBuffer anonymBaseType= new StringBuffer();
- getTypeLabel(baseType, flags & JavaScriptElementLabels.T_TYPE_PARAMETERS, anonymBaseType);
- buffer.append(Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, anonymBaseType.toString()));
- } else {
- buffer.append(JavaUIMessages.JavaElementLabels_anonym);
- }
- } else {
- buffer.append("UNKNOWN"); //$NON-NLS-1$
- }
- } else {
- buffer.append(name);
- }
- }
-
-
- if ((flags & JavaScriptElementLabels.T_POST_QUALIFIED) != 0) {
- final IFunctionBinding declaringMethod= binding.getDeclaringMethod();
- final ITypeBinding declaringType= binding.getDeclaringClass();
- if (declaringMethod != null) {
- buffer.append(JavaScriptElementLabels.CONCAT_STRING);
- getMethodLabel(declaringMethod, JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- } else if (declaringType != null) {
- buffer.append(JavaScriptElementLabels.CONCAT_STRING);
- getTypeLabel(declaringType, JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & JavaScriptElementLabels.P_COMPRESSED), buffer);
- } else {
- final IPackageBinding pack= binding.getPackage();
- if (pack != null && !pack.isUnnamed()) {
- buffer.append(JavaScriptElementLabels.CONCAT_STRING);
- buffer.append(pack.getName());
- }
- }
- }
- }
-
-// private static void getTypeArgumentsLabel(ITypeBinding[] typeArgs, long flags, StringBuffer buf) {
-// if (typeArgs.length > 0) {
-// buf.append('<');
-// for (int i = 0; i < typeArgs.length; i++) {
-// if (i > 0) {
-// buf.append(JavaScriptElementLabels.COMMA_STRING);
-// }
-// getTypeLabel(typeArgs[i], flags & JavaScriptElementLabels.T_TYPE_PARAMETERS, buf);
-// }
-// buf.append('>');
-// }
-// }
-
- /**
- * Returns the label for a Java element with the flags as defined by {@link JavaScriptElementLabels}.
- * @param binding The binding to render.
- * @param flags The text flags as defined in {@link JavaScriptElementLabels}
- * @return the label of the binding
- */
- public static String getBindingLabel(IBinding binding, long flags) {
- StringBuffer buffer= new StringBuffer(60);
- if (binding instanceof ITypeBinding) {
- getTypeLabel(((ITypeBinding) binding), flags, buffer);
- } else if (binding instanceof IFunctionBinding) {
- getMethodLabel(((IFunctionBinding) binding), flags, buffer);
- } else if (binding instanceof IVariableBinding) {
- final IVariableBinding variable= (IVariableBinding) binding;
- if (variable.isField())
- getFieldLabel(variable, flags, buffer);
- else
- getLocalVariableLabel(variable, flags, buffer);
- }
- return buffer.toString();
- }
-
- /**
- * Returns the image descriptor for a binding with the flags as defined by {@link JavaElementImageProvider}.
- * @param binding The binding to get the image for.
- * @param imageFlags The image flags as defined in {@link JavaElementImageProvider}.
- * @return the image of the binding or null if there is no image
- */
- public static ImageDescriptor getBindingImageDescriptor(IBinding binding, int imageFlags) {
- ImageDescriptor baseImage= getBaseImageDescriptor(binding, imageFlags);
- if (baseImage != null) {
- int adornmentFlags= getAdornmentFlags(binding, imageFlags);
- Point size= ((imageFlags & JavaElementImageProvider.SMALL_ICONS) != 0) ? JavaElementImageProvider.SMALL_SIZE : JavaElementImageProvider.BIG_SIZE;
- return new JavaScriptElementImageDescriptor(baseImage, adornmentFlags, size);
- }
- return null;
- }
-
-
- public static final long DEFAULT_TEXTFLAGS= JavaScriptElementLabels.ALL_DEFAULT;
- public static final int DEFAULT_IMAGEFLAGS= JavaElementImageProvider.OVERLAY_ICONS;
-
-
- final private long fTextFlags;
- final private int fImageFlags;
-
- private ImageDescriptorRegistry fRegistry;
-
- /**
- * Creates a new binding label provider with default text and image flags
- */
- public BindingLabelProvider() {
- this(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
- }
-
- /**
- * @param textFlags Flags defined in {@link JavaScriptElementLabels}.
- * @param imageFlags Flags defined in {@link JavaElementImageProvider}.
- */
- public BindingLabelProvider(final long textFlags, final int imageFlags) {
- fImageFlags= imageFlags;
- fTextFlags= textFlags;
- fRegistry= null;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
- */
- public Image getImage(Object element) {
- if (element instanceof IBinding) {
- ImageDescriptor baseImage= getBindingImageDescriptor((IBinding) element, fImageFlags);
- if (baseImage != null) {
- return getRegistry().get(baseImage);
- }
- }
- return super.getImage(element);
- }
-
- private ImageDescriptorRegistry getRegistry() {
- if (fRegistry == null)
- fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
- return fRegistry;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
- */
- public String getText(Object element) {
- if (element instanceof IBinding) {
- return getBindingLabel((IBinding) element, fTextFlags);
- }
- return super.getText(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredJavaElementLabels.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredJavaElementLabels.java
deleted file mode 100644
index 9ee81d55..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredJavaElementLabels.java
+++ /dev/null
@@ -1,895 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.core.BindingKey;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString.Style;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class ColoredJavaElementLabels {
-
- public static final Style QUALIFIER_STYLE= new Style(ColoredViewersManager.QUALIFIER_COLOR_NAME);
- public static final Style COUNTER_STYLE= new Style(ColoredViewersManager.COUNTER_COLOR_NAME);
- public static final Style DECORATIONS_STYLE= new Style(ColoredViewersManager.DECORATIONS_COLOR_NAME);
-
- private static final Style APPENDED_TYPE_STYLE= DECORATIONS_STYLE;
-
- public final static long COLORIZE= 1L << 55;
-
- private final static long QUALIFIER_FLAGS= JavaScriptElementLabels.P_COMPRESSED | JavaScriptElementLabels.USE_RESOLVED;
-
-
- private static final boolean getFlag(long flags, long flag) {
- return (flags & flag) != 0;
- }
-
- /**
- * Returns the label of the given object. The object must be of type {@link IJavaScriptElement} or adapt to {@link org.eclipse.ui.model.IWorkbenchAdapter}. The empty string is returned
- * if the element type is not known.
- * @param obj Object to get the label from.
- * @param flags The rendering flags
- * @return Returns the label or the empty string if the object type is not supported.
- */
- public static ColoredString getTextLabel(Object obj, long flags) {
- if (obj instanceof IJavaScriptElement) {
- return getElementLabel((IJavaScriptElement) obj, flags);
- } else if (obj instanceof IResource) {
- return new ColoredString(((IResource) obj).getName());
- } else if (obj instanceof JsGlobalScopeContainer) {
- JsGlobalScopeContainer container= (JsGlobalScopeContainer) obj;
- return getContainerEntryLabel(container.getClasspathEntry().getPath(), container.getJavaProject());
- }
- return new ColoredString(JavaScriptElementLabels.getTextLabel(obj, flags));
- }
-
- /**
- * Returns the label for a Java element with the flags as defined by this class.
- * @param element The element to render.
- * @param flags The rendering flags.
- * @return the label of the Java element
- */
- public static ColoredString getElementLabel(IJavaScriptElement element, long flags) {
- ColoredString result= new ColoredString();
- getElementLabel(element, flags, result);
- return result;
- }
-
- /**
- * Returns the label for a Java element with the flags as defined by this class.
- * @param element The element to render.
- * @param flags The rendering flags.
- * @param result The buffer to append the resulting label to.
- */
- public static void getElementLabel(IJavaScriptElement element, long flags, ColoredString result) {
- int type= element.getElementType();
- IPackageFragmentRoot root= null;
-
- if (type != IJavaScriptElement.JAVASCRIPT_MODEL && type != IJavaScriptElement.JAVASCRIPT_PROJECT && type != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- root= JavaModelUtil.getPackageFragmentRoot(element);
- if (root != null && getFlag(flags, JavaScriptElementLabels.PREPEND_ROOT_PATH)) {
- getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED, result);
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- }
-
- switch (type) {
- case IJavaScriptElement.METHOD:
- getMethodLabel((IFunction) element, flags, result);
- break;
- case IJavaScriptElement.FIELD:
- getFieldLabel((IField) element, flags, result);
- break;
- case IJavaScriptElement.LOCAL_VARIABLE:
- getLocalVariableLabel((ILocalVariable) element, flags, result);
- break;
- case IJavaScriptElement.INITIALIZER:
- getInitializerLabel((IInitializer) element, flags, result);
- break;
- case IJavaScriptElement.TYPE:
- getTypeLabel((IType) element, flags, result);
- break;
- case IJavaScriptElement.CLASS_FILE:
- getClassFileLabel((IClassFile) element, flags, result);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- getCompilationUnitLabel((IJavaScriptUnit) element, flags, result);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- getPackageFragmentLabel((IPackageFragment) element, flags, result);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, result);
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- getDeclarationLabel(element, flags, result);
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- result.append(element.getElementName());
- break;
- default:
- result.append(element.getElementName());
- }
-
- if (root != null && getFlag(flags, JavaScriptElementLabels.APPEND_ROOT_PATH)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED, result);
-
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
-
- }
- }
-
- /**
- * Appends the label for a method to a {@link ColoredString}. Considers the M_* flags.
- * @param method The element to render.
- * @param flags The rendering flags. Flags with names starting with 'M_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getMethodLabel(IFunction method, long flags, ColoredString result) {
- try {
- BindingKey resolvedKey= getFlag(flags, JavaScriptElementLabels.USE_RESOLVED) && method.isResolved() ? new BindingKey(method.getKey()) : null;
- String resolvedSig= (resolvedKey != null) ? resolvedKey.toSignature() : null;
-
- // return type
- if (getFlag(flags, JavaScriptElementLabels.M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
- String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType();
- getTypeSignatureLabel(returnTypeSig, flags, result);
- result.append(' ');
- }
-
- // qualification
- if (getFlag(flags, JavaScriptElementLabels.M_FULLY_QUALIFIED)) {
- getTypeLabel(method.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
-
- result.append(method.getElementName());
-
- // parameters
- result.append('(');
- if (getFlag(flags, JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES)) {
- String[] types= null;
- int nParams= 0;
- boolean renderVarargs= false;
- if (getFlag(flags, JavaScriptElementLabels.M_PARAMETER_TYPES)) {
- if (resolvedSig != null) {
- types= Signature.getParameterTypes(resolvedSig);
- } else {
- types= method.getParameterTypes();
- }
- nParams= types.length;
- renderVarargs= method.exists() && Flags.isVarargs(method.getFlags());
- }
- String[] names= null;
- if (getFlag(flags, JavaScriptElementLabels.M_PARAMETER_NAMES) && method.exists()) {
- names= method.getParameterNames();
- if (types == null) {
- nParams= names.length;
- } else { // types != null
- if (nParams != names.length) {
- if (resolvedSig != null && types.length > names.length) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137
- nParams= names.length;
- String[] typesWithoutSyntheticParams= new String[nParams];
- System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0, nParams);
- types= typesWithoutSyntheticParams;
- } else {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029
- // JavaScriptPlugin.logErrorMessage("JavaScriptElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- names= null; // no names rendered
- }
- }
- }
- }
-
- for (int i= 0; i < nParams; i++) {
- if (i > 0) {
- result.append(JavaScriptElementLabels.COMMA_STRING);
- }
- if (types != null) {
- String paramSig= types[i];
- if (renderVarargs && (i == nParams - 1)) {
- int newDim= Signature.getArrayCount(paramSig) - 1;
- getTypeSignatureLabel(Signature.getElementType(paramSig), flags, result);
- for (int k= 0; k < newDim; k++) {
- result.append('[').append(']');
- }
- result.append(JavaScriptElementLabels.ELLIPSIS_STRING);
- } else {
- getTypeSignatureLabel(paramSig, flags, result);
- }
- }
- if (names != null) {
- if (types != null) {
- result.append(' ');
- }
- result.append(names[i]);
- }
- }
- } else {
- if (method.getParameterTypes().length > 0) {
- result.append(JavaScriptElementLabels.ELLIPSIS_STRING);
- }
- }
- result.append(')');
-
- if (getFlag(flags, JavaScriptElementLabels.M_EXCEPTIONS)) {
- String[] types;
- if (resolvedKey != null) {
- //types= resolvedKey.getThrownExceptions();
- types = new String[0];
- } else {
- types= new String[0];
- }
- if (types.length > 0) {
- result.append(" throws "); //$NON-NLS-1$
- for (int i= 0; i < types.length; i++) {
- if (i > 0) {
- result.append(JavaScriptElementLabels.COMMA_STRING);
- }
- getTypeSignatureLabel(types[i], flags, result);
- }
- }
- }
-
- if (getFlag(flags, JavaScriptElementLabels.M_APP_TYPE_PARAMETERS)) {
- int offset= result.length();
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, APPENDED_TYPE_STYLE);
- }
- }
-
- if (getFlag(flags, JavaScriptElementLabels.M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.DECL_STRING);
- String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType();
- getTypeSignatureLabel(returnTypeSig, flags, result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, APPENDED_TYPE_STYLE);
- }
- }
-
- // category
- if (getFlag(flags, JavaScriptElementLabels.M_CATEGORY) && method.exists())
- getCategoryLabel(method, result);
-
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.M_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- if (method.getDeclaringType()!=null)
- getTypeLabel(method.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // NotExistsException will not reach this point
- }
- }
-
- private static void getCategoryLabel(IMember member, ColoredString result) throws JavaScriptModelException {
- String[] categories= member.getCategories();
- if (categories.length > 0) {
- ColoredString categoriesBuf= new ColoredString();
- for (int i= 0; i < categories.length; i++) {
- if (i > 0)
- categoriesBuf.append(JavaUIMessages.JavaElementLabels_category_separator_string);
- categoriesBuf.append(categories[i]);
- }
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(Messages.format(JavaUIMessages.JavaElementLabels_category , categoriesBuf.toString()));
- }
- }
-
- /**
- * Appends the label for a field to a {@link ColoredString}. Considers the F_* flags.
- * @param field The element to render.
- * @param flags The rendering flags. Flags with names starting with 'F_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getFieldLabel(IField field, long flags, ColoredString result) {
- try {
-
- if (getFlag(flags, JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE) && field.exists()) {
- if (getFlag(flags, JavaScriptElementLabels.USE_RESOLVED) && field.isResolved()) {
- getTypeSignatureLabel(new BindingKey(field.getKey()).toSignature(), flags, result);
- } else {
- getTypeSignatureLabel(field.getTypeSignature(), flags, result);
- }
- result.append(' ');
- }
-
- // qualification
- if (getFlag(flags, JavaScriptElementLabels.F_FULLY_QUALIFIED)) {
- getTypeLabel(field.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- result.append(field.getElementName());
-
- if (getFlag(flags, JavaScriptElementLabels.F_APP_TYPE_SIGNATURE) && field.exists()) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.DECL_STRING);
- if (getFlag(flags, JavaScriptElementLabels.USE_RESOLVED) && field.isResolved()) {
- getTypeSignatureLabel(new BindingKey(field.getKey()).toSignature(), flags, result);
- } else {
- getTypeSignatureLabel(field.getTypeSignature(), flags, result);
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, APPENDED_TYPE_STYLE);
- }
- }
-
- // category
- if (getFlag(flags, JavaScriptElementLabels.F_CATEGORY) && field.exists())
- getCategoryLabel(field, result);
-
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.F_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getTypeLabel(field.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // NotExistsException will not reach this point
- }
- }
-
- /**
- * Appends the label for a local variable to a {@link ColoredString}.
- * @param localVariable The element to render.
- * @param flags The rendering flags. Flags with names starting with 'F_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getLocalVariableLabel(ILocalVariable localVariable, long flags, ColoredString result) {
- if (getFlag(flags, JavaScriptElementLabels.F_PRE_TYPE_SIGNATURE)) {
- getTypeSignatureLabel(localVariable.getTypeSignature(), flags, result);
- result.append(' ');
- }
-
- if (getFlag(flags, JavaScriptElementLabels.F_FULLY_QUALIFIED)) {
- getElementLabel(localVariable.getParent(), JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
-
- result.append(localVariable.getElementName());
-
- if (getFlag(flags, JavaScriptElementLabels.F_APP_TYPE_SIGNATURE)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.DECL_STRING);
- getTypeSignatureLabel(localVariable.getTypeSignature(), flags, result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, APPENDED_TYPE_STYLE);
- }
- }
-
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.F_POST_QUALIFIED)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getElementLabel(localVariable.getParent(), JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- }
- }
-
- /**
- * Appends the label for a initializer to a {@link ColoredString}. Considers the I_* flags.
- * @param initializer The element to render.
- * @param flags The rendering flags. Flags with names starting with 'I_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getInitializerLabel(IInitializer initializer, long flags, ColoredString result) {
- // qualification
- if (getFlag(flags, JavaScriptElementLabels.I_FULLY_QUALIFIED)) {
- getTypeLabel(initializer.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- result.append(JavaUIMessages.JavaElementLabels_initializer);
-
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.I_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getTypeLabel(initializer.getDeclaringType(), JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- private static void getTypeSignatureLabel(String typeSig, long flags, ColoredString result) {
- int sigKind= Signature.getTypeSignatureKind(typeSig);
- switch (sigKind) {
- case Signature.BASE_TYPE_SIGNATURE:
- result.append(Signature.toString(typeSig));
- break;
- case Signature.ARRAY_TYPE_SIGNATURE:
- getTypeSignatureLabel(Signature.getElementType(typeSig), flags, result);
- for (int dim= Signature.getArrayCount(typeSig); dim > 0; dim--) {
- result.append('[').append(']');
- }
- break;
- case Signature.CLASS_TYPE_SIGNATURE:
- String baseType= Signature.toString(typeSig);
- result.append(Signature.getSimpleName(baseType));
-
- getTypeArgumentSignaturesLabel(new String[0], flags, result);
- break;
- default:
- // unknown
- }
- }
-
- private static void getTypeArgumentSignaturesLabel(String[] typeArgsSig, long flags, ColoredString result) {
- if (typeArgsSig.length > 0) {
- result.append('<');
- for (int i = 0; i < typeArgsSig.length; i++) {
- if (i > 0) {
- result.append(JavaScriptElementLabels.COMMA_STRING);
- }
- getTypeSignatureLabel(typeArgsSig[i], flags, result);
- }
- result.append('>');
- }
- }
-
- private static void getTypeParameterSignaturesLabel(String[] typeParamSigs, long flags, ColoredString result) {
- if (typeParamSigs.length > 0) {
- result.append('<');
- for (int i = 0; i < typeParamSigs.length; i++) {
- if (i > 0) {
- result.append(JavaScriptElementLabels.COMMA_STRING);
- }
- result.append(Signature.getTypeVariable(typeParamSigs[i]));
- }
- result.append('>');
- }
- }
-
-
- /**
- * Appends the label for a type to a {@link ColoredString}. Considers the T_* flags.
- * @param type The element to render.
- * @param flags The rendering flags. Flags with names starting with 'T_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getTypeLabel(IType type, long flags, ColoredString result) {
-
- if (getFlag(flags, JavaScriptElementLabels.T_FULLY_QUALIFIED)) {
- IPackageFragment pack= type.getPackageFragment();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- }
- if (getFlag(flags, JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.T_CONTAINER_QUALIFIED)) {
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- getTypeLabel(declaringType, JavaScriptElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- int parentType= type.getParent().getElementType();
- if (parentType == IJavaScriptElement.METHOD || parentType == IJavaScriptElement.FIELD || parentType == IJavaScriptElement.INITIALIZER) { // anonymous or local
- getElementLabel(type.getParent(), 0, result);
- result.append('.');
- }
- }
-
- String typeName= type.getElementName();
- if (typeName.length() == 0) { // anonymous
- try {
- String supertypeName= Signature.getSimpleName(type.getSuperclassName());
-
- typeName= Messages.format(JavaUIMessages.JavaElementLabels_anonym_type , supertypeName);
-
- } catch (JavaScriptModelException e) {
- //ignore
- typeName= JavaUIMessages.JavaElementLabels_anonym;
- }
- }
- result.append(typeName);
- if (getFlag(flags, JavaScriptElementLabels.T_TYPE_PARAMETERS)) {
- if (getFlag(flags, JavaScriptElementLabels.USE_RESOLVED) && type.isResolved()) {
- BindingKey key= new BindingKey(type.getKey());
- getTypeParameterSignaturesLabel(new String[0], flags, result);
- }
- }
-
- // category
- if (getFlag(flags, JavaScriptElementLabels.T_CATEGORY) && type.exists()) {
- try {
- getCategoryLabel(type, result);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
-
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.T_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- getTypeLabel(declaringType, JavaScriptElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), result);
- int parentType= type.getParent().getElementType();
- if (parentType == IJavaScriptElement.METHOD || parentType == IJavaScriptElement.FIELD || parentType == IJavaScriptElement.INITIALIZER) { // anonymous or local
- result.append('.');
- getElementLabel(type.getParent(), 0, result);
- }
- } else {
- getPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS, result);
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * Appends the label for a import container, import or package declaration to a {@link ColoredString}. Considers the D_* flags.
- * @param declaration The element to render.
- * @param flags The rendering flags. Flags with names starting with 'D_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getDeclarationLabel(IJavaScriptElement declaration, long flags, ColoredString result) {
- if (getFlag(flags, JavaScriptElementLabels.D_QUALIFIED)) {
- IJavaScriptElement openable= (IJavaScriptElement) declaration.getOpenable();
- if (openable != null) {
- result.append(getElementLabel(openable, JavaScriptElementLabels.CF_QUALIFIED | JavaScriptElementLabels.CU_QUALIFIED | (flags & QUALIFIER_FLAGS)));
- result.append('/');
- }
- }
- if (declaration.getElementType() == IJavaScriptElement.IMPORT_CONTAINER) {
- result.append(JavaUIMessages.JavaElementLabels_import_container);
- } else {
- result.append(declaration.getElementName());
- }
- // post qualification
- if (getFlag(flags, JavaScriptElementLabels.D_POST_QUALIFIED)) {
- int offset= result.length();
- IJavaScriptElement openable= (IJavaScriptElement) declaration.getOpenable();
- if (openable != null) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(getElementLabel(openable, JavaScriptElementLabels.CF_QUALIFIED | JavaScriptElementLabels.CU_QUALIFIED | (flags & QUALIFIER_FLAGS)));
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * Appends the label for a class file to a {@link ColoredString}. Considers the CF_* flags.
- * @param classFile The element to render.
- * @param flags The rendering flags. Flags with names starting with 'CF_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getClassFileLabel(IClassFile classFile, long flags, ColoredString result) {
- if (getFlag(flags, JavaScriptElementLabels.CF_QUALIFIED)) {
- IPackageFragment pack= (IPackageFragment) classFile.getParent();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- }
- result.append(classFile.getElementName());
-
- if (getFlag(flags, JavaScriptElementLabels.CF_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getPackageFragmentLabel((IPackageFragment) classFile.getParent(), flags & QUALIFIER_FLAGS, result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * Appends the label for a compilation unit to a {@link ColoredString}. Considers the CU_* flags.
- * @param cu The element to render.
- * @param flags The rendering flags. Flags with names starting with 'CU_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getCompilationUnitLabel(IJavaScriptUnit cu, long flags, ColoredString result) {
- if (getFlag(flags, JavaScriptElementLabels.CU_QUALIFIED)) {
- IPackageFragment pack= (IPackageFragment) cu.getParent();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), result);
- result.append('.');
- }
- }
- result.append(cu.getElementName());
-
- if (getFlag(flags, JavaScriptElementLabels.CU_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getPackageFragmentLabel((IPackageFragment) cu.getParent(), flags & QUALIFIER_FLAGS, result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * Appends the label for a package fragment to a {@link ColoredString}. Considers the P_* flags.
- * @param pack The element to render.
- * @param flags The rendering flags. Flags with names starting with P_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getPackageFragmentLabel(IPackageFragment pack, long flags, ColoredString result) {
- if (getFlag(flags, JavaScriptElementLabels.P_QUALIFIED)) {
- getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaScriptElementLabels.ROOT_QUALIFIED, result);
- result.append('/');
- }
- if (pack.isDefaultPackage()) {
- result.append(JavaScriptElementLabels.DEFAULT_PACKAGE);
- } else if (getFlag(flags, JavaScriptElementLabels.P_COMPRESSED)) {
- StringBuffer buf= new StringBuffer();
- JavaScriptElementLabels.getPackageFragmentLabel(pack, JavaScriptElementLabels.P_COMPRESSED, buf);
- result.append(buf.toString());
- } else {
- result.append(pack.getElementName());
- }
- if (getFlag(flags, JavaScriptElementLabels.P_POST_QUALIFIED)) {
- int offset= result.length();
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaScriptElementLabels.ROOT_QUALIFIED, result);
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * Appends the label for a package fragment root to a {@link ColoredString}. Considers the ROOT_* flags.
- * @param root The element to render.
- * @param flags The rendering flags. Flags with names starting with ROOT_' are considered.
- * @param result The buffer to append the resulting label to.
- */
- public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- if (root.isArchive())
- getArchiveLabel(root, flags, result);
- else
- getFolderLabel(root, flags, result);
- }
-
- private static void getArchiveLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- // Handle variables different
- if (getFlag(flags, JavaScriptElementLabels.ROOT_VARIABLE) && getVariableLabel(root, flags, result))
- return;
- boolean external= root.isExternal();
- if (external)
- getExternalArchiveLabel(root, flags, result);
- else
- getInternalArchiveLabel(root, flags, result);
- }
-
- private static boolean getVariableLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- try {
- IIncludePathEntry rawEntry= root.getRawIncludepathEntry();
- if (rawEntry != null && rawEntry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE) {
- IPath path= rawEntry.getPath().makeRelative();
- int offset= result.length();
- if (getFlag(flags, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) {
- int segements= path.segmentCount();
- if (segements > 0) {
- result.append(path.segment(segements - 1));
- if (segements > 1) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(path.removeLastSegments(1).toOSString());
- }
- } else {
- result.append(path.toString());
- }
- } else {
- result.append(path.toString());
- }
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- if (root.isExternal())
- result.append(root.getPath().toOSString());
- else
- result.append(root.getPath().makeRelative().toString());
-
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- return true;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // problems with class path
- }
- return false;
- }
-
- private static void getExternalArchiveLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- IPath path= root.getPath();
- if (getFlag(flags, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) {
- int segements= path.segmentCount();
- if (segements > 0) {
- result.append(path.segment(segements - 1));
- int offset= result.length();
- if (segements > 1 || path.getDevice() != null) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(path.removeLastSegments(1).toOSString());
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- } else {
- result.append(path.toOSString());
- }
- } else {
- result.append(path.toOSString());
- }
- }
-
- private static void getInternalArchiveLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- IResource resource= root.getResource();
- boolean rootQualified= getFlag(flags, JavaScriptElementLabels.ROOT_QUALIFIED);
- boolean referencedQualified= getFlag(flags, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root);
- if (rootQualified) {
- result.append(root.getPath().makeRelative().toString());
- } else {
- result.append(root.getElementName());
- int offset= result.length();
- if (referencedQualified) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(resource.getParent().getFullPath().makeRelative().toString());
- } else if (getFlag(flags, JavaScriptElementLabels.ROOT_POST_QUALIFIED)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(root.getParent().getPath().makeRelative().toString());
- } else {
- return;
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- private static void getFolderLabel(IPackageFragmentRoot root, long flags, ColoredString result) {
- IResource resource= root.getResource();
- boolean rootQualified= getFlag(flags, JavaScriptElementLabels.ROOT_QUALIFIED);
- boolean referencedQualified= getFlag(flags, JavaScriptElementLabels.REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root);
- if (rootQualified) {
- result.append(root.getPath().makeRelative().toString());
- } else {
- if (resource != null) {
- IPath projectRelativePath= resource.getProjectRelativePath();
- if (projectRelativePath.segmentCount() == 0) {
- result.append(resource.getName());
- referencedQualified= false;
- } else {
- result.append(projectRelativePath.toString());
- }
- } else
- result.append(root.getElementName());
- int offset= result.length();
- if (referencedQualified) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(resource.getProject().getName());
- } else if (getFlag(flags, JavaScriptElementLabels.ROOT_POST_QUALIFIED)) {
- result.append(JavaScriptElementLabels.CONCAT_STRING);
- result.append(root.getParent().getElementName());
- } else {
- return;
- }
- if (getFlag(flags, COLORIZE)) {
- result.colorize(offset, result.length() - offset, QUALIFIER_STYLE);
- }
- }
- }
-
- /**
- * @param root
- * @return <code>true</code> if the given package fragment root is
- * referenced. This means it is owned by a different project but is referenced
- * by the root's parent. Returns <code>false</code> if the given root
- * doesn't have an underlying resource.
- */
- private static boolean isReferenced(IPackageFragmentRoot root) {
- IResource resource= root.getResource();
- if (resource != null) {
- IProject jarProject= resource.getProject();
- IProject container= root.getJavaScriptProject().getProject();
- return !container.equals(jarProject);
- }
- return false;
- }
-
- /**
- * Returns the label of a classpath container
- * @param containerPath The path of the container.
- * @param project The project the container is resolved in.
- * @return Returns the label of the classpath container
- */
- public static ColoredString getContainerEntryLabel(IPath containerPath, IJavaScriptProject project) {
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, project);
- String description= null;
- if (container != null) {
- description= container.getDescription();
- }
- if (description == null) {
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- if (initializer != null) {
- description= initializer.getDescription(containerPath, project);
- }
- }
- if (description != null) {
- ColoredString str= new ColoredString(description);
- if (containerPath.segmentCount() > 0 && JavaRuntime.JRE_CONTAINER.equals(containerPath.segment(0))) {
- int index= description.indexOf('[');
- if (index != -1) {
- str.colorize(index, description.length() - index, DECORATIONS_STYLE);
- }
- }
- return str;
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return new ColoredString(containerPath.toString());
- }
-
- public static ColoredString decorateColoredString(ColoredString string, String decorated, Style color) {
- String label= string.getString();
- int originalStart= decorated.indexOf(label);
- if (originalStart == -1) {
- return new ColoredString(decorated); // the decorator did something wild
- }
- if (originalStart > 0) {
- ColoredString newString= new ColoredString(decorated.substring(0, originalStart), color);
- newString.append(string);
- string= newString;
- }
- if (decorated.length() > originalStart + label.length()) { // decorator appended something
- return string.append(decorated.substring(originalStart + label.length()), color);
- }
- return string; // no change
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredString.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredString.java
deleted file mode 100644
index 6753ad42..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredString.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-
-public class ColoredString {
-
- public static class Style {
- private final String fForegroundColorName;
-
- public Style(String foregroundColorName) {
- fForegroundColorName= foregroundColorName;
- }
-
- public String getForegroundColorName() {
- return fForegroundColorName;
- }
- }
-
- public static final Style DEFAULT_STYLE= null;
-
- private StringBuffer fBuffer;
- private ArrayList fRanges;
-
- public ColoredString() {
- fBuffer= new StringBuffer();
- fRanges= null;
- }
-
- public ColoredString(String text) {
- this(text, ColoredString.DEFAULT_STYLE);
- }
-
- public ColoredString(String text, Style style) {
- this();
- append(text, style);
- }
-
- public String getString() {
- return fBuffer.toString();
- }
-
- public int length() {
- return fBuffer.length();
- }
-
- public Iterator getRanges() {
- if (!hasRanges())
- return Collections.EMPTY_LIST.iterator();
- return getRangesList().iterator();
- }
-
- public ColoredString append(String text) {
- return append(text, DEFAULT_STYLE);
- }
-
- public ColoredString append(char ch) {
- return append(String.valueOf(ch), DEFAULT_STYLE);
- }
-
- public ColoredString append(ColoredString string) {
- int offset= fBuffer.length();
- fBuffer.append(string.getString());
- for (Iterator iterator= string.getRanges(); iterator.hasNext();) {
- StyleRange curr= (StyleRange) iterator.next();
- addRange(new StyleRange(offset + curr.offset, curr.length, curr.style));
- }
- return this;
- }
-
- public ColoredString append(String text, Style style) {
- if (text.length() == 0)
- return this;
-
- int offset= fBuffer.length();
- fBuffer.append(text);
- if (style != null) {
- int nRanges= getNumberOfRanges();
- if (nRanges > 0) {
- StyleRange last= getRange(nRanges - 1);
- if (last.offset + last.length == offset && style.equals(last.style)) {
- last.length += text.length();
- return this;
- }
- }
- addRange(new StyleRange(offset, text.length(), style));
- }
- return this;
- }
-
- public void colorize(int offset, int length, Style style) {
- if (offset < 0 || offset + length > fBuffer.length()) {
- throw new IllegalArgumentException("Invalid offset (" + offset + ") or length (" + length + ")"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
-
- int insertPos= 0;
- int nRanges= getNumberOfRanges();
- for (int i= 0; i < nRanges; i++) {
- StyleRange curr= getRange(i);
- if (curr.offset + curr.length <= offset) {
- insertPos= i + 1;
- }
- }
- if (insertPos < nRanges) {
- StyleRange curr= getRange(insertPos);
- if (curr.offset > offset + length) {
- throw new IllegalArgumentException("Overlapping ranges"); //$NON-NLS-1$
- }
- }
- addRange(insertPos, new StyleRange(offset, length, style));
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return fBuffer.toString();
- }
-
- private boolean hasRanges() {
- return fRanges != null && !fRanges.isEmpty();
- }
-
- private int getNumberOfRanges() {
- return fRanges == null ? 0 : fRanges.size();
- }
-
- private StyleRange getRange(int index) {
- if (fRanges != null) {
- return (StyleRange) fRanges.get(index);
- }
- throw new IndexOutOfBoundsException();
- }
-
- private void addRange(StyleRange range) {
- getRangesList().add(range);
- }
-
- private void addRange(int index, StyleRange range) {
- getRangesList().add(index, range);
- }
-
- private List getRangesList() {
- if (fRanges == null)
- fRanges= new ArrayList(2);
- return fRanges;
- }
-
- public static class StyleRange {
- public int offset;
- public int length;
- public Style style;
-
- public StyleRange(int offset, int length, Style style) {
- this.offset= offset;
- this.length= length;
- this.style= style;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredViewersManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredViewersManager.java
deleted file mode 100644
index 1ef91525..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ColoredViewersManager.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.jface.resource.ColorRegistry;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.wst.jsdt.internal.ui.preferences.AppearancePreferencePage;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class ColoredViewersManager implements IPropertyChangeListener {
-
- public static final String QUALIFIER_COLOR_NAME= "org.eclipse.wst.jsdt.ui.ColoredLabels.qualifier"; //$NON-NLS-1$
- public static final String DECORATIONS_COLOR_NAME= "org.eclipse.wst.jsdt.ui.ColoredLabels.decorations"; //$NON-NLS-1$
- public static final String COUNTER_COLOR_NAME= "org.eclipse.wst.jsdt.ui.ColoredLabels.counter"; //$NON-NLS-1$
- public static final String INHERITED_COLOR_NAME= "org.eclipse.wst.jsdt.ui.ColoredLabels.inherited"; //$NON-NLS-1$
-
- private static ColoredViewersManager fgInstance= new ColoredViewersManager();
-
- private Map fManagedViewers;
- private ColorRegistry fColorRegisty;
-
- public ColoredViewersManager() {
- fManagedViewers= new HashMap();
- fColorRegisty= JFaceResources.getColorRegistry();
- }
-
- public void installColoredLabels(StructuredViewer viewer) {
- if (fManagedViewers.containsKey(viewer)) {
- return; // already installed
- }
- if (fManagedViewers.isEmpty()) {
- // first viewer installed
- PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this);
- fColorRegisty.addListener(this);
- }
- fManagedViewers.put(viewer, new ManagedViewer(viewer));
- }
-
-
- public void uninstallColoredLabels(StructuredViewer viewer) {
- ManagedViewer mv= (ManagedViewer) fManagedViewers.remove(viewer);
- if (mv == null)
- return; // not installed
-
- if (fManagedViewers.isEmpty()) {
- PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this);
- fColorRegisty.removeListener(this);
- // last viewer uninstalled
- }
- }
-
- public Color getColorForName(String symbolicName) {
- return fColorRegisty.get(symbolicName);
- }
-
-
- public void propertyChange(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (property.equals(QUALIFIER_COLOR_NAME) || property.equals(COUNTER_COLOR_NAME) || property.equals(DECORATIONS_COLOR_NAME)
- || property.equals(AppearancePreferencePage.PREF_COLORED_LABELS)) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- refreshAllViewers();
- }
- });
- }
- }
-
- protected final void refreshAllViewers() {
- for (Iterator iterator= fManagedViewers.values().iterator(); iterator.hasNext();) {
- ManagedViewer viewer= (ManagedViewer) iterator.next();
- viewer.refresh();
- }
- }
-
- private class ManagedViewer implements DisposeListener {
-
- private static final String COLORED_LABEL_KEY= "coloredlabel"; //$NON-NLS-1$
-
- private StructuredViewer fViewer;
- private OwnerDrawSupport fOwnerDrawSupport;
-
- private ManagedViewer(StructuredViewer viewer) {
- fViewer= viewer;
- fOwnerDrawSupport= null;
- fViewer.getControl().addDisposeListener(this);
- if (showColoredLabels()) {
- installOwnerDraw();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
- */
- public void widgetDisposed(DisposeEvent e) {
- uninstallColoredLabels(fViewer);
- }
-
- public final void refresh() {
- Control control= fViewer.getControl();
- if (!control.isDisposed()) {
- if (showColoredLabels()) {
- installOwnerDraw();
- } else {
- uninstallOwnerDraw();
- }
- }
- }
-
- protected void installOwnerDraw() {
- if (fOwnerDrawSupport == null) {
- // not yet installed
- fOwnerDrawSupport= new OwnerDrawSupport(fViewer.getControl()) { // will install itself as listeners
- public ColoredString getColoredLabel(Item item) {
- return getColoredLabelForView(item);
- }
-
- public Color getColor(String foregroundColorName, Display display) {
- return getColorForName(foregroundColorName);
- }
- };
- }
- refreshViewer();
- }
-
- protected void uninstallOwnerDraw() {
- if (fOwnerDrawSupport == null)
- return; // not installed
-
- fOwnerDrawSupport.dispose(); // removes itself as listener
- fOwnerDrawSupport= null;
- refreshViewer();
- }
-
- private void refreshViewer() {
- Control control= fViewer.getControl();
- if (!control.isDisposed()) {
- if (control instanceof Tree) {
- refresh(((Tree) control).getItems());
- } else if (control instanceof Table) {
- refresh(((Table) control).getItems());
- }
- }
- }
-
- private void refresh(Item[] items) {
- for (int i= 0; i < items.length; i++) {
- Item item= items[i];
- item.setData(COLORED_LABEL_KEY, null);
- String text= item.getText();
- item.setText(""); //$NON-NLS-1$
- item.setText(text);
- if (item instanceof TreeItem) {
- refresh(((TreeItem) item).getItems());
- }
- }
- }
-
- private ColoredString getColoredLabelForView(Item item) {
- ColoredString oldLabel= (ColoredString) item.getData(COLORED_LABEL_KEY);
- String itemText= item.getText();
- if (oldLabel != null && oldLabel.getString().equals(itemText)) {
- // avoid accesses to the label provider if possible
- return oldLabel;
- }
- ColoredString newLabel= null;
- IBaseLabelProvider labelProvider= fViewer.getLabelProvider();
- if (labelProvider instanceof IRichLabelProvider) {
- newLabel= ((IRichLabelProvider) labelProvider).getRichTextLabel(item.getData());
- }
- if (newLabel == null) {
- newLabel= new ColoredString(itemText); // fallback. Should never happen.
- } else if (!newLabel.getString().equals(itemText)) {
- // the decorator manager has already queued an new update
- newLabel= ColoredJavaElementLabels.decorateColoredString(newLabel, itemText, ColoredJavaElementLabels.DECORATIONS_STYLE);
- }
- item.setData(COLORED_LABEL_KEY, newLabel); // cache the result
- return newLabel;
- }
-
- }
-
- public static boolean showColoredLabels() {
- String preference= PreferenceConstants.getPreference(AppearancePreferencePage.PREF_COLORED_LABELS, null);
- return preference != null && Boolean.valueOf(preference).booleanValue();
- }
-
- public static void install(StructuredViewer viewer) {
- fgInstance.installColoredLabels(viewer);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java
deleted file mode 100644
index 05db0ad7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.DecoratingLabelProvider;
-import org.eclipse.jface.viewers.DecorationContext;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelDecorator;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.packageview.HierarchicalDecorationContext;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-
-public class DecoratingJavaLabelProvider extends DecoratingLabelProvider implements IRichLabelProvider {
-
- /**
- * Decorating label provider for Java. Combines a JavaUILabelProvider
- * with problem and override indicator with the workbench decorator (label
- * decorator extension point).
- * @param labelProvider the label provider to decorate
- */
- public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider) {
- this(labelProvider, true);
- }
-
- /**
- * Decorating label provider for Java. Combines a JavaUILabelProvider
- * (if enabled with problem indicator) with the workbench
- * decorator (label decorator extension point).
- * @param labelProvider the label provider to decorate
- * @param errorTick show error ticks
- */
- public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider, boolean errorTick) {
- this(labelProvider, errorTick, true);
- }
-
- /**
- * Decorating label provider for Java. Combines a JavaUILabelProvider
- * (if enabled with problem indicator) with the workbench
- * decorator (label decorator extension point).
- * @param labelProvider the label provider to decorate
- * @param errorTick show error ticks
- * @param flatPackageMode configure flat package mode
- */
- public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider, boolean errorTick, boolean flatPackageMode) {
- super(labelProvider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator());
- if (errorTick) {
- labelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
- }
- setFlatPackageMode(flatPackageMode);
- }
-
- /**
- * Tells the label decorator if the view presents packages flat or hierarchical.
- * @param enable If set, packages are presented in flat mode.
- */
- public void setFlatPackageMode(boolean enable) {
- if (enable) {
- setDecorationContext(DecorationContext.DEFAULT_CONTEXT);
- } else {
- setDecorationContext(HierarchicalDecorationContext.CONTEXT);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.IRichLabelProvider#getRichTextLabel(Object)
- */
- public ColoredString getRichTextLabel(Object element) {
- ILabelProvider labelProvider= getLabelProvider();
- if (labelProvider instanceof IRichLabelProvider) {
- // get a rich label from the label decorator
- IRichLabelProvider richLabelProvider= (IRichLabelProvider) labelProvider;
- ColoredString richLabel= richLabelProvider.getRichTextLabel(element);
- if (richLabel != null) {
- String decorated= null;
- ILabelDecorator labelDecorator= getLabelDecorator();
- if (labelDecorator != null) {
- if (labelDecorator instanceof LabelDecorator) {
- decorated= ((LabelDecorator) labelDecorator).decorateText(richLabel.getString(), element, getDecorationContext());
- } else {
- decorated= labelDecorator.decorateText(richLabel.getString(), element);
- }
- }
- if (decorated != null) {
- return ColoredJavaElementLabels.decorateColoredString(richLabel, decorated, ColoredJavaElementLabels.DECORATIONS_STYLE);
- }
- return richLabel;
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/FilterUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/FilterUpdater.java
deleted file mode 100644
index cba4e82d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/FilterUpdater.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-public class FilterUpdater implements IResourceChangeListener {
-
- private ProblemTreeViewer fViewer;
-
- public FilterUpdater(ProblemTreeViewer viewer) {
- Assert.isNotNull(viewer);
- fViewer= viewer;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
- */
- public void resourceChanged(IResourceChangeEvent event) {
- if (fViewer.getInput() == null) {
- return;
- }
- IResourceDelta delta= event.getDelta();
- if (delta == null)
- return;
- IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED);
- for (int i= 0; i < projDeltas.length; i++) {
- IResourceDelta pDelta= projDeltas[i];
- if ((pDelta.getFlags() & IResourceDelta.DESCRIPTION) != 0) {
- IProject project= (IProject) pDelta.getResource();
- if (needsRefiltering(project)) {
- final Control ctrl= fViewer.getControl();
- if (ctrl != null && !ctrl.isDisposed()) {
- // async is needed due to bug 33783
- ctrl.getDisplay().asyncExec(new Runnable() {
- public void run() {
- if (!ctrl.isDisposed())
- fViewer.refresh(false);
- }
- });
- }
- return; // one refresh is good enough
- }
- }
- }
- }
-
- private boolean needsRefiltering(IProject project) {
- try {
- Object element= project;
- if (project.hasNature(JavaScriptCore.NATURE_ID)) {
- element= JavaScriptCore.create(project);
- }
- boolean inView= fViewer.testFindItem(element) != null;
- boolean afterFilter= !fViewer.isFiltered(element, fViewer.getInput());
-
- return inView != afterFilter;
- } catch (CoreException e) {
- return true;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryDropDownAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryDropDownAction.java
deleted file mode 100644
index f428afd1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryDropDownAction.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IWorkbenchActionConstants;
-
-/*package*/ class HistoryDropDownAction extends Action {
-
- private class HistoryAction extends Action {
- private final Object fElement;
-
- public HistoryAction(Object element, int accelerator) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- Assert.isNotNull(element);
- fElement= element;
-
- String label= fHistory.getText(element);
- if (accelerator < 10) {
- //add the numerical accelerator
- label= new StringBuffer().append('&').append(accelerator).append(' ').append(label).toString();
- }
-
- setText(label);
- setImageDescriptor(fHistory.getImageDescriptor(element));
- }
-
- public void run() {
- fHistory.setActiveEntry(fElement);
- }
- }
-
- private class HistoryMenuCreator implements IMenuCreator {
-
- public Menu getMenu(Menu parent) {
- return null;
- }
-
- public Menu getMenu(Control parent) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- final MenuManager manager= new MenuManager();
- manager.setRemoveAllWhenShown(true);
- manager.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager2) {
- List entries= fHistory.getHistoryEntries();
- boolean checkOthers= addEntryMenuItems(manager2, entries);
-
- manager2.add(new Separator());
-
- Action others= new HistoryListAction(fHistory);
- others.setChecked(checkOthers);
- manager2.add(others);
-
- Action clearAction= fHistory.getClearAction();
- if (clearAction != null) {
- manager2.add(clearAction);
- }
-
- manager2.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
-
- fHistory.addMenuEntries(manager);
- }
-
- private boolean addEntryMenuItems(IMenuManager manager2, List entries) {
- if (entries.isEmpty()) {
- return false;
- }
-
- boolean checkOthers= true;
- int min= Math.min(entries.size(), RESULTS_IN_DROP_DOWN);
- for (int i= 0; i < min; i++) {
- Object entry= entries.get(i);
- HistoryAction action= new HistoryAction(entry, i + 1);
- boolean check= entry.equals(fHistory.getCurrentEntry());
- action.setChecked(check);
- if (check)
- checkOthers= false;
- manager2.add(action);
- }
- return checkOthers;
- }
- });
-
- fMenu= manager.createContextMenu(parent);
-
- //workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=129973
- final Display display= parent.getDisplay();
- fMenu.addMenuListener(new MenuAdapter() {
- public void menuHidden(final MenuEvent e) {
- display.asyncExec(new Runnable() {
- public void run() {
- manager.removeAll();
- if (fMenu != null) {
- fMenu.dispose();
- fMenu= null;
- }
- }
- });
- }
- });
- return fMenu;
- }
-
- public void dispose() {
- fHistory= null;
-
- if (fMenu != null) {
- fMenu.dispose();
- fMenu= null;
- }
- }
- }
-
- public static final int RESULTS_IN_DROP_DOWN= 10;
-
- private ViewHistory fHistory;
- private Menu fMenu;
-
- public HistoryDropDownAction(ViewHistory history) {
- fHistory= history;
- fMenu= null;
- setMenuCreator(new HistoryMenuCreator());
- fHistory.configureHistoryDropDownAction(this);
- }
-
- public void run() {
- new HistoryListAction(fHistory).run();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryListAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryListAction.java
deleted file mode 100644
index aceaac90..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/HistoryListAction.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation
- * (report 36180: Callers/Callees view)
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.Separator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-/*package*/ class HistoryListAction extends Action {
-
- private class HistoryListDialog extends StatusDialog {
- private static final int MAX_MAX_ENTRIES= 100;
- private ListDialogField fHistoryList;
- private StringDialogField fMaxEntriesField;
- private int fMaxEntries;
-
- private Object fResult;
-
- private HistoryListDialog() {
- super(fHistory.getShell());
- setTitle(fHistory.getHistoryListDialogTitle());
-
- createHistoryList();
- createMaxEntriesField();
- setHelpAvailable(false);
- }
-
- private void createHistoryList() {
- IListAdapter adapter= new IListAdapter() {
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed(index);
- }
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged();
- }
-
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked();
- }
- };
- String[] buttonLabels= new String[] { JavaUIMessages.HistoryListAction_remove, JavaUIMessages.HistoryListAction_remove_all };
- LabelProvider labelProvider= new TestRunLabelProvider();
- fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider);
- fHistoryList.setLabelText(fHistory.getHistoryListDialogMessage());
-
- List historyEntries= fHistory.getHistoryEntries();
- fHistoryList.setElements(historyEntries);
-
- Object currentEntry= fHistory.getCurrentEntry();
- ISelection sel;
- if (currentEntry != null) {
- sel= new StructuredSelection(currentEntry);
- } else {
- sel= new StructuredSelection();
- }
- fHistoryList.selectElements(sel);
- }
-
- private void createMaxEntriesField() {
- fMaxEntriesField= new StringDialogField();
- fMaxEntriesField.setLabelText(fHistory.getMaxEntriesMessage());
- fMaxEntriesField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- String maxString= fMaxEntriesField.getText();
- boolean valid;
- try {
- fMaxEntries= Integer.parseInt(maxString);
- valid= fMaxEntries > 0 && fMaxEntries < MAX_MAX_ENTRIES;
- } catch (NumberFormatException e) {
- valid= false;
- }
- if (valid)
- updateStatus(StatusInfo.OK_STATUS);
- else
- updateStatus(new StatusInfo(IStatus.ERROR, Messages.format(JavaUIMessages.HistoryListAction_max_entries_constraint, Integer.toString(MAX_MAX_ENTRIES))));
- }
- });
- fMaxEntriesField.setText(Integer.toString(fHistory.getMaxEntries()));
- }
-
- /*
- * @see Dialog#createDialogArea(Composite)
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- inner.setFont(composite.getFont());
-
- LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList, new Separator() }, true);
- LayoutUtil.setHeightHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12));
- LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null));
-
- Composite additionalControls= new Composite(inner, SWT.NONE);
- additionalControls.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- LayoutUtil.doDefaultLayout(additionalControls, new DialogField[] { fMaxEntriesField }, false);
- LayoutUtil.setHorizontalGrabbing(fMaxEntriesField.getTextControl(null));
-
- applyDialogFont(composite);
- return composite;
- }
-
- private void doCustomButtonPressed(int index) {
- switch (index) {
- case 0: // remove
- fHistoryList.removeElements(fHistoryList.getSelectedElements());
- fHistoryList.selectFirstElement();
- break;
-
- case 1: // remove all
- fHistoryList.removeAllElements();
-
- //$FALL-THROUGH$
- default:
- break;
- }
- }
-
- private void doDoubleClicked() {
- okPressed();
- }
-
- private void doSelectionChanged() {
- List selected= fHistoryList.getSelectedElements();
- if (selected.size() >= 1) {
- fResult= selected.get(0);
- } else {
- fResult= null;
- }
- fHistoryList.enableButton(0, selected.size() != 0);
- }
-
- public Object getResult() {
- return fResult;
- }
-
- public List getRemaining() {
- return fHistoryList.getElements();
- }
-
- public int getMaxEntries() {
- return fMaxEntries;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.StatusDialog#create()
- */
- public void create() {
- setShellStyle(getShellStyle() | SWT.RESIZE);
- super.create();
- }
-
- }
-
- private final class TestRunLabelProvider extends LabelProvider {
- private final HashMap fImages= new HashMap();
-
- public String getText(Object element) {
- return fHistory.getText(element);
- }
-
- public Image getImage(Object element) {
- ImageDescriptor imageDescriptor= fHistory.getImageDescriptor(element);
- return getCachedImage(imageDescriptor);
- }
-
- private Image getCachedImage(ImageDescriptor imageDescriptor) {
- Object cached= fImages.get(imageDescriptor);
- if (cached != null)
- return (Image) cached;
- Image image= imageDescriptor.createImage(fHistory.getShell().getDisplay());
- fImages.put(imageDescriptor, image);
- return image;
- }
-
- public void dispose() {
- for (Iterator iter= fImages.values().iterator(); iter.hasNext();) {
- Image image= (Image) iter.next();
- image.dispose();
- }
- fImages.clear();
- }
- }
-
- private ViewHistory fHistory;
-
- public HistoryListAction(ViewHistory history) {
- super(null, IAction.AS_RADIO_BUTTON);
- fHistory= history;
- fHistory.configureHistoryListAction(this);
- }
-
- /*
- * @see IAction#run()
- */
- public void run() {
- HistoryListDialog dialog= new HistoryListDialog();
- if (dialog.open() == Window.OK) {
- fHistory.setHistoryEntries(dialog.getRemaining(), dialog.getResult());
- fHistory.setMaxEntries(dialog.getMaxEntries());
- }
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IProblemChangedListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IProblemChangedListener.java
deleted file mode 100644
index a8a32361..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IProblemChangedListener.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.resources.IResource;
-
-/**
- * Can be added to a ProblemMarkerManager to get notified about problem
- * marker changes. Used to update error ticks.
- */
-public interface IProblemChangedListener {
-
- /**
- * Called when problems changed. This call is posted in an aynch exec, therefore passed
- * resources must not exist.
- * @param changedResources A set with elements of type <code>IResource</code> that
- * describe the resources that had an problem change.
- * @param isMarkerChange If set to <code>true</code>, the change was a marker change, if
- * <code>false</code>, the change came from an annotation model modification.
- */
- void problemsChanged(IResource[] changedResources, boolean isMarkerChange);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IRichLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IRichLabelProvider.java
deleted file mode 100644
index 99eac362..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IRichLabelProvider.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-
-public interface IRichLabelProvider extends ILabelProvider {
-
- ColoredString getRichTextLabel(Object object);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ISelectionListenerWithAST.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ISelectionListenerWithAST.java
deleted file mode 100644
index e6b0b69c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ISelectionListenerWithAST.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- * Listener to be informed on text selection changes in an editor (post selection), including the corresponding AST.
- * The AST is shared and must not be modified.
- * Listeners can be registered in a <code>SelectionListenerWithASTManager</code>.
- */
-public interface ISelectionListenerWithAST {
-
- /**
- * Called when a selection has changed. The method is called in a post selection event in an background
- * thread.
- *
- * @param part The editor part in which the selection change has occurred.
- * @param selection The new text selection
- * @param astRoot The AST tree corresponding to the editor's input. This AST is shared and must
- * not be modified.
- */
- void selectionChanged(IEditorPart part, ITextSelection selection, JavaScriptUnit astRoot);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IViewPartInputProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IViewPartInputProvider.java
deleted file mode 100644
index 20d90c83..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/IViewPartInputProvider.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-/**
- * Interface common to all view parts that provide an input.
- */
-public interface IViewPartInputProvider {
-
- /**
- * Returns the input.
- *
- * @return the input object
- */
- public Object getViewPartInput();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDescriptorRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDescriptorRegistry.java
deleted file mode 100644
index 1447856e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDescriptorRegistry.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.HashMap;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * A registry that maps <code>ImageDescriptors</code> to <code>Image</code>.
- */
-public class ImageDescriptorRegistry {
-
- private HashMap fRegistry= new HashMap(10);
- private Display fDisplay;
-
- /**
- * Creates a new image descriptor registry for the current or default display,
- * respectively.
- */
- public ImageDescriptorRegistry() {
- this(SWTUtil.getStandardDisplay());
- }
-
- /**
- * Creates a new image descriptor registry for the given display. All images
- * managed by this registry will be disposed when the display gets disposed.
- *
- * @param display the display the images managed by this registry are allocated for
- */
- public ImageDescriptorRegistry(Display display) {
- fDisplay= display;
- Assert.isNotNull(fDisplay);
- hookDisplay();
- }
-
- /**
- * Returns the image associated with the given image descriptor.
- *
- * @param descriptor the image descriptor for which the registry manages an image,
- * or <code>null</code> for a missing image descriptor
- * @return the image associated with the image descriptor or <code>null</code>
- * if the image descriptor can't create the requested image.
- */
- public Image get(ImageDescriptor descriptor) {
- if (descriptor == null)
- descriptor= ImageDescriptor.getMissingImageDescriptor();
-
- Image result= (Image)fRegistry.get(descriptor);
- if (result != null)
- return result;
-
- Assert.isTrue(fDisplay == SWTUtil.getStandardDisplay(), "Allocating image for wrong display."); //$NON-NLS-1$
- result= descriptor.createImage();
- if (result != null)
- fRegistry.put(descriptor, result);
- return result;
- }
-
- /**
- * Disposes all images managed by this registry.
- */
- public void dispose() {
- for (Iterator iter= fRegistry.values().iterator(); iter.hasNext(); ) {
- Image image= (Image)iter.next();
- image.dispose();
- }
- fRegistry.clear();
- }
-
- private void hookDisplay() {
- fDisplay.disposeExec(new Runnable() {
- public void run() {
- dispose();
- }
- });
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDisposer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDisposer.java
deleted file mode 100644
index 4311b9b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageDisposer.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Image;
-
-
-/**
- * Helper class to manage images that should be disposed when a control is disposed
- * contol.addWidgetListener(new ImageDisposer(myImage));
- */
-public class ImageDisposer implements DisposeListener {
-
- private Image[] fImages;
-
- public ImageDisposer(Image image) {
- this(new Image[] { image });
- }
-
- public ImageDisposer(Image[] images) {
- Assert.isNotNull(images);
- fImages= images;
- }
-
- /*
- * @see WidgetListener#widgetDisposed
- */
- public void widgetDisposed(DisposeEvent e) {
- if (fImages != null) {
- for (int i= 0; i < fImages.length; i++) {
- fImages[i].dispose();
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageImageDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageImageDescriptor.java
deleted file mode 100644
index 9a05a79f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ImageImageDescriptor.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-
-/**
- */
-public class ImageImageDescriptor extends ImageDescriptor {
-
- private Image fImage;
-
- /**
- * Constructor for ImagImageDescriptor.
- */
- public ImageImageDescriptor(Image image) {
- super();
- fImage= image;
- }
-
- /* (non-Javadoc)
- * @see ImageDescriptor#getImageData()
- */
- public ImageData getImageData() {
- return fImage.getImageData();
- }
-
- /* (non-Javadoc)
- * @see Object#equals(Object)
- */
- public boolean equals(Object obj) {
- return (obj != null) && getClass().equals(obj.getClass()) && fImage.equals(((ImageImageDescriptor)obj).fImage);
- }
-
- /* (non-Javadoc)
- * @see Object#hashCode()
- */
- public int hashCode() {
- return fImage.hashCode();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java
deleted file mode 100644
index c765a834..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java
+++ /dev/null
@@ -1,399 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaWorkbenchAdapter;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-
-/**
- * Default strategy of the Java plugin for the construction of Java element icons.
- */
-public class JavaElementImageProvider {
-
- /**
- * Flags for the JavaImageLabelProvider:
- * Generate images with overlays.
- */
- public final static int OVERLAY_ICONS= 0x1;
-
- /**
- * Generate small sized images.
- */
- public final static int SMALL_ICONS= 0x2;
-
- /**
- * Use the 'light' style for rendering types.
- */
- public final static int LIGHT_TYPE_ICONS= 0x4;
-
-
- public static final Point SMALL_SIZE= new Point(16, 16);
- public static final Point BIG_SIZE= new Point(22, 16);
-
- private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED;
- private static ImageDescriptor DESC_OBJ_PROJECT;
- {
- ISharedImages images= JavaScriptPlugin.getDefault().getWorkbench().getSharedImages();
- DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED);
- DESC_OBJ_PROJECT= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT);
- }
-
- private ImageDescriptorRegistry fRegistry;
-
- public JavaElementImageProvider() {
- fRegistry= null; // lazy initialization
- }
-
- /**
- * Returns the icon for a given element. The icon depends on the element type
- * and element properties. If configured, overlay icons are constructed for
- * <code>ISourceReference</code>s.
- * @param flags Flags as defined by the JavaImageLabelProvider
- */
- public Image getImageLabel(Object element, int flags) {
- return getImageLabel(computeDescriptor(element, flags));
- }
-
- private Image getImageLabel(ImageDescriptor descriptor){
- if (descriptor == null)
- return null;
- return getRegistry().get(descriptor);
- }
-
- private ImageDescriptorRegistry getRegistry() {
- if (fRegistry == null) {
- fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
- }
- return fRegistry;
- }
-
-
- private ImageDescriptor computeDescriptor(Object element, int flags){
- if (element instanceof IJavaScriptElement) {
- return getJavaImageDescriptor((IJavaScriptElement) element, flags);
- } else if (element instanceof IFile) {
- IFile file= (IFile) element;
- if (JavaScriptCore.isJavaScriptLikeFileName(file.getName())) {
- return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path
- }
- return getWorkbenchImageDescriptor(file, flags);
- } else if (element instanceof IAdaptable) {
- return getWorkbenchImageDescriptor((IAdaptable) element, flags);
- }
- return null;
- }
-
- private static boolean showOverlayIcons(int flags) {
- return (flags & OVERLAY_ICONS) != 0;
- }
-
- private static boolean useSmallSize(int flags) {
- return (flags & SMALL_ICONS) != 0;
- }
-
- private static boolean useLightIcons(int flags) {
- return (flags & LIGHT_TYPE_ICONS) != 0;
- }
-
- /**
- * Returns an image descriptor for a compilation unit not on the class path.
- * The descriptor includes overlays, if specified.
- */
- public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) {
- Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
- return new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_OBJS_CUNIT_RESOURCE, 0, size);
- }
-
- /**
- * Returns an image descriptor for a java element. The descriptor includes overlays, if specified.
- */
- public ImageDescriptor getJavaImageDescriptor(IJavaScriptElement element, int flags) {
- Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
-
- ImageDescriptor baseDesc= getBaseImageDescriptor(element, flags);
- if (baseDesc != null) {
- int adornmentFlags= computeJavaAdornmentFlags(element, flags);
- return new JavaScriptElementImageDescriptor(baseDesc, adornmentFlags, size);
- }
- return new JavaScriptElementImageDescriptor(JavaPluginImages.DESC_OBJS_GHOST, 0, size);
- }
-
- /**
- * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply).
- * Returns <code>null</code> if no image could be found.
- */
- public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) {
- IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class);
- if (wbAdapter == null) {
- return null;
- }
- ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable);
- if (descriptor == null) {
- return null;
- }
-
- Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
- return new JavaScriptElementImageDescriptor(descriptor, 0, size);
- }
-
- // ---- Computation of base image key -------------------------------------------------
-
- /**
- * Returns an image descriptor for a java element. This is the base image, no overlays.
- */
- public ImageDescriptor getBaseImageDescriptor(IJavaScriptElement element, int renderFlags) {
-
- try {
- switch (element.getElementType()) {
- case IJavaScriptElement.INITIALIZER:
- return JavaPluginImages.DESC_MISC_PRIVATE; // 23479
- case IJavaScriptElement.METHOD: {
- IFunction method= (IFunction) element;
- IType declType= method.getDeclaringType();
- int flags= method.getFlags();
-// if (declType.isEnum() && isDefaultFlag(flags) && method.isConstructor())
-// return JavaPluginImages.DESC_MISC_PRIVATE;
- return getMethodImageDescriptor(false, flags);
- }
- case IJavaScriptElement.FIELD: {
- IMember member= (IMember) element;
- IType declType= member.getDeclaringType();
- return getFieldImageDescriptor(false, member.getFlags());
- }
- case IJavaScriptElement.LOCAL_VARIABLE:
- return JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE;
-
- case IJavaScriptElement.IMPORT_DECLARATION:
- return JavaPluginImages.DESC_OBJS_IMPDECL;
-
- case IJavaScriptElement.IMPORT_CONTAINER:
- return JavaPluginImages.DESC_OBJS_IMPCONT;
-
- case IJavaScriptElement.TYPE: {
- IType type= (IType) element;
-
- IType declType= type.getDeclaringType();
- boolean isInner= declType != null;
- return getTypeImageDescriptor(isInner, false, type.getFlags(), useLightIcons(renderFlags));
- }
-
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: {
- IPackageFragmentRoot root= (IPackageFragmentRoot) element;
- if (root.isArchive()) {
- IPath attach= root.getSourceAttachmentPath();
- if (root.isExternal()) {
- if (attach == null) {
- return JavaPluginImages.DESC_OBJS_EXTJAR;
- } else {
- return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC;
- }
- } else {
- if (attach == null) {
- return JavaPluginImages.DESC_OBJS_JAR;
- } else {
- return JavaPluginImages.DESC_OBJS_JAR_WSRC;
- }
- }
- } else {
- return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT;
- }
- }
-
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- return getPackageFragmentIcon(element, renderFlags);
-
-
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return JavaPluginImages.DESC_OBJS_CUNIT;
-
- case IJavaScriptElement.CLASS_FILE:
- /* this is too expensive for large packages
- try {
- IClassFile cfile= (IClassFile)element;
- if (cfile.isClass())
- return JavaPluginImages.IMG_OBJS_CFILECLASS;
- return JavaPluginImages.IMG_OBJS_CFILEINT;
- } catch(JavaScriptModelException e) {
- // fall through;
- }*/
- return JavaPluginImages.DESC_OBJS_CFILE;
-
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IJavaScriptProject jp= (IJavaScriptProject)element;
- if (jp.getProject().isOpen()) {
- IProject project= jp.getProject();
- IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class);
- if (adapter != null) {
- ImageDescriptor result= adapter.getImageDescriptor(project);
- if (result != null)
- return result;
- }
- return DESC_OBJ_PROJECT;
- }
- return DESC_OBJ_PROJECT_CLOSED;
-
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- return JavaPluginImages.DESC_OBJS_JAVA_MODEL;
-
- default:
- // ignore. Must be a new, yet unknown Java element
- // give an advanced IWorkbenchAdapter the chance
- IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) element.getAdapter(IWorkbenchAdapter.class);
- if (wbAdapter != null && !(wbAdapter instanceof JavaWorkbenchAdapter)) { // avoid recursion
- ImageDescriptor imageDescriptor= wbAdapter.getImageDescriptor(element);
- if (imageDescriptor != null) {
- return imageDescriptor;
- }
- }
- return JavaPluginImages.DESC_OBJS_GHOST;
- }
-
- } catch (JavaScriptModelException e) {
- if (e.isDoesNotExist())
- return JavaPluginImages.DESC_OBJS_UNKNOWN;
- JavaScriptPlugin.log(e);
- return JavaPluginImages.DESC_OBJS_GHOST;
- }
- }
-
-// private static boolean isDefaultFlag(int flags) {
-// return !Flags.isPublic(flags) && !Flags.isProtected(flags) && !Flags.isPrivate(flags);
-// }
-//
- protected ImageDescriptor getPackageFragmentIcon(IJavaScriptElement element, int renderFlags) throws JavaScriptModelException {
-// IPackageFragment fragment= (IPackageFragment)element;
-// boolean containsJavaElements= false;
-// try {
-// containsJavaElements= fragment.hasChildren();
-// } catch(JavaScriptModelException e) {
-// // assuming no children;
-// }
-// if(!containsJavaElements && (fragment.getNonJavaResources().length > 0))
-// return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES;
-// else if (!containsJavaElements)
-// return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE;
- return JavaPluginImages.DESC_OBJS_PACKAGE;
- }
-
- public void dispose() {
- }
-
- // ---- Methods to compute the adornments flags ---------------------------------
-
- private int computeJavaAdornmentFlags(IJavaScriptElement element, int renderFlags) {
- int flags= 0;
- if (showOverlayIcons(renderFlags) && element instanceof IMember) {
- try {
- IMember member= (IMember) element;
-
- if (element.getElementType() == IJavaScriptElement.METHOD && ((IFunction)element).isConstructor())
- flags |= JavaScriptElementImageDescriptor.CONSTRUCTOR;
-
- int modifiers= member.getFlags();
- if (Flags.isAbstract(modifiers) && confirmAbstract(member))
- flags |= JavaScriptElementImageDescriptor.ABSTRACT;
- if (Flags.isStatic(modifiers))
- flags |= JavaScriptElementImageDescriptor.STATIC;
-
- if (Flags.isDeprecated(modifiers))
- flags |= JavaScriptElementImageDescriptor.DEPRECATED;
- } catch (JavaScriptModelException e) {
- // do nothing. Can't compute runnable adornment or get flags
- }
- }
- return flags;
- }
-
- private static boolean confirmAbstract(IMember element) throws JavaScriptModelException {
- // never show the abstract symbol on interfaces or members in interfaces
- if (element.getElementType() == IJavaScriptElement.TYPE) {
- return true;
- }
- return true;
- }
-
- public static ImageDescriptor getMethodImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) {
- if (Flags.isPublic(flags) || isInInterfaceOrAnnotation)
- return JavaPluginImages.DESC_MISC_PUBLIC;
- if (Flags.isProtected(flags))
- return JavaPluginImages.DESC_MISC_PROTECTED;
- if (Flags.isPrivate(flags))
- return JavaPluginImages.DESC_MISC_PRIVATE;
-
- return JavaPluginImages.DESC_MISC_DEFAULT;
- }
-
- public static ImageDescriptor getFieldImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) {
- if (Flags.isPublic(flags) || isInInterfaceOrAnnotation)
- return JavaPluginImages.DESC_FIELD_PUBLIC;
- if (Flags.isProtected(flags))
- return JavaPluginImages.DESC_FIELD_PROTECTED;
- if (Flags.isPrivate(flags))
- return JavaPluginImages.DESC_FIELD_PRIVATE;
-
- return JavaPluginImages.DESC_FIELD_DEFAULT;
- }
-
- public static ImageDescriptor getTypeImageDescriptor(boolean isInner, boolean isInInterfaceOrAnnotation, int flags, boolean useLightIcons) {
- if (useLightIcons) {
- return JavaPluginImages.DESC_OBJS_CLASSALT;
- }
- if (isInner) {
- return getInnerClassImageDescriptor(isInInterfaceOrAnnotation, flags);
- }
- return getClassImageDescriptor(flags);
-
- }
-
-
- public static Image getDecoratedImage(ImageDescriptor baseImage, int adornments, Point size) {
- return JavaScriptPlugin.getImageDescriptorRegistry().get(new JavaScriptElementImageDescriptor(baseImage, adornments, size));
- }
-
-
- private static ImageDescriptor getClassImageDescriptor(int flags) {
- if (Flags.isPublic(flags) || Flags.isPrivate(flags))
- return JavaPluginImages.DESC_OBJS_CLASS;
- else
- return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT;
- }
-
- private static ImageDescriptor getInnerClassImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) {
- if (Flags.isPublic(flags) || isInInterfaceOrAnnotation)
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC;
- else if (Flags.isPrivate(flags))
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE;
- else
- return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaUILabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaUILabelProvider.java
deleted file mode 100644
index ff6e8340..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaUILabelProvider.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class JavaUILabelProvider implements ILabelProvider, IColorProvider, IRichLabelProvider {
-
- protected ListenerList fListeners = new ListenerList();
-
- protected JavaElementImageProvider fImageLabelProvider;
- protected StorageLabelProvider fStorageLabelProvider;
-
- private ArrayList fLabelDecorators;
-
- private int fImageFlags;
- private long fTextFlags;
-
- /**
- * Creates a new label provider with default flags.
- */
- public JavaUILabelProvider() {
- this(JavaScriptElementLabels.ALL_DEFAULT, JavaElementImageProvider.OVERLAY_ICONS);
- }
-
- /**
- * @param textFlags Flags defined in <code>JavaScriptElementLabels</code>.
- * @param imageFlags Flags defined in <code>JavaElementImageProvider</code>.
- */
- public JavaUILabelProvider(long textFlags, int imageFlags) {
- fImageLabelProvider= new JavaElementImageProvider();
- fLabelDecorators= null;
-
- fStorageLabelProvider= new StorageLabelProvider();
- fImageFlags= imageFlags;
- fTextFlags= textFlags;
- }
-
- /**
- * Adds a decorator to the label provider
- * @param decorator the decorator to add
- */
- public void addLabelDecorator(ILabelDecorator decorator) {
- if (fLabelDecorators == null) {
- fLabelDecorators= new ArrayList(2);
- }
- fLabelDecorators.add(decorator);
- }
-
- /**
- * Sets the textFlags.
- * @param textFlags The textFlags to set
- */
- public final void setTextFlags(long textFlags) {
- fTextFlags= textFlags;
- }
-
- /**
- * Sets the imageFlags
- * @param imageFlags The imageFlags to set
- */
- public final void setImageFlags(int imageFlags) {
- fImageFlags= imageFlags;
- }
-
- /**
- * Gets the image flags.
- * Can be overwritten by super classes.
- * @return Returns a int
- */
- public final int getImageFlags() {
- return fImageFlags;
- }
-
- /**
- * Gets the text flags.
- * @return Returns a int
- */
- public final long getTextFlags() {
- return fTextFlags;
- }
-
- /**
- * Evaluates the image flags for a element.
- * Can be overwritten by super classes.
- * @param element the element to compute the image flags for
- * @return Returns a int
- */
- protected int evaluateImageFlags(Object element) {
- return getImageFlags();
- }
-
- /**
- * Evaluates the text flags for a element. Can be overwritten by super classes.
- * @param element the element to compute the text flags for
- * @return Returns a int
- */
- protected long evaluateTextFlags(Object element) {
- return getTextFlags();
- }
-
- protected Image decorateImage(Image image, Object element) {
- if (fLabelDecorators != null && image != null) {
- for (int i= 0; i < fLabelDecorators.size(); i++) {
- ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
- image= decorator.decorateImage(image, element);
- }
- }
- return image;
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getImage
- */
- public Image getImage(Object element) {
- Image result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element));
- if (result == null && (element instanceof IStorage)) {
- result= fStorageLabelProvider.getImage(element);
- }
-
- return decorateImage(result, element);
- }
-
- protected String decorateText(String text, Object element) {
- if (fLabelDecorators != null && text.length() > 0) {
- for (int i= 0; i < fLabelDecorators.size(); i++) {
- ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
- String decorated= decorator.decorateText(text, element);
- if (decorated != null) {
- text= decorated;
- }
- }
- }
- return text;
- }
-
-
- /* (non-Javadoc)
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- String result= JavaScriptElementLabels.getTextLabel(element, evaluateTextFlags(element));
- if (result.length() == 0 && (element instanceof IStorage)) {
- result= fStorageLabelProvider.getText(element);
- }
- return decorateText(result, element);
- }
-
- public ColoredString getRichTextLabel(Object element) {
- ColoredString string= ColoredJavaElementLabels.getTextLabel(element, evaluateTextFlags(element) | ColoredJavaElementLabels.COLORIZE);
- if (string.length() == 0 && (element instanceof IStorage)) {
- string= new ColoredString(fStorageLabelProvider.getText(element));
- }
- String decorated= decorateText(string.getString(), element);
- if (decorated != null) {
- return ColoredJavaElementLabels.decorateColoredString(string, decorated, ColoredJavaElementLabels.DECORATIONS_STYLE);
- }
- return string;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#dispose
- */
- public void dispose() {
- if (fLabelDecorators != null) {
- for (int i= 0; i < fLabelDecorators.size(); i++) {
- ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
- decorator.dispose();
- }
- fLabelDecorators= null;
- }
- fStorageLabelProvider.dispose();
- fImageLabelProvider.dispose();
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#addListener(ILabelProviderListener)
- */
- public void addListener(ILabelProviderListener listener) {
- if (fLabelDecorators != null) {
- for (int i= 0; i < fLabelDecorators.size(); i++) {
- ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
- decorator.addListener(listener);
- }
- }
- fListeners.add(listener);
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#isLabelProperty(Object, String)
- */
- public boolean isLabelProperty(Object element, String property) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
- */
- public void removeListener(ILabelProviderListener listener) {
- if (fLabelDecorators != null) {
- for (int i= 0; i < fLabelDecorators.size(); i++) {
- ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
- decorator.removeListener(listener);
- }
- }
- fListeners.remove(listener);
- }
-
- public static ILabelDecorator[] getDecorators(boolean errortick, ILabelDecorator extra) {
- if (errortick) {
- if (extra == null) {
- return new ILabelDecorator[] {};
- } else {
- return new ILabelDecorator[] { extra };
- }
- }
- if (extra != null) {
- return new ILabelDecorator[] { extra };
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- return null;
- }
-
- /**
- * Fires a label provider changed event to all registered listeners
- * Only listeners registered at the time this method is called are notified.
- *
- * @param event a label provider changed event
- *
- * @see ILabelProviderListener#labelProviderChanged
- */
- protected void fireLabelProviderChanged(final LabelProviderChangedEvent event) {
- Object[] listeners = fListeners.getListeners();
- for (int i = 0; i < listeners.length; ++i) {
- final ILabelProviderListener l = (ILabelProviderListener) listeners[i];
- SafeRunner.run(new SafeRunnable() {
- public void run() {
- l.labelProviderChanged(event);
- }
- });
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaViewerFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaViewerFilter.java
deleted file mode 100644
index 8478ebaf..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaViewerFilter.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-/**
- * filter with a live cycle
- */
-public abstract class JavaViewerFilter extends ViewerFilter {
-
- private int fCount= 0;
-
- /**
- * To be overridden by implement
- */
- protected abstract void initFilter();
-
- protected abstract void freeFilter();
-
- public final void filteringStart() {
- if (fCount == 0)
- initFilter();
- fCount++;
- }
-
- public final void filteringEnd() {
- fCount--;
- if (fCount == 0)
- freeFilter();
- }
-
- /*
- * Overrides method from ViewerFilter
- */
- public Object[] filter(Viewer viewer, Object parent, Object[] elements) {
- try {
- filteringStart();
- return super.filter(viewer, parent, elements);
- } finally {
- filteringEnd();
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LabelProviderDisposer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LabelProviderDisposer.java
deleted file mode 100644
index 3030628e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LabelProviderDisposer.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-
-/**
- * Helper class to manage images that should be disposed when a control is disposed
- * contol.addWidgetListener(new LabelProviderDisposer(myLabelProvider));
- */
-public class LabelProviderDisposer implements DisposeListener {
-
- private ILabelProvider fLabelProvider;
-
- public LabelProviderDisposer(ILabelProvider labelProvider) {
- fLabelProvider= labelProvider;
- }
-
- public void widgetDisposed(DisposeEvent e) {
- fLabelProvider.dispose();
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LibraryFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LibraryFilter.java
deleted file mode 100644
index 35e9aaca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/LibraryFilter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-
-/**
- * Filters out all elements which libraries
- */
-public class LibraryFilter extends ViewerFilter {
-
- /**
- * Returns the result of this filter, when applied to the
- * given inputs.
- *
- * @return Returns true if element should be included in filtered set
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragmentRoot)
- return !((IPackageFragmentRoot)element).isArchive();
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilter.java
deleted file mode 100644
index 791464a3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilter.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * Filter for the methods viewer.
- * Changing a filter property does not trigger a refiltering of the viewer
- */
-public class MemberFilter extends ViewerFilter {
-
- public static final int FILTER_NONPUBLIC= 1;
- public static final int FILTER_STATIC= 2;
- public static final int FILTER_FIELDS= 4;
- public static final int FILTER_LOCALTYPES= 8;
-
- private int fFilterProperties;
-
-
- /**
- * Modifies filter and add a property to filter for
- */
- public final void addFilter(int filter) {
- fFilterProperties |= filter;
- }
- /**
- * Modifies filter and remove a property to filter for
- */
- public final void removeFilter(int filter) {
- fFilterProperties &= (-1 ^ filter);
- }
- /**
- * Tests if a property is filtered
- */
- public final boolean hasFilter(int filter) {
- return (fFilterProperties & filter) != 0;
- }
-
- /*
- * @see ViewerFilter#isFilterProperty(java.lang.Object, java.lang.String)
- */
- public boolean isFilterProperty(Object element, Object property) {
- return false;
- }
- /*
- * @see ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- try {
- if (element instanceof IMember) {
- IMember member= (IMember) element;
- int memberType= member.getElementType();
-
- if (hasFilter(FILTER_FIELDS) && memberType == IJavaScriptElement.FIELD) {
- return false;
- }
-
- if (hasFilter(FILTER_LOCALTYPES) && memberType == IJavaScriptElement.TYPE && isLocalType((IType) member)) {
- return false;
- }
-
- if (member.getElementName().startsWith("<")) { // filter out <clinit> //$NON-NLS-1$
- return false;
- }
- int flags= member.getFlags();
- if (hasFilter(FILTER_STATIC) && (Flags.isStatic(flags)) && memberType != IJavaScriptElement.TYPE) {
- return false;
- }
- if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) && !isTopLevelType(member)) {
- return false;
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- }
- return true;
- }
-
- private boolean isLocalType(IType type) {
- IJavaScriptElement parent= type.getParent();
- return parent instanceof IMember && !(parent instanceof IType);
- }
-
- private boolean isTopLevelType(IMember member) {
-// IType parent= member.getDeclaringType();
-// return parent == null;
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilterAction.java
deleted file mode 100644
index cc78db71..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/MemberFilterAction.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.ui.actions.MemberFilterActionGroup;
-
-/**
- * Action used to enable / disable method filter properties
- */
-public class MemberFilterAction extends Action {
-
- private int fFilterProperty;
- private MemberFilterActionGroup fFilterActionGroup;
-
- public MemberFilterAction(MemberFilterActionGroup actionGroup, String title, int property, String contextHelpId, boolean initValue) {
- super(title);
- fFilterActionGroup= actionGroup;
- fFilterProperty= property;
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, contextHelpId);
-
- setChecked(initValue);
- }
-
- /**
- * Returns this action's filter property.
- */
- public int getFilterProperty() {
- return fFilterProperty;
- }
-
- /*
- * @see Action#actionPerformed
- */
- public void run() {
- fFilterActionGroup.setMemberFilter(fFilterProperty, isChecked());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/OwnerDrawSupport.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/OwnerDrawSupport.java
deleted file mode 100644
index 9c6e62e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/OwnerDrawSupport.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.Iterator;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.graphics.TextLayout;
-import org.eclipse.swt.graphics.TextStyle;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.TreeItem;
-
-/**
- * Adding owner draw support to a control
- */
-public abstract class OwnerDrawSupport implements Listener {
-
- private TextLayout fTextLayout;
- private final Control fControl;
-
- public OwnerDrawSupport(Control control) {
- fControl= control;
- fTextLayout= new TextLayout(control.getDisplay());
-
- control.addListener(SWT.PaintItem, this);
- control.addListener(SWT.EraseItem, this);
- control.addListener(SWT.Dispose, this);
- }
-
- /**
- * Return the colored label for the given item.
- * @param item the item to return the colored label for
- * @return the colored string
- */
- public abstract ColoredString getColoredLabel(Item item);
-
- /**
- * Return the color for the given style
- * @param foregroundColorName the name of the color
- * @param display the current display
- * @return the color
- */
- public abstract Color getColor(String foregroundColorName, Display display);
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
- */
- public void handleEvent(Event event) {
- if (event.type == SWT.PaintItem) {
- performPaint(event);
- } else if (event.type == SWT.EraseItem) {
- performErase(event);
- } else if (event.type == SWT.Dispose) {
- dispose();
- }
- }
-
- private void performErase(Event event) {
- event.detail &= ~SWT.FOREGROUND;
- }
-
- private void performPaint(Event event) {
- Item item= (Item) event.item;
- GC gc= event.gc;
-
- ColoredString coloredLabel= getColoredLabel(item);
- boolean isSelected= (event.detail & SWT.SELECTED) != 0 && fControl.isFocusControl();
- if (item instanceof TreeItem) {
- TreeItem treeItem= (TreeItem) item;
- Image image = treeItem.getImage(event.index);
- if (image != null) {
- processImage(image, gc, treeItem.getImageBounds(event.index));
- }
- Rectangle textBounds= treeItem.getTextBounds(event.index);
- Font font= treeItem.getFont(event.index);
- processColoredLabel(coloredLabel, gc, textBounds, isSelected, font);
-
- Rectangle bounds= treeItem.getBounds();
- if ((event.detail & SWT.FOCUSED) != 0) {
- gc.drawFocus(bounds.x, bounds.y, bounds.width, bounds.height);
- }
- } else if (item instanceof TableItem) {
- TableItem tableItem= (TableItem) item;
- Image image = tableItem.getImage(event.index);
- if (image != null) {
- processImage(image, gc, tableItem.getImageBounds(event.index));
- }
- Rectangle textBounds= tableItem.getTextBounds(event.index);
- Font font= tableItem.getFont(event.index);
- processColoredLabel(coloredLabel, gc, textBounds, isSelected, font);
-
- Rectangle bounds= tableItem.getBounds();
- if ((event.detail & SWT.FOCUSED) != 0) {
- gc.drawFocus(bounds.x, bounds.y, bounds.width, bounds.height);
- }
- }
- }
-
- private void processImage(Image image, GC gc, Rectangle imageBounds) {
- Rectangle bounds= image.getBounds();
- int x= imageBounds.x + Math.max(0, (imageBounds.width - bounds.width) / 2);
- int y= imageBounds.y + Math.max(0, (imageBounds.height - bounds.height) / 2);
- gc.drawImage(image, x, y);
- }
-
- private void processColoredLabel(ColoredString richLabel, GC gc, Rectangle textBounds, boolean isSelected, Font font) {
- String text= richLabel.getString();
- fTextLayout.setText(text);
- fTextLayout.setFont(font);
-
- if (!isSelected) {
- // apply the styled ranges only when element is not selected
- Display display= (Display) gc.getDevice();
- Iterator ranges= richLabel.getRanges();
- while (ranges.hasNext()) {
- ColoredString.StyleRange curr= (ColoredString.StyleRange) ranges.next();
- ColoredString.Style style= curr.style;
- if (style != null) {
- Color foreground= getColor(style.getForegroundColorName(), display);
- TextStyle textStyle= new TextStyle(null, foreground, null);
- fTextLayout.setStyle(textStyle, curr.offset, curr.offset + curr.length - 1);
- }
- }
- }
-
- Rectangle bounds= fTextLayout.getBounds();
- int x= textBounds.x;
- int y = textBounds.y + Math.max(0, (textBounds.height - bounds.height) / 2);
-
- fTextLayout.draw(gc, x, y);
- fTextLayout.setText(""); // clear all ranges //$NON-NLS-1$
- }
-
- public void dispose() {
- if (fTextLayout != null) {
- fTextLayout.dispose();
- fTextLayout= null;
- }
- if (!fControl.isDisposed()) {
- fControl.removeListener(SWT.PaintItem, this);
- fControl.removeListener(SWT.EraseItem, this);
- fControl.removeListener(SWT.Dispose, this);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemMarkerManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemMarkerManager.java
deleted file mode 100644
index 5da9aaa4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemMarkerManager.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-
-import java.util.HashSet;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.text.source.AnnotationModelEvent;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.IAnnotationModelListener;
-import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitAnnotationModelEvent;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * Listens to resource deltas and filters for marker changes of type IMarker.PROBLEM
- * Viewers showing error ticks should register as listener to
- * this type.
- */
-public class ProblemMarkerManager implements IResourceChangeListener, IAnnotationModelListener , IAnnotationModelListenerExtension {
-
- /**
- * Visitors used to look if the element change delta contains a marker change.
- */
- private static class ProjectErrorVisitor implements IResourceDeltaVisitor {
-
- private HashSet fChangedElements;
-
- public ProjectErrorVisitor(HashSet changedElements) {
- fChangedElements= changedElements;
- }
-
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource res= delta.getResource();
- if (res instanceof IProject && delta.getKind() == IResourceDelta.CHANGED) {
- IProject project= (IProject) res;
- if (!project.isAccessible()) {
- // only track open Java projects
- return false;
- }
- }
- checkInvalidate(delta, res);
- return true;
- }
-
- private void checkInvalidate(IResourceDelta delta, IResource resource) {
- int kind= delta.getKind();
- if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) {
- // invalidate the resource and all parents
- while (resource.getType() != IResource.ROOT && fChangedElements.add(resource)) {
- resource= resource.getParent();
- }
- }
- }
-
- private boolean isErrorDelta(IResourceDelta delta) {
- if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) {
- IMarkerDelta[] markerDeltas= delta.getMarkerDeltas();
- for (int i= 0; i < markerDeltas.length; i++) {
- if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) {
- int kind= markerDeltas[i].getKind();
- if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)
- return true;
- int severity= markerDeltas[i].getAttribute(IMarker.SEVERITY, -1);
- int newSeverity= markerDeltas[i].getMarker().getAttribute(IMarker.SEVERITY, -1);
- if (newSeverity != severity)
- return true;
- }
- }
- }
- return false;
- }
- }
-
- private ListenerList fListeners;
-
-
- public ProblemMarkerManager() {
- fListeners= new ListenerList();
- }
-
- /*
- * @see IResourceChangeListener#resourceChanged
- */
- public void resourceChanged(IResourceChangeEvent event) {
- HashSet changedElements= new HashSet();
-
- try {
- IResourceDelta delta= event.getDelta();
- if (delta != null)
- delta.accept(new ProjectErrorVisitor(changedElements));
- } catch (CoreException e) {
- JavaScriptPlugin.log(e.getStatus());
- }
-
- if (!changedElements.isEmpty()) {
- IResource[] changes= (IResource[]) changedElements.toArray(new IResource[changedElements.size()]);
- fireChanges(changes, true);
- }
- }
-
- /* (non-Javadoc)
- * @see IAnnotationModelListener#modelChanged(IAnnotationModel)
- */
- public void modelChanged(IAnnotationModel model) {
- // no action
- }
-
- /* (non-Javadoc)
- * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
- */
- public void modelChanged(AnnotationModelEvent event) {
- if (event instanceof CompilationUnitAnnotationModelEvent) {
- CompilationUnitAnnotationModelEvent cuEvent= (CompilationUnitAnnotationModelEvent) event;
- if (cuEvent.includesProblemMarkerAnnotationChanges()) {
- IResource[] changes= new IResource[] { cuEvent.getUnderlyingResource() };
- fireChanges(changes, false);
- }
- }
- }
-
-
- /**
- * Adds a listener for problem marker changes.
- */
- public void addListener(IProblemChangedListener listener) {
- if (fListeners.isEmpty()) {
- JavaScriptPlugin.getWorkspace().addResourceChangeListener(this);
- JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().addGlobalAnnotationModelListener(this);
- }
- fListeners.add(listener);
- }
-
- /**
- * Removes a <code>IProblemChangedListener</code>.
- */
- public void removeListener(IProblemChangedListener listener) {
- fListeners.remove(listener);
- if (fListeners.isEmpty()) {
- JavaScriptPlugin.getWorkspace().removeResourceChangeListener(this);
- JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().removeGlobalAnnotationModelListener(this);
- }
- }
-
- private void fireChanges(final IResource[] changes, final boolean isMarkerChange) {
- Display display= SWTUtil.getStandardDisplay();
- if (display != null && !display.isDisposed()) {
- display.asyncExec(new Runnable() {
- public void run() {
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- IProblemChangedListener curr= (IProblemChangedListener) listeners[i];
- curr.problemsChanged(changes, isMarkerChange);
- }
- }
- });
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTableViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTableViewer.java
deleted file mode 100644
index ca7e260c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTableViewer.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyProvider;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
-
-/**
- * Extends a TableViewer to allow more performance when showing error ticks.
- * A <code>ProblemItemMapper</code> is contained that maps all items in
- * the tree to underlying resource
- */
-public class ProblemTableViewer extends TableViewer implements ResourceToItemsMapper.IContentViewerAccessor {
-
- protected ResourceToItemsMapper fResourceToItemsMapper;
-
- /**
- * Constructor for ProblemTableViewer.
- * @param parent
- */
- public ProblemTableViewer(Composite parent) {
- super(parent);
- initMapper();
- }
-
- /**
- * Constructor for ProblemTableViewer.
- * @param parent
- * @param style
- */
- public ProblemTableViewer(Composite parent, int style) {
- super(parent, style);
- initMapper();
- }
-
- /**
- * Constructor for ProblemTableViewer.
- * @param table
- */
- public ProblemTableViewer(Table table) {
- super(table);
- initMapper();
- }
-
- private void initMapper() {
- fResourceToItemsMapper= new ResourceToItemsMapper(this);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.ResourceToItemsMapper.IContentViewerAccessor#doUpdateItem(org.eclipse.swt.widgets.Widget)
- */
- public void doUpdateItem(Widget item) {
- doUpdateItem(item, item.getData(), true);
- }
-
- /*
- * @see StructuredViewer#mapElement(Object, Widget)
- */
- protected void mapElement(Object element, Widget item) {
- super.mapElement(element, item);
- if (item instanceof Item) {
- fResourceToItemsMapper.addToMap(element, (Item) item);
- }
- }
-
- /*
- * @see StructuredViewer#unmapElement(Object, Widget)
- */
- protected void unmapElement(Object element, Widget item) {
- if (item instanceof Item) {
- fResourceToItemsMapper.removeFromMap(element, (Item) item);
- }
- super.unmapElement(element, item);
- }
-
- /*
- * @see StructuredViewer#unmapAllElements()
- */
- protected void unmapAllElements() {
- fResourceToItemsMapper.clearMap();
- super.unmapAllElements();
- }
-
- /*
- * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
- */
- protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
- if (event instanceof ProblemsLabelChangedEvent) {
- ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
- if (!e.isMarkerChange() && canIgnoreChangesFromAnnotionModel()) {
- return;
- }
- }
-
- Object[] changed= event.getElements();
- if (changed != null && !fResourceToItemsMapper.isEmpty()) {
- ArrayList others= new ArrayList(changed.length);
- for (int i= 0; i < changed.length; i++) {
- Object curr= changed[i];
- if (curr instanceof IResource) {
- fResourceToItemsMapper.resourceChanged((IResource) curr);
- } else {
- others.add(curr);
- }
- }
- if (others.isEmpty()) {
- return;
- }
- event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray());
- }
- super.handleLabelProviderChanged(event);
- }
-
- /**
- * Answers whether this viewer can ignore label provider changes resulting from
- * marker changes in annotation models
- */
- private boolean canIgnoreChangesFromAnnotionModel() {
- Object contentProvider= getContentProvider();
- return contentProvider instanceof IWorkingCopyProvider && !((IWorkingCopyProvider)contentProvider).providesWorkingCopies();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTreeViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTreeViewer.java
deleted file mode 100644
index 5a24af78..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProblemTreeViewer.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.ui.IWorkingCopyProvider;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
-
-
-/**
- * Extends a TreeViewer to allow more performance when showing error ticks.
- * A <code>ProblemItemMapper</code> is contained that maps all items in
- * the tree to underlying resource
- */
-public class ProblemTreeViewer extends TreeViewer implements ResourceToItemsMapper.IContentViewerAccessor {
-
- protected ResourceToItemsMapper fResourceToItemsMapper;
-
- /*
- * @see TreeViewer#TreeViewer(Composite)
- */
- public ProblemTreeViewer(Composite parent) {
- super(parent);
- initMapper();
- }
-
- /*
- * @see TreeViewer#TreeViewer(Composite, int)
- */
- public ProblemTreeViewer(Composite parent, int style) {
- super(parent, style);
- initMapper();
- }
-
- /*
- * @see TreeViewer#TreeViewer(Tree)
- */
- public ProblemTreeViewer(Tree tree) {
- super(tree);
- initMapper();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.ResourceToItemsMapper.IContentViewerAccessor#doUpdateItem(org.eclipse.swt.widgets.Widget)
- */
- public void doUpdateItem(Widget item) {
- doUpdateItem(item, item.getData(), true);
- }
-
- private void initMapper() {
- fResourceToItemsMapper= new ResourceToItemsMapper(this);
- }
-
-
- /*
- * @see StructuredViewer#mapElement(Object, Widget)
- */
- protected void mapElement(Object element, Widget item) {
- super.mapElement(element, item);
- if (item instanceof Item) {
- fResourceToItemsMapper.addToMap(element, (Item) item);
- }
- }
-
- /*
- * @see StructuredViewer#unmapElement(Object, Widget)
- */
- protected void unmapElement(Object element, Widget item) {
- if (item instanceof Item) {
- fResourceToItemsMapper.removeFromMap(element, (Item) item);
- }
- super.unmapElement(element, item);
- }
-
- /*
- * @see StructuredViewer#unmapAllElements()
- */
- protected void unmapAllElements() {
- fResourceToItemsMapper.clearMap();
- super.unmapAllElements();
- }
-
-
- // ---------------- filter sessions ----------------------------
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(org.eclipse.jface.viewers.ViewerFilter)
- */
- public void addFilter(ViewerFilter filter) {
- if (filter instanceof JavaViewerFilter) {
- ((JavaViewerFilter) filter).filteringStart();
- }
- super.addFilter(filter);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#removeFilter(org.eclipse.jface.viewers.ViewerFilter)
- */
- public void removeFilter(ViewerFilter filter) {
- super.removeFilter(filter);
- if (filter instanceof JavaViewerFilter) {
- ((JavaViewerFilter) filter).filteringEnd();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#setFilters(org.eclipse.jface.viewers.ViewerFilter[])
- */
- public void setFilters(ViewerFilter[] filters) {
- ViewerFilter[] oldFilters= getFilters();
- for (int i= 0; i < filters.length; i++) {
- ViewerFilter curr= filters[i];
- if (curr instanceof JavaViewerFilter && !findAndRemove(oldFilters, curr)) {
- ((JavaViewerFilter) curr).filteringStart();
- }
- }
- endFilterSessions(oldFilters);
- super.setFilters(filters);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#resetFilters()
- */
- public void resetFilters() {
- endFilterSessions(getFilters());
- super.resetFilters();
- }
-
- private boolean findAndRemove(ViewerFilter[] filters, ViewerFilter filter) {
- for (int i= 0; i < filters.length; i++) {
- if (filters[i] == filter) {
- filters[i]= null;
- return true;
- }
- }
- return false;
- }
-
- private void endFilterSessions(ViewerFilter[] filters) {
- for (int i= 0; i < filters.length; i++) {
- ViewerFilter curr= filters[i];
- if (curr instanceof JavaViewerFilter) {
- ((JavaViewerFilter) curr).filteringEnd();
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#handleDispose(org.eclipse.swt.events.DisposeEvent)
- */
- protected void handleDispose(DisposeEvent event) {
- endFilterSessions(getFilters());
- super.handleDispose(event);
- }
-
-
- /*
- * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
- */
- protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
- if (event instanceof ProblemsLabelChangedEvent) {
- ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
- if (!e.isMarkerChange() && canIgnoreChangesFromAnnotionModel()) {
- return;
- }
- }
- Object[] changed= addAditionalProblemParents(event.getElements());
-
- if (changed != null && !fResourceToItemsMapper.isEmpty()) {
- ArrayList others= new ArrayList();
- for (int i= 0; i < changed.length; i++) {
- Object curr= changed[i];
- if (curr instanceof IResource) {
- fResourceToItemsMapper.resourceChanged((IResource) curr);
- } else {
- others.add(curr);
- }
- }
- if (others.isEmpty()) {
- return;
- }
- event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray());
- } else {
- // we have modified the list of changed elements via add additional parents.
- if (event.getElements() != changed)
- event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), changed);
- }
- super.handleLabelProviderChanged(event);
- }
-
- /**
- * Answers whether this viewer can ignore label provider changes resulting from
- * marker changes in annotation models
- * @return return <code>true</code> if annotation model marker changes can be ignored
- */
- private boolean canIgnoreChangesFromAnnotionModel() {
- Object contentProvider= getContentProvider();
- return contentProvider instanceof IWorkingCopyProvider && !((IWorkingCopyProvider)contentProvider).providesWorkingCopies();
- }
-
-
- /**
- * Decides if {@link #isExpandable(Object)} should also test filters. The default behaviour is to
- * do this only for IMembers. Implementors can replace this behaviour.
- * @param parent the given element
- * @return returns if if {@link #isExpandable(Object)} should also test filters for the given element.
- */
- protected boolean evaluateExpandableWithFilters(Object parent) {
- return parent instanceof IMember;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object)
- */
- public boolean isExpandable(Object parent) {
- if (hasFilters() && evaluateExpandableWithFilters(parent)) {
- // workaround for 65762
- return hasFilteredChildren(parent);
- }
- return super.isExpandable(parent);
- }
-
- protected final boolean hasFilteredChildren(Object parent) {
- Object[] rawChildren= getRawChildren(parent);
- return containsNonFiltered(rawChildren, parent);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.AbstractTreeViewer#getFilteredChildren(java.lang.Object)
- */
- protected final Object[] getFilteredChildren(Object parent) {
- return filter(getRawChildren(parent), parent);
- }
-
- private Object[] filter(Object[] elements, Object parent) {
- if (!hasFilters() || elements.length == 0) {
- return elements;
- }
- List list= new ArrayList(elements.length);
- ViewerFilter[] filters = getFilters();
- for (int i = 0; i < elements.length; i++) {
- Object object = elements[i];
- if (!isFiltered(object, parent, filters)) {
- list.add(object);
- }
- }
- return list.toArray();
- }
-
- private boolean containsNonFiltered(Object[] elements, Object parent) {
- if (elements.length == 0) {
- return false;
- }
- if (!hasFilters()) {
- return true;
- }
- ViewerFilter[] filters = getFilters();
- for (int i = 0; i < elements.length; i++) {
- Object object = elements[i];
- if (!isFiltered(object, parent, filters)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * All element filter tests must go through this method.
- * Can be overridden by subclasses.
- *
- * @param object the object to filter
- * @param parent the parent
- * @param filters the filters to apply
- * @return true if the element is filtered
- */
- protected boolean isFiltered(Object object, Object parent, ViewerFilter[] filters) {
- for (int i = 0; i < filters.length; i++) {
- ViewerFilter filter = filters[i];
- if (!filter.select(this, parent, object))
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object[])
- */
- protected final Object[] filter(Object[] elements) {
- return filter(elements, getRoot());
- }
-
- protected Object[] addAditionalProblemParents(Object[] elements) {
- return elements;
- }
-
- /**
- * Public method to test if a element is filtered by the views active filters
- * @param object the element to test for
- * @param parent the parent element
- * @return return <code>true if the element is filtered</code>
- */
- public boolean isFiltered(Object object, Object parent) {
- return isFiltered(object, parent, getFilters());
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProjectTemplateStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProjectTemplateStore.java
deleted file mode 100644
index b015bef8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ProjectTemplateStore.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
-import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter;
-import org.eclipse.jface.text.templates.persistence.TemplateStore;
-import org.eclipse.ui.preferences.ScopedPreferenceStore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- *
- */
-public final class ProjectTemplateStore {
-
- private static final String KEY= "org.eclipse.wst.jsdt.ui.text.custom_code_templates"; //$NON-NLS-1$
-
- private final TemplateStore fInstanceStore;
- private final TemplateStore fProjectStore;
-
- public ProjectTemplateStore(IProject project) {
- fInstanceStore= JavaScriptPlugin.getDefault().getCodeTemplateStore();
- if (project == null) {
- fProjectStore= null;
- } else {
- final ScopedPreferenceStore projectSettings= new ScopedPreferenceStore(new ProjectScope(project), JavaScriptUI.ID_PLUGIN);
- fProjectStore= new TemplateStore(projectSettings, KEY) {
- /*
- * Make sure we keep the id of added code templates - add removes
- * it in the usual add() method
- */
- public void add(TemplatePersistenceData data) {
- internalAdd(data);
- }
-
- public void save() throws IOException {
-
- StringWriter output= new StringWriter();
- TemplateReaderWriter writer= new TemplateReaderWriter();
- writer.save(getTemplateData(false), output);
-
- projectSettings.setValue(KEY, output.toString());
- projectSettings.save();
- }
- };
- }
- }
-
- public static boolean hasProjectSpecificTempates(IProject project) {
- String pref= new ProjectScope(project).getNode(JavaScriptUI.ID_PLUGIN).get(KEY, null);
- if (pref != null && pref.trim().length() > 0) {
- Reader input= new StringReader(pref);
- TemplateReaderWriter reader= new TemplateReaderWriter();
- TemplatePersistenceData[] datas;
- try {
- datas= reader.read(input);
- return datas.length > 0;
- } catch (IOException e) {
- // ignore
- }
- }
- return false;
- }
-
-
- public TemplatePersistenceData[] getTemplateData() {
- if (fProjectStore != null) {
- return fProjectStore.getTemplateData(true);
- } else {
- return fInstanceStore.getTemplateData(true);
- }
- }
-
- public Template findTemplateById(String id) {
- Template template= null;
- if (fProjectStore != null)
- template= fProjectStore.findTemplateById(id);
- if (template == null)
- template= fInstanceStore.findTemplateById(id);
-
- return template;
- }
-
- public void load() throws IOException {
- if (fProjectStore != null) {
- fProjectStore.load();
-
- Set datas= new HashSet();
- TemplatePersistenceData[] data= fProjectStore.getTemplateData(false);
- for (int i= 0; i < data.length; i++) {
- datas.add(data[i].getId());
- }
-
- data= fInstanceStore.getTemplateData(false);
- for (int i= 0; i < data.length; i++) {
- TemplatePersistenceData orig= data[i];
- if (!datas.contains(orig.getId())) {
- TemplatePersistenceData copy= new TemplatePersistenceData(new Template(orig.getTemplate()), orig.isEnabled(), orig.getId());
- fProjectStore.add(copy);
- copy.setDeleted(true);
- }
- }
- }
- }
-
- public boolean isProjectSpecific(String id) {
- if (id == null) {
- return false;
- }
-
- if (fProjectStore == null)
- return false;
-
- return fProjectStore.findTemplateById(id) != null;
- }
-
-
- public void setProjectSpecific(String id, boolean projectSpecific) {
- Assert.isNotNull(fProjectStore);
-
- TemplatePersistenceData data= fProjectStore.getTemplateData(id);
- if (data == null) {
- return; // does not exist
- } else {
- data.setDeleted(!projectSpecific);
- }
- }
-
- public void restoreDefaults() {
- if (fProjectStore == null) {
- fInstanceStore.restoreDefaults();
- } else {
- fProjectStore.restoreDefaults();
- }
- }
-
- public void save() throws IOException {
- if (fProjectStore == null) {
- fInstanceStore.save();
- } else {
- fProjectStore.save();
- }
- }
-
- public void revertChanges() throws IOException {
- if (fProjectStore != null) {
- // nothing to do
- } else {
- fInstanceStore.load();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ResourceToItemsMapper.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ResourceToItemsMapper.java
deleted file mode 100644
index f43f97e0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ResourceToItemsMapper.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Stack;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * Helper class for updating error markers and other decorators that work on resources.
- * Items are mapped to their element's underlying resource.
- * Method <code>resourceChanged</code> updates all items that are affected from the changed
- * elements.
- */
-public class ResourceToItemsMapper {
-
- public static interface IContentViewerAccessor {
- public void doUpdateItem(Widget item);
- }
-
-
- private static final int NUMBER_LIST_REUSE= 10;
-
- // map from resource to item
- private HashMap fResourceToItem;
- private Stack fReuseLists;
-
- private IContentViewerAccessor fContentViewerAccess;
-
- public ResourceToItemsMapper(IContentViewerAccessor viewer) {
- fResourceToItem= new HashMap();
- fReuseLists= new Stack();
-
- fContentViewerAccess= viewer;
- }
-
- /**
- * Must be called from the UI thread.
- * @param changedResource Changed resource
- */
- public void resourceChanged(IResource changedResource) {
- Object obj= fResourceToItem.get(changedResource);
- if (obj == null) {
- // not mapped
- } else if (obj instanceof Item) {
- updateItem((Item) obj);
- } else { // List of Items
- List list= (List) obj;
- for (int k= 0; k < list.size(); k++) {
- updateItem((Item) list.get(k));
- }
- }
- }
-
- private void updateItem(Item item) {
- if (!item.isDisposed()) {
- fContentViewerAccess.doUpdateItem(item);
- }
- }
-
- /**
- * Adds a new item to the map.
- * @param element Element to map
- * @param item The item used for the element
- */
- public void addToMap(Object element, Item item) {
- IResource resource= getCorrespondingResource(element);
- if (resource != null) {
- Object existingMapping= fResourceToItem.get(resource);
- if (existingMapping == null) {
- fResourceToItem.put(resource, item);
- } else if (existingMapping instanceof Item) {
- if (existingMapping != item) {
- List list= getNewList();
- list.add(existingMapping);
- list.add(item);
- fResourceToItem.put(resource, list);
- }
- } else { // List
- List list= (List) existingMapping;
- if (!list.contains(item)) {
- list.add(item);
- }
- }
- }
- }
-
- /**
- * Removes an element from the map.
- * @param element The data element
- * @param item The table or tree item
- */
- public void removeFromMap(Object element, Item item) {
- IResource resource= getCorrespondingResource(element);
- if (resource != null) {
- Object existingMapping= fResourceToItem.get(resource);
- if (existingMapping == null) {
- return;
- } else if (existingMapping instanceof Item) {
- fResourceToItem.remove(resource);
- } else { // List
- List list= (List) existingMapping;
- list.remove(item);
- if (list.isEmpty()) {
- fResourceToItem.remove(list);
- releaseList(list);
- }
- }
- }
- }
-
- private List getNewList() {
- if (!fReuseLists.isEmpty()) {
- return (List) fReuseLists.pop();
- }
- return new ArrayList(2);
- }
-
- private void releaseList(List list) {
- if (fReuseLists.size() < NUMBER_LIST_REUSE) {
- fReuseLists.push(list);
- }
- }
-
- /**
- * Clears the map.
- */
- public void clearMap() {
- fResourceToItem.clear();
- }
-
- /**
- * Tests if the map is empty
- * @return Returns if there are mappings
- */
- public boolean isEmpty() {
- return fResourceToItem.isEmpty();
- }
-
- /**
- * Method that decides which elements can have error markers
- * Returns null if an element can not have error markers.
- * @param element The input element
- * @return Returns the corresponding resource or null
- */
- private static IResource getCorrespondingResource(Object element) {
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) element;
- IResource res= elem.getResource();
- if (res == null) {
- IJavaScriptUnit cu= (IJavaScriptUnit) elem.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- // elements in compilation units are mapped to the underlying resource of the original cu
- res= cu.getResource();
- }
- }
- return res;
- } else if (element instanceof IResource) {
- return (IResource) element;
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java
deleted file mode 100644
index 7dfbc57a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-
-/**
- * Infrastructure to share an AST for editor post selection listeners.
- */
-public class SelectionListenerWithASTManager {
-
- private static SelectionListenerWithASTManager fgDefault;
-
- /**
- * @return Returns the default manager instance.
- */
- public static SelectionListenerWithASTManager getDefault() {
- if (fgDefault == null) {
- fgDefault= new SelectionListenerWithASTManager();
- }
- return fgDefault;
- }
-
-
- private final static class PartListenerGroup {
- private ITextEditor fPart;
- private ISelectionListener fPostSelectionListener;
- private ISelectionChangedListener fSelectionListener;
- private Job fCurrentJob;
- private ListenerList fAstListeners;
- /**
- * Lock to avoid having more than one calculateAndInform job in parallel.
- * Only jobs may synchronize on this as otherwise deadlocks are possible.
- */
- private final Object fJobLock= new Object();
-
- public PartListenerGroup(ITextEditor editorPart) {
- fPart= editorPart;
- fCurrentJob= null;
- fAstListeners= new ListenerList(ListenerList.IDENTITY);
-
- fSelectionListener= new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection= event.getSelection();
- if (selection instanceof ITextSelection) {
- fireSelectionChanged((ITextSelection) selection);
- }
- }
- };
-
- fPostSelectionListener= new ISelectionListener() {
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (part == fPart && selection instanceof ITextSelection)
- firePostSelectionChanged((ITextSelection) selection);
- }
- };
- }
-
- public boolean isEmpty() {
- return fAstListeners.isEmpty();
- }
-
- public void install(ISelectionListenerWithAST listener) {
- if (isEmpty()) {
- fPart.getEditorSite().getPage().addPostSelectionListener(fPostSelectionListener);
- ISelectionProvider selectionProvider= fPart.getSelectionProvider();
- if (selectionProvider != null)
- selectionProvider.addSelectionChangedListener(fSelectionListener);
- }
- fAstListeners.add(listener);
- }
-
- public void uninstall(ISelectionListenerWithAST listener) {
- fAstListeners.remove(listener);
- if (isEmpty()) {
- fPart.getEditorSite().getPage().removePostSelectionListener(fPostSelectionListener);
- ISelectionProvider selectionProvider= fPart.getSelectionProvider();
- if (selectionProvider != null)
- selectionProvider.removeSelectionChangedListener(fSelectionListener);
- }
- }
-
- public void fireSelectionChanged(final ITextSelection selection) {
- if (fCurrentJob != null) {
- fCurrentJob.cancel();
- }
- }
-
- public void firePostSelectionChanged(final ITextSelection selection) {
- if (fCurrentJob != null) {
- fCurrentJob.cancel();
- }
- final IJavaScriptElement input= EditorUtility.getEditorInputJavaElement(fPart, false);
- if (input == null) {
- return;
- }
-
- fCurrentJob= new Job(JavaUIMessages.SelectionListenerWithASTManager_job_title) {
- public IStatus run(IProgressMonitor monitor) {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- synchronized (fJobLock) {
- return calculateASTandInform(input, selection, monitor);
- }
- }
- };
- fCurrentJob.setPriority(Job.DECORATE);
- fCurrentJob.setSystem(true);
- fCurrentJob.schedule();
- }
-
- protected IStatus calculateASTandInform(IJavaScriptElement input, ITextSelection selection, IProgressMonitor monitor) {
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- // create AST
- try {
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(input, ASTProvider.WAIT_ACTIVE_ONLY, monitor);
-
- if (astRoot != null && !monitor.isCanceled()) {
- Object[] listeners;
- synchronized (PartListenerGroup.this) {
- listeners= fAstListeners.getListeners();
- }
- for (int i= 0; i < listeners.length; i++) {
- ((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection, astRoot);
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- }
- return Status.OK_STATUS;
- }
- } catch (OperationCanceledException e) {
- // thrown when canceling the AST creation
- }
- return Status.CANCEL_STATUS;
- }
- }
-
-
- private Map fListenerGroups;
-
- private SelectionListenerWithASTManager() {
- fListenerGroups= new HashMap();
- }
-
- /**
- * Registers a selection listener for the given editor part.
- * @param part The editor part to listen to.
- * @param listener The listener to register.
- */
- public void addListener(ITextEditor part, ISelectionListenerWithAST listener) {
- synchronized (this) {
- PartListenerGroup partListener= (PartListenerGroup) fListenerGroups.get(part);
- if (partListener == null) {
- partListener= new PartListenerGroup(part);
- fListenerGroups.put(part, partListener);
- }
- partListener.install(listener);
- }
- }
-
- /**
- * Unregisters a selection listener.
- * @param part The editor part the listener was registered.
- * @param listener The listener to unregister.
- */
- public void removeListener(ITextEditor part, ISelectionListenerWithAST listener) {
- synchronized (this) {
- PartListenerGroup partListener= (PartListenerGroup) fListenerGroups.get(part);
- if (partListener != null) {
- partListener.uninstall(listener);
- if (partListener.isEmpty()) {
- fListenerGroups.remove(part);
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionProviderMediator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionProviderMediator.java
deleted file mode 100644
index e40a4e72..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionProviderMediator.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.viewers.IPostSelectionProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Widget;
-
-/**
- * A selection provider for view parts with more that one viewer.
- * Tracks the focus of the viewers to provide the correct selection.
- */
-public class SelectionProviderMediator implements IPostSelectionProvider {
-
- private class InternalListener implements ISelectionChangedListener, FocusListener {
- /*
- * @see ISelectionChangedListener#selectionChanged
- */
- public void selectionChanged(SelectionChangedEvent event) {
- doSelectionChanged(event);
- }
-
- /*
- * @see FocusListener#focusGained
- */
- public void focusGained(FocusEvent e) {
- doFocusChanged(e.widget);
- }
-
- /*
- * @see FocusListener#focusLost
- */
- public void focusLost(FocusEvent e) {
- // do not reset due to focus behavior on GTK
- //fViewerInFocus= null;
- }
- }
-
- private class InternalPostSelectionListener implements ISelectionChangedListener {
- public void selectionChanged(SelectionChangedEvent event) {
- doPostSelectionChanged(event);
- }
-
- }
-
- private StructuredViewer[] fViewers;
-
- private StructuredViewer fViewerInFocus;
- private ListenerList fSelectionChangedListeners;
- private ListenerList fPostSelectionChangedListeners;
-
- /**
- * @param viewers All viewers that can provide a selection
- * @param viewerInFocus the viewer currently in focus or <code>null</code>
- */
- public SelectionProviderMediator(StructuredViewer[] viewers, StructuredViewer viewerInFocus) {
- Assert.isNotNull(viewers);
- fViewers= viewers;
- InternalListener listener= new InternalListener();
- fSelectionChangedListeners= new ListenerList();
- fPostSelectionChangedListeners= new ListenerList();
- fViewerInFocus= viewerInFocus;
-
- for (int i= 0; i < fViewers.length; i++) {
- StructuredViewer viewer= fViewers[i];
- viewer.addSelectionChangedListener(listener);
- viewer.addPostSelectionChangedListener(new InternalPostSelectionListener());
- Control control= viewer.getControl();
- control.addFocusListener(listener);
- }
- }
-
- private void doFocusChanged(Widget control) {
- for (int i= 0; i < fViewers.length; i++) {
- if (fViewers[i].getControl() == control) {
- propagateFocusChanged(fViewers[i]);
- return;
- }
- }
- }
-
- final void doPostSelectionChanged(SelectionChangedEvent event) {
- ISelectionProvider provider= event.getSelectionProvider();
- if (provider == fViewerInFocus) {
- firePostSelectionChanged();
- }
- }
-
- final void doSelectionChanged(SelectionChangedEvent event) {
- ISelectionProvider provider= event.getSelectionProvider();
- if (provider == fViewerInFocus) {
- fireSelectionChanged();
- }
- }
-
- final void propagateFocusChanged(StructuredViewer viewer) {
- if (viewer != fViewerInFocus) { // OK to compare by identity
- fViewerInFocus= viewer;
- fireSelectionChanged();
- firePostSelectionChanged();
- }
- }
-
- private void fireSelectionChanged() {
- if (fSelectionChangedListeners != null) {
- SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection());
-
- Object[] listeners= fSelectionChangedListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i];
- listener.selectionChanged(event);
- }
- }
- }
-
- private void firePostSelectionChanged() {
- if (fPostSelectionChangedListeners != null) {
- SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection());
-
- Object[] listeners= fPostSelectionChangedListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i];
- listener.selectionChanged(event);
- }
- }
- }
-
- /*
- * @see ISelectionProvider#addSelectionChangedListener
- */
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- fSelectionChangedListeners.add(listener);
- }
-
- /*
- * @see ISelectionProvider#removeSelectionChangedListener
- */
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- fSelectionChangedListeners.remove(listener);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
- fPostSelectionChangedListeners.add(listener);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
- */
- public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
- fPostSelectionChangedListeners.remove(listener);
- }
-
- /*
- * @see ISelectionProvider#getSelection
- */
- public ISelection getSelection() {
- if (fViewerInFocus != null) {
- return fViewerInFocus.getSelection();
- }
- return StructuredSelection.EMPTY;
- }
-
- /*
- * @see ISelectionProvider#setSelection
- */
- public void setSelection(ISelection selection) {
- if (fViewerInFocus != null) {
- fViewerInFocus.setSelection(selection);
- }
- }
-
- public void setSelection(ISelection selection, boolean reveal) {
- if (fViewerInFocus != null) {
- fViewerInFocus.setSelection(selection, reveal);
- }
- }
-
- /**
- * Returns the viewer in focus or null if no viewer has the focus
- */
- public StructuredViewer getViewerInFocus() {
- return fViewerInFocus;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SourcePositionComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SourcePositionComparator.java
deleted file mode 100644
index 0e4bf704..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SourcePositionComparator.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-
-/**
- * Viewer sorter which sorts the Java elements like
- * they appear in the source.
- *
- *
- */
-public class SourcePositionComparator extends ViewerComparator {
-
- /*
- * @see org.eclipse.jface.viewers.ViewerSorter#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public int compare(Viewer viewer, Object e1, Object e2) {
- if (!(e1 instanceof ISourceReference))
- return 0;
- if (!(e2 instanceof ISourceReference))
- return 0;
-
- IJavaScriptElement parent1= ((IJavaScriptElement)e1).getParent();
- if (parent1 == null || !parent1.equals(((IJavaScriptElement)e2).getParent())) {
- IType t1= getOutermostDeclaringType(e1);
- if (t1 == null)
- return 0;
-
- IType t2= getOutermostDeclaringType(e2);
- try {
- if (!t1.equals(t2)) {
- if (t2 == null)
- return 0;
-
- if (Flags.isPublic(t1.getFlags()) && Flags.isPublic(t2.getFlags()))
- return 0;
-
- if (!t1.getPackageFragment().equals(t2.getPackageFragment()))
- return 0;
-
- IJavaScriptUnit cu1= (IJavaScriptUnit)((IJavaScriptElement)e1).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu1 != null) {
- if (!cu1.equals(((IJavaScriptElement)e2).getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT)))
- return 0;
- } else {
- IClassFile cf1= (IClassFile)((IJavaScriptElement)e1).getAncestor(IJavaScriptElement.CLASS_FILE);
- if (cf1 == null)
- return 0;
- IClassFile cf2= (IClassFile)((IJavaScriptElement)e2).getAncestor(IJavaScriptElement.CLASS_FILE);
- String source1= cf1.getSource();
- if (source1 != null && !source1.equals(cf2.getSource()))
- return 0;
- }
- }
- } catch (JavaScriptModelException e3) {
- return 0;
- }
- }
-
- try {
- ISourceRange sr1= ((ISourceReference)e1).getSourceRange();
- ISourceRange sr2= ((ISourceReference)e2).getSourceRange();
- if (sr1 == null || sr2 == null)
- return 0;
-
- return sr1.getOffset() - sr2.getOffset();
-
- } catch (JavaScriptModelException e) {
- return 0;
- }
- }
-
- private IType getOutermostDeclaringType(Object element) {
- if (!(element instanceof IMember))
- return null;
-
- IType declaringType;
- if (element instanceof IType)
- declaringType= (IType)element;
- else {
- declaringType= ((IMember)element).getDeclaringType();
- if (declaringType == null)
- return null;
- }
-
- IType declaringTypeDeclaringType= declaringType.getDeclaringType();
- while (declaringTypeDeclaringType != null) {
- declaringType= declaringTypeDeclaringType;
- declaringTypeDeclaringType= declaringType.getDeclaringType();
- }
- return declaringType;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StatusBarUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StatusBarUpdater.java
deleted file mode 100644
index c68eb1cb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StatusBarUpdater.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * Add the <code>StatusBarUpdater</code> to your ViewPart to have the statusbar
- * describing the selected elements.
- */
-public class StatusBarUpdater implements ISelectionChangedListener {
-
- private final long LABEL_FLAGS= JavaScriptElementLabels.DEFAULT_QUALIFIED | JavaScriptElementLabels.ROOT_POST_QUALIFIED | JavaScriptElementLabels.APPEND_ROOT_PATH |
- JavaScriptElementLabels.M_PARAMETER_TYPES | JavaScriptElementLabels.M_PARAMETER_NAMES | JavaScriptElementLabels.M_APP_RETURNTYPE | JavaScriptElementLabels.M_EXCEPTIONS |
- JavaScriptElementLabels.F_APP_TYPE_SIGNATURE | JavaScriptElementLabels.T_TYPE_PARAMETERS;
-
- private IStatusLineManager fStatusLineManager;
-
- public StatusBarUpdater(IStatusLineManager statusLineManager) {
- fStatusLineManager= statusLineManager;
- }
-
- /*
- * @see ISelectionChangedListener#selectionChanged
- */
- public void selectionChanged(SelectionChangedEvent event) {
- String statusBarMessage= formatMessage(event.getSelection());
- fStatusLineManager.setMessage(statusBarMessage);
- }
-
-
- protected String formatMessage(ISelection sel) {
- if (sel instanceof IStructuredSelection && !sel.isEmpty()) {
- IStructuredSelection selection= (IStructuredSelection) sel;
-
- int nElements= selection.size();
- if (nElements > 1) {
- return Messages.format(JavaUIMessages.StatusBarUpdater_num_elements_selected, String.valueOf(nElements));
- } else {
- Object elem= selection.getFirstElement();
- if (elem instanceof IJavaScriptElement) {
- return formatJavaElementMessage((IJavaScriptElement) elem);
- } else if (elem instanceof IResource) {
- return formatResourceMessage((IResource) elem);
- } else if (elem instanceof PackageFragmentRootContainer) {
- PackageFragmentRootContainer container= (PackageFragmentRootContainer) elem;
- return container.getLabel() + JavaScriptElementLabels.CONCAT_STRING + container.getJavaProject().getElementName();
- } else if (elem instanceof IJarEntryResource) {
- IJarEntryResource jarEntryResource= (IJarEntryResource) elem;
- StringBuffer buf= new StringBuffer(jarEntryResource.getName());
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- IPath fullPath= jarEntryResource.getFullPath();
- if (fullPath.segmentCount() > 1) {
- buf.append(fullPath.removeLastSegments(1).makeRelative());
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- }
- JavaScriptElementLabels.getPackageFragmentRootLabel(jarEntryResource.getPackageFragmentRoot(), JavaScriptElementLabels.ROOT_POST_QUALIFIED, buf);
- return buf.toString();
- } else if (elem instanceof IAdaptable) {
- IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)elem).getAdapter(IWorkbenchAdapter.class);
- if (wbadapter != null) {
- return wbadapter.getLabel(elem);
- }
- }
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- private String formatJavaElementMessage(IJavaScriptElement element) {
- return JavaScriptElementLabels.getElementLabel(element, LABEL_FLAGS);
- }
-
- private String formatResourceMessage(IResource element) {
- IContainer parent= element.getParent();
- if (parent != null && parent.getType() != IResource.ROOT)
- return element.getName() + JavaScriptElementLabels.CONCAT_STRING + parent.getFullPath().makeRelative().toString();
- else
- return element.getName();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StorageLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StorageLabelProvider.java
deleted file mode 100644
index a0bda001..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/StorageLabelProvider.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorRegistry;
-import org.eclipse.ui.IFileEditorMapping;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-
-/**
- * Standard label provider for IStorage objects.
- * Use this class when you want to present IStorage objects in a viewer.
- */
-public class StorageLabelProvider extends LabelProvider {
-
- private IEditorRegistry fEditorRegistry= null;
- private Map fJarImageMap= new HashMap(10);
- private Image fDefaultImage;
-
- private IEditorRegistry getEditorRegistry() {
- if (fEditorRegistry == null)
- fEditorRegistry= PlatformUI.getWorkbench().getEditorRegistry();
- return fEditorRegistry;
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getImage
- */
- public Image getImage(Object element) {
- if (element instanceof IStorage)
- return getImageForJarEntry((IStorage)element);
-
- return super.getImage(element);
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- if (element instanceof IStorage) {
- return ((IStorage)element).getName();
- }
- return super.getText(element);
- }
-
- /* (non-Javadoc)
- *
- * @see IBaseLabelProvider#dispose
- */
- public void dispose() {
- if (fJarImageMap != null) {
- Iterator each= fJarImageMap.values().iterator();
- while (each.hasNext()) {
- Image image= (Image)each.next();
- image.dispose();
- }
- fJarImageMap= null;
- }
- fDefaultImage= null;
- }
-
- /*
- * Gets and caches an image for a JarEntryFile.
- * The image for a JarEntryFile is retrieved from the EditorRegistry.
- */
- private Image getImageForJarEntry(IStorage element) {
- if (element instanceof IJarEntryResource && !((IJarEntryResource) element).isFile()) {
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
- }
-
- if (fJarImageMap == null)
- return getDefaultImage();
-
- if (element == null || element.getName() == null)
- return getDefaultImage();
-
- // Try to find icon for full name
- String name= element.getName();
- Image image= (Image)fJarImageMap.get(name);
- if (image != null)
- return image;
- IFileEditorMapping[] mappings= getEditorRegistry().getFileEditorMappings();
- int i= 0;
- while (i < mappings.length) {
- if (mappings[i].getLabel().equals(name))
- break;
- i++;
- }
- String key= name;
- if (i == mappings.length) {
- // Try to find icon for extension
- IPath path= element.getFullPath();
- if (path == null)
- return getDefaultImage();
- key= path.getFileExtension();
- if (key == null)
- return getDefaultImage();
- image= (Image)fJarImageMap.get(key);
- if (image != null)
- return image;
- }
-
- // Get the image from the editor registry
- ImageDescriptor desc= getEditorRegistry().getImageDescriptor(name);
- image= desc.createImage();
-
- fJarImageMap.put(key, image);
-
- return image;
- }
-
- private Image getDefaultImage() {
- if (fDefaultImage == null)
- fDefaultImage= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
- return fDefaultImage;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/TreeHierarchyLayoutProblemsDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/TreeHierarchyLayoutProblemsDecorator.java
deleted file mode 100644
index 1ad7a78a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/TreeHierarchyLayoutProblemsDecorator.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator;
-
-/**
- * Special problem decorator for hierarchical package layout.
- * <p>
- * It only decorates package fragments which are not covered by the
- * <code>ProblemsLabelDecorator</code>.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator
- *
- */
-public class TreeHierarchyLayoutProblemsDecorator extends ProblemsLabelDecorator {
-
- private boolean fIsFlatLayout;
-
- public TreeHierarchyLayoutProblemsDecorator() {
- this(false);
- }
-
- public TreeHierarchyLayoutProblemsDecorator(boolean isFlatLayout) {
- super(null);
- fIsFlatLayout= isFlatLayout;
- }
-
- protected int computePackageAdornmentFlags(IPackageFragment fragment) {
- if (!fIsFlatLayout && !fragment.isDefaultPackage()) {
- return super.computeAdornmentFlags(fragment.getResource());
- }
- return super.computeAdornmentFlags(fragment);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.ProblemsLabelDecorator#computeAdornmentFlags(java.lang.Object)
- */
- protected int computeAdornmentFlags(Object element) {
- if (element instanceof IPackageFragment) {
- return computePackageAdornmentFlags((IPackageFragment) element);
- } else if (element instanceof LogicalPackage) {
- IPackageFragment[] fragments= ((LogicalPackage) element).getFragments();
- int res= 0;
- for (int i= 0; i < fragments.length; i++) {
- int flags= computePackageAdornmentFlags(fragments[i]);
- if (flags == JavaScriptElementImageDescriptor.ERROR) {
- return flags;
- } else if (flags != 0) {
- res= flags;
- }
- }
- return res;
- }
- return super.computeAdornmentFlags(element);
- }
-
- public void setIsFlatLayout(boolean state) {
- fIsFlatLayout= state;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ViewHistory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ViewHistory.java
deleted file mode 100644
index 8e0a692e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/ViewHistory.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.viewsupport;
-
-import java.util.List;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Shell;
-
-
-/**
- *
- */
-public abstract class ViewHistory {
-
- /**
- * Configure the history List action.
- * Clients typically want to set a text and an image.
- *
- * @param action the action
- */
- public abstract void configureHistoryListAction(IAction action);
-
- /**
- * Configure the history drop down action.
- * Clients typically want to set a tooltip and an image.
- *
- * @param action the action
- */
- public abstract void configureHistoryDropDownAction(IAction action);
-
- /**
- * @return action to clear history entries, or <code>null</code>
- */
- public abstract Action getClearAction();
-
- public abstract String getHistoryListDialogTitle();
-
- public abstract String getHistoryListDialogMessage();
-
- public abstract Shell getShell();
-
-
- /**
- * @return An unmodifiable list of history entries, can be empty. The list
- * is sorted by age, youngest first.
- */
- public abstract List getHistoryEntries();
-
- /**
- * @return the active entry from the history
- */
- public abstract Object getCurrentEntry();
-
- /**
- * @param entry the entry to activate, or <code>null</code> if none should be active
- */
- public abstract void setActiveEntry(Object entry);
-
- /**
- * @param remainingEntries all the remaining history entries, can be empty
- * @param activeEntry the entry to activate, or <code>null</code> if none should be active
- */
- public abstract void setHistoryEntries(List remainingEntries, Object activeEntry);
-
- /**
- * @param element the element to render
- * @return the image descriptor for the given element, or <code>null</code>
- */
- public abstract ImageDescriptor getImageDescriptor(Object element);
-
- /**
- * @param element the element to render
- * @return the label text for the given element
- */
- public abstract String getText(Object element);
-
- /**
- * @return a history drop down action, ready for inclusion in a view toolbar
- */
- public final IAction createHistoryDropDownAction() {
- return new HistoryDropDownAction(this);
- }
-
- public abstract void addMenuEntries(MenuManager manager);
-
- public abstract String getMaxEntriesMessage();
- public abstract int getMaxEntries();
- public abstract void setMaxEntries(int maxEntries);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/ClassPathDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/ClassPathDetector.java
deleted file mode 100644
index 8ab53c61..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/ClassPathDetector.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceProxy;
-import org.eclipse.core.resources.IResourceProxyVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-import com.ibm.icu.text.Collator;
-
-public class ClassPathDetector implements IResourceProxyVisitor {
-
- private HashMap fSourceFolders;
- private IProject fProject;
- private IIncludePathEntry[] fResultClasspath;
- private IProgressMonitor fMonitor;
-
- private static class CPSorter implements Comparator {
- private Collator fCollator= Collator.getInstance();
- public int compare(Object o1, Object o2) {
- IIncludePathEntry e1= (IIncludePathEntry) o1;
- IIncludePathEntry e2= (IIncludePathEntry) o2;
- return fCollator.compare(e1.getPath().toString(), e2.getPath().toString());
- }
- }
-
- public ClassPathDetector(IProject project, IProgressMonitor monitor) throws CoreException {
- fSourceFolders= new HashMap();
- fProject= project;
- fResultClasspath= null;
-
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
-
- detectClasspath(monitor);
- }
-
- /**
- * Method detectClasspath.
- * @param monitor The progress monitor (not null)
- * @throws CoreException
- */
- private void detectClasspath(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(NewWizardMessages.ClassPathDetector_operation_description, 4);
-
- fMonitor= monitor;
- fProject.accept(this, IResource.NONE);
- monitor.worked(1);
-
- ArrayList cpEntries= new ArrayList();
-
- detectSourceFolders(cpEntries);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- monitor.worked(1);
-
- if (cpEntries.isEmpty()) {
- return;
- }
-
- IIncludePathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
- for (int i= 0; i < jreEntries.length; i++) {
- cpEntries.add(jreEntries[i]);
- }
-
- IIncludePathEntry[] entries= (IIncludePathEntry[]) cpEntries.toArray(new IIncludePathEntry[cpEntries.size()]);
- if (!JavaScriptConventions.validateClasspath(JavaScriptCore.create(fProject), entries).isOK()) {
- return;
- }
-
- fResultClasspath= entries;
- } finally {
- monitor.done();
- }
- }
-
- private void detectSourceFolders(ArrayList resEntries) {
- ArrayList res= new ArrayList();
- Set sourceFolderSet= fSourceFolders.keySet();
- for (Iterator iter= sourceFolderSet.iterator(); iter.hasNext();) {
- IPath path= (IPath) iter.next();
- ArrayList excluded= new ArrayList();
- for (Iterator inner= sourceFolderSet.iterator(); inner.hasNext();) {
- IPath other= (IPath) inner.next();
- if (!path.equals(other) && path.isPrefixOf(other)) {
- IPath pathToExclude= other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
- excluded.add(pathToExclude);
- }
- }
- IPath[] excludedPaths= (IPath[]) excluded.toArray(new IPath[excluded.size()]);
- IIncludePathEntry entry= JavaScriptCore.newSourceEntry(path, excludedPaths);
- res.add(entry);
- }
- Collections.sort(res, new CPSorter());
- resEntries.addAll(res);
- }
-
- private void visitCompilationUnit(IFile file) {
- IJavaScriptUnit cu= JavaScriptCore.createCompilationUnitFrom(file);
- if (cu != null) {
- IJavaScriptUnit workingCopy= null;
- try {
- workingCopy= cu.getWorkingCopy(null);
- IPath relPath= getPackagePath(workingCopy.getSource());
- IPath packPath= file.getParent().getFullPath();
- String cuName= file.getName();
- if (relPath == null) {
- addToMap(fSourceFolders, packPath, new Path(cuName));
- } else {
- IPath folderPath= getFolderPath(packPath, relPath);
- if (folderPath != null) {
- addToMap(fSourceFolders, folderPath, relPath.append(cuName));
- }
- }
- } catch (JavaScriptModelException e) {
- // ignore
- } catch (InvalidInputException e) {
- // ignore
- } finally {
- if (workingCopy != null) {
- try {
- workingCopy.discardWorkingCopy();
- } catch (JavaScriptModelException ignore) {
- }
- }
- }
- }
- }
-
- private IPath getPackagePath(String source) throws InvalidInputException {
- IScanner scanner= ToolFactory.createScanner(false, false, false, false);
- scanner.setSource(source.toCharArray());
- scanner.resetTo(0, source.length() - 1);
- int tok= scanner.getNextToken();
- if (tok != ITerminalSymbols.TokenNamepackage) {
- return null;
- }
- IPath res= Path.EMPTY;
- do {
- tok= scanner.getNextToken();
- if (tok == ITerminalSymbols.TokenNameIdentifier) {
- res= res.append(new String(scanner.getCurrentTokenSource()));
- } else {
- return res;
- }
- tok= scanner.getNextToken();
- } while (tok == ITerminalSymbols.TokenNameDOT);
-
- return res;
- }
-
-
- private void addToMap(HashMap map, IPath folderPath, IPath relPath) {
- List list= (List) map.get(folderPath);
- if (list == null) {
- list= new ArrayList(50);
- map.put(folderPath, list);
- }
- list.add(relPath);
- }
-
- private IPath getFolderPath(IPath packPath, IPath relpath) {
- int remainingSegments= packPath.segmentCount() - relpath.segmentCount();
- if (remainingSegments >= 0) {
- IPath common= packPath.removeFirstSegments(remainingSegments);
- if (common.equals(relpath)) {
- return packPath.uptoSegment(remainingSegments);
- }
- }
- return null;
- }
-
- private boolean isValidCUName(String name) {
- return !JavaScriptConventions.validateCompilationUnitName(name).matches(IStatus.ERROR);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
- */
- public boolean visit(IResourceProxy proxy) {
- if (fMonitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- if (proxy.getType() == IResource.FILE) {
- String name= proxy.getName();
- if (isValidCUName(name))
- visitCompilationUnit((IFile) proxy.requestResource());
- return false;
- }
- return true;
- }
-
- public IIncludePathEntry[] getClasspath() {
- if (fResultClasspath == null)
- return new IIncludePathEntry[0];
- return fResultClasspath;
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/IStatusChangeListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/IStatusChangeListener.java
deleted file mode 100644
index 2c1eac75..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/IStatusChangeListener.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.core.runtime.IStatus;
-
-public interface IStatusChangeListener {
-
- /**
- * Notifies this listener that the given status has changed.
- *
- * @param status the new status
- */
- void statusChanged(IStatus status);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizard.java
deleted file mode 100644
index 1eee3fbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizard.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExecutableExtension;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerPart;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.JavaWorkingSetUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.ViewActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetConfigurationBlock;
-
-public class JavaProjectWizard extends NewElementWizard implements IExecutableExtension {
-
- private JavaProjectWizardFirstPage fFirstPage;
- private JavaProjectWizardSecondPage fSecondPage;
-
- private IConfigurationElement fConfigElement;
-
- public JavaProjectWizard() {
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ);
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- setWindowTitle(NewWizardMessages.JavaProjectWizard_title);
- }
-
- /*
- * @see Wizard#addPages
- */
- public void addPages() {
- super.addPages();
- fFirstPage= new JavaProjectWizardFirstPage();
- fFirstPage.setWorkingSets(getWorkingSets(getSelection()));
- addPage(fFirstPage);
- fSecondPage= new JavaProjectWizardSecondPage(fFirstPage);
- addPage(fSecondPage);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
- fSecondPage.performFinish(monitor); // use the full progress monitor
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.IWizard#performFinish()
- */
- public boolean performFinish() {
- boolean res= super.performFinish();
- if (res) {
- final IJavaScriptElement newElement= getCreatedElement();
-
- IWorkingSet[] workingSets= fFirstPage.getWorkingSets();
- WorkingSetConfigurationBlock.addToWorkingSets(newElement, workingSets);
-
- BasicNewProjectResourceWizard.updatePerspective(fConfigElement);
- selectAndReveal(fSecondPage.getJavaProject().getProject());
-
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- PackageExplorerPart activePackageExplorer= getActivePackageExplorer();
- if (activePackageExplorer != null) {
- activePackageExplorer.tryToReveal(newElement);
- }
- }
- });
- }
- return res;
- }
-
- protected void handleFinishException(Shell shell, InvocationTargetException e) {
- String title= NewWizardMessages.JavaProjectWizard_op_error_title;
- String message= NewWizardMessages.JavaProjectWizard_op_error_create_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
-
- /*
- * Stores the configuration element for the wizard. The config element will be used
- * in <code>performFinish</code> to set the result perspective.
- */
- public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) {
- fConfigElement= cfig;
- }
-
- /* (non-Javadoc)
- * @see IWizard#performCancel()
- */
- public boolean performCancel() {
- fSecondPage.performCancel();
- return super.performCancel();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard#getCreatedElement()
- */
- public IJavaScriptElement getCreatedElement() {
- return JavaScriptCore.create(fFirstPage.getProjectHandle());
- }
-
- private IWorkingSet[] getWorkingSets(IStructuredSelection selection) {
- IWorkingSet[] selected= WorkingSetConfigurationBlock.getSelectedWorkingSet(selection);
- if (selected != null && selected.length > 0) {
- for (int i= 0; i < selected.length; i++) {
- if (!isValidWorkingSet(selected[i]))
- return null;
- }
- return selected;
- }
-
- PackageExplorerPart explorerPart= getActivePackageExplorer();
- if (explorerPart == null)
- return null;
-
- if (explorerPart.getRootMode() == ViewActionGroup.SHOW_PROJECTS) {
- //Get active filter
- IWorkingSet filterWorkingSet= explorerPart.getFilterWorkingSet();
- if (filterWorkingSet == null)
- return null;
-
- if (!isValidWorkingSet(filterWorkingSet))
- return null;
-
- return new IWorkingSet[] {filterWorkingSet};
- } else if (explorerPart.getRootMode() == ViewActionGroup.SHOW_WORKING_SETS) {
- //If we have been gone into a working set return the working set
- Object input= explorerPart.getViewPartInput();
- if (!(input instanceof IWorkingSet))
- return null;
-
- IWorkingSet workingSet= (IWorkingSet)input;
- if (!isValidWorkingSet(workingSet))
- return null;
-
- return new IWorkingSet[] {workingSet};
- }
-
- return null;
- }
-
- private PackageExplorerPart getActivePackageExplorer() {
- PackageExplorerPart explorerPart= PackageExplorerPart.getFromActivePerspective();
- if (explorerPart == null)
- return null;
-
- IWorkbenchPage activePage= explorerPart.getViewSite().getWorkbenchWindow().getActivePage();
- if (activePage == null)
- return null;
-
- if (activePage.getActivePart() != explorerPart)
- return null;
-
- return explorerPart;
- }
-
- private boolean isValidWorkingSet(IWorkingSet workingSet) {
- String id= workingSet.getId();
- if (!JavaWorkingSetUpdater.ID.equals(id) && !"org.eclipse.ui.resourceWorkingSetPage".equals(id)) //$NON-NLS-1$
- return false;
-
- if (workingSet.isAggregateWorkingSet())
- return false;
-
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java
deleted file mode 100644
index fb021d66..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java
+++ /dev/null
@@ -1,725 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.io.File;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.NewJavaProjectPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.JavaWorkingSetUpdater;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetConfigurationBlock;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * The first page of the <code>JavaScriptProjectWizard</code>.
- */
-public class JavaProjectWizardFirstPage extends WizardPage {
-
- /**
- * Request a project name. Notifies observers whenever the text field is
- * changed, regardless of its content.
- */
- private final class NameGroup extends Observable implements IDialogFieldListener {
-
- protected final StringDialogField fNameField;
-
- public NameGroup(Composite composite, String initialName) {
- final Composite nameComposite= new Composite(composite, SWT.NONE);
- nameComposite.setFont(composite.getFont());
- nameComposite.setLayout(initGridLayout(new GridLayout(2, false), false));
- nameComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // text field for project name
- fNameField= new StringDialogField();
- fNameField.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_NameGroup_label_text);
- fNameField.setDialogFieldListener(this);
-
- setName(initialName);
-
- fNameField.doFillIntoGrid(nameComposite, 2);
- LayoutUtil.setHorizontalGrabbing(fNameField.getTextControl(null));
- }
-
- public String getName() {
- return fNameField.getText().trim();
- }
-
- public void postSetFocus() {
- fNameField.postSetFocusOnDialogField(getShell().getDisplay());
- }
-
- public void setName(String name) {
- fNameField.setText(name);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- setChanged();
- notifyObservers();
- }
- }
-
- /**
- * Request a location for the project. Fires an event whenever the location
- * field is changed, regardless of whether the change originates from the
- * user or has been invoked programmatically.
- */
- private final class LocationGroup extends Observable implements Observer, IStringButtonAdapter, IDialogFieldListener {
-
- protected final SelectionButtonDialogField fWorkspaceRadio;
- protected final SelectionButtonDialogField fExternalRadio;
- protected final StringButtonDialogField fLocation;
-
- private String fPreviousExternalLocation;
-
- private static final String DIALOGSTORE_LAST_EXTERNAL_LOC= JavaScriptUI.ID_PLUGIN + ".last.external.project"; //$NON-NLS-1$
-
- public LocationGroup(Composite composite) {
-
- final int numColumns= 3;
-
- final Group group= new Group(composite, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- group.setLayout(initGridLayout(new GridLayout(numColumns, false), true));
- group.setText(NewWizardMessages.JavaProjectWizardFirstPage_LocationGroup_title);
-
- fWorkspaceRadio= new SelectionButtonDialogField(SWT.RADIO);
- fWorkspaceRadio.setDialogFieldListener(this);
- fWorkspaceRadio.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_LocationGroup_workspace_desc);
-
- fExternalRadio= new SelectionButtonDialogField(SWT.RADIO);
- fExternalRadio.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_LocationGroup_external_desc);
-
- fLocation= new StringButtonDialogField(this);
- fLocation.setDialogFieldListener(this);
- fLocation.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_LocationGroup_locationLabel_desc);
- fLocation.setButtonLabel(NewWizardMessages.JavaProjectWizardFirstPage_LocationGroup_browseButton_desc);
-
- fExternalRadio.attachDialogField(fLocation);
-
- fWorkspaceRadio.setSelection(true);
- fExternalRadio.setSelection(false);
-
- fPreviousExternalLocation= ""; //$NON-NLS-1$
-
- fWorkspaceRadio.doFillIntoGrid(group, numColumns);
- fExternalRadio.doFillIntoGrid(group, numColumns);
- fLocation.doFillIntoGrid(group, numColumns);
- LayoutUtil.setHorizontalGrabbing(fLocation.getTextControl(null));
- }
-
- protected void fireEvent() {
- setChanged();
- notifyObservers();
- }
-
- protected String getDefaultPath(String name) {
- final IPath path= Platform.getLocation().append(name);
- return path.toOSString();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.Observer#update(java.util.Observable,
- * java.lang.Object)
- */
- public void update(Observable o, Object arg) {
- if (isInWorkspace()) {
- fLocation.setText(getDefaultPath(fNameGroup.getName()));
- }
- fireEvent();
- }
-
- public IPath getLocation() {
- if (isInWorkspace()) {
- return Platform.getLocation();
- }
- return Path.fromOSString(fLocation.getText().trim());
- }
-
- public boolean isInWorkspace() {
- return fWorkspaceRadio.isSelected();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void changeControlPressed(DialogField field) {
- final DirectoryDialog dialog= new DirectoryDialog(getShell());
- dialog.setMessage(NewWizardMessages.JavaProjectWizardFirstPage_directory_message);
- String directoryName = fLocation.getText().trim();
- if (directoryName.length() == 0) {
- String prevLocation= JavaScriptPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LAST_EXTERNAL_LOC);
- if (prevLocation != null) {
- directoryName= prevLocation;
- }
- }
-
- if (directoryName.length() > 0) {
- final File path = new File(directoryName);
- if (path.exists())
- dialog.setFilterPath(directoryName);
- }
- final String selectedDirectory = dialog.open();
- if (selectedDirectory != null) {
- fLocation.setText(selectedDirectory);
- JavaScriptPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LAST_EXTERNAL_LOC, selectedDirectory);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- if (field == fWorkspaceRadio) {
- final boolean checked= fWorkspaceRadio.isSelected();
- if (checked) {
- fPreviousExternalLocation= fLocation.getText();
- fLocation.setText(getDefaultPath(fNameGroup.getName()));
- } else {
- fLocation.setText(fPreviousExternalLocation);
- }
- }
- fireEvent();
- }
- }
-
- /**
- * Request a project layout.
- */
- private final class LayoutGroup implements Observer, SelectionListener {
-
- private final SelectionButtonDialogField fStdRadio, fSrcBinRadio;
- private final Group fGroup;
- private final Link fPreferenceLink;
-
- public LayoutGroup(Composite composite) {
-
- fGroup= new Group(composite, SWT.NONE);
- fGroup.setFont(composite.getFont());
- fGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fGroup.setLayout(initGridLayout(new GridLayout(3, false), true));
- fGroup.setText(NewWizardMessages.JavaProjectWizardFirstPage_LayoutGroup_title);
-
- fStdRadio= new SelectionButtonDialogField(SWT.RADIO);
- fStdRadio.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_LayoutGroup_option_oneFolder);
-
- fSrcBinRadio= new SelectionButtonDialogField(SWT.RADIO);
- fSrcBinRadio.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_LayoutGroup_option_separateFolders);
-
- fStdRadio.doFillIntoGrid(fGroup, 3);
- LayoutUtil.setHorizontalGrabbing(fStdRadio.getSelectionButton(null));
-
- fSrcBinRadio.doFillIntoGrid(fGroup, 2);
-
- fPreferenceLink= new Link(fGroup, SWT.NONE);
- fPreferenceLink.setText(NewWizardMessages.JavaProjectWizardFirstPage_LayoutGroup_link_description);
- fPreferenceLink.setLayoutData(new GridData(GridData.END, GridData.END, false, false));
- fPreferenceLink.addSelectionListener(this);
-
- boolean useSrcBin= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
- fSrcBinRadio.setSelection(useSrcBin);
- fStdRadio.setSelection(!useSrcBin);
- }
-
- public void update(Observable o, Object arg) {
- final boolean detect= fDetectGroup.mustDetect();
- fStdRadio.setEnabled(!detect);
- fSrcBinRadio.setEnabled(!detect);
- fPreferenceLink.setEnabled(!detect);
- fGroup.setEnabled(!detect);
- }
-
- public boolean isSrcBin() {
- return fSrcBinRadio.isSelected();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- public void widgetSelected(SelectionEvent e) {
- widgetDefaultSelected(e);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
- */
- public void widgetDefaultSelected(SelectionEvent e) {
- String id= NewJavaProjectPreferencePage.ID;
- PreferencesUtil.createPreferenceDialogOn(getShell(), id, new String[] { id }, null).open();
- }
- }
-
- private final class WebPageSupportGroup implements Observer {
-
- private final Group fGroup;
-
- private final SelectionButtonDialogField fEnableWebSupport;
- private final SelectionButtonDialogField fDefaultWindowSuperType;
-
- public WebPageSupportGroup(Composite composite) {
- fGroup= new Group(composite, SWT.NONE);
- fGroup.setFont(composite.getFont());
- fGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- fGroup.setLayout(initGridLayout(new GridLayout(3, false), true));
- fGroup.setText(NewWizardMessages.JavaProjectWizardFirstPage_0);
-
- fEnableWebSupport= new SelectionButtonDialogField(SWT.CHECK);
- fEnableWebSupport.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_1);
- fEnableWebSupport.doFillIntoGrid(fGroup, 2);
- fEnableWebSupport.setEnabled(true);
- fEnableWebSupport.getSelectionButton(fGroup).addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- if (fDefaultWindowSuperType != null)
- fDefaultWindowSuperType.setEnabled(fEnableWebSupport.isSelected());
- }
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
-
- fDefaultWindowSuperType = new SelectionButtonDialogField(SWT.CHECK);
- fDefaultWindowSuperType.setLabelText(NewWizardMessages.JavaProjectWizardFirstPage_2);
- fDefaultWindowSuperType.doFillIntoGrid(fGroup, 2);
- fDefaultWindowSuperType.setEnabled(true);
-
-
- fEnableWebSupport.setSelection(true);
- fDefaultWindowSuperType.setSelection(true);
- }
-
- public boolean shouldEnableWebSupport() {
- return fEnableWebSupport.isSelected();
- }
- public boolean shouldDefaultToWebBrowser() {
- return fDefaultWindowSuperType.isEnabled() && fDefaultWindowSuperType.isSelected();
- }
-
- public void update(Observable o, Object arg) {
- final boolean detect= fDetectGroup.mustDetect();
- fEnableWebSupport.setEnabled(!detect);
- fDefaultWindowSuperType.setEnabled(!detect);
- fGroup.setEnabled(!detect);
- }
- }
-
-
- private final class WorkingSetGroup {
-
- private WorkingSetConfigurationBlock fWorkingSetBlock;
-
- public WorkingSetGroup(Composite composite, IWorkingSet[] initialWorkingSets) {
- Group workingSetGroup= new Group(composite, SWT.NONE);
- workingSetGroup.setFont(composite.getFont());
- workingSetGroup.setText(NewWizardMessages.JavaProjectWizardFirstPage_WorkingSets_group);
- workingSetGroup.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- workingSetGroup.setLayout(new GridLayout(1, false));
-
- String[] workingSetIds= new String[] {JavaWorkingSetUpdater.ID, "org.eclipse.ui.resourceWorkingSetPage"}; //$NON-NLS-1$
- fWorkingSetBlock= new WorkingSetConfigurationBlock(workingSetIds, NewWizardMessages.JavaProjectWizardFirstPage_EnableWorkingSet_button, JavaScriptPlugin.getDefault().getDialogSettings());
- fWorkingSetBlock.setDialogMessage(NewWizardMessages.JavaProjectWizardFirstPage_WorkingSetSelection_message);
- fWorkingSetBlock.setSelection(initialWorkingSets);
- fWorkingSetBlock.createContent(workingSetGroup);
- }
-
- public IWorkingSet[] getSelectedWorkingSets() {
- return fWorkingSetBlock.getSelectedWorkingSets();
- }
- }
-
- /**
- * Show a warning when the project location contains files.
- */
- private final class DetectGroup extends Observable implements Observer {
-
- private final Link fHintText;
- private Label fIcon;
- private boolean fDetect;
-
- public DetectGroup(Composite parent) {
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- GridLayout layout= new GridLayout(2, false);
- layout.horizontalSpacing= 10;
- composite.setLayout(layout);
-
- fIcon= new Label(composite, SWT.LEFT);
- fIcon.setImage(Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));
- GridData gridData= new GridData(SWT.LEFT, SWT.CENTER, false, false);
- fIcon.setLayoutData(gridData);
- fIcon.setVisible(false);
-
- fHintText= new Link(composite, SWT.WRAP);
- fHintText.setFont(composite.getFont());
- gridData= new GridData(GridData.FILL, SWT.FILL, true, true);
- gridData.widthHint= convertWidthInCharsToPixels(50);
- gridData.heightHint= convertHeightInCharsToPixels(3);
- fHintText.setLayoutData(gridData);
- }
-
- public void update(Observable o, Object arg) {
- if (o instanceof LocationGroup) {
- boolean oldDetectState= fDetect;
- if (fLocationGroup.isInWorkspace()) {
- fDetect= false;
- } else {
- final File directory= fLocationGroup.getLocation().toFile();
- fDetect= directory.isDirectory();
- }
-
- if (oldDetectState != fDetect) {
- setChanged();
- notifyObservers();
-
- if (fDetect) {
- fHintText.setVisible(true);
- fHintText.setText(NewWizardMessages.JavaProjectWizardFirstPage_DetectGroup_message);
- fIcon.setImage(Dialog.getImage(Dialog.DLG_IMG_MESSAGE_INFO));
- fIcon.setVisible(true);
- } else {
- fHintText.setVisible(false);
- fIcon.setVisible(false);
- }
- }
- }
- }
-
- public boolean mustDetect() {
- return fDetect;
- }
- }
-
- /**
- * Validate this page and show appropriate warnings and error NewWizardMessages.
- */
- private final class Validator implements Observer {
-
- public void update(Observable o, Object arg) {
-
- final IWorkspace workspace= JavaScriptPlugin.getWorkspace();
-
- final String name= fNameGroup.getName();
-
- // check whether the project name field is empty
- if (name.length() == 0) {
- setErrorMessage(null);
- setMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_enterProjectName);
- setPageComplete(false);
- return;
- }
-
- // check whether the project name is valid
- final IStatus nameStatus= workspace.validateName(name, IResource.PROJECT);
- if (!nameStatus.isOK()) {
- setErrorMessage(nameStatus.getMessage());
- setPageComplete(false);
- return;
- }
-
- // check whether project already exists
- final IProject handle= getProjectHandle();
- if (handle.exists()) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_projectAlreadyExists);
- setPageComplete(false);
- return;
- }
-
- final String location= fLocationGroup.getLocation().toOSString();
-
- // check whether location is empty
- if (location.length() == 0) {
- setErrorMessage(null);
- setMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_enterLocation);
- setPageComplete(false);
- return;
- }
-
- // check whether the location is a syntactically correct path
- if (!Path.EMPTY.isValidPath(location)) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_invalidDirectory);
- setPageComplete(false);
- return;
- }
-
- IPath projectPath= Path.fromOSString(location);
- // check external location
- if (!fLocationGroup.isInWorkspace()) {
- if (!canCreate(projectPath.toFile())) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_cannotCreateAtExternalLocation);
- setPageComplete(false);
- return;
- }
-
- if (!Platform.getLocation().equals(projectPath) && Platform.getLocation().isPrefixOf(projectPath)) {
- if (!Platform.getLocation().equals(projectPath.removeLastSegments(1))) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_notOnWorkspaceRoot);
- setPageComplete(false);
- return;
- }
-
- if (!projectPath.toFile().exists()) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_notExisingProjectOnWorkspaceRoot);
- setPageComplete(false);
- return;
- }
-
- String existingName= projectPath.lastSegment();
- if (!existingName.equals(fNameGroup.getName())) {
- setErrorMessage(Messages.format(NewWizardMessages.JavaProjectWizardFirstPage_Message_invalidProjectNameForWorkspaceRoot, existingName));
- setPageComplete(false);
- return;
- }
- } else {
- // If we do not place the contents in the workspace validate the
- // location.
- final IStatus locationStatus= workspace.validateProjectLocation(handle, projectPath);
- if (!locationStatus.isOK()) {
- setErrorMessage(locationStatus.getMessage());
- setPageComplete(false);
- return;
- }
- }
- } else {
- IPath projectFolder= projectPath.append(fNameGroup.getName());
- if (projectFolder.toFile().exists()) {
- setErrorMessage(NewWizardMessages.JavaProjectWizardFirstPage_Message_existingFolderInWorkspace);
- setPageComplete(false);
- return;
- }
- }
-
- setPageComplete(true);
-
- setErrorMessage(null);
- setMessage(null);
- }
-
- private boolean canCreate(File file) {
- while (!file.exists()) {
- file= file.getParentFile();
- if (file == null)
- return false;
- }
-
- return file.canWrite();
- }
-
- }
-
- private NameGroup fNameGroup;
- private LocationGroup fLocationGroup;
- private LayoutGroup fLayoutGroup;
- private WebPageSupportGroup webPageSupportGroup;
- private DetectGroup fDetectGroup;
- private Validator fValidator;
-
- private String fInitialName;
-
- private static final String PAGE_NAME= NewWizardMessages.JavaProjectWizardFirstPage_page_pageName;
- private WorkingSetGroup fWorkingSetGroup;
- private IWorkingSet[] fInitWorkingSets;
-
- /**
- * Create a new <code>SimpleProjectFirstPage</code>.
- */
- public JavaProjectWizardFirstPage() {
- super(PAGE_NAME);
- setPageComplete(false);
- setTitle(NewWizardMessages.JavaProjectWizardFirstPage_page_title);
- setDescription(NewWizardMessages.JavaProjectWizardFirstPage_page_description);
- fInitialName= ""; //$NON-NLS-1$
- }
-
- public void setName(String name) {
- fInitialName= name;
- if (fNameGroup != null) {
- fNameGroup.setName(name);
- }
- }
-
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- final Composite composite= new Composite(parent, SWT.NULL);
- composite.setFont(parent.getFont());
- composite.setLayout(initGridLayout(new GridLayout(1, false), true));
- composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- // create UI elements
- fNameGroup= new NameGroup(composite, fInitialName);
- fLocationGroup= new LocationGroup(composite);
- webPageSupportGroup= new WebPageSupportGroup(composite);
- fLayoutGroup= new LayoutGroup(composite);
- fWorkingSetGroup= new WorkingSetGroup(composite, fInitWorkingSets);
- fDetectGroup= new DetectGroup(composite);
-
- // establish connections
- fNameGroup.addObserver(fLocationGroup);
- fDetectGroup.addObserver(fLayoutGroup);
- fDetectGroup.addObserver(webPageSupportGroup);
- fLocationGroup.addObserver(fDetectGroup);
-
- // initialize all elements
- fNameGroup.notifyObservers();
-
- // create and connect validator
- fValidator= new Validator();
- fLocationGroup.addObserver(fValidator);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE);
- }
-
- /**
- * Returns the current project location path as entered by the user, or its
- * anticipated initial value. Note that if the default has been returned
- * the path in a project description used to create a project should not be
- * set.
- * <p>
- * TODO At some point this method has to be converted to return an URI instead
- * of an path. However, this first requires support from Platform/UI to specify
- * a project location different than in a local file system.
- * </p>
- * @return the project location path or its anticipated initial value.
- */
- public IPath getLocationPath() {
- return fLocationGroup.getLocation();
- }
-
- /**
- * Creates a project resource handle for the current project name field
- * value.
- * <p>
- * This method does not create the project resource; this is the
- * responsibility of <code>IProject::create</code> invoked by the new
- * project resource wizard.
- * </p>
- *
- * @return the new project resource handle
- */
- public IProject getProjectHandle() {
- return ResourcesPlugin.getWorkspace().getRoot().getProject(fNameGroup.getName());
- }
-
- public boolean isInWorkspace() {
- final String location= fLocationGroup.getLocation().toOSString();
- IPath projectPath= Path.fromOSString(location);
- return Platform.getLocation().isPrefixOf(projectPath);
- }
-
- public String getProjectName() {
- return fNameGroup.getName();
- }
-
- public boolean getDetect() {
- return fDetectGroup.mustDetect();
- }
-
- public boolean isSrcBin() {
- return fLayoutGroup.isSrcBin();
- }
-
- /**
- * @return the selected Compiler Compliance, or <code>null</code> iff the default Compiler Compliance should be used
- */
- public boolean isWebEnabled() {
- return webPageSupportGroup.shouldEnableWebSupport();
- }
-
- public boolean isWebDefault() {
- return webPageSupportGroup.shouldDefaultToWebBrowser();
- }
-
- /*
- * see @DialogPage.setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- fNameGroup.postSetFocus();
- }
- }
-
- /**
- * Initialize a grid layout with the default Dialog settings.
- * @param layout the layout to initialize
- * @param margins true if margins should be used
- * @return the initialized layout
- */
- protected GridLayout initGridLayout(GridLayout layout, boolean margins) {
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- if (margins) {
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- } else {
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- }
- return layout;
- }
-
- /**
- * @param workingSets the initial selected working sets or <b>null</b>
- */
- public void setWorkingSets(IWorkingSet[] workingSets) {
- fInitWorkingSets= workingSets;
- }
-
- /**
- * @return the selected working sets, not <b>null</b>
- */
- public IWorkingSet[] getWorkingSets() {
- return fWorkingSetGroup.getSelectedWorkingSets();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardSecondPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardSecondPage.java
deleted file mode 100644
index b829fdd8..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardSecondPage.java
+++ /dev/null
@@ -1,462 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.wizards.JavaCapabilityConfigurationPage;
-
-/**
- * As addition to the JavaCapabilityConfigurationPage, the wizard does an
- * early project creation (so that linked folders can be defined) and, if an
- * existing external location was specified, offers to do a classpath detection
- */
-public class JavaProjectWizardSecondPage extends JavaCapabilityConfigurationPage {
-
- private static final String FILENAME_PROJECT= ".project"; //$NON-NLS-1$
-
- private final JavaProjectWizardFirstPage fFirstPage;
-
- private URI fCurrProjectLocation; // null if location is platform location
- private IProject fCurrProject;
-
- private boolean fKeepContent;
-
- private File fDotProjectBackup;
- private File fDotClasspathBackup;
- private Boolean fIsAutobuild;
- private static final String SUPER_TYPE_NAME = "Window"; //$NON-NLS-1$
- /**
- * Constructor for JavaProjectWizardSecondPage.
- * @param mainPage the first page of the wizard
- */
- public JavaProjectWizardSecondPage(JavaProjectWizardFirstPage mainPage) {
- fFirstPage= mainPage;
- fCurrProjectLocation= null;
- fCurrProject= null;
- fKeepContent= false;
-
- fDotProjectBackup= null;
- fDotClasspathBackup= null;
- fIsAutobuild= null;
- }
-
- protected boolean useNewSourcePage() {
- return true;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- if (visible) {
- IStatus status= changeToNewProject();
- if (status != null && !status.isOK()) {
- ErrorDialog.openError(getShell(), NewWizardMessages.JavaProjectWizardSecondPage_error_title, null, status);
- }
- } else {
- removeProject();
- }
- super.setVisible(visible);
- if (visible) {
-
- setFocus();
- }
- }
-
- private IStatus changeToNewProject() {
- fKeepContent= fFirstPage.getDetect();
-
- class UpdateRunnable implements IRunnableWithProgress {
- public IStatus infoStatus= Status.OK_STATUS;
-
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- if (fIsAutobuild == null) {
- fIsAutobuild= Boolean.valueOf(CoreUtility.enableAutoBuild(false));
- }
- infoStatus= updateProject(monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- } finally {
- monitor.done();
- }
- }
- }
- UpdateRunnable op= new UpdateRunnable();
- try {
- getContainer().run(true, false, new WorkspaceModifyDelegatingOperation(op));
- return op.infoStatus;
- } catch (InvocationTargetException e) {
- final String title= NewWizardMessages.JavaProjectWizardSecondPage_error_title;
- final String message= NewWizardMessages.JavaProjectWizardSecondPage_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- } catch (InterruptedException e) {
- // cancel pressed
- }
- return null;
- }
-
- final IStatus updateProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
-
- IStatus result= StatusInfo.OK_STATUS;
-
- fCurrProject= fFirstPage.getProjectHandle();
- fCurrProjectLocation= getProjectLocationURI();
-
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- try {
- monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_initialize, 7);
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- URI realLocation= fCurrProjectLocation;
- if (fCurrProjectLocation == null) { // inside workspace
- try {
- URI rootLocation= ResourcesPlugin.getWorkspace().getRoot().getLocationURI();
- realLocation= new URI(rootLocation.getScheme(), null,
- Path.fromPortableString(rootLocation.getPath()).append(fCurrProject.getName()).toString(),
- null);
- } catch (URISyntaxException e) {
- Assert.isTrue(false, "Can't happen"); //$NON-NLS-1$
- }
- }
-
- rememberExistingFiles(realLocation);
-
- try {
- createProject(fCurrProject, fCurrProjectLocation, new SubProgressMonitor(monitor, 2));
- } catch (CoreException e) {
- if (e.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) {
- result= new StatusInfo(IStatus.INFO, Messages.format(NewWizardMessages.JavaProjectWizardSecondPage_DeleteCorruptProjectFile_message, e.getLocalizedMessage()));
-
- deleteProjectFile(realLocation);
- if (fCurrProject.exists())
- fCurrProject.delete(true, null);
-
- createProject(fCurrProject, fCurrProjectLocation, null);
- } else {
- throw e;
- }
- }
-
- IIncludePathEntry[] entries= null;
-
- if (fFirstPage.getDetect()) {
- if (!fCurrProject.getFolder(JavaProject.SHARED_PROPERTIES_DIRECTORY).getFile(JavaProject.CLASSPATH_FILENAME).exists()) {
- final ClassPathDetector detector= new ClassPathDetector(fCurrProject, new SubProgressMonitor(monitor, 2));
- entries= detector.getClasspath();
- } else {
- monitor.worked(2);
- }
- } else if (fFirstPage.isSrcBin()) {
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- IPath srcPath= new Path(store.getString(PreferenceConstants.SRCBIN_SRCNAME));
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272495
- // IPath binPath= new Path(store.getString(PreferenceConstants.SRCBIN_BINNAME));
-
- if (srcPath.segmentCount() > 0) {
- IFolder folder= fCurrProject.getFolder(srcPath);
- CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
-
-// if (binPath.segmentCount() > 0 && !binPath.equals(srcPath)) {
-// IFolder folder= fCurrProject.getFolder(binPath);
-// CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
-// } else {
- monitor.worked(1);
-// }
-
- final IPath projectPath= fCurrProject.getFullPath();
-
- // configure the classpath entries, including the default jre library.
- List cpEntries= new ArrayList();
- cpEntries.add(JavaScriptCore.newSourceEntry(projectPath.append(srcPath)));
- cpEntries.addAll(Arrays.asList(getDefaultClasspathEntry()));
- entries= (IIncludePathEntry[]) cpEntries.toArray(new IIncludePathEntry[cpEntries.size()]);
-
- // configure the output location
-// outputLocation= projectPath.append(binPath);
- } else {
- IPath projectPath= fCurrProject.getFullPath();
- List cpEntries= new ArrayList();
- cpEntries.add(JavaScriptCore.newSourceEntry(projectPath));
- cpEntries.addAll(Arrays.asList(getDefaultClasspathEntry()));
- entries= (IIncludePathEntry[]) cpEntries.toArray(new IIncludePathEntry[cpEntries.size()]);
-
-// outputLocation= projectPath;
- monitor.worked(2);
- }
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- IJavaScriptProject javaProject = JavaScriptCore.create(fCurrProject);
- init(javaProject, entries, false);
- if(fFirstPage.isWebDefault()) {
- LibrarySuperType superType = new LibrarySuperType(new Path( JavaRuntime.BASE_BROWSER_LIB), getJavaProject(), SUPER_TYPE_NAME);
- getBuildPathsBlock().setSuperType(superType);
- configureJavaProject(new SubProgressMonitor(monitor, 3)); // create the Java project to allow the use of the new source folder page
- }else {
- configureJavaProject(new SubProgressMonitor(monitor, 3)); // create the Java project to allow the use of the new source folder page
- }
-
- } finally {
- monitor.done();
- }
- return result;
- }
-
- private URI getProjectLocationURI() throws CoreException {
- if (fFirstPage.isInWorkspace()) {
- return null;
- }
- return URIUtil.toURI(fFirstPage.getLocationPath());
- }
-
- private IIncludePathEntry[] getDefaultClasspathEntry() {
- IPath jreContainerPath= new Path(JavaRuntime.JRE_CONTAINER);
- IPath BROWSER_LIB = new Path(JavaRuntime.BASE_BROWSER_LIB);
-
- if (fFirstPage.isWebEnabled()) {
- // use default
- return new IIncludePathEntry[] { JavaScriptCore.newContainerEntry(jreContainerPath),
- JavaScriptCore.newContainerEntry(BROWSER_LIB) };
- }else {
- return new IIncludePathEntry[] { JavaScriptCore.newContainerEntry(jreContainerPath)};
- }
- }
-
- private void deleteProjectFile(URI projectLocation) throws CoreException {
- IFileStore file= EFS.getStore(projectLocation);
- if (file.fetchInfo().exists()) {
- IFileStore projectFile= file.getChild(FILENAME_PROJECT);
- if (projectFile.fetchInfo().exists()) {
- projectFile.delete(EFS.NONE, null);
- }
- }
- }
-
- private void rememberExistingFiles(URI projectLocation) throws CoreException {
- fDotProjectBackup= null;
- fDotClasspathBackup= null;
-
- IFileStore file= EFS.getStore(projectLocation);
- if (file.fetchInfo().exists()) {
- IFileStore projectFile= file.getChild(FILENAME_PROJECT);
- if (projectFile.fetchInfo().exists()) {
- fDotProjectBackup= createBackup(projectFile, "project-desc"); //$NON-NLS-1$
- }
- IFileStore classpathFile= file.getChild(JavaProject.CLASSPATH_FILENAME);
- if (classpathFile.fetchInfo().exists()) {
- fDotClasspathBackup= createBackup(classpathFile, "classpath-desc"); //$NON-NLS-1$
- }
- }
- }
-
- private void restoreExistingFiles(URI projectLocation, IProgressMonitor monitor) throws CoreException {
- int ticks= ((fDotProjectBackup != null ? 1 : 0) + (fDotClasspathBackup != null ? 1 : 0)) * 2;
- monitor.beginTask("", ticks); //$NON-NLS-1$
- try {
- IFileStore projectFile= EFS.getStore(projectLocation).getChild(FILENAME_PROJECT);
- projectFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
- if (fDotProjectBackup != null) {
- copyFile(fDotProjectBackup, projectFile, new SubProgressMonitor(monitor, 1));
- }
- } catch (IOException e) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, NewWizardMessages.JavaProjectWizardSecondPage_problem_restore_project, e);
- throw new CoreException(status);
- }
- try {
- IFileStore classpathFile= EFS.getStore(projectLocation).getChild(JavaProject.CLASSPATH_FILENAME);
- classpathFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
- if (fDotClasspathBackup != null) {
- copyFile(fDotClasspathBackup, classpathFile, new SubProgressMonitor(monitor, 1));
- }
- } catch (IOException e) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, NewWizardMessages.JavaProjectWizardSecondPage_problem_restore_classpath, e);
- throw new CoreException(status);
- }
- }
-
- private File createBackup(IFileStore source, String name) throws CoreException {
- try {
- File bak= File.createTempFile("eclipse-" + name, ".bak"); //$NON-NLS-1$//$NON-NLS-2$
- copyFile(source, bak);
- return bak;
- } catch (IOException e) {
- IStatus status= new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, Messages.format(NewWizardMessages.JavaProjectWizardSecondPage_problem_backup, name), e);
- throw new CoreException(status);
- }
- }
-
- private void copyFile(IFileStore source, File target) throws IOException, CoreException {
- InputStream is= source.openInputStream(EFS.NONE, null);
- FileOutputStream os= new FileOutputStream(target);
- copyFile(is, os);
- }
-
- private void copyFile(File source, IFileStore target, IProgressMonitor monitor) throws IOException, CoreException {
- FileInputStream is= new FileInputStream(source);
- OutputStream os= target.openOutputStream(EFS.NONE, monitor);
- copyFile(is, os);
- }
-
- private void copyFile(InputStream is, OutputStream os) throws IOException {
- try {
- byte[] buffer = new byte[8192];
- while (true) {
- int bytesRead= is.read(buffer);
- if (bytesRead == -1)
- break;
-
- os.write(buffer, 0, bytesRead);
- }
- } finally {
- try {
- is.close();
- } finally {
- os.close();
- }
- }
- }
-
- /**
- * Called from the wizard on finish.
- * @param monitor the progress monitor
- * @throws CoreException thrown when the project creation or configuration failed
- * @throws InterruptedException thrown when the user cancelled the project creation
- */
- public void performFinish(IProgressMonitor monitor) throws CoreException, InterruptedException {
- try {
- monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_create, 3);
- if (fCurrProject == null) {
- updateProject(new SubProgressMonitor(monitor, 1));
- }
- configureJavaProject(new SubProgressMonitor(monitor, 2));
- } finally {
- monitor.done();
- fCurrProject= null;
- if (fIsAutobuild != null) {
- CoreUtility.enableAutoBuild(fIsAutobuild.booleanValue());
- fIsAutobuild= null;
- }
- }
- }
-
- private void removeProject() {
- if (fCurrProject == null || !fCurrProject.exists()) {
- return;
- }
-
- IRunnableWithProgress op= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- doRemoveProject(monitor);
- }
- };
-
- try {
- getContainer().run(true, true, new WorkspaceModifyDelegatingOperation(op));
- } catch (InvocationTargetException e) {
- final String title= NewWizardMessages.JavaProjectWizardSecondPage_error_remove_title;
- final String message= NewWizardMessages.JavaProjectWizardSecondPage_error_remove_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- } catch (InterruptedException e) {
- // cancel pressed
- }
- }
-
- final void doRemoveProject(IProgressMonitor monitor) throws InvocationTargetException {
- final boolean noProgressMonitor= (fCurrProjectLocation == null); // inside workspace
- if (monitor == null || noProgressMonitor) {
- monitor= new NullProgressMonitor();
- }
- monitor.beginTask(NewWizardMessages.JavaProjectWizardSecondPage_operation_remove, 3);
- try {
- try {
- URI projLoc= fCurrProject.getLocationURI();
-
- boolean removeContent= !fKeepContent && fCurrProject.isSynchronized(IResource.DEPTH_INFINITE);
- fCurrProject.delete(removeContent, false, new SubProgressMonitor(monitor, 2));
-
- restoreExistingFiles(projLoc, new SubProgressMonitor(monitor, 1));
- } finally {
- CoreUtility.enableAutoBuild(fIsAutobuild.booleanValue()); // fIsAutobuild must be set
- fIsAutobuild= null;
- }
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- fCurrProject= null;
- fKeepContent= false;
- }
- }
-
- /**
- * Called from the wizard on cancel.
- */
- public void performCancel() {
- removeProject();
- }
- }
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewClassCreationWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewClassCreationWizard.java
deleted file mode 100644
index 104c2eaa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewClassCreationWizard.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.ui.wizards.NewClassWizardPage;
-
-public class NewClassCreationWizard extends NewElementWizard {
-
- private NewClassWizardPage fPage;
- private boolean fOpenEditorOnFinish;
-
- public NewClassCreationWizard(NewClassWizardPage page, boolean openEditorOnFinish) {
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS);
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- setWindowTitle(NewWizardMessages.NewClassCreationWizard_title);
-
- fPage= page;
- fOpenEditorOnFinish= openEditorOnFinish;
- }
-
- public NewClassCreationWizard() {
- this(null, true);
- }
-
- /*
- * @see Wizard#createPages
- */
- public void addPages() {
- super.addPages();
- if (fPage == null) {
- fPage= new NewClassWizardPage();
- fPage.init(getSelection());
- }
- addPage(fPage);
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard#canRunForked()
- */
- protected boolean canRunForked() {
- return !fPage.isEnclosingTypeSelected();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
- fPage.createType(monitor); // use the full progress monitor
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.IWizard#performFinish()
- */
- public boolean performFinish() {
- warnAboutTypeCommentDeprecation();
- boolean res= super.performFinish();
- if (res) {
- IResource resource= fPage.getModifiedResource();
- if (resource != null) {
- selectAndReveal(resource);
- if (fOpenEditorOnFinish) {
- openResource((IFile) resource);
- }
- }
- }
- return res;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard#getCreatedElement()
- */
- public IJavaScriptElement getCreatedElement() {
- return fPage.getCreatedType();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewElementWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewElementWizard.java
deleted file mode 100644
index 666c5c7c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewElementWizard.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.templates.persistence.TemplateStore;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-public abstract class NewElementWizard extends Wizard implements INewWizard {
-
- private IWorkbench fWorkbench;
- private IStructuredSelection fSelection;
-
- public NewElementWizard() {
- setNeedsProgressMonitor(true);
- }
-
- protected void openResource(final IFile resource) {
- final IWorkbenchPage activePage= JavaScriptPlugin.getActivePage();
- if (activePage != null) {
- final Display display= getShell().getDisplay();
- if (display != null) {
- display.asyncExec(new Runnable() {
- public void run() {
- try {
- IDE.openEditor(activePage, resource, true);
- } catch (PartInitException e) {
- JavaScriptPlugin.log(e);
- }
- }
- });
- }
- }
- }
-
- /**
- * Subclasses should override to perform the actions of the wizard.
- * This method is run in the wizard container's context as a workspace runnable.
- * @param monitor
- * @throws InterruptedException
- * @throws CoreException
- */
- protected abstract void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException;
-
- /**
- * Returns the scheduling rule for creating the element.
- */
- protected ISchedulingRule getSchedulingRule() {
- return ResourcesPlugin.getWorkspace().getRoot(); // look all by default
- }
-
-
- protected boolean canRunForked() {
- return true;
- }
-
- public abstract IJavaScriptElement getCreatedElement();
-
- protected void handleFinishException(Shell shell, InvocationTargetException e) {
- String title= NewWizardMessages.NewElementWizard_op_error_title;
- String message= NewWizardMessages.NewElementWizard_op_error_message;
- ExceptionHandler.handle(e, shell, title, message);
- }
-
- /*
- * @see Wizard#performFinish
- */
- public boolean performFinish() {
- IWorkspaceRunnable op= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- try {
- finishPage(monitor);
- } catch (InterruptedException e) {
- throw new OperationCanceledException(e.getMessage());
- }
- }
- };
- try {
- ISchedulingRule rule= null;
- Job job= Job.getJobManager().currentJob();
- if (job != null)
- rule= job.getRule();
- IRunnableWithProgress runnable= null;
- if (rule != null)
- runnable= new WorkbenchRunnableAdapter(op, rule, true);
- else
- runnable= new WorkbenchRunnableAdapter(op, getSchedulingRule());
- getContainer().run(canRunForked(), true, runnable);
- } catch (InvocationTargetException e) {
- handleFinishException(getShell(), e);
- return false;
- } catch (InterruptedException e) {
- return false;
- }
- return true;
- }
-
- protected void warnAboutTypeCommentDeprecation() {
- String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED;
- if (OptionalMessageDialog.isDialogEnabled(key)) {
- TemplateStore templates= JavaScriptPlugin.getDefault().getTemplateStore();
- boolean isOldWorkspace= templates.findTemplate("filecomment") != null && templates.findTemplate("typecomment") != null; //$NON-NLS-1$ //$NON-NLS-2$
- if (!isOldWorkspace) {
- OptionalMessageDialog.setDialogEnabled(key, false);
- }
- String title= NewWizardMessages.NewElementWizard_typecomment_deprecated_title;
- String message= NewWizardMessages.NewElementWizard_typecomment_deprecated_message;
- OptionalMessageDialog.open(key, getShell(), title, null, message, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
- fWorkbench= workbench;
- fSelection= currentSelection;
- }
-
- public IStructuredSelection getSelection() {
- return fSelection;
- }
-
- public IWorkbench getWorkbench() {
- return fWorkbench;
- }
-
- protected void selectAndReveal(IResource newResource) {
- BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench.getActiveWorkbenchWindow());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java
deleted file mode 100644
index 1501c043..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-class NewJSFileWizardPage extends WizardNewFileCreationPage {
-
- private IContentType fContentType;
- private List fValidExtensions = null;
-
- public NewJSFileWizardPage(String pageName, IStructuredSelection selection) {
- super(pageName, selection);
- }
-
- /**
- * This method is overriden to set the selected folder to web contents
- * folder if the current selection is outside the web contents folder.
- */
- protected void initialPopulateContainerNameField() {
-
- super.initialPopulateContainerNameField();
-
- IPath fullPath = getContainerFullPath();
- if (fullPath != null && fullPath.segmentCount() > 0) {
- IProject project = getProjectFromPath(fullPath);
- IPath webContentPath = getWebContentPath(project);
- IPath projectPath = project.getFullPath();
- if (projectPath.equals(fullPath))
- setContainerFullPath(webContentPath);
- else
- setContainerFullPath(fullPath);
- }
- //if (webContentPath != null && !webContentPath.isPrefixOf(fullPath)) {
- //setContainerFullPath(webContentPath);
- // }else{
- //setContainerFullPath(new Path(""));
- // }
-
- }
-
- /**
- * This method is overriden to set additional validation specific to
- * javascript files.
- */
- protected boolean validatePage() {
- setMessage(null);
- setErrorMessage(null);
-
- if (!super.validatePage()) {
- return false;
- }
-
- String fileName = getFileName();
- IPath fullPath = getContainerFullPath();
- if ((fullPath != null) && (fullPath.isEmpty() == false) && (fileName != null)) {
- // check that filename does not contain invalid extension
- if (!extensionValidForContentType(fileName)) {
- setErrorMessage(NLS.bind(NewWizardMessages.Javascript_Error_Filename_Must_End_JS, getValidExtensions().toString()));
- return false;
- }
- // no file extension specified so check adding default
- // extension doesn't equal a file that already exists
- if (fileName.lastIndexOf('.') == -1) {
- String newFileName = addDefaultExtension(fileName);
- IPath resourcePath = fullPath.append(newFileName);
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus result = workspace.validatePath(resourcePath.toString(), IResource.FOLDER);
- if (!result.isOK()) {
- // path invalid
- setErrorMessage(result.getMessage());
- return false;
- }
-
- if ((workspace.getRoot().getFolder(resourcePath).exists() || workspace.getRoot().getFile(resourcePath).exists())) {
- setErrorMessage(NewWizardMessages.Javascript_Resource_Group_Name_Exists);
- return false;
- }
- }
-
- // get the IProject for the selection path
- IProject project = getProjectFromPath(fullPath);
- // if inside web project, check if inside webContent folder
- if (project != null && isWebProject(project)) {
- // check that the path is inside the webContent folder
- IPath webContentPath = getWebContentPath(project);
- if (!webContentPath.isPrefixOf(fullPath)) {
- setMessage(NewWizardMessages.Javascript_Warning_Folder_Must_Be_Inside_Web_Content, WARNING);
- }
- }
- }
-
- return true;
- }
-
- /**
- * Get content type associated with this new file wizard
- *
- * @return IContentType
- */
- private IContentType getContentType() {
- if (fContentType == null)
-// fContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJavaScript.ContentTypeID_JAVASCRIPT);
- fContentType = Platform.getContentTypeManager().getContentType("org.eclipse.wst.jsdt.core.jsSource"); //$NON-NLS-1$
- return fContentType;
- }
-
- /**
- * Get list of valid extensions for JavaScript Content type
- *
- * @return
- */
- private List getValidExtensions() {
- if (fValidExtensions == null) {
- IContentType type = getContentType();
- fValidExtensions = new ArrayList(Arrays.asList(type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC)));
- }
- return fValidExtensions;
- }
-
- /**
- * Verifies if fileName is valid name for content type. Takes base content
- * type into consideration.
- *
- * @param fileName
- * @return true if extension is valid for this content type
- */
- private boolean extensionValidForContentType(String fileName) {
- boolean valid = false;
-
- IContentType type = getContentType();
- // there is currently an extension
- if (fileName.lastIndexOf('.') != -1) {
- // check what content types are associated with current extension
- IContentType[] types = Platform.getContentTypeManager().findContentTypesFor(fileName);
- int i = 0;
- while (i < types.length && !valid) {
- valid = types[i].isKindOf(type);
- ++i;
- }
- }
- else
- valid = true; // no extension so valid
- return valid;
- }
-
- /**
- * Adds default extension to the filename
- *
- * @param filename
- * @return
- */
- String addDefaultExtension(String filename) {
- StringBuffer newFileName = new StringBuffer(filename);
-
-// Preferences preference = JavaScriptCorePlugin.getDefault().getPluginPreferences();
-// String ext = preference.getString(JavaScriptCorePreferenceNames.DEFAULT_EXTENSION);
-
- newFileName.append("."); //$NON-NLS-1$
-// newFileName.append(ext);
-newFileName.append("js"); //$NON-NLS-1$
- return newFileName.toString();
- }
-
- /**
- * Returns the project that contains the specified path
- *
- * @param path the path which project is needed
- * @return IProject object. If path is <code>null</code> the return value
- * is also <code>null</code>.
- */
- private IProject getProjectFromPath(IPath path) {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IProject project = null;
-
- if (path != null) {
- if (workspace.validatePath(path.toString(), IResource.PROJECT).isOK()) {
- project = workspace.getRoot().getProject(path.toString());
- } else {
- project = workspace.getRoot().getFile(path).getProject();
- }
- }
-
- return project;
- }
-
- /**
- * Checks if the specified project is a web project.
- *
- * @param project project to be checked
- * @return true if the project is web project, otherwise false
- */
- private boolean isWebProject(IProject project) {
-/*
- IFacetedProject faceted = null;
- try {
- faceted = ProjectFacetsManager.create(project);
- } catch (CoreException e) {
- Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
- }
-
- if (faceted != null &&
- (faceted.hasProjectFacet(ProjectFacetsManager.getProjectFacet(IModuleConstants.WST_WEB_MODULE)) ||
- faceted.hasProjectFacet(ProjectFacetsManager.getProjectFacet(IModuleConstants.JST_WEB_MODULE)))) {
- return true;
- }
-
- return false;
-*/
-return true;
- }
-
- /**
- * Returns the web contents folder of the specified project
- *
- * @param project the project which web contents path is needed
- * @return IPath of the web contents folder
- */
- private IPath getWebContentPath(IProject project) {
- IPath path = null;
-
- if (project != null && isWebProject(project)) {
- path = project.getFullPath();
-// IVirtualComponent component = ComponentCore.createComponent(project);
-// path = component.getRootFolder().getWorkspaceRelativePath();
-path.append("/"); //$NON-NLS-1$
- }
-
- return path;
- }
-
- public void addFileComment(IFile file) {
- IJavaScriptUnit cu= JavaScriptCore.createCompilationUnitFrom(file);
- try {
- cu.becomeWorkingCopy(new NullProgressMonitor());
- cu.getBuffer().setContents(CodeGeneration.getFileComment(cu, StubUtility.getLineDelimiterUsed(cu)));
- cu.commitWorkingCopy(true, new NullProgressMonitor());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java
deleted file mode 100644
index a5732dc0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class NewJSWizard extends Wizard implements INewWizard {
-
- private NewJSFileWizardPage fNewFilePage;
- private IStructuredSelection fSelection;
-
- public void addPages() {
- fNewFilePage = new NewJSFileWizardPage("JSWizardNewFileCreationPage", new StructuredSelection(IDE.computeSelectedResources(fSelection))); //$NON-NLS-1$
- fNewFilePage.setTitle(NewWizardMessages.Javascript_UI_Wizard_New_Heading); //$NON-NLS-1$
- fNewFilePage.setDescription(NewWizardMessages.Javascript_UI_Wizard_New_Description); //$NON-NLS-1$
- addPage(fNewFilePage);
- }
-
- public void init(IWorkbench aWorkbench, IStructuredSelection aSelection) {
- fSelection = aSelection;
- setWindowTitle(NewWizardMessages.Javascript_UI_Wizard_New_Title); //$NON-NLS-1$
- setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJSFILE);
- }
-
- private void openEditor(final IFile file) {
- if (file != null) {
- getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- try {
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IDE.openEditor(page, file, true, false);
- }
- catch (PartInitException e) {
- // STP Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
- JavaScriptPlugin.log(e);
- }
- }
- });
- }
- }
-
- public boolean performFinish() {
- boolean performedOK = false;
-
- // no file extension specified so add default extension
- String fileName = fNewFilePage.getFileName();
- if (fileName.lastIndexOf('.') == -1) {
- String newFileName = fNewFilePage.addDefaultExtension(fileName);
- fNewFilePage.setFileName(newFileName);
- }
-
- // create a new empty file
- IFile file = fNewFilePage.createNewFile();
- // add comment to created file
- fNewFilePage.addFileComment(file);
- // if there was problem with creating file, it will be null, so make
- // sure to check
- if (file != null) {
- // open the file in editor
- openEditor(file);
-
- // everything's fine
- performedOK = true;
- }
- return performedOK;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewSourceFolderWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewSourceFolderWizardPage.java
deleted file mode 100644
index 5981253c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewSourceFolderWizardPage.java
+++ /dev/null
@@ -1,510 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-
-public class NewSourceFolderWizardPage extends NewElementWizardPage {
-
- private static final String PAGE_NAME= "NewSourceFolderWizardPage"; //$NON-NLS-1$
-
- private StringButtonDialogField fProjectField;
- private StatusInfo fProjectStatus;
-
- private StringButtonDialogField fRootDialogField;
- private StatusInfo fRootStatus;
-
- private SelectionButtonDialogField fExcludeInOthersFields;
-
- private IWorkspaceRoot fWorkspaceRoot;
-
- private IJavaScriptProject fCurrJProject;
- private IIncludePathEntry[] fEntries;
-
- private IIncludePathEntry[] fNewEntries;
-
- private boolean fIsProjectAsSourceFolder;
-
- private IPackageFragmentRoot fCreatedRoot;
-
- public NewSourceFolderWizardPage() {
- super(PAGE_NAME);
-
- setTitle(NewWizardMessages.NewSourceFolderWizardPage_title);
- setDescription(NewWizardMessages.NewSourceFolderWizardPage_description);
-
- fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
-
- RootFieldAdapter adapter= new RootFieldAdapter();
-
- fProjectField= new StringButtonDialogField(adapter);
- fProjectField.setDialogFieldListener(adapter);
- fProjectField.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_project_label);
- fProjectField.setButtonLabel(NewWizardMessages.NewSourceFolderWizardPage_project_button);
-
- fRootDialogField= new StringButtonDialogField(adapter);
- fRootDialogField.setDialogFieldListener(adapter);
- fRootDialogField.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_root_label);
- fRootDialogField.setButtonLabel(NewWizardMessages.NewSourceFolderWizardPage_root_button);
-
- fExcludeInOthersFields= new SelectionButtonDialogField(SWT.CHECK);
- fExcludeInOthersFields.setDialogFieldListener(adapter);
- fExcludeInOthersFields.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_exclude_label);
-
- //fExcludeInOthersFields.setEnabled(JavaScriptCore.ENABLED.equals(JavaScriptCore.getOption(JavaScriptCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS)));
- fExcludeInOthersFields.setEnabled(true);
- fRootStatus= new StatusInfo();
- fProjectStatus= new StatusInfo();
- }
-
- // -------- Initialization ---------
-
- public void init(IStructuredSelection selection) {
- String projPath= getProjectPath(selection);
- if (projPath != null) {
- fProjectField.setText(projPath);
- }
- fRootDialogField.setText(""); //$NON-NLS-1$
- }
-
- private String getProjectPath(IStructuredSelection selection) {
- Object selectedElement= null;
- if (selection == null || selection.isEmpty()) {
- selectedElement= EditorUtility.getActiveEditorJavaInput();
- } else if (selection.size() == 1) {
- selectedElement= selection.getFirstElement();
- }
-
- if (selectedElement instanceof IResource) {
- IProject proj= ((IResource)selectedElement).getProject();
- if (proj != null) {
- return proj.getFullPath().makeRelative().toString();
- }
- } else if (selectedElement instanceof IJavaScriptElement) {
- IJavaScriptProject jproject= ((IJavaScriptElement)selectedElement).getJavaScriptProject();
- if (jproject != null) {
- return jproject.getProject().getFullPath().makeRelative().toString();
- }
- }
-
- return null;
- }
-
- // -------- UI Creation ---------
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 3;
- composite.setLayout(layout);
-
- fProjectField.doFillIntoGrid(composite, 3);
- fRootDialogField.doFillIntoGrid(composite, 3);
- fExcludeInOthersFields.doFillIntoGrid(composite, 3);
-
- int maxFieldWidth= convertWidthInCharsToPixels(40);
- LayoutUtil.setWidthHint(fProjectField.getTextControl(null), maxFieldWidth);
- LayoutUtil.setHorizontalGrabbing(fProjectField.getTextControl(null));
- LayoutUtil.setWidthHint(fRootDialogField.getTextControl(null), maxFieldWidth);
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- fRootDialogField.setFocus();
- }
- }
-
- // -------- ContainerFieldAdapter --------
-
- private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
-
- // -------- IStringButtonAdapter
- public void changeControlPressed(DialogField field) {
- packRootChangeControlPressed(field);
- }
-
- // -------- IDialogFieldListener
- public void dialogFieldChanged(DialogField field) {
- packRootDialogFieldChanged(field);
- }
- }
- protected void packRootChangeControlPressed(DialogField field) {
- if (field == fRootDialogField) {
- IPath initialPath= new Path(fRootDialogField.getText());
- String title= NewWizardMessages.NewSourceFolderWizardPage_ChooseExistingRootDialog_title;
- String message= NewWizardMessages.NewSourceFolderWizardPage_ChooseExistingRootDialog_description;
- IFolder folder= chooseFolder(title, message, initialPath);
- if (folder != null) {
- IPath path= folder.getFullPath().removeFirstSegments(1);
- fRootDialogField.setText(path.toString());
- }
- } else if (field == fProjectField) {
- IJavaScriptProject jproject= chooseProject();
- if (jproject != null) {
- IPath path= jproject.getProject().getFullPath().makeRelative();
- fProjectField.setText(path.toString());
- }
- }
- }
-
- protected void packRootDialogFieldChanged(DialogField field) {
- if (field == fRootDialogField) {
- updateRootStatus();
- } else if (field == fProjectField) {
- updateProjectStatus();
- updateRootStatus();
- } else if (field == fExcludeInOthersFields) {
- updateRootStatus();
- }
- updateStatus(new IStatus[] { fProjectStatus, fRootStatus });
- }
-
-
- private void updateProjectStatus() {
- fCurrJProject= null;
- fIsProjectAsSourceFolder= false;
-
- String str= fProjectField.getText();
- if (str.length() == 0) {
- fProjectStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_EnterProjectName);
- return;
- }
- IPath path= new Path(str);
- if (path.segmentCount() != 1) {
- fProjectStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidProjectPath);
- return;
- }
- IProject project= fWorkspaceRoot.getProject(path.toString());
- if (!project.exists()) {
- fProjectStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_ProjectNotExists);
- return;
- }
- if (!project.isOpen()) {
- fProjectStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_ProjectNotOpen);
- return;
- }
- try {
- if (project.hasNature(JavaScriptCore.NATURE_ID)) {
- fCurrJProject= JavaScriptCore.create(project);
- fEntries= fCurrJProject.getRawIncludepath();
- fProjectStatus.setOK();
- return;
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- fCurrJProject= null;
- }
- fProjectStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAJavaProject);
- }
-
- private void updateRootStatus() {
- fRootDialogField.enableButton(fCurrJProject != null);
- fIsProjectAsSourceFolder= false;
- if (fCurrJProject == null) {
- return;
- }
- fRootStatus.setOK();
-
- IPath projPath= fCurrJProject.getProject().getFullPath();
- String str= fRootDialogField.getText();
- if (str.length() == 0) {
- fRootStatus.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_EnterRootName, fCurrJProject.getProject().getFullPath().toString()));
- } else {
- IPath path= projPath.append(str);
- IStatus validate= fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
- if (validate.matches(IStatus.ERROR)) {
- fRootStatus.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
- } else {
- IResource res= fWorkspaceRoot.findMember(path);
- if (res != null) {
- if (res.getType() != IResource.FOLDER) {
- fRootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
- return;
- }
- } else {
- URI projLocation= fCurrJProject.getProject().getLocationURI();
- if (projLocation != null) {
- try {
- IFileStore store= EFS.getStore(projLocation).getChild(str);
- if (store.fetchInfo().exists()) {
- fRootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
- return;
- }
- } catch (CoreException e) {
- // we couldn't create the file store. Ignore the exception
- // since we can't check if the file exist. Pretend that it
- // doesn't.
- }
- }
- }
- ArrayList newEntries= new ArrayList(fEntries.length + 1);
- int projectEntryIndex= -1;
-
- for (int i= 0; i < fEntries.length; i++) {
- IIncludePathEntry curr= fEntries[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (path.equals(curr.getPath())) {
- fRootStatus.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExisting);
- return;
- }
- if (projPath.equals(curr.getPath())) {
- projectEntryIndex= i;
- }
- }
- newEntries.add(curr);
- }
-
- IIncludePathEntry newEntry= JavaScriptCore.newSourceEntry(path);
-
- Set modified= new HashSet();
- if (fExcludeInOthersFields.isSelected()) {
- addExclusionPatterns(newEntry, newEntries, modified);
- IIncludePathEntry entry= JavaScriptCore.newSourceEntry(path);
- insertAtEndOfCategory(entry, newEntries);
- } else {
- if (projectEntryIndex != -1) {
- fIsProjectAsSourceFolder= true;
- newEntries.set(projectEntryIndex, newEntry);
- } else {
- IIncludePathEntry entry= JavaScriptCore.newSourceEntry(path);
- insertAtEndOfCategory(entry, newEntries);
- }
- }
-
- fNewEntries= (IIncludePathEntry[]) newEntries.toArray(new IIncludePathEntry[newEntries.size()]);
-
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(fCurrJProject, fNewEntries);
- if (!status.isOK()) {
- fRootStatus.setError(status.getMessage());
- return;
- } else if (fIsProjectAsSourceFolder) {
- fRootStatus.setInfo(NewWizardMessages.NewSourceFolderWizardPage_warning_ReplaceSF);
- return;
- }
- if (!modified.isEmpty()) {
- fRootStatus.setInfo(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_warning_AddedExclusions, String.valueOf(modified.size())));
- return;
- }
- }
- }
- }
-
- private void insertAtEndOfCategory(IIncludePathEntry entry, List entries) {
- int length= entries.size();
- IIncludePathEntry[] elements= (IIncludePathEntry[])entries.toArray(new IIncludePathEntry[length]);
- int i= 0;
- while (i < length && elements[i].getEntryKind() != entry.getEntryKind()) {
- i++;
- }
- if (i < length) {
- i++;
- while (i < length && elements[i].getEntryKind() == entry.getEntryKind()) {
- i++;
- }
- entries.add(i, entry);
- return;
- }
-
- switch (entry.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- entries.add(0, entry);
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_PROJECT:
- case IIncludePathEntry.CPE_VARIABLE:
- default:
- entries.add(entry);
- break;
- }
- }
-
- private void addExclusionPatterns(IIncludePathEntry newEntry, List existing, Set modifiedEntries) {
- IPath entryPath= newEntry.getPath();
- for (int i= 0; i < existing.size(); i++) {
- IIncludePathEntry curr= (IIncludePathEntry) existing.get(i);
- IPath currPath= curr.getPath();
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE && currPath.isPrefixOf(entryPath)) {
- IPath[] exclusionFilters= curr.getExclusionPatterns();
- if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
- IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
- IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
- System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
- newExclusionFilters[exclusionFilters.length]= pathToExclude;
-
- IIncludePathEntry updated= JavaScriptCore.newSourceEntry(currPath, newExclusionFilters, null);
- existing.set(i, updated);
- modifiedEntries.add(updated);
- }
- }
- }
- }
-
- // ---- creation ----------------
-
- public IPackageFragmentRoot getNewPackageFragmentRoot() {
- return fCreatedRoot;
- }
-
- public IResource getCorrespondingResource() {
- return fCurrJProject.getProject().getFolder(fRootDialogField.getText());
- }
-
- public void createPackageFragmentRoot(IProgressMonitor monitor) throws CoreException, InterruptedException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.beginTask(NewWizardMessages.NewSourceFolderWizardPage_operation, 3);
- try {
- String relPath= fRootDialogField.getText();
-
- IFolder folder= fCurrJProject.getProject().getFolder(relPath);
- if (!folder.exists()) {
- CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
- }
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
-
- fCurrJProject.setRawIncludepath(fNewEntries, new SubProgressMonitor(monitor, 2));
-
- fCreatedRoot= fCurrJProject.getPackageFragmentRoot(folder);
- } finally {
- monitor.done();
- }
- }
-
- // ------------- choose dialogs
-
- private IFolder chooseFolder(String title, String message, IPath initialPath) {
- Class[] acceptedClasses= new Class[] { IFolder.class };
- ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses, null);
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new WorkbenchContentProvider();
-
- IProject currProject= fCurrJProject.getProject();
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
- dialog.setValidator(validator);
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.addFilter(filter);
- dialog.setInput(currProject);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- IResource res= currProject.findMember(initialPath);
- if (res != null) {
- dialog.setInitialSelection(res);
- }
-
- if (dialog.open() == Window.OK) {
- return (IFolder) dialog.getFirstResult();
- }
- return null;
- }
-
- private IJavaScriptProject chooseProject() {
- IJavaScriptProject[] projects;
- try {
- projects= JavaScriptCore.create(fWorkspaceRoot).getJavaScriptProjects();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- projects= new IJavaScriptProject[0];
- }
-
- ILabelProvider labelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT);
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
- dialog.setTitle(NewWizardMessages.NewSourceFolderWizardPage_ChooseProjectDialog_title);
- dialog.setMessage(NewWizardMessages.NewSourceFolderWizardPage_ChooseProjectDialog_description);
- dialog.setElements(projects);
- dialog.setInitialSelections(new Object[] { fCurrJProject });
- dialog.setHelpAvailable(false);
- if (dialog.open() == Window.OK) {
- return (IJavaScriptProject) dialog.getFirstResult();
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.java
deleted file mode 100644
index 4fb27fdd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.java
+++ /dev/null
@@ -1,683 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class NewWizardMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages";//$NON-NLS-1$
-
- private NewWizardMessages() {
- // Do not instantiate
- }
-
- public static String AbstractOpenWizardAction_noproject_title;
- public static String AbstractOpenWizardAction_noproject_message;
- public static String AbstractOpenWizardAction_createerror_title;
- public static String AbstractOpenWizardAction_createerror_message;
- public static String AddArchiveToBuildpathAction_DuplicateArchiveInfo_message;
- public static String AddArchiveToBuildpathAction_DuplicateArchivesInfo_message;
-
- public static String AddSourceFolderToBuildpathAction_ErrorTitle;
-
- public static String AddSourceFolderWizardPage_description;
- public static String AddSourceFolderWizardPage_addSinglePattern;
- public static String AddSourceFolderWizardPage_conflictWarning;
- public static String AddSourceFolderWizardPage_ignoreNestingConflicts;
- public static String AddSourceFolderWizardPage_replaceSourceFolderInfo;
- public static String BuildPathDialogAccess_SelectSupertType;
- public static String BuildPathDialogAccess_SuperTypeSelection;
- public static String BuildPathsBlock_GlobalOrder;
- public static String BuildPathSupport_deprecated;
- public static String ClasspathOrderingWorkbookPage_SelectReorder;
- public static String ClasspathOrderingWorkbookPage_SuperType;
- public static String CPListLabelProvider_attribute_label;
- public static String CPVariableElementLabelProvider_appendix;
- public static String CPVariableElementLabelProvider_deprecated;
- public static String CPVariableElementLabelProvider_one_restriction;
- public static String CPVariableElementLabelProvider_read_only;
- public static String CPVariableElementLabelProvider_two_restrictions;
-
- public static String ExcludeFromBuildathAction_ErrorTitle;
-
- public static String IncludeToBuildpathAction_ErrorTitle;
- public static String JavaProjectWizardFirstPage_0;
- public static String JavaProjectWizardFirstPage_1;
- public static String JavaProjectWizardFirstPage_2;
- public static String JavaProjectWizardFirstPage_EnableWorkingSet_button;
- public static String JavaProjectWizardFirstPage_Message_existingFolderInWorkspace;
- public static String JavaProjectWizardFirstPage_Message_invalidProjectNameForWorkspaceRoot;
- public static String JavaProjectWizardFirstPage_Message_notExisingProjectOnWorkspaceRoot;
- public static String JavaProjectWizardFirstPage_Message_notOnWorkspaceRoot;
- public static String JavaProjectWizardFirstPage_UnknownDefaultJRE_name;
- public static String JavaProjectWizardFirstPage_WorkingSets_group;
- public static String JavaProjectWizardFirstPage_WorkingSetSelection_message;
- public static String JavaProjectWizardSecondPage_DeleteCorruptProjectFile_message;
-
- public static String NewElementWizard_op_error_title;
- public static String NewElementWizard_op_error_message;
- public static String NewElementWizard_typecomment_deprecated_title;
- public static String NewElementWizard_typecomment_deprecated_message;
-
- public static String NewContainerWizardPage_container_label;
- public static String NewContainerWizardPage_container_button;
- public static String NewContainerWizardPage_error_EnterContainerName;
- public static String NewContainerWizardPage_error_ContainerIsBinary;
- public static String NewContainerWizardPage_error_ContainerDoesNotExist;
- public static String NewContainerWizardPage_error_NotAFolder;
- public static String NewContainerWizardPage_error_ProjectClosed;
- public static String NewContainerWizardPage_warning_NotAJavaProject;
- public static String NewContainerWizardPage_warning_NotInAJavaProject;
- public static String NewContainerWizardPage_warning_NotOnClassPath;
- public static String NewContainerWizardPage_ChooseSourceContainerDialog_title;
- public static String NewContainerWizardPage_ChooseSourceContainerDialog_description;
-
- public static String NewPackageCreationWizard_title;
-
- public static String NewPackageWizardPage_package_label;
- public static String NewPackageWizardPage_error_InvalidPackageName;
- public static String NewPackageWizardPage_error_IsOutputFolder;
- public static String NewPackageWizardPage_error_PackageExists;
- public static String NewPackageWizardPage_error_PackageExistsDifferentCase;
- public static String NewPackageWizardPage_error_EnterName;
- public static String NewPackageWizardPage_error_PackageNotShown;
- public static String NewPackageWizardPage_warning_DiscouragedPackageName;
- public static String NewPackageWizardPage_title;
- public static String NewPackageWizardPage_description;
- public static String NewPackageWizardPage_info;
- public static String NewSourceFolderWizardPage_error_ProjectNotOpen;
-
- public static String NewTypeWizardPage_package_label;
- public static String NewTypeWizardPage_package_button;
- public static String NewTypeWizardPage_enclosing_selection_label;
- public static String NewTypeWizardPage_enclosing_field_description;
- public static String NewTypeWizardPage_enclosing_button;
- public static String NewTypeWizardPage_error_InvalidPackageName;
- public static String NewTypeWizardPage_error_ClashOutputLocation;
- public static String NewTypeWizardPage_warning_DiscouragedPackageName;
- public static String NewTypeWizardPage_warning_DefaultPackageDiscouraged;
- public static String NewTypeWizardPage_warning_NotJDKCompliant;
- public static String NewTypeWizardPage_warning_EnumClassNotFound;
- public static String NewTypeWizardPage_default;
- public static String NewTypeWizardPage_ChoosePackageDialog_title;
- public static String NewTypeWizardPage_ChoosePackageDialog_description;
- public static String NewTypeWizardPage_ChoosePackageDialog_empty;
- public static String NewTypeWizardPage_ChooseEnclosingTypeDialog_title;
- public static String NewTypeWizardPage_ChooseEnclosingTypeDialog_description;
- public static String NewTypeWizardPage_error_EnclosingTypeEnterName;
- public static String NewTypeWizardPage_error_EnclosingTypeNotExists;
- public static String NewTypeWizardPage_error_EnclosingNotInCU;
- public static String NewTypeWizardPage_error_EnclosingNotEditable;
- public static String NewTypeWizardPage_warning_EnclosingNotInSourceFolder;
- public static String NewTypeWizardPage_typename_label;
- public static String NewTypeWizardPage_superclass_label;
- public static String NewTypeWizardPage_superclass_button;
- public static String NewTypeWizardPage_interfaces_class_label;
- public static String NewTypeWizardPage_interfaces_ifc_label;
- public static String NewTypeWizardPage_interfaces_add;
- public static String NewTypeWizardPage_interfaces_remove;
- public static String NewTypeWizardPage_modifiers_acc_label;
- public static String NewTypeWizardPage_modifiers_public;
- public static String NewTypeWizardPage_modifiers_private;
- public static String NewTypeWizardPage_modifiers_protected;
- public static String NewTypeWizardPage_modifiers_default;
- public static String NewTypeWizardPage_modifiers_abstract;
- public static String NewTypeWizardPage_modifiers_final;
- public static String NewTypeWizardPage_modifiers_static;
- public static String NewTypeWizardPage_addcomment_label;
- public static String NewTypeWizardPage_addcomment_description;
- public static String NewTypeWizardPage_error_EnterTypeName;
- public static String NewTypeWizardPage_error_TypeNameExists;
- public static String NewTypeWizardPage_error_TypeNameExistsDifferentCase;
- public static String NewTypeWizardPage_error_InvalidTypeName;
- public static String NewTypeWizardPage_error_QualifiedName;
- public static String NewTypeWizardPage_warning_TypeNameDiscouraged;
- public static String NewTypeWizardPage_error_TypeParameters;
- public static String NewTypeWizardPage_error_InvalidSuperClassName;
- public static String NewTypeWizardPage_error_SuperClassNotParameterized;
- public static String NewTypeWizardPage_error_InvalidSuperInterfaceName;
- public static String NewTypeWizardPage_error_SuperInterfaceNotParameterized;
- public static String NewTypeWizardPage_error_ModifiersFinalAndAbstract;
- public static String NewTypeWizardPage_configure_templates_message;
- public static String NewTypeWizardPage_configure_templates_title;
- public static String NewTypeWizardPage_SuperClassDialog_title;
- public static String NewTypeWizardPage_SuperClassDialog_message;
- public static String NewTypeWizardPage_InterfacesDialog_class_title;
- public static String NewTypeWizardPage_InterfacesDialog_interface_title;
- public static String NewTypeWizardPage_InterfacesDialog_message;
- public static String NewTypeWizardPage_operationdesc;
- public static String NewTypeWizardPage_error_uri_location_unkown;
-
- public static String RemoveFromBuildpathAction_ErrorTitle;
-
- public static String SuperInterfaceSelectionDialog_addButton_label;
- public static String SuperInterfaceSelectionDialog_interfaceadded_info;
- public static String SuperInterfaceSelectionDialog_interfacealreadyadded_info;
-
- public static String NewClassCreationWizard_title;
- public static String NewClassWizardPage_title;
- public static String NewClassWizardPage_description;
- public static String NewClassWizardPage_methods_label;
- public static String NewClassWizardPage_methods_main;
- public static String NewClassWizardPage_methods_constructors;
- public static String NewClassWizardPage_methods_inherited;
-
- public static String NewInterfaceCreationWizard_title;
- public static String NewInterfaceWizardPage_title;
- public static String NewInterfaceWizardPage_description;
-
- public static String JavaCapabilityConfigurationPage_title;
- public static String JavaCapabilityConfigurationPage_description;
- public static String JavaCapabilityConfigurationPage_op_desc_java;
-
- public static String JavaProjectWizard_title;
- public static String JavaProjectWizard_op_error_title;
- public static String JavaProjectWizard_op_error_create_message;
-
- public static String NewJavaProjectWizardPage_title;
- public static String NewJavaProjectWizardPage_description;
- public static String NewJavaProjectWizardPage_op_desc;
-
- public static String NewSourceFolderCreationWizard_title;
- public static String NewSourceFolderCreationWizard_edit_title;
- public static String NewSourceFolderCreationWizard_link_title;
- public static String NewSourceFolderWizardPage_title;
- public static String NewSourceFolderWizardPage_description;
- public static String NewSourceFolderWizardPage_root_label;
- public static String NewSourceFolderWizardPage_root_button;
- public static String NewSourceFolderWizardPage_project_label;
- public static String NewSourceFolderWizardPage_project_button;
- public static String NewSourceFolderWizardPage_operation;
- public static String NewSourceFolderWizardPage_exclude_label;
- public static String NewSourceFolderWizardPage_ChooseExistingRootDialog_title;
- public static String NewSourceFolderWizardPage_ChooseExistingRootDialog_description;
- public static String NewSourceFolderWizardPage_ChooseProjectDialog_title;
- public static String NewSourceFolderWizardPage_ChooseProjectDialog_description;
- public static String NewSourceFolderWizardPage_error_EnterRootName;
- public static String NewSourceFolderWizardPage_error_InvalidRootName;
- public static String NewSourceFolderWizardPage_error_NotAFolder;
- public static String NewSourceFolderWizardPage_error_AlreadyExisting;
- public static String NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase;
- public static String NewSourceFolderWizardPage_error_EnterProjectName;
- public static String NewSourceFolderWizardPage_error_InvalidProjectPath;
- public static String NewSourceFolderWizardPage_error_NotAJavaProject;
- public static String NewSourceFolderWizardPage_error_ProjectNotExists;
- public static String NewSourceFolderWizardPage_warning_ReplaceSFandOL;
- public static String NewSourceFolderWizardPage_warning_ReplaceOL;
- public static String NewSourceFolderWizardPage_warning_ReplaceSF;
- public static String NewSourceFolderWizardPage_warning_AddedExclusions;
- public static String NewSourceFolderWizardPage_ReplaceExistingSourceFolder_label;
- public static String NewSourceFolderWizardPage_edit_description;
-
- public static String BuildPathsBlock_tab_source;
- public static String BuildPathsBlock_tab_projects;
- public static String BuildPathsBlock_tab_libraries;
- public static String BuildPathsBlock_tab_order;
- public static String BuildPathsBlock_classpath_label;
- public static String BuildPathsBlock_classpath_up_button;
- public static String BuildPathsBlock_classpath_down_button;
- public static String BuildPathsBlock_classpath_top_button;
- public static String BuildPathsBlock_classpath_bottom_button;
- public static String BuildPathsBlock_classpath_checkall_button;
- public static String BuildPathsBlock_classpath_uncheckall_button;
- public static String BuildPathsBlock_buildpath_label;
- public static String BuildPathsBlock_buildpath_button;
- public static String BuildPathsBlock_error_InvalidBuildPath;
- public static String BuildPathsBlock_error_EnterBuildPath;
- public static String BuildPathsBlock_warning_EntryMissing;
- public static String BuildPathsBlock_warning_EntriesMissing;
- public static String BuildPathsBlock_operationdesc_project;
- public static String BuildPathsBlock_operationdesc_java;
- public static String BuildPathsBlock_ChooseOutputFolderDialog_title;
- public static String BuildPathsBlock_ChooseOutputFolderDialog_description;
- public static String BuildPathsBlock_RemoveBinariesDialog_title;
- public static String BuildPathsBlock_RemoveBinariesDialog_description;
-
- public static String CPListLabelProvider_new;
- public static String CPListLabelProvider_classcontainer;
- public static String CPListLabelProvider_twopart;
- public static String CPListLabelProvider_willbecreated;
- public static String CPListLabelProvider_unbound_library;
- public static String CPListLabelProvider_systemlibrary;
-
- public static String SourceContainerWorkbookPage_folders_label;
- public static String SourceContainerWorkbookPage_folders_remove_button;
- public static String SourceContainerWorkbookPage_folders_add_button;
- public static String SourceContainerWorkbookPage_folders_edit_button;
- public static String SourceContainerWorkbookPage_folders_check;
- public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_title;
- public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_description;
- public static String SourceContainerWorkbookPage_NewSourceFolderDialog_new_title;
- public static String SourceContainerWorkbookPage_NewSourceFolderDialog_edit_title;
- public static String SourceContainerWorkbookPage_NewSourceFolderDialog_description;
- public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_title;
- public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_and_output_message;
- public static String SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_message;
- public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_title;
- public static String SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_description;
- public static String SourceContainerWorkbookPage_exclusion_added_title;
- public static String SourceContainerWorkbookPage_exclusion_added_message;
- public static String SourceContainerWorkbookPage_folders_link_source_button;
- public static String SourceContainerWorkbookPage_error_while_linking;
-
- public static String ProjectsWorkbookPage_projects_label;
- public static String ProjectsWorkbookPage_projects_add_button;
- public static String ProjectsWorkbookPage_projects_edit_button;
- public static String ProjectsWorkbookPage_projects_remove_button;
- public static String ProjectsWorkbookPage_chooseProjects_message;
- public static String ProjectsWorkbookPage_chooseProjects_title;
-
- public static String LibrariesWorkbookPage_libraries_label;
- public static String LibrariesWorkbookPage_libraries_remove_button;
- public static String LibrariesWorkbookPage_libraries_addjar_button;
- public static String LibrariesWorkbookPage_libraries_addextjar_button;
- public static String LibrariesWorkbookPage_libraries_addvariable_button;
- public static String LibrariesWorkbookPage_libraries_addlibrary_button;
- public static String LibrariesWorkbookPage_libraries_addclassfolder_button;
- public static String LibrariesWorkbookPage_libraries_replace_button;
- public static String LibrariesWorkbookPage_configurecontainer_error_title;
- public static String LibrariesWorkbookPage_configurecontainer_error_message;
- public static String LibrariesWorkbookPage_libraries_edit_button;
- public static String LibrariesWorkbookPage_NewClassFolderDialog_new_title;
- public static String LibrariesWorkbookPage_NewClassFolderDialog_edit_title;
- public static String LibrariesWorkbookPage_NewClassFolderDialog_description;
- public static String LibrariesWorkbookPage_JavadocPropertyDialog_title;
- public static String LibrariesWorkbookPage_exclusion_added_title;
- public static String LibrariesWorkbookPage_exclusion_added_message;
-
- public static String BuildPathsBlock_tab_scriptimport;
- public static String BuildPathDialogAccess_ExistingSourceFolderDialog_new_title;
- public static String BuildPathDialogAccess_ExistingSourceFolderDialog_new_description;
- public static String BuildPathDialogAccess_ExistingClassFolderDialog_new_title;
- public static String BuildPathDialogAccess_ExistingClassFolderDialog_new_description;
- public static String BuildPathDialogAccess_JARArchiveDialog_new_title;
- public static String BuildPathDialogAccess_JARArchiveDialog_new_description;
- public static String BuildPathDialogAccess_JARArchiveDialog_edit_title;
- public static String BuildPathDialogAccess_JARArchiveDialog_edit_description;
- public static String BuildPathDialogAccess_ExtJARArchiveDialog_new_title;
- public static String BuildPathDialogAccess_ExtJARArchiveDialog_edit_title;
-
- public static String NewContainerDialog_error_invalidpath;
- public static String NewContainerDialog_error_enterpath;
- public static String NewContainerDialog_error_pathexists;
- public static String NewSourceFolderDialog_error_invalidpath;
- public static String NewSourceFolderDialog_error_enterpath;
- public static String NewSourceFolderDialog_error_pathexists;
-
- public static String SourceAttachmentBlock_message;
- public static String SourceAttachmentBlock_filename_description;
- public static String SourceAttachmentBlock_filename_label;
- public static String SourceAttachmentBlock_filename_externalfile_button;
- public static String SourceAttachmentBlock_filename_externalfolder_button;
- public static String SourceAttachmentBlock_filename_internal_button;
- public static String SourceAttachmentBlock_filename_varlabel;
- public static String SourceAttachmentBlock_filename_variable_button;
- public static String SourceAttachmentBlock_filename_external_varbutton;
- public static String SourceAttachmentBlock_filename_error_notvalid;
- public static String SourceAttachmentBlock_filename_error_notabsolute;
- public static String SourceAttachmentBlock_filename_error_filenotexists;
- public static String SourceAttachmentBlock_filename_error_varnotexists;
- public static String SourceAttachmentBlock_filename_error_deviceinpath;
- public static String SourceAttachmentBlock_filename_warning_varempty;
- public static String SourceAttachmentBlock_intjardialog_title;
- public static String SourceAttachmentBlock_intjardialog_message;
- public static String SourceAttachmentBlock_extvardialog_title;
- public static String SourceAttachmentBlock_extvardialog_description;
- public static String SourceAttachmentBlock_extjardialog_text;
- public static String SourceAttachmentBlock_extfolderdialog_text;
-
- public static String BuildPathSupport_putoncpdialog_title;
- public static String BuildPathSupport_putoncpdialog_message;
-
- public static String SourceAttachmentDialog_title;
- public static String EditVariableEntryDialog_title;
- public static String EditVariableEntryDialog_filename_varlabel;
- public static String EditVariableEntryDialog_filename_variable_button;
- public static String EditVariableEntryDialog_filename_external_varbutton;
- public static String EditVariableEntryDialog_extvardialog_title;
- public static String EditVariableEntryDialog_extvardialog_description;
- public static String EditVariableEntryDialog_filename_error_notvalid;
- public static String EditVariableEntryDialog_filename_error_filenotexists;
- public static String EditVariableEntryDialog_filename_error_varnotexists;
- public static String EditVariableEntryDialog_filename_error_deviceinpath;
- public static String EditVariableEntryDialog_filename_warning_varempty;
- public static String EditVariableEntryDialog_filename_error_alreadyexists;
-
- public static String VariableBlock_vars_label;
- public static String VariableBlock_vars_add_button;
- public static String VariableBlock_vars_edit_button;
- public static String VariableBlock_vars_remove_button;
- public static String VariableBlock_operation_desc;
- public static String VariableBlock_job_description;
- public static String VariableBlock_needsbuild_title;
- public static String VariableBlock_needsbuild_message;
- public static String VariableBlock_variableSettingError_titel;
- public static String VariableBlock_variableSettingError_message;
- public static String VariablePathDialogField_variabledialog_title;
-
- public static String CPVariableElementLabelProvider_empty;
-
- public static String VariableCreationDialog_titlenew;
- public static String VariableCreationDialog_titleedit;
- public static String VariableCreationDialog_name_label;
- public static String VariableCreationDialog_path_label;
- public static String VariableCreationDialog_path_file_button;
- public static String VariableCreationDialog_path_dir_button;
- public static String VariableCreationDialog_error_entername;
- public static String VariableCreationDialog_error_whitespace;
- public static String VariableCreationDialog_error_invalidname;
- public static String VariableCreationDialog_error_nameexists;
- public static String VariableCreationDialog_error_invalidpath;
- public static String VariableCreationDialog_warning_pathnotexists;
- public static String VariableCreationDialog_extjardialog_text;
- public static String VariableCreationDialog_extdirdialog_text;
- public static String VariableCreationDialog_extdirdialog_message;
-
- public static String NewVariableEntryDialog_title;
- public static String NewVariableEntryDialog_vars_extend;
- public static String NewVariableEntryDialog_configbutton_label;
- public static String NewVariableEntryDialog_vars_label;
- public static String NewVariableEntryDialog_ExtensionDialog_title;
- public static String NewVariableEntryDialog_ExtensionDialog_description;
- public static String NewVariableEntryDialog_info_isfolder;
- public static String NewVariableEntryDialog_info_notexists;
- public static String NewVariableEntryDialog_info_noselection;
- public static String NewVariableEntryDialog_info_selected;
-
- public static String ExclusionInclusionDialog_title;
- public static String ExclusionInclusionDialog_description;
- public static String ExclusionInclusionDialog_description2;
- public static String ExclusionInclusionDialog_exclusion_pattern_label;
- public static String ExclusionInclusionDialog_inclusion_pattern_label;
- public static String ExclusionInclusionDialog_inclusion_pattern_add;
- public static String ExclusionInclusionDialog_inclusion_pattern_add_multiple;
- public static String ExclusionInclusionDialog_inclusion_pattern_remove;
- public static String ExclusionInclusionDialog_inclusion_pattern_edit;
- public static String ExclusionInclusionDialog_exclusion_pattern_add;
- public static String ExclusionInclusionDialog_exclusion_pattern_add_multiple;
- public static String ExclusionInclusionDialog_exclusion_pattern_remove;
- public static String ExclusionInclusionDialog_exclusion_pattern_edit;
- public static String ExclusionInclusionDialog_ChooseExclusionPattern_title;
- public static String ExclusionInclusionDialog_ChooseExclusionPattern_description;
- public static String ExclusionInclusionDialog_ChooseInclusionPattern_title;
- public static String ExclusionInclusionDialog_ChooseInclusionPattern_description;
- public static String ExclusionInclusionDialog_Info_SrcAndOutput;
- public static String ExclusionInclusionDialog_Info_Src;
- public static String ExclusionInclusionDialog_Info_Output;
- public static String ExclusionInclusionEntryDialog_exclude_add_title;
- public static String ExclusionInclusionEntryDialog_exclude_edit_title;
- public static String ExclusionInclusionEntryDialog_exclude_description;
- public static String ExclusionInclusionEntryDialog_exclude_pattern_label;
- public static String ExclusionInclusionEntryDialog_include_add_title;
- public static String ExclusionInclusionEntryDialog_include_edit_title;
- public static String ExclusionInclusionEntryDialog_include_description;
- public static String ExclusionInclusionEntryDialog_include_pattern_label;
- public static String ExclusionInclusionEntryDialog_pattern_button;
- public static String ExclusionInclusionEntryDialog_error_empty;
- public static String ExclusionInclusionEntryDialog_error_notrelative;
- public static String ExclusionInclusionEntryDialog_error_exists;
- public static String ExclusionInclusionEntryDialog_ChooseExclusionPattern_title;
- public static String ExclusionInclusionEntryDialog_ChooseExclusionPattern_description;
- public static String ExclusionInclusionEntryDialog_ChooseInclusionPattern_title;
- public static String ExclusionInclusionEntryDialog_ChooseInclusionPattern_description;
-
- public static String AccessRulesDialog_title;
- public static String AccessRulesDialog_container_description;
- public static String AccessRulesDialog_project_description;
- public static String AccessRulesDialog_description;
- public static String AccessRulesDialog_rules_label;
- public static String AccessRulesDialog_rules_add;
- public static String AccessRulesDialog_rules_up;
- public static String AccessRulesDialog_rules_remove;
- public static String AccessRulesDialog_combine_label;
- public static String AccessRulesDialog_rules_edit;
- public static String AccessRulesDialog_rules_down;
- public static String AccessRulesLabelProvider_kind_accessible;
- public static String AccessRulesLabelProvider_kind_discouraged;
- public static String AccessRulesLabelProvider_kind_non_accessible;
-
- public static String TypeRestrictionEntryDialog_add_title;
- public static String TypeRestrictionEntryDialog_edit_title;
- public static String TypeRestrictionEntryDialog_pattern_label;
- public static String TypeRestrictionEntryDialog_description;
- public static String TypeRestrictionEntryDialog_description2;
- public static String TypeRestrictionEntryDialog_error_empty;
- public static String TypeRestrictionEntryDialog_error_notrelative;
- public static String TypeRestrictionEntryDialog_kind_accessible;
- public static String TypeRestrictionEntryDialog_kind_label;
- public static String TypeRestrictionEntryDialog_kind_discourraged;
- public static String TypeRestrictionEntryDialog_kind_non_accessible;
-
- public static String JsGlobalScopeContainerDefaultPage_title;
- public static String JsGlobalScopeContainerDefaultPage_description;
- public static String JsGlobalScopeContainerDefaultPage_path_label;
- public static String JsGlobalScopeContainerDefaultPage_path_error_enterpath;
- public static String JsGlobalScopeContainerDefaultPage_path_error_invalidpath;
- public static String JsGlobalScopeContainerDefaultPage_path_error_needssegment;
- public static String JsGlobalScopeContainerDefaultPage_path_error_alreadyexists;
- public static String JsGlobalScopeContainerSelectionPage_title;
- public static String JsGlobalScopeContainerSelectionPage_description;
- public static String JsGlobalScopeContainerWizard_pagecreationerror_title;
- public static String JsGlobalScopeContainerWizard_pagecreationerror_message;
- public static String JsGlobalScopeContainerWizard_new_title;
- public static String JsGlobalScopeContainerWizard_edit_title;
-
- public static String FolderSelectionDialog_button;
- public static String MultipleFolderSelectionDialog_button;
-
- public static String CPListLabelProvider_none;
- public static String CPListLabelProvider_all;
- public static String CPListLabelProvider_source_attachment_label;
- public static String CPListLabelProvider_javadoc_location_label;
- public static String CPListLabelProvider_output_folder_label;
- public static String CPListLabelProvider_default_output_folder_label;
- public static String CPListLabelProvider_exclusion_filter_label;
- public static String CPListLabelProvider_exclusion_filter_separator;
- public static String CPListLabelProvider_inclusion_filter_label;
- public static String CPListLabelProvider_inclusion_filter_separator;
- public static String CPListLabelProvider_unknown_element_label;
- public static String CPListLabelProvider_access_rules_enabled;
- public static String CPListLabelProvider_project_access_rules_combined;
- public static String CPListLabelProvider_project_access_rules_no_rules;
- public static String CPListLabelProvider_project_access_rules_not_combined;
- public static String CPListLabelProvider_access_rules_disabled;
-
- public static String NewSourceFolderDialog_useproject_button;
- public static String NewSourceFolderDialog_usefolder_button;
- public static String NewSourceFolderDialog_sourcefolder_label;
-
- public static String JavaProjectWizardFirstPage_NameGroup_label_text;
- public static String JavaProjectWizardFirstPage_LocationGroup_title;
- public static String JavaProjectWizardFirstPage_LocationGroup_external_desc;
- public static String JavaProjectWizardFirstPage_LocationGroup_workspace_desc;
- public static String JavaProjectWizardFirstPage_LocationGroup_locationLabel_desc;
- public static String JavaProjectWizardFirstPage_LocationGroup_browseButton_desc;
- public static String JavaProjectWizardFirstPage_LayoutGroup_title;
- public static String JavaProjectWizardFirstPage_LayoutGroup_option_separateFolders;
- public static String JavaProjectWizardFirstPage_LayoutGroup_option_oneFolder;
- public static String JavaProjectWizardFirstPage_LayoutGroup_configure;
- public static String JavaProjectWizardFirstPage_DetectGroup_message;
- public static String JavaProjectWizardFirstPage_Message_enterProjectName;
- public static String JavaProjectWizardFirstPage_Message_projectAlreadyExists;
- public static String JavaProjectWizardFirstPage_Message_enterLocation;
- public static String JavaProjectWizardFirstPage_Message_invalidDirectory;
- public static String JavaProjectWizardFirstPage_Message_cannotCreateAtExternalLocation;
- public static String JavaProjectWizardFirstPage_page_pageName;
- public static String JavaProjectWizardFirstPage_page_title;
- public static String JavaProjectWizardFirstPage_page_description;
-
- public static String HintTextGroup_Exception_Title;
- public static String HintTextGroup_Exception_Title_refresh;
- public static String HintTextGroup_Exception_Title_output;
- public static String HintTextGroup_NoAction;
-
- public static String NewSourceContainerWorkbookPage_Exception_Title;
- public static String NewSourceContainerWorkbookPage_Exception_refresh;
- public static String NewSourceContainerWorkbookPage_HintTextGroup_title;
- public static String NewSourceContainerWorkbookPage_ToolBar_CreateFolder_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Edit_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_EditOutput_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_EditOutput_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_label;
-
- public static String NewSourceContainerWorkbookPage_ToolBar_AddJarCP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddJarCP_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddLibCP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_AddLibCP_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Include_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Exclude_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Uninclude_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Unexclude_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Reset_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_ClearAll_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_CreateOutput_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Link_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Link_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Help_tooltip;
- public static String NewSourceContainerWorkbookPage_ToolBar_Help_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_Help_link;
- public static String NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_label;
- public static String NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_tooltip;
-
- public static String NewFolderDialog_linkTargetNonExistent;
- public static String NewFolderDialog_linkTargetNotFolder;
- public static String NewFolderDialog_folderNameEmpty;
- public static String NewFolderDialog_folderNameEmpty_alreadyExists;
- public static String NewFolderDialog_errorTitle;
- public static String NewFolderDialog_internalError;
- public static String NewFolderDialog_progress;
- public static String NewFolderDialog_createIn;
-
- public static String LinkFolderDialog_title;
- public static String LinkFolderDialog_createIn;
- public static String LinkFolderDialog_folderNameGroup_label;
- public static String LinkFolderDialog_dependenciesGroup_locationLabel_desc;
- public static String LinkFolderDialog_dependenciesGroup_browseButton_desc;
- public static String LinkFolderDialog_dependenciesGroup_variables_desc;
-
- public static String PackageExplorerActionGroup_NoAction_NullSelection;
- public static String PackageExplorerActionGroup_NoAction_MultiSelection;
- public static String PackageExplorerActionGroup_NoAction_NoReason;
- public static String PackageExplorerActionGroup_FormText_createLinkedFolder;
- public static String PackageExplorerActionGroup_FormText_FolderToBuildpath;
- public static String PackageExplorerActionGroup_FormText_PackageToBuildpath;
- public static String PackageExplorerActionGroup_FormText_ProjectToBuildpath;
- public static String PackageExplorerActionGroup_FormText_fromBuildpath;
- public static String PackageExplorerActionGroup_FormText_ProjectFromBuildpath;
- public static String PackageExplorerActionGroup_FormText_ExcludePackage;
- public static String PackageExplorerActionGroup_FormText_ExcludeFile;
- public static String PackageExplorerActionGroup_FormText_Edit;
- public static String PackageExplorerActionGroup_FormText_UnexcludeFolder;
- public static String PackageExplorerActionGroup_FormText_UnexcludeFile;
- public static String PackageExplorerActionGroup_FormText_Default_Unexclude;
- public static String PackageExplorerActionGroup_FormText_Default_FromBuildpath;
- public static String PackageExplorerActionGroup_FormText_Default_Exclude;
- public static String PackageExplorerActionGroup_FormText_Default_toBuildpath;
- public static String PackageExplorerActionGroup_FormText_Default_ResetAll;
- public static String PackageExplorerActionGroup_FormText_createNewSourceFolder;
-
- public static String DialogPackageExplorer_LabelProvider_Excluded;
- public static String DialogPackageExplorer_LabelProvider_SingleExcluded;
- public static String DialogPackageExplorer_LabelProvider_MultiExcluded;
-
- public static String ClasspathModifier_Monitor_AddToBuildpath;
- public static String ClasspathModifier_Monitor_RemoveFromBuildpath;
- public static String ClasspathModifier_Monitor_ResetFilters;
- public static String ClasspathModifier_Monitor_Including;
- public static String ClasspathModifier_Monitor_Excluding;
- public static String ClasspathModifier_Monitor_RemoveExclusion;
- public static String ClasspathModifier_Monitor_ContainsPath;
- public static String ClasspathModifier_Monitor_ExamineInputFilters;
- public static String ClasspathModifier_Monitor_RemovePath;
- public static String ClasspathModifier_Monitor_CheckOutputFolders;
- public static String ClasspathModifier_Monitor_SetNewEntry;
- public static String ClasspathModifier_Monitor_ComparePaths;
- public static String ClasspathModifier_ChangeOutputLocationDialog_title;
- public static String ClasspathModifier_ChangeOutputLocationDialog_project_message;
- public static String ClasspathModifier_ChangeOutputLocationDialog_project_outputLocation;
- public static String ClasspathModifier_Error_NoNatures;
-
- public static String ClassPathDetector_operation_description;
-
- public static String JavaProjectWizardSecondPage_error_title;
- public static String JavaProjectWizardSecondPage_error_message;
- public static String JavaProjectWizardSecondPage_problem_backup;
- public static String JavaProjectWizardSecondPage_operation_initialize;
- public static String JavaProjectWizardSecondPage_operation_create;
- public static String JavaProjectWizardSecondPage_operation_remove;
- public static String JavaProjectWizardSecondPage_error_remove_title;
- public static String JavaProjectWizardSecondPage_error_remove_message;
- public static String JavaProjectWizardSecondPage_problem_restore_project;
- public static String JavaProjectWizardSecondPage_problem_restore_classpath;
- public static String JavaProjectWizardFirstPage_directory_message;
-
- public static String UserLibraryWizardPage_title;
- public static String UserLibraryWizardPage_list_config_button;
- public static String UserLibraryWizardPage_list_label;
- public static String UserLibraryWizardPage_description_new;
- public static String UserLibraryWizardPage_description_edit;
- public static String UserLibraryWizardPage_error_selectentry;
- public static String UserLibraryWizardPage_error_selectonlyone;
- public static String UserLibraryWizardPage_error_alreadyoncp;
- public static String UserLibraryMarkerResolutionGenerator_changetouserlib_label;
- public static String UserLibraryMarkerResolutionGenerator_createuserlib_label;
- public static String UserLibraryMarkerResolutionGenerator_changetoother;
- public static String UserLibraryMarkerResolutionGenerator_error_creationfailed_message;
- public static String UserLibraryMarkerResolutionGenerator_error_title;
- public static String UserLibraryMarkerResolutionGenerator_error_applyingfailed_message;
-
- public static String BaseLibraryWizardPage_title;
- public static String BaseLibraryWizardPage_DefaultBrowserLibraryAdded;
- public static String BaseLibraryWizardPage_WebBrowserSupport;
-
- public static String NewContainerWizardPage_warning_inside_classfolder;
-
- public static String CPListLabelProvider_access_rules_label;
- public static String CPListLabelProvider_container_access_rules;
- public static String CPListLabelProvider_container_no_access_rules;
-
- public static String SourceAttachmentBlock_extfolderdialog_message;
- public static String AccessRulesDialog_severity_info_with_link;
- public static String AccessRulesDialog_severity_info_no_link;
- public static String AccessRulesDialog_severity_error;
- public static String AccessRulesDialog_severity_warning;
- public static String AccessRulesDialog_severity_ignore;
- public static String AccessRulesDialog_switch_dialog_title;
- public static String AccessRulesDialog_switch_dialog_message;
- public static String JavaProjectWizardFirstPage_LayoutGroup_link_description;
- public static String ClasspathModifierQueries_confirm_remove_linked_folder_label;
- public static String ClasspathModifierQueries_confirm_remove_linked_folder_message;
- public static String ClasspathModifierQueries_delete_linked_folder;
- public static String ClasspathModifierQueries_do_not_delete_linked_folder;
- public static String EditVariableEntryDialog_filename_empty;
-
- public static String Javascript_UI_Wizard_New_Description;
- public static String Javascript_UI_Wizard_New_Heading;
- public static String Javascript_UI_Wizard_New_Title;
- public static String Javascript_Error_Filename_Must_End_JS;
- public static String Javascript_Resource_Group_Name_Exists;
- public static String Javascript_Warning_Folder_Must_Be_Inside_Web_Content;
- static {
- NLS.initializeMessages(BUNDLE_NAME, NewWizardMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties
deleted file mode 100644
index 8c056296..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties
+++ /dev/null
@@ -1,901 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2010 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-# ------- AbstractOpenWizardAction -------
-
-AbstractOpenWizardAction_noproject_title=New
-AbstractOpenWizardAction_noproject_message=A project needs to be created first.\nOpen the 'New Project' wizard'?
-
-AbstractOpenWizardAction_createerror_title=Open Wizard
-AbstractOpenWizardAction_createerror_message=The wizard could not be opened. See log for details.
-
-# ------- NewElementWizard -------
-
-NewElementWizard_op_error_title=New
-NewElementWizard_op_error_message=Creation of element failed.
-
-NewElementWizard_typecomment_deprecated_title=Type Creation
-NewElementWizard_typecomment_deprecated_message=You can configure the default layout of newly created files and types on the 'code generation' preference page. This was previously implemented on the template page in the templates 'filecomment' and 'typecomment'.
-# ------- NewContainerWizardPage -------
-
-NewContainerWizardPage_container_label=Source fol&der:
-NewContainerWizardPage_container_button=Br&owse...
-
-NewContainerWizardPage_error_EnterContainerName=Source folder name is empty.
-NewContainerWizardPage_error_ContainerIsBinary=''{0}'' is a JAR archive.
-NewContainerWizardPage_error_ContainerDoesNotExist=Folder ''{0}'' does not exist.
-NewContainerWizardPage_error_NotAFolder=''{0}'' must be a project or folder.
-NewContainerWizardPage_error_ProjectClosed=Project ''{0}'' must be accessible.
-
-NewContainerWizardPage_warning_NotAJavaProject=Source folder is not a JavaScript project.
-NewContainerWizardPage_warning_NotInAJavaProject=Source folder is not in a JavaScript project.
-NewContainerWizardPage_warning_inside_classfolder=''{0}'' is a library folder.
-NewContainerWizardPage_warning_NotOnClassPath=Source folder is not on the JavaScript include path.
-
-NewContainerWizardPage_ChooseSourceContainerDialog_title=Source Folder Selection
-NewContainerWizardPage_ChooseSourceContainerDialog_description=&Choose a source folder:
-
-# ------- NewPackageWizardPage -------
-
-NewPackageCreationWizard_title=New JavaScript directory
-
-NewPackageWizardPage_package_label=Na&me:
-
-NewPackageWizardPage_error_InvalidPackageName=Invalid package name. {0}
-NewPackageWizardPage_error_IsOutputFolder=Name conflict with output folder.
-
-NewPackageWizardPage_error_PackageExists=Package already exists.
-NewPackageWizardPage_error_PackageExistsDifferentCase=Package already exists with a different case
-NewPackageWizardPage_error_EnterName=Enter a package name.
-NewPackageWizardPage_error_PackageNotShown=Package already exists. Note: Views might filter empty parent packages.
-NewPackageWizardPage_warning_DiscouragedPackageName=Discouraged package name. {0}
-
-NewPackageWizardPage_title=JavaScript Package
-NewPackageWizardPage_description=Create a JavaScript package.
-NewPackageWizardPage_info=Creates folders corresponding to packages.
-
-# ------- NewTypeWizardPage -------
-
-NewTypeWizardPage_package_label=Pac&kage:
-NewTypeWizardPage_package_button=Bro&wse...
-
-NewTypeWizardPage_enclosing_selection_label=Enclosing t&ype:
-NewTypeWizardPage_enclosing_field_description=Enclosing type name
-NewTypeWizardPage_enclosing_button=Bro&wse...
-
-NewTypeWizardPage_error_InvalidPackageName=Package name is not valid. {0}
-NewTypeWizardPage_error_ClashOutputLocation=Package clashes with project output folder.
-NewTypeWizardPage_error_uri_location_unkown=Cannot locate resource {0}
-NewTypeWizardPage_warning_DiscouragedPackageName=This package name is discouraged. {0}
-NewTypeWizardPage_warning_DefaultPackageDiscouraged=The use of the default package is discouraged.
-NewTypeWizardPage_warning_NotJDKCompliant=Project ''{0}'' is not a JDK 5.0 compliant project.
-NewTypeWizardPage_warning_EnumClassNotFound=Type 'java.lang.Enum' is not on the project's build path. Make sure you use a 5.0 JDK.
-
-NewTypeWizardPage_default=(default)
-NewTypeWizardPage_ChoosePackageDialog_title=Package Selection
-NewTypeWizardPage_ChoosePackageDialog_description=&Choose a folder:
-NewTypeWizardPage_ChoosePackageDialog_empty=Cannot find packages to select.
-
-NewTypeWizardPage_ChooseEnclosingTypeDialog_title=Enclosing Type Selection
-NewTypeWizardPage_ChooseEnclosingTypeDialog_description=&Choose a type to which the new class will be added:
-
-NewTypeWizardPage_error_EnclosingTypeEnterName=Name of enclosing type must be entered.
-NewTypeWizardPage_error_EnclosingTypeNotExists=Enclosing type does not exist.
-NewTypeWizardPage_error_EnclosingNotInCU=Enclosing type is binary.
-NewTypeWizardPage_error_EnclosingNotEditable=Enclosing type is not editable.
-NewTypeWizardPage_warning_EnclosingNotInSourceFolder=Enclosing type is not in specified source folder.
-
-NewTypeWizardPage_typename_label=Na&me:
-
-NewTypeWizardPage_superclass_label=&Superclass:
-NewTypeWizardPage_superclass_button=Brows&e...
-
-NewTypeWizardPage_interfaces_class_label=&Interfaces:
-NewTypeWizardPage_interfaces_ifc_label=Extended &interfaces:
-NewTypeWizardPage_interfaces_add=&Add...
-NewTypeWizardPage_interfaces_remove=&Remove
-
-NewTypeWizardPage_modifiers_acc_label=Modifiers:
-NewTypeWizardPage_modifiers_public=&public
-NewTypeWizardPage_modifiers_private=pri&vate
-NewTypeWizardPage_modifiers_protected=pro&tected
-NewTypeWizardPage_modifiers_default=defa&ult
-NewTypeWizardPage_modifiers_abstract=abs&tract
-NewTypeWizardPage_modifiers_final=fina&l
-NewTypeWizardPage_modifiers_static=stati&c
-NewTypeWizardPage_addcomment_label=&Generate comments
-NewTypeWizardPage_addcomment_description=Do you want to add comments as configured in the <a>properties</a> of the current project?
-NewTypeWizardPage_error_EnterTypeName=Type name is empty.
-NewTypeWizardPage_error_TypeNameExists=Type already exists.
-NewTypeWizardPage_error_TypeNameExistsDifferentCase=Type with same name but different case exists.
-NewTypeWizardPage_error_InvalidTypeName=Type name is not valid. {0}
-NewTypeWizardPage_error_QualifiedName=Type name must not be qualified.
-NewTypeWizardPage_warning_TypeNameDiscouraged=Type name is discouraged. {0}
-NewTypeWizardPage_error_TypeParameters=Type name is not valid. Type parameters are only available if source level is 5.0.
-
-NewTypeWizardPage_error_InvalidSuperClassName=Superclass type is not valid.
-NewTypeWizardPage_error_SuperClassNotParameterized=Superclass cannot be parameterized unless source level is 5.0.
-NewTypeWizardPage_error_InvalidSuperInterfaceName=Extended interface ''{0}'' is not valid.
-NewTypeWizardPage_error_SuperInterfaceNotParameterized=Extended interface ''{0}'' cannot be parameterized unless source level is 5.0.
-
-NewTypeWizardPage_error_ModifiersFinalAndAbstract=Class cannot be both final and abstract
-
-NewTypeWizardPage_configure_templates_message=Can not open the project properties. The wizard page does not yet specify a valid project.
-NewTypeWizardPage_configure_templates_title=Configure Code Templates
-
-NewTypeWizardPage_SuperClassDialog_title=Superclass Selection
-NewTypeWizardPage_SuperClassDialog_message=&Choose a type:
-
-NewTypeWizardPage_InterfacesDialog_class_title= Implemented Interfaces Selection
-NewTypeWizardPage_InterfacesDialog_interface_title= Extended Interfaces Selection
-NewTypeWizardPage_InterfacesDialog_message=&Choose interfaces:
-
-NewTypeWizardPage_operationdesc=Creating type....
-
-# ------- SuperInterfaceSelectionDialog -----
-
-SuperInterfaceSelectionDialog_addButton_label=&Add
-SuperInterfaceSelectionDialog_interfaceadded_info=''{0}'' added.
-SuperInterfaceSelectionDialog_interfacealreadyadded_info=''{0}'' already in list.
-
-# ------- NewClassWizardPage -------
-
-NewClassCreationWizard_title=New Java Class
-
-NewClassWizardPage_title=Java Class
-NewClassWizardPage_description=Create a new Java class.
-
-NewClassWizardPage_methods_label=Which function stubs would you like to create?
-NewClassWizardPage_methods_main=pu&blic static void main(String[] args)
-NewClassWizardPage_methods_constructors=&Constructors from superclass
-NewClassWizardPage_methods_inherited=In&herited abstract methods
-
-
-# ------- NewInterfaceWizardPage -------
-
-NewInterfaceCreationWizard_title=New JavaScript Interface
-
-NewInterfaceWizardPage_title=JavaScript Interface
-NewInterfaceWizardPage_description=Create a new Java interface.
-
-
-# ------- JavaCapabilityConfigurationPage -------
-
-JavaCapabilityConfigurationPage_title=JavaScript Settings
-JavaCapabilityConfigurationPage_description=Define the JavaScript project's build settings. This will determine which files will be validated and made available for content assist.
-JavaCapabilityConfigurationPage_op_desc_java=Configuring JavaScript project...
-
-
-# ------- JavaProjectWizard -------
-
-JavaProjectWizard_title=New JavaScript Project
-JavaProjectWizard_op_error_title=Error Creating JavaScript Project
-JavaProjectWizard_op_error_create_message=An error occurred while creating the JavaScript project
-
-
-# ------- NewJavaProjectWizardPage-------
-
-NewJavaProjectWizardPage_title=JavaScript Settings
-NewJavaProjectWizardPage_description=Define the JavaScript build settings.
-
-NewJavaProjectWizardPage_op_desc=Creating JavaScript project...
-
-
-# ------- NewSourceFolderWizardPage-------
-
-NewSourceFolderCreationWizard_title=New Source Folder
-NewSourceFolderCreationWizard_edit_title=Edit source folder
-NewSourceFolderCreationWizard_link_title=Link Source
-
-NewSourceFolderWizardPage_title=Source folder
-NewSourceFolderWizardPage_description=Add a new source folder.
-NewSourceFolderWizardPage_edit_description=Edit source folder
-
-NewSourceFolderWizardPage_root_label=Fol&der name:
-NewSourceFolderWizardPage_root_button=Br&owse...
-
-NewSourceFolderWizardPage_project_label=Project &name:
-NewSourceFolderWizardPage_project_button=Bro&wse...
-
-NewSourceFolderWizardPage_operation=Creating new source folder...
-
-NewSourceFolderWizardPage_exclude_label=&Update exclusion filters in other source folders to solve nesting
-
-NewSourceFolderWizardPage_ChooseExistingRootDialog_title=Existing Folder Selection
-NewSourceFolderWizardPage_ChooseExistingRootDialog_description=&Choose folder as source folder:
-
-NewSourceFolderWizardPage_ChooseProjectDialog_title=Project Selection
-NewSourceFolderWizardPage_ChooseProjectDialog_description=&Choose project for the new source folder:
-
-NewSourceFolderWizardPage_error_EnterRootName=Root name must be entered.
-NewSourceFolderWizardPage_error_InvalidRootName=Invalid folder name. {0}
-NewSourceFolderWizardPage_error_NotAFolder=Not a folder.
-NewSourceFolderWizardPage_error_AlreadyExisting=The folder is already a source folder.
-NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase=Folder already exists with a different case
-NewSourceFolderWizardPage_ReplaceExistingSourceFolder_label=Replace existing project source folder entry to solve nesting
-
-NewSourceFolderWizardPage_error_EnterProjectName=Project name must be entered.
-NewSourceFolderWizardPage_error_InvalidProjectPath=Invalid project path.
-NewSourceFolderWizardPage_error_NotAJavaProject=Project is not a JavaScript project.
-NewSourceFolderWizardPage_error_ProjectNotExists=Project does not exist.
-NewSourceFolderWizardPage_error_ProjectNotOpen=Project is not open.
-
-NewSourceFolderWizardPage_warning_ReplaceSFandOL=To avoid overlapping, the existing project source folder entry will be replaced and the output folder set to ''{0}''.
-NewSourceFolderWizardPage_warning_ReplaceOL=An exclusion pattern will be added to the project source folder entry and the output folder will be set to ''{0}''.
-NewSourceFolderWizardPage_warning_ReplaceSF=To avoid overlapping, the existing project source folder entry will be replaced.
-NewSourceFolderWizardPage_warning_AddedExclusions=Exclusion patterns of {0} source folder(s) updated to solve nesting.
-
-# ------- BuildPathsBlock -------
-
-BuildPathsBlock_tab_source=&Source
-BuildPathsBlock_tab_projects=&Projects
-BuildPathsBlock_GlobalOrder=&Global SuperType
-BuildPathsBlock_tab_libraries=&Libraries
-BuildPathsBlock_tab_scriptimport=&Libraries
-BuildPathsBlock_tab_order=&Global SuperType
-
-#BuildPathsBlock_classpath_label=Build &class path order and exported entries:\n(Exported entries are contributed to dependent projects)
-BuildPathsBlock_classpath_label=Project exports and JSDT Global Scope Resolution Order:
-
-BuildPathsBlock_classpath_up_button=&Up
-BuildPathsBlock_classpath_down_button=&Down
-BuildPathsBlock_classpath_top_button=&Top
-BuildPathsBlock_classpath_bottom_button=Botto&m
-BuildPathsBlock_classpath_checkall_button=Select &All
-BuildPathsBlock_classpath_uncheckall_button=D&eselect All
-
-BuildPathsBlock_buildpath_label=Defaul&t output folder:
-BuildPathsBlock_buildpath_button=Bro&wse...
-
-BuildPathsBlock_error_InvalidBuildPath=Invalid build output folder: ''{0}''
-BuildPathsBlock_error_EnterBuildPath=Build output folder must be entered.
-
-BuildPathsBlock_warning_EntryMissing=Build path entry is missing: {0}
-BuildPathsBlock_warning_EntriesMissing={0} build path entries are missing.
-
-BuildPathsBlock_operationdesc_project=Creating project...
-BuildPathsBlock_operationdesc_java=Setting build paths...
-
-BuildPathsBlock_ChooseOutputFolderDialog_title=Folder Selection
-BuildPathsBlock_ChooseOutputFolderDialog_description=&Choose the folder for the build output:
-
-BuildPathsBlock_RemoveBinariesDialog_title=Setting Build Paths
-BuildPathsBlock_RemoveBinariesDialog_description=The output folder has changed. Do you want to remove all generated resources from the old location ''{0}''?
-
-# ------- CPListLabelProvider -------
-
-CPListLabelProvider_new=(new)
-CPListLabelProvider_classcontainer=(library folder)
-CPListLabelProvider_twopart={0} - {1}
-CPListLabelProvider_willbecreated=(missing)
-CPListLabelProvider_unbound_library={0} (unbound)
-CPListLabelProvider_attribute_label={0}: {1}
-CPListLabelProvider_systemlibrary={0} [system library]
-
-
-# ------- SourceContainerWorkbookPage-------
-
-SourceContainerWorkbookPage_folders_label=Source files and folders in the Global Scope:
-SourceContainerWorkbookPage_folders_remove_button=&Remove
-SourceContainerWorkbookPage_folders_link_source_button=Link E&xternal Folder...
-SourceContainerWorkbookPage_folders_add_button=&Add Folder...
-SourceContainerWorkbookPage_folders_edit_button=&Edit...
-SourceContainerWorkbookPage_error_while_linking=Error while linking new source to the project
-
-SourceContainerWorkbookPage_folders_check=Allow output folders for sour&ce folders
-
-SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_title=Source Folder Selection
-SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_description=&Choose source folders to be added to the build path:
-
-SourceContainerWorkbookPage_NewSourceFolderDialog_new_title=New Source Folder
-SourceContainerWorkbookPage_NewSourceFolderDialog_edit_title=Edit Source Folder
-
-SourceContainerWorkbookPage_NewSourceFolderDialog_description=&Enter a path relative to ''{0}'':
-
-SourceContainerWorkbookPage_ChangeOutputLocationDialog_title=Source Folder Added
-SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_and_output_message=Do you want to remove the project as source folder and update build output folder to ''{0}''?
-SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_message=Do you want to remove the project as source folder?
-
-SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_title=Source Folder Selection
-SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_description=&Select the source folder:
-
-SourceContainerWorkbookPage_exclusion_added_title=Source Folder Added
-SourceContainerWorkbookPage_exclusion_added_message=Exclusion filters have been added to nesting folders.
-
-# ------- ProjectsWorkbookPage-------
-
-ProjectsWorkbookPage_projects_label=&Referenced Projects:
-ProjectsWorkbookPage_projects_add_button=&Add...
-ProjectsWorkbookPage_projects_edit_button=Edi&t...
-ProjectsWorkbookPage_projects_remove_button=Re&move
-ProjectsWorkbookPage_chooseProjects_message=Select projects to add:
-ProjectsWorkbookPage_chooseProjects_title=Referenced Project Selection
-
-# ------- LibrariesWorkbookPage-------
-
-# LibrariesWorkbookPage_libraries_label=JARs &and class folders on the build path:
-LibrariesWorkbookPage_libraries_label=JavaScript Libraries:
-LibrariesWorkbookPage_libraries_remove_button=&Remove
-LibrariesWorkbookPage_libraries_replace_button=Migrate JAR &File...
-
-LibrariesWorkbookPage_libraries_addjar_button=Add &File From Project...
-LibrariesWorkbookPage_libraries_addextjar_button=Add File From F&ilesystem...
-LibrariesWorkbookPage_libraries_addvariable_button=Add &Variable...
-LibrariesWorkbookPage_libraries_addlibrary_button=Add JavaScript Li&brary...
-LibrariesWorkbookPage_libraries_addclassfolder_button=Add a Library Folder...
-
-LibrariesWorkbookPage_configurecontainer_error_title=Configure Source Attachment
-LibrariesWorkbookPage_configurecontainer_error_message=An error occurred while associating the source.
-
-LibrariesWorkbookPage_libraries_edit_button=&Edit...
-
-LibrariesWorkbookPage_NewClassFolderDialog_new_title=New Class Folder
-LibrariesWorkbookPage_NewClassFolderDialog_edit_title=Edit Class Folder
-
-LibrariesWorkbookPage_NewClassFolderDialog_description=&Enter a path relative to ''{0}'':
-
-LibrariesWorkbookPage_JavadocPropertyDialog_title=JSDoc For ''{0}''
-
-LibrariesWorkbookPage_exclusion_added_title=Class Folder Added
-LibrariesWorkbookPage_exclusion_added_message=Exclusion filters have been added to nesting source folders.
-
-# ---- BuildPathDialogAccess -------
-
-BuildPathDialogAccess_ExistingSourceFolderDialog_new_title=Source Folder Selection
-BuildPathDialogAccess_ExistingSourceFolderDialog_new_description=&Choose source folders to be added to the build path:
-
-BuildPathDialogAccess_ExistingClassFolderDialog_new_title=Library Folder Selection
-BuildPathDialogAccess_ExistingClassFolderDialog_new_description=&Choose library folders to be added to the Project Context:
-
-BuildPathDialogAccess_JARArchiveDialog_new_title=JavasSript File Selection
-BuildPathDialogAccess_SuperTypeSelection=JavaScript Sourcefile SuperType Selection
-BuildPathDialogAccess_SelectSupertType=Select a class from the installed libraries to use as \nthe SuperType for all JavaScript Source Files:
-BuildPathDialogAccess_JARArchiveDialog_new_description=&Choose JavaScript files to add to the Project Context:
-
-BuildPathDialogAccess_JARArchiveDialog_edit_title=Edit JAR
-BuildPathDialogAccess_JARArchiveDialog_edit_description=&Select the jar archive:
-
-BuildPathDialogAccess_ExtJARArchiveDialog_new_title=JavaScript Selection
-
-BuildPathDialogAccess_ExtJARArchiveDialog_edit_title=Edit JAR
-
-# ------- NewContainerDialog-------
-
-NewContainerDialog_error_invalidpath=Invalid folder path: ''{0}''
-NewContainerDialog_error_enterpath=Folder name must be entered
-NewContainerDialog_error_pathexists=This folder is already on the list or it is an output folder.
-# ------- NewSourceFolderDialog-------
-
-NewSourceFolderDialog_error_invalidpath=Invalid folder path: ''{0}''
-NewSourceFolderDialog_error_enterpath=Folder name must be entered.
-NewSourceFolderDialog_error_pathexists=The folder is already on the list.
-
-# ------- SourceAttachmentBlock-------
-
-SourceAttachmentBlock_message=Select the location (folder, JAR or zip) containing the source for ''{0}'':
-SourceAttachmentBlock_filename_description=Source attachments for variable entries are defined by variable paths. The first segment of such a path describes a variable name, the rest is an optional path extension.
-
-SourceAttachmentBlock_filename_label=Lo&cation path:
-SourceAttachmentBlock_filename_externalfile_button=External &File...
-SourceAttachmentBlock_filename_externalfolder_button=External F&older...
-SourceAttachmentBlock_filename_internal_button=&Workspace...
-
-SourceAttachmentBlock_filename_varlabel=Lo&cation variable path:
-SourceAttachmentBlock_filename_variable_button=&Variable...
-SourceAttachmentBlock_filename_external_varbutton=&Extension....
-
-SourceAttachmentBlock_filename_error_notvalid= The archive path is not a valid path.
-SourceAttachmentBlock_filename_error_notabsolute=The path must be absolute.
-SourceAttachmentBlock_filename_error_filenotexists= The path ''{0}'' does not exist.
-SourceAttachmentBlock_filename_error_varnotexists= The variable in the location variable path does not exist.
-SourceAttachmentBlock_filename_error_deviceinpath= The location variable path must begin with a variable.
-SourceAttachmentBlock_filename_warning_varempty= The location variable path is empty.
-
-SourceAttachmentBlock_intjardialog_title=Source Location Selection
-SourceAttachmentBlock_intjardialog_message=&Select folder or JAR/zip archive containing the source:
-
-SourceAttachmentBlock_extvardialog_title=Variable Extension Selection
-SourceAttachmentBlock_extvardialog_description=Select source location:
-
-SourceAttachmentBlock_extjardialog_text=JAR/ZIP File Selection
-SourceAttachmentBlock_extfolderdialog_text=Folder Selection
-SourceAttachmentBlock_extfolderdialog_message=Choose a directory containing source:
-
-BuildPathSupport_putoncpdialog_title=Setting Source Attachment
-BuildPathSupport_deprecated={0} is deprecated: {1}.
-BuildPathSupport_putoncpdialog_message=Source can only be attached to libraries on the build path.\nDo you want to add the library to the build path?
-SourceAttachmentDialog_title=Source Attachment Configuration
-
-# ------- EditVariableEntryDialog -------
-
-EditVariableEntryDialog_title=Edit Variable Entry
-
-EditVariableEntryDialog_filename_varlabel=Edit classpath variable entry:
-EditVariableEntryDialog_filename_empty=Enter a classpath variable.
-EditVariableEntryDialog_filename_variable_button=&Variable...
-EditVariableEntryDialog_filename_external_varbutton=&Extension....
-
-EditVariableEntryDialog_extvardialog_title=Variable Extension Selection
-EditVariableEntryDialog_extvardialog_description=Select JAR archive:
-
-EditVariableEntryDialog_filename_error_notvalid=The archive path is not a valid path.
-EditVariableEntryDialog_filename_error_filenotexists=The path ''{0}'' does not point to an existing archive.
-EditVariableEntryDialog_filename_error_varnotexists=Variable in the archive path does not exist.
-EditVariableEntryDialog_filename_error_deviceinpath=The archive must be described by a variable path.
-EditVariableEntryDialog_filename_warning_varempty=Archive variable path is empty.
-EditVariableEntryDialog_filename_error_alreadyexists=Classpath entry already exists.
-
-# ------- VariableBlock-------
-
-VariableBlock_vars_label=Defined &classpath variables:
-VariableBlock_vars_add_button=&New...
-VariableBlock_vars_edit_button=&Edit...
-VariableBlock_vars_remove_button=&Remove
-VariableBlock_variableSettingError_titel=Setting Classpath Variables
-
-VariableBlock_operation_desc=Setting classpath variables...
-VariableBlock_job_description=Setting variables
-
-VariableBlock_needsbuild_title=Classpath Variables Changed
-VariableBlock_needsbuild_message=The classpath variables have changed. A full rebuild is recommended for changes to take effect. Do the full build now?
-
-VariablePathDialogField_variabledialog_title=Variable Selection
-
-CPVariableElementLabelProvider_read_only=non modifiable
-CPVariableElementLabelProvider_deprecated=deprecated
-CPVariableElementLabelProvider_one_restriction={0} ({1})
-CPVariableElementLabelProvider_two_restrictions={0} ({1}, {2})
-CPVariableElementLabelProvider_appendix={0} - {1}
-CPVariableElementLabelProvider_empty=(empty)
-
-# ------- VariableCreationDialog-------
-
-VariableCreationDialog_titlenew=New Variable Entry
-VariableCreationDialog_titleedit=Edit Variable Entry
-
-VariableCreationDialog_name_label=&Name:
-VariableCreationDialog_path_label=&Path:
-VariableCreationDialog_path_file_button=&File...
-VariableCreationDialog_path_dir_button=F&older...
-
-VariableCreationDialog_error_entername=Enter a variable name.
-VariableCreationDialog_error_whitespace=The variable name starts or ends with white spaces.
-VariableCreationDialog_error_invalidname=The variable name contains ':', '/' or '\\'.
-VariableCreationDialog_error_nameexists=Variable name already exists.
-VariableCreationDialog_error_invalidpath=The path is invalid.
-
-VariableCreationDialog_warning_pathnotexists=Path does not exist.
-
-
-VariableCreationDialog_extjardialog_text=JAR Selection
-VariableCreationDialog_extdirdialog_text=Folder Selection
-VariableCreationDialog_extdirdialog_message=Specify the folder to be represented by the variable:
-VariableBlock_variableSettingError_message=Could not set Classpath Variables
-
-# ------- NewVariableEntryDialog -------
-
-NewVariableEntryDialog_title=New Variable Classpath Entry
-
-NewVariableEntryDialog_vars_extend=E&xtend...
-
-NewVariableEntryDialog_configbutton_label=Configur&e Variables...
-
-NewVariableEntryDialog_vars_label=Select &variables to add to build path:
-
-NewVariableEntryDialog_ExtensionDialog_title=Variable Extension
-NewVariableEntryDialog_ExtensionDialog_description=Choose extensions to ''{0}''.
-
-NewVariableEntryDialog_info_notexists=Variable points to a non-existing location.
-NewVariableEntryDialog_info_isfolder=Variable points to a folder: Use 'Extend...' to select an archive inside the folder.
-NewVariableEntryDialog_info_noselection=Select variable(s) to add to the classpath.
-NewVariableEntryDialog_info_selected={0} variables selected.
-
-
-# ------- ExclusionInclusionDialog -------
-
-ExclusionInclusionDialog_title=Inclusion and Exclusion Patterns
-ExclusionInclusionDialog_description=Included and excluded resources for ''{0}''.
-ExclusionInclusionDialog_description2=Add or remove inclusion and exclusion patterns to source folder
-
-ExclusionInclusionDialog_exclusion_pattern_label=E&xclusion patterns:
-ExclusionInclusionDialog_inclusion_pattern_label=I&nclusion patterns:
-
-ExclusionInclusionDialog_inclusion_pattern_add=A&dd...
-ExclusionInclusionDialog_inclusion_pattern_add_multiple=Add &Multiple...
-ExclusionInclusionDialog_inclusion_pattern_remove=&Remove
-ExclusionInclusionDialog_inclusion_pattern_edit=&Edit...
-
-ExclusionInclusionDialog_exclusion_pattern_add=&Add...
-ExclusionInclusionDialog_exclusion_pattern_add_multiple=Add M&ultiple...
-ExclusionInclusionDialog_exclusion_pattern_remove=Rem&ove
-ExclusionInclusionDialog_exclusion_pattern_edit=Edi&t...
-
-ExclusionInclusionDialog_ChooseExclusionPattern_title=Exclusion Pattern Selection
-ExclusionInclusionDialog_ChooseExclusionPattern_description=&Choose folders or files to exclude:
-
-ExclusionInclusionDialog_ChooseInclusionPattern_title=Inclusion Pattern Selection
-ExclusionInclusionDialog_ChooseInclusionPattern_description=&Choose folders or files to include:
-
-ExclusionInclusionDialog_Info_SrcAndOutput=Removing is not possible because some entries correspond \nto source and output folders
-ExclusionInclusionDialog_Info_Src=Removing is not possible because some entries correspond to \nsource folders
-ExclusionInclusionDialog_Info_Output=Removing is not possible because this entry corresponds to \nan output folder
-
-
-# ------- ExclusionInclusionEntryDialog -------
-
-ExclusionInclusionEntryDialog_exclude_add_title=Add Exclusion Pattern
-ExclusionInclusionEntryDialog_exclude_edit_title=Edit Exclusion Pattern
-ExclusionInclusionEntryDialog_exclude_description=Enter a pattern for excluding files from the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'java/util/A*.java', 'java/util/', '**/Test*'.
-
-ExclusionInclusionEntryDialog_exclude_pattern_label=E&xclusion pattern (Path relative to ''{0}''):
-
-ExclusionInclusionEntryDialog_include_add_title=Add Inclusion Pattern
-ExclusionInclusionEntryDialog_include_edit_title=Edit Inclusion Pattern
-ExclusionInclusionEntryDialog_include_description=Enter a pattern for including files to the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'java/util/A*.java', 'java/util/', '**/Test*'.
-
-ExclusionInclusionEntryDialog_include_pattern_label=I&nclusion pattern (Path relative to ''{0}''):
-
-ExclusionInclusionEntryDialog_pattern_button=Bro&wse...
-
-ExclusionInclusionEntryDialog_error_empty=Enter a pattern.
-ExclusionInclusionEntryDialog_error_notrelative=Pattern must be a relative path.
-ExclusionInclusionEntryDialog_error_exists=Pattern already exists.
-
-ExclusionInclusionEntryDialog_ChooseExclusionPattern_title=Exclusion Pattern Selection
-ExclusionInclusionEntryDialog_ChooseExclusionPattern_description=&Choose a folder or file to exclude:
-
-ExclusionInclusionEntryDialog_ChooseInclusionPattern_title=Inclusion Pattern Selection
-ExclusionInclusionEntryDialog_ChooseInclusionPattern_description=&Choose a folder or file to include:
-
-# ------- TypeRestrictionDialog -------
-
-AccessRulesDialog_title=Type Access Rules
-AccessRulesDialog_description=Specify access rules for ''{0}''.\nWhen accessing a type in the library, the rules are processed top down until a rule pattern matches. When no pattern matches, the type is considered accessible.
-AccessRulesDialog_container_description=Specify access rules for the library ''{0}''.\nWhen accessing a type in a library child entry, these rules are processed top down until a rule pattern matches. When no pattern matches, the rules defined for library child entry are taken.
-AccessRulesDialog_switch_dialog_message=To switch to the 'Error/Warning' page, this dialog will be closed and changes applied. OK to continue?
-AccessRulesDialog_project_description=Specify access rules for the project ''{0}''.\nWhen accessing a type from a source folders in the project, the rules are processed top down until a rule pattern matches. When no pattern matches, the type is considered accessible.
-AccessRulesDialog_switch_dialog_title=Access Rules
-AccessRulesDialog_rules_label=A&ccess rules:
-AccessRulesDialog_rules_add=&Add...
-AccessRulesDialog_rules_up=&Up
-AccessRulesDialog_rules_remove=Rem&ove
-AccessRulesDialog_combine_label=Com&bine rules with the access rules of the exported project entries
-AccessRulesDialog_severity_info_with_link=<form><p>The problem severities as configured on the ''<a>Error/Warning</a>'' page currently are:</p><p>Discouraged: <b>{0}</b>, Forbidden: <b>{1}</b></p></form>
-AccessRulesDialog_severity_info_no_link=<form><p>The problem severities as configured on the ''Error/Warning'' page currently are:</p><p>Discouraged: <b>{0}</b>, Forbidden: <b>{1}</b></p></form>
-AccessRulesDialog_severity_error=Error
-AccessRulesDialog_severity_warning=Warning
-AccessRulesDialog_severity_ignore=Ignore
-AccessRulesDialog_rules_edit=Edi&t...
-AccessRulesDialog_rules_down=Do&wn
-AccessRulesLabelProvider_kind_accessible=Accessible
-AccessRulesLabelProvider_kind_discouraged=Discouraged
-AccessRulesLabelProvider_kind_non_accessible=Forbidden
-TypeRestrictionEntryDialog_add_title=Add Access Rule
-TypeRestrictionEntryDialog_edit_title=Edit Access Rule
-
-TypeRestrictionEntryDialog_pattern_label=&Rule Pattern:
-TypeRestrictionEntryDialog_description=Enter a pattern for the rule.
-TypeRestrictionEntryDialog_description2=Allowed wildcards are '*', '?' and '**'. Pattern segments are separated by '/'. '**' matches any number of segments.\nExamples are: 'java/util/**', '**/internal/**', 'org/e*/**'.
-
-TypeRestrictionEntryDialog_error_empty=Enter a pattern for the rule.
-TypeRestrictionEntryDialog_error_notrelative=Pattern must be a relative path.
-
-TypeRestrictionEntryDialog_kind_accessible=Accessible
-TypeRestrictionEntryDialog_kind_label=Re&solution:
-TypeRestrictionEntryDialog_kind_discourraged=Discouraged
-TypeRestrictionEntryDialog_kind_non_accessible=Forbidden
-
-# ------- JsGlobalScopeContainerDefaultPage-------
-
-JsGlobalScopeContainerDefaultPage_title=Classpath Container
-JsGlobalScopeContainerDefaultPage_description=Edit the classpath container path. First segment is the container type.
-
-JsGlobalScopeContainerDefaultPage_path_label=&Classpath container path:
-
-JsGlobalScopeContainerDefaultPage_path_error_enterpath=Enter path.
-JsGlobalScopeContainerDefaultPage_path_error_invalidpath=Invalid path.
-JsGlobalScopeContainerDefaultPage_path_error_needssegment=Path needs at least one segment.
-JsGlobalScopeContainerDefaultPage_path_error_alreadyexists=Entry already exists.
-
-# ------- JsGlobalScopeContainerSelectionPage-------
-
-JsGlobalScopeContainerSelectionPage_title=Add JavaScript Library
-JsGlobalScopeContainerSelectionPage_description=Select the JavaScript library to include in the project.
-
-# ------- JsGlobalScopeContainerWizard-------
-
-JsGlobalScopeContainerWizard_pagecreationerror_title= JavaScript Library Wizard
-JsGlobalScopeContainerWizard_pagecreationerror_message=Wizard page creation failed. Check log for details.
-
-JsGlobalScopeContainerWizard_new_title=Add JavaScript Library
-JsGlobalScopeContainerWizard_edit_title=Edit JavaScript Library
-
-FolderSelectionDialog_button=Create &New Folder...
-MultipleFolderSelectionDialog_button=Create &New Folder...
-
-CPListLabelProvider_javadoc_location_label=JSDoc location
-
-CPListLabelProvider_none=(None)
-CPListLabelProvider_all=(All)
-CPListLabelProvider_access_rules_label={0}: {1}
-CPListLabelProvider_container_access_rules=Access rules: {0} rules(s) defined, added to all library child entries
-CPListLabelProvider_container_no_access_rules=Access rules: No rules defined
-CPListLabelProvider_source_attachment_label=Source attachment: {0}
-CPListLabelProvider_output_folder_label=Output folder: {0}
-CPListLabelProvider_default_output_folder_label=(Default output folder)
-CPListLabelProvider_exclusion_filter_label=Excluded: {0}
-CPListLabelProvider_exclusion_filter_separator=;
-CPListLabelProvider_inclusion_filter_label=Included: {0}
-CPListLabelProvider_inclusion_filter_separator=;
-CPListLabelProvider_unknown_element_label=unknown element
-CPListLabelProvider_access_rules_enabled=Access rules: {0} rule(s) defined
-CPListLabelProvider_project_access_rules_combined=Access rules: {0} rule(s) defined, added to all project child entries
-CPListLabelProvider_project_access_rules_no_rules=Access rules: No rules defined
-CPListLabelProvider_project_access_rules_not_combined=Access rules: {0} rule(s) defined, added only to project source entries
-CPListLabelProvider_access_rules_disabled=Access rules: (No restrictions)
-NewSourceFolderDialog_useproject_button=&Project as source folder
-NewSourceFolderDialog_usefolder_button=&Folder as source folder
-NewSourceFolderDialog_sourcefolder_label=&Source folder name:
-
-JavaProjectWizardFirstPage_0=Web Page Support
-JavaProjectWizardFirstPage_1=Include ECMA 3 Browser Library
-JavaProjectWizardFirstPage_2=Use Window as the default SuperType
-JavaProjectWizardFirstPage_NameGroup_label_text=&Project name:
-JavaProjectWizardFirstPage_LocationGroup_title=Contents
-JavaProjectWizardFirstPage_LocationGroup_external_desc=Create project from e&xisting source
-JavaProjectWizardFirstPage_WorkingSetSelection_message=The new project will be added to the selected working sets:
-JavaProjectWizardFirstPage_LocationGroup_workspace_desc=Create new project in &workspace
-JavaProjectWizardFirstPage_LocationGroup_locationLabel_desc=&Directory:
-JavaProjectWizardFirstPage_LocationGroup_browseButton_desc=B&rowse...
-JavaProjectWizardFirstPage_LayoutGroup_title=Project layout
-JavaProjectWizardFirstPage_LayoutGroup_option_separateFolders=&Create a separate root folder
-JavaProjectWizardFirstPage_LayoutGroup_option_oneFolder=&Use project folder as root for the JavaScript global context
-JavaProjectWizardFirstPage_LayoutGroup_link_description=<a>Configure d&efault...</a>
-JavaProjectWizardFirstPage_LayoutGroup_configure=C&onfigure Defaults...
-JavaProjectWizardFirstPage_DetectGroup_message=The specified external location already exists. If a project is created in this location, the wizard will automatically try to detect existing sources and class files and configure the classpath appropriately.
-JavaProjectWizardFirstPage_EnableWorkingSet_button=Add projec&t to working sets
-JavaProjectWizardFirstPage_Message_enterProjectName=Enter a project name.
-JavaProjectWizardFirstPage_Message_projectAlreadyExists=A project with this name already exists.
-JavaProjectWizardFirstPage_Message_enterLocation=Enter a location for the project.
-JavaProjectWizardFirstPage_UnknownDefaultJRE_name=Unknown
-JavaProjectWizardFirstPage_Message_invalidDirectory=Invalid project contents directory
-JavaProjectWizardFirstPage_Message_notOnWorkspaceRoot=Projects located in the workspace folder must be direct sub folders of the workspace folder
-JavaProjectWizardFirstPage_Message_cannotCreateAtExternalLocation=Cannot create project content at the given external location.
-JavaProjectWizardFirstPage_Message_existingFolderInWorkspace=A resource with the project name already exists in the workspace root
-JavaProjectWizardFirstPage_Message_notExisingProjectOnWorkspaceRoot=The selected existing source location in the workspace root does not exist
-JavaProjectWizardFirstPage_Message_invalidProjectNameForWorkspaceRoot=The name of the new project must be ''{0}''
-JavaProjectWizardFirstPage_page_pageName=SimpleProjectFirstPage
-JavaProjectWizardFirstPage_page_title=Create a JavaScript project
-JavaProjectWizardFirstPage_page_description=Create a JavaScript project in the workspace or in an external location.
-
-# ------- HintTextGroup -------
-HintTextGroup_Exception_Title=Error Caused by Operation ''{0}''
-HintTextGroup_Exception_Title_refresh=Error while Refreshing the Tree
-HintTextGroup_Exception_Title_output=Error while Setting the Output Text Field
-HintTextGroup_NoAction=<form>\
-No actions available for this selection.<br>Reason:</br>{0}\
-</form>
-
-# ------- NewSourceContainerWorkbookPage -------
-NewSourceContainerWorkbookPage_Exception_Title=Error while Executing ''{0}''
-NewSourceContainerWorkbookPage_Exception_refresh=Error while Refreshing Action Group
-NewSourceContainerWorkbookPage_HintTextGroup_title=Details
-NewSourceContainerWorkbookPage_ToolBar_CreateFolder_tooltip=Create New Folder
-NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_tooltip=Configure Build Path
-NewSourceContainerWorkbookPage_ToolBar_ConfigureBP_label=&Configure Build Path...
-
-NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip=Configure Inclusion / Exclusion Filters
-NewSourceContainerWorkbookPage_ToolBar_Edit_label=Configure Inclusion / Exclusion &Filters...
-NewSourceContainerWorkbookPage_ToolBar_EditOutput_tooltip=Configure Output Folder
-NewSourceContainerWorkbookPage_ToolBar_EditOutput_label=Configure &Output Folder...
-NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip=Use as Source Folder
-NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label=&Use as Source Folder
-NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_tooltip=Add to Build Path
-NewSourceContainerWorkbookPage_ToolBar_AddSelLibToCP_label=&Add to Build Path
-
-NewSourceContainerWorkbookPage_ToolBar_AddJarCP_tooltip=Add External Archives to JavaScript Include Path
-NewSourceContainerWorkbookPage_ToolBar_AddJarCP_label=Add External Archi&ves...
-NewSourceContainerWorkbookPage_ToolBar_AddLibCP_tooltip=Add Libraries to JavaScript Include Path
-NewSourceContainerWorkbookPage_ToolBar_AddLibCP_label=Add &Libraries...
-NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip=Remove from Include Path
-NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label=&Remove from Build Path
-NewSourceContainerWorkbookPage_ToolBar_Include_tooltip=Add to Inclusion Filter
-NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip=Exclude
-NewSourceContainerWorkbookPage_ToolBar_Exclude_label=&Exclude
-NewSourceContainerWorkbookPage_ToolBar_Uninclude_tooltip=Remove from Inclusion Filter
-NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip=Include
-NewSourceContainerWorkbookPage_ToolBar_Unexclude_label=In&clude
-NewSourceContainerWorkbookPage_ToolBar_Reset_tooltip=Reset
-NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip=Clear All Changes
-NewSourceContainerWorkbookPage_ToolBar_ClearAll_label=&Clear All Changes
-NewSourceContainerWorkbookPage_ToolBar_CreateOutput_tooltip=Create Output Folder
-NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_label=&Create new source folder
-NewSourceContainerWorkbookPage_ToolBar_CreateSrcFolder_tooltip=Create a new Source Folder for the Project
-NewSourceContainerWorkbookPage_ToolBar_Link_tooltip=Link Additional Source to Project
-NewSourceContainerWorkbookPage_ToolBar_Link_label=Link &Source...
-NewSourceContainerWorkbookPage_ToolBar_Help_tooltip=JavaScript Include Path Help
-NewSourceContainerWorkbookPage_ToolBar_Help_label=JavaScript Include Path &Help
-NewSourceContainerWorkbookPage_ToolBar_Help_link=/org.eclipse.wst.jsdt.doc.user/reference/ref-123b.htm
-
-# ------- NewFolderDialog -------
-NewFolderDialog_linkTargetNonExistent=Link target does not exist
-NewFolderDialog_linkTargetNotFolder=Link target must be a folder
-NewFolderDialog_folderNameEmpty=Folder name must NewFolderDialog_dependenciesGroup_be specified
-NewFolderDialog_folderNameEmpty_alreadyExists=The folder ''{0}'' already exists.
-NewFolderDialog_errorTitle=Creation Error
-NewFolderDialog_internalError=Internal error: {0}
-NewFolderDialog_progress=Creating new folder
-NewFolderDialog_createIn=Link additional source to project ''{0}''.
-
-# ------- Link Folder Dialog -------
-LinkFolderDialog_title=Link Additional Source
-LinkFolderDialog_createIn=Link additional source to project ''{0}''.
-LinkFolderDialog_folderNameGroup_label=&Folder name:
-LinkFolderDialog_dependenciesGroup_locationLabel_desc=&Linked folder location:
-LinkFolderDialog_dependenciesGroup_browseButton_desc=Bro&wse...
-LinkFolderDialog_dependenciesGroup_variables_desc=&Variables...
-
-# ------- PackageExplorerActionGroup -------
-PackageExplorerActionGroup_NoAction_NullSelection=No element selected in the tree.
-PackageExplorerActionGroup_NoAction_MultiSelection=You selected a set of elements which do not have common specific actions. Instead, try to select \
-less elements at the time to have more actions available.
-PackageExplorerActionGroup_NoAction_NoReason=For the given situation no help or reason can be provided.
-
-PackageExplorerActionGroup_FormText_createLinkedFolder=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Link additional source</a>: use this if you have a folder in the file system \
-that should be used as additional source folder.</li>\
-</form>
-PackageExplorerActionGroup_FormText_createNewSourceFolder=<form><li style="image" value="defaultImage" bindent="5"><a href="">Create new source folder</a>: use this if you want to add a new source folder to your project.</li></form>
-PackageExplorerActionGroup_FormText_FolderToBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Add folder ''{0}'' to include path</a>: Add the folder to the include path if the \
-folder is the root of packages and source files. Entries on the include path are visible for content assist and validation purposes.</li>\
-</form>
-PackageExplorerActionGroup_FormText_PackageToBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Add package ''{0}'' to include path</a>: Add the folder corresponding to the package to the include path if the \
-folder is the root of packages and source files. Entries on the include path are visible for content assist and validation purposes.</li>\
-</form>
-PackageExplorerActionGroup_FormText_ProjectToBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Add project ''{0}'' to include path</a>: Add the project to the include path if the project is the root \
-of packages and source files. Entries on the include path are visible for content assist and validation purposes.</li>\
-</form>
-PackageExplorerActionGroup_FormText_fromBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Remove source folder ''{0}'' from build path</a>: Children of the folder will not be included when building the project.</li>\
-</form>
-PackageExplorerActionGroup_FormText_ProjectFromBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Remove project ''{0}'' from build path</a>: Children of the project which are not source folders \
-will not be included when building the project.</li>\
-</form>
-PackageExplorerActionGroup_FormText_ExcludePackage=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Exclude ''{0}'' from build path</a>: Use this action to hide all resources in this package from \
-the Java compiler. The contained source files with will not be built but treated as normal resources.</li>\
-</form>
-PackageExplorerActionGroup_FormText_ExcludeFile=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Exclude ''{0}'' from build path</a>: Use this action to hide file from \
-the Java compiler. The files will not be built but treated as normal resources.</li>\
-</form>
-PackageExplorerActionGroup_FormText_Edit=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Configure inclusion and exclusion filters</a>: specify patterns to the inclusion and exclusion filters \
-instead of including and excluding each folder or file manually.</li>\
-</form>
-PackageExplorerActionGroup_FormText_UnexcludeFolder=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Include ''{0}'' to build path</a>: Make the folder and all its contents visible again to the Java compiler.</li>\
-</form>
-PackageExplorerActionGroup_FormText_UnexcludeFile=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Include ''{0}'' to build path</a>: Make the file visible again to the Java compiler.</li>\
-</form>
-
-# -- default messages --
-PackageExplorerActionGroup_FormText_Default_Unexclude=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Include in build path</a>: Make the selected resources visible again to the Java compiler.</li>\
-</form>
-PackageExplorerActionGroup_FormText_Default_FromBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Remove from build path</a>: Children of the selected resources will not be included when building the project.</li>\
-</form>
-PackageExplorerActionGroup_FormText_Default_Exclude=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Exclude from build path</a>: Use this action to hide the selected resources (and their children if any) \
-from the Java compiler. Excluded resources will not be built but treated as normal resources.</li>\
-</form>
-PackageExplorerActionGroup_FormText_Default_toBuildpath=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Add to JavaScript include path</a>: Use this action if the selected resources should be \
-visible for content assist and validation purposes. Source include path entries must be selected in such \
-a way that the package declarations in its source files match with the actual relative path to the source folder.</li>\
-</form>
-PackageExplorerActionGroup_FormText_Default_ResetAll=<form>\
-<li style="image" value="defaultImage" bindent="5"><a href="">Undo all changes</a>: use this if all changes applied so far to the project should be made undone and \
-the initial state of the project should be restored.</li>\
-</form>
-
-# ------- DialogPackageExplorer -------
-DialogPackageExplorer_LabelProvider_Excluded={0} - (excluded)
-DialogPackageExplorer_LabelProvider_SingleExcluded={0} - (1 item excluded)
-DialogPackageExplorer_LabelProvider_MultiExcluded={0} - ({1} items excluded)
-
-# ------- ClasspathModifier -------
-ClasspathModifier_Monitor_AddToBuildpath=Adding to include path
-ClasspathModifier_Monitor_RemoveFromBuildpath=Removing from build path
-ClasspathModifier_Monitor_ResetFilters= Resetting filters
-ClasspathModifier_Monitor_Including=Setting inclusion filters
-ClasspathModifier_Monitor_Excluding=Setting exclusion filters
-ClasspathModifier_Monitor_RemoveExclusion=Removing from exclusion filters
-ClasspathModifier_Monitor_ContainsPath=Checking path constraints
-ClasspathModifier_Monitor_ExamineInputFilters=Examining input filters
-ClasspathModifier_Monitor_RemovePath=Removing path entries
-ClasspathModifier_Monitor_CheckOutputFolders=Checking output folders
-ClasspathModifier_Monitor_SetNewEntry=Setting new entry and validating
-ClasspathModifier_Monitor_ComparePaths=Comparing paths
-ClasspathOrderingWorkbookPage_SuperType=Default 'SuperType' from which to inherit fields and methods:
-ClassPathDetector_operation_description=Examine existing files to detect classpath entries
-ClasspathOrderingWorkbookPage_SelectReorder=B&rowse...
-ClasspathModifier_ChangeOutputLocationDialog_title=Source Folder Added
-ClasspathModifier_ChangeOutputLocationDialog_project_message=Do you want to remove the project as source folder?
-ClasspathModifier_ChangeOutputLocationDialog_project_outputLocation=To avoid overlapping, the project is removed as source folder and the default output folder is set to ''{0}''.
-ClasspathModifier_Error_NoNatures= This project does not have the JavaScript nature. Adding to the include path is not possible when the project lacks the JavaScript nature.
-
-ClasspathModifierQueries_delete_linked_folder=&Unlink the folder from the project and remove from build path
-ClasspathModifierQueries_do_not_delete_linked_folder=&Keep the linked folder in the project and only remove from build path
-ClasspathModifierQueries_confirm_remove_linked_folder_label=JavaScript Build Settings
-ClasspathModifierQueries_confirm_remove_linked_folder_message=Are you sure you want to remove folder ''{0}'' from the build path?
-
-JavaProjectWizardSecondPage_error_title=New JavaScript project
-JavaProjectWizardSecondPage_error_message=An error occurred while creating project. Check log for details.
-JavaProjectWizardSecondPage_problem_backup=Problem while creating backup for ''{0}''
-JavaProjectWizardSecondPage_operation_initialize=Initializing project...
-JavaProjectWizardSecondPage_operation_create=Creating project...
-JavaProjectWizardSecondPage_operation_remove=Removing project...
-JavaProjectWizardSecondPage_error_remove_title=Error Creating JavaScript Project
-JavaProjectWizardSecondPage_error_remove_message=An error occurred while removing a temporary project.
-JavaProjectWizardSecondPage_problem_restore_project=Problem while restoring backup for .project
-JavaProjectWizardSecondPage_problem_restore_classpath=Problem while restoring backup for .jsdtscope
-JavaProjectWizardSecondPage_DeleteCorruptProjectFile_message=A problem occurred while creating the project from existing source:\n\n''{0}''\n\nThe corrupt project file will be replaced by a valid one.
-JavaProjectWizardFirstPage_directory_message=Choose a directory for the project contents:
-JavaProjectWizardFirstPage_WorkingSets_group=Working sets
-
-
-UserLibraryWizardPage_title=User Library
-UserLibraryWizardPage_list_config_button=Configure &User Libraries...
-UserLibraryWizardPage_list_label=&Selected User Libraries:
-UserLibraryWizardPage_description_new=Select one or more user libraries to include in the project.
-UserLibraryWizardPage_description_edit=Modify user library ''{0}''
-UserLibraryWizardPage_error_selectentry=Select a library.
-UserLibraryWizardPage_error_selectonlyone=More than one library selected.
-UserLibraryWizardPage_error_alreadyoncp=One or more selected libraries are already on the build path.
-UserLibraryMarkerResolutionGenerator_changetouserlib_label=Select existing user library
-UserLibraryMarkerResolutionGenerator_createuserlib_label=Create user library ''{0}''
-UserLibraryMarkerResolutionGenerator_changetoother=Replace with other library
-UserLibraryMarkerResolutionGenerator_error_creationfailed_message=Could not offer quick fix to correct a container entry.
-UserLibraryMarkerResolutionGenerator_error_title=Error in Classpath Container Entry
-UserLibraryMarkerResolutionGenerator_error_applyingfailed_message=Could not apply quick fix to correct a container entry.
-
-AddSourceFolderWizardPage_description=Add a new source folder relative to ''{0}''.
-AddSourceFolderWizardPage_ignoreNestingConflicts=Ignore nesting conflicts
-AddSourceFolderWizardPage_conflictWarning=Creating the folder will result in a conflict:
-AddSourceFolderWizardPage_addSinglePattern=''{0}'' will be excluded from ''{1}'' to solve a nesting conflict.
-AddSourceFolderToBuildpathAction_ErrorTitle=Error while adding to include path
-AddSourceFolderWizardPage_replaceSourceFolderInfo=To avoid overlapping, the existing project source folder entry will be replaced.
-
-AddArchiveToBuildpathAction_DuplicateArchivesInfo_message=Following archives are already on the build path and will not be added:\n{0}
-AddArchiveToBuildpathAction_DuplicateArchiveInfo_message=The archive ''{0}'' is already on the build path and will not be added.
-RemoveFromBuildpathAction_ErrorTitle=Error while removing from build path
-ExcludeFromBuildathAction_ErrorTitle=Error while excluding from build path
-IncludeToBuildpathAction_ErrorTitle=Error while including to build path
-
-BaseLibraryWizardPage_title=ECMA 3 Browser Support Library
-BaseLibraryWizardPage_DefaultBrowserLibraryAdded=Default Browser Library added to Project.\n\n - This library supports the document and window objects supported by most browsers.
-BaseLibraryWizardPage_WebBrowserSupport=Web Browser Support
-
-# --- [ Javascript ] ---
-Javascript_UI_Wizard_New_Title=New JavaScript file
-Javascript_UI_Wizard_New_Heading=JavaScript
-Javascript_UI_Wizard_New_Description=Create a new JavaScript file.
-Javascript_Resource_Group_Name_Exists=The same name already exists.
-Javascript_Error_Filename_Must_End_JS=The file name must end in one of the following extensions {0}.
-Javascript_Warning_Folder_Must_Be_Inside_Web_Content=Files created outside of the Web Content folder will not be included in your deployed Web application.
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java
deleted file mode 100644
index f6b4ec3c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction;
-
-public class OpenJavaScriptFileWizardToolbarAction extends AbstractOpenWizardAction implements IWorkbenchWindowActionDelegate {
-
- public OpenJavaScriptFileWizardToolbarAction() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
- */
- public void dispose() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
- */
- public void init(IWorkbenchWindow window) {
- setShell(window.getShell());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- public void run(IAction action) {
- super.run();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
- */
- public void selectionChanged(IAction action, ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- setSelection((IStructuredSelection) selection);
- } else {
- setSelection(StructuredSelection.EMPTY);
- }
- }
-
- protected INewWizard createWizard() throws CoreException {
- return new NewJSWizard();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java
deleted file mode 100644
index ed551c0a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.wst.jsdt.ui.actions.OpenNewJavaProjectWizardAction;
-
-public class OpenJavaScriptProjectWizardToolbarAction extends OpenNewJavaProjectWizardAction implements IWorkbenchWindowActionDelegate {
-
- public OpenJavaScriptProjectWizardToolbarAction() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
- */
- public void dispose() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
- */
- public void init(IWorkbenchWindow window) {
- setShell(window.getShell());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- public void run(IAction action) {
- super.run();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
- */
- public void selectionChanged(IAction action, ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- setSelection((IStructuredSelection) selection);
- } else {
- setSelection(StructuredSelection.EMPTY);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedElementSelectionValidator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedElementSelectionValidator.java
deleted file mode 100644
index fe0ebe53..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedElementSelectionValidator.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import java.util.Collection;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-/**
- * Implementation of a <code>ISelectionValidator</code> to validate the
- * type of an element.
- * Empty selections are not accepted.
- */
-public class TypedElementSelectionValidator implements ISelectionStatusValidator {
-
- private IStatus fgErrorStatus= new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- private IStatus fgOKStatus= new StatusInfo();
-
- private Class[] fAcceptedTypes;
- private boolean fAllowMultipleSelection;
- private Collection fRejectedElements;
-
- /**
- * @param acceptedTypes The types accepted by the validator
- * @param allowMultipleSelection If set to <code>true</code>, the validator
- * allows multiple selection.
- */
- public TypedElementSelectionValidator(Class[] acceptedTypes, boolean allowMultipleSelection) {
- this(acceptedTypes, allowMultipleSelection, null);
- }
-
- /**
- * @param acceptedTypes The types accepted by the validator
- * @param allowMultipleSelection If set to <code>true</code>, the validator
- * allows multiple selection.
- * @param rejectedElements A list of elements that are not accepted
- */
- public TypedElementSelectionValidator(Class[] acceptedTypes, boolean allowMultipleSelection, Collection rejectedElements) {
- Assert.isNotNull(acceptedTypes);
- fAcceptedTypes= acceptedTypes;
- fAllowMultipleSelection= allowMultipleSelection;
- fRejectedElements= rejectedElements;
- }
-
- /*
- * @see org.eclipse.ui.dialogs.ISelectionValidator#isValid(java.lang.Object)
- */
- public IStatus validate(Object[] elements) {
- if (isValid(elements)) {
- return fgOKStatus;
- }
- return fgErrorStatus;
- }
-
- private boolean isOfAcceptedType(Object o) {
- for (int i= 0; i < fAcceptedTypes.length; i++) {
- if (fAcceptedTypes[i].isInstance(o)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isRejectedElement(Object elem) {
- return (fRejectedElements != null) && fRejectedElements.contains(elem);
- }
-
- protected boolean isSelectedValid(Object elem) {
- return true;
- }
-
- private boolean isValid(Object[] selection) {
- if (selection.length == 0) {
- return false;
- }
-
- if (!fAllowMultipleSelection && selection.length != 1) {
- return false;
- }
-
- for (int i= 0; i < selection.length; i++) {
- Object o= selection[i];
- if (!isOfAcceptedType(o) || isRejectedElement(o) || !isSelectedValid(o)) {
- return false;
- }
- }
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java
deleted file mode 100644
index e7a22965..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-/**
- * Viewer filter used in selection dialogs.
- */
-public class TypedViewerFilter extends ViewerFilter {
-
- private Class[] fAcceptedTypes;
- private Object[] fRejectedElements;
-
- /**
- * Creates a filter that only allows elements of gives types.
- * @param acceptedTypes The types of accepted elements
- */
- public TypedViewerFilter(Class[] acceptedTypes) {
- this(acceptedTypes, null);
- }
-
- /**
- * Creates a filter that only allows elements of gives types, but not from a
- * list of rejected elements.
- * @param acceptedTypes Accepted elements must be of this types
- * @param rejectedElements Element equals to the rejected elements are
- * filtered out
- */
- public TypedViewerFilter(Class[] acceptedTypes, Object[] rejectedElements) {
- Assert.isNotNull(acceptedTypes);
- fAcceptedTypes= acceptedTypes;
- fRejectedElements= rejectedElements;
- }
-
- /**
- * @see ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (fRejectedElements != null) {
- for (int i= 0; i < fRejectedElements.length; i++) {
- if (element.equals(fRejectedElements[i])) {
- return false;
- }
- }
- }
- for (int i= 0; i < fAcceptedTypes.length; i++) {
- if (fAcceptedTypes[i].isInstance(element)) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRuleEntryDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRuleEntryDialog.java
deleted file mode 100644
index 34f52d3e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRuleEntryDialog.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ComboDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-public class AccessRuleEntryDialog extends StatusDialog {
-
- private StringDialogField fPatternDialog;
- private StatusInfo fPatternStatus;
-
- private String fPattern;
- private ComboDialogField fRuleKindCombo;
- private int[] fRuleKinds;
-
- public AccessRuleEntryDialog(Shell parent, IAccessRule ruleToEdit, CPListElement entryToEdit) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- String title, message;
- if (ruleToEdit == null) {
- title= NewWizardMessages.TypeRestrictionEntryDialog_add_title;
- } else {
- title= NewWizardMessages.TypeRestrictionEntryDialog_edit_title;
- }
- message= Messages.format(NewWizardMessages.TypeRestrictionEntryDialog_pattern_label, entryToEdit.getPath().makeRelative().toString());
- setTitle(title);
-
- fPatternStatus= new StatusInfo();
-
- TypeRulesAdapter adapter= new TypeRulesAdapter();
- fPatternDialog= new StringDialogField();
- fPatternDialog.setLabelText(message);
- fPatternDialog.setDialogFieldListener(adapter);
-
- fRuleKindCombo= new ComboDialogField(SWT.READ_ONLY);
- fRuleKindCombo.setLabelText(NewWizardMessages.TypeRestrictionEntryDialog_kind_label);
- fRuleKindCombo.setDialogFieldListener(adapter);
- String[] items= {
- NewWizardMessages.TypeRestrictionEntryDialog_kind_non_accessible,
- NewWizardMessages.TypeRestrictionEntryDialog_kind_discourraged,
- NewWizardMessages.TypeRestrictionEntryDialog_kind_accessible
- };
- fRuleKinds= new int[] {
- IAccessRule.K_NON_ACCESSIBLE,
- IAccessRule.K_DISCOURAGED,
- IAccessRule.K_ACCESSIBLE
- };
- fRuleKindCombo.setItems(items);
-
-
- if (ruleToEdit == null) {
- fPatternDialog.setText(""); //$NON-NLS-1$
- fRuleKindCombo.selectItem(0);
- } else {
- fPatternDialog.setText(ruleToEdit.getPattern().toString());
- for (int i= 0; i < fRuleKinds.length; i++) {
- if (fRuleKinds[i] == ruleToEdit.getKind()) {
- fRuleKindCombo.selectItem(i);
- break;
- }
- }
- }
- }
-
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
- inner.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
-
- Label description= new Label(inner, SWT.WRAP);
- description.setText(NewWizardMessages.TypeRestrictionEntryDialog_description);
-
- GridData gd= new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1);
- gd.widthHint= convertWidthInCharsToPixels(60);
- description.setLayoutData(gd);
-
- fRuleKindCombo.doFillIntoGrid(inner, 2);
- fPatternDialog.doFillIntoGrid(inner, 2);
-
- Label description2= new Label(inner, SWT.WRAP);
- description2.setText(NewWizardMessages.TypeRestrictionEntryDialog_description2);
-
- gd= new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1);
- gd.widthHint= convertWidthInCharsToPixels(60);
- description2.setLayoutData(gd);
-
- fPatternDialog.postSetFocusOnDialogField(parent.getDisplay());
- applyDialogFont(composite);
- return composite;
- }
-
-
- // -------- TypeRulesAdapter --------
-
- private class TypeRulesAdapter implements IDialogFieldListener {
-
- public void dialogFieldChanged(DialogField field) {
- doStatusLineUpdate();
- }
- }
-
-
- protected void doStatusLineUpdate() {
- checkIfPatternValid();
- updateStatus(fPatternStatus);
- }
-
- protected void checkIfPatternValid() {
- String pattern= fPatternDialog.getText().trim();
- if (pattern.length() == 0) {
- fPatternStatus.setError(NewWizardMessages.TypeRestrictionEntryDialog_error_empty);
- return;
- }
- IPath path= new Path(pattern);
- if (path.isAbsolute() || path.getDevice() != null) {
- fPatternStatus.setError(NewWizardMessages.TypeRestrictionEntryDialog_error_notrelative);
- return;
- }
-
- fPattern= pattern;
- fPatternStatus.setOK();
- }
-
- public IAccessRule getRule() {
- IPath filePattern= new Path(fPattern);
- int kind= fRuleKinds[fRuleKindCombo.getSelectionIndex()];
- return JavaScriptCore.newAccessRule(filePattern, kind);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.ACCESS_RULES_DIALOG);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesDialog.java
deleted file mode 100644
index 3206d6af..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesDialog.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnPixelData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.ProblemSeveritiesPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-public class AccessRulesDialog extends StatusDialog {
-
- public static final int SWITCH_PAGE= 10;
-
- private final ListDialogField fAccessRulesList;
- private final SelectionButtonDialogField fCombineRulesCheckbox;
- private final CPListElement fCurrElement;
-
- private final IJavaScriptProject fProject;
- private final boolean fParentCanSwitchPage;
-
- private static final int IDX_ADD= 0;
- private static final int IDX_EDIT= 1;
- private static final int IDX_UP= 3;
- private static final int IDX_DOWN= 4;
- private static final int IDX_REMOVE= 6;
-
-
- public AccessRulesDialog(Shell parent, CPListElement entryToEdit, IJavaScriptProject project, boolean parentCanSwitchPage) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fCurrElement= entryToEdit;
- fProject= project; // can be null
-
- setTitle(NewWizardMessages.AccessRulesDialog_title);
-
- fAccessRulesList= createListContents(entryToEdit);
-
- fCombineRulesCheckbox= new SelectionButtonDialogField(SWT.CHECK);
- fCombineRulesCheckbox.setLabelText(NewWizardMessages.AccessRulesDialog_combine_label);
- fCombineRulesCheckbox.setSelection(Boolean.TRUE.equals(entryToEdit.getAttribute(CPListElement.COMBINE_ACCESSRULES)));
-
- fParentCanSwitchPage= parentCanSwitchPage;
- }
-
-
- private ListDialogField createListContents(CPListElement entryToEdit) {
- String label= NewWizardMessages.AccessRulesDialog_rules_label;
- String[] buttonLabels= new String[] {
- NewWizardMessages.AccessRulesDialog_rules_add,
- NewWizardMessages.AccessRulesDialog_rules_edit,
- null,
- NewWizardMessages.AccessRulesDialog_rules_up,
- NewWizardMessages.AccessRulesDialog_rules_down,
- null,
- NewWizardMessages.AccessRulesDialog_rules_remove
- };
-
- TypeRestrictionAdapter adapter= new TypeRestrictionAdapter();
- AccessRulesLabelProvider labelProvider= new AccessRulesLabelProvider();
-
- ListDialogField patternList= new ListDialogField(adapter, buttonLabels, labelProvider);
- patternList.setDialogFieldListener(adapter);
-
- patternList.setLabelText(label);
- patternList.setRemoveButtonIndex(IDX_REMOVE);
- patternList.setUpButtonIndex(IDX_UP);
- patternList.setDownButtonIndex(IDX_DOWN);
- patternList.enableButton(IDX_EDIT, false);
-
- IAccessRule[] rules= (IAccessRule[]) entryToEdit.getAttribute(CPListElement.ACCESSRULES);
- ArrayList elements= new ArrayList(rules.length);
- for (int i= 0; i < rules.length; i++) {
- elements.add(rules[i]);
- }
- patternList.setElements(elements);
- patternList.selectFirstElement();
- return patternList;
- }
-
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- int maxLabelSize= 0;
- GC gc= new GC(composite);
- try {
- maxLabelSize= gc.textExtent(AccessRulesLabelProvider.getResolutionLabel(IAccessRule.K_ACCESSIBLE)).x;
- int len2= gc.textExtent(AccessRulesLabelProvider.getResolutionLabel(IAccessRule.K_DISCOURAGED)).x;
- if (len2 > maxLabelSize) {
- maxLabelSize= len2;
- }
- int len3= gc.textExtent(AccessRulesLabelProvider.getResolutionLabel(IAccessRule.K_NON_ACCESSIBLE)).x;
- if (len3 > maxLabelSize) {
- maxLabelSize= len3;
- }
- } finally {
- gc.dispose();
- }
-
- ColumnLayoutData[] columnDta= new ColumnLayoutData[] {
- new ColumnPixelData(maxLabelSize + 40),
- new ColumnWeightData(1),
- };
- fAccessRulesList.setTableColumns(new ListDialogField.ColumnsDescription(columnDta, null, false));
-
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(composite.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Label description= new Label(inner, SWT.WRAP);
-
- description.setText(getDescriptionString());
-
- GridData data= new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1);
- data.widthHint= convertWidthInCharsToPixels(70);
- description.setLayoutData(data);
-
- fAccessRulesList.doFillIntoGrid(inner, 3);
-
- LayoutUtil.setHorizontalSpan(fAccessRulesList.getLabelControl(null), 2);
-
- data= (GridData) fAccessRulesList.getListControl(null).getLayoutData();
- data.grabExcessHorizontalSpace= true;
- data.heightHint= SWT.DEFAULT;
-
- if (fCurrElement.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
- fCombineRulesCheckbox.doFillIntoGrid(inner, 2);
- }
-
- if (fProject != null) {
- String forbiddenSeverity= fProject.getOption(JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE, true);
- String discouragedSeverity= fProject.getOption(JavaScriptCore.COMPILER_PB_DISCOURAGED_REFERENCE, true);
- String[] args= { getLocalizedString(discouragedSeverity), getLocalizedString(forbiddenSeverity) };
-
- FormToolkit toolkit= new FormToolkit(parent.getDisplay());
- toolkit.setBackground(null);
- try {
- FormText text = toolkit.createFormText(composite, true);
- text.setFont(inner.getFont());
- if (fParentCanSwitchPage) {
- // with link
- text.setText(Messages.format(NewWizardMessages.AccessRulesDialog_severity_info_with_link, args), true, false);
- text.addHyperlinkListener(new HyperlinkAdapter() {
- public void linkActivated(HyperlinkEvent e) {
- doErrorWarningLinkPressed();
- }
- });
- } else {
- // no link
- text.setText(Messages.format(NewWizardMessages.AccessRulesDialog_severity_info_no_link, args), true, false);
- }
- data= new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1);
- data.widthHint= convertWidthInCharsToPixels(70);
- text.setLayoutData(data);
- } catch (IllegalArgumentException e) {
- JavaScriptPlugin.log(e); // invalid string
- } finally {
- toolkit.dispose();
- }
- }
- applyDialogFont(composite);
- return composite;
- }
-
- final void doErrorWarningLinkPressed() {
- if (fParentCanSwitchPage && MessageDialog.openQuestion(getShell(), NewWizardMessages.AccessRulesDialog_switch_dialog_title, NewWizardMessages.AccessRulesDialog_switch_dialog_message)) {
- setReturnCode(SWITCH_PAGE);
- close();
- }
- }
-
- private String getLocalizedString(String severity) {
- if (JavaScriptCore.ERROR.equals(severity)) {
- return NewWizardMessages.AccessRulesDialog_severity_error;
- } else if (JavaScriptCore.WARNING.equals(severity)) {
- return NewWizardMessages.AccessRulesDialog_severity_warning;
- } else {
- return NewWizardMessages.AccessRulesDialog_severity_ignore;
- }
- }
-
- private String getDescriptionString() {
- String desc;
- String name= fCurrElement.getPath().lastSegment();
- switch (fCurrElement.getEntryKind()) {
- case IIncludePathEntry.CPE_CONTAINER:
- try {
- name= JavaScriptElementLabels.getContainerEntryLabel(fCurrElement.getPath(), fCurrElement.getJavaProject());
- } catch (JavaScriptModelException e) {
- }
- desc= NewWizardMessages.AccessRulesDialog_container_description;
- break;
- case IIncludePathEntry.CPE_PROJECT:
- desc= NewWizardMessages.AccessRulesDialog_project_description;
- break;
- default:
- desc= NewWizardMessages.AccessRulesDialog_description;
- }
-
- return Messages.format(desc, name);
- }
-
-
- protected void doCustomButtonPressed(ListDialogField field, int index) {
- if (index == IDX_ADD) {
- addEntry(field);
- } else if (index == IDX_EDIT) {
- editEntry(field);
- }
- }
-
- protected void doDoubleClicked(ListDialogField field) {
- editEntry(field);
- }
-
- protected void doSelectionChanged(ListDialogField field) {
- List selected= field.getSelectedElements();
- field.enableButton(IDX_EDIT, canEdit(selected));
- }
-
- private boolean canEdit(List selected) {
- return selected.size() == 1;
- }
-
- private void editEntry(ListDialogField field) {
-
- List selElements= field.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- IAccessRule rule= (IAccessRule) selElements.get(0);
- AccessRuleEntryDialog dialog= new AccessRuleEntryDialog(getShell(), rule, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.replaceElement(rule, dialog.getRule());
- }
- }
-
- private void addEntry(ListDialogField field) {
- AccessRuleEntryDialog dialog= new AccessRuleEntryDialog(getShell(), null, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.addElement(dialog.getRule());
- }
- }
-
-
-
- // -------- TypeRestrictionAdapter --------
-
- private class TypeRestrictionAdapter implements IListAdapter, IDialogFieldListener {
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField, int)
- */
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed(field, index);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged(field);
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#doubleClicked(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked(field);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- }
-
- }
-
- protected void doStatusLineUpdate() {
- }
-
- protected void checkIfPatternValid() {
- }
-
- public IAccessRule[] getAccessRules() {
- List elements= fAccessRulesList.getElements();
- return (IAccessRule[]) elements.toArray(new IAccessRule[elements.size()]);
- }
-
- public boolean doCombineAccessRules() {
- return fCombineRulesCheckbox.isSelected();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.ACCESS_RULES_DIALOG);
- }
-
-
- public void performPageSwitch(IWorkbenchPreferenceContainer pageContainer) {
- HashMap data= new HashMap();
- data.put(ProblemSeveritiesPreferencePage.DATA_SELECT_OPTION_KEY, JavaScriptCore.COMPILER_PB_FORBIDDEN_REFERENCE);
- data.put(ProblemSeveritiesPreferencePage.DATA_SELECT_OPTION_QUALIFIER, JavaScriptCore.PLUGIN_ID);
- pageContainer.openPage(ProblemSeveritiesPreferencePage.PROP_ID, data);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesLabelProvider.java
deleted file mode 100644
index a6ae16b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AccessRulesLabelProvider.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-public class AccessRulesLabelProvider extends LabelProvider implements ITableLabelProvider {
-
- public AccessRulesLabelProvider() {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
- */
- public Image getColumnImage(Object element, int columnIndex) {
- if (element instanceof IAccessRule) {
- IAccessRule rule= (IAccessRule) element;
- if (columnIndex == 0) {
- return getResolutionImage(rule.getKind());
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
- */
- public String getColumnText(Object element, int columnIndex) {
- if (element instanceof IAccessRule) {
- IAccessRule rule= (IAccessRule) element;
- if (columnIndex == 0) {
- return getResolutionLabel(rule.getKind());
- } else {
- return rule.getPattern().toString();
- }
- }
- return element.toString();
- }
-
- public static Image getResolutionImage(int kind) {
- switch (kind) {
- case IAccessRule.K_ACCESSIBLE:
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_TRANSLATE);
- case IAccessRule.K_DISCOURAGED:
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING);
- case IAccessRule.K_NON_ACCESSIBLE:
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_ERROR);
- }
- return null;
- }
-
-
- public static String getResolutionLabel(int kind) {
- switch (kind) {
- case IAccessRule.K_ACCESSIBLE:
- return NewWizardMessages.AccessRulesLabelProvider_kind_accessible;
- case IAccessRule.K_DISCOURAGED:
- return NewWizardMessages.AccessRulesLabelProvider_kind_discouraged;
- case IAccessRule.K_NON_ACCESSIBLE:
- return NewWizardMessages.AccessRulesLabelProvider_kind_non_accessible;
- }
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java
deleted file mode 100644
index 27765720..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-public class AddSourceFolderWizard extends BuildPathWizard {
-
- private AddSourceFolderWizardPage fAddFolderPage;
- private SetFilterWizardPage fFilterPage;
- private final boolean fLinkedMode;
- private boolean fAllowConflict;
- private final boolean fAllowRemoveProjectFolder;
- private final boolean fAllowAddExclusionPatterns;
- private final boolean fCanCommitConflict;
- private final IContainer fParent;
-
- public AddSourceFolderWizard(CPListElement[] existingEntries, CPListElement newEntry,
- boolean linkedMode, boolean canCommitConflict,
- boolean allowConflict, boolean allowRemoveProjectFolder, boolean allowAddExclusionPatterns) {
- this(existingEntries, newEntry, linkedMode, canCommitConflict, allowConflict, allowRemoveProjectFolder, allowAddExclusionPatterns, newEntry.getJavaProject().getProject());
- }
-
- public AddSourceFolderWizard(CPListElement[] existingEntries, CPListElement newEntry,
- boolean linkedMode, boolean canCommitConflict,
- boolean allowConflict, boolean allowRemoveProjectFolder, boolean allowAddExclusionPatterns, IContainer parent) {
- super(existingEntries, newEntry, getTitel(newEntry, linkedMode), JavaPluginImages.DESC_WIZBAN_NEWSRCFOLDR);
- fLinkedMode= linkedMode;
- fCanCommitConflict= canCommitConflict;
- fAllowConflict= allowConflict;
- fAllowRemoveProjectFolder= allowRemoveProjectFolder;
- fAllowAddExclusionPatterns= allowAddExclusionPatterns;
- fParent= parent;
- }
-
- private static String getTitel(CPListElement newEntry, boolean linkedMode) {
- if (newEntry.getPath() == null) {
- if (linkedMode) {
- return NewWizardMessages.NewSourceFolderCreationWizard_link_title;
- } else {
- return NewWizardMessages.NewSourceFolderCreationWizard_title;
- }
- } else {
- return NewWizardMessages.NewSourceFolderCreationWizard_edit_title;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void addPages() {
- super.addPages();
-
- fAddFolderPage= new AddSourceFolderWizardPage(getEntryToEdit(), getExistingEntries(),
- fLinkedMode, fCanCommitConflict,
- fAllowConflict, fAllowRemoveProjectFolder, fAllowAddExclusionPatterns, fParent);
- addPage(fAddFolderPage);
-
- fFilterPage= new SetFilterWizardPage(getEntryToEdit(), getExistingEntries());
- addPage(fFilterPage);
- }
-
- /**
- * {@inheritDoc}
- */
- public List getInsertedElements() {
- List result= super.getInsertedElements();
- if (getEntryToEdit().getOrginalPath() == null)
- result.add(getEntryToEdit());
-
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public List getRemovedElements() {
- return fAddFolderPage.getRemovedElements();
- }
-
- /**
- * {@inheritDoc}
- */
- public List getModifiedElements() {
- return fAddFolderPage.getModifiedElements();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean performFinish() {
- getEntryToEdit().setAttribute(CPListElement.INCLUSION, fFilterPage.getInclusionPattern());
- getEntryToEdit().setAttribute(CPListElement.EXCLUSION, fFilterPage.getExclusionPattern());
-
- boolean res= super.performFinish();
- if (res) {
- selectAndReveal(fAddFolderPage.getCorrespondingResource());
- }
- return res;
- }
-
- public void cancel() {
- fAddFolderPage.restore();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizardPage.java
deleted file mode 100644
index 13d5adfd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizardPage.java
+++ /dev/null
@@ -1,732 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.io.File;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IPathVariableManager;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.ide.dialogs.PathVariableSelectionDialog;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-
-public class AddSourceFolderWizardPage extends NewElementWizardPage {
-
- private final class LinkFields implements IStringButtonAdapter, IDialogFieldListener{
- private StringButtonDialogField fLinkLocation;
-
- private static final String DIALOGSTORE_LAST_EXTERNAL_LOC= JavaScriptUI.ID_PLUGIN + ".last.external.project"; //$NON-NLS-1$
-
- private RootFieldAdapter fAdapter;
-
- private SelectionButtonDialogField fVariables;
-
- public LinkFields() {
- fLinkLocation= new StringButtonDialogField(this);
-
- fLinkLocation.setLabelText(NewWizardMessages.LinkFolderDialog_dependenciesGroup_locationLabel_desc);
- fLinkLocation.setButtonLabel(NewWizardMessages.LinkFolderDialog_dependenciesGroup_browseButton_desc);
- fLinkLocation.setDialogFieldListener(this);
-
- fVariables= new SelectionButtonDialogField(SWT.PUSH);
- fVariables.setLabelText(NewWizardMessages.LinkFolderDialog_dependenciesGroup_variables_desc);
- fVariables.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- handleVariablesButtonPressed();
- }
- });
- }
-
- public void setDialogFieldListener(RootFieldAdapter adapter) {
- fAdapter= adapter;
- }
-
- private void doFillIntoGrid(Composite parent, int numColumns) {
- fLinkLocation.doFillIntoGrid(parent, numColumns);
-
- LayoutUtil.setHorizontalSpan(fLinkLocation.getLabelControl(null), numColumns);
- LayoutUtil.setHorizontalGrabbing(fLinkLocation.getTextControl(null));
-
- fVariables.doFillIntoGrid(parent, 1);
- }
-
- public IPath getLinkTarget() {
- return Path.fromOSString(fLinkLocation.getText());
- }
-
- public void setLinkTarget(IPath path) {
- fLinkLocation.setText(path.toOSString());
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void changeControlPressed(DialogField field) {
- final DirectoryDialog dialog= new DirectoryDialog(getShell());
- dialog.setMessage(NewWizardMessages.JavaProjectWizardFirstPage_directory_message);
- String directoryName = fLinkLocation.getText().trim();
- if (directoryName.length() == 0) {
- String prevLocation= JavaScriptPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LAST_EXTERNAL_LOC);
- if (prevLocation != null) {
- directoryName= prevLocation;
- }
- }
-
- if (directoryName.length() > 0) {
- final File path = new File(directoryName);
- if (path.exists())
- dialog.setFilterPath(directoryName);
- }
- final String selectedDirectory = dialog.open();
- if (selectedDirectory != null) {
- fLinkLocation.setText(selectedDirectory);
- fRootDialogField.setText(selectedDirectory.substring(selectedDirectory.lastIndexOf(File.separatorChar) + 1));
- JavaScriptPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LAST_EXTERNAL_LOC, selectedDirectory);
- if (fAdapter != null) {
- fAdapter.dialogFieldChanged(fRootDialogField);
- }
- }
- }
-
- /**
- * Opens a path variable selection dialog
- */
- private void handleVariablesButtonPressed() {
- int variableTypes = IResource.FOLDER;
- PathVariableSelectionDialog dialog = new PathVariableSelectionDialog(getShell(), variableTypes);
- if (dialog.open() == IDialogConstants.OK_ID) {
- String[] variableNames = (String[]) dialog.getResult();
- if (variableNames != null && variableNames.length == 1) {
- fLinkLocation.setText(variableNames[0]);
- fRootDialogField.setText(variableNames[0]);
- if (fAdapter != null) {
- fAdapter.dialogFieldChanged(fRootDialogField);
- }
- }
- }
- }
-
- public void dialogFieldChanged(DialogField field) {
- if (fAdapter != null) {
- fAdapter.dialogFieldChanged(fLinkLocation);
- }
- }
- }
-
- private static final String PAGE_NAME= "NewSourceFolderWizardPage"; //$NON-NLS-1$
-
- private final StringDialogField fRootDialogField;
- private final SelectionButtonDialogField fAddExclusionPatterns, fRemoveProjectFolder, fIgnoreConflicts;
- private final LinkFields fLinkFields;
-
- private final CPListElement fNewElement;
- private final List/*<CPListElement>*/ fExistingEntries;
- private final Hashtable/*<CPListElement, IPath[]>*/ fOrginalExlusionFilters, fOrginalInclusionFilters, fOrginalExlusionFiltersCopy, fOrginalInclusionFiltersCopy;
- private final IPath fOrginalPath;
- private final boolean fLinkedMode;
-
- private CPListElement fOldProjectSourceFolder;
-
- private List fModifiedElements;
- private List fRemovedElements;
-
- private final boolean fAllowConflict;
- private final boolean fAllowRemoveProjectFolder;
- private final boolean fAllowAddExclusionPatterns;
- private final boolean fCanCommitConflictingBuildpath;
- private final IContainer fParent;
-
- public AddSourceFolderWizardPage(CPListElement newElement, List/*<CPListElement>*/ existingEntries,
- boolean linkedMode, boolean canCommitConflictingBuildpath,
- boolean allowIgnoreConflicts, boolean allowRemoveProjectFolder, boolean allowAddExclusionPatterns, IContainer parent) {
-
- super(PAGE_NAME);
-
- fLinkedMode= linkedMode;
- fCanCommitConflictingBuildpath= canCommitConflictingBuildpath;
- fAllowConflict= allowIgnoreConflicts;
- fAllowRemoveProjectFolder= allowRemoveProjectFolder;
- fAllowAddExclusionPatterns= allowAddExclusionPatterns;
- fParent= parent;
-
- fOrginalExlusionFilters= new Hashtable();
- fOrginalInclusionFilters= new Hashtable();
- fOrginalExlusionFiltersCopy= new Hashtable();
- fOrginalInclusionFiltersCopy= new Hashtable();
- for (Iterator iter= existingEntries.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- IPath[] exlusions= (IPath[])element.getAttribute(CPListElement.EXCLUSION);
- if (exlusions != null) {
- IPath[] save= new IPath[exlusions.length];
- for (int i= 0; i < save.length; i++) {
- save[i]= exlusions[i];
- }
- fOrginalExlusionFiltersCopy.put(element, save);
- fOrginalExlusionFilters.put(element, exlusions);
- }
- IPath[] inclusions= (IPath[])element.getAttribute(CPListElement.INCLUSION);
- if (inclusions != null) {
- IPath[] save= new IPath[inclusions.length];
- for (int i= 0; i < save.length; i++) {
- save[i]= inclusions[i];
- }
- fOrginalInclusionFiltersCopy.put(element, save);
- fOrginalInclusionFilters.put(element, inclusions);
- }
- }
-
- setTitle(NewWizardMessages.NewSourceFolderWizardPage_title);
- fOrginalPath= newElement.getPath();
- if (fOrginalPath == null) {
- if (linkedMode) {
- setDescription(Messages.format(NewWizardMessages.NewFolderDialog_createIn, newElement.getJavaProject().getElementName()));
- } else {
- setDescription(Messages.format(NewWizardMessages.AddSourceFolderWizardPage_description, fParent.getFullPath().toString()));
- }
- } else {
- setDescription(NewWizardMessages.NewSourceFolderWizardPage_edit_description);
- }
-
- fNewElement= newElement;
- fExistingEntries= existingEntries;
- fModifiedElements= new ArrayList();
- fRemovedElements= new ArrayList();
-
- RootFieldAdapter adapter= new RootFieldAdapter();
-
- fRootDialogField= new StringDialogField();
- fRootDialogField.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_root_label);
- if (fNewElement.getPath() == null) {
- fRootDialogField.setText(""); //$NON-NLS-1$
- } else {
- setFolderDialogText(fNewElement.getPath());
- }
- fRootDialogField.setEnabled(fNewElement.getJavaProject() != null);
-
- int buttonStyle= SWT.CHECK;
- if ((fAllowConflict && fAllowAddExclusionPatterns) ||
- (fAllowConflict && fAllowRemoveProjectFolder) ||
- (fAllowAddExclusionPatterns && fAllowRemoveProjectFolder)) {
- buttonStyle= SWT.RADIO;
- }
-
- fAddExclusionPatterns= new SelectionButtonDialogField(buttonStyle);
- fAddExclusionPatterns.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_exclude_label);
- fAddExclusionPatterns.setSelection(true);
-
- fRemoveProjectFolder= new SelectionButtonDialogField(buttonStyle);
- fRemoveProjectFolder.setLabelText(NewWizardMessages.NewSourceFolderWizardPage_ReplaceExistingSourceFolder_label);
- fRemoveProjectFolder.setSelection(false);
-
- fIgnoreConflicts= new SelectionButtonDialogField(buttonStyle);
- fIgnoreConflicts.setLabelText(NewWizardMessages.AddSourceFolderWizardPage_ignoreNestingConflicts);
- fIgnoreConflicts.setSelection(false);
-
- fLinkFields= new LinkFields();
- if (fNewElement.getLinkTarget() != null) {
- fLinkFields.setLinkTarget(fNewElement.getLinkTarget());
- }
-
- fRemoveProjectFolder.setDialogFieldListener(adapter);
- fAddExclusionPatterns.setDialogFieldListener(adapter);
- fIgnoreConflicts.setDialogFieldListener(adapter);
- fRootDialogField.setDialogFieldListener(adapter);
- fLinkFields.setDialogFieldListener(adapter);
-
- packRootDialogFieldChanged();
- }
-
- // -------- UI Creation ---------
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
-
- GridLayout layout= new GridLayout();
- layout.numColumns= 4;
- composite.setLayout(layout);
-
- if (fLinkedMode) {
- fLinkFields.doFillIntoGrid(composite, layout.numColumns);
- fRootDialogField.doFillIntoGrid(composite, layout.numColumns - 1);
- } else {
- fRootDialogField.doFillIntoGrid(composite, layout.numColumns - 1);
- }
-
- if (fAllowRemoveProjectFolder)
- fRemoveProjectFolder.doFillIntoGrid(composite, layout.numColumns);
-
- if (fAllowAddExclusionPatterns)
- fAddExclusionPatterns.doFillIntoGrid(composite, layout.numColumns);
-
- if (fAllowConflict)
- fIgnoreConflicts.doFillIntoGrid(composite, layout.numColumns);
-
- LayoutUtil.setHorizontalSpan(fRootDialogField.getLabelControl(null), layout.numColumns);
- LayoutUtil.setHorizontalGrabbing(fRootDialogField.getTextControl(null));
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- fRootDialogField.setFocus();
- }
- }
-
- // -------- ContainerFieldAdapter --------
-
- private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
-
- // -------- IStringButtonAdapter
- public void changeControlPressed(DialogField field) {
- packRootChangeControlPressed(field);
- }
-
- // -------- IDialogFieldListener
- public void dialogFieldChanged(DialogField field) {
- packRootDialogFieldChanged();
- }
- }
-
- protected void packRootChangeControlPressed(DialogField field) {
- if (field == fRootDialogField) {
- IPath initialPath= new Path(fRootDialogField.getText());
- String title= NewWizardMessages.NewSourceFolderWizardPage_ChooseExistingRootDialog_title;
- String message= NewWizardMessages.NewSourceFolderWizardPage_ChooseExistingRootDialog_description;
- IFolder folder= chooseFolder(title, message, initialPath);
- if (folder != null) {
- setFolderDialogText(folder.getFullPath());
- }
- }
- }
-
- private void setFolderDialogText(IPath path) {
- IPath shortPath= path.removeFirstSegments(1);
- fRootDialogField.setText(shortPath.toString());
- }
-
- protected void packRootDialogFieldChanged() {
- StatusInfo status= updateRootStatus();
- updateStatus(new IStatus[] {status});
- }
-
- private StatusInfo updateRootStatus() {
- IJavaScriptProject javaProject= fNewElement.getJavaProject();
- IProject project= javaProject.getProject();
-
- StatusInfo pathNameStatus= validatePathName(fRootDialogField.getText(), fParent);
-
- if (!pathNameStatus.isOK())
- return pathNameStatus;
-
- if (fLinkedMode) {
- IStatus linkNameStatus= validateLinkLocation(fRootDialogField.getText());
- if (linkNameStatus.matches(IStatus.ERROR)) {
- StatusInfo result= new StatusInfo();
- result.setError(linkNameStatus.getMessage());
- return result;
- }
- }
-
- StatusInfo result= new StatusInfo();
- result.setOK();
-
- IPath projPath= project.getFullPath();
- IPath path= fParent.getFullPath().append(fRootDialogField.getText());
-
- restoreCPElements();
-
- int projectEntryIndex= -1;
- boolean createFolderForExisting= false;
-
- IFolder folder= fParent.getFolder(new Path(fRootDialogField.getText()));
- for (int i= 0; i < fExistingEntries.size(); i++) {
- IIncludePathEntry curr= ((CPListElement)fExistingEntries.get(i)).getClasspathEntry();
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (path.equals(curr.getPath()) && fExistingEntries.get(i) != fNewElement) {
- if (folder.exists()) {
- result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExisting);
- return result;
- } else {
- createFolderForExisting= true;
- }
- }
- if (projPath.equals(curr.getPath())) {
- projectEntryIndex= i;
- }
- }
- }
-
- if (folder.exists() && !folder.getFullPath().equals(fOrginalPath))
- return new StatusInfo(IStatus.ERROR, Messages.format(NewWizardMessages.NewFolderDialog_folderNameEmpty_alreadyExists, folder.getFullPath().toString()));
-
- boolean isProjectASourceFolder= projectEntryIndex != -1;
-
- fModifiedElements.clear();
- updateFilters(fNewElement.getPath(), path);
-
- fNewElement.setPath(path);
- if (fLinkedMode) {
- fNewElement.setLinkTarget(fLinkFields.getLinkTarget());
- }
- fRemovedElements.clear();
- Set modified= new HashSet();
- boolean isProjectSourceFolderReplaced= false;
- if (fAddExclusionPatterns.isSelected()) {
- if (fOrginalPath == null) {
- addExclusionPatterns(fNewElement, fExistingEntries, modified);
- fModifiedElements.addAll(modified);
- if (!createFolderForExisting)
- CPListElement.insert(fNewElement, fExistingEntries);
- }
- } else {
- if (isProjectASourceFolder) {
- if (fRemoveProjectFolder.isSelected()) {
- fOldProjectSourceFolder= (CPListElement)fExistingEntries.get(projectEntryIndex);
- fRemovedElements.add(fOldProjectSourceFolder);
- fExistingEntries.set(projectEntryIndex, fNewElement);
- isProjectSourceFolderReplaced= true;
- } else {
- if (!createFolderForExisting)
- CPListElement.insert(fNewElement, fExistingEntries);
- }
- } else {
- if (!createFolderForExisting)
- CPListElement.insert(fNewElement, fExistingEntries);
- }
- }
-
- if ((!fAllowConflict && fCanCommitConflictingBuildpath) || createFolderForExisting)
- return new StatusInfo();
-
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(javaProject, CPListElement.convertToClasspathEntries(fExistingEntries));
- if (!status.isOK()) {
- //Don't know what the problem is, report to user
- if (fCanCommitConflictingBuildpath) {
- result.setInfo(NewWizardMessages.AddSourceFolderWizardPage_conflictWarning + status.getMessage());
- } else {
- result.setError(status.getMessage());
- }
- return result;
- }
- if (!modified.isEmpty()) {
- //Added exclusion patterns to solve problem
- if (modified.size() == 1) {
- CPListElement elem= (CPListElement)modified.toArray()[0];
- IPath changed= elem.getPath().makeRelative();
- IPath excl= fNewElement.getPath().makeRelative();
- result.setInfo(Messages.format(NewWizardMessages.AddSourceFolderWizardPage_addSinglePattern, new Object[] {excl, changed}));
- } else {
- result.setInfo(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_warning_AddedExclusions, String.valueOf(modified.size())));
- }
- return result;
- }
- if (isProjectSourceFolderReplaced) {
- result.setInfo(NewWizardMessages.AddSourceFolderWizardPage_replaceSourceFolderInfo);
- return result;
- }
-
- return result;
- }
-
- public void restore() {
- for (Iterator iter= fExistingEntries.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- if (fOrginalExlusionFilters.containsKey(element)) {
- element.setAttribute(CPListElement.EXCLUSION, fOrginalExlusionFiltersCopy.get(element));
- }
- if (fOrginalInclusionFilters.containsKey(element)) {
- element.setAttribute(CPListElement.INCLUSION, fOrginalInclusionFiltersCopy.get(element));
- }
- }
- fNewElement.setPath(fOrginalPath);
- }
-
- private void restoreCPElements() {
- if (fNewElement.getPath() != null) {
- for (Iterator iter= fExistingEntries.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- if (fOrginalExlusionFilters.containsKey(element)) {
- element.setAttribute(CPListElement.EXCLUSION, fOrginalExlusionFilters.get(element));
- }
- if (fOrginalInclusionFilters.containsKey(element)) {
- element.setAttribute(CPListElement.INCLUSION, fOrginalInclusionFilters.get(element));
- }
- }
-
- if (fOldProjectSourceFolder != null) {
- fExistingEntries.set(fExistingEntries.indexOf(fNewElement), fOldProjectSourceFolder);
- fOldProjectSourceFolder= null;
- } else if (fExistingEntries.contains(fNewElement)) {
- fExistingEntries.remove(fNewElement);
- }
- }
- }
-
- private void updateFilters(IPath oldPath, IPath newPath) {
- if (oldPath == null)
- return;
-
- IPath projPath= fNewElement.getJavaProject().getProject().getFullPath();
- if (projPath.isPrefixOf(oldPath)) {
- oldPath= oldPath.removeFirstSegments(projPath.segmentCount()).addTrailingSeparator();
- }
- if (projPath.isPrefixOf(newPath)) {
- newPath= newPath.removeFirstSegments(projPath.segmentCount()).addTrailingSeparator();
- }
-
- for (Iterator iter= fExistingEntries.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- IPath elementPath= element.getPath();
- if (projPath.isPrefixOf(elementPath)) {
- elementPath= elementPath.removeFirstSegments(projPath.segmentCount());
- if (elementPath.segmentCount() > 0)
- elementPath= elementPath.addTrailingSeparator();
- }
-
- IPath[] exlusions= (IPath[])element.getAttribute(CPListElement.EXCLUSION);
- if (exlusions != null) {
- for (int i= 0; i < exlusions.length; i++) {
- if (elementPath.append(exlusions[i]).equals(oldPath)) {
- fModifiedElements.add(element);
- exlusions[i]= newPath.removeFirstSegments(elementPath.segmentCount());
- }
- }
- element.setAttribute(CPListElement.EXCLUSION, exlusions);
- }
-
- IPath[] inclusion= (IPath[])element.getAttribute(CPListElement.INCLUSION);
- if (inclusion != null) {
- for (int i= 0; i < inclusion.length; i++) {
- if (elementPath.append(inclusion[i]).equals(oldPath)) {
- fModifiedElements.add(element);
- inclusion[i]= newPath.removeFirstSegments(elementPath.segmentCount());
- }
- }
- element.setAttribute(CPListElement.INCLUSION, inclusion);
- }
- }
- }
-
- /**
- * Validates this page's controls.
- *
- * @return IStatus indicating the validation result. IStatus.OK if the
- * specified link target is valid given the linkHandle.
- */
- private IStatus validateLinkLocation(String folderName) {
- IWorkspace workspace= JavaScriptPlugin.getWorkspace();
- IPath path= Path.fromOSString(fLinkFields.fLinkLocation.getText());
-
- IFolder folder= fNewElement.getJavaProject().getProject().getFolder(new Path(folderName));
- IStatus locationStatus= workspace.validateLinkLocation(folder, path);
- if (locationStatus.matches(IStatus.ERROR))
- return locationStatus;
-
- IPathVariableManager pathVariableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
- IPath path1= Path.fromOSString(fLinkFields.fLinkLocation.getText());
- IPath resolvedPath= pathVariableManager.resolvePath(path1);
- // use the resolved link target name
- String resolvedLinkTarget= resolvedPath.toOSString();
-
- path= new Path(resolvedLinkTarget);
- File linkTargetFile= new Path(resolvedLinkTarget).toFile();
- if (linkTargetFile.exists()) {
- if (!linkTargetFile.isDirectory())
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.NewFolderDialog_linkTargetNotFolder);
- } else {
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.NewFolderDialog_linkTargetNonExistent);
- }
- if (locationStatus.isOK()) {
- return new StatusInfo();
- }
- return new StatusInfo(locationStatus.getSeverity(), locationStatus.getMessage());
- }
-
- private static StatusInfo validatePathName(String str, IContainer parent) {
- StatusInfo result= new StatusInfo();
- result.setOK();
-
- IPath parentPath= parent.getFullPath();
-
- if (str.length() == 0) {
- result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_EnterRootName, parentPath.toString()));
- return result;
- }
-
- IPath path= parentPath.append(str);
-
- IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
- IStatus validate= workspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
- if (validate.matches(IStatus.ERROR)) {
- result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
- return result;
- }
-
- IResource res= workspaceRoot.findMember(path);
- if (res != null) {
- if (res.getType() != IResource.FOLDER) {
- result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
- return result;
- }
- } else {
-
- URI parentLocation= parent.getLocationURI();
- if (parentLocation != null) {
- try {
- IFileStore store= EFS.getStore(parentLocation).getChild(str);
- if (store.fetchInfo().exists()) {
- result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
- return result;
- }
- } catch (CoreException e) {
- // we couldn't create the file store. Ignore the exception
- // since we can't check if the file exist. Pretend that it
- // doesn't.
- }
- }
- }
-
- return result;
- }
-
- private void addExclusionPatterns(CPListElement newEntry, List existing, Set modifiedEntries) {
- IPath entryPath= newEntry.getPath();
- for (int i= 0; i < existing.size(); i++) {
- CPListElement curr= (CPListElement) existing.get(i);
- IPath currPath= curr.getPath();
- if (curr != newEntry && curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE && currPath.isPrefixOf(entryPath)) {
- boolean added= curr.addToExclusions(entryPath);
- if (added) {
- modifiedEntries.add(curr);
- }
- }
- }
- }
-
- public IResource getCorrespondingResource() {
- return fParent.getFolder(new Path(fRootDialogField.getText()));
- }
-
- // ------------- choose dialogs
-
- private IFolder chooseFolder(String title, String message, IPath initialPath) {
- Class[] acceptedClasses= new Class[] { IFolder.class };
- ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses, null);
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new WorkbenchContentProvider();
-
- IProject currProject= fNewElement.getJavaProject().getProject();
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp) {
- protected Control createDialogArea(Composite parent) {
- Control result= super.createDialogArea(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_CHOOSE_EXISTING_FOLDER_TO_MAKE_SOURCE_FOLDER);
- return result;
- }
- };
- dialog.setValidator(validator);
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.addFilter(filter);
- dialog.setInput(currProject);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- IResource res= currProject.findMember(initialPath);
- if (res != null) {
- dialog.setInitialSelection(res);
- }
-
- if (dialog.open() == Window.OK) {
- return (IFolder) dialog.getFirstResult();
- }
- return null;
- }
-
- public List getModifiedElements() {
- if (fOrginalPath != null && !fModifiedElements.contains(fNewElement))
- fModifiedElements.add(fNewElement);
-
- return fModifiedElements;
- }
-
- public List getRemovedElements() {
- return fRemovedElements;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ArchiveFileFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ArchiveFileFilter.java
deleted file mode 100644
index 2eda6d57..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ArchiveFileFilter.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Viewer filter for archive selection dialogs.
- * Archives are files with file extension 'jar' and 'zip'.
- * The filter is not case sensitive.
- */
-public class ArchiveFileFilter extends ViewerFilter {
-
- //public static final String[] FILTER_EXTENSIONS= new String[] {"*.jar;*.zip"}; //$NON-NLS-1$
- public static final String[] FILTER_EXTENSIONS= new String[] {"*.js"}; //$NON-NLS-1$
- private static final String[] fgArchiveExtensions= { "js"}; //$NON-NLS-1$ //$NON-NLS-2$
- //private static final String[] fgArchiveExtensions= {"*jar","zip"}; //$NON-NLS-1$ //$NON-NLS-2$
- private List fExcludes;
- private boolean fRecursive;
-
- /**
- * @param excludedFiles Excluded files will not pass the filter.
- * <code>null</code> is allowed if no files should be excluded.
- * @param recusive Folders are only shown if, searched recursively, contain
- * an archive
- */
- public ArchiveFileFilter(IFile[] excludedFiles, boolean recusive) {
- if (excludedFiles != null) {
- fExcludes= Arrays.asList(excludedFiles);
- } else {
- fExcludes= null;
- }
- fRecursive= recusive;
- }
-
- public ArchiveFileFilter(List excludedFiles, boolean recusive) {
- fExcludes= excludedFiles;
- fRecursive= recusive;
- }
-
- /*
- * @see ViewerFilter#select
- */
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IFile) {
- if (fExcludes != null && fExcludes.contains(element)) {
- return false;
- }
- return isArchivePath(((IFile)element).getFullPath());
- } else if (element instanceof IContainer) { // IProject, IFolder
- if (!fRecursive) {
- return true;
- }
- // Ignore closed projects
- if (element instanceof IProject && !((IProject)element).isOpen())
- return false;
- try {
- IResource[] resources= ((IContainer)element).members();
- for (int i= 0; i < resources.length; i++) {
- // recursive! Only show containers that contain an archive
- if (select(viewer, parent, resources[i])) {
- return true;
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e.getStatus());
- }
- }
- return false;
- }
-
- public static boolean isArchivePath(IPath path) {
- String ext= path.getFileExtension();
- if (ext != null && ext.length() != 0) {
- return isArchiveFileExtension(ext);
- }
- return false;
- }
-
- public static boolean isArchiveFileExtension(String ext) {
- for (int i= 0; i < fgArchiveExtensions.length; i++) {
- if (ext.equalsIgnoreCase(fgArchiveExtensions[i])) {
- return true;
- }
- }
- return false;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathBasePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathBasePage.java
deleted file mode 100644
index 5ccd81ae..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathBasePage.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration;
-
-public abstract class BuildPathBasePage {
-
- private ClasspathAttributeConfigurationDescriptors fAttributeDescriptors;
-
- public BuildPathBasePage() {
- fAttributeDescriptors= JavaScriptPlugin.getDefault().getClasspathAttributeConfigurationDescriptors();
- }
-
- protected boolean editCustomAttribute(Shell shell, CPListElementAttribute elem) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(elem.getKey());
- if (config != null) {
- IIncludePathAttribute result= config.performEdit(shell, elem.getClasspathAttributeAccess());
- if (result != null) {
- elem.setValue(result.getValue());
- return true;
- }
- }
- return false;
- }
-
- protected boolean removeCustomAttribute(CPListElementAttribute elem) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(elem.getKey());
- if (config != null) {
- IIncludePathAttribute result= config.performRemove(elem.getClasspathAttributeAccess());
- if (result != null) {
- elem.setValue(result.getValue());
- return true;
- }
- }
- return false;
- }
-
- protected boolean canEditCustomAttribute(CPListElementAttribute elem) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(elem.getKey());
- if (config != null) {
- return config.canEdit(elem.getClasspathAttributeAccess());
- }
- return false;
- }
-
- protected boolean canRemoveCustomAttribute(CPListElementAttribute elem) {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(elem.getKey());
- if (config != null) {
- return config.canRemove(elem.getClasspathAttributeAccess());
- }
- return false;
- }
-
-
- public abstract List getSelection();
- public abstract void setSelection(List selection, boolean expand);
-
-
- public void addElement(CPListElement element) {
-
- }
-
- public abstract boolean isEntryKind(int kind);
-
- protected void filterAndSetSelection(List list) {
- ArrayList res= new ArrayList(list.size());
- for (int i= list.size()-1; i >= 0; i--) {
- Object curr= list.get(i);
- if (curr instanceof CPListElement) {
- CPListElement elem= (CPListElement) curr;
- if (elem.getParentContainer() == null && isEntryKind(elem.getEntryKind())) {
- res.add(curr);
- }
- }
- }
- setSelection(res, false);
- }
-
- public static void fixNestingConflicts(CPListElement[] newEntries, CPListElement[] existing, Set modifiedSourceEntries) {
- for (int i= 0; i < newEntries.length; i++) {
- addExclusionPatterns(newEntries[i], existing, modifiedSourceEntries);
- }
- }
-
- private static void addExclusionPatterns(CPListElement newEntry, CPListElement[] existing, Set modifiedEntries) {
- IPath entryPath= newEntry.getPath();
- for (int i= 0; i < existing.length; i++) {
- CPListElement curr= existing[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- IPath currPath= curr.getPath();
- if (!currPath.equals(entryPath)) {
- if (currPath.isPrefixOf(entryPath)) {
- if (addToExclusions(entryPath, curr)) {
- modifiedEntries.add(curr);
- }
- } else if (entryPath.isPrefixOf(currPath) && newEntry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (addToExclusions(currPath, newEntry)) {
- modifiedEntries.add(curr);
- }
- }
- }
- }
- }
- }
-
- private static boolean addToExclusions(IPath entryPath, CPListElement curr) {
- IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
- if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
- IPath pathToExclude= entryPath.removeFirstSegments(curr.getPath().segmentCount()).addTrailingSeparator();
- IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
- System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
- newExclusionFilters[exclusionFilters.length]= pathToExclude;
- curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
- return true;
- }
- return false;
- }
-
- protected boolean containsOnlyTopLevelEntries(List selElements) {
- if (selElements.size() == 0) {
- return true;
- }
- for (int i= 0; i < selElements.size(); i++) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElement) {
- if (((CPListElement) elem).getParentContainer() != null) {
- return false;
- }
- } else {
- return false;
- }
- }
- return true;
- }
-
- public abstract void init(IJavaScriptProject javaProject);
-
- public abstract Control getControl(Composite parent);
-
- public abstract void setFocus();
-
- public void aboutToShow() {}
- public void aboutToDispose() {}
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathSupport.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathSupport.java
deleted file mode 100644
index 70b45048..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathSupport.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- *
- */
-public class BuildPathSupport {
-
- public static final String JRE_PREF_PAGE_ID= "org.eclipse.wst.jsdt.debug.ui.preferences.VMPreferencePage"; //$NON-NLS-1$
-
-
- private BuildPathSupport() {
- super();
- }
-
- /**
- * Returns a deprecation message for a classpath variable name.
- *
- * @param variableName classpath variable name
- * @return the deprecation message, or <code>null</code> iff
- * <code>variableName</code> is not a classpath variable or the
- * variable is not deprecated
- */
- public static String getDeprecationMessage(String variableName) {
- String deprecationMessage= JavaScriptCore.getIncludepathVariableDeprecationMessage(variableName);
- if (deprecationMessage == null )
- return null;
- else
- return Messages.format(NewWizardMessages.BuildPathSupport_deprecated,
- new Object[] {variableName, deprecationMessage});
- }
-
- /**
- * Finds a source attachment for a new archive in the existing classpaths.
- * @param elem The new classpath entry
- * @return A path to be taken for the source attachment or <code>null</code>
- */
- public static IPath guessSourceAttachment(CPListElement elem) {
- if (elem.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- return null;
- }
- IJavaScriptProject currProject= elem.getJavaProject(); // can be null
- try {
- // try if the jar itself contains the source
- IJavaScriptModel jmodel= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- IJavaScriptProject[] jprojects= jmodel.getJavaScriptProjects();
- for (int i= 0; i < jprojects.length; i++) {
- IJavaScriptProject curr= jprojects[i];
- if (!curr.equals(currProject)) {
- IIncludePathEntry[] entries= curr.getRawIncludepath();
- for (int k= 0; k < entries.length; k++) {
- IIncludePathEntry entry= entries[k];
- if (entry.getEntryKind() == elem.getEntryKind()
- && entry.getPath().equals(elem.getPath())) {
- IPath attachPath= entry.getSourceAttachmentPath();
- if (attachPath != null && !attachPath.isEmpty()) {
- return attachPath;
- }
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus());
- }
- return null;
- }
-
- /**
- * Finds a javadoc location for a new archive in the existing classpaths.
- * @param elem The new classpath entry
- * @return A javadoc location found in a similar classpath entry or <code>null</code>.
- */
- public static String guessJavadocLocation(CPListElement elem) {
- if (elem.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- return null;
- }
- IJavaScriptProject currProject= elem.getJavaProject(); // can be null
- try {
- // try if the jar itself contains the source
- IJavaScriptModel jmodel= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- IJavaScriptProject[] jprojects= jmodel.getJavaScriptProjects();
- for (int i= 0; i < jprojects.length; i++) {
- IJavaScriptProject curr= jprojects[i];
- if (!curr.equals(currProject)) {
- IIncludePathEntry[] entries= curr.getRawIncludepath();
- for (int k= 0; k < entries.length; k++) {
- IIncludePathEntry entry= entries[k];
- if (entry.getEntryKind() == elem.getEntryKind() && entry.getPath().equals(elem.getPath())) {
- IIncludePathAttribute[] attributes= entry.getExtraAttributes();
- for (int n= 0; n < attributes.length; n++) {
- IIncludePathAttribute attrib= attributes[n];
- if (IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
- return attrib.getValue();
- }
- }
- }
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus());
- }
- return null;
- }
-
- private static class UpdatedJsGlobalScopeContainer implements IJsGlobalScopeContainer {
-
- private IIncludePathEntry[] fNewEntries;
- private IJsGlobalScopeContainer fOriginal;
-
- public UpdatedJsGlobalScopeContainer(IJsGlobalScopeContainer original, IIncludePathEntry[] newEntries) {
- fNewEntries= newEntries;
- fOriginal= original;
- }
-
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- public IIncludePathEntry[] getIncludepathEntries() {
- return fNewEntries;
- }
-
- public String getDescription() {
- return fOriginal.getDescription();
- }
-
- public int getKind() {
- return fOriginal.getKind();
- }
-
- public IPath getPath() {
- return fOriginal.getPath();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#resolvedLibraryImport(java.lang.String)
- */
- public String[] resolvedLibraryImport(String a) {
- return null;
- }
- }
-
- /**
- * Apply a modified classpath entry to the classpath. The classpath entry can also be from a classpath container.
- * @param shell If not null and the entry could not be found on the projects classpath, a dialog will ask to put the entry on the classpath
- * @param newEntry The modified entry. The entry's kind or path must be unchanged.
- * @param changedAttributes The attibutes that have changed. See {@link CPListElement} for constants values.
- * @param jproject Project where the entry belongs to
- * @param containerPath The path of the entry's parent container or <code>null</code> if the entry is not in a container
- * @param monitor The progress monitor to use
- * @throws CoreException
- */
- public static void modifyClasspathEntry(Shell shell, IIncludePathEntry newEntry, String[] changedAttributes, IJavaScriptProject jproject, IPath containerPath, IProgressMonitor monitor) throws CoreException {
- if (containerPath != null) {
- updateContainerClasspath(jproject, containerPath, newEntry, changedAttributes, monitor);
- } else {
- updateProjectClasspath(shell, jproject, newEntry, changedAttributes, monitor);
- }
- }
-
-
- /**
- * Apply a modified classpath entry to the classpath. The classpath entry can also be from a classpath container.
- * @param shell If not null and the entry could not be found on the projects classpath, a dialog will ask to put the entry on the classpath
- * @param newEntry The modified entry. The entry's kind or path must be unchanged.
- * @param jproject Project where the entry belongs to
- * @param containerPath The path of the entry's parent container or <code>null</code> if the entry is not in a container
- * @param monitor The progress monitor to use
- * @throws CoreException
- */
- public static void modifyClasspathEntry(Shell shell, IIncludePathEntry newEntry, IJavaScriptProject jproject, IPath containerPath, IProgressMonitor monitor) throws CoreException {
- modifyClasspathEntry(shell, newEntry, null, jproject, containerPath, monitor);
- }
-
- private static void updateContainerClasspath(IJavaScriptProject jproject, IPath containerPath, IIncludePathEntry newEntry, String[] changedAttributes, IProgressMonitor monitor) throws CoreException {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, jproject);
- if (container == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, "Container " + containerPath + " cannot be resolved", null)); //$NON-NLS-1$//$NON-NLS-2$
- }
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- IIncludePathEntry[] newEntries= new IIncludePathEntry[entries.length];
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr= entries[i];
- if (curr.getEntryKind() == newEntry.getEntryKind() && curr.getPath().equals(newEntry.getPath())) {
- newEntries[i]= getUpdatedEntry(curr, newEntry, changedAttributes, jproject);
- } else {
- newEntries[i]= curr;
- }
- }
- requestContainerUpdate(jproject, container, newEntries);
- monitor.worked(1);
- }
-
- private static IIncludePathEntry getUpdatedEntry(IIncludePathEntry currEntry, IIncludePathEntry updatedEntry, String[] updatedAttributes, IJavaScriptProject jproject) {
- if (updatedAttributes == null) {
- return updatedEntry; // used updated entry 'as is'
- }
- CPListElement currElem= CPListElement.createFromExisting(currEntry, jproject);
- CPListElement newElem= CPListElement.createFromExisting(updatedEntry, jproject);
- for (int i= 0; i < updatedAttributes.length; i++) {
- String attrib= updatedAttributes[i];
- currElem.setAttribute(attrib, newElem.getAttribute(attrib));
- }
- return currElem.getClasspathEntry();
- }
-
- /**
- * Request a container update.
- * @param jproject The project of the container
- * @param container The container to requesta change to
- * @param newEntries The updated entries
- * @throws CoreException
- */
- public static void requestContainerUpdate(IJavaScriptProject jproject, IJsGlobalScopeContainer container, IIncludePathEntry[] newEntries) throws CoreException {
- IPath containerPath= container.getPath();
- IJsGlobalScopeContainer updatedContainer= new UpdatedJsGlobalScopeContainer(container, newEntries);
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- if (initializer != null) {
- initializer.requestJsGlobalScopeContainerUpdate(containerPath, jproject, updatedContainer);
- }
- }
-
- private static void updateProjectClasspath(Shell shell, IJavaScriptProject jproject, IIncludePathEntry newEntry, String[] changedAttributes, IProgressMonitor monitor) throws JavaScriptModelException {
- IIncludePathEntry[] oldClasspath= jproject.getRawIncludepath();
- int nEntries= oldClasspath.length;
- ArrayList newEntries= new ArrayList(nEntries + 1);
- int entryKind= newEntry.getEntryKind();
- IPath jarPath= newEntry.getPath();
- boolean found= false;
- for (int i= 0; i < nEntries; i++) {
- IIncludePathEntry curr= oldClasspath[i];
- if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
- // add modified entry
- newEntries.add(getUpdatedEntry(curr, newEntry, changedAttributes, jproject));
- found= true;
- } else {
- newEntries.add(curr);
- }
- }
- if (!found) {
- if (!putJarOnClasspathDialog(shell)) {
- return;
- }
- // add new
- newEntries.add(newEntry);
- }
- IIncludePathEntry[] newClasspath= (IIncludePathEntry[]) newEntries.toArray(new IIncludePathEntry[newEntries.size()]);
- jproject.setRawIncludepath(newClasspath, monitor);
- }
-
- private static boolean putJarOnClasspathDialog(final Shell shell) {
- if (shell == null) {
- return false;
- }
-
- final boolean[] result= new boolean[1];
- shell.getDisplay().syncExec(new Runnable() {
- public void run() {
- String title= NewWizardMessages.BuildPathSupport_putoncpdialog_title;
- String message= NewWizardMessages.BuildPathSupport_putoncpdialog_message;
- result[0]= MessageDialog.openQuestion(shell, title, message);
- }
- });
- return result[0];
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java
deleted file mode 100644
index 4b2faf1a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard;
-
-public abstract class BuildPathWizard extends NewElementWizard {
-
- private boolean fDoFlushChange;
- private final CPListElement fEntryToEdit;
- private IPackageFragmentRoot fPackageFragmentRoot;
- private final ArrayList fExistingEntries;
-
- public BuildPathWizard(CPListElement[] existingEntries, CPListElement newEntry, String titel, ImageDescriptor image) {
- if (image != null)
- setDefaultPageImageDescriptor(image);
-
- setDialogSettings(JavaScriptPlugin.getDefault().getDialogSettings());
- setWindowTitle(titel);
-
- fEntryToEdit= newEntry;
- fExistingEntries= new ArrayList(Arrays.asList(existingEntries));
- fDoFlushChange= true;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
- if (fDoFlushChange) {
- IJavaScriptProject javaProject= getEntryToEdit().getJavaProject();
-
- BuildPathsBlock.flush(getExistingEntries(), javaProject, getSuperType(), monitor);
-
- IProject project= javaProject.getProject();
- IPath path= getEntryToEdit().getPath();
-
- IResource folder= project.getWorkspace().getRoot().findMember(path);
- fPackageFragmentRoot= javaProject.getPackageFragmentRoot(folder);
- }
- }
- public LibrarySuperType getSuperType() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public IJavaScriptElement getCreatedElement() {
- return fPackageFragmentRoot;
- }
-
- public void setDoFlushChange(boolean b) {
- fDoFlushChange= b;
- }
-
- public ArrayList getExistingEntries() {
- return fExistingEntries;
- }
-
- protected CPListElement getEntryToEdit() {
- return fEntryToEdit;
- }
-
- public List/*<CPListElement>*/ getInsertedElements() {
- return new ArrayList();
- }
-
- public List/*<CPListElement>*/ getRemovedElements() {
- return new ArrayList();
- }
-
- public List/*<CPListElement>*/ getModifiedElements() {
- ArrayList result= new ArrayList(1);
- result.add(fEntryToEdit);
- return result;
- }
-
- public abstract void cancel();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
deleted file mode 100644
index 638b9cbd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
+++ /dev/null
@@ -1,1016 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.TabFolder;
-import org.eclipse.swt.widgets.TabItem;
-import org.eclipse.swt.widgets.Widget;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDisposer;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage.NewSourceContainerWorkbookPage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-public class BuildPathsBlock {
-
- private CheckedListDialogField fClassPathList;
-
- private StatusInfo fClassPathStatus;
- private StatusInfo fBuildPathStatus;
-
- private IJavaScriptProject fCurrJSProject;
-
- private IStatusChangeListener fContext;
- private Control fSWTWidget;
- private TabFolder fTabFolder;
-
- private int fPageIndex;
-
- private BuildPathBasePage fSourceContainerPage;
- private ProjectsWorkbookPage fProjectsPage;
- private LibrariesWorkbookPage fLibrariesPage;
-
- private BuildPathBasePage fCurrPage;
-
- private String fUserSettingsTimeStamp;
- private long fFileTimeStamp;
-
- private IRunnableContext fRunnableContext;
- private boolean fUseNewPage;
- private ClasspathOrderingWorkbookPage ordpage;
-
- private final IWorkbenchPreferenceContainer fPageContainer; // null when invoked from a non-property page context
-
- private final static int IDX_UP= 0;
- private final static int IDX_DOWN= 1;
- private final static int IDX_TOP= 3;
- private final static int IDX_BOTTOM= 4;
- private final static int IDX_SELECT_ALL= 6;
- private final static int IDX_UNSELECT_ALL= 7;
-
- public BuildPathsBlock(IRunnableContext runnableContext, IStatusChangeListener context, int pageToShow, boolean useNewPage, IWorkbenchPreferenceContainer pageContainer) {
- fPageContainer= pageContainer;
- fContext= context;
- fUseNewPage= useNewPage;
-
- fPageIndex= pageToShow;
-
- fSourceContainerPage= null;
- fLibrariesPage= null;
- fProjectsPage= null;
- fCurrPage= null;
- fRunnableContext= runnableContext;
-
- BuildPathAdapter adapter= new BuildPathAdapter();
-
- String[] buttonLabels= new String[] {
- /* IDX_UP */ NewWizardMessages.BuildPathsBlock_classpath_up_button,
- /* IDX_DOWN */ NewWizardMessages.BuildPathsBlock_classpath_down_button,
- /* 2 */ null,
- /* IDX_TOP */ NewWizardMessages.BuildPathsBlock_classpath_top_button,
- /* IDX_BOTTOM */ NewWizardMessages.BuildPathsBlock_classpath_bottom_button,
- /* 5 */ null,
- /* IDX_SELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_checkall_button,
- /* IDX_UNSELECT_ALL */ NewWizardMessages.BuildPathsBlock_classpath_uncheckall_button
-
- };
-
- fClassPathList= new CheckedListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fClassPathList.setDialogFieldListener(adapter);
- fClassPathList.setLabelText(NewWizardMessages.BuildPathsBlock_classpath_label);
- fClassPathList.setUpButtonIndex(IDX_UP);
- fClassPathList.setDownButtonIndex(IDX_DOWN);
- fClassPathList.setCheckAllButtonIndex(IDX_SELECT_ALL);
- fClassPathList.setUncheckAllButtonIndex(IDX_UNSELECT_ALL);
-
- fBuildPathStatus= new StatusInfo();
- fClassPathStatus= new StatusInfo();
-
- fCurrJSProject= null;
- }
-
- // -------- UI creation ---------
-
- public Control createControl(Composite parent) {
- fSWTWidget= parent;
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- layout.numColumns= 1;
- composite.setLayout(layout);
-
- TabFolder folder= new TabFolder(composite, SWT.NONE);
- folder.setLayoutData(new GridData(GridData.FILL_BOTH));
- folder.setFont(composite.getFont());
-
- TabItem item = null;
-
- // Libraries tab
- fLibrariesPage= new LibrariesWorkbookPage(fClassPathList, fPageContainer);
- item= new TabItem(folder, SWT.NONE);
- item.setText(NewWizardMessages.BuildPathsBlock_tab_scriptimport);
- item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LIBRARY));
- item.setData(fLibrariesPage);
- item.setControl(fLibrariesPage.getControl(folder));
-
-
- // source folders tab
- if (fUseNewPage) {
- fSourceContainerPage= new NewSourceContainerWorkbookPage(fClassPathList, fRunnableContext, this);
- } else {
- fSourceContainerPage= new SourceContainerWorkbookPage(fClassPathList);
- }
- item= new TabItem(folder, SWT.NONE);
- item.setText(NewWizardMessages.BuildPathsBlock_tab_source);
- item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
-
- item.setData(fSourceContainerPage);
- item.setControl(fSourceContainerPage.getControl(folder));
-
-
- // project dependency tab
- IWorkbench workbench= JavaScriptPlugin.getDefault().getWorkbench();
- Image projectImage= workbench.getSharedImages().getImage(IDE.SharedImages.IMG_OBJ_PROJECT);
-
- fProjectsPage= new ProjectsWorkbookPage(fClassPathList, fPageContainer);
- item= new TabItem(folder, SWT.NONE);
- item.setText(NewWizardMessages.BuildPathsBlock_tab_projects);
- item.setImage(projectImage);
- item.setData(fProjectsPage);
- item.setControl(fProjectsPage.getControl(folder));
-
-
- //global supertype tab
- Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
- composite.addDisposeListener(new ImageDisposer(cpoImage));
-
- ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
-
- /* init super type field with either default or the one defined for the project */
- ordpage.getSuperField().setValue(getProjectSuperType(fCurrJSProject));
-
- item= new TabItem(folder, SWT.NONE);
- item.setText(NewWizardMessages.BuildPathsBlock_GlobalOrder);
- item.setImage(cpoImage);
- item.setData(ordpage);
- item.setControl(ordpage.getControl(folder));
-
-
- //a non shared image
- if (fCurrJSProject != null) {
- fSourceContainerPage.init(fCurrJSProject);
- fLibrariesPage.init(fCurrJSProject);
- fProjectsPage.init(fCurrJSProject);
- ordpage.init(fCurrJSProject);
-
- }
-
- if(fPageIndex < folder.getItems().length) {
- folder.setSelection(fPageIndex);
- fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
- }
- folder.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- tabChanged(e.item);
- }
- });
- fTabFolder= folder;
-
- Dialog.applyDialogFont(composite);
- return composite;
- }
-
-// private Shell getShell() {
-// if (fSWTWidget != null) {
-// return fSWTWidget.getShell();
-// }
-// return JavaScriptPlugin.getActiveWorkbenchShell();
-// }
-
- /**
- * Initializes the classpath for the given project. Multiple calls to init are allowed,
- * but all existing settings will be cleared and replace by the given or default paths.
- * @param jproject The java project to configure. Does not have to exist.
- * @param outputLocation The output location to be set in the page. If <code>null</code>
- * is passed, jdt default settings are used, or - if the project is an existing Java project- the
- * output location of the existing project
- * @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
- * is passed, jdt default settings are used, or - if the project is an existing Java project - the
- * classpath entries of the existing project
- */
- // public void init(IJavaScriptProject jproject, IPath outputLocation, IIncludePathEntry[] classpathEntries) {
- public void init(IJavaScriptProject jproject,IIncludePathEntry[] classpathEntries) {
- fCurrJSProject= jproject;
- boolean projectExists= false;
- List newClassPath= null;
- IProject project= fCurrJSProject.getProject();
- projectExists= (project.exists() && jproject.getJSDTScopeFile().exists()); //$NON-NLS-1$
- if (projectExists) {
-// if (outputLocation == null) {
-// outputLocation= fCurrJProject.readOutputLocation();
-// }
- if (classpathEntries == null) {
- classpathEntries= fCurrJSProject.readRawIncludepath();
- }
- }
-//// if (outputLocation == null) {
-//// outputLocation= getDefaultOutputLocation(jproject);
-//// }
-//
- if (classpathEntries != null) {
- newClassPath= getExistingEntries(classpathEntries);
- }
- if (newClassPath == null) {
- newClassPath= getDefaultClassPath(jproject);
- }
-
- List exportedEntries = new ArrayList();
- for (int i= 0; i < newClassPath.size(); i++) {
- CPListElement curr= (CPListElement) newClassPath.get(i);
- if (curr.isExported() || curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- exportedEntries.add(curr);
- }
- }
-
- // inits the dialog field
- //fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
- //fBuildPathDialogField.enableButton(project.exists());
-
- fClassPathList.setElements(newClassPath);
- fClassPathList.setCheckedElements(exportedEntries);
-
- fClassPathList.selectFirstElement();
-
- if (fSourceContainerPage != null) {
- fSourceContainerPage.init(fCurrJSProject);
- fProjectsPage.init(fCurrJSProject);
- fLibrariesPage.init(fCurrJSProject);
- }
-
- initializeTimeStamps();
- updateUI();
- }
-
- protected void updateUI() {
- if (fSWTWidget == null || fSWTWidget.isDisposed()) {
- return;
- }
-
- if (Display.getCurrent() != null) {
- doUpdateUI();
- } else {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- if (fSWTWidget == null || fSWTWidget.isDisposed()) {
- return;
- }
- doUpdateUI();
- }
- });
- }
- }
-
- public void setSuperType(LibrarySuperType type) {
- ordpage.getSuperField().setValue(type);
-
- }
-
- protected void doUpdateUI() {
- // fBuildPathDialogField.refresh();
- fClassPathList.refresh();
-
- doStatusLineUpdate();
- }
-
- private String getEncodedSettings() {
- StringBuffer buf= new StringBuffer();
- //CPListElement.appendEncodePath(fOutputLocationPath, buf).append(';');
-
- int nElements= fClassPathList.getSize();
- buf.append('[').append(nElements).append(']');
- for (int i= 0; i < nElements; i++) {
- CPListElement elem= (CPListElement) fClassPathList.getElement(i);
- elem.appendEncodedSettings(buf);
- }
- return buf.toString();
- }
-
- public boolean hasChangesInSuper() {
- LibrarySuperType savedSuperType = getProjectSuperType(fCurrJSProject);
-
- Object o = ordpage.getSuperField().getValue();
-
- if(o!=null && !o.equals(savedSuperType)) return true;
- return false;
- }
-
- public boolean hasChangesInDialog() {
-
-
-
- String currSettings= getEncodedSettings();
- return !currSettings.equals(fUserSettingsTimeStamp);
- }
-
- public void aboutToDispose() {
- if(fCurrPage!=null) fCurrPage.aboutToDispose();
- }
-
- public void aboutToShow() {
- if(fCurrPage!=null) fCurrPage.aboutToShow();
- }
- public boolean hasChangesInClasspathFile() {
- IFile file= fCurrJSProject.getJSDTScopeFile(); //$NON-NLS-1$
- return fFileTimeStamp != file.getModificationStamp();
- }
-
- public boolean isClassfileMissing() {
- return !fCurrJSProject.getJSDTScopeFile().exists(); //$NON-NLS-1$
- }
-
- public void initializeTimeStamps() {
- IFile file= fCurrJSProject.getJSDTScopeFile(true); //$NON-NLS-1$
- fFileTimeStamp= file.getModificationStamp();
- fUserSettingsTimeStamp= getEncodedSettings();
- }
-
- private ArrayList getExistingEntries(IIncludePathEntry[] classpathEntries) {
- ArrayList newClassPath= new ArrayList();
- for (int i= 0; i < classpathEntries.length; i++) {
- IIncludePathEntry curr= classpathEntries[i];
- newClassPath.add(CPListElement.createFromExisting(curr, fCurrJSProject));
- }
- return newClassPath;
- }
-
- // -------- public api --------
-
- /**
- * @return Returns the Java project. Can return <code>null<code> if the page has not
- * been initialized.
- */
- public IJavaScriptProject getJavaProject() {
- return fCurrJSProject;
- }
-
- /**
- * @return Returns the current output location. Note that the path returned must not be valid.
- */
- public IPath getOutputLocation() {
- //return new Path(fBuildPathDialogField.getText()).makeAbsolute();
- return new Path(""); //$NON-NLS-1$
- }
-
- /**
- * @return Returns the current class path (raw). Note that the entries returned must not be valid.
- */
- public IIncludePathEntry[] getRawClassPath() {
- List elements= fClassPathList.getElements();
- int nElements= elements.size();
- IIncludePathEntry[] entries= new IIncludePathEntry[elements.size()];
-
- for (int i= 0; i < nElements; i++) {
- CPListElement currElement= (CPListElement) elements.get(i);
- entries[i]= currElement.getClasspathEntry();
- }
- return entries;
- }
-
- public int getPageIndex() {
- return fPageIndex;
- }
-
-
- // -------- evaluate default settings --------
- private List getDefaultClassPath(IJavaScriptProject jproj) {
- List list= new ArrayList();
- IResource srcFolder;
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
- if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
- srcFolder= jproj.getProject().getFolder(sourceFolderName);
- } else {
- srcFolder= jproj.getProject();
- }
-
- list.add(new CPListElement(jproj, IIncludePathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
-
- IIncludePathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
- list.addAll(getExistingEntries(jreEntries));
- return list;
- }
-// private List getDefaultClassPath(IJavaScriptProject jproj) {
-// List list= new ArrayList();
-//
-//
-//
-//
-// IIncludePathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
-// list.addAll(getExistingEntries(jreEntries));
-// CPListElement projectSourceRoot = new CPListElement(jproj, IIncludePathEntry.CPE_SOURCE,jproj.getProject().getFullPath(),jproj.getProject());
-//
-//
-// projectSourceRoot.setAttribute(CPListElement.EXCLUSION, (new IPath[] {new Path("*/*/**")}));
-//
-//
-//
-// list.add(projectSourceRoot);
-// return list;
-// }
-//
-
- public static LibrarySuperType getProjectSuperType(IJavaScriptProject jproj) {
- if(jproj==null) {
- return getDefaultSuperType(jproj);
- }
- JavaProject javaProject = ((JavaProject)jproj);
-
- //String superTypeName =null;
- //String superTypeContainer =null;
- LibrarySuperType projectSuperType = null;
- // try {
- projectSuperType = javaProject.getCommonSuperType();
- //superTypeName = javaProject.getSharedProperty(LibrarySuperType.SUPER_TYPE_NAME);
- //superTypeContainer = javaProject.getSharedProperty(LibrarySuperType.SUPER_TYPE_CONTAINER);
- // } catch (CoreException ex) {
- // TODO Auto-generated catch block
- // ex.printStackTrace();
- //}
-// / IPreferenceStore store= PreferenceConstants.getPreferenceStore();
-// String superTypeContainerPath= store.getString(PreferenceConstants.SUPER_TYPE_CONTAINER);
-// String superTypeName= store.getString(PreferenceConstants.SUPER_TYPE_NAME);
- //if(superTypeName==null || superTypeContainer==null || superTypeName.equals("") ) {
- if(projectSuperType==null) {
- LibrarySuperType defaultSt =getDefaultSuperType(jproj);
- setProjectSuperType(jproj, defaultSt);
- return defaultSt;
- }
- return projectSuperType;
- //return new LibrarySuperType(new Path(superTypeContainer),jproj, superTypeName);
-// IPreferenceStore store= PreferenceConstants.getPreferenceStore();
-// if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
-// String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME);
-// return jproj.getProject().getFullPath().append(outputLocationName);
-// } else {
-// return jproj.getProject().getFullPath();
-// }
- }
-
- public static LibrarySuperType getDefaultSuperType(IJavaScriptProject jproj) {
- IPath JREPath = new Path(JavaRuntime.DEFAULT_SUPER_TYPE_LIBRARY);
- String superTypeName = JavaRuntime.DEFAULT_SUPER_TYPE;
-
- return new LibrarySuperType(JREPath, jproj, superTypeName);
- }
-
- public static void setProjectSuperType(IJavaScriptProject jproj, LibrarySuperType superType) {
- JavaProject javaScriptProject = ((JavaProject)jproj);
- javaScriptProject.setCommonSuperType(superType);
- }
-
-
- private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
-
- // -------- IStringButtonAdapter --------
- public void changeControlPressed(DialogField field) {
- buildPathChangeControlPressed(field);
- }
-
- // ---------- IDialogFieldListener --------
- public void dialogFieldChanged(DialogField field) {
- buildPathDialogFieldChanged(field);
- }
-
- // ---------- IListAdapter --------
- public void customButtonPressed(ListDialogField field, int index) {
- buildPathCustomButtonPressed(field, index);
- }
-
- public void doubleClicked(ListDialogField field) {
- }
-
- public void selectionChanged(ListDialogField field) {
- List selected = field.getSelectedElements();
- if(selected==null) {
- enableButtons();
- return;
- }
-
- if(selected.size()!=1 ) {
- disableButtons();
- return;
- }
-
- Object selection = selected.get(0);
- int selctedIndext = field.getIndexOfElement(selection);
-
- if(selctedIndext == 0) {
- disableButtons();
- return;
- }else {
- enableButtons();
- }
-
-
- updateTopButtonEnablement();
- }
- }
-
- public void disableButtons() {
- fClassPathList.enableButton(IDX_BOTTOM, false);
- fClassPathList.enableButton(IDX_TOP, false);
- fClassPathList.enableButton(IDX_UP, false);
- fClassPathList.enableButton(IDX_DOWN, false);
-
- }
-
- public void enableButtons() {
- fClassPathList.enableButton(IDX_BOTTOM, fClassPathList.canMoveDown());
- fClassPathList.enableButton(IDX_TOP, fClassPathList.canMoveUp());
- fClassPathList.enableButton(IDX_UP, true);
- fClassPathList.enableButton(IDX_DOWN, true);
-
- }
-
- private void buildPathChangeControlPressed(DialogField field) {
-// if (field == fBuildPathDialogField) {
-// IContainer container= chooseContainer();
-// if (container != null) {
-// fBuildPathDialogField.setText(container.getFullPath().toString());
-// }
-// }
- }
-
- public void updateTopButtonEnablement() {
- fClassPathList.enableButton(IDX_BOTTOM, fClassPathList.canMoveDown());
- fClassPathList.enableButton(IDX_TOP, fClassPathList.canMoveUp());
-
- }
-
- public void buildPathCustomButtonPressed(ListDialogField field, int index) {
- List elems= field.getSelectedElements();
- field.removeElements(elems);
- if (index == IDX_BOTTOM) {
- field.addElements(elems);
- } else if (index == IDX_TOP) {
- field.addElements(elems, 0);
- }
- }
-
- private void buildPathDialogFieldChanged(DialogField field) {
- if (field == fClassPathList) {
- updateClassPathStatus();
- updateTopButtonEnablement();
- }
-// else if (field == fBuildPathDialogField) {
-// updateOutputLocationStatus();
-// }
- doStatusLineUpdate();
- }
-
-
-
- // -------- verification -------------------------------
-
- private void doStatusLineUpdate() {
- if (Display.getCurrent() != null) {
- IStatus res= findMostSevereStatus();
- fContext.statusChanged(res);
- }
- }
-
- private IStatus findMostSevereStatus() {
- return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fBuildPathStatus });
- }
-
-
- /**
- * Validates the build path.
- */
- public void updateClassPathStatus() {
- fClassPathStatus.setOK();
-
- List elements= fClassPathList.getElements();
-
- CPListElement entryMissing= null;
- CPListElement entryDeprecated= null;
- int nEntriesMissing= 0;
- IIncludePathEntry[] entries= new IIncludePathEntry[elements.size()];
-
- for (int i= elements.size()-1 ; i >= 0 ; i--) {
- CPListElement currElement= (CPListElement)elements.get(i);
- boolean isChecked= fClassPathList.isChecked(currElement);
- if (currElement.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (!isChecked) {
- fClassPathList.setCheckedWithoutUpdate(currElement, true);
- }
- if (!fClassPathList.isGrayed(currElement)) {
- fClassPathList.setGrayedWithoutUpdate(currElement, true);
- }
- } else {
- currElement.setExported(isChecked);
- }
-
- entries[i]= currElement.getClasspathEntry();
- if (currElement.isMissing()) {
- nEntriesMissing++;
- if (entryMissing == null) {
- entryMissing= currElement;
- }
- }
- if (entryDeprecated == null & currElement.isDeprecated()) {
- entryDeprecated= currElement;
- }
- }
-
- if (nEntriesMissing > 0) {
- if (nEntriesMissing == 1) {
- fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntryMissing, entryMissing.getPath().toString()));
- } else {
- fClassPathStatus.setWarning(Messages.format(NewWizardMessages.BuildPathsBlock_warning_EntriesMissing, String.valueOf(nEntriesMissing)));
- }
- } else if (entryDeprecated != null) {
- fClassPathStatus.setInfo(entryDeprecated.getDeprecationMessage());
- }
-
-/* if (fCurrJProject.hasClasspathCycle(entries)) {
- fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
- }
-*/
- updateBuildPathStatus();
- }
-
- private void updateBuildPathStatus() {
- List elements= fClassPathList.getElements();
- IIncludePathEntry[] entries= new IIncludePathEntry[elements.size()];
-
- for (int i= elements.size()-1 ; i >= 0 ; i--) {
- CPListElement currElement= (CPListElement)elements.get(i);
- entries[i]= currElement.getClasspathEntry();
- }
-
- //IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(fCurrJProject, entries);
-// if (!status.isOK()) {
-// fBuildPathStatus.setError(status.getMessage());
-// return;
-// }
- fBuildPathStatus.setOK();
- }
-
- // -------- creation -------------------------------
-
- public static void createProject(IProject project, URI locationURI, IProgressMonitor monitor) throws CoreException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.beginTask(NewWizardMessages.BuildPathsBlock_operationdesc_project, 10);
-
- // create the project
- try {
- if (!project.exists()) {
- IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName());
- if (locationURI != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(locationURI)) {
- locationURI= null;
- }
- desc.setLocationURI(locationURI);
- project.create(desc, monitor);
- monitor= null;
- }
- if (!project.isOpen()) {
- project.open(monitor);
- monitor= null;
- }
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
- public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (!project.hasNature(JavaScriptCore.NATURE_ID)) {
- 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]= JavaScriptCore.NATURE_ID;
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- } else {
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- }
-
-
- public void configureJavaProject(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- aboutToDispose();
- flush(fClassPathList.getElements(), getJavaProject(), getSuperType(), monitor);
- initializeTimeStamps();
-
- updateUI();
- }
-
- public LibrarySuperType getSuperType() {
-
- Object o = ordpage.getSuperField().getValue();
-
- return (LibrarySuperType)o;
- }
-
- /*
- * Creates the Java project and sets the configured build path.
- * If the project already exists only build paths are updated.
- */
- public static void flush(List classPathEntries, IJavaScriptProject javaScriptProject, LibrarySuperType superType, IProgressMonitor monitor) throws CoreException, OperationCanceledException {
- if(superType==null) {
- System.out.println("---------------------------------- NULL SUPER TYPE -------------------------"); //$NON-NLS-1$
- }
- if (superType != null) {
- setProjectSuperType(javaScriptProject, superType);
- }
-
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.setTaskName(NewWizardMessages.BuildPathsBlock_operationdesc_java);
- monitor.beginTask("", classPathEntries.size() * 4 + 4); //$NON-NLS-1$
-
- try {
- IProject project= javaScriptProject.getProject();
- IPath projPath= project.getFullPath();
-
- monitor.worked(1);
-
- //IWorkspaceRoot fWorkspaceRoot= JavaScriptPlugin.getWorkspace().getRoot();
-
- monitor.worked(1);
-
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- IIncludePathEntry[] classpath= new IIncludePathEntry[classPathEntries.size()];
-
- int i= 0;
- for (Iterator iter= classPathEntries.iterator(); iter.hasNext();) {
- CPListElement entry= (CPListElement)iter.next();
- classpath[i]= entry.getClasspathEntry();
- i++;
-
- IResource res= entry.getResource();
- //1 tick
- if (res instanceof IFolder && entry.getLinkTarget() == null && !res.exists()) {
- CoreUtility.createFolder((IFolder)res, true, true, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
-
- //3 ticks
- if (entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- monitor.worked(1);
-
- IPath path= entry.getPath();
- if (projPath.equals(path)) {
- monitor.worked(2);
- continue;
- }
-
- if (projPath.isPrefixOf(path)) {
- path= path.removeFirstSegments(projPath.segmentCount());
- }
- IFolder folder= project.getFolder(path);
- IPath orginalPath= entry.getOrginalPath();
- if (orginalPath == null) {
- if (!folder.exists()) {
- //New source folder needs to be created
- if (entry.getLinkTarget() == null) {
- CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 2));
- } else {
- folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 2));
- }
- }
- } else {
- if (projPath.isPrefixOf(orginalPath)) {
- orginalPath= orginalPath.removeFirstSegments(projPath.segmentCount());
- }
- IFolder orginalFolder= project.getFolder(orginalPath);
- if (entry.getLinkTarget() == null) {
- if (!folder.exists()) {
- //Source folder was edited, move to new location
- IPath parentPath= entry.getPath().removeLastSegments(1);
- if (projPath.isPrefixOf(parentPath)) {
- parentPath= parentPath.removeFirstSegments(projPath.segmentCount());
- }
- if (parentPath.segmentCount() > 0) {
- IFolder parentFolder= project.getFolder(parentPath);
- if (!parentFolder.exists()) {
- CoreUtility.createFolder(parentFolder, true, true, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
- } else {
- monitor.worked(1);
- }
- orginalFolder.move(entry.getPath(), true, true, new SubProgressMonitor(monitor, 1));
- }
- } else {
- if (!folder.exists() || !entry.getLinkTarget().equals(entry.getOrginalLinkTarget())) {
- orginalFolder.delete(true, new SubProgressMonitor(monitor, 1));
- folder.createLink(entry.getLinkTarget(), IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 1));
- }
- }
- }
- } else {
- monitor.worked(3);
- }
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- }
-
- javaScriptProject.setRawIncludepath(classpath, new SubProgressMonitor(monitor, 2));
- } finally {
- monitor.done();
- }
- }
-
- // -------- tab switching ----------
-
- private void tabChanged(Widget widget) {
- if (widget instanceof TabItem) {
- TabItem tabItem= (TabItem) widget;
- BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
- if (fCurrPage != null) {
- List selection= fCurrPage.getSelection();
- if (!selection.isEmpty()) {
- newPage.setSelection(selection, false);
- }
- fCurrPage.aboutToDispose();
- newPage.aboutToShow();
- }
-
- fCurrPage= newPage;
- fPageIndex= tabItem.getParent().getSelectionIndex();
- }
- }
-
- private int getPageIndex(int entryKind) {
- switch (entryKind) {
- case IIncludePathEntry.CPE_CONTAINER:
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_VARIABLE:
- return 2;
- case IIncludePathEntry.CPE_PROJECT:
- return 1;
- case IIncludePathEntry.CPE_SOURCE:
- return 0;
- }
- return 0;
- }
-
- private CPListElement findElement(IIncludePathEntry entry) {
- for (int i= 0, len= fClassPathList.getSize(); i < len; i++) {
- CPListElement curr= (CPListElement) fClassPathList.getElement(i);
- if (curr.getEntryKind() == entry.getEntryKind() && curr.getPath().equals(entry.getPath())) {
- return curr;
- }
- }
- return null;
- }
-
- public void setElementToReveal(IIncludePathEntry entry, String attributeKey) {
- int pageIndex= getPageIndex(entry.getEntryKind());
- if (fTabFolder == null) {
- fPageIndex= pageIndex;
- } else {
- fTabFolder.setSelection(pageIndex);
- CPListElement element= findElement(entry);
- if (element != null) {
- Object elementToSelect= element;
-
- if (attributeKey != null) {
- Object attrib= element.findAttributeElement(attributeKey);
- if (attrib != null) {
- elementToSelect= attrib;
- }
- }
- BuildPathBasePage page= (BuildPathBasePage) fTabFolder.getItem(pageIndex).getData();
- List selection= new ArrayList(1);
- selection.add(elementToSelect);
- page.setSelection(selection, true);
- }
- }
- }
-
- public void showPage(int pageIndex) {
- if (fTabFolder == null) {
- fPageIndex= pageIndex;
- } else {
- fTabFolder.setSelection(pageIndex);
- fCurrPage= (BuildPathBasePage)fTabFolder.getItem(pageIndex).getData();
- fCurrPage.aboutToShow();
- //BuildPathBasePage page= (BuildPathBasePage) fTabFolder.getItem(pageIndex).getData();
- }
- updateUI();
- }
-
-
- public void addElement(IIncludePathEntry entry) {
- int pageIndex= getPageIndex(entry.getEntryKind());
- if (fTabFolder == null) {
- fPageIndex= pageIndex;
- } else {
- fTabFolder.setSelection(pageIndex);
-
- Object page= fTabFolder.getItem(pageIndex).getData();
- if (page instanceof LibrariesWorkbookPage) {
- CPListElement element= CPListElement.createFromExisting(entry, fCurrJSProject);
- ((LibrariesWorkbookPage) page).addElement(element);
- }
- }
- }
-
- public void dispose() {
- if (fSourceContainerPage instanceof NewSourceContainerWorkbookPage) {
- ((NewSourceContainerWorkbookPage)fSourceContainerPage).dispose();
- fSourceContainerPage= null;
- }
- }
-
- public boolean isOKStatus() {
- return findMostSevereStatus().isOK();
- }
-
- public void setFocus() {
- fSourceContainerPage.setFocus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java
deleted file mode 100644
index 9d2a2988..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java
+++ /dev/null
@@ -1,828 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class CPListElement {
-
- public static final String EXCLUSION= "exclusion"; //$NON-NLS-1$
- public static final String INCLUSION= "inclusion"; //$NON-NLS-1$
-
- public static final String ACCESSRULES= "accessrules"; //$NON-NLS-1$
- public static final String COMBINE_ACCESSRULES= "combineaccessrules"; //$NON-NLS-1$
-
- public static final String JAVADOC= IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME;
-
- private IJavaScriptProject fProject;
-
- private int fEntryKind;
- private IPath fPath, fOrginalPath;
- private IResource fResource;
- private boolean fIsExported;
- private boolean fIsMissing;
-
- private Object fParentContainer;
-
- private IIncludePathEntry fCachedEntry;
- private ArrayList fChildren;
- private IPath fLinkTarget, fOrginalLinkTarget;
-
- private CPListElement() {}
-
- public CPListElement(IJavaScriptProject project, int entryKind, IPath path, IResource res) {
- this(null, project, entryKind, path, res);
- }
-
- public CPListElement(Object parent, IJavaScriptProject project, int entryKind, IPath path, IResource res) {
- this(parent, project, entryKind, path, res, null);
- }
-
- public CPListElement(IJavaScriptProject project, int entryKind) {
- this(null, project, entryKind, null, null);
- }
-
- public CPListElement(Object parent, IJavaScriptProject project, int entryKind, IPath path, IResource res, IPath linkTarget) {
- fProject= project;
-
- fEntryKind= entryKind;
- fPath= path;
- fOrginalPath= path;
- fLinkTarget= linkTarget;
- fOrginalLinkTarget= linkTarget;
- fChildren= new ArrayList();
- fResource= res;
- fIsExported= false;
-
- fIsMissing= false;
- fCachedEntry= null;
- fParentContainer= parent;
-
- JsGlobalScopeContainerInitializer init = getContainerInitializer();
-
- boolean allowJsDoc = true;
-
- if(init!=null) {
- allowJsDoc = init.allowAttachJsDoc();
- }
-
- switch (entryKind) {
- case IIncludePathEntry.CPE_SOURCE:
- createAttributeElement(INCLUSION, new Path[0], true);
- createAttributeElement(EXCLUSION, new Path[0], true);
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_VARIABLE:
- if(allowJsDoc) createAttributeElement(JAVADOC, null, false);
- createAttributeElement(ACCESSRULES, new IAccessRule[0], true);
- break;
- case IIncludePathEntry.CPE_PROJECT:
- createAttributeElement(ACCESSRULES, new IAccessRule[0], true);
- createAttributeElement(COMBINE_ACCESSRULES, Boolean.FALSE, true); // not rendered
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- createAttributeElement(ACCESSRULES, new IAccessRule[0], true);
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(fPath, fProject);
- if (container != null) {
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- if (entries != null) { // invalid container implementation
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry entry= entries[i];
- if (entry != null) {
- if(init!=null) {
- String displayText = init.getDescription(entry.getPath(), project);
- if(displayText==null) continue;
- }
-
- CPListElement curr= createFromExisting(this, entry, fProject);
- fChildren.add(curr);
- } else {
- JavaScriptPlugin.logErrorMessage("Null entry in container '" + fPath + "'"); //$NON-NLS-1$//$NON-NLS-2$
- }
- }
- } else {
- JavaScriptPlugin.logErrorMessage("container returns null as entries: '" + fPath + "'"); //$NON-NLS-1$//$NON-NLS-2$
- }
- }
- } catch (JavaScriptModelException e) {
- }
- break;
- default:
- }
-
- }
-
- public IIncludePathEntry getClasspathEntry() {
- if (fCachedEntry == null) {
- fCachedEntry= newClasspathEntry();
- }
- return fCachedEntry;
- }
-
-
- private IIncludePathAttribute[] getClasspathAttributes() {
- ArrayList res= new ArrayList();
- for (int i= 0; i < fChildren.size(); i++) {
- Object curr= fChildren.get(i);
- if (curr instanceof CPListElementAttribute) {
- CPListElementAttribute elem= (CPListElementAttribute) curr;
- if (!elem.isBuiltIn() && elem.getValue() != null) {
- res.add(elem.getClasspathAttribute());
- }
- }
- }
- return (IIncludePathAttribute[]) res.toArray(new IIncludePathAttribute[res.size()]);
- }
-
-
- private IIncludePathEntry newClasspathEntry() {
-
- IIncludePathAttribute[] extraAttributes= getClasspathAttributes();
- switch (fEntryKind) {
- case IIncludePathEntry.CPE_SOURCE:
- IPath[] inclusionPattern= (IPath[]) getAttribute(INCLUSION);
- IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION);
- return JavaScriptCore.newSourceEntry(fPath, inclusionPattern, exclusionPattern, null, extraAttributes);
- case IIncludePathEntry.CPE_LIBRARY: {
- IAccessRule[] accesRules= (IAccessRule[]) getAttribute(ACCESSRULES);
- return JavaScriptCore.newLibraryEntry(fPath, null, null, accesRules, extraAttributes, isExported());
- }
- case IIncludePathEntry.CPE_PROJECT: {
- IAccessRule[] accesRules= (IAccessRule[]) getAttribute(ACCESSRULES);
- boolean combineAccessRules= ((Boolean) getAttribute(COMBINE_ACCESSRULES)).booleanValue();
- return JavaScriptCore.newProjectEntry(fPath, accesRules, combineAccessRules, extraAttributes, isExported());
- }
- case IIncludePathEntry.CPE_CONTAINER: {
- IAccessRule[] accesRules= (IAccessRule[]) getAttribute(ACCESSRULES);
- return JavaScriptCore.newContainerEntry(fPath, accesRules, extraAttributes, isExported());
- }
- case IIncludePathEntry.CPE_VARIABLE: {
- IAccessRule[] accesRules= (IAccessRule[]) getAttribute(ACCESSRULES);
- return JavaScriptCore.newVariableEntry(fPath, null, null, accesRules, extraAttributes, isExported());
- }
- default:
- return null;
- }
- }
-
- /**
- * Gets the class path entry path.
- * @return returns the path
- * @see IIncludePathEntry#getPath()
- */
- public IPath getPath() {
- return fPath;
- }
-
- /**
- * Gets the class path entry kind.
- * @return the entry kind
- * @see IIncludePathEntry#getEntryKind()
- */
- public int getEntryKind() {
- return fEntryKind;
- }
-
- /**
- * Entries without resource are either non existing or a variable entry
- * External jars do not have a resource
- * @return returns the resource
- */
- public IResource getResource() {
- return fResource;
- }
-
- public CPListElementAttribute setAttribute(String key, Object value) {
- CPListElementAttribute attribute= findAttributeElement(key);
- if (attribute == null) {
- return null;
- //createAttributeElement(key, value, false);
- }
- if (key.equals(EXCLUSION) || key.equals(INCLUSION)) {
- Assert.isTrue(value != null || fEntryKind != IIncludePathEntry.CPE_SOURCE);
- }
-
- if (key.equals(ACCESSRULES)) {
- Assert.isTrue(value != null || fEntryKind == IIncludePathEntry.CPE_SOURCE);
- }
- if (key.equals(COMBINE_ACCESSRULES)) {
- Assert.isTrue(value instanceof Boolean);
- }
-
- attribute.setValue(value);
- return attribute;
- }
-
- public boolean addToExclusions(IPath path) {
- String key= CPListElement.EXCLUSION;
- return addFilter(path, key);
- }
-
- public boolean addToInclusion(IPath path) {
- String key= CPListElement.INCLUSION;
- return addFilter(path, key);
- }
-
- public boolean removeFromExclusions(IPath path) {
- String key= CPListElement.EXCLUSION;
- return removeFilter(path, key);
- }
-
- public boolean removeFromInclusion(IPath path) {
- String key= CPListElement.INCLUSION;
- return removeFilter(path, key);
- }
-
- private boolean addFilter(IPath path, String key) {
- IPath[] filters= (IPath[]) getAttribute(key);
- if (filters == null)
- return false;
-
- if (!JavaModelUtil.isExcludedPath(path, filters)) {
- IPath toAdd= path.removeFirstSegments(getPath().segmentCount()).addTrailingSeparator();
- IPath[] newFilters= new IPath[filters.length + 1];
- System.arraycopy(filters, 0, newFilters, 0, filters.length);
- newFilters[filters.length]= toAdd;
- setAttribute(key, newFilters);
- return true;
- }
- return false;
- }
-
- private boolean removeFilter(IPath path, String key) {
- IPath[] filters= (IPath[]) getAttribute(key);
- if (filters == null)
- return false;
-
- IPath toRemove= path.removeFirstSegments(getPath().segmentCount()).addTrailingSeparator();
- if (JavaModelUtil.isExcludedPath(toRemove, filters)) {
- List l= new ArrayList(Arrays.asList(filters));
- l.remove(toRemove);
- IPath[] newFilters= (IPath[])l.toArray(new IPath[l.size()]);
- setAttribute(key, newFilters);
- return true;
- }
- return false;
- }
-
- public CPListElementAttribute findAttributeElement(String key) {
- for (int i= 0; i < fChildren.size(); i++) {
- Object curr= fChildren.get(i);
- if (curr instanceof CPListElementAttribute) {
- CPListElementAttribute elem= (CPListElementAttribute) curr;
- if (key.equals(elem.getKey())) {
- return elem;
- }
- }
- }
- return null;
- }
-
-
- public Object getAttribute(String key) {
- CPListElementAttribute attrib= findAttributeElement(key);
- if (attrib != null) {
- return attrib.getValue();
- }
- return null;
- }
-
- public CPListElementAttribute[] getAllAttributes() {
- ArrayList res= new ArrayList();
- for (int i= 0; i < fChildren.size(); i++) {
- Object curr= fChildren.get(i);
- if (curr instanceof CPListElementAttribute) {
- res.add(curr);
- }
- }
- return (CPListElementAttribute[]) res.toArray(new CPListElementAttribute[res.size()]);
- }
-
-
- private void createAttributeElement(String key, Object value, boolean builtIn) {
- fChildren.add(new CPListElementAttribute(this, key, value, builtIn));
- }
-
- private static boolean isFiltered(Object entry, String[] filteredKeys) {
- if (entry instanceof CPListElementAttribute) {
- CPListElementAttribute curr= (CPListElementAttribute) entry;
- String key= curr.getKey();
- for (int i= 0; i < filteredKeys.length; i++) {
- if (key.equals(filteredKeys[i])) {
- return true;
- }
- }
- if (curr.isNotSupported()) {
- return true;
- }
- if (!curr.isBuiltIn() && !key.equals(CPListElement.JAVADOC)) {
- return !JavaScriptPlugin.getDefault().getClasspathAttributeConfigurationDescriptors().containsKey(key);
- }
- }
- return false;
- }
-
- private Object[] getFilteredChildren(String[] filteredKeys) {
- int nChildren= fChildren.size();
- ArrayList res= new ArrayList(nChildren);
-
- for (int i= 0; i < nChildren; i++) {
- Object curr= fChildren.get(i);
- if (!isFiltered(curr, filteredKeys)) {
- res.add(curr);
- }
- }
- return res.toArray();
- }
-
- public Object[] getChildren() {
- if (fEntryKind == IIncludePathEntry.CPE_PROJECT) {
- return getFilteredChildren(new String[] { COMBINE_ACCESSRULES });
- }
- return getFilteredChildren(new String[0]);
- }
-
- public Object getParentContainer() {
- return fParentContainer;
- }
-
- protected void attributeChanged(String key) {
- fCachedEntry= null;
- }
- /* return JsGlobalScopeContainerInitializer (if it exists)
- *
- */
- public JsGlobalScopeContainerInitializer getContainerInitializer() {
- if (fEntryKind == IIncludePathEntry.CPE_CONTAINER && fProject != null) {
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(fPath.segment(0));
- return initializer ;
- }else if(fParentContainer !=null && fParentContainer instanceof CPListElement) {
- return ((CPListElement)fParentContainer).getContainerInitializer();
- }
- return null;
- }
-
-
- private IStatus evaluateContainerChildStatus(CPListElementAttribute attrib) {
- if (fProject != null) {
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(fPath.segment(0));
- if (initializer != null && initializer.canUpdateJsGlobalScopeContainer(fPath, fProject)) {
- if (attrib.isBuiltIn()) {
- if (CPListElement.ACCESSRULES.equals(attrib.getKey())) {
- return initializer.getAccessRulesStatus(fPath, fProject);
- }
- } else {
- return initializer.getAttributeStatus(fPath, fProject, attrib.getKey());
- }
- }
- return new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, JsGlobalScopeContainerInitializer.ATTRIBUTE_READ_ONLY, "", null); //$NON-NLS-1$
- }
- return null;
- }
-
- private boolean canUpdateContainer() {
- if (fEntryKind == IIncludePathEntry.CPE_CONTAINER && fProject != null) {
- //JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(fPath.segment(0));
- JsGlobalScopeContainerInitializer initializer=getContainerInitializer();
- return (initializer != null && initializer.canUpdateJsGlobalScopeContainer(fPath, fProject));
- }
- return false;
- }
-
- public boolean isInNonModifiableContainer() {
- if (fParentContainer!=null && fParentContainer instanceof CPListElement) {
- return !((CPListElement) fParentContainer).canUpdateContainer();
- }
- return fParentContainer==null && !canUpdateContainer();
- }
-
- public IStatus getContainerChildStatus(CPListElementAttribute attrib) {
- if (fParentContainer instanceof CPListElement) {
- CPListElement parent= (CPListElement) fParentContainer;
- if (parent.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- return parent.evaluateContainerChildStatus(attrib);
- }
- return ((CPListElement) fParentContainer).getContainerChildStatus(attrib);
- }
- return null;
- }
-
- public boolean isJRE() {
- IPath containerPath = getPath();
- IPath JREPath = new Path(JavaRuntime.JRE_CONTAINER);
-
- return (containerPath!=null && containerPath.equals(JREPath));
- }
-
- public boolean isInContainer(String containerName) {
- if (fParentContainer instanceof CPListElement) {
- CPListElement elem= (CPListElement) fParentContainer;
- return new Path(containerName).isPrefixOf(elem.getPath());
- }
- return false;
- }
-
- public boolean isDeprecated() {
- if (fEntryKind != IIncludePathEntry.CPE_VARIABLE) {
- return false;
- }
- if (fPath.segmentCount() > 0) {
- return JavaScriptCore.getIncludepathVariableDeprecationMessage(fPath.segment(0)) != null;
- }
- return false;
- }
-
- public String getDeprecationMessage() {
- if (fEntryKind != IIncludePathEntry.CPE_VARIABLE) {
- return null;
- }
- if (fPath.segmentCount() > 0) {
- String varName= fPath.segment(0);
- return BuildPathSupport.getDeprecationMessage(varName);
- }
- return null;
- }
-
- /*
- * @see Object#equals(java.lang.Object)
- */
- public boolean equals(Object other) {
- if (other != null && other.getClass().equals(getClass())) {
- CPListElement elem= (CPListElement) other;
- return getClasspathEntry().equals(elem.getClasspathEntry());
- }
- return false;
- }
-
- /*
- * @see Object#hashCode()
- */
- public int hashCode() {
- return fPath.hashCode() + fEntryKind;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return getClasspathEntry().toString();
- }
-
- /**
- * Returns if a entry is missing.
- * @return Returns a boolean
- */
- public boolean isMissing() {
- return fIsMissing;
- }
-
- /**
- * Sets the 'missing' state of the entry.
- * @param isMissing the new state
- */
- public void setIsMissing(boolean isMissing) {
- fIsMissing= isMissing;
- }
-
- /**
- * Returns if a entry is exported (only applies to libraries)
- * @return Returns a boolean
- */
- public boolean isExported() {
- return fIsExported;
- }
-
- /**
- * Sets the export state of the entry.
- * @param isExported the new state
- */
- public void setExported(boolean isExported) {
- if (isExported != fIsExported) {
- fIsExported = isExported;
-
- attributeChanged(null);
- }
- }
-
- /**
- * Gets the project.
- * @return Returns a IJavaScriptProject
- */
- public IJavaScriptProject getJavaProject() {
- return fProject;
- }
-
- public static CPListElement createFromExisting(IIncludePathEntry curr, IJavaScriptProject project) {
- return createFromExisting(null, curr, project);
- }
-
- public static CPListElement createFromExisting(Object parent, IIncludePathEntry curr, IJavaScriptProject project) {
- IPath path= curr.getPath();
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
-
- // get the resource
- IResource res= null;
- boolean isMissing= false;
- IPath linkTarget= null;
-
- switch (curr.getEntryKind()) {
- case IIncludePathEntry.CPE_CONTAINER:
- try {
- isMissing= project != null && (JavaScriptCore.getJsGlobalScopeContainer(path, project) == null);
- } catch (JavaScriptModelException e) {
- isMissing= true;
- }
- break;
- case IIncludePathEntry.CPE_VARIABLE:
- IPath resolvedPath= JavaScriptCore.getResolvedVariablePath(path);
- isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile();
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- res= root.findMember(path);
- if (res == null) {
- if (!ArchiveFileFilter.isArchivePath(path)) {
- if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()
- && root.getProject(path.segment(0)).exists()) {
- res= root.getFolder(path);
- }
- }
- isMissing= !path.toFile().isFile(); // look for external JARs
- } else if (res.isLinked()) {
- linkTarget= res.getLocation();
- }
- break;
- case IIncludePathEntry.CPE_SOURCE:
- path= path.removeTrailingSeparator();
- res= root.findMember(path);
- if (res == null) {
- if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
- res= root.getFolder(path);
- }
- isMissing= true;
- } else if (res.isLinked()) {
- linkTarget= res.getLocation();
- }
- break;
- case IIncludePathEntry.CPE_PROJECT:
- res= root.findMember(path);
- isMissing= (res == null);
- break;
- }
- CPListElement elem= new CPListElement(parent, project, curr.getEntryKind(), path, res, linkTarget);
- elem.setExported(curr.isExported());
- elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
- elem.setAttribute(INCLUSION, curr.getInclusionPatterns());
- elem.setAttribute(ACCESSRULES, curr.getAccessRules());
- elem.setAttribute(COMBINE_ACCESSRULES, new Boolean(curr.combineAccessRules()));
-
- IIncludePathAttribute[] extraAttributes= curr.getExtraAttributes();
- for (int i= 0; i < extraAttributes.length; i++) {
- IIncludePathAttribute attrib= extraAttributes[i];
- CPListElementAttribute attribElem= elem.findAttributeElement(attrib.getName());
- if (attribElem == null) {
- elem.createAttributeElement(attrib.getName(), attrib.getValue(), false);
- } else {
- attribElem.setValue(attrib.getValue());
- }
- }
-
- if (project != null && project.exists()) {
- elem.setIsMissing(isMissing);
- }
- return elem;
- }
-
- public static StringBuffer appendEncodePath(IPath path, StringBuffer buf) {
- if (path != null) {
- String str= path.toString();
- buf.append('[').append(str.length()).append(']').append(str);
- } else {
- buf.append('[').append(']');
- }
- return buf;
- }
-
- public static StringBuffer appendEncodedString(String str, StringBuffer buf) {
- if (str != null) {
- buf.append('[').append(str.length()).append(']').append(str);
- } else {
- buf.append('[').append(']');
- }
- return buf;
- }
-
- public static StringBuffer appendEncodedFilter(IPath[] filters, StringBuffer buf) {
- if (filters != null) {
- buf.append('[').append(filters.length).append(']');
- for (int i= 0; i < filters.length; i++) {
- appendEncodePath(filters[i], buf).append(';');
- }
- } else {
- buf.append('[').append(']');
- }
- return buf;
- }
-
- public static StringBuffer appendEncodedAccessRules(IAccessRule[] rules, StringBuffer buf) {
- if (rules != null) {
- buf.append('[').append(rules.length).append(']');
- for (int i= 0; i < rules.length; i++) {
- appendEncodePath(rules[i].getPattern(), buf).append(';');
- buf.append(rules[i].getKind()).append(';');
- }
- } else {
- buf.append('[').append(']');
- }
- return buf;
- }
-
-
- public StringBuffer appendEncodedSettings(StringBuffer buf) {
- buf.append(fEntryKind).append(';');
- if (getLinkTarget() == null) {
- appendEncodePath(fPath, buf).append(';');
- } else {
- appendEncodePath(fPath, buf).append('-').append('>');
- appendEncodePath(getLinkTarget(), buf).append(';');
- }
- buf.append(Boolean.valueOf(fIsExported)).append(';');
- for (int i= 0; i < fChildren.size(); i++) {
- Object curr= fChildren.get(i);
- if (curr instanceof CPListElementAttribute) {
- CPListElementAttribute elem= (CPListElementAttribute) curr;
- if (elem.isBuiltIn()) {
- String key= elem.getKey();
- if (EXCLUSION.equals(key) || INCLUSION.equals(key)) {
- appendEncodedFilter((IPath[]) elem.getValue(), buf).append(';');
- } else if (ACCESSRULES.equals(key)) {
- appendEncodedAccessRules((IAccessRule[]) elem.getValue(), buf).append(';');
- } else if (COMBINE_ACCESSRULES.equals(key)) {
- buf.append(((Boolean) elem.getValue()).booleanValue()).append(';');
- }
- } else {
- appendEncodedString((String) elem.getValue(), buf);
- }
- }
- }
- return buf;
- }
-
- public IPath getLinkTarget() {
- return fLinkTarget;
- }
-
- public void setPath(IPath path) {
- fCachedEntry= null;
- fPath= path;
- }
-
- public void setLinkTarget(IPath linkTarget) {
- fCachedEntry= null;
- fLinkTarget= linkTarget;
- }
-
- public static void insert(CPListElement element, List cpList) {
- int length= cpList.size();
- CPListElement[] elements= (CPListElement[])cpList.toArray(new CPListElement[length]);
- int i= 0;
- while (i < length && elements[i].getEntryKind() != element.getEntryKind()) {
- i++;
- }
- if (i < length) {
- i++;
- while (i < length && elements[i].getEntryKind() == element.getEntryKind()) {
- i++;
- }
- cpList.add(i, element);
- return;
- }
-
- switch (element.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- cpList.add(0, element);
- break;
- case IIncludePathEntry.CPE_CONTAINER:
- case IIncludePathEntry.CPE_LIBRARY:
- case IIncludePathEntry.CPE_PROJECT:
- case IIncludePathEntry.CPE_VARIABLE:
- default:
- cpList.add(element);
- break;
- }
- }
-
- public static IIncludePathEntry[] convertToClasspathEntries(List/*<CPListElement>*/ cpList) {
- IIncludePathEntry[] result= new IIncludePathEntry[cpList.size()];
- int i= 0;
- for (Iterator iter= cpList.iterator(); iter.hasNext();) {
- CPListElement cur= (CPListElement)iter.next();
- result[i]= cur.getClasspathEntry();
- i++;
- }
- return result;
- }
-
- public static CPListElement[] createFromExisting(IJavaScriptProject project) throws JavaScriptModelException {
- IIncludePathEntry[] rawClasspath= project.getRawIncludepath();
- CPListElement[] result= new CPListElement[rawClasspath.length];
- for (int i= 0; i < rawClasspath.length; i++) {
- result[i]= CPListElement.createFromExisting(rawClasspath[i], project);
- }
- return result;
- }
-
- public static boolean isProjectSourceFolder(CPListElement[] existing, IJavaScriptProject project) {
- IPath projPath= project.getProject().getFullPath();
- for (int i= 0; i < existing.length; i++) {
- IIncludePathEntry curr= existing[i].getClasspathEntry();
- if (curr.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- if (projPath.equals(curr.getPath())) {
- return true;
- }
- }
- }
- return false;
- }
-
- public IPath getOrginalPath() {
- return fOrginalPath;
- }
-
- public IPath getOrginalLinkTarget() {
- return fOrginalLinkTarget;
- }
-
-
- public CPListElement copy() {
- CPListElement result= new CPListElement();
- result.fProject= fProject;
- result.fEntryKind= fEntryKind;
- result.fPath= fPath;
- result.fOrginalPath= fOrginalPath;
- result.fResource= fResource;
- result.fIsExported= fIsExported;
- result.fIsMissing= fIsMissing;
- result.fParentContainer= fParentContainer;
- result.fCachedEntry= null;
- result.fChildren= new ArrayList(fChildren.size());
- for (Iterator iterator= fChildren.iterator(); iterator.hasNext();) {
- Object child= iterator.next();
- if (child instanceof CPListElement) {
- result.fChildren.add(((CPListElement)child).copy());
- } else {
- result.fChildren.add(((CPListElementAttribute)child).copy());
- }
- }
- result.fLinkTarget= fLinkTarget;
- result.fOrginalLinkTarget= fOrginalLinkTarget;
- return result;
- }
-
- public void setAttributesFromExisting(CPListElement existing) {
- Assert.isTrue(existing.getEntryKind() == getEntryKind());
- CPListElementAttribute[] attributes= existing.getAllAttributes();
- for (int i= 0; i < attributes.length; i++) {
- CPListElementAttribute curr= attributes[i];
- CPListElementAttribute elem= findAttributeElement(curr.getKey());
- if (elem == null) {
- createAttributeElement(curr.getKey(), curr.getValue(), false);
- } else {
- elem.setValue(curr.getValue());
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementAttribute.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementAttribute.java
deleted file mode 100644
index 4392e547..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementAttribute.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess;
-
-
-/**
- */
-public class CPListElementAttribute {
-
- private CPListElement fParent;
- private String fKey;
- private Object fValue;
- private final boolean fBuiltIn;
- private IStatus fStatus;
-
- private ClasspathAttributeAccess fCachedAccess;
-
- public CPListElementAttribute(CPListElement parent, String key, Object value, boolean builtIn) {
- fKey= key;
- fValue= value;
- fParent= parent;
- fBuiltIn= builtIn;
- if (!builtIn) {
- Assert.isTrue(value instanceof String || value == null);
- }
- fStatus= getContainerChildStatus();
- }
-
- private CPListElementAttribute(boolean buildIn) {
- fBuiltIn= buildIn;
- }
-
- public IIncludePathAttribute getClasspathAttribute() {
- Assert.isTrue(!fBuiltIn);
- return JavaScriptCore.newIncludepathAttribute(fKey, (String) fValue);
- }
-
- public CPListElement getParent() {
- return fParent;
- }
-
- /**
- * @return Returns <code>true</code> if the attribute is a built in attribute.
- */
- public boolean isBuiltIn() {
- return fBuiltIn;
- }
-
- /**
- * @return Returns <code>true</code> if the attribute a on a container child and is read-only
- */
- public boolean isNonModifiable() {
- return fStatus != null && !fStatus.isOK();
- }
-
- /**
- * @return Returns <code>true</code> if the attribute a on a container child and is not supported
- */
- public boolean isNotSupported() {
- return fStatus != null && fStatus.getCode() == JsGlobalScopeContainerInitializer.ATTRIBUTE_NOT_SUPPORTED;
- }
-
- /**
- * @return Returns the container child status or <code>null</code> if the attribute is not in a container child
- */
- private IStatus getContainerChildStatus() {
- return fParent.getContainerChildStatus(this);
- }
-
-
- /**
- * Returns the key.
- * @return String
- */
- public String getKey() {
- return fKey;
- }
-
- /**
- * Returns the value.
- * @return Object
- */
- public Object getValue() {
- return fValue;
- }
-
- /**
- * Returns the value.
- * @param value value to set
- */
- public void setValue(Object value) {
- fValue= value;
- fCachedAccess= null;
- getParent().attributeChanged(fKey);
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof CPListElementAttribute))
- return false;
- CPListElementAttribute attrib= (CPListElementAttribute)obj;
- return attrib.fKey== this.fKey && attrib.getParent().getPath().equals(fParent.getPath());
- }
-
- public CPListElementAttribute copy() {
- CPListElementAttribute result= new CPListElementAttribute(fBuiltIn);
- result.fParent= fParent;
- result.fKey= fKey;
- result.fValue= fValue;
- result.fStatus= fStatus;
- return result;
- }
-
- public ClasspathAttributeAccess getClasspathAttributeAccess() {
- if (fCachedAccess == null) {
- fCachedAccess= new ClasspathAttributeAccess() {
- public IIncludePathAttribute getClasspathAttribute() {
- return CPListElementAttribute.this.getClasspathAttribute();
- }
- public IJavaScriptProject getJavaProject() {
- return getParent().getJavaProject();
- }
- public IIncludePathEntry getParentClasspassEntry() {
- return getParent().getClasspathEntry();
- }
- };
- }
- return fCachedAccess;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java
deleted file mode 100644
index 5cf735ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.jface.viewers.ContentViewer;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-
-public class CPListElementSorter extends ViewerComparator {
-
- private static final int SOURCE= 0;
- private static final int PROJECT= 1;
- private static final int LIBRARY= 2;
- private static final int CONTAINER= 4;
-
- private static final int ATTRIBUTE= 5;
- private static final int CONTAINER_ENTRY= 6;
- private static final int JRE_ENTRY = -2;
- private static final int REQUIRED_ENTRY = -1;
- private static final int OTHER= 7;
-
- /*
- * @see ViewerSorter#category(Object)
- */
- public int category(Object obj) {
- if (obj instanceof CPListElement) {
- CPListElement element= (CPListElement) obj;
- if (element.getParentContainer() != null) {
- return CONTAINER_ENTRY;
- }
-
- if(element.isJRE()) {
- return JRE_ENTRY;
- }
-
- if(element.isInNonModifiableContainer()) {
- return REQUIRED_ENTRY;
- }
-
- switch (element.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY:
- return LIBRARY;
- case IIncludePathEntry.CPE_PROJECT:
- return PROJECT;
- case IIncludePathEntry.CPE_SOURCE:
- return SOURCE;
- case IIncludePathEntry.CPE_CONTAINER:
- return CONTAINER;
- }
- } else if (obj instanceof CPListElementAttribute) {
- return ATTRIBUTE;
- } else if (obj instanceof IAccessRule) {
- return ATTRIBUTE;
- }
- return OTHER;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerSorter#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public int compare(Viewer viewer, Object e1, Object e2) {
-
- int cat1 = category(e1);
- int cat2 = category(e2);
-
- if (cat1 != cat2)
- return cat1 - cat2;
-
- if (cat1 == ATTRIBUTE || cat1 == CONTAINER_ENTRY) {
- return 0; // do not sort attributes or container entries
- }
-
- if (viewer instanceof ContentViewer) {
- IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
- if (prov instanceof ILabelProvider) {
- ILabelProvider lprov = (ILabelProvider) prov;
- String name1 = lprov.getText(e1);
- String name2 = lprov.getText(e2);
- return getComparator().compare(name1, name2);
- }
- }
- return 0;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java
deleted file mode 100644
index cf992afb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java
+++ /dev/null
@@ -1,360 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJsGlobalScopeContainerInitializerExtension;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.util.JSDScopeUiUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.ui.ISharedImages;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess;
-
-public class CPListLabelProvider extends LabelProvider {
-
- private String fNewLabel, fClassLabel, fCreateLabel;
-
- private ImageDescriptorRegistry fRegistry;
- private ISharedImages fSharedImages;
-
- private ImageDescriptor fProjectImage;
-
- private ClasspathAttributeConfigurationDescriptors fAttributeDescriptors;
-
-
- public CPListLabelProvider() {
- fNewLabel= NewWizardMessages.CPListLabelProvider_new;
- fClassLabel= NewWizardMessages.CPListLabelProvider_classcontainer;
- fCreateLabel= NewWizardMessages.CPListLabelProvider_willbecreated;
- fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
-
- fSharedImages= JavaScriptUI.getSharedImages();
-
- IWorkbench workbench= JavaScriptPlugin.getDefault().getWorkbench();
-
- fProjectImage= workbench.getSharedImages().getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT);
- fAttributeDescriptors= JavaScriptPlugin.getDefault().getClasspathAttributeConfigurationDescriptors();
- }
-
- public String getText(Object element) {
- if (element instanceof CPListElement) {
- return getCPListElementText((CPListElement) element);
- } else if (element instanceof CPListElementAttribute) {
- CPListElementAttribute attribute= (CPListElementAttribute) element;
- String text= getCPListElementAttributeText(attribute);
-// if (attribute.isInNonModifiableContainer()) {
-// return Messages.format(NewWizardMessages.CPListLabelProvider_non_modifiable_attribute, text);
-// }
- return text;
- } else if (element instanceof CPUserLibraryElement) {
- return getCPUserLibraryText((CPUserLibraryElement) element);
- } else if (element instanceof IAccessRule) {
- IAccessRule rule= (IAccessRule) element;
- return Messages.format(NewWizardMessages.CPListLabelProvider_access_rules_label, new String[] { AccessRulesLabelProvider.getResolutionLabel(rule.getKind()), rule.getPattern().toString()});
- }
- return super.getText(element);
- }
-
- public String getCPUserLibraryText(CPUserLibraryElement element) {
- return element.getName();
- }
-
- public String getCPListElementAttributeText(CPListElementAttribute attrib) {
- String notAvailable= NewWizardMessages.CPListLabelProvider_none;
- String key= attrib.getKey();
- if (key.equals(CPListElement.EXCLUSION)) {
- String arg= null;
- IPath[] patterns= (IPath[]) attrib.getValue();
- if (patterns != null && patterns.length > 0) {
- int patternsCount= 0;
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < patterns.length; i++) {
- String pattern= patterns[i].toString();
- if (pattern.length() > 0) {
- if (patternsCount > 0) {
- buf.append(NewWizardMessages.CPListLabelProvider_exclusion_filter_separator);
- }
- buf.append(pattern);
- patternsCount++;
- }
- }
- if (patternsCount > 0) {
- arg= buf.toString();
- } else {
- arg= notAvailable;
- }
- } else {
- arg= notAvailable;
- }
- return Messages.format(NewWizardMessages.CPListLabelProvider_exclusion_filter_label, new String[] { arg });
- } else if (key.equals(CPListElement.INCLUSION)) {
- String arg= null;
- IPath[] patterns= (IPath[]) attrib.getValue();
- if (patterns != null && patterns.length > 0) {
- int patternsCount= 0;
- StringBuffer buf= new StringBuffer();
- for (int i= 0; i < patterns.length; i++) {
- String pattern= patterns[i].toString();
- if (pattern.length() > 0) {
- if (patternsCount > 0) {
- buf.append(NewWizardMessages.CPListLabelProvider_inclusion_filter_separator);
- }
- buf.append(pattern);
- patternsCount++;
- }
- }
- if (patternsCount > 0) {
- arg= buf.toString();
- } else {
- arg= notAvailable;
- }
- } else {
- arg= NewWizardMessages.CPListLabelProvider_all;
- }
- return Messages.format(NewWizardMessages.CPListLabelProvider_inclusion_filter_label, new String[] { arg });
- } else if (key.equals(CPListElement.ACCESSRULES)) {
- IAccessRule[] rules= (IAccessRule[]) attrib.getValue();
- int nRules= rules != null ? rules.length : 0;
-
- int parentKind= attrib.getParent().getEntryKind();
- if (parentKind == IIncludePathEntry.CPE_PROJECT) {
- Boolean combined= (Boolean) attrib.getParent().getAttribute(CPListElement.COMBINE_ACCESSRULES);
- if (nRules > 0) {
- if (combined.booleanValue()) {
- return Messages.format(NewWizardMessages.CPListLabelProvider_project_access_rules_combined, String.valueOf(nRules));
- } else {
- return Messages.format(NewWizardMessages.CPListLabelProvider_project_access_rules_not_combined, String.valueOf(nRules));
- }
- } else {
- return NewWizardMessages.CPListLabelProvider_project_access_rules_no_rules;
- }
- } else if (parentKind == IIncludePathEntry.CPE_CONTAINER) {
- if (nRules > 0) {
- return Messages.format(NewWizardMessages.CPListLabelProvider_container_access_rules, String.valueOf(nRules));
- } else {
- return NewWizardMessages.CPListLabelProvider_container_no_access_rules;
- }
- } else {
- if (nRules > 0) {
- return Messages.format(NewWizardMessages.CPListLabelProvider_access_rules_enabled, String.valueOf(nRules));
- } else {
- return NewWizardMessages.CPListLabelProvider_access_rules_disabled;
- }
- }
- } else {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(key);
- if (config != null) {
- ClasspathAttributeAccess access= attrib.getClasspathAttributeAccess();
- String nameLabel= config.getNameLabel(access);
- String valueLabel= config.getValueLabel(access);
- return Messages.format(NewWizardMessages.CPListLabelProvider_attribute_label, new String[] { nameLabel, valueLabel });
- }
- String arg= (String) attrib.getValue();
- if (arg == null) {
- arg= notAvailable;
- }
- return Messages.format(NewWizardMessages.CPListLabelProvider_attribute_label, new String[] { key, arg });
- }
- }
-
- public String getCPListElementText(CPListElement cpentry) {
- IPath path= cpentry.getPath();
- switch (cpentry.getEntryKind()) {
- case IIncludePathEntry.CPE_LIBRARY: {
-
- JsGlobalScopeContainerInitializer cpinit = cpentry.getContainerInitializer();
- if(cpinit!=null) {
- String displayText = cpinit.getDescription(cpentry.getPath(), cpentry.getJavaProject());
- if(displayText!=null)
- return displayText;
- }
-
- IResource resource= cpentry.getResource();
- if (resource instanceof IContainer) {
- StringBuffer buf= new StringBuffer(path.makeRelative().toString());
- IPath linkTarget= cpentry.getLinkTarget();
- if (linkTarget != null) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(linkTarget.toOSString());
- }
- buf.append(' ');
- buf.append(fClassLabel);
- if (!resource.exists()) {
- buf.append(' ');
- if (cpentry.isMissing()) {
- buf.append(fCreateLabel);
- } else {
- buf.append(fNewLabel);
- }
- }
- return buf.toString();
- } else if (ArchiveFileFilter.isArchivePath(path) || path.getFileExtension() == null) {
- return getPathString(path, resource == null);
- }
- // should not get here
- return path.makeRelative().toString();
- }
- case IIncludePathEntry.CPE_PROJECT:
- return path.lastSegment();
- case IIncludePathEntry.CPE_CONTAINER:
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(path, cpentry.getJavaProject());
-
- if (container != null) {
-
-
- return container.getDescription();
- }
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(path.segment(0));
- if (initializer != null) {
- String description= initializer.getDescription(path, cpentry.getJavaProject());
- return Messages.format(NewWizardMessages.CPListLabelProvider_unbound_library, description);
- }
- } catch (JavaScriptModelException e) {
-
- }
- return path.toString();
- case IIncludePathEntry.CPE_SOURCE: {
- StringBuffer buf= new StringBuffer(path.makeRelative().toString());
- IPath linkTarget= cpentry.getLinkTarget();
- if (linkTarget != null) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(linkTarget.toOSString());
- }
- IResource resource= cpentry.getResource();
- if (resource != null && !resource.exists()) {
- buf.append(' ');
- if (cpentry.isMissing()) {
- buf.append(fCreateLabel);
- } else {
- buf.append(fNewLabel);
- }
- } else if (cpentry.getOrginalPath() == null) {
- buf.append(' ');
- buf.append(fNewLabel);
- }
- return buf.toString();
- }
- default:
- // pass
- }
- return NewWizardMessages.CPListLabelProvider_unknown_element_label;
- }
-
- private String getPathString(IPath path, boolean isExternal) {
- if (ArchiveFileFilter.isArchivePath(path)) {
- IPath appendedPath= path.removeLastSegments(1);
- String appended= isExternal ? appendedPath.toOSString() : appendedPath.makeRelative().toString();
- return Messages.format(NewWizardMessages.CPListLabelProvider_twopart, new String[] { path.lastSegment(), appended });
- } else {
- return isExternal ? path.toOSString() : path.makeRelative().toString();
- }
- }
-
- private ImageDescriptor getCPListElementBaseImage(CPListElement cpentry) {
-
- IJsGlobalScopeContainerInitializerExtension init = JSDScopeUiUtil.getContainerUiInitializer(cpentry.getPath());
- if(init!=null ) {
- IPath entPath = cpentry.getPath();
- ImageDescriptor image = init.getImage(entPath, cpentry.toString(), cpentry.getJavaProject());
- if(image!=null) return image;
- }
-
- switch (cpentry.getEntryKind()) {
- case IIncludePathEntry.CPE_SOURCE:
- if (cpentry.getPath().segmentCount() == 1) {
- return fProjectImage;
- } else {
- return fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_PACKFRAG_ROOT);
- }
- case IIncludePathEntry.CPE_LIBRARY:
- IResource res= cpentry.getResource();
- if (res == null) {
- return fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_EXTERNAL_ARCHIVE_WITH_SOURCE);
- } else if (res instanceof IFile) {
- return fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_JAR_WITH_SOURCE);
- } else {
- return fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_PACKFRAG_ROOT);
- }
- case IIncludePathEntry.CPE_PROJECT:
- return fProjectImage;
- case IIncludePathEntry.CPE_VARIABLE:
- ImageDescriptor variableImage= fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_CLASSPATH_VAR_ENTRY);
- if (cpentry.isDeprecated()) {
- return new JavaScriptElementImageDescriptor(variableImage, JavaScriptElementImageDescriptor.DEPRECATED, JavaElementImageProvider.SMALL_SIZE);
- }
- return variableImage;
- case IIncludePathEntry.CPE_CONTAINER:
- return fSharedImages.getImageDescriptor(ISharedImages.IMG_OBJS_LIBRARY);
- default:
- return null;
- }
- }
-
- public Image getImage(Object element) {
- if (element instanceof CPListElement) {
- CPListElement cpentry= (CPListElement) element;
- ImageDescriptor imageDescriptor= getCPListElementBaseImage(cpentry);
- if (imageDescriptor != null) {
- if (cpentry.isMissing()) {
- imageDescriptor= new JavaScriptElementImageDescriptor(imageDescriptor, JavaScriptElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE);
- }
- return fRegistry.get(imageDescriptor);
- }
- } else if (element instanceof CPListElementAttribute) {
- CPListElementAttribute attribute= (CPListElementAttribute) element;
- String key= (attribute).getKey();
- if (key.equals(CPListElement.EXCLUSION)) {
- return fRegistry.get(JavaPluginImages.DESC_OBJS_EXCLUSION_FILTER_ATTRIB);
- } else if (key.equals(CPListElement.INCLUSION)) {
- return fRegistry.get(JavaPluginImages.DESC_OBJS_INCLUSION_FILTER_ATTRIB);
- } else if (key.equals(CPListElement.ACCESSRULES)) {
- return fRegistry.get(JavaPluginImages.DESC_OBJS_ACCESSRULES_ATTRIB);
- } else {
- ClasspathAttributeConfiguration config= fAttributeDescriptors.get(key);
- if (config != null) {
- return fRegistry.get(config.getImageDescriptor(attribute.getClasspathAttributeAccess()));
- }
- }
- return fSharedImages.getImage(ISharedImages.IMG_OBJS_CLASSPATH_VAR_ENTRY);
- } else if (element instanceof CPUserLibraryElement) {
- return fSharedImages.getImage(ISharedImages.IMG_OBJS_LIBRARY);
- } else if (element instanceof IAccessRule) {
- IAccessRule rule= (IAccessRule) element;
- return AccessRulesLabelProvider.getResolutionImage(rule.getKind());
- }
- return null;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java
deleted file mode 100644
index b7e29625..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class CPUserLibraryElement {
-
- private class UpdatedJsGlobalScopeContainer implements IJsGlobalScopeContainer {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getClasspathEntries()
- */
- /**
- * @deprecated Use {@link #getIncludepathEntries()} instead
- */
- public IIncludePathEntry[] getClasspathEntries() {
- return getIncludepathEntries();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getClasspathEntries()
- */
- public IIncludePathEntry[] getIncludepathEntries() {
- CPListElement[] children= getChildren();
- IIncludePathEntry[] entries= new IIncludePathEntry[children.length];
- for (int i= 0; i < entries.length; i++) {
- entries[i]= children[i].getClasspathEntry();
- }
- return entries;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getDescription()
- */
- public String getDescription() {
- return getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getKind()
- */
- public int getKind() {
- return K_APPLICATION;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#getPath()
- */
- public IPath getPath() {
- return CPUserLibraryElement.this.getPath();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer#resolvedLibraryImport(java.lang.String)
- */
- public String[] resolvedLibraryImport(String a) {
- // TODO Auto-generated method stub
- return null;
- }
- }
-
-
- private String fName;
- private List fChildren;
-
- public CPUserLibraryElement(String name, IJsGlobalScopeContainer container, IJavaScriptProject project) {
- fName= name;
- fChildren= new ArrayList();
- if (container != null) {
- IIncludePathEntry[] entries= container.getIncludepathEntries();
- CPListElement[] res= new CPListElement[entries.length];
- for (int i= 0; i < res.length; i++) {
- IIncludePathEntry curr= entries[i];
- CPListElement elem= CPListElement.createFromExisting(this, curr, project);
- fChildren.add(elem);
- }
- }
- }
-
- public CPUserLibraryElement(String name, CPListElement[] children) {
- fName= name;
- fChildren= new ArrayList();
- if (children != null) {
- for (int i= 0; i < children.length; i++) {
- fChildren.add(children[i]);
- }
- }
- }
-
- public CPListElement[] getChildren() {
- return (CPListElement[]) fChildren.toArray(new CPListElement[fChildren.size()]);
- }
-
- public String getName() {
- return fName;
- }
-
- public IPath getPath() {
- return new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(fName);
- }
-
- public void add(CPListElement element) {
- if (!fChildren.contains(element)) {
- fChildren.add(element);
- }
- }
-
- public void remove(CPListElement element) {
- fChildren.remove(element);
- }
-
- public void replace(CPListElement existingElement, CPListElement element) {
- if (fChildren.contains(element)) {
- fChildren.remove(existingElement);
- } else {
- int index= fChildren.indexOf(existingElement);
- if (index != -1) {
- fChildren.set(index, element);
- } else {
- fChildren.add(element);
- }
- element.setAttributesFromExisting(existingElement);
- }
- }
-
- public IJsGlobalScopeContainer getUpdatedContainer() {
- return new UpdatedJsGlobalScopeContainer();
- }
-
- public boolean hasChanges(IJsGlobalScopeContainer oldContainer) {
- if (oldContainer == null) {
- return true;
- }
- IIncludePathEntry[] oldEntries= oldContainer.getIncludepathEntries();
- if (fChildren.size() != oldEntries.length) {
- return true;
- }
- for (int i= 0; i < oldEntries.length; i++) {
- CPListElement child= (CPListElement) fChildren.get(i);
- if (!child.getClasspathEntry().equals(oldEntries[i])) {
- return true;
- }
- }
- return false;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathAttributeConfigurationDescriptors.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathAttributeConfigurationDescriptors.java
deleted file mode 100644
index a30d86a0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathAttributeConfigurationDescriptors.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.HashMap;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.ISafeRunnable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration;
-
-public class ClasspathAttributeConfigurationDescriptors {
-
- private static class Descriptor {
-
- private IConfigurationElement fConfigElement;
- private ClasspathAttributeConfiguration fInstance;
-
- private static final String ATT_NAME = "attributeName"; //$NON-NLS-1$
- private static final String ATT_CLASS = "class"; //$NON-NLS-1$
-
- public Descriptor(IConfigurationElement configElement) throws CoreException {
- fConfigElement = configElement;
- fInstance= null;
-
- String name = configElement.getAttribute(ATT_NAME);
- String pageClassName = configElement.getAttribute(ATT_CLASS);
-
- if (name == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (missing attributeName)", null)); //$NON-NLS-1$
- }
- if (pageClassName == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (missing class name): " + name, null)); //$NON-NLS-1$
- }
- }
-
- public ClasspathAttributeConfiguration getInstance() throws CoreException {
- if (fInstance == null) {
- Object elem= CoreUtility.createExtension(fConfigElement, ATT_CLASS);
- if (elem instanceof ClasspathAttributeConfiguration) {
- fInstance= (ClasspathAttributeConfiguration) elem;
- } else {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (page not of type IJsGlobalScopeContainerPage): " + getKey(), null)); //$NON-NLS-1$
- }
- }
- return fInstance;
- }
-
- public String getKey() {
- return fConfigElement.getAttribute(ATT_NAME);
- }
- }
-
- private static final String ATT_EXTENSION = "classpathAttributeConfiguration"; //$NON-NLS-1$
-
- private HashMap fDescriptors;
-
- public ClasspathAttributeConfigurationDescriptors() {
- fDescriptors= null;
- }
-
- private HashMap getDescriptors() {
- if (fDescriptors == null) {
- fDescriptors= readExtensions();
- }
- return fDescriptors;
- }
-
- public boolean containsKey(String attributeKey) {
- return getDescriptors().containsKey(attributeKey);
- }
-
- public ClasspathAttributeConfiguration get(final String attributeKey) {
- final Descriptor desc= (Descriptor) getDescriptors().get(attributeKey);
- if (desc == null) {
- return null;
- }
- final ClasspathAttributeConfiguration[] res= { null };
- SafeRunner.run(new ISafeRunnable() {
-
- public void handleException(Throwable exception) {
- JavaScriptPlugin.log(exception);
- getDescriptors().remove(attributeKey); // remove from list
- }
-
- public void run() throws Exception {
- res[0]= desc.getInstance();
- }
- });
- return res[0];
- }
-
- private static HashMap readExtensions() {
- IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(JavaScriptUI.ID_PLUGIN, ATT_EXTENSION);
- HashMap descriptors= new HashMap(elements.length * 2);
- for (int i= 0; i < elements.length; i++) {
- try {
- Descriptor curr= new Descriptor(elements[i]);
- descriptors.put(curr.getKey(), curr);
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return descriptors;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathOrderingWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathOrderingWorkbookPage.java
deleted file mode 100644
index 5887774e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ClasspathOrderingWorkbookPage.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ObjectStringStatusButtonDialogField;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-
-public class ClasspathOrderingWorkbookPage extends BuildPathBasePage {
-
- private ListDialogField fClassPathList;
-
- private List allCpElements;
-
- private static final boolean HIDE_ALL_READONLY_CONTAINERS = true;
- private ObjectStringStatusButtonDialogField superTypeField;
- private IJavaScriptProject fJavaProject;
- private Control fSWTControl;
-
-
- public ClasspathOrderingWorkbookPage(ListDialogField classPathList) {
- fClassPathList= classPathList;
- superTypeField = new ObjectStringStatusButtonDialogField(new OrderingWorkbookPageAdapter());
-
- }
-
- public ObjectStringStatusButtonDialogField getSuperField() {
- return superTypeField;
- }
- class OrderingWorkbookPageAdapter implements IStringButtonAdapter{
- public void changeControlPressed(DialogField field) {
- if(field==superTypeField) {
- CPListElement elements[] = (CPListElement[])allCpElements.toArray(new CPListElement[allCpElements.size()]);
- Object prevSuperTypeObject = superTypeField.getValue();
- LibrarySuperType oldSuper = null;
-
- if(prevSuperTypeObject!=null) {
- oldSuper = (LibrarySuperType)prevSuperTypeObject;
- }
-
-
- LibrarySuperType superType = openSuperTypeSelectionDialog(elements,oldSuper);
-
- if(superType!=null && superType!=oldSuper) {
- superTypeField.setValue(superType);
- //List reOrder = fClassPathList.getElements();
- IPath cpEntryPath = superType.getRawContainerPath();
-
- Iterator listItt = allCpElements.iterator();
- CPListElement found = null;
- int foundIndex = -1;
-
- while(listItt.hasNext()) {
- foundIndex++;
- CPListElement o = (CPListElement)listItt.next();
- if(o.getPath().equals(cpEntryPath)) {
- found = o;
- break;
- }
- }
-
- if(found!=null) {
- allCpElements.add(0,allCpElements.remove(foundIndex));
- }
-
-
- fClassPathList.setElements(filterNodes( allCpElements));
-
- }
- }
-
- }
-
- }
-
-// private String[] popupFieldSelectionDialog() {
-// return new String[] {"Window","Basic Browser Library"};
-// }
-
- public Control getControl(Composite parent) {
- PixelConverter converter= new PixelConverter(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- superTypeField.setButtonLabel(NewWizardMessages.ClasspathOrderingWorkbookPage_SelectReorder);
- //superTypeField.setDialogFieldListener(null);
-
- superTypeField.setLabelText(NewWizardMessages.ClasspathOrderingWorkbookPage_SuperType);
-
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fClassPathList, superTypeField }, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fClassPathList.getListControl(null));
- //superTypeField.setTextFieldEditable(false);
-
- int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
- fClassPathList.setButtonsMinWidth(buttonBarWidth);
- fSWTControl = composite;
- return composite;
- }
-
- /*
- * @see BuildPathBasePage#getSelection
- */
- public List getSelection() {
- return fClassPathList.getSelectedElements();
- }
-
- /*
- * @see BuildPathBasePage#setSelection
- */
- public void setSelection(List selElements, boolean expand) {
- allCpElements = selElements;
- fClassPathList.selectElements(new StructuredSelection(allCpElements));
- }
-
- private List filterNodes(List elements) {
- ArrayList filter = new ArrayList();
-
- Iterator itt = elements.iterator();
-
- while(itt.hasNext()) {
- Object next = itt.next();
- if(((next instanceof CPListElement) && ((CPListElement)next).isJRE() )) {
- // dont add
- }else if(HIDE_ALL_READONLY_CONTAINERS && (next instanceof CPListElement) && ((CPListElement)next).isInNonModifiableContainer()) {
- // dont add
- }else {
- filter.add(next);
- }
- }
-
- return filter;
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
- */
- public boolean isEntryKind(int kind) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#init(org.eclipse.wst.jsdt.core.IJavaScriptProject)
- */
- public void init(IJavaScriptProject javaProject) {
- fJavaProject = javaProject;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
-
- fClassPathList.setFocus();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#aboutToDispose()
- */
- public void aboutToDispose() {
- fClassPathList.setElements(allCpElements);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#aboutToShow()
- */
- public void aboutToShow() {
- allCpElements = fClassPathList.getElements();
- fClassPathList.setElements(filterNodes( fClassPathList.getElements()));
- superTypeField.setText(superTypeField.getValue().toString());
- }
-
- private LibrarySuperType openSuperTypeSelectionDialog(CPListElement[] existingCp, LibrarySuperType existingSuper) {
- LibrarySuperType newLib = BuildPathDialogAccess.chooseSuperType(getShell(), existingCp, existingSuper, fJavaProject);
- return newLib;
- }
-
-// private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
-// if (existing == null) {
-// IIncludePathEntry[] created= BuildPathDialogAccess.chooseContainerEntries(getShell(), fCurrJProject, getRawClasspath());
-// if (created != null) {
-// CPListElement[] res= new CPListElement[created.length];
-// for (int i= 0; i < res.length; i++) {
-// //res[i]= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created[i].getPath(), null);
-// res[i]= new CPListElement(fCurrJProject, created[i].getEntryKind(), created[i].getPath(), null);
-// }
-// return res;
-// }
-// } else {
-// IIncludePathEntry created= BuildPathDialogAccess.configureContainerEntry(getShell(), existing.getClasspathEntry(), fCurrJProject, getRawClasspath());
-// if (created != null) {
-// //CPListElement elem= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created.getPath(), null);
-// CPListElement elem= new CPListElement(fCurrJProject, created.getEntryKind(), created.getPath(), null);
-// return new CPListElement[] { elem };
-// }
-// }
-// return null;
-// }
-
- private Shell getShell() {
- if (fSWTControl != null) {
- return fSWTControl.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java
deleted file mode 100644
index 92427efe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TrayDialog;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.model.BaseWorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-import org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction;
-
-public class CreateMultipleSourceFoldersDialog extends TrayDialog {
-
- private final class FakeFolderBaseWorkbenchContentProvider extends BaseWorkbenchContentProvider {
- /**
- * {@inheritDoc}
- */
- public Object getParent(Object element) {
- Object object= fNonExistingFolders.get(element);
- if (object != null)
- return object;
-
- return super.getParent(element);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object[] getChildren(Object element) {
- List result= new ArrayList();
- //all keys with value element
- Set keys= fNonExistingFolders.keySet();
- for (Iterator iter= keys.iterator(); iter.hasNext();) {
- Object key= iter.next();
- if (fNonExistingFolders.get(key).equals(element)) {
- result.add(key);
- }
- }
- if (result.size() == 0)
- return super.getChildren(element);
-
- Object[] children= super.getChildren(element);
- for (int i= 0; i < children.length; i++) {
- result.add(children[i]);
- }
- return result.toArray();
- }
- }
-
- private final IJavaScriptProject fJavaProject;
- private final CPListElement[] fExistingElements;
- private String fOutputLocation;
- private final HashSet fRemovedElements;
- private final HashSet fModifiedElements;
- private final HashSet fInsertedElements;
- private final Hashtable fNonExistingFolders;
-
- public CreateMultipleSourceFoldersDialog(final IJavaScriptProject javaProject, final CPListElement[] existingElements, final String outputLocation, Shell shell) {
- super(shell);
- fJavaProject= javaProject;
- fExistingElements= existingElements;
- fOutputLocation= outputLocation;
- fRemovedElements= new HashSet();
- fModifiedElements= new HashSet();
- fInsertedElements= new HashSet();
- fNonExistingFolders= new Hashtable();
-
- for (int i= 0; i < existingElements.length; i++) {
- CPListElement cur= existingElements[i];
- if (cur.getResource() == null || !cur.getResource().exists()) {
- addFakeFolder(fJavaProject.getProject(), cur);
- }
- }
- }
-
- public int open() {
- Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
- List existingContainers= getExistingContainers(fExistingElements);
-
- IProject[] allProjects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- ArrayList rejectedElements= new ArrayList(allProjects.length);
- IProject currProject= fJavaProject.getProject();
- for (int i= 0; i < allProjects.length; i++) {
- if (!allProjects[i].equals(currProject)) {
- rejectedElements.add(allProjects[i]);
- }
- }
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new FakeFolderBaseWorkbenchContentProvider();
-
- String title= NewWizardMessages.SourceContainerWorkbookPage_ExistingSourceFolderDialog_new_title;
- String message= NewWizardMessages.SourceContainerWorkbookPage_ExistingSourceFolderDialog_edit_description;
-
-
- MultipleFolderSelectionDialog dialog= new MultipleFolderSelectionDialog(getShell(), lp, cp) {
- protected Control createDialogArea(Composite parent) {
- Control result= super.createDialogArea(parent);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_CHOOSE_EXISTING_FOLDER_TO_MAKE_SOURCE_FOLDER);
- return result;
- }
-
- protected Object createFolder(final IContainer container) {
- final Object[] result= new Object[1];
- final CPListElement newElement= new CPListElement(fJavaProject, IIncludePathEntry.CPE_SOURCE);
- final AddSourceFolderWizard wizard= newSourceFolderWizard(newElement, fExistingElements, fOutputLocation, container);
- AbstractOpenWizardAction action= new AbstractOpenWizardAction() {
- protected INewWizard createWizard() throws CoreException {
- return wizard;
- }
- };
- action.addPropertyChangeListener(new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(IAction.RESULT)) {
- if (event.getNewValue().equals(Boolean.TRUE)) {
- result[0]= addFakeFolder(fJavaProject.getProject(), newElement);
- } else {
- wizard.cancel();
- }
- }
- }
- });
- action.run();
- return result[0];
- }
- };
- dialog.setExisting(existingContainers.toArray());
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.addFilter(filter);
- dialog.setInput(fJavaProject.getProject().getParent());
- dialog.setInitialFocus(fJavaProject.getProject());
-
- if (dialog.open() == Window.OK) {
- Object[] elements= dialog.getResult();
- for (int i= 0; i < elements.length; i++) {
- IResource res= (IResource)elements[i];
- fInsertedElements.add(new CPListElement(fJavaProject, IIncludePathEntry.CPE_SOURCE, res.getFullPath(), res));
- }
-
- if (fExistingElements.length == 1) {
- CPListElement existingElement= fExistingElements[0];
- if (existingElement.getResource() instanceof IProject) {
- if (!removeProjectFromBP(existingElement)) {
- ArrayList added= new ArrayList(fInsertedElements);
- HashSet updatedEclusionPatterns= new HashSet();
- addExlusionPatterns(added, updatedEclusionPatterns);
- fModifiedElements.addAll(updatedEclusionPatterns);
- }
- }
- } else {
- ArrayList added= new ArrayList(fInsertedElements);
- HashSet updatedEclusionPatterns= new HashSet();
- addExlusionPatterns(added, updatedEclusionPatterns);
- fModifiedElements.addAll(updatedEclusionPatterns);
- }
- return Window.OK;
- } else {
- return Window.CANCEL;
- }
- }
-
- public List getInsertedElements() {
- return new ArrayList(fInsertedElements);
- }
-
- public List getRemovedElements() {
- return new ArrayList(fRemovedElements);
- }
-
- public List getModifiedElements() {
- return new ArrayList(fModifiedElements);
- }
-
- public IPath getOutputLocation() {
- return new Path(fOutputLocation).makeAbsolute();
- }
-
- /**
- * Asks to change the output folder to 'proj/bin' when no source folders were existing
- */
- private boolean removeProjectFromBP(CPListElement existing) {
- IPath outputFolder= new Path(fOutputLocation);
-
- IPath newOutputFolder= null;
- String message;
- if (outputFolder.segmentCount() == 1) {
- String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
- newOutputFolder= outputFolder.append(outputFolderName);
- message= Messages.format(NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_and_output_message, newOutputFolder);
- } else {
- message= NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_message;
- }
- String title= NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_title;
- if (MessageDialog.openQuestion(getShell(), title, message)) {
- fRemovedElements.add(existing);
- if (newOutputFolder != null) {
- fOutputLocation= newOutputFolder.toString();
- }
- return true;
- }
- return false;
- }
-
- private void addExlusionPatterns(List newEntries, Set modifiedEntries) {
- BuildPathBasePage.fixNestingConflicts((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]), fExistingElements, modifiedEntries);
- if (!modifiedEntries.isEmpty()) {
- String title= NewWizardMessages.SourceContainerWorkbookPage_exclusion_added_title;
- String message= NewWizardMessages.SourceContainerWorkbookPage_exclusion_added_message;
- MessageDialog.openInformation(getShell(), title, message);
- }
- }
-
- private AddSourceFolderWizard newSourceFolderWizard(CPListElement element, CPListElement[] existing, String outputLocation, IContainer parent) {
- AddSourceFolderWizard wizard= new AddSourceFolderWizard(existing, element, false, true, false, false, false, parent);
- wizard.setDoFlushChange(false);
- return wizard;
- }
-
- private List getExistingContainers(CPListElement[] existingElements) {
- List res= new ArrayList();
- for (int i= 0; i < existingElements.length; i++) {
- IResource resource= existingElements[i].getResource();
- if (resource instanceof IContainer) {
- res.add(resource);
- }
- }
- Set keys= fNonExistingFolders.keySet();
- for (Iterator iter= keys.iterator(); iter.hasNext();) {
- IFolder folder= (IFolder)iter.next();
- res.add(folder);
- }
- return res;
- }
-
- private IFolder addFakeFolder(final IContainer container, final CPListElement element) {
- IFolder result;
- IPath projectPath= fJavaProject.getPath();
- IPath path= element.getPath();
- if (projectPath.isPrefixOf(path)) {
- path= path.removeFirstSegments(projectPath.segmentCount());
- }
- result= container.getFolder(path);
- IFolder folder= result;
- do {
- IContainer parent= folder.getParent();
- fNonExistingFolders.put(folder, parent);
- if (parent instanceof IFolder) {
- folder= (IFolder)parent;
- } else {
- folder= null;
- }
- } while (folder != null && !folder.exists());
- return result;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java
deleted file mode 100644
index 4995229e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-public class EditFilterWizard extends BuildPathWizard {
-
- private SetFilterWizardPage fFilterPage;
- private final IPath[] fOrginalInclusion, fOriginalExclusion;
-
- public EditFilterWizard(CPListElement[] existingEntries, CPListElement newEntry) {
- super(existingEntries, newEntry, NewWizardMessages.ExclusionInclusionDialog_title, null);
-
- IPath[] inc= (IPath[])newEntry.getAttribute(CPListElement.INCLUSION);
- fOrginalInclusion= new IPath[inc.length];
- System.arraycopy(inc, 0, fOrginalInclusion, 0, inc.length);
-
- IPath[] excl= (IPath[])newEntry.getAttribute(CPListElement.EXCLUSION);
- fOriginalExclusion= new IPath[excl.length];
- System.arraycopy(excl, 0, fOriginalExclusion, 0, excl.length);
- }
-
- /*
- * @see Wizard#addPages
- */
- public void addPages() {
- super.addPages();
-
- fFilterPage= new SetFilterWizardPage(getEntryToEdit(), getExistingEntries());
- addPage(fFilterPage);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.IWizard#performFinish()
- */
- public boolean performFinish() {
- CPListElement entryToEdit= getEntryToEdit();
- entryToEdit.setAttribute(CPListElement.INCLUSION, fFilterPage.getInclusionPattern());
- entryToEdit.setAttribute(CPListElement.EXCLUSION, fFilterPage.getExclusionPattern());
-
- return super.performFinish();
- }
-
- /**
- * {@inheritDoc}
- */
- public void cancel() {
- CPListElement entryToEdit= getEntryToEdit();
- entryToEdit.setAttribute(CPListElement.INCLUSION, fOrginalInclusion);
- entryToEdit.setAttribute(CPListElement.EXCLUSION, fOriginalExclusion);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionDialog.java
deleted file mode 100644
index e7933bb0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionDialog.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-
-public class ExclusionInclusionDialog extends StatusDialog {
-
- private static class ExclusionInclusionLabelProvider extends LabelProvider {
-
- private Image fElementImage;
-
- public ExclusionInclusionLabelProvider(ImageDescriptor descriptor) {
- ImageDescriptorRegistry registry= JavaScriptPlugin.getImageDescriptorRegistry();
- fElementImage= registry.get(descriptor);
- }
-
- public Image getImage(Object element) {
- return fElementImage;
- }
-
- public String getText(Object element) {
- return (String) element;
- }
-
- }
-
- private ListDialogField fInclusionPatternList;
- private ListDialogField fExclusionPatternList;
- private CPListElement fCurrElement;
- private IProject fCurrProject;
-
- private IContainer fCurrSourceFolder;
-
- private static final int IDX_ADD= 0;
- private static final int IDX_ADD_MULTIPLE= 1;
- private static final int IDX_EDIT= 2;
- private static final int IDX_REMOVE= 4;
-
-
- public ExclusionInclusionDialog(Shell parent, CPListElement entryToEdit, boolean focusOnExcluded) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fCurrElement= entryToEdit;
-
- setTitle(NewWizardMessages.ExclusionInclusionDialog_title);
-
- fCurrProject= entryToEdit.getJavaProject().getProject();
- IWorkspaceRoot root= fCurrProject.getWorkspace().getRoot();
- IResource res= root.findMember(entryToEdit.getPath());
- if (res instanceof IContainer) {
- fCurrSourceFolder= (IContainer) res;
- }
-
- String excLabel= NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_label;
- ImageDescriptor excDescriptor= JavaPluginImages.DESC_OBJS_EXCLUSION_FILTER_ATTRIB;
- String[] excButtonLabels= new String[] {
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add_multiple,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_edit,
- null,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_remove
- };
-
-
- String incLabel= NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_label;
- ImageDescriptor incDescriptor= JavaPluginImages.DESC_OBJS_INCLUSION_FILTER_ATTRIB;
- String[] incButtonLabels= new String[] {
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add_multiple,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_edit,
- null,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_remove
- };
-
- fExclusionPatternList= createListContents(entryToEdit, CPListElement.EXCLUSION, excLabel, excDescriptor, excButtonLabels);
- fInclusionPatternList= createListContents(entryToEdit, CPListElement.INCLUSION, incLabel, incDescriptor, incButtonLabels);
- if (focusOnExcluded) {
- fExclusionPatternList.postSetFocusOnDialogField(parent.getDisplay());
- } else {
- fInclusionPatternList.postSetFocusOnDialogField(parent.getDisplay());
- }
- }
-
-
- private ListDialogField createListContents(CPListElement entryToEdit, String key, String label, ImageDescriptor descriptor, String[] buttonLabels) {
- ExclusionPatternAdapter adapter= new ExclusionPatternAdapter();
-
- ListDialogField patternList= new ListDialogField(adapter, buttonLabels, new ExclusionInclusionLabelProvider(descriptor));
- patternList.setDialogFieldListener(adapter);
- patternList.setLabelText(label);
- patternList.setRemoveButtonIndex(IDX_REMOVE);
- patternList.enableButton(IDX_EDIT, false);
-
- IPath[] pattern= (IPath[]) entryToEdit.getAttribute(key);
-
- ArrayList elements= new ArrayList(pattern.length);
- for (int i= 0; i < pattern.length; i++) {
- elements.add(pattern[i].toString());
- }
- patternList.setElements(elements);
- patternList.selectFirstElement();
- patternList.enableButton(IDX_ADD_MULTIPLE, fCurrSourceFolder != null);
- patternList.setViewerComparator(new ViewerComparator());
- return patternList;
- }
-
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- DialogField labelField= new DialogField();
- String name= fCurrElement.getPath().makeRelative().toString();
- labelField.setLabelText(Messages.format(NewWizardMessages.ExclusionInclusionDialog_description, name));
- labelField.doFillIntoGrid(inner, 2);
-
- fInclusionPatternList.doFillIntoGrid(inner, 3);
- LayoutUtil.setHorizontalSpan(fInclusionPatternList.getLabelControl(null), 2);
- LayoutUtil.setHorizontalGrabbing(fInclusionPatternList.getListControl(null));
-
- fExclusionPatternList.doFillIntoGrid(inner, 3);
- LayoutUtil.setHorizontalSpan(fExclusionPatternList.getLabelControl(null), 2);
- LayoutUtil.setHorizontalGrabbing(fExclusionPatternList.getListControl(null));
-
- applyDialogFont(composite);
- return composite;
- }
-
- protected void doCustomButtonPressed(ListDialogField field, int index) {
- if (index == IDX_ADD) {
- addEntry(field);
- } else if (index == IDX_EDIT) {
- editEntry(field);
- } else if (index == IDX_ADD_MULTIPLE) {
- addMultipleEntries(field);
- }
- }
-
- protected void doDoubleClicked(ListDialogField field) {
- editEntry(field);
- }
-
- protected void doSelectionChanged(ListDialogField field) {
- List selected= field.getSelectedElements();
- field.enableButton(IDX_EDIT, canEdit(selected));
- }
-
- private boolean canEdit(List selected) {
- return selected.size() == 1;
- }
-
- private void editEntry(ListDialogField field) {
- List selElements= field.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- List existing= field.getElements();
- String entry= (String) selElements.get(0);
- ExclusionInclusionEntryDialog dialog= new ExclusionInclusionEntryDialog(getShell(), isExclusion(field), entry, existing, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.replaceElement(entry, dialog.getExclusionPattern());
- }
- }
-
- private boolean isExclusion(ListDialogField field) {
- return field == fExclusionPatternList;
- }
-
-
- private void addEntry(ListDialogField field) {
- List existing= field.getElements();
- ExclusionInclusionEntryDialog dialog= new ExclusionInclusionEntryDialog(getShell(), isExclusion(field), null, existing, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.addElement(dialog.getExclusionPattern());
- }
- }
-
-
-
- // -------- ExclusionPatternAdapter --------
-
- private class ExclusionPatternAdapter implements IListAdapter, IDialogFieldListener {
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField, int)
- */
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed(field, index);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged(field);
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#doubleClicked(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked(field);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- }
-
- }
-
- protected void doStatusLineUpdate() {
- }
-
- protected void checkIfPatternValid() {
- }
-
-
- private IPath[] getPattern(ListDialogField field) {
- Object[] arr= field.getElements().toArray();
- Arrays.sort(arr);
- IPath[] res= new IPath[arr.length];
- for (int i= 0; i < res.length; i++) {
- res[i]= new Path((String) arr[i]);
- }
- return res;
- }
-
- public IPath[] getExclusionPattern() {
- return getPattern(fExclusionPatternList);
- }
-
- public IPath[] getInclusionPattern() {
- return getPattern(fInclusionPatternList);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.EXCLUSION_PATTERN_DIALOG);
- }
-
- private void addMultipleEntries(ListDialogField field) {
- String title, message;
- if (isExclusion(field)) {
- title= NewWizardMessages.ExclusionInclusionDialog_ChooseExclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionDialog_ChooseExclusionPattern_description;
- } else {
- title= NewWizardMessages.ExclusionInclusionDialog_ChooseInclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionDialog_ChooseInclusionPattern_description;
- }
-
- IPath[] res= ExclusionInclusionEntryDialog.chooseExclusionPattern(getShell(), fCurrSourceFolder, title, message, null, true);
- if (res != null) {
- for (int i= 0; i < res.length; i++) {
- field.addElement(res[i].toString());
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionEntryDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionEntryDialog.java
deleted file mode 100644
index ed6e71b3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ExclusionInclusionEntryDialog.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-
-public class ExclusionInclusionEntryDialog extends StatusDialog {
-
- private StringButtonDialogField fExclusionPatternDialog;
- private StatusInfo fExclusionPatternStatus;
-
- private IContainer fCurrSourceFolder;
- private String fExclusionPattern;
- private List fExistingPatterns;
- private boolean fIsExclusion;
-
- public ExclusionInclusionEntryDialog(Shell parent, boolean isExclusion, String patternToEdit, List existingPatterns, CPListElement entryToEdit) {
- super(parent);
- fIsExclusion= isExclusion;
- fExistingPatterns= existingPatterns;
- String title, message;
- if (isExclusion) {
- if (patternToEdit == null) {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_exclude_add_title;
- } else {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_exclude_edit_title;
- }
- message= Messages.format(NewWizardMessages.ExclusionInclusionEntryDialog_exclude_pattern_label, entryToEdit.getPath().makeRelative().toString());
- } else {
- if (patternToEdit == null) {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_include_add_title;
- } else {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_include_edit_title;
- }
- message= Messages.format(NewWizardMessages.ExclusionInclusionEntryDialog_include_pattern_label, entryToEdit.getPath().makeRelative().toString());
- }
- setTitle(title);
- if (patternToEdit != null) {
- fExistingPatterns.remove(patternToEdit);
- }
-
-
- IWorkspaceRoot root= entryToEdit.getJavaProject().getProject().getWorkspace().getRoot();
- IResource res= root.findMember(entryToEdit.getPath());
- if (res instanceof IContainer) {
- fCurrSourceFolder= (IContainer) res;
- }
-
- fExclusionPatternStatus= new StatusInfo();
-
- ExclusionPatternAdapter adapter= new ExclusionPatternAdapter();
- fExclusionPatternDialog= new StringButtonDialogField(adapter);
- fExclusionPatternDialog.setLabelText(message);
- fExclusionPatternDialog.setButtonLabel(NewWizardMessages.ExclusionInclusionEntryDialog_pattern_button);
- fExclusionPatternDialog.setDialogFieldListener(adapter);
- fExclusionPatternDialog.enableButton(fCurrSourceFolder != null);
-
- if (patternToEdit == null) {
- fExclusionPatternDialog.setText(""); //$NON-NLS-1$
- } else {
- fExclusionPatternDialog.setText(patternToEdit.toString());
- }
- }
-
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite)super.createDialogArea(parent);
-
- int widthHint= convertWidthInCharsToPixels(60);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
-
- Label description= new Label(inner, SWT.WRAP);
-
- if (fIsExclusion) {
- description.setText(NewWizardMessages.ExclusionInclusionEntryDialog_exclude_description);
- } else {
- description.setText(NewWizardMessages.ExclusionInclusionEntryDialog_include_description);
- }
- GridData gd= new GridData();
- gd.horizontalSpan= 2;
- gd.widthHint= convertWidthInCharsToPixels(80);
- description.setLayoutData(gd);
-
- fExclusionPatternDialog.doFillIntoGrid(inner, 3);
-
- LayoutUtil.setWidthHint(fExclusionPatternDialog.getLabelControl(null), widthHint);
- LayoutUtil.setHorizontalSpan(fExclusionPatternDialog.getLabelControl(null), 2);
-
- LayoutUtil.setWidthHint(fExclusionPatternDialog.getTextControl(null), widthHint);
- LayoutUtil.setHorizontalGrabbing(fExclusionPatternDialog.getTextControl(null));
-
- fExclusionPatternDialog.postSetFocusOnDialogField(parent.getDisplay());
- applyDialogFont(composite);
- return composite;
- }
-
-
- // -------- ExclusionPatternAdapter --------
-
- private class ExclusionPatternAdapter implements IDialogFieldListener, IStringButtonAdapter {
-
- // -------- IDialogFieldListener
-
- public void dialogFieldChanged(DialogField field) {
- doStatusLineUpdate();
- }
-
- public void changeControlPressed(DialogField field) {
- doChangeControlPressed();
- }
- }
-
- protected void doChangeControlPressed() {
- IPath pattern= chooseExclusionPattern();
- if (pattern != null) {
- fExclusionPatternDialog.setText(pattern.toString());
- }
- }
-
- protected void doStatusLineUpdate() {
- checkIfPatternValid();
- updateStatus(fExclusionPatternStatus);
- }
-
- protected void checkIfPatternValid() {
- String pattern= fExclusionPatternDialog.getText().trim();
- if (pattern.length() == 0) {
- fExclusionPatternStatus.setError(NewWizardMessages.ExclusionInclusionEntryDialog_error_empty);
- return;
- }
- IPath path= new Path(pattern);
- if (path.isAbsolute() || path.getDevice() != null) {
- fExclusionPatternStatus.setError(NewWizardMessages.ExclusionInclusionEntryDialog_error_notrelative);
- return;
- }
- if (fExistingPatterns.contains(pattern)) {
- fExclusionPatternStatus.setError(NewWizardMessages.ExclusionInclusionEntryDialog_error_exists);
- return;
- }
-
- fExclusionPattern= pattern;
- fExclusionPatternStatus.setOK();
- }
-
-
- public String getExclusionPattern() {
- return fExclusionPattern;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.EXCLUSION_PATTERN_DIALOG);
- }
-
- // ---------- util method ------------
-
- private IPath chooseExclusionPattern() {
- String title, message;
- if (fIsExclusion) {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_ChooseExclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionEntryDialog_ChooseExclusionPattern_description;
- } else {
- title= NewWizardMessages.ExclusionInclusionEntryDialog_ChooseInclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionEntryDialog_ChooseInclusionPattern_description;
- }
- IPath initialPath= new Path(fExclusionPatternDialog.getText());
-
- IPath[] res= chooseExclusionPattern(getShell(), fCurrSourceFolder, title, message, initialPath, false);
- if (res == null) {
- return null;
- }
- return res[0];
- }
-
- public static IPath[] chooseExclusionPattern(Shell shell, IContainer currentSourceFolder, String title, String message, IPath initialPath, boolean multiSelection) {
- Class[] acceptedClasses= new Class[] { IFolder.class, IFile.class };
- ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, multiSelection);
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses);
-
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new WorkbenchContentProvider();
-
- IResource initialElement= null;
- if (initialPath != null) {
- IContainer curr= currentSourceFolder;
- int nSegments= initialPath.segmentCount();
- for (int i= 0; i < nSegments; i++) {
- IResource elem= curr.findMember(initialPath.segment(i));
- if (elem != null) {
- initialElement= elem;
- }
- if (elem instanceof IContainer) {
- curr= (IContainer) elem;
- } else {
- break;
- }
- }
- }
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(shell, lp, cp);
- dialog.setTitle(title);
- dialog.setValidator(validator);
- dialog.setMessage(message);
- dialog.addFilter(filter);
- dialog.setInput(currentSourceFolder);
- dialog.setInitialSelection(initialElement);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- dialog.setHelpAvailable(false);
-
- if (dialog.open() == Window.OK) {
- Object[] objects= dialog.getResult();
- int existingSegments= currentSourceFolder.getFullPath().segmentCount();
-
- IPath[] resArr= new IPath[objects.length];
- for (int i= 0; i < objects.length; i++) {
- IResource currRes= (IResource) objects[i];
- IPath path= currRes.getFullPath().removeFirstSegments(existingSegments).makeRelative();
- if (currRes instanceof IContainer) {
- path= path.addTrailingSeparator();
- }
- resArr[i]= path;
- }
- return resArr;
- }
- return null;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/FolderSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/FolderSelectionDialog.java
deleted file mode 100644
index 4beaec4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/FolderSelectionDialog.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.NewFolderDialog;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- */
-public class FolderSelectionDialog extends ElementTreeSelectionDialog implements ISelectionChangedListener {
-
- private Button fNewFolderButton;
- private IContainer fSelectedContainer;
-
- public FolderSelectionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) {
- super(parent, labelProvider, contentProvider);
- setComparator(new ResourceComparator(ResourceComparator.NAME));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite result= (Composite)super.createDialogArea(parent);
-
- getTreeViewer().addSelectionChangedListener(this);
-
- Button button = new Button(result, SWT.PUSH);
- button.setText(NewWizardMessages.FolderSelectionDialog_button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- newFolderButtonPressed();
- }
- });
- button.setFont(parent.getFont());
- fNewFolderButton= button;
-
- applyDialogFont(result);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_SELECT_DEFAULT_OUTPUT_FOLDER_DIALOG);
-
- return result;
- }
-
- public void addFilter(ViewerFilter filter) {
- super.addFilter(filter);
- }
-
- private void updateNewFolderButtonState() {
- IStructuredSelection selection= (IStructuredSelection) getTreeViewer().getSelection();
- fSelectedContainer= null;
- if (selection.size() == 1) {
- Object first= selection.getFirstElement();
- if (first instanceof IContainer) {
- fSelectedContainer= (IContainer) first;
- }
- }
- fNewFolderButton.setEnabled(fSelectedContainer != null);
- }
-
- protected void newFolderButtonPressed() {
- NewFolderDialog dialog= new NewFolderDialog(getShell(), fSelectedContainer) {
- protected Control createContents(Composite parent) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_CREATE_NEW_FOLDER);
- return super.createContents(parent);
- }
- };
- if (dialog.open() == Window.OK) {
- TreeViewer treeViewer= getTreeViewer();
- treeViewer.refresh(fSelectedContainer);
- Object createdFolder= dialog.getResult()[0];
- treeViewer.reveal(createdFolder);
- treeViewer.setSelection(new StructuredSelection(createdFolder));
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
- */
- public void selectionChanged(SelectionChangedEvent event) {
- updateNewFolderButtonState();
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JARFileSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JARFileSelectionDialog.java
deleted file mode 100644
index ae2fa0dc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JARFileSelectionDialog.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-
-/**
- * Selection dialog to select a JAR on the file system.
- * Set input to a java.io.File that point to folder.
- */
-public class JARFileSelectionDialog extends ElementTreeSelectionDialog {
-
- /**
- * Constructor for JARFileSelectionDialog.
- * @param parent parent shell
- * @param multiSelect specifies if selecting multiple elements is allowed
- * @param acceptFolders specifies if folders can be selected as well
- */
- public JARFileSelectionDialog(Shell parent, boolean multiSelect, boolean acceptFolders) {
- super(parent, new FileLabelProvider(), new FileContentProvider());
- setComparator(new FileViewerComparator());
- addFilter(new FileArchiveFileFilter(acceptFolders));
- setValidator(new FileSelectionValidator(multiSelect, acceptFolders));
- setHelpAvailable(false);
- }
-
- private static boolean isArchive(File file) {
- String name= file.getName();
- int detIndex= name.lastIndexOf('.');
- return (detIndex != -1 && ArchiveFileFilter.isArchiveFileExtension(name.substring(detIndex + 1)));
- }
-
- private static class FileLabelProvider extends LabelProvider {
- private final Image IMG_FOLDER= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
- private final Image IMG_JAR= JavaScriptPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_EXTJAR);
-
- public Image getImage(Object element) {
- if (element instanceof File) {
- File curr= (File) element;
- if (curr.isDirectory()) {
- return IMG_FOLDER;
- } else {
- return IMG_JAR;
- }
- }
- return null;
- }
-
- public String getText(Object element) {
- if (element instanceof File) {
- return ((File) element).getName();
- }
- return super.getText(element);
- }
- }
-
- private static class FileContentProvider implements ITreeContentProvider {
-
- private final Object[] EMPTY= new Object[0];
-
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof File) {
- File[] children= ((File) parentElement).listFiles();
- if (children != null) {
- return children;
- }
- }
- return EMPTY;
- }
-
- public Object getParent(Object element) {
- if (element instanceof File) {
- return ((File) element).getParentFile();
- }
- return null;
- }
-
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- public Object[] getElements(Object element) {
- return getChildren(element);
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- }
-
- private static class FileArchiveFileFilter extends ViewerFilter {
- private final boolean fAcceptFolders;
-
- public FileArchiveFileFilter(boolean acceptFolders) {
- fAcceptFolders= acceptFolders;
- }
-
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof File) {
- File file= (File) element;
- if (file.isFile()) {
- return isArchive(file);
- } else if (fAcceptFolders) {
- return true;
- } else {
- File[] listFiles= file.listFiles();
- if (listFiles != null) {
- for (int i= 0; i < listFiles.length; i++) {
- if (select(viewer, file, listFiles[i])) {
- return true;
- }
- }
- }
- }
- }
- return false;
- }
- }
-
- private static class FileViewerComparator extends ViewerComparator {
- public int category(Object element) {
- if (element instanceof File) {
- if (((File) element).isFile()) {
- return 1;
- }
- }
- return 0;
- }
- }
-
- private static class FileSelectionValidator implements ISelectionStatusValidator {
- private boolean fMultiSelect;
- private boolean fAcceptFolders;
-
- public FileSelectionValidator(boolean multiSelect, boolean acceptFolders) {
- fMultiSelect= multiSelect;
- fAcceptFolders= acceptFolders;
- }
-
- public IStatus validate(Object[] selection) {
- int nSelected= selection.length;
- if (nSelected == 0 || (nSelected > 1 && !fMultiSelect)) {
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- }
- for (int i= 0; i < selection.length; i++) {
- Object curr= selection[i];
- if (curr instanceof File) {
- File file= (File) curr;
- if (!fAcceptFolders && !file.isFile()) {
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- }
- }
- }
- return new StatusInfo();
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocAttributeConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocAttributeConfiguration.java
deleted file mode 100644
index 9916021b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocAttributeConfiguration.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-import org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration;
-
-public class JavadocAttributeConfiguration extends ClasspathAttributeConfiguration {
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#getImageDescriptor(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public ImageDescriptor getImageDescriptor(ClasspathAttributeAccess attribute) {
- return JavaPluginImages.DESC_OBJS_JAVADOC_LOCATION_ATTRIB;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#getNameLabel(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public String getNameLabel(ClasspathAttributeAccess attribute) {
- return NewWizardMessages.CPListLabelProvider_javadoc_location_label;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#getValueLabel(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public String getValueLabel(ClasspathAttributeAccess access) {
- String arg= null;
- String str= access.getClasspathAttribute().getValue();
- if (str != null) {
- String prefix= JavaDocLocations.ARCHIVE_PREFIX;
- if (str.startsWith(prefix)) {
- int sepIndex= str.lastIndexOf("!/"); //$NON-NLS-1$
- if (sepIndex == -1) {
- arg= str.substring(prefix.length());
- } else {
- String archive= str.substring(prefix.length(), sepIndex);
- String root= str.substring(sepIndex + 2);
- if (root.length() > 0) {
- arg= Messages.format(NewWizardMessages.CPListLabelProvider_twopart, new String[] { archive, root });
- } else {
- arg= archive;
- }
- }
- } else {
- arg= str;
- }
- } else {
- arg= NewWizardMessages.CPListLabelProvider_none;
- }
- return arg;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#performEdit(org.eclipse.swt.widgets.Shell, org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public IIncludePathAttribute performEdit(Shell shell, ClasspathAttributeAccess attribute) {
- String initialLocation= attribute.getClasspathAttribute().getValue();
- String elementName= attribute.getParentClasspassEntry().getPath().lastSegment();
- try {
- URL locationURL= initialLocation != null ? new URL(initialLocation) : null;
- URL[] result= BuildPathDialogAccess.configureJavadocLocation(shell, elementName, locationURL);
- if (result != null) {
- URL newURL= result[0];
- String string= newURL != null ? newURL.toExternalForm() : null;
- return JavaScriptCore.newIncludepathAttribute(IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME, string);
- }
- } catch (MalformedURLException e) {
- // todo
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#performRemove(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public IIncludePathAttribute performRemove(ClasspathAttributeAccess attribute) {
- return JavaScriptCore.newIncludepathAttribute(IIncludePathAttribute.JSDOC_LOCATION_ATTRIBUTE_NAME, null);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#canEdit(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public boolean canEdit(ClasspathAttributeAccess attribute) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration#canRemove(org.eclipse.wst.jsdt.ui.wizards.ClasspathAttributeConfiguration.ClasspathAttributeAccess)
- */
- public boolean canRemove(ClasspathAttributeAccess attribute) {
- return attribute.getClasspathAttribute().getValue() != null;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocLocationDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocLocationDialog.java
deleted file mode 100644
index 80701b09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JavadocLocationDialog.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.net.URL;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavadocConfigurationBlock;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * Dialog to configure a Javadoc location
- */
-public class JavadocLocationDialog extends StatusDialog {
-
- private JavadocConfigurationBlock fJavadocConfigurationBlock;
-
- /**
- * Shows the UI for configuring a javadoc location.
- * Use {@link org.eclipse.wst.jsdt.ui.JavaScriptUI} to access and configure Javadoc locations.
- *
- * @param parent The parent shell for the dialog.
- * @param libraryName Name of of the library to which configured javadoc location belongs.
- * @param initialURL The initial URL or <code>null</code>.
- */
- public JavadocLocationDialog(Shell parent, String libraryName, URL initialURL) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- IStatusChangeListener listener= new IStatusChangeListener() {
- public void statusChanged(IStatus status) {
- updateStatus(status);
- }
- };
-
- setTitle(Messages.format(NewWizardMessages.LibrariesWorkbookPage_JavadocPropertyDialog_title, libraryName));
- fJavadocConfigurationBlock= new JavadocConfigurationBlock(parent, listener, initialURL, false);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
- Control inner= fJavadocConfigurationBlock.createContents(composite);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- applyDialogFont(composite);
- return composite;
- }
-
- /**
- * Returns the configured Javadoc location. The result is only valid after the dialog
- * has been opened and has not been cancelled by the user.
- * @return The configured javadoc location
- */
- public URL getResult() {
- return fJavadocConfigurationBlock.getJavadocLocation();
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDefaultPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDefaultPage.java
deleted file mode 100644
index ea31045f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDefaultPage.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-/**
- */
-public class JsGlobalScopeContainerDefaultPage extends NewElementWizardPage implements IJsGlobalScopeContainerPage, IJsGlobalScopeContainerPageExtension {
-
- private StringDialogField fEntryField;
- private ArrayList fUsedPaths;
-
- /**
- * Constructor for JsGlobalScopeContainerDefaultPage.
- */
- public JsGlobalScopeContainerDefaultPage() {
- super("JsGlobalScopeContainerDefaultPage"); //$NON-NLS-1$
- setTitle(NewWizardMessages.JsGlobalScopeContainerDefaultPage_title);
- setDescription(NewWizardMessages.JsGlobalScopeContainerDefaultPage_description);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY);
-
- fUsedPaths= new ArrayList();
-
- fEntryField= new StringDialogField();
- fEntryField.setLabelText(NewWizardMessages.JsGlobalScopeContainerDefaultPage_path_label);
- fEntryField.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- validatePath();
- }
- });
- validatePath();
- }
-
- private void validatePath() {
- StatusInfo status= new StatusInfo();
- String str= fEntryField.getText();
- if (str.length() == 0) {
- status.setError(NewWizardMessages.JsGlobalScopeContainerDefaultPage_path_error_enterpath);
- } else if (!Path.ROOT.isValidPath(str)) {
- status.setError(NewWizardMessages.JsGlobalScopeContainerDefaultPage_path_error_invalidpath);
- } else {
- IPath path= new Path(str);
- if (path.segmentCount() == 0) {
- status.setError(NewWizardMessages.JsGlobalScopeContainerDefaultPage_path_error_needssegment);
- } else if (fUsedPaths.contains(path)) {
- status.setError(NewWizardMessages.JsGlobalScopeContainerDefaultPage_path_error_alreadyexists);
- }
- }
- updateStatus(status);
- }
-
- /* (non-Javadoc)
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.numColumns= 1;
- composite.setLayout(layout);
-
- fEntryField.doFillIntoGrid(composite, 2);
- LayoutUtil.setHorizontalGrabbing(fEntryField.getTextControl(null));
-
- fEntryField.setFocus();
-
- setControl(composite);
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.CLASSPATH_CONTAINER_DEFAULT_PAGE);
- }
-
- /* (non-Javadoc)
- * @see IJsGlobalScopeContainerPage#finish()
- */
- public boolean finish() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IJsGlobalScopeContainerPage#getSelection()
- */
- public IIncludePathEntry getSelection() {
- return JavaScriptCore.newContainerEntry(new Path(fEntryField.getText()));
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension#initialize(org.eclipse.wst.jsdt.core.IJavaScriptProject, org.eclipse.wst.jsdt.core.IIncludePathEntry)
- */
- public void initialize(IJavaScriptProject project, IIncludePathEntry[] currentEntries) {
- for (int i= 0; i < currentEntries.length; i++) {
- IIncludePathEntry curr= currentEntries[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- fUsedPaths.add(curr.getPath());
- }
- }
- }
-
- /* (non-Javadoc)
- * @see IJsGlobalScopeContainerPage#setSelection(IIncludePathEntry)
- */
- public void setSelection(IIncludePathEntry containerEntry) {
- if (containerEntry != null) {
- fUsedPaths.remove(containerEntry.getPath());
- fEntryField.setText(containerEntry.getPath().toString());
- } else {
- fEntryField.setText(""); //$NON-NLS-1$
- }
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDescriptor.java
deleted file mode 100644
index 7c1d41e9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerDescriptor.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.CoreUtility;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage;
-
-/**
- */
-public class JsGlobalScopeContainerDescriptor {
-
- private IConfigurationElement fConfigElement;
- private IJsGlobalScopeContainerPage fPage;
-
- private static final String ATT_EXTENSION = "JsGlobalScopeContainerPage"; //$NON-NLS-1$
-
- private static final String ATT_ID = "id"; //$NON-NLS-1$
- private static final String ATT_NAME = "name"; //$NON-NLS-1$
- private static final String ATT_PAGE_CLASS = "class"; //$NON-NLS-1$
-
- public JsGlobalScopeContainerDescriptor(IConfigurationElement configElement) throws CoreException {
- super();
- fConfigElement = configElement;
- fPage= null;
-
- String id = fConfigElement.getAttribute(ATT_ID);
- String name = configElement.getAttribute(ATT_NAME);
- String pageClassName = configElement.getAttribute(ATT_PAGE_CLASS);
-
- if (name == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (missing name): " + id, null)); //$NON-NLS-1$
- }
- if (pageClassName == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (missing page class name): " + id, null)); //$NON-NLS-1$
- }
- }
-
- public IJsGlobalScopeContainerPage createPage() throws CoreException {
- if (fPage == null) {
- Object elem= CoreUtility.createExtension(fConfigElement, ATT_PAGE_CLASS);
- if (elem instanceof IJsGlobalScopeContainerPage) {
- fPage= (IJsGlobalScopeContainerPage) elem;
- } else {
- String id= fConfigElement.getAttribute(ATT_ID);
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, 0, "Invalid extension (page not of type IJsGlobalScopeContainerPage): " + id, null)); //$NON-NLS-1$
- }
- }
- return fPage;
- }
-
- public IJsGlobalScopeContainerPage getPage() {
- return fPage;
- }
-
- public void setPage(IJsGlobalScopeContainerPage page) {
- fPage= page;
- }
-
- public void dispose() {
- if (fPage != null) {
- fPage.dispose();
- fPage= null;
- }
- }
-
- public String getName() {
- return fConfigElement.getAttribute(ATT_NAME);
- }
-
- public String getPageClass() {
- return fConfigElement.getAttribute(ATT_PAGE_CLASS);
- }
-
- public boolean canEdit(IIncludePathEntry entry) {
- String id = fConfigElement.getAttribute(ATT_ID);
- if (entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- String type = entry.getPath().segment(0);
- return id.equals(type);
- }
- return false;
- }
-
- public static JsGlobalScopeContainerDescriptor[] getDescriptors() {
- ArrayList containers= new ArrayList();
-
- IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(JavaScriptUI.ID_PLUGIN, ATT_EXTENSION);
- if (extensionPoint != null) {
- JsGlobalScopeContainerDescriptor defaultPage= null;
- String defaultPageName= JsGlobalScopeContainerDefaultPage.class.getName();
-
- IConfigurationElement[] elements = extensionPoint.getConfigurationElements();
- for (int i = 0; i < elements.length; i++) {
- try {
- JsGlobalScopeContainerDescriptor curr= new JsGlobalScopeContainerDescriptor(elements[i]);
- if (defaultPageName.equals(curr.getPageClass())) {
- defaultPage= curr;
- } else {
- containers.add(curr);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- if (defaultPageName != null && containers.isEmpty()) {
- // default page only added of no other extensions found
- containers.add(defaultPage);
- }
- }
- return (JsGlobalScopeContainerDescriptor[]) containers.toArray(new JsGlobalScopeContainerDescriptor[containers.size()]);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java
deleted file mode 100644
index f2cc53ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.Arrays;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ListViewer;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.util.SelectionUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * The first page of the Add JavaScript Library wizard.
- */
-public class JsGlobalScopeContainerSelectionPage extends WizardPage {
-
- /**
- * A label provider for the wizard page
- */
- private static class JsGlobalScopeContainerLabelProvider extends LabelProvider {
- public String getText(Object element) {
- return ((JsGlobalScopeContainerDescriptor) element).getName();
- }
- }
-
- private static final String DIALOGSTORE_SECTION= "JsGlobalScopeContainerSelectionPage"; //$NON-NLS-1$
- private static final String DIALOGSTORE_CONTAINER_IDX= "index"; //$NON-NLS-1$
-
- private JsGlobalScopeContainerDescriptor[] fContainers;
-
- private ListViewer fListViewer;
- private IDialogSettings fDialogSettings;
-
- /**
- * Constructor for JsGlobalScopeContainerWizardPage.
- * @param containerPages
- */
- protected JsGlobalScopeContainerSelectionPage(JsGlobalScopeContainerDescriptor[] containerPages) {
- super("JsGlobalScopeContainerWizardPage"); //$NON-NLS-1$
- setTitle(NewWizardMessages.JsGlobalScopeContainerSelectionPage_title);
- setDescription(NewWizardMessages.JsGlobalScopeContainerSelectionPage_description);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY);
-
- fContainers= containerPages;
-
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings();
- fDialogSettings= settings.getSection(DIALOGSTORE_SECTION);
- if (fDialogSettings == null) {
- fDialogSettings= settings.addNewSection(DIALOGSTORE_SECTION);
- fDialogSettings.put(DIALOGSTORE_CONTAINER_IDX, 0);
- }
- }
-
- /* (non-Javadoc)
- * @see IDialogPage#createControl(Composite)
- */
- public void createControl(Composite parent) {
- fListViewer= new ListViewer(parent, SWT.SINGLE | SWT.BORDER);
- fListViewer.setLabelProvider(new JsGlobalScopeContainerLabelProvider());
- fListViewer.setContentProvider(new ArrayContentProvider());
- fListViewer.setComparator(new ViewerComparator());
- fListViewer.setInput(Arrays.asList(fContainers));
- fListViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- if(canFlipToNextPage())
- getNextPage();
- validatePage();
- }
- });
- fListViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- doDoubleClick();
- }
- });
-
- int selectionIndex= fDialogSettings.getInt(DIALOGSTORE_CONTAINER_IDX);
- if (selectionIndex >= fContainers.length) {
- selectionIndex= 0;
- }
- fListViewer.getList().select(selectionIndex);
- if(canFlipToNextPage())
- getNextPage();
- validatePage();
- setControl(fListViewer.getList());
- Dialog.applyDialogFont(fListViewer.getList());
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IJavaHelpContextIds.BP_SELECT_CLASSPATH_CONTAINER);
- }
-
- /**
- * Method validatePage.
- */
- private void validatePage() {
- setPageComplete(getSelected() != null);
- }
-
-
- public JsGlobalScopeContainerDescriptor getSelected() {
- if (fListViewer != null) {
- ISelection selection= fListViewer.getSelection();
- return (JsGlobalScopeContainerDescriptor) SelectionUtil.getSingleElement(selection);
- }
- return null;
- }
-
- public JsGlobalScopeContainerDescriptor[] getContainers() {
- return fContainers;
- }
-
- protected void doDoubleClick() {
- if (canFlipToNextPage()) {
- getContainer().showPage(getNextPage());
- }
- }
-
- /* (non-Javadoc)
- * @see IWizardPage#canFlipToNextPage()
- */
- public boolean canFlipToNextPage() {
- return isPageComplete(); // avoid the getNextPage call to prevent potential plugin load
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
- */
- public void setVisible(boolean visible) {
- if (!visible && fListViewer != null) {
- fDialogSettings.put(DIALOGSTORE_CONTAINER_IDX, fListViewer.getList().getSelectionIndex());
- }
- super.setVisible(visible);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerWizard.java
deleted file mode 100644
index 438185ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerWizard.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension2;
-
-/**
- * This wizard is used to add/edit JavaScript libraries to a JavaScript project.
- */
-public class JsGlobalScopeContainerWizard extends Wizard {
-
- private IJavaScriptProject fCurrProject;
-
- private IIncludePathEntry fEntryToEdit;
- private IIncludePathEntry[] fNewEntries;
- private IIncludePathEntry[] fCurrClasspath;
-
- private JsGlobalScopeContainerSelectionPage fSelectionWizardPage;
- private IJsGlobalScopeContainerPage fContainerPage;
-
- /**
- * Constructor for JsGlobalScopeContainerWizard.
- * @param entryToEdit entry to edit
- * @param currProject current project
- * @param currEntries entries currently in classpath
- */
- public JsGlobalScopeContainerWizard(IIncludePathEntry entryToEdit, IJavaScriptProject currProject, IIncludePathEntry[] currEntries) {
- fCurrProject= currProject;
-
- fEntryToEdit= entryToEdit;
- fNewEntries= null;
- fCurrClasspath= currEntries;
-
- if (entryToEdit == null) {
- setWindowTitle(NewWizardMessages.JsGlobalScopeContainerWizard_new_title);
- } else {
- setWindowTitle(NewWizardMessages.JsGlobalScopeContainerWizard_edit_title);
- }
- }
-
- /**
- * Return an array of new include path entries
- * @return
- */
- public IIncludePathEntry[] getNewEntries() {
- return fNewEntries;
- }
-
- /* (non-Javadoc)
- * @see IWizard#performFinish()
- */
- public boolean performFinish() {
- if (fContainerPage != null) {
- if (fContainerPage.finish()) {
- if (fEntryToEdit == null && fContainerPage instanceof IJsGlobalScopeContainerPageExtension2) {
- fNewEntries= ((IJsGlobalScopeContainerPageExtension2) fContainerPage).getNewContainers();
- } else {
- IIncludePathEntry entry= fContainerPage.getSelection();
- fNewEntries= (entry != null) ? new IIncludePathEntry[] { entry } : null;
- }
- return true;
- }
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see IWizard#addPages()
- */
- public void addPages() {
- if (fEntryToEdit == null) { // new entry: show selection page as first page
- JsGlobalScopeContainerDescriptor[] containers= JsGlobalScopeContainerDescriptor.getDescriptors();
-
- fSelectionWizardPage= new JsGlobalScopeContainerSelectionPage(containers);
- addPage(fSelectionWizardPage);
-
- // add as dummy, will not be shown
- fContainerPage= new JsGlobalScopeContainerDefaultPage();
- addPage(fContainerPage);
- } else { // fPageDesc == null && fEntryToEdit != null
- JsGlobalScopeContainerDescriptor[] containers= JsGlobalScopeContainerDescriptor.getDescriptors();
- JsGlobalScopeContainerDescriptor descriptor= findDescriptorPage(containers, fEntryToEdit);
- fContainerPage= getContainerPage(descriptor);
- addPage(fContainerPage);
- }
- super.addPages();
- }
-
- private IJsGlobalScopeContainerPage getContainerPage(JsGlobalScopeContainerDescriptor pageDesc) {
- IJsGlobalScopeContainerPage containerPage= null;
- if (pageDesc != null) {
- IJsGlobalScopeContainerPage page= pageDesc.getPage();
- if (page != null) {
- return page; // if page is already created, avoid double initialization
- }
- try {
- containerPage= pageDesc.createPage();
- } catch (CoreException e) {
- handlePageCreationFailed(e);
- }
- }
-
- if (containerPage == null) {
- containerPage= new JsGlobalScopeContainerDefaultPage();
- if (pageDesc != null) {
- pageDesc.setPage(containerPage); // avoid creation next time
- }
- }
-
- if (containerPage instanceof IJsGlobalScopeContainerPageExtension) {
- ((IJsGlobalScopeContainerPageExtension) containerPage).initialize(fCurrProject, fCurrClasspath);
- }
-
- containerPage.setSelection(fEntryToEdit);
- containerPage.setWizard(this);
- return containerPage;
- }
-
- /* (non-Javadoc)
- * @see IWizard#getNextPage(IWizardPage)
- */
- public IWizardPage getNextPage(IWizardPage page) {
- if (page == fSelectionWizardPage) {
-
- JsGlobalScopeContainerDescriptor selected= fSelectionWizardPage.getSelected();
- fContainerPage= getContainerPage(selected);
-
- return fContainerPage;
- }
- return super.getNextPage(page);
- }
-
- private void handlePageCreationFailed(CoreException e) {
- String title= NewWizardMessages.JsGlobalScopeContainerWizard_pagecreationerror_title;
- String message= NewWizardMessages.JsGlobalScopeContainerWizard_pagecreationerror_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- }
-
-
- private JsGlobalScopeContainerDescriptor findDescriptorPage(JsGlobalScopeContainerDescriptor[] containers, IIncludePathEntry entry) {
- for (int i = 0; i < containers.length; i++) {
- if (containers[i].canEdit(entry)) {
- return containers[i];
- }
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.wizard.Wizard#dispose()
- */
- public void dispose() {
- if (fSelectionWizardPage != null) {
- JsGlobalScopeContainerDescriptor[] descriptors= fSelectionWizardPage.getContainers();
- for (int i= 0; i < descriptors.length; i++) {
- descriptors[i].dispose();
- }
- }
- super.dispose();
- }
-
- /* (non-Javadoc)
- * @see IWizard#canFinish()
- */
- public boolean canFinish() {
- return fContainerPage.isPageComplete();
- }
-
- public static int openWizard(Shell shell, JsGlobalScopeContainerWizard wizard) {
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- return dialog.open();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
deleted file mode 100644
index 9ab1415f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
+++ /dev/null
@@ -1,863 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.TreeListDialogField;
-import org.eclipse.wst.jsdt.launching.JavaRuntime;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-public class LibrariesWorkbookPage extends BuildPathBasePage {
-
- private ListDialogField fClassPathList;
- private IJavaScriptProject fCurrJProject;
-
- private TreeListDialogField fLibrariesList;
-
- private Control fSWTControl;
- private final IWorkbenchPreferenceContainer fPageContainer;
-
- //private final int IDX_ADDJAR= 0;
- //private final int IDX_ADDEXT= 1;
- //private final int IDX_ADDVAR= 2;
- private final int IDX_ADDLIB= 0;
- private final int IDX_ADDFOL= 1;
-
- private final int IDX_EDIT= 3;
- private final int IDX_REMOVE= 4;
-
- //private final int IDX_REPLACE= 9;
-
- public LibrariesWorkbookPage(CheckedListDialogField classPathList, IWorkbenchPreferenceContainer pageContainer) {
- fClassPathList= classPathList;
- fPageContainer= pageContainer;
- fSWTControl= null;
-
- String[] buttonLabels= new String[] {
- //NewWizardMessages.LibrariesWorkbookPage_libraries_addjar_button,
- //NewWizardMessages.LibrariesWorkbookPage_libraries_addextjar_button,
- //NewWizardMessages.LibrariesWorkbookPage_libraries_addvariable_button,
- NewWizardMessages.LibrariesWorkbookPage_libraries_addlibrary_button,
- NewWizardMessages.LibrariesWorkbookPage_libraries_addclassfolder_button,
- /* */ null,
- NewWizardMessages.LibrariesWorkbookPage_libraries_edit_button,
- NewWizardMessages.LibrariesWorkbookPage_libraries_remove_button,
- /* */
- //NewWizardMessages.LibrariesWorkbookPage_libraries_replace_button
- };
-
- LibrariesAdapter adapter= new LibrariesAdapter();
-
- fLibrariesList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fLibrariesList.setDialogFieldListener(adapter);
- fLibrariesList.setLabelText(NewWizardMessages.LibrariesWorkbookPage_libraries_label);
- fLibrariesList.enableButton(IDX_EDIT, false);
- fLibrariesList.enableButton(IDX_REMOVE, false);
-
- //fLibrariesList.enableButton(IDX_REPLACE, false);
-
- fLibrariesList.setViewerComparator(new CPListElementSorter());
-
- }
-
- public void init(IJavaScriptProject jproject) {
- fCurrJProject= jproject;
- if (Display.getCurrent() != null) {
- updateLibrariesList();
- } else {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- updateLibrariesList();
- }
- });
- }
- }
-
- private void updateLibrariesList() {
- List cpelements= fClassPathList.getElements();
- List libelements= new ArrayList(cpelements.size());
-
- int nElements= cpelements.size();
- for (int i= 0; i < nElements; i++) {
- CPListElement cpe= (CPListElement)cpelements.get(i);
- if (isEntryKind(cpe.getEntryKind())) {
- libelements.add(cpe);
- }
- }
- fLibrariesList.setElements(libelements);
- }
-
- // -------- UI creation
-
- public Control getControl(Composite parent) {
- PixelConverter converter= new PixelConverter(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
-
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fLibrariesList.getTreeControl(null));
-
- int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
- fLibrariesList.setButtonsMinWidth(buttonBarWidth);
-
- fLibrariesList.setViewerComparator(new CPListElementSorter());
-
- fSWTControl= composite;
-
- return composite;
- }
-
- private Shell getShell() {
- if (fSWTControl != null) {
- return fSWTControl.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
-
- private class LibrariesAdapter implements IDialogFieldListener, ITreeListAdapter {
-
- private final Object[] EMPTY_ARR= new Object[0];
-
- // -------- IListAdapter --------
- public void customButtonPressed(TreeListDialogField field, int index) {
- libaryPageCustomButtonPressed(field, index);
- }
-
- public void selectionChanged(TreeListDialogField field) {
- libaryPageSelectionChanged(field);
- }
-
- public void doubleClicked(TreeListDialogField field) {
- libaryPageDoubleClicked(field);
- }
-
- public void keyPressed(TreeListDialogField field, KeyEvent event) {
- libaryPageKeyPressed(field, event);
- }
-
- public Object[] getChildren(TreeListDialogField field, Object element) {
- if (element instanceof CPListElement) {
- return ((CPListElement) element).getChildren();
- } else if (element instanceof CPListElementAttribute) {
- CPListElementAttribute attribute= (CPListElementAttribute) element;
- if (CPListElement.ACCESSRULES.equals(attribute.getKey())) {
- return (IAccessRule[]) attribute.getValue();
- }
- }
- return EMPTY_ARR;
- }
-
- public Object getParent(TreeListDialogField field, Object element) {
- if (element instanceof CPListElementAttribute) {
- return ((CPListElementAttribute) element).getParent();
- }
- return null;
- }
-
- public boolean hasChildren(TreeListDialogField field, Object element) {
- return getChildren(field, element).length > 0;
- }
-
- // ---------- IDialogFieldListener --------
-
- public void dialogFieldChanged(DialogField field) {
- libaryPageDialogFieldChanged(field);
- }
- }
-
- private void libaryPageCustomButtonPressed(DialogField field, int index) {
- CPListElement[] libentries= null;
- switch (index) {
-// case IDX_ADDJAR: /* add jar */
-// libentries= openJarFileDialog(null);
-// break;
-// case IDX_ADDEXT: /* add external jar */
-// libentries= openExtJarFileDialog(null);
-// break;
-// case IDX_ADDVAR: /* add variable */
-// libentries= openVariableSelectionDialog(null);
-// break;
- case IDX_ADDLIB: /* add library */
- libentries= openContainerSelectionDialog(null);
- break;
- case IDX_ADDFOL: /* add folder */
- libentries= openClassFolderDialog(null);
- break;
- case IDX_EDIT: /* edit */
- editEntry();
- return;
- case IDX_REMOVE: /* remove */
- removeEntry();
- return;
-// case IDX_REPLACE: /* replace */
-// replaceJarFile();
-// return;
- }
- if (libentries != null) {
- int nElementsChosen= libentries.length;
- // remove duplicates
- List cplist= fLibrariesList.getElements();
- List elementsToAdd= new ArrayList(nElementsChosen);
-
- for (int i= 0; i < nElementsChosen; i++) {
- CPListElement curr= libentries[i];
- if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
- elementsToAdd.add(curr);
- curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport.guessJavadocLocation(curr));
- }
- }
-// if (!elementsToAdd.isEmpty() && (index == IDX_ADDFOL)) {
-// askForAddingExclusionPatternsDialog(elementsToAdd);
-// }
-
- fLibrariesList.addElements(elementsToAdd);
- // || index == IDX_ADDVAR
- if (index == IDX_ADDLIB ) {
- fLibrariesList.refresh();
- }
- fLibrariesList.postSetSelection(new StructuredSelection(libentries));
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#addElement(org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement)
- */
- public void addElement(CPListElement element) {
- fLibrariesList.addElement(element);
- fLibrariesList.postSetSelection(new StructuredSelection(element));
- }
-
-// private void askForAddingExclusionPatternsDialog(List newEntries) {
-// HashSet modified= new HashSet();
-// List existing= fClassPathList.getElements();
-// fixNestingConflicts((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]), (CPListElement[])existing.toArray(new CPListElement[existing.size()]), modified);
-// if (!modified.isEmpty()) {
-// String title= NewWizardMessages.LibrariesWorkbookPage_exclusion_added_title;
-// String message= NewWizardMessages.LibrariesWorkbookPage_exclusion_added_message;
-// MessageDialog.openInformation(getShell(), title, message);
-// }
-// }
-
- protected void libaryPageDoubleClicked(TreeListDialogField field) {
- List selection= fLibrariesList.getSelectedElements();
- if (canEdit(selection)) {
- editEntry();
- }
- }
-
- protected void libaryPageKeyPressed(TreeListDialogField field, KeyEvent event) {
- if (field == fLibrariesList) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- List selection= field.getSelectedElements();
- if (canRemove(selection)) {
- removeEntry();
- }
- }
- }
- }
-
-// private void replaceJarFile() {
-// final IPackageFragmentRoot root= getSelectedPackageFragmentRoot();
-// if (root != null) {
-// final IImportWizard wizard= new JarImportWizard(false);
-// wizard.init(PlatformUI.getWorkbench(), new StructuredSelection(root));
-// final WizardDialog dialog= new WizardDialog(getShell(), wizard);
-// dialog.create();
-// dialog.getShell().setSize(Math.max(JarImportWizardAction.SIZING_WIZARD_WIDTH, dialog.getShell().getSize().x), JarImportWizardAction.SIZING_WIZARD_HEIGHT);
-// PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IJavaHelpContextIds.JARIMPORT_WIZARD_PAGE);
-// dialog.open();
-// }
-// }
-
-// private IPackageFragmentRoot getSelectedPackageFragmentRoot() {
-// final List elements= fLibrariesList.getSelectedElements();
-// if (elements.size() == 1) {
-// final Object object= elements.get(0);
-// if (object instanceof CPListElement) {
-// final CPListElement element= (CPListElement) object;
-// final IIncludePathEntry entry= element.getClasspathEntry();
-// if (JarImportWizard.isValidClassPathEntry(entry)) {
-// final IJavaScriptProject project= element.getJavaProject();
-// if (project != null) {
-// try {
-// final IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
-// for (int index= 0; index < roots.length; index++) {
-// if (entry.equals(roots[index].getRawClasspathEntry()))
-// return roots[index];
-// }
-// } catch (JavaScriptModelException exception) {
-// JavaScriptPlugin.log(exception);
-// }
-// }
-// }
-// }
-// }
-// return null;
-// }
-
- private void removeEntry() {
- List selElements= fLibrariesList.getSelectedElements();
- HashMap containerEntriesToUpdate= new HashMap();
- for (int i= selElements.size() - 1; i >= 0 ; i--) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- String key= attrib.getKey();
- if (attrib.isBuiltIn()) {
- Object value= null;
- if (key.equals(CPListElement.ACCESSRULES)) {
- value= new IAccessRule[0];
- }
- attrib.setValue(value);
- }else {
- removeCustomAttribute(attrib);
- }
- selElements.remove(i);
- if (attrib.getParent().getParentContainer() instanceof CPListElement) { // inside a container: apply changes right away
- CPListElement containerEntry= attrib.getParent();
- HashSet changedAttributes= (HashSet) containerEntriesToUpdate.get(containerEntry);
- if (changedAttributes == null) {
- changedAttributes= new HashSet();
- containerEntriesToUpdate.put(containerEntry, changedAttributes);
- }
- changedAttributes.add(key); // collect the changed attributes
- }
- }else if(elem instanceof CPListElement) {
- CPListElement listElem = (CPListElement)elem;
- if (listElem.getEntryKind()==IIncludePathEntry.CPE_CONTAINER)
- {
- JsGlobalScopeContainerInitializer init = listElem.getContainerInitializer();
- init.removeFromProject(fCurrJProject);
- }
-
-
- }
-
- }
- if (selElements.isEmpty()) {
- fLibrariesList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
- } else {
- fLibrariesList.removeElements(selElements);
- }
- for (Iterator iter= containerEntriesToUpdate.entrySet().iterator(); iter.hasNext();) {
- Map.Entry entry= (Entry) iter.next();
- CPListElement curr= (CPListElement) entry.getKey();
- HashSet attribs= (HashSet) entry.getValue();
- String[] changedAttributes= (String[]) attribs.toArray(new String[attribs.size()]);
- IIncludePathEntry changedEntry= curr.getClasspathEntry();
- updateContainerEntry(changedEntry, changedAttributes, fCurrJProject, ((CPListElement) curr.getParentContainer()).getPath());
- }
- }
-
- private boolean canRemove(List selElements) {
- if (selElements.size() == 0) {
- return false;
- }
- for (int i= 0; i < selElements.size(); i++) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isNonModifiable()) {
- return false;
- }
- if (attrib.isBuiltIn()) {
- if (attrib.getParent().isInContainer(JavaRuntime.JRE_CONTAINER) && CPListElement.ACCESSRULES.equals(attrib.getKey())) {
- return false; // workaround for 166519 until we have full story
- }
- if (attrib.getKey().equals(CPListElement.ACCESSRULES)) {
- return ((IAccessRule[]) attrib.getValue()).length > 0;
- }
- if (attrib.getValue() == null) {
- return false;
- }
- } else {
- if (!canRemoveCustomAttribute(attrib)) {
- return false;
- }
- }
- } else if (elem instanceof CPListElement) {
- CPListElement curr= (CPListElement) elem;
- if (curr.getEntryKind()==IIncludePathEntry.CPE_CONTAINER)
- return !curr.isInNonModifiableContainer();
- if (curr.getParentContainer() != null) {
- return false;
- }
- } else { // unknown element
- return false;
- }
- }
- return true;
- }
-
- /**
- * Method editEntry.
- */
- private void editEntry() {
- List selElements= fLibrariesList.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- Object elem= selElements.get(0);
- if (fLibrariesList.getIndexOfElement(elem) != -1) {
- editElementEntry((CPListElement) elem);
- } else if (elem instanceof CPListElementAttribute) {
- editAttributeEntry((CPListElementAttribute) elem);
- }
- }
-
- private void editAttributeEntry(CPListElementAttribute elem) {
- String key= elem.getKey();
- CPListElement selElement= elem.getParent();
-
- if (key.equals(CPListElement.ACCESSRULES)) {
- AccessRulesDialog dialog= new AccessRulesDialog(getShell(), selElement, fCurrJProject, fPageContainer != null);
- int res= dialog.open();
- if (res == Window.OK || res == AccessRulesDialog.SWITCH_PAGE) {
- selElement.setAttribute(CPListElement.ACCESSRULES, dialog.getAccessRules());
- String[] changedAttributes= { CPListElement.ACCESSRULES };
- attributeUpdated(selElement, changedAttributes);
-
- fLibrariesList.refresh(elem);
- fClassPathList.dialogFieldChanged(); // validate
- updateEnabledState();
-
- if (res == AccessRulesDialog.SWITCH_PAGE) { // switch after updates and validation
- dialog.performPageSwitch(fPageContainer);
- }
- }
- } else {
- if (editCustomAttribute(getShell(), elem)) {
- String[] changedAttributes= { key };
- attributeUpdated(selElement, changedAttributes);
- fLibrariesList.refresh(elem);
- fClassPathList.dialogFieldChanged(); // validate
- updateEnabledState();
- }
- }
- }
-
- private void attributeUpdated(CPListElement selElement, String[] changedAttributes) {
- Object parentContainer= selElement.getParentContainer();
- if (parentContainer instanceof CPListElement) { // inside a container: apply changes right away
- IIncludePathEntry updatedEntry= selElement.getClasspathEntry();
- updateContainerEntry(updatedEntry, changedAttributes, fCurrJProject, ((CPListElement) parentContainer).getPath());
- }
- }
-
- private void updateContainerEntry(final IIncludePathEntry newEntry, final String[] changedAttributes, final IJavaScriptProject jproject, final IPath containerPath) {
- try {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- BuildPathSupport.modifyClasspathEntry(null, newEntry, changedAttributes, jproject, containerPath, monitor);
- }
- };
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(runnable));
-
- } catch (InvocationTargetException e) {
- String title= NewWizardMessages.LibrariesWorkbookPage_configurecontainer_error_title;
- String message= NewWizardMessages.LibrariesWorkbookPage_configurecontainer_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- } catch (InterruptedException e) {
- //
- }
- }
-
- private void editElementEntry(CPListElement elem) {
- CPListElement[] res= null;
-
- switch (elem.getEntryKind()) {
- case IIncludePathEntry.CPE_CONTAINER:
- res= openContainerSelectionDialog(elem);
- break;
- case IIncludePathEntry.CPE_LIBRARY:
- IResource resource= elem.getResource();
-// if (resource == null) {
-// res= openExtJarFileDialog(elem);
-// } else
- if (resource.getType() == IResource.FOLDER) {
- if (resource.exists()) {
- res= openClassFolderDialog(elem);
- } else {
- //res= openNewClassFolderDialog(elem);
- }
-// } else if (resource.getType() == IResource.FILE) {
-// res= openJarFileDialog(elem);
- }
- break;
-// case IIncludePathEntry.CPE_VARIABLE:
-// res= openVariableSelectionDialog(elem);
-// break;
- }
- if (res != null && res.length > 0) {
- CPListElement curr= res[0];
- curr.setExported(elem.isExported());
- curr.setAttributesFromExisting(elem);
- fLibrariesList.replaceElement(elem, curr);
- if (elem.getEntryKind() == IIncludePathEntry.CPE_VARIABLE) {
- fLibrariesList.refresh();
- }
- }
-
- }
-
- private void libaryPageSelectionChanged(DialogField field) {
- updateEnabledState();
- }
-
- private void updateEnabledState() {
- List selElements= fLibrariesList.getSelectedElements();
- fLibrariesList.enableButton(IDX_EDIT, canEdit(selElements));
- fLibrariesList.enableButton(IDX_REMOVE, canRemove(selElements));
- //fLibrariesList.enableButton(IDX_REPLACE, getSelectedPackageFragmentRoot() != null);
-
- boolean noAttributes= containsOnlyTopLevelEntries(selElements);
- //fLibrariesList.enableButton(IDX_ADDEXT, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDFOL, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDJAR, noAttributes);
- fLibrariesList.enableButton(IDX_ADDLIB, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDVAR, noAttributes);
- }
-
- private boolean canEdit(List selElements) {
- if (selElements.size() != 1) {
- return false;
- }
- Object elem= selElements.get(0);
- if (elem instanceof CPListElement) {
- CPListElement curr= (CPListElement) elem;
- if (curr.getEntryKind()==IIncludePathEntry.CPE_CONTAINER)
- return !curr.isInNonModifiableContainer();
- return !(curr.getResource() instanceof IFolder) && curr.getParentContainer() == null;
- }
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
-// if (attrib.isInNonModifiableContainer()) {
-// return false;
-// }
-
-
-// if (attrib.getParent().isInContainer(JavaRuntime.JRE_CONTAINER) && CPListElement.ACCESSRULES.equals(attrib.getKey())) {
-// return false; // workaround for 166519 until we have full story
-// }
-//
-// if(CPListElement.ACCESSRULES.equals(attrib.getKey()){
-// return true;
-// }
-
- if (!attrib.isBuiltIn()) {
- return canEditCustomAttribute(attrib);
- }
- return true;
- }
- return false;
- }
-
- private void libaryPageDialogFieldChanged(DialogField field) {
- if (fCurrJProject != null) {
- // already initialized
- updateClasspathList();
- }
- }
-
- private void updateClasspathList() {
- List projelements= fLibrariesList.getElements();
-
- List cpelements= fClassPathList.getElements();
- int nEntries= cpelements.size();
- // backwards, as entries will be deleted
- int lastRemovePos= nEntries;
- for (int i= nEntries - 1; i >= 0; i--) {
- CPListElement cpe= (CPListElement)cpelements.get(i);
- int kind= cpe.getEntryKind();
- if (isEntryKind(kind)) {
- if (!projelements.remove(cpe)) {
- cpelements.remove(i);
- lastRemovePos= i;
- }
- }
- }
-
- cpelements.addAll(lastRemovePos, projelements);
-
- if (lastRemovePos != nEntries || !projelements.isEmpty()) {
- fClassPathList.setElements(cpelements);
- }
- }
-
-
-// private CPListElement[] openNewClassFolderDialog(CPListElement existing) {
-// String title= (existing == null) ? NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_new_title : NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_edit_title;
-// IProject currProject= fCurrJProject.getProject();
-//
-// NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing);
-// IPath projpath= currProject.getFullPath();
-// dialog.setMessage(Messages.format(NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_description, projpath.toString()));
-// if (dialog.open() == Window.OK) {
-// IFolder folder= dialog.getFolder();
-// return new CPListElement[] { newCPLibraryElement(folder) };
-// }
-// return null;
-// }
-
-
- private CPListElement[] openClassFolderDialog(CPListElement existing) {
- if (existing == null) {
- IPath[] selected= BuildPathDialogAccess.chooseClassFolderEntries(getShell(), fCurrJProject.getPath(), getUsedContainers(existing));
- if (selected != null) {
- IWorkspaceRoot root= fCurrJProject.getProject().getWorkspace().getRoot();
- ArrayList res= new ArrayList();
- for (int i= 0; i < selected.length; i++) {
- IPath curr= selected[i];
- IResource resource= root.findMember(curr);
- if (resource instanceof IContainer) {
- res.add(newCPLibraryElement(resource));
- }
- }
- return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
- }
- } else {
- // disabled
- }
- return null;
- }
-
-// private CPListElement[] openJarFileDialog(CPListElement existing) {
-// IWorkspaceRoot root= fCurrJProject.getProject().getWorkspace().getRoot();
-//
-// if (existing == null) {
-// IPath[] selected= BuildPathDialogAccess.chooseJAREntries(getShell(), fCurrJProject.getPath(), getUsedJARFiles(existing));
-// if (selected != null) {
-// ArrayList res= new ArrayList();
-//
-// for (int i= 0; i < selected.length; i++) {
-// IPath curr= selected[i];
-// IResource resource= root.findMember(curr);
-// if (resource instanceof IFile) {
-// res.add(newCPLibraryElement(resource));
-// }
-// }
-// return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
-// }
-// } else {
-// IPath configured= BuildPathDialogAccess.configureJAREntry(getShell(), existing.getPath(), getUsedJARFiles(existing));
-// if (configured != null) {
-// IResource resource= root.findMember(configured);
-// if (resource instanceof IFile) {
-// return new CPListElement[] { newCPLibraryElement(resource) };
-// }
-// }
-// }
-// return null;
-// }
-
- private IPath[] getUsedContainers(CPListElement existing) {
- ArrayList res= new ArrayList();
-
- List cplist= fLibrariesList.getElements();
- for (int i= 0; i < cplist.size(); i++) {
- CPListElement elem= (CPListElement)cplist.get(i);
- if (elem.getEntryKind() == IIncludePathEntry.CPE_LIBRARY && (elem != existing)) {
- IResource resource= elem.getResource();
- if (resource instanceof IContainer && !resource.equals(existing)) {
- res.add(resource.getFullPath());
- }
- }
- }
- return (IPath[]) res.toArray(new IPath[res.size()]);
- }
-
-// private IPath[] getUsedJARFiles(CPListElement existing) {
-// List res= new ArrayList();
-// List cplist= fLibrariesList.getElements();
-// for (int i= 0; i < cplist.size(); i++) {
-// CPListElement elem= (CPListElement)cplist.get(i);
-// if (elem.getEntryKind() == IIncludePathEntry.CPE_LIBRARY && (elem != existing)) {
-// IResource resource= elem.getResource();
-// if (resource instanceof IFile) {
-// res.add(resource.getFullPath());
-// }
-// }
-// }
-// return (IPath[]) res.toArray(new IPath[res.size()]);
-// }
-
- private CPListElement newCPLibraryElement(IResource res) {
- return new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, res.getFullPath(), res);
- }
-
-// private CPListElement[] openExtJarFileDialog(CPListElement existing) {
-// if (existing == null) {
-// IPath[] selected= BuildPathDialogAccess.chooseExternalJAREntries(getShell());
-// if (selected != null) {
-// ArrayList res= new ArrayList();
-// for (int i= 0; i < selected.length; i++) {
-// res.add(new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, selected[i], null));
-// }
-// return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
-// }
-// } else {
-// IPath configured= BuildPathDialogAccess.configureExternalJAREntry(getShell(), existing.getPath());
-// if (configured != null) {
-// return new CPListElement[] { new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, configured, null) };
-// }
-// }
-// return null;
-// }
-
-// private CPListElement[] openVariableSelectionDialog(CPListElement existing) {
-// List existingElements= fLibrariesList.getElements();
-// ArrayList existingPaths= new ArrayList(existingElements.size());
-// for (int i= 0; i < existingElements.size(); i++) {
-// CPListElement elem= (CPListElement) existingElements.get(i);
-// if (elem.getEntryKind() == IIncludePathEntry.CPE_VARIABLE) {
-// existingPaths.add(elem.getPath());
-// }
-// }
-// IPath[] existingPathsArray= (IPath[]) existingPaths.toArray(new IPath[existingPaths.size()]);
-//
-// if (existing == null) {
-// IPath[] paths= BuildPathDialogAccess.chooseVariableEntries(getShell(), existingPathsArray);
-// if (paths != null) {
-// ArrayList result= new ArrayList();
-// for (int i = 0; i < paths.length; i++) {
-// IPath path= paths[i];
-// CPListElement elem= createCPVariableElement(path);
-// if (!existingElements.contains(elem)) {
-// result.add(elem);
-// }
-// }
-// return (CPListElement[]) result.toArray(new CPListElement[result.size()]);
-// }
-// } else {
-// IPath path= BuildPathDialogAccess.configureVariableEntry(getShell(), existing.getPath(), existingPathsArray);
-// if (path != null) {
-// return new CPListElement[] { createCPVariableElement(path) };
-// }
-// }
-// return null;
-// }
-
-// private CPListElement createCPVariableElement(IPath path) {
-// CPListElement elem= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_VARIABLE, path, null);
-// IPath resolvedPath= JavaScriptCore.getResolvedVariablePath(path);
-// elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().exists());
-// return elem;
-// }
-
- private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
- if (existing == null) {
- IIncludePathEntry[] created= BuildPathDialogAccess.chooseContainerEntries(getShell(), fCurrJProject, getRawClasspath());
- if (created != null) {
- CPListElement[] res= new CPListElement[created.length];
- for (int i= 0; i < res.length; i++) {
- //res[i]= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created[i].getPath(), null);
- res[i]= new CPListElement(fCurrJProject, created[i].getEntryKind(), created[i].getPath(), null);
- }
- return res;
- }
- } else {
- IIncludePathEntry created= BuildPathDialogAccess.configureContainerEntry(getShell(), existing.getClasspathEntry(), fCurrJProject, getRawClasspath());
- if (created != null) {
- //CPListElement elem= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created.getPath(), null);
- CPListElement elem= new CPListElement(fCurrJProject, created.getEntryKind(), created.getPath(), null);
- return new CPListElement[] { elem };
- }
- }
- return null;
- }
-
- private IIncludePathEntry[] getRawClasspath() {
- IIncludePathEntry[] currEntries= new IIncludePathEntry[fClassPathList.getSize()];
- for (int i= 0; i < currEntries.length; i++) {
- CPListElement curr= (CPListElement) fClassPathList.getElement(i);
- currEntries[i]= curr.getClasspathEntry();
- }
- return currEntries;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
- */
- public boolean isEntryKind(int kind) {
- //return true;
- return kind == IIncludePathEntry.CPE_LIBRARY || kind == IIncludePathEntry.CPE_VARIABLE || kind == IIncludePathEntry.CPE_CONTAINER ;
- }
-
- /*
- * @see BuildPathBasePage#getSelection
- */
- public List getSelection() {
- return fLibrariesList.getSelectedElements();
- }
-
- /*
- * @see BuildPathBasePage#setSelection
- */
- public void setSelection(List selElements, boolean expand) {
- fLibrariesList.selectElements(new StructuredSelection(selElements));
- if (expand) {
- for (int i= 0; i < selElements.size(); i++) {
- fLibrariesList.expandElement(selElements.get(i), 1);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
- fLibrariesList.setFocus();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/MultipleFolderSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/MultipleFolderSelectionDialog.java
deleted file mode 100644
index cbe952c6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/MultipleFolderSelectionDialog.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.dialogs.NewFolderDialog;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- */
-public class MultipleFolderSelectionDialog extends SelectionStatusDialog implements ISelectionChangedListener {
-
- private CheckboxTreeViewer fViewer;
-
- private ILabelProvider fLabelProvider;
- private ITreeContentProvider fContentProvider;
- private List fFilters;
-
- private Object fInput;
- private Button fNewFolderButton;
- private IContainer fSelectedContainer;
- private Set fExisting;
- private Object fFocusElement;
-
- public MultipleFolderSelectionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) {
- super(parent);
- fLabelProvider= labelProvider;
- fContentProvider= contentProvider;
-
- setSelectionResult(null);
- setStatusLineAboveButtons(true);
-
- int shellStyle = getShellStyle();
- setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
-
- fExisting= null;
- fFocusElement= null;
- fFilters= null;
- }
-
- public void setExisting(Object[] existing) {
- fExisting= new HashSet();
- for (int i= 0; i < existing.length; i++) {
- fExisting.add(existing[i]);
- }
- }
-
- /**
- * Sets the tree input.
- * @param input the tree input.
- */
- public void setInput(Object input) {
- fInput = input;
- }
-
- /**
- * Adds a filter to the tree viewer.
- * @param filter a filter.
- */
- public void addFilter(ViewerFilter filter) {
- if (fFilters == null)
- fFilters = new ArrayList(4);
-
- fFilters.add(filter);
- }
-
- /**
- * Handles cancel button pressed event.
- */
- protected void cancelPressed() {
- setSelectionResult(null);
- super.cancelPressed();
- }
-
- /*
- * @see SelectionStatusDialog#computeResult()
- */
- protected void computeResult() {
- Object[] checked= fViewer.getCheckedElements();
- if (fExisting == null) {
- if (checked.length == 0) {
- checked= null;
- }
- } else {
- ArrayList res= new ArrayList();
- for (int i= 0; i < checked.length; i++) {
- Object elem= checked[i];
- if (!fExisting.contains(elem)) {
- res.add(elem);
- }
- }
- if (!res.isEmpty()) {
- checked= res.toArray();
- } else {
- checked= null;
- }
- }
- setSelectionResult(checked);
- }
-
- private void access$superCreate() {
- super.create();
- }
-
- /*
- * @see Window#create()
- */
- public void create() {
-
- BusyIndicator.showWhile(null, new Runnable() {
- public void run() {
- access$superCreate();
-
- fViewer.setCheckedElements(
- getInitialElementSelections().toArray());
-
- fViewer.expandToLevel(2);
- if (fExisting != null) {
- for (Iterator iter= fExisting.iterator(); iter.hasNext();) {
- fViewer.reveal(iter.next());
- }
- }
-
- updateOKStatus();
- }
- });
-
- }
-
- /**
- * Creates the tree viewer.
- *
- * @param parent the parent composite
- * @return the tree viewer
- */
- protected CheckboxTreeViewer createTreeViewer(Composite parent) {
- fViewer = new CheckboxTreeViewer(parent, SWT.BORDER);
-
- fViewer.setContentProvider(fContentProvider);
- fViewer.setLabelProvider(fLabelProvider);
- fViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- updateOKStatus();
- }
- });
-
- fViewer.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (fFilters != null) {
- for (int i = 0; i != fFilters.size(); i++)
- fViewer.addFilter((ViewerFilter) fFilters.get(i));
- }
-
- fViewer.setInput(fInput);
-
- return fViewer;
- }
-
-
-
- /**
- *
- */
- protected void updateOKStatus() {
- computeResult();
- if (getResult() != null) {
- updateStatus(new StatusInfo());
- } else {
- updateStatus(new StatusInfo(IStatus.ERROR, "")); //$NON-NLS-1$
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
-
- createMessageArea(composite);
- CheckboxTreeViewer treeViewer = createTreeViewer(composite);
-
- GridData data = new GridData(GridData.FILL_BOTH);
- data.widthHint = convertWidthInCharsToPixels(60);
- data.heightHint = convertHeightInCharsToPixels(18);
-
- Tree treeWidget = treeViewer.getTree();
- treeWidget.setLayoutData(data);
- treeWidget.setFont(composite.getFont());
-
- Button button = new Button(composite, SWT.PUSH);
- button.setText(NewWizardMessages.MultipleFolderSelectionDialog_button);
- button.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent event) {
- newFolderButtonPressed();
- }
- });
- button.setFont(composite.getFont());
-
- fNewFolderButton= button;
-
- treeViewer.addSelectionChangedListener(this);
- if (fExisting != null) {
- Object[] existing= fExisting.toArray();
- treeViewer.setGrayedElements(existing);
- setInitialSelections(existing);
- }
- if (fFocusElement != null) {
- treeViewer.setSelection(new StructuredSelection(fFocusElement), true);
- }
- treeViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- forceExistingChecked(event);
- }
- });
-
- applyDialogFont(composite);
- return composite;
- }
-
- protected void forceExistingChecked(CheckStateChangedEvent event) {
- if (fExisting != null) {
- Object elem= event.getElement();
- if (fExisting.contains(elem)) {
- fViewer.setChecked(elem, true);
- }
- }
- }
-
- private void updateNewFolderButtonState() {
- IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
- fSelectedContainer= null;
- if (selection.size() == 1) {
- Object first= selection.getFirstElement();
- if (first instanceof IContainer) {
- fSelectedContainer= (IContainer) first;
- }
- }
- fNewFolderButton.setEnabled(fSelectedContainer != null);
- }
-
- protected void newFolderButtonPressed() {
- Object createdFolder= createFolder(fSelectedContainer);
- if (createdFolder != null) {
- CheckboxTreeViewer treeViewer= fViewer;
- treeViewer.refresh(fSelectedContainer);
- treeViewer.reveal(createdFolder);
- treeViewer.setChecked(createdFolder, true);
- treeViewer.setSelection(new StructuredSelection(createdFolder));
- updateOKStatus();
- }
- }
-
- protected Object createFolder(IContainer container) {
- NewFolderDialog dialog= new NewFolderDialog(getShell(), container);
- if (dialog.open() == Window.OK) {
- return dialog.getResult()[0];
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
- */
- public void selectionChanged(SelectionChangedEvent event) {
- updateNewFolderButtonState();
- }
-
- public void setInitialFocus(Object focusElement) {
- fFocusElement= focusElement;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewContainerDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewContainerDialog.java
deleted file mode 100644
index 359d26ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewContainerDialog.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-public class NewContainerDialog extends StatusDialog {
-
- private StringDialogField fContainerDialogField;
- private StatusInfo fContainerFieldStatus;
-
- private IFolder fFolder;
- private IPath[] fExistingFolders;
- private IProject fCurrProject;
-
- public NewContainerDialog(Shell parent, String title, IProject project, IPath[] existingFolders, CPListElement entryToEdit) {
- super(parent);
- setTitle(title);
-
- fContainerFieldStatus= new StatusInfo();
-
- SourceContainerAdapter adapter= new SourceContainerAdapter();
- fContainerDialogField= new StringDialogField();
- fContainerDialogField.setDialogFieldListener(adapter);
-
- fFolder= null;
- fExistingFolders= existingFolders;
- fCurrProject= project;
-
- if (entryToEdit == null) {
- fContainerDialogField.setText(""); //$NON-NLS-1$
- } else {
- fContainerDialogField.setText(entryToEdit.getPath().removeFirstSegments(1).toString());
- }
- }
-
- public void setMessage(String message) {
- fContainerDialogField.setLabelText(message);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite)super.createDialogArea(parent);
-
- int widthHint= convertWidthInCharsToPixels(80);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
- inner.setLayout(layout);
-
- fContainerDialogField.doFillIntoGrid(inner, 2);
-
- LayoutUtil.setWidthHint(fContainerDialogField.getLabelControl(null), widthHint);
- LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), widthHint);
- LayoutUtil.setHorizontalGrabbing(fContainerDialogField.getTextControl(null));
-
- fContainerDialogField.postSetFocusOnDialogField(parent.getDisplay());
- applyDialogFont(composite);
- return composite;
- }
-
-
- // -------- SourceContainerAdapter --------
-
- private class SourceContainerAdapter implements IDialogFieldListener {
-
- // -------- IDialogFieldListener
-
- public void dialogFieldChanged(DialogField field) {
- doStatusLineUpdate();
- }
- }
-
- protected void doStatusLineUpdate() {
- checkIfPathValid();
- updateStatus(fContainerFieldStatus);
- }
-
- protected void checkIfPathValid() {
- fFolder= null;
-
- String pathStr= fContainerDialogField.getText();
- if (pathStr.length() == 0) {
- fContainerFieldStatus.setError(NewWizardMessages.NewContainerDialog_error_enterpath);
- return;
- }
- IPath path= fCurrProject.getFullPath().append(pathStr);
- IWorkspace workspace= fCurrProject.getWorkspace();
-
- IStatus pathValidation= workspace.validatePath(path.toString(), IResource.FOLDER);
- if (!pathValidation.isOK()) {
- fContainerFieldStatus.setError(Messages.format(NewWizardMessages.NewContainerDialog_error_invalidpath, pathValidation.getMessage()));
- return;
- }
- IFolder folder= fCurrProject.getFolder(pathStr);
- if (isFolderExisting(folder)) {
- fContainerFieldStatus.setError(NewWizardMessages.NewContainerDialog_error_pathexists);
- return;
- }
- fContainerFieldStatus.setOK();
- fFolder= folder;
- }
-
- private boolean isFolderExisting(IFolder folder) {
- for (int i= 0; i < fExistingFolders.length; i++) {
- if (folder.getFullPath().equals(fExistingFolders[i])) {
- return true;
- }
- }
- return false;
- }
-
-
-
- public IFolder getFolder() {
- return fFolder;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.NEW_CONTAINER_DIALOG);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewSourceFolderDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewSourceFolderDialog.java
deleted file mode 100644
index 7e7d15f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/NewSourceFolderDialog.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-
-public class NewSourceFolderDialog extends StatusDialog {
-
- private SelectionButtonDialogField fUseProjectButton;
- private SelectionButtonDialogField fUseFolderButton;
-
- private StringDialogField fContainerDialogField;
- private StatusInfo fContainerFieldStatus;
-
- private IContainer fFolder;
- private List fExistingFolders;
- private IProject fCurrProject;
-
- public NewSourceFolderDialog(Shell parent, String title, IProject project, List existingFolders, CPListElement entryToEdit) {
- super(parent);
- setTitle(title);
-
- fContainerFieldStatus= new StatusInfo();
-
- SourceContainerAdapter adapter= new SourceContainerAdapter();
-
- fUseProjectButton= new SelectionButtonDialogField(SWT.RADIO);
- fUseProjectButton.setLabelText(NewWizardMessages.NewSourceFolderDialog_useproject_button);
- fUseProjectButton.setDialogFieldListener(adapter);
-
- fUseFolderButton= new SelectionButtonDialogField(SWT.RADIO);
- fUseFolderButton.setLabelText(NewWizardMessages.NewSourceFolderDialog_usefolder_button);
- fUseFolderButton.setDialogFieldListener(adapter);
-
- fContainerDialogField= new StringDialogField();
- fContainerDialogField.setDialogFieldListener(adapter);
- fContainerDialogField.setLabelText(NewWizardMessages.NewSourceFolderDialog_sourcefolder_label);
-
- fUseFolderButton.attachDialogField(fContainerDialogField);
-
- fFolder= null;
- fExistingFolders= existingFolders;
- fCurrProject= project;
-
- boolean useFolders= true;
- if (entryToEdit == null) {
- fContainerDialogField.setText(""); //$NON-NLS-1$
- } else {
- IPath editPath= entryToEdit.getPath().removeFirstSegments(1);
- fContainerDialogField.setText(editPath.toString());
- useFolders= !editPath.isEmpty();
- }
- fUseFolderButton.setSelection(useFolders);
- fUseProjectButton.setSelection(!useFolders);
- }
-
- public void setMessage(String message) {
- fContainerDialogField.setLabelText(message);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite)super.createDialogArea(parent);
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
- inner.setLayout(layout);
-
- int widthHint= convertWidthInCharsToPixels(50);
-
-
- GridData data= new GridData(GridData.FILL_HORIZONTAL);
- data.widthHint= widthHint;
-
- if (fExistingFolders.contains(fCurrProject)) {
- fContainerDialogField.doFillIntoGrid(inner, 2);
- } else {
- fUseProjectButton.doFillIntoGrid(inner, 1);
- fUseFolderButton.doFillIntoGrid(inner, 1);
- fContainerDialogField.getTextControl(inner);
-
- int horizontalIndent= convertWidthInCharsToPixels(3);
- data.horizontalIndent= horizontalIndent;
- }
- Text text= fContainerDialogField.getTextControl(null);
- text.setLayoutData(data);
- TextFieldNavigationHandler.install(text);
-
- fContainerDialogField.postSetFocusOnDialogField(parent.getDisplay());
- applyDialogFont(composite);
- return composite;
- }
-
-
- // -------- SourceContainerAdapter --------
-
- private class SourceContainerAdapter implements IDialogFieldListener {
-
- // -------- IDialogFieldListener
-
- public void dialogFieldChanged(DialogField field) {
- doStatusLineUpdate();
- }
- }
-
- protected void doStatusLineUpdate() {
- checkIfPathValid();
- updateStatus(fContainerFieldStatus);
- }
-
- protected void checkIfPathValid() {
- fFolder= null;
- IContainer folder= null;
- if (fUseFolderButton.isSelected()) {
- String pathStr= fContainerDialogField.getText();
- if (pathStr.length() == 0) {
- fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_enterpath);
- return;
- }
- IPath path= fCurrProject.getFullPath().append(pathStr);
- IWorkspace workspace= fCurrProject.getWorkspace();
-
- IStatus pathValidation= workspace.validatePath(path.toString(), IResource.FOLDER);
- if (!pathValidation.isOK()) {
- fContainerFieldStatus.setError(Messages.format(NewWizardMessages.NewSourceFolderDialog_error_invalidpath, pathValidation.getMessage()));
- return;
- }
- folder= fCurrProject.getFolder(pathStr);
- } else {
- folder= fCurrProject;
- }
- if (isExisting(folder)) {
- fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_pathexists);
- return;
- }
- fContainerFieldStatus.setOK();
- fFolder= folder;
- }
-
- private boolean isExisting(IContainer folder) {
- return fExistingFolders.contains(folder);
- }
-
-
-
- public IContainer getSourceFolder() {
- return fFolder;
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.NEW_CONTAINER_DIALOG);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java
deleted file mode 100644
index cd79b8f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ListSelectionDialog;
-import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
-import org.eclipse.wst.jsdt.core.IAccessRule;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.TreeListDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-
-
-public class ProjectsWorkbookPage extends BuildPathBasePage {
-
- private final int IDX_ADDPROJECT= 0;
- private final int IDX_EDIT= 1;
- private final int IDX_REMOVE= 2;
-
- private ListDialogField fClassPathList;
- private IJavaScriptProject fCurrJProject;
-
- private TreeListDialogField fProjectsList;
-
- private Control fSWTControl;
-
- private final IWorkbenchPreferenceContainer fPageContainer;
-
- public ProjectsWorkbookPage(ListDialogField classPathList, IWorkbenchPreferenceContainer pageContainer) {
- fClassPathList= classPathList;
- fPageContainer= pageContainer;
- fSWTControl= null;
-
- String[] buttonLabels= new String[] {
- NewWizardMessages.ProjectsWorkbookPage_projects_add_button,
- NewWizardMessages.ProjectsWorkbookPage_projects_edit_button,
- NewWizardMessages.ProjectsWorkbookPage_projects_remove_button
- };
-
- ProjectsAdapter adapter= new ProjectsAdapter();
-
- fProjectsList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fProjectsList.setDialogFieldListener(adapter);
- fProjectsList.setLabelText(NewWizardMessages.ProjectsWorkbookPage_projects_label);
-
- fProjectsList.enableButton(IDX_REMOVE, false);
- fProjectsList.enableButton(IDX_EDIT, false);
-
- fProjectsList.setViewerComparator(new CPListElementSorter());
- }
-
- public void init(final IJavaScriptProject jproject) {
- fCurrJProject= jproject;
-
- if (Display.getCurrent() != null) {
- updateProjectsList(jproject);
- } else {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- updateProjectsList(jproject);
- }
- });
- }
- }
-
- private void updateProjectsList(IJavaScriptProject currJProject) {
- // add the projects-cpentries that are already on the class path
- List cpelements= fClassPathList.getElements();
-
- final List checkedProjects= new ArrayList(cpelements.size());
-
- for (int i= cpelements.size() - 1 ; i >= 0; i--) {
- CPListElement cpelem= (CPListElement)cpelements.get(i);
- if (isEntryKind(cpelem.getEntryKind())) {
- checkedProjects.add(cpelem);
- }
- }
- fProjectsList.setElements(checkedProjects);
- }
-
- // -------- UI creation ---------
-
- public Control getControl(Composite parent) {
- PixelConverter converter= new PixelConverter(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
-
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fProjectsList }, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fProjectsList.getTreeControl(null));
-
- int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
- fProjectsList.setButtonsMinWidth(buttonBarWidth);
-
- fSWTControl= composite;
-
- return composite;
- }
-
- private void updateClasspathList() {
- List projelements= fProjectsList.getElements();
-
- boolean remove= false;
- List cpelements= fClassPathList.getElements();
- // backwards, as entries will be deleted
- for (int i= cpelements.size() -1; i >= 0 ; i--) {
- CPListElement cpe= (CPListElement)cpelements.get(i);
- if (isEntryKind(cpe.getEntryKind())) {
- if (!projelements.remove(cpe)) {
- cpelements.remove(i);
- remove= true;
- }
- }
- }
- for (int i= 0; i < projelements.size(); i++) {
- cpelements.add(projelements.get(i));
- }
- if (remove || (projelements.size() > 0)) {
- fClassPathList.setElements(cpelements);
- }
- }
-
- /*
- * @see BuildPathBasePage#getSelection
- */
- public List getSelection() {
- return fProjectsList.getSelectedElements();
- }
-
- /*
- * @see BuildPathBasePage#setSelection
- */
- public void setSelection(List selElements, boolean expand) {
- fProjectsList.selectElements(new StructuredSelection(selElements));
- if (expand) {
- for (int i= 0; i < selElements.size(); i++) {
- fProjectsList.expandElement(selElements.get(i), 1);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
- */
- public boolean isEntryKind(int kind) {
- return kind == IIncludePathEntry.CPE_PROJECT;
- }
-
-
- private class ProjectsAdapter implements IDialogFieldListener, ITreeListAdapter {
-
- private final Object[] EMPTY_ARR= new Object[0];
-
- // -------- IListAdapter --------
- public void customButtonPressed(TreeListDialogField field, int index) {
- projectPageCustomButtonPressed(field, index);
- }
-
- public void selectionChanged(TreeListDialogField field) {
- projectPageSelectionChanged(field);
- }
-
- public void doubleClicked(TreeListDialogField field) {
- projectPageDoubleClicked(field);
- }
-
- public void keyPressed(TreeListDialogField field, KeyEvent event) {
- projectPageKeyPressed(field, event);
- }
-
- public Object[] getChildren(TreeListDialogField field, Object element) {
- if (element instanceof CPListElement) {
- return ((CPListElement) element).getChildren();
- }
- return EMPTY_ARR;
- }
-
- public Object getParent(TreeListDialogField field, Object element) {
- if (element instanceof CPListElementAttribute) {
- return ((CPListElementAttribute) element).getParent();
- }
- return null;
- }
-
- public boolean hasChildren(TreeListDialogField field, Object element) {
- return getChildren(field, element).length > 0;
- }
-
- // ---------- IDialogFieldListener --------
-
- public void dialogFieldChanged(DialogField field) {
- projectPageDialogFieldChanged(field);
- }
- }
-
- private void projectPageCustomButtonPressed(DialogField field, int index) {
- CPListElement[] entries= null;
- switch (index) {
- case IDX_ADDPROJECT: /* add project */
- entries= openProjectDialog(null);
- break;
- case IDX_EDIT: /* edit */
- editEntry();
- return;
- case IDX_REMOVE: /* remove */
- removeEntry();
- return;
- }
- if (entries != null) {
- int nElementsChosen= entries.length;
- // remove duplicates
- List cplist= fProjectsList.getElements();
- List elementsToAdd= new ArrayList(nElementsChosen);
- for (int i= 0; i < nElementsChosen; i++) {
- CPListElement curr= entries[i];
- if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
- elementsToAdd.add(curr);
- }
- }
-
- fProjectsList.addElements(elementsToAdd);
- if (index == IDX_ADDPROJECT) {
- fProjectsList.refresh();
- }
- fProjectsList.postSetSelection(new StructuredSelection(entries));
- }
- }
-
- private void removeEntry() {
- List selElements= fProjectsList.getSelectedElements();
- for (int i= selElements.size() - 1; i >= 0 ; i--) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isBuiltIn()) {
- String key= attrib.getKey();
- Object value= null;
- if (key.equals(CPListElement.ACCESSRULES)) {
- value= new IAccessRule[0];
- }
- attrib.getParent().setAttribute(key, value);
- } else {
- removeCustomAttribute(attrib);
- }
- selElements.remove(i);
- }
- }
- if (selElements.isEmpty()) {
- fProjectsList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
- } else {
- fProjectsList.removeElements(selElements);
- }
- }
-
- private boolean canRemove(List selElements) {
- if (selElements.size() == 0) {
- return false;
- }
-
- for (int i= 0; i < selElements.size(); i++) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isNonModifiable()) {
- return false;
- }
- if (attrib.isBuiltIn()) {
- if (CPListElement.ACCESSRULES.equals(attrib.getKey())) {
- if (((IAccessRule[]) attrib.getValue()).length == 0) {
- return false;
- }
- } else if (attrib.getValue() == null) {
- return false;
- }
- } else {
- if (!canRemoveCustomAttribute(attrib)) {
- return false;
- }
- }
- }
- }
- return true;
- }
-
- private boolean canEdit(List selElements) {
- if (selElements.size() != 1) {
- return false;
- }
- Object elem= selElements.get(0);
- if (elem instanceof CPListElement) {
- return false;
- }
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isNonModifiable()) {
- return false;
- }
- if (!attrib.isBuiltIn()) {
- return canEditCustomAttribute(attrib);
- }
- return true;
- }
- return false;
- }
-
- /**
- * Method editEntry.
- */
- private void editEntry() {
- List selElements= fProjectsList.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- Object elem= selElements.get(0);
- if (fProjectsList.getIndexOfElement(elem) != -1) {
- editElementEntry((CPListElement) elem);
- } else if (elem instanceof CPListElementAttribute) {
- editAttributeEntry((CPListElementAttribute) elem);
- }
- }
-
- private void editAttributeEntry(CPListElementAttribute elem) {
- String key= elem.getKey();
- if (key.equals(CPListElement.ACCESSRULES)) {
- showAccessRestrictionDialog(elem.getParent());
- } else {
- if (editCustomAttribute(getShell(), elem)) {
- fProjectsList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
- }
- }
- }
-
- private void showAccessRestrictionDialog(CPListElement selElement) {
- AccessRulesDialog dialog= new AccessRulesDialog(getShell(), selElement, fCurrJProject, fPageContainer != null);
- int res= dialog.open();
- if (res == Window.OK || res == AccessRulesDialog.SWITCH_PAGE) {
- selElement.setAttribute(CPListElement.ACCESSRULES, dialog.getAccessRules());
- selElement.setAttribute(CPListElement.COMBINE_ACCESSRULES, new Boolean(dialog.doCombineAccessRules()));
- fProjectsList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
-
- if (res == AccessRulesDialog.SWITCH_PAGE) {
- dialog.performPageSwitch(fPageContainer);
- }
- }
- }
-
- private void editElementEntry(CPListElement elem) {
- CPListElement[] res= openProjectDialog(elem);
- if (res != null && res.length > 0) {
- CPListElement curr= res[0];
- curr.setExported(elem.isExported());
- fProjectsList.replaceElement(elem, curr);
- }
-
- }
-
- private Shell getShell() {
- if (fSWTControl != null) {
- return fSWTControl.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
-
- private CPListElement[] openProjectDialog(CPListElement elem) {
-
- try {
- ArrayList selectable= new ArrayList();
- selectable.addAll(Arrays.asList(fCurrJProject.getJavaScriptModel().getJavaScriptProjects()));
- selectable.remove(fCurrJProject);
-
- List elements= fProjectsList.getElements();
- for (int i= 0; i < elements.size(); i++) {
- CPListElement curr= (CPListElement) elements.get(0);
- IJavaScriptProject proj= (IJavaScriptProject) JavaScriptCore.create(curr.getResource());
- selectable.remove(proj);
- }
- Object[] selectArr= selectable.toArray();
- new JavaScriptElementComparator().sort(null, selectArr);
-
- ListSelectionDialog dialog= new ListSelectionDialog(getShell(), Arrays.asList(selectArr), new ArrayContentProvider(), new JavaUILabelProvider(), NewWizardMessages.ProjectsWorkbookPage_chooseProjects_message);
- dialog.setTitle(NewWizardMessages.ProjectsWorkbookPage_chooseProjects_title);
- dialog.setHelpAvailable(false);
- if (dialog.open() == Window.OK) {
- Object[] result= dialog.getResult();
- CPListElement[] cpElements= new CPListElement[result.length];
- for (int i= 0; i < result.length; i++) {
- IJavaScriptProject curr= (IJavaScriptProject) result[i];
- cpElements[i]= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_PROJECT, curr.getPath(), curr.getResource());
- }
- return cpElements;
- }
- } catch (JavaScriptModelException e) {
- return null;
- }
- return null;
- }
-
- protected void projectPageDoubleClicked(TreeListDialogField field) {
- List selection= fProjectsList.getSelectedElements();
- if (canEdit(selection)) {
- editEntry();
- }
- }
-
- protected void projectPageKeyPressed(TreeListDialogField field, KeyEvent event) {
- if (field == fProjectsList) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- List selection= field.getSelectedElements();
- if (canRemove(selection)) {
- removeEntry();
- }
- }
- }
- }
-
- private void projectPageDialogFieldChanged(DialogField field) {
- if (fCurrJProject != null) {
- // already initialized
- updateClasspathList();
- }
- }
-
- private void projectPageSelectionChanged(DialogField field) {
- List selElements= fProjectsList.getSelectedElements();
- fProjectsList.enableButton(IDX_EDIT, canEdit(selElements));
- fProjectsList.enableButton(IDX_REMOVE, canRemove(selElements));
-
- boolean noAttributes= containsOnlyTopLevelEntries(selElements);
- fProjectsList.enableButton(IDX_ADDPROJECT, noAttributes);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
- fProjectsList.setFocus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SetFilterWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SetFilterWizardPage.java
deleted file mode 100644
index 14512c70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SetFilterWizardPage.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-public class SetFilterWizardPage extends NewElementWizardPage {
-
- private static final String PAGE_NAME= "SetFilterWizardPage"; //$NON-NLS-1$
-
- private ListDialogField fInclusionPatternList;
- private ListDialogField fExclusionPatternList;
- private CPListElement fCurrElement;
- private IProject fCurrProject;
-
- private IContainer fCurrSourceFolder;
-
- private static final int IDX_ADD= 0;
- private static final int IDX_ADD_MULTIPLE= 1;
- private static final int IDX_EDIT= 2;
- private static final int IDX_REMOVE= 4;
-
- private final ArrayList fExistingEntries;
-
- public SetFilterWizardPage(CPListElement entryToEdit, ArrayList existingEntries) {
- super(PAGE_NAME);
- fExistingEntries= existingEntries;
-
- setTitle(NewWizardMessages.ExclusionInclusionDialog_title);
- setDescription(NewWizardMessages.ExclusionInclusionDialog_description2);
-
- fCurrElement= entryToEdit;
- fCurrProject= entryToEdit.getJavaProject().getProject();
- IWorkspaceRoot root= fCurrProject.getWorkspace().getRoot();
- IResource res= root.findMember(entryToEdit.getPath());
- if (res instanceof IContainer) {
- fCurrSourceFolder= (IContainer) res;
- }
-
- String excLabel= NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_label;
- ImageDescriptor excDescriptor= JavaPluginImages.DESC_OBJS_EXCLUSION_FILTER_ATTRIB;
- String[] excButtonLabels= new String[] {
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add_multiple,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_edit,
- null,
- NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_remove
- };
-
-
- String incLabel= NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_label;
- ImageDescriptor incDescriptor= JavaPluginImages.DESC_OBJS_INCLUSION_FILTER_ATTRIB;
- String[] incButtonLabels= new String[] {
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add_multiple,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_edit,
- null,
- NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_remove
- };
-
- fExclusionPatternList= createListContents(entryToEdit, CPListElement.EXCLUSION, excLabel, excDescriptor, excButtonLabels);
- fInclusionPatternList= createListContents(entryToEdit, CPListElement.INCLUSION, incLabel, incDescriptor, incButtonLabels);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite inner= new Composite(parent, SWT.NONE);
- inner.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 2;
- inner.setLayout(layout);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- fInclusionPatternList.doFillIntoGrid(inner, 3);
- LayoutUtil.setHorizontalSpan(fInclusionPatternList.getLabelControl(null), 2);
- LayoutUtil.setHorizontalGrabbing(fInclusionPatternList.getListControl(null));
-
- fExclusionPatternList.doFillIntoGrid(inner, 3);
- LayoutUtil.setHorizontalSpan(fExclusionPatternList.getLabelControl(null), 2);
- LayoutUtil.setHorizontalGrabbing(fExclusionPatternList.getListControl(null));
-
- setControl(inner);
- Dialog.applyDialogFont(inner);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(inner, IJavaHelpContextIds.INCLUSION_EXCLUSION_WIZARD_PAGE);
- }
-
-
- private static class ExclusionInclusionLabelProvider extends LabelProvider {
-
- private Image fElementImage;
-
- public ExclusionInclusionLabelProvider(ImageDescriptor descriptor) {
- ImageDescriptorRegistry registry= JavaScriptPlugin.getImageDescriptorRegistry();
- fElementImage= registry.get(descriptor);
- }
-
- public Image getImage(Object element) {
- return fElementImage;
- }
-
- public String getText(Object element) {
- return (String) element;
- }
-
- }
-
- private ListDialogField createListContents(CPListElement entryToEdit, String key, String label, ImageDescriptor descriptor, String[] buttonLabels) {
- ExclusionPatternAdapter adapter= new ExclusionPatternAdapter();
-
- ListDialogField patternList= new ListDialogField(adapter, buttonLabels, new ExclusionInclusionLabelProvider(descriptor));
- patternList.setDialogFieldListener(adapter);
- patternList.setLabelText(label);
- patternList.enableButton(IDX_EDIT, false);
-
- IPath[] pattern= (IPath[]) entryToEdit.getAttribute(key);
-
- ArrayList elements= new ArrayList(pattern.length);
- for (int i= 0; i < pattern.length; i++) {
- String patternName= pattern[i].toString();
- if (patternName.length() > 0)
- elements.add(patternName);
- }
- patternList.setElements(elements);
- patternList.selectFirstElement();
- patternList.enableButton(IDX_ADD_MULTIPLE, fCurrSourceFolder != null);
- patternList.setViewerComparator(new ViewerComparator());
- return patternList;
- }
-
- protected void doCustomButtonPressed(ListDialogField field, int index) {
- if (index == IDX_ADD) {
- addEntry(field);
- } else if (index == IDX_EDIT) {
- editEntry(field);
- } else if (index == IDX_ADD_MULTIPLE) {
- addMultipleEntries(field);
- } else if (index == IDX_REMOVE) {
- field.removeElements(field.getSelectedElements());
- }
- updateStatus();
- }
-
- private void updateStatus() {
-// fCurrElement.setAttribute(CPListElement.INCLUSION, getInclusionPattern());
-// fCurrElement.setAttribute(CPListElement.EXCLUSION, getExclusionPattern());
-// StatusInfo statusInfo= new StatusInfo();
-// statusInfo.setOK();
-// updateStatus(statusInfo);
-
-// fCurrElement.setAttribute(CPListElement.INCLUSION, getInclusionPattern());
-// fCurrElement.setAttribute(CPListElement.EXCLUSION, getExclusionPattern());
- IJavaScriptModelStatus status= JavaScriptConventions.validateClasspath(fCurrElement.getJavaProject(), CPListElement.convertToClasspathEntries(fExistingEntries));
- if (!status.isOK()) {
- StatusInfo statusInfo= new StatusInfo();
- statusInfo.setError(status.getMessage());
- updateStatus(statusInfo);
- } else {
- StatusInfo statusInfo= new StatusInfo();
- statusInfo.setOK();
- updateStatus(statusInfo);
- }
- }
-
- protected void doDoubleClicked(ListDialogField field) {
- editEntry(field);
- updateStatus();
- }
-
- protected void doSelectionChanged(ListDialogField field) {
- List selected= field.getSelectedElements();
- field.enableButton(IDX_EDIT, canEdit(selected));
- }
-
- private boolean canEdit(List selected) {
- return selected.size() == 1;
- }
-
- private void editEntry(ListDialogField field) {
- List selElements= field.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- List existing= field.getElements();
- String entry= (String) selElements.get(0);
- ExclusionInclusionEntryDialog dialog= new ExclusionInclusionEntryDialog(getShell(), isExclusion(field), entry, existing, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.replaceElement(entry, dialog.getExclusionPattern());
- }
- }
-
- private boolean isExclusion(ListDialogField field) {
- return field == fExclusionPatternList;
- }
-
-
- private void addEntry(ListDialogField field) {
- List existing= field.getElements();
- ExclusionInclusionEntryDialog dialog= new ExclusionInclusionEntryDialog(getShell(), isExclusion(field), null, existing, fCurrElement);
- if (dialog.open() == Window.OK) {
- field.addElement(dialog.getExclusionPattern());
- }
- }
-
- // -------- ExclusionPatternAdapter --------
-
- private class ExclusionPatternAdapter implements IListAdapter, IDialogFieldListener {
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#customButtonPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField, int)
- */
- public void customButtonPressed(ListDialogField field, int index) {
- doCustomButtonPressed(field, index);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#selectionChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void selectionChanged(ListDialogField field) {
- doSelectionChanged(field);
- }
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter#doubleClicked(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField)
- */
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked(field);
- }
-
- /**
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void dialogFieldChanged(DialogField field) {
- }
-
- }
-
- protected void doStatusLineUpdate() {
- }
-
- protected void checkIfPatternValid() {
- }
-
-
- private IPath[] getPattern(ListDialogField field) {
- Object[] arr= field.getElements().toArray();
- Arrays.sort(arr);
- IPath[] res= new IPath[arr.length];
- for (int i= 0; i < res.length; i++) {
- res[i]= new Path((String) arr[i]);
- }
- return res;
- }
-
- public IPath[] getExclusionPattern() {
- return getPattern(fExclusionPatternList);
- }
-
- public IPath[] getInclusionPattern() {
- return getPattern(fInclusionPatternList);
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.EXCLUSION_PATTERN_DIALOG);
- }
-
- private void addMultipleEntries(ListDialogField field) {
- String title, message;
- if (isExclusion(field)) {
- title= NewWizardMessages.ExclusionInclusionDialog_ChooseExclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionDialog_ChooseExclusionPattern_description;
- } else {
- title= NewWizardMessages.ExclusionInclusionDialog_ChooseInclusionPattern_title;
- message= NewWizardMessages.ExclusionInclusionDialog_ChooseInclusionPattern_description;
- }
-
- IPath[] res= ExclusionInclusionEntryDialog.chooseExclusionPattern(getShell(), fCurrSourceFolder, title, message, null, true);
- if (res != null) {
- for (int i= 0; i < res.length; i++) {
- field.addElement(res[i].toString());
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
deleted file mode 100644
index 5d0c1e82..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
+++ /dev/null
@@ -1,583 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-
-/**
- * UI to set the source attachment archive and root.
- * Same implementation for both setting attachments for libraries from
- * variable entries and for normal (internal or external) jar.
- */
-public class SourceAttachmentBlock {
-
- private IStatusChangeListener fContext;
-
- private StringButtonDialogField fFileNameField;
- private SelectionButtonDialogField fWorkspaceButton;
- private SelectionButtonDialogField fExternalFolderButton;
-
- private IStatus fNameStatus;
-
- /**
- * The path to which the archive variable points.
- * Null if invalid path or not resolvable. Must not exist.
- */
- private IPath fFileVariablePath;
-
- private IWorkspaceRoot fWorkspaceRoot;
-
- private Control fSWTWidget;
- private Label fFullPathResolvedLabel;
-
- private IJavaScriptProject fProject;
- private IIncludePathEntry fEntry;
- private IPath fContainerPath;
-
-
- /**
- * @param context listeners for status updates
- * @param entry The entry to edit
- */
- public SourceAttachmentBlock(IStatusChangeListener context, IIncludePathEntry entry) {
- Assert.isNotNull(entry);
-
- fContext= context;
- fEntry= entry;
-
-
- int kind= entry.getEntryKind();
- Assert.isTrue(kind == IIncludePathEntry.CPE_LIBRARY || kind == IIncludePathEntry.CPE_VARIABLE);
-
- fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
-
- fNameStatus= new StatusInfo();
-
- SourceAttachmentAdapter adapter= new SourceAttachmentAdapter();
-
- fFileNameField= new StringButtonDialogField(adapter);
- fFileNameField.setDialogFieldListener(adapter);
- fFileNameField.setLabelText(NewWizardMessages.SourceAttachmentBlock_filename_label);
- fFileNameField.setButtonLabel(NewWizardMessages.SourceAttachmentBlock_filename_externalfile_button);
-
- fWorkspaceButton= new SelectionButtonDialogField(SWT.PUSH);
- fWorkspaceButton.setDialogFieldListener(adapter);
- fWorkspaceButton.setLabelText(NewWizardMessages.SourceAttachmentBlock_filename_internal_button);
-
- fExternalFolderButton= new SelectionButtonDialogField(SWT.PUSH);
- fExternalFolderButton.setDialogFieldListener(adapter);
- fExternalFolderButton.setLabelText(NewWizardMessages.SourceAttachmentBlock_filename_externalfolder_button);
-
- // set the old settings
- setDefaults();
- }
-
- /**
- * @deprecated Use API {@link org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess#configureSourceAttachment(Shell, IIncludePathEntry)}
- */
- public SourceAttachmentBlock(IStatusChangeListener context, IIncludePathEntry entry, IPath containerPath, IJavaScriptProject project) {
- this(context, entry);
- fContainerPath= containerPath;
- fProject= project;
- }
-
- public void setDefaults() {
- if (fEntry.getSourceAttachmentPath() != null) {
- fFileNameField.setText(fEntry.getSourceAttachmentPath().toString());
- } else {
- fFileNameField.setText(""); //$NON-NLS-1$
- }
- }
-
- private boolean isVariableEntry() {
- return fEntry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE;
- }
-
-
- /**
- * Gets the source attachment path chosen by the user
- */
- public IPath getSourceAttachmentPath() {
- if (fFileNameField.getText().length() == 0) {
- return null;
- }
- return getFilePath();
- }
-
- /**
- * Gets the source attachment root chosen by the user
- * Returns null to let JCore automatically detect the root.
- */
- public IPath getSourceAttachmentRootPath() {
- return null;
- }
-
- public IIncludePathEntry getNewEntry() {
- CPListElement elem= CPListElement.createFromExisting(fEntry, fProject);
- return elem.getClasspathEntry();
- }
-
- /**
- * Creates the control
- */
- public Control createControl(Composite parent) {
- PixelConverter converter= new PixelConverter(parent);
-
- fSWTWidget= parent;
-
- Composite composite= new Composite(parent, SWT.NONE);
-
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 4;
- composite.setLayout(layout);
-
-
- if (isVariableEntry()) {
- int widthHint= converter.convertWidthInCharsToPixels(40);
- int labelWidthHint= widthHint * 2;
-
- Label message= new Label(composite, SWT.WRAP);
- GridData gd= new GridData(GridData.FILL, GridData.BEGINNING, false, false, 4, 1);
- message.setLayoutData(gd);
- message.setText(Messages.format(NewWizardMessages.SourceAttachmentBlock_message, fEntry.getPath().lastSegment()));
-
- //DialogField.createEmptySpace(composite, 1);
-
- Label desc= new Label(composite, SWT.WRAP);
- gd= new GridData(GridData.FILL, GridData.BEGINNING, false, false, 4, 1);
- gd.widthHint= labelWidthHint;
- desc.setLayoutData(gd);
- desc.setText(NewWizardMessages.SourceAttachmentBlock_filename_description);
-
- fFileNameField.doFillIntoGrid(composite, 4);
- LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint);
-
- // label that shows the resolved path for variable jars
- //DialogField.createEmptySpace(composite, 1);
- fFullPathResolvedLabel= new Label(composite, SWT.WRAP);
- fFullPathResolvedLabel.setText(getResolvedLabelString());
- gd= new GridData(GridData.FILL, GridData.BEGINNING, false, false, 4, 1);
- gd.widthHint= labelWidthHint;
- fFullPathResolvedLabel.setLayoutData(gd);
-
- LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null));
- } else {
- int widthHint= converter.convertWidthInCharsToPixels(60);
-
- GridData gd= new GridData(GridData.FILL, GridData.BEGINNING, false, false, 3, 1);
- gd.widthHint= converter.convertWidthInCharsToPixels(50);
-
- Label message= new Label(composite, SWT.LEFT + SWT.WRAP);
- message.setLayoutData(gd);
- message.setText(Messages.format(NewWizardMessages.SourceAttachmentBlock_message, fEntry.getPath().lastSegment()));
-
- fWorkspaceButton.doFillIntoGrid(composite, 1);
- ((GridData) fWorkspaceButton.getSelectionButton(null).getLayoutData()).verticalAlignment= SWT.END;
-
-
- // archive name field
- fFileNameField.doFillIntoGrid(composite, 4);
- LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint);
- LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null));
-
- // Additional 'browse workspace' button for normal jars
- DialogField.createEmptySpace(composite, 3);
-
- fExternalFolderButton.doFillIntoGrid(composite, 1);
- }
-
- fFileNameField.postSetFocusOnDialogField(parent.getDisplay());
-
- Dialog.applyDialogFont(composite);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK);
- return composite;
- }
-
-
- private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener {
-
- // -------- IStringButtonAdapter --------
- public void changeControlPressed(DialogField field) {
- attachmentChangeControlPressed(field);
- }
-
- // ---------- IDialogFieldListener --------
- public void dialogFieldChanged(DialogField field) {
- attachmentDialogFieldChanged(field);
- }
- }
-
- private void attachmentChangeControlPressed(DialogField field) {
- if (field == fFileNameField) {
- IPath jarFilePath= isVariableEntry() ? chooseExtension() : chooseExtJarFile();
- if (jarFilePath != null) {
- fFileNameField.setText(jarFilePath.toString());
- }
- }
- }
-
- // ---------- IDialogFieldListener --------
-
- private void attachmentDialogFieldChanged(DialogField field) {
- if (field == fFileNameField) {
- fNameStatus= updateFileNameStatus();
- } else if (field == fWorkspaceButton) {
- IPath jarFilePath= chooseInternal();
- if (jarFilePath != null) {
- fFileNameField.setText(jarFilePath.toString());
- }
- return;
- } else if (field == fExternalFolderButton) {
- IPath folderPath= chooseExtFolder();
- if (folderPath != null) {
- fFileNameField.setText(folderPath.toString());
- }
- return;
- }
- doStatusLineUpdate();
- }
-
- private void doStatusLineUpdate() {
- fFileNameField.enableButton(canBrowseFileName());
-
- // set the resolved path for variable jars
- if (fFullPathResolvedLabel != null) {
- fFullPathResolvedLabel.setText(getResolvedLabelString());
- }
-
- IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus });
- fContext.statusChanged(status);
- }
-
- private boolean canBrowseFileName() {
- if (!isVariableEntry()) {
- return true;
- }
- // to browse with a variable JAR, the variable name must point to a directory
- if (fFileVariablePath != null) {
- return fFileVariablePath.toFile().isDirectory();
- }
- return false;
- }
-
- private String getResolvedLabelString() {
- IPath resolvedPath= getResolvedPath(getFilePath());
- if (resolvedPath != null) {
- return resolvedPath.toOSString();
- }
- return ""; //$NON-NLS-1$
- }
-
- private IPath getResolvedPath(IPath path) {
- if (path != null) {
- String varName= path.segment(0);
- if (varName != null) {
- IPath varPath= JavaScriptCore.getIncludepathVariable(varName);
- if (varPath != null) {
- return varPath.append(path.removeFirstSegments(1));
- }
- }
- }
- return null;
- }
-
- private IStatus updateFileNameStatus() {
- StatusInfo status= new StatusInfo();
- fFileVariablePath= null;
-
- String fileName= fFileNameField.getText();
- if (fileName.length() == 0) {
- // no source attachment
- return status;
- } else {
- if (!Path.EMPTY.isValidPath(fileName)) {
- status.setError(NewWizardMessages.SourceAttachmentBlock_filename_error_notvalid);
- return status;
- }
- IPath filePath= Path.fromOSString(fileName);
- IPath resolvedPath;
- if (isVariableEntry()) {
- if (filePath.getDevice() != null) {
- status.setError(NewWizardMessages.SourceAttachmentBlock_filename_error_deviceinpath);
- return status;
- }
- String varName= filePath.segment(0);
- if (varName == null) {
- status.setError(NewWizardMessages.SourceAttachmentBlock_filename_error_notvalid);
- return status;
- }
- fFileVariablePath= JavaScriptCore.getIncludepathVariable(varName);
- if (fFileVariablePath == null) {
- status.setError(NewWizardMessages.SourceAttachmentBlock_filename_error_varnotexists);
- return status;
- }
- resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
-
- if (resolvedPath.isEmpty()) {
- status.setWarning(NewWizardMessages.SourceAttachmentBlock_filename_warning_varempty);
- return status;
- }
- File file= resolvedPath.toFile();
- if (!file.exists()) {
- String message= Messages.format(NewWizardMessages.SourceAttachmentBlock_filename_error_filenotexists, resolvedPath.toOSString());
- status.setWarning(message);
- return status;
- }
- if (!resolvedPath.isAbsolute()) {
- String message= Messages.format(NewWizardMessages.SourceAttachmentBlock_filename_error_notabsolute, filePath.toString());
- status.setError(message);
- return status;
- }
-
- String deprecationMessage= BuildPathSupport.getDeprecationMessage(varName);
- if (deprecationMessage != null) {
- status.setWarning(deprecationMessage);
- return status;
- }
-
- } else {
- // JDT/Core only supports source attachments in archives on the
- // local file system. So using getLocation is save here.
- File file= filePath.toFile();
- IResource res= fWorkspaceRoot.findMember(filePath);
- if (res != null && res.getLocation() != null) {
- file= res.getLocation().toFile();
- }
- if (!file.exists()) {
- String message= Messages.format(NewWizardMessages.SourceAttachmentBlock_filename_error_filenotexists, filePath.toString());
- status.setError(message);
- return status;
- }
- if (res == null) {
- if (!filePath.isAbsolute()) {
- String message= Messages.format(NewWizardMessages.SourceAttachmentBlock_filename_error_notabsolute, filePath.toString());
- status.setError(message);
- return status;
- }
- }
- }
-
- }
- return status;
- }
-
- private IPath getFilePath() {
- return Path.fromOSString(fFileNameField.getText()).makeAbsolute();
- }
-
- private IPath chooseExtension() {
- IPath currPath= getFilePath();
- if (currPath.segmentCount() == 0) {
- currPath= fEntry.getPath();
- }
-
- IPath resolvedPath= getResolvedPath(currPath);
- File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null;
-
- String currVariable= currPath.segment(0);
- JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, true);
- dialog.setTitle(NewWizardMessages.SourceAttachmentBlock_extvardialog_title);
- dialog.setMessage(NewWizardMessages.SourceAttachmentBlock_extvardialog_description);
- dialog.setInput(fFileVariablePath.toFile());
- dialog.setInitialSelection(initialSelection);
- if (dialog.open() == Window.OK) {
- File result= (File) dialog.getResult()[0];
- IPath returnPath= Path.fromOSString(result.getPath()).makeAbsolute();
- return modifyPath(returnPath, currVariable);
- }
- return null;
- }
-
- /*
- * Opens a dialog to choose a jar from the file system.
- */
- private IPath chooseExtJarFile() {
- IPath currPath= getFilePath();
- if (currPath.segmentCount() == 0) {
- currPath= fEntry.getPath();
- }
-
- if (ArchiveFileFilter.isArchivePath(currPath)) {
- currPath= currPath.removeLastSegments(1);
- }
-
- FileDialog dialog= new FileDialog(getShell());
- dialog.setText(NewWizardMessages.SourceAttachmentBlock_extjardialog_text);
- dialog.setFilterExtensions(new String[] {"*.jar;*.zip;*.js"}); //$NON-NLS-1$
- dialog.setFilterPath(currPath.toOSString());
- String res= dialog.open();
- if (res != null) {
- return Path.fromOSString(res).makeAbsolute();
- }
- return null;
- }
-
- private IPath chooseExtFolder() {
- IPath currPath= getFilePath();
- if (currPath.segmentCount() == 0) {
- currPath= fEntry.getPath();
- }
- if (ArchiveFileFilter.isArchivePath(currPath)) {
- currPath= currPath.removeLastSegments(1);
- }
-
- DirectoryDialog dialog= new DirectoryDialog(getShell());
- dialog.setMessage(NewWizardMessages.SourceAttachmentBlock_extfolderdialog_message);
- dialog.setText(NewWizardMessages.SourceAttachmentBlock_extfolderdialog_text);
- dialog.setFilterPath(currPath.toOSString());
- String res= dialog.open();
- if (res != null) {
- return Path.fromOSString(res).makeAbsolute();
- }
- return null;
- }
-
- /*
- * Opens a dialog to choose an internal jar.
- */
- private IPath chooseInternal() {
- String initSelection= fFileNameField.getText();
-
- ViewerFilter filter= new ArchiveFileFilter((List) null, false);
-
- ILabelProvider lp= new WorkbenchLabelProvider();
- ITreeContentProvider cp= new WorkbenchContentProvider();
-
- IResource initSel= null;
- if (initSelection.length() > 0) {
- initSel= fWorkspaceRoot.findMember(new Path(initSelection));
- }
- if (initSel == null) {
- initSel= fWorkspaceRoot.findMember(fEntry.getPath());
- }
-
- FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
- dialog.setAllowMultiple(false);
- dialog.addFilter(filter);
- dialog.setTitle(NewWizardMessages.SourceAttachmentBlock_intjardialog_title);
- dialog.setMessage(NewWizardMessages.SourceAttachmentBlock_intjardialog_message);
- dialog.setInput(fWorkspaceRoot);
- dialog.setInitialSelection(initSel);
- if (dialog.open() == Window.OK) {
- IResource res= (IResource) dialog.getFirstResult();
- return res.getFullPath();
- }
- return null;
- }
-
- private Shell getShell() {
- if (fSWTWidget != null) {
- return fSWTWidget.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- /**
- * Takes a path and replaces the beginning with a variable name
- * (if the beginning matches with the variables value)
- */
- private IPath modifyPath(IPath path, String varName) {
- if (varName == null || path == null) {
- return null;
- }
- if (path.isEmpty()) {
- return new Path(varName);
- }
-
- IPath varPath= JavaScriptCore.getIncludepathVariable(varName);
- if (varPath != null) {
- if (varPath.isPrefixOf(path)) {
- path= path.removeFirstSegments(varPath.segmentCount());
- } else {
- path= new Path(path.lastSegment());
- }
- } else {
- path= new Path(path.lastSegment());
- }
- return new Path(varName).append(path);
- }
-
-
- /**
- * Creates a runnable that sets the source attachment by modifying the project's classpath.
- */
- public static IRunnableWithProgress getRunnable(final Shell shell, final IIncludePathEntry newEntry, final IJavaScriptProject jproject, final IPath containerPath) {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- String[] changedAttributes= {};
- BuildPathSupport.modifyClasspathEntry(shell, newEntry, changedAttributes, jproject, containerPath, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- }
-
- /**
- * @deprecated Use {@link #getRunnable(Shell, IIncludePathEntry, IJavaScriptProject, IPath)}
- */
- public IRunnableWithProgress getRunnable(final Shell shell) {
- return getRunnable(shell, getNewEntry(), fProject, fContainerPath);
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentDialog.java
deleted file mode 100644
index 1ddf5de3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentDialog.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * A dialog to configure the source attachment of a library (class folder, archives
- * and variable entries).
- *
- */
-public class SourceAttachmentDialog extends StatusDialog {
-
- private SourceAttachmentBlock fSourceAttachmentBlock;
-
- /**
- * Creates an instance of the SourceAttachmentDialog. After
- * <code>open</code>, the edited paths can be accessed from
- * the classpath entry returned by <code>getResult</code>
- * @param parent Parent shell for the dialog
- * @param entry The entry to edit.
- */
- public SourceAttachmentDialog(Shell parent, IIncludePathEntry entry) {
- super(parent);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- IStatusChangeListener listener= new IStatusChangeListener() {
- public void statusChanged(IStatus status) {
- updateStatus(status);
- }
- };
- fSourceAttachmentBlock= new SourceAttachmentBlock(listener, entry);
-
- setTitle(NewWizardMessages.SourceAttachmentDialog_title);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite) super.createDialogArea(parent);
-
- Control inner= createSourceAttachmentControls(composite);
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- applyDialogFont(composite);
- return composite;
- }
-
- /**
- * Creates the controls for the source attachment configuration.
- */
- protected Control createSourceAttachmentControls(Composite composite) {
- return fSourceAttachmentBlock.createControl(composite);
- }
-
- /**
- * Returns the configured class path entry
- */
- public IIncludePathEntry getResult() {
- return fSourceAttachmentBlock.getNewEntry();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
deleted file mode 100644
index fc8deb37..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
+++ /dev/null
@@ -1,918 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.TreeListDialogField;
-import org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-public class SourceContainerWorkbookPage extends BuildPathBasePage {
-
- private class OpenBuildPathWizardAction extends AbstractOpenWizardAction implements IPropertyChangeListener {
-
- private final BuildPathWizard fWizard;
- private final List fSelectedElements;
-
- public OpenBuildPathWizardAction(BuildPathWizard wizard) {
- fWizard= wizard;
- addPropertyChangeListener(this);
- fSelectedElements= fFoldersList.getSelectedElements();
- }
-
- /**
- * {@inheritDoc}
- */
- protected INewWizard createWizard() throws CoreException {
- return fWizard;
- }
-
- /**
- * {@inheritDoc}
- */
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(IAction.RESULT)) {
- if (event.getNewValue().equals(Boolean.TRUE)) {
- finishWizard();
- } else {
- fWizard.cancel();
- }
- }
- }
-
- protected void finishWizard() {
- List insertedElements= fWizard.getInsertedElements();
- refresh(insertedElements, fWizard.getRemovedElements(), fWizard.getModifiedElements());
-
- if (insertedElements.isEmpty()) {
- fFoldersList.postSetSelection(new StructuredSelection(fSelectedElements));
- }
- }
-
- }
-
- private static AddSourceFolderWizard newSourceFolderWizard(CPListElement element, List/*<CPListElement>*/ existingElements, String outputLocation, boolean newFolder) {
- CPListElement[] existing= (CPListElement[])existingElements.toArray(new CPListElement[existingElements.size()]);
- AddSourceFolderWizard wizard= new AddSourceFolderWizard(existing, element, false, newFolder, newFolder, newFolder?CPListElement.isProjectSourceFolder(existing, element.getJavaProject()):false, newFolder);
- wizard.setDoFlushChange(false);
- return wizard;
- }
-
- private static AddSourceFolderWizard newLinkedSourceFolderWizard(CPListElement element, List/*<CPListElement>*/ existingElements, String outputLocation, boolean newFolder) {
- CPListElement[] existing= (CPListElement[])existingElements.toArray(new CPListElement[existingElements.size()]);
- AddSourceFolderWizard wizard= new AddSourceFolderWizard(existing, element, true, newFolder, newFolder, newFolder?CPListElement.isProjectSourceFolder(existing, element.getJavaProject()):false, newFolder);
- wizard.setDoFlushChange(false);
- return wizard;
- }
-
- private static EditFilterWizard newEditFilterWizard(CPListElement element, List/*<CPListElement>*/ existingElements, String outputLocation) {
- CPListElement[] existing= (CPListElement[])existingElements.toArray(new CPListElement[existingElements.size()]);
- EditFilterWizard result = new EditFilterWizard(existing, element);
- result.setDoFlushChange(false);
- return result;
- }
-
- private ListDialogField fClassPathList;
- private IJavaScriptProject fCurrJProject;
-
- private Control fSWTControl;
- private TreeListDialogField fFoldersList;
-
- //private StringDialogField fOutputLocationField;
-
- //private SelectionButtonDialogField fUseFolderOutputs;
-
- private final int IDX_ADD= 0;
- private final int IDX_ADD_LINK= 1;
-
- private final int IDX_ADDEXT= 3;
- private final int IDX_ADDJAR= 4;
-
- private final int IDX_ADDVAR= 5;
- private final int IDX_EDIT=7;
- private final int IDX_REMOVE= 8;
-
- public SourceContainerWorkbookPage(ListDialogField classPathList) {
- fClassPathList= classPathList;
-
- //fOutputLocationField= outputLocationField;
-
- fSWTControl= null;
-
- SourceContainerAdapter adapter= new SourceContainerAdapter();
-
- String[] buttonLabels;
-
- buttonLabels= new String[] {
- NewWizardMessages.SourceContainerWorkbookPage_folders_add_button,
- NewWizardMessages.SourceContainerWorkbookPage_folders_link_source_button,
- /* 1 */ null,
- NewWizardMessages.LibrariesWorkbookPage_libraries_addextjar_button,
- NewWizardMessages.LibrariesWorkbookPage_libraries_addjar_button,
- NewWizardMessages.LibrariesWorkbookPage_libraries_addvariable_button,
- null,
- NewWizardMessages.SourceContainerWorkbookPage_folders_edit_button,
- NewWizardMessages.SourceContainerWorkbookPage_folders_remove_button
- };
-
- fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fFoldersList.setDialogFieldListener(adapter);
- fFoldersList.setLabelText(NewWizardMessages.SourceContainerWorkbookPage_folders_label);
-
- fFoldersList.setViewerComparator(new CPListElementSorter());
- fFoldersList.enableButton(IDX_EDIT, false);
- fFoldersList.enableButton(IDX_ADDVAR, false);
-
-// fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
-// fUseFolderOutputs.setSelection(false);
-// fUseFolderOutputs.setLabelText(NewWizardMessages.SourceContainerWorkbookPage_folders_check);
-// fUseFolderOutputs.setDialogFieldListener(adapter);
- }
-
- public void init(IJavaScriptProject jproject) {
- fCurrJProject= jproject;
- if (Display.getCurrent() != null) {
- updateFoldersList();
- } else {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- updateFoldersList();
- }
- });
- }
- }
-
- private void updateFoldersList() {
- if (fSWTControl == null || fSWTControl.isDisposed()) {
- return;
- }
-
- ArrayList folders= new ArrayList();
-
-// boolean useFolderOutputs= false;
- List cpelements= fClassPathList.getElements();
- for (int i= 0; i < cpelements.size(); i++) {
- CPListElement cpe= (CPListElement)cpelements.get(i);
- if (isEntryKind(cpe.getEntryKind()) ) {
- folders.add(cpe);
- }
- }
- fFoldersList.setElements(folders);
- //fUseFolderOutputs.setSelection(useFolderOutputs);
-
- for (int i= 0; i < folders.size(); i++) {
- CPListElement cpe= (CPListElement) folders.get(i);
- IPath[] ePatterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
- IPath[] iPatterns= (IPath[])cpe.getAttribute(CPListElement.INCLUSION);
- if (ePatterns!=null && iPatterns!=null && (ePatterns.length > 0 || iPatterns.length > 0)) {
- fFoldersList.expandElement(cpe, 3);
- }
- }
- }
-
- public Control getControl(Composite parent) {
- PixelConverter converter= new PixelConverter(parent);
- Composite composite= new Composite(parent, SWT.NONE);
-
- //LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs , fOutputLocationField}, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList}, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
-
- int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
- fFoldersList.setButtonsMinWidth(buttonBarWidth);
-
- fSWTControl= composite;
-
- // expand
- List elements= fFoldersList.getElements();
- for (int i= 0; i < elements.size(); i++) {
- CPListElement elem= (CPListElement) elements.get(i);
- IPath[] exclusionPatterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
- IPath[] inclusionPatterns= (IPath[]) elem.getAttribute(CPListElement.INCLUSION);
- if (exclusionPatterns.length > 0 || inclusionPatterns.length > 0) {
- fFoldersList.expandElement(elem, 3);
- }
- }
- return composite;
- }
-
- private Shell getShell() {
- if (fSWTControl != null) {
- return fSWTControl.getShell();
- }
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
-
- private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
-
- private final Object[] EMPTY_ARR= new Object[0];
-
- // -------- IListAdapter --------
- public void customButtonPressed(TreeListDialogField field, int index) {
- sourcePageCustomButtonPressed(field, index);
- }
-
- public void selectionChanged(TreeListDialogField field) {
- sourcePageSelectionChanged(field);
- }
-
- public void doubleClicked(TreeListDialogField field) {
- sourcePageDoubleClicked(field);
- }
-
- public void keyPressed(TreeListDialogField field, KeyEvent event) {
- sourcePageKeyPressed(field, event);
- }
-
- public Object[] getChildren(TreeListDialogField field, Object element) {
- if (element instanceof CPListElement) {
- return ((CPListElement) element).getChildren();
- }
- return EMPTY_ARR;
- }
-
- public Object getParent(TreeListDialogField field, Object element) {
- if (element instanceof CPListElementAttribute) {
- return ((CPListElementAttribute) element).getParent();
- }
- return null;
- }
-
- public boolean hasChildren(TreeListDialogField field, Object element) {
- return (element instanceof CPListElement);
- }
-
- // ---------- IDialogFieldListener --------
- public void dialogFieldChanged(DialogField field) {
- sourcePageDialogFieldChanged(field);
- }
-
- }
-
- protected void sourcePageKeyPressed(TreeListDialogField field, KeyEvent event) {
- if (field == fFoldersList) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- List selection= field.getSelectedElements();
- if (canRemove(selection)) {
- removeEntry();
- }
- }
- }
- }
-
- protected void sourcePageDoubleClicked(TreeListDialogField field) {
- if (field == fFoldersList) {
- List selection= field.getSelectedElements();
- if (canEdit(selection)) {
- editEntry();
- }
- }
- }
-
- protected void sourcePageCustomButtonPressed(DialogField field, int index) {
- CPListElement[] libentries= null;
- if (field == fFoldersList) {
- if (index == IDX_ADD) {
- IProject project= fCurrJProject.getProject();
- if (project.exists() && hasFolders(project)) {
- List existingElements= fFoldersList.getElements();
- CPListElement[] existing= (CPListElement[])existingElements.toArray(new CPListElement[existingElements.size()]);
- CreateMultipleSourceFoldersDialog dialog= new CreateMultipleSourceFoldersDialog(fCurrJProject, existing, "", getShell()); //$NON-NLS-1$
- if (dialog.open() == Window.OK) {
- refresh(dialog.getInsertedElements(), dialog.getRemovedElements(), dialog.getModifiedElements());
- }
- } else {
- CPListElement newElement= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_SOURCE);
- AddSourceFolderWizard wizard= newSourceFolderWizard(newElement, fFoldersList.getElements(), "", true); //$NON-NLS-1$
- OpenBuildPathWizardAction action= new OpenBuildPathWizardAction(wizard);
- action.run();
- }
- } else if (index == IDX_ADD_LINK) {
- CPListElement newElement= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_SOURCE);
- AddSourceFolderWizard wizard= newLinkedSourceFolderWizard(newElement, fFoldersList.getElements(), "", true); //$NON-NLS-1$
- OpenBuildPathWizardAction action= new OpenBuildPathWizardAction(wizard);
- action.run();
- } else if (index==IDX_ADDJAR) {
- libentries= openJarFileDialog(null);
- }else if (index==IDX_ADDEXT) {
- libentries= openExtJarFileDialog(null);
-
- }
-
- else if (index == IDX_EDIT) {
- editEntry();
- } else if (index == IDX_REMOVE) {
- removeEntry();
- }
- }
-
- if (libentries != null) {
- int nElementsChosen= libentries.length;
- // remove duplicates
- List cplist= fClassPathList.getElements();
- List elementsToAdd= new ArrayList(nElementsChosen);
-
- for (int i= 0; i < nElementsChosen; i++) {
- CPListElement curr= libentries[i];
- if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
- elementsToAdd.add(curr);
- curr.setAttribute(CPListElement.JAVADOC, BuildPathSupport.guessJavadocLocation(curr));
- }
- }
- refresh(elementsToAdd,null,null);
-
- fClassPathList.addElements(elementsToAdd);
- // || index == IDX_ADDVAR
-
- fClassPathList.postSetSelection(new StructuredSelection(libentries));
-// if (index == IDX_ADDJAR || index == IDX_ADDVAR || index==IDX_ADDEXT) {
-// fClassPathList.refresh();
-// }
- }
- }
- private CPListElement[] openJarFileDialog(CPListElement existing) {
- IWorkspaceRoot root= fCurrJProject.getProject().getWorkspace().getRoot();
-
- if (existing == null) {
- IPath[] selected= BuildPathDialogAccess.chooseJAREntries(getShell(), fCurrJProject.getPath(), getUsedJARFiles(existing));
- if (selected != null) {
- ArrayList res= new ArrayList();
-
- for (int i= 0; i < selected.length; i++) {
- IPath curr= selected[i];
- IResource resource= root.findMember(curr);
- if (resource instanceof IFile) {
- res.add(newCPLibraryElement(resource));
- }
- }
- return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
- }
- } else {
- IPath configured= BuildPathDialogAccess.configureJAREntry(getShell(), existing.getPath(), getUsedJARFiles(existing));
- if (configured != null) {
- IResource resource= root.findMember(configured);
- if (resource instanceof IFile) {
- return new CPListElement[] { newCPLibraryElement(resource) };
- }
- }
- }
- return null;
- }
-
-
- private CPListElement[] openExtJarFileDialog(CPListElement existing) {
- CPListElement tempElem=null;
- if (existing == null) {
- IPath[] selected= BuildPathDialogAccess.chooseExternalJAREntries(getShell());
- if (selected != null) {
- ArrayList res= new ArrayList();
- for (int i= 0; i < selected.length; i++) {
- tempElem = new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, selected[i], null);
- tempElem.setExported(true);
- res.add(tempElem);
- }
- return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
- }
- } else {
- IPath configured= BuildPathDialogAccess.configureExternalJAREntry(getShell(), existing.getPath());
- if (configured != null) {
- tempElem = new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, configured, null);
- tempElem.setExported(true);
- return new CPListElement[] { tempElem };
- }
- }
- return null;
- }
-
- private IPath[] getUsedJARFiles(CPListElement existing) {
- List res= new ArrayList();
- List cplist= fFoldersList.getElements();
- for (int i= 0; i < cplist.size(); i++) {
- CPListElement elem= (CPListElement)cplist.get(i);
- //
- if ( elem.getEntryKind() == IIncludePathEntry.CPE_LIBRARY && (elem != existing)) {
- IResource resource= elem.getResource();
- if (resource instanceof IFile) {
- res.add(resource.getFullPath());
- }else if (resource instanceof IPath) {
- res.add(resource);
- }
- }
- }
- return (IPath[]) res.toArray(new IPath[res.size()]);
- }
- private CPListElement newCPLibraryElement(IResource res) {
- CPListElement elem= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_LIBRARY, res.getFullPath(), res);
- elem.setExported(true);
- return elem;
- }
-
- private boolean hasFolders(IContainer container) {
-
- try {
- IResource[] members= container.members();
- for (int i= 0; i < members.length; i++) {
- if (members[i] instanceof IContainer) {
- return true;
- }
- }
- } catch (CoreException e) {
- // ignore
- }
-
- List elements= fFoldersList.getElements();
- if (elements.size() > 1)
- return true;
-
- if (elements.size() == 0)
- return false;
-
- CPListElement single= (CPListElement)elements.get(0);
- if (single.getPath().equals(fCurrJProject.getPath()))
- return false;
-
- return true;
- }
-
- private void editEntry() {
- List selElements= fFoldersList.getSelectedElements();
- if (selElements.size() != 1) {
- return;
- }
- Object elem= selElements.get(0);
- if (fFoldersList.getIndexOfElement(elem) != -1) {
- editElementEntry((CPListElement) elem);
- } else if (elem instanceof CPListElementAttribute) {
- editAttributeEntry((CPListElementAttribute) elem);
- }
- }
-
- private void editElementEntry(CPListElement elem) {
- CPListElement[] res= null;
-
-
- if(elem.getEntryKind()== IIncludePathEntry.CPE_CONTAINER) {
- res= openContainerSelectionDialog(elem);
- }else if(elem.getEntryKind()== IIncludePathEntry.CPE_LIBRARY) {
- IResource resource= elem.getResource();
- if (resource == null) {
- res= openExtJarFileDialog(elem);
- } else if (resource.getType() == IResource.FOLDER) {
- if (resource.exists()) {
- res= openClassFolderDialog(elem);
- } else {
- res= openNewClassFolderDialog(elem);
- }
- } else if (resource.getType() == IResource.FILE) {
- res= openJarFileDialog(elem);
- }
- }if (elem.getLinkTarget() != null) {
- AddSourceFolderWizard wizard= newLinkedSourceFolderWizard(elem, fFoldersList.getElements(), "", false); //$NON-NLS-1$
- OpenBuildPathWizardAction action= new OpenBuildPathWizardAction(wizard);
- action.run();
- } else {
- AddSourceFolderWizard wizard= newSourceFolderWizard(elem, fFoldersList.getElements(), "", false); //$NON-NLS-1$
- OpenBuildPathWizardAction action= new OpenBuildPathWizardAction(wizard);
- action.run();
- }
-
- if (res != null && res.length > 0) {
- CPListElement curr= res[0];
- curr.setExported(elem.isExported());
- curr.setAttributesFromExisting(elem);
- ArrayList removed = new ArrayList(0);
- ArrayList added = new ArrayList(0);
- removed.add(curr);
- added.add(elem);
- //fLibrariesList.replaceElement(elem, curr);
- refresh(added,removed,null);
-
- }
- }
- private CPListElement[] openNewClassFolderDialog(CPListElement existing) {
- String title= (existing == null) ? NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_new_title : NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_edit_title;
- IProject currProject= fCurrJProject.getProject();
-
- NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing);
- IPath projpath= currProject.getFullPath();
- dialog.setMessage(Messages.format(NewWizardMessages.LibrariesWorkbookPage_NewClassFolderDialog_description, projpath.toString()));
- if (dialog.open() == Window.OK) {
- IFolder folder= dialog.getFolder();
- return new CPListElement[] { newCPLibraryElement(folder) };
- }
- return null;
- }
- private IPath[] getUsedContainers(CPListElement existing) {
- ArrayList res= new ArrayList();
-
- List cplist= fFoldersList.getElements();
- for (int i= 0; i < cplist.size(); i++) {
- CPListElement elem= (CPListElement)cplist.get(i);
- if (elem.getEntryKind() == IIncludePathEntry.CPE_LIBRARY && (elem != existing)) {
- IResource resource= elem.getResource();
- if (resource instanceof IContainer && !resource.equals(existing)) {
- res.add(resource.getFullPath());
- }
- }
- }
- return (IPath[]) res.toArray(new IPath[res.size()]);
- }
- private CPListElement[] openClassFolderDialog(CPListElement existing) {
- if (existing == null) {
- IPath[] selected= BuildPathDialogAccess.chooseClassFolderEntries(getShell(), fCurrJProject.getPath(), getUsedContainers(existing));
- if (selected != null) {
- IWorkspaceRoot root= fCurrJProject.getProject().getWorkspace().getRoot();
- ArrayList res= new ArrayList();
- for (int i= 0; i < selected.length; i++) {
- IPath curr= selected[i];
- IResource resource= root.findMember(curr);
- if (resource instanceof IContainer) {
- res.add(newCPLibraryElement(resource));
- }
- }
- return (CPListElement[]) res.toArray(new CPListElement[res.size()]);
- }
- } else {
- // disabled
- }
- return null;
- }
-
- private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
- if (existing == null) {
- IIncludePathEntry[] created= BuildPathDialogAccess.chooseContainerEntries(getShell(), fCurrJProject, getRawClasspath());
- if (created != null) {
- CPListElement[] res= new CPListElement[created.length];
- for (int i= 0; i < res.length; i++) {
- res[i]= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created[i].getPath(), null);
- }
- return res;
- }
- } else {
- IIncludePathEntry created= BuildPathDialogAccess.configureContainerEntry(getShell(), existing.getClasspathEntry(), fCurrJProject, getRawClasspath());
- if (created != null) {
- CPListElement elem= new CPListElement(fCurrJProject, IIncludePathEntry.CPE_CONTAINER, created.getPath(), null);
- return new CPListElement[] { elem };
- }
- }
- return null;
- }
-
- private IIncludePathEntry[] getRawClasspath() {
- IIncludePathEntry[] currEntries= new IIncludePathEntry[fClassPathList.getSize()];
- for (int i= 0; i < currEntries.length; i++) {
- CPListElement curr= (CPListElement) fClassPathList.getElement(i);
- currEntries[i]= curr.getClasspathEntry();
- }
- return currEntries;
- }
- private void attributeUpdated(CPListElement selElement, String[] changedAttributes) {
- Object parentContainer= selElement.getParentContainer();
- if (parentContainer instanceof CPListElement) { // inside a container: apply changes right away
- IIncludePathEntry updatedEntry= selElement.getClasspathEntry();
- updateContainerEntry(updatedEntry, changedAttributes, fCurrJProject, ((CPListElement) parentContainer).getPath());
- }
- }
-
- private void updateContainerEntry(final IIncludePathEntry newEntry, final String[] changedAttributes, final IJavaScriptProject jproject, final IPath containerPath) {
- try {
- IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- BuildPathSupport.modifyClasspathEntry(null, newEntry, changedAttributes, jproject, containerPath, monitor);
- }
- };
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(runnable));
-
- } catch (InvocationTargetException e) {
- String title= NewWizardMessages.LibrariesWorkbookPage_configurecontainer_error_title;
- String message= NewWizardMessages.LibrariesWorkbookPage_configurecontainer_error_message;
- ExceptionHandler.handle(e, getShell(), title, message);
- } catch (InterruptedException e) {
- //
- }
- }
-
- private void editAttributeEntry(CPListElementAttribute elem) {
- String key= elem.getKey();
-
- CPListElement selElement= elem.getParent();
-
- if (key.equals(CPListElement.ACCESSRULES)) {
- AccessRulesDialog dialog= new AccessRulesDialog(getShell(), selElement, fCurrJProject, false);
- int res= dialog.open();
- if (res == Window.OK || res == AccessRulesDialog.SWITCH_PAGE) {
- selElement.setAttribute(CPListElement.ACCESSRULES, dialog.getAccessRules());
- String[] changedAttributes= { CPListElement.ACCESSRULES };
- attributeUpdated(selElement, changedAttributes);
-
- fFoldersList.refresh(elem);
- fClassPathList.dialogFieldChanged(); // validate
- updateEnabledState();
-
-// if (res == AccessRulesDialog.SWITCH_PAGE) { // switch after updates and validation
-// dialog.performPageSwitch(fPageContainer);
-// }
- }
-// } else if (key.equals(CPListElement.OUTPUT)) {
-// //CPListElement selElement= elem.getParent();
-// OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement, fClassPathList.getElements(), new Path("").makeAbsolute(), true); //$NON-NLS-1$
-// if (dialog.open() == Window.OK) {
-// selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
-// fFoldersList.refresh();
-// fClassPathList.dialogFieldChanged(); // validate
-// }
- } else if (key.equals(CPListElement.EXCLUSION) || key.equals(CPListElement.INCLUSION)) {
- EditFilterWizard wizard= newEditFilterWizard(elem.getParent(), fFoldersList.getElements(), ""); //$NON-NLS-1$
- OpenBuildPathWizardAction action= new OpenBuildPathWizardAction(wizard);
- action.run();
- } else {
- if (editCustomAttribute(getShell(), elem)) {
- fFoldersList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
- }
- }
- }
-
- protected void sourcePageSelectionChanged(DialogField field) {
- List selected= fFoldersList.getSelectedElements();
- fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
- fFoldersList.enableButton(IDX_REMOVE, canRemove(selected));
- boolean noAttributes= containsOnlyTopLevelEntries(selected);
- fFoldersList.enableButton(IDX_ADD, noAttributes);
- }
-
- private void removeEntry() {
- List selElements= fFoldersList.getSelectedElements();
- for (int i= selElements.size() - 1; i >= 0 ; i--) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- String key= attrib.getKey();
- if (attrib.isBuiltIn()) {
- Object value= null;
- if (key.equals(CPListElement.EXCLUSION) || key.equals(CPListElement.INCLUSION)) {
- value= new Path[0];
- }
- attrib.getParent().setAttribute(key, value);
- } else {
- removeCustomAttribute(attrib);
- }
- selElements.remove(i);
- }
- }
- if (selElements.isEmpty()) {
- fFoldersList.refresh();
- fClassPathList.dialogFieldChanged(); // validate
- } else {
- for (Iterator iter= selElements.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- if (element.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- List list= ClasspathModifier.removeFilters(element.getPath(), fCurrJProject, fFoldersList.getElements());
- for (Iterator iterator= list.iterator(); iterator.hasNext();) {
- CPListElement modified= (CPListElement)iterator.next();
- fFoldersList.refresh(modified);
- fFoldersList.expandElement(modified, 3);
- }
- }
- }
- fFoldersList.removeElements(selElements);
- }
- }
-
- private boolean canRemove(List selElements) {
- if (selElements.size() == 0) {
- return false;
- }
- for (int i= 0; i < selElements.size(); i++) {
- Object elem= selElements.get(i);
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- String key= attrib.getKey();
- if (attrib.isBuiltIn()) {
- if (CPListElement.INCLUSION.equals(key)) {
- if (((IPath[]) attrib.getValue()).length == 0) {
- return false;
- }
- } else if (CPListElement.EXCLUSION.equals(key)) {
- if (((IPath[]) attrib.getValue()).length == 0) {
- return false;
- }
- } else if (attrib.getValue() == null) {
- return false;
- }
- } else {
- if (!canRemoveCustomAttribute(attrib)) {
- return false;
- }
- }
- } else if (elem instanceof CPListElement) {
- CPListElement curr= (CPListElement) elem;
- if (curr.getParentContainer() != null) {
- return false;
- }
- }
- }
- return true;
- }
-
- private boolean canEdit(List selElements) {
- if (selElements.size() != 1) {
- return false;
- }
- Object elem= selElements.get(0);
- if (elem instanceof CPListElement) {
- CPListElement cp= ((CPListElement)elem);
- if (cp.getPath().equals(cp.getJavaProject().getPath()))
- return false;
-
- return true;
- }
- if (elem instanceof CPListElementAttribute) {
- CPListElementAttribute attrib= (CPListElementAttribute) elem;
- if (attrib.isBuiltIn()) {
- return true;
- } else {
- return canEditCustomAttribute(attrib);
- }
- }
- return false;
- }
-
- private void sourcePageDialogFieldChanged(DialogField field) {
- if (fCurrJProject == null) {
- // not initialized
- return;
- }
-
-// if (field == fUseFolderOutputs) {
-// if (!fUseFolderOutputs.isSelected()) {
-// int nFolders= fFoldersList.getSize();
-// for (int i= 0; i < nFolders; i++) {
-// CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
-// cpe.setAttribute(CPListElement.OUTPUT, null);
-// }
-// }
-// fFoldersList.refresh();
-// } else
-
- if (field == fFoldersList) {
- updateClasspathList();
- }
- }
-
-
- private void updateClasspathList() {
- List srcelements= fFoldersList.getElements();
-
- List cpelements= fClassPathList.getElements();
- int nEntries= cpelements.size();
- // backwards, as entries will be deleted
- int lastRemovePos= nEntries;
- int afterLastSourcePos= 0;
- for (int i= nEntries - 1; i >= 0; i--) {
- CPListElement cpe= (CPListElement)cpelements.get(i);
- int kind= cpe.getEntryKind();
- if (isEntryKind(kind)) {
- if (!srcelements.remove(cpe)) {
- cpelements.remove(i);
- lastRemovePos= i;
- } else if (lastRemovePos == nEntries) {
- afterLastSourcePos= i + 1;
- }
- }
- }
-
- if (!srcelements.isEmpty()) {
- int insertPos= Math.min(afterLastSourcePos, lastRemovePos);
- cpelements.addAll(insertPos, srcelements);
- }
-
- if (lastRemovePos != nEntries || !srcelements.isEmpty()) {
- fClassPathList.setElements(cpelements);
- }
- }
-
- /*
- * @see BuildPathBasePage#getSelection
- */
- public List getSelection() {
- return fFoldersList.getSelectedElements();
- }
-
- /*
- * @see BuildPathBasePage#setSelection
- */
- public void setSelection(List selElements, boolean expand) {
- fFoldersList.selectElements(new StructuredSelection(selElements));
- if (expand) {
- for (int i= 0; i < selElements.size(); i++) {
- fFoldersList.expandElement(selElements.get(i), 1);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
- */
- public boolean isEntryKind(int kind) {
- return (kind == IIncludePathEntry.CPE_SOURCE || kind==IIncludePathEntry.CPE_LIBRARY || kind==IIncludePathEntry.CPE_VARIABLE);
- }
-
- private void refresh(List insertedElements, List removedElements, List modifiedElements) {
- if (removedElements==null)
- removedElements=new ArrayList();
- if (modifiedElements==null)
- modifiedElements=new ArrayList();
- fFoldersList.addElements(insertedElements);
- for (Iterator iter= insertedElements.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- fFoldersList.expandElement(element, 3);
- }
-
- fFoldersList.removeElements(removedElements);
-
- for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
- CPListElement element= (CPListElement)iter.next();
- fFoldersList.refresh(element);
- fFoldersList.expandElement(element, 3);
- }
-
- fFoldersList.refresh(); //does enforce the order of the entries.
- if (!insertedElements.isEmpty()) {
- fFoldersList.postSetSelection(new StructuredSelection(insertedElements));
- }
-
- //fOutputLocationField.setText(outputLocation.makeRelative().toOSString());
- }
- private void updateEnabledState() {
- List selElements= fFoldersList.getSelectedElements();
- fFoldersList.enableButton(IDX_EDIT, canEdit(selElements));
- fFoldersList.enableButton(IDX_REMOVE, canRemove(selElements));
- //fFoldersList.enableButton(IDX_REPLACE, getSelectedPackageFragmentRoot() != null);
-
-// boolean noAttributes= containsOnlyTopLevelEntries(selElements);
- //fLibrariesList.enableButton(IDX_ADDEXT, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDFOL, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDJAR, noAttributes);
- //fFoldersList.enableButton(IDX_ADDLIB, noAttributes);
- //fLibrariesList.enableButton(IDX_ADDVAR, noAttributes);
- }
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
- fFoldersList.setFocus();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryMarkerResolutionGenerator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryMarkerResolutionGenerator.java
deleted file mode 100644
index d8e56ebe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryMarkerResolutionGenerator.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IMarkerResolutionGenerator;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.CorrectionEngine;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelMarker;
-import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BuildPathsPropertyPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.UserLibraryPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.CorrectionMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-public class UserLibraryMarkerResolutionGenerator implements IMarkerResolutionGenerator, IMarkerResolutionGenerator2 {
-
- private final static IMarkerResolution[] NO_RESOLUTION = new IMarkerResolution[0];
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolutionGenerator2#hasResolutions(org.eclipse.core.resources.IMarker)
- */
- public boolean hasResolutions(IMarker marker) {
- int id= marker.getAttribute(IJavaScriptModelMarker.ID, -1);
- if (id == IJavaScriptModelStatusConstants.CP_CONTAINER_PATH_UNBOUND
- || id == IJavaScriptModelStatusConstants.CP_VARIABLE_PATH_UNBOUND
- || id == IJavaScriptModelStatusConstants.INVALID_CP_CONTAINER_ENTRY
- || id == IJavaScriptModelStatusConstants.DEPRECATED_VARIABLE
- || id == IJavaScriptModelStatusConstants.INVALID_INCLUDEPATH) {
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolutionGenerator#getResolutions(org.eclipse.core.resources.IMarker)
- */
- public IMarkerResolution[] getResolutions(IMarker marker) {
- final Shell shell= JavaScriptPlugin.getActiveWorkbenchShell();
- if (!hasResolutions(marker) || shell == null) {
- return NO_RESOLUTION;
- }
-
- ArrayList resolutions= new ArrayList();
-
- final IJavaScriptProject project= getJavaProject(marker);
-
- int id= marker.getAttribute(IJavaScriptModelMarker.ID, -1);
- if (id == IJavaScriptModelStatusConstants.CP_CONTAINER_PATH_UNBOUND) {
- String[] arguments= CorrectionEngine.getProblemArguments(marker);
- final IPath path= new Path(arguments[0]);
-
- if (path.segment(0).equals(JavaScriptCore.USER_LIBRARY_CONTAINER_ID)) {
- String label= NewWizardMessages.UserLibraryMarkerResolutionGenerator_changetouserlib_label;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME);
- resolutions.add(new UserLibraryMarkerResolution(label, image) {
- public void run(IMarker m) {
- changeToExistingLibrary(shell, path, false, project);
- }
- });
- if (path.segmentCount() == 2) {
- String label2= Messages.format(NewWizardMessages.UserLibraryMarkerResolutionGenerator_createuserlib_label, path.segment(1));
- Image image2= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
- resolutions.add(new UserLibraryMarkerResolution(label2, image2) {
- public void run(IMarker m) {
- createUserLibrary(shell, path, project);
- }
- });
- }
- }
- String label= NewWizardMessages.UserLibraryMarkerResolutionGenerator_changetoother;
- Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME);
- resolutions.add(new UserLibraryMarkerResolution(label, image) {
- public void run(IMarker m) {
- changeToExistingLibrary(shell, path, true, project);
- }
- });
- }
-
- if (project != null) {
- resolutions.add(new OpenBuildPathMarkerResolution(project));
- }
-
- return (IMarkerResolution[]) resolutions.toArray(new IMarkerResolution[resolutions.size()]);
- }
-
- protected void changeToExistingLibrary(Shell shell, IPath path, boolean isNew, final IJavaScriptProject project) {
- try {
- IIncludePathEntry[] entries= project.getRawIncludepath();
- int idx= indexOfClasspath(entries, path);
- if (idx == -1) {
- return;
- }
- IIncludePathEntry[] res;
- if (isNew) {
- res= BuildPathDialogAccess.chooseContainerEntries(shell, project, entries);
- if (res == null) {
- return;
- }
- } else {
- IIncludePathEntry resEntry= BuildPathDialogAccess.configureContainerEntry(shell, entries[idx], project, entries);
- if (resEntry == null) {
- return;
- }
- res= new IIncludePathEntry[] { resEntry };
- }
- final IIncludePathEntry[] newEntries= new IIncludePathEntry[entries.length - 1 + res.length];
- System.arraycopy(entries, 0, newEntries, 0, idx);
- System.arraycopy(res, 0, newEntries, idx, res.length);
- System.arraycopy(entries, idx + 1, newEntries, idx + res.length, entries.length - idx - 1);
-
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null) {
- context= PlatformUI.getWorkbench().getProgressService();
- }
- context.run(true, true, new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- project.setRawIncludepath(newEntries, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- });
- } catch (JavaScriptModelException e) {
- String title= NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_title;
- String message= NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_creationfailed_message;
- ExceptionHandler.handle(e, shell, title, message);
- } catch (InvocationTargetException e) {
- String title= NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_title;
- String message= NewWizardMessages.UserLibraryMarkerResolutionGenerator_error_applyingfailed_message;
- ExceptionHandler.handle(e, shell, title, message);
- } catch (InterruptedException e) {
- // user cancelled
- }
- }
-
- private int indexOfClasspath(IIncludePathEntry[] entries, IPath path) {
- for (int i= 0; i < entries.length; i++) {
- IIncludePathEntry curr= entries[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_CONTAINER && curr.getPath().equals(path)) {
- return i;
- }
- }
- return -1;
- }
-
- protected void createUserLibrary(final Shell shell, IPath unboundPath, IJavaScriptProject project) {
- String name= unboundPath.segment(1);
- String id= UserLibraryPreferencePage.ID;
- HashMap data= new HashMap(3);
- data.put(UserLibraryPreferencePage.DATA_LIBRARY_TO_SELECT, name);
- data.put(UserLibraryPreferencePage.DATA_DO_CREATE, Boolean.TRUE);
- PreferencesUtil.createPreferenceDialogOn(shell, id, new String[] { id }, data).open();
- }
-
- private IJavaScriptProject getJavaProject(IMarker marker) {
- return JavaScriptCore.create(marker.getResource().getProject());
- }
-
- /**
- * Library quick fix base class
- */
- private static abstract class UserLibraryMarkerResolution implements IMarkerResolution, IMarkerResolution2 {
-
- private String fLabel;
- private Image fImage;
-
- public UserLibraryMarkerResolution(String label, Image image) {
- fLabel= label;
- fImage= image;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolution#getLabel()
- */
- public String getLabel() {
- return fLabel;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolution2#getDescription()
- */
- public String getDescription() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IMarkerResolution2#getImage()
- */
- public Image getImage() {
- return fImage;
- }
- }
-
- private static class OpenBuildPathMarkerResolution implements IMarkerResolution2 {
- private IJavaScriptProject fProject;
-
- public OpenBuildPathMarkerResolution(IJavaScriptProject project) {
- fProject= project;
- }
-
- public String getDescription() {
- return Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_configure_buildpath_description, fProject.getElementName());
- }
-
- public Image getImage() {
- return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_ACCESSRULES_ATTRIB);
- }
-
- public String getLabel() {
- return CorrectionMessages.ReorgCorrectionsSubProcessor_configure_buildpath_label;
- }
-
- public void run(IMarker marker) {
- PreferencesUtil.createPropertyDialogOn(JavaScriptPlugin.getActiveWorkbenchShell(), fProject, BuildPathsPropertyPage.PROP_ID, null, null).open();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java
deleted file mode 100644
index 493c3815..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java
+++ /dev/null
@@ -1,326 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.preferences.UserLibraryPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension;
-import org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension2;
-import org.eclipse.wst.jsdt.ui.wizards.NewElementWizardPage;
-
-import com.ibm.icu.text.Collator;
-
-/**
- *
- */
-public class UserLibraryWizardPage extends NewElementWizardPage implements IJsGlobalScopeContainerPage, IJsGlobalScopeContainerPageExtension, IJsGlobalScopeContainerPageExtension2 {
-
- private IJavaScriptProject fProject;
-
- private CheckedListDialogField fLibrarySelector;
- private CPUserLibraryElement fEditResult;
- private Set fUsedPaths;
-
- private boolean fIsEditMode;
- private boolean fIsExported;
-
- public UserLibraryWizardPage() {
- super("UserLibraryWizardPage"); //$NON-NLS-1$
- setTitle(NewWizardMessages.UserLibraryWizardPage_title);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY);
- updateDescription(null);
- fUsedPaths= new HashSet();
- fProject= createPlaceholderProject();
-
- LibraryListAdapter adapter= new LibraryListAdapter();
- String[] buttonLabels= new String[] {
- NewWizardMessages.UserLibraryWizardPage_list_config_button
- };
- fLibrarySelector= new CheckedListDialogField(adapter, buttonLabels, new CPListLabelProvider());
- fLibrarySelector.setDialogFieldListener(adapter);
- fLibrarySelector.setLabelText(NewWizardMessages.UserLibraryWizardPage_list_label);
- fEditResult= null;
- updateStatus(validateSetting(Collections.EMPTY_LIST));
- }
-
- private static IJavaScriptProject createPlaceholderProject() {
- String name= "####internal"; //$NON-NLS-1$
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- while (true) {
- IProject project= root.getProject(name);
- if (!project.exists()) {
- return JavaScriptCore.create(project);
- }
- name += '1';
- }
- }
-
- private void updateDescription(IIncludePathEntry containerEntry) {
- if (containerEntry == null || containerEntry.getPath().segmentCount() != 2) {
- setDescription(NewWizardMessages.UserLibraryWizardPage_description_new);
- } else {
- setDescription(Messages.format(NewWizardMessages.UserLibraryWizardPage_description_edit, containerEntry.getPath().segment(1)));
- }
- }
-
- private List updateLibraryList() {
- HashSet oldNames= new HashSet();
- HashSet oldCheckedNames= new HashSet();
- List oldElements= fLibrarySelector.getElements();
- for (int i= 0; i < oldElements.size(); i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) oldElements.get(i);
- oldNames.add(curr.getName());
- if (fLibrarySelector.isChecked(curr)) {
- oldCheckedNames.add(curr.getName());
- }
- }
-
- ArrayList entriesToCheck= new ArrayList();
-
- String[] names= JavaScriptCore.getUserLibraryNames();
- Arrays.sort(names, Collator.getInstance());
-
- ArrayList elements= new ArrayList(names.length);
- for (int i= 0; i < names.length; i++) {
- String curr= names[i];
- IPath path= new Path(JavaScriptCore.USER_LIBRARY_CONTAINER_ID).append(curr);
- try {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(path, fProject);
- CPUserLibraryElement elem= new CPUserLibraryElement(curr, container, fProject);
- elements.add(elem);
- if (!oldCheckedNames.isEmpty()) {
- if (oldCheckedNames.contains(curr)) {
- entriesToCheck.add(elem);
- }
- } else {
- if (!oldNames.contains(curr)) {
- entriesToCheck.add(elem);
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- // ignore
- }
- }
- fLibrarySelector.setElements(elements);
- return entriesToCheck;
- }
-
- private void doDialogFieldChanged(DialogField field) {
- if (field == fLibrarySelector) {
- List list= fLibrarySelector.getCheckedElements();
- if (fIsEditMode) {
- if (list.size() > 1) {
- if (fEditResult != null && list.remove(fEditResult)) {
- fLibrarySelector.setCheckedWithoutUpdate(fEditResult, false);
- }
- fEditResult= (CPUserLibraryElement) list.get(0); // take the first
- for (int i= 1; i < list.size(); i++) { // uncheck the rest
- fLibrarySelector.setCheckedWithoutUpdate(list.get(i), false);
- }
- } else if (list.size() == 1) {
- fEditResult= (CPUserLibraryElement) list.get(0);
- }
- }
- updateStatus(validateSetting(list));
- }
- }
-
- private IStatus validateSetting(List selected) {
- int nSelected= selected.size();
- if (nSelected == 0) {
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.UserLibraryWizardPage_error_selectentry);
- } else if (fIsEditMode && nSelected > 1) {
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.UserLibraryWizardPage_error_selectonlyone);
- }
- for (int i= 0; i < selected.size(); i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) selected.get(i);
- if (fUsedPaths.contains(curr.getPath())) {
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.UserLibraryWizardPage_error_alreadyoncp);
- }
- }
- return new StatusInfo();
- }
-
- private void doButtonPressed(int index) {
- if (index == 0) {
- HashMap data= new HashMap(3);
- if (fEditResult != null) {
- data.put(UserLibraryPreferencePage.DATA_LIBRARY_TO_SELECT, fEditResult.getName());
- }
- String id= UserLibraryPreferencePage.ID;
- PreferencesUtil.createPreferenceDialogOn(getShell(), id, new String[] { id }, data).open();
-
- List newEntries= updateLibraryList();
- if (newEntries.size() > 0) {
- if (fIsEditMode) {
- fLibrarySelector.setChecked(newEntries.get(0), true);
- } else {
- fLibrarySelector.setCheckedElements(newEntries);
- }
- }
- } else {
- fLibrarySelector.setCheckedElements(fLibrarySelector.getSelectedElements());
- }
- }
-
- private void doDoubleClicked(ListDialogField field) {
- List list= fLibrarySelector.getSelectedElements();
- if (list.size() == 1) {
- Object elem= list.get(0);
- boolean state= fLibrarySelector.isChecked(elem);
- if (!state || !fIsEditMode) {
- fLibrarySelector.setChecked(elem, !state);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrarySelector }, true, SWT.DEFAULT, SWT.DEFAULT);
- LayoutUtil.setHorizontalGrabbing(fLibrarySelector.getListControl(null));
- Dialog.applyDialogFont(composite);
- setControl(composite);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage#finish()
- */
- public boolean finish() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage#getSelection()
- */
- public IIncludePathEntry getSelection() {
- if (fEditResult != null) {
- return JavaScriptCore.newContainerEntry(fEditResult.getPath(), fIsExported);
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension2#getNewContainers()
- */
- public IIncludePathEntry[] getNewContainers() {
- List selected= fLibrarySelector.getCheckedElements();
- IIncludePathEntry[] res= new IIncludePathEntry[selected.size()];
- for (int i= 0; i < res.length; i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) selected.get(i);
- res[i]= JavaScriptCore.newContainerEntry(curr.getPath(), fIsExported);
- }
- return res;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPage#setSelection(org.eclipse.wst.jsdt.core.IIncludePathEntry)
- */
- public void setSelection(IIncludePathEntry containerEntry) {
- fIsExported= containerEntry != null && containerEntry.isExported();
-
- updateDescription(containerEntry);
- fIsEditMode= (containerEntry != null);
- if (fIsEditMode) {
- fUsedPaths.remove(containerEntry.getPath());
- }
-
- String selected= null;
- if (containerEntry != null && containerEntry.getPath().segmentCount() == 2) {
- selected= containerEntry.getPath().segment(1);
- } else {
- // get from dialog store
- }
- updateLibraryList();
- if (selected != null) {
- List elements= fLibrarySelector.getElements();
- for (int i= 0; i < elements.size(); i++) {
- CPUserLibraryElement curr= (CPUserLibraryElement) elements.get(i);
- if (curr.getName().equals(selected)) {
- fLibrarySelector.setChecked(curr, true);
- return;
- }
- }
- }
- }
-
- private class LibraryListAdapter implements IListAdapter, IDialogFieldListener {
-
- public LibraryListAdapter() {
- }
-
- public void dialogFieldChanged(DialogField field) {
- doDialogFieldChanged(field);
- }
-
- public void customButtonPressed(ListDialogField field, int index) {
- doButtonPressed(index);
- }
-
- public void selectionChanged(ListDialogField field) {
- }
-
- public void doubleClicked(ListDialogField field) {
- doDoubleClicked(field);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.wizards.IJsGlobalScopeContainerPageExtension#initialize(org.eclipse.wst.jsdt.core.IJavaScriptProject, org.eclipse.wst.jsdt.core.IIncludePathEntry[])
- */
- public void initialize(IJavaScriptProject project, IIncludePathEntry[] currentEntries) {
- for (int i= 0; i < currentEntries.length; i++) {
- IIncludePathEntry curr= currentEntries[i];
- if (curr.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- fUsedPaths.add(curr.getPath());
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java
deleted file mode 100644
index 677241ef..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-/**
- * The action that is run to add a project or a folder to the the build path as a source folder. Is enabled only if
- * the selected item can be added as a source folder and is not already a source folder.
- *
- */
-public class AddFolderToBuildpathAction extends BuildpathModifierAction {
-
- private final IRunnableContext fContext;
-
- public AddFolderToBuildpathAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public AddFolderToBuildpathAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private AddFolderToBuildpathAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.ADD_SEL_SF_TO_BP);
-
- fContext= context;
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_label);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_ADD_AS_SOURCE_FOLDER);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_AddSelSFToCP_tooltip);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (!isEnabled())
- return null;
-
- if (getSelectedElements().size() != 1)
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_toBuildpath;
-
- Object obj= getSelectedElements().get(0);
- if (obj instanceof IJavaScriptProject) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_ProjectToBuildpath, ((IJavaScriptProject)obj).getElementName());
- } else if (obj instanceof IPackageFragment) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_PackageToBuildpath, ((IPackageFragment)obj).getElementName());
- } else if (obj instanceof IResource) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_FolderToBuildpath, ((IResource)obj).getName());
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- try {
- final IJavaScriptProject project;
- Object object= getSelectedElements().get(0);
- if (object instanceof IJavaScriptProject) {
- project= (IJavaScriptProject)object;
- } else if (object instanceof IPackageFragment) {
- project= ((IPackageFragment)object).getJavaScriptProject();
- } else {
- IFolder folder= (IFolder)object;
- project= JavaScriptCore.create(folder.getProject());
- if (project == null)
- return;
- }
-
- final IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- List result= addToClasspath(getSelectedElements(), project, monitor);
- selectAndReveal(new StructuredSelection(result));
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- fContext.run(false, false, runnable);
- } catch (final InvocationTargetException e) {
- if (e.getCause() instanceof CoreException) {
- showExceptionDialog((CoreException)e.getCause(), NewWizardMessages.AddSourceFolderToBuildpathAction_ErrorTitle);
- } else {
- JavaScriptPlugin.log(e);
- }
- } catch (final InterruptedException e) {
- }
- }
-
- private List addToClasspath(List elements, IJavaScriptProject project, IProgressMonitor monitor) throws OperationCanceledException, CoreException {
- if (!project.getProject().hasNature(JavaScriptCore.NATURE_ID)) {
- StatusInfo rootStatus= new StatusInfo();
- rootStatus.setError(NewWizardMessages.ClasspathModifier_Error_NoNatures);
- throw new CoreException(rootStatus);
- }
-
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_AddToBuildpath, elements.size() + 4);
-
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
-
- List existingEntries= ClasspathModifier.getExistingEntries(project);
-
- List newEntries= new ArrayList();
- for (int i= 0; i < elements.size(); i++) {
- Object element= elements.get(i);
- CPListElement entry;
- if (element instanceof IResource)
- entry= ClasspathModifier.addToClasspath((IResource) element, existingEntries, newEntries, project, new SubProgressMonitor(monitor, 1));
- else
- entry= ClasspathModifier.addToClasspath((IJavaScriptElement) element, existingEntries, newEntries, project, new SubProgressMonitor(monitor, 1));
- newEntries.add(entry);
- }
-
- Set modifiedSourceEntries= new HashSet();
- BuildPathBasePage.fixNestingConflicts((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]), (CPListElement[])existingEntries.toArray(new CPListElement[existingEntries.size()]), modifiedSourceEntries);
-
- ClasspathModifier.setNewEntry(existingEntries, newEntries, project, new SubProgressMonitor(monitor, 1));
-
- ClasspathModifier.commitClassPath(existingEntries, project, new SubProgressMonitor(monitor, 1));
-
- delta.setNewEntries((CPListElement[])existingEntries.toArray(new CPListElement[existingEntries.size()]));
- informListeners(delta);
-
- List result= new ArrayList();
- for (int i= 0; i < newEntries.size(); i++) {
- IIncludePathEntry entry= ((CPListElement) newEntries.get(i)).getClasspathEntry();
- IJavaScriptElement root;
- if (entry.getPath().equals(project.getPath()))
- root= project;
- else
- root= project.findPackageFragmentRoot(entry.getPath());
- if (root != null) {
- result.add(root);
- }
- }
- return result;
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Determines whether this action can be run on the current selection or selections. If any
- * of the items is not able to run this action then it will not be presented to the user in the wizard.
- */
- protected boolean canHandle(IStructuredSelection elements) {
- if (elements.size() == 0)
- return false;
- try {
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IJavaScriptProject) {
- // if this is a javascript project and its already the source folder then return false
- if (ClasspathModifier.isSourceFolder((IJavaScriptProject)element))
- return false;
- } else if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment)element;
- if (ClasspathModifier.isDefaultFragment(fragment))
- return false;
-
- if (((IPackageFragmentRoot)fragment.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)).isArchive())
- return false;
- } else if (element instanceof IFolder) {
- IProject project= ((IFolder)element).getProject();
- IJavaScriptProject javaProject= JavaScriptCore.create(project);
- if (javaProject == null || !javaProject.exists())
- return false;
- } else {
- return false;
- }
- }
- return true;
- } catch (CoreException e) {
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java
deleted file mode 100644
index a98a04f1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.IBuildpathModifierListener;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public abstract class BuildpathModifierAction extends Action implements ISelectionChangedListener {
-
- public static final int ADD_SEL_SF_TO_BP= 0;
- public static final int REMOVE_FROM_BP= 1;
- public static final int EXCLUDE= 2;
- public static final int UNEXCLUDE= 3;
- public static final int EDIT_FILTERS= 4;
- public static final int CREATE_LINK= 5;
- public static final int RESET_ALL= 6;
- public static final int RESET= 9;
- public static final int INCLUDE= 10;
- public static final int UNINCLUDE= 11;
- public static final int CREATE_FOLDER= 12;
- public static final int ADD_JAR_TO_BP= 13;
- public static final int ADD_LIB_TO_BP= 14;
- public static final int ADD_SEL_LIB_TO_BP= 15;
- public static final int CONFIGURE_BUILD_PATH= 16;
- public static final int DROP_DOWN_ACTION= 18;
-
- private final IWorkbenchSite fSite;
- private final List fSelectedElements;
- private final ISetSelectionTarget fSelectionTarget;
- private final List fListeners;
-
- public BuildpathModifierAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, int id) {
- this(site, selectionTarget, id, IAction.AS_PUSH_BUTTON);
- }
-
- public BuildpathModifierAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, int id, int style) {
- super("", style); //$NON-NLS-1$
-
- fSite= site;
- fSelectionTarget= selectionTarget;
- fSelectedElements= new ArrayList();
- fListeners= new ArrayList();
-
- setId(Integer.toString(id));
- }
-
- /**
- * A detailed description usable for a {@link org.eclipse.ui.forms.widgets.FormText}
- * depending on the current selection, or <code>null</code>
- * if <code>!enabled()</code>
- *
- * @return A detailed description or null if <code>!enabled()</code>
- */
- public abstract String getDetailedDescription();
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(final SelectionChangedEvent event) {
- final ISelection selection = event.getSelection();
- if (selection instanceof IStructuredSelection) {
- setEnabled(canHandle((IStructuredSelection) selection));
- fSelectedElements.clear();
- fSelectedElements.addAll(((IStructuredSelection)selection).toList());
- } else {
- setEnabled(canHandle(StructuredSelection.EMPTY));
- fSelectedElements.clear();
- }
- }
-
- protected abstract boolean canHandle(IStructuredSelection elements);
-
- protected List getSelectedElements() {
- return fSelectedElements;
- }
-
- public void addBuildpathModifierListener(IBuildpathModifierListener listener) {
- fListeners.add(listener);
- }
-
- public void removeBuildpathModifierListener(IBuildpathModifierListener listener) {
- fListeners.remove(listener);
- }
-
- protected void informListeners(BuildpathDelta delta) {
- for (Iterator iterator= fListeners.iterator(); iterator.hasNext();) {
- ((IBuildpathModifierListener)iterator.next()).buildpathChanged(delta);
- }
- }
-
- protected Shell getShell() {
- if (fSite == null)
- return JavaScriptPlugin.getActiveWorkbenchShell();
-
- return fSite.getShell() != null ? fSite.getShell() : JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- protected void showExceptionDialog(CoreException exception, String title) {
- showError(exception, getShell(), title, exception.getMessage());
- }
-
- protected void showError(CoreException e, Shell shell, String title, String message) {
- IStatus status= e.getStatus();
- if (status != null) {
- ErrorDialog.openError(shell, message, title, status);
- } else {
- MessageDialog.openError(shell, title, message);
- }
- }
-
- protected void selectAndReveal(final ISelection selection) {
- if (fSelectionTarget != null)
- fSelectionTarget.selectReveal(selection);
-
- if (fSite == null)
- return;
-
- // validate the input
- IWorkbenchPage page= fSite.getPage();
- if (page == null)
- return;
-
- // get all the view and editor parts
- List parts= new ArrayList();
- IWorkbenchPartReference refs[]= page.getViewReferences();
- for (int i= 0; i < refs.length; i++) {
- IWorkbenchPart part= refs[i].getPart(false);
- if (part != null)
- parts.add(part);
- }
- refs= page.getEditorReferences();
- for (int i= 0; i < refs.length; i++) {
- if (refs[i].getPart(false) != null)
- parts.add(refs[i].getPart(false));
- }
-
- Iterator itr= parts.iterator();
- while (itr.hasNext()) {
- IWorkbenchPart part= (IWorkbenchPart) itr.next();
-
- // get the part's ISetSelectionTarget implementation
- ISetSelectionTarget target= null;
- if (part instanceof ISetSelectionTarget)
- target= (ISetSelectionTarget) part;
- else
- target= (ISetSelectionTarget) part.getAdapter(ISetSelectionTarget.class);
-
- if (target != null) {
- // select and reveal resource
- final ISetSelectionTarget finalTarget= target;
- page.getWorkbenchWindow().getShell().getDisplay().asyncExec(new Runnable() {
- public void run() {
- finalTarget.selectReveal(selection);
- }
- });
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierDropDownAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierDropDownAction.java
deleted file mode 100644
index 945c4fe3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierDropDownAction.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-
-/**
- * Drop down action for toolbars containing <code>BuildpathModifierAction</code>s.
- * The drop down action manages a list of actions that are displayed when invoking
- * the drop down. If there is at least one valid action, then the drop down action
- * itself will also be valid and invoking run will delegate the call to the
- * first valid action in the list.
- */
-public class ClasspathModifierDropDownAction extends BuildpathModifierAction implements IMenuCreator {
-
- /** The menu to be populated with items*/
- private Menu fMenu;
- private List fActions;
- //The action to execute on run iff enabled
- private BuildpathModifierAction fFirstValidAction;
-
- /**
- * Create a drop down action using the same descriptors as the provided action, but it's on
- * tool tip text. The action will automatically be put in the list of actions that are
- * managed by this drop down menu.
- */
- public ClasspathModifierDropDownAction() {
- super(null, null, BuildpathModifierAction.DROP_DOWN_ACTION, IAction.AS_DROP_DOWN_MENU);
-
- fActions= new ArrayList();
- fFirstValidAction= null;
-
- setText(""); //$NON-NLS-1$
- setToolTipText(""); //$NON-NLS-1$
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (fFirstValidAction != null) {
- return fFirstValidAction.getDetailedDescription();
- } else if (fActions.size() > 0) {
- return ((BuildpathModifierAction)fActions.get(0)).getDetailedDescription();
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-
- /**
- * Runs the first action of the list of managed actions that is valid.
- */
- public void run() {
- fFirstValidAction.run();
- }
-
- public IMenuCreator getMenuCreator() {
- return this;
- }
-
- public Menu getMenu(Control parent) {
- if (fMenu != null) {
- fMenu.dispose();
- }
- fMenu = new Menu(parent);
- createEntries(fMenu);
- return fMenu;
-
- }
-
- public Menu getMenu(Menu parent) {
- return fMenu;
- }
-
- /**
- * Add dynamically an action to the drop down menu.
- *
- * @param action the action to be added
- */
- public void addAction(BuildpathModifierAction action) {
- fActions.add(action);
- update();
- }
-
- /**
- * Remove an action from the drop down menu
- *
- * @param action the action to be removed
- */
- public void removeAction(BuildpathModifierAction action) {
- fActions.remove(action);
- update();
- }
-
- /**
- * Populate the menu with the given action item
- *
- * @param parent the menu to add an action for
- * @param action the action to be added
- */
- private void addActionToMenu(Menu parent, IAction action) {
- ActionContributionItem item = new ActionContributionItem(action);
- item.fill(parent, -1);
- }
-
- /**
- * Fill the menu with all actions
- *
- * @param menu the menu to be populated
- */
- private void createEntries(Menu menu) {
- for(int i= 0; i < fActions.size(); i++) {
- IAction action= (IAction)fActions.get(i);
- addActionToMenu(menu, action);
- }
- }
-
- public void dispose() {
- if (fMenu != null) {
- fMenu.dispose();
- fMenu = null;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean canHandle(IStructuredSelection elements) {
- update();
- return fFirstValidAction != null;
- }
-
- private void update() {
- for (Iterator iterator= fActions.iterator(); iterator.hasNext();) {
- BuildpathModifierAction action= (BuildpathModifierAction)iterator.next();
- if (action.isEnabled()) {
- if (action != fFirstValidAction) {
- updateButton(action);
- }
- fFirstValidAction= action;
- return;
- }
- }
- if (fFirstValidAction != null) {
- if (fActions.size() > 0) {
- updateButton((BuildpathModifierAction)fActions.get(0));
- } else {
- updateButton(this);
- }
- }
- fFirstValidAction= null;
- }
-
- private void updateButton(BuildpathModifierAction action) {
- setImageDescriptor(action.getImageDescriptor());
- setDisabledImageDescriptor(action.getDisabledImageDescriptor());
- setText(action.getText());
- setToolTipText(action.getToolTipText());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java
deleted file mode 100644
index e8e4548e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.NewFolderDialog;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ExclusionInclusionDialog;
-import org.eclipse.wst.jsdt.ui.wizards.BuildPathDialogAccess;
-
-/**
- * Helper class for queries used by the <code>ClasspathModifier</code>.
- * Clients can either decide to implement their own queries or just taking
- * the predefined queries.
- */
-public class ClasspathModifierQueries {
-
- /**
- * Query to get information about the inclusion and exclusion filters of
- * an element.
- */
- public static interface IInclusionExclusionQuery {
- /**
- * Query to get information about the
- * inclusion and exclusion filters of
- * an element.
- *
- * While executing <code>doQuery</code>,
- * these filter might change.
- *
- * On calling <code>getInclusionPattern()</code>
- * or <code>getExclusionPattern()</code> it
- * is expected to get the new and updated
- * filters back.
- *
- * @param element the element to get the
- * information from
- * @param focusOnExcluded
- * @return <code>true</code> if changes
- * have been accepted and <code>getInclusionPatter</code>
- * or <code>getExclusionPattern</code> can
- * be called.
- */
- public boolean doQuery(CPListElement element, boolean focusOnExcluded);
-
- /**
- * Can only be called after <code>
- * doQuery</code> has been executed and
- * has returned <code>true</code>
- *
- * @return the new inclusion filters
- */
- public IPath[] getInclusionPattern();
-
- /**
- * Can only be called after <code>
- * doQuery</code> has been executed and
- * has returned <code>true</code>
- *
- * @return the new exclusion filters
- */
- public IPath[] getExclusionPattern();
- }
-
- /**
- * Query to determine whether a linked folder should be removed.
- */
- public static interface IRemoveLinkedFolderQuery {
-
- /** Remove status indicating that the removal should be cancelled */
- public static final int REMOVE_CANCEL= 0;
-
- /** Remove status indicating that the folder should be removed from the build path only */
- public static final int REMOVE_BUILD_PATH= 1;
-
- /** Remove status indicating that the folder should be removed from the build path and deleted */
- public static final int REMOVE_BUILD_PATH_AND_FOLDER= 2;
-
- /**
- * Query to determined whether the linked folder should be removed as well.
- *
- * @param folder the linked folder to remove
- * @return a status code corresponding to one of the IRemoveLinkedFolderQuery#REMOVE_XXX constants
- */
- public int doQuery(IFolder folder);
- }
-
- /**
- * Query to create a folder.
- */
- public static interface ICreateFolderQuery {
- /**
- * Query to create a folder.
- *
- * @return <code>true</code> if the operation
- * was successful (e.g. no cancelled), <code>
- * false</code> otherwise
- */
- public boolean doQuery();
-
- /**
- * Find out whether a source folder is about
- * to be created or a normal folder which
- * is not on the classpath (and therefore
- * might have to be excluded).
- *
- * Should only be called after having executed
- * <code>doQuery</code>, because otherwise
- * it might not be sure if a result exists or
- * not.
- *
- * @return <code>true</code> if a source
- * folder should be created, <code>false
- * </code> otherwise
- */
- public boolean isSourceFolder();
-
- /**
- * Get the newly created folder.
- * This method is only valid after having
- * called <code>doQuery</code>.
- *
- * @return the created folder of type
- * <code>IFolder</code>
- */
- public IFolder getCreatedFolder();
- }
-
- /**
- * Query to add archives (.jar or .zip files) to the buildpath.
- */
- public static interface IAddArchivesQuery {
- /**
- * Get the paths to the new archive entries that should be added to the buildpath.
- *
- * @return Returns the new classpath container entry paths or an empty array if the query has
- * been cancelled by the user.
- */
- public IPath[] doQuery();
- }
-
- /**
- * Query to add libraries to the buildpath.
- */
- public static interface IAddLibrariesQuery {
- /**
- * Get the new classpath entries for libraries to be added to the buildpath.
- *
- * @param project the Java project
- * @param entries an array of classpath entries for the project
- * @return Returns the selected classpath container entries or an empty if the query has
- * been cancelled by the user.
- */
- public IIncludePathEntry[] doQuery(final IJavaScriptProject project, final IIncludePathEntry[] entries);
- }
-
- /**
- * A default query for inclusion and exclusion filters.
- * The query is used to get information about the
- * inclusion and exclusion filters of an element.
- *
- * @param shell shell if there is any or <code>null</code>
- * @return an <code>IInclusionExclusionQuery</code> that can be executed
- *
- * @see ClasspathModifierQueries.IInclusionExclusionQuery
- */
- public static IInclusionExclusionQuery getDefaultInclusionExclusionQuery(final Shell shell) {
- return new IInclusionExclusionQuery() {
-
- protected IPath[] fInclusionPattern;
- protected IPath[] fExclusionPattern;
-
- public boolean doQuery(final CPListElement element, final boolean focusOnExcluded) {
- final boolean[] result= { false };
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- Shell sh= shell != null ? shell : JavaScriptPlugin.getActiveWorkbenchShell();
- ExclusionInclusionDialog dialog= new ExclusionInclusionDialog(sh, element, focusOnExcluded);
- result[0]= dialog.open() == Window.OK;
- fInclusionPattern= dialog.getInclusionPattern();
- fExclusionPattern= dialog.getExclusionPattern();
- }
- });
- return result[0];
- }
-
- public IPath[] getInclusionPattern() {
- return fInclusionPattern;
- }
-
- public IPath[] getExclusionPattern() {
- return fExclusionPattern;
- }
- };
- }
-
- /**
- * Shows the UI to select new external JAR or ZIP archive entries. If the query
- * was aborted, the result is an empty array.
- *
- * @param shell The parent shell for the dialog, can be <code>null</code>
- * @return an <code>IAddArchivesQuery</code> showing a dialog to selected archive files
- * to be added to the buildpath
- *
- * @see IAddArchivesQuery
- */
- public static IAddArchivesQuery getDefaultArchivesQuery(final Shell shell) {
- return new IAddArchivesQuery() {
-
- public IPath[] doQuery() {
- final IPath[][] selected= {null};
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- Shell sh= shell != null ? shell : JavaScriptPlugin.getActiveWorkbenchShell();
- selected[0]= BuildPathDialogAccess.chooseExternalJAREntries(sh);
- }
- });
- if(selected[0] == null)
- return new IPath[0];
- return selected[0];
- }
- };
- }
-
- /**
- * Shows the UI to prompt whether a linked folder which has been removed from the build path should be deleted as well.
- *
- * @param shell The parent shell for the dialog, can be <code>null</code>
- * @return an <code>IRemoveLinkedFolderQuery</code> showing a dialog to prompt whether the linked folder should be deleted as well
- *
- * @see IRemoveLinkedFolderQuery
- */
- public static IRemoveLinkedFolderQuery getDefaultRemoveLinkedFolderQuery(final Shell shell) {
- return new IRemoveLinkedFolderQuery() {
-
- public final int doQuery(final IFolder folder) {
- final int[] result= { IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH};
- Display.getDefault().syncExec(new Runnable() {
-
- public final void run() {
- final RemoveLinkedFolderDialog dialog= new RemoveLinkedFolderDialog((shell != null ? shell : JavaScriptPlugin.getActiveWorkbenchShell()), folder);
- final int status= dialog.open();
- if (status == 0)
- result[0]= dialog.getRemoveStatus();
- else
- result[0]= IRemoveLinkedFolderQuery.REMOVE_CANCEL;
- }
- });
- return result[0];
- }
- };
- }
-
- /**
- * Shows the UI to choose new classpath container classpath entries. See {@link IIncludePathEntry#CPE_CONTAINER} for
- * details about container classpath entries.
- * The query returns the selected classpath entries or an empty array if the query has
- * been cancelled.
- *
- * @param shell The parent shell for the dialog, can be <code>null</code>
- * @return Returns the selected classpath container entries or an empty array if the query has
- * been cancelled by the user.
- */
- public static IAddLibrariesQuery getDefaultLibrariesQuery(final Shell shell) {
- return new IAddLibrariesQuery() {
-
- public IIncludePathEntry[] doQuery(final IJavaScriptProject project, final IIncludePathEntry[] entries) {
- final IIncludePathEntry[][] selected= {null};
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- Shell sh= shell != null ? shell : JavaScriptPlugin.getActiveWorkbenchShell();
- selected[0]= BuildPathDialogAccess.chooseContainerEntries(sh, project, entries);
- }
- });
- if(selected[0] == null)
- return new IIncludePathEntry[0];
- return selected[0];
- }
- };
- }
-
- /**
- * Shows the UI to create a new source folder.
- *
- * @param shell The parent shell for the dialog, can be <code>null</code>
- * @param project the Java project to create the source folder for
- * @return returns the query
- */
- public static ICreateFolderQuery getDefaultCreateFolderQuery(final Shell shell, final IJavaScriptProject project) {
- return new ICreateFolderQuery() {
-
- private IFolder fNewFolder;
-
- public boolean doQuery() {
- final boolean[] isOK= {false};
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- Shell sh= shell != null ? shell : JavaScriptPlugin.getActiveWorkbenchShell();
-
- NewFolderDialog dialog= new NewFolderDialog(sh, project.getProject());
- isOK[0]= dialog.open() == Window.OK;
- if (isOK[0]) {
- IResource sourceContainer= (IResource) dialog.getResult()[0];
- if (sourceContainer instanceof IFolder) {
- fNewFolder= (IFolder)sourceContainer;
- } else {
- fNewFolder= null;
- }
- }
- }
- });
- return isOK[0];
- }
-
-
- public boolean isSourceFolder() {
- return true;
- }
-
- public IFolder getCreatedFolder() {
- return fNewFolder;
- }
-
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java
deleted file mode 100644
index a9efb664..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.AddSourceFolderWizard;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-//SelectedElements iff enabled: IJavaScriptProject && size == 1
-public class CreateLinkedSourceFolderAction extends BuildpathModifierAction {
-
- public CreateLinkedSourceFolderAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public CreateLinkedSourceFolderAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private CreateLinkedSourceFolderAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.CREATE_LINK);
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Link_label);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Link_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_ADD_LINKED_SOURCE_TO_BUILDPATH);
- setDescription(NewWizardMessages.PackageExplorerActionGroup_FormText_createLinkedFolder);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- return NewWizardMessages.PackageExplorerActionGroup_FormText_createLinkedFolder;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell= getShell();
-
- try {
- IJavaScriptProject javaProject= (IJavaScriptProject)getSelectedElements().get(0);
-
- CPListElement newEntrie= new CPListElement(javaProject, IIncludePathEntry.CPE_SOURCE);
- CPListElement[] existing= CPListElement.createFromExisting(javaProject);
- boolean isProjectSrcFolder= CPListElement.isProjectSourceFolder(existing, javaProject);
-
- AddSourceFolderWizard wizard= new AddSourceFolderWizard(existing, newEntrie, true, false, false, isProjectSrcFolder, isProjectSrcFolder);
- wizard.init(PlatformUI.getWorkbench(), new StructuredSelection(javaProject));
-
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- int res= dialog.open();
- if (res == Window.OK) {
-
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
-
- ArrayList newEntries= wizard.getExistingEntries();
- delta.setNewEntries((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]));
-
- IResource resource= wizard.getCreatedElement().getCorrespondingResource();
- delta.addCreatedResource(resource);
-
- informListeners(delta);
-
- selectAndReveal(new StructuredSelection(wizard.getCreatedElement()));
- }
-
- notifyResult(res == Window.OK);
- } catch (CoreException e) {
- String title= NewWizardMessages.AbstractOpenWizardAction_createerror_title;
- String message= NewWizardMessages.AbstractOpenWizardAction_createerror_message;
- ExceptionHandler.handle(e, shell, title, message);
- }
- }
-
- protected boolean canHandle(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
-
- if (!(selection.getFirstElement() instanceof IJavaScriptProject))
- return false;
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction2.java
deleted file mode 100644
index 0db3cfbc..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction2.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.part.ISetSelectionTarget;
-
-public class CreateLinkedSourceFolderAction2 extends CreateLinkedSourceFolderAction {
-
- private final HintTextGroup fProvider;
-
- public CreateLinkedSourceFolderAction2(HintTextGroup provider, IRunnableContext context, ISetSelectionTarget selectionTarget) {
- super(context, selectionTarget);
- fProvider= provider;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void selectAndReveal(ISelection selection) {
- fProvider.handleFolderCreation(((StructuredSelection)selection).toList());
-
- super.selectAndReveal(selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java
deleted file mode 100644
index 21667bf6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.AddSourceFolderWizard;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-//SelectedElements iff enabled: IJavaScriptProject && size==1
-public class CreateSourceFolderAction extends BuildpathModifierAction {
-
- public CreateSourceFolderAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public CreateSourceFolderAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private CreateSourceFolderAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.CREATE_FOLDER);
-
- setText(ActionMessages.OpenNewSourceFolderWizardAction_text2);
- setDescription(ActionMessages.OpenNewSourceFolderWizardAction_description);
- setToolTipText(ActionMessages.OpenNewSourceFolderWizardAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_TOOL_NEWPACKROOT);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_SOURCEFOLDER_WIZARD_ACTION);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- return NewWizardMessages.PackageExplorerActionGroup_FormText_createNewSourceFolder;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell= getShell();
-
- try {
- IJavaScriptProject javaProject= (IJavaScriptProject)getSelectedElements().get(0);
-
- CPListElement newEntrie= new CPListElement(javaProject, IIncludePathEntry.CPE_SOURCE);
- CPListElement[] existing= CPListElement.createFromExisting(javaProject);
- boolean isProjectSrcFolder= CPListElement.isProjectSourceFolder(existing, javaProject);
-
- AddSourceFolderWizard wizard= new AddSourceFolderWizard(existing, newEntrie, false, false, false, isProjectSrcFolder, isProjectSrcFolder);
- wizard.init(PlatformUI.getWorkbench(), new StructuredSelection(javaProject));
-
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- int res= dialog.open();
- if (res == Window.OK) {
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
-
- ArrayList newEntries= wizard.getExistingEntries();
- delta.setNewEntries((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]));
-
- IResource resource= wizard.getCreatedElement().getCorrespondingResource();
- delta.addCreatedResource(resource);
-
- informListeners(delta);
-
- selectAndReveal(new StructuredSelection(wizard.getCreatedElement()));
- }
-
- notifyResult(res == Window.OK);
- } catch (CoreException e) {
- String title= NewWizardMessages.AbstractOpenWizardAction_createerror_title;
- String message= NewWizardMessages.AbstractOpenWizardAction_createerror_message;
- ExceptionHandler.handle(e, shell, title, message);
- }
- }
-
- protected boolean canHandle(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
-
- if (!(selection.getFirstElement() instanceof IJavaScriptProject))
- return false;
-
- return true;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction2.java
deleted file mode 100644
index c903ee86..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction2.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.part.ISetSelectionTarget;
-
-public class CreateSourceFolderAction2 extends CreateSourceFolderAction {
-
- private final HintTextGroup fProvider;
-
- public CreateSourceFolderAction2(HintTextGroup provider, IRunnableContext context, ISetSelectionTarget selectionTarget) {
- super(context, selectionTarget);
-
- fProvider= provider;
- }
-
- /**
- * {@inheritDoc}
- */
- protected void selectAndReveal(ISelection selection) {
- fProvider.handleFolderCreation(((StructuredSelection)selection).toList());
-
- super.selectAndReveal(selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java
deleted file mode 100644
index a26ea4b7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java
+++ /dev/null
@@ -1,451 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IPostSelectionProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.filters.LibraryFilter;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerContentProvider;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElementAttribute;
-import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * A package explorer widget that can be used in dialogs. It uses its own
- * content provider, label provider, element sorter and filter to display
- * elements that are not shown usually in the package explorer of the
- * workspace.
- */
-public class DialogPackageExplorer implements IMenuListener, ISelectionProvider, IPostSelectionProvider, ISetSelectionTarget {
- /**
- * A extended content provider for the package explorer.
- */
- private final class PackageContentProvider extends PackageExplorerContentProvider {
- public PackageContentProvider() {
- super(false);
- }
-
- /**
- * Get the elements of the current project
- *
- * @param element the element to get the children from, will
- * not be used, instead the project children are returned directly
- * @return returns the children of the project
- */
- public Object[] getElements(Object element) {
- if (fCurrJProject == null || !fCurrJProject.exists())
- return new Object[0];
- return new Object[] {fCurrJProject};
- }
- }
-
- /**
- * A extended label provider for the package explorer.
- */
- private final class PackageLabelProvider extends AppearanceAwareLabelProvider {
-
- public PackageLabelProvider(long textFlags, int imageFlags) {
- super(textFlags, imageFlags);
- }
-
- public String getText(Object element) {
- if (element instanceof CPListElementAttribute)
- return null;
- String text= super.getText(element);
- try {
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- if (root.exists() && ClasspathModifier.filtersSet(root)) {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- int excluded= entry.getExclusionPatterns().length;
- if (excluded == 1)
- return Messages.format(NewWizardMessages.DialogPackageExplorer_LabelProvider_SingleExcluded, text);
- else if (excluded > 1)
- return Messages.format(NewWizardMessages.DialogPackageExplorer_LabelProvider_MultiExcluded, new Object[] {text, new Integer(excluded)});
- }
- }
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject project= (IJavaScriptProject)element;
- if (project.exists() && project.isOnIncludepath(project)) {
- IPackageFragmentRoot root= project.findPackageFragmentRoot(project.getPath());
- if (ClasspathModifier.filtersSet(root)) {
- IIncludePathEntry entry= root.getRawIncludepathEntry();
- int excluded= entry.getExclusionPatterns().length;
- if (excluded == 1)
- return Messages.format(NewWizardMessages.DialogPackageExplorer_LabelProvider_SingleExcluded, text);
- else if (excluded > 1)
- return Messages.format(NewWizardMessages.DialogPackageExplorer_LabelProvider_MultiExcluded, new Object[] {text, new Integer(excluded)});
- }
- }
- }
- if (element instanceof IFile || element instanceof IFolder) {
- IResource resource= (IResource)element;
- if (resource.exists() && ClasspathModifier.isExcluded(resource, fCurrJProject))
- return Messages.format(NewWizardMessages.DialogPackageExplorer_LabelProvider_Excluded, text);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return text;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- try {
- if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- if (root.exists() && ClasspathModifier.filtersSet(root))
- return getBlueColor();
- }
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject project= (IJavaScriptProject)element;
- if (project.exists() && project.isOnIncludepath(project)) {
- IPackageFragmentRoot root= project.findPackageFragmentRoot(project.getPath());
- if (root != null && ClasspathModifier.filtersSet(root))
- return getBlueColor();
- }
- }
- if (element instanceof IFile || element instanceof IFolder) {
- IResource resource= (IResource)element;
- if (resource.exists() && ClasspathModifier.isExcluded(resource, fCurrJProject))
- return getBlueColor();
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
- private Color getBlueColor() {
- return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
- }
- }
-
- /**
- * A extended element sorter for the package explorer. The java elements
- * are sorted in the normal way.
- */
- private final class ExtendedJavaElementSorter extends JavaScriptElementComparator {
- public ExtendedJavaElementSorter() {
- super();
- }
-
- public int compare(Viewer viewer, Object e1, Object e2) {
- if (e1 instanceof CPListElementAttribute)
- return -1;
- if (e2 instanceof CPListElementAttribute)
- return 1;
- return super.compare(viewer, e1, e2);
- }
- }
-
- /**
- * An extended filter for the package explorer which filters
- * libraries,
- * files named ".classpath" or ".project",
- * the default package, and
- * hidden folders.
- */
- private final class PackageFilter extends LibraryFilter {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- try {
- if (element instanceof IFile) {
- IFile file= (IFile) element;
- if (file.getName().equals(JavaProject.CLASSPATH_FILENAME) || file.getName().equals(".project")) //$NON-NLS-1$//$NON-NLS-2$
- return false;
- } else if (element instanceof IPackageFragmentRoot) {
- IIncludePathEntry cpe= ((IPackageFragmentRoot)element).getRawIncludepathEntry();
- if (cpe == null || cpe.getEntryKind() == IIncludePathEntry.CPE_CONTAINER || cpe.getEntryKind() == IIncludePathEntry.CPE_LIBRARY || cpe.getEntryKind() == IIncludePathEntry.CPE_VARIABLE)
- return false;
- } else if (element instanceof PackageFragmentRootContainer) {
- return false;
- } else if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment)element;
- if (fragment.isDefaultPackage() && !fragment.hasChildren())
- return false;
- } else if (element instanceof IFolder) {
- IFolder folder= (IFolder)element;
- if (folder.getName().startsWith(".")) //$NON-NLS-1$
- return false;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- /*if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- if (root.getElementName().endsWith(".jar") || root.getElementName().endsWith(".zip")) //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }*/
- return super.select(viewer, parentElement, element);
- }
- }
-
- /** The tree showing the project like in the package explorer */
- private TreeViewer fPackageViewer;
- /** The tree's context menu */
- private Menu fContextMenu;
- /** The action group which is used to fill the context menu. The action group
- * is also called if the selection on the tree changes */
- private DialogPackageExplorerActionGroup fActionGroup;
-
- /** Stores the current selection in the tree
- * @see #getSelection()
- */
- private IStructuredSelection fCurrentSelection;
-
- /** The current java project
- * @see #setInput(IJavaScriptProject)
- */
- private IJavaScriptProject fCurrJProject;
- private PackageContentProvider fContentProvider;
-
- public DialogPackageExplorer() {
- fActionGroup= null;
- fCurrJProject= null;
- fCurrentSelection= new StructuredSelection();
- }
-
- public Control createControl(Composite parent) {
- fPackageViewer= new TreeViewer(parent, SWT.MULTI);
- fPackageViewer.setComparer(WorkingSetModel.COMPARER);
- fPackageViewer.addFilter(new PackageFilter());
- fPackageViewer.setComparator(new ExtendedJavaElementSorter());
- fPackageViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
- if (fPackageViewer.isExpandable(element)) {
- fPackageViewer.setExpandedState(element, !fPackageViewer.getExpandedState(element));
- }
- }
- });
-
- MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(this);
- fContextMenu= menuMgr.createContextMenu(fPackageViewer.getTree());
- fPackageViewer.getTree().setMenu(fContextMenu);
- parent.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- fContextMenu.dispose();
- }
- });
-
- return fPackageViewer.getControl();
- }
-
- /**
- * Sets the action group for the package explorer.
- * The action group is necessary to populate the
- * context menu with available actions. If no
- * context menu is needed, then this method does not
- * have to be called.
- *
- * Should only be called once.
- *
- * @param actionGroup the action group to be used for
- * the context menu.
- */
- public void setActionGroup(final DialogPackageExplorerActionGroup actionGroup) {
- fActionGroup= actionGroup;
- }
-
- /**
- * Populate the context menu with the necessary actions.
- *
- * @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
- */
- public void menuAboutToShow(IMenuManager manager) {
- if (fActionGroup == null) // no context menu
- return;
- JavaScriptPlugin.createStandardGroups(manager);
- fActionGroup.fillContextMenu(manager);
- }
-
- /**
- * Set the content and label provider of the
- * <code>fPackageViewer</code>
- */
- public void setContentProvider() {
- if (fContentProvider != null) {
- fContentProvider.dispose();
- }
- fContentProvider= new PackageContentProvider();
- fContentProvider.setIsFlatLayout(true);
- PackageLabelProvider labelProvider= new PackageLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS);
- fPackageViewer.setContentProvider(fContentProvider);
- fPackageViewer.setLabelProvider(new DecoratingJavaLabelProvider(labelProvider, false));
- }
-
- /**
- * Set the input for the package explorer.
- *
- * @param project the project to be displayed
- */
- public void setInput(IJavaScriptProject project) {
- IJavaScriptProject oldProject= fCurrJProject;
- fCurrJProject= project;
- if (fContentProvider != null)
- fContentProvider.inputChanged(fPackageViewer, oldProject, fCurrJProject);
- fPackageViewer.setInput(new Object[0]);
-
- List selectedElements= new ArrayList();
- selectedElements.add(fCurrJProject);
- setSelection(selectedElements);
- }
-
- public void dispose() {
- if (fContentProvider != null) {
- fContentProvider.dispose();
- fContentProvider= null;
- }
- if (fActionGroup != null) {
- fActionGroup.dispose();
- fActionGroup= null;
- }
- fPackageViewer= null;
- }
-
- /**
- * Set the selection and focus to the list of elements
- * @param elements the object to be selected and displayed
- */
- public void setSelection(final List elements) {
- if (elements == null || elements.size() == 0)
- return;
- try {
- ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- fPackageViewer.refresh();
- IStructuredSelection selection= new StructuredSelection(elements);
- fPackageViewer.setSelection(selection, true);
- fPackageViewer.getTree().setFocus();
-
- if (elements.size() == 1 && elements.get(0) instanceof IJavaScriptProject)
- fPackageViewer.expandToLevel(elements.get(0), 1);
- }
- }, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor());
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- /**
- * The current list of selected elements. The
- * list may be empty if no element is selected.
- *
- * @return the current selection
- */
- public ISelection getSelection() {
- return fCurrentSelection;
- }
-
- /**
- * Get the viewer's control
- *
- * @return the viewers control
- */
- public Control getViewerControl() {
- return fPackageViewer.getControl();
- }
-
- /**
- * {@inheritDoc}
- */
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- fPackageViewer.addSelectionChangedListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- fPackageViewer.removeSelectionChangedListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setSelection(ISelection selection) {
- setSelection(((StructuredSelection)selection).toList());
- }
-
- /**
- * {@inheritDoc}
- */
- public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
- fPackageViewer.addPostSelectionChangedListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
- fPackageViewer.removePostSelectionChangedListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectReveal(ISelection selection) {
- setSelection(selection);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java
deleted file mode 100644
index 31e4af6a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java
+++ /dev/null
@@ -1,292 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.IBuildpathModifierListener;
-import org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.util.ViewerPane;
-
-/**
- * Action group for the dialog package explorer shown on the second page
- * of the new java project wizard.
- */
-public class DialogPackageExplorerActionGroup extends CompositeActionGroup {
-
- private DialogPackageExplorer fDialogPackageExplorer;
-
- private final AddFolderToBuildpathAction fAddFolderToBuildpathAction;
- private final RemoveFromBuildpathAction fRemoveFromBuildpathAction;
- private final ExcludeFromBuildpathAction fExcludeFromBuildpathAction;
- private final IncludeToBuildpathAction fIncludeToBuildpathAction;
- private final EditFilterAction fEditFilterAction;
- private final ClasspathModifierDropDownAction fDropDownAction;
- private final CreateLinkedSourceFolderAction fCreateLinkedSourceFolderAction;
- private final CreateSourceFolderAction fCreateSourceFolderAction;
- private final ResetAllAction fResetAllAction;
-
- /**
- * Constructor which creates the operations and based on this
- * operations the actions.
- *
- * @param provider a information provider to pass necessary information
- * to the operations
- * @param context
- * @param dialogPackageExplorer the package explorer for which to contribute the actions to
- * @param page the page showing the package explorer
- */
- public DialogPackageExplorerActionGroup(HintTextGroup provider, IRunnableContext context, DialogPackageExplorer dialogPackageExplorer, final NewSourceContainerWorkbookPage page) {
- super();
-
- fDialogPackageExplorer= dialogPackageExplorer;
-
- if (context == null)
- context= PlatformUI.getWorkbench().getProgressService();
-
- fAddFolderToBuildpathAction= new AddFolderToBuildpathAction(context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
- };
- fDialogPackageExplorer.addSelectionChangedListener(fAddFolderToBuildpathAction);
-
- fRemoveFromBuildpathAction= new RemoveFromBuildpathAction(context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
- };
- fDialogPackageExplorer.addSelectionChangedListener(fRemoveFromBuildpathAction);
-
- fExcludeFromBuildpathAction= new ExcludeFromBuildpathAction(context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
- };
- fDialogPackageExplorer.addSelectionChangedListener(fExcludeFromBuildpathAction);
-
- fIncludeToBuildpathAction= new IncludeToBuildpathAction(context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
- };
- fDialogPackageExplorer.addSelectionChangedListener(fIncludeToBuildpathAction);
-
- fEditFilterAction= new EditFilterAction(context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
- };
- fDialogPackageExplorer.addSelectionChangedListener(fEditFilterAction);
-
- fDropDownAction= new ClasspathModifierDropDownAction();
- fDropDownAction.addAction(fEditFilterAction);
- fDialogPackageExplorer.addPostSelectionChangedListener(fDropDownAction);
-
- fCreateLinkedSourceFolderAction= new CreateLinkedSourceFolderAction2(provider, context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
-
- /**
- * {@inheritDoc}
- */
- protected List getSelectedElements() {
- ArrayList result= new ArrayList();
- result.add(page.getJavaScriptProject());
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean canHandle(IStructuredSelection selection) {
- return true;
- }
- };
-
- fCreateSourceFolderAction= new CreateSourceFolderAction2(provider, context, fDialogPackageExplorer) {
- public void run() {
- super.run();
- }
-
- /**
- * {@inheritDoc}
- */
- protected List getSelectedElements() {
- ArrayList result= new ArrayList();
- result.add(page.getJavaScriptProject());
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean canHandle(IStructuredSelection selection) {
- return true;
- }
- };
-
- fResetAllAction= new ResetAllAction(provider, context, fDialogPackageExplorer);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.actions.CompositeActionGroup#dispose()
- */
- public void dispose() {
- super.dispose();
-
- fDialogPackageExplorer.removeSelectionChangedListener(fAddFolderToBuildpathAction);
- fDialogPackageExplorer.removeSelectionChangedListener(fRemoveFromBuildpathAction);
- fDialogPackageExplorer.removeSelectionChangedListener(fExcludeFromBuildpathAction);
- fDialogPackageExplorer.removeSelectionChangedListener(fIncludeToBuildpathAction);
- fDialogPackageExplorer.removeSelectionChangedListener(fEditFilterAction);
- fDialogPackageExplorer.removePostSelectionChangedListener(fDropDownAction);
- fDialogPackageExplorer= null;
- }
-
- public void addBuildpathModifierListener(IBuildpathModifierListener listener) {
- fAddFolderToBuildpathAction.addBuildpathModifierListener(listener);
- fRemoveFromBuildpathAction.addBuildpathModifierListener(listener);
- fExcludeFromBuildpathAction.addBuildpathModifierListener(listener);
- fIncludeToBuildpathAction.addBuildpathModifierListener(listener);
- fEditFilterAction.addBuildpathModifierListener(listener);
- fCreateLinkedSourceFolderAction.addBuildpathModifierListener(listener);
- fCreateSourceFolderAction.addBuildpathModifierListener(listener);
- }
-
- public void removeBuildpathModifierListener(IBuildpathModifierListener listener) {
- fAddFolderToBuildpathAction.removeBuildpathModifierListener(listener);
- fRemoveFromBuildpathAction.removeBuildpathModifierListener(listener);
- fExcludeFromBuildpathAction.removeBuildpathModifierListener(listener);
- fIncludeToBuildpathAction.removeBuildpathModifierListener(listener);
- fEditFilterAction.removeBuildpathModifierListener(listener);
- fCreateLinkedSourceFolderAction.removeBuildpathModifierListener(listener);
- fCreateSourceFolderAction.removeBuildpathModifierListener(listener);
- }
-
- /**
- * Create a toolbar manager for a given
- * <code>ViewerPane</code>
- *
- * @param pane the pane to create the <code>
- * ToolBarManager</code> for.
- * @return the created <code>ToolBarManager</code>
- */
- public ToolBarManager createLeftToolBarManager(ViewerPane pane) {
- ToolBarManager tbm= pane.getToolBarManager();
-
- tbm.add(fAddFolderToBuildpathAction);
- tbm.add(fRemoveFromBuildpathAction);
- tbm.add(new Separator());
- tbm.add(fExcludeFromBuildpathAction);
- tbm.add(fIncludeToBuildpathAction);
- tbm.add(new Separator());
- tbm.add(fDropDownAction);
-
- tbm.update(true);
- return tbm;
- }
-
- /**
- * Create a toolbar manager for a given
- * <code>ViewerPane</code>
- *
- * @param pane the pane to create the help toolbar for
- * @return the created <code>ToolBarManager</code>
- */
- public ToolBarManager createLeftToolBar(ViewerPane pane) {
- ToolBar tb= new ToolBar(pane, SWT.FLAT);
- pane.setTopRight(tb);
- ToolBarManager tbm= new ToolBarManager(tb);
-
- tbm.add(fCreateLinkedSourceFolderAction);
- tbm.add(fCreateSourceFolderAction);
- tbm.add(fResetAllAction);
- tbm.add(new HelpAction());
-
- tbm.update(true);
- return tbm;
- }
-
- /**
- * Fill the context menu with the available actions
- *
- * @param menu the menu to be filled up with actions
- */
- public void fillContextMenu(IMenuManager menu) {
-
- if (fAddFolderToBuildpathAction.isEnabled())
- menu.add(fAddFolderToBuildpathAction);
-
- if (fRemoveFromBuildpathAction.isEnabled())
- menu.add(fRemoveFromBuildpathAction);
-
- if (fExcludeFromBuildpathAction.isEnabled())
- menu.add(fExcludeFromBuildpathAction);
-
- if (fIncludeToBuildpathAction.isEnabled())
- menu.add(fIncludeToBuildpathAction);
-
- if (fEditFilterAction.isEnabled())
- menu.add(fEditFilterAction);
-
- if (fCreateLinkedSourceFolderAction.isEnabled())
- menu.add(fCreateLinkedSourceFolderAction);
-
- if (fCreateSourceFolderAction.isEnabled())
- menu.add(fCreateSourceFolderAction);
-
- super.fillContextMenu(menu);
- }
-
- public BuildpathModifierAction[] getHintTextGroupActions() {
- List result= new ArrayList();
-
- if (fCreateSourceFolderAction.isEnabled())
- result.add(fCreateSourceFolderAction);
-
- if (fCreateLinkedSourceFolderAction.isEnabled())
- result.add(fCreateLinkedSourceFolderAction);
-
- if (fEditFilterAction.isEnabled())
- result.add(fEditFilterAction);
-
- if (fExcludeFromBuildpathAction.isEnabled())
- result.add(fExcludeFromBuildpathAction);
-
- if (fIncludeToBuildpathAction.isEnabled())
- result.add(fIncludeToBuildpathAction);
-
- if (fAddFolderToBuildpathAction.isEnabled())
- result.add(fAddFolderToBuildpathAction);
-
- if (fRemoveFromBuildpathAction.isEnabled())
- result.add(fRemoveFromBuildpathAction);
-
- return (BuildpathModifierAction[])result.toArray(new BuildpathModifierAction[result.size()]);
- }
-
- public ResetAllAction getResetAllAction() {
- return fResetAllAction;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java
deleted file mode 100644
index 1879fbdb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.EditFilterWizard;
-
-//SelectedElements iff enabled: (IJavaScriptProject || IPackageFragmentRoot) && size == 1
-public class EditFilterAction extends BuildpathModifierAction {
-
- public EditFilterAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public EditFilterAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private EditFilterAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.EDIT_FILTERS);
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Edit_label);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_CONFIGURE_BUILDPATH_FILTERS);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Edit_tooltip);
- setDescription(NewWizardMessages.PackageExplorerActionGroup_FormText_Edit);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_CONFIGURE_BUILDPATH_FILTERS);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (!isEnabled())
- return null;
-
-
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Edit;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell= getShell();
-
- try {
- EditFilterWizard wizard= createWizard();
- wizard.init(PlatformUI.getWorkbench(), new StructuredSelection(getSelectedElements().get(0)));
-
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- int res= dialog.open();
- if (res == Window.OK) {
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
-
- ArrayList newEntries= wizard.getExistingEntries();
- delta.setNewEntries((CPListElement[])newEntries.toArray(new CPListElement[newEntries.size()]));
-
- IResource resource= wizard.getCreatedElement().getCorrespondingResource();
- delta.addCreatedResource(resource);
-
- informListeners(delta);
-
- selectAndReveal(new StructuredSelection(wizard.getCreatedElement()));
- }
-
- notifyResult(res == Window.OK);
- } catch (CoreException e) {
- String title= NewWizardMessages.AbstractOpenWizardAction_createerror_title;
- String message= NewWizardMessages.AbstractOpenWizardAction_createerror_message;
- ExceptionHandler.handle(e, shell, title, message);
- }
- }
-
- private EditFilterWizard createWizard() throws CoreException {
- IJavaScriptProject javaProject= null;
- Object firstElement= getSelectedElements().get(0);
- if (firstElement instanceof IJavaScriptProject) {
- javaProject= (IJavaScriptProject)firstElement;
- } else {
- javaProject= ((IPackageFragmentRoot)firstElement).getJavaScriptProject();
- }
- CPListElement[] existingEntries= CPListElement.createFromExisting(javaProject);
- CPListElement elementToEdit= findElement((IJavaScriptElement)firstElement, existingEntries);
- return new EditFilterWizard(existingEntries, elementToEdit);
- }
-
- private static CPListElement findElement(IJavaScriptElement element, CPListElement[] elements) {
- IPath path= element.getPath();
- for (int i= 0; i < elements.length; i++) {
- CPListElement cur= elements[i];
- if (cur.getEntryKind() == IIncludePathEntry.CPE_SOURCE && cur.getPath().equals(path)) {
- return cur;
- }
- }
- return null;
- }
-
- protected boolean canHandle(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
-
- try {
- Object element= selection.getFirstElement();
- if (element instanceof IJavaScriptProject) {
- return ClasspathModifier.isSourceFolder((IJavaScriptProject)element);
- } else if (element instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot packageFragmentRoot= ((IPackageFragmentRoot) element);
- if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
- return false;
-
- return packageFragmentRoot.getJavaScriptProject() != null;
- }
- } catch (JavaScriptModelException e) {
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ExcludeFromBuildpathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ExcludeFromBuildpathAction.java
deleted file mode 100644
index 353614d7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ExcludeFromBuildpathAction.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-//SelectedElements iff enabled: IPackageFragment || IJavaScriptUnit
-public class ExcludeFromBuildpathAction extends BuildpathModifierAction {
-
- private final IRunnableContext fContext;
-
- public ExcludeFromBuildpathAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public ExcludeFromBuildpathAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private ExcludeFromBuildpathAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.EXCLUDE);
-
- fContext= context;
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Exclude_label);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_EXCLUDE_FROM_BUILDPATH);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Exclude_tooltip);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_EXCLUDE_FROM_BUILDPATH);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (!isEnabled())
- return null;
-
- if (getSelectedElements().size() != 1)
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_Exclude;
-
- IJavaScriptElement elem= (IJavaScriptElement) getSelectedElements().get(0);
- String name= ClasspathModifier.escapeSpecialChars(elem.getElementName());
- if (elem instanceof IPackageFragment) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_ExcludePackage, name);
- } else if (elem instanceof IJavaScriptUnit) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_ExcludeFile, name);
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- final IJavaScriptProject project;
- Object object= getSelectedElements().get(0);
- if (object instanceof IJavaScriptUnit) {
- project= ((IJavaScriptUnit)object).getJavaScriptProject();
- } else {
- project= ((IPackageFragment)object).getJavaScriptProject();
- }
-
- try {
- final IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- List result= exclude(getSelectedElements(), project, monitor);
- selectAndReveal(new StructuredSelection(result));
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- fContext.run(false, false, runnable);
- } catch (final InvocationTargetException e) {
- if (e.getCause() instanceof CoreException) {
- showExceptionDialog((CoreException)e.getCause(), NewWizardMessages.ExcludeFromBuildathAction_ErrorTitle);
- } else {
- JavaScriptPlugin.log(e);
- }
- } catch (final InterruptedException e) {
- }
- }
-
- private List exclude(List javaElements, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_Excluding, javaElements.size() + 4);
-
- List existingEntries= ClasspathModifier.getExistingEntries(project);
- List resources= new ArrayList();
- for (int i= 0; i < javaElements.size(); i++) {
- IJavaScriptElement javaElement= (IJavaScriptElement) javaElements.get(i);
- IPackageFragmentRoot root= (IPackageFragmentRoot) javaElement.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- CPListElement entry= ClasspathModifier.getClasspathEntry(existingEntries, root);
-
- IResource resource= ClasspathModifier.exclude(javaElement, entry, project, new SubProgressMonitor(monitor, 1));
- if (resource != null) {
- resources.add(resource);
- }
- }
-
- ClasspathModifier.commitClassPath(existingEntries, project, new SubProgressMonitor(monitor, 4));
-
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
- delta.setNewEntries((CPListElement[])existingEntries.toArray(new CPListElement[existingEntries.size()]));
- informListeners(delta);
-
- return resources;
- } finally {
- monitor.done();
- }
- }
-
- protected boolean canHandle(IStructuredSelection elements) {
- if (elements.size() == 0)
- return false;
-
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment)element;
- if (ClasspathModifier.isDefaultFragment(fragment))
- return false;
-
- if (((IPackageFragmentRoot)fragment.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)).isArchive())
- return false;
- } else if (element instanceof IJavaScriptUnit) {
- } else {
- return false;
- }
- }
- return true;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HelpAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HelpAction.java
deleted file mode 100644
index 680d67b5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HelpAction.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * Action to get help.
- */
-public class HelpAction extends Action {
-
- public HelpAction() {
- super();
- setImageDescriptor(JavaPluginImages.DESC_OBJS_HELP);
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Help_label);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Help_tooltip);
- }
-
- public void run() {
- PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Help_link);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java
deleted file mode 100644
index 1d2ff465..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.ScrolledPageContent;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * Displays a set of available links to modify or adjust the project.
- * The links contain a short description about the consequences of
- * this action.
- *
- * The content depends on the selection made on the project.
- * If selection changes, then the <code>HintTextGroup</code> will be
- * notified through the <code>IPackageExplorerActionListener</code> interface.
- */
-public final class HintTextGroup implements ISelectionChangedListener {
-
- private Composite fTopComposite;
- private DialogPackageExplorerActionGroup fActionGroup;
- private List fNewFolders;
- private HashMap fImageMap;
-
- public HintTextGroup() {
- fNewFolders= new ArrayList();
- fImageMap= new HashMap();
- }
-
- public Composite createControl(Composite parent) {
- fTopComposite= new Composite(parent, SWT.NONE);
- fTopComposite.setFont(parent.getFont());
-
- GridData gridData= new GridData(GridData.FILL_BOTH);
- PixelConverter converter= new PixelConverter(parent);
- gridData.heightHint= converter.convertHeightInCharsToPixels(12);
- gridData.widthHint= converter.convertWidthInCharsToPixels(25);
- GridLayout gridLayout= new GridLayout();
- gridLayout.marginWidth= 0;//-converter.convertWidthInCharsToPixels(2);
- gridLayout.marginHeight= 0;//= -4;
- fTopComposite.setLayout(gridLayout);
- fTopComposite.setLayoutData(gridData);
- fTopComposite.setData(null);
- fTopComposite.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- Collection collection= fImageMap.values();
- Iterator iterator= collection.iterator();
- while(iterator.hasNext()) {
- Image image= (Image)iterator.next();
- image.dispose();
- }
- }
- });
- return fTopComposite;
- }
-
- private Shell getShell() {
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
- /**
- * An action group managing the actions needed by
- * the <code>HintTextGroup</code>.
- *
- * Note: This method has to be called on initialization.
- * Calling this method in the constructor is not
- * possible because the actions might need a reference to
- * this class.
- *
- * @param actionGroup the action group containing the necessary
- * actions
- *
- * @see DialogPackageExplorerActionGroup
- */
- public void setActionGroup(DialogPackageExplorerActionGroup actionGroup) {
- fActionGroup= actionGroup;
- }
-
- /**
- * Creates a form text.
- *
- * @param parent the parent to put the form text on
- * @param text the form text to be displayed
- * @return the created form text
- *
- * @see FormToolkit#createFormText(org.eclipse.swt.widgets.Composite, boolean)
- */
- private FormText createFormText(Composite parent, String text) {
- FormToolkit toolkit= new FormToolkit(getShell().getDisplay());
- try {
- FormText formText= toolkit.createFormText(parent, true);
- formText.setFont(parent.getFont());
- try {
- formText.setText(text, true, false);
- } catch (IllegalArgumentException e) {
- formText.setText(e.getMessage(), false, false);
- JavaScriptPlugin.log(e);
- }
- formText.marginHeight= 2;
- formText.marginWidth= 0;
- formText.setBackground(null);
- formText.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
- return formText;
- } finally {
- toolkit.dispose();
- }
- }
-
- /**
- * Create a label with a hyperlink and a picture.
- *
- * @param parent the parent widget of the label
- * @param text the text of the label
- * @param action the action to be executed if the hyperlink is activated
- */
- private void createLabel(Composite parent, String text, final BuildpathModifierAction action) {
- FormText formText= createFormText(parent, text);
- Image image= (Image)fImageMap.get(action.getId());
- if (image == null) {
- image= action.getImageDescriptor().createImage();
- fImageMap.put(action.getId(), image);
- }
- formText.setImage("defaultImage", image); //$NON-NLS-1$
- formText.addHyperlinkListener(new HyperlinkAdapter() {
-
- public void linkActivated(HyperlinkEvent e) {
- action.run();
- }
-
- });
- }
-
- /**
- * Handle folder creation. This includes:
- * <li>Set the selection of the <code>fPackageExplorer</code>
- * to the result object, unless the result object is <code>
- * null</code></li>
- * <li>Add the created folder to the list of new folders</li>
- *
- * In this case, the list consists only of one element on which the
- * new folder has been created
- *
- * @param result a list with only one element to be selected by the
- * <code>fPackageExplorer</code>, or an empty list if creation was
- * aborted
- */
- void handleFolderCreation(List result) {
- if (result.size() == 1) {
- try {
- fNewFolders.add(((IPackageFragmentRoot)result.get(0)).getCorrespondingResource());
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- public List getCreatedResources() {
- return fNewFolders;
- }
-
- public void resetCreatedResources() {
- fNewFolders.clear();
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(SelectionChangedEvent event) {
- if (event.getSelection() instanceof StructuredSelection) {
- handlePostSelectionChange((StructuredSelection)event.getSelection());
- } else {
- handlePostSelectionChange(StructuredSelection.EMPTY);
- }
- }
-
- private void handlePostSelectionChange(StructuredSelection selection) {
-
- BuildpathModifierAction[] actions= fActionGroup.getHintTextGroupActions();
- String[] descriptions= new String[actions.length];
- for (int i= 0; i < actions.length; i++) {
- descriptions[i]= actions[i].getDetailedDescription();
- }
-
- // Get the child composite of the top composite
- Composite childComposite= (Composite)fTopComposite.getData();
-
- // Dispose old composite (if necessary)
- if (childComposite != null && childComposite.getParent() != null)
- childComposite.getParent().dispose();
-
- PixelConverter converter= new PixelConverter(fTopComposite);
-
- // Create new composite
- ScrolledPageContent spc= new ScrolledPageContent(fTopComposite, SWT.V_SCROLL);
- spc.getVerticalBar().setIncrement(5);
-
- GridData gridData= new GridData(GridData.FILL_BOTH);
-
- gridData.heightHint= converter.convertHeightInCharsToPixels(12);
- gridData.widthHint= converter.convertWidthInCharsToPixels(25);
- spc.setLayoutData(gridData);
-
- childComposite= spc.getBody();
- TableWrapLayout tableWrapLayout= new TableWrapLayout();
- tableWrapLayout.leftMargin= 0;
- tableWrapLayout.rightMargin= 0;
- childComposite.setLayout(tableWrapLayout);
- gridData= new GridData(GridData.FILL_BOTH);
- gridData.heightHint= converter.convertHeightInCharsToPixels(12);
- gridData.widthHint= converter.convertWidthInCharsToPixels(25);
- childComposite.setLayoutData(gridData);
-
- fTopComposite.setData(childComposite);
-
- if (noContextHelpAvailable(actions)) {
- String noAction= noAction(selection);
- createFormText(childComposite, Messages.format(NewWizardMessages.HintTextGroup_NoAction, noAction));
- fTopComposite.layout(true);
- return;
- }
-
- for (int i= 0; i < actions.length; i++) {
- createLabel(childComposite, descriptions[i], actions[i]);
- }
-
- fTopComposite.layout(true);
- }
-
- private String noAction(ISelection selection) {
- if (selection instanceof StructuredSelection) {
- return noAction(((StructuredSelection)selection).toList());
- } else {
- return noAction(Collections.EMPTY_LIST);
- }
- }
-
- private String noAction(List selectedElements) {
- if (selectedElements.size() == 0)
- return NewWizardMessages.PackageExplorerActionGroup_NoAction_NullSelection;
-
- if (selectedElements.size() == 1)
- return NewWizardMessages.PackageExplorerActionGroup_NoAction_NoReason;
-
- return NewWizardMessages.PackageExplorerActionGroup_NoAction_MultiSelection;
- }
-
- /**
- * Check if for the current type of selection, no context specific actions can
- * be applied. Note: this does not mean, that there are NO actions available at all.<p>
- *
- * For example: if the default package is selected, there is no specific action for this kind
- * of selection as no operations are allowed on the default package. Nevertheless, the
- * <code>PackageExplorerActionEvent</code> will return at least one action that allows to
- * link to an existing folder in the file system, but this operation is always available
- * and does not add any supporting information to the current selection. Therefore,
- * it can be filtered and the correct answer to the user is that there is no specific
- * action for the default package.
- *
- * @param actions an array of provided actions
- * @return <code>true</code> if there is at least one action that allows context
- * sensitive operations, <code>false</code> otherwise.
- */
- private boolean noContextHelpAvailable(BuildpathModifierAction[] actions) {
- if (actions.length == 0)
- return true;
- if (actions.length == 1) {
- int id= Integer.parseInt(actions[0].getId());
- if (id == BuildpathModifierAction.CREATE_LINK)
- return true;
- }
- if (actions.length == 2) {
- int idLink= Integer.parseInt(actions[0].getId());
- int idReset= Integer.parseInt(actions[1].getId());
- if (idReset == BuildpathModifierAction.RESET_ALL &&
- idLink == BuildpathModifierAction.CREATE_LINK)
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/IncludeToBuildpathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/IncludeToBuildpathAction.java
deleted file mode 100644
index 00c57e21..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/IncludeToBuildpathAction.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-//SelectedElements iff enabled: IResource
-public class IncludeToBuildpathAction extends BuildpathModifierAction {
-
- private final IRunnableContext fContext;
-
- public IncludeToBuildpathAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
- }
-
- public IncludeToBuildpathAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
- }
-
- private IncludeToBuildpathAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.INCLUDE);
-
- fContext= context;
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Unexclude_label);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_INCLUDE_ON_BUILDPATH);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_Unexclude_tooltip);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_INCLUDE_ON_BUILDPATH);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (!isEnabled())
- return null;
-
- if (getSelectedElements().size() != 1)
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_Unexclude;
-
- IResource resource= (IResource) getSelectedElements().get(0);
- String name= ClasspathModifier.escapeSpecialChars(resource.getName());
-
- if (resource instanceof IContainer) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_UnexcludeFolder, name);
- } else if (resource instanceof IFile) {
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_UnexcludeFile, name);
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- IResource resource= (IResource)getSelectedElements().get(0);
- final IJavaScriptProject project= JavaScriptCore.create(resource.getProject());
-
- try {
- final IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- List result= unExclude(getSelectedElements(), project, monitor);
- selectAndReveal(new StructuredSelection(result));
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- fContext.run(false, false, runnable);
- } catch (final InvocationTargetException e) {
- if (e.getCause() instanceof CoreException) {
- showExceptionDialog((CoreException)e.getCause(), NewWizardMessages.IncludeToBuildpathAction_ErrorTitle);
- } else {
- JavaScriptPlugin.log(e);
- }
- } catch (final InterruptedException e) {
- }
- }
-
- protected List unExclude(List elements, IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor == null)
- monitor= new NullProgressMonitor();
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_Including, 2 * elements.size());
-
- List entries= ClasspathModifier.getExistingEntries(project);
- for (int i= 0; i < elements.size(); i++) {
- IResource resource= (IResource) elements.get(i);
- IPackageFragmentRoot root= ClasspathModifier.getFragmentRoot(resource, project, new SubProgressMonitor(monitor, 1));
- if (root != null) {
- CPListElement entry= ClasspathModifier.getClasspathEntry(entries, root);
- ClasspathModifier.unExclude(resource, entry, project, new SubProgressMonitor(monitor, 1));
- }
- }
-
- ClasspathModifier.commitClassPath(entries, project, new SubProgressMonitor(monitor, 4));
-
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
- delta.setNewEntries((CPListElement[])entries.toArray(new CPListElement[entries.size()]));
- informListeners(delta);
-
- List resultElements= ClasspathModifier.getCorrespondingElements(elements, project);
- return resultElements;
- } finally {
- monitor.done();
- }
- }
-
- protected boolean canHandle(IStructuredSelection elements) {
- if (elements.size() == 0)
- return false;
-
- try {
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IResource) {
- IResource resource= (IResource)element;
- IJavaScriptProject project= JavaScriptCore.create(resource.getProject());
- if (project == null || !project.exists())
- return false;
-
- if (!ClasspathModifier.isExcluded(resource, project))
- return false;
- } else {
- return false;
- }
- }
- return true;
- } catch (CoreException e) {
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/LinkFolderDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/LinkFolderDialog.java
deleted file mode 100644
index b71b7128..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/LinkFolderDialog.java
+++ /dev/null
@@ -1,515 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IPathVariableManager;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.dialogs.StatusDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.actions.WorkspaceModifyOperation;
-import org.eclipse.ui.ide.dialogs.PathVariableSelectionDialog;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-public class LinkFolderDialog extends StatusDialog {
- private final class FolderNameField extends Observable implements IDialogFieldListener {
- private StringDialogField fNameDialogField;
-
- public FolderNameField(Composite parent, int numOfColumns) {
- createControls(parent, numOfColumns);
- }
-
- private void createControls(Composite parent, int numColumns) {
- fNameDialogField= new StringDialogField();
- fNameDialogField.setLabelText(NewWizardMessages.LinkFolderDialog_folderNameGroup_label);
- fNameDialogField.doFillIntoGrid(parent, 2);
- LayoutUtil.setHorizontalGrabbing(fNameDialogField.getTextControl(null));
- LayoutUtil.setHorizontalSpan(fNameDialogField.getLabelControl(null), numColumns);
- DialogField.createEmptySpace(parent, numColumns - 1);
-
- fNameDialogField.setDialogFieldListener(this);
- }
-
- public StringDialogField getNameDialogField() {
- return fNameDialogField;
- }
-
- public void setText(String text) {
- fNameDialogField.setText(text);
- fNameDialogField.setFocus();
- }
-
- public String getText() {
- return fNameDialogField.getText();
- }
-
- protected void fireEvent() {
- setChanged();
- notifyObservers();
- }
-
- public void dialogFieldChanged(DialogField field) {
- fireEvent();
- }
- }
-
- private final class LinkFields extends Observable implements IStringButtonAdapter, IDialogFieldListener{
- private StringButtonDialogField fLinkLocation;
-
- private static final String DIALOGSTORE_LAST_EXTERNAL_LOC= JavaScriptUI.ID_PLUGIN + ".last.external.project"; //$NON-NLS-1$
-
- public LinkFields(Composite parent, int numColumns) {
- createControls(parent, numColumns);
- }
-
- private void createControls(Composite parent, int numColumns) {
- fLinkLocation= new StringButtonDialogField(this);
-
- fLinkLocation.setLabelText(NewWizardMessages.LinkFolderDialog_dependenciesGroup_locationLabel_desc);
- fLinkLocation.setButtonLabel(NewWizardMessages.LinkFolderDialog_dependenciesGroup_browseButton_desc);
- fLinkLocation.setDialogFieldListener(this);
-
- SelectionButtonDialogField variables= new SelectionButtonDialogField(SWT.PUSH);
- variables.setLabelText(NewWizardMessages.LinkFolderDialog_dependenciesGroup_variables_desc);
- variables.setDialogFieldListener(new IDialogFieldListener() {
- public void dialogFieldChanged(DialogField field) {
- handleVariablesButtonPressed();
- }
- });
-
- fLinkLocation.doFillIntoGrid(parent, numColumns);
-
- LayoutUtil.setHorizontalSpan(fLinkLocation.getLabelControl(null), numColumns);
- LayoutUtil.setHorizontalGrabbing(fLinkLocation.getTextControl(null));
-
- variables.doFillIntoGrid(parent, 1);
- }
-
- public String getLinkTarget() {
- return fLinkLocation.getText();
- }
-
- public void setLinkTarget(String text) {
- fLinkLocation.setText(text);
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField)
- */
- public void changeControlPressed(DialogField field) {
- final DirectoryDialog dialog= new DirectoryDialog(getShell());
- dialog.setMessage(NewWizardMessages.JavaProjectWizardFirstPage_directory_message);
- String directoryName = getLinkTarget().trim();
- if (directoryName.length() == 0) {
- String prevLocation= JavaScriptPlugin.getDefault().getDialogSettings().get(DIALOGSTORE_LAST_EXTERNAL_LOC);
- if (prevLocation != null) {
- directoryName= prevLocation;
- }
- }
-
- if (directoryName.length() > 0) {
- final File path = new File(directoryName);
- if (path.exists())
- dialog.setFilterPath(directoryName);
- }
- final String selectedDirectory = dialog.open();
- if (selectedDirectory != null) {
- fLinkLocation.setText(selectedDirectory);
- if (fName == null) {
- fFolderNameField.setText(selectedDirectory.substring(selectedDirectory.lastIndexOf(File.separatorChar) + 1));
- }
- JavaScriptPlugin.getDefault().getDialogSettings().put(DIALOGSTORE_LAST_EXTERNAL_LOC, selectedDirectory);
- }
- }
-
- /**
- * Opens a path variable selection dialog
- */
- private void handleVariablesButtonPressed() {
- int variableTypes = IResource.FOLDER;
-
- // allow selecting file and folder variables when creating a
- // linked file
- /*if (type == IResource.FILE)
- variableTypes |= IResource.FILE;*/
-
- PathVariableSelectionDialog dialog = new PathVariableSelectionDialog(getShell(), variableTypes);
- if (dialog.open() == IDialogConstants.OK_ID) {
- String[] variableNames = (String[]) dialog.getResult();
- if (variableNames != null && variableNames.length == 1) {
- fLinkLocation.setText(variableNames[0]);
- if (fName == null) {
- fFolderNameField.setText(variableNames[0]);
- }
- }
- }
- }
-
- public void dialogFieldChanged(DialogField field) {
- fireEvent();
- }
-
- private void fireEvent() {
- setChanged();
- notifyObservers();
- }
- }
-
- /**
- * Validate this page and show appropriate warnings and error NewWizardMessages.
- */
- private final class Validator implements Observer {
-
- public void update(Observable o, Object arg) {
- String name= fFolderNameField.getText();
- IStatus nameStatus= validateFolderName(name);
- if (nameStatus.matches(IStatus.ERROR)) {
- updateStatus(nameStatus);
- } else {
- IStatus dependencyStatus= validateLinkLocation(name);
- updateStatus(StatusUtil.getMoreSevere(nameStatus, dependencyStatus));
- }
- }
-
- /**
- * Validates this page's controls.
- *
- * @return IStatus indicating the validation result. IStatus.OK if the
- * specified link target is valid given the linkHandle.
- */
- private IStatus validateLinkLocation(String name) {
- IWorkspace workspace= JavaScriptPlugin.getWorkspace();
- IPath path= Path.fromOSString(fDependenciesGroup.getLinkTarget());
-
- IStatus locationStatus= workspace.validateLinkLocation(fContainer.getFolder(new Path(name)), path);
- if (locationStatus.matches(IStatus.ERROR))
- return locationStatus;
-
- // use the resolved link target name
- String resolvedLinkTarget= resolveVariable();
- path= new Path(resolvedLinkTarget);
- File linkTargetFile= new Path(resolvedLinkTarget).toFile();
- if (linkTargetFile.exists()) {
- IStatus fileTypeStatus= validateFileType(linkTargetFile);
- if (!fileTypeStatus.isOK())
- return fileTypeStatus;
- } else
- if (locationStatus.isOK()) {
- // locationStatus takes precedence over missing location warning.
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.NewFolderDialog_linkTargetNonExistent);
- }
- if (locationStatus.isOK()) {
- return new StatusInfo();
- }
- return new StatusInfo(locationStatus.getSeverity(), locationStatus.getMessage());
- }
-
- /**
- * Validates the type of the given file against the link type specified
- * in the constructor.
- *
- * @param linkTargetFile file to validate
- * @return IStatus indicating the validation result. IStatus.OK if the
- * given file is valid.
- */
- private IStatus validateFileType(File linkTargetFile) {
- if (!linkTargetFile.isDirectory())
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.NewFolderDialog_linkTargetNotFolder);
- return new StatusInfo();
- }
-
- /**
- * Tries to resolve the value entered in the link target field as
- * a variable, if the value is a relative path.
- * Displays the resolved value if the entered value is a variable.
- */
- private String resolveVariable() {
- IPathVariableManager pathVariableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
- IPath path= Path.fromOSString(fDependenciesGroup.getLinkTarget());
- IPath resolvedPath= pathVariableManager.resolvePath(path);
- return resolvedPath.toOSString();
- }
-
- /**
- * Checks if the folder name is valid.
- *
- * @return <code>true</code> if validation was
- * correct, <code>false</code> otherwise
- */
- private IStatus validateFolderName(String name) {
- if (name.length() == 0) {
- return new StatusInfo(IStatus.ERROR, NewWizardMessages.NewFolderDialog_folderNameEmpty);
- }
-
- IStatus nameStatus = fContainer.getWorkspace().validateName(name, IResource.FOLDER);
- if (!nameStatus.matches(IStatus.ERROR)) {
- return nameStatus;
- }
-
- IPath path = new Path(name);
- if (fContainer.findMember(path) != null) {
- return new StatusInfo(IStatus.ERROR, Messages.format(NewWizardMessages.NewFolderDialog_folderNameEmpty_alreadyExists, name));
- }
- return nameStatus;
- }
- }
-
- private FolderNameField fFolderNameField;
- private LinkFields fDependenciesGroup;
- private IContainer fContainer;
- private IFolder fCreatedFolder;
- private boolean fCreateLink;
- private String fName;
- private String fTarget;
-
- /**
- * Creates a NewFolderDialog
- *
- * @param parentShell parent of the new dialog
- * @param container parent of the new folder
- *
- * @see HintTextGroup
- */
- public LinkFolderDialog(Shell parentShell, IContainer container) {
- this(parentShell, container, true);
- }
-
- public LinkFolderDialog(Shell parentShell, IContainer container, boolean createLink) {
- super(parentShell);
- fContainer = container;
- fCreateLink= createLink;
- setTitle(NewWizardMessages.LinkFolderDialog_title);
- setShellStyle(getShellStyle() | SWT.RESIZE);
- setStatusLineAboveButtons(true);
- }
-
- /* (non-Javadoc)
- * Method declared in Window.
- */
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- }
-
- /**
- * @see org.eclipse.jface.window.Window#create()
- */
- public void create() {
- super.create();
- // initially disable the ok button since we don't preset the
- // folder name field
- getButton(IDialogConstants.OK_ID).setEnabled(false);
- }
-
- public void setName(String name) {
- if (fFolderNameField != null) {
- fFolderNameField.setText(name);
- }
- fName= name;
- }
-
- public void setLinkTarget(String target) {
- if (fDependenciesGroup != null) {
- fDependenciesGroup.setLinkTarget(target);
- }
- fTarget= target;
- }
-
- /* (non-Javadoc)
- * Method declared on Dialog.
- */
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- int numOfColumns= 3;
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- GridLayout layout = new GridLayout(numOfColumns, false);
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- composite.setLayout(layout);
- GridData gridData= new GridData(SWT.FILL, SWT.FILL, true, true);
- gridData.minimumWidth= convertWidthInCharsToPixels(80);
- composite.setLayoutData(gridData);
-
- Label label= new Label(composite, SWT.NONE);
- label.setFont(composite.getFont());
- label.setText(Messages.format(NewWizardMessages.LinkFolderDialog_createIn, fContainer.getFullPath().makeRelative().toString()));
- label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, numOfColumns, 1));
-
- fDependenciesGroup= new LinkFields(composite, numOfColumns);
- if (fTarget != null) {
- fDependenciesGroup.setLinkTarget(fTarget);
- }
- fFolderNameField= new FolderNameField(composite, numOfColumns);
- if (fName != null) {
- fFolderNameField.setText(fName);
- }
-
- Validator validator= new Validator();
- fDependenciesGroup.addObserver(validator);
- fFolderNameField.addObserver(validator);
-
- return composite;
- }
-
- /**
- * Creates a folder resource handle for the folder with the given name.
- * The folder handle is created relative to the container specified during
- * object creation.
- *
- * @param folderName the name of the folder resource to create a handle for
- * @return the new folder resource handle
- */
- private IFolder createFolderHandle(String folderName) {
- IWorkspaceRoot workspaceRoot = fContainer.getWorkspace().getRoot();
- IPath folderPath = fContainer.getFullPath().append(folderName);
- IFolder folderHandle = workspaceRoot.getFolder(folderPath);
-
- return folderHandle;
- }
-
- /**
- * Creates a new folder with the given name and optionally linking to
- * the specified link target.
- *
- * @param folderName name of the new folder
- * @param linkTargetName name of the link target folder. may be null.
- * @return IFolder the new folder
- */
- private IFolder createNewFolder(final String folderName, final String linkTargetName) {
- final IFolder folderHandle = createFolderHandle(folderName);
-
- WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
- public void execute(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(NewWizardMessages.NewFolderDialog_progress, 2000);
- if (monitor.isCanceled())
- throw new OperationCanceledException();
-
- // create link to folder
- folderHandle.createLink(Path.fromOSString(fDependenciesGroup.getLinkTarget()), IResource.ALLOW_MISSING_LOCAL, monitor);
-
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- } catch (StringIndexOutOfBoundsException e) {
- e.printStackTrace();
- }
- finally {
- monitor.done();
- }
- }
- };
-
- try {
- new ProgressMonitorDialog(getShell())
- .run(true, true, operation);
- } catch (InterruptedException exception) {
- return null;
- } catch (InvocationTargetException exception) {
- if (exception.getTargetException() instanceof CoreException) {
- ErrorDialog.openError(getShell(), NewWizardMessages.NewFolderDialog_errorTitle,
- null, // no special message
- ((CoreException) exception.getTargetException())
- .getStatus());
- } else {
- // CoreExceptions are handled above, but unexpected runtime exceptions and errors may still occur.
- JavaScriptPlugin.log(new Exception(Messages.format(
- "Exception in {0}.createNewFolder(): {1}", //$NON-NLS-1$
- new Object[] { getClass().getName(),
- exception.getTargetException() })));
- MessageDialog.openError(getShell(), NewWizardMessages.NewFolderDialog_errorTitle,
- Messages.format(
- NewWizardMessages.NewFolderDialog_internalError,
- new Object[] { exception.getTargetException()
- .getMessage() }));
- }
- return null;
- }
-
- return folderHandle;
- }
-
- /**
- * Update the dialog's status line to reflect the given status. It is safe to call
- * this method before the dialog has been opened.
- */
- protected void updateStatus(IStatus status) {
- super.updateStatus(status);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.dialogs.SelectionStatusDialog#okPressed()
- */
- protected void okPressed() {
- if (fCreateLink) {
- String linkTarget = fDependenciesGroup.getLinkTarget();
- linkTarget= linkTarget.length() == 0 ? null : linkTarget;
- fCreatedFolder = createNewFolder(fFolderNameField.getText(), linkTarget);
- } else {
- fCreatedFolder = createFolderHandle(fFolderNameField.getText());
- }
- super.okPressed();
- }
-
- /**
- * Returns the created folder or <code>null</code>
- * if there is none.
- *
- * @return created folder or <code>null</code>
- */
- public IFolder getCreatedFolder() {
- return fCreatedFolder;
- }
-
- public IPath getLinkTarget() {
- return Path.fromOSString(fDependenciesGroup.getLinkTarget());
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java
deleted file mode 100644
index 03aa5e90..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.forms.events.ExpansionAdapter;
-import org.eclipse.ui.forms.events.ExpansionEvent;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.IBuildpathModifierListener;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.preferences.ScrolledPageContent;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.ViewerPane;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElementAttribute;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-
-public class NewSourceContainerWorkbookPage extends BuildPathBasePage implements IBuildpathModifierListener {
-
- public static final String OPEN_SETTING= "org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.NewSourceContainerPage.openSetting"; //$NON-NLS-1$
-
- private ListDialogField fClassPathList;
- private HintTextGroup fHintTextGroup;
- private DialogPackageExplorer fPackageExplorer;
- private DialogPackageExplorerActionGroup fActionGroup;
-
- private IJavaScriptProject fJavaScriptProject;
-
- private final IRunnableContext fContext;
-
- /**
- * Constructor of the <code>NewSourceContainerWorkbookPage</code> which consists of
- * a tree representing the project, a toolbar with the available actions, an area
- * containing hyperlinks that perform the same actions as those in the toolbar but
- * additionally with some short description.
- *
- * @param classPathList
- * @param context a runnable context, can be <code>null</code>
- * @param buildPathsBlock
- */
- public NewSourceContainerWorkbookPage(ListDialogField classPathList, IRunnableContext context, BuildPathsBlock buildPathsBlock) {
- fClassPathList= classPathList;
- fContext= context;
-
- fPackageExplorer= new DialogPackageExplorer();
- fHintTextGroup= new HintTextGroup();
- }
-
- /**
- * Initialize the controls displaying
- * the content of the java project and saving
- * the '.classpath' and '.project' file.
- *
- * Must be called before initializing the
- * controls using <code>getControl(Composite)</code>.
- *
- * @param javaProject the current java project
- */
- public void init(IJavaScriptProject javaProject) {
- fJavaScriptProject= javaProject;
- fPackageExplorer.addPostSelectionChangedListener(fHintTextGroup);
- fActionGroup.getResetAllAction().setBreakPoint(javaProject);
-
- if (Display.getCurrent() != null) {
- doUpdateUI();
- } else {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- doUpdateUI();
- }
- });
- }
- }
-
- private void doUpdateUI() {
- fPackageExplorer.setInput(fJavaScriptProject);
- }
-
- public void dispose() {
- if (fActionGroup != null) {
- fActionGroup.removeBuildpathModifierListener(this);
- fActionGroup= null;
- }
- fPackageExplorer.removePostSelectionChangedListener(fHintTextGroup);
- fPackageExplorer.dispose();
- }
-
- /**
- * Initializes controls and return composite containing
- * these controls.
- *
- * Before calling this method, make sure to have
- * initialized this instance with a java project
- * using <code>init(IJavaScriptProject)</code>.
- *
- * @param parent the parent composite
- * @return composite containing controls
- *
- * @see #init(IJavaScriptProject)
- */
- public Control getControl(Composite parent) {
- final int[] sashWeight= {60};
- final IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- preferenceStore.setDefault(OPEN_SETTING, true);
-
- // ScrolledPageContent is needed for resizing on expand the expandable composite
- ScrolledPageContent scrolledContent = new ScrolledPageContent(parent);
- Composite body= scrolledContent.getBody();
- body.setLayout(new GridLayout());
-
- final SashForm sashForm= new SashForm(body, SWT.VERTICAL | SWT.NONE);
- sashForm.setFont(sashForm.getFont());
-
- ViewerPane pane= new ViewerPane(sashForm, SWT.BORDER | SWT.FLAT);
- pane.setContent(fPackageExplorer.createControl(pane));
- fPackageExplorer.setContentProvider();
-
- final ExpandableComposite excomposite= new ExpandableComposite(sashForm, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT);
- excomposite.setFont(sashForm.getFont());
- excomposite.setText(NewWizardMessages.NewSourceContainerWorkbookPage_HintTextGroup_title);
- final boolean isExpanded= preferenceStore.getBoolean(OPEN_SETTING);
- excomposite.setExpanded(isExpanded);
- excomposite.addExpansionListener(new ExpansionAdapter() {
- public void expansionStateChanged(ExpansionEvent e) {
- ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(excomposite);
- if (parentScrolledComposite != null) {
- boolean expanded= excomposite.isExpanded();
- parentScrolledComposite.reflow(true);
- adjustSashForm(sashWeight, sashForm, expanded);
- preferenceStore.setValue(OPEN_SETTING, expanded);
- }
- }
- });
-
- excomposite.setClient(fHintTextGroup.createControl(excomposite));
-
- fActionGroup= new DialogPackageExplorerActionGroup(fHintTextGroup, fContext, fPackageExplorer, this);
- fActionGroup.addBuildpathModifierListener(this);
-
- // Create toolbar with actions on the left
- ToolBarManager tbm= fActionGroup.createLeftToolBarManager(pane);
- pane.setTopCenter(null);
- pane.setTopLeft(tbm.getControl());
-
- // Create toolbar with help on the right
- tbm= fActionGroup.createLeftToolBar(pane);
- pane.setTopRight(tbm.getControl());
-
- fHintTextGroup.setActionGroup(fActionGroup);
- fPackageExplorer.setActionGroup(fActionGroup);
-
- sashForm.setWeights(new int[] {60, 40});
- adjustSashForm(sashWeight, sashForm, excomposite.isExpanded());
- GridData gd= new GridData(GridData.FILL_BOTH);
- PixelConverter converter= new PixelConverter(parent);
- gd.heightHint= converter.convertHeightInCharsToPixels(20);
- sashForm.setLayoutData(gd);
-
- parent.layout(true);
-
- return scrolledContent;
- }
-
- /**
- * Adjust the size of the sash form.
- *
- * @param sashWeight the weight to be read or written
- * @param sashForm the sash form to apply the new weights to
- * @param isExpanded <code>true</code> if the expandable composite is
- * expanded, <code>false</code> otherwise
- */
- private void adjustSashForm(int[] sashWeight, SashForm sashForm, boolean isExpanded) {
- if (isExpanded) {
- int upperWeight= sashWeight[0];
- sashForm.setWeights(new int[]{upperWeight, 100 - upperWeight});
- }
- else {
- // TODO Dividing by 10 because of https://bugs.eclipse.org/bugs/show_bug.cgi?id=81939
- sashWeight[0]= sashForm.getWeights()[0] / 10;
- sashForm.setWeights(new int[]{95, 5});
- }
- sashForm.layout(true);
- }
-
- /**
- * Get the scrolled page content of the given control by
- * traversing the parents.
- *
- * @param control the control to get the scrolled page content for
- * @return the scrolled page content or <code>null</code> if none found
- */
- private ScrolledPageContent getParentScrolledComposite(Control control) {
- Control parent= control.getParent();
- while (!(parent instanceof ScrolledPageContent)) {
- parent= parent.getParent();
- }
- if (parent instanceof ScrolledPageContent) {
- return (ScrolledPageContent) parent;
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#getSelection()
- */
- public List getSelection() {
- List selectedList= new ArrayList();
-
- IJavaScriptProject project= fJavaScriptProject;
- try {
- List list= ((StructuredSelection)fPackageExplorer.getSelection()).toList();
- List existingEntries= ClasspathModifier.getExistingEntries(project);
-
- for(int i= 0; i < list.size(); i++) {
- Object obj= list.get(i);
- if (obj instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot element= (IPackageFragmentRoot)obj;
- CPListElement cpElement= ClasspathModifier.getClasspathEntry(existingEntries, element);
- selectedList.add(cpElement);
- }
- else if (obj instanceof IJavaScriptProject) {
- IIncludePathEntry entry= ClasspathModifier.getClasspathEntryFor(project.getPath(), project, IIncludePathEntry.CPE_SOURCE);
- if (entry == null)
- continue;
- CPListElement cpElement= CPListElement.createFromExisting(entry, project);
- selectedList.add(cpElement);
- }
- }
- } catch (JavaScriptModelException e) {
- return new ArrayList();
- }
- return selectedList;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#setSelection(java.util.List)
- */
- public void setSelection(List selection, boolean expand) {
- // page switch
-
- if (selection.size() == 0)
- return;
-
- List cpEntries= new ArrayList();
-
- for (int i= 0; i < selection.size(); i++) {
- Object obj= selection.get(i);
- if (obj instanceof CPListElement) {
- CPListElement element= (CPListElement) obj;
- if (element.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- cpEntries.add(element);
- }
- } else if (obj instanceof CPListElementAttribute) {
- CPListElementAttribute attribute= (CPListElementAttribute)obj;
- CPListElement element= attribute.getParent();
- if (element.getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- cpEntries.add(element);
- }
- }
- }
-
- // refresh classpath
- List list= fClassPathList.getElements();
- IIncludePathEntry[] entries= new IIncludePathEntry[list.size()];
- for(int i= 0; i < list.size(); i++) {
- CPListElement entry= (CPListElement) list.get(i);
- entries[i]= entry.getClasspathEntry();
- }
- try {
- fJavaScriptProject.setRawIncludepath(entries, null);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
-
- fPackageExplorer.setSelection(cpEntries);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
- */
- public boolean isEntryKind(int kind) {
- return kind == IIncludePathEntry.CPE_SOURCE;
- }
-
- /**
- * Update <code>fClassPathList</code>.
- */
- public void buildpathChanged(BuildpathDelta delta) {
- fClassPathList.setElements(Arrays.asList(delta.getNewEntries()));
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFocus() {
- fPackageExplorer.getViewerControl().setFocus();
- }
-
- public IJavaScriptProject getJavaScriptProject() {
- return fJavaScriptProject;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveFromBuildpathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveFromBuildpathAction.java
deleted file mode 100644
index 0b56673a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveFromBuildpathAction.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.CPJavaProject;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage.ClasspathModifierQueries.IRemoveLinkedFolderQuery;
-
-//SelectedElements iff enabled: IPackageFramgentRoot || IJavaScriptProject || JsGlobalScopeContainer
-public class RemoveFromBuildpathAction extends BuildpathModifierAction {
-
- private final IRunnableContext fContext;
-
- public RemoveFromBuildpathAction(IWorkbenchSite site) {
- this(site, null, PlatformUI.getWorkbench().getProgressService());
-
- setImageDescriptor(JavaPluginImages.DESC_ELCL_REMOVE_FROM_BP);
- }
-
- public RemoveFromBuildpathAction(IRunnableContext context, ISetSelectionTarget selectionTarget) {
- this(null, selectionTarget, context);
-
- setImageDescriptor(JavaPluginImages.DESC_ELCL_REMOVE_AS_SOURCE_FOLDER);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_REMOVE_AS_SOURCE_FOLDER);
- }
-
- public RemoveFromBuildpathAction(IWorkbenchSite site, ISetSelectionTarget selectionTarget, IRunnableContext context) {
- super(site, selectionTarget, BuildpathModifierAction.REMOVE_FROM_BP);
-
- fContext= context;
-
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_label);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_RemoveFromCP_tooltip);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- if (!isEnabled())
- return null;
-
- if (getSelectedElements().size() != 1)
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_FromBuildpath;
-
- Object elem= getSelectedElements().get(0);
-
- if (elem instanceof IJavaScriptProject) {
- String name= ClasspathModifier.escapeSpecialChars(((IJavaScriptElement)elem).getElementName());
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_ProjectFromBuildpath, name);
- } else if (elem instanceof IPackageFragmentRoot) {
- String name= ClasspathModifier.escapeSpecialChars(((IJavaScriptElement)elem).getElementName());
- return Messages.format(NewWizardMessages.PackageExplorerActionGroup_FormText_fromBuildpath, name);
- } else if (elem instanceof JsGlobalScopeContainer) {
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_FromBuildpath;
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- try {
-
- final IJavaScriptProject project;
- Object object= getSelectedElements().get(0);
- if (object instanceof IJavaScriptProject) {
- project= (IJavaScriptProject)object;
- } else if (object instanceof IPackageFragmentRoot) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)object;
- project= root.getJavaScriptProject();
- } else {
- JsGlobalScopeContainer container= (JsGlobalScopeContainer)object;
- project= container.getJavaProject();
- }
-
- final List elementsToRemove= new ArrayList();
- final List foldersToDelete= new ArrayList();
- queryToRemoveLinkedFolders(elementsToRemove, foldersToDelete);
-
- final IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_RemoveFromBuildpath, foldersToDelete.size() + 10);
-
- CPJavaProject cpProject= CPJavaProject.createFromExisting(project);
- CPListElement[] toRemove= new CPListElement[elementsToRemove.size()];
- int i= 0;
- for (Iterator iterator= elementsToRemove.iterator(); iterator.hasNext();) {
- Object element= iterator.next();
- if (element instanceof IJavaScriptProject) {
- toRemove[i]= ClasspathModifier.getListElement(((IJavaScriptProject)element).getPath(), cpProject.getCPListElements());
- } else if (element instanceof IPackageFragmentRoot) {
- toRemove[i]= CPListElement.createFromExisting(((IPackageFragmentRoot)element).getRawIncludepathEntry(), project);
- } else {
- toRemove[i]= CPListElement.createFromExisting(((JsGlobalScopeContainer)element).getClasspathEntry(), project);
- }
- i++;
- }
-
- BuildpathDelta delta= ClasspathModifier.removeFromBuildpath(toRemove, cpProject);
- ClasspathModifier.commitClassPath(cpProject, new SubProgressMonitor(monitor, 10));
-
- deleteFolders(foldersToDelete, new SubProgressMonitor(monitor, foldersToDelete.size()));
-
- informListeners(delta);
-
- if (delta.getDeletedResources().length == foldersToDelete.size()) {
- selectAndReveal(new StructuredSelection(project));
- } else {
- List result= new ArrayList(Arrays.asList(delta.getDeletedResources()));
- result.removeAll(foldersToDelete);
- selectAndReveal(new StructuredSelection(result));
- }
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- fContext.run(false, false, runnable);
-
- } catch (CoreException e) {
- showExceptionDialog(e, NewWizardMessages.RemoveFromBuildpathAction_ErrorTitle);
- } catch (InvocationTargetException e) {
- if (e.getCause() instanceof CoreException) {
- showExceptionDialog((CoreException)e.getCause(), NewWizardMessages.RemoveFromBuildpathAction_ErrorTitle);
- } else {
- JavaScriptPlugin.log(e);
- }
- } catch (InterruptedException e) {
- }
- }
-
- private void deleteFolders(List folders, IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(NewWizardMessages.ClasspathModifier_Monitor_RemoveFromBuildpath, folders.size());
-
- for (Iterator iter= folders.iterator(); iter.hasNext();) {
- IFolder folder= (IFolder)iter.next();
- folder.delete(true, true, new SubProgressMonitor(monitor, 1));
- }
- } finally {
- monitor.done();
- }
- }
-
- private void queryToRemoveLinkedFolders(final List elementsToRemove, final List foldersToDelete) throws JavaScriptModelException {
- final Shell shell= getShell();
- for (Iterator iter= getSelectedElements().iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IPackageFragmentRoot) {
- IFolder folder= getLinkedSourceFolder((IPackageFragmentRoot)element);
- if (folder != null) {
- RemoveLinkedFolderDialog dialog= new RemoveLinkedFolderDialog(shell, folder);
-
- final int result= dialog.open() == Window.OK?dialog.getRemoveStatus():IRemoveLinkedFolderQuery.REMOVE_CANCEL;
-
- if (result != IRemoveLinkedFolderQuery.REMOVE_CANCEL) {
- if (result == IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH) {
- elementsToRemove.add(element);
- } else if (result == IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH_AND_FOLDER) {
- elementsToRemove.add(element);
- foldersToDelete.add(folder);
- }
- }
- } else {
- elementsToRemove.add(element);
- }
- } else {
- elementsToRemove.add(element);
- }
- }
- }
-
- private IFolder getLinkedSourceFolder(IPackageFragmentRoot root) throws JavaScriptModelException {
- if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
- return null;
-
- final IResource resource= root.getCorrespondingResource();
- if (!(resource instanceof IFolder))
- return null;
-
- final IFolder folder= (IFolder) resource;
- if (!folder.isLinked())
- return null;
-
- return folder;
- }
-
- protected boolean canHandle(IStructuredSelection elements) {
- if (elements.size() == 0)
- return false;
-
- try {
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
-
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject project= (IJavaScriptProject)element;
- if (!ClasspathModifier.isSourceFolder(project))
- return false;
-
- } else if (element instanceof IPackageFragmentRoot) {
- IIncludePathEntry entry= ((IPackageFragmentRoot) element).getRawIncludepathEntry();
- if (entry != null && entry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- return false;
- }
- } else if (element instanceof JsGlobalScopeContainer) {
- return true;
- } else {
- return false;
- }
- }
- return true;
- } catch (JavaScriptModelException e) {
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveLinkedFolderDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveLinkedFolderDialog.java
deleted file mode 100644
index 8c353b27..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/RemoveLinkedFolderDialog.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage.ClasspathModifierQueries.IRemoveLinkedFolderQuery;
-
-/**
- * Dialog to prompt whether a linked folder should be deleted.
- *
- */
-class RemoveLinkedFolderDialog extends MessageDialog {
-
- /** The remove status */
- private int fRemoveStatus= IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH_AND_FOLDER;
-
- /** The remove build path and folder button */
- private Button fRemoveBuildPathAndFolder;
-
- /** The remove build path button */
- private Button fRemoveBuildPath;
-
- /**
- * Creates a new remove linked folder dialog.
- *
- * @param shell the parent shell to use
- * @param folder the linked folder to remove
- */
- RemoveLinkedFolderDialog(final Shell shell, final IFolder folder) {
- super(shell, NewWizardMessages.ClasspathModifierQueries_confirm_remove_linked_folder_label, null, Messages.format(NewWizardMessages.ClasspathModifierQueries_confirm_remove_linked_folder_message, new Object[] { folder.getFullPath()}), MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL}, 0); // yes is the default
- Assert.isTrue(folder.isLinked());
- }
-
- protected Control createCustomArea(final Composite parent) {
-
- final Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout());
-
- fRemoveBuildPathAndFolder= new Button(composite, SWT.RADIO);
- fRemoveBuildPathAndFolder.addSelectionListener(selectionListener);
-
- fRemoveBuildPathAndFolder.setText(NewWizardMessages.ClasspathModifierQueries_delete_linked_folder);
- fRemoveBuildPathAndFolder.setFont(parent.getFont());
-
- fRemoveBuildPath= new Button(composite, SWT.RADIO);
- fRemoveBuildPath.addSelectionListener(selectionListener);
-
- fRemoveBuildPath.setText(NewWizardMessages.ClasspathModifierQueries_do_not_delete_linked_folder);
- fRemoveBuildPath.setFont(parent.getFont());
-
- fRemoveBuildPathAndFolder.setSelection(fRemoveStatus == IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH_AND_FOLDER);
- fRemoveBuildPath.setSelection(fRemoveStatus == IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH);
-
- return composite;
- }
-
- private SelectionListener selectionListener= new SelectionAdapter() {
-
- public final void widgetSelected(final SelectionEvent event) {
- final Button button= (Button) event.widget;
- if (button.getSelection())
- fRemoveStatus= (button == fRemoveBuildPathAndFolder) ? IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH_AND_FOLDER : IRemoveLinkedFolderQuery.REMOVE_BUILD_PATH;
- }
- };
-
- /**
- * Returns the remove status.
- *
- * @return the remove status, one of IRemoveLinkedFolderQuery#REMOVE_XXX
- */
- public final int getRemoveStatus() {
- return fRemoveStatus;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java
deleted file mode 100644
index 3041e51a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.newsourcepage;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.BuildpathDelta;
-import org.eclipse.wst.jsdt.internal.corext.buildpath.ClasspathModifier;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-
-//TODO: Use global history
-/**
- * On the source page of the JavaScript Settings wizard page this action is run
- */
-public class ResetAllAction extends BuildpathModifierAction {
-
- private final HintTextGroup fProvider;
- private final IRunnableContext fContext;
- private IJavaScriptProject fJavaScriptProject;
- private List fEntries;
-
- public ResetAllAction(HintTextGroup provider, IRunnableContext context, ISetSelectionTarget selectionTarget) {
- super(null, selectionTarget, BuildpathModifierAction.RESET_ALL);
-
- fProvider= provider;
- fContext= context;
-
- setImageDescriptor(JavaPluginImages.DESC_ELCL_CLEAR);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_CLEAR);
- setText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_ClearAll_label);
- setToolTipText(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip);
- setEnabled(false);
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDetailedDescription() {
- return NewWizardMessages.PackageExplorerActionGroup_FormText_Default_ResetAll;
- }
-
- public void setBreakPoint(IJavaScriptProject javaProject) {
- fJavaScriptProject= javaProject;
- if (fJavaScriptProject.exists()) {
- try {
- fEntries= ClasspathModifier.getExistingEntries(fJavaScriptProject);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return;
- }
- setEnabled(true);
- } else {
- JavaScriptCore.addElementChangedListener(new IElementChangedListener() {
-
- public void elementChanged(ElementChangedEvent event) {
- if (fJavaScriptProject.exists()) {
- try {
- fEntries= ClasspathModifier.getExistingEntries(fJavaScriptProject);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- return;
- } finally {
- JavaScriptCore.removeElementChangedListener(this);
- }
- setEnabled(true);
- }
- }
-
- }, ElementChangedEvent.POST_CHANGE);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
-
- try {
- final IRunnableWithProgress runnable= new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
-
- monitor.beginTask("", 3); //$NON-NLS-1$
- try {
- if (!hasChange(fJavaScriptProject))
- return;
-
- BuildpathDelta delta= new BuildpathDelta(getToolTipText());
-
- ClasspathModifier.commitClassPath(fEntries, fJavaScriptProject, monitor);
- delta.setNewEntries((CPListElement[])fEntries.toArray(new CPListElement[fEntries.size()]));
-
- for (Iterator iterator= fProvider.getCreatedResources().iterator(); iterator.hasNext();) {
- IResource resource= (IResource)iterator.next();
- resource.delete(false, null);
- delta.addDeletedResource(resource);
- }
-
- fProvider.resetCreatedResources();
-
- informListeners(delta);
-
- selectAndReveal(new StructuredSelection(fJavaScriptProject));
- } catch (JavaScriptModelException e) {
- showExceptionDialog(e, NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip);
- } catch (CoreException e) {
- showExceptionDialog(e, NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip);
- } finally {
- monitor.done();
- }
- }
- };
- fContext.run(false, false, runnable);
- } catch (InvocationTargetException e) {
- if (e.getCause() instanceof CoreException) {
- showExceptionDialog((CoreException)e.getCause(), NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_ClearAll_tooltip);
- } else {
- JavaScriptPlugin.log(e);
- }
- } catch (InterruptedException e) {
- }
- }
-
-
- /**
- * {@inheritDoc}
- */
- protected boolean canHandle(IStructuredSelection elements) {
- if (fJavaScriptProject == null)
- return false;
-
- return true;
- }
-
-
- //TODO: Remove, action should be disabled if not hasChange
- private boolean hasChange(IJavaScriptProject project) throws JavaScriptModelException {
- IIncludePathEntry[] currentEntries= project.getRawIncludepath();
- if (currentEntries.length != fEntries.size())
- return true;
-
- int i= 0;
- for (Iterator iterator= fEntries.iterator(); iterator.hasNext();) {
- CPListElement oldEntrie= (CPListElement)iterator.next();
- if (!oldEntrie.getClasspathEntry().equals(currentEntries[i]))
- return true;
- i++;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java
deleted file mode 100644
index b08e0a19..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Table;
-
-/**
- * A list with check boxes and a button bar. Typical buttons are 'Check All' and 'Uncheck All'.
- * List model is independent of widget creation.
- * DialogFields controls are: Label, List and Composite containing buttons.
- */
-public class CheckedListDialogField extends ListDialogField {
-
- private int fCheckAllButtonIndex;
- private int fUncheckAllButtonIndex;
-
- private List fCheckedElements;
- private List fGrayedElements;
-
- public CheckedListDialogField(IListAdapter adapter, String[] customButtonLabels, ILabelProvider lprovider) {
- super(adapter, customButtonLabels, lprovider);
- fCheckedElements= new ArrayList();
- fGrayedElements= new ArrayList();
-
- fCheckAllButtonIndex= -1;
- fUncheckAllButtonIndex= -1;
- }
-
- /**
- * Sets the index of the 'check' button in the button label array passed in the constructor.
- * The behavior of the button marked as the check button will then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setCheckAllButtonIndex(int checkButtonIndex) {
- Assert.isTrue(checkButtonIndex < fButtonLabels.length);
- fCheckAllButtonIndex= checkButtonIndex;
- }
-
- /**
- * Sets the index of the 'uncheck' button in the button label array passed in the constructor.
- * The behavior of the button marked as the uncheck button will then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setUncheckAllButtonIndex(int uncheckButtonIndex) {
- Assert.isTrue(uncheckButtonIndex < fButtonLabels.length);
- fUncheckAllButtonIndex= uncheckButtonIndex;
- }
-
-
- /*
- * @see ListDialogField#createTableViewer
- */
- protected TableViewer createTableViewer(Composite parent) {
- Table table= new Table(parent, SWT.CHECK + getListStyle());
- table.setFont(parent.getFont());
- CheckboxTableViewer tableViewer= new CheckboxTableViewer(table);
- tableViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent e) {
- doCheckStateChanged(e);
- }
- });
- return tableViewer;
- }
-
-
- /*
- * @see ListDialogField#getListControl
- */
- public Control getListControl(Composite parent) {
- Control control= super.getListControl(parent);
- if (parent != null) {
- ((CheckboxTableViewer)fTable).setCheckedElements(fCheckedElements.toArray());
- ((CheckboxTableViewer)fTable).setGrayedElements(fGrayedElements.toArray());
- }
- return control;
- }
-
- /*
- * @see DialogField#dialogFieldChanged
- * Hooks in to get element changes to update check model.
- */
- public void dialogFieldChanged() {
- for (int i= fCheckedElements.size() -1; i >= 0; i--) {
- if (!fElements.contains(fCheckedElements.get(i))) {
- fCheckedElements.remove(i);
- }
- }
- super.dialogFieldChanged();
- }
-
- private void checkStateChanged() {
- //call super and do not update check model
- super.dialogFieldChanged();
- }
-
- /**
- * Gets the checked elements.
- */
- public List getCheckedElements() {
- if (isOkToUse(fTableControl)) {
- // workaround for bug 53853
- Object[] checked= ((CheckboxTableViewer) fTable).getCheckedElements();
- ArrayList res= new ArrayList(checked.length);
- for (int i= 0; i < checked.length; i++) {
- res.add(checked[i]);
- }
- return res;
- }
-
-
- return new ArrayList(fCheckedElements);
- }
-
- /**
- * Returns the number of checked elements.
- */
- public int getCheckedSize() {
- return fCheckedElements.size();
- }
-
- /**
- * Returns true if the element is checked.
- */
- public boolean isChecked(Object obj) {
- if (isOkToUse(fTableControl)) {
- return ((CheckboxTableViewer) fTable).getChecked(obj);
- }
-
- return fCheckedElements.contains(obj);
- }
-
- public boolean isGrayed(Object obj) {
- if (isOkToUse(fTableControl)) {
- return ((CheckboxTableViewer) fTable).getGrayed(obj);
- }
-
- return fGrayedElements.contains(obj);
- }
-
- /**
- * Sets the checked elements.
- */
- public void setCheckedElements(Collection list) {
- fCheckedElements= new ArrayList(list);
- if (isOkToUse(fTableControl)) {
- ((CheckboxTableViewer)fTable).setCheckedElements(list.toArray());
- }
- checkStateChanged();
- }
-
- /**
- * Sets the checked state of an element.
- */
- public void setChecked(Object object, boolean state) {
- setCheckedWithoutUpdate(object, state);
- checkStateChanged();
- }
-
- /**
- * Sets the checked state of an element. No dialog changed listener is informed.
- */
- public void setCheckedWithoutUpdate(Object object, boolean state) {
- if (state) {
- if (!fCheckedElements.contains(object)) {
- fCheckedElements.add(object);
- }
- } else {
- fCheckedElements.remove(object);
- }
- if (isOkToUse(fTableControl)) {
- ((CheckboxTableViewer)fTable).setChecked(object, state);
- }
- }
-
- public void setGrayedWithoutUpdate(Object object, boolean state) {
- if (state) {
- if (!fGrayedElements.contains(object)) {
- fGrayedElements.add(object);
- }
- } else {
- fGrayedElements.remove(object);
- }
- if (isOkToUse(fTableControl)) {
- ((CheckboxTableViewer)fTable).setGrayed(object, state);
- }
- }
-
- /**
- * Sets the check state of all elements
- */
- public void checkAll(boolean state) {
- if (state) {
- fCheckedElements= getElements();
- } else {
- fCheckedElements.clear();
- }
- if (isOkToUse(fTableControl)) {
- ((CheckboxTableViewer)fTable).setAllChecked(state);
- }
- checkStateChanged();
- }
-
-
- private void doCheckStateChanged(CheckStateChangedEvent e) {
- if (e.getChecked()) {
- fCheckedElements.add(e.getElement());
- } else {
- fCheckedElements.remove(e.getElement());
- }
- checkStateChanged();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField#replaceElement(java.lang.Object, java.lang.Object)
- */
- public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
- boolean wasChecked= isChecked(oldElement);
- super.replaceElement(oldElement, newElement);
- setChecked(newElement, wasChecked);
- }
-
- // ------ enable / disable management
-
- /*
- * @see ListDialogField#getManagedButtonState
- */
- protected boolean getManagedButtonState(ISelection sel, int index) {
- if (index == fCheckAllButtonIndex) {
- return !fElements.isEmpty();
- } else if (index == fUncheckAllButtonIndex) {
- return !fElements.isEmpty();
- }
- return super.getManagedButtonState(sel, index);
- }
-
- /*
- * @see ListDialogField#extraButtonPressed
- */
- protected boolean managedButtonPressed(int index) {
- if (index == fCheckAllButtonIndex) {
- checkAll(true);
- } else if (index == fUncheckAllButtonIndex) {
- checkAll(false);
- } else {
- return super.managedButtonPressed(index);
- }
- return true;
- }
-
- public void refresh() {
- super.refresh();
- if (isOkToUse(fTableControl)) {
- ((CheckboxTableViewer)fTable).setCheckedElements(fCheckedElements.toArray());
- ((CheckboxTableViewer)fTable).setGrayedElements(fGrayedElements.toArray());
- }
- }
-
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ComboDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ComboDialogField.java
deleted file mode 100644
index ee6fadc7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ComboDialogField.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-
-/**
- * Dialog field containing a label and a combo control.
- */
-public class ComboDialogField extends DialogField {
-
- private String fText;
- private int fSelectionIndex;
- private String[] fItems;
- private Combo fComboControl;
- private ModifyListener fModifyListener;
- private int fFlags;
-
- public ComboDialogField(int flags) {
- super();
- fText= ""; //$NON-NLS-1$
- fItems= new String[0];
- fFlags= flags;
- fSelectionIndex= -1;
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(1));
- Combo combo= getComboControl(parent);
- combo.setLayoutData(gridDataForCombo(nColumns - 1));
-
- return new Control[] { label, combo };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 2;
- }
-
- protected static GridData gridDataForCombo(int span) {
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalSpan= span;
- return gd;
- }
-
- // ------- focus methods
-
- /*
- * @see DialogField#setFocus
- */
- public boolean setFocus() {
- if (isOkToUse(fComboControl)) {
- fComboControl.setFocus();
- }
- return true;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created combo control.
- * @param parent The parent composite or <code>null</code> when the widget has
- * already been created.
- */
- public Combo getComboControl(Composite parent) {
- if (fComboControl == null) {
- assertCompositeNotNull(parent);
- fModifyListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doModifyText(e);
- }
- };
- SelectionListener selectionListener= new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- doSelectionChanged(e);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) { }
- };
-
- fComboControl= new Combo(parent, fFlags);
- // moved up due to 1GEUNW2
- fComboControl.setItems(fItems);
- if (fSelectionIndex != -1) {
- fComboControl.select(fSelectionIndex);
- } else {
- fComboControl.setText(fText);
- }
- fComboControl.setFont(parent.getFont());
- fComboControl.addModifyListener(fModifyListener);
- fComboControl.addSelectionListener(selectionListener);
- fComboControl.setEnabled(isEnabled());
- }
- return fComboControl;
- }
-
- private void doModifyText(ModifyEvent e) {
- if (isOkToUse(fComboControl)) {
- fText= fComboControl.getText();
- fSelectionIndex= fComboControl.getSelectionIndex();
- }
- dialogFieldChanged();
- }
-
- private void doSelectionChanged(SelectionEvent e) {
- if (isOkToUse(fComboControl)) {
- fItems= fComboControl.getItems();
- fText= fComboControl.getText();
- fSelectionIndex= fComboControl.getSelectionIndex();
- }
- dialogFieldChanged();
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
- if (isOkToUse(fComboControl)) {
- fComboControl.setEnabled(isEnabled());
- }
- }
-
- // ------ text access
-
- /**
- * Gets the combo items.
- */
- public String[] getItems() {
- return fItems;
- }
-
- /**
- * Sets the combo items. Triggers a dialog-changed event.
- */
- public void setItems(String[] items) {
- fItems= items;
- if (isOkToUse(fComboControl)) {
- fComboControl.setItems(items);
- }
- dialogFieldChanged();
- }
-
- /**
- * Gets the text.
- */
- public String getText() {
- return fText;
- }
-
- /**
- * Sets the text. Triggers a dialog-changed event.
- */
- public void setText(String text) {
- fText= text;
- if (isOkToUse(fComboControl)) {
- fComboControl.setText(text);
- } else {
- dialogFieldChanged();
- }
- }
-
- /**
- * Selects an item.
- */
- public boolean selectItem(int index) {
- boolean success= false;
- if (isOkToUse(fComboControl)) {
- fComboControl.select(index);
- success= fComboControl.getSelectionIndex() == index;
- } else {
- if (index >= 0 && index < fItems.length) {
- fText= fItems[index];
- fSelectionIndex= index;
- success= true;
- }
- }
- if (success) {
- dialogFieldChanged();
- }
- return success;
- }
-
- /**
- * Selects an item.
- */
- public boolean selectItem(String name) {
- for (int i= 0; i < fItems.length; i++) {
- if (fItems[i].equals(name)) {
- return selectItem(i);
- }
- }
- return false;
- }
-
-
- public int getSelectionIndex() {
- return fSelectionIndex;
- }
-
-
- /**
- * Sets the text without triggering a dialog-changed event.
- */
- public void setTextWithoutUpdate(String text) {
- fText= text;
- if (isOkToUse(fComboControl)) {
- fComboControl.removeModifyListener(fModifyListener);
- fComboControl.setText(text);
- fComboControl.addModifyListener(fModifyListener);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#refresh()
- */
- public void refresh() {
- super.refresh();
- setTextWithoutUpdate(fText);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/DialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/DialogField.java
deleted file mode 100644
index 7770fe38..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/DialogField.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-
-
-/**
- * Base class of all dialog fields.
- * Dialog fields manage controls together with the model, independed
- * from the creation time of the widgets.
- * - support for automated layouting.
- * - enable / disable, set focus a concept of the base class.
- *
- * DialogField have a label.
- */
-public class DialogField {
-
- private Label fLabel;
- protected String fLabelText;
-
- private IDialogFieldListener fDialogFieldListener;
-
- private boolean fEnabled;
-
- public DialogField() {
- fEnabled= true;
- fLabel= null;
- fLabelText= ""; //$NON-NLS-1$
- }
-
- /**
- * Sets the label of the dialog field.
- */
- public void setLabelText(String labeltext) {
- fLabelText= labeltext;
- if (isOkToUse(fLabel)) {
- fLabel.setText(labeltext);
- }
- }
-
- // ------ change listener
-
- /**
- * Defines the listener for this dialog field.
- */
- public final void setDialogFieldListener(IDialogFieldListener listener) {
- fDialogFieldListener= listener;
- }
-
- /**
- * Programatical invocation of a dialog field change.
- */
- public void dialogFieldChanged() {
- if (fDialogFieldListener != null) {
- fDialogFieldListener.dialogFieldChanged(this);
- }
- }
-
- // ------- focus management
-
- /**
- * Tries to set the focus to the dialog field.
- * Returns <code>true</code> if the dialog field can take focus.
- * To be reimplemented by dialog field implementors.
- */
- public boolean setFocus() {
- return false;
- }
-
- /**
- * Posts <code>setFocus</code> to the display event queue.
- */
- public void postSetFocusOnDialogField(Display display) {
- if (display != null) {
- display.asyncExec(
- new Runnable() {
- public void run() {
- setFocus();
- }
- }
- );
- }
- }
-
- // ------- layout helpers
-
- /**
- * Creates all controls of the dialog field and fills it to a composite.
- * The composite is assumed to have <code>MGridLayout</code> as
- * layout.
- * The dialog field will adjust its controls' spans to the number of columns given.
- * To be reimplemented by dialog field implementors.
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(nColumns));
-
- return new Control[] { label };
- }
-
- /**
- * Returns the number of columns of the dialog field.
- * To be reimplemented by dialog field implementors.
- */
- public int getNumberOfControls() {
- return 1;
- }
-
- protected static GridData gridDataForLabel(int span) {
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= span;
- return gd;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created label widget.
- * @param parent The parent composite or <code>null</code> if the widget has
- * already been created.
- */
- public Label getLabelControl(Composite parent) {
- if (fLabel == null) {
- assertCompositeNotNull(parent);
-
- fLabel= new Label(parent, SWT.LEFT | SWT.WRAP);
- fLabel.setFont(parent.getFont());
- fLabel.setEnabled(fEnabled);
- if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$
- fLabel.setText(fLabelText);
- } else {
- // XXX: to avoid a 16 pixel wide empty label - revisit
- fLabel.setText("."); //$NON-NLS-1$
- fLabel.setVisible(false);
- }
- }
- return fLabel;
- }
-
- /**
- * Creates a spacer control.
- * @param parent The parent composite
- */
- public static Control createEmptySpace(Composite parent) {
- return createEmptySpace(parent, 1);
- }
-
- /**
- * Creates a spacer control with the given span.
- * The composite is assumed to have <code>MGridLayout</code> as
- * layout.
- * @param parent The parent composite
- */
- public static Control createEmptySpace(Composite parent, int span) {
- Label label= new Label(parent, SWT.LEFT);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.BEGINNING;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalSpan= span;
- gd.horizontalIndent= 0;
- gd.widthHint= 0;
- gd.heightHint= 0;
- label.setLayoutData(gd);
- return label;
- }
-
- /**
- * Tests is the control is not <code>null</code> and not disposed.
- */
- protected final boolean isOkToUse(Control control) {
- return (control != null) && (Display.getCurrent() != null) && !control.isDisposed();
- }
-
- // --------- enable / disable management
-
- /**
- * Sets the enable state of the dialog field.
- */
- public final void setEnabled(boolean enabled) {
- if (enabled != fEnabled) {
- fEnabled= enabled;
- updateEnableState();
- }
- }
-
- /**
- * Called when the enable state changed.
- * To be extended by dialog field implementors.
- */
- protected void updateEnableState() {
- if (fLabel != null) {
- fLabel.setEnabled(fEnabled);
- }
- }
-
- /**
- * Brings the UI in sync with the model. Only needed when model was changed
- * in different thread whil UI was lready created.
- */
- public void refresh() {
- updateEnableState();
- }
-
- /**
- * Gets the enable state of the dialog field.
- */
- public final boolean isEnabled() {
- return fEnabled;
- }
-
- protected final void assertCompositeNotNull(Composite comp) {
- Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$
- }
-
- protected final void assertEnoughColumns(int nColumns) {
- Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$
- }
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java
deleted file mode 100644
index c270dc16..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-/**
- * Change listener used by <code>DialogField</code>
- */
-public interface IDialogFieldListener {
-
- /**
- * The dialog field has changed.
- */
- void dialogFieldChanged(DialogField field);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IListAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IListAdapter.java
deleted file mode 100644
index 7c0cfb0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IListAdapter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-/**
- * Change listener used by <code>ListDialogField</code> and <code>CheckedListDialogField</code>
- */
-public interface IListAdapter {
-
- /**
- * A button from the button bar has been pressed.
- */
- void customButtonPressed(ListDialogField field, int index);
-
- /**
- * The selection of the list has changed.
- */
- void selectionChanged(ListDialogField field);
-
- /**
- * En entry in the list has been double clicked
- */
- void doubleClicked(ListDialogField field);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java
deleted file mode 100644
index 630f7907..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-/**
- * Change listener used by <code>StringButtonDialogField</code>
- */
-public interface IStringButtonAdapter {
-
- void changeControlPressed(DialogField field);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java
deleted file mode 100644
index 46850247..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.events.KeyEvent;
-
-/**
- * Change listener used by <code>TreeListDialogField</code>
- */
-public interface ITreeListAdapter {
-
- /**
- * A button from the button bar has been pressed.
- */
- void customButtonPressed(TreeListDialogField field, int index);
-
- /**
- * The selection of the list has changed.
- */
- void selectionChanged(TreeListDialogField field);
-
- /**
- * The list has been double clicked
- */
- void doubleClicked(TreeListDialogField field);
-
- /**
- * A key has been pressed
- */
- void keyPressed(TreeListDialogField field, KeyEvent event);
-
- Object[] getChildren(TreeListDialogField field, Object element);
-
- Object getParent(TreeListDialogField field, Object element);
-
- boolean hasChildren(TreeListDialogField field, Object element);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/LayoutUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/LayoutUtil.java
deleted file mode 100644
index e9365841..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/LayoutUtil.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-public class LayoutUtil {
-
- /**
- * Calculates the number of columns needed by field editors
- */
- public static int getNumberOfColumns(DialogField[] editors) {
- int nCulumns= 0;
- for (int i= 0; i < editors.length; i++) {
- nCulumns= Math.max(editors[i].getNumberOfControls(), nCulumns);
- }
- return nCulumns;
- }
-
- /**
- * Creates a composite and fills in the given editors.
- * @param labelOnTop Defines if the label of all fields should be on top of the fields
- */
- public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop) {
- doDefaultLayout(parent, editors, labelOnTop, 0, 0);
- }
-
- /**
- * Creates a composite and fills in the given editors.
- * @param labelOnTop Defines if the label of all fields should be on top of the fields
- * @param marginWidth The margin width to be used by the composite
- * @param marginHeight The margin height to be used by the composite
- */
- public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int marginWidth, int marginHeight) {
- int nCulumns= getNumberOfColumns(editors);
- Control[][] controls= new Control[editors.length][];
- for (int i= 0; i < editors.length; i++) {
- controls[i]= editors[i].doFillIntoGrid(parent, nCulumns);
- }
- if (labelOnTop) {
- nCulumns--;
- modifyLabelSpans(controls, nCulumns);
- }
- GridLayout layout= null;
- if (parent.getLayout() instanceof GridLayout) {
- layout= (GridLayout) parent.getLayout();
- } else {
- layout= new GridLayout();
- }
- if (marginWidth != SWT.DEFAULT) {
- layout.marginWidth= marginWidth;
- }
- if (marginHeight != SWT.DEFAULT) {
- layout.marginHeight= marginHeight;
- }
- layout.numColumns= nCulumns;
- parent.setLayout(layout);
- }
-
- private static void modifyLabelSpans(Control[][] controls, int nCulumns) {
- for (int i= 0; i < controls.length; i++) {
- setHorizontalSpan(controls[i][0], nCulumns);
- }
- }
-
- /**
- * Sets the span of a control. Assumes that GridData is used.
- */
- public static void setHorizontalSpan(Control control, int span) {
- Object ld= control.getLayoutData();
- if (ld instanceof GridData) {
- ((GridData)ld).horizontalSpan= span;
- } else if (span != 1) {
- GridData gd= new GridData();
- gd.horizontalSpan= span;
- control.setLayoutData(gd);
- }
- }
-
- /**
- * Sets the width hint of a control. Assumes that GridData is used.
- */
- public static void setWidthHint(Control control, int widthHint) {
- Object ld= control.getLayoutData();
- if (ld instanceof GridData) {
- ((GridData)ld).widthHint= widthHint;
- }
- }
-
- /**
- * Sets the heightHint hint of a control. Assumes that GridData is used.
- */
- public static void setHeightHint(Control control, int heightHint) {
- Object ld= control.getLayoutData();
- if (ld instanceof GridData) {
- ((GridData)ld).heightHint= heightHint;
- }
- }
-
- /**
- * Sets the horizontal indent of a control. Assumes that GridData is used.
- */
- public static void setHorizontalIndent(Control control, int horizontalIndent) {
- Object ld= control.getLayoutData();
- if (ld instanceof GridData) {
- ((GridData)ld).horizontalIndent= horizontalIndent;
- }
- }
-
- /**
- * Sets the horizontal grabbing of a control to true. Assumes that GridData is used.
- */
- public static void setHorizontalGrabbing(Control control) {
- Object ld= control.getLayoutData();
- if (ld instanceof GridData) {
- ((GridData)ld).grabExcessHorizontalSpace= true;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java
deleted file mode 100644
index 1ce79dd6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java
+++ /dev/null
@@ -1,942 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.ColumnLayoutData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.TableLayoutComposite;
-
-/**
- * A list with a button bar.
- * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
- * List model is independent of widget creation.
- * DialogFields controls are: Label, List and Composite containing buttons.
- */
-public class ListDialogField extends DialogField {
-
- public static class ColumnsDescription {
- private ColumnLayoutData[] columns;
- private String[] headers;
- private boolean drawLines;
-
- public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) {
- this.columns= columns;
- this.headers= headers;
- this.drawLines= drawLines;
- }
-
- public ColumnsDescription(String[] headers, boolean drawLines) {
- this(createColumnWeightData(headers.length), headers, drawLines);
- }
-
- public ColumnsDescription(int nColumns, boolean drawLines) {
- this(createColumnWeightData(nColumns), null, drawLines);
- }
-
- private static ColumnLayoutData[] createColumnWeightData(int nColumns) {
- ColumnLayoutData[] data= new ColumnLayoutData[nColumns];
- for (int i= 0; i < nColumns; i++) {
- data[i]= new ColumnWeightData(1);
- }
- return data;
- }
- }
-
- protected TableViewer fTable;
- protected Control fTableControl;
- protected ILabelProvider fLabelProvider;
- protected ListViewerAdapter fListViewerAdapter;
- protected List fElements;
- protected ViewerComparator fViewerComparator;
-
- protected String[] fButtonLabels;
- private Button[] fButtonControls;
-
- private boolean[] fButtonsEnabled;
-
- private int fRemoveButtonIndex;
- private int fUpButtonIndex;
- private int fDownButtonIndex;
-
- private Label fLastSeparator;
-
-
- private Composite fButtonsControl;
- private ISelection fSelectionWhenEnabled;
-
- private IListAdapter fListAdapter;
-
- private Object fParentElement;
-
- private ColumnsDescription fTableColumns;
-
-
- /**
- * Creates the <code>ListDialogField</code>.
- * @param adapter A listener for button invocation, selection changes. Can
- * be <code>null</code>.
- * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and
- * marks a separator.
- * @param lprovider The label provider to render the table entries
- */
- public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
- super();
- fListAdapter= adapter;
-
- fLabelProvider= lprovider;
- fListViewerAdapter= new ListViewerAdapter();
- fParentElement= this;
-
- fElements= new ArrayList(10);
-
- fButtonLabels= buttonLabels;
- if (fButtonLabels != null) {
- int nButtons= fButtonLabels.length;
- fButtonsEnabled= new boolean[nButtons];
- for (int i= 0; i < nButtons; i++) {
- fButtonsEnabled[i]= true;
- }
- }
-
- fTable= null;
- fTableControl= null;
- fButtonsControl= null;
- fTableColumns= null;
-
- fRemoveButtonIndex= -1;
- fUpButtonIndex= -1;
- fDownButtonIndex= -1;
- }
-
- /**
- * Sets the index of the 'remove' button in the button label array passed in the constructor.
- * The behavior of the button marked as the 'remove' button will then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setRemoveButtonIndex(int removeButtonIndex) {
- Assert.isTrue(removeButtonIndex < fButtonLabels.length);
- fRemoveButtonIndex= removeButtonIndex;
- }
-
- /**
- * Sets the index of the 'up' button in the button label array passed in the constructor.
- * The behavior of the button marked as the 'up' button will then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setUpButtonIndex(int upButtonIndex) {
- Assert.isTrue(upButtonIndex < fButtonLabels.length);
- fUpButtonIndex= upButtonIndex;
- }
-
- /**
- * Sets the index of the 'down' button in the button label array passed in the constructor.
- * The behavior of the button marked as the 'down' button will then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setDownButtonIndex(int downButtonIndex) {
- Assert.isTrue(downButtonIndex < fButtonLabels.length);
- fDownButtonIndex= downButtonIndex;
- }
-
- /**
- * Sets the viewer comparator.
- * @param viewerComparator The viewer comparator to set
- */
- public void setViewerComparator(ViewerComparator viewerComparator) {
- fViewerComparator= viewerComparator;
- }
-
- public void setTableColumns(ColumnsDescription column) {
- fTableColumns= column;
- }
-
-
-
- // ------ adapter communication
-
- private void buttonPressed(int index) {
- if (!managedButtonPressed(index) && fListAdapter != null) {
- fListAdapter.customButtonPressed(this, index);
- }
- }
-
- /**
- * Checks if the button pressed is handled internally
- * @return Returns true if button has been handled.
- */
- protected boolean managedButtonPressed(int index) {
- if (index == fRemoveButtonIndex) {
- remove();
- } else if (index == fUpButtonIndex) {
- up();
- if (!fButtonControls[index].isEnabled() && fDownButtonIndex != -1) {
- fButtonControls[fDownButtonIndex].setFocus();
- }
- } else if (index == fDownButtonIndex) {
- down();
- if (!fButtonControls[index].isEnabled() && fUpButtonIndex != -1) {
- fButtonControls[fUpButtonIndex].setFocus();
- }
- } else {
- return false;
- }
- return true;
- }
-
-
- // ------ layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- PixelConverter converter= new PixelConverter(parent);
-
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- GridData gd= gridDataForLabel(1);
- gd.verticalAlignment= GridData.BEGINNING;
- label.setLayoutData(gd);
-
- Control list= getListControl(parent);
- gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
- gd.horizontalSpan= nColumns - 2;
- gd.widthHint= converter.convertWidthInCharsToPixels(50);
- gd.heightHint= converter.convertHeightInCharsToPixels(6);
-
- list.setLayoutData(gd);
-
- Composite buttons= getButtonBox(parent);
- gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
- gd.horizontalSpan= 1;
- buttons.setLayoutData(gd);
-
- return new Control[] { label, list, buttons };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 3;
- }
-
- /**
- * Sets the minimal width of the buttons. Must be called after widget creation.
- */
- public void setButtonsMinWidth(int minWidth) {
- if (fLastSeparator != null) {
- ((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth;
- }
- }
-
-
- // ------ UI creation
-
- /**
- * Returns the list control. When called the first time, the control will be created.
- * @param parent The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Control getListControl(Composite parent) {
- if (fTableControl == null) {
- assertCompositeNotNull(parent);
-
- if (fTableColumns == null) {
- fTable= createTableViewer(parent);
- Table tableControl= fTable.getTable();
-
- fTableControl= tableControl;
- tableControl.setLayout(new TableLayout());
- } else {
- TableLayoutComposite composite= new TableLayoutComposite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- fTableControl= composite;
-
- fTable= createTableViewer(composite);
- Table tableControl= fTable.getTable();
-
- tableControl.setHeaderVisible(fTableColumns.headers != null);
- tableControl.setLinesVisible(fTableColumns.drawLines);
- ColumnLayoutData[] columns= fTableColumns.columns;
- for (int i= 0; i < columns.length; i++) {
- composite.addColumnData(columns[i]);
- TableColumn column= new TableColumn(tableControl, SWT.NONE);
- //tableLayout.addColumnData(columns[i]);
- if (fTableColumns.headers != null) {
- column.setText(fTableColumns.headers[i]);
- }
- }
- }
-
- fTable.getTable().addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- handleKeyPressed(e);
- }
- });
-
- //fTableControl.setLayout(tableLayout);
-
- fTable.setContentProvider(fListViewerAdapter);
- fTable.setLabelProvider(fLabelProvider);
- fTable.addSelectionChangedListener(fListViewerAdapter);
- fTable.addDoubleClickListener(fListViewerAdapter);
-
- fTable.setInput(fParentElement);
-
- if (fViewerComparator != null) {
- fTable.setComparator(fViewerComparator);
- }
-
- fTableControl.setEnabled(isEnabled());
- if (fSelectionWhenEnabled != null) {
- selectElements(fSelectionWhenEnabled);
- }
- }
- return fTableControl;
- }
-
- /**
- * Returns the internally used table viewer.
- */
- public TableViewer getTableViewer() {
- return fTable;
- }
-
- /*
- * Subclasses may override to specify a different style.
- */
- protected int getListStyle(){
- int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ;
- if (fTableColumns != null) {
- style |= SWT.FULL_SELECTION;
- }
- return style;
- }
-
- protected TableViewer createTableViewer(Composite parent) {
- Table table= new Table(parent, getListStyle());
- table.setFont(parent.getFont());
- return new TableViewer(table);
- }
-
- protected Button createButton(Composite parent, String label, SelectionListener listener) {
- Button button= new Button(parent, SWT.PUSH);
- button.setFont(parent.getFont());
- button.setText(label);
- button.addSelectionListener(listener);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= true;
- gd.verticalAlignment= GridData.BEGINNING;
- gd.widthHint = SWTUtil.getButtonWidthHint(button);
-
- button.setLayoutData(gd);
-
- return button;
- }
-
- private Label createSeparator(Composite parent) {
- Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setFont(parent.getFont());
- separator.setVisible(false);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.verticalAlignment= GridData.BEGINNING;
- gd.verticalIndent= 4;
- separator.setLayoutData(gd);
- return separator;
- }
-
- /**
- * Returns the composite containing the buttons. When called the first time, the control
- * will be created.
- * @param parent The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Composite getButtonBox(Composite parent) {
- if (fButtonsControl == null) {
- assertCompositeNotNull(parent);
-
- SelectionListener listener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- doButtonSelected(e);
- }
- public void widgetSelected(SelectionEvent e) {
- doButtonSelected(e);
- }
- };
-
- Composite contents= new Composite(parent, SWT.NONE);
- contents.setFont(parent.getFont());
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- contents.setLayout(layout);
-
- if (fButtonLabels != null) {
- fButtonControls= new Button[fButtonLabels.length];
- for (int i= 0; i < fButtonLabels.length; i++) {
- String currLabel= fButtonLabels[i];
- if (currLabel != null) {
- fButtonControls[i]= createButton(contents, currLabel, listener);
- fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
- } else {
- fButtonControls[i]= null;
- createSeparator(contents);
- }
- }
- }
-
- fLastSeparator= createSeparator(contents);
-
- updateButtonState();
- fButtonsControl= contents;
- }
-
- return fButtonsControl;
- }
-
- private void doButtonSelected(SelectionEvent e) {
- if (fButtonControls != null) {
- for (int i= 0; i < fButtonControls.length; i++) {
- if (e.widget == fButtonControls[i]) {
- buttonPressed(i);
- return;
- }
- }
- }
- }
-
- /**
- * Handles key events in the table viewer. Specifically
- * when the delete key is pressed.
- */
- protected void handleKeyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) {
- managedButtonPressed(fRemoveButtonIndex);
- }
- }
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#dialogFieldChanged
- */
- public void dialogFieldChanged() {
- super.dialogFieldChanged();
- updateButtonState();
- }
-
- /*
- * Updates the enable state of the all buttons
- */
- protected void updateButtonState() {
- if (fButtonControls != null && isOkToUse(fTableControl) && fTableControl.isEnabled()) {
- ISelection sel= fTable.getSelection();
- for (int i= 0; i < fButtonControls.length; i++) {
- Button button= fButtonControls[i];
- if (isOkToUse(button)) {
- button.setEnabled(isButtonEnabled(sel, i));
- }
- }
- }
- }
-
- protected boolean getManagedButtonState(ISelection sel, int index) {
- if (index == fRemoveButtonIndex) {
- return !sel.isEmpty();
- } else if (index == fUpButtonIndex) {
- return !sel.isEmpty() && canMoveUp();
- } else if (index == fDownButtonIndex) {
- return !sel.isEmpty() && canMoveDown();
- }
- return true;
- }
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
-
- boolean enabled= isEnabled();
- if (isOkToUse(fTableControl)) {
- if (!enabled) {
- if (fSelectionWhenEnabled == null) {
- fSelectionWhenEnabled= fTable.getSelection();
- selectElements(null);
- }
- } else if (fSelectionWhenEnabled != null) {
- selectElements(fSelectionWhenEnabled);
- fSelectionWhenEnabled= null;
- }
- fTableControl.setEnabled(enabled);
- }
- updateButtonState();
- }
-
- /**
- * Sets a button enabled or disabled.
- */
- public void enableButton(int index, boolean enable) {
- if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
- fButtonsEnabled[index]= enable;
- updateButtonState();
- }
- }
-
- private boolean isButtonEnabled(ISelection sel, int index) {
- boolean extraState= getManagedButtonState(sel, index);
- return isEnabled() && extraState && fButtonsEnabled[index];
- }
-
-
- // ------ model access
-
- /**
- * Sets the elements shown in the list.
- */
- public void setElements(Collection elements) {
- fElements= new ArrayList(elements);
- if (isOkToUse(fTableControl)) {
- fTable.refresh();
- }
- dialogFieldChanged();
- }
-
- /**
- * Gets the elements shown in the list.
- * The list returned is a copy, so it can be modified by the user.
- */
- public List getElements() {
- return new ArrayList(fElements);
- }
-
- /**
- * Gets the elements shown at the given index.
- */
- public Object getElement(int index) {
- return fElements.get(index);
- }
-
- /**
- * Gets the index of an element in the list or -1 if element is not in list.
- */
- public int getIndexOfElement(Object elem) {
- return fElements.indexOf(elem);
- }
-
- /**
- * Replaces an element.
- */
- public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
- int idx= fElements.indexOf(oldElement);
- if (idx != -1) {
- fElements.set(idx, newElement);
- if (isOkToUse(fTableControl)) {
- List selected= getSelectedElements();
- if (selected.remove(oldElement)) {
- selected.add(newElement);
- }
- fTable.refresh();
- selectElements(new StructuredSelection(selected));
- }
- dialogFieldChanged();
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Notifies clients that the element has changed.
- */
- public void elementChanged(Object element) throws IllegalArgumentException {
- if (fElements.contains(element)) {
- if (isOkToUse(fTableControl)) {
- fTable.update(element, null);
- }
- dialogFieldChanged();
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Adds an element at the end of the list.
- */
- public boolean addElement(Object element) {
- return addElement(element, fElements.size());
- }
-
- /**
- * Adds an element at a position.
- */
- public boolean addElement(Object element, int index) {
- if (fElements.contains(element)) {
- return false;
- }
- fElements.add(index, element);
- if (isOkToUse(fTableControl)) {
- fTable.refresh();
- fTable.setSelection(new StructuredSelection(element));
- }
-
- dialogFieldChanged();
- return true;
- }
-
- /**
- * Adds elements at the given index
- */
- public boolean addElements(List elements, int index) {
-
- int nElements= elements.size();
-
- if (nElements > 0 && index >= 0 && index <= fElements.size()) {
- // filter duplicated
- ArrayList elementsToAdd= new ArrayList(nElements);
-
- for (int i= 0; i < nElements; i++) {
- Object elem= elements.get(i);
- if (!fElements.contains(elem)) {
- elementsToAdd.add(elem);
- }
- }
- if (!elementsToAdd.isEmpty()) {
- fElements.addAll(index, elementsToAdd);
- if (isOkToUse(fTableControl)) {
- if (index == fElements.size()) {
- fTable.add(elementsToAdd.toArray());
- } else {
- for (int i= elementsToAdd.size() - 1; i >= 0 ; i--) {
- fTable.insert(elementsToAdd.get(i), index);
- }
- }
- fTable.setSelection(new StructuredSelection(elementsToAdd));
- }
- dialogFieldChanged();
- return true;
- }
- }
- return false;
- }
-
- /**
- * Adds elements at the end of the list.
- */
- public boolean addElements(List elements) {
- return addElements(elements, fElements.size());
- }
-
-
-
- /**
- * Adds an element at a position.
- */
- public void removeAllElements() {
- if (fElements.size() > 0) {
- fElements.clear();
- if (isOkToUse(fTableControl)) {
- fTable.refresh();
- }
- dialogFieldChanged();
- }
- }
-
- /**
- * Removes an element from the list.
- */
- public void removeElement(Object element) throws IllegalArgumentException {
- if (fElements.remove(element)) {
- if (isOkToUse(fTableControl)) {
- fTable.remove(element);
- }
- dialogFieldChanged();
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Removes elements from the list.
- */
- public void removeElements(List elements) {
- if (elements.size() > 0) {
- fElements.removeAll(elements);
- if (isOkToUse(fTableControl)) {
- fTable.remove(elements.toArray());
- }
- dialogFieldChanged();
- }
- }
-
- /**
- * Gets the number of elements
- */
- public int getSize() {
- return fElements.size();
- }
-
-
- public void selectElements(ISelection selection) {
- fSelectionWhenEnabled= selection;
- if (isOkToUse(fTableControl)) {
- fTable.setSelection(selection, true);
- }
- }
-
- public void selectFirstElement() {
- Object element= null;
- if (fViewerComparator != null) {
- Object[] arr= fElements.toArray();
- fViewerComparator.sort(fTable, arr);
- if (arr.length > 0) {
- element= arr[0];
- }
- } else {
- if (fElements.size() > 0) {
- element= fElements.get(0);
- }
- }
- if (element != null) {
- selectElements(new StructuredSelection(element));
- }
- }
-
- public void editElement(Object element) {
- if (isOkToUse(fTableControl)) {
- fTable.refresh(element);
- fTable.editElement(element, 0);
- }
- }
-
-
- public void postSetSelection(final ISelection selection) {
- if (isOkToUse(fTableControl)) {
- Display d= fTableControl.getDisplay();
- d.asyncExec(new Runnable() {
- public void run() {
- if (isOkToUse(fTableControl)) {
- selectElements(selection);
- }
- }
- });
- }
- }
-
- /**
- * Refreshes the table.
- */
- public void refresh() {
- super.refresh();
- if (isOkToUse(fTableControl)) {
- fTable.refresh();
- }
- }
-
- // ------- list maintenance
-
- private List moveUp(List elements, List move) {
- int nElements= elements.size();
- List res= new ArrayList(nElements);
- Object floating= null;
- for (int i= 0; i < nElements; i++) {
- Object curr= elements.get(i);
- if (move.contains(curr)) {
- res.add(curr);
- } else {
- if (floating != null) {
- res.add(floating);
- }
- floating= curr;
- }
- }
- if (floating != null) {
- res.add(floating);
- }
- return res;
- }
-
- private void moveUp(List toMoveUp) {
- if (toMoveUp.size() > 0) {
- setElements(moveUp(fElements, toMoveUp));
- fTable.reveal(toMoveUp.get(0));
- }
- }
-
- private void moveDown(List toMoveDown) {
- if (toMoveDown.size() > 0) {
- setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
- fTable.reveal(toMoveDown.get(toMoveDown.size() - 1));
- }
- }
-
- private List reverse(List p) {
- List reverse= new ArrayList(p.size());
- for (int i= p.size()-1; i >= 0; i--) {
- reverse.add(p.get(i));
- }
- return reverse;
- }
-
-
- private void remove() {
- removeElements(getSelectedElements());
- }
-
- private void up() {
- moveUp(getSelectedElements());
- }
-
- private void down() {
- moveDown(getSelectedElements());
- }
-
- public boolean canMoveUp() {
- if (isOkToUse(fTableControl)) {
- int[] indc= fTable.getTable().getSelectionIndices();
- for (int i= 0; i < indc.length; i++) {
- if (indc[i] != i) {
- return true;
- }
- }
- }
- return false;
- }
-
- public boolean canMoveDown() {
- if (isOkToUse(fTableControl)) {
- int[] indc= fTable.getTable().getSelectionIndices();
- int k= fElements.size() - 1;
- for (int i= indc.length - 1; i >= 0 ; i--, k--) {
- if (indc[i] != k) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the selected elements.
- */
- public List getSelectedElements() {
- List result= new ArrayList();
- if (isOkToUse(fTableControl)) {
- ISelection selection= fTable.getSelection();
- if (selection instanceof IStructuredSelection) {
- Iterator iter= ((IStructuredSelection)selection).iterator();
- while (iter.hasNext()) {
- result.add(iter.next());
- }
- }
- }
- return result;
- }
-
- // ------- ListViewerAdapter
-
- private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener {
-
- // ------- ITableContentProvider Interface ------------
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // will never happen
- }
-
- public boolean isDeleted(Object element) {
- return false;
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object obj) {
- return fElements.toArray();
- }
-
- // ------- ISelectionChangedListener Interface ------------
-
- public void selectionChanged(SelectionChangedEvent event) {
- doListSelected(event);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
- */
- public void doubleClick(DoubleClickEvent event) {
- doDoubleClick(event);
- }
-
- }
-
-
- protected void doListSelected(SelectionChangedEvent event) {
- updateButtonState();
- if (fListAdapter != null) {
- fListAdapter.selectionChanged(this);
- }
- }
-
- protected void doDoubleClick(DoubleClickEvent event) {
- if (fListAdapter != null) {
- fListAdapter.doubleClicked(this);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ObjectStringStatusButtonDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ObjectStringStatusButtonDialogField.java
deleted file mode 100644
index ae56ef6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ObjectStringStatusButtonDialogField.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * @author childsb
- *
- */
-public class ObjectStringStatusButtonDialogField extends StringButtonDialogField {
-
- Object enclosedObject;
- String description;
-
- public ObjectStringStatusButtonDialogField(IStringButtonAdapter adapter) {
- super(adapter);
- //super.setTextFieldEditable(false);
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField#getTextControl(org.eclipse.swt.widgets.Composite)
- */
- public Text getTextControl(Composite parent) {
-
- Text superTextControl = super.getTextControl(parent);
- if(superTextControl!=null) superTextControl.setEditable(false);
- return superTextControl;
- }
-
-
- public void setDescription(String description) {
- this.description=description;
- }
-
- public String getDescription() {
- if(description==null && enclosedObject==null)
- return ""; //$NON-NLS-1$
- return description==null?enclosedObject.toString():description;
- }
-
- public void setValue(Object newValue) {
- this.enclosedObject = newValue;
- updateStatusField();
- }
-
- private void updateStatusField() {
- if(description==null && enclosedObject==null)
- return;
-
- setText(description==null?enclosedObject.toString():description);
- }
-
- public Object getValue() {
- return enclosedObject;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java
deleted file mode 100644
index ce2cfe46..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * Dialog Field containing a single button such as a radio or checkbox button.
- */
-public class SelectionButtonDialogField extends DialogField {
-
- private Button fButton;
- private boolean fIsSelected;
- private DialogField[] fAttachedDialogFields;
- private int fButtonStyle;
-
- /**
- * Creates a selection button.
- * Allowed button styles: SWT.RADIO, SWT.CHECK, SWT.TOGGLE, SWT.PUSH
- */
- public SelectionButtonDialogField(int buttonStyle) {
- super();
- fIsSelected= false;
- fAttachedDialogFields= null;
- fButtonStyle= buttonStyle;
- }
-
- /**
- * Attaches a field to the selection state of the selection button.
- * The attached field will be disabled if the selection button is not selected.
- */
- public void attachDialogField(DialogField dialogField) {
- attachDialogFields(new DialogField[] { dialogField });
- }
-
- /**
- * Attaches fields to the selection state of the selection button.
- * The attached fields will be disabled if the selection button is not selected.
- */
- public void attachDialogFields(DialogField[] dialogFields) {
- fAttachedDialogFields= dialogFields;
- for (int i= 0; i < dialogFields.length; i++) {
- dialogFields[i].setEnabled(fIsSelected);
- }
- }
-
- /**
- * Returns <code>true</code> is teh gived field is attached to the selection button.
- */
- public boolean isAttached(DialogField editor) {
- if (fAttachedDialogFields != null) {
- for (int i=0; i < fAttachedDialogFields.length; i++) {
- if (fAttachedDialogFields[i] == editor) {
- return true;
- }
- }
- }
- return false;
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Button button= getSelectionButton(parent);
- GridData gd= new GridData();
- gd.horizontalSpan= nColumns;
- gd.horizontalAlignment= GridData.FILL;
- if (fButtonStyle == SWT.PUSH) {
- gd.widthHint = SWTUtil.getButtonWidthHint(button);
- }
-
- button.setLayoutData(gd);
-
- return new Control[] { button };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 1;
- }
-
- // ------- ui creation
-
- /**
- * Returns the selection button widget. When called the first time, the widget will be created.
- * @param group The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Button getSelectionButton(Composite group) {
- if (fButton == null) {
- assertCompositeNotNull(group);
-
- fButton= new Button(group, fButtonStyle);
- fButton.setFont(group.getFont());
- fButton.setText(fLabelText);
- fButton.setEnabled(isEnabled());
- fButton.setSelection(fIsSelected);
- fButton.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- doWidgetSelected(e);
- }
- public void widgetSelected(SelectionEvent e) {
- doWidgetSelected(e);
- }
- });
- }
- return fButton;
- }
-
- private void doWidgetSelected(SelectionEvent e) {
- if (isOkToUse(fButton)) {
- changeValue(fButton.getSelection());
- }
- }
-
- private void changeValue(boolean newState) {
- if (fIsSelected != newState) {
- fIsSelected= newState;
- if (fAttachedDialogFields != null) {
- boolean focusSet= false;
- for (int i= 0; i < fAttachedDialogFields.length; i++) {
- fAttachedDialogFields[i].setEnabled(fIsSelected);
- if (fIsSelected && !focusSet) {
- focusSet= fAttachedDialogFields[i].setFocus();
- }
- }
- }
- dialogFieldChanged();
- } else if (fButtonStyle == SWT.PUSH) {
- dialogFieldChanged();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#setLabelText(java.lang.String)
- */
- public void setLabelText(String labeltext) {
- fLabelText= labeltext;
- if (isOkToUse(fButton)) {
- fButton.setText(labeltext);
- }
- }
-
-
- // ------ model access
-
- /**
- * Returns the selection state of the button.
- */
- public boolean isSelected() {
- return fIsSelected;
- }
-
- /**
- * Sets the selection state of the button.
- */
- public void setSelection(boolean selected) {
- changeValue(selected);
- if (isOkToUse(fButton)) {
- fButton.setSelection(selected);
- }
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
- if (isOkToUse(fButton)) {
- fButton.setEnabled(isEnabled());
- }
- }
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#refresh()
- */
- public void refresh() {
- super.refresh();
- if (isOkToUse(fButton)) {
- fButton.setSelection(fIsSelected);
- }
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java
deleted file mode 100644
index 8a6ea411..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-
-
-/**
- * Dialog field describing a group with buttons (Checkboxes, radio buttons..)
- */
-public class SelectionButtonDialogFieldGroup extends DialogField {
-
- private Composite fButtonComposite;
-
- private Button[] fButtons;
- private String[] fButtonNames;
- private boolean[] fButtonsSelected;
- private boolean[] fButtonsEnabled;
-
- private int fGroupBorderStyle;
- private int fGroupNumberOfColumns;
- private int fButtonsStyle;
-
- /**
- * Creates a group without border.
- */
- public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns) {
- this(buttonsStyle, buttonNames, nColumns, SWT.NONE);
- }
-
-
- /**
- * Creates a group with border (label in border).
- * Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE
- * For border styles see <code>Group</code>
- */
- public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) {
- super();
-
- Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE);
- fButtonNames= buttonNames;
- fButtonsStyle= buttonsStyle;
-
- int nButtons= buttonNames.length;
- fButtonsSelected= new boolean[nButtons];
- fButtonsEnabled= new boolean[nButtons];
- for (int i= 0; i < nButtons; i++) {
- fButtonsSelected[i]= false;
- fButtonsEnabled[i]= true;
- }
- if (buttonsStyle == SWT.RADIO) {
- fButtonsSelected[0]= true;
- }
-
- fGroupBorderStyle= borderStyle;
- fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns;
-
-
-
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- if (fGroupBorderStyle == SWT.NONE) {
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(1));
-
- Composite buttonsgroup= getSelectionButtonsGroup(parent);
- GridData gd= new GridData();
- gd.horizontalSpan= nColumns - 1;
- buttonsgroup.setLayoutData(gd);
-
- return new Control[] { label, buttonsgroup };
- } else {
- Composite buttonsgroup= getSelectionButtonsGroup(parent);
- GridData gd= new GridData();
- gd.horizontalSpan= nColumns;
- buttonsgroup.setLayoutData(gd);
-
- return new Control[] { buttonsgroup };
- }
- }
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public int getNumberOfControls() {
- return (fGroupBorderStyle == SWT.NONE) ? 2 : 1;
- }
-
- // ------- ui creation
-
- private Button createSelectionButton(int index, Composite group, SelectionListener listener) {
- Button button= new Button(group, fButtonsStyle | SWT.LEFT);
- button.setFont(group.getFont());
- button.setText(fButtonNames[index]);
- button.setEnabled(isEnabled() && fButtonsEnabled[index]);
- button.setSelection(fButtonsSelected[index]);
- button.addSelectionListener(listener);
- button.setLayoutData(new GridData());
- return button;
- }
-
- /**
- * Returns the group widget. When called the first time, the widget will be created.
- * @param parent The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Composite getSelectionButtonsGroup(Composite parent) {
- if (fButtonComposite == null) {
- assertCompositeNotNull(parent);
-
- GridLayout layout= new GridLayout();
- layout.makeColumnsEqualWidth= true;
- layout.numColumns= fGroupNumberOfColumns;
-
- if (fGroupBorderStyle != SWT.NONE) {
- Group group= new Group(parent, fGroupBorderStyle);
- group.setFont(parent.getFont());
- if (fLabelText != null && fLabelText.length() > 0) {
- group.setText(fLabelText);
- }
- fButtonComposite= group;
- } else {
- fButtonComposite= new Composite(parent, SWT.NONE);
- fButtonComposite.setFont(parent.getFont());
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- }
-
- fButtonComposite.setLayout(layout);
-
- SelectionListener listener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- doWidgetSelected(e);
- }
- public void widgetSelected(SelectionEvent e) {
- doWidgetSelected(e);
- }
- };
- int nButtons= fButtonNames.length;
- fButtons= new Button[nButtons];
- for (int i= 0; i < nButtons; i++) {
- fButtons[i]= createSelectionButton(i, fButtonComposite, listener);
- }
- int nRows= nButtons / fGroupNumberOfColumns;
- int nFillElements= nRows * fGroupNumberOfColumns - nButtons;
- for (int i= 0; i < nFillElements; i++) {
- createEmptySpace(fButtonComposite);
- }
- }
- return fButtonComposite;
- }
-
- /**
- * Returns a button from the group or <code>null</code> if not yet created.
- */
- public Button getSelectionButton(int index) {
- if (index >= 0 && index < fButtons.length) {
- return fButtons[index];
- }
- return null;
- }
-
- private void doWidgetSelected(SelectionEvent e) {
- Button button= (Button)e.widget;
- for (int i= 0; i < fButtons.length; i++) {
- if (fButtons[i] == button) {
- fButtonsSelected[i]= button.getSelection();
- dialogFieldChanged();
- return;
- }
- }
- }
-
- // ------ model access
-
- /**
- * Returns the selection state of a button contained in the group.
- * @param index The index of the button
- */
- public boolean isSelected(int index) {
- if (index >= 0 && index < fButtonsSelected.length) {
- return fButtonsSelected[index];
- }
- return false;
- }
-
- /**
- * Sets the selection state of a button contained in the group.
- */
- public void setSelection(int index, boolean selected) {
- if (index >= 0 && index < fButtonsSelected.length) {
- if (fButtonsSelected[index] != selected) {
- fButtonsSelected[index]= selected;
- if (fButtons != null) {
- Button button= fButtons[index];
- if (isOkToUse(button)) {
- button.setSelection(selected);
- }
- }
- }
- }
- }
-
- // ------ enable / disable management
-
- protected void updateEnableState() {
- super.updateEnableState();
- if (fButtons != null) {
- boolean enabled= isEnabled();
- for (int i= 0; i < fButtons.length; i++) {
- Button button= fButtons[i];
- if (isOkToUse(button)) {
- button.setEnabled(enabled && fButtonsEnabled[i]);
- }
- }
- }
- }
-
- /**
- * Sets the enable state of a button contained in the group.
- */
- public void enableSelectionButton(int index, boolean enable) {
- if (index >= 0 && index < fButtonsEnabled.length) {
- fButtonsEnabled[index]= enable;
- if (fButtons != null) {
- Button button= fButtons[index];
- if (isOkToUse(button)) {
- button.setEnabled(isEnabled() && enable);
- }
- }
- }
- }
-
-
- /*(non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#refresh()
- */
- public void refresh() {
- super.refresh();
- for (int i= 0; i < fButtons.length; i++) {
- Button button= fButtons[i];
- if (isOkToUse(button)) {
- button.setSelection(fButtonsSelected[i]);
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/Separator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/Separator.java
deleted file mode 100644
index ace57b26..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/Separator.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-
-/**
- * Dialog field describing a separator.
- */
-public class Separator extends DialogField {
-
- private Label fSeparator;
- private int fStyle;
-
- public Separator() {
- this(SWT.NONE);
- }
-
- /**
- * @param style of the separator. See <code>Label</code> for possible
- * styles.
- */
- public Separator(int style) {
- super();
- fStyle= style;
- }
-
- // ------- layout helpers
-
- /**
- * Creates the separator and fills it in a MGridLayout.
- * @param height The height of the separator
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns, int height) {
- assertEnoughColumns(nColumns);
-
- Control separator= getSeparator(parent);
- separator.setLayoutData(gridDataForSeperator(nColumns, height));
-
- return new Control[] { separator };
- }
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- return doFillIntoGrid(parent, nColumns, 4);
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 1;
- }
-
- protected static GridData gridDataForSeperator(int span, int height) {
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.verticalAlignment= GridData.BEGINNING;
- gd.heightHint= height;
- gd.horizontalSpan= span;
- return gd;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created separator.
- * @param parent The parent composite or <code>null</code> if the widget has
- * already been created.
- */
- public Control getSeparator(Composite parent) {
- if (fSeparator == null) {
- assertCompositeNotNull(parent);
- fSeparator= new Label(parent, fStyle);
- }
- return fSeparator;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java
deleted file mode 100644
index a6fe7fba..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * Dialog field containing a label, text control and a button control.
- */
-public class StringButtonDialogField extends StringDialogField {
-
- private Button fBrowseButton;
- private String fBrowseButtonLabel;
- private IStringButtonAdapter fStringButtonAdapter;
-
- private boolean fButtonEnabled;
-
- public StringButtonDialogField(IStringButtonAdapter adapter) {
- super();
- fStringButtonAdapter= adapter;
- fBrowseButtonLabel= "!Browse...!"; //$NON-NLS-1$
- fButtonEnabled= true;
- }
-
- /**
- * Sets the label of the button.
- */
- public void setButtonLabel(String label) {
- fBrowseButtonLabel= label;
- }
-
- // ------ adapter communication
-
- /**
- * Programmatical pressing of the button
- */
- public void changeControlPressed() {
- fStringButtonAdapter.changeControlPressed(this);
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(1));
- Text text= getTextControl(parent);
- text.setLayoutData(gridDataForText(nColumns - 2));
- Button button= getChangeControl(parent);
- button.setLayoutData(gridDataForButton(button, 1));
-
- return new Control[] { label, text, button };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 3;
- }
-
- protected static GridData gridDataForButton(Button button, int span) {
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalSpan= span;
- gd.widthHint = SWTUtil.getButtonWidthHint(button);
- return gd;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created buttom widget.
- * @param parent The parent composite or <code>null</code> if the widget has
- * already been created.
- */
- public Button getChangeControl(Composite parent) {
- if (fBrowseButton == null) {
- assertCompositeNotNull(parent);
-
- fBrowseButton= new Button(parent, SWT.PUSH);
- fBrowseButton.setFont(parent.getFont());
- fBrowseButton.setText(fBrowseButtonLabel);
- fBrowseButton.setEnabled(isEnabled() && fButtonEnabled);
- fBrowseButton.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- changeControlPressed();
- }
- public void widgetSelected(SelectionEvent e) {
- changeControlPressed();
- }
- });
-
- }
- return fBrowseButton;
- }
-
- // ------ enable / disable management
-
- /**
- * Sets the enable state of the button.
- */
- public void enableButton(boolean enable) {
- if (isOkToUse(fBrowseButton)) {
- fBrowseButton.setEnabled(isEnabled() && enable);
- }
- fButtonEnabled= enable;
- }
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
- if (isOkToUse(fBrowseButton)) {
- fBrowseButton.setEnabled(isEnabled() && fButtonEnabled);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java
deleted file mode 100644
index ad0bb626..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Dialog field containing a label, text control, status label and a button control.
- * The status label can be either a image or text label, and can be usd to give
- * additional information about the current element chosen.
- */
-public class StringButtonStatusDialogField extends StringButtonDialogField {
-
- private Label fStatusLabelControl;
- private Object fStatus; // String or ImageDescriptor
-
- private String fWidthHintString;
- private int fWidthHint;
-
- public StringButtonStatusDialogField(IStringButtonAdapter adapter) {
- super(adapter);
- fStatus= null;
- fWidthHintString= null;
- fWidthHint= -1;
- }
-
- // ------ set status
-
- /**
- * Sets the status string.
- */
- public void setStatus(String status) {
- if (isOkToUse(fStatusLabelControl)) {
- fStatusLabelControl.setText(status);
- }
- fStatus= status;
- }
-
- /**
- * Sets the status image.
- * Caller is responsible to dispose image
- */
- public void setStatus(Image image) {
- if (isOkToUse(fStatusLabelControl)) {
- if (image == null) {
- fStatusLabelControl.setImage(null);
- } else {
- fStatusLabelControl.setImage(image);
- }
- }
- fStatus= image;
- }
-
- /**
- * Sets the staus string hint of the status label.
- * The string is used to calculate the size of the status label.
- */
- public void setStatusWidthHint(String widthHintString) {
- fWidthHintString= widthHintString;
- fWidthHint= -1;
- }
-
- /**
- * Sets the width hint of the status label.
- */
- public void setStatusWidthHint(int widthHint) {
- fWidthHint= widthHint;
- fWidthHintString= null;
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(1));
- Text text= getTextControl(parent);
- text.setLayoutData(gridDataForText(nColumns - 3));
- Label status= getStatusLabelControl(parent);
- status.setLayoutData(gridDataForStatusLabel(parent, 1));
- Button button= getChangeControl(parent);
- button.setLayoutData(gridDataForButton(button, 1));
-
- return new Control[] { label, text, status, button };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 4;
- }
-
- protected GridData gridDataForStatusLabel(Control aControl, int span) {
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.BEGINNING;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalIndent= 0;
- if (fWidthHintString != null) {
- GC gc= new GC(aControl);
- gc.setFont(JFaceResources.getDialogFont());
- gd.widthHint= gc.textExtent(fWidthHintString).x;
- gc.dispose();
- } else if (fWidthHint != -1) {
- gd.widthHint= fWidthHint;
- } else {
- gd.widthHint= SWT.DEFAULT;
- }
- return gd;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created status label widget.
- * @param parent The parent composite or <code>null</code> when the widget has
- * already been created.
- */
- public Label getStatusLabelControl(Composite parent) {
- if (fStatusLabelControl == null) {
- assertCompositeNotNull(parent);
- fStatusLabelControl= new Label(parent, SWT.LEFT);
- fStatusLabelControl.setFont(parent.getFont());
- fStatusLabelControl.setEnabled(isEnabled());
- if (fStatus instanceof Image) {
- fStatusLabelControl.setImage((Image)fStatus);
- } else if (fStatus instanceof String) {
- fStatusLabelControl.setText((String)fStatus);
- } else {
- // must be null
- }
- }
- return fStatusLabelControl;
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
- if (isOkToUse(fStatusLabelControl)) {
- fStatusLabelControl.setEnabled(isEnabled());
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#refresh()
- */
- public void refresh() {
- super.refresh();
- if (fStatus instanceof String) {
- setStatus((String) fStatus);
- } else {
- setStatus((Image) fStatus);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringDialogField.java
deleted file mode 100644
index fd373472..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/StringDialogField.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-
-/**
- * Dialog field containing a label and a text control.
- */
-public class StringDialogField extends DialogField {
-
- private String fText;
- private Text fTextControl;
- private ModifyListener fModifyListener;
- private IContentAssistProcessor fContentAssistProcessor;
-
- public StringDialogField() {
- super();
- fText= ""; //$NON-NLS-1$
- }
-
- public void setContentAssistProcessor(IContentAssistProcessor processor) {
- fContentAssistProcessor= processor;
- if (fContentAssistProcessor != null && isOkToUse(fTextControl)) {
- ControlContentAssistHelper.createTextContentAssistant(fTextControl, fContentAssistProcessor);
- }
- }
-
- public IContentAssistProcessor getContentAssistProcessor() {
- return fContentAssistProcessor;
- }
-
- // ------- layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- label.setLayoutData(gridDataForLabel(1));
- Text text= getTextControl(parent);
- text.setLayoutData(gridDataForText(nColumns - 1));
-
- return new Control[] { label, text };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 2;
- }
-
- protected static GridData gridDataForText(int span) {
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.horizontalSpan= span;
- return gd;
- }
-
- // ------- focus methods
-
- /*
- * @see DialogField#setFocus
- */
- public boolean setFocus() {
- if (isOkToUse(fTextControl)) {
- fTextControl.setFocus();
- fTextControl.setSelection(0, fTextControl.getText().length());
- }
- return true;
- }
-
- // ------- ui creation
-
- /**
- * Creates or returns the created text control.
- * @param parent The parent composite or <code>null</code> when the widget has
- * already been created.
- */
- public Text getTextControl(Composite parent) {
- if (fTextControl == null) {
- assertCompositeNotNull(parent);
- fModifyListener= new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- doModifyText(e);
- }
- };
-
- fTextControl= new Text(parent, SWT.SINGLE | SWT.BORDER);
- // moved up due to 1GEUNW2
- fTextControl.setText(fText);
- fTextControl.setFont(parent.getFont());
- fTextControl.addModifyListener(fModifyListener);
-
- fTextControl.setEnabled(isEnabled());
- if (fContentAssistProcessor != null) {
- ControlContentAssistHelper.createTextContentAssistant(fTextControl, fContentAssistProcessor);
- }
- }
- return fTextControl;
- }
-
- public void setTextFieldEditable(boolean editable) {
- fTextControl.setEditable(editable);
- }
-
- private void doModifyText(ModifyEvent e) {
- if (isOkToUse(fTextControl)) {
- fText= fTextControl.getText();
- }
- dialogFieldChanged();
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
- if (isOkToUse(fTextControl)) {
- fTextControl.setEnabled(isEnabled());
- }
- }
-
- // ------ text access
-
- /**
- * Gets the text. Can not be <code>null</code>
- */
- public String getText() {
- return fText;
- }
-
- /**
- * Sets the text. Triggers a dialog-changed event.
- */
- public void setText(String text) {
- fText= text;
- if (isOkToUse(fTextControl)) {
- fTextControl.setText(text);
- } else {
- dialogFieldChanged();
- }
- }
-
- /**
- * Sets the text without triggering a dialog-changed event.
- */
- public void setTextWithoutUpdate(String text) {
- fText= text;
- if (isOkToUse(fTextControl)) {
- fTextControl.removeModifyListener(fModifyListener);
- fTextControl.setText(text);
- fTextControl.addModifyListener(fModifyListener);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField#refresh()
- */
- public void refresh() {
- super.refresh();
- if (isOkToUse(fTextControl)) {
- setTextWithoutUpdate(fText);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/TreeListDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/TreeListDialogField.java
deleted file mode 100644
index f7c64352..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/TreeListDialogField.java
+++ /dev/null
@@ -1,909 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-
-/**
- * A list with a button bar.
- * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
- * List model is independent of widget creation.
- * DialogFields controls are: Label, List and Composite containing buttons.
- */
-public class TreeListDialogField extends DialogField {
-
- protected TreeViewer fTree;
- protected ILabelProvider fLabelProvider;
- protected TreeViewerAdapter fTreeViewerAdapter;
- protected List fElements;
- protected ViewerComparator fViewerComparator;
-
- protected String[] fButtonLabels;
- private Button[] fButtonControls;
-
- private boolean[] fButtonsEnabled;
-
- private int fRemoveButtonIndex;
- private int fUpButtonIndex;
- private int fDownButtonIndex;
-
- private Label fLastSeparator;
-
- private Tree fTreeControl;
- private Composite fButtonsControl;
- private ISelection fSelectionWhenEnabled;
-
- private ITreeListAdapter fTreeAdapter;
-
- private Object fParentElement;
- private int fTreeExpandLevel;
-
- /**
- * @param adapter Can be <code>null</code>.
- */
- public TreeListDialogField(ITreeListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
- super();
- fTreeAdapter= adapter;
-
- fLabelProvider= lprovider;
- fTreeViewerAdapter= new TreeViewerAdapter();
- fParentElement= this;
-
- fElements= new ArrayList(10);
-
- fButtonLabels= buttonLabels;
- if (fButtonLabels != null) {
- int nButtons= fButtonLabels.length;
- fButtonsEnabled= new boolean[nButtons];
- for (int i= 0; i < nButtons; i++) {
- fButtonsEnabled[i]= true;
- }
- }
-
- fTree= null;
- fTreeControl= null;
- fButtonsControl= null;
-
- fRemoveButtonIndex= -1;
- fUpButtonIndex= -1;
- fDownButtonIndex= -1;
-
- fTreeExpandLevel= 0;
- }
-
- /**
- * Sets the index of the 'remove' button in the button label array passed in
- * the constructor. The behavior of the button marked as the 'remove' button
- * will then be handled internally. (enable state, button invocation
- * behavior)
- */
- public void setRemoveButtonIndex(int removeButtonIndex) {
- Assert.isTrue(removeButtonIndex < fButtonLabels.length);
- fRemoveButtonIndex= removeButtonIndex;
- }
-
- /**
- * Sets the index of the 'up' button in the button label array passed in the
- * constructor. The behavior of the button marked as the 'up' button will
- * then be handled internally.
- * (enable state, button invocation behavior)
- */
- public void setUpButtonIndex(int upButtonIndex) {
- Assert.isTrue(upButtonIndex < fButtonLabels.length);
- fUpButtonIndex= upButtonIndex;
- }
-
- /**
- * Sets the index of the 'down' button in the button label array passed in
- * the constructor. The behavior of the button marked as the 'down' button
- * will then be handled internally. (enable state, button invocation
- * behavior)
- */
- public void setDownButtonIndex(int downButtonIndex) {
- Assert.isTrue(downButtonIndex < fButtonLabels.length);
- fDownButtonIndex= downButtonIndex;
- }
-
- /**
- * Sets the viewer comparator.
- * @param viewerComparator The viewer comparator to set
- */
- public void setViewerComparator(ViewerComparator viewerComparator) {
- fViewerComparator= viewerComparator;
- }
-
- public void setTreeExpansionLevel(int level) {
- fTreeExpandLevel= level;
- if (isOkToUse(fTreeControl) && fTreeExpandLevel > 0) {
- fTree.expandToLevel(level);
- }
- }
-
- // ------ adapter communication
-
- private void buttonPressed(int index) {
- if (!managedButtonPressed(index) && fTreeAdapter != null) {
- fTreeAdapter.customButtonPressed(this, index);
- }
- }
-
- /**
- * Checks if the button pressed is handled internally
- * @return Returns true if button has been handled.
- */
- protected boolean managedButtonPressed(int index) {
- if (index == fRemoveButtonIndex) {
- remove();
- } else if (index == fUpButtonIndex) {
- up();
- } else if (index == fDownButtonIndex) {
- down();
- } else {
- return false;
- }
- return true;
- }
-
- // ------ layout helpers
-
- /*
- * @see DialogField#doFillIntoGrid
- */
- public Control[] doFillIntoGrid(Composite parent, int nColumns) {
- PixelConverter converter= new PixelConverter(parent);
-
- assertEnoughColumns(nColumns);
-
- Label label= getLabelControl(parent);
- GridData gd= gridDataForLabel(1);
- gd.verticalAlignment= GridData.BEGINNING;
- label.setLayoutData(gd);
-
- Control list= getTreeControl(parent);
- gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
- gd.horizontalSpan= nColumns - 2;
- gd.widthHint= converter.convertWidthInCharsToPixels(50);
- gd.heightHint= converter.convertHeightInCharsToPixels(6);
-
- list.setLayoutData(gd);
-
- Composite buttons= getButtonBox(parent);
- gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= false;
- gd.verticalAlignment= GridData.FILL;
- gd.grabExcessVerticalSpace= true;
- gd.horizontalSpan= 1;
- buttons.setLayoutData(gd);
-
- return new Control[] { label, list, buttons };
- }
-
- /*
- * @see DialogField#getNumberOfControls
- */
- public int getNumberOfControls() {
- return 3;
- }
-
- /**
- * Sets the minimal width of the buttons. Must be called after widget creation.
- */
- public void setButtonsMinWidth(int minWidth) {
- if (fLastSeparator != null) {
- ((GridData) fLastSeparator.getLayoutData()).widthHint= minWidth;
- }
- }
-
- // ------ UI creation
-
- /**
- * Returns the tree control. When called the first time, the control will be
- * created.
- * @param parent The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Control getTreeControl(Composite parent) {
- if (fTreeControl == null) {
- assertCompositeNotNull(parent);
-
- fTree= createTreeViewer(parent);
-
- fTreeControl= (Tree) fTree.getControl();
- fTreeControl.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- handleKeyPressed(e);
- }
- });
- fTree.setContentProvider(fTreeViewerAdapter);
- fTree.setLabelProvider(fLabelProvider);
- fTree.addSelectionChangedListener(fTreeViewerAdapter);
- fTree.addDoubleClickListener(fTreeViewerAdapter);
-
- fTree.setInput(fParentElement);
- fTree.expandToLevel(fTreeExpandLevel);
-
- if (fViewerComparator != null) {
- fTree.setComparator(fViewerComparator);
- }
-
- fTreeControl.setEnabled(isEnabled());
- if (fSelectionWhenEnabled != null) {
- postSetSelection(fSelectionWhenEnabled);
- }
- }
- return fTreeControl;
- }
-
- /**
- * Returns the internally used table viewer.
- */
- public TreeViewer getTreeViewer() {
- return fTree;
- }
-
- /*
- * Subclasses may override to specify a different style.
- */
- protected int getTreeStyle() {
- int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL;
- return style;
- }
-
- protected TreeViewer createTreeViewer(Composite parent) {
- Tree tree= new Tree(parent, getTreeStyle());
- tree.setFont(parent.getFont());
- return new TreeViewer(tree);
- }
-
- protected Button createButton(Composite parent, String label, SelectionListener listener) {
- Button button= new Button(parent, SWT.PUSH);
- button.setFont(parent.getFont());
- button.setText(label);
- button.addSelectionListener(listener);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.grabExcessHorizontalSpace= true;
- gd.verticalAlignment= GridData.BEGINNING;
- gd.widthHint= SWTUtil.getButtonWidthHint(button);
-
- button.setLayoutData(gd);
- return button;
- }
-
- private Label createSeparator(Composite parent) {
- Label separator= new Label(parent, SWT.NONE);
- separator.setFont(parent.getFont());
- separator.setVisible(false);
- GridData gd= new GridData();
- gd.horizontalAlignment= GridData.FILL;
- gd.verticalAlignment= GridData.BEGINNING;
- gd.heightHint= 4;
- separator.setLayoutData(gd);
- return separator;
- }
-
- /**
- * Returns the composite containing the buttons. When called the first time, the control
- * will be created.
- * @param parent The parent composite when called the first time, or <code>null</code>
- * after.
- */
- public Composite getButtonBox(Composite parent) {
- if (fButtonsControl == null) {
- assertCompositeNotNull(parent);
-
- SelectionListener listener= new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- doButtonSelected(e);
- }
- public void widgetSelected(SelectionEvent e) {
- doButtonSelected(e);
- }
- };
-
- Composite contents= new Composite(parent, SWT.NONE);
- contents.setFont(parent.getFont());
-
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- contents.setLayout(layout);
-
- if (fButtonLabels != null) {
- fButtonControls= new Button[fButtonLabels.length];
- for (int i= 0; i < fButtonLabels.length; i++) {
- String currLabel= fButtonLabels[i];
- if (currLabel != null) {
- fButtonControls[i]= createButton(contents, currLabel, listener);
- fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
- } else {
- fButtonControls[i]= null;
- createSeparator(contents);
- }
- }
- }
-
- fLastSeparator= createSeparator(contents);
-
- updateButtonState();
- fButtonsControl= contents;
- }
-
- return fButtonsControl;
- }
-
- private void doButtonSelected(SelectionEvent e) {
- if (fButtonControls != null) {
- for (int i= 0; i < fButtonControls.length; i++) {
- if (e.widget == fButtonControls[i]) {
- buttonPressed(i);
- return;
- }
- }
- }
- }
-
- /**
- * Handles key events in the table viewer. Specifically
- * when the delete key is pressed.
- */
- protected void handleKeyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- if (fRemoveButtonIndex != -1 && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) {
- managedButtonPressed(fRemoveButtonIndex);
- return;
- }
- }
- fTreeAdapter.keyPressed(this, event);
- }
-
- // ------ enable / disable management
-
- /*
- * @see DialogField#dialogFieldChanged
- */
- public void dialogFieldChanged() {
- super.dialogFieldChanged();
- updateButtonState();
- }
-
- /*
- * Updates the enable state of the all buttons
- */
- protected void updateButtonState() {
- if (fButtonControls != null && isOkToUse(fTreeControl) && fTreeControl.isEnabled()) {
- ISelection sel= fTree.getSelection();
- for (int i= 0; i < fButtonControls.length; i++) {
- Button button= fButtonControls[i];
- if (isOkToUse(button)) {
- button.setEnabled(isButtonEnabled(sel, i));
- }
- }
- }
- }
-
-
- protected boolean containsAttributes(List selected) {
- for (int i= 0; i < selected.size(); i++) {
- if (!fElements.contains(selected.get(i))) {
- return true;
- }
- }
- return false;
- }
-
-
- protected boolean getManagedButtonState(ISelection sel, int index) {
- List selected= getSelectedElements();
- boolean hasAttributes= containsAttributes(selected);
- if (index == fRemoveButtonIndex) {
- return !selected.isEmpty() && !hasAttributes;
- } else if (index == fUpButtonIndex) {
- return !sel.isEmpty() && !hasAttributes && canMoveUp(selected);
- } else if (index == fDownButtonIndex) {
- return !sel.isEmpty() && !hasAttributes && canMoveDown(selected);
- }
- return true;
- }
-
- /*
- * @see DialogField#updateEnableState
- */
- protected void updateEnableState() {
- super.updateEnableState();
-
- boolean enabled= isEnabled();
- if (isOkToUse(fTreeControl)) {
- if (!enabled) {
- if (fSelectionWhenEnabled == null) {
- fSelectionWhenEnabled= fTree.getSelection();
- selectElements(null);
- }
- } else if (fSelectionWhenEnabled != null) {
- selectElements(fSelectionWhenEnabled);
- }
- fTreeControl.setEnabled(enabled);
- }
- updateButtonState();
- }
-
- /**
- * Sets a button enabled or disabled.
- */
- public void enableButton(int index, boolean enable) {
- if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
- fButtonsEnabled[index]= enable;
- updateButtonState();
- }
- }
-
- private boolean isButtonEnabled(ISelection sel, int index) {
- boolean extraState= getManagedButtonState(sel, index);
- return isEnabled() && extraState && fButtonsEnabled[index];
- }
-
- // ------ model access
-
- /**
- * Sets the elements shown in the list.
- */
- public void setElements(List elements) {
- fElements= new ArrayList(elements);
- refresh();
- if (isOkToUse(fTreeControl)) {
- fTree.expandToLevel(fTreeExpandLevel);
- }
- dialogFieldChanged();
- }
-
- /**
- * Gets the elements shown in the list.
- * The list returned is a copy, so it can be modified by the user.
- */
- public List getElements() {
- return new ArrayList(fElements);
- }
-
- /**
- * Gets the element shown at the given index.
- */
- public Object getElement(int index) {
- return fElements.get(index);
- }
-
- /**
- * Gets the index of an element in the list or -1 if element is not in list.
- */
- public int getIndexOfElement(Object elem) {
- return fElements.indexOf(elem);
- }
-
- /**
- * Replace an element.
- */
- public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
- int idx= fElements.indexOf(oldElement);
- if (idx != -1) {
- fElements.set(idx, newElement);
- if (isOkToUse(fTreeControl)) {
- List selected= getSelectedElements();
- if (selected.remove(oldElement)) {
- selected.add(newElement);
- }
- boolean isExpanded= fTree.getExpandedState(oldElement);
- fTree.remove(oldElement);
- fTree.add(fParentElement, newElement);
- if (isExpanded) {
- fTree.expandToLevel(newElement, fTreeExpandLevel);
- }
- selectElements(new StructuredSelection(selected));
- }
- dialogFieldChanged();
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Adds an element at the end of the tree list.
- */
- public boolean addElement(Object element) {
- if (fElements.contains(element)) {
- return false;
- }
- fElements.add(element);
- if (isOkToUse(fTreeControl)) {
- fTree.add(fParentElement, element);
- fTree.expandToLevel(element, fTreeExpandLevel);
- }
- dialogFieldChanged();
- return true;
- }
-
- /**
- * Adds elements at the end of the tree list.
- */
- public boolean addElements(List elements) {
- int nElements= elements.size();
-
- if (nElements > 0) {
- // filter duplicated
- ArrayList elementsToAdd= new ArrayList(nElements);
-
- for (int i= 0; i < nElements; i++) {
- Object elem= elements.get(i);
- if (!fElements.contains(elem)) {
- elementsToAdd.add(elem);
- }
- }
- if (!elementsToAdd.isEmpty()) {
- fElements.addAll(elementsToAdd);
- if (isOkToUse(fTreeControl)) {
- fTree.add(fParentElement, elementsToAdd.toArray());
- for (int i= 0; i < elementsToAdd.size(); i++) {
- fTree.expandToLevel(elementsToAdd.get(i), fTreeExpandLevel);
- }
- }
- dialogFieldChanged();
- return true;
- }
- }
- return false;
- }
-
- /**
- * Adds an element at a position.
- */
- public void insertElementAt(Object element, int index) {
- if (fElements.contains(element)) {
- return;
- }
- fElements.add(index, element);
- if (isOkToUse(fTreeControl)) {
- fTree.add(fParentElement, element);
- if (fTreeExpandLevel != -1) {
- fTree.expandToLevel(element, fTreeExpandLevel);
- }
- }
-
- dialogFieldChanged();
- }
-
- /**
- * Adds an element at a position.
- */
- public void removeAllElements() {
- if (fElements.size() > 0) {
- fElements.clear();
- refresh();
- dialogFieldChanged();
- }
- }
-
- /**
- * Removes an element from the list.
- */
- public void removeElement(Object element) throws IllegalArgumentException {
- if (fElements.remove(element)) {
- if (isOkToUse(fTreeControl)) {
- fTree.remove(element);
- }
- dialogFieldChanged();
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Removes elements from the list.
- */
- public void removeElements(List elements) {
- if (elements.size() > 0) {
- fElements.removeAll(elements);
- if (isOkToUse(fTreeControl)) {
- fTree.remove(elements.toArray());
- }
- dialogFieldChanged();
- }
- }
-
- /**
- * Gets the number of elements
- */
- public int getSize() {
- return fElements.size();
- }
-
- public void selectElements(ISelection selection) {
- fSelectionWhenEnabled= selection;
- if (isOkToUse(fTreeControl)) {
- fTree.setSelection(selection, true);
- }
- }
-
- public void selectFirstElement() {
- Object element= null;
- if (fViewerComparator != null) {
- Object[] arr= fElements.toArray();
- fViewerComparator.sort(fTree, arr);
- if (arr.length > 0) {
- element= arr[0];
- }
- } else {
- if (fElements.size() > 0) {
- element= fElements.get(0);
- }
- }
- if (element != null) {
- selectElements(new StructuredSelection(element));
- }
- }
-
- public void postSetSelection(final ISelection selection) {
- if (isOkToUse(fTreeControl)) {
- Display d= fTreeControl.getDisplay();
- d.asyncExec(new Runnable() {
- public void run() {
- if (isOkToUse(fTreeControl)) {
- selectElements(selection);
- }
- }
- });
- }
- }
-
- /**
- * Refreshes the tree.
- */
- public void refresh() {
- super.refresh();
- if (isOkToUse(fTreeControl)) {
- fTree.refresh();
- }
- }
-
- /**
- * Refreshes the tree.
- */
- public void refresh(Object element) {
- if (isOkToUse(fTreeControl)) {
- fTree.refresh(element);
- }
- }
-
- /**
- * Updates the element.
- */
- public void update(Object element) {
- if (isOkToUse(fTreeControl)) {
- fTree.update(element, null);
- }
- }
-
- // ------- list maintenance
-
- private List moveUp(List elements, List move) {
- int nElements= elements.size();
- List res= new ArrayList(nElements);
- Object floating= null;
- for (int i= 0; i < nElements; i++) {
- Object curr= elements.get(i);
- if (move.contains(curr)) {
- res.add(curr);
- } else {
- if (floating != null) {
- res.add(floating);
- }
- floating= curr;
- }
- }
- if (floating != null) {
- res.add(floating);
- }
- return res;
- }
-
- private void moveUp(List toMoveUp) {
- if (toMoveUp.size() > 0) {
- setElements(moveUp(fElements, toMoveUp));
- fTree.reveal(toMoveUp.get(0));
- }
- }
-
- private void moveDown(List toMoveDown) {
- if (toMoveDown.size() > 0) {
- setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
- fTree.reveal(toMoveDown.get(toMoveDown.size() - 1));
- }
- }
-
- private List reverse(List p) {
- List reverse= new ArrayList(p.size());
- for (int i= p.size() - 1; i >= 0; i--) {
- reverse.add(p.get(i));
- }
- return reverse;
- }
-
- private void remove() {
- removeElements(getSelectedElements());
- }
-
- private void up() {
- moveUp(getSelectedElements());
- }
-
- private void down() {
- moveDown(getSelectedElements());
- }
-
- private boolean canMoveUp(List selectedElements) {
- if (isOkToUse(fTreeControl)) {
- int nSelected= selectedElements.size();
- int nElements= fElements.size();
- for (int i= 0; i < nElements && nSelected > 0; i++) {
- if (!selectedElements.contains(fElements.get(i))) {
- return true;
- }
- nSelected--;
- }
- }
- return false;
- }
-
- private boolean canMoveDown(List selectedElements) {
- if (isOkToUse(fTreeControl)) {
- int nSelected= selectedElements.size();
- for (int i= fElements.size() - 1; i >= 0 && nSelected > 0; i--) {
- if (!selectedElements.contains(fElements.get(i))) {
- return true;
- }
- nSelected--;
- }
- }
- return false;
- }
-
- /**
- * Returns the selected elements.
- */
- public List getSelectedElements() {
- ArrayList result= new ArrayList();
- if (isOkToUse(fTreeControl)) {
- ISelection selection= fTree.getSelection();
- if (selection instanceof IStructuredSelection) {
- Iterator iter= ((IStructuredSelection)selection).iterator();
- while (iter.hasNext()) {
- result.add(iter.next());
- }
- }
- }
- return result;
- }
-
- public void expandElement(Object element, int level) {
- if (isOkToUse(fTreeControl)) {
- fTree.expandToLevel(element, level);
- }
- }
-
-
- // ------- TreeViewerAdapter
-
- private class TreeViewerAdapter implements ITreeContentProvider, ISelectionChangedListener, IDoubleClickListener {
-
- private final Object[] NO_ELEMENTS= new Object[0];
-
- // ------- ITreeContentProvider Interface ------------
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // will never happen
- }
-
- public boolean isDeleted(Object element) {
- return false;
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object obj) {
- return fElements.toArray();
- }
-
- public Object[] getChildren(Object element) {
- if (fTreeAdapter != null) {
- return fTreeAdapter.getChildren(TreeListDialogField.this, element);
- }
- return NO_ELEMENTS;
- }
-
- public Object getParent(Object element) {
- if (!fElements.contains(element) && fTreeAdapter != null) {
- return fTreeAdapter.getParent(TreeListDialogField.this, element);
- }
- return fParentElement;
- }
-
- public boolean hasChildren(Object element) {
- if (fTreeAdapter != null) {
- return fTreeAdapter.hasChildren(TreeListDialogField.this, element);
- }
- return false;
- }
-
- // ------- ISelectionChangedListener Interface ------------
-
- public void selectionChanged(SelectionChangedEvent event) {
- doListSelected(event);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
- */
- public void doubleClick(DoubleClickEvent event) {
- doDoubleClick(event);
- }
-
- }
-
- protected void doListSelected(SelectionChangedEvent event) {
- updateButtonState();
- if (fTreeAdapter != null) {
- fTreeAdapter.selectionChanged(this);
- }
- }
-
- protected void doDoubleClick(DoubleClickEvent event) {
- if (fTreeAdapter != null) {
- fTreeAdapter.doubleClicked(this);
- }
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java
deleted file mode 100644
index adc2a789..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetPage;
-
-/**
- *
- */
-public abstract class AbstractWorkingSetWizardPage extends WizardPage implements IWorkingSetPage {
-
- private boolean fIsFirstValidation;
- private Text fWorkingSetName;
- private IWorkingSet fWorkingSet;
-
- /**
- * Default constructor.
- */
- public AbstractWorkingSetWizardPage(String pageid, String title, ImageDescriptor image) {
- super(pageid, title, image);
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout());
- composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
- setControl(composite);
-
- Label label= new Label(composite, SWT.WRAP);
- label.setText(WorkingSetMessages.AbstractWorkingSetPage_workingSet_name);
- GridData gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER);
- label.setLayoutData(gd);
-
- fWorkingSetName= new Text(composite, SWT.SINGLE | SWT.BORDER);
- fWorkingSetName.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
- fWorkingSetName.addModifyListener(
- new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- }
- );
- fWorkingSetName.setFocus();
-
- Dialog.applyDialogFont(composite);
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public IWorkingSet getSelection() {
- return fWorkingSet;
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public void setSelection(IWorkingSet workingSet) {
- Assert.isNotNull(workingSet, "Working set must not be null"); //$NON-NLS-1$
- fWorkingSet= workingSet;
- if (getContainer() != null && getShell() != null && fWorkingSetName != null) {
- fWorkingSetName.setText(fWorkingSet.getName());
- validateInput();
- }
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public void finish() {
- String workingSetName= fWorkingSetName.getText();
- if (fWorkingSet == null) {
- fWorkingSet= createWorkingSet(workingSetName);
- }
- fWorkingSet.setName(workingSetName);
- }
-
- protected abstract IWorkingSet createWorkingSet(String workingSetName);
-
- private void validateInput() {
- String errorMessage= null;
- String newText= fWorkingSetName.getText();
-
- if (newText.equals(newText.trim()) == false)
- errorMessage = WorkingSetMessages.AbstractWorkingSetPage_warning_nameWhitespace;
- if (newText.equals("")) { //$NON-NLS-1$
- if (fIsFirstValidation) {
- setPageComplete(false);
- fIsFirstValidation= false;
- return;
- } else {
- errorMessage= WorkingSetMessages.AbstractWorkingSetPage_warning_nameMustNotBeEmpty;
- }
- }
-
- fIsFirstValidation= false;
-
- if (errorMessage == null && (fWorkingSet == null || newText.equals(fWorkingSet.getName()) == false)) {
- IWorkingSet[] workingSets= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets();
- for (int i= 0; i < workingSets.length; i++) {
- if (newText.equals(workingSets[i].getName())) {
- errorMessage= WorkingSetMessages.AbstractWorkingSetPage_warning_workingSetExists;
- }
- }
- }
- setErrorMessage(errorMessage);
- setPageComplete(errorMessage == null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java
deleted file mode 100644
index a92b8ba0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-
-/**
- * Clears the selected working set in the action group's view.
- *
- *
- */
-public class ClearWorkingSetAction extends Action {
-
- private WorkingSetFilterActionGroup fActionGroup;
-
- public ClearWorkingSetAction(WorkingSetFilterActionGroup actionGroup) {
- super(WorkingSetMessages.ClearWorkingSetAction_text);
- Assert.isNotNull(actionGroup);
- setToolTipText(WorkingSetMessages.ClearWorkingSetAction_toolTip);
- setEnabled(actionGroup.getWorkingSet() != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CLEAR_WORKING_SET_ACTION);
- fActionGroup= actionGroup;
- }
-
- /*
- * Overrides method from Action
- */
- public void run() {
- fActionGroup.setWorkingSet(null, true);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAction.java
deleted file mode 100644
index d8704cf5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAction.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-
-public class ConfigureWorkingSetAction extends Action {
-
- private final IWorkbenchPartSite fSite;
- private WorkingSetModel fWorkingSetModel;
-
- public ConfigureWorkingSetAction(IWorkbenchPartSite site) {
- super(WorkingSetMessages.ConfigureWorkingSetAction_label);
- fSite= site;
- }
-
- public void setWorkingSetModel(WorkingSetModel model) {
- fWorkingSetModel= model;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- List workingSets= new ArrayList(Arrays.asList(fWorkingSetModel.getAllWorkingSets()));
- IWorkingSet[] activeWorkingSets= fWorkingSetModel.getActiveWorkingSets();
- WorkingSetConfigurationDialog dialog= new WorkingSetConfigurationDialog(
- fSite.getShell(),
- (IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]),
- activeWorkingSets);
- dialog.setSelection(activeWorkingSets);
- if (dialog.open() == IDialogConstants.OK_ID) {
- IWorkingSet[] selection= dialog.getSelection();
- fWorkingSetModel.setActiveWorkingSets(selection);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAssignementAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAssignementAction.java
deleted file mode 100644
index 4c61ee63..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ConfigureWorkingSetAssignementAction.java
+++ /dev/null
@@ -1,573 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerPart;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public final class ConfigureWorkingSetAssignementAction extends SelectionDispatchAction {
-
- private static final class GrayedCheckedModel {
-
- private GrayedCheckedModelElement[] fElements;
- private final Hashtable fLookup;
-
- public GrayedCheckedModel(GrayedCheckedModelElement[] elements) {
- fElements= elements;
- fLookup= new Hashtable();
- for (int i= 0; i < elements.length; i++) {
- fLookup.put(elements[i].getWorkingSet(), elements[i]);
- }
- }
-
- public void addElement(GrayedCheckedModelElement element) {
- ArrayList list= new ArrayList(Arrays.asList(fElements));
- list.add(element);
- fElements= (GrayedCheckedModelElement[])list.toArray(new GrayedCheckedModelElement[list.size()]);
-
- fLookup.put(element.getWorkingSet(), element);
- }
-
- public IWorkingSet[] getAll() {
- IWorkingSet[] result= new IWorkingSet[fElements.length];
- for (int i= 0; i < fElements.length; i++) {
- result[i]= fElements[i].getWorkingSet();
- }
- return result;
- }
-
- public GrayedCheckedModelElement getModelElement(IWorkingSet element) {
- return (GrayedCheckedModelElement)fLookup.get(element);
- }
-
- public IWorkingSet[] getChecked() {
- ArrayList result= new ArrayList();
- for (int i= 0; i < fElements.length; i++) {
- if (fElements[i].isChecked())
- result.add(fElements[i].getWorkingSet());
- }
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
-
- public IWorkingSet[] getGrayed() {
- ArrayList result= new ArrayList();
- for (int i= 0; i < fElements.length; i++) {
- if (fElements[i].isGrayed())
- result.add(fElements[i].getWorkingSet());
- }
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
-
- public void selectAll() {
- for (int i= 0; i < fElements.length; i++) {
- fElements[i].select();
- }
- }
-
- public void deselectAll() {
- for (int i= 0; i < fElements.length; i++) {
- fElements[i].deselect();
- }
- }
-
- }
-
- private final static class GrayedCheckedModelElement {
-
- private final IWorkingSet fWorkingSet;
- private final int fElementCount;
- private int fCheckCount;
-
- public GrayedCheckedModelElement(IWorkingSet workingSet, int checkCount, int elementCount) {
- fWorkingSet= workingSet;
- fCheckCount= checkCount;
- fElementCount= elementCount;
- }
-
- public IWorkingSet getWorkingSet() {
- return fWorkingSet;
- }
-
- public int getCheckCount() {
- return fCheckCount;
- }
-
- public boolean isGrayed() {
- return isChecked() && fCheckCount < fElementCount;
- }
-
- public boolean isChecked() {
- return fCheckCount > 0;
- }
-
- public void deselect() {
- fCheckCount= 0;
- }
-
- public void select() {
- fCheckCount= fElementCount;
- }
-
- }
-
- private final class WorkingSetModelAwareSelectionDialog extends SimpleWorkingSetSelectionDialog {
-
- private CheckboxTableViewer fTableViewer;
- private boolean fShowVisibleOnly;
- private GrayedCheckedModel fModel;
- private final IAdaptable[] fElements;
-
- private WorkingSetModelAwareSelectionDialog(Shell shell, GrayedCheckedModel model, IAdaptable[] elements) {
- super(shell, VALID_WORKING_SET_IDS, model.getChecked());
- setTitle(WorkingSetMessages.ConfigureWorkingSetAssignementAction_WorkingSetAssignments_title);
- fModel= model;
- fShowVisibleOnly= true;
- fElements= elements;
- }
-
- public IWorkingSet[] getGrayed() {
- return fModel.getGrayed();
- }
-
- public IWorkingSet[] getSelection() {
- return fModel.getChecked();
- }
-
- protected CheckboxTableViewer createTableViewer(Composite parent) {
- fTableViewer= super.createTableViewer(parent);
- fTableViewer.setGrayedElements(fModel.getGrayed());
- fTableViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- IWorkingSet element= (IWorkingSet)event.getElement();
- fTableViewer.setGrayed(element, false);
- GrayedCheckedModelElement modelElement= fModel.getModelElement(element);
- if (event.getChecked()) {
- modelElement.select();
- } else {
- modelElement.deselect();
- }
- fTableViewer.update(element, null);
- }
- });
-
- createShowVisibleOnly(parent);
-
- return fTableViewer;
- }
-
- protected void selectAll() {
- super.selectAll();
- fModel.selectAll();
- fTableViewer.setGrayedElements(new Object[0]);
- fTableViewer.refresh();
- }
-
- protected void deselectAll() {
- super.deselectAll();
- fModel.deselectAll();
- fTableViewer.setGrayedElements(new Object[0]);
- fTableViewer.refresh();
- }
-
- /**
- * {@inheritDoc}
- */
- protected void addNewWorkingSet(IWorkingSet workingSet) {
- if (fWorkingSetModel != null) {
- IWorkingSet[] workingSets= fWorkingSetModel.getActiveWorkingSets();
- IWorkingSet[] activeWorkingSets= new IWorkingSet[workingSets.length+ 1];
- activeWorkingSets[0]= workingSet;
- System.arraycopy(workingSets, 0, activeWorkingSets, 1, workingSets.length);
- fWorkingSetModel.setActiveWorkingSets(activeWorkingSets);
- }
-
- int checkCount= 0;
- for (int i= 0; i < fElements.length; i++) {
- IAdaptable adapted= adapt(workingSet, fElements[i]);
- if (adapted != null && contains(workingSet, adapted)) {
- checkCount++;
- }
- }
-
- fModel.addElement(new GrayedCheckedModelElement(workingSet, checkCount, fElements.length));
-
- fTableViewer.setInput(fModel.getAll());
- fTableViewer.refresh();
-
- fTableViewer.setCheckedElements(fModel.getChecked());
- fTableViewer.setGrayedElements(fModel.getGrayed());
-
- fTableViewer.setSelection(new StructuredSelection(workingSet));
- }
-
- protected ViewerFilter createTableFilter() {
- final ViewerFilter superFilter= super.createTableFilter();
- return new ViewerFilter() {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (!superFilter.select(viewer, parentElement, element))
- return false;
-
- IWorkingSet set= (IWorkingSet)element;
- if (!isValidWorkingSet(set))
- return false;
-
- if (fWorkingSetModel == null)
- return true;
-
- if (fShowVisibleOnly) {
- if (!fWorkingSetModel.isActiveWorkingSet(set))
- return false;
-
- return true;
- } else {
- return true;
- }
- }
- };
- }
-
- protected ViewerSorter createTableSorter() {
- final ViewerSorter superSorter= super.createTableSorter();
- return new ViewerSorter() {
- public int compare(Viewer viewer, Object e1, Object e2) {
- if (fWorkingSetModel == null)
- return superSorter.compare(viewer, e1, e2);
-
- IWorkingSet[] activeWorkingSets= fWorkingSetModel.getActiveWorkingSets();
- for (int i= 0; i < activeWorkingSets.length; i++) {
- IWorkingSet active= activeWorkingSets[i];
- if (active == e1) {
- return -1;
- } else if (active == e2) {
- return 1;
- }
- }
-
- return superSorter.compare(viewer, e1, e2);
- }
- };
- }
-
- protected LabelProvider createTableLabelProvider() {
- final LabelProvider superLabelProvider= super.createTableLabelProvider();
- return new LabelProvider() {
- public String getText(Object element) {
- String superText= superLabelProvider.getText(element);
- if (superText == null)
- return null;
-
- GrayedCheckedModelElement modelElement= fModel.getModelElement((IWorkingSet)element);
- if (!modelElement.isGrayed())
- return superText;
-
- return superText + Messages.format(WorkingSetMessages.ConfigureWorkingSetAssignementAction_XofY_label, new Object[] {new Integer(modelElement.getCheckCount()), new Integer(fElements.length)});
- }
- };
- }
-
- private void createShowVisibleOnly(Composite parent) {
- if (fWorkingSetModel == null)
- return;
-
- Composite bar= new Composite(parent, SWT.NONE);
- bar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- GridLayout gridLayout= new GridLayout(2, false);
- gridLayout.marginHeight= 0;
- gridLayout.marginWidth= 0;
- bar.setLayout(gridLayout);
-
- final Button showVisibleOnly= new Button(bar, SWT.CHECK);
- showVisibleOnly.setSelection(fShowVisibleOnly);
- showVisibleOnly.setLayoutData(new GridData(SWT.LEAD, SWT.FILL, false, true));
- showVisibleOnly.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fShowVisibleOnly= showVisibleOnly.getSelection();
-
- fTableViewer.refresh();
-
- fTableViewer.setCheckedElements(fModel.getChecked());
- fTableViewer.setGrayedElements(fModel.getGrayed());
- }
- });
-
- Link ppwsLink= new Link(bar, SWT.NONE);
- ppwsLink.setText(WorkingSetMessages.ConfigureWorkingSetAssignementAction_OnlyShowVisible_link);
- ppwsLink.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- ppwsLink.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
-
- List workingSets= new ArrayList(Arrays.asList(fWorkingSetModel.getAllWorkingSets()));
- IWorkingSet[] activeWorkingSets= fWorkingSetModel.getActiveWorkingSets();
- WorkingSetConfigurationDialog dialog= new WorkingSetConfigurationDialog(
- getShell(),
- (IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]),
- activeWorkingSets);
- dialog.setSelection(activeWorkingSets);
- if (dialog.open() == IDialogConstants.OK_ID) {
- IWorkingSet[] selection= dialog.getSelection();
- fWorkingSetModel.setActiveWorkingSets(selection);
- }
-
- recalculateCheckedState();
- }
- });
- }
-
- private void recalculateCheckedState() {
- fModel= createGrayedCheckedModel(fElements, getAllWorkingSets());
-
- fTableViewer.setInput(fModel.getAll());
- fTableViewer.refresh();
- fTableViewer.setCheckedElements(fModel.getChecked());
- fTableViewer.setGrayedElements(fModel.getGrayed());
- }
- }
-
- private static final String[] VALID_WORKING_SET_IDS= new String[] {
- JavaWorkingSetUpdater.ID,
- "org.eclipse.ui.resourceWorkingSetPage" //$NON-NLS-1$
- };
-
- private WorkingSetModel fWorkingSetModel;
- private final IWorkbenchSite fSite;
-
- public ConfigureWorkingSetAssignementAction(IWorkbenchSite site) {
- super(site);
- fSite= site;
- setText(WorkingSetMessages.ConfigureWorkingSetAssignementAction_WorkingSets_actionLabel);
- setEnabled(false);
- }
-
- public void setWorkingSetModel(WorkingSetModel workingSetModel) {
- fWorkingSetModel= workingSetModel;
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(canEnable(selection));
- }
-
- private boolean canEnable(IStructuredSelection selection) {
- if (selection.isEmpty())
- return false;
-
- List list= selection.toList();
- for (Iterator iterator= list.iterator(); iterator.hasNext();) {
- Object object= iterator.next();
- if (!(object instanceof IResource) && !(object instanceof IJavaScriptElement))
- return false;
- }
-
- return true;
- }
-
- private IAdaptable[] getSelectedElements(IStructuredSelection selection) {
- ArrayList result= new ArrayList();
-
- List list= selection.toList();
- for (Iterator iterator= list.iterator(); iterator.hasNext();) {
- Object object= iterator.next();
- if (object instanceof IResource || object instanceof IJavaScriptElement) {
- result.add(object);
- }
- }
-
- return (IAdaptable[])result.toArray(new IAdaptable[result.size()]);
- }
-
- public void run(IStructuredSelection selection) {
- IAdaptable[] elements= getSelectedElements(selection);
- GrayedCheckedModel model= createGrayedCheckedModel(elements, getAllWorkingSets());
- WorkingSetModelAwareSelectionDialog dialog= new WorkingSetModelAwareSelectionDialog(fSite.getShell(), model, elements);
-
- if (elements.length == 1) {
- IAdaptable element= elements[0];
- String elementName;
- if (element instanceof IResource) {
- elementName= ((IResource)element).getName();
- } else {
- elementName= JavaScriptElementLabels.getElementLabel((IJavaScriptElement)element, JavaScriptElementLabels.ALL_DEFAULT);
- }
- dialog.setMessage(Messages.format(WorkingSetMessages.ConfigureWorkingSetAssignementAction_DialogMessage_specific, elementName));
- } else {
- dialog.setMessage(Messages.format(WorkingSetMessages.ConfigureWorkingSetAssignementAction_DialogMessage_multi, new Integer(elements.length)));
- }
- if (dialog.open() == Window.OK) {
- updateWorkingSets(dialog.getSelection(), dialog.getGrayed(), elements);
- selectAndReveal(elements);
- }
- }
-
- private static GrayedCheckedModel createGrayedCheckedModel(IAdaptable[] elements, IWorkingSet[] workingSets) {
- GrayedCheckedModelElement[] result= new GrayedCheckedModelElement[workingSets.length];
-
- for (int i= 0; i < workingSets.length; i++) {
- IWorkingSet set= workingSets[i];
-
- int checkCount= 0;
- for (int j= 0; j < elements.length; j++) {
- IAdaptable adapted= adapt(set, elements[j]);
- if (adapted != null && contains(set, adapted)) {
- checkCount++;
- }
- }
-
- result[i]= new GrayedCheckedModelElement(set, checkCount, elements.length);
- }
-
- return new GrayedCheckedModel(result);
- }
-
- private void updateWorkingSets(IWorkingSet[] newWorkingSets, IWorkingSet[] grayedWorkingSets, IAdaptable[] elements) {
- HashSet selectedSets= new HashSet(Arrays.asList(newWorkingSets));
- HashSet grayedSets= new HashSet(Arrays.asList(grayedWorkingSets));
- IWorkingSet[] workingSets= getAllWorkingSets();
-
- for (int i= 0; i < workingSets.length; i++) {
- IWorkingSet workingSet= workingSets[i];
- if (isValidWorkingSet(workingSet) && !selectedSets.contains(workingSet) && !grayedSets.contains(workingSet)) {
- for (int j= 0; j < elements.length; j++) {
- IAdaptable adapted= adapt(workingSet, elements[j]);
- if (adapted != null && contains(workingSet, adapted)) {
- remove(workingSet, adapted);
- }
- }
- }
- }
-
- for (int i= 0; i < newWorkingSets.length; i++) {
- IWorkingSet set= newWorkingSets[i];
- if (isValidWorkingSet(set) && !grayedSets.contains(set)) {
- for (int j= 0; j < elements.length; j++) {
- IAdaptable adapted= adapt(set, elements[j]);
- if (adapted != null && !contains(set, adapted)) {
- add(set, adapted);
- }
- }
- }
- }
- }
-
- private IWorkingSet[] getAllWorkingSets() {
- if (fWorkingSetModel != null) {
- return fWorkingSetModel.getAllWorkingSets();
- } else {
- return PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets();
- }
- }
-
- private static boolean isValidWorkingSet(IWorkingSet set) {
- if (set.isAggregateWorkingSet() || !set.isSelfUpdating())
- return false;
-
- if (!set.isVisible())
- return false;
-
- if (!set.isEditable())
- return false;
-
- for (int i= 0; i < VALID_WORKING_SET_IDS.length; i++) {
- if (VALID_WORKING_SET_IDS[i].equals(set.getId()))
- return true;
- }
-
- return false;
- }
-
- private static IAdaptable adapt(IWorkingSet set, IAdaptable element) {
- IAdaptable[] adaptedElements= set.adaptElements(new IAdaptable[] {
- element
- });
- if (adaptedElements.length != 1)
- return null;
-
- return adaptedElements[0];
- }
-
- private static boolean contains(IWorkingSet set, IAdaptable adaptedElement) {
- IAdaptable[] elements= set.getElements();
- for (int i= 0; i < elements.length; i++) {
- if (elements[i].equals(adaptedElement))
- return true;
- }
-
- return false;
- }
-
- private static void remove(IWorkingSet workingSet, IAdaptable adaptedElement) {
- HashSet set= new HashSet(Arrays.asList(workingSet.getElements()));
- set.remove(adaptedElement);
- workingSet.setElements((IAdaptable[])set.toArray(new IAdaptable[set.size()]));
- }
-
- private static void add(IWorkingSet workingSet, IAdaptable adaptedElement) {
- IAdaptable[] elements= workingSet.getElements();
- IAdaptable[] newElements= new IAdaptable[elements.length + 1];
- System.arraycopy(elements, 0, newElements, 0, elements.length);
- newElements[elements.length]= adaptedElement;
- workingSet.setElements(newElements);
- }
-
- private void selectAndReveal(IAdaptable[] elements) {
- PackageExplorerPart explorer= getActivePackageExplorer();
- if (explorer != null)
- explorer.selectReveal(new StructuredSelection(elements));
- }
-
- private PackageExplorerPart getActivePackageExplorer() {
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page != null) {
- IWorkbenchPart activePart= page.getActivePart();
- if (activePart instanceof PackageExplorerPart) {
- return (PackageExplorerPart) activePart;
- }
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditWorkingSetAction.java
deleted file mode 100644
index 9d23c58d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditWorkingSetAction.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetEditWizard;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Displays an IWorkingSetEditWizard for editing a working set.
- *
- *
- */
-public class EditWorkingSetAction extends Action {
- private IWorkbenchPartSite fSite;
- private Shell fShell;
- private WorkingSetFilterActionGroup fActionGroup;
-
- public EditWorkingSetAction(WorkingSetFilterActionGroup actionGroup, IWorkbenchPartSite site) {
- this(actionGroup);
- fSite= site;
- }
-
- public EditWorkingSetAction(WorkingSetFilterActionGroup actionGroup, Shell shell) {
- this(actionGroup);
- fShell= shell;
- }
-
- private EditWorkingSetAction(WorkingSetFilterActionGroup actionGroup) {
- super(WorkingSetMessages.EditWorkingSetAction_text);
- Assert.isNotNull(actionGroup);
- setToolTipText(WorkingSetMessages.EditWorkingSetAction_toolTip);
- setEnabled(actionGroup.getWorkingSet() != null);
- fActionGroup= actionGroup;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EDIT_WORKING_SET_ACTION);
- }
-
- /*
- * Overrides method from Action
- */
- public void run() {
- Shell shell= getShell();
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- IWorkingSet workingSet= fActionGroup.getWorkingSet();
- if (workingSet == null || workingSet.isAggregateWorkingSet()) {
- setEnabled(false);
- return;
- }
- IWorkingSetEditWizard wizard= manager.createWorkingSetEditWizard(workingSet);
- if (wizard == null) {
- String title= WorkingSetMessages.EditWorkingSetAction_error_nowizard_title;
- String message= WorkingSetMessages.EditWorkingSetAction_error_nowizard_message;
- MessageDialog.openError(shell, title, message);
- return;
- }
- WizardDialog dialog= new WizardDialog(shell, wizard);
- dialog.create();
- if (dialog.open() == Window.OK)
- fActionGroup.setWorkingSet(wizard.getSelection(), true);
- }
-
- private Shell getShell() {
- if (fSite != null) {
- return fSite.getShell();
- } else if (fShell != null) {
- return fShell;
- } else {
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditorTracker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditorTracker.java
deleted file mode 100644
index 47d69efb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/EditorTracker.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IPageListener;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IWindowListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-
-
-public abstract class EditorTracker implements IWindowListener, IPageListener, IPartListener {
-
- //--- Window listener
-
- public void windowActivated(IWorkbenchWindow window) {
- }
- public void windowDeactivated(IWorkbenchWindow window) {
- }
- public void windowClosed(IWorkbenchWindow window) {
- window.removePageListener(this);
- }
- public void windowOpened(IWorkbenchWindow window) {
- window.addPageListener(this);
- }
-
- //---- IPageListener
-
- public void pageActivated(IWorkbenchPage page) {
- }
- public void pageClosed(IWorkbenchPage page) {
- page.removePartListener(this);
- }
- public void pageOpened(IWorkbenchPage page) {
- page.addPartListener(this);
- }
-
- //---- Part Listener
-
- public void partActivated(IWorkbenchPart part) {
- }
- public void partBroughtToTop(IWorkbenchPart part) {
- }
- public void partClosed(IWorkbenchPart part) {
- if (part instanceof IEditorPart) {
- editorClosed((IEditorPart)part);
- }
- }
- public void partDeactivated(IWorkbenchPart part) {
- }
- public void partOpened(IWorkbenchPart part) {
- if (part instanceof IEditorPart) {
- editorOpened((IEditorPart)part);
- }
- }
-
- public abstract void editorOpened(IEditorPart part);
-
- public abstract void editorClosed(IEditorPart part);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/IWorkingSetActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/IWorkingSetActionGroup.java
deleted file mode 100644
index 9224c1f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/IWorkingSetActionGroup.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.jface.action.IMenuManager;
-
-public interface IWorkingSetActionGroup {
-
- public static final String ACTION_GROUP= "working_set_action_group"; //$NON-NLS-1$
-
- public void fillViewMenu(IMenuManager mm);
-
- public void cleanViewMenu(IMenuManager menuManager);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetElementAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetElementAdapter.java
deleted file mode 100644
index a0813132..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetElementAdapter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetElementAdapter;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-public class JavaWorkingSetElementAdapter implements IWorkingSetElementAdapter {
-
- public IAdaptable[] adaptElements(IWorkingSet ws, IAdaptable[] elements) {
- ArrayList result= new ArrayList(elements.length);
-
- for (int i= 0; i < elements.length; i++) {
- IAdaptable curr= elements[i];
- if (curr instanceof IJavaScriptElement) {
- result.add(curr);
- } else if (curr instanceof IResource) {
- result.add(adaptFromResource((IResource) curr));
- } else {
- Object elem= curr.getAdapter(IJavaScriptElement.class);
- if (elem == null) {
- elem= curr.getAdapter(IResource.class);
- if (elem != null) {
- elem= adaptFromResource((IResource) elem);
- }
- }
- if (elem != null) {
- result.add(elem);
- } // ignore all others
- }
- }
- return (IAdaptable[]) result.toArray(new IAdaptable[result.size()]);
- }
-
- private Object adaptFromResource(IResource resource) {
- IProject project= resource.getProject();
- if (project != null && project.isAccessible()) {
- try {
- if (project.hasNature(JavaScriptCore.NATURE_ID)) {
- IJavaScriptElement elem= JavaScriptCore.create(resource);
- if (elem != null) {
- return elem;
- }
- }
- } catch (CoreException e) {
- // ignore
- }
- }
- return resource;
- }
-
-
- public void dispose() {
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPage.java
deleted file mode 100644
index 50bfd092..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPage.java
+++ /dev/null
@@ -1,480 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Rodrigo Kumpera <kumpera AT gmail.com> - bug 95232
- *
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ITreeViewerListener;
-import org.eclipse.jface.viewers.TreeExpansionEvent;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetPage;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.filters.EmptyInnerPackageFilter;
-import org.eclipse.wst.jsdt.internal.ui.util.JavaUIHelp;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-/**
- * The Java working set page allows the user to create
- * and edit a Java working set.
- * <p>
- * Working set elements are presented as a Java element tree.
- * </p>
- *
- *
- */
-public class JavaWorkingSetPage extends WizardPage implements IWorkingSetPage {
-
- final private static String PAGE_TITLE= WorkingSetMessages.JavaWorkingSetPage_title;
- final private static String PAGE_ID= "javaWorkingSetPage"; //$NON-NLS-1$
-
- private Text fWorkingSetName;
- private CheckboxTreeViewer fTree;
- private ITreeContentProvider fTreeContentProvider;
-
- private boolean fFirstCheck;
- private IWorkingSet fWorkingSet;
-
- /**
- * Default constructor.
- */
- public JavaWorkingSetPage() {
- super(PAGE_ID, PAGE_TITLE, JavaPluginImages.DESC_WIZBAN_JAVA_WORKINGSET);
- setDescription(WorkingSetMessages.JavaWorkingSetPage_workingSet_description);
- fFirstCheck= true;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout());
- composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
- setControl(composite);
-
- Label label= new Label(composite, SWT.WRAP);
- label.setText(WorkingSetMessages.JavaWorkingSetPage_workingSet_name);
- GridData gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER);
- label.setLayoutData(gd);
-
- fWorkingSetName= new Text(composite, SWT.SINGLE | SWT.BORDER);
- fWorkingSetName.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
- fWorkingSetName.addModifyListener(
- new ModifyListener() {
- public void modifyText(ModifyEvent e) {
- validateInput();
- }
- }
- );
- fWorkingSetName.setFocus();
-
- label= new Label(composite, SWT.WRAP);
- label.setText(WorkingSetMessages.JavaWorkingSetPage_workingSet_content);
- gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER);
- label.setLayoutData(gd);
-
- fTree= new CheckboxTreeViewer(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
- ColoredViewersManager.install(fTree);
- gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL);
- gd.heightHint= convertHeightInCharsToPixels(15);
- fTree.getControl().setLayoutData(gd);
-
- fTreeContentProvider= new JavaWorkingSetPageContentProvider();
- fTree.setContentProvider(fTreeContentProvider);
-
- AppearanceAwareLabelProvider fJavaElementLabelProvider=
- new AppearanceAwareLabelProvider(
- AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaScriptElementLabels.P_COMPRESSED,
- AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS
- );
-
- fTree.setLabelProvider(new DecoratingJavaLabelProvider(fJavaElementLabelProvider));
- fTree.setComparator(new JavaScriptElementComparator());
- fTree.addFilter(new EmptyInnerPackageFilter());
- fTree.setUseHashlookup(true);
-
- fTree.setInput(JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot()));
-
- fTree.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- handleCheckStateChange(event);
- }
- });
-
- fTree.addTreeListener(new ITreeViewerListener() {
- public void treeCollapsed(TreeExpansionEvent event) {
- }
- public void treeExpanded(TreeExpansionEvent event) {
- final Object element= event.getElement();
- if (fTree.getGrayed(element) == false)
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
- public void run() {
- setSubtreeChecked(element, fTree.getChecked(element), false);
- }
- });
- }
- });
-
- // Add select / deselect all buttons for bug 46669
- Composite buttonComposite = new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout(2, false);
- layout.marginWidth= 0; layout.marginHeight= 0;
- buttonComposite.setLayout(layout);
- buttonComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- Button selectAllButton = new Button(buttonComposite, SWT.PUSH);
- selectAllButton.setText(WorkingSetMessages.JavaWorkingSetPage_selectAll_label);
- selectAllButton.setToolTipText(WorkingSetMessages.JavaWorkingSetPage_selectAll_toolTip);
- selectAllButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent selectionEvent) {
- fTree.setCheckedElements(fTreeContentProvider.getElements(fTree.getInput()));
- validateInput();
- }
- });
- selectAllButton.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(selectAllButton);
-
- Button deselectAllButton = new Button(buttonComposite, SWT.PUSH);
- deselectAllButton.setText(WorkingSetMessages.JavaWorkingSetPage_deselectAll_label);
- deselectAllButton.setToolTipText(WorkingSetMessages.JavaWorkingSetPage_deselectAll_toolTip);
- deselectAllButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent selectionEvent) {
- fTree.setCheckedElements(new Object[0]);
- validateInput();
- }
- });
- deselectAllButton.setLayoutData(new GridData());
- SWTUtil.setButtonDimensionHint(deselectAllButton);
-
- if (fWorkingSet != null)
- fWorkingSetName.setText(fWorkingSet.getName());
- initializeCheckedState();
- validateInput();
-
- Dialog.applyDialogFont(composite);
- // Set help for the page
- JavaUIHelp.setHelp(fTree, IJavaHelpContextIds.JAVA_WORKING_SET_PAGE);
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public IWorkingSet getSelection() {
- return fWorkingSet;
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public void setSelection(IWorkingSet workingSet) {
- Assert.isNotNull(workingSet, "Working set must not be null"); //$NON-NLS-1$
- fWorkingSet= workingSet;
- if (getContainer() != null && getShell() != null && fWorkingSetName != null) {
- fFirstCheck= false;
- fWorkingSetName.setText(fWorkingSet.getName());
- initializeCheckedState();
- validateInput();
- }
- }
-
- /*
- * Implements method from IWorkingSetPage
- */
- public void finish() {
- String workingSetName= fWorkingSetName.getText();
- ArrayList elements= new ArrayList(10);
- findCheckedElements(elements, fTree.getInput());
- if (fWorkingSet == null) {
- IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
- fWorkingSet= workingSetManager.createWorkingSet(workingSetName, (IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- } else {
- // Add inaccessible resources
- IAdaptable[] oldItems= fWorkingSet.getElements();
- HashSet closedWithChildren= new HashSet(elements.size());
- for (int i= 0; i < oldItems.length; i++) {
- IResource oldResource= null;
- if (oldItems[i] instanceof IResource) {
- oldResource= (IResource)oldItems[i];
- } else {
- oldResource= (IResource)oldItems[i].getAdapter(IResource.class);
- }
- if (oldResource != null && oldResource.isAccessible() == false) {
- IProject project= oldResource.getProject();
- if (closedWithChildren.contains(project) || elements.contains(project)) {
- elements.add(oldItems[i]);
- elements.remove(project);
- closedWithChildren.add(project);
- }
- }
- }
- fWorkingSet.setName(workingSetName);
- fWorkingSet.setElements((IAdaptable[]) elements.toArray(new IAdaptable[elements.size()]));
- }
- }
-
- private void validateInput() {
- String errorMessage= null;
- String infoMessage= null;
- String newText= fWorkingSetName.getText();
-
- if (newText.equals(newText.trim()) == false)
- errorMessage = WorkingSetMessages.JavaWorkingSetPage_warning_nameWhitespace;
- if (newText.equals("")) { //$NON-NLS-1$
- if (fFirstCheck) {
- setPageComplete(false);
- fFirstCheck= false;
- return;
- }
- else
- errorMessage= WorkingSetMessages.JavaWorkingSetPage_warning_nameMustNotBeEmpty;
- }
-
- fFirstCheck= false;
-
- if (errorMessage == null && (fWorkingSet == null || newText.equals(fWorkingSet.getName()) == false)) {
- IWorkingSet[] workingSets= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets();
- for (int i= 0; i < workingSets.length; i++) {
- if (newText.equals(workingSets[i].getName())) {
- errorMessage= WorkingSetMessages.JavaWorkingSetPage_warning_workingSetExists;
- }
- }
- }
-
- if (!hasCheckedElement())
- infoMessage= WorkingSetMessages.JavaWorkingSetPage_warning_resourceMustBeChecked;
-
- setMessage(infoMessage, INFORMATION);
- setErrorMessage(errorMessage);
- setPageComplete(errorMessage == null);
- }
-
- private boolean hasCheckedElement() {
- TreeItem[] items= fTree.getTree().getItems();
- for (int i= 0; i < items.length; i++) {
- if (items[i].getChecked())
- return true;
- }
- return false;
- }
-
- private void findCheckedElements(List checkedResources, Object parent) {
- Object[] children= fTreeContentProvider.getChildren(parent);
- for (int i= 0; i < children.length; i++) {
- if (fTree.getGrayed(children[i]))
- findCheckedElements(checkedResources, children[i]);
- else if (fTree.getChecked(children[i]))
- checkedResources.add(children[i]);
- }
- }
-
- void handleCheckStateChange(final CheckStateChangedEvent event) {
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
- public void run() {
- IAdaptable element= (IAdaptable)event.getElement();
- boolean state= event.getChecked();
- fTree.setGrayed(element, false);
- if (isExpandable(element))
- setSubtreeChecked(element, state, state); // only check subtree if state is set to true
-
- updateParentState(element, state);
- validateInput();
- }
- });
- }
-
- private void setSubtreeChecked(Object parent, boolean state, boolean checkExpandedState) {
- if (!(parent instanceof IAdaptable))
- return;
- IContainer container= (IContainer)((IAdaptable)parent).getAdapter(IContainer.class);
- if ((!fTree.getExpandedState(parent) && checkExpandedState) || (container != null && !container.isAccessible()))
- return;
-
- Object[] children= fTreeContentProvider.getChildren(parent);
- for (int i= children.length - 1; i >= 0; i--) {
- Object element= children[i];
- if (state) {
- fTree.setChecked(element, true);
- fTree.setGrayed(element, false);
- }
- else
- fTree.setGrayChecked(element, false);
- if (isExpandable(element))
- setSubtreeChecked(element, state, true);
- }
- }
-
- private void updateParentState(Object child, boolean baseChildState) {
- if (child == null)
- return;
- if (child instanceof IAdaptable) {
- IResource resource= (IResource)((IAdaptable)child).getAdapter(IResource.class);
- if (resource != null && !resource.isAccessible())
- return;
- }
- Object parent= fTreeContentProvider.getParent(child);
- if (parent == null)
- return;
-
- updateObjectState(parent, baseChildState);
- }
-
- private void updateObjectState(Object element, boolean baseChildState) {
-
- boolean allSameState= true;
- Object[] children= fTreeContentProvider.getChildren(element);
-
- for (int i= children.length -1; i >= 0; i--) {
- if (fTree.getChecked(children[i]) != baseChildState || fTree.getGrayed(children[i])) {
- allSameState= false;
- break;
- }
- }
-
- fTree.setGrayed(element, !allSameState);
- fTree.setChecked(element, !allSameState || baseChildState);
-
- updateParentState(element, baseChildState);
- }
-
- private void initializeCheckedState() {
-
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
- public void run() {
- Object[] elements;
- if (fWorkingSet == null) {
- // Use current part's selection for initialization
- IWorkbenchPage page= JavaScriptPlugin.getActivePage();
- if (page == null)
- return;
-
- IWorkbenchPart part= JavaScriptPlugin.getActivePage().getActivePart();
- if (part == null)
- return;
-
- try {
- elements= SelectionConverter.getStructuredSelection(part).toArray();
- for (int i= 0; i < elements.length; i++) {
- if (elements[i] instanceof IResource) {
- IJavaScriptElement je= (IJavaScriptElement)((IResource)elements[i]).getAdapter(IJavaScriptElement.class);
- if (je != null && je.exists() && je.getJavaScriptProject().isOnIncludepath((IResource)elements[i]))
- elements[i]= je;
- }
- }
- } catch (JavaScriptModelException e) {
- return;
- }
- }
- else
- elements= fWorkingSet.getElements();
-
- // Use closed project for elements in closed project
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- if (element instanceof IResource) {
- IProject project= ((IResource)element).getProject();
- if (!project.isAccessible())
- elements[i]= project;
- }
- if (element instanceof IJavaScriptElement) {
- IJavaScriptProject jProject= ((IJavaScriptElement)element).getJavaScriptProject();
- if (jProject != null && !jProject.getProject().isAccessible())
- elements[i]= jProject.getProject();
- }
- }
-
- fTree.setCheckedElements(elements);
- HashSet parents = new HashSet();
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- if (isExpandable(element))
- setSubtreeChecked(element, true, true);
-
- if (element instanceof IAdaptable) {
- IResource resource= (IResource) ((IAdaptable)element).getAdapter(IResource.class);
- if (resource != null && !resource.isAccessible())
- continue;
- }
- Object parent= fTreeContentProvider.getParent(element);
- if (parent != null)
- parents.add(parent);
- }
-
- for (Iterator i = parents.iterator(); i.hasNext();)
- updateObjectState(i.next(), true);
- }
- });
- }
-
- private boolean isExpandable(Object element) {
- return (
- element instanceof IJavaScriptProject
- ||
- element instanceof IPackageFragmentRoot
- ||
- element instanceof IPackageFragment
- ||
- element instanceof IJavaScriptModel
- ||
- element instanceof IContainer);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPageContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPageContentProvider.java
deleted file mode 100644
index 37122f78..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetPageContentProvider.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-class JavaWorkingSetPageContentProvider extends StandardJavaScriptElementContentProvider {
-
- public boolean hasChildren(Object element) {
-
- if (element instanceof IProject && !((IProject)element).isAccessible())
- return false;
-
- if (element instanceof IPackageFragment) {
- IPackageFragment pkg= (IPackageFragment)element;
- try {
- if (pkg.getKind() == IPackageFragmentRoot.K_BINARY)
- return pkg.getChildren().length > 0;
- } catch (JavaScriptModelException ex) {
- // use super behavior
- }
- }
- return super.hasChildren(element);
- }
-
- public Object[] getChildren(Object parentElement) {
- try {
- if (parentElement instanceof IJavaScriptModel)
- return concatenate(super.getChildren(parentElement), getNonJavaProjects((IJavaScriptModel)parentElement));
-
- if (parentElement instanceof IProject)
- return ((IProject)parentElement).members();
-
- return super.getChildren(parentElement);
- } catch (CoreException e) {
- return NO_CHILDREN;
- }
- }
-
- private Object[] getNonJavaProjects(IJavaScriptModel model) throws JavaScriptModelException {
- return model.getNonJavaScriptResources();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetUpdater.java
deleted file mode 100644
index 677ccfce..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/JavaWorkingSetUpdater.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetUpdater;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-
-
-public class JavaWorkingSetUpdater implements IWorkingSetUpdater, IElementChangedListener {
-
- public static final String ID= "org.eclipse.wst.jsdt.ui.JavaWorkingSetPage"; //$NON-NLS-1$
-
- private List fWorkingSets;
-
- private static class WorkingSetDelta {
- private IWorkingSet fWorkingSet;
- private List fElements;
- private boolean fChanged;
- public WorkingSetDelta(IWorkingSet workingSet) {
- fWorkingSet= workingSet;
- fElements= new ArrayList(Arrays.asList(workingSet.getElements()));
- }
- public int indexOf(Object element) {
- return fElements.indexOf(element);
- }
- public void set(int index, Object element) {
- fElements.set(index, element);
- fChanged= true;
- }
- public void remove(int index) {
- if (fElements.remove(index) != null) {
- fChanged= true;
- }
- }
- public void process() {
- if (fChanged) {
- fWorkingSet.setElements((IAdaptable[])fElements.toArray(new IAdaptable[fElements.size()]));
- }
- }
- }
-
- public JavaWorkingSetUpdater() {
- fWorkingSets= new ArrayList();
- JavaScriptCore.addElementChangedListener(this);
- }
-
- /**
- * {@inheritDoc}
- */
- public void add(IWorkingSet workingSet) {
- checkElementExistence(workingSet);
- synchronized (fWorkingSets) {
- fWorkingSets.add(workingSet);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean remove(IWorkingSet workingSet) {
- boolean result;
- synchronized(fWorkingSets) {
- result= fWorkingSets.remove(workingSet);
- }
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(IWorkingSet workingSet) {
- synchronized(fWorkingSets) {
- return fWorkingSets.contains(workingSet);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- synchronized(fWorkingSets) {
- fWorkingSets.clear();
- }
- JavaScriptCore.removeElementChangedListener(this);
- }
-
- /**
- * {@inheritDoc}
- */
- public void elementChanged(ElementChangedEvent event) {
- IWorkingSet[] workingSets;
- synchronized(fWorkingSets) {
- workingSets= (IWorkingSet[])fWorkingSets.toArray(new IWorkingSet[fWorkingSets.size()]);
- }
- for (int w= 0; w < workingSets.length; w++) {
- WorkingSetDelta workingSetDelta= new WorkingSetDelta(workingSets[w]);
- processJavaDelta(workingSetDelta, event.getDelta());
- IResourceDelta[] resourceDeltas= event.getDelta().getResourceDeltas();
- if (resourceDeltas != null) {
- for (int r= 0; r < resourceDeltas.length; r++) {
- processResourceDelta(workingSetDelta, resourceDeltas[r]);
- }
- }
- workingSetDelta.process();
- }
- }
-
- private void processJavaDelta(WorkingSetDelta result, IJavaScriptElementDelta delta) {
- IJavaScriptElement jElement= delta.getElement();
- int index= result.indexOf(jElement);
- int type= jElement.getElementType();
- int kind= delta.getKind();
- int flags= delta.getFlags();
- if (type == IJavaScriptElement.JAVASCRIPT_PROJECT && kind == IJavaScriptElementDelta.CHANGED) {
- if (index != -1 && (flags & IJavaScriptElementDelta.F_CLOSED) != 0) {
- result.set(index, ((IJavaScriptProject)jElement).getProject());
- } else if ((flags & IJavaScriptElementDelta.F_OPENED) != 0) {
- index= result.indexOf(((IJavaScriptProject)jElement).getProject());
- if (index != -1)
- result.set(index, jElement);
- }
- }
- if (index != -1) {
- if (kind == IJavaScriptElementDelta.REMOVED) {
- if ((flags & IJavaScriptElementDelta.F_MOVED_TO) != 0) {
- result.set(index, delta.getMovedToElement());
- } else {
- result.remove(index);
- }
- }
- }
- IResourceDelta[] resourceDeltas= delta.getResourceDeltas();
- if (resourceDeltas != null) {
- for (int i= 0; i < resourceDeltas.length; i++) {
- processResourceDelta(result, resourceDeltas[i]);
- }
- }
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- processJavaDelta(result, children[i]);
- }
- }
-
- private void processResourceDelta(WorkingSetDelta result, IResourceDelta delta) {
- IResource resource= delta.getResource();
- int type= resource.getType();
- int index= result.indexOf(resource);
- int kind= delta.getKind();
- int flags= delta.getFlags();
- if (kind == IResourceDelta.CHANGED && type == IResource.PROJECT && index != -1) {
- if ((flags & IResourceDelta.OPEN) != 0) {
- result.set(index, resource);
- }
- }
- if (index != -1 && kind == IResourceDelta.REMOVED) {
- if ((flags & IResourceDelta.MOVED_TO) != 0) {
- result.set(index,
- ResourcesPlugin.getWorkspace().getRoot().findMember(delta.getMovedToPath()));
- } else {
- result.remove(index);
- }
- }
-
- // Don't dive into closed or opened projects
- if (projectGotClosedOrOpened(resource, kind, flags))
- return;
-
- IResourceDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- processResourceDelta(result, children[i]);
- }
- }
-
- private boolean projectGotClosedOrOpened(IResource resource, int kind, int flags) {
- return resource.getType() == IResource.PROJECT
- && kind == IResourceDelta.CHANGED
- && (flags & IResourceDelta.OPEN) != 0;
- }
-
- private void checkElementExistence(IWorkingSet workingSet) {
- List elements= new ArrayList(Arrays.asList(workingSet.getElements()));
- boolean changed= false;
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- IAdaptable element= (IAdaptable)iter.next();
- boolean remove= false;
- if (element instanceof IJavaScriptElement) {
- IJavaScriptElement jElement= (IJavaScriptElement)element;
- // If we have directly a project then remove it when it
- // doesn't exist anymore. However if we have a sub element
- // under a project only remove the element if the parent
- // project is open. Otherwise we would remove all elements
- // in closed projects.
- if (jElement instanceof IJavaScriptProject) {
- remove= !jElement.exists();
- } else {
- IProject project= jElement.getJavaScriptProject().getProject();
- remove= project.isOpen() && !jElement.exists();
- }
- } else if (element instanceof IResource) {
- IResource resource= (IResource)element;
- // See comments above
- if (resource instanceof IProject) {
- remove= !resource.exists();
- } else {
- IProject project= resource.getProject();
- remove= (project != null ? project.isOpen() : true) && !resource.exists();
- }
- }
- if (remove) {
- iter.remove();
- changed= true;
- }
- }
- if (changed) {
- workingSet.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/Mementos.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/Mementos.java
deleted file mode 100644
index 45785dfe..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/Mementos.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.ui.IElementFactory;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.ui.PlatformUI;
-
-public class Mementos {
-
- public static final String TAG_FACTORY_ID = "factoryID"; //$NON-NLS-1$
- public static final String TAG_ITEM = "item"; //$NON-NLS-1$
-
- public static void saveItem(IMemento memento, IAdaptable element) {
- IPersistableElement persistable= (IPersistableElement)element.getAdapter(IPersistableElement.class);
- if (persistable != null) {
- memento.putString(
- TAG_FACTORY_ID,
- persistable.getFactoryId());
- persistable.saveState(memento);
- }
-
- }
-
- public static IAdaptable restoreItem(IMemento memento) {
- return restoreItem(memento, TAG_FACTORY_ID);
- }
-
- public static IAdaptable restoreItem(IMemento memento, String factoryTag) {
- if (memento == null)
- return null;
- String factoryID = memento.getString(factoryTag);
- if (factoryID == null) return null;
- IElementFactory factory = PlatformUI.getWorkbench().getElementFactory(factoryID);
- if (factory == null) return null;
- return factory.createElement(memento);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OpenPropertiesWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OpenPropertiesWorkingSetAction.java
deleted file mode 100644
index c4d7bc4f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OpenPropertiesWorkingSetAction.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetEditWizard;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-
-public class OpenPropertiesWorkingSetAction extends SelectionDispatchAction {
-
- public OpenPropertiesWorkingSetAction(IWorkbenchSite site) {
- super(site);
- setText(WorkingSetMessages.OpenPropertiesWorkingSetAction_label);
- setEnabled(false);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getWorkingSet(selection) != null);
- }
-
- private IWorkingSet getWorkingSet(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object element= selection.getFirstElement();
- if (!(element instanceof IWorkingSet))
- return null;
- IWorkingSet ws= (IWorkingSet)element;
- if (!ws.isEditable())
- return null;
- return ws;
- }
-
- public void run(IStructuredSelection selection) {
- IWorkingSet ws= getWorkingSet(selection);
- if (ws == null)
- return;
- IWorkingSetEditWizard wizard= PlatformUI.getWorkbench().
- getWorkingSetManager().createWorkingSetEditWizard(ws);
- WizardDialog dialog= new WizardDialog(getShell(), wizard);
- dialog.open();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OthersWorkingSetUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OthersWorkingSetUpdater.java
deleted file mode 100644
index b84b3ee6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/OthersWorkingSetUpdater.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.IWorkingSetUpdater;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-public class OthersWorkingSetUpdater implements IWorkingSetUpdater {
-
- public static final String ID= "org.eclipse.wst.jsdt.internal.ui.OthersWorkingSet"; //$NON-NLS-1$
-
- private IWorkingSet fWorkingSet;
- private WorkingSetModel fWorkingSetModel;
-
- private class ResourceChangeListener implements IResourceChangeListener {
- public void resourceChanged(IResourceChangeEvent event) {
- if (fWorkingSet == null)
- return; // not yet initialized
- IResourceDelta delta= event.getDelta();
- IResourceDelta[] affectedChildren= delta.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED, IResource.PROJECT);
- if (affectedChildren.length > 0) {
- updateElements();
- } else {
- affectedChildren= delta.getAffectedChildren(IResourceDelta.CHANGED, IResource.PROJECT);
- for (int i= 0; i < affectedChildren.length; i++) {
- IResourceDelta projectDelta= affectedChildren[i];
- if ((projectDelta.getFlags() & IResourceDelta.DESCRIPTION) != 0) {
- updateElements();
- // one is enough
- return;
- }
- }
- }
- }
- }
- private IResourceChangeListener fResourceChangeListener;
-
- private class WorkingSetListener implements IPropertyChangeListener {
- public void propertyChange(PropertyChangeEvent event) {
- if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(event.getProperty())) {
- IWorkingSet changedWorkingSet= (IWorkingSet) event.getNewValue();
- if (changedWorkingSet != fWorkingSet && fWorkingSetModel.isActiveWorkingSet(changedWorkingSet)) {
- updateElements();
- }
- }
- }
- }
- private IPropertyChangeListener fWorkingSetListener;
-
- private class JavaElementChangeListener implements IElementChangedListener {
- public void elementChanged(ElementChangedEvent event) {
- if (fWorkingSet == null)
- return; // not yet initialized
-
- processJavaDelta(new ArrayList(Arrays.asList(fWorkingSet.getElements())), event.getDelta());
- }
- private void processJavaDelta(List elements, IJavaScriptElementDelta delta) {
- IJavaScriptElement jElement= delta.getElement();
- int type= jElement.getElementType();
- if (type == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- int index= elements.indexOf(jElement);
- int kind= delta.getKind();
- int flags= delta.getFlags();
- if (kind == IJavaScriptElementDelta.CHANGED) {
- if (index != -1 && (flags & IJavaScriptElementDelta.F_CLOSED) != 0) {
- elements.set(index, ((IJavaScriptProject)jElement).getProject());
- fWorkingSet.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- } else if ((flags & IJavaScriptElementDelta.F_OPENED) != 0) {
- index= elements.indexOf(((IJavaScriptProject)jElement).getProject());
- if (index != -1) {
- elements.set(index, jElement);
- fWorkingSet.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- }
- }
- }
- // don't visit below projects
- return;
- }
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
- for (int i= 0; i < children.length; i++) {
- processJavaDelta(elements, children[i]);
- }
- }
- }
- private IElementChangedListener fJavaElementChangeListener;
-
- /**
- * {@inheritDoc}
- */
- public void add(IWorkingSet workingSet) {
- Assert.isTrue(fWorkingSet == null && fWorkingSetModel != null);
- fWorkingSet= workingSet;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean remove(IWorkingSet workingSet) {
- Assert.isTrue(fWorkingSet == workingSet);
- fWorkingSet= null;
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(IWorkingSet workingSet) {
- return fWorkingSet == workingSet;
- }
-
- public void init(WorkingSetModel model) {
- fWorkingSetModel= model;
- fResourceChangeListener= new ResourceChangeListener();
- ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceChangeListener, IResourceChangeEvent.POST_CHANGE);
- fWorkingSetListener= new WorkingSetListener();
- PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(fWorkingSetListener);
- fJavaElementChangeListener= new JavaElementChangeListener();
- JavaScriptCore.addElementChangedListener(fJavaElementChangeListener, ElementChangedEvent.POST_CHANGE);
- }
-
- public void dispose() {
- if (fResourceChangeListener != null) {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(fResourceChangeListener);
- fResourceChangeListener= null;
- }
- if (fWorkingSetListener != null) {
- PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(fWorkingSetListener);
- fWorkingSetListener= null;
- }
- if (fJavaElementChangeListener != null) {
- JavaScriptCore.removeElementChangedListener(fJavaElementChangeListener);
- }
- }
-
- public void updateElements() {
- Assert.isTrue(fWorkingSet != null && fWorkingSetModel != null); // init and addWorkingSet have happend
-
- IWorkingSet[] activeWorkingSets= fWorkingSetModel.getActiveWorkingSets();
-
- List result= new ArrayList();
- Set projects= new HashSet();
- for (int i= 0; i < activeWorkingSets.length; i++) {
- if (activeWorkingSets[i] == fWorkingSet) continue;
- IAdaptable[] elements= activeWorkingSets[i].getElements();
- for (int j= 0; j < elements.length; j++) {
- IAdaptable element= elements[j];
- IResource resource= (IResource)element.getAdapter(IResource.class);
- if (resource != null && resource.getType() == IResource.PROJECT) {
- projects.add(resource);
- }
- }
- }
- IJavaScriptModel model= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- try {
- IJavaScriptProject[] jProjects= model.getJavaScriptProjects();
- for (int i= 0; i < jProjects.length; i++) {
- if (!projects.contains(jProjects[i].getProject()))
- result.add(jProjects[i]);
- }
- Object[] rProjects= model.getNonJavaScriptResources();
- for (int i= 0; i < rProjects.length; i++) {
- if (!projects.contains(rProjects[i]))
- result.add(rProjects[i]);
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- fWorkingSet.setElements((IAdaptable[])result.toArray(new IAdaptable[result.size()]));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/RemoveWorkingSetElementAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/RemoveWorkingSetElementAction.java
deleted file mode 100644
index cd5d84ed..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/RemoveWorkingSetElementAction.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction;
-
-public class RemoveWorkingSetElementAction extends SelectionDispatchAction {
-
- public RemoveWorkingSetElementAction(IWorkbenchSite site) {
- super(site);
- setText(WorkingSetMessages.RemoveWorkingSetElementAction_label);
- }
-
- public void selectionChanged(IStructuredSelection selection) {
- IWorkingSet workingSet= getWorkingSet(selection);
- setEnabled(workingSet != null && !OthersWorkingSetUpdater.ID.equals(workingSet.getId()));
- }
-
- private IWorkingSet getWorkingSet(IStructuredSelection selection) {
- if (!(selection instanceof ITreeSelection))
- return null;
- ITreeSelection treeSelection= (ITreeSelection)selection;
- List elements= treeSelection.toList();
- IWorkingSet result= null;
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object element= iter.next();
- TreePath[] paths= treeSelection.getPathsFor(element);
- if (paths.length != 1)
- return null;
- TreePath path= paths[0];
- if (path.getSegmentCount() != 2)
- return null;
- Object candidate= path.getSegment(0);
- if (!(candidate instanceof IWorkingSet))
- return null;
- if (result == null) {
- result= (IWorkingSet)candidate;
- } else {
- if (result != candidate)
- return null;
- }
- }
- return result;
- }
-
- public void run(IStructuredSelection selection) {
- IWorkingSet ws= getWorkingSet(selection);
- if (ws == null)
- return;
- HashSet elements= new HashSet(Arrays.asList(ws.getElements()));
- List selectedElements= selection.toList();
- for (Iterator iter= selectedElements.iterator(); iter.hasNext();) {
- Object object= iter.next();
- if (object instanceof IAdaptable) {
- IAdaptable[] adaptedElements= ws.adaptElements(new IAdaptable[] {(IAdaptable)object});
- if (adaptedElements.length == 1) {
- elements.remove(adaptedElements[0]);
- }
- }
- }
- ws.setElements((IAdaptable[])elements.toArray(new IAdaptable[elements.size()]));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SelectWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SelectWorkingSetAction.java
deleted file mode 100644
index 7455c491..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SelectWorkingSetAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-
-/**
- * Displays an IWorkingSetSelectionDialog and sets the selected
- * working set in the action group's view.
- *
- *
- */
-public class SelectWorkingSetAction extends Action {
- private IWorkbenchPartSite fSite;
- private Shell fShell;
- private WorkingSetFilterActionGroup fActionGroup;
-
- public SelectWorkingSetAction(WorkingSetFilterActionGroup actionGroup, IWorkbenchPartSite site) {
- this(actionGroup);
- fSite= site;
- }
-
- public SelectWorkingSetAction(WorkingSetFilterActionGroup actionGroup, Shell shell) {
- this(actionGroup);
- fShell= shell;
- }
-
- private SelectWorkingSetAction(WorkingSetFilterActionGroup actionGroup) {
- super(WorkingSetMessages.SelectWorkingSetAction_text);
- Assert.isNotNull(actionGroup);
- setToolTipText(WorkingSetMessages.SelectWorkingSetAction_toolTip);
- fActionGroup= actionGroup;
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SELECT_WORKING_SET_ACTION);
- }
-
- /*
- * Overrides method from Action
- */
- public void run() {
- Shell shell= getShell();
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- IWorkingSetSelectionDialog dialog= manager.createWorkingSetSelectionDialog(shell, false);
- IWorkingSet workingSet= fActionGroup.getWorkingSet();
- if (workingSet != null)
- dialog.setSelection(new IWorkingSet[]{workingSet});
-
- if (dialog.open() == Window.OK) {
- IWorkingSet[] result= dialog.getSelection();
- if (result != null && result.length > 0) {
- fActionGroup.setWorkingSet(result[0], true);
- manager.addRecentWorkingSet(result[0]);
- }
- else
- fActionGroup.setWorkingSet(null, true);
- }
- }
-
- private Shell getShell() {
- if (fSite != null) {
- return fSite.getShell();
- } else if (fShell != null) {
- return fShell;
- } else {
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SimpleWorkingSetSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SimpleWorkingSetSelectionDialog.java
deleted file mode 100644
index cc0f7ee3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/SimpleWorkingSetSelectionDialog.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetNewWizard;
-import org.eclipse.ui.dialogs.SelectionDialog;
-
-import com.ibm.icu.text.Collator;
-
-public class SimpleWorkingSetSelectionDialog extends SelectionDialog {
-
- private static class WorkingSetLabelProvider extends LabelProvider {
-
- private Map fIcons;
-
- public WorkingSetLabelProvider() {
- fIcons= new Hashtable();
- }
-
- public void dispose() {
- Iterator iterator= fIcons.values().iterator();
- while (iterator.hasNext()) {
- Image icon= (Image)iterator.next();
- icon.dispose();
- }
- super.dispose();
- }
-
- public Image getImage(Object object) {
- Assert.isTrue(object instanceof IWorkingSet);
- IWorkingSet workingSet= (IWorkingSet)object;
- ImageDescriptor imageDescriptor= workingSet.getImageDescriptor();
- if (imageDescriptor == null)
- return null;
-
- Image icon= (Image)fIcons.get(imageDescriptor);
- if (icon == null) {
- icon= imageDescriptor.createImage();
- fIcons.put(imageDescriptor, icon);
- }
-
- return icon;
- }
-
- public String getText(Object object) {
- Assert.isTrue(object instanceof IWorkingSet);
- IWorkingSet workingSet= (IWorkingSet)object;
- return workingSet.getName();
- }
-
- }
-
- private class Filter extends ViewerFilter {
-
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- return isCompatible((IWorkingSet)element);
- }
-
- private boolean isCompatible(IWorkingSet set) {
- if (set.isAggregateWorkingSet() || !set.isSelfUpdating())
- return false;
-
- if (!set.isVisible())
- return false;
-
- if (!set.isEditable())
- return false;
-
- return true;
- }
-
- }
-
- private final IWorkingSet[] fWorkingSets;
- private final IWorkingSet[] fInitialSelection;
- private final ArrayList fCreatedWorkingSets;
-
- private CheckboxTableViewer fTableViewer;
- private IWorkingSet[] fCheckedElements;
-
- private Button fSelectAll;
- private Button fDeselectAll;
- private Button fNewWorkingSet;
-
- public SimpleWorkingSetSelectionDialog(Shell shell, String[] workingSetIds, IWorkingSet[] initialSelection) {
- super(shell);
-
- setTitle(WorkingSetMessages.SimpleWorkingSetSelectionDialog_SimpleSelectWorkingSetDialog_title);
- setHelpAvailable(false);
- setShellStyle(getShellStyle() | SWT.RESIZE);
-
- fWorkingSets= WorkingSetConfigurationBlock.filter(PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets(), workingSetIds);
- fInitialSelection= initialSelection;
- fCheckedElements= fInitialSelection;
- fCreatedWorkingSets= new ArrayList();
- }
-
- protected final Control createDialogArea(Composite parent) {
- Composite composite= (Composite)super.createDialogArea(parent);
- composite.setFont(parent.getFont());
-
- createMessageArea(composite);
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- inner.setLayout(layout);
-
- Composite tableComposite= new Composite(inner, SWT.NONE);
- tableComposite.setFont(composite.getFont());
- tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- tableComposite.setLayout(layout);
-
- fTableViewer= createTableViewer(tableComposite);
- createRightButtonBar(inner);
-
- createBottomButtonBar(composite);
-
- return composite;
- }
-
- public IWorkingSet[] getSelection() {
- return fCheckedElements;
- }
-
- protected CheckboxTableViewer createTableViewer(Composite parent) {
- CheckboxTableViewer result= CheckboxTableViewer.newCheckList(parent, SWT.BORDER | SWT.MULTI);
- result.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- checkedStateChanged();
- }
- });
- GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= convertHeightInCharsToPixels(20);
- data.widthHint= convertWidthInCharsToPixels(50);
- result.getTable().setLayoutData(data);
- result.getTable().setFont(parent.getFont());
-
- result.addFilter(createTableFilter());
- result.setLabelProvider(createTableLabelProvider());
- result.setSorter(createTableSorter());
- result.setContentProvider(new IStructuredContentProvider() {
- public Object[] getElements(Object element) {
- return (Object[])element;
- }
- public void dispose() {
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- });
-
- result.setInput(fWorkingSets);
- result.setCheckedElements(fInitialSelection);
-
- return result;
- }
-
- protected ViewerSorter createTableSorter() {
- return new ViewerSorter() {
- public int compare(Viewer viewer, Object e1, Object e2) {
- IWorkingSet w1= (IWorkingSet)e1;
- IWorkingSet w2= (IWorkingSet)e2;
- return Collator.getInstance().compare(w1.getLabel(), w2.getLabel());
- }
- };
- }
-
- protected LabelProvider createTableLabelProvider() {
- return new WorkingSetLabelProvider();
- }
-
- protected ViewerFilter createTableFilter() {
- return new Filter();
- }
-
- protected void createRightButtonBar(Composite parent) {
- Composite buttons= new Composite(parent, SWT.NONE);
- buttons.setFont(parent.getFont());
- buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- buttons.setLayout(layout);
-
- createButtonsForRightButtonBar(buttons);
- }
-
- protected void createButtonsForRightButtonBar(Composite bar) {
- fSelectAll= new Button(bar, SWT.PUSH);
- fSelectAll.setText(WorkingSetMessages.SimpleWorkingSetSelectionDialog_SelectAll_button);
- fSelectAll.setFont(bar.getFont());
- setButtonLayoutData(fSelectAll);
- fSelectAll.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- selectAll();
- }
- });
-
- fDeselectAll= new Button(bar, SWT.PUSH);
- fDeselectAll.setText(WorkingSetMessages.SimpleWorkingSetSelectionDialog_DeselectAll_button);
- fDeselectAll.setFont(bar.getFont());
- setButtonLayoutData(fDeselectAll);
- fDeselectAll.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- deselectAll();
- }
- });
-
- new Label(bar, SWT.NONE);
-
- fNewWorkingSet= new Button(bar, SWT.PUSH);
- fNewWorkingSet.setText(WorkingSetMessages.SimpleWorkingSetSelectionDialog_New_button);
- fNewWorkingSet.setFont(bar.getFont());
- setButtonLayoutData(fNewWorkingSet);
- fNewWorkingSet.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IWorkingSet workingSet= newWorkingSet();
- if (workingSet != null) {
-
- }
- }
- });
- }
-
- protected void createBottomButtonBar(Composite parent) {
- }
-
- protected void checkedStateChanged() {
- List elements= Arrays.asList(fTableViewer.getCheckedElements());
- fCheckedElements= (IWorkingSet[])elements.toArray(new IWorkingSet[elements.size()]);
- }
-
- protected void selectAll() {
- fTableViewer.setAllChecked(true);
- checkedStateChanged();
- }
-
- protected void deselectAll() {
- fTableViewer.setAllChecked(false);
- checkedStateChanged();
- }
-
- protected IWorkingSet newWorkingSet() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
-
- //can only allow to create java working sets at the moment, see bug 186762
-// IWorkingSetNewWizard wizard= manager.createWorkingSetNewWizard(fWorkingSetIds);
-// if (wizard == null)
-// return;
-
- IWorkingSetNewWizard wizard= manager.createWorkingSetNewWizard(new String[] {JavaWorkingSetUpdater.ID});
-
- WizardDialog dialog= new WizardDialog(getShell(), wizard);
- dialog.create();
- if (dialog.open() == Window.OK) {
- IWorkingSet workingSet= wizard.getSelection();
- Filter filter= new Filter();
- if (filter.select(null, null, workingSet)) {
- addNewWorkingSet(workingSet);
- checkedStateChanged();
- manager.addWorkingSet(workingSet);
- fCreatedWorkingSets.add(workingSet);
- return workingSet;
- }
- }
-
- return null;
- }
-
- protected void addNewWorkingSet(IWorkingSet workingSet) {
- fTableViewer.add(workingSet);
- fTableViewer.setSelection(new StructuredSelection(workingSet), true);
- fTableViewer.setChecked(workingSet, true);
- }
-
- /**
- * {@inheritDoc}
- */
- protected void cancelPressed() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- for (int i= 0; i < fCreatedWorkingSets.size(); i++) {
- manager.removeWorkingSet((IWorkingSet)fCreatedWorkingSets.get(i));
- }
-
- super.cancelPressed();
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewAction.java
deleted file mode 100644
index c57ae657..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewAction.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-
-public class ViewAction extends Action {
-
- private final ViewActionGroup fActionGroup;
- private final int fMode;
-
- public ViewAction(ViewActionGroup group, int mode) {
- super("", AS_RADIO_BUTTON); //$NON-NLS-1$
- Assert.isNotNull(group);
- fActionGroup= group;
- fMode= mode;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- if (isChecked())
- fActionGroup.setMode(fMode);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewActionGroup.java
deleted file mode 100644
index 46808813..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ViewActionGroup.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * An action group to provide access to the working sets.
- */
-public class ViewActionGroup extends ActionGroup {
-
- public static final int SHOW_PROJECTS= 1;
- public static final int SHOW_WORKING_SETS= 2;
- public static final String MODE_CHANGED= ViewActionGroup.class.getName() + ".mode_changed"; //$NON-NLS-1$
-
- private static final Integer INT_SHOW_PROJECTS= new Integer(SHOW_PROJECTS);
- private static final Integer INT_SHOW_WORKING_SETS= new Integer(SHOW_WORKING_SETS);
-
- private IPropertyChangeListener fChangeListener;
-
- private int fMode;
- private IMenuManager fMenuManager;
- private IWorkingSetActionGroup fActiveActionGroup;
- private final WorkingSetShowActionGroup fShowActionGroup;
- private final WorkingSetFilterActionGroup fFilterActionGroup;
- private final ConfigureWorkingSetAssignementAction fWorkingSetAssignementAction;
- private final OpenPropertiesWorkingSetAction fEditWorkingSetGroupAction; // active on working sets: edit
- private final IWorkbenchPartSite fSite;
-
- public ViewActionGroup(int mode, IPropertyChangeListener changeListener, IWorkbenchPartSite site) {
- fChangeListener= changeListener;
- fSite= site;
- if (fChangeListener == null) {
- fChangeListener = new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {}
- };
- }
- fFilterActionGroup= new WorkingSetFilterActionGroup(site, fChangeListener);
- fShowActionGroup= new WorkingSetShowActionGroup(site);
- fWorkingSetAssignementAction= new ConfigureWorkingSetAssignementAction(site);
- fEditWorkingSetGroupAction= new OpenPropertiesWorkingSetAction(site);
-
- ISelectionProvider selectionProvider= site.getSelectionProvider();
- selectionProvider.addSelectionChangedListener(fWorkingSetAssignementAction);
- selectionProvider.addSelectionChangedListener(fEditWorkingSetGroupAction);
-
- fMode= mode;
- if (showWorkingSets())
- fActiveActionGroup= fShowActionGroup;
- else
- fActiveActionGroup= fFilterActionGroup;
- }
-
- public void dispose() {
- fFilterActionGroup.dispose();
- fShowActionGroup.dispose();
- fChangeListener= null;
- ISelectionProvider selectionProvider= fSite.getSelectionProvider();
- selectionProvider.removeSelectionChangedListener(fWorkingSetAssignementAction);
- selectionProvider.removeSelectionChangedListener(fEditWorkingSetGroupAction);
- super.dispose();
- }
-
- public void setWorkingSetModel(WorkingSetModel model) {
- fShowActionGroup.setWorkingSetMode(model);
- fWorkingSetAssignementAction.setWorkingSetModel(model);
- }
-
- public void fillContextMenu(IMenuManager menu) {
- if (fWorkingSetAssignementAction.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fWorkingSetAssignementAction);
-
- if (fEditWorkingSetGroupAction.isEnabled()) {
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fEditWorkingSetGroupAction);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- fMenuManager= actionBars.getMenuManager();
- fillViewMenu(fMenuManager);
-
- if (fActiveActionGroup == null)
- fActiveActionGroup= fFilterActionGroup;
- ((ActionGroup)fActiveActionGroup).fillActionBars(actionBars);
- }
-
- private void fillViewMenu(IMenuManager menu) {
- IMenuManager showMenu= new MenuManager(WorkingSetMessages.ViewActionGroup_show_label);
- fillShowMenu(showMenu);
- menu.add(showMenu);
- menu.add(new Separator(IWorkingSetActionGroup.ACTION_GROUP));
- }
-
- private void fillShowMenu(IMenuManager menu) {
- ViewAction projects= new ViewAction(this, SHOW_PROJECTS);
- projects.setText(WorkingSetMessages.ViewActionGroup_projects_label);
- menu.add(projects);
- ViewAction workingSets= new ViewAction(this, SHOW_WORKING_SETS);
- workingSets.setText(WorkingSetMessages.ViewActionGroup_workingSets_label);
- menu.add(workingSets);
- if (fMode == SHOW_PROJECTS) {
- projects.setChecked(true);
- } else {
- workingSets.setChecked(true);
- }
- }
-
- public void fillFilters(StructuredViewer viewer) {
- ViewerFilter workingSetFilter= fFilterActionGroup.getWorkingSetFilter();
- if (showProjects()) {
- viewer.addFilter(workingSetFilter);
- } else if (showWorkingSets()) {
- viewer.removeFilter(workingSetFilter);
- }
- }
-
- public void setMode(int mode) {
- fMode= mode;
- fActiveActionGroup.cleanViewMenu(fMenuManager);
- PropertyChangeEvent event;
- if (mode == SHOW_PROJECTS) {
- fActiveActionGroup= fFilterActionGroup;
- event= new PropertyChangeEvent(this, MODE_CHANGED, INT_SHOW_WORKING_SETS, INT_SHOW_PROJECTS);
- } else {
- fActiveActionGroup= fShowActionGroup;
- event= new PropertyChangeEvent(this, MODE_CHANGED, INT_SHOW_PROJECTS, INT_SHOW_WORKING_SETS);
- }
- fActiveActionGroup.fillViewMenu(fMenuManager);
- fMenuManager.updateAll(true);
- if(fChangeListener != null)
- fChangeListener.propertyChange(event);
- }
-
- public WorkingSetFilterActionGroup getFilterGroup() {
- return fFilterActionGroup;
- }
-
- public void restoreState(IMemento memento) {
- fFilterActionGroup.restoreState(memento);
- }
-
- public void saveState(IMemento memento) {
- fFilterActionGroup.saveState(memento);
- }
-
- private boolean showProjects() {
- return fMode == SHOW_PROJECTS;
- }
-
- private boolean showWorkingSets() {
- return fMode == SHOW_WORKING_SETS;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationBlock.java
deleted file mode 100644
index 28f414f6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationBlock.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.FontMetrics;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-
-import com.ibm.icu.text.Collator;
-
-
-public class WorkingSetConfigurationBlock {
-
- //Some static methods for convenience
-
- /**
- * Retrieves a working set from the given <code>selection</code>
- * or <b>null</b> if no working set could be retrieved.
- *
- * @param selection the selection to retrieve the working set from
- * @return the selected working set or <b>null</b>
- */
- public static IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection) {
- if (!(selection instanceof ITreeSelection))
- return null;
-
- ITreeSelection treeSelection= (ITreeSelection)selection;
- if (treeSelection.isEmpty())
- return null;
-
- List elements= treeSelection.toList();
- if (elements.size() == 1) {
- Object element= elements.get(0);
- TreePath[] paths= treeSelection.getPathsFor(element);
- if (paths.length != 1)
- return null;
-
- TreePath path= paths[0];
- if (path.getSegmentCount() == 0)
- return null;
-
- Object candidate= path.getSegment(0);
- if (!(candidate instanceof IWorkingSet))
- return null;
-
- return new IWorkingSet[] {(IWorkingSet)candidate};
- } else {
- ArrayList result= new ArrayList();
- for (Iterator iterator= elements.iterator(); iterator.hasNext();) {
- Object element= iterator.next();
- if (element instanceof IWorkingSet) {
- result.add(element);
- }
- }
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
- }
-
- /**
- * Add the <code>element</code> to each given working set in
- * <code>workingSets</code> if possible.
- *
- * @param element the element to add
- * @param workingSets the working sets to add the element to
- */
- public static void addToWorkingSets(IAdaptable element, IWorkingSet[] workingSets) {
- for (int i= 0; i < workingSets.length; i++) {
- IWorkingSet workingSet= workingSets[i];
- IAdaptable[] adaptedNewElements= workingSet.adaptElements(new IAdaptable[] {element});
- if (adaptedNewElements.length == 1) {
- IAdaptable[] elements= workingSet.getElements();
- IAdaptable[] newElements= new IAdaptable[elements.length + 1];
- System.arraycopy(elements, 0, newElements, 0, elements.length);
- newElements[newElements.length - 1]= adaptedNewElements[0];
- workingSet.setElements(newElements);
- }
- }
- }
-
- /**
- * Filters the given working sets such that the following is true:
- * for each IWorkingSet s in result: s.getId() is element of workingSetIds
- *
- * @param workingSets the array to filter
- * @param workingSetIds the acceptable working set ids
- * @return the filtered elements
- */
- public static IWorkingSet[] filter(IWorkingSet[] workingSets, String[] workingSetIds) {
- ArrayList result= new ArrayList();
-
- for (int i= 0; i < workingSets.length; i++) {
- if (accept(workingSets[i], workingSetIds))
- result.add(workingSets[i]);
- }
-
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
-
- private static boolean accept(IWorkingSet set, String[] workingSetIDs) {
- for (int i= 0; i < workingSetIDs.length; i++) {
- if (workingSetIDs[i].equals(set.getId()))
- return true;
- }
-
- return false;
- }
-
- private static final String WORKINGSET_SELECTION_HISTORY= "workingset_selection_history"; //$NON-NLS-1$
- private static final int MAX_HISTORY_SIZE= 5;
-
- private Label fLabel;
- private Combo fWorkingSetCombo;
- private Button fConfigure;
- private IWorkingSet[] fSelectedWorkingSets;
- private String fMessage;
- private Button fEnableButton;
- private ArrayList fSelectionHistory;
- private final IDialogSettings fSettings;
- private final String fEnableButtonText;
- private final String[] fWorkingSetIds;
-
- /**
- * @param workingSetIds working set ids from which the user can choose
- * @param enableButtonText the text shown for the enable button
- * @param settings to store/load the selection history
- */
- public WorkingSetConfigurationBlock(String[] workingSetIds, String enableButtonText, IDialogSettings settings) {
- Assert.isNotNull(workingSetIds);
- Assert.isNotNull(enableButtonText);
- Assert.isNotNull(settings);
-
- fWorkingSetIds= workingSetIds;
- fEnableButtonText= enableButtonText;
- fSelectedWorkingSets= new IWorkingSet[0];
- fSettings= settings;
- fSelectionHistory= loadSelectionHistory(settings, workingSetIds);
- }
-
- /**
- * @param message the message to show to the user in the working set selection dialog
- */
- public void setDialogMessage(String message) {
- fMessage= message;
- }
-
- /**
- * @param selection the selection to present in the UI or <b>null</b>
- */
- public void setSelection(IWorkingSet[] selection) {
- if (selection == null)
- selection= new IWorkingSet[0];
-
- fSelectedWorkingSets= selection;
- if (fWorkingSetCombo != null)
- updateSelectedWorkingSets();
- }
-
- /**
- * @return the selected working sets
- */
- public IWorkingSet[] getSelectedWorkingSets() {
- if (fEnableButton.getSelection()) {
- return fSelectedWorkingSets;
- } else {
- return new IWorkingSet[0];
- }
- }
-
- /**
- * Add this block to the <code>parent</parent>
- *
- * @param parent the parent to add the block to
- */
- public void createContent(final Composite parent) {
- int numColumn= 3;
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- composite.setLayout(new GridLayout(numColumn, false));
-
- fEnableButton= new Button(composite, SWT.CHECK);
- fEnableButton.setText(fEnableButtonText);
- GridData enableData= new GridData(SWT.FILL, SWT.CENTER, true, false);
- enableData.horizontalSpan= numColumn;
- fEnableButton.setLayoutData(enableData);
- fEnableButton.setSelection(fSelectedWorkingSets.length > 0);
-
- fLabel= new Label(composite, SWT.NONE);
- fLabel.setText(WorkingSetMessages.WorkingSetConfigurationBlock_WorkingSetText_name);
-
- fWorkingSetCombo= new Combo(composite, SWT.READ_ONLY | SWT.BORDER);
- GridData textData= new GridData(SWT.FILL, SWT.CENTER, true, false);
- textData.horizontalSpan= numColumn - 2;
- textData.horizontalIndent= 0;
- fWorkingSetCombo.setLayoutData(textData);
-
- fConfigure= new Button(composite, SWT.PUSH);
- fConfigure.setText(WorkingSetMessages.WorkingSetConfigurationBlock_SelectWorkingSet_button);
- GridData configureData= new GridData(SWT.LEFT, SWT.CENTER, false, false);
- configureData.widthHint= getButtonWidthHint(fConfigure);
- fConfigure.setLayoutData(configureData);
- fConfigure.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- SimpleWorkingSetSelectionDialog dialog= new SimpleWorkingSetSelectionDialog(parent.getShell(), fWorkingSetIds, fSelectedWorkingSets);
- if (fMessage != null)
- dialog.setMessage(fMessage);
-
- if (dialog.open() == Window.OK) {
- IWorkingSet[] result= dialog.getSelection();
- if (result != null && result.length > 0) {
- fSelectedWorkingSets= result;
- PlatformUI.getWorkbench().getWorkingSetManager().addRecentWorkingSet(result[0]);
- } else {
- fSelectedWorkingSets= new IWorkingSet[0];
- }
- updateWorkingSetSelection();
- }
- }
- });
-
- fEnableButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- updateEnableState(fEnableButton.getSelection());
- }
- });
- updateEnableState(fEnableButton.getSelection());
-
- fWorkingSetCombo.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- updateSelectedWorkingSets();
- }
- });
-
- fWorkingSetCombo.setItems(getHistoryEntries());
- if (fSelectedWorkingSets.length == 0 && fSelectionHistory.size() > 0) {
- fWorkingSetCombo.select(historyIndex((String)fSelectionHistory.get(0)));
- updateSelectedWorkingSets();
- } else {
- updateWorkingSetSelection();
- }
- }
-
- private void updateEnableState(boolean enabled) {
- fLabel.setEnabled(enabled);
- fWorkingSetCombo.setEnabled(enabled && (fSelectedWorkingSets.length > 0 || getHistoryEntries().length > 0));
- fConfigure.setEnabled(enabled);
- }
-
- private void updateWorkingSetSelection() {
- if (fSelectedWorkingSets.length > 0) {
- fWorkingSetCombo.setEnabled(true);
- StringBuffer buf= new StringBuffer();
-
- buf.append(fSelectedWorkingSets[0].getLabel());
- for (int i= 1; i < fSelectedWorkingSets.length; i++) {
- IWorkingSet ws= fSelectedWorkingSets[i];
- buf.append(',').append(' ');
- buf.append(ws.getLabel());
- }
-
- String currentSelection= buf.toString();
- int index= historyIndex(currentSelection);
- historyInsert(currentSelection);
- if (index >= 0) {
- fWorkingSetCombo.select(index);
- } else {
- fWorkingSetCombo.setItems(getHistoryEntries());
- fWorkingSetCombo.select(historyIndex(currentSelection));
- }
- }else {
- fEnableButton.setSelection(false);
- updateEnableState(false);
- }
- }
-
- private String[] getHistoryEntries() {
- String[] history= (String[])fSelectionHistory.toArray(new String[fSelectionHistory.size()]);
- Arrays.sort(history, new Comparator() {
- public int compare(Object o1, Object o2) {
- return Collator.getInstance().compare(o1, o2);
- }
- });
- return history;
- }
-
- private void historyInsert(String entry) {
- fSelectionHistory.remove(entry);
- fSelectionHistory.add(0, entry);
- storeSelectionHistory(fSettings);
- }
-
- private int historyIndex(String entry) {
- for (int i= 0; i < fWorkingSetCombo.getItemCount(); i++) {
- if (fWorkingSetCombo.getItem(i).equals(entry))
- return i;
- }
-
- return -1;
- }
-
- private void updateSelectedWorkingSets() {
- String item= fWorkingSetCombo.getItem(fWorkingSetCombo.getSelectionIndex());
- String[] workingSetNames= item.split(", "); //$NON-NLS-1$
-
- IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
- fSelectedWorkingSets= new IWorkingSet[workingSetNames.length];
- for (int i= 0; i < workingSetNames.length; i++) {
- IWorkingSet set= workingSetManager.getWorkingSet(workingSetNames[i]);
- Assert.isNotNull(set);
- fSelectedWorkingSets[i]= set;
- }
- }
-
- private void storeSelectionHistory(IDialogSettings settings) {
- String[] history;
- if (fSelectionHistory.size() > MAX_HISTORY_SIZE) {
- List subList= fSelectionHistory.subList(0, MAX_HISTORY_SIZE);
- history= (String[])subList.toArray(new String[subList.size()]);
- } else {
- history= (String[])fSelectionHistory.toArray(new String[fSelectionHistory.size()]);
- }
- settings.put(WORKINGSET_SELECTION_HISTORY, history);
- }
-
- private ArrayList loadSelectionHistory(IDialogSettings settings, String[] workingSetIds) {
- String[] strings= settings.getArray(WORKINGSET_SELECTION_HISTORY);
- if (strings == null || strings.length == 0)
- return new ArrayList();
-
- ArrayList result= new ArrayList();
-
- HashSet workingSetIdsSet= new HashSet(Arrays.asList(workingSetIds));
-
- IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager();
- for (int i= 0; i < strings.length; i++) {
- String[] workingSetNames= strings[i].split(", "); //$NON-NLS-1$
- boolean valid= true;
- for (int j= 0; j < workingSetNames.length && valid; j++) {
- IWorkingSet workingSet= workingSetManager.getWorkingSet(workingSetNames[j]);
- if (workingSet == null) {
- valid= false;
- } else {
- if (!workingSetIdsSet.contains(workingSet.getId()))
- valid= false;
- }
- }
- if (valid) {
- result.add(strings[i]);
- }
- }
-
- return result;
- }
-
- private static int getButtonWidthHint(Button button) {
- button.setFont(JFaceResources.getDialogFont());
-
- GC gc = new GC(button);
- gc.setFont(button.getFont());
- FontMetrics fontMetrics= gc.getFontMetrics();
- gc.dispose();
-
- int widthHint= Dialog.convertHorizontalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_WIDTH);
- return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationDialog.java
deleted file mode 100644
index 5d51d355..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetConfigurationDialog.java
+++ /dev/null
@@ -1,609 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * 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.
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.IWorkingSetEditWizard;
-import org.eclipse.ui.dialogs.IWorkingSetNewWizard;
-import org.eclipse.ui.dialogs.SelectionDialog;
-
-public class WorkingSetConfigurationDialog extends SelectionDialog {
-
- private static class WorkingSetLabelProvider extends LabelProvider {
- private Map fIcons;
- public WorkingSetLabelProvider() {
- fIcons= new Hashtable();
- }
- public void dispose() {
- Iterator iterator= fIcons.values().iterator();
- while (iterator.hasNext()) {
- Image icon= (Image)iterator.next();
- icon.dispose();
- }
- super.dispose();
- }
- public Image getImage(Object object) {
- Assert.isTrue(object instanceof IWorkingSet);
- IWorkingSet workingSet= (IWorkingSet)object;
- ImageDescriptor imageDescriptor= workingSet.getImage();
- if (imageDescriptor == null)
- return null;
- Image icon= (Image)fIcons.get(imageDescriptor);
- if (icon == null) {
- icon= imageDescriptor.createImage();
- fIcons.put(imageDescriptor, icon);
- }
- return icon;
- }
- public String getText(Object object) {
- Assert.isTrue(object instanceof IWorkingSet);
- IWorkingSet workingSet= (IWorkingSet)object;
- return workingSet.getName();
- }
- }
-
- private class Filter extends ViewerFilter {
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- IWorkingSet ws= (IWorkingSet)element;
- String id= ws.getId();
- return OthersWorkingSetUpdater.ID.equals(id) ||
- JavaWorkingSetUpdater.ID.equals(id) || isCompatible(ws) || isActive(ws);
- }
- private boolean isCompatible(IWorkingSet set) {
- if (!set.isSelfUpdating() || set.isAggregateWorkingSet())
- return false;
- IAdaptable[] elements= set.getElements();
- if (elements.length == 0)
- return false;
- for (int i= 0; i < elements.length; i++) {
- IAdaptable element= elements[i];
- IProject p= (IProject)element.getAdapter(IProject.class);
- if (p == null || !p.exists())
- return false;
- }
- return true;
- }
- private boolean isActive(IWorkingSet workingSet) {
- return fActiveWorkingSets.contains(workingSet);
- }
- }
-
- private List fAllWorkingSets;
- private List fActiveWorkingSets;
- private CheckboxTableViewer fTableViewer;
-
- private Button fNewButton;
- private Button fEditButton;
- private Button fRemoveButton;
- private Button fUpButton;
- private Button fDownButton;
- private Button fSelectAll;
- private Button fDeselectAll;
-
- private IWorkingSet[] fResult;
- private List fAddedWorkingSets;
- private List fRemovedWorkingSets;
- private Map fEditedWorkingSets;
- private List fRemovedMRUWorkingSets;
-
- private int nextButtonId= IDialogConstants.CLIENT_ID + 1;
-
- public WorkingSetConfigurationDialog(Shell parentShell, IWorkingSet[] allWorkingSets, IWorkingSet[] activeWorkingSets) {
- super(parentShell);
- setTitle(WorkingSetMessages.WorkingSetConfigurationDialog_title);
- setMessage(WorkingSetMessages.WorkingSetConfigurationDialog_message);
- fAllWorkingSets= new ArrayList(allWorkingSets.length);
- fActiveWorkingSets= Arrays.asList(activeWorkingSets);
- Filter filter= new Filter();
- for (int i= 0; i < allWorkingSets.length; i++) {
- if (filter.select(null, null, allWorkingSets[i]))
- fAllWorkingSets.add(allWorkingSets[i]);
- }
- setShellStyle(getShellStyle() | SWT.RESIZE);
- }
-
- /**
- * Returns the selected working sets
- *
- * @return the selected working sets
- */
- public IWorkingSet[] getSelection() {
- return fResult;
- }
-
- /**
- * Sets the initial selection
- *
- * @param workingSets the initial selection
- */
- public void setSelection(IWorkingSet[] workingSets) {
- fResult= workingSets;
- setInitialSelections(workingSets);
- }
-
- /**
- * {@inheritDoc}
- */
- protected Control createContents(Composite parent) {
- Control control= super.createContents(parent);
- setInitialSelection();
- updateButtonAvailability();
- return control;
- }
-
- /**
- * {@inheritDoc}
- */
- protected Control createDialogArea(Composite parent) {
- Composite composite= (Composite)super.createDialogArea(parent);
- composite.setFont(parent.getFont());
-
- createMessageArea(composite);
- Composite inner= new Composite(composite, SWT.NONE);
- inner.setFont(composite.getFont());
- inner.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- inner.setLayout(layout);
- createTableViewer(inner);
- createOrderButtons(inner);
- createModifyButtons(composite);
- fTableViewer.setInput(fAllWorkingSets);
-
- return composite;
- }
-
- private void createTableViewer(Composite parent) {
- fTableViewer= CheckboxTableViewer.newCheckList(parent, SWT.BORDER | SWT.MULTI);
- fTableViewer.addCheckStateListener(new ICheckStateListener() {
- public void checkStateChanged(CheckStateChangedEvent event) {
- updateButtonAvailability();
- }
- });
- GridData data= new GridData(GridData.FILL_BOTH);
- data.heightHint= convertHeightInCharsToPixels(20);
- data.widthHint= convertWidthInCharsToPixels(50);
- fTableViewer.getTable().setLayoutData(data);
- fTableViewer.getTable().setFont(parent.getFont());
-
- fTableViewer.addFilter(new Filter());
- fTableViewer.setLabelProvider(new WorkingSetLabelProvider());
- fTableViewer.setContentProvider(new IStructuredContentProvider() {
- public Object[] getElements(Object element) {
- return ((List)element).toArray();
- }
- public void dispose() {
- }
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- });
- fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- handleSelectionChanged();
- }
- });
- }
-
- private void createModifyButtons(Composite composite) {
- Composite buttonComposite= new Composite(composite, SWT.RIGHT);
- GridLayout layout= new GridLayout();
- layout.numColumns= 2;
- buttonComposite.setLayout(layout);
- GridData data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL);
- data.grabExcessHorizontalSpace= true;
- composite.setData(data);
-
- fNewButton= createButton(buttonComposite, nextButtonId++,
- WorkingSetMessages.WorkingSetConfigurationDialog_new_label, false);
- fNewButton.setFont(composite.getFont());
- fNewButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- createWorkingSet();
- }
- });
-
- fEditButton= createButton(buttonComposite, nextButtonId++,
- WorkingSetMessages.WorkingSetConfigurationDialog_edit_label, false);
- fEditButton.setFont(composite.getFont());
- fEditButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- editSelectedWorkingSet();
- }
- });
-
- fRemoveButton= createButton(buttonComposite, nextButtonId++,
- WorkingSetMessages.WorkingSetConfigurationDialog_remove_label, false);
- fRemoveButton.setFont(composite.getFont());
- fRemoveButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- removeSelectedWorkingSets();
- }
- });
- }
-
- private void createOrderButtons(Composite parent) {
- Composite buttons= new Composite(parent, SWT.NONE);
- buttons.setFont(parent.getFont());
- buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- buttons.setLayout(layout);
-
- fUpButton= new Button(buttons, SWT.PUSH);
- fUpButton.setText(WorkingSetMessages.WorkingSetConfigurationDialog_up_label);
- fUpButton.setFont(parent.getFont());
- setButtonLayoutData(fUpButton);
- fUpButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- moveUp(((IStructuredSelection)fTableViewer.getSelection()).toList());
- }
- });
-
- fDownButton= new Button(buttons, SWT.PUSH);
- fDownButton.setText(WorkingSetMessages.WorkingSetConfigurationDialog_down_label);
- fDownButton.setFont(parent.getFont());
- setButtonLayoutData(fDownButton);
- fDownButton.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- moveDown(((IStructuredSelection)fTableViewer.getSelection()).toList());
- }
- });
-
- fSelectAll= new Button(buttons, SWT.PUSH);
- fSelectAll.setText(WorkingSetMessages.WorkingSetConfigurationDialog_selectAll_label);
- fSelectAll.setFont(parent.getFont());
- setButtonLayoutData(fSelectAll);
- fSelectAll.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- selectAll();
- }
- });
-
- fDeselectAll= new Button(buttons, SWT.PUSH);
- fDeselectAll.setText(WorkingSetMessages.WorkingSetConfigurationDialog_deselectAll_label);
- fDeselectAll.setFont(parent.getFont());
- setButtonLayoutData(fDeselectAll);
- fDeselectAll.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- deselectAll();
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- protected void okPressed() {
- List newResult= getResultWorkingSets();
- fResult= (IWorkingSet[])newResult.toArray(new IWorkingSet[newResult.size()]);
- setResult(newResult);
- super.okPressed();
- }
-
- private List getResultWorkingSets() {
- Object[] checked= fTableViewer.getCheckedElements();
- return new ArrayList(Arrays.asList(checked));
- }
-
- /**
- * {@inheritDoc}
- */
- protected void cancelPressed() {
- restoreAddedWorkingSets();
- restoreChangedWorkingSets();
- restoreRemovedWorkingSets();
- super.cancelPressed();
- }
-
- private void setInitialSelection() {
- List selections= getInitialElementSelections();
- if (!selections.isEmpty()) {
- fTableViewer.setCheckedElements(selections.toArray());
- }
- }
-
- private void createWorkingSet() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- IWorkingSetNewWizard wizard= manager.createWorkingSetNewWizard(new String[] {JavaWorkingSetUpdater.ID});
- // the wizard can't be null since we have at least the Java working set.
- WizardDialog dialog= new WizardDialog(getShell(), wizard);
- dialog.create();
- if (dialog.open() == Window.OK) {
- IWorkingSet workingSet= wizard.getSelection();
- Filter filter= new Filter();
- if (filter.select(null, null, workingSet)) {
- fAllWorkingSets.add(workingSet);
- fTableViewer.add(workingSet);
- fTableViewer.setSelection(new StructuredSelection(workingSet), true);
- fTableViewer.setChecked(workingSet, true);
- manager.addWorkingSet(workingSet);
- fAddedWorkingSets.add(workingSet);
- }
- }
- }
-
- private void editSelectedWorkingSet() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- IWorkingSet editWorkingSet= (IWorkingSet)((IStructuredSelection)fTableViewer.getSelection()).getFirstElement();
- IWorkingSetEditWizard wizard= manager.createWorkingSetEditWizard(editWorkingSet);
- WizardDialog dialog= new WizardDialog(getShell(), wizard);
- IWorkingSet originalWorkingSet= (IWorkingSet)fEditedWorkingSets.get(editWorkingSet);
- boolean firstEdit= originalWorkingSet == null;
-
- // save the original working set values for restoration when selection
- // dialog is cancelled.
- if (firstEdit) {
- originalWorkingSet=
- PlatformUI.getWorkbench().getWorkingSetManager().
- createWorkingSet(editWorkingSet.getName(), editWorkingSet.getElements());
- } else {
- fEditedWorkingSets.remove(editWorkingSet);
- }
- dialog.create();
- if (dialog.open() == Window.OK) {
- editWorkingSet= wizard.getSelection();
- fTableViewer.update(editWorkingSet, null);
- // make sure ok button is enabled when the selected working set
- // is edited. Fixes bug 33386.
- updateButtonAvailability();
- }
- fEditedWorkingSets.put(editWorkingSet, originalWorkingSet);
- }
-
- /**
- * Called when the selection has changed.
- */
- void handleSelectionChanged() {
- updateButtonAvailability();
- }
-
- /**
- * Overrides method in Dialog
- *
- * @see org.eclipse.jface.dialogs.Dialog#open()
- */
- public int open() {
- fAddedWorkingSets= new ArrayList();
- fRemovedWorkingSets= new ArrayList();
- fEditedWorkingSets= new HashMap();
- fRemovedMRUWorkingSets= new ArrayList();
- return super.open();
- }
-
- /**
- * Removes the selected working sets from the workbench.
- */
- private void removeSelectedWorkingSets() {
- ISelection selection= fTableViewer.getSelection();
- if (selection instanceof IStructuredSelection) {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- Iterator iter= ((IStructuredSelection)selection).iterator();
- while (iter.hasNext()) {
- IWorkingSet workingSet= (IWorkingSet)iter.next();
- if (fAddedWorkingSets.contains(workingSet)) {
- fAddedWorkingSets.remove(workingSet);
- } else {
- IWorkingSet[] recentWorkingSets= manager.getRecentWorkingSets();
- for (int i= 0; i < recentWorkingSets.length; i++) {
- if (workingSet.equals(recentWorkingSets[i])) {
- fRemovedMRUWorkingSets.add(workingSet);
- break;
- }
- }
- fRemovedWorkingSets.add(workingSet);
- }
- fAllWorkingSets.remove(workingSet);
- manager.removeWorkingSet(workingSet);
- }
- fTableViewer.remove(((IStructuredSelection)selection).toArray());
- }
- }
-
- /**
- * Removes newly created working sets from the working set manager.
- */
- private void restoreAddedWorkingSets() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- Iterator iterator= fAddedWorkingSets.iterator();
-
- while (iterator.hasNext()) {
- manager.removeWorkingSet(((IWorkingSet)iterator.next()));
- }
- }
-
- /**
- * Rolls back changes to working sets.
- */
- private void restoreChangedWorkingSets() {
- Iterator iterator= fEditedWorkingSets.keySet().iterator();
-
- while (iterator.hasNext()) {
- IWorkingSet editedWorkingSet= (IWorkingSet)iterator.next();
- IWorkingSet originalWorkingSet= (IWorkingSet)fEditedWorkingSets.get(editedWorkingSet);
-
- if (editedWorkingSet.getName().equals(originalWorkingSet.getName()) == false) {
- editedWorkingSet.setName(originalWorkingSet.getName());
- }
- if (editedWorkingSet.getElements().equals(originalWorkingSet.getElements()) == false) {
- editedWorkingSet.setElements(originalWorkingSet.getElements());
- }
- }
- }
-
- /**
- * Adds back removed working sets to the working set manager.
- */
- private void restoreRemovedWorkingSets() {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- Iterator iterator= fRemovedWorkingSets.iterator();
-
- while (iterator.hasNext()) {
- manager.addWorkingSet(((IWorkingSet)iterator.next()));
- }
- iterator= fRemovedMRUWorkingSets.iterator();
- while (iterator.hasNext()) {
- manager.addRecentWorkingSet(((IWorkingSet)iterator.next()));
- }
- }
-
- /**
- * Updates the modify buttons' enabled state based on the current seleciton.
- */
- private void updateButtonAvailability() {
- IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
- boolean hasSelection= !selection.isEmpty();
- boolean hasSingleSelection= selection.size() == 1;
-
- fRemoveButton.setEnabled(hasSelection && areAllGlobalWorkingSets(selection));
- fEditButton.setEnabled(hasSingleSelection && ((IWorkingSet)selection.getFirstElement()).isEditable());
- if (fUpButton != null) {
- fUpButton.setEnabled(canMoveUp());
- }
- if (fDownButton != null) {
- fDownButton.setEnabled(canMoveDown());
- }
- }
-
- private boolean areAllGlobalWorkingSets(IStructuredSelection selection) {
- Set globals= new HashSet(Arrays.asList(PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets()));
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- if (!globals.contains(iter.next()))
- return false;
- }
- return true;
- }
-
- private void moveUp(List toMoveUp) {
- if (toMoveUp.size() > 0) {
- setElements(moveUp(fAllWorkingSets, toMoveUp));
- fTableViewer.reveal(toMoveUp.get(0));
- }
- }
-
- private void moveDown(List toMoveDown) {
- if (toMoveDown.size() > 0) {
- setElements(reverse(moveUp(reverse(fAllWorkingSets), toMoveDown)));
- fTableViewer.reveal(toMoveDown.get(toMoveDown.size() - 1));
- }
- }
-
- private void setElements(List elements) {
- fAllWorkingSets= elements;
- fTableViewer.setInput(fAllWorkingSets);
- updateButtonAvailability();
- }
-
- private List moveUp(List elements, List move) {
- int nElements= elements.size();
- List res= new ArrayList(nElements);
- Object floating= null;
- for (int i= 0; i < nElements; i++) {
- Object curr= elements.get(i);
- if (move.contains(curr)) {
- res.add(curr);
- } else {
- if (floating != null) {
- res.add(floating);
- }
- floating= curr;
- }
- }
- if (floating != null) {
- res.add(floating);
- }
- return res;
- }
-
- private List reverse(List p) {
- List reverse= new ArrayList(p.size());
- for (int i= p.size() - 1; i >= 0; i--) {
- reverse.add(p.get(i));
- }
- return reverse;
- }
-
- private boolean canMoveUp() {
- int[] indc= fTableViewer.getTable().getSelectionIndices();
- for (int i= 0; i < indc.length; i++) {
- if (indc[i] != i) {
- return true;
- }
- }
- return false;
- }
-
- private boolean canMoveDown() {
- int[] indc= fTableViewer.getTable().getSelectionIndices();
- int k= fAllWorkingSets.size() - 1;
- for (int i= indc.length - 1; i >= 0; i--, k--) {
- if (indc[i] != k) {
- return true;
- }
- }
- return false;
- }
-
- //---- select / deselect --------------------------------------------------
-
- private void selectAll() {
- fTableViewer.setAllChecked(true);
- }
-
- private void deselectAll() {
- fTableViewer.setAllChecked(false);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilter.java
deleted file mode 100644
index 79701aff..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilter.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer.RequiredProjectWrapper;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaViewerFilter;
-
-/**
- * Working set filter for Java viewers.
- */
-public class WorkingSetFilter extends JavaViewerFilter {
-
- private static class WorkingSetCompareEntry {
- private IPath fResourcePath;
- private IJavaScriptElement fJavaElement;
-
- public WorkingSetCompareEntry(IAdaptable a) {
- if (a instanceof IJavaScriptElement) {
- init((IJavaScriptElement) a);
- } else if (a instanceof IResource) {
- init((IResource) a);
- } else if (a instanceof RequiredProjectWrapper) {
- RequiredProjectWrapper wrapper= (RequiredProjectWrapper) a;
- IJavaScriptProject proj= wrapper.getParentJsGlobalScopeContainer().getJavaProject();
- // the project reference is treated like an internal JAR.
- // that means it will only appear if the parent container project is in the working set
- IResource fakeInternal= proj.getProject().getFile(wrapper.getProject().getElementName() + "-fake-jar.jar"); //$NON-NLS-1$
- init(proj.getPackageFragmentRoot(fakeInternal));
- } else {
- IJavaScriptElement je= (IJavaScriptElement) a.getAdapter(IJavaScriptElement.class);
- if (je != null) {
- init(je);
- } else {
- IResource resource= (IResource) a.getAdapter(IResource.class);
- if (resource != null) {
- init(resource);
- } else {
- fResourcePath= null;
- fJavaElement= null;
- }
- }
- }
- }
-
- private void init(IResource resource) {
- fJavaElement= JavaScriptCore.create(resource);
- fResourcePath= resource.getFullPath();
- }
-
- private void init(IJavaScriptElement curr) {
- fJavaElement= curr;
- fResourcePath= curr.getPath();
- }
-
- public boolean contains(WorkingSetCompareEntry element) {
- if (fJavaElement != null && element.fJavaElement != null) {
- IJavaScriptElement other= element.fJavaElement;
- if (fJavaElement.getElementType() == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot) other.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- if (pkgRoot != null && pkgRoot.isExternal() && pkgRoot.isArchive()) {
- if (((IJavaScriptProject) fJavaElement).isOnIncludepath(other)) {
- return true;
- }
- }
- }
-
- if (isAncestor(other, fJavaElement) || isAncestor(fJavaElement, other)) {
- return true;
- }
- return false;
- }
- if (fResourcePath != null && element.fResourcePath != null) {
- IPath other= element.fResourcePath;
- if (other.isPrefixOf(fResourcePath) || fResourcePath.isPrefixOf(other))
- return true;
- }
- return false;
- }
-
- private boolean isAncestor(IJavaScriptElement elem, IJavaScriptElement parent) {
- IJavaScriptElement anc= elem.getAncestor(parent.getElementType());
- if (parent.equals(anc)) {
- return true;
- }
- while (anc instanceof IMember) { // ITypes can be in ITypes
- anc= anc.getParent().getAncestor(parent.getElementType());
- if (parent.equals(anc)) {
- return true;
- }
- }
- return false;
- }
- }
-
- private IWorkingSet fWorkingSet;
-
- private WorkingSetCompareEntry[] fCachedCompareEntries;
-
- public WorkingSetFilter() {
- fWorkingSet= null;
- fCachedCompareEntries= null;
- }
-
- /**
- * Returns the working set which is used by this filter.
- *
- * @return the working set
- */
- public IWorkingSet getWorkingSet() {
- return fWorkingSet;
- }
-
- /**
- * Sets this filter's working set.
- *
- * @param workingSet the working set
- */
- public void setWorkingSet(IWorkingSet workingSet) {
- if (fWorkingSet != workingSet) {
- fWorkingSet= workingSet;
- notifyWorkingSetContentChange();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.filters.JavaViewerFilter#initFilter()
- */
- protected void initFilter() {
- notifyWorkingSetContentChange();
- }
-
- /**
- * Invoke when the content of the current working set changed. Clients are responsible to listen to changes and call this method.
- */
- public final void notifyWorkingSetContentChange() {
- if (fWorkingSet != null) {
- IAdaptable[] elements= fWorkingSet.getElements();
- fCachedCompareEntries= new WorkingSetCompareEntry[elements.length];
- for (int i= 0; i < elements.length; i++) {
- fCachedCompareEntries[i]= new WorkingSetCompareEntry(elements[i]);
- }
- } else {
- fCachedCompareEntries= null;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.internal.ui.filters.JavaViewerFilter#freeFilter()
- */
- protected void freeFilter() {
- fCachedCompareEntries= null;
- }
-
- /*
- * Overrides method from ViewerFilter.
- */
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (fWorkingSet == null || (fWorkingSet.isAggregateWorkingSet() && fWorkingSet.isEmpty()))
- return true;
-
- if (element instanceof PackageFragmentRootContainer) {
- return isEnclosing((PackageFragmentRootContainer)element);
- }
-
- if (element instanceof IAdaptable)
- return isEnclosing((IAdaptable)element);
-
- return true;
- }
-
- public boolean isEnclosing(IAdaptable a) {
- WorkingSetCompareEntry curr= new WorkingSetCompareEntry(a);
- if (fCachedCompareEntries != null) {
- for (int i= 0; i < fCachedCompareEntries.length; i++) {
- if (fCachedCompareEntries[i].contains(curr)) {
- return true;
- }
- }
- return false;
- }
- if (fWorkingSet != null) {
- IAdaptable[] elements= fWorkingSet.getElements();
- for (int i= 0; i < elements.length; i++) {
- if (new WorkingSetCompareEntry(elements[i]).contains(curr)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean isEnclosing(PackageFragmentRootContainer container) {
- // check whether the containing package fragment roots are enclosed
- IAdaptable[] roots= container.getChildren();
- for (int i= 0; i < roots.length; i++) {
- if (isEnclosing(roots[i])) {
- return true;
- }
- }
- return false;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java
deleted file mode 100644
index 357a971e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchPreferenceConstants;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.search.WorkingSetComparator;
-
-/**
- * Working set filter actions (set / clear)
- *
- *
- *
- */
-public class WorkingSetFilterActionGroup extends ActionGroup implements IWorkingSetActionGroup {
-
- private static final String TAG_WORKING_SET_NAME= "workingSetName"; //$NON-NLS-1$
- private static final String TAG_IS_WINDOW_WORKING_SET= "isWindowWorkingSet"; //$NON-NLS-1$
- private static final String LRU_GROUP= "workingSet_lru_group"; //$NON-NLS-1$
-
- private final WorkingSetFilter fWorkingSetFilter;
-
- private IWorkingSet fWorkingSet= null;
-
- private final ClearWorkingSetAction fClearWorkingSetAction;
- private final SelectWorkingSetAction fSelectWorkingSetAction;
- private final EditWorkingSetAction fEditWorkingSetAction;
-
- private IPropertyChangeListener fWorkingSetListener;
- private IPropertyChangeListener fChangeListener;
-
- private int fLRUMenuCount;
- private IMenuManager fMenuManager;
- private IMenuListener fMenuListener;
- private List fContributions= new ArrayList();
- private final IWorkbenchPage fWorkbenchPage;
- private boolean fAllowWindowWorkingSetByDefault;
-
- public WorkingSetFilterActionGroup(IWorkbenchPartSite site, IPropertyChangeListener changeListener) {
- Assert.isNotNull(site);
- Assert.isNotNull(changeListener);
-
- fChangeListener= changeListener;
- fWorkbenchPage= site.getPage();
- fAllowWindowWorkingSetByDefault= true;
- fClearWorkingSetAction= new ClearWorkingSetAction(this);
- fSelectWorkingSetAction= new SelectWorkingSetAction(this, site);
- fEditWorkingSetAction= new EditWorkingSetAction(this, site);
-
- fWorkingSetListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doPropertyChange(event);
- }
- };
- fWorkingSetFilter= new WorkingSetFilter();
-
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- manager.addPropertyChangeListener(fWorkingSetListener);
-
- if (useWindowWorkingSetByDefault()) {
- setWorkingSet(site.getPage().getAggregateWorkingSet(), false);
- }
- }
-
- public WorkingSetFilterActionGroup(Shell shell, IWorkbenchPage page, IPropertyChangeListener changeListener) {
- Assert.isNotNull(shell);
- Assert.isNotNull(changeListener);
-
- fWorkbenchPage= page;
- fAllowWindowWorkingSetByDefault= false;
- fChangeListener= changeListener;
- fClearWorkingSetAction= new ClearWorkingSetAction(this);
- fSelectWorkingSetAction= new SelectWorkingSetAction(this, shell);
- fEditWorkingSetAction= new EditWorkingSetAction(this, shell);
-
- fWorkingSetListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- doPropertyChange(event);
- }
- };
-
- fWorkingSetFilter= new WorkingSetFilter();
-
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- manager.addPropertyChangeListener(fWorkingSetListener);
-
- setWorkingSet(null, false);
- }
-
- /**
- * Returns whether the current working set filters the given element
- *
- * @param parent the parent
- * @param object the element to test
- * @return the working set
- */
- public boolean isFiltered(Object parent, Object object) {
- if (fWorkingSetFilter == null)
- return false;
- return !fWorkingSetFilter.select(null, parent, object);
- }
-
-
- /**
- * Returns the working set which is used by the filter.
- *
- * @return the working set
- */
- public IWorkingSet getWorkingSet() {
- return fWorkingSet;
- }
-
- /**
- * Sets this filter's working set.
- *
- * @param workingSet the working set
- * @param refreshViewer Indicates if the viewer should be refreshed.
- */
- public void setWorkingSet(IWorkingSet workingSet, boolean refreshViewer) {
- // Update action
- fClearWorkingSetAction.setEnabled(workingSet != null);
- fEditWorkingSetAction.setEnabled(workingSet != null && !workingSet.isAggregateWorkingSet());
-
- fWorkingSet= workingSet;
-
- fWorkingSetFilter.setWorkingSet(workingSet);
- if (refreshViewer) {
- fChangeListener.propertyChange(new PropertyChangeEvent(this, IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE, null, workingSet));
- }
- }
-
- /**
- * Saves the state of the filter actions in a memento.
- *
- * @param memento the memento
- */
- public void saveState(IMemento memento) {
- String workingSetName= ""; //$NON-NLS-1$
- boolean isWindowWorkingSet= false;
- if (fWorkingSet != null) {
- if (fWorkingSet.isAggregateWorkingSet()) {
- isWindowWorkingSet= true;
- } else {
- workingSetName= fWorkingSet.getName();
- }
- }
- memento.putString(TAG_IS_WINDOW_WORKING_SET, Boolean.toString(isWindowWorkingSet));
- memento.putString(TAG_WORKING_SET_NAME, workingSetName);
- }
-
- /**
- * Restores the state of the filter actions from a memento.
- * <p>
- * Note: This method does not refresh the viewer.
- * </p>
- * @param memento
- */
- public void restoreState(IMemento memento) {
- boolean isWindowWorkingSet;
- if (memento.getString(TAG_IS_WINDOW_WORKING_SET) != null) {
- isWindowWorkingSet= Boolean.valueOf(memento.getString(TAG_IS_WINDOW_WORKING_SET)).booleanValue();
- } else {
- isWindowWorkingSet= useWindowWorkingSetByDefault();
- }
- String workingSetName= memento.getString(TAG_WORKING_SET_NAME);
- boolean hasWorkingSetName= workingSetName != null && workingSetName.length() > 0;
-
- IWorkingSet ws= null;
- // First handle name if present.
- if (hasWorkingSetName) {
- ws= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(workingSetName);
- } else if (isWindowWorkingSet && fWorkbenchPage != null) {
- ws= fWorkbenchPage.getAggregateWorkingSet();
- }
- setWorkingSet(ws, false);
- }
-
- private boolean useWindowWorkingSetByDefault() {
- return fAllowWindowWorkingSetByDefault && PlatformUI.getPreferenceStore().getBoolean(IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT);
- }
-
-
- /* (non-Javadoc)
- * @see ActionGroup#fillActionBars(IActionBars)
- */
- public void fillActionBars(IActionBars actionBars) {
- fillToolBar(actionBars.getToolBarManager());
- fillViewMenu(actionBars.getMenuManager());
- }
-
- /**
- * Adds the filter actions to the tool bar
- *
- * @param tbm the tool bar manager
- */
- private void fillToolBar(IToolBarManager tbm) {
- // do nothing
- }
-
- /**
- * Adds the filter actions to the menu
- *
- * @param mm the menu manager
- */
- public void fillViewMenu(IMenuManager mm) {
- if (mm.find(IWorkingSetActionGroup.ACTION_GROUP) == null) {
- mm.add(new Separator(IWorkingSetActionGroup.ACTION_GROUP));
- }
- add(mm, fSelectWorkingSetAction);
- add(mm, fClearWorkingSetAction);
- add(mm, fEditWorkingSetAction);
- add(mm, new Separator());
- add(mm, new Separator(LRU_GROUP));
-
- fMenuManager= mm;
- fMenuListener= new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- removePreviousLRUWorkingSetActions(manager);
- addLRUWorkingSetActions(manager);
- }
- };
- fMenuManager.addMenuListener(fMenuListener);
- }
-
- private void add(IMenuManager mm, IAction action) {
- IContributionItem item= new ActionContributionItem(action);
- mm.appendToGroup(ACTION_GROUP, item);
- fContributions.add(item);
- }
-
- private void add(IMenuManager mm, IContributionItem item) {
- mm.appendToGroup(ACTION_GROUP, item);
- fContributions.add(item);
- }
-
- private void removePreviousLRUWorkingSetActions(IMenuManager mm) {
- for (int i= 1; i < fLRUMenuCount; i++) {
- String id= WorkingSetMenuContributionItem.getId(i);
- IContributionItem item= mm.remove(id);
- if (item != null) {
- item.dispose();
- fContributions.remove(item);
- }
- }
- }
-
- private void addLRUWorkingSetActions(IMenuManager mm) {
- IWorkingSet[] workingSets= PlatformUI.getWorkbench().getWorkingSetManager().getRecentWorkingSets();
- Arrays.sort(workingSets, new WorkingSetComparator());
-
- int currId= 1;
- if (fWorkbenchPage != null) {
- addLRUWorkingSetAction(mm, currId++, fWorkbenchPage.getAggregateWorkingSet());
- }
-
- for (int i= 0; i < workingSets.length; i++) {
- if (!workingSets[i].isAggregateWorkingSet()) {
- addLRUWorkingSetAction(mm, currId++, workingSets[i]);
- }
- }
- fLRUMenuCount= currId;
- }
-
- private void addLRUWorkingSetAction(IMenuManager mm, int id, IWorkingSet workingSet) {
- IContributionItem item= new WorkingSetMenuContributionItem(id, this, workingSet);
- mm.insertBefore(LRU_GROUP, item);
- fContributions.add(item);
- }
-
-
- public void cleanViewMenu(IMenuManager menuManager) {
- for (Iterator iter= fContributions.iterator(); iter.hasNext();) {
- IContributionItem removed= menuManager.remove((IContributionItem) iter.next());
- if (removed != null) {
- removed.dispose();
- }
- }
- fContributions.clear();
- fMenuManager.removeMenuListener(fMenuListener);
- fMenuListener= null;
- }
-
- /* (non-Javadoc)
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- if (fMenuManager != null && fMenuListener != null)
- fMenuManager.removeMenuListener(fMenuListener);
-
- if (fWorkingSetListener != null) {
- PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(fWorkingSetListener);
- fWorkingSetListener= null;
- }
- fChangeListener= null; // clear the reference to the viewer
-
- super.dispose();
- }
-
- /**
- * @return Returns viewer filter always configured with the current working set.
- */
- public ViewerFilter getWorkingSetFilter() {
- return fWorkingSetFilter;
- }
-
- /*
- * Called by the working set change listener
- */
- private void doPropertyChange(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
- fChangeListener.propertyChange(event);
- } else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- IWorkingSet newWorkingSet= (IWorkingSet) event.getNewValue();
- if (newWorkingSet.equals(fWorkingSet)) {
- if (fWorkingSetFilter != null) {
- fWorkingSetFilter.notifyWorkingSetContentChange(); // first refresh the filter
- }
- fChangeListener.propertyChange(event);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java
deleted file mode 100644
index e0e87a77..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Menu contribution item which shows and lets select a working set.
- *
- *
- */
-public class WorkingSetMenuContributionItem extends ContributionItem {
-
- private int fId;
- private IWorkingSet fWorkingSet;
- private WorkingSetFilterActionGroup fActionGroup;
- private Image fImage;
-
- /**
- * Constructor for WorkingSetMenuContributionItem.
- *
- * @param id the id
- * @param actionGroup the action group
- * @param workingSet the working set
- */
- public WorkingSetMenuContributionItem(int id, WorkingSetFilterActionGroup actionGroup, IWorkingSet workingSet) {
- super(getId(id));
- Assert.isNotNull(actionGroup);
- Assert.isNotNull(workingSet);
- fId= id;
- fActionGroup= actionGroup;
- fWorkingSet= workingSet;
- }
-
- /*
- * Overrides method from ContributionItem.
- */
- public void fill(Menu menu, int index) {
- MenuItem mi= new MenuItem(menu, SWT.RADIO, index);
-
- String name= fWorkingSet.getLabel();
-
- mi.setText("&" + fId + " " + name); //$NON-NLS-1$ //$NON-NLS-2$
- if (fImage == null) {
- ImageDescriptor imageDescriptor= fWorkingSet.getImage();
- if (imageDescriptor != null)
- fImage= imageDescriptor.createImage();
- }
- mi.setImage(fImage);
- mi.setSelection(fWorkingSet.equals(fActionGroup.getWorkingSet()));
- mi.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- IWorkingSetManager manager= PlatformUI.getWorkbench().getWorkingSetManager();
- fActionGroup.setWorkingSet(fWorkingSet, true);
- manager.addRecentWorkingSet(fWorkingSet);
- }
- });
- }
-
- /*
- * @see org.eclipse.jface.action.ContributionItem#dispose()
- *
- */
- public void dispose() {
- if (fImage != null && !fImage.isDisposed())
- fImage.dispose();
- fImage= null;
-
- super.dispose();
- }
-
- /*
- * @see org.eclipse.jface.action.IContributionItem#isDynamic()
- */
- public boolean isDynamic() {
- return true;
- }
-
- static String getId(int id) {
- return WorkingSetMenuContributionItem.class.getName() + "." + id; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.java
deleted file mode 100644
index e74c0f52..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import org.eclipse.osgi.util.NLS;
-
-public final class WorkingSetMessages extends NLS {
-
- private static final String BUNDLE_NAME= "org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetMessages";//$NON-NLS-1$
-
- private WorkingSetMessages() {
- // Do not instantiate
- }
-
- public static String AbstractWorkingSetPage_workingSet_name;
- public static String AbstractWorkingSetPage_warning_nameMustNotBeEmpty;
- public static String AbstractWorkingSetPage_warning_workingSetExists;
- public static String AbstractWorkingSetPage_warning_nameWhitespace;
- public static String ConfigureWorkingSetAssignementAction_DialogMessage_multi;
- public static String ConfigureWorkingSetAssignementAction_DialogMessage_specific;
- public static String ConfigureWorkingSetAssignementAction_OnlyShowVisible_link;
- public static String ConfigureWorkingSetAssignementAction_WorkingSetAssignments_title;
- public static String ConfigureWorkingSetAssignementAction_WorkingSets_actionLabel;
- public static String ConfigureWorkingSetAssignementAction_XofY_label;
-
- public static String JavaWorkingSetPage_title;
- public static String JavaWorkingSetPage_workingSet_name;
- public static String JavaWorkingSetPage_workingSet_description;
- public static String JavaWorkingSetPage_workingSet_content;
- public static String JavaWorkingSetPage_warning_nameMustNotBeEmpty;
- public static String JavaWorkingSetPage_warning_workingSetExists;
- public static String JavaWorkingSetPage_warning_resourceMustBeChecked;
- public static String JavaWorkingSetPage_warning_nameWhitespace;
- public static String JavaWorkingSetPage_selectAll_label;
- public static String JavaWorkingSetPage_selectAll_toolTip;
- public static String JavaWorkingSetPage_deselectAll_label;
- public static String JavaWorkingSetPage_deselectAll_toolTip;
-
- public static String SelectWorkingSetAction_text;
- public static String SelectWorkingSetAction_toolTip;
-
- public static String EditWorkingSetAction_text;
- public static String EditWorkingSetAction_toolTip;
- public static String EditWorkingSetAction_error_nowizard_title;
- public static String EditWorkingSetAction_error_nowizard_message;
-
- public static String ClearWorkingSetAction_text;
- public static String ClearWorkingSetAction_toolTip;
-
- public static String ConfigureWorkingSetAction_label;
- public static String SimpleWorkingSetSelectionDialog_DeselectAll_button;
- public static String SimpleWorkingSetSelectionDialog_New_button;
- public static String SimpleWorkingSetSelectionDialog_SelectAll_button;
- public static String SimpleWorkingSetSelectionDialog_SimpleSelectWorkingSetDialog_title;
- public static String ViewActionGroup_show_label;
- public static String ViewActionGroup_projects_label;
- public static String ViewActionGroup_workingSets_label;
- public static String WorkingSetConfigurationBlock_SelectWorkingSet_button;
- public static String WorkingSetConfigurationBlock_WorkingSetText_name;
-
- public static String WorkingSetModel_others_name;
-
- public static String WorkingSetConfigurationDialog_title;
- public static String WorkingSetConfigurationDialog_message;
- public static String WorkingSetConfigurationDialog_new_label;
- public static String WorkingSetConfigurationDialog_edit_label;
- public static String WorkingSetConfigurationDialog_remove_label;
- public static String WorkingSetConfigurationDialog_up_label;
- public static String WorkingSetConfigurationDialog_down_label;
- public static String WorkingSetConfigurationDialog_selectAll_label;
- public static String WorkingSetConfigurationDialog_deselectAll_label;
-
- public static String OpenPropertiesWorkingSetAction_label;
- public static String RemoveWorkingSetElementAction_label;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, WorkingSetMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties
deleted file mode 100644
index fcb9e427..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties
+++ /dev/null
@@ -1,79 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-AbstractWorkingSetPage_workingSet_name= &Working set name:
-AbstractWorkingSetPage_warning_nameMustNotBeEmpty= The name must not be empty.
-AbstractWorkingSetPage_warning_workingSetExists= A working set with that name already exists.
-AbstractWorkingSetPage_warning_nameWhitespace= The name must not have leading or trailing whitespace.
-
-JavaWorkingSetPage_title= JavaScript Working Set
-JavaWorkingSetPage_workingSet_name= &Working set name:
-JavaWorkingSetPage_workingSet_description= Enter a working set name and select the working set elements.
-
-JavaWorkingSetPage_workingSet_content= Working set &content:
-JavaWorkingSetPage_warning_nameMustNotBeEmpty= The name must not be empty.
-JavaWorkingSetPage_warning_workingSetExists= A working set with that name already exists.
-JavaWorkingSetPage_warning_resourceMustBeChecked= No resources selected.
-JavaWorkingSetPage_warning_nameWhitespace= The name must not have leading or trailing whitespace.
-
-JavaWorkingSetPage_selectAll_label=Select &All
-JavaWorkingSetPage_selectAll_toolTip=Select all of the JavaScript elements for this working set.
-JavaWorkingSetPage_deselectAll_label=Dese&lect All
-JavaWorkingSetPage_deselectAll_toolTip=Deselect all of the JavaScript elements for this working set.
-
-SelectWorkingSetAction_text= Select &Working Set...
-SelectWorkingSetAction_toolTip= Select a working set
-
-EditWorkingSetAction_text= &Edit Active Working Set...
-EditWorkingSetAction_toolTip= Edit the active working set
-EditWorkingSetAction_error_nowizard_title= Edit Working Set
-EditWorkingSetAction_error_nowizard_message= Cannot edit the active working set.
-
-ClearWorkingSetAction_text= &Deselect Working Set
-ClearWorkingSetAction_toolTip= Deselect the active working set
-
-ConfigureWorkingSetAction_label=Configure &Working Sets...
-ViewActionGroup_show_label=&Top Level Elements
-ViewActionGroup_projects_label=&Projects
-ViewActionGroup_workingSets_label=&Working Sets
-
-#---- working set model ---------------------------------------------------------------
-WorkingSetModel_others_name=Other Projects
-
-#---- working set configuration dialog ------------------------------------------------
-WorkingSetConfigurationDialog_title=Select Working Sets
-WorkingSetConfigurationDialog_message=Check &working sets visible in Script Explorer:
-WorkingSetConfigurationDialog_new_label=&New...
-WorkingSetConfigurationDialog_edit_label=&Edit...
-WorkingSetConfigurationDialog_remove_label=&Remove
-WorkingSetConfigurationDialog_up_label=&Up
-WorkingSetConfigurationDialog_down_label=&Down
-WorkingSetConfigurationDialog_selectAll_label=Select &All
-WorkingSetConfigurationDialog_deselectAll_label=Dese&lect All
-WorkingSetConfigurationBlock_WorkingSetText_name=W&orking sets:
-WorkingSetConfigurationBlock_SelectWorkingSet_button=S&elect...
-
-
-#---- Properties action -------------------------------------------------------
-OpenPropertiesWorkingSetAction_label=Con&figure...
-
-#---- Remove action -----------------------------------------------------------
-RemoveWorkingSetElementAction_label=Remo&ve from Working Set
-SimpleWorkingSetSelectionDialog_SimpleSelectWorkingSetDialog_title=Working Set Selection
-SimpleWorkingSetSelectionDialog_SelectAll_button=Select &All
-SimpleWorkingSetSelectionDialog_New_button=&New...
-SimpleWorkingSetSelectionDialog_DeselectAll_button=&Deselect All
-ConfigureWorkingSetAssignementAction_OnlyShowVisible_link=Show &only <a>Script Explorer working sets</a>
-ConfigureWorkingSetAssignementAction_WorkingSets_actionLabel=&Assign Working Sets...
-ConfigureWorkingSetAssignementAction_WorkingSetAssignments_title=Working Set Assignments
-ConfigureWorkingSetAssignementAction_DialogMessage_specific=Select &working sets for ''{0}'':
-ConfigureWorkingSetAssignementAction_DialogMessage_multi=Select &working sets for {0} selected elements:
-ConfigureWorkingSetAssignementAction_XofY_label=\ ({0} of {1})
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetModel.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetModel.java
deleted file mode 100644
index 74a45cb7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetModel.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.ui.ILocalWorkingSetManager;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.IWorkingSetManager;
-import org.eclipse.ui.IWorkingSetUpdater;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-public class WorkingSetModel {
-
- public static final String CHANGE_WORKING_SET_MODEL_CONTENT= "workingSetModelChanged"; //$NON-NLS-1$
-
- public static final IElementComparer COMPARER= new WorkingSetComparar();
-
- private static final String TAG_LOCAL_WORKING_SET_MANAGER= "localWorkingSetManager"; //$NON-NLS-1$
- private static final String TAG_ACTIVE_WORKING_SET= "activeWorkingSet"; //$NON-NLS-1$
- private static final String TAG_WORKING_SET_NAME= "workingSetName"; //$NON-NLS-1$
- private static final String TAG_CONFIGURED= "configured"; //$NON-NLS-1$
-
- private ILocalWorkingSetManager fLocalWorkingSetManager;
- private List fActiveWorkingSets;
- private ListenerList fListeners;
- private IPropertyChangeListener fWorkingSetManagerListener;
- private OthersWorkingSetUpdater fOthersWorkingSetUpdater;
-
- private ElementMapper fElementMapper= new ElementMapper();
-
- private boolean fConfigured;
-
- private static class WorkingSetComparar implements IElementComparer {
- public boolean equals(Object o1, Object o2) {
- IWorkingSet w1= o1 instanceof IWorkingSet ? (IWorkingSet)o1 : null;
- IWorkingSet w2= o2 instanceof IWorkingSet ? (IWorkingSet)o2 : null;
- if (w1 == null || w2 == null)
- return o1.equals(o2);
- return w1 == w2;
- }
- public int hashCode(Object element) {
- if (element instanceof IWorkingSet)
- return System.identityHashCode(element);
- return element.hashCode();
- }
- }
-
- private static class ElementMapper {
- private Map fElementToWorkingSet= new HashMap();
- private Map fWorkingSetToElement= new IdentityHashMap();
-
- private Map fResourceToWorkingSet= new HashMap();
- private List fNonProjectTopLevelElements= new ArrayList();
-
- public void clear() {
- fElementToWorkingSet.clear();
- fWorkingSetToElement.clear();
- fResourceToWorkingSet.clear();
- fNonProjectTopLevelElements.clear();
- }
- public void rebuild(IWorkingSet[] workingSets) {
- clear();
- for (int i= 0; i < workingSets.length; i++) {
- put(workingSets[i]);
- }
- }
- public IAdaptable[] remove(IWorkingSet ws) {
- IAdaptable[] elements= (IAdaptable[])fWorkingSetToElement.remove(ws);
- if (elements != null) {
- for (int i= 0; i < elements.length; i++) {
- removeElement(elements[i], ws);
- }
- }
- return elements;
- }
- public IAdaptable[] refresh(IWorkingSet ws) {
- IAdaptable[] oldElements= (IAdaptable[])fWorkingSetToElement.get(ws);
- if (oldElements == null)
- return null;
- IAdaptable[] newElements= ws.getElements();
- List toRemove= new ArrayList(Arrays.asList(oldElements));
- List toAdd= new ArrayList(Arrays.asList(newElements));
- computeDelta(toRemove, toAdd, oldElements, newElements);
- for (Iterator iter= toAdd.iterator(); iter.hasNext();) {
- addElement((IAdaptable)iter.next(), ws);
- }
- for (Iterator iter= toRemove.iterator(); iter.hasNext();) {
- removeElement((IAdaptable)iter.next(), ws);
- }
- if (toRemove.size() > 0 || toAdd.size() > 0)
- fWorkingSetToElement.put(ws, newElements);
- return oldElements;
- }
- private void computeDelta(List toRemove, List toAdd, IAdaptable[] oldElements, IAdaptable[] newElements) {
- for (int i= 0; i < oldElements.length; i++) {
- toAdd.remove(oldElements[i]);
- }
- for (int i= 0; i < newElements.length; i++) {
- toRemove.remove(newElements[i]);
- }
-
- }
- public IWorkingSet getFirstWorkingSet(Object element) {
- return (IWorkingSet)getFirstElement(fElementToWorkingSet, element);
- }
- public List getAllWorkingSets(Object element) {
- List allElements= getAllElements(fElementToWorkingSet, element);
- if (allElements.isEmpty() && element instanceof IJavaScriptElement) {
- // try a second time in case the working set was manually updated (bug 168032)
- allElements= getAllElements(fElementToWorkingSet, ((IJavaScriptElement) element).getResource());
- }
- return allElements;
- }
- public IWorkingSet getFirstWorkingSetForResource(IResource resource) {
- return (IWorkingSet)getFirstElement(fResourceToWorkingSet, resource);
- }
- public List getAllWorkingSetsForResource(IResource resource) {
- return getAllElements(fResourceToWorkingSet, resource);
- }
- public List getNonProjectTopLevelElements() {
- return fNonProjectTopLevelElements;
- }
- private void put(IWorkingSet ws) {
- if (fWorkingSetToElement.containsKey(ws))
- return;
- IAdaptable[] elements= ws.getElements();
- fWorkingSetToElement.put(ws, elements);
- for (int i= 0; i < elements.length; i++) {
- IAdaptable element= elements[i];
- addElement(element, ws);
- if (!(element instanceof IProject) && !(element instanceof IJavaScriptProject)) {
- fNonProjectTopLevelElements.add(element);
- }
- }
- }
- private void addElement(IAdaptable element, IWorkingSet ws) {
- addToMap(fElementToWorkingSet, element, ws);
- IResource resource= (IResource)element.getAdapter(IResource.class);
- if (resource != null) {
- addToMap(fResourceToWorkingSet, resource, ws);
- }
- }
- private void removeElement(IAdaptable element, IWorkingSet ws) {
- removeFromMap(fElementToWorkingSet, element, ws);
- IResource resource= (IResource)element.getAdapter(IResource.class);
- if (resource != null) {
- removeFromMap(fResourceToWorkingSet, resource, ws);
- }
- }
- private void addToMap(Map map, IAdaptable key, IWorkingSet value) {
- Object obj= map.get(key);
- if (obj == null) {
- map.put(key, value);
- } else if (obj instanceof IWorkingSet) {
- List l= new ArrayList(2);
- l.add(obj);
- l.add(value);
- map.put(key, l);
- } else if (obj instanceof List) {
- ((List)obj).add(value);
- }
- }
- private void removeFromMap(Map map, IAdaptable key, IWorkingSet value) {
- Object current= map.get(key);
- if (current == null) {
- return;
- } else if (current instanceof List) {
- List list= (List)current;
- list.remove(value);
- switch (list.size()) {
- case 0:
- map.remove(key);
- break;
- case 1:
- map.put(key, list.get(0));
- break;
- }
- } else if (current == value) {
- map.remove(key);
- }
- }
- private Object getFirstElement(Map map, Object key) {
- Object obj= map.get(key);
- if (obj instanceof List)
- return ((List)obj).get(0);
- return obj;
- }
- private List getAllElements(Map map, Object key) {
- Object obj= map.get(key);
- if (obj instanceof List)
- return (List)obj;
- if (obj == null)
- return Collections.EMPTY_LIST;
- List result= new ArrayList(1);
- result.add(obj);
- return result;
- }
- }
-
- /**
- * @param memento a memento, or <code>null</code>
- */
- public WorkingSetModel(IMemento memento) {
- fLocalWorkingSetManager= PlatformUI.getWorkbench().createLocalWorkingSetManager();
- addListenersToWorkingSetManagers();
- fActiveWorkingSets= new ArrayList(2);
-
- if (memento == null || ! restoreState(memento)) {
- IWorkingSet others= fLocalWorkingSetManager.createWorkingSet(WorkingSetMessages.WorkingSetModel_others_name, new IAdaptable[0]);
- others.setId(OthersWorkingSetUpdater.ID);
- fLocalWorkingSetManager.addWorkingSet(others);
- fActiveWorkingSets.add(others);
- }
- Assert.isNotNull(fOthersWorkingSetUpdater);
-
- fElementMapper.rebuild(getActiveWorkingSets());
- fOthersWorkingSetUpdater.updateElements();
- }
-
- private void addListenersToWorkingSetManagers() {
- fListeners= new ListenerList(ListenerList.IDENTITY);
- fWorkingSetManagerListener= new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- workingSetManagerChanged(event);
- }
- };
- PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(fWorkingSetManagerListener);
- fLocalWorkingSetManager.addPropertyChangeListener(fWorkingSetManagerListener);
- }
-
- public void dispose() {
- if (fWorkingSetManagerListener != null) {
- PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(fWorkingSetManagerListener);
- fLocalWorkingSetManager.removePropertyChangeListener(fWorkingSetManagerListener);
- fLocalWorkingSetManager.dispose();
- fWorkingSetManagerListener= null;
- }
- }
-
- //---- model relationships ---------------------------------------
-
- public IAdaptable[] getChildren(IWorkingSet workingSet) {
- return workingSet.getElements();
- }
-
- public Object getParent(Object element) {
- if (element instanceof IWorkingSet && fActiveWorkingSets.contains(element))
- return this;
- return fElementMapper.getFirstWorkingSet(element);
- }
-
- public Object[] getAllParents(Object element) {
- if (element instanceof IWorkingSet && fActiveWorkingSets.contains(element))
- return new Object[] {this};
- return fElementMapper.getAllWorkingSets(element).toArray();
- }
-
- public Object[] addWorkingSets(Object[] elements) {
- List result= null;
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- List sets= null;
- if (element instanceof IResource) {
- sets= fElementMapper.getAllWorkingSetsForResource((IResource)element);
- } else {
- sets= fElementMapper.getAllWorkingSets(element);
- }
- if (sets != null && sets.size() > 0) {
- if (result == null)
- result= new ArrayList(Arrays.asList(elements));
- result.addAll(sets);
- }
- }
- if (result == null)
- return elements;
- return result.toArray();
- }
-
- public boolean needsConfiguration() {
- return !fConfigured && fActiveWorkingSets.size() == 1 &&
- OthersWorkingSetUpdater.ID.equals(((IWorkingSet)fActiveWorkingSets.get(0)).getId());
- }
-
- public void configured() {
- fConfigured= true;
- }
-
- //---- working set management -----------------------------------
-
- /**
- * Adds a property change listener.
- *
- * @param listener the property change listener to add
- */
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.add(listener);
- }
-
- /**
- * Removes the property change listener.
- *
- * @param listener the property change listener to remove
- */
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- fListeners.remove(listener);
- }
-
- public IWorkingSet[] getActiveWorkingSets() {
- return (IWorkingSet[])fActiveWorkingSets.toArray(new IWorkingSet[fActiveWorkingSets.size()]);
- }
-
- public IWorkingSet[] getAllWorkingSets() {
- List result= new ArrayList();
- result.addAll(fActiveWorkingSets);
- IWorkingSet[] locals= fLocalWorkingSetManager.getWorkingSets();
- for (int i= 0; i < locals.length; i++) {
- if (!result.contains(locals[i]))
- result.add(locals[i]);
- }
- IWorkingSet[] globals= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets();
- for (int i= 0; i < globals.length; i++) {
- if (!result.contains(globals[i]))
- result.add(globals[i]);
- }
- return (IWorkingSet[])result.toArray(new IWorkingSet[result.size()]);
- }
-
- public void setActiveWorkingSets(IWorkingSet[] workingSets) {
- fActiveWorkingSets= new ArrayList(Arrays.asList(workingSets));
- fElementMapper.rebuild(getActiveWorkingSets());
- fOthersWorkingSetUpdater.updateElements();
- fireEvent(new PropertyChangeEvent(this, CHANGE_WORKING_SET_MODEL_CONTENT, null, null));
- }
-
- public void saveState(IMemento memento) {
- memento.putString(TAG_CONFIGURED, Boolean.toString(fConfigured));
- fLocalWorkingSetManager.saveState(memento.createChild(TAG_LOCAL_WORKING_SET_MANAGER));
- for (Iterator iter= fActiveWorkingSets.iterator(); iter.hasNext();) {
- IMemento active= memento.createChild(TAG_ACTIVE_WORKING_SET);
- IWorkingSet workingSet= (IWorkingSet)iter.next();
- active.putString(TAG_WORKING_SET_NAME, workingSet.getName());
- }
- }
-
- public List getNonProjectTopLevelElements() {
- return fElementMapper.getNonProjectTopLevelElements();
- }
-
- /**
- * Restore localWorkingSetManager and active working sets
- * @param memento
- * @return whether the restore was successful
- */
- private boolean restoreState(IMemento memento) {
- String configured= memento.getString(TAG_CONFIGURED);
- if (configured == null)
- return false;
-
- fConfigured= Boolean.valueOf(configured).booleanValue();
- fLocalWorkingSetManager.restoreState(memento.getChild(TAG_LOCAL_WORKING_SET_MANAGER));
-
- IMemento[] actives= memento.getChildren(TAG_ACTIVE_WORKING_SET);
- for (int i= 0; i < actives.length; i++) {
- String name= actives[i].getString(TAG_WORKING_SET_NAME);
- if (name != null) {
- IWorkingSet ws= fLocalWorkingSetManager.getWorkingSet(name);
- if (ws == null) {
- ws= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(name);
- }
- if (ws != null) {
- fActiveWorkingSets.add(ws);
- }
- }
- }
- return true;
- }
- private void workingSetManagerChanged(PropertyChangeEvent event) {
- String property= event.getProperty();
- if (IWorkingSetManager.CHANGE_WORKING_SET_UPDATER_INSTALLED.equals(property) && event.getSource() == fLocalWorkingSetManager) {
- IWorkingSetUpdater updater= (IWorkingSetUpdater)event.getNewValue();
- if (updater instanceof OthersWorkingSetUpdater) {
- fOthersWorkingSetUpdater= (OthersWorkingSetUpdater)updater;
- fOthersWorkingSetUpdater.init(this);
- }
- return;
- }
- // don't handle working sets not managed by the model
- if (!isAffected(event))
- return;
-
- if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
- IWorkingSet workingSet= (IWorkingSet)event.getNewValue();
- IAdaptable[] elements= fElementMapper.refresh(workingSet);
- if (elements != null) {
- fireEvent(event);
- }
- } else if (IWorkingSetManager.CHANGE_WORKING_SET_REMOVE.equals(property)) {
- IWorkingSet workingSet= (IWorkingSet)event.getOldValue();
- List elements= new ArrayList(fActiveWorkingSets);
- elements.remove(workingSet);
- setActiveWorkingSets((IWorkingSet[])elements.toArray(new IWorkingSet[elements.size()]));
- } else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
- fireEvent(event);
- }
- }
-
- private void fireEvent(PropertyChangeEvent event) {
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ((IPropertyChangeListener)listeners[i]).propertyChange(event);
- }
- }
-
- private boolean isAffected(PropertyChangeEvent event) {
- if (fActiveWorkingSets == null)
- return false;
- Object oldValue= event.getOldValue();
- Object newValue= event.getNewValue();
- if ((oldValue != null && fActiveWorkingSets.contains(oldValue))
- || (newValue != null && fActiveWorkingSets.contains(newValue))) {
- return true;
- }
- return false;
- }
-
- public boolean isActiveWorkingSet(IWorkingSet changedWorkingSet) {
- return fActiveWorkingSets.contains(changedWorkingSet);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetShowActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetShowActionGroup.java
deleted file mode 100644
index a3eb4af0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetShowActionGroup.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.internal.ui.workingsets;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.actions.ActionGroup;
-
-public class WorkingSetShowActionGroup extends ActionGroup implements IWorkingSetActionGroup {
-
- private List fContributions= new ArrayList();
- private ConfigureWorkingSetAction fConfigureWorkingSetAction;
- private WorkingSetModel fWorkingSetModel;
- private final IWorkbenchPartSite fSite;
-
- public WorkingSetShowActionGroup(IWorkbenchPartSite site) {
- Assert.isNotNull(site);
- fSite= site;
- }
-
- public void setWorkingSetMode(WorkingSetModel model) {
- Assert.isNotNull(model);
- fWorkingSetModel= model;
- if (fConfigureWorkingSetAction != null)
- fConfigureWorkingSetAction.setWorkingSetModel(fWorkingSetModel);
- }
-
- /**
- * {@inheritDoc}
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- IMenuManager menuManager= actionBars.getMenuManager();
- fillViewMenu(menuManager);
- }
-
- public void fillViewMenu(IMenuManager menuManager) {
- fConfigureWorkingSetAction= new ConfigureWorkingSetAction(fSite);
- if (fWorkingSetModel != null)
- fConfigureWorkingSetAction.setWorkingSetModel(fWorkingSetModel);
- addAction(menuManager, fConfigureWorkingSetAction);
- }
-
- public void cleanViewMenu(IMenuManager menuManager) {
- for (Iterator iter= fContributions.iterator(); iter.hasNext();) {
- IContributionItem removed= menuManager.remove((IContributionItem) iter.next());
- if (removed != null) {
- removed.dispose();
- }
- }
- fContributions.clear();
- }
-
- private void addAction(IMenuManager menuManager, Action action) {
- IContributionItem item= new ActionContributionItem(action);
- menuManager.appendToGroup(ACTION_GROUP, item);
- fContributions.add(item);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java
deleted file mode 100644
index eaee11c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.libraries;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.IJsGlobalScopeContainerInitializerExtension;
-
-/**
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class BasicBrowserLibraryContainerUIExtension implements IJsGlobalScopeContainerInitializerExtension {
- public ImageDescriptor getImage(IPath containerPath, String element, IJavaScriptProject project) {
-
- if(containerPath==null) return null;
- /* Dont use the rino image for the individual files */
- String requestedContainerPath = new Path(element).getFileExtension();
- if(requestedContainerPath!=null && requestedContainerPath.equalsIgnoreCase("js")) return null; //$NON-NLS-1$
- return ImageDescriptor.createFromFile(this.getClass(),"rino.gif"); //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/rino.gif b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/rino.gif
deleted file mode 100644
index cf14f3d4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/rino.gif
+++ /dev/null
Binary files differ
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeGeneration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeGeneration.java
deleted file mode 100644
index f57b6b1e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeGeneration.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CodeGeneration {
-
-
- /**
- * Constant ID for the type kind to be used in {@link #getTypeBody(String, IJavaScriptUnit, String, String)} to get the code template used
- * for a new class type body.
- *
- */
- public static final String CLASS_BODY_TEMPLATE_ID= CodeTemplateContextType.CLASSBODY_ID;
-
- private CodeGeneration() {
- }
-
- /**
- * Returns the content for a new compilation unit using the 'new JavaScript file' code template.
- * @param cu The compilation unit to create the source for. The compilation unit does not need to exist.
- * @param typeComment The comment for the type to be created. Used when the code template contains a <i>${typecomment}</i> variable. Can be <code>null</code> if
- * no comment should be added.
- * @param typeContent The code of the type, including type declaration and body.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the template is undefined or empty.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getCompilationUnitContent(IJavaScriptUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
- return getCompilationUnitContent(cu, getFileComment(cu, lineDelimiter), typeComment, typeContent, lineDelimiter);
- }
-
- /**
- * Returns the content for a new compilation unit using the 'new JavaScript file' code template.
- * @param cu The compilation unit to create the source for. The compilation unit does not need to exist.
- * @param fileComment The file comment to be used when the code template contains a <i>${filecomment}</i> variable. Can be <code>null</code> if
- * no comment should be added.
- * @param typeComment The comment for the type to be created. Used when the code template contains a <i>${typecomment}</i> variable. Can be <code>null</code> if
- * no comment should be added.
- * @param typeContent The code of the type, including type declaration and body.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the template is undefined or empty.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getCompilationUnitContent(IJavaScriptUnit cu, String fileComment, String typeComment, String typeContent, String lineDelimiter) throws CoreException {
- return StubUtility.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
- }
-
- /**
- * Returns the content for a new file comment using the 'file comment' code template. The returned content is unformatted and is not indented.
- * @param cu The compilation unit to add the comment to. The compilation unit does not need to exist.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getFileComment(IJavaScriptUnit cu, String lineDelimiter) throws CoreException {
- return StubUtility.getFileComment(cu, lineDelimiter);
- }
-
- /**
- * Returns the content for a new type comment using the 'type comment' code template. The returned content is unformatted and is not indented.
- * @param cu The compilation unit where the type is contained. The compilation unit does not need to exist.
- * @param typeQualifiedName The name of the type to which the comment is added. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getTypeComment(IJavaScriptUnit cu, String typeQualifiedName, String lineDelimiter) throws CoreException {
- return StubUtility.getTypeComment(cu, typeQualifiedName, lineDelimiter);
- }
-
- /**
- * Returns the content of a new new type body using the 'type body' code templates. The returned content is unformatted and is not indented.
- * @param typeKind The type kind ID of the body template. Valid values are {@link #CLASS_BODY_TEMPLATE_ID}, {@link #INTERFACE_BODY_TEMPLATE_ID},
- * {@link #ENUM_BODY_TEMPLATE_ID} and {@link #ANNOTATION_BODY_TEMPLATE_ID}.
- * @param cu The compilation unit where the type is contained. The compilation unit does not need to exist.
- * @param typeName The name of the type(for embedding in the template as a user variable).
- * @param lineDelim The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getTypeBody(String typeKind, IJavaScriptUnit cu, String typeName, String lineDelim) throws CoreException {
- return StubUtility.getTypeBody(typeKind, cu, typeName, lineDelim);
- }
-
- /**
- * Returns the content for a new field comment using the 'field comment' code template. The returned content is unformatted and is not indented.
- * @param cu The compilation unit where the field is contained. The compilation unit does not need to exist.
- * @param typeName The name of the field declared type.
- * @param fieldName The name of the field to which the comment is added.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the new content or <code>null</code> if the code template is undefined or empty. The returned content is unformatted and is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getFieldComment(IJavaScriptUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException {
- return StubUtility.getFieldComment(cu, typeName, fieldName, lineDelimiter);
- }
-
- /**
- * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method).
- * <code>null</code> is returned if the template is empty.
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param decl The FunctionDeclaration AST node that will be added as new
- * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve.
- * See {@link org.eclipse.wst.jsdt.core.dom.AST#newFunctionDeclaration()} for how to create such a node.
- * @param overridden The binding of the method to which to add an "@see" link or
- * <code>null</code> if no link should be created.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the generated method comment or <code>null</code> if the
- * code template is empty. The returned content is unformatted and not indented (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getMethodComment(IJavaScriptUnit cu, String declaringTypeName, FunctionDeclaration decl, IFunctionBinding overridden, String lineDelimiter) throws CoreException {
- if (overridden != null) {
- overridden= overridden.getMethodDeclaration();
- String declaringClassQualifiedName= overridden.getDeclaringClass().getQualifiedName();
- String linkToMethodName= overridden.getName();
- String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(overridden);
- return StubUtility.getMethodComment(cu, declaringTypeName, decl, overridden.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, false, lineDelimiter);
- } else {
- return StubUtility.getMethodComment(cu, declaringTypeName, decl, false, null, null, null, false, lineDelimiter);
- }
- }
-
- /**
- * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method).
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- * <p>Exception types and return type are in signature notation. e.g. a source method declared as <code>public void foo(String text, int length)</code>
- * would return the array <code>{"QString;","I"}</code> as parameter types. See {@link org.eclipse.wst.jsdt.core.Signature}.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName Name of the method.
- * @param paramNames Names of the parameters for the method.
- * @param excTypeSig Thrown exceptions (Signature notation).
- * @param retTypeSig Return type (Signature notation) or <code>null</code>
- * for constructors.
- * @param overridden The method that will be overridden by the created method or
- * <code>null</code> for non-overriding methods. If not <code>null</code>, the method must exist.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed comment or <code>null</code> if
- * the comment code template is empty. The returned content is unformatted and not indented (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getMethodComment(IJavaScriptUnit cu, String declaringTypeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IFunction overridden, String lineDelimiter) throws CoreException {
- return StubUtility.getMethodComment(cu, declaringTypeName, methodName, paramNames, excTypeSig, retTypeSig, overridden, false, lineDelimiter);
- }
-
- /**
- * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method).
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param method The method to be documented. The method must exist.
- * @param overridden The method that will be overridden by the created method or
- * <code>null</code> for non-overriding methods. If not <code>null</code>, the method must exist.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed comment or <code>null</code> if
- * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getMethodComment(IFunction method, IFunction overridden, String lineDelimiter) throws CoreException {
- String retType= method.getReturnType();
- String[] paramNames= method.getParameterNames();
-
- String typeName = (method.getDeclaringType()!=null) ? method.getDeclaringType().getElementName() : ""; //$NON-NLS-1$
- return StubUtility.getMethodComment(method.getJavaScriptUnit(), typeName,
- method.getElementName(), paramNames, new String[0], retType, overridden, false, lineDelimiter);
- }
-
- /**
- * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method).
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
-
- * @param decl The FunctionDeclaration AST node that will be added as new
- * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve.
- * See {@link org.eclipse.wst.jsdt.core.dom.AST#newFunctionDeclaration()} for how to create such a node.
- * @param isDeprecated If set, the method is deprecated
- * @param overriddenMethodName If a method is overridden, the simple name of the overridden method, or <code>null</code> if no method is overridden.
- * @param overriddenMethodDeclaringTypeName If a method is overridden, the fully qualified type name of the overridden method's declaring type,
- * or <code>null</code> if no method is overridden.
- * @param overriddenMethodParameterTypeNames If a method is overridden, the fully qualified parameter type names of the overridden method,
- * or <code>null</code> if no method is overridden.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed comment or <code>null</code> if
- * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
-
- public static String getMethodComment(IJavaScriptUnit cu, String declaringTypeName, FunctionDeclaration decl, boolean isDeprecated, String overriddenMethodName, String overriddenMethodDeclaringTypeName, String[] overriddenMethodParameterTypeNames, String lineDelimiter) throws CoreException {
- return StubUtility.getMethodComment(cu, declaringTypeName, decl, isDeprecated, overriddenMethodName, overriddenMethodDeclaringTypeName, overriddenMethodParameterTypeNames, false, lineDelimiter);
- }
-
- /**
- * Returns the content of the body for a method or constructor using the method body templates.
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName Name of the method.
- * @param isConstructor Defines if the created body is for a constructor.
- * @param bodyStatement The code to be entered at the place of the variable ${body_statement}.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed body content or <code>null</code> if
- * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- */
- public static String getMethodBodyContent(IJavaScriptUnit cu, String declaringTypeName, String methodName, boolean isConstructor, String bodyStatement, String lineDelimiter) throws CoreException {
- return StubUtility.getMethodBodyContent(isConstructor, cu.getJavaScriptProject(), declaringTypeName, methodName, bodyStatement, lineDelimiter);
- }
-
- /**
- * Returns the content of body for a getter method using the getter method body template.
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName The name of the getter method.
- * @param fieldName The name of the field to get in the getter method, corresponding to the template variable for ${field}.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed body content or <code>null</code> if
- * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getGetterMethodBodyContent(IJavaScriptUnit cu, String declaringTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException {
- return StubUtility.getGetterMethodBodyContent(cu.getJavaScriptProject(), declaringTypeName, methodName, fieldName, lineDelimiter);
- }
-
- /**
- * Returns the content of body for a setter method using the setter method body template.
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName The name of the setter method.
- * @param fieldName The name of the field to be set in the setter method, corresponding to the template variable for ${field}.
- * @param paramName The name of the parameter passed to the setter method, corresponding to the template variable for $(param).
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the constructed body content or <code>null</code> if
- * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required).
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getSetterMethodBodyContent(IJavaScriptUnit cu, String declaringTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException {
- return StubUtility.getSetterMethodBodyContent(cu.getJavaScriptProject(), declaringTypeName, methodName, fieldName, paramName, lineDelimiter);
- }
-
- /**
- * Returns the comment for a getter method using the getter comment template.
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName Name of the method.
- * @param fieldName Name of the field to get.
- * @param fieldType The type of the field to get.
- * @param bareFieldName The field name without prefix or suffix.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the generated getter comment or <code>null</code> if the
- * code template is empty. The returned content is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getGetterComment(IJavaScriptUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException {
- return StubUtility.getGetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, bareFieldName, lineDelimiter);
- }
-
- /**
- * Returns the comment for a setter method using the setter method body template.
- * <code>null</code> is returned if the template is empty.
- * <p>The returned string is unformatted and not indented.
- *
- * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
- * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
- * types names (dot separated). See {@link org.eclipse.wst.jsdt.core.IType#getTypeQualifiedName(char)}.
- * @param methodName Name of the method.
- * @param fieldName Name of the field that is set.
- * @param fieldType The type of the field that is to set.
- * @param paramName The name of the parameter that used to set.
- * @param bareFieldName The field name without prefix or suffix.
- * @param lineDelimiter The line delimiter to be used.
- * @return Returns the generated setter comment or <code>null</code> if the
- * code template is empty. The returned comment is not indented.
- * @throws CoreException Thrown when the evaluation of the code template fails.
- *
- */
- public static String getSetterComment(IJavaScriptUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException {
- return StubUtility.getSetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, paramName, bareFieldName, lineDelimiter);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeStyleConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeStyleConfiguration.java
deleted file mode 100644
index f7468b0e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/CodeStyleConfiguration.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.regex.Pattern;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class CodeStyleConfiguration {
-
- private static final Pattern SEMICOLON_PATTERN= Pattern.compile(";"); //$NON-NLS-1$
-
- private CodeStyleConfiguration() {
- // do not instantiate and subclass
- }
-
-
- /**
- * Returns a {@link ImportRewrite} using {@link ImportRewrite#create(IJavaScriptUnit, boolean)} and
- * configures the rewriter with the settings as specified in the JDT UI preferences.
- * <p>
- *
- * @param cu the compilation unit to create the rewriter on
- * @param restoreExistingImports specifies if the existing imports should be kept or removed.
- * @return the new rewriter configured with the settings as specified in the JDT UI preferences.
- * @throws JavaScriptModelException thrown when the compilation unit could not be accessed.
- *
- * @see ImportRewrite#create(IJavaScriptUnit, boolean)
- */
- public static ImportRewrite createImportRewrite(IJavaScriptUnit cu, boolean restoreExistingImports) throws JavaScriptModelException {
- return configureImportRewrite(ImportRewrite.create(cu, restoreExistingImports));
- }
-
- /**
- * Returns a {@link ImportRewrite} using {@link ImportRewrite#create(JavaScriptUnit, boolean)} and
- * configures the rewriter with the settings as specified in the JDT UI preferences.
- *
- * @param astRoot the AST root to create the rewriter on
- * @param restoreExistingImports specifies if the existing imports should be kept or removed.
- * @return the new rewriter configured with the settings as specified in the JDT UI preferences.
- *
- * @see ImportRewrite#create(JavaScriptUnit, boolean)
- */
- public static ImportRewrite createImportRewrite(JavaScriptUnit astRoot, boolean restoreExistingImports) {
- return configureImportRewrite(ImportRewrite.create(astRoot, restoreExistingImports));
- }
-
- private static ImportRewrite configureImportRewrite(ImportRewrite rewrite) {
- IJavaScriptProject project= rewrite.getCompilationUnit().getJavaScriptProject();
- String order= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_IMPORTORDER, project);
- rewrite.setImportOrder(SEMICOLON_PATTERN.split(order, 0));
-
- String thres= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, project);
- try {
- int num= Integer.parseInt(thres);
- if (num == 0)
- num= 1;
- rewrite.setOnDemandImportThreshold(num);
- } catch (NumberFormatException e) {
- // ignore
- }
- String thresStatic= PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_STATIC_ONDEMANDTHRESHOLD, project);
- try {
- int num= Integer.parseInt(thresStatic);
- if (num == 0)
- num= 1;
- rewrite.setStaticOnDemandImportThreshold(num);
- } catch (NumberFormatException e) {
- // ignore
- }
- return rewrite;
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IContextMenuConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IContextMenuConstants.java
deleted file mode 100644
index 18b77127..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IContextMenuConstants.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.ui.navigator.ICommonMenuConstants;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IContextMenuConstants {
-
-
- /**
- * Type hierarchy view part: pop-up menu target ID for type hierarchy viewer
- * (value <code>"org.eclipse.wst.jsdt.ui.TypeHierarchy.typehierarchy"</code>).
- *
- *
- */
- public static final String TARGET_ID_HIERARCHY_VIEW= JavaScriptUI.ID_TYPE_HIERARCHY + ".typehierarchy"; //$NON-NLS-1$
-
- /**
- * Type hierarchy view part: pop-up menu target ID for supertype hierarchy viewer
- * (value <code>"org.eclipse.wst.jsdt.ui.TypeHierarchy.supertypes"</code>).
- *
- *
- */
- public static final String TARGET_ID_SUPERTYPES_VIEW= JavaScriptUI.ID_TYPE_HIERARCHY + ".supertypes"; //$NON-NLS-1$
-
- /**
- * Type hierarchy view part: Pop-up menu target ID for the subtype hierarchy viewer
- * (value <code>"org.eclipse.wst.jsdt.ui.TypeHierarchy.subtypes"</code>).
- *
- *
- */
- public static final String TARGET_ID_SUBTYPES_VIEW= JavaScriptUI.ID_TYPE_HIERARCHY + ".subtypes"; //$NON-NLS-1$
-
- /**
- * Type hierarchy view part: pop-up menu target ID for the member viewer
- * (value <code>"org.eclipse.wst.jsdt.ui.TypeHierarchy.members"</code>).
- *
- *
- */
- public static final String TARGET_ID_MEMBERS_VIEW= JavaScriptUI.ID_TYPE_HIERARCHY + ".members"; //$NON-NLS-1$
-
-
- /**
- * Pop-up menu: name of group for goto actions (value <code>"group.goto"</code>).
- * <p>
- * Examples for open actions are:
- * <ul>
- * <li>Go Into</li>
- * <li>Go To</li>
- * </ul>
- * </p>
- */
- public static final String GROUP_GOTO= ICommonMenuConstants.GROUP_GOTO;
- /**
- * Pop-up menu: name of group for open actions (value <code>"group.open"</code>).
- * <p>
- * Examples for open actions are:
- * <ul>
- * <li>Open To</li>
- * <li>Open With</li>
- * </ul>
- * </p>
- */
- public static final String GROUP_OPEN= ICommonMenuConstants.GROUP_OPEN;
-
- /**
- * Pop-up menu: name of group for show actions (value <code>"group.show"</code>).
- * <p>
- * Examples for show actions are:
- * <ul>
- * <li>Show in Navigator</li>
- * <li>Show in Type Hierarchy</li>
- * </ul>
- * </p>
- */
- public static final String GROUP_SHOW= ICommonMenuConstants.GROUP_SHOW;
-
- /**
- * Pop-up menu: name of group for new actions (value <code>"group.new"</code>).
- * <p>
- * Examples for new actions are:
- * <ul>
- * <li>Create new class</li>
- * <li>Create new interface</li>
- * </ul>
- * </p>
- */
- public static final String GROUP_NEW= ICommonMenuConstants.GROUP_NEW;
-
- /**
- * Pop-up menu: name of group for build actions (value <code>"group.build"</code>).
- */
- public static final String GROUP_BUILD= ICommonMenuConstants.GROUP_BUILD;
-
- /**
- * Pop-up menu: name of group for reorganize actions (value <code>"group.reorganize"</code>).
- */
- public static final String GROUP_REORGANIZE= ICommonMenuConstants.GROUP_REORGANIZE;
-
- /**
- * Pop-up menu: name of group for code generation actions (
- * value <code>"group.generate"</code>).
- */
- public static final String GROUP_GENERATE= ICommonMenuConstants.GROUP_GENERATE;
-
- /**
- * Pop-up menu: name of group for source actions. This is an alias for
- * <code>GROUP_GENERATE</code> to be more consistent with main menu
- * bar structure.
- *
- *
- */
- public static final String GROUP_SOURCE= ICommonMenuConstants.GROUP_SOURCE;
-
- /**
- * Pop-up menu: name of group for search actions (value <code>"group.search"</code>).
- */
- public static final String GROUP_SEARCH= ICommonMenuConstants.GROUP_SEARCH;
-
- /**
- * Pop-up menu: name of group for additional actions (value <code>"additions"</code>).
- */
- public static final String GROUP_ADDITIONS= ICommonMenuConstants.GROUP_ADDITIONS;
-
- /**
- * Pop-up menu: name of group for viewer setup actions (value <code>"group.viewerSetup"</code>).
- */
- public static final String GROUP_VIEWER_SETUP= ICommonMenuConstants.GROUP_VIEWER_SETUP;
-
- /**
- * Pop-up menu: name of group for properties actions (value <code>"group.properties"</code>).
- */
- public static final String GROUP_PROPERTIES= ICommonMenuConstants.GROUP_PROPERTIES;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IDocumentationReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IDocumentationReader.java
deleted file mode 100644
index 8a509ef0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IDocumentationReader.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import java.io.Reader;
-
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- *
- * Provisional API: This class/interface is part of an interim API that is
- * still under development and expected to change significantly before
- * reaching stability. It is being made available at this early stage to
- * solicit feedback from pioneering adopters on the understanding that any
- * code that uses this API will almost certainly be broken (repeatedly) as the
- * API evolves.
- *
- * Implementors of this interface retrieve raw and formatted documentation for
- * specific JavaScript elements
- */
-public interface IDocumentationReader {
-
- public boolean appliesTo(IMember member);
- public boolean appliesTo(ILocalVariable declaration);
-
- public Reader getDocumentation2HTMLReader(Reader contentReader);
-
- public Reader getContentReader(IMember member, boolean allowInherited) throws JavaScriptModelException;
- public Reader getContentReader(ILocalVariable declaration, boolean allowInherited) throws JavaScriptModelException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java
deleted file mode 100644
index 17f6826b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IJavaScriptElementSearchConstants {
-
- /**
- * Search scope constant indicating that classes should be considered.
- * Used when opening certain kinds of selection dialogs.
- */
- public static final int CONSIDER_CLASSES= 1 << 1;
-
- /**
- * Search scope constant indicating that interfaces should be considered.
- * Used when opening certain kinds of selection dialogs.
- */
- public static final int CONSIDER_INTERFACES= 1 << 2;
-
- /**
- * Search scope constant (bit mask) indicating that binaries should be considered.
- * Used when opening certain kinds of selection dialogs.
- */
- public static final int CONSIDER_BINARIES= 1 << 3;
-
- /**
- * Search scope constant (bit mask) indicating that external JARs should be considered.
- * Used when opening certain kinds of selection dialogs.
- */
- public static final int CONSIDER_EXTERNAL_JARS= 1 << 4;
-
- /**
- * Search scope constant (bit mask) indicating that required projects should be considered.
- * Used when opening certain kinds of selection dialogs.
- *
- *
- */
- public static final int CONSIDER_REQUIRED_PROJECTS= 1 << 5;
-
- /**
- * Search scope constant indicating that annotation types should be considered.
- * Used when opening certain kinds of selection dialogs.
- *
- *
- */
- public static final int CONSIDER_ANNOTATION_TYPES= 1 << 6;
-
- /**
- * Search scope constant indicating that enums should be considered.
- * Used when opening certain kinds of selection dialogs.
- *
- *
- */
- public static final int CONSIDER_ENUMS= 1 << 7;
-
- /**
- * Search scope constant indicating that classes, interfaces, annotations
- * and enums should be considered.
- *
- *
- */
- public static final int CONSIDER_ALL_TYPES= 1 << 8;
-
- /**
- * Search scope constant indicating that only classes and interfaces
- * should be considered.
- *
- *
- */
- public static final int CONSIDER_CLASSES_AND_INTERFACES= 1 << 9;
-
- /**
- * Search scope constant indicating that only classes and enumeration types
- * should be considered.
- *
- *
- */
- public static final int CONSIDER_CLASSES_AND_ENUMS= 1 << 10;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IPackagesViewPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IPackagesViewPart.java
deleted file mode 100644
index b51416ca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IPackagesViewPart.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ui.IViewPart;
-
-/**
-*
-* Provisional API: This class/interface is part of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public interface IPackagesViewPart extends IViewPart {
- /**
- * Selects and reveals the given element in this packages view.
- * The tree will be expanded as needed to show the element.
- *
- * @param element the element to be revealed
- */
- void selectAndReveal(Object element);
-
- /**
- * Returns the TreeViewer shown in the Packages view.
- *
- * @return the tree viewer used in the Packages view
- *
- *
- */
- TreeViewer getTreeViewer();
-
- /**
- * Returns whether this Packages view's selection automatically tracks the active editor.
- *
- * @return <code>true</code> if linking is enabled, <code>false</code> if not
- *
- */
- boolean isLinkingEnabled();
-
- /**
- * Sets whether this Packages view's selection automatically tracks the active editor.
- *
- * @param enabled <code>true</code> to enable, <code>false</code> to disable
- *
- */
- void setLinkingEnabled(boolean enabled);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java
deleted file mode 100644
index 4ce7efe5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java
+++ /dev/null
@@ -1,317 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * Standard images provided by the JavaScript UI plug-in. This class offers access to the
- * standard images in two forms:
- * <ul>
- * <li>Use <code>ISharedImages.getImage(IMG_OBJS_<i>FOO</i>)</code>
- * to access the shared standard <code>Image</code> object (caller must not
- * dispose of image).</li>
- * <li>Use <code>ISharedImages.getImageDescriptor(IMG_OBJS_<i>FOO</i>)</code>
- * to access the standard <code>ImageDescriptor</code> object (caller is
- * responsible for disposing of any <code>Image</code> objects it creates using
- * this descriptor).</li>
- * </ul>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
-
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface ISharedImages {
-
- /**
- * Key to access the shared image or image descriptor for a JavaScript compilation unit.
- */
- public static final String IMG_OBJS_CUNIT= JavaPluginImages.IMG_OBJS_CUNIT;
-
- /**
- * Key to access the shared image or image descriptor for a JavaScript class file.
- */
- public static final String IMG_OBJS_CFILE= JavaPluginImages.IMG_OBJS_CFILE;
-
- /**
- * Key to access the shared image or image descriptor for a JAR archive.
- */
- public static final String IMG_OBJS_JAR= JavaPluginImages.IMG_OBJS_JAR;
-
- /**
- * Key to access the shared image or image descriptor for a JAR with source.
- *
- */
- public static final String IMG_OBJS_JAR_WITH_SOURCE= JavaPluginImages.IMG_OBJS_JAR_WSRC;
-
- /**
- * Key to access the shared image or image descriptor for external archives.
- *
- */
- public static final String IMG_OBJS_EXTERNAL_ARCHIVE= JavaPluginImages.IMG_OBJS_EXTJAR;
-
- /**
- * Key to access the shared image or image descriptor for external archives with source.
- *
- */
- public static final String IMG_OBJS_EXTERNAL_ARCHIVE_WITH_SOURCE= JavaPluginImages.IMG_OBJS_EXTJAR_WSRC;
-
- /**
- * Key to access the shared image or image descriptor for a classpath variable entry.
- *
- */
- public static final String IMG_OBJS_CLASSPATH_VAR_ENTRY= JavaPluginImages.IMG_OBJS_ENV_VAR;
-
- /**
- * Key to access the shared image or image descriptor for a library (class path container).
- *
- */
- public static final String IMG_OBJS_LIBRARY= JavaPluginImages.IMG_OBJS_LIBRARY;
-
- /**
- * Key to access the shared image or image descriptor for a package fragment root.
- *
- */
- public static final String IMG_OBJS_PACKFRAG_ROOT= JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT;
-
- /**
- * Key to access the shared image or image descriptor for a package.
- */
- public static final String IMG_OBJS_PACKAGE= JavaPluginImages.IMG_OBJS_PACKAGE;
-
- /**
- * Key to access the shared image or image descriptor for an empty package.
- *
- */
- public static final String IMG_OBJS_EMPTY_PACKAGE= JavaPluginImages.IMG_OBJS_EMPTY_PACKAGE;
-
- /**
- * Key to access the shared image or image descriptor for a logical package.
- *
- */
- public static final String IMG_OBJS_LOGICAL_PACKAGE= JavaPluginImages.IMG_OBJS_LOGICAL_PACKAGE;
-
- /**
- * Key to access the shared image or image descriptor for an empty logical package.
- *
- */
- public static final String IMG_OBJS_EMPTY_LOGICAL_PACKAGE= JavaPluginImages.IMG_OBJS_EMPTY_LOGICAL_PACKAGE;
-
- /**
- * Key to access the shared image or image descriptor for a class.
- */
- public static final String IMG_OBJS_CLASS= JavaPluginImages.IMG_OBJS_CLASS;
-
- /**
- * Key to access the shared image or image descriptor for a class with default visibility.
- *
- */
- public static final String IMG_OBJS_CLASS_DEFAULT= JavaPluginImages.IMG_OBJS_CLASS_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a public inner class.
- *
- */
- public static final String IMG_OBJS_INNER_CLASS_PUBLIC= JavaPluginImages.IMG_OBJS_INNER_CLASS_PUBLIC;
-
- /**
- * Key to access the shared image or image descriptor for a inner class with default visibility.
- *
- */
- public static final String IMG_OBJS_INNER_CLASS_DEFAULT= JavaPluginImages.IMG_OBJS_INNER_CLASS_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a protected inner class.
- *
- */
- public static final String IMG_OBJS_INNER_CLASS_PROTECTED= JavaPluginImages.IMG_OBJS_INNER_CLASS_PROTECTED;
-
- /**
- * Key to access the shared image or image descriptor for a private inner class.
- *
- */
- public static final String IMG_OBJS_INNER_CLASS_PRIVATE= JavaPluginImages.IMG_OBJS_INNER_CLASS_PRIVATE;
-
- /**
- * Key to access the shared image or image descriptor for an interface.
- */
- public static final String IMG_OBJS_INTERFACE= JavaPluginImages.IMG_OBJS_INTERFACE;
-
- /**
- * Key to access the shared image or image descriptor for an interface with default visibility.
- *
- */
- public static final String IMG_OBJS_INTERFACE_DEFAULT= JavaPluginImages.IMG_OBJS_INTERFACE_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a public inner interface.
- *
- */
- public static final String IMG_OBJS_INNER_INTERFACE_PUBLIC= JavaPluginImages.IMG_OBJS_INNER_INTERFACE_PUBLIC;
-
- /**
- * Key to access the shared image or image descriptor for an inner interface with default visibility.
- *
- */
- public static final String IMG_OBJS_INNER_INTERFACE_DEFAULT= JavaPluginImages.IMG_OBJS_INNER_INTERFACE_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a protected inner interface.
- *
- */
- public static final String IMG_OBJS_INNER_INTERFACE_PROTECTED= JavaPluginImages.IMG_OBJS_INNER_INTERFACE_PROTECTED;
-
- /**
- * Key to access the shared image or image descriptor for a private inner interface.
- *
- */
- public static final String IMG_OBJS_INNER_INTERFACE_PRIVATE= JavaPluginImages.IMG_OBJS_INNER_INTERFACE_PRIVATE;
-
- /** Key to access the shared image or image descriptor for a package declaration. */
- public static final String IMG_OBJS_PACKDECL= JavaPluginImages.IMG_OBJS_PACKDECL;
-
- /** Key to access the shared image or image descriptor for an import container. */
- public static final String IMG_OBJS_IMPCONT= JavaPluginImages.IMG_OBJS_IMPCONT;
-
- /** Key to access the shared image or image descriptor for an import statement. */
- public static final String IMG_OBJS_IMPDECL= JavaPluginImages.IMG_OBJS_IMPDECL;
-
- /** Key to access the shared image or image descriptor for a public member. */
- public static final String IMG_OBJS_PUBLIC= JavaPluginImages.IMG_MISC_PUBLIC;
-
- /** Key to access the shared image or image descriptor for a protected member. */
- public static final String IMG_OBJS_PROTECTED= JavaPluginImages.IMG_MISC_PROTECTED;
-
- /** Key to access the shared image or image descriptor for a private member. */
- public static final String IMG_OBJS_PRIVATE= JavaPluginImages.IMG_MISC_PRIVATE;
-
- /** Key to access the shared image or image descriptor for class members with default visibility. */
- public static final String IMG_OBJS_DEFAULT= JavaPluginImages.IMG_MISC_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a public field.
- *
- */
- public static final String IMG_FIELD_PUBLIC= JavaPluginImages.IMG_FIELD_PUBLIC;
-
- /**
- * Key to access the shared image or image descriptor for a protected field.
- *
- */
- public static final String IMG_FIELD_PROTECTED= JavaPluginImages.IMG_FIELD_PROTECTED;
-
- /**
- * Key to access the shared image or image descriptor for a private field.
- *
- */
- public static final String IMG_FIELD_PRIVATE= JavaPluginImages.IMG_FIELD_PRIVATE;
-
- /**
- * Key to access the shared image or image descriptor for a field with default visibility.
- *
- */
- public static final String IMG_FIELD_DEFAULT= JavaPluginImages.IMG_FIELD_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a local variable.
- *
- */
- public static final String IMG_OBJS_LOCAL_VARIABLE= JavaPluginImages.IMG_OBJS_LOCAL_VARIABLE;
-
- /**
- * Key to access the shared image or image descriptor for a enum type.
- *
- */
- public static final String IMG_OBJS_ENUM= JavaPluginImages.IMG_OBJS_ENUM;
-
- /**
- * Key to access the shared image or image descriptor for a enum type
- * with default visibility.
- *
- */
- public static final String IMG_OBJS_ENUM_DEFAULT= JavaPluginImages.IMG_OBJS_ENUM_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a enum type
- * with protected visibility.
- *
- */
- public static final String IMG_OBJS_ENUM_PROTECTED= JavaPluginImages.IMG_OBJS_ENUM_PROTECTED;
-
- /**
- * Key to access the shared image or image descriptor for a enum type
- * with private visibility.
- *
- */
- public static final String IMG_OBJS_ENUM_PRIVATE= JavaPluginImages.IMG_OBJS_ENUM_PRIVATE;
-
- /**
- * Key to access the shared image or image descriptor for a annotation type.
- *
- */
- public static final String IMG_OBJS_ANNOTATION= JavaPluginImages.IMG_OBJS_ANNOTATION;
-
- /**
- * Key to access the shared image or image descriptor for a annotation type
- * with default visibility.
- *
- */
- public static final String IMG_OBJS_ANNOTATION_DEFAULT= JavaPluginImages.IMG_OBJS_ANNOTATION_DEFAULT;
-
- /**
- * Key to access the shared image or image descriptor for a annotation type
- * with protected visibility.
- *
- */
- public static final String IMG_OBJS_ANNOTATION_PROTECTED= JavaPluginImages.IMG_OBJS_ANNOTATION_PROTECTED;
-
- /**
- * Key to access the shared image or image descriptor for a annotation type
- * with private visibility.
- *
- */
- public static final String IMG_OBJS_ANNOTATION_PRIVATE= JavaPluginImages.IMG_OBJS_ANNOTATION_PRIVATE;
-
- /**
- * Key to access the shared image or image descriptor for javadoc tags.
- *
- */
- public static final String IMG_OBJS_JAVADOCTAG= JavaPluginImages.IMG_OBJS_JAVADOCTAG;
-
- /**
- * Returns the shared image managed under the given key.
- * <p>
- * Note that clients <b>must not</b> dispose the image returned by this method.
- * </p>
- *
- * @param key the image key; one of the <code>IMG_OBJS_* </code> constants
- * @return the shared image managed under the given key, or <code>null</code>
- * if none
- */
- public Image getImage(String key);
-
- /**
- * Returns the image descriptor managed under the given key.
- *
- * @param key the image key; one of the <code>IMG_OBJS_* </code> constants
- * @return the image descriptor managed under the given key, or <code>null</code>
- * if none
- */
- public ImageDescriptor getImageDescriptor(String key);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ITypeHierarchyViewPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ITypeHierarchyViewPart.java
deleted file mode 100644
index fda34a09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ITypeHierarchyViewPart.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-
-import org.eclipse.ui.IViewPart;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-
-/**
- * The standard type hierarchy view presents a type hierarchy for a given input class
- * or interface. Visually, this view consists of a pair of viewers, one showing the type
- * hierarchy, the other showing the members of the type selected in the first.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- * @see JavaScriptUI#ID_TYPE_HIERARCHY
-
- *
-
- */
-public interface ITypeHierarchyViewPart extends IViewPart {
-
- /**
- * Constant used for the vertical view layout.
- *
- */
- public static final int VIEW_LAYOUT_VERTICAL= 0;
-
- /**
- * Constant used for the horizontal view layout.
- *
- */
- public static final int VIEW_LAYOUT_HORIZONTAL= 1;
-
- /**
- * Constant used for the single view layout (no members view)
- *
- */
- public static final int VIEW_LAYOUT_SINGLE= 2;
-
- /**
- * Constant used for the automatic view layout.
- *
- */
- public static final int VIEW_LAYOUT_AUTOMATIC= 3;
-
- /**
- * Constant used for the 'classic' type hierarchy mode.
- *
- */
- public static final int HIERARCHY_MODE_CLASSIC= 2;
-
- /**
- * Constant used for the super types hierarchy mode.
- *
- */
- public static final int HIERARCHY_MODE_SUPERTYPES= 0;
-
- /**
- * Constant used for the sub types hierarchy mode.
- *
- */
- public static final int HIERARCHY_MODE_SUBTYPES= 1;
-
- /**
- * Sets the input element of this type hierarchy view to a type.
- *
- * @param type the input element of this type hierarchy view, or <code>null</code>
- * to clear any input element
- * @deprecated use setInputElement instead
- */
- public void setInput(IType type);
-
- /**
- * Sets the input element of this type hierarchy view. The following input types are possible
- * <code>IMember</code> (types, methods, fields..), <code>IPackageFragment</code>, <code>IPackageFragmentRoot</code>
- * and <code>IJavaScriptProject</code>.
- *
- * @param element the input element of this type hierarchy view, or <code>null</code>
- * to clear any input
- *
- *
- */
- public void setInputElement(IJavaScriptElement element);
-
- /**
- * Returns the input element of this type hierarchy view.
- *
- * @return the input element, or <code>null</code> if no input element is set
- * @see #setInputElement(IJavaScriptElement)
- *
- *
- */
- public IJavaScriptElement getInputElement();
-
- /**
- * Locks the the members view and shows the selected members in the hierarchy.
- *
- * @param enabled If set, the members view will be locked and the selected members are shown in the hierarchy.
- *
- *
- */
- public void showMembersInHierarchy(boolean enabled);
-
- /**
- * If set, the lock mode is enabled.
- *
- * @return returns if the lock mode is enabled.
- *
- *
- */
- public boolean isShowMembersInHierarchy();
-
- /**
- * Specifies if type names are shown with the parent container's name.
- *
- * @param enabled if enabled, the hierarchy will also show the type container names
- *
- *
- */
- public void showQualifiedTypeNames(boolean enabled);
-
- /**
- * If set, type names are shown with the parent container's name.
- *
- * @return returns if type names are shown with the parent container's name.
- *
- *
- */
- public boolean isQualifiedTypeNamesEnabled();
-
- /**
- * Returns whether this type hierarchy view's selection automatically tracks the active editor.
- *
- * @return <code>true</code> if linking is enabled, <code>false</code> if not
- *
- *
- */
- public boolean isLinkingEnabled();
-
- /**
- * Sets whether this type hierarchy view's selection automatically tracks the active editor.
- *
- * @param enabled <code>true</code> to enable, <code>false</code> to disable
- *
- *
- */
- public void setLinkingEnabled(boolean enabled);
-
- /**
- * Sets the view layout. Valid inputs are {@link #VIEW_LAYOUT_VERTICAL}, {@link #VIEW_LAYOUT_HORIZONTAL}
- * {@link #VIEW_LAYOUT_SINGLE} and {@link #VIEW_LAYOUT_AUTOMATIC}.
- *
- * @param layout The layout to set
- *
- *
- */
- public void setViewLayout(int layout);
-
- /**
- * Returns the currently configured view layout. Possible layouts are {@link #VIEW_LAYOUT_VERTICAL}, {@link #VIEW_LAYOUT_HORIZONTAL}
- * {@link #VIEW_LAYOUT_SINGLE} and {@link #VIEW_LAYOUT_AUTOMATIC} but clients should also be able to handle yet unknown
- * layout.
- *
- * @return The layout currently set
- *
- *
- */
- public int getViewLayout();
-
- /**
- * Sets the hierarchy mode. Valid modes are {@link #HIERARCHY_MODE_SUBTYPES}, {@link #HIERARCHY_MODE_SUPERTYPES}
- * and {@link #HIERARCHY_MODE_CLASSIC}.
- *
- * @param mode The hierarchy mode to set
- *
- *
- */
- public void setHierarchyMode(int mode);
-
- /**
- * Returns the currently configured hierarchy mode. Possible modes are {@link #HIERARCHY_MODE_SUBTYPES}, {@link #HIERARCHY_MODE_SUPERTYPES}
- * and {@link #HIERARCHY_MODE_CLASSIC} but clients should also be able to handle yet unknown modes.
- *
- * @return The hierarchy mode currently set
- *
- *
- */
- public int getHierarchyMode();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManager.java
deleted file mode 100644
index 51836576..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManager.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- * Interface for accessing working copies of <code>IJavaScriptUnit</code>
- * objects. The original compilation unit is only given indirectly by means
- * of an <code>IEditorInput</code>. The life cycle is as follows:
- * <ul>
- * <li> <code>connect</code> creates and remembers a working copy of the
- * compilation unit which is encoded in the given editor input</li>
- * <li> <code>getWorkingCopy</code> returns the working copy remembered on
- * <code>connect</code></li>
- * <li> <code>disconnect</code> destroys the working copy remembered on
- * <code>connect</code></li>
- * </ul>
- * <p>
- * In order to provide backward compatibility for clients of <code>IWorkingCopyManager</code>, extension
- * interfaces are used to provide a means of evolution. The following extension interfaces
- * exist:
- * <ul>
- * <li> {@link org.eclipse.wst.jsdt.ui.IWorkingCopyManagerExtension} since version 2.1 introducing API
- * to set and remove the working copy for a given editor input.</li>
- * </ul>
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- * @see JavaScriptUI#getWorkingCopyManager()
- * @see org.eclipse.wst.jsdt.ui.IWorkingCopyManagerExtension
- */
-public interface IWorkingCopyManager {
-
- /**
- * Connects the given editor input to this manager. After calling
- * this method, a working copy will be available for the compilation unit encoded
- * in the given editor input (does nothing if there is no encoded compilation unit).
- *
- * @param input the editor input
- * @exception CoreException if the working copy cannot be created for the
- * compilation unit
- */
- void connect(IEditorInput input) throws CoreException;
-
- /**
- * Disconnects the given editor input from this manager. After calling
- * this method, a working copy for the compilation unit encoded
- * in the given editor input will no longer be available. Does nothing if there
- * is no encoded compilation unit, or if there is no remembered working copy for
- * the compilation unit.
- *
- * @param input the editor input
- */
- void disconnect(IEditorInput input);
-
- /**
- * Returns the working copy remembered for the compilation unit encoded in the
- * given editor input.
- *
- * @param input the editor input
- * @return the working copy of the compilation unit, or <code>null</code> if the
- * input does not encode an editor input, or if there is no remembered working
- * copy for this compilation unit
- */
- IJavaScriptUnit getWorkingCopy(IEditorInput input);
-
- /**
- * Shuts down this working copy manager. All working copies still remembered
- * by this manager are destroyed.
- */
- void shutdown();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManagerExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManagerExtension.java
deleted file mode 100644
index 76e193ee..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyManagerExtension.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-/**
- * Extension interface for {@link IWorkingCopyManager}.
- * <p>
- * Introduces API to set and remove the working copy for a given editor input.<p>
- * </p>
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface IWorkingCopyManagerExtension {
-
- /**
- * Sets the given working copy for the given editor input. If the given editor input
- * is not connected to this working copy manager, this call has no effect. <p>
- * This working copy manager does not assume the ownership of this working copy, i.e.,
- * the given working copy is not automatically be freed when this manager is shut down.
- *
- * @param input the editor input
- * @param workingCopy the working copy
- */
- void setWorkingCopy(IEditorInput input, IJavaScriptUnit workingCopy);
-
- /**
- * Removes the working copy set for the given editor input. If there is no
- * working copy set for this input or this input is not connected to this
- * working copy manager, this call has no effect.
- *
- * @param input the editor input
- */
- void removeWorkingCopy(IEditorInput input);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyProvider.java
deleted file mode 100644
index dc4ca061..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IWorkingCopyProvider.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-/**
- * Interface used for JavaScript element content providers to indicate that
- * the content provider can return working copy elements for members
- * below compilation units.
- *
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- * @see org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider
- *
-
- */
-public interface IWorkingCopyProvider {
-
- /**
- * Returns <code>true</code> if the content provider returns working
- * copy elements; otherwise <code>false</code> is returned.
- *
- * @return whether working copy elements are provided.
- */
- public boolean providesWorkingCopies();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java
deleted file mode 100644
index 77b9b4cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeHierarchy;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.util.SequenceReader;
-import org.eclipse.wst.jsdt.internal.core.MetadataFile;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocCommentReader;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.OAADocReader;
-
-/**
- * Helper needed to get the content of a Javadoc comment.
- *
- * <p>
- * This class is not intended to be subclassed or instantiated by clients.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JSdocContentAccess {
-
- public static final String EXTENSION_POINT= "documentationProvider"; //$NON-NLS-1$
-
- protected static final String TAG_DOCUMENTATIONPROVIDER = "documentationProvider"; //$NON-NLS-1$
- protected static final String ATTR_DOCUMENTATIONPROVIDER_CLASS = "class"; //$NON-NLS-1$
-
- private static IDocumentationReader[] docReaders;
-
- private JSdocContentAccess() {
- // do not instantiate
- }
-
- /**
- * Gets a reader for an IMember's Javadoc comment content from the source attachment.
- * The content does contain only the text from the comment without the Javadoc leading star characters.
- * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available.
- * @param member The member to get the Javadoc of.
- * @param allowInherited For methods with no (Javadoc) comment, the comment of the overridden class
- * is returned if <code>allowInherited</code> is <code>true</code>.
- * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
- * does not contain a Javadoc comment or if no source is available
- * @throws JavaScriptModelException is thrown when the elements javadoc can not be accessed
- */
- public static Reader getContentReader(IMember member, boolean allowInherited) throws JavaScriptModelException {
- List readers = new ArrayList(2);
- IDocumentationReader[] docReaders = getDocReaders(member);
- for (int i = 0; i < docReaders.length; i++) {
- Reader contentReader = docReaders[i].getContentReader(member, allowInherited);
- if(contentReader != null) {
- readers.add(contentReader);
- }
- }
-
- IOpenable openable = member.getOpenable();
- if (openable instanceof MetadataFile)
- {
- return new OAADocReader((MetadataFile)openable, member);
- }
-
- IBuffer buf= openable.getBuffer();
- if (buf != null) {
- try {
- // source or attachment found
- ISourceRange jsDocRange = member.getJSdocRange();
- if (jsDocRange == null && member.getElementType() == IJavaScriptElement.TYPE) {
- IFunction constructor = ((IType) member).getFunction(member.getElementName(), null);
- if (constructor.exists()) {
- jsDocRange = constructor.getJSdocRange();
- }
- }
- if (jsDocRange != null) {
- JavaDocCommentReader reader = new JavaDocCommentReader(buf, jsDocRange.getOffset(), jsDocRange.getOffset() + jsDocRange.getLength() - 1);
- if (!containsOnlyInheritDoc(reader, jsDocRange.getLength())) {
- reader.reset();
- readers.add(reader);
- }
- else if (allowInherited && (member.getElementType() == IJavaScriptElement.METHOD)) {
- Reader hierarchyDocReader = findDocInHierarchy((IFunction) member);
- if (hierarchyDocReader != null)
- readers.add(hierarchyDocReader);
- }
- }
- }
- catch (JavaScriptModelException e) {
- // doesn't exist
- }
- }
-
- if (!readers.isEmpty()) {
- if (readers.size() == 1)
- return (Reader) readers.get(0);
- return new SequenceReader((Reader[]) readers.toArray(new Reader[readers.size()]));
- }
- return null;
- }
-
- /**
- * Checks whether the given reader only returns
- * the inheritDoc tag.
- *
- * @param reader the reader
- * @param length the length of the underlying content
- * @return <code>true</code> if the reader only returns the inheritDoc tag
- *
- */
- private static boolean containsOnlyInheritDoc(Reader reader, int length) {
- char[] content= new char[length];
- try {
- reader.read(content, 0, length);
- } catch (IOException e) {
- return false;
- }
- return new String(content).trim().equals("{@inheritDoc}"); //$NON-NLS-1$
-
- }
-
- /**
- * Gets a reader for an IMember's Javadoc comment content from the source attachment.
- * and renders the tags in HTML.
- * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available.
- *
- * @param member the member to get the Javadoc of.
- * @param allowInherited for methods with no (Javadoc) comment, the comment of the overridden
- * class is returned if <code>allowInherited</code> is <code>true</code>
- * @param useAttachedJavadoc if <code>true</code> Javadoc will be extracted from attached Javadoc
- * if there's no source
- * @return a reader for the Javadoc comment content in HTML or <code>null</code> if the member
- * does not contain a Javadoc comment or if no source is available
- * @throws JavaScriptModelException is thrown when the elements Javadoc can not be accessed
- *
- */
- public static Reader getHTMLContentReader(IMember member, boolean allowInherited, boolean useAttachedJavadoc) throws JavaScriptModelException {
- Reader contentReader= getContentReader(member, allowInherited);
- if (contentReader != null)
- {
- IDocumentationReader[] docReaders = getDocReaders(member);
- if (docReaders.length > 0) {
- List htmlReaders = new ArrayList(docReaders.length);
- for (int i = 0; i < docReaders.length; i++) {
- Reader htmlReader = docReaders[i].getDocumentation2HTMLReader(contentReader);
- if (htmlReader != null) {
- htmlReaders.add(htmlReader);
- }
- }
- /* return any and all HTML readers in sequence */
- if (!htmlReaders.isEmpty()) {
-// htmlReaders.add(/*0, */new JavaDoc2HTMLTextReader(contentReader));
- return new SequenceReader((Reader[]) htmlReaders.toArray(new Reader[htmlReaders.size()]));
- }
- }
- return new JavaDoc2HTMLTextReader(contentReader);
- }
-
- if (useAttachedJavadoc && member.getOpenable().getBuffer() == null) { // only if no source available
- String s= member.getAttachedJavadoc(null);
- if (s != null)
- return new StringReader(s);
- }
- return null;
- }
-
- /**
- * Gets a reader for an ILocalDeclaration documentation comment content.
- * and renders the tags in HTML.
- * Returns <code>null</code> if the declaration does not contain a doc comment or if no source is available.
- *
- * @param variable the variable declaration to get the doc of.
- * @param allowInherited for methods with no (JSDoc) comment, the comment of the overridden
- * class is returned if <code>allowInherited</code> is <code>true</code>
- * @param useAttachedDoc if <code>true</code> JSDoc will be extracted from attached JSDoc
- * if there's no source
- * @return a reader for the JSDoc comment content in HTML or <code>null</code> if the member
- * does not contain a JSDoc comment or if no source is available
- * @throws JavaScriptModelException is thrown when the elements JSDoc can not be accessed
- *
- */
- public static Reader getHTMLContentReader(ILocalVariable variable, boolean allowInherited, boolean useAttachedDoc) throws JavaScriptModelException {
- Reader contentReader= getContentReader(variable, allowInherited);
- if (contentReader != null)
- {
- IDocumentationReader[] docReaders = new IDocumentationReader[0];//getDocReaders(declaration);
- if (docReaders.length > 0) {
- List htmlReaders = new ArrayList(docReaders.length);
- for (int i = 0; i < docReaders.length; i++) {
- Reader documentation2htmlReader = docReaders[i].getDocumentation2HTMLReader(contentReader);
- if (documentation2htmlReader != null) {
- htmlReaders.add(documentation2htmlReader);
- }
- }
- if (!htmlReaders.isEmpty()) {
- htmlReaders.add(/*0, */new JavaDoc2HTMLTextReader(contentReader));
- return new SequenceReader((Reader[]) htmlReaders.toArray(new Reader[htmlReaders.size()]));
- }
- }
- return new JavaDoc2HTMLTextReader(contentReader);
- }
-
- return null;
- }
-
-
-
- /**
- * Gets a reader for an ILocalDeclaration's doc comment content from the
- * source attachment. Returns <code>null</code> if the declaration does
- * not have a doc comment or if no source is available.
- *
- * @param declaration
- * The declaration to get the doc of.
- * @param allowInherited
- * For methods with no doc comment, the comment of the
- * overridden class is returned if <code>allowInherited</code>
- * is <code>true</code> and this is an argument.
- * @return Returns a reader for the doc comment content or
- * <code>null</code> if the declaration does not contain a doc
- * comment or if no source is available
- * @throws JavaScriptModelException
- * is thrown when the declaration's doc can not be accessed
- */
- public static Reader getContentReader(ILocalVariable declaration, boolean allowInherited) throws JavaScriptModelException {
- List readers = new ArrayList(2);
- IDocumentationReader[] docReaders = getDocReaders(declaration);
- for (int i = 0; i < docReaders.length; i++) {
- Reader contentReader = docReaders[i].getContentReader(declaration, allowInherited);
- if (contentReader != null) {
- readers.add(contentReader);
- }
- }
-
- if (!readers.isEmpty()) {
- if (readers.size() == 1)
- return (Reader) readers.get(0);
- return new SequenceReader((Reader[]) readers.toArray(new Reader[readers.size()]));
- }
- return null;
- }
-
- private static Reader findDocInHierarchy(IFunction method) throws JavaScriptModelException {
- IType type= method.getDeclaringType();
- if (type==null)
- return null;
- ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null);
-
- MethodOverrideTester tester= new MethodOverrideTester(type, hierarchy);
-
- IType[] superTypes= hierarchy.getAllSuperclasses(type);
- for (int i= 0; i < superTypes.length; i++) {
- IType curr= superTypes[i];
- IFunction overridden= tester.findOverriddenMethodInType(curr, method);
- if (overridden != null) {
- Reader reader= getContentReader(overridden, false);
- if (reader != null) {
- return reader;
- }
- }
- }
- return null;
- }
-
- private static IDocumentationReader[] getDocReaders(IMember member)
- {
- if (docReaders==null)
- loadExtensions();
- List readers = new ArrayList(docReaders.length);
- for (int i = 0; i < docReaders.length; i++) {
- if (docReaders[i].appliesTo(member)) {
- readers.add(docReaders[i]);
- }
- }
- return (IDocumentationReader[]) readers.toArray(new IDocumentationReader[readers.size()]);
- }
-
- private static IDocumentationReader[] getDocReaders(ILocalVariable declaration)
- {
- if (docReaders==null)
- loadExtensions();
- List readers = new ArrayList(docReaders.length);
- for (int i = 0; i < docReaders.length; i++) {
- if (docReaders[i].appliesTo(declaration)) {
- readers.add(docReaders[i]);
- }
- }
- return (IDocumentationReader[]) readers.toArray(new IDocumentationReader[readers.size()]);
- }
-
-
- private static void loadExtensions() {
- IExtensionRegistry registry = Platform.getExtensionRegistry();
- ArrayList extList = new ArrayList();
- if (registry != null) {
- IExtensionPoint point = registry.getExtensionPoint(
- JavaScriptPlugin.getPluginId(), EXTENSION_POINT);
-
- if (point != null) {
- IExtension[] extensions = point.getExtensions();
- for (int i = 0; i < extensions.length; i++) {
- IConfigurationElement[] elements = extensions[i]
- .getConfigurationElements();
- for (int j = 0; j < elements.length; j++) {
- try {
- IDocumentationReader docProvider = null;
- if (elements[j].getName().equals(TAG_DOCUMENTATIONPROVIDER)) {
- docProvider = (IDocumentationReader) elements[j]
- .createExecutableExtension(ATTR_DOCUMENTATIONPROVIDER_CLASS);
- }
-
- extList.add(docProvider);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
-
- docReaders = (IDocumentationReader[]) extList
- .toArray(new IDocumentationReader[extList.size()]);
- }
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaElementSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaElementSorter.java
deleted file mode 100644
index 1d08a2f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaElementSorter.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-
-
-/**
- * Sorter for JavaScript elements. Ordered by element category, then by element name.
- * Package fragment roots are sorted as ordered on the classpath.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaElementSorter extends ViewerSorter {
-
- private final JavaScriptElementComparator fComparator;
-
- /**
- * Constructor.
- */
- public JavaElementSorter() {
- super(null); // delay initialization of collator
- fComparator= new JavaScriptElementComparator();
- }
-
- /*
- * @see ViewerSorter#category
- */
- public int category(Object element) {
- return fComparator.category(element);
- }
-
- /*
- * @see ViewerSorter#compare
- */
- public int compare(Viewer viewer, Object e1, Object e2) {
- return fComparator.compare(viewer, e1, e2);
- }
-
- /**
- * Overrides {@link org.eclipse.jface.viewers.ViewerSorter#getCollator()}.
- * @deprecated The method is not intended to be used by clients.
- */
- public final java.text.Collator getCollator() {
- // kept in for API compatibility
- if (collator == null) {
- collator= java.text.Collator.getInstance();
- }
- return collator;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java
deleted file mode 100644
index cc245b42..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.viewers.ContentViewer;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.packageview.NamespaceGroup;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer;
-import org.eclipse.wst.jsdt.internal.ui.preferences.MembersOrderPreferenceCache;
-
-
-/**
- * Viewer comparator for JavaScript elements. Ordered by element category, then by element name.
- * Package fragment roots are sorted as ordered on the classpath.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptElementComparator extends ViewerComparator {
-
- private static final int PROJECTS= 1;
- private static final int PACKAGEFRAGMENTROOTS= 2;
- private static final int PACKAGEFRAGMENT= 3;
-
- private static final int JAVASCRIPTUNITS= 4;
- private static final int CLASSFILES= 5;
-
- private static final int RESOURCEFOLDERS= 7;
- private static final int RESOURCES= 8;
-
- private static final int IMPORT_CONTAINER= 11;
- private static final int IMPORT_DECLARATION= 12;
-
- // Includes all categories ordered using the OutlineSortOrderPage:
- // types, initializers, methods & fields
- private static final int MEMBERSOFFSET= 15;
-
- private static final int JAVAELEMENTS= 50;
- private static final int OTHERS= 51;
-
- private MembersOrderPreferenceCache fMemberOrderCache;
-
- /**
- * Constructor.
- */
- public JavaScriptElementComparator() {
- super(null); // delay initialization of collator
- fMemberOrderCache= JavaScriptPlugin.getDefault().getMemberOrderPreferenceCache();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerComparator#category(java.lang.Object)
- */
- public int category(Object element) {
- if (element instanceof IJavaScriptElement) {
- try {
- IJavaScriptElement je= (IJavaScriptElement) element;
-
- switch (je.getElementType()) {
- case IJavaScriptElement.METHOD:
- {
- IFunction method= (IFunction) je;
- if (method.isConstructor()) {
- return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
- }
- int flags= method.getFlags();
- if (Flags.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX);
- }
- case IJavaScriptElement.FIELD :
- {
- int flags= ((IField) je).getFlags();
- if (Flags.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX);
- }
- case IJavaScriptElement.INITIALIZER :
- {
- int flags= ((IInitializer) je).getFlags();
- if (Flags.isStatic(flags))
- return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX);
- else
- return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX);
- }
- case IJavaScriptElement.TYPE :
- return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX);
- case IJavaScriptElement.IMPORT_CONTAINER :
- return IMPORT_CONTAINER;
- case IJavaScriptElement.IMPORT_DECLARATION :
- return IMPORT_DECLARATION;
- case IJavaScriptElement.PACKAGE_FRAGMENT :
- return PACKAGEFRAGMENT;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT :
- return PACKAGEFRAGMENTROOTS;
- case IJavaScriptElement.JAVASCRIPT_PROJECT :
- return PROJECTS;
- case IJavaScriptElement.CLASS_FILE :
- return CLASSFILES;
- case IJavaScriptElement.JAVASCRIPT_UNIT :
-// return JAVASCRIPTUNITS;
- return RESOURCES;
- }
-
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist())
- JavaScriptPlugin.log(e);
- }
- return JAVAELEMENTS;
- } else if (element instanceof IFile) {
- return RESOURCES;
- } else if (element instanceof IProject) {
- return PROJECTS;
- } else if (element instanceof IContainer) {
- return RESOURCEFOLDERS;
- } else if (element instanceof IJarEntryResource) {
- if (((IJarEntryResource) element).isFile()) {
- return RESOURCES;
- }
- return RESOURCEFOLDERS;
- } else if (element instanceof PackageFragmentRootContainer) {
- return PACKAGEFRAGMENTROOTS;
- } else if (element instanceof ProjectLibraryRoot) {
- return PROJECTS;
- } else if (element instanceof NamespaceGroup) {
- return PROJECTS;
- }
-
- return OTHERS;
- }
-
- private int getMemberCategory(int kind) {
- int offset= fMemberOrderCache.getCategoryIndex(kind);
- return offset + MEMBERSOFFSET;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- public int compare(Viewer viewer, Object e1, Object e2) {
- int cat1= category(e1);
- int cat2= category(e2);
-
- if (needsClasspathComparision(e1, cat1, e2, cat2)) {
- IPackageFragmentRoot root1= getPackageFragmentRoot(e1);
- IPackageFragmentRoot root2= getPackageFragmentRoot(e2);
- if (root1 == null) {
- if (root2 == null) {
- return 0;
- } else {
- return 1;
- }
- } else if (root2 == null) {
- return -1;
- }
- // check if not same to avoid expensive class path access
- if (!root1.getPath().equals(root2.getPath())) {
- int p1= getClassPathIndex(root1);
- int p2= getClassPathIndex(root2);
- if (p1 != p2) {
- return p1 - p2;
- }
- }
- }
-
- if (cat1 != cat2)
- return cat1 - cat2;
-
- if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == OTHERS) {
- String name1= getNonJavaElementLabel(viewer, e1);
- String name2= getNonJavaElementLabel(viewer, e2);
- if (name1 != null && name2 != null) {
- return getComparator().compare(name1, name2);
- }
- return 0; // can't compare
- }
- // only JavaScript elements from this point
-
- if (e1 instanceof IMember) {
- if (fMemberOrderCache.isSortByVisibility()) {
- try {
- int flags1= JdtFlags.getVisibilityCode((IMember) e1);
- int flags2= JdtFlags.getVisibilityCode((IMember) e2);
- int vis= fMemberOrderCache.getVisibilityIndex(flags1) - fMemberOrderCache.getVisibilityIndex(flags2);
- if (vis != 0) {
- return vis;
- }
- } catch (JavaScriptModelException ignore) {
- }
- }
- }
-
- String name1= getElementName(e1);
- String name2= getElementName(e2);
-
- if (e1 instanceof IType) { // handle anonymous types
- if (name1.length() == 0) {
- if (name2.length() == 0) {
- try {
- return getComparator().compare(((IType) e1).getSuperclassName(), ((IType) e2).getSuperclassName());
- } catch (JavaScriptModelException e) {
- return 0;
- }
- } else {
- return 1;
- }
- } else if (name2.length() == 0) {
- return -1;
- }
- }
-
- int cmp= getComparator().compare(name1, name2);
- if (cmp != 0) {
- return cmp;
- }
-
- if (e1 instanceof IFunction) {
- String[] params1= ((IFunction) e1).getParameterTypes();
- String[] params2= ((IFunction) e2).getParameterTypes();
- int len= Math.min(params1.length, params2.length);
- for (int i = 0; i < len; i++) {
- cmp= getComparator().compare(Signature.toString(params1[i]), Signature.toString(params2[i]));
- if (cmp != 0) {
- return cmp;
- }
- }
- return params1.length - params2.length;
- }
- return 0;
- }
-
- private IPackageFragmentRoot getPackageFragmentRoot(Object element) {
- if (element instanceof PackageFragmentRootContainer) {
- // return first package fragment root from the container
- PackageFragmentRootContainer cp= (PackageFragmentRootContainer)element;
- Object[] roots= cp.getPackageFragmentRoots();
- if (roots.length > 0)
- return (IPackageFragmentRoot)roots[0];
- // non resolvable - return null
- return null;
- }
- return JavaModelUtil.getPackageFragmentRoot((IJavaScriptElement)element);
- }
-
- private String getNonJavaElementLabel(Viewer viewer, Object element) {
- // try to use the workbench adapter for non - JavaScript resources or if not available, use the viewers label provider
- if (element instanceof IResource) {
- return ((IResource) element).getName();
- }
- if (element instanceof IStorage) {
- return ((IStorage) element).getName();
- }
- if (element instanceof IAdaptable) {
- IWorkbenchAdapter adapter= (IWorkbenchAdapter) ((IAdaptable) element).getAdapter(IWorkbenchAdapter.class);
- if (adapter != null) {
- return adapter.getLabel(element);
- }
- }
- if (viewer instanceof ContentViewer) {
- IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
- if (prov instanceof ILabelProvider) {
- return ((ILabelProvider) prov).getText(element);
- }
- }
- return null;
- }
-
- private int getClassPathIndex(IPackageFragmentRoot root) {
- try {
- IPath rootPath= root.getPath();
- IPackageFragmentRoot[] roots= root.getJavaScriptProject().getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (roots[i].getPath().equals(rootPath)) {
- return i;
- }
- }
- } catch (JavaScriptModelException e) {
- }
-
- return Integer.MAX_VALUE;
- }
-
- private boolean needsClasspathComparision(Object e1, int cat1, Object e2, int cat2) {
- if ((cat1 == PACKAGEFRAGMENTROOTS && cat2 == PACKAGEFRAGMENTROOTS) ||
- (cat1 == PACKAGEFRAGMENT &&
- ((IPackageFragment)e1).getParent().getResource() instanceof IProject &&
- cat2 == PACKAGEFRAGMENTROOTS) ||
- (cat1 == PACKAGEFRAGMENTROOTS &&
- cat2 == PACKAGEFRAGMENT &&
- ((IPackageFragment)e2).getParent().getResource() instanceof IProject)) {
- IJavaScriptProject p1= getJavaProject(e1);
- return p1 != null && p1.equals(getJavaProject(e2));
- }
- return false;
- }
-
- private IJavaScriptProject getJavaProject(Object element) {
- if (element instanceof IJavaScriptElement) {
- return ((IJavaScriptElement)element).getJavaScriptProject();
- } else if (element instanceof PackageFragmentRootContainer) {
- return ((PackageFragmentRootContainer)element).getJavaProject();
- }
- return null;
- }
-
- private String getElementName(Object element) {
- if (element instanceof IJavaScriptElement) {
- return ((IJavaScriptElement)element).getElementName();
- } else if (element instanceof PackageFragmentRootContainer) {
- return ((PackageFragmentRootContainer)element).getLabel();
- } else {
- return element.toString();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementImageDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementImageDescriptor.java
deleted file mode 100644
index 4b29a2cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementImageDescriptor.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-
-/**
- * A {@link JavaScriptElementImageDescriptor} consists of a base image and several adornments. The adornments
- * are computed according to the flags either passed during creation or set via the method
- *{@link #setAdornments(int)}.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- * * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- */
-public class JavaScriptElementImageDescriptor extends CompositeImageDescriptor {
-
- /** Flag to render the abstract adornment. */
- public final static int ABSTRACT= 0x001;
-
- /** Flag to render the final adornment. */
- public final static int FINAL= 0x002;
-
- /** Flag to render the synchronized adornment. */
- public final static int SYNCHRONIZED= 0x004;
-
- /** Flag to render the static adornment. */
- public final static int STATIC= 0x008;
-
- /** Flag to render the runnable adornment. */
- public final static int RUNNABLE= 0x010;
-
- /** Flag to render the warning adornment. */
- public final static int WARNING= 0x020;
-
- /** Flag to render the error adornment. */
- public final static int ERROR= 0x040;
-
- /** Flag to render the 'override' adornment. */
- public final static int OVERRIDES= 0x080;
-
- /** Flag to render the 'implements' adornment. */
- public final static int IMPLEMENTS= 0x100;
-
- /** Flag to render the 'constructor' adornment. */
- public final static int CONSTRUCTOR= 0x200;
-
- /**
- * Flag to render the 'deprecated' adornment.
- *
- */
- public final static int DEPRECATED= 0x400;
-
- /**
- * Flag to render the 'volatile' adornment.
- *
- */
- public final static int VOLATILE= 0x800;
-
- /**
- * Flag to render the 'transient' adornment.
- *
- */
- public final static int TRANSIENT= 0x1000;
-
-
- private ImageDescriptor fBaseImage;
- private int fFlags;
- private Point fSize;
-
- /**
- * Creates a new JavaScriptElementImageDescriptor.
- *
- * @param baseImage an image descriptor used as the base image
- * @param flags flags indicating which adornments are to be rendered. See {@link #setAdornments(int)}
- * for valid values.
- * @param size the size of the resulting image
- */
- public JavaScriptElementImageDescriptor(ImageDescriptor baseImage, int flags, Point size) {
- fBaseImage= baseImage;
- Assert.isNotNull(fBaseImage);
- fFlags= flags;
- Assert.isTrue(fFlags >= 0);
- fSize= size;
- Assert.isNotNull(fSize);
- }
-
- /**
- * Sets the descriptors adornments. Valid values are: {@link #ABSTRACT}, {@link #FINAL},
- * {@link #SYNCHRONIZED}, {@link #STATIC}, {@link #RUNNABLE}, {@link #WARNING},
- * {@link #ERROR}, {@link #OVERRIDES}, {@link #IMPLEMENTS}, {@link #CONSTRUCTOR},
- * {@link #DEPRECATED}, {@link #VOLATILE}, {@link #TRANSIENT} or any combination of those.
- *
- * @param adornments the image descriptors adornments
- */
- public void setAdornments(int adornments) {
- Assert.isTrue(adornments >= 0);
- fFlags= adornments;
- }
-
- /**
- * Returns the current adornments.
- *
- * @return the current adornments
- */
- public int getAdronments() {
- return fFlags;
- }
-
- /**
- * Sets the size of the image created by calling {@link #createImage()}.
- *
- * @param size the size of the image returned from calling {@link #createImage()}
- */
- public void setImageSize(Point size) {
- Assert.isNotNull(size);
- Assert.isTrue(size.x >= 0 && size.y >= 0);
- fSize= size;
- }
-
- /**
- * Returns the size of the image created by calling {@link #createImage()}.
- *
- * @return the size of the image created by calling {@link #createImage()}
- */
- public Point getImageSize() {
- return new Point(fSize.x, fSize.y);
- }
-
- /* (non-Javadoc)
- * Method declared in CompositeImageDescriptor
- */
- protected Point getSize() {
- return fSize;
- }
-
- /* (non-Javadoc)
- * Method declared on Object.
- */
- public boolean equals(Object object) {
- if (object == null || !JavaScriptElementImageDescriptor.class.equals(object.getClass()))
- return false;
-
- JavaScriptElementImageDescriptor other= (JavaScriptElementImageDescriptor)object;
- return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize.equals(other.fSize));
- }
-
- /* (non-Javadoc)
- * Method declared on Object.
- */
- public int hashCode() {
- return fBaseImage.hashCode() | fFlags | fSize.hashCode();
- }
-
- /* (non-Javadoc)
- * Method declared in CompositeImageDescriptor
- */
- protected void drawCompositeImage(int width, int height) {
- ImageData bg= getImageData(fBaseImage);
-
- if ((fFlags & DEPRECATED) != 0) { // draw *behind* the full image
- Point size= getSize();
- ImageData data= getImageData(JavaPluginImages.DESC_OVR_DEPRECATED);
- drawImage(data, 0, size.y - data.height);
- }
- drawImage(bg, 0, 0);
-
- drawTopRight();
- drawBottomRight();
- drawBottomLeft();
-
-
- }
-
- private ImageData getImageData(ImageDescriptor descriptor) {
- ImageData data= descriptor.getImageData(); // see bug 51965: getImageData can return null
- if (data == null) {
- data= DEFAULT_IMAGE_DATA;
- JavaScriptPlugin.logErrorMessage("Image data not available: " + descriptor.toString()); //$NON-NLS-1$
- }
- return data;
- }
-
- private void addTopRightImage(ImageDescriptor desc, Point pos) {
- ImageData data= getImageData(desc);
- int x= pos.x - data.width;
- if (x >= 0) {
- drawImage(data, x, pos.y);
- pos.x= x;
- }
- }
-
- private void addBottomRightImage(ImageDescriptor desc, Point pos) {
- ImageData data= getImageData(desc);
- int x= pos.x - data.width;
- int y= pos.y - data.height;
- if (x >= 0 && y >= 0) {
- drawImage(data, x, y);
- pos.x= x;
- }
- }
-
- private void addBottomLeftImage(ImageDescriptor desc, Point pos) {
- ImageData data= getImageData(desc);
- int x= pos.x;
- int y= pos.y - data.height;
- if (x + data.width < getSize().x && y >= 0) {
- drawImage(data, x, y);
- pos.x= x + data.width;
- }
- }
-
-
- private void drawTopRight() {
- Point pos= new Point(getSize().x, 0);
- if ((fFlags & ABSTRACT) != 0) {
- addTopRightImage(JavaPluginImages.DESC_OVR_ABSTRACT, pos);
- }
- if ((fFlags & CONSTRUCTOR) != 0) {
- addTopRightImage(JavaPluginImages.DESC_OVR_CONSTRUCTOR, pos);
- }
- if ((fFlags & FINAL) != 0) {
- addTopRightImage(JavaPluginImages.DESC_OVR_FINAL, pos);
- }
- if ((fFlags & VOLATILE) != 0) {
- addTopRightImage(JavaPluginImages.DESC_OVR_VOLATILE, pos);
- }
- if ((fFlags & STATIC) != 0) {
- addTopRightImage(JavaPluginImages.DESC_OVR_STATIC, pos);
- }
-
- }
-
- private void drawBottomRight() {
- Point size= getSize();
- Point pos= new Point(size.x, size.y);
-
- int flags= fFlags;
-
- int syncAndOver= SYNCHRONIZED | OVERRIDES;
- int syncAndImpl= SYNCHRONIZED | IMPLEMENTS;
-
- if ((flags & syncAndOver) == syncAndOver) { // both flags set: merged overlay image
- addBottomRightImage(JavaPluginImages.DESC_OVR_SYNCH_AND_OVERRIDES, pos);
- flags &= ~syncAndOver; // clear to not render again
- } else if ((flags & syncAndImpl) == syncAndImpl) { // both flags set: merged overlay image
- addBottomRightImage(JavaPluginImages.DESC_OVR_SYNCH_AND_IMPLEMENTS, pos);
- flags &= ~syncAndImpl; // clear to not render again
- }
- if ((flags & OVERRIDES) != 0) {
- addBottomRightImage(JavaPluginImages.DESC_OVR_OVERRIDES, pos);
- }
- if ((flags & IMPLEMENTS) != 0) {
- addBottomRightImage(JavaPluginImages.DESC_OVR_IMPLEMENTS, pos);
- }
- if ((flags & SYNCHRONIZED) != 0) {
- addBottomRightImage(JavaPluginImages.DESC_OVR_SYNCH, pos);
- }
- if ((flags & RUNNABLE) != 0) {
- addBottomRightImage(JavaPluginImages.DESC_OVR_RUN, pos);
- }
- if ((flags & TRANSIENT) != 0) {
- addBottomRightImage(JavaPluginImages.DESC_OVR_TRANSIENT, pos);
- }
- }
-
- private void drawBottomLeft() {
- Point pos= new Point(0, getSize().y);
- if ((fFlags & ERROR) != 0) {
- addBottomLeftImage(JavaPluginImages.DESC_OVR_ERROR, pos);
- }
- if ((fFlags & WARNING) != 0) {
- addBottomLeftImage(JavaPluginImages.DESC_OVR_WARNING, pos);
- }
-
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabelProvider.java
deleted file mode 100644
index 92c7c19d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabelProvider.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StorageLabelProvider;
-
-/**
- * Standard label provider for JavaScript elements.
- * Use this class when you want to present the JavaScript elements in a viewer.
- * <p>
- * The implementation also handles non-JavaScript elements by forwarding the requests to the
- * <code>IWorkbenchAdapter</code> of the element.
- * </p>
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- * * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptElementLabelProvider extends LabelProvider {
-
- /**
- * Flag (bit mask) indicating that methods labels include the method return type (appended).
- */
- public final static int SHOW_RETURN_TYPE= 0x001;
-
- /**
- * Flag (bit mask) indicating that method label include parameter types.
- */
- public final static int SHOW_PARAMETERS= 0x002;
-
- /**
- * Flag (bit mask) indicating that the label of a member should include the container.
- * For example, include the name of the type enclosing a field.
- * @deprecated Use SHOW_QUALIFIED or SHOW_ROOT instead
- */
- public final static int SHOW_CONTAINER= 0x004;
-
- /**
- * Flag (bit mask) indicating that the label of a type should be fully qualified.
- * For example, include the fully qualified name of the type enclosing a type.
- * @deprecated Use SHOW_QUALIFIED instead
- */
- public final static int SHOW_CONTAINER_QUALIFICATION= 0x008;
-
- /**
- * Flag (bit mask) indicating that the label should include overlay icons
- * for element type and modifiers.
- */
- public final static int SHOW_OVERLAY_ICONS= 0x010;
-
- /**
- * Flag (bit mask) indicating that a field label should include the declared type.
- */
- public final static int SHOW_TYPE= 0x020;
-
- /**
- * Flag (bit mask) indicating that the label should include the name of the
- * package fragment root (appended).
- */
- public final static int SHOW_ROOT= 0x040;
-
- /**
- * Flag (bit mask) indicating that the label qualification of a type should
- * be shown after the name.
- * @deprecated SHOW_POST_QUALIFIED instead
- */
- public final static int SHOW_POSTIFIX_QUALIFICATION= 0x080;
-
- /**
- * Flag (bit mask) indicating that the label should show the icons with no space
- * reserved for overlays.
- */
- public final static int SHOW_SMALL_ICONS= 0x100;
-
- /**
- * Flag (bit mask) indicating that the package fragment roots from class path variables should
- * be rendered with the variable in the name
- */
- public final static int SHOW_VARIABLE= 0x200;
-
- /**
- * Flag (bit mask) indicating that compilation units, class files, types, declarations and members
- * should be rendered qualified.
- * Examples: <code>java.lang.String</code>, <code>java.util.Vector.size()</code>
- *
- *
- */
- public final static int SHOW_QUALIFIED= 0x400;
-
- /**
- * Flag (bit mask) indicating that compilation units, class files, types, declarations and members
- * should be rendered qualified.The qualification is appended.
- * Examples: <code>String - java.lang</code>, <code>size() - java.util.Vector</code>
- *
- *
- */
- public final static int SHOW_POST_QUALIFIED= 0x800;
-
-
- /**
- * Constant (value <code>0</code>) indicating that the label should show
- * the basic images only.
- */
- public final static int SHOW_BASICS= 0x000;
-
-
- /**
- * Constant indicating the default label rendering.
- * Currently the default is equivalent to
- * <code>SHOW_PARAMETERS | SHOW_OVERLAY_ICONS</code>.
- */
- public final static int SHOW_DEFAULT= new Integer(SHOW_PARAMETERS | SHOW_OVERLAY_ICONS).intValue();
-
- private JavaElementImageProvider fImageLabelProvider;
-
- private StorageLabelProvider fStorageLabelProvider;
- private int fFlags;
- private int fImageFlags;
- private long fTextFlags;
-
- /**
- * Creates a new label provider with <code>SHOW_DEFAULT</code> flag.
- *
- * @see #SHOW_DEFAULT
- *
- */
- public JavaScriptElementLabelProvider() {
- this(SHOW_DEFAULT);
- }
-
- /**
- * Creates a new label provider.
- *
- * @param flags the initial options; a bitwise OR of <code>SHOW_* </code> constants
- */
- public JavaScriptElementLabelProvider(int flags) {
- fImageLabelProvider= new JavaElementImageProvider();
- fStorageLabelProvider= new StorageLabelProvider();
- fFlags= flags;
- updateImageProviderFlags();
- updateTextProviderFlags();
- }
-
- private boolean getFlag( int flag) {
- return (fFlags & flag) != 0;
- }
-
- /**
- * Turns on the rendering options specified in the given flags.
- *
- * @param flags the options; a bitwise OR of <code>SHOW_* </code> constants
- */
- public void turnOn(int flags) {
- fFlags |= flags;
- updateImageProviderFlags();
- updateTextProviderFlags();
- }
-
- /**
- * Turns off the rendering options specified in the given flags.
- *
- * @param flags the initial options; a bitwise OR of <code>SHOW_* </code> constants
- */
- public void turnOff(int flags) {
- fFlags &= (~flags);
- updateImageProviderFlags();
- updateTextProviderFlags();
- }
-
- private void updateImageProviderFlags() {
- fImageFlags= 0;
- if (getFlag(SHOW_OVERLAY_ICONS)) {
- fImageFlags |= JavaElementImageProvider.OVERLAY_ICONS;
- }
- if (getFlag(SHOW_SMALL_ICONS)) {
- fImageFlags |= JavaElementImageProvider.SMALL_ICONS;
- }
- }
-
- private void updateTextProviderFlags() {
- fTextFlags= JavaScriptElementLabels.T_TYPE_PARAMETERS;
- if (getFlag(SHOW_RETURN_TYPE)) {
- fTextFlags |= JavaScriptElementLabels.M_APP_RETURNTYPE;
- }
- if (getFlag(SHOW_PARAMETERS)) {
- fTextFlags |= JavaScriptElementLabels.M_PARAMETER_TYPES;
- }
- if (getFlag(SHOW_CONTAINER)) {
- fTextFlags |= JavaScriptElementLabels.P_POST_QUALIFIED | JavaScriptElementLabels.T_POST_QUALIFIED | JavaScriptElementLabels.CF_POST_QUALIFIED | JavaScriptElementLabels.CU_POST_QUALIFIED | JavaScriptElementLabels.M_POST_QUALIFIED | JavaScriptElementLabels.F_POST_QUALIFIED;
- }
- if (getFlag(SHOW_POSTIFIX_QUALIFICATION)) {
- fTextFlags |= (JavaScriptElementLabels.T_POST_QUALIFIED | JavaScriptElementLabels.CF_POST_QUALIFIED | JavaScriptElementLabels.CU_POST_QUALIFIED);
- } else if (getFlag(SHOW_CONTAINER_QUALIFICATION)) {
- fTextFlags |=(JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.CF_QUALIFIED | JavaScriptElementLabels.CU_QUALIFIED);
- }
- if (getFlag(SHOW_TYPE)) {
- fTextFlags |= JavaScriptElementLabels.F_APP_TYPE_SIGNATURE;
- }
- if (getFlag(SHOW_ROOT)) {
- fTextFlags |= JavaScriptElementLabels.APPEND_ROOT_PATH;
- }
- if (getFlag(SHOW_VARIABLE)) {
- fTextFlags |= JavaScriptElementLabels.ROOT_VARIABLE;
- }
- if (getFlag(SHOW_QUALIFIED)) {
- fTextFlags |= (JavaScriptElementLabels.F_FULLY_QUALIFIED | JavaScriptElementLabels.M_FULLY_QUALIFIED | JavaScriptElementLabels.I_FULLY_QUALIFIED
- | JavaScriptElementLabels.T_FULLY_QUALIFIED | JavaScriptElementLabels.D_QUALIFIED | JavaScriptElementLabels.CF_QUALIFIED | JavaScriptElementLabels.CU_QUALIFIED);
- }
- if (getFlag(SHOW_POST_QUALIFIED)) {
- fTextFlags |= (JavaScriptElementLabels.F_POST_QUALIFIED | JavaScriptElementLabels.M_POST_QUALIFIED | JavaScriptElementLabels.I_POST_QUALIFIED
- | JavaScriptElementLabels.T_POST_QUALIFIED | JavaScriptElementLabels.D_POST_QUALIFIED | JavaScriptElementLabels.CF_POST_QUALIFIED | JavaScriptElementLabels.CU_POST_QUALIFIED);
- }
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getImage
- */
- public Image getImage(Object element) {
- Image result= fImageLabelProvider.getImageLabel(element, fImageFlags);
- if (result != null) {
- return result;
- }
-
- if (element instanceof IStorage)
- return fStorageLabelProvider.getImage(element);
-
- return result;
- }
-
- /* (non-Javadoc)
- * @see ILabelProvider#getText
- */
- public String getText(Object element) {
- String text= JavaScriptElementLabels.getTextLabel(element, fTextFlags);
- if (text.length() > 0) {
- return text;
- }
-
- if (element instanceof IStorage)
- return fStorageLabelProvider.getText(element);
-
- return text;
- }
-
- /* (non-Javadoc)
- *
- * @see IBaseLabelProvider#dispose
- */
- public void dispose() {
- fStorageLabelProvider.dispose();
- fImageLabelProvider.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java
deleted file mode 100644
index bb8e8e66..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java
+++ /dev/null
@@ -1,1191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.BindingKey;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IInitializer;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.StorageLabelProvider;
-
-/**
- * <code>JavaScriptElementLabels</code> provides helper methods to render names of JavaScript elements.
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptElementLabels {
-
-
- /**
- * Method names contain parameter types.
- * e.g. <code>foo(int)</code>
- */
- public final static long M_PARAMETER_TYPES= 1L << 0;
-
- /**
- * Method names contain parameter names.
- * e.g. <code>foo(index)</code>
- */
- public final static long M_PARAMETER_NAMES= 1L << 1;
-
- /**
- * Method names contain type parameters prepended.
- * e.g. <code>&lt;A&gt; foo(A index)</code>
- */
- public final static long M_PRE_TYPE_PARAMETERS= 1L << 2;
-
- /**
- * Method names contain type parameters appended.
- * e.g. <code>foo(A index) &lt;A&gt;</code>
- */
- public final static long M_APP_TYPE_PARAMETERS= 1L << 3;
-
- /**
- * Method names contain thrown exceptions.
- * e.g. <code>foo throws IOException</code>
- */
- public final static long M_EXCEPTIONS= 1L << 4;
-
- /**
- * Method names contain return type (appended)
- * e.g. <code>foo : int</code>
- */
- public final static long M_APP_RETURNTYPE= 1L << 5;
-
- /**
- * Method names contain return type (appended)
- * e.g. <code>int foo</code>
- */
- public final static long M_PRE_RETURNTYPE= 1L << 6;
-
- /**
- * Method names are fully qualified.
- * e.g. <code>java.util.Vector.size</code>
- */
- public final static long M_FULLY_QUALIFIED= 1L << 7;
-
- /**
- * Method names are post qualified.
- * e.g. <code>size - java.util.Vector</code>
- */
- public final static long M_POST_QUALIFIED= 1L << 8;
-
- /**
- * Initializer names are fully qualified.
- * e.g. <code>java.util.Vector.{ ... }</code>
- */
- public final static long I_FULLY_QUALIFIED= 1L << 10;
-
- /**
- * Type names are post qualified.
- * e.g. <code>{ ... } - java.util.Map</code>
- */
- public final static long I_POST_QUALIFIED= 1L << 11;
-
- /**
- * Field names contain the declared type (appended)
- * e.g. <code>fHello : int</code>
- */
- public final static long F_APP_TYPE_SIGNATURE= 1L << 14;
-
- /**
- * Field names contain the declared type (prepended)
- * e.g. <code>int fHello</code>
- */
- public final static long F_PRE_TYPE_SIGNATURE= 1L << 15;
-
- /**
- * Fields names are fully qualified.
- * e.g. <code>java.lang.System.out</code>
- */
- public final static long F_FULLY_QUALIFIED= 1L << 16;
-
- /**
- * Fields names are post qualified.
- * e.g. <code>out - java.lang.System</code>
- */
- public final static long F_POST_QUALIFIED= 1L << 17;
-
- /**
- * Type names are fully qualified.
- * e.g. <code>java.util.Map.MapEntry</code>
- */
- public final static long T_FULLY_QUALIFIED= 1L << 18;
-
- /**
- * Type names are type container qualified.
- * e.g. <code>Map.MapEntry</code>
- */
- public final static long T_CONTAINER_QUALIFIED= 1L << 19;
-
- /**
- * Type names are post qualified.
- * e.g. <code>MapEntry - java.util.Map</code>
- */
- public final static long T_POST_QUALIFIED= 1L << 20;
-
- /**
- * Type names contain type parameters.
- * e.g. <code>Map&lt;S, T&gt;</code>
- */
- public final static long T_TYPE_PARAMETERS= 1L << 21;
-
- /**
- * Declarations (import container / declaration, package declaration) are qualified.
- * e.g. <code>java.util.Vector.class/import container</code>
- */
- public final static long D_QUALIFIED= 1L << 24;
-
- /**
- * Declarations (import container / declaration, package declaration) are post qualified.
- * e.g. <code>import container - java.util.Vector.class</code>
- */
- public final static long D_POST_QUALIFIED= 1L << 25;
-
- /**
- * Class file names are fully qualified.
- * e.g. <code>java.util.Vector.class</code>
- */
- public final static long CF_QUALIFIED= 1L << 27;
-
- /**
- * Class file names are post qualified.
- * e.g. <code>Vector.class - java.util</code>
- */
- public final static long CF_POST_QUALIFIED= 1L << 28;
-
- /**
- * Compilation unit names are fully qualified.
- * e.g. <code>java.util.Vector.java</code>
- */
- public final static long CU_QUALIFIED= 1L << 31;
-
- /**
- * Compilation unit names are post qualified.
- * e.g. <code>Vector.JavaScript - java.util</code>
- */
- public final static long CU_POST_QUALIFIED= 1L << 32;
-
- /**
- * Package names are qualified.
- * e.g. <code>MyProject/src/java.util</code>
- */
- public final static long P_QUALIFIED= 1L << 35;
-
- /**
- * Package names are post qualified.
- * e.g. <code>java.util - MyProject/src</code>
- */
- public final static long P_POST_QUALIFIED= 1L << 36;
-
- /**
- * Package names are compressed.
- * e.g. <code>o*.e*.search</code>
- */
- public final static long P_COMPRESSED= 1L << 37;
-
- /**
- * Package Fragment Roots contain variable name if from a variable.
- * e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code>
- */
- public final static long ROOT_VARIABLE= 1L << 40;
-
- /**
- * Package Fragment Roots contain the project name if not an archive (prepended).
- * e.g. <code>MyProject/src</code>
- */
- public final static long ROOT_QUALIFIED= 1L << 41;
-
- /**
- * Package Fragment Roots contain the project name if not an archive (appended).
- * e.g. <code>src - MyProject</code>
- */
- public final static long ROOT_POST_QUALIFIED= 1L << 42;
-
- /**
- * Add root path to all elements except Package Fragment Roots and JavaScript projects.
- * e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
- * Option only applies to getElementLabel
- */
- public final static long APPEND_ROOT_PATH= 1L << 43;
-
- /**
- * Add root path to all elements except Package Fragment Roots and JavaScript projects.
- * e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
- * Option only applies to getElementLabel
- */
- public final static long PREPEND_ROOT_PATH= 1L << 44;
-
- /**
- * Post qualify referenced package fragment roots. For example
- * <code>jdt.jar - org.eclipse.wst.jsdt.ui</code> if the jar is referenced
- * from another project.
- */
- public final static long REFERENCED_ROOT_POST_QUALIFIED= 1L << 45;
-
- /**
- * Specified to use the resolved information of a IType, IFunction or IField. See {@link IType#isResolved()}.
- * If resolved information is available, types will be rendered with type parameters of the instantiated type.
- * Resolved method render with the parameter types of the method instance.
- * <code>Vector&lt;String&gt;.get(String)</code>
- */
- public final static long USE_RESOLVED= 1L << 48;
-
- /**
- * Prepend first category (if any) to field.
- *
- */
- public final static long F_CATEGORY= 1L << 49;
- /**
- * Prepend first category (if any) to method.
- *
- */
- public final static long M_CATEGORY= 1L << 50;
- /**
- * Prepend first category (if any) to type.
- *
- */
- public final static long T_CATEGORY= 1L << 51;
-
- /**
- * @deprecated no longer used
- */
- public final static long SHOW_TYPE= 1L << 52;
-
- /**
- * Show category for all elements.
- *
- */
- public final static long ALL_CATEGORY= new Long(JavaScriptElementLabels.F_CATEGORY | JavaScriptElementLabels.M_CATEGORY | JavaScriptElementLabels.T_CATEGORY).longValue();
-
- /**
- * Qualify all elements
- */
- public final static long ALL_FULLY_QUALIFIED= new Long(F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED).longValue();
-
-
- /**
- * Post qualify all elements
- */
- public final static long ALL_POST_QUALIFIED= new Long(F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED).longValue();
-
- /**
- * Default options (M_PARAMETER_TYPES, M_APP_TYPE_PARAMETERS & T_TYPE_PARAMETERS enabled)
- */
- public final static long ALL_DEFAULT= new Long(M_PARAMETER_NAMES | M_APP_TYPE_PARAMETERS | T_TYPE_PARAMETERS).longValue();
-
- /**
- * Default qualify options (All except Root and Package)
- */
- public final static long DEFAULT_QUALIFIED= new Long(F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED).longValue();
-
- /**
- * Default post qualify options (All except Root and Package)
- */
- public final static long DEFAULT_POST_QUALIFIED= new Long(F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED).longValue();
-
- /**
- * User-readable string for separating post qualified names (e.g. " - ").
- */
- public final static String CONCAT_STRING= JavaUIMessages.JavaElementLabels_concat_string;
- /**
- * User-readable string for separating list items (e.g. ", ").
- */
- public final static String COMMA_STRING= JavaUIMessages.JavaElementLabels_comma_string;
- /**
- * User-readable string for separating the return type (e.g. " : ").
- */
- public final static String DECL_STRING= JavaUIMessages.JavaElementLabels_declseparator_string;
- /**
- * User-readable string for concatenating categories (e.g. " ").
- * XXX: to be made API post 3.2
- *
- */
- private final static String CATEGORY_SEPARATOR_STRING= JavaUIMessages.JavaElementLabels_category_separator_string;
- /**
- * User-readable string for ellipsis ("...").
- */
- public final static String ELLIPSIS_STRING= "..."; //$NON-NLS-1$
- /**
- * User-readable string for the default package name (e.g. "(default package)").
- */
- public final static String DEFAULT_PACKAGE= JavaUIMessages.JavaElementLabels_default_package;
-
-
- private final static long QUALIFIER_FLAGS= P_COMPRESSED | USE_RESOLVED;
-
- /*
- * Package name compression
- */
- private static String fgPkgNamePattern= ""; //$NON-NLS-1$
- private static String fgPkgNamePrefix;
- private static String fgPkgNamePostfix;
- private static int fgPkgNameChars;
- private static int fgPkgNameLength= -1;
-
- private JavaScriptElementLabels() {
- }
-
- private static final boolean getFlag(long flags, long flag) {
- return (flags & flag) != 0;
- }
-
- /**
- * Returns the label of the given object. The object must be of type {@link IJavaScriptElement} or adapt to {@link IWorkbenchAdapter}. The empty string is returned
- * if the element type is not known.
- * @param obj Object to get the label from.
- * @param flags The rendering flags
- * @return Returns the label or the empty string if the object type is not supported.
- */
- public static String getTextLabel(Object obj, long flags) {
- if (obj instanceof IJavaScriptElement) {
- return getElementLabel((IJavaScriptElement) obj, flags);
- } else if (obj instanceof IResource) {
- return ((IResource) obj).getName();
- } else if (obj instanceof IStorage) {
- StorageLabelProvider storageLabelProvider= new StorageLabelProvider();
- String label= storageLabelProvider.getText(obj);
- storageLabelProvider.dispose();
- return label;
- } else if (obj instanceof IAdaptable) {
- IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
- if (wbadapter != null) {
- return wbadapter.getLabel(obj);
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Returns the label for a JavaScript element with the flags as defined by this class.
- * @param element The element to render.
- * @param flags The rendering flags.
- * @return the label of the JavaScript element
- */
- public static String getElementLabel(IJavaScriptElement element, long flags) {
- StringBuffer buf= new StringBuffer(60);
- getElementLabel(element, flags, buf);
- return buf.toString();
- }
-
- /**
- * Returns the label for a JavaScript element with the flags as defined by this class.
- * @param element The element to render.
- * @param flags The rendering flags.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getElementLabel(IJavaScriptElement element, long flags, StringBuffer buf) {
- int type= element.getElementType();
- IPackageFragmentRoot root= null;
-
- if (type != IJavaScriptElement.JAVASCRIPT_MODEL && type != IJavaScriptElement.JAVASCRIPT_PROJECT && type != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- root= JavaModelUtil.getPackageFragmentRoot(element);
- if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
- getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
- buf.append(CONCAT_STRING);
- }
-
- switch (type) {
- case IJavaScriptElement.METHOD:
- getMethodLabel((IFunction) element, flags, buf);
- break;
- case IJavaScriptElement.FIELD:
- getFieldLabel((IField) element, flags, buf);
- break;
- case IJavaScriptElement.LOCAL_VARIABLE:
- getLocalVariableLabel((ILocalVariable) element, flags, buf);
- break;
- case IJavaScriptElement.INITIALIZER:
- getInitializerLabel((IInitializer) element, flags, buf);
- break;
- case IJavaScriptElement.TYPE:
- getTypeLabel((IType) element, flags, buf);
- break;
- case IJavaScriptElement.CLASS_FILE:
- getClassFileLabel((IClassFile) element, flags, buf);
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- getCompilationUnitLabel((IJavaScriptUnit) element, flags, buf);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- getPackageFragmentLabel((IPackageFragment) element, flags, buf);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
- break;
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.IMPORT_DECLARATION:
- getDeclarationLabel(element, flags, buf);
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- buf.append(element.getDisplayName());
- break;
- default:
- buf.append(element.getDisplayName());
- }
-
- if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
- buf.append(CONCAT_STRING);
- getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
- }
- }
-
- /**
- * Appends the label for a method to a {@link StringBuffer}. Considers the M_* flags.
- * @param method The element to render.
- * @param flags The rendering flags. Flags with names starting with 'M_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getMethodLabel(IFunction method, long flags, StringBuffer buf) {
- try {
- BindingKey resolvedKey= getFlag(flags, USE_RESOLVED) && method.isResolved() ? new BindingKey(method.getKey()) : null;
- String resolvedSig= (resolvedKey != null) ? resolvedKey.toSignature() : null;
-
- // return type
- if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
- String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType();
- getTypeSignatureLabel(returnTypeSig, flags, buf);
- buf.append(' ');
- }
-
- // qualification
- IType declaringType = method.getDeclaringType();
- if (getFlag(flags, M_FULLY_QUALIFIED) ) {
- if (declaringType!=null && !method.isConstructor())
- {
- getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- } else {
- buf.append('[');
- getFileLabel(method, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append(']');
- }
-
- }
-
- if(buf.length() != 0)
- buf.append(' ');
- buf.append(method.getDisplayName());
-
- // parameters
- buf.append('(');
- if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
- String[] types= null;
- int nParams= 0;
- boolean renderVarargs= false;
- if (getFlag(flags, M_PARAMETER_TYPES)) {
- if (resolvedSig != null) {
- types= Signature.getParameterTypes(resolvedSig);
- } else {
- types= method.getParameterTypes();
- }
- nParams= types.length;
- renderVarargs= method.exists() && Flags.isVarargs(method.getFlags());
- }
- String[] names= null;
- if (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) {
- names= method.getParameterNames();
- if (types == null) {
- nParams= names.length;
- } else { // types != null
- if (nParams != names.length) {
- if (resolvedSig != null && types.length > names.length) {
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137
- nParams= names.length;
- String[] typesWithoutSyntheticParams= new String[nParams];
- System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0, nParams);
- types= typesWithoutSyntheticParams;
- } else {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029
- // JavaScriptPlugin.logErrorMessage("JavaScriptElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- names= null; // no names rendered
- }
- }
- }
- }
-
- for (int i= 0; i < nParams; i++) {
- if (i > 0) {
- buf.append(COMMA_STRING);
- }
- if (types != null) {
- String paramSig= types[i];
- if (renderVarargs && (i == nParams - 1)) {
- int newDim= Signature.getArrayCount(paramSig) - 1;
- getTypeSignatureLabel(Signature.getElementType(paramSig), flags, buf);
- for (int k= 0; k < newDim; k++) {
- buf.append('[').append(']');
- }
- buf.append(ELLIPSIS_STRING);
- } else {
- getTypeSignatureLabel(paramSig, flags, buf);
- }
- }
- if (names != null) {
- if (types != null) {
- buf.append(' ');
- }
- buf.append(names[i]);
- }
- }
- } else {
- if (method.getParameterTypes().length > 0) {
- buf.append(ELLIPSIS_STRING);
- }
- }
- buf.append(')');
-
- if (getFlag(flags, M_EXCEPTIONS)) {
- String[] types;
- if (resolvedKey != null) {
- //types= resolvedKey.getThrownExceptions();
- types = new String[0];
- } else {
- types= new String[0];
- }
- if (types.length > 0) {
- buf.append(" throws "); //$NON-NLS-1$
- for (int i= 0; i < types.length; i++) {
- if (i > 0) {
- buf.append(COMMA_STRING);
- }
- getTypeSignatureLabel(types[i], flags, buf);
- }
- }
- }
-
- if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
- if (method.getReturnType()!=null)
- {
- buf.append(DECL_STRING);
- String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType();
- getTypeSignatureLabel(returnTypeSig, flags, buf);
- }
- }
-
- // category
- if (getFlag(flags, M_CATEGORY) && method.exists())
- getCategoryLabel(method, buf);
-
- // post qualification
- if (getFlag(flags, M_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- if (declaringType!=null)
- getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- else
- getFileLabel(method, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // NotExistsException will not reach this point
- }
- }
-
- private static void getCategoryLabel(IMember member, StringBuffer buf) throws JavaScriptModelException {
- String[] categories= member.getCategories();
- if (categories.length > 0) {
- StringBuffer categoriesBuf= new StringBuffer(30);
- for (int i= 0; i < categories.length; i++) {
- if (i > 0)
- categoriesBuf.append(CATEGORY_SEPARATOR_STRING);
- categoriesBuf.append(categories[i]);
- }
- buf.append(CONCAT_STRING);
- buf.append(Messages.format(JavaUIMessages.JavaElementLabels_category , categoriesBuf.toString()));
- }
- }
-
- /**
- * Appends the label for a field to a {@link StringBuffer}. Considers the F_* flags.
- * @param field The element to render.
- * @param flags The rendering flags. Flags with names starting with 'F_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getFieldLabel(IField field, long flags, StringBuffer buf) {
- try {
-
- if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
- if (getFlag(flags, USE_RESOLVED) && field.isResolved()) {
- getTypeSignatureLabel(new BindingKey(field.getKey()).toSignature(), flags, buf);
- } else {
- getTypeSignatureLabel(field.getTypeSignature(), flags, buf);
- }
- buf.append(' ');
- }
-
- // qualification
- IType declaringType = field.getDeclaringType();
- if (getFlag(flags, F_FULLY_QUALIFIED)) {
- if (declaringType!=null)
- getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- else
- getFileLabel(field, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
- buf.append(field.getDisplayName());
-
- if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
- if (field.getTypeSignature()!=null)
- {
- buf.append(DECL_STRING);
- if (getFlag(flags, USE_RESOLVED) && field.isResolved()) {
- getTypeSignatureLabel(new BindingKey(field.getKey()).toSignature(), flags, buf);
- } else {
- getTypeSignatureLabel(field.getTypeSignature(), flags, buf);
- }
- }
- }
-
- // category
- if (getFlag(flags, F_CATEGORY) && field.exists())
- getCategoryLabel(field, buf);
-
- // post qualification
- if (getFlag(flags, F_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- if (declaringType!=null)
- getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- else
- getFileLabel(field, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- }
-
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // NotExistsException will not reach this point
- }
- }
-
- /**
- * Appends the label for a local variable to a {@link StringBuffer}.
- * @param localVariable The element to render.
- * @param flags The rendering flags. Flags with names starting with 'F_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getLocalVariableLabel(ILocalVariable localVariable, long flags, StringBuffer buf) {
- if (getFlag(flags, F_PRE_TYPE_SIGNATURE)) {
- getTypeSignatureLabel(localVariable.getTypeSignature(), flags, buf);
- buf.append(' ');
- }
-
- if (getFlag(flags, F_FULLY_QUALIFIED)) {
- getElementLabel(localVariable.getParent(), M_PARAMETER_TYPES | M_FULLY_QUALIFIED | T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
-
- buf.append(localVariable.getDisplayName());
-
- if (getFlag(flags, F_APP_TYPE_SIGNATURE)) {
- buf.append(DECL_STRING);
- getTypeSignatureLabel(localVariable.getTypeSignature(), flags, buf);
- }
-
- // post qualification
- if (getFlag(flags, F_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- getElementLabel(localVariable.getParent(), M_PARAMETER_TYPES | M_FULLY_QUALIFIED | T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- }
- }
-
- /**
- * Appends the label for a initializer to a {@link StringBuffer}. Considers the I_* flags.
- * @param initializer The element to render.
- * @param flags The rendering flags. Flags with names starting with 'I_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getInitializerLabel(IInitializer initializer, long flags, StringBuffer buf) {
- // qualification
- if (getFlag(flags, I_FULLY_QUALIFIED)) {
- getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
- buf.append(JavaUIMessages.JavaElementLabels_initializer);
-
- // post qualification
- if (getFlag(flags, I_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- }
- }
-
- private static void getTypeSignatureLabel(String typeSig, long flags, StringBuffer buf) {
- int sigKind= Signature.getTypeSignatureKind(typeSig);
- switch (sigKind) {
- case Signature.BASE_TYPE_SIGNATURE:
- buf.append(Signature.toString(typeSig));
- break;
- case Signature.ARRAY_TYPE_SIGNATURE:
- getTypeSignatureLabel(Signature.getElementType(typeSig), flags, buf);
- for (int dim= Signature.getArrayCount(typeSig); dim > 0; dim--) {
- buf.append('[').append(']');
- }
- break;
- case Signature.CLASS_TYPE_SIGNATURE:
- String baseType= Signature.toString(typeSig);
-
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( Signature.getSimpleName(baseType), buf );
-
- getTypeArgumentSignaturesLabel(new String[0], flags, buf);
- break;
- default:
- // unknown
- }
- }
-
- private static void getTypeArgumentSignaturesLabel(String[] typeArgsSig, long flags, StringBuffer buf) {
- if (typeArgsSig.length > 0) {
- buf.append('<');
- for (int i = 0; i < typeArgsSig.length; i++) {
- if (i > 0) {
- buf.append(COMMA_STRING);
- }
- getTypeSignatureLabel(typeArgsSig[i], flags, buf);
- }
- buf.append('>');
- }
- }
-
- private static void getTypeParameterSignaturesLabel(String[] typeParamSigs, long flags, StringBuffer buf) {
- if (typeParamSigs.length > 0) {
- buf.append('<');
- for (int i = 0; i < typeParamSigs.length; i++) {
- if (i > 0) {
- buf.append(COMMA_STRING);
- }
- buf.append(Signature.getTypeVariable(typeParamSigs[i]));
- }
- buf.append('>');
- }
- }
-
-
- /**
- * Appends the label for a type to a {@link StringBuffer}. Considers the T_* flags.
- * @param type The element to render.
- * @param flags The rendering flags. Flags with names starting with 'T_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getTypeLabel(IType type, long flags, StringBuffer buf) {
-
- if (getFlag(flags, T_FULLY_QUALIFIED)) {
- IPackageFragment pack= type.getPackageFragment();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), buf);
- //buf.append('.');
- }
- }
- if (getFlag(flags, T_FULLY_QUALIFIED | T_CONTAINER_QUALIFIED)) {
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- getTypeLabel(declaringType, T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
- int parentType= type.getParent().getElementType();
- if (parentType == IJavaScriptElement.METHOD || parentType == IJavaScriptElement.FIELD || parentType == IJavaScriptElement.INITIALIZER) { // anonymous or local
- getElementLabel(type.getParent(), 0, buf);
- buf.append('.');
- }
- }
-
- String typeName= type.getDisplayName();
- if (typeName.length() == 0) { // anonymous
- try {
- String supertypeName= Signature.getSimpleName(type.getSuperclassName());
-
- typeName= Messages.format(JavaUIMessages.JavaElementLabels_anonym_type , supertypeName);
-
- } catch (JavaScriptModelException e) {
- //ignore
- typeName= JavaUIMessages.JavaElementLabels_anonym;
- }
- }
- buf.append(typeName);
- if (getFlag(flags, T_TYPE_PARAMETERS)) {
- if (getFlag(flags, USE_RESOLVED) && type.isResolved()) {
- getTypeParameterSignaturesLabel(new String[0], flags, buf);
- }
- }
-
- // category
- if (getFlag(flags, T_CATEGORY) && type.exists()) {
- try {
- getCategoryLabel(type, buf);
- } catch (JavaScriptModelException e) {
- // ignore
- }
- }
-
- // post qualification
- if (getFlag(flags, T_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- IType declaringType= type.getDeclaringType();
- if (declaringType != null) {
- getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS), buf);
- int parentType= type.getParent().getElementType();
- if (parentType == IJavaScriptElement.METHOD || parentType == IJavaScriptElement.FIELD || parentType == IJavaScriptElement.INITIALIZER) { // anonymous or local
- buf.append('.');
- getElementLabel(type.getParent(), 0, buf);
- }
- } else {
- getPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS, buf);
- }
- }
- }
-
- /**
- * Appends the label for a import container, import or package declaration to a {@link StringBuffer}. Considers the D_* flags.
- * @param declaration The element to render.
- * @param flags The rendering flags. Flags with names starting with 'D_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getDeclarationLabel(IJavaScriptElement declaration, long flags, StringBuffer buf) {
- if (getFlag(flags, D_QUALIFIED)) {
- IJavaScriptElement openable= (IJavaScriptElement) declaration.getOpenable();
- if (openable != null) {
- buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED | (flags & QUALIFIER_FLAGS)));
- buf.append('/');
- }
- }
- if (declaration.getElementType() == IJavaScriptElement.IMPORT_CONTAINER) {
- buf.append(JavaUIMessages.JavaElementLabels_import_container);
- } else {
- buf.append(declaration.getDisplayName());
- }
- // post qualification
- if (getFlag(flags, D_POST_QUALIFIED)) {
- IJavaScriptElement openable= (IJavaScriptElement) declaration.getOpenable();
- if (openable != null) {
- buf.append(CONCAT_STRING);
- buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED | (flags & QUALIFIER_FLAGS)));
- }
- }
- }
-
- /**
- * Appends the label for a class file to a {@link StringBuffer}. Considers the CF_* flags.
- * @param classFile The element to render.
- * @param flags The rendering flags. Flags with names starting with 'CF_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getClassFileLabel(IClassFile classFile, long flags, StringBuffer buf) {
- if (getFlag(flags, CF_QUALIFIED)) {
- IPackageFragment pack= (IPackageFragment) classFile.getParent();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
- }
- buf.append(classFile.getDisplayName());
-
- if (getFlag(flags, CF_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- getPackageFragmentLabel((IPackageFragment) classFile.getParent(), flags & QUALIFIER_FLAGS, buf);
- }
- }
-
- /**
- * Appends the label for a compilation unit to a {@link StringBuffer}. Considers the CU_* flags.
- * @param cu The element to render.
- * @param flags The rendering flags. Flags with names starting with 'CU_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getCompilationUnitLabel(IJavaScriptUnit cu, long flags, StringBuffer buf) {
- if (getFlag(flags, CU_QUALIFIED)) {
- IPackageFragment pack= (IPackageFragment) cu.getParent();
- if (!pack.isDefaultPackage()) {
- getPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS), buf);
- buf.append('.');
- }
- }
- buf.append(cu.getDisplayName());
-
- if (getFlag(flags, CU_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- getPackageFragmentLabel((IPackageFragment) cu.getParent(), flags & QUALIFIER_FLAGS, buf);
- }
- }
-
- public static void getFileLabel(IMember member, long flags, StringBuffer buf) {
- IJavaScriptUnit compUnit=member.getJavaScriptUnit();
- if (compUnit!=null)
- getCompilationUnitLabel(compUnit, flags, buf);
- else {
- IClassFile classFile = member.getClassFile();
- if (classFile!=null)
- getClassFileLabel(classFile, flags, buf);
- }
-
- }
- /**
- * Appends the label for a package fragment to a {@link StringBuffer}. Considers the P_* flags.
- * @param pack The element to render.
- * @param flags The rendering flags. Flags with names starting with P_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getPackageFragmentLabel(IPackageFragment pack, long flags, StringBuffer buf) {
- if (getFlag(flags, P_QUALIFIED)) {
- getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
- buf.append('/');
- }
- refreshPackageNamePattern();
- if (pack.isDefaultPackage()) {
- buf.append(DEFAULT_PACKAGE);
- } else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
- String name= pack.getDisplayName();
- int start= 0;
- int dot= name.indexOf('.', start);
- while (dot > 0) {
- if (dot - start > fgPkgNameLength-1) {
- buf.append(fgPkgNamePrefix);
- if (fgPkgNameChars > 0)
- buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
- buf.append(fgPkgNamePostfix);
- } else
- buf.append(name.substring(start, dot + 1));
- start= dot + 1;
- dot= name.indexOf('.', start);
- }
- buf.append(name.substring(start));
- } else {
- buf.append(pack.getDisplayName());
- }
- if (getFlag(flags, P_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
- }
- }
-
- /**
- * Appends the label for a package fragment root to a {@link StringBuffer}. Considers the ROOT_* flags.
- * @param root The element to render.
- * @param flags The rendering flags. Flags with names starting with ROOT_' are considered.
- * @param buf The buffer to append the resulting label to.
- */
- public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- if (root.isArchive())
- getArchiveLabel(root, flags, buf);
- else
- getFolderLabel(root, flags, buf);
- }
-
- private static void getArchiveLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- // Handle variables different
- if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf))
- return;
- boolean external= root.isExternal();
- if (external)
- getExternalArchiveLabel(root, flags, buf);
- else
- getInternalArchiveLabel(root, flags, buf);
- }
-
- private static boolean getVariableLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- try {
- IIncludePathEntry rawEntry= root.getRawIncludepathEntry();
- if (rawEntry != null && rawEntry.getEntryKind() == IIncludePathEntry.CPE_VARIABLE) {
- IPath path= rawEntry.getPath().makeRelative();
- if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
- int segements= path.segmentCount();
- if (segements > 0) {
- buf.append(path.segment(segements - 1));
- if (segements > 1) {
- buf.append(CONCAT_STRING);
- buf.append(path.removeLastSegments(1).toOSString());
- }
- } else {
- buf.append(path.toString());
- }
- } else {
- buf.append(path.toString());
- }
- buf.append(CONCAT_STRING);
- if (root.isExternal())
- buf.append(root.getPath().toOSString());
- else
- buf.append(root.getPath().makeRelative().toString());
- return true;
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e); // problems with class path
- }
- return false;
- }
-
- private static void getExternalArchiveLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- IPath path= root.getPath();
- if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
- int segements= path.segmentCount();
- if (segements > 0) {
- buf.append(path.segment(segements - 1));
- if (segements > 1 || path.getDevice() != null) {
- buf.append(CONCAT_STRING);
- buf.append(path.removeLastSegments(1).toOSString());
- }
- } else {
- buf.append(path.toOSString());
- }
- } else {
- buf.append(path.toOSString());
- }
- }
-
- private static void getInternalArchiveLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- IResource resource= root.getResource();
- boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
- boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root);
- if (rootQualified) {
- buf.append(root.getPath().makeRelative().toString());
- } else {
- buf.append(root.getDisplayName());
- if (referencedQualified) {
- buf.append(CONCAT_STRING);
- buf.append(resource.getParent().getFullPath().makeRelative().toString());
- } else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- buf.append(root.getParent().getPath().makeRelative().toString());
- }
- }
- }
-
- private static void getFolderLabel(IPackageFragmentRoot root, long flags, StringBuffer buf) {
- IResource resource= root.getResource();
- boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
- boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root);
- if (rootQualified) {
- buf.append(root.getPath().makeRelative().toString());
- } else {
- if (resource != null) {
- IPath projectRelativePath= resource.getProjectRelativePath();
- if (projectRelativePath.segmentCount() == 0) {
- buf.append(resource.getName());
- referencedQualified= false;
- } else {
- buf.append(projectRelativePath.toString());
- }
- } else
- buf.append(root.getDisplayName());
- if (referencedQualified) {
- buf.append(CONCAT_STRING);
- buf.append(resource.getProject().getName());
- } else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
- buf.append(CONCAT_STRING);
- buf.append(root.getParent().getDisplayName());
- }
- }
- }
-
- /**
- * Returns <code>true</code> if the given package fragment root is
- * referenced. This means it is own by a different project but is referenced
- * by the root's parent. Returns <code>false</code> if the given root
- * doesn't have an underlying resource.
- *
- *
- */
- private static boolean isReferenced(IPackageFragmentRoot root) {
- IResource resource= root.getResource();
- if (resource != null) {
- IProject jarProject= resource.getProject();
- IProject container= root.getJavaScriptProject().getProject();
- return !container.equals(jarProject);
- }
- return false;
- }
-
- private static void refreshPackageNamePattern() {
- String pattern= getPkgNamePatternForPackagesView();
- final String EMPTY_STRING= ""; //$NON-NLS-1$
- if (pattern.equals(fgPkgNamePattern))
- return;
- else if (pattern.length() == 0) {
- fgPkgNamePattern= EMPTY_STRING;
- fgPkgNameLength= -1;
- return;
- }
- fgPkgNamePattern= pattern;
- int i= 0;
- fgPkgNameChars= 0;
- fgPkgNamePrefix= EMPTY_STRING;
- fgPkgNamePostfix= EMPTY_STRING;
- while (i < pattern.length()) {
- char ch= pattern.charAt(i);
- if (Character.isDigit(ch)) {
- fgPkgNameChars= ch-48;
- if (i > 0)
- fgPkgNamePrefix= pattern.substring(0, i);
- if (i >= 0)
- fgPkgNamePostfix= pattern.substring(i+1);
- fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
- return;
- }
- i++;
- }
- fgPkgNamePrefix= pattern;
- fgPkgNameLength= pattern.length();
- }
-
- private static String getPkgNamePatternForPackagesView() {
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
- return ""; //$NON-NLS-1$
- return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
- }
-
- /**
- * Returns the label of a classpath container
- * @param containerPath The path of the container.
- * @param project The project the container is resolved in.
- * @return Returns the label of the classpath container
- * @throws JavaScriptModelException Thrown when the resolving of the container failed.
- */
- public static String getContainerEntryLabel(IPath containerPath, IJavaScriptProject project) throws JavaScriptModelException {
- IJsGlobalScopeContainer container= JavaScriptCore.getJsGlobalScopeContainer(containerPath, project);
- if (container != null) {
- return container.getDescription();
- }
- JsGlobalScopeContainerInitializer initializer= JavaScriptCore.getJsGlobalScopeContainerInitializer(containerPath.segment(0));
- if (initializer != null) {
- return initializer.getDescription(containerPath, project);
- }
- return containerPath.toString();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptLibrariesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptLibrariesAction.java
deleted file mode 100644
index d191bb6f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptLibrariesAction.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.Hashtable;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.packageview.NamespaceGroup;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BuildPathsPropertyPage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.CodeStylePreferencePage;
-
-
-/**
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptLibrariesAction implements IObjectActionDelegate {
-
- private IWorkbenchSite fSite;
- protected IJavaScriptProject project;
- protected static final Hashtable PROPS_TO_IDS = new Hashtable();
-
- {
- PROPS_TO_IDS.put("org.eclipse.wst.jsdt.internal.ui.configure.scope", BuildPathsPropertyPage.PROP_ID); //$NON-NLS-1$
- PROPS_TO_IDS.put("org.eclipse.wst.jsdt.internal.ui.configure.javascript.properties", CodeStylePreferencePage.PROP_ID); //$NON-NLS-1$
- PROPS_TO_IDS.put("org.eclipse.wst.jsdt.internal.ui.configure.source.folders", BuildPathsPropertyPage.PROP_ID); //$NON-NLS-1$
- //PROPS_TO_IDS.put("", BuildPathsPropertyPage.PROP_ID);
- //PROPS_TO_IDS.put("", BuildPathsPropertyPage.PROP_ID);
-
-
-
- }
-
-
- public void setActivePart(IAction arg0, IWorkbenchPart arg1) {
- fSite = arg1.getSite();
-
- }
-
-
- public void run(IAction arg0) {
- Object data = null;
- String ID = arg0.getId();
- String propertyPage = (String)PROPS_TO_IDS.get(ID);
-
- PreferencesUtil.createPropertyDialogOn(getShell(), project, propertyPage , null, data).open();
-
-
- }
-
-
- public void selectionChanged(IAction arg0, ISelection arg1) {
- if (arg1 instanceof IStructuredSelection) {
- IStructuredSelection selection = (IStructuredSelection) arg1;
- Object item = selection.getFirstElement();
-
- if (item instanceof NamespaceGroup) {
- item = ((NamespaceGroup) item).getPackageFragmentRoot();
- }
- if (item instanceof ProjectLibraryRoot) {
- ProjectLibraryRoot root = ((ProjectLibraryRoot) item);
- project = root.getProject();
- }
- }
-
- }
-
- protected Shell getShell() {
- if (fSite == null)
- return JavaScriptPlugin.getActiveWorkbenchShell();
-
- return fSite.getShell() != null ? fSite.getShell() : JavaScriptPlugin.getActiveWorkbenchShell();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSourceFoldersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSourceFoldersAction.java
deleted file mode 100644
index e1e102c9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSourceFoldersAction.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BuildPathsPropertyPage;
-
-/**
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- */
-public class JavaScriptSourceFoldersAction extends JavaScriptLibrariesAction {
-
- private static final int BUILD_PATH_PAGE_INDEX = 2;
-
- public void run(IAction arg0) {
- Map data = new HashMap();
- data.put(BuildPathsPropertyPage.DATA_PAGE_INDEX, new Integer(BUILD_PATH_PAGE_INDEX));
- String ID = arg0.getId();
- String propertyPage = (String)PROPS_TO_IDS.get(ID);
-
- PreferencesUtil.createPropertyDialogOn(getShell(), project, propertyPage , null, data).open();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSuperTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSuperTypeAction.java
deleted file mode 100644
index 6a70390a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptSuperTypeAction.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.internal.ui.preferences.BuildPathsPropertyPage;
-
-/**
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- */
-public class JavaScriptSuperTypeAction extends JavaScriptLibrariesAction {
-
- private static final int BUILD_PATH_PAGE_INDEX = 1;
-
- public void run(IAction arg0) {
- Map data = new HashMap();
- data.put(BuildPathsPropertyPage.DATA_PAGE_INDEX, new Integer(BUILD_PATH_PAGE_INDEX));
- String ID = arg0.getId();
- String propertyPage = (String)PROPS_TO_IDS.get(ID);
-
- PreferencesUtil.createPropertyDialogOn(getShell(), project, propertyPage , null, data).open();
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java
deleted file mode 100644
index 3b915b15..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java
+++ /dev/null
@@ -1,753 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaElementTransfer;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.SharedImages;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.PackageSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension;
-import org.eclipse.wst.jsdt.ui.text.IColorManager;
-
-/**
- * Central access point for the JavaScript UI plug-in (id <code>"org.eclipse.wst.jsdt.ui"</code>).
- * This class provides static methods for:
- * <ul>
- * <li> creating various kinds of selection dialogs to present a collection
- * of JavaScript elements to the user and let them make a selection.</li>
- * <li> opening a JavaScript editor on a compilation unit.</li>
- * </ul>
- * <p>
- * This class provides static methods and fields only; it is not intended to be
- * instantiated or subclassed by clients.
- * </p>
- * * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public final class JavaScriptUI {
-
- private static ISharedImages fgSharedImages= null;
-
- private JavaScriptUI() {
- // prevent instantiation of JavaScriptUI.
- }
-
- /**
- * The id of the JavaScript plug-in (value <code>"org.eclipse.wst.jsdt.ui"</code>).
- */
- public static final String ID_PLUGIN= "org.eclipse.wst.jsdt.ui"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript perspective
- * (value <code>"org.eclipse.wst.jsdt.ui.JavaPerspective"</code>).
- */
- public static final String ID_PERSPECTIVE= "org.eclipse.wst.jsdt.ui.JavaPerspective"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript action set
- * (value <code>"org.eclipse.wst.jsdt.ui.JavaActionSet"</code>).
- */
- public static final String ID_ACTION_SET= "org.eclipse.wst.jsdt.ui.JavaActionSet"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript Element Creation action set
- * (value <code>"org.eclipse.wst.jsdt.ui.JavaElementCreationActionSet"</code>).
- *
- *
- */
- public static final String ID_ELEMENT_CREATION_ACTION_SET= "org.eclipse.wst.jsdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript Coding action set
- * (value <code>"org.eclipse.wst.jsdt.ui.CodingActionSet"</code>).
- *
- *
- */
- public static final String ID_CODING_ACTION_SET= "org.eclipse.wst.jsdt.ui.CodingActionSet"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript action set for open actions
- * (value <code>"org.eclipse.wst.jsdt.ui.A_OpenActionSet"</code>).
- *
- *
- */
- public static final String ID_OPEN_ACTION_SET= "org.eclipse.wst.jsdt.ui.A_OpenActionSet"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript Search action set
- * (value <code>org.eclipse.wst.jsdt.ui.SearchActionSet"</code>).
- *
- *
- */
- public static final String ID_SEARCH_ACTION_SET= "org.eclipse.wst.jsdt.ui.SearchActionSet"; //$NON-NLS-1$
-
- /**
- * The editor part id of the editor that presents JavaScript compilation units
- * (value <code>"org.eclipse.wst.jsdt.ui.CompilationUnitEditor"</code>).
- */
- public static final String ID_CU_EDITOR= "org.eclipse.wst.jsdt.ui.CompilationUnitEditor"; //$NON-NLS-1$
-
- /**
- * The editor part id of the editor that presents JavaScript binary class files
- * (value <code>"org.eclipse.wst.jsdt.ui.ClassFileEditor"</code>).
- */
- public static final String ID_CF_EDITOR= "org.eclipse.wst.jsdt.ui.ClassFileEditor"; //$NON-NLS-1$
-
- /**
- * The editor part id of the code snippet editor
- * (value <code>"org.eclipse.wst.jsdt.ui.SnippetEditor"</code>).
- */
- public static final String ID_SNIPPET_EDITOR= "org.eclipse.wst.jsdt.ui.SnippetEditor"; //$NON-NLS-1$
-
- /**
- * The view part id of the Packages view
- * (value <code>"org.eclipse.wst.jsdt.ui.PackageExplorer"</code>).
- * <p>
- * When this id is used to access
- * a view part with <code>IWorkbenchPage.findView</code> or
- * <code>showView</code>, the returned <code>IViewPart</code>
- * can be safely cast to an <code>IPackagesViewPart</code>.
- * </p>
- *
- * @see IPackagesViewPart
- * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String)
- * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String)
- */
- public static final String ID_PACKAGES= "org.eclipse.wst.jsdt.ui.PackageExplorer"; //$NON-NLS-1$
-
- /**
- * The view part id of the type hierarchy part
- * (value <code>"org.eclipse.wst.jsdt.ui.TypeHierarchy"</code>).
- * <p>
- * When this id is used to access
- * a view part with <code>IWorkbenchPage.findView</code> or
- * <code>showView</code>, the returned <code>IViewPart</code>
- * can be safely cast to an <code>ITypeHierarchyViewPart</code>.
- * </p>
- *
- * @see ITypeHierarchyViewPart
- * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String)
- * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String)
- */
- public static final String ID_TYPE_HIERARCHY= "org.eclipse.wst.jsdt.ui.TypeHierarchy"; //$NON-NLS-1$
-
- /**
- * The view part id of the source (declaration) view
- * (value <code>"org.eclipse.wst.jsdt.ui.SourceView"</code>).
- *
- * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String)
- * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String)
- *
- */
- public static final String ID_SOURCE_VIEW= "org.eclipse.wst.jsdt.ui.SourceView"; //$NON-NLS-1$
-
- /**
- * The view part id of the Javadoc view
- * (value <code>"org.eclipse.wst.jsdt.ui.JavadocView"</code>).
- *
- * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String)
- * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String)
- *
- */
- public static final String ID_JAVADOC_VIEW= "org.eclipse.wst.jsdt.ui.JavadocView"; //$NON-NLS-1$
-
- /**
- * The id of the JavaScript Browsing Perspective
- * (value <code>"org.eclipse.wst.jsdt.ui.JavaBrowsingPerspective"</code>).
- *
- *
- */
- public static String ID_BROWSING_PERSPECTIVE= "org.eclipse.wst.jsdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$
-
- /**
- * The view part id of the JavaScript Browsing Projects view
- * (value <code>"org.eclipse.wst.jsdt.ui.ProjectsView"</code>).
- *
- *
- */
- public static String ID_PROJECTS_VIEW= "org.eclipse.wst.jsdt.ui.ProjectsView"; //$NON-NLS-1$
-
- /**
- * The view part id of the JavaScript Browsing Packages view
- * (value <code>"org.eclipse.wst.jsdt.ui.PackagesView"</code>).
- *
- *
- */
- public static String ID_PACKAGES_VIEW= "org.eclipse.wst.jsdt.ui.PackagesView"; //$NON-NLS-1$
-
- /**
- * The view part id of the JavaScript Browsing Types view
- * (value <code>"org.eclipse.wst.jsdt.ui.TypesView"</code>).
- *
- *
- */
- public static String ID_TYPES_VIEW= "org.eclipse.wst.jsdt.ui.TypesView"; //$NON-NLS-1$
-
- /**
- * The view part id of the JavaScript Browsing Members view
- * (value <code>"org.eclipse.wst.jsdt.ui.MembersView"</code>).
- *
- *
- */
- public static String ID_MEMBERS_VIEW= "org.eclipse.wst.jsdt.ui.MembersView"; //$NON-NLS-1$
-
- /**
- * Returns the shared images for the JavaScript UI.
- *
- * @return the shared images manager
- */
- public static ISharedImages getSharedImages() {
- if (fgSharedImages == null)
- fgSharedImages= new SharedImages();
-
- return fgSharedImages;
- }
-
- /**
- * Creates a selection dialog that lists all packages of the given JavaScript project.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected package (of type
- * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param project the JavaScript project
- * @param style flags defining the style of the dialog; the valid flags are:
- * <code>IJavaScriptElementSearchConstants.CONSIDER_BINARIES</code>, indicating that
- * packages from binary package fragment roots should be included in addition
- * to those from source package fragment roots;
- * <code>IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that
- * packages from required projects should be included as well.
- * @param filter the initial pattern to filter the set of packages. For example "com" shows
- * all packages starting with "com". The meta character '?' representing any character and
- * '*' representing any string are supported. Clients can pass an empty string if no filtering
- * is required.
- * @return a new selection dialog
- * @exception JavaScriptModelException if the selection dialog could not be opened
- *
- *
- */
- public static SelectionDialog createPackageDialog(Shell parent, IJavaScriptProject project, int style, String filter) throws JavaScriptModelException {
- Assert.isTrue((style | IJavaScriptElementSearchConstants.CONSIDER_BINARIES | IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) ==
- (IJavaScriptElementSearchConstants.CONSIDER_BINARIES | IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS));
-
- IPackageFragmentRoot[] roots= null;
- if ((style & IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) {
- roots= project.getAllPackageFragmentRoots();
- } else {
- roots= project.getPackageFragmentRoots();
- }
-
- List consideredRoots= null;
- if ((style & IJavaScriptElementSearchConstants.CONSIDER_BINARIES) != 0) {
- consideredRoots= Arrays.asList(roots);
- } else {
- consideredRoots= new ArrayList(roots.length);
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (root.getKind() != IPackageFragmentRoot.K_BINARY)
- consideredRoots.add(root);
-
- }
- }
-
- IJavaScriptSearchScope searchScope= SearchEngine.createJavaSearchScope((IJavaScriptElement[])consideredRoots.toArray(new IJavaScriptElement[consideredRoots.size()]));
- BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
- if (style == 0 || style == IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) {
- return createPackageDialog(parent, context, searchScope, false, true, filter);
- } else {
- return createPackageDialog(parent, context, searchScope, false, false, filter);
- }
- }
-
- /**
- * Creates a selection dialog that lists all packages of the given JavaScript search scope.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected package (of type
- * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param context the runnable context to run the search in
- * @param scope the scope defining the available packages.
- * @param multipleSelection true if multiple selection is allowed
- * @param removeDuplicates true if only one package is shown per package name
- * @param filter the initial pattern to filter the set of packages. For example "com" shows
- * all packages starting with "com". The meta character '?' representing any character and
- * '*' representing any string are supported. Clients can pass an empty string if no filtering
- * is required.
- * @return a new selection dialog
- *
- *
- */
- public static SelectionDialog createPackageDialog(Shell parent, IRunnableContext context, IJavaScriptSearchScope scope,
- boolean multipleSelection, boolean removeDuplicates, String filter) {
-
- int flag= removeDuplicates ? PackageSelectionDialog.F_REMOVE_DUPLICATES : 0;
- PackageSelectionDialog dialog= new PackageSelectionDialog(parent, context, flag, scope);
- dialog.setFilter(filter);
- dialog.setIgnoreCase(false);
- dialog.setMultipleSelection(multipleSelection);
- return dialog;
- }
-
- /**
- * Creates a selection dialog that lists all packages of the given JavaScript project.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected package (of type
- * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param project the JavaScript project
- * @param style flags defining the style of the dialog; the valid flags are:
- * <code>IJavaScriptElementSearchConstants.CONSIDER_BINARIES</code>, indicating that
- * packages from binary package fragment roots should be included in addition
- * to those from source package fragment roots;
- * <code>IJavaScriptElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that
- * packages from required projects should be included as well.
- * @return a new selection dialog
- * @exception JavaScriptModelException if the selection dialog could not be opened
- */
- public static SelectionDialog createPackageDialog(Shell parent, IJavaScriptProject project, int style) throws JavaScriptModelException {
- return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$
- }
-
- /**
- * Creates a selection dialog that lists all packages under the given package
- * fragment root.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected package (of type
- * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param root the package fragment root
- * @param filter the initial pattern to filter the set of packages. For example "com" shows
- * all packages starting with "com". The meta character '?' representing any character and
- * '*' representing any string are supported. Clients can pass an empty string if no filtering
- * is required.
- * @return a new selection dialog
- * @exception JavaScriptModelException if the selection dialog could not be opened
- *
- *
- */
- public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root, String filter) throws JavaScriptModelException {
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {root});
- BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
- return createPackageDialog(parent, context, scope, false, true, filter);
- }
-
- /**
- * Creates a selection dialog that lists all packages under the given package
- * fragment root.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected package (of type
- * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param root the package fragment root
- * @return a new selection dialog
- * @exception JavaScriptModelException if the selection dialog could not be opened
- */
- public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaScriptModelException {
- return createPackageDialog(parent, root, ""); //$NON-NLS-1$
- }
-
- /**
- * Creates a selection dialog that lists all types in the given project.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected type(s) (of type
- * <code>IType</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param context the runnable context used to show progress when the dialog
- * is being populated
- * @param project the JavaScript project
- * @param style flags defining the style of the dialog; the only valid values are
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_INTERFACES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ANNOTATION_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ENUMS</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES</code>
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS</code>. Please note that
- * the bitwise OR combination of the elementary constants is not supported.
- * @param multipleSelection <code>true</code> if multiple selection is allowed
- *
- * @return a new selection dialog
- *
- * @exception JavaScriptModelException if the selection dialog could not be opened
- */
- public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IProject project, int style, boolean multipleSelection) throws JavaScriptModelException {
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptProject[] { JavaScriptCore.create(project) });
- return createTypeDialog(parent, context, scope, style, multipleSelection);
- }
-
- /**
- * Creates a selection dialog that lists all types in the given scope.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected type(s) (of type
- * <code>IType</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param context the runnable context used to show progress when the dialog
- * is being populated
- * @param scope the scope that limits which types are included
- * @param style flags defining the style of the dialog; the only valid values are
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_INTERFACES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ANNOTATION_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ENUMS</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES</code>
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS</code>. Please note that
- * the bitwise OR combination of the elementary constants is not supported.
- * @param multipleSelection <code>true</code> if multiple selection is allowed
- *
- * @return a new selection dialog
- *
- * @exception JavaScriptModelException if the selection dialog could not be opened
- */
- public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaScriptSearchScope scope, int style, boolean multipleSelection) throws JavaScriptModelException {
- return createTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$
- }
-
- /**
- * Creates a selection dialog that lists all types in the given scope.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected type(s) (of type
- * <code>IType</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param context the runnable context used to show progress when the dialog
- * is being populated
- * @param scope the scope that limits which types are included
- * @param style flags defining the style of the dialog; the only valid values are
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_INTERFACES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ANNOTATION_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ENUMS</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES</code>
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS</code>. Please note that
- * the bitwise OR combination of the elementary constants is not supported.
- * @param multipleSelection <code>true</code> if multiple selection is allowed
- * @param filter the initial pattern to filter the set of types. For example "Abstract" shows
- * all types starting with "abstract". The meta character '?' representing any character and
- * '*' representing any string are supported. Clients can pass an empty string if no filtering
- * is required.
- *
- * @return a new selection dialog
- *
- * @exception JavaScriptModelException if the selection dialog could not be opened
- *
- *
- */
- public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaScriptSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaScriptModelException {
- return createTypeDialog(parent, context, scope, style, multipleSelection, filter, null);
- }
-
- /**
- * Creates a selection dialog that lists all types in the given scope.
- * The caller is responsible for opening the dialog with <code>Window.open</code>,
- * and subsequently extracting the selected type(s) (of type
- * <code>IType</code>) via <code>SelectionDialog.getResult</code>.
- *
- * @param parent the parent shell of the dialog to be created
- * @param context the runnable context used to show progress when the dialog
- * is being populated
- * @param scope the scope that limits which types are included
- * @param style flags defining the style of the dialog; the only valid values are
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_INTERFACES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ANNOTATION_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ENUMS</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES</code>,
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES</code>
- * <code>IJavaScriptElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS</code>. Please note that
- * the bitwise OR combination of the elementary constants is not supported.
- * @param multipleSelection <code>true</code> if multiple selection is allowed
- * @param filter the initial pattern to filter the set of types. For example "Abstract" shows
- * all types starting with "abstract". The meta character '?' representing any character and
- * '*' representing any string are supported. Clients can pass an empty string if no filtering
- * is required.
- * @param extension a user interface extension to the type selection dialog or <code>null</code>
- * if no extension is desired
- *
- * @return a new selection dialog
- *
- * @exception JavaScriptModelException if the selection dialog could not be opened
- *
- *
- */
- public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaScriptSearchScope scope, int style,
- boolean multipleSelection, String filter, TypeSelectionExtension extension) throws JavaScriptModelException {
- int elementKinds= 0;
- if (style == IJavaScriptElementSearchConstants.CONSIDER_ALL_TYPES) {
- elementKinds= IJavaScriptSearchConstants.TYPE;
- } else if (style == IJavaScriptElementSearchConstants.CONSIDER_CLASSES) {
- elementKinds= IJavaScriptSearchConstants.CLASS;
- } else {
- throw new IllegalArgumentException("Invalid style constant."); //$NON-NLS-1$
- }
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(parent, multipleSelection,
- context, scope, elementKinds, extension);
- dialog.setMessage(JavaUIMessages.JavaUI_defaultDialogMessage);
- dialog.setInitialPattern(filter);
- return dialog;
- }
-
-
-
- /**
- * Opens an editor on the given JavaScript element in the active page. Valid elements are all JavaScript elements that are {@link ISourceReference}.
- * For elements inside a compilation unit or class file, the parent is opened in the editor is opened and the element revealed.
- * If there already is an open JavaScript editor for the given element, it is returned.
- *
- * @param element the input element; either a compilation unit
- * (<code>IJavaScriptUnit</code>) or a class file (<code>IClassFile</code>) or source references inside.
- * @return returns the editor part of the opened editor or <code>null</code> if the element is not a {@link ISourceReference} or the
- * file was opened in an external editor.
- * @exception PartInitException if the editor could not be initialized or no workbench page is active
- * @exception JavaScriptModelException if this element does not exist or if an exception occurs while accessing its underlying resource
- */
- public static IEditorPart openInEditor(IJavaScriptElement element) throws JavaScriptModelException, PartInitException {
- return openInEditor(element, true, true);
- }
-
- /**
- * Opens an editor on the given JavaScript element in the active page. Valid elements are all JavaScript elements that are {@link ISourceReference}.
- * For elements inside a compilation unit or class file, the parent is opened in the editor is opened.
- * If there already is an open JavaScript editor for the given element, it is returned.
- *
- * @param element the input element; either a compilation unit
- * (<code>IJavaScriptUnit</code>) or a class file (<code>IClassFile</code>) or source references inside.
- * @param activate if set, the editor will be activated.
- * @param reveal if set, the element will be revealed.
- * @return returns the editor part of the opened editor or <code>null</code> if the element is not a {@link ISourceReference} or the
- * file was opened in an external editor.
- * @exception PartInitException if the editor could not be initialized or no workbench page is active
- * @exception JavaScriptModelException if this element does not exist or if an exception occurs while accessing its underlying resource
- *
- */
- public static IEditorPart openInEditor(IJavaScriptElement element, boolean activate, boolean reveal) throws JavaScriptModelException, PartInitException {
- if (!(element instanceof ISourceReference)) {
- return null;
- }
- IEditorPart part= EditorUtility.openInEditor(element, activate);
- if (reveal && part != null) {
- EditorUtility.revealInEditor(part, element);
- }
- return part;
- }
-
- /**
- * Reveals the given JavaScript element in the given editor. If the element is not an instance
- * of <code>ISourceReference</code> this method result in a NOP. If it is a source
- * reference no checking is done if the editor displays a compilation unit or class file that
- * contains the source reference element. The editor simply reveals the source range
- * denoted by the given element.
- *
- * @param part the editor displaying a compilation unit or class file
- * @param element the element to be revealed
- *
- *
- */
- public static void revealInEditor(IEditorPart part, IJavaScriptElement element) {
- EditorUtility.revealInEditor(part, element);
- }
-
- /**
- * Returns the working copy manager for the JavaScript UI plug-in.
- *
- * @return the working copy manager for the JavaScript UI plug-in
- */
- public static IWorkingCopyManager getWorkingCopyManager() {
- return JavaScriptPlugin.getDefault().getWorkingCopyManager();
- }
-
- /**
- * Returns the JavaScript element wrapped by the given editor input.
- *
- * @param editorInput the editor input
- * @return the JavaScript element wrapped by <code>editorInput</code> or <code>null</code> if none
- *
- */
- public static IJavaScriptElement getEditorInputJavaElement(IEditorInput editorInput) {
- // Performance: check working copy manager first: this is faster
- IJavaScriptElement je= JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput);
- if (je != null)
- return je;
-
- return (IJavaScriptElement)editorInput.getAdapter(IJavaScriptElement.class);
- }
-
- /**
- * Returns the DocumentProvider used for JavaScript compilation units.
- *
- * @return the DocumentProvider for JavaScript compilation units.
- *
- * @see IDocumentProvider
- *
- */
- public static IDocumentProvider getDocumentProvider() {
- return JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider();
- }
-
- /**
- * Returns the Javadoc location for library's classpath entry or <code>null</code> if no
- * location is available. Note that only classpath entries of kind {@link IIncludePathEntry#CPE_LIBRARY} and
- * {@link IIncludePathEntry#CPE_VARIABLE} support Javadoc locations.
- *
- * @param entry the classpath entry to get the Javadoc location for
- * @return the Javadoc location or<code>null</code> if no Javadoc location is available
- * @throws IllegalArgumentException Thrown when the entry is <code>null</code> or not of kind
- * {@link IIncludePathEntry#CPE_LIBRARY} or {@link IIncludePathEntry#CPE_VARIABLE}.
- *
- *
- */
- public static URL getLibraryJSdocLocation(IIncludePathEntry entry) {
- return JavaDocLocations.getLibraryJavadocLocation(entry);
- }
-
- /**
- * Sets the Javadoc location for a JavaScript project. This location is used for
- * all types located in the project's source folders.
- *
- * @param project the project
- * @param url the Javadoc location to set. This location should contain index.html and
- * a file 'package-list'. <code>null</code> clears the current documentation
- * location.
- *
- *
- */
- public static void setProjectJSdocLocation(IJavaScriptProject project, URL url) {
- JavaDocLocations.setProjectJavadocLocation(project, url);
- }
-
- /**
- * Returns the Javadoc location for a JavaScript project or <code>null</code> if no
- * location is available. This location is used for all types located in the project's
- * source folders.
- *
- * @param project the project
- * @return the Javadoc location for a JavaScript project or <code>null</code>
- *
- *
- */
- public static URL getProjectJSdocLocation(IJavaScriptProject project) {
- return JavaDocLocations.getProjectJavadocLocation(project);
- }
-
- /**
- * Returns the Javadoc base URL for an element. The base location contains the
- * index file. This location doesn't have to exist. Returns <code>null</code>
- * if no javadoc location has been attached to the element's library or project.
- * Example of a returned URL is <i>http://www.junit.org/junit/javadoc</i>.
- *
- * @param element the element for which the documentation URL is requested.
- * @return the base location
- * @throws JavaScriptModelException thrown when the element can not be accessed
- *
- *
- */
- public static URL getJSdocBaseLocation(IJavaScriptElement element) throws JavaScriptModelException {
- return JavaDocLocations.getJavadocBaseLocation(element);
- }
-
- /**
- * Returns the Javadoc URL for an element. Example of a returned URL is
- * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html</i>.
- * This returned location doesn't have to exist. Returns <code>null</code>
- * if no javadoc location has been attached to the element's library or
- * project.
- *
- * @param element the element for which the documentation URL is requested.
- * @param includeAnchor If set, the URL contains an anchor for member references:
- * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult)</i>. Note
- * that this involves type resolving and is a more expensive call than without anchor.
- * @return the Javadoc URL for the element
- * @throws JavaScriptModelException thrown when the element can not be accessed
- *
- *
- */
- public static URL getJSdocLocation(IJavaScriptElement element, boolean includeAnchor) throws JavaScriptModelException {
- return JavaDocLocations.getJavadocLocation(element, includeAnchor);
- }
-
- /**
- * Returns the transfer instance used to copy/paste JavaScript elements to
- * and from the clipboard. Objects managed by this transfer instance
- * are of type <code>IJavaScriptElement[]</code>. So to access data from the
- * clipboard clients should use the following code snippet:
- * <pre>
- * IJavaScriptElement[] elements=
- * (IJavaScriptElement[])clipboard.getContents(JavaScriptUI.getJavaElementClipboardTransfer());
- * </pre>
- *
- * To put elements into the clipboard use the following snippet:
- *
- * <pre>
- * IJavaScriptElement[] javaElements= ...;
- * clipboard.setContents(
- * new Object[] { javaElements },
- * new Transfer[] { JavaScriptUI.getJavaElementClipboardTransfer() } );
- * </pre>
- *
- * @return returns the transfer object used to copy/paste JavaScript elements
- * to and from the clipboard
- *
- *
- */
- public static Transfer getJavaElementClipboardTransfer() {
- return JavaElementTransfer.getInstance();
- }
-
- /**
- * Returns the color manager the JavaScript UI plug-in which is used to manage
- * any Java-specific colors needed for such things like syntax highlighting.
- *
- * @return the color manager to be used for JavaScript text viewers
- *
- */
- public static IColorManager getColorManager() {
- return JavaScriptPlugin.getDefault().getJavaTextTools().getColorManager();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/Messages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/Messages.java
deleted file mode 100644
index d93f8106..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/Messages.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-/**
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- */
-public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.ui.messages"; //$NON-NLS-1$
-
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
-
- private Messages() {
- }
-
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- }
- catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/OverrideIndicatorLabelDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/OverrideIndicatorLabelDecorator.java
deleted file mode 100644
index 6bcf283c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/OverrideIndicatorLabelDecorator.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ILightweightLabelDecorator;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.SimpleName;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.util.JdtFlags;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageImageDescriptor;
-
-/**
- * LabelDecorator that decorates an method's image with override or implements overlays.
- * The viewer using this decorator is responsible for updating the images on element changes.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OverrideIndicatorLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator {
-
- private ImageDescriptorRegistry fRegistry;
- private boolean fUseNewRegistry= false;
-
- /**
- * Creates a decorator. The decorator creates an own image registry to cache
- * images.
- */
- public OverrideIndicatorLabelDecorator() {
- this(null);
- fUseNewRegistry= true;
- }
-
- /*
- * Creates decorator with a shared image registry.
- *
- * @param registry The registry to use or <code>null</code> to use the JavaScript plugin's
- * image registry.
- */
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param registry The registry to use.
- */
- public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) {
- fRegistry= registry;
- }
-
- private ImageDescriptorRegistry getRegistry() {
- if (fRegistry == null) {
- fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : JavaScriptPlugin.getImageDescriptorRegistry();
- }
- return fRegistry;
- }
-
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateText(String, Object)
- */
- public String decorateText(String text, Object element) {
- return text;
- }
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateImage(Image, Object)
- */
- public Image decorateImage(Image image, Object element) {
- int adornmentFlags= computeAdornmentFlags(element);
- if (adornmentFlags != 0) {
- ImageDescriptor baseImage= new ImageImageDescriptor(image);
- Rectangle bounds= image.getBounds();
- return getRegistry().get(new JavaScriptElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
- }
- return image;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param element The element to decorate
- * @return Resulting decorations (combination of JavaScriptElementImageDescriptor.IMPLEMENTS
- * and JavaScriptElementImageDescriptor.OVERRIDES)
- */
- public int computeAdornmentFlags(Object element) {
- if (element instanceof IFunction) {
- try {
- IFunction method= (IFunction) element;
- if (!method.getJavaScriptProject().isOnIncludepath(method)) {
- return 0;
- }
- int flags= method.getFlags();
- if (!method.isConstructor() && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) {
- int res= getOverrideIndicators(method);
- return res;
- }
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- JavaScriptPlugin.log(e);
- }
- }
- }
- return 0;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param method The element to decorate
- * @return Resulting decorations (combination of JavaScriptElementImageDescriptor.IMPLEMENTS
- * and JavaScriptElementImageDescriptor.OVERRIDES)
- * @throws JavaScriptModelException
- */
- protected int getOverrideIndicators(IFunction method) throws JavaScriptModelException {
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST((IJavaScriptElement) method.getOpenable(), ASTProvider.WAIT_ACTIVE_ONLY, null);
- if (astRoot != null) {
- int res= findInHierarchyWithAST(astRoot, method);
- if (res != -1) {
- return res;
- }
- }
-
- IType type= method.getDeclaringType();
- if (type==null)
- return 0;
-
- MethodOverrideTester methodOverrideTester= SuperTypeHierarchyCache.getMethodOverrideTester(type);
- IFunction defining= methodOverrideTester.findOverriddenMethod(method, true);
- if (defining != null) {
- if (JdtFlags.isAbstract(defining)) {
- return JavaScriptElementImageDescriptor.IMPLEMENTS;
- } else {
- return JavaScriptElementImageDescriptor.OVERRIDES;
- }
- }
- return 0;
- }
-
- private int findInHierarchyWithAST(JavaScriptUnit astRoot, IFunction method) throws JavaScriptModelException {
- ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
- if (node instanceof SimpleName && node.getParent() instanceof FunctionDeclaration) {
- IFunctionBinding binding= ((FunctionDeclaration) node.getParent()).resolveBinding();
- if (binding != null) {
- IFunctionBinding defining= Bindings.findOverriddenMethod(binding, true);
- if (defining != null) {
- if (JdtFlags.isAbstract(defining)) {
- return JavaScriptElementImageDescriptor.IMPLEMENTS;
- } else {
- return JavaScriptElementImageDescriptor.OVERRIDES;
- }
- }
- return 0;
- }
- }
- return -1;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#addListener(ILabelProviderListener)
- */
- public void addListener(ILabelProviderListener listener) {
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#dispose()
- */
- public void dispose() {
- if (fRegistry != null && fUseNewRegistry) {
- fRegistry.dispose();
- }
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#isLabelProperty(Object, String)
- */
- public boolean isLabelProperty(Object element, String property) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
- */
- public void removeListener(ILabelProviderListener listener) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration)
- */
- public void decorate(Object element, IDecoration decoration) {
- int adornmentFlags= computeAdornmentFlags(element);
- if ((adornmentFlags & JavaScriptElementImageDescriptor.IMPLEMENTS) != 0) {
- if ((adornmentFlags & JavaScriptElementImageDescriptor.SYNCHRONIZED) != 0) {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_SYNCH_AND_IMPLEMENTS);
- } else {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_IMPLEMENTS);
- }
- } else if ((adornmentFlags & JavaScriptElementImageDescriptor.OVERRIDES) != 0) {
- if ((adornmentFlags & JavaScriptElementImageDescriptor.SYNCHRONIZED) != 0) {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_SYNCH_AND_OVERRIDES);
- } else {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_OVERRIDES);
- }
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/PreferenceConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/PreferenceConstants.java
deleted file mode 100644
index 8f5055ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/PreferenceConstants.java
+++ /dev/null
@@ -1,3772 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.preferences.DefaultScope;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceConverter;
-import org.eclipse.jface.resource.ColorRegistry;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.ui.texteditor.AbstractTextEditor;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.fix.CleanUpConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaThemeConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings;
-import org.eclipse.wst.jsdt.internal.ui.preferences.NewJavaProjectPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.FormatterProfileManager;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants;
-
-/**
- * Preference constants used in the JDT-UI preference store. Clients should only read the
- * JDT-UI preference store using these values. Clients are not allowed to modify the
- * preference store programmatically.
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class PreferenceConstants {
-
- private PreferenceConstants() {
- }
-
- /**
- * A named preference that controls return type rendering of methods in the UI.
- * <p>
- * Value is of type <code>Boolean</code>: if <code>true</code> return types
- * are rendered
- * </p>
- */
- public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.wst.jsdt.ui.methodreturntype";//$NON-NLS-1$
-
- /**
- * A named preference that controls type parameter rendering of methods in the UI.
- * <p>
- * Value is of type <code>Boolean</code>: if <code>true</code> return types
- * are rendered
- * </p>
- *
- */
- public static final String APPEARANCE_METHOD_TYPEPARAMETERS= "org.eclipse.wst.jsdt.ui.methodtypeparametesr";//$NON-NLS-1$
-
- /**
- * A named preference that controls if quick assist light bulbs are shown.
- * <p>
- * Value is of type <code>Boolean</code>: if <code>true</code> light bulbs are shown
- * for quick assists.
- * </p>
- *
- *
- */
- public static final String EDITOR_QUICKASSIST_LIGHTBULB="org.eclipse.wst.jsdt.quickassist.lightbulb"; //$NON-NLS-1$
-
-
-
- /**
- * A named preference that defines the pattern used for package name compression.
- * <p>
- * Value is of type <code>String</code>. For example for the given package name 'org.eclipse.wst.jsdt' pattern
- * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'.
- * </p>
- */
- public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$
-
- /**
- * A named preference that controls if package name compression is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW
- */
- public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.wst.jsdt.ui.compresspackagenames";//$NON-NLS-1$
-
- /**
- * A named preference that controls if empty inner packages are folded in
- * the hierarchical mode of the package explorer.
- * <p>
- * Value is of type <code>Boolean</code>: if <code>true</code> empty
- * inner packages are folded.
- * </p>
- *
- */
- public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.wst.jsdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$
-
- /**
- * A named preference that defines how member elements are ordered by the
- * JavaScript views using the <code>JavaElementSorter</code>.
- * <p>
- * Value is of type <code>String</code>: A comma separated list of the
- * following entries. Each entry must be in the list, no duplication. List
- * order defines the sort order.
- * <ul>
- * <li><b>T</b>: Types</li>
- * <li><b>C</b>: Constructors</li>
- * <li><b>I</b>: Initializers</li>
- * <li><b>M</b>: Methods</li>
- * <li><b>F</b>: Fields</li>
- * <li><b>SI</b>: Static Initializers</li>
- * <li><b>SM</b>: Static Methods</li>
- * <li><b>SF</b>: Static Fields</li>
- * </ul>
- * </p>
- *
- */
- public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$
-
- /**
- * A named preference that defines how member elements are ordered by visibility in the
- * JavaScript views using the <code>JavaElementSorter</code>.
- * <p>
- * Value is of type <code>String</code>: A comma separated list of the
- * following entries. Each entry must be in the list, no duplication. List
- * order defines the sort order.
- * <ul>
- * <li><b>B</b>: Public</li>
- * <li><b>V</b>: Private</li>
- * <li><b>R</b>: Protected</li>
- * <li><b>D</b>: Default</li>
- * </ul>
- * </p>
- *
- */
- public static final String APPEARANCE_VISIBILITY_SORT_ORDER= "org.eclipse.wst.jsdt.ui.visibility.order"; //$NON-NLS-1$
-
- /**
- * A named preferences that controls if JavaScript elements are also sorted by
- * visibility.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER= "org.eclipse.wst.jsdt.ui.enable.visibility.order"; //$NON-NLS-1$
-
- /**
- * A named preference that controls category rendering of JavaScript elements in the UI.
- * <p>
- * Value is of type <code>Boolean</code>: if <code>true</code> category is rendered
- * </p>
- *
- */
- public static final String APPEARANCE_CATEGORY= "org.eclipse.wst.jsdt.ui.category";//$NON-NLS-1$
-
- /**
- * The symbolic font name for the font used to display Javadoc
- * (value <code>"org.eclipse.wst.jsdt.ui.javadocfont"</code>).
- *
- *
- */
- public final static String APPEARANCE_JAVADOC_FONT= "org.eclipse.wst.jsdt.ui.javadocfont"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if prefix removal during setter/getter generation is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated Use JavaScriptCore preference store (key JavaScriptCore.
- * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
- */
- public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.wst.jsdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$
-
- /**
- * A named preference that holds a list of prefixes to be removed from a local variable to compute setter
- * and getter names.
- * <p>
- * Value is of type <code>String</code>: comma separated list of prefixed
- * </p>
- *
- * @deprecated Use JavaScriptCore preference store (key JavaScriptCore.
- * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
- */
- public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.wst.jsdt.ui.gettersetter.prefix.list";//$NON-NLS-1$
-
- /**
- * A named preference that controls if suffix removal during setter/getter generation is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated Use JavaScriptCore preference store (key JavaScriptCore.
- * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
- */
- public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.wst.jsdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$
-
- /**
- * A named preference that holds a list of suffixes to be removed from a local variable to compute setter
- * and getter names.
- * <p>
- * Value is of type <code>String</code>: comma separated list of suffixes
- * </p>
- * @deprecated Use setting from JavaScriptCore preference store (key JavaScriptCore.
- * CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES)
- */
- public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.wst.jsdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the keyword "this" will be added
- * automatically to field accesses in generated methods.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.wst.jsdt.ui.keywordthis"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether to use the prefix "is" or the prefix "get" for
- * automatically created getters which return a boolean field.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.wst.jsdt.ui.gettersetter.use.is"; //$NON-NLS-1$
-
-
- /**
- * A named preference that defines the preferred variable names for exceptions in
- * catch clauses.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- */
- public static final String CODEGEN_EXCEPTION_VAR_NAME= "org.eclipse.wst.jsdt.ui.exception.name"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if comment stubs will be added
- * automatically to newly created types and methods.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.wst.jsdt.ui.javadoc"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether to add a override annotation for newly created methods
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String CODEGEN_USE_OVERRIDE_ANNOTATION= "org.eclipse.wst.jsdt.ui.overrideannotation"; //$NON-NLS-1$
-
- /**
- * A named preference that holds a list of semicolon separated fully qualified type names with wild card characters.
- *
- */
- public static final String TYPEFILTER_ENABLED= "org.eclipse.wst.jsdt.ui.typefilter.enabled"; //$NON-NLS-1$
-
- /**
- * A named preference that holds a list of semicolon separated fully qualified type names with wild card characters.
- *
- */
- public static final String TYPEFILTER_DISABLED= "org.eclipse.wst.jsdt.ui.typefilter.disabled"; //$NON-NLS-1$
-
-
- /**
- * A named preference that holds a list of semicolon separated package names. The list specifies the import order used by
- * the "Organize Imports" operation.
- * <p>
- * Value is of type <code>String</code>: semicolon separated list of package
- * names
- * </p>
- */
- public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.wst.jsdt.ui.importorder"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies the number of imports added before a star-import declaration is used.
- * <p>
- * Value is of type <code>Integer</code>: positive value specifying the number of non star-import is used
- * </p>
- */
- public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.wst.jsdt.ui.ondemandthreshold"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies the number of static imports added before a star-import declaration is used.
- * <p>
- * Value is of type <code>Integer</code>: positive value specifying the number of non star-import is used
- * </p>
- *
- */
- public static final String ORGIMPORTS_STATIC_ONDEMANDTHRESHOLD= "org.eclipse.wst.jsdt.ui.staticondemandthreshold"; //$NON-NLS-1$
-
- /**
- * A named preferences that controls if types that start with a lower case letters get added by the
- * "Organize Import" operation.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.wst.jsdt.ui.ignorelowercasenames"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies whether children of a compilation unit are shown in the package explorer.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public static final String SHOW_CU_CHILDREN= "org.eclipse.wst.jsdt.ui.packages.cuchildren"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the projects view's selection is
- * linked to the active editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.wst.jsdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the packages view's selection is
- * linked to the active editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.wst.jsdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$
-
-
- /* supertype preferences */
- public static final String SUPER_TYPE_CONTAINER= "org.eclipse.wst.jsdt.ui.superType.container"; //$NON-NLS-1$
- public static final String SUPER_TYPE_NAME= "org.eclipse.wst.jsdt.ui.superType.name"; //$NON-NLS-1$
-
-
- /**
- * A named preference that controls whether the types view's selection is
- * linked to the active editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.wst.jsdt.ui.browsing.typestoeditor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the members view's selection is
- * linked to the active editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.wst.jsdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$
- /**
- * A named preference that controls whether new projects are generated using source and output folder.
- * <p>
- * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and
- * output folder. If <code>false</code> source and output folder equals to the project.
- * </p>
- */
- public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.wst.jsdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies the source folder name used when creating a new JavaScript project. Value is inactive
- * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- * @see #SRCBIN_FOLDERS_IN_NEWPROJ
- */
- public static final String SRCBIN_SRCNAME= "org.eclipse.wst.jsdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies the output folder name used when creating a new JavaScript project. Value is inactive
- * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- * @deprecated - there is no output
- * @see #SRCBIN_FOLDERS_IN_NEWPROJ
- */
- public static final String SRCBIN_BINNAME= "org.eclipse.wst.jsdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$
-
- /**
- * A named preference that holds a list of possible JRE libraries used by the New JavaScript Project wizard. A library
- * consists of a description and an arbitrary number of <code>IIncludePathEntry</code>s, that will represent the
- * JRE on the new project's class path.
- * <p>
- * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries.
- * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients
- * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string
- * and the methods <code>decodeJRELibraryDescription(String)</code> and <code>
- * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array
- * of class path entries from an encoded string.
- * </p>
- *
- * @see #NEWPROJECT_JRELIBRARY_INDEX
- * @see #encodeJRELibrary(String, IIncludePathEntry[])
- * @see #decodeJRELibraryDescription(String)
- * @see #decodeJRELibraryClasspathEntries(String)
- */
- public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.wst.jsdt.ui.wizards.jre.list"; //$NON-NLS-1$
-
- /**
- * A named preferences that specifies the current active JRE library.
- * <p>
- * Value is of type <code>Integer</code>: an index into the list of possible JRE libraries.
- * </p>
- *
- * @see #NEWPROJECT_JRELIBRARY_LIST
- */
- public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.wst.jsdt.ui.wizards.jre.index"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the behavior when double clicking on a container in the packages view.
- * <p>
- * Value is of type <code>String</code>: possible values are <code>
- * DOUBLE_CLICK_GOES_INTO</code> or <code>
- * DOUBLE_CLICK_EXPANDS</code>.
- * </p>
- *
- * @see #DOUBLE_CLICK_EXPANDS
- * @see #DOUBLE_CLICK_GOES_INTO
- */
- public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>DOUBLE_CLICK</code>.
- *
- * @see #DOUBLE_CLICK
- */
- public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>DOUBLE_CLICK</code>.
- *
- * @see #DOUBLE_CLICK
- */
- public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether JavaScript views update their presentation while editing or when saving the
- * content of an editor.
- * <p>
- * Value is of type <code>String</code>: possible values are <code>
- * UPDATE_ON_SAVE</code> or <code>
- * UPDATE_WHILE_EDITING</code>.
- * </p>
- *
- * @see #UPDATE_ON_SAVE
- * @see #UPDATE_WHILE_EDITING
- * @deprecated Since 3.0, views now always update while editing
- */
- public static final String UPDATE_JAVA_VIEWS= "JavaScriptUI.update"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
- *
- * @see #UPDATE_JAVA_VIEWS
- * @deprecated Since 3.0, views now always update while editing
- */
- public static final String UPDATE_ON_SAVE= "JavaScriptUI.update.onSave"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
- *
- * @see #UPDATE_JAVA_VIEWS
- * @deprecated Since 3.0, views now always update while editing
- */
- public static final String UPDATE_WHILE_EDITING= "JavaScriptUI.update.whileEditing"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- */
- public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$
-
- /**
- * A named preference that defines whether the hint to make hover sticky should be shown.
- *
- * @see JavaScriptUI
- *
- * @deprecated As of 3.3, replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_SHOW_TEXT_HOVER_AFFORDANCE}
- */
- public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE= "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the key for the hover modifiers.
- *
- * @see JavaScriptUI
- *
- */
- public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the key for the hover modifier state masks.
- * The value is only used if the value of <code>EDITOR_TEXT_HOVER_MODIFIERS</code>
- * cannot be resolved to valid SWT modifier bits.
- *
- * @see JavaScriptUI
- * @see #EDITOR_TEXT_HOVER_MODIFIERS
- *
- */
- public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS= "hoverModifierMasks"; //$NON-NLS-1$
-
- /**
- * The id of the best match hover contributed for extension point
- * <code>javaEditorTextHovers</code>.
- *
- *
- */
- public static final String ID_BESTMATCH_HOVER= "org.eclipse.wst.jsdt.ui.BestMatchHover"; //$NON-NLS-1$
-
- /**
- * The id of the source code hover contributed for extension point
- * <code>javaEditorTextHovers</code>.
- *
- *
- */
- public static final String ID_SOURCE_HOVER= "org.eclipse.wst.jsdt.ui.JavaSourceHover"; //$NON-NLS-1$
-
- /**
- * The id of the javadoc hover contributed for extension point
- * <code>javaEditorTextHovers</code>.
- *
- *
- */
- public static final String ID_JAVADOC_HOVER= "org.eclipse.wst.jsdt.ui.JavadocHover"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether bracket matching highlighting is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to highlight matching brackets.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the current line highlighting is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to highlight the current line.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the print margin is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render the print margin.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$
-
- /**
- * Print margin column. Integer value.
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used for the find/replace scope.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated As of 3.2, use {@link AbstractTextEditor#PREFERENCE_COLOR_FIND_SCOPE} instead}
- */
- public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE;
-
- /**
- * A named preference that specifies if the editor uses spaces for tabs.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used
- * in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab
- * key.
- * </p>
- * @deprecated As of 3.1 replaced by the formatter setting defined in {@link org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants#FORMATTER_TAB_CHAR}
- */
- public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the number of spaces used per tab in the editor.
- * <p>
- * Value is of type <code>Integer</code>: positive integer value specifying the number of
- * spaces per tab.
- * </p>
- * @deprecated As of 3.0 replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_TAB_WIDTH}
- */
- public final static String EDITOR_TAB_WIDTH= "org.eclipse.wst.jsdt.ui.editor.tab.width"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the outline view selection
- * should stay in sync with with the element at the current cursor position.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if correction indicators are shown in the UI.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows problem indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render problem indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_PROBLEM_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows warning indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render warning indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_WARNING_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows task indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render task indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_TASK_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows bookmark
- * indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render bookmark indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_BOOKMARK_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows search
- * indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render search indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_SEARCH_RESULT_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the editor shows unknown
- * indicators in text (squiggly lines).
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render unknown
- * indicators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see #EDITOR_UNKNOWN_INDICATION
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows error
- * indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows warning
- * indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows task
- * indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows
- * bookmark indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows
- * search result indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the overview ruler shows
- * unknown indicators.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
- */
- public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'close strings' feature
- * is enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'wrap strings' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'escape strings' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_ESCAPE_STRINGS= "escapeStrings"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'close brackets' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'close braces' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'close JavaScript docs' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'add JavaDoc tags' feature
- * is enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'format Javadoc tags'
- * feature is enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'smart paste' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether 'paste' should update the imports.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_IMPORTS_ON_PASTE= "importsOnPaste"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether the 'smart home-end' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @deprecated as of 3.3 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants#EDITOR_SMART_HOME_END}
- */
- public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END;
-
- /**
- * A named preference that controls whether the 'sub-word navigation' feature is
- * enabled.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_SUB_WORD_NAVIGATION= "subWordNavigation"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if temporary problems are evaluated and shown in the UI.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the overview ruler is shown in the UI.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the line number ruler is shown in the UI.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render line numbers inside the line number ruler.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @see #EDITOR_LINE_NUMBER_RULER
- * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants}
- */
- public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render linked positions inside code templates.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @deprecated not used any longer as the linked positions are displayed as annotations
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used as the text foreground.
- * This value has not effect if the system default color is used.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated As of 3.1, replaced by {@link AbstractTextEditor#PREFERENCE_COLOR_FOREGROUND}
- */
- public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND;
-
- /**
- * A named preference that describes if the system default foreground color
- * is used as the text foreground.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated As of 3.1, replaced by {@link AbstractTextEditor#PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT}
- */
- public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT;
-
- /**
- * A named preference that holds the color used as the text background.
- * This value has not effect if the system default color is used.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- * @deprecated As of 3.1, replaced by {@link AbstractTextEditor#PREFERENCE_COLOR_BACKGROUND}
- */
- public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND;
-
- /**
- * A named preference that describes if the system default background color
- * is used as the text background.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * @deprecated As of 3.1, replaced by {@link AbstractTextEditor#PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT}
- */
- public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT;
-
- /**
- * Preference key suffix for bold text style preference keys.
- *
- *
- */
- public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$
-
- /**
- * Preference key suffix for italic text style preference keys.
- *
- *
- */
- public static final String EDITOR_ITALIC_SUFFIX= "_italic"; //$NON-NLS-1$
-
- /**
- * Preference key suffix for strikethrough text style preference keys.
- *
- *
- */
- public static final String EDITOR_STRIKETHROUGH_SUFFIX= "_strikethrough"; //$NON-NLS-1$
-
- /**
- * Preference key suffix for underline text style preference keys.
- *
- *
- */
- public static final String EDITOR_UNDERLINE_SUFFIX= "_underline"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render multi-line comments.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT;
-
- /**
- * The symbolic font name for the JavaScript editor text font
- * (value <code>"org.eclipse.wst.jsdt.ui.editors.textfont"</code>).
- *
- *
- */
- public final static String EDITOR_TEXT_FONT= "org.eclipse.wst.jsdt.ui.editors.textfont"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether multi-line comments are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> multi-line comments are rendered
- * in bold. If <code>false</code> the are rendered using no font style attribute.
- * </p>
- */
- public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether multi-line comments are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> multi-line comments are rendered
- * in italic. If <code>false</code> the are rendered using no italic font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_MULTI_LINE_COMMENT_ITALIC= IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether multi-line comments are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> multi-line comments are rendered
- * in strikethrough. If <code>false</code> the are rendered using no strikethrough font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_MULTI_LINE_COMMENT_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether multi-line comments are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> multi-line comments are rendered
- * in underline. If <code>false</code> the are rendered using no underline font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_MULTI_LINE_COMMENT_UNDERLINE= IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render single line comments.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT;
-
- /**
- * A named preference that controls whether single line comments are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
- * in bold. If <code>false</code> the are rendered using no font style attribute.
- * </p>
- */
- public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether single line comments are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
- * in italic. If <code>false</code> the are rendered using no italic font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_SINGLE_LINE_COMMENT_ITALIC= IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether single line comments are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
- * in strikethrough. If <code>false</code> the are rendered using no italic font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_SINGLE_LINE_COMMENT_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether single line comments are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
- * in underline. If <code>false</code> the are rendered using no italic font style attribute.
- * </p>
- *
- *
- */
- public final static String EDITOR_SINGLE_LINE_COMMENT_UNDERLINE= IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render JavaScript keywords.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaScriptColorConstants.JAVA_KEYWORD;
-
- /**
- * A named preference that controls whether keywords are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaScriptColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether keywords are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_ITALIC= IJavaScriptColorConstants.JAVA_KEYWORD + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether keywords are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_KEYWORD + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether keywords are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_UNDERLINE= IJavaScriptColorConstants.JAVA_KEYWORD + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render string constants.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_STRING_COLOR= IJavaScriptColorConstants.JAVA_STRING;
-
- /**
- * A named preference that controls whether string constants are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_STRING_BOLD= IJavaScriptColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether string constants are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_STRING_ITALIC= IJavaScriptColorConstants.JAVA_STRING + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether string constants are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_STRING_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_STRING + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether string constants are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_STRING_UNDERLINE= IJavaScriptColorConstants.JAVA_STRING + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render method names.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated the method name highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#METHOD}
- */
- public final static String EDITOR_JAVA_METHOD_NAME_COLOR= IJavaScriptColorConstants.JAVA_METHOD_NAME;
-
- /**
- * A named preference that controls whether method names are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the method name highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#METHOD}
- */
- public final static String EDITOR_JAVA_METHOD_NAME_BOLD= IJavaScriptColorConstants.JAVA_METHOD_NAME + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether method names are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the method name highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#METHOD}
- */
- public final static String EDITOR_JAVA_METHOD_NAME_ITALIC= IJavaScriptColorConstants.JAVA_METHOD_NAME + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that holds the color used to render the 'return' keyword.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_RETURN_COLOR= IJavaScriptColorConstants.JAVA_KEYWORD_RETURN;
-
- /**
- * A named preference that controls whether 'return' keyword is rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_RETURN_BOLD= IJavaScriptColorConstants.JAVA_KEYWORD_RETURN + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether 'return' keyword is rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_RETURN_ITALIC= IJavaScriptColorConstants.JAVA_KEYWORD_RETURN + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether 'return' keyword is rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_RETURN_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_KEYWORD_RETURN + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether 'return' keyword is rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_KEYWORD_RETURN_UNDERLINE= IJavaScriptColorConstants.JAVA_KEYWORD_RETURN + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render operators.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_JAVA_OPERATOR_COLOR= IJavaScriptColorConstants.JAVA_OPERATOR;
-
- /**
- * A named preference that controls whether operators are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_OPERATOR_BOLD= IJavaScriptColorConstants.JAVA_OPERATOR + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether operators are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_OPERATOR_ITALIC= IJavaScriptColorConstants.JAVA_OPERATOR + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether operators are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_OPERATOR_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_OPERATOR + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether operators are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_OPERATOR_UNDERLINE= IJavaScriptColorConstants.JAVA_OPERATOR + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render brackets.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_JAVA_BRACKET_COLOR= IJavaScriptColorConstants.JAVA_BRACKET;
-
- /**
- * A named preference that controls whether brackets are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_BRACKET_BOLD= IJavaScriptColorConstants.JAVA_BRACKET + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether brackets are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_BRACKET_ITALIC= IJavaScriptColorConstants.JAVA_BRACKET + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether brackets are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_BRACKET_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_BRACKET + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether brackets are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_BRACKET_UNDERLINE= IJavaScriptColorConstants.JAVA_BRACKET + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render annotations.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated the annotation highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- public final static String EDITOR_JAVA_ANNOTATION_COLOR= IJavaScriptColorConstants.JAVA_ANNOTATION;
-
- /**
- * A named preference that controls whether annotations are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the annotation highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- public final static String EDITOR_JAVA_ANNOTATION_BOLD= IJavaScriptColorConstants.JAVA_ANNOTATION + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether annotations are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the annotation highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- public final static String EDITOR_JAVA_ANNOTATION_ITALIC= IJavaScriptColorConstants.JAVA_ANNOTATION + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether annotations are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the annotation highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- public final static String EDITOR_JAVA_ANNOTATION_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_ANNOTATION + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether annotations are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated the annotation highlighting has been replaced by a semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- public final static String EDITOR_JAVA_ANNOTATION_UNDERLINE= IJavaScriptColorConstants.JAVA_ANNOTATION + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render JavaScript default text.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaScriptColorConstants.JAVA_DEFAULT;
-
- /**
- * A named preference that controls whether JavaScript default text is rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaScriptColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether JavaScript default text is rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_DEFAULT_ITALIC= IJavaScriptColorConstants.JAVA_DEFAULT + EDITOR_ITALIC_SUFFIX;
- /**
- * A named preference that controls whether JavaScript default text is rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_DEFAULT_STRIKETHROUGH= IJavaScriptColorConstants.JAVA_DEFAULT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether JavaScript default text is rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVA_DEFAULT_UNDERLINE= IJavaScriptColorConstants.JAVA_DEFAULT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render task tags.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_TASK_TAG_COLOR= IJavaScriptColorConstants.TASK_TAG;
-
- /**
- * A named preference that controls whether task tags are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String EDITOR_TASK_TAG_BOLD= IJavaScriptColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether task tags are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_TASK_TAG_ITALIC= IJavaScriptColorConstants.TASK_TAG + EDITOR_ITALIC_SUFFIX;
- /**
- * A named preference that controls whether task tags are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_TASK_TAG_STRIKETHROUGH= IJavaScriptColorConstants.TASK_TAG + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether task tags are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_TASK_TAG_UNDERLINE= IJavaScriptColorConstants.TASK_TAG + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render javadoc keywords.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaScriptColorConstants.JAVADOC_KEYWORD;
-
- /**
- * A named preference that controls whether javadoc keywords are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaScriptColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc keywords are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_KEYWORD_ITALIC= IJavaScriptColorConstants.JAVADOC_KEYWORD + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc keywords are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- *
- */
- public final static String EDITOR_JAVADOC_KEYWORD_STRIKETHROUGH= IJavaScriptColorConstants.JAVADOC_KEYWORD + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc keywords are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_KEYWORD_UNDERLINE= IJavaScriptColorConstants.JAVADOC_KEYWORD + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render javadoc tags.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaScriptColorConstants.JAVADOC_TAG;
-
- /**
- * A named preference that controls whether javadoc tags are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaScriptColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc tags are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_TAG_ITALIC= IJavaScriptColorConstants.JAVADOC_TAG + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc tags are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_TAG_STRIKETHROUGH= IJavaScriptColorConstants.JAVADOC_TAG + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc tags are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_TAG_UNDERLINE= IJavaScriptColorConstants.JAVADOC_TAG + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render javadoc links.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaScriptColorConstants.JAVADOC_LINK;
-
- /**
- * A named preference that controls whether javadoc links are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaScriptColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc links are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_LINKS_ITALIC= IJavaScriptColorConstants.JAVADOC_LINK + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc links are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_LINKS_STRIKETHROUGH= IJavaScriptColorConstants.JAVADOC_LINK + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc links are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_LINKS_UNDERLINE= IJavaScriptColorConstants.JAVADOC_LINK + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render javadoc default text.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaScriptColorConstants.JAVADOC_DEFAULT;
-
- /**
- * A named preference that controls whether javadoc default text is rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaScriptColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc default text is rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_DEFAULT_ITALIC= IJavaScriptColorConstants.JAVADOC_DEFAULT + EDITOR_ITALIC_SUFFIX;
- /**
- * A named preference that controls whether javadoc default text is rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_DEFAULT_STRIKETHROUGH= IJavaScriptColorConstants.JAVADOC_DEFAULT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether javadoc default text is rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String EDITOR_JAVADOC_DEFAULT_UNDERLINE= IJavaScriptColorConstants.JAVADOC_DEFAULT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used for 'linked-mode' underline.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- * @deprecated As of 3.1, replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_HYPERLINK_COLOR}
- */
- public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether hover tool tips in the editor are turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public static final String EDITOR_SHOW_HOVER= "org.eclipse.wst.jsdt.ui.editor.showHover"; //$NON-NLS-1$
-
-
- /**
- * A named preference that defines the hover shown when no control key is
- * pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover
- * contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>CTRL</code> modifier key is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>SHIFT</code> modifier key is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI ID_*_HOVER
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>CTRL + ALT</code> modifier keys is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI ID_*_HOVER
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI ID_*_HOVER
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>CTRL + SHIFT</code> modifier keys is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI ID_*_HOVER
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover shown when the
- * <code>ALT</code> modifier key is pressed.
- * <p>Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code>,
- * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
- * hover contributed as <code>javaEditorTextHovers</code>.
- * </p>
- * @see #EDITOR_NO_HOVER_CONFIGURED_ID
- * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
- * @see JavaScriptUI ID_*_HOVER
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- *
- */
- public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preferences for hover configuration to
- * describe that no hover should be shown for the given key modifiers.
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- *
- */
- public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preferences for hover configuration to
- * describe that the default hover should be shown for the given key
- * modifiers. The default hover is described by the
- * <code>EDITOR_DEFAULT_HOVER</code> property.
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$
-
- /**
- * A named preference that defines the hover named the 'default hover'.
- * Value is of type <code>String</code>: possible values are <code>
- * EDITOR_NO_HOVER_CONFIGURED_ID</code> or the hover id of a hover
- * contributed as <code>javaEditorTextHovers</code>.
- * </p>
- *
- * @deprecated As of 3.0, replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
- */
- public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if segmented view (show selected element only) is turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.wst.jsdt.ui.editor.showSegments"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if browser like links are turned on or off.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated As of 3.1, replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_HYPERLINKS_ENABLED}
- */
- public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the key modifier for browser like links.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- *
- * @deprecated As of 3.1, replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_HYPERLINK_KEY_MODIFIER}
- */
- public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the key modifier mask for browser like links.
- * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
- * cannot be resolved to valid SWT modifier bits.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER
- *
- * @deprecated As of 3.1, replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_HYPERLINK_KEY_MODIFIER_MASK}
- */
- public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether occurrences are marked in the editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_OCCURRENCES= "markOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether occurrences are sticky in the editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_STICKY_OCCURRENCES= "stickyOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether type occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_TYPE_OCCURRENCES= "markTypeOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether method occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_METHOD_OCCURRENCES= "markMethodOccurrences"; //$NON-NLS-1$
- /**
- * A named preference that controls whether non-constant field occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_FIELD_OCCURRENCES= "markFieldOccurrences"; //$NON-NLS-1$
- /**
- * A named preference that controls whether constant (static final) occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_CONSTANT_OCCURRENCES= "markConstantOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether local variable occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES= "markLocalVariableOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether exception occurrences are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_EXCEPTION_OCCURRENCES= "markExceptionOccurrences"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether method exit points are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_METHOD_EXIT_POINTS= "markMethodExitPoints"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether targets for of <code>break</code> and <code>continue</code> statements are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_BREAK_CONTINUE_TARGETS= "markBreakContinueTargets"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether method exit points are marked.
- * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_MARK_IMPLEMENTORS= "markImplementors"; //$NON-NLS-1$
-
- /**
- * A named preference prefix for semantic highlighting preferences.
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX="semanticHighlighting."; //$NON-NLS-1$
-
- /**
- * A named preference that controls if semantic highlighting is enabled.
- * <p>
- * Value is of type <code>Boolean</code>:<code>true</code> if enabled.
- * </p>
- *
- *
- * @deprecated As of 3.1, this preference is not used or set any longer; see
- * {@link SemanticHighlightings#affectsEnablement(IPreferenceStore, org.eclipse.jface.util.PropertyChangeEvent)}
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED=EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + "enabled"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls a semantic highlighting's color.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX=".color"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls if semantic highlighting has the text attribute bold.
- * <p>
- * Value is of type <code>Boolean</code>: <code>true</code> if bold.
- * </p>
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX=".bold"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls if semantic highlighting has the text attribute italic.
- * <p>
- * Value is of type <code>Boolean</code>: <code>true</code> if italic.
- * </p>
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX=".italic"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls if semantic highlighting has the text attribute strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>: <code>true</code> if strikethrough.
- * </p>
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_STRIKETHROUGH_SUFFIX=".strikethrough"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls if semantic highlighting has the text attribute underline.
- * <p>
- * Value is of type <code>Boolean</code>: <code>true</code> if underline.
- * </p>
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX=".underline"; //$NON-NLS-1$
-
- /**
- * A named preference suffix that controls if semantic highlighting is enabled.
- * <p>
- * Value is of type <code>Boolean</code>: <code>true</code> if enabled.
- * </p>
- *
- *
- */
- public static final String EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX=".enabled"; //$NON-NLS-1$
-
- /**
- * A named preference that controls disabling of the overwrite mode.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- * @deprecated as of 3.1 replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_DISABLE_OVERWRITE_MODE}
- */
- public static final String EDITOR_DISABLE_OVERWRITE_MODE= "disable_overwrite_mode"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the "smart semicolon" smart typing handler.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_SMART_SEMICOLON= "smart_semicolon"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the smart backspace behavior.
- * <p>
- * Value is of type <code>Boolean</code>.
- *
- *
- */
- public static final String EDITOR_SMART_BACKSPACE= "smart_backspace"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the "smart opening brace" smart typing handler.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_SMART_OPENING_BRACE= "smart_opening_brace"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the smart tab behavior.
- * <p>
- * Value is of type <code>Boolean</code>.
- *
- *
- */
- public static final String EDITOR_SMART_TAB= "smart_tab"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether words containing digits should
- * be skipped during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_DIGITS= "spelling_ignore_digits"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether mixed case words should be
- * skipped during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_MIXED= "spelling_ignore_mixed"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether sentence capitalization should
- * be ignored during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_SENTENCE= "spelling_ignore_sentence"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether upper case words should be
- * skipped during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_UPPER= "spelling_ignore_upper"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether URLs should be ignored during
- * spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_URLS= "spelling_ignore_urls"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether single letters
- * should be ignored during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_SINGLE_LETTERS= "spelling_ignore_single_letters"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether '&' in
- * JavaScript properties files are ignored.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_AMPERSAND_IN_PROPERTIES= "spelling_ignore_ampersand_in_properties"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether non-letters at word boundaries
- * should be ignored during spell checking.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_IGNORE_NON_LETTERS= "spelling_ignore_non_letters"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the locale used for spell checking.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_LOCALE= "spelling_locale"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the number of proposals offered during
- * spell checking.
- * <p>
- * Value is of type <code>Integer</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_PROPOSAL_THRESHOLD= "spelling_proposal_threshold"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies the workspace user dictionary.
- * <p>
- * Value is of type <code>Integer</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_USER_DICTIONARY= "spelling_user_dictionary"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies encoding of the workspace user dictionary.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_USER_DICTIONARY_ENCODING= "spelling_user_dictionary_encoding"; //$NON-NLS-1$
-
- /**
- * A named preference that specifies whether spelling dictionaries are available to content assist.
- *
- * <strong>Note:</strong> This is currently not supported because the spelling engine
- * cannot return word proposals but only correction proposals.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String SPELLING_ENABLE_CONTENTASSIST= "spelling_enable_contentassist"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the JavaScript code assist gets auto activated.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$
-
- /**
- * A name preference that holds the auto activation delay time in milliseconds.
- * <p>
- * Value is of type <code>Integer</code>.
- * </p>
- */
- public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if code assist contains only visible proposals.
- * <p>
- * Value is of type <code>Boolean</code>. if <code>true</code> code assist only contains visible members. If
- * <code>false</code> all members are included.
- * </p>
- */
- public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the JavaScript code assist inserts a
- * proposal automatically if only one proposal is available.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the JavaScript code assist adds import
- * statements.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the JavaScript code assist only inserts
- * completions. If set to false the proposals can also _replace_ code.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether code assist proposals filtering is case sensitive or not.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$
-
- /**
- * A named preference that defines if code assist proposals are sorted in alphabetical order.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical
- * order. If <code>false</code> that are unsorted.
- * </p>
- * @deprecated use {@link #CODEASSIST_SORTER} instead
- */
- public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if argument names are filled in when a method is selected from as list
- * of code assist proposal.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if method arguments are guessed when a
- * method is selected from as list of code assist proposal.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the characters that auto activate code assist in JavaScript code.
- * <p>
- * Value is of type <code>String</code>. All characters that trigger auto code assist in JavaScript code.
- * </p>
- */
- public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the characters that auto activate code assist in Javadoc.
- * <p>
- * Value is of type <code>String</code>. All characters that trigger auto code assist in Javadoc.
- * </p>
- */
- public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the background color used in the code assist selection dialog.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the foreground color used in the code assist selection dialog.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the background color used for parameter hints.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the foreground color used in the code assist selection dialog.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- */
- public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the background color used in the code
- * assist selection dialog to mark replaced code.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the foreground color used in the code
- * assist selection dialog to mark replaced code.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the favorite static members.
- * <p>
- * Value is of type <code>String</code>: semicolon separated list of favorites.
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String CODEASSIST_FAVORITE_STATIC_MEMBERS= "content_assist_favorite_static_members"; //$NON-NLS-1$
-
-
- /**
- * A named preference that controls the behavior of the refactoring wizard for showing the error page.
- * <p>
- * Value is of type <code>String</code>. Valid values are:
- * <code>REFACTOR_FATAL_SEVERITY</code>,
- * <code>REFACTOR_ERROR_SEVERITY</code>,
- * <code>REFACTOR_WARNING_SEVERITY</code>
- * <code>REFACTOR_INFO_SEVERITY</code>,
- * <code>REFACTOR_OK_SEVERITY</code>.
- * </p>
- *
- * @see #REFACTOR_FATAL_SEVERITY
- * @see #REFACTOR_ERROR_SEVERITY
- * @see #REFACTOR_WARNING_SEVERITY
- * @see #REFACTOR_INFO_SEVERITY
- * @see #REFACTOR_OK_SEVERITY
- *
- * @deprecated Use method {@link org.eclipse.ltk.core.refactoring.RefactoringCore#getConditionCheckingFailedSeverity()}.
- */
- public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
- *
- * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
- * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#FATAL}
- */
- public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
- *
- * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
- * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#ERROR}
- */
- public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
- *
- * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
- * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#WARNING}
- */
- public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
- *
- * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
- * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#INFO}
- */
- public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$
-
- /**
- * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
- *
- * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
- * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#OK}
- */
- public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether all dirty editors are automatically saved before a refactoring is
- * executed.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- */
- public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether certain refactorings use a lightweight UI when
- * started from a JavaScript editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- * <p>
- * Note: this is work in progress and may change any time
- * </p>
- *
- */
- public static final String REFACTOR_LIGHTWEIGHT= "Refactor.lightweight"; //$NON-NLS-1$
-
- /**
- * A named preference that controls a reduced search menu is used in the JavaScript editors.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String SEARCH_USE_REDUCED_MENU= "Search.usereducemenu"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if the JavaScript Browsing views are linked to the active editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- */
- public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.wst.jsdt.ui.browsing.linktoeditor"; //$NON-NLS-1$
-
- /**
- * A named preference that controls the layout of the JavaScript Browsing views vertically. Boolean value.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> the views are stacked vertical.
- * If <code>false</code> they are stacked horizontal.
- * </p>
- */
- public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.wst.jsdt.ui.browsing.stackVertically"; //$NON-NLS-1$
-
-
- /**
- * A named preference that controls if templates are formatted when applied.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.wst.jsdt.ui.template.format"; //$NON-NLS-1$
-
- /**
- * A named preference that controls which profile is used by the code formatter.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- *
- */
- public static final String FORMATTER_PROFILE= "formatter_profile"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether annotation roll over is used or not.
- * <p>
- * Value is of type <code>Boolean</code>. If <code>true</code> the annotation ruler column
- * uses a roll over to display multiple annotations
- * </p>
- *
- *
- */
- public static final String EDITOR_ANNOTATION_ROLL_OVER= "editor_annotation_roll_over"; //$NON-NLS-1$
-
- /**
- * A named preference that controls if content assist inserts the common
- * prefix of all proposals before presenting choices.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public final static String CODEASSIST_PREFIX_COMPLETION= "content_assist_prefix_completion"; //$NON-NLS-1$
-
- /**
- * A named preference that controls which completion proposal categories
- * have been excluded from the default proposal list.
- * <p>
- * Value is of type <code>String</code>, a "\0"-separated list of identifiers.
- * </p>
- *
- *
- */
- public static final String CODEASSIST_EXCLUDED_CATEGORIES= "content_assist_disabled_computers"; //$NON-NLS-1$
-
- /**
- * A named preference that controls which the order of the specific code assist commands.
- * <p>
- * Value is of type <code>String</code>, a "\0"-separated list of identifiers.
- * </p>
- *
- *
- */
- public static final String CODEASSIST_CATEGORY_ORDER= "content_assist_category_order"; //$NON-NLS-1$
-
- /**
- * A named preference that controls whether folding is enabled in the JavaScript editor.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_ENABLED= "editor_folding_enabled"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the configured folding provider.
- * <p>
- * Value is of type <code>String</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_PROVIDER= "editor_folding_provider"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the value for Javadoc folding for the default folding provider.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_JAVADOC= "editor_folding_default_javadoc"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the value for inner type folding for the default folding provider.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_INNERTYPES= "editor_folding_default_innertypes"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the value for method folding for the default folding provider.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_METHODS= "editor_folding_default_methods"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the value for imports folding for the default folding provider.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_IMPORTS= "editor_folding_default_imports"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the value for header comment folding for the default folding provider.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String EDITOR_FOLDING_HEADERS= "editor_folding_default_headers"; //$NON-NLS-1$
-
-
- //---------- Properties File Editor ----------
-
- /**
- * The symbolic font name for the JavaScript properties file editor text font
- * (value <code>"org.eclipse.wst.jsdt.ui.PropertiesFileEditor.textfont"</code>).
- * @deprecated - we don't expose this editor
- *
- */
- public static final String PROPERTIES_FILE_EDITOR_TEXT_FONT= "org.eclipse.wst.jsdt.ui.PropertiesFileEditor.textfont"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the color used to render keys in a properties file.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String PROPERTIES_FILE_COLORING_KEY= IJavaScriptColorConstants.PROPERTIES_FILE_COLORING_KEY;
-
- /**
- * A named preference that controls whether keys in a properties file are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_KEY_BOLD= PROPERTIES_FILE_COLORING_KEY + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether keys in a properties file are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_KEY_ITALIC= PROPERTIES_FILE_COLORING_KEY + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether keys in a properties file are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_KEY_STRIKETHROUGH= PROPERTIES_FILE_COLORING_KEY + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether keys in a properties file are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_KEY_UNDERLINE= PROPERTIES_FILE_COLORING_KEY + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render comments in a properties file.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String PROPERTIES_FILE_COLORING_COMMENT= IJavaScriptColorConstants.PROPERTIES_FILE_COLORING_COMMENT;
-
- /**
- * A named preference that controls whether comments in a properties file are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_COMMENT_BOLD= PROPERTIES_FILE_COLORING_COMMENT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether comments in a properties file are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_COMMENT_ITALIC= PROPERTIES_FILE_COLORING_COMMENT + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether comments in a properties file are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_COMMENT_STRIKETHROUGH= PROPERTIES_FILE_COLORING_COMMENT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether comments in a properties file are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_COMMENT_UNDERLINE= PROPERTIES_FILE_COLORING_COMMENT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render values in a properties file.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String PROPERTIES_FILE_COLORING_VALUE= IJavaScriptColorConstants.PROPERTIES_FILE_COLORING_VALUE;
-
- /**
- * A named preference that controls whether values in a properties file are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_VALUE_BOLD= PROPERTIES_FILE_COLORING_VALUE + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether values in a properties file are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_VALUE_ITALIC= PROPERTIES_FILE_COLORING_VALUE + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether values in a properties file are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_VALUE_STRIKETHROUGH= PROPERTIES_FILE_COLORING_VALUE + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether values in a properties file are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_VALUE_UNDERLINE= PROPERTIES_FILE_COLORING_VALUE + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render assignments in a properties file.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ASSIGNMENT= IJavaScriptColorConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT;
-
- /**
- * A named preference that controls whether assignments in a properties file are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ASSIGNMENT_BOLD= PROPERTIES_FILE_COLORING_ASSIGNMENT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether assignments in a properties file are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ASSIGNMENT_ITALIC= PROPERTIES_FILE_COLORING_ASSIGNMENT + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether assignments in a properties file are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ASSIGNMENT_STRIKETHROUGH= PROPERTIES_FILE_COLORING_ASSIGNMENT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether assignments in a properties file are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ASSIGNMENT_UNDERLINE= PROPERTIES_FILE_COLORING_ASSIGNMENT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that holds the color used to render arguments in a properties file.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ARGUMENT= IJavaScriptColorConstants.PROPERTIES_FILE_COLORING_ARGUMENT;
-
- /**
- * A named preference that controls whether arguments in a properties file are rendered in bold.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ARGUMENT_BOLD= PROPERTIES_FILE_COLORING_ARGUMENT + EDITOR_BOLD_SUFFIX;
-
- /**
- * A named preference that controls whether arguments in a properties file are rendered in italic.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ARGUMENT_ITALIC= PROPERTIES_FILE_COLORING_ARGUMENT + EDITOR_ITALIC_SUFFIX;
-
- /**
- * A named preference that controls whether arguments in a properties file are rendered in strikethrough.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ARGUMENT_STRIKETHROUGH= PROPERTIES_FILE_COLORING_ARGUMENT + EDITOR_STRIKETHROUGH_SUFFIX;
-
- /**
- * A named preference that controls whether arguments in a properties file are rendered in underline.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- *
- */
- public static final String PROPERTIES_FILE_COLORING_ARGUMENT_UNDERLINE= PROPERTIES_FILE_COLORING_ARGUMENT + EDITOR_UNDERLINE_SUFFIX;
-
- /**
- * A named preference that stores the content assist LRU history
- * <p>
- * Value is an XML encoded version of the history.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistHistory#load(org.eclipse.core.runtime.Preferences, String)
- *
- */
- public static final String CODEASSIST_LRU_HISTORY= "content_assist_lru_history"; //$NON-NLS-1$
-
- /**
- * A named preference that stores the content assist sorter id.
- * <p>
- * Value is a {@link String}.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.internal.ui.text.java.ProposalSorterRegistry
- *
- */
- public static final String CODEASSIST_SORTER= "content_assist_sorter"; //$NON-NLS-1$
-
- /**
- * A named preference that holds the source hover background color.
- * <p>
- * Value is of type <code>String</code>. A RGB color value encoded as a string
- * using class <code>PreferenceConverter</code>
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_SOURCE_HOVER_BACKGROUND_COLOR= "sourceHoverBackgroundColor"; //$NON-NLS-1$
-
- /**
- * A named preference that tells whether to use the system
- * default color ({@link SWT#COLOR_INFO_BACKGROUND}) for
- * the source hover background color.
- * <p>
- * Value is of type <code>Boolean</code>.
- * </p>
- *
- * @see org.eclipse.jface.resource.StringConverter
- * @see org.eclipse.jface.preference.PreferenceConverter
- *
- */
- public final static String EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT= "sourceHoverBackgroundColor.SystemDefault"; //$NON-NLS-1$
-
- /**
- * Initializes the given preference store with the default values.
- *
- * @param store the preference store to be initialized
- *
- *
- */
- public static void initializeDefaultValues(IPreferenceStore store) {
- ColorRegistry registry= PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry();
- store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
-
- // JavaBasePreferencePage
- store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS);
- store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING);
- store.setToDefault(PreferenceConstants.UPDATE_JAVA_VIEWS); // clear preference, update on save not supported anymore
-
- store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true);
- store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true);
- store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true);
- store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true);
-
- store.setDefault(PreferenceConstants.SEARCH_USE_REDUCED_MENU, true);
-
- // AppearancePreferencePage
- store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false);
- store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false);
- store.setDefault(PreferenceConstants.APPEARANCE_METHOD_TYPEPARAMETERS, true);
- store.setDefault(PreferenceConstants.APPEARANCE_CATEGORY, true);
- store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true);
- store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false);
- store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true);
-
- // ImportOrganizePreferencePage
- store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99);
- store.setDefault(PreferenceConstants.ORGIMPORTS_STATIC_ONDEMANDTHRESHOLD, 99);
- store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true);
-
- // TypeFilterPreferencePage
- store.setDefault(PreferenceConstants.TYPEFILTER_ENABLED, ""); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.TYPEFILTER_DISABLED, ""); //$NON-NLS-1$
-
- // ClasspathVariablesPreferencePage
- // CodeFormatterPreferencePage
- // CompilerPreferencePage
- // no initialization needed
-
- // RefactoringPreferencePage
- store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_WARNING_SEVERITY);
- store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false);
- store.setDefault(PreferenceConstants.REFACTOR_LIGHTWEIGHT, true);
-
- // TemplatePreferencePage
- store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true);
-
- // CodeGenerationPreferencePage
- // compatibility code
- if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) {
- String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
- if (prefix.length() > 0) {
- JavaScriptCore.getPlugin().getPluginPreferences().setValue(JavaScriptCore.CODEASSIST_FIELD_PREFIXES, prefix);
- store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX);
- store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
- }
- }
- if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) {
- String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
- if (suffix.length() > 0) {
- JavaScriptCore.getPlugin().getPluginPreferences().setValue(JavaScriptCore.CODEASSIST_FIELD_SUFFIXES, suffix);
- store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX);
- store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
- }
- }
- store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false);
- store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true);
- store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
- store.setDefault(PreferenceConstants.CODEGEN_USE_OVERRIDE_ANNOTATION, true);
-
- // MembersOrderPreferencePage
-// store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SF,SI,SM,F,I,C,M"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,F,I,C,M"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, "B,V,R,D"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, false);
-
- // JavaEditorPreferencePage
- store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true);
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192)));
-
- store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true);
- store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true);
-
- store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true);
-
- PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(121, 121, 121));
-
- store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4);
- store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)));
-
- store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)));
-
- store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_ITALIC, false);
-
- PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_ANNOTATION_COLOR, new RGB(100, 100, 100));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_ANNOTATION_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_ANNOTATION_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_STRING_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)));
-
- store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_STRING_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_ITALIC, false);
-
- setDefaultAndFireEvent(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR, new RGB(127, 0, 85)));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_BOLD, true);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0)));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVA_BRACKET_COLOR, new RGB(0, 0, 0)));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_BRACKET_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVA_BRACKET_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_TASK_TAG_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)));
- store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true);
- store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)));
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true);
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)));
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)));
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR,
- findRGB(registry, IJavaThemeConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)));
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false);
- store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_ITALIC, false);
-
- store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true);
- store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 300);
-
- store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true);
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(255, 255, 255)));
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)));
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(255, 255, 255)));
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)));
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)));
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND,
- findRGB(registry, IJavaThemeConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)));
- store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@#"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true);
- store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false);
- store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, false);
- store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true);
- store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, true);
- store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, false);
- store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, false);
- store.setDefault(PreferenceConstants.CODEASSIST_EXCLUDED_CATEGORIES, "org.eclipse.wst.jsdt.ui.spellingProposalCategory\0org.eclipse.wst.jsdt.ui.textProposalCategory\0"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_CATEGORY_ORDER, "org.eclipse.wst.jsdt.ui.spellingProposalCategory:65545\0org.eclipse.wst.jsdt.ui.javaTypeProposalCategory:65540\0org.eclipse.wst.jsdt.ui.javaNoTypeProposalCategory:65539\0org.eclipse.wst.jsdt.ui.textProposalCategory:65541\0org.eclipse.wst.jsdt.ui.templateProposalCategory:2\0"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_LRU_HISTORY, ""); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_SORTER, "org.eclipse.wst.jsdt.ui.RelevanceSorter"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS, ""); //$NON-NLS-1$
-
- store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true);
- store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true);
- store.setDefault(PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, true);
- store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true);
- store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true);
- store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true);
- store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true);
- store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true);
- store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false);
- store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true);
- store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false);
-
- int sourceHoverModifier= SWT.MOD2;
- String sourceHoverModifierName= Action.findModifierString(sourceHoverModifier); // Shift
- int nlsHoverModifier= SWT.MOD1 + SWT.MOD3;
- String nlsHoverModifierName= Action.findModifierString(SWT.MOD1) + "+" + Action.findModifierString(SWT.MOD3); // Ctrl + Alt //$NON-NLS-1$
- store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.wst.jsdt.ui.BestMatchHover;0;org.eclipse.wst.jsdt.ui.JavaSourceHover;" + sourceHoverModifierName + ";org.eclipse.wst.jsdt.ui.NLSStringHover;" + nlsHoverModifierName); //$NON-NLS-1$ //$NON-NLS-2$
- store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.wst.jsdt.ui.BestMatchHover;0;org.eclipse.wst.jsdt.ui.JavaSourceHover;" + sourceHoverModifier + ";org.eclipse.wst.jsdt.ui.NLSStringHover;" + nlsHoverModifier); //$NON-NLS-1$ //$NON-NLS-2$
-
- store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true);
- store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true);
- store.setDefault(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER, false);
-
- store.setDefault(EDITOR_SOURCE_HOVER_BACKGROUND_COLOR_SYSTEM_DEFAULT, true);
-
- store.setDefault(PreferenceConstants.FORMATTER_PROFILE, FormatterProfileManager.DEFAULT_PROFILE);
-
- // mark occurrences
- store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_BREAK_CONTINUE_TARGETS, true);
- store.setDefault(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, true);
-
-
- // folding
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true);
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, "org.eclipse.wst.jsdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, false);
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, false);
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false);
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, true);
- store.setDefault(PreferenceConstants.EDITOR_FOLDING_HEADERS, true);
-
- // properties file editor
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.PROPERTIES_FILE_COLORING_KEY,
- findRGB(registry, IJavaThemeConstants.PROPERTIES_FILE_COLORING_KEY, new RGB(0, 0, 0)));
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_KEY_BOLD, false);
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_KEY_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.PROPERTIES_FILE_COLORING_VALUE,
- findRGB(registry, IJavaThemeConstants.PROPERTIES_FILE_COLORING_VALUE, new RGB(42, 0, 255)));
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_VALUE_BOLD, false);
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_VALUE_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT,
- findRGB(registry, IJavaThemeConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT, new RGB(0, 0, 0)));
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT_BOLD, false);
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_ASSIGNMENT_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.PROPERTIES_FILE_COLORING_ARGUMENT,
- findRGB(registry, IJavaThemeConstants.PROPERTIES_FILE_COLORING_ARGUMENT, new RGB(127, 0, 85)));
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_ARGUMENT_BOLD, true);
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_ARGUMENT_ITALIC, false);
-
- setDefaultAndFireEvent(
- store,
- PreferenceConstants.PROPERTIES_FILE_COLORING_COMMENT,
- findRGB(registry, IJavaThemeConstants.PROPERTIES_FILE_COLORING_COMMENT, new RGB(63, 127, 95)));
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_COMMENT_BOLD, false);
- store.setDefault(PreferenceConstants.PROPERTIES_FILE_COLORING_COMMENT_ITALIC, false);
-
- // semantic highlighting
- SemanticHighlightings.initDefaults(store);
-
- // do more complicated stuff
- NewJavaProjectPreferencePage.initDefaults(store);
-
- // reset preferences that are not settable by editor any longer
- // see AbstractDecoratedTextEditorPreferenceConstants
- store.setToDefault(EDITOR_SMART_HOME_END); // global
- store.setToDefault(EDITOR_LINE_NUMBER_RULER); // global
- store.setToDefault(EDITOR_LINE_NUMBER_RULER_COLOR); // global
- store.setToDefault(EDITOR_OVERVIEW_RULER); // removed -> true
- store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS); // accessibility
-
- store.setToDefault(PreferenceConstants.EDITOR_CURRENT_LINE); // global
- store.setToDefault(PreferenceConstants.EDITOR_CURRENT_LINE_COLOR); // global
-
- store.setToDefault(PreferenceConstants.EDITOR_PRINT_MARGIN); // global
- store.setToDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); // global
- store.setToDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR); // global
-
- store.setToDefault(PreferenceConstants.EDITOR_FOREGROUND_COLOR); // global
- store.setToDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR); // global
- store.setToDefault(PreferenceConstants.EDITOR_BACKGROUND_COLOR); // global
- store.setToDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); // global
- store.setToDefault(PreferenceConstants.EDITOR_FIND_SCOPE_COLOR); // global
- store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR); // global
- store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR); // global
-
- store.setToDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE); // global
-
- store.setToDefault(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED); // removed
-
- store.setToDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE); // global
-
-
- //Code Clean Up
- CleanUpConstants.initDefaults(store);
- }
-
- /**
- * Returns the JDT-UI preference store.
- *
- * @return the JDT-UI preference store
- */
- public static IPreferenceStore getPreferenceStore() {
- return JavaScriptPlugin.getDefault().getPreferenceStore();
- }
-
- /**
- * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>.
- *
- * @param description a string value describing the JRE library. The description is used
- * to identify the JDR library in the UI
- * @param entries an array of classpath entries to be encoded
- *
- * @return the encoded string.
- */
- public static String encodeJRELibrary(String description, IIncludePathEntry[] entries) {
- return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries);
- }
-
- /**
- * Decodes an encoded JRE library and returns its description string.
- * @param encodedLibrary the encoded library
- * @return the description of an encoded JRE library
- *
- * @see #encodeJRELibrary(String, IIncludePathEntry[])
- */
- public static String decodeJRELibraryDescription(String encodedLibrary) {
- return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary);
- }
-
- /**
- * Decodes an encoded JRE library and returns its class path entries.
- * @param encodedLibrary the encoded library
- * @return the array of classpath entries of an encoded JRE library.
- *
- * @see #encodeJRELibrary(String, IIncludePathEntry[])
- */
- public static IIncludePathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) {
- return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary);
- }
-
- /**
- * Returns the current configuration for the JRE to be used as default in new JavaScript projects.
- * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST
- * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>.
- *
- * @return the current default set of class path entries
- *
- * @see #NEWPROJECT_JRELIBRARY_LIST
- * @see #NEWPROJECT_JRELIBRARY_INDEX
- */
- public static IIncludePathEntry[] getDefaultJRELibrary() {
- return NewJavaProjectPreferencePage.getDefaultJRELibrary();
- }
-
- /**
- * Returns the value for the given key in the given context.
- * @param key The preference key
- * @param project The current context or <code>null</code> if no context is available and the
- * workspace setting should be taken. Note that passing <code>null</code> should
- * be avoided.
- * @return Returns the current value for the string.
- *
- */
- public static String getPreference(String key, IJavaScriptProject project) {
- String val;
- if (project != null) {
- val= new ProjectScope(project.getProject()).getNode(JavaScriptUI.ID_PLUGIN).get(key, null);
- if (val != null) {
- return val;
- }
- }
- val= new InstanceScope().getNode(JavaScriptUI.ID_PLUGIN).get(key, null);
- if (val != null) {
- return val;
- }
- return new DefaultScope().getNode(JavaScriptUI.ID_PLUGIN).get(key, null);
- }
-
- /**
- * Sets the default value and fires a property
- * change event if necessary.
- *
- * @param store the preference store
- * @param key the preference key
- * @param newValue the new value
- *
- */
- private static void setDefaultAndFireEvent(IPreferenceStore store, String key, RGB newValue) {
- RGB oldValue= null;
- if (store.isDefault(key))
- oldValue= PreferenceConverter.getDefaultColor(store, key);
-
- PreferenceConverter.setDefault(store, key, newValue);
-
- if (oldValue != null && !oldValue.equals(newValue))
- store.firePropertyChangeEvent(key, oldValue, newValue);
- }
-
- /**
- * Returns the RGB for the given key in the given color registry.
- *
- * @param registry the color registry
- * @param key the key for the constant in the registry
- * @param defaultRGB the default RGB if no entry is found
- * @return RGB the RGB
- *
- */
- private static RGB findRGB(ColorRegistry registry, String key, RGB defaultRGB) {
- RGB rgb= registry.getRGB(key);
- if (rgb != null)
- return rgb;
- return defaultRGB;
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java
deleted file mode 100644
index af48b6b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java
+++ /dev/null
@@ -1,398 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ILightweightLabelDecorator;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.MarkerAnnotation;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IProblemChangedListener;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageImageDescriptor;
-
-/**
- * LabelDecorator that decorates an element's image with error and warning overlays that
- * represent the severity of markers attached to the element's underlying resource. To see
- * a problem decoration for a marker, the marker needs to be a subtype of <code>IMarker.PROBLEM</code>.
- * <p>
- * <b>Important</b>: Although this decorator implements ILightweightLabelDecorator, do not contribute this
- * class as a decorator to the <code>org.eclipse.ui.decorators</code> extension. Only use this class in your
- * own views and label providers.
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator {
-
- /**
- * This is a special <code>LabelProviderChangedEvent</code> carrying additional
- * information whether the event origins from a maker change.
- * <p>
- * <code>ProblemsLabelChangedEvent</code>s are only generated by <code>
- * ProblemsLabelDecorator</code>s.
- * </p>
- */
- public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent {
-
- private static final long serialVersionUID= 1L;
-
- private boolean fMarkerChange;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param eventSource the base label provider
- * @param changedResource the changed resources
- * @param isMarkerChange <code>true</code> if the change is a marker change; otherwise
- * <code>false</code>
- */
- public ProblemsLabelChangedEvent(IBaseLabelProvider eventSource, IResource[] changedResource, boolean isMarkerChange) {
- super(eventSource, changedResource);
- fMarkerChange= isMarkerChange;
- }
-
- /**
- * Returns whether this event origins from marker changes. If <code>false</code> an annotation
- * model change is the origin. In this case viewers not displaying working copies can ignore these
- * events.
- *
- * @return if this event origins from a marker change.
- */
- public boolean isMarkerChange() {
- return fMarkerChange;
- }
-
- }
-
- private static final int ERRORTICK_WARNING= JavaScriptElementImageDescriptor.WARNING;
- private static final int ERRORTICK_ERROR= JavaScriptElementImageDescriptor.ERROR;
-
- private ImageDescriptorRegistry fRegistry;
- private boolean fUseNewRegistry= false;
- private IProblemChangedListener fProblemChangedListener;
-
- private ListenerList fListeners;
- private ISourceRange fCachedRange;
-
- /**
- * Creates a new <code>ProblemsLabelDecorator</code>.
- */
- public ProblemsLabelDecorator() {
- this(null);
- fUseNewRegistry= true;
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param registry The registry to use or <code>null</code> to use the JavaScript plugin's
- * image registry
- */
- public ProblemsLabelDecorator(ImageDescriptorRegistry registry) {
- fRegistry= registry;
- fProblemChangedListener= null;
- }
-
- private ImageDescriptorRegistry getRegistry() {
- if (fRegistry == null) {
- fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : JavaScriptPlugin.getImageDescriptorRegistry();
- }
- return fRegistry;
- }
-
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateText(String, Object)
- */
- public String decorateText(String text, Object element) {
- return text;
- }
-
- /* (non-Javadoc)
- * @see ILabelDecorator#decorateImage(Image, Object)
- */
- public Image decorateImage(Image image, Object obj) {
- int adornmentFlags= computeAdornmentFlags(obj);
- if (adornmentFlags != 0) {
- ImageDescriptor baseImage= new ImageImageDescriptor(image);
- Rectangle bounds= image.getBounds();
- return getRegistry().get(new JavaScriptElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
- }
- return image;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- *
- * @param obj the element to compute the flags for
- *
- * @return the adornment flags
- */
- protected int computeAdornmentFlags(Object obj) {
- try {
- if (obj instanceof IJavaScriptElement) {
- IJavaScriptElement element= (IJavaScriptElement) obj;
- int type= element.getElementType();
- switch (type) {
- case IJavaScriptElement.JAVASCRIPT_MODEL:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- case IJavaScriptElement.CLASS_FILE:
- return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
- case IJavaScriptElement.IMPORT_DECLARATION:
- case IJavaScriptElement.IMPORT_CONTAINER:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.LOCAL_VARIABLE:
- IJavaScriptUnit cu= (IJavaScriptUnit) element.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- ISourceReference ref= (type == IJavaScriptElement.JAVASCRIPT_UNIT) ? null : (ISourceReference) element;
- // The assumption is that only source elements in compilation unit can have markers
- IAnnotationModel model= isInJavaAnnotationModel(cu);
- int result= 0;
- if (model != null) {
- // open in JavaScript editor: look at annotation model
- result= getErrorTicksFromAnnotationModel(model, ref);
- } else {
- result= getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
- }
- fCachedRange= null;
- return result;
- }
- break;
- default:
- }
- } else if (obj instanceof IResource) {
- return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
- }
- } catch (CoreException e) {
- if (e instanceof JavaScriptModelException) {
- if (((JavaScriptModelException) e).isDoesNotExist()) {
- return 0;
- }
- }
- if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND) {
- return 0;
- }
-
- JavaScriptPlugin.log(e);
- }
- return 0;
- }
-
- private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException {
- if (res == null || !res.isAccessible()) {
- return 0;
- }
- int severity= 0;
- if (sourceElement == null) {
- severity= res.findMaxProblemSeverity(IMarker.PROBLEM, true, depth);
- } else {
- IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
- if (markers != null && markers.length > 0) {
- for (int i= 0; i < markers.length && (severity != IMarker.SEVERITY_ERROR); i++) {
- IMarker curr= markers[i];
- if (isMarkerInRange(curr, sourceElement)) {
- int val= curr.getAttribute(IMarker.SEVERITY, -1);
- if (val == IMarker.SEVERITY_WARNING || val == IMarker.SEVERITY_ERROR) {
- severity= val;
- }
- }
- }
- }
- }
- if (severity == IMarker.SEVERITY_ERROR) {
- return ERRORTICK_ERROR;
- } else if (severity == IMarker.SEVERITY_WARNING) {
- return ERRORTICK_WARNING;
- }
- return 0;
- }
-
- private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException {
- if (marker.isSubtypeOf(IMarker.TEXT)) {
- int pos= marker.getAttribute(IMarker.CHAR_START, -1);
- return isInside(pos, sourceElement);
- }
- return false;
- }
-
- private IAnnotationModel isInJavaAnnotationModel(IJavaScriptUnit original) {
- if (original.isWorkingCopy()) {
- FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource());
- return JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
- }
- return null;
- }
-
-
- private int getErrorTicksFromAnnotationModel(IAnnotationModel model, ISourceReference sourceElement) throws CoreException {
- int info= 0;
- Iterator iter= model.getAnnotationIterator();
- while ((info != ERRORTICK_ERROR) && iter.hasNext()) {
- Annotation annot= (Annotation) iter.next();
- IMarker marker= isAnnotationInRange(model, annot, sourceElement);
- if (marker != null) {
- int priority= marker.getAttribute(IMarker.SEVERITY, -1);
- if (priority == IMarker.SEVERITY_WARNING) {
- info= ERRORTICK_WARNING;
- } else if (priority == IMarker.SEVERITY_ERROR) {
- info= ERRORTICK_ERROR;
- }
- }
- }
- return info;
- }
-
- private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException {
- if (annot instanceof MarkerAnnotation) {
- if (sourceElement == null || isInside(model.getPosition(annot), sourceElement)) {
- IMarker marker= ((MarkerAnnotation) annot).getMarker();
- if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) {
- return marker;
- }
- }
- }
- return null;
- }
-
- private boolean isInside(Position pos, ISourceReference sourceElement) throws CoreException {
- return pos != null && isInside(pos.getOffset(), sourceElement);
- }
-
- /**
- * Tests if a position is inside the source range of an element.
- * @param pos Position to be tested.
- * @param sourceElement Source element (must be a IJavaScriptElement)
- * @return boolean Return <code>true</code> if position is located inside the source element.
- * @throws CoreException Exception thrown if element range could not be accessed.
- *
- *
- */
- protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
- if (fCachedRange == null) {
- fCachedRange= sourceElement.getSourceRange();
- }
- ISourceRange range= fCachedRange;
- if (range != null) {
- int rangeOffset= range.getOffset();
- return (rangeOffset <= pos && rangeOffset + range.getLength() > pos);
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#dispose()
- */
- public void dispose() {
- if (fProblemChangedListener != null) {
- JavaScriptPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
- fProblemChangedListener= null;
- }
- if (fRegistry != null && fUseNewRegistry) {
- fRegistry.dispose();
- }
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#isLabelProperty(Object, String)
- */
- public boolean isLabelProperty(Object element, String property) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#addListener(ILabelProviderListener)
- */
- public void addListener(ILabelProviderListener listener) {
- if (fListeners == null) {
- fListeners= new ListenerList();
- }
- fListeners.add(listener);
- if (fProblemChangedListener == null) {
- fProblemChangedListener= new IProblemChangedListener() {
- public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
- fireProblemsChanged(changedResources, isMarkerChange);
- }
- };
- JavaScriptPlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener);
- }
- }
-
- /* (non-Javadoc)
- * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
- */
- public void removeListener(ILabelProviderListener listener) {
- if (fListeners != null) {
- fListeners.remove(listener);
- if (fListeners.isEmpty() && fProblemChangedListener != null) {
- JavaScriptPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
- fProblemChangedListener= null;
- }
- }
- }
-
- private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) {
- if (fListeners != null && !fListeners.isEmpty()) {
- LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ((ILabelProviderListener) listeners[i]).labelProviderChanged(event);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration)
- */
- public void decorate(Object element, IDecoration decoration) {
- int adornmentFlags= computeAdornmentFlags(element);
- if (adornmentFlags == ERRORTICK_ERROR) {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_ERROR);
- } else if (adornmentFlags == ERRORTICK_WARNING) {
- decoration.addOverlay(JavaPluginImages.DESC_OVR_WARNING);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java
deleted file mode 100644
index 9700d830..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-/**
- *
- */
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.model.IWorkbenchAdapter;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer;
-import org.eclipse.wst.jsdt.internal.ui.packageview.LibraryContainer;
-
-/**
- * @author childsb
- *
- */
-public class ProjectLibraryRoot implements IAdaptable{
-
- private IJavaScriptProject project;
- private static final String LIBRARY_UI_DESC = Messages.getString("ProjectLibraryRoot.0"); //$NON-NLS-1$
-
-
- public static final class WorkBenchAdapter implements IWorkbenchAdapter{
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object)
- */
- public Object[] getChildren(Object o) {
-
- if(o instanceof ProjectLibraryRoot)
- return ((ProjectLibraryRoot)o).getChildren();
- return new Object[0];
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getImageDescriptor(java.lang.Object)
- */
- public ImageDescriptor getImageDescriptor(Object object) {
- return JavaPluginImages.DESC_OBJS_LIBRARY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object)
- */
- public String getLabel(Object o) {
- if(o instanceof ProjectLibraryRoot) {
- return LIBRARY_UI_DESC;
- }
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.model.IWorkbenchAdapter#getParent(java.lang.Object)
- */
- public Object getParent(Object o) {
- // TODO Auto-generated method stub
- System.out.println("Unimplemented method:WorkBenchAdapter.getParent"); //$NON-NLS-1$
- return null;
- }
-
- }
-
- public ProjectLibraryRoot(IJavaScriptProject project) {
- this.project=project;
-
- }
- public IJavaScriptProject getProject() {
- return project;
- }
- public String getText() {
- return ProjectLibraryRoot.LIBRARY_UI_DESC;
- }
-
- public boolean hasChildren() {
- try {
- return project.getPackageFragmentRoots().length > 0;
- }
- catch (JavaScriptModelException e) {
- e.printStackTrace();
- }
- return true;
- }
-
- public Object[] getChildren() {
- if (!project.getProject().isOpen())
- return new Object[0];
- boolean addJARContainer= false;
- ArrayList projectPackageFragmentRoots = new ArrayList();
- IPackageFragmentRoot[] roots = new IPackageFragmentRoot[0];
- try {
- roots = project.getPackageFragmentRoots();
- }
- catch (JavaScriptModelException e1) {}
- next: for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- IIncludePathEntry classpathEntry=null;
- try {
- classpathEntry = root.getRawIncludepathEntry();
- }
- catch (JavaScriptModelException e) {}
-
- int entryKind= classpathEntry.getEntryKind();
- IIncludePathAttribute[] attribs = classpathEntry.getExtraAttributes();
-
- for(int k = 0;attribs!=null && k<attribs.length;k++) {
- if(attribs[k]==IIncludePathAttribute.HIDE) continue next;
-
- }
-
-
- if ( (entryKind != IIncludePathEntry.CPE_SOURCE) && entryKind!=IIncludePathEntry.CPE_CONTAINER) {
- addJARContainer= true;
- projectPackageFragmentRoots.add(root);
- }
- }
-
- if (addJARContainer) {
- projectPackageFragmentRoots.add(new LibraryContainer(project));
- }
-
- // separate loop to make sure all containers are on the classpath
- IIncludePathEntry[] rawClasspath = new IIncludePathEntry[0];
- try {
- rawClasspath = project.getRawIncludepath();
- }
- catch (JavaScriptModelException e) {}
- next2: for (int i= 0; i < rawClasspath.length; i++) {
- IIncludePathEntry classpathEntry= rawClasspath[i];
- IIncludePathAttribute[] attribs = classpathEntry.getExtraAttributes();
-
- for(int k = 0;attribs!=null && k<attribs.length;k++) {
- if(attribs[k].equals(IIncludePathAttribute.HIDE)) continue next2;
- }
-
- if (classpathEntry.getEntryKind() == IIncludePathEntry.CPE_CONTAINER) {
- projectPackageFragmentRoots.add(new JsGlobalScopeContainer(project, classpathEntry));
- }
- }
- return projectPackageFragmentRoots.toArray();
- }
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- public Object getAdapter(Class adapter) {
- if(adapter == IWorkbenchAdapter.class) {
- return new WorkBenchAdapter();
- } else if(adapter == IProject.class){
- return getProject().getProject();
- }
-
- return null;
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof ProjectLibraryRoot)
- return project.equals(((ProjectLibraryRoot) obj).project);
- return super.equals(obj);
- }
-
- public int hashCode() {
- return project.hashCode() + super.hashCode();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java
deleted file mode 100644
index 4133e4f3..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java
+++ /dev/null
@@ -1,509 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Vector;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJarEntryResource;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-
-/**
- * A base content provider for JavaScriptelements. It provides access to the
- * JavaScriptelement hierarchy without listening to changes in the JavaScriptmodel.
- * If updating the presentation on JavaScript model change is required than
- * clients have to subclass, listen to JavaScript model changes and have to update
- * the UI using corresponding methods provided by the JFace viewers or their
- * own UI presentation.
- * <p>
- * The following JavaScript element hierarchy is surfaced by this content provider:
- * <p>
- * <pre>
-JavaScript model (<code>IJavaScriptModel</code>)
- JavaScript project (<code>IJavaScriptProject</code>)
- package fragment root (<code>IPackageFragmentRoot</code>)
- package fragment (<code>IPackageFragment</code>)
- compilation unit (<code>IJavaScriptUnit</code>)
- binary class file (<code>IClassFile</code>)
- * </pre>
- * </p>
- * <p>
- * Note that when the entire JavaScript project is declared to be package fragment root,
- * the corresponding package fragment root element that normally appears between the
- * JavaScript project and the package fragments is automatically filtered out.
- * </p>
- *
- *
- */
-public class StandardJavaScriptElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider {
-
- protected static final Object[] NO_CHILDREN= new Object[0];
- protected boolean fProvideMembers;
- protected boolean fProvideWorkingCopy;
-
- /**
- * Creates a new content provider. The content provider does not
- * provide members of compilation units or class files.
- */
- public StandardJavaScriptElementContentProvider() {
- this(false);
- }
-
- /**
- * Creates a new <code>StandardJavaScriptElementContentProvider</code>.
- *
- * @param provideMembers if <code>true</code> members below compilation units
- * and class files are provided.
- */
- public StandardJavaScriptElementContentProvider(boolean provideMembers) {
- fProvideMembers= provideMembers;
- fProvideWorkingCopy= provideMembers;
- }
-
- /**
- * Returns whether members are provided when asking
- * for a compilation units or class file for its children.
- *
- * @return <code>true</code> if the content provider provides members;
- * otherwise <code>false</code> is returned
- */
- public boolean getProvideMembers() {
- return fProvideMembers;
- }
-
- /**
- * Sets whether the content provider is supposed to return members
- * when asking a compilation unit or class file for its children.
- *
- * @param b if <code>true</code> then members are provided.
- * If <code>false</code> compilation units and class files are the
- * leaves provided by this content provider.
- */
- public void setProvideMembers(boolean b) {
- //hello
- fProvideMembers= b;
- }
-
- /**
- * @deprecated Since 3.0 compilation unit children are always provided as working copies. The JavaScript model
- * does not support the 'original' mode anymore.
- */
- public boolean getProvideWorkingCopy() {
- return fProvideWorkingCopy;
- }
-
- /* (non-Javadoc)
- * @see IWorkingCopyProvider#providesWorkingCopies()
- */
- public boolean providesWorkingCopies() {
- return getProvideWorkingCopy();
- }
-
- /* (non-Javadoc)
- * Method declared on IStructuredContentProvider.
- */
- public Object[] getElements(Object parent) {
- return getChildren(parent);
- }
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- /* (non-Javadoc)
- * Method declared on IContentProvider.
- */
- public void dispose() {
- }
-
- /* (non-Javadoc)
- * Method declared on ITreeContentProvider.
- */
- public Object[] getChildren(Object element) {
- if (!exists(element))
- return NO_CHILDREN;
-
- try {
- if (element instanceof IJavaScriptModel)
- return getJavaProjects((IJavaScriptModel)element);
-
- if (element instanceof IJavaScriptProject)
- return getPackageFragmentRoots((IJavaScriptProject)element);
-
- if (element instanceof IPackageFragmentRoot)
- return getPackageFragmentRootContent((IPackageFragmentRoot)element);
-
- if (element instanceof IPackageFragment)
- return getPackageContent((IPackageFragment)element);
-
- if (element instanceof IFolder)
- return getFolderContent((IFolder)element);
-
- if (element instanceof IJarEntryResource) {
- return ((IJarEntryResource) element).getChildren();
- }
-
- if (getProvideMembers() && element instanceof ISourceReference && element instanceof IParent) {
-
- //@GINO: Anonymous Filter top level anonymous
- if( element instanceof ITypeRoot )
- return filter( ((IParent)element).getChildren() );
- else
- return ((IParent)element).getChildren();
-
- }
- } catch (CoreException e) {
- return NO_CHILDREN;
- }
- return NO_CHILDREN;
- }
-
- /*
- * @GINO: Anonymous -- matches anonymous types on the top level
- */
- protected boolean matches(IJavaScriptElement element) {
-
- if (element.getElementType() == IJavaScriptElement.TYPE && (element.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT || element.getParent().getElementType() == IJavaScriptElement.CLASS_FILE) ) {
-
- IType type = (IType)element;
- try {
- return type.isAnonymous();
- } catch (JavaScriptModelException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return false;
- }
-
- /*
- * @GINO: Anonymous Filter from top level
- *
- */
- protected IJavaScriptElement[] filter(IJavaScriptElement[] children) {
- boolean initializers= false;
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i])) {
- initializers= true;
- break;
- }
- }
-
- if (!initializers)
- return children;
-
- Vector v= new Vector();
- for (int i= 0; i < children.length; i++) {
- if (matches(children[i]))
- continue;
- v.addElement(children[i]);
- }
-
- IJavaScriptElement[] result= new IJavaScriptElement[v.size()];
- v.copyInto(result);
- return result;
- }
-
- /* (non-Javadoc)
- * @see ITreeContentProvider
- */
- public boolean hasChildren(Object element) {
- if (getProvideMembers()) {
- // assume CUs and class files are never empty
- if (element instanceof IJavaScriptUnit || element instanceof IClassFile) {
- try {
- if(element instanceof IJavaScriptUnit ) {
- IJavaScriptUnit cu = (IJavaScriptUnit)element;
- return cu.hasChildren();
- }else if(element instanceof IClassFile) {
- IClassFile cf = (IClassFile)element;
- return cf.hasChildren();
- }
- }catch(JavaScriptModelException ex) {
- return false;
- }
-
-
- return true;
- }
- } else {
- // don't allow to drill down into a compilation unit or class file
- if (element instanceof IJavaScriptUnit ||
- element instanceof IClassFile ||
- element instanceof IFile)
- return false;
- }
-
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jp= (IJavaScriptProject)element;
- if (!jp.getProject().isOpen()) {
- return false;
- }
- }
-
- if (element instanceof IParent) {
- try {
- // when we have JavaScript children return true, else we fetch all the children
- if (((IParent)element).hasChildren())
- return true;
- } catch(JavaScriptModelException e) {
- return true;
- }
- }
- Object[] children= getChildren(element);
- return (children != null) && children.length > 0;
- }
-
- /* (non-Javadoc)
- * Method declared on ITreeContentProvider.
- */
- public Object getParent(Object element) {
- if (!exists(element))
- return null;
- return internalGetParent(element);
- }
-
- /**
- * Evaluates all children of a given {@link IPackageFragmentRoot}. Clients can override this method.
- * @param root The root to evaluate the children for.
- * @return The children of the root
- * @exception JavaScriptModelException if the package fragment root does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- *
- */
- protected Object[] getPackageFragmentRootContent(IPackageFragmentRoot root) throws JavaScriptModelException {
- IJavaScriptElement[] fragments= root.getChildren();
- if (isProjectPackageFragmentRoot(root)) {
- return fragments;
- }
- Object[] nonJavaResources= root.getNonJavaScriptResources();
- if (nonJavaResources == null)
- return fragments;
- return concatenate(fragments, nonJavaResources);
- }
-
- /**
- * Evaluates all children of a given {@link IJavaScriptProject}. Clients can override this method.
- * @param project The JavaScript project to evaluate the children for.
- * @return The children of the project. Typically these are package fragment roots but can also be other elements.
- * @exception JavaScriptModelException if the JavaScript project does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- protected Object[] getPackageFragmentRoots(IJavaScriptProject project) throws JavaScriptModelException {
- if (!project.getProject().isOpen())
- return NO_CHILDREN;
-
- IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
- List list= new ArrayList(roots.length);
- // filter out package fragments that correspond to projects and
- // replace them with the package fragments directly
- for (int i= 0; i < roots.length; i++) {
- IPackageFragmentRoot root= roots[i];
- if (isProjectPackageFragmentRoot(root)) {
- Object[] fragments= getPackageFragmentRootContent(root);
- for (int j= 0; j < fragments.length; j++) {
- list.add(fragments[j]);
- }
- } else {
- list.add(root);
- }
- }
- Object[] resources= project.getNonJavaScriptResources();
- for (int i= 0; i < resources.length; i++) {
- list.add(resources[i]);
- }
- return list.toArray();
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected Object[] getJavaProjects(IJavaScriptModel jm) throws JavaScriptModelException {
- return jm.getJavaScriptProjects();
- }
-
- /**
- * Evaluates all children of a given {@link IPackageFragment}. Clients can override this method.
- * @param fragment The fragment to evaluate the children for.
- * @return The children of the given package fragment.
- * @exception JavaScriptModelException if the package fragment does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- *
- */
- protected Object[] getPackageContent(IPackageFragment fragment) throws JavaScriptModelException {
- if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
- return concatenate(fragment.getJavaScriptUnits(), fragment.getNonJavaScriptResources());
- }
- return concatenate(fragment.getClassFiles(), fragment.getNonJavaScriptResources());
- }
-
- /**
- * Evaluates all children of a given {@link IFolder}. Clients can override this method.
- * @param folder The folder to evaluate the children for.
- * @return The children of the given package fragment.
- * @exception CoreException if the folder does not exist.
- *
- *
- */
- protected Object[] getFolderContent(IFolder folder) throws CoreException {
- IResource[] members= folder.members();
- IJavaScriptProject javaProject= JavaScriptCore.create(folder.getProject());
- if (javaProject == null || !javaProject.exists())
- return members;
- boolean isFolderOnClasspath = javaProject.isOnIncludepath(folder);
- List nonJavaResources= new ArrayList();
- // Can be on classpath but as a member of non-JavaScript resource folder
- for (int i= 0; i < members.length; i++) {
- IResource member= members[i];
- // A resource can also be a JavaScript element
- // in the case of exclusion and inclusion filters.
- // We therefore exclude JavaScript elements from the list
- // of non-JavaScript resources.
- if (isFolderOnClasspath) {
- if (javaProject.findPackageFragmentRoot(member.getFullPath()) == null) {
- nonJavaResources.add(member);
- }
- } else if (!javaProject.isOnIncludepath(member)) {
- nonJavaResources.add(member);
- }
- }
- return nonJavaResources.toArray();
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected boolean isClassPathChange(IJavaScriptElementDelta delta) {
-
- // need to test the flags only for package fragment roots
- if (delta.getElement().getElementType() != IJavaScriptElement.PACKAGE_FRAGMENT_ROOT)
- return false;
-
- int flags= delta.getFlags();
- return (delta.getKind() == IJavaScriptElementDelta.CHANGED &&
- ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) != 0) ||
- ((flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) ||
- ((flags & IJavaScriptElementDelta.F_REORDER) != 0));
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) {
- if (isProjectPackageFragmentRoot(root))
- return root.getParent();
- return root;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected boolean isPackageFragmentEmpty(IJavaScriptElement element) throws JavaScriptModelException {
- if (element instanceof IPackageFragment) {
- IPackageFragment fragment= (IPackageFragment)element;
- if (fragment.exists() && !(fragment.hasChildren() || fragment.getNonJavaScriptResources().length > 0) && fragment.hasSubpackages())
- return true;
- }
- return false;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) {
- IJavaScriptProject javaProject= root.getJavaScriptProject();
- return javaProject != null && javaProject.getPath().equals(root.getPath());
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected boolean exists(Object element) {
- if (element == null) {
- return false;
- }
- if (element instanceof IResource) {
- return ((IResource)element).exists();
- }
- if (element instanceof IJavaScriptElement) {
- return ((IJavaScriptElement)element).exists();
- }
- return true;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected Object internalGetParent(Object element) {
-
- // try to map resources to the containing package fragment
- if (element instanceof IResource) {
- IResource parent= ((IResource)element).getParent();
- IJavaScriptElement jParent= JavaScriptCore.create(parent);
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=31374
- if (jParent != null && jParent.exists())
- return jParent;
- return parent;
- } else if (element instanceof IJavaScriptElement) {
- IJavaScriptElement parent= ((IJavaScriptElement) element).getParent();
- // for package fragments that are contained in a project package fragment
- // we have to skip the package fragment root as the parent.
- if (element instanceof IPackageFragment) {
- return skipProjectPackageFragmentRoot((IPackageFragmentRoot) parent);
- }
- return parent;
- } else if (element instanceof IJarEntryResource) {
- return ((IJarEntryResource) element).getParent();
- }
- return null;
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- protected static Object[] concatenate(Object[] a1, Object[] a2) {
- int a1Len= a1.length;
- int a2Len= a2.length;
- if (a1Len == 0) return a2;
- if (a2Len == 0) return a1;
- Object[] res= new Object[a1Len + a2Len];
- System.arraycopy(a1, 0, res, 0, a1Len);
- System.arraycopy(a2, 0, res, a1Len, a2Len);
- return res;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AbstractOpenWizardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AbstractOpenWizardAction.java
deleted file mode 100644
index 5357800f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AbstractOpenWizardAction.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.NewProjectAction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-
-/**
- * <p>Abstract base classed used for the open wizard actions.</p>
- *
- * <p>
- * Note: This class is for internal use only. Clients should not use this class.
- * </p>
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public abstract class AbstractOpenWizardAction extends Action {
-
- private Shell fShell;
- private IStructuredSelection fSelection;
- private IJavaScriptElement fCreatedElement;
-
- /**
- * Creates the action.
- */
- protected AbstractOpenWizardAction() {
- fShell= null;
- fSelection= null;
- fCreatedElement= null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.action.Action#run()
- */
- public void run() {
- Shell shell= getShell();
- if (!doCreateProjectFirstOnEmptyWorkspace(shell)) {
- return;
- }
- try {
- INewWizard wizard= createWizard();
- wizard.init(PlatformUI.getWorkbench(), getSelection());
-
- WizardDialog dialog= new WizardDialog(shell, wizard);
- PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont());
- dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20));
- dialog.create();
- int res= dialog.open();
- if (res == Window.OK && wizard instanceof NewElementWizard) {
- fCreatedElement= ((NewElementWizard)wizard).getCreatedElement();
- }
-
- notifyResult(res == Window.OK);
- } catch (CoreException e) {
- String title= NewWizardMessages.AbstractOpenWizardAction_createerror_title;
- String message= NewWizardMessages.AbstractOpenWizardAction_createerror_message;
- ExceptionHandler.handle(e, shell, title, message);
- }
- }
-
- /**
- * Creates and configures the wizard. This method should only be called once.
- * @return returns the created wizard.
- * @throws CoreException exception is thrown when the creation was not successful.
- */
- abstract protected INewWizard createWizard() throws CoreException;
-
- /**
- * Returns the configured selection. If no selection has been configured using {@link #setSelection(IStructuredSelection)},
- * the currently selected element of the active workbench is returned.
- * @return the configured selection
- */
- protected IStructuredSelection getSelection() {
- if (fSelection == null) {
- return evaluateCurrentSelection();
- }
- return fSelection;
- }
-
- private IStructuredSelection evaluateCurrentSelection() {
- IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (window != null) {
- ISelection selection= window.getSelectionService().getSelection();
- if (selection instanceof IStructuredSelection) {
- return (IStructuredSelection) selection;
- }
- }
- return StructuredSelection.EMPTY;
- }
-
- /**
- * Configures the selection to be used as initial selection of the wizard.
- * @param selection the selection to be set or <code>null</code> to use the selection of the active workbench window
- */
- public void setSelection(IStructuredSelection selection) {
- fSelection= selection;
- }
-
- /**
- * Returns the configured shell. If no shell has been configured using {@link #setShell(Shell)},
- * the shell of the currently active workbench is returned.
- * @return the configured shell
- */
- protected Shell getShell() {
- if (fShell == null) {
- return JavaScriptPlugin.getActiveWorkbenchShell();
- }
- return fShell;
- }
-
- /**
- * Configures the shell to be used as parent shell by the wizard.
- * @param shell the shell to be set or <code>null</code> to use the shell of the active workbench window
- */
- public void setShell(Shell shell) {
- fShell= shell;
- }
-
- /**
- * Opens the new project dialog if the workspace is empty. This method is called on {@link #run()}.
- * @param shell the shell to use
- * @return returns <code>true</code> when a project has been created, or <code>false</code> when the
- * new project has been canceled.
- */
- protected boolean doCreateProjectFirstOnEmptyWorkspace(Shell shell) {
- IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
- if (workspaceRoot.getProjects().length == 0) {
- String title= NewWizardMessages.AbstractOpenWizardAction_noproject_title;
- String message= NewWizardMessages.AbstractOpenWizardAction_noproject_message;
- if (MessageDialog.openQuestion(shell, title, message)) {
- new NewProjectAction().run();
- return workspaceRoot.getProjects().length != 0;
- }
- return false;
- }
- return true;
- }
-
- /**
- * Returns the created element or <code>null</code> if the wizard has not run or was canceled.
- * @return the created element or <code>null</code>
- */
- public IJavaScriptElement getCreatedElement() {
- return fCreatedElement;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddDelegateMethodsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddDelegateMethodsAction.java
deleted file mode 100644
index dca9ed18..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddDelegateMethodsAction.java
+++ /dev/null
@@ -1,596 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * Martin Moebius (m.moebius@gmx.de) - initial API and implementation
- * (report 28793)
- * IBM Corporation - updates
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.IBinding;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddDelegateMethodsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-import com.ibm.icu.text.Collator;
-
-/**
- * Creates delegate methods for a type's fields. Opens a dialog with a list of fields for
- * which delegate methods can be generated. User is able to check or uncheck items before
- * methods are generated.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. The result is unsaved, so the
- * user can decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements of type
- * <code>IField</code> or <code>IType</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class AddDelegateMethodsAction extends SelectionDispatchAction {
-
- // ---- Helpers -------------------------------------------------------------------
-
- private static class AddDelegateMethodsActionStatusValidator implements ISelectionStatusValidator {
-
- private static int fEntries;
-
- AddDelegateMethodsActionStatusValidator(int entries) {
- fEntries= entries;
- }
-
- public IStatus validate(Object[] selection) {
- StatusInfo info= new StatusInfo();
- if (selection != null && selection.length > 0) {
- int count= 0;
- List bindings= new ArrayList(selection.length);
- IFunctionBinding binding= null;
- for (int index= 0; index < selection.length; index++) {
- if (selection[index] instanceof IBinding[]) {
- count++;
- binding= (IFunctionBinding) ((IBinding[]) selection[index])[1];
- IFunctionBinding existing= null;
- for (int offset= 0; offset < bindings.size(); offset++) {
- existing= (IFunctionBinding) bindings.get(offset);
- if (Bindings.isEqualMethod(binding, existing.getName(), existing.getParameterTypes())) {
- return new StatusInfo(IStatus.ERROR, ActionMessages.AddDelegateMethodsAction_duplicate_methods);
- }
- }
- bindings.add(binding);
- info= new StatusInfo(IStatus.INFO, Messages.format(ActionMessages.AddDelegateMethodsAction_selectioninfo_more, new Object[] { String.valueOf(count), String.valueOf(fEntries)}));
- }
- }
- }
- return info;
- }
- }
-
- private static class AddDelegateMethodsContentProvider implements ITreeContentProvider {
-
- private IBinding[][] fBindings= new IBinding[0][0];
-
- private int fCount= 0;
-
- private IVariableBinding[] fExpanded= new IVariableBinding[0];
-
- private final JavaScriptUnit fUnit;
-
- AddDelegateMethodsContentProvider(IType type, IField[] fields) throws JavaScriptModelException {
- RefactoringASTParser parser= new RefactoringASTParser(AST.JLS3);
- fUnit= parser.parse(type.getJavaScriptUnit(), true);
- final ITypeBinding binding= ASTNodes.getTypeBinding(fUnit, type);
- if (binding != null) {
- IBinding[][] bindings= StubUtility2.getDelegatableMethods(fUnit.getAST(), binding);
- if (bindings != null) {
- fBindings= bindings;
- fCount= bindings.length;
- }
- List expanded= new ArrayList();
- for (int index= 0; index < fields.length; index++) {
- VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(fields[index], fUnit);
- if (fragment != null) {
- IVariableBinding variableBinding= fragment.resolveBinding();
- if (variableBinding != null)
- expanded.add(variableBinding);
- }
- }
- IVariableBinding[] result= new IVariableBinding[expanded.size()];
- expanded.toArray(result);
- fExpanded= result;
- }
- }
-
- public JavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- public void dispose() {
- }
-
- public Object[] getChildren(Object element) {
- if (element instanceof IVariableBinding) {
- IVariableBinding binding= (IVariableBinding) element;
- List result= new ArrayList();
- final String key= binding.getKey();
- for (int index= 0; index < fBindings.length; index++)
- if (fBindings[index][0].getKey().equals(key))
- result.add(fBindings[index]);
- return result.toArray();
- }
- return null;
- }
-
- public int getCount() {
- return fCount;
- }
-
- public Object[] getElements(Object inputElement) {
- Set keys= new HashSet();
- List result= new ArrayList();
- for (int index= 0; index < fBindings.length; index++) {
- IBinding[] bindings= fBindings[index];
- final String key= bindings[0].getKey();
- if (!keys.contains(key)) {
- keys.add(key);
- result.add(bindings[0]);
- }
- }
- return result.toArray();
- }
-
- public IVariableBinding[] getExpandedElements() {
- return fExpanded;
- }
-
- public IBinding[][] getInitiallySelectedElements() {
- List result= new ArrayList();
- for (int index= 0; index < fBindings.length; index++)
- for (int offset= 0; offset < fExpanded.length; offset++)
- if (fExpanded[offset].getKey().equals(fBindings[index][0].getKey()))
- result.add(fBindings[index]);
- return (IBinding[][]) result.toArray(new IBinding[result.size()][2]);
- }
-
- public Object getParent(Object element) {
- if (element instanceof IBinding[])
- return ((IBinding[]) element)[0];
- return null;
- }
-
- public boolean hasChildren(Object element) {
- return element instanceof IVariableBinding;
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- private static class AddDelegateMethodsDialog extends SourceActionDialog {
-
- public AddDelegateMethodsDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type, boolean isConstructor) throws JavaScriptModelException {
- super(parent, labelProvider, contentProvider, editor, type, isConstructor);
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.ADD_DELEGATE_METHODS_SELECTION_DIALOG);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog#createLinkControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP);
- link.setText(ActionMessages.AddDelegateMethodsAction_template_link_message);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.OVERRIDECOMMENT_ID);
- }
- });
- link.setToolTipText(ActionMessages.AddDelegateMethodsAction_template_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
- link.setLayoutData(gridData);
- return link;
- }
- }
-
- private static class AddDelegateMethodsLabelProvider extends BindingLabelProvider {
-
- public Image getImage(Object element) {
- if (element instanceof IBinding[]) {
- return super.getImage((((IBinding[]) element)[1]));
- } else if (element instanceof IVariableBinding) {
- return super.getImage(element);
- }
- return null;
- }
-
- public String getText(Object element) {
- if (element instanceof IBinding[]) {
- return super.getText((((IBinding[]) element)[1]));
- } else if (element instanceof IVariableBinding) {
- return super.getText(element);
- }
- return null;
- }
- }
-
- private static class AddDelegateMethodsViewerComparator extends ViewerComparator {
-
- private final BindingLabelProvider fProvider= new BindingLabelProvider();
- private final Collator fCollator= Collator.getInstance();
-
- public int category(Object element) {
- if (element instanceof IBinding[])
- return 0;
- return 1;
- }
-
- public int compare(Viewer viewer, Object object1, Object object2) {
- String first= ""; //$NON-NLS-1$
- String second= ""; //$NON-NLS-1$
- if (object1 instanceof IBinding[])
- first= fProvider.getText(((IBinding[]) object1)[1]);
- else if (object1 instanceof IVariableBinding)
- first= ((IBinding) object1).getName();
- if (object2 instanceof IBinding[])
- second= fProvider.getText(((IBinding[]) object2)[1]);
- else if (object2 instanceof IVariableBinding)
- second= ((IBinding) object2).getName();
- return fCollator.compare(first, second);
- }
- }
-
- private static final String DIALOG_TITLE= ActionMessages.AddDelegateMethodsAction_error_title;
-
- private static boolean hasPrimitiveType(IField field) throws JavaScriptModelException {
- String signature= field.getTypeSignature();
- char first= Signature.getElementType(signature).charAt(0);
- return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED);
- }
-
- private static boolean isArray(IField field) throws JavaScriptModelException {
- return Signature.getArrayCount(field.getTypeSignature()) > 0;
- }
-
- private CompilationUnitEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this
- * constructor.
- *
- * @param editor the compilation unit editor
- */
- public AddDelegateMethodsAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
- }
-
- /**
- * Creates a new <code>AddDelegateMethodsAction</code>. The action requires that
- * the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public AddDelegateMethodsAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.AddDelegateMethodsAction_label);
- setDescription(ActionMessages.AddDelegateMethodsAction_description);
- setToolTipText(ActionMessages.AddDelegateMethodsAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_DELEGATE_METHODS_ACTION);
- }
-
- private boolean canEnable(IStructuredSelection selection) throws JavaScriptModelException {
- if (getSelectedFields(selection) != null)
- return true;
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
- IType type= (IType) selection.getFirstElement();
- return type.getJavaScriptUnit() != null;
- }
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IJavaScriptUnit))
- return true;
-
- return false;
- }
-
- private boolean canRunOn(IField[] fields) throws JavaScriptModelException {
- if (fields == null || fields.length == 0)
- return false;
- int count= 0;
- for (int index= 0; index < fields.length; index++) {
- if (!hasPrimitiveType(fields[index]) || isArray(fields[index]))
- count++;
- }
- if (count == 0)
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_not_applicable);
- return (count > 0);
- }
-
- private boolean canRunOn(IType type) throws JavaScriptModelException {
- if (type == null || type.getJavaScriptUnit() == null) {
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_not_in_source_file);
- return false;
- }
- return canRunOn(type.getFields());
- }
-
- private IField[] getSelectedFields(IStructuredSelection selection) {
- List elements= selection.toList();
- if (elements.size() > 0) {
- IField[] result= new IField[elements.size()];
- IJavaScriptUnit unit= null;
- for (int index= 0; index < elements.size(); index++) {
- if (elements.get(index) instanceof IField) {
- IField field= (IField) elements.get(index);
-
- if (index == 0) {
- // remember the CU of the first element
- unit= field.getJavaScriptUnit();
- if (unit == null) {
- return null;
- }
- } else if (!unit.equals(field.getJavaScriptUnit())) {
- // all fields must be in the same CU
- return null;
- }
-
- result[index]= field;
- } else {
- return null;
- }
- }
- return result;
- }
- return null;
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- try {
- IField[] selectedFields= getSelectedFields(selection);
- if (canRunOn(selectedFields)) {
- run(selectedFields[0].getDeclaringType(), selectedFields, false);
- return;
- }
- Object firstElement= selection.getFirstElement();
- if (firstElement instanceof IType)
- run((IType) firstElement, new IField[0], false);
- else if (firstElement instanceof IJavaScriptUnit)
- run(JavaElementUtil.getMainType((IJavaScriptUnit) firstElement), new IField[0], false);
- else if (!(firstElement instanceof IField))
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_not_applicable);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_error_actionfailed);
- }
-
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- if (!ActionUtil.isProcessable(fEditor))
- return;
-
- IJavaScriptElement[] elements= SelectionConverter.codeResolveForked(fEditor, true);
- if (elements.length == 1 && (elements[0] instanceof IField)) {
- IField field= (IField) elements[0];
- run(field.getDeclaringType(), new IField[] { field}, true);
- return;
- }
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element != null) {
- IType type= (IType) element.getAncestor(IJavaScriptElement.TYPE);
- if (type != null) {
- if (type.getFields().length > 0) {
- run(type, new IField[0], true);
- return;
- }
- }
- }
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_not_applicable);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_error_actionfailed);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_error_actionfailed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
- if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor))
- return;
- if (!ActionUtil.isEditable(fEditor, getShell(), type))
- return;
- if (!canRunOn(type))
- return;
- showUI(type, preselected);
- }
-
- // ---- Structured Viewer -----------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(canEnable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- // ---- JavaScript Editor --------------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- private void showUI(IType type, IField[] fields) {
- try {
- AddDelegateMethodsContentProvider provider= new AddDelegateMethodsContentProvider(type, fields);
- SourceActionDialog dialog= new AddDelegateMethodsDialog(getShell(), new AddDelegateMethodsLabelProvider(), provider, fEditor, type, false);
- dialog.setValidator(new AddDelegateMethodsActionStatusValidator(provider.getCount()));
- AddDelegateMethodsViewerComparator comparator= new AddDelegateMethodsViewerComparator();
- dialog.setComparator(comparator);
- dialog.setInput(new Object());
- dialog.setContainerMode(true);
- dialog.setMessage(ActionMessages.AddDelegateMethodsAction_message);
- dialog.setTitle(ActionMessages.AddDelegateMethodsAction_title);
- IVariableBinding[] expanded= provider.getExpandedElements();
- if (expanded.length > 0) {
- dialog.setExpandedElements(expanded);
- } else {
- Object[] elements= provider.getElements(null);
- if (elements.length > 0) {
- comparator.sort(null, elements);
- Object[] expand= { elements[0]};
- dialog.setExpandedElements(expand);
- }
- }
- dialog.setInitialSelections(provider.getInitiallySelectedElements());
- dialog.setSize(60, 18);
- int result= dialog.open();
- if (result == Window.OK) {
- Object[] object= dialog.getResult();
- if (object == null) {
- notifyResult(false);
- return;
- }
- List tuples= new ArrayList(object.length);
- for (int index= 0; index < object.length; index++) {
- if (object[index] instanceof IBinding[])
- tuples.add(object[index]);
- }
- IEditorPart part= JavaScriptUI.openInEditor(type);
- IRewriteTarget target= (IRewriteTarget) part.getAdapter(IRewriteTarget.class);
- try {
- if (target != null)
- target.beginCompoundChange();
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject());
- settings.createComments= dialog.getGenerateComment();
- final int size= tuples.size();
- String[] methodKeys= new String[size];
- String[] variableKeys= new String[size];
- for (int index= 0; index < size; index++) {
- final IBinding[] tuple= (IBinding[]) tuples.get(index);
- variableKeys[index]= tuple[0].getKey();
- methodKeys[index]= tuple[1].getKey();
- }
- AddDelegateMethodsOperation operation= new AddDelegateMethodsOperation(type, dialog.getElementPosition(), provider.getCompilationUnit(), variableKeys, methodKeys, settings, true, false);
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null)
- context= new BusyIndicatorRunnableContext();
- try {
- PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
- } catch (InterruptedException exception) {
- // User interruption
- }
- } finally {
- if (target != null)
- target.endCompoundChange();
- }
- }
- notifyResult(result == Window.OK);
- } catch (CoreException exception) {
- ExceptionHandler.handle(exception, DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_error_actionfailed);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.AddDelegateMethodsAction_error_actionfailed);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddGetterSetterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddGetterSetterAction.java
deleted file mode 100644
index 5da2e015..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddGetterSetterAction.java
+++ /dev/null
@@ -1,1083 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Philippe Ombredanne - bug 149382
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddGetterSetterOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.GetterSetterUtil;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.IRequestQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Creates getter and setter methods for a type's fields. Opens a dialog with a list of
- * fields for which a setter or getter can be generated. User is able to check or uncheck
- * items before setters or getters are generated.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. The result is unsaved, so the
- * user can decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements of type
- * <code>IField</code> or <code>IType</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class AddGetterSetterAction extends SelectionDispatchAction {
-
- private boolean fSort;
-
- //private boolean fFinal;
-
- private int fVisibility;
-
- private boolean fGenerateComment;
-
- private int fNumEntries;
-
- private CompilationUnitEditor fEditor;
-
- private static final String DIALOG_TITLE= ActionMessages.AddGetterSetterAction_error_title;
-
- /**
- * Creates a new <code>AddGetterSetterAction</code>. The action requires that the
- * selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public AddGetterSetterAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.AddGetterSetterAction_label);
- setDescription(ActionMessages.AddGetterSetterAction_description);
- setToolTipText(ActionMessages.AddGetterSetterAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this
- * constructor.
- *
- * @param editor the compilation unit editor
- */
- public AddGetterSetterAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
- fEditor.getEditorSite();
- }
-
- // ---- Structured Viewer -----------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(canEnable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- try {
- IField[] selectedFields= getSelectedFields(selection);
- if (canRunOn(selectedFields)) {
- run(selectedFields[0].getDeclaringType(), selectedFields, false);
- return;
- }
- Object firstElement= selection.getFirstElement();
-
- if (firstElement instanceof IType)
- run((IType) firstElement, new IField[0], false);
- else if (firstElement instanceof IJavaScriptUnit) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38500
- IType type= ((IJavaScriptUnit) firstElement).findPrimaryType();
- // type can be null if file has a bad encoding
- if (type == null) {
- MessageDialog.openError(getShell(),
- ActionMessages.AddGetterSetterAction_no_primary_type_title,
- ActionMessages.AddGetterSetterAction_no_primary_type_message);
- notifyResult(false);
- return;
- }
-
- run(((IJavaScriptUnit) firstElement).findPrimaryType(), new IField[0], false);
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_error_actionfailed);
- }
-
- }
-
- private boolean canEnable(IStructuredSelection selection) throws JavaScriptModelException {
- if (getSelectedFields(selection) != null)
- return true;
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
- IType type= (IType) selection.getFirstElement();
- return type.getJavaScriptUnit() != null && !type.isLocal();
- }
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IJavaScriptUnit))
- return true;
-
- return false;
- }
-
- private boolean canRunOn(IField[] fields) throws JavaScriptModelException {
- if (fields == null || fields.length == 0)
- return false;
- int count= 0;
- for (int index= 0; index < fields.length; index++) {
- count++;
- }
- if (count == 0)
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_not_applicable);
- return (count > 0);
- }
-
- private void resetNumEntries() {
- fNumEntries= 0;
- }
-
- private void incNumEntries() {
- fNumEntries++;
- }
-
- private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
- if (type.getJavaScriptUnit() == null) {
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_error_not_in_source_file);
- notifyResult(false);
- return;
- }
- if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor)) {
- notifyResult(false);
- return;
- }
- if (!ActionUtil.isEditable(getShell(), type)) {
- notifyResult(false);
- return;
- }
-
- ILabelProvider lp= new AddGetterSetterLabelProvider();
- resetNumEntries();
- Map entries= createGetterSetterMapping(type);
- if (entries.isEmpty()) {
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddGettSetterAction_typeContainsNoFields_message);
- notifyResult(false);
- return;
- }
- AddGetterSetterContentProvider cp= new AddGetterSetterContentProvider(entries);
- GetterSetterTreeSelectionDialog dialog= new GetterSetterTreeSelectionDialog(getShell(), lp, cp, fEditor, type);
- dialog.setComparator(new JavaScriptElementComparator());
- dialog.setTitle(DIALOG_TITLE);
- String message= ActionMessages.AddGetterSetterAction_dialog_label;
- dialog.setMessage(message);
- dialog.setValidator(createValidator(fNumEntries));
- dialog.setContainerMode(true);
- dialog.setSize(60, 18);
- dialog.setInput(type);
-
- if (preselected.length > 0) {
- dialog.setInitialSelections(preselected);
- dialog.setExpandedElements(preselected);
- }
- final Set keySet= new LinkedHashSet(entries.keySet());
- int dialogResult= dialog.open();
- if (dialogResult == Window.OK) {
- Object[] result= dialog.getResult();
- if (result == null) {
- notifyResult(false);
- return;
- }
- fSort= dialog.getSortOrder();
- //fFinal= dialog.getFinal();
- fVisibility= dialog.getVisibilityModifier();
- fGenerateComment= dialog.getGenerateComment();
- IField[] getterFields, setterFields, getterSetterFields;
- if (fSort) {
- getterFields= getGetterFields(result, keySet);
- setterFields= getSetterFields(result, keySet);
- getterSetterFields= new IField[0];
- } else {
- getterFields= getGetterOnlyFields(result, keySet);
- setterFields= getSetterOnlyFields(result, keySet);
- getterSetterFields= getGetterSetterFields(result, keySet);
- }
- generate(type, getterFields, setterFields, getterSetterFields, new RefactoringASTParser(AST.JLS3).parse(type.getJavaScriptUnit(), true), dialog.getElementPosition());
- }
- notifyResult(dialogResult == Window.OK);
- }
-
- private static class AddGetterSetterSelectionStatusValidator implements ISelectionStatusValidator {
-
- private static int fEntries;
-
- AddGetterSetterSelectionStatusValidator(int entries) {
- fEntries= entries;
- }
-
- public IStatus validate(Object[] selection) {
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38478
- HashSet map= null;
- if ((selection != null) && (selection.length > 1)) {
- map= new HashSet(selection.length);
- }
-
- int count= 0;
- for (int i= 0; i < selection.length; i++) {
- try {
- if (selection[i] instanceof GetterSetterEntry) {
- Object key= selection[i];
- IField getsetField= ((GetterSetterEntry) selection[i]).field;
- if (((GetterSetterEntry) selection[i]).isGetter) {
- if (!map.add(GetterSetterUtil.getGetterName(getsetField, null)))
- return new StatusInfo(IStatus.WARNING, ActionMessages.AddGetterSetterAction_error_duplicate_methods);
- } else {
- key= createSignatureKey(GetterSetterUtil.getSetterName(getsetField, null), getsetField);
- if (!map.add(key))
- return new StatusInfo(IStatus.WARNING, ActionMessages.AddGetterSetterAction_error_duplicate_methods);
- }
- count++;
- }
- } catch (JavaScriptModelException e) {
- }
- }
-
- if (count == 0)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- String message= Messages.format(ActionMessages.AddGetterSetterAction_methods_selected,
- new Object[] { String.valueOf(count), String.valueOf(fEntries)});
- return new StatusInfo(IStatus.INFO, message);
- }
- }
-
- /**
- * Creates a key used in hash maps for a method signature
- * (gettersettername+arguments(fqn)).
- */
- private static String createSignatureKey(String methodName, IField field) throws JavaScriptModelException {
- StringBuffer buffer= new StringBuffer();
- buffer.append(methodName);
- String fieldType= field.getTypeSignature();
- String signature= Signature.getSimpleName(Signature.toString(fieldType));
- buffer.append("#"); //$NON-NLS-1$
- buffer.append(signature);
-
- return buffer.toString();
- }
-
- private static ISelectionStatusValidator createValidator(int entries) {
- AddGetterSetterSelectionStatusValidator validator= new AddGetterSetterSelectionStatusValidator(entries);
- return validator;
- }
-
- // returns a list of fields with setter entries checked
- private static IField[] getSetterFields(Object[] result, Set set) {
- List list= new ArrayList(0);
- Object each= null;
- GetterSetterEntry entry= null;
- for (int i= 0; i < result.length; i++) {
- each= result[i];
- if ((each instanceof GetterSetterEntry)) {
- entry= (GetterSetterEntry) each;
- if (!entry.isGetter) {
- list.add(entry.field);
- }
- }
- }
- list= reorderFields(list, set);
- return (IField[]) list.toArray(new IField[list.size()]);
- }
-
- // returns a list of fields with getter entries checked
- private static IField[] getGetterFields(Object[] result, Set set) {
- List list= new ArrayList(0);
- Object each= null;
- GetterSetterEntry entry= null;
- for (int i= 0; i < result.length; i++) {
- each= result[i];
- if ((each instanceof GetterSetterEntry)) {
- entry= (GetterSetterEntry) each;
- if (entry.isGetter) {
- list.add(entry.field);
- }
- }
- }
- list= reorderFields(list, set);
- return (IField[]) list.toArray(new IField[list.size()]);
- }
-
- // returns a list of fields with only getter entries checked
- private static IField[] getGetterOnlyFields(Object[] result, Set set) {
- List list= new ArrayList(0);
- Object each= null;
- GetterSetterEntry entry= null;
- boolean getterSet= false;
- for (int i= 0; i < result.length; i++) {
- each= result[i];
- if ((each instanceof GetterSetterEntry)) {
- entry= (GetterSetterEntry) each;
- if (entry.isGetter) {
- list.add(entry.field);
- getterSet= true;
- }
- if ((!entry.isGetter) && (getterSet == true)) {
- list.remove(entry.field);
- getterSet= false;
- }
- } else
- getterSet= false;
- }
- list= reorderFields(list, set);
- return (IField[]) list.toArray(new IField[list.size()]);
- }
-
- // returns a list of fields with only setter entries checked
- private static IField[] getSetterOnlyFields(Object[] result, Set set) {
- List list= new ArrayList(0);
- Object each= null;
- GetterSetterEntry entry= null;
- boolean getterSet= false;
- for (int i= 0; i < result.length; i++) {
- each= result[i];
- if ((each instanceof GetterSetterEntry)) {
- entry= (GetterSetterEntry) each;
- if (entry.isGetter) {
- getterSet= true;
- }
- if ((!entry.isGetter) && (getterSet != true)) {
- list.add(entry.field);
- getterSet= false;
- }
- } else
- getterSet= false;
- }
- list= reorderFields(list, set);
- return (IField[]) list.toArray(new IField[list.size()]);
- }
-
- // returns a list of fields with both entries checked
- private static IField[] getGetterSetterFields(Object[] result, Set set) {
- List list= new ArrayList(0);
- Object each= null;
- GetterSetterEntry entry= null;
- boolean getterSet= false;
- for (int i= 0; i < result.length; i++) {
- each= result[i];
- if ((each instanceof GetterSetterEntry)) {
- entry= (GetterSetterEntry) each;
- if (entry.isGetter) {
- getterSet= true;
- }
- if ((!entry.isGetter) && (getterSet == true)) {
- list.add(entry.field);
- getterSet= false;
- }
- } else
- getterSet= false;
- }
- list= reorderFields(list, set);
- return (IField[]) list.toArray(new IField[list.size()]);
- }
-
- private static List reorderFields(List collection, Set set) {
- final List list= new ArrayList(collection.size());
- for (final Iterator iterator= set.iterator(); iterator.hasNext();) {
- final IField field= (IField) iterator.next();
- if (collection.contains(field))
- list.add(field);
- }
- return list;
- }
-
- private void generate(IType type, IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, JavaScriptUnit unit, IJavaScriptElement elementPosition) throws CoreException {
- if (getterFields.length == 0 && setterFields.length == 0 && getterSetterFields.length == 0)
- return;
-
- IJavaScriptUnit cu= null;
- if (getterFields.length != 0)
- cu= getterFields[0].getJavaScriptUnit();
- else if (setterFields.length != 0)
- cu= setterFields[0].getJavaScriptUnit();
- else
- cu= getterSetterFields[0].getJavaScriptUnit();
- // open the editor, forces the creation of a working copy
- run(cu, type, getterFields, setterFields, getterSetterFields, JavaScriptUI.openInEditor(cu), unit, elementPosition);
- }
-
- // ---- JavaScript Editor --------------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- if (!ActionUtil.isProcessable(fEditor)) {
- notifyResult(false);
- return;
- }
-
- IJavaScriptElement[] elements= SelectionConverter.codeResolveForked(fEditor, true);
- if (elements.length == 1 && (elements[0] instanceof IField)) {
- IField field= (IField) elements[0];
- run(field.getDeclaringType(), new IField[] { field}, true);
- return;
- }
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
-
- if (element != null) {
- IType type= (IType) element.getAncestor(IJavaScriptElement.TYPE);
- if (type != null) {
- if (type.getFields().length > 0) {
- run(type, new IField[0], true);
- return;
- }
- }
- }
- MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_not_applicable);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_error_actionfailed);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.AddGetterSetterAction_error_actionfailed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- // ---- Helpers -------------------------------------------------------------------
-
- private void run(IJavaScriptUnit cu, IType type, IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IEditorPart editor, JavaScriptUnit unit, IJavaScriptElement elementPosition) {
- IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.beginCompoundChange();
- }
- try {
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaScriptProject());
- settings.createComments= fGenerateComment;
-
- AddGetterSetterOperation op= new AddGetterSetterOperation(type, getterFields, setterFields, getterSetterFields, unit, skipReplaceQuery(), elementPosition, settings, true, false);
- setOperationStatusFields(op);
-
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null) {
- context= new BusyIndicatorRunnableContext();
- }
-
- PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(op, op.getSchedulingRule()), op.getSchedulingRule());
-
- } catch (InvocationTargetException e) {
- String message= ActionMessages.AddGetterSetterAction_error_actionfailed;
- ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, message);
- } catch (InterruptedException e) {
- // operation canceled
- } finally {
- if (target != null) {
- target.endCompoundChange();
- }
- }
- }
-
- private void setOperationStatusFields(AddGetterSetterOperation op) {
- // Set the status fields corresponding to the visibility and modifiers set
- int flags= fVisibility;
-
- op.setSort(fSort);
- op.setVisibility(flags);
- }
-
- private IRequestQuery skipReplaceQuery() {
- return new IRequestQuery() {
-
- public int doQuery(IMember method) {
- int[] returnCodes= { IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
- String skipLabel= ActionMessages.AddGetterSetterAction_SkipExistingDialog_skip_label;
- String replaceLabel= ActionMessages.AddGetterSetterAction_SkipExistingDialog_replace_label;
- String skipAllLabel= ActionMessages.AddGetterSetterAction_SkipExistingDialog_skipAll_label;
- String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
- String methodName= JavaScriptElementLabels.getElementLabel(method, JavaScriptElementLabels.M_PARAMETER_TYPES);
- String formattedMessage= Messages.format(ActionMessages.AddGetterSetterAction_SkipExistingDialog_message, methodName);
- return showQueryDialog(formattedMessage, options, returnCodes);
- }
- };
- }
-
- private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
- final Shell shell= getShell();
- if (shell == null) {
- JavaScriptPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
- return IRequestQuery.CANCEL;
- }
- final int[] result= { Window.CANCEL};
- shell.getDisplay().syncExec(new Runnable() {
-
- public void run() {
- String title= ActionMessages.AddGetterSetterAction_QueryDialog_title;
- MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
- result[0]= dialog.open();
- }
- });
- int returnVal= result[0];
- return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
- }
-
- /*
- * Returns fields in the selection or <code>null</code> if the selection is empty or
- * not valid.
- */
- private IField[] getSelectedFields(IStructuredSelection selection) {
- List elements= selection.toList();
- int nElements= elements.size();
- if (nElements > 0) {
- IField[] res= new IField[nElements];
- IJavaScriptUnit cu= null;
- for (int i= 0; i < nElements; i++) {
- Object curr= elements.get(i);
- if (curr instanceof IField) {
- IField fld= (IField) curr;
-
- if (i == 0) {
- // remember the cu of the first element
- cu= fld.getJavaScriptUnit();
- if (cu == null) {
- return null;
- }
- } else if (!cu.equals(fld.getJavaScriptUnit())) {
- // all fields must be in the same CU
- return null;
- }
-
- final IType declaringType= fld.getDeclaringType();
- if (declaringType==null)
- return null;
-
- res[i]= fld;
- } else {
- return null;
- }
- }
- return res;
- }
- return null;
- }
-
- private static class AddGetterSetterLabelProvider extends JavaScriptElementLabelProvider {
-
- AddGetterSetterLabelProvider() {
- }
-
- /*
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- if (element instanceof GetterSetterEntry) {
- GetterSetterEntry entry= (GetterSetterEntry) element;
- try {
- if (entry.isGetter) {
- return GetterSetterUtil.getGetterName(entry.field, null) + "()"; //$NON-NLS-1$
- } else {
- return GetterSetterUtil.getSetterName(entry.field, null) + '(' + Signature.getSimpleName(Signature.toString(entry.field.getTypeSignature())) + ')';
- }
- } catch (JavaScriptModelException e) {
- return ""; //$NON-NLS-1$
- }
- }
- return super.getText(element);
- }
-
- /*
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- if (element instanceof GetterSetterEntry) {
- int flags= 0;
- try {
- flags= ((GetterSetterEntry) element).field.getFlags();
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
- int adornmentFlags= Flags.isStatic(flags) ? JavaScriptElementImageDescriptor.STATIC : 0;
- desc= new JavaScriptElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
- return JavaScriptPlugin.getImageDescriptorRegistry().get(desc);
- }
- return super.getImage(element);
- }
- }
-
- /**
- * @return map IField -> GetterSetterEntry[]
- */
- private Map createGetterSetterMapping(IType type) throws JavaScriptModelException {
- IField[] fields= type.getFields();
- Map result= new LinkedHashMap();
- for (int i= 0; i < fields.length; i++) {
- IField field= fields[i];
-
- List l= new ArrayList(2);
- if (GetterSetterUtil.getGetter(field) == null) {
- l.add(new GetterSetterEntry(field, true, false));
- incNumEntries();
- }
-
- if (GetterSetterUtil.getSetter(field) == null) {
- l.add(new GetterSetterEntry(field, false, false));
- incNumEntries();
- }
-
- if (!l.isEmpty())
- result.put(field, l.toArray(new GetterSetterEntry[l.size()]));
-
- }
- return result;
- }
-
- private static class AddGetterSetterContentProvider implements ITreeContentProvider {
-
- private static final Object[] EMPTY= new Object[0];
-
- //private Viewer fViewer;
-
- private Map fGetterSetterEntries;
-
- public AddGetterSetterContentProvider(Map entries) {
- fGetterSetterEntries= entries;
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- //fViewer= viewer;
- }
-
-// public Viewer getViewer() {
-// return fViewer;
-// }
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof IField)
- return (Object[]) fGetterSetterEntries.get(parentElement);
- return EMPTY;
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- if (element instanceof IMember)
- { IMember member=(IMember) element;
- return member.getDeclaringType()!=null ?
- member.getDeclaringType() :(Object)member.getJavaScriptUnit();
- }
- if (element instanceof GetterSetterEntry)
- return ((GetterSetterEntry) element).field;
- return null;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- return fGetterSetterEntries.keySet().toArray();
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- fGetterSetterEntries.clear();
- fGetterSetterEntries= null;
- }
- }
-
- private static class SettersForFinalFieldsFilter extends ViewerFilter {
-
- private final AddGetterSetterContentProvider fContentProvider;
-
- public SettersForFinalFieldsFilter(AddGetterSetterContentProvider contentProvider) {
- fContentProvider= contentProvider;
- }
-
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof GetterSetterEntry) {
- GetterSetterEntry getterSetterEntry= (GetterSetterEntry) element;
- return getterSetterEntry.isGetter || !getterSetterEntry.isFinal;
- } else if (element instanceof IField) {
- Object[] children= fContentProvider.getChildren(element);
- for (int i= 0; i < children.length; i++) {
- GetterSetterEntry curr= (GetterSetterEntry) children[i];
- if (curr.isGetter || !curr.isFinal) {
- return true;
- }
- }
- return false;
- }
- return true;
- }
- }
-
-
- private static class GetterSetterTreeSelectionDialog extends SourceActionDialog {
-
- private AddGetterSetterContentProvider fContentProvider;
-
- private static final int SELECT_GETTERS_ID= IDialogConstants.CLIENT_ID + 1;
- private static final int SELECT_SETTERS_ID= IDialogConstants.CLIENT_ID + 2;
- private final String SETTINGS_SECTION= "AddGetterSetterDialog"; //$NON-NLS-1$
- private final String SORT_ORDER= "SortOrdering"; //$NON-NLS-1$
- private final String ALLOW_SETTERS_FOR_FINALS= "RemoveFinal"; //$NON-NLS-1$
-
- private IDialogSettings fSettings;
- private SettersForFinalFieldsFilter fSettersForFinalFieldsFilter;
-
- private boolean fSortOrder;
- private boolean fAllowSettersForFinals;
-
- private ArrayList fPreviousSelectedFinals;
-
-
- public GetterSetterTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, AddGetterSetterContentProvider contentProvider, CompilationUnitEditor editor, IType type) throws JavaScriptModelException {
- super(parent, labelProvider, contentProvider, editor, type, false);
- fContentProvider= contentProvider;
- fPreviousSelectedFinals= new ArrayList();
-
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fSettings= dialogSettings.getSection(SETTINGS_SECTION);
- if (fSettings == null) {
- fSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
- fSettings.put(SORT_ORDER, false);
- fSettings.put(ALLOW_SETTERS_FOR_FINALS, false);
- }
-
- fSortOrder= fSettings.getBoolean(SORT_ORDER);
- fAllowSettersForFinals= fSettings.getBoolean(ALLOW_SETTERS_FOR_FINALS);
-
- fSettersForFinalFieldsFilter= new SettersForFinalFieldsFilter(contentProvider);
- }
-
- public boolean getSortOrder() {
- return fSortOrder;
- }
-
- public void setSortOrder(boolean sort) {
- if (fSortOrder != sort) {
- fSortOrder= sort;
- fSettings.put(SORT_ORDER, sort);
- if (getTreeViewer() != null) {
- getTreeViewer().refresh();
- }
- }
- }
-
- private boolean allowSettersForFinals() {
- return fAllowSettersForFinals;
- }
-
- public void allowSettersForFinals(boolean allowSettersForFinals) {
- if (fAllowSettersForFinals != allowSettersForFinals) {
- fAllowSettersForFinals= allowSettersForFinals;
- fSettings.put(ALLOW_SETTERS_FOR_FINALS, allowSettersForFinals);
- CheckboxTreeViewer treeViewer= getTreeViewer();
- if (treeViewer != null) {
- ArrayList newChecked= new ArrayList();
- if (allowSettersForFinals) {
- newChecked.addAll(fPreviousSelectedFinals);
- }
- fPreviousSelectedFinals.clear();
- Object[] checkedElements= treeViewer.getCheckedElements();
- for (int i= 0; i < checkedElements.length; i++) {
- if (checkedElements[i] instanceof GetterSetterEntry) {
- GetterSetterEntry entry= (GetterSetterEntry) checkedElements[i];
- if (allowSettersForFinals || entry.isGetter || !entry.isFinal) {
- newChecked.add(entry);
- } else {
- fPreviousSelectedFinals.add(entry);
- }
- }
- }
- if (allowSettersForFinals) {
- treeViewer.removeFilter(fSettersForFinalFieldsFilter);
- } else {
- treeViewer.addFilter(fSettersForFinalFieldsFilter);
- }
- treeViewer.setCheckedElements(newChecked.toArray());
- }
- updateOKStatus();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.dialogs.CheckedTreeSelectionDialog#createTreeViewer(org.eclipse.swt.widgets.Composite)
- */
- protected CheckboxTreeViewer createTreeViewer(Composite parent) {
- CheckboxTreeViewer treeViewer= super.createTreeViewer(parent);
- if (!fAllowSettersForFinals) {
- treeViewer.addFilter(fSettersForFinalFieldsFilter);
- }
- return treeViewer;
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.ADD_GETTER_SETTER_SELECTION_DIALOG);
- }
-
- private void createGetterSetterButtons(Composite buttonComposite) {
- createButton(buttonComposite, SELECT_GETTERS_ID, ActionMessages.GetterSetterTreeSelectionDialog_select_getters, false);
- createButton(buttonComposite, SELECT_SETTERS_ID, ActionMessages.GetterSetterTreeSelectionDialog_select_setters, false);
- }
-
- protected void buttonPressed(int buttonId) {
- super.buttonPressed(buttonId);
- switch (buttonId) {
- case SELECT_GETTERS_ID: {
- getTreeViewer().setCheckedElements(getGetterSetterElements(true));
- updateOKStatus();
- break;
- }
- case SELECT_SETTERS_ID: {
- getTreeViewer().setCheckedElements(getGetterSetterElements(false));
- updateOKStatus();
- break;
- }
- }
- }
-
- protected Composite createInsertPositionCombo(Composite composite) {
- Button addRemoveFinalCheckbox= addAllowSettersForFinalslCheckbox(composite);
- addRemoveFinalCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite entryComposite= super.createInsertPositionCombo(composite);
- addSortOrder(entryComposite);
- addVisibilityAndModifiersChoices(entryComposite);
- return entryComposite;
- }
-
- private Button addAllowSettersForFinalslCheckbox(Composite entryComposite) {
- Button allowSettersForFinalsButton= new Button(entryComposite, SWT.CHECK);
- allowSettersForFinalsButton.setText(ActionMessages.AddGetterSetterAction_allow_setters_for_finals_description);
-
- allowSettersForFinalsButton.addSelectionListener(new SelectionListener() {
- public void widgetSelected(SelectionEvent e) {
- boolean isSelected= (((Button) e.widget).getSelection());
- allowSettersForFinals(isSelected);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
- });
- allowSettersForFinalsButton.setSelection(allowSettersForFinals());
- return allowSettersForFinalsButton;
- }
-
- private Composite addSortOrder(Composite composite) {
- Label label= new Label(composite, SWT.NONE);
- label.setText(ActionMessages.GetterSetterTreeSelectionDialog_sort_label);
- GridData gd= new GridData(GridData.FILL_BOTH);
- label.setLayoutData(gd);
-
- final Combo combo= new Combo(composite, SWT.READ_ONLY);
- combo.setItems(new String[] { ActionMessages.GetterSetterTreeSelectionDialog_alpha_pair_sort,
- ActionMessages.GetterSetterTreeSelectionDialog_alpha_method_sort});
- final int methodIndex= 1; // Hard-coded. Change this if the
- // list gets more complicated.
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
- int sort= getSortOrder() ? 1 : 0;
- combo.setText(combo.getItem(sort));
- gd= new GridData(GridData.FILL_BOTH);
- combo.setLayoutData(gd);
- combo.addSelectionListener(new SelectionAdapter() {
-
- public void widgetSelected(SelectionEvent e) {
- setSortOrder(combo.getSelectionIndex() == methodIndex);
- }
- });
- return composite;
- }
-
- private Object[] getGetterSetterElements(boolean isGetter) {
- Object[] allFields= fContentProvider.getElements(null);
- Set result= new HashSet();
- for (int i= 0; i < allFields.length; i++) {
- IField field= (IField) allFields[i];
- GetterSetterEntry[] entries= getEntries(field);
- for (int j= 0; j < entries.length; j++) {
- AddGetterSetterAction.GetterSetterEntry entry= entries[j];
- if (entry.isGetter == isGetter)
- result.add(entry);
- }
- }
- return result.toArray();
- }
-
- private GetterSetterEntry[] getEntries(IField field) {
- List result= Arrays.asList(fContentProvider.getChildren(field));
- return (GetterSetterEntry[]) result.toArray(new GetterSetterEntry[result.size()]);
- }
-
- protected Composite createSelectionButtons(Composite composite) {
- Composite buttonComposite= super.createSelectionButtons(composite);
-
- GridLayout layout= new GridLayout();
- buttonComposite.setLayout(layout);
-
- createGetterSetterButtons(buttonComposite);
-
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.numColumns= 1;
-
- return buttonComposite;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog#createLinkControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP);
- link.setText(ActionMessages.AddGetterSetterAction_template_link_description);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.GETTERCOMMENT_ID);
- }
- });
- link.setToolTipText(ActionMessages.AddGetterSetterAction_template_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
- link.setLayoutData(gridData);
- return link;
- }
- }
-
- private static class GetterSetterEntry {
- public final IField field;
- public final boolean isGetter;
- public final boolean isFinal;
-
- GetterSetterEntry(IField field, boolean isGetterEntry, boolean isFinal) {
- this.field= field;
- this.isGetter= isGetterEntry;
- this.isFinal= isFinal;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddJavaDocStubAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddJavaDocStubAction.java
deleted file mode 100644
index 1d6b186a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddJavaDocStubAction.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddJavaDocStubOperation;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Create Javadoc comment stubs for the selected members.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. The result is
- * unsaved, so the user can decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements
- * of type <code>IMember</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class AddJavaDocStubAction extends SelectionDispatchAction {
-
- private CompilationUnitEditor fEditor;
-
- /**
- * Creates a new <code>AddJavaDocStubAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public AddJavaDocStubAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.AddJavaDocStubAction_label);
- setDescription(ActionMessages.AddJavaDocStubAction_description);
- setToolTipText(ActionMessages.AddJavaDocStubAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_JAVADOC_STUB_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public AddJavaDocStubAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(checkEnabledEditor());
- }
-
- //---- Structured Viewer -----------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- IMember[] members= getSelectedMembers(selection);
- setEnabled(members != null && members.length > 0);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- IMember[] members= getSelectedMembers(selection);
- if (members == null || members.length == 0) {
- return;
- }
-
- try {
- IJavaScriptUnit cu= members[0].getJavaScriptUnit();
- if (!ActionUtil.isEditable(getShell(), cu)) {
- return;
- }
-
- // open the editor, forces the creation of a working copy
- IEditorPart editor= JavaScriptUI.openInEditor(cu);
-
- if (ElementValidator.check(members, getShell(), getDialogTitle(), false))
- run(cu, members);
- JavaModelUtil.reconcile(cu);
- EditorUtility.revealInEditor(editor, members[0]);
-
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.AddJavaDocStubsAction_error_actionFailed);
- }
- }
-
- //---- JavaScript Editor --------------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- private boolean checkEnabledEditor() {
- return fEditor != null && SelectionConverter.canOperateOn(fEditor);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (!ActionUtil.isEditable(fEditor, getShell(), element))
- return;
- int type= element != null ? element.getElementType() : -1;
- if (type != IJavaScriptElement.METHOD && type != IJavaScriptElement.TYPE && type != IJavaScriptElement.FIELD) {
- element= SelectionConverter.getTypeAtOffset(fEditor);
- if (element == null) {
- MessageDialog.openInformation(getShell(), getDialogTitle(),
- ActionMessages.AddJavaDocStubsAction_not_applicable);
- return;
- }
- }
- IMember[] members= new IMember[] { (IMember)element };
- if (ElementValidator.checkValidateEdit(members, getShell(), getDialogTitle()))
- run(members[0].getJavaScriptUnit(), members);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.AddJavaDocStubsAction_error_actionFailed);
- }
- }
-
- //---- Helpers -------------------------------------------------------------------
-
- /**
- * Note this method is for internal use only.
- *
- * @param cu the compilation unit
- * @param members an array of members
- */
- public void run(IJavaScriptUnit cu, IMember[] members) {
- try {
- AddJavaDocStubOperation op= new AddJavaDocStubOperation(members);
- PlatformUI.getWorkbench().getProgressService().runInUI(
- PlatformUI.getWorkbench().getProgressService(),
- new WorkbenchRunnableAdapter(op, op.getScheduleRule()),
- op.getScheduleRule());
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.AddJavaDocStubsAction_error_actionFailed);
- } catch (InterruptedException e) {
- // operation canceled
- }
- }
-
- private IMember[] getSelectedMembers(IStructuredSelection selection) {
- List elements= selection.toList();
- int nElements= elements.size();
- if (nElements > 0) {
- IMember[] res= new IMember[nElements];
- IJavaScriptUnit cu= null;
- for (int i= 0; i < nElements; i++) {
- Object curr= elements.get(i);
- if (curr instanceof IFunction || curr instanceof IType || curr instanceof IField) {
- IMember member= (IMember)curr; // limit to methods, types & fields
- if (! member.exists()) {
- return null;
- }
- if (i == 0) {
- cu= member.getJavaScriptUnit();
- if (cu == null) {
- return null;
- }
- } else if (!cu.equals(member.getJavaScriptUnit())) {
- return null;
- }
- if (member instanceof IType && member.getElementName().length() == 0) {
- return null; // anonymous type
- }
- res[i]= member;
- } else {
- return null;
- }
- }
- return res;
- }
- return null;
- }
-
- private String getDialogTitle() {
- return ActionMessages.AddJavaDocStubsAction_error_dialogTitle;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddToClasspathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddToClasspathAction.java
deleted file mode 100644
index e87a176e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddToClasspathAction.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ArchiveFileFilter;
-
-/**
- * Action to add a JAR to the classpath of its parent project.
- * Action is applicable to selections containing archives (JAR or zip)
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class AddToClasspathAction extends SelectionDispatchAction {
-
- /**
- * Creates a new <code>AddToClasspathAction</code>. The action requires that
- * the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public AddToClasspathAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.AddToClasspathAction_label);
- setToolTipText(ActionMessages.AddToClasspathAction_toolTip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_TO_CLASSPATH_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(checkEnabled(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- private static boolean checkEnabled(IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty())
- return false;
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- if (! canBeAddedToBuildPath(iter.next()))
- return false;
- }
- return true;
- }
-
- private static boolean canBeAddedToBuildPath(Object element) throws JavaScriptModelException{
- return (element instanceof IAdaptable) && getCandidate((IAdaptable) element) != null;
- }
-
- private static IFile getCandidate(IAdaptable element) throws JavaScriptModelException {
- IResource resource= (IResource)element.getAdapter(IResource.class);
- if (! (resource instanceof IFile) || ! ArchiveFileFilter.isArchivePath(resource.getFullPath()))
- return null;
-
- IJavaScriptProject project= JavaScriptCore.create(resource.getProject());
- if (project != null && project.exists() && (project.findPackageFragmentRoot(resource.getFullPath()) == null))
- return (IFile) resource;
- return null;
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- try {
- final IFile[] files= getJARFiles(selection);
-
- IWorkspaceRunnable operation= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- monitor.beginTask(ActionMessages.AddToClasspathAction_progressMessage, files.length);
- for (int i= 0; i < files.length; i++) {
- monitor.subTask(files[i].getFullPath().toString());
- IJavaScriptProject project= JavaScriptCore.create(files[i].getProject());
- addToClassPath(project, files[i].getFullPath(), new SubProgressMonitor(monitor, 1));
- }
- }
-
- private void addToClassPath(IJavaScriptProject project, IPath jarPath, IProgressMonitor monitor) throws JavaScriptModelException {
- if (monitor.isCanceled())
- throw new OperationCanceledException();
- IIncludePathEntry[] entries= project.getRawIncludepath();
- IIncludePathEntry[] newEntries= new IIncludePathEntry[entries.length + 1];
- System.arraycopy(entries, 0, newEntries, 0, entries.length);
- newEntries[entries.length]= JavaScriptCore.newLibraryEntry(jarPath, null, null, false);
- project.setRawIncludepath(newEntries, monitor);
- }
- };
-
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, new WorkbenchRunnableAdapter(operation));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(),
- ActionMessages.AddToClasspathAction_error_title,
- ActionMessages.AddToClasspathAction_error_message);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(),
- ActionMessages.AddToClasspathAction_error_title,
- ActionMessages.AddToClasspathAction_error_message);
- } catch (InterruptedException e) {
- // canceled
- }
-
- }
-
- private static IFile[] getJARFiles(IStructuredSelection selection) throws JavaScriptModelException {
- ArrayList list= new ArrayList();
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IAdaptable) {
- IFile file= getCandidate((IAdaptable) element);
- if (file != null) {
- list.add(file);
- }
- }
- }
- return (IFile[]) list.toArray(new IFile[list.size()]);
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddUnimplementedConstructorsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddUnimplementedConstructorsAction.java
deleted file mode 100644
index 8819fb2a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/AddUnimplementedConstructorsAction.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.CheckboxTreeViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.NodeFinder;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.corext.template.java.CodeTemplateContextType;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.IVisibilityChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Creates unimplemented constructors for a type.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. Opens a dialog with a list of
- * constructors from the super class which can be generated. User is able to check or
- * uncheck items before constructors are generated. The result is unsaved, so the user can
- * decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements of type
- * <code>IType</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class AddUnimplementedConstructorsAction extends SelectionDispatchAction {
-
- private static class AddUnimplementedConstructorsContentProvider implements ITreeContentProvider {
-
- private static final Object[] EMPTY= new Object[0];
-
- private IFunctionBinding[] fMethodsList= new IFunctionBinding[0];
-
- private final JavaScriptUnit fUnit;
-
- public AddUnimplementedConstructorsContentProvider(IType type) throws JavaScriptModelException {
- RefactoringASTParser parser= new RefactoringASTParser(AST.JLS3);
- fUnit= parser.parse(type.getJavaScriptUnit(), true);
- AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()), AbstractTypeDeclaration.class);
- if (declaration != null) {
- ITypeBinding binding= declaration.resolveBinding();
- if (binding != null)
- fMethodsList= StubUtility2.getVisibleConstructors(binding, true, false);
- }
- }
-
- public JavaScriptUnit getCompilationUnit() {
- return fUnit;
- }
-
- /*
- * @see IContentProvider#dispose()
- */
- public void dispose() {
- }
-
- /*
- * @see ITreeContentProvider#getChildren(Object)
- */
- public Object[] getChildren(Object parentElement) {
- return EMPTY;
- }
-
- /*
- * @see IStructuredContentProvider#getElements(Object)
- */
- public Object[] getElements(Object inputElement) {
- return fMethodsList;
- }
-
- /*
- * @see ITreeContentProvider#getParent(Object)
- */
- public Object getParent(Object element) {
- return null;
- }
-
- /*
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- /*
- * @see IContentProvider#inputChanged(Viewer, Object, Object)
- */
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- }
-
- private static class AddUnimplementedConstructorsDialog extends SourceActionDialog {
-
- private IDialogSettings fAddConstructorsSettings;
-
- private int fHeight= 18;
-
- private boolean fOmitSuper;
-
- private int fWidth= 60;
-
- private final String OMIT_SUPER= "OmitCallToSuper"; //$NON-NLS-1$
-
- private final String SETTINGS_SECTION= "AddUnimplementedConstructorsDialog"; //$NON-NLS-1$
-
- public AddUnimplementedConstructorsDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type) throws JavaScriptModelException {
- super(parent, labelProvider, contentProvider, editor, type, true);
-
- IDialogSettings dialogSettings= JavaScriptPlugin.getDefault().getDialogSettings();
- fAddConstructorsSettings= dialogSettings.getSection(SETTINGS_SECTION);
- if (fAddConstructorsSettings == null) {
- fAddConstructorsSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
- fAddConstructorsSettings.put(OMIT_SUPER, false);
- }
-
- fOmitSuper= fAddConstructorsSettings.getBoolean(OMIT_SUPER);
- }
-
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_DIALOG);
- }
-
- protected Control createDialogArea(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- GridLayout layout= new GridLayout();
- GridData gd= null;
-
- layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
- layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
- layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
- composite.setLayout(layout);
-
- Label messageLabel= createMessageArea(composite);
- if (messageLabel != null) {
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- messageLabel.setLayoutData(gd);
- }
-
- Composite inner= new Composite(composite, SWT.NONE);
- GridLayout innerLayout= new GridLayout();
- innerLayout.numColumns= 2;
- innerLayout.marginHeight= 0;
- innerLayout.marginWidth= 0;
- inner.setLayout(innerLayout);
- inner.setFont(parent.getFont());
-
- CheckboxTreeViewer treeViewer= createTreeViewer(inner);
- gd= new GridData(GridData.FILL_BOTH);
- gd.widthHint= convertWidthInCharsToPixels(fWidth);
- gd.heightHint= convertHeightInCharsToPixels(fHeight);
- treeViewer.getControl().setLayoutData(gd);
-
- Composite buttonComposite= createSelectionButtons(inner);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
- buttonComposite.setLayoutData(gd);
-
- gd= new GridData(GridData.FILL_BOTH);
- inner.setLayoutData(gd);
-
- Composite entryComposite= createInsertPositionCombo(composite);
- entryComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite commentComposite= createCommentSelection(composite);
- commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite overrideSuperComposite= createOmitSuper(composite);
- overrideSuperComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Control linkControl= createLinkControl(composite);
- if (linkControl != null)
- linkControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
-
- applyDialogFont(composite);
-
- return composite;
- }
-
- protected Composite createInsertPositionCombo(Composite composite) {
- Composite entryComposite= super.createInsertPositionCombo(composite);
- addVisibilityAndModifiersChoices(entryComposite);
-
- return entryComposite;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.internal.ui.dialogs.SourceActionDialog#createLinkControl(org.eclipse.swt.widgets.Composite)
- */
- protected Control createLinkControl(Composite composite) {
- Link link= new Link(composite, SWT.WRAP);
- link.setText(ActionMessages.AddUnimplementedConstructorsAction_template_link_message);
- link.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- openCodeTempatePage(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID);
- }
- });
- link.setToolTipText(ActionMessages.AddUnimplementedConstructorsAction_template_link_tooltip);
-
- GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- gridData.widthHint= convertWidthInCharsToPixels(40); // only expand further if anyone else requires it
- link.setLayoutData(gridData);
- return link;
- }
-
- private Composite createOmitSuper(Composite composite) {
- Composite omitSuperComposite= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- omitSuperComposite.setLayout(layout);
- omitSuperComposite.setFont(composite.getFont());
-
- Button omitSuperButton= new Button(omitSuperComposite, SWT.CHECK);
- omitSuperButton.setText(ActionMessages.AddUnimplementedConstructorsDialog_omit_super);
- omitSuperButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
-
- omitSuperButton.addSelectionListener(new SelectionListener() {
-
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- }
-
- public void widgetSelected(SelectionEvent e) {
- boolean isSelected= (((Button) e.widget).getSelection());
- setOmitSuper(isSelected);
- }
- });
- omitSuperButton.setSelection(isOmitSuper());
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= 2;
- omitSuperButton.setLayoutData(gd);
-
- return omitSuperComposite;
- }
-
- protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
- Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility);
- return visibilityComposite;
- }
-
- public boolean isOmitSuper() {
- return fOmitSuper;
- }
-
- public void setOmitSuper(boolean omitSuper) {
- if (fOmitSuper != omitSuper) {
- fOmitSuper= omitSuper;
- fAddConstructorsSettings.put(OMIT_SUPER, omitSuper);
- }
- }
- }
-
- private static class AddUnimplementedConstructorsValidator implements ISelectionStatusValidator {
-
- private static int fEntries;
-
- AddUnimplementedConstructorsValidator(int entries) {
- super();
- fEntries= entries;
- }
-
- private int countSelectedMethods(Object[] selection) {
- int count= 0;
- for (int i= 0; i < selection.length; i++) {
- if (selection[i] instanceof IFunctionBinding)
- count++;
- }
- return count;
- }
-
- public IStatus validate(Object[] selection) {
- int count= countSelectedMethods(selection);
- if (count == 0)
- return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
- String message= Messages.format(ActionMessages.AddUnimplementedConstructorsAction_methods_selected, new Object[] { String.valueOf(count), String.valueOf(fEntries)});
- return new StatusInfo(IStatus.INFO, message);
- }
- }
-
- private static final String DIALOG_TITLE= ActionMessages.AddUnimplementedConstructorsAction_error_title;
-
- private CompilationUnitEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this
- * constructor.
- *
- * @param editor the compilation unit editor
- */
- public AddUnimplementedConstructorsAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(checkEnabledEditor());
- }
-
- /**
- * Creates a new <code>AddUnimplementedConstructorsAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public AddUnimplementedConstructorsAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.AddUnimplementedConstructorsAction_label);
- setDescription(ActionMessages.AddUnimplementedConstructorsAction_description);
- setToolTipText(ActionMessages.AddUnimplementedConstructorsAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION);
- }
-
- private boolean canEnable(IStructuredSelection selection) throws JavaScriptModelException {
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
- IType type= (IType) selection.getFirstElement();
- return type.getJavaScriptUnit() != null;
- }
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IJavaScriptUnit))
- return true;
-
- return false;
- }
-
- private boolean checkEnabledEditor() {
- return fEditor != null && SelectionConverter.canOperateOn(fEditor);
- }
-
- private String getDialogTitle() {
- return DIALOG_TITLE;
- }
-
- private IType getSelectedType(IStructuredSelection selection) throws JavaScriptModelException {
- Object[] elements= selection.toArray();
- if (elements.length == 1 && (elements[0] instanceof IType)) {
- IType type= (IType) elements[0];
- if (type.getJavaScriptUnit() != null) {
- return type;
- }
- } else if (elements[0] instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit) elements[0];
- IType type= cu.findPrimaryType();
- if (type != null)
- return type;
- }
- return null;
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- Shell shell= getShell();
- try {
- IType type= getSelectedType(selection);
- if (type == null) {
- MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.AddUnimplementedConstructorsAction_not_applicable);
- return;
- }
- run(shell, type, false);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, shell, getDialogTitle(), null);
- }
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isProcessable(fEditor))
- return;
- try {
- Shell shell= getShell();
- IType type= SelectionConverter.getTypeAtOffset(fEditor);
- if (type != null)
- run(shell, type, true);
- else
- MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.AddUnimplementedConstructorsAction_not_applicable);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
- }
- }
-
- // ---- Helpers -------------------------------------------------------------------
-
- private void run(Shell shell, IType type, boolean activatedFromEditor) throws CoreException {
- if (!ElementValidator.check(type, getShell(), getDialogTitle(), activatedFromEditor)) {
- notifyResult(false);
- return;
- }
- if (!ActionUtil.isEditable(fEditor, getShell(), type)) {
- notifyResult(false);
- return;
- }
-
- AddUnimplementedConstructorsContentProvider provider= new AddUnimplementedConstructorsContentProvider(type);
- Object[] constructors= provider.getElements(null);
- if (constructors.length == 0) {
- MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.AddUnimplementedConstructorsAction_error_nothing_found);
- notifyResult(false);
- return;
- }
-
- AddUnimplementedConstructorsDialog dialog= new AddUnimplementedConstructorsDialog(shell, new BindingLabelProvider(), provider, fEditor, type);
- dialog.setCommentString(ActionMessages.SourceActionDialog_createConstructorComment);
- dialog.setTitle(ActionMessages.AddUnimplementedConstructorsAction_dialog_title);
- dialog.setInitialSelections(constructors);
- dialog.setContainerMode(true);
- dialog.setComparator(new JavaScriptElementComparator());
- dialog.setSize(60, 18);
- dialog.setInput(new Object());
- dialog.setMessage(ActionMessages.AddUnimplementedConstructorsAction_dialog_label);
- dialog.setValidator(new AddUnimplementedConstructorsValidator(constructors.length));
-
- final int dialogResult= dialog.open();
- if (dialogResult == Window.OK) {
- Object[] elements= dialog.getResult();
- if (elements == null) {
- notifyResult(false);
- return;
- }
-
- ArrayList result= new ArrayList();
- for (int i= 0; i < elements.length; i++) {
- Object elem= elements[i];
- if (elem instanceof IFunctionBinding) {
- result.add(elem);
- }
- }
- IFunctionBinding[] selected= (IFunctionBinding[]) result.toArray(new IFunctionBinding[result.size()]);
-
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject());
- settings.createComments= dialog.getGenerateComment();
- IEditorPart editor= JavaScriptUI.openInEditor(type, true, false);
- IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
- if (target != null)
- target.beginCompoundChange();
- try {
- JavaScriptUnit astRoot= provider.getCompilationUnit();
- final ITypeBinding typeBinding= ASTNodes.getTypeBinding(astRoot, type);
- int insertPos= dialog.getInsertOffset();
-
- AddUnimplementedConstructorsOperation operation= (AddUnimplementedConstructorsOperation) createRunnable(astRoot, typeBinding, selected, insertPos, dialog.getGenerateComment(), dialog.getVisibilityModifier(), dialog.isOmitSuper());
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null)
- context= new BusyIndicatorRunnableContext();
- PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
- String[] created= operation.getCreatedConstructors();
- if (created == null || created.length == 0)
- MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.AddUnimplementedConstructorsAction_error_nothing_found);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, shell, getDialogTitle(), null);
- } catch (InterruptedException e) {
- // Do nothing. Operation has been canceled by user.
- } finally {
- if (target != null) {
- target.endCompoundChange();
- }
- }
- }
- notifyResult(dialogResult == Window.OK);
- }
-
- /**
- * Returns a runnable that creates the constructor stubs.
- *
- * @param astRoot the AST of the compilation unit to work on. The AST must have been created from a {@link IJavaScriptUnit}, that
- * means {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setSource(IJavaScriptUnit)} was used.
- * @param type the binding of the type to add the new methods to. The type binding must correspond to a type declaration in the AST.
- * @param constructorsToOverride the bindings of constructors to override or <code>null</code> to implement all visible constructors from the super class.
- * @param insertPos a hint for a location in the source where to insert the new methods or <code>-1</code> to use the default behavior.
- * @param createComments if set, comments will be added to the new methods.
- * @param visibility the visibility for the new modifiers. (see {@link org.eclipse.wst.jsdt.core.Flags}) for visibility constants.
- * @param omitSuper if set, no <code>super()</code> call without arguments will be created.
- * @return returns a runnable that creates the constructor stubs.
- * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown if the AST passed has not been created from a {@link IJavaScriptUnit}.
- *
- *
- */
- public static IWorkspaceRunnable createRunnable(JavaScriptUnit astRoot, ITypeBinding type, IFunctionBinding[] constructorsToOverride, int insertPos, boolean createComments, int visibility, boolean omitSuper) {
- AddUnimplementedConstructorsOperation operation= new AddUnimplementedConstructorsOperation(astRoot, type, constructorsToOverride, insertPos, true, true, false);
- operation.setCreateComments(createComments);
- operation.setOmitSuper(omitSuper);
- operation.setVisibility(visibility);
- return operation;
- }
-
- // ---- Structured Viewer -----------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(canEnable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- // ---- JavaScript Editor --------------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/BuildActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/BuildActionGroup.java
deleted file mode 100644
index c521f669..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/BuildActionGroup.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.BuildAction;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Contributes all build related actions to the context menu and installs handlers for the
- * corresponding global menu actions.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class BuildActionGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
-
- private BuildAction fBuildAction;
- private RefreshAction fRefreshAction;
-
- /**
- * Creates a new <code>BuildActionGroup</code>. The group requires that
- * the selection provided by the view part's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public BuildActionGroup(IViewPart part) {
- fSite= part.getSite();
- Shell shell= fSite.getShell();
- ISelectionProvider provider= fSite.getSelectionProvider();
-
- fBuildAction= new BuildAction(shell, IncrementalProjectBuilder.INCREMENTAL_BUILD);
- fBuildAction.setText(ActionMessages.BuildAction_label);
- fBuildAction.setActionDefinitionId("org.eclipse.ui.project.buildProject"); //$NON-NLS-1$
-
- fRefreshAction= new RefreshAction(fSite);
- fRefreshAction.setActionDefinitionId("org.eclipse.ui.file.refresh"); //$NON-NLS-1$
-
- provider.addSelectionChangedListener(fBuildAction);
- provider.addSelectionChangedListener(fRefreshAction);
- }
-
- /**
- * Returns the refresh action managed by this group.
- *
- * @return the refresh action. If this group doesn't manage a refresh action
- * <code>null</code> is returned
- */
- public IAction getRefreshAction() {
- return fRefreshAction;
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- setGlobalActionHandlers(actionBar);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- ISelection selection= getContext().getSelection();
- if (!ResourcesPlugin.getWorkspace().isAutoBuilding() && isBuildTarget(selection)) {
- appendToGroup(menu, fBuildAction);
- }
- appendToGroup(menu, fRefreshAction);
- super.fillContextMenu(menu);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- provider.removeSelectionChangedListener(fBuildAction);
- provider.removeSelectionChangedListener(fRefreshAction);
- super.dispose();
- }
-
- private void setGlobalActionHandlers(IActionBars actionBar) {
- actionBar.setGlobalActionHandler(IDEActionFactory.BUILD_PROJECT.getId(), fBuildAction);
- actionBar.setGlobalActionHandler(ActionFactory.REFRESH.getId(), fRefreshAction);
- }
-
- private void appendToGroup(IMenuManager menu, IAction action) {
- if (action.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, action);
- }
-
- private boolean isBuildTarget(ISelection s) {
- if (!(s instanceof IStructuredSelection))
- return false;
- IStructuredSelection selection= (IStructuredSelection)s;
- if (selection.size() != 1)
- return false;
- return selection.getFirstElement() instanceof IJavaScriptProject;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java
deleted file mode 100644
index 6e084a95..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.navigator.ICommonMenuConstants;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.CopyQualifiedNameAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.CopyToClipboardAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.CutAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.DeleteAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.PasteAction;
-
-/**
- * Action group that adds the copy, cut, paste actions to a view part's context
- * menu and installs handlers for the corresponding global menu actions.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class CCPActionGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
- private Clipboard fClipboard;
-
- private SelectionDispatchAction[] fActions;
-
- private SelectionDispatchAction fDeleteAction;
- private SelectionDispatchAction fCopyAction;
- private SelectionDispatchAction fCopyQualifiedNameAction;
- private SelectionDispatchAction fPasteAction;
- private SelectionDispatchAction fCutAction;
-
- private boolean showLimited;
-
- /**
- * Creates a new <code>CCPActionGroup</code>. The group requires that
- * the selection provided by the view part's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public CCPActionGroup(IViewPart part) {
- this(part.getSite());
- }
-
- /**
- * Creates a new <code>CCPActionGroup</code>. The group requires that
- * the selection provided by the page's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page that owns this action group
- */
- public CCPActionGroup(Page page) {
- this(page.getSite());
- }
-
- private CCPActionGroup(IWorkbenchSite site) {
- fSite= site;
- fClipboard= new Clipboard(site.getShell().getDisplay());
-
- fPasteAction= new PasteAction(fSite, fClipboard);
- fPasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
-
- fCopyAction= new CopyToClipboardAction(fSite, fClipboard);
- fCopyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
-
- fCopyQualifiedNameAction= new CopyQualifiedNameAction(fSite);
- fCopyQualifiedNameAction.setActionDefinitionId(CopyQualifiedNameAction.ACTION_DEFINITION_ID);
-
- fCutAction= new CutAction(fSite, fClipboard);
- fCutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT);
-
- fDeleteAction= new DeleteAction(fSite);
- fDeleteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.DELETE);
-
- fActions= new SelectionDispatchAction[] { fCutAction, fCopyAction, fCopyQualifiedNameAction, fPasteAction, fDeleteAction };
- registerActionsAsSelectionChangeListeners();
- }
-
- private void registerActionsAsSelectionChangeListeners() {
- ISelectionProvider provider = fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- for (int i= 0; i < fActions.length; i++) {
- SelectionDispatchAction action= fActions[i];
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
- }
-
- private void deregisterActionsAsSelectionChangeListeners() {
- ISelectionProvider provider = fSite.getSelectionProvider();
- for (int i= 0; i < fActions.length; i++) {
- provider.removeSelectionChangedListener(fActions[i]);
- }
- }
-
-
- /**
- * Returns the delete action managed by this action group.
- *
- * @return the delete action. Returns <code>null</code> if the group
- * doesn't provide any delete action
- */
- public IAction getDeleteAction() {
- return fDeleteAction;
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), fDeleteAction);
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), fCopyAction);
- actionBars.setGlobalActionHandler(CopyQualifiedNameAction.ACTION_HANDLER_ID, fCopyQualifiedNameAction);
- actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(), fCutAction);
- actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), fPasteAction);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- for (int i= 0; i < fActions.length; i++) {
- SelectionDispatchAction action= fActions[i];
- if (action == fCutAction && !fCutAction.isEnabled())
- continue;
- if (this.showLimited/* -- in case you want paste action to always show up-- && action!=fPasteAction */)
- continue;
- menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, action);
- }
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- super.dispose();
- if (fClipboard != null){
- fClipboard.dispose();
- fClipboard= null;
- }
- deregisterActionsAsSelectionChangeListeners();
- }
- public void setShowLimited(boolean showLimited) {
- this.showLimited = showLimited;
- }
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ChangeTypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ChangeTypeAction.java
deleted file mode 100644
index 5ad46653..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ChangeTypeAction.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.dom.PrimitiveType;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to generalize the type of a local or field declaration or the
- * return type of a method declaration.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ChangeTypeAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- * @param editor the JavaScript editor
- */
- public ChangeTypeAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Creates a new <code>ChangeTypeAction</code>. The action requires that
- * the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ChangeTypeAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.ChangeTypeAction_label);
- setToolTipText(RefactoringMessages.ChangeTypeAction_tooltipText);
- setDescription(RefactoringMessages.ChangeTypeAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CHANGE_TYPE_ACTION);
- }
-
- //---- structured selection ---------------------------------------------
-
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isGeneralizeTypeAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- public void run(IStructuredSelection selection) {
- try {
- IMember member= getMember(selection);
- if (member == null || !ActionUtil.isEditable(getShell(), member))
- return;
- ISourceRange range= member.getNameRange();
- RefactoringExecutionStarter.startChangeTypeRefactoring(member.getJavaScriptUnit(), getShell(), range.getOffset(), range.getLength());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ChangeTypeAction_dialog_title, RefactoringMessages.ChangeTypeAction_exception);
- }
- }
-
- private static IMember getMember(IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.size() != 1)
- return null;
-
- Object element= selection.getFirstElement();
- if (!(element instanceof IMember))
- return null;
-
- if (element instanceof IFunction) {
- IFunction method= (IFunction)element;
- String returnType= method.getReturnType();
- if (PrimitiveType.toCode(Signature.toString(returnType)) != null)
- return null;
- return method;
- } else if (element instanceof IField) {
- return (IField)element;
- }
- return null;
- }
-
- //---- text selection ------------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param selection the JavaScript text selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isGeneralizeTypeAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try {
- RefactoringExecutionStarter.startChangeTypeRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), getShell(), selection.getOffset(), selection.getLength());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ChangeTypeAction_dialog_title, RefactoringMessages.ChangeTypeAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertAnonymousToNestedAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertAnonymousToNestedAction.java
deleted file mode 100644
index 2539c750..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertAnonymousToNestedAction.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to convert an anonymous inner class to a nested class.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ConvertAnonymousToNestedAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ConvertAnonymousToNestedAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.ConvertAnonymousToNestedAction_Convert_Anonymous);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CONVERT_ANONYMOUS_TO_NESTED_ACTION);
- }
-
- /**
- * Creates a new <code>ConvertAnonymousToNestedAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ConvertAnonymousToNestedAction(IWorkbenchSite site) {
- super(site);
- fEditor= null;
- setText(RefactoringMessages.ConvertAnonymousToNestedAction_Convert_Anonymous);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CONVERT_ANONYMOUS_TO_NESTED_ACTION);
- }
-
- //---- Structured selection -----------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isConvertAnonymousAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- IType type= getElement(selection);
- if (type == null)
- return;
- ISourceRange range;
- try {
- range= type.getNameRange();
- run(type.getJavaScriptUnit(), range.getOffset(), range.getLength());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ConvertAnonymousToNestedAction_dialog_title, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-
- private IType getElement(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object element= selection.getFirstElement();
- if (!(element instanceof IType))
- return null;
- IType type= (IType)element;
- try {
- if (type.isAnonymous())
- return type;
- } catch (JavaScriptModelException e) {
- // fall through
- }
- return null;
- }
-
- //---- Text selection -----------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try{
- run(SelectionConverter.getInputAsCompilationUnit(fEditor), selection.getOffset(), selection.getLength());
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.ConvertAnonymousToNestedAction_dialog_title, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isConvertAnonymousAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- //---- helpers -------------------------------------------------------------------
-
- private void run(IJavaScriptUnit unit, int offset, int length) throws JavaScriptModelException {
- if (!ActionUtil.isEditable(fEditor, getShell(), unit))
- return;
- RefactoringExecutionStarter.startConvertAnonymousRefactoring(unit, offset, length, getShell());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertLocalToFieldAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertLocalToFieldAction.java
deleted file mode 100644
index 2b896cf2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertLocalToFieldAction.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.PromoteTempWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to convert a local variable to a field.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ConvertLocalToFieldAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public ConvertLocalToFieldAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.ConvertLocalToField_label);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.PROMOTE_TEMP_TO_FIELD_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isPromoteTempAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try{
- IJavaScriptUnit cunit= SelectionConverter.getInputAsCompilationUnit(fEditor);
- final PromoteTempToFieldRefactoring refactoring= new PromoteTempToFieldRefactoring(cunit, selection.getOffset(), selection.getLength());
- new RefactoringStarter().activate(refactoring, new PromoteTempWizard(refactoring), getShell(), RefactoringMessages.ConvertLocalToField_title, RefactoringSaveHelper.SAVE_NOTHING);
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.ConvertLocalToField_title, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertNestedToTopAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertNestedToTopAction.java
deleted file mode 100644
index 54f40f2d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertNestedToTopAction.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-
-import java.io.CharConversionException;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to convert a nested class to a top level class.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ConvertNestedToTopAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- * @param editor the JavaScript editor
- */
- public ConvertNestedToTopAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new <code>MoveInnerToTopAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type
- * <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site
- * the site providing context information for this action
- */
- public ConvertNestedToTopAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.ConvertNestedToTopAction_Convert);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_INNER_TO_TOP_ACTION);
- }
-
- //---- Structured selection ------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveInnerAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (!(e.getException() instanceof CharConversionException) && JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- //we have to call this here - no selection changed event is sent
- // after a refactoring but it may still invalidate enablement
- if (RefactoringAvailabilityTester.isMoveInnerAvailable(selection)) {
- IType singleSelectedType= getSingleSelectedType(selection);
- if (! ActionUtil.isEditable(getShell(), singleSelectedType))
- return;
- RefactoringExecutionStarter.startMoveInnerRefactoring(singleSelectedType, getShell());
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e,
- RefactoringMessages.OpenRefactoringWizardAction_refactoring,
- RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- private static IType getSingleSelectedType(IStructuredSelection selection) throws JavaScriptModelException {
- if (selection.isEmpty() || selection.size() != 1)
- return null;
-
- Object first= selection.getFirstElement();
- if (first instanceof IType)
- return (IType)first;
- if (first instanceof IJavaScriptUnit)
- return JavaElementUtil.getMainType((IJavaScriptUnit)first);
- return null;
- }
-
- //---- Text Selection -------------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isMoveInnerAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(ITextSelection)
- */
- public void run(ITextSelection selection) {
- try {
- IType type= RefactoringAvailabilityTester.getDeclaringType(SelectionConverter.resolveEnclosingElement(fEditor, selection));
- if (type != null && RefactoringAvailabilityTester.isMoveInnerAvailable(type)) {
- if (! ActionUtil.isEditable(fEditor, getShell(), type))
- return;
- RefactoringExecutionStarter.startMoveInnerRefactoring(type, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.ConvertNestedToTopAction_To_activate);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e,
- RefactoringMessages.OpenRefactoringWizardAction_refactoring,
- RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertingSelectionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertingSelectionProvider.java
deleted file mode 100644
index f7ba16a5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ConvertingSelectionProvider.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-
-
-/**
- * A converting selection provider is a special selection provider which converts
- * a selection before notifying any listeners. Additional it converts the selection
- * on <code>getSelection</code> and <code>setSelection</code>. The default strategy
- * used to adapt the elements of the selection to {@link IJavaScriptElement} or a {@link IResource},
- * but implementors can override this behavior.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ConvertingSelectionProvider implements ISelectionProvider {
-
- private final ISelectionProvider fProvider;
- private SelectionChangedListener fListener;
-
- private class SelectionChangedListener implements ISelectionChangedListener {
-
- ListenerList fListeners= new ListenerList();
-
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection= convertFrom(event.getSelection());
- SelectionChangedEvent newEvent= new SelectionChangedEvent(ConvertingSelectionProvider.this, selection);
- Object[] listeners= fListeners.getListeners();
- for (int i= 0; i < listeners.length; i++) {
- ((ISelectionChangedListener)listeners[i]).selectionChanged(newEvent);
- }
- }
- public void addListener(ISelectionChangedListener listener) {
- fListeners.add(listener);
- }
- public void removeListener(ISelectionChangedListener listener) {
- fListeners.remove(listener);
- }
- public boolean isEmpty() {
- return fListeners.isEmpty();
- }
- }
-
- /**
- * Creates a {@link ConvertingSelectionProvider} to convert from a given selection provider
- * using the default mechanism.
- *
- * @param provider the provider to covert from and to
- */
- public ConvertingSelectionProvider(ISelectionProvider provider) {
- Assert.isNotNull(provider);
- fProvider= provider;
- }
-
- /**
- * Converts the given original viewer selection into a new
- * selection. The default behavior adapts the elements in the selection
- * first to {@link IJavaScriptElement} then to {@link IResource}.
- * Implementors want to override this method.
- *
- * @param viewerSelection the original viewer selection
- *
- * @return the new selection to be used
- */
- public ISelection convertFrom(ISelection viewerSelection) {
- return convertFromUsingDefaultMechanism(viewerSelection);
- }
-
-
- private ISelection convertFromUsingDefaultMechanism(ISelection viewerSelection) {
- if (! (viewerSelection instanceof IStructuredSelection))
- return viewerSelection;
- IStructuredSelection selection= (IStructuredSelection)viewerSelection;
- List result= new ArrayList(selection.size());
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IResource || element instanceof IJavaScriptElement) {
- result.add(element);
- } else if (element instanceof IAdaptable) {
- IAdaptable adaptable= (IAdaptable)element;
- IJavaScriptElement jElement= (IJavaScriptElement)adaptable.getAdapter(IJavaScriptElement.class);
- if (jElement != null) {
- result.add(jElement);
- } else {
- IResource resource= (IResource)adaptable.getAdapter(IResource.class);
- if (resource != null) {
- result.add(resource);
- } else {
- result.add(element);
- }
- }
- } else {
- result.add(element);
- }
- }
- return new StructuredSelection(result);
- }
-
- /**
- * Converts a selection to a viewer selection. The default implementation does not convert
- * the selection. Implementors want to override this behavior.
- *
- * @param selection the selection to convert
- *
- * @return a viewer selection
- */
- public ISelection convertTo(ISelection selection) {
- return selection;
- }
-
-
- /**
- * {@inheritDoc}
- */
- public final ISelection getSelection() {
- return convertFrom(fProvider.getSelection());
- }
-
- /**
- * {@inheritDoc}
- */
- public final void setSelection(ISelection selection) {
- fProvider.setSelection(convertTo(selection));
- }
-
- /**
- * {@inheritDoc}
- */
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- if (fListener == null) {
- fListener= new SelectionChangedListener();
- fProvider.addSelectionChangedListener(fListener);
- }
- fListener.addListener(listener);
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- if (fListener == null)
- return;
- fListener.removeListener(listener);
- if (fListener.isEmpty()) {
- fProvider.removeSelectionChangedListener(fListener);
- fListener= null;
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CustomFiltersActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CustomFiltersActionGroup.java
deleted file mode 100644
index 6bfdc187..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CustomFiltersActionGroup.java
+++ /dev/null
@@ -1,757 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.Stack;
-import java.util.StringTokenizer;
-import java.util.TreeSet;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.IContentProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.filters.CustomFiltersDialog;
-import org.eclipse.wst.jsdt.internal.ui.filters.FilterDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.filters.FilterMessages;
-import org.eclipse.wst.jsdt.internal.ui.filters.NamePatternFilter;
-
-/**
- * Action group to add the filter action to a view part's tool bar
- * menu.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class CustomFiltersActionGroup extends ActionGroup {
-
- private static final String TAG_DUMMY_TO_TEST_EXISTENCE= "TAG_DUMMY_TO_TEST_EXISTENCE"; //$NON-NLS-1$
-
- class ShowFilterDialogAction extends Action {
- ShowFilterDialogAction() {
- setText(FilterMessages.OpenCustomFiltersDialogAction_text);
- setImageDescriptor(JavaPluginImages.DESC_ELCL_FILTER);
- setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_FILTER);
- }
-
- public void run() {
- openDialog();
- }
- }
-
- /**
- * Menu contribution item which shows and lets check and uncheck filters.
- *
- *
- */
- class FilterActionMenuContributionItem extends ContributionItem {
-
- private int fItemNumber;
- private boolean fState;
- private String fFilterId;
- private String fFilterName;
- private CustomFiltersActionGroup fActionGroup;
-
- /**
- * Constructor for FilterActionMenuContributionItem.
- *
- * @param actionGroup the action group
- * @param filterId the id of the filter
- * @param filterName the name of the filter
- * @param state the initial state of the filter
- * @param itemNumber the menu item index
- */
- public FilterActionMenuContributionItem(CustomFiltersActionGroup actionGroup, String filterId, String filterName, boolean state, int itemNumber) {
- super(filterId);
- Assert.isNotNull(actionGroup);
- Assert.isNotNull(filterId);
- Assert.isNotNull(filterName);
- fActionGroup= actionGroup;
- fFilterId= filterId;
- fFilterName= filterName;
- fState= state;
- fItemNumber= itemNumber;
- }
-
- /*
- * Overrides method from ContributionItem.
- */
- public void fill(Menu menu, int index) {
- MenuItem mi= new MenuItem(menu, SWT.CHECK, index);
- mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$
- /*
- * XXX: Don't set the image - would look bad because other menu items don't provide image
- * XXX: Get working set specific image name from XML - would need to cache icons
- */
-// mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET));
- mi.setSelection(fState);
- mi.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- fState= !fState;
- fActionGroup.setFilter(fFilterId, fState);
- }
- });
- }
-
- /*
- * @see org.eclipse.jface.action.IContributionItem#isDynamic()
- */
- public boolean isDynamic() {
- return true;
- }
- }
-
- private static final String TAG_CUSTOM_FILTERS = "customFilters"; //$NON-NLS-1$
- private static final String TAG_USER_DEFINED_PATTERNS_ENABLED= "userDefinedPatternsEnabled"; //$NON-NLS-1$
- private static final String TAG_USER_DEFINED_PATTERNS= "userDefinedPatterns"; //$NON-NLS-1$
- private static final String TAG_XML_DEFINED_FILTERS= "xmlDefinedFilters"; //$NON-NLS-1$
- private static final String TAG_LRU_FILTERS = "lastRecentlyUsedFilters"; //$NON-NLS-1$
-
- private static final String TAG_CHILD= "child"; //$NON-NLS-1$
- private static final String TAG_PATTERN= "pattern"; //$NON-NLS-1$
- private static final String TAG_FILTER_ID= "filterId"; //$NON-NLS-1$
- private static final String TAG_IS_ENABLED= "isEnabled"; //$NON-NLS-1$
-
- private static final String SEPARATOR= ","; //$NON-NLS-1$
-
- private static final int MAX_FILTER_MENU_ENTRIES= 3;
- private static final String RECENT_FILTERS_GROUP_NAME= "recentFiltersGroup"; //$NON-NLS-1$
-
- private static class FilterItem {
- boolean enabled;
- boolean previouslyEnabled;
- FilterDescriptor descriptor;
- String id;
-
- private ViewerFilter filterInstance= null;
-
- public FilterItem(FilterDescriptor descriptor) {
- this.descriptor= descriptor;
- this.id= descriptor.getId();
- this.previouslyEnabled= false;
- this.enabled= descriptor.isEnabled();
- }
-
- public ViewerFilter getFilterInstance() {
- if (filterInstance == null) {
- filterInstance= descriptor.createViewerFilter();
- }
- return filterInstance;
-
- }
- }
-
-
- private final StructuredViewer fViewer;
- private final NamePatternFilter fPatternFilter;
-
- private boolean fUserDefinedPatternsEnabled;
- private String[] fUserDefinedPatterns;
-
- private String[] fPreviousPatterns;
-
- private final Map/*String, FilterItem*/ fFilterItems;
-
- /**
- * Recently changed filter Ids stack with oldest on top (i.e. at the end).
- *
- *
- */
- private Stack fLRUFilterIdsStack;
- /**
- * Handle to menu manager to dynamically update
- * the last recently used filters.
- *
- *
- */
- private IMenuManager fMenuManager;
- /**
- * The menu listener which dynamically updates
- * the last recently used filters.
- *
- *
- */
- private IMenuListener fMenuListener;
- /**
- * Filter Ids used in the last view menu invocation.
- *
- *
- */
- private String[] fFilterIdsUsedInLastViewMenu;
-
- private final String fTargetId;
-
- /**
- * Creates a new <code>CustomFiltersActionGroup</code>.
- *
- * @param part the view part that owns this action group
- * @param viewer the viewer to be filtered
- */
- public CustomFiltersActionGroup(IViewPart part, StructuredViewer viewer) {
- this(part.getViewSite().getId(), viewer);
- }
-
- /**
- * Creates a new <code>CustomFiltersActionGroup</code>.
- *
- * @param ownerId the id of this action group's owner
- * @param viewer the viewer to be filtered
- */
- public CustomFiltersActionGroup(String ownerId, StructuredViewer viewer) {
- Assert.isNotNull(ownerId);
- Assert.isNotNull(viewer);
- fTargetId= ownerId;
- fViewer= viewer;
- fPatternFilter= new NamePatternFilter();
-
- fLRUFilterIdsStack= new Stack();
-
- fUserDefinedPatterns= new String[0];
- fUserDefinedPatternsEnabled= false;
- fPreviousPatterns= new String[0];
-
- fFilterItems= new HashMap();
- FilterDescriptor[] filterDescriptors= FilterDescriptor.getFilterDescriptors(fTargetId);
- for (int i= 0; i < filterDescriptors.length; i++) {
- FilterItem item= new FilterItem(filterDescriptors[i]);
- Object existing= fFilterItems.put(item.id, item);
- if (existing != null) {
- JavaScriptPlugin.logErrorMessage("WARNING: Duplicate id for extension-point \"org.eclipse.wst.jsdt.ui.javaElementFilters\" in " + ownerId); //$NON-NLS-1$
- }
- }
-
- initializeWithViewDefaults();
-
- updateViewerFilters();
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- fillToolBar(actionBars.getToolBarManager());
- fillViewMenu(actionBars.getMenuManager());
- }
-
- /**
- * Returns a list of currently enabled filters. The filter
- * is identified by its id.
- * <p>
- * This method is for internal use only and should not
- * be called by clients outside of JDT/UI.
- * </p>
- *
- * @return a list of currently enabled filters
- *
- *
- */
- public String[] internalGetEnabledFilterIds() {
- ArrayList enabledFilterIds= new ArrayList();
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- if (item.enabled) {
- enabledFilterIds.add(item.id);
- }
- }
- return (String[])enabledFilterIds.toArray(new String[enabledFilterIds.size()]);
- }
-
- /**
- * Removes filters for the given parent and element
- *
- * @param parent the parent of the element
- * @param element the element
- * @param contentProvider the content provider of the viewer from which
- * the filters will be removed
- *
- * @return the array of new filter ids
- */
- public String[] removeFiltersFor(Object parent, Object element, IContentProvider contentProvider) {
- ArrayList newFilters= new ArrayList();
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- if (item.enabled) {
- ViewerFilter filter= item.getFilterInstance();
- if (filter != null && isSelected(parent, element, contentProvider, filter))
- newFilters.add(item.id);
- }
- }
- return (String[])newFilters.toArray(new String[newFilters.size()]);
- }
-
- /**
- * Sets the filters to the given array of new filters
- *
- * @param newFilters the new filters
- */
- public void setFilters(String[] newFilters) {
- setEnabledFilterIds(newFilters);
- updateViewerFilters();
- }
-
- private boolean isSelected(Object parent, Object element, IContentProvider contentProvider, ViewerFilter filter) {
- if (contentProvider instanceof ITreeContentProvider) {
- // the element and all its parents have to be selected
- ITreeContentProvider provider = (ITreeContentProvider) contentProvider;
- while (element != null && !(element instanceof IJavaScriptModel)) {
- if (!filter.select(fViewer, parent, element))
- return false;
- element= provider.getParent( element);
- }
- return true;
- }
- return filter.select(fViewer, parent, element);
- }
-
- /**
- * Sets the enable state of the given filter.
- *
- * @param filterId the id of the filter
- * @param state the filter state
- */
- private void setFilter(String filterId, boolean state) {
- // Renew filter id in LRU stack
- fLRUFilterIdsStack.remove(filterId);
- fLRUFilterIdsStack.add(0, filterId);
-
- FilterItem item= (FilterItem) fFilterItems.get(filterId);
- if (item != null) {
- item.enabled= state;
- storeViewDefaults();
-
- updateViewerFilters();
- }
- }
-
- private void setEnabledFilterIds(String[] enabledIds) {
- // set all to false
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- item.enabled= false;
- }
- // set enabled to true
- for (int i= 0; i < enabledIds.length; i++) {
- FilterItem item= (FilterItem) fFilterItems.get(enabledIds[i]);
- if (item != null) {
- item.enabled= true;
- }
- }
- }
-
- private void setUserDefinedPatterns(String[] patterns) {
- fUserDefinedPatterns= patterns;
- }
-
- /**
- * Sets the recently changed filters.
- *
- * @param changeHistory the change history
- *
- */
- private void setRecentlyChangedFilters(Stack changeHistory) {
- Stack oldestFirstStack= new Stack();
-
- int length= Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES);
- for (int i= 0; i < length; i++)
- oldestFirstStack.push(((FilterDescriptor)changeHistory.pop()).getId());
-
- length= Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES - oldestFirstStack.size());
- int NEWEST= 0;
- for (int i= 0; i < length; i++) {
- Object filter= fLRUFilterIdsStack.remove(NEWEST);
- if (!oldestFirstStack.contains(filter))
- oldestFirstStack.push(filter);
- }
- fLRUFilterIdsStack= oldestFirstStack;
- }
-
- private boolean areUserDefinedPatternsEnabled() {
- return fUserDefinedPatternsEnabled;
- }
-
- private void setUserDefinedPatternsEnabled(boolean state) {
- fUserDefinedPatternsEnabled= state;
- }
-
- private void fillToolBar(IToolBarManager tooBar) {
- }
-
- /**
- * Fills the given view menu with the entries managed by the
- * group.
- *
- * @param viewMenu the menu to fill
- */
- public void fillViewMenu(IMenuManager viewMenu) {
- /*
- * Don't change the separator group name.
- * Using this name ensures that other filters
- * get contributed to the same group.
- */
- viewMenu.add(new Separator("filters")); //$NON-NLS-1$
- viewMenu.add(new GroupMarker(RECENT_FILTERS_GROUP_NAME));
- viewMenu.add(new ShowFilterDialogAction());
-
- fMenuManager= viewMenu;
- fMenuListener= new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- removePreviousLRUFilterActions(manager);
- addLRUFilterActions(manager);
- }
- };
- fMenuManager.addMenuListener(fMenuListener);
- }
-
- private void removePreviousLRUFilterActions(IMenuManager mm) {
- if (fFilterIdsUsedInLastViewMenu == null)
- return;
-
- for (int i= 0; i < fFilterIdsUsedInLastViewMenu.length; i++)
- mm.remove(fFilterIdsUsedInLastViewMenu[i]);
- }
-
- private void addLRUFilterActions(IMenuManager mm) {
- if (fLRUFilterIdsStack.isEmpty()) {
- fFilterIdsUsedInLastViewMenu= null;
- return;
- }
-
- SortedSet sortedFilters= new TreeSet(fLRUFilterIdsStack);
- String[] recentlyChangedFilterIds= (String[])sortedFilters.toArray(new String[sortedFilters.size()]);
-
- fFilterIdsUsedInLastViewMenu= new String[recentlyChangedFilterIds.length];
- for (int i= 0; i < recentlyChangedFilterIds.length; i++) {
- String id= recentlyChangedFilterIds[i];
- fFilterIdsUsedInLastViewMenu[i]= id;
- FilterItem filterItem= (FilterItem) fFilterItems.get(id);
- if (filterItem != null) {
- IContributionItem item= new FilterActionMenuContributionItem(this, id, filterItem.descriptor.getName(), filterItem.enabled, i+1);
- mm.insertBefore(RECENT_FILTERS_GROUP_NAME, item);
- }
- }
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- if (fMenuManager != null)
- fMenuManager.removeMenuListener(fMenuListener);
- fFilterItems.clear();
- super.dispose();
- }
-
- // ---------- viewer filter handling ----------
-
- private boolean updateViewerFilters() {
- ViewerFilter[] installedFilters= fViewer.getFilters();
- ArrayList viewerFilters= new ArrayList(Arrays.asList(installedFilters));
- HashSet patterns= new HashSet();
-
- boolean hasChange= false;
- boolean patternChange= false;
-
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- if (item.descriptor.isCustomFilter()) {
- if (item.enabled != item.previouslyEnabled) {
- ViewerFilter filter= item.getFilterInstance(); // only create when changed
- if (filter != null) {
- if (item.enabled) {
- viewerFilters.add(filter);
- } else {
- viewerFilters.remove(filter);
- }
- hasChange= true;
- }
- }
- } else if (item.descriptor.isPatternFilter()) {
- if (item.enabled) {
- patterns.add(item.descriptor.getPattern());
- }
- patternChange |= (item.enabled != item.previouslyEnabled);
- }
- item.previouslyEnabled= item.enabled;
- }
-
- if (areUserDefinedPatternsEnabled()) {
- for (int i= 0; i < fUserDefinedPatterns.length; i++) {
- patterns.add(fUserDefinedPatterns[i]);
- }
- }
- if (!patternChange) { // no pattern change so far, test if the user patterns made a difference
- patternChange= hasChanges(patterns, fPreviousPatterns);
- }
-
- fPreviousPatterns= (String[]) patterns.toArray(new String[patterns.size()]);
- if (patternChange) {
- fPatternFilter.setPatterns(fPreviousPatterns);
- if (patterns.isEmpty()) {
- viewerFilters.remove(fPatternFilter);
- } else if (!viewerFilters.contains(fPatternFilter)) {
- viewerFilters.add(fPatternFilter);
- }
- hasChange= true;
- }
- if (hasChange) {
- fViewer.setFilters((ViewerFilter[]) viewerFilters.toArray(new ViewerFilter[viewerFilters.size()])); // will refresh
- }
- return hasChange;
- }
-
- private boolean hasChanges(HashSet patterns, String[] oldPatterns) {
- HashSet copy= (HashSet) patterns.clone();
- for (int i= 0; i < oldPatterns.length; i++) {
- boolean found= copy.remove(oldPatterns[i]);
- if (!found)
- return true;
- }
- return !copy.isEmpty();
- }
-
- // ---------- view kind/defaults persistency ----------
-
- private void initializeWithViewDefaults() {
- // get default values for view
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=22533
- if (!store.contains(getPreferenceKey(TAG_DUMMY_TO_TEST_EXISTENCE)))
- return;
-
- fUserDefinedPatternsEnabled= store.getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED));
- setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store.getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), SEPARATOR));
-
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- String id= item.id;
- // set default to value from plugin contributions (fixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=73991 ):
- store.setDefault(id, item.descriptor.isEnabled());
- item.enabled= store.getBoolean(id);
- }
-
- fLRUFilterIdsStack.clear();
- String lruFilterIds= store.getString(TAG_LRU_FILTERS);
- StringTokenizer tokenizer= new StringTokenizer(lruFilterIds, SEPARATOR);
- while (tokenizer.hasMoreTokens()) {
- String id= tokenizer.nextToken();
- if (fFilterItems.containsKey(id) && !fLRUFilterIdsStack.contains(id))
- fLRUFilterIdsStack.push(id);
- }
- }
-
- private void storeViewDefaults() {
- // get default values for view
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
-
- // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=22533
- store.setValue(getPreferenceKey(TAG_DUMMY_TO_TEST_EXISTENCE), "storedViewPreferences");//$NON-NLS-1$
-
- store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), fUserDefinedPatternsEnabled);
- store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), CustomFiltersDialog.convertToString(fUserDefinedPatterns ,SEPARATOR));
-
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
- store.setValue(item.id, item.enabled);
- }
-
- StringBuffer buf= new StringBuffer(fLRUFilterIdsStack.size() * 20);
- Iterator iter= fLRUFilterIdsStack.iterator();
- while (iter.hasNext()) {
- buf.append((String)iter.next());
- buf.append(SEPARATOR);
- }
- store.setValue(TAG_LRU_FILTERS, buf.toString());
- }
-
- private String getPreferenceKey(String tag) {
- return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$
- }
-
- // ---------- view instance persistency ----------
-
- /**
- * Saves the state of the custom filters in a memento.
- *
- * @param memento the memento into which the state is saved
- */
- public void saveState(IMemento memento) {
- IMemento customFilters= memento.createChild(TAG_CUSTOM_FILTERS);
- customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, Boolean.toString(fUserDefinedPatternsEnabled));
- saveUserDefinedPatterns(customFilters);
- saveXmlDefinedFilters(customFilters);
- saveLRUFilters(customFilters);
- }
-
- private void saveXmlDefinedFilters(IMemento memento) {
- IMemento xmlDefinedFilters= memento.createChild(TAG_XML_DEFINED_FILTERS);
-
- for (Iterator iterator= fFilterItems.values().iterator(); iterator.hasNext();) {
- FilterItem item= (FilterItem) iterator.next();
-
- IMemento child= xmlDefinedFilters.createChild(TAG_CHILD);
- child.putString(TAG_FILTER_ID, item.id);
- child.putString(TAG_IS_ENABLED, String.valueOf(item.enabled));
- }
- }
- /**
- * Stores the last recently used filter Ids into
- * the given memento
- *
- * @param memento the memento into which to store the LRU filter Ids
- *
- */
- private void saveLRUFilters(IMemento memento) {
- if(fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) {
- IMemento lruFilters= memento.createChild(TAG_LRU_FILTERS);
- Iterator iter= fLRUFilterIdsStack.iterator();
- while (iter.hasNext()) {
- String id= (String)iter.next();
- IMemento child= lruFilters.createChild(TAG_CHILD);
- child.putString(TAG_FILTER_ID, id);
- }
- }
- }
-
- private void saveUserDefinedPatterns(IMemento memento) {
- if(fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) {
- IMemento userDefinedPatterns= memento.createChild(TAG_USER_DEFINED_PATTERNS);
- for (int i= 0; i < fUserDefinedPatterns.length; i++) {
- IMemento child= userDefinedPatterns.createChild(TAG_CHILD);
- child.putString(TAG_PATTERN, fUserDefinedPatterns[i]);
- }
- }
- }
-
- /**
- * Restores the state of the filter actions from a memento.
- * <p>
- * Note: This method does not refresh the viewer.
- * </p>
- *
- * @param memento the memento from which the state is restored
- */
- public void restoreState(IMemento memento) {
- if (memento == null)
- return;
- IMemento customFilters= memento.getChild(TAG_CUSTOM_FILTERS);
- if (customFilters == null)
- return;
- String userDefinedPatternsEnabled= customFilters.getString(TAG_USER_DEFINED_PATTERNS_ENABLED);
- if (userDefinedPatternsEnabled == null)
- return;
-
- fUserDefinedPatternsEnabled= Boolean.valueOf(userDefinedPatternsEnabled).booleanValue();
- restoreUserDefinedPatterns(customFilters);
- restoreXmlDefinedFilters(customFilters);
- restoreLRUFilters(customFilters);
-
- updateViewerFilters();
- }
-
- private void restoreUserDefinedPatterns(IMemento memento) {
- IMemento userDefinedPatterns= memento.getChild(TAG_USER_DEFINED_PATTERNS);
- if(userDefinedPatterns != null) {
- IMemento children[]= userDefinedPatterns.getChildren(TAG_CHILD);
- String[] patterns= new String[children.length];
- for (int i = 0; i < children.length; i++)
- patterns[i]= children[i].getString(TAG_PATTERN);
-
- setUserDefinedPatterns(patterns);
- } else
- setUserDefinedPatterns(new String[0]);
- }
-
- private void restoreXmlDefinedFilters(IMemento memento) {
- IMemento xmlDefinedFilters= memento.getChild(TAG_XML_DEFINED_FILTERS);
- if(xmlDefinedFilters != null) {
- IMemento[] children= xmlDefinedFilters.getChildren(TAG_CHILD);
- for (int i= 0; i < children.length; i++) {
- String id= children[i].getString(TAG_FILTER_ID);
- Boolean isEnabled= Boolean.valueOf(children[i].getString(TAG_IS_ENABLED));
- FilterItem item= (FilterItem) fFilterItems.get(id);
- if (item != null) {
- item.enabled= isEnabled.booleanValue();
- }
- }
- }
- }
-
- private void restoreLRUFilters(IMemento memento) {
- IMemento lruFilters= memento.getChild(TAG_LRU_FILTERS);
- fLRUFilterIdsStack.clear();
- if(lruFilters != null) {
- IMemento[] children= lruFilters.getChildren(TAG_CHILD);
- for (int i= 0; i < children.length; i++) {
- String id= children[i].getString(TAG_FILTER_ID);
- if (fFilterItems.containsKey(id) && !fLRUFilterIdsStack.contains(id))
- fLRUFilterIdsStack.push(id);
- }
- }
- }
-
- // ---------- dialog related code ----------
-
- private void openDialog() {
- CustomFiltersDialog dialog= new CustomFiltersDialog(
- fViewer.getControl().getShell(),
- fTargetId,
- areUserDefinedPatternsEnabled(),
- fUserDefinedPatterns,
- internalGetEnabledFilterIds());
-
- if (dialog.open() == Window.OK) {
- setEnabledFilterIds(dialog.getEnabledFilterIds());
- setUserDefinedPatternsEnabled(dialog.areUserDefinedPatternsEnabled());
- setUserDefinedPatterns(dialog.getUserDefinedPatterns());
- setRecentlyChangedFilters(dialog.getFilterDescriptorChangeHistory());
-
- storeViewDefaults();
-
- updateViewerFilters();
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java
deleted file mode 100644
index b89edac0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the search for declarations actions to a
- * context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class DeclarationsSearchGroup extends ActionGroup {
-
- private static final String MENU_TEXT= SearchMessages.group_declarations;
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindDeclarationsAction fFindDeclarationsAction;
- private FindDeclarationsInProjectAction fFindDeclarationsInProjectAction;
- private FindDeclarationsInWorkingSetAction fFindDeclarationsInWorkingSetAction;
- private FindDeclarationsInHierarchyAction fFindDeclarationsInHierarchyAction;
-
- /**
- * Creates a new <code>DeclarationsSearchGroup</code>. The group requires
- * that the selection provided by the site's selection provider is of type <code>
- * IStructuredSelection</code>.
- *
- * @param site the workbench site that owns this action group
- */
- public DeclarationsSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fFindDeclarationsAction= new FindDeclarationsAction(site);
- fFindDeclarationsAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKSPACE);
-
- fFindDeclarationsInProjectAction= new FindDeclarationsInProjectAction(site);
- fFindDeclarationsInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_PROJECTS);
-
- fFindDeclarationsInHierarchyAction= new FindDeclarationsInHierarchyAction(site);
- fFindDeclarationsInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_HIERARCHY);
-
- fFindDeclarationsInWorkingSetAction= new FindDeclarationsInWorkingSetAction(site);
- fFindDeclarationsInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKING_SET);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fFindDeclarationsAction, provider, selection);
- registerAction(fFindDeclarationsInProjectAction, provider, selection);
- registerAction(fFindDeclarationsInHierarchyAction, provider, selection);
- registerAction(fFindDeclarationsInWorkingSetAction, provider, selection);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public DeclarationsSearchGroup(JavaEditor editor) {
- Assert.isNotNull(editor);
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fFindDeclarationsAction= new FindDeclarationsAction(fEditor);
- fFindDeclarationsAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKSPACE);
- fEditor.setAction("SearchDeclarationsInWorkspace", fFindDeclarationsAction); //$NON-NLS-1$
-
- fFindDeclarationsInProjectAction= new FindDeclarationsInProjectAction(fEditor);
- fFindDeclarationsInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_PROJECTS);
- fEditor.setAction("SearchDeclarationsInProjects", fFindDeclarationsInProjectAction); //$NON-NLS-1$
-
- fFindDeclarationsInHierarchyAction= new FindDeclarationsInHierarchyAction(fEditor);
- fFindDeclarationsInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_HIERARCHY);
- fEditor.setAction("SearchDeclarationsInHierarchy", fFindDeclarationsInHierarchyAction); //$NON-NLS-1$
-
- fFindDeclarationsInWorkingSetAction= new FindDeclarationsInWorkingSetAction(fEditor);
- fFindDeclarationsInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKING_SET);
- fEditor.setAction("SearchDeclarationsInWorkingSet", fFindDeclarationsInWorkingSetAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection) {
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
- private void addAction(IAction action, IMenuManager manager) {
- if (action.isEnabled()) {
- manager.add(action);
- }
- }
-
- private void addWorkingSetAction(IWorkingSet[] workingSets, IMenuManager manager) {
- FindAction action;
- if (fEditor != null)
- action= new WorkingSetFindAction(fEditor, new FindDeclarationsInWorkingSetAction(fEditor, workingSets), SearchUtil.toString(workingSets));
- else
- action= new WorkingSetFindAction(fSite, new FindDeclarationsInWorkingSetAction(fSite, workingSets), SearchUtil.toString(workingSets));
- action.update(getContext().getSelection());
- addAction(action, manager);
- }
-
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- IMenuManager javaSearchMM= new MenuManager(MENU_TEXT, IContextMenuConstants.GROUP_SEARCH);
- addAction(fFindDeclarationsAction, javaSearchMM);
- addAction(fFindDeclarationsInProjectAction, javaSearchMM);
- addAction(fFindDeclarationsInHierarchyAction, javaSearchMM);
-
- javaSearchMM.add(new Separator());
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- addWorkingSetAction((IWorkingSet[]) iter.next(), javaSearchMM);
- }
- addAction(fFindDeclarationsInWorkingSetAction, javaSearchMM);
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindDeclarationsAction, provider);
- disposeAction(fFindDeclarationsInProjectAction, provider);
- disposeAction(fFindDeclarationsInHierarchyAction, provider);
- disposeAction(fFindDeclarationsInWorkingSetAction, provider);
- }
- fFindDeclarationsAction= null;
- fFindDeclarationsInProjectAction= null;
- fFindDeclarationsInHierarchyAction= null;
- fFindDeclarationsInWorkingSetAction= null;
- updateGlobalActionHandlers();
- super.dispose();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_DECLARATIONS_IN_WORKSPACE, fFindDeclarationsAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_DECLARATIONS_IN_PROJECT, fFindDeclarationsInProjectAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_DECLARATIONS_IN_HIERARCHY, fFindDeclarationsInHierarchyAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_DECLARATIONS_IN_WORKING_SET, fFindDeclarationsInWorkingSetAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExternalizeStringsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExternalizeStringsAction.java
deleted file mode 100644
index fd81231d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExternalizeStringsAction.java
+++ /dev/null
@@ -1,541 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSElement;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSLine;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.nls.NLSScanner;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.ReorgUtils;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.ListDialog;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.nls.ExternalizeWizard;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * Externalizes the strings of a compilation unit or find all strings
- * in a package or project that are not externalized yet. Opens a wizard that
- * gathers additional information to externalize the strings.
- * <p>
- * The action is applicable to structured selections containing elements
- * of type <code>IJavaScriptUnit</code>, <code>IType</code>, <code>IJavaScriptProject</code>,
- * <code>IPackageFragment</code>, and <code>IPackageFragmentRoot</code>
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ExternalizeStringsAction extends SelectionDispatchAction {
-
- private CompilationUnitEditor fEditor;
-
- private NonNLSElement[] fElements;
-
- /**
- * Creates a new <code>ExternalizeStringsAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ExternalizeStringsAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.ExternalizeStringsAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTERNALIZE_STRINGS_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public ExternalizeStringsAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(fEditor != null && SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isExternalizeStringsAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI - happens on selection changes
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptElement element= SelectionConverter.getInput(fEditor);
- if (!(element instanceof IJavaScriptUnit))
- return;
- run((IJavaScriptUnit)element);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- IJavaScriptUnit unit= getCompilationUnit(selection);
- if (unit != null) {//run on cu
- run(unit);
- } else {
- //run on multiple
- try {
- PlatformUI.getWorkbench().getProgressService().run(true, true, createRunnable(selection));
- } catch(InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(),
- ActionMessages.ExternalizeStringsAction_dialog_title,
- ActionMessages.FindStringsToExternalizeAction_error_message);
- return;
- } catch(InterruptedException e) {
- // OK
- return;
- }
- showResults();
- }
- }
-
- /**
- * Note: this method is for internal use only. Clients should not call this method.
- */
- public void run(final IJavaScriptUnit unit) {
- if (!ActionUtil.isEditable(fEditor, getShell(), unit))
- return;
-
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
- public void run() {
- try {
- if (unit != null && unit.exists()) {
- NLSRefactoring refactoring= NLSRefactoring.create(unit);
- if (refactoring != null)
- new RefactoringStarter().activate(refactoring, new ExternalizeWizard(refactoring), getShell(), ActionMessages.ExternalizeStringsAction_dialog_title, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
- }
- } catch(JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.ExternalizeStringsAction_dialog_title, ActionMessages.ExternalizeStringsAction_dialog_message);
- }
- }
- });
- }
-
- private static IJavaScriptUnit getCompilationUnit(IStructuredSelection selection) {
- if (selection.isEmpty() || selection.size() != 1)
- return null;
- Object first= selection.getFirstElement();
- if (first instanceof IJavaScriptUnit)
- return (IJavaScriptUnit) first;
- if (first instanceof IType)
- return ((IType) first).getJavaScriptUnit();
- return null;
- }
-
- private IRunnableWithProgress createRunnable(final IStructuredSelection selection) {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) throws InvocationTargetException {
- try {
- fElements= doRun(selection, pm);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- }
-
- private NonNLSElement[] doRun(IStructuredSelection selection, IProgressMonitor pm) throws CoreException {
- List elements= getSelectedElementList(selection);
- if (elements == null || elements.isEmpty())
- return new NonNLSElement[0];
-
- pm.beginTask(ActionMessages.FindStringsToExternalizeAction_find_strings, elements.size());
-
- try{
- List result= new ArrayList();
- for (Iterator iter= elements.iterator(); iter.hasNext();) {
- Object obj= iter.next();
- if (obj instanceof IJavaScriptElement) {
- IJavaScriptElement element= (IJavaScriptElement) obj;
- int elementType= element.getElementType();
-
- if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT) {
- result.addAll(analyze((IPackageFragment) element, new SubProgressMonitor(pm, 1)));
- } else if (elementType == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT) {
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- if (!root.isExternal() && !ReorgUtils.isClassFolder(root)) {
- result.addAll(analyze((IPackageFragmentRoot) element, new SubProgressMonitor(pm, 1)));
- } else {
- pm.worked(1);
- }
- } else if (elementType == IJavaScriptElement.JAVASCRIPT_PROJECT) {
- result.addAll(analyze((IJavaScriptProject) element, new SubProgressMonitor(pm, 1)));
- } else if (elementType == IJavaScriptElement.JAVASCRIPT_UNIT) {
- IJavaScriptUnit cu= (IJavaScriptUnit)element;
- if (cu.exists()) {
- NonNLSElement nlsElement= analyze(cu);
- if (nlsElement != null) {
- result.add(nlsElement);
- }
- }
- pm.worked(1);
- } else if (elementType == IJavaScriptElement.TYPE) {
- IType type= (IType)element;
- IJavaScriptUnit cu= type.getJavaScriptUnit();
- if (cu != null && cu.exists()) {
- NonNLSElement nlsElement= analyze(cu);
- if (nlsElement != null) {
- result.add(nlsElement);
- }
- }
- pm.worked(1);
- } else {
- pm.worked(1);
- }
- } else {
- pm.worked(1);
- }
- }
- return (NonNLSElement[]) result.toArray(new NonNLSElement[result.size()]);
- } finally{
- pm.done();
- }
- }
-
- private void showResults() {
- if (noStrings())
- MessageDialog.openInformation(getShell(), ActionMessages.ExternalizeStringsAction_dialog_title, ActionMessages.FindStringsToExternalizeAction_noStrings);
- else
- new NonNLSListDialog(getShell(), fElements, countStrings()).open();
- }
-
- private boolean noStrings() {
- if (fElements != null) {
- for (int i= 0; i < fElements.length; i++) {
- if (fElements[i].count != 0)
- return false;
- }
- }
- return true;
- }
-
- /*
- * returns List of Strings
- */
- private List analyze(IPackageFragment pack, IProgressMonitor pm) throws CoreException {
- try{
- if (pack == null)
- return new ArrayList(0);
-
- IJavaScriptUnit[] cus= pack.getJavaScriptUnits();
-
- pm.beginTask("", cus.length); //$NON-NLS-1$
- pm.setTaskName(pack.getElementName());
-
- List l= new ArrayList(cus.length);
- for (int i= 0; i < cus.length; i++){
- pm.subTask(cus[i].getElementName());
- NonNLSElement element= analyze(cus[i]);
- if (element != null)
- l.add(element);
- pm.worked(1);
- if (pm.isCanceled())
- throw new OperationCanceledException();
- }
- return l;
- } finally {
- pm.done();
- }
- }
-
- /*
- * returns List of Strings
- */
- private List analyze(IPackageFragmentRoot sourceFolder, IProgressMonitor pm) throws CoreException {
- try{
- IJavaScriptElement[] children= sourceFolder.getChildren();
- pm.beginTask("", children.length); //$NON-NLS-1$
- pm.setTaskName(sourceFolder.getElementName());
- List result= new ArrayList();
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElement iJavaElement= children[i];
- if (iJavaElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT){
- IPackageFragment pack= (IPackageFragment)iJavaElement;
- if (! pack.isReadOnly())
- result.addAll(analyze(pack, new SubProgressMonitor(pm, 1)));
- else
- pm.worked(1);
- } else
- pm.worked(1);
- }
- return result;
- } finally{
- pm.done();
- }
- }
-
- /*
- * returns List of Strings
- */
- private List analyze(IJavaScriptProject project, IProgressMonitor pm) throws CoreException {
- try{
- IPackageFragment[] packs= project.getPackageFragments();
- pm.beginTask("", packs.length); //$NON-NLS-1$
- List result= new ArrayList();
- for (int i= 0; i < packs.length; i++) {
- if (! packs[i].isReadOnly())
- result.addAll(analyze(packs[i], new SubProgressMonitor(pm, 1)));
- else
- pm.worked(1);
- }
- return result;
- } finally{
- pm.done();
- }
- }
-
- private int countStrings() {
- int found= 0;
- if (fElements != null) {
- for (int i= 0; i < fElements.length; i++)
- found+= fElements[i].count;
- }
- return found;
- }
-
- private NonNLSElement analyze(IJavaScriptUnit cu) throws CoreException {
- int count= countNonExternalizedStrings(cu);
- if (count == 0)
- return null;
- else
- return new NonNLSElement(cu, count);
- }
-
- private int countNonExternalizedStrings(IJavaScriptUnit cu) throws CoreException {
- try{
- NLSLine[] lines= NLSScanner.scan(cu);
- int result= 0;
- for (int i= 0; i < lines.length; i++) {
- result += countNonExternalizedStrings(lines[i]);
- }
- return result;
- } catch (InvalidInputException e) {
- throw new CoreException(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,
- Messages.format(ActionMessages.FindStringsToExternalizeAction_error_cannotBeParsed, cu.getElementName()),
- e));
- }
- }
-
- private int countNonExternalizedStrings(NLSLine line){
- int result= 0;
- NLSElement[] elements= line.getElements();
- for (int i= 0; i < elements.length; i++){
- if (! elements[i].hasTag())
- result++;
- }
- return result;
- }
-
- /**
- * returns <code>List</code> of <code>IPackageFragments</code>, <code>IPackageFragmentRoots</code> or
- * <code>IJavaProjects</code> (all entries are of the same kind)
- */
- private static List getSelectedElementList(IStructuredSelection selection) {
- if (selection == null)
- return null;
-
- return selection.toList();
- }
-
- //-------private classes --------------
-
- private static class NonNLSListDialog extends ListDialog {
-
- private static final int OPEN_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
-
- private Button fOpenButton;
-
- NonNLSListDialog(Shell parent, NonNLSElement[] input, int count) {
- super(parent);
- setInput(Arrays.asList(input));
- setTitle(ActionMessages.ExternalizeStringsAction_dialog_title);
- setMessage(Messages.format(ActionMessages.FindStringsToExternalizeAction_non_externalized, new Object[] {new Integer(count)} ));
- setContentProvider(new ArrayContentProvider());
- setLabelProvider(createLabelProvider());
- }
-
- public void create() {
- setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN);
- super.create();
- }
-
- protected Point getInitialSize() {
- return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
- }
-
- protected Control createDialogArea(Composite parent) {
- Composite result= (Composite)super.createDialogArea(parent);
- getTableViewer().addSelectionChangedListener(new ISelectionChangedListener(){
- public void selectionChanged(SelectionChangedEvent event){
- if (fOpenButton != null){
- fOpenButton.setEnabled(! getTableViewer().getSelection().isEmpty());
- }
- }
- });
- getTableViewer().getTable().addSelectionListener(new SelectionAdapter(){
- public void widgetDefaultSelected(SelectionEvent e) {
- NonNLSElement element= (NonNLSElement)e.item.getData();
- openWizard(element.cu);
- }
- });
- getTableViewer().getTable().setFocus();
- applyDialogFont(result);
- return result;
- }
-
- protected void createButtonsForButtonBar(Composite parent) {
- fOpenButton= createButton(parent, OPEN_BUTTON_ID, ActionMessages.FindStringsToExternalizeAction_button_label, true);
- fOpenButton.setEnabled(false);
-
- //looks like a 'close' but it a 'cancel'
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CLOSE_LABEL, false);
- }
-
- protected void buttonPressed(int buttonId) {
- if (buttonId != OPEN_BUTTON_ID){
- super.buttonPressed(buttonId);
- return;
- }
- ISelection s= getTableViewer().getSelection();
- if (s instanceof IStructuredSelection){
- IStructuredSelection ss= (IStructuredSelection)s;
- if (ss.getFirstElement() instanceof NonNLSElement)
- openWizard(((NonNLSElement)ss.getFirstElement()).cu);
- }
- }
-
- private void openWizard(IJavaScriptUnit unit) {
- try {
- if (unit != null && unit.exists()) {
- NLSRefactoring refactoring= NLSRefactoring.create(unit);
- if (refactoring != null)
- new RefactoringStarter().activate(refactoring, new ExternalizeWizard(refactoring), getShell(), ActionMessages.ExternalizeStringsAction_dialog_title, RefactoringSaveHelper.SAVE_NON_JAVA_UPDATES);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e,
- ActionMessages.ExternalizeStringsAction_dialog_title,
- ActionMessages.FindStringsToExternalizeAction_error_message);
- }
- }
-
- private static LabelProvider createLabelProvider() {
- return new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT){
- public String getText(Object element) {
- NonNLSElement nlsel= (NonNLSElement)element;
- String elementName= nlsel.cu.getResource().getFullPath().toString();
- return Messages.format(
- ActionMessages.FindStringsToExternalizeAction_foundStrings,
- new Object[] {new Integer(nlsel.count), elementName} );
- }
- public Image getImage(Object element) {
- return super.getImage(((NonNLSElement)element).cu);
- }
- };
- }
-
- /*
- * @see org.eclipse.jface.window.Window#configureShell(Shell)
- */
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.NONNLS_DIALOG);
- }
-
-
- }
-
- private static class NonNLSElement{
- IJavaScriptUnit cu;
- int count;
- NonNLSElement(IJavaScriptUnit cu, int count){
- this.cu= cu;
- this.count= count;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractConstantAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractConstantAction.java
deleted file mode 100644
index dd1f8f6c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractConstantAction.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ExtractConstantWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Extracts an expression into a constant field and replaces all occurrences of
- * the expression with the new constant.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ExtractConstantAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ExtractConstantAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.ExtractConstantAction_label);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTRACT_CONSTANT_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled((fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null));
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- setEnabled(RefactoringAvailabilityTester.isExtractConstantAvailable(selection));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try{
- final ExtractConstantRefactoring refactoring= new ExtractConstantRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection.getOffset(), selection.getLength());
- new RefactoringStarter().activate(refactoring, new ExtractConstantWizard(refactoring), getShell(), RefactoringMessages.ExtractConstantAction_extract_constant, RefactoringSaveHelper.SAVE_NOTHING);
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.ExtractConstantAction_extract_constant, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java
deleted file mode 100644
index ef26d148..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractMethodRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.code.ExtractMethodWizard;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Extracts the code selected inside a compilation unit editor into a new method.
- * Necessary arguments, exceptions and returns values are computed and an
- * appropriate method signature is generated.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ExtractMethodAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public ExtractMethodAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.ExtractMethodAction_label);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTRACT_METHOD_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(selection.getLength() == 0 ? false : fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- setEnabled(RefactoringAvailabilityTester.isExtractMethodAvailable(selection));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try{
- final ExtractMethodRefactoring refactoring= new ExtractMethodRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection.getOffset(), selection.getLength());
- new RefactoringStarter().activate(refactoring, new ExtractMethodWizard(refactoring), getShell(), RefactoringMessages.ExtractMethodAction_dialog_title, RefactoringSaveHelper.SAVE_NOTHING);
- } catch (CoreException e){
- ExceptionHandler.handle(e, RefactoringMessages.ExtractMethodAction_dialog_title, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractTempAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractTempAction.java
deleted file mode 100644
index e52d06b2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractTempAction.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.code.ExtractTempRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.ExtractTempWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringStarter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Extracts an expression into a new local variable and replaces all occurrences of
- * the expression with the local variable.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ExtractTempAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ExtractTempAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.ExtractTempAction_label);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.EXTRACT_TEMP_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- setEnabled(RefactoringAvailabilityTester.isExtractTempAvailable(selection));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try{
- final ExtractTempRefactoring refactoring= new ExtractTempRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection.getOffset(), selection.getLength());
- new RefactoringStarter().activate(refactoring, new ExtractTempWizard(refactoring), getShell(), RefactoringMessages.ExtractTempAction_extract_temp, RefactoringSaveHelper.SAVE_NOTHING);
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.ExtractTempAction_extract_temp, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindAction.java
deleted file mode 100644
index b88c5fb6..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindAction.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchQuery;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Abstract class for JavaScript search actions.
- * <p>
- * Note: This class is for internal use only. Clients should not use this class.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public abstract class FindAction extends SelectionDispatchAction {
-
- // A dummy which can't be selected in the UI
- private static final IJavaScriptElement RETURN_WITHOUT_BEEP= JavaScriptCore.create(JavaScriptPlugin.getWorkspace().getRoot());
-
- private Class[] fValidTypes;
- private JavaEditor fEditor;
-
-
- FindAction(IWorkbenchSite site) {
- super(site);
- fValidTypes= getValidTypes();
- init();
- }
-
- FindAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Called once by the constructors to initialize label, tooltip, image and help support of the action.
- * To be overridden by implementors of this action.
- */
- abstract void init();
-
- /**
- * Called once by the constructors to get the list of the valid input types of the action.
- * To be overridden by implementors of this action.
- * @return the valid input types of the action
- */
- abstract Class[] getValidTypes();
-
- private boolean canOperateOn(IStructuredSelection sel) {
- return sel != null && !sel.isEmpty() && canOperateOn(getJavaElement(sel, true));
- }
-
- boolean canOperateOn(IJavaScriptElement element) {
- if (element == null || fValidTypes == null || fValidTypes.length == 0 || !ActionUtil.isOnBuildPath(element))
- return false;
-
- for (int i= 0; i < fValidTypes.length; i++) {
- if (fValidTypes[i].isInstance(element)) {
- if (element.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT)
- return hasChildren((IPackageFragment)element);
- else
- return true;
- }
- }
- return false;
- }
-
- private boolean hasChildren(IPackageFragment packageFragment) {
- try {
- return packageFragment.hasChildren();
- } catch (JavaScriptModelException ex) {
- return false;
- }
- }
-
- private IJavaScriptElement getTypeIfPossible(IJavaScriptElement o, boolean silent) {
- switch (o.getElementType()) {
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- if (silent)
- return o;
- else
- return findType((IJavaScriptUnit)o, silent);
- case IJavaScriptElement.CLASS_FILE:
- return ((IClassFile)o).getType();
- default:
- return o;
- }
- }
-
- IJavaScriptElement getJavaElement(IStructuredSelection selection, boolean silent) {
- if (selection.size() == 1) {
- Object firstElement= selection.getFirstElement();
- IJavaScriptElement elem= null;
- if (firstElement instanceof IJavaScriptElement)
- elem= (IJavaScriptElement) firstElement;
- else if (firstElement instanceof IAdaptable)
- elem= (IJavaScriptElement) ((IAdaptable) firstElement).getAdapter(IJavaScriptElement.class);
- if (elem != null) {
- return getTypeIfPossible(elem, silent);
- }
-
- }
- return null;
- }
-
- private void showOperationUnavailableDialog() {
- MessageDialog.openInformation(getShell(), SearchMessages.JavaElementAction_operationUnavailable_title, getOperationUnavailableMessage());
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_generic;
- }
-
- private IJavaScriptElement findType(IJavaScriptUnit cu, boolean silent) {
- IType[] types= null;
- try {
- types= cu.getAllTypes();
- } catch (JavaScriptModelException ex) {
- if (JavaModelUtil.isExceptionToBeLogged(ex))
- ExceptionHandler.log(ex, SearchMessages.JavaElementAction_error_open_message);
- if (silent)
- return RETURN_WITHOUT_BEEP;
- else
- return null;
- }
- if (types.length == 1 || (silent && types.length > 0))
- return types[0];
- if (silent)
- return RETURN_WITHOUT_BEEP;
- if (types.length == 0)
- return null;
- String title= SearchMessages.JavaElementAction_typeSelectionDialog_title;
- String message = SearchMessages.JavaElementAction_typeSelectionDialog_message;
- int flags= (JavaScriptElementLabelProvider.SHOW_DEFAULT);
-
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaScriptElementLabelProvider(flags));
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.setElements(types);
-
- if (dialog.open() == Window.OK)
- return (IType)dialog.getFirstResult();
- else
- return RETURN_WITHOUT_BEEP;
- }
-
- /*
- * Method declared on SelectionChangedAction.
- */
- public void run(IStructuredSelection selection) {
- IJavaScriptElement element= getJavaElement(selection, false);
- if (element == null || !element.exists()) {
- showOperationUnavailableDialog();
- return;
- }
- else if (element == RETURN_WITHOUT_BEEP)
- return;
-
- run(element);
- }
-
- /*
- * Method declared on SelectionChangedAction.
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isProcessable(fEditor))
- return;
- try {
- String title= SearchMessages.SearchElementSelectionDialog_title;
- String message= SearchMessages.SearchElementSelectionDialog_message;
-
- IJavaScriptElement[] elements= SelectionConverter.codeResolveForked(fEditor, true);
- if (elements.length > 0 && canOperateOn(elements[0])) {
- IJavaScriptElement element= elements[0];
- if (elements.length > 1)
- element= SelectionConverter.selectJavaElement(elements, getShell(), title, message);
- if (element != null)
- run(element);
- }
- else
- showOperationUnavailableDialog();
- } catch (InvocationTargetException ex) {
- String title= SearchMessages.Search_Error_search_title;
- String message= SearchMessages.Search_Error_codeResolve;
- ExceptionHandler.handle(ex, getShell(), title, message);
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- /*
- * Method declared on SelectionChangedAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(canOperateOn(selection));
- }
-
- /*
- * Method declared on SelectionChangedAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /**
- * Executes this action for the given JavaScript element.
- * @param element The JavaScript element to be found.
- */
- public void run(IJavaScriptElement element) {
-
- if (!ActionUtil.isProcessable(getShell(), element))
- return;
-
- // will return true except for debugging purposes.
- try {
- performNewSearch(element);
- } catch (JavaScriptModelException ex) {
- ExceptionHandler.handle(ex, getShell(), SearchMessages.Search_Error_search_notsuccessful_title, SearchMessages.Search_Error_search_notsuccessful_message);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- private void performNewSearch(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchQuery query= new JavaSearchQuery(createQuery(element));
- if (query.canRunInBackground()) {
- /*
- * This indirection with Object as parameter is needed to prevent the loading
- * of the Search plug-in: the VM verifies the method call and hence loads the
- * types used in the method signature, eventually triggering the loading of
- * a plug-in (in this case ISearchQuery results in Search plug-in being loaded).
- */
- SearchUtil.runQueryInBackground(query);
- } else {
- IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
- /*
- * This indirection with Object as parameter is needed to prevent the loading
- * of the Search plug-in: the VM verifies the method call and hence loads the
- * types used in the method signature, eventually triggering the loading of
- * a plug-in (in this case it would be ISearchQuery).
- */
- IStatus status= SearchUtil.runQueryInForeground(progressService, query);
- if (status.matches(IStatus.ERROR | IStatus.INFO | IStatus.WARNING)) {
- ErrorDialog.openError(getShell(), SearchMessages.Search_Error_search_title, SearchMessages.Search_Error_search_message, status);
- }
- }
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- IJavaScriptSearchScope scope= factory.createWorkspaceScope(true);
- String description= factory.getWorkspaceScopeDescription(true);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
- abstract int getLimitTo();
-
- IType getType(IJavaScriptElement element) {
- if (element == null)
- return null;
-
- IType type= null;
- if (element.getElementType() == IJavaScriptElement.TYPE)
- type= (IType)element;
- else if (element instanceof IMember)
- type= ((IMember)element).getDeclaringType();
- else if (element instanceof ILocalVariable) {
- type= (IType)element.getAncestor(IJavaScriptElement.TYPE);
- }
- return type;
- }
-
- JavaEditor getEditor() {
- return fEditor;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsAction.java
deleted file mode 100644
index 606c85fa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsAction.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds declarations of the selected element in the workspace.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindDeclarationsAction extends FindAction {
-
- /**
- * Creates a new <code>FindDeclarationsAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindDeclarationsAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindDeclarationsAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindDeclarationAction_label);
- setToolTipText(SearchMessages.Search_FindDeclarationAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_DECLARATIONS_IN_WORKSPACE_ACTION);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, IFunction.class, IType.class, IJavaScriptUnit.class, IImportDeclaration.class, IPackageFragment.class, ILocalVariable.class };
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.DECLARATIONS | IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE | IJavaScriptSearchConstants.IGNORE_RETURN_TYPE;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInHierarchyAction.java
deleted file mode 100644
index 02fc9776..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInHierarchyAction.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds declarations of the selected element in its hierarchy.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindDeclarationsInHierarchyAction extends FindDeclarationsAction {
-
- /**
- * Creates a new <code>FindDeclarationsInHierarchyAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindDeclarationsInHierarchyAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindDeclarationsInHierarchyAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, IFunction.class, ILocalVariable.class};
- }
-
- void init() {
- setText(SearchMessages.Search_FindHierarchyDeclarationsAction_label);
- setToolTipText(SearchMessages.Search_FindHierarchyDeclarationsAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_DECLARATIONS_IN_HIERARCHY_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
-
- IType type= getType(element);
- if (type == null) {
- return super.createQuery(element);
- }
- IJavaScriptSearchScope scope= SearchEngine.createHierarchyScope(type);
- String description= factory.getHierarchyScopeDescription(type);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInProjectAction.java
deleted file mode 100644
index 2acb5fe2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInProjectAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds declarations of the selected element in the enclosing project
- * of the selected element.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindDeclarationsInProjectAction extends FindDeclarationsAction {
-
- /**
- * Creates a new <code>FindDeclarationsInProjectAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindDeclarationsInProjectAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindDeclarationsInProjectAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindDeclarationsInProjectAction_label);
- setToolTipText(SearchMessages.Search_FindDeclarationsInProjectAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_DECLARATIONS_IN_PROJECT_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- JavaEditor editor= getEditor();
-
- IJavaScriptSearchScope scope;
- String description;
- boolean isInsideJRE= true;
- if (editor != null) {
- scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
- description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
- } else {
- scope= factory.createJavaProjectSearchScope(element.getJavaScriptProject(), isInsideJRE);
- description= factory.getProjectScopeDescription(element.getJavaScriptProject(), isInsideJRE);
- }
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInWorkingSetAction.java
deleted file mode 100644
index 104336c7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindDeclarationsInWorkingSetAction.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds declarations of the selected element in working sets.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindDeclarationsInWorkingSetAction extends FindDeclarationsAction {
-
- private IWorkingSet[] fWorkingSet;
-
- /**
- * Creates a new <code>FindDeclarationsInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
- * prompted to select the working sets.
- *
- * @param site the site providing context information for this action
- */
- public FindDeclarationsInWorkingSetAction(IWorkbenchSite site) {
- this(site, null);
- }
-
- /**
- * Creates a new <code>FindDeclarationsInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param workingSets the working sets to be used in the search
- */
- public FindDeclarationsInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
- super(site);
- fWorkingSet= workingSets;
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindDeclarationsInWorkingSetAction(JavaEditor editor) {
- this(editor, null);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- * @param workingSets the working sets to be used in the search
- */
- public FindDeclarationsInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
- super(editor);
- fWorkingSet= workingSets;
- }
-
- void init() {
- setText(SearchMessages.Search_FindDeclarationsInWorkingSetAction_label);
- setToolTipText(SearchMessages.Search_FindDeclarationsInWorkingSetAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_DECLARATIONS_IN_WORKING_SET_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
-
- IWorkingSet[] workingSets= fWorkingSet;
- if (fWorkingSet == null) {
- workingSets= factory.queryWorkingSets();
- if (workingSets == null)
- return null;
- }
- SearchUtil.updateLRUWorkingSets(workingSets);
- IJavaScriptSearchScope scope= factory.createJavaSearchScope(workingSets, true);
- String description= factory.getWorkingSetScopeDescription(workingSets, true);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindExceptionOccurrencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindExceptionOccurrencesAction.java
deleted file mode 100644
index ef66248d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindExceptionOccurrencesAction.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.ExceptionOccurrencesFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.FindOccurrencesEngine;
-
-/**
- * Action to find all originators of a exception (e.g. method invocations,
- * class casts, ...) for a given exception.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindExceptionOccurrencesAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public FindExceptionOccurrencesAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(getEditorInput(editor) != null);
- }
-
- /**
- * Creates a new <code>FindExceptionOccurrencesAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindExceptionOccurrencesAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.FindExceptionOccurrences_text);
- setToolTipText(ActionMessages.FindExceptionOccurrences_toolTip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_EXCEPTION_OCCURRENCES);
- }
-
- //---- Text Selection ----------------------------------------------------------------------
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /**
- * {@inheritDoc}
- *
- *
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getMember(selection) != null);
- }
-
- /* (non-JavaDoc)
- * Method declared in SelectionDispatchAction.
- */
- public final void run(ITextSelection ts) {
- IJavaScriptElement input= getEditorInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
- FindOccurrencesEngine engine= FindOccurrencesEngine.create(input, new ExceptionOccurrencesFinder());
- try {
- String result= engine.run(ts.getOffset(), ts.getLength());
- if (result != null)
- showMessage(getShell(), fEditor, result);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static IJavaScriptElement getEditorInput(JavaEditor editor) {
- IEditorInput input= editor.getEditorInput();
- if (input instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)input).getClassFile();
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input);
- }
-
- private static void showMessage(Shell shell, JavaEditor editor, String msg) {
- IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
- if (statusLine != null)
- statusLine.setMessage(true, msg, null);
- shell.getDisplay().beep();
- }
-
- private IMember getMember(IStructuredSelection selection) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementOccurrencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementOccurrencesAction.java
deleted file mode 100644
index 11ad6055..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementOccurrencesAction.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.FindOccurrencesEngine;
-import org.eclipse.wst.jsdt.internal.ui.search.ImplementOccurrencesFinder;
-
-/**
- * Action to find all implement occurrences of an extended class or an implemented interface.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindImplementOccurrencesAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public FindImplementOccurrencesAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(getEditorInput(editor) != null);
- }
-
- /**
- * Creates a new <code>FindImplementOccurrencesAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindImplementOccurrencesAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.FindImplementOccurrencesAction_text);
- setToolTipText(ActionMessages.FindImplementOccurrencesAction_toolTip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_IMPLEMENT_OCCURRENCES);
- }
-
- //---- Text Selection ----------------------------------------------------------------------
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /**
- * {@inheritDoc}
- *
- *
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getMember(selection) != null);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
- */
- public final void run(ITextSelection ts) {
- IJavaScriptElement input= getEditorInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
- FindOccurrencesEngine engine= FindOccurrencesEngine.create(input, new ImplementOccurrencesFinder());
- try {
- String result= engine.run(ts.getOffset(), ts.getLength());
- if (result != null)
- showMessage(getShell(), fEditor, result);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static IJavaScriptElement getEditorInput(JavaEditor editor) {
- IEditorInput input= editor.getEditorInput();
- if (input instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)input).getClassFile();
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input);
- }
-
- private static void showMessage(Shell shell, JavaEditor editor, String msg) {
- IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
- if (statusLine != null)
- statusLine.setMessage(true, msg, null);
- shell.getDisplay().beep();
- }
-
- private IMember getMember(IStructuredSelection selection) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsAction.java
deleted file mode 100644
index 95f747ad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsAction.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds implementors of the selected element in the workspace.
- * The action is applicable to selections representing a JavaScript interface.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindImplementorsAction extends FindAction {
-
- /**
- * Creates a new <code>FindImplementorsAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindImplementorsAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindImplementorsAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindImplementorsAction_label);
- setToolTipText(SearchMessages.Search_FindImplementorsAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IJavaScriptUnit.class, IType.class};
- }
-
- boolean canOperateOn(IJavaScriptElement element) {
- return false;
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.IMPLEMENTORS;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_interface;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInProjectAction.java
deleted file mode 100644
index 1b5f1742..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInProjectAction.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds implementors of the selected element in the enclosing project.
- * The action is applicable to selections representing a JavaScript interface.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindImplementorsInProjectAction extends FindImplementorsAction {
-
- /**
- * Creates a new <code>FindImplementorsInProjectAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindImplementorsInProjectAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindImplementorsInProjectAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindImplementorsInProjectAction_label);
- setToolTipText(SearchMessages.Search_FindImplementorsInProjectAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_IMPLEMENTORS_IN_PROJECT_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- JavaEditor editor= getEditor();
-
- IJavaScriptSearchScope scope;
- String description;
- boolean isInsideJRE= factory.isInsideJRE(element);
- if (editor != null) {
- scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
- description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
- } else {
- scope= factory.createJavaProjectSearchScope(element.getJavaScriptProject(), isInsideJRE);
- description= factory.getProjectScopeDescription(element.getJavaScriptProject(), isInsideJRE);
- }
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInWorkingSetAction.java
deleted file mode 100644
index 307de421..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindImplementorsInWorkingSetAction.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds implementors of the selected element in working sets.
- * The action is applicable to selections representing a JavaScript interface.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindImplementorsInWorkingSetAction extends FindImplementorsAction {
-
- private IWorkingSet[] fWorkingSets;
-
- /**
- * Creates a new <code>FindImplementorsInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
- * prompted to select the working sets.
- *
- * @param site the site providing context information for this action
- */
- public FindImplementorsInWorkingSetAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Creates a new <code>FindImplementorsInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param workingSets the working sets to be used in the search
- */
- public FindImplementorsInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
- this(site);
- fWorkingSets= workingSets;
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindImplementorsInWorkingSetAction(JavaEditor editor) {
- super(editor);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- * @param workingSets the working sets to be used in the search
- */
- public FindImplementorsInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
- this(editor);
- fWorkingSets= workingSets;
- }
-
- void init() {
- setText(SearchMessages.Search_FindImplementorsInWorkingSetAction_label);
- setToolTipText(SearchMessages.Search_FindImplementorsInWorkingSetAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
-
- IWorkingSet[] workingSets= fWorkingSets;
- if (fWorkingSets == null) {
- workingSets= factory.queryWorkingSets();
- if (workingSets == null)
- return super.createQuery(element); // workspace
- }
- SearchUtil.updateLRUWorkingSets(workingSets);
- IJavaScriptSearchScope scope= factory.createJavaSearchScope(workingSets, true);
- String description= factory.getWorkingSetScopeDescription(workingSets, true);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindOccurrencesInFileAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindOccurrencesInFileAction.java
deleted file mode 100644
index c645bc2d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindOccurrencesInFileAction.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.FindOccurrencesEngine;
-import org.eclipse.wst.jsdt.internal.ui.search.OccurrencesFinder;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Action to find all occurrences of a compilation unit member (e.g.
- * fields, methods, types, and local variables) in a file.
- * <p>
- * Action is applicable to selections containing elements of type
- * <tt>IMember</tt>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindOccurrencesInFileAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- /**
- * Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
- * that the selection provided by the view part's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the part providing context information for this action
- */
- public FindOccurrencesInFileAction(IViewPart part) {
- this(part.getSite());
- }
-
- /**
- * Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
- * that the selection provided by the page's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page providing context information for this action
- */
- public FindOccurrencesInFileAction(Page page) {
- this(page.getSite());
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindOccurrencesInFileAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(getEditorInput(editor) != null);
- }
-
- /**
- * Creates a new <code>FindOccurrencesInFileAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- *
- */
- public FindOccurrencesInFileAction(IWorkbenchSite site) {
- super(site);
-
- if (site instanceof IViewSite)
- fActionBars= ((IViewSite)site).getActionBars();
- else if (site instanceof IEditorSite)
- fActionBars= ((IEditorSite)site).getActionBars();
- else if (site instanceof IPageSite)
- fActionBars= ((IPageSite)site).getActionBars();
-
- setText(SearchMessages.Search_FindOccurrencesInFile_label);
- setToolTipText(SearchMessages.Search_FindOccurrencesInFile_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_OCCURRENCES_IN_FILE_ACTION);
- }
-
- //---- Structured Selection -------------------------------------------------------------
-
- /* (non-JavaDoc)
- * Method declared in SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getMember(selection) != null);
- }
-
- /* (non-JavaDoc)
- * Method declared in SelectionDispatchAction.
- */
- private IMember getMember(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object o= selection.getFirstElement();
- if (o instanceof IMember) {
- IMember member= (IMember)o;
- try {
- if (member.getNameRange() == null)
- return null;
- } catch (JavaScriptModelException ex) {
- return null;
- }
-
- IClassFile file= member.getClassFile();
- if (file != null) {
- try {
- if (file.getSourceRange() != null)
- return member;
- } catch (JavaScriptModelException e) {
- return null;
- }
- }
- return member;
- }
- return null;
- }
-
- public void run(IStructuredSelection selection) {
- IMember member= getMember(selection);
- if (!ActionUtil.isProcessable(getShell(), member))
- return;
- FindOccurrencesEngine engine= FindOccurrencesEngine.create(member, new OccurrencesFinder());
- try {
- ISourceRange range= member.getNameRange();
- String result= engine.run(range.getOffset(), range.getLength());
- if (result != null)
- showMessage(getShell(), fActionBars, result);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static void showMessage(Shell shell, IActionBars actionBars, String msg) {
- if (actionBars != null) {
- IStatusLineManager statusLine= actionBars.getStatusLineManager();
- if (statusLine != null)
- statusLine.setMessage(msg);
- }
- shell.getDisplay().beep();
- }
-
- //---- Text Selection ----------------------------------------------------------------------
-
- /* (non-JavaDoc)
- * Method declared in SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-JavaDoc)
- * Method declared in SelectionDispatchAction.
- */
- public final void run(ITextSelection ts) {
- IJavaScriptElement input= getEditorInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
- FindOccurrencesEngine engine= FindOccurrencesEngine.create(input, new OccurrencesFinder());
- try {
- String result= engine.run(ts.getOffset(), ts.getLength());
- if (result != null)
- showMessage(getShell(), fEditor, result);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private static IJavaScriptElement getEditorInput(JavaEditor editor) {
- IEditorInput input= editor.getEditorInput();
- if (input instanceof IClassFileEditorInput)
- return ((IClassFileEditorInput)input).getClassFile();
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input);
- }
-
- private static void showMessage(Shell shell, JavaEditor editor, String msg) {
- IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
- if (statusLine != null)
- statusLine.setMessage(true, msg, null);
- shell.getDisplay().beep();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesAction.java
deleted file mode 100644
index f477e5be..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesAction.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field read accesses of the selected element in the workspace.
- * The action is applicable to selections representing a JavaScript interface field.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReadReferencesAction extends FindReferencesAction {
-
- /**
- * Creates a new <code>FindReadReferencesAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReadReferencesAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReadReferencesAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindReadReferencesAction_label);
- setToolTipText(SearchMessages.Search_FindReadReferencesAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_READ_REFERENCES_IN_WORKSPACE_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.READ_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInHierarchyAction.java
deleted file mode 100644
index 47ec220e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInHierarchyAction.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field read accesses of the selected element in its hierarchy.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReadReferencesInHierarchyAction extends FindReferencesInHierarchyAction {
-
- /**
- * Creates a new <code>FindReadReferencesInHierarchyAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReadReferencesInHierarchyAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReadReferencesInHierarchyAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindReadReferencesInHierarchyAction_label);
- setToolTipText(SearchMessages.Search_FindReadReferencesInHierarchyAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_READ_REFERENCES_IN_HIERARCHY_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.READ_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInProjectAction.java
deleted file mode 100644
index 716d2e60..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInProjectAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds field read accesses of the selected element in the enclosing project.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReadReferencesInProjectAction extends FindReadReferencesAction {
-
- /**
- * Creates a new <code>FindReadReferencesInProjectAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReadReferencesInProjectAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReadReferencesInProjectAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindReadReferencesInProjectAction_label);
- setToolTipText(SearchMessages.Search_FindReadReferencesInProjectAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_READ_REFERENCES_IN_PROJECT_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- JavaEditor editor= getEditor();
-
- IJavaScriptSearchScope scope;
- String description;
- boolean isInsideJRE= factory.isInsideJRE(element);
- if (editor != null) {
- scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
- description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
- } else {
- scope= factory.createJavaProjectSearchScope(element.getJavaScriptProject(), isInsideJRE);
- description= factory.getProjectScopeDescription(element.getJavaScriptProject(), isInsideJRE);
- }
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInWorkingSetAction.java
deleted file mode 100644
index 2e482daa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReadReferencesInWorkingSetAction.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field read accesses of the selected element in working sets.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReadReferencesInWorkingSetAction extends FindReferencesInWorkingSetAction {
-
- /**
- * Creates a new <code>FindReadReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
- * prompted to select the working sets.
- *
- * @param site the site providing context information for this action
- */
- public FindReadReferencesInWorkingSetAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Creates a new <code>FindReadReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param workingSets the working sets to be used in the search
- */
- public FindReadReferencesInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
- super(site, workingSets);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReadReferencesInWorkingSetAction(JavaEditor editor) {
- super(editor);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- * @param workingSets the working sets to be used in the search
- */
- public FindReadReferencesInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
- super(editor, workingSets);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindReadReferencesInWorkingSetAction_label);
- setToolTipText(SearchMessages.Search_FindReadReferencesInWorkingSetAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_READ_REFERENCES_IN_WORKING_SET_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.READ_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesAction.java
deleted file mode 100644
index cdae0884..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesAction.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds references of the selected element in the workspace.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReferencesAction extends FindAction {
-
- /**
- * Creates a new <code>FindReferencesAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReferencesAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReferencesAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IJavaScriptUnit.class, IType.class, IFunction.class, IField.class, IImportDeclaration.class, IPackageFragment.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindReferencesAction_label);
- setToolTipText(SearchMessages.Search_FindReferencesAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_REFERENCES_IN_WORKSPACE_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.REFERENCES;
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- boolean isInsideJRE= factory.isInsideJRE(element);
-
- IJavaScriptSearchScope scope= factory.createWorkspaceScope(isInsideJRE);
- String description= factory.getWorkspaceScopeDescription(isInsideJRE);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
- public void run(IJavaScriptElement element) {
- SearchUtil.warnIfBinaryConstant(element, getShell());
- super.run(element);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInHierarchyAction.java
deleted file mode 100644
index abb4285a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInHierarchyAction.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds references of the selected element in its hierarchy.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReferencesInHierarchyAction extends FindReferencesAction {
-
- /**
- * Creates a new <code>FindReferencesInHierarchyAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReferencesInHierarchyAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReferencesInHierarchyAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IJavaScriptUnit.class, IType.class, IFunction.class, IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindHierarchyReferencesAction_label);
- setToolTipText(SearchMessages.Search_FindHierarchyReferencesAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_REFERENCES_IN_HIERARCHY_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- IType type= getType(element);
- if (type == null) {
- return super.createQuery(element);
- }
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- IJavaScriptSearchScope scope= SearchEngine.createHierarchyScope(type);
- String description= factory.getHierarchyScopeDescription(type);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInProjectAction.java
deleted file mode 100644
index e046fdca..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInProjectAction.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds references to the selected element in the enclosing project
- * of the selected element.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReferencesInProjectAction extends FindReferencesAction {
-
- /**
- * Creates a new <code>FindReferencesInProjectAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindReferencesInProjectAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReferencesInProjectAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, IFunction.class, IType.class, IJavaScriptUnit.class, IImportDeclaration.class, IPackageFragment.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindReferencesInProjectAction_label);
- setToolTipText(SearchMessages.Search_FindReferencesInProjectAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_REFERENCES_IN_PROJECT_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- JavaEditor editor= getEditor();
-
- IJavaScriptSearchScope scope;
- String description;
- boolean isInsideJRE= factory.isInsideJRE(element);
- if (editor != null) {
- scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
- description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
- } else {
- scope= factory.createJavaProjectSearchScope(element.getJavaScriptProject(), isInsideJRE);
- description= factory.getProjectScopeDescription(element.getJavaScriptProject(), isInsideJRE);
- }
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInWorkingSetAction.java
deleted file mode 100644
index 895db799..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindReferencesInWorkingSetAction.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-
-/**
- * Finds references of the selected element in working sets.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindReferencesInWorkingSetAction extends FindReferencesAction {
-
- private IWorkingSet[] fWorkingSets;
-
- /**
- * Creates a new <code>FindReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will
- * be prompted to select the working sets.
- *
- * @param site the site providing context information for this action
- */
- public FindReferencesInWorkingSetAction(IWorkbenchSite site) {
- this(site, null);
- }
-
- /**
- * Creates a new <code>FindReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param workingSets the working sets to be used in the search
- */
- public FindReferencesInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
- super(site);
- fWorkingSets= workingSets;
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindReferencesInWorkingSetAction(JavaEditor editor) {
- this(editor, null);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- * @param workingSets the working sets to be used in the search
- */
- public FindReferencesInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
- super(editor);
- fWorkingSets= workingSets;
- }
-
- void init() {
- setText(SearchMessages.Search_FindReferencesInWorkingSetAction_label);
- setToolTipText(SearchMessages.Search_FindReferencesInWorkingSetAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_REFERENCES_IN_WORKING_SET_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException, InterruptedException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
-
- IWorkingSet[] workingSets= fWorkingSets;
- if (fWorkingSets == null) {
- workingSets= factory.queryWorkingSets();
- if (workingSets == null)
- return super.createQuery(element); // in workspace
- }
- SearchUtil.updateLRUWorkingSets(workingSets);
- IJavaScriptSearchScope scope= factory.createJavaSearchScope(workingSets, true);
- String description= factory.getWorkingSetScopeDescription(workingSets, true);
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesAction.java
deleted file mode 100644
index ade523b4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesAction.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field write accesses of the selected element in the workspace.
- * The action is applicable to selections representing a JavaScript element.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindWriteReferencesAction extends FindReferencesAction {
-
- /**
- * Creates a new <code>FindWriteReferencesAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindWriteReferencesAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindWriteReferencesAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindWriteReferencesAction_label);
- setToolTipText(SearchMessages.Search_FindWriteReferencesAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.WRITE_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInHierarchyAction.java
deleted file mode 100644
index b34f7908..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInHierarchyAction.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field write accesses of the selected element in its hierarchy.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindWriteReferencesInHierarchyAction extends FindReferencesInHierarchyAction {
-
- /**
- * Creates a new <code>FindWriteReferencesInHierarchyAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindWriteReferencesInHierarchyAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindWriteReferencesInHierarchyAction(JavaEditor editor) {
- super(editor);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindWriteReferencesInHierarchyAction_label);
- setToolTipText(SearchMessages.Search_FindWriteReferencesInHierarchyAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.WRITE_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInProjectAction.java
deleted file mode 100644
index 9c600c61..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInProjectAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.search.ElementQuerySpecification;
-import org.eclipse.wst.jsdt.ui.search.QuerySpecification;
-
-/**
- * Finds field write accesses of the selected element in the enclosing project.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindWriteReferencesInProjectAction extends FindWriteReferencesAction {
-
- /**
- * Creates a new <code>FindWriteReferencesInProjectAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FindWriteReferencesInProjectAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindWriteReferencesInProjectAction(JavaEditor editor) {
- super(editor);
- }
-
- void init() {
- setText(SearchMessages.Search_FindWriteReferencesInProjectAction_label);
- setToolTipText(SearchMessages.Search_FindWriteReferencesInProjectAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_PROJECT_ACTION);
- }
-
- QuerySpecification createQuery(IJavaScriptElement element) throws JavaScriptModelException {
- JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
- JavaEditor editor= getEditor();
-
- IJavaScriptSearchScope scope;
- String description;
- boolean isInsideJRE= factory.isInsideJRE(element);
- if (editor != null) {
- scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
- description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
- } else {
- scope= factory.createJavaProjectSearchScope(element.getJavaScriptProject(), isInsideJRE);
- description= factory.getProjectScopeDescription(element.getJavaScriptProject(), isInsideJRE);
- }
- return new ElementQuerySpecification(element, getLimitTo(), scope, description);
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInWorkingSetAction.java
deleted file mode 100644
index 834e1fd4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FindWriteReferencesInWorkingSetAction.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-
-/**
- * Finds field write accesses of the selected element in working sets.
- * The action is applicable to selections representing a JavaScript field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FindWriteReferencesInWorkingSetAction extends FindReferencesInWorkingSetAction {
-
- /**
- * Creates a new <code>FindWriteReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
- * prompted to select the working sets.
- *
- * @param site the site providing context information for this action
- */
- public FindWriteReferencesInWorkingSetAction(IWorkbenchSite site) {
- super(site);
- }
-
- /**
- * Creates a new <code>FindWriteReferencesInWorkingSetAction</code>. The action
- * requires that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- * @param workingSets the working sets to be used in the search
- */
- public FindWriteReferencesInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
- super(site, workingSets);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public FindWriteReferencesInWorkingSetAction(JavaEditor editor) {
- super(editor);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- * @param workingSets the working sets to be used in the search
- */
- public FindWriteReferencesInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
- super(editor, workingSets);
- }
-
- Class[] getValidTypes() {
- return new Class[] { IField.class, ILocalVariable.class };
- }
-
- void init() {
- setText(SearchMessages.Search_FindWriteReferencesInWorkingSetAction_label);
- setToolTipText(SearchMessages.Search_FindWriteReferencesInWorkingSetAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION);
- }
-
- int getLimitTo() {
- return IJavaScriptSearchConstants.WRITE_ACCESSES;
- }
-
- String getOperationUnavailableMessage() {
- return SearchMessages.JavaElementAction_operationUnavailable_field;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FormatAllAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FormatAllAction.java
deleted file mode 100644
index 7943b3e7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/FormatAllAction.java
+++ /dev/null
@@ -1,430 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.DocumentRewriteSession;
-import org.eclipse.jface.text.DocumentRewriteSessionType;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension;
-import org.eclipse.jface.text.IDocumentExtension4;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.jface.text.formatter.MultiPassContentFormatter;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaFormattingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions;
-
-/**
- * Formats the code of the compilation units contained in the selection.
- * <p>
- * The action is applicable to selections containing elements of
- * type <code>IJavaScriptUnit</code>, <code>IPackage
- * </code>, <code>IPackageFragmentRoot/code> and
- * <code>IJavaScriptProject</code>.
- * </p>
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class FormatAllAction extends SelectionDispatchAction {
-
- private DocumentRewriteSession fRewriteSession;
-
- /* (non-Javadoc)
- * Class implements IObjectActionDelegate
- */
- public static class ObjectDelegate implements IObjectActionDelegate {
- private FormatAllAction fAction;
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- fAction= new FormatAllAction(targetPart.getSite());
- }
- public void run(IAction action) {
- fAction.run();
- }
- public void selectionChanged(IAction action, ISelection selection) {
- if (fAction == null)
- action.setEnabled(false);
- }
- }
-
- /**
- * Creates a new <code>FormatAllAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public FormatAllAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.FormatAllAction_label);
- setToolTipText(ActionMessages.FormatAllAction_tooltip);
- setDescription(ActionMessages.FormatAllAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FORMAT_ALL);
- }
-
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- // do nothing
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(isEnabled(selection));
- }
-
- private IJavaScriptUnit[] getCompilationUnits(IStructuredSelection selection) {
- HashSet result= new HashSet();
- Object[] selected= selection.toArray();
- for (int i= 0; i < selected.length; i++) {
- try {
- if (selected[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) selected[i];
- if (elem.exists()) {
-
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- if (elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT) {
- result.add(elem.getParent());
- }
- break;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- result.add(elem);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- collectCompilationUnits((IPackageFragment) elem, result);
- break;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- collectCompilationUnits((IPackageFragmentRoot) elem, result);
- break;
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- IPackageFragmentRoot[] roots= ((IJavaScriptProject) elem).getPackageFragmentRoots();
- for (int k= 0; k < roots.length; k++) {
- collectCompilationUnits(roots[k], result);
- }
- break;
- }
- }
- } else if (selected[i] instanceof LogicalPackage) {
- IPackageFragment[] packageFragments= ((LogicalPackage)selected[i]).getFragments();
- for (int k= 0; k < packageFragments.length; k++) {
- IPackageFragment pack= packageFragments[k];
- if (pack.exists()) {
- collectCompilationUnits(pack, result);
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return (IJavaScriptUnit[]) result.toArray(new IJavaScriptUnit[result.size()]);
- }
-
- private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaScriptModelException {
- result.addAll(Arrays.asList(pack.getJavaScriptUnits()));
- }
-
- private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaScriptModelException {
- if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
- IJavaScriptElement[] children= root.getChildren();
- for (int i= 0; i < children.length; i++) {
- collectCompilationUnits((IPackageFragment) children[i], result);
- }
- }
- }
-
- private boolean isEnabled(IStructuredSelection selection) {
- Object[] selected= selection.toArray();
- for (int i= 0; i < selected.length; i++) {
- try {
- if (selected[i] instanceof IJavaScriptElement) {
- IJavaScriptElement elem= (IJavaScriptElement) selected[i];
- if (elem.exists()) {
- switch (elem.getElementType()) {
- case IJavaScriptElement.TYPE:
- return elem.getParent().getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT; // for browsing perspective
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return true;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT);
- return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
- return true;
- }
- }
- } else if (selected[i] instanceof LogicalPackage) {
- return true;
- }
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- IJavaScriptUnit[] cus= getCompilationUnits(selection);
- if (cus.length == 0) {
- MessageDialog.openInformation(getShell(), ActionMessages.FormatAllAction_EmptySelection_title, ActionMessages.FormatAllAction_EmptySelection_description);
- return;
- }
- try {
- if (cus.length == 1) {
- JavaScriptUI.openInEditor(cus[0]);
- } else {
- int returnCode= OptionalMessageDialog.open("FormatAll", //$NON-NLS-1$
- getShell(),
- ActionMessages.FormatAllAction_noundo_title,
- null,
- ActionMessages.FormatAllAction_noundo_message,
- MessageDialog.WARNING,
- new String[] {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL},
- 0);
- if (returnCode != OptionalMessageDialog.NOT_SHOWN && returnCode != Window.OK )
- return;
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.FormatAllAction_error_title, ActionMessages.FormatAllAction_error_message);
- }
- runOnMultiple(cus);
- }
-
- private IResource[] getResources(IJavaScriptUnit[] cus) {
- IResource[] res= new IResource[cus.length];
- for (int i= 0; i < res.length; i++) {
- res[i]= cus[i].getResource();
- }
- return res;
- }
-
- /**
- * Perform format all on the given compilation units.
- * @param cus The compilation units to format.
- */
- public void runOnMultiple(final IJavaScriptUnit[] cus) {
- try {
- final MultiStatus status= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, ActionMessages.FormatAllAction_status_description, null);
-
- IStatus valEditStatus= Resources.makeCommittable(getResources(cus), getShell());
- if (valEditStatus.matches(IStatus.CANCEL)) {
- return;
- }
- status.merge(valEditStatus);
- if (!status.matches(IStatus.ERROR)) {
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) {
- doRunOnMultiple(cus, status, monitor);
- }
- })); // workspace lock
- }
- if (!status.isOK()) {
- String title= ActionMessages.FormatAllAction_multi_status_title;
- ErrorDialog.openError(getShell(), title, null, status);
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.FormatAllAction_error_title, ActionMessages.FormatAllAction_error_message);
- } catch (InterruptedException e) {
- // Canceled by user
- }
- }
-
- private static Map getFomatterSettings(IJavaScriptProject project) {
- return new HashMap(project.getOptions(true));
- }
-
- private void doFormat(IDocument document, Map options) {
- final IFormattingContext context = new CommentFormattingContext();
- try {
- context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, options);
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
-
- final MultiPassContentFormatter formatter= new MultiPassContentFormatter(IJavaScriptPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE);
-
- formatter.setMasterStrategy(new JavaFormattingStrategy());
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_DOC);
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
-
- try {
- startSequentialRewriteMode(document);
- formatter.format(document, context);
- } finally {
- stopSequentialRewriteMode(document);
- }
- } finally {
- context.dispose();
- }
- }
-
- private void startSequentialRewriteMode(IDocument document) {
- if (document instanceof IDocumentExtension4) {
- IDocumentExtension4 extension= (IDocumentExtension4) document;
- fRewriteSession= extension.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
- } else if (document instanceof IDocumentExtension) {
- IDocumentExtension extension= (IDocumentExtension) document;
- extension.startSequentialRewrite(false);
- }
- }
-
- private void stopSequentialRewriteMode(IDocument document) {
- if (document instanceof IDocumentExtension4) {
- IDocumentExtension4 extension= (IDocumentExtension4) document;
- extension.stopRewriteSession(fRewriteSession);
- } else if (document instanceof IDocumentExtension) {
- IDocumentExtension extension= (IDocumentExtension)document;
- extension.stopSequentialRewrite();
- }
- }
-
- private void doRunOnMultiple(IJavaScriptUnit[] cus, MultiStatus status, IProgressMonitor monitor) throws OperationCanceledException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.setTaskName(ActionMessages.FormatAllAction_operation_description);
-
- monitor.beginTask("", cus.length * 4); //$NON-NLS-1$
- try {
- Map lastOptions= null;
- IJavaScriptProject lastProject= null;
-
- for (int i= 0; i < cus.length; i++) {
- IJavaScriptUnit cu= cus[i];
- IPath path= cu.getPath();
- if (lastProject == null || !lastProject.equals(cu.getJavaScriptProject())) {
- lastProject= cu.getJavaScriptProject();
- lastOptions= getFomatterSettings(lastProject);
- }
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (cu.getResource().getResourceAttributes().isReadOnly()) {
- String message= Messages.format(ActionMessages.FormatAllAction_read_only_skipped, path.toString());
- status.add(new Status(IStatus.WARNING, JavaScriptUI.ID_PLUGIN, IStatus.WARNING, message, null));
- continue;
- }
-
- ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
- try {
- try {
- manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
-
- monitor.subTask(path.makeRelative().toString());
- ITextFileBuffer fileBuffer= manager.getTextFileBuffer(path, LocationKind.IFILE);
-
- formatCompilationUnit(fileBuffer, lastOptions);
-
- if (fileBuffer.isDirty() && !fileBuffer.isShared()) {
- fileBuffer.commit(new SubProgressMonitor(monitor, 2), false);
- } else {
- monitor.worked(2);
- }
- } finally {
- manager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
- }
- } catch (CoreException e) {
- String message= Messages.format(ActionMessages.FormatAllAction_problem_accessing, new String[] { path.toString(), e.getLocalizedMessage() });
- status.add(new Status(IStatus.WARNING, JavaScriptUI.ID_PLUGIN, IStatus.WARNING, message, e));
- }
- }
- } finally {
- monitor.done();
- }
- }
-
- private void formatCompilationUnit(final ITextFileBuffer fileBuffer, final Map options) {
- if (fileBuffer.isShared()) {
- getShell().getDisplay().syncExec(new Runnable() {
- public void run() {
- doFormat(fileBuffer.getDocument(), options);
- }
- });
- } else {
- doFormat(fileBuffer.getDocument(), options); // run in context thread
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java
deleted file mode 100644
index 05d098bd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java
+++ /dev/null
@@ -1,535 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.commands.ActionHandler;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.AddBookmarkAction;
-import org.eclipse.ui.handlers.IHandlerActivation;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.AddTaskAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.AllCleanUpsAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.FindBrokenNLSKeysAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.JDTQuickMenuAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.MultiSortMembersAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the source and generate actions to a part's context
- * menu and installs handlers for the corresponding global menu actions.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class GenerateActionGroup extends ActionGroup {
-
- /**
- * Pop-up menu: id of the source sub menu (value <code>org.eclipse.wst.jsdt.ui.source.menu</code>).
- *
- *
- */
- public static final String MENU_ID= "org.eclipse.wst.jsdt.ui.source.menu"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the import group of the source sub menu (value
- * <code>importGroup</code>).
- *
- *
- */
- public static final String GROUP_IMPORT= "importGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the generate group of the source sub menu (value
- * <code>generateGroup</code>).
- *
- *
- */
- public static final String GROUP_GENERATE= "generateGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the code group of the source sub menu (value
- * <code>codeGroup</code>).
- *
- *
- */
- public static final String GROUP_CODE= "codeGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the externalize group of the source sub menu (value
- * <code>externalizeGroup</code>).
- *
- * TODO: Make API
- */
- private static final String GROUP_EXTERNALIZE= "externalizeGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the comment group of the source sub menu (value
- * <code>commentGroup</code>).
- *
- * TODO: Make API
- */
- private static final String GROUP_COMMENT= "commentGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the edit group of the source sub menu (value
- * <code>editGroup</code>).
- *
- * TODO: Make API
- */
- private static final String GROUP_EDIT= "editGroup"; //$NON-NLS-1$
-
- private CompilationUnitEditor fEditor;
- private IWorkbenchSite fSite;
- private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE;
- private List fRegisteredSelectionListeners;
-
-// private AddImportOnSelectionAction fAddImport;
- private OverrideMethodsAction fOverrideMethods;
-// private GenerateHashCodeEqualsAction fHashCodeEquals;
- private AddGetterSetterAction fAddGetterSetter;
- private AddDelegateMethodsAction fAddDelegateMethods;
-// private AddUnimplementedConstructorsAction fAddUnimplementedConstructors;
- private GenerateNewConstructorUsingFieldsAction fGenerateConstructorUsingFields;
- private AddJavaDocStubAction fAddJavaDocStub;
- private AddBookmarkAction fAddBookmark;
- private AddTaskAction fAddTaskAction;
- private ExternalizeStringsAction fExternalizeStrings;
- private AllCleanUpsAction fCleanUp;
- private FindBrokenNLSKeysAction fFindNLSProblems;
-
-// private OrganizeImportsAction fOrganizeImports;
- private MultiSortMembersAction fSortMembers;
- private FormatAllAction fFormatAll;
-
- private static final String QUICK_MENU_ID= "org.eclipse.wst.jsdt.ui.edit.text.java.source.quickMenu"; //$NON-NLS-1$
-
- private class SourceQuickAccessAction extends JDTQuickMenuAction {
- public SourceQuickAccessAction(CompilationUnitEditor editor) {
- super(editor, QUICK_MENU_ID);
- }
- protected void fillMenu(IMenuManager menu) {
- fillQuickMenu(menu);
- }
- }
-
- private JDTQuickMenuAction fQuickAccessAction;
- private IHandlerActivation fQuickAccessHandlerActivation;
- private IHandlerService fHandlerService;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- * @param groupName the group name to add the action to
- */
- public GenerateActionGroup(CompilationUnitEditor editor, String groupName) {
- fSite= editor.getSite();
- fEditor= editor;
- fGroupName= groupName;
-
-// fAddImport= new AddImportOnSelectionAction(editor);
-// fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT);
-// fAddImport.update();
-// editor.setAction("AddImport", fAddImport); //$NON-NLS-1$
-//
-// fOrganizeImports= new OrganizeImportsAction(editor);
-// fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS);
-// editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$
-
- fSortMembers= new MultiSortMembersAction(editor);
- fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS);
- editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$
-
-// IAction pastAction= editor.getAction(ITextEditorActionConstants.PASTE);//IWorkbenchActionDefinitionIds.PASTE);
-// fCopyQualifiedNameAction= new CopyQualifiedNameAction(editor, null, pastAction);
-// fCopyQualifiedNameAction.setActionDefinitionId(CopyQualifiedNameAction.JAVA_EDITOR_ACTION_DEFINITIONS_ID);
-// editor.setAction("CopyQualifiedName", fCopyQualifiedNameAction); //$NON-NLS-1$
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fOverrideMethods= new OverrideMethodsAction(editor);
- fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS);
- editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$
-
-
- fAddGetterSetter= new AddGetterSetterAction(editor);
- fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER);
- editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$
-
- fAddDelegateMethods= new AddDelegateMethodsAction(editor);
- fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
- editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
-
-// fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
-// fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
-// editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$
-
- fGenerateConstructorUsingFields= new GenerateNewConstructorUsingFieldsAction(editor);
- fGenerateConstructorUsingFields.setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS);
- editor.setAction("GenerateConstructorUsingFields", fGenerateConstructorUsingFields); //$NON-NLS-1$
- }
-
-// fHashCodeEquals= new GenerateHashCodeEqualsAction(editor);
-// fHashCodeEquals.setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_HASHCODE_EQUALS);
-// editor.setAction("GenerateHashCodeEquals", fHashCodeEquals); //$NON-NLS-1$
-
- fAddJavaDocStub= new AddJavaDocStubAction(editor);
- fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
- editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$
-
- fCleanUp= new AllCleanUpsAction(editor);
- fCleanUp.setActionDefinitionId(IJavaEditorActionDefinitionIds.CLEAN_UP);
- editor.setAction("CleanUp", fCleanUp); //$NON-NLS-1$
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fExternalizeStrings= new ExternalizeStringsAction(editor);
- fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS);
- editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$
- }
-
- installQuickAccessAction();
- }
-
- /**
- * Creates a new <code>GenerateActionGroup</code>. The group
- * requires that the selection provided by the page's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page that owns this action group
- */
- public GenerateActionGroup(Page page) {
- this(page.getSite());
- }
-
- /**
- * Creates a new <code>GenerateActionGroup</code>. The group
- * requires that the selection provided by the part's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public GenerateActionGroup(IViewPart part) {
- this(part.getSite());
- }
-
- private GenerateActionGroup(IWorkbenchSite site) {
- fSite= site;
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fOverrideMethods = new OverrideMethodsAction(site);
- fOverrideMethods
- .setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS);
- fAddGetterSetter = new AddGetterSetterAction(site);
- fAddGetterSetter
- .setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER);
- fAddDelegateMethods = new AddDelegateMethodsAction(site);
- fAddDelegateMethods
- .setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
- fGenerateConstructorUsingFields = new GenerateNewConstructorUsingFieldsAction(
- site);
- fGenerateConstructorUsingFields
- .setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS);
- }
- fAddJavaDocStub= new AddJavaDocStubAction(site);
- fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
-
- fAddBookmark= new AddBookmarkAction(site.getShell());
- fAddBookmark.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_BOOKMARK);
-
- // context-menu only -> no action definition ids
-
- fAddTaskAction= new AddTaskAction(site);
- fAddTaskAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_TASK);
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fExternalizeStrings = new ExternalizeStringsAction(site);
- fExternalizeStrings
- .setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS);
- fFindNLSProblems = new FindBrokenNLSKeysAction(site);
- fFindNLSProblems
- .setActionDefinitionId(FindBrokenNLSKeysAction.FIND_BROKEN_NLS_KEYS_ACTION_ID);
- }
- fSortMembers= new MultiSortMembersAction(site);
- fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS);
-
- fFormatAll= new FormatAllAction(site);
- fFormatAll.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
-
- fCleanUp= new AllCleanUpsAction(site);
- fCleanUp.setActionDefinitionId(IJavaEditorActionDefinitionIds.CLEAN_UP);
-
-
- fAddJavaDocStub.update(selection);
- if (IUIConstants.SUPPORT_REFACTORING) {
- fOverrideMethods.update(selection);
- fAddGetterSetter.update(selection);
- fAddDelegateMethods.update(selection);
- // fAddUnimplementedConstructors.update(selection);
- fGenerateConstructorUsingFields.update(selection);
- // fHashCodeEquals.update(selection);
- fExternalizeStrings.update(selection);
- fFindNLSProblems.update(selection);
- }
- fCleanUp.update(selection);
- fAddTaskAction.update(selection);
-// fOrganizeImports.update(selection);
- fSortMembers.update(selection);
- fFormatAll.update(selection);
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection ss= (IStructuredSelection)selection;
- fAddBookmark.selectionChanged(ss);
- } else {
- fAddBookmark.setEnabled(false);
- }
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- registerSelectionListener(provider, fOverrideMethods);
- registerSelectionListener(provider, fAddGetterSetter);
- registerSelectionListener(provider, fAddDelegateMethods);
- // registerSelectionListener(provider, fAddUnimplementedConstructors);
- registerSelectionListener(provider, fGenerateConstructorUsingFields);
- registerSelectionListener(provider, fExternalizeStrings);
- registerSelectionListener(provider, fFindNLSProblems);
- }
- // registerSelectionListener(provider, fHashCodeEquals);
- registerSelectionListener(provider, fAddJavaDocStub);
- registerSelectionListener(provider, fAddBookmark);
-// registerSelectionListener(provider, fOrganizeImports);
- registerSelectionListener(provider, fFormatAll);
- registerSelectionListener(provider, fSortMembers);
- registerSelectionListener(provider, fAddTaskAction);
- registerSelectionListener(provider, fCleanUp);
-
- installQuickAccessAction();
- }
-
- private void installQuickAccessAction() {
- fHandlerService= (IHandlerService)fSite.getService(IHandlerService.class);
- if (fHandlerService != null) {
- fQuickAccessAction= new SourceQuickAccessAction(fEditor);
- fQuickAccessHandlerActivation= fHandlerService.activateHandler(fQuickAccessAction.getActionDefinitionId(), new ActionHandler(fQuickAccessAction));
- }
- }
-
- private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) {
- if (fRegisteredSelectionListeners == null)
- fRegisteredSelectionListeners= new ArrayList(20);
- provider.addSelectionChangedListener(listener);
- fRegisteredSelectionListeners.add(listener);
- }
-
- /*
- * The state of the editor owning this action group has changed.
- * This method does nothing if the group's owner isn't an
- * editor.
- */
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void editorStateChanged() {
- Assert.isTrue(isEditorOwner());
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- setGlobalActionHandlers(actionBar);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- String menuText= ActionMessages.SourceMenu_label;
- if (fQuickAccessAction != null) {
- menuText= fQuickAccessAction.addShortcut(menuText);
- }
- IMenuManager subMenu= new MenuManager(menuText, MENU_ID);
- int added= 0;
- if (isEditorOwner()) {
- added= fillEditorSubMenu(subMenu);
- } else {
- added= fillViewSubMenu(subMenu);
- }
- if (added > 0)
- menu.appendToGroup(fGroupName, subMenu);
- }
-
- private void fillQuickMenu(IMenuManager menu) {
- if (isEditorOwner()) {
- fillEditorSubMenu(menu);
- } else {
- fillViewSubMenu(menu);
- }
- }
-
- private int fillEditorSubMenu(IMenuManager source) {
- int added= 0;
- source.add(new Separator(GROUP_COMMENT));
- added+= addEditorAction(source, "ToggleComment"); //$NON-NLS-1$
- added+= addEditorAction(source, "AddBlockComment"); //$NON-NLS-1$
- added+= addEditorAction(source, "RemoveBlockComment"); //$NON-NLS-1$
- added+= addAction(source, fAddJavaDocStub);
- source.add(new Separator(GROUP_EDIT));
- added+= addEditorAction(source, "Indent"); //$NON-NLS-1$
- added+= addEditorAction(source, "Format"); //$NON-NLS-1$
- source.add(new Separator(GROUP_IMPORT));
-// added+= addAction(source, fAddImport);
-// added+= addAction(source, fOrganizeImports);
- added+= addAction(source, fSortMembers);
- added+= addAction(source, fCleanUp);
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- source.add(new Separator(GROUP_GENERATE));
- added += addAction(source, fOverrideMethods);
- added += addAction(source, fAddGetterSetter);
- added += addAction(source, fAddDelegateMethods);
- // added+= addAction(source, fHashCodeEquals);
- added += addAction(source, fGenerateConstructorUsingFields);
- }
- // added+= addAction(source, fAddUnimplementedConstructors);
- source.add(new Separator(GROUP_CODE));
- source.add(new Separator(GROUP_EXTERNALIZE));
- if (IUIConstants.SUPPORT_REFACTORING)
- added+= addAction(source, fExternalizeStrings);
- return added;
- }
-
- private int fillViewSubMenu(IMenuManager source) {
- int added= 0;
- source.add(new Separator(GROUP_COMMENT));
- added+= addAction(source, fAddJavaDocStub);
- source.add(new Separator(GROUP_EDIT));
- added+= addAction(source, fFormatAll);
- source.add(new Separator(GROUP_IMPORT));
-// added+= addAction(source, fAddImport);
-// added+= addAction(source, fOrganizeImports);
- added+= addAction(source, fSortMembers);
- added+= addAction(source, fCleanUp);
- if (IUIConstants.SUPPORT_REFACTORING) {
- source.add(new Separator(GROUP_GENERATE));
- added+= addAction(source, fOverrideMethods);
- added+= addAction(source, fAddGetterSetter);
- added+= addAction(source, fAddDelegateMethods);
- // added+= addAction(source, fHashCodeEquals);
- added+= addAction(source, fGenerateConstructorUsingFields);
- // added+= addAction(source, fAddUnimplementedConstructors);
- }
- source.add(new Separator(GROUP_CODE));
- source.add(new Separator(GROUP_EXTERNALIZE));
- if (IUIConstants.SUPPORT_REFACTORING) {
- added+= addAction(source, fExternalizeStrings);
- added+= addAction(source, fFindNLSProblems);
- }
- return added;
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void dispose() {
- if (fRegisteredSelectionListeners != null) {
- ISelectionProvider provider= fSite.getSelectionProvider();
- for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) {
- ISelectionChangedListener listener= (ISelectionChangedListener) iter.next();
- provider.removeSelectionChangedListener(listener);
- }
- }
- if (fQuickAccessHandlerActivation != null && fHandlerService != null) {
- fHandlerService.deactivateHandler(fQuickAccessHandlerActivation);
- }
- fEditor= null;
- fCleanUp.dispose();
- super.dispose();
- }
-
- private void setGlobalActionHandlers(IActionBars actionBar) {
-// actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport);
- actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods);
- actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter);
- actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods);
-// actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors);
- actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_CONSTRUCTOR_USING_FIELDS, fGenerateConstructorUsingFields);
-// actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_HASHCODE_EQUALS, fHashCodeEquals);
- actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub);
- actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings);
- actionBar.setGlobalActionHandler(JdtActionConstants.CLEAN_UP, fCleanUp);
- actionBar.setGlobalActionHandler(FindBrokenNLSKeysAction.ACTION_HANDLER_ID, fFindNLSProblems);
-// actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports);
- actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers);
- if (!isEditorOwner()) {
- // editor provides its own implementation of these actions.
- actionBar.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), fAddBookmark);
- actionBar.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), fAddTaskAction);
- actionBar.setGlobalActionHandler(JdtActionConstants.FORMAT, fFormatAll);
- }
- }
-
- private int addAction(IMenuManager menu, IAction action) {
- if (action != null && action.isEnabled()) {
- menu.add(action);
- return 1;
- }
- return 0;
- }
-
- private int addEditorAction(IMenuManager menu, String actionID) {
- if (fEditor == null)
- return 0;
- IAction action= fEditor.getAction(actionID);
- if (action == null)
- return 0;
- if (action instanceof IUpdate)
- ((IUpdate)action).update();
- if (action.isEnabled()) {
- menu.add(action);
- return 1;
- }
- return 0;
- }
-
- private boolean isEditorOwner() {
- return fEditor != null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateNewConstructorUsingFieldsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateNewConstructorUsingFieldsAction.java
deleted file mode 100644
index 13c3e778..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateNewConstructorUsingFieldsAction.java
+++ /dev/null
@@ -1,387 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.IVariableBinding;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddCustomConstructorOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility2;
-import org.eclipse.wst.jsdt.internal.corext.dom.Bindings;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.GenerateConstructorUsingFieldsContentProvider;
-import org.eclipse.wst.jsdt.internal.ui.actions.GenerateConstructorUsingFieldsSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.actions.GenerateConstructorUsingFieldsValidator;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Creates constructors for a type based on existing fields.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. Opens a dialog with a list
- * fields from which a constructor will be generated. User is able to check or uncheck
- * items before constructors are generated. The result is unsaved, so the user can decide
- * if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements of type
- * <code>IType</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class GenerateNewConstructorUsingFieldsAction extends SelectionDispatchAction {
-
- private CompilationUnitEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this
- * constructor.
- *
- * @param editor the compilation unit editor
- */
- public GenerateNewConstructorUsingFieldsAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(checkEnabledEditor());
- }
-
- /**
- * Creates a new <code>GenerateConstructorUsingFieldsAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public GenerateNewConstructorUsingFieldsAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.GenerateConstructorUsingFieldsAction_label);
- setDescription(ActionMessages.GenerateConstructorUsingFieldsAction_description);
- setToolTipText(ActionMessages.GenerateConstructorUsingFieldsAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CREATE_NEW_CONSTRUCTOR_ACTION);
- }
-
- private boolean canEnable(IStructuredSelection selection) throws JavaScriptModelException {
- if (getSelectedFields(selection) != null)
- return true;
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
- IType type= (IType) selection.getFirstElement();
- return type.getJavaScriptUnit() != null;
- }
-
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IJavaScriptUnit))
- return true;
-
- return false;
- }
-
- private boolean canRunOn(IField[] fields) throws JavaScriptModelException {
- if (fields != null && fields.length > 0) {
- return true;
- }
- return false;
- }
-
- private boolean checkEnabledEditor() {
- return fEditor != null && SelectionConverter.canOperateOn(fEditor);
- }
-
- /*
- * Returns fields in the selection or <code>null</code> if the selection is empty or
- * not valid.
- */
- private IField[] getSelectedFields(IStructuredSelection selection) {
- List elements= selection.toList();
- if (elements.size() > 0) {
- IField[] fields= new IField[elements.size()];
- IJavaScriptUnit unit= null;
- for (int index= 0; index < elements.size(); index++) {
- if (elements.get(index) instanceof IField) {
- IField field= (IField) elements.get(index);
- if (index == 0) {
- // remember the CU of the first element
- unit= field.getJavaScriptUnit();
- if (unit == null) {
- return null;
- }
- } else if (!unit.equals(field.getJavaScriptUnit())) {
- // all fields must be in the same CU
- return null;
- }
-
- final IType declaringType= field.getDeclaringType();
- if (declaringType==null)
- return null;
-
- fields[index]= field;
- } else {
- return null;
- }
- }
- return fields;
- }
- return null;
- }
-
- private IType getSelectedType(IStructuredSelection selection) throws JavaScriptModelException {
- Object[] elements= selection.toArray();
- if (elements.length == 1 && (elements[0] instanceof IType)) {
- IType type= (IType) elements[0];
- if (type.getJavaScriptUnit() != null) {
- return type;
- }
- } else if (elements[0] instanceof IJavaScriptUnit) {
- IJavaScriptUnit unit= (IJavaScriptUnit) elements[0];
- IType type= unit.findPrimaryType();
- if (type != null)
- return type;
- } else if (elements[0] instanceof IField) {
- return ((IField) elements[0]).getJavaScriptUnit().findPrimaryType();
- }
- return null;
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- try {
- IType selectionType= getSelectedType(selection);
- if (selectionType == null) {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_not_applicable);
- notifyResult(false);
- return;
- }
-
- IField[] selectedFields= getSelectedFields(selection);
-
- if (canRunOn(selectedFields)) {
- run(selectedFields[0].getDeclaringType(), selectedFields, false);
- return;
- }
- Object firstElement= selection.getFirstElement();
-
- if (firstElement instanceof IType) {
- run((IType) firstElement, new IField[0], false);
- } else if (firstElement instanceof IJavaScriptUnit) {
- run(((IJavaScriptUnit) firstElement).findPrimaryType(), new IField[0], false);
- }
- } catch (CoreException exception) {
- ExceptionHandler.handle(exception, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_actionfailed);
- }
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isProcessable(fEditor)) {
- notifyResult(false);
- return;
- }
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveForked(fEditor, true);
- if (elements.length == 1 && (elements[0] instanceof IField)) {
- IField field= (IField) elements[0];
- run(field.getDeclaringType(), new IField[] { field}, false);
- return;
- }
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element != null) {
- IType type= (IType) element.getAncestor(IJavaScriptElement.TYPE);
- if (type != null) {
- if (type.getFields().length > 0) {
- run(type, new IField[0], true);
- } else {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_typeContainsNoFields_message);
- }
- return;
- }
- }
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_not_applicable);
- } catch (CoreException exception) {
- ExceptionHandler.handle(exception, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_actionfailed);
- } catch (InvocationTargetException exception) {
- ExceptionHandler.handle(exception, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_actionfailed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- // ---- Helpers -------------------------------------------------------------------
-
- void run(IType type, IField[] selected, boolean activated) throws CoreException {
- if (!ElementValidator.check(type, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, activated)) {
- notifyResult(false);
- return;
- }
- if (!ActionUtil.isEditable(fEditor, getShell(), type)) {
- notifyResult(false);
- return;
- }
- if (type.getJavaScriptUnit() == null) {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateNewConstructorUsingFieldsAction_error_not_a_source_file);
- notifyResult(false);
- return;
-
- }
-
- IField[] candidates= type.getFields();
- ArrayList fields= new ArrayList();
- for (int index= 0; index < candidates.length; index++) {
- boolean isStatic= Flags.isStatic(candidates[index].getFlags());
- if (!isStatic) {
- fields.add(candidates[index]);
- }
- }
- if (fields.isEmpty()) {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_typeContainsNoFields_message);
- notifyResult(false);
- return;
- }
- final GenerateConstructorUsingFieldsContentProvider provider= new GenerateConstructorUsingFieldsContentProvider(type, fields, Arrays.asList(selected));
- IFunctionBinding[] bindings= null;
- final ITypeBinding provided= provider.getType();
- if (provided.isAnonymous()) {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_anonymous_class);
- notifyResult(false);
- return;
- }
-
- bindings= StubUtility2.getVisibleConstructors(provided, false, true);
- if (bindings.length == 0) {
- MessageDialog.openInformation(getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_nothing_found);
- notifyResult(false);
- return;
- }
-
- GenerateConstructorUsingFieldsSelectionDialog dialog= new GenerateConstructorUsingFieldsSelectionDialog(getShell(), new BindingLabelProvider(), provider, fEditor, type, bindings);
- dialog.setCommentString(ActionMessages.SourceActionDialog_createConstructorComment);
- dialog.setTitle(ActionMessages.GenerateConstructorUsingFieldsAction_dialog_title);
- dialog.setInitialSelections(provider.getInitiallySelectedElements());
- dialog.setContainerMode(true);
- dialog.setSize(60, 18);
- dialog.setInput(new Object());
- dialog.setMessage(ActionMessages.GenerateConstructorUsingFieldsAction_dialog_label);
- dialog.setValidator(new GenerateConstructorUsingFieldsValidator(dialog, provided, fields.size()));
-
- final int dialogResult= dialog.open();
- if (dialogResult == Window.OK) {
- Object[] elements= dialog.getResult();
- if (elements == null) {
- notifyResult(false);
- return;
- }
- ArrayList result= new ArrayList(elements.length);
- for (int index= 0; index < elements.length; index++) {
- if (elements[index] instanceof IVariableBinding)
- result.add(elements[index]);
- }
- IVariableBinding[] variables= new IVariableBinding[result.size()];
- result.toArray(variables);
- IEditorPart editor= JavaScriptUI.openInEditor(type.getJavaScriptUnit());
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject());
- settings.createComments= dialog.getGenerateComment();
- IFunctionBinding constructor= dialog.getSuperConstructorChoice();
- IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
- if (target != null)
- target.beginCompoundChange();
- try {
- AddCustomConstructorOperation operation= new AddCustomConstructorOperation(type, dialog.getElementPosition(), provider.getCompilationUnit(), variables, constructor, settings, true, false);
- operation.setVisibility(dialog.getVisibilityModifier());
- if (constructor.getParameterTypes().length == 0)
- operation.setOmitSuper(dialog.isOmitSuper());
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null)
- context= new BusyIndicatorRunnableContext();
- PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
- } catch (InvocationTargetException exception) {
- ExceptionHandler.handle(exception, getShell(), ActionMessages.GenerateConstructorUsingFieldsAction_error_title, ActionMessages.GenerateConstructorUsingFieldsAction_error_actionfailed);
- } catch (InterruptedException exception) {
- // Do nothing. Operation has been canceled by user.
- } finally {
- if (target != null) {
- target.endCompoundChange();
- }
- }
- }
- notifyResult(dialogResult == Window.OK);
- }
-
- private IFunctionBinding getObjectConstructor(JavaScriptUnit compilationUnit) {
- final ITypeBinding binding= compilationUnit.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
- return Bindings.findMethodInType(binding, "Object", new ITypeBinding[0]); //$NON-NLS-1$
- }
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(canEnable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);
- }
- }
-
- // ---- JavaScript Editor --------------------------------------------------------------
-
- /*
- * (non-Javadoc) Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java
deleted file mode 100644
index 5b60dbab..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java
+++ /dev/null
@@ -1,635 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-
-/**
- * Defines the definition IDs for the JavaScript editor actions.
- *
- * <p>
- * This interface is not intended to be implemented or extended.
- * </p>.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface IJavaEditorActionDefinitionIds extends ITextEditorActionDefinitionIds {
-
- // edit
-
- /**
- * Action definition ID of the edit -> smart typing action
- * (value <code>"org.eclipse.wst.jsdt.smartTyping.toggle"</code>).
- *
- *
- */
- public static final String TOGGLE_SMART_TYPING= "org.eclipse.wst.jsdt.smartTyping.toggle"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> go to matching bracket action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.goto.matching.bracket"</code>).
- *
- *
- */
- public static final String GOTO_MATCHING_BRACKET= "org.eclipse.wst.jsdt.ui.edit.text.java.goto.matching.bracket"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> go to next member action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.goto.next.member"</code>).
- *
- *
- */
- public static final String GOTO_NEXT_MEMBER= "org.eclipse.wst.jsdt.ui.edit.text.java.goto.next.member"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> go to previous member action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.goto.previous.member"</code>).
- *
- *
- */
- public static final String GOTO_PREVIOUS_MEMBER= "org.eclipse.wst.jsdt.ui.edit.text.java.goto.previous.member"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> select enclosing action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.select.enclosing"</code>).
- */
- public static final String SELECT_ENCLOSING= "org.eclipse.wst.jsdt.ui.edit.text.java.select.enclosing"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> select next action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.select.next"</code>).
- */
- public static final String SELECT_NEXT= "org.eclipse.wst.jsdt.ui.edit.text.java.select.next"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> select previous action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.select.previous"</code>).
- */
- public static final String SELECT_PREVIOUS= "org.eclipse.wst.jsdt.ui.edit.text.java.select.previous"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the edit -> select restore last action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.select.last"</code>).
- */
- public static final String SELECT_LAST= "org.eclipse.wst.jsdt.ui.edit.text.java.select.last"; //$NON-NLS-1$
-
-
-
- /**
- * Action definition ID of the edit -> content assist complete prefix action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.complete.prefix"</code>).
- *
- */
- public static final String CONTENT_ASSIST_COMPLETE_PREFIX= "org.eclipse.wst.jsdt.ui.edit.text.java.complete.prefix"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> Show Outline action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.show.outline"</code>).
- *
- *
- */
- public static final String SHOW_OUTLINE= "org.eclipse.wst.jsdt.ui.edit.text.java.show.outline"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> Show Hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.open.hierarchy"</code>).
- *
- *
- */
- public static final String OPEN_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.open.hierarchy"; //$NON-NLS-1$
-
-
- /**
- * Action definition ID of the Navigate -> Open Structure action
- * (value <code>"org.eclipse.wst.jsdt.ui.navigate.java.open.structure"</code>).
- *
- *
- */
- public static final String OPEN_STRUCTURE= "org.eclipse.wst.jsdt.ui.navigate.java.open.structure"; //$NON-NLS-1$
-
- // source
-
- /**
- * Action definition ID of the source -> comment action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.comment"</code>).
- */
- public static final String COMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.comment"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> uncomment action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.uncomment"</code>).
- */
- public static final String UNCOMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.uncomment"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> toggle comment action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.toggle.comment"</code>).
- *
- */
- public static final String TOGGLE_COMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.toggle.comment"; //$NON-NLS-1$
-
-
- /**
- * Action definition ID of the source -> add block comment action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.add.block.comment"</code>).
- *
- */
- public static final String ADD_BLOCK_COMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.add.block.comment"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> remove block comment action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.remove.block.comment"</code>).
- *
- */
- public static final String REMOVE_BLOCK_COMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.remove.block.comment"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> indent action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.indent"</code>).
- */
- public static final String INDENT= "org.eclipse.wst.jsdt.ui.edit.text.java.indent"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> format action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.format"</code>).
- */
- public static final String FORMAT= "org.eclipse.wst.jsdt.ui.edit.text.java.format"; //$NON-NLS-1$
-
- /**
- * Action definition id of the JavaScript quick format action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.quick.format"</code>).
- *
- */
- public static final String QUICK_FORMAT= "org.eclipse.wst.jsdt.ui.edit.text.java.quick.format"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> add import action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.add.import"</code>).
- */
- public static final String ADD_IMPORT= "org.eclipse.wst.jsdt.ui.edit.text.java.add.import"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> organize imports action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.organize.imports"</code>).
- */
- public static final String ORGANIZE_IMPORTS= "org.eclipse.wst.jsdt.ui.edit.text.java.organize.imports"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> sort order action (value
- * <code>"org.eclipse.wst.jsdt.ui.edit.text.java.sort.members"</code>).
- *
- */
- public static final String SORT_MEMBERS= "org.eclipse.wst.jsdt.ui.edit.text.java.sort.members"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> add javadoc comment action (value
- * <code>"org.eclipse.wst.jsdt.ui.edit.text.java.add.javadoc.comment"</code>).
- *
- */
- public static final String ADD_JAVADOC_COMMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.add.javadoc.comment"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> surround with try/catch action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.surround.with.try.catch"</code>).
- */
- public static final String SURROUND_WITH_TRY_CATCH= "org.eclipse.wst.jsdt.ui.edit.text.java.surround.with.try.catch"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> override methods action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.override.methods"</code>).
- */
- public static final String OVERRIDE_METHODS= "org.eclipse.wst.jsdt.ui.edit.text.java.override.methods"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> add unimplemented constructors action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.add.unimplemented.constructors"</code>).
- */
- public static final String ADD_UNIMPLEMENTED_CONTRUCTORS= "org.eclipse.wst.jsdt.ui.edit.text.java.add.unimplemented.constructors"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source ->generate constructor using fields action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.generate.constructor.using.fields"</code>).
- */
- public static final String GENERATE_CONSTRUCTOR_USING_FIELDS= "org.eclipse.wst.jsdt.ui.edit.text.java.generate.constructor.using.fields"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source ->generate hashcode() and equals() action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.generate.hashcode.equals"</code>).
- *
- */
- public static final String GENERATE_HASHCODE_EQUALS= "org.eclipse.wst.jsdt.ui.edit.text.java.generate.hashcode.equals"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> generate setter/getter action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.create.getter.setter"</code>).
- */
- public static final String CREATE_GETTER_SETTER= "org.eclipse.wst.jsdt.ui.edit.text.java.create.getter.setter"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the source -> generate delegates action (value
- * <code>"org.eclipse.wst.jsdt.ui.edit.text.java.create.delegate.methods"</code>).
- *
- */
- public static final String CREATE_DELEGATE_METHODS= "org.eclipse.wst.jsdt.ui.edit.text.java.create.delegate.methods"; //$NON-NLS-1$
-
-
- /**
- * Action definition ID of the source -> externalize strings action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.externalize.strings"</code>).
- */
- public static final String EXTERNALIZE_STRINGS= "org.eclipse.wst.jsdt.ui.edit.text.java.externalize.strings"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> pull up action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.pull.up"</code>).
- */
- public static final String PULL_UP= "org.eclipse.wst.jsdt.ui.edit.text.java.pull.up"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> push down action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.push.down"</code>).
- *
- *
- */
- public static final String PUSH_DOWN= "org.eclipse.wst.jsdt.ui.edit.text.java.push.down"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> rename element action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.rename.element"</code>).
- */
- public static final String RENAME_ELEMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.rename.element"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> modify method parameters action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.modify.method.parameters"</code>).
- */
- public static final String MODIFY_METHOD_PARAMETERS= "org.eclipse.wst.jsdt.ui.edit.text.java.modify.method.parameters"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> move element action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.move.element"</code>).
- */
- public static final String MOVE_ELEMENT= "org.eclipse.wst.jsdt.ui.edit.text.java.move.element"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> extract local variable action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.extract.local.variable"</code>).
- */
- public static final String EXTRACT_LOCAL_VARIABLE= "org.eclipse.wst.jsdt.ui.edit.text.java.extract.local.variable"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> extract constant action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.extract.constant"</code>).
- *
- *
- */
- public static final String EXTRACT_CONSTANT= "org.eclipse.wst.jsdt.ui.edit.text.java.extract.constant"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> introduce parameter action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.introduce.parameter"</code>).
- *
- *
- */
- public static final String INTRODUCE_PARAMETER= "org.eclipse.wst.jsdt.ui.edit.text.java.introduce.parameter"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> introduce factory action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.introduce.factory"</code>).
- *
- *
- */
- public static final String INTRODUCE_FACTORY= "org.eclipse.wst.jsdt.ui.edit.text.java.introduce.factory"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> self encapsulate field action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.self.encapsulate.field"</code>).
- */
- public static final String SELF_ENCAPSULATE_FIELD= "org.eclipse.wst.jsdt.ui.edit.text.java.self.encapsulate.field"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> extract method action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.extract.method"</code>).
- */
- public static final String EXTRACT_METHOD= "org.eclipse.wst.jsdt.ui.edit.text.java.extract.method"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> inline action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.inline"</code>).
- *
- *
- */
- public static final String INLINE= "org.eclipse.wst.jsdt.ui.edit.text.java.inline"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> replace invocations action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.replace.invocations"</code>).
- *
- *
- */
- public static final String REPLACE_INVOCATIONS= "org.eclipse.wst.jsdt.ui.edit.text.java.replace.invocations"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> introduce indirection action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.create.indirection"</code>).
- *
- *
- */
- public static final String INTRODUCE_INDIRECTION= "org.eclipse.wst.jsdt.ui.edit.text.java.introduce.indirection"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> extract interface action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.extract.interface"</code>).
- *
- *
- */
- public static final String EXTRACT_INTERFACE= "org.eclipse.wst.jsdt.ui.edit.text.java.extract.interface"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> change type action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.change.type"</code>).
- *
- *
- */
- public static final String CHANGE_TYPE= "org.eclipse.wst.jsdt.ui.edit.text.java.change.type"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> move inner type to top level action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.move.inner.to.top.level"</code>).
- *
- *
- */
- public static final String MOVE_INNER_TO_TOP= "org.eclipse.wst.jsdt.ui.edit.text.java.move.inner.to.top.level"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> use supertype action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.use.supertype"</code>).
- *
- *
- */
- public static final String USE_SUPERTYPE= "org.eclipse.wst.jsdt.ui.edit.text.java.use.supertype"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> infer generic type arguments action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.infer.type.arguments"</code>).
- *
- *
- */
- public static final String INFER_TYPE_ARGUMENTS_ACTION= "org.eclipse.wst.jsdt.ui.edit.text.java.infer.type.arguments"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> promote local variable action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.promote.local.variable"</code>).
- *
- *
- */
- public static final String PROMOTE_LOCAL_VARIABLE= "org.eclipse.wst.jsdt.ui.edit.text.java.promote.local.variable"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the refactor -> convert anonymous to nested action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.convert.anonymous.to.nested"</code>).
- *
- *
- */
- public static final String CONVERT_ANONYMOUS_TO_NESTED= "org.eclipse.wst.jsdt.ui.edit.text.java.convert.anonymous.to.nested"; //$NON-NLS-1$
-
- // navigate
-
- /**
- * Action definition ID of the navigate -> open action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.open.editor"</code>).
- */
- public static final String OPEN_EDITOR= "org.eclipse.wst.jsdt.ui.edit.text.java.open.editor"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> open super implementation action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.open.super.implementation"</code>).
- */
- public static final String OPEN_SUPER_IMPLEMENTATION= "org.eclipse.wst.jsdt.ui.edit.text.java.open.super.implementation"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> open external javadoc action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.open.external.javadoc"</code>).
- */
- public static final String OPEN_EXTERNAL_JAVADOC= "org.eclipse.wst.jsdt.ui.edit.text.java.open.external.javadoc"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> open type hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.org.eclipse.wst.jsdt.ui.edit.text.java.open.type.hierarchy"</code>).
- */
- public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.open.type.hierarchy"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> open call hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.org.eclipse.wst.jsdt.ui.edit.text.java.open.call.hierarchy"</code>).
- *
- */
- public static final String OPEN_CALL_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.open.call.hierarchy"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> show in package explorer action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.show.in.package.view"</code>).
- */
- public static final String SHOW_IN_PACKAGE_VIEW= "org.eclipse.wst.jsdt.ui.edit.text.java.show.in.package.view"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the navigate -> show in navigator action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.show.in.navigator.view"</code>).
- */
- public static final String SHOW_IN_NAVIGATOR_VIEW= "org.eclipse.wst.jsdt.ui.edit.text.java.show.in.navigator.view"; //$NON-NLS-1$
-
- // search
-
- /**
- * Action definition ID of the search -> references in workspace action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.workspace"</code>).
- */
- public static final String SEARCH_REFERENCES_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.workspace"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> references in project action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.project"</code>).
- */
- public static final String SEARCH_REFERENCES_IN_PROJECT= "org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.project"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> references in hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.hierarchy"</code>).
- */
- public static final String SEARCH_REFERENCES_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.hierarchy"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> references in working set action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.working.set"</code>).
- */
- public static final String SEARCH_REFERENCES_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.edit.text.java.search.references.in.working.set"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> read access in workspace action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.workspace"</code>).
- */
- public static final String SEARCH_READ_ACCESS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.workspace"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> read access in project action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.project"</code>).
- */
- public static final String SEARCH_READ_ACCESS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.project"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> read access in hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.hierarchy"</code>).
- */
- public static final String SEARCH_READ_ACCESS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.hierarchy"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> read access in working set action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.working.set"</code>).
- */
- public static final String SEARCH_READ_ACCESS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.edit.text.java.search.read.access.in.working.set"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> write access in workspace action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.workspace"</code>).
- */
- public static final String SEARCH_WRITE_ACCESS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.workspace"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> write access in project action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.project"</code>).
- */
- public static final String SEARCH_WRITE_ACCESS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.project"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> write access in hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.hierarchy"</code>).
- */
- public static final String SEARCH_WRITE_ACCESS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.hierarchy"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> write access in working set action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.working.set"</code>).
- */
- public static final String SEARCH_WRITE_ACCESS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.edit.text.java.search.write.access.in.working.set"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> declarations in workspace action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.workspace"</code>).
- */
- public static final String SEARCH_DECLARATIONS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.workspace"; //$NON-NLS-1$
- /**
- * Action definition ID of the search -> declarations in project action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.project"</code>).
- */
- public static final String SEARCH_DECLARATIONS_IN_PROJECTS= "org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.project"; //$NON-NLS-1$
- /**
- * Action definition ID of the search -> declarations in hierarchy action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.hierarchy"</code>).
- */
- public static final String SEARCH_DECLARATIONS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.hierarchy"; //$NON-NLS-1$
- /**
- * Action definition ID of the search -> declarations in working set action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.working.set"</code>).
- */
- public static final String SEARCH_DECLARATIONS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.edit.text.java.search.declarations.in.working.set"; //$NON-NLS-1$
- /**
- * Action definition ID of the search -> implementors in workspace action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.workspace"</code>).
- */
- public static final String SEARCH_IMPLEMENTORS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.workspace"; //$NON-NLS-1$
- /**
- * Action definition ID of the search -> implementors in working set action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.working.set"</code>).
- */
- public static final String SEARCH_IMPLEMENTORS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.working.set"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> implementors in project action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.project"</code>).
- *
- */
- public static final String SEARCH_IMPLEMENTORS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.edit.text.java.search.implementors.in.project"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> occurrences in file quick menu action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.occurrences.in.file.quickMenu"</code>).
- *
- */
- public static final String SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU= "org.eclipse.wst.jsdt.ui.edit.text.java.search.occurrences.in.file.quickMenu"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> occurrences in file > elements action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.occurrences.in.file"</code>).
- *
- */
- public static final String SEARCH_OCCURRENCES_IN_FILE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.occurrences.in.file"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> occurrences in file > exceptions action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.exception.occurrences"</code>).
- *
- */
- public static final String SEARCH_EXCEPTION_OCCURRENCES_IN_FILE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.exception.occurrences"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the search -> occurrences in file > implements action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.search.implement.occurrences"</code>).
- *
- */
- public static final String SEARCH_IMPLEMENT_OCCURRENCES_IN_FILE= "org.eclipse.wst.jsdt.ui.edit.text.java.search.implement.occurrences"; //$NON-NLS-1$
-
- // miscellaneous
-
- /**
- * Action definition ID of the toggle text hover tool bar button action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.java.toggle.text.hover"</code>).
- */
- public static final String TOGGLE_TEXT_HOVER= "org.eclipse.wst.jsdt.ui.edit.text.java.toggle.text.hover"; //$NON-NLS-1$
-
- /**
- * Action definition ID of the remove occurrence annotations action
- * (value <code>"org.eclipse.wst.jsdt.ui.edit.text.remove.occurrence.annotations"</code>).
- *
- */
- public static final String REMOVE_OCCURRENCE_ANNOTATIONS= "org.eclipse.wst.jsdt.ui.edit.text.remove.occurrence.annotations"; //$NON-NLS-1$
-
- /**
- * Action definition id of toggle mark occurrences action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.toggleMarkOccurrences"</code>).
- *
- */
- public static final String TOGGLE_MARK_OCCURRENCES= "org.eclipse.wst.jsdt.ui.edit.text.java.toggleMarkOccurrences"; //$NON-NLS-1$
-
- /**
- * Action definition id of the collapse members action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.folding.collapseMembers"</code>).
- *
- */
- public static final String FOLDING_COLLAPSE_MEMBERS= "org.eclipse.wst.jsdt.ui.edit.text.java.folding.collapseMembers"; //$NON-NLS-1$
-
- /**
- * Action definition id of the collapse comments action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.folding.collapseComments"</code>).
- *
- */
- public static final String FOLDING_COLLAPSE_COMMENTS= "org.eclipse.wst.jsdt.ui.edit.text.java.folding.collapseComments"; //$NON-NLS-1$
-
- /**
- * Action definition id of the code clean up action
- * (value: <code>"org.eclipse.wst.jsdt.ui.edit.text.java.clean.up"</code>).
- *
- */
- public static final String CLEAN_UP= "org.eclipse.wst.jsdt.ui.edit.text.java.clean.up"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java
deleted file mode 100644
index 5a09fb77..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the search for implementors actions to a
- * context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ImplementorsSearchGroup extends ActionGroup {
-
- private static final String MENU_TEXT= SearchMessages.group_implementors;
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindImplementorsAction fFindImplementorsAction;
- private FindImplementorsInProjectAction fFindImplementorsInProjectAction;
- private FindImplementorsInWorkingSetAction fFindImplementorsInWorkingSetAction;
-
- /**
- * Creates a new <code>ImplementorsSearchGroup</code>. The group
- * requires that the selection provided by the site's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public ImplementorsSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fFindImplementorsAction= new FindImplementorsAction(site);
- fFindImplementorsAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_WORKSPACE);
-
- fFindImplementorsInProjectAction= new FindImplementorsInProjectAction(site);
- fFindImplementorsInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_PROJECT);
-
- fFindImplementorsInWorkingSetAction= new FindImplementorsInWorkingSetAction(site);
- fFindImplementorsInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_WORKING_SET);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fFindImplementorsAction, provider, selection);
- registerAction(fFindImplementorsInProjectAction, provider, selection);
- registerAction(fFindImplementorsInWorkingSetAction, provider, selection);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ImplementorsSearchGroup(JavaEditor editor) {
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fFindImplementorsAction= new FindImplementorsAction(fEditor);
- fFindImplementorsAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_WORKSPACE);
- fEditor.setAction("SearchImplementorsInWorkspace", fFindImplementorsAction); //$NON-NLS-1$
-
- fFindImplementorsInProjectAction= new FindImplementorsInProjectAction(fEditor);
- fFindImplementorsInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_PROJECT);
- fEditor.setAction("SearchImplementorsInProject", fFindImplementorsInProjectAction); //$NON-NLS-1$
-
- fFindImplementorsInWorkingSetAction= new FindImplementorsInWorkingSetAction(fEditor);
- fFindImplementorsInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENTORS_IN_WORKING_SET);
- fEditor.setAction("SearchImplementorsInWorkingSet", fFindImplementorsInWorkingSetAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection){
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- private void addAction(IAction action, IMenuManager manager) {
- if (action.isEnabled()) {
- manager.add(action);
- }
- }
-
- private void addWorkingSetAction(IWorkingSet[] workingSets, IMenuManager manager) {
- FindAction action;
- if (fEditor != null)
- action= new WorkingSetFindAction(fEditor, new FindImplementorsInWorkingSetAction(fEditor, workingSets), SearchUtil.toString(workingSets));
- else
- action= new WorkingSetFindAction(fSite, new FindImplementorsInWorkingSetAction(fSite, workingSets), SearchUtil.toString(workingSets));
- action.update(getContext().getSelection());
- addAction(action, manager);
- }
-
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- MenuManager javaSearchMM= new MenuManager(MENU_TEXT, IContextMenuConstants.GROUP_SEARCH);
- addAction(fFindImplementorsAction, javaSearchMM);
- addAction(fFindImplementorsInProjectAction, javaSearchMM);
-
- javaSearchMM.add(new Separator());
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- addWorkingSetAction((IWorkingSet[]) iter.next(), javaSearchMM);
- }
- addAction(fFindImplementorsInWorkingSetAction, javaSearchMM);
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindImplementorsAction, provider);
- disposeAction(fFindImplementorsInProjectAction, provider);
- disposeAction(fFindImplementorsInWorkingSetAction, provider);
- }
- super.dispose();
- fFindImplementorsAction= null;
- fFindImplementorsInProjectAction= null;
- fFindImplementorsInWorkingSetAction= null;
- updateGlobalActionHandlers();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_IMPLEMENTORS_IN_WORKSPACE, fFindImplementorsAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_IMPLEMENTORS_IN_PROJECT, fFindImplementorsInProjectAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_IMPLEMENTORS_IN_WORKING_SET, fFindImplementorsInWorkingSetAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
-
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImportActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImportActionGroup.java
deleted file mode 100644
index 22bfb841..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImportActionGroup.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.ExportResourcesAction;
-import org.eclipse.ui.actions.ImportResourcesAction;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group to add the Import and Export action to a view part's
- * context menu.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ImportActionGroup extends ActionGroup {
-
- private static final String GROUP_IMPORT= "group.import"; //$NON-NLS-1$
-
- private ImportResourcesAction fImportAction;
- private ExportResourcesAction fExportAction;
-
- /**
- * Creates a new <code>ImportActionGroup</code>. The group
- * requires that the selection provided by the part's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public ImportActionGroup(IViewPart part) {
- IWorkbenchWindow workbenchWindow = part.getSite().getWorkbenchWindow();
- fImportAction= new ImportResourcesAction(workbenchWindow);
- fExportAction= new ExportResourcesAction(workbenchWindow);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new Separator(GROUP_IMPORT));
- menu.appendToGroup(GROUP_IMPORT, fImportAction);
- menu.appendToGroup(GROUP_IMPORT, fExportAction);
- super.fillContextMenu(menu);
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- fImportAction.dispose();
- fExportAction.dispose();
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineAction.java
deleted file mode 100644
index 075f407e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineAction.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.RefactoringASTParser;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.InlineConstantAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.InlineMethodAction;
-
-/**
- * Inlines a method, local variable or a static final field.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class InlineAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
- private final InlineTempAction fInlineTemp;
- private final InlineMethodAction fInlineMethod;
- private final InlineConstantAction fInlineConstant;
-
- /**
- * Creates a new <code>InlineAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public InlineAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.InlineAction_Inline);
- fInlineTemp = new InlineTempAction(site);
- fInlineConstant = new InlineConstantAction(site);
- fInlineMethod = new InlineMethodAction(site);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public InlineAction(JavaEditor editor) {
- //don't want to call 'this' here - it'd create useless action objects
- super(editor.getEditorSite());
- setText(RefactoringMessages.InlineAction_Inline);
- fEditor= editor;
- fInlineTemp = new InlineTempAction(editor);
- fInlineConstant = new InlineConstantAction(editor);
- fInlineMethod = new InlineMethodAction(editor);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection)
- */
- public void selectionChanged(ISelection selection) {
- fInlineConstant.update(selection);
- fInlineMethod.update(selection);
- fInlineTemp.update(selection);
- setEnabled((fInlineTemp.isEnabled() || fInlineConstant.isEnabled() || fInlineMethod.isEnabled()));
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
-
- ITypeRoot typeRoot= SelectionConverter.getInputAsTypeRoot(fEditor);
- if (typeRoot == null)
- return;
-
- JavaScriptUnit node= RefactoringASTParser.parseWithASTProvider(typeRoot, true, null);
-
- if (typeRoot instanceof IJavaScriptUnit) {
- IJavaScriptUnit cu= (IJavaScriptUnit) typeRoot;
- if (fInlineTemp.isEnabled() && fInlineTemp.tryInlineTemp(cu, node, selection, getShell()))
- return;
-
- if (fInlineConstant.isEnabled() && fInlineConstant.tryInlineConstant(cu, node, selection, getShell()))
- return;
- }
- //InlineMethod is last (also tries enclosing element):
- if (fInlineMethod.isEnabled() && fInlineMethod.tryInlineMethod(typeRoot, node, selection, getShell()))
- return;
-
- MessageDialog.openInformation(getShell(), RefactoringMessages.InlineAction_dialog_title, RefactoringMessages.InlineAction_select);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- if (fInlineConstant.isEnabled())
- fInlineConstant.run(selection);
- else if (fInlineMethod.isEnabled())
- fInlineMethod.run(selection);
- else
- //inline temp will never be enabled on IStructuredSelection
- //don't bother running it
- Assert.isTrue(! fInlineTemp.isEnabled());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineTempAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineTempAction.java
deleted file mode 100644
index 0f2084c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/InlineTempAction.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Inlines the value of a local variable at all places where a read reference
- * is used.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class InlineTempAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public InlineTempAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* package */ InlineTempAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.InlineTempAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
- }
-
- //---- text selection ----------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isInlineTempAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try{
- IJavaScriptUnit input= SelectionConverter.getInputAsCompilationUnit(fEditor);
- if (!ActionUtil.isEditable(fEditor))
- return;
- RefactoringExecutionStarter.startInlineTempRefactoring(input, null, selection, getShell());
- } catch (JavaScriptModelException e){
- ExceptionHandler.handle(e, RefactoringMessages.InlineTempAction_inline_temp, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- //do nothing
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(false);
- }
-
- /* package */ boolean tryInlineTemp(IJavaScriptUnit unit, JavaScriptUnit node, ITextSelection selection, Shell shell) {
- try {
- if (RefactoringExecutionStarter.startInlineTempRefactoring(unit, node, selection, shell)) {
- return true;
- }
- } catch (JavaScriptModelException exception) {
- ExceptionHandler.handle(exception, RefactoringMessages.InlineTempAction_inline_temp, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceFactoryAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceFactoryAction.java
deleted file mode 100644
index bab6b02f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceFactoryAction.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action that encapsulates the a constructor call with a factory
- * method.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class IntroduceFactoryAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public IntroduceFactoryAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Creates a new <code>IntroduceFactoryAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public IntroduceFactoryAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.IntroduceFactoryAction_label);
- setToolTipText(RefactoringMessages.IntroduceFactoryAction_tooltipText);
- setDescription(RefactoringMessages.IntroduceFactoryAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INTRODUCE_FACTORY_ACTION);
- }
-
- //---- structured selection --------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isIntroduceFactoryAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI here - happens on selection changes
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- // we have to call this here - no selection changed event is sent after a refactoring but it may still invalidate enablement
- if (RefactoringAvailabilityTester.isIntroduceFactoryAvailable(selection)) {
- IFunction method= (IFunction) selection.getFirstElement();
- if (!ActionUtil.isEditable(getShell(), method))
- return;
- ISourceRange range= method.getNameRange();
- RefactoringExecutionStarter.startIntroduceFactoryRefactoring(method.getJavaScriptUnit(), new TextSelection(range.getOffset(), range.getLength()), getShell());
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.IntroduceFactoryAction_dialog_title, RefactoringMessages.IntroduceFactoryAction_exception);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isIntroduceFactoryAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try {
- RefactoringExecutionStarter.startIntroduceFactoryRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection, getShell());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.IntroduceFactoryAction_dialog_title, RefactoringMessages.IntroduceFactoryAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceIndirectionAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceIndirectionAction.java
deleted file mode 100644
index 68e4e079..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceIndirectionAction.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action that introduces an indirection for a certain method. This action may be invoked
- * on source or binary methods or method invocations with or without attached source.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class IntroduceIndirectionAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public IntroduceIndirectionAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(true);
- }
-
- /**
- * Creates a new <code>IntroduceIndirectionAction</code>.
- *
- * @param site the site providing context information for this action
- */
- public IntroduceIndirectionAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.IntroduceIndirectionAction_title);
- setToolTipText(RefactoringMessages.IntroduceIndirectionAction_tooltip);
- setDescription(RefactoringMessages.IntroduceIndirectionAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INTRODUCE_INDIRECTION_ACTION);
- }
-
- //---- structured selection --------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- Assert.isTrue(RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(selection));
- Object first= selection.getFirstElement();
- Assert.isTrue(first instanceof IFunction);
- run((IFunction) first);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.IntroduceIndirectionAction_dialog_title, RefactoringMessages.IntroduceIndirectionAction_unknown_exception);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- Object editorInput= SelectionConverter.getInput(fEditor);
- if (editorInput instanceof IJavaScriptUnit)
- run(selection.getOffset(), selection.getLength(), (IJavaScriptUnit) editorInput);
- else if (editorInput instanceof IClassFile)
- run(selection.getOffset(), selection.getLength(), (IClassFile) editorInput);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), RefactoringMessages.IntroduceIndirectionAction_dialog_title, RefactoringMessages.IntroduceIndirectionAction_unknown_exception);
- }
- }
-
- private void run(int offset, int length, IJavaScriptUnit unit) throws JavaScriptModelException {
- if (!ActionUtil.isEditable(fEditor, getShell(), unit))
- return;
- RefactoringExecutionStarter.startIntroduceIndirectionRefactoring(unit, offset, length, getShell());
- }
-
- private void run(int offset, int length, IClassFile file) throws JavaScriptModelException {
- if (!ActionUtil.isEditable(fEditor, getShell(), file))
- return;
- RefactoringExecutionStarter.startIntroduceIndirectionRefactoring(file, offset, length, getShell());
- }
-
- private void run(IFunction method) throws JavaScriptModelException {
- if (!ActionUtil.isEditable(fEditor, getShell(), method))
- return;
- RefactoringExecutionStarter.startIntroduceIndirectionRefactoring(method, getShell());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceParameterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceParameterAction.java
deleted file mode 100644
index 29c500c4..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IntroduceParameterAction.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Introduces a new method parameter from a selected expression.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class IntroduceParameterAction extends SelectionDispatchAction {
-
- private final JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public IntroduceParameterAction(JavaEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.IntroduceParameterAction_label);
- fEditor= editor;
- setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.INTRODUCE_PARAMETER_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled((fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null));
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- setEnabled(RefactoringAvailabilityTester.isIntroduceParameterAvailable(selection));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- try{
- IJavaScriptUnit unit= SelectionConverter.getInputAsCompilationUnit(fEditor);
- RefactoringExecutionStarter.startIntroduceParameter(unit, selection.getOffset(), selection.getLength(), getShell());
- } catch (CoreException e){
- ExceptionHandler.handle(e, RefactoringMessages.IntroduceParameterAction_dialog_title, RefactoringMessages.NewTextRefactoringAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java
deleted file mode 100644
index 3eb32021..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Action group that adds the JavaScript search actions to a context menu and
- * the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaSearchActionGroup extends ActionGroup {
-
- private JavaEditor fEditor;
-
- private ReferencesSearchGroup fReferencesGroup;
- private ReadReferencesSearchGroup fReadAccessGroup;
- private WriteReferencesSearchGroup fWriteAccessGroup;
- private DeclarationsSearchGroup fDeclarationsGroup;
-// private ImplementorsSearchGroup fImplementorsGroup;
- private OccurrencesSearchGroup fOccurrencesGroup;
-
-
- /**
- * Creates a new <code>JavaSearchActionGroup</code>. The group
- * requires that the selection provided by the part's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public JavaSearchActionGroup(IViewPart part) {
- this(part.getViewSite());
- }
-
- /**
- * Creates a new <code>JavaSearchActionGroup</code>. The group
- * requires that the selection provided by the page's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page that owns this action group
- */
- public JavaSearchActionGroup(Page page) {
- this(page.getSite());
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public JavaSearchActionGroup(JavaEditor editor) {
- Assert.isNotNull(editor);
- fEditor= editor;
-
- fReferencesGroup= new ReferencesSearchGroup(fEditor);
- fReadAccessGroup= new ReadReferencesSearchGroup(fEditor);
- fWriteAccessGroup= new WriteReferencesSearchGroup(fEditor);
- fDeclarationsGroup= new DeclarationsSearchGroup(fEditor);
-// fImplementorsGroup= new ImplementorsSearchGroup(fEditor);
- fOccurrencesGroup= new OccurrencesSearchGroup(fEditor);
- }
-
- private JavaSearchActionGroup(IWorkbenchSite site) {
- fReferencesGroup= new ReferencesSearchGroup(site);
- fReadAccessGroup= new ReadReferencesSearchGroup(site);
- fWriteAccessGroup= new WriteReferencesSearchGroup(site);
- fDeclarationsGroup= new DeclarationsSearchGroup(site);
-// fImplementorsGroup= new ImplementorsSearchGroup(site);
- fOccurrencesGroup= new OccurrencesSearchGroup(site);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void setContext(ActionContext context) {
- fReferencesGroup.setContext(context);
- fDeclarationsGroup.setContext(context);
-// fImplementorsGroup.setContext(context);
- fReadAccessGroup.setContext(context);
- fWriteAccessGroup.setContext(context);
- fOccurrencesGroup.setContext(context);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- fReferencesGroup.fillActionBars(actionBar);
- fDeclarationsGroup.fillActionBars(actionBar);
-// fImplementorsGroup.fillActionBars(actionBar);
- fReadAccessGroup.fillActionBars(actionBar);
- fWriteAccessGroup.fillActionBars(actionBar);
- fOccurrencesGroup.fillActionBars(actionBar);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
-
- if(PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SEARCH_USE_REDUCED_MENU)) {
- fReferencesGroup.fillContextMenu(menu);
- fDeclarationsGroup.fillContextMenu(menu);
-
- if (fEditor == null) {
-// fImplementorsGroup.fillContextMenu(menu);
- fReadAccessGroup.fillContextMenu(menu);
- fWriteAccessGroup.fillContextMenu(menu);
- }
- } else {
- IMenuManager target= menu;
- IMenuManager searchSubMenu= null;
- if (fEditor != null) {
- String groupName= SearchMessages.group_search;
- searchSubMenu= new MenuManager(groupName, ITextEditorActionConstants.GROUP_FIND);
- searchSubMenu.add(new GroupMarker(ITextEditorActionConstants.GROUP_FIND));
- target= searchSubMenu;
- }
-
- fReferencesGroup.fillContextMenu(target);
- fDeclarationsGroup.fillContextMenu(target);
-// fImplementorsGroup.fillContextMenu(target);
- fReadAccessGroup.fillContextMenu(target);
- fWriteAccessGroup.fillContextMenu(target);
-
- if (searchSubMenu != null) {
- fOccurrencesGroup.fillContextMenu(target);
- searchSubMenu.add(new Separator());
- }
-
- // no other way to find out if we have added items.
- if (searchSubMenu != null && searchSubMenu.getItems().length > 2) {
- menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, searchSubMenu);
- }
- }
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- fReferencesGroup.dispose();
- fDeclarationsGroup.dispose();
-// fImplementorsGroup.dispose();
- fReadAccessGroup.dispose();
- fWriteAccessGroup.dispose();
- fOccurrencesGroup.dispose();
-
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java
deleted file mode 100644
index 7792deda..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java
+++ /dev/null
@@ -1,565 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-
-/**
- * Action ids for standard actions, for groups in the menu bar, and
- * for actions in context menus of JDT views.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JdtActionConstants {
-
- // Navigate menu
-
- /**
- * Navigate menu: name of standard Goto Type global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.GoToType"</code>).
- */
- public static final String GOTO_TYPE= "org.eclipse.wst.jsdt.ui.actions.GoToType"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Goto Package global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.GoToPackage"</code>).
- */
- public static final String GOTO_PACKAGE= "org.eclipse.wst.jsdt.ui.actions.GoToPackage"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Open global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Open"</code>).
- */
- public static final String OPEN= "org.eclipse.wst.jsdt.ui.actions.Open"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Open Super Implementation global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OpenSuperImplementation"</code>).
- */
- public static final String OPEN_SUPER_IMPLEMENTATION= "org.eclipse.wst.jsdt.ui.actions.OpenSuperImplementation"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Open Type Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OpenTypeHierarchy"</code>).
- */
- public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.OpenTypeHierarchy"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Open Call Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OpenCallHierarchy"</code>).
- *
- */
- public static final String OPEN_CALL_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.OpenCallHierarchy"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Open External Javadoc global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OpenExternalJavaDoc"</code>).
- */
- public static final String OPEN_EXTERNAL_JAVA_DOC= "org.eclipse.wst.jsdt.ui.actions.OpenExternalJavaDoc"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Show in Packages View global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ShowInPackagesView"</code>).
- */
- public static final String SHOW_IN_PACKAGE_VIEW= "org.eclipse.wst.jsdt.ui.actions.ShowInPackagesView"; //$NON-NLS-1$
-
- /**
- * Navigate menu: name of standard Show in Navigator View global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ShowInNaviagtorView"</code>).
- */
- public static final String SHOW_IN_NAVIGATOR_VIEW= "org.eclipse.wst.jsdt.ui.actions.ShowInNaviagtorView"; //$NON-NLS-1$
-
- // Edit menu
-
- /**
- * Edit menu: name of standard Code Assist global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ContentAssist"</code>).
- */
- public static final String CONTENT_ASSIST= "org.eclipse.wst.jsdt.ui.actions.ContentAssist"; //$NON-NLS-1$
-
- // Source menu
-
- /**
- * Source menu: name of standard Comment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Comment"</code>).
- */
- public static final String COMMENT= "org.eclipse.wst.jsdt.ui.actions.Comment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Uncomment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Uncomment"</code>).
- */
- public static final String UNCOMMENT= "org.eclipse.wst.jsdt.ui.actions.Uncomment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard ToggleComment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ToggleComment"</code>).
- *
- */
- public static final String TOGGLE_COMMENT= "org.eclipse.wst.jsdt.ui.actions.ToggleComment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Block Comment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.AddBlockComment"</code>).
- *
- *
- */
- public static final String ADD_BLOCK_COMMENT= "org.eclipse.wst.jsdt.ui.actions.AddBlockComment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Block Uncomment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.RemoveBlockComment"</code>).
- *
- *
- */
- public static final String REMOVE_BLOCK_COMMENT= "org.eclipse.wst.jsdt.ui.actions.RemoveBlockComment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Indent global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Indent"</code>).
- *
- *
- */
- public static final String INDENT= "org.eclipse.wst.jsdt.ui.actions.Indent"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Shift Right action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ShiftRight"</code>).
- */
- public static final String SHIFT_RIGHT= "org.eclipse.wst.jsdt.ui.actions.ShiftRight"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Shift Left global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ShiftLeft"</code>).
- */
- public static final String SHIFT_LEFT= "org.eclipse.wst.jsdt.ui.actions.ShiftLeft"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Format global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Format"</code>).
- */
- public static final String FORMAT= "org.eclipse.wst.jsdt.ui.actions.Format"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Format Element global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.FormatElement"</code>).
- *
- */
- public static final String FORMAT_ELEMENT= "org.eclipse.wst.jsdt.ui.actions.FormatElement"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Add Import global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.AddImport"</code>).
- */
- public static final String ADD_IMPORT= "org.eclipse.wst.jsdt.ui.actions.AddImport"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Organize Imports global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OrganizeImports"</code>).
- */
- public static final String ORGANIZE_IMPORTS= "org.eclipse.wst.jsdt.ui.actions.OrganizeImports"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Sort Members global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.SortMembers"</code>).
- *
- */
- public static final String SORT_MEMBERS= "org.eclipse.wst.jsdt.ui.actions.SortMembers"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Surround with try/catch block global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.SurroundWithTryCatch"</code>).
- */
- public static final String SURROUND_WITH_TRY_CATCH= "org.eclipse.wst.jsdt.ui.actions.SurroundWithTryCatch"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Override Methods global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.OverrideMethods"</code>).
- */
- public static final String OVERRIDE_METHODS= "org.eclipse.wst.jsdt.ui.actions.OverrideMethods"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Generate Getter and Setter global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.GenerateGetterSetter"</code>).
- */
- public static final String GENERATE_GETTER_SETTER= "org.eclipse.wst.jsdt.ui.actions.GenerateGetterSetter"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard delegate methods global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.GenerateDelegateMethods"</code>).
- *
- */
- public static final String GENERATE_DELEGATE_METHODS= "org.eclipse.wst.jsdt.ui.actions.GenerateDelegateMethods"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Add Constructor From Superclass global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.AddConstructorFromSuperclass"</code>).
- */
- public static final String ADD_CONSTRUCTOR_FROM_SUPERCLASS= "org.eclipse.wst.jsdt.ui.actions.AddConstructorFromSuperclass"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Generate Constructor using Fields global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.GenerateConstructorUsingFields"</code>).
- */
- public static final String GENERATE_CONSTRUCTOR_USING_FIELDS= "org.eclipse.wst.jsdt.ui.actions.GenerateConstructorUsingFields"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Generate hashCode() and equals() global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.GenerateHashCodeEquals"</code>).
- *
- */
- public static final String GENERATE_HASHCODE_EQUALS= "org.eclipse.wst.jsdt.ui.actions.GenerateHashCodeEquals"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Add Javadoc Comment global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.AddJavaDocComment"</code>).
- */
- public static final String ADD_JAVA_DOC_COMMENT= "org.eclipse.wst.jsdt.ui.actions.AddJavaDocComment"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Externalize Strings global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ExternalizeStrings"</code>).
- */
- public static final String EXTERNALIZE_STRINGS= "org.eclipse.wst.jsdt.ui.actions.ExternalizeStrings"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Convert Line Delimiters To Windows global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToWindows"</code>).
- */
- public static final String CONVERT_LINE_DELIMITERS_TO_WINDOWS= "org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToWindows"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Convert Line Delimiters To UNIX global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToUNIX"</code>).
- */
- public static final String CONVERT_LINE_DELIMITERS_TO_UNIX= "org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToUNIX"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standardConvert Line Delimiters To Mac global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToMac"</code>).
- */
- public static final String CONVERT_LINE_DELIMITERS_TO_MAC= "org.eclipse.wst.jsdt.ui.actions.ConvertLineDelimitersToMac"; //$NON-NLS-1$
-
- /**
- * Source menu: name of standard Clean up global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.CleanUp"</code>).
- *
- *
- */
- public static final String CLEAN_UP= "org.eclipse.wst.jsdt.ui.actions.CleanUp"; //$NON-NLS-1$
-
- // Refactor menu
-
- /**
- * Refactor menu: name of standard Self Encapsulate Field global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.SelfEncapsulateField"</code>).
- */
- public static final String SELF_ENCAPSULATE_FIELD= "org.eclipse.wst.jsdt.ui.actions.SelfEncapsulateField"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Modify Parameters global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ModifyParameters"</code>).
- */
- public static final String MODIFY_PARAMETERS= "org.eclipse.wst.jsdt.ui.actions.ModifyParameters"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Pull Up global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.PullUp"</code>).
- */
- public static final String PULL_UP= "org.eclipse.wst.jsdt.ui.actions.PullUp"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Push Down global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.PushDown"</code>).
- *
- *
- */
- public static final String PUSH_DOWN= "org.eclipse.wst.jsdt.ui.actions.PushDown"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Move Element global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Move"</code>).
- */
- public static final String MOVE= "org.eclipse.wst.jsdt.ui.actions.Move"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Rename Element global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Rename"</code>).
- */
- public static final String RENAME= "org.eclipse.wst.jsdt.ui.actions.Rename"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Extract Temp global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ExtractTemp"</code>).
- */
- public static final String EXTRACT_TEMP= "org.eclipse.wst.jsdt.ui.actions.ExtractTemp"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Extract Constant global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ExtractConstant"</code>).
- *
- *
- */
- public static final String EXTRACT_CONSTANT= "org.eclipse.wst.jsdt.ui.actions.ExtractConstant"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Introduce Parameter global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.IntroduceParameter"</code>).
- *
- *
- */
- public static final String INTRODUCE_PARAMETER= "org.eclipse.wst.jsdt.ui.actions.IntroduceParameter"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Introduce Factory global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.IntroduceFactory"</code>).
- *
- *
- */
- public static final String INTRODUCE_FACTORY= "org.eclipse.wst.jsdt.ui.actions.IntroduceFactory"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Extract Method global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ExtractMethod"</code>).
- */
- public static final String EXTRACT_METHOD= "org.eclipse.wst.jsdt.ui.actions.ExtractMethod"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Replace Invocations global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReplaceInvocations"</code>).
- *
- *
- */
- public static final String REPLACE_INVOCATIONS="org.eclipse.wst.jsdt.ui.actions.ReplaceInvocations"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Introduce Indirection global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.IntroduceIndirection"</code>).
- *
- *
- */
- public static final String INTRODUCE_INDIRECTION= "org.eclipse.wst.jsdt.ui.actions.IntroduceIndirection"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Inline global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.Inline"</code>).
- *
- *
- */
- public static final String INLINE= "org.eclipse.wst.jsdt.ui.actions.Inline"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Extract Interface global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ExtractInterface"</code>).
- *
- *
- */
- public static final String EXTRACT_INTERFACE= "org.eclipse.wst.jsdt.ui.actions.ExtractInterface"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Generalize Declared Type global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ChangeType"</code>).
- *
- *
- */
- public static final String CHANGE_TYPE= "org.eclipse.wst.jsdt.ui.actions.ChangeType"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard global action to convert a nested type to a top level type
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.MoveInnerToTop"</code>).
- *
- *
- */
- public static final String CONVERT_NESTED_TO_TOP= "org.eclipse.wst.jsdt.ui.actions.ConvertNestedToTop"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Use Supertype global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.UseSupertype"</code>).
- *
- *
- */
- public static final String USE_SUPERTYPE= "org.eclipse.wst.jsdt.ui.actions.UseSupertype"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Infer Generic Type Arguments global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.InferTypeArguments"</code>).
- *
- *
- */
- public static final String INFER_TYPE_ARGUMENTS= "org.eclipse.wst.jsdt.ui.actions.InferTypeArguments"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard global action to convert a local
- * variable to a field (value <code>"org.eclipse.wst.jsdt.ui.actions.ConvertLocalToField"</code>).
- *
- *
- */
- public static final String CONVERT_LOCAL_TO_FIELD= "org.eclipse.wst.jsdt.ui.actions.ConvertLocalToField"; //$NON-NLS-1$
-
- /**
- * Refactor menu: name of standard Covert Anonymous to Nested global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ConvertAnonymousToNested"</code>).
- *
- *
- */
- public static final String CONVERT_ANONYMOUS_TO_NESTED= "org.eclipse.wst.jsdt.ui.actions.ConvertAnonymousToNested"; //$NON-NLS-1$
-
- // Search Menu
-
- /**
- * Search menu: name of standard Find References in Workspace global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReferencesInWorkspace"</code>).
- */
- public static final String FIND_REFERENCES_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.actions.ReferencesInWorkspace"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find References in Project global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReferencesInProject"</code>).
- */
- public static final String FIND_REFERENCES_IN_PROJECT= "org.eclipse.wst.jsdt.ui.actions.ReferencesInProject"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find References in Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReferencesInHierarchy"</code>).
- */
- public static final String FIND_REFERENCES_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.ReferencesInHierarchy"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find References in Working Set global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReferencesInWorkingSet"</code>).
- */
- public static final String FIND_REFERENCES_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.actions.ReferencesInWorkingSet"; //$NON-NLS-1$
-
-
-
- /**
- * Search menu: name of standard Find Declarations in Workspace global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.DeclarationsInWorkspace"</code>).
- */
- public static final String FIND_DECLARATIONS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.actions.DeclarationsInWorkspace"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Declarations in Project global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.DeclarationsInProject"</code>).
- */
- public static final String FIND_DECLARATIONS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.actions.DeclarationsInProject"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Declarations in Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.DeclarationsInHierarchy"</code>).
- */
- public static final String FIND_DECLARATIONS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.DeclarationsInHierarchy"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Declarations in Working Set global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.DeclarationsInWorkingSet"</code>).
- */
- public static final String FIND_DECLARATIONS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.actions.DeclarationsInWorkingSet"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Implementors in Workspace global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ImplementorsInWorkspace"</code>).
- */
- public static final String FIND_IMPLEMENTORS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.actions.ImplementorsInWorkspace"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Implementors in Project global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ImplementorsInProject"</code>).
- */
- public static final String FIND_IMPLEMENTORS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.actions.ImplementorsInProject"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Implementors in Working Set global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ImplementorsInWorkingSet"</code>).
- */
- public static final String FIND_IMPLEMENTORS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.actions.ImplementorsInWorkingSet"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Workspace global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReadAccessInWorkspace"</code>).
- */
- public static final String FIND_READ_ACCESS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.actions.ReadAccessInWorkspace"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Project global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReadAccessInProject"</code>).
- */
- public static final String FIND_READ_ACCESS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.actions.ReadAccessInProject"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReadAccessInHierarchy"</code>).
- */
- public static final String FIND_READ_ACCESS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.ReadAccessInHierarchy"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Working Set global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.ReadAccessInWorkingSet"</code>).
- */
- public static final String FIND_READ_ACCESS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.actions.ReadAccessInWorkingSet"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Write Access in Workspace global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.WriteAccessInWorkspace"</code>).
- */
- public static final String FIND_WRITE_ACCESS_IN_WORKSPACE= "org.eclipse.wst.jsdt.ui.actions.WriteAccessInWorkspace"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Write Access in Project global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.WriteAccessInProject"</code>).
- */
- public static final String FIND_WRITE_ACCESS_IN_PROJECT= "org.eclipse.wst.jsdt.ui.actions.WriteAccessInProject"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Hierarchy global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.WriteAccessInHierarchy"</code>).
- */
- public static final String FIND_WRITE_ACCESS_IN_HIERARCHY= "org.eclipse.wst.jsdt.ui.actions.WriteAccessInHierarchy"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find Read Access in Working Set global action
- * (value <code>"org.eclipse.wst.jsdt.ui.actions.WriteAccessInWorkingSet"</code>).
- */
- public static final String FIND_WRITE_ACCESS_IN_WORKING_SET= "org.eclipse.wst.jsdt.ui.actions.WriteAccessInWorkingSet"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Occurrences in File global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.OccurrencesInFile"</code>).
- *
- *
- */
- public static final String FIND_OCCURRENCES_IN_FILE= "org.eclipse.wst.jsdt.ui.actions.OccurrencesInFile"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find exception occurrences global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.ExceptionOccurrences"</code>).
- *
- *
- */
- public static final String FIND_EXCEPTION_OCCURRENCES= "org.eclipse.wst.jsdt.ui.actions.ExceptionOccurrences"; //$NON-NLS-1$
-
- /**
- * Search menu: name of standard Find implement occurrences global action (value
- * <code>"org.eclipse.wst.jsdt.ui.actions.ImplementOccurrences"</code>).
- *
- *
- */
- public static final String FIND_IMPLEMENT_OCCURRENCES= "org.eclipse.wst.jsdt.ui.actions.ImplementOccurrences"; //$NON-NLS-1$
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MemberFilterActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MemberFilterActionGroup.java
deleted file mode 100644
index 02326beb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MemberFilterActionGroup.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilter;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.MemberFilterAction;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Action Group that contributes filter buttons for a view parts showing
- * methods and fields. Contributed filters are: hide fields, hide static
- * members hide non-public members and hide local types.
- * <p>
- * The action group installs a filter on a structured viewer. The filter is connected
- * to the actions installed in the view part's toolbar menu and is updated when the
- * state of the buttons changes.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class MemberFilterActionGroup extends ActionGroup {
-
- public static final int FILTER_NONPUBLIC= MemberFilter.FILTER_NONPUBLIC;
- public static final int FILTER_STATIC= MemberFilter.FILTER_STATIC;
- public static final int FILTER_FIELDS= MemberFilter.FILTER_FIELDS;
-
- /** */
- public static final int FILTER_LOCALTYPES= MemberFilter.FILTER_LOCALTYPES;
- /** */
- public static final int ALL_FILTERS= FILTER_NONPUBLIC | FILTER_FIELDS | FILTER_STATIC | FILTER_LOCALTYPES;
-
- private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$
- private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$
- private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$
- private static final String TAG_HIDELOCALTYPES= "hidelocaltypes"; //$NON-NLS-1$
-
- private MemberFilterAction[] fFilterActions;
- private MemberFilter fFilter;
-
- private StructuredViewer fViewer;
- private String fViewerId;
- private boolean fInViewMenu;
-
-
- /**
- * Creates a new <code>MemberFilterActionGroup</code>.
- *
- * @param viewer the viewer to be filtered
- * @param viewerId a unique id of the viewer. Used as a key to to store
- * the last used filter settings in the preference store
- */
- public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) {
- this(viewer, viewerId, false);
- }
-
- /**
- * Creates a new <code>MemberFilterActionGroup</code>.
- *
- * @param viewer the viewer to be filtered
- * @param viewerId a unique id of the viewer. Used as a key to to store
- * the last used filter settings in the preference store
- * @param inViewMenu if <code>true</code> the actions are added to the view
- * menu. If <code>false</code> they are added to the toolbar.
- *
- *
- */
- public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu) {
- this(viewer, viewerId, inViewMenu, ALL_FILTERS);
- }
-
- /**
- * Creates a new <code>MemberFilterActionGroup</code>.
- *
- * @param viewer the viewer to be filtered
- * @param viewerId a unique id of the viewer. Used as a key to to store
- * the last used filter settings in the preference store
- * @param inViewMenu if <code>true</code> the actions are added to the view
- * menu. If <code>false</code> they are added to the toolbar.
- * @param availableFilters Specifies which filter action should be contained. <code>FILTER_NONPUBLIC</code>,
- * <code>FILTER_STATIC</code>, <code>FILTER_FIELDS</code> and <code>FILTER_LOCALTYPES</code>
- * or a combination of these constants are possible values. Use <code>ALL_FILTERS</code> to select all available filters.
- *
- *
- */
- public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu, int availableFilters) {
-
- fViewer= viewer;
- fViewerId= viewerId;
- fInViewMenu= inViewMenu;
-
- IPreferenceStore store= PreferenceConstants.getPreferenceStore();
- fFilter= new MemberFilter();
-
- String title, helpContext;
- ArrayList actions= new ArrayList(4);
-
- // fields
- int filterProperty= FILTER_FIELDS;
- if (isSet(filterProperty, availableFilters)) {
- boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty));
- if (filterEnabled) {
- fFilter.addFilter(filterProperty);
- }
- title= ActionMessages.MemberFilterActionGroup_hide_fields_label;
- helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION;
- MemberFilterAction hideFields= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled);
- hideFields.setDescription(ActionMessages.MemberFilterActionGroup_hide_fields_description);
- hideFields.setToolTipText(ActionMessages.MemberFilterActionGroup_hide_fields_tooltip);
- JavaPluginImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$
- actions.add(hideFields);
- }
-
- // static
- filterProperty= FILTER_STATIC;
- if (isSet(filterProperty, availableFilters)) {
- boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty));
- if (filterEnabled) {
- fFilter.addFilter(filterProperty);
- }
- title= ActionMessages.MemberFilterActionGroup_hide_static_label;
- helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION;
- MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, filterEnabled);
- hideStatic.setDescription(ActionMessages.MemberFilterActionGroup_hide_static_description);
- hideStatic.setToolTipText(ActionMessages.MemberFilterActionGroup_hide_static_tooltip);
- JavaPluginImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$
- actions.add(hideStatic);
- }
-
- // non-public
- filterProperty= FILTER_NONPUBLIC;
- if (isSet(filterProperty, availableFilters)) {
- boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty));
- if (filterEnabled) {
- fFilter.addFilter(filterProperty);
- }
- title= ActionMessages.MemberFilterActionGroup_hide_nonpublic_label;
- helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION;
- MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled);
- hideNonPublic.setDescription(ActionMessages.MemberFilterActionGroup_hide_nonpublic_description);
- hideNonPublic.setToolTipText(ActionMessages.MemberFilterActionGroup_hide_nonpublic_tooltip);
- JavaPluginImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$
- actions.add(hideNonPublic);
- }
-
- // local types
- filterProperty= FILTER_LOCALTYPES;
- if (isSet(filterProperty, availableFilters)) {
- boolean filterEnabled= store.getBoolean(getPreferenceKey(filterProperty));
- if (filterEnabled) {
- fFilter.addFilter(filterProperty);
- }
- title= ActionMessages.MemberFilterActionGroup_hide_localtypes_label;
- helpContext= IJavaHelpContextIds.FILTER_LOCALTYPES_ACTION;
- MemberFilterAction hideLocalTypes= new MemberFilterAction(this, title, filterProperty, helpContext, filterEnabled);
- hideLocalTypes.setDescription(ActionMessages.MemberFilterActionGroup_hide_localtypes_description);
- hideLocalTypes.setToolTipText(ActionMessages.MemberFilterActionGroup_hide_localtypes_tooltip);
- JavaPluginImages.setLocalImageDescriptors(hideLocalTypes, "localtypes_co.gif"); //$NON-NLS-1$
- actions.add(hideLocalTypes);
- }
-
- // order corresponds to order in toolbar
- fFilterActions= (MemberFilterAction[]) actions.toArray(new MemberFilterAction[actions.size()]);
-
- fViewer.addFilter(fFilter);
- }
-
- private String getPreferenceKey(int filterProperty) {
- return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$
- }
-
- /**
- * Sets the member filters.
- *
- * @param filterProperty the filter to be manipulated. Valid values are <code>FILTER_FIELDS</code>,
- * <code>FILTER_PUBLIC</code> <code>FILTER_PRIVATE</code> and <code>FILTER_LOCALTYPES_ACTION</code>
- * as defined by this action group
- * @param set if <code>true</code> the given filter is installed. If <code>false</code> the
- * given filter is removed
- * .
- */
- public void setMemberFilter(int filterProperty, boolean set) {
- setMemberFilters(new int[] {filterProperty}, new boolean[] {set}, true);
- }
-
- private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, boolean refresh) {
- if (propertyKeys.length == 0)
- return;
- Assert.isTrue(propertyKeys.length == propertyValues.length);
-
- for (int i= 0; i < propertyKeys.length; i++) {
- int filterProperty= propertyKeys[i];
- boolean set= propertyValues[i];
-
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- boolean found= false;
- for (int j= 0; j < fFilterActions.length; j++) {
- int currProperty= fFilterActions[j].getFilterProperty();
- if (currProperty == filterProperty) {
- fFilterActions[j].setChecked(set);
- found= true;
- store.setValue(getPreferenceKey(filterProperty), set);
- }
- }
- if (found) {
- if (set) {
- fFilter.addFilter(filterProperty);
- } else {
- fFilter.removeFilter(filterProperty);
- }
- }
- }
- if (refresh) {
- fViewer.getControl().setRedraw(false);
- BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() {
- public void run() {
- fViewer.refresh();
- }
- });
- fViewer.getControl().setRedraw(true);
- }
- }
-
- private boolean isSet(int flag, int set) {
- return (flag & set) != 0;
- }
-
- /**
- * Returns <code>true</code> if the given filter is installed.
- *
- * @param filterProperty the filter to be tested. Valid values are <code>FILTER_FIELDS</code>,
- * <code>FILTER_PUBLIC</code>, <code>FILTER_PRIVATE</code> and <code>FILTER_LOCALTYPES</code> as defined by this action
- * group
- */
- public boolean hasMemberFilter(int filterProperty) {
- return fFilter.hasFilter(filterProperty);
- }
-
- /**
- * Saves the state of the filter actions in a memento.
- *
- * @param memento the memento to which the state is saved
- */
- public void saveState(IMemento memento) {
- memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(FILTER_FIELDS)));
- memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(FILTER_STATIC)));
- memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(FILTER_NONPUBLIC)));
- memento.putString(TAG_HIDELOCALTYPES, String.valueOf(hasMemberFilter(FILTER_LOCALTYPES)));
- }
-
- /**
- * Restores the state of the filter actions from a memento.
- * <p>
- * Note: This method does not refresh the viewer.
- * </p>
- * @param memento the memento from which the state is restored
- */
- public void restoreState(IMemento memento) {
- setMemberFilters(
- new int[] {FILTER_FIELDS, FILTER_STATIC, FILTER_NONPUBLIC, FILTER_LOCALTYPES},
- new boolean[] {
- Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(),
- Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(),
- Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue(),
- Boolean.valueOf(memento.getString(TAG_HIDELOCALTYPES)).booleanValue()
- }, false);
- }
-
- /* (non-Javadoc)
- * @see ActionGroup#fillActionBars(IActionBars)
- */
- public void fillActionBars(IActionBars actionBars) {
- contributeToToolBar(actionBars.getToolBarManager());
- }
-
- /**
- * Adds the filter actions to the given tool bar
- *
- * @param tbm the tool bar to which the actions are added
- */
- public void contributeToToolBar(IToolBarManager tbm) {
- if (fInViewMenu)
- return;
- for (int i= 0; i < fFilterActions.length; i++) {
- tbm.add(fFilterActions[i]);
- }
- }
-
- /**
- * Adds the filter actions to the given menu manager.
- *
- * @param menu the menu manager to which the actions are added
- *
- */
- public void contributeToViewMenu(IMenuManager menu) {
- if (!fInViewMenu)
- return;
- final String filters= "filters"; //$NON-NLS-1$
- if (menu.find(filters) != null) {
- for (int i= 0; i < fFilterActions.length; i++) {
- menu.prependToGroup(filters, fFilterActions[i]);
- }
- } else {
- for (int i= 0; i < fFilterActions.length; i++) {
- menu.add(fFilterActions[i]);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- super.dispose();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ModifyParametersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ModifyParametersAction.java
deleted file mode 100644
index 691084fa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ModifyParametersAction.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to start the modify parameters refactoring. The refactoring supports
- * swapping and renaming of arguments.
- * <p>
- * This action is applicable to selections containing a method with one or
- * more arguments.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ModifyParametersAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ModifyParametersAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new <code>ModifyParametersAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ModifyParametersAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.RefactoringGroup_modify_Parameters_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MODIFY_PARAMETERS_ACTION);
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isChangeSignatureAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI here - happens on selection changes
- }
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isChangeSignatureAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- // we have to call this here - no selection changed event is sent after a refactoring but it may still invalidate enablement
- if (RefactoringAvailabilityTester.isChangeSignatureAvailable(selection)) {
- IFunction method= getSingleSelectedMethod(selection);
- if (! ActionUtil.isEditable(getShell(), method))
- return;
- RefactoringExecutionStarter.startChangeSignatureRefactoring(method, this, getShell());
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(ITextSelection)
- */
- public void run(ITextSelection selection) {
- try {
- if (! ActionUtil.isEditable(fEditor))
- return;
- IFunction method= getSingleSelectedMethod(selection);
- if (RefactoringAvailabilityTester.isChangeSignatureAvailable(method)){
- RefactoringExecutionStarter.startChangeSignatureRefactoring(method, this, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.ModifyParametersAction_unavailable);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- private static IFunction getSingleSelectedMethod(IStructuredSelection selection){
- if (selection.isEmpty() || selection.size() != 1)
- return null;
- if (selection.getFirstElement() instanceof IFunction)
- return (IFunction)selection.getFirstElement();
- return null;
- }
-
- private IFunction getSingleSelectedMethod(ITextSelection selection) throws JavaScriptModelException{
- //- when caret/selection on method name (call or declaration) -> that method
- //- otherwise: caret position's enclosing method declaration
- // - when caret inside argument list of method declaration -> enclosing method declaration
- // - when caret inside argument list of method call -> enclosing method declaration (and NOT method call)
- IJavaScriptElement[] elements= SelectionConverter.codeResolve(fEditor);
- if (elements.length > 1)
- return null;
- if (elements.length == 1 && elements[0] instanceof IFunction)
- return (IFunction)elements[0];
- IJavaScriptElement elementAt= SelectionConverter.getInputAsCompilationUnit(fEditor).getElementAt(selection.getOffset());
- if (elementAt instanceof IFunction)
- return (IFunction)elementAt;
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MoveAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MoveAction.java
deleted file mode 100644
index ee821c95..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/MoveAction.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.MoveInstanceMethodAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.MoveStaticMembersAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.ReorgMoveAction;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * This action moves JavaScript elements to a new location. The action prompts
- * the user for the new location.
- * <p>
- * The action is applicable to a homogeneous selection containing either
- * projects, package fragment roots, package fragments, compilation units,
- * or static methods.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class MoveAction extends SelectionDispatchAction{
-//TODO: remove duplicate availability checks. Look at
-//- f...Action.selectionChanged
-//- f...Action.isEnabled
-//- ...Refactoring.isAvailable
-//- try...
-//... and remove duplicated code for text/structured selections.
-//We have to clean this up, once we have a long term solution to
-//bug 35748 (no JavaElements for local types).
-
- private JavaEditor fEditor;
- private MoveInstanceMethodAction fMoveInstanceMethodAction;
- private MoveStaticMembersAction fMoveStaticMembersAction;
- private ReorgMoveAction fReorgMoveAction;
-
- /**
- * Creates a new <code>MoveAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public MoveAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.MoveAction_text);
- fMoveStaticMembersAction= new MoveStaticMembersAction(site);
- fMoveInstanceMethodAction= new MoveInstanceMethodAction(site);
- fReorgMoveAction= new ReorgMoveAction(site);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public MoveAction(JavaEditor editor) {
- super(editor.getEditorSite());
- fEditor= editor;
- setText(RefactoringMessages.MoveAction_text);
- fMoveStaticMembersAction= new MoveStaticMembersAction(editor);
- fMoveInstanceMethodAction= new MoveInstanceMethodAction(editor);
- fReorgMoveAction= new ReorgMoveAction(editor.getEditorSite());
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.MOVE_ACTION);
- }
-
- /*
- * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent)
- */
- public void selectionChanged(SelectionChangedEvent event) {
- fMoveStaticMembersAction.selectionChanged(event);
- fMoveInstanceMethodAction.selectionChanged(event);
- fReorgMoveAction.selectionChanged(event);
- setEnabled(computeEnableState());
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- if (fMoveInstanceMethodAction.isEnabled() && tryMoveInstanceMethod(selection))
- return;
-
- if (fMoveStaticMembersAction.isEnabled() && tryMoveStaticMembers(selection))
- return;
-
- if (fReorgMoveAction.isEnabled())
- fReorgMoveAction.run();
-
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
-
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
- */
- public void run(ITextSelection selection) {
- try {
- if (!ActionUtil.isEditable(fEditor))
- return;
- if (fMoveStaticMembersAction.isEnabled() && tryMoveStaticMembers(selection))
- return;
-
- if (fMoveInstanceMethodAction.isEnabled() && tryMoveInstanceMethod(selection))
- return;
-
- if (tryReorgMove(selection))
- return;
-
- MessageDialog.openInformation(getShell(), RefactoringMessages.MoveAction_Move, RefactoringMessages.MoveAction_select);
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- private boolean tryMoveStaticMembers(ITextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element == null || !(element instanceof IMember))
- return false;
- IMember[] array= new IMember[] { (IMember) element};
- if (!RefactoringAvailabilityTester.isMoveStaticMembersAvailable(array))
- return false;
- fMoveStaticMembersAction.run(selection);
- return true;
- }
-
- private static IMember[] getSelectedMembers(IStructuredSelection selection){
- if (selection.isEmpty())
- return null;
-
- for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
- if (! (iter.next() instanceof IMember))
- return null;
- }
- return convertToMemberArray(selection.toArray());
- }
-
- private static IMember[] convertToMemberArray(Object[] obj) {
- if (obj == null)
- return null;
- Set memberSet= new HashSet();
- memberSet.addAll(Arrays.asList(obj));
- return (IMember[]) memberSet.toArray(new IMember[memberSet.size()]);
- }
-
- private boolean tryMoveStaticMembers(IStructuredSelection selection) throws JavaScriptModelException {
- IMember[] array= getSelectedMembers(selection);
- if (!RefactoringAvailabilityTester.isMoveStaticMembersAvailable(array))
- return false;
- fMoveStaticMembersAction.run(selection);
- return true;
- }
-
- private boolean tryMoveInstanceMethod(ITextSelection selection) throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element == null || !(element instanceof IFunction))
- return false;
-
- IFunction method= (IFunction) element;
- if (!RefactoringAvailabilityTester.isMoveMethodAvailable(method))
- return false;
- fMoveInstanceMethodAction.run(selection);
- return true;
- }
-
- private boolean tryMoveInstanceMethod(IStructuredSelection selection) throws JavaScriptModelException {
- IFunction method= getSingleSelectedMethod(selection);
- if (method == null)
- return false;
- if (!RefactoringAvailabilityTester.isMoveMethodAvailable(method))
- return false;
- fMoveInstanceMethodAction.run(selection);
- return true;
- }
-
- private static IFunction getSingleSelectedMethod(IStructuredSelection selection) {
- if (selection.isEmpty() || selection.size() != 1)
- return null;
-
- Object first= selection.getFirstElement();
- if (! (first instanceof IFunction))
- return null;
- return (IFunction) first;
- }
-
-
- private boolean tryReorgMove(ITextSelection selection) throws JavaScriptModelException{
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element == null)
- return false;
- StructuredSelection mockStructuredSelection= new StructuredSelection(element);
- fReorgMoveAction.selectionChanged(mockStructuredSelection);
- if (!fReorgMoveAction.isEnabled())
- return false;
-
- fReorgMoveAction.run(mockStructuredSelection);
- return true;
- }
-
-
- /*
- * @see SelectionDispatchAction#update(ISelection)
- */
- public void update(ISelection selection) {
- fMoveStaticMembersAction.update(selection);
- fMoveInstanceMethodAction.update(selection);
- fReorgMoveAction.update(selection);
- setEnabled(computeEnableState());
- }
-
- private boolean computeEnableState(){
- return fMoveStaticMembersAction.isEnabled()
- || fMoveInstanceMethodAction.isEnabled()
- || fReorgMoveAction.isEnabled();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/NavigateActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/NavigateActionGroup.java
deleted file mode 100644
index c6ed66c1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/NavigateActionGroup.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.actions.ActionContext;
-import org.eclipse.ui.actions.ActionGroup;
-
-/**
- * Action group that adds the open and show actions to a context menu and
- * the action bar's navigate menu. This action group reuses the <code>
- * OpenEditorActionGroup</code> and <code>OpenViewActionGroup</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class NavigateActionGroup extends ActionGroup {
-
- private OpenEditorActionGroup fOpenEditorActionGroup;
- private OpenViewActionGroup fOpenViewActionGroup;
-
- /**
- * Creates a new <code>NavigateActionGroup</code>. The group requires
- * that the selection provided by the part's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public NavigateActionGroup(IViewPart part) {
- fOpenEditorActionGroup= new OpenEditorActionGroup(part);
- fOpenViewActionGroup= new OpenViewActionGroup(part);
- }
-
- /**
- * Returns the open action managed by this action group.
- *
- * @return the open action. Returns <code>null</code> if the group
- * doesn't provide any open action
- */
- public IAction getOpenAction() {
- return fOpenEditorActionGroup.getOpenAction();
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void dispose() {
- super.dispose();
- fOpenEditorActionGroup.dispose();
- fOpenViewActionGroup.dispose();
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- fOpenEditorActionGroup.fillActionBars(actionBars);
- fOpenViewActionGroup.fillActionBars(actionBars);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
-
- fOpenEditorActionGroup.fillContextMenu(menu);
- fOpenViewActionGroup.fillContextMenu(menu);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void setContext(ActionContext context) {
- super.setContext(context);
- fOpenEditorActionGroup.setContext(context);
- fOpenViewActionGroup.setContext(context);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void updateActionBars() {
- super.updateActionBars();
- fOpenEditorActionGroup.updateActionBars();
- fOpenViewActionGroup.updateActionBars();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java
deleted file mode 100644
index 230942f9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the occurrences in file actions
- * to a context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OccurrencesSearchGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindOccurrencesInFileAction fOccurrencesInFileAction;
- private FindExceptionOccurrencesAction fExceptionOccurrencesAction;
- private FindImplementOccurrencesAction fFindImplementorOccurrencesAction;
-
- /**
- * Creates a new <code>ImplementorsSearchGroup</code>. The group
- * requires that the selection provided by the site's selection provider
- * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public OccurrencesSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fOccurrencesInFileAction= new FindOccurrencesInFileAction(site);
- fOccurrencesInFileAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_OCCURRENCES_IN_FILE);
- // Need to reset the label
- fOccurrencesInFileAction.setText(SearchMessages.Search_FindOccurrencesInFile_shortLabel);
-
- fExceptionOccurrencesAction= new FindExceptionOccurrencesAction(site);
- fExceptionOccurrencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_EXCEPTION_OCCURRENCES_IN_FILE);
-
- fFindImplementorOccurrencesAction= new FindImplementOccurrencesAction(site);
- fFindImplementorOccurrencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENT_OCCURRENCES_IN_FILE);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fOccurrencesInFileAction, provider, selection);
- registerAction(fExceptionOccurrencesAction, provider, selection);
- registerAction(fFindImplementorOccurrencesAction, provider, selection);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public OccurrencesSearchGroup(JavaEditor editor) {
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fOccurrencesInFileAction= new FindOccurrencesInFileAction(fEditor);
- fOccurrencesInFileAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_OCCURRENCES_IN_FILE);
- // Need to reset the label
- fOccurrencesInFileAction.setText(SearchMessages.Search_FindOccurrencesInFile_shortLabel);
- fEditor.setAction("SearchOccurrencesInFile", fOccurrencesInFileAction); //$NON-NLS-1$
-
- fExceptionOccurrencesAction= new FindExceptionOccurrencesAction(fEditor);
- fExceptionOccurrencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_EXCEPTION_OCCURRENCES_IN_FILE);
- fEditor.setAction("SearchExceptionOccurrences", fExceptionOccurrencesAction); //$NON-NLS-1$
-
- fFindImplementorOccurrencesAction= new FindImplementOccurrencesAction(fEditor);
- fFindImplementorOccurrencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_IMPLEMENT_OCCURRENCES_IN_FILE);
- fEditor.setAction("SearchImplementOccurrences", fFindImplementorOccurrencesAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection){
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- private IAction[] getActions() {
- IAction[] actions= new IAction[3];
- actions[0]= fOccurrencesInFileAction;
- actions[1]= fExceptionOccurrencesAction;
- actions[2]= fFindImplementorOccurrencesAction;
- return actions;
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- String menuText= SearchMessages.group_occurrences;
- String shortcut= getShortcutString();
- if (shortcut != null) {
- menuText= menuText + '\t' + shortcut;
- }
-
- MenuManager javaSearchMM= new MenuManager(menuText, IContextMenuConstants.GROUP_SEARCH);
- IAction[] actions= getActions();
- for (int i= 0; i < actions.length; i++) {
- IAction action= actions[i];
- if (action.isEnabled())
- javaSearchMM.add(action);
- }
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
- private String getShortcutString() {
- IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService == null)
- return null;
- return bindingService.getBestActiveBindingFormattedFor(IJavaEditorActionDefinitionIds.SEARCH_OCCURRENCES_IN_FILE_QUICK_MENU);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindImplementorOccurrencesAction, provider);
- disposeAction(fExceptionOccurrencesAction, provider);
- disposeAction(fOccurrencesInFileAction, provider);
- }
- super.dispose();
- fFindImplementorOccurrencesAction= null;
- fExceptionOccurrencesAction= null;
- fOccurrencesInFileAction= null;
- updateGlobalActionHandlers();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_OCCURRENCES_IN_FILE, fOccurrencesInFileAction);
-// fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_EXCEPTION_OCCURRENCES, fExceptionOccurrencesAction);
-// fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_IMPLEMENT_OCCURRENCES, fFindImplementorOccurrencesAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenAction.java
deleted file mode 100644
index 61aef244..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenAction.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.util.OpenStrategy;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IEditorStatusLine;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaUILabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * This action opens a JavaScript editor on a JavaScript element or file.
- * <p>
- * The action is applicable to selections containing elements of
- * type <code>IJavaScriptUnit</code>, <code>IMember</code>
- * or <code>IFile</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>OpenAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OpenAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.OpenAction_label);
- setToolTipText(ActionMessages.OpenAction_tooltip);
- setDescription(ActionMessages.OpenAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OpenAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setText(ActionMessages.OpenAction_declaration_label);
- setEnabled(EditorUtility.getEditorInputJavaElement(fEditor, false) != null);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(checkEnabled(selection));
- }
-
- private boolean checkEnabled(IStructuredSelection selection) {
- if (selection.isEmpty())
- return false;
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof ISourceReference)
- continue;
- if (element instanceof IFile)
- continue;
- if (JavaModelUtil.isOpenableStorage(element))
- continue;
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- if (!isProcessable())
- return;
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveForked(fEditor, false);
- if (elements == null || elements.length == 0) {
- IEditorStatusLine statusLine= (IEditorStatusLine) fEditor.getAdapter(IEditorStatusLine.class);
- if (statusLine != null)
- statusLine.setMessage(true, ActionMessages.OpenAction_error_messageBadSelection, null);
- getShell().getDisplay().beep();
- return;
- }
- IJavaScriptElement element= elements[0];
- if (elements.length > 1) {
- element= SelectionConverter.selectJavaElement(elements, getShell(), getDialogTitle(), ActionMessages.OpenAction_select_element);
- if (element == null)
- return;
- }
-
- if (element!=null)
- {
- int type= element.getElementType();
- if (type == IJavaScriptElement.JAVASCRIPT_PROJECT || type == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT || type == IJavaScriptElement.PACKAGE_FRAGMENT)
- element= EditorUtility.getEditorInputJavaElement(fEditor, false);
- run(new Object[] {element} );
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.OpenAction_error_message);
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- private boolean isProcessable() {
- if (fEditor != null) {
- IJavaScriptElement je= EditorUtility.getEditorInputJavaElement(fEditor, false);
- if (je instanceof IJavaScriptUnit && !JavaModelUtil.isPrimary((IJavaScriptUnit)je))
- return true; // can process non-primary working copies
- }
- return ActionUtil.isProcessable(fEditor);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (!checkEnabled(selection))
- return;
- run(selection.toArray());
- }
-
- /**
- * Note: this method is for internal use only. Clients should not call this method.
- *
- * @param elements the elements to process
- */
- public void run(Object[] elements) {
- if (elements == null)
- return;
-
- MultiStatus status= new MultiStatus(JavaScriptUI.ID_PLUGIN, IStatus.OK, ActionMessages.OpenAction_multistatus_message, null);
-
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- try {
- element= getElementToOpen(element);
- boolean activateOnOpen= fEditor != null ? true : OpenStrategy.activateOnOpen();
- IEditorPart part= EditorUtility.openInEditor(element, activateOnOpen);
- if (part != null && element instanceof IJavaScriptElement)
- JavaScriptUI.revealInEditor(part, (IJavaScriptElement)element);
- } catch (PartInitException e) {
- String message= Messages.format(ActionMessages.OpenAction_error_problem_opening_editor, new String[] { new JavaUILabelProvider().getText(element), e.getStatus().getMessage() });
- status.add(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message, null));
- } catch (CoreException e) {
- String message= Messages.format(ActionMessages.OpenAction_error_problem_opening_editor, new String[] { new JavaUILabelProvider().getText(element), e.getStatus().getMessage() });
- status.add(new Status(IStatus.ERROR, JavaScriptUI.ID_PLUGIN, IStatus.ERROR, message, null));
- JavaScriptPlugin.log(e);
- }
- }
- if (!status.isOK()) {
- IStatus[] children= status.getChildren();
- ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.OpenAction_error_message, children.length == 1 ? children[0] : status);
- }
- }
-
- /**
- * Note: this method is for internal use only. Clients should not call this method.
- *
- * @param object the element to open
- * @return the real element to open
- * @throws JavaScriptModelException if an error occurs while accessing the JavaScript model
- */
- public Object getElementToOpen(Object object) throws JavaScriptModelException {
- return object;
- }
-
- private String getDialogTitle() {
- return ActionMessages.OpenAction_error_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java
deleted file mode 100644
index f5099ede..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.OpenWithMenu;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the actions opening a new editor to the
- * context menu and the action bar's navigate menu.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenEditorActionGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
- private boolean fIsEditorOwner;
- private OpenAction fOpen;
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the part's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public OpenEditorActionGroup(IViewPart part) {
- fSite= part.getSite();
- fOpen= new OpenAction(fSite);
- fOpen.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EDITOR);
- initialize(fSite.getSelectionProvider());
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OpenEditorActionGroup(JavaEditor editor) {
- fIsEditorOwner= true;
- fOpen= new OpenAction(editor);
- fOpen.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EDITOR);
- editor.setAction("OpenEditor", fOpen); //$NON-NLS-1$
- fSite= editor.getEditorSite();
- initialize(fSite.getSelectionProvider());
- }
-
- /**
- * Returns the open action managed by this action group.
- *
- * @return the open action. Returns <code>null</code> if the group
- * doesn't provide any open action
- */
- public IAction getOpenAction() {
- return fOpen;
- }
-
- private void initialize(ISelectionProvider provider) {
- ISelection selection= provider.getSelection();
- fOpen.update(selection);
- if (!fIsEditorOwner) {
- provider.addSelectionChangedListener(fOpen);
- }
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- setGlobalActionHandlers(actionBar);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- appendToGroup(menu, fOpen);
- if (!fIsEditorOwner) {
- addOpenWithMenu(menu);
- }
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- provider.removeSelectionChangedListener(fOpen);
- super.dispose();
- }
-
- private void setGlobalActionHandlers(IActionBars actionBars) {
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN, fOpen);
- }
-
- private void appendToGroup(IMenuManager menu, IAction action) {
- if (action.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
- }
-
- private void addOpenWithMenu(IMenuManager menu) {
- ISelection selection= getContext().getSelection();
- if (selection.isEmpty() || !(selection instanceof IStructuredSelection))
- return;
- IStructuredSelection ss= (IStructuredSelection)selection;
- if (ss.size() != 1)
- return;
-
- Object o= ss.getFirstElement();
- if (!(o instanceof IAdaptable))
- return;
-
- IAdaptable element= (IAdaptable)o;
- Object resource= element.getAdapter(IResource.class);
- if (!(resource instanceof IFile))
- return;
-
- // Create a menu.
- IMenuManager submenu= new MenuManager(ActionMessages.OpenWithMenu_label);
- submenu.add(new OpenWithMenu(fSite.getPage(), (IFile) resource));
-
- // Add the submenu.
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenExternalJavadocAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenExternalJavadocAction.java
deleted file mode 100644
index 41682e12..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenExternalJavadocAction.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.OpenBrowserUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * This action opens the selected element's Javadoc in an external
- * browser.
- * <p>
- * The action is applicable to selections containing elements of
- * type <code>IJavaScriptElement</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenExternalJavadocAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>OpenExternalJavadocAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing additional context information for this action
- */
- public OpenExternalJavadocAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.OpenExternalJavadocAction_label);
- setDescription(ActionMessages.OpenExternalJavadocAction_description);
- setToolTipText(ActionMessages.OpenExternalJavadocAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_EXTERNAL_JAVADOC_ACTION);
- }
-
-
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OpenExternalJavadocAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(checkEnabled(selection));
- }
-
- private boolean checkEnabled(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
- return selection.getFirstElement() instanceof IJavaScriptElement;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptElement element= SelectionConverter.getInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), element))
- return;
-
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveOrInputForked(fEditor);
- if (elements == null || elements.length == 0)
- return;
- IJavaScriptElement candidate= elements[0];
- if (elements.length > 1) {
- candidate= SelectionConverter.selectJavaElement(elements, getShell(), getDialogTitle(), ActionMessages.OpenExternalJavadocAction_select_element);
- }
- if (candidate != null) {
- run(candidate);
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.OpenExternalJavadocAction_code_resolve_failed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (!checkEnabled(selection))
- return;
- IJavaScriptElement element= (IJavaScriptElement)selection.getFirstElement();
- if (!ActionUtil.isProcessable(getShell(), element))
- return;
- run(element);
- }
-
- /*
- * No Javadoc since the method isn't meant to be public but is
- * since the beginning
- */
- public void run(IJavaScriptElement element) {
- if (element == null)
- return;
- Shell shell= getShell();
- try {
- String labelName= JavaScriptElementLabels.getElementLabel(element, JavaScriptElementLabels.ALL_DEFAULT);
-
- URL baseURL= JavaScriptUI.getJSdocBaseLocation(element);
- if (baseURL == null) {
- IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
- if (root != null && root.getKind() == IPackageFragmentRoot.K_BINARY) {
- String message= ActionMessages.OpenExternalJavadocAction_libraries_no_location;
- showMessage(shell, Messages.format(message, new String[] { labelName, root.getElementName() }), false);
- } else {
- IJavaScriptElement annotatedElement= element.getJavaScriptProject();
- String message= ActionMessages.OpenExternalJavadocAction_source_no_location;
- showMessage(shell, Messages.format(message, new String[] { labelName, annotatedElement.getElementName() }), false);
- }
- return;
- }
- URL url= JavaScriptUI.getJSdocLocation(element, true);
- if (url != null) {
- OpenBrowserUtil.open(url, shell.getDisplay(), getTitle());
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- showMessage(shell, ActionMessages.OpenExternalJavadocAction_opening_failed, true);
- }
- }
-
- private static void showMessage(final Shell shell, final String message, final boolean isError) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- if (isError) {
- MessageDialog.openError(shell, getTitle(), message);
- } else {
- MessageDialog.openInformation(shell, getTitle(), message);
- }
- }
- });
- }
-
- private static String getTitle() {
- return ActionMessages.OpenExternalJavadocAction_dialog_title;
- }
-
- /**
- * Note: this method is for internal use only. Clients should not call this method.
- *
- * @return the dialog default title
- */
- protected String getDialogTitle() {
- return getTitle();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenJavaPerspectiveAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenJavaPerspectiveAction.java
deleted file mode 100644
index 04bd532f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenJavaPerspectiveAction.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.Action;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Action to programmatically open a JavaScript perspective.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenJavaPerspectiveAction extends Action {
-
- /**
- * Create a new <code>OpenJavaPerspectiveAction</code>.
- */
- public OpenJavaPerspectiveAction() {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_JAVA_PERSPECTIVE_ACTION);
- }
-
- public void run() {
- IWorkbench workbench= JavaScriptPlugin.getDefault().getWorkbench();
- IWorkbenchWindow window= workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page= window.getActivePage();
- IAdaptable input;
- if (page != null)
- input= page.getInput();
- else
- input= ResourcesPlugin.getWorkspace().getRoot();
- try {
- workbench.showPerspective(JavaScriptUI.ID_PERSPECTIVE, window, input);
- } catch (WorkbenchException e) {
- ExceptionHandler.handle(e, window.getShell(),
- ActionMessages.OpenJavaPerspectiveAction_dialog_title,
- ActionMessages.OpenJavaPerspectiveAction_error_open_failed);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java
deleted file mode 100644
index c203641d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewClassCreationWizard;
-import org.eclipse.wst.jsdt.ui.wizards.NewClassWizardPage;
-
-/**
- * <p>Action that opens the new class wizard. The action initialized the wizard with either the selection
- * as configured by {@link #setSelection(org.eclipse.jface.viewers.IStructuredSelection)} or takes a preconfigured
- * new class wizard page, see {@link #setConfiguredWizardPage(NewClassWizardPage)}.</p>
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenNewClassWizardAction extends AbstractOpenWizardAction {
-
- private NewClassWizardPage fPage;
- private boolean fOpenEditorOnFinish;
-
- /**
- * Creates an instance of the <code>OpenNewClassWizardAction</code>.
- */
- public OpenNewClassWizardAction() {
- setText(ActionMessages.OpenNewClassWizardAction_text);
- setDescription(ActionMessages.OpenNewClassWizardAction_description);
- setToolTipText(ActionMessages.OpenNewClassWizardAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_CLASS_WIZARD_ACTION);
-
- fPage= null;
- fOpenEditorOnFinish= true;
- }
-
- /**
- * Sets a page to be used by the wizard or <code>null</code> to use a page initialized with values
- * from the current selection (see {@link #getSelection()} and {@link #setSelection(org.eclipse.jface.viewers.IStructuredSelection)}).
- * @param page the page to use or <code>null</code>
- */
- public void setConfiguredWizardPage(NewClassWizardPage page) {
- fPage= page;
- }
-
- /**
- * Specifies if the wizard will open the created type with the default editor. The default behaviour is to open
- * an editor.
- *
- * @param openEditorOnFinish if set, the wizard will open the created type with the default editor
- *
- *
- */
- public void setOpenEditorOnFinish(boolean openEditorOnFinish) {
- fOpenEditorOnFinish= openEditorOnFinish;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction#createWizard()
- */
- protected final INewWizard createWizard() throws CoreException {
- return new NewClassCreationWizard(fPage, fOpenEditorOnFinish);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewJavaProjectWizardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewJavaProjectWizardAction.java
deleted file mode 100644
index f5d1834f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewJavaProjectWizardAction.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.JavaProjectWizard;
-
-/**
- * <p>Action that opens the new JavaScript project wizard. The action initializes the wizard with the
- * selection as configured by {@link #setSelection(org.eclipse.jface.viewers.IStructuredSelection)} or the selection of
- * the active workbench window.</p>
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenNewJavaProjectWizardAction extends AbstractOpenWizardAction {
-
- /**
- * Creates an instance of the <code>OpenNewJavaProjectWizardAction</code>.
- */
- public OpenNewJavaProjectWizardAction() {
- setText(ActionMessages.OpenNewJavaProjectWizardAction_text);
- setDescription(ActionMessages.OpenNewJavaProjectWizardAction_description);
- setToolTipText(ActionMessages.OpenNewJavaProjectWizardAction_tooltip);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_PROJECT_WIZARD_ACTION);
- setShell(JavaScriptPlugin.getActiveWorkbenchShell());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction#createWizard()
- */
- protected final INewWizard createWizard() throws CoreException {
- return new JavaProjectWizard();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.AbstractOpenWizardAction#doCreateProjectFirstOnEmptyWorkspace(Shell)
- */
- protected boolean doCreateProjectFirstOnEmptyWorkspace(Shell shell) {
- return true; // can work on an empty workspace
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenProjectAction.java
deleted file mode 100644
index 7f8b2639..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenProjectAction.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.OpenResourceAction;
-import org.eclipse.ui.dialogs.ListSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * Action to open a closed project. Action either opens the closed projects
- * provided by the structured selection or presents a dialog from which the
- * user can select the projects to be opened.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenProjectAction extends SelectionDispatchAction implements IResourceChangeListener {
-
- private int CLOSED_PROJECTS_SELECTED= 1;
- private int OTHER_ELEMENTS_SELECTED= 2;
-
- private OpenResourceAction fWorkbenchAction;
-
- /**
- * Creates a new <code>OpenProjectAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OpenProjectAction(IWorkbenchSite site) {
- super(site);
- fWorkbenchAction= new OpenResourceAction(site.getShell());
- setText(fWorkbenchAction.getText());
- setToolTipText(fWorkbenchAction.getToolTipText());
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_PROJECT_ACTION);
- setEnabled(hasClosedProjectsInWorkspace());
- }
-
- /*
- * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
- */
- public void resourceChanged(IResourceChangeEvent event) {
- IResourceDelta delta = event.getDelta();
- if (delta != null) {
- IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED);
- for (int i = 0; i < projDeltas.length; ++i) {
- IResourceDelta projDelta = projDeltas[i];
- if ((projDelta.getFlags() & IResourceDelta.OPEN) != 0) {
- setEnabled(hasClosedProjectsInWorkspace());
- return;
- }
- }
- }
- }
-
- //---- normal selection -------------------------------------
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection)
- */
- public void selectionChanged(ISelection selection) {
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.ISelection)
- */
- public void run(ISelection selection) {
- internalRun(null);
- }
-
- private int evaluateSelection(IStructuredSelection selection, List allClosedProjects) {
- Object[] array= selection.toArray();
- int selectionStatus = 0;
- for (int i= 0; i < array.length; i++) {
- Object curr= array[i];
- if (isClosedProject(curr)) {
- if (allClosedProjects != null)
- allClosedProjects.add(curr);
- selectionStatus |= CLOSED_PROJECTS_SELECTED;
- } else {
- if (curr instanceof IWorkingSet) {
- IAdaptable[] elements= ((IWorkingSet) curr).getElements();
- for (int k= 0; k < elements.length; k++) {
- Object elem= elements[k];
- if (isClosedProject(elem)) {
- if (allClosedProjects != null)
- allClosedProjects.add(elem);
- selectionStatus |= CLOSED_PROJECTS_SELECTED;
- }
- }
- }
- selectionStatus |= OTHER_ELEMENTS_SELECTED;
- }
-
- }
- return selectionStatus;
- }
-
- private static boolean isClosedProject(Object element) {
- // assume all closed project are rendered as IProject
- return element instanceof IProject && !((IProject) element).isOpen();
- }
-
-
- //---- structured selection ---------------------------------------
-
- /* (non-Javadoc)
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- ArrayList allClosedProjects= new ArrayList();
- int selectionStatus= evaluateSelection(selection, allClosedProjects);
- if (selectionStatus == CLOSED_PROJECTS_SELECTED) { // only closed projects selected
- fWorkbenchAction.selectionChanged(new StructuredSelection(allClosedProjects));
- fWorkbenchAction.run();
- } else {
- internalRun(allClosedProjects);
- }
- }
-
- private void internalRun(List initialSelection) {
- ListSelectionDialog dialog= new ListSelectionDialog(getShell(), getClosedProjectsInWorkspace(), new ArrayContentProvider(), new JavaScriptElementLabelProvider(), ActionMessages.OpenProjectAction_dialog_message);
- dialog.setTitle(ActionMessages.OpenProjectAction_dialog_title);
- if (initialSelection != null && !initialSelection.isEmpty()) {
- dialog.setInitialElementSelections(initialSelection);
- }
- int result= dialog.open();
- if (result != Window.OK)
- return;
- final Object[] projects= dialog.getResult();
- IWorkspaceRunnable runnable= createRunnable(projects);
- try {
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(runnable));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.OpenProjectAction_dialog_title, ActionMessages.OpenProjectAction_error_message);
- } catch (InterruptedException e) {
- // user cancelled
- }
- }
-
- private IWorkspaceRunnable createRunnable(final Object[] projects) {
- return new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- monitor.beginTask("", projects.length); //$NON-NLS-1$
- MultiStatus errorStatus= null;
- for (int i = 0; i < projects.length; i++) {
- IProject project= (IProject)projects[i];
- try {
- project.open(new SubProgressMonitor(monitor, 1));
- } catch (CoreException e) {
- if (errorStatus == null)
- errorStatus = new MultiStatus(JavaScriptPlugin.getPluginId(), IStatus.ERROR, ActionMessages.OpenProjectAction_error_message, null);
- errorStatus.add(e.getStatus());
- }
- }
- monitor.done();
- if (errorStatus != null)
- throw new CoreException(errorStatus);
- }
- };
- }
-
- private Object[] getClosedProjectsInWorkspace() {
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- List result= new ArrayList(5);
- for (int i = 0; i < projects.length; i++) {
- IProject project= projects[i];
- if (!project.isOpen())
- result.add(project);
- }
- return result.toArray();
- }
-
- private boolean hasClosedProjectsInWorkspace() {
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projects.length; i++) {
- if (!projects[i].isOpen())
- return true;
- }
- return false;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenSuperImplementationAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenSuperImplementationAction.java
deleted file mode 100644
index 69ad7147..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenSuperImplementationAction.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester;
-import org.eclipse.wst.jsdt.internal.corext.util.SuperTypeHierarchyCache;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * The action opens a JavaScript editor on the selected method's super implementation.
- * <p>
- * The action is applicable to selections containing elements of type <code>
- * IFunction</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenSuperImplementationAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>OpenSuperImplementationAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OpenSuperImplementationAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.OpenSuperImplementationAction_label);
- setDescription(ActionMessages.OpenSuperImplementationAction_description);
- setToolTipText(ActionMessages.OpenSuperImplementationAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_SUPER_IMPLEMENTATION_ACTION);
- }
-
-
-
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OpenSuperImplementationAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- IFunction method= getMethod(selection);
-
- setEnabled(method != null && checkMethod(method));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- if (!ActionUtil.isProcessable(fEditor))
- return;
- IJavaScriptElement element= elementAtOffset();
- if (element == null || !(element instanceof IFunction)) {
- MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OpenSuperImplementationAction_not_applicable);
- return;
- }
- run((IFunction) element);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- run(getMethod(selection));
- }
-
- /*
- * No Javadoc since the method isn't meant to be public but is
- * since the beginning
- */
- public void run(IFunction method) {
- if (method == null)
- return;
- if (!ActionUtil.isProcessable(getShell(), method))
- return;
-
- if (!checkMethod(method)) {
- MessageDialog.openInformation(getShell(), getDialogTitle(),
- Messages.format(ActionMessages.OpenSuperImplementationAction_no_super_implementation, method.getElementName()));
- return;
- }
-
- try {
- IFunction impl= findSuperImplementation(method);
- if (impl != null) {
- JavaScriptUI.openInEditor(impl, true, true);
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getDialogTitle(), ActionMessages.OpenSuperImplementationAction_error_message);
- }
- }
-
- private IFunction findSuperImplementation(IFunction method) throws JavaScriptModelException {
- MethodOverrideTester tester= SuperTypeHierarchyCache.getMethodOverrideTester(method.getDeclaringType());
- return tester.findOverriddenMethod(method, false);
- }
-
-
- private IFunction getMethod(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object element= selection.getFirstElement();
- if (element instanceof IFunction) {
- return (IFunction) element;
- }
- return null;
- }
-
- private boolean checkMethod(IFunction method) {
- try {
- int flags= method.getFlags();
- if (!Flags.isStatic(flags) && !Flags.isPrivate(flags)) {
- IType declaringType= method.getDeclaringType();
- if (declaringType==null)
- return false;
- if (SuperTypeHierarchyCache.hasInCache(declaringType)) {
- if (findSuperImplementation(method) == null) {
- return false;
- }
- }
- return true;
- }
- } catch (JavaScriptModelException e) {
- if (!e.isDoesNotExist()) {
- JavaScriptPlugin.log(e);
- }
- }
- return false;
- }
-
- private IJavaScriptElement elementAtOffset() {
- try {
- return SelectionConverter.getElementAtOffset(fEditor);
- } catch(JavaScriptModelException e) {
- }
- return null;
- }
-
- private static String getDialogTitle() {
- return ActionMessages.OpenSuperImplementationAction_error_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenTypeHierarchyAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenTypeHierarchyAction.java
deleted file mode 100644
index 33b19f31..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenTypeHierarchyAction.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IClassFile;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.browsing.LogicalPackage;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.OpenTypeHierarchyUtil;
-
-/**
- * This action opens a type hierarchy on the selected type.
- * <p>
- * The action is applicable to selections containing elements of type
- * <code>IType</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenTypeHierarchyAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>OpenTypeHierarchyAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OpenTypeHierarchyAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.OpenTypeHierarchyAction_label);
- setToolTipText(ActionMessages.OpenTypeHierarchyAction_tooltip);
- setDescription(ActionMessages.OpenTypeHierarchyAction_description);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.OPEN_TYPE_HIERARCHY_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OpenTypeHierarchyAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(isEnabled(selection));
- }
-
- private boolean isEnabled(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
- Object input= selection.getFirstElement();
-
-
- if (input instanceof LogicalPackage)
- return true;
-
- if (!(input instanceof IJavaScriptElement))
- return false;
- switch (((IJavaScriptElement)input).getElementType()) {
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.TYPE:
- return true;
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- case IJavaScriptElement.IMPORT_DECLARATION:
- case IJavaScriptElement.CLASS_FILE:
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- return true;
- case IJavaScriptElement.LOCAL_VARIABLE:
- default:
- return false;
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptElement input= SelectionConverter.getInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
-
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveOrInputForked(fEditor);
- if (elements == null)
- return;
- List candidates= new ArrayList(elements.length);
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement[] resolvedElements= OpenTypeHierarchyUtil.getCandidates(elements[i]);
- if (resolvedElements != null)
- candidates.addAll(Arrays.asList(resolvedElements));
- }
- run((IJavaScriptElement[])candidates.toArray(new IJavaScriptElement[candidates.size()]));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.SelectionConverter_codeResolve_failed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (selection.size() != 1)
- return;
- Object input= selection.getFirstElement();
-
- if (input instanceof LogicalPackage) {
- IPackageFragment[] fragments= ((LogicalPackage)input).getFragments();
- if (fragments.length == 0)
- return;
- input= fragments[0];
- }
-
- if (!(input instanceof IJavaScriptElement)) {
- IStatus status= createStatus(ActionMessages.OpenTypeHierarchyAction_messages_no_java_element);
- ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.OpenTypeHierarchyAction_messages_title, status);
- return;
- }
- IJavaScriptElement element= (IJavaScriptElement) input;
- if (!ActionUtil.isProcessable(getShell(), element))
- return;
-
- List result= new ArrayList(1);
- IStatus status= compileCandidates(result, element);
- if (status.isOK()) {
- run((IJavaScriptElement[]) result.toArray(new IJavaScriptElement[result.size()]));
- } else {
- ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.OpenTypeHierarchyAction_messages_title, status);
- }
- }
-
- /*
- * No Javadoc since the method isn't meant to be public but is
- * since the beginning
- */
- public void run(IJavaScriptElement[] elements) {
- if (elements.length == 0) {
- getShell().getDisplay().beep();
- return;
- }
- OpenTypeHierarchyUtil.open(elements, getSite().getWorkbenchWindow());
- }
-
- private static String getDialogTitle() {
- return ActionMessages.OpenTypeHierarchyAction_dialog_title;
- }
-
- private static IStatus compileCandidates(List result, IJavaScriptElement elem) {
- IStatus ok= new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
- try {
- switch (elem.getElementType()) {
- case IJavaScriptElement.INITIALIZER:
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.TYPE:
- case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
- case IJavaScriptElement.JAVASCRIPT_PROJECT:
- result.add(elem);
- return ok;
- case IJavaScriptElement.PACKAGE_FRAGMENT:
- if (((IPackageFragment)elem).containsJavaResources()) {
- result.add(elem);
- return ok;
- }
- return createStatus(ActionMessages.OpenTypeHierarchyAction_messages_no_java_resources);
- case IJavaScriptElement.IMPORT_DECLARATION:
- IImportDeclaration decl= (IImportDeclaration) elem;
- if (decl.isOnDemand()) {
- elem= JavaModelUtil.findTypeContainer(elem.getJavaScriptProject(), Signature.getQualifier(elem.getElementName()));
- } else {
- elem= elem.getJavaScriptProject().findType(elem.getElementName());
- }
- if (elem != null) {
- result.add(elem);
- return ok;
- }
- return createStatus(ActionMessages.OpenTypeHierarchyAction_messages_unknown_import_decl);
- case IJavaScriptElement.CLASS_FILE:
- result.add(((IClassFile)elem).getType());
- return ok;
- case IJavaScriptElement.JAVASCRIPT_UNIT:
- IJavaScriptUnit cu= (IJavaScriptUnit)elem;
- IType[] types= cu.getTypes();
- if (types.length > 0) {
- result.addAll(Arrays.asList(types));
- return ok;
- }
- return createStatus(ActionMessages.OpenTypeHierarchyAction_messages_no_types);
- }
- } catch (JavaScriptModelException e) {
- return e.getStatus();
- }
- return createStatus(ActionMessages.OpenTypeHierarchyAction_messages_no_valid_java_element);
- }
-
- private static IStatus createStatus(String message) {
- return new Status(IStatus.INFO, JavaScriptPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java
deleted file mode 100644
index 9074ec09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.ContributionItemFactory;
-import org.eclipse.ui.dialogs.PropertyDialogAction;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.callhierarchy.OpenCallHierarchyAction;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds actions to open a new JDT view part or an external
- * viewer to a context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OpenViewActionGroup extends ActionGroup {
-
- private boolean fEditorIsOwner;
- private boolean fIsTypeHiararchyViewerOwner;
- private boolean fIsCallHiararchyViewerOwner;
-
- private ISelectionProvider fSelectionProvider;
-
- private OpenSuperImplementationAction fOpenSuperImplementation;
- private OpenExternalJavadocAction fOpenExternalJavadoc;
- private OpenTypeHierarchyAction fOpenTypeHierarchy;
- private OpenCallHierarchyAction fOpenCallHierarchy;
- private PropertyDialogAction fOpenPropertiesDialog;
-
- private boolean fShowOpenPropertiesAction= true;
- private boolean fShowShowInMenu= true;
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the page's selection provider is
- * of type {@link IStructuredSelection}.
- *
- * @param page the page that owns this action group
- */
- public OpenViewActionGroup(Page page) {
- createSiteActions(page.getSite(), null);
- }
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the given selection provider is
- * of type {@link IStructuredSelection}.
- *
- * @param page the page that owns this action group
- * @param selectionProvider the selection provider used instead of the
- * page selection provider.
- *
- *
- */
- public OpenViewActionGroup(Page page, ISelectionProvider selectionProvider) {
- createSiteActions(page.getSite(), selectionProvider);
- }
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the part's selection provider is
- * of type {@link IStructuredSelection}.
- *
- * @param part the view part that owns this action group
- */
- public OpenViewActionGroup(IViewPart part) {
- this(part, null);
- }
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the given selection provider is of type
- * {@link IStructuredSelection}.
- *
- * @param part the view part that owns this action group
- * @param selectionProvider the selection provider used instead of the
- * page selection provider.
- *
- *
- */
- public OpenViewActionGroup(IViewPart part, ISelectionProvider selectionProvider) {
- createSiteActions(part.getSite(), selectionProvider);
- // we do a name check here to avoid class loading.
- String partName= part.getClass().getName();
- fIsTypeHiararchyViewerOwner= "org.eclipse.wst.jsdt.internal.ui.typehierarchy.TypeHierarchyViewPart".equals(partName); //$NON-NLS-1$
- fIsCallHiararchyViewerOwner= "org.eclipse.wst.jsdt.internal.ui.callhierarchy.CallHierarchyViewPart".equals(partName); //$NON-NLS-1$
- }
-
- /**
- * Creates a new <code>OpenActionGroup</code>. The group requires
- * that the selection provided by the given selection provider is of type
- * {@link IStructuredSelection}.
- *
- * @param site the site that will own the action group.
- * @param selectionProvider the selection provider used instead of the
- * page selection provider.
- *
- *
- */
- public OpenViewActionGroup(IWorkbenchSite site, ISelectionProvider selectionProvider) {
- createSiteActions(site, selectionProvider);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param part the editor part
- */
- public OpenViewActionGroup(JavaEditor part) {
- fEditorIsOwner= true;
- fShowShowInMenu= false;
-
- fOpenSuperImplementation= new OpenSuperImplementationAction(part);
- fOpenSuperImplementation.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_SUPER_IMPLEMENTATION);
- part.setAction("OpenSuperImplementation", fOpenSuperImplementation); //$NON-NLS-1$
-
- fOpenExternalJavadoc= new OpenExternalJavadocAction(part);
- fOpenExternalJavadoc.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EXTERNAL_JAVADOC);
- part.setAction("OpenExternalJavadoc", fOpenExternalJavadoc); //$NON-NLS-1$
-
- fOpenTypeHierarchy= new OpenTypeHierarchyAction(part);
- fOpenTypeHierarchy.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_TYPE_HIERARCHY);
- part.setAction("OpenTypeHierarchy", fOpenTypeHierarchy); //$NON-NLS-1$
-
- fOpenCallHierarchy= new OpenCallHierarchyAction(part);
- fOpenCallHierarchy.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_CALL_HIERARCHY);
- part.setAction("OpenCallHierarchy", fOpenCallHierarchy); //$NON-NLS-1$
-
- initialize(part.getEditorSite().getSelectionProvider());
- }
-
- /**
- * Specifies if this action group also contains the 'Properties' action ({@link PropertyDialogAction}).
- * By default, the action is contained in the group.
- *
- * @param enable If set, the 'Properties' action is part of this action group
- *
- */
- public void containsOpenPropertiesAction(boolean enable) {
- fShowOpenPropertiesAction= enable;
- }
-
- /**
- * Specifies if this action group also contains the 'Show In' menu (See {@link ContributionItemFactory#VIEWS_SHOW_IN}).
- * By default, the action is contained in the group except for editors.
- *
- * @param enable If set, the 'Show In' menu is part of this action group
- *
- */
- public void containsShowInMenu(boolean enable) {
- fShowShowInMenu= enable;
- }
-
- private void createSiteActions(IWorkbenchSite site, ISelectionProvider specialProvider) {
- fOpenSuperImplementation= new OpenSuperImplementationAction(site);
- fOpenSuperImplementation.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_SUPER_IMPLEMENTATION);
- fOpenSuperImplementation.setSpecialSelectionProvider(specialProvider);
-
- fOpenExternalJavadoc= new OpenExternalJavadocAction(site);
- fOpenExternalJavadoc.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EXTERNAL_JAVADOC);
- fOpenExternalJavadoc.setSpecialSelectionProvider(specialProvider);
-
- fOpenTypeHierarchy= new OpenTypeHierarchyAction(site);
- fOpenTypeHierarchy.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_TYPE_HIERARCHY);
- fOpenTypeHierarchy.setSpecialSelectionProvider(specialProvider);
-
- fOpenCallHierarchy= new OpenCallHierarchyAction(site);
- fOpenCallHierarchy.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_CALL_HIERARCHY);
- fOpenCallHierarchy.setSpecialSelectionProvider(specialProvider);
-
- ISelectionProvider provider= specialProvider != null ? specialProvider : site.getSelectionProvider();
-
- fOpenPropertiesDialog= new PropertyDialogAction(site, provider);
- fOpenPropertiesDialog.setActionDefinitionId(IWorkbenchActionDefinitionIds.PROPERTIES);
-
- initialize(provider);
- }
-
- private void initialize(ISelectionProvider provider) {
- fSelectionProvider= provider;
- ISelection selection= provider.getSelection();
- fOpenSuperImplementation.update(selection);
- fOpenExternalJavadoc.update(selection);
- fOpenTypeHierarchy.update(selection);
- fOpenCallHierarchy.update(selection);
- if (!fEditorIsOwner) {
- if (fShowOpenPropertiesAction) {
- if (selection instanceof IStructuredSelection) {
- fOpenPropertiesDialog.selectionChanged((IStructuredSelection) selection);
- } else {
- fOpenPropertiesDialog.selectionChanged(selection);
- }
- }
- provider.addSelectionChangedListener(fOpenSuperImplementation);
- provider.addSelectionChangedListener(fOpenExternalJavadoc);
- provider.addSelectionChangedListener(fOpenTypeHierarchy);
- provider.addSelectionChangedListener(fOpenCallHierarchy);
- // no need to register the open properties dialog action since it registers itself
- }
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- setGlobalActionHandlers(actionBar);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- if (!fIsTypeHiararchyViewerOwner)
- appendToGroup(menu, fOpenTypeHierarchy);
- if (!fIsCallHiararchyViewerOwner)
- appendToGroup(menu, fOpenCallHierarchy);
-
- if (fShowShowInMenu) {
- MenuManager showInSubMenu= new MenuManager(getShowInMenuLabel());
- IWorkbenchWindow workbenchWindow= fOpenSuperImplementation.getSite().getWorkbenchWindow();
- showInSubMenu.add(ContributionItemFactory.VIEWS_SHOW_IN.create(workbenchWindow));
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, showInSubMenu);
- }
-
- IStructuredSelection selection= getStructuredSelection();
- if (fShowOpenPropertiesAction && selection != null)
- menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fOpenPropertiesDialog);
- }
-
- private String getShowInMenuLabel() {
- String keyBinding= null;
-
- IBindingService bindingService= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class);
- if (bindingService != null)
- keyBinding= bindingService.getBestActiveBindingFormattedFor("org.eclipse.ui.navigate.showInQuickMenu"); //$NON-NLS-1$
-
- if (keyBinding == null)
- keyBinding= ""; //$NON-NLS-1$
-
- return ActionMessages.OpenViewActionGroup_showInAction_label + '\t' + keyBinding;
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- fSelectionProvider.removeSelectionChangedListener(fOpenSuperImplementation);
- fSelectionProvider.removeSelectionChangedListener(fOpenExternalJavadoc);
- fSelectionProvider.removeSelectionChangedListener(fOpenTypeHierarchy);
- fSelectionProvider.removeSelectionChangedListener(fOpenCallHierarchy);
- super.dispose();
- }
-
- private void setGlobalActionHandlers(IActionBars actionBars) {
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN_SUPER_IMPLEMENTATION, fOpenSuperImplementation);
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN_EXTERNAL_JAVA_DOC, fOpenExternalJavadoc);
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN_TYPE_HIERARCHY, fOpenTypeHierarchy);
- actionBars.setGlobalActionHandler(JdtActionConstants.OPEN_CALL_HIERARCHY, fOpenCallHierarchy);
-
- if (!fEditorIsOwner && fShowOpenPropertiesAction)
- actionBars.setGlobalActionHandler(ActionFactory.PROPERTIES.getId(), fOpenPropertiesDialog);
- }
-
- private void appendToGroup(IMenuManager menu, IAction action) {
- if (action.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action);
- }
-
- private IStructuredSelection getStructuredSelection() {
- ISelection selection= getContext().getSelection();
- if (selection instanceof IStructuredSelection)
- return (IStructuredSelection)selection;
- return null;
- }
-
-
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OrganizeImportsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OrganizeImportsAction.java
deleted file mode 100644
index a91035e2..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OrganizeImportsAction.java
+++ /dev/null
@@ -1,397 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Comparator;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IEditingSupport;
-import org.eclipse.jface.text.IEditingSupportRegistry;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.search.TypeNameMatch;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.OrganizeImportsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
-import org.eclipse.wst.jsdt.internal.corext.util.History;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.QualifiedTypeNameHistory;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.MultiOrganizeImportAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.MultiElementListSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ASTProvider;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-import com.ibm.icu.text.Collator;
-
-/**
- * Organizes the imports of a compilation unit.
- * <p>
- * The action is applicable to selections containing elements of
- * type <code>IJavaScriptUnit</code> or <code>IPackage
- * </code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OrganizeImportsAction extends SelectionDispatchAction {
-
- private static final OrganizeImportComparator ORGANIZE_IMPORT_COMPARATOR= new OrganizeImportComparator();
-
- private JavaEditor fEditor;
- /** <code>true</code> if the query dialog is showing. */
- private boolean fIsQueryShowing= false;
- private final MultiOrganizeImportAction fCleanUpDelegate;
-
- /* (non-Javadoc)
- * Class implements IObjectActionDelegate
- */
- public static class ObjectDelegate implements IObjectActionDelegate {
- private OrganizeImportsAction fAction;
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- fAction= new OrganizeImportsAction(targetPart.getSite());
- }
- public void run(IAction action) {
- fAction.run();
- }
- public void selectionChanged(IAction action, ISelection selection) {
- if (fAction == null)
- action.setEnabled(false);
- }
- }
-
- private static final class OrganizeImportComparator implements Comparator {
-
- public int compare(Object o1, Object o2) {
- if (((String)o1).equals(o2))
- return 0;
-
- History history= QualifiedTypeNameHistory.getDefault();
-
- int pos1= history.getPosition(o1);
- int pos2= history.getPosition(o2);
-
- if (pos1 == pos2)
- return Collator.getInstance().compare(o1, o2);
-
- if (pos1 > pos2) {
- return -1;
- } else {
- return 1;
- }
- }
-
- }
-
- /**
- * Creates a new <code>OrganizeImportsAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public OrganizeImportsAction(IWorkbenchSite site) {
- super(site);
-
- fCleanUpDelegate= new MultiOrganizeImportAction(site);
-
- setText(ActionMessages.OrganizeImportsAction_label);
- setToolTipText(ActionMessages.OrganizeImportsAction_tooltip);
- setDescription(ActionMessages.OrganizeImportsAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public OrganizeImportsAction(JavaEditor editor) {
- super(editor.getEditorSite());
-
- fEditor= editor;
- fCleanUpDelegate= new MultiOrganizeImportAction(editor);
-
- setText(ActionMessages.OrganizeImportsAction_label);
- setToolTipText(ActionMessages.OrganizeImportsAction_tooltip);
- setDescription(ActionMessages.OrganizeImportsAction_description);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
-
- setEnabled(fCleanUpDelegate.isEnabled());
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- fCleanUpDelegate.selectionChanged(selection);
- setEnabled(fCleanUpDelegate.isEnabled());
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- fCleanUpDelegate.selectionChanged(selection);
- setEnabled(fCleanUpDelegate.isEnabled());
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptUnit cu= getCompilationUnit(fEditor);
- if (cu != null) {
- run(cu);
- }
- }
-
- private static IJavaScriptUnit getCompilationUnit(JavaEditor editor) {
- IJavaScriptElement element= JavaScriptUI.getEditorInputJavaElement(editor.getEditorInput());
- if (!(element instanceof IJavaScriptUnit))
- return null;
-
- return (IJavaScriptUnit)element;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- IJavaScriptUnit[] cus= fCleanUpDelegate.getCompilationUnits(selection);
- if (cus.length == 0) {
- MessageDialog.openInformation(getShell(), ActionMessages.OrganizeImportsAction_EmptySelection_title, ActionMessages.OrganizeImportsAction_EmptySelection_description);
- } else if (cus.length == 1) {
- run(cus[0]);
- } else {
- fCleanUpDelegate.run(selection);
- }
- }
-
- /**
- * Perform organize import on multiple compilation units. No editors are opened.
- * @param cus The compilation units to run on
- */
- public void runOnMultiple(final IJavaScriptUnit[] cus) {
- if (cus.length == 0)
- return;
-
- fCleanUpDelegate.run(new StructuredSelection(cus));
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- * @param cu The compilation unit to process
- */
- public void run(IJavaScriptUnit cu) {
- if (!ElementValidator.check(cu, getShell(), ActionMessages.OrganizeImportsAction_error_title, fEditor != null))
- return;
- if (!ActionUtil.isEditable(fEditor, getShell(), cu))
- return;
-
- IEditingSupport helper= createViewerHelper();
- try {
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaScriptProject());
-
- if (fEditor == null && EditorUtility.isOpenInEditor(cu) == null) {
- IEditorPart editor= JavaScriptUI.openInEditor(cu);
- if (editor instanceof JavaEditor) {
- fEditor= (JavaEditor) editor;
- }
- }
-
- JavaScriptUnit astRoot= JavaScriptPlugin.getDefault().getASTProvider().getAST(cu, ASTProvider.WAIT_ACTIVE_ONLY, null);
-
- OrganizeImportsOperation op= new OrganizeImportsOperation(cu, astRoot, settings.importIgnoreLowercase, !cu.isWorkingCopy(), true, createChooseImportQuery());
-
- IRewriteTarget target= null;
- if (fEditor != null) {
- target= (IRewriteTarget) fEditor.getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.beginCompoundChange();
- }
- }
-
- IProgressService progressService= PlatformUI.getWorkbench().getProgressService();
- IRunnableContext context= getSite().getWorkbenchWindow();
- if (context == null) {
- context= progressService;
- }
- try {
- registerHelper(helper);
- progressService.runInUI(context, new WorkbenchRunnableAdapter(op, op.getScheduleRule()), op.getScheduleRule());
- IProblem parseError= op.getParseError();
- if (parseError != null) {
- String message= Messages.format(ActionMessages.OrganizeImportsAction_single_error_parse, parseError.getMessage());
- MessageDialog.openInformation(getShell(), ActionMessages.OrganizeImportsAction_error_title, message);
- if (fEditor != null && parseError.getSourceStart() != -1) {
- fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1);
- }
- } else {
- if (fEditor != null) {
- setStatusBarMessage(getOrganizeInfo(op));
- }
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.OrganizeImportsAction_error_title, ActionMessages.OrganizeImportsAction_error_message);
- } catch (InterruptedException e) {
- } finally {
- deregisterHelper(helper);
- if (target != null) {
- target.endCompoundChange();
- }
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), ActionMessages.OrganizeImportsAction_error_title, ActionMessages.OrganizeImportsAction_error_message);
- }
- }
-
- private String getOrganizeInfo(OrganizeImportsOperation op) {
- int nImportsAdded= op.getNumberOfImportsAdded();
- if (nImportsAdded >= 0) {
- return Messages.format(ActionMessages.OrganizeImportsAction_summary_added, String.valueOf(nImportsAdded));
- } else {
- return Messages.format(ActionMessages.OrganizeImportsAction_summary_removed, String.valueOf(-nImportsAdded));
- }
- }
-
- private IChooseImportQuery createChooseImportQuery() {
- return new IChooseImportQuery() {
- public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
- return doChooseImports(openChoices, ranges);
- }
- };
- }
-
- private TypeNameMatch[] doChooseImports(TypeNameMatch[][] openChoices, final ISourceRange[] ranges) {
- // remember selection
- ISelection sel= fEditor != null ? fEditor.getSelectionProvider().getSelection() : null;
- TypeNameMatch[] result= null;
- ILabelProvider labelProvider= new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED);
-
- MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) {
- protected void handleSelectionChanged() {
- super.handleSelectionChanged();
- // show choices in editor
- doListSelectionChanged(getCurrentPage(), ranges);
- }
- };
- fIsQueryShowing= true;
- dialog.setTitle(ActionMessages.OrganizeImportsAction_selectiondialog_title);
- dialog.setMessage(ActionMessages.OrganizeImportsAction_selectiondialog_message);
- dialog.setElements(openChoices);
- dialog.setComparator(ORGANIZE_IMPORT_COMPARATOR);
- if (dialog.open() == Window.OK) {
- Object[] res= dialog.getResult();
- result= new TypeNameMatch[res.length];
- for (int i= 0; i < res.length; i++) {
- Object[] array= (Object[]) res[i];
- if (array.length > 0) {
- result[i]= (TypeNameMatch) array[0];
- QualifiedTypeNameHistory.remember(result[i].getFullyQualifiedName());
- }
- }
- }
- // restore selection
- if (sel instanceof ITextSelection) {
- ITextSelection textSelection= (ITextSelection) sel;
- fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength());
- }
- fIsQueryShowing= false;
- return result;
- }
-
- private void doListSelectionChanged(int page, ISourceRange[] ranges) {
- if (fEditor != null && ranges != null && page >= 0 && page < ranges.length) {
- ISourceRange range= ranges[page];
- fEditor.selectAndReveal(range.getOffset(), range.getLength());
- }
- }
-
- private void setStatusBarMessage(String message) {
- IStatusLineManager manager= fEditor.getEditorSite().getActionBars().getStatusLineManager();
- manager.setMessage(message);
- }
-
- private IEditingSupport createViewerHelper() {
- return new IEditingSupport() {
- public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) {
- return true; // assume true, since we only register while we are active
- }
- public boolean ownsFocusShell() {
- return fIsQueryShowing;
- }
-
- };
- }
-
- private void registerHelper(IEditingSupport helper) {
- if (fEditor == null)
- return;
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.register(helper);
- }
- }
-
- private void deregisterHelper(IEditingSupport helper) {
- if (fEditor == null)
- return;
- ISourceViewer viewer= fEditor.getViewer();
- if (viewer instanceof IEditingSupportRegistry) {
- IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
- registry.unregister(helper);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OverrideMethodsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OverrideMethodsAction.java
deleted file mode 100644
index 8a1e40f7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OverrideMethodsAction.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.IFunctionBinding;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OverrideMethodDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Adds unimplemented methods of a type. The action opens a dialog from which the user can
- * choose the methods to be added.
- * <p>
- * Will open the parent compilation unit in a JavaScript editor. The result is unsaved, so the
- * user can decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing elements of type
- * {@link org.eclipse.wst.jsdt.core.IType}.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class OverrideMethodsAction extends SelectionDispatchAction {
-
- /** The dialog title */
- private static final String DIALOG_TITLE= ActionMessages.OverrideMethodsAction_error_title;
-
- /** The compilation unit editor */
- private CompilationUnitEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this
- * constructor.
- * @param editor the compilation unit editor
- */
- public OverrideMethodsAction(final CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(checkEnabledEditor());
- }
-
- /**
- * Creates a new override method action.
- * <p>
- * The action requires that the selection provided by the site's selection provider is
- * of type {@link org.eclipse.jface.viewers.IStructuredSelection}.
- *
- * @param site the workbench site providing context information for this action
- */
- public OverrideMethodsAction(final IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.OverrideMethodsAction_label);
- setDescription(ActionMessages.OverrideMethodsAction_description);
- setToolTipText(ActionMessages.OverrideMethodsAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
- }
-
- private boolean canEnable(IStructuredSelection selection) throws JavaScriptModelException {
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
- final IType type= (IType) selection.getFirstElement();
- return type.getJavaScriptUnit() != null;
- }
- if ((selection.size() == 1) && (selection.getFirstElement() instanceof IJavaScriptUnit))
- return true;
- return false;
- }
-
- private boolean checkEnabledEditor() {
- return fEditor != null && SelectionConverter.canOperateOn(fEditor);
- }
-
- private String getDialogTitle() {
- return DIALOG_TITLE;
- }
-
- private IType getSelectedType(IStructuredSelection selection) throws JavaScriptModelException {
- final Object[] elements= selection.toArray();
- if (elements.length == 1 && (elements[0] instanceof IType)) {
- final IType type= (IType) elements[0];
- if (type.getJavaScriptUnit() != null) {
- return type;
- }
- } else if (elements[0] instanceof IJavaScriptUnit) {
- final IType type= ((IJavaScriptUnit) elements[0]).findPrimaryType();
- if (type != null)
- return type;
- }
- return null;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- final IType type= getSelectedType(selection);
- if (type == null) {
- MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
- notifyResult(false);
- return;
- }
- if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(getShell(), type)) {
- notifyResult(false);
- return;
- }
- run(getShell(), type);
- } catch (CoreException exception) {
- ExceptionHandler.handle(exception, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
- */
- public void run(ITextSelection selection) {
- try {
- final IType type= SelectionConverter.getTypeAtOffset(fEditor);
- if (type != null) {
- if (!ElementValidator.check(type, getShell(), getDialogTitle(), false) || !ActionUtil.isEditable(fEditor, getShell(), type)) {
- notifyResult(false);
- return;
- }
- run(getShell(), type);
- } else {
- MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_not_applicable);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.OverrideMethodsAction_error_actionfailed);
- }
- }
-
- private void run(Shell shell, IType type) throws CoreException {
- final OverrideMethodDialog dialog= new OverrideMethodDialog(shell, fEditor, type,false);
- if (!dialog.hasMethodsToOverride()) {
- MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
- notifyResult(false);
- return;
- }
- if (dialog.open() != Window.OK) {
- notifyResult(false);
- return;
- }
-
- final Object[] selected= dialog.getResult();
- if (selected == null) {
- notifyResult(false);
- return;
- }
-
- ArrayList methods= new ArrayList();
- for (int i= 0; i < selected.length; i++) {
- Object elem= selected[i];
- if (elem instanceof IFunctionBinding) {
- methods.add(elem);
- }
- }
- IFunctionBinding[] methodToOverride= (IFunctionBinding[]) methods.toArray(new IFunctionBinding[methods.size()]);
-
-
- final IEditorPart editor= JavaScriptUI.openInEditor(type.getJavaScriptUnit());
- final IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
- if (target != null)
- target.beginCompoundChange();
- try {
- JavaScriptUnit astRoot= dialog.getCompilationUnit();
- final ITypeBinding typeBinding= ASTNodes.getTypeBinding(astRoot, type);
- int insertPos= dialog.getInsertOffset();
-
- AddUnimplementedMethodsOperation operation= (AddUnimplementedMethodsOperation) createRunnable(astRoot, typeBinding, methodToOverride, insertPos, dialog.getGenerateComment());
- IRunnableContext context= JavaScriptPlugin.getActiveWorkbenchWindow();
- if (context == null)
- context= new BusyIndicatorRunnableContext();
- PlatformUI.getWorkbench().getProgressService().runInUI(context, new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()), operation.getSchedulingRule());
- final String[] created= operation.getCreatedMethods();
- if (created == null || created.length == 0)
- MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
- } catch (InvocationTargetException exception) {
- ExceptionHandler.handle(exception, shell, getDialogTitle(), null);
- } catch (InterruptedException exception) {
- // Do nothing. Operation has been canceled by user.
- } finally {
- if (target != null)
- target.endCompoundChange();
- }
- notifyResult(true);
- }
-
- /**
- * Returns a runnable that creates the method stubs for overridden methods.
- *
- * @param astRoot the AST of the compilation unit to work on. The AST must have been created from a {@link IJavaScriptUnit}, that
- * means {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setSource(IJavaScriptUnit)} was used.
- * @param type the binding of the type to add the new methods to. The type binding must correspond to a type declaration in the AST.
- * @param methodToOverride the bindings of methods to override or <code>null</code> to implement all unimplemented, abstract methods from super types.
- * @param insertPos a hint for a location in the source where to insert the new methods or <code>-1</code> to use the default behavior.
- * @param createComments if set, comments will be added to the new methods.
- * @return returns a runnable that creates the methods stubs.
- * @throws IllegalArgumentException a {@link IllegalArgumentException} is thrown if the AST passed has not been created from a {@link IJavaScriptUnit}.
- *
- *
- */
- public static IWorkspaceRunnable createRunnable(JavaScriptUnit astRoot, ITypeBinding type, IFunctionBinding[] methodToOverride, int insertPos, boolean createComments) {
- AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(astRoot, type, methodToOverride, insertPos, true, true, false);
- operation.setCreateComments(createComments);
- return operation;
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(canEnable(selection));
- } catch (JavaScriptModelException exception) {
- if (JavaModelUtil.isExceptionToBeLogged(exception))
- JavaScriptPlugin.log(exception);
- setEnabled(false);
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- // Do nothing
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ProjectActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ProjectActionGroup.java
deleted file mode 100644
index fc909046..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ProjectActionGroup.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.actions.CloseResourceAction;
-import org.eclipse.ui.actions.CloseUnrelatedProjectsAction;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Adds actions to open and close a project to the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ProjectActionGroup extends ActionGroup {
-
- private IWorkbenchSite fSite;
-
- private OpenProjectAction fOpenAction;
- private CloseResourceAction fCloseAction;
- private CloseResourceAction fCloseUnrelatedAction;
-
- private ISelectionChangedListener fSelectionChangedListener;
-
- /**
- * Creates a new <code>ProjectActionGroup</code>. The group requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public ProjectActionGroup(IViewPart part) {
- fSite = part.getSite();
- Shell shell= fSite.getShell();
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
-
- fCloseAction= new CloseResourceAction(shell);
- fCloseAction.setActionDefinitionId("org.eclipse.ui.project.closeProject"); //$NON-NLS-1$
-
- fCloseUnrelatedAction= new CloseUnrelatedProjectsAction(shell);
- fCloseUnrelatedAction.setActionDefinitionId("org.eclipse.ui.project.closeUnrelatedProjects"); //$NON-NLS-1$
-
- fOpenAction= new OpenProjectAction(fSite);
- fOpenAction.setActionDefinitionId("org.eclipse.ui.project.openProject"); //$NON-NLS-1$
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection s= (IStructuredSelection)selection;
- fOpenAction.selectionChanged(s);
- fCloseAction.selectionChanged(s);
- fCloseUnrelatedAction.selectionChanged(s);
- }
-
- fSelectionChangedListener= new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection s= event.getSelection();
- if (s instanceof IStructuredSelection) {
- performSelectionChanged((IStructuredSelection) s);
- }
- }
- };
- provider.addSelectionChangedListener(fSelectionChangedListener);
-
- IWorkspace workspace= ResourcesPlugin.getWorkspace();
- workspace.addResourceChangeListener(fOpenAction);
- workspace.addResourceChangeListener(fCloseAction);
- workspace.addResourceChangeListener(fCloseUnrelatedAction);
- }
-
- protected void performSelectionChanged(IStructuredSelection structuredSelection) {
- Object[] array= structuredSelection.toArray();
- ArrayList openProjects= new ArrayList();
- int selectionStatus= evaluateSelection(array, openProjects);
- StructuredSelection sel= new StructuredSelection(openProjects);
-
- fOpenAction.setEnabled(selectionStatus == CLOSED_PROJECTS_SELECTED || (selectionStatus == 0 && hasClosedProjectsInWorkspace()));
- fCloseAction.selectionChanged(sel);
- fCloseUnrelatedAction.selectionChanged(sel);
- }
-
- private int CLOSED_PROJECTS_SELECTED= 1;
- private int NON_PROJECT_SELECTED= 2;
-
- private int evaluateSelection(Object[] array, List allOpenProjects) {
- int status= 0;
- for (int i= 0; i < array.length; i++) {
- Object curr= array[i];
- if (curr instanceof IJavaScriptProject) {
- curr= ((IJavaScriptProject) curr).getProject();
- }
- if (curr instanceof IProject) {
- IProject project= (IProject) curr;
- if (project.isOpen()) {
- allOpenProjects.add(project);
- } else {
- status |= CLOSED_PROJECTS_SELECTED;
- }
- } else {
- if (curr instanceof IWorkingSet) {
- int res= evaluateSelection(((IWorkingSet) curr).getElements(), allOpenProjects);
- status |= res;
- } else {
- status |= NON_PROJECT_SELECTED;
- }
- }
- }
- return status;
- }
-
- private boolean hasClosedProjectsInWorkspace() {
- IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projects.length; i++) {
- if (!projects[i].isOpen())
- return true;
- }
- return false;
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- actionBars.setGlobalActionHandler(IDEActionFactory.CLOSE_PROJECT.getId(), fCloseAction);
- actionBars.setGlobalActionHandler(IDEActionFactory.CLOSE_UNRELATED_PROJECTS.getId(), fCloseUnrelatedAction);
- actionBars.setGlobalActionHandler(IDEActionFactory.OPEN_PROJECT.getId(), fOpenAction);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- if (fOpenAction.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fOpenAction);
- if (fCloseAction.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fCloseAction);
- if (fCloseUnrelatedAction.isEnabled() && areOnlyProjectsSelected(fCloseUnrelatedAction.getStructuredSelection()))
- menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fCloseUnrelatedAction);
- }
-
- /**
- * Returns the open project action contained in this project action group.
- *
- * @return returns the open project action
- *
- *
- */
- public OpenProjectAction getOpenProjectAction() {
- return fOpenAction;
- }
-
- private boolean areOnlyProjectsSelected(IStructuredSelection selection) {
- if (selection.isEmpty())
- return false;
-
- Iterator iter= selection.iterator();
- while (iter.hasNext()) {
- Object obj= iter.next();
- if (obj instanceof IAdaptable) {
- if (((IAdaptable)obj).getAdapter(IProject.class) == null)
- return false;
- }
- }
- return true;
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- provider.removeSelectionChangedListener(fSelectionChangedListener);
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(fOpenAction);
- workspace.removeResourceChangeListener(fCloseAction);
- workspace.removeResourceChangeListener(fCloseUnrelatedAction);
- super.dispose();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PullUpAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PullUpAction.java
deleted file mode 100644
index 3bd0b7c5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PullUpAction.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to pull up method and fields into a superclass.
- * <p>
- * Action is applicable to selections containing elements of type
- * <code>IType</code> (top-level types only), <code>IField</code> and
- * <code>IFunction</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class PullUpAction extends SelectionDispatchAction {
-
- private static IMember[] getSelectedMembers(IStructuredSelection selection) {
- if (selection.isEmpty())
- return null;
- if (selection.size() == 1) {
- try {
- final IType type= RefactoringAvailabilityTester.getSingleSelectedType(selection);
- if (type != null)
- return new IType[] { type};
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- if (!(iter.next() instanceof IMember))
- return null;
- }
- Set memberSet= new HashSet();
- memberSet.addAll(Arrays.asList(selection.toArray()));
- return (IMember[]) memberSet.toArray(new IMember[memberSet.size()]);
- }
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- *
- * @param editor
- * the JavaScript editor
- */
- public PullUpAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new <code>PullUpAction</code>. The action requires that the
- * selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site
- * the site providing context information for this action
- */
- public PullUpAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.RefactoringGroup_pull_Up_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.PULL_UP_ACTION);
- }
-
- private IMember getSelectedMemberFromEditor() throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.resolveEnclosingElement(fEditor, (ITextSelection) fEditor.getSelectionProvider().getSelection());
- if (element == null || !(element instanceof IMember))
- return null;
- return (IMember) element;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(IStructuredSelection selection) {
- try {
- IMember[] members= getSelectedMembers(selection);
- if (RefactoringAvailabilityTester.isPullUpAvailable(members) && ActionUtil.isEditable(getShell(), members[0]))
- RefactoringExecutionStarter.startPullUpRefactoring(members, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(ITextSelection selection) {
- try {
- if (!ActionUtil.isEditable(fEditor))
- return;
- IMember member= getSelectedMemberFromEditor();
- IMember[] array= new IMember[] { member};
- if (member != null && RefactoringAvailabilityTester.isPullUpAvailable(array)) {
- RefactoringExecutionStarter.startPullUpRefactoring(array, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.PullUpAction_unavailable);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isPullUpAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);// no UI
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this
- * method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isPullUpAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PushDownAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PushDownAction.java
deleted file mode 100644
index 56978a08..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/PushDownAction.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to push down methods and fields into subclasses.
- * <p>
- * Action is applicable to selections containing elements of type
- * <code>IField</code> and <code>IFunction</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class PushDownAction extends SelectionDispatchAction {
-
- private static IMember[] getSelectedMembers(IStructuredSelection selection) {
- if (selection.isEmpty())
- return null;
- if (selection.size() == 1) {
- try {
- final IType type= RefactoringAvailabilityTester.getSingleSelectedType(selection);
- if (type != null)
- return new IType[] { type};
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- }
- }
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- if (!(iter.next() instanceof IMember))
- return null;
- }
- Set memberSet= new HashSet();
- memberSet.addAll(Arrays.asList(selection.toArray()));
- return (IMember[]) memberSet.toArray(new IMember[memberSet.size()]);
- }
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call
- * this constructor.
- *
- * @param editor the JavaScript editor
- */
- public PushDownAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new <code>PushDownAction</code>. The action requires that
- * the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site
- * the site providing context information for this action
- */
- public PushDownAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.PushDownAction_Push_Down);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.PUSH_DOWN_ACTION);
- }
-
- private IMember getSelectedMemberFromEditor() throws JavaScriptModelException {
- IJavaScriptElement element= SelectionConverter.resolveEnclosingElement(fEditor, (ITextSelection) fEditor.getSelectionProvider().getSelection());
- if (element == null || !(element instanceof IMember))
- return null;
- return (IMember) element;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(IStructuredSelection selection) {
- try {
- IMember[] members= getSelectedMembers(selection);
- if (RefactoringAvailabilityTester.isPushDownAvailable(members) && ActionUtil.isEditable(getShell(), members[0]))
- RefactoringExecutionStarter.startPushDownRefactoring(members, getShell());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void run(ITextSelection selection) {
- try {
- if (!ActionUtil.isEditable(fEditor))
- return;
- IMember member= getSelectedMemberFromEditor();
- IMember[] array= new IMember[] { member};
- if (member != null && RefactoringAvailabilityTester.isPushDownAvailable(array)) {
- RefactoringExecutionStarter.startPushDownRefactoring(array, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.PushDownAction_To_activate);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isPushDownAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);// no UI
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this
- * method.
- *
- * @param selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isPushDownAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java
deleted file mode 100644
index e37e4d99..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the search for read references actions to a
- * context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ReadReferencesSearchGroup extends ActionGroup {
-
- private static final String MENU_TEXT= SearchMessages.group_readReferences;
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindReadReferencesAction fFindReadReferencesAction;
- private FindReadReferencesInProjectAction fFindReadReferencesInProjectAction;
- private FindReadReferencesInHierarchyAction fFindReadReferencesInHierarchyAction;
- private FindReadReferencesInWorkingSetAction fFindReadReferencesInWorkingSetAction;
-
- /**
- * Creates a new <code>ReadReferencesSearchGroup</code>. The group requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public ReadReferencesSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fFindReadReferencesAction= new FindReadReferencesAction(site);
- fFindReadReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKSPACE);
-
- fFindReadReferencesInProjectAction= new FindReadReferencesInProjectAction(site);
- fFindReadReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_READ_ACCESS_IN_PROJECT);
-
- fFindReadReferencesInHierarchyAction= new FindReadReferencesInHierarchyAction(site);
- fFindReadReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_HIERARCHY);
-
- fFindReadReferencesInWorkingSetAction= new FindReadReferencesInWorkingSetAction(site);
- fFindReadReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKING_SET);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fFindReadReferencesAction, provider, selection);
- registerAction(fFindReadReferencesInProjectAction, provider, selection);
- registerAction(fFindReadReferencesInHierarchyAction, provider, selection);
- registerAction(fFindReadReferencesInWorkingSetAction, provider, selection);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ReadReferencesSearchGroup(JavaEditor editor) {
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fFindReadReferencesAction= new FindReadReferencesAction(fEditor);
- fFindReadReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKSPACE);
- fEditor.setAction("SearchReadAccessInWorkspace", fFindReadReferencesAction); //$NON-NLS-1$
-
- fFindReadReferencesInProjectAction= new FindReadReferencesInProjectAction(fEditor);
- fFindReadReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_READ_ACCESS_IN_PROJECT);
- fEditor.setAction("SearchReadAccessInProject", fFindReadReferencesInProjectAction); //$NON-NLS-1$
-
- fFindReadReferencesInHierarchyAction= new FindReadReferencesInHierarchyAction(fEditor);
- fFindReadReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_HIERARCHY);
- fEditor.setAction("SearchReadAccessInHierarchy", fFindReadReferencesInHierarchyAction); //$NON-NLS-1$
-
- fFindReadReferencesInWorkingSetAction= new FindReadReferencesInWorkingSetAction(fEditor);
- fFindReadReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKING_SET);
- fEditor.setAction("SearchReadAccessInWorkingSet", fFindReadReferencesInWorkingSetAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection) {
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- private void addAction(IAction action, IMenuManager manager) {
- if (action.isEnabled()) {
- manager.add(action);
- }
- }
-
- private void addWorkingSetAction(IWorkingSet[] workingSets, IMenuManager manager) {
- FindAction action;
- if (fEditor != null)
- action= new WorkingSetFindAction(fEditor, new FindReadReferencesInWorkingSetAction(fEditor, workingSets), SearchUtil.toString(workingSets));
- else
- action= new WorkingSetFindAction(fSite, new FindReadReferencesInWorkingSetAction(fSite, workingSets), SearchUtil.toString(workingSets));
- action.update(getContext().getSelection());
- addAction(action, manager);
- }
-
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- MenuManager javaSearchMM= new MenuManager(MENU_TEXT, IContextMenuConstants.GROUP_SEARCH);
- addAction(fFindReadReferencesAction, javaSearchMM);
- addAction(fFindReadReferencesInProjectAction, javaSearchMM);
- addAction(fFindReadReferencesInHierarchyAction, javaSearchMM);
-
- javaSearchMM.add(new Separator());
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- addWorkingSetAction((IWorkingSet[]) iter.next(), javaSearchMM);
- }
- addAction(fFindReadReferencesInWorkingSetAction, javaSearchMM);
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindReadReferencesAction, provider);
- disposeAction(fFindReadReferencesInProjectAction, provider);
- disposeAction(fFindReadReferencesInHierarchyAction, provider);
- disposeAction(fFindReadReferencesInWorkingSetAction, provider);
- }
- fFindReadReferencesAction= null;
- fFindReadReferencesInProjectAction= null;
- fFindReadReferencesInHierarchyAction= null;
- fFindReadReferencesInWorkingSetAction= null;
- updateGlobalActionHandlers();
- super.dispose();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_READ_ACCESS_IN_WORKSPACE, fFindReadReferencesAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_READ_ACCESS_IN_PROJECT, fFindReadReferencesInProjectAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_READ_ACCESS_IN_HIERARCHY, fFindReadReferencesInHierarchyAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_READ_ACCESS_IN_WORKING_SET, fFindReadReferencesInWorkingSetAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefactorActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefactorActionGroup.java
deleted file mode 100644
index 1506ca0a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefactorActionGroup.java
+++ /dev/null
@@ -1,670 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.commands.operations.IUndoContext;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.PerformanceStats;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.commands.ActionHandler;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.handlers.IHandlerActivation;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.operations.UndoRedoActionGroup;
-import org.eclipse.ui.part.Page;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.ExtractSuperClassAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.JDTQuickMenuAction;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds refactor actions (for example 'Rename', 'Move')
- * to a context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class RefactorActionGroup extends ActionGroup {
-
- private static final String PERF_REFACTOR_ACTION_GROUP= "org.eclipse.wst.jsdt.ui/perf/explorer/RefactorActionGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the refactor sub menu (value <code>org.eclipse.wst.jsdt.ui.refactoring.menu</code>).
- *
- *
- */
- public static final String MENU_ID= "org.eclipse.wst.jsdt.ui.refactoring.menu"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the reorg group of the refactor sub menu (value
- * <code>reorgGroup</code>).
- *
- *
- */
- public static final String GROUP_REORG= "reorgGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the type group of the refactor sub menu (value
- * <code>typeGroup</code>).
- *
- *
- */
- public static final String GROUP_TYPE= "typeGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the coding group of the refactor sub menu (value
- * <code>codingGroup</code>).
- *
- *
- */
- public static final String GROUP_CODING= "codingGroup"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the coding group 2 of the refactor sub menu (value
- * <code>codingGroup2</code>).
- *
- *
- */
- public static final String GROUP_CODING2= "codingGroup2"; //$NON-NLS-1$
-
- /**
- * Pop-up menu: id of the reorg group 2 of the refactor sub menu (value
- * <code>reorgGroup2</code>).
- *
- *
- */
- private static final String GROUP_REORG2= "reorgGroup2"; //$NON-NLS-1$ //TODO(3.3): make public
-
- /**
- * Pop-up menu: id of the type group 2 of the refactor sub menu (value
- * <code>typeGroup2</code>).
- *
- *
- */
- private static final String GROUP_TYPE2= "typeGroup2"; //$NON-NLS-1$ //TODO(3.3): make public
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE;
- private boolean fBinary= false;
-
- private SelectionDispatchAction fMoveAction;
- private SelectionDispatchAction fRenameAction;
- private SelectionDispatchAction fModifyParametersAction;
-// private SelectionDispatchAction fConvertAnonymousToNestedAction;
-// private SelectionDispatchAction fConvertNestedToTopAction;
-
- private SelectionDispatchAction fPullUpAction;
- private SelectionDispatchAction fPushDownAction;
-// private SelectionDispatchAction fExtractInterfaceAction;
- private SelectionDispatchAction fExtractSupertypeAction;
-// private SelectionDispatchAction fChangeTypeAction;
- private SelectionDispatchAction fUseSupertypeAction;
-
- private SelectionDispatchAction fInlineAction;
-// private SelectionDispatchAction fReplaceInvocationsAction;
- private SelectionDispatchAction fIntroduceIndirectionAction;
- private SelectionDispatchAction fExtractMethodAction;
- private SelectionDispatchAction fExtractTempAction;
- private SelectionDispatchAction fExtractConstantAction;
- private SelectionDispatchAction fIntroduceParameterAction;
- private SelectionDispatchAction fIntroduceFactoryAction;
- private SelectionDispatchAction fConvertLocalToFieldAction;
- private SelectionDispatchAction fSelfEncapsulateField;
-
- private UndoRedoActionGroup fUndoRedoActionGroup;
-
- private final List fActions= new ArrayList();
-
- private static final String QUICK_MENU_ID= "org.eclipse.wst.jsdt.ui.edit.text.java.refactor.quickMenu"; //$NON-NLS-1$
-
- private class RefactorQuickAccessAction extends JDTQuickMenuAction {
- public RefactorQuickAccessAction(JavaEditor editor) {
- super(editor, QUICK_MENU_ID);
- }
- protected void fillMenu(IMenuManager menu) {
- fillQuickMenu(menu);
- }
- }
-
- private JDTQuickMenuAction fQuickAccessAction;
- private IHandlerActivation fQuickAccessHandlerActivation;
- private IHandlerService fHandlerService;
-
- private static class NoActionAvailable extends Action {
- public NoActionAvailable() {
- setEnabled(true);
- setText(RefactoringMessages.RefactorActionGroup_no_refactoring_available);
- }
- }
- private Action fNoActionAvailable= new NoActionAvailable();
-
- /**
- * Creates a new <code>RefactorActionGroup</code>. The group requires
- * that the selection provided by the part's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public RefactorActionGroup(IViewPart part) {
- this(part.getSite());
-
- IUndoContext workspaceContext= (IUndoContext)ResourcesPlugin.getWorkspace().getAdapter(IUndoContext.class);
- fUndoRedoActionGroup= new UndoRedoActionGroup(part.getViewSite(), workspaceContext, true);
- }
-
- /**
- * Creates a new <code>RefactorActionGroup</code>. The action requires
- * that the selection provided by the page's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page that owns this action group
- */
- public RefactorActionGroup(Page page) {
- this(page.getSite());
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- * @param groupName the group name to add the actions to
- * @param binary <code>true</code> if the action group is used in a binary environment, <code>false</code> otherwise
- */
- public RefactorActionGroup(JavaEditor editor, String groupName, boolean binary) {
-
- final PerformanceStats stats= PerformanceStats.getStats(PERF_REFACTOR_ACTION_GROUP, this);
- stats.startRun();
-
- fSite= editor.getEditorSite();
- fEditor= editor;
- fGroupName= groupName;
- fBinary= binary;
-
- ISelectionProvider provider= editor.getSelectionProvider();
- ISelection selection= provider.getSelection();
-
- if (!fBinary) {
- fRenameAction= new RenameAction(editor);
- initAction(fRenameAction, selection, IJavaEditorActionDefinitionIds.RENAME_ELEMENT);
- editor.setAction("RenameElement", fRenameAction); //$NON-NLS-1$
-
- fMoveAction= new MoveAction(editor);
- initAction(fMoveAction, selection, IJavaEditorActionDefinitionIds.MOVE_ELEMENT);
- editor.setAction("MoveElement", fMoveAction); //$NON-NLS-1$
-
- fModifyParametersAction= new ModifyParametersAction(editor);
- initAction(fModifyParametersAction, selection, IJavaEditorActionDefinitionIds.MODIFY_METHOD_PARAMETERS);
- editor.setAction("ModifyParameters", fModifyParametersAction); //$NON-NLS-1$
-
-// fConvertAnonymousToNestedAction= new ConvertAnonymousToNestedAction(editor);
-// initUpdatingAction(fConvertAnonymousToNestedAction, provider, selection, IJavaEditorActionDefinitionIds.CONVERT_ANONYMOUS_TO_NESTED);
-// editor.setAction("ConvertAnonymousToNested", fConvertAnonymousToNestedAction); //$NON-NLS-1$
-//
-// fConvertNestedToTopAction= new ConvertNestedToTopAction(editor);
-// initAction(fConvertNestedToTopAction, selection, IJavaEditorActionDefinitionIds.MOVE_INNER_TO_TOP);
-// editor.setAction("MoveInnerToTop", fConvertNestedToTopAction); //$NON-NLS-1$
-
- if (IUIConstants.SUPPORT_REFACTORING)
- {
- fPullUpAction= new PullUpAction(editor);
- initAction(fPullUpAction, selection, IJavaEditorActionDefinitionIds.PULL_UP);
- editor.setAction("PullUp", fPullUpAction); //$NON-NLS-1$
-
- fPushDownAction= new PushDownAction(editor);
- initAction(fPushDownAction, selection, IJavaEditorActionDefinitionIds.PUSH_DOWN);
- editor.setAction("PushDown", fPushDownAction); //$NON-NLS-1$
-
- fExtractSupertypeAction= new ExtractSuperClassAction(editor);
- initAction(fExtractSupertypeAction, selection, ExtractSuperClassAction.EXTRACT_SUPERTYPE);
- editor.setAction("ExtractSupertype", fExtractSupertypeAction); //$NON-NLS-1$
-
- }
-
- fExtractMethodAction= new ExtractMethodAction(editor);
- initUpdatingAction(fExtractMethodAction, provider, selection, IJavaEditorActionDefinitionIds.EXTRACT_METHOD);
- editor.setAction("ExtractMethod", fExtractMethodAction); //$NON-NLS-1$
-
- fExtractTempAction= new ExtractTempAction(editor);
- initUpdatingAction(fExtractTempAction, provider, selection, IJavaEditorActionDefinitionIds.EXTRACT_LOCAL_VARIABLE);
- editor.setAction("ExtractLocalVariable", fExtractTempAction); //$NON-NLS-1$
-
- fExtractConstantAction= new ExtractConstantAction(editor);
- initUpdatingAction(fExtractConstantAction, provider, selection, IJavaEditorActionDefinitionIds.EXTRACT_CONSTANT);
- editor.setAction("ExtractConstant", fExtractConstantAction); //$NON-NLS-1$
-
- fIntroduceParameterAction= new IntroduceParameterAction(editor);
- initUpdatingAction(fIntroduceParameterAction, provider, selection, IJavaEditorActionDefinitionIds.INTRODUCE_PARAMETER);
- editor.setAction("IntroduceParameter", fIntroduceParameterAction); //$NON-NLS-1$
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fIntroduceFactoryAction = new IntroduceFactoryAction(editor);
- initUpdatingAction(fIntroduceFactoryAction, provider,
- selection,
- IJavaEditorActionDefinitionIds.INTRODUCE_FACTORY);
- editor.setAction("IntroduceFactory", fIntroduceFactoryAction); //$NON-NLS-1$
- fConvertLocalToFieldAction = new ConvertLocalToFieldAction(
- editor);
- initUpdatingAction(fConvertLocalToFieldAction, provider,
- selection,
- IJavaEditorActionDefinitionIds.PROMOTE_LOCAL_VARIABLE);
- editor.setAction("PromoteTemp", fConvertLocalToFieldAction); //$NON-NLS-1$
- fSelfEncapsulateField = new SelfEncapsulateFieldAction(editor);
- initAction(fSelfEncapsulateField, selection,
- IJavaEditorActionDefinitionIds.SELF_ENCAPSULATE_FIELD);
- editor.setAction("SelfEncapsulateField", fSelfEncapsulateField); //$NON-NLS-1$
- }
- }
- if (IUIConstants.SUPPORT_REFACTORING) {
- fIntroduceIndirectionAction = new IntroduceIndirectionAction(editor);
- initUpdatingAction(fIntroduceIndirectionAction, provider,
- selection,
- IJavaEditorActionDefinitionIds.INTRODUCE_INDIRECTION);
- editor.setAction(
- "IntroduceIndirection", fIntroduceIndirectionAction); //$NON-NLS-1$
- fUseSupertypeAction = new UseSupertypeAction(editor);
- initAction(fUseSupertypeAction, selection,
- IJavaEditorActionDefinitionIds.USE_SUPERTYPE);
- editor.setAction("UseSupertype", fUseSupertypeAction); //$NON-NLS-1$
- }
- fInlineAction= new InlineAction(editor);
- initAction(fInlineAction, selection, IJavaEditorActionDefinitionIds.INLINE);
- editor.setAction("Inline", fInlineAction); //$NON-NLS-1$
-
- installQuickAccessAction();
-
- stats.endRun();
- }
-
- private RefactorActionGroup(IWorkbenchSite site) {
-
- final PerformanceStats stats= PerformanceStats.getStats(PERF_REFACTOR_ACTION_GROUP, this);
- stats.startRun();
-
- fSite= site;
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
-
- if (!fBinary) {
-
- fMoveAction= new MoveAction(site);
- initUpdatingAction(fMoveAction, provider, selection, IJavaEditorActionDefinitionIds.MOVE_ELEMENT);
-
- fRenameAction= new RenameAction(site);
- initUpdatingAction(fRenameAction, provider, selection, IJavaEditorActionDefinitionIds.RENAME_ELEMENT);
-
- fModifyParametersAction= new ModifyParametersAction(fSite);
- initUpdatingAction(fModifyParametersAction, provider, selection, IJavaEditorActionDefinitionIds.MODIFY_METHOD_PARAMETERS);
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fPullUpAction = new PullUpAction(fSite);
- initUpdatingAction(fPullUpAction, provider, selection,
- IJavaEditorActionDefinitionIds.PULL_UP);
- fPushDownAction = new PushDownAction(fSite);
- initUpdatingAction(fPushDownAction, provider, selection,
- IJavaEditorActionDefinitionIds.PUSH_DOWN);
- fSelfEncapsulateField = new SelfEncapsulateFieldAction(fSite);
- initUpdatingAction(fSelfEncapsulateField, provider, selection,
- IJavaEditorActionDefinitionIds.SELF_ENCAPSULATE_FIELD);
- fExtractSupertypeAction = new ExtractSuperClassAction(fSite);
- initUpdatingAction(fExtractSupertypeAction, provider,
- selection, ExtractSuperClassAction.EXTRACT_SUPERTYPE);
- fIntroduceFactoryAction = new IntroduceFactoryAction(fSite);
- initUpdatingAction(fIntroduceFactoryAction, provider,
- selection,
- IJavaEditorActionDefinitionIds.INTRODUCE_FACTORY);
- }
-
-// fConvertAnonymousToNestedAction= new ConvertAnonymousToNestedAction(fSite);
-// initUpdatingAction(fConvertAnonymousToNestedAction, provider, selection, IJavaEditorActionDefinitionIds.CONVERT_ANONYMOUS_TO_NESTED);
- }
- fInlineAction= new InlineAction(fSite);
- initUpdatingAction(fInlineAction, provider, selection, IJavaEditorActionDefinitionIds.INLINE);
-
- if (IUIConstants.SUPPORT_REFACTORING) {
- fUseSupertypeAction = new UseSupertypeAction(fSite);
- initUpdatingAction(fUseSupertypeAction, provider, selection,
- IJavaEditorActionDefinitionIds.USE_SUPERTYPE);
- fIntroduceIndirectionAction = new IntroduceIndirectionAction(fSite);
- initUpdatingAction(fIntroduceIndirectionAction, provider,
- selection,
- IJavaEditorActionDefinitionIds.INTRODUCE_INDIRECTION);
- }
- installQuickAccessAction();
-
- stats.endRun();
- }
-
- private void installQuickAccessAction() {
- fHandlerService= (IHandlerService)fSite.getService(IHandlerService.class);
- if (fHandlerService != null) {
- fQuickAccessAction= new RefactorQuickAccessAction(fEditor);
- fQuickAccessHandlerActivation= fHandlerService.activateHandler(fQuickAccessAction.getActionDefinitionId(), new ActionHandler(fQuickAccessAction));
- }
- }
-
- private void initAction(SelectionDispatchAction action, ISelection selection, String actionDefinitionId){
- initUpdatingAction(action, null, selection, actionDefinitionId);
- }
-
- /**
- * Sets actionDefinitionId, updates enablement, adds to fActions,
- * and adds selection changed listener if provider is not <code>null</code>.
- *
- * @param action
- * @param provider can be <code>null</code>
- * @param selection
- * @param actionDefinitionId
- */
- private void initUpdatingAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection, String actionDefinitionId){
- action.setActionDefinitionId(actionDefinitionId);
- action.update(selection);
- if (provider != null)
- provider.addSelectionChangedListener(action);
- fActions.add(action);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBars) {
- super.fillActionBars(actionBars);
- if (!fBinary) {
- if (IUIConstants.SUPPORT_REFACTORING)
- actionBars.setGlobalActionHandler(JdtActionConstants.SELF_ENCAPSULATE_FIELD, fSelfEncapsulateField);
- actionBars.setGlobalActionHandler(JdtActionConstants.MOVE, fMoveAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.RENAME, fRenameAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.MODIFY_PARAMETERS, fModifyParametersAction);
- if (IUIConstants.SUPPORT_REFACTORING) {
- actionBars.setGlobalActionHandler(JdtActionConstants.PULL_UP,
- fPullUpAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.PUSH_DOWN,
- fPushDownAction);
- }
- actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_TEMP, fExtractTempAction);
- if (IUIConstants.SUPPORT_REFACTORING) {
- actionBars.setGlobalActionHandler(
- JdtActionConstants.EXTRACT_CONSTANT,
- fExtractConstantAction);
- actionBars.setGlobalActionHandler(
- JdtActionConstants.INTRODUCE_PARAMETER,
- fIntroduceParameterAction);
- actionBars.setGlobalActionHandler(
- JdtActionConstants.INTRODUCE_FACTORY,
- fIntroduceFactoryAction);
- }
- actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_METHOD, fExtractMethodAction);
- // actionBars.setGlobalActionHandler(JdtActionConstants.REPLACE_INVOCATIONS, fReplaceInvocationsAction);
-// actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_INTERFACE, fExtractInterfaceAction);
- if (IUIConstants.SUPPORT_REFACTORING) {
- actionBars.setGlobalActionHandler(ExtractSuperClassAction.EXTRACT_SUPERTYPES, fExtractSupertypeAction);
- // actionBars.setGlobalActionHandler(JdtActionConstants.CHANGE_TYPE, fChangeTypeAction);
- // actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_NESTED_TO_TOP, fConvertNestedToTopAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_LOCAL_TO_FIELD, fConvertLocalToFieldAction);
- // actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_ANONYMOUS_TO_NESTED, fConvertAnonymousToNestedAction);
- }
- }
- if (IUIConstants.SUPPORT_REFACTORING) {
- actionBars.setGlobalActionHandler(JdtActionConstants.INLINE, fInlineAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.USE_SUPERTYPE, fUseSupertypeAction);
- actionBars.setGlobalActionHandler(JdtActionConstants.INTRODUCE_INDIRECTION, fIntroduceIndirectionAction);
- }
- if (fUndoRedoActionGroup != null) {
- fUndoRedoActionGroup.fillActionBars(actionBars);
- }
- }
-
- /**
- * Retargets the File actions with the corresponding refactoring actions.
- *
- * @param actionBars the action bar to register the move and rename action with
- */
- public void retargetFileMenuActions(IActionBars actionBars) {
- actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), fRenameAction);
- actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), fMoveAction);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- addRefactorSubmenu(menu);
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (!fBinary) {
- disposeAction(fMoveAction, provider);
- disposeAction(fRenameAction, provider);
- disposeAction(fExtractTempAction, provider);
- disposeAction(fIntroduceParameterAction, provider);
- disposeAction(fExtractMethodAction, provider);
- if (IUIConstants.SUPPORT_REFACTORING) {
- disposeAction(fSelfEncapsulateField, provider);
- disposeAction(fModifyParametersAction, provider);
- disposeAction(fPullUpAction, provider);
- disposeAction(fPushDownAction, provider);
- disposeAction(fExtractConstantAction, provider);
- disposeAction(fIntroduceFactoryAction, provider);
- // disposeAction(fReplaceInvocationsAction, provider);
- // disposeAction(fExtractInterfaceAction, provider);
- disposeAction(fExtractSupertypeAction, provider);
- // disposeAction(fChangeTypeAction, provider);
- // disposeAction(fConvertNestedToTopAction, provider);
- disposeAction(fConvertLocalToFieldAction, provider);
- // disposeAction(fConvertAnonymousToNestedAction, provider);
- }
- }
- if (IUIConstants.SUPPORT_REFACTORING) {
- disposeAction(fIntroduceIndirectionAction, provider);
- disposeAction(fInlineAction, provider);
- disposeAction(fUseSupertypeAction, provider);
- }
- if (fQuickAccessHandlerActivation != null && fHandlerService != null) {
- fHandlerService.deactivateHandler(fQuickAccessHandlerActivation);
- }
- if (fUndoRedoActionGroup != null) {
- fUndoRedoActionGroup.dispose();
- }
- super.dispose();
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-
- private void addRefactorSubmenu(IMenuManager menu) {
- String menuText= ActionMessages.RefactorMenu_label;
- if (fQuickAccessAction != null) {
- menuText= fQuickAccessAction.addShortcut(menuText);
- }
- IMenuManager refactorSubmenu= new MenuManager(menuText, MENU_ID);
- if (fEditor != null) {
- IJavaScriptElement element= SelectionConverter.getInput(fEditor);
- if (element != null && ActionUtil.isOnBuildPath(element)) {
- refactorSubmenu.addMenuListener(new IMenuListener() {
- public void menuAboutToShow(IMenuManager manager) {
- refactorMenuShown(manager);
- }
- });
- refactorSubmenu.add(fNoActionAvailable);
- menu.appendToGroup(fGroupName, refactorSubmenu);
- }
- } else {
- ISelection selection= fSite.getSelectionProvider().getSelection();
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- ((SelectionDispatchAction)iter.next()).update(selection);
- }
- if (fillRefactorMenu(refactorSubmenu) > 0)
- menu.appendToGroup(fGroupName, refactorSubmenu);
- }
- }
-
- private int fillRefactorMenu(IMenuManager refactorSubmenu) {
- int added= 0;
- refactorSubmenu.add(new Separator(GROUP_REORG));
- added+= addAction(refactorSubmenu, fRenameAction);
- added+= addAction(refactorSubmenu, fMoveAction);
- refactorSubmenu.add(new Separator(GROUP_CODING));
- added+= addAction(refactorSubmenu, fModifyParametersAction);
- added+= addAction(refactorSubmenu, fExtractMethodAction);
- added+= addAction(refactorSubmenu, fExtractTempAction);
- if (IUIConstants.SUPPORT_REFACTORING) {
- added += addAction(refactorSubmenu, fExtractConstantAction);
- added += addAction(refactorSubmenu, fInlineAction);
- refactorSubmenu.add(new Separator(GROUP_REORG2));
- // added+= addAction(refactorSubmenu, fConvertAnonymousToNestedAction);
- // added+= addAction(refactorSubmenu, fConvertNestedToTopAction);
- added += addAction(refactorSubmenu, fConvertLocalToFieldAction);
- refactorSubmenu.add(new Separator(GROUP_TYPE));
- // added+= addAction(refactorSubmenu, fExtractInterfaceAction);
- added += addAction(refactorSubmenu, fExtractSupertypeAction);
- added += addAction(refactorSubmenu, fUseSupertypeAction);
- added += addAction(refactorSubmenu, fPullUpAction);
- added += addAction(refactorSubmenu, fPushDownAction);
- }
- refactorSubmenu.add(new Separator(GROUP_CODING2));
- if (IUIConstants.SUPPORT_REFACTORING) {
- added += addAction(refactorSubmenu, fIntroduceIndirectionAction);
- added += addAction(refactorSubmenu, fIntroduceFactoryAction);
- }
- added+= addAction(refactorSubmenu, fIntroduceParameterAction);
- if (IUIConstants.SUPPORT_REFACTORING)
- added+= addAction(refactorSubmenu, fSelfEncapsulateField);
-// added+= addAction(refactorSubmenu, fReplaceInvocationsAction);
- if (IUIConstants.SUPPORT_REFACTORING) {
- refactorSubmenu.add(new Separator(GROUP_TYPE2));
- }
- return added;
- }
-
- private int addAction(IMenuManager menu, IAction action) {
- if (action != null && action.isEnabled()) {
- menu.add(action);
- return 1;
- }
- return 0;
- }
-
- private void refactorMenuShown(final IMenuManager refactorSubmenu) {
- // we know that we have an MenuManager since we created it in
- // addRefactorSubmenu.
- Menu menu= ((MenuManager)refactorSubmenu).getMenu();
- menu.addMenuListener(new MenuAdapter() {
- public void menuHidden(MenuEvent e) {
- refactorMenuHidden(refactorSubmenu);
- }
- });
- ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection();
- JavaTextSelection javaSelection= new JavaTextSelection(
- getEditorInput(), getDocument(), textSelection.getOffset(), textSelection.getLength());
-
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- SelectionDispatchAction action= (SelectionDispatchAction)iter.next();
- action.update(javaSelection);
- }
- refactorSubmenu.removeAll();
- if (fillRefactorMenu(refactorSubmenu) == 0)
- refactorSubmenu.add(fNoActionAvailable);
- }
-
- private void refactorMenuHidden(IMenuManager manager) {
- ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection();
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- SelectionDispatchAction action= (SelectionDispatchAction)iter.next();
- action.update(textSelection);
- }
- }
-
- private IJavaScriptElement getEditorInput() {
- final IEditorInput input= fEditor.getEditorInput();
- if (input instanceof IClassFileEditorInput) {
- IClassFileEditorInput extended= (IClassFileEditorInput) input;
- return extended.getClassFile();
- }
- return JavaScriptPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(input);
- }
-
- private IDocument getDocument() {
- return JavaScriptPlugin.getDefault().getCompilationUnitDocumentProvider().
- getDocument(fEditor.getEditorInput());
- }
-
- private void fillQuickMenu(IMenuManager menu) {
- if (fEditor != null) {
- IJavaScriptElement element= SelectionConverter.getInput(fEditor);
- if (element == null || !ActionUtil.isOnBuildPath(element)) {
- menu.add(fNoActionAvailable);
- return;
- }
- ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection();
- JavaTextSelection javaSelection= new JavaTextSelection(
- getEditorInput(), getDocument(), textSelection.getOffset(), textSelection.getLength());
-
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- ((SelectionDispatchAction)iter.next()).update(javaSelection);
- }
- fillRefactorMenu(menu);
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- ((SelectionDispatchAction)iter.next()).update(textSelection);
- }
-
- } else {
- ISelection selection= fSite.getSelectionProvider().getSelection();
- for (Iterator iter= fActions.iterator(); iter.hasNext(); ) {
- ((SelectionDispatchAction)iter.next()).update(selection);
- }
- fillRefactorMenu(menu);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java
deleted file mode 100644
index 8c62ce09..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the search for references actions to a
- * context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ReferencesSearchGroup extends ActionGroup {
-
- private static final String MENU_TEXT= SearchMessages.group_references;
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindReferencesAction fFindReferencesAction;
- private FindReferencesInProjectAction fFindReferencesInProjectAction;
- private FindReferencesInHierarchyAction fFindReferencesInHierarchyAction;
- private FindReferencesInWorkingSetAction fFindReferencesInWorkingSetAction;
-
- /**
- * Creates a new <code>ReferencesSearchGroup</code>. The group requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public ReferencesSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fFindReferencesAction= new FindReferencesAction(site);
- fFindReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_WORKSPACE);
-
- fFindReferencesInProjectAction= new FindReferencesInProjectAction(site);
- fFindReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_PROJECT);
-
- fFindReferencesInHierarchyAction= new FindReferencesInHierarchyAction(site);
- fFindReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_HIERARCHY);
-
- fFindReferencesInWorkingSetAction= new FindReferencesInWorkingSetAction(site);
- fFindReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_WORKING_SET);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fFindReferencesAction, provider, selection);
- registerAction(fFindReferencesInProjectAction, provider, selection);
- registerAction(fFindReferencesInHierarchyAction, provider, selection);
- registerAction(fFindReferencesInWorkingSetAction, provider, selection);
- }
-
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ReferencesSearchGroup(JavaEditor editor) {
- Assert.isNotNull(editor);
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fFindReferencesAction= new FindReferencesAction(editor);
- fFindReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_WORKSPACE);
- fEditor.setAction("SearchReferencesInWorkspace", fFindReferencesAction); //$NON-NLS-1$
-
- fFindReferencesInProjectAction= new FindReferencesInProjectAction(fEditor);
- fFindReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_PROJECT);
- fEditor.setAction("SearchReferencesInProject", fFindReferencesInProjectAction); //$NON-NLS-1$
-
- fFindReferencesInHierarchyAction= new FindReferencesInHierarchyAction(fEditor);
- fFindReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_HIERARCHY);
- fEditor.setAction("SearchReferencesInHierarchy", fFindReferencesInHierarchyAction); //$NON-NLS-1$
-
- fFindReferencesInWorkingSetAction= new FindReferencesInWorkingSetAction(fEditor);
- fFindReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_REFERENCES_IN_WORKING_SET);
- fEditor.setAction("SearchReferencesInWorkingSet", fFindReferencesInWorkingSetAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection) {
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- /**
- * Note: this method is for internal use only. Clients should not call this method.
- *
- * @return the menu label
- */
- protected String getName() {
- return MENU_TEXT;
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
-
- private void addAction(IAction action, IMenuManager manager) {
- if (action.isEnabled()) {
- manager.add(action);
- }
- }
-
- private void addWorkingSetAction(IWorkingSet[] workingSets, IMenuManager manager) {
- FindAction action;
- if (fEditor != null)
- action= new WorkingSetFindAction(fEditor, new FindReferencesInWorkingSetAction(fEditor, workingSets), SearchUtil.toString(workingSets));
- else
- action= new WorkingSetFindAction(fSite, new FindReferencesInWorkingSetAction(fSite, workingSets), SearchUtil.toString(workingSets));
- action.update(getContext().getSelection());
- addAction(action, manager);
- }
-
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- MenuManager javaSearchMM= new MenuManager(getName(), IContextMenuConstants.GROUP_SEARCH);
- addAction(fFindReferencesAction, javaSearchMM);
- addAction(fFindReferencesInProjectAction, javaSearchMM);
- addAction(fFindReferencesInHierarchyAction, javaSearchMM);
-
- javaSearchMM.add(new Separator());
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- addWorkingSetAction((IWorkingSet[]) iter.next(), javaSearchMM);
- }
- addAction(fFindReferencesInWorkingSetAction, javaSearchMM);
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
- /*
- * Overrides method declared in ActionGroup
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindReferencesAction, provider);
- disposeAction(fFindReferencesInProjectAction, provider);
- disposeAction(fFindReferencesInHierarchyAction, provider);
- disposeAction(fFindReferencesInWorkingSetAction, provider);
- }
- fFindReferencesAction= null;
- fFindReferencesInProjectAction= null;
- fFindReferencesInHierarchyAction= null;
- fFindReferencesInWorkingSetAction= null;
- updateGlobalActionHandlers();
- super.dispose();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_REFERENCES_IN_WORKSPACE, fFindReferencesAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_REFERENCES_IN_PROJECT, fFindReferencesInProjectAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_REFERENCES_IN_HIERARCHY, fFindReferencesInHierarchyAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_REFERENCES_IN_WORKING_SET, fFindReferencesInWorkingSetAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefreshAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefreshAction.java
deleted file mode 100644
index 0c3a3ffa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RefreshAction.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action for refreshing the workspace from the local file system for
- * the selected resources and all of their descendants. This action
- * also considers external Jars managed by the JavaScript Model.
- * <p>
- * Action is applicable to selections containing resources and Java
- * elements down to compilation units.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class RefreshAction extends SelectionDispatchAction {
-
- /**
- * Creates a new <code>RefreshAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public RefreshAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.RefreshAction_label);
- setToolTipText(ActionMessages.RefreshAction_toolTip);
- JavaPluginImages.setLocalImageDescriptors(this, "refresh_nav.gif");//$NON-NLS-1$
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.REFRESH_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(checkEnabled(selection));
- }
-
- private boolean checkEnabled(IStructuredSelection selection) {
- if (selection.isEmpty())
- return true;
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (element instanceof IWorkingSet) {
- // don't inspect working sets any deeper.
- } else if (element instanceof IAdaptable) {
- IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class);
- if (resource == null)
- return false;
- if (resource.getType() == IResource.PROJECT && !((IProject)resource).isOpen())
- return false;
- } else {
- return false;
- }
- }
- return true;
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- final IResource[] resources= getResources(selection);
- IWorkspaceRunnable operation= new IWorkspaceRunnable() {
- public void run(IProgressMonitor monitor) throws CoreException {
- monitor.beginTask(ActionMessages.RefreshAction_progressMessage, resources.length * 2);
- monitor.subTask(""); //$NON-NLS-1$
- List javaElements= new ArrayList(5);
- for (int r= 0; r < resources.length; r++) {
- IResource resource= resources[r];
- if (resource.getType() == IResource.PROJECT) {
- checkLocationDeleted((IProject) resource);
- } else if (resource.getType() == IResource.ROOT) {
- IProject[] projects = ((IWorkspaceRoot)resource).getProjects();
- for (int p = 0; p < projects.length; p++) {
- checkLocationDeleted(projects[p]);
- }
- }
- resource.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));
- IJavaScriptElement jElement= JavaScriptCore.create(resource);
- if (jElement != null && jElement.exists())
- javaElements.add(jElement);
- }
- IJavaScriptModel model= JavaScriptCore.create(ResourcesPlugin.getWorkspace().getRoot());
- model.refreshExternalArchives(
- (IJavaScriptElement[]) javaElements.toArray(new IJavaScriptElement[javaElements.size()]),
- new SubProgressMonitor(monitor, resources.length));
- }
- };
-
- try {
- PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(operation));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(),
- ActionMessages.RefreshAction_error_title,
- ActionMessages.RefreshAction_error_message);
- } catch (InterruptedException e) {
- // canceled
- }
- }
-
- private IResource[] getResources(IStructuredSelection selection) {
- if (selection.isEmpty()) {
- return new IResource[] {ResourcesPlugin.getWorkspace().getRoot()};
- }
-
- List result= new ArrayList(selection.size());
- getResources(result, selection.toArray());
-
- for (Iterator iter= result.iterator(); iter.hasNext();) {
- IResource resource= (IResource) iter.next();
- if (isDescendent(result, resource))
- iter.remove();
- }
-
- return (IResource[]) result.toArray(new IResource[result.size()]);
- }
-
- private void getResources(List result, Object[] elements) {
- for (int i= 0; i < elements.length; i++) {
- Object element= elements[i];
- // Must check working set before IAdaptable since WorkingSet
- // implements IAdaptable
- if (element instanceof IWorkingSet) {
- getResources(result, ((IWorkingSet)element).getElements());
- } else if (element instanceof IAdaptable) {
- IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class);
- if (resource == null)
- continue;
- if (resource.getType() != IResource.PROJECT ||
- (resource.getType() == IResource.PROJECT && ((IProject)resource).isOpen())) {
- result.add(resource);
- }
- }
- }
- }
-
- private boolean isDescendent(List candidates, IResource element) {
- IResource parent= element.getParent();
- while (parent != null) {
- if (candidates.contains(parent))
- return true;
- parent= parent.getParent();
- }
- return false;
- }
-
- private void checkLocationDeleted(IProject project) throws CoreException {
- if (!project.exists())
- return;
- URI location= project.getLocationURI();
- if (location == null)
- return;
- IFileStore store= EFS.getStore(location);
- if (!store.fetchInfo().exists()) {
- final String message = Messages.format(
- ActionMessages.RefreshAction_locationDeleted_message,
- new Object[] { project.getName(), Resources.getLocationString(project) });
- final boolean[] result= new boolean[1];
- // Must prompt user in UI thread (we're in the operation thread here).
- getShell().getDisplay().syncExec(new Runnable() {
- public void run() {
- result[0]= MessageDialog.openQuestion(getShell(),
- ActionMessages.RefreshAction_locationDeleted_title,
- message);
- }
- });
- if (result[0]) {
- project.delete(true, true, null);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RemoveFromClasspathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RemoveFromClasspathAction.java
deleted file mode 100644
index 745786a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RemoveFromClasspathAction.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to remove package fragment roots from the classpath of its parent
- * project. Currently, the action is applicable to selections containing
- * non-external archives (JAR or zip).
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class RemoveFromClasspathAction extends SelectionDispatchAction {
-
- /**
- * Creates a new <code>RemoveFromClasspathAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type
- * <code> org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public RemoveFromClasspathAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.RemoveFromClasspathAction_Remove);
- setToolTipText(ActionMessages.RemoveFromClasspathAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.REMOVE_FROM_CLASSPATH_ACTION);
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(checkEnabled(selection));
- }
-
- private static boolean checkEnabled(IStructuredSelection selection) {
- if (selection.isEmpty())
- return false;
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- if (! canRemove(iter.next()))
- return false;
- }
- return true;
- }
-
- /* (non-Javadoc)
- * Method declared in SelectionDispatchAction
- */
- public void run(final IStructuredSelection selection) {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
- public void run(IProgressMonitor pm) throws CoreException {
- try{
- IPackageFragmentRoot[] roots= getRootsToRemove(selection);
- pm.beginTask(ActionMessages.RemoveFromClasspathAction_Removing, roots.length);
- for (int i= 0; i < roots.length; i++) {
- int jCoreFlags= IPackageFragmentRoot.NO_RESOURCE_MODIFICATION | IPackageFragmentRoot.ORIGINATING_PROJECT_INCLUDEPATH;
- roots[i].delete(IResource.NONE, jCoreFlags, new SubProgressMonitor(pm, 1));
- }
- } finally {
- pm.done();
- }
- }
- }));
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getShell(),
- ActionMessages.RemoveFromClasspathAction_exception_dialog_title,
- ActionMessages.RemoveFromClasspathAction_Problems_occurred);
- } catch (InterruptedException e) {
- // canceled
- }
- }
-
- private static IPackageFragmentRoot[] getRootsToRemove(IStructuredSelection selection){
- List result= new ArrayList(selection.size());
- for (Iterator iter= selection.iterator(); iter.hasNext();) {
- Object element= iter.next();
- if (canRemove(element))
- result.add(element);
- }
- return (IPackageFragmentRoot[]) result.toArray(new IPackageFragmentRoot[result.size()]);
- }
-
- private static boolean canRemove(Object element){
- if (! (element instanceof IPackageFragmentRoot))
- return false;
- IPackageFragmentRoot root= (IPackageFragmentRoot)element;
- try {
- IIncludePathEntry cpe= root.getRawIncludepathEntry();
- if (cpe == null || cpe.getEntryKind() == IIncludePathEntry.CPE_CONTAINER)
- return false; // don't want to remove the container if only a child is selected
- return true;
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- return false;
- }
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RenameAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RenameAction.java
deleted file mode 100644
index 380c8703..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/RenameAction.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RenameJavaElementAction;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RenameResourceAction;
-
-/**
- * Renames a JavaScript element or workbench resource.
- * <p>
- * Action is applicable to selections containing elements of type
- * <code>IJavaScriptElement</code> or <code>IResource</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class RenameAction extends SelectionDispatchAction {
-
- private RenameJavaElementAction fRenameJavaElement;
- private RenameResourceAction fRenameResource;
-
- /**
- * Creates a new <code>RenameAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public RenameAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.RenameAction_text);
- fRenameJavaElement= new RenameJavaElementAction(site);
- fRenameJavaElement.setText(getText());
- fRenameResource= new RenameResourceAction(site);
- fRenameResource.setText(getText());
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.RENAME_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public RenameAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fRenameJavaElement= new RenameJavaElementAction(editor);
- }
-
- /*
- * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent)
- */
- public void selectionChanged(SelectionChangedEvent event) {
- fRenameJavaElement.selectionChanged(event);
- if (fRenameResource != null)
- fRenameResource.selectionChanged(event);
- setEnabled(computeEnabledState());
- }
-
- /*
- * @see SelectionDispatchAction#update(ISelection)
- */
- public void update(ISelection selection) {
- fRenameJavaElement.update(selection);
-
- if (fRenameResource != null)
- fRenameResource.update(selection);
-
- setEnabled(computeEnabledState());
- }
-
- private boolean computeEnabledState(){
- if (fRenameResource != null) {
- return fRenameJavaElement.isEnabled() || fRenameResource.isEnabled();
- } else {
- return fRenameJavaElement.isEnabled();
- }
- }
-
- public void run(IStructuredSelection selection) {
- if (fRenameJavaElement.isEnabled())
- fRenameJavaElement.run(selection);
- if (fRenameResource != null && fRenameResource.isEnabled())
- fRenameResource.run(selection);
- }
-
- public void run(ITextSelection selection) {
- if (fRenameJavaElement.canRunInEditor())
- fRenameJavaElement.run(selection);
- else
- MessageDialog.openInformation(getShell(), RefactoringMessages.RenameAction_rename, RefactoringMessages.RenameAction_unavailable);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReplaceInvocationsAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReplaceInvocationsAction.java
deleted file mode 100644
index 9af06b6d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReplaceInvocationsAction.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.ITypeRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action that replaces method invocations. This action may be invoked
- * on source or binary methods or method invocations with or without attached source.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ReplaceInvocationsAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ReplaceInvocationsAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(true);
- }
-
- /**
- * Creates a new <code>ReplaceInvocationsAction</code>.
- *
- * @param site the site providing context information for this action
- */
- public ReplaceInvocationsAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.ReplaceInvocationsAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.REPLACE_INVOCATIONS_ACTION);
- }
-
- //---- structured selection --------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
- } catch (JavaScriptModelException e) {
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- }
- }
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- Assert.isTrue(RefactoringAvailabilityTester.isReplaceInvocationsAvailable(selection));
- Object first= selection.getFirstElement();
- Assert.isTrue(first instanceof IFunction);
- IFunction method= (IFunction) first;
- if (ActionUtil.isProcessable(getShell(), method))
- RefactoringExecutionStarter.startReplaceInvocationsRefactoring(method, getShell());
- } catch (CoreException e) {
- handleException(e);
- }
- }
-
- private void handleException(CoreException e) {
- ExceptionHandler.handle(e, RefactoringMessages.ReplaceInvocationsAction_dialog_title, RefactoringMessages.ReplaceInvocationsAction_unavailable);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- try {
- IJavaScriptElement editorInput= SelectionConverter.getInput(fEditor);
- if ((editorInput instanceof ITypeRoot)
- && ActionUtil.isProcessable(getShell(), editorInput)) {
- ITypeRoot typeRoot= (ITypeRoot) editorInput;
- RefactoringExecutionStarter.startReplaceInvocationsRefactoring(typeRoot, selection.getOffset(), selection.getLength(), getShell());
- }
- } catch (JavaScriptModelException e) {
- handleException(e);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java
deleted file mode 100644
index 6a269cf5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-
-/**
- * Action that dispatches the <code>IAction#run()</code> and the
- * <code>ISelectionChangedListener#selectionChanged</code>
- * according to the type of the selection.
- *
- * <ul>
- * <li>if selection is of type <code>ITextSelection</code> then
- * <code>run(ITextSelection)</code> and <code>selectionChanged(ITextSelection)</code>
- * is called.</li>
- * <li>if selection is of type <code>IStructuredSelection</code> then
- * <code>run(IStructuredSelection)</code> and <code>
- * selectionChanged(IStructuredSelection)</code> is called.</li>
- * <li>default is to call <code>run(ISelection)</code> and <code>
- * selectionChanged(ISelection)</code>.</li>
- * </ul>
- *
- * <p>
- * Note: This class is not intended to be subclassed outside the JDT UI plug-in.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public abstract class SelectionDispatchAction extends Action implements ISelectionChangedListener {
-
- private IWorkbenchSite fSite;
- private ISelectionProvider fSpecialSelectionProvider;
-
- /**
- * Creates a new action with no text and no image.
- * <p>
- * Configure the action later using the set methods.
- * </p>
- *
- * @param site the site this action is working on
- */
- protected SelectionDispatchAction(IWorkbenchSite site) {
- Assert.isNotNull(site);
- fSite= site;
- }
-
- /**
- * Returns the site owning this action.
- *
- * @return the site owning this action
- */
- public IWorkbenchSite getSite() {
- return fSite;
- }
-
- /**
- * Returns the selection provided by the site owning this action.
- *
- * @return the site's selection
- */
- public ISelection getSelection() {
- ISelectionProvider selectionProvider= getSelectionProvider();
- if (selectionProvider != null)
- return selectionProvider.getSelection();
- else
- return null;
- }
-
- /**
- * Returns the shell provided by the site owning this action.
- *
- * @return the site's shell
- */
- public Shell getShell() {
- return fSite.getShell();
- }
-
- /**
- * Returns the selection provider managed by the site owning this action or the selection
- * provider explicitly set in {@link #setSpecialSelectionProvider(ISelectionProvider)}.
- *
- * @return the site's selection provider
- */
- public ISelectionProvider getSelectionProvider() {
- if (fSpecialSelectionProvider != null) {
- return fSpecialSelectionProvider;
- }
- return fSite.getSelectionProvider();
- }
-
- /**
- * Sets a special selection provider which will be used instead of the site's selection provider.
- * This method should be used directly after constructing the action and before the action is
- * registered as a selection listener. The invocation will not a perform a selection change notification.
- *
- * @param provider a special selection provider which is used
- * instead of the site's selection provider or <code>null</code> to use the site's
- * selection provider. Clients can for example use a {@link ConvertingSelectionProvider}
- * to first convert a selection before passing it to the action.
- *
- *
- */
- public void setSpecialSelectionProvider(ISelectionProvider provider) {
- fSpecialSelectionProvider= provider;
- }
-
- /**
- * Updates the action's enablement state according to the given selection. This
- * default implementation calls one of the <code>selectionChanged</code>
- * methods depending on the type of the passed selection.
- *
- * @param selection the selection this action is working on
- */
- public void update(ISelection selection) {
- dispatchSelectionChanged(selection);
- }
-
- /**
- * Notifies this action that the given structured selection has changed. This default
- * implementation calls <code>selectionChanged(ISelection selection)</code>.
- *
- * @param selection the new selection
- */
- public void selectionChanged(IStructuredSelection selection) {
- selectionChanged((ISelection)selection);
- }
-
- /**
- * Executes this actions with the given structured selection. This default implementation
- * calls <code>run(ISelection selection)</code>.
- *
- * @param selection the selection
- */
- public void run(IStructuredSelection selection) {
- run((ISelection)selection);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- *
- * @param selection the selection
- */
- public void selectionChanged(JavaTextSelection selection) {
- selectionChanged((ITextSelection)selection);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- *
- * @param selection the selection
- */
- public void run(JavaTextSelection selection) {
- run((ITextSelection)selection);
- }
-
- /**
- * Notifies this action that the given text selection has changed. This default
- * implementation calls <code>selectionChanged(ISelection selection)</code>.
- *
- * @param selection the new selection
- */
- public void selectionChanged(ITextSelection selection) {
- selectionChanged((ISelection)selection);
- }
-
- /**
- * Executes this actions with the given text selection. This default implementation
- * calls <code>run(ISelection selection)</code>.
- *
- * @param selection the selection
- */
- public void run(ITextSelection selection) {
- run((ISelection)selection);
- }
-
- /**
- * Notifies this action that the given selection has changed. This default
- * implementation sets the action's enablement state to <code>false</code>.
- *
- * @param selection the new selection
- */
- public void selectionChanged(ISelection selection) {
- setEnabled(false);
- }
-
- /**
- * Executes this actions with the given selection. This default implementation
- * does nothing.
- *
- * @param selection the selection
- */
- public void run(ISelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on IAction.
- */
- public void run() {
- dispatchRun(getSelection());
- }
-
- /* (non-Javadoc)
- * Method declared on ISelectionChangedListener.
- */
- public void selectionChanged(SelectionChangedEvent event) {
- dispatchSelectionChanged(event.getSelection());
- }
-
- private void dispatchSelectionChanged(ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- selectionChanged((IStructuredSelection)selection);
- } else if (selection instanceof JavaTextSelection) {
- selectionChanged((JavaTextSelection)selection);
- } else if (selection instanceof ITextSelection) {
- selectionChanged((ITextSelection)selection);
- } else {
- selectionChanged(selection);
- }
- }
-
- private void dispatchRun(ISelection selection) {
- if (selection instanceof IStructuredSelection) {
- run((IStructuredSelection)selection);
- } else if (selection instanceof JavaTextSelection) {
- run((JavaTextSelection)selection);
- } else if (selection instanceof ITextSelection) {
- run((ITextSelection)selection);
- } else {
- run(selection);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelfEncapsulateFieldAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelfEncapsulateFieldAction.java
deleted file mode 100644
index 2c74af6b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelfEncapsulateFieldAction.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to run the self encapsulate field refactoring.
- * <p>
- * Action is applicable to selections containing elements of type
- * <code>IField</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class SelfEncapsulateFieldAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>SelfEncapsulateFieldAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public SelfEncapsulateFieldAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.SelfEncapsulateFieldAction_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SELF_ENCAPSULATE_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- *
- * @param editor the JavaScript editor
- */
- public SelfEncapsulateFieldAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- //---- text selection -------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isSelfEncapsulateAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolve(fEditor);
- if (elements.length != 1 || !(elements[0] instanceof IField)) {
- MessageDialog.openInformation(getShell(), ActionMessages.SelfEncapsulateFieldAction_dialog_title, ActionMessages.SelfEncapsulateFieldAction_dialog_unavailable);
- return;
- }
- IField field= (IField)elements[0];
-
- if (!RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
- MessageDialog.openInformation(getShell(), ActionMessages.SelfEncapsulateFieldAction_dialog_title, ActionMessages.SelfEncapsulateFieldAction_dialog_unavailable);
- return;
- }
- run(field);
- } catch (JavaScriptModelException exception) {
- JavaScriptPlugin.log(exception);
- return;
- }
- }
-
- //---- structured selection -------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isSelfEncapsulateAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);//no UI
- }
- }
-
- /*
- * (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- try {
- if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(selection))
- run((IField) selection.getFirstElement());
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- //---- private helpers --------------------------------------------------------
-
- /*
- * Should be private. But got shipped in this state in 2.0 so changing this is a
- * breaking API change.
- */
- public void run(IField field) {
- if (! ActionUtil.isEditable(fEditor, getShell(), field))
- return;
- RefactoringExecutionStarter.startSelfEncapsulateRefactoring(field, getShell());
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java
deleted file mode 100644
index 8569e62d..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.part.Page;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerPart;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the show actions to a context menu and
- * the action bar's navigate menu.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ShowActionGroup extends ActionGroup {
-
- private boolean fIsPackageExplorer;
-
- private IWorkbenchSite fSite;
- private ShowInPackageViewAction fShowInPackagesViewAction;
-
- /**
- * Creates a new <code>ShowActionGroup</code>. The action requires
- * that the selection provided by the page's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param page the page that owns this action group
- */
- public ShowActionGroup(Page page) {
- this(page.getSite());
- }
-
- /**
- * Creates a new <code>ShowActionGroup</code>. The action requires
- * that the selection provided by the part's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param part the view part that owns this action group
- */
- public ShowActionGroup(IViewPart part) {
- this(part.getSite());
- fIsPackageExplorer= part instanceof PackageExplorerPart;
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param part the JavaScript editor
- */
- public ShowActionGroup(JavaEditor part) {
- fShowInPackagesViewAction= new ShowInPackageViewAction(part);
- fShowInPackagesViewAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
- part.setAction("ShowInPackageView", fShowInPackagesViewAction); //$NON-NLS-1$
-
- initialize(part.getSite(), true);
- }
-
- private ShowActionGroup(IWorkbenchSite site) {
- fShowInPackagesViewAction= new ShowInPackageViewAction(site);
- fShowInPackagesViewAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_IN_PACKAGE_VIEW);
-
- initialize(site , false);
- }
-
- private void initialize(IWorkbenchSite site, boolean isJavaEditor) {
- fSite= site;
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- fShowInPackagesViewAction.update(selection);
- if (!isJavaEditor) {
- provider.addSelectionChangedListener(fShowInPackagesViewAction);
- }
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillActionBars(IActionBars actionBar) {
- super.fillActionBars(actionBar);
- setGlobalActionHandlers(actionBar);
- }
-
- /* (non-Javadoc)
- * Method declared in ActionGroup
- */
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- if (!fIsPackageExplorer) {
- appendToGroup(menu, fShowInPackagesViewAction);
- }
- }
-
- /*
- * @see ActionGroup#dispose()
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- provider.removeSelectionChangedListener(fShowInPackagesViewAction);
- super.dispose();
- }
-
- private void setGlobalActionHandlers(IActionBars actionBar) {
- if (!fIsPackageExplorer)
- actionBar.setGlobalActionHandler(JdtActionConstants.SHOW_IN_PACKAGE_VIEW, fShowInPackagesViewAction);
- }
-
- private void appendToGroup(IMenuManager menu, IAction action) {
- if (action.isEnabled())
- menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInNavigatorViewAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInNavigatorViewAction.java
deleted file mode 100644
index 5057dc52..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInNavigatorViewAction.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ISetSelectionTarget;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Reveals the selected element in the resource navigator view.
- * <p>
- * Action is applicable to structured selections containing JavaScript element
- * or resources.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ShowInNavigatorViewAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>ShowInNavigatorViewAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ShowInNavigatorViewAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.ShowInNavigatorView_label);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SHOW_IN_NAVIGATOR_VIEW_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ShowInNavigatorViewAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(getResource(selection) != null);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- IJavaScriptElement input= SelectionConverter.getInput(fEditor);
- if (!ActionUtil.isProcessable(getShell(), input))
- return;
-
-
- try {
- IJavaScriptElement[] elements= SelectionConverter.codeResolveOrInputForked(fEditor);
- if (elements == null || elements.length == 0)
- return;
-
- IJavaScriptElement candidate= elements[0];
- if (elements.length > 1) {
- candidate= SelectionConverter.selectJavaElement(elements, getShell(), getDialogTitle(), ActionMessages.ShowInNavigatorView_dialog_message);
- }
- if (candidate != null) {
- run(getResource(candidate));
- }
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getDialogTitle(), ActionMessages.SelectionConverter_codeResolve_failed);
- } catch (InterruptedException e) {
- // cancelled
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- run(getResource(selection));
- }
-
- /*
- * No Javadoc. The method should be internal but can't be changed since
- * we shipped it with a public visibility
- */
- public void run(IResource resource) {
- if (resource == null)
- return;
- try {
- IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage();
- IViewPart view= page.showView(IPageLayout.ID_RES_NAV);
- if (view instanceof ISetSelectionTarget) {
- ISelection selection= new StructuredSelection(resource);
- ((ISetSelectionTarget)view).selectReveal(selection);
- }
- } catch(PartInitException e) {
- ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.ShowInNavigatorView_error_activation_failed);
- }
- }
-
- private IResource getResource(IStructuredSelection selection) {
- if (selection.size() != 1)
- return null;
- Object element= selection.getFirstElement();
- if (element instanceof IResource)
- return (IResource)element;
- if (element instanceof IJavaScriptElement)
- return getResource((IJavaScriptElement)element);
- return null;
- }
-
- private IResource getResource(IJavaScriptElement element) {
- if (element == null)
- return null;
-
- element= (IJavaScriptElement) element.getOpenable();
- if (element instanceof IJavaScriptUnit) {
- element= ((IJavaScriptUnit) element).getPrimary();
- }
- return element.getResource();
- }
-
- private static String getDialogTitle() {
- return ActionMessages.ShowInNavigatorView_dialog_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInPackageViewAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInPackageViewAction.java
deleted file mode 100644
index 9b49bdaa..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowInPackageViewAction.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IOpenable;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.packageview.PackageExplorerPart;
-/**
- * This action reveals the currently selected JavaScript element in the
- * package explorer.
- * <p>
- * The action is applicable to selections containing elements of type
- * <code>IJavaScriptElement</code>.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class ShowInPackageViewAction extends SelectionDispatchAction {
-
- private JavaEditor fEditor;
-
- /**
- * Creates a new <code>ShowInPackageViewAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type
- * <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public ShowInPackageViewAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.ShowInPackageViewAction_label);
- setDescription(ActionMessages.ShowInPackageViewAction_description);
- setToolTipText(ActionMessages.ShowInPackageViewAction_tooltip);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SHOW_IN_PACKAGEVIEW_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public ShowInPackageViewAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void selectionChanged(IStructuredSelection selection) {
- setEnabled(checkEnabled(selection));
- }
-
- private boolean checkEnabled(IStructuredSelection selection) {
- if (selection.size() != 1)
- return false;
- return selection.getFirstElement() instanceof IJavaScriptElement;
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(ITextSelection selection) {
- try {
- IJavaScriptElement element= SelectionConverter.getElementAtOffset(fEditor);
- if (element != null)
- run(element);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- String message= ActionMessages.ShowInPackageViewAction_error_message;
- ErrorDialog.openError(getShell(), getDialogTitle(), message, e.getStatus());
- }
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction.
- */
- public void run(IStructuredSelection selection) {
- if (!checkEnabled(selection))
- return;
- run((IJavaScriptElement)selection.getFirstElement());
- }
-
- /*
- * No Javadoc. The method should be internal but can't be changed since
- * we shipped it with a public visibility
- */
- public void run(IJavaScriptElement element) {
- if (element == null)
- return;
-
- // reveal the top most element only
- IOpenable openable= element.getOpenable();
- if (openable instanceof IJavaScriptElement)
- element= (IJavaScriptElement)openable;
-
- PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
- view.tryToReveal(element);
- }
-
- private static String getDialogTitle() {
- return ActionMessages.ShowInPackageViewAction_dialog_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SortMembersAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SortMembersAction.java
deleted file mode 100644
index 782ec79e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SortMembersAction.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.SortMembersOperation;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionMessages;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.OptionalMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.SortMembersMessageDialog;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IJavaAnnotation;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Sorts the members of a compilation unit with the sort order as specified in
- * the Sort Order preference page.
- * <p>
- * The action will open the parent compilation unit in a JavaScript editor. The result
- * is unsaved, so the user can decide if the changes are acceptable.
- * <p>
- * The action is applicable to structured selections containing a single
- * <code>IJavaScriptUnit</code> or top level <code>IType</code> in a
- * compilation unit.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class SortMembersAction extends SelectionDispatchAction {
-
- private CompilationUnitEditor fEditor;
- private final static String ID_OPTIONAL_DIALOG= "org.eclipse.wst.jsdt.ui.actions.SortMembersAction"; //$NON-NLS-1$
-
- /**
- * Creates a new <code>SortMembersAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public SortMembersAction(IWorkbenchSite site) {
- super(site);
- setText(ActionMessages.SortMembersAction_label);
- setDescription(ActionMessages.SortMembersAction_description);
- setToolTipText(ActionMessages.SortMembersAction_tooltip);
-
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public SortMembersAction(CompilationUnitEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(checkEnabledEditor());
- }
-
- private boolean checkEnabledEditor() {
- return fEditor != null && SelectionConverter.canOperateOn(fEditor);
- }
-
- //---- Structured Viewer -----------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(IStructuredSelection selection) {
- boolean enabled= false;
- enabled= getSelectedCompilationUnit(selection) != null;
- setEnabled(enabled);
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(IStructuredSelection selection) {
- Shell shell= getShell();
- try {
- IJavaScriptUnit cu= getSelectedCompilationUnit(selection);
- if (cu == null) {
- return;
- }
- IJavaScriptElement[] types= cu.getChildren();
- if (!hasMembersToSort(types)) {
- return;
- }
- if (!ActionUtil.isEditable(getShell(), cu)) {
- return;
- }
-
- SortMembersMessageDialog dialog= new SortMembersMessageDialog(getShell());
- if (dialog.open() != Window.OK) {
- return;
- }
-
- if (!ElementValidator.check(cu, getShell(), getDialogTitle(), false)) {
- return;
- }
-
- // open an editor and work on a working copy
- IEditorPart editor= JavaScriptUI.openInEditor(cu);
- if (editor != null) {
- run(shell, cu, editor, dialog.isNotSortingFieldsEnabled());
- }
- } catch (CoreException e) {
- ExceptionHandler.handle(e, shell, getDialogTitle(), null);
- }
- }
-
- private boolean hasMembersToSort(IJavaScriptElement[] members) throws JavaScriptModelException {
- if (members.length > 1) {
- return true;
- }
- if (members.length == 1) {
- IJavaScriptElement elem= members[0];
- if (elem instanceof IParent) {
- return hasMembersToSort(((IParent) elem).getChildren());
- }
- }
- return false;
- }
-
- //---- JavaScript Editor --------------------------------------------------------------
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void selectionChanged(ITextSelection selection) {
- }
-
- /* (non-Javadoc)
- * Method declared on SelectionDispatchAction
- */
- public void run(ITextSelection selection) {
- Shell shell= getShell();
- IJavaScriptElement input= SelectionConverter.getInput(fEditor);
- if (input instanceof IJavaScriptUnit) {
- if (!ActionUtil.isEditable(fEditor)) {
- return;
- }
- SortMembersMessageDialog dialog= new SortMembersMessageDialog(getShell());
- if (dialog.open() != Window.OK) {
- return;
- }
- if (!ElementValidator.check(input, getShell(), getDialogTitle(), true)) {
- return;
- }
- run(shell, (IJavaScriptUnit) input, fEditor, dialog.isNotSortingFieldsEnabled());
- } else {
- MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.SortMembersAction_not_applicable);
- }
- }
-
- //---- Helpers -------------------------------------------------------------------
-
- private boolean containsRelevantMarkers(IEditorPart editor) {
- IAnnotationModel model= JavaScriptUI.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
- Iterator iterator= model.getAnnotationIterator();
- while (iterator.hasNext()) {
- Object element= iterator.next();
- if (element instanceof IJavaAnnotation) {
- IJavaAnnotation annot= (IJavaAnnotation) element;
- if (!annot.isMarkedDeleted() && annot.isPersistent() && !annot.isProblem())
- return true;
- }
- }
- return false;
- }
-
- private void run(Shell shell, IJavaScriptUnit cu, IEditorPart editor, boolean isNotSortFields) {
- if (containsRelevantMarkers(editor)) {
- int returnCode= OptionalMessageDialog.open(ID_OPTIONAL_DIALOG,
- getShell(),
- getDialogTitle(),
- null,
- ActionMessages.SortMembersAction_containsmarkers,
- MessageDialog.WARNING,
- new String[] {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL},
- 0);
- if (returnCode != OptionalMessageDialog.NOT_SHOWN &&
- returnCode != Window.OK ) return;
- }
-
- SortMembersOperation op= new SortMembersOperation(cu, null, isNotSortFields);
- try {
- BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
- PlatformUI.getWorkbench().getProgressService().runInUI(context,
- new WorkbenchRunnableAdapter(op, op.getScheduleRule()),
- op.getScheduleRule());
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, shell, getDialogTitle(), null);
- } catch (InterruptedException e) {
- // Do nothing. Operation has been canceled by user.
- }
- }
-
-
- private IJavaScriptUnit getSelectedCompilationUnit(IStructuredSelection selection) {
- if (selection.size() == 1) {
- Object element= selection.getFirstElement();
- if (element instanceof IJavaScriptUnit) {
- return (IJavaScriptUnit) element;
- } else if (element instanceof IType) {
- IType type= (IType) element;
- if (type.getParent() instanceof IJavaScriptUnit) { // only top level types
- return type.getJavaScriptUnit();
- }
- }
- }
- return null;
- }
-
- private String getDialogTitle() {
- return ActionMessages.SortMembersAction_dialog_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SurroundWithTryCatchAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SurroundWithTryCatchAction.java
deleted file mode 100644
index 39293ec7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SurroundWithTryCatchAction.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids - Fixed bug 25898
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.PerformChangeOperation;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
-import org.eclipse.ltk.ui.refactoring.RefactoringUI;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.base.JavaStatusContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.surround.ISurroundWithTryCatchQuery;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.util.ElementValidator;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Action to surround a set of statements with a try/catch block.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class SurroundWithTryCatchAction extends SelectionDispatchAction {
-
- private CompilationUnitEditor fEditor;
-
- private static class Query implements ISurroundWithTryCatchQuery {
- private Shell fParent;
- public Query(Shell shell) {
- fParent= shell;
- }
- public boolean catchRuntimeException() {
- MessageDialog dialog = new MessageDialog(
- fParent, getDialogTitle(), null, // accept the default window icon
- RefactoringMessages.SurroundWithTryCatchAction_no_exceptions,
- MessageDialog.QUESTION,
- new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL},
- 1) {
- // Work around for http://dev.eclipse.org/bugs/show_bug.cgi?id=18303
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- Button button= getButton(1);
- if (button != null)
- button.setFocus();
- }
- };
- return dialog.open() == 0; // yes selected
- }
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the compilation unit editor
- */
- public SurroundWithTryCatchAction(CompilationUnitEditor editor) {
- super(editor.getEditorSite());
- setText(RefactoringMessages.SurroundWithTryCatchAction_label);
- fEditor= editor;
- setEnabled((fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null));
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.SURROUND_WITH_TRY_CATCH_ACTION);
- }
-
- public void run(ITextSelection selection) {
- if (!ActionUtil.isEditable(fEditor))
- return;
- IJavaScriptUnit cu= SelectionConverter.getInputAsCompilationUnit(fEditor);
- if (cu == null || !ElementValidator.checkValidateEdit(cu, getShell(), getDialogTitle()))
- return;
- SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selection, new Query(getShell()));
-
- if (refactoring == null)
- return;
- try {
- RefactoringStatus status= refactoring.checkInitialConditions(new NullProgressMonitor());
- if (status.hasFatalError()) {
- RefactoringStatusEntry entry= status.getEntryMatchingSeverity(RefactoringStatus.FATAL);
- MessageDialog.openInformation(getShell(), getDialogTitle(), entry.getMessage());
- if (entry.getContext() instanceof JavaStatusContext && fEditor != null) {
- JavaStatusContext context= (JavaStatusContext)entry.getContext();
- ISourceRange range= context.getSourceRange();
- fEditor.setHighlightRange(range.getOffset(), range.getLength(), true);
- }
- return;
- }
- if (refactoring.stopExecution())
- return;
- Change change= refactoring.createChange(new NullProgressMonitor());
- change.initializeValidationData(new NullProgressMonitor());
- PerformChangeOperation op= RefactoringUI.createUIAwareChangeOperation(change);
- // must be fork == false since file buffers can't be manipulated in a different thread.
- WorkbenchRunnableAdapter adapter= new WorkbenchRunnableAdapter(op);
- PlatformUI.getWorkbench().getProgressService().runInUI(
- new BusyIndicatorRunnableContext(), adapter, adapter.getSchedulingRule());
- } catch (CoreException e) {
- ExceptionHandler.handle(e, getDialogTitle(), RefactoringMessages.SurroundWithTryCatchAction_exception);
- } catch (InvocationTargetException e) {
- ExceptionHandler.handle(e, getDialogTitle(), RefactoringMessages.SurroundWithTryCatchAction_exception);
- } catch (InterruptedException e) {
- // not cancelable
- }
- }
-
- public void selectionChanged(ITextSelection selection) {
- setEnabled(selection.getLength() > 0 && (fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null));
- }
-
- private static String getDialogTitle() {
- return RefactoringMessages.SurroundWithTryCatchAction_dialog_title;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/UseSupertypeAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/UseSupertypeAction.java
deleted file mode 100644
index e45bd938..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/UseSupertypeAction.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.io.CharConversionException;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringAvailabilityTester;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.RefactoringExecutionStarter;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.util.JavaElementUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.ActionUtil;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaTextSelection;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.actions.RefactoringActions;
-import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler;
-
-/**
- * Tries to use a super type of a class where possible.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class UseSupertypeAction extends SelectionDispatchAction{
-
- private JavaEditor fEditor;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public UseSupertypeAction(JavaEditor editor) {
- this(editor.getEditorSite());
- fEditor= editor;
- setEnabled(SelectionConverter.canOperateOn(fEditor));
- }
-
- /**
- * Creates a new <code>UseSupertypeAction</code>. The action requires
- * that the selection provided by the site's selection provider is of type <code>
- * org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the site providing context information for this action
- */
- public UseSupertypeAction(IWorkbenchSite site) {
- super(site);
- setText(RefactoringMessages.UseSupertypeAction_use_Supertype);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.USE_SUPERTYPE_ACTION);
- }
-
- //---- structured selection ---------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(IStructuredSelection)
- */
- public void selectionChanged(IStructuredSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isUseSuperTypeAvailable(selection));
- } catch (JavaScriptModelException e) {
- // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
- if (!(e.getException() instanceof CharConversionException) && JavaModelUtil.isExceptionToBeLogged(e))
- JavaScriptPlugin.log(e);
- setEnabled(false);// no UI - happens on selection changes
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(IStructuredSelection)
- */
- public void run(IStructuredSelection selection) {
- try {
- if (RefactoringAvailabilityTester.isUseSuperTypeAvailable(selection)) {
- IType singleSelectedType= getSingleSelectedType(selection);
- if (! ActionUtil.isEditable(getShell(), singleSelectedType))
- return;
- RefactoringExecutionStarter.startUseSupertypeRefactoring(singleSelectedType, getShell());
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-
- private static IType getSingleSelectedType(IStructuredSelection selection) throws JavaScriptModelException{
- if (selection.isEmpty() || selection.size() != 1)
- return null;
-
- Object first= selection.getFirstElement();
- if (first instanceof IType)
- return (IType)first;
- if (first instanceof IJavaScriptUnit)
- return JavaElementUtil.getMainType((IJavaScriptUnit)first);
- return null;
- }
-
- //---- text selection ------------------------------------------------------
-
- /*
- * @see SelectionDispatchAction#selectionChanged(ITextSelection)
- */
- public void selectionChanged(ITextSelection selection) {
- setEnabled(true);
- }
-
- /**
- * Note: This method is for internal use only. Clients should not call this method.
- */
- public void selectionChanged(JavaTextSelection selection) {
- try {
- setEnabled(RefactoringAvailabilityTester.isUseSuperTypeAvailable(selection));
- } catch (JavaScriptModelException e) {
- setEnabled(false);
- }
- }
-
- /*
- * @see SelectionDispatchAction#run(ITextSelection)
- */
- public void run(ITextSelection selection) {
- try {
- IType type= RefactoringActions.getEnclosingOrPrimaryType(fEditor);
- if (RefactoringAvailabilityTester.isUseSuperTypeAvailable(type)) {
- if (! ActionUtil.isEditable(fEditor, getShell(), type))
- return;
- RefactoringExecutionStarter.startUseSupertypeRefactoring(type, getShell());
- } else {
- MessageDialog.openInformation(getShell(), RefactoringMessages.OpenRefactoringWizardAction_unavailable, RefactoringMessages.UseSupertypeAction_to_activate);
- }
- } catch (JavaScriptModelException e) {
- ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.OpenRefactoringWizardAction_exception);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WorkingSetFindAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WorkingSetFindAction.java
deleted file mode 100644
index d97fe573..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WorkingSetFindAction.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-
-/**
- * Wraps a <code>JavaElementSearchActions</code> to find its results
- * in the specified working set.
- * <p>
- * The action is applicable to selections and Search view entries
- * representing a JavaScript element.
- *
- * <p>
- * Note: This class is for internal use only. Clients should not use this class.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class WorkingSetFindAction extends FindAction {
-
- private FindAction fAction;
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- */
- public WorkingSetFindAction(IWorkbenchSite site, FindAction action, String workingSetName) {
- super(site);
- init(action, workingSetName);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- */
- public WorkingSetFindAction(JavaEditor editor, FindAction action, String workingSetName) {
- super(editor);
- init(action, workingSetName);
- }
-
- Class[] getValidTypes() {
- return null; // ignore, we override canOperateOn
- }
-
- void init() {
- // ignore: do our own init in 'init(FindAction, String)'
- }
-
- private void init(FindAction action, String workingSetName) {
- Assert.isNotNull(action);
- fAction= action;
- setText(workingSetName);
- setImageDescriptor(action.getImageDescriptor());
- setToolTipText(action.getToolTipText());
- PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.WORKING_SET_FIND_ACTION);
- }
-
- public void run(IJavaScriptElement element) {
- fAction.run(element);
- }
-
- boolean canOperateOn(IJavaScriptElement element) {
- return fAction.canOperateOn(element);
- }
-
- int getLimitTo() {
- return -1;
- }
-
- String getOperationUnavailableMessage() {
- return fAction.getOperationUnavailableMessage();
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java
deleted file mode 100644
index 2286177f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IWorkbenchSite;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.actions.ActionGroup;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchMessages;
-import org.eclipse.wst.jsdt.internal.ui.search.SearchUtil;
-import org.eclipse.wst.jsdt.ui.IContextMenuConstants;
-
-/**
- * Action group that adds the search for write references actions to a
- * context menu and the global menu bar.
- *
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class WriteReferencesSearchGroup extends ActionGroup {
-
- private static final String MENU_TEXT= SearchMessages.group_writeReferences;
-
- private IWorkbenchSite fSite;
- private JavaEditor fEditor;
- private IActionBars fActionBars;
-
- private String fGroupId;
-
- private FindWriteReferencesAction fFindWriteReferencesAction;
- private FindWriteReferencesInProjectAction fFindWriteReferencesInProjectAction;
- private FindWriteReferencesInHierarchyAction fFindWriteReferencesInHierarchyAction;
- private FindWriteReferencesInWorkingSetAction fFindWriteReferencesInWorkingSetAction;
-
- /**
- * Creates a new <code>WriteReferencesSearchGroup</code>. The action
- * requires that the selection provided by the site's selection provider is of
- * type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
- *
- * @param site the view part that owns this action group
- */
- public WriteReferencesSearchGroup(IWorkbenchSite site) {
- fSite= site;
- fGroupId= IContextMenuConstants.GROUP_SEARCH;
-
- fFindWriteReferencesAction= new FindWriteReferencesAction(site);
- fFindWriteReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKSPACE);
-
- fFindWriteReferencesInProjectAction= new FindWriteReferencesInProjectAction(site);
- fFindWriteReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_PROJECT);
-
- fFindWriteReferencesInHierarchyAction= new FindWriteReferencesInHierarchyAction(site);
- fFindWriteReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_HIERARCHY);
-
- fFindWriteReferencesInWorkingSetAction= new FindWriteReferencesInWorkingSetAction(site);
- fFindWriteReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKING_SET);
-
- // register the actions as selection listeners
- ISelectionProvider provider= fSite.getSelectionProvider();
- ISelection selection= provider.getSelection();
- registerAction(fFindWriteReferencesAction, provider, selection);
- registerAction(fFindWriteReferencesInProjectAction, provider, selection);
- registerAction(fFindWriteReferencesInHierarchyAction, provider, selection);
- registerAction(fFindWriteReferencesInWorkingSetAction, provider, selection);
- }
-
- /**
- * Note: This constructor is for internal use only. Clients should not call this constructor.
- * @param editor the JavaScript editor
- */
- public WriteReferencesSearchGroup(JavaEditor editor) {
- fEditor= editor;
- fSite= fEditor.getSite();
- fGroupId= ITextEditorActionConstants.GROUP_FIND;
-
- fFindWriteReferencesAction= new FindWriteReferencesAction(fEditor);
- fFindWriteReferencesAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKSPACE);
- fEditor.setAction("SearchWriteAccessInWorkspace", fFindWriteReferencesAction); //$NON-NLS-1$
-
- fFindWriteReferencesInProjectAction= new FindWriteReferencesInProjectAction(fEditor);
- fFindWriteReferencesInProjectAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_PROJECT);
- fEditor.setAction("SearchWriteAccessInProject", fFindWriteReferencesInProjectAction); //$NON-NLS-1$
-
- fFindWriteReferencesInHierarchyAction= new FindWriteReferencesInHierarchyAction(fEditor);
- fFindWriteReferencesInHierarchyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_HIERARCHY);
- fEditor.setAction("SearchWriteAccessInHierarchy", fFindWriteReferencesInHierarchyAction); //$NON-NLS-1$
-
- fFindWriteReferencesInWorkingSetAction= new FindWriteReferencesInWorkingSetAction(fEditor);
- fFindWriteReferencesInWorkingSetAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SEARCH_WRITE_ACCESS_IN_WORKING_SET);
- fEditor.setAction("SearchWriteAccessInWorkingSet", fFindWriteReferencesInWorkingSetAction); //$NON-NLS-1$
- }
-
- private void registerAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection) {
- action.update(selection);
- provider.addSelectionChangedListener(action);
- }
-
- private void addAction(IAction action, IMenuManager manager) {
- if (action.isEnabled()) {
- manager.add(action);
- }
- }
-
- private void addWorkingSetAction(IWorkingSet[] workingSets, IMenuManager manager) {
- FindAction action;
- if (fEditor != null)
- action= new WorkingSetFindAction(fEditor, new FindWriteReferencesInWorkingSetAction(fEditor, workingSets), SearchUtil.toString(workingSets));
- else
- action= new WorkingSetFindAction(fSite, new FindWriteReferencesInWorkingSetAction(fSite, workingSets), SearchUtil.toString(workingSets));
- action.update(getContext().getSelection());
- addAction(action, manager);
- }
-
-
- /* (non-Javadoc)
- * Method declared on ActionGroup.
- */
- public void fillContextMenu(IMenuManager manager) {
- MenuManager javaSearchMM= new MenuManager(MENU_TEXT, IContextMenuConstants.GROUP_SEARCH);
- addAction(fFindWriteReferencesAction, javaSearchMM);
- addAction(fFindWriteReferencesInProjectAction, javaSearchMM);
- addAction(fFindWriteReferencesInHierarchyAction, javaSearchMM);
-
- javaSearchMM.add(new Separator());
-
- Iterator iter= SearchUtil.getLRUWorkingSets().sortedIterator();
- while (iter.hasNext()) {
- addWorkingSetAction((IWorkingSet[]) iter.next(), javaSearchMM);
- }
- addAction(fFindWriteReferencesInWorkingSetAction, javaSearchMM);
-
- if (!javaSearchMM.isEmpty())
- manager.appendToGroup(fGroupId, javaSearchMM);
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void fillActionBars(IActionBars actionBars) {
- Assert.isNotNull(actionBars);
- super.fillActionBars(actionBars);
- fActionBars= actionBars;
- updateGlobalActionHandlers();
- }
-
- /*
- * Method declared on ActionGroup.
- */
- public void dispose() {
- ISelectionProvider provider= fSite.getSelectionProvider();
- if (provider != null) {
- disposeAction(fFindWriteReferencesAction, provider);
- disposeAction(fFindWriteReferencesInProjectAction, provider);
- disposeAction(fFindWriteReferencesInHierarchyAction, provider);
- disposeAction(fFindWriteReferencesInWorkingSetAction, provider);
- }
- fFindWriteReferencesAction= null;
- fFindWriteReferencesInProjectAction= null;
- fFindWriteReferencesInHierarchyAction= null;
- fFindWriteReferencesInWorkingSetAction= null;
- updateGlobalActionHandlers();
- super.dispose();
- }
-
- private void updateGlobalActionHandlers() {
- if (fActionBars != null) {
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_WRITE_ACCESS_IN_WORKSPACE, fFindWriteReferencesAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_WRITE_ACCESS_IN_PROJECT, fFindWriteReferencesInProjectAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_WRITE_ACCESS_IN_HIERARCHY, fFindWriteReferencesInHierarchyAction);
- fActionBars.setGlobalActionHandler(JdtActionConstants.FIND_WRITE_ACCESS_IN_WORKING_SET, fFindWriteReferencesInWorkingSetAction);
- }
- }
-
- private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) {
- if (action != null)
- provider.removeSelectionChangedListener(action);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoFilterExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoFilterExtension.java
deleted file mode 100644
index 6af09cd7..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoFilterExtension.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.dialogs;
-
-/**
- * A filter to select {@link ITypeInfoRequestor} objects.
- * <p>
- * The interface should be implemented by clients wishing to provide special
- * filtering to the type selection dialog.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface ITypeInfoFilterExtension {
-
- /**
- * Returns whether the given type makes it into the list or
- * not.
- *
- * @param typeInfoRequestor the <code>ITypeInfoRequestor</code> to
- * used to access data for the type under inspection
- *
- * @return whether the type is selected or not
- */
- public boolean select(ITypeInfoRequestor typeInfoRequestor);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoImageProvider.java
deleted file mode 100644
index 83e10f16..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoImageProvider.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.dialogs;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/**
- * A special image descriptor provider for {@link ITypeInfoRequestor}.
- * <p>
- * The interface should be implemented by clients wishing to provide special
- * images inside the type selection dialog.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface ITypeInfoImageProvider {
-
- /**
- * Returns the image descriptor for the type represented by the
- * given {@link ITypeInfoRequestor}.
- * <p>
- * Note, that this method may be called from non UI threads.
- * </p>
- *
- * @param typeInfoRequestor the {@link ITypeInfoRequestor} to access
- * information for the type under inspection
- *
- * @return the image descriptor or <code>null</code> to use the default
- * image
- */
- public ImageDescriptor getImageDescriptor(ITypeInfoRequestor typeInfoRequestor);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoRequestor.java
deleted file mode 100644
index 0cd8a54c..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeInfoRequestor.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.dialogs;
-
-/**
- * An interfaces to give access to the type presented in type
- * selection dialogs like the open type dialog.
- * <p>
- * Please note that <code>ITypeInfoRequestor</code> objects <strong>don't
- * </strong> have value semantic. The state of the object might change over
- * time especially since objects are reused for different call backs.
- * </p>
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public interface ITypeInfoRequestor {
-
- /**
- * Returns the type's modifiers. The modifiers can be
- * inspected using the class {@link org.eclipse.wst.jsdt.core.Flags}.
- *
- * @return the type's modifiers
- */
- public int getModifiers();
-
- /**
- * Returns the type name.
- *
- * @return the info's type name.
- */
- public String getTypeName();
-
- /**
- * Returns the package name.
- *
- * @return the info's package name.
- */
- public String getPackageName();
-
- /**
- * Returns a dot separated string of the enclosing types or an
- * empty string if the type is a top level type.
- *
- * @return a dot separated string of the enclosing types
- */
- public String getEnclosingName();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeSelectionComponent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeSelectionComponent.java
deleted file mode 100644
index 99383e70..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/ITypeSelectionComponent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.dialogs;
-
-/**
- * Interface to access the type selection component hosting a
- * type selection extension.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface ITypeSelectionComponent {
-
- /**
- * Triggers a search inside the type component with the
- * current settings.
- */
- public void triggerSearch();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/TypeSelectionExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/TypeSelectionExtension.java
deleted file mode 100644
index 35d9c291..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/dialogs/TypeSelectionExtension.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.dialogs;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-
-/**
- * The class provides API to extend type selection dialogs like the
- * open type dialog.
- * <p>
- * The class should be subclassed by clients wishing to extend the type
- * selection dialog.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.ui.JavaScriptUI#createTypeDialog(org.eclipse.swt.widgets.Shell, org.eclipse.jface.operation.IRunnableContext, org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope, int, boolean, String, TypeSelectionExtension)
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class TypeSelectionExtension {
-
- private ITypeSelectionComponent fComponent;
-
- /**
- * Initializes the type dialog extension with the given type dialog
- *
- * @param component the type dialog hosting this extension
- */
- public final void initialize(ITypeSelectionComponent component) {
- fComponent= component;
- }
-
- /**
- * Returns the type selection dialog or <code>null</code> if
- * the extension has not been initialized yet.
- *
- * @return the type selection dialog or <code>null</code>
- */
- public final ITypeSelectionComponent getTypeSelectionComponent() {
- return fComponent;
- }
-
- /**
- * Creates the content area which the extensions contributes to the
- * type selection dialog. The area will be presented between the
- * table showing the list of types and the optional status line.
- *
- * @param parent the parent of the additional content area
- * @return the additional content area or <code>null</code> if no
- * additional content area is required
- */
- public Control createContentArea(Composite parent) {
- return null;
- }
-
- /**
- * Returns the filter extension or <code>null</code> if
- * no additional filtering is required.
- *
- * @return the additional filter extension
- */
- public ITypeInfoFilterExtension getFilterExtension() {
- return null;
- }
-
- /**
- * Returns the selection validator or <code>null</code> if
- * selection validation is not required. The elements passed
- * to the selection validator are of type {@link org.eclipse.wst.jsdt.core.IType}.
- *
- * @return the selection validator or <code>null</code>
- */
- public ISelectionStatusValidator getSelectionValidator() {
- return null;
- }
-
- /**
- * Returns an image provider or <code>null</code> if the standard
- * images should be used.
- *
- * @return the image provider
- */
- public ITypeInfoImageProvider getImageProvider() {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties
deleted file mode 100644
index 7686a549..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties
+++ /dev/null
@@ -1,11 +0,0 @@
-###############################################################################
-# Copyright (c) 2007, 2009 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-ProjectLibraryRoot.0=JavaScript Resources
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/project/JsNature.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/project/JsNature.java
deleted file mode 100644
index 8aff13ea..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/project/JsNature.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.project;
-
-import java.util.Arrays;
-import java.util.Vector;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.core.JavaProject;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-/**
- *
-* Provisional API: This class/interface
- * of an interim API that is still under development and expected to
-* change significantly before reaching stability. It is being made available at this early stage to solicit feedback
-* from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
-* (repeatedly) as the API evolves.
-*/
-public class JsNature implements IProjectNature {
- //private static final String FILENAME_CLASSPATH = ".classpath"; //$NON-NLS-1$
- // private static final String NATURE_IDS[] =
- // {"org.eclipse.wst.jsdt.web.core.embeded.jsNature",JavaScriptCore.NATURE_ID};
- // //$NON-NLS-1$
- private static final String NATURE_IDS[] = { JavaScriptCore.NATURE_ID };
- private static final String SUPER_TYPE_NAME = JavaUIMessages.JsNature_Global;
- private static final String SUPER_TYPE_LIBRARY = "org.eclipse.wst.jsdt.launching.JRE_CONTAINER"; //$NON-NLS-1$
-
- public static void addJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (!JsNature.hasNature(project)) {
- IProjectDescription description = project.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length + JsNature.NATURE_IDS.length];
- System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
- // newNatures[prevNatures.length] = JavaScriptCore.NATURE_ID;
- for (int i = 0; i < JsNature.NATURE_IDS.length; i++) {
- newNatures[prevNatures.length + i] = JsNature.NATURE_IDS[i];
- }
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- } else {
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- }
-
- public static boolean hasNature(IProject project) {
- try {
- for (int i = 0; i < JsNature.NATURE_IDS.length; i++) {
- if (!project.hasNature(JsNature.NATURE_IDS[i])) {
- return false;
- }
- }
- } catch (CoreException ex) {
- return false;
- }
- return true;
- }
-
- public static void removeJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if (JsNature.hasNature(project)) {
- IProjectDescription description = project.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length - JsNature.NATURE_IDS.length];
- int k = 0;
- head: for (int i = 0; i < prevNatures.length; i++) {
- for (int j = 0; j < JsNature.NATURE_IDS.length; j++) {
- if (prevNatures[i].equals(JsNature.NATURE_IDS[j])) {
- continue head;
- }
- }
- newNatures[k++] = prevNatures[i];
- }
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- } else {
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- }
- private Vector classPathEntries = new Vector();
- private boolean DEBUG = false;
- private IProject fCurrProject;
- private JavaProject fJavaProject;
- private IPath fOutputLocation;
- private IProgressMonitor monitor;
-
- public JsNature() {
- monitor = new NullProgressMonitor();
- }
-
- public JsNature(IProject project, IProgressMonitor monitor) {
- fCurrProject = project;
- if (monitor != null) {
- this.monitor = monitor;
- } else {
- monitor = new NullProgressMonitor();
- }
- }
-
- public void configure() throws CoreException {
-
- initOutputPath();
- createSourceClassPath();
- initJREEntry();
- initLocalClassPath();
- if (hasProjectClassPathFile()) {
- IIncludePathEntry[] entries = getRawClassPath();
- if (entries != null && entries.length > 0) {
- classPathEntries.removeAll(Arrays.asList(entries));
- classPathEntries.addAll(Arrays.asList(entries));
- }
- }
- JsNature.addJsNature(fCurrProject, monitor);
- fJavaProject = (JavaProject) JavaScriptCore.create(fCurrProject);
- fJavaProject.setProject(fCurrProject);
- try {
- // , fOutputLocation
- if (!hasProjectClassPathFile()) {
- fJavaProject.setRawIncludepath((IIncludePathEntry[]) classPathEntries.toArray(new IIncludePathEntry[] {}), fOutputLocation, monitor);
- }
- if (hasProjectClassPathFile()) {
- fJavaProject.setRawIncludepath((IIncludePathEntry[]) classPathEntries.toArray(new IIncludePathEntry[] {}), monitor);
- }
- } catch (Exception e) {
- System.out.println(e);
- }
- LibrarySuperType superType = new LibrarySuperType(new Path( SUPER_TYPE_LIBRARY), getJavaProject(), SUPER_TYPE_NAME);
- getJavaProject().setCommonSuperType(superType);
- // getJavaProject().addToBuildSpec(BUILDER_ID);
- fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-
- private void createSourceClassPath() {
- if (hasAValidSourcePath()) {
- return;
- }
- // IPath projectPath = fCurrProject.getFullPath();
- // classPathEntries.add(JavaScriptCore.newSourceEntry(projectPath));
- }
-
- public void deconfigure() throws CoreException {
- Vector badEntries = new Vector();
- IIncludePathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary();
- IIncludePathEntry[] localEntries = initLocalClassPath();
- badEntries.addAll(Arrays.asList(defaultJRELibrary));
- badEntries.addAll(Arrays.asList(localEntries));
- IIncludePathEntry[] entries = getRawClassPath();
- Vector goodEntries = new Vector();
- for (int i = 0; i < entries.length; i++) {
- if (!badEntries.contains(entries[i])) {
- goodEntries.add(entries[i]);
- }
- }
- // getJavaProject().removeFromBuildSpec(BUILDER_ID);
- IPath outputLocation = getJavaProject().getOutputLocation();
- getJavaProject().setRawIncludepath((IIncludePathEntry[]) goodEntries.toArray(new IIncludePathEntry[] {}), outputLocation, monitor);
- getJavaProject().deconfigure();
- JsNature.removeJsNature(fCurrProject, monitor);
- fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-
-
-
- public JavaProject getJavaProject() {
- if (fJavaProject == null) {
- fJavaProject = (JavaProject) JavaScriptCore.create(fCurrProject);
- fJavaProject.setProject(fCurrProject);
- }
- return fJavaProject;
- }
-
- public IProject getProject() {
- return this.fCurrProject;
- }
-
- private IIncludePathEntry[] getRawClassPath() {
- JavaProject proj = new JavaProject();
- proj.setProject(fCurrProject);
- return proj.readRawIncludepath();
- }
-
- private boolean hasAValidSourcePath() {
- if (hasProjectClassPathFile()) {
- try {
- IIncludePathEntry[] entries = getRawClassPath();
- for (int i = 0; i < entries.length; i++) {
- if (entries[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE) {
- return true;
- }
- }
- } catch (Exception e) {
- if (DEBUG) {
- System.out.println("Error checking sourcepath:" + e); //$NON-NLS-1$
- }
- }
- }
- return false;
- }
-
- private boolean hasProjectClassPathFile() {
- if (fCurrProject == null) {
- return false;
- }
- return fCurrProject.getFolder(JavaProject.DEFAULT_PREFERENCES_DIRNAME).getFile(JavaProject.CLASSPATH_FILENAME).exists();
- }
-
- private void initJREEntry() {
- IIncludePathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary();
- try {
- IIncludePathEntry[] entries = getRawClassPath();
- for (int i = 0; i < entries.length; i++) {
- if (entries[i] == defaultJRELibrary[0]) {
- return;
- }
- }
- classPathEntries.add(defaultJRELibrary[0]);
- } catch (Exception e) {
- if (DEBUG) {
- System.out.println("Error checking sourcepath:" + e); //$NON-NLS-1$
- }
- }
- }
-
- private IIncludePathEntry[] initLocalClassPath() {
-
-
-
-
- //IPath webRoot = WebRootFinder.getWebContentFolder(fCurrProject);
- IIncludePathEntry source = JavaScriptCore.newSourceEntry(fCurrProject.getFullPath().append("/")); //$NON-NLS-1$
- // classPathEntries.add(source);
- return new IIncludePathEntry[] {source};
- }
-
- private void initOutputPath() {
- if (fOutputLocation == null) {
- fOutputLocation = fCurrProject.getFullPath();
- }
- }
-
- public void setProject(IProject project) {
- this.fCurrProject = project;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/IRefactoringProcessorIds.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/IRefactoringProcessorIds.java
deleted file mode 100644
index eebea213..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/IRefactoringProcessorIds.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.refactoring;
-
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameJavaProjectProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameResourceProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameSourceFolderProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaDeleteProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-
-/**
- * Interface to define the processor IDs provided by the JDT refactoring.
- *
- * <p>
- * This interface declares static final fields only; it is not intended to be
- * implemented.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- *
- */
-public interface IRefactoringProcessorIds {
-
- /**
- * Processor ID of the rename JavaScript project processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameJavaProjectProcessor"</code>).
- *
- * The rename JavaScript project processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IJavaScriptProject</code>.</li>
- * <li>participants registered for renaming <code>IProject</code>.</li>
- * </ul>
- */
- public static String RENAME_JAVA_PROJECT_PROCESSOR= RenameJavaProjectProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename source folder
- * (value <code>"org.eclipse.wst.jsdt.ui.renameSourceFolderProcessor"</code>).
- *
- * The rename package fragment root processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IPackageFragmentRoot</code>.</li>
- * <li>participants registered for renaming <code>IFolder</code>.</li>
- * </ul>
- */
- public static String RENAME_SOURCE_FOLDER_PROCESSOR= RenameSourceFolderProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename package fragment processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renamePackageProcessor"</code>).
- *
- * The rename package fragment processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IPackageFragment</code>.</li>
- * <li>participants registered for moving <code>IFile</code> to participate in the
- * file moves caused by the package fragment rename.</li>
- * <li>participants registered for creating <code>IFolder</code> if the package
- * rename results in creating a new destination folder.</li>
- * <li>participants registered for deleting <code>IFolder</code> if the package
- * rename results in deleting the folder corresponding to the package
- * fragment to be renamed.</li>
- * </ul>
- *
- * <p>Since 3.3:</p>
- *
- * <p>The refactoring processor moves and renames JavaScript elements and resources.
- * Rename package fragment participants can retrieve the new location of
- * JavaScript elements and resources through the interfaces
- * {@link org.eclipse.wst.jsdt.core.refactoring.IJavaScriptElementMapper} and {@link org.eclipse.ltk.core.refactoring.IResourceMapper}, which can be
- * retrieved from the processor using the getAdapter() method.</p>
- */
- public static String RENAME_PACKAGE_FRAGMENT_PROCESSOR= RenamePackageProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename compilation unit processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameCompilationUnitProcessor"</code>).
- *
- * The rename compilation unit processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IJavaScriptUnit</code>.</li>
- * <li>participants registered for renaming <code>IFile</code>.</li>
- * <li>participants registered for renaming <code>IType</code> if the
- * compilation unit contains a top level type.</li>
- * </ul>
- */
- public static String RENAME_COMPILATION_UNIT_PROCESSOR= RenameCompilationUnitProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename type processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameTypeProcessor"</code>).
- *
- * The rename type processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IType</code>.</li>
- * <li>participants registered for renaming <code>IJavaScriptUnit</code> if the
- * type is a public top level type.</li>
- * <li>participants registered for renaming <code>IFile</code> if the compilation
- * unit gets rename as well.</li>
- * </ul>
- *
- * <p>Since 3.2:</p>
- *
- * <p>Participants that declare <pre> &lt;param name="handlesSimilarDeclarations" value="false"/&gt; </pre>
- * in their extension contribution will not be loaded if the user selects the
- * "update similar declarations" feature.</p>
- *
- * <p>Rename type participants can retrieve information about similar declarations by casting the
- * RenameArguments to RenameTypeArguments. The new signatures of similar declarations
- * (and of other JavaScript elements or resources) are available
- * through the interfaces {@link org.eclipse.wst.jsdt.core.refactoring.IJavaScriptElementMapper} and {@link org.eclipse.ltk.core.refactoring.IResourceMapper}, which can be retrieved from the
- * processor using the getAdapter() method.</p>
- *
- */
- public static String RENAME_TYPE_PROCESSOR= RenameTypeProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename method processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameMethodProcessor"</code>).
- *
- * The rename method processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IFunction</code>. Renaming
- * virtual methods will rename methods with the same name in the type
- * hierarchy of the type declaring the method to be renamed as well.
- * For those derived methods participants will be loaded as well.</li>
- * </ul>
- */
- public static String RENAME_METHOD_PROCESSOR= RenameMethodProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename field processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameFieldProcessor"</code>).
- *
- * The rename filed processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IField</code>.</li>
- * <li>participants registered for renaming <code>IFunction</code> if
- * corresponding setter and getter methods are renamed as well.</li>
- * </ul>
- */
- public static String RENAME_FIELD_PROCESSOR= RenameFieldProcessor.IDENTIFIER;
-
-// /**
-// * Processor ID of the rename enum constant processor
-// * (value <code>"org.eclipse.wst.jsdt.ui.renameEnumConstProcessor"</code>).
-// *
-// * The rename filed processor loads the following participants:
-// * <ul>
-// * <li>participants registered for renaming <code>IField</code>.</li>
-// * </ul>
-// *
-// */
-// public static String RENAME_ENUM_CONSTANT_PROCESSOR= RenameEnumConstProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the rename resource processor
- * (value <code>"org.eclipse.wst.jsdt.ui.renameResourceProcessor"</code>).
- *
- * The rename resource processor loads the following participants:
- * <ul>
- * <li>participants registered for renaming <code>IResource</code>.</li>
- * </ul>
- */
- public static String RENAME_RESOURCE_PROCESSOR= RenameResourceProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the move resource processor
- * (value <code>"org.eclipse.wst.jsdt.ui.MoveProcessor"</code>).
- *
- * The move processor loads the following participants, depending on the type of
- * element that gets moved:
- * <ul>
- * <li><code>IPackageFragmentRoot</code>: participants registered for moving
- * package fragment roots together with participants moving a <code>IFolder
- * </code>.</li>
- * <li><code>IPackageFragment</code>: participants registered for moving
- * package fragments. Additionally move file, create folder and delete
- * folder participants are loaded to reflect the resource changes
- * caused by a moving a package fragment.</li>
- * <li><code>IJavaScriptUnit</code>: participants registered for moving
- * compilation units and <code>IFile</code>. If the compilation unit
- * contains top level types, participants for these types are loaded
- * as well.</li>
- * <li><code>IResource</code>: participants registered for moving resources.</li>
- * </ul>
- */
- public static String MOVE_PROCESSOR= JavaMoveProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the move static member processor
- * (value <code>"org.eclipse.wst.jsdt.ui.MoveStaticMemberProcessor"</code>).
- *
- * The move static members processor loads participants registered for the
- * static JavaScript element that gets moved. No support is available to participate
- * in non static member moves.
- */
- public static String MOVE_STATIC_MEMBERS_PROCESSOR= "org.eclipse.wst.jsdt.ui.MoveStaticMemberProcessor"; //$NON-NLS-1$
-
- /**
- * Processor ID of the delete resource processor
- * (value <code>"org.eclipse.wst.jsdt.ui.DeleteProcessor"</code>).
- *
- * The delete processor loads the following participants, depending on the type of
- * element that gets deleted:
- * <ul>
- * <li><code>IJavaScriptProject</code>: participants registered for deleting <code>IJavaScriptProject
- * </code> and <code>IProject</code></li>.
- * <li><code>IPackageFragmentRoot</code>: participants registered for deleting
- * <code>IPackageFragmentRoot</code> and <code>IFolder</code>.
- * <li><code>IPackageFragment</code>: participants registered for deleting
- * <code>IPackageFragment</code>. Additionally delete file and delete folder
- * participants are loaded to reflect the resource changes caused by
- * deleting a package fragment.</li>
- * <li><code>IJavaScriptUnit</code>: participants registered for deleting compilation
- * units and files. Additionally type delete participants are loaded to reflect the
- * deletion of the top level types declared in the compilation unit.</li>
- * <li><code>IType</code>: participants registered for deleting types. Additional
- * compilation unit and file delete participants are loaded if the type to be deleted
- * is the only top level type of a compilation unit.</li>
- * <li><code>IMember</code>: participants registered for deleting members.</li>
- * <li><code>IResource</code>: participants registered for deleting resources.</li>
- * </ul>
- */
- public static String DELETE_PROCESSOR= JavaDeleteProcessor.IDENTIFIER;
-
- /**
- * Processor ID of the copy processor (value <code>"org.eclipse.wst.jsdt.ui.CopyProcessor"</code>).
- *
- * The copy processor is used when copying elements via drag and drop or when pasting
- * elements from the clipboard. The copy processor loads the following participants,
- * depending on the type of the element that gets copied:
- * <ul>
- * <li><code>IJavaScriptProject</code>: no participants are loaded.</li>
- * <li><code>IPackageFragmentRoot</code>: participants registered for copying
- * <code>IPackageFragmentRoot</code> and <code>org.eclipse.core.resources.mapping.ResourceMapping</code>.</li>
- * <li><code>IPackageFragment</code>: participants registered for copying
- * <code>IPackageFragment</code> and <code>org.eclipse.core.resources.mapping.ResourceMapping</code>.</li>
- * <li><code>IJavaScriptUnit</code>: participants registered for copying
- * <code>IJavaScriptUnit</code> and <code>org.eclipse.core.resources.mapping.ResourceMapping</code>.</li>
- * <li><code>IType</code>: like IJavaScriptUnit if the primary top level type is copied.
- * Otherwise no participants are loaded.</li>
- * <li><code>IMember</code>: no participants are loaded.</li>
- * <li><code>IFolder</code>: participants registered for copying folders.</li>
- * <li><code>IFile</code>: participants registered for copying files.</li>
- * </ul>
- * <p>
- * Use the method {@link org.eclipse.core.resources.mapping.ResourceMapping#accept(org.eclipse.core.resources.mapping.ResourceMappingContext context, org.eclipse.core.resources.IResourceVisitor visitor, org.eclipse.core.runtime.IProgressMonitor monitor)}
- * to enumerate the resources which form the JavaScript element. <code>org.eclipse.core.resources.mapping.ResourceMappingContext.LOCAL_CONTEXT</code>
- * should be use as the <code>org.eclipse.core.resources.mapping.ResourceMappingContext</code> passed to the accept method.
- * </p>
- * @see org.eclipse.core.resources.mapping.ResourceMapping
- *
- */
- public static String COPY_PROCESSOR= JavaCopyProcessor.IDENTIFIER;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/RenameSupport.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/RenameSupport.java
deleted file mode 100644
index 97f42160..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/refactoring/RenameSupport.java
+++ /dev/null
@@ -1,471 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.refactoring;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.ltk.core.refactoring.RefactoringCore;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IField;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.ILocalVariable;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.refactoring.descriptors.RenameJavaScriptElementDescriptor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.JavaRenameRefactoring;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.MethodChecks;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameJavaProjectProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameLocalVariableProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameSourceFolderProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.INameUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.IReferenceUpdating;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.tagging.ITextUpdating;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.RefactoringExecutionHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.UserInterfaceStarter;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameRefactoringWizard;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameSelectionState;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameUserInterfaceManager;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.reorg.RenameUserInterfaceStarter;
-
-/**
- * Central access point to execute rename refactorings.
- * <p>
- * Note: this class is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- */
-public class RenameSupport {
-
- private RenameRefactoring fRefactoring;
- private RefactoringStatus fPreCheckStatus;
-
- /**
- * Executes some light weight precondition checking. If the returned status
- * is an error then the refactoring can't be executed at all. However,
- * returning an OK status doesn't guarantee that the refactoring can be
- * executed. It may still fail while performing the exhaustive precondition
- * checking done inside the methods <code>openDialog</code> or
- * <code>perform</code>.
- *
- * The method is mainly used to determine enable/disablement of actions.
- *
- * @return the result of the light weight precondition checking.
- *
- * @throws CoreException if an unexpected exception occurs while performing the checking.
- *
- * @see #openDialog(Shell)
- * @see #perform(Shell, IRunnableContext)
- */
- public IStatus preCheck() throws CoreException {
- ensureChecked();
- if (fPreCheckStatus.hasFatalError())
- return fPreCheckStatus.getEntryMatchingSeverity(RefactoringStatus.FATAL).toStatus();
- else
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
- }
-
- /**
- * Opens the refactoring dialog for this rename support.
- *
- * @param parent a shell used as a parent for the refactoring dialog.
- * @throws CoreException if an unexpected exception occurs while opening the
- * dialog.
- *
- * @see #openDialog(Shell, boolean)
- */
- public void openDialog(Shell parent) throws CoreException {
- openDialog(parent, false);
- }
-
- /**
- * Opens the refactoring dialog for this rename support.
- *
- * <p>
- * This method has to be called from within the UI thread.
- * </p>
- *
- * @param parent a shell used as a parent for the refactoring, preview, or error dialog
- * @param showPreviewOnly if <code>true</code>, the dialog skips all user input pages and
- * directly shows the preview or error page. Otherwise, shows all pages.
- * @return <code>true</code> if the refactoring has been executed successfully,
- * <code>false</code> if it has been canceled or if an error has happened during
- * initial conditions checking.
- *
- * @throws CoreException if an error occurred while executing the
- * operation.
- *
- * @see #openDialog(Shell)
- *
- */
- public boolean openDialog(Shell parent, boolean showPreviewOnly) throws CoreException {
- ensureChecked();
- if (fPreCheckStatus.hasFatalError()) {
- showInformation(parent, fPreCheckStatus);
- return false;
- }
-
- UserInterfaceStarter starter;
- if (! showPreviewOnly) {
- starter= RenameUserInterfaceManager.getDefault().getStarter(fRefactoring);
- } else {
- starter= new RenameUserInterfaceStarter();
- RenameRefactoringWizard wizard= new RenameRefactoringWizard(fRefactoring, fRefactoring.getName(), null, null, null) {
- protected void addUserInputPages() {
- // nothing to add
- }
- };
- wizard.setForcePreviewReview(showPreviewOnly);
- starter.initialize(wizard);
- }
- return starter.activate(fRefactoring, parent, getJavaRenameProcessor().getSaveMode());
- }
-
- /**
- * Executes the rename refactoring without showing a dialog to gather
- * additional user input (for example the new name of the <tt>IJavaScriptElement</tt>).
- * Only an error dialog is shown (if necessary) to present the result
- * of the refactoring's full precondition checking.
- * <p>
- * The method has to be called from within the UI thread.
- * </p>
- *
- * @param parent a shell used as a parent for the error dialog.
- * @param context a {@link IRunnableContext} to execute the operation.
- *
- * @throws InterruptedException if the operation has been canceled by the
- * user.
- * @throws InvocationTargetException if an error occurred while executing the
- * operation.
- *
- * @see #openDialog(Shell)
- * @see IRunnableContext#run(boolean, boolean, org.eclipse.jface.operation.IRunnableWithProgress)
- */
- public void perform(Shell parent, IRunnableContext context) throws InterruptedException, InvocationTargetException {
- try {
- ensureChecked();
- if (fPreCheckStatus.hasFatalError()) {
- showInformation(parent, fPreCheckStatus);
- return;
- }
-
- RenameSelectionState state= createSelectionState();
-
- RefactoringExecutionHelper helper= new RefactoringExecutionHelper(fRefactoring,
- RefactoringCore.getConditionCheckingFailedSeverity(),
- getJavaRenameProcessor().getSaveMode(),
- parent,
- context);
- helper.perform(true, true);
-
- restoreSelectionState(state);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
-
- /** Flag indication that no additional update is to be performed. */
- public static final int NONE= 0;
-
- /** Flag indicating that references are to be updated as well. */
- public static final int UPDATE_REFERENCES= 1 << 0;
-
- /**
- * Flag indicating that textual matches in comments and in string literals
- * are to be updated as well.
- *
- */
- public static final int UPDATE_TEXTUAL_MATCHES= 1 << 6;
-
- /** Flag indicating that the getter method is to be updated as well. */
- public static final int UPDATE_GETTER_METHOD= 1 << 4;
-
- /** Flag indicating that the setter method is to be updated as well. */
- public static final int UPDATE_SETTER_METHOD= 1 << 5;
-
-
- private RenameSupport(RenameJavaScriptElementDescriptor descriptor) throws CoreException {
- RefactoringStatus refactoringStatus= new RefactoringStatus();
- fRefactoring= (RenameRefactoring) descriptor.createRefactoring(refactoringStatus);
- if (refactoringStatus.hasFatalError()) {
- fPreCheckStatus= refactoringStatus;
- } else {
- preCheck();
- refactoringStatus.merge(fPreCheckStatus);
- fPreCheckStatus= refactoringStatus;
- }
- }
-
- /**
- * Creates a new rename support for the given
- * {@link RenameJavaScriptElementDescriptor}.
- *
- * @param descriptor the {@link RenameJavaScriptElementDescriptor} to create a
- * {@link RenameSupport} for. The caller is responsible for
- * configuring the descriptor before it is passed.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating the
- * {@link RenameSupport}.
- *
- */
- public static RenameSupport create(RenameJavaScriptElementDescriptor descriptor) throws CoreException {
- return new RenameSupport(descriptor);
- }
-
- private RenameSupport(JavaRenameProcessor processor, String newName, int flags) throws CoreException {
- fRefactoring= new JavaRenameRefactoring(processor);
- initialize(fRefactoring, newName, flags);
- }
-
- private JavaRenameProcessor getJavaRenameProcessor() {
- return (JavaRenameProcessor) fRefactoring.getProcessor();
- }
-
- /**
- * Creates a new rename support for the given {@link IJavaScriptProject}.
- *
- * @param project the {@link IJavaScriptProject} to be renamed.
- * @param newName the project's new name. <code>null</code> is a valid
- * value indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IJavaScriptProject project, String newName, int flags) throws CoreException {
- JavaRenameProcessor processor= new RenameJavaProjectProcessor(project);
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link IPackageFragmentRoot}.
- *
- * @param root the {@link IPackageFragmentRoot} to be renamed.
- * @param newName the package fragment root's new name. <code>null</code> is
- * a valid value indicating that no new name is provided.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IPackageFragmentRoot root, String newName) throws CoreException {
- JavaRenameProcessor processor= new RenameSourceFolderProcessor(root);
- return new RenameSupport(processor, newName, 0);
- }
-
- /**
- * Creates a new rename support for the given {@link IPackageFragment}.
- *
- * @param fragment the {@link IPackageFragment} to be renamed.
- * @param newName the package fragment's new name. <code>null</code> is a
- * valid value indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code>, and <code>UPDATE_TEXTUAL_MATCHES</code>,
- * or their bitwise OR, or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IPackageFragment fragment, String newName, int flags) throws CoreException {
- JavaRenameProcessor processor= new RenamePackageProcessor(fragment);
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link IJavaScriptUnit}.
- *
- * @param unit the {@link IJavaScriptUnit} to be renamed.
- * @param newName the compilation unit's new name. <code>null</code> is a
- * valid value indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code>, and <code>UPDATE_TEXTUAL_MATCHES</code>,
- * or their bitwise OR, or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IJavaScriptUnit unit, String newName, int flags) throws CoreException {
- JavaRenameProcessor processor= new RenameCompilationUnitProcessor(unit);
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link IType}.
- *
- * @param type the {@link IType} to be renamed.
- * @param newName the type's new name. <code>null</code> is a valid value
- * indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code>, and <code>UPDATE_TEXTUAL_MATCHES</code>,
- * or their bitwise OR, or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IType type, String newName, int flags) throws CoreException {
- JavaRenameProcessor processor= new RenameTypeProcessor(type);
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link IFunction}.
- *
- * @param method the {@link IFunction} to be renamed.
- * @param newName the method's new name. <code>null</code> is a valid value
- * indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IFunction method, String newName, int flags) throws CoreException {
- JavaRenameProcessor processor;
- if (MethodChecks.isVirtual(method)) {
- processor= new RenameVirtualMethodProcessor(method);
- } else {
- processor= new RenameNonVirtualMethodProcessor(method);
- }
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link IField}.
- *
- * @param field the {@link IField} to be renamed.
- * @param newName the field's new name. <code>null</code> is a valid value
- * indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code>, <code>UPDATE_TEXTUAL_MATCHES</code>,
- * <code>UPDATE_GETTER_METHOD</code>, and <code>UPDATE_SETTER_METHOD</code>,
- * or their bitwise OR, or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- */
- public static RenameSupport create(IField field, String newName, int flags) throws CoreException {
- final RenameFieldProcessor processor= new RenameFieldProcessor(field);
- processor.setRenameGetter(updateGetterMethod(flags));
- processor.setRenameSetter(updateSetterMethod(flags));
- return new RenameSupport(processor, newName, flags);
- }
-
- /**
- * Creates a new rename support for the given {@link ILocalVariable}.
- *
- * @param variable the {@link ILocalVariable} to be renamed.
- * @param newName the variable's new name. <code>null</code> is a valid value
- * indicating that no new name is provided.
- * @param flags flags controlling additional parameters. Valid flags are
- * <code>UPDATE_REFERENCES</code>, or <code>NONE</code>.
- * @return the {@link RenameSupport}.
- * @throws CoreException if an unexpected error occurred while creating
- * the {@link RenameSupport}.
- *
- */
- public static RenameSupport create(ILocalVariable variable, String newName, int flags) throws CoreException {
- RenameLocalVariableProcessor processor= new RenameLocalVariableProcessor(variable);
- processor.setUpdateReferences(updateReferences(flags));
- return new RenameSupport(processor, newName, flags);
- }
-
- private static void initialize(RenameRefactoring refactoring, String newName, int flags) {
- if (refactoring.getProcessor() == null)
- return;
- setNewName((INameUpdating)refactoring.getAdapter(INameUpdating.class), newName);
- IReferenceUpdating reference= (IReferenceUpdating)refactoring.getAdapter(IReferenceUpdating.class);
- if (reference != null) {
- reference.setUpdateReferences(updateReferences(flags));
- }
- ITextUpdating text= (ITextUpdating)refactoring.getAdapter(ITextUpdating.class);
- if (text != null) {
- text.setUpdateTextualMatches(updateTextualMatches(flags));
- }
- }
-
- private static void setNewName(INameUpdating refactoring, String newName) {
- if (newName != null)
- refactoring.setNewElementName(newName);
- }
-
- private static boolean updateReferences(int flags) {
- return (flags & UPDATE_REFERENCES) != 0;
- }
-
- private static boolean updateTextualMatches(int flags) {
- int TEXT_UPDATES= UPDATE_TEXTUAL_MATCHES;
- return (flags & TEXT_UPDATES) != 0;
- }
-
- private static boolean updateGetterMethod(int flags) {
- return (flags & UPDATE_GETTER_METHOD) != 0;
- }
-
- private static boolean updateSetterMethod(int flags) {
- return (flags & UPDATE_SETTER_METHOD) != 0;
- }
-
- private void ensureChecked() throws CoreException {
- if (fPreCheckStatus == null) {
- if (!fRefactoring.isApplicable()) {
- fPreCheckStatus= RefactoringStatus.createFatalErrorStatus(JavaUIMessages.RenameSupport_not_available);
- } else {
- fPreCheckStatus= new RefactoringStatus();
- }
- }
- }
-
- private void showInformation(Shell parent, RefactoringStatus status) {
- String message= status.getMessageMatchingSeverity(RefactoringStatus.FATAL);
- MessageDialog.openInformation(parent, JavaUIMessages.RenameSupport_dialog_title, message);
- }
-
- private RenameSelectionState createSelectionState() {
- RenameProcessor processor= (RenameProcessor) fRefactoring.getAdapter(RenameProcessor.class);
- Object[] elements= processor.getElements();
- RenameSelectionState state= elements.length == 1 ? new RenameSelectionState(elements[0]) : null;
- return state;
- }
-
- private void restoreSelectionState(RenameSelectionState state) throws CoreException {
- INameUpdating nameUpdating= (INameUpdating) fRefactoring.getAdapter(INameUpdating.class);
- if (nameUpdating != null && state != null) {
- Object newElement= nameUpdating.getNewElement();
- if (newElement != null) {
- state.restore(newElement);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ElementQuerySpecification.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ElementQuerySpecification.java
deleted file mode 100644
index 76e65615..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ElementQuerySpecification.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-
-/**
- * <p>
- * Describes a search query by giving the {@link IJavaScriptElement} to search
- * for.
- * </p>
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.ui.search.QuerySpecification
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class ElementQuerySpecification extends QuerySpecification {
- private IJavaScriptElement fElement;
-
- /**
- * A constructor.
- * @param javaElement The JavaScript element the query should search for.
- * @param limitTo The kind of occurrence the query should search for.
- * @param scope The scope to search in.
- * @param scopeDescription A human readable description of the search scope.
- */
- public ElementQuerySpecification(IJavaScriptElement javaElement, int limitTo, IJavaScriptSearchScope scope, String scopeDescription) {
- super(limitTo, scope, scopeDescription);
- fElement= javaElement;
- }
-
- /**
- * Returns the element to search for.
- * @return The element to search for.
- */
- public IJavaScriptElement getElement() {
- return fElement;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IMatchPresentation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IMatchPresentation.java
deleted file mode 100644
index 0e60cc04..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IMatchPresentation.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.search.ui.text.Match;
-import org.eclipse.ui.PartInitException;
-
-/**
- * This interface serves to display elements that a search participant has contributed to a search
- * result.
- * <p>
- * Each {@link IMatchPresentation} is associated with a particular {@link IQueryParticipant}. The {@link IMatchPresentation}
- * will only be asked to handle elements and matches which its {@link IQueryParticipant} contributed to the
- * search result. If two search participants report matches against the same element, one of them will
- * be chosen to handle the element.
- * </p>
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IMatchPresentation {
- /**
- * Creates a new instance of a label provider for elements that have been contributed
- * to a search result by the corresponding query participant. The search view
- * will call this method when it needs to render elements and will dispose the
- * label providers when it is done with them. This method may therefore be called
- * multiple times.
- * @return A label provider for elements found by the corresponding query participant.
- */
- ILabelProvider createLabelProvider();
- /**
- * Opens an editor on the given element and selects the given range of text.
- * The location of matches are automatically updated when a file is edited
- * through the file buffer infrastructure (see {@link org.eclipse.core.filebuffers.ITextFileBufferManager}).
- * When a file buffer is saved, the current positions are written back to the
- * match.
- * If the <code>activate</code> parameter is <code>true</code> the opened editor
- * should have be activated. Otherwise the focus should not be changed.
- *
- * @param match
- * The match to show.
- * @param currentOffset
- * The current start offset of the match.
- * @param currentLength
- * The current length of the selection.
- * @param activate
- * Whether to activate the editor the match is shown in.
- * @throws PartInitException
- * If an editor can't be opened.
- */
- void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException;
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IQueryParticipant.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IQueryParticipant.java
deleted file mode 100644
index 1938812a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/IQueryParticipant.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * This is the interface expected of extensions to the extension point
- * <code>org.eclipse.wst.jsdt.ui.queryParticipants</code>.
- * <p>
- * A <code>IQueryParticipant</code> is called during the execution of a
- * JavaScript search query. It can report matches via an {@link ISearchRequestor} and
- * may contribute a {@link IMatchPresentation} to help render the elements it contributes.
- * </p>
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IQueryParticipant {
- /**
- * Executes the search described by the given <code>querySpecification</code>. Matches are reported
- * to the given <code>requester</code>.
- * The interpretation of what a given JavaScript search (e.g. "References to class Foo") means is up to the
- * participant.
- * @param requestor The requester to report matches to.
- * @param querySpecification The specification of the query to run.
- * @param monitor A monitor to report progress on.
- * @throws CoreException Thrown when the search can not be executed
- */
- void search(ISearchRequestor requestor, QuerySpecification querySpecification, IProgressMonitor monitor) throws CoreException;
- /**
- * Returns the number of units of work estimated. The returned number should be normalized such
- * that the number of ticks for the original JavaScript search job is 1000. For example if the participant
- * uses the same amount of time as the JavaScript search, it should return 1000, if it uses half the time,
- * it should return 500, etc.
- * This method is supposed to give a quick estimate of the work to be done and is assumed
- * to be much faster than the actual query.
- * @param specification the specification to estimate.
- * @return The number of ticks estimated.
- */
- int estimateTicks(QuerySpecification specification);
- /**
- * Gets the UI participant responsible for handling the display of elements not known to the JavaScript search UI. The JavaScript search UI knows
- * elements are of type <code>IJavaScriptElement</code> and <code>IResource</code>.
- * A participant may return <code>null</code> if matches are only reported against elements of type <code>IResource</code> and <code>IJavaScriptElement</code>.
- * @return The UI participant for this query participant or <code>null</code>.
- */
- IMatchPresentation getUIParticipant();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java
deleted file mode 100644
index e4895e7f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.search.ui.text.Match;
-
-/**
- * A callback interface to report matches against. This class serves as a bottleneck and minimal interface
- * to report matches to the JavaScript search infrastructure. Query participants will be passed an
- * instance of this interface when their <code>search(...)</code> method is called.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface ISearchRequestor {
- /**
- * Adds a match to the search that issued this particular {@link ISearchRequestor}.
- * @param match The match to be reported.
- */
- void reportMatch(Match match);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/PatternQuerySpecification.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/PatternQuerySpecification.java
deleted file mode 100644
index 82127814..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/PatternQuerySpecification.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-
-
-/**
- * <p>
- * Describes a search query by giving a textual pattern to search for.
- * </p>
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * @see org.eclipse.wst.jsdt.ui.search.QuerySpecification
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class PatternQuerySpecification extends QuerySpecification {
- private String fPattern;
- private int fSearchFor;
- private boolean fCaseSensitive;
-
- /**
- * @param pattern
- * The string that the query should search for.
- * @param searchFor
- * What kind of <code>IJavaScriptElement</code> the query should search for.
- * @param caseSensitive
- * Whether the query should be case sensitive.
- * @param limitTo
- * The kind of occurrence the query should search for.
- * @param scope
- * The scope to search in.
- * @param scopeDescription
- * A human readable description of the search scope.
- *
- * @see org.eclipse.wst.jsdt.core.search.SearchPattern#createPattern(java.lang.String, int, int, int)
- */
- public PatternQuerySpecification(String pattern, int searchFor, boolean caseSensitive, int limitTo, IJavaScriptSearchScope scope, String scopeDescription) {
- super(limitTo, scope, scopeDescription);
- fPattern= pattern;
- fSearchFor= searchFor;
- fCaseSensitive= caseSensitive;
- }
-
- /**
- * Whether the query should be case sensitive.
- * @return Whether the query should be case sensitive.
- */
- public boolean isCaseSensitive() {
- return fCaseSensitive;
- }
-
- /**
- * Returns the search pattern the query should search for.
- * @return the search pattern
- * @see org.eclipse.wst.jsdt.core.search.SearchPattern#createPattern(java.lang.String, int, int, int)
- */
- public String getPattern() {
- return fPattern;
- }
-
- /**
- * Returns what kind of <code>IJavaScriptElement</code> the query should search for.
- *
- * @return The kind of <code>IJavaScriptElement</code> to search for.
- *
- * @see org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants
- */
- public int getSearchFor() {
- return fSearchFor;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/QuerySpecification.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/QuerySpecification.java
deleted file mode 100644
index f4237291..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/QuerySpecification.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.search;
-
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-
-/**
- * <p>
- * Describes a JavaScript search query. A query is described by giving a scope, a
- * scope description, what kind of match to search for (reference, declarations,
- * etc) and either a JavaScript element or a string and what kind of element to search
- * for (type, field, etc). What exactly it means to, for example, to search for
- * "references to type foo" is up to query participants. For example, a
- * participant might consider the "class" attribute of an extension in a
- * plugin.xml file to be a reference to the class mentioned in the attribute.
- * </p>
- *
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class QuerySpecification {
- private IJavaScriptSearchScope fScope;
- private int fLimitTo;
- private String fScopeDescription;
-
- QuerySpecification(int limitTo, IJavaScriptSearchScope scope, String scopeDescription) {
- fScope= scope;
- fLimitTo= limitTo;
- fScopeDescription= scopeDescription;
- }
-
- /**
- * Returns the search scope to be used in the query.
- * @return The search scope.
- */
- public IJavaScriptSearchScope getScope() {
- return fScope;
- }
-
- /**
- * Returns a human readable description of the search scope.
- * @return A description of the search scope.
- * @see QuerySpecification#getScope()
- */
- public String getScopeDescription() {
- return fScopeDescription;
- }
-
- /**
- * Returns what kind of occurrences the query should look for.
- * @return Whether to search for reference, declaration, etc.
- * @see org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants
- */
- public int getLimitTo() {
- return fLimitTo;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManager.java
deleted file mode 100644
index c5754283..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManager.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-import org.eclipse.jface.text.source.ISharedTextColors;
-import org.eclipse.swt.graphics.Color;
-
-
-/**
- * Manages SWT color objects for the given color keys and
- * given <code>RGB</code> objects. Until the <code>dispose</code>
- * method is called, the same color object is returned for
- * equal keys and equal <code>RGB</code> values.
- * <p>
- * In order to provide backward compatibility for clients of <code>IColorManager</code>, extension
- * interfaces are used to provide a means of evolution. The following extension interfaces exist:
- * <ul>
- * <li>{@link org.eclipse.wst.jsdt.ui.text.IColorManagerExtension} since version 2.0 introducing
- * the ability to bind and un-bind colors.</li>
- * </ul>
- * </p>
- * <p>
- * This interface may be implemented by clients.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- * @see org.eclipse.wst.jsdt.ui.text.IColorManagerExtension
- * @see org.eclipse.wst.jsdt.ui.text.IJavaScriptColorConstants
- *
- */
-public interface IColorManager extends ISharedTextColors {
-
- /**
- * Returns a color object for the given key. The color objects
- * are remembered internally; the same color object is returned
- * for equal keys.
- *
- * @param key the color key
- * @return the color object for the given key
- */
- Color getColor(String key);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManagerExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManagerExtension.java
deleted file mode 100644
index 56f6fc5f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IColorManagerExtension.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-import org.eclipse.swt.graphics.RGB;
-
-
-/**
- * Extends {@link org.eclipse.wst.jsdt.ui.text.IColorManager} with
- * the ability to bind and un-bind colors.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IColorManagerExtension {
-
- /**
- * Remembers the given color specification under the given key.
- *
- * @param key the color key
- * @param rgb the color specification
- * @throws java.lang.UnsupportedOperationException if there is already a
- * color specification remembered under the given key
- */
- void bindColor(String key, RGB rgb);
-
-
- /**
- * Forgets the color specification remembered under the given key.
- *
- * @param key the color key
- */
- void unbindColor(String key);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptColorConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptColorConstants.java
deleted file mode 100644
index 318ca647..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptColorConstants.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-/**
- * Color keys used for syntax highlighting Java
- * code and Javadoc compliant comments.
- * A <code>IColorManager</code> is responsible for mapping
- * concrete colors to these keys.
- * <p>
- * This interface declares static final fields only; it is not intended to be
- * implemented.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. *
- * @see org.eclipse.wst.jsdt.ui.text.IColorManager
- * @see org.eclipse.wst.jsdt.ui.text.IColorManagerExtension
- */
-public interface IJavaScriptColorConstants {
-
- /**
- * Note: This constant is for internal use only. Clients should not use this constant.
- * The prefix all color constants start with
- * (value <code>"java_"</code>).
- */
- String PREFIX= "java_"; //$NON-NLS-1$
-
- /** The color key for multi-line comments in JavaScript code
- * (value <code>"java_multi_line_comment"</code>).
- */
- String JAVA_MULTI_LINE_COMMENT= "java_multi_line_comment"; //$NON-NLS-1$
-
- /** The color key for single-line comments in JavaScript code
- * (value <code>"java_single_line_comment"</code>).
- */
- String JAVA_SINGLE_LINE_COMMENT= "java_single_line_comment"; //$NON-NLS-1$
-
- /** The color key for JavaScript keywords in JavaScript code
- * (value <code>"java_keyword"</code>).
- */
- String JAVA_KEYWORD= "java_keyword"; //$NON-NLS-1$
-
- /** The color key for string and character literals in JavaScript code
- * (value <code>"java_string"</code>).
- */
- String JAVA_STRING= "java_string"; //$NON-NLS-1$
-
- /** The color key for method names in JavaScript code
- * (value <code>"java_method_name"</code>).
- *
- *
- * @deprecated replaced as of 3.1 by an equivalent semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#METHOD}
- */
- String JAVA_METHOD_NAME= "java_method_name"; //$NON-NLS-1$
-
- /** The color key for keyword 'return' in JavaScript code
- * (value <code>"java_keyword_return"</code>).
- *
- *
- */
- String JAVA_KEYWORD_RETURN= "java_keyword_return"; //$NON-NLS-1$
-
- /** The color key for operators in JavaScript code
- * (value <code>"java_operator"</code>).
- *
- *
- */
- String JAVA_OPERATOR= "java_operator"; //$NON-NLS-1$
-
- /** The color key for brackets in JavaScript code
- * (value <code>"java_bracket"</code>).
- *
- *
- */
- String JAVA_BRACKET= "java_bracket"; //$NON-NLS-1$
-
- /**
- * The color key for everything in JavaScript code for which no other color is specified
- * (value <code>"java_default"</code>).
- */
- String JAVA_DEFAULT= "java_default"; //$NON-NLS-1$
-
- /**
- * The color key for annotations
- * (value <code>"java_annotation"</code>).
- *
- *
- * @deprecated replaced as of 3.2 by an equivalent semantic highlighting, see {@link org.eclipse.wst.jsdt.internal.ui.javaeditor.SemanticHighlightings#ANNOTATION}
- */
- String JAVA_ANNOTATION= "java_annotation"; //$NON-NLS-1$
-
- /**
- * The color key for task tags in JavaScript comments
- * (value <code>"java_comment_task_tag"</code>).
- *
- *
- */
- String TASK_TAG= "java_comment_task_tag"; //$NON-NLS-1$
-
- /**
- * The color key for JavaDoc keywords (<code>@foo</code>) in JavaDoc comments
- * (value <code>"java_doc_keyword"</code>).
- */
- String JAVADOC_KEYWORD= "java_doc_keyword"; //$NON-NLS-1$
-
- /**
- * The color key for HTML tags (<code>&lt;foo&gt;</code>) in JavaDoc comments
- * (value <code>"java_doc_tag"</code>).
- */
- String JAVADOC_TAG= "java_doc_tag"; //$NON-NLS-1$
-
- /**
- * The color key for JavaDoc links (<code>{foo}</code>) in JavaDoc comments
- * (value <code>"java_doc_link"</code>).
- */
- String JAVADOC_LINK= "java_doc_link"; //$NON-NLS-1$
-
- /**
- * The color key for everything in JavaDoc comments for which no other color is specified
- * (value <code>"java_doc_default"</code>).
- */
- String JAVADOC_DEFAULT= "java_doc_default"; //$NON-NLS-1$
-
- //---------- Properties File Editor ----------
-
- /**
- * The color key for keys in a properties file
- * (value <code>"pf_coloring_key"</code>).
- *
- *
- */
- String PROPERTIES_FILE_COLORING_KEY= "pf_coloring_key"; //$NON-NLS-1$
-
- /**
- * The color key for comments in a properties file
- * (value <code>"pf_coloring_comment"</code>).
- *
- *
- */
-
- String PROPERTIES_FILE_COLORING_COMMENT= "pf_coloring_comment"; //$NON-NLS-1$
-
- /**
- * The color key for values in a properties file
- * (value <code>"pf_coloring_value"</code>).
- *
- *
- */
- String PROPERTIES_FILE_COLORING_VALUE= "pf_coloring_value"; //$NON-NLS-1$
-
- /**
- * The color key for assignment in a properties file.
- * (value <code>"pf_coloring_assignment"</code>).
- *
- *
- */
- String PROPERTIES_FILE_COLORING_ASSIGNMENT= "pf_coloring_assignment"; //$NON-NLS-1$
-
- /**
- * The color key for arguments in values in a properties file.
- * (value <code>"pf_coloring_argument"</code>).
- *
- *
- */
- String PROPERTIES_FILE_COLORING_ARGUMENT= "pf_coloring_argument"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptPartitions.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptPartitions.java
deleted file mode 100644
index a36b2ba9..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/IJavaScriptPartitions.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-/**
- * Definition of JavaScript partitioning and its partitions.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaScriptPartitions {
-
- /**
- * The identifier of the JavaScript partitioning.
- */
- String JAVA_PARTITIONING= "___java_partitioning"; //$NON-NLS-1$
-
- /**
- * The identifier of the single-line (JLS2: EndOfLineComment) end comment partition content type.
- */
- String JAVA_SINGLE_LINE_COMMENT= "__java_singleline_comment"; //$NON-NLS-1$
-
- /**
- * The identifier multi-line (JLS2: TraditionalComment) comment partition content type.
- */
- String JAVA_MULTI_LINE_COMMENT= "__java_multiline_comment"; //$NON-NLS-1$
-
- /**
- * The identifier of the Javadoc (JLS2: DocumentationComment) partition content type.
- */
- String JAVA_DOC= "__java_javadoc"; //$NON-NLS-1$
-
- /**
- * The identifier of the JavaScript string partition content type.
- */
- String JAVA_STRING= "__java_string"; //$NON-NLS-1$
-
- /**
- * The identifier of the JavaScript character partition content type.
- */
- String JAVA_CHARACTER= "__java_character"; //$NON-NLS-1$
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java
deleted file mode 100644
index eab76b2e..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java
+++ /dev/null
@@ -1,849 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * Tom Eicher (Avaloq Evolution AG) - block selection mode
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-import java.util.Arrays;
-import java.util.Map;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.AbstractInformationControlManager;
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
-import org.eclipse.jface.text.IAutoEditStrategy;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IInformationControl;
-import org.eclipse.jface.text.IInformationControlCreator;
-import org.eclipse.jface.text.ITextDoubleClickStrategy;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextViewerExtension2;
-import org.eclipse.jface.text.contentassist.ContentAssistant;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContentAssistant;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.formatter.MultiPassContentFormatter;
-import org.eclipse.jface.text.information.IInformationPresenter;
-import org.eclipse.jface.text.information.IInformationProvider;
-import org.eclipse.jface.text.information.InformationPresenter;
-import org.eclipse.jface.text.presentation.IPresentationReconciler;
-import org.eclipse.jface.text.presentation.PresentationReconciler;
-import org.eclipse.jface.text.quickassist.IQuickAssistAssistant;
-import org.eclipse.jface.text.reconciler.IReconciler;
-import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
-import org.eclipse.jface.text.rules.RuleBasedScanner;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationHover;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
-import org.eclipse.ui.texteditor.ChainedPreferenceStore;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.IClassFileEditorInput;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.AbstractJavaScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.ContentAssistPreference;
-import org.eclipse.wst.jsdt.internal.ui.text.HTMLAnnotationHover;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCommentScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCompositeReconcilingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaElementProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaOutlineInformationControl;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaPresentationReconciler;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaReconciler;
-import org.eclipse.wst.jsdt.internal.ui.text.PreferencesAdapter;
-import org.eclipse.wst.jsdt.internal.ui.text.SingleTokenJavaScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionAssistant;
-import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaAutoIndentStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCodeScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaDoubleClickSelector;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaFormattingStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaStringDoubleClickSelector;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavadocDoubleClickStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
-import org.eclipse.wst.jsdt.internal.ui.text.java.hover.JavaInformationProvider;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDocScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavadocCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.typehierarchy.HierarchyInformationControl;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-import org.eclipse.wst.jsdt.ui.actions.IJavaEditorActionDefinitionIds;
-
-
-/**
- * Configuration for a source viewer which shows JavaScript code.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptSourceViewerConfiguration extends TextSourceViewerConfiguration {
-
- private JavaScriptTextTools fJavaTextTools;
- private ITextEditor fTextEditor;
- /**
- * The document partitioning.
- *
- */
- private String fDocumentPartitioning;
- /**
- * The JavaScript source code scanner.
- *
- */
- private AbstractJavaScanner fCodeScanner;
- /**
- * The JavaScript multi-line comment scanner.
- *
- */
- private AbstractJavaScanner fMultilineCommentScanner;
- /**
- * The JavaScript single-line comment scanner.
- *
- */
- private AbstractJavaScanner fSinglelineCommentScanner;
- /**
- * The JavaScript string scanner.
- *
- */
- private AbstractJavaScanner fStringScanner;
- /**
- * The Javadoc scanner.
- *
- */
- private AbstractJavaScanner fJavaDocScanner;
- /**
- * The color manager.
- *
- */
- private IColorManager fColorManager;
- /**
- * The double click strategy.
- *
- */
- private JavaDoubleClickSelector fJavaDoubleClickSelector;
-
-
- /**
- * Creates a new JavaScript source viewer configuration for viewers in the given editor
- * using the given preference store, the color manager and the specified document partitioning.
- * <p>
- * Creates a JavaScript source viewer configuration in the new setup without text tools. Clients are
- * allowed to call {@link JavaScriptSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}
- * on the resulting
- * JavaScript source viewer configuration.
- * </p>
- *
- * @param colorManager the color manager
- * @param preferenceStore the preference store, can be read-only
- * @param editor the editor in which the configured viewer(s) will reside, or <code>null</code> if none
- * @param partitioning the document partitioning for this configuration, or <code>null</code> for the default partitioning
- *
- */
- public JavaScriptSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, String partitioning) {
- super(preferenceStore);
- fColorManager= colorManager;
- fTextEditor= editor;
- fDocumentPartitioning= partitioning;
- initializeScanners();
- }
-
- /**
- * Returns the JavaScript source code scanner for this configuration.
- *
- * @return the JavaScript source code scanner
- */
- protected RuleBasedScanner getCodeScanner() {
- return fCodeScanner;
- }
-
- /**
- * Returns the JavaScript multi-line comment scanner for this configuration.
- *
- * @return the JavaScript multi-line comment scanner
- *
- */
- protected RuleBasedScanner getMultilineCommentScanner() {
- return fMultilineCommentScanner;
- }
-
- /**
- * Returns the JavaScript single-line comment scanner for this configuration.
- *
- * @return the JavaScript single-line comment scanner
- *
- */
- protected RuleBasedScanner getSinglelineCommentScanner() {
- return fSinglelineCommentScanner;
- }
-
- /**
- * Returns the JavaScript string scanner for this configuration.
- *
- * @return the JavaScript string scanner
- *
- */
- protected RuleBasedScanner getStringScanner() {
- return fStringScanner;
- }
-
- /**
- * Returns the JavaDoc scanner for this configuration.
- *
- * @return the JavaDoc scanner
- */
- protected RuleBasedScanner getJavaDocScanner() {
- return fJavaDocScanner;
- }
-
- /**
- * Returns the color manager for this configuration.
- *
- * @return the color manager
- */
- protected IColorManager getColorManager() {
- return fColorManager;
- }
-
- /**
- * Returns the editor in which the configured viewer(s) will reside.
- *
- * @return the enclosing editor
- */
- protected ITextEditor getEditor() {
- return fTextEditor;
- }
-
- /**
- * @return <code>true</code> iff the new setup without text tools is in use.
- *
- *
- */
- private boolean isNewSetup() {
- return fJavaTextTools == null;
- }
-
- /**
- * Creates and returns a preference store which combines the preference
- * stores from the text tools and which is read-only.
- *
- * @param javaTextTools the JavaScript text tools
- * @return the combined read-only preference store
- *
- */
- private static final IPreferenceStore createPreferenceStore(JavaScriptTextTools javaTextTools) {
- Assert.isNotNull(javaTextTools);
- IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
- if (javaTextTools.getCorePreferenceStore() == null)
- return new ChainedPreferenceStore(new IPreferenceStore[] { javaTextTools.getPreferenceStore(), generalTextStore});
-
- return new ChainedPreferenceStore(new IPreferenceStore[] { javaTextTools.getPreferenceStore(), new PreferencesAdapter(javaTextTools.getCorePreferenceStore()), generalTextStore });
- }
-
- /**
- * Initializes the scanners.
- *
- *
- */
- private void initializeScanners() {
- Assert.isTrue(isNewSetup());
- fCodeScanner= new JavaCodeScanner(getColorManager(), fPreferenceStore);
- fMultilineCommentScanner= new JavaCommentScanner(getColorManager(), fPreferenceStore, IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT);
- fSinglelineCommentScanner= new JavaCommentScanner(getColorManager(), fPreferenceStore, IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT);
- fStringScanner= new SingleTokenJavaScanner(getColorManager(), fPreferenceStore, IJavaScriptColorConstants.JAVA_STRING);
- fJavaDocScanner= new JavaDocScanner(getColorManager(), fPreferenceStore);
- }
-
- /*
- * @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
- */
- public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
-
- PresentationReconciler reconciler= new JavaPresentationReconciler();
- reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
-
- DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
- reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
- reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-
- dr= new DefaultDamagerRepairer(getJavaDocScanner());
- reconciler.setDamager(dr, IJavaScriptPartitions.JAVA_DOC);
- reconciler.setRepairer(dr, IJavaScriptPartitions.JAVA_DOC);
-
- dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
- reconciler.setDamager(dr, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- reconciler.setRepairer(dr, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
-
- dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
- reconciler.setDamager(dr, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- reconciler.setRepairer(dr, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
-
- dr= new DefaultDamagerRepairer(getStringScanner());
- reconciler.setDamager(dr, IJavaScriptPartitions.JAVA_STRING);
- reconciler.setRepairer(dr, IJavaScriptPartitions.JAVA_STRING);
-
- dr= new DefaultDamagerRepairer(getStringScanner());
- reconciler.setDamager(dr, IJavaScriptPartitions.JAVA_CHARACTER);
- reconciler.setRepairer(dr, IJavaScriptPartitions.JAVA_CHARACTER);
-
-
- return reconciler;
- }
-
- /*
- * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
- */
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
-
- if (getEditor() != null) {
-
- ContentAssistant assistant= new ContentAssistant();
- assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
-
- assistant.setRestoreCompletionProposalSize(getSettings("completion_proposal_size")); //$NON-NLS-1$
-
- IContentAssistProcessor javaProcessor= new JavaCompletionProcessor(getEditor(), assistant, IDocument.DEFAULT_CONTENT_TYPE);
- assistant.setContentAssistProcessor(javaProcessor, IDocument.DEFAULT_CONTENT_TYPE);
-
- ContentAssistProcessor singleLineProcessor= new JavaCompletionProcessor(getEditor(), assistant, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- assistant.setContentAssistProcessor(singleLineProcessor, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
-
- ContentAssistProcessor stringProcessor= new JavaCompletionProcessor(getEditor(), assistant, IJavaScriptPartitions.JAVA_STRING);
- assistant.setContentAssistProcessor(stringProcessor, IJavaScriptPartitions.JAVA_STRING);
-
- ContentAssistProcessor multiLineProcessor= new JavaCompletionProcessor(getEditor(), assistant, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- assistant.setContentAssistProcessor(multiLineProcessor, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
-
- ContentAssistProcessor javadocProcessor= new JavadocCompletionProcessor(getEditor(), assistant);
- assistant.setContentAssistProcessor(javadocProcessor, IJavaScriptPartitions.JAVA_DOC);
-
- ContentAssistPreference.configure(assistant, fPreferenceStore);
-
- assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
- assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
-
- return assistant;
- }
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getQuickAssistAssistant(org.eclipse.jface.text.source.ISourceViewer)
- *
- */
- public IQuickAssistAssistant getQuickAssistAssistant(ISourceViewer sourceViewer) {
- if (getEditor() != null)
- return new JavaCorrectionAssistant(getEditor());
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getReconciler(ISourceViewer)
- */
- public IReconciler getReconciler(ISourceViewer sourceViewer) {
-
- final ITextEditor editor= getEditor();
- if (editor != null && editor.isEditable()) {
-
- JavaCompositeReconcilingStrategy strategy= new JavaCompositeReconcilingStrategy(sourceViewer, editor, getConfiguredDocumentPartitioning(sourceViewer));
- JavaReconciler reconciler= new JavaReconciler(editor, strategy, false);
- reconciler.setIsIncrementalReconciler(false);
- reconciler.setIsAllowedToModifyDocument(false);
- reconciler.setProgressMonitor(new NullProgressMonitor());
- reconciler.setDelay(500);
-
- return reconciler;
- }
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
- */
- public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
- String partitioning= getConfiguredDocumentPartitioning(sourceViewer);
- if (IJavaScriptPartitions.JAVA_DOC.equals(contentType) || IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType))
- return new IAutoEditStrategy[] { new JavaDocAutoIndentStrategy(partitioning) };
- else if (IJavaScriptPartitions.JAVA_STRING.equals(contentType))
- return new IAutoEditStrategy[] { new SmartSemicolonAutoEditStrategy(partitioning), new JavaStringAutoIndentStrategy(partitioning) };
- else if (IJavaScriptPartitions.JAVA_CHARACTER.equals(contentType) || IDocument.DEFAULT_CONTENT_TYPE.equals(contentType))
- return new IAutoEditStrategy[] { new SmartSemicolonAutoEditStrategy(partitioning), new JavaAutoIndentStrategy(partitioning, getProject(), sourceViewer) };
- else
- return new IAutoEditStrategy[] { new JavaAutoIndentStrategy(partitioning, getProject(), sourceViewer) };
- }
-
- /*
- * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
- */
- public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
- if (IJavaScriptPartitions.JAVA_DOC.equals(contentType))
- return new JavadocDoubleClickStrategy();
- if (IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
- IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
- return new DefaultTextDoubleClickStrategy();
- else if (IJavaScriptPartitions.JAVA_STRING.equals(contentType) ||
- IJavaScriptPartitions.JAVA_CHARACTER.equals(contentType))
- return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer));
- if (fJavaDoubleClickSelector == null) {
- fJavaDoubleClickSelector= new JavaDoubleClickSelector();
- fJavaDoubleClickSelector.setSourceVersion(fPreferenceStore.getString(JavaScriptCore.COMPILER_SOURCE));
- }
- return fJavaDoubleClickSelector;
- }
-
- /*
- * @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String)
- *
- */
- public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
- return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /*
- * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
- */
- public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
- IJavaScriptProject project= getProject();
- final int tabWidth= CodeFormatterUtil.getTabWidth(project);
- final int indentWidth= CodeFormatterUtil.getIndentWidth(project);
- boolean allowTabs= tabWidth <= indentWidth;
-
- String indentMode;
- if (project == null)
- indentMode= JavaScriptCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- else
- indentMode= project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true);
-
- boolean useSpaces= JavaScriptCore.SPACE.equals(indentMode) || DefaultCodeFormatterConstants.MIXED.equals(indentMode);
-
- Assert.isLegal(allowTabs || useSpaces);
-
- if (!allowTabs) {
- char[] spaces= new char[indentWidth];
- Arrays.fill(spaces, ' ');
- return new String[] { new String(spaces), "" }; //$NON-NLS-1$
- } else if (!useSpaces)
- return getIndentPrefixesForTab(tabWidth);
- else
- return getIndentPrefixesForSpaces(tabWidth);
- }
-
- /**
- * Computes and returns the indent prefixes for space indentation
- * and the given <code>tabWidth</code>.
- *
- * @param tabWidth the display tab width
- * @return the indent prefixes
- * @see #getIndentPrefixes(ISourceViewer, String)
- *
- */
- private String[] getIndentPrefixesForSpaces(int tabWidth) {
- String[] indentPrefixes= new String[tabWidth + 2];
- indentPrefixes[0]= getStringWithSpaces(tabWidth);
-
- for (int i= 0; i < tabWidth; i++) {
- String spaces= getStringWithSpaces(i);
- if (i < tabWidth)
- indentPrefixes[i+1]= spaces + '\t';
- else
- indentPrefixes[i+1]= new String(spaces);
- }
-
- indentPrefixes[tabWidth + 1]= ""; //$NON-NLS-1$
-
- return indentPrefixes;
- }
-
- /**
- * Creates and returns a String with <code>count</code> spaces.
- *
- * @param count the space count
- * @return the string with the spaces
- *
- */
- private String getStringWithSpaces(int count) {
- char[] spaceChars= new char[count];
- Arrays.fill(spaceChars, ' ');
- return new String(spaceChars);
- }
-
- private IJavaScriptProject getProject() {
- ITextEditor editor= getEditor();
- if (editor == null)
- return null;
-
- IJavaScriptElement element= null;
- IEditorInput input= editor.getEditorInput();
- IDocumentProvider provider= editor.getDocumentProvider();
- if (provider instanceof ICompilationUnitDocumentProvider) {
- ICompilationUnitDocumentProvider cudp= (ICompilationUnitDocumentProvider) provider;
- element= cudp.getWorkingCopy(input);
- } else if (input instanceof IClassFileEditorInput) {
- IClassFileEditorInput cfei= (IClassFileEditorInput) input;
- element= cfei.getClassFile();
- }
-
- if (element == null)
- return null;
-
- return element.getJavaScriptProject();
- }
-
- /*
- * @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
- */
- public int getTabWidth(ISourceViewer sourceViewer) {
- return CodeFormatterUtil.getTabWidth(getProject());
- }
-
- /*
- * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
- */
- public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
- return new HTMLAnnotationHover() {
- protected boolean isIncluded(Annotation annotation) {
- return isShowInVerticalRuler(annotation);
- }
- };
- }
-
- /*
- * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
- *
- */
- public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
- return new HTMLAnnotationHover() {
- protected boolean isIncluded(Annotation annotation) {
- return isShowInOverviewRuler(annotation);
- }
- };
- }
-
- /*
- * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
- *
- */
- public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
- JavaEditorTextHoverDescriptor[] hoverDescs= JavaScriptPlugin.getDefault().getJavaEditorTextHoverDescriptors();
- int stateMasks[]= new int[hoverDescs.length];
- int stateMasksLength= 0;
- for (int i= 0; i < hoverDescs.length; i++) {
- if (hoverDescs[i].isEnabled()) {
- int j= 0;
- int stateMask= hoverDescs[i].getStateMask();
- while (j < stateMasksLength) {
- if (stateMasks[j] == stateMask)
- break;
- j++;
- }
- if (j == stateMasksLength)
- stateMasks[stateMasksLength++]= stateMask;
- }
- }
- if (stateMasksLength == hoverDescs.length)
- return stateMasks;
-
- int[] shortenedStateMasks= new int[stateMasksLength];
- System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength);
- return shortenedStateMasks;
- }
-
- /*
- * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
- *
- */
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
- JavaEditorTextHoverDescriptor[] hoverDescs= JavaScriptPlugin.getDefault().getJavaEditorTextHoverDescriptors();
- int i= 0;
- while (i < hoverDescs.length) {
- if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask)
- return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor());
- i++;
- }
-
- return null;
- }
-
- /*
- * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
- */
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
- return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
- }
-
- /*
- * @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
- */
- public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
- return new String[] {
- IDocument.DEFAULT_CONTENT_TYPE,
- IJavaScriptPartitions.JAVA_DOC,
- IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_STRING,
- IJavaScriptPartitions.JAVA_CHARACTER
- };
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
- *
- */
- public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
- if (fDocumentPartitioning != null)
- return fDocumentPartitioning;
- return super.getConfiguredDocumentPartitioning(sourceViewer);
- }
-
- /*
- * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
- */
- public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
- final MultiPassContentFormatter formatter= new MultiPassContentFormatter(getConfiguredDocumentPartitioning(sourceViewer), IDocument.DEFAULT_CONTENT_TYPE);
-
- formatter.setMasterStrategy(new JavaFormattingStrategy());
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_DOC);
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- formatter.setSlaveStrategy(new CommentFormattingStrategy(), IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
-
- return formatter;
- }
-
- /*
- * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
- *
- */
- public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
- }
- };
- }
-
- /**
- * Returns the information presenter control creator. The creator is a factory creating the
- * presenter controls for the given source viewer. This implementation always returns a creator
- * for <code>DefaultInformationControl</code> instances.
- *
- * @param sourceViewer the source viewer to be configured by this configuration
- * @return an information control creator
- *
- */
- private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE | SWT.TOOL;
- int style= SWT.V_SCROLL | SWT.H_SCROLL;
- return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
- }
- };
- }
-
- /**
- * Returns the outline presenter control creator. The creator is a factory creating outline
- * presenter controls for the given source viewer. This implementation always returns a creator
- * for <code>JavaOutlineInformationControl</code> instances.
- *
- * @param sourceViewer the source viewer to be configured by this configuration
- * @param commandId the ID of the command that opens this control
- * @return an information control creator
- *
- */
- private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer, final String commandId) {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE;
- int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
- return new JavaOutlineInformationControl(parent, shellStyle, treeStyle, commandId);
- }
- };
- }
-
- private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) {
- return new IInformationControlCreator() {
- public IInformationControl createInformationControl(Shell parent) {
- int shellStyle= SWT.RESIZE;
- int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
- return new HierarchyInformationControl(parent, shellStyle, treeStyle);
- }
- };
- }
-
- /*
- * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
- *
- */
- public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
- InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
- presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
-
- // Register information provider
- IInformationProvider provider= new JavaInformationProvider(getEditor());
- String[] contentTypes= getConfiguredContentTypes(sourceViewer);
- for (int i= 0; i < contentTypes.length; i++)
- presenter.setInformationProvider(provider, contentTypes[i]);
-
- presenter.setSizeConstraints(60, 10, true, true);
- return presenter;
- }
-
- /**
- * Returns the outline presenter which will determine and shown
- * information requested for the current cursor position.
- *
- * @param sourceViewer the source viewer to be configured by this configuration
- * @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the JavaScript element
- * @return an information presenter
- *
- */
- public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
- InformationPresenter presenter;
- if (doCodeResolve)
- presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE));
- else
- presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.SHOW_OUTLINE));
- presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
- presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
- IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
- presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_DOC);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_STRING);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_CHARACTER);
- presenter.setSizeConstraints(50, 20, true, false);
- return presenter;
- }
-
- /**
- * Returns the settings for the given section.
- *
- * @param sectionName the section name
- * @return the settings
- *
- */
- private IDialogSettings getSettings(String sectionName) {
- IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(sectionName);
- if (settings == null)
- settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(sectionName);
-
- return settings;
- }
-
- /**
- * Returns the hierarchy presenter which will determine and shown type hierarchy
- * information requested for the current cursor position.
- *
- * @param sourceViewer the source viewer to be configured by this configuration
- * @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the JavaScript element
- * @return an information presenter
- *
- */
- public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
-
- // Do not create hierarchy presenter if there's no CU.
- if (getEditor() != null && getEditor().getEditorInput() != null && JavaScriptUI.getEditorInputJavaElement(getEditor().getEditorInput()) == null)
- return null;
-
- InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer));
- presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
- presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
- IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
- presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_DOC);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_STRING);
- presenter.setInformationProvider(provider, IJavaScriptPartitions.JAVA_CHARACTER);
- presenter.setSizeConstraints(50, 20, true, false);
- return presenter;
- }
-
- /**
- * Determines whether the preference change encoded by the given event
- * changes the behavior of one of its contained components.
- *
- * @param event the event to be investigated
- * @return <code>true</code> if event causes a behavioral change
- *
- */
- public boolean affectsTextPresentation(PropertyChangeEvent event) {
- return fCodeScanner.affectsBehavior(event)
- || fMultilineCommentScanner.affectsBehavior(event)
- || fSinglelineCommentScanner.affectsBehavior(event)
- || fStringScanner.affectsBehavior(event)
- || fJavaDocScanner.affectsBehavior(event);
- }
-
- /**
- * Adapts the behavior of the contained components to the change
- * encoded in the given event.
- * <p>
- * Clients are not allowed to call this method if the old setup with
- * text tools is in use.
- * </p>
- *
- * @param event the event to which to adapt
- * @see JavaScriptSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)
- *
- */
- public void handlePropertyChangeEvent(PropertyChangeEvent event) {
- Assert.isTrue(isNewSetup());
- if (fCodeScanner.affectsBehavior(event))
- fCodeScanner.adaptToPreferenceChange(event);
- if (fMultilineCommentScanner.affectsBehavior(event))
- fMultilineCommentScanner.adaptToPreferenceChange(event);
- if (fSinglelineCommentScanner.affectsBehavior(event))
- fSinglelineCommentScanner.adaptToPreferenceChange(event);
- if (fStringScanner.affectsBehavior(event))
- fStringScanner.adaptToPreferenceChange(event);
- if (fJavaDocScanner.affectsBehavior(event))
- fJavaDocScanner.adaptToPreferenceChange(event);
- if (fJavaDoubleClickSelector != null && JavaScriptCore.COMPILER_SOURCE.equals(event.getProperty()))
- if (event.getNewValue() instanceof String)
- fJavaDoubleClickSelector.setSourceVersion((String) event.getNewValue());
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectorTargets(org.eclipse.jface.text.source.ISourceViewer)
- *
- */
- protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
- Map targets= super.getHyperlinkDetectorTargets(sourceViewer);
- targets.put("org.eclipse.wst.jsdt.ui.javaCode", fTextEditor); //$NON-NLS-1$
- return targets;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptTextTools.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptTextTools.java
deleted file mode 100644
index e2155f85..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptTextTools.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text;
-
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension3;
-import org.eclipse.jface.text.IDocumentPartitioner;
-import org.eclipse.jface.text.rules.FastPartitioner;
-import org.eclipse.jface.text.rules.IPartitionTokenScanner;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.wst.jsdt.internal.ui.text.FastJavaPartitionScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaColorManager;
-import org.eclipse.wst.jsdt.internal.ui.text.JavaCommentScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.SingleTokenJavaScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCodeScanner;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDocScanner;
-
-
-/**
- * Tools required to configure a JavaScript text viewer.
- * The color manager and all scanner exist only one time, i.e.
- * the same instances are returned to all clients. Thus, clients
- * share those tools.
- * <p>
- * This class may be instantiated; it is not intended to be subclassed.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class JavaScriptTextTools {
-
- /**
- * Array with legal content types.
- *
- */
- private final static String[] LEGAL_CONTENT_TYPES= new String[] {
- IJavaScriptPartitions.JAVA_DOC,
- IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT,
- IJavaScriptPartitions.JAVA_STRING,
- IJavaScriptPartitions.JAVA_CHARACTER
- };
-
- /**
- * This tools' preference listener.
- */
- private class PreferenceListener implements IPropertyChangeListener, Preferences.IPropertyChangeListener {
- public void propertyChange(PropertyChangeEvent event) {
- adaptToPreferenceChange(event);
- }
- public void propertyChange(Preferences.PropertyChangeEvent event) {
- adaptToPreferenceChange(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue()));
- }
- }
-
- /** The color manager. */
- private JavaColorManager fColorManager;
- /** The JavaScript source code scanner. */
- private JavaCodeScanner fCodeScanner;
- /** The JavaScript multi-line comment scanner. */
- private JavaCommentScanner fMultilineCommentScanner;
- /** The JavaScript single-line comment scanner. */
- private JavaCommentScanner fSinglelineCommentScanner;
- /** The JavaScript string scanner. */
- private SingleTokenJavaScanner fStringScanner;
- /** The JavaDoc scanner. */
- private JavaDocScanner fJavaDocScanner;
- /** The preference store. */
- private IPreferenceStore fPreferenceStore;
- /**
- * The core preference store.
- *
- */
- private Preferences fCorePreferenceStore;
- /** The preference change listener */
- private PreferenceListener fPreferenceListener= new PreferenceListener();
-
-
- /**
- * Creates a new JavaScript text tools collection.
- *
- * @param store the preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store. In general <code>PreferenceConstants.
- * getPreferenceStore()</code> should be used to initialize the text tools.
- * @see org.eclipse.wst.jsdt.ui.PreferenceConstants#getPreferenceStore()
- *
- */
- public JavaScriptTextTools(IPreferenceStore store) {
- this(store, null, true);
- }
-
- /**
- * Creates a new JavaScript text tools collection.
- *
- * @param store the preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store. In general <code>PreferenceConstants.
- * getPreferenceStore()</code> should be used to initialize the text tools.
- * @param autoDisposeOnDisplayDispose if <code>true</code> the color manager
- * automatically disposes all managed colors when the current display gets disposed
- * and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()} are ignored.
- * @see org.eclipse.wst.jsdt.ui.PreferenceConstants#getPreferenceStore()
- *
- */
- public JavaScriptTextTools(IPreferenceStore store, boolean autoDisposeOnDisplayDispose) {
- this(store, null, autoDisposeOnDisplayDispose);
- }
-
- /**
- * Creates a new JavaScript text tools collection.
- * @param store the preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store. In general <code>PreferenceConstants.
- * getPreferenceStore()</code> should be used to initialize the text tools.
- * @param coreStore optional preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store.
- * @see org.eclipse.wst.jsdt.ui.PreferenceConstants#getPreferenceStore()
- *
- */
- public JavaScriptTextTools(IPreferenceStore store, Preferences coreStore) {
- this(store, coreStore, true);
- }
-
- /**
- * Creates a new JavaScript text tools collection.
- *
- * @param store the preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store. In general <code>PreferenceConstants.
- * getPreferenceStore()</code> should be used to initialize the text tools.
- * @param coreStore optional preference store to initialize the text tools. The text tool
- * instance installs a listener on the passed preference store to adapt itself to
- * changes in the preference store.
- * @param autoDisposeOnDisplayDispose if <code>true</code> the color manager
- * automatically disposes all managed colors when the current display gets disposed
- * and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()} are ignored.
- * @see org.eclipse.wst.jsdt.ui.PreferenceConstants#getPreferenceStore()
- *
- */
- public JavaScriptTextTools(IPreferenceStore store, Preferences coreStore, boolean autoDisposeOnDisplayDispose) {
- fPreferenceStore= store;
- fPreferenceStore.addPropertyChangeListener(fPreferenceListener);
-
- fCorePreferenceStore= coreStore;
- if (fCorePreferenceStore != null)
- fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener);
-
- fColorManager= new JavaColorManager(autoDisposeOnDisplayDispose);
- fCodeScanner= new JavaCodeScanner(fColorManager, store);
- fMultilineCommentScanner= new JavaCommentScanner(fColorManager, store, coreStore, IJavaScriptColorConstants.JAVA_MULTI_LINE_COMMENT);
- fSinglelineCommentScanner= new JavaCommentScanner(fColorManager, store, coreStore, IJavaScriptColorConstants.JAVA_SINGLE_LINE_COMMENT);
- fStringScanner= new SingleTokenJavaScanner(fColorManager, store, IJavaScriptColorConstants.JAVA_STRING);
- fJavaDocScanner= new JavaDocScanner(fColorManager, store, coreStore);
- }
-
- /**
- * Disposes all the individual tools of this tools collection.
- */
- public void dispose() {
-
- fCodeScanner= null;
- fMultilineCommentScanner= null;
- fSinglelineCommentScanner= null;
- fStringScanner= null;
- fJavaDocScanner= null;
-
- if (fColorManager != null) {
- fColorManager.dispose();
- fColorManager= null;
- }
-
- if (fPreferenceStore != null) {
- fPreferenceStore.removePropertyChangeListener(fPreferenceListener);
- fPreferenceStore= null;
-
- if (fCorePreferenceStore != null) {
- fCorePreferenceStore.removePropertyChangeListener(fPreferenceListener);
- fCorePreferenceStore= null;
- }
-
- fPreferenceListener= null;
- }
- }
-
- /**
- * Returns the color manager which is used to manage
- * any Java-specific colors needed for such things like syntax highlighting.
- * <p>
- * Clients which are only interested in the color manager of the JavaScript UI
- * plug-in should use {@link org.eclipse.wst.jsdt.ui.JavaScriptUI#getColorManager()}.
- * </p>
- *
- * @return the color manager to be used for JavaScript text viewers
- * @see org.eclipse.wst.jsdt.ui.JavaScriptUI#getColorManager()
- */
- public IColorManager getColorManager() {
- return fColorManager;
- }
-
- /**
- * Returns a scanner which is configured to scan
- * Java-specific partitions, which are multi-line comments,
- * Javadoc comments, and regular JavaScript source code.
- *
- * @return a JavaScript partition scanner
- */
- public IPartitionTokenScanner getPartitionScanner() {
- return new FastJavaPartitionScanner();
- }
-
- /**
- * Factory method for creating a Java-specific document partitioner
- * using this object's partitions scanner. This method is a
- * convenience method.
- *
- * @return a newly created JavaScript document partitioner
- */
- public IDocumentPartitioner createDocumentPartitioner() {
- return new FastPartitioner(getPartitionScanner(), LEGAL_CONTENT_TYPES);
- }
-
- /**
- * Adapts the behavior of the contained components to the change
- * encoded in the given event.
- *
- * @param event the event to which to adapt
- *
- * @deprecated As of 3.0, no replacement
- */
- protected void adaptToPreferenceChange(PropertyChangeEvent event) {
- if (fCodeScanner.affectsBehavior(event))
- fCodeScanner.adaptToPreferenceChange(event);
- if (fMultilineCommentScanner.affectsBehavior(event))
- fMultilineCommentScanner.adaptToPreferenceChange(event);
- if (fSinglelineCommentScanner.affectsBehavior(event))
- fSinglelineCommentScanner.adaptToPreferenceChange(event);
- if (fStringScanner.affectsBehavior(event))
- fStringScanner.adaptToPreferenceChange(event);
- if (fJavaDocScanner.affectsBehavior(event))
- fJavaDocScanner.adaptToPreferenceChange(event);
- }
-
- /**
- * Sets up the JavaScript document partitioner for the given document for the default partitioning.
- *
- * @param document the document to be set up
- *
- */
- public void setupJavaDocumentPartitioner(IDocument document) {
- setupJavaDocumentPartitioner(document, IDocumentExtension3.DEFAULT_PARTITIONING);
- }
-
- /**
- * Sets up the JavaScript document partitioner for the given document for the given partitioning.
- *
- * @param document the document to be set up
- * @param partitioning the document partitioning
- *
- */
- public void setupJavaDocumentPartitioner(IDocument document, String partitioning) {
- IDocumentPartitioner partitioner= createDocumentPartitioner();
- if (document instanceof IDocumentExtension3) {
- IDocumentExtension3 extension3= (IDocumentExtension3) document;
- extension3.setDocumentPartitioner(partitioning, partitioner);
- } else {
- document.setDocumentPartitioner(partitioner);
- }
- partitioner.connect(document);
- }
-
- /**
- * Returns this text tool's preference store.
- *
- * @return the preference store
- *
- */
- protected IPreferenceStore getPreferenceStore() {
- return fPreferenceStore;
- }
-
- /**
- * Returns this text tool's core preference store.
- *
- * @return the core preference store
- *
- */
- protected Preferences getCorePreferenceStore() {
- return fCorePreferenceStore;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java
deleted file mode 100644
index 1b7ee261..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java
+++ /dev/null
@@ -1,1456 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.folding;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.projection.IProjectionListener;
-import org.eclipse.jface.text.source.projection.IProjectionPosition;
-import org.eclipse.jface.text.source.projection.ProjectionAnnotation;
-import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
-import org.eclipse.jface.text.source.projection.ProjectionViewer;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.jsdt.core.ElementChangedEvent;
-import org.eclipse.wst.jsdt.core.IElementChangedListener;
-import org.eclipse.wst.jsdt.core.IImportContainer;
-import org.eclipse.wst.jsdt.core.IImportDeclaration;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptElementDelta;
-import org.eclipse.wst.jsdt.core.IMember;
-import org.eclipse.wst.jsdt.core.IParent;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.ISourceReference;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.internal.corext.SourceRange;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.actions.SelectionConverter;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.wst.jsdt.internal.ui.text.DocumentCharacterIterator;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * Updates the projection model of a class file or compilation unit.
- * <p>
- * Clients may instantiate or subclass. Subclasses must make sure to always call the superclass'
- * code when overriding methods that are marked with "subclasses may extend".
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class DefaultJavaFoldingStructureProvider implements IJavaFoldingStructureProvider, IJavaFoldingStructureProviderExtension {
- /**
- * A context that contains the information needed to compute the folding structure of an
- * {@link org.eclipse.wst.jsdt.core.IJavaScriptUnit} or an {@link org.eclipse.wst.jsdt.core.IClassFile}. Computed folding regions are collected
- * via
- * {@linkplain #addProjectionRange(DefaultJavaFoldingStructureProvider.JavaProjectionAnnotation, Position) addProjectionRange}.
- */
- protected final class FoldingStructureComputationContext {
- private final ProjectionAnnotationModel fModel;
- private final IDocument fDocument;
-
- private final boolean fAllowCollapsing;
-
- private IType fFirstType;
- private boolean fHasHeaderComment;
- private LinkedHashMap fMap= new LinkedHashMap();
- private IScanner fScanner;
-
- private FoldingStructureComputationContext(IDocument document, ProjectionAnnotationModel model, boolean allowCollapsing, IScanner scanner) {
- Assert.isNotNull(document);
- Assert.isNotNull(model);
- fDocument= document;
- fModel= model;
- fAllowCollapsing= allowCollapsing;
- fScanner= scanner;
- }
-
- private void setFirstType(IType type) {
- if (hasFirstType())
- throw new IllegalStateException();
- fFirstType= type;
- }
-
- boolean hasFirstType() {
- return fFirstType != null;
- }
-
- private IType getFirstType() {
- return fFirstType;
- }
-
- private boolean hasHeaderComment() {
- return fHasHeaderComment;
- }
-
- private void setHasHeaderComment() {
- fHasHeaderComment= true;
- }
-
- /**
- * Returns <code>true</code> if newly created folding regions may be collapsed,
- * <code>false</code> if not. This is usually <code>false</code> when updating the
- * folding structure while typing; it may be <code>true</code> when computing or restoring
- * the initial folding structure.
- *
- * @return <code>true</code> if newly created folding regions may be collapsed,
- * <code>false</code> if not
- */
- public boolean allowCollapsing() {
- return fAllowCollapsing;
- }
-
- /**
- * Returns the document which contains the code being folded.
- *
- * @return the document which contains the code being folded
- */
- private IDocument getDocument() {
- return fDocument;
- }
-
- private ProjectionAnnotationModel getModel() {
- return fModel;
- }
-
- private IScanner getScanner() {
- if (fScanner == null)
- fScanner= ToolFactory.createScanner(true, false, false, false);
- return fScanner;
- }
-
- /**
- * Adds a projection (folding) region to this context. The created annotation / position
- * pair will be added to the {@link ProjectionAnnotationModel} of the
- * {@link ProjectionViewer} of the editor.
- *
- * @param annotation the annotation to add
- * @param position the corresponding position
- */
- public void addProjectionRange(JavaProjectionAnnotation annotation, Position position) {
- fMap.put(annotation, position);
- }
-
- /**
- * Returns <code>true</code> if header comments should be collapsed.
- *
- * @return <code>true</code> if header comments should be collapsed
- */
- public boolean collapseHeaderComments() {
- return fAllowCollapsing && fCollapseHeaderComments;
- }
-
- /**
- * Returns <code>true</code> if import containers should be collapsed.
- *
- * @return <code>true</code> if import containers should be collapsed
- */
- public boolean collapseImportContainer() {
- return fAllowCollapsing && fCollapseImportContainer;
- }
-
- /**
- * Returns <code>true</code> if inner types should be collapsed.
- *
- * @return <code>true</code> if inner types should be collapsed
- */
- public boolean collapseInnerTypes() {
- return fAllowCollapsing && fCollapseInnerTypes;
- }
-
- /**
- * Returns <code>true</code> if javadoc comments should be collapsed.
- *
- * @return <code>true</code> if javadoc comments should be collapsed
- */
- public boolean collapseJavadoc() {
- return fAllowCollapsing && fCollapseJavadoc;
- }
-
- /**
- * Returns <code>true</code> if methods should be collapsed.
- *
- * @return <code>true</code> if methods should be collapsed
- */
- public boolean collapseMembers() {
- return fAllowCollapsing && fCollapseMembers;
- }
- }
-
- /**
- * A {@link ProjectionAnnotation} for JavaScript code.
- */
- protected static final class JavaProjectionAnnotation extends ProjectionAnnotation {
-
- private IJavaScriptElement fJavaElement;
- private boolean fIsComment;
-
- /**
- * Creates a new projection annotation.
- *
- * @param isCollapsed <code>true</code> to set the initial state to collapsed,
- * <code>false</code> to set it to expanded
- * @param element the JavaScript element this annotation refers to
- * @param isComment <code>true</code> for a foldable comment, <code>false</code> for a
- * foldable code element
- */
- public JavaProjectionAnnotation(boolean isCollapsed, IJavaScriptElement element, boolean isComment) {
- super(isCollapsed);
- fJavaElement= element;
- fIsComment= isComment;
- }
-
- IJavaScriptElement getElement() {
- return fJavaElement;
- }
-
- void setElement(IJavaScriptElement element) {
- fJavaElement= element;
- }
-
- boolean isComment() {
- return fIsComment;
- }
-
- void setIsComment(boolean isComment) {
- fIsComment= isComment;
- }
-
- /*
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "JavaProjectionAnnotation:\n" + //$NON-NLS-1$
- "\telement: \t"+ fJavaElement.toString() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
- "\tcollapsed: \t" + isCollapsed() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
- "\tcomment: \t" + isComment() + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
-
- private static final class Tuple {
- JavaProjectionAnnotation annotation;
- Position position;
- Tuple(JavaProjectionAnnotation annotation, Position position) {
- this.annotation= annotation;
- this.position= position;
- }
- }
-
- /**
- * Filter for annotations.
- */
- private static interface Filter {
- boolean match(JavaProjectionAnnotation annotation);
- }
-
- /**
- * Matches comments.
- */
- private static final class CommentFilter implements Filter {
- public boolean match(JavaProjectionAnnotation annotation) {
- if (annotation.isComment() && !annotation.isMarkedDeleted()) {
- return true;
- }
- return false;
- }
- }
-
- /**
- * Matches members.
- */
- private static final class MemberFilter implements Filter {
- public boolean match(JavaProjectionAnnotation annotation) {
- if (!annotation.isComment() && !annotation.isMarkedDeleted()) {
- IJavaScriptElement element= annotation.getElement();
- if (element instanceof IMember) {
- if (element.getElementType() != IJavaScriptElement.TYPE || ((IMember) element).getDeclaringType() != null) {
- return true;
- }
- }
- }
- return false;
- }
- }
-
- /**
- * Matches JavaScript elements contained in a certain set.
- */
- private static final class JavaElementSetFilter implements Filter {
- private final Set/*<? extends IJavaScriptElement>*/ fSet;
- private final boolean fMatchCollapsed;
-
- private JavaElementSetFilter(Set/*<? extends IJavaScriptElement>*/ set, boolean matchCollapsed) {
- fSet= set;
- fMatchCollapsed= matchCollapsed;
- }
-
- public boolean match(JavaProjectionAnnotation annotation) {
- boolean stateMatch= fMatchCollapsed == annotation.isCollapsed();
- if (stateMatch && !annotation.isComment() && !annotation.isMarkedDeleted()) {
- IJavaScriptElement element= annotation.getElement();
- if (fSet.contains(element)) {
- return true;
- }
- }
- return false;
- }
- }
-
- private class ElementChangedListener implements IElementChangedListener {
-
- /*
- * @see org.eclipse.wst.jsdt.core.IElementChangedListener#elementChanged(org.eclipse.wst.jsdt.core.ElementChangedEvent)
- */
- public void elementChanged(ElementChangedEvent e) {
- IJavaScriptElementDelta delta= findElement(fInput, e.getDelta());
- if (delta != null && (delta.getFlags() & (IJavaScriptElementDelta.F_CONTENT | IJavaScriptElementDelta.F_CHILDREN)) != 0) {
-
- if (shouldIgnoreDelta(e.getDelta().getJavaScriptUnitAST(), delta))
- return;
-
- fUpdatingCount++;
- try {
- update(createContext(false));
- } finally {
- fUpdatingCount--;
- }
- }
- }
-
- /**
- * Ignore the delta if there are errors on the caret line.
- * <p>
- * We don't ignore the delta if an import is added and the
- * caret isn't inside the import container.
- * </p>
- *
- * @param ast the compilation unit AST
- * @param delta the JavaScript element delta for the given AST element
- * @return <code>true</code> if the delta should be ignored
- *
- */
- private boolean shouldIgnoreDelta(JavaScriptUnit ast, IJavaScriptElementDelta delta) {
- if (ast == null)
- return false; // can't compute
-
- IDocument document= getDocument();
- if (document == null)
- return false; // can't compute
-
- JavaEditor editor= fEditor;
- if (editor == null || editor.getCachedSelectedRange() == null)
- return false; // can't compute
-
- try {
- if (delta.getAffectedChildren().length == 1 && delta.getAffectedChildren()[0].getElement() instanceof IImportContainer) {
- IJavaScriptElement elem= SelectionConverter.getElementAtOffset(ast.getJavaElement(), new TextSelection(editor.getCachedSelectedRange().x, editor.getCachedSelectedRange().y));
- if (!(elem instanceof IImportDeclaration))
- return false;
-
- }
- } catch (JavaScriptModelException e) {
- return false; // can't compute
- }
-
- int caretLine= 0;
- try {
- caretLine= document.getLineOfOffset(editor.getCachedSelectedRange().x) + 1;
- } catch (BadLocationException x) {
- return false; // can't compute
- }
-
- if (caretLine > 0 && ast != null) {
- IProblem[] problems= ast.getProblems();
- for (int i= 0; i < problems.length; i++) {
- if (problems[i].isError() && caretLine == problems[i].getSourceLineNumber())
- return true;
- }
- }
-
- return false;
- }
-
- private IJavaScriptElementDelta findElement(IJavaScriptElement target, IJavaScriptElementDelta delta) {
-
- if (delta == null || target == null)
- return null;
-
- IJavaScriptElement element= delta.getElement();
-
- if (element.getElementType() > IJavaScriptElement.CLASS_FILE)
- return null;
-
- if (target.equals(element))
- return delta;
-
- IJavaScriptElementDelta[] children= delta.getAffectedChildren();
-
- for (int i= 0; i < children.length; i++) {
- IJavaScriptElementDelta d= findElement(target, children[i]);
- if (d != null)
- return d;
- }
-
- return null;
- }
- }
-
- /**
- * Projection position that will return two foldable regions: one folding away
- * the region from after the '/**' to the beginning of the content, the other
- * from after the first content line until after the comment.
- */
- private static final class CommentPosition extends Position implements IProjectionPosition {
- CommentPosition(int offset, int length) {
- super(offset, length);
- }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument)
- */
- public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException {
- DocumentCharacterIterator sequence= new DocumentCharacterIterator(document, offset, offset + length);
- int prefixEnd= 0;
- int contentStart= findFirstContent(sequence, prefixEnd);
-
- int firstLine= document.getLineOfOffset(offset + prefixEnd);
- int captionLine= document.getLineOfOffset(offset + contentStart);
- int lastLine= document.getLineOfOffset(offset + length);
-
- Assert.isTrue(firstLine <= captionLine, "first folded line is greater than the caption line"); //$NON-NLS-1$
- Assert.isTrue(captionLine <= lastLine, "caption line is greater than the last folded line"); //$NON-NLS-1$
-
- IRegion preRegion;
- if (firstLine < captionLine) {
-// preRegion= new Region(offset + prefixEnd, contentStart - prefixEnd);
- int preOffset= document.getLineOffset(firstLine);
- IRegion preEndLineInfo= document.getLineInformation(captionLine);
- int preEnd= preEndLineInfo.getOffset();
- preRegion= new Region(preOffset, preEnd - preOffset);
- } else {
- preRegion= null;
- }
-
- if (captionLine < lastLine) {
- int postOffset= document.getLineOffset(captionLine + 1);
- IRegion postRegion= new Region(postOffset, offset + length - postOffset);
-
- if (preRegion == null)
- return new IRegion[] { postRegion };
-
- return new IRegion[] { preRegion, postRegion };
- }
-
- if (preRegion != null)
- return new IRegion[] { preRegion };
-
- return null;
- }
-
- /**
- * Finds the offset of the first identifier part within <code>content</code>.
- * Returns 0 if none is found.
- *
- * @param content the content to search
- * @param prefixEnd the end of the prefix
- * @return the first index of a unicode identifier part, or zero if none can
- * be found
- */
- private int findFirstContent(final CharSequence content, int prefixEnd) {
- int lenght= content.length();
- for (int i= prefixEnd; i < lenght; i++) {
- if (Character.isUnicodeIdentifierPart(content.charAt(i)))
- return i;
- }
- return 0;
- }
-
-// /**
-// * Finds the offset of the first identifier part within <code>content</code>.
-// * Returns 0 if none is found.
-// *
-// * @param content the content to search
-// * @return the first index of a unicode identifier part, or zero if none can
-// * be found
-// */
-// private int findPrefixEnd(final CharSequence content) {
-// // return the index after the leading '/*' or '/**'
-// int len= content.length();
-// int i= 0;
-// while (i < len && isWhiteSpace(content.charAt(i)))
-// i++;
-// if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) == '*')
-// if (len >= i + 3 && content.charAt(i + 2) == '*')
-// return i + 3;
-// else
-// return i + 2;
-// else
-// return i;
-// }
-//
-// private boolean isWhiteSpace(char c) {
-// return c == ' ' || c == '\t';
-// }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument)
- */
- public int computeCaptionOffset(IDocument document) {
-// return 0;
- DocumentCharacterIterator sequence= new DocumentCharacterIterator(document, offset, offset + length);
- return findFirstContent(sequence, 0);
- }
- }
-
- /**
- * Projection position that will return two foldable regions: one folding away
- * the lines before the one containing the simple name of the JavaScript element, one
- * folding away any lines after the caption.
- */
- private static final class JavaElementPosition extends Position implements IProjectionPosition {
-
- private IMember fMember;
-
- public JavaElementPosition(int offset, int length, IMember member) {
- super(offset, length);
- Assert.isNotNull(member);
- fMember= member;
- }
-
- public void setMember(IMember member) {
- Assert.isNotNull(member);
- fMember= member;
- }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument)
- */
- public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException {
- int nameStart= offset;
- try {
- /* The member's name range may not be correct. However,
- * reconciling would trigger another element delta which would
- * lead to reentrant situations. Therefore, we optimistically
- * assume that the name range is correct, but double check the
- * received lines below. */
- ISourceRange nameRange= fMember.getNameRange();
- if (nameRange != null)
- nameStart= nameRange.getOffset();
-
- } catch (JavaScriptModelException e) {
- // ignore and use default
- }
-
- int firstLine= document.getLineOfOffset(offset);
- int captionLine= document.getLineOfOffset(nameStart);
- int lastLine= document.getLineOfOffset(offset + length);
-
- /* see comment above - adjust the caption line to be inside the
- * entire folded region, and rely on later element deltas to correct
- * the name range. */
- if (captionLine < firstLine)
- captionLine= firstLine;
- if (captionLine > lastLine)
- captionLine= lastLine;
-
- IRegion preRegion;
- if (firstLine < captionLine) {
- int preOffset= document.getLineOffset(firstLine);
- IRegion preEndLineInfo= document.getLineInformation(captionLine);
- int preEnd= preEndLineInfo.getOffset();
- preRegion= new Region(preOffset, preEnd - preOffset);
- } else {
- preRegion= null;
- }
-
- if (captionLine < lastLine) {
- int postOffset= document.getLineOffset(captionLine + 1);
- IRegion postRegion= new Region(postOffset, offset + length - postOffset);
-
- if (preRegion == null)
- return new IRegion[] { postRegion };
-
- return new IRegion[] { preRegion, postRegion };
- }
-
- if (preRegion != null)
- return new IRegion[] { preRegion };
-
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument)
- */
- public int computeCaptionOffset(IDocument document) throws BadLocationException {
- int nameStart= offset;
- try {
- // need a reconcile here?
- ISourceRange nameRange= fMember.getNameRange();
- if (nameRange != null)
- nameStart= nameRange.getOffset();
- } catch (JavaScriptModelException e) {
- // ignore and use default
- }
-
- return nameStart - offset;
- }
-
- }
-
- /**
- * Internal projection listener.
- */
- private final class ProjectionListener implements IProjectionListener {
- private ProjectionViewer fViewer;
-
- /**
- * Registers the listener with the viewer.
- *
- * @param viewer the viewer to register a listener with
- */
- public ProjectionListener(ProjectionViewer viewer) {
- Assert.isLegal(viewer != null);
- fViewer= viewer;
- fViewer.addProjectionListener(this);
- }
-
- /**
- * Disposes of this listener and removes the projection listener from the viewer.
- */
- public void dispose() {
- if (fViewer != null) {
- fViewer.removeProjectionListener(this);
- fViewer= null;
- }
- }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled()
- */
- public void projectionEnabled() {
- handleProjectionEnabled();
- }
-
- /*
- * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled()
- */
- public void projectionDisabled() {
- handleProjectionDisabled();
- }
- }
-
- /* context and listeners */
- private JavaEditor fEditor;
- private ProjectionListener fProjectionListener;
- private IJavaScriptElement fInput;
- private IElementChangedListener fElementListener;
-
- /* preferences */
- private boolean fCollapseJavadoc= false;
- private boolean fCollapseImportContainer= true;
- private boolean fCollapseInnerTypes= true;
- private boolean fCollapseMembers= false;
- private boolean fCollapseHeaderComments= true;
-
- /* filters */
- /** Member filter, matches nested members (but not top-level types). */
- private final Filter fMemberFilter = new MemberFilter();
- /** Comment filter, matches comments. */
- private final Filter fCommentFilter = new CommentFilter();
-
- /**
- * Reusable scanner.
- *
- */
- private IScanner fSharedScanner= ToolFactory.createScanner(true, false, false, false);
-
- private volatile int fUpdatingCount= 0;
-
- /**
- * Creates a new folding provider. It must be
- * {@link #install(ITextEditor, ProjectionViewer) installed} on an editor/viewer pair before it
- * can be used, and {@link #uninstall() uninstalled} when not used any longer.
- * <p>
- * The projection state may be reset by calling {@link #initialize()}.
- * </p>
- */
- public DefaultJavaFoldingStructureProvider() {
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Subclasses may extend.
- * </p>
- *
- * @param editor {@inheritDoc}
- * @param viewer {@inheritDoc}
- */
- public void install(ITextEditor editor, ProjectionViewer viewer) {
- Assert.isLegal(editor != null);
- Assert.isLegal(viewer != null);
-
- internalUninstall();
-
- if (editor instanceof JavaEditor) {
- fProjectionListener= new ProjectionListener(viewer);
- fEditor= (JavaEditor)editor;
- }
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Subclasses may extend.
- * </p>
- */
- public void uninstall() {
- internalUninstall();
- }
-
- /**
- * Internal implementation of {@link #uninstall()}.
- */
- private void internalUninstall() {
- if (isInstalled()) {
- handleProjectionDisabled();
- fProjectionListener.dispose();
- fProjectionListener= null;
- fEditor= null;
- }
- }
-
- /**
- * Returns <code>true</code> if the provider is installed, <code>false</code> otherwise.
- *
- * @return <code>true</code> if the provider is installed, <code>false</code> otherwise
- */
- protected final boolean isInstalled() {
- return fEditor != null;
- }
-
- /**
- * Called whenever projection is enabled, for example when the viewer issues a
- * {@link IProjectionListener#projectionEnabled() projectionEnabled} message. When the provider
- * is already enabled when this method is called, it is first
- * {@link #handleProjectionDisabled() disabled}.
- * <p>
- * Subclasses may extend.
- * </p>
- */
- protected void handleProjectionEnabled() {
- // http://home.ott.oti.com/teams/wswb/anon/out/vms/index.html
- // projectionEnabled messages are not always paired with projectionDisabled
- // i.e. multiple enabled messages may be sent out.
- // we have to make sure that we disable first when getting an enable
- // message.
- handleProjectionDisabled();
-
- if (isInstalled()) {
- initialize();
- fElementListener= new ElementChangedListener();
- JavaScriptCore.addElementChangedListener(fElementListener);
- }
- }
-
- /**
- * Called whenever projection is disabled, for example when the provider is
- * {@link #uninstall() uninstalled}, when the viewer issues a
- * {@link IProjectionListener#projectionDisabled() projectionDisabled} message and before
- * {@link #handleProjectionEnabled() enabling} the provider. Implementations must be prepared to
- * handle multiple calls to this method even if the provider is already disabled.
- * <p>
- * Subclasses may extend.
- * </p>
- */
- protected void handleProjectionDisabled() {
- if (fElementListener != null) {
- JavaScriptCore.removeElementChangedListener(fElementListener);
- fElementListener= null;
- }
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProvider#initialize()
- */
- public final void initialize() {
- fUpdatingCount++;
- try {
- update(createInitialContext());
- } finally {
- fUpdatingCount--;
- }
- }
-
- private FoldingStructureComputationContext createInitialContext() {
- initializePreferences();
- fInput= getInputElement();
- if (fInput == null)
- return null;
-
- return createContext(true);
- }
-
- private FoldingStructureComputationContext createContext(boolean allowCollapse) {
- if (!isInstalled())
- return null;
- ProjectionAnnotationModel model= getModel();
- if (model == null)
- return null;
- IDocument doc= getDocument();
- if (doc == null)
- return null;
-
- IScanner scanner= null;
- if (fUpdatingCount == 1)
- scanner= fSharedScanner; // reuse scanner
-
- return new FoldingStructureComputationContext(doc, model, allowCollapse, scanner);
- }
-
- private IJavaScriptElement getInputElement() {
- if (fEditor == null)
- return null;
- return EditorUtility.getEditorInputJavaElement(fEditor, false);
- }
-
- private void initializePreferences() {
- IPreferenceStore store= JavaScriptPlugin.getDefault().getPreferenceStore();
- fCollapseInnerTypes= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES);
- fCollapseImportContainer= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS);
- fCollapseJavadoc= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC);
- fCollapseMembers= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS);
- fCollapseHeaderComments= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS);
- }
-
- private void update(FoldingStructureComputationContext ctx) {
- if (ctx == null)
- return;
-
- Map additions= new HashMap();
- List deletions= new ArrayList();
- List updates= new ArrayList();
-
- computeFoldingStructure(ctx);
- Map newStructure= ctx.fMap;
- Map oldStructure= computeCurrentStructure(ctx);
-
- Iterator e= newStructure.keySet().iterator();
- while (e.hasNext()) {
- JavaProjectionAnnotation newAnnotation= (JavaProjectionAnnotation) e.next();
- Position newPosition= (Position) newStructure.get(newAnnotation);
-
- IJavaScriptElement element= newAnnotation.getElement();
- /*
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=130472 and
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=127445 In the presence of syntax
- * errors, anonymous types may have a source range offset of 0. When such a situation is
- * encountered, we ignore the proposed folding range: if no corresponding folding range
- * exists, it is silently ignored; if there *is* a matching folding range, we ignore the
- * position update and keep the old range, in order to keep the folding structure
- * stable.
- */
- boolean isMalformedAnonymousType= newPosition.getOffset() == 0 && element.getElementType() == IJavaScriptElement.TYPE && isInnerType((IType) element);
- List annotations= (List) oldStructure.get(element);
- if (annotations == null) {
- if (!isMalformedAnonymousType)
- additions.put(newAnnotation, newPosition);
- } else {
- Iterator x= annotations.iterator();
- boolean matched= false;
- while (x.hasNext()) {
- Tuple tuple= (Tuple) x.next();
- JavaProjectionAnnotation existingAnnotation= tuple.annotation;
- Position existingPosition= tuple.position;
- if (newAnnotation.isComment() == existingAnnotation.isComment()) {
- boolean updateCollapsedState= ctx.allowCollapsing() && existingAnnotation.isCollapsed() != newAnnotation.isCollapsed();
- if (!isMalformedAnonymousType && existingPosition != null && (!newPosition.equals(existingPosition) || updateCollapsedState)) {
- existingPosition.setOffset(newPosition.getOffset());
- existingPosition.setLength(newPosition.getLength());
- if (updateCollapsedState)
- if (newAnnotation.isCollapsed())
- existingAnnotation.markCollapsed();
- else
- existingAnnotation.markExpanded();
- updates.add(existingAnnotation);
- }
- matched= true;
- x.remove();
- break;
- }
- }
- if (!matched)
- additions.put(newAnnotation, newPosition);
-
- if (annotations.isEmpty())
- oldStructure.remove(element);
- }
- }
-
- e= oldStructure.values().iterator();
- while (e.hasNext()) {
- List list= (List) e.next();
- int size= list.size();
- for (int i= 0; i < size; i++)
- deletions.add(((Tuple) list.get(i)).annotation);
- }
-
- match(deletions, additions, updates, ctx);
-
- Annotation[] deletedArray= (Annotation[]) deletions.toArray(new Annotation[deletions.size()]);
- Annotation[] changedArray= (Annotation[]) updates.toArray(new Annotation[updates.size()]);
- ctx.getModel().modifyAnnotations(deletedArray, additions, changedArray);
-
- ctx.fScanner.setSource(null);
- }
-
- private void computeFoldingStructure(FoldingStructureComputationContext ctx) {
- IParent parent= (IParent) fInput;
- try {
- if (!(fInput instanceof ISourceReference))
- return;
- String source= ((ISourceReference)fInput).getSource();
- if (source == null)
- return;
-
- ctx.getScanner().setSource(source.toCharArray());
- computeFoldingStructure(parent.getChildren(), ctx);
- } catch (JavaScriptModelException x) {
- }
- }
-
- private void computeFoldingStructure(IJavaScriptElement[] elements, FoldingStructureComputationContext ctx) throws JavaScriptModelException {
- for (int i= 0; i < elements.length; i++) {
- IJavaScriptElement element= elements[i];
-
- computeFoldingStructure(element, ctx);
-
- if (element instanceof IParent) {
- IParent parent= (IParent) element;
- computeFoldingStructure(parent.getChildren(), ctx);
- }
- }
- }
-
- /**
- * Computes the folding structure for a given {@link IJavaScriptElement JavaScript element}. Computed
- * projection annotations are
- * {@link DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext#addProjectionRange(DefaultJavaFoldingStructureProvider.JavaProjectionAnnotation, Position) added}
- * to the computation context.
- * <p>
- * Subclasses may extend or replace. The default implementation creates projection annotations
- * for the following elements:
- * <ul>
- * <li>true members (not for top-level types)</li>
- * <li>the javadoc comments of any member</li>
- * <li>header comments (javadoc or multi-line comments appearing before the first type's
- * javadoc or before the package or import declarations).</li>
- * </ul>
- * </p>
- *
- * @param element the JavaScript element to compute the folding structure for
- * @param ctx the computation context
- */
- protected void computeFoldingStructure(IJavaScriptElement element, FoldingStructureComputationContext ctx) {
-
- boolean collapse= false;
- boolean collapseCode= true;
- switch (element.getElementType()) {
-
- case IJavaScriptElement.IMPORT_CONTAINER:
- collapse= ctx.collapseImportContainer();
- break;
- case IJavaScriptElement.TYPE:
- collapseCode= isInnerType((IType) element);
- collapse= ctx.collapseInnerTypes() && collapseCode;
- break;
- case IJavaScriptElement.METHOD:
- case IJavaScriptElement.FIELD:
- case IJavaScriptElement.INITIALIZER:
- collapse= ctx.collapseMembers();
- break;
- default:
- return;
- }
-
- IRegion[] regions= computeProjectionRanges((ISourceReference) element, ctx);
- if (regions.length > 0) {
- // comments
- for (int i= 0; i < regions.length - 1; i++) {
- IRegion normalized= alignRegion(regions[i], ctx);
- if (normalized != null) {
- Position position= createCommentPosition(normalized);
- if (position != null) {
- boolean commentCollapse;
- if (i == 0 && (regions.length > 2 || ctx.hasHeaderComment()) && element == ctx.getFirstType()) {
- commentCollapse= ctx.collapseHeaderComments();
- } else {
- commentCollapse= ctx.collapseJavadoc();
- }
- ctx.addProjectionRange(new JavaProjectionAnnotation(commentCollapse, element, true), position);
- }
- }
- }
- // code
- if (collapseCode) {
- IRegion normalized= alignRegion(regions[regions.length - 1], ctx);
- if (normalized != null) {
- Position position= element instanceof IMember ? createMemberPosition(normalized, (IMember) element) : createCommentPosition(normalized);
- if (position != null)
- ctx.addProjectionRange(new JavaProjectionAnnotation(collapse, element, false), position);
- }
- }
- }
- }
-
- /**
- * Returns <code>true</code> if <code>type</code> is not a top-level type, <code>false</code> if it is.
- *
- * @param type the type to test
- * @return <code>true</code> if <code>type</code> is an inner type
- */
- private boolean isInnerType(IType type) {
- return type.getDeclaringType() != null;
- }
-
- /**
- * Computes the projection ranges for a given <code>ISourceReference</code>. More than one
- * range or none at all may be returned. If there are no foldable regions, an empty array is
- * returned.
- * <p>
- * The last region in the returned array (if not empty) describes the region for the java
- * element that implements the source reference. Any preceding regions describe javadoc comments
- * of that JavaScript element.
- * </p>
- *
- * @param reference a JavaScript element that is a source reference
- * @param ctx the folding context
- * @return the regions to be folded
- */
- protected final IRegion[] computeProjectionRanges(ISourceReference reference, FoldingStructureComputationContext ctx) {
- try {
- ISourceRange range= reference.getSourceRange();
- if (!SourceRange.isAvailable(range))
- return new IRegion[0];
-
- String contents= reference.getSource();
- if (contents == null)
- return new IRegion[0];
-
- List regions= new ArrayList();
- if (!ctx.hasFirstType() && reference instanceof IType) {
- ctx.setFirstType((IType) reference);
- IRegion headerComment= computeHeaderComment(ctx);
- if (headerComment != null) {
- regions.add(headerComment);
- ctx.setHasHeaderComment();
- }
- }
-
- final int shift= range.getOffset();
- IScanner scanner= ctx.getScanner();
- scanner.resetTo(shift, shift + range.getLength());
-
- int start= shift;
- while (true) {
-
- int token= scanner.getNextToken();
- start= scanner.getCurrentTokenStartPosition();
-
- switch (token) {
- case ITerminalSymbols.TokenNameCOMMENT_JAVADOC:
- case ITerminalSymbols.TokenNameCOMMENT_BLOCK: {
- int end= scanner.getCurrentTokenEndPosition() + 1;
- regions.add(new Region(start, end - start));
- continue;
- }
- case ITerminalSymbols.TokenNameCOMMENT_LINE:
- continue;
- }
-
- break;
- }
-
- regions.add(new Region(start, shift + range.getLength() - start));
-
- IRegion[] result= new IRegion[regions.size()];
- regions.toArray(result);
- return result;
- } catch (JavaScriptModelException e) {
- } catch (InvalidInputException e) {
- }
-
- return new IRegion[0];
- }
-
- private IRegion computeHeaderComment(FoldingStructureComputationContext ctx) throws JavaScriptModelException {
- // search at most up to the first type
- ISourceRange range= ctx.getFirstType().getSourceRange();
- if (range == null)
- return null;
- int start= 0;
- int end= range.getOffset();
-
-
- /* code adapted from CommentFormattingStrategy:
- * scan the header content up to the first type. Once a comment is
- * found, accumulate any additional comments up to the stop condition.
- * The stop condition is reaching a package declaration, import container,
- * or the end of the input.
- */
- IScanner scanner= ctx.getScanner();
- scanner.resetTo(start, end);
-
- int headerStart= -1;
- int headerEnd= -1;
- try {
- boolean foundComment= false;
- int terminal= scanner.getNextToken();
- while (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal== ITerminalSymbols.TokenNameWHITESPACE ||
- terminal == ITerminalSymbols.TokenNameCOMMENT_LINE || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK)
-
- {
-
- if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) {
- if (!foundComment)
- headerStart= scanner.getCurrentTokenStartPosition();
- headerEnd= scanner.getCurrentTokenEndPosition();
- foundComment= true;
- }
- terminal= scanner.getNextToken();
- }
-
-
- } catch (InvalidInputException ex) {
- return null;
- }
-
- if (headerEnd != -1) {
- return new Region(headerStart, headerEnd - headerStart);
- }
- return null;
- }
-
- /**
- * Creates a comment folding position from an
- * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned}
- * region.
- *
- * @param aligned an aligned region
- * @return a folding position corresponding to <code>aligned</code>
- */
- protected final Position createCommentPosition(IRegion aligned) {
- return new CommentPosition(aligned.getOffset(), aligned.getLength());
- }
-
- /**
- * Creates a folding position that remembers its member from an
- * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned}
- * region.
- *
- * @param aligned an aligned region
- * @param member the member to remember
- * @return a folding position corresponding to <code>aligned</code>
- */
- protected final Position createMemberPosition(IRegion aligned, IMember member) {
- return new JavaElementPosition(aligned.getOffset(), aligned.getLength(), member);
- }
-
- /**
- * Aligns <code>region</code> to start and end at a line offset. The region's start is
- * decreased to the next line offset, and the end offset increased to the next line start or the
- * end of the document. <code>null</code> is returned if <code>region</code> is
- * <code>null</code> itself or does not comprise at least one line delimiter, as a single line
- * cannot be folded.
- *
- * @param region the region to align, may be <code>null</code>
- * @param ctx the folding context
- * @return a region equal or greater than <code>region</code> that is aligned with line
- * offsets, <code>null</code> if the region is too small to be foldable (e.g. covers
- * only one line)
- */
- protected final IRegion alignRegion(IRegion region, FoldingStructureComputationContext ctx) {
- if (region == null)
- return null;
-
- IDocument document= ctx.getDocument();
-
- try {
-
- int start= document.getLineOfOffset(region.getOffset());
- int end= document.getLineOfOffset(region.getOffset() + region.getLength());
- if (start >= end)
- return null;
-
- int offset= document.getLineOffset(start);
- int endOffset;
- if (document.getNumberOfLines() > end + 1)
- endOffset= document.getLineOffset(end + 1);
- else
- endOffset= document.getLineOffset(end) + document.getLineLength(end);
-
- return new Region(offset, endOffset - offset);
-
- } catch (BadLocationException x) {
- // concurrent modification
- return null;
- }
- }
-
- private ProjectionAnnotationModel getModel() {
- return (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class);
- }
-
- private IDocument getDocument() {
- JavaEditor editor= fEditor;
- if (editor == null)
- return null;
-
- IDocumentProvider provider= editor.getDocumentProvider();
- if (provider == null)
- return null;
-
- return provider.getDocument(editor.getEditorInput());
- }
-
- /**
- * Matches deleted annotations to changed or added ones. A deleted
- * annotation/position tuple that has a matching addition / change
- * is updated and marked as changed. The matching tuple is not added
- * (for additions) or marked as deletion instead (for changes). The
- * result is that more annotations are changed and fewer get
- * deleted/re-added.
- *
- * @param deletions list with deleted annotations
- * @param additions map with position to annotation mappings
- * @param changes list with changed annotations
- * @param ctx the context
- */
- private void match(List deletions, Map additions, List changes, FoldingStructureComputationContext ctx) {
- if (deletions.isEmpty() || (additions.isEmpty() && changes.isEmpty()))
- return;
-
- List newDeletions= new ArrayList();
- List newChanges= new ArrayList();
-
- Iterator deletionIterator= deletions.iterator();
- while (deletionIterator.hasNext()) {
- JavaProjectionAnnotation deleted= (JavaProjectionAnnotation) deletionIterator.next();
- Position deletedPosition= ctx.getModel().getPosition(deleted);
- if (deletedPosition == null)
- continue;
-
- Tuple deletedTuple= new Tuple(deleted, deletedPosition);
-
- Tuple match= findMatch(deletedTuple, changes, null, ctx);
- boolean addToDeletions= true;
- if (match == null) {
- match= findMatch(deletedTuple, additions.keySet(), additions, ctx);
- addToDeletions= false;
- }
-
- if (match != null) {
- IJavaScriptElement element= match.annotation.getElement();
- deleted.setElement(element);
- deletedPosition.setLength(match.position.getLength());
- if (deletedPosition instanceof JavaElementPosition && element instanceof IMember) {
- JavaElementPosition jep= (JavaElementPosition) deletedPosition;
- jep.setMember((IMember) element);
- }
-
- deletionIterator.remove();
- newChanges.add(deleted);
-
- if (addToDeletions)
- newDeletions.add(match.annotation);
- }
- }
-
- deletions.addAll(newDeletions);
- changes.addAll(newChanges);
- }
-
- /**
- * Finds a match for <code>tuple</code> in a collection of
- * annotations. The positions for the
- * <code>JavaProjectionAnnotation</code> instances in
- * <code>annotations</code> can be found in the passed
- * <code>positionMap</code> or <code>fCachedModel</code> if
- * <code>positionMap</code> is <code>null</code>.
- * <p>
- * A tuple is said to match another if their annotations have the
- * same comment flag and their position offsets are equal.
- * </p>
- * <p>
- * If a match is found, the annotation gets removed from
- * <code>annotations</code>.
- * </p>
- *
- * @param tuple the tuple for which we want to find a match
- * @param annotations collection of
- * <code>JavaProjectionAnnotation</code>
- * @param positionMap a <code>Map&lt;Annotation, Position&gt;</code>
- * or <code>null</code>
- * @param ctx the context
- * @return a matching tuple or <code>null</code> for no match
- */
- private Tuple findMatch(Tuple tuple, Collection annotations, Map positionMap, FoldingStructureComputationContext ctx) {
- Iterator it= annotations.iterator();
- while (it.hasNext()) {
- JavaProjectionAnnotation annotation= (JavaProjectionAnnotation) it.next();
- if (tuple.annotation.isComment() == annotation.isComment()) {
- Position position= positionMap == null ? ctx.getModel().getPosition(annotation) : (Position) positionMap.get(annotation);
- if (position == null)
- continue;
-
- if (tuple.position.getOffset() == position.getOffset()) {
- it.remove();
- return new Tuple(annotation, position);
- }
- }
- }
-
- return null;
- }
-
- private Map computeCurrentStructure(FoldingStructureComputationContext ctx) {
- Map map= new HashMap();
- ProjectionAnnotationModel model= ctx.getModel();
- Iterator e= model.getAnnotationIterator();
- while (e.hasNext()) {
- Object annotation= e.next();
- if (annotation instanceof JavaProjectionAnnotation) {
- JavaProjectionAnnotation java= (JavaProjectionAnnotation) annotation;
- Position position= model.getPosition(java);
- Assert.isNotNull(position);
- List list= (List) map.get(java.getElement());
- if (list == null) {
- list= new ArrayList(2);
- map.put(java.getElement(), list);
- }
- list.add(new Tuple(java, position));
- }
- }
-
- Comparator comparator= new Comparator() {
- public int compare(Object o1, Object o2) {
- return ((Tuple) o1).position.getOffset() - ((Tuple) o2).position.getOffset();
- }
- };
- for (Iterator it= map.values().iterator(); it.hasNext();) {
- List list= (List) it.next();
- Collections.sort(list, comparator);
- }
- return map;
- }
-
- /*
- * @see IJavaFoldingStructureProviderExtension#collapseMembers()
- *
- */
- public final void collapseMembers() {
- modifyFiltered(fMemberFilter, false);
- }
-
- /*
- * @see IJavaFoldingStructureProviderExtension#collapseComments()
- *
- */
- public final void collapseComments() {
- modifyFiltered(fCommentFilter, false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProviderExtension#collapseElements(org.eclipse.wst.jsdt.core.IJavaScriptElement[])
- */
- public final void collapseElements(IJavaScriptElement[] elements) {
- Set set= new HashSet(Arrays.asList(elements));
- modifyFiltered(new JavaElementSetFilter(set, false), false);
- }
-
- /*
- * @see org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProviderExtension#expandElements(org.eclipse.wst.jsdt.core.IJavaScriptElement[])
- */
- public final void expandElements(IJavaScriptElement[] elements) {
- Set set= new HashSet(Arrays.asList(elements));
- modifyFiltered(new JavaElementSetFilter(set, true), true);
- }
-
- /**
- * Collapses or expands all annotations matched by the passed filter.
- *
- * @param filter the filter to use to select which annotations to collapse
- * @param expand <code>true</code> to expand the matched annotations, <code>false</code> to
- * collapse them
- */
- private void modifyFiltered(Filter filter, boolean expand) {
- if (!isInstalled())
- return;
-
- ProjectionAnnotationModel model= getModel();
- if (model == null)
- return;
-
- List modified= new ArrayList();
- Iterator iter= model.getAnnotationIterator();
- while (iter.hasNext()) {
- Object annotation= iter.next();
- if (annotation instanceof JavaProjectionAnnotation) {
- JavaProjectionAnnotation java= (JavaProjectionAnnotation) annotation;
-
- if (expand == java.isCollapsed() && filter.match(java)) {
- if (expand)
- java.markExpanded();
- else
- java.markCollapsed();
- modified.add(java);
- }
-
- }
- }
-
- model.modifyAnnotations(null, null, (Annotation[]) modified.toArray(new Annotation[modified.size()]));
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java
deleted file mode 100644
index 0bcfdcad..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.folding;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-
-/**
- * Contributors to the <code>org.eclipse.wst.jsdt.ui.foldingStructureProvider</code> extension point
- * can specify an implementation of this interface to be displayed on the JavaScript &gt; Editor &gt; Folding
- * preference page.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaFoldingPreferenceBlock {
-
- /**
- * Creates the control that will be displayed on the JavaScript &gt; Editor &gt; Folding
- * preference page.
- *
- * @param parent the parent composite to which to add the preferences control
- * @return the control that was added to <code>parent</code>
- */
- Control createControl(Composite parent);
-
- /**
- * Called after creating the control. Implementations should load the
- * preferences values and update the controls accordingly.
- */
- void initialize();
-
- /**
- * Called when the <code>OK</code> button is pressed on the preference
- * page. Implementations should commit the configured preference settings
- * into their form of preference storage.
- */
- void performOk();
-
- /**
- * Called when the <code>Defaults</code> button is pressed on the
- * preference page. Implementation should reset any preference settings to
- * their default values and adjust the controls accordingly.
- */
- void performDefaults();
-
- /**
- * Called when the preference page is being disposed. Implementations should
- * free any resources they are holding on to.
- */
- void dispose();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java
deleted file mode 100644
index 54d25a1f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.folding;
-
-import org.eclipse.jface.text.source.projection.ProjectionViewer;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-
-/**
- * Contributors to the
- * <code>org.eclipse.wst.jsdt.ui.foldingStructureProvider</code> extension
- * point must specify an implementation of this interface which will create and
- * maintain {@link org.eclipse.jface.text.source.projection.ProjectionAnnotation} objects
- * that define folded regions in the {@link org.eclipse.jface.text.source.projection.ProjectionViewer}.
- * <p>
- * Clients may implement this interface.
- * </p>
- * <p>
- * In order to provide backward compatibility for clients of <code>IJavaFoldingStructureProvider</code>, extension
- * interfaces are used to provide a means of evolution. The following extension interfaces exist:
- * <ul>
- * <li>{@link org.eclipse.wst.jsdt.ui.text.folding.IJavaFoldingStructureProviderExtension} since version 3.2 introducing
- * the following functions:
- * <ul>
- * <li>collapsing of comments and members</li>
- * <li>expanding and collapsing of certain JavaScript elements</li>
- * </ul>
- * </li>
- * </ul>
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaFoldingStructureProvider {
-
- /**
- * Installs this structure provider on the given editor and viewer.
- * Implementations should listen to the projection events generated by
- * <code>viewer</code> and enable / disable generation of projection
- * structure accordingly.
- *
- * @param editor the editor that this provider works on
- * @param viewer the projection viewer that displays the annotations created
- * by this structure provider
- */
- public abstract void install(ITextEditor editor, ProjectionViewer viewer);
-
- /**
- * Uninstalls this structure provider. Any references to editors or viewers
- * should be cleared.
- */
- public abstract void uninstall();
-
- /**
- * (Re-)initializes the structure provided by the receiver.
- */
- public abstract void initialize();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProviderExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProviderExtension.java
deleted file mode 100644
index c0d7fb20..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProviderExtension.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.folding;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-
-/**
- * Extends {@link IJavaFoldingStructureProvider} with the following
- * functions:
- * <ul>
- * <li>collapsing of comments and members</li>
- * <li>expanding and collapsing of certain JavaScript elements</li>
- * </ul>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaFoldingStructureProviderExtension {
- /**
- * Collapses all members except for top level types.
- */
- void collapseMembers();
-
- /**
- * Collapses all comments.
- */
- void collapseComments();
-
- /**
- * Collapses the given elements.
- *
- * @param elements the JavaScript elements to collapse (the array and its elements must not be
- * modified)
- */
- void collapseElements(IJavaScriptElement[] elements);
-
- /**
- * Expands the given elements.
- *
- * @param elements the JavaScript elements to expand (the array and its elements must not be modified)
- */
- void expandElements(IJavaScriptElement[] elements);
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/AbstractProposalSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/AbstractProposalSorter.java
deleted file mode 100644
index 398a1a9b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/AbstractProposalSorter.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import java.util.Comparator;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-
-/**
- * Abstract base class for sorters contributed to the
- * <code>org.eclipse.wst.jsdt.ui.javaCompletionProposalSorters</code> extension point.
- * <p>
- * Subclasses need to implement {@link #compare(ICompletionProposal, ICompletionProposal)} and may
- * override {@link #beginSorting(ContentAssistInvocationContext) beginSorting} and
- * {@link #endSorting() endSorting}.
- * </p>
- * <p>
- * The orderings imposed by a subclass need not be consistent with equals.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class AbstractProposalSorter implements Comparator {
-
- /**
- * Creates a new sorter. Note that subclasses must provide a zero-argument constructor to be
- * instantiatable via {@link org.eclipse.core.runtime.IConfigurationElement#createExecutableExtension(String)}.
- */
- protected AbstractProposalSorter() {
- }
-
- /**
- * Called once before sorting.
- * <p>
- * Clients may override, the default implementation does nothing.
- * </p>
- *
- * @param context the context of the content assist invocation
- */
- public void beginSorting(ContentAssistInvocationContext context) {
- }
-
- /**
- * Implements the same contract as {@link Comparator#compare(Object, Object)} but with
- * completion proposals as parameters. This method will implement the {@link Comparator}
- * interface if this class is ever converted to extend
- * <code>Comparator&lt;ICompletionProposal&gt;</code>.
- * <p>
- * The orderings imposed by an implementation need not be consistent with equals.
- * </p>
- *
- * @param p1 the first proposal to be compared
- * @param p2 the second proposal to be compared
- * @return a negative integer, zero, or a positive integer as the first argument is less than,
- * equal to, or greater than the second.
- */
- public abstract int compare(ICompletionProposal p1, ICompletionProposal p2);
-
- /**
- * Called once after sorting.
- * <p>
- * Clients may override, the default implementation does nothing.
- * </p>
- */
- public void endSorting() {
- }
-
- /**
- * This method delegates to {@link #compare(ICompletionProposal, ICompletionProposal)} and may
- * be removed if the class is ever converted to extend
- * <code>Comparator&lt;ICompletionProposal&gt;</code>.
- *
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- */
- public final int compare(Object o1, Object o2) {
- ICompletionProposal p1= (ICompletionProposal) o1;
- ICompletionProposal p2= (ICompletionProposal) o2;
-
- return compare(p1, p2);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java
deleted file mode 100644
index 531dc612..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java
+++ /dev/null
@@ -1,769 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.jsdt.core.CompletionContext;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.CompletionRequestor;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.text.java.AnonymousTypeCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.AnonymousTypeProposalInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.java.FieldProposalInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.java.FilledArgumentNamesMethodProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.GetterSetterCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.JavaMethodCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaTypeCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.MethodDeclarationCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.MethodProposalInfo;
-import org.eclipse.wst.jsdt.internal.ui.text.java.OverrideCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ParameterGuessingProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ProposalContextInformation;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavadocInlineTagCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavadocLinkTypeCompletionProposal;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.ImageDescriptorRegistry;
-import org.eclipse.wst.jsdt.ui.PreferenceConstants;
-
-/**
- * JavaScript UI implementation of <code>CompletionRequestor</code>. Produces
- * {@link IJavaCompletionProposal}s from the proposal descriptors received via
- * the <code>CompletionRequestor</code> interface.
- * <p>
- * The lifecycle of a <code>CompletionProposalCollector</code> instance is very
- * simple:
- * <pre>
- * IJavaScriptUnit unit= ...
- * int offset= ...
- *
- * CompletionProposalCollector collector= new CompletionProposalCollector(unit);
- * unit.codeComplete(offset, collector);
- * IJavaCompletionProposal[] proposals= collector.getJavaCompletionProposals();
- * String errorMessage= collector.getErrorMessage();
- *
- * &#x2f;&#x2f; display &#x2f; process proposals
- * </pre>
- * Note that after a code completion operation, the collector will store any
- * received proposals, which may require a considerable amount of memory, so the
- * collector should not be kept as a reference after a completion operation.
- * </p>
- * <p>
- * Clients may instantiate or subclass.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class CompletionProposalCollector extends CompletionRequestor {
-
- /** Tells whether this class is in debug mode. */
- private static final boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ResultCollector")); //$NON-NLS-1$//$NON-NLS-2$
-
- /** Triggers for method proposals without parameters. Do not modify. */
- protected final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' };
- /** Triggers for method proposals. Do not modify. */
- protected final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
- /** Triggers for types. Do not modify. */
- protected final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' };
- /** Triggers for variables. Do not modify. */
- protected final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';', '.' };
-
- private final CompletionProposalLabelProvider fLabelProvider= new CompletionProposalLabelProvider();
- private final ImageDescriptorRegistry fRegistry= JavaScriptPlugin.getImageDescriptorRegistry();
-
- private final List fJavaProposals= new ArrayList();
- private final List fKeywords= new ArrayList();
- private final Set fSuggestedMethodNames= new HashSet();
-
- private final IJavaScriptUnit fCompilationUnit;
- private final IJavaScriptProject fJavaProject;
- private int fUserReplacementLength;
-
- private CompletionContext fContext;
- private IProblem fLastProblem;
-
- /* performance instrumentation */
- private long fStartTime;
- private long fUITime;
-
- /**
- * The UI invocation context or <code>null</code>.
- *
- *
- */
- private JavaContentAssistInvocationContext fInvocationContext;
-
- /**
- * Creates a new instance ready to collect proposals. If the passed
- * <code>IJavaScriptUnit</code> is not contained in an
- * {@link IJavaScriptProject}, no javadoc will be available as
- * {@link org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() additional info}
- * on the created proposals.
- *
- * @param cu the compilation unit that the result collector will operate on
- */
- public CompletionProposalCollector(IJavaScriptUnit cu) {
- this(cu == null ? null : cu.getJavaScriptProject(), cu);
- }
-
- /**
- * Creates a new instance ready to collect proposals. Note that proposals
- * for anonymous types and method declarations are not created when using
- * this constructor, as those need to know the compilation unit that they
- * are created on. Use
- * {@link CompletionProposalCollector#CompletionProposalCollector(IJavaScriptUnit)}
- * instead to get all proposals.
- * <p>
- * If the passed JavaScript project is <code>null</code>, no javadoc will be
- * available as
- * {@link org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() additional info}
- * on the created (e.g. method and type) proposals.
- * </p>
- * @param project the project that the result collector will operate on, or
- * <code>null</code>
- */
- public CompletionProposalCollector(IJavaScriptProject project) {
- this(project, null);
- }
-
- private CompletionProposalCollector(IJavaScriptProject project, IJavaScriptUnit cu) {
- fJavaProject= project;
- fCompilationUnit= cu;
-
- fUserReplacementLength= -1;
- }
-
- /**
- * Sets the invocation context.
- * <p>
- * Subclasses may extend.
- * </p>
- *
- * @param context the invocation context
- * @see #getInvocationContext()
- *
- */
- public void setInvocationContext(JavaContentAssistInvocationContext context) {
- Assert.isNotNull(context);
- fInvocationContext= context;
- context.setCollector(this);
- }
-
- /**
- * Returns the invocation context. If none has been set via
- * {@link #setInvocationContext(JavaContentAssistInvocationContext)}, a new one is created.
- *
- * @return invocationContext the invocation context
- *
- */
- protected final JavaContentAssistInvocationContext getInvocationContext() {
- if (fInvocationContext == null)
- setInvocationContext(new JavaContentAssistInvocationContext(getCompilationUnit()));
- return fInvocationContext;
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Subclasses may replace, but usually should not need to. Consider
- * replacing
- * {@linkplain #createJavaCompletionProposal(CompletionProposal) createJavaCompletionProposal}
- * instead.
- * </p>
- */
- public void accept(CompletionProposal proposal) {
- long start= DEBUG ? System.currentTimeMillis() : 0;
- try {
- if (isFiltered(proposal))
- return;
-
- if (proposal.getKind() == CompletionProposal.POTENTIAL_METHOD_DECLARATION) {
- acceptPotentialMethodDeclaration(proposal);
- } else {
- IJavaCompletionProposal javaProposal= createJavaCompletionProposal(proposal);
- if (javaProposal != null) {
- fJavaProposals.add(javaProposal);
- if (proposal.getKind() == CompletionProposal.KEYWORD)
- fKeywords.add(javaProposal);
- }
- }
- } catch (IllegalArgumentException e) {
- // all signature processing method may throw IAEs
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=84657
- // don't abort, but log and show all the valid proposals
- JavaScriptPlugin.log(new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.OK, "Exception when processing proposal for: " + String.valueOf(proposal.getCompletion()), e)); //$NON-NLS-1$
- }
-
- if (DEBUG) fUITime += System.currentTimeMillis() - start;
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Subclasses may extend, but usually should not need to.
- * </p>
- * @see #getContext()
- */
- public void acceptContext(CompletionContext context) {
- fContext= context;
- fLabelProvider.setContext(context);
- }
-
- /**
- * {@inheritDoc}
- *
- * Subclasses may extend, but must call the super implementation.
- */
- public void beginReporting() {
- if (DEBUG) {
- fStartTime= System.currentTimeMillis();
- fUITime= 0;
- }
-
- fLastProblem= null;
- fJavaProposals.clear();
- fKeywords.clear();
- fSuggestedMethodNames.clear();
- }
-
- /**
- * {@inheritDoc}
- *
- * Subclasses may extend, but must call the super implementation.
- */
- public void completionFailure(IProblem problem) {
- fLastProblem= problem;
- }
-
- /**
- * {@inheritDoc}
- *
- * Subclasses may extend, but must call the super implementation.
- */
- public void endReporting() {
- if (DEBUG) {
- long total= System.currentTimeMillis() - fStartTime;
- System.err.println("Core Collector (core):\t" + (total - fUITime)); //$NON-NLS-1$
- System.err.println("Core Collector (ui):\t" + fUITime); //$NON-NLS-1$
- }
- }
-
- /**
- * Returns an error message about any error that may have occurred during
- * code completion, or the empty string if none.
- * <p>
- * Subclasses may replace or extend.
- * </p>
- * @return an error message or the empty string
- */
- public String getErrorMessage() {
- if (fLastProblem != null)
- return fLastProblem.getMessage();
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Returns the unsorted list of received proposals.
- *
- * @return the unsorted list of received proposals
- */
- public final IJavaCompletionProposal[] getJavaCompletionProposals() {
- return (IJavaCompletionProposal[]) fJavaProposals.toArray(new IJavaCompletionProposal[fJavaProposals.size()]);
- }
-
- /**
- * Returns the unsorted list of received keyword proposals.
- *
- * @return the unsorted list of received keyword proposals
- */
- public final JavaCompletionProposal[] getKeywordCompletionProposals() {
- return (JavaCompletionProposal[]) fKeywords.toArray(new JavaCompletionProposal[fKeywords.size()]);
- }
-
- /**
- * If the replacement length is set, it overrides the length returned from
- * the content assist infrastructure. Use this setting if code assist is
- * called with a none empty selection.
- *
- * @param length the new replacement length, relative to the code assist
- * offset. Must be equal to or greater than zero.
- */
- public final void setReplacementLength(int length) {
- Assert.isLegal(length >= 0);
- fUserReplacementLength= length;
- }
-
- /**
- * Computes the relevance for a given <code>CompletionProposal</code>.
- * <p>
- * Subclasses may replace, but usually should not need to.
- * </p>
- * @param proposal the proposal to compute the relevance for
- * @return the relevance for <code>proposal</code>
- */
- protected int computeRelevance(CompletionProposal proposal) {
- final int baseRelevance= proposal.getRelevance() * 16;
- switch (proposal.getKind()) {
- case CompletionProposal.PACKAGE_REF:
- return baseRelevance + 0;
- case CompletionProposal.LABEL_REF:
- return baseRelevance + 1;
- case CompletionProposal.KEYWORD:
- return baseRelevance + 2;
- case CompletionProposal.TYPE_REF:
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- return baseRelevance + 3;
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.METHOD_DECLARATION:
- return baseRelevance + 4;
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- return baseRelevance + 4 /* + 99 */;
- case CompletionProposal.FIELD_REF:
- return baseRelevance + 5;
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- return baseRelevance + 6;
- default:
- return baseRelevance;
- }
- }
-
- /**
- * Creates a new JavaScript completion proposal from a core proposal. This may
- * involve computing the display label and setting up some context.
- * <p>
- * This method is called for every proposal that will be displayed to the
- * user, which may be hundreds. Implementations should therefore defer as
- * much work as possible: Labels should be computed lazily to leverage
- * virtual table usage, and any information only needed when
- * <em>applying</em> a proposal should not be computed yet.
- * </p>
- * <p>
- * Implementations may return <code>null</code> if a proposal should not
- * be included in the list presented to the user.
- * </p>
- * <p>
- * Subclasses may extend or replace this method.
- * </p>
- *
- * @param proposal the core completion proposal to create a UI proposal for
- * @return the created JavaScript completion proposal, or <code>null</code> if
- * no proposal should be displayed
- */
- protected IJavaCompletionProposal createJavaCompletionProposal(CompletionProposal proposal) {
- switch (proposal.getKind()) {
- case CompletionProposal.KEYWORD:
- return createKeywordProposal(proposal);
- case CompletionProposal.PACKAGE_REF:
- return createPackageProposal(proposal);
- case CompletionProposal.TYPE_REF:
- return createTypeProposal(proposal);
- case CompletionProposal.JSDOC_TYPE_REF:
- return createJavadocLinkTypeProposal(proposal);
- case CompletionProposal.FIELD_REF:
- case CompletionProposal.JSDOC_FIELD_REF:
- return createFieldProposal(proposal);
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.JSDOC_METHOD_REF:
- return createMethodReferenceProposal(proposal);
- case CompletionProposal.METHOD_DECLARATION:
- return createMethodDeclarationProposal(proposal);
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- return createAnonymousTypeProposal(proposal);
- case CompletionProposal.LABEL_REF:
- return createLabelProposal(proposal);
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- return createLocalVariableProposal(proposal);
- case CompletionProposal.JSDOC_BLOCK_TAG:
- case CompletionProposal.JSDOC_PARAM_REF:
- return createJavadocSimpleProposal(proposal);
- case CompletionProposal.JSDOC_INLINE_TAG:
- return createJavadocInlineTagProposal(proposal);
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- default:
- return null;
- }
- }
-
- /**
- * Creates the context information for a given method reference proposal.
- * The passed proposal must be of kind {@link CompletionProposal#METHOD_REF}.
- *
- * @param methodProposal the method proposal for which to create context information
- * @return the context information for <code>methodProposal</code>
- */
- protected final IContextInformation createMethodContextInformation(CompletionProposal methodProposal) {
- Assert.isTrue(methodProposal.getKind() == CompletionProposal.METHOD_REF);
- return new ProposalContextInformation(methodProposal);
- }
-
- /**
- * Returns the compilation unit that the receiver operates on, or
- * <code>null</code> if the <code>IJavaScriptProject</code> constructor was
- * used to create the receiver.
- *
- * @return the compilation unit that the receiver operates on, or
- * <code>null</code>
- */
- protected final IJavaScriptUnit getCompilationUnit() {
- return fCompilationUnit;
- }
-
- /**
- * Returns the <code>CompletionContext</code> for this completion operation.
-
- * @return the <code>CompletionContext</code> for this completion operation
- * @see CompletionRequestor#acceptContext(CompletionContext)
- */
- protected final CompletionContext getContext() {
- return fContext;
- }
-
- /**
- * Returns a cached image for the given descriptor.
- *
- * @param descriptor the image descriptor to get an image for, may be
- * <code>null</code>
- * @return the image corresponding to <code>descriptor</code>
- */
- protected final Image getImage(ImageDescriptor descriptor) {
- return (descriptor == null) ? null : fRegistry.get(descriptor);
- }
-
- /**
- * Returns the proposal label provider used by the receiver.
- *
- * @return the proposal label provider used by the receiver
- */
- protected final CompletionProposalLabelProvider getLabelProvider() {
- return fLabelProvider;
- }
-
- /**
- * Returns the replacement length of a given completion proposal. The
- * replacement length is usually the difference between the return values of
- * <code>proposal.getReplaceEnd</code> and
- * <code>proposal.getReplaceStart</code>, but this behavior may be
- * overridden by calling {@link #setReplacementLength(int)}.
- *
- * @param proposal the completion proposal to get the replacement length for
- * @return the replacement length for <code>proposal</code>
- */
- protected final int getLength(CompletionProposal proposal) {
- int start= proposal.getReplaceStart();
- int end= proposal.getReplaceEnd();
- int length;
- if (fUserReplacementLength == -1) {
- length= end - start;
- } else {
- length= fUserReplacementLength;
- // extend length to begin at start
- int behindCompletion= proposal.getCompletionLocation() + 1;
- if (start < behindCompletion) {
- length+= behindCompletion - start;
- }
- }
- return length;
- }
-
- /**
- * Returns <code>true</code> if <code>proposal</code> is filtered, e.g.
- * should not be proposed to the user, <code>false</code> if it is valid.
- * <p>
- * Subclasses may extends this method. The default implementation filters
- * proposals set to be ignored via
- * {@linkplain CompletionRequestor#setIgnored(int, boolean) setIgnored} and
- * types set to be ignored in the preferences.
- * </p>
- *
- * @param proposal the proposal to filter
- * @return <code>true</code> to filter <code>proposal</code>,
- * <code>false</code> to let it pass
- */
- protected boolean isFiltered(CompletionProposal proposal) {
- if (isIgnored(proposal.getKind()))
- return true;
- char[] declaringType= getDeclaringType(proposal);
- return declaringType!= null && TypeFilter.isFiltered(declaringType);
- }
-
- /**
- * Returns the type signature of the declaring type of a
- * <code>CompletionProposal</code>, or <code>null</code> for proposals
- * that do not have a declaring type. The return value is <em>not</em>
- * <code>null</code> for proposals of the following kinds:
- * <ul>
- * <li>FUNCTION_DECLARATION</li>
- * <li>METHOD_NAME_REFERENCE</li>
- * <li>FUNCTION_REF</li>
- * <li>ANNOTATION_ATTRIBUTE_REF</li>
- * <li>POTENTIAL_METHOD_DECLARATION</li>
- * <li>ANONYMOUS_CLASS_DECLARATION</li>
- * <li>FIELD_REF</li>
- * <li>PACKAGE_REF (returns the package, but no type)</li>
- * <li>TYPE_REF</li>
- * </ul>
- *
- * @param proposal the completion proposal to get the declaring type for
- * @return the type signature of the declaring type, or <code>null</code> if there is none
- * @see Signature#toCharArray(char[])
- */
- protected final char[] getDeclaringType(CompletionProposal proposal) {
- switch (proposal.getKind()) {
- case CompletionProposal.METHOD_DECLARATION:
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.JSDOC_METHOD_REF:
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- case CompletionProposal.FIELD_REF:
- case CompletionProposal.JSDOC_FIELD_REF:
- char[] declaration= proposal.getDeclarationSignature();
- // special methods may not have a declaring type: methods defined on arrays etc.
- // Currently known: class literals don't have a declaring type - use Object
- if (declaration == null)
- return "java.lang.Object".toCharArray(); //$NON-NLS-1$
- return Signature.toCharArray(declaration);
- case CompletionProposal.PACKAGE_REF:
- return proposal.getDeclarationSignature();
- case CompletionProposal.JSDOC_TYPE_REF:
- case CompletionProposal.TYPE_REF:
- return Signature.toCharArray(proposal.getSignature());
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- case CompletionProposal.KEYWORD:
- case CompletionProposal.LABEL_REF:
- case CompletionProposal.JSDOC_BLOCK_TAG:
- case CompletionProposal.JSDOC_INLINE_TAG:
- case CompletionProposal.JSDOC_PARAM_REF:
- return null;
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- private void acceptPotentialMethodDeclaration(CompletionProposal proposal) {
- if (fCompilationUnit == null)
- return;
-
- String prefix= String.valueOf(proposal.getName());
- int completionStart= proposal.getReplaceStart();
- int completionEnd= proposal.getReplaceEnd();
- int relevance= computeRelevance(proposal);
-
- try {
- IJavaScriptElement element= fCompilationUnit.getElementAt(proposal.getCompletionLocation() + 1);
- if (element != null) {
- IType type= (IType) element.getAncestor(IJavaScriptElement.TYPE);
- if (type != null) {
- GetterSetterCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, relevance + 1, fSuggestedMethodNames, fJavaProposals);
- MethodDeclarationCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, relevance, fSuggestedMethodNames, fJavaProposals);
- }
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
-
- private IJavaCompletionProposal createAnonymousTypeProposal(CompletionProposal proposal) {
- if (fCompilationUnit == null || fJavaProject == null)
- return null;
-
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- int relevance= computeRelevance(proposal);
-
- String label= fLabelProvider.createAnonymousTypeLabel(proposal);
-
- JavaCompletionProposal javaProposal= new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, completion, label, String.valueOf(proposal.getDeclarationSignature()), relevance);
- javaProposal.setProposalInfo(new AnonymousTypeProposalInfo(fJavaProject, proposal));
- return javaProposal;
- }
-
- private IJavaCompletionProposal createFieldProposal(CompletionProposal proposal) {
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- String label= fLabelProvider.createLabel(proposal);
- Image image= getImage(fLabelProvider.createFieldImageDescriptor(proposal));
- int relevance= computeRelevance(proposal);
-
- JavaCompletionProposal javaProposal= new JavaCompletionProposal(completion, start, length, image, label, relevance, getContext().isInJsdoc(), getInvocationContext());
- if (fJavaProject != null)
- javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));
-
- javaProposal.setTriggerCharacters(VAR_TRIGGER);
-
- return javaProposal;
- }
-
- private IJavaCompletionProposal createJavadocSimpleProposal(CompletionProposal javadocProposal) {
- // TODO do better with javadoc proposals
-// String completion= String.valueOf(proposal.getCompletion());
-// int start= proposal.getReplaceStart();
-// int length= getLength(proposal);
-// String label= fLabelProvider.createSimpleLabel(proposal);
-// Image image= getImage(fLabelProvider.createImageDescriptor(proposal));
-// int relevance= computeRelevance(proposal);
-//
-// JavaCompletionProposal javaProposal= new JavaCompletionProposal(completion, start, length, image, label, relevance);
-// if (fJavaProject != null)
-// javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal));
-//
-// javaProposal.setTriggerCharacters(VAR_TRIGGER);
-//
-// return javaProposal;
- LazyJavaCompletionProposal proposal = new LazyJavaCompletionProposal(javadocProposal, getInvocationContext());
-// adaptLength(proposal, javadocProposal);
- return proposal;
- }
-
- private IJavaCompletionProposal createJavadocInlineTagProposal(CompletionProposal javadocProposal) {
- LazyJavaCompletionProposal proposal= new JavadocInlineTagCompletionProposal(javadocProposal, getInvocationContext());
- adaptLength(proposal, javadocProposal);
- return proposal;
- }
-
- private IJavaCompletionProposal createKeywordProposal(CompletionProposal proposal) {
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- String label= fLabelProvider.createSimpleLabel(proposal);
- int relevance= computeRelevance(proposal);
- return new JavaCompletionProposal(completion, start, length, null, label, relevance);
- }
-
- private IJavaCompletionProposal createLabelProposal(CompletionProposal proposal) {
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- String label= fLabelProvider.createSimpleLabel(proposal);
- int relevance= computeRelevance(proposal);
-
- return new JavaCompletionProposal(completion, start, length, null, label, relevance);
- }
-
- private IJavaCompletionProposal createLocalVariableProposal(CompletionProposal proposal) {
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- Image image= getImage(fLabelProvider.createLocalImageDescriptor(proposal));
- String label= fLabelProvider.createSimpleLabelWithType(proposal);
- int relevance= computeRelevance(proposal);
-
- final JavaCompletionProposal javaProposal= new JavaCompletionProposal(completion, start, length, image, label, relevance);
- javaProposal.setTriggerCharacters(VAR_TRIGGER);
- return javaProposal;
- }
-
- private IJavaCompletionProposal createMethodDeclarationProposal(CompletionProposal proposal) {
- if (fCompilationUnit == null || fJavaProject == null)
- return null;
-
- String name= String.valueOf(proposal.getName());
- String[] paramTypes= Signature.getParameterTypes(String.valueOf(proposal.getSignature()));
- for (int index= 0; index < paramTypes.length; index++)
- paramTypes[index]= Signature.toString(paramTypes[index]);
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
-
- String label= fLabelProvider.createOverrideMethodProposalLabel(proposal);
-
- JavaCompletionProposal javaProposal= new OverrideCompletionProposal(fJavaProject, fCompilationUnit, name, paramTypes, start, length, label, String.valueOf(proposal.getCompletion()));
- javaProposal.setImage(getImage(fLabelProvider.createMethodImageDescriptor(proposal)));
- javaProposal.setProposalInfo(new MethodProposalInfo(fJavaProject, proposal));
- javaProposal.setRelevance(computeRelevance(proposal));
-
- fSuggestedMethodNames.add(new String(name));
- return javaProposal;
- }
-
- private IJavaCompletionProposal createMethodReferenceProposal(CompletionProposal methodProposal) {
- IPreferenceStore preferenceStore= JavaScriptPlugin.getDefault().getPreferenceStore();
- LazyJavaCompletionProposal proposal = null;
-
- if(preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)) {
- String completion= String.valueOf(methodProposal.getCompletion());
- // normal behavior if this is not a normal completion or has no parameters
- if ((completion.length() == 0) || ((completion.length() == 1) && completion.charAt(0) == ')') || Signature.getParameterCount(methodProposal.getSignature()) == 0 || getContext().isInJsdoc()) {
- proposal= new JavaMethodCompletionProposal(methodProposal, getInvocationContext());
- } else {
- if (preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS))
- proposal = new ParameterGuessingProposal(methodProposal, getInvocationContext());
- else
- proposal = new FilledArgumentNamesMethodProposal(methodProposal, getInvocationContext());
- }
- }
-
- if(proposal == null)
- proposal= new JavaMethodCompletionProposal(methodProposal, getInvocationContext());
-
- adaptLength(proposal, methodProposal);
- return proposal;
- }
-
- private void adaptLength(LazyJavaCompletionProposal proposal, CompletionProposal coreProposal) {
- if (fUserReplacementLength != -1) {
- proposal.setReplacementLength(getLength(coreProposal));
- }
- }
-
- private IJavaCompletionProposal createPackageProposal(CompletionProposal proposal) {
- String completion= String.valueOf(proposal.getCompletion());
- int start= proposal.getReplaceStart();
- int length= getLength(proposal);
- String label= fLabelProvider.createSimpleLabel(proposal);
- Image image= getImage(fLabelProvider.createPackageImageDescriptor(proposal));
- int relevance= computeRelevance(proposal);
-
- return new JavaCompletionProposal(completion, start, length, image, label, relevance);
- }
-
- private IJavaCompletionProposal createTypeProposal(CompletionProposal typeProposal) {
- LazyJavaCompletionProposal proposal= new LazyJavaTypeCompletionProposal(typeProposal, getInvocationContext());
- adaptLength(proposal, typeProposal);
- return proposal;
- }
-
- private IJavaCompletionProposal createJavadocLinkTypeProposal(CompletionProposal typeProposal) {
- LazyJavaCompletionProposal proposal= new JavadocLinkTypeCompletionProposal(typeProposal, getInvocationContext());
- adaptLength(proposal, typeProposal);
- return proposal;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java
deleted file mode 100644
index 800a0369..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import java.util.Comparator;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.templates.TemplateProposal;
-import org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal;
-
-/**
- * Comparator for JavaScript completion proposals. Completion proposals can be sorted by relevance or
- * alphabetically.
- * <p>
- * Note: this comparator imposes orderings that are inconsistent with equals.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public final class CompletionProposalComparator implements Comparator {
-
- private boolean fOrderAlphabetically;
-
- /**
- * Creates a comparator that sorts by relevance.
- */
- public CompletionProposalComparator() {
- fOrderAlphabetically= false;
- }
-
- /**
- * Sets the sort order. Default is <code>false</code>, i.e. order by
- * relevance.
- *
- * @param orderAlphabetically <code>true</code> to order alphabetically,
- * <code>false</code> to order by relevance
- */
- public void setOrderAlphabetically(boolean orderAlphabetically) {
- fOrderAlphabetically= orderAlphabetically;
- }
-
- /*
- * @see Comparator#compare(Object, Object)
- */
- public int compare(Object o1, Object o2) {
- ICompletionProposal p1= (ICompletionProposal) o1;
- ICompletionProposal p2= (ICompletionProposal) o2;
-
- if (!fOrderAlphabetically) {
- int r1= getRelevance(p1);
- int r2= getRelevance(p2);
- int relevanceDif= r2 - r1;
- if (relevanceDif != 0) {
- return relevanceDif;
- }
- }
- /*
- * TODO the correct (but possibly much slower) sorting would use a
- * collator.
- */
- // fix for bug 67468
- return getSortKey(p1).compareToIgnoreCase(getSortKey(p2));
- }
-
- private String getSortKey(ICompletionProposal p) {
- if (p instanceof AbstractJavaCompletionProposal)
- return ((AbstractJavaCompletionProposal) p).getSortString();
- return p.getDisplayString();
- }
-
- private int getRelevance(ICompletionProposal obj) {
- if (obj instanceof IJavaCompletionProposal) {
- IJavaCompletionProposal jcp= (IJavaCompletionProposal) obj;
- return jcp.getRelevance();
- } else if (obj instanceof TemplateProposal) {
- TemplateProposal tp= (TemplateProposal) obj;
- return tp.getRelevance();
- }
- // catch all
- return 0;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java
deleted file mode 100644
index 044208e1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java
+++ /dev/null
@@ -1,722 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import java.util.Arrays;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.wst.jsdt.core.CompletionContext;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JSDScopeUtil;
-import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementImageDescriptor;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels;
-
-
-/**
- * Provides labels for JavaScript content assist proposals. The functionality is
- * similar to the one provided by {@link org.eclipse.wst.jsdt.ui.JavaScriptElementLabels},
- * but based on signatures and {@link CompletionProposal}s.
- *
- * @see Signature
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class CompletionProposalLabelProvider {
-
- /**
- * The completion context.
- *
- *
- */
- private CompletionContext fContext;
-
- /**
- * Creates a new label provider.
- */
- public CompletionProposalLabelProvider() {
- }
-
- /**
- * Creates and returns a parameter list of the given method or type proposal
- * suitable for display. The list does not include parentheses. The lower
- * bound of parameter types is returned.
- * <p>
- * Examples:
- * <pre>
- * &quot;void method(int i, Strings)&quot; -&gt; &quot;int i, String s&quot;
- * &quot;? extends Number method(java.lang.String s, ? super Number n)&quot; -&gt; &quot;String s, Number n&quot;
- * </pre>
- * </p>
- *
- * @param proposal the proposal to create the parameter list
- * for. Must be of kind {@link CompletionProposal#METHOD_REF} or
- * {@link CompletionProposal#TYPE_REF}.
- * @return the list of comma-separated parameters suitable for display
- */
- public String createParameterList(CompletionProposal proposal) {
- int kind= proposal.getKind();
- switch (kind) {
- case CompletionProposal.METHOD_REF:
- return appendUnboundedParameterList(new StringBuffer(), proposal).toString();
- default:
- Assert.isLegal(false);
- return null; // dummy
- }
- }
-
- /**
- * Appends the parameter list to <code>buffer</code>.
- *
- * @param buffer the buffer to append to
- * @param methodProposal the method proposal
- * @return the modified <code>buffer</code>
- */
- private StringBuffer appendUnboundedParameterList(StringBuffer buffer, CompletionProposal methodProposal) {
- // TODO remove once https://bugs.eclipse.org/bugs/show_bug.cgi?id=85293
- // gets fixed.
- char[] signature= methodProposal.getSignature();
- char[][] parameterNames= methodProposal.findParameterNames(null);
- char[][] parameterTypes= Signature.getParameterTypes(signature);
-
- for (int i= 0; i < parameterTypes.length; i++)
- parameterTypes[i]= createTypeDisplayName(parameterTypes[i]);
-
- if (Flags.isVarargs(methodProposal.getFlags())) {
- int index= parameterTypes.length - 1;
- parameterTypes[index]= convertToVararg(parameterTypes[index]);
- }
- return appendParameterSignature(buffer, parameterTypes, parameterNames);
- }
-
- /**
- * Converts the display name for an array type into a variable arity display name.
- * <p>
- * Examples:
- * <ul>
- * <li> "int[]" -> "int..."</li>
- * <li> "Object[][]" -> "Object[]..."</li>
- * <li> "String" -> "String"</li>
- * </ul>
- * </p>
- * <p>
- * If <code>typeName</code> does not include the substring "[]", it is returned unchanged.
- * </p>
- *
- * @param typeName the type name to convert
- * @return the converted type name
- *
- */
- private char[] convertToVararg(char[] typeName) {
- if (typeName == null)
- return typeName;
- final int len= typeName.length;
- if (len < 2)
- return typeName;
-
- if (typeName[len - 1] != ']')
- return typeName;
- if (typeName[len - 2] != '[')
- return typeName;
-
- char[] vararg= new char[len + 1];
- System.arraycopy(typeName, 0, vararg, 0, len - 2);
- vararg[len - 2]= '.';
- vararg[len - 1]= '.';
- vararg[len]= '.';
- return vararg;
- }
-
- /**
- * Returns the display string for a JavaScript type signature.
- *
- * @param typeSignature the type signature to create a display name for
- * @return the display name for <code>typeSignature</code>
- * @throws IllegalArgumentException if <code>typeSignature</code> is not a
- * valid signature
- * @see Signature#toCharArray(char[])
- * @see Signature#getSimpleName(char[])
- */
- private char[] createTypeDisplayName(char[] typeSignature) throws IllegalArgumentException {
- char[] displayName= Signature.getSimpleName(Signature.toCharArray(typeSignature));
-
- // XXX see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84675
- boolean useShortGenerics= false;
- if (useShortGenerics) {
- StringBuffer buf= new StringBuffer();
- buf.append(displayName);
- int pos;
- do {
- pos= buf.indexOf("? extends "); //$NON-NLS-1$
- if (pos >= 0) {
- buf.replace(pos, pos + 10, "+"); //$NON-NLS-1$
- } else {
- pos= buf.indexOf("? super "); //$NON-NLS-1$
- if (pos >= 0)
- buf.replace(pos, pos + 8, "-"); //$NON-NLS-1$
- }
- } while (pos >= 0);
- return buf.toString().toCharArray();
- }
- return displayName;
- }
-
- /**
- * Creates a display string of a parameter list (without the parentheses)
- * for the given parameter types and names.
- *
- * @param buffer the string buffer
- * @param parameterTypes the parameter types
- * @param parameterNames the parameter names
- * @return the display string of the parameter list defined by the passed arguments
- */
- private final StringBuffer appendParameterSignature(StringBuffer buffer, char[][] parameterTypes, char[][] parameterNames) {
- if (parameterTypes != null) {
- for (int i = 0; i < parameterTypes.length; i++) {
- if (i > 0) {
- buffer.append(',');
- buffer.append(' ');
- }
- if (!Arrays.equals(Signature.ANY, parameterTypes[i])) {
- buffer.append(parameterTypes[i]);
- buffer.append(' ');
- }
-
- if (parameterNames != null && parameterNames[i] != null) {
- buffer.append(parameterNames[i]);
- }
- }
- }
- return buffer;
- }
-
- /**
- * Creates a display label for the given method proposal. The display label
- * consists of:
- * <ul>
- * <li>the method name</li>
- * <li>the parameter list (see {@link #createParameterList(CompletionProposal)})</li>
- * <li>the upper bound of the return type (see {@link SignatureUtil#getUpperBound(String)})</li>
- * <li>the raw simple name of the declaring type</li>
- * </ul>
- * <p>
- * Examples:
- * For the <code>get(int)</code> method of a variable of type <code>List<? extends Number></code>, the following
- * display name is returned: <code>get(int index) Number - List</code>.<br>
- * For the <code>add(E)</code> method of a variable of type <code>List<? super Number></code>, the following
- * display name is returned: <code>add(Number o) void - List</code>.<br>
- * </p>
- *
- * @param methodProposal the method proposal to display
- * @return the display label for the given method proposal
- */
- String createMethodProposalLabel(CompletionProposal methodProposal) {
- StringBuffer nameBuffer= new StringBuffer();
-
- // method name
- nameBuffer.append(methodProposal.getName());
-
- // parameters
- nameBuffer.append('(');
- appendUnboundedParameterList(nameBuffer, methodProposal);
- nameBuffer.append(')');
-
- // return type
- if (!methodProposal.isConstructor()) {
- // TODO remove SignatureUtil.fix83600 call when bugs are fixed
- char[] returnType= createTypeDisplayName(Signature.getReturnType(methodProposal.getSignature()));
- if (!Arrays.equals(Signature.ANY,returnType))
- {
- nameBuffer.append(" "); //$NON-NLS-1$
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( returnType, nameBuffer );
- //nameBuffer.append(returnType);
- }
- }
-
- // declaring type
- nameBuffer.append(" - "); //$NON-NLS-1$
- String declaringType= extractDeclaringTypeFQN(methodProposal);
-// declaringType= Signature.getSimpleName(declaringType);
-
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declaringType, nameBuffer );
-
- return nameBuffer.toString();
- }
-
- /**
- * Creates a display label for the given method proposal. The display label consists of:
- * <ul>
- * <li>the method name</li>
- * <li>the raw simple name of the declaring type</li>
- * </ul>
- * <p>
- * Examples: For the <code>get(int)</code> method of a variable of type
- * <code>List<? extends Number></code>, the following display name is returned <code>get(int) - List</code>.<br>
- * For the <code>add(E)</code> method of a variable of type <code>List</code>, the
- * following display name is returned:
- * <code>add(Object) - List</code>.<br>
- * </p>
- *
- * @param methodProposal the method proposal to display
- * @return the display label for the given method proposal
- *
- */
- String createJavadocMethodProposalLabel(CompletionProposal methodProposal) {
- StringBuffer nameBuffer= new StringBuffer();
-
- // method name
- nameBuffer.append(methodProposal.getCompletion());
-
- // declaring type
- nameBuffer.append(" - "); //$NON-NLS-1$
- String declaringType= extractDeclaringTypeFQN(methodProposal);
- declaringType= Signature.getSimpleName(declaringType);
- nameBuffer.append(declaringType);
-
- return nameBuffer.toString();
- }
-
- String createOverrideMethodProposalLabel(CompletionProposal methodProposal) {
- StringBuffer nameBuffer= new StringBuffer();
-
- // method name
- nameBuffer.append(methodProposal.getName());
-
- // parameters
- nameBuffer.append('(');
- appendUnboundedParameterList(nameBuffer, methodProposal);
- nameBuffer.append(") "); //$NON-NLS-1$
-
- // return type
- // TODO remove SignatureUtil.fix83600 call when bugs are fixed
- char[] returnType= createTypeDisplayName(Signature.getReturnType(methodProposal.getSignature()));
- nameBuffer.append(returnType);
-
- // declaring type
- nameBuffer.append(" - "); //$NON-NLS-1$
-
- String declaringType= extractDeclaringTypeFQN(methodProposal);
- declaringType= Signature.getSimpleName(declaringType);
- nameBuffer.append(Messages.format(JavaTextMessages.ResultCollector_overridingmethod, new String(declaringType)));
-
- return nameBuffer.toString();
- }
-
- /**
- * Extracts the fully qualified name of the declaring type of a method
- * reference.
- *
- * @param methodProposal a proposed method
- * @return the qualified name of the declaring type
- */
- private String extractDeclaringTypeFQN(CompletionProposal methodProposal) {
- char[] declaringTypeSignature= methodProposal.getDeclarationSignature();
- char[] compUnit = methodProposal.getDeclarationTypeName();
- IJavaScriptProject project = methodProposal.getJavaProject();
- JsGlobalScopeContainerInitializer init = JSDScopeUtil.findLibraryInitializer(new Path(new String(compUnit)),project);
- if(init!=null) {
- String description = init.getDescription(new Path(new String(compUnit)),project);
- if( description!=null) return "[" + description + "]"; //$NON-NLS-1$ //$NON-NLS-2$
-
- }
-
- // special methods may not have a declaring type: methods defined on arrays etc.
- // TODO remove when bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed
- if (declaringTypeSignature == null)
- return "java.lang.Object"; //$NON-NLS-1$
- return SignatureUtil.stripSignatureToFQN(String.valueOf(declaringTypeSignature));
- }
-
- /**
- * Creates a display label for a given type proposal. The display label
- * consists of:
- * <ul>
- * <li>the simple type name (erased when the context is in javadoc)</li>
- * <li>the package name</li>
- * </ul>
- * <p>
- * Examples:
- * A proposal for the generic type <code>java.util.List&lt;E&gt;</code>, the display label
- * is: <code>List<E> - java.util</code>.
- * </p>
- *
- * @param typeProposal the method proposal to display
- * @return the display label for the given type proposal
- */
- String createTypeProposalLabel(CompletionProposal typeProposal) {
- StringBuffer buf= new StringBuffer();
- buf.append(typeProposal.getCompletion());
- char[] declarationSignature = typeProposal.getDeclarationSignature();
- if (declarationSignature!=null && declarationSignature.length>0)
- {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(declarationSignature);
- }
- return buf.toString();
-// char[] signature;
-// if (fContext != null && fContext.isInJavadoc())
-// signature= Signature.getTypeErasure(typeProposal.getSignature());
-// else
-// signature= typeProposal.getSignature();
-// char[] fullName= Signature.toCharArray(signature);
-// return createTypeProposalLabel(fullName);
- }
-
- String createJavadocTypeProposalLabel(CompletionProposal typeProposal) {
- char[] fullName= Signature.toCharArray(typeProposal.getSignature());
- return createJavadocTypeProposalLabel(fullName);
- }
-
- String createJavadocSimpleProposalLabel(CompletionProposal proposal) {
- // TODO get rid of this
- return createSimpleLabel(proposal);
- }
-
- String createTypeProposalLabel(char[] fullName) {
- // only display innermost type name as type name, using any
- // enclosing types as qualification
-// int qIndex= findSimpleNameStart(fullName);
-//
- StringBuffer buf= new StringBuffer();
-// buf.append(fullName, qIndex, fullName.length - qIndex);
-// if (qIndex > 0) {
-// buf.append(JavaScriptElementLabels.CONCAT_STRING);
-// buf.append(fullName, 0, qIndex - 1);
-// }
- buf.append(fullName);
- return buf.toString();
- }
-
- String createJavadocTypeProposalLabel(char[] fullName) {
- // only display innermost type name as type name, using any
- // enclosing types as qualification
- int qIndex= findSimpleNameStart(fullName);
-
- StringBuffer buf= new StringBuffer("{@link "); //$NON-NLS-1$
- buf.append(fullName, qIndex, fullName.length - qIndex);
- buf.append('}');
- if (qIndex > 0) {
- buf.append(JavaScriptElementLabels.CONCAT_STRING);
- buf.append(fullName, 0, qIndex - 1);
- }
- return buf.toString();
- }
-
- private int findSimpleNameStart(char[] array) {
- int lastDot= 0;
- for (int i= 0, len= array.length; i < len; i++) {
- char ch= array[i];
- if (ch == '<') {
- return lastDot;
- } else if (ch == '.') {
- lastDot= i + 1;
- }
- }
- return lastDot;
- }
-
- String createSimpleLabelWithType(CompletionProposal proposal) {
- StringBuffer buf= new StringBuffer();
- buf.append(proposal.getCompletion());
- char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
-
- if (typeName.length > 0) {
- buf.append(" "); //$NON-NLS-1$
-
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( typeName, buf );
- }
- return buf.toString();
- }
-
- /**
- * Returns whether the given string starts with "this.".
- *
- * @param string
- * @return <code>true</code> if the given string starts with "this."
- *
- */
- private boolean isThisPrefix(char[] string) {
- if (string == null || string.length < 5)
- return false;
- return string[0] == 't' && string[1] == 'h' && string[2] == 'i' && string[3] == 's' && string[4] == '.';
- }
- String createLabelWithTypeAndDeclaration(CompletionProposal proposal) {
- char[] name= proposal.getCompletion();
- if (!isThisPrefix(name))
- name= proposal.getName();
-
- StringBuffer buf= new StringBuffer();
- buf.append(name);
- char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature());
- if (typeName.length > 0&& !(Arrays.equals(Signature.ANY, typeName))) {
- buf.append(" "); //$NON-NLS-1$
-
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( typeName, buf );
- }
- char[] declaration= proposal.getDeclarationSignature();
- if (declaration != null) {
- declaration= Signature.getSignatureSimpleName(declaration);
- if (declaration.length > 0) {
- buf.append(" - "); //$NON-NLS-1$
-
- //@GINO: Anonymous UI Label
- org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declaration, buf );
- }
- }
-
- return buf.toString();
- }
-
- String createPackageProposalLabel(CompletionProposal proposal) {
- Assert.isTrue(proposal.getKind() == CompletionProposal.PACKAGE_REF);
- return String.valueOf(proposal.getDeclarationSignature());
- }
-
- String createSimpleLabel(CompletionProposal proposal) {
- return String.valueOf(proposal.getCompletion());
- }
-
- String createAnonymousTypeLabel(CompletionProposal proposal) {
- char[] declaringTypeSignature= proposal.getDeclarationSignature();
-
- StringBuffer buffer= new StringBuffer();
- buffer.append(Signature.getSignatureSimpleName(declaringTypeSignature));
- buffer.append('(');
- appendUnboundedParameterList(buffer, proposal);
- buffer.append(')');
- buffer.append(" "); //$NON-NLS-1$
- buffer.append(JavaTextMessages.ResultCollector_anonymous_type);
-
- return buffer.toString();
- }
-
- /**
- * Creates the display label for a given <code>CompletionProposal</code>.
- *
- * @param proposal the completion proposal to create the display label for
- * @return the display label for <code>proposal</code>
- */
- public String createLabel(CompletionProposal proposal) {
- switch (proposal.getKind()) {
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- if (fContext != null && fContext.isInJsdoc())
- return createJavadocMethodProposalLabel(proposal);
- return createMethodProposalLabel(proposal);
- case CompletionProposal.METHOD_DECLARATION:
- return createOverrideMethodProposalLabel(proposal);
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- return createAnonymousTypeLabel(proposal);
- case CompletionProposal.TYPE_REF:
- return createTypeProposalLabel(proposal);
- case CompletionProposal.JSDOC_TYPE_REF:
- return createJavadocTypeProposalLabel(proposal);
- case CompletionProposal.JSDOC_FIELD_REF:
- case CompletionProposal.JSDOC_BLOCK_TAG:
- case CompletionProposal.JSDOC_INLINE_TAG:
- case CompletionProposal.JSDOC_PARAM_REF:
- return createJavadocSimpleProposalLabel(proposal);
- case CompletionProposal.JSDOC_METHOD_REF:
- return createJavadocMethodProposalLabel(proposal);
- case CompletionProposal.PACKAGE_REF:
- return createPackageProposalLabel(proposal);
- case CompletionProposal.FIELD_REF:
- return createLabelWithTypeAndDeclaration(proposal);
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- return createSimpleLabelWithType(proposal);
- case CompletionProposal.KEYWORD:
- case CompletionProposal.LABEL_REF:
- return createSimpleLabel(proposal);
- default:
- Assert.isTrue(false);
- return null;
- }
- }
-
- /**
- * Creates and returns a decorated image descriptor for a completion proposal.
- *
- * @param proposal the proposal for which to create an image descriptor
- * @return the created image descriptor, or <code>null</code> if no image is available
- */
- public ImageDescriptor createImageDescriptor(CompletionProposal proposal) {
-// char[] compUnit = proposal.getDeclarationTypeName();
-// char[] propType = proposal.getName();
-// IJavaScriptProject project = proposal.getJavaProject();
-//
-// IJsGlobalScopeContainerInitializerExtension init = null;
-// IType type = proposal.getNameLookup().findType(new String(compUnit), true, NameLookup.ACCEPT_ALL);
-// IPackageFragment frag = type.getPackageFragment();
-//
-// if(compUnit!=null && propType!=null)
-// init = JSDScopeUiUtil.findLibraryUiInitializer(new Path(new String(compUnit)),project);
-// if(init!=null) {
-// ImageDescriptor description = init.getImage(new Path(new String(compUnit)),new String(propType), project);
-// if( description!=null) return description;
-// }
-
- final int flags= proposal.getFlags();
-
- ImageDescriptor descriptor;
- switch (proposal.getKind()) {
- case CompletionProposal.METHOD_DECLARATION:
- case CompletionProposal.METHOD_NAME_REFERENCE:
- case CompletionProposal.METHOD_REF:
- case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
- descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, flags);
- break;
- case CompletionProposal.ANONYMOUS_CLASS_DECLARATION:
- case CompletionProposal.TYPE_REF:
- switch (Signature.getTypeSignatureKind(proposal.getSignature())) {
- case Signature.CLASS_TYPE_SIGNATURE:
- descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, false, flags, false);
- break;
- default:
- descriptor= null;
- }
- break;
- case CompletionProposal.FIELD_REF:
- descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, flags);
- break;
- case CompletionProposal.LOCAL_VARIABLE_REF:
- case CompletionProposal.VARIABLE_DECLARATION:
- descriptor= JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE;
- break;
- case CompletionProposal.PACKAGE_REF:
- descriptor= JavaPluginImages.DESC_OBJS_PACKAGE;
- break;
- case CompletionProposal.KEYWORD:
- case CompletionProposal.LABEL_REF:
- descriptor= null;
- break;
- case CompletionProposal.JSDOC_METHOD_REF:
- case CompletionProposal.JSDOC_TYPE_REF:
- case CompletionProposal.JSDOC_FIELD_REF:
- case CompletionProposal.JSDOC_BLOCK_TAG:
- case CompletionProposal.JSDOC_INLINE_TAG:
- case CompletionProposal.JSDOC_PARAM_REF:
- descriptor = JavaPluginImages.DESC_OBJS_JAVADOCTAG;
- break;
- default:
- descriptor= null;
- Assert.isTrue(false);
- }
-
- if (descriptor == null)
- return null;
- return decorateImageDescriptor(descriptor, proposal);
- }
-
- ImageDescriptor createMethodImageDescriptor(CompletionProposal proposal) {
-// char[] compUnit = proposal.getDeclarationTypeName();
-// char[] propType = proposal.getName();
-// IJavaScriptProject project = proposal.getJavaProject();
- //if (compUnit!=null && compUnit.length>0)
-// {
-// IJsGlobalScopeContainerInitializerExtension init = JSDScopeUiUtil.findLibraryUiInitializer(new Path(new String(compUnit)),project);
-// if(init!=null) {
-// ImageDescriptor description = init.getImage(new Path(new String(compUnit)),new String(propType), project);
-// if( description!=null) return description;
-// }
-// }
- final int flags= proposal.getFlags();
- return decorateImageDescriptor(JavaElementImageProvider.getMethodImageDescriptor(false, flags), proposal);
- }
-
- ImageDescriptor createTypeImageDescriptor(CompletionProposal proposal) {
- final int flags= proposal.getFlags();
- return decorateImageDescriptor(JavaElementImageProvider.getTypeImageDescriptor(true /* in order to get all visibility decorations */, false, flags, false), proposal);
- }
-
- ImageDescriptor createFieldImageDescriptor(CompletionProposal proposal) {
-// char[] compUnit = proposal.getDeclarationTypeName();
-// char[] propType = proposal.getName();
-// IJavaScriptProject project = proposal.getJavaProject();
-// NameLookup lookup = proposal.getNameLookup();
-// IJavaScriptUnit[] sources = lookup.findTypeSources(new String(propType),true);
-
-
-// if (compUnit!=null && compUnit.length>0)
-// {
-// IJsGlobalScopeContainerInitializerExtension init = JSDScopeUiUtil.findLibraryUiInitializer(new Path(new String(compUnit)),project);
-// if(init!=null) {
-// ImageDescriptor description = init.getImage(new Path(new String(compUnit)),new String(propType), project);
-// if( description!=null) return description;
-// }
-// }
-//
- final int flags= proposal.getFlags();
- return decorateImageDescriptor(JavaElementImageProvider.getFieldImageDescriptor(false, flags), proposal);
- }
-
- ImageDescriptor createLocalImageDescriptor(CompletionProposal proposal) {
- return decorateImageDescriptor(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, proposal);
- }
-
- ImageDescriptor createPackageImageDescriptor(CompletionProposal proposal) {
- return decorateImageDescriptor(JavaPluginImages.DESC_OBJS_PACKAGE, proposal);
- }
-
- /**
- * Returns a version of <code>descriptor</code> decorated according to
- * the passed <code>modifier</code> flags.
- *
- * @param descriptor the image descriptor to decorate
- * @param proposal the proposal
- * @return an image descriptor for a method proposal
- * @see Flags
- */
- private ImageDescriptor decorateImageDescriptor(ImageDescriptor descriptor, CompletionProposal proposal) {
- int adornments= 0;
- int flags= proposal.getFlags();
- int kind= proposal.getKind();
-
- if (Flags.isDeprecated(flags))
- adornments |= JavaScriptElementImageDescriptor.DEPRECATED;
-
- if (kind == CompletionProposal.FIELD_REF || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE || kind == CompletionProposal.METHOD_REF)
- if (Flags.isStatic(flags))
- adornments |= JavaScriptElementImageDescriptor.STATIC;
-
- if (kind == CompletionProposal.TYPE_REF && Flags.isAbstract(flags))
- adornments |= JavaScriptElementImageDescriptor.ABSTRACT;
-
- return new JavaScriptElementImageDescriptor(descriptor, adornments, JavaElementImageProvider.SMALL_SIZE);
- }
-
- /**
- * Sets the completion context.
- *
- * @param context the completion context
- *
- */
- void setContext(CompletionContext context) {
- fContext= context;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/ContentAssistInvocationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/ContentAssistInvocationContext.java
deleted file mode 100644
index 6cc99527..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/ContentAssistInvocationContext.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-
-/**
- * Describes the context of an invocation of content assist in a text viewer. The context knows the
- * document, the invocation offset and can lazily compute the identifier prefix preceding the
- * invocation offset. It may know the viewer.
- * <p>
- * Subclasses may add information to their environment. For example, source code editors may provide
- * specific context information such as an AST.
- * </p>
- * <p>
- * Clients may instantiate and subclass.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class ContentAssistInvocationContext {
-
- /* state */
- private final ITextViewer fViewer;
- private final IDocument fDocument;
- private final int fOffset;
-
- /* cached additional info */
- private CharSequence fPrefix;
-
- /**
- * Equivalent to
- * {@linkplain #ContentAssistInvocationContext(ITextViewer, int) ContentAssistInvocationContext(viewer, viewer.getSelectedRange().x)}.
- *
- * @param viewer the text viewer that content assist is invoked in
- */
- public ContentAssistInvocationContext(ITextViewer viewer) {
- this(viewer, viewer.getSelectedRange().x);
- }
-
- /**
- * Creates a new context for the given viewer and offset.
- *
- * @param viewer the text viewer that content assist is invoked in
- * @param offset the offset into the viewer's document where content assist is invoked at
- */
- public ContentAssistInvocationContext(ITextViewer viewer, int offset) {
- Assert.isNotNull(viewer);
- fViewer= viewer;
- fDocument= null;
- fOffset= offset;
- }
-
- /**
- * Creates a new context with no viewer or invocation offset set.
- */
- protected ContentAssistInvocationContext() {
- fDocument= null;
- fViewer= null;
- fOffset= -1;
- }
-
- /**
- * Creates a new context for the given document and offset.
- *
- * @param document the document that content assist is invoked in
- * @param offset the offset into the document where content assist is invoked at
- */
- public ContentAssistInvocationContext(IDocument document, int offset) {
- Assert.isNotNull(document);
- Assert.isTrue(offset >= 0);
- fViewer= null;
- fDocument= document;
- fOffset= offset;
- }
-
- /**
- * Returns the invocation offset.
- *
- * @return the invocation offset
- */
- public final int getInvocationOffset() {
- return fOffset;
- }
-
- /**
- * Returns the viewer, <code>null</code> if not available.
- *
- * @return the viewer, possibly <code>null</code>
- */
- public final ITextViewer getViewer() {
- return fViewer;
- }
-
- /**
- * Returns the document that content assist is invoked on, or <code>null</code> if not known.
- *
- * @return the document or <code>null</code>
- */
- public IDocument getDocument() {
- if (fDocument == null) {
- if (fViewer == null)
- return null;
- return fViewer.getDocument();
- }
- return fDocument;
- }
-
- /**
- * Computes the identifier (as specified by {@link Character#isJavaIdentifierPart(char)}) that
- * immediately precedes the invocation offset.
- *
- * @return the prefix preceding the content assist invocation offset, <code>null</code> if
- * there is no document
- * @throws BadLocationException if accessing the document fails
- */
- public CharSequence computeIdentifierPrefix() throws BadLocationException {
- if (fPrefix == null) {
- IDocument document= getDocument();
- if (document == null)
- return null;
- int end= getInvocationOffset();
- int start= end;
- while (--start >= 0) {
- if (!Character.isJavaIdentifierPart(document.getChar(start)))
- break;
- }
- start++;
- fPrefix= document.get(start, end - start);
- }
-
- return fPrefix;
- }
-
- /**
- * Invocation contexts are equal if they describe the same context and are of the same type.
- * This implementation checks for <code>null</code> values and class equality. Subclasses
- * should extend this method by adding checks for their context relevant fields (but not
- * necessarily cached values).
- * <p>
- * Example:
- *
- * <pre>
- * class MyContext extends ContentAssistInvocationContext {
- * private final Object fState;
- * private Object fCachedInfo;
- *
- * ...
- *
- * public boolean equals(Object obj) {
- * if (!super.equals(obj))
- * return false;
- * MyContext other= (MyContext) obj;
- * return fState.equals(other.fState);
- * }
- * }
- * </pre>
- *
- * </p>
- * <p>
- * Subclasses should also extend {@link Object#hashCode()}.
- * </p>
- *
- * @param obj {@inheritDoc}
- * @return {@inheritDoc}
- */
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
- if (!getClass().equals(obj.getClass()))
- return false;
- ContentAssistInvocationContext other= (ContentAssistInvocationContext) obj;
- return (fViewer == null && other.fViewer == null || fViewer != null && fViewer.equals(other.fViewer)) && fOffset == other.fOffset && (fDocument == null && other.fDocument == null || fDocument != null && fDocument.equals(other.fDocument));
- }
-
- /*
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- return 23459213 << 5 | (fViewer == null ? 0 : fViewer.hashCode() << 3) | fOffset;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IInvocationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IInvocationContext.java
deleted file mode 100644
index 721b73cd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IInvocationContext.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-/**
- * Context information for quick fix and quick assist processors.
- * <p>
- * Note: this interface is not intended to be implemented.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IInvocationContext {
-
- /**
- * @return Returns the current compilation unit.
- */
- IJavaScriptUnit getCompilationUnit();
-
- /**
- * @return Returns the offset of the current selection
- */
- int getSelectionOffset();
-
- /**
- * @return Returns the length of the current selection
- */
- int getSelectionLength();
-
- /**
- * Returns an AST of the compilation unit, possibly only a partial AST focused on the selection
- * offset (see {@link org.eclipse.wst.jsdt.core.dom.ASTParser#setFocalPosition(int)}).
- * The returned AST is shared and therefore protected and cannot be modified.
- * The client must check the AST API level and do nothing if they are given an AST
- * they can't handle. (see {@link org.eclipse.wst.jsdt.core.dom.AST#apiLevel()}).
- * @return Returns the root of the AST corresponding to the current compilation unit.
- */
- JavaScriptUnit getASTRoot();
-
- /**
- * Convenience method to evaluate the AST node covering the current selection.
- * @return Returns the node that covers the location of the problem
- */
- ASTNode getCoveringNode();
-
- /**
- * Convenience method to evaluate the AST node that is covered by the current selection.
- * @return Returns the node that is covered by the location of the problem
- */
- ASTNode getCoveredNode();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposal.java
deleted file mode 100644
index 1fa5c67a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposal.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-
-/**
- * A completion proposal with a relevance value.
- * The relevance value is used to sort the completion proposals. Proposals with higher relevance
- * should be listed before proposals with lower relevance.
- * <p>
- * This interface can be implemented by clients.
- * </p>
- *
- * @see org.eclipse.jface.text.contentassist.ICompletionProposal
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaCompletionProposal extends ICompletionProposal {
-
- /**
- * Returns the relevance of this completion proposal.
- * <p>
- * The relevance is used to determine if this proposal is more
- * relevant than another proposal.</p>
- *
- * @return the relevance of this completion proposal in the range of [0, 100]
- */
- int getRelevance();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java
deleted file mode 100644
index 9690695f..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * Computes completions and context information displayed by the JavaScript editor content assistant.
- * Contributions to the <tt>org.eclipse.wst.jsdt.ui.javaCompletionProposalComputer</tt> extension point
- * must implement this interface.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaCompletionProposalComputer {
- /**
- * Informs the computer that a content assist session has started. This call will always be
- * followed by a {@link #sessionEnded()} call, but not necessarily by calls to
- * {@linkplain #computeCompletionProposals(ContentAssistInvocationContext, IProgressMonitor) computeCompletionProposals}
- * or
- * {@linkplain #computeContextInformation(ContentAssistInvocationContext, IProgressMonitor) computeContextInformation}.
- */
- void sessionStarted();
-
- /**
- * Returns a list of completion proposals valid at the given invocation context.
- *
- * @param context the context of the content assist invocation
- * @param monitor a progress monitor to report progress. The monitor is private to this
- * invocation, i.e. there is no need for the receiver to spawn a sub monitor.
- * @return a list of completion proposals (element type: {@link org.eclipse.jface.text.contentassist.ICompletionProposal})
- */
- List computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor);
-
- /**
- * Returns context information objects valid at the given invocation context.
- *
- * @param context the context of the content assist invocation
- * @param monitor a progress monitor to report progress. The monitor is private to this
- * invocation, i.e. there is no need for the receiver to spawn a sub monitor.
- * @return a list of context information objects (element type: {@link org.eclipse.jface.text.contentassist.IContextInformation})
- */
- List computeContextInformation(ContentAssistInvocationContext context, IProgressMonitor monitor);
-
- /**
- * Returns the reason why this computer was unable to produce any completion proposals or
- * context information.
- *
- * @return an error message or <code>null</code> if no error occurred
- */
- String getErrorMessage();
-
- /**
- * Informs the computer that a content assist session has ended. This call will always be after
- * any calls to
- * {@linkplain #computeCompletionProposals(ContentAssistInvocationContext, IProgressMonitor) computeCompletionProposals}
- * and
- * {@linkplain #computeContextInformation(ContentAssistInvocationContext, IProgressMonitor) computeContextInformation}.
- */
- void sessionEnded();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavadocCompletionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavadocCompletionProcessor.java
deleted file mode 100644
index e22bcb2b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavadocCompletionProcessor.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-/**
- * A Javadoc processor proposes completions and computes
- * context information for a particular content type.
- * <p>
- * This interface must be implemented by clients who extend the
- * <code>org.eclipse.wst.jsdt.ui.javadocCompletionProcessor</code> extension-point</p>.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavadocCompletionProcessor {
-
- /**
- * Flag used by <code>computeCompletionProposals</code>.
- * Specifies that only proposals should be returned that match
- * the case of the prefix in the code (value: <code>1</code>).
- */
- int RESTRICT_TO_MATCHING_CASE= 1;
-
-
- /**
- * Returns information about possible contexts based on the
- * specified location within the compilation unit.
- *
- * @param cu the working copy of the compilation unit which
- * is used to compute the possible contexts
- * @param offset an offset within the compilation unit for
- * which context information should be computed
- * @return an array of context information objects or <code>null</code>
- * if no context could be found
- */
- IContextInformation[] computeContextInformation(IJavaScriptUnit cu, int offset);
-
-
- /**
- * Returns the completion proposals based on the specified location
- * within the compilation unit.
- *
- * @param cu the working copy of the compilation unit in which the
- * completion request has been called.
- * @param offset an offset within the compilation unit for which
- * completion proposals should be computed
- * @param length the length of the current selection.
- * @param flags settings for the code assist. Flags as defined in this interface,
- * e.g. <code>RESTRICT_TO_MATCHING_CASE</code>.
- * @return an array of completion proposals or <code>null</code> if
- * no proposals could be found
- */
- IJavaCompletionProposal[] computeCompletionProposals(IJavaScriptUnit cu, int offset, int length, int flags);
-
-
- /**
- * Returns the reason why this completion processor was unable
- * to produce a completion proposals or context information.
- *
- * @return an error message or <code>null</code> if no error occurred
- */
- String getErrorMessage();
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IProblemLocation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IProblemLocation.java
deleted file mode 100644
index 351d31a1..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IProblemLocation.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-
-
-/**
- * Problem information for quick fix and quick assist processors.
- * <p>
- * Note: this interface is not intended to be implemented.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IProblemLocation {
-
- /**
- * Returns the start offset of the problem.
- *
- * @return the start offset of the problem
- */
- int getOffset();
-
- /**
- * Returns the length of the problem.
- *
- * @return the length of the problem
- */
- int getLength();
-
- /**
- * Returns the marker type of this problem.
- *
- * @return The marker type of the problem.
- *
- */
- String getMarkerType();
-
- /**
- * Returns the id of problem. Note that problem ids are defined per problem marker type.
- * See {@link org.eclipse.wst.jsdt.core.compiler.IProblem} for id definitions for problems of type
- * <code>org.eclipse.wst.jsdt.core.problem</code> and <code>org.eclipse.wst.jsdt.core.task</code>.
- *
- * @return The id of the problem.
- */
- int getProblemId();
-
- /**
- * Returns the original arguments recorded into the problem.
- *
- * @return String[] Returns the problem arguments.
- */
- String[] getProblemArguments();
-
- /**
- * Returns if the problem has error severity.
- *
- * @return <code>true</code> if the problem has error severity
- */
- boolean isError();
-
- /**
- * Convenience method to evaluate the AST node covering this problem.
- *
- * @param astRoot The root node of the current AST
- * @return Returns the node that covers the location of the problem
- */
- ASTNode getCoveringNode(JavaScriptUnit astRoot);
-
- /**
- * Convenience method to evaluate the AST node covered by this problem.
- *
- * @param astRoot The root node of the current AST
- * @return Returns the node that is covered by the location of the problem
- */
- ASTNode getCoveredNode(JavaScriptUnit astRoot);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickAssistProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickAssistProcessor.java
deleted file mode 100644
index 2087708a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickAssistProcessor.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.core.runtime.CoreException;
-
-
-/**
- * Interface to be implemented by contributors to the extension point
- * <code>org.eclipse.wst.jsdt.ui.quickAssistProcessors</code>.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IQuickAssistProcessor {
-
- /**
- * Evaluates if quick assists can be created for the given context. This evaluation must be precise.
- *
- * @param context The invocation context
- * @return Returns <code>true</code> if quick assists can be created
- * @throws CoreException CoreException can be thrown if the operation fails
- */
- boolean hasAssists(IInvocationContext context) throws CoreException;
-
- /**
- * Collects quick assists for the given context.
- *
- * @param context Defines current compilation unit, position and a shared AST
- * @param locations The locations of problems at the invocation offset. The processor can decide to only
- * add assists when there are no errors at the selection offset.
- * @return Returns the assists applicable at the location or <code>null</code> if no proposals
- * can be offered.
- * @throws CoreException CoreException can be thrown if the operation fails
- */
- IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickFixProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickFixProcessor.java
deleted file mode 100644
index 90394f9a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IQuickFixProcessor.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-
-
-/**
- * Interface to be implemented by contributors to the extension point
- * <code>org.eclipse.wst.jsdt.ui.quickFixProcessors</code>.
- * <p>Since 3.2, each extension specifies the marker types it can handle, and {@link #hasCorrections(IJavaScriptUnit, int)} and
- * {@link #getCorrections(IInvocationContext, IProblemLocation[])} are called if (and only if) quick fix is
- * required for a problem of these types.</p>
- * <p>Note, if a extension does not specify marker types it will be only called for problem of type
- * <code>org.eclipse.wst.jsdt.core.problem</code>, <code>org.eclipse.wst.jsdt.core.buildpath_problem</code>
- * and <code>org.eclipse.wst.jsdt.core.task</code>; compatible with the behavior prior to 3.2</p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IQuickFixProcessor {
-
- /**
- * Returns <code>true</code> if the processor has proposals for the given problem. This test should be an
- * optimistic guess and be very cheap.
- *
- * @param unit the compilation unit
- * @param problemId the problem Id. The id is of a problem of the problem type(s) this processor specified in
- * the extension point.
- * @return <code>true</code> if the processor has proposals for the given problem
- */
- boolean hasCorrections(IJavaScriptUnit unit, int problemId);
-
- /**
- * Collects corrections or code manipulations for the given context.
- *
- * @param context Defines current compilation unit, position and a shared AST
- * @param locations Problems are the current location.
- * @return the corrections applicable at the location or <code>null</code> if no proposals
- * can be offered
- * @throws CoreException CoreException can be thrown if the operation fails
- */
- IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException;
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaContentAssistInvocationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaContentAssistInvocationContext.java
deleted file mode 100644
index 6110effd..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaContentAssistInvocationContext.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.jsdt.core.CompletionContext;
-import org.eclipse.wst.jsdt.core.CompletionProposal;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.wst.jsdt.internal.ui.text.java.ContentAssistHistory.RHSHistory;
-
-/**
- * Describes the context of a content assist invocation in a JavaScript editor.
- * <p>
- * Clients may use but not subclass this class.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class JavaContentAssistInvocationContext extends ContentAssistInvocationContext {
- private final IEditorPart fEditor;
-
- private IJavaScriptUnit fCU= null;
- private boolean fCUComputed= false;
-
- private CompletionProposalLabelProvider fLabelProvider;
- private CompletionProposalCollector fCollector;
- private RHSHistory fRHSHistory;
- private IType fType;
-
- private IJavaCompletionProposal[] fKeywordProposals= null;
- private CompletionContext fCoreContext= null;
-
- /**
- * Creates a new context.
- *
- * @param viewer the viewer used by the editor
- * @param offset the invocation offset
- * @param editor the editor that content assist is invoked in
- */
- public JavaContentAssistInvocationContext(ITextViewer viewer, int offset, IEditorPart editor) {
- super(viewer, offset);
-
- fEditor= editor;
- }
-
- /**
- * Creates a new context.
- *
- * @param unit the compilation unit in <code>document</code>
- */
- public JavaContentAssistInvocationContext(IJavaScriptUnit unit) {
- super();
- fCU= unit;
- fCUComputed= true;
- fEditor= null;
- }
-
- /**
- * Returns the compilation unit that content assist is invoked in, <code>null</code> if there
- * is none.
- *
- * @return the compilation unit that content assist is invoked in, possibly <code>null</code>
- */
- public IJavaScriptUnit getCompilationUnit() {
- if (!fCUComputed) {
- fCUComputed= true;
- if (fCollector != null)
- fCU= fCollector.getCompilationUnit();
- else {
- IJavaScriptElement je= EditorUtility.getEditorInputJavaElement(fEditor, false);
- if (je instanceof IJavaScriptUnit)
- fCU= (IJavaScriptUnit)je;
- }
- }
- return fCU;
- }
-
- /**
- * Returns the project of the compilation unit that content assist is invoked in,
- * <code>null</code> if none.
- *
- * @return the current JavaScript project, possibly <code>null</code>
- */
- public IJavaScriptProject getProject() {
- IJavaScriptUnit unit= getCompilationUnit();
- return unit == null ? null : unit.getJavaScriptProject();
- }
-
- /**
- * Returns the keyword proposals that are available in this context, possibly none.
- * <p>
- * <strong>Note:</strong> This method may run
- * {@linkplain org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) codeComplete}
- * on the compilation unit.
- * </p>
- *
- * @return the available keyword proposals
- */
- public IJavaCompletionProposal[] getKeywordProposals() {
- if (fKeywordProposals == null) {
- if (fCollector != null && !fCollector.isIgnored(CompletionProposal.KEYWORD) && fCollector.getContext() != null) {
- // use the existing collector if it exists, collects keywords, and has already been invoked
- fKeywordProposals= fCollector.getKeywordCompletionProposals();
- } else {
- // otherwise, retrieve keywords ourselves
- computeKeywordsAndContext();
- }
- }
-
- return fKeywordProposals;
- }
-
- /**
- * Returns the {@link CompletionContext core completion context} if available, <code>null</code>
- * otherwise.
- * <p>
- * <strong>Note:</strong> This method may run
- * {@linkplain org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) codeComplete}
- * on the compilation unit.
- * </p>
- *
- * @return the core completion context if available, <code>null</code> otherwise
- */
- public CompletionContext getCoreContext() {
- if (fCoreContext == null) {
- // use the context from the existing collector if it exists, retrieve one ourselves otherwise
- if (fCollector != null)
- fCoreContext= fCollector.getContext();
- if (fCoreContext == null)
- computeKeywordsAndContext();
- }
- return fCoreContext;
- }
-
- /**
- * Returns an float in [0.0,&nbsp;1.0] based on whether the type has been recently used as a
- * right hand side for the type expected in the current context. 0 signals that the
- * <code>qualifiedTypeName</code> does not match the expected type, while 1.0 signals that
- * <code>qualifiedTypeName</code> has most recently been used in a similar context.
- * <p>
- * <strong>Note:</strong> This method may run
- * {@linkplain org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) codeComplete}
- * on the compilation unit.
- * </p>
- *
- * @param qualifiedTypeName the type name of the type of interest
- * @return a relevance in [0.0,&nbsp;1.0] based on previous content assist invocations
- */
- public float getHistoryRelevance(String qualifiedTypeName) {
- return getRHSHistory().getRank(qualifiedTypeName);
- }
-
- /**
- * Returns the content assist type history for the expected type.
- *
- * @return the content assist type history for the expected type
- */
- private RHSHistory getRHSHistory() {
- if (fRHSHistory == null) {
- CompletionContext context= getCoreContext();
- if (context != null) {
- char[][] expectedTypes= context.getExpectedTypesSignatures();
- if (expectedTypes != null && expectedTypes.length > 0) {
- String expected= SignatureUtil.stripSignatureToFQN(String.valueOf(expectedTypes[0]));
- fRHSHistory= JavaScriptPlugin.getDefault().getContentAssistHistory().getHistory(expected);
- }
- }
- if (fRHSHistory == null)
- fRHSHistory= JavaScriptPlugin.getDefault().getContentAssistHistory().getHistory(null);
- }
- return fRHSHistory;
- }
-
- /**
- * Returns the expected type if any, <code>null</code> otherwise.
- * <p>
- * <strong>Note:</strong> This method may run
- * {@linkplain org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) codeComplete}
- * on the compilation unit.
- * </p>
- *
- * @return the expected type if any, <code>null</code> otherwise
- */
- public IType getExpectedType() {
- if (fType == null && getCompilationUnit() != null) {
- CompletionContext context= getCoreContext();
- if (context != null) {
- char[][] expectedTypes= context.getExpectedTypesSignatures();
- if (expectedTypes != null && expectedTypes.length > 0) {
- IJavaScriptProject project= getCompilationUnit().getJavaScriptProject();
- if (project != null) {
- try {
- fType= project.findType(SignatureUtil.stripSignatureToFQN(String.valueOf(expectedTypes[0])));
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x);
- }
- }
- }
- }
- }
- return fType;
- }
-
- /**
- * Returns a label provider that can be used to compute proposal labels.
- *
- * @return a label provider that can be used to compute proposal labels
- */
- public CompletionProposalLabelProvider getLabelProvider() {
- if (fLabelProvider == null) {
- if (fCollector != null)
- fLabelProvider= fCollector.getLabelProvider();
- else
- fLabelProvider= new CompletionProposalLabelProvider();
- }
-
- return fLabelProvider;
- }
-
- /**
- * Sets the collector, which is used to access the compilation unit, the core context and the
- * label provider. This is a performance optimization: {@link IJavaCompletionProposalComputer}s
- * may instantiate a {@link CompletionProposalCollector} and set this invocation context via
- * {@link CompletionProposalCollector#setInvocationContext(JavaContentAssistInvocationContext)},
- * which in turn calls this method. This allows the invocation context to retrieve the core
- * context and keyword proposals from the existing collector, instead of computing theses values
- * itself via {@link #computeKeywordsAndContext()}.
- *
- * @param collector the collector
- */
- protected void setCollector(CompletionProposalCollector collector) {
- fCollector= collector;
- }
-
- /**
- * Fallback to retrieve a core context and keyword proposals when no collector is available.
- * Runs code completion on the cu and collects keyword proposals. {@link #fKeywordProposals} is
- * non-<code>null</code> after this call.
- *
- *
- */
- private void computeKeywordsAndContext() {
- IJavaScriptUnit cu= getCompilationUnit();
- if (cu == null) {
- if (fKeywordProposals == null)
- fKeywordProposals= new IJavaCompletionProposal[0];
- return;
- }
-
- CompletionProposalCollector collector= new CompletionProposalCollector(cu);
- collector.setIgnored(CompletionProposal.KEYWORD, false);
- collector.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
- collector.setIgnored(CompletionProposal.FIELD_REF, true);
- collector.setIgnored(CompletionProposal.LABEL_REF, true);
- collector.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
- collector.setIgnored(CompletionProposal.METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
- collector.setIgnored(CompletionProposal.METHOD_REF, true);
- collector.setIgnored(CompletionProposal.PACKAGE_REF, true);
- collector.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
- collector.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
- collector.setIgnored(CompletionProposal.JSDOC_BLOCK_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_FIELD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_INLINE_TAG, true);
- collector.setIgnored(CompletionProposal.JSDOC_METHOD_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_PARAM_REF, true);
- collector.setIgnored(CompletionProposal.JSDOC_TYPE_REF, true);
- collector.setIgnored(CompletionProposal.TYPE_REF, true);
-
- try {
- cu.codeComplete(getInvocationOffset(), collector);
- if (fCoreContext == null)
- fCoreContext= collector.getContext();
- if (fKeywordProposals == null)
- fKeywordProposals= collector.getKeywordCompletionProposals();
- if (fLabelProvider == null)
- fLabelProvider= collector.getLabelProvider();
- } catch (JavaScriptModelException x) {
- JavaScriptPlugin.log(x);
- if (fKeywordProposals == null)
- fKeywordProposals= new IJavaCompletionProposal[0];
- }
- }
-
- /*
- * Implementation note: There is no need to override hashCode and equals, as we only add cached
- * values shared across one assist invocation.
- */
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java
deleted file mode 100644
index 277d181b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Helper class to get NLSed messages.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-final class JavaTextMessages extends NLS {
-
- private static final String BUNDLE_NAME= JavaTextMessages.class.getName();
-
- private JavaTextMessages() {
- // Do not instantiate
- }
-
- public static String ResultCollector_anonymous_type;
- public static String ResultCollector_overridingmethod;
-
- static {
- NLS.initializeMessages(BUNDLE_NAME, JavaTextMessages.class);
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties
deleted file mode 100644
index a039bc28..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-###############################################################################
-# Copyright (c) 2000, 2007 IBM Corporation and others.
-# 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:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-ResultCollector_anonymous_type=Anonymous Inner Type
-ResultCollector_overridingmethod=Override function in ''{0}''
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/hover/IJavaEditorTextHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/hover/IJavaEditorTextHover.java
deleted file mode 100644
index ee524f4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/hover/IJavaEditorTextHover.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.text.java.hover;
-
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.ui.IEditorPart;
-
-
-/**
- * Provides a hover popup which appears on top of an editor with relevant
- * display information. If the text hover does not provide information no
- * hover popup is shown.
- * <p>
- * Clients may implement this interface.
- * </p>
- *
- * @see org.eclipse.ui.IEditorPart
- * @see org.eclipse.jface.text.ITextHover
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJavaEditorTextHover extends ITextHover {
-
- /**
- * Sets the editor on which the hover is shown.
- *
- * @param editor the editor on which the hover popup should be shown
- */
- void setEditor(IEditorPart editor);
-
-}
-
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java
deleted file mode 100644
index d7ffc069..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-
-/**
- * Wizard page for adding base library support to the project.
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class BaseLibraryWizardPage extends NewElementWizardPage implements IJsGlobalScopeContainerPage, IJsGlobalScopeContainerPageExtension, IJsGlobalScopeContainerPageExtension2 {
-
- private static final String CONTAINER_ID="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"; //$NON-NLS-1$
-
- public BaseLibraryWizardPage() {
- super("BaseicLibraryWizzardPage"); //$NON-NLS-1$
- setTitle(NewWizardMessages.BaseLibraryWizardPage_title);
- setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY);
- }
-
- public boolean finish() {
- return true;
- }
-
- public IIncludePathEntry getSelection() {
- System.out.println("Unimplemented method:BaseLibraryWizardPage.getSelection"); //$NON-NLS-1$
- return null;
- }
-
- public void setSelection(IIncludePathEntry containerEntry) {}
-
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- DialogField field = new DialogField();
-
- field.setLabelText(NewWizardMessages.BaseLibraryWizardPage_DefaultBrowserLibraryAdded);
- LayoutUtil.doDefaultLayout(composite, new DialogField[] {field }, false, SWT.DEFAULT, SWT.DEFAULT);
- Dialog.applyDialogFont(composite);
- setControl(composite);
- setDescription(NewWizardMessages.BaseLibraryWizardPage_WebBrowserSupport);
- }
-
- public void initialize(IJavaScriptProject project, IIncludePathEntry[] currentEntries) {
- // nothing to initialize
- }
-
- public IIncludePathEntry[] getNewContainers() {
- IIncludePathEntry library = JavaScriptCore.newContainerEntry( new Path(CONTAINER_ID));
- return new IIncludePathEntry[] {library};
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java
deleted file mode 100644
index cb74eb4a..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java
+++ /dev/null
@@ -1,601 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import java.net.URL;
-import java.util.ArrayList;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-import org.eclipse.ui.views.navigator.ResourceComparator;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.LibrarySuperType;
-import org.eclipse.wst.jsdt.internal.ui.IUIConstants;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.ArchiveFileFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.CPListElement;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.JavadocLocationDialog;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.JsGlobalScopeContainerWizard;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.MultipleFolderSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.SourceAttachmentDialog;
-import org.eclipse.wst.jsdt.ui.JavaScriptUI;
-
-/**
- * Class that gives access to dialogs used by the JavaScript build path page to configure classpath entries
- * and properties of classpath entries.
- * Static methods are provided to show dialogs for:
- * <ul>
- * <li> configuration of source attachments</li>
- * <li> configuration of Javadoc locations</li>
- * <li> configuration and selection of classpath variable entries</li>
- * <li> configuration and selection of classpath container entries</li>
- * <li> configuration and selection of JAR and external JAR entries</li>
- * <li> selection of class and source folders</li>
- * </ul>
- * <p>
- * This class is not intended to be instantiated or subclassed by clients.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public final class BuildPathDialogAccess {
-
- private BuildPathDialogAccess() {
- // do not instantiate
- }
-
- /**
- * Shows the UI for configuring source attachments. <code>null</code> is returned
- * if the user cancels the dialog. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog
- * @param initialEntry The entry to edit. The kind of the classpath entry must be either
- * <code>IIncludePathEntry.CPE_LIBRARY</code> or <code>IIncludePathEntry.CPE_VARIABLE</code>.
- * @return Returns the resulting classpath entry containing a potentially modified source attachment path and
- * source attachment root. The resulting entry can be used to replace the original entry on the classpath.
- * Note that the dialog does not make any changes on the passed entry nor on the classpath that
- * contains it.
- */
- public static IIncludePathEntry configureSourceAttachment(Shell shell, IIncludePathEntry initialEntry) {
- if (initialEntry == null) {
- throw new IllegalArgumentException();
- }
- int entryKind= initialEntry.getEntryKind();
- if (entryKind != IIncludePathEntry.CPE_LIBRARY && entryKind != IIncludePathEntry.CPE_VARIABLE) {
- throw new IllegalArgumentException();
- }
-
- SourceAttachmentDialog dialog= new SourceAttachmentDialog(shell, initialEntry);
- if (dialog.open() == Window.OK) {
- return dialog.getResult();
- }
- return null;
- }
-
- /**
- * Shows the UI for configuring a javadoc location. <code>null</code> is returned
- * if the user cancels the dialog. If OK is pressed, an array of length 1 containing the configured URL is
- * returned. Note that the configured URL can be <code>null</code> when the user
- * wishes to have no URL location specified. The dialog does not apply any changes.
- * Use {@link org.eclipse.wst.jsdt.ui.JavaScriptUI} to access and configure
- * Javadoc locations.
- *
- * @param shell The parent shell for the dialog.
- * @param libraryName Name of of the library to which configured javadoc location belongs.
- * @param initialURL The initial URL or <code>null</code>.
- * @return Returns an array of size 1 that contains the resulting javadoc location or
- * <code>null</code> if the dialog has been canceled. Note that the configured URL can be <code>null</code> when the user
- * wishes to have no URL location specified.
- */
- public static URL[] configureJavadocLocation(Shell shell, String libraryName, URL initialURL) {
- if (libraryName == null) {
- throw new IllegalArgumentException();
- }
-
- JavadocLocationDialog dialog= new JavadocLocationDialog(shell, libraryName, initialURL);
- if (dialog.open() == Window.OK) {
- return new URL[] { dialog.getResult() };
- }
- return null;
- }
-
- /**
- * Shows the UI for configuring a javadoc location attribute of the classpath entry. <code>null</code> is returned
- * if the user cancels the dialog. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialEntry The entry to edit. The kind of the classpath entry must be either
- * <code>IIncludePathEntry.CPE_LIBRARY</code> or <code>IIncludePathEntry.CPE_VARIABLE</code>.
- * @return Returns the resulting classpath entry containing a potentially modified javadoc location attribute
- * The resulting entry can be used to replace the original entry on the classpath.
- * Note that the dialog does not make any changes on the passed entry nor on the classpath that
- * contains it.
- *
- *
- */
- public static IIncludePathEntry configureJavadocLocation(Shell shell, IIncludePathEntry initialEntry) {
- if (initialEntry == null) {
- throw new IllegalArgumentException();
- }
- int entryKind= initialEntry.getEntryKind();
- if (entryKind != IIncludePathEntry.CPE_LIBRARY && entryKind != IIncludePathEntry.CPE_VARIABLE) {
- throw new IllegalArgumentException();
- }
-
- URL location= JavaScriptUI.getLibraryJSdocLocation(initialEntry);
- JavadocLocationDialog dialog= new JavadocLocationDialog(shell, initialEntry.getPath().toString(), location);
- if (dialog.open() == Window.OK) {
- CPListElement element= CPListElement.createFromExisting(initialEntry, null);
- URL res= dialog.getResult();
- element.setAttribute(CPListElement.JAVADOC, res != null ? res.toExternalForm() : null);
- return element.getClasspathEntry();
- }
- return null;
- }
-
- /**
- * Shows the UI to configure a classpath container classpath entry. See {@link IIncludePathEntry#CPE_CONTAINER} for
- * details about container classpath entries.
- * The dialog returns the configured classpath entry or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialEntry The initial classpath container entry.
- * @param project The project the entry belongs to. The project does not have to exist and can also be <code>null</code>.
- * @param currentClasspath The class path entries currently selected to be set as the projects classpath. This can also
- * include the entry to be edited. The dialog uses these entries as information only (e.g. to avoid duplicate entries); The user still can make changes after the
- * the classpath container dialog has been closed. See {@link IJsGlobalScopeContainerPageExtension} for
- * more information.
- * @return Returns the configured classpath container entry or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IIncludePathEntry configureContainerEntry(Shell shell, IIncludePathEntry initialEntry, IJavaScriptProject project, IIncludePathEntry[] currentClasspath) {
- if (initialEntry == null || currentClasspath == null) {
- throw new IllegalArgumentException();
- }
-
- JsGlobalScopeContainerWizard wizard= new JsGlobalScopeContainerWizard(initialEntry, project, currentClasspath);
- if (JsGlobalScopeContainerWizard.openWizard(shell, wizard) == Window.OK) {
- IIncludePathEntry[] created= wizard.getNewEntries();
- if (created != null && created.length == 1) {
- return created[0];
- }
- }
- return null;
- }
-
- /**
- * Shows the UI to choose new classpath container classpath entries. See {@link IIncludePathEntry#CPE_CONTAINER} for
- * details about container classpath entries.
- * The dialog returns the selected classpath entries or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param project The project the entry belongs to. The project does not have to exist and
- * can also be <code>null</code>.
- * @param currentClasspath The class path entries currently selected to be set as the projects classpath. This can also
- * include the entry to be edited. The dialog uses these entries as information only; The user still can make changes after the
- * the classpath container dialog has been closed. See {@link IJsGlobalScopeContainerPageExtension} for
- * more information.
- * @return Returns the selected classpath container entries or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IIncludePathEntry[] chooseContainerEntries(Shell shell, IJavaScriptProject project, IIncludePathEntry[] currentClasspath) {
- if (currentClasspath == null) {
- throw new IllegalArgumentException();
- }
-
- JsGlobalScopeContainerWizard wizard= new JsGlobalScopeContainerWizard((IIncludePathEntry) null, project, currentClasspath);
- if (JsGlobalScopeContainerWizard.openWizard(shell, wizard) == Window.OK) {
- return wizard.getNewEntries();
- }
- return null;
- }
-
-
- /**
- * Shows the UI to configure a JAR or ZIP archive located in the workspace.
- * The dialog returns the configured classpath entry path or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialEntry The path of the initial archive entry
- * @param usedEntries An array of paths that are already on the classpath and therefore should not be
- * selected again.
- * @return Returns the configured classpath container entry path or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath configureJAREntry(Shell shell, IPath initialEntry, IPath[] usedEntries) {
- if (initialEntry == null || usedEntries == null) {
- throw new IllegalArgumentException();
- }
-
- Class[] acceptedClasses= new Class[] { IFile.class };
- TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
-
- ArrayList usedJars= new ArrayList(usedEntries.length);
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int i= 0; i < usedEntries.length; i++) {
- IPath curr= usedEntries[i];
- if (!curr.equals(initialEntry)) {
- IResource resource= root.findMember(usedEntries[i]);
- if (resource instanceof IFile) {
- usedJars.add(resource);
- }
- }
- }
-
- IResource existing= root.findMember(initialEntry);
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(shell, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setValidator(validator);
- dialog.setTitle(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_edit_title);
- dialog.setMessage(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_edit_description);
- dialog.addFilter(new ArchiveFileFilter(usedJars, true));
- dialog.setInput(root);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- dialog.setInitialSelection(existing);
-
- if (dialog.open() == Window.OK) {
- IResource element= (IResource) dialog.getFirstResult();
- return element.getFullPath();
- }
- return null;
- }
-
- /**
- * Shows the UI to select new JAR or ZIP archive entries located in the workspace.
- * The dialog returns the selected entries or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialSelection The path of the element (container or archive) to initially select or <code>null</code> to not select an entry.
- * @param usedEntries An array of paths that are already on the classpath and therefore should not be
- * selected again.
- * @return Returns the new classpath container entry paths or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath[] chooseJAREntries(Shell shell, IPath initialSelection, IPath[] usedEntries) {
- if (usedEntries == null) {
- throw new IllegalArgumentException();
- }
-
- Class[] acceptedClasses= new Class[] { IFile.class };
- TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
- ArrayList usedJars= new ArrayList(usedEntries.length);
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int i= 0; i < usedEntries.length; i++) {
- IResource resource= root.findMember(usedEntries[i]);
- if (resource instanceof IFile) {
- usedJars.add(resource);
- }
- }
- IResource focus= initialSelection != null ? root.findMember(initialSelection) : null;
-
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(shell, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setHelpAvailable(false);
- dialog.setValidator(validator);
- dialog.setTitle(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_new_title);
- dialog.setMessage(NewWizardMessages.BuildPathDialogAccess_JARArchiveDialog_new_description);
- dialog.addFilter(new ArchiveFileFilter(usedJars, true));
- dialog.setInput(root);
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- dialog.setInitialSelection(focus);
-
- if (dialog.open() == Window.OK) {
- Object[] elements= dialog.getResult();
- IPath[] res= new IPath[elements.length];
- for (int i= 0; i < res.length; i++) {
- IResource elem= (IResource)elements[i];
- res[i]= elem.getFullPath();
- }
- return res;
- }
- return null;
- }
-
-
-
-
- public static LibrarySuperType chooseSuperType(Shell shell, CPListElement[] cpEntries, LibrarySuperType initialSelection, IJavaScriptProject project) {
- if (cpEntries == null) {
- throw new IllegalArgumentException();
- }
-
-// Class[] acceptedClasses= new Class[] { IFile.class };
-// TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
-// ArrayList usedJars= new ArrayList(usedEntries.length);
-// IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
-// for (int i= 0; i < usedEntries.length; i++) {
-// IResource resource= root.findMember(usedEntries[i]);
-// if (resource instanceof IFile) {
-// usedJars.add(resource);
-// }
-// }
-// IResource focus= initialSelection != null ? root.findMember(initialSelection) : null;
- ArrayList allLibsSuper = new ArrayList();
-
- for(int i = 0;i<cpEntries.length;i++) {
- LibrarySuperType libSuperParent = new LibrarySuperType(cpEntries[i].getPath(), cpEntries[i].getJavaProject());
- if(libSuperParent.hasChildren()) {
- allLibsSuper.add(libSuperParent);
- }
- //allLibsSuper.addAll(Arrays.asList(libSupers));
- }
-
- boolean currentIsValid = initialSelection!=null && allLibsSuper.contains(initialSelection.getParent());
-
- LibrarySuperType[] libSupers = (LibrarySuperType[])allLibsSuper.toArray(new LibrarySuperType[allLibsSuper.size()]);
-
-
-
- class LibrarySuperTypeContentProvider implements ITreeContentProvider,
- ILabelProvider,
- ISelectionStatusValidator{
- public Object[] getChildren(Object parentElement) {
- if(parentElement==null) return null;
- return ((LibrarySuperType)parentElement).getChildren();
-
- }
- public Object getParent(Object element) {
- if(element==null) return null;
- return ((LibrarySuperType)element).getParent();
- }
-
- public boolean hasChildren(Object element) {
- if(element==null) return false;
- return ((LibrarySuperType)element).hasChildren();
- }
- public Object[] getElements(Object inputElement) {
- if(inputElement instanceof Object[]) return (Object[])inputElement;
- return new Object[] {inputElement} ;
- }
- public void dispose() {}
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
- public Image getImage(Object element) {
- return null;
-// if(element==null) return null;
-// return ((LibrarySuperType)element).toImage();
- }
-
- public String getText(Object element) {
- if(element==null) return null;
-
- String superTypeName = ((LibrarySuperType)element).getSuperTypeName();
- String libraryName = ((LibrarySuperType)element).getLibraryName();
- if(superTypeName!=null) return superTypeName;
- return libraryName;
- }
-
- public void addListener(ILabelProviderListener listener) {}
- public boolean isLabelProperty(Object element, String property) {return false;}
- public void removeListener(ILabelProviderListener listener) {}
-
- public IStatus validate(Object[] selection) {
- if(selection==null || selection.length!=1) {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, null, null);
- }else if( ! (selection[0] instanceof LibrarySuperType) ){
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR,null, null);
- }else if(((LibrarySuperType)selection[0]).isParent()) {
- return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, null, null);
- }
- return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
- }
-
- }
- LibrarySuperTypeContentProvider libValidator = new LibrarySuperTypeContentProvider();
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(shell,libValidator , libValidator);
- dialog.setAllowMultiple(false);
-
- dialog.setHelpAvailable(false);
- dialog.setInput(libSupers);
- dialog.setValidator(libValidator);
- dialog.setTitle(NewWizardMessages.BuildPathDialogAccess_SuperTypeSelection);
- dialog.setMessage(NewWizardMessages.BuildPathDialogAccess_SelectSupertType);
- //dialog.addFilter(new ArchiveFileFilter(usedJars, true));
- if(currentIsValid) dialog.setInitialSelection(initialSelection);
- // dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- //dialog.setInitialSelection(focus);
-
- if (dialog.open() == Window.OK) {
- Object[] elements= dialog.getResult();
- if(elements==null || elements.length==0 || !(elements[0] instanceof LibrarySuperType) ) return null;
- return (LibrarySuperType)elements[0];
-
-// IPath[] res= new IPath[elements.length];
-// for (int i= 0; i < res.length; i++) {
-// IResource elem= (IResource)elements[i];
-// res[i]= elem.getFullPath();
-// }
-// return res;
- }
- return null;
- }
-
-
-
-
-
- /**
- * Shows the UI to configure an external JAR or ZIP archive.
- * The dialog returns the configured or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialEntry The path of the initial archive entry.
- * @return Returns the configured classpath container entry path or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath configureExternalJAREntry(Shell shell, IPath initialEntry) {
- if (initialEntry == null) {
- throw new IllegalArgumentException();
- }
-
- String lastUsedPath= initialEntry.removeLastSegments(1).toOSString();
-
- FileDialog dialog= new FileDialog(shell, SWT.SINGLE);
- dialog.setText(NewWizardMessages.BuildPathDialogAccess_ExtJARArchiveDialog_edit_title);
- dialog.setFilterExtensions(ArchiveFileFilter.FILTER_EXTENSIONS);
- dialog.setFilterPath(lastUsedPath);
- dialog.setFileName(initialEntry.lastSegment());
-
- String res= dialog.open();
- if (res == null) {
- return null;
- }
- JavaScriptPlugin.getDefault().getDialogSettings().put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());
-
- return Path.fromOSString(res).makeAbsolute();
- }
-
- /**
- * Shows the UI to select new external JAR or ZIP archive entries.
- * The dialog returns the selected entry paths or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @return Returns the new classpath container entry paths or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath[] chooseExternalJAREntries(Shell shell) {
- String lastUsedPath= JavaScriptPlugin.getDefault().getDialogSettings().get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
- if (lastUsedPath == null) {
- lastUsedPath= ""; //$NON-NLS-1$
- }
- FileDialog dialog= new FileDialog(shell, SWT.MULTI);
- dialog.setText(NewWizardMessages.BuildPathDialogAccess_ExtJARArchiveDialog_new_title);
- dialog.setFilterExtensions(ArchiveFileFilter.FILTER_EXTENSIONS);
- dialog.setFilterPath(lastUsedPath);
-
- String res= dialog.open();
- if (res == null) {
- return null;
- }
- String[] fileNames= dialog.getFileNames();
- int nChosen= fileNames.length;
-
- IPath filterPath= Path.fromOSString(dialog.getFilterPath());
- IPath[] elems= new IPath[nChosen];
- for (int i= 0; i < nChosen; i++) {
- elems[i]= filterPath.append(fileNames[i]).makeAbsolute();
- }
- JavaScriptPlugin.getDefault().getDialogSettings().put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());
-
- return elems;
- }
-
- /**
- * Shows the UI to select new class folders.
- * The dialog returns the selected classpath entry paths or <code>null</code> if the dialog has
- * been canceled. The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialSelection The path of the element to initially select or <code>null</code>.
- * @param usedEntries An array of paths that are already on the classpath and therefore should not be
- * selected again.
- * @return Returns the configured classpath container entry path or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath[] chooseClassFolderEntries(Shell shell, IPath initialSelection, IPath[] usedEntries) {
- if (usedEntries == null) {
- throw new IllegalArgumentException();
- }
- String title= NewWizardMessages.BuildPathDialogAccess_ExistingClassFolderDialog_new_title;
- String message= NewWizardMessages.BuildPathDialogAccess_ExistingClassFolderDialog_new_description;
- return internalChooseFolderEntry(shell, initialSelection, usedEntries, title, message);
- }
-
- /**
- * Shows the UI to select new source folders.
- * The dialog returns the selected classpath entry paths or <code>null</code> if the dialog has
- * been canceled The dialog does not apply any changes.
- *
- * @param shell The parent shell for the dialog.
- * @param initialSelection The path of the element to initially select or <code>null</code>
- * @param usedEntries An array of paths that are already on the classpath and therefore should not be
- * selected again.
- * @return Returns the configured classpath container entry path or <code>null</code> if the dialog has
- * been canceled by the user.
- */
- public static IPath[] chooseSourceFolderEntries(Shell shell, IPath initialSelection, IPath[] usedEntries) {
- if (usedEntries == null) {
- throw new IllegalArgumentException();
- }
- String title= NewWizardMessages.BuildPathDialogAccess_ExistingSourceFolderDialog_new_title;
- String message= NewWizardMessages.BuildPathDialogAccess_ExistingSourceFolderDialog_new_description;
- return internalChooseFolderEntry(shell, initialSelection, usedEntries, title, message);
- }
-
-
- private static IPath[] internalChooseFolderEntry(Shell shell, IPath initialSelection, IPath[] usedEntries, String title, String message) {
- Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
-
- ArrayList usedContainers= new ArrayList(usedEntries.length);
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- for (int i= 0; i < usedEntries.length; i++) {
- IResource resource= root.findMember(usedEntries[i]);
- if (resource instanceof IContainer) {
- usedContainers.add(resource);
- }
- }
-
- IResource focus= initialSelection != null ? root.findMember(initialSelection) : null;
- Object[] used= usedContainers.toArray();
-
- MultipleFolderSelectionDialog dialog= new MultipleFolderSelectionDialog(shell, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setExisting(used);
- dialog.setTitle(title);
- dialog.setMessage(message);
- dialog.setHelpAvailable(false);
- dialog.addFilter(new TypedViewerFilter(acceptedClasses, used));
- dialog.setInput(root);
- dialog.setInitialFocus(focus);
-
- if (dialog.open() == Window.OK) {
- Object[] elements= dialog.getResult();
- IPath[] res= new IPath[elements.length];
- for (int i= 0; i < res.length; i++) {
- IResource elem= (IResource) elements[i];
- res[i]= elem.getFullPath();
- }
- return res;
- }
- return null;
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/ClasspathAttributeConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/ClasspathAttributeConfiguration.java
deleted file mode 100644
index 1673fa15..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/ClasspathAttributeConfiguration.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.jsdt.core.IIncludePathAttribute;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * A {@link ClasspathAttributeConfiguration} specifies how a {@link IIncludePathAttribute class path attribute} is presented and configured
- * in the JavaScript build path dialog.
- * <p>
- * Clients should implement this interface and include the name of their
- * class in an extension contributed to the jdt.ui's classpath attribute configuration
- * extension point (named <code>org.eclipse.wst.jsdt.ui.classpathAttributeConfiguration
- * </code>).
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class ClasspathAttributeConfiguration {
-
- /**
- * This class provides information about the attribute to be rendered or configured.
- */
- public static abstract class ClasspathAttributeAccess {
-
- /**
- * Returns the classpath attribute
- * @return the classpath attribute
- */
- public abstract IIncludePathAttribute getClasspathAttribute();
-
- /**
- * Returns the classpath entry the current attribute is part of
- * @return the parent classpath entry
- */
- public abstract IIncludePathEntry getParentClasspassEntry();
-
- /**
- * Returns the JavaScript project the current attribute is part of.
- * @return the parent JavaScript project
- */
- public abstract IJavaScriptProject getJavaProject();
-
- }
-
- /**
- * Returns the image descriptor of the classpath attributes name as a translated string.
- *
- * @param attribute access to the attributes to render
- * @return returns the label value of the value
- */
- public abstract ImageDescriptor getImageDescriptor(ClasspathAttributeAccess attribute);
-
-
- /**
- * Returns the label of the classpath attributes name as a translated string.
- *
- * @param attribute access to the attributes to render
- * @return returns the label value of the value
- */
- public abstract String getNameLabel(ClasspathAttributeAccess attribute);
-
-
- /**
- * Returns the label of the classpath attributes value as a translated string.
- *
- * @param attribute access to the attributes to render
- * @return returns the label value of the value
- */
- public abstract String getValueLabel(ClasspathAttributeAccess attribute);
-
- /**
- * Specifies if the given attribute can be edited. This will enable the <em>Edit</em> button that typically
- * shows the edit dialog.
- *
- * @param attribute access to the attribute to answer the question of
- * @return returns true if the attribute can be edited.
- */
- public abstract boolean canEdit(ClasspathAttributeAccess attribute);
-
- /**
- * Specifies if 'Remove' is a valid action on the given attribute. This will enable the <em>Remove</em> button. The action
- * will typically clear the attributes value. The method should only return <code>true</code> if the element isn't already cleared.
- *
- * @param attribute access to the attribute to answer the question of
- * @return returns true if the attribute can be edited.
- */
- public abstract boolean canRemove(ClasspathAttributeAccess attribute);
-
- /**
- * This method is invoked when the <em>Edit</em> is pressed. The method is expected to show a configuration dialog.
- *
- * @param shell the parent shell
- * @param attribute access to the attribute to configure
- * @return returns the configured attribute or <code>null</code> if the action has been cancelled.
- */
- public abstract IIncludePathAttribute performEdit(Shell shell, ClasspathAttributeAccess attribute);
-
- /**
- * This method is invoked when the <em>Remove</em> is pressed. The method should not show a dialog.
- *
- * @param attribute access to the attribute to configure
- * @return returns the configured attribute
- */
- public abstract IIncludePathAttribute performRemove(ClasspathAttributeAccess attribute);
-
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java
deleted file mode 100644
index 72611d14..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-
-/**
- * A classpath container page allows the user to create a new or edit an
- * existing classpath container entry.
- * <p>
- * Clients should implement this interface and include the name of their
- * class in an extension contributed to the jdt.ui's classpath container page
- * extension point (named <code>org.eclipse.wst.jsdt.ui.JsGlobalScopeContainerPage
- * </code>).
- * </p>
- * <p>
- * Clients implementing this interface may subclass from
- * <code>org.eclipse.jface.wizard.WizardPage</code>.
- * </p>
- * Clients implementing this interface may also implement
- * <code>IJsGlobalScopeContainerPageExtension</code> to get additional context
- * before this page is opened.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJsGlobalScopeContainerPage extends IWizardPage {
-
- /**
- * Called when the classpath container wizard is closed by selecting
- * the finish button. Implementers typically override this method to
- * store the page result (new/changed classpath entry returned in
- * getSelection) into its model.
- *
- * @return if the operation was successful. Only when returned
- * <code>true</code>, the wizard will close.
- */
- public boolean finish();
-
- /**
- * Returns the edited or created classpath container entry. This method
- * may return <code>null</code> if no classpath container entry exists.
- * The returned classpath entry is of kind <code>IIncludePathEntry.CPE_CONTAINER
- * </code>.
- *
- * @return the classpath entry edited or created on the page.
- */
- public IIncludePathEntry getSelection();
-
- /**
- * Sets the classpath container entry to be edited or <code>null</code>
- * if a new entry should be created.
- *
- * @param containerEntry the classpath entry to edit or <code>null</code>.
- * If not <code>null</code> then the classpath entry must be of
- * kind <code>IIncludePathEntry.CPE_CONTAINER</code>
- */
- public void setSelection(IIncludePathEntry containerEntry);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension.java
deleted file mode 100644
index a04568d5..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-
-/**
- * Classpath container pages that implement <code>IJsGlobalScopeContainerPage</code> can
- * optionally implement <code>IJsGlobalScopeContainerPageExtension</code> to get additional
- * information about the context when the page is opened. Method <code>initialize()</code>
- * is called before <code>IJsGlobalScopeContainerPage.setSelection</code>.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJsGlobalScopeContainerPageExtension {
-
- /**
- * Method <code>initialize()</code> is called before <code>IJsGlobalScopeContainerPage.setSelection</code>
- * to give additional information about the context the classpath container entry is configured in. This information
- * only reflects the underlying dialogs current selection state. The user still can make changes after the
- * the classpath container pages has been closed or decide to cancel the operation.
- * @param project The project the new or modified entry is added to. The project does not have to exist.
- * Project can be <code>null</code>.
- * @param currentEntries The class path entries currently selected to be set as the projects classpath. This can also
- * include the entry to be edited.
- */
- public void initialize(IJavaScriptProject project, IIncludePathEntry[] currentEntries);
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension2.java
deleted file mode 100644
index 5f6f2e24..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPageExtension2.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-
-/**
- * Classpath container pages that implement {@link IJsGlobalScopeContainerPage} can
- * optionally implement {@link IJsGlobalScopeContainerPageExtension2} to return more
- * than one element when creating new containers. If implemented, the method {@link #getNewContainers()}
- * is used instead of the method {@link IJsGlobalScopeContainerPage#getSelection() } to get the
- * newly selected containers. {@link IJsGlobalScopeContainerPage#getSelection() } is still used
- * for edited elements.
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public interface IJsGlobalScopeContainerPageExtension2 {
-
- /**
- * Method {@link #getNewContainers()} is called instead of {@link IJsGlobalScopeContainerPage#getSelection() }
- * to get the newly added containers. {@link IJsGlobalScopeContainerPage#getSelection() } is still used
- * to get the edited elements.
- * @return the classpath entries created on the page. All returned entries must be on kind
- * {@link IIncludePathEntry#CPE_CONTAINER}
- */
- public IIncludePathEntry[] getNewContainers();
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java
deleted file mode 100644
index c8bc8bfb..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URI;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-
-/**
- * Standard wizard page for creating new JavaScript projects. This page can be used in
- * project creation wizards. The page shows UI to configure the project with a JavaScript
- * build path and output location. On finish the page will also configure the JavaScript nature.
- * <p>
- * This is a replacement for <code>NewJavaProjectWizardPage</code> with a cleaner API.
- * </p>
- * <p>
- * Clients may instantiate or subclass.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class JavaCapabilityConfigurationPage extends NewElementWizardPage {
-
- private static final String PAGE_NAME= "JavaScriptCapabilityConfigurationPage"; //$NON-NLS-1$
-
- private IJavaScriptProject fJavaScriptProject;
- private BuildPathsBlock fBuildPathsBlock;
-
- /**
- * Creates a wizard page that can be used in a JavaScript project creation wizard.
- * It contains UI to configure a the classpath.
- *
- * <p>
- * After constructing, a call to {@link #init(IJavaScriptProject, IPath, IIncludePathEntry[], boolean)} is required.
- * </p>
- */
- public JavaCapabilityConfigurationPage() {
- super(PAGE_NAME);
- fJavaScriptProject= null;
-
- setTitle(NewWizardMessages.JavaCapabilityConfigurationPage_title);
- setDescription(NewWizardMessages.JavaCapabilityConfigurationPage_description);
- }
-
- protected BuildPathsBlock getBuildPathsBlock() {
- if (fBuildPathsBlock == null) {
- IStatusChangeListener listener= new IStatusChangeListener() {
- public void statusChanged(IStatus status) {
- updateStatus(status);
- }
- };
- fBuildPathsBlock= new BuildPathsBlock(new BusyIndicatorRunnableContext(), listener, 0, useNewSourcePage(), null);
- }
- return fBuildPathsBlock;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- *
- */
- public void dispose() {
- try {
- super.dispose();
- } finally {
- if (fBuildPathsBlock != null) {
- fBuildPathsBlock.dispose();
- fBuildPathsBlock= null;
- }
- }
- }
-
- /**
- * Clients can override this method to choose if the new source page is used. The new source page
- * requires that the project is already created as JavaScript project. The page will directly manipulate the classpath.
- * By default <code>false</code> is returned.
- * @return Returns <code>true</code> if the new source page should be used.
- *
- */
- protected boolean useNewSourcePage() {
- return false;
- }
-
- /**
- * Initializes the page with the project and default classpath.
- * <p>
- * The default classpath entries must correspond the given project.
- * </p>
- * <p>
- * The caller of this method is responsible for creating the underlying project. The page will create the output,
- * source and library folders if required.
- * </p>
- * <p>
- * The project does not have to exist at the time of initialization, but must exist when executing the runnable
- * obtained by <code>getRunnable()</code>.
- * </p>
- * @param jproject The JavaScript project.
- * @param defaultOutputLocation The default classpath entries or <code>null</code> to let the page choose the default
- * @param defaultEntries The folder to be taken as the default output path or <code>null</code> to let the page choose the default
- * @param defaultsOverrideExistingClasspath If set to <code>true</code>, an existing '.classpath' file is ignored. If set to <code>false</code>
- * the given default classpath and output location is only used if no '.classpath' exists.
- */
- public void init(IJavaScriptProject jproject, IIncludePathEntry[] defaultEntries, boolean defaultsOverrideExistingClasspath) {
- if (!defaultsOverrideExistingClasspath && jproject.exists() && jproject.getJSDTScopeFile().exists()) { //$NON-NLS-1$
-
- defaultEntries= null;
- }
- getBuildPathsBlock().init(jproject, defaultEntries);
- fJavaScriptProject= jproject;
- }
-
- /* (non-Javadoc)
- * @see WizardPage#createControl
- */
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- composite.setLayout(new GridLayout(1, false));
- Control control= getBuildPathsBlock().createControl(composite);
- control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE);
- setControl(composite);
- }
-
- /**
- * Returns the currently configured output location. Note that the returned path
- * might not be a valid path.
- *
- * @return the currently configured output location
- */
- public IPath getOutputLocation() {
- return getBuildPathsBlock().getOutputLocation();
- }
-
- /**
- * Returns the currently configured classpath. Note that the classpath might
- * not be valid.
- *
- * @return the currently configured classpath
- */
- public IIncludePathEntry[] getRawClassPath() {
- return getBuildPathsBlock().getRawClassPath();
- }
-
- /**
- * Returns the JavaScript project that was passed in {@link #init(IJavaScriptProject, IPath, IIncludePathEntry[], boolean)} or <code>null</code> if the
- * page has not been initialized yet.
- *
- * @return the managed JavaScript project or <code>null</code>
- */
- public IJavaScriptProject getJavaProject() {
- return fJavaScriptProject;
- }
-
-
- /**
- * Returns the runnable that will create the JavaScript project or <code>null</code> if the page has
- * not been initialized. The runnable sets the project's classpath and output location to the values
- * configured in the page and adds the JavaScript nature if not set yet. The method requires that the
- * project is created and opened.
- *
- * @return the runnable that creates the new JavaScript project
- */
- public IRunnableWithProgress getRunnable() {
- if (getJavaProject() != null) {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- configureJavaProject(monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- }
- return null;
- }
-
- /**
- * Helper method to create and open a IProject. The project location
- * is configured. No natures are added.
- *
- * @param project The handle of the project to create.
- * @param locationURI The location of the project or <code>null</code> to create the project in the workspace
- * @param monitor a progress monitor to report progress or <code>null</code> if
- * progress reporting is not desired
- * @throws CoreException if the project couldn't be created
- * @see org.eclipse.core.resources.IProjectDescription#setLocationURI(java.net.URI)
- *
- */
- public static void createProject(IProject project, URI locationURI, IProgressMonitor monitor) throws CoreException {
- BuildPathsBlock.createProject(project, locationURI, monitor);
- }
-
- /**
- * Adds the JavaScript nature to the project (if not set yet) and configures the build classpath.
- *
- * @param monitor a progress monitor to report progress or <code>null</code> if
- * progress reporting is not desired
- * @throws CoreException Thrown when the configuring the JavaScript project failed.
- * @throws InterruptedException Thrown when the operation has been canceled.
- */
- public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
-
- int nSteps= 6;
- monitor.beginTask(NewWizardMessages.JavaCapabilityConfigurationPage_op_desc_java, nSteps);
-
- try {
- IProject project= getJavaProject().getProject();
- BuildPathsBlock.addJavaNature(project, new SubProgressMonitor(monitor, 1));
- getBuildPathsBlock().configureJavaProject(new SubProgressMonitor(monitor, 5));
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- } finally {
- monitor.done();
- }
- }
-
- /**
- * Transfers the focus into this page.
- *
- *
- */
- protected void setFocus() {
- getBuildPathsBlock().setFocus();
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewClassWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewClassWizardPage.java
deleted file mode 100644
index 9af6fff0..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewClassWizardPage.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-
-/**
- * Wizard page to create a new class.
- * <p>
- * Note: This class is not intended to be subclassed, but clients can instantiate.
- * To implement a different kind of a new class wizard page, extend <code>NewTypeWizardPage</code>.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public class NewClassWizardPage extends NewTypeWizardPage {
-
- private final static String PAGE_NAME= "NewClassWizardPage"; //$NON-NLS-1$
-
- private final static String SETTINGS_CREATEMAIN= "create_main"; //$NON-NLS-1$
- private final static String SETTINGS_CREATECONSTR= "create_constructor"; //$NON-NLS-1$
- private final static String SETTINGS_CREATEUNIMPLEMENTED= "create_unimplemented"; //$NON-NLS-1$
-
- private SelectionButtonDialogFieldGroup fMethodStubsButtons;
-
- /**
- * Creates a new <code>NewClassWizardPage</code>
- */
- public NewClassWizardPage() {
- super(true, PAGE_NAME);
-
- setTitle(NewWizardMessages.NewClassWizardPage_title);
- setDescription(NewWizardMessages.NewClassWizardPage_description);
-
- String[] buttonNames3= new String[] {
- NewWizardMessages.NewClassWizardPage_methods_main, NewWizardMessages.NewClassWizardPage_methods_constructors,
- NewWizardMessages.NewClassWizardPage_methods_inherited
- };
- fMethodStubsButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames3, 1);
- fMethodStubsButtons.setLabelText(NewWizardMessages.NewClassWizardPage_methods_label);
- }
-
- // -------- Initialization ---------
-
- /**
- * The wizard owning this page is responsible for calling this method with the
- * current selection. The selection is used to initialize the fields of the wizard
- * page.
- *
- * @param selection used to initialize the fields
- */
- public void init(IStructuredSelection selection) {
- IJavaScriptElement jelem= getInitialJavaElement(selection);
- initContainerPage(jelem);
- initTypePage(jelem);
- doStatusUpdate();
-
- boolean createMain= false;
- boolean createConstructors= false;
- boolean createUnimplemented= true;
- IDialogSettings dialogSettings= getDialogSettings();
- if (dialogSettings != null) {
- IDialogSettings section= dialogSettings.getSection(PAGE_NAME);
- if (section != null) {
- createMain= section.getBoolean(SETTINGS_CREATEMAIN);
- createConstructors= section.getBoolean(SETTINGS_CREATECONSTR);
- createUnimplemented= section.getBoolean(SETTINGS_CREATEUNIMPLEMENTED);
- }
- }
-
- setMethodStubSelection(createMain, createConstructors, createUnimplemented, true);
- }
-
- // ------ validation --------
- private void doStatusUpdate() {
- // status of all used components
- IStatus[] status= new IStatus[] {
- fContainerStatus,
- isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus,
- fTypeNameStatus,
- fModifierStatus,
- fSuperClassStatus,
- fSuperInterfacesStatus
- };
-
- // the mode severe status will be displayed and the OK button enabled/disabled.
- updateStatus(status);
- }
-
-
- /*
- * @see NewContainerWizardPage#handleFieldChanged
- */
- protected void handleFieldChanged(String fieldName) {
- super.handleFieldChanged(fieldName);
-
- doStatusUpdate();
- }
-
-
- // ------ UI --------
-
- /*
- * @see WizardPage#createControl
- */
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
-
- int nColumns= 4;
-
- GridLayout layout= new GridLayout();
- layout.numColumns= nColumns;
- composite.setLayout(layout);
-
- // pick & choose the wanted UI components
-
- createContainerControls(composite, nColumns);
- createPackageControls(composite, nColumns);
- createEnclosingTypeControls(composite, nColumns);
-
- createSeparator(composite, nColumns);
-
- createTypeNameControls(composite, nColumns);
- createModifierControls(composite, nColumns);
-
- createSuperClassControls(composite, nColumns);
- createSuperInterfacesControls(composite, nColumns);
-
- createMethodStubSelectionControls(composite, nColumns);
-
- createCommentControls(composite, nColumns);
- enableCommentControl(true);
-
- setControl(composite);
-
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_CLASS_WIZARD_PAGE);
- }
-
- /*
- * @see WizardPage#becomesVisible
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- setFocus();
- } else {
- IDialogSettings dialogSettings= getDialogSettings();
- if (dialogSettings != null) {
- IDialogSettings section= dialogSettings.getSection(PAGE_NAME);
- if (section == null) {
- section= dialogSettings.addNewSection(PAGE_NAME);
- }
- section.put(SETTINGS_CREATEMAIN, isCreateMain());
- section.put(SETTINGS_CREATECONSTR, isCreateConstructors());
- section.put(SETTINGS_CREATEUNIMPLEMENTED, isCreateInherited());
- }
- }
- }
-
- private void createMethodStubSelectionControls(Composite composite, int nColumns) {
- Control labelControl= fMethodStubsButtons.getLabelControl(composite);
- LayoutUtil.setHorizontalSpan(labelControl, nColumns);
-
- DialogField.createEmptySpace(composite);
-
- Control buttonGroup= fMethodStubsButtons.getSelectionButtonsGroup(composite);
- LayoutUtil.setHorizontalSpan(buttonGroup, nColumns - 1);
- }
-
- /**
- * Returns the current selection state of the 'Create Main' checkbox.
- *
- * @return the selection state of the 'Create Main' checkbox
- */
- public boolean isCreateMain() {
- return fMethodStubsButtons.isSelected(0);
- }
-
- /**
- * Returns the current selection state of the 'Create Constructors' checkbox.
- *
- * @return the selection state of the 'Create Constructors' checkbox
- */
- public boolean isCreateConstructors() {
- return fMethodStubsButtons.isSelected(1);
- }
-
- /**
- * Returns the current selection state of the 'Create inherited abstract methods'
- * checkbox.
- *
- * @return the selection state of the 'Create inherited abstract methods' checkbox
- */
- public boolean isCreateInherited() {
- return fMethodStubsButtons.isSelected(2);
- }
-
- /**
- * Sets the selection state of the method stub checkboxes.
- *
- * @param createMain initial selection state of the 'Create Main' checkbox.
- * @param createConstructors initial selection state of the 'Create Constructors' checkbox.
- * @param createInherited initial selection state of the 'Create inherited abstract methods' checkbox.
- * @param canBeModified if <code>true</code> the method stub checkboxes can be changed by
- * the user. If <code>false</code> the buttons are "read-only"
- */
- public void setMethodStubSelection(boolean createMain, boolean createConstructors, boolean createInherited, boolean canBeModified) {
- fMethodStubsButtons.setSelection(0, createMain);
- fMethodStubsButtons.setSelection(1, createConstructors);
- fMethodStubsButtons.setSelection(2, createInherited);
-
- fMethodStubsButtons.setEnabled(canBeModified);
- }
-
- // ---- creation ----------------
-
- /*
- * @see NewTypeWizardPage#createTypeMembers
- */
- protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
- boolean doMain= isCreateMain();
- boolean doConstr= isCreateConstructors();
- boolean doInherited= isCreateInherited();
- createInheritedMethods(type, doConstr, doInherited, imports, new SubProgressMonitor(monitor, 1));
-
- if (doMain) {
- StringBuffer buf= new StringBuffer();
- final String lineDelim= "\n"; // OK, since content is formatted afterwards //$NON-NLS-1$
- String comment= CodeGeneration.getMethodComment(type.getJavaScriptUnit(), type.getTypeQualifiedName('.'), "main", new String[] {"args"}, new String[0], Signature.createTypeSignature("void", true), null, lineDelim); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (comment != null) {
- buf.append(comment);
- buf.append(lineDelim);
- }
- buf.append("public static void main("); //$NON-NLS-1$
- buf.append(imports.addImport("java.lang.String")); //$NON-NLS-1$
- buf.append("[] args) {"); //$NON-NLS-1$
- buf.append(lineDelim);
- final String content= CodeGeneration.getMethodBodyContent(type.getJavaScriptUnit(), type.getTypeQualifiedName('.'), "main", false, "", lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
- if (content != null && content.length() != 0)
- buf.append(content);
- buf.append(lineDelim);
- buf.append("}"); //$NON-NLS-1$
- type.createMethod(buf.toString(), null, false, null);
- }
-
- if (monitor != null) {
- monitor.done();
- }
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewContainerWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewContainerWizardPage.java
deleted file mode 100644
index eb101964..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewContainerWizardPage.java
+++ /dev/null
@@ -1,519 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.views.contentoutline.ContentOutline;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptModel;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.viewsupport.IViewPartInputProvider;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementComparator;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-import org.eclipse.wst.jsdt.ui.StandardJavaScriptElementContentProvider;
-
-/**
- * Wizard page that acts as a base class for wizard pages that create new JavaScript elements.
- * The class provides a input field for source folders (called container in this class) and
- * API to validate the enter source folder name.
- *
- * <p>
- * Clients may subclass.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class NewContainerWizardPage extends NewElementWizardPage {
-
- /** Id of the container field */
- protected static final String CONTAINER= "NewContainerWizardPage.container"; //$NON-NLS-1$
-
- /** The status of the last validation. */
- protected IStatus fContainerStatus;
-
- private StringButtonDialogField fContainerDialogField;
-
- /*
- * package fragment root corresponding to the input type (can be null)
- */
- private IPackageFragmentRoot fCurrRoot;
-
- private IWorkspaceRoot fWorkspaceRoot;
-
- /**
- * Create a new <code>NewContainerWizardPage</code>
- *
- * @param name the wizard page's name
- */
- public NewContainerWizardPage(String name) {
- super(name);
- fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
- ContainerFieldAdapter adapter= new ContainerFieldAdapter();
-
- fContainerDialogField= new StringButtonDialogField(adapter);
- fContainerDialogField.setDialogFieldListener(adapter);
- fContainerDialogField.setLabelText(getContainerLabel());
- fContainerDialogField.setButtonLabel(NewWizardMessages.NewContainerWizardPage_container_button);
-
- fContainerStatus= new StatusInfo();
- fCurrRoot= null;
- }
-
- /**
- * Returns the label that is used for the container input field.
- *
- * @return the label that is used for the container input field.
- *
- */
- protected String getContainerLabel() {
- return NewWizardMessages.NewContainerWizardPage_container_label;
- }
-
- /**
- * Initializes the source folder field with a valid package fragment root.
- * The package fragment root is computed from the given JavaScript element.
- *
- * @param elem the JavaScript element used to compute the initial package
- * fragment root used as the source folder
- */
- protected void initContainerPage(IJavaScriptElement elem) {
- IPackageFragmentRoot initRoot= null;
- if (elem != null) {
- initRoot= JavaModelUtil.getPackageFragmentRoot(elem);
- try {
- if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
- IJavaScriptProject jproject= elem.getJavaScriptProject();
- if (jproject != null) {
- initRoot= null;
- if (jproject.exists()) {
- IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
- for (int i= 0; i < roots.length; i++) {
- if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
- initRoot= roots[i];
- break;
- }
- }
- }
- if (initRoot == null) {
- initRoot= jproject.getPackageFragmentRoot(jproject.getResource());
- }
- }
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- setPackageFragmentRoot(initRoot, true);
- }
-
- /**
- * Utility method to inspect a selection to find a JavaScript element.
- *
- * @param selection the selection to be inspected
- * @return a JavaScript element to be used as the initial selection, or <code>null</code>,
- * if no JavaScript element exists in the given selection
- */
- protected IJavaScriptElement getInitialJavaElement(IStructuredSelection selection) {
- IJavaScriptElement jelem= null;
- if (selection != null && !selection.isEmpty()) {
- Object selectedElement= selection.getFirstElement();
- if (selectedElement instanceof IAdaptable) {
- IAdaptable adaptable= (IAdaptable) selectedElement;
-
- jelem= (IJavaScriptElement) adaptable.getAdapter(IJavaScriptElement.class);
- if (jelem == null) {
- IResource resource= (IResource) adaptable.getAdapter(IResource.class);
- if (resource != null && resource.getType() != IResource.ROOT) {
- while (jelem == null && resource.getType() != IResource.PROJECT) {
- resource= resource.getParent();
- jelem= (IJavaScriptElement) resource.getAdapter(IJavaScriptElement.class);
- }
- if (jelem == null) {
- jelem= JavaScriptCore.create(resource); // JavaScript project
- }
- }
- }
- }
- }
- if (jelem == null) {
- IWorkbenchPart part= JavaScriptPlugin.getActivePage().getActivePart();
- if (part instanceof ContentOutline) {
- part= JavaScriptPlugin.getActivePage().getActiveEditor();
- }
-
- if (part instanceof IViewPartInputProvider) {
- Object elem= ((IViewPartInputProvider)part).getViewPartInput();
- if (elem instanceof IJavaScriptElement) {
- jelem= (IJavaScriptElement) elem;
- }
- }
- }
-
- if (jelem == null || jelem.getElementType() == IJavaScriptElement.JAVASCRIPT_MODEL) {
- try {
- IJavaScriptProject[] projects= JavaScriptCore.create(getWorkspaceRoot()).getJavaScriptProjects();
- if (projects.length == 1) {
- jelem= projects[0];
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return jelem;
- }
-
- /**
- * Returns the text selection of the current editor. <code>null</code> is returned
- * when the current editor does not have focus or does not return a text selection.
- * @return Returns the text selection of the current editor or <code>null</code>.
- *
- *
- */
- protected ITextSelection getCurrentTextSelection() {
- IWorkbenchPart part= JavaScriptPlugin.getActivePage().getActivePart();
- if (part instanceof IEditorPart) {
- ISelectionProvider selectionProvider= part.getSite().getSelectionProvider();
- if (selectionProvider != null) {
- ISelection selection= selectionProvider.getSelection();
- if (selection instanceof ITextSelection) {
- return (ITextSelection) selection;
- }
- }
- }
- return null;
- }
-
-
- /**
- * Returns the recommended maximum width for text fields (in pixels). This
- * method requires that createContent has been called before this method is
- * call. Subclasses may override to change the maximum width for text
- * fields.
- *
- * @return the recommended maximum width for text fields.
- */
- protected int getMaxFieldWidth() {
- return convertWidthInCharsToPixels(40);
- }
-
-
- /**
- * Creates the necessary controls (label, text field and browse button) to edit
- * the source folder location. The method expects that the parent composite
- * uses a <code>GridLayout</code> as its layout manager and that the
- * grid layout has at least 3 columns.
- *
- * @param parent the parent composite
- * @param nColumns the number of columns to span. This number must be
- * greater or equal three
- */
- protected void createContainerControls(Composite parent, int nColumns) {
- fContainerDialogField.doFillIntoGrid(parent, nColumns);
- LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), getMaxFieldWidth());
- }
-
- /**
- * Sets the focus to the source folder's text field.
- */
- protected void setFocusOnContainer() {
- fContainerDialogField.setFocus();
- }
-
- // -------- ContainerFieldAdapter --------
-
- private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
-
- // -------- IStringButtonAdapter
- public void changeControlPressed(DialogField field) {
- containerChangeControlPressed(field);
- }
-
- // -------- IDialogFieldListener
- public void dialogFieldChanged(DialogField field) {
- containerDialogFieldChanged(field);
- }
- }
-
- private void containerChangeControlPressed(DialogField field) {
- // take the current jproject as init element of the dialog
- IPackageFragmentRoot root= chooseContainer();
- if (root != null) {
- setPackageFragmentRoot(root, true);
- }
- }
-
- private void containerDialogFieldChanged(DialogField field) {
- if (field == fContainerDialogField) {
- fContainerStatus= containerChanged();
- }
- // tell all others
- handleFieldChanged(CONTAINER);
- }
-
- // ----------- validation ----------
-
- /**
- * This method is a hook which gets called after the source folder's
- * text input field has changed. This default implementation updates
- * the model and returns an error status. The underlying model
- * is only valid if the returned status is OK.
- *
- * @return the model's error status
- */
- protected IStatus containerChanged() {
- StatusInfo status= new StatusInfo();
-
- fCurrRoot= null;
- String str= getPackageFragmentRootText();
- if (str.length() == 0) {
- status.setError(NewWizardMessages.NewContainerWizardPage_error_EnterContainerName);
- return status;
- }
- IPath path= new Path(str);
- IResource res= fWorkspaceRoot.findMember(path);
- if (res != null) {
- int resType= res.getType();
- if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
- IProject proj= res.getProject();
- if (!proj.isOpen()) {
- status.setError(Messages.format(NewWizardMessages.NewContainerWizardPage_error_ProjectClosed, proj.getFullPath().toString()));
- return status;
- }
- IJavaScriptProject jproject= JavaScriptCore.create(proj);
- fCurrRoot= jproject.getPackageFragmentRoot(res);
- if (res.exists()) {
- try {
- if (!proj.hasNature(JavaScriptCore.NATURE_ID)) {
- if (resType == IResource.PROJECT) {
- status.setError(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
- } else {
- status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotInAJavaProject);
- }
- return status;
- }
- if (fCurrRoot.isArchive()) {
- status.setError(Messages.format(NewWizardMessages.NewContainerWizardPage_error_ContainerIsBinary, str));
- return status;
- }
- if (fCurrRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
- status.setWarning(Messages.format(NewWizardMessages.NewContainerWizardPage_warning_inside_classfolder, str));
- } else if (!jproject.isOnIncludepath(fCurrRoot)) {
- status.setWarning(Messages.format(NewWizardMessages.NewContainerWizardPage_warning_NotOnClassPath, str));
- }
- } catch (CoreException e) {
- status.setWarning(NewWizardMessages.NewContainerWizardPage_warning_NotAJavaProject);
- }
- }
- return status;
- } else {
- status.setError(Messages.format(NewWizardMessages.NewContainerWizardPage_error_NotAFolder, str));
- return status;
- }
- } else {
- status.setError(Messages.format(NewWizardMessages.NewContainerWizardPage_error_ContainerDoesNotExist, str));
- return status;
- }
- }
-
- // -------- update message ----------------
-
- /**
- * Hook method that gets called when a field on this page has changed. For this page the
- * method gets called when the source folder field changes.
- * <p>
- * Every sub type is responsible to call this method when a field on its page has changed.
- * Subtypes override (extend) the method to add verification when a own field has a
- * dependency to an other field. For example the class name input must be verified
- * again when the package field changes (check for duplicated class names).
- *
- * @param fieldName The name of the field that has changed (field id). For the
- * source folder the field id is <code>CONTAINER</code>
- */
- protected void handleFieldChanged(String fieldName) {
- }
-
-
- // ---- get ----------------
-
- /**
- * Returns the workspace root.
- *
- * @return the workspace root
- */
- protected IWorkspaceRoot getWorkspaceRoot() {
- return fWorkspaceRoot;
- }
-
- /**
- * Returns the JavaScript project of the currently selected package fragment root or <code>null</code>
- * if no package fragment root is configured.
- *
- * @return The current JavaScript project or <code>null</code>.
- *
- */
- public IJavaScriptProject getJavaProject() {
- IPackageFragmentRoot root= getPackageFragmentRoot();
- if (root != null) {
- return root.getJavaScriptProject();
- }
- return null;
- }
-
- /**
- * Returns the <code>IPackageFragmentRoot</code> that corresponds to the current
- * value of the source folder field.
- *
- * @return the IPackageFragmentRoot or <code>null</code> if the current source
- * folder value is not a valid package fragment root
- *
- */
- public IPackageFragmentRoot getPackageFragmentRoot() {
- return fCurrRoot;
- }
-
- /**
- * Returns the current text of source folder text field.
- *
- * @return the text of the source folder text field
- */
- public String getPackageFragmentRootText() {
- return fContainerDialogField.getText();
- }
-
-
- /**
- * Sets the current source folder (model and text field) to the given package
- * fragment root.
-
- * @param root The new root.
- * @param canBeModified if <code>false</code> the source folder field can
- * not be changed by the user. If <code>true</code> the field is editable
- */
- public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) {
- fCurrRoot= root;
- String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$
- fContainerDialogField.setText(str);
- fContainerDialogField.setEnabled(canBeModified);
- }
-
- // ------------- choose source container dialog
-
- /**
- * Opens a selection dialog that allows to select a source container.
- *
- * @return returns the selected package fragment root or <code>null</code> if the dialog has been canceled.
- * The caller typically sets the result to the container input field.
- * <p>
- * Clients can override this method if they want to offer a different dialog.
- * </p>
- *
- *
- */
- protected IPackageFragmentRoot chooseContainer() {
- IJavaScriptElement initElement= getPackageFragmentRoot();
- Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaScriptProject.class };
- TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
- public boolean isSelectedValid(Object element) {
- try {
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject)element;
- IPath path= jproject.getProject().getFullPath();
- return (jproject.findPackageFragmentRoot(path) != null);
- } else if (element instanceof IPackageFragmentRoot) {
- return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
- }
- return true;
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus()); // just log, no UI in validation
- }
- return false;
- }
- };
-
- acceptedClasses= new Class[] { IJavaScriptModel.class, IPackageFragmentRoot.class, IJavaScriptProject.class };
- ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragmentRoot) {
- try {
- return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e.getStatus()); // just log, no UI in validation
- return false;
- }
- }
- return super.select(viewer, parent, element);
- }
- };
-
- StandardJavaScriptElementContentProvider provider= new StandardJavaScriptElementContentProvider();
- ILabelProvider labelProvider= new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT);
- ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
- dialog.setValidator(validator);
- dialog.setComparator(new JavaScriptElementComparator());
- dialog.setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
- dialog.setMessage(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
- dialog.addFilter(filter);
- dialog.setInput(JavaScriptCore.create(fWorkspaceRoot));
- dialog.setInitialSelection(initElement);
- dialog.setHelpAvailable(false);
-
- if (dialog.open() == Window.OK) {
- Object element= dialog.getFirstResult();
- if (element instanceof IJavaScriptProject) {
- IJavaScriptProject jproject= (IJavaScriptProject)element;
- return jproject.getPackageFragmentRoot(jproject.getProject());
- } else if (element instanceof IPackageFragmentRoot) {
- return (IPackageFragmentRoot)element;
- }
- return null;
- }
- return null;
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java
deleted file mode 100644
index 90a4d303..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusUtil;
-
-/**
- * Base class for wizard page responsible to create JavaScript elements. The class
- * provides API to update the wizard's status line and OK button according to
- * the value of a <code>IStatus</code> object.
- *
- * <p>
- * Clients may subclass.
- * </p>
- *
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves. */
-public abstract class NewElementWizardPage extends WizardPage {
-
- private IStatus fCurrStatus;
-
- private boolean fPageVisible;
-
- /**
- * Creates a <code>NewElementWizardPage</code>.
- *
- * @param name the wizard page's name
- */
- public NewElementWizardPage(String name) {
- super(name);
- fPageVisible= false;
- fCurrStatus= new StatusInfo();
- }
-
- // ---- WizardPage ----------------
-
- /*
- * @see WizardPage#becomesVisible
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- fPageVisible= visible;
- // policy: wizards are not allowed to come up with an error message
- if (visible && fCurrStatus.matches(IStatus.ERROR)) {
- StatusInfo status= new StatusInfo();
- status.setError(""); //$NON-NLS-1$
- fCurrStatus= status;
- }
- updateStatus(fCurrStatus);
- }
-
- /**
- * Updates the status line and the OK button according to the given status
- *
- * @param status status to apply
- */
- protected void updateStatus(IStatus status) {
- fCurrStatus= status;
- setPageComplete(!status.matches(IStatus.ERROR));
- if (fPageVisible) {
- StatusUtil.applyToStatusLine(this, status);
- }
- }
-
- /**
- * Updates the status line and the OK button according to the status evaluate from
- * an array of status. The most severe error is taken. In case that two status with
- * the same severity exists, the status with lower index is taken.
- *
- * @param status the array of status
- */
- protected void updateStatus(IStatus[] status) {
- updateStatus(StatusUtil.getMostSevere(status));
- }
-
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewJavaProjectWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewJavaProjectWizardPage.java
deleted file mode 100644
index 76ba2f04..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewJavaProjectWizardPage.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
-import org.eclipse.wst.jsdt.core.IIncludePathEntry;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.wst.jsdt.internal.ui.preferences.NewJavaProjectPreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.util.BusyIndicatorRunnableContext;
-import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
-
-/**
- * Standard wizard page for creating new JavaScript projects. This page can be used in
- * project creation wizards for projects and will configure the project with the
- * JavaScript nature. This page also allows the user to configure the JavaScript project's
- * output location for class files generated by the JavaScript builder.
- * <p>
- * Whenever possible clients should use the class <code>JavaCapabilityConfigurationPage
- * </code> in favor of this class.
- * </p>
- * <p>
- * Clients may instantiate or subclass.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- */
-public class NewJavaProjectWizardPage extends NewElementWizardPage {
-
- private static final String PAGE_NAME= "NewJavaProjectWizardPage"; //$NON-NLS-1$
-
- private WizardNewProjectCreationPage fMainPage;
-
-// private IPath fOutputLocation;
- private IIncludePathEntry[] fClasspathEntries;
- private BuildPathsBlock fBuildPathsBlock;
-
- private boolean fProjectModified;
-
- /**
- * Creates a JavaScript project wizard creation page.
- * <p>
- * The JavaScript project wizard reads project name and location from the main page.
- * </p>
- *
- * @param root the workspace root
- * @param mainpage the main page of the wizard
- */
- public NewJavaProjectWizardPage(IWorkspaceRoot root, WizardNewProjectCreationPage mainpage) {
- super(PAGE_NAME);
-
- setTitle(NewWizardMessages.NewJavaProjectWizardPage_title);
- setDescription(NewWizardMessages.NewJavaProjectWizardPage_description);
-
- fMainPage= mainpage;
- IStatusChangeListener listener= new IStatusChangeListener() {
- public void statusChanged(IStatus status) {
- updateStatus(status);
- }
- };
-
- fBuildPathsBlock= new BuildPathsBlock(new BusyIndicatorRunnableContext(), listener, 0, false, null);
-
- fProjectModified= true;
-// fOutputLocation= null;
- fClasspathEntries= null;
- }
-
- /*
- * @see org.eclipse.jface.dialogs.DialogPage#dispose()
- *
- */
- public void dispose() {
- try {
- super.dispose();
- } finally {
- if (fBuildPathsBlock != null) {
- fBuildPathsBlock.dispose();
- fBuildPathsBlock= null;
- }
- }
- }
-
- /**
- * Sets the default output location to be used for the new JavaScript project.
- * This is the path of the folder (with the project) into which the JavaScript builder
- * will generate binary class files corresponding to the project's JavaScript source
- * files.
- * <p>
- * The wizard will create this folder if required.
- * </p>
- * <p>
- * The default classpath will be applied when <code>initBuildPaths</code> is
- * called. This is done automatically when the page becomes visible and
- * the project or the default paths have changed.
- * </p>
- *
- * @param path the folder to be taken as the default output path
- */
- public void setDefaultOutputFolder(IPath path) {
-// fOutputLocation= path;
- setProjectModified();
- }
-
- /**
- * Sets the default classpath to be used for the new JavaScript project.
- * <p>
- * The caller of this method is responsible for creating the classpath entries
- * for the <code>IJavaScriptProject</code> that corresponds to the created project.
- * The caller is responsible for creating any new folders that might be mentioned
- * on the classpath.
- * </p>
- * <p>
- * The default output location will be applied when <code>initBuildPaths</code> is
- * called. This is done automatically when the page becomes visible and
- * the project or the default paths have changed.
- * </p>
- *
- * @param entries the default classpath entries
- * @param appendDefaultJRE <code>true</code> a variable entry for the
- * default JRE (specified in the preferences) will be added to the classpath.
- */
- public void setDefaultClassPath(IIncludePathEntry[] entries, boolean appendDefaultJRE) {
- if (entries != null && appendDefaultJRE) {
- IIncludePathEntry[] jreEntry= NewJavaProjectPreferencePage.getDefaultJRELibrary();
- IIncludePathEntry[] newEntries= new IIncludePathEntry[entries.length + jreEntry.length];
- System.arraycopy(entries, 0, newEntries, 0, entries.length);
- System.arraycopy(jreEntry, 0, newEntries, entries.length, jreEntry.length);
- entries= newEntries;
- }
- fClasspathEntries= entries;
- setProjectModified();
- }
-
- /**
- * Sets the project state to modified. Doing so will initialize the page
- * the next time it becomes visible.
- *
- *
- */
- public void setProjectModified() {
- fProjectModified= true;
- }
-
- /**
- * Returns the project handle. Subclasses should override this
- * method if they don't provide a main page or if they provide
- * their own main page implementation.
- *
- * @return the project handle
- */
- protected IProject getProjectHandle() {
- Assert.isNotNull(fMainPage);
- return fMainPage.getProjectHandle();
- }
-
- /**
- * Returns the project location path. Subclasses should override this
- * method if they don't provide a main page or if they provide
- * their own main page implementation.
- *
- * @return the project location path
- */
- protected IPath getLocationPath() {
- Assert.isNotNull(fMainPage);
- return fMainPage.getLocationPath();
- }
-
- /**
- * Returns the JavaScript project handle by converting the result of
- * <code>getProjectHandle()</code> into a JavaScript project.
- *
- * @return the JavaScript project handle
- * @see #getProjectHandle()
- */
- public IJavaScriptProject getNewJavaProject() {
- return JavaScriptCore.create(getProjectHandle());
- }
-
- /* (non-Javadoc)
- * @see WizardPage#createControl
- */
- public void createControl(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setFont(parent.getFont());
- composite.setLayout(new GridLayout(1, false));
- Control control= fBuildPathsBlock.createControl(composite);
- control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Dialog.applyDialogFont(composite);
- PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE);
- setControl(composite);
- }
-
- /**
- * Forces the initialization of the JavaScript project page. Default classpath or buildpath
- * will be used if set. The initialization should only be performed when the project
- * or default paths have changed. Toggling back and forward the pages without
- * changes should not re-initialize the page, as changes from the user will be
- * overwritten.
- *
- *
- */
- protected void initBuildPaths() {
- fBuildPathsBlock.init(getNewJavaProject(), fClasspathEntries);
- }
-
- /**
- * Extend this method to set a user defined default classpath or output location.
- * The method <code>initBuildPaths</code> is called when the page becomes
- * visible the first time or the project or the default paths have changed.
- *
- * @param visible if <code>true</code> the page becomes visible; otherwise
- * it becomes invisible
- */
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- // evaluate if a initialization is required
- if (fProjectModified || isNewProjectHandle()) {
- // only initialize the project when needed
- initBuildPaths();
- fProjectModified= false;
- }
- }
- }
-
- private boolean isNewProjectHandle() {
- IProject oldProject= fBuildPathsBlock.getJavaProject().getProject();
- return !oldProject.equals(getProjectHandle());
- }
-
-
- /**
- * Returns the currently configured output location. Note that the returned path
- * might not be valid.
- *
- * @return the configured output location
- *
- *
- */
- public IPath getOutputLocation() {
- return fBuildPathsBlock.getOutputLocation();
- }
-
- /**
- * Returns the currently configured classpath. Note that the classpath might
- * not be valid.
- *
- * @return the configured classpath
- *
- *
- */
- public IIncludePathEntry[] getRawClassPath() {
- return fBuildPathsBlock.getRawClassPath();
- }
-
-
- /**
- * Returns the runnable that will create the JavaScript project. The runnable will create
- * and open the project if needed. The runnable will add the JavaScript nature to the
- * project, and set the project's classpath and output location.
- * <p>
- * To create the new JavaScript project, execute this runnable
- * </p>
- *
- * @return the runnable
- */
- public IRunnableWithProgress getRunnable() {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- monitor.beginTask(NewWizardMessages.NewJavaProjectWizardPage_op_desc, 10);
- // initialize if needed
- if (fProjectModified || isNewProjectHandle()) {
- initBuildPaths();
- }
-
- // create the project
- try {
- IPath locationPath= getLocationPath();
- BuildPathsBlock.createProject(getProjectHandle(),
- locationPath != null ? URIUtil.toURI(locationPath) : null,
- new SubProgressMonitor(monitor, 2));
- BuildPathsBlock.addJavaNature(getProjectHandle(), new SubProgressMonitor(monitor, 2));
- fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 6));
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } catch (OperationCanceledException e) {
- throw new InterruptedException();
- } finally {
- monitor.done();
- }
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java
deleted file mode 100644
index 7cdfba1b..00000000
--- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java
+++ /dev/null
@@ -1,2407 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * 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:
- * IBM Corporation - initial API and implementation
- * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
- *******************************************************************************/
-package org.eclipse.wst.jsdt.ui.wizards;
-
-import java.lang.reflect.InvocationTargetException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.templates.Template;
-import org.eclipse.jface.text.templates.TemplateException;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.accessibility.AccessibleAdapter;
-import org.eclipse.swt.accessibility.AccessibleEvent;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Item;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.contentassist.ContentAssistHandler;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.wst.jsdt.core.Flags;
-import org.eclipse.wst.jsdt.core.IBuffer;
-import org.eclipse.wst.jsdt.core.IFunction;
-import org.eclipse.wst.jsdt.core.IJavaScriptElement;
-import org.eclipse.wst.jsdt.core.IJavaScriptProject;
-import org.eclipse.wst.jsdt.core.IJavaScriptUnit;
-import org.eclipse.wst.jsdt.core.IPackageFragment;
-import org.eclipse.wst.jsdt.core.IPackageFragmentRoot;
-import org.eclipse.wst.jsdt.core.ISourceRange;
-import org.eclipse.wst.jsdt.core.IType;
-import org.eclipse.wst.jsdt.core.JavaScriptConventions;
-import org.eclipse.wst.jsdt.core.JavaScriptCore;
-import org.eclipse.wst.jsdt.core.JavaScriptModelException;
-import org.eclipse.wst.jsdt.core.Signature;
-import org.eclipse.wst.jsdt.core.ToolFactory;
-import org.eclipse.wst.jsdt.core.compiler.IProblem;
-import org.eclipse.wst.jsdt.core.compiler.IScanner;
-import org.eclipse.wst.jsdt.core.compiler.ITerminalSymbols;
-import org.eclipse.wst.jsdt.core.compiler.InvalidInputException;
-import org.eclipse.wst.jsdt.core.dom.AST;
-import org.eclipse.wst.jsdt.core.dom.ASTNode;
-import org.eclipse.wst.jsdt.core.dom.ASTParser;
-import org.eclipse.wst.jsdt.core.dom.AbstractTypeDeclaration;
-import org.eclipse.wst.jsdt.core.dom.ITypeBinding;
-import org.eclipse.wst.jsdt.core.dom.ImportDeclaration;
-import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit;
-import org.eclipse.wst.jsdt.core.dom.Type;
-import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants;
-import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope;
-import org.eclipse.wst.jsdt.core.search.SearchEngine;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility;
-import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes;
-import org.eclipse.wst.jsdt.internal.corext.dom.TokenScanner;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.StubTypeContext;
-import org.eclipse.wst.jsdt.internal.corext.refactoring.TypeContextChecker;
-import org.eclipse.wst.jsdt.internal.corext.template.java.JavaContext;
-import org.eclipse.wst.jsdt.internal.corext.util.CodeFormatterUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.wst.jsdt.internal.corext.util.Messages;
-import org.eclipse.wst.jsdt.internal.corext.util.Resources;
-import org.eclipse.wst.jsdt.internal.corext.util.Strings;
-import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages;
-import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TableTextCellEditor;
-import org.eclipse.wst.jsdt.internal.ui.dialogs.TextFieldNavigationHandler;
-import org.eclipse.wst.jsdt.internal.ui.preferences.CodeTemplatePreferencePage;
-import org.eclipse.wst.jsdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.CompletionContextRequestor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
-import org.eclipse.wst.jsdt.internal.ui.util.SWTUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IListAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ListDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.Separator;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
-import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.StringDialogField;
-import org.eclipse.wst.jsdt.ui.CodeGeneration;
-import org.eclipse.wst.jsdt.ui.CodeStyleConfiguration;
-import org.eclipse.wst.jsdt.ui.JavaScriptElementLabelProvider;
-
-/**
- * The class <code>NewTypeWizardPage</code> contains controls and validation routines
- * for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
- * Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
- * is intended to serve as base class of all wizards that create types like applets, servlets, classes,
- * interfaces, etc.
- * <p>
- * See {@link NewClassWizardPage} or {@link NewInterfaceWizardPage} for an
- * example usage of the <code>NewTypeWizardPage</code>.
- * </p>
- *
- * Provisional API: This class/interface is part of an interim API that is still under development and expected to
- * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
- * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
- * (repeatedly) as the API evolves.
- *
- * @see org.eclipse.wst.jsdt.ui.wizards.NewClassWizardPage
- * @see org.eclipse.wst.jsdt.ui.wizards.NewInterfaceWizardPage
- *
- */
-public abstract class NewTypeWizardPage extends NewContainerWizardPage {
-
- /**
- * Class used in stub creation routines to add needed imports to a
- * compilation unit.
- */
- public static class ImportsManager {
-
- private ImportRewrite fImportsRewrite;
-
- /* package */ ImportsManager(JavaScriptUnit astRoot) throws CoreException {
- fImportsRewrite= CodeStyleConfiguration.createImportRewrite(astRoot, true);
- }
-
- /* package */ IJavaScriptUnit getCompilationUnit() {
- return fImportsRewrite.getCompilationUnit();
- }
-
- /**
- * Adds a new import declaration that is sorted in the existing imports.
- * If an import already exists or the import would conflict with an import
- * of an other type with the same simple name, the import is not added.
- *
- * @param qualifiedTypeName The fully qualified name of the type to import
- * (dot separated).
- * @return Returns the simple type name that can be used in the code or the
- * fully qualified type name if an import conflict prevented the import.
- */
- public String addImport(String qualifiedTypeName) {
- return fImportsRewrite.addImport(qualifiedTypeName);
- }
-
- /**
- * Adds a new import declaration that is sorted in the existing imports.
- * If an import already exists or the import would conflict with an import
- * of an other type with the same simple name, the import is not added.
- *
- * @param typeBinding the binding of the type to import
- *
- * @return Returns the simple type name that can be used in the code or the
- * fully qualified type name if an import conflict prevented the import.
- */
- public String addImport(ITypeBinding typeBinding) {
- return fImportsRewrite.addImport(typeBinding);
- }
-
- /**
- * Adds a new import declaration for a static type that is sorted in the existing imports.
- * If an import already exists or the import would conflict with an import
- * of an other static import with the same simple name, the import is not added.
- *
- * @param declaringTypeName The qualified name of the static's member declaring type
- * @param simpleName the simple name of the member; either a field or a method name.
- * @param isField <code>true</code> specifies that the member is a field, <code>false</code> if it is a
- * method.
- * @return returns either the simple member name if the import was successful or else the qualified name if
- * an import conflict prevented the import.
- *
- *
- */
- public String addStaticImport(String declaringTypeName, String simpleName, boolean isField) {
- return fImportsRewrite.addStaticImport(declaringTypeName, simpleName, isField);
- }
-
- /* package */ void create(boolean needsSave, IProgressMonitor monitor) throws CoreException {
- TextEdit edit= fImportsRewrite.rewriteImports(monitor);
- JavaModelUtil.applyEdit(fImportsRewrite.getCompilationUnit(), edit, needsSave, null);
- }
-
- /* package */ void removeImport(String qualifiedName) {
- fImportsRewrite.removeImport(qualifiedName);
- }
-
- /* package */ void removeStaticImport(String qualifiedName) {
- fImportsRewrite.removeStaticImport(qualifiedName);
- }
- }
-
-
- /** Public access flag. See The JavaScript Virtual Machine Specification for more details. */
- public int F_PUBLIC = Flags.AccPublic;
- /** Private access flag. See The JavaScript Virtual Machine Specification for more details. */
- public int F_PRIVATE = Flags.AccPrivate;
- /** Static access flag. See The JavaScript Virtual Machine Specification for more details. */
- public int F_STATIC = Flags.AccStatic;
- /** Abstract property flag. See The JavaScript Virtual Machine Specification for more details. */
- public int F_ABSTRACT = Flags.AccAbstract;
-
- private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
-
- /** Field ID of the package input field. */
- protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
- /** Field ID of the enclosing type input field. */
- protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
- /** Field ID of the enclosing type checkbox. */
- protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
- /** Field ID of the type name input field. */
- protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
- /** Field ID of the super type input field. */
- protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
- /** Field ID of the super interfaces input field. */
- protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
- /** Field ID of the modifier check boxes. */
- protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
- /** Field ID of the method stubs check boxes. */
- protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
-
- private static class InterfaceWrapper {
- public String interfaceName;
-
- public InterfaceWrapper(String interfaceName) {
- this.interfaceName= interfaceName;
- }
-
- public int hashCode() {
- return interfaceName.hashCode();
- }
-
- public boolean equals(Object obj) {
- return obj != null && getClass().equals(obj.getClass()) && ((InterfaceWrapper) obj).interfaceName.equals(interfaceName);
- }
- }
-
- private static class InterfacesListLabelProvider extends LabelProvider {
- private Image fInterfaceImage;
-
- public InterfacesListLabelProvider() {
- fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
- }
-
- public String getText(Object element) {
- return ((InterfaceWrapper) element).interfaceName;
- }
-
- public Image getImage(Object element) {
- return fInterfaceImage;
- }
- }
-
- private StringButtonStatusDialogField fPackageDialogField;
-
- private SelectionButtonDialogField fEnclosingTypeSelection;
- private StringButtonDialogField fEnclosingTypeDialogField;
-
- private boolean fCanModifyPackage;
- private boolean fCanModifyEnclosingType;
-
- private IPackageFragment fCurrPackage;
-
- private IType fCurrEnclosingType;
- /**
- * a handle to the type to be created (does usually not exist, can be null)
- */
- private IType fCurrType;
- private StringDialogField fTypeNameDialogField;
-
- private StringButtonDialogField fSuperClassDialogField;
- private ListDialogField fSuperInterfacesDialogField;
-
- private SelectionButtonDialogFieldGroup fAccMdfButtons;
- private SelectionButtonDialogFieldGroup fOtherMdfButtons;
-
- private SelectionButtonDialogField fAddCommentButton;
- private boolean fUseAddCommentButtonValue; // used for compatibility: Wizards that don't show the comment button control
- // will use the preferences settings
-
- private IType fCreatedType;
-
- private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
- private JavaTypeCompletionProcessor fEnclosingTypeCompletionProcessor;
- private StubTypeContext fSuperClassStubTypeContext;
- private StubTypeContext fSuperInterfaceStubTypeContext;
-
- protected IStatus fEnclosingTypeStatus;
- protected IStatus fPackageStatus;
- protected IStatus fTypeNameStatus;
- protected IStatus fSuperClassStatus;
- protected IStatus fModifierStatus;
- protected IStatus fSuperInterfacesStatus;
-
- private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
- private final int ABSTRACT_INDEX= 0, STATIC_INDEX= 2, ENUM_ANNOT_STATIC_INDEX= 1;
-
- private int fTypeKind;
-
- /**
- * Constant to signal that the created type is a class.
- *
- */
- public static final int CLASS_TYPE = 1;
-
- /**
- * Constant to signal that the created type is a interface.
- *
- */
- public static final int INTERFACE_TYPE = 2;
-
- /**
- * Constant to signal that the created type is an enum.
- *
- */
- public static final int ENUM_TYPE = 3;
-
- /**
- * Constant to signal that the created type is an annotation.
- *
- */
- public static final int ANNOTATION_TYPE = 4;
-
- /**
- * Creates a new <code>NewTypeWizardPage</code>.
- *
- * @param isClass <code>true</code> if a new class is to be created; otherwise
- * an interface is to be created
- * @param pageName the wizard page's name
- */
- public NewTypeWizardPage(boolean isClass, String pageName) {
- this(isClass ? CLASS_TYPE : INTERFACE_TYPE, pageName);
- }
-
- /**
- * Creates a new <code>NewTypeWizardPage</code>.
- *
- * @param typeKind Signals the kind of the type to be created. Valid kinds are
- * {@link #CLASS_TYPE}, {@link #INTERFACE_TYPE}, {@link #ENUM_TYPE} and {@link #ANNOTATION_TYPE}
- * @param pageName the wizard page's name
- *
- */
- public NewTypeWizardPage(int typeKind, String pageName) {
- super(pageName);
- fTypeKind= typeKind;
-
- fCreatedType= null;
-
- TypeFieldsAdapter adapter= new TypeFieldsAdapter();
-
- fPackageDialogField= new StringButtonStatusDialogField(adapter);
- fPackageDialogField.setDialogFieldListener(adapter);
- fPackageDialogField.setLabelText(getPackageLabel());
- fPackageDialogField.setButtonLabel(NewWizardMessages.NewTypeWizardPage_package_button);
- fPackageDialogField.setStatusWidthHint(NewWizardMessages.NewTypeWizardPage_default);
-
- fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
- fEnclosingTypeSelection.setDialogFieldListener(adapter);
- fEnclosingTypeSelection.setLabelText(getEnclosingTypeLabel());
-
- fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
- fEnclosingTypeDialogField.setDialogFieldListener(adapter);
- fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.NewTypeWizardPage_enclosing_button);
-
- fTypeNameDialogField= new StringDialogField();
- fTypeNameDialogField.setDialogFieldListener(adapter);
- fTypeNameDialogField.setLabelText(getTypeNameLabel());
-
- fSuperClassDialogField= new StringButtonDialogField(adapter);
- fSuperClassDialogField.setDialogFieldListener(adapter);
- fSuperClassDialogField.setLabelText(getSuperClassLabel());
- fSuperClassDialogField.setButtonLabel(NewWizardMessages.NewTypeWizardPage_superclass_button);
-
- String[] addButtons= new String[] {
- NewWizardMessages.NewTypeWizardPage_interfaces_add,
- /* 1 */ null,
- NewWizardMessages.NewTypeWizardPage_interfaces_remove
- };
- fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
- fSuperInterfacesDialogField.setDialogFieldListener(adapter);
- fSuperInterfacesDialogField.setTableColumns(new ListDialogField.ColumnsDescription(1, false));
- fSuperInterfacesDialogField.setLabelText(getSuperInterfacesLabel());
- fSuperInterfacesDialogField.setRemoveButtonIndex(2);
-
- String[] buttonNames1= new String[] {
- NewWizardMessages.NewTypeWizardPage_modifiers_public,
- NewWizardMessages.NewTypeWizardPage_modifiers_default,
- NewWizardMessages.NewTypeWizardPage_modifiers_private,
- NewWizardMessages.NewTypeWizardPage_modifiers_protected
- };
- fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
- fAccMdfButtons.setDialogFieldListener(adapter);
- fAccMdfButtons.setLabelText(getModifiersLabel());
- fAccMdfButtons.setSelection(0, true);
-
- String[] buttonNames2;
- if (fTypeKind == CLASS_TYPE) {
- buttonNames2= new String[] {
- NewWizardMessages.NewTypeWizardPage_modifiers_abstract,
- NewWizardMessages.NewTypeWizardPage_modifiers_final,
- NewWizardMessages.NewTypeWizardPage_modifiers_static
- };
- } else {
- if (fTypeKind == ENUM_TYPE || fTypeKind == ANNOTATION_TYPE) {
- buttonNames2= new String[] {
- NewWizardMessages.NewTypeWizardPage_modifiers_abstract,
- NewWizardMessages.NewTypeWizardPage_modifiers_static
- };
- }
- else
- buttonNames2= new String[] {};
- }
-
- fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
- fOtherMdfButtons.setDialogFieldListener(adapter);
-
- fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
- fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
- fOtherMdfButtons.enableSelectionButton(STATIC_INDEX, false);
-
- if (fTypeKind == ENUM_TYPE || fTypeKind == ANNOTATION_TYPE) {
- fOtherMdfButtons.enableSelectionButton(ABSTRACT_INDEX, false);
- fOtherMdfButtons.enableSelectionButton(ENUM_ANNOT_STATIC_INDEX, false);
- }
-
- fAddCommentButton= new SelectionButtonDialogField(SWT.CHECK);
- fAddCommentButton.setLabelText(NewWizardMessages.NewTypeWizardPage_addcomment_label);
-
- fUseAddCommentButtonValue= false; // only used when enabled
-
- fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
- fEnclosingTypeCompletionProcessor= new JavaTypeCompletionProcessor(false, false, true);
-
- fPackageStatus= new StatusInfo();
- fEnclosingTypeStatus= new StatusInfo();
-
- fCanModifyPackage= true;
- fCanModifyEnclosingType= true;
- updateEnableState();
-
- fTypeNameStatus= new StatusInfo();
- fSuperClassStatus= new StatusInfo();
- fSuperInterfacesStatus= new StatusInfo();
- fModifierStatus= new StatusInfo();
- }
-
- /**
- * Initializes all fields provided by the page with a given selection.
- *
- * @param elem the selection used to initialize this page or <code>
- * null</code> if no selection was available
- */
- protected void initTypePage(IJavaScriptElement elem) {
- String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
- ArrayList initSuperinterfaces= new ArrayList(5);
-
- IJavaScriptProject project= null;
- IPackageFragment pack= null;
- IType enclosingType= null;
-
- if (elem != null) {
- // evaluate the enclosing type
- project= elem.getJavaScriptProject();
- pack= (IPackageFragment) elem.getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT);
- IType typeInCU= (IType) elem.getAncestor(IJavaScriptElement.TYPE);
- if (typeInCU != null) {
- if (typeInCU.getJavaScriptUnit() != null) {
- enclosingType= typeInCU;
- }
- } else {
- IJavaScriptUnit cu= (IJavaScriptUnit) elem.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT);
- if (cu != null) {
- enclosingType= cu.findPrimaryType();
- }
- }
-
- IType type= null;
- if (elem.getElementType() == IJavaScriptElement.TYPE) {
- type= (IType)elem;
- if (type.exists()) {
- String superName= JavaModelUtil.getFullyQualifiedName(type);
- initSuperclass= superName;
- }
- }
- }
-
- String typeName= ""; //$NON-NLS-1$
-
- ITextSelection selection= getCurrentTextSelection();
- if (selection != null) {
- String text= selection.getText();
- if (text != null && validateJavaTypeName(text, project).isOK()) {
- typeName= text;
- }
- }
-
- setPackageFragment(pack, true);
- setEnclosingType(enclosingType, true);
- setEnclosingTypeSelection(false, true);
-
- setTypeName(typeName, true);
- setSuperClass(initSuperclass, true);
- setSuperInterfaces(initSuperinterfaces, true);
-
- setAddComments(StubUtility.doAddComments(project), true); // from project or workspace
- }
-
- private static IStatus validateJavaTypeName(String text, IJavaScriptProject project) {
- if (project == null || !project.exists()) {
- return JavaScriptConventions.validateJavaScriptTypeName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3);
- }
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String compliance= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- return JavaScriptConventions.validateJavaScriptTypeName(text, sourceLevel, compliance);
- }
-
- private static IStatus validatePackageName(String text, IJavaScriptProject project) {
- if (project == null || !project.exists()) {
- return JavaScriptConventions.validatePackageName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3);
- }
- String sourceLevel= project.getOption(JavaScriptCore.COMPILER_SOURCE, true);
- String compliance= project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true);
- return JavaScriptConventions.validatePackageName(text, sourceLevel, compliance);
- }
-
- // -------- UI Creation ---------
-
- /**
- * Returns the label that is used for the package input field.
- *
- * @return the label that is used for the package input field.
- *
- */
- protected String getPackageLabel() {
- return NewWizardMessages.NewTypeWizardPage_package_label;
- }
-
- /**
- * Returns the label that is used for the enclosing type input field.
- *
- * @return the label that is used for the enclosing type input field.
- *
- */
- protected String getEnclosingTypeLabel() {
- return NewWizardMessages.NewTypeWizardPage_enclosing_selection_label;
- }
-
- /**
- * Returns the label that is used for the type name input field.
- *
- * @return the label that is used for the type name input field.
- *
- */
- protected String getTypeNameLabel() {
- return NewWizardMessages.NewTypeWizardPage_typename_label;
- }
-
- /**
- * Returns the label that is used for the modifiers input field.
- *
- * @return the label that is used for the modifiers input field
- *
- */
- protected String getModifiersLabel() {
- return NewWizardMessages.NewTypeWizardPage_modifiers_acc_label;
- }
-
- /**
- * Returns the label that is used for the super class input field.
- *
- * @return the label that is used for the super class input field.
- *
- */
- protected String getSuperClassLabel() {
- return NewWizardMessages.NewTypeWizardPage_superclass_label;
- }
-
- /**
- * Returns the label that is used for the super interfaces input field.
- *
- * @return the label that is used for the super interfaces input field.
- *
- */
- protected String getSuperInterfacesLabel() {
- if (fTypeKind != INTERFACE_TYPE)
- return NewWizardMessages.NewTypeWizardPage_interfaces_class_label;
- return NewWizardMessages.NewTypeWizardPage_interfaces_ifc_label;
- }
-
- /**
- * Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createSeparator(Composite composite, int nColumns) {
- (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
- }
-
- /**
- * Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
- * least 4 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createPackageControls(Composite composite, int nColumns) {
- fPackageDialogField.doFillIntoGrid(composite, nColumns);
- Text text= fPackageDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, getMaxFieldWidth());
- LayoutUtil.setHorizontalGrabbing(text);
- ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
- TextFieldNavigationHandler.install(text);
- }
-
- /**
- * Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
- * least 4 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createEnclosingTypeControls(Composite composite, int nColumns) {
- // #6891
- Composite tabGroup= new Composite(composite, SWT.NONE);
- GridLayout layout= new GridLayout();
- layout.marginWidth= 0;
- layout.marginHeight= 0;
- tabGroup.setLayout(layout);
-
- fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
-
- Text text= fEnclosingTypeDialogField.getTextControl(composite);
- text.getAccessible().addAccessibleListener(new AccessibleAdapter() {
- public void getName(AccessibleEvent e) {
- e.result= NewWizardMessages.NewTypeWizardPage_enclosing_field_description;
- }
- });
- GridData gd= new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint= getMaxFieldWidth();
- gd.horizontalSpan= 2;
- text.setLayoutData(gd);
-
- Button button= fEnclosingTypeDialogField.getChangeControl(composite);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.widthHint = SWTUtil.getButtonWidthHint(button);
- button.setLayoutData(gd);
- ControlContentAssistHelper.createTextContentAssistant(text, fEnclosingTypeCompletionProcessor);
- TextFieldNavigationHandler.install(text);
- }
-
- /**
- * Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
- * least 2 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createTypeNameControls(Composite composite, int nColumns) {
- fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
- DialogField.createEmptySpace(composite);
-
- Text text= fTypeNameDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, getMaxFieldWidth());
- TextFieldNavigationHandler.install(text);
- }
-
- /**
- * Creates the controls for the modifiers radio/checkbox buttons. Expects a
- * <code>GridLayout</code> with at least 3 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createModifierControls(Composite composite, int nColumns) {
- LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
-
- Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
- GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= nColumns - 2;
- control.setLayoutData(gd);
-
- DialogField.createEmptySpace(composite);
-
- if (fTypeKind == CLASS_TYPE) {
- DialogField.createEmptySpace(composite);
-
- control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
- gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan= nColumns - 2;
- control.setLayoutData(gd);
-
- DialogField.createEmptySpace(composite);
- }
- }
-
- /**
- * Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
- * with at least 3 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createSuperClassControls(Composite composite, int nColumns) {
- fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
- Text text= fSuperClassDialogField.getTextControl(null);
- LayoutUtil.setWidthHint(text, getMaxFieldWidth());
-
- JavaTypeCompletionProcessor superClassCompletionProcessor= new JavaTypeCompletionProcessor(false, false, true);
- superClassCompletionProcessor.setCompletionContextRequestor(new CompletionContextRequestor() {
- public StubTypeContext getStubTypeContext() {
- return getSuperClassStubTypeContext();
- }
- });
-
- ControlContentAssistHelper.createTextContentAssistant(text, superClassCompletionProcessor);
- TextFieldNavigationHandler.install(text);
- }
-
- /**
- * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
- * at least 3 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- */
- protected void createSuperInterfacesControls(Composite composite, int nColumns) {
- final String INTERFACE= "interface"; //$NON-NLS-1$
- fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
- final TableViewer tableViewer= fSuperInterfacesDialogField.getTableViewer();
- tableViewer.setColumnProperties(new String[] {INTERFACE});
-
- TableTextCellEditor cellEditor= new TableTextCellEditor(tableViewer, 0) {
- protected void doSetFocus() {
- if (text != null) {
- text.setFocus();
- text.setSelection(text.getText().length());
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
- }
- };
- JavaTypeCompletionProcessor superInterfaceCompletionProcessor= new JavaTypeCompletionProcessor(false, false, true);
- superInterfaceCompletionProcessor.setCompletionContextRequestor(new CompletionContextRequestor() {
- public StubTypeContext getStubTypeContext() {
- return getSuperInterfacesStubTypeContext();
- }
- });
- SubjectControlContentAssistant contentAssistant= ControlContentAssistHelper.createJavaContentAssistant(superInterfaceCompletionProcessor);
- Text cellEditorText= cellEditor.getText();
- ContentAssistHandler.createHandlerForText(cellEditorText, contentAssistant);
- TextFieldNavigationHandler.install(cellEditorText);
- cellEditor.setContentAssistant(contentAssistant);
-
- tableViewer.setCellEditors(new CellEditor[] { cellEditor });
- tableViewer.setCellModifier(new ICellModifier() {
- public void modify(Object element, String property, Object value) {
- if (element instanceof Item)
- element = ((Item) element).getData();
-
- ((InterfaceWrapper) element).interfaceName= (String) value;
- fSuperInterfacesDialogField.elementChanged(element);
- }
- public Object getValue(Object element, String property) {
- return ((InterfaceWrapper) element).interfaceName;
- }
- public boolean canModify(Object element, String property) {
- return true;
- }
- });
- tableViewer.getTable().addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent event) {
- if (event.keyCode == SWT.F2 && event.stateMask == 0) {
- ISelection selection= tableViewer.getSelection();
- if (! (selection instanceof IStructuredSelection))
- return;
- IStructuredSelection structuredSelection= (IStructuredSelection) selection;
- tableViewer.editElement(structuredSelection.getFirstElement(), 0);
- }
- }
- });
- GridData gd= (GridData) fSuperInterfacesDialogField.getListControl(null).getLayoutData();
- if (fTypeKind == CLASS_TYPE) {
- gd.heightHint= convertHeightInCharsToPixels(3);
- } else {
- gd.heightHint= convertHeightInCharsToPixels(6);
- }
- gd.grabExcessVerticalSpace= false;
- gd.widthHint= getMaxFieldWidth();
- }
-
- /**
- * Creates the controls for the preference page links. Expects a <code>GridLayout</code> with
- * at least 3 columns.
- *
- * @param composite the parent composite
- * @param nColumns number of columns to span
- *
- *
- */
- protected void createCommentControls(Composite composite, int nColumns) {
- Link link= new Link(composite, SWT.NONE);
- link.setText(NewWizardMessages.NewTypeWizardPage_addcomment_description);
- link.addSelectionListener(new TypeFieldsAdapter());
- link.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, nColumns, 1));
- DialogField.createEmptySpace(composite);
- fAddCommentButton.doFillIntoGrid(composite, nColumns - 1);
- }
-
-
-
- /**
- * Sets the focus on the type name input field.
- */
- protected void setFocus() {
- fTypeNameDialogField.setFocus();
- }
-
- // -------- TypeFieldsAdapter --------
-
- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter, SelectionListener {
-
- // -------- IStringButtonAdapter
- public void changeControlPressed(DialogField field) {
- typePageChangeControlPressed(field);
- }
-
- // -------- IListAdapter
- public void customButtonPressed(ListDialogField field, int index) {
- typePageCustomButtonPressed(field, index);
- }
-
- public void selectionChanged(ListDialogField field) {}
-
- // -------- IDialogFieldListener
- public void dialogFieldChanged(DialogField field) {
- typePageDialogFieldChanged(field);
- }
-
- public void doubleClicked(ListDialogField field) {
- }
-
-
- public void widgetSelected(SelectionEvent e) {
- typePageLinkActivated(e);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- typePageLinkActivated(e);
- }
- }
-
- private void typePageLinkActivated(SelectionEvent e) {
- IJavaScriptProject project= getJavaProject();
- if (project != null) {
- PreferenceDialog dialog= PreferencesUtil.createPropertyDialogOn(getShell(), project.getProject(), CodeTemplatePreferencePage.PROP_ID, null, null);
- dialog.open();
- } else {
- String title= NewWizardMessages.NewTypeWizardPage_configure_templates_title;
- String message= NewWizardMessages.NewTypeWizardPage_configure_templates_message;
- MessageDialog.openInformation(getShell(), title, message);
- }
- }
-
- private void typePageChangeControlPressed(DialogField field) {
- if (field == fPackageDialogField) {
- IPackageFragment pack= choosePackage();
- if (pack != null) {
- fPackageDialogField.setText(pack.getElementName());
- }
- } else if (field == fEnclosingTypeDialogField) {
- IType type= chooseEnclosingType();
- if (type != null) {
- fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
- }
- } else if (field == fSuperClassDialogField) {
- IType type= chooseSuperClass();
- if (type != null) {
- fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
- }
- }
- }
-
- private void typePageCustomButtonPressed(DialogField field, int index) {
- if (field == fSuperInterfacesDialogField) {
- List interfaces= fSuperInterfacesDialogField.getElements();
- if (!interfaces.isEmpty()) {
- Object element= interfaces.get(interfaces.size() - 1);
- fSuperInterfacesDialogField.editElement(element);
- }
- }
- }
-
- /*
- * A field on the type has changed. The fields' status and all dependent
- * status are updated.
- */
- private void typePageDialogFieldChanged(DialogField field) {
- String fieldName= null;
- if (field == fPackageDialogField) {
- fPackageStatus= packageChanged();
- updatePackageStatusLabel();
- fTypeNameStatus= typeNameChanged();
- fSuperClassStatus= superClassChanged();
- fieldName= PACKAGE;
- } else if (field == fEnclosingTypeDialogField) {
- fEnclosingTypeStatus= enclosingTypeChanged();
- fTypeNameStatus= typeNameChanged();
- fSuperClassStatus= superClassChanged();
- fieldName= ENCLOSING;
- } else if (field == fEnclosingTypeSelection) {
- updateEnableState();
- boolean isEnclosedType= isEnclosingTypeSelected();
- if (!isEnclosedType) {
- if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
- fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
- fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
- fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
- }
- if (fOtherMdfButtons.isSelected(STATIC_INDEX)) {
- fOtherMdfButtons.setSelection(STATIC_INDEX, false);
- }
- }
- fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType);
- fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType);
- fOtherMdfButtons.enableSelectionButton(STATIC_INDEX, isEnclosedType);
- fTypeNameStatus= typeNameChanged();
- fSuperClassStatus= superClassChanged();
- fieldName= ENCLOSINGSELECTION;
- } else if (field == fTypeNameDialogField) {
- fTypeNameStatus= typeNameChanged();
- fieldName= TYPENAME;
- } else if (field == fSuperClassDialogField) {
- fSuperClassStatus= superClassChanged();
- fieldName= SUPER;
- } else if (field == fSuperInterfacesDialogField) {
- fSuperInterfacesStatus= superInterfacesChanged();
- fieldName= INTERFACES;
- } else if (field == fOtherMdfButtons || field == fAccMdfButtons) {
- fModifierStatus= modifiersChanged();
- fieldName= MODIFIERS;
- } else {
- fieldName= METHODS;
- }
- // tell all others
- handleFieldChanged(fieldName);
- }
-
- // -------- update message ----------------
-
- /*
- * @see org.eclipse.wst.jsdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
- */
- protected void handleFieldChanged(String fieldName) {
- super.handleFieldChanged(fieldName);
- if (fieldName == CONTAINER) {
- fPackageStatus= packageChanged();
- fEnclosingTypeStatus= enclosingTypeChanged();
- fTypeNameStatus= typeNameChanged();
- fSuperClassStatus= superClassChanged();
- fSuperInterfacesStatus= superInterfacesChanged();
- }
- }
-
- // ---- set / get ----------------
-
- /**
- * Returns the text of the package input field.
- *
- * @return the text of the package input field
- */
- public String getPackageText() {
- return fPackageDialogField.getText();
- }
-
- /**
- * Returns the text of the enclosing type input field.
- *
- * @return the text of the enclosing type input field
- */
- public String getEnclosingTypeText() {
- return fEnclosingTypeDialogField.getText();
- }
-
-
- /**
- * Returns the package fragment corresponding to the current input.
- *
- * @return a package fragment or <code>null</code> if the input
- * could not be resolved.
- */
- public IPackageFragment getPackageFragment() {
- if (!isEnclosingTypeSelected()) {
- return fCurrPackage;
- } else {
- if (fCurrEnclosingType != null) {
- return fCurrEnclosingType.getPackageFragment();
- }
- }
- return null;
- }
-
- /**
- * Sets the package fragment to the given value. The method updates the model
- * and the text of the control.
- *
- * @param pack the package fragment to be set
- * @param canBeModified if <code>true</code> the package fragment is
- * editable; otherwise it is read-only.
- */
- public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
- fCurrPackage= pack;
- fCanModifyPackage= canBeModified;
- String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
- fPackageDialogField.setText(str);
- updateEnableState();
- }
-
- /**
- * Returns the enclosing type corresponding to the current input.
- *
- * @return the enclosing type or <code>null</code> if the enclosing type is
- * not selected or the input could not be resolved
- */
- public IType getEnclosingType() {
- if (isEnclosingTypeSelected()) {
- return fCurrEnclosingType;
- }
- return null;
- }
-
- /**
- * Sets the enclosing type. The method updates the underlying model
- * and the text of the control.
- *
- * @param type the enclosing type
- * @param canBeModified if <code>true</code> the enclosing type field is
- * editable; otherwise it is read-only.
- */
- public void setEnclosingType(IType type, boolean canBeModified) {
- fCurrEnclosingType= type;
- fCanModifyEnclosingType= canBeModified;
- String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
- fEnclosingTypeDialogField.setText(str);
- updateEnableState();
- }
-
- /**
- * Returns the selection state of the enclosing type checkbox.
- *
- * @return the selection state of the enclosing type checkbox
- */
- public boolean isEnclosingTypeSelected() {
- return fEnclosingTypeSelection.isSelected();
- }
-
- /**
- * Sets the enclosing type checkbox's selection state.
- *
- * @param isSelected the checkbox's selection state
- * @param canBeModified if <code>true</code> the enclosing type checkbox is
- * modifiable; otherwise it is read-only.
- */
- public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
- fEnclosingTypeSelection.setSelection(isSelected);
- fEnclosingTypeSelection.setEnabled(canBeModified);
- updateEnableState();
- }
-
- /**
- * Returns the type name entered into the type input field.
- *
- * @return the type name
- */
- public String getTypeName() {
- return fTypeNameDialogField.getText();
- }
-
- /**
- * Sets the type name input field's text to the given value. Method doesn't update
- * the model.
- *
- * @param name the new type name
- * @param canBeModified if <code>true</code> the type name field is
- * editable; otherwise it is read-only.
- */
- public void setTypeName(String name, boolean canBeModified) {
- fTypeNameDialogField.setText(name);
- fTypeNameDialogField.setEnabled(canBeModified);
- }
-
- /**
- * Returns the selected modifiers.
- *
- * @return the selected modifiers
- * @see Flags
- */
- public int getModifiers() {
- int mdf= 0;
- if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
- mdf+= F_PUBLIC;
- } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
- mdf+= F_PRIVATE;
- }
- if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX)) {
- mdf+= F_ABSTRACT;
- }
- if (fOtherMdfButtons.isSelected(STATIC_INDEX)) {
- mdf+= F_STATIC;
- }
- return mdf;
- }
-
- /**
- * Sets the modifiers.
- *
- * @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
- * <code>F_PROTECTED</code>, <code>F_ABSTRACT</code>, <code>F_FINAL</code>
- * or <code>F_STATIC</code> or a valid combination.
- * @param canBeModified if <code>true</code> the modifier fields are
- * editable; otherwise they are read-only
- * @see Flags
- */
- public void setModifiers(int modifiers, boolean canBeModified) {
- if (Flags.isPublic(modifiers)) {
- fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
- } else if (Flags.isPrivate(modifiers)) {
- fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
- } else {
- fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
- }
- if (Flags.isAbstract(modifiers)) {
- fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
- }
- if (Flags.isStatic(modifiers)) {
- fOtherMdfButtons.setSelection(STATIC_INDEX, true);
- }
-
- fAccMdfButtons.setEnabled(canBeModified);
- fOtherMdfButtons.setEnabled(canBeModified);
- }
-
- /**
- * Returns the content of the superclass input field.
- *
- * @return the superclass name
- */
- public String getSuperClass() {
- return fSuperClassDialogField.getText();
- }
-
- /**
- * Sets the super class name.
- *
- * @param name the new superclass name
- * @param canBeModified if <code>true</code> the superclass name field is
- * editable; otherwise it is read-only.
- */
- public void setSuperClass(String name, boolean canBeModified) {
- fSuperClassDialogField.setText(name);
- fSuperClassDialogField.setEnabled(canBeModified);
- }
-
- /**
- * Returns the chosen super interfaces.
- *
- * @return a list of chosen super interfaces. The list's elements
- * are of type <code>String</code>
- */
- public List getSuperInterfaces() {
- List interfaces= fSuperInterfacesDialogField.getElements();
- ArrayList result= new ArrayList(interfaces.size());
- for (Iterator iter= interfaces.iterator(); iter.hasNext();) {
- InterfaceWrapper wrapper= (InterfaceWrapper) iter.next();
- result.add(wrapper.interfaceName);
- }
- return result;
- }
-
- /**
- * Sets the super interfaces.
- *
- * @param interfacesNames a list of super interface. The method requires that
- * the list's elements are of type <code>String</code>
- * @param canBeModified if <code>true</code> the super interface field is
- * editable; otherwise it is read-only.
- */
- public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
- ArrayList interfaces= new ArrayList(interfacesNames.size());
- for (Iterator iter= interfacesNames.iterator(); iter.hasNext();) {
- interfaces.add(new InterfaceWrapper((String) iter.next()));
- }
- fSuperInterfacesDialogField.setElements(interfaces);
- fSuperInterfacesDialogField.setEnabled(canBeModified);
- }
-
- /**
- * Adds a super interface to the end of the list and selects it if it is not in the list yet.
- *
- * @param superInterface the fully qualified type name of the interface.
- * @return returns <code>true</code>if the interfaces has been added, <code>false</code>
- * if the interface already is in the list.
- *
- */
- public boolean addSuperInterface(String superInterface) {
- return fSuperInterfacesDialogField.addElement(new InterfaceWrapper(superInterface));
- }
-
-
- /**
- * Sets 'Add comment' checkbox. The value set will only be used when creating source when
- * the comment control is enabled (see {@link #enableCommentControl(boolean)}
- *
- * @param doAddComments if <code>true</code>, comments are added.
- * @param canBeModified if <code>true</code> check box is
- * editable; otherwise it is read-only.
- *
- */
- public void setAddComments(boolean doAddComments, boolean canBeModified) {
- fAddCommentButton.setSelection(doAddComments);
- fAddCommentButton.setEnabled(canBeModified);
- }
-
- /**
- * Sets to use the 'Add comment' checkbox value. Clients that use the 'Add comment' checkbox
- * additionally have to enable the control. This has been added for backwards compatibility.
- *
- * @param useAddCommentValue if <code>true</code>,
- *
- */
- public void enableCommentControl(boolean useAddCommentValue) {
- fUseAddCommentButtonValue= useAddCommentValue;
- }
-
-
- /**
- * Returns if comments are added. This method can be overridden by clients.
- * The selection of the comment control is taken if enabled (see {@link #enableCommentControl(boolean)}, otherwise
- * the settings as specified in the preferences is used.
- *
- * @return Returns <code>true</code> if comments can be added
- *
- */
- public boolean isAddComments() {
- if (fUseAddCommentButtonValue) {
- return fAddCommentButton.isSelected();
- }
- return StubUtility.doAddComments(getJavaProject());
- }
-
- /**
- * Returns the resource handle that corresponds to the compilation unit to was or
- * will be created or modified.
- * @return A resource or null if the page contains illegal values.
- *
- */
- public IResource getModifiedResource() {
- IType enclosing= getEnclosingType();
- if (enclosing != null) {
- return enclosing.getResource();
- }
- IPackageFragment pack= getPackageFragment();
- if (pack != null) {
- String cuName= getCompilationUnitName(getTypeNameWithoutParameters());
- return pack.getJavaScriptUnit(cuName).getResource();
- }
- return null;
- }
-
- // ----------- validation ----------
-
- /*
- * @see org.eclipse.wst.jsdt.ui.wizards.NewContainerWizardPage#containerChanged()
- */
- protected IStatus containerChanged() {
- IStatus status= super.containerChanged();
- IPackageFragmentRoot root= getPackageFragmentRoot();
- if ((fTypeKind == ANNOTATION_TYPE || fTypeKind == ENUM_TYPE) && !status.matches(IStatus.ERROR)) {
- if (root != null && !JavaModelUtil.is50OrHigher(root.getJavaScriptProject())) {
- // error as createType will fail otherwise (bug 96928)
- return new StatusInfo(IStatus.ERROR, Messages.format(NewWizardMessages.NewTypeWizardPage_warning_NotJDKCompliant, root.getJavaScriptProject().getElementName()));
- }
- if (fTypeKind == ENUM_TYPE) {
- try {
- // if findType(...) == null then Enum is unavailable
- if (findType(root.getJavaScriptProject(), "java.lang.Enum") == null) //$NON-NLS-1$
- return new StatusInfo(IStatus.WARNING, NewWizardMessages.NewTypeWizardPage_warning_EnumClassNotFound);
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- }
- }
-
- fCurrPackageCompletionProcessor.setPackageFragmentRoot(root);
- if (root != null) {
- fEnclosingTypeCompletionProcessor.setPackageFragment(root.getPackageFragment("")); //$NON-NLS-1$
- }
- return status;
- }
-
- /**
- * A hook method that gets called when the package field has changed. The method
- * validates the package name and returns the status of the validation. The validation
- * also updates the package fragment model.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus packageChanged() {
- StatusInfo status= new StatusInfo();
- IPackageFragmentRoot root= getPackageFragmentRoot();
- fPackageDialogField.enableButton(root != null);
-
- IJavaScriptProject project= root != null ? root.getJavaScriptProject() : null;
-
- String packName= getPackageText();
- if (packName.length() > 0) {
- IStatus val= validatePackageName(packName, project);
- if (val.getSeverity() == IStatus.ERROR) {
- status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName, val.getMessage()));
- return status;
- } else if (val.getSeverity() == IStatus.WARNING) {
- status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
- // continue
- }
- } else {
- status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
- }
-
- if (project != null) {
- fCurrPackage= root.getPackageFragment(packName);
- } else {
- status.setError(""); //$NON-NLS-1$
- }
- return status;
- }
-
- /*
- * Updates the 'default' label next to the package field.
- */
- private void updatePackageStatusLabel() {
- String packName= getPackageText();
-
- if (packName.length() == 0) {
- fPackageDialogField.setStatus(NewWizardMessages.NewTypeWizardPage_default);
- } else {
- fPackageDialogField.setStatus(""); //$NON-NLS-1$
- }
- }
-
- /*
- * Updates the enable state of buttons related to the enclosing type selection checkbox.
- */
- private void updateEnableState() {
- boolean enclosing= isEnclosingTypeSelected();
- fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
- fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
- if (fTypeKind == ENUM_TYPE || fTypeKind == ANNOTATION_TYPE) {
- fOtherMdfButtons.enableSelectionButton(ABSTRACT_INDEX, enclosing);
- fOtherMdfButtons.enableSelectionButton(ENUM_ANNOT_STATIC_INDEX, enclosing);
- }
- }
-
- /**
- * Hook method that gets called when the enclosing type name has changed. The method
- * validates the enclosing type and returns the status of the validation. It also updates the
- * enclosing type model.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus enclosingTypeChanged() {
- StatusInfo status= new StatusInfo();
- fCurrEnclosingType= null;
-
- IPackageFragmentRoot root= getPackageFragmentRoot();
-
- fEnclosingTypeDialogField.enableButton(root != null);
- if (root == null) {
- status.setError(""); //$NON-NLS-1$
- return status;
- }
-
- String enclName= getEnclosingTypeText();
- if (enclName.length() == 0) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeEnterName);
- return status;
- }
- try {
- IType type= findType(root.getJavaScriptProject(), enclName);
- if (type == null) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists);
- return status;
- }
-
- if (type.getJavaScriptUnit() == null) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotInCU);
- return status;
- }
- if (!JavaModelUtil.isEditable(type.getJavaScriptUnit())) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingNotEditable);
- return status;
- }
-
- fCurrEnclosingType= type;
- IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
- if (!enclosingRoot.equals(root)) {
- status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_EnclosingNotInSourceFolder);
- }
- return status;
- } catch (JavaScriptModelException e) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnclosingTypeNotExists);
- JavaScriptPlugin.log(e);
- return status;
- }
- }
-
- private IType findType(IJavaScriptProject project, String typeName) throws JavaScriptModelException {
- if (project.exists()) {
- return project.findType(typeName);
- }
- return null;
- }
-
- private String getTypeNameWithoutParameters() {
- String typeNameWithParameters= getTypeName();
- int angleBracketOffset= typeNameWithParameters.indexOf('<');
- if (angleBracketOffset == -1) {
- return typeNameWithParameters;
- } else {
- return typeNameWithParameters.substring(0, angleBracketOffset);
- }
- }
-
- /**
- * Hook method that is called when evaluating the name of the compilation unit to create. By default, a file extension
- * <code>java</code> is added to the given type name, but implementors can override this behavior.
- *
- * @param typeName the name of the type to create the compilation unit for.
- * @return the name of the compilation unit to be created for the given name
- *
- *
- */
- protected String getCompilationUnitName(String typeName) {
- return typeName + JavaModelUtil.DEFAULT_CU_SUFFIX;
- }
-
-
- /**
- * Hook method that gets called when the type name has changed. The method validates the
- * type name and returns the status of the validation.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus typeNameChanged() {
- StatusInfo status= new StatusInfo();
- fCurrType= null;
- String typeNameWithParameters= getTypeName();
- // must not be empty
- if (typeNameWithParameters.length() == 0) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
- return status;
- }
-
- String typeName= getTypeNameWithoutParameters();
- if (typeName.indexOf('.') != -1) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
- return status;
- }
-
- IJavaScriptProject project= getJavaProject();
- IStatus val= validateJavaTypeName(typeName, project);
- if (val.getSeverity() == IStatus.ERROR) {
- status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
- return status;
- } else if (val.getSeverity() == IStatus.WARNING) {
- status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
- // continue checking
- }
-
- // must not exist
- if (!isEnclosingTypeSelected()) {
- IPackageFragment pack= getPackageFragment();
- if (pack != null) {
- IJavaScriptUnit cu= pack.getJavaScriptUnit(getCompilationUnitName(typeName));
- fCurrType= cu.getType(typeName);
- IResource resource= cu.getResource();
-
- if (resource.exists()) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
- return status;
- }
- URI location= resource.getLocationURI();
- if (location != null) {
- try {
- IFileStore store= EFS.getStore(location);
- if (store.fetchInfo().exists()) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
- return status;
- }
- } catch (CoreException e) {
- status.setError(Messages.format(
- NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
- Resources.getLocationString(resource)));
- }
- }
- }
- } else {
- IType type= getEnclosingType();
- if (type != null) {
- fCurrType= type.getType(typeName);
- if (fCurrType.exists()) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
- return status;
- }
- }
- }
-
- if (!typeNameWithParameters.equals(typeName) && project != null) {
- if (!JavaModelUtil.is50OrHigher(project)) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
- return status;
- }
- String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(typeDeclaration.toCharArray());
- parser.setProject(project);
- JavaScriptUnit compilationUnit= (JavaScriptUnit) parser.createAST(null);
- IProblem[] problems= compilationUnit.getProblems();
- if (problems.length > 0) {
- status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
- return status;
- }
- }
- return status;
- }
-
- /**
- * Hook method that gets called when the superclass name has changed. The method
- * validates the superclass name and returns the status of the validation.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus superClassChanged() {
- StatusInfo status= new StatusInfo();
- IPackageFragmentRoot root= getPackageFragmentRoot();
- fSuperClassDialogField.enableButton(root != null);
-
- fSuperClassStubTypeContext= null;
-
- String sclassName= getSuperClass();
- if (sclassName.length() == 0) {
- // accept the empty field (stands for java.lang.Object)
- return status;
- }
-
- if (root != null) {
- Type type= TypeContextChecker.parseSuperClass(sclassName);
- if (type == null) {
- status.setError(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperClassName);
- return status;
- }
- } else {
- status.setError(""); //$NON-NLS-1$
- }
- return status;
- }
-
- private StubTypeContext getSuperClassStubTypeContext() {
- if (fSuperClassStubTypeContext == null) {
- String typeName;
- if (fCurrType != null) {
- typeName= getTypeName();
- } else {
- typeName= JavaTypeCompletionProcessor.DUMMY_CLASS_NAME;
- }
- fSuperClassStubTypeContext= TypeContextChecker.createSuperClassStubTypeContext(typeName, getEnclosingType(), getPackageFragment());
- }
- return fSuperClassStubTypeContext;
- }
-
- /**
- * Hook method that gets called when the list of super interface has changed. The method
- * validates the super interfaces and returns the status of the validation.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus superInterfacesChanged() {
- StatusInfo status= new StatusInfo();
-
- IPackageFragmentRoot root= getPackageFragmentRoot();
- fSuperInterfacesDialogField.enableButton(0, root != null);
-
- if (root != null) {
- List elements= fSuperInterfacesDialogField.getElements();
- int nElements= elements.size();
- for (int i= 0; i < nElements; i++) {
- String intfname= ((InterfaceWrapper) elements.get(i)).interfaceName;
- Type type= TypeContextChecker.parseSuperInterface(intfname);
- if (type == null) {
- status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperInterfaceName, intfname));
- return status;
- }
- }
- }
- return status;
- }
-
- private StubTypeContext getSuperInterfacesStubTypeContext() {
- if (fSuperInterfaceStubTypeContext == null) {
- String typeName;
- if (fCurrType != null) {
- typeName= getTypeName();
- } else {
- typeName= JavaTypeCompletionProcessor.DUMMY_CLASS_NAME;
- }
- fSuperInterfaceStubTypeContext= TypeContextChecker.createSuperInterfaceStubTypeContext(typeName, getEnclosingType(), getPackageFragment());
- }
- return fSuperInterfaceStubTypeContext;
- }
-
- /**
- * Hook method that gets called when the modifiers have changed. The method validates
- * the modifiers and returns the status of the validation.
- * <p>
- * Subclasses may extend this method to perform their own validation.
- * </p>
- *
- * @return the status of the validation
- */
- protected IStatus modifiersChanged() {
- StatusInfo status= new StatusInfo();
- return status;
- }
-
- // selection dialogs
-
- /**
- * Opens a selection dialog that allows to select a package.
- *
- * @return returns the selected package or <code>null</code> if the dialog has been canceled.
- * The caller typically sets the result to the package input field.
- * <p>
- * Clients can override this method if they want to offer a different dialog.
- * </p>
- *
- *
- */
- protected IPackageFragment choosePackage() {
- IPackageFragmentRoot froot= getPackageFragmentRoot();
- IJavaScriptElement[] packages= null;
- try {
- if (froot != null && froot.exists()) {
- packages= froot.getChildren();
- }
- } catch (JavaScriptModelException e) {
- JavaScriptPlugin.log(e);
- }
- if (packages == null) {
- packages= new IJavaScriptElement[0];
- }
-
- ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaScriptElementLabelProvider(JavaScriptElementLabelProvider.SHOW_DEFAULT));
- dialog.setIgnoreCase(false);
- dialog.setTitle(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_title);
- dialog.setMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_description);
- dialog.setEmptyListMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_empty);
- dialog.setElements(packages);
- dialog.setHelpAvailable(false);
-
- IPackageFragment pack= getPackageFragment();
- if (pack != null) {
- dialog.setInitialSelections(new Object[] { pack });
- }
-
- if (dialog.open() == Window.OK) {
- return (IPackageFragment) dialog.getFirstResult();
- }
- return null;
- }
-
- /**
- * Opens a selection dialog that allows to select an enclosing type.
- *
- * @return returns the selected type or <code>null</code> if the dialog has been canceled.
- * The caller typically sets the result to the enclosing type input field.
- * <p>
- * Clients can override this method if they want to offer a different dialog.
- * </p>
- *
- *
- */
- protected IType chooseEnclosingType() {
- IPackageFragmentRoot root= getPackageFragmentRoot();
- if (root == null) {
- return null;
- }
-
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { root });
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(),
- false, getWizard().getContainer(), scope, IJavaScriptSearchConstants.TYPE);
- dialog.setTitle(NewWizardMessages.NewTypeWizardPage_ChooseEnclosingTypeDialog_title);
- dialog.setMessage(NewWizardMessages.NewTypeWizardPage_ChooseEnclosingTypeDialog_description);
- dialog.setInitialPattern(Signature.getSimpleName(getEnclosingTypeText()));
-
- if (dialog.open() == Window.OK) {
- return (IType) dialog.getFirstResult();
- }
- return null;
- }
-
- /**
- * Opens a selection dialog that allows to select a super class.
- *
- * @return returns the selected type or <code>null</code> if the dialog has been canceled.
- * The caller typically sets the result to the super class input field.
- * <p>
- * Clients can override this method if they want to offer a different dialog.
- * </p>
- *
- *
- */
- protected IType chooseSuperClass() {
- IJavaScriptProject project= getJavaProject();
- if (project == null) {
- return null;
- }
-
- IJavaScriptElement[] elements= new IJavaScriptElement[] { project };
- IJavaScriptSearchScope scope= SearchEngine.createJavaSearchScope(elements);
-
- FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
- getWizard().getContainer(), scope, IJavaScriptSearchConstants.CLASS);
- dialog.setTitle(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_title);
- dialog.setMessage(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_message);
- dialog.setInitialPattern(getSuperClass());
-
- if (dialog.open() == Window.OK) {
- return (IType) dialog.getFirstResult();
- }
- return null;
- }
-
- // ---- creation ----------------
-
- /**
- * Creates the new type using the entered field values.
- *
- * @param monitor a progress monitor to report progress.
- * @throws CoreException Thrown when the creation failed.
- * @throws InterruptedException Thrown when the operation was canceled.
- */
- public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
-
- monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);
-
- IPackageFragmentRoot root= getPackageFragmentRoot();
- IPackageFragment pack= getPackageFragment();
- if (pack == null) {
- pack= root.getPackageFragment(""); //$NON-NLS-1$
- }
-
- if (!pack.exists()) {
- String packName= pack.getElementName();
- pack= root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
-
- boolean needsSave;
- IJavaScriptUnit connectedCU= null;
-
- try {
- String typeName= getTypeNameWithoutParameters();
-
- boolean isInnerClass= isEnclosingTypeSelected();
-
- IType createdType;
- ImportsManager imports;
- int indent= 0;
-
- Set /* String (import names) */ existingImports;
-
- String lineDelimiter= null;
- if (!isInnerClass) {
- lineDelimiter= StubUtility.getLineDelimiterUsed(pack.getJavaScriptProject());
-
- String cuName= getCompilationUnitName(typeName);
- IJavaScriptUnit parentCU= pack.createCompilationUnit(cuName, "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$
- // create a working copy with a new owner
-
- needsSave= true;
- parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy
- connectedCU= parentCU;
-
- IBuffer buffer= parentCU.getBuffer();
-
- String simpleTypeStub= constructSimpleTypeStub();
- String cuContent= constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
- buffer.setContents(cuContent);
-
- JavaScriptUnit astRoot= createASTForImports(parentCU);
- existingImports= getExistingImports(astRoot);
-
- imports= new ImportsManager(astRoot);
- // add an import that will be removed again. Having this import solves 14661
- imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));
-
- String typeContent= constructTypeStub(parentCU, imports, lineDelimiter);
-
- int index= cuContent.lastIndexOf(simpleTypeStub);
- if (index == -1) {
- AbstractTypeDeclaration typeNode= (AbstractTypeDeclaration) astRoot.types().get(0);
- int start= ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
- int end= typeNode.getStartPosition() + typeNode.getLength();
- buffer.replace(start, end - start, typeContent);
- } else {
- buffer.replace(index, simpleTypeStub.length(), typeContent);
- }
-
- createdType= parentCU.getType(typeName);
- } else {
- IType enclosingType= getEnclosingType();
-
- IJavaScriptUnit parentCU= enclosingType.getJavaScriptUnit();
-
- needsSave= !parentCU.isWorkingCopy();
- parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy
- connectedCU= parentCU;
-
- JavaScriptUnit astRoot= createASTForImports(parentCU);
- imports= new ImportsManager(astRoot);
- existingImports= getExistingImports(astRoot);
-
-
- // add imports that will be removed again. Having the imports solves 14661
- IType[] topLevelTypes= parentCU.getTypes();
- for (int i= 0; i < topLevelTypes.length; i++) {
- imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
- }
-
- lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
- StringBuffer content= new StringBuffer();
-
- String comment= getTypeComment(parentCU, lineDelimiter);
- if (comment != null) {
- content.append(comment);
- content.append(lineDelimiter);
- }
-
- content.append(constructTypeStub(parentCU, imports, lineDelimiter));
- IJavaScriptElement sibling= null;
-
- IJavaScriptElement[] elems= enclosingType.getChildren();
- sibling = elems.length > 0 ? elems[0] : null;
-
- createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 2));
-
- indent= StubUtility.getIndentUsed(enclosingType) + 1;
- }
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
-
- // add imports for superclass/interfaces, so types can be resolved correctly
-
- IJavaScriptUnit cu= createdType.getJavaScriptUnit();
-
- imports.create(false, new SubProgressMonitor(monitor, 1));
-
- JavaModelUtil.reconcile(cu);
-
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
-
- // set up again
- JavaScriptUnit astRoot= createASTForImports(imports.getCompilationUnit());
- imports= new ImportsManager(astRoot);
-
- createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
-
- // add imports
- imports.create(false, new SubProgressMonitor(monitor, 1));
-
- removeUnusedImports(cu, existingImports, false);
-
- JavaModelUtil.reconcile(cu);
-
- ISourceRange range= createdType.getSourceRange();
-
- IBuffer buf= cu.getBuffer();
- String originalContent= buf.getText(range.getOffset(), range.getLength());
-
- String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaScriptProject());
- formattedContent= Strings.trimLeadingTabsAndSpaces(formattedContent);
- buf.replace(range.getOffset(), range.getLength(), formattedContent);
- if (!isInnerClass) {
- String fileComment= getFileComment(cu);
- if (fileComment != null && fileComment.length() > 0) {
- buf.replace(0, 0, fileComment + lineDelimiter);
- }
- }
- fCreatedType= createdType;
-
- if (needsSave) {
- cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
- } else {
- monitor.worked(1);
- }
-
- } finally {
- if (connectedCU != null) {
- connectedCU.discardWorkingCopy();
- }
- monitor.done();
- }
- }
-
- private JavaScriptUnit createASTForImports(IJavaScriptUnit cu) {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(cu);
- parser.setResolveBindings(false);
- parser.setFocalPosition(0);
- return (JavaScriptUnit) parser.createAST(null);
- }
-
-
- private Set /* String */ getExistingImports(JavaScriptUnit root) {
- List imports= root.imports();
- Set res= new HashSet(imports.size());
- for (int i= 0; i < imports.size(); i++) {
- res.add(ASTNodes.asString((ImportDeclaration) imports.get(i)));
- }
- return res;
- }
-
- private void removeUnusedImports(IJavaScriptUnit cu, Set existingImports, boolean needsSave) throws CoreException {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setSource(cu);
- parser.setResolveBindings(true);
-
- JavaScriptUnit root= (JavaScriptUnit) parser.createAST(null);
- if (root.getProblems().length == 0) {
- return;
- }
-
- List importsDecls= root.imports();
- if (importsDecls.isEmpty()) {
- return;
- }
- ImportsManager imports= new ImportsManager(root);
-
- int importsEnd= ASTNodes.getExclusiveEnd((ASTNode) importsDecls.get(importsDecls.size() - 1));
- IProblem[] problems= root.getProblems();
- for (int i= 0; i < problems.length; i++) {
- IProblem curr= problems[i];
- if (curr.getSourceEnd() < importsEnd) {
- int id= curr.getID();
- if( id == IProblem.NotVisibleType) { // not visible problems hide unused -> remove both
- int pos= curr.getSourceStart();
- for (int k= 0; k < importsDecls.size(); k++) {
- ImportDeclaration decl= (ImportDeclaration) importsDecls.get(k);
- if (decl.getStartPosition() <= pos && pos < decl.getStartPosition() + decl.getLength()) {
- if (existingImports.isEmpty() || !existingImports.contains(ASTNodes.asString(decl))) {
- String name= decl.getName().getFullyQualifiedName();
- if (decl.isOnDemand()) {
- name += ".*"; //$NON-NLS-1$
- }
- if (decl.isStatic()) {
- imports.removeStaticImport(name);
- } else {
- imports.removeImport(name);
- }
- }
- break;
- }
- }
- }
- }
- }
- imports.create(needsSave, null);
- }
-
- /**
- * Uses the New JavaScript file template from the code template page to generate a
- * compilation unit with the given type content.
- * @param cu The new created compilation unit
- * @param typeContent The content of the type, including signature and type
- * body.
- * @param lineDelimiter The line delimiter to be used.
- * @return String Returns the result of evaluating the new file template
- * with the given type content.
- * @throws CoreException
- *
- */
- protected String constructCUContent(IJavaScriptUnit cu, String typeContent, String lineDelimiter) throws CoreException {
- String fileComment= getFileComment(cu, lineDelimiter);
- String typeComment= getTypeComment(cu, lineDelimiter);
- IPackageFragment pack= (IPackageFragment) cu.getParent();
- String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
- if (content != null) {
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setProject(cu.getJavaScriptProject());
- parser.setSource(content.toCharArray());
- JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(null);
- if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
- return content;
- }
- }
- StringBuffer buf= new StringBuffer();
- if (!pack.isDefaultPackage()) {
- buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
- }
- buf.append(lineDelimiter).append(lineDelimiter);
- if (typeComment != null) {
- buf.append(typeComment).append(lineDelimiter);
- }
- buf.append(typeContent);
- return buf.toString();
- }
-
-
- /**
- * Returns the created type or <code>null</code> is the type has not been created yet. The method
- * only returns a valid type after <code>createType</code> has been called.
- *
- * @return the created type
- * @see #createType(IProgressMonitor)
- */
- public IType getCreatedType() {
- return fCreatedType;
- }
-
- // ---- construct CU body----------------
-
- private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
- String superclass= getSuperClass();
- if (fTypeKind == CLASS_TYPE && superclass.length() > 0 && !"java.lang.Object".equals(superclass)) { //$NON-NLS-1$
- buf.append(" extends "); //$NON-NLS-1$
-
- ITypeBinding binding= null;
- if (fCurrType != null) {
- binding= TypeContextChecker.resolveSuperClass(superclass, fCurrType, getSuperClassStubTypeContext());
- }
- if (binding != null) {
- buf.append(imports.addImport(binding));
- } else {
- buf.append(imports.addImport(superclass));
- }
- }
- }
-
- private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
- List interfaces= getSuperInterfaces();
- int last= interfaces.size() - 1;
- if (last >= 0) {
- if (fTypeKind != INTERFACE_TYPE) {
- buf.append(" implements "); //$NON-NLS-1$
- } else {
- buf.append(" extends "); //$NON-NLS-1$
- }
- String[] intfs= (String[]) interfaces.toArray(new String[interfaces.size()]);
- ITypeBinding[] bindings;
- if (fCurrType != null) {
- bindings= TypeContextChecker.resolveSuperInterfaces(intfs, fCurrType, getSuperInterfacesStubTypeContext());
- } else {
- bindings= new ITypeBinding[intfs.length];
- }
- for (int i= 0; i <= last; i++) {
- ITypeBinding binding= bindings[i];
- if (binding != null) {
- buf.append(imports.addImport(binding));
- } else {
- buf.append(imports.addImport(intfs[i]));
- }
- if (i < last) {
- buf.append(',');
- }
- }
- }
- }
-
-
- private String constructSimpleTypeStub() {
- StringBuffer buf= new StringBuffer("public class "); //$NON-NLS-1$
- buf.append(getTypeName());
- buf.append("{ }"); //$NON-NLS-1$
- return buf.toString();
- }
-
- /*
- * Called from createType to construct the source for this type
- */
- private String constructTypeStub(IJavaScriptUnit parentCU, ImportsManager imports, String lineDelimiter) throws CoreException {
- StringBuffer buf= new StringBuffer();
-
- int modifiers= getModifiers();
- buf.append(Flags.toString(modifiers));
- if (modifiers != 0) {
- buf.append(' ');
- }
- String type= ""; //$NON-NLS-1$
- String templateID= ""; //$NON-NLS-1$
- switch (fTypeKind) {
- case CLASS_TYPE:
- type= "class "; //$NON-NLS-1$
- templateID= CodeGeneration.CLASS_BODY_TEMPLATE_ID;
- break;
- }
- buf.append(type);
- buf.append(getTypeName());
- writeSuperClass(buf, imports);
- writeSuperInterfaces(buf, imports);
-
- buf.append(" {").append(lineDelimiter); //$NON-NLS-1$
- String typeBody= CodeGeneration.getTypeBody(templateID, parentCU, getTypeName(), lineDelimiter);
- if (typeBody != null) {
- buf.append(typeBody);
- } else {
- buf.append(lineDelimiter);
- }
- buf.append('}').append(lineDelimiter);
- return buf.toString();
- }
-
- /**
- * Hook method that gets called from <code>createType</code> to support adding of
- * unanticipated methods, fields, and inner types to the created type.
- * <p>
- * Implementers can use any methods defined on <code>IType</code> to manipulate the
- * new type.
- * </p>
- * <p>
- * The source code of the new type will be formatted using the platform's formatter. Needed
- * imports are added by the wizard at the end of the type creation process using the given
- * import manager.
- * </p>
- *
- * @param newType the new type created via <code>createType</code>
- * @param imports an import manager which can be used to add new imports
- * @param monitor a progress monitor to report progress. Must not be <code>null</code>
- * @throws CoreException thrown when creation of the type members failed
- *
- * @see #createType(IProgressMonitor)
- */
- protected void createTypeMembers(IType newType, final ImportsManager imports, IProgressMonitor monitor) throws CoreException {
- // default implementation does nothing
- // example would be
- // String mainMathod= "public void foo(Vector vec) {}"
- // createdType.createMethod(main, null, false, null);
- // imports.addImport("java.lang.Vector");
- }
-
-
- /**
- * @param parentCU the current compilation unit
- * @return returns the file template or <code>null</code>
- * @deprecated Instead of file templates, the new type code template
- * specifies the stub for a compilation unit.
- */
- protected String getFileComment(IJavaScriptUnit parentCU) {
- return null;
- }
-
- /**
- * Hook method that gets called from <code>createType</code> to retrieve
- * a file comment. This default implementation returns the content of the
- * 'file comment' template or <code>null</code> if no comment should be created.
- *
- * @param parentCU the parent compilation unit
- * @param lineDelimiter the line delimiter to use
- * @return the file comment or <code>null</code> if a file comment
- * is not desired
- * @throws CoreException
- *
- *
- */
- protected String getFileComment(IJavaScriptUnit parentCU, String lineDelimiter) throws CoreException {
- if (isAddComments()) {
- return CodeGeneration.getFileComment(parentCU, lineDelimiter);
- }
- return null;
-
- }
-
- private boolean isValidComment(String template) {
- IScanner scanner= ToolFactory.createScanner(true, false, false, false);
- scanner.setSource(template.toCharArray());
- try {
- int next= scanner.getNextToken();
- while (TokenScanner.isComment(next)) {
- next= scanner.getNextToken();
- }
- return next == ITerminalSymbols.TokenNameEOF;
- } catch (InvalidInputException e) {
- }
- return false;
- }
-
- /**
- * Hook method that gets called from <code>createType</code> to retrieve
- * a type comment. This default implementation returns the content of the
- * 'type comment' template.
- *
- * @param parentCU the parent compilation unit
- * @param lineDelimiter the line delimiter to use
- * @return the type comment or <code>null</code> if a type comment
- * is not desired
- *
- *
- */
- protected String getTypeComment(IJavaScriptUnit parentCU, String lineDelimiter) {
- if (isAddComments()) {
- try {
- StringBuffer typeName= new StringBuffer();
- if (isEnclosingTypeSelected()) {
- typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
- }
- typeName.append(getTypeNameWithoutParameters());
- String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter);
- if (comment != null && isValidComment(comment)) {
- return comment;
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- }
- }
- return null;
- }
-
- /**
- * Returns the string resulting from evaluation the given template in
- * the context of the given compilation unit. This accesses the normal
- * template page, not the code templates. To use code templates use
- * <code>constructCUContent</code> to construct a compilation unit stub or
- * getTypeComment for the comment of the type.
- *
- * @param name the template to be evaluated
- * @param parentCU the templates evaluation context
- * @param pos a source offset into the parent compilation unit. The
- * template is evaluated at the given source offset
- * @return return the template with the given name or <code>null</code> if the template could not be found.
- */
- protected String getTemplate(String name, IJavaScriptUnit parentCU, int pos) {
- try {
- Template template= JavaScriptPlugin.getDefault().getTemplateStore().findTemplate(name);
- if (template != null) {
- return JavaContext.evaluateTemplate(template, parentCU, pos);
- }
- } catch (CoreException e) {
- JavaScriptPlugin.log(e);
- } catch (BadLocationException e) {
- JavaScriptPlugin.log(e);
- } catch (TemplateException e) {
- JavaScriptPlugin.log(e);
- }
- return null;
- }
-
-
- /**
- * Creates the bodies of all unimplemented methods and constructors and adds them to the type.
- * Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
- * needed method and constructors.
- *
- * @param type the type for which the new methods and constructor are to be created
- * @param doConstructors if <code>true</code> unimplemented constructors are created
- * @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
- * @param imports an import manager to add all needed import statements
- * @param monitor a progress monitor to report progress
- * @return the created methods.
- * @throws CoreException thrown when the creation fails.
- */
- protected IFunction[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
- final IJavaScriptUnit cu= type.getJavaScriptUnit();
- JavaModelUtil.reconcile(cu);
- IFunction[] typeMethods= type.getFunctions();
- Set handleIds= new HashSet(typeMethods.length);
- for (int index= 0; index < typeMethods.length; index++)
- handleIds.add(typeMethods[index].getHandleIdentifier());
- ArrayList newMethods= new ArrayList();
- CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(type.getJavaScriptProject());
- settings.createComments= isAddComments();
- ASTParser parser= ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
- parser.setSource(cu);
- JavaScriptUnit unit= (JavaScriptUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
- final ITypeBinding binding= ASTNodes.getTypeBinding(unit, type);
- if (binding != null) {
- if (doUnimplementedMethods) {
- AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(unit, binding, null, -1, false, true, false);
- operation.setCreateComments(isAddComments());
- operation.run(monitor);
- createImports(imports, operation.getCreatedImports());
- }
- if (doConstructors) {
- AddUnimplementedConstructorsOperation operation= new AddUnimplementedConstructorsOperation(unit, binding, null, -1, false, true, false);
- operation.setOmitSuper(true);
- operation.setCreateComments(isAddComments());
- operation.run(monitor);
- createImports(imports, operation.getCreatedImports());
- }
- }
- JavaModelUtil.reconcile(cu);
- typeMethods= type.getFunctions();
- for (int index= 0; index < typeMethods.length; index++)
- if (!handleIds.contains(typeMethods[index].getHandleIdentifier()))
- newMethods.add(typeMethods[index]);
- IFunction[] methods= new IFunction[newMethods.size()];
- newMethods.toArray(methods);
- return methods;
- }
-
- private void createImports(ImportsManager imports, String[] createdImports) {
- for (int index= 0; index < createdImports.length; index++)
- imports.addImport(createdImports[index]);
- }
-
-
- // ---- creation ----------------
-
- /**
- * Returns the runnable that creates the type using the current settings.
- * The returned runnable must be executed in the UI thread.
- *
- * @return the runnable to create the new type
- */
- public IRunnableWithProgress getRunnable() {
- return new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- try {
- if (monitor == null) {
- monitor= new NullProgressMonitor();
- }
- createType(monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- }
-}

Back to the top